File size: 24,890 Bytes
04e89f2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 | #!/usr/bin/env python3
"""compose_reply_v9 - the turn governed by the loop (PLAN_CONVERSATION_115 S2 + S3), on V8.
Connection 1: the turn is READ into programs by the turn kernel (K8 for store sentences, induced conversational rules
for the rest). Connection 2: a conversation is a scene with obligations. Each user clause the kernel reads is an
obligation the user bound (its slots are the givens). The reply's FORM comes from the corpus scene index (what the role
said next after this form, counted over DailyDialog train), and its places are bound: carried from the user's own turn
where the corpus carries them (reflect), bound from the head's record where the slot is a name the store links (fill),
otherwise open. The reply is said only at the dew point: every place bound. Said = the skeleton refilled; proved = the
second reading (the reply read back is the program it was said from). An open place is a named hole (C4). Nothing about
the data is written by hand: forms, their order and the carrying of places are all counted off the corpus.
Store answers keep precedence (quality): where V8 composes a cited fact, that reply stands. The learned move replaces V8's
hand ports (social, ack, hole-without-record) and the next-question predictor."""
import collections
import json
import os
import re
import sys
from compose_reply_v8 import ComposeRouterV8, content_words
_HERE = os.path.dirname(os.path.abspath(__file__)) # the package itself: its K8 reader, its data
_TREE = os.path.abspath(os.path.join(_HERE, "..", "..")) # the release this package ships in
TK_DIR = os.environ.get("ORACLE7_TK", os.path.join(_HERE, "data", "tk"))
WT = os.environ.get("ORACLE7_WT", os.path.join(_TREE, "root", "wander-train"))
for p in (WT, _HERE): # the package's own modules first; nothing outside the release
if p not in sys.path:
sys.path.insert(0, p)
from turn_kernel import TurnKernel, Induced, toks # noqa: E402
CARRY_MIN = 0.5 # a role place is carried from the user's turn when the corpus carries it at least this often
MOVE_MIN = 2 # a (user form -> role form) pair must occur at least this often to be a move
AUX = re.compile(r"^(do|does|did|is|are|was|were|can|could|would|will|shall|should|have|has|had|may|might)$", re.I)
WH = re.compile(r"^(what|who|where|when|why|how|which|whose)$", re.I)
class SceneIndex:
"""counted off scene_programs.json: for each user form, the role's next forms, and how their places are carried"""
def __init__(self, path, rules):
self.rule = {r["rule_id"]: r for r in rules}
self.next = collections.defaultdict(collections.Counter) # user rule -> Counter(role rule)
self.next_given = collections.defaultdict(collections.Counter) # (user rule, one of the user's own words) -> Counter(role rule)
self.carry = collections.defaultdict(collections.Counter) # (user rule, role rule, role slot k) -> Counter(user slot m | "new")
self.fill = collections.defaultdict(collections.Counter) # (user rule, role rule, role slot k) -> Counter(word the role brought)
self.fill_given = collections.defaultdict(collections.Counter) # (..., k, a user slot value) -> Counter(word the role brought)
self.pairs = collections.Counter()
scenes = json.load(open(path))
for dl in scenes:
for j in range(len(dl) - 1):
ups = [p for p in dl[j] if p]
rps = [p for p in dl[j + 1] if p]
if not ups or not rps:
continue
u = ups[-1] # the last thing the user said is what the role answers
for r in rps[:1]: # the role's first clause is its move
self.next[u["rule"]][r["rule"]] += 1
self.pairs[(u["rule"], r["rule"])] += 1
us = {int(k): v.lower() for k, v in u["slots"].items()}
for uv in set(us.values()):
self.next_given[(u["rule"], uv)][r["rule"]] += 1
for k, v in r["slots"].items():
src = next((m for m, uv in us.items() if uv == v.lower()), "new")
self.carry[(u["rule"], r["rule"], int(k))][src] += 1
if src == "new": # the role brought this word: the scene's own vocabulary
self.fill[(u["rule"], r["rule"], int(k))][v] += 1
for uv in us.values():
self.fill_given[(u["rule"], r["rule"], int(k), uv)][v] += 1
# the scene ids the judge reads: one per (user form, role form) pair that is a move
self.scene_of = {}
self.scenes = []
for (ur, rr), n in self.pairs.most_common():
if n < MOVE_MIN:
break
sid = "p%d" % len(self.scenes)
self.scene_of[(ur, rr)] = sid
skel = self.rule[rr]["skeleton_tokens"]
text = " ".join(skel)
lead = [s for s in skel if not s.startswith("<")]
wh = "yes/no" if lead and AUX.match(lead[0]) else next((s for s in lead if WH.match(s)), None)
key = [w for w in content_words(" ".join(s for s in self.rule[ur]["skeleton_tokens"] + skel if not s.startswith("<")))]
self.scenes.append({"id": sid, "key": key[:8], "n": n, "user_form": ur, "role_form": rr,
"moves": [{"act": "question" if skel and skel[-1] == "?" else "statement", "text": text,
"wh": wh, "slot": None}]})
def opens(self, rr):
"""a move opens an obligation: it asks, or it brings a name or a number. A bare acknowledgement is not a move."""
skel = self.rule[rr]["skeleton_tokens"]
return (skel and skel[-1] == "?") or any(s in ("<NAME>", "<NUM>") for s in skel)
def moves(self, user_rule, user_slots=None):
"""the role's next forms after this form: given one of the user's own words where the corpus counted that (>= MOVE_MIN),
then by the form alone; only forms that open an obligation"""
out, seen = [], set()
for uv in (user_slots or {}).values():
for rr, n in self.next_given.get((user_rule, uv.lower()), {}).most_common():
if n >= MOVE_MIN and rr not in seen and self.opens(rr):
out.append((rr, n)); seen.add(rr)
for rr, n in self.next.get(user_rule, {}).most_common():
if n >= MOVE_MIN and rr not in seen and self.opens(rr):
out.append((rr, n)); seen.add(rr)
return out
def filler(self, ur, rr, k, user_slots):
"""the word the role brings at this place, counted off the scene: given the user's own words first, else overall"""
for uv in user_slots.values():
c = self.fill_given.get((ur, rr, k, uv.lower()))
if c and c.most_common(1)[0][1] >= 2:
return c.most_common(1)[0][0]
c = self.fill.get((ur, rr, k))
return c.most_common(1)[0][0] if c else None
def carried(self, ur, rr, k):
c = self.carry.get((ur, rr, k))
if not c:
return None
src, n = c.most_common(1)[0]
return src if src != "new" and n / sum(c.values()) >= CARRY_MIN else None
class ComposeRouterV9(ComposeRouterV8):
def __init__(self, *a, **k):
super().__init__(*a, **k)
from stage5m13e9_kernel_k8 import ConstructionKernelK8
self.tk = TurnKernel(ConstructionKernelK8(compositional=True), TK_DIR)
self.index = SceneIndex(os.path.join(TK_DIR, "scene_programs.json"), self.tk.ind.rules)
self.scene_programs = json.load(open(os.path.join(TK_DIR, "scene_programs.json"))) # train dialogue -> turn -> programs
self.obl = collections.defaultdict(list) # session -> obligations: {rule, slots, by, turn}
try: # the build door (converse/builder.py): present in the pack, optional in the harness
from builder import Builder
self.builder = Builder(self)
except Exception: # noqa: BLE001
self.builder = None
self.played9 = collections.defaultdict(set) # session -> role forms already used
self.holes9 = collections.Counter() # the typed holes this router leaves (S5 reads them)
out_dir = os.environ.get("ORACLE7_TMP", TK_DIR)
os.makedirs(out_dir, exist_ok=True)
json.dump(self.index.scenes, open(os.path.join(out_dir, "program_scenes.json"), "w"), ensure_ascii=False)
# the resonator (resonance.py): role-aware resonance over the scene memory ranks the scenes in place of the mover's cosine
self.resonator = None
if os.environ.get("ORACLE7_RESONANCE", "1") == "1" and self.mover is not None:
from resonance import Resonator
self.resonator = Resonator(os.environ.get("ORACLE7_MOVES", "/opt/o7conv/moves.json"))
self.res_cfg = dict(L=int(os.environ.get("RES_L", 1)), p=int(os.environ.get("RES_P", 2)), sq=int(os.environ.get("RES_SQ", 1)))
# ---------------- the loop over obligations
def bind_turn(self, turn, session):
"""read the turn; every clause read is an obligation the user bound. -> programs (None where unread)"""
ps = self.tk.compile(turn)
n = len(self.turns[session])
for p in ps:
if p and p["kind"] == "rule":
self.obl[session].append({"rule": p["rule"], "slots": p["slots"], "by": "user", "turn": n})
self.dbg.append(("read", [(p["kind"], p.get("rule")) if p else None for p in ps]))
if not ps or not any(ps):
self.holes9["unread"] += 1
elif not all(ps):
self.holes9["part_read"] += 1
return ps
def scene_move(self, turn, session, ents):
"""the scenes nearest in CONTENT (the mover's neighbours over what was said, the user's previous turn and the role's), read
as programs: the role's next form in each, voted by similarity; its places bound (carried from the turn, the store's name,
or the scene's own word); only a form that opens an obligation; said at the dew point and proved by the second reading"""
if self.mover is None or not hasattr(self, "scene_programs"):
return None
T = self.turns.get(session) or []
R = self.role_turns.get(session) or []
if getattr(self, "resonator", None) is not None:
sc = self.resonator.rank(T[-1] if T else turn, T[-2] if len(T) > 1 else None, R[-1] if R else None, **self.res_cfg)
else:
sc = self.mover.scored(T[-1] if T else turn, T[-2] if len(T) > 1 else None, R[-1] if R else None)
n = len(self.turns[session])
tw = {t.lower() for t in toks(turn)}
names = [self.label(e) for _, e, _ in ents][:3]
# the read-out order IS the choice (the standalone measurement's 37.8%): the first pooled scene whose reply opens an
# obligation and was not played. If its reply reads as a form, the form is refilled (places carried from the turn, the
# store's name, else the scene's own word) and proved by the second reading; if it does not read, or the second reading
# fails, the reply is the LITERAL form (the corpus's own words): no open place, proved by identity.
for sim, i in sc[:20]:
e = self.mover.entries[i]
if getattr(self, "resonator", None) is None and sim < self.mover.tau:
break
if getattr(self, "resonator", None) is not None and sim < self.resonator.tau():
break # below the read-off tau: no move; the hole or the head's reply stands
if e["id"] in self.played9[session] or "?" not in e["text"]:
continue
# (round 25) the 'slot already said' skip is removed: the corpus role often asks about the word just said
di, j = int(e["dlg"][1:]), int(e["id"].split("_")[1])
try:
progs = [p for p in self.scene_programs[di][j + 1] if p]
except (IndexError, KeyError):
progs = []
cite_scene = " [scene:%s%s]" % (e["id"], (":" + e["slot"]) if e.get("slot") else "")
text, cites, how = None, [], "literal"
for p in progs:
rr = p["rule"]
if not self.index.opens(rr):
continue
skel = self.index.rule[rr]["skeleton_tokens"]
slots, cs = {}, []
for k, s_ in enumerate(skel):
if not s_.startswith("<"):
continue
own = p["slots"].get(str(k))
if own and own.lower() in tw:
slots[k] = own; cs.append("[turn:%d]" % n)
elif s_ == "<NAME>" and names:
slots[k] = names[0]; cs.append("[wd:Q%d]" % ents[0][1])
elif own:
slots[k] = own
else:
slots = None
break
if slots is None:
continue
prog = {"kind": "rule", "rule": rr, "slots": slots, "skeleton": skel}
t = Induced.realize(prog)
if self.tk.same(prog, t):
text, cites, how = t, cs, "form:" + rr
self.obl[session].append({"rule": rr, "slots": slots, "by": "role", "turn": n})
else:
self.holes9["second_reading"] += 1
break
if text is None:
text = e["text"]
self.holes9["literal_move"] += 1
self.played9[session].add(e["id"])
self.mover_last[session] = (e["dlg"], e["step"])
self.dbg.append(("scene_move", e["id"], round(sim, 3), how, text[:60]))
return "play", (text + " " + " ".join(dict.fromkeys(cites)) + cite_scene).replace(" ", " "), True
return None
def move(self, turn, ps, session, ents):
"""the role's next form after the user's last read form, its places bound; said at the dew point only"""
sm = self.scene_move(turn, session, ents)
if sm:
return sm
last = next((p for p in reversed(ps) if p and p["kind"] == "rule"), None)
if not last:
return None
ur = last["rule"]
n = len(self.turns[session])
names = [self.label(e) for _, e, _ in ents][:3]
open_need = None
for rr, cnt in self.index.moves(ur, last["slots"]):
if rr in self.played9[session]:
continue
skel = self.index.rule[rr]["skeleton_tokens"]
slots, cites, open_ = {}, [], []
for k, s in enumerate(skel):
if not s.startswith("<"):
continue
typ = s[1:-1]
m = self.index.carried(ur, rr, k)
if m is not None and m in last["slots"]:
slots[k] = last["slots"][m] # reflected from the user's own turn
cites.append("[turn:%d]" % n)
elif typ == "NAME" and names:
slots[k] = names[0] # filled from the store's linked name
cites.append("[wd:Q%d]" % ents[0][1])
elif typ == "NUM" and any(t.isdigit() for t in toks(turn)):
slots[k] = next(t for t in toks(turn) if t.isdigit())
cites.append("[turn:%d]" % n)
else:
w = self.index.filler(ur, rr, k, last["slots"]) # bound from the scene's own record (S3 fill, hole class open_place)
if w is not None and (typ != "NAME" or not names):
slots[k] = w
cites.append("[scene:%s]" % self.index.scene_of.get((ur, rr), "p0"))
else:
open_.append(typ)
if open_:
if open_need is None:
open_need = (rr, open_)
continue
prog = {"kind": "rule", "rule": rr, "slots": slots, "skeleton": skel}
text = Induced.realize(prog)
if not self.tk.same(prog, text):
self.holes9["second_reading"] += 1
self.dbg.append(("second_reading_failed", rr, text[:60]))
continue
self.played9[session].add(rr)
sid = self.index.scene_of.get((ur, rr), "p0")
self.obl[session].append({"rule": rr, "slots": slots, "by": "role", "turn": n})
act = "play" if skel and skel[-1] == "?" else "answer"
# a question is a move and cites its scene; a statement is said only from what it carries (the turn, the store)
cite = " ".join(dict.fromkeys(cites)) + ((" [scene:%s]" % sid) if act == "play" else "")
self.dbg.append(("move", ur, "->", rr, cnt, text[:60]))
return act, text + " " + cite, True
if open_need:
rr, open_ = open_need
self.holes9["open_place:" + open_[0]] += 1
sid = self.index.scene_of.get((ur, rr), "p0")
return "hole", "The next thing to say here needs a %s I don't hold [scene:%s]; give me the %s and I go on." % (
open_[0].lower(), sid, open_[0].lower()), False
self.holes9["no_move"] += 1
return None
# ---------------- the plug: store facts first, then the learned move, then V8's remaining ports
COMPARE = re.compile(r"\b(compare|compared|comparison|longer|shorter|taller|bigger|larger|smaller|older|newer|heavier|higher)\b", re.I)
def compare(self, turn, session, asked):
"""Amendment 14 (1): a comparison binds two entities (this turn's, else the most recent one the conversation named) and
one relation, read from the store for both; both values are stated with their citations. The judgement is made only
when the values are comparable; the relational store keeps quantities without units, so a quantity is never judged."""
ents = [e for _s, e, _ in self.link(turn)]
if len(ents) < 2:
for prev in reversed(self.turns[session][:-1]):
if self.COMPARE.search(prev):
continue # the referent of "it" is the thing asked about, not an earlier comparison's other side
for _s, e, _ in self.link(prev):
if e not in ents:
ents.append(e)
break
if len(ents) >= 2:
break
if len(ents) < 2:
return None
a, b = ents[0], ents[1]
prevq = " ".join([t for t in self.turns[session][:-1] if t.rstrip().endswith("?")][-3:]) or turn
from compose_reply_v8 import content_words, unit as _unit
names = set(w for e in (a, b) for w in content_words(self.label(e) or ""))
rest = [w for w in content_words(prevq + " " + turn) if w not in names and not self.COMPARE.search(w)]
# a comparative names its quantity by its base ("longer" -> long, "taller" -> tall, "older" -> old)
rest += [m.lower()[:-3] if m.lower().endswith("ier") else m.lower()[:-2] for m in self.COMPARE.findall(turn) if m.lower().endswith("er")]
if self.COMPARE.search(turn) and asked in (None, "noun", "yesno"):
asked = "number"
qv = _unit(self.text_vec(rest, {w: 1.0 for w in rest})) if rest else None
if qv is None:
return None
ra, _ = self.relations(a, qv, asked or "number")
if not ra:
return None
pa, lab, va, _f = ra[0]
rb, _ = self.relations(b, qv, asked or "number")
vb = next((v for pp, _l, v, _f in rb if pp == pa), None)
if vb is None:
return ("hole", "%s. I hold no %s for %s [none]; a record of it would let me compare them." % (
self.r_fact(a, pa, lab, va), lab, self.label(b)), False)
txt = "%s, and %s." % (self.r_fact(a, pa, lab, va), self.r_fact(b, pa, lab, vb))
num = lambda v: float(v[0]) if v and re.match(r"^[+-]?\d+(\.\d+)?$", str(v[0])) else None
if num(va) is not None and num(vb) is not None:
txt += " My records keep these without their units, so I won't say which is greater until a source gives the unit."
return "answer", txt, True
def program(self, turn, fr, session, wts, h, q, ref_words):
if self.COMPARE.search(turn) and (fr.get("mood") == "question" or turn.rstrip().endswith("?")):
try:
c = self.compare(turn, session, self.asked(fr))
except Exception as e: # noqa: BLE001
c = None
self.dbg.append(("compare_error", repr(e)[:120]))
if c:
self.stats["compare"] = self.stats.get("compare", 0) + 1
return c
ps = self.bind_turn(turn, session)
if self.builder is not None: # a build request, or an example question binding one of its places
try:
b = self.builder.step(turn, fr, session, q)
except Exception as e: # noqa: BLE001
b = None
self.dbg.append(("builder_error", repr(e)[:120]))
if b:
return b
act, text, subst = super().program(turn, fr, session, wts, h, q, ref_words)
if act == "answer" and "[wd:" in text and " P" in text:
return act, text, subst # a cited fact from the store stands (quality)
if act in ("cancel", "plan") or (act == "answer" and "[ledger:" in text) or (act == "answer" and "[op:" in text):
return act, text, subst # the work ledger and the head's own operations stand
ents = getattr(self, "_ents9", []) or []
mv = self.move(turn, ps, session, ents) if any(ps) else self.scene_move(turn, session, ents)
# 12.0 step 3, the Tiferet rule: a question the head declined and the store did not fill is met by the hole that names
# the open place, never by a scene move (the 11.5 end-to-end answered a bridge length with a scene about dancing)
# the class (wake run 11-08: the first rule only caught a play replacing a hole): on a QUESTION the head declined, a
# play is never the reply; a hole or a cited answer stands, otherwise the hole names what is open
if mv and mv[0] == "play" and (fr.get("mood") == "question" or turn.rstrip().endswith("?")):
self.stats["hole_over_play"] = self.stats.get("hole_over_play", 0) + 1
if act == "hole" or (act == "answer" and "[" in str(text)):
return act, text, subst
keys = [str(k) for k in (fr.get("keys") or []) if k][:4]
need = (" What I would need: a record of " + ", ".join(keys) + ".") if keys else ""
return "hole", "I cannot answer that from anything I can check [turn:%d].%s" % (len(self.turns[session]), need), False
if mv:
self.stats["move9"] += 1
return mv
if act == "play" and (fr.get("mood") == "question" or turn.rstrip().endswith("?")):
# the same class on the older composer's own play (wake run: "What would you build next" got a recorded line)
self.stats["hole_over_play"] = self.stats.get("hole_over_play", 0) + 1
keys = [str(k) for k in (fr.get("keys") or []) if k][:4]
need = (" What I would need: a record of " + ", ".join(keys) + ".") if keys else ""
return "hole", "I cannot answer that from anything I can check [turn:%d].%s" % (len(self.turns[session]), need), False
return act, text, subst
def link(self, turn, wh_about=True, want_p=None):
ents = super().link(turn, wh_about=wh_about, want_p=want_p)
self._ents9 = ents
return ents
def prime(self, user_turn, role_turn, session="convo"):
super().prime(user_turn, role_turn, session)
n = len(self.turns[session])
for p in self.tk.compile(user_turn):
if p and p["kind"] == "rule":
self.obl[session].append({"rule": p["rule"], "slots": p["slots"], "by": "user", "turn": n})
for p in self.tk.compile(role_turn):
if p and p["kind"] == "rule":
self.obl[session].append({"rule": p["rule"], "slots": p["slots"], "by": "role", "turn": n})
self.played9[session].add(p["rule"])
|