iisadia commited on
Commit
7b14dbf
·
verified ·
1 Parent(s): 0b6764a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -39
app.py CHANGED
@@ -4,49 +4,50 @@ from fpdf import FPDF
4
  import os
5
  import time
6
  from datetime import datetime
 
7
 
8
- # Groq API key (replace with your actual key)
9
- groq_api_key = "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"
10
 
11
- # Function to call Groq Llama API
 
 
 
12
  def call_groq_api(prompt):
13
- url = "https://api.groq.com/openai/v1/chat/completions"
14
-
15
- headers = {
16
- "Authorization": f"Bearer {groq_api_key}",
17
- "Content-Type": "application/json"
18
- }
19
- payload = {
20
- "model": "llama-2-13b-chat",
21
- "messages": [{"role": "user", "content": prompt}]
22
- }
23
  try:
24
- response = requests.post(url, headers=headers, json=payload)
25
- response.raise_for_status()
26
- return response.json()['choices'][0]['message']['content']
27
- except requests.exceptions.HTTPError as err:
28
- return f"HTTP Error: {err}"
 
 
29
  except Exception as err:
30
  return f"Error: {err}"
31
 
32
- # Function to analyze requirements
33
- def analyze_requirement_groq(requirement):
 
34
  type_prompt = f"Classify the following requirement as Functional or Non-Functional:\n\n{requirement}\n\nType:"
35
  req_type = call_groq_api(type_prompt)
36
 
 
37
  stakeholders_prompt = f"Identify the stakeholders for the following requirement:\n\n{requirement}\n\nStakeholders:"
38
  stakeholders = call_groq_api(stakeholders_prompt)
39
 
 
40
  domain_prompt = f"Classify the domain for the following requirement (e.g., Bank, Healthcare, etc.):\n\n{requirement}\n\nDomain:"
41
  domain = call_groq_api(domain_prompt)
42
 
 
43
  defects_prompt = f"""Analyze the following requirement and identify ONLY MAJOR defects (e.g., Ambiguity, Incompleteness, etc.).
44
  If the requirement is clear and complete, respond with 'No defects.'
45
  Requirement: {requirement}
46
  Defects:"""
47
  defects = call_groq_api(defects_prompt)
48
 
49
- rewritten = rewrite_requirement_groq(requirement, defects)
 
50
 
51
  return {
52
  "Requirement": requirement,
@@ -58,10 +59,11 @@ def analyze_requirement_groq(requirement):
58
  }
59
 
60
  # Function to rewrite requirement concisely
61
- def rewrite_requirement_groq(requirement, defects):
62
  if "no defects" in defects.lower():
63
  return "No modification needed."
64
 
 
65
  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.
66
 
67
  Original Requirement: {requirement}
@@ -72,27 +74,40 @@ def rewrite_requirement_groq(requirement, defects):
72
  response = call_groq_api(prompt)
73
  return response.strip()
74
 
75
- # Function to generate a PDF report
76
- def generate_pdf_report_groq(results):
77
  pdf = FPDF()
78
  pdf.add_page()
79
  pdf.set_font("Arial", size=12)
80
 
 
 
 
 
 
 
 
 
81
  pdf.set_font("Arial", 'B', 16)
