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
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
#!/usr/bin/env python3
"""TURN READER (round 5 of the open-conversation loop; Ben 2026-11-06: "we need basically an autocorrect for misspellings
and the turn reader"). Two parts, both built from what Oracle7 already holds; nothing is written about any turn.

1. SPELLER. A word is KNOWN if it occurs >= 2 times in the frequency corpus (DailyDialog's human dialogue, Oracle7's own
   released records, the head's dictionary glosses) or the head's dictionary has an entry for it that is not only a
   spelling variant. A word whose every dictionary entry says "<obsolete|alternative|pronunciation|misspelling...>
   spelling of X" becomes X. An unknown word becomes the corpus word at edit distance 1 (else 2; transpositions count
   as 1) with the best score: log frequency + context (the corpus bigram with the word before and the word after)
   - 2 per edit; or a split into two known words ("thankyou"). Words with digits, and words with no candidate, are kept
   (names, versions, coined terms: holes, never guessed).
2. READER. The corrected turn -> a typed FRAME, by grammar (closed-class words and the dictionary's parts of speech),
   the kernel's law 3 generalised (the wanted thing is the head of the asking phrase):
     mood     question | request | commitment | social | statement
     verb     the lemma of the acting verb (after the request marker; "get X fixed" -> fix)
     object   the noun phrase the verb acts on (head of the asking phrase for a question)
     topic    the noun phrase after on/about/of/regarding/for
     goal     the clause after so (that) / in order to / because
     status   a question about the state of work ("did it work", "is it live", "where are we")
     refs     it/this/that/them in object or topic (bound by the caller to common ground)
     keys     the content lemmas of verb + object + topic (what a reply must be about)
usage: module (Speller(db, texts), Reader(db, speller).read(turn))"""
from __future__ import annotations

import collections
import json
import math
import re

TOK = re.compile(r"[A-Za-z0-9][A-Za-z0-9'\-]*|[?.!,;:]")
WORD = re.compile(r"[a-z]+")
SPELLING_OF = re.compile(r"^(?:(?:obsolete|archaic|alternative|nonstandard|informal|eye dialect|pronunciation|dated|"
                         r"rare|colloquial|common|uncommon)\s+)*(?:spelling|misspelling|form) of ([a-z][a-z' ]*?)\s*(?:[.,;(]|$)",
                         re.I)
INFLECTION = re.compile(r"\b(?:plural|simple past|past participle|present participle|third-person|gerund|comparative|"
                        r"superlative|first-person|second-person) .*\bof\b", re.I)
FUNC = {"and", "or", "but", "with", "on", "in", "at", "to", "for", "of", "from", "by", "as", "then", "that", "which",
        "who", "when", "so", "if", "till", "until", "than", "like", "into", "onto", "about", "over", "after", "before",
        "not", "while", "where", "what", "how", "why", "also", "just", "now", "please", "too", "very", "here", "there"}
ALPHA = "abcdefghijklmnopqrstuvwxyz"
CLOSED = {"pron", "prep", "conj", "det", "article", "particle", "num", "contraction"}


def _glosses(g):
    try:
        return json.loads(g or "[]")
    except Exception:  # noqa: BLE001
        return []


