iisadia commited on
Commit
312326d
·
verified ·
1 Parent(s): 2334625

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -17
app.py CHANGED
@@ -7,8 +7,8 @@ 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", "your_mistral_api_key")
11
- groq_api_key = os.getenv("GROQ_API_KEY", "your_groq_api_key")
12
 
13
  # Initialize Groq client
14
  groq_client = groq.Client(api_key=groq_api_key)
@@ -28,13 +28,13 @@ def call_mistral_api(prompt):
28
  }
29
  try:
30
  response = requests.post(url, headers=headers, json=payload)
31
- response.raise_for_status()
32
  return response.json()['choices'][0]['message']['content']
33
  except requests.exceptions.HTTPError as err:
34
- if response.status_code == 429:
35
  st.warning("Rate limit exceeded. Please wait a few seconds and try again.")
36
- time.sleep(5)
37
- return call_mistral_api(prompt)
38
  return f"HTTP Error: {err}"
39
  except Exception as err:
40
  return f"Error: {err}"
@@ -43,32 +43,110 @@ def call_mistral_api(prompt):
43
  def call_groq_api(prompt):
44
  try:
45
  response = groq_client.chat.completions.create(
46
- model="llama-3.3-70b-versatile",
47
- messages=[{"role": "user", "content": prompt}]
 
 
48
  )
49
  return response.choices[0].message.content
50
  except Exception as err:
51
  st.error(f"Error: {err}")
52
  return f"Error: {err}"
53
 
54
- # Streamlit UI
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  def main():
56
- st.title("AI Powered Requirement Analysis")
57
  st.markdown("**Team Name:** Sadia, Areeba, Rabbia, Tesmia")
58
  st.markdown("**Models:** Mistral (Classification & Domain) + Groq (Defects & Rewriting)")
59
-
60
- input_text = st.text_area("Enter requirements (one per line or separated by periods):")
61
- requirements = [req.strip() for req in input_text.replace("\n", ".").split(".") if req.strip()]
62
-
 
 
 
 
63
  if st.button("Analyze Requirements"):
64
  if not requirements:
65
  st.warning("Please enter requirements.")
66
  else:
67
  results = []
68
  for req in requirements:
69
- if req.strip():
70
  results.append(analyze_requirement(req.strip()))
71
-
 
72
  st.subheader("Analysis Results")
73
  for i, result in enumerate(results, start=1):
74
  st.write(f"### Requirement R{i}: {result['Requirement']}")
@@ -78,5 +156,16 @@ def main():
78
  st.write(f"**Rewritten:** {result['Rewritten']}")
79
  st.write("---")
80
 
 
 
 
 
 
 
 
 
 
 
 
81
  if __name__ == "__main__":
