"""A question keeps its demanded field while source sentences are read. The native dictionary and ClaimReader supply open words and clause roles. The closed wh/auxiliary inversion below supplies the missing role, not a list of topics or answers. A match means the source says the answer, not that the source is independently true. Unknown grammar remains a received hole. """ import hashlib import json import re UNKNOWN = "o7answerfield" WORD = re.compile(r"[A-Za-z0-9_]+(?:['’-][A-Za-z0-9_]+)*") AUX = set("am is are was were be been being do does did have has had can could will would shall should may might must".split()) NEG_AUX = {"don't": "do", "doesn't": "does", "didn't": "did", "isn't": "is", "aren't": "are", "wasn't": "was", "weren't": "were", "cannot": "can", "can't": "can", "won't": "will", "wouldn't": "would", "couldn't": "could", "shouldn't": "should"} COPULA = set("am is are was were be been being".split()) DETERMINERS = {"a", "an", "the"} MONTH = r"(?:January|February|March|April|May|June|July|August|September|October|November|December)" DATE = re.compile(r"(?:\d{3,4}(?:\s*(?:BC|BCE|AD|CE))?|\d{1,4}\s*(?:BC|BCE|AD|CE)|" r"\d{1,2}\s+" + MONTH + r"(?:\s+\d{3,4})?|" + MONTH + r"(?:\s+\d{1,2},?)?(?:\s+\d{3,4})?)", re.I) CONDITION = {"condition", "alternative"} def _digest(value): return hashlib.sha256(json.dumps(value, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode()).hexdigest() def _words(text, reader): return tuple(reader.d.lemma(w.lower()) for w in WORD.findall(text) if w.lower() not in DETERMINERS) def _passive(node, reader): """'was created' read as be + the property 'created' is the passive of create: when the first property after be is a verb's past participle in the store (its forms table), the relation is that verb and the property role is dropped. Read the same way for the question and for every source sentence, so neither side gains a reading the other lacks.""" if node["predicate"].get("lemma") != "be": return None props = [c for c in node["complements"] if c["role"] == "property"] if not props: return None first = props[0]["text"].split() if len(first) != 1: return None word = first[0].lower() try: row = reader.d.db.execute("SELECT lemma FROM forms WHERE form=? AND pos='verb' AND tags_json LIKE '%past%' LIMIT 1", (word,)).fetchone() except Exception: # noqa: BLE001 row = None return (row[0], props[0]) if row else None def _agent(node, reader): """the by-phrase of a passive clause: its actor ("created by Arlene Klasky")""" passive = _passive(node, reader) if not passive: return None return next((c for c in node["complements"] if c is not passive[1] and str(c.get("marker") or "").lower() == "by"), None) def _node(node, reader): """A passive clause is read in its active order: the by-phrase is the actor (subject), the grammatical subject is the object. "Rugrats was created by Arlene Klasky" and "Who created Rugrats?" then share one shape; an agentless passive ("When was Bitcoin created?") has an empty actor, which any actor satisfies.""" passive = _passive(node, reader) agent = _agent(node, reader) complements = [c for c in node["complements"] if not (passive and (c is passive[1] or c is agent))] roles = tuple((c["role"], c.get("marker"), _words(c["text"], reader)) for c in complements) subject = _words(node["subject"]["text"], reader) if passive: roles = (("object", None, subject),) + roles subject = _words(agent["text"], reader) if agent else () return {"subject": subject, "relation": passive[0] if passive else node["predicate"]["lemma"], "roles": roles, "polarity": node["polarity"], "modal": (node.get("modal") or {}).get("lemma"), "modifiers": tuple(w for w in (_words(c["text"], reader) for c in node.get("modifiers", [])) if w), # a modifier of determiners only says nothing "attribution": (node["attribution"]["speaker"], node["attribution"]["stance"])} def _conditions(graph, node_id, reader): nodes = {n["id"]: n for n in graph["nodes"]} return sorted((link["kind"], link["mode"], _digest(_node(nodes[link["from"]], reader))) for link in graph["links"] if link["to"] == node_id and link["kind"] in CONDITION) def _graph(text, reader, *, source=False): from claim_shape import ClaimReader from claim_judge import shape graph = ClaimReader(reader).read(text) checked = shape(graph, reader.d) if (graph["holes"] and not source) or not checked["passed"]: return None return graph def receive(question, reader=None, subjects=()): """Receive one field question; return its complete duty or a precise hole. `subjects` is an optional *already resolved* reference, never a guessed article title. It is deliberately retained separately from original words. """ duty = {"version": 1, "original": str(question), "missing": [], "receiver": "question_obligation.receive"} if reader is None: duty["missing"] = ["the native dictionary reader"] return duty text = str(question).strip().rstrip("?!. ") if len(subjects) == 1: text = re.sub(r"\b(?:it|this|that)\b", lambda _m: str(subjects[0]), text, flags=re.I) tokens = WORD.findall(text) if not tokens: duty["missing"] = ["a question"] return duty first = tokens.pop(0).lower() kind = {"when": "time", "where": "place", "why": "reason", "how": "method", "who": "person", "whom": "person", "what": "value", "which": "value"}.get(first) if kind is None: duty["missing"] = ["a received question field"] return duty count_noun = [] if first in {"what", "which"} and tokens and tokens[0].lower() in {"year", "date", "time"}: kind = "time"; tokens.pop(0) elif first == "how" and tokens and tokens[0].lower() in {"many", "much"}: kind = "number"; tokens.pop(0) boundary = next((i for i, word in enumerate(tokens) if word.lower() in AUX or word.lower() in NEG_AUX), None) if boundary is None: duty["missing"] = ["the count's received noun role"] return duty count_noun, tokens = tokens[:boundary], tokens[boundary:] if not tokens: duty["missing"] = ["the subject and relation being asked about"] return duty first_rest = tokens[0].lower() auxiliary = NEG_AUX.get(first_rest, first_rest) unknown_role = None if auxiliary in AUX: tokens.pop(0) # Locate the lexical predicate using the native dictionary. A proper # name cannot itself become the acting word just because it is a verb. from claim_shape import ClaimReader, SUFFIX cr = ClaimReader(reader) main = " ".join(tokens) joined = SUFFIX.search(main) main_tokens = WORD.findall(main[:joined.start()]) if joined else tokens # A resolved label must occupy the actual subject prefix. It cannot # exchange an object or incidental article title for the actor. anchors = {i for label in subjects if isinstance(label, str) and label for i in range(1, len(main_tokens) + 1) if _words(" ".join(main_tokens[:i]), reader) == _words(label, reader)} split = next(iter(anchors)) if len(anchors) == 1 else None if split is None: candidates = [i for i, word in enumerate(main_tokens) if i and cr._verb(word) and not word[:1].isupper() and word.lower() not in {"not", "never"} and (auxiliary not in {"do", "does", "did"} or reader.d.lemma(word.lower(), "verb") == word.lower())] if len(candidates) > 1: duty["missing"] = ["the subject boundary among the noun/verb readings; name or resolve the subject"] return duty split = candidates[0] if candidates else None if split is None and auxiliary in COPULA: # Inverted copular properties can have no lexical verb at all. # Find an adjective after the subject's nominal head; adjectives # before that head remain inside its noun phrase. nominal = False for i, word in enumerate(main_tokens): roles = reader.d.pos(word.lower()) if i and nominal and "adj" in roles and not word[:1].isupper(): split = i break if word.lower() not in DETERMINERS | {"not", "never"} and (roles & {"noun", "name", "proper noun", "pron"} or not roles): nominal = True if split is None: if auxiliary not in COPULA: duty["missing"] = ["the received predicate after the auxiliary"] return duty split = len(tokens) subject, tail = tokens[:split], tokens[split:] negatives = [word for word in subject if word.lower() in {"not", "never"}] subject = [word for word in subject if word.lower() not in {"not", "never"}] if first_rest in NEG_AUX: negatives.append("not") if not subject: duty["missing"] = ["the subject of the requested relation"] return duty if kind in {"value", "person", "number"}: tail += [UNKNOWN] + count_noun unknown_role = "complement" statement = " ".join(subject + [auxiliary] + negatives + tail) elif kind in {"person", "value"}: statement = " ".join([UNKNOWN] + tokens) unknown_role = "subject" else: # Embedded question clauses ("explain why the valve closes") already # have declarative order; the same native reader judges their roles. statement = " ".join(tokens) graph = _graph(statement + ".", reader) roots = [n for n in (graph or {}).get("nodes", []) if n["id"] in graph["roots"]] if graph else [] if len(roots) != 1: duty["missing"] = ["an unambiguous native clause for the question"] return duty node = roots[0] received = _node(node, reader) duty.update(kind=kind, unknown_role=unknown_role, shape=received, conditions=_conditions(graph, node["id"], reader), reading=graph, resolved_subjects=list(subjects)) duty["key"] = _digest({k: duty[k] for k in ("version", "kind", "unknown_role", "shape", "conditions")}) return duty def _tail_scope(graph, node, value, sentence, kind): """A checked reason may be quoted without interpreting its trailing relative. This exception admits no unknown main role, cause link, polarity, or condition. Every unreceived span must be a relative-reference tail directly after the complete received reason; the full source remains attached. """ holes = graph.get("holes", []) if not holes: return {} if kind != "reason" or len(holes) != 1: return None hole = holes[0] a, b = hole.get("span", [-1, -1]) end = value["span"][1] if (hole.get("kind") != "reference" or a < end or sentence[end:a].strip() or not re.match(r"^(?:that|which|who)\b", sentence[a:b], re.I) or sentence[b:].strip(" .!?\r\n\t") or any(n["span"][0] < b and n["span"][1] > a for n in graph["nodes"])): return None # Its exact omission is visible; no pronoun referent or relative scope is # inferred. The quote retains all parsed complements, including without. start = min(node["span"][0], value["span"][0]) return {"source_excerpt": sentence[start:end] + " …", "source_excerpt_span": [start, end], "unresolved_tail": [{"text": sentence[a:b], "span": [a, b], "kind": hole["kind"]}], "reading_scope": "received main clause and explicit reason; trailing relative remains unresolved"} PAGE_PRONOUNS = {"it", "he", "she", "they"} REASON_MARKERS = {"because", "because of", "due to", "owing to", "since", "as a result of"} def _same_subject(held, expected, title, reader): """On a page about its title, the clause's subject is that title when it is the title's words, a third-person pronoun standing for the page's own subject ("It is not known who wrote it" on the Beowulf page), or a noun phrase that begins with the expected words and goes on to describe them ("The sky, which is made up of gas molecules, is blue ..."). A phrase that only contains the words ("the Blue Nile" on the Nile page) is another subject.""" held, expected = tuple(held), tuple(expected) if held == expected or not expected: # an agentless passive question names no actor return True page = _words(title, reader) if title else () if len(held) == 1 and held[0] in PAGE_PRONOUNS and expected and page and (expected == page or set(expected) <= set(page)): return True return bool(expected) and held[:len(expected)] == expected and len(held) > len(expected) def match(duty, sentence, reader=None, title=""): """Read the source independently and bind the demanded field, or return None.""" if duty.get("missing") or reader is None: return None graph = _graph(sentence, reader, source=True) if not graph: return None if title: # a page's own pronoun is resolved by the page (see below) graph = dict(graph, holes=[h for h in graph.get("holes", []) if not ( h.get("kind") == "reference" and str(h.get("text", "")).strip().lower() in PAGE_PRONOUNS)]) # Duties are durable JSON records; tuple/list representation after reload # must not change the received meaning or turn a valid continuation away. expected = json.loads(json.dumps(duty["shape"])) candidates = [] for node in graph["nodes"]: held = json.loads(json.dumps(_node(node, reader))) if title: # the page's own pronoun stands for the page's subject in any role page = list(_words(title, reader)) held["roles"] = [[r, m, page if len(w) == 1 and w[0] in PAGE_PRONOUNS else w] for r, m, w in held["roles"]] if any(held[k] != expected[k] for k in ("relation", "polarity", "modal", "modifiers", "attribution")): continue if duty["unknown_role"] != "subject" and not _same_subject(held["subject"], expected["subject"], title, reader): continue if _digest(_conditions(graph, node["id"], reader)) != _digest(duty["conditions"]): continue # Roles are ordered and owned. Topic overlap cannot exchange actor and # object or let an unrelated date satisfy this clause. required = [r for r in expected["roles"] if UNKNOWN not in r[2]] # a held phrase that ends with the asked words is that role ("According to legend, Rome" ends with "Rome") if any(not any(h[0] == r[0] and h[1] == r[1] and list(h[2])[-len(r[2]):] == list(r[2]) for h in held["roles"]) for r in required if r[2]): continue values = [] if duty["unknown_role"] == "subject": agent = _agent(node, reader) values = [agent] if agent else ([] if _passive(node, reader) else [node["subject"]]) elif duty["unknown_role"] == "complement": wanted = [r for r in expected["roles"] if UNKNOWN in r[2]] for role, marker, words in wanted: words = tuple(words) position = words.index(UNKNOWN) prefix, suffix = words[:position], words[position + 1:] values += [c for c in node["complements"] if c["role"] == role and c.get("marker") == marker and _words(c["text"], reader)[:len(prefix)] == prefix and (not suffix or _words(c["text"], reader)[-len(suffix):] == suffix) and len(_words(c["text"], reader)) > len(prefix) + len(suffix)] elif duty["kind"] == "reason": nodes = {n["id"]: n for n in graph["nodes"]} values = [nodes[link["from"]] for link in graph["links"] if link["to"] == node["id"] and link["kind"] == "reason" and not link.get("scope")] # a reason given as a phrase of the same clause ("is blue because of the random scattering of sunlight") values += [c for c in node["complements"] if str(c.get("marker") or "").lower() in REASON_MARKERS] else: for c in node["complements"]: marker, value = c.get("marker"), c["text"] if duty["kind"] == "time" and marker in {"in", "on", "at", "during", "before", "after", "since", "until"} and DATE.fullmatch(value): values.append(c) elif duty["kind"] == "place" and marker in {"in", "at", "from", "into", "within", "on"} and not DATE.fullmatch(value): values.append(c) elif duty["kind"] == "method" and marker in {"by", "through", "with"}: values.append(c) for value in values: scope = _tail_scope(graph, node, value, sentence, duty["kind"]) if scope is None: continue a, b = value["span"] if sentence[a:b] != value["text"]: continue if duty["kind"] == "number": number = re.search(r"\b\d+(?:[,.]\d+)*\b", value["text"]) if not number: continue a, b = a + number.start(), a + number.end() candidates.append({"value": sentence[a:b], "normalized": _words(sentence[a:b], reader), "value_span": [a, b], "clause_span": node["span"], "duty_key": duty["key"], "sentence": sentence, "sha256": hashlib.sha256(sentence.encode()).hexdigest(), "basis": "native clause roles and demanded field", "title": title, **scope}) # Multiple possible values do not silently become whichever was first. unique = {tuple(c["normalized"]): c for c in candidates} return next(iter(unique.values())) if len(unique) == 1 else None def select_records(question, records, reader=None, title="", subjects=()): """Select a checked original page record; the caller decides its truth label.""" duty = receive(question, reader, subjects or ((title,) if title else ())) if duty["missing"]: return None selected = [] for record in records: checked = match(duty, record.get("sentence", ""), reader, record.get("title") or title) if checked: selected.append(dict(record, question_obligation=duty, answer_check=checked)) if agreement([record["answer_check"] for record in selected])["conflict"]: return None return selected[0] if selected else None def agreement(checks): """Agreement on the same demanded value; it says nothing about independence.""" checks = [c for c in checks if c] if len(checks) < 2 or len({c["duty_key"] for c in checks}) != 1: return {"agrees": False, "conflict": False, "values": []} values = {tuple(c["normalized"]) for c in checks} # Values that nest are one answer at two grains ("Africa", "the north of Africa"): every value's words lie inside # the widest. Two values neither of which contains the other still conflict and stay conflicting. widest = max(values, key=len) nested = all(set(v) <= set(widest) for v in values) return {"agrees": len(values) == 1 or nested, "conflict": len(values) > 1 and not nested, "values": [list(value) for value in sorted(values)]}