jyo01 commited on
Commit
a747f19
·
verified ·
1 Parent(s): 03053a2

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +224 -0
app.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import json
3
+ import base64
4
+ import requests
5
+ import torch
6
+ import nest_asyncio
7
+ from fastapi import HTTPException
8
+ from pydantic import BaseModel
9
+ from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
10
+ from sentence_transformers import SentenceTransformer, models
11
+ import gradio as gr
12
+
13
+
14
+ # Apply nest_asyncio to allow async operations in the notebook/Spaces
15
+ nest_asyncio.apply()
16
+
17
+ import os
18
+
19
+ HF_TOKEN = os.environ.get("HF_TOKEN")
20
+ GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")
21
+
22
+
23
+ ############################################
24
+ # GitHub API Functions
25
+ ############################################
26
+
27
+ def extract_repo_info(github_url: str):
28
+ pattern = r"github\.com/([^/]+)/([^/]+)"
29
+ match = re.search(pattern, github_url)
30
+ if match:
31
+ owner = match.group(1)
32
+ repo = match.group(2).replace('.git', '')
33
+ return owner, repo
34
+ else:
35
+ raise ValueError("Invalid GitHub URL provided.")
36
+
37
+ def get_repo_metadata(owner: str, repo: str):
38
+ headers = {'Authorization': f'token {GITHUB_TOKEN}'}
39
+ repo_url = f"https://api.github.com/repos/{owner}/{repo}"
40
+ response = requests.get(repo_url, headers=headers)
41
+ return response.json()
42
+
43
+ def get_repo_tree(owner: str, repo: str, branch: str):
44
+ headers = {'Authorization': f'token {GITHUB_TOKEN}'}
45
+ tree_url = f"https://api.github.com/repos/{owner}/{repo}/git/trees/{branch}?recursive=1"
46
+ response = requests.get(tree_url, headers=headers)
47
+ return response.json()
48
+
49
+ def get_file_content(owner: str, repo: str, file_path: str):
50
+ headers = {'Authorization': f'token {GITHUB_TOKEN}'}
51
+ content_url = f"https://api.github.com/repos/{owner}/{repo}/contents/{file_path}"
52
+ response = requests.get(content_url, headers=headers)
53
+ data = response.json()
54
+ if 'content' in data:
55
+ return base64.b64decode(data['content']).decode('utf-8')
56
+ else:
57
+ return None
58
+
59
+ ############################################
60
+ # Embedding Functions
61
+ ############################################
62
+
63
+ def preprocess_text(text: str) -> str:
64
+ cleaned_text = text.strip()
65
+ cleaned_text = re.sub(r'\s+', ' ', cleaned_text)
66
+ return cleaned_text
67
+
68
+ def load_embedding_model(model_name: str = 'huggingface/CodeBERTa-small-v1') -> SentenceTransformer:
69
+ transformer_model = models.Transformer(model_name)
70
+ pooling_model = models.Pooling(transformer_model.get_word_embedding_dimension(),
71
+ pooling_mode_mean_tokens=True)
72
+ model = SentenceTransformer(modules=[transformer_model, pooling_model])
73
+ return model
74
+
75
+ def generate_embedding(text: str, model_name: str = 'huggingface/CodeBERTa-small-v1') -> list:
76
+ processed_text = preprocess_text(text)
77
+ model = load_embedding_model(model_name)
78
+ embedding = model.encode(processed_text)
79
+ return embedding
80
+
81
+ ############################################
82
+ # LLM Integration Functions
83
+ ############################################
84
+
85
+ def is_detailed_query(query: str) -> bool:
86
+ keywords = ["detail", "detailed", "thorough", "in depth", "comprehensive", "extensive"]
87
+ return any(keyword in query.lower() for keyword in keywords)
88
+
89
+ def generate_prompt(query: str, context_snippets: list) -> str:
90
+ context = "\n\n".join(context_snippets)
91
+ if is_detailed_query(query):
92
+ instruction = "Provide an extremely detailed and thorough explanation of at least 500 words."
93
+ else:
94
+ instruction = "Answer concisely."
95
+
96
+ prompt = (
97
+ f"Below is some context from a GitHub repository:\n\n"
98
+ f"{context}\n\n"
99
+ f"Based on the above, {instruction}\n{query}\n"
100
+ f"Answer:"
101
+ )
102
+ return prompt
103
+
104
+ def get_llm_response(prompt: str, model_name: str = "meta-llama/Llama-2-7b-chat-hf", max_new_tokens: int = None) -> str:
105
+ if max_new_tokens is None:
106
+ max_new_tokens = 1024 if is_detailed_query(prompt) else 256
107
+
108
+ torch.cuda.empty_cache()
109
+
110
+ # Load tokenizer and model with authentication using the 'token' parameter.
111
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True, token=HF_TOKEN)
112
+ model = AutoModelForCausalLM.from_pretrained(
113
+ model_name,
114
+ device_map="auto",
115
+ use_safetensors=False,
116
+ trust_remote_code=True,
117
+ torch_dtype=torch.float16,
118
+ token=HF_TOKEN
119
+ )
120
+
121
+ text_gen = pipeline("text-generation", model=model, tokenizer=tokenizer)
122
+ outputs = text_gen(prompt, max_new_tokens=max_new_tokens, do_sample=True, temperature=0.7)
123
+ full_response = outputs[0]['generated_text']
124
+
125
+ marker = "Answer:"
126
+ if marker in full_response:
127
+ answer = full_response.split(marker, 1)[1].strip()
128
+ else:
129
+ answer = full_response.strip()
130
+
131
+ return answer
132
+
133
+ ############################################
134
+ # Gradio Interface Functions
135
+ ############################################
136
+
137
+ def load_repo_contents(github_url: str):
138
+ try:
139
+ owner, repo = extract_repo_info(github_url)
140
+ except Exception as e:
141
+ return f"Error: {str(e)}"
142
+ repo_data = get_repo_metadata(owner, repo)
143
+ default_branch = repo_data.get("default_branch", "main")
144
+ tree_data = get_repo_tree(owner, repo, default_branch)
145
+ if "tree" not in tree_data:
146
+ return "Error: Could not fetch repository tree."
147
+ file_list = [item["path"] for item in tree_data["tree"] if item["type"] == "blob"]
148
+ return file_list
149
+
150
+ def get_file_content_for_choice(github_url: str, file_choice: int):
151
+ try:
152
+ owner, repo = extract_repo_info(github_url)
153
+ except Exception as e:
154
+ return str(e)
155
+ repo_data = get_repo_metadata(owner, repo)
156
+ default_branch = repo_data.get("default_branch", "main")
157
+ tree_data = get_repo_tree(owner, repo, default_branch)
158
+ if "tree" not in tree_data:
159
+ return "Error: Could not fetch repository tree."
160
+ file_list = [item["path"] for item in tree_data["tree"] if item["type"] == "blob"]
161
+ if file_choice < 1 or file_choice > len(file_list):
162
+ return "Error: Invalid file choice."
163
+ selected_file = file_list[file_choice - 1]
164
+ content = get_file_content(owner, repo, selected_file)
165
+ return content, selected_file
166
+
167
+ def chat_with_file(github_url: str, file_choice: int, user_query: str):
168
+ result = get_file_content_for_choice(github_url, file_choice)
169
+ if isinstance(result, str):
170
+ return result # Error message
171
+ file_content, selected_file = result
172
+ preprocessed = preprocess_text(file_content)
173
+ context_snippet = preprocessed[:1000] # use first 1000 characters as context
174
+ prompt = generate_prompt(user_query, [context_snippet])
175
+ llm_response = get_llm_response(prompt)
176
+ return f"File: {selected_file}\n\nLLM Response:\n{llm_response}"
177
+
178
+ ############################################
179
+ # Gradio Interface Setup
180
+ ############################################
181
+
182
+ with gr.Blocks() as demo:
183
+ gr.Markdown("# RepoChat - Chat with Repository Files")
184
+
185
+ with gr.Row():
186
+ with gr.Column(scale=1):
187
+ gr.Markdown("### Repository Information")
188
+ github_url_input = gr.Textbox(label="GitHub Repository URL", placeholder="https://github.com/username/repository")
189
+ load_repo_btn = gr.Button("Load Repository Contents")
190
+ file_dropdown = gr.Dropdown(label="Select a File", interactive=True)
191
+ repo_content_output = gr.Textbox(label="File Content", interactive=False, lines=10)
192
+ with gr.Column(scale=2):
193
+ gr.Markdown("### Chat Interface")
194
+ chat_query_input = gr.Textbox(label="Your Query", placeholder="Type your query here")
195
+ chat_output = gr.Textbox(label="Chatbot Response", interactive=False, lines=10)
196
+ chat_btn = gr.Button("Send Query")
197
+
198
+ # When clicking "Load Repository Contents", update file dropdown
199
+ def update_file_dropdown(github_url):
200
+ files = load_repo_contents(github_url)
201
+ return files
202
+
203
+ load_repo_btn.click(fn=update_file_dropdown, inputs=[github_url_input], outputs=[file_dropdown])
204
+
205
+ # When file selection changes, update file content display
206
+ def update_repo_content(github_url, file_choice):
207
+ if not file_choice:
208
+ return "No file selected."
209
+ try:
210
+ file_index = int(file_choice)
211
+ except:
212
+ file_index = 1
213
+ content, _ = get_file_content_for_choice(github_url, file_index)
214
+ return content
215
+
216
+ file_dropdown.change(fn=update_repo_content, inputs=[github_url_input, file_dropdown], outputs=[repo_content_output])
217
+
218
+ # When sending a chat query, process it
219
+ def process_chat(github_url, file_choice, chat_query):
220
+ return chat_with_file(github_url, int(file_choice), chat_query)
221
+
222
+ chat_btn.click(fn=process_chat, inputs=[github_url_input, file_dropdown, chat_query_input], outputs=[chat_output])
223
+
224
+ demo.launch()