iisadia commited on
Commit
5315b13
·
verified ·
1 Parent(s): ccb31be

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +138 -63
app.py CHANGED
@@ -1,4 +1,3 @@
1
- import unittest
2
  import streamlit as st
3
  import requests
4
  from fpdf import FPDF
@@ -6,57 +5,142 @@ import os
6
  import time
7
  from datetime import datetime
8
 
9
- # Mock function to call Mistral API (replace with real call for actual usage)
10
- def call_mistral_api(prompt):
11
- return "Functional" # Mock response for testing
12
-
13
- # Test case class to check requirement analysis functionality
14
- class RequirementTestCase(unittest.TestCase):
15
-
16
- def test_requirement_type(self):
17
- requirement = "The system shall allow users to login."
18
- expected = "Functional"
19
- actual = call_mistral_api(f"Classify the following requirement as Functional or Non-Functional:\n\n{requirement}\n\nType:")
20
- self.assertEqual(actual, expected, f"Test failed for requirement type. Expected: {expected}, but got: {actual}")
21
-
22
- def test_stakeholders_identification(self):
23
- requirement = "The system shall allow users to login."
24
- expected = "User, System Administrator"
25
- actual = call_mistral_api(f"Identify the stakeholders for the following requirement:\n\n{requirement}\n\nStakeholders:")
26
- self.assertEqual(actual, expected, f"Test failed for stakeholders. Expected: {expected}, but got: {actual}")
27
-
28
- def test_defects_identification(self):
29
- requirement = "The system shall allow users to login."
30
- expected = "No defects"
31
- actual = call_mistral_api(f"Analyze the following requirement and identify ONLY MAJOR defects:\n\n{requirement}\n\nDefects:")
32
- self.assertEqual(actual, expected, f"Test failed for defects. Expected: {expected}, but got: {actual}")
33
-
34
- # Add more test cases as needed...
35
-
36
- # Custom runner to display detailed results
37
- class DetailedTextTestRunner(unittest.TextTestRunner):
38
- def getDescription(self, test):
39
- return f"{test.__class__.__name__} ({test._testMethodName})"
40
-
41
- def run(self, test):
42
- result = super().run(test)
43
- self.display_results(result)
44
- return result
45
-
46
- def display_results(self, result):
47
- if result.errors or result.failures:
48
- st.subheader("Test Results")
49
- for test, traceback in result.errors + result.failures:
50
- st.write(f"**Test Case:** {test}")
51
- st.write(f"**Error/Failure:** {traceback}")
52
- else:
53
- st.success("All tests passed successfully!")
54
 
55
- st.subheader("Test Summary")
56
- st.write(f"Total Tests Run: {result.testsRun}")
57
- st.write(f"Failures: {len(result.failures)}")
58
- st.write(f"Errors: {len(result.errors)}")
59
- st.write(f"Skipped: {len(result.skipped)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  # Streamlit app
62
  def main():
@@ -71,7 +155,7 @@ def main():
71
  # Split by periods or newlines
72
  requirements = [req.strip() for req in input_text.replace("\n", ".").split(".") if req.strip()]
73
 
74
- # Analyze requirements and display results
75
  if st.button("Analyze Requirements"):
76
  if not requirements:
77
  st.warning("Please enter requirements.")
@@ -85,11 +169,8 @@ def main():
85
  st.subheader("Analysis Results")
86
  for i, result in enumerate(results, start=1):
87
  st.write(f"### Requirement R{i}: {result['Requirement']}")
88
- st.write(f"**Type:** {result['Type']}")
89
- st.write(f"**Stakeholders:** {result['Stakeholders']}")
90
- st.write(f"**Domain:** {result['Domain']}")
91
- st.write(f"**Defects:** {result['Defects']}")
92
- st.write(f"**Rewritten:** {result['Rewritten']}")
93
  st.write("---")
94
 
95
  # Generate and download PDF report
@@ -102,12 +183,6 @@ def main():
102
  mime="application/pdf"
103
  )
