Files
smeta-web/tests/quality_eval.py

103 lines
3.6 KiB
Python
Raw Permalink 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
"""Correctness-eval: верны ли ОТВЕТЫ на курированных вопросах (по эталонным
маркерам из test_questions.json). В отличие от dialog_replay (тот про «не
порушить»), этот про «ответ содержит нужные факты». Уникальный юзер на каждый
вопрос — обход per-user rate-limit (10/мин), иначе 429 портит прогон.
Запуск на дев-сервере:
set -a && . ./.env && set +a
python3 tests/quality_eval.py http://127.0.0.1:8104 [N] # N=кол-во вопросов, 0/пусто = все
"""
import json
import re
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
import httpx
from auth import _make_token
URL = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8104"
N = int(sys.argv[2]) if len(sys.argv) > 2 else 0
TESTS = Path(__file__).resolve().parent
QS = json.loads((TESTS / "test_questions.json").read_text(encoding="utf-8"))
if N:
QS = QS[:N]
def _norm(s: str) -> str:
s = s.lower().replace("**", "").replace("*", "")
s = s.replace(",", ".").replace("–", "-").replace("—", "-")
s = re.sub(r"\s+", " ", s)
s = re.sub(r"\s*\.\s*", ".", s)
s = re.sub(r"\s*-\s*", "-", s)
return s
def missing_markers(resp: str, markers) -> list:
rn = _norm(resp)
return [m for m in markers if _norm(m) not in rn]
def ask(q: str, i: int) -> str:
tok = _make_token(f"qeval{i}@test.local", "admin")
with httpx.Client(timeout=150) as c:
r = c.post(f"{URL}/api/chat", json={"message": q},
headers={"Authorization": f"Bearer {tok}", "X-Tab-Id": f"qeval{i}"})
if r.status_code != 200:
return f"__HTTP_{r.status_code}__"
texts = []
for line in r.text.split("\n"):
if line.startswith("data: "):
try:
d = json.loads(line[6:])
t = d.get("text") or d.get("result") or ""
if t:
texts.append(t)
except json.JSONDecodeError:
pass
return "\n".join(texts)
def main():
passed = fail = err = 0
fails = []
by_cat = {}
for i, q in enumerate(QS):
ans = ask(q["question"], i)
cat = q["category"]
by_cat.setdefault(cat, [0, 0])
if not ans.strip() or ans.startswith("__HTTP_"):
err += 1
fails.append((q["id"], cat, f"пусто/ошибка {ans[:20]}"))
by_cat[cat][1] += 1
icon = "💥"
else:
miss = missing_markers(ans, q["markers"])
if miss:
fail += 1
fails.append((q["id"], cat, f"нет маркеров {miss}"))
by_cat[cat][1] += 1
icon = "❌"
else:
passed += 1
by_cat[cat][0] += 1
icon = "✅"
print(f" {icon} Q{q['id']:3d} [{cat}]")
total = len(QS)
print(f"\n{'='*54}")
print(f" CORRECTNESS: {passed}/{total} верно | расхождений {fail} | пусто/ошибка {err}")
print(f"{'='*54}")
for cat in sorted(by_cat):
ok, bad = by_cat[cat]
print(f" {'✅' if bad == 0 else '⚠'} {cat:20s} {ok}/{ok+bad}")
if fails:
print("\n Расхождения (часть — ложные флаги: рус.запятая, диапазоны):")
for fid, cat, why in fails[:25]:
print(f" Q{fid} [{cat}]: {why}")
if __name__ == "__main__":
main()