#!/usr/bin/env python3 """Check every entry against the saved copies of its sources. Deterministic: no AI. python3 scripts/verify_sources.py --sources DIR [ENTRY.yaml ...] DIR is a folder (searched recursively) holding the saved copies the entries were written from. Copies are matched to sources by SHA-256, so file names don't matter. With no entries named, every file in entries/ is checked. For each entry it confirms that: - every web source has a saved copy whose SHA-256 matches the entry; - every quote appears word for word in its source. Whitespace and line breaks are ignored, because extraction tools break lines differently. HTML is read with its tags removed, after decoding Cloudflare's email obfuscation. PDF text is extracted with independent engines (pypdf and pdfminer.six, plus Apple PDFKit on macOS or poppler's pdftotext when installed), and a quote must be found by at least two of them, so one engine's misreading can neither pass a wrong quote nor block a right one. Some PDFs use a font that maps "ti", "tt", "ft" and similar pairs to nothing, so every text engine reads "arbitra on" for "arbitration". As a last resort such a PDF is read by OCR (Apple Vision, macOS only): a quote then passes when the OCR text has it word for word and a text engine has it too, with those letter pairs ignored on both sides; - an entry rated `none` has no "arbitrat" anywhere in its sources. Exits with status 1 when anything fails. """ import argparse import shutil import subprocess import hashlib import html import io import json import pathlib import re import sys import yaml import logging logging.getLogger("pypdf").setLevel(logging.ERROR) # quiet "text extraction not allowed" notices ROOT = pathlib.Path(__file__).resolve().parent.parent LIGATURES = {"ff": "ff", "fi": "fi", "fl": "fl", "ffi": "ffi", "ffl": "ffl"} def squash(text): """Compare without whitespace, ligatures, bullets or curly-quote differences.""" for lig, letters in LIGATURES.items(): text = text.replace(lig, letters) text = text.replace("’", "'").replace("‘", "'").replace("“", '"').replace("”", '"') text = re.sub("[●•○◦▪■□▫‣⁃]", "", text).replace("­", "") return re.sub(r"\s+", "", text) def without_page_numbers(text): """Drop lines that are only a page number, so quotes can cross a page break.""" return re.sub(r"(?m)^\s*(?:Page\s+)?\d{1,3}(?:\s+of\s+\d{1,3})?\s*$", "", text) def decode_cf_email(match): data = bytes.fromhex(match.group(1)) return bytes(b ^ data[0] for b in data[1:]).decode("utf-8", "replace") def html_texts(raw): """Readable text of an HTML page, in two variants: tags replaced by spaces, and tags removed outright (some pages split words with inline tags).""" raw = re.sub(r'<[^>]*data-cfemail="([0-9a-fA-F]+)"[^>]*>.*?]+>', decode_cf_email, raw, flags=re.S) raw = re.sub(r"(?is)<(script|style)\b.*?", " ", raw) return [html.unescape(re.sub(r"<[^>]+>", " ", raw)), html.unescape(re.sub(r"<[^>]+>", "", raw))] def script_text(raw): """Text inside a JavaScript or JSON file: string literals, unescaped.""" out = [raw] for literal in re.findall(r'"((?:[^"\\]|\\.)*)"', raw): try: out.append(json.loads(f'"{literal}"')) except ValueError: pass return ["\n".join(out)] def pdf_texts(data): texts = {} try: from pypdf import PdfReader texts["pypdf"] = "\n".join((p.extract_text() or "") for p in PdfReader(io.BytesIO(data)).pages) except Exception as error: # an unreadable PDF is reported, not fatal for the other engine texts["pypdf"] = f"<>" try: from pdfminer.high_level import extract_text texts["pdfminer"] = extract_text(io.BytesIO(data)) except Exception as error: texts["pdfminer"] = f"<>" return {name: without_page_numbers(t) for name, t in texts.items()} def extra_pdf_texts(path): """Third and fourth opinions, when available: Apple PDFKit and poppler's pdftotext.""" texts = {} script = pathlib.Path(__file__).resolve().parent / "pdftext.swift" if shutil.which("swift") and script.is_file(): run = subprocess.run(["swift", str(script), str(path)], capture_output=True, text=True, timeout=300) if run.returncode == 0: texts["pdfkit"] = without_page_numbers(run.stdout) if shutil.which("pdftotext"): run = subprocess.run(["pdftotext", "-layout", str(path), "-"], capture_output=True, text=True, timeout=300) if run.returncode == 0: texts["pdftotext"] = without_page_numbers(run.stdout) return texts # Letter pairs that broken ligature fonts drop. Removed from both sides, longest first, # for the comparison with a text engine when OCR has already confirmed the full words. DROPPABLE = re.compile(r"ffi|ffl|ff|fi|fl|ft|tt|ti") def ocr_text(path): """The PDF read by OCR (scripts/pdfocr.swift), or None when unavailable.""" script = pathlib.Path(__file__).resolve().parent / "pdfocr.swift" if not (shutil.which("swift") and script.is_file()): return None run = subprocess.run(["swift", str(script), str(path)], capture_output=True, text=True, timeout=600) return without_page_numbers(run.stdout) if run.returncode == 0 else None def load_source(path): """{engine: text} for a saved copy. Every engine must contain each quote.""" data = path.read_bytes() if data[:5] == b"%PDF-": return pdf_texts(data) raw = data.decode("utf-8", "replace") if path.suffix in (".js", ".json"): return {"text": "\n".join(script_text(raw))} variants = html_texts(raw) if "<" in raw[:2000] else [raw] return {"html": "\n".join(variants)} def check_entry(path, copies): entry = yaml.safe_load(path.read_text(encoding="utf-8")) problems, notes = [], [] texts, files, extra_done, ocr = {}, {}, set(), {} for source in entry.get("sources", []): if source.get("kind") == "email": notes.append(f"{source['id']}: an email, not checkable against a public copy") continue if entry.get("tier") == "unverified" and not source.get("sha256"): notes.append(f"{source['id']}: not read (rated `unverified`, {entry.get('unverified_reason')})") continue copy = copies.get(source.get("sha256")) if copy is None: problems.append(f"{source['id']}: no saved copy with SHA-256 {source.get('sha256')}") continue texts[source["id"]] = {name: squash(t) for name, t in load_source(copy).items()} files[source["id"]] = copy for name, quote in (entry.get("quotes") or {}).items(): engines = texts.get(quote.get("source")) if engines is None: continue wanted = squash(quote["text"]) missing = [engine for engine, text in engines.items() if wanted not in text] if missing and len(engines) > 1 and quote["source"] not in extra_done: # PDF engines disagree: ask the extra engines before deciding. extra_done.add(quote["source"]) engines.update({k: squash(t) for k, t in extra_pdf_texts(files[quote["source"]]).items()}) missing = [engine for engine, text in engines.items() if wanted not in text] found = [engine for engine in engines if engine not in missing] needed = 2 if len(engines) > 1 else 1 if len(found) < needed and len(engines) > 1: # Still short: a font may be dropping letter pairs. Read the PDF by OCR. if quote["source"] not in ocr: text = ocr_text(files[quote["source"]]) ocr[quote["source"]] = squash(text) if text else None seen = ocr[quote["source"]] if seen and wanted in seen: found = found + ["ocr"] if len(found) < needed: dropped = DROPPABLE.sub("", wanted) partial = [e for e in missing if dropped in DROPPABLE.sub("", engines[e])] if partial: found.append(f"{partial[0]} (ignoring dropped letter pairs)") missing.remove(partial[0]) if len(found) < needed: problems.append(f"quotes.{name}: not found word for word in {quote['source']} " f"(found by {', '.join(found) or 'no engine'}; missing in {', '.join(missing)})") elif missing: notes.append(f"quotes.{name}: confirmed by {', '.join(found)}; {', '.join(missing)} read it differently") if entry.get("tier") == "none": # Passages the entry declares (in `arbitration_mentions`) as mentioning arbitration # without being an agreement to arbitrate are removed first; any other mention fails. declared = [squash(entry["quotes"][n]["text"]) for n in entry.get("arbitration_mentions") or [] if n in entry.get("quotes", {})] for sid, engines in texts.items(): for engine, text in engines.items(): for passage in declared: text = text.replace(passage, "") if "arbitrat" in text.lower(): problems.append(f"rated `none`, but source {sid} mentions arbitration ({engine})") break return problems, notes def main(): parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) parser.add_argument("--sources", required=True, type=pathlib.Path, help="folder with the saved copies of the sources (searched recursively)") parser.add_argument("entries", nargs="*", type=pathlib.Path) args = parser.parse_args() copies = {} for path in args.sources.rglob("*"): if path.is_file() and path.suffix not in (".txt", ".md", ".yaml"): copies.setdefault(hashlib.sha256(path.read_bytes()).hexdigest(), path) paths = args.entries or sorted((ROOT / "entries").glob("*.yaml")) failed = 0 for path in paths: problems, notes = check_entry(path, copies) status = "OK " if not problems else "FAIL" print(f"{status} {path.stem}") for line in problems: print(f" - {line}") for line in notes: print(f" · {line}") failed += bool(problems) print(f"{len(paths) - failed} of {len(paths)} entries verified against their sources.") return 1 if failed else 0 if __name__ == "__main__": sys.exit(main())