File size: 11,823 Bytes
d9b105f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""learn - the gap loop (12.0). When the door cannot answer a question under the law, it says so and offers to look it up in the
verified sources; on your go it searches them, reads what it finds, takes the sentences that answer the question, checks them,
and keeps what holds, with its source, for every later turn.

  look      Wikipedia (English) and Simple English Wikipedia, through their public search and plain-text extract APIs
  read      the extract of the best article from each, split into sentences
  answer    the native clause that binds the question's subject, roles and demanded field
  check     compare the demanded values, retaining disagreements and source provenance;
            Wikipedia editions are related sources, not independent confirmation
  keep      workbench/local/learned.jsonl: question, sentence, source URL, sha256 of the sentence, corroborated or not;
            a later question that resonates with a kept one is answered from it, with the same citation
No language model; nothing outside the verified list is fetched."""
import hashlib
import json
import os
import re
import time
import urllib.parse
import urllib.request
from pathlib import Path

WB = Path(__file__).resolve().parent
STORE = Path(os.environ.get("ORACLE7_LEARNED", WB / "local" / "learned.jsonl"))
UA = {"User-Agent": "Oracle7/12.0 (https://huggingface.co/psiloceyeben/oracle7; verified-sources reader, no language model)"}
SOURCES = [("Wikipedia", "en.wikipedia.org"), ("Simple English Wikipedia", "simple.wikipedia.org")]
STOP = set("the a an of in on at to for with by from as is are was were be been being do does did what which who whom whose "
           "where when why how many much is it its this that these those and or not no yes tell me about please there their "
           "they he she his her him you your i we our us can could would should will shall may might must has have had".split())
W = re.compile(r"[A-Za-z][A-Za-z'-]+|\d[\d,.]*")


def words(t):
    return [w.lower().strip(".,") for w in W.findall(t or "")]


def content(t):
    return [w for w in words(t) if w not in STOP and len(w) > 1]


def stem(w):
    for s in ("ies", "es", "s", "ing", "ed"):
        if len(w) > len(s) + 3 and w.endswith(s):
            return w[: -len(s)]
    return w


def _get(url, tries=3):
    """one polite request: identified, and when the source says too many requests, wait as long as it asks (or 5 s) and retry"""
    import urllib.error
    for k in range(tries):
        time.sleep(0.4)                                  # never a burst
        req = urllib.request.Request(url, headers=UA)
        try:
            with urllib.request.urlopen(req, timeout=25) as r:
                return json.loads(r.read(3_000_000).decode("utf-8", "ignore"))
        except urllib.error.HTTPError as e:
            if e.code != 429 or k == tries - 1:
                raise
            time.sleep(min(30, int(e.headers.get("Retry-After") or 5)))
    return {}


def search(host, q, n=2):
    q = " ".join(content(q)) or q                       # the question's content words, not its frame
    u = "https://%s/w/api.php?%s" % (host, urllib.parse.urlencode(
        {"action": "query", "list": "search", "srsearch": q, "format": "json", "srlimit": n}))
    return [h["title"] for h in _get(u).get("query", {}).get("search", [])]


def extract(host, title):
    u = "https://%s/w/api.php?%s" % (host, urllib.parse.urlencode(
        {"action": "query", "prop": "extracts", "explaintext": 1, "titles": title, "format": "json", "redirects": 1}))
    pages = _get(u).get("query", {}).get("pages", {})
    for p in pages.values():
        return p.get("extract") or ""
    return ""


ABBR = re.compile(r"\b(c|ca|e\.g|i\.e|Mr|Mrs|Ms|Dr|St|No|vs|approx|est|Jr|Sr|Inc|Ltd|Co|Mt|Ft|U\.S|U\.K)\.$")
YEAR = re.compile(r"\b(1\d{3}|20\d{2})\b|\b\d{1,2} (January|February|March|April|May|June|July|August|September|October|"
                  r"November|December)\b|\b(January|February|March|April|May|June|July|August|September|October|November|"
                  r"December) \d{1,2}\b")


def sentences(text):
    text = re.sub(r"(?m)^\s*=+[^=\n]*=+\s*$", "\n", text)        # section headings are not sentences
    text = re.sub(r"\s*\n\s*", " ", text)
    out, cur = [], ""
    for piece in re.split(r"(?<=[.!?])\s+(?=[A-Z0-9\"(])", text[:80000]):
        cur = (cur + " " + piece).strip() if cur else piece.strip()
        if ABBR.search(cur):                           # "Cellos made before c." does not end a sentence
            continue
        out.append(cur)
        cur = ""
    if cur:
        out.append(cur)
    return out


def wants(question):
    """the kind of answer the question asks for, read from its first words"""
    q = question.strip().lower()
    if re.match(r"(when|what year|in what year|which year|what date)\b", q):
        return "time"
    if re.match(r"(who|whom|whose)\b", q):
        return "person"
    if re.match(r"(how many|how much|how long|how tall|how high|how old|how far|how big|how deep|how heavy|what is the population)\b", q):
        return "number"
    if re.match(r"where\b", q):
        return "place"
    return None


def fits(kind, s, question):
    if kind == "time":
        return bool(YEAR.search(s))
    if kind == "number":
        return bool(re.search(r"\d", s))
    if kind in ("person", "place"):
        qw = {w.lower() for w in W.findall(question)}
        caps = [w for w in re.findall(r"(?<![.!?]\s)(?<!^)\b[A-Z][a-z]+", s) if w.lower() not in qw]
        return bool(caps)
    return True


def select_answer(question, text, title="", reader=None):
    """Keep the exact selected source sentence and its checked question duty."""
    from question_obligation import select_records
    records = [{"sentence": s, "title": title} for s in sentences(text)
               if 4 <= len(s) <= 1200 and not s.startswith("==")]
    return select_records(question, records, reader, title)


def best_sentence(question, text, title, reader=None):
    selected = select_answer(question, text, title, reader)
    return selected["sentence"] if selected else None


def lookup(question, reader=None):
    """-> {"status": answered|offered|hole, "response", "path", "evidence": [...]}"""
    from question_obligation import receive
    duty = receive(question, reader)
    if duty["missing"]:
        return {"status": "hole", "path": "learn:question", "evidence": [], "question_obligation": duty,
                "response": "Before selecting a source answer I need %s." % "; ".join(duty["missing"])}
    found = []
    qstems = {stem(w) for w in content(question)}
    for name, host in SOURCES:
        try:
            titles = search(host, question, n=4)
            # the article about the question's subject first: most of the question's words in its title, then search order
            titles = sorted(titles, key=lambda t: -len({stem(w) for w in content(t)} & qstems))
            for title in titles[:2]:
                selected = select_answer(question, extract(host, title), title, reader)
                if selected:
                    found.append(dict(selected, source=name, provenance_family="Wikimedia",
                                      url="https://%s/wiki/%s" % (host, urllib.parse.quote(title.replace(" ", "_")))))
                    break
        except Exception as e:  # noqa: BLE001
            found.append({"source": name, "error": repr(e)[:120]})
    good = [f for f in found if f.get("sentence")]
    if not good:
        return {"status": "hole", "path": "learn:none", "evidence": found,
                "response": "I looked in %s and found nothing that answers it, so I still do not hold it." % (
                    " and ".join(n for n, _ in SOURCES))}
    from question_obligation import agreement
    checked = agreement([f["answer_check"] for f in good])
    lead = good[0]
    for f in good:
        keep(question, f, False, reader=reader, agreement=checked)
    if checked["conflict"]:
        return {"status": "hole", "path": "learn:conflict", "evidence": good, "agreement": checked,
                "response": "The sources disagree on the requested %s: %s. I have kept both accounts; this answer remains unresolved." %
                            (lead["question_obligation"]["kind"], "; ".join("%s [%s]" % (f["sentence"], f["url"]) for f in good))}
    if checked["agrees"]:
        resp = "%s [%s] The two Wikipedia editions agree on this answer, but they are related sources, not independent confirmation. [%s]" % (
            lead["sentence"], lead["url"], good[1]["url"])
        return {"status": "offered", "path": "learn:source-agreement", "evidence": good, "agreement": checked, "response": resp}
    resp = "From %s, one source: %s [%s]" % (lead["source"], lead["sentence"], lead["url"])
    return {"status": "offered", "path": "learn:one-source", "evidence": good, "agreement": checked, "response": resp}


def keep(question, f, corroborated=False, reader=None, agreement=None):
    from question_obligation import receive, match
    duty = receive(question, reader)
    checked = match(duty, f["sentence"], reader, f.get("title", ""))
    if not checked:
        return False
    STORE.parent.mkdir(parents=True, exist_ok=True)
    rec = {"t": int(time.time()), "q": question, "sentence": f["sentence"], "source": f["source"], "url": f["url"],
           "sha256": hashlib.sha256(f["sentence"].encode()).hexdigest(), "corroborated": False,
           "title": f.get("title", ""), "question_obligation": duty, "answer_check": checked,
           "agreement": agreement or {}, "provenance_family": f.get("provenance_family", "unverified")}
    with open(STORE, "a", encoding="utf-8") as fh:
        fh.write(json.dumps(rec) + "\n")
    return True


def recall(question, reader=None):
    """Recheck the same demanded field and source integrity before using a record."""
    if not STORE.is_file():
        return None
    from question_obligation import receive, match, agreement
    duty = receive(question, reader)
    if duty["missing"]:
        return None
    found = []
    with open(STORE, encoding="utf-8") as source:
        for line in source:
            try:
                r = json.loads(line)
                if hashlib.sha256(r["sentence"].encode()).hexdigest() != r["sha256"]:
                    continue
                original = receive(r["q"], reader)
                if original.get("key") != duty["key"]:
                    continue
                checked = match(duty, r["sentence"], reader, r.get("title", ""))
                if checked and r.get("source") and r.get("url"):
                    found.append(dict(r, answer_check=checked))
            except (ValueError, TypeError, KeyError):
                continue
    if not found:
        return None
    checked = agreement([f["answer_check"] for f in found])
    if checked["conflict"]:
        return {"status": "hole", "path": "learn:kept-conflict", "evidence": found, "agreement": checked,
                "response": "The kept sources disagree on this requested field: " + "; ".join(
                    "%s [%s]" % (f["sentence"], f["url"]) for f in found) + ". The answer remains unresolved."}
    best = found[-1]
    return {"status": "offered", "path": "learn:kept", "evidence": [best], "agreement": checked,
            "response": "I kept this source account from %s (not independently confirmed): %s [%s]" % (
                best["source"], best["sentence"], best["url"])}


GO = re.compile(r"^\s*(?:yes|yeah|yep|go|go ahead|do it|sure|ok|okay|please do|look it up|fetch (?:it|them)|find out)\b[\s.!]*$", re.I)


def offer_text():
    return "I don't hold that. I can look it up in %s and compare their answers; those editions are related sources. Say go." % (
        " and ".join(n for n, _ in SOURCES))