143 lines
7.2 KiB
Python
143 lines
7.2 KiB
Python
"""Checks of one answer and the place where it failed (planner, retrieval, check, source or content).
|
|
|
|
Expectation keys (case["expect"]):
|
|
status allowed statuses (default ["ok"])
|
|
sources sources the answer must cite when it is "ok": "wiki", "crzp" (default both when
|
|
both_sources is true, the format of the CRZP+wiki set)
|
|
urls_any at least one of these links in the answer or its sources
|
|
all / any / none texts the answer must contain / one of them / none of them (case and diacritics ignored)
|
|
number a number the answer must state
|
|
refusal a question the agent must not answer: a clarification, no_answer or an explicit
|
|
"not in the records" passes; a made-up answer fails
|
|
alt another correct outcome: {"status": [...], "any": [...]} (the register's namesakes asked for)
|
|
A name in "all" ("Martin Šarišský") also passes in another case ("Martina Šarišského").
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import unicodedata
|
|
|
|
WIKI = "zp.kemt.fei.tuke.sk"
|
|
CRZP = "opac.crzp.sk"
|
|
BRANCH = re.compile(r"^(?:unified\.|combined\.|crzp\.answer|crzp\.part|wiki\.deliver)")
|
|
# an explicit "the records do not say" (folded text)
|
|
REFUSAL = re.compile(r"nie je uveden|nie je v podkladoch|v podkladoch nie|taky udaj nie je|nenasl|nemam|nepodarilo|"
|
|
r"neexist|nie je zaznamenan|nie su zaznamenan|nemozem|neviem|ziadn|nie je dostupn|upresn|ktor\w+ mysli|"
|
|
r"nie je mozne|nepotvrdzujem|neuvadza|nie je zname|nie je evidovan|odpovedam len|nie je doloz|"
|
|
r"skontroluj meno|uved cele meno|nie je isté|nie je iste|nema v podkladoch|nemaju v podkladoch|"
|
|
r"klucove slovo [^.;]{1,60}? nema\b|\bnemaju\s+spolocn|\bspolocn\w*(?:\s+\w+){0,4}\s+nemaju\b|nespomina|nesplna|"
|
|
r"v podkladoch nie su")
|
|
|
|
|
|
def fold(text: str | None) -> str:
|
|
return " ".join(unicodedata.normalize("NFKD", text or "").encode("ascii", "ignore").decode().lower().split())
|
|
|
|
|
|
def is_name(phrase: str) -> bool:
|
|
"""Two or three words, each capitalized and only letters ("Martin Šarišský", "Denis Le Thanh")."""
|
|
words = phrase.split()
|
|
return 2 <= len(words) <= 3 and all(w.isalpha() and w[0].isupper() for w in words)
|
|
|
|
|
|
def contains(phrase: str, text: str) -> bool:
|
|
"""The phrase in the folded text; a person's name also in another case ("Martina Šarišského" for
|
|
"Martin Šarišský"): the words' stems next to each other, in order (never words of two other people)."""
|
|
if fold(phrase) in text:
|
|
return True
|
|
if not is_name(phrase.strip()):
|
|
return False
|
|
stems = [fold(w)[:max(4, len(fold(w)) - 2)] for w in phrase.split()]
|
|
return bool(re.search(r"\b" + r"\w*\s+".join(re.escape(stem) for stem in stems) + r"\w*\b", text))
|
|
|
|
|
|
def check(case: dict, result: dict) -> dict:
|
|
expect = case.get("expect") or {}
|
|
answer = result.get("answer") or ""
|
|
shown = answer + " " + " ".join(result.get("source_urls") or [])
|
|
text = fold(answer)
|
|
status = result.get("status")
|
|
alt = expect.get("alt")
|
|
if alt and status in (alt.get("status") or []):
|
|
# another correct answer, e.g. the register's namesakes: "Ktorú osobu myslíš?"
|
|
checks = {"alternatívna odpoveď": not alt.get("any") or any(fold(p) in text for p in alt["any"])}
|
|
for phrase in expect.get("none") or []:
|
|
checks[f"neobsahuje: {phrase}"] = fold(phrase) not in text
|
|
return checks
|
|
if expect.get("refusal"):
|
|
checks = {"odmietnutie": status in ("no_answer", "ambiguous") or (status == "ok" and bool(REFUSAL.search(text)))}
|
|
for phrase in expect.get("none") or []:
|
|
checks[f"neobsahuje: {phrase}"] = fold(phrase) not in text
|
|
return checks
|
|
allowed = expect.get("status") or ["ok"]
|
|
allowed = [allowed] if isinstance(allowed, str) else allowed
|
|
checks = {"status": status in allowed}
|
|
sources = expect.get("sources")
|
|
if sources is None:
|
|
sources = ["wiki", "crzp"] if expect.get("both_sources", True) else []
|
|
if status == "ok":
|
|
if "wiki" in sources:
|
|
checks["zdroj ZP Wiki"] = WIKI in shown
|
|
if "crzp" in sources:
|
|
checks["zdroj CRZP"] = CRZP in shown
|
|
if expect.get("urls_any"):
|
|
checks["očakávaný odkaz"] = any(u.rstrip("/") in shown for u in expect["urls_any"])
|
|
for phrase in expect.get("all") or []:
|
|
checks[f"obsahuje: {phrase}"] = contains(phrase, text)
|
|
if expect.get("any"):
|
|
checks["obsahuje jedno z: " + " | ".join(expect["any"][:4])] = any(fold(p) in text for p in expect["any"])
|
|
for phrase in expect.get("none") or []:
|
|
checks[f"neobsahuje: {phrase}"] = fold(phrase) not in text
|
|
if expect.get("number") is not None:
|
|
checks[f"číslo {expect['number']}"] = bool(re.search(rf"(?<![\d.,]){expect['number']}(?![\d]|[.,]\d)", answer))
|
|
return checks
|
|
|
|
|
|
def failure_point(case: dict, result: dict, checks: dict, trace: dict) -> str | None:
|
|
"""The first place the answer went wrong, as a short label ("plánovač: ambiguous_work")."""
|
|
if all(checks.values()):
|
|
return None
|
|
route = trace.get("route") or []
|
|
notes = trace.get("notes") or {}
|
|
status, reason = result.get("status"), result.get("reason")
|
|
if status == "request_error":
|
|
return "spojenie: " + str(reason)[:60]
|
|
if checks.get("odmietnutie") is False:
|
|
if status == "error":
|
|
return f"záporná otázka: chyba {reason}"
|
|
return "záporná otázka zodpovedaná: " + (last_branch(route) or "?")
|
|
if checks.get("odmietnutie") is True:
|
|
return "záporná otázka: obsahuje zakázaný text"
|
|
if not checks.get("status", True):
|
|
if status == "error":
|
|
fulfilment = notes.get("fulfilment") or {}
|
|
if reason == "answer_rejected" and fulfilment:
|
|
failed = [k for k in ("plan", "facts", "clear", "all_identified") if fulfilment.get(k) is False]
|
|
return "kontrola modelom: " + (",".join(failed) or "statuses=" + ",".join(fulfilment.get("statuses") or []))
|
|
return f"chyba: {reason}"
|
|
if status == "ambiguous":
|
|
return f"plánovač/upresnenie: {reason}"
|
|
if status == "no_answer":
|
|
return f"vyhľadávanie: {reason}"
|
|
return f"stav {status}: {reason}"
|
|
if checks.get("zdroj CRZP") is False:
|
|
plan = next((r for r in route if r.startswith("crzp.plan")), None)
|
|
return "CRZP nepoužité: " + (plan or "crzp.plan nevrátil plán (pravidlo ho vylúčilo)")
|
|
if checks.get("zdroj ZP Wiki") is False:
|
|
return "ZP Wiki nepoužitá: " + (last_branch(route) or "?")
|
|
if checks.get("očakávaný odkaz") is False:
|
|
return "chýba očakávaný zdroj: " + (last_branch(route) or "?")
|
|
return "obsah: " + (last_branch(route) or "?")
|
|
|
|
|
|
HELPERS = {"unified.person_works", "unified.supervisor_in"}
|
|
|
|
|
|
def last_branch(route: list[str]) -> str | None:
|
|
"""The branch that wrote the answer: a presentation branch first, then a combined branch, CRZP, the wiki."""
|
|
labels = [r.split("=")[0].split("!")[0] for r in route]
|
|
for prefix in ("unified.", "combined.", "crzp.answer", "crzp.part", "wiki.deliver"):
|
|
found = [l for l in labels if l.startswith(prefix) and l not in HELPERS]
|
|
if found:
|
|
return found[-1]
|
|
return None
|