export interface OcrLine { text: string; /** Vertical centre of the line, used to put lines in top-to-bottom order. */ y: number; confidence: number; } const MAX_PAGE = 5000; const MIN_CONFIDENCE = 60; // Page numbers live in the header or footer, so only look at the outermost lines. const EDGE_LINES = 3; // "12", "- 12 -", "[12]", "| 12" const STANDALONE = /^[\s\-–—|[(•·]*(\d{1,4})[\s\-–—|\]).•·]*$/; // "Seite 12", "S. 12", "Page 12", "p. 12" const LABELLED = /^(?:seite|s\.|page|p\.)\s*(\d{1,4})$/i; // Running headers: "12 Chapter One" / "Chapter One 13" const LEADING = /^(\d{1,4})\s+\p{L}/u; const TRAILING = /\p{L}[\p{L}\p{P}\s]*\s(\d{1,4})$/u; function toPage(match: RegExpMatchArray | null): number | null { if (!match) return null; const n = Number(match[1]); return n >= 1 && n <= MAX_PAGE ? n : null; } function looksLikeHeader(text: string): boolean { return !/[.,;:!?]$/.test(text) && text.split(/\s+/).length <= 8; } /** * Picks the most likely printed page number from OCR lines of a full book page, * or null if nothing looks like one. */ export function findPageNumber(lines: OcrLine[]): number | null { const ordered = lines .map((line) => ({ ...line, text: line.text.trim() })) .filter((line) => line.text && line.confidence >= MIN_CONFIDENCE) .sort((a, b) => a.y - b.y); if (ordered.length === 0) return null; const candidates: { page: number; score: number }[] = []; ordered.forEach((line, index) => { const distanceFromEdge = Math.min(index, ordered.length - 1 - index); if (distanceFromEdge >= EDGE_LINES) return; // Closer to the very top/bottom is more likely to be the page number. const edgeBonus = EDGE_LINES - distanceFromEdge; const standalone = toPage(line.text.match(STANDALONE)) ?? toPage(line.text.match(LABELLED)); if (standalone) { candidates.push({ page: standalone, score: 10 + edgeBonus }); return; } // A number at the start/end of a sentence is common in body text, so only // trust it in something that looks like a running header: the very first // line, short, and not ending like a sentence. if (index === 0 && looksLikeHeader(line.text)) { const inHeader = toPage(line.text.match(LEADING)) ?? toPage(line.text.match(TRAILING)); if (inHeader) candidates.push({ page: inHeader, score: edgeBonus }); } }); candidates.sort((a, b) => b.score - a.score); return candidates[0]?.page ?? null; }