iisadia commited on
Commit
f004bde
·
verified ·
1 Parent(s): e0d70a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -46
app.py CHANGED
@@ -5,6 +5,8 @@ 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")
@@ -33,16 +35,15 @@ def call_mistral_api(prompt):
33
  end_time = time.time()
34
  speed = end_time - start_time
35
  content = response.json()['choices'][0]['message']['content']
36
- confidence = len(content.split()) # Simulate confidence with response length
37
- return content, speed, confidence
38
  except requests.exceptions.HTTPError as err:
39
  if response.status_code == 429: # Rate limit exceeded
40
  st.warning("Rate limit exceeded. Please wait a few seconds and try again.")
41
  time.sleep(5) # Wait for 5 seconds before retrying
42
  return call_mistral_api(prompt) # Retry the request
43
- return f"HTTP Error: {err}", 0, 0
44
  except Exception as err:
45
- return f"Error: {err}", 0, 0
46
 
47
  # Function to call Groq API
48
  def call_groq_api(prompt):
@@ -57,48 +58,49 @@ def call_groq_api(prompt):
57
  end_time = time.time()
58
  speed = end_time - start_time
59
  content = response.choices[0].message.content
60
- confidence = len(content.split()) # Simulate confidence with response length
61
- return content, speed, confidence
62
  except Exception as err:
63
  st.error(f"Error: {err}")
64
- return f"Error: {err}", 0, 0
65
 
66
  # Function to analyze a single requirement using both models
67
  def analyze_requirement(requirement):
68
  # Use Mistral for classification and domain identification
69
  type_prompt = f"Classify the following requirement as Functional or Non-Functional in one word:\n\n{requirement}\n\nType:"
70
- req_type, type_speed, type_confidence = call_mistral_api(type_prompt)
71
  req_type = req_type.strip()
72
 
73
  domain_prompt = f"Classify the domain for the following requirement in one word (e.g., E-commerce, Education, etc.):\n\n{requirement}\n\nDomain:"
74
- domain, domain_speed, domain_confidence = call_mistral_api(domain_prompt)
75
  domain = domain.strip()
76
 
77
  # Use Groq for defect analysis and rewriting
