import streamlit as st import requests from fpdf import FPDF import os import time from datetime import datetime import groq # API keys (replace with your keys or use environment variables) mistral_api_key = os.getenv("MISTRAL_API_KEY", "gz6lDXokxgR6cLY72oomALWcm7vhjRzQ") groq_api_key = os.getenv("GROQ_API_KEY", "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") # Initialize Groq client groq_client = groq.Client(api_key=groq_api_key) # Function to call Mistral API def call_mistral_api(prompt): url = "https://api.mistral.ai/v1/chat/completions" headers = { "Authorization": f"Bearer {mistral_api_key}", "Content-Type": "application/json" } payload = { "model": "mistral-medium", "messages": [ {"role": "user", "content": prompt} ] } try: response = requests.post(url, headers=headers, json=payload) response.raise_for_status() return response.json()['choices'][0]['message']['content'] except requests.exceptions.HTTPError as err: if response.status_code == 429: st.warning("Rate limit exceeded. Please wait a few seconds and try again.") time.sleep(5) return call_mistral_api(prompt) return f"HTTP Error: {err}" except Exception as err: return f"Error: {err}" # Function to call Groq API def call_groq_api(prompt): try: response = groq_client.chat.completions.create( model="llama3-70b-8192", messages=[ {"role": "user", "content": prompt} ] ) return response.choices[0].message.content except Exception as err: st.error(f"Error: {err}") return f"Error: {err}" # Function to analyze a single requirement def analyze_requirement(requirement): # Use Mistral for classification and domain identification type_prompt = f"Classify the following requirement as Functional or Non-Functional in one word:\n\n{requirement}\n\nType:" req_type = call_mistral_api(type_prompt).strip() domain_prompt = f"Classify the domain for the following requirement in one word (e.g., E-commerce, Education, etc.):\n\n{requirement}\n\nDomain:" domain = call_mistral_api(domain_prompt).strip() stakeholder_prompt = f"""Identify key major stakeholders for this requirement. Provide a comma-separated list of roles. Examples: Users, Administrators, Developers, Security Team. Requirement:\n\n{requirement}\n\nStakeholders:""" stakeholders = call_groq_api(stakeholder_prompt).strip() # Use Groq for defect analysis and rewriting defects_prompt = f"""List ONLY the major defects in the following requirement (e.g., Ambiguity, Incompleteness, etc.) in 1-2 words each:\n\n{requirement}\n\nDefects:""" defects = call_groq_api(defects_prompt).strip() rewritten_prompt = f"""Rewrite the following requirement in 1-2 sentences to address the defects:\n\n{requirement}\n\nRewritten:""" rewritten = call_groq_api(rewritten_prompt).strip() return { "Requirement": requirement, "Type": req_type, "Domain": domain, "Stakeholders": stakeholders, "Defects": defects, "Rewritten": rewritten } # Function to generate a PDF report def generate_pdf_report(results): pdf = FPDF() pdf.add_page() pdf.set_font("Arial", size=12) # Add watermark pdf.set_font("Arial", 'B', 50) pdf.set_text_color(230, 230, 230) # Light gray color for watermark pdf.rotate(45) # Rotate the text for watermark effect pdf.text(60, 150, "AI Powered Requirement Analysis") pdf.rotate(0) # Reset rotation # Add title and date/time pdf.set_font("Arial", 'B', 16) pdf.set_text_color(0, 0, 0) # Black color for title pdf.cell(200, 10, txt="AI Powered Requirement Analysis and Defect Detection", ln=True, align='C') pdf.set_font("Arial", size=12) pdf.cell(200, 10, txt=f"Report Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C') pdf.ln(10) # Add some space # Add requirements analysis pdf.set_font("Arial", size=12) for i, result in enumerate(results, start=1): if pdf.get_y() > 250: # If the content is near the bottom of the page pdf.add_page() # Add a new page pdf.set_font("Arial", 'B', 16) pdf.cell(200, 10, txt="AI Powered Requirement Analysis and Defect Detection", ln=True, align='C') pdf.set_font("Arial", size=12) pdf.cell(200, 10, txt=f"Report Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C') pdf.ln(10) # Add some space # Add requirement details pdf.set_font("Arial", 'B', 14) pdf.multi_cell(200, 10, txt=f"Requirement R{i}: {result['Requirement']}", align='L') pdf.set_font("Arial", size=12) pdf.multi_cell(200, 10, txt=f"Type: {result['Type']}", align='L') pdf.multi_cell(200, 10, txt=f"Domain: {result['Domain']}", align='L') pdf.multi_cell(200, 10, txt=f"Stakeholders: {result['Stakeholders']}", align='L') pdf.multi_cell(200, 10, txt=f"Defects: {result['Defects']}", align='L') pdf.multi_cell(200, 10, txt=f"Rewritten: {result['Rewritten']}", align='L') pdf.multi_cell(200, 10, txt="-" * 50, align='L') pdf.ln(5) # Add some space between requirements pdf_output = "requirements_report.pdf" pdf.output(pdf_output) return pdf_output # Custom CSS for professional styling st.markdown(""" """, unsafe_allow_html=True) def main(): # Professional Header Section with st.container(): st.markdown('
', unsafe_allow_html=True) st.title("📝 AI-Based Requirement Defect Detection Using Large Language Models (LLMs)") st.markdown("""
Automated Requirement Classification, Defect Detection & Optimization
Team: Sadia, Areeba, Rabbia, Tesmia
Mistral + Groq API
""", unsafe_allow_html=True) st.markdown('
', unsafe_allow_html=True) # Input Section with st.container(): st.subheader("📥 Input Requirements") input_text = st.text_area( "Enter your software requirements (one per line or separated by periods):", height=200, placeholder="Example:\nThe system shall allow users to reset their password via email verification.\nThe interface must load within 2 seconds of user interaction...", help="Enter each requirement on a new line or separate with periods." ) # Analysis Section if st.button("🚀 Start Analysis", type="primary", use_container_width=True): if not input_text.strip(): st.warning("⚠️ Please enter requirements to analyze") else: with st.spinner("🔍 Analyzing requirements..."): requirements = [req.strip() for req in input_text.replace("\n", ".").split(".") if req.strip()] results = [] progress_bar = st.progress(0) for i, req in enumerate(requirements): results.append(analyze_requirement(req)) progress_bar.progress((i+1)/len(requirements)) st.success("✅ Analysis Completed!") time.sleep(0.5) st.session_state.results = results # Display Results if 'results' in st.session_state: st.subheader("📊 Analysis Results") with st.container(): for i, result in enumerate(st.session_state.results, 1): with st.expander(f"Requirement #{i}: {result['Requirement'][:50]}...", expanded=True): st.markdown(f"""
📌 Type: {result['Type']}
🏷️ Domain: {result['Domain']}
👥 Stakeholders: {result['Stakeholders']}
🔎 Identified Defects:
Explanation: {result['Defects']}
Improved Version:
Explanation: {result['Rewritten']}
""", unsafe_allow_html=True) # PDF Report Section st.subheader("📤 Generate Report") with st.container(): col1, col2 = st.columns([3, 2]) with col1: st.info("💡 Click below to generate a comprehensive PDF report with all analysis details") with col2: if st.button("📄 Generate PDF Report", type="secondary", use_container_width=True): with st.spinner("Generating PDF..."): pdf_report = generate_pdf_report(st.session_state.results) with open(pdf_report, "rb") as f: st.download_button( label="⬇️ Download Full Report", data=f, file_name="Requirement_Analysis_Report.pdf", mime="application/pdf", use_container_width=True, type="primary" ) # Footer st.markdown("---") st.markdown("""

AI-Powered Requirement Analysis System

🚀 Powered by Mistral AI & Groq • 🛠️ Developed by Team Four

""", unsafe_allow_html=True) if __name__ == "__main__": main()