oracle7 / workbench /kernel /kernel_v2.py
psiloceyeben's picture
Release 12.0 (full): one browser harness that converses, writes from held sources and builds what you describe, keeping each request through corrections and restarts. No language model. (part 5)
d9b105f verified
Raw History Blame Contribute Delete
8.98 kB
#!/usr/bin/env python3
"""The Oracle7 kernel, v2 (KERNEL_SPEC.md step K2): ONE kernel over declared and induced faces.
READER glue v3's reader gives every given's SI value, dimension and surface span. The kernel adds each given's
QUANTITY NOUN from the words just before it, matched only against nouns the admitted formula parts use (the
longest known noun ending there: "a density of 7850 kg per cubic metre" -> density), and the WANTED noun as the
longest known noun in the question's asking clause ("what is its mass" -> mass).
DECLARED the formula parts (830), planned by kernel v1: keys = noun + dimension, system-aware links, every plan agrees.
Used only when every given and the wanted quantity are named.
INDUCED the specialists, through glue v3's learned faces, typed medium and law (conditions, coverage, named ratios).
LAW both readings answer -> they must agree (relative 1%), else the kernel declines ("two readings disagree").
One answers -> that answer, with its receipts. Neither -> a hole: what was wanted, what was given, why.
usage: kernel_v2.py (module; see run_kernel_dev.py)"""
from __future__ import annotations
import collections
import json
import os
import re
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
sys.path.insert(0, str(HERE))
from kernel_v1 import Kernel1 # noqa: E402
from kernel_v0 import ORGAN # noqa: E402
ORGAN_DIR = ORGAN / "specialists"
from network_glue_v3 import GlueNetwork3, reader # noqa: E402
STOP_TAIL = {"of", "is", "was", "at", "a", "an", "the", "its", "with", "has", "=", "to", "by", "about", "and", "in", "for"}
def to7(d6):
"""glue (m, kg, s, A, K, $) -> formula side (m, kg, s, A, K, mol, cd); money has no formula-side dimension"""
if d6[5]:
return None
return (d6[0], d6[1], d6[2], d6[3], d6[4], 0, 0)
WORD = re.compile(r"[a-z][a-z\-]+")
TITLE_STOP = {"from", "the", "a", "an", "of", "and", "in", "on", "by", "for", "to", "with", "wikidata", "per", "unit", "system"}
class Declared(Kernel1):
"""kernel v1's declared side, with SYSTEM CONDITIONS replacing v1's link rule. A key several systems produce (a cone's
height and a cylinder's height are both 'height') is produced, for a given question, only by systems the question
names: a system's distinguishing words are its titles' words that no other system producing that key uses. A key one
system produces needs no naming. (v1's rule blocked valid chains such as sphere volume -> mass through density.)"""
def __init__(self, *a, **k):
super().__init__(*a, **k)
self.sys_words = collections.defaultdict(set)
for pid, p in self.parts.items():
try:
t = json.loads((ORGAN_DIR / pid / "spec.json").read_text(encoding="utf-8")).get("title", "")
except Exception: # noqa: BLE001
t = ""
self.sys_words[self.sys[pid]] |= {w for w in WORD.findall(t.lower()) if w not in TITLE_STOP}
# rivals: systems giving the SAME output from the SAME inputs (alternative models, e.g. cone vs cylinder volume
# from radius and height). Systems that reach an output from different inputs are told apart by the givens.
self.key_systems = collections.defaultdict(set)
for p in self.parts.values():
self.key_systems[(p["out_key"], tuple(sorted(p["in_keys"])))].add(self.sys[p["id"]])
self.qwords = set()
def allowed(self, p):
systems = self.key_systems[(p["out_key"], tuple(sorted(p["in_keys"])))]
if len(systems) <= 1:
return True
mine = self.sys_words[self.sys[p["id"]]]
others = set().union(*(self.sys_words[s] for s in systems if s != self.sys[p["id"]]))
return bool((mine - others) & self.qwords)
def linked_ok(self, plan, given):
return all(self.allowed(p) for p in plan)
class Kernel2:
def __init__(self, standing, spec_root="/opt/o7spec", combo="/opt/o7spec/_fam"):
self.declared = Declared()
self.induced = GlueNetwork3(standing, spec_root, combo, log=lambda s: None)
self.nouns = sorted({k[0] for k in self.declared.keys}, key=lambda n: -len(n))
self.noun_dims = {}
for (n, d) in self.declared.keys:
self.noun_dims.setdefault(n, set()).add(d)
def _noun_before(self, text, span):
i = text.find(span)
if i < 0:
return None
words = re.findall(r"[a-z][a-z\-]*", text[:i].lower())
while words and words[-1] in STOP_TAIL:
words.pop()
for n in self.nouns: # longest first
nw = n.split()
if len(nw) <= len(words) and words[-len(nw):] == nw:
return n
return None
def _wanted(self, text):
sents = [s for s in re.split(r"(?<=[.?!])\s+", text.strip()) if s]
ask = (sents[-1] if sents else text).lower()
best = None
for n in self.nouns:
if re.search(r"\b%s\b" % re.escape(n), ask):
best = n
break
return best
def _leaves(self, want, d7, depth=3):
"""every input key that appears in some chain (depth <= 3) toward the wanted key, among parts this question allows"""
seen, frontier, leaves = set(), [(want, d7)], set()
for _ in range(depth):
nxt = []
for key in frontier:
for p in self.declared.planner.by_out.get(key, []):
if p["id"] in seen or not self.declared.allowed(p):
continue
seen.add(p["id"])
for ik in p["in_keys"]:
leaves.add(ik)
nxt.append(ik)
frontier = nxt
return leaves
def declared_answer(self, text):
t = reader.normalise(text)
givens, flags = reader.read_givens(t)
goal = reader.read_goal(t)
if not givens or flags.get("unread_numbers") or goal is None or goal[0] != "dim":
return None, "declared: question not fully read"
want = self._wanted(t)
gd7 = to7(goal[1])
if want is None or gd7 is None or gd7 not in self.noun_dims.get(want, set()):
return None, "declared: no wanted quantity a part produces"
self.declared.qwords = {w for w in WORD.findall(t.lower())}
leaves = self._leaves(want, gd7)
given, unnamed = {}, []
for q in givens:
n = self._noun_before(t, q.text)
d7 = to7(q.dim)
if d7 is None:
return None, "declared: money has no formula-side quantity"
if n is None or d7 not in self.noun_dims.get(n, set()):
unnamed.append((q, d7)) # named by its dimension below, if that is unambiguous
continue
if (n, d7) in given:
return None, "declared: two givens of the same quantity"
given[(n, d7)] = q.v
for q, d7 in unnamed:
cands = [key for key in leaves if key[1] == d7 and key not in given]
if len(cands) != 1:
return None, "declared: %s names no quantity, and its dimension fits %d inputs" % (q.text, len(cands))
given[cands[0]] = q.v
r = self.declared.ask_keys(want, given)
if r["status"] != "answered":
return None, "declared: " + r.get("why", "")
val = r["value"] / goal[3]
unit = goal[2]
return {"status": "answered", "answer": ("$%.2f" % val) if unit == "$" else "%s %s" % (reader.g(round(val, 6)), unit),
"value_si": r["value"], "path": [x["part"] for x in r["receipts"]], "receipts": r["receipts"],
"reading": "declared"}, None
def solve(self, text):
a, why_a = self.declared_answer(text)
b = self.induced.solve(text)
b_ok = b.get("status") == "answered"
if a and b_ok:
vb = _num(b.get("answer"))
va = _num(a["answer"])
if va is not None and vb is not None and abs(va - vb) > 0.01 * max(abs(va), abs(vb), 1e-12):
return {"status": "declined", "reason": "two readings disagree: declared %s, induced %s" % (a["answer"], b["answer"]),
"check": "readings agree"}
return dict(a, also_induced=b.get("answer"), trace=b.get("trace", []))
if a:
return dict(a, trace=[{"node": p} for p in a["path"]])
if b_ok:
return dict(b, reading="induced")
return {"status": "declined", "reason": b.get("reason") or why_a, "declared_reason": why_a,
"hole": {"question": text, "declared": why_a, "induced": b.get("reason")}}
def _num(ans):
m = re.search(r"-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?", str(ans or "").replace("$", ""))
return float(m.group(0).replace(",", "")) if m else None