class Dict:
    """the head's own dictionary store (its own read-only connection: the head's is bound to the head's thread)"""

    def __init__(self, db):
        self.db = db
        self._e, self._l = {}, {}

    def entries(self, w):
        if w not in self._e:
            try:
                self._e[w] = [(p, _glosses(g)) for p, g in
                              self.db.execute("SELECT pos, glosses_json FROM entry WHERE word=?", (w,)).fetchall()]
            except Exception:  # noqa: BLE001
                self._e[w] = []
        return self._e[w]

    def pos(self, w):
        return {p for p, _ in self.entries(w)}

    def lemma(self, w, want=None):
        """lemma by the dictionary's forms table (first non-archaic reading; `want` = a part of speech to prefer)"""
        k = (w, want)
        if k not in self._l:
            out = w
            own = [(p, gs) for p, gs in self.entries(w) if not want or p == want]
            if own and not all(INFLECTION.search(g) or SPELLING_OF.match(g.strip()) for _, gs in own for g in gs):
                self._l[k] = w                             # the word is a lemma in its own right (run, brief, hugging)
                return w
            try:
                rows = self.db.execute("SELECT lemma, pos, tags_json FROM forms WHERE form=?", (w,)).fetchall()
            except Exception:  # noqa: BLE001
                rows = []
            rows = [r for r in rows if not any(t in (r[2] or "") for t in ("archaic", "obsolete", "nonstandard",
                                                                             "alternative", "dialectal"))]
            if want:
                rows = [r for r in rows if r[1] == want] or rows
            rows = [r for r in rows if re.fullmatch(r"[a-z]+", (r[0] or "").lower())]
            if rows and rows[0][0] != w and self.entries(rows[0][0]):
                out = rows[0][0].lower()
            self._l[k] = out
        return self._l[k]

    def spelling_target(self, w):
        """X if EVERY entry of w is a spelling variant of X"""
        es = self.entries(w)
        if not es:
            return None
        tgt = None
        for _, gs in es:
            for g in gs:
                m = SPELLING_OF.match(g.strip())
                if not m:
                    return None
                tgt = tgt or m.group(1).lower()
        return tgt if tgt and tgt != w else None


class Speller:
    def __init__(self, d, texts, min_known=2):
        self.d = d
        self.freq = collections.Counter()
        self.bi = collections.Counter()
        for t in texts:
            ws = WORD.findall(t.lower())
            self.freq.update(ws)
            self.bi.update(zip(ws, ws[1:]))
        self.min_known = min_known
        self.vocab = {w for w, k in self.freq.items() if k >= min_known and len(w) >= 1}
        self.total = sum(self.freq.values())
        self._c = {}
        self.conv = collections.Counter()

    def observe(self, text):
        """common ground: a word the person has used twice in this conversation is theirs (a name, a project)"""
        self.conv.update(set(WORD.findall((text or "").lower())))

    def known(self, w):
        if self.freq.get(w, 0) >= self.min_known or self.conv.get(w, 0) >= 2:
            return True
        es = self.d.entries(w)
        return bool(es) and self.d.spelling_target(w) is None

    @staticmethod
    def edits1(w):
        sp = [(w[:i], w[i:]) for i in range(len(w) + 1)]
        dels = [a + b[1:] for a, b in sp if b]
        tr = [a + b[1] + b[0] + b[2:] for a, b in sp if len(b) > 1]
        rep = [a + c + b[1:] for a, b in sp if b for c in ALPHA]
        ins = [a + c + b for a, b in sp for c in ALPHA]
        return set(dels + tr + rep + ins)

    def _cands(self, w):
        if w not in self._c:
            e1 = self.edits1(w)
            c = [(x, 1) for x in e1 if x in self.vocab]
            if not c and len(w) >= 5:
                c = [(y, 2) for x in e1 for y in self.edits1(x) if y in self.vocab]
            c = list(dict(sorted(c, key=lambda t: -t[1])).items())       # keep the smaller distance per word
            for i in range(2, len(w) - 1):                                   # a missing space
                a, b = w[:i], w[i:]
                if self.freq.get(a, 0) >= 50 and self.freq.get(b, 0) >= 50:
                    c.append((a + " " + b, 1))
            self._c[w] = c
        return self._c[w]

    def score(self, c, dist, prev, nxt, w=""):
        import difflib
        ws = c.split()
        self._ratio = difflib.SequenceMatcher(None, w, c.replace(" ", "")).ratio() if w else 0.0
        s = math.log(self.freq.get(ws[0], 0) + 1) - 2.0 * dist + 4.0 * self._ratio
        if self.conv.get(ws[0], 0):
            s += 3.0                                   # a word this person already used here
        if prev:
            s += 1.5 * math.log(self.bi.get((prev, ws[0]), 0) + 1)
        if nxt:
            s += 1.5 * math.log(self.bi.get((ws[-1], nxt), 0) + 1)
        return s

    def fix_word(self, w, prev=None, nxt=None):
        lw = w.lower()
        if any(ch.isdigit() for ch in lw) or len(lw) <= 2 or not lw.isalpha():
            return w
        if self.freq.get(lw, 0) >= 20 or self.conv.get(lw, 0) >= 2:
            return w                                   # common as written: never "corrected" (okay stays okay)
        t = self.d.spelling_target(lw)
        if t:
            return t
        if self.known(lw):
            return w
        cs = self._cands(lw)
        if not cs:
            return w
        best = max(cs, key=lambda cd: self.score(cd[0], cd[1], prev, nxt, lw))
        return best[0]

    def fix(self, text):
        toks = TOK.findall(text or "")
        out = []
        low = [t.lower() for t in toks]
        for i, t in enumerate(toks):
            prev = out[-1].lower().split()[-1] if out and out[-1][0].isalpha() else None
            nxt = low[i + 1] if i + 1 < len(low) and low[i + 1][0].isalpha() else None
            out.append(self.fix_word(t, prev, nxt) if t[0].isalpha() and "'" not in t else t)
        changes = [(a, b) for a, b in zip(toks, out) if a.lower() != b.lower()]
        s = ""
        for t in out:
            s += (t if t in "?.!,;:" else (" " + t if s else t))
        return s, changes


