iisadia commited on
Commit
6600546
·
verified ·
1 Parent(s): 7213b9a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +188 -0
app.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ from fpdf import FPDF
4
+ import os
5
+ import time
6
+ from datetime import datetime
7
+ import groq
8
+
9
+ # API keys (replace with your keys or use environment variables)
10
+ mistral_api_key = os.getenv("MISTRAL_API_KEY", "gz6lDXokxgR6cLY72oomALWcm7vhjRzQ")
11
+ groq_api_key = os.getenv("GROQ_API_KEY", "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")
12
+
13
+ # Initialize Groq client
14
+ groq_client = groq.Client(api_key=groq_api_key)
15
+
16
+ # Function to call Mistral API
17
+ def call_mistral_api(prompt):
18
+ url = "https://api.mistral.ai/v1/chat/completions"
19
+ headers = {
20
+ "Authorization": f"Bearer {mistral_api_key}",
21
+ "Content-Type": "application/json"
22
+ }
23
+ payload = {
24
+ "model": "mistral-medium",
25
+ "messages": [
26
+ {"role": "user", "content": prompt}
27
+ ]
28
+ }
29
+ try:
30
+ response = requests.post(url, headers=headers, json=payload)
31
+ response.raise_for_status() # Raise an error for bad status codes
32
+ return response.json()['choices'][0]['message']['content']
33
+ except requests.exceptions.HTTPError as err:
34
+ if response.status_code == 429: # Rate limit exceeded
35
+ st.warning("Rate limit exceeded. Please wait a few seconds and try again.")
36
+ time.sleep(5) # Wait for 5 seconds before retrying
37
+ return call_mistral_api(prompt) # Retry the request
38
+ return f"HTTP Error: {err}"
39
+ except Exception as err:
40
+ return f"Error: {err}"
41
+
42
+ # Function to call Groq API
43
+ def call_groq_api(prompt):
44
+ try:
45
+ response = groq_client.chat.completions.create(
46
+ model="llama-3.3-70b-versatile", # Correct model name
47
+ messages=[
48
+ {"role": "user", "content": prompt}
49
+ ]
50
+ )
51
+ return response.choices[0].message.content
52
+ except Exception as err:
53
+ st.error(f"Error: {err}")
54
+ return f"Error: {err}"
55
+
56
+ # Function to analyze a single requirement using both models
57
+ def analyze_requirement(requirement):
58
+ # Use Mistral for classification and domain identification
59
+ type_prompt = f"Classify the following requirement as Functional or Non-Functional:\n\n{requirement}\n\nType:"
60
+ req_type = call_mistral_api(type_prompt)
61
+
62
+ domain_prompt = f"Classify the domain for the following requirement (e.g., Bank, Healthcare, etc.):\n\n{requirement}\n\nDomain:"
63
+ domain = call_mistral_api(domain_prompt)
64
+
65
+ # Use Groq for defect analysis and rewriting
66
+ defects_prompt = f"""Analyze the following requirement and identify ONLY MAJOR defects (e.g., Ambiguity, Incompleteness, etc.).
67
+ If the requirement is clear and complete, respond with 'No defects.'
68
+ Requirement: {requirement}
69
+ Defects:"""
70
+ defects = call_groq_api(defects_prompt)
71
+
72
+ rewritten = rewrite_requirement(requirement, defects)
73
+
74
+ return {
75
+ "Requirement": requirement,
76
+ "Type": req_type,
77
+ "Domain": domain,
78
+ "Defects": defects,
79
+ "Rewritten": rewritten
80
+ }
81
+
82
+ # Function to rewrite requirement concisely using Groq
83
+ def rewrite_requirement(requirement, defects):
84
+ if "no defects" in defects.lower():
85
+ return "No modification needed."
86
+
87
+ 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.
88
+
89
+ Original Requirement: {requirement}
90
+
91
+ Defects: {defects}
92
+
93
+ Rewritten Requirement:"""
94
+ response = call_groq_api(prompt)
95
+ return response.strip()
96
+
97
+ # Function to generate a PDF report
98
+ def generate_pdf_report(results):
99
+ pdf = FPDF()
100
+ pdf.add_page()
101
+ pdf.set_font("Arial", size=12)
102
+
103
+ # Add watermark
104
+ pdf.set_font("Arial", 'B', 50)
105
+ pdf.set_text_color(230, 230, 230) # Light gray color for watermark
106
+ pdf.rotate(45) # Rotate the text for watermark effect
107
+ pdf.text(60, 150, "AI Powered Requirement Analysis")
108
+ pdf.rotate(0) # Reset rotation
109
+
110
+ # Add title and date/time
111
+ pdf.set_font("Arial", 'B', 16)
112
+ pdf.set_text_color(0, 0, 0) # Black color for title
113
+ pdf.cell(200, 10, txt="AI Powered Requirement Analysis and Defect Detection", ln=True, align='C')
114
+ pdf.set_font("Arial", size=12)
115
+ pdf.cell(200, 10, txt=f"Report Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C')
116
+ pdf.ln(10) # Add some space
117
+
118
+ # Add requirements analysis
119
+ pdf.set_font("Arial", size=12)
120
+ for i, result in enumerate(results, start=1):
121
+ if pdf.get_y() > 250: # If the content is near the bottom of the page
122
+ pdf.add_page() # Add a new page
123
+ pdf.set_font("Arial", 'B', 16)
124
+ pdf.cell(200, 10, txt="AI Powered Requirement Analysis and Defect Detection", ln=True, align='C')
125
+ pdf.set_font("Arial", size=12)
126
+ pdf.cell(200, 10, txt=f"Report Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C')
127
+ pdf.ln(10) # Add some space
128
+
129
+ # Add requirement details
130
+ pdf.set_font("Arial", 'B', 14)
131
+ pdf.multi_cell(200, 10, txt=f"Requirement R{i}: {result['Requirement']}", align='L')
132
+ pdf.set_font("Arial", size=12)
133
+ pdf.multi_cell(200, 10, txt=f"Type: {result['Type']}", align='L')
134
+ pdf.multi_cell(200, 10, txt=f"Domain: {result['Domain']}", align='L')
135
+ pdf.multi_cell(200, 10, txt=f"Defects: {result['Defects']}", align='L')
136
+ pdf.multi_cell(200, 10, txt=f"Rewritten: {result['Rewritten']}", align='L')
137
+ pdf.multi_cell(200, 10, txt="-" * 50, align='L')
138
+ pdf.ln(5) # Add some space between requirements
139
+
140
+ pdf_output = "requirements_report.pdf"
141
+ pdf.output(pdf_output)
142
+ return pdf_output
143
+
144
+ # Streamlit app
145
+ def main():
146
+ st.title("AI Powered Requirement Analysis and Defect Detection")
147
+ st.markdown("**Team Name:** Sadia, Areeba, Rabbia, Tesmia")
148
+ st.markdown("**Models:** Mistral (Classification & Domain) + Groq (Defects & Rewriting)")
149
+
150
+ # Input requirements manually
151
+ input_text = st.text_area("Enter your requirements (one per line or separated by periods):")
152
+ requirements = []
153
+ if input_text:
154
+ requirements = [req.strip() for req in input_text.replace("\n", ".").split(".") if req.strip()]
155
+
156
+ # Analyze requirements
157
+ if st.button("Analyze Requirements"):
158
+ if not requirements:
159
+ st.warning("Please enter requirements.")
160
+ else:
161
+ results = []
162
+ for req in requirements:
163
+ if req.strip(): # Ignore empty lines
164
+ results.append(analyze_requirement(req.strip()))
165
+
166
+ # Display results
167
+ st.subheader("Analysis Results")
168
+ for i, result in enumerate(results, start=1):
169
+ st.write(f"### Requirement R{i}: {result['Requirement']}")
170
+ st.write(f"**Type:** {result['Type']}")
171
+ st.write(f"**Domain:** {result['Domain']}")
172
+ st.write(f"**Defects:** {result['Defects']}")
173
+ st.write(f"**Rewritten:** {result['Rewritten']}")
174
+ st.write("---")
175
+
176
+ # Generate and download PDF report
177
+ pdf_report = generate_pdf_report(results)
178
+ with open(pdf_report, "rb") as f:
179
+ st.download_button(
180
+ label="Download PDF Report",
181
+ data=f,
182
+ file_name="requirements_report.pdf",
183
+ mime="application/pdf"
184
+ )
185
+
186
+ # Run the app
187
+ if __name__ == "__main__":
188
+ main()