oracle7 / workbench /converse /definition_reader.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
26.9 kB
"""definition_reader - a dictionary definition read by its own grammar (revised 12.0, 2026-11-17; second version,
rebuilt on an independent judgement of 300 readings: final-gaps-20261116/defreader_judge/JUDGEMENT.md).
A definition is read left to right, and every phrase belongs to the noun nearest before it (the first version put
every phrase on the head; 53 of 116 false readings were of-phrases of another noun, 11 were clauses about an inner noun):
[a|an|the] [describing words, listed] HEAD [or HEAD] what the thing is ("kind", "kinds")
HEAD of THING [of THING] the head's own of-chain ("of")
NOUN that|which|who DOING said of that NOUN: the head's -> "does"; another's -> "inner"
NOUN used|designed|made|meant to DOING the same
NOUN PARTICIPLE by|with|to|in THING passive, of that NOUN
NOUN PREPOSITION THING the head's -> "where"; another's is not the head's role
"to" + a verb is an infinitive, never the preposition "to"; a word is a verb only in a verb's place; after "and/or"
inside a list of things the next word is a thing; modals and "is/are" are never the verb; up/off/out after a verb
belong to the verb.
Reading stops at: "such as", "as in", "as opposed to", "rather than", "e.g.", "especially", a preposition + "which"
clause, and at "not"/"no" (what follows a negation is never asserted).
"one of the X" is an X.
-> {"kind", "kinds", "of", "does": [{"verb","to","with","passive"}], "where", "inner": [{"noun","does"}], "unread"}
Would not solve: which noun a clause after an of-chain describes when grammar allows both ("the property of a body
that resists": said of the body here, the nearest noun); definitions outside this grammar are left unread, not guessed.
"""
import re
DET = {"a", "an", "the", "its", "their", "his", "her", "one's", "any", "some", "each", "every", "another", "other",
"certain", "this", "these", "those", "such", "all", "both", "several", "many", "various", "two", "three"}
REL = {"that", "which", "who", "whose", "whereby"}
PURPOSE = {"used", "designed", "made", "intended", "meant", "employed", "built"}
BE = {"be", "been", "is", "are", "was", "were", "being"}
MODAL = {"can", "may", "will", "must", "should", "could", "might", "only", "also", "often", "usually", "typically",
"generally", "sometimes", "commonly", "normally", "mostly", "mainly", "chiefly", "primarily"} | BE
PREP = {"of", "in", "on", "at", "by", "with", "from", "to", "into", "for", "between", "through", "under", "over",
"against", "along", "across", "around", "within", "without", "upon", "onto", "toward", "towards", "via",
"during", "after", "before", "near", "among", "about", "above", "below", "beneath", "behind", "inside",
"outside", "per", "as"}
JOIN = {"or", "and"}
MEASURE = {"one", "number", "group", "pair", "set", "series", "variety", "kind", "type", "sort", "class"}
PARTICLE = {"up", "off", "out", "down", "away", "back"}
STOP = re.compile(r"(?i)\b(?:such as|as in|as opposed to|rather than|e\.g\.|especially|particularly|for example|"
r"including|not|no|never|without)\b|,\s*(?:or|and)?\s*(?:usually|often|typically|sometimes)\b|"
r"\b(?:%s)\s+(?:which|whom)\b" % "|".join(sorted(PREP)))
FUNCTION = DET | REL | PURPOSE | MODAL | PREP | JOIN | PARTICLE
def _tokens(text):
return re.findall(r"[A-Za-z][A-Za-z'-]*|[,;:()]", text)
class _Reader:
def __init__(self, d):
self.d = d
def pos(self, w):
return self.d.pos(w.lower())
def verbish(self, w):
w = w.lower()
if w in FUNCTION:
return False
return "verb" in self.pos(w) or self.d.lemma(w, "verb") != w
def nounish(self, w):
low = w.lower()
if low in FUNCTION:
return False
if self.d.lemma(low, "verb") != low and not low.endswith(("s", "ing")) and "verb" in self.pos(self.d.lemma(low, "verb")):
return False # a past form ("found", "held", "made") is a doing, not a thing
# a word the store does not list, or a capitalised word that is no common word, is a name: a thing
return "noun" in self.pos(low) or not self.pos(low) or (w[:1].isupper() and "name" in self.pos(low))
def participle(self, w):
w = w.lower()
if w in FUNCTION or self.d.lemma(w, "verb") == w or not w.endswith(("ed", "en", "ing", "t", "n")):
return False
if w.endswith(("t", "n")) and not w.endswith(("en", "nt")) and "noun" in self.pos(w):
return False # "feet", "plan": things; "built", "sent" have no noun sense
return not ("noun" in self.pos(w) and self.d.lemma(w, "noun") != w)
def describing(self, w):
w = w.lower()
if w in FUNCTION:
return False
p = self.pos(w)
return bool(p & {"adj", "adv", "num"}) or (w.endswith(("ed", "ing")) and "noun" not in p)
def noun_ahead(self, toks, k):
n = len(toks)
while k < n and (toks[k] == "," or toks[k].lower() in JOIN or (
self.describing(toks[k]) and not (self.nounish(toks[k]) and (k + 1 >= n or not self.nounish(toks[k + 1]))))):
k += 1
return k < n and self.nounish(toks[k])
def thing(self, toks, i):
"""-> (head noun lemma or None, next index): [det] [describing, listed]* noun+ ; the last noun of the run is
the head; a describing word or participle after the noun ends the phrase ("substance given to", "tree native to")"""
n = len(toks)
while i < n and (toks[i].lower() in DET or (toks[i].lower() in MODAL - BE and i + 1 < n)):
i += 1 # "a typically cold-blooded animal": the adverb is not the thing
head = None
while i < n:
w = toks[i].lower()
if head is None and (w == "," or w in JOIN) and self.noun_ahead(toks, i + 1):
i += 1
continue
if w in FUNCTION or w in ",;:()":
break
if head is None and self.describing(w) and self.noun_ahead(toks, i + 1):
nxt = toks[i + 1].lower() if i + 1 < n else ""
# "long, narrow, deep inlet"; "real or perceived movement"; but "a key or combination" lists things
listed = (nxt == "," or nxt in JOIN) and (not self.nounish(w) or "adj" in self.pos(w) and (
i + 2 < n and self.describing(toks[i + 2]) and not self.nounish(toks[i + 2]) or nxt == ","))
if listed or not self.nounish(w) or self.nounish(nxt) or self.describing(nxt) or w.endswith("ing"):
i += 1
continue
if head is not None and w.endswith("ing") and "noun" in self.pos(w) and i + 1 < n and toks[i + 1].lower() == "of":
head = self.d.lemma(w, "noun")
i += 1
continue
if head is not None and (self.participle(w) or ("adj" in self.pos(w) and not self.nounish(w))
or (w.endswith("s") and self.d.lemma(w, "verb") != w and self.d.lemma(w, "noun") == w)):
break # a postposed describing word, or a verb in -s, ends the phrase
if i + 1 < n and toks[i + 1].lower() in PREP | PARTICLE and (
(head is not None and toks[i + 1].lower() == "by" and self.verbish(w))
or ("adj" in self.pos(w) and (head is not None or toks[i + 1].lower() == "to"))
or (self.d.lemma(w, "verb") != w and not w.endswith(("s", "ing")) and head is not None)):
break # "spread by", "native to", "equal to", "found in", "left over" # "disease spread by", "tree native to"; not "ketose form of"
if self.nounish(toks[i]):
head = self.d.lemma(w, "noun") if "noun" in self.pos(w) else w
i += 1
continue
if head is None and w.endswith("ing") and (i + 1 >= n or toks[i + 1] in ",;" or toks[i + 1].lower() == "of"):
head = w # "a betrothing", "the earning of ...": the doing named as a thing
i += 1
break
# "one of the X" is an X; "one of a number / group / pair of X" is one X
while head in MEASURE and i + 1 < n and toks[i].lower() == "of":
sub, j = self.thing(toks, i + 1)
if not sub:
break
head, i = sub, j
return head, i
def infinitive(self, toks, i):
"""toks[i] is "to": an infinitive when a verb follows that is not the start of a thing"""
n = len(toks)
if i + 1 >= n or toks[i + 1].lower() in DET or not self.verbish(toks[i + 1]):
return False
w = toks[i + 1].lower()
if "verb" not in self.pos(w) and self.nounish(w):
return False
return (not self.nounish(w)) or i + 2 >= n or toks[i + 2] in ",;" or toks[i + 2].lower() in DET | PREP | JOIN \
or self.nounish(toks[i + 2]) or self.describing(toks[i + 2])
def doing(self, toks, i):
"""-> ([{"verb","to","with","passive"}], next index); the verbs of one clause share its things"""
n, verbs, passive = len(toks), [], False
while i < n and toks[i].lower() in MODAL:
if toks[i].lower() in BE:
passive = True
i += 1
if passive and i < n and not self.participle(toks[i]):
return [], i # "is absent from": a state, not something done
raws = []
while i < n and self.verbish(toks[i]):
verbs.append(self.d.lemma(toks[i].lower(), "verb"))
raws.append(toks[i].lower())
i += 1
while i < n and toks[i].lower() in PARTICLE:
i += 1 # "rolled up", "cut off"
if i + 1 < n and toks[i].lower() in JOIN and self.verbish(toks[i + 1]):
i += 1 # "V1 or V2 the X": no thing stands between, so V2 is a verb
continue
if i + 2 < n and toks[i].lower() in JOIN and self.pos(toks[i + 1]) == {"adv"} and self.verbish(toks[i + 2]):
i += 2 # "grind or otherwise process"
continue
break
if not verbs:
return [], i
if verbs[-1] in ("use", "used") and i < n and toks[i].lower() == "to" and self.infinitive(toks, i):
return self.doing(toks, i + 1) # "that is used to control or power ..."
things, withs, thing_of = [], {}, []
if i < n and toks[i].lower() not in PREP | REL and toks[i] not in ",;:()":
head, j = self.thing(toks, i)
if head:
things.append(head)
i = j
while i + 1 < n and toks[i].lower() == "of": # "the motion of a wheel": the wheel is the motion's
sub, j = self.thing(toks, i + 1)
if not sub:
break
thing_of.append(sub)
i = j
while i + 2 < n and toks[i] == "," and toks[i + 1].lower() == "or" and toks[i + 2].lower() == "of":
sub, j = self.thing(toks, i + 3) # ", or of a vehicle"
if not sub:
break
thing_of.append(sub)
i = j
while i + 1 < n and toks[i].lower() in JOIN and (self.nounish(toks[i + 1]) or toks[i + 1].lower() in DET):
sub, j = self.thing(toks, i + 1) # "a machine or mechanism": things, never verbs
if not sub:
break
things.append(sub)
i = j
while i < n and toks[i].lower() in PREP and toks[i].lower() != "of":
prep = toks[i].lower()
if prep == "to" and self.infinitive(toks, i):
more, j = self.doing(toks, i + 1) # "hired to show people": an infinitive, its own doing
first = [{"verb": v, "raw": w, "to": list(things), "to_of": list(thing_of), "with": dict(withs),
"passive": passive} for v, w in zip(verbs, raws)]
return first + more, j
head, j = self.thing(toks, i + 1)
if not head:
break
withs[prep] = head
i = j
while i < n and toks[i].lower() not in FUNCTION and toks[i] not in ",;:()" and self.pos(toks[i]) and not (
self.pos(toks[i]) - {"adv", "adj"}):
i += 1 # "pulls something apart": how it is done, part of the verb
return [{"verb": v, "raw": w, "to": list(things), "to_of": list(thing_of), "with": dict(withs), "passive": passive}
for v, w in zip(verbs, raws)], i
INSTRUMENT = re.compile(r"(?i)\bby means of\b|\bby the use of\b|\bwith the aid of\b|,?\s*\busing\s+(?=(?:an?|the)\b)")
def _instrument(text):
""""by means of a net", "using an oven": the thing a doing is done with, said one way"""
return INSTRUMENT.sub(" with ", text)
def _verb_object(main):
"""a verb definition names what is acted on in brackets straight after its verbs: "To move (water or other liquid)
by means of a pump", "To fit (a lock) with a key". That bracket is the object, not an aside; a leading "(of a
camera)" says whose doing it is and other brackets are asides. -> the clause with the object in place."""
main = re.sub(r"(?i)^\s*\((?:of|said of)[^)]*\)\s*", "", main)
m = re.match(r"(?i)^(\s*to\s+[a-z-]+(?:\s+(?:up|off|out|down|away|back))?(?:(?:\s*,\s*|\s+or\s+|\s+and\s+)[a-z-]+)*)\s*\(([^)]*)\)", main)
if m and not re.match(r"(?i)\s*(?:%s|as|e\.g|i\.e|especially|usually|often)\b" % "|".join(sorted(PREP)), m.group(2)):
inner = re.split(r"(?i),?\s*(?:such as|etc|e\.g|especially|or other|or the like)\b", m.group(2))[0].strip(" ,")
main = m.group(1) + " " + inner + " " + main[m.end():]
return re.sub(r"\([^)]*\)", " ", main)
def read(gloss, d):
"""a noun definition -> its roles; None when no head noun can be placed"""
r = _Reader(d)
main = re.split(r";|\.\s", gloss.strip())[0]
main = re.sub(r"\([^)]*\)", " ", main) # an aside in brackets is not the defining clause
main = _instrument(main)
cut = STOP.search(main)
stopped = None
if cut:
stopped, main = main[cut.start():].strip(), main[:cut.start()]
main = re.sub(r"(?i)^one who,?\s+or that which,?\s+", "One who ", main) # "One who, or that which, houses"
main = re.sub(r"(?i)^any of (the|several|various|numerous|many)\b", r"Any", main) # "Any of the family X of ..."
toks = _tokens(main)
low = [t.lower() for t in toks]
out = {"kind": None, "kinds": [], "of": [], "does": [], "where": {}, "inner": [], "unread": []}
if stopped:
out["not_read"] = stopped[:80]
if low[:2] in (["one", "who"], ["someone", "who"]) or low[:3] == ["a", "person", "who"]:
head, i = "person", low.index("who")
elif low[:2] in (["that", "which"], ["something", "that"], ["something", "which"]):
head, i = "thing", 1
else:
head, i = r.thing(toks, 0)
if not head:
return None
out["kind"], out["kinds"] = head, [head]
n = len(toks)
while i + 1 < n and low[i] in JOIN and (low[i + 1] in DET or r.nounish(low[i + 1]) or r.describing(low[i + 1])):
alt, j = r.thing(toks, i + 1) # "a person or device": joined to the head itself
if not alt:
break
out["kinds"].append(alt)
i = j
state = {"owner": None} # None: the head; otherwise the nearest noun before the phrase
def give(does, src):
for item in does:
item["src"] = src # the clause type that produced it (trusted or not by type)
if state["owner"] is None:
out["does"] += does
else:
out["inner"].append({"noun": state["owner"], "does": does})
while i < n:
w = low[i]
if w == ",":
state["owner"] = None # what follows a comma is said of the head again
i += 1
if not out["does"] and not out["where"] and not out["of"] and i < n:
alt, j = r.thing(toks, i) # "Expectation, hope"; "the Hawaiian duck, Anas wyvilliana"
if alt and (j >= n or low[j] == ","):
out["kinds"].append(alt)
i = j
continue
if w == "of":
gerund = i + 1 < n and low[i + 1].endswith("ing") and r.verbish(low[i + 1])
sub, j = (None, i) if gerund else r.thing(toks, i + 1)
if sub:
if state["owner"] is None and not out["does"] and not out["where"]:
out["of"].append(sub) # the head's own of-chain
state["owner"], i = sub, j # what follows is said of this noun
continue
i = n # "act of killing a person": the gerund's own matter, not read
continue
if w.endswith("ing") and r.verbish(w) and d.lemma(w, "verb") != w and i + 1 < n and (
low[i + 1] in DET or r.nounish(toks[i + 1]) or r.describing(toks[i + 1])):
verb = d.lemma(w, "verb") # "combining feminism and environmentalism", "containing barium"
things, j = [], i + 1
while j < n:
sub, k = r.thing(toks, j)
if not sub:
break
things.append(sub)
j = k
while j < n and (low[j] == "," or low[j] in JOIN):
j += 1
if things:
state["owner"] = None
give([{"verb": verb, "to": things, "with": {}, "passive": False}], "ing")
i = j
continue
if w == "for" and i + 1 < n and low[i + 1].endswith("ing") and r.verbish(low[i + 1]):
stated = i > 0 and low[i - 1] in PURPOSE # "used for cutting", "designed for cutting": a stated purpose
verbs, j = [(d.lemma(low[i + 1], "verb"), low[i + 1])], i + 2
while j < n and low[j] in PARTICLE:
j += 1
while j + 1 < n and low[j] in JOIN and low[j + 1].endswith("ing") and r.verbish(low[j + 1]) \
and d.lemma(low[j + 1], "verb") != low[j + 1]:
verbs.append((d.lemma(low[j + 1], "verb"), low[j + 1])) # "for baking or heating": two doings
j += 2
while j < n and low[j] in PARTICLE:
j += 1
things, k, joiner = [], j, "and"
sub, k2 = r.thing(toks, j)
while sub:
things.append(sub)
k = k2
if k + 1 < n and low[k] in JOIN and (low[k + 1] in DET or r.nounish(toks[k + 1])):
joiner = low[k]
sub, k2 = r.thing(toks, k + 1) # "a liquid or gas": either is acted on
else:
break
state["owner"] = None
give([{"verb": v, "raw": raw, "to": list(things), "with": {}, "passive": False, "purpose": True,
"joiner": joiner} for v, raw in verbs], "purpose-for" if stated else "for")
i = k
continue
if w in REL:
nxt = low[i + 1] if i + 1 < n else ""
own_subject = w == "whose" or nxt in DET or (r.nounish(nxt) and not r.verbish(nxt)) or (
r.nounish(nxt) and i + 2 < n and (low[i + 2] in BE or r.verbish(low[i + 2])))
if own_subject:
out["not_read"] = " ".join(toks[i:])[:80] # the clause is about its own subject: not asserted
break
does, j = r.doing(toks, i + 1)
if does:
give(does, "rel")
i = j
continue
if w in PURPOSE and i + 1 < n and low[i + 1] == "to" and r.infinitive(toks, i + 1):
does, j = r.doing(toks, i + 2)
if does:
state["owner"] = None # a purpose clause is the head's
give(does, "purpose")
i = j
continue
if w in PURPOSE and i + 2 < n and low[i + 1] == "for" and low[i + 2].endswith("ing") and r.verbish(low[i + 2]):
i += 1 # falls to the "for V-ing" doing below
continue
if w in PURPOSE and i + 1 < n and low[i + 1] in ("for", "as", "in"):
sub, j = r.thing(toks, i + 2)
if sub:
if state["owner"] is None:
out["where"][low[i + 1]] = sub
state["owner"], i = sub, j
continue
if (r.participle(w) and w.endswith(("ed", "en", "t", "n")) and i + 1 < n and low[i + 1] in PREP
and not (low[i + 1] == "to" and r.infinitive(toks, i + 1))):
prep = low[i + 1]
sub, j = r.thing(toks, i + 2)
if sub:
state["owner"] = None # a participle clause is the head's
give([{"verb": d.lemma(w, "verb"), "raw": w, "to": [], "with": {prep: sub}, "passive": True}], "participle")
state["owner"], i = sub, j
continue
if w == "to" and r.infinitive(toks, i):
does, j = r.doing(toks, i + 1)
if does:
state["owner"] = None
give(does, "to")
i = j
continue
if w in PREP:
sub, j = r.thing(toks, i + 1)
if sub:
if state["owner"] is None:
out["where"][w] = sub
state["owner"], i = sub, j
continue
if w not in ",;:()" and w not in MODAL | DET | JOIN:
out["unread"].append(w)
i += 1
return out
# ---------------------------------------------------------------- forms: what is verified is trusted, the rest unread
FORM_KEEP = DET | REL | PURPOSE | MODAL | PREP | JOIN | {"having", "where", "not", "no", "such", "than", "rather",
"especially", "usually", "when", "if", "so"}
_VERIFIED = None
def form(gloss):
"""a definition's form: function words kept, each run of content words written C (the M14 skeleton of 11.5's
turn_kernel, over definitions): "One who studies lymphology" and "One who repairs clocks" are both "C who C"."""
main = re.split(r";|\.\s", gloss.strip())[0]
main = re.sub(r"\([^)]*\)", " ", main)
out = []
for t in re.findall(r"[A-Za-z][A-Za-z'-]*|,", main):
w = t.lower()
if w in FORM_KEEP or w == ",":
out.append("the" if w in ("a", "an", "the") else w)
elif not out or out[-1] != "C":
out.append("C")
return " ".join(out)
def verified_forms():
"""the forms an independent judge found right on every sampled instance (data/verified_forms.json)"""
global _VERIFIED
if _VERIFIED is None:
import json
from pathlib import Path
path = Path(__file__).resolve().parent / "data" / "verified_forms.json"
try:
_VERIFIED = {item["form"] for item in json.loads(path.read_text(encoding="utf-8"))}
except (OSError, ValueError):
_VERIFIED = set()
return _VERIFIED
def read_verified(gloss, d):
"""the reading of a definition whose form is verified and which reads with every word placed; None otherwise
(an unverified form is left unread, never guessed)"""
if form(gloss) not in verified_forms():
return None
r = read(gloss, d)
if not r or r["unread"] or r.get("not_read"):
return None
return r
# ---------------------------------------------------------------- pieces trusted on common words
# Independent judgement of 200 common nouns by piece (defreader_judge/JUDGEMENT_COMMON.md, 2026-11-18): kind 93%,
# joined kinds 93%, of 88%, doings from that/which/who 93%, used/designed to 100%, participle + preposition 93%;
# not trusted: where 57%, for V-ing 73%, -ing clauses 54%, bare "to V" 29%, inner clauses (too few to rate).
TRUSTED_DOES = {"rel", "purpose", "participle"}
def read_trusted(gloss, d, also=()):
"""a definition's reading kept to the pieces judged reliable; the rest is left unsaid. A reading, not a proof: what is
built on it is offered with the definition beside it, never marked answered on its own. `also` names clause types
under judgement (development only)."""
r = read(gloss, d)
if not r:
return None
ok = TRUSTED_DOES | set(also)
return {"kind": r["kind"], "kinds": list(r["kinds"]), "of": list(r["of"]),
"does": [x for x in r["does"] if x.get("src") in ok], "where": {}, "inner": [],
"unread": list(r["unread"]), "left_unsaid": [x["verb"] for x in r["does"] if x.get("src") not in ok]}
def read_verb(gloss, d):
"""a verb definition ("To be supported by a fluid of greater density", "To operate a pedal") -> what doing it is:
{"means": [{"verb","raw","to","to_of","with","passive"}], "unread"}; None when it does not open as "To V"."""
r = _Reader(d)
main = re.split(r";|\.\s", gloss.strip())[0]
main = _instrument(_verb_object(main))
cut = STOP.search(main)
if cut:
main = main[:cut.start()]
toks = _tokens(main)
if len(toks) < 2 or toks[0].lower() != "to":
return None
does, i = r.doing(toks, 1)
if not does:
return None
for item in does:
item["src"] = "verb"
rest = [t.lower() for t in toks[i:] if t not in ",;:()" and t.lower() not in MODAL | DET | JOIN]
return {"means": does, "unread": rest}