Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -45,158 +45,27 @@ class InferenceClient:
|
|
45 |
|
46 |
class MyChatbot(gr.Chatbot):
|
47 |
"""Custom Chatbot class for enhanced functionality."""
|
48 |
-
def __init__(self,
|
49 |
-
super().__init__(
|
50 |
self.issues = [] # Store fetched issues
|
51 |
self.current_issue = None # Store the currently selected issue
|
52 |
|
53 |
def postprocess(self, y):
|
54 |
"""Post-processes the response to handle commands and display results."""
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
# Handle
|
59 |
-
if y
|
60 |
-
|
61 |
-
|
62 |
-
else:
|
63 |
-
try:
|
64 |
-
self.issues = fetch_github_issues(y['github_api_token'], y['github_username'], y['github_repository'])
|
65 |
-
issue_list = "\n".join([f"{i+1}. {issue['title']}" for i, issue in enumerate(self.issues)])
|
66 |
-
return f"Available GitHub Issues:\n{issue_list}\n\nEnter the issue number to analyze:"
|
67 |
-
except Exception as e:
|
68 |
-
return f"Error fetching GitHub issues: {e}"
|
69 |
-
elif y['command'] == "/help":
|
70 |
-
return """Available commands:
|
71 |
-
- `/github`: Analyze a GitHub issue
|
72 |
-
- `/help`: Show this help message
|
73 |
-
- `/generate_code [code description]`: Generate code based on the description
|
74 |
-
- `/explain_concept [concept]`: Explain a concept
|
75 |
-
- `/write_documentation [topic]`: Write documentation for a given topic
|
76 |
-
- `/translate_code [code] to [target language]`: Translate code to another language"""
|
77 |
-
elif y['command'].isdigit() and self.issues:
|
78 |
-
try:
|
79 |
-
issue_number = int(y['command']) - 1
|
80 |
-
self.current_issue = self.issues[issue_number] # Store the selected issue
|
81 |
-
issue_text = self.current_issue['title'] + "\n\n" + self.current_issue['body']
|
82 |
-
resolution = analyze_issues(issue_text, y['selected_model'], y['severity'], y['programming_language'])
|
83 |
-
related_issues = find_related_issues(issue_text, self.issues)
|
84 |
-
related_issue_text = "\n".join(
|
85 |
-
[f"- {issue['title']} (Similarity: {similarity:.2f})" for issue, similarity in related_issues]
|
86 |
-
)
|
87 |
-
return f"Resolution for Issue '{self.current_issue['title']}':\n{resolution['assistant_response']}\n\nRelated Issues:\n{related_issue_text}"
|
88 |
-
except Exception as e:
|
89 |
-
return f"Error analyzing issue: {e}"
|
90 |
-
elif y['command'].startswith("/"):
|
91 |
-
# Handle commands like `/generate_code`, `/explain_concept`, etc.
|
92 |
-
if self.current_issue:
|
93 |
-
# Use the current issue's context for these commands
|
94 |
-
issue_text = self.current_issue['title'] + "\n\n" + self.current_issue['body']
|
95 |
-
return analyze_issues(issue_text, y['selected_model'], y['severity'], y['programming_language'])['assistant_response']
|
96 |
-
else:
|
97 |
-
return "Please select an issue first using `/github`."
|
98 |
else:
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
def analyze_issues(issue_text: str, model_name: str, severity: str = None, programming_language: str = None) -> str:
|
103 |
-
"""Analyzes issues and provides solutions using a specified language model."""
|
104 |
-
model = pipeline("text-generation", model=model_name)
|
105 |
-
response = model(
|
106 |
-
f"{system_message}\n{issue_text}\nAssistant: ",
|
107 |
-
max_length=max_tokens,
|
108 |
-
do_sample=True,
|
109 |
-
temperature=temperature,
|
110 |
-
top_k=top_p,
|
111 |
-
)
|
112 |
-
assistant_response = response[0]['generated_text'].strip()
|
113 |
-
|
114 |
-
# Extract severity and programming language from the response
|
115 |
-
if "Severity" in assistant_response:
|
116 |
-
severity = assistant_response.split(":")[1].strip()
|
117 |
-
if "Programming Language" in assistant_response:
|
118 |
-
programming_language = assistant_response.split(":")[1].strip()
|
119 |
-
|
120 |
-
return {
|
121 |
-
'assistant_response': assistant_response,
|
122 |
-
'severity': severity,
|
123 |
-
'programming_language': programming_language,
|
124 |
-
}
|
125 |
|
126 |
-
|
127 |
-
"""Finds semantically related issues from a list of issues based on the input issue text."""
|
128 |
-
similarity_model = SentenceTransformer('all-mpnet-base-v2')
|
129 |
-
issue_embedding = similarity_model.encode(issue_text)
|
130 |
-
similarities = [util.cos_sim(issue_embedding, similarity_model.encode(issue['title'])) for issue in issues]
|
131 |
-
sorted_issues = sorted(enumerate(similarities), key=lambda x: x[1], reverse=True)
|
132 |
-
related_issues = [issues[i] for i, similarity in sorted_issues[:5]]
|
133 |
-
return related_issues
|
134 |
-
|
135 |
-
def fetch_github_issues(github_api_token: str, github_username: str, github_repository: str) -> list:
|
136 |
-
"""Fetches issues from a specified GitHub repository using the GitHub API."""
|
137 |
-
headers = {'Authorization': f'token {github_api_token}'}
|
138 |
-
url = f"https://api.github.com/repos/{github_username}/{github_repository}/issues"
|
139 |
-
response = requests.get(url, headers=headers)
|
140 |
-
issues = response.json()
|
141 |
-
return issues
|
142 |
-
|
143 |
-
def push_to_repo(github_api_token: str, github_username: str, github_repository: str, commit_message: str, commit_file: str):
|
144 |
-
"""Pushes changes to a GitHub repository."""
|
145 |
-
try:
|
146 |
-
repo = git.Repo.clone_from(f"https://github.com/{github_username}/{github_repository}.git", f"{github_repository}")
|
147 |
-
repo.git.add(commit_file)
|
148 |
-
repo.git.commit(m=commit_message)
|
149 |
-
repo.git.push()
|
150 |
-
return f"Changes pushed to {github_repository} successfully."
|
151 |
-
except gitdb.exc.InvalidGitRepositoryError:
|
152 |
-
return f"Invalid repository: {github_repository}"
|
153 |
-
except Exception as e:
|
154 |
-
return f"Error pushing to repository: {e}"
|
155 |
-
|
156 |
-
def resolve_issue(github_api_token: str, github_username: str, github_repository: str, issue_number: int, resolution: str):
|
157 |
-
"""Resolves an issue by pushing a commit with the resolution."""
|
158 |
-
try:
|
159 |
-
issue_text = fetch_github_issues(github_api_token, github_username, github_repository)[issue_number]['body']
|
160 |
-
commit_message = f"Resolved issue {issue_number}: {issue_text}"
|
161 |
-
commit_file = "resolution.txt"
|
162 |
-
with open(commit_file, "w") as f:
|
163 |
-
f.write(resolution)
|
164 |
-
return push_to_repo(github_api_token, github_username, github_repository, commit_message, commit_file)
|
165 |
-
except Exception as e:
|
166 |
-
return f"Error resolving issue: {e}"
|
167 |
-
|
168 |
-
def respond(
|
169 |
-
command,
|
170 |
-
history,
|
171 |
-
system_message,
|
172 |
-
max_tokens,
|
173 |
-
temperature,
|
174 |
-
top_p,
|
175 |
-
github_api_token,
|
176 |
-
github_username,
|
177 |
-
github_repository,
|
178 |
-
selected_model,
|
179 |
-
severity,
|
180 |
-
programming_language,
|
181 |
-
*args,
|
182 |
-
**kwargs,
|
183 |
-
) -> dict:
|
184 |
-
"""Handles user commands and generates responses using the selected language model."""
|
185 |
-
model = pipeline("text-generation", model="OpenBMB/multilingual-codeparrot")
|
186 |
-
response = model(
|
187 |
-
f"{system_message}\n{command}\n{history}\n{github_username}/{github_repository}\n{severity}\n{programming_language}\nAssistant: ",
|
188 |
-
max_length=max_tokens,
|
189 |
-
do_sample=True,
|
190 |
-
temperature=temperature,
|
191 |
-
top_k=top_p,
|
192 |
-
)
|
193 |
-
assistant_response = response[0]['generated_text'].strip()
|
194 |
-
return {
|
195 |
-
'assistant_response': assistant_response,
|
196 |
-
'severity': severity,
|
197 |
-
'programming_language': programming_language,
|
198 |
-
}
|
199 |
|
|
|
200 |
with gr.Blocks() as demo:
|
201 |
with gr.Row():
|
202 |
github_api_token = gr.Textbox(label="GitHub API Token", type="password")
|
@@ -226,45 +95,126 @@ with gr.Blocks() as demo:
|
|
226 |
|
227 |
programming_language_textbox = gr.Textbox(label="Programming Language")
|
228 |
|
229 |
-
chatbot
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
234 |
system_message,
|
235 |
gr.Slider(minimum=1, maximum=8192, value=2048, step=1, label="Max new tokens"),
|
236 |
gr.Slider(minimum=0.1, maximum=4.0, value=0.71, step=0.1, label="Temperature"),
|
237 |
-
gr.Slider(
|
238 |
-
minimum=0.1,
|
239 |
-
maximum=1.0,
|
240 |
-
value=0.95,
|
241 |
-
step=0.01,
|
242 |
-
label="Top-p (nucleus sampling)",
|
243 |
-
),
|
244 |
github_api_token,
|
245 |
github_username,
|
246 |
github_repository,
|
247 |
model_dropdown,
|
248 |
severity_dropdown,
|
249 |
-
programming_language_textbox
|
250 |
],
|
251 |
-
|
252 |
)
|
253 |
|
254 |
# Add a button to fetch GitHub issues
|
255 |
fetch_issues_button = gr.Button(label="Fetch Issues")
|
256 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
257 |
|
258 |
# Add a dropdown to select an issue
|
259 |
issue_dropdown = gr.Dropdown(label="Select Issue", choices=[], interactive=True)
|
260 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
261 |
|
262 |
# Add a button to resolve an issue
|
263 |
resolve_issue_button = gr.Button(label="Resolve Issue")
|
264 |
-
|
265 |
-
|
266 |
-
|
267 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
268 |
|
269 |
if __name__ == "__main__":
|
270 |
demo.queue().launch(
|
|
|
45 |
|
46 |
class MyChatbot(gr.Chatbot):
|
47 |
"""Custom Chatbot class for enhanced functionality."""
|
48 |
+
def __init__(self, **kwargs):
|
49 |
+
super().__init__(**kwargs)
|
50 |
self.issues = [] # Store fetched issues
|
51 |
self.current_issue = None # Store the currently selected issue
|
52 |
|
53 |
def postprocess(self, y):
|
54 |
"""Post-processes the response to handle commands and display results."""
|
55 |
+
if not y:
|
56 |
+
return []
|
57 |
+
|
58 |
+
# Handle different types of input
|
59 |
+
if isinstance(y, dict):
|
60 |
+
assistant_response = y.get('assistant_response', '')
|
61 |
+
command = y.get('command', '')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
62 |
else:
|
63 |
+
assistant_response = str(y)
|
64 |
+
command = ''
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
|
66 |
+
return [(None, assistant_response)]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
+
# Update the Blocks implementation
|
69 |
with gr.Blocks() as demo:
|
70 |
with gr.Row():
|
71 |
github_api_token = gr.Textbox(label="GitHub API Token", type="password")
|
|
|
95 |
|
96 |
programming_language_textbox = gr.Textbox(label="Programming Language")
|
97 |
|
98 |
+
# Create the chatbot instance
|
99 |
+
chatbot = MyChatbot()
|
100 |
+
|
101 |
+
# Create input textbox for user messages
|
102 |
+
msg = gr.Textbox(label="Message")
|
103 |
+
|
104 |
+
# Create state for storing conversation history
|
105 |
+
state = gr.State([])
|
106 |
+
|
107 |
+
def user(user_message, history):
|
108 |
+
"""Handle user messages"""
|
109 |
+
return "", history + [[user_message, None]]
|
110 |
+
|
111 |
+
def bot(history, system_msg, max_tokens, temp, top_p, api_token, username, repo, model, severity, lang):
|
112 |
+
"""Generate bot response"""
|
113 |
+
if len(history) == 0:
|
114 |
+
return history
|
115 |
+
|
116 |
+
user_message = history[-1][0]
|
117 |
+
response = respond(
|
118 |
+
command=user_message,
|
119 |
+
history=history[:-1],
|
120 |
+
system_message=system_msg,
|
121 |
+
max_tokens=max_tokens,
|
122 |
+
temperature=temp,
|
123 |
+
top_p=top_p,
|
124 |
+
github_api_token=api_token,
|
125 |
+
github_username=username,
|
126 |
+
github_repository=repo,
|
127 |
+
selected_model=model,
|
128 |
+
severity=severity,
|
129 |
+
programming_language=lang
|
130 |
+
)
|
131 |
+
|
132 |
+
history[-1][1] = response['assistant_response']
|
133 |
+
return history
|
134 |
+
|
135 |
+
# Connect the components
|
136 |
+
msg.submit(
|
137 |
+
user,
|
138 |
+
[msg, chatbot],
|
139 |
+
[msg, chatbot]
|
140 |
+
).then(
|
141 |
+
bot,
|
142 |
+
[
|
143 |
+
chatbot,
|
144 |
system_message,
|
145 |
gr.Slider(minimum=1, maximum=8192, value=2048, step=1, label="Max new tokens"),
|
146 |
gr.Slider(minimum=0.1, maximum=4.0, value=0.71, step=0.1, label="Temperature"),
|
147 |
+
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.01, label="Top-p"),
|
|
|
|
|
|
|
|
|
|
|
|
|
148 |
github_api_token,
|
149 |
github_username,
|
150 |
github_repository,
|
151 |
model_dropdown,
|
152 |
severity_dropdown,
|
153 |
+
programming_language_textbox
|
154 |
],
|
155 |
+
[chatbot]
|
156 |
)
|
157 |
|
158 |
# Add a button to fetch GitHub issues
|
159 |
fetch_issues_button = gr.Button(label="Fetch Issues")
|
160 |
+
|
161 |
+
def fetch_issues(api_token, username, repo):
|
162 |
+
"""Fetch GitHub issues and update the chatbot"""
|
163 |
+
issues = fetch_github_issues(api_token, username, repo)
|
164 |
+
chatbot.issues = issues
|
165 |
+
return gr.Dropdown(choices=[f"{i+1}. {issue['title']}" for i, issue in enumerate(issues)])
|
166 |
+
|
167 |
+
fetch_issues_button.click(
|
168 |
+
fetch_issues,
|
169 |
+
inputs=[github_api_token, github_username, github_repository],
|
170 |
+
outputs=[issue_dropdown]
|
171 |
+
)
|
172 |
|
173 |
# Add a dropdown to select an issue
|
174 |
issue_dropdown = gr.Dropdown(label="Select Issue", choices=[], interactive=True)
|
175 |
+
|
176 |
+
def select_issue(selected, chatbot):
|
177 |
+
"""Handle issue selection"""
|
178 |
+
if selected:
|
179 |
+
issue_num = int(selected.split('.')[0]) - 1
|
180 |
+
chatbot.current_issue = chatbot.issues[issue_num]
|
181 |
+
return chatbot.postprocess({
|
182 |
+
'command': str(issue_num + 1),
|
183 |
+
'github_api_token': github_api_token.value,
|
184 |
+
'github_username': github_username.value,
|
185 |
+
'github_repository': github_repository.value,
|
186 |
+
'selected_model': model_dropdown.value,
|
187 |
+
'severity': severity_dropdown.value,
|
188 |
+
'programming_language': programming_language_textbox.value
|
189 |
+
})
|
190 |
+
return []
|
191 |
+
|
192 |
+
issue_dropdown.change(
|
193 |
+
select_issue,
|
194 |
+
inputs=[issue_dropdown, chatbot],
|
195 |
+
outputs=[chatbot]
|
196 |
+
)
|
197 |
|
198 |
# Add a button to resolve an issue
|
199 |
resolve_issue_button = gr.Button(label="Resolve Issue")
|
200 |
+
|
201 |
+
def resolve_selected_issue(api_token, username, repo, resolution):
|
202 |
+
"""Resolve the currently selected issue"""
|
203 |
+
if chatbot.current_issue:
|
204 |
+
issue_number = chatbot.issues.index(chatbot.current_issue)
|
205 |
+
return resolve_issue(api_token, username, repo, issue_number, resolution)
|
206 |
+
return "No issue selected"
|
207 |
+
|
208 |
+
resolve_issue_button.click(
|
209 |
+
resolve_selected_issue,
|
210 |
+
inputs=[
|
211 |
+
github_api_token,
|
212 |
+
github_username,
|
213 |
+
github_repository,
|
214 |
+
chatbot
|
215 |
+
],
|
216 |
+
outputs=[chatbot]
|
217 |
+
)
|
218 |
|
219 |
if __name__ == "__main__":
|
220 |
demo.queue().launch(
|