78
  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:"""
79
- defects, defects_speed, defects_confidence = call_groq_api(defects_prompt)
80
  defects = defects.strip()
81
 
82
  rewritten_prompt = f"""Rewrite the following requirement in 1-2 sentences to address the defects:\n\n{requirement}\n\nRewritten:"""
83
- rewritten, rewritten_speed, rewritten_confidence = call_groq_api(rewritten_prompt)
84
  rewritten = rewritten.strip()
85
 
 
 
 
86
  return {
87
  "Requirement": requirement,
88
  "Type": req_type,
89
  "Domain": domain,
90
  "Defects": defects,
91
  "Rewritten": rewritten,
92
- "Type_Speed": type_speed,
93
- "Type_Confidence": type_confidence,
94
- "Domain_Speed": domain_speed,
95
- "Domain_Confidence": domain_confidence,
96
- "Defects_Speed": defects_speed,
97
- "Defects_Confidence": defects_confidence,
98
- "Rewritten_Speed": rewritten_speed,
99
- "Rewritten_Confidence": rewritten_confidence
100
  }
101
 
 
 
 
 
 
 
102
  # Function to generate a PDF report
103
  def generate_pdf_report(results):
104
  pdf = FPDF()
@@ -139,14 +141,7 @@ def generate_pdf_report(results):
139
  pdf.multi_cell(200, 10, txt=f"Domain: {result['Domain']}", align='L')
140
  pdf.multi_cell(200, 10, txt=f"Defects: {result['Defects']}", align='L')
141
  pdf.multi_cell(200, 10, txt=f"Rewritten: {result['Rewritten']}", align='L')
142
- pdf.multi_cell(200, 10, txt=f"Type Speed: {result['Type_Speed']:.2f}s", align='L')
143
- pdf.multi_cell(200, 10, txt=f"Type Confidence: {result['Type_Confidence']}", align='L')
144
- pdf.multi_cell(200, 10, txt=f"Domain Speed: {result['Domain_Speed']:.2f}s", align='L')
145
- pdf.multi_cell(200, 10, txt=f"Domain Confidence: {result['Domain_Confidence']}", align='L')
146
- pdf.multi_cell(200, 10, txt=f"Defects Speed: {result['Defects_Speed']:.2f}s", align='L')
147
- pdf.multi_cell(200, 10, txt=f"Defects Confidence: {result['Defects_Confidence']}", align='L')
148
- pdf.multi_cell(200, 10, txt=f"Rewritten Speed: {result['Rewritten_Speed']:.2f}s", align='L')
149
- pdf.multi_cell(200, 10, txt=f"Rewritten Confidence: {result['Rewritten_Confidence']}", align='L')
150
  pdf.multi_cell(200, 10, txt="-" * 50, align='L')
151
  pdf.ln(5) # Add some space between requirements
152
 
@@ -172,27 +167,41 @@ def main():
172
  st.warning("Please enter requirements.")
173
  else:
174
  results = []
 
175
  for req in requirements:
176
  if req.strip(): # Ignore empty lines
177
- results.append(analyze_requirement(req.strip()))
178
-
179
- # Display results
180
- st.subheader("Analysis Results")
181
- for i, result in enumerate(results, start=1):
182
- st.write(f"### Requirement R{i}: {result['Requirement']}")
183
- st.write(f"**Type:** {result['Type']}")
184
- st.write(f"**Domain:** {result['Domain']}")
185
- st.write(f"**Defects:** {result['Defects']}")
186
- st.write(f"**Rewritten:** {result['Rewritten']}")
187
- st.write(f"**Type Speed:** {result['Type_Speed']:.2f}s")
188
- st.write(f"**Type Confidence:** {result['Type_Confidence']}")
189
- st.write(f"**Domain Speed:** {result['Domain_Speed']:.2f}s")
190
- st.write(f"**Domain Confidence:** {result['Domain_Confidence']}")
191
- st.write(f"**Defects Speed:** {result['Defects_Speed']:.2f}s")
192
- st.write(f"**Defects Confidence:** {result['Defects_Confidence']}")
193
- st.write(f"**Rewritten Speed:** {result['Rewritten_Speed']:.2f}s")
194
- st.write(f"**Rewritten Confidence:** {result['Rewritten_Confidence']}")
195
- st.write("---")
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
  # Generate and download PDF report
198
  pdf_report = generate_pdf_report(results)
 
5
  import time
6
  from datetime import datetime
7
  import groq
8
+ import pandas as pd
9
+ import matplotlib.pyplot as plt
10
 
11
  # API keys (replace with your keys or use environment variables)
12
  mistral_api_key = os.getenv("MISTRAL_API_KEY", "gz6lDXokxgR6cLY72oomALWcm7vhjRzQ")
 
35
  end_time = time.time()
36
  speed = end_time - start_time
37
  content = response.json()['choices'][0]['message']['content']
38
+ return content, speed
 
39
  except requests.exceptions.HTTPError as err:
40
  if response.status_code == 429: # Rate limit exceeded
41
  st.warning("Rate limit exceeded. Please wait a few seconds and try again.")
42
  time.sleep(5) # Wait for 5 seconds before retrying
43
  return call_mistral_api(prompt) # Retry the request
44
+ return f"HTTP Error: {err}", 0
45
  except Exception as err:
46
+ return f"Error: {err}", 0
47
 
48
  # Function to call Groq API
49
  def call_groq_api(prompt):
 
58
  end_time = time.time()
59
  speed = end_time - start_time
60
  content = response.choices[0].message.content
61
+ return content, speed
 
62
  except Exception as err:
63
  st.error(f"Error: {err}")
64
+ return f"Error: {err}", 0
65
 
66
  # Function to analyze a single requirement using both models
67
  def analyze_requirement(requirement):
68
  # Use Mistral for classification and domain identification
69
  type_prompt = f"Classify the following requirement as Functional or Non-Functional in one word:\n\n{requirement}\n\nType:"
70
+ req_type, type_speed = call_mistral_api(type_prompt)
71
  req_type = req_type.strip()
72
 
73
  domain_prompt = f"Classify the domain for the following requirement in one word (e.g., E-commerce, Education, etc.):\n\n{requirement}\n\nDomain:"
74
+ domain, domain_speed = call_mistral_api(domain_prompt)
75
  domain = domain.strip()
76
 
77
  # Use Groq for defect analysis and rewriting
78
  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:"""
