Files
romanov_btg_rag/scripts/quote_check.py
T
anorandClaude Opus 4.8 49d745c74a feat: карточки пилота — 4 лекции, 160 карточек + независимый quote-check
Принцип 39 (+8 номиналов), Схема БТГ 51, Лекция 109 — 25, A1R1 — 45.
quote_check.py: таймкод существует в segments своего видео/фрагмента +
мягкое сопоставление цитаты (ASR-нормализация учтена). Найдено и
исправлено 6 промахов таймкодов (цитаты верны, якорь указывал не туда).
Итог: 279 источников, 0 битых, покрытие золотого набора 33/33.

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

96 lines
4.4 KiB
Python
Raw 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
"""Quote-check: независимая верификация источников карточек по транскриптам.
python scripts/quote_check.py # все файлы data/knowledge/
python scripts/quote_check.py <файл> # один файл
Для каждого source карточки проверяется:
1) строка [mm:ss] существует в segments-файле своего видео/фрагмента;
2) цитата пересекается по словам с текстом сегмента (±1 строка) — цитаты
нормализованы от ASR, поэтому проверка мягкая, по значимым словам.
Скрипт ТОЛЬКО докладывает (никаких мутаций); exit 1 при битых таймкодах.
"""
import json
import re
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) # корень в путь
from rag import config # noqa: E402
_WORD = re.compile(r"[а-яёa-z0-9]+", re.IGNORECASE)
def _segments_path(video: str) -> Path | None:
"""video из source → segments-файл: ручной разбор или фрагмент торрента."""
for d in config.MANUAL_DIRS:
if d.name == video:
found = sorted(d.rglob("*segments*.txt"))
return found[0] if found else None
p = config.CORPUS_DIR / video / "transcript" / "segments.txt"
return p if p.exists() else None
def quote_matches(quote: str, segment_text: str) -> bool:
"""Мягкое совпадение: хотя бы 2 значимых слова цитаты (или 1, если их мало)
встречаются в тексте сегмента. Цитаты ASR-нормализованы — точного
совпадения не бывает."""
q_words = {w.lower() for w in _WORD.findall(quote) if len(w) >= 4}
if not q_words:
return True # цитата из коротких слов/чисел — не проверяема мягко
s_lower = segment_text.lower()
hits = sum(1 for w in q_words if w in s_lower)
return hits >= min(2, len(q_words))
def check_file(path: Path) -> dict:
data = json.loads(path.read_text(encoding="utf-8"))
stats = {"sources": 0, "bad_timecode": [], "weak_quote": [], "no_segments": set()}
seg_cache: dict[str, list[str] | None] = {}
for card in data["cards"]:
for s in card["sources"]:
stats["sources"] += 1
video, tc = s["video"], s["timecode"]
if video not in seg_cache:
p = _segments_path(video)
seg_cache[video] = p.read_text(encoding="utf-8").splitlines() if p else None
lines = seg_cache[video]
if lines is None:
stats["no_segments"].add(video)
continue
idx = next((i for i, ln in enumerate(lines) if ln.startswith(f"[{tc}]")), None)
if idx is None:
stats["bad_timecode"].append((card["title"], video, tc))
continue
# сегмент ±1 строка: факт часто размазан по соседним репликам
window = " ".join(lines[max(0, idx - 1): idx + 2])
if not quote_matches(s["quote"], window):
stats["weak_quote"].append((card["title"], tc, s["quote"][:60]))
return stats
def main() -> int:
files = ([Path(sys.argv[1])] if len(sys.argv) > 1
else sorted(config.KNOWLEDGE_DIR.glob("*.json")))
ok = True
for f in files:
st = check_file(f)
n_bad, n_weak = len(st["bad_timecode"]), len(st["weak_quote"])
mark = "✓" if not n_bad else "✗"
print(f"{mark} {f.name}: источников {st['sources']}, "
f"битых таймкодов {n_bad}, слабых цитат {n_weak}")
for title, video, tc in st["bad_timecode"]:
print(f" ✗ ТАЙМКОД [{tc}] нет в {video[:50]} — «{title[:60]}»")
for title, tc, q in st["weak_quote"]:
print(f" ⚠ цитата не сошлась [{tc}] «{q}» — «{title[:60]}»")
for video in st["no_segments"]:
print(f" ✗ не найден segments для video={video[:70]}")
ok = False
if n_bad:
ok = False
return 0 if ok else 1
if __name__ == "__main__":
raise SystemExit(main())