feat(eval): scripts/classifier_eval.py — прогон эталонов классификации без записи; change email-classification-entities заархивирован (Purpose в main-спеке)
This commit is contained in:
Executable
+172
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
classifier_eval.py — прогон эталонных примеров классификации БЕЗ записи в архив.
|
||||
|
||||
Берёт data/classification-examples.json, для каждого примера читает письмо из
|
||||
архива, заново классифицирует его локальной моделью (та же функция, что у
|
||||
scripts/email_classifier.py) и сравнивает результат с ожидаемым.
|
||||
|
||||
Frontmatter НЕ меняется: письма читаются только на чтение. Ответ модели
|
||||
печатается рядом с ожидаемым, чтобы видеть расхождение и причину.
|
||||
|
||||
Что проверяется:
|
||||
• набор меток (classification) — жёсткая проверка;
|
||||
• meeting_datetime — жёсткая проверка, если он задан в эталоне;
|
||||
• слова из expected_reason_contains — мягкая проверка (предупреждение):
|
||||
формулировки модели вольные, важен смысл.
|
||||
|
||||
Код возврата: 0 — все жёсткие проверки прошли, 1 — есть расхождения,
|
||||
2 — эталон/архив недоступны (письмо не найдено, Ollama не отвечает).
|
||||
|
||||
Запуск:
|
||||
python3 scripts/classifier_eval.py # все эталоны
|
||||
python3 scripts/classifier_eval.py --only ex-2026-10-30-ispring
|
||||
python3 scripts/classifier_eval.py --json # машинный вывод
|
||||
python3 scripts/classifier_eval.py --repeat 3 # стабильность модели
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
import email_classifier as clf # noqa: E402
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
EXAMPLES_FILE = PROJECT_ROOT / "data" / "classification-examples.json"
|
||||
|
||||
|
||||
def load_examples(path: Path):
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
return data.get("examples", [])
|
||||
|
||||
|
||||
def label_set(tags: str) -> set[str]:
|
||||
return {t.strip().lower() for t in str(tags or "").split(",") if t.strip()}
|
||||
|
||||
|
||||
def classify_email(email_md: Path):
|
||||
"""Прогнать письмо через классификатор. Возвращает (tags, reason, meeting_dt)."""
|
||||
headers, body, _content, _fm_end = clf.parse_email_md(email_md)
|
||||
subject = headers.get("subject", "").strip()
|
||||
sender = headers.get("from", "").strip()
|
||||
raw = clf.call_llm(subject, sender, body)
|
||||
if raw is None:
|
||||
return None
|
||||
return clf.normalize_classification(raw)
|
||||
|
||||
|
||||
def check_example(example: dict, repeat: int = 1) -> dict:
|
||||
"""Проверить один эталон. Возвращает отчёт с полями ok/failures/warnings."""
|
||||
result = {
|
||||
"id": example.get("id"),
|
||||
"subject": example.get("subject"),
|
||||
"path": example.get("path"),
|
||||
"expected": sorted(example.get("expected_labels") or []),
|
||||
"runs": [],
|
||||
"failures": [],
|
||||
"warnings": [],
|
||||
}
|
||||
email_md = clf.EMAIL_ROOT / (example.get("path") or "")
|
||||
if not email_md.is_file():
|
||||
result["failures"].append(f"письмо не найдено: {email_md}")
|
||||
return result
|
||||
|
||||
expected_labels = label_set(",".join(example.get("expected_labels") or []))
|
||||
expected_dt = example.get("expected_meeting_datetime")
|
||||
keywords = [k.lower() for k in (example.get("expected_reason_contains") or [])]
|
||||
|
||||
for run in range(max(1, repeat)):
|
||||
got = classify_email(email_md)
|
||||
if got is None:
|
||||
result["failures"].append("модель не вернула ответ (Ollama недоступна?)")
|
||||
return result
|
||||
tags, reason, meeting_dt = got
|
||||
run_info = {"tags": tags, "reason": reason, "meeting_datetime": meeting_dt}
|
||||
result["runs"].append(run_info)
|
||||
|
||||
got_labels = label_set(tags)
|
||||
if got_labels != expected_labels:
|
||||
result["failures"].append(
|
||||
f"прогон {run + 1}: метки {sorted(got_labels)} ≠ ожидаемых {sorted(expected_labels)}")
|
||||
if expected_dt and meeting_dt != expected_dt:
|
||||
result["failures"].append(
|
||||
f"прогон {run + 1}: meeting_datetime {meeting_dt!r} ≠ ожидаемого {expected_dt!r}")
|
||||
if keywords:
|
||||
low = reason.lower()
|
||||
missing = [k for k in keywords if k not in low]
|
||||
if missing:
|
||||
result["warnings"].append(
|
||||
f"прогон {run + 1}: в обосновании нет слов {missing}")
|
||||
|
||||
result["ok"] = not result["failures"]
|
||||
result["reason"] = result["runs"][-1]["reason"] if result["runs"] else ""
|
||||
return result
|
||||
|
||||
|
||||
def print_report(results, as_json: bool):
|
||||
if as_json:
|
||||
print(json.dumps({"results": results,
|
||||
"ok": all(r["ok"] for r in results)}, ensure_ascii=False, indent=2))
|
||||
return
|
||||
total = len(results)
|
||||
passed = sum(1 for r in results if r["ok"])
|
||||
for r in results:
|
||||
mark = "✓" if r["ok"] else "✗"
|
||||
print(f"\n{mark} {r['id']} — {r['subject']}")
|
||||
print(f" письмо: {r['path']}")
|
||||
print(f" ожидалось: {', '.join(r['expected']) or '—'}"
|
||||
+ (f" · {r['expected_dt']}" if r.get("expected_dt") else ""))
|
||||
for run in r["runs"]:
|
||||
dt = f" · {run['meeting_datetime']}" if run["meeting_datetime"] else ""
|
||||
print(f" получено: {run['tags'] or '—'}{dt}")
|
||||
print(f" причина: {run['reason'][:160]}")
|
||||
for f in r["failures"]:
|
||||
print(f" ✗ {f}")
|
||||
for w in r["warnings"]:
|
||||
print(f" ⚠ {w}")
|
||||
print(f"\nИтог: {passed}/{total} эталонов совпали")
|
||||
if passed < total:
|
||||
print("Расхождение — правьте промпт/эталон (данные архива не тронуты).")
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="Прогон эталонов классификации без записи в архив")
|
||||
ap.add_argument("--file", default=str(EXAMPLES_FILE), help="Файл эталонов (по умолчанию data/classification-examples.json)")
|
||||
ap.add_argument("--only", default="", help="Только эталон с указанным id")
|
||||
ap.add_argument("--repeat", type=int, default=1, help="Прогнать каждый эталон N раз (проверка стабильности)")
|
||||
ap.add_argument("--json", action="store_true", help="Машинный вывод")
|
||||
args = ap.parse_args()
|
||||
|
||||
examples_path = Path(args.file)
|
||||
if not examples_path.is_file():
|
||||
print(f"нет файла эталонов: {examples_path}", file=sys.stderr)
|
||||
return 2
|
||||
examples = load_examples(examples_path)
|
||||
if args.only:
|
||||
examples = [e for e in examples if e.get("id") == args.only]
|
||||
if not examples:
|
||||
print(f"эталон {args.only!r} не найден в {examples_path}", file=sys.stderr)
|
||||
return 2
|
||||
if not examples:
|
||||
print("эталонов нет — нечего проверять", file=sys.stderr)
|
||||
return 0
|
||||
|
||||
results = []
|
||||
for example in examples:
|
||||
if not args.json:
|
||||
print(f"… классифицирую {example.get('id')}", file=sys.stderr)
|
||||
r = check_example(example, repeat=args.repeat)
|
||||
r["expected_dt"] = example.get("expected_meeting_datetime")
|
||||
results.append(r)
|
||||
|
||||
print_report(results, args.json)
|
||||
if any("модель не вернула ответ" in f for r in results for f in r["failures"]):
|
||||
return 2
|
||||
return 0 if all(r["ok"] for r in results) else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user