Files
romanov_btg_rag/scripts/zai_compare.py
T
anorandClaude Opus 4.8 a8a8d18f1b feat: извлечение через Z.AI (GLM) и сравнение с эталоном Opus
Anthropic-совместимый эндпоинт Z.AI; схему просим текстом (structured
output у GLM нет), pydantic-валидация + один ретрай с фидбеком ошибки.
zai_compare.py: GLM извлекает «Принцип» по сырому ASR → сравнение с
эталоном по типам карточек, битым таймкодам, покрытию 9 golden-фактов.
Выход GLM в data/eval/zai/ — базу знаний не трогает.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-05 00:40:30 +10:00

112 lines
5.7 KiB
Python

#!/usr/bin/env python3
"""Сравнение извлечения Z.AI (GLM) с эталоном Opus на лекции «Принцип».
python scripts/zai_compare.py # извлечь (если нет) и сравнить
python scripts/zai_compare.py --force # переизвлечь GLM-вариант
Эталон: data/knowledge/_Романов_принцип.json (агент Opus, проверен пилотом).
GLM-вариант: data/eval/zai/_Романов_принцип.json (в базу знаний НЕ попадает).
Решает вопрос масштабирования: можно ли отдать массовое извлечение дешёвой
модели без потери качества.
"""
import argparse
import importlib.util
import json
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 zai # noqa: E402
_spec = importlib.util.spec_from_file_location(
"quote_check", Path(__file__).parent / "quote_check.py")
quote_check = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(quote_check)
REFERENCE = config.KNOWLEDGE_DIR / "_Романов_принцип.json"
ZAI_OUT = config.EVAL_DIR / "zai" / "_Романов_принцип.json"
# Ключевые факты золотого набора из «Принципа» (видео П) — проверка по словам
GOLDEN_FACTS = {
"P1 синус-симметрия": lambda t: "синус" in t and ("туда" in t or "излишк" in t),
"P2 2Ф+АМ": lambda t: "2ф" in t or "2 ф" in t,
"P4 горячее/холодное": lambda t: "горяч" in t or "холодн" in t,
"P5 3Ф+ФМ/ЧМ": lambda t: "3ф" in t or "3 ф" in t,
"S2 стробирование питания": lambda t: "сняли" in t or "гейтир" in t or "строб" in t,
"S3 приёмник-детектор": lambda t: "детектор" in t,
"N6 несущая 200-400 + IR2153": lambda t: ("200" in t or "300" in t) and "ir2153" in t.replace(" ", ""),
"T1 ΔU/рыбки": lambda t: "рыбк" in t or "δ" in t or "дельта" in t,
"A3 добротность сама-на-себя": lambda t: "добротн" in t,
}
def describe(path: Path) -> dict:
data = json.loads(path.read_text(encoding="utf-8"))
by_type: dict[str, int] = {}
n_sources = 0
flagged = 0
for c in data["cards"]:
by_type[c["type"]] = by_type.get(c["type"], 0) + 1
n_sources += len(c["sources"])
flagged += bool(c.get("needs_frame_check"))
text = " ".join(json.dumps(c, ensure_ascii=False) for c in data["cards"]).lower()
golden = {name: check(text) for name, check in GOLDEN_FACTS.items()}
qc = quote_check.check_file(path)
return {"cards": len(data["cards"]), "by_type": by_type, "sources": n_sources,
"frame_check": flagged, "golden": golden, "qc": qc,
"usage": data.get("_usage", {})}
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--force", action="store_true")
args = ap.parse_args()
lecture = next(lec for lec in corpus.iter_lectures()
if lec.id == "_Романов_принцип")
if args.force or not ZAI_OUT.exists():
print(f"Извлечение GLM ({config.ZAI_MODEL}) из «Принципа»…", flush=True)
result, usage = zai.extract_lecture_zai(lecture)
payload = result.model_dump()
payload["_fragments"] = ["_Романов_принцип"]
payload["_extractor"] = f"zai/{config.ZAI_MODEL}"
payload["_usage"] = {"input_tokens": usage.input_tokens,
"output_tokens": usage.output_tokens,
"cost_usd": round(usage.cost_usd, 4),
"retries": usage.retries}
ZAI_OUT.parent.mkdir(parents=True, exist_ok=True)
ZAI_OUT.write_text(json.dumps(payload, ensure_ascii=False, indent=2),
encoding="utf-8")
print(f" токены {usage.input_tokens}→{usage.output_tokens}, "
f"${usage.cost_usd:.4f}, ретраев {usage.retries}")
ref, cand = describe(REFERENCE), describe(ZAI_OUT)
print(f"\n{'':38} {'Opus (эталон)':>15} {'GLM':>15}")
print(f"{'карточек всего':38} {ref['cards']:>15} {cand['cards']:>15}")
types = sorted(set(ref["by_type"]) | set(cand["by_type"]))
for t in types:
print(f"{' ' + t:38} {ref['by_type'].get(t, 0):>15} {cand['by_type'].get(t, 0):>15}")
print(f"{'источников':38} {ref['sources']:>15} {cand['sources']:>15}")
print(f"{'битых таймкодов':38} {len(ref['qc']['bad_timecode']):>15} "
f"{len(cand['qc']['bad_timecode']):>15}")
print(f"{'слабых цитат':38} {len(ref['qc']['weak_quote']):>15} "
f"{len(cand['qc']['weak_quote']):>15}")
print(f"{'помечено «сверить с кадром»':38} {ref['frame_check']:>15} {cand['frame_check']:>15}")
g_ref = sum(ref["golden"].values())
g_cand = sum(cand["golden"].values())
print(f"{'golden-фактов покрыто':38} {g_ref:>13}/9 {g_cand:>13}/9")
for name in GOLDEN_FACTS:
r, c = ref["golden"][name], cand["golden"][name]
if not (r and c):
print(f" {'✓' if r else '✗'} эталон | {'✓' if c else '✗'} GLM — {name}")
if cand["qc"]["bad_timecode"]:
print("\nБитые таймкоды GLM (галлюцинации источников!):")
for title, video, tc in cand["qc"]["bad_timecode"][:10]:
print(f" ✗ [{tc}] {title[:70]}")
return 0
if __name__ == "__main__":
raise SystemExit(main())