Whittaker's History (1910), reviewed › The review's files › sim/whittaker/check_chapters_fable/part_1_chapters_I-III/

quotes_pages.py

In the investigation at sim/whittaker/check_chapters_fable/part_1_chapters_I-III/quotes_pages.py · last changed in commit 88cc542, 25 November 2026 · 7,276 bytes


"""Check every quotation on a Whittaker chapter page against the archive's OCR text, and the page number the page gives for it
against the page on which the OCR has it (from pagemap.json, built by pagemap.py from the running heads).
The thirty-fifth reviewer's tool (T7, part 1), 25 November 2026.  Own derivation; the earlier quotecheck.py was not imported.
usage: python3 -I quotes_pages.py OCR_TXT PAGEMAP_JSON CHAPTER_MD FIRST_LINE LAST_LINE > out.txt
  FIRST_LINE, LAST_LINE: the OCR lines of the chapter (the contents list at the front repeats the headings, so it is excluded).
Each quotation "..." on the page is split at ellipses and bracketed insertions; each piece of 12 letters or more is sought in the
normalised OCR text (lower case, accents and punctuation dropped, hyphenation at line ends joined).  A piece not found exactly is
sought by alignment on its rarer words and scored by difflib.  The page number the page claims is the nearest "p. N" or "pp. N to M"
on the same line after the quotation, else before it, else the section heading's range.  Verdicts: OK (every piece found, on a
claimed page); PAGE? (found, but not on the page claimed); OCR~ (found within 10% only: OCR noise or a changed word, read it);
NOT IN BOOK (not Whittaker's text: a quotation from an original read at source, or a misquotation)."""
import re, sys, json, unicodedata, difflib
ocr_path, map_path, md_path, lo, hi = sys.argv[1], sys.argv[2], sys.argv[3], int(sys.argv[4]), int(sys.argv[5])
raw = open(ocr_path, encoding='utf-8', errors='replace').read().split('\n')
pagemap = json.load(open(map_path))
def page_of_line(ln):
    pg = None
    for l, p in pagemap:
        if l <= ln: pg = p
        else: break
    return pg
def norm_char(ch):
    ch = unicodedata.normalize('NFKD', ch)
    ch = ''.join(c for c in ch if not unicodedata.combining(c))
    return ch.lower()
# normalised OCR text with a map from each normalised character to its OCR line
chars, linemap = [], []
for i in range(lo - 1, hi):
    line = raw[i]
    if line.rstrip().endswith('-') and not line.rstrip().endswith('--'): line = line.rstrip()[:-1]   # join a hyphenated word
    else: line = line + ' '
    for ch in line:
        n = norm_char(ch)
        for c in n:
            if c.isalnum(): chars.append(c); linemap.append(i + 1)
B = ''.join(chars)
words_pos = {}   # word -> list of start offsets, for the fuzzy search (words are runs of letters in the normalised OCR, >= 5 chars)
def norm(s):
    s = ''.join(norm_char(c) for c in s)
    return re.sub(r'[^a-z0-9]+', ' ', s).strip()
# build a word index on the normalised OCR with spaces kept
Bw = []
cur = ''
spaced, spaced_map = [], []
prev_line = None
for i in range(lo - 1, hi):
    line = raw[i]
    hy = line.rstrip().endswith('-') and not line.rstrip().endswith('--')
    txt = line.rstrip()[:-1] if hy else line
    for ch in txt:
        n = norm_char(ch)
        for c in n:
            if c.isalnum(): spaced.append(c); spaced_map.append(i + 1)
            elif spaced and spaced[-1] != ' ': spaced.append(' '); spaced_map.append(i + 1)
    if not hy and spaced and spaced[-1] != ' ': spaced.append(' '); spaced_map.append(i + 1)
S = ''.join(spaced)
idx = {}
for m in re.finditer(r'\S+', S):
    w = m.group(0)
    if len(w) >= 5: idx.setdefault(w, []).append(m.start())
