diff --git a/test/rule_trace/scoring.py b/test/rule_trace/scoring.py index 055c72e..8eee5cb 100644 --- a/test/rule_trace/scoring.py +++ b/test/rule_trace/scoring.py @@ -9,6 +9,8 @@ Expectation keys (case["expect"]): 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 @@ -30,12 +32,33 @@ def fold(text: str | None) -> str: return " ".join(unicodedata.normalize("NFKD", text or "").encode("ascii", "ignore").decode().lower().split()) +NAME = re.compile(r"^[A-ZÁ-Ž][^\W\d_]+(?:\s+[A-ZÁ-Ž][^\W\d_]+){1,2}$") + + +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ý"): every word's stem starts a word of the text.""" + if fold(phrase) in text: + return True + if not NAME.match(phrase.strip()): + return False + stems = [fold(w)[:max(4, len(w) - 2)] for w in phrase.split()] + return all(re.search(rf"\b{re.escape(stem)}", text) for stem in stems) + + 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 []: @@ -55,7 +78,7 @@ def check(case: dict, result: dict) -> dict: 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}"] = fold(phrase) in text + 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 []: