oracle7 / workbench /converse /compose_reply_v8.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 4)
04e89f2 verified
Raw History Blame Contribute Delete
44.9 kB
#!/usr/bin/env python3
"""COMPOSE ROUTER v8 (round 9): the transformer of Oracle7's parts GENERATES THE PROGRAM UNDER THE SURFACE.
Ben, 2026-11-05: "it must generate the symbolic logic (typed terms / programs) under the surface, not surface text;
realizer + law handle surface; never pad with filler caveats." Ben, 2026-11-07: "it needs to be broad."
Rounds 3-8 attended over Oracle7's own record sentences and copied the best-fitting one. v8 attends over the BROAD store
and composes typed terms; every term carries its source; the surface is rendered from the terms and nothing is copied:
query the turn's demand (reader frame; the HRR REF head of v6 binds what "it"/"that" points at)
keys ENTITY names (names_v1: 14.1M), the RELATIONS an entity holds (prop labels + aliases), the OPERATIONS
(v7's head), the SCENES (roles mined from DailyDialog), the LEDGER, the DICTIONARY
attention cosine fit of demand to key, HRR word vectors (v6), masked by what the store actually holds for the entity
program ACT x TERMS: answer(E, R, V) | describe(E) | define(w) | yes/no(E, R, V) | do(op, receipt) | plan(op) |
play(scene, move) | ack(E) + relate(E, R, V) | judge(ledger) | hole(missing, filler, question-back) | social
render own clauses from the terms, each with its citation: [wd:Q.. P..] [dict:w] [ledger:n] [op:cmd] [scene:id]
[turn:k] [none]
usage: module (ComposeRouterV8(..., reader=Reader), same constructor as v4-v7)"""
from __future__ import annotations
import collections
import json
import os
import re
import sqlite3
import numpy as np
from squircle_reply import content_words
from squircle_reply_v4 import GENERIC
from squircle_reply_v6 import SquircleRouterV6, unit, D
from squircle_reply_v7 import SquircleRouterV7
OP_TAU = 0.42
_HERE = os.path.dirname(os.path.abspath(__file__))
_TREE = os.path.abspath(os.path.join(_HERE, "..", ".."))
REL_ROOT = os.environ.get("ORACLE7_RELSTORE_DIR", os.path.join(_TREE, "root", "relstore")) # the release's own store
SCENES = os.environ.get("ORACLE7_SCENES", os.path.join(_HERE, "data", "scenes.json"))
MOVES = os.environ.get("ORACLE7_MOVES", os.path.join(_HERE, "data", "moves.json"))
MOVER_TAU = 0.45 # superseded: the tau now lives in moves.json, read off the dev-slice eval (conv_mover.py eval)
REL_TAU = 0.24
LEX_W = 0.35 # the learned lexicon's vote, added to the declared-name fit # a relation must fit the demand this well to be the asked one
SCENE_TAU = 0.45 # a scene must fit this well to be played
MAX_ENT = 3
SKIP_P = {31, 279, 373, 646, 214, 227, 244, 213, 268, 269, 349, 434, 435, 436, 18, 109, 94, 154, 242, 158, 1442, 910, 1151,
2959, 5008, 1343, 1889, 4224, 3450, 1464, 1465, 1792, 2354, 7867, 1424} # ids, images, categories
PLACE_P = {17, 131, 276, 159, 19, 20, 30, 706, 36, 150, 47}
TIME_TYPES = {"Time"}
NUM_TYPES = {"Quantity"}
STOPW = set("a an the of in on at to for by with from and or is was were are be been being i you he she it we they me him her us "
"them my your his its our their this that these those there here please thanks thank yes no not so very just like would "
"could can will shall may might must do does did have has had am get got go going come want need let say said tell ask "
"know think sure ok okay well oh hi hello good sir madam miss mr mrs ms excuse sorry much many some any".split())
CANCEL = re.compile(r"\b(ignore that|never ?mind|forget (it|that)|scratch that|wrong (chat|window|channel|char))\b")
AGREE = re.compile(r"^(?:(?:yes|yeah|yep|ok|okay|sure|right|alright|good|great|fine|please|do it|go ahead|go|lets|let\x27s)[ ,.!]*){1,4}"
r"(?:(?:do|try|run|go with|get on with|start|build) (?:that|it|this|those|them|one|first))?[ .!]*$")
DEFQ = re.compile(r"^(?:so |ok |okay )?(?:what|whats|what's|what is|what are|what does|define|meaning of)\s+(?:a |an |the )?([a-z\-']+(?: [a-z\-']+)?)\s*(?:mean|means)?\s*\??$")
DEF_NOT = {"plan", "status", "eta", "progress", "goal", "point", "deal", "matter", "idea", "problem", "issue", "next", "news", "time",
"difference", "result", "answer", "verdict", "score", "count", "number", "price", "cost", "name", "date", "year"}
def defq_word(core, d=None):
"""the word a definition question asks about, or None: one noun (or noun noun), not a status word, not modified"""
m = DEFQ.match(core)
if not m:
return None
ws = m.group(1).split()
if ws[-1] in DEF_NOT or ws[0] in ("full", "whole", "current", "next", "new", "best", "right", "real", "actual", "exact"):
return None
if d is not None and len(ws) == 2 and ("noun" not in d.pos(ws[0]) or "adj" in d.pos(ws[0])):
return None
return ws[-1]
TITLES = {"mr", "mrs", "ms", "miss", "dr", "prof", "sir", "madam", "mister", "doctor", "professor", "captain", "officer"}
HUMAN = re.compile(r"\b(\d{4}\)|\(born|player|actor|actress|politician|writer|singer|footballer|musician|painter|poet|author|"
r"composer|scientist|businessman|businesswoman|journalist|director|producer|athlete|physician|lawyer|"
r"american|british|canadian|german|french|chinese|japanese|english|australian|indian|italian|spanish|russian)\b")
SCENE_OPEN = re.compile(r"^(hello|hi|hey|good (morning|afternoon|evening)|excuse me|welcome|this is|may i|can i|could i)\b")
OPENERS = re.compile(r"^(?:(?:hello|hi|hey|good (?:morning|afternoon|evening)|excuse me|sorry|welcome|please|sir|madam|miss|"
r"mr\.? \w+|mrs\.? \w+|ms\.? \w+|dr\.? \w+|oh|well|um|er|so|okay|ok)[,.!? ]+)+", re.I)
COMPARE = re.compile(r"\b(difference|differences|compare|comparison|versus|vs|similarit(y|ies)|between)\b")
STATUS = re.compile(r"\b(where are we|where we are|whats been done|what's been done|whats left|what's left|is it (all )?(finished|done|built)|eta\b|status\b|how far (are|along)|progress\b|what did you (do|run))")
OTHER_OFFER = re.compile(r"\b(can|could|may) i help( you)?\b|\bwhat can i do for you\b|\bhow can i (help|be of service)\b")
SCENE_STOP = {"him", "her", "them", "service", "server", "previous", "single", "time", "day", "today", "way", "thing", "people", "work", "home", "line"}
OFFER = re.compile(r"^(?:can|could|may|shall|should) i\b")
SELFQ = re.compile(r"^(?:what|who) (?:do|are|can) (?:you|u)\b|^what(?:'s| is) (?:this|oracle7|oracle 7)\b|^who are you")
EVAL = {"huge", "great", "better", "worse", "good", "bad", "amazing", "wrong", "broken", "slow", "fast", "dark", "nice", "cool",
"awesome", "terrible", "fine", "perfect", "big", "small", "important", "significant"}
def norm(s):
import unicodedata
s = unicodedata.normalize("NFKD", str(s)).encode("ascii", "ignore").decode("ascii")
return " ".join(re.sub(r"[^a-z0-9 ]+", " ", s.lower()).split())
class ComposeRouterV8(SquircleRouterV7):
def __init__(self, *a, **k):
super().__init__(*a, **k)
self.rel = sqlite3.connect("file:%s/relations_v2.sqlite3?mode=ro&immutable=1" % REL_ROOT, uri=True, check_same_thread=False)
self.names = sqlite3.connect("file:%s/names_v1.sqlite3?mode=ro&immutable=1" % REL_ROOT, uri=True, check_same_thread=False)
self.ptype, self.plabel = {}, {}
for p, t, lab, n, g in self.rel.execute("SELECT p, type, label, facts, global FROM prop_src"):
self.ptype[p], self.plabel[p] = t, lab
self.palias = {}
try:
al = json.load(open(REL_ROOT + "/prop_aliases_v1.json"))
for p, v in al.items():
p = int(p)
self.palias[p] = v.get("aliases", [])[:12]
if v.get("label"):
self.plabel.setdefault(p, v["label"])
dt = (v.get("datatype") or "").lower()
if "time" in dt:
self.ptype.setdefault(p, "Time")
elif "quantity" in dt:
self.ptype.setdefault(p, "Quantity")
elif "item" in dt:
self.ptype.setdefault(p, "WikibaseItem")
elif dt:
self.ptype.setdefault(p, dt)
except Exception: # noqa: BLE001
pass
self._pk = {}
self.mover, self.played_m = None, {}
if os.path.exists(MOVES):
from conv_mover import Mover
self.mover = Mover(MOVES)
self.scenes = []
if os.path.exists(SCENES):
self.scenes = json.load(open(SCENES))
self.SK = np.zeros((len(self.scenes), D), dtype=np.float32)
for i, s in enumerate(self.scenes):
self.SK[i] = unit(self.text_vec(s["key"]))
self.lex = {"words": {}, "asked": {}}
lp = os.environ.get("ORACLE7_REL_LEXICON", "/opt/o7conv/rel_lexicon.json")
if os.path.exists(lp):
try:
self.lex = json.load(open(lp))
except Exception: # noqa: BLE001
pass
self.played = {} # session -> (scene index, moves used)
self.role_turns = collections.defaultdict(list) # session -> what the role said (its replies, or a transcript it was given)
self.mover_last = {} # session -> (dialogue, step) of the last move the mover played (scene continuity)
self.lastprog = {} # session -> (act, text) of the last composed program
self.dbg = []
self.stats.clear()
# ---------------- the broad store: entities and their relations
def link(self, turn, wh_about=True, want_p=None):
"""entity spans of the turn: longest first, by the name table's link count; the original case is kept.
want_p: relations the demand asks for; among a span's candidates the first that HOLDS one of them wins."""
words = re.findall(r"[A-Za-z0-9][A-Za-z0-9'\-]*", turn)
taken, out = set(), []
self._ltrace = []
for n in (6, 5, 4, 3, 2, 1):
for i in range(len(words) - n + 1):
if any(j in taken for j in range(i, i + n)):
continue
span = words[i:i + n]
low = [w.lower() for w in span]
if n > 3 and not (span[0][:1].isupper() and span[-1][:1].isupper()):
continue
if (low[0] in STOPW and not (n > 1 and span[0][:1].isupper() and i > 0)) or low[-1] in STOPW or all(w in STOPW for w in low):
continue
caps = any(w[:1].isupper() for w in span)
before = words[i - 1].lower().rstrip(".") if i > 0 else ""
if before in TITLES:
taken.update(range(i, i + n))
continue # "Mr Jackson", "Dr Steward": a person in the room
if n == 1:
w = low[0]
ps = self.reader.d.pos(w)
if len(w) < 3 or w in GENERIC or self.reader.is_closed(w) or not caps:
continue
if i == 0 and (ps & {"noun", "verb", "adj", "adv", "intj"}) and "name" not in ps:
continue # sentence-initial common word ("How", "Is", "Mom")
elif not caps:
if all("noun" in self.reader.d.pos(w) or self.reader.is_closed(w) for w in low):
continue # "computer file", "one way ticket": words, not a name
elif not (span[0][:1].isupper() and span[-1][:1].isupper()):
continue # "live in Tokyo": the name is Tokyo
cands = self.names.execute("SELECT qid, links FROM name WHERE norm=? ORDER BY links DESC LIMIT 6", (norm(" ".join(span)),)).fetchall()
cands = [c for c in cands if not ((not caps and c[1] < 120) or (n == 1 and c[1] < 60))]
if not cands:
self._ltrace.append((" ".join(span), "no candidate"))
continue
sp = norm(" ".join(span))
good = [c for c in cands if norm(self.label(int(c[0])) or "") == sp or norm(self.label(int(c[0])) or "").startswith(sp + " ")]
if not good and n > 1:
good = cands[:1] # a multiword alias with no exact label: the best-linked one
if not good:
self._ltrace.append((" ".join(span), "no label match"))
continue
r = good[0]
if want_p:
for c in good[:4]:
if any(self.rel.execute("SELECT 1 FROM fact WHERE s=? AND p=? LIMIT 1", (int(c[0]), p)).fetchone() for p in want_p):
r = c
break
if n == 1:
ps = self.reader.d.pos(low[0])
if ("noun" in ps or "verb" in ps or "adj" in ps) and "name" not in ps:
self._ltrace.append((span[0], "common word"))
continue # Jack, Dick, Horde, Mechanics: words first
dsc = (self.descr(int(r[0])) or "").lower()
if want_p and any(self.rel.execute("SELECT 1 FROM fact WHERE s=? AND p=? LIMIT 1", (int(r[0]), p)).fetchone() for p in want_p):
pass # it holds the asked relation: it is the thing asked about
elif re.search(r"\b(given name|family name|surname|male name|female name)\b", dsc) or (
r[1] < 150 and re.search(r"\b(river|village|hamlet|album|song|film|band|genus|family of|species)\b", dsc)
and "name" in self.reader.d.pos(low[0])):
continue
if not wh_about:
dsc = (self.descr(int(r[0])) or "").lower()
if HUMAN.search(dsc):
taken.update(range(i, i + n))
continue # a person named in a scene stays a person in the scene
out.append((" ".join(span), int(r[0]), int(r[1])))
taken.update(range(i, i + n))
out.sort(key=lambda x: (-len(x[0].split()), -x[2]))
return out[:MAX_ENT]
def label(self, qid):
r = self.rel.execute("SELECT label, enwiki FROM entity WHERE qid=?", (qid,)).fetchone()
return (r[0] or r[1]) if r else None
def descr(self, qid):
r = self.rel.execute("SELECT text FROM descr WHERE qid=?", (qid,)).fetchone()
return r[0] if r else None
def pkey(self, p):
if p not in self._pk:
ws = content_words(self.plabel.get(p, "") + " " + " ".join(self.palias.get(p, [])))
self._pk[p] = unit(self.text_vec([w for w in ws if w not in STOPW])) if ws else np.zeros(D, dtype=np.float32)
return self._pk[p]
def fmt_lit(self, lit):
m = re.match(r"^([+-]?\d{1,5})-(\d\d)-(\d\d)", str(lit))
if m:
return m.group(1).lstrip("+")
s = str(lit)
return s[:60]
def relations(self, qid, q, asked):
"""the RELATION head: softmax over the relations this entity holds, keyed by their declared names"""
rows = self.rel.execute("SELECT p, o, lit FROM fact WHERE s=? LIMIT 3000", (qid,)).fetchall()
byp = {}
for p, o, lit in rows:
if p in SKIP_P or p not in self.plabel or self.ptype.get(p, "").lower() in (
"externalid", "external-id", "commonsmedia", "url", "string", "math", "globecoordinate", "globe-coordinate",
"monolingualtext", "wikibase-lexeme", "wikibase-form", "wikibase-sense", "wikibase-property", "tabular-data",
"geo-shape", "musical-notation"):
continue
byp.setdefault(p, []).append((o, lit))
if not byp:
return [], []
ps = list(byp)
K = np.stack([self.pkey(p) for p in ps])
fit = K @ q
# the relation lexicon, learned from the loop's own tests: which demand words (and asked forms) mean which relation
qw = getattr(self, "_qwords", None) or []
lw = self.lex.get("words", {})
if lw and qw:
votes = collections.Counter()
for w in qw:
for pp, c in lw.get(w, {}).items():
votes[int(pp)] += c
if votes:
top = max(votes.values())
fit = fit + np.array([LEX_W * votes.get(p, 0) / top for p in ps], dtype=np.float32)
aw = self.lex.get("asked", {}).get(getattr(self, "_asked_form", "") or "", {})
if aw:
top = max(aw.values())
fit = fit + np.array([0.5 * LEX_W * aw.get(str(p), 0) / top for p in ps], dtype=np.float32)
if asked == "time":
fit = np.where([self.ptype.get(p) in TIME_TYPES for p in ps], fit + 0.15, fit - 0.2)
elif asked == "number":
fit = np.where([self.ptype.get(p) in NUM_TYPES for p in ps], fit + 0.15, fit - 0.2)
elif asked == "place":
fit = np.where([p in PLACE_P for p in ps], fit + 0.15, fit)
order = np.argsort(-fit)
out = []
for j in order[:3]:
if fit[j] < REL_TAU:
break
p = ps[j]
vals = []
for o, lit in byp[p][:3]:
v = self.label(o) if o is not None else self.fmt_lit(lit)
if v:
vals.append(v)
if vals:
out.append((p, self.plabel.get(p, "P%d" % p), vals, float(fit[j])))
if not out and asked in ("time", "number"):
# Amendment 14 (1): a typed place is filled by type. The question asks for a date (or a number) and the entity holds
# relations of that type: the best of them fills it, named, so the reply says which relation answered (11-08:
# "When did he paint it?" -> "I hold no date for Mona Lisa ... What I do hold: inception, ...")
types = TIME_TYPES if asked == "time" else NUM_TYPES
typed = [j for j in order if self.ptype.get(ps[j]) in types]
if len(typed) == 1:
j = typed[0]
p = ps[j]
vals = [v for v in ((self.label(o) if o is not None else self.fmt_lit(lit)) for o, lit in byp[p][:3]) if v]
if vals:
out.append((p, self.plabel.get(p, "P%d" % p), vals, float(fit[j])))
held = [self.plabel.get(ps[j], "") for j in order[:6] if self.plabel.get(ps[j])]
return out, held
def asked(self, fr):
wh, core = fr.get("wh"), fr["fixed"].lower()
if wh == "yes/no" or re.search(r"\b(no|right|yes|correct|isn't it|isnt it|innit|ok|okay)\s*\?\s*$", core):
return "yesno"
if wh == "when" or re.search(r"\b(what|which) year\b", core[:40]):
return "time"
if re.match(r"\s*how (many|much|long|old|far|tall|high)", core):
return "number"
if wh in ("who", "whom", "whose"):
return "name"
if wh == "where":
return "place"
return "noun"
# ---------------- scenes: the PLAY act
def scene(self, session, q, words):
said = set(words)
if self.mover is not None:
T = self.turns.get(session) or []
R = self.role_turns.get(session) or []
hit = self.mover.query(T[-1] if T else " ".join(words), T[-2] if len(T) > 1 else None, R[-1] if R else None,
last=self.mover_last.get(session))
if hit:
e, sim = hit
self.dbg.append(("mover", round(sim, 3), e["id"], e["wh"], e["slot"]))
used = self.played_m.setdefault(session, set())
if sim >= self.mover.tau and e["id"] not in used and not (e["slot"] and e["slot"] in said):
used.add(e["id"])
self.mover_last[session] = (e["dlg"], e["step"])
return ({"id": e["id"], "key": e["ctx"][:8]}, {"act": "question", "text": e["text"], "wh": e["wh"], "slot": e["slot"]}, float(sim))
if not self.scenes or float(np.linalg.norm(q)) == 0:
return None
best, j = 0.0, -1
for i, sc in enumerate(self.scenes):
key = sc["key"]
shared = [k for k in key if k in said]
if not shared or (len(shared) < 2 and (max(self.idf(k) for k in shared) < 6.0 or len(said) > 6
or shared[0] in SCENE_STOP or "noun" not in self.reader.d.pos(shared[0]))):
continue
cov = sum(self.idf(k) for k in shared) / max(1e-6, sum(self.idf(k) for k in key))
f = cov * (0.6 + 0.4 * min(1.0, len(shared) / 2.0))
if f > best:
best, j = f, i
fit = {j: best} if j >= 0 else {}
self.dbg.append(("scene", round(best, 3), self.scenes[j]["key"][:3] if j >= 0 else None))
if j < 0 or best < SCENE_TAU:
return None
cur = self.played.get(session)
if cur and cur[0] != j and any(k in said for k in self.scenes[cur[0]]["key"]):
j = cur[0]
used = cur[1] if cur and cur[0] == j else set()
s = self.scenes[j]
for k, m in enumerate(s["moves"]):
if k in used:
continue
if m["act"] == "question" and m["slot"] and m["slot"] in said:
used.add(k) # the obligation is already bound by what was said
continue
if len(m["text"].split()) > 28:
used.add(k)
continue
if k == 0 or m["act"] == "question":
used.add(k)
self.played[session] = (j, used)
return s, m, float(fit[j])
return None
# ---------------- render: own clauses from typed terms
def r_fact(self, e, p, lab, vals):
return "%s's %s is %s [wd:Q%d P%d]" % (self.label(e), lab, ", ".join(vals[:2]), e, p)
def r_play(self, sc, key, descrs, n_turn):
s_, m, fit = sc
# the premise check: a move may ASK anything; it may ASSERT only what it can cite. Sentences without a "?" are cut.
sents = [x for x in re.split(r"(?<=[.!?])\s+", m["text"].strip()) if x.strip()]
kept = [x for x in sents if "?" in x] or sents[-1:]
text = " ".join(kept)
cite = " [scene:%s%s]" % (s_["id"], (":" + m["slot"]) if m.get("slot") else "")
ack = (descrs[0] + ". ") if descrs else "" # a move asks; it asserts only what the store holds
return ack + text + cite
def r_descr(self, e):
d = self.descr(e)
if not d:
return None
d = d.rstrip(".")
first = d.split()[0]
ps = self.reader.d.pos(first.lower())
if first[:1].islower() and first not in ("a", "an", "the") and (("noun" in ps and not first.endswith("s")) or ("adj" in ps and len(d.split()) > 1)):
d = ("an " if first[0] in "aeiou" else "a ") + d
return "%s is %s [wd:Q%d]" % (self.label(e), d, e)
def op_head(self, q, tau=None, words=None):
"""v7's operations head with a lexical gate: the request and the operation must share one content word"""
if self.OK.shape[0] == 0 or float(np.linalg.norm(q)) == 0:
return None
fit = self.OK @ q
order = np.argsort(-fit)[:8]
tau = OP_TAU if tau is None else tau
for j in order:
if fit[j] < tau:
return None
kind, cmd, usage, desc = self.op_rows[j]
if words is not None:
ow = set(content_words(desc + " " + cmd.replace("-", " ").replace(".", " ").replace("_", " ")))
if not (ow & {w for w in words if w not in GENERIC and self.idf(w) >= 2.5}):
continue
return (float(fit[j]),) + self.op_rows[j]
return None
def program(self, turn, fr, session, wts, h, q, ref_words):
"""compose the typed terms for this turn; returns (act, text, substantive)"""
mood = fr["mood"]
core0 = fr["fixed"].strip().lower()
words = list(fr.get("_own") or wts)
wh_about = mood == "question" and fr.get("wh") not in (None, "yes/no") and not SCENE_OPEN.search(core0)
want_p = []
if mood == "question":
votes = collections.Counter()
for w in words:
for pp, c in self.lex.get("words", {}).get(w, {}).items():
votes[int(pp)] += c
hm0 = re.match(r"^\W*(when|where|who|how many|how much|how long|how old|how tall|what year|which|what)", core0)
for pp, c in self.lex.get("asked", {}).get(hm0.group(1) if hm0 else "", {}).items():
votes[int(pp)] += 0.5 * c
want_p = [p for p, _ in votes.most_common(3)]
ents = self.link(fr["fixed"] if fr["changes"] else turn, wh_about=wh_about, want_p=want_p)
self.dbg.append(("link", want_p, self._ltrace[:4]))
if not ents and ref_words and fr["refs"]:
ents = self.link(" ".join(ref_words).title())
self.dbg.append(("ents", [(e[0], e[1]) for e in ents], "ref", ref_words[:3]))
asked = self.asked(fr) if mood == "question" else None
self._qwords = [w for w in words if w not in GENERIC]
hm = re.match(r"^\W*(when|where|who|how many|how much|how long|how old|how tall|what year|which|what)", fr["fixed"].lower())
self._asked_form = hm.group(1) if hm else ""
qrel = q
if ents:
ew = set(w for e in ents for w in content_words(e[0]))
rest = [w for w in words if w not in ew]
qrel = unit(self.text_vec(rest, wts)) if rest else q
facts, descrs, helds = [], [], []
for span, e, _ in ents:
rels, held = self.relations(e, qrel, asked)
self.stats["ent"] += 1
for p, lab, vals, fit in rels[:1 if mood != "question" else 2]:
facts.append((e, p, lab, vals, fit))
d = self.r_descr(e)
if d:
descrs.append(d)
helds.append((e, held))
key = h
if not key or key in GENERIC:
key = next((w for w in reversed(fr["object"]) if w.isalpha() and w not in GENERIC and not self.reader.is_closed(w)
and "noun" in self.reader.d.pos(w)), None)
if key in ("no", "yes", "one", "thing", "something", "anything", "lot", "bit", "kind", "sort"):
key = None
if not key:
key = next((w for w in reversed(words) if w.isalpha() and w not in GENERIC and not self.reader.is_closed(w)
and "noun" in self.reader.d.pos(w) and w not in ("no", "yes", "one", "thing")), None)
if not key and ref_words and fr["refs"]:
key = ref_words[0]
self.dbg.append(("key", key, "obj", fr["object"][:4], "h", h))
core = fr["fixed"].strip().lower()
n_turn = len(self.turns[session])
# ----- the acts
if CANCEL.search(core):
self.stats["cancel"] += 1
return "cancel", "Ignored; I drop that turn and keep the earlier ones [turn:%d]." % n_turn, True
if mood in ("request", "commitment", "social", "statement") and AGREE.match(core):
last = self.lastprog.get(session)
self.stats["agree"] += 1
if last and last[0] == "plan":
return "plan", "On your go, then: " + last[1], True
if last and last[0] == "play":
return "play", last[1], True
if last and last[0] == "hole":
return "hole", "Agreed, but it is still the hole I named: " + last[1], False
L = self.ledger.get(session) or []
if L and L[-1]["open"]:
return "plan", "Then I would run `%s` [ledger:%d]; say the word and I run it and keep the receipt." % (L[-1]["cmd"], L[-1]["turn"]), True
return "hole", "Agreed [turn:%d], but nothing of mine is pending from the last turn. What should I do first?" % n_turn, False
if mood == "social":
return "social", "Hello. Ask me something I can check, or tell me what to run, and I'll show the working.", True
if STATUS.search(core) and mood in ("question", "request", "statement"):
self.stats["status"] += 1
L = self.ledger.get(session) or []
done = [e for e in L if not e["open"]][-3:]
open_ = [e for e in L if e["open"]][-2:]
parts = []
if done:
parts.append("Run here: " + "; ".join("`%s` -> %s [ledger:%d]" % (e["cmd"], (e["receipt"] or "no result")[:60], e["turn"]) for e in done) + ".")
if open_:
parts.append("Waiting on your go: " + "; ".join("`%s` [ledger:%d]" % (e["cmd"], e["turn"]) for e in open_) + ".")
prev = [t for t in self.turns[session][:-1] if not STATUS.search(t.lower())]
if prev:
pw = " ".join(w for w in content_words(prev[-1]) if w not in GENERIC)[:70]
parts.append("The last thing asked of me was about %s [turn:%d]%s" % (
pw or "the previous turn", len(self.turns[session]) - 1,
"; nothing of mine ran for it, so that is the open item." if not L else "."))
if not parts:
parts.append("Nothing of mine has run in this conversation [ledger:0], and nothing was asked before this; what do you want checked first?")
return "answer", " ".join(parts), True
if OTHER_OFFER.search(core):
self.stats["accept"] += 1
return "answer", ("Yes, please: I check claims against records I can cite and run my own operations, so give me one "
"claim or one question and I show the working [turn:%d]." % n_turn), True
if mood == "question" and len(ents) >= 2 and COMPARE.search(core):
a, b = ents[0], ents[1]
da, db = self.r_descr(a[1]), self.r_descr(b[1])
if da and db:
ca = {o for o, _ in self.rel.execute("SELECT o, lit FROM fact WHERE s=? AND p=31", (a[1],)) if o}
cb = {o for o, _ in self.rel.execute("SELECT o, lit FROM fact WHERE s=? AND p=31", (b[1],)) if o}
both = [self.label(x) for x in (ca & cb)][:2]
tail = (" Both are %s [wd:Q%d P31]." % (" and ".join(both), a[1])) if both else " My records give them no common class."
self.stats["compare"] += 1
return "answer", da + ". " + db + "." + tail, True
if mood == "question":
if OFFER.match(core):
self.stats["offer"] += 1
return "answer", "Yes, gladly%s: tell me what to check, or what to run, and I show the working [turn:%d]." % (
(", " + key) if key else "", n_turn), True
if SELFQ.match(core):
self.stats["selfq"] += 1
cmds = ", ".join(c for c, _, _ in self.rep[:8])
return "answer", ("I am Oracle7 [op:help]: I answer from records I can cite, run my own operations (%s and %d more) and "
"say what I lack when I lack it." % (cmds, max(0, len(self.rep) - 8))), True
ev = [w for w in words if w in EVAL]
if asked == "yesno" and ev and not ents:
L = self.ledger.get(session) or []
if L:
e = L[-1]
return "answer", "I can't say yes or no beyond my last receipt: `%s`: %s [ledger:%d]." % (
e["cmd"], (e["receipt"] or "no result")[:100], e["turn"]), True
return "answer", ("I can't say yes or no [turn:%d]: '%s' is a judgement, and I hold no measure for it here. "
"What should I measure it by?" % (n_turn, ev[0])), True
if re.match(r"^(?:so |ok |okay )?how (?:do|can|could|would|should|to|does one|might) (?:i|we|you|one)?\b", core):
op = self.op_head(q)
if op and not facts:
fit, kind, cmd, usage, desc = op
self.stats["howto"] += 1
return "answer", "That is `oracle7.py %s` [op:%s]: %s." % (usage if kind == "command" else cmd, cmd, desc[:160].rstrip(".")), True
if asked == "yesno":
if facts:
e, p, lab, vals, _ = facts[0]
hit = any(norm(v) in norm(turn) for v in vals)
return ("answer", ("Yes: " if hit else "No, not by my records: ") + self.r_fact(e, p, lab, vals) + ".", True)
if descrs:
return ("answer", "I can't say yes or no from what I hold. %s. What about %s should I check?" % (
descrs[0], self.label(ents[0][1])), True)
else:
if facts:
e, p, lab, vals, _ = facts[0]
txt = self.r_fact(e, p, lab, vals) + "."
if descrs and len(facts) == 1:
txt = descrs[0] + ". " + txt
self.stats["answer"] += 1
return "answer", txt, True
if descrs and asked == "noun":
self.stats["describe"] += 1
return "answer", descrs[0] + ".", True
if ents and helds and helds[0][1]:
e, held = helds[0]
self.stats["hole_rel"] += 1
return ("hole", "I hold no %s for %s [none]; a record of it would fill that. What I do hold on %s: %s [wd:Q%d]. "
"Which of those do you want?" % ({"yesno": "yes or no", "time": "date", "number": "number", "name": "name",
"place": "place"}.get(asked, "answer"), self.label(e), self.label(e),
", ".join(held[:5]), e), False)
dw = defq_word(core, self.reader.d)
if dw:
w = dw
g = self.ffn_define(w)
if g:
self.stats["define"] += 1
return "answer", g.rstrip(".") + " [dict:%s]." % w, True
sc = self.scene(session, unit(self.text_vec(words, wts)) if words else q, words)
if sc:
self.stats["play"] += 1
return "play", self.r_play(sc, key, descrs if ents and ents[0][0].lower() in core else [], n_turn), True
if key:
return ("hole", "I hold no record that names %s [none]; a record of %s would fill that. Which %s do you mean?" % (
key, key, key), False)
return "hole", "I hold nothing that answers that [none]. What is it about?", False
if mood in ("request", "commitment"):
verb, thing, top = self.understood(fr, h)
m = re.search(r"\b(?:like|want|need|love)\s+to\s+([a-z]+)\s+(.*)$", core)
if m and (verb in ("like", "want", "need", "love", None) or not thing):
verb = m.group(1)
thing = " ".join(w for w in content_words(m.group(2)) if w not in GENERIC and not self.reader.is_closed(w))[:60] or thing
if not fr["object"] and ref_words and thing == " ".join(fr.get("bound", [])[:2]):
thing = "" # a referent is not the thing to act on unless the turn says so
want = " ".join(x for x in [verb, thing, ("on " + top) if top else ""] if x).strip() or "that"
op = self.op_head(q, words=words)
lead = ""
if descrs and ents and ents[0][0].lower() in core:
lead = descrs[0] + ". "
if op:
fit, kind, cmd, usage, desc = op
self.stats["plan"] += 1
return ("plan", lead + "I would run `oracle7.py %s` [op:%s]: %s. Shall I?" % (
usage if kind == "command" else cmd, cmd, desc[:140].rstrip(".")), True)
sc = self.scene(session, unit(self.text_vec(words, wts)), words) if not op else None
if sc:
self.stats["play"] += 1
return "play", self.r_play(sc, thing or key, descrs if ents and ents[0][0].lower() in core else [], n_turn), True
self.stats["hole_op"] += 1
if verb in GENERIC or not verb or "verb" not in self.reader.d.pos(verb):
want = "do that ('%s')" % " ".join(re.sub(r"\s+", " ", core).split()[:6])
near = ""
op2 = self.op_head(q, tau=0.25, words=[w for w in words if self.idf(w) >= 4.0])
if op2:
fit, kind, cmd, usage, desc = op2
near = " The nearest I have is `oracle7.py %s` [op:%s]: %s." % (usage if kind == "command" else cmd, cmd, desc[:110].rstrip("."))
elif len(self.turns[session]) > 1:
pw = " ".join(w for w in content_words(self.turns[session][-2]) if w not in GENERIC)[:60]
near = " It follows what you asked about %s [turn:%d]." % (pw or "before", n_turn - 1)
return ("hole", lead + "I can't %s [none]: no operation of mine acts on %s; a part that does would fill it.%s "
"What would count as done?" % (want, thing or "that", near), False)
# statement
parts = []
own = [e for e in ents if e[0].lower() in core]
if descrs and own:
parts.append(descrs[0] + ".")
if facts and own:
e, p, lab, vals, _ = facts[0]
parts.append(self.r_fact(e, p, lab, vals) + ".")
ev = [w for w in words if w in EVAL]
if ev:
L = self.ledger.get(session) or []
prev = self.turns[session][-2] if len(self.turns[session]) > 1 else None
if L:
e = L[-1]
parts.append("By my last receipt it is `%s`: %s [ledger:%d]." % (e["cmd"], (e["receipt"] or "no result")[:100], e["turn"]))
elif prev and fr["refs"]:
pw = " ".join(w for w in content_words(prev) if w not in GENERIC)[:60]
parts.append("You mean what we had on %s [turn:%d]: '%s'. No operation of mine changes that; the part that renders it would. "
"Which element?" % (pw or "the last turn", n_turn - 1, ev[0]))
else:
parts.append("I have no measure of my own for '%s' here [turn:%d]; what should I measure it by?" % (ev[0], n_turn))
sc = None
if not parts or (self.mover is not None and not ev):
sc = self.scene(session, unit(self.text_vec(words, wts)) if words else q, words)
if sc:
self.stats["play"] += 1
return "play", self.r_play(sc, key, [p.rstrip(".") for p in parts[:1]], n_turn), True
if parts:
self.stats["ack"] += 1
about = (" ".join(ref_words[:3]) if ref_words and not h else key) or (ents[0][0] if ents else "that")
return "ack", "Noted on %s. %s" % (about, " ".join(parts)), True
L = self.ledger.get(session) or []
if key:
if L:
e = L[-1]
return "ack", "Noted on %s. My last receipt here is `%s`: %s [ledger:%d]. What came of it on your side?" % (
key, e["cmd"], (e["receipt"] or "no result")[:80], e["turn"]), True
return "hole", "Noted on %s [turn:%d]. I hold no record of it and no receipt of my own; tell me what came of it and I keep it." % (
key, n_turn), False
return "hole", "Noted [turn:%d]. What should I do with that?" % n_turn, False
def candidates(self, turn, fr, session, cg, head):
out = super(SquircleRouterV6, self).candidates(turn, fr, session, cg, head) # v4's ports: head, ledger, essay, run, commit
out = [c for c in out if c[1] not in ("hole", "records")] # no copied record sentences, no v4 hole
kept = []
for c in out:
if c[1].startswith("head"):
hp, nw = c[4], len(str(c[2]).split())
self.dbg.append(("head", hp[:60], nw))
if hp.startswith("help") or "lecture" in hp or hp.startswith("wordnet") or (nw > 90 and fr["mood"] == "question"):
continue # a help lecture is not an answer
kept.append(c)
out = kept
wts, h = self.demand(turn, fr)
words = list(wts)
q = unit(self.text_vec(words, wts)) if words else np.zeros(D, dtype=np.float32)
own = [w for w in sorted(wts, key=lambda x: -wts[x])][:6]
fr["_own"] = list(wts)
q_own = q
q, ref_words = self.ref_head(session, q, fr, wts) if words or self.hist[session] else (q, [])
for w in ref_words:
wts.setdefault(w, 1.0)
fr["bound"] = list(dict.fromkeys(fr.get("bound", []) + ref_words))[:6]
ran = any(sub in ("run", "commit", "essay") and text for _, sub, text, _, _ in out)
try:
act, text, subst = self.program(turn, fr, session, wts, h, q, ref_words)
except Exception as e: # noqa: BLE001
self.stats["program_error"] += 1
self.dbg.append(("error", repr(e)[:200]))
act, text, subst = "hole", "I can't compose a reply to that [none]. What is it about?", False
self.lastprog[session] = (act, text)
if ran and act in ("plan", "hole"):
pass # v4 already did the work; its receipt wins
else:
port = "hole" if act == "hole" else ("commissive" if act in ("plan", "play") else "inform")
out.append((port, "c8:" + act, text, subst, ""))
self.stats["act_" + act] += 1
self.hist[session].append((q_own if float(np.linalg.norm(q_own)) > 0 else np.zeros(D, dtype=np.float32) + 1e-6, own))
return out
def prime(self, user_turn, role_turn, session="convo"):
"""record one exchange of a transcript (what the user said, what the role said) without composing anything"""
self.turns[session].append(user_turn)
self.role_turns[session].append(role_turn)
self.reader.sp.observe(user_turn)
def reply(self, turn, session="convo"):
"""v4's act (forward ports, inverted read-back), with one change: a composed program is read back by its own terms
(its citations), so it is not dropped for lacking the turn's words"""
from squircle_reply_v4 import MOOD_ACT, LECTURE, COVER
self._cur = turn
self.turns[session].append(turn)
self.reader.sp.observe(turn)
cg = self.common[session]
self.receive(cg, turn)
stripped = OPENERS.sub("", turn, count=1).strip() or turn
fr = self.bind(session, self.reader.read(stripped if len(stripped.split()) >= 2 else turn))
fr["turn"] = turn
u = MOOD_ACT.get(fr["mood"], "inform")
head = self.head_chat(turn, session)
cands = self.candidates(turn, fr, session, cg, head)
self.frames[session].append(fr)
scored = []
for port, sub, text, substantive, hpath in cands:
if not text:
continue
fit, agree, act_c = self.inverse(fr, u, text)
if sub.startswith("head") and fr["mood"] == "question" and hpath and not LECTURE.match(hpath):
agree = max(agree, COVER)
if sub.startswith("c8:") and "[" in text:
agree = max(agree, COVER)
if agree < COVER and port != "hole":
continue
bonus = 0.5 if sub.startswith("c8:") and substantive else 0.0
scored.append((agree + fit + (1.0 if substantive else 0.0) + bonus, port, sub, text, act_c, round(agree, 2)))
frame = {k: fr[k] for k in ("mood", "verb", "object", "topic", "status", "keys", "bound", "changes", "wh")}
if not scored:
return {"status": "declined", "response": "I can't reply to that with anything I can check.",
"path": "compose8:%s>none" % u, "act_in": u, "frame": frame}
scored.sort(key=lambda x: -x[0])
s, port, sub, text, act_c, agree = scored[0]
self.role_turns[session].append(text)
return {"status": "answered", "response": text, "path": "compose8:%s>%s:%s" % (u, port, sub), "act_in": u,
"act_out": act_c, "agree": agree, "frame": frame,
"considered": [(round(x[0], 2), x[1] + ":" + x[2], x[5]) for x in scored[:5]]}