#!/usr/bin/env python3 """priorart.py -- sweep any served note for its owning convention and locate every statement it imports at the page, in one run. python3 priorart.py research/fold-arithmetic-bridge.md python3 priorart.py research/fold-arithmetic-bridge.md --object "sifting limit" \ --carrier arXiv:1012.3809v1 --find "sifting limit" --find 4.266 What it does, generically, for a note it has never seen: 0. fetches the note and the conventions file from the project's served document tree and prints the sha256 of both, so a reviewer sees at once whether a served copy has moved since a return cited it; 1. finds the note's own **source table** -- the markdown table whose header carries a `locator` or `statement used` column -- and parses it; nothing note-specific is hard-coded, so a note with two source tables, or none, is handled the same way; 2. splits the rows into **imported** and **UNREAD** by the note's own marking (the word UNREAD in any cell), because the project's convention is that an unread source is not an import, and every row is printed with its own classification; 3. derives the **carrier** (arXiv identifier or URL) from the source or locator cell, and inherits it down the table for a row that says "same file": the inheritance is keyed on the first word of the source cell, so "Wu, same file" picks up Wu's identifier and not the identifier of whatever row sits in between; 4. derives the **locator keys** -- printed-page numbers from the locator cell, labels such as `(2.6)`, `Lemma 2.3`, `Theorem 3.12` from the source and locator cells -- so what is searched for is exactly what the row claims about where the statement sits; 5. fetches every distinct carrier once, hashes it, and for a PDF with a text layer prints the page where each label first occurs with that page's first line, so the printed folio can be compared with the cited one; 6. matches the source table's author names against the conventions file and prints the convention row(s) that own them; and with `--object` prints the convention rows for that object and fetches the carriers those rows name; 7. with `--carrier` and `--find` locates any extra carrier, so a convention's own literature (a sifting limit, a named constant) is reached in the same run. Only two things are project-specific and both are arguments: the document base URL and the served path of the conventions file. Anything the note does not cite in a source table is out of scope by construction, so the sweep is as complete as the note's own sourcing. python3 priorart.py [--conventions PATH] [--base URL] [--object TOKEN] [--carrier ID_OR_URL] [--find STRING] [--no-fetch] stdout is a pure function of the bytes fetched: no clock, no host, no working directory, no temporary path, no loop over an unordered set. Only PDF carriers are hashed; a live HTML page is reported by URL and not fetched, because its bytes are not a fixed input and a hash of them would not reproduce. Fetch failures print a FETCH-FAIL line instead of raising, so one dead carrier does not abort the sweep. PDF carriers need `pdftotext`. Known limits: tables only (a note that cites in prose yields nothing), first occurrence of each label only, and no claim that a located label is the statement the row means. """ import hashlib import json import os import re import subprocess import sys import tempfile import urllib.error import urllib.request BASE = "https://solveathome.org/projects/twin-primes" UA = {"User-Agent": "priorart-agent (solveathome twin-primes)"} ARXIV = re.compile(r"arXiv:\s*(\d{4}\.\d{4,5}(?:v\d+)?)", re.I) ARXIV_URL = re.compile(r"arxiv\.org/(?:abs|pdf|html)/(\d{4}\.\d{4,5}(?:v\d+)?)", re.I) URL = re.compile(r"https?://[^\s)\]|>]+") PAGE_LOC = re.compile(r"\bpp?\.\s*(\d+)(?:\s*[-\u2013]\s*(\d+))?") LABEL = re.compile(r"\((?:[0-9]+[a-z]?)(?:\.[0-9]+)*\)|" r"\b(?:Theorem|Lemma|Proposition|Corollary|Chapter|Ch\.|Section|Table)\s*" r"[0-9]+(?:\.[0-9]+)*") NAME = re.compile(r"\b([A-Z][a-z]{2,})\b") SAME = re.compile(r"\bsame (?:file|paper|work|source)\b|\bibid\b|\bidem\b", re.I) NOT_A_NAME = { "the", "and", "for", "with", "read", "same", "file", "paper", "work", "source", "page", "pages", "version", "locator", "statement", "used", "hypotheses", "discharged", "unmatched", "none", "needed", "unread", "here", "only", "all", "from", "see", "this", "that", "then", "than", "when", "over", "under", "above", "below", "form", "into", "both", "each", "every", "also", "first", "second", "third", "four", "five", "upper", "lower", "bound", "bounds", "acta", "arith", "acad", "proc", "notes", "note", "methods", "method", "sieve", "sieves", "twin", "prime", "primes", "theorem", "lemma", "proposition", "corollary", "chapter", "section", "example", "table", "figure", "shown", "book", "press", "volume", "vol", "edition", "journal", "university", "cambridge", "oxford", "wiley", "springer", "dover", "verlag", "ann", "math", "mathematik", "invent", "review", "history", "index", "its", "his", "her", "their", "where", "which", "what", "does", "how", "not", "can", "may", "must", "was", "were", "has", "have", "had", "are", "but", "or", "as", "at", "by", "in", "of", "on", "to", "is", "it", "if", "no", "so", "we", "our", "any", "one", "two", "three", "part", "rest", "case", "list", "rows", "row", "code", "data", "corpus", "project", "snapshot", "commit", "sha", "hash", "line", "lines", "text", "http", "https", "www", "arxiv", "pdf", "html", "org", "edu", "com", } def sha(b): return hashlib.sha256(b).hexdigest() def fetch(url, accept="application/json"): try: rq = urllib.request.Request(url, headers=dict(UA, Accept=accept)) return urllib.request.urlopen(rq, timeout=180).read() except urllib.error.HTTPError as e: print(" FETCH-FAIL HTTP %s %s" % (e.code, url)) except Exception as e: # noqa: BLE001 - report, never raise print(" FETCH-FAIL %s %s" % (type(e).__name__, url)) return None def tables(md): """Every markdown table as (header_cells, [row_cells, ...]).""" out, cur = [], None for line in md.split("\n"): s = line.strip() if s.startswith("|") and s.endswith("|"): cells = [c.strip() for c in s.strip("|").split("|")] if set("".join(cells)) <= set("-: "): continue if cur is None: cur = (cells, []) else: cur[1].append(cells) else: if cur is not None: out.append(cur) cur = None if cur is not None: out.append(cur) return out def source_table(md): for hdr, rows in tables(md): low = " ".join(h.lower() for h in hdr) if "locator" in low or "statement used" in low: i_loc = next((i for i, h in enumerate(hdr) if "locator" in h.lower() or "version" in h.lower()), 1) return hdr, rows, i_loc return None, [], 1 def carrier_keys(text): """arXiv identifiers (bare or in a URL) and non-arXiv URLs named in `text`.""" ids = sorted(set(ARXIV.findall(text)) | set(ARXIV_URL.findall(text))) urls = sorted({u.rstrip(".,;") for u in URL.findall(text) if "arxiv.org" not in u}) return ids, urls def locator_keys(src, loc): pages = sorted({int(p) for p, _ in PAGE_LOC.findall(loc)}) labels = sorted({re.sub(r"\s+", " ", l) for l in LABEL.findall(src + " " + loc)}) return pages, labels def pdf_pages(b): """Text of each page of a PDF, via pdftotext. This build reads a path, not stdin.""" fd, path = tempfile.mkstemp(suffix=".pdf") try: os.write(fd, b) os.close(fd) p = subprocess.run(["pdftotext", "-layout", path, "-"], capture_output=True, timeout=900) except Exception: # noqa: BLE001 return None finally: try: os.unlink(path) except OSError: pass if p.returncode != 0 or not p.stdout: return None return p.stdout.decode("utf-8", "replace").split("\f") def locate(blob, pattern): """First 1-based page where `pattern` occurs, with that page's first line.""" for i, pg in enumerate(blob, 1): if re.search(pattern, pg): first = next((l.strip() for l in pg.split("\n") if l.strip()), "") return i, first return None, "" def get_pdf(cache, aid, do_fetch): key = ("arxiv", aid) if key not in cache: cache[key] = fetch("https://arxiv.org/pdf/" + aid, "application/pdf") if do_fetch else None return cache[key] def report_pdf(cache, aid, labels, pages, do_fetch, indent=" ", lab_w=16): b = get_pdf(cache, aid, do_fetch) if b is None: print("%s%-34s NOT FETCHED" % (indent, aid)) return None blob = pdf_pages(b) print("%s%-34s %8d bytes sha256 %s %s" % (indent, aid, len(b), sha(b), "pdf text layer" if blob else "pdf, no text layer")) for pg in pages: print("%s cited printed page %-5d" % (indent, pg)) if not blob: for lab in labels[:6]: print("%s %-*s not read (no text layer)" % (indent, lab_w, lab)) return None for lab in labels[:6]: page, first = locate(blob, re.escape(lab)) where = ("pdf page %d" % page) if page else "NOT FOUND in the text layer" print("%s %-*s %-30s %s" % (indent, lab_w, lab, where, first.encode("ascii", "replace").decode()[:74])) return blob def main(argv): if len(argv) < 2 or argv[1].startswith("-"): print("usage: priorart.py [--conventions PATH] [--base URL] " "[--object TOKEN] [--carrier ID_OR_URL] [--find STRING] [--no-fetch]") return 2 note = argv[1] conv = "research/SEARCH-CONVENTIONS.md" base, obj, do_fetch = BASE, None, True extra, finds = [], [] i = 2 while i < len(argv): if argv[i] == "--conventions": conv = argv[i + 1]; i += 2 elif argv[i] == "--base": base = argv[i + 1]; i += 2 elif argv[i] == "--object": obj = argv[i + 1]; i += 2 elif argv[i] == "--carrier": extra.append(argv[i + 1]); i += 2 elif argv[i] == "--find": finds.append(argv[i + 1]); i += 2 elif argv[i] == "--no-fetch": do_fetch = False; i += 1 else: print("unknown argument: " + argv[i]); return 2 print("== 0. served documents ==") nbytes = fetch(base + "/docs/" + note) if do_fetch else None md = nbytes.decode("utf-8", "replace") if nbytes else "" print(" %-44s %s" % (note, "%d bytes sha256 %s" % (len(nbytes), sha(nbytes)) if nbytes else "NOT FETCHED")) cbytes = fetch(base + "/docs/" + conv) if do_fetch else None conv_md = cbytes.decode("utf-8", "replace") if cbytes else "" print(" %-44s %s" % (conv, "%d bytes sha256 %s" % (len(cbytes), sha(cbytes)) if cbytes else "NOT FETCHED")) led = re.search(r"", md, re.S) if led: lid = re.search(r"id:\s*(\S+)", led.group(1)) lq = re.search(r"question:\s*(.+)", led.group(1)) if lid: print(" ledger id %s" % lid.group(1)) if lq: print(" question %s" % lq.group(1).strip()[:170]) cache = {} print() print("== 1. the note's own source table ==") hdr, rows, i_loc = source_table(md) if not rows: print(" no source table found; nothing to sweep (the note cites in prose)") else: print(" columns: %s" % ", ".join(hdr)) print(" rows: %d" % len(rows)) unread = [r for r in rows if any("UNREAD" in c.upper() for c in r)] print(" imported: %d marked UNREAD: %d" % (len(rows) - len(unread), len(unread))) print() print("== 2. each row, its carrier and its locator ==") by_name, last = {}, [] for r in rows: src = r[0] if r else "" loc = r[i_loc] if len(r) > i_loc else "" ids, urls = carrier_keys(src + " " + loc) pages, labels = locator_keys(src, loc) tag = "UNREAD" if any("UNREAD" in c.upper() for c in r) else "import" head = (src.split()[0].rstrip(",") if src.split() else "") inherited = False if not ids and not urls and (SAME.search(src) or SAME.search(loc)): got = by_name.get(head) or (last[0] if last else ([], [])) if got and (got[0] or got[1]): ids, urls, inherited = list(got[0]), list(got[1]), True if ids or urls: by_name[head] = (ids, urls) last = [ids, urls] print(" [%s] %s" % (tag, src[:104])) print(" locator: %s" % re.sub(r"\s+", " ", loc)[:140]) if inherited: print(" carrier inherited from the earlier \"%s\" row" % head) if not ids and not urls: print(" carrier: none named in the row (local-only, or a book citation)") for aid in ids: report_pdf(cache, aid, labels, pages, do_fetch) for u in urls: if re.search(r"\.pdf($|\?)", u, re.I): report_pdf(cache, u, labels, pages, do_fetch) else: print(" %-60s live page, not fetched (bytes not a fixed input)" % u[:60]) print() print("== 3. owning convention(s) for the sources above ==") names = set() for r in rows: for w in NAME.findall(r[0] if r else ""): if w.lower() not in NOT_A_NAME: names.add(w) hits = 0 for w in sorted(names): pat = re.compile(r"\b%s\b" % re.escape(w)) for line in conv_md.split("\n"): if "|" in line and pat.search(line): print(" %-14s %s" % (w, re.sub(r"\s+", " ", line.strip())[:200])) hits += 1 break if not hits: print(" no author of the source table appears in the conventions table") if obj: print() print("== 4. the object's own convention, and the carriers it names ==") olines = [l for l in conv_md.split("\n") if obj.lower() in l.lower()] for l in olines[:6]: print(" %s" % re.sub(r"\s+", " ", l.strip())[:230]) oids = set() for l in olines: a, u = carrier_keys(l) oids |= set(a) for x in u: print(" carrier named by the convention, as a live page: %s" % x[:90]) for aid in sorted(oids): report_pdf(cache, aid, [], [], do_fetch, indent=" ", lab_w=16) if extra: print() print("== 5. extra carriers, located ==") for c in extra: if c.startswith("http"): print(" %s live page, not fetched (bytes not a fixed input)" % c[:90]) continue mo = ARXIV.search(c) or ARXIV_URL.search(c) aid = mo.group(1) if mo else c print(" carrier %s searching: %s" % (aid, ", ".join(finds) or "(no --find given)")) report_pdf(cache, aid, finds, [], do_fetch, indent=" ", lab_w=20) print() print("== summary ==") print(json.dumps({"note": note, "note_sha256": sha(nbytes) if nbytes else None, "conventions_sha256": sha(cbytes) if cbytes else None, "rows": len(rows), "imported": len([r for r in rows if not any("UNREAD" in c.upper() for c in r)]), "unread": len([r for r in rows if any("UNREAD" in c.upper() for c in r)]), "carriers_fetched": len([k for k, v in cache.items() if v]) if rows else 0}, sort_keys=True)) return 0 if __name__ == "__main__": sys.exit(main(sys.argv))