Files
romanov_btg_rag/scripts/quote_check.py
T
anorandClaude Opus 4.8 dbbca44d45 fix: Unicode NFC-нормализация id лекций и фрагментов
macOS хранит имена каталогов в NFD, LLM печатают NFC — байтово разные
строки выглядят одинаково, ломая идемпотентность (9 лекций числились
неизвлечёнными). id корпуса нормализуются на входе, quote_check
сравнивает в NFC, данные приведены одноразово. Реестр: 28 извлечено,
0 сирот, 41 осталась.

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

99 lines
4.7 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
import unicodedata
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-файл: ручной разбор или фрагмент торрента.
Сравнение в NFC: на диске имена NFD (macOS), в карточках — как напечатано."""
video = unicodedata.normalize("NFC", video)
for d in config.MANUAL_DIRS:
if unicodedata.normalize("NFC", 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())