chore: удалены мёртвые файлы (fix_*, services/grid_generator, word_bank) + code_summary.py (22.09.2026)
This commit is contained in:
@@ -1,43 +0,0 @@
|
|||||||
with open('routers/learning.py', 'r') as f:
|
|
||||||
content = f.read()
|
|
||||||
|
|
||||||
# Добавляем regex для удаления технических ID
|
|
||||||
content = content.replace(
|
|
||||||
''' data = response.json()
|
|
||||||
ai_response = data["choices"][0]["message"]["content"].strip()
|
|
||||||
ai_response = ai_response.replace("**", "").replace("*", "").replace("#", "")
|
|
||||||
|
|
||||||
return {"analytics_enabled": True, "response": ai_response}''',
|
|
||||||
''' data = response.json()
|
|
||||||
ai_response = data["choices"][0]["message"]["content"].strip()
|
|
||||||
ai_response = ai_response.replace("**", "").replace("*", "").replace("#", "")
|
|
||||||
|
|
||||||
# Убираем технические ID в скобках: (self_intro), (family_masz_mam) и т.д.
|
|
||||||
import re
|
|
||||||
ai_response = re.sub(r'\\s*\\([a-z_]+_[a-z_]+\\)', '', ai_response)
|
|
||||||
|
|
||||||
return {"analytics_enabled": True, "response": ai_response}'''
|
|
||||||
)
|
|
||||||
|
|
||||||
# Убираем из промпта упоминание процента завершения уровня (правило 12)
|
|
||||||
content = content.replace(
|
|
||||||
'''12. ВАЖНО: level_completion_percent показывает сколько тем пройдено из ВСЕГО уровня (A1 = 30+ тем). Если пройдено 5 тем из 30+ — это только начало (около 16%), а не "почти готово". НЕ говори что уровень почти завершён, если пройдено меньше 100%.
|
|
||||||
''',
|
|
||||||
'''12. ВАЖНО: НИКОГДА не упоминай процент завершения уровня, количество пройденных тем или сколько тем осталось. Не говори "ты прошёл X тем" или "осталось Y тем". Просто анализируй навыки.
|
|
||||||
'''
|
|
||||||
)
|
|
||||||
|
|
||||||
# Убираем из user_prompt пункт про прогресс
|
|
||||||
content = content.replace(
|
|
||||||
'''5. Твой общий прогресс и мотивация
|
|
||||||
|
|
||||||
В конце напиши: "Жду тебя в разделе Повторение!\\""""''',
|
|
||||||
'''5. Твоя мотивация (без упоминания процентов и количества тем)
|
|
||||||
|
|
||||||
В конце напиши: "Жду тебя в разделе Повторение!\\""""'''
|
|
||||||
)
|
|
||||||
|
|
||||||
with open('routers/learning.py', 'w') as f:
|
|
||||||
f.write(content)
|
|
||||||
|
|
||||||
print("learning.py fixed!")
|
|
||||||
@@ -1,135 +0,0 @@
|
|||||||
"""
|
|
||||||
Патч: исправляет колонку text_pl в question_options там, где при заполнении
|
|
||||||
контента по ошибке продублировали русский перевод вместо настоящей польской
|
|
||||||
фразы (вопросы типа "Co oznacza / Co znaczy ...?").
|
|
||||||
|
|
||||||
Затронуто 12 question_id по темам: greetings, family, food, home,
|
|
||||||
numbers_time (3 шт.), colors_clothes, weather_seasons.
|
|
||||||
|
|
||||||
Запуск на сервере:
|
|
||||||
python3 fix_polish_options.py
|
|
||||||
Требует переменную DB_CONFIG из config.py (как остальные твои скрипты).
|
|
||||||
|
|
||||||
Скрипт идемпотентен: можно запускать повторно, ничего не сломает —
|
|
||||||
он просто перезапишет text_pl тем же корректным значением.
|
|
||||||
"""
|
|
||||||
import asyncio
|
|
||||||
import asyncpg
|
|
||||||
from config import DB_CONFIG
|
|
||||||
|
|
||||||
|
|
||||||
# Каждая запись: (question_id, option_key, правильный польский текст)
|
|
||||||
FIXES = [
|
|
||||||
# ==================== Тема 1: Greetings ====================
|
|
||||||
("a1_greetings_t09", "A", "Jak się nazywasz?"),
|
|
||||||
("a1_greetings_t09", "B", "Jak się masz?"),
|
|
||||||
("a1_greetings_t09", "C", "Gdzie mieszkasz?"),
|
|
||||||
("a1_greetings_t09", "D", "Do widzenia."),
|
|
||||||
|
|
||||||
# ==================== Тема 3: Family ====================
|
|
||||||
# Один и тот же набор опций встречается в уроке и в тесте
|
|
||||||
("a1_family_l07_q1", "A", "Masz siostrę?"),
|
|
||||||
("a1_family_l07_q1", "B", "Czy to jest twoja siostra?"),
|
|
||||||
("a1_family_l07_q1", "C", "Jesteś siostrą?"),
|
|
||||||
("a1_family_l07_q1", "D", "Gdzie jest twoja siostra?"),
|
|
||||||
|
|
||||||
("a1_family_t06", "A", "Masz siostrę?"),
|
|
||||||
("a1_family_t06", "B", "Czy to jest twoja siostra?"),
|
|
||||||
("a1_family_t06", "C", "Jesteś siostrą?"),
|
|
||||||
("a1_family_t06", "D", "Gdzie jest twoja siostra?"),
|
|
||||||
|
|
||||||
# ==================== Тема 4: Food ====================
|
|
||||||
("a1_food_l08_q1", "A", "Co jesz na śniadanie?"),
|
|
||||||
("a1_food_l08_q1", "B", "Co pijesz rano?"),
|
|
||||||
("a1_food_l08_q1", "C", "Kiedy jesz śniadanie?"),
|
|
||||||
("a1_food_l08_q1", "D", "Czy lubisz śniadanie?"),
|
|
||||||
|
|
||||||
# ==================== Тема 5: Home ====================
|
|
||||||
("a1_home_l09_q1", "A", "Ile masz pokoi?"),
|
|
||||||
("a1_home_l09_q1", "B", "Gdzie jest twój pokój?"),
|
|
||||||
("a1_home_l09_q1", "C", "Czy podoba ci się twój pokój?"),
|
|
||||||
("a1_home_l09_q1", "D", "Jaki jest twój pokój?"),
|
|
||||||
|
|
||||||
# ==================== Тема 6: Numbers/Time ====================
|
|
||||||
("a1_numbers_time_l05_q1", "A", "Która godzina?"),
|
|
||||||
("a1_numbers_time_l05_q1", "B", "Jaki dziś dzień?"),
|
|
||||||
("a1_numbers_time_l05_q1", "C", "Ile masz lat?"),
|
|
||||||
("a1_numbers_time_l05_q1", "D", "Gdzie jesteś?"),
|
|
||||||
|
|
||||||
("a1_numbers_time_t04", "A", "Która godzina?"),
|
|
||||||
("a1_numbers_time_t04", "B", "Jaki dziś dzień?"),
|
|
||||||
("a1_numbers_time_t04", "C", "Ile masz lat?"),
|
|
||||||
("a1_numbers_time_t04", "D", "Gdzie jesteś?"),
|
|
||||||
|
|
||||||
("a1_numbers_time_l06_q1", "A", "za piętnaście piąta"),
|
|
||||||
("a1_numbers_time_l06_q1", "B", "kwadrans po czwartej"),
|
|
||||||
("a1_numbers_time_l06_q1", "C", "wpół do piątej"),
|
|
||||||
("a1_numbers_time_l06_q1", "D", "dokładnie piąta"),
|
|
||||||
|
|
||||||
("a1_numbers_time_l07_q1", "A", "O której godzinie?"),
|
|
||||||
("a1_numbers_time_l07_q1", "B", "Która godzina?"),
|
|
||||||
("a1_numbers_time_l07_q1", "C", "Jaki dziś dzień?"),
|
|
||||||
("a1_numbers_time_l07_q1", "D", "Jak długo?"),
|
|
||||||
|
|
||||||
("a1_numbers_time_t05", "A", "O której godzinie?"),
|
|
||||||
("a1_numbers_time_t05", "B", "Która godzina?"),
|
|
||||||
("a1_numbers_time_t05", "C", "Jaki dziś dzień?"),
|
|
||||||
("a1_numbers_time_t05", "D", "Jak długo?"),
|
|
||||||
|
|
||||||
# ==================== Тема 7: Colors/Clothes ====================
|
|
||||||
("a1_colors_clothes_l09_q1", "A", "Jakiego koloru jest...?"),
|
|
||||||
("a1_colors_clothes_l09_q1", "B", "Która godzina jest...?"),
|
|
||||||
("a1_colors_clothes_l09_q1", "C", "Ile kosztuje...?"),
|
|
||||||
("a1_colors_clothes_l09_q1", "D", "Gdzie jest...?"),
|
|
||||||
|
|
||||||
("a1_colors_clothes_t06", "A", "Jakiego koloru jest...?"),
|
|
||||||
("a1_colors_clothes_t06", "B", "Która godzina jest...?"),
|
|
||||||
("a1_colors_clothes_t06", "C", "Ile kosztuje...?"),
|
|
||||||
("a1_colors_clothes_t06", "D", "Gdzie jest...?"),
|
|
||||||
|
|
||||||
# ==================== Тема 8: Weather/Seasons ====================
|
|
||||||
("a1_weather_seasons_l09_q1", "A", "Jutro będzie padać deszcz."),
|
|
||||||
("a1_weather_seasons_l09_q1", "B", "Wczoraj padał deszcz."),
|
|
||||||
("a1_weather_seasons_l09_q1", "C", "Dziś pada deszcz."),
|
|
||||||
("a1_weather_seasons_l09_q1", "D", "Jutro będzie zimno."),
|
|
||||||
|
|
||||||
("a1_weather_seasons_t06", "A", "Jutro będzie padać deszcz."),
|
|
||||||
("a1_weather_seasons_t06", "B", "Wczoraj padał deszcz."),
|
|
||||||
("a1_weather_seasons_t06", "C", "Dziś pada deszcz."),
|
|
||||||
("a1_weather_seasons_t06", "D", "Jutro będzie zimno."),
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
async def main():
|
|
||||||
pool = await asyncpg.create_pool(**DB_CONFIG)
|
|
||||||
updated = 0
|
|
||||||
not_found = []
|
|
||||||
|
|
||||||
async with pool.acquire() as conn:
|
|
||||||
for question_id, option_key, correct_pl in FIXES:
|
|
||||||
result = await conn.execute("""
|
|
||||||
UPDATE question_options
|
|
||||||
SET text_pl = $3
|
|
||||||
WHERE question_id = $1 AND option_key = $2
|
|
||||||
""", question_id, option_key, correct_pl)
|
|
||||||
|
|
||||||
# asyncpg возвращает строку вида "UPDATE 1" или "UPDATE 0"
|
|
||||||
affected = int(result.split()[-1])
|
|
||||||
if affected == 0:
|
|
||||||
not_found.append((question_id, option_key))
|
|
||||||
else:
|
|
||||||
updated += affected
|
|
||||||
|
|
||||||
await pool.close()
|
|
||||||
|
|
||||||
print(f"✅ Обновлено записей: {updated} из {len(FIXES)}")
|
|
||||||
if not_found:
|
|
||||||
print(f"⚠️ Не найдено в БД (проверь question_id/option_key вручную):")
|
|
||||||
for qid, key in not_found:
|
|
||||||
print(f" - {qid} / {key}")
|
|
||||||
else:
|
|
||||||
print("🎉 Все записи найдены и обновлены.")
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
asyncio.run(main())
|
|
||||||
-113
@@ -1,113 +0,0 @@
|
|||||||
import re
|
|
||||||
|
|
||||||
with open('routers/review.py', 'r') as f:
|
|
||||||
content = f.read()
|
|
||||||
|
|
||||||
# Полный SKILL_TAG_DESCRIPTION (как в learning.py)
|
|
||||||
full_skill_tags = '''# Понятные названия навыков
|
|
||||||
SKILL_TAG_DESCRIPTION = """
|
|
||||||
Понятные названия навыков (используй ИХ в ответе, а не технические ID):
|
|
||||||
- family_vocabulary → "слова по теме «Семья»"
|
|
||||||
- family_possessive → "мой/моя (mój/moja)"
|
|
||||||
- family_accusative → "винительный падеж (mam brata, mam siostrę)"
|
|
||||||
- family_questions → "вопросы о семье (Masz brata?)"
|
|
||||||
- family_description → "рассказ о семье"
|
|
||||||
- family_babcia_dziadek → "бабушка и дедушка"
|
|
||||||
- family_brat_siostra → "брат и сестра"
|
|
||||||
- family_masz_mam → "у меня есть / у тебя есть"
|
|
||||||
- family_duza_mala → "большая/маленькая семья"
|
|
||||||
- family_mama_tata → "мама и папа"
|
|
||||||
- family_maz_zona → "муж и жена"
|
|
||||||
- family_dzieci → "дети"
|
|
||||||
- family_wujek_ciocia → "дядя и тётя"
|
|
||||||
- family_kto_to_jest → "вопрос «Кто это?»"
|
|
||||||
- asking_name → "вопрос «Как тебя зовут?»"
|
|
||||||
- answering_name → "ответ на вопрос об имени"
|
|
||||||
- formal_address_pan_pani → "вежливое обращение Pan/Pani"
|
|
||||||
- greeting_formal → "формальные приветствия"
|
|
||||||
- greeting_informal → "неформальные приветствия"
|
|
||||||
- asking_origin → "вопрос «Откуда ты?»"
|
|
||||||
- answering_origin → "ответ о происхождении"
|
|
||||||
- asking_residence → "вопрос «Где ты живёшь?»"
|
|
||||||
- answering_residence → "ответ о месте жительства"
|
|
||||||
- self_description → "рассказ о себе"
|
|
||||||
- self_intro → "представление себя"
|
|
||||||
- how_are_you → "вопрос «Как дела?»"
|
|
||||||
- responding_how_are_you → "ответ на «Как дела?»"
|
|
||||||
- farewell_formal → "формальные прощания"
|
|
||||||
- farewell_informal → "неформальные прощания"
|
|
||||||
- mieszkac_conjugation → "спряжение глагола mieszkać"
|
|
||||||
- skad_vs_gdzie → "разница между Skąd и Gdzie"
|
|
||||||
- country_vocabulary → "названия стран"
|
|
||||||
- nationality_forms → "национальности"
|
|
||||||
- city_vocabulary → "названия городов"
|
|
||||||
- food_vocabulary → "слова по теме «Еда»"
|
|
||||||
- food_fruits_vegetables → "фрукты и овощи"
|
|
||||||
- food_drinks → "напитки"
|
|
||||||
- food_meals → "приёмы пищи"
|
|
||||||
- food_lubie → "глагол lubić (любить)"
|
|
||||||
- home_vocabulary → "слова по теме «Дом»"
|
|
||||||
- home_furniture → "мебель"
|
|
||||||
- home_location → "предлоги места (w, na)"
|
|
||||||
- home_ownership → "mam dom, mam mieszkanie"
|
|
||||||
- home_description → "описание дома/квартиры"
|
|
||||||
|
|
||||||
НИКОГДА не пиши технические ID навыков в ответе. Всегда заменяй их на понятные названия из списка выше.
|
|
||||||
"""'''
|
|
||||||
|
|
||||||
# Заменяем короткий SKILL_TAG_DESCRIPTION на полный
|
|
||||||
content = re.sub(
|
|
||||||
r'# Понятные названия навыков\nSKILL_TAG_DESCRIPTION = """.*?"""',
|
|
||||||
full_skill_tags,
|
|
||||||
content,
|
|
||||||
flags=re.DOTALL
|
|
||||||
)
|
|
||||||
|
|
||||||
# Добавляем attempts_count >= 2 в SQL
|
|
||||||
content = content.replace(
|
|
||||||
''' WHERE user_id = $1
|
|
||||||
AND (
|
|
||||||
mastery_score < 75
|
|
||||||
OR retention_status IN ('needs_review', 'overdue')
|
|
||||||
OR repeated_error_count > 0
|
|
||||||
)''',
|
|
||||||
''' WHERE user_id = $1
|
|
||||||
AND attempts_count >= 2
|
|
||||||
AND (
|
|
||||||
mastery_score < 75
|
|
||||||
OR retention_status IN ('needs_review', 'overdue')
|
|
||||||
OR repeated_error_count > 0
|
|
||||||
)'''
|
|
||||||
)
|
|
||||||
|
|
||||||
# Добавляем regex для удаления технических ID
|
|
||||||
content = content.replace(
|
|
||||||
''' data = response.json()
|
|
||||||
review_text = data["choices"][0]["message"]["content"].strip()
|
|
||||||
review_text = review_text.replace("**", "").replace("*", "").replace("#", "")''',
|
|
||||||
''' data = response.json()
|
|
||||||
review_text = data["choices"][0]["message"]["content"].strip()
|
|
||||||
review_text = review_text.replace("**", "").replace("*", "").replace("#", "")
|
|
||||||
|
|
||||||
# Убираем технические ID в скобках
|
|
||||||
import re
|
|
||||||
review_text = re.sub(r'\\s*\\([a-z_]+_[a-z_]+\\), '', review_text)'''
|
|
||||||
)
|
|
||||||
|
|
||||||
# Добавляем правила в промпт
|
|
||||||
content = content.replace(
|
|
||||||
'''5. Каждый мини-урок: правило + 2 примера + 1 задание
|
|
||||||
6. Не пиши технические ID навыков — используй понятные названия
|
|
||||||
7. Будь дружелюбным и мотивирующим"""''',
|
|
||||||
'''5. Каждый мини-урок: правило + 2 примера + 1 задание
|
|
||||||
6. Не пиши технические ID навыков — используй понятные названия
|
|
||||||
7. Будь дружелюбным и мотивирующим
|
|
||||||
8. ВАЖНО: Никогда не давай готовый ответ на задание в том же сообщении. Задание должно оставаться открытым.
|
|
||||||
9. ВАЖНО: В списках слов-подсказок используй только польские слова, без смешения языков.
|
|
||||||
10. ВАЖНО: Если mastery >= 75 и навык включён из-за retention_status (needs_review/overdue) — формулируй как "быстрое освежение", а не "давай разберём с нуля"."""'''
|
|
||||||
)
|
|
||||||
|
|
||||||
with open('routers/review.py', 'w') as f:
|
|
||||||
f.write(content)
|
|
||||||
|
|
||||||
print("review.py fixed!")
|
|
||||||
@@ -0,0 +1,268 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""
|
||||||
|
Code Summary — сводка по коду проекта Filwords PL.
|
||||||
|
|
||||||
|
Проходит по всем .py (backend) или .ts/.tsx (frontend) файлам,
|
||||||
|
вытаскивает docstring, функции, классы, импорты.
|
||||||
|
Формирует .md файл для быстрого ознакомления.
|
||||||
|
|
||||||
|
(22.09.2026) Первая версия. Без AI — только парсинг.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import ast
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from datetime import datetime
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
|
# ============ Настройки ============
|
||||||
|
|
||||||
|
IGNORE_DIRS = {
|
||||||
|
"venv", ".venv", "__pycache__", ".git", ".gitea",
|
||||||
|
"node_modules", "dist", "build", ".vite", "coverage",
|
||||||
|
"archive", "uploads", "tts_cache", ".cache", "public",
|
||||||
|
}
|
||||||
|
|
||||||
|
# Большие файлы контента (не код) — пропускаем
|
||||||
|
IGNORE_FILES = {
|
||||||
|
"level_a1.py", "level_a2.py", "level_b1.py", "level_b2.py",
|
||||||
|
"level_c1.py", "level_c2.py",
|
||||||
|
}
|
||||||
|
|
||||||
|
# Максимальный размер файла для парсинга
|
||||||
|
MAX_FILE_SIZE = 100_000
|
||||||
|
|
||||||
|
|
||||||
|
# ============ Парсер Python ============
|
||||||
|
|
||||||
|
def parse_python(path: Path, repo_root: Path) -> dict | None:
|
||||||
|
"""Парсит один .py файл. Возвращает dict со сводкой или None."""
|
||||||
|
try:
|
||||||
|
content = path.read_text(encoding="utf-8")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"⚠️ Не прочитал {path}: {e}", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
|
||||||
|
if len(content) > MAX_FILE_SIZE:
|
||||||
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
|
tree = ast.parse(content)
|
||||||
|
except SyntaxError as e:
|
||||||
|
print(f"⚠️ Синтаксис {path}: {e}", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Docstring модуля
|
||||||
|
module_doc = ast.get_docstring(tree) or ""
|
||||||
|
first_line = module_doc.strip().split("\n")[0] if module_doc else ""
|
||||||
|
|
||||||
|
# Функции и классы
|
||||||
|
functions: list[str] = []
|
||||||
|
classes: list[str] = []
|
||||||
|
|
||||||
|
for node in tree.body:
|
||||||
|
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
||||||
|
args = [a.arg for a in node.args.args]
|
||||||
|
functions.append(f"{node.name}({', '.join(args)})")
|
||||||
|
elif isinstance(node, ast.ClassDef):
|
||||||
|
classes.append(node.name)
|
||||||
|
|
||||||
|
# Импорты
|
||||||
|
imports: list[str] = []
|
||||||
|
for node in tree.body:
|
||||||
|
if isinstance(node, ast.Import):
|
||||||
|
for alias in node.names:
|
||||||
|
imports.append(alias.name.split(".")[0])
|
||||||
|
elif isinstance(node, ast.ImportFrom):
|
||||||
|
if node.module:
|
||||||
|
imports.append(node.module.split(".")[0])
|
||||||
|
|
||||||
|
# Топ-3 импорта
|
||||||
|
imports = list(dict.fromkeys(imports))[:5]
|
||||||
|
|
||||||
|
rel = str(path.relative_to(repo_root)).replace("\\", "/")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"path": rel,
|
||||||
|
"lang": "python",
|
||||||
|
"doc": first_line,
|
||||||
|
"functions": functions,
|
||||||
|
"classes": classes,
|
||||||
|
"imports": imports,
|
||||||
|
"lines": len(content.split("\n")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ============ Парсер TypeScript ============
|
||||||
|
|
||||||
|
def parse_typescript(path: Path, repo_root: Path) -> dict | None:
|
||||||
|
"""Парсит один .ts/.tsx файл. Возвращает dict со сводкой или None."""
|
||||||
|
try:
|
||||||
|
content = path.read_text(encoding="utf-8")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"⚠️ Не прочитал {path}: {e}", file=sys.stderr)
|
||||||
|
return None
|
||||||
|
|
||||||
|
if len(content) > MAX_FILE_SIZE:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Docstring — первая многострочная /** ... */ или // в начале
|
||||||
|
doc_match = re.match(r'^(?:/\*\*(.*?)\*/|//\s*(.+?)$)', content, re.DOTALL | re.MULTILINE)
|
||||||
|
doc = ""
|
||||||
|
if doc_match:
|
||||||
|
doc = (doc_match.group(1) or doc_match.group(2) or "").strip()
|
||||||
|
doc = doc.split("\n")[0].strip().lstrip("*").strip()
|
||||||
|
|
||||||
|
# Функции (function name, const name = () =>)
|
||||||
|
funcs = re.findall(r'(?:export\s+)?(?:async\s+)?function\s+(\w+)', content)
|
||||||
|
funcs += re.findall(r'(?:export\s+)?const\s+(\w+)\s*=\s*(?:async\s+)?\(', content)
|
||||||
|
funcs = list(dict.fromkeys(funcs))[:15] # максимум 15
|
||||||
|
|
||||||
|
# Компоненты (const Name: React.FC)
|
||||||
|
components = re.findall(r'const\s+(\w+):\s*React\.FC', content)
|
||||||
|
components = list(dict.fromkeys(components))[:15]
|
||||||
|
|
||||||
|
# Импорты — топ-5
|
||||||
|
imports_raw = re.findall(r"from\s+['\"]([^'\"]+)['\"]", content)
|
||||||
|
imports_raw = [i for i in imports_raw if not i.startswith(".")][:5]
|
||||||
|
|
||||||
|
rel = str(path.relative_to(repo_root)).replace("\\", "/")
|
||||||
|
|
||||||
|
return {
|
||||||
|
"path": rel,
|
||||||
|
"lang": "typescript",
|
||||||
|
"doc": doc,
|
||||||
|
"functions": funcs,
|
||||||
|
"classes": components, # переиспользуем поле под компоненты
|
||||||
|
"imports": imports_raw,
|
||||||
|
"lines": len(content.split("\n")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ============ Обход файлов ============
|
||||||
|
|
||||||
|
def collect_files(repo_root: Path, mode: str) -> list[Path]:
|
||||||
|
"""Собирает файлы для парсинга."""
|
||||||
|
if mode == "backend":
|
||||||
|
extensions = {".py"}
|
||||||
|
else:
|
||||||
|
extensions = {".ts", ".tsx", ".js", ".jsx"}
|
||||||
|
|
||||||
|
files: list[Path] = []
|
||||||
|
for path in sorted(repo_root.rglob("*")):
|
||||||
|
if not path.is_file():
|
||||||
|
continue
|
||||||
|
if path.suffix not in extensions:
|
||||||
|
continue
|
||||||
|
if any(part in IGNORE_DIRS for part in path.relative_to(repo_root).parts):
|
||||||
|
continue
|
||||||
|
if path.name in IGNORE_FILES:
|
||||||
|
continue
|
||||||
|
files.append(path)
|
||||||
|
return files
|
||||||
|
|
||||||
|
|
||||||
|
# ============ Формирование сводки ============
|
||||||
|
|
||||||
|
def format_summary(items: list[dict], mode: str, repo_name: str) -> str:
|
||||||
|
"""Формирует markdown-сводку."""
|
||||||
|
lines: list[str] = []
|
||||||
|
date_str = datetime.now().strftime("%Y-%m-%d %H:%M")
|
||||||
|
|
||||||
|
lines.append(f"# 📋 Code Summary — {repo_name}")
|
||||||
|
lines.append("")
|
||||||
|
lines.append(f"**Дата:** {date_str}")
|
||||||
|
lines.append(f"**Режим:** {mode}")
|
||||||
|
lines.append(f"**Файлов:** {len(items)}")
|
||||||
|
lines.append("")
|
||||||
|
lines.append("---")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
for item in items:
|
||||||
|
lines.append(f"## `{item['path']}`")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
if item["doc"]:
|
||||||
|
lines.append(f"- **Назначение:** {item['doc']}")
|
||||||
|
else:
|
||||||
|
lines.append(f"- **Назначение:** _(docstring отсутствует)_")
|
||||||
|
|
||||||
|
if item["functions"]:
|
||||||
|
lines.append(f"- **Функции:** {', '.join(item['functions'][:20])}")
|
||||||
|
if len(item["functions"]) > 20:
|
||||||
|
lines.append(f" _(+{len(item['functions']) - 20} ещё)_")
|
||||||
|
|
||||||
|
if item["classes"]:
|
||||||
|
label = "Компоненты" if mode == "frontend" else "Классы"
|
||||||
|
lines.append(f"- **{label}:** {', '.join(item['classes'][:20])}")
|
||||||
|
|
||||||
|
if item["imports"]:
|
||||||
|
lines.append(f"- **Импорты:** {', '.join(item['imports'])}")
|
||||||
|
|
||||||
|
lines.append(f"- **Строк:** {item['lines']}")
|
||||||
|
lines.append("")
|
||||||
|
|
||||||
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
# ============ Main ============
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
parser = argparse.ArgumentParser(description="Code Summary для Filwords PL")
|
||||||
|
parser.add_argument("mode", choices=["backend", "frontend"], help="Режим")
|
||||||
|
parser.add_argument(
|
||||||
|
"--path",
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help="Путь к репозиторию (по умолчанию — текущая папка)",
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"--output",
|
||||||
|
type=str,
|
||||||
|
default=None,
|
||||||
|
help="Путь к выходному .md (по умолчанию — ~/Desktop/CODE_SUMMARY_*.md)",
|
||||||
|
)
|
||||||
|
|
||||||
|
args = parser.parse_args()
|
||||||
|
|
||||||
|
repo_root = Path(args.path).resolve() if args.path else Path(".").resolve()
|
||||||
|
|
||||||
|
if not repo_root.exists():
|
||||||
|
print(f"❌ Папка не найдена: {repo_root}", file=sys.stderr)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
print(f"📁 Репозиторий: {repo_root}")
|
||||||
|
print(f"🎯 Режим: {args.mode}")
|
||||||
|
|
||||||
|
files = collect_files(repo_root, args.mode)
|
||||||
|
print(f"📂 Найдено файлов: {len(files)}")
|
||||||
|
|
||||||
|
items: list[dict] = []
|
||||||
|
for f in files:
|
||||||
|
if args.mode == "backend":
|
||||||
|
result = parse_python(f, repo_root)
|
||||||
|
else:
|
||||||
|
result = parse_typescript(f, repo_root)
|
||||||
|
if result:
|
||||||
|
items.append(result)
|
||||||
|
|
||||||
|
print(f"✅ Обработано: {len(items)}")
|
||||||
|
|
||||||
|
repo_name = repo_root.name
|
||||||
|
summary = format_summary(items, args.mode, repo_name)
|
||||||
|
|
||||||
|
if args.output:
|
||||||
|
output_path = Path(args.output)
|
||||||
|
else:
|
||||||
|
date_str = datetime.now().strftime("%Y%m%d_%H%M")
|
||||||
|
output_path = Path.home() / "Desktop" / f"CODE_SUMMARY_{args.mode.upper()}_{date_str}.md"
|
||||||
|
|
||||||
|
output_path.write_text(summary, encoding="utf-8")
|
||||||
|
print(f"💾 Сохранено: {output_path}")
|
||||||
|
print(f"📊 Размер: {len(summary):,} символов")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user