"""Deterministic ambiguity audit for attribute-of-entity answers (layer 1). Run J taught the shape: 'What office is Pedro Sánchez associated with as President?' has THREE defensible readings in the KG (prime minister of Spain, secretary-general of PSOE, president of Socialist International); the answer step picked one literally and the machine never learned the other two existed. The fix is not prompt tuning — it is a data type the pipeline could not express: 'this answer is one of several'. LAW: the audit runs AFTER a value is picked, over rows the KG already holds, zero LLM, zero network. The single-candidate path stays byte-identical: an audit that flags nothing changes nothing. LAW: a role word in the question gates the whole audit. 'as President' -> office-class roles; a question about population or river length never enters the audit (no ambiguity detection everywhere — the audit must stay quiet on ordinary questions). """ from __future__ import annotations import re from .store import norm_name _WORD = re.compile(r"[A-Za-zÀ-ÿ0-9']+") def _toks(text: str) -> set[str]: return {w.casefold() for w in _WORD.findall(text or "")} # curated, closed vocabulary — ROLE WORDS that make a relation an # office/position claim. Multiword entries match as phrases (both # spellings listed); single words match on token boundaries ('chairman' # never matches 'chairmanship' by substring). _ROLE_WORDS = ( # head-of-state / head-of-government "president", "prime minister", "premier", "chancellor", # party / organisation leadership "secretary general", "secretary-general", "chairman", "chairperson", "chair", "leader", "secretary", # legislature / local "speaker", "governor", "mayor", "minister", ) # question words never part of an entity name _QSTOPS = {"What", "Which", "Who", "When", "Where", "Why", "How", "The", "Is", "Are", "Was", "Were", "In", "On", "At", "For", "Of", "Their", "Its", "Those", "These", "That", "This"} _MONTHS = {"january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"} def role_in_text(text: str) -> str | None: """The ROLE named in a question, relation or object, if any: 'president of the government' -> 'president'; 'population' -> None. Longest phrase wins; single words need a token boundary.""" low = (text or "").casefold() for r in sorted(_ROLE_WORDS, key=len, reverse=True): if " " in r: if r in low: return r elif re.search(rf"\b{re.escape(r)}\b", low): return r return None def ref_entity(question: str) -> str | None: """The entity the question is about: the longest capitalized RUN that is not itself a role phrase. Runs break at any lowercase word, so 'What office is Pedro Sanchez associated with as President?' yields runs [Pedro Sanchez] and [President]; the role run is dropped and 'Pedro Sanchez' wins. 'Who is the President of France?' -> 'France'.""" runs: list[list[str]] = [] run: list[str] = [] for w in _WORD.findall(question or ""): if w[0].isupper() and w not in _QSTOPS: run.append(w) elif run: runs.append(run) run = [] if run: runs.append(run) entity_runs = [r for r in runs if not role_in_text(" ".join(r))] pool = entity_runs or [r for r in runs if len(r) > 1] if not pool: return None return " ".join(max(pool, key=len)) def _is_roleish_value(val: str) -> bool: """A candidate alternative must NAME something: a bare number, year or date is a quantity row, not an office ('president since' | '2 June 2018' must never become an alternative). Month names are dates in disguise.""" words = [w.casefold() for w in re.findall(r"[A-Za-zÀ-ÿ]+", val or "") if len(w) >= 3 and w.casefold() not in _MONTHS] return bool(words) and sum(len(w) for w in words) >= 4 def _ent_row_match(ent: str, src: str) -> bool: """Same-entity law: every entity token present in the row's subject (question names 'pedro sanchez', node says 'pedro sanchez perez castejon'), or the reverse when the node is the shorter form and still >= 2 tokens. Single-token shortcuts never match.""" etoks = set(norm_name(ent).split()) stoks = set(norm_name(src).split()) if not etoks or not stoks: return False if etoks <= stoks: return True return len(stoks) >= 2 and stoks <= etoks def _merge_alternatives(cands: list[dict]) -> list[dict]: """Same role + token-containment values = ONE office in two extraction shapes ('prime minister of' | 'Spain' and 'office' | 'Prime Minister of Spain'). Keep the longer value — it loses no verbatim information; keep the best quote (verbatim law); sum corroboration.""" out: list[dict] = [] for a in sorted(cands, key=lambda c: len(c["value"]), reverse=True): merged = False for b in out: if b["role"] != a["role"]: continue at = set(norm_name(a["value"]).split()) bt = set(norm_name(b["value"]).split()) if at <= bt or bt <= at: b["corroboration"] += a["corroboration"] if a["quote"] and not b["quote"]: b["quote"] = a["quote"] merged = True break if not merged: out.append(dict(a)) return out def audit_role_multiplicity( question: str, rows: list, picked_value: str, max_alternatives: int = 5) -> dict | None: """Layer-1 audit: does the KG hold MORE THAN ONE office-class role for the question's entity? Returns None when there is nothing to report (no role word in the question, no entity, single office) — the caller's answer stays exactly as it was. When it fires, returns {"axis": ..., "alternatives": [...]} where each alternative is {value, role, quote, url} — every field verbatim from the KG, no inference. The PICKED reading is not repeated among the alternatives: the report says the OTHER defensible readings.""" # GATE 1: the question must name a role ('as President', 'which # office ... as premier'). Population/length questions never enter. q_role = role_in_text(question) if not q_role: return None # GATE 2: an entity to audit. No entity -> nothing to compare. ent = ref_entity(question) if not ent: return None # GATE 3: only rows ABOUT the entity, only office-class roles. The # role may live in the relation ('president of' | 'Socialist # International') or in the object ('office' | 'Prime Minister of # Spain') — extraction shape varies, the audit must not care. by_key: dict[tuple[str, str], dict] = {} for r in rows: if not _ent_row_match(ent, r.src or ""): continue role = role_in_text(r.rel) or role_in_text(r.dst) if not role: continue val = (r.dst or "").strip() if (not val or not _is_roleish_value(val) or norm_name(val) == norm_name(ent) or norm_name(val) == norm_name(picked_value or "")): continue key = (role, val) if key not in by_key or r.corroboration > by_key[key]["corroboration"]: by_key[key] = {"value": val, "role": role, "quote": r.quote, "url": r.url, "corroboration": r.corroboration} merged = _merge_alternatives(list(by_key.values())) if len(merged) < 2: return None alts = sorted(merged, key=lambda c: -c["corroboration"])[:max_alternatives] return { "axis": f"which office does '{q_role}' refer to?", "alternatives": [{"value": c["value"], "role": c["role"], "quote": (c["quote"] or "")[:160], "url": c["url"]} for c in alts]}