iisadia's picture
Update app.py
8a0a253 verified
Raw History Blame Contribute Delete
7.09 kB
import streamlit as st
import requests
from fpdf import FPDF
import os
import time
from datetime import datetime
import groq
# Groq API key (replace with your key or use environment variable)
api_key = os.getenv("GROQ_API_KEY", "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")
# Initialize Groq client
groq_client = groq.Client(api_key=api_key)
# Function to call Groq API with rate limit handling
def call_groq_api(prompt):
try:
response = groq_client.chat.completions.create(
model="llama-3.3-70b-versatile", # Correct model name
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):
# Detect requirement type
type_prompt = f"Classify the following requirement as Functional or Non-Functional:\n\n{requirement}\n\nType:"
req_type = call_groq_api(type_prompt)
# Identify stakeholders
stakeholders_prompt = f"Identify the stakeholders for the following requirement:\n\n{requirement}\n\nStakeholders:"
stakeholders = call_groq_api(stakeholders_prompt)
# Classify domain
domain_prompt = f"Classify the domain for the following requirement (e.g., Bank, Healthcare, etc.):\n\n{requirement}\n\nDomain:"
domain = call_groq_api(domain_prompt)
# Detect defects
defects_prompt = f"""Analyze the following requirement and identify ONLY MAJOR defects (e.g., Ambiguity, Incompleteness, etc.).
If the requirement is clear and complete, respond with 'No defects.'
Requirement: {requirement}
Defects:"""
defects = call_groq_api(defects_prompt)
# Rewrite requirement
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,
"Stakeholders": stakeholders,
"Domain": domain,
"Defects": defects,
"Rewritten": rewritten
}
# Function to rewrite requirement concisely
def rewrite_requirement(requirement, defects):
if "no defects" in defects.lower():
return "No modification needed."
# If defects are found, generate a concise and clear rewritten requirement
prompt = f"""Rewrite the following requirement to address the defects listed below. Ensure the rewritten requirement is clear, concise, and free of defects. It should be no more than 1-2 sentences.
Original Requirement: {requirement}
Defects: {defects}
Rewritten Requirement:"""
response = call_groq_api(prompt)
return response.strip()
# Function to generate a PDF report with professional formatting
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 using LLaMA Model", 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):
# Check if we need a new page
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 using LLaMA Model", 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"Stakeholders: {result['Stakeholders']}", 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) # Add some space between requirements
pdf_output = "requirements_report.pdf"
pdf.output(pdf_output)
return pdf_output
# Streamlit app
def main():
st.title("AI Powered Requirement Analysis and Defect Detection using Large Language Model LLaMA")
st.markdown("**Team:** MSSE-31")
st.markdown("**Model:** LLaMA-3.3-70b-Versatile")
# Input requirements manually
input_text = st.text_area("Enter your requirements (one per line or separated by periods):")
requirements = []
if input_text:
# Split by periods or newlines
requirements = [req.strip() for req in input_text.replace("\n", ".").split(".") if req.strip()]
# Analyze requirements
if st.button("Analyze Requirements"):
if not requirements:
st.warning("Please enter requirements.")
else:
results = []
for req in requirements:
if req.strip(): # Ignore empty lines
results.append(analyze_requirement(req.strip()))
# Display results
st.subheader("Analysis Results")
for i, result in enumerate(results, start=1):
st.write(f"### Requirement R{i}: {result['Requirement']}")
st.write(f"**Type:** {result['Type']}")
st.write(f"**Stakeholders:** {result['Stakeholders']}")
st.write(f"**Domain:** {result['Domain']}")
st.write(f"**Defects:** {result['Defects']}")
st.write(f"**Rewritten:** {result['Rewritten']}")
st.write("---")
# Generate and download PDF report
pdf_report = generate_pdf_report(results)
with open(pdf_report, "rb") as f:
st.download_button(
label="Download PDF Report",
data=f,
file_name="requirements_report.pdf",
mime="application/pdf"
)
# Run the app
if __name__ == "__main__":
main()