82
- main()
 
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)
 
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}"
 
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 in one word:\n\n{requirement}\n\nType:"
60
+ req_type = call_mistral_api(type_prompt).strip()
61
+
62
+ domain_prompt = f"Classify the domain for the following requirement in one word (e.g., E-commerce, Education, etc.):\n\n{requirement}\n\nDomain:"
63
+ domain = call_mistral_api(domain_prompt).strip()
64
+
65
+ # Use Groq for defect analysis and rewriting
66
+ 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:"""
67
+ defects = call_groq_api(defects_prompt).strip()
68
+
69
+ rewritten_prompt = f"""Rewrite the following requirement in 1-2 sentences to address the defects:\n\n{requirement}\n\nRewritten:"""
70
+ rewritten = call_groq_api(rewritten_prompt).strip()
71
+
72
+ return {
73
+ "Requirement": requirement,
74
+ "Type": req_type,
75
+ "Domain": domain,
76
+ "Defects": defects,
77
+ "Rewritten": rewritten
78
+ }
79
+
80
+ # Function to generate a PDF report
81
+ def generate_pdf_report(results):
82
+ pdf = FPDF()
83
+ pdf.add_page()
84
+ pdf.set_font("Arial", size=12)
85
+
86
+ # Add watermark
87
+ pdf.set_font("Arial", 'B', 50)
88
+ pdf.set_text_color(230, 230, 230) # Light gray color for watermark
89
+ pdf.rotate(45) # Rotate the text for watermark effect
90
+ pdf.text(60, 150, "AI Powered Requirement Analysis")
91
+ pdf.rotate(0) # Reset rotation
92
+
93
+ # Add title and date/time
94
+ pdf.set_font("Arial", 'B', 16)
95
+ pdf.set_text_color(0, 0, 0) # Black color for title
96
+ pdf.cell(200, 10, txt="AI Powered Requirement Analysis and Defect Detection", ln=True, align='C')
97
+ pdf.set_font("Arial", size=12)
98
+ pdf.cell(200, 10, txt=f"Report Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C')
99
+ pdf.ln(10) # Add some space
100
+
101
+ # Add requirements analysis
102
+ pdf.set_font("Arial", size=12)
103
+ for i, result in enumerate(results, start=1):
104
+ if pdf.get_y() > 250: # If the content is near the bottom of the page
105
+ pdf.add_page() # Add a new page
106
+ pdf.set_font("Arial", 'B', 16)
107
+ pdf.cell(200, 10, txt="AI Powered Requirement Analysis and Defect Detection", ln=True, align='C')
108
+ pdf.set_font("Arial", size=12)
109
+ pdf.cell(200, 10, txt=f"Report Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C')
110
+ pdf.ln(10) # Add some space
111
+
112
+ # Add requirement details
113
+ pdf.set_font("Arial", 'B', 14)
114
+ pdf.multi_cell(200, 10, txt=f"Requirement R{i}: {result['Requirement']}", align='L')
115
+ pdf.set_font("Arial", size=12)
116
+ pdf.multi_cell(200, 10, txt=f"Type: {result['Type']}", align='L')
117
+ pdf.multi_cell(200, 10, txt=f"Domain: {result['Domain']}", align='L')
118
+ pdf.multi_cell(200, 10, txt=f"Defects: {result['Defects']}", align='L')
119
+ pdf.multi_cell(200, 10, txt=f"Rewritten: {result['Rewritten']}", align='L')
120
+ pdf.multi_cell(200, 10, txt="-" * 50, align='L')
121
+ pdf.ln(5) # Add some space between requirements
122
+
123
+ pdf_output = "requirements_report.pdf"
124
+ pdf.output(pdf_output)
125
+ return pdf_output
126
+
127
+ # Streamlit app
128
  def main():
129
+ st.title("AI Powered Requirement Analysis and Defect Detection")
130
  st.markdown("**Team Name:** Sadia, Areeba, Rabbia, Tesmia")
131
  st.markdown("**Models:** Mistral (Classification & Domain) + Groq (Defects & Rewriting)")
132
+
133
+ # Input requirements manually
134
+ input_text = st.text_area("Enter your requirements (one per line or separated by periods):")
135
+ requirements = []
136
+ if input_text:
137
+ requirements = [req.strip() for req in input_text.replace("\n", ".").split(".") if req.strip()]
138
+
139
+ # Analyze requirements
140
  if st.button("Analyze Requirements"):
141
  if not requirements:
142
  st.warning("Please enter requirements.")
143
  else:
144
  results = []
145
  for req in requirements:
146
+ if req.strip(): # Ignore empty lines
147
  results.append(analyze_requirement(req.strip()))
148
+
149
+ # Display results
150
  st.subheader("Analysis Results")
151
  for i, result in enumerate(results, start=1):
152
  st.write(f"### Requirement R{i}: {result['Requirement']}")
 
156
  st.write(f"**Rewritten:** {result['Rewritten']}")
157
  st.write("---")
158
 
159
+ # Generate and download PDF report
160
+ pdf_report = generate_pdf_report(results)
161
+ with open(pdf_report, "rb") as f:
162
+ st.download_button(
163
+ label="Download PDF Report",
164
+ data=f,
165
+ file_name="requirements_report.pdf",
166
+ mime="application/pdf"
167
+ )
168
+
169
+ # Run the app
170
  if __name__ == "__main__":
171
+ main()