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 Download workbench/converse/claim_shape.py from psiloceyeben/oracle7: direct link, hf CLI and curl.
- Browser
- Download file 24.7 kB
-
https://huggingface.co/psiloceyeben/oracle7/resolve/main/workbench/converse/claim_shape.py
- Command line
-
hf download hf://psiloceyeben/oracle7/workbench/converse/claim_shape.py
-
curl -L -o claim_shape.py https://huggingface.co/psiloceyeben/oracle7/resolve/main/workbench/converse/claim_shape.py
24.7 kB
| """Receive a claim as owned parts and joins, retaining every source span. | |
| The native dictionary supplies open words and their forms. The small closed | |
| grammar below supplies joins, attribution and modal scope; it contains no | |
| project domains or example answers. A received claim is not a verified fact. | |
| """ | |
| import copy | |
| import json | |
| import re | |
| from turn_meaning import outside_literals, literals, _ExactWords | |
| WORD = re.compile(r"[A-Za-z0-9_]+(?:['’-][A-Za-z0-9_]+)*") | |
| COPULA = {"am", "is", "are", "was", "were", "be", "been", "being"} | |
| MODAL = {"should": "obligation", "must": "obligation", "shall": "obligation", "may": "possibility_or_permission", | |
| "might": "possibility", "could": "possibility", "can": "ability_or_possibility", "will": "future", "would": "conditional"} | |
| AUXILIARY = {"do", "does", "did", "have", "has", "had"} | |
| NEGATED_AUX = {"don't": "do", "doesn't": "does", "didn't": "did", "isn't": "is", "aren't": "are", "wasn't": "was", | |
| "weren't": "were", "can't": "can", "cannot": "can", "couldn't": "could", "shouldn't": "should", | |
| "mustn't": "must", "won't": "will", "wouldn't": "would", "hasn't": "has", "haven't": "have", "hadn't": "had"} | |
| DETERMINERS = {"a", "an", "the", "my", "your", "our", "their", "his", "her", "its", "this", "that", "these", "those", "every", "each", "some", "any", "no"} | |
| PREPOSITIONS = {"to", "from", "with", "without", "in", "on", "at", "for", "by", "like", "as", "into", "onto", "through", "across", "under", "over", "above", "below", "beside", "between", "around", "against", "within", "beyond", "before", "after", "until", "during"} | |
| REPORT = re.compile(r"^(?P<speaker>I|we|[A-Z][\w-]*(?:\s+[A-Z][\w-]*)?)\s+" | |
| r"(?P<stance>(?:(?:do not|don't|does not|doesn't)\s+)?(?:(?:personally|really|strongly|honestly)\s+)?" | |
| r"(?:think|thinks|believe|believes|feel|feels|suspect|suspects|hope|hopes|say|says|said|claim|claims|argue|argues))\b\s*(?:that\s+)?", re.I) | |
| PREFIX = re.compile(r"^(only if|provided that|because|if|when|unless|while|although|after|before)\b\s*", re.I) | |
| SUFFIX = re.compile(r"\b(because|only if|provided that|unless|when|if|so that|in order to)\b", re.I) | |
| COORD = re.compile(r"\b(and then|and|but|or|then)\b", re.I) | |
| def atom(source, start, end, **fields): | |
| while start < end and source[start].isspace(): | |
| start += 1 | |
| while end > start and (source[end - 1].isspace() or source[end - 1] in ".?!,;"): | |
| end -= 1 | |
| return dict(text=source[start:end], span=[start, end], source=source, **fields) | |
| class ClaimReader: | |
| def __init__(self, reader, meanings=None): | |
| from turn_reader import Reader | |
| self.native = Reader(reader.d, _ExactWords()) | |
| self.d = reader.d | |
| self.meanings = meanings or {} | |
| def _verb(self, word): | |
| low = word.lower() | |
| if low in DETERMINERS or low in PREPOSITIONS or low in {"and", "or", "but", "if", "when", "that", "which", "who", "i", "we", "you", "they", "it"}: | |
| return None | |
| target = self.meanings.get(low, {}).get("meaning", low) | |
| lemma = self.d.lemma(target, "verb") | |
| if "verb" in self.d.pos(target): | |
| return lemma | |
| try: | |
| explicit = self.d.db.execute("SELECT 1 FROM forms WHERE form=? AND pos='verb' LIMIT 1", (target,)).fetchone() | |
| except Exception: | |
| explicit = None | |
| return lemma if explicit and "verb" in self.d.pos(lemma) else None | |
| def _tokens(self, start, end): | |
| tokens = [(m.group(), m.start(), m.end()) for m in WORD.finditer(self.mask, start, end)] | |
| tokens += [(x["text"], *x["span"]) for x in self.g["literals"] if start <= x["span"][0] and x["span"][1] <= end] | |
| return sorted(tokens, key=lambda x: x[1]) | |
| def _syntax(self, start, end, kind): | |
| self.g["syntax"].append(atom(self.text, start, end, kind=kind)) | |
| def _hole(self, text, start, end, kind="reading"): | |
| h = atom(self.text, start, end, kind=kind, need=text) | |
| self.g["holes"].append(h) | |
| return [] | |
| def _predicate(self, tokens, inherited=False, request=False): | |
| if not tokens: | |
| return None | |
| if inherited and self._verb(tokens[0][0]): | |
| return 0 | |
| # Closed grammatical markers locate the finite phrase without guessing | |
| # a noun/verb sense from an incidental word in a dictionary definition. | |
| for i, (word, _, _) in enumerate(tokens): | |
| low = word.lower() | |
| if i and (low in COPULA or low in MODAL or low in AUXILIARY or low in NEGATED_AUX): | |
| return i | |
| if request and self._verb(tokens[0][0]): | |
| counts = {pos: sum(len(gs) for p, gs in self.d.entries(tokens[0][0].lower()) if p == pos) for pos in ("noun", "adj", "verb")} | |
| if counts["verb"] >= max(counts["noun"], counts["adj"]): | |
| return 0 | |
| for i, (word, _, _) in enumerate(tokens): | |
| if not i or not self._verb(word) or word.lower().endswith("ing"): | |
| continue | |
| before = tokens[i - 1][0].lower() | |
| if before in DETERMINERS or before in PREPOSITIONS: | |
| continue | |
| # A following verb-only word cannot be the apparent object head. | |
| if i + 1 < len(tokens) and self._verb(tokens[i + 1][0]) and self.d.pos(tokens[i + 1][0].lower()) <= {"verb"} and not tokens[i + 1][0].lower().endswith("ing"): | |
| continue | |
| return i | |
| return None | |
| def _role_boundaries(self, tokens): | |
| """Retain competing finite boundaries allowed by noun forms/agreement. | |
| This is a conservative ambiguity check, not a likelihood ranking of | |
| dictionary senses. Closed auxiliaries already locate a finite phrase. | |
| """ | |
| if any(w.lower() in COPULA | set(MODAL) | AUXILIARY | set(NEGATED_AUX) for w, _, _ in tokens): | |
| return [] | |
| candidates = [] | |
| for i, (word, _, _) in enumerate(tokens): | |
| if not i or not self._verb(word): continue | |
| if i + 1 < len(tokens) and self._verb(tokens[i + 1][0]) and self.d.pos(tokens[i + 1][0].lower()) <= {"verb"}: | |
| continue | |
| prefix = [w.lower() for w, _, _ in tokens[:i]] | |
| if prefix[-1] in DETERMINERS | PREPOSITIONS: continue | |
| # All pre-head words must remain possible nominal modifiers. | |
| if any(w in PREPOSITIONS or (self.d.pos(w) and not self.d.pos(w) & {"noun", "adj", "name", "proper noun", "det"} and w not in DETERMINERS) | |
| for w in prefix): continue | |
| number = self._number({"text": prefix[-1]}) | |
| if number is None: continue | |
| try: | |
| forms = [set(json.loads(r[0])) for r in self.d.db.execute("SELECT tags_json FROM forms WHERE form=? AND pos='verb'", (word.lower(),))] | |
| except (ValueError, TypeError): | |
| forms = [] | |
| # Base forms take plural subjects; third-person singular forms take | |
| # singular subjects. Past tense is number-neutral. Participles alone | |
| # do not supply the finite verb for this received class. | |
| finite = any("past" in tags and "participle" not in tags for tags in forms) | |
| finite |= number == "singular" and any("third-person" in tags for tags in forms) | |
| finite |= number == "plural" and word.lower() == self._verb(word) | |
| if finite: candidates.append(i) | |
| return candidates | |
| def _has_clause(self, start, end, inherited=False): | |
| return self._predicate(self._tokens(start, end), inherited=inherited) is not None | |
| def _complements(self, start, end, lemma): | |
| result = [] | |
| cursor, role, marker = start, "property" if lemma == "be" else "object", None | |
| markers = [(word, a, z) for word, a, z in self._tokens(start, end) if word.lower() in PREPOSITIONS] | |
| markers += [(m.group(), m.start(), m.end()) for m in re.finditer(r"\bregardless of\b", self.mask, re.I) if start <= m.start() < end] | |
| for word, a, z in sorted(markers, key=lambda x: x[1]): | |
| if a > cursor: result.append(atom(self.text, cursor, a, role=role, marker=marker)) | |
| marker = word.lower() | |
| self._syntax(a, z, "preposition") | |
| cursor, role = z, "preposition" | |
| if cursor < end: result.append(atom(self.text, cursor, end, role=role, marker=marker)) | |
| return result | |
| def read(self, text, previous=None, content_span=None): | |
| self.text = str(text or "") | |
| self.mask = outside_literals(self.text) | |
| self.previous = previous | |
| native = self.native.read(self.text) | |
| self.g = {"version": 1, "original": self.text, "sources": [self.text], "act": native["mood"], "nodes": [], "roots": [], | |
| "links": [], "syntax": [], "holes": [], "literals": literals(self.text), "correction": None, | |
| "basis": "native dictionary + received clause parts", "truth": "unverified", "context_sources": []} | |
| start, end = content_span or (0, len(self.text)) | |
| if content_span: | |
| if start: | |
| self._syntax(0, start, "received envelope") | |
| if end < len(self.text): | |
| self._syntax(end, len(self.text), "received envelope") | |
| revised = re.match(r"\s*(?:(?:actually|no|rather|instead)[,\s]+|I meant\s+)", self.mask, re.I) if not content_span else None | |
| if revised: | |
| self.g["correction"] = atom(self.text, revised.start(), revised.end(), kind="replacement") | |
| self._syntax(revised.start(), revised.end(), "correction") | |
| start = revised.end() | |
| # A direct modal question/request is not a received assertion. | |
| if self.text.rstrip().endswith("?"): | |
| self.g["act"] = "request" if re.match(r"\s*(?:can|could|would|will)\s+you\b", self.mask, re.I) else "question" | |
| elif PREFIX.match(self.mask.strip()) and "," in self.mask: | |
| self.g["act"] = "statement" | |
| roots = self._read(start, end, attribution={"speaker": "user", "stance": "asserted"}, speech_act=self.g["act"]) | |
| self.g["roots"] = roots | |
| if roots and self.g["act"] not in ("question", "social"): | |
| self.g["act"] = "request" if any(n["speech_act"] == "request" for n in self.g["nodes"] if n["id"] in roots) else "statement" | |
| self._bind_references() | |
| return self.g | |
| def _read(self, start, end, attribution, speech_act, inherited=None, depth=0): | |
| part = atom(self.text, start, end) | |
| start, end = part["span"] | |
| if start >= end: | |
| return [] | |
| if depth > 12: | |
| return self._hole("Name the clauses separately; this nesting has not been received.", start, end) | |
| mask = self.mask[start:end] | |
| # Every independent sentence gets a part; punctuation inside literal | |
| # source/code remains data. | |
| cuts = list(re.finditer(r"[;.!?](?=\s|$)", mask)) | |
| if cuts: | |
| result, cursor = [], start | |
| for cut in cuts: | |
| result += self._read(cursor, start + cut.start(), attribution, speech_act, inherited, depth + 1) | |
| cursor = start + cut.end() | |
| result += self._read(cursor, end, attribution, speech_act, inherited, depth + 1) | |
| return result | |
| # An attribution owns its embedded claim, never the user's endorsement. | |
| report = REPORT.match(self.text[start:end]) | |
| if report and self._has_clause(start + report.end(), end): | |
| speaker = report.group("speaker") | |
| own = speaker.lower() in ("i", "we") | |
| stance = "withheld_belief" if re.search(r"\bnot\b|n't\b", report.group("stance"), re.I) else "tentative" if own else "reported" | |
| attr = {"speaker": "user" if own else speaker, "stance": stance, | |
| "wording": atom(self.text, start, start + report.end())} | |
| return self._read(start + report.end(), end, attr, "statement", inherited, depth + 1) | |
| # Prefix situations bind to their whole main clause, not to one noun. | |
| pre = PREFIX.match(mask) | |
| if pre: | |
| comma = mask.find(",", pre.end()) | |
| if comma < 0: | |
| return self._hole("Supply the main clause after this condition.", start, end, "main_clause") | |
| condition = self._read(start + pre.end(), start + comma, attribution, "statement", None, depth + 1) | |
| main = self._read(start + comma + 1, end, attribution, speech_act, inherited, depth + 1) | |
| self._join(pre.group(1).lower(), condition, main, start, start + pre.end()) | |
| return main | |
| # Reasons and conditions are links between received clauses. No link | |
| # here promotes the reason to a proven causal account. | |
| suffix = SUFFIX.search(mask) | |
| if suffix: | |
| main = self._read(start, start + suffix.start(), attribution, speech_act, inherited, depth + 1) | |
| linked = self._read(start + suffix.end(), end, attribution, "statement", None, depth + 1) | |
| self._join(suffix.group(1).lower(), linked, main, start + suffix.start(), start + suffix.end()) | |
| if suffix.group(1).lower() == "because" and attribution.get("stance") == "withheld_belief": | |
| for link in self.g["links"]: | |
| if link["from"] in linked and link["to"] in main: | |
| link["scope"] = "unresolved" | |
| self.g["holes"].append(atom(self.text, start + suffix.start(), end, kind="reason_scope", | |
| need="Does this explain why you withhold belief, or is it the reason inside the claim you are withholding?")) | |
| return main | |
| # A relative clause receives the referenced object as its subject. | |
| relative = re.search(r"\b(that|which|who)\b", mask, re.I) | |
| if relative and self._has_clause(start + relative.end(), end, inherited=True): | |
| main = self._read(start, start + relative.start(), attribution, speech_act, inherited, depth + 1) | |
| parent = next((n for n in self.g["nodes"] if main and n["id"] == main[-1]), None) | |
| target = next((c for c in (parent or {}).get("complements", []) if c["role"] == "object"), None) | |
| if target: | |
| child = self._read(start + relative.end(), end, attribution, "requirement" if parent["speech_act"] == "request" else "statement", target, depth + 1) | |
| self._join("relative", child, main, start + relative.start(), start + relative.end()) | |
| return main | |
| return self._hole("Name what this relative clause describes.", start + relative.start(), end, "reference") + main | |
| # Coordination splits only where a following clause/predicate is read; | |
| # object lists such as 'salt and pepper' stay one object. | |
| for join in COORD.finditer(mask): | |
| after = start + join.end() | |
| if not self._has_clause(after, end, inherited=True): | |
| continue | |
| first = self._read(start, start + join.start(), attribution, speech_act, inherited, depth + 1) | |
| parent = next((n for n in self.g["nodes"] if first and n["id"] == first[-1]), None) | |
| tokens = self._tokens(after, end) | |
| shared = parent["subject"] if parent and tokens and self._verb(tokens[0][0]) else None | |
| second = self._read(after, end, attribution, speech_act, shared, depth + 1) | |
| self._join(join.group().lower(), first, second, start + join.start(), start + join.end()) | |
| explicit_new_speaker = REPORT.match(self.text[after:end].lstrip()) | |
| if join.group().lower() == "but" and attribution.get("wording") and not shared and not explicit_new_speaker: | |
| for node in self.g["nodes"]: | |
| if node["id"] in second: | |
| node["attribution"]["candidates"] = [attribution["speaker"], "user"] | |
| node["attribution"]["speaker"] = "unresolved" | |
| self.g["holes"].append(atom(self.text, after, end, kind="attribution_scope", | |
| need="Does this contrasting clause belong to the reported view too, or is it your separate claim?", candidates=[attribution["speaker"], "user"])) | |
| return first + second | |
| # Polite action envelopes are grammar, not part of a subject. | |
| envelope = re.match(r"(?:(?:can|could|would|will)\s+you\s+(?:please\s+)?|please\s+|let(?:'s| us)\s+)", mask, re.I) | |
| if envelope: | |
| self._syntax(start, start + envelope.end(), "request_envelope") | |
| start += envelope.end() | |
| speech_act = "request" | |
| focus = re.match(r"(?:even|also|only)\s+", self.mask[start:end], re.I) | |
| focus_atom = None | |
| if focus: | |
| focus_atom = atom(self.text, start, start + focus.end(), kind="focus") | |
| start += focus.end() | |
| tokens = self._tokens(start, end) | |
| request = bool(tokens and speech_act == "request" and not attribution.get("wording") and self._verb(tokens[0][0])) | |
| pi = self._predicate(tokens, inherited is not None, request) | |
| if pi is None: | |
| return self._hole("Name the action or property relating the subject to the rest of this clause.", start, end, "predicate") | |
| boundaries = self._role_boundaries(tokens) if pi and inherited is None else [] | |
| if boundaries: | |
| pi = boundaries[0] | |
| if pi == 0: | |
| subject = copy.deepcopy(inherited) if inherited else {"text": "you", "implicit": "requested actor"} | |
| if not inherited: | |
| speech_act = "request" | |
| else: | |
| subject = atom(self.text, start, tokens[pi][1]) | |
| if speech_act == "request" and not re.match(r"(?:i|we)\s+(?:want|need)\b", self.mask[start:end], re.I): | |
| speech_act = "statement" # a third-party 'should' is a claim, not permission to act | |
| j, modal, negatives, auxiliaries = pi, None, [], [] | |
| while j < len(tokens): | |
| word, a, z = tokens[j] | |
| low = word.lower() | |
| base = NEGATED_AUX.get(low, low) | |
| if low in NEGATED_AUX: | |
| negatives.append(atom(self.text, a, z)) | |
| if base in MODAL: | |
| modal = atom(self.text, a, z, kind=MODAL[base], lemma=base) | |
| auxiliaries.append(atom(self.text, a, z)); j += 1 | |
| elif base in COPULA or base in AUXILIARY: | |
| auxiliaries.append(atom(self.text, a, z)); j += 1 | |
| elif low in ("not", "never"): | |
| negatives.append(atom(self.text, a, z)); j += 1 | |
| else: | |
| break | |
| base = NEGATED_AUX.get(tokens[pi][0].lower(), tokens[pi][0].lower()) | |
| copular = bool(auxiliaries and any(NEGATED_AUX.get(x["text"].lower(), x["text"].lower()) in COPULA for x in auxiliaries)) | |
| modifiers = [] | |
| while j + 1 < len(tokens) and "adv" in self.d.pos(tokens[j][0].lower()) and any(self._verb(x[0]) for x in tokens[j + 1:]): | |
| modifiers.append(atom(self.text, tokens[j][1], tokens[j][2])); j += 1 | |
| lexical = self._verb(tokens[j][0]) if j < len(tokens) else None | |
| # An adjective after be is a property, even if another dictionary sense | |
| # is a verb. A by-agent or -ing form makes the action reading explicit. | |
| # A determiner between be and the next word ("is a river", "was the capital") opens a noun phrase: the word after | |
| # it is the complement's head, not a verb, even when the store also lists a verb sense ("to river"). | |
| gap = self.text[auxiliaries[-1]["span"][1]:tokens[j][1]].lower().split() if (copular and j < len(tokens)) else [] | |
| nominal = any(w.strip(",;:") in DETERMINERS for w in gap) | |
| if copular and j < len(tokens) and (nominal or "adj" in self.d.pos(tokens[j][0].lower()) or not lexical) and not tokens[j][0].lower().endswith("ing"): | |
| lemma, p_end = "be", tokens[j - 1][2] | |
| elif lexical: | |
| lemma, p_end = lexical, tokens[j][2] | |
| j += 1 | |
| elif copular: | |
| lemma, p_end = "be", tokens[j - 1][2] | |
| else: | |
| return self._hole("The verb after this auxiliary is not held by the dictionary; supply its meaning.", tokens[pi][1], end, "predicate") | |
| predicate = atom(self.text, tokens[pi][1], p_end, lemma=lemma) | |
| if tokens[max(pi, j - 1)][0].lower() in self.meanings: | |
| predicate["meaning"] = copy.deepcopy(self.meanings[tokens[j - 1][0].lower()]) | |
| tail_start = tokens[j][1] if j < len(tokens) else end | |
| complements = self._complements(tail_start, end, lemma) | |
| node = {"id": "P%d" % (len(self.g["nodes"]) + 1), "kind": "claim", "text": part["text"], "span": part["span"], "source": self.text, | |
| "subject": subject, "predicate": predicate, "complements": complements, "modal": modal, | |
| "polarity": "negative" if negatives else "positive", "negatives": negatives, "auxiliaries": auxiliaries, | |
| "attribution": copy.deepcopy(attribution), "speech_act": speech_act, "truth": "unverified", "focus": focus_atom, "modifiers": modifiers} | |
| self.g["nodes"].append(node) | |
| if len(boundaries) > 1: | |
| candidates = [] | |
| for boundary in boundaries: | |
| word, a, z = tokens[boundary] | |
| candidates.append({"subject": atom(self.text, start, a), | |
| "predicate": atom(self.text, a, z, lemma=self._verb(word)), | |
| "complements": self._complements(z, end, self._verb(word))}) | |
| node["role_reading"] = {"status": "unresolved", "candidates": candidates} | |
| choices = " or ".join(repr(c["subject"]["text"]) for c in candidates) | |
| self.g["holes"].append(atom(self.text, start, end, kind="role_boundary", node=node["id"], | |
| need="Which is the subject: %s? You can say 'The subject is ...'." % choices)) | |
| return [node["id"]] | |
| def _join(self, word, origins, targets, start, end): | |
| kind = ("reason" if word == "because" else "purpose" if word in ("so that", "in order to") else | |
| "contrast" if word in ("but", "although") else "sequence" if word in ("then", "and then") else | |
| "alternative" if word == "or" else "coordination" if word == "and" else "relative" if word == "relative" else "condition") | |
| connector = atom(self.text, start, end) | |
| self.g["syntax"].append(dict(connector, kind="join")) | |
| for origin in origins: | |
| for target in targets: | |
| self.g["links"].append({"kind": kind, "mode": word, "from": origin, "to": target, "connector": connector}) | |
| def _bind_references(self): | |
| prior_nodes = (self.previous or {}).get("nodes", []) | |
| prior_roots = (self.previous or {}).get("roots", []) | |
| prior_parts = [part for n in prior_nodes if n["id"] in prior_roots and n.get("role_reading", {}).get("status") != "unresolved" for part in [n["subject"]] + | |
| [c for c in n["complements"] if c["role"] == "object"]] | |
| unique = {x["text"].lower(): x for x in prior_parts} | |
| self.g["reference_context"] = list(unique.values()) | |
| for source in (self.previous or {}).get("sources", []): | |
| if source not in self.g["sources"]: | |
| self.g["sources"].append(source); self.g["context_sources"].append(source) | |
| for node in self.g["nodes"]: | |
| for subject in [node["subject"]] + node["complements"]: | |
| if subject["text"].lower() not in ("it", "they", "this", "that", "these", "those", "them"): | |
| continue | |
| plural = subject["text"].lower() in ("they", "these", "those", "them") | |
| candidates = [x for x in unique.values() if self._number(x) in (None, "plural" if plural else "singular")] | |
| if len(candidates) == 1: | |
| subject["binding"] = {"target": copy.deepcopy(candidates[0]), "basis": "previous received referent"} | |
| else: | |
| self.g["holes"].append(dict(subject, kind="reference", need="Name which thing this pronoun refers to.", candidates=[x["text"] for x in candidates])) | |
| def _number(self, part): | |
| words = WORD.findall(part["text"].lower()) | |
| if not words: return None | |
| head = words[-1] | |
| try: | |
| rows = self.d.db.execute("SELECT tags_json FROM forms WHERE form=? AND pos='noun'", (head,)).fetchall() | |
| if any("plural" in row[0] for row in rows): return "plural" | |
| except Exception: | |
| pass | |
| return "singular" if "noun" in self.d.pos(head) else None | |
| def receive(text, reader, previous=None, meanings=None): | |
| return ClaimReader(reader, meanings).read(text, previous) | |