79
+ defects, defects_speed = call_groq_api(defects_prompt)
80
  defects = defects.strip()
81
 
82
  rewritten_prompt = f"""Rewrite the following requirement in 1-2 sentences to address the defects:\n\n{requirement}\n\nRewritten:"""
83
+ rewritten, rewritten_speed = call_groq_api(rewritten_prompt)
84
  rewritten = rewritten.strip()
85
 
86
+ # Calculate total speed for this requirement
87
+ total_speed = type_speed + domain_speed + defects_speed + rewritten_speed
88
+
89
  return {
90
  "Requirement": requirement,
91
  "Type": req_type,
92
  "Domain": domain,
93
  "Defects": defects,
94
  "Rewritten": rewritten,
95
+ "Total_Speed": total_speed
 
 
 
 
 
 
 
96
  }
97
 
98
+ # Function to calculate accuracy (placeholder logic)
99
+ def calculate_accuracy(results):
100
+ # Placeholder logic: Assume 80% accuracy for demonstration
101
+ # Replace this with actual logic if you have correct answers
102
+ return 80.0 # Return accuracy as a percentage
103
+
104
  # Function to generate a PDF report
105
  def generate_pdf_report(results):
106
  pdf = FPDF()
 
141
  pdf.multi_cell(200, 10, txt=f"Domain: {result['Domain']}", align='L')
142
  pdf.multi_cell(200, 10, txt=f"Defects: {result['Defects']}", align='L')
143
  pdf.multi_cell(200, 10, txt=f"Rewritten: {result['Rewritten']}", align='L')
144
+ pdf.multi_cell(200, 10, txt=f"Total Speed: {result['Total_Speed']:.2f}s", align='L')
 
 
 
 
 
 
 
145
  pdf.multi_cell(200, 10, txt="-" * 50, align='L')
146
  pdf.ln(5) # Add some space between requirements
147
 
 
167
  st.warning("Please enter requirements.")
168
  else:
169
  results = []
170
+ total_speed = 0
171
  for req in requirements:
172
  if req.strip(): # Ignore empty lines
173
+ result = analyze_requirement(req.strip())
174
+ results.append(result)
175
+ total_speed += result["Total_Speed"]
176
+
177
+ # Calculate accuracy (placeholder logic)
178
+ accuracy = calculate_accuracy(results)
179
+
180
+ # Display total speed and accuracy
181
+ st.subheader("Performance Metrics")
182
+ col1, col2 = st.columns(2)
183
+ with col1:
184
+ st.metric("Total Speed", f"{total_speed:.2f} seconds")
185
+ with col2:
186
+ st.metric("Accuracy", f"{accuracy:.2f}%")
187
+
188
+ # Visualize metrics
189
+ st.subheader("Visualization")
190
+ metrics_data = {
191
+ "Metric": ["Total Speed", "Accuracy"],
192
+ "Value": [total_speed, accuracy]
193
+ }
194
+ df = pd.DataFrame(metrics_data)
195
+
196
+ # Bar chart
197
+ fig, ax = plt.subplots()
198
+ ax.bar(df["Metric"], df["Value"], color=["blue", "green"])
199
+ ax.set_ylabel("Value")
200
+ ax.set_title("Performance Metrics")
201
+ st.pyplot(fig)
202
+
203
+ # Table
204
+ st.table(df)
205
 
206
  # Generate and download PDF report
207
  pdf_report = generate_pdf_report(results)