acecalisto3 commited on
Commit
3fecdca
·
verified ·
1 Parent(s): 4388fcb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -23
app.py CHANGED
@@ -4,6 +4,10 @@ import os
4
  import requests
5
  from transformers import pipeline
6
  from sentence_transformers import SentenceTransformer, util
 
 
 
 
7
 
8
  # Hugging Face Inference Client
9
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
@@ -23,6 +27,7 @@ def analyze_issues(issue_text: str, model_name: str, severity: str = None, progr
23
  Returns:
24
  str: The analyzed issue and solution.
25
  """
 
26
  prompt = f"""Issue: {issue_text}
27
  Severity: {severity}
28
  Programming Language: {programming_language}
@@ -50,9 +55,12 @@ Please provide a comprehensive resolution in the following format:
50
  """
51
  try:
52
  nlp = pipeline("text-generation", model=model_name, max_length=1000) # Increase max_length
 
53
  result = nlp(prompt)
 
54
  return result[0]['generated_text']
55
  except Exception as e:
 
56
  return f"Error analyzing issue with model {model_name}: {e}"
57
 
58
  ### Function to find related issues
@@ -65,6 +73,7 @@ def find_related_issues(issue_text: str, issues: list) -> list:
65
  Returns:
66
  list: The list of related issues.
67
  """
 
68
  issue_embedding = similarity_model.encode(issue_text)
69
  related_issues = []
70
  for issue in issues:
@@ -72,6 +81,7 @@ def find_related_issues(issue_text: str, issues: list) -> list:
72
  similarity = util.cos_sim(issue_embedding, title_embedding)[0][0]
73
  related_issues.append((issue, similarity))
74
  related_issues = sorted(related_issues, key=lambda x: x[1], reverse=True)
 
75
  return related_issues[:3] # Return top 3 most similar issues
76
 
77
  ### Function to fetch GitHub issues
@@ -85,6 +95,7 @@ def fetch_github_issues(github_api_token: str, github_username: str, github_repo
85
  Returns:
86
  list: The list of GitHub issues.
87
  """
 
88
  url = f"https://api.github.com/repos/{github_username}/{github_repository}/issues"
89
  headers = {
90
  "Authorization": f"Bearer {github_api_token}",
@@ -92,8 +103,11 @@ def fetch_github_issues(github_api_token: str, github_username: str, github_repo
92
  }
93
  response = requests.get(url, headers=headers)
94
  if response.status_code == 200:
95
- return response.json()
 
 
96
  else:
 
97
  raise Exception(f"Error fetching issues: {response.status_code}")
98
 
99
  ### Function to handle chat responses
@@ -136,12 +150,17 @@ def respond(
136
  issues = []
137
 
138
  messages = [{"role": "system", "content": system_message}]
 
 
 
 
 
 
 
 
 
139
 
140
- for val in history:
141
- if val[0]:
142
- messages.append({"role": "user", "content": val[0]})
143
- if val[1]:
144
- messages.append({"role": "assistant", "content": val[1]})
145
 
146
  if command == "/github":
147
  if not github_api_token:
@@ -152,6 +171,7 @@ def respond(
152
  issue_list = "\n".join([f"{i+1}. {issue['title']}" for i, issue in enumerate(issues)])
153
  yield f"Available GitHub Issues:\n{issue_list}\n\nEnter the issue number to analyze:"
154
  except Exception as e:
 
155
  yield f"Error fetching GitHub issues: {e}"
156
 
157
  elif command == "/help":
@@ -178,6 +198,7 @@ def respond(
178
 
179
  yield f"Resolution for Issue '{issue['title']}':\n{resolution}\n\nRelated Issues:\n{related_issue_text}"
180
  except Exception as e:
 
181
  yield f"Error analyzing issue: {e}"
182
 
183
  elif command.startswith("/generate_code"):
@@ -189,8 +210,13 @@ def respond(
189
  prompt = f"Generate code for the following: {code_description}\nProgramming Language: {programming_language}"
190
  try:
191
  generated_code = analyze_issues(prompt, selected_model) # Reuse analyze_issues for code generation
192
- yield f"```{programming_language}\n{generated_code}\n```"
193
- except Exception as e:
 
 
 
 
 
194
  yield f"Error generating code: {e}"
195
 
196
  elif command.startswith("/explain_concept"):
@@ -203,6 +229,7 @@ def respond(
203
  explanation = analyze_issues(prompt, selected_model) # Reuse analyze_issues for explanation
204
  yield explanation
205
  except Exception as e:
 
206
  yield f"Error explaining concept: {e}"
207
 
208
  elif command.startswith("/write_documentation"):
@@ -215,6 +242,7 @@ def respond(
215
  documentation = analyze_issues(prompt, selected_model)
216
  yield documentation
217
  except Exception as e:
 
218
  yield f"Error writing documentation: {e}"
219
 
220
  elif command.startswith("/translate_code"):
@@ -223,27 +251,42 @@ def respond(
223
  yield "Invalid command format. Use: /translate_code [code] to [target language]"
224
  else:
225
  code, target_language = parts
226
- prompt = f"Translate the following code to {target_language}:\n```\n{code}\n```"
227
- try:
 
 
 
 
228
  translated_code = analyze_issues(prompt, selected_model)
229
- yield f"```{target_language}\n{translated_code}\n```"
230
- except Exception as e:
 
 
 
 
 
231
  yield f"Error translating code: {e}"
232
 
233
  else:
234
  messages.append({"role": "user", "content": command})
 
235
 
236
  response = ""
237
- for message in client.chat_completion(
238
- messages,
239
- max_tokens=max_tokens,
240
- stream=True,
241
- temperature=temperature,
242
- top_p=top_p,
243
- ):
244
- token = message.choices[0].delta.content
245
- response += token
246
- yield response
 
 
 
 
 
247
 
248
  with gr.Blocks() as demo:
249
  with gr.Row():
@@ -322,4 +365,4 @@ with gr.Blocks() as demo:
322
  )
323
 
324
  if __name__ == "__main__":
325
- demo.queue().launch(share=True, server_name="0.0.0.0", server_port=7860, show_header=False)
 
4
  import requests
5
  from transformers import pipeline
6
  from sentence_transformers import SentenceTransformer, util
7
+ import logging
8
+
9
+ # Enable detailed logging
10
+ logging.basicConfig(level=logging.INFO)
11
 
12
  # Hugging Face Inference Client
13
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
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}
 
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
 
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
  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
  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}",
 
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
 
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:
 
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":
 
198
 
199
  yield f"Resolution for Issue '{issue['title']}':\n{resolution}\n\nRelated Issues:\n{related_issue_text}"
200
  except Exception as e:
201
+ logging.error(f"Error analyzing issue: {e}")
202
  yield f"Error analyzing issue: {e}"
203
 
204
  elif command.startswith("/generate_code"):
 
210
  prompt = f"Generate code for the following: {code_description}\nProgramming Language: {programming_language}"
211
  try:
212
  generated_code = analyze_issues(prompt, selected_model) # Reuse analyze_issues for code generation
213
+ yield f"
214
+
215
+
216
+ {programming_language}\n{generated_code}\n
217
+
218
+ except Exception as e:
219
+ logging.error(f"Error generating code: {e}")
220
  yield f"Error generating code: {e}"
221
 
222
  elif command.startswith("/explain_concept"):
 
229
  explanation = analyze_issues(prompt, selected_model) # Reuse analyze_issues for explanation
230
  yield explanation
231
  except Exception as e:
232
+ logging.error(f"Error explaining concept: {e}")
233
  yield f"Error explaining concept: {e}"
234
 
235
  elif command.startswith("/write_documentation"):
 
242
  documentation = analyze_issues(prompt, selected_model)
243
  yield documentation
244
  except Exception as e:
245
+ logging.error(f"Error writing documentation: {e}")
246
  yield f"Error writing documentation: {e}"
247
 
248
  elif command.startswith("/translate_code"):
 
251
  yield "Invalid command format. Use: /translate_code [code] to [target language]"
252
  else:
253
  code, target_language = parts
254
+ prompt = f"Translate the following code to {target_language}:\n
255
+
256
+
257
+ \n{code}\n
258
+
259
+ try:
260
  translated_code = analyze_issues(prompt, selected_model)
261
+ yield f"
262
+
263
+
264
+ {target_language}\n{translated_code}\n
265
+
266
+ except Exception as e:
267
+ logging.error(f"Error translating code: {e}")
268
  yield f"Error translating code: {e}"
269
 
270
  else:
271
  messages.append({"role": "user", "content": command})
272
+ logging.info(f"User message: {command}")
273
 
274
  response = ""
275
+ try:
276
+ for message in client.chat_completion(
277
+ messages,
278
+ max_tokens=max_tokens,
279
+ stream=True,
280
+ temperature=temperature,
281
+ top_p=top_p,
282
+ ):
283
+ logging.info(f"Received message from chat completion: {message}")
284
+ token = message.choices[0].delta.content
285
+ response += token
286
+ yield response
287
+ except Exception as e:
288
+ logging.error(f"Error during chat completion: {e}")
289
+ yield f"An error occurred: {e}"
290
 
291
  with gr.Blocks() as demo:
292
  with gr.Row():
 
365
  )
366
 
367
  if __name__ == "__main__":
368
+ demo.queue().launch(share=True, server_name="0.0.0.0", server_port=7860, show_header=False, debug=True)