-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
391 lines (302 loc) · 14.7 KB
/
app.py
File metadata and controls
391 lines (302 loc) · 14.7 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
from flask import Flask, request, jsonify
import os
import requests
from requests.exceptions import HTTPError
import warnings
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
import json
import re
from urllib.parse import urlparse
import base64
import logging
from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import JsonOutputParser
from pydantic import BaseModel, Field
# Настраиваем логирование: пишем в файл app.log и в консоль
logging.basicConfig(
level=logging.INFO, # Уровень отлова сообщений
format='%(asctime)s [%(levelname)s] %(message)s',
handlers=[
#logging.FileHandler("app.log", encoding="utf-8"),
logging.StreamHandler() # Вывод в консоль
]
)
logger = logging.getLogger(__name__)
# Загружаем переменные окружения
load_dotenv()
NEBIUS_API_KEY = os.environ.get("NEBIUS_API_KEY")
GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")
# Инициализируем LLM
llm = ChatOpenAI(
base_url="https://api.tokenfactory.nebius.com/v1/",
api_key=NEBIUS_API_KEY,
model="Qwen/Qwen3-Coder-480B-A35B-Instruct",
#model="meta-llama/Meta-Llama-3.1-8B-Instruct",
request_timeout=120.0, # Ждать максимум 120 секунд!
temperature=0,
model_kwargs={"response_format": {"type": "json_object"}},
)
class ImportantFilesSchema(BaseModel):
# Pydantic ожидает объект (словарь), поэтому мы оборачиваем список в ключ "files"
files: list[str] = Field(description="JSON array of file paths, for example: ['src/main.py', 'config.yaml']")
class RepoSummarySchema(BaseModel):
summary: str = Field(description="A clear, human-readable description of what this project does")
technologies: list[str] = Field(description="List of main technologies, languages, frameworks")
structure: str = Field(description="Brief description of the project structure and organization")
app = Flask(__name__)
def get_github_headers():
"""Возвращает headers для GitHub API с токеном если есть"""
headers = {}
if GITHUB_TOKEN:
headers["Authorization"] = f"Bearer {GITHUB_TOKEN}"
return headers
def parse_github_url(url: str):
if not isinstance(url, str) or not url.strip():
raise ValueError("URL must be a non-empty string")
# Нормализация SSH-формата: git@github.com:owner/repo -> https://github.com/owner/repo
if re.match(r"^git@", url):
url = re.sub(r"^git@([^:]+):", r"https://\1/", url)
parsed = urlparse(url)
# Разбиваем путь на сегменты, убирая пустые строки (от слешей)
segments = [s for s in parsed.path.split("/") if s]
if len(segments) < 2:
raise ValueError(f"Cannot extract owner/repo from URL: {url}")
owner = segments[0]
# Убираем .git только в конце строки
repo = re.sub(r"\.git$", "", segments[1])
return owner, repo
def get_repo_tree(owner: str, repo: str, max_depth: int = 2) -> list[dict]:
"""
Получает дерево файлов репозитория.
Возвращает только blob-файлы (без директорий), прошедшие все фильтры.
"""
headers = get_github_headers()
binary_extensions = (
'.exe', '.dll', '.so', '.a', '.lib', '.dylib', '.o', '.obj',
'.zip', '.tar', '.gz', '.rar', '.7z', '.pdf', '.doc', '.docx',
'.png', '.jpg', '.jpeg', '.gif', '.mp3', '.mp4', '.iso', '.db',
'.sqlite', '.jar', '.class', '.pyc', '.whl', '.ds_store', '.svg',
'.woff', '.woff2', '.ttf', '.eot', '.ico', '.lockb',
)
url = f"https://api.github.com/repos/{owner}/{repo}/git/trees/HEAD?recursive=1"
try:
response = requests.get(url, headers=headers)
response.raise_for_status()
except HTTPError as e:
if e.response.status_code == 409:
logger.debug("[%s/%s] Репозиторий пустой (409 Conflict), возвращаем []", owner, repo)
return []
raise
data = response.json()
tree = data.get("tree", [])
logger.debug(
"[%s/%s] Получено записей от API: %d (truncated=%s)",
owner, repo, len(tree), data.get("truncated", False)
)
if data.get("truncated"):
warnings.warn(
f"GitHub API вернул неполное дерево для {owner}/{repo} "
f"(более 100 000 файлов или >7 MB). "
f"Используйте нерекурсивный обход поддеревьев для полного результата.",
RuntimeWarning,
stacklevel=2,
)
filtered_tree = []
excluded_tree = [] # (путь, причина)
for item in tree:
depth = item["path"].count("/")
if depth >= max_depth:
excluded_tree.append((item["path"], f"depth={depth} >= max_depth={max_depth}"))
continue
if item["type"] != "blob":
excluded_tree.append((item["path"], f"type={item['type']}"))
continue
path_lower = item["path"].lower()
if path_lower.endswith(binary_extensions) or path_lower.endswith("package-lock.json"):
excluded_tree.append((item["path"], "binary/irrelevant extension"))
continue
filtered_tree.append(item)
# --- Итоговый дамп ---
logger.debug(
"[%s/%s] Итого после фильтрации: %d файлов (исключено: %d)",
owner, repo, len(filtered_tree), len(excluded_tree)
)
if excluded_tree:
excluded_lines = "\n".join(f" - {path} [{reason}]" for path, reason in excluded_tree)
logger.debug("[%s/%s] Исключённые записи:\n%s", owner, repo, excluded_lines)
if filtered_tree:
included_lines = "\n".join(f" + {item['path']}" for item in filtered_tree)
logger.debug("[%s/%s] Включённые файлы:\n%s", owner, repo, included_lines)
return filtered_tree
def get_readme(owner, repo):
"""Получает содержимое README.md если есть"""
headers = get_github_headers()
for readme_name in ["README.md", "readme.md", "Readme.md", "README"]:
url = f"https://api.github.com/repos/{owner}/{repo}/contents/{readme_name}"
response = requests.get(url, headers=headers)
if response.status_code == 200:
content = response.json().get("content", "")
return base64.b64decode(content).decode("utf-8")
return None
def get_file_content(owner, repo, file_path):
"""Получает содержимое конкретного файла"""
headers = get_github_headers()
url = f"https://api.github.com/repos/{owner}/{repo}/contents/{file_path}"
response = requests.get(url, headers=headers)
response.raise_for_status()
content = response.json().get("content", "")
return base64.b64decode(content).decode("utf-8")
def analyze_repo_structure(owner, repo, tree, readme):
"""Анализирует структуру и выбирает важные файлы"""
tree_text = "\n".join([f"{item['type']}: {item['path']}" for item in tree])
# 1. Инициализируем парсер с нашей схемой
parser = JsonOutputParser(pydantic_object=ImportantFilesSchema)
# 2. Создаем шаблон, куда LangChain сам вставит требования к JSON
prompt = PromptTemplate(
template="""You are analyzing a GitHub repository structure.
Repository tree (depth up to 2):
{tree_text}
README content:
{readme}
Based on this structure and README, select up to 6 most valuable files that would help understand:
1. What this project does
2. How it works
3. Its architecture and main components
CRITICAL INSTRUCTIONS FOR FILE PATHS:
- You MUST copy the file paths EXACTLY as they appear in the "Repository tree" list above.
- DO NOT modify, shorten, or guess file paths.
- DO NOT remove prefixes like 'src/', 'lib/', or 'app/'.
- If the tree shows "src/requests/api.py", you must return exactly "src/requests/api.py".
- Select only files (not directories). Prioritize configuration files, entry points, and core source files.
{format_instructions}""",
input_variables=["tree_text", "readme"],
partial_variables={"format_instructions": parser.get_format_instructions()},
)
# 3. Собираем пайплайн: Промпт -> LLM -> Парсер
chain = prompt | llm | parser
try:
# Вызываем цепочку. На выходе сразу получаем Python-словарь!
result = chain.invoke({
"tree_text": tree_text,
"readme": readme if readme else "No README found."
})
logger.debug("=== PARSED LLM RESPONSE (FILES) ===")
logger.debug(result)
logger.debug("===================================")
# Парсер вернет словарь вида {"files": ["path1", "path2"]},
# возвращаем только список, чтобы не сломать вашу логику дальше
return result["files"]
except Exception as e:
logger.error(f"Failed to parse files JSON: {e}")
raise ValueError("Could not extract valid JSON array of files from LLM response")
def generate_repo_summary(owner, repo, tree, readme, important_files, MAX_CHARS_PER_FILE = 10000):
"""Генерирует summary репозитория"""
files_content = {}
for file_path in important_files:
try:
content = get_file_content(owner, repo, file_path)
files_content[file_path] = content
except Exception as e:
# Заменил print на logger
logger.warning(f"Warning: Could not fetch {file_path}: {e}")
tree_text = "\n".join([f"{item['type']}: {item['path']}" for item in tree])
# 10000 symbols is Около 2500 токенов на файл максимум
files_text = ""
for path, content in files_content.items():
# Если файл огромный, берем только начало и конец (или просто начало)
if len(content) > MAX_CHARS_PER_FILE:
content = content[:MAX_CHARS_PER_FILE] + "\n\n... [CONTENT TRUNCATED DUE TO SIZE] ..."
files_text += f"\n\n=== FILE: {path} ===\n{content}\n"
# 1. Инициализируем парсер
parser = JsonOutputParser(pydantic_object=RepoSummarySchema)
# 2. Создаем шаблон
prompt = PromptTemplate(
template="""Analyze this GitHub repository and provide a structured summary.
Repository tree:
{tree_text}
README:
{readme}
Key files content:
{files_text}
{format_instructions}""",
input_variables=["tree_text", "readme", "files_text"],
partial_variables={"format_instructions": parser.get_format_instructions()},
)
# 3. Собираем пайплайн
chain = prompt | llm | parser
try:
# 4. Вызываем и сразу получаем валидный словарь
result = chain.invoke({
"tree_text": tree_text,
"readme": readme if readme else "No README found.",
"files_text": files_text
})
logger.debug("=== PARSED LLM RESPONSE (SUMMARY) ===")
logger.debug(result)
logger.debug("=====================================")
return result
except Exception as e:
logger.error(f"Failed to parse summary JSON: {e}")
raise ValueError("Could not extract valid JSON object from LLM response")
@app.route('/summarize', methods=['POST'])
def summarize():
"""
POST /summarize
Принимает GitHub URL и возвращает summary репозитория
"""
try:
# Получаем данные из запроса
data = request.get_json()
if not data or 'github_url' not in data:
# ИСПРАВЛЕНО: строка 327 - изменён формат ошибки с {"error": ...} на {"status": "error", "message": ...}
return jsonify({
"status": "error",
"message": "Missing required field: github_url"
}), 400
github_url = data['github_url']
# Парсим URL
try:
owner, repo = parse_github_url(github_url)
except ValueError as e:
# ИСПРАВЛЕНО: строка 338 - изменён формат ошибки с {"error": ...} на {"status": "error", "message": ...}
return jsonify({
"status": "error",
"message": str(e)
}), 400
# Получаем дерево и README
tree = get_repo_tree(owner, repo, max_depth=2)
readme = get_readme(owner, repo)
# Анализируем структуру
important_files = analyze_repo_structure(owner, repo, tree, readme)
# Генерируем summary
summary_data = generate_repo_summary(owner, repo, tree, readme, important_files)
return jsonify(summary_data), 200
except requests.exceptions.HTTPError as e:
# ИСПРАВЛЕНО: строка 359 - изменён формат ошибки с {"error": ...} на {"status": "error", "message": ...}
return jsonify({
"status": "error",
"message": f"GitHub API error: {str(e)}"
}), 502
except json.JSONDecodeError as e:
# ИСПРАВЛЕНО: строка 366 - изменён формат ошибки с {"error": ...} на {"status": "error", "message": ...}
return jsonify({
"status": "error",
"message": f"Failed to parse LLM response: {str(e)}"
}), 500
except Exception as e:
# ИСПРАВЛЕНО: строка 373 - изменён формат ошибки с {"error": ...} на {"status": "error", "message": ...}
return jsonify({
"status": "error",
"message": f"Internal server error: {str(e)}"
}), 500
@app.route('/health', methods=['GET'])
def health():
"""Health check endpoint"""
return jsonify({"status": "ok"}), 200
if __name__ == '__main__':
if not GITHUB_TOKEN:
logging.warning("⚠️ Warning: GITHUB_TOKEN not set. API rate limit: 60 requests/hour")
else:
logging.info("✓ GitHub token loaded. API rate limit: 5000 requests/hour")
app.run(debug=False, host='0.0.0.0', port=8000)