messages.parse() с pydantic-схемой (валидация на клиенте), adaptive thinking, кэш system-промпта, замер usage и стоимости на лекцию. CLI build_knowledge.py: --source/--limit/--lecture/--dry-run/--force, выход в data/knowledge/<лекция>.json. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
77 lines
3.4 KiB
Python
77 lines
3.4 KiB
Python
#!/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="перезаписать готовые карточки")
|
||
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 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"
|
||
if out_path.exists() and not args.force:
|
||
print(f" пропуск (готово): {lec.id}")
|
||
continue
|
||
print(f" извлечение: {lec.id} ({len(lec.fragments)} фрагм.) …", flush=True)
|
||
result, usage = extract.extract_lecture(lec)
|
||
payload = result.model_dump()
|
||
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())
|