def fuzzy(piece):
    """Best alignment of a normalised piece in S: candidate offsets from its words, scored by difflib."""
    ws = piece.split(); cand = {}
    offs = [0]
    for w in ws[:-1]: offs.append(offs[-1] + len(w) + 1)
    for k, w in enumerate(ws):
        if len(w) < 5: continue
        for pos in idx.get(w, [])[:600]: cand[pos - offs[k]] = cand.get(pos - offs[k], 0) + 1
    best = (0.0, None, None)
    for start in sorted(cand, key=lambda s: -cand[s])[:15]:
        for d in (-3, 0, 3):
            a = max(0, start + d); seg = S[a:a + len(piece) + 6]
            r = difflib.SequenceMatcher(None, piece, seg).ratio()
            if r > best[0]: best = (r, a, seg)
    return best
def find_exact(piece):
    key = piece.replace(' ', '')
    out = []
    start = 0
    while True:
        j = B.find(key, start)
        if j < 0 or len(out) > 5: break
        out.append((linemap[j], linemap[j + len(key) - 1])); start = j + 1
    return out
md = open(md_path, encoding='utf-8').read().split('\n')
PREF = re.compile(r'\[?pp?\.\s*(\d{1,3})\]?(?:\([^)]*\))?(?:\s*(?:to|and|,)\s*(\d{1,3}))?')
def claimed_pages(line, qstart, qend, section_range):
    refs = [(m.start(), int(m.group(1)), int(m.group(2)) if m.group(2) else int(m.group(1))) for m in PREF.finditer(line)]
    after = [r for r in refs if r[0] >= qend]
    before = [r for r in refs if r[0] < qstart]
    if after: r = after[0]
    elif before: r = before[-1]
    else: return section_range, 'section'
    return (min(r[1], r[2]), max(r[1], r[2])), 'line'
section_range = None
tot = ok = pagebad = fuzz = notin = 0
rows = []
for ln, line in enumerate(md, 1):
    if line.startswith('#'):
        m = re.search(r'\(pp?\.\s*(\d{1,3})(?:\s*to\s*(\d{1,3}))?\)', line)
        section_range = (int(m.group(1)), int(m.group(2) or m.group(1))) if m else None
    for q in re.finditer(r'"([^"]*)"', line):           # pair every quotation mark first, then drop short quotations
        text = q.group(1)
        if len(re.sub(r'[^A-Za-z0-9]', '', text)) < 12: continue
        pieces = [norm(x) for x in re.split(r'\.\.\.|…|\[[^\]]*\]', text)]
        pieces = [p for p in pieces if len(p.replace(' ', '')) >= 12]
        if not pieces: continue
        tot += 1
        claim, how = claimed_pages(line, q.start(), q.end(), section_range)
        found_pages, verdict, note = set(), 'OK', ''
        for p in pieces:
            hits = find_exact(p)
            if hits:
                for a, b in hits[:1]: found_pages.update({page_of_line(a), page_of_line(b)})
            else:
                r, a, seg = fuzzy(p)
                if r >= 0.9 and a is not None:
                    found_pages.update({page_of_line(spaced_map[a]), page_of_line(spaced_map[min(a + len(p), len(spaced_map) - 1)])})
                    if verdict == 'OK': verdict = 'OCR~'
                    note += f' | best {r:.2f}: "{seg[:90]}"'
                else:
                    verdict = 'NOT IN BOOK'; note += f' | best {r:.2f}: "{(seg or "")[:90]}"'
        if verdict != 'NOT IN BOOK' and found_pages:
            if claim is None: verdict += ' (no page claimed)'
            elif not any(claim[0] <= p <= claim[1] for p in found_pages): verdict = 'PAGE? ' + verdict
        if verdict.startswith('OK'): ok += 1
        elif verdict.startswith('PAGE?'): pagebad += 1
        elif verdict.startswith('OCR~'): fuzz += 1
        else: notin += 1
        fp = ','.join(str(p) for p in sorted(x for x in found_pages if x)) or '-'
        cl = f'{claim[0]}' + (f'-{claim[1]}' if claim and claim[1] != claim[0] else '') if claim else 'none'
        rows.append(f'{verdict:22s} line {ln:4d}  found p.{fp:8s} claimed p.{cl:8s} ({how})  "{text[:70]}"{note}')
print(f'{md_path.split("/")[-1]}: {tot} quotations of 12+ letters; {ok} OK (found, page right); {pagebad} on another page than claimed; '
      f'{fuzz} found only within 10% (OCR noise or changed words); {notin} not in the book text')
print('\n'.join(rows))