104
 
105
- # Run the unit tests
106
- st.subheader("Running Unit Tests...")
107
- test_suite = unittest.defaultTestLoader.loadTestsFromTestCase(RequirementTestCase)
108
- test_runner = DetailedTextTestRunner(verbosity=2)
109
- test_runner.run(test_suite)
110
-
111
  # Run the app
112
  if __name__ == "__main__":
113
  main()
 
 
1
  import streamlit as st
2
  import requests
3
  from fpdf import FPDF
 
5
  import time
6
  from datetime import datetime
7
 
8
+ # Mistral API key (replace with your key or use environment variable)
9
+ api_key = os.getenv("MISTRAL_API_KEY", "gz6lDXokxgR6cLY72oomALWcm7vhjRzQ")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
+ # Function to call Mistral API with rate limit handling
12
+ def call_mistral_api(prompt):
13
+ url = "https://api.mistral.ai/v1/chat/completions"
14
+ headers = {
15
+ "Authorization": f"Bearer {api_key}",
16
+ "Content-Type": "application/json"
17
+ }
18
+ payload = {
19
+ "model": "mistral-medium",
20
+ "messages": [
21
+ {"role": "user", "content": prompt}
22
+ ]
23
+ }
24
+ try:
25
+ response = requests.post(url, headers=headers, json=payload)
26
+ response.raise_for_status() # Raise an error for bad status codes
27
+ return response.json()['choices'][0]['message']['content']
28
+ except requests.exceptions.HTTPError as err:
29
+ if response.status_code == 429: # Rate limit exceeded
30
+ st.warning("Rate limit exceeded. Please wait a few seconds and try again.")
31
+ time.sleep(5) # Wait for 5 seconds before retrying
32
+ return call_mistral_api(prompt) # Retry the request
33
+ return f"HTTP Error: {err}"
34
+ except Exception as err:
35
+ return f"Error: {err}"
36
+
37
+ # Function to analyze a single requirement
38
+ def analyze_requirement(requirement):
39
+ # Define test case expectations
40
+ expected_outcomes = {
41
+ "Type": "Functional or Non-Functional",
42
+ "Stakeholders": "List of stakeholders for the requirement",
43
+ "Domain": "Classify the domain (e.g., Bank, Healthcare)",
44
+ "Defects": "List of major defects or 'No defects' if none",
45
+ "Rewritten": "Concise, defect-free rewritten requirement"
46
+ }
47
+
48
+ # Detect requirement type
49
+ type_prompt = f"Classify the following requirement as Functional or Non-Functional:\n\n{requirement}\n\nType:"
50
+ req_type = call_mistral_api(type_prompt)
51
+
52
+ # Identify stakeholders
53
+ stakeholders_prompt = f"Identify the stakeholders for the following requirement:\n\n{requirement}\n\nStakeholders:"
54
+ stakeholders = call_mistral_api(stakeholders_prompt)
55
+
56
+ # Classify domain
57
+ domain_prompt = f"Classify the domain for the following requirement (e.g., Bank, Healthcare, etc.):\n\n{requirement}\n\nDomain:"
58
+ domain = call_mistral_api(domain_prompt)
59
+
60
+ # Detect defects
61
+ defects_prompt = f"""Analyze the following requirement and identify ONLY MAJOR defects (e.g., Ambiguity, Incompleteness, etc.).
62
+ If the requirement is clear and complete, respond with 'No defects.'
63
+ Requirement: {requirement}
64
+ Defects:"""
65
+ defects = call_mistral_api(defects_prompt)
66
+
67
+ # Rewrite requirement
68
+ rewritten = rewrite_requirement(requirement, defects)
69
+
70
+ # Return both the result and expected outcome comparison
71
+ return {
72
+ "Requirement": requirement,
73
+ "Type": {"Expected": expected_outcomes["Type"], "Actual": req_type},
74
+ "Stakeholders": {"Expected": expected_outcomes["Stakeholders"], "Actual": stakeholders},
75
+ "Domain": {"Expected": expected_outcomes["Domain"], "Actual": domain},
76
+ "Defects": {"Expected": expected_outcomes["Defects"], "Actual": defects},
77
+ "Rewritten": {"Expected": expected_outcomes["Rewritten"], "Actual": rewritten}
78
+ }
79
+
80
+ # Function to rewrite requirement concisely
81
+ def rewrite_requirement(requirement, defects):
82
+ if "no defects" in defects.lower():
83
+ return "No modification needed."
84
+
85
+ # If defects are found, generate a concise and clear rewritten requirement
86
+ 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.
87
+
88
+ Original Requirement: {requirement}
89
+
90
+ Defects: {defects}
91
+
92
+ Rewritten Requirement:"""
93
+ response = call_mistral_api(prompt)
94
+ return response.strip()
95
+
96
+ # Function to generate a PDF report with professional formatting
97
+ def generate_pdf_report(results):
98
+ pdf = FPDF()
99
+ pdf.add_page()
100
+ pdf.set_font("Arial", size=12)
101
+
102
+ # Add watermark
103
+ pdf.set_font("Arial", 'B', 50)
104
+ pdf.set_text_color(230, 230, 230) # Light gray color for watermark
105
+ pdf.rotate(45) # Rotate the text for watermark effect
106
+ pdf.text(60, 150, "AI Powered Requirement Analysis")
107
+ pdf.rotate(0) # Reset rotation
108
+
109
+ # Add title and date/time
110
+ pdf.set_font("Arial", 'B', 16)
111
+ pdf.set_text_color(0, 0, 0) # Black color for title
112
+ pdf.cell(200, 10, txt="AI Powered Requirement Analysis and Defect Detection using LLM Model Mistral", ln=True, align='C')
113
+ pdf.set_font("Arial", size=12)
114
+ pdf.cell(200, 10, txt=f"Report Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C')
115
+ pdf.ln(10) # Add some space
116
+
117
+ # Add requirements analysis
118
+ pdf.set_font("Arial", size=12)
119
+ for i, result in enumerate(results, start=1):
120
+ # Check if we need a new page
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 using LLM Model Mistral", 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
+
134
+ # Display expected vs actual results
135
+ for key in ["Type", "Stakeholders", "Domain", "Defects", "Rewritten"]:
136
+ pdf.multi_cell(200, 10, txt=f"{key}:\nExpected: {result[key]['Expected']}\nActual: {result[key]['Actual']}", align='L')
137
+
138
+ pdf.multi_cell(200, 10, txt="-" * 50, align='L')
139
+ pdf.ln(5) # Add some space between requirements
140
+
141
+ pdf_output = "requirements_report.pdf"
142
+ pdf.output(pdf_output)
143
+ return pdf_output
144
 
145
  # Streamlit app
146
  def main():
 
155
  # Split by periods or newlines
156
  requirements = [req.strip() for req in input_text.replace("\n", ".").split(".") if req.strip()]
157
 
158
+ # Analyze requirements
159
  if st.button("Analyze Requirements"):
160
  if not requirements:
161
  st.warning("Please enter requirements.")
 
169
  st.subheader("Analysis Results")
170
  for i, result in enumerate(results, start=1):
171
  st.write(f"### Requirement R{i}: {result['Requirement']}")
172
+ for key in ["Type", "Stakeholders", "Domain", "Defects", "Rewritten"]:
173
+ st.write(f"**{key}:** Expected: {result[key]['Expected']} | Actual: {result[key]['Actual']}")
 
 
 
174
  st.write("---")
175
 
176
  # Generate and download PDF report
 
183
  mime="application/pdf"
184
  )
185
 
 
 
 
 
 
 
186
  # Run the app
187
  if __name__ == "__main__":
188
  main()