Whittaker's History (1910), reviewed › The review's files › sim/whittaker/check_chapters_fable/part_3_chapters_VII-IX/
check_quotes_pages.py
"""Check every quotation on a Whittaker chapter page against the book's OCR, and the page number the page gives for it
against the page where the OCR has the words. Reviewer's own tool (thirty-first review, part 3), 25 November 2026.
usage: python3 -I check_quotes_pages.py REPO PAGEDIR 07 08 09
PAGEDIR holds pNNN.txt from split_pages.py (pages whose header the OCR lost are inside the page before: 244 in 243, 251 in 250,
268 in 267, 310 in 309, 313 in 312, 316 to 318 in 315).
For each line of papers/whittaker_review/Chapter_NN.md: the quotations in double quotes (8+ letters), the page references on the
line ("p. N", "pp. N to M", "[p. N](...)", "[pp. N](...) to M"), where the quotation's words are found in the OCR pages of
Chapters VII to IX (exact after normalising; else the best fuzzy match), and whether that page lies in the cited range."""
import re, sys, os, glob, unicodedata, difflib
REPO, PD = sys.argv[1], sys.argv[2]
LOST = {244: 243, 251: 250, 268: 267, 310: 309, 313: 312, 316: 315, 317: 315, 318: 315}
def norm(s):
s = unicodedata.normalize('NFKD', s)
s = ''.join(ch for ch in s if not unicodedata.combining(ch)).lower()
s = re.sub(r'-\s*\n\s*', '', s) # hyphenation at line ends
s = s.replace('’', "'").replace('‘', "'")
return re.sub(r'[^a-z0-9]+', ' ', s).strip()
pages = {}
for f in glob.glob(os.path.join(PD, 'p*.txt')):
n = int(os.path.basename(f)[1:4]); pages[n] = norm(open(f, encoding='utf-8', errors='replace').read())
allp = sorted(pages)
joined = ' '.join(pages[n] for n in allp)
# word index -> page, for locating a fuzzy match
wp = []
for n in allp:
wp += [n] * len(pages[n].split())
jw = joined.split()
def find(piece):
"""return (page or None, ratio) for a normalised piece"""
pc = piece.replace(' ', '')
for n in allp:
if pc in pages[n].replace(' ', ''): return n, 1.0
# straddling two pages
for i in range(len(allp) - 1):
if pc in (pages[allp[i]] + ' ' + pages[allp[i + 1]]).replace(' ', ''): return allp[i], 1.0
ws = piece.split(); L = len(ws); best = (0.0, None)
anchors = [w for w in ws if len(w) >= 6][:6] or ws[:3]
cand = set()
for a in anchors:
for k, w in enumerate(jw):
if w == a:
cand.add(max(0, k - ws.index(a)))
for s in list(cand)[:3000]:
seg = ' '.join(jw[s:s + L]); q = difflib.SequenceMatcher(None, piece, seg).ratio()
if q > best[0]: best = (q, wp[min(s, len(wp) - 1)])
return best[1], best[0]
def cited_pages(line):
"""all page numbers referred to on the line, as a set of ints (ranges expanded)"""
out = set()
t = re.sub(r'\]\([^)]*\)', ']', line) # drop link targets
for m in re.finditer(r'pp?\.\s*\[?(\d{1,3})\]?(?:\s*(?:to|-|–|and)\s*\[?(\d{1,3})\]?)?', t):
a = int(m.group(1)); b = int(m.group(2)) if m.group(2) else a
if 200 <= a <= 340:
out.update(range(a, max(a, b) + 1))
return out
tot = ex = fz = 0; rows = []
for ch in sys.argv[3:]:
f = os.path.join(REPO, f'papers/whittaker_review/Chapter_{ch}.md')
for ln, line in enumerate(open(f, encoding='utf-8').read().split('\n'), 1):
qs = re.findall(r'"([^"]+)"', line) + re.findall(r'“([^”]+)”', line)
if not qs: continue
cp = cited_pages(line)
for q in qs:
pieces = [norm(x) for x in re.split(r'\.\.\.|…|\[[^\]]*\]', q)]
pieces = [x for x in pieces if len(x) >= 8]
if not pieces: continue
tot += 1
res = [find(x) for x in pieces]
pg = [r[0] for r in res if r[0]]; q0 = min(r[1] for r in res)
if q0 >= 0.999: ex += 1
elif q0 >= 0.9: fz += 1
status = 'exact' if q0 >= 0.999 else ('ocr' if q0 >= 0.9 else 'LOOK')
pgs = sorted(set(pg))
if cp and pgs:
inrange = all(p in cp or LOST.get(p, p) in cp or any(LOST.get(c, c) == p for c in cp) for p in pgs)
pstat = 'page ok' if inrange else f'PAGE: cited {sorted(cp)} found {pgs}'
elif pgs: pstat = f'no page cited on line; found {pgs}'
else: pstat = 'not found in VII-IX'
rows.append((ch, ln, status, round(q0, 2), pstat, q[:110]))
print(f'{tot} quotations on the pages: {ex} exact in the OCR of pp. 222-336, {fz} within 10% (OCR noise), {tot - ex - fz} to look at')
for r in rows:
if r[2] != 'exact' or 'ok' not in r[4]:
print(f' Ch{r[0]}:{r[1]} [{r[2]} {r[3]}] {r[4]}\n "{r[5]}"')
print('--- all rows ---')
for r in rows: print(f'Ch{r[0]}:{r[1]}\t{r[2]}\t{r[3]}\t{r[4]}\t{r[5]}')