Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,327 +1,261 @@
|
|
1 |
-
import argparse
|
2 |
-
import os
|
3 |
-
import re
|
4 |
-
import subprocess
|
5 |
-
import sys
|
6 |
-
import zipfile
|
7 |
-
import random
|
8 |
-
import string
|
9 |
-
import shutil
|
10 |
-
import io
|
11 |
-
import webbrowser
|
12 |
-
from typing import List, Any, Dict, Union
|
13 |
-
from concurrent.futures import ThreadPoolExecutor, as_completed
|
14 |
-
import logging
|
15 |
-
import aiohttp
|
16 |
-
import asyncio
|
17 |
-
import hashlib
|
18 |
import gradio as gr
|
19 |
-
from transformers import
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
CACHE_DIR = './cache'
|
29 |
-
|
30 |
-
class OpenAIWrapper:
|
31 |
-
# Implement OpenAI interaction methods here
|
32 |
-
pass
|
33 |
-
|
34 |
-
async def download_file(url: str) -> bytes:
|
35 |
-
"""Downloads a file asynchronously with retries and returns its content."""
|
36 |
-
logging.info(f"Downloading content from {url}...")
|
37 |
-
async with aiohttp.ClientSession() as session:
|
38 |
-
for attempt in range(3):
|
39 |
-
try:
|
40 |
-
async with session.get(url) as response:
|
41 |
-
if response.status == 200:
|
42 |
-
logging.info("Download complete!")
|
43 |
-
return await response.read()
|
44 |
-
else:
|
45 |
-
logging.error(f"Failed to download content from {url} (status code: {response.status})")
|
46 |
-
except aiohttp.ClientError as e:
|
47 |
-
logging.error(f"Error downloading {url}: {e}")
|
48 |
-
await asyncio.sleep(2 ** attempt) # Exponential backoff
|
49 |
-
return None
|
50 |
-
|
51 |
-
def get_cache_path(url: str) -> str:
|
52 |
-
"""Returns a unique cache path based on the URL."""
|
53 |
-
hash_digest = hashlib.md5(url.encode()).hexdigest()
|
54 |
-
return os.path.join(CACHE_DIR, hash_digest)
|
55 |
-
|
56 |
-
class DownloadItemTask:
|
57 |
-
"""Class responsible for fetching remote content"""
|
58 |
-
|
59 |
-
def __init__(self, url: str):
|
60 |
-
self.url = url
|
61 |
-
|
62 |
-
async def download(self) -> bytes:
|
63 |
-
"""Attempts to download the file using the download_file function"""
|
64 |
-
cache_path = get_cache_path(self.url)
|
65 |
-
if os.path.exists(cache_path):
|
66 |
-
logging.info(f"Using cached file for {self.url}")
|
67 |
-
with open(cache_path, 'rb') as f:
|
68 |
-
return f.read()
|
69 |
-
data = await download_file(self.url)
|
70 |
-
if data:
|
71 |
-
os.makedirs(CACHE_DIR, exist_ok=True)
|
72 |
-
with open(cache_path, 'wb') as f:
|
73 |
-
f.write(data)
|
74 |
-
return data
|
75 |
-
|
76 |
-
class UnarchiveTask:
|
77 |
-
"""Utility class dealing with archives such as .zip or tarballs"""
|
78 |
-
|
79 |
-
def __init__(self, data: bytes):
|
80 |
-
self.data = data
|
81 |
-
|
82 |
-
def unarchive(self) -> str:
|
83 |
-
"""Unpacks and returns root directory holding contents"""
|
84 |
-
logging.info("Unarchiving downloaded file...")
|
85 |
-
extracted_dir = os.path.join(CACHE_DIR, ''.join(random.choices(string.ascii_uppercase + string.digits, k=10)))
|
86 |
-
os.makedirs(extracted_dir, exist_ok=True)
|
87 |
-
|
88 |
-
try:
|
89 |
-
if sys.platform == 'darwin' or sys.platform.startswith('linux'):
|
90 |
-
with open(os.path.join(extracted_dir, 'archive.tar'), 'wb') as f:
|
91 |
-
f.write(self.data)
|
92 |
-
subprocess.run(['tar', '-xf', 'archive.tar', '-C', extracted_dir], check=True)
|
93 |
-
else:
|
94 |
-
with zipfile.ZipFile(io.BytesIO(self.data), 'r') as zip_ref:
|
95 |
-
zip_ref.extractall(extracted_dir)
|
96 |
-
logging.info("Unarchiving complete!")
|
97 |
-
except Exception as e:
|
98 |
-
logging.error(f"Error unarchiving file: {e}")
|
99 |
-
return None
|
100 |
|
101 |
-
|
|
|
102 |
|
103 |
-
|
104 |
-
|
105 |
|
106 |
-
|
107 |
-
|
108 |
-
}
|
109 |
|
110 |
-
def
|
111 |
-
|
112 |
-
self.has_openai_dep = False
|
113 |
|
114 |
-
def
|
115 |
-
|
116 |
-
logging.info("Searching for dependencies...")
|
117 |
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
124 |
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
129 |
except Exception as e:
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
|
172 |
-
|
173 |
-
f.write(f"{dep}: {','.join(paths)}\n")
|
174 |
-
|
175 |
-
def load_mapping(self, mapping_file: str):
|
176 |
-
"""Loads the dependency mapping from a file for future use"""
|
177 |
-
with open(mapping_file, 'r') as f:
|
178 |
-
lines = f.readlines()
|
179 |
-
|
180 |
-
for line in lines:
|
181 |
-
dep, paths = line.strip().split(': ')
|
182 |
-
self.finder.found_paths[dep] = {path.strip() for path in paths.split(',')}
|
183 |
-
|
184 |
-
class WebAppCreatorTask:
|
185 |
-
"""Creates a web app directory and copies converted files to it"""
|
186 |
-
|
187 |
-
def __init__(self, webapp_dirname: str, unarchived_dir: str):
|
188 |
-
self.webapp_dirname = webapp_dirname
|
189 |
-
self.unarchived_dir = unarchived_dir
|
190 |
-
|
191 |
-
def create(self) -> bool:
|
192 |
-
"""Creates a web app directory and copies converted files to it"""
|
193 |
-
logging.info("Creating web app directory...")
|
194 |
-
|
195 |
-
webapp_dir = os.path.join(self.unarchived_dir, self.webapp_dirname)
|
196 |
-
os.makedirs(webapp_dir, exist_ok=True)
|
197 |
-
|
198 |
-
try:
|
199 |
-
for root, _, files in os.walk(self.unarchived_dir):
|
200 |
-
for file in files:
|
201 |
-
if not file.endswith('.html'):
|
202 |
-
continue
|
203 |
-
|
204 |
-
src_path = os.path.join(root, file)
|
205 |
-
dest_path = os.path.join(webapp_dir, file)
|
206 |
-
shutil.copy2(src_path, dest_path)
|
207 |
-
logging.info("Web app directory creation complete!")
|
208 |
-
except Exception as e:
|
209 |
-
logging.error(f"Error creating web app directory: {e}")
|
210 |
-
return False
|
211 |
-
|
212 |
-
return os.path.exists(webapp_dir)
|
213 |
-
|
214 |
-
class DeploymentTask:
|
215 |
-
"""Class responsible for deploying the web application"""
|
216 |
-
|
217 |
-
def __init__(self, webapp_dir: str, api_key: str):
|
218 |
-
self.webapp_dir = webapp_dir
|
219 |
-
self.api_key = api_key
|
220 |
-
self.success = False
|
221 |
-
|
222 |
-
def deploy(self):
|
223 |
-
"""Deploys the web application using the specified API key"""
|
224 |
-
logging.info("Deploying web application...")
|
225 |
-
|
226 |
-
try:
|
227 |
-
# Deployment logic here
|
228 |
-
self.success = True
|
229 |
-
logging.info("Deployment complete!")
|
230 |
-
except Exception as e:
|
231 |
-
logging.error(f"Error during deployment: {e}")
|
232 |
-
self.success = False
|
233 |
-
return self
|
234 |
-
|
235 |
-
def process_file(file_path: str, api_key: str, action: str, dependency_mapping: Dict[str, List[str]]):
|
236 |
-
logging.info(f'\nProcessing local file: {file_path}')
|
237 |
-
|
238 |
-
with open(file_path, 'rb') as f:
|
239 |
-
downloaded_file = f.read()
|
240 |
-
|
241 |
-
unarchived_dir = UnarchiveTask(downloaded_file).unarchive()
|
242 |
-
if not unarchived_dir:
|
243 |
-
logging.error("Unarchiving failed! Proceeding to next URL...")
|
244 |
-
return
|
245 |
-
os.chdir(unarchived_dir)
|
246 |
-
|
247 |
-
tokenizer = AutoTokenizer.from_pretrained('ELECTRA-base-discriminator')
|
248 |
-
pipe = pipeline('text-generation', model='ELECTRA-base-discriminator', tokenizer=tokenizer)
|
249 |
-
|
250 |
-
finder = DependencyFinderTask().find_dependencies(os.curdir)
|
251 |
-
|
252 |
-
# Load dependency mapping if provided
|
253 |
-
if dependency_mapping:
|
254 |
-
finder.load_mapping(dependency_mapping)
|
255 |
-
|
256 |
-
if finder.has_openai_dep:
|
257 |
-
replacer = DependencyReplacerTask(finder, pipe, OpenAIWrapper()).replace()
|
258 |
-
replacer.save_mapping(dependency_mapping)
|
259 |
-
|
260 |
-
created_webapp = WebAppCreatorTask(WEBAPP_DIRNAME, unarchived_dir).create()
|
261 |
-
os.chdir('..')
|
262 |
-
|
263 |
-
if action == 'upload':
|
264 |
-
deploy_task = DeploymentTask(created_webapp, api_key).deploy()
|
265 |
-
if not deploy_task.success:
|
266 |
-
logging.error("Deployment failed! Continuing to next URL...")
|
267 |
-
|
268 |
-
logging.info(f"Successfully processed local file: {file_path}")
|
269 |
-
|
270 |
-
def process_urls(urls: List[str], api_key: str, action: str, dependency_mapping: Dict[str, List[str]]):
|
271 |
-
async def process_url_task(url: str):
|
272 |
-
file_data = await DownloadItemTask(url).download()
|
273 |
-
if file_data:
|
274 |
-
unarchived_dir = UnarchiveTask(file_data).unarchive()
|
275 |
-
if unarchived_dir:
|
276 |
-
process_file(unarchived_dir, api_key, action, dependency_mapping)
|
277 |
-
os.chdir('..')
|
278 |
-
|
279 |
-
with ThreadPoolExecutor() as executor:
|
280 |
-
futures = {executor.submit(process_url_task, url) for url in urls}
|
281 |
-
for future in as_completed(futures):
|
282 |
-
future.result()
|
283 |
-
|
284 |
-
def main():
|
285 |
-
parser = argparse.ArgumentParser()
|
286 |
-
parser.add_argument('--api-key', '-a', type=str, help='Hugging Face API Key')
|
287 |
-
parser.add_argument('--action', '-t', type=str, choices=['convert', 'upload'], help='Action to perform')
|
288 |
-
parser.add_argument('--dependency-mapping', '-d', type=str, help='Dependency mapping file path')
|
289 |
-
|
290 |
-
args = parser.parse_args()
|
291 |
-
|
292 |
-
if not args.api_key:
|
293 |
-
print("Please provide an API key using --api-key flag.")
|
294 |
-
sys.exit(1)
|
295 |
-
|
296 |
-
if not args.action:
|
297 |
-
print("Please provide an action to perform using --action flag.")
|
298 |
-
sys.exit(1)
|
299 |
-
|
300 |
-
dependency_mapping = {}
|
301 |
-
if args.dependency_mapping:
|
302 |
-
if not os.path.exists(args.dependency_mapping):
|
303 |
-
print(f"Dependency mapping file '{args.dependency_mapping}' does not exist.")
|
304 |
-
sys.exit(1)
|
305 |
-
|
306 |
-
with open(args.dependency_mapping, 'r') as f:
|
307 |
-
for line in f:
|
308 |
-
dep, paths = line.strip().split(': ')
|
309 |
-
dependency_mapping[dep] = [path.strip() for path in paths.split(',')]
|
310 |
-
|
311 |
-
iface = gr.Interface(
|
312 |
-
fn=lambda x: None,
|
313 |
-
inputs=gr.inputs.Textbox(label="URLs (comma-separated)"),
|
314 |
-
outputs="text",
|
315 |
-
title="Project Converter and Uploader",
|
316 |
-
description="Convert and upload projects to Hugging Face Spaces."
|
317 |
)
|
318 |
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
|
|
|
|
|
|
|
|
|
|
323 |
|
324 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
325 |
|
326 |
if __name__ == "__main__":
|
327 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import pipeline
|
3 |
+
from sentence_transformers import SentenceTransformer, util
|
4 |
+
import os
|
5 |
+
import requests
|
6 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
7 |
+
|
8 |
+
class InferenceClient:
|
9 |
+
def __init__(self):
|
10 |
+
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
+
def create_endpoint(self, repo_id, handler_path, model_id, task, description, hyperparameters):
|
13 |
+
pass
|
14 |
|
15 |
+
def update_endpoint(self, repo_id, handler_path, model_id, task, description, hyperparameters):
|
16 |
+
pass
|
17 |
|
18 |
+
def delete_endpoint(self, repo_id, handler_path):
|
19 |
+
pass
|
|
|
20 |
|
21 |
+
def list_endpoints(self):
|
22 |
+
pass
|
|
|
23 |
|
24 |
+
def get_endpoint_status(self, repo_id, handler_path):
|
25 |
+
pass
|
|
|
26 |
|
27 |
+
def get_endpoint_logs(self, repo_id, handler_path, num_lines):
|
28 |
+
pass
|
29 |
+
|
30 |
+
def get_endpoint_metrics(self, repo_id, handler_path):
|
31 |
+
pass
|
32 |
+
|
33 |
+
|
34 |
+
from huggingface_hub import InferenceClient,HfApi
|
35 |
+
|
36 |
+
|
37 |
+
client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
|
38 |
+
|
39 |
+
# Load the pre-trained model and tokenizer
|
40 |
+
model_name = "mistralai/Mixtral-8x7B-Instruct-v0.1"
|
41 |
+
model = AutoModelForCodeGeneration.from_pretrained(model_name)
|
42 |
+
tokenizer = AutoTokenizerForCodeGeneration.from_pretrained(model_name)
|
43 |
+
|
44 |
+
# Define input prompt
|
45 |
+
input_prompt = "(input value = highest-level-quality code content invocation ; True)"
|
46 |
+
|
47 |
+
# Tokenize the input prompt
|
48 |
+
input_ids = tokenizer(input_prompt, return_tensors="pt", truncation=True)
|
49 |
+
|
50 |
+
# Generate the code
|
51 |
+
generated_code = model.generate(input_ids.to(model.device))
|
52 |
+
|
53 |
+
# Decode the generated code
|
54 |
+
generated_code_str = tokenizer.batch_decode(generated_code, skip_special_tokens=True)[0]
|
55 |
+
|
56 |
+
# Print the generated code
|
57 |
+
print(generated_code_str)
|
58 |
+
# Constants for enhanced organization
|
59 |
+
GITHUB_API_BASE_URL = "https://api.github.com/repos"
|
60 |
+
DEFAULT_MODEL = "apple/OpenELM"
|
61 |
+
MAX_RELATED_ISSUES = 3
|
62 |
|
63 |
+
# Load a pre-trained model for sentence similarity
|
64 |
+
similarity_model = SentenceTransformer('all-mpnet-base-v2')
|
65 |
+
|
66 |
+
def analyze_issues(issue_text: str, model_name: str, severity: str = None, programming_language: str = None) -> str:
|
67 |
+
"""Analyzes issues and provides solutions using a specified language model."""
|
68 |
+
model = pipeline("text-generation", model=model_name)
|
69 |
+
response = model(
|
70 |
+
f"{system_message}\n{issue_text}\nAssistant: ",
|
71 |
+
max_length=max_tokens,
|
72 |
+
do_sample=True,
|
73 |
+
temperature=temperature,
|
74 |
+
top_k=top_p,
|
75 |
+
)
|
76 |
+
assistant_response = response[0]['generated_text'].strip()
|
77 |
+
|
78 |
+
# Extract severity and programming language from the response
|
79 |
+
if "Severity" in assistant_response:
|
80 |
+
severity = assistant_response.split(":")[1].strip()
|
81 |
+
if "Programming Language" in assistant_response:
|
82 |
+
programming_language = assistant_response.split(":")[1].strip()
|
83 |
+
|
84 |
+
return {
|
85 |
+
'assistant_response': assistant_response,
|
86 |
+
'severity': severity,
|
87 |
+
'programming_language': programming_language,
|
88 |
+
}
|
89 |
+
|
90 |
+
def find_related_issues(issue_text: str, issues: list) -> list:
|
91 |
+
"""Finds semantically related issues from a list of issues based on the input issue text."""
|
92 |
+
issue_embedding = similarity_model.encode(issue_text)
|
93 |
+
similarities = [util.cos_sim(issue_embedding, similarity_model.encode(issue['title'])) for issue in issues]
|
94 |
+
sorted_issues = sorted(enumerate(similarities), key=lambda x: x[1], reverse=True)
|
95 |
+
related_issues = [issues[i] for i, similarity in sorted_issues[:MAX_RELATED_ISSUES]]
|
96 |
+
return related_issues
|
97 |
+
|
98 |
+
def fetch_github_issues(github_api_token: str, github_username: str, github_repository: str) -> list:
|
99 |
+
"""Fetches issues from a specified GitHub repository using the GitHub API."""
|
100 |
+
headers = {'Authorization': f'token {github_api_token}'}
|
101 |
+
url = f"{GITHUB_API_BASE_URL}/{github_username}/{github_repository}/issues"
|
102 |
+
response = requests.get(url, headers=headers)
|
103 |
+
issues = response.json()
|
104 |
+
return issues
|
105 |
+
|
106 |
+
def respond(
|
107 |
+
command,
|
108 |
+
history,
|
109 |
+
system_message,
|
110 |
+
max_tokens,
|
111 |
+
temperature,
|
112 |
+
top_p,
|
113 |
+
github_api_token,
|
114 |
+
github_username,
|
115 |
+
github_repository,
|
116 |
+
selected_model,
|
117 |
+
severity,
|
118 |
+
programming_language,
|
119 |
+
*args,
|
120 |
+
**kwargs,
|
121 |
+
) -> dict:
|
122 |
+
"""Handles user commands and generates responses using the selected language model."""
|
123 |
+
model = pipeline("text-generation", model="enricoros/big-agi")
|
124 |
+
response = model(
|
125 |
+
f"{system_message}\n{command}\n{history}\n{github_username}/{github_repository}\n{severity}\n{programming_language}\nAssistant: ",
|
126 |
+
max_length=max_tokens,
|
127 |
+
do_sample=True,
|
128 |
+
temperature=temperature,
|
129 |
+
top_k=top_p,
|
130 |
+
)
|
131 |
+
assistant_response = response[0]['generated_text'].strip()
|
132 |
+
return {
|
133 |
+
'assistant_response': assistant_response,
|
134 |
+
'severity': severity,
|
135 |
+
'programming_language': programming_language,
|
136 |
+
}
|
137 |
+
|
138 |
+
class MyChatbot(gr.Chatbot):
|
139 |
+
"""Custom Chatbot class for enhanced functionality."""
|
140 |
+
def __init__(self, fn, **kwargs):
|
141 |
+
super().__init__(fn, **kwargs)
|
142 |
+
self.issues = [] # Store fetched issues
|
143 |
+
self.current_issue = None # Store the currently selected issue
|
144 |
+
|
145 |
+
def postprocess(self, y):
|
146 |
+
"""Post-processes the response to handle commands and display results."""
|
147 |
+
# Extract the response from the dictionary
|
148 |
+
assistant_response = y['assistant_response']
|
149 |
+
|
150 |
+
# Handle commands
|
151 |
+
if y['command'] == "/github":
|
152 |
+
if not y['github_api_token']:
|
153 |
+
return "Please enter your GitHub API token first."
|
154 |
+
else:
|
155 |
+
try:
|
156 |
+
self.issues = fetch_github_issues(y['github_api_token'], y['github_username'], y['github_repository'])
|
157 |
+
issue_list = "\n".join([f"{i+1}. {issue['title']}" for i, issue in enumerate(self.issues)])
|
158 |
+
return f"Available GitHub Issues:\n{issue_list}\n\nEnter the issue number to analyze:"
|
159 |
except Exception as e:
|
160 |
+
return f"Error fetching GitHub issues: {e}"
|
161 |
+
elif y['command'] == "/help":
|
162 |
+
return """Available commands:
|
163 |
+
- `/github`: Analyze a GitHub issue
|
164 |
+
- `/help`: Show this help message
|
165 |
+
- `/generate_code [code description]`: Generate code based on the description
|
166 |
+
- `/explain_concept [concept]`: Explain a concept
|
167 |
+
- `/write_documentation [topic]`: Write documentation for a given topic
|
168 |
+
- `/translate_code [code] to [target language]`: Translate code to another language"""
|
169 |
+
elif y['command'].isdigit() and self.issues:
|
170 |
+
try:
|
171 |
+
issue_number = int(y['command']) - 1
|
172 |
+
self.current_issue = self.issues[issue_number] # Store the selected issue
|
173 |
+
issue_text = self.current_issue['title'] + "\n\n" + self.current_issue['body']
|
174 |
+
resolution = analyze_issues(issue_text, y['selected_model'], y['severity'], y['programming_language'])
|
175 |
+
related_issues = find_related_issues(issue_text, self.issues)
|
176 |
+
related_issue_text = "\n".join(
|
177 |
+
[f"- {issue['title']} (Similarity: {similarity:.2f})" for issue, similarity in related_issues]
|
178 |
+
)
|
179 |
+
return f"Resolution for Issue '{self.current_issue['title']}':\n{resolution['assistant_response']}\n\nRelated Issues:\n{related_issue_text}"
|
180 |
+
except Exception as e:
|
181 |
+
return f"Error analyzing issue: {e}"
|
182 |
+
elif y['command'].startswith("/"):
|
183 |
+
# Handle commands like `/generate_code`, `/explain_concept`, etc.
|
184 |
+
if self.current_issue:
|
185 |
+
# Use the current issue's context for these commands
|
186 |
+
issue_text = self.current_issue['title'] + "\n\n" + self.current_issue['body']
|
187 |
+
return analyze_issues(issue_text, y['selected_model'], y['severity'], y['programming_language'])['assistant_response']
|
188 |
+
else:
|
189 |
+
return "Please select an issue first using `/github`."
|
190 |
+
else:
|
191 |
+
# For free-form text, simply display the assistant's response
|
192 |
+
return assistant_response
|
193 |
+
|
194 |
+
with gr.Blocks() as demo:
|
195 |
+
with gr.Row():
|
196 |
+
github_api_token = gr.Textbox(label="GitHub API Token", type="password")
|
197 |
+
github_username = gr.Textbox(label="GitHub Username")
|
198 |
+
github_repository = gr.Textbox(label="GitHub Repository")
|
199 |
+
|
200 |
+
system_message = gr.Textbox(
|
201 |
+
value="You are GitBot, the Github project guardian angel. You resolve issues and propose implementation of feature requests",
|
202 |
+
label="System message",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
203 |
)
|
204 |
|
205 |
+
model_dropdown = gr.Dropdown(
|
206 |
+
choices=[
|
207 |
+
"mistralai/Mixtral-8x7B-Instruct-v0.1",
|
208 |
+
"Gabriel/Swe-review-setfit-model",
|
209 |
+
"OpenBMB/multilingual-codeparrot"
|
210 |
+
],
|
211 |
+
label="Select Model for Issue Resolution",
|
212 |
+
value=DEFAULT_MODEL,
|
213 |
+
)
|
214 |
|
215 |
+
severity_dropdown = gr.Dropdown(
|
216 |
+
choices=["Critical", "Major", "Minor", "Trivial"],
|
217 |
+
label="Severity",
|
218 |
+
value=None,
|
219 |
+
)
|
220 |
+
|
221 |
+
programming_language_textbox = gr.Textbox(label="Programming Language")
|
222 |
+
|
223 |
+
chatbot = MyChatbot(
|
224 |
+
respond,
|
225 |
+
additional_inputs=[
|
226 |
+
system_message,
|
227 |
+
gr.Slider(minimum=1, maximum=8192, value=2048, step=1, label="Max new tokens"),
|
228 |
+
gr.Slider(minimum=0.1, maximum=4.0, value=0.71, step=0.1, label="Temperature"),
|
229 |
+
gr.Slider(
|
230 |
+
minimum=0.1,
|
231 |
+
maximum=1.0,
|
232 |
+
value=0.95,
|
233 |
+
step=0.01,
|
234 |
+
label="Top-p (nucleus sampling)",
|
235 |
+
),
|
236 |
+
github_api_token,
|
237 |
+
github_username,
|
238 |
+
github_repository,
|
239 |
+
model_dropdown,
|
240 |
+
severity_dropdown,
|
241 |
+
programming_language_textbox,
|
242 |
+
],
|
243 |
+
)
|
244 |
+
|
245 |
+
# Add a button to fetch GitHub issues
|
246 |
+
fetch_issues_button = gr.Button(label="Fetch Issues")
|
247 |
+
fetch_issues_button.click(fn=lambda github_api_token, github_username, github_repository: chatbot.issues, inputs=[github_api_token, github_username, github_repository], outputs=[chatbot])
|
248 |
+
|
249 |
+
# Add a dropdown to select an issue
|
250 |
+
issue_dropdown = gr.Dropdown(label="Select Issue", choices=[], interactive=True)
|
251 |
+
issue_dropdown.change(fn=lambda issue_number, chatbot: chatbot.postprocess(issue_number), inputs=[issue_dropdown, chatbot], outputs=[chatbot])
|
252 |
+
|
253 |
+
# Connect the chatbot input to the issue dropdown
|
254 |
+
chatbot.input.change(fn=lambda chatbot, github_api_token, github_username, github_repository: chatbot.postprocess("/github"), inputs=[chatbot, github_api_token, github_username, github_repository], outputs=[chatbot])
|
255 |
|
256 |
if __name__ == "__main__":
|
257 |
+
demo.queue().launch(
|
258 |
+
share=True,
|
259 |
+
server_name="0.0.0.0",
|
260 |
+
server_port=7860
|
261 |
+
)
|