Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
408 lines (292 loc) · 7.46 KB
/
Copy pathapp.py
File metadata and controls
408 lines (292 loc) · 7.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import os
import shutil
import tempfile
import streamlit as st
from dotenv import load_dotenv
from git import Repo
from langchain_community.vectorstores import FAISS
from langchain_huggingface import HuggingFaceEmbeddings
from langchain_groq import ChatGroq
from langchain_core.documents import Document
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
SUPPORTED_EXTENSIONS = {
".py",
".js",
".jsx",
".ts",
".tsx",
".java",
".cpp",
".c",
".h",
}
IGNORED_DIRECTORIES = {
".git",
"node_modules",
"venv",
".venv",
"__pycache__",
"dist",
"build",
}
def clone_repository(repo_url):
repository_path = tempfile.mkdtemp(
prefix="codemap_repo_"
)
Repo.clone_from(
repo_url,
repository_path
)
return repository_path
def load_code_files(repository_path):
documents = []
for root, directories, files in os.walk(
repository_path
):
directories[:] = [
directory
for directory in directories
if directory not in IGNORED_DIRECTORIES
]
for filename in files:
extension = os.path.splitext(
filename
)[1].lower()
if extension not in SUPPORTED_EXTENSIONS:
continue
file_path = os.path.join(
root,
filename
)
try:
with open(
file_path,
"r",
encoding="utf-8",
errors="ignore"
) as file:
content = file.read()
if not content.strip():
continue
relative_path = os.path.relpath(
file_path,
repository_path
)
documents.append(
Document(
page_content=content,
metadata={
"source": relative_path,
"file_name": filename,
"extension": extension,
}
)
)
except Exception:
continue
return documents
def create_vector_store(documents):
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=1000,
chunk_overlap=200
)
chunks = text_splitter.split_documents(
documents
)
embedding_model = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
vector_store = FAISS.from_documents(
chunks,
embedding_model
)
return vector_store
def create_llm():
load_dotenv()
api_key = os.getenv(
"GROQ_API_KEY"
)
if not api_key:
raise ValueError(
"GROQ_API_KEY was not found in .env"
)
return ChatGroq(
model="openai/gpt-oss-20b",
temperature=0,
api_key=api_key
)
def answer_question(
vector_store,
llm,
question
):
retriever = vector_store.as_retriever(
search_kwargs={
"k": 4
}
)
documents = retriever.invoke(
question
)
context_parts = []
for document in documents:
source = document.metadata.get(
"source",
"Unknown"
)
context_parts.append(
f"FILE: {source}\n\n"
f"{document.page_content}"
)
context = "\n\n".join(
context_parts
)
prompt = PromptTemplate(
template="""
You are CodeMap, an AI assistant that helps
developers understand unfamiliar codebases.
Answer the question using ONLY the provided
code context.
Be accurate and concise.
Always mention the relevant file names.
If the answer cannot be found in the context,
say:
"I could not find the answer in the provided repository."
CODE CONTEXT:
{context}
QUESTION:
{question}
ANSWER:
""",
input_variables=[
"context",
"question"
]
)
chain = (
prompt
| llm
| StrOutputParser()
)
answer = chain.invoke(
{
"context": context,
"question": question
}
)
sources = []
for document in documents:
source = document.metadata.get(
"source",
"Unknown"
)
if source not in sources:
sources.append(
source
)
return answer, sources
st.set_page_config(
page_title="CodeMap",
page_icon="Code",
layout="wide"
)
st.title("CodeMap")
st.write(
"Understand any GitHub codebase using natural language."
)
st.subheader(
"1. Enter GitHub Repository"
)
repo_url = st.text_input(
"GitHub Repository URL",
placeholder="https://github.com/user/project"
)
if st.button(
"Analyze Repository",
type="primary"
):
if not repo_url:
st.warning(
"Please enter a GitHub repository URL."
)
else:
try:
with st.spinner(
"Cloning and analyzing repository..."
):
repository_path = clone_repository(
repo_url
)
documents = load_code_files(
repository_path
)
if not documents:
raise ValueError(
"No supported source code files found."
)
vector_store = create_vector_store(
documents
)
llm = create_llm()
st.session_state.vector_store = (
vector_store
)
st.session_state.llm = llm
st.session_state.repository_ready = True
st.success(
f"Repository analyzed successfully. "
f"Found {len(documents)} source files."
)
except Exception as e:
st.error(
f"Could not analyze repository: {e}"
)
if st.session_state.get(
"repository_ready",
False
):
st.divider()
st.subheader(
"2. Ask About the Code"
)
question = st.text_input(
"Ask a question",
placeholder="Where is authentication handled?"
)
if st.button(
"Ask CodeMap",
type="primary"
):
if not question:
st.warning(
"Please enter a question."
)
else:
try:
with st.spinner(
"Searching the codebase..."
):
answer, sources = answer_question(
st.session_state.vector_store,
st.session_state.llm,
question
)
st.subheader(
"Answer"
)
st.write(
answer
)
st.subheader(
"Sources"
)
for source in sources:
st.code(
source
)
except Exception as e:
st.error(
f"Something went wrong: {e}"
)