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

pagemap.py

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


"""Map the 1910 edition's page numbers to line numbers of the archive's OCR text, from the running heads.
The reviewer's own tool (T7, part 2). usage: python3 -I pagemap.py OCR_TXT OUT_JSON
Even pages carry 'NNN  Title...' at the top; odd pages carry '...Title.  NNN'. OCR garbles some digits, so the
map is built by walking forward and accepting a head only if its number is the next page expected (or a small
skip, reported as a gap)."""
import re, sys, json
lines = open(sys.argv[1], encoding='utf-8', errors='replace').read().split('\n')
cands = []  # (line index, number, kind)
for i, ln in enumerate(lines):
    s = ln.strip()
    m = re.match(r'^(\d{1,3})\s+[A-Za-z]', s)
    if m and len(s) < 80:
        cands.append((i, int(m.group(1)), 'even'))
        continue
    m = re.match(r'^[A-Za-z].*?\s(\d{1,3})\s*$', s)
    if m and len(s) < 80 and not re.search(r'\b(p|pp|vol|No|Nr)\.\s*\d+\s*$', s) and not re.search(r'[\(\)]', s):
        cands.append((i, int(m.group(1)), 'odd'))
# walk: find page 1 .. 475 in order, allowing skips up to 3 (OCR-garbled heads)
page_line = {}
expect = 1
j = 0
while j < len(cands) and expect <= 475:
    i, n, k = cands[j]
    if n == expect:
        page_line[n] = i; expect += 1
    elif expect < n <= expect + 3:
        # look ahead: accept only if the following candidates continue from n
        ok = any(c[1] == n + 1 for c in cands[j + 1:j + 60])
        if ok:
            page_line[n] = i; expect = n + 1
    j += 1
json.dump({str(k): v + 1 for k, v in sorted(page_line.items())}, open(sys.argv[2], 'w'), indent=0)  # 1-based lines
missing = [p for p in range(1, 476) if p not in page_line]
print(f'pages mapped: {len(page_line)} of 475; missing heads: {missing}')
for p in range(95, 226):
    if p in page_line:
        print(p, page_line[p] + 1, lines[page_line[p]].strip()[:60])