Files
anorandClaude Opus 4.8 7cd7049e1c feat: учёт неполных лекций — Фаза 0 идёт фоном
Каталоги фрагментов появляются раньше транскриптов: лекция получает
признак полноты (28 из 54 сейчас частичные). Извлечение по умолчанию
берёт только полные (--allow-partial для остальных); лекция, выросшая
новыми фрагментами с прошлого прогона, переизвлекается автоматически.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 14:39:44 +10:00

94 lines
4.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Фаза 1 — извлечение карточек знаний из транскриптов.
Запуск из корня проекта (нужен ANTHROPIC_API_KEY в .env):
python scripts/build_knowledge.py --source manual --limit 1 # пример
python scripts/build_knowledge.py --lecture "1.5" # по подстроке id
python scripts/build_knowledge.py --dry-run # без API: что и сколько
Выход: data/knowledge/<лекция>.json (карточки + usage) — версионируется в git.
"""
import argparse
import json
import re
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # корень в путь
from rag import config, corpus # noqa: E402
from rag.extract import extract # noqa: E402
def _safe_name(lecture_id: str) -> str:
return re.sub(r'[/\\:*?"<>|]', "_", lecture_id)[:150]
def main() -> int:
ap = argparse.ArgumentParser(description="Фаза 1: транскрипт → карточки знаний")
ap.add_argument("--limit", type=int, default=0, help="сколько лекций (0 = все)")
ap.add_argument("--source", choices=["all", "mass", "manual"], default="all")
ap.add_argument("--lecture", default="", help="фильтр по подстроке id лекции")
ap.add_argument("--dry-run", action="store_true", help="показать план без вызовов API")
ap.add_argument("--force", action="store_true", help="перезаписать готовые карточки")
ap.add_argument("--allow-partial", action="store_true",
help="извлекать и из частично разобранных лекций (Фаза 0 идёт)")
args = ap.parse_args()
items = [lec for lec in corpus.iter_lectures()
if (args.source == "all" or lec.source == args.source)
and (not args.lecture or args.lecture.lower() in lec.id.lower())]
if not args.allow_partial:
partial = [lec for lec in items if not lec.complete]
items = [lec for lec in items if lec.complete]
if partial:
print(f"Пропущено ЧАСТИЧНЫХ лекций: {len(partial)} (разбор идёт; "
f"--allow-partial чтобы взять как есть)")
if args.limit:
items = items[: args.limit]
print(f"К обработке: {len(items)} лекций (source={args.source})")
if args.dry_run:
for lec in items:
print(f" [{lec.source}] {lec.id} — {len(lec.fragments)} фрагм., "
f"{len(lec.load_text())} симв.")
return 0
config.KNOWLEDGE_DIR.mkdir(parents=True, exist_ok=True)
total_cost = 0.0
for lec in items:
out_path = config.KNOWLEDGE_DIR / f"{_safe_name(lec.id)}.json"
fragment_ids = [f.id for f in lec.fragments]
if out_path.exists() and not args.force:
# лекция могла дорасти новыми фрагментами с прошлого прогона —
# тогда карточки устарели и переизвлекаются
old = json.loads(out_path.read_text(encoding="utf-8"))
if old.get("_fragments") == fragment_ids:
print(f" пропуск (готово): {lec.id}")
continue
print(f" лекция выросла ({len(old.get('_fragments', []))}→"
f"{len(fragment_ids)} фрагм.) — переизвлечение: {lec.id}")
print(f" извлечение: {lec.id} ({len(lec.fragments)} фрагм.) …", flush=True)
result, usage = extract.extract_lecture(lec)
payload = result.model_dump()
payload["_fragments"] = fragment_ids
payload["_complete"] = lec.complete
payload["_usage"] = {
"input_tokens": usage.input_tokens,
"output_tokens": usage.output_tokens,
"cache_read_tokens": usage.cache_read_tokens,
"cost_usd": round(usage.cost_usd, 4),
"model": extract.MODEL,
}
out_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2),
encoding="utf-8")
total_cost += usage.cost_usd
print(f" карточек: {len(result.cards)}, токены {usage.input_tokens}→"
f"{usage.output_tokens}, ${usage.cost_usd:.3f} → {out_path.name}")
print(f"\nИтого стоимость прогона: ${total_cost:.3f}")
return 0
if __name__ == "__main__":
raise SystemExit(main())