# ---------------- the reader: grammar (closed-class words) + the dictionary's parts of speech
WH = {"what", "whats", "what's", "where", "wheres", "where's", "when", "why", "how", "hows", "how's", "who", "whos",
      "who's", "which"}
AUX = {"is", "are", "was", "were", "did", "does", "do", "has", "have", "had", "can", "could", "will", "would", "should",
       "shall", "may", "might", "isnt", "isn't", "didnt", "didn't", "doesnt", "doesn't", "arent", "aren't"}
REQUEST = re.compile(r"^(?:.*?\b)?(?:(?:can|could|would|will)\s+(?:you|we|u)(?:\s+please)?(?:\s+just)?|please|"
                     r"let'?s|lets|let us|(?:we|i)\s+(?:need|want|have)(?:\s+to)?|need\s+to|make\s+sure(?:\s+that)?|"
                     r"go\s+ahead\s+and|i'?d\s+like(?:\s+you)?(?:\s+to)?)\s+(.+)$", re.I)
SHOULD = re.compile(r"^(?:.*?\b)?(?:should|must|has\s+to|needs\s+to|have\s+to)\s+(?:be\s+)?(.+)$", re.I)
COMMIT = re.compile(r"^(?:.*?\b)?(?:i'?ll|i\s+will|i'?m\s+gonna|i\s+am\s+going\s+to|i'?m\s+going\s+to)\s+(.+)$", re.I)
GOAL = re.compile(r"\b(?:so\s+that|so|in\s+order\s+to|because|that\s+way)\s+(.+)$", re.I)
TOPIC = re.compile(r"\b(?:on|about|regarding|of|for|called)\s+(.+)$", re.I)
REFW = {"it", "this", "that", "them", "these", "those", "everything"}
STATE_Q = re.compile(r"^(?:did|does|is|are|was|has|have)\s+(?:it|that|this|they|everything|the\s+\w+|\w+)\s+"
                     r"(?:\w+\s+)?(?:work|working|worked|done|finished|live|ready|up|running|uploaded|deployed|built|"
                     r"fixed|complete|completed|go|through)\b|^(?:where|how)\s+(?:are|is)\s+(?:we|it|things|that)\b|"
                     r"\bwhere\s+(?:are\s+)?we\s+at\b|\bwhats?\s+(?:the\s+)?(?:status|progress)\b|"
                     r"\bi\s+(?:dont|don't|do\s+not)\s+see\s+(?:it|the\s+\w+)", re.I)
CAUSE = {"get", "have", "make", "keep"}        # get/have X <participle> -> the participle is the act