82
- pdf.cell(200, 10, txt="AI Powered Requirement Analysis - Groq Llama", ln=True, align='C')
 
 
83
  pdf.cell(200, 10, txt=f"Report Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C')
84
- pdf.ln(10)
85
 
 
86
  pdf.set_font("Arial", size=12)
87
  for i, result in enumerate(results, start=1):
88
- if pdf.get_y() > 250:
89
- pdf.add_page()
 
90
  pdf.set_font("Arial", 'B', 16)
91
- pdf.cell(200, 10, txt="AI Powered Requirement Analysis - Groq Llama", ln=True, align='C')
92
  pdf.set_font("Arial", size=12)
93
  pdf.cell(200, 10, txt=f"Report Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C')
94
- pdf.ln(10)
95
 
 
96
  pdf.set_font("Arial", 'B', 14)
97
  pdf.multi_cell(200, 10, txt=f"Requirement R{i}: {result['Requirement']}", align='L')
98
  pdf.set_font("Arial", size=12)
@@ -102,32 +117,36 @@ def generate_pdf_report_groq(results):
102
  pdf.multi_cell(200, 10, txt=f"Defects: {result['Defects']}", align='L')
103
  pdf.multi_cell(200, 10, txt=f"Rewritten: {result['Rewritten']}", align='L')
104
  pdf.multi_cell(200, 10, txt="-" * 50, align='L')
105
- pdf.ln(5)
106
 
107
- pdf_output = "requirements_report_groq.pdf"
108
  pdf.output(pdf_output)
109
  return pdf_output
110
 
111
  # Streamlit app
112
  def main():
113
- st.title("AI Requirement Analysis - Groq Llama")
114
  st.markdown("**Team Name:** Sadia, Areeba, Rabbia, Tesmia")
115
- st.markdown("**Model:** Groq Llama")
116
 
 
117
  input_text = st.text_area("Enter your requirements (one per line or separated by periods):")
118
  requirements = []
119
  if input_text:
 
120
  requirements = [req.strip() for req in input_text.replace("\n", ".").split(".") if req.strip()]
121
 
 
122
  if st.button("Analyze Requirements"):
123
  if not requirements:
124
  st.warning("Please enter requirements.")
125
  else:
126
  results = []
127
  for req in requirements:
128
- if req.strip():
129
- results.append(analyze_requirement_groq(req.strip()))
130
 
 
131
  st.subheader("Analysis Results")
132
  for i, result in enumerate(results, start=1):
133
  st.write(f"### Requirement R{i}: {result['Requirement']}")
@@ -138,14 +157,16 @@ def main():
138
  st.write(f"**Rewritten:** {result['Rewritten']}")
139
  st.write("---")
140
 
141
- pdf_report = generate_pdf_report_groq(results)
 
142
  with open(pdf_report, "rb") as f:
143
  st.download_button(
144
  label="Download PDF Report",
145
  data=f,
146
- file_name="requirements_report_groq.pdf",
147
  mime="application/pdf"
148
  )
149
 
 
150
  if __name__ == "__main__":
151
- main()
 
4
  import os
5
  import time
6
  from datetime import datetime
7
+ import groq
8
 
9
+ # Groq API key (replace with your key or use environment variable)
10
+ api_key = os.getenv("GROQ_API_KEY", "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")
11
 
12
+ # Initialize Groq client
13
+ groq_client = groq.Client(api_key=api_key)
14
+
15
+ # Function to call Groq API with rate limit handling
16
  def call_groq_api(prompt):
 
 
 
 
 
 
 
 
 
 
17
  try:
18
+ response = groq_client.chat.completions.create(
19
+ model="llama2-70b-4096",
20
+ messages=[
21
+ {"role": "user", "content": prompt}
22
+ ]
23
+ )
24
+ return response.choices[0].message.content
25
  except Exception as err:
26
  return f"Error: {err}"
27
 
28
+ # Function to analyze a single requirement
29
+ def analyze_requirement(requirement):
30
+ # Detect requirement type
31
  type_prompt = f"Classify the following requirement as Functional or Non-Functional:\n\n{requirement}\n\nType:"
32
  req_type = call_groq_api(type_prompt)
33
 
34
+ # Identify stakeholders
35
  stakeholders_prompt = f"Identify the stakeholders for the following requirement:\n\n{requirement}\n\nStakeholders:"
36
  stakeholders = call_groq_api(stakeholders_prompt)
37
 
38
+ # Classify domain
39
  domain_prompt = f"Classify the domain for the following requirement (e.g., Bank, Healthcare, etc.):\n\n{requirement}\n\nDomain:"
40
  domain = call_groq_api(domain_prompt)
41
 
42
+ # Detect defects
43
  defects_prompt = f"""Analyze the following requirement and identify ONLY MAJOR defects (e.g., Ambiguity, Incompleteness, etc.).
44
  If the requirement is clear and complete, respond with 'No defects.'
45
  Requirement: {requirement}
46
  Defects:"""
47
  defects = call_groq_api(defects_prompt)
48
 
49
+ # Rewrite requirement
50
+ rewritten = rewrite_requirement(requirement, defects)
51
 
52
  return {
53
  "Requirement": requirement,
 
59
  }
60
 
61
  # Function to rewrite requirement concisely
62
+ def rewrite_requirement(requirement, defects):
63
  if "no defects" in defects.lower():
64
  return "No modification needed."
65
 
66
+ # If defects are found, generate a concise and clear rewritten requirement
67
  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.
68
 
69
  Original Requirement: {requirement}
 
74
  response = call_groq_api(prompt)
75
  return response.strip()
76
 
77
+ # Function to generate a PDF report with professional formatting
78
+ def generate_pdf_report(results):
79
  pdf = FPDF()
80
  pdf.add_page()
81
  pdf.set_font("Arial", size=12)
82
 
83
+ # Add watermark
84
+ pdf.set_font("Arial", 'B', 50)
85
+ pdf.set_text_color(230, 230, 230) # Light gray color for watermark
86
+ pdf.rotate(45) # Rotate the text for watermark effect
87
+ pdf.text(60, 150, "AI Powered Requirement Analysis")
88
+ pdf.rotate(0) # Reset rotation
89
+
90
+ # Add title and date/time
91
  pdf.set_font("Arial", 'B', 16)
92
+ pdf.set_text_color(0, 0, 0) # Black color for title
93
+ pdf.cell(200, 10, txt="AI Powered Requirement Analysis and Defect Detection using LLaMA Model", ln=True, align='C')
94
+ pdf.set_font("Arial", size=12)
95
  pdf.cell(200, 10, txt=f"Report Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C')
96
+ pdf.ln(10) # Add some space
97
 
98
+ # Add requirements analysis
99
  pdf.set_font("Arial", size=12)
100
  for i, result in enumerate(results, start=1):
101
+ # Check if we need a new page
102
+ if pdf.get_y() > 250: # If the content is near the bottom of the page
103
+ pdf.add_page() # Add a new page
104
  pdf.set_font("Arial", 'B', 16)
105
+ pdf.cell(200, 10, txt="AI Powered Requirement Analysis and Defect Detection using LLaMA Model", ln=True, align='C')
106
  pdf.set_font("Arial", size=12)
107
  pdf.cell(200, 10, txt=f"Report Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}", ln=True, align='C')
108
+ pdf.ln(10) # Add some space
109
 
110
+ # Add requirement details
111
  pdf.set_font("Arial", 'B', 14)
112
  pdf.multi_cell(200, 10, txt=f"Requirement R{i}: {result['Requirement']}", align='L')
113
  pdf.set_font("Arial", size=12)
 
117
  pdf.multi_cell(200, 10, txt=f"Defects: {result['Defects']}", align='L')
118
  pdf.multi_cell(200, 10, txt=f"Rewritten: {result['Rewritten']}", align='L')
119
  pdf.multi_cell(200, 10, txt="-" * 50, align='L')
120
+ pdf.ln(5) # Add some space between requirements
121
 
122
+ pdf_output = "requirements_report.pdf"
123
  pdf.output(pdf_output)
124
  return pdf_output
125
 
126
  # Streamlit app
127
  def main():
128
+ st.title("AI Powered Requirement Analysis and Defect Detection using Large Language Model LLaMA")
129
  st.markdown("**Team Name:** Sadia, Areeba, Rabbia, Tesmia")
130
+ st.markdown("**Model:** LLaMA")
131
 
132
+ # Input requirements manually
133
  input_text = st.text_area("Enter your requirements (one per line or separated by periods):")
134
  requirements = []
135
  if input_text:
136
+ # Split by periods or newlines
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']}")
 
157
  st.write(f"**Rewritten:** {result['Rewritten']}")
158
  st.write("---")
159
 
160
+ # Generate and download PDF report
161
+ pdf_report = generate_pdf_report(results)
162
  with open(pdf_report, "rb") as f:
163
  st.download_button(
164
  label="Download PDF Report",
165
  data=f,
166
+ file_name="requirements_report.pdf",
167
  mime="application/pdf"
168
  )
169
 
170
+ # Run the app
171
  if __name__ == "__main__":
172
+ main()