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

quote_page_check.py

In the investigation at sim/whittaker/check_chapters_fable/part_2_chapters_IV-VI/quote_page_check.py · last changed in commit 88cc542, 25 November 2026 · 6,085 bytes


"""Check every quotation on a Whittaker chapter page against the archive's OCR text, and its cited page number
against the page where the words are found (from pagemap.json). The reviewer's own tool (T7, part 2).
usage: python3 -I quote_page_check.py OCR_TXT PAGEMAP_JSON CHAPTER_MD
Prints one block per quotation: status, cited page(s), found page(s), the quotation, and for inexact matches the
best OCR passage. Statuses: EXACT (words found verbatim after normalisation), FUZZY (>= 0.85 similarity; OCR noise
or a small change of wording), NOT FOUND (best candidate shown). PAGE OK / PAGE MISMATCH / PAGE UNCITED follows."""
import re, sys, json, unicodedata, difflib

def norm(s):
    s = unicodedata.normalize('NFKD', s)
    s = ''.join(ch for ch in s if not unicodedata.combining(ch)).lower()
    s = s.replace('’', "'").replace('‘', "'")
    s = re.sub(r'-\s*\n\s*', '', s)          # hyphenated line breaks
    s = re.sub(r"'s\b", 's', s)              # possessives: OCR often splits them
    return re.sub(r'[^a-z0-9]+', ' ', s).strip()

ocr_lines = open(sys.argv[1], encoding='utf-8', errors='replace').read().split('\n')
pagemap = {int(k): v for k, v in json.load(open(sys.argv[2])).items()}   # page -> 1-based line of its head
heads = sorted(pagemap.items())

def page_of_line(ln):
    """Return (page_lo, page_hi) for a 1-based OCR line: exact when heads on both sides are mapped."""
    p = None
    for pg, hl in heads:
        if hl <= ln: p = pg
        else: break
    if p is None: return (0, 0)
    nxt = [pg for pg, hl in heads if hl > ln]
    hi = (nxt[0] - 1) if nxt else p
    return (p, hi)

# normalised book with char -> line map
chars = []; cmap = []
for i, ln in enumerate(ocr_lines):
    n = norm(ln).replace(' ', '')
    chars.append(n); cmap.extend([i + 1] * len(n))
B = ''.join(chars)
words = norm('\n'.join(ocr_lines)).split()
# word index for fuzzy search
widx = {}
for i, w in enumerate(words): widx.setdefault(w, []).append(i)
# word -> approximate char position: build by cumulative length
wpos = []; acc = 0
for w in words: wpos.append(acc); acc += len(w)

def best(piece):
    ws = piece.split(); n = len(ws); cand = {}
    for k, w in enumerate(ws):
        if len(w) < 5: continue
        for i in widx.get(w, [])[:600]: cand[i - k] = cand.get(i - k, 0) + 1
    top = sorted(cand, key=lambda s: -cand[s])[:15]; r = (0.0, '', None)
    for s in top:
        for d in (-2, -1, 0, 1, 2):
            a = max(0, s + d); seg = ' '.join(words[a:a + n])
            q = difflib.SequenceMatcher(None, piece, seg).ratio()
            if q > r[0]: r = (q, seg, a)
    return r

text = open(sys.argv[3], encoding='utf-8').read()
# strip markdown links to their text so 'p. 100' survives: [p. 100](url) -> p. 100
text = re.sub(r'\[([^\]]+)\]\((https?://[^)]+)\)', r'\1', text)
lines = text.split('\n')

def cited_pages(after, before, section_range):
    for src in (after, before):
        m = re.search(r'\bpp?\.\s*(\d{1,3})(?:\s*(?:to|–|-|and)\s*(\d{1,3}))?', src)
        if m:
            lo = int(m.group(1)); hi = int(m.group(2)) if m.group(2) else lo
            if hi < lo: hi = lo
            return (lo, hi, 'explicit')
    if section_range: return (section_range[0], section_range[1], 'section heading')
    return None

section_range = None
tot = ex = fz = nf = pok = pbad = punc = 0
for ln_no, line in enumerate(lines, 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
    if line.startswith('## '):
        section_range = None
    qs = list(re.finditer(r'"([^"]{8,})"|“([^”]{8,})”', line))
    for qi, m in enumerate(qs):
        q = m.group(1) or m.group(2)
        pieces = [norm(x) for x in re.split(r'\.\.\.|…|\[[^\]]*\]', q)]
        pieces = [x for x in pieces if len(x.replace(' ', '')) >= 8]
        if not pieces: continue
        tot += 1
        after = line[m.end(): (qs[qi + 1].start() if qi + 1 < len(qs) else m.end() + 160)]
        before = line[max(0, m.start() - 200): m.start()]
        cp = cited_pages(after, before, section_range)
        found_pages = []; status = 'EXACT'; notes = []
        for x in pieces:
            key = x.replace(' ', '')
            pos = B.find(key)
            if pos >= 0:
                occ = [pp for pp in [pos] + [B.find(key, pos + 1)] if pp >= 0]
                for pp in occ: found_pages.append(page_of_line(cmap[pp]))
            else:
                r = best(x)
                if r[0] >= 0.85:
                    status = 'FUZZY' if status == 'EXACT' else status
                    cpos = wpos[r[2]]
                    found_pages.append(page_of_line(cmap[min(cpos, len(cmap) - 1)]))
                    notes.append(f'    best {r[0]:.2f} (p. {page_of_line(cmap[min(cpos, len(cmap) - 1)])}): {r[1][:200]}')
                else:
                    status = 'NOT FOUND'
                    if r[2] is not None:
                        cpos = wpos[r[2]]
                        notes.append(f'    best {r[0]:.2f} (p. {page_of_line(cmap[min(cpos, len(cmap) - 1)])}): {r[1][:200]}')
        if status == 'EXACT': ex += 1
        elif status == 'FUZZY': fz += 1
        else: nf += 1
        pv = 'PAGE UNCITED'
        if cp and found_pages and status != 'NOT FOUND':
            lo, hi, how = cp
            ok = any(not (fp[1] < lo or fp[0] > hi) for fp in found_pages)
            pv = f'PAGE OK ({how})' if ok else f'PAGE MISMATCH ({how})'
            if ok: pok += 1
            else: pbad += 1
        elif status != 'NOT FOUND':
            punc += 1
        fps = ', '.join(f'{a}' if a == b else f'{a}-{b}' for a, b in found_pages) or '-'
        cps = f'{cp[0]}' if cp and cp[0] == cp[1] else (f'{cp[0]}-{cp[1]}' if cp else '-')
        print(f'L{ln_no} {status}; {pv}; cited {cps}; found {fps}\n    "{q[:170]}"')
        for n_ in notes: print(n_)
print(f'\nSUMMARY: {tot} quotations; {ex} exact, {fz} fuzzy, {nf} not found; pages: {pok} ok, {pbad} mismatch, {punc} uncited (of those found)')