#!/usr/bin/env python3 """coverage102 - Oracle7 10.2: COVERAGE BY VERIFIED PARTS, and the word-to-step JUDGE that every answer passes. Where the 9.0 reader and 10.1's clause layer decline, the question has usually been read in parts: 77% of declines stop at "no outer wording" - its clauses run on the knowledge base and name something, but no wording seen in training joins them. Until now those verified parts were thrown away, or (reader_v8, 10.1 development) joined by shape while the words no part covered were ignored - 13 right and 21 wrong, every wrong one an ignored word ("not", "or", "shorter"). Here the uncovered words are the HOLE, and the hole is searched for: PARTS the fragments the reader verified (each runs on the knowledge base and names something) are kept HOLE the content words no verified fragment covers, with the clause-opening word before them and any written value beside them, are the stretch to fill; what remains of the question is read by every released reader SEARCH the stretch is read as a PATCH (the steps a stretch adds, learned from training by the clause layer). Where no learned wording matches exactly, the nearest learned patches are RECALLED by HRR resonance of the stretch's shape (osub_seed phasors, the codebook of the path memory and the spine): a partial cue finds the patches whose wordings share its slots and words, ranked over every learned patch at once by one matrix product JOIN each patch is attached to each reading of the rest, at the steps the clause layer's learned places allow (and, for a hole after no written name, at every step of the patch's target kind), and RUN on the knowledge base JUDGE every content word of the question must be said by a step, and every step must be said by a word (below) AGREE an answer only when every judged reading that ran gives the same one; the opening must take its kind (9.0) A strict fallback: it is asked only where every released reader declined, so it can add answers and cannot lose one. THE JUDGE (align): a reading is the one the question meant only if the question and the reading account for each other. a word is accounted for when it is glue, an interrogative, part of a value the program reads written in the question (a name, a concept, a value, or one of their learned aliases), or a word LEARNED to say one of the program's features; a step's non-literal input (an attribute key, a relation, a qualifier key, a comparison) is accounted for when the question writes it or a word learned to say it; Count, Or, the select and verify steps and the qualifier queries need a word that says them. The word -> feature bindings are learned from the training split as 9.0 learns its operator words: a word says a feature when, in both halves, the feature is in at least half the programs of questions using the word, or the word is in at least 5% of the questions whose program has the feature and makes the feature at least twice as likely. So "died" says the date of death and leaves a date-of-birth reading unexplained; "not" says the inequality; "how many" says Count. The judge is also run over every answer the released readers give (judge_all) and reported separately; it becomes part of the law only where it catches more wrong answers than it costs right ones. use: C = coverage102.Coverage(rd, clauses, train); answers, readings = C.read(question); ok, why = C.align(question, prog)""" from __future__ import annotations import collections import copy import hashlib import json import os import re import steps_budget as SB import sys import time from pathlib import Path import numpy as np import reader_v4 as R4 import reader_v6 as R6 import reader_v7 as R7 import clause101 as CL D = 1024 SUPPORT = int(os.environ.get("O7_C2_SUP", 8)) TOPK = int(os.environ.get("O7_C2_TOPK", 6)) MIN_COS = float(os.environ.get("O7_C2_COS", 0.45)) BACK, AHEAD = 4, 3 DISCOURSE = {"one", "ones", "tell", "me", "you", "can", "could", "please", "give", "find", "show", "list", "know", "does", "did", "do", "is", "are", "was", "were", "be", "been", "being", "has", "have", "had", "the", "a", "an", "this", "that", "these", "those", "there", "here", "it", "its", "of", "to", "in", "on", "at", "by", "for", "with", "as", "and", "also", "both", "two", "which", "what", "who", "whom", "whose", "when", "where", "how", "many", "much", "statement", "terms", "kind", "type", "name", "named", "called", "known", "among", "between", "than", "s", "equal", "either", "there", "their", "its", "his", "her", "regarding", "respect", "about", "out", "if", "we"} SAID_FN = {"Count", "Or", "SelectBetween", "SelectAmong", "VerifyStr", "VerifyNum", "VerifyYear", "VerifyDate", "QueryRelation"} # a relation question says its function (connection, related) LITERAL_AT = {"Find": (0,), "FilterConcept": (0,), "FilterStr": (1,), "FilterNum": (1,), "FilterYear": (1,), "FilterDate": (1,), "QFilterStr": (1,), "QFilterNum": (1,), "QFilterYear": (1,), "QFilterDate": (1,), "VerifyStr": (0,), "VerifyNum": (0,), "VerifyYear": (0,), "VerifyDate": (0,), "QueryAttrUnderCondition": (2,), "QueryAttrQualifier": (1,)} def osub_seed(text, dim=D): """the substrate's codebook (path_hrr_v1, o7spine_v1): a sha256-seeded unit phasor per symbol""" h = int(hashlib.sha256(text.lower().strip().encode()).hexdigest(), 16) rng = np.random.RandomState(h % (2 ** 31)) return np.exp(1j * rng.uniform(0, 2 * np.pi, dim)).astype(np.complex64) def shape(tm): """a template's shape: its words and slots superposed, each bound to nothing (a bag the cue can partly match)""" toks = [t for t in tm.split() if not R7.is_glue(t)] if not toks: return None v = np.sum([osub_seed("o7c2:" + t) for t in toks], axis=0) return v / np.linalg.norm(v) def _half(q): return int(hashlib.md5(("c2|" + q).encode()).hexdigest(), 16) % 2 def _num(v): return bool(re.fullmatch(r"-?\d[\d,]*(?:\.\d+)?", str(v).strip())) def step_features(prog): """what each step of a program does that a question must say: (step index, feature, literal or None)""" out = [] for i, st in enumerate(prog): fn = st["function"] out.append((i, "FN:" + fn, None)) lit = LITERAL_AT.get(fn, ()) for k, v in enumerate(st["inputs"]): if not isinstance(v, str) or not v.strip() or _num(v): continue if k in lit: out.append((i, "LIT", v)) else: out.append((i, "IN:%s:%s" % (fn, v) if v in R6.CONSTS or v in ("forward", "backward") else "IN:" + v, None)) return out def family(f): """features that compete for a word: every attribute or relation input is one family, each function its own""" return "IN" if f.startswith("IN:") and f.count(":") == 1 else f YESNO = {"is", "are", "was", "were", "does", "do", "did", "has", "have", "had", "can", "could"} def _forms(t): """a written value and its plural/singular variants (88 minute / 88 minutes)""" out = {t} out.add(re.sub(r"(\w+)$", lambda m: m.group(1) + "s", t)) if t.endswith("s"): out.add(t[:-1]) return out class Lexicon: """word -> the program features it says, learned from the training split in both halves""" def __init__(self, train): df, ff, hit, n = [collections.Counter(), collections.Counter()], [collections.Counter(), collections.Counter()], \ [collections.Counter(), collections.Counter()], [0, 0] for x in train: h = _half(x["question"]) n[h] += 1 ws = set(R4.norm(x["question"]).split()) fs = {f for _i, f, lit in step_features(x["program"]) if lit is None} for w in ws: df[h][w] += 1 for f in fs: ff[h][f] += 1 for w in ws: hit[h][(w, f)] += 1 self.says = collections.defaultdict(set) # strict: a word accounts for the features it predicts best self.loose = collections.defaultdict(set) # loose: the words that can say a step for (w, f), _c in (hit[0] + hit[1]).items(): if R7.is_glue(w): continue if all(hit[h][(w, f)] >= SUPPORT and hit[h][(w, f)] / max(1, ff[h][f]) >= 0.02 and hit[h][(w, f)] / max(1, df[h][w]) >= 2 * ff[h][f] / max(1, n[h]) for h in (0, 1)): self.loose[f].add(w) self.strong = collections.defaultdict(set) # the judge's: a word that predicts the feature P >= 0.5 for (w, f), _c in (hit[0] + hit[1]).items(): if not R7.is_glue(w) and all(hit[h][(w, f)] >= SUPPORT and hit[h][(w, f)] / max(1, df[h][w]) >= 0.5 for h in (0, 1)): self.strong[f].add(w) cand = collections.defaultdict(dict) # word -> {feature: min over halves of P(feature | word)} for (w, f), _c in (hit[0] + hit[1]).items(): if R7.is_glue(w): continue ps = [] for h in (0, 1): c = hit[h][(w, f)] p_f = ff[h][f] / max(1, n[h]) if c < SUPPORT or c / max(1, df[h][w]) < max(0.2, 3 * p_f): break ps.append(c / max(1, df[h][w])) else: cand[w][f] = min(ps) for w, fs in cand.items(): best = collections.defaultdict(float) for f, p in fs.items(): best[family(f)] = max(best[family(f)], p) for f, p in fs.items(): # "born" says the date of birth, not the date of death if p >= 0.6 * best[family(f)]: self.says[f].add(w) self.words = set().union(*self.says.values()) if self.says else set() # kind words: a word says a concept when, in both halves, half the questions using it filter by that concept cdf, chit = [collections.Counter(), collections.Counter()], [collections.Counter(), collections.Counter()] for x in train: h = _half(x["question"]) ws_ = set(R4.norm(x["question"]).split()) cs_ = {str(st["inputs"][0]) for st in x["program"] if st["function"] == "FilterConcept" and st["inputs"]} for w in ws_: cdf[h][w] += 1 for c in cs_: if w not in R4.norm(c).split(): chit[h][(w, c)] += 1 self.concept_words = {} best = {} for (w, c), _n in (chit[0] + chit[1]).items(): if R7.is_glue(w) or len(w) < 3: continue ps = [chit[h][(w, c)] / max(1, cdf[h][w]) for h in (0, 1) if chit[h][(w, c)] >= SUPPORT] if len(ps) == 2 and min(ps) >= 0.5 and min(ps) > best.get(w, 0): best[w] = min(ps) self.concept_words[w] = c def _cache_dir(): try: import organs10 as O10 d = Path(O10.MADE) / "cache" except Exception: # noqa: BLE001 d = Path(os.environ.get("ORACLE7_STATE", ".")) / "cache" d.mkdir(parents=True, exist_ok=True) return d def _train_key(train): h = hashlib.sha256() h.update(str(len(train)).encode()) for x in train[:2000]: h.update(x["question"].encode("utf-8", "replace")) return h.hexdigest()[:16] class Coverage: def __init__(self, rd, clauses, train): import pickle self.rd, self.CL = rd, clauses if not hasattr(clauses, "reach"): clauses.reach = set() # the clause layer's recursion records reach; it may not have run yet key = _train_key(train) cache = _cache_dir() / ("coverage102_lex_%s.pickle" % key) try: self.lex = pickle.load(open(cache, "rb")) except Exception: # noqa: BLE001 self.lex = Lexicon(train) try: pickle.dump(self.lex, open(cache, "wb")) except Exception: # noqa: BLE001 pass self._train_ref = train # for the learned unit forms (unit_words) self.aliases = collections.defaultdict(set) # canonical -> written aliases (normalised) for (_kd, t), c in getattr(rd, "alias_canon", {}).items(): self.aliases[R4.norm(str(c))].add(t) try: # learned: the other ways training questions write a Find literal for canon, forms in self.entity_aliases().items(): self.aliases[R4.norm(canon)] |= forms except Exception: # noqa: BLE001 pass self._pv = {} self._curq = None self.closer = None try: # the learned closing (close_learn102): step order from training import close_learn102 as CLS self.closer = CLS.Closer(self, Path(__file__).resolve().parent / "data" / "step_order102.json") except Exception: # noqa: BLE001 self.closer = None try: # the learned word-to-step alignment (align_learn102.py) A = json.load(open(os.environ.get("O7_ALIGN") or Path(__file__).resolve().parent / "data" / "alignment102.json"))["p_feature_given_word"] except Exception: # noqa: BLE001 A = {} self.align_t = A self.align_w = collections.defaultdict(dict) # word -> {feature: P(feature | word)} for f, d in A.items(): for w, pr in d.items(): self.align_w[w][f] = pr self.lex.words |= set(self.align_w) self.why = collections.Counter() # where each question stopped self.why_close = collections.Counter() # why no shape closed self.why_left = collections.Counter() # the words the closest shape left self.why_words = collections.Counter() # what the judge found unexplained self.index = {} for lvl, P in clauses.P.items(): keys = [tm for tm in P if shape(tm) is not None] self.index[lvl] = (keys, np.stack([shape(tm) for tm in keys]) if keys else None) self.stats = collections.Counter() # ------------------------------------------------------------------ the judge DIRECTION_OF = {">": "up", "greater": "up", "largest": "up", "<": "down", "less": "down", "smallest": "down", "!=": "ne", "=": "eq"} def op_direction_mass(self, v, w): """P(a comparison of v's direction | w) summed over every OP feature of that direction in the learned alignment""" d = self.DIRECTION_OF.get(v) if d is None: return 0.0 cache = getattr(self, "_dir_mass", None) if cache is None: cache = self._dir_mass = {} if (d, w) not in cache: tot = 0.0 for f, ws_ in self.align_t.items(): if f.startswith("OP:") and self.DIRECTION_OF.get(f.rsplit(":", 1)[1]) == d: tot += ws_.get(w, 0.0) cache[(d, w)] = tot return cache[(d, w)] def unit_words(self): """store unit -> the words training questions write it with, learned: the word(s) after the same number in the question of a training pair whose program reads a quantity literal "N unit" (metre -> meters)""" if getattr(self, "_unit_words", None) is None: seen = collections.defaultdict(collections.Counter) for x in getattr(self, "_train_ref", None) or []: qn = " " + R4.norm(x["question"]) + " " for st in x["program"]: if st["function"] not in ("VerifyNum", "FilterNum", "QFilterNum"): continue lit = st["inputs"][0] if st["function"] == "VerifyNum" else (st["inputs"][1] if len(st["inputs"]) > 1 else None) m = re.fullmatch(r"([\d.,]+) (.+)", R4.norm(str(lit or ""))) if not m: continue for mm in re.finditer(r" " + re.escape(m.group(1)) + r" ((?:\w+ ){0,2}\w+)", qn): for n in (len(m.group(2).split()),): # as many words as the store unit cand = " ".join(mm.group(1).split()[:n]) if cand and cand != m.group(2) and cand.split()[0] not in ("or", "and", "in", "of", "than", "the", "a", "an", "is", "was"): seen[m.group(2)][cand] += 1 self._unit_words = {u: {w for w, c in ws.items() if c >= 2} for u, ws in seen.items()} best = {} for u, ws in seen.items(): for w, c in ws.items(): if c >= 2 and (w not in best or c > best[w][1]): best[w] = (u, c) self._unit_canon = {w: u for w, (u, _c) in best.items()} return self._unit_words def unit_canon(self): """written unit word(s) -> the store's unit, from unit_words""" self.unit_words() return self._unit_canon def concept_said(self, q, prog, i, concept): """the words that say an unwritten concept step: the learned alignment (person -> C:human), or, when no word does, the store itself when the filter keeps every item it was given (the concept already held; the step needs no word)""" words = q.split() said = {w for w in words if self.align_t.get("C:" + str(concept), {}).get(w, 0) >= 0.25} said |= {w for w in words if self.label_written(concept, w)} # the concept's content words written within a window cn = R4.norm(str(concept)) said |= {w for w in words if cn in R7.singulars(w)} # a single-word concept written in the plural (cities) if said: return said # both: the alignment's words and the label's try: dep = prog[i]["dependencies"][0] res = self.rd.exec_steps(copy.deepcopy(prog[:i + 1])) a, b = res[dep], res[i] if isinstance(a, tuple) and isinstance(b, tuple) and a[0] and set(a[0]) == set(b[0]): return {"(the concept holds of every item)"} except Exception: # noqa: BLE001 pass return set() STOP_EDGE = {"the", "a", "an", "of", "in", "on", "at", "to", "for", "and", "or", "is", "was", "are", "were", "which", "what", "who", "how", "many", "that", "with", "by", "from", "as", "its", "it", "this", "does", "did", "do", "has", "have"} def entity_aliases(self): """Find literal (as the store spells it) -> the n-grams (1-4 words) training questions write it with when they do not write it as spelled: co-occurring at least 3 times, standing for that literal in at least half of the n-gram's occurrences; cached beside the lexicon""" if getattr(self, "_ealias", None) is not None: return self._ealias import pickle train = getattr(self, "_train_ref", None) or [] cache = _cache_dir() / ("coverage102_ealias_%s.pickle" % _train_key(train)) try: self._ealias, self._ealias_map = pickle.load(open(cache, "rb")) return self._ealias except Exception: # noqa: BLE001 pass gram_total = collections.Counter() pair = collections.Counter() spell = {} for x in train: ws = R4.norm(x["question"]).split() grams = set() for a in range(len(ws)): for b in range(a + 1, min(len(ws), a + 4) + 1): if ws[a] in self.STOP_EDGE or ws[b - 1] in self.STOP_EDGE: continue grams.add(" ".join(ws[a:b])) for g in grams: gram_total[g] += 1 qn = " " + " ".join(ws) + " " lits = set() for st in x["program"]: if st["function"] == "Find": lit = R4.norm(str(st["inputs"][0])) if " " + lit + " " not in qn: lits.add(lit) spell[lit] = str(st["inputs"][0]) for lit in lits: for g in grams: if g in lit: continue # a piece of the label itself is not an alias (academy / award) pair[(lit, g)] += 1 out = collections.defaultdict(set) for (lit, g), c in pair.items(): if c >= 3 and c / max(1, gram_total[g]) >= 0.5: out[spell[lit]].add(g) self._ealias = dict(out) self._ealias_map = {} for canon, forms in self._ealias.items(): for g in forms: if g not in self._ealias_map or pair[(R4.norm(canon), g)] > pair[(R4.norm(self._ealias_map[g]), g)]: self._ealias_map[g] = canon try: pickle.dump((self._ealias, self._ealias_map), open(cache, "wb")) except Exception: # noqa: BLE001 pass return self._ealias def entity_alias_map(self): """written n-gram -> the Find literal it stands for (the strongest), from entity_aliases""" self.entity_aliases() return getattr(self, "_ealias_map", {}) or {} def _written(self, q, v): """the longest way the question writes v (itself, a learned alias, a plural, a learned unit form), or None""" if self._curq == q: # memoised per value within the question self._memo() k_ = str(v) if k_ not in self._ww: self._ww[k_] = self._written_raw(q, v) return self._ww[k_] return self._written_raw(q, v) def _written_raw(self, q, v): t = R4.norm(str(v)) forms = set() for f0 in {t} | self.aliases.get(t, set()): forms |= _forms(f0) m = re.fullmatch(r"([\d.,]+) (.+)", t) if m: for u in self.unit_words().get(m.group(2), set()) | _forms(m.group(2)): forms |= _forms(m.group(1) + " " + u) if t.startswith(("http ", "https ")): # a URL is written with or without its scheme (norm writes "http x") forms.add(t.split(" ", 1)[1]) for form in sorted(forms, key=len, reverse=True): if form and re.search(r"(?:^| )" + re.escape(form) + r"(?: |$)", q): return form return None def align(self, question, prog, template=None, strict=False): """(True, None) when every content word and every step account for each other; else (False, what is unexplained). template: the learned wording a released reader matched; its words were learned with this program, so they are accounted for, and only what no learned wording covers is judged""" q = R4.norm(question) words = q.split() covered = {w for w in str(template or "").split() if w.islower()} feats = step_features(prog) unsaid = [] litw = set() conw = set() # words that say an unwritten concept (its label or the alignment) fset = {f for _i, f, lit in feats if lit is None} for i, f, lit in feats: if lit is not None: form = self._written(q, lit) if form is not None and prog[i]["function"] not in ("Find", "FilterConcept") and \ (all(R7.is_glue(w) or w in YESNO or w in CL.OPEN or w in self.PRONOUNS for w in form.split()) or (len(form) < 2 and not form.isdigit())): form = None # a value written only as glue ("is"), a pronoun or one character is not a value the question gives fn_ = prog[i]["function"] if form is not None and fn_.endswith("Str") and re.fullmatch(r"[-+]?[\d.,]+|\d{4}-\d{2}-\d{2}", form): unsaid.append("%s takes a string, not %r" % (fn_, lit)) # a value is typed by the function that takes it elif form is not None and fn_.endswith(("Num", "Year", "Date")) and not re.search(r"\d", form): unsaid.append("%s takes a number or date, not %r" % (fn_, lit)) if form is not None and prog[i]["function"].startswith(("Verify", "Filter", "QFilter")) and not _num(form): names_ = [R4.norm(str(st_["inputs"][0])) for st_ in prog if st_["function"] == "Find" and st_["inputs"]] if any(form != nm_ and re.search(r"(?:^| )" + re.escape(form) + r"(?: |$)", nm_) for nm_ in names_): form = None # a piece of a name the program finds ("Patrick") is not a value if form is not None: litw |= set(form.split()) if form is None and prog[i]["function"] == "Find": loose = {w for w in words if self.label_written(lit, w)} # a name written loosely (bob Robers), the pools' own test if loose: covered |= loose litw |= loose continue if form is None and prog[i]["function"] == "FilterConcept": said_c = self.concept_said(q, prog, i, lit) if said_c: covered |= said_c conw |= said_c continue if form is None: unsaid.append("%s %r not written" % (prog[i]["function"], lit)) else: covered |= set(form.split()) for i, f, lit in feats: if lit is not None: continue if f.startswith("FN:") and f[3:] not in SAID_FN: continue if strict: bar = 0.15 if (f.startswith("FN:") or f.startswith("OP:")) else 0.3 # an operation word ("or", "greater") is rarer and sharper said = {w for w in words if self.align_t.get(f, {}).get(w, 0) >= bar} | (self.lex.strong.get(f, set()) & set(words)) if f.startswith("IN:") and f.count(":") == 1: said |= {w for w in words if self.says_word(f, f[3:], w)} # ONE definition, the flash's own said |= {w for w in words if self.best_available(f, w, fset)} # the word's best key among those the program has else: said = (self.lex.says.get(f, set()) | (self.lex.loose.get(f, set()) if f.startswith("IN:") else set())) & set(words) if f.startswith("FN:Verify") and words: rest_ = self.read_form(q)[1].split() if words[0] in YESNO or (rest_ and rest_[0] in YESNO) or (rest_[:2] == ["tell", "me"] and len(rest_) > 2 and rest_[2] in ("if", "whether")): said = said or {words[0] if words[0] in YESNO else (rest_[0] if rest_[0] in YESNO else rest_[2])} if template and not (f.startswith("FN:") and f[3:] in SAID_FN): said = said or {"(learned wording)"} # what is asked (count, or, select, verify) the question itself must say name = f.split(":", 1)[1] if f.startswith("IN:") and f.count(":") == 1 else None if name: form = self._written(q, name) if form: covered |= set(form.split()) said = said or {form} if not said and f.startswith("IN:") and f.count(":") == 2: v_ = f.rsplit(":", 1)[1] if strict and v_ in self.DIRECTION_OF and v_ != "=": said = {w for w in words if self.op_direction_mass(v_, w) >= 0.15 or self.OP_WORDS.get(w) == v_ or self.align_t.get("OP:" + f[3:], {}).get(w, 0) >= 0.15 or w in self.DIRECTION or (v_ == "!=" and w in ("not", "except", "neither", "nor"))} # the plain negation says "!=" if not said: unsaid.append("%s says nothing in the question" % f) # a comparison other than equality must be asked for if not said: continue # an equality constant: v8's bindings check it if not said: unsaid.append("%s says nothing in the question" % f) covered |= said for f in fset: if f.startswith("FN:") and f[3:] not in SAID_FN: continue # a read/filter/relate function says no content word by itself covered |= (self.lex.strong if strict else self.lex.says).get(f, set()) & set(words) covered |= {w for w in words if self.align_t.get(f, {}).get(w, 0) >= (0.4 if strict else 0.3)} if f.startswith("IN:") and f.count(":") == 1: for w in words: # a word that says a family of keys (born: date / place of birth) is covered by the if self.best_available(f, w, fset): # member the program uses when no key it says more strongly is in the program covered.add(w) for st in prog: # concepts and comparisons the program uses, by the alignment fn_ = st["function"] # a value is typed by the function that takes it (numeric literals are not step features) for k_ in LITERAL_AT.get(fn_, ()): if fn_ in ("Find", "FilterConcept") or k_ >= len(st["inputs"]) or not isinstance(st["inputs"][k_], str): continue v_ = R4.norm(st["inputs"][k_]) kt_ = self.key_value_types(self.step_key(prog, st)) if fn_.endswith("Str") and re.fullmatch(r"[-+]?[\d.,]+|\d{4}-\d{2}-\d{2}", v_) and kt_ and "string" not in kt_: unsaid.append("%s takes a string, not %r" % (fn_, st["inputs"][k_])) # unless the key itself holds strings ("717") elif fn_.endswith(("Num", "Year", "Date")) and not re.search(r"\d", v_): unsaid.append("%s takes a number or date, not %r" % (fn_, st["inputs"][k_])) elif kt_ and fn_.endswith(("Year", "Date")) and not (kt_ & {"year", "date"}): unsaid.append("%s reads a year or date; the key holds %s" % (fn_, sorted(kt_))) # the function family follows the key's type elif kt_ and fn_.endswith("Num") and "quantity" not in kt_: unsaid.append("%s reads a quantity; the key holds %s" % (fn_, sorted(kt_))) op_ = next((str(x_) for x_ in st["inputs"] if str(x_) in ("=", "!=", "<", ">")), None) if op_ == "=" and re.search(r"\d", v_): # the comparison the question wrote before the value must be the one used form_ = self._written(q, st["inputs"][k_]) m_ = re.search(r"(?:^| )" + re.escape(form_) + r"(?: |$)", q) if form_ else None if m_ is not None and self.value_op(q[:m_.start()]) != "=": unsaid.append("%s compares with =; the question says %s before %r" % (fn_, self.value_op(q[:m_.start()]), form_)) if st["function"].startswith("Select") and st["inputs"] and str(st["inputs"][-1]) not in ("greater", "less", "largest", "smallest"): unsaid.append("%s takes greater/less, not %r" % (st["function"], st["inputs"][-1])) if st["function"].startswith("Select") and st["inputs"]: # the key is one the direction word says, when it says any key dir_keys = {} for w in words: if w in self.DIRECTION: for f_, p_ in self.align_w.get(w, {}).items(): if f_.startswith("IN:") and f_.count(":") == 1 and p_ >= 0.15: dir_keys[f_[3:]] = max(dir_keys.get(f_[3:], 0.0), p_) if dir_keys and str(st["inputs"][0]) not in dir_keys: unsaid.append("%s compares %r; the question's comparative says %s" % (st["function"], st["inputs"][0], sorted(dir_keys)[:3])) if st["function"] == "FilterConcept" and st["inputs"]: covered |= {w for w in words if self.align_t.get("C:" + str(st["inputs"][0]), {}).get(w, 0) >= 0.25} for v in st["inputs"]: if isinstance(v, str) and v in ("=", "!=", "<", ">", "greater", "less", "largest", "smallest"): covered |= {w for w in words if self.align_t.get("OP:%s:%s" % (st["function"], v), {}).get(w, 0) >= 0.15} covered |= {w for w in words if self.op_direction_mass(v, w) >= 0.15} # "more" says the same comparison whichever function carries it if v in ("<", ">", "!=", "greater", "less", "largest", "smallest"): covered |= {w for w in words if w in self.OP_WORDS or w in self.DIRECTION or w in ("than", "or")} if False else set() asking = {a[4:] for a in R7.asking_words(question)} # only a word that carries meaning somewhere (it says some feature in training) can be left unexplained ops = set(R6.OPS) | set(R6.KEEPW) | {"or", "not", "nor", "neither", "except"} # operator words are always meaning if strict: # EVERY word the question writes is held to account, whether or not the lexicon knows it: names, rare words and # numbers must be used by a step; only glue, interrogatives, clause openers and discourse words are free for st in prog: for v in st["inputs"]: if isinstance(v, str): covered |= set(R4.norm(v).split()) covered |= self.DIRECTION if any(st["function"] in ("SelectAmong", "SelectBetween") for st in prog) else set() pf0 = {f for _i, f, lit in feats if lit is None and f.startswith("IN:") and f.count(":") == 1} labw = {w for w in words if any(self.label_written(f[3:], w) for f in pf0)} for f in pf0: # a key established by its label or a strong word covers its loose associates if any(self.label_written(f[3:], w) or self.says_word(f, f[3:], w) for w in words): covered |= self.lex.loose.get(f, set()) & set(words) for f in pf0: # a word between the content words of a window-written label is part of that phrase lab_ = R4.norm(f[3:]).replace("-", " ") content = [self._stem(t) for t in lab_.split() if not R7.is_glue(t) and len(t) > 2] if len(content) >= 2: idx = [k for k, x in enumerate(words) if self.label_written(f[3:], x) or self.align_t.get(f, {}).get(x, 0) >= 0.3 or (self._stem(x) in content and not R7.is_glue(x))] if len(idx) >= 2 and max(idx) - min(idx) <= 6: covered |= set(words[min(idx):max(idx) + 1]) labw |= set(words[min(idx):max(idx) + 1]) anchor = litw | labw for k, w in enumerate(words): # a kind word before a name is accounted when the store holds the item of that kind if k + 1 >= len(words) or (w in covered and w in conw): continue cs_ = [c_ for ph_, c_ in self.concept_phrases([w]) if ph_ == w] if cs_ and self.kind_of_named(prog, cs_[0], words, k): covered.add(w) conw.add(w) # strong evidence: the store confirms the kind inw = {x_ for st_ in prog for v_ in st_["inputs"] if isinstance(v_, str) for x_ in R4.norm(v_).split()} covered -= {w for w in words if _num(w) and w not in litw and w not in inw} # a number is accounted for only when a step writes it if not any(st["function"].startswith("Select") or any(str(v) in ("<", ">") for v in st["inputs"]) for st in prog): covered -= self.DIRECTION # a direction word is covered by a Select or comparison step, never by a key it happens to co-occur with for k, w in enumerate(words): # a word beside a written label or value with no key meaning of its own is part of that phrase if w not in covered and max([p_ for f_, p_ in self.align_w.get(w, {}).items() if f_.startswith(("IN:", "C:"))] + [0.0]) < 0.15 and \ ((k > 0 and words[k - 1] in anchor) or (k + 1 < len(words) and words[k + 1] in anchor)): covered.add(w) lead_ = q[:len(q) - len(self.read_form(q)[1])].split() # the lead-in before the first interrogative lead_free = {w for w in lead_ if max(self.align_w.get(w, {}).values(), default=0.0) < 0.15 and not _num(w)} left = [w for w in words if w not in covered and w not in lead_free and (not R7.is_glue(w) or w in ops or w in self.align_w) and w not in asking and (w not in CL.OPEN or w in ops or w in self.align_w) and w not in DISCOURSE and len(w) > 1] # a word whose strongest learned meaning is a key or concept the program never uses, and that nothing in the # program covers at half that mass, means a step the program does not take (subscribers -> number of subscribers) pf = {f for _i, f, lit in feats if lit is None} | {"C:" + str(st["inputs"][0]) for st in prog if st["function"] == "FilterConcept" and st["inputs"]} for w in words: if w in litw or w in left or w in asking or _num(w) or w in conw or w in labw: continue # a literal, a concept's word, a label's word or phrase: strong evidence if any(self.label_written(f[3:], w) or self.best_available(f, w, pf) or (self._stem(w) in {self._stem(t_) for t_ in R4.norm(f[3:]).replace("-", " ").split() if not R7.is_glue(t_) and len(t_) > 2} and self.align_t.get(f, {}).get(w, 0) >= 0.15) for f in pf if f.startswith("IN:") and f.count(":") == 1): continue # the program's own label is written with this word (death place) top = max(self.align_w.get(w, {}).items(), key=lambda kv: kv[1], default=(None, 0.0)) if top[0] and top[1] >= 0.5 and top[0] not in pf and (top[0].startswith("C:") or (top[0].startswith("IN:") and top[0].count(":") == 1)): if max([self.align_t.get(f, {}).get(w, 0.0) for f in pf] + [0.0]) < top[1] / 2: left.append(w) self.why_words[" " + top[0][:40]] += 1 else: left = [w for w in words if w not in covered and (w in self.lex.words or w in ops) and (not R7.is_glue(w) or w in ops) and w not in asking and not _num(w) and (w not in CL.OPEN or w in ops)] if unsaid or left: if strict: for w in set(left): self.why_words[w] += 1 for u in unsaid: self.why_words[" " + u.split(" says")[0].split(" not written")[0][:40]] += 1 return False, {"unexplained_words": left, "unsaid_steps": unsaid} return True, None # ------------------------------------------------------------------ the hole and its search def holes(self, q, frs): """stretches around the content words no verified fragment covers""" ws = q.split() offs, o = [], 0 for w in ws: offs.append(o) o += len(w) + 1 inside = [any(s <= offs[k] < e for s, e, _p in frs) for k in range(len(ws))] asking = {a[4:] for a in R7.asking_words(q)} bare = [k for k, w in enumerate(ws) if not inside[k] and not R7.is_glue(w) and w not in asking and w not in CL.OPEN] runs, cur = [], [] for k in bare: if cur and k - cur[-1] > 2: runs.append(cur) cur = [] cur.append(k) if cur: runs.append(cur) found_ends = sorted({e for _s, e, _k in self.rd.found(q)}) out = set() for r in runs: a, b = r[0], r[-1] starts = [p for p in range(max(0, a - BACK), a + 1) if ws[p] in CL.OPEN or p == a] ends = [b] + [m for m in range(b + 1, min(len(ws), b + 1 + AHEAD)) if offs[m] + len(ws[m]) in found_ends] for p in starts: for e in ends: cs, ce = offs[p], offs[e] + len(ws[e]) if ce - cs < len(q): out.add((cs, ce)) return sorted(out, key=lambda x: (x[0], -(x[1] - x[0]))) def recall(self, ctext, lvl): """patch readings of the stretch: the learned wording itself, else the nearest learned patches by HRR resonance""" pats = self.CL.stretch_readings(ctext, lvl) if pats: self.stats["patch exact"] += 1 return pats, True keys, M = self.index.get(lvl, ([], None)) if M is None: return [], False rd = self.rd rd.level2 = lvl found = rd.found(ctext) out, seen = [], set() for ch in rd.combos(found, 0, len(ctext) + 1, 50, must_start=None): tm, order = R4.delex(ctext, ch) v = shape(tm) if v is None: continue sims = np.real(M @ np.conj(v)) texts = rd.texts_of(order) for j in np.argsort(-sims)[:TOPK]: if sims[j] < MIN_COS or keys[j] in seen: continue seen.add(keys[j]) hit = self.CL.P[lvl][keys[j]] total = sum(hit.values()) for sj, n in hit.items(): spec = json.loads(sj) if n < 0.5 * total or R6.hidden_literal(spec["steps"]): continue steps = [] for s in spec["steps"]: ins = rd.fill_inputs(s["inputs"], texts) if ins is None: steps = None break steps.append({"function": s["function"], "dependencies": s["dependencies"], "inputs": ins}) if steps: out.append((steps, spec)) if out: self.stats["patch recalled"] += 1 return out, False def bases(self, rest): """every released reading of the rest, with the learned wording it matched""" out = [] try: _a, _d, r6 = self.rd.read(rest) out += [(tm, p) for tm, p in r6 if isinstance(p, list)] except Exception: # noqa: BLE001 pass try: _a, r7 = self.rd.read7(rest) out += [(tm, p) for tm, p in r7] except Exception: # noqa: BLE001 pass if not out: out = [("", p) for p in self.CL.base_readings(rest, 0)] return out # ------------------------------------------------------------------ every part visible, and the step between parts @staticmethod def _stem(w): return w[:5] if len(w) >= 5 else w DIRECTION = {"largest", "highest", "most", "biggest", "longest", "tallest", "oldest", "greatest", "heaviest", "latest", "smallest", "lowest", "least", "shortest", "youngest", "fewest", "lightest", "earliest", "longer", "taller", "larger", "bigger", "higher", "greater", "heavier", "older", "more", "shorter", "smaller", "lower", "less", "fewer", "lighter", "younger"} def label_df(self): """how many key and relation labels each label word (by stem) appears in, across the store""" if getattr(self, "_ldf", None) is None: kq = self.rd.kq labels = {x["key"] for e in kq.ents.values() for x in e.get("attributes", [])} labels |= {r for lst in kq.rel.values() for r, _d, _o, _q in lst} df = collections.Counter() for lab in labels: for t in {self._stem(t) for t in R4.norm(lab).split() if len(t) >= 3}: df[t] += 1 self._ldf = df return self._ldf def best_available(self, f, w, fset): """does word w say key f because f is the key it says most strongly among those the program has (>= 0.15)""" p_ = self.align_t.get(f, {}).get(w, 0.0) if p_ < 0.15: return False for g in fset: if g != f and g.startswith("IN:") and g.count(":") == 1 and self.align_t.get(g, {}).get(w, 0.0) > p_: return False return True def kind_of_named(self, prog, concept, words, k): """the item named right after word k (a Find literal of the program) is of this concept, by the store""" kq = self.rd.kq after = " ".join(words[k + 1:k + 7]) for st in prog: if st["function"] != "Find" or not st["inputs"]: continue nm = R4.norm(str(st["inputs"][0])) if not after.startswith(nm): continue if not hasattr(self, "_name_ids"): self._name_ids = collections.defaultdict(list) for i_, e_ in kq.ents.items(): self._name_ids[R4.norm(e_.get("name") or "")].append(i_) ids = self._name_ids.get(nm, [])[:3] try: if ids and kq.FilterConcept((ids, {}), concept)[0]: return True except Exception: # noqa: BLE001 pass return False def label_written(self, label, w): """the label itself is written with word w: whole, or its content words within a window in any order""" _sw, lw = self._memo() k_ = (label, w) if k_ not in lw: lw[k_] = self._label_written(label, w) return lw[k_] def _label_written(self, label, w): lab = R4.norm(label) if not (self._curq and lab): return False if w in lab.split() and re.search(r"(?:^| )" + re.escape(lab) + r"(?: |$)", self._curq): return True lab = lab.replace("-", " ") # not-for-profit is written "not for profit" content = [self._stem(t) for t in lab.split() if not R7.is_glue(t) and len(t) > 2] stems_w = {self._stem(w)} | {self._stem(f_) for f_ in R7.singulars(w)} if len(content) >= 2 and stems_w & set(content): qw = self._curq.split() qs = [{self._stem(x)} | {self._stem(f_) for f_ in R7.singulars(x)} for x in qw] # singular forms too (cities -> city) win = 5 + len(content) # the window grows with the label for k, x in enumerate(qw): if x == w and all(any(t in st_ for st_ in qs[max(0, k - win):k + win + 1]) for t in content): return True return False def _memo(self): """the per-question memo of says_word and label_written (pure in the question)""" if getattr(self, "_memo_q", "") != self._curq or not hasattr(self, "_ww"): self._memo_q, self._sw, self._lw, self._ww = self._curq, {}, {}, {} return self._sw, self._lw def says_word(self, feature, label, w): """does word w say this key or relation: a word the lexicon learned for it, or a DISTINCTIVE word of its label (in at most 3 labels across the store); a superlative or comparative says only the direction""" sw, _lw = self._memo() k_ = (feature, label, w) if k_ not in sw: sw[k_] = self._says_word(feature, label, w) return sw[k_] def _says_word(self, feature, label, w): if w in self.DIRECTION: return False if getattr(self, "_say_min", None) is None: self._say_min = float(os.environ.get("O7_SAY_MIN", "0.3")) if self.align_t.get(feature, {}).get(w, 0) >= self._say_min or w in self.lex.says.get(feature, ()): return True lab = R4.norm(label) if self._curq and lab and w in lab.split() and re.search(r"(?:^| )" + re.escape(lab) + r"(?: |$)", self._curq): return True # the whole label is written in the question if self._curq and lab: if self.label_written(label, w): # the label's content words written in any order within a window (one definition) return True content = {self._stem(t) for t in lab.replace("-", " ").split() if not R7.is_glue(t) and len(t) > 2} if self._stem(w) in content and self.align_t.get(feature, {}).get(w, 0) >= 0.15: return True # a content word of the label by stem that carries learned mass for it ("released") return False def prop_vec(self, label): """a key's or relation's HRR vector: its label's words and the words learned to say it, superposed""" if label not in self._pv: toks = {self._stem(t) for t in R4.norm(label).split() if len(t) >= 3} toks |= {self._stem(w) for w in self.lex.says.get("IN:" + label, set())} v = np.sum([osub_seed("o7w:" + t) for t in toks], axis=0) if toks else None self._pv[label] = v / np.linalg.norm(v) if v is not None else None return self._pv[label] OP_WORDS = {"before": "<", "earlier": "<", "prior": "<", "until": "<", "preceding": "<", "after": ">", "later": ">", "since": ">", "subsequent": ">", "following": ">", "different": "!=", "unlike": "!=", "greater": ">", "more": ">", "higher": ">", "larger": ">", "bigger": ">", "over": ">", "above": ">", "exceeds": ">", "less": "<", "fewer": "<", "lower": "<", "smaller": "<", "under": "<", "below": "<"} def value_op(self, before): """the comparison the words just before a written value give it ("before 1966", "greater than 7800", "not equal to")""" w = before.split()[-4:] if "not" in w or ("other" in w and "than" in w) or "different" in w or "unlike" in w: return "!=" for x in reversed(w): if x in self.OP_WORDS: return self.OP_WORDS[x] ops = [(pr, f.rsplit(":", 1)[1]) for f, pr in self.align_w.get(x, {}).items() if f.startswith("OP:Filter") and pr >= 0.4 and f.rsplit(":", 1)[1] in ("<", ">", "!=")] if ops: return max(ops)[1] return "=" def units(self): """every unit the store's quantities use""" if getattr(self, "_units", None) is None: u = set() for e in self.rd.kq.ents.values(): for x in e.get("attributes", []): v = x["value"] if isinstance(v, dict) and v.get("unit") and v.get("unit") != "1": u.add(R4.norm(str(v["unit"]))) self._units = u return self._units @staticmethod def vkey(v): """a value's canonical form: lower case, digit grouping and spacing inside identifiers removed""" t = R4.norm(str(v)).replace(",", "") t = re.sub(r"^https?://", "", t).rstrip("/") # a URL with or without its scheme is one value t = re.sub(r"(?<=\d) (?=\d)", "", t) # 0000 0001 1496 3797 and 0000000114963797 are one t = re.sub(r"\.0+$", "", t) return t def threshold(self): """the learned score threshold (data/flash_threshold.json, chosen on development for precision >= 0.95 on additions)""" if os.environ.get("O7_FLASH_THRESHOLD"): # development only: measure every scored answer; the file is the law return float(os.environ["O7_FLASH_THRESHOLD"]) if getattr(self, "_thr", None) is None: try: self._thr = float(json.load(open(Path(__file__).resolve().parent / "data" / "flash_threshold.json"))["threshold"]) except Exception: # noqa: BLE001 self._thr = float(os.environ.get("O7_FLASH_MIN_SCORE", "0")) return self._thr def program_score(self, q, prog): """how strongly the question's words say the program's steps: the mean over its non-literal features of the best alignment probability any question word gives that feature (1.0 for a whole label written)""" words = set(q.split()) tot, n = 0.0, 0 for _i, f, lit in step_features(prog): if lit is not None or (f.startswith("FN:") and f[3:] not in SAID_FN): continue best = max([self.align_t.get(f, {}).get(w, 0.0) for w in words] + [0.0]) tot += best n += 1 for st in prog: if st["function"] == "FilterConcept" and st["inputs"]: tot += max([self.align_t.get("C:" + str(st["inputs"][0]), {}).get(w, 0.0) for w in words] + [0.5]) n += 1 return tot / n if n else 0.0 def key_types(self): """the store's type of each attribute key (majority)""" if getattr(self, "_ktypes", None) is None: c = collections.defaultdict(collections.Counter) for e in self.rd.kq.ents.values(): for x in e.get("attributes", []): v = x["value"] c[x["key"]][v.get("type") if isinstance(v, dict) else "string"] += 1 self._ktypes = {k: cnt.most_common(1)[0][0] for k, cnt in c.items()} return self._ktypes def type_mass(self, w): """alignment mass of a word summed by the store's type of the keys it says -> {type: mass}""" out = collections.Counter() kt = self.key_types() for f, pr in self.align_w.get(w, {}).items(): if f.startswith("IN:") and f[3:] in kt: out[kt[f[3:]]] += pr return out def values_from_store(self, question, q, P): """every written span (up to 6 words) whose canonical form is a value the store holds, outside the parts; as the store stores it (its own string), with the words it is written as -> [(start, end, value, words)]""" vix = self.value_index() ws = q.split() offs, o = [], 0 for w in ws: offs.append(o) o += len(w) + 1 out, seen = [], set() for a_ in range(len(ws)): for b_ in range(min(len(ws), a_ + 6), a_, -1): s1, e1 = offs[a_], offs[b_ - 1] + len(ws[b_ - 1]) if any(x <= s1 < y for x, y, _pr, _i in P if (y - x) > (e1 - s1)): continue if any(x <= s1 and e1 <= y for x, y, pr, _i in P if pr and pr[0]["function"] == "Find"): continue # a named entity is never a value t = self.vkey(q[s1:e1]) written = b_ == a_ + 1 and re.fullmatch(r"-?\d[\d,]*(?:\.\d+)?|\d{4}-\d{2}-\d{2}|\d{4} \d{2} \d{2}", q[s1:e1]) is not None if not t or (t not in vix and not written) or (s1, e1) in seen or any(x <= s1 and e1 <= y for x, y in seen): continue stored = min(self._vstore.get(t, {None}), key=str) if t in vix else None if stored is None: # a written number or date the store does not hold: as written m = re.search(re.escape(q[s1:e1]).replace("\ ", r"\W+"), question, re.I) stored = question[m.start():m.end()] if m else q[s1:e1] seen.add((s1, e1)) out.append((s1, e1, stored, set(ws[a_:b_]))) return out def value_index(self): """built once: every attribute value as written (normalised) -> {key: items holding it}; cached after the first build""" if getattr(self, "_vix", None) is not None: return self._vix import pickle kq = self.rd.kq cache = _cache_dir() / ("coverage102_values_%d.pickle" % len(kq.ents)) try: vix, self._vkind, self._vstore = pickle.load(open(cache, "rb")) self._vix = collections.defaultdict(lambda: collections.defaultdict(set), {k: collections.defaultdict(set, v) for k, v in vix.items()}) return self._vix except Exception: # noqa: BLE001 pass vix = collections.defaultdict(lambda: collections.defaultdict(set)) self._vkind = {} self._vstore = {} for i, e in kq.ents.items(): for x in e.get("attributes", []): v = x["value"] raw = v.get("value") if isinstance(v, dict) else v t = self.vkey(raw) if not t or len(t) > 80: continue vix[t][x["key"]].add(i) self._vkind[(t, x["key"])] = v.get("type") if isinstance(v, dict) else "string" self._vstore.setdefault(t, set()).add(str(raw)) self._vix = vix try: pickle.dump(({k: dict(v) for k, v in vix.items()}, self._vkind, self._vstore), open(cache, "wb")) except Exception: # noqa: BLE001 pass return vix def parts(self, q, frs): """EVERY verified part the question holds: every fragment the reader verified (both levels, nested, composed), and every name or concept it writes as a one-step part. -> [(start, end, program, ids)]""" rd = self.rd progs = [(s0, e0, p) for s0, e0, p in frs] rd.level2 = True for s0, e0, kinds in rd.found(q): t = q[s0:e0] if "E" in kinds: progs.append((s0, e0, [{"function": "Find", "dependencies": [], "inputs": [rd.spell.get(rd.alias_canon.get(("E", t), t), t) if hasattr(rd, "spell") else t]}])) if "C" in kinds: c = rd.alias_canon.get(("C", t), t) progs.append((s0, e0, [{"function": "FindAll", "dependencies": [], "inputs": []}, {"function": "FilterConcept", "dependencies": [0], "inputs": [c]}])) vix = self.value_index() qws = q.split() spans = {(s0, e0) for s0, e0, _k in rd.found(q)} offs_, o_ = [], 0 for w in qws: offs_.append(o_) o_ += len(w) + 1 for a_ in range(len(qws)): # every written stretch of up to 6 words may be a stored value for b_ in range(a_ + 1, min(len(qws), a_ + 6) + 1): spans.add((offs_[a_], offs_[b_ - 1] + len(qws[b_ - 1]))) for s0, e0 in sorted(spans): t = q[s0:e0] for key, ids_ in vix.get(self.vkey(t), {}).items(): keyed = any(self.says_word("IN:" + key, key, w) for w in qws if w not in t.split()) distinctive = len(t) >= 5 and bool(re.search(r"[\d\W_]", t.replace(" ", ""))) if not keyed and (len(ids_) > 3 or not distinctive): continue # an unkeyed value must name its item alone fn = {"quantity": "FilterNum", "year": "FilterYear", "date": "FilterDate"}.get(self._vkind.get((t, key)), "FilterStr") op = self.value_op(q[:s0]) if fn != "FilterStr" else "=" ins = [key, t, op] if fn != "FilterStr" else [key, t] progs.append((s0, e0, [{"function": "FindAll", "dependencies": [], "inputs": []}, {"function": fn, "dependencies": [0], "inputs": ins}])) # "or" between two parts: their union is a part (the knowledge base's Or) base = list(progs) for s0, e0, p in base: for s1, e1, p2 in base: if s1 > e0 and q[e0:s1].strip() in ("or", "or the", "or a", "or have", "or has", "or have the", "or has the", "or have a", "or has a", "or is", "or are", "or was", "or were"): p2s = [dict(st, dependencies=[x + len(p) for x in st["dependencies"]]) for st in p2] progs.append((s0, e1, p + p2s + [{"function": "Or", "dependencies": [len(p) - 1, len(p) + len(p2) - 1], "inputs": []}])) names = [(s0, e0) for s0, e0, p in progs if len(p) == 1 and p[0]["function"] == "Find"] progs = [(s0, e0, p) for s0, e0, p in progs if not (len(p) == 1 and p[0]["function"] == "Find" and any( a_ <= s0 and e0 <= b_ and (a_, b_) != (s0, e0) for a_, b_ in names))] out, seen = [], set() for s0, e0, p in progs: key = (s0, e0, json.dumps(p)) if key in seen: continue seen.add(key) try: res = rd.exec_steps(copy.deepcopy(p)) except Exception: # noqa: BLE001 res = None if res and isinstance(res[-1], tuple) and res[-1][0] and len(res[-1][0]) <= 400: out.append((s0, e0, p, frozenset(res[-1][0]))) return out def value_written(self, q, nodes, key): """the question writes this attribute's value for one of these items: it is a condition the answer meets, so reading it back is never the answer ("which town has the postal code 06880" does not ask for a postal code)""" kq = self.rd.kq for i in list(nodes)[:60]: for x in (kq.ents.get(i) or {}).get("attributes", []): if x["key"] == key: v = x["value"].get("value") if isinstance(x["value"], dict) else x["value"] t = R4.norm(str(v)) if t and re.search(r"(?:^| )" + re.escape(t) + r"(?: |$)", q): return True return False def flash_index(self): """built once: every item a number, and every relation (with its direction) an adjacency array in compressed-row form, so growth along a relation is one vector operation over the whole store; cached on disk after the first build""" if getattr(self, "_flash", None) is not None: return self._flash kq = self.rd.kq cache = _cache_dir() / ("coverage102_flash_%d_%d.npz" % (len(kq.ents), sum(len(v) for v in kq.rel.values()))) if cache.exists(): try: z = np.load(cache, allow_pickle=True) ids = list(z["ids"]) keys = list(z["keys"]) csr = {tuple(k.split("\x00")): (z["indptr_%d" % i], z["dst_%d" % i]) for i, k in enumerate(keys)} self._flash = {"ids": ids, "num": {i: n for n, i in enumerate(ids)}, "N": len(ids), "csr": csr} return self._flash except Exception: # noqa: BLE001 pass ids = sorted(set(kq.ents) | set(kq.concepts) | set(kq.rel)) num = {i: n for n, i in enumerate(ids)} edges = collections.defaultdict(lambda: ([], [])) for i, lst in kq.rel.items(): for r, d, o_, _q in lst: if o_ in num: e = edges[(r, d)] e[0].append(num[i]) e[1].append(num[o_]) N = len(ids) csr = {} for key, (src, dst) in edges.items(): src, dst = np.asarray(src, dtype=np.int64), np.asarray(dst, dtype=np.int64) order = np.argsort(src, kind="stable") src, dst = src[order], dst[order] indptr = np.zeros(N + 1, dtype=np.int64) np.add.at(indptr, src + 1, 1) csr[key] = (np.cumsum(indptr), dst) self._flash = {"ids": ids, "num": num, "N": N, "csr": csr} try: keys = list(csr) np.savez(cache, ids=np.array(ids, dtype=object), keys=np.array(["\x00".join(k) for k in keys], dtype=object), **{"indptr_%d" % i: csr[k][0] for i, k in enumerate(keys)}, **{"dst_%d" % i: csr[k][1] for i, k in enumerate(keys)}) except Exception: # noqa: BLE001 pass return self._flash @staticmethod def _step(frontier, indptr, dst, N): """the flash along one relation: every lit item lights everything it relates to, at once""" rows = np.flatnonzero(frontier) if rows.size == 0: return np.zeros(N, dtype=bool) starts, ends = indptr[rows], indptr[rows + 1] lens = ends - starts tot = int(lens.sum()) out = np.zeros(N, dtype=bool) if tot == 0: return out offs = np.repeat(starts - np.concatenate(([0], np.cumsum(lens)[:-1])), lens) + np.arange(tot) out[dst[offs]] = True return out def part_words(self, ws, idx, prog): """the words a part accounts for: its span, and for a value part the words that said its key; a union ("or") owns only what its two sides say and "or" (UNION_OWN), never the words written between them""" if any(st["function"] == "Or" for st in prog): own = {"or"} for st in prog: for v in st["inputs"]: if isinstance(v, str) and v: own |= set(R4.norm(v).split()) & set(ws) if st["function"].startswith("Filter") and st["function"] != "FilterConcept" and st["inputs"]: own |= {w for w in ws if self.says_word("IN:" + st["inputs"][0], st["inputs"][0], w)} return own own = {ws[k] for k in idx} if prog and prog[0]["function"] == "Find": own |= {w for w in ws if w in ("named", "called", "titled", "name", "entitled")} for st in prog: if st["function"] in ("FilterNum", "FilterYear", "FilterDate") and len(st["inputs"]) > 2 and st["inputs"][2] != "=": own |= {w for w in ws if w in self.OP_WORDS or w in ("than", "not", "equal", "other", "to")} for st in prog: if st["function"].startswith("Filter") and st["function"] != "FilterConcept" and st["inputs"]: key = st["inputs"][0] own |= {w for w in ws if self.says_word("IN:" + key, key, w)} return own COMPARE_UP = {"longer", "taller", "larger", "bigger", "higher", "greater", "heavier", "older", "more", "wider", "deeper", "later", "faster", "longest", "highest", "largest", "greatest", "better"} COMPARE_DOWN = {"shorter", "smaller", "lower", "less", "fewer", "lighter", "younger", "narrower", "shallower", "earlier", "slower", "worse"} def compare(self, question, q, frs, ws, offs): """which of two things has more or less of a quantity: two single-item parts, a key the remaining words name, and the direction the comparative word gives -> SelectBetween, run exactly and judged""" up = self.COMPARE_UP & set(ws) down = self.COMPARE_DOWN & set(ws) if " or " not in " %s " % q or bool(up) == bool(down): return [] op = "greater" if up else "less" rd, kq = self.rd, self.rd.kq P = [x for x in self.parts(q, frs) if len(x[3]) == 1] res = [] for a in range(len(P)): for b in range(a + 1, len(P)): A, B = P[a], P[b] if not (A[1] <= B[0] or B[1] <= A[0]) or A[3] == B[3]: continue ia, ib = next(iter(A[3])), next(iter(B[3])) ka = {x["key"] for x in (kq.ents.get(ia) or {}).get("attributes", [])} kb = {x["key"] for x in (kq.ents.get(ib) or {}).get("attributes", [])} for k in ka & kb: said = {w for w in ws if self.says_word("IN:" + k, k, w)} if not said or not self.same_unit({ia, ib}, k): continue pa = copy.deepcopy(A[2]) pb = [dict(st, dependencies=[x + len(pa) for x in st["dependencies"]]) for st in copy.deepcopy(B[2])] pp = pa + pb + [{"function": "SelectBetween", "dependencies": [len(pa) - 1, len(pa) + len(pb) - 1], "inputs": [k, op]}] ok, _why = self.align(question, pp, None, strict=True) if not ok or not self.kind_holds(pp, self.asked_kind(q)): continue try: ans = rd.run(copy.deepcopy(pp)) except Exception: # noqa: BLE001 ans = None if ans: res.append((str(ans), pp)) return res YESNO_OPEN = ("is", "are", "was", "were", "does", "do", "did", "has", "have", "had") SUPER_UP = {"largest", "highest", "most", "biggest", "longest", "tallest", "oldest", "greatest", "heaviest", "latest"} SUPER_DOWN = {"smallest", "lowest", "least", "shortest", "youngest", "fewest", "lightest", "earliest"} WHEN_Q = ("point in time", "start time", "end time", "date") def closures2(self, question, q, frs, ws, offs): """the forms the flash closes beside name, count and attribute: yes/no, the relation between two items, the qualifier of an attribute statement or of a relation, and the superlative. Each is the knowledge base's own operation, run exactly and judged; every content word must be accounted for (the judge).""" rd, kq = self.rd, self.rd.kq P = self.parts(q, frs) singles = [x for x in P if len(x[3]) == 1 and x[2][0]["function"] == "Find"] res = [] deadline = SB.deadline() def run(pp): if len(res) >= 8 or SB.spent() > deadline: return for st in pp: if st["function"] == "Find": nm = str(st["inputs"][0]) if nm[:1].isupper() and nm not in question and nm.lower() in question.lower(): return ok, _why = self.align(question, pp, None, strict=True) if not ok or not self.kind_holds(pp, self.asked_kind(q)): return try: ans = rd.run(copy.deepcopy(pp)) except Exception: # noqa: BLE001 ans = None if ans is not None and str(ans) not in ("", "None"): res.append((str(ans), pp)) def attrs(i): return (kq.ents.get(i) or {}).get("attributes", []) def sval(v): return R4.norm(str(v.get("value") if isinstance(v, dict) else v)) def written_values(exclude): out = [] for s0, e0, kinds in rd.found(q): if any(a <= s0 < b for a, b in exclude): continue if {"V", "N"} & set(kinds) or re.fullmatch(r"\d[\d,.]*|\d{4}-\d{2}-\d{2}", q[s0:e0]): m = re.search(re.escape(q[s0:e0]).replace("\\ ", r"\W+"), question, re.I) # as the question writes it out.append((s0, e0, question[m.start():m.end()] if m else q[s0:e0])) return out # yes / no: "is the of ?", "did have a of ?" if ws and ws[0] in self.YESNO_OPEN and not (" or " in " %s " % q and (self.COMPARE_UP | self.COMPARE_DOWN) & set(ws)): conds = [(a_, b_) for a_, b_, pr, _i in P if any(st["function"].startswith("Filter") and st["function"] != "FilterConcept" for st in pr)] for s0, e0, pa, ida in singles: i = next(iter(ida)) for s1, e1, v in written_values([(s0, e0)] + conds): after = q[e1:].split()[:1] if after and re.fullmatch(r"[\d.,]+", v): scale = {"thousand": 1e3, "million": 1e6, "billion": 1e9}.get(after[0]) unit = after[0][:-1] if after[0].endswith("s") and len(after[0]) > 3 else after[0] if scale: # "7 million" is 7000000 try: v = ("%f" % (float(v.replace(",", "")) * scale)).rstrip("0").rstrip(".") except ValueError: pass elif unit in self.units() or after[0] in self.units(): v = v + " " + (unit if unit in self.units() else after[0]) # only a unit the store uses elif self.unit_canon().get(after[0]) or self.unit_canon().get(unit): v = v + " " + (self.unit_canon().get(after[0]) or self.unit_canon().get(unit)) # a learned written form of a store unit for x in attrs(i): k = x["key"] if not any(self.says_word("IN:" + k, k, w) for w in ws): continue t = (x["value"] or {}).get("type") if isinstance(x["value"], dict) else "string" fn = {"quantity": "VerifyNum", "year": "VerifyYear", "date": "VerifyDate"}.get(t, "VerifyStr") ins = [v] if fn == "VerifyStr" else [v, self.value_op(q[:s1])] run(copy.deepcopy(pa) + [{"function": "QueryAttr", "dependencies": [len(pa) - 1], "inputs": [k]}, {"function": fn, "dependencies": [len(pa)], "inputs": ins}]) return res # the relation between two items, and the qualifier of that relation for a in range(len(singles)): for b in range(len(singles)): if a == b: continue A, B = singles[a], singles[b] if not (A[1] <= B[0] or B[1] <= A[0]): continue ia, ib = next(iter(A[3])), next(iter(B[3])) pa = copy.deepcopy(A[2]) pb = [dict(st, dependencies=[x + len(pa) for x in st["dependencies"]]) for st in copy.deepcopy(B[2])] if a < b and {"relation", "relationship", "connection", "related", "relate", "association", "associated", "connected"} & set(ws): run(pa + pb + [{"function": "QueryRelation", "dependencies": [len(pa) - 1, len(pa) + len(pb) - 1], "inputs": []}]) for r, d, o_, qual in kq.rel.get(ia, ()): if o_ != ib or d != "forward" or not qual: continue for qk in qual: said = any(self.says_word("IN:" + qk, qk, w) for w in ws) or (ws[0] == "when" and qk in self.WHEN_Q) if said: run(pa + pb + [{"function": "QueryRelationQualifier", "dependencies": [len(pa) - 1, len(pa) + len(pb) - 1], "inputs": [r, qk]}]) # the qualifier of an attribute statement: "in what year did have a of ?" for s0, e0, pa, ida in singles: i = next(iter(ida)) vals = {sval(x["value"]): x for x in attrs(i)} for s1, e1, v in written_values([(s0, e0)]): x = vals.get(R4.norm(v)) if not x or not x.get("qualifiers"): continue for qk in x["qualifiers"]: said = any(self.says_word("IN:" + qk, qk, w) for w in ws) or (ws[0] == "when" and qk in self.WHEN_Q) if said: raw = x["value"].get("value") if isinstance(x["value"], dict) else x["value"] run(copy.deepcopy(pa) + [{"function": "QueryAttrQualifier", "dependencies": [len(pa) - 1], "inputs": [x["key"], str(raw) if not isinstance(raw, str) else raw, qk]}]) # the superlative over a set: "which has the largest ?" up, down = self.SUPER_UP & set(ws), self.SUPER_DOWN & set(ws) if bool(up) != bool(down): op = "largest" if up else "smallest" for s0, e0, pa, ida in P: if len(ida) < 2 or len(ida) > 400 or len(pa) < 2: continue # the ranked set must be defined by its own words (a grown part) keys = {x["key"] for i in list(ida)[:60] for x in attrs(i)} for k in keys: if any(self.says_word("IN:" + k, k, w) for w in ws) and self.same_unit(ida, k): run(copy.deepcopy(pa) + [{"function": "SelectAmong", "dependencies": [len(pa) - 1], "inputs": [k, op]}]) return res def same_unit(self, ids, key): """every value of this key held by these items has one unit (or none has a unit)""" kq = self.rd.kq units = set() for i in ids: for x in (kq.ents.get(i) or {}).get("attributes", []): if x["key"] == key: v = x["value"] units.add(v.get("unit") if isinstance(v, dict) else None) return len(units) <= 1 def asked_kind(self, q): """the kind of thing the question asks for, if it names one: the concept right after "what"/"which" (or "which one of the"/"among the" for a superlative), in its singular form""" kq = self.rd.kq ws = q.split() starts = [] if ws and ws[0] in ("who", "whom") and "human" in kq.cname: return "human" # who asks for a person if ws and ws[0] in ("what", "which"): k = 1 while k < len(ws) and ws[k] in ("one", "of", "the", "is", "was", "are", "were", "a", "an", "among"): k += 1 starts.append(k) for k, w in enumerate(ws): if w == "among": starts.append(k + 2 if k + 1 < len(ws) and ws[k + 1] == "the" else k + 1) if w == "many" and k > 0 and ws[k - 1] == "how": starts.append(k + 1) # "how many ": the counted things are of that kind if w == "number" and k + 1 < len(ws) and ws[k + 1] == "of": starts.append(k + 2) # "the number of " phrases = dict(self.concept_phrases(ws)) # the same resolver the parts use (name, alias, singular, learned) for k in starts: # a concept whose content stems all stand in the window, before any single word lc = self.loose_concepts(ws, k, 6) if lc: return lc[0] for k in starts: for j in range(k, min(len(ws), k + 6)): # the earliest concept phrase within six words of the opening, for n in range(min(5, len(ws) - j), 0, -1): # the longest first; a longer phrase starting a word later beats a single word t = " ".join(ws[j:j + n]) if t in phrases: if n == 1 and j + 1 < len(ws): for n2 in range(min(5, len(ws) - j - 1), 1, -1): t2 = " ".join(ws[j:j + 1 + n2]) if t2 in phrases: return phrases[t2] return phrases[t] return None PRONOUNS = {"he", "she", "it", "they", "him", "her", "them", "his", "hers", "its", "their", "theirs", "you", "we", "i", "me", "us"} def branch_kinds(self, pp, i): """the concept of the last FilterConcept on each branch feeding step i (through And / Or); None for a branch without one""" st = pp[i] if st["function"] in ("And", "Or"): out = [] for d in st["dependencies"]: out += self.branch_kinds(pp, d) return out j = i while j is not None: s_ = pp[j] if s_["function"] == "FilterConcept" and s_["inputs"]: return [str(s_["inputs"][0])] if s_["function"] in ("And", "Or"): return self.branch_kinds(pp, j) j = s_["dependencies"][0] if s_["dependencies"] else None return [None] def loose_concepts(self, ws, k, width): """concepts with two or more content stems all written within ws[k:k+width] (singular forms too), longest label first""" kq = self.rd.kq if not hasattr(self, "_cstems"): idx = collections.defaultdict(list) for cn in kq.cname: cs = tuple(sorted({self._stem(t) for t in R4.norm(cn).replace("-", " ").split() if not R7.is_glue(t) and len(t) > 2})) if len(cs) >= 2: for c_ in cs: idx[c_].append((cs, cn)) self._cstems = idx win = ws[k:k + width] stems = set() for w in win: stems.add(self._stem(w)) stems |= {self._stem(f_) for f_ in R7.singulars(w)} out = [] for st_ in stems: for cs, cn in self._cstems.get(st_, ()): if len(cs) <= len(win) and all(c_ in stems for c_ in cs) and cn not in out: out.append(cn) return sorted(out, key=lambda c: -len(c)) def kind_within(self, concept, asked): """is concept the asked kind or one of its descendants, by the store""" if concept == asked: return True ca = {self._stem(t) for t in R4.norm(str(asked)).replace("-", " ").split() if not R7.is_glue(t) and len(t) > 2} cc = {self._stem(t) for t in R4.norm(str(concept)).replace("-", " ").split() if not R7.is_glue(t) and len(t) > 2} if ca and ca <= cc: return True # by its own label: a "city of Pennsylvania" is a city kq = self.rd.kq try: cs = kq.descendants(kq.cname.get(asked, set())) return bool(kq.cname.get(concept, set()) & cs) except Exception: # noqa: BLE001 return False def key_value_types(self, key): """the value types a key holds in the store (string / quantity / year / date), built once; empty when unknown""" if key is None: return set() if not hasattr(self, "_kvtypes"): kt = collections.defaultdict(set) for e in self.rd.kq.ents.values(): for x in e.get("attributes", []): v = x["value"] kt[x["key"]].add(v.get("type", "string") if isinstance(v, dict) else "string") for qk, qv in (x.get("qualifiers") or {}).items(): for q_ in (qv if isinstance(qv, list) else [qv]): kt[qk].add(q_.get("type", "string") if isinstance(q_, dict) else "string") for lst in self.rd.kq.rel.values(): for _r, _d, _o, qq in lst: for qk, qv in (qq or {}).items(): for q_ in (qv if isinstance(qv, list) else [qv]): kt[qk].add(q_.get("type", "string") if isinstance(q_, dict) else "string") self._kvtypes = dict(kt) return self._kvtypes.get(key, set()) @staticmethod def step_key(prog, st): """the key a filter or verify step reads: its own first input, or the QueryAttrs key up a Verifys chain""" fn = st["function"] if fn.startswith(("Filter", "QFilter")) and fn != "FilterConcept" and st["inputs"]: return str(st["inputs"][0]) if fn.startswith("Verify"): j = st["dependencies"][0] if st["dependencies"] else None while j is not None: s_ = prog[j] if s_["function"].startswith("QueryAttr") and s_["inputs"]: return str(s_["inputs"][0]) j = s_["dependencies"][0] if s_["dependencies"] else None return None def kind_holds(self, pp, concept): """every item the answer is drawn from is of the asked kind; a stored attribute value is never a thing of a kind""" fin = pp[-1]["function"] if concept is not None and fin in ("QueryAttr", "QueryAttrQualifier", "QueryRelationQualifier"): return False if concept is None or fin not in ("What", "SelectAmong", "SelectBetween", "Count"): return True rd = self.rd try: if fin == "SelectBetween": sets = [] for d in pp[-1]["dependencies"]: sub = rd.exec_steps(copy.deepcopy(pp[:d + 1])) sets.append(sub[-1] if sub else None) else: sub = rd.exec_steps(copy.deepcopy(pp[:-1]), allow_empty=(fin == "Count")) sets = [sub[-1] if sub else None] for st in sets: if not st or not isinstance(st, tuple): return False if not st[0]: if fin == "Count": # a count of nothing: the kind the program filtered by must be the asked kind (structural) for d in pp[-1]["dependencies"]: for bk in self.branch_kinds(pp, d): if bk is not None and not self.kind_within(bk, concept): return False continue return False kept = rd.kq.FilterConcept(st, concept) if len(kept[0]) != len(st[0]): bks = [bk for d in pp[-1]["dependencies"] for bk in self.branch_kinds(pp, d)] if bks and all(bk is not None and self.kind_within(bk, concept) for bk in bks): continue # the program filtered by a kind that is the asked kind by its own label return False except Exception: # noqa: BLE001 return False return True LEADINS = ("regarding", "tell me", "for", "among", "of", "out of", "if we", "the", "in terms of", "with respect to", "considering") def read_form(self, q): """the asked form from the FIRST interrogative (a lead-in such as "regarding the X," or "tell me" is skipped): count, when (incl. "what date/year", "in what year"), name (incl. "where": a place), or verify (a yes/no opening). -> (form, the question from that interrogative on, or q)""" ws = q.split() yes = ("is", "are", "was", "were", "does", "do", "did", "has", "have", "had") for k, w in enumerate(ws[:12]): rest = " ".join(ws[k:]) if w == "tell" and ws[k + 1:k + 3] in (["me", "if"], ["me", "whether"]): return "verify", rest # "tell me if ..." asks yes or no if w == "how" and k + 1 < len(ws) and ws[k + 1] in ("many", "much"): return ("count" if ws[k + 1] == "many" else "name"), rest if re.match(r"^(?:what|tell me|which) (?:is|are|was|were) the number of ", rest) or re.match(r"^what number of ", rest): return "count", rest if re.match(r"^(?:on|in|at) (?:what|which) (?:date|year|day|time)\b", rest) or re.match(r"^(?:what|which) (?:date|year|day)\b", rest): return "when", rest if w == "when": return "when", rest if w in ("what", "which", "who", "whom", "where"): return "name", rest if w in yes and (k == 0 or (k + 1 < len(ws) and ws[k + 1] in ("it", "this", "the", "he", "she", "they", "these", "those", "that"))): # a yes/no opener after a lead-in clause ("For the X, does it ...") return "verify", rest return None, q def concept_phrases(self, ws): """every written phrase of up to 5 words that names a concept: by its name, a learned alias or its singular form; longest first -> [(phrase, concept)]""" kq, rd = self.rd.kq, self.rd out = {} for a in range(len(ws)): for b in range(a + 1, min(len(ws), a + 5) + 1): t = " ".join(ws[a:b]) for form in [t] + list(R7.singulars(t)): c = form if form in kq.cname else rd.alias_canon.get(("C", form)) if not c and b == a + 1: c = self.lex.concept_words.get(form) # a learned kind word: "person" -> human cs_ = [(pr, f[2:]) for f, pr in self.align_w.get(form, {}).items() if f.startswith("C:") and pr >= 0.25] if not c and cs_: c = max(cs_)[1] if c and c in kq.cname: out.setdefault(t, c) break return sorted(out.items(), key=lambda x: -len(x[0])) def hyphae(self, question, q, frs): """HYPHAE, as a flash. Every verified part lights its items; the light runs along every relation a word of the question says (the highlight: nothing else is lit), up to two steps, all relations at once, as vector operations over the whole store. Where the light from different parts meets, the paths form a SHAPE. A shape is parsed only if it accounts for every content word (the parts' words, the relations crossed, the concept named, the attribute asked) and ends on ONE thing or one agreed value; it is then run exactly on the knowledge base and judged.""" rd, kq = self.rd, self.rd.kq F = self.flash_index() N, num, ids_of = F["N"], F["num"], F["ids"] ws = q.split() offs, o = [], 0 for w in ws: offs.append(o) o += len(w) + 1 self._curq = q if {"nor", "neither", "except"} & set(ws) or ("not" in ws and not any( st["function"] in ("FilterNum", "FilterYear", "FilterDate") and st["inputs"][2:3] == ["!="] for _a, _b, pr, _i in self.parts(q, frs) for st in pr)): return [] # the measured closing forms the learned closer does not yet build (a comparison of two items, yes/no on a value, the # relation between two items, a statement's qualifier, a superlative); every answer they give passes the opening's # learned answer family (close_learn102.terminal_allowed), like the learned closer's cmp = [x for x in self.compare(question, q, frs, ws, offs) if self.closer is None or self.closer.terminal_allowed(q, x[1][-1]["function"])] if cmp: return cmp extra = [x for x in self.closures2(question, q, frs, ws, offs) if self.closer is None or self.closer.terminal_allowed(q, x[1][-1]["function"])] if extra: return extra form, from_q = self.read_form(q) # the form, from the first interrogative (lead-ins kept: they hold parts) if form == "count": hm = from_q.split() cs = 2 if from_q.startswith("how many") else (hm.index("of") + 1 if "of" in hm else 2) if not any(ph == " ".join(hm[cs:cs + len(ph.split())]) for ph, _c in self.concept_phrases(hm)): form = "name" # "how many subscribers": a quantity an item holds, read as stored if form is None and self.closer is None: self.why_close["opening not read: " + " ".join(ws[:2])] += 1 return [] kind = self.asked_kind(q) if form == "name" else None asking = {a[4:] for a in R7.asking_words(question)} content = {k for k, w in enumerate(ws) if (w in self.lex.words or len(w) > 3) and not R7.is_glue(w) and w not in asking and not _num(w) and w not in CL.OPEN and w not in ("many", "much") and w not in DISCOURSE} P = self.parts(q, frs) if not P: return [] # a shape must be anchored by something the question NAMES (an entity or a written value): a concept and a # relation alone are underdetermined ("Who was the main actor?"), the law of w572 applied to the flash if not any(pr[0]["function"] == "Find" or any(st["function"].startswith("Filter") and st["function"] != "FilterConcept" for st in pr) for _a, _b, pr, _i in P): self.why_close["no named anchor"] += 1 return [] span = lambda a, b: {k for k in range(len(ws)) if a <= offs[k] < b} concepts = self.concept_phrases(ws) # written phrase -> concept (by name, alias or singular) conditioned = {st["inputs"][0] for _a, _b, pr, _i in P for st in pr if st["function"].startswith("Filter") and st["function"] != "FilterConcept" and st["inputs"]} allwords = frozenset(ws[k] for k in content) lit_rel = {} # the highlight: relation -> the question's words that say it for key in F["csr"]: sw = frozenset(w for w in allwords if self.says_word("IN:" + key[0], key[0], w)) if sw: lit_rel[key] = sw res = [] def vec(idset): v = np.zeros(N, dtype=bool) v[[num[i] for i in idset if i in num]] = True return v def program(prog, path): pp = copy.deepcopy(prog) for r, d in path: pp.append({"function": "Relate", "dependencies": [len(pp) - 1], "inputs": [r, d]}) return pp def one_value(nodes, k): vals = set() for i in list(nodes)[:60]: for x in (kq.ents.get(i) or {}).get("attributes", []): if x["key"] == k: vals.add(json.dumps(x["value"], sort_keys=True)) return len(vals) == 1 def close(pp, nodes, used, need): """the words a shape leaves are a concept that filters (if any), then an attribute read or the asked form""" left = set(need) - set(used) outs = [] leftover.append(frozenset(left)) for ph, c in [x for x in concepts if set(x[0].split()) <= left] + [(None, None)]: after = left - set(ph.split()) if c else set(left) base = pp + [{"function": "FilterConcept", "dependencies": [len(pp) - 1], "inputs": [c]}] if c else list(pp) cw = set(ph.split()) if c else set() if c: try: pre = rd.exec_steps(copy.deepcopy(base)) except Exception: # noqa: BLE001 pre = None if not pre or not isinstance(pre[-1], tuple) or not pre[-1][0]: continue end = set(pre[-1][0]) else: end = set(nodes) if not after: if form == "count": outs.append((base + [{"function": "Count", "dependencies": [len(base) - 1], "inputs": []}], cw)) elif form == "name": outs.append((base + [{"function": "What", "dependencies": [len(base) - 1], "inputs": []}], cw)) continue if form == "verify" and len(end) == 1: i1 = next(iter(end)) for x in (kq.ents.get(i1) or {}).get("attributes", []): k = x["key"] for s1, e1, v in vals_written: vw = set(v.lower().split()) sw = {w for w in after - vw if self.says_word("IN:" + k, k, w)} if sw != (after - vw - set(self.OP_WORDS) - {"than", "different", "not", "equal", "other"}): continue t = (x["value"] or {}).get("type") if isinstance(x["value"], dict) else "string" fn = {"quantity": "VerifyNum", "year": "VerifyYear", "date": "VerifyDate"}.get(t, "VerifyStr") ins = [v] if fn == "VerifyStr" else [v, self.value_op(q[:s1])] outs.append((base + [{"function": "QueryAttr", "dependencies": [len(base) - 1], "inputs": [k]}, {"function": fn, "dependencies": [len(base)], "inputs": ins}], cw | sw | vw)) continue if form in ("name", "when") and len(end) <= 40: for k in {x["key"] for i in list(end)[:40] for x in (kq.ents.get(i) or {}).get("attributes", [])}: if form == "when" and not any(t in k for t in ("date", "time", "year", "inception", "start", "end", "founded")): continue if k in conditioned or self.value_written(q, end, k) or not one_value(end, k): continue sw = {w for w in after if self.says_word("IN:" + k, k, w)} if sw == after or (form == "when" and sw and sw >= after - {"year", "date"}): outs.append((base + [{"function": "QueryAttr", "dependencies": [len(base) - 1], "inputs": [k]}], cw | sw)) return outs def closing(pp, nodes, used, need): """the learned closing when it is loaded; the hand-written close() otherwise (10.2 development comparison)""" if self.closer is None: return close(pp, nodes, used, need) outs = [] others = [(a_, b_, pr) for a_, b_, pr, ids_ in P if len(ids_) == 1 and not any( json.dumps(st) in json.dumps(pp) for st in pr if st["function"] == "Find")] self.closer.close(question, q, pp, nodes, set(used), set(need), values_all, kq, deadline, outs, others=others) leftover.append(frozenset(set(need) - set(used))) return [(pq, uw - set(used)) for pq, uw in outs] def frag_words(a_, b_, prog_): """a verified fragment's wording was learned with its program; a one-step part (a name, a value) has none""" return q[a_:b_] if len(prog_) > 1 and prog_[0]["function"] != "FindAll" else "" def judge_run(pp, learned): if len(res) >= 12: return for st in pp: if st["function"] == "Find": nm = str(st["inputs"][0]) if nm[:1].isupper() and nm not in question and nm.lower() in question.lower(): return # written only in lower case: not this name (w572) if pp[-1]["function"] == "What": try: pre = rd.exec_steps(copy.deepcopy(pp[:-1])) except Exception: # noqa: BLE001 pre = None if not pre or not isinstance(pre[-1], tuple) or len(pre[-1][0]) != 1: return # a shape must end on ONE thing ok, _why = self.align(question, pp, learned or None, strict=True) if not ok or not self.kind_holds(pp, kind): return try: ans = rd.run(copy.deepcopy(pp)) except Exception: # noqa: BLE001 ans = None if ans is not None and str(ans) not in ("", "None") and not (form == "count" and str(ans) == "0"): res.append((str(ans), pp)) leftover = [] vals_written = [] values_all = self.values_from_store(question, q, P) # every written span that is a stored value, as stored if form == "verify": # the values a yes/no compares: written, and no part's condition for s1, e1, kinds in rd.found(q): if ({"V", "N"} & set(kinds) or re.fullmatch(r"\d[\d,.]*|\d{4}-\d{2}-\d{2}", q[s1:e1])) and not any( a_ <= s1 < b_ for a_, b_, pr, _i in P): m = re.search(re.escape(q[s1:e1]).replace("\\ ", r"\W+"), question, re.I) vals_written.append((s1, e1, question[m.start():m.end()] if m else q[s1:e1])) # the flash: from every part, along every lit relation, up to two steps - all at once deadline = SB.deadline() grown = [] for s0, e0, prog, idset in P: own = self.part_words(ws, span(s0, e0), prog) need = frozenset(allwords - own) if not need: continue start = vec(idset) beams = [((), frozenset(), start)] for _d in range(2): nxt = [] for path, used, v in beams[-24:]: for key, sw in lit_rel.items(): if sw <= used: continue # each step must say something not already said by this path indptr, dst = F["csr"][key] out = self._step(v, indptr, dst, N) if out.any(): nxt.append((path + (key,), used | (sw & need), out)) nxt.sort(key=lambda b_: -len(b_[1])) beams += nxt[:24] grown.append((s0, e0, prog, own, need, [b_ for b_ in beams if b_[0]], start)) for s0, e0, prog, own, need, beams, _start in grown: for path, used, v in beams: if SB.spent() > deadline: break nodes = {ids_of[n] for n in np.flatnonzero(v)[:200]} for pp, cw in closing(program(prog, path), nodes, used, need): judge_run(pp, frag_words(s0, e0, prog)) # where light from two parts meets (at their own items, or after steps): both paths, merged on shared items for x in range(len(grown)): for y in range(x + 1, len(grown)): A, B = grown[x], grown[y] if not (A[1] <= B[0] or B[1] <= A[0]): continue need = (A[4] - B[3]) | (B[4] - A[3]) for pa_, ua, va in [((), frozenset(), A[6])] + A[5]: # a part's own items meet the other's light for pb_, ub, vb in [((), frozenset(), B[6])] + B[5]: if SB.spent() > deadline: break meet = va & vb if not meet.any() or meet.sum() > 50: continue nodes = {ids_of[n] for n in np.flatnonzero(meet)} xa, xb = program(A[2], pa_), program(B[2], pb_) xb = [dict(st, dependencies=[i_ + len(xa) for i_ in st["dependencies"]]) for st in xb] pp = xa + xb + [{"function": "And", "dependencies": [len(xa) - 1, len(xa) + len(xb) - 1], "inputs": []}] for pq, cw in closing(pp, nodes, ua | ub, need): judge_run(pq, " ".join(x_ for x_ in (frag_words(A[0], A[1], A[2]), frag_words(B[0], B[1], B[2])) if x_)) if res: self.stats["hyphae"] += 1 else: grew = any(b_ for g_ in grown for b_ in g_[5]) if grown else False self.why_close["grew nothing" if not grew else "shapes left words"] += 1 if leftover: for w in min(leftover, key=len): self.why_left[w] += 1 self.last = dict(getattr(self, "last", {}) or {}, left=sorted(min(leftover, key=len))) return res def store_search(self, question, q, frs): """the parts find the rest in the knowledge base. From every part at once: each attribute and relation its items hold is a candidate step, ranked against the question's remaining words in one HRR product; the step between two parts is the stored relation that connects their items (or the items they share). A reading stands only when its steps account for every remaining word; it is run exactly and judged.""" rd, kq = self.rd, self.rd.kq ws = q.split() offs, o = [], 0 for w in ws: offs.append(o) o += len(w) + 1 if {"or", "not", "nor", "neither", "except"} & set(ws): return [] # an operator over sets is the reader's own work, not a hole form = "count" if q.startswith("how many") else ("name" if ws and ws[0] in ("what", "which", "who", "whom") else ("when" if ws and ws[0] == "when" else None)) if form is None: return [] asking = {a[4:] for a in R7.asking_words(question)} content = {k for k, w in enumerate(ws) if (w in self.lex.words or len(w) > 3) and not R7.is_glue(w) and w not in asking and not _num(w) and w not in CL.OPEN and w not in ("many", "much")} P = self.parts(q, frs) if not P: return [] span = lambda a, b: {k for k in range(len(ws)) if a <= offs[k] < b} concepts = sorted({" ".join(ws[a:b]) for a in range(len(ws)) for b in range(a + 1, min(len(ws), a + 5) + 1)} & set(kq.cname), key=len, reverse=True) res = [] def finish(prog, used_words, hole_words): """the asked form on top, a named concept as a filter; every hole word must be used""" rest = [w for w in hole_words if w not in used_words] outs = [] if form in ("name", "count"): cn = [c for c in concepts if set(c.split()) & set(rest) and set(rest) <= set(c.split())] if rest and not cn: return [] fin = "Count" if form == "count" else "What" if cn: for c in cn[:2]: outs.append((prog + [{"function": "FilterConcept", "dependencies": [len(prog) - 1], "inputs": [c]}, {"function": fin, "dependencies": [len(prog)], "inputs": []}], set(c.split()))) else: outs.append((prog + [{"function": fin, "dependencies": [len(prog) - 1], "inputs": []}], set())) return outs def judge_run(pp, learned): ok, _why = self.align(question, pp, learned) if not ok: return try: ans = rd.run(copy.deepcopy(pp)) except Exception: # noqa: BLE001 ans = None if ans is not None and str(ans) not in ("", "None") and not (form == "count" and str(ans) == "0"): res.append((str(ans), pp)) for a, (s0, e0, pa, ida) in enumerate(P): hole = [ws[k] for k in sorted(content - span(s0, e0))] if not hole: continue hv = np.sum([osub_seed("o7w:" + self._stem(w)) for w in hole], axis=0) hv = hv / np.linalg.norm(hv) keys = {x["key"] for i in list(ida)[:40] for x in (kq.ents.get(i) or {}).get("attributes", [])} rels = {(r, d) for i in list(ida)[:40] for r, d, _o, _q in kq.rel.get(i, ())} cands = [("attr", k, None) for k in keys] + [("rel", r, d) for r, d in rels] vecs = [self.prop_vec(c[1]) for c in cands] keep = [j for j, v in enumerate(vecs) if v is not None] if not keep: continue sims = np.real(np.stack([vecs[j] for j in keep]) @ np.conj(hv)) for j in [keep[j] for j in np.argsort(-sims)[:24]]: kind, label, d = cands[j] said = {w for w in hole if self.says_word("IN:" + label, label, w)} if not said: continue if kind == "attr": if self.value_written(q, ida, label): continue rest = [w for w in hole if w not in said] if form == "count" or rest: continue if form == "when" and not any(t in label for t in ("date", "time", "year", "inception", "start", "end", "founded")): continue pp = copy.deepcopy(pa) + [{"function": "QueryAttr", "dependencies": [len(pa) - 1], "inputs": [label]}] judge_run(pp, " ".join([q[s0:e0]] + sorted(said))) continue if form == "when": continue base = copy.deepcopy(pa) + [{"function": "Relate", "dependencies": [len(pa) - 1], "inputs": [label, d]}] targets = set() for i in list(ida)[:40]: targets |= {o_ for r_, d_, o_, _q in kq.rel.get(i, ()) if r_ == label and d_ == d} # the step between parts: this relation's targets merged with another part's items for s1, e1, pb, idb in P: if not (e1 <= s0 or e0 <= s1) or not (targets & idb): continue left = [w for w in hole if w not in said and w not in {ws[k] for k in span(s1, e1)}] p2 = [dict(st, dependencies=[x + len(base) for x in st["dependencies"]]) for st in copy.deepcopy(pb)] joined = base + p2 + [{"function": "And", "dependencies": [len(base) - 1, len(base) + len(p2) - 1], "inputs": []}] for pp, cw in finish(joined, set(), left): judge_run(pp, " ".join([q[s0:e0], q[s1:e1]] + sorted(said) + sorted(cw))) for pp, cw in finish(base, said, hole): judge_run(pp, " ".join([q[s0:e0]] + sorted(said) + sorted(cw))) if res: self.stats["store search"] += 1 return res def join(self, question, q, frs): """SORT-MERGE JOIN of verified parts: fragments that each name a set, and together cover every content word of the question, are intersected on their shared ids; exactly one thing left is the answer to a "what/which/who" question. The joined program (the fragments, And, What) is run exactly and judged like every reading.""" rd = self.rd ws = q.split() offs, o = [], 0 for w in ws: offs.append(o) o += len(w) + 1 asking = {a[4:] for a in R7.asking_words(question)} need = {k for k, w in enumerate(ws) if w in self.lex.words and not R7.is_glue(w) and w not in asking and not _num(w) and w not in CL.OPEN} sets = [] for s0, e0, prog in frs: try: out = rd.exec_steps(copy.deepcopy(prog)) except Exception: # noqa: BLE001 out = None if not out or not isinstance(out[-1], tuple) or not out[-1][0]: continue ids = frozenset(out[-1][0]) cov = {k for k in range(len(ws)) if s0 <= offs[k] < e0} sets.append((s0, e0, prog, ids, cov)) res = [] n = len(sets) for a in range(n): for b in range(a + 1, n): A, B = sets[a], sets[b] if A[0] < B[1] and B[0] < A[1]: continue # the parts must not overlap if not need <= (A[4] | B[4]): continue # every content word inside a joined part both = sorted(A[3] & B[3]) # the merge: ids both parts name if len(both) != 1: continue pa, pb = A[2], B[2] prog = [dict(st, dependencies=list(st["dependencies"])) for st in pa] prog += [dict(st, dependencies=[d + len(pa) for d in st["dependencies"]]) for st in pb] prog += [{"function": "And", "dependencies": [len(pa) - 1, len(pa) + len(pb) - 1], "inputs": []}, {"function": "What", "dependencies": [len(pa) + len(pb)], "inputs": []}] learned = " ".join((q[A[0]:A[1]], q[B[0]:B[1]])) ok, _why = self.align(question, prog, learned) if not ok: continue try: ans = rd.run(copy.deepcopy(prog)) except Exception: # noqa: BLE001 ans = None if ans is not None: res.append((str(ans), prog)) if res: self.stats["joined"] += 1 return res def read(self, question): """-> (answers, readings), like read7; only every judged reading that ran""" rd = self.rd if R7.unreadable(question): return [], [] q = R4.norm(question) frs = [] for F, _O, S, lvl in rd.levels: rd.level2 = lvl f = rd.fragments(q, F) if rd.use_segments: f = rd.composed(q, S, f) frs += f if not frs: return [], [] res, rejected = [], 0 ws0 = q.split() res += self.hyphae(question, q, frs) # first: every part grows; where growth meets is the shape if ws0 and ws0[0] in ("what", "which", "who", "whom"): res += self.join(question, q, frs) # and the verified fragments merged on what they share if res: return self._finish(question, res) for cs, ce in self.holes(q, frs): rest = (q[:cs] + " " + q[ce:]).strip() if not rest or len(rest.split()) < 2: continue bases = None for lvl in (False, True): pats, exact = self.recall(q[cs:ce], lvl) if not pats: continue if bases is None: bases = self.bases(rest) if not bases: break before = q[:cs].rstrip() for btm, base in bases: learned = " ".join(x for x in (btm, q[cs:ce] if exact else "") if x) anchored = set() for an in self.CL.anchors(base, before): anchored.add(an) for steps, spec in pats: for t, st in enumerate(base): if st["function"] != spec["target_fn"]: continue if anchored and not any(base[an]["function"] == spec["anchor_fn"] and CL.hop_from(base, an, t) == spec["hop"] for an in anchored): continue prog = self.CL.attach(base, steps, t) if prog[-1]["function"] != base[-1]["function"]: continue # a hole is a clause: what is asked is the rest's reading's ok, _why = self.align(question, prog, learned or None) if not ok: rejected += 1 continue try: ans = rd.run(copy.deepcopy(prog)) # run() may rewrite the program it is given except Exception: # noqa: BLE001 ans = None if ans is not None: res.append((str(ans), prog)) self.stats["judge rejected"] += rejected return self._finish(question, res) def _finish(self, question, res): rd = self.rd if not res: return [], [] if rd.forms and any(not rd.forms.ok(self.read_form(R4.norm(question))[1], p) for _a, p in res): self.stats["vetoed"] += 1 return [], [] uniq = {} for a, p in res: uniq.setdefault(json.dumps(p), (a, p)) return [a for a, _p in uniq.values()], [("COVERAGE", p) for _a, p in uniq.values()] def assemble(self, question, q, frs): """ASSEMBLY: the learned step structures (skeleton102, from the training programs) filled only with what the flash lit - the parts, the relations and keys a word says, the concepts, the written values - each prefix run on the store as it is placed, the complete programs judged. Ordering comes from data; content from the light.""" if getattr(self, "_sk", None) is None: try: import skeleton102 as SK self._sk = SK.Skeletons(self.rd, self, Path(__file__).resolve().parent / "data" / "skeletons102.json") except Exception: # noqa: BLE001 self._sk = False if not self._sk: return [] try: out = self._sk.parse(question, q, frs, budget=float(os.environ.get("O7_ASSEMBLE_BUDGET", "3.0"))) except Exception: # noqa: BLE001 return [] if out: self.stats["assembled"] += 1 return out def flash_answer(self, question): """the flash as the head asks it: an answer only when every shape that ran agrees; the reply carries the program and its steps, like every reading of the knowledge base""" if R7.unreadable(question): return None q = R4.norm(question) rd = self.rd frs = [] for F, _O, S, lvl in rd.levels: rd.level2 = lvl f = rd.fragments(q, F) if rd.use_segments: f = rd.composed(q, S, f) frs += f n0 = sum(self.why_words.values()) self.last = {"stop": None, "left": None} res = self.hyphae(question, q, frs) if not res and os.environ.get("O7_ASSEMBLE", "1") == "1": res = self.assemble(question, q, frs) # the lit primitives assembled by learned step structures if not res: stop = ("no part lit" if not self.parts(q, frs) else ("judge refused every shape" if sum(self.why_words.values()) > n0 else "no shape closed")) self.why[stop] += 1 self.last["stop"] = stop return None kind = self.asked_kind(q) if kind is not None and res: # the asked kind holds of every answer, whichever path built it res = [(a_, p_) for a_, p_ in res if self.kind_holds(p_, kind)] if not res: self.why["asked kind does not hold"] += 1 return None if rd.forms and any(not rd.forms.ok(self.read_form(R4.norm(question))[1], p_) for _a, p_ in res): self.why["opening's kind veto"] += 1 return None scored = sorted(((self.program_score(q, p_), a, p_) for a, p_ in res), key=lambda x: -x[0]) if len(scored) > 1 and scored[0][1] != scored[1][1] and scored[0][0] - scored[1][0] < 0.05: answers = {scored[0][1], scored[1][1]} # a tie between different answers: the question is ambiguous else: answers = {scored[0][1]} res = [(scored[0][1], scored[0][2])] if len(answers) != 1: self.why["shapes disagree"] += 1 return {"status": "declined", "why": "the shapes the question lit disagree (%s)" % " / ".join(sorted(answers)[:3])} a, prog = res[0] score = self.program_score(q, prog) if score < self.threshold(): self.why["below score threshold"] += 1 return None self.why["answered"] += 1 return {"status": "answered", "answer": a, "key": a.lower(), "show": {"read": "lit and joined", "program": prog, "score": round(score, 3)}}