"""writeup - longer pieces on things Oracle7 has not learned, and a report on a release from its own record (12.0 Amendment 11). write_up(topic) it holds nothing to write from, so (on the user's go) it reads the topic's page in Simple English Wikipedia and Wikipedia (learn.py's verified reader), keeps the sentences it read with their source, and arranges them into paragraphs: every sentence is the source's sentence, numbered to its page. Where the two sources both carry a sentence's distinctive words it says so. It is offered, not answered: it was read just now, not checked against the store. report(record, version) a release, section by section, from its own changelog: what it is, what you can do with it, what was measured, what is inside; each paragraph is the record's own units, cited to the file. Nothing here writes a sentence of its own. No language model.""" import json import re import time from pathlib import Path WORD = re.compile(r"[A-Za-z][A-Za-z'-]+") POINTS_BACK = re.compile(r"^(?:It|They|This|These|That|Those|He|She|Its|Their|His|Her|However|But|Also|In addition)\b") def _key(s): return {w.lower() for w in WORD.findall(s) if len(w) > 4} def _paragraphs(units, per=4): """3-5 sentences to a paragraph, never cut before a sentence that points back""" out, cur = [], [] for u in units: if cur and len(cur) >= per - 1 and not POINTS_BACK.match(u["sentence"]): out.append(cur) cur = [] cur.append(u) if cur: out.append(cur) return out def _link_run(s): """12.0.2: a run of page links is not a sentence ("Weather Atmosphere Atomic physics ... Archived 2007-08-15 at the Wayback Machine" came through the sky page as a paragraph): ten or more words, most of them capitalised""" ws = re.findall(r"[A-Za-z][A-Za-z-]*", s) return len(ws) >= 10 and sum(1 for w in ws if w[0].isupper()) > 0.6 * len(ws) def _extract_titled(learn, host, title): """the page's text and its own title after redirects ("Airplanes" is read as the page "Airplane")""" import urllib.parse u = "https://%s/w/api.php?%s" % (host, urllib.parse.urlencode( {"action": "query", "prop": "extracts", "explaintext": 1, "titles": title, "format": "json", "redirects": 1})) for p in learn._get(u).get("query", {}).get("pages", {}).values(): return p.get("title") or title, p.get("extract") or "" return title, "" def write_up(topic, keep_dir=None, limit=12): import learn topic = " ".join(str(topic).split())[:80] got = [] # one form for a word on both sides of every comparison here: learn.stem leaves "twinkle" and makes "twinkl" of # "twinkling" ("salty" / "salt"); the read-up compares words only with itself, so learn.stem stays as it is for lookup k = lambda w: __import__("re").sub(r"(?:e|y)$", "", learn.stem(w)) qst = {k(w) for w in learn.content(topic)} # the words of a name the request carries (capitalised; a topic is not a sentence, so its first word counts too) names = {k(w.lower()) for w in __import__("re").findall(r"[A-Za-z][\w'-]*", topic) if w[:1].isupper()} for name, host in (("Simple English Wikipedia", "simple.wikipedia.org"), ("Wikipedia", "en.wikipedia.org")): try: # 12.0.2: the subject's page, not the page the words name. A page is about the asked subject when every content # word of its title is in the request; of those, the one whose sentences carry the request most is read. best = None cands = ([got[0]["title"]] if got else []) + learn.search(host, topic, 4) + [ w[:1].upper() + w[1:] for w in learn.content(topic)] seen = set() for title in cands: if title in seen: continue seen.add(title) tst = {k(w) for w in learn.content(title)} if not tst or not tst <= qst: continue title, text = _extract_titled(learn, host, title) ss = [s for s in learn.sentences(text) if 40 <= len(s) <= 420 and not s.rstrip().endswith(":") and not _link_run(s)] if not ss: continue carry = sum(1 for x in ss if len({k(w) for w in learn.content(x)} & qst) >= min(2, len(qst))) rest = (qst - tst) & names if rest and not (got and title == got[0]["title"]) and not any( rest & {k(w) for w in learn.content(x)} for x in ss[:40]): continue # names part of a name and never says the rest ("Baghdad" for Baghdad Battery) if got and title == got[0]["title"]: # the same subject as the first edition: read to check it best = (carry, title, ss, tst) break if best is None or carry > best[0]: best = (carry, title, ss, tst) if best: got.append({"source": name, "title": best[1], "url": "https://%s/wiki/%s" % (host, best[1].replace(" ", "_")), "sentences": best[2], "asks_more": bool(qst - best[3])}) except Exception: # noqa: BLE001 continue if not got: return {"status": "hole", "path": "writeup:nothing", "response": "I read Simple English Wikipedia and Wikipedia and found no page about %s, so I still hold nothing to write from." % topic} for g in got: if g["asks_more"]: # the request asks more than the page names: keep what carries the request keep = [x for i, x in enumerate(g["sentences"]) if i == 0 or len({k(w) for w in learn.content(x)} & qst) >= min(2, len(qst))] if len(keep) >= 3: g["sentences"] = keep lead = got[0] other = [_key(s) for g in got[1:] for s in g["sentences"][:60]] units, n_both = [], 0 for s in lead["sentences"][:limit]: k = _key(s) both = bool(k) and any(len(k & o) >= max(3, int(0.6 * len(k))) for o in other) n_both += both units.append({"sentence": s, "both": both}) paras = _paragraphs(units) body, n = [], 0 for p in paras: body.append(" ".join(u["sentence"] for u in p) + " [1]") n += len(p) srcs = ["1. %s - %s (%s)" % (lead["title"], lead["source"], lead["url"])] if len(got) > 1: srcs.append("2. %s - %s (%s), read to check the first" % (got[1]["title"], got[1]["source"], got[1]["url"])) note = "(%d sentences, each as %s writes it; %d of them are also carried by the second source; read just now, not checked against my store)" % ( n, lead["source"], n_both) text = "# %s\n\n%s\n\n### Sources\n\n%s\n%s" % (lead["title"], "\n\n".join(body), "\n".join(srcs), note) if keep_dir: try: d = Path(keep_dir) d.mkdir(parents=True, exist_ok=True) (d / (re.sub(r"[^a-z0-9]+", "_", topic.lower()).strip("_")[:60] + ".json")).write_text(json.dumps( {"t": int(time.time()), "topic": topic, "sources": [{k: g[k] for k in ("source", "title", "url")} for g in got], "sentences": [u["sentence"] for u in units]}, indent=1), encoding="utf-8") except Exception: # noqa: BLE001 pass return {"status": "offered", "path": "writeup:read:" + lead["source"], "response": text} SECTIONS = (("What it is", lambda u, i: i < 2 and not u["head"].lower().startswith(("what you can", "measured", "what is inside"))), ("What you can do with it", lambda u, i: u["head"].lower().startswith("what you can")), ("What was measured", lambda u, i: u["head"].lower().startswith(("measured", "proof", "results", "gate"))), ("What is inside", lambda u, i: u["head"].lower().startswith(("what is inside", "what's inside", "new in", "what is new", "what changed")))) def report(record, version=None): """a release from its own changelog, section by section, in the record's own words""" ver = version or record.newest units = [u for u in record.units if u["ver"] == ver] if not units: return None out, used = ["# Oracle7 %s, from its own record" % ver, ""], 0 for title, pick in SECTIONS: us = [u for i, u in enumerate(units) if pick(u, i)][:7] if not us: continue out.append("### " + title) out.append("") if len(us) == 1 or title == "What it is": out.append(" ".join(record._short(u["text"], 420) for u in us) + " [1]") else: out += ["- " + record._short(u["text"], 340) + " [1]" for u in us] # each passage of the record on its own line out.append("") used += len(us) if not used: return None out += ["### Sources", "", "1. %s - Oracle7's own changelog for release %s (in this install)" % (units[0]["file"], ver), "(%d passages, each in the record's own words)" % used] return {"status": "answered", "path": "converse:report:" + units[0]["file"], "response": "\n".join(out)}