acecalisto3 commited on
Commit
ef3dea5
·
verified ·
1 Parent(s): b64707a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +123 -126
app.py CHANGED
@@ -27,10 +27,10 @@ def analyze_issues(issue_text: str, model_name: str, severity: str = None, progr
27
  Returns:
28
  str: The analyzed issue and solution.
29
  """
30
- logging.info(f"Analyzing issue: {issue_text} with model: {model_name}")
31
- prompt = f"""Issue: {issue_text}
32
- Severity: {severity}
33
- Programming Language: {programming_language}
34
  Please provide a comprehensive resolution in the following format:
35
  ## Problem Summary:
36
  (Concise summary of the issue)
@@ -52,16 +52,16 @@ Please provide a comprehensive resolution in the following format:
52
  ## Verification Steps:
53
  1. (Step 1)
54
  2. (Step 2)
55
- """
56
  try:
57
  nlp = pipeline("text-generation", model=model_name, max_length=1000) # Increase max_length
58
- logging.info(f"Pipeline created with model: {model_name}")
59
  result = nlp(prompt)
60
- logging.info(f"Model output: {result}")
61
  return result[0]['generated_text']
62
  except Exception as e:
63
- logging.error(f"Error analyzing issue with model {model_name}: {e}")
64
- return f"Error analyzing issue with model {model_name}: {e}"
65
 
66
  ### Function to find related issues
67
  def find_related_issues(issue_text: str, issues: list) -> list:
@@ -73,7 +73,7 @@ def find_related_issues(issue_text: str, issues: list) -> list:
73
  Returns:
74
  list: The list of related issues.
75
  """
76
- logging.info(f"Finding related issues for: {issue_text}")
77
  issue_embedding = similarity_model.encode(issue_text)
78
  related_issues = []
79
  for issue in issues:
@@ -81,7 +81,7 @@ def find_related_issues(issue_text: str, issues: list) -> list:
81
  similarity = util.cos_sim(issue_embedding, title_embedding)[0][0]
82
  related_issues.append((issue, similarity))
83
  related_issues = sorted(related_issues, key=lambda x: x[1], reverse=True)
84
- logging.info(f"Found related issues: {related_issues}")
85
  return related_issues[:3] # Return top 3 most similar issues
86
 
87
  ### Function to fetch GitHub issues
@@ -95,20 +95,20 @@ def fetch_github_issues(github_api_token: str, github_username: str, github_repo
95
  Returns:
96
  list: The list of GitHub issues.
97
  """
98
- logging.info(f"Fetching GitHub issues for: {github_username}/{github_repository}")
99
- url = f"https://api.github.com/repos/{github_username}/{github_repository}/issues"
100
  headers = {
101
- "Authorization": f"Bearer {github_api_token}",
102
  "Accept": "application/vnd.github.v3+json"
103
  }
104
  response = requests.get(url, headers=headers)
105
  if response.status_code == 200:
106
  issues = response.json()
107
- logging.info(f"Fetched issues: {issues}")
108
  return issues
109
  else:
110
- logging.error(f"Error fetching issues: {response.status_code}")
111
- raise Exception(f"Error fetching issues: {response.status_code}")
112
 
113
  ### Function to handle chat responses
114
  def respond(
@@ -124,7 +124,6 @@ def respond(
124
  selected_model: str,
125
  severity: str,
126
  programming_language: str,
127
- *args # Add *args here
128
  ) -> str:
129
  """
130
  Handle chat responses.
@@ -150,138 +149,136 @@ def respond(
150
  issues = []
151
 
152
  messages = [{"role": "system", "content": system_message}]
153
- logging.info(f"System message: {system_message}")
154
 
155
  for user_msg, assistant_msg in history:
156
  if user_msg:
157
  messages.append({"role": "user", "content": user_msg})
158
- logging.info(f"User message: {user_msg}")
159
  if assistant_msg:
160
  messages.append({"role": "assistant", "content": assistant_msg})
161
- logging.info(f"Assistant message: {assistant_msg}")
162
 
163
- logging.info(f"Command received: {command}")
164
 
165
  if command == "/github":
166
- if not github_api_token:
167
- yield "Please enter your GitHub API token first. <https://github.com/settings/tokens>"
168
- else:
169
- try:
170
- issues = fetch_github_issues(github_api_token, github_username, github_repository)
171
- issue_list = "\n".join([f"{i+1}. {issue['title']}" for i, issue in enumerate(issues)])
172
- yield f"Available GitHub Issues:\n{issue_list}\n\nEnter the issue number to analyze:"
173
- except Exception as e:
174
- logging.error(f"Error fetching GitHub issues: {e}")
175
- yield f"Error fetching GitHub issues: {e}"
176
-
177
- elif command == "/help":
178
- help_message = f"""Available commands:
179
  - `/github`: Analyze a GitHub issue
180
  - `/help`: Show this help message
181
  - `/generate_code [code description]`: Generate code based on the description
182
  - `/explain_concept [concept]`: Explain a concept
183
  - `/write_documentation [topic]`: Write documentation for a given topic
184
  - `/translate_code [code] to [target language]`: Translate code to another language"""
185
- yield help_message # Yield the pre-formatted help message
186
-
187
- elif command.isdigit() and issues:
188
- try:
189
- issue_number = int(command) - 1
190
- issue = issues[issue_number]
191
- issue_text = issue['title'] + "\n\n" + issue['body']
192
- resolution = analyze_issues(issue_text, selected_model, severity, programming_language)
193
-
194
- # Find and display related issues
195
- related_issues = find_related_issues(issue_text, issues)
196
- related_issue_text = "\n".join(
197
- [f"- {issue['title']} (Similarity: {similarity:.2f})" for issue, similarity in related_issues]
198
- )
199
 
200
- yield f"Resolution for Issue '{issue['title']}':\n{resolution}\n\nRelated Issues:\n{related_issue_text}"
201
- except Exception as e:
202
- logging.error(f"Error analyzing issue: {e}")
203
- yield f"Error analyzing issue: {e}"
204
-
205
- elif command.startswith("/generate_code"):
206
- # Extract the code description from the command
207
- code_description = command.replace("/generate_code", "").strip()
208
- if not code_description:
209
- yield "Please provide a description of the code you want to generate."
210
- else:
211
- prompt = f"Generate code for the following: {code_description}\nProgramming Language: {programming_language}"
212
  try:
213
- generated_code = analyze_issues(prompt, selected_model)
214
- code_output = f"<pre>{programming_language}\n{generated_code}</pre>"
215
- yield code_output # Yield the formatted string
 
 
 
 
 
 
 
 
 
216
  except Exception as e:
217
- logging.error(f"Error generating code: {e}")
218
- yield f"Error generating code: {e}"
219
-
220
- elif command.startswith("/explain_concept"):
221
- concept = command.replace("/explain_concept", "").strip()
222
- if not concept:
223
- yield "Please provide a concept to explain."
224
- else:
225
- prompt = f"Explain the concept of {concept} in detail."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
226
  try:
227
- explanation = analyze_issues(prompt, selected_model)
228
- yield f"<pre>{explanation}</pre>"
 
 
 
 
 
 
 
 
 
229
  except Exception as e:
230
- logging.error(f"Error explaining concept: {e}")
231
- yield f"Error explaining concept: {e}"
232
 
233
- elif command.startswith("/write_documentation"):
234
- topic = command.replace("/write_documentation", "").strip()
235
- if not topic:
236
- yield "Please provide a topic for documentation."
237
  else:
238
- prompt = f"Write comprehensive documentation for the following topic: {topic}"
 
 
 
239
  try:
240
- documentation = analyze_issues(prompt, selected_model)
241
- yield f"<pre>{documentation}</pre>"
 
 
 
 
 
 
 
 
 
242
  except Exception as e:
243
- logging.error(f"Error writing documentation: {e}")
244
- yield f"Error writing documentation: {e}"
245
-
246
- elif command.startswith("/translate_code"):
247
- parts = command.replace("/translate_code", "").strip().split(" to ")
248
- if len(parts) != 2:
249
- yield "Invalid command format. Use: /translate_code [code] to [target language]"
250
- else:
251
- code, target_language = parts
252
- prompt = f"Translate the following code to {target_language}:\n\n
253
-
254
-
255
- {code}\n
256
-
257
- try:
258
- translated_code = analyze_issues(prompt, selected_model)
259
- code_output = f"<pre>{target_language}\n{translated_code}</pre>"
260
- yield code_output # Yield the formatted string
261
- except Exception as e:
262
- logging.error(f"Error translating code: {e}")
263
- yield f"Error translating code: {e}"
264
-
265
- else:
266
- messages.append({"role": "user", "content": command})
267
- logging.info(f"User message: {command}")
268
-
269
- response = ""
270
- try:
271
- for message in client.chat_completion(
272
- messages,
273
- max_tokens=max_tokens,
274
- stream=True,
275
- temperature=temperature,
276
- top_p=top_p,
277
- ):
278
- logging.info(f"Received message from chat completion: {message}")
279
- token = message.choices[0].delta.content
280
- response += token
281
- yield response
282
- except Exception as e:
283
- logging.error(f"Error during chat completion: {e}")
284
- yield f"An error occurred: {e}"
285
 
286
  with gr.Blocks() as demo:
287
  with gr.Row():
 
27
  Returns:
28
  str: The analyzed issue and solution.
29
  """
30
+ logging.info("Analyzing issue: {} with model: {}".format(issue_text, model_name))
31
+ prompt = """Issue: {}
32
+ Severity: {}
33
+ Programming Language: {}
34
  Please provide a comprehensive resolution in the following format:
35
  ## Problem Summary:
36
  (Concise summary of the issue)
 
52
  ## Verification Steps:
53
  1. (Step 1)
54
  2. (Step 2)
55
+ """.format(issue_text, severity, programming_language)
56
  try:
57
  nlp = pipeline("text-generation", model=model_name, max_length=1000) # Increase max_length
58
+ logging.info("Pipeline created with model: {}".format(model_name))
59
  result = nlp(prompt)
60
+ logging.info("Model output: {}".format(result))
61
  return result[0]['generated_text']
62
  except Exception as e:
63
+ logging.error("Error analyzing issue with model {}: {}".format(model_name, e))
64
+ return "Error analyzing issue with model {}: {}".format(model_name, e)
65
 
66
  ### Function to find related issues
67
  def find_related_issues(issue_text: str, issues: list) -> list:
 
73
  Returns:
74
  list: The list of related issues.
75
  """
76
+ logging.info("Finding related issues for: {}".format(issue_text))
77
  issue_embedding = similarity_model.encode(issue_text)
78
  related_issues = []
79
  for issue in issues:
 
81
  similarity = util.cos_sim(issue_embedding, title_embedding)[0][0]
82
  related_issues.append((issue, similarity))
83
  related_issues = sorted(related_issues, key=lambda x: x[1], reverse=True)
84
+ logging.info("Found related issues: {}".format(related_issues))
85
  return related_issues[:3] # Return top 3 most similar issues
86
 
87
  ### Function to fetch GitHub issues
 
95
  Returns:
96
  list: The list of GitHub issues.
97
  """
98
+ logging.info("Fetching GitHub issues for: {}/{}".format(github_username, github_repository))
99
+ url = "https://api.github.com/repos/{}/{}/issues".format(github_username, github_repository)
100
  headers = {
101
+ "Authorization": "Bearer {}".format(github_api_token),
102
  "Accept": "application/vnd.github.v3+json"
103
  }
104
  response = requests.get(url, headers=headers)
105
  if response.status_code == 200:
106
  issues = response.json()
107
+ logging.info("Fetched issues: {}".format(issues))
108
  return issues
109
  else:
110
+ logging.error("Error fetching issues: {}".format(response.status_code))
111
+ raise Exception("Error fetching issues: {}".format(response.status_code))
112
 
113
  ### Function to handle chat responses
114
  def respond(
 
124
  selected_model: str,
125
  severity: str,
126
  programming_language: str,
 
127
  ) -> str:
128
  """
129
  Handle chat responses.
 
149
  issues = []
150
 
151
  messages = [{"role": "system", "content": system_message}]
152
+ logging.info("System message: {}".format(system_message))
153
 
154
  for user_msg, assistant_msg in history:
155
  if user_msg:
156
  messages.append({"role": "user", "content": user_msg})
157
+ logging.info("User message: {}".format(user_msg))
158
  if assistant_msg:
159
  messages.append({"role": "assistant", "content": assistant_msg})
160
+ logging.info("Assistant message: {}".format(assistant_msg))
161
 
162
+ logging.info("Command received: {}".format(command))
163
 
164
  if command == "/github":
165
+ if not github_api_token:
166
+ return "Please enter your GitHub API token first. <https://github.com/settings/tokens>"
167
+ else:
168
+ try:
169
+ issues = fetch_github_issues(github_api_token, github_username, github_repository)
170
+ issue_list = "\n".join(["{}. {}".format(i+1, issue['title']) for i, issue in enumerate(issues)])
171
+ return "Available GitHub Issues:\n{}\n\nEnter the issue number to analyze:".format(issue_list)
172
+ except Exception as e:
173
+ logging.error("Error fetching GitHub issues: {}".format(e))
174
+ return "Error fetching GitHub issues: {}".format(e)
175
+
176
+ elif command == "/help":
177
+ help_message = """Available commands:
178
  - `/github`: Analyze a GitHub issue
179
  - `/help`: Show this help message
180
  - `/generate_code [code description]`: Generate code based on the description
181
  - `/explain_concept [concept]`: Explain a concept
182
  - `/write_documentation [topic]`: Write documentation for a given topic
183
  - `/translate_code [code] to [target language]`: Translate code to another language"""
184
+ return help_message # Yield the pre-formatted help message
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
+ elif command.isdigit() and issues:
 
 
 
 
 
 
 
 
 
 
 
187
  try:
188
+ issue_number = int(command) - 1
189
+ issue = issues[issue_number]
190
+ issue_text = issue['title'] + "\n\n" + issue['body']
191
+ resolution = analyze_issues(issue_text, selected_model, severity, programming_language)
192
+
193
+ # Find and display related issues
194
+ related_issues = find_related_issues(issue_text, issues)
195
+ related_issue_text = "\n".join(
196
+ ["- {} (Similarity: {:.2f})".format(issue['title'], similarity) for issue, similarity in related_issues]
197
+ )
198
+
199
+ return "Resolution for Issue '{}':\n{}\n\nRelated Issues:\n{}".format(issue['title'], resolution, related_issue_text)
200
  except Exception as e:
201
+ logging.error("Error analyzing issue: {}".format(e))
202
+ return "Error analyzing issue: {}".format(e)
203
+
204
+ elif command.startswith("/generate_code"):
205
+ # Extract the code description from the command
206
+ code_description = command.replace("/generate_code", "").strip()
207
+ if not code_description:
208
+ return "Please provide a description of the code you want to generate."
209
+ else:
210
+ prompt = "Generate code for the following: {}\nProgramming Language: {}".format(code_description, programming_language)
211
+ try:
212
+ generated_code = analyze_issues(prompt, selected_model)
213
+ code_output = "<pre>{}</pre>".format(generated_code)
214
+ return code_output # Yield the formatted string
215
+ except Exception as e:
216
+ logging.error("Error generating code: {}".format(e))
217
+ return "Error generating code: {}".format(e)
218
+
219
+ elif command.startswith("/explain_concept"):
220
+ concept = command.replace("/explain_concept", "").strip()
221
+ if not concept:
222
+ return "Please provide a concept to explain."
223
+ else:
224
+ prompt = "Explain the concept of {} in detail.".format(concept)
225
+ try:
226
+ explanation = analyze_issues(prompt, selected_model)
227
+ return "<pre>{}</pre>".format(explanation)
228
+ except Exception as e:
229
+ logging.error("Error explaining concept: {}".format(e))
230
+ return "Error explaining concept: {}".format(e)
231
+
232
+ elif command.startswith("/write_documentation"):
233
+ topic = command.replace("/write_documentation", "").strip()
234
+ if not topic:
235
+ return "Please provide a topic for the documentation."
236
+ else:
237
+ prompt = "Write documentation for the following topic: {}\nProgramming Language: {}".format(topic, programming_language)
238
+ try:
239
+ documentation = analyze_issues(prompt, selected_model)
240
+ return "<pre>{}</pre>".format(documentation)
241
+ except Exception as e:
242
+ logging.error("Error writing documentation: {}".format(e))
243
+ return "Error writing documentation: {}".format(e)
244
+
245
+ elif command.startswith("/translate_code"):
246
  try:
247
+ code_and_language = command.replace("/translate_code", "").strip().split(" to ")
248
+ code = code_and_language[0]
249
+ target_language = code_and_language[1]
250
+ prompt = "Translate the following code to {}:\n\n{}".format(target_language, code)
251
+ try:
252
+ translated_code = analyze_issues(prompt, selected_model)
253
+ code_output = "<pre>{}</pre>".format(translated_code)
254
+ return code_output # Yield the formatted string
255
+ except Exception as e:
256
+ logging.error("Error translating code: {}".format(e))
257
+ return "Error translating code: {}".format(e)
258
  except Exception as e:
259
+ logging.error("Error parsing translate_code command: {}".format(e))
260
+ return "Error parsing translate_code command: {}".format(e)
261
 
 
 
 
 
262
  else:
263
+ messages.append({"role": "user", "content": command})
264
+ logging.info(f"User message: {command}")
265
+
266
+ response = ""
267
  try:
268
+ for message in client.chat_completion(
269
+ messages,
270
+ max_tokens=max_tokens,
271
+ stream=True,
272
+ temperature=temperature,
273
+ top_p=top_p,
274
+ ):
275
+ logging.info(f"Received message from chat completion: {message}")
276
+ token = message.choices[0].delta.content
277
+ response += token
278
+ return response
279
  except Exception as e:
280
+ logging.error(f"Error during chat completion: {e}")
281
+ return "An error occurred: {}".format(e)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
 
283
  with gr.Blocks() as demo:
284
  with gr.Row():