iisadia's picture
Update app.py
62dccbc verified
raw
history blame
12.6 kB
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):
try:
# 1. Classify requirement type
type_prompt = f"Classify exactly as either 'Functional' or 'Non-Functional':\n{requirement}"
req_type = call_mistral_api(type_prompt).strip()
# 2. Identify domain
domain_prompt = f"Identify the business domain in one word (e.g., Healthcare, Finance):\n{requirement}"
domain = call_mistral_api(domain_prompt).strip()
# 3. Detect defects - more explicit prompt
defects_prompt = f"""Analyze this software requirement and list EXACTLY 3 defects using ONLY these formats:
- Ambiguity: [specific unclear part]
- Incompleteness: [missing element]
- Unverifiability: [unmeasurable aspect]
Requirement: {requirement}
Defects:"""
defects_response = call_groq_api(defects_prompt).strip()
# Process defects - more robust parsing
defects = []
if "API Error" not in defects_response:
# Extract all lines starting with "-"
defect_lines = [line.strip() for line in defects_response.split("\n") if line.strip().startswith("-")]
if defect_lines:
defects = [line[2:].split(":")[0].strip() for line in defect_lines[:3]] # Take first 3 defects
else:
defects = ["No defects found"]
else:
defects = ["Analysis error"]
# 4. Rewrite requirement - more constrained prompt
rewrite_prompt = f"""Improve this requirement by fixing defects while keeping it concise (1 sentence):
Original: {requirement}
Improved:"""
rewritten = call_groq_api(rewrite_prompt).strip()
# Clean rewritten output
if "Improved:" in rewritten:
rewritten = rewritten.split("Improved:")[-1].strip()
return {
"Requirement": requirement,
"Type": req_type,
"Domain": domain,
"Defects": defects if defects else ["No defects found"],
"Rewritten": rewritten if rewritten and "API Error" not in rewritten else requirement
}
except Exception as e:
return {
"Requirement": requirement,
"Type": "Error",
"Domain": "Error",
"Defects": ["Analysis failed"],
"Rewritten": requirement
}
# 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)
pdf.rotate(45)
pdf.text(60, 150, "AI Powered Requirement Analysis")
pdf.rotate(0)
# Add title and date/time
pdf.set_font("Arial", 'B', 16)
pdf.set_text_color(0, 0, 0)
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 requirements analysis
pdf.set_font("Arial", size=12)
for i, result in enumerate(results, start=1):
if pdf.get_y() > 250:
pdf.add_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)
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"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)
pdf_output = "requirements_report.pdf"
pdf.output(pdf_output)
return pdf_output
# Custom CSS for professional styling
st.markdown("""
<style>
.main {
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}
.stApp {
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
}
.header {
text-align: center;
padding: 2rem;
background: white;
border-radius: 15px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
margin-bottom: 2rem;
border: 1px solid #e0e0e0;
}
.requirement-card {
background: white;
padding: 1.5rem;
border-radius: 10px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
margin-bottom: 1.5rem;
transition: transform 0.2s;
color: #333333;
}
.requirement-card:hover {
transform: translateY(-3px);
}
.analysis-badge {
padding: 0.5rem 1rem;
border-radius: 20px;
font-weight: 500;
margin: 0.3rem;
}
.download-btn {
width: 100%;
padding: 1rem;
font-size: 1.1rem;
margin-top: 2rem;
}
.type-functional { background: #e8f5e9; color: #2e7d32; }
.type-non-functional { background: #fff3e0; color: #ef6c00; }
.defect-badge { background: #ffebee; color: #c62828; }
.improved-badge { background: #e3f2fd; color: #1565c0; }
</style>
""", unsafe_allow_html=True)
def main():
# Professional Header Section
with st.container():
st.markdown('<div class="header">', unsafe_allow_html=True)
st.title("πŸ“ AI-Powered Requirement Analysis System")
st.markdown("""
<div style="margin: 1.5rem 0;">
<div style="font-size: 1.2rem; color: #4a4a4a;">Automated Requirement Classification, Defect Detection & Optimization</div>
<div style="display: flex; justify-content: center; gap: 1rem; margin: 1rem 0;">
<div style="padding: 0.5rem 1rem; background: #f0f2f6;color: black; border-radius: 20px;">Team: Sadia, Areeba, Rabbia, Tesmia</div>
<div style="padding: 0.5rem 1rem; background: #f0f2f6; color: black; border-radius: 20px;">Mistral + Groq API</div>
</div>
</div>
""", unsafe_allow_html=True)
st.markdown('</div>', 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
# In your results display section:
for i, result in enumerate(st.session_state.results, 1):
with st.expander(f"Requirement #{i}: {result['Requirement'][:50]}...", expanded=True):
st.markdown(f"""
<div class="requirement-card">
<!-- Type and Domain sections remain the same -->
<div style="margin: 1rem 0;">
<h4>πŸ”Ž Identified Issues</h4>
<div style="display: flex; gap: 0.5rem; flex-wrap: wrap;">
{''.join([f'<div class="analysis-badge defect-badge">⚠️ {d}</div>'
for d in result["Defects"] if d and d != "No defects found"]) or
'<div class="analysis-badge" style="background:#e8f5e9;color:#2e7d32;">βœ“ No major defects found</div>'}
</div>
</div>
<div style="margin: 1rem 0;">
<h4>✨ Improved Version</h4>
<div class="analysis-badge improved-badge">
πŸ“ {result["Rewritten"] if result["Rewritten"] != result["Requirement"] else "No improvements suggested"}
</div>
</div>
</div>
""", 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("""
<div style="text-align: center; color: #666; margin-top: 3rem;">
<p>AI-Powered Requirement Analysis System β€’ Final Year Project β€’ Computer Science Department</p>
<p>πŸš€ Powered by Mistral AI & Groq β€’ πŸ› οΈ Developed by Team Four</p>
</div>
""", unsafe_allow_html=True)
if __name__ == "__main__":
main()