class Reader:
    def __init__(self, d, speller):
        self.d, self.sp = d, speller

    def _p(self, w):
        return self.d.pos(w.lower())

    def is_closed(self, w):
        lw = w.lower()
        p = self._p(lw)
        return lw in REFW or lw in AUX or lw in FUNC or lw in WH or (bool(p) and p <= (CLOSED | {"adv", "intj"}))

    def _np(self, toks):
        """the noun phrase at the head of toks: skip determiners/possessives, take noun/adj/name words, stop at a
        function word, a verb-only word or punctuation"""
        out = []
        for t in toks:
            lw = t.lower()
            if lw in "?.!,;:":
                break
            p = self._p(lw)
            if lw in REFW and not out:
                return [lw]
            if not out and (p & {"det", "article"} or lw in {"the", "a", "an", "my", "our", "your", "his", "her",
                                                             "their", "some", "all", "both", "any", "just", "please",
                                                             "me", "us", "him", "you"}):
                continue
            if lw in FUNC or lw in AUX or lw in WH:
                break
            if p and not p & {"noun", "adj", "name", "num"} and out:
                break
            out.append(lw)
            if len(out) >= 5:
                break
        return out

    def _verb_np(self, rt, marker_verb=None):
        """verb + object after a request/commitment marker; get/have/make X <participle> -> the participle is the act;
        keep/continue + -ing -> continue"""
        i = 0
        while i < len(rt) and rt[i] in {"please", "just", "also", "go", "ahead", "and", "to", "now", "then", "actually",
                                        "really", "still", "pls"}:
            i += 1
        if i >= len(rt):
            return marker_verb, []
        v = rt[i]
        p = self._p(v)
        if "verb" not in p or p & {"det", "article"} or v in REFW:
            return marker_verb, self._np(rt[i:])            # "we need a post": the marker is the verb
        verb = self.d.lemma(v, "verb")
        after = rt[i + 1:]
        if verb in {"keep", "continue"} and after and after[0].endswith("ing"):
            return "continue", self._np(after[1:])
        obj = self._np(after)
        if verb in CAUSE:
            for w in after[:len(obj) + 3]:
                if w.endswith("ed") or w in {"done", "made", "built", "finished"}:
                    lem = self.d.lemma(w, "verb")
                    if lem != "do":
                        verb = lem
                    obj = [x for x in obj if x != w]
                    break
        return verb, obj

    def read(self, turn):
        fixed, changes = self.sp.fix(turn)
        low = fixed.lower().strip()
        toks = [t for t in TOK.findall(low)]
        while len(toks) > 2 and (toks[0] in {"okay", "ok", "oh", "well", "so", "also", "and", "but", "yeah", "yes",
                                             "no", "first", "alright", "hey", "hi", "bro", "now", "then", "see", "right"}
                                 or (self._p(toks[0]) & {"intj", "conj"} and not self._p(toks[0]) & {"verb", "noun"})):
            toks = toks[1:]
        core = " ".join(toks)
        fr = {"turn": turn, "fixed": fixed, "changes": changes, "mood": "statement", "verb": None, "object": [],
              "subject": [], "topic": [], "goal": None, "status": bool(STATE_Q.search(core)), "refs": [], "wh": None}
        words = [t for t in toks if t[0].isalnum()]
        first = words[0] if words else ""
        if "?" in turn or first in WH or (first in AUX and len(words) > 1 and words[1] not in {"you", "u", "we"}):
            fr["mood"] = "question"
            fr["wh"] = first if first in WH else ("yes/no" if first in AUX else None)
        m = REQUEST.match(core)
        c = COMMIT.match(core)
        s = SHOULD.match(core)
        copula = any(w in {"is", "are", "was", "were", "isnt", "seems", "looks"} for w in words[1:4])
        if m and (fr["mood"] != "question" or re.match(r"^(?:can|could|would|will)\s+(?:you|u|we)\b", core)):
            mv = re.search(r"\b(need|want|like)\b", core[:m.start(1)])
            fr["mood"] = "request"
            fr["verb"], fr["object"] = self._verb_np(TOK.findall(m.group(1)), mv.group(1) if mv else None)
        elif fr["mood"] == "statement" and c:
            fr["mood"] = "commitment"
            fr["verb"], fr["object"] = self._verb_np(TOK.findall(c.group(1)))
        elif fr["mood"] == "statement" and s and not re.match(r"^i\b", core):
            # "connect should be a side panel": the subject is what is acted on, the rest is the change wanted
            fr["mood"] = "request"
            fr["subject"] = self._np(TOK.findall(core[:s.start(1)]))
            fr["verb"], obj = self._verb_np(TOK.findall(s.group(1)), "be")
            fr["object"] = fr["subject"] + [w for w in obj if w not in fr["subject"]]
        elif fr["mood"] == "statement" and first and "verb" in self._p(first) and first not in AUX \
                and self.d.lemma(first, "verb") == first and not self._p(first) & {"pron", "det", "num"} and not copula:
            fr["mood"] = "request"                                          # imperative: a bare base-form verb first
            fr["verb"], fr["object"] = self._verb_np(words)
        elif fr["mood"] == "statement" and len(words) <= 4 and words and all(
                self._p(w) & {"intj"} or w in {"thanks", "thank", "you", "hello", "hi", "bye", "welcome", "back"}
                for w in words):
            fr["mood"] = "social"
        elif fr["mood"] == "question":
            # the kernel's law 3: the wanted thing is the head of the asking phrase
            m2 = re.search(r"\b(?:what(?:'s|s)?|which|who(?:'s|s)?|how(?:\s+(?:much|many|long|to))?|where(?:'s|s)?|"
                           r"why|when|is|are|was|were|did|does|do|has|have|can|could|will|would|should)\s+"
                           r"(?:(?:is|are|was|were|did|does|do|has|have|the|a|an|it|i|we|you|they|there|that|this)\s+)*"
                           r"(.+)$", core)
            seg = TOK.findall(m2.group(1)) if m2 else words
            fr["object"] = self._np(seg)
            vs = [w for w in seg if "verb" in self._p(w) and not self._p(w) & {"noun", "adj"} and w not in AUX]
            fr["verb"] = self.d.lemma(vs[0], "verb") if vs else None
        if fr["mood"] == "statement":
            fr["subject"] = self._np(words)
            fr["object"] = fr["subject"]
            vs = [w for w in words if "verb" in self._p(w) and not self._p(w) & {"noun", "adj", "pron"} and w not in AUX]
            fr["verb"] = self.d.lemma(vs[0], "verb") if vs else None
        tm = TOPIC.search(core)
        if tm:
            fr["topic"] = self._np(TOK.findall(tm.group(1)))
        gm = GOAL.search(core)
        if gm:
            fr["goal"] = gm.group(1)[:120]
        fr["refs"] = [w for w in fr["object"] + fr["topic"] if w in REFW]
        fr["keys"] = self.keys(fr)
        return fr

    def keys(self, fr):
        ws = ([fr["verb"]] if fr["verb"] else []) + fr["object"] + fr["topic"]
        out = []
        for w in ws:
            if not w or self.is_closed(w) or len(w) <= 2 or w in {"need", "want", "get", "make", "give", "be", "do",
                                                                   "have", "let", "put", "like"}:
                continue
            l = self.d.lemma(w) if w.isalpha() else w
            if l not in out:
                out.append(l)
        return out

    def lemmas_of(self, text):
        """the content lemmas of any text (used to read a candidate REPLY back: the inverted squircle)"""
        out = set()
        for w in WORD.findall((text or "").lower()):
            if len(w) <= 2 or w in REFW:
                continue
            out.add(self.d.lemma(w))
            out.add(w)
        return out


def corpus_texts(tree, dd_path, db, cache=None):
    """the frequency corpus: DailyDialog's human utterances, Oracle7's released .md records, the dictionary's glosses"""
    import os
    import pickle
    if cache and os.path.exists(cache):
        return pickle.load(open(cache, "rb"))
    texts = []
    dd = json.load(open(dd_path))
    for split in dd.values():
        for r in split:
            texts.extend(r["utterances"])
    for root, _, files in os.walk(tree):
        if "__pycache__" in root:
            continue
        for f in files:
            if f.endswith(".md"):
                try:
                    texts.append(open(os.path.join(root, f), encoding="utf-8", errors="ignore").read())
                except OSError:
                    pass
    for (g,) in db.execute("SELECT glosses_json FROM entry"):
        texts.append(" ".join(_glosses(g)))
    if cache:
        pickle.dump(texts, open(cache, "wb"))
    return texts


def open_dict():
    import os
    import sqlite3
    import sys
    sys.path.insert(0, os.environ.get("ORACLE7_WT", os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "root", "wander-train")))
    from oracle_release_runtime_m import WIKT
    return sqlite3.connect(WIKT.resolve().as_uri() + "?mode=ro&immutable=1", uri=True, check_same_thread=False)