Detect the page number from the scanned photo

After the cropped text is recognized, run a second OCR pass on the full,
uncropped photo (the crop usually cuts off the header/footer) and look
for a printed page number in the outermost lines: a standalone number
("42", "- 17 -"), a labelled one ("Seite 128", "p. 12"), or a number at
either end of a short running header on the first line.

The result fills the Page field only if it is still empty, with a hint
asking the user to check it. Failures are silent; the user can still
type the page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Claudio Schaad 2026-11-06 15:27:49 +01:00
parent 42f6b63715
commit 366d43a13c
3 changed files with 112 additions and 1 deletions

View file

@ -1,3 +1,5 @@
import { findPageNumber, type OcrLine } from "./pageNumber";
let workerPromise: Promise<import("tesseract.js").Worker> | null = null;
function getWorker() {
@ -35,6 +37,24 @@ function cleanUpText(raw: string): string {
.trim();
}
/** Looks for the printed page number on a photo of a whole book page. */
export async function recognizePageNumber(image: Blob): Promise<number | null> {
const worker = await getWorker();
const {
data: { blocks }
} = await worker.recognize(image, {}, { blocks: true });
const lines: OcrLine[] = (blocks ?? []).flatMap((block) =>
block.paragraphs.flatMap((paragraph) =>
paragraph.lines.map((line) => ({
text: line.text,
y: (line.bbox.y0 + line.bbox.y1) / 2,
confidence: line.confidence
}))
)
);
return findPageNumber(lines);
}
export async function recognizeText(image: Blob): Promise<string> {
const worker = await getWorker();
const {

View file

@ -0,0 +1,65 @@
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;
}

View file

@ -3,7 +3,7 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { fetchTopics } from "../api/topics";
import { saveNote } from "../api/notes";
import { logout } from "../api/auth";
import { recognizeText } from "../lib/ocr";
import { recognizePageNumber, recognizeText } from "../lib/ocr";
import { ImageCropper } from "../components/ImageCropper";
const NEW_TOPIC_OPTION = "__new__";
@ -19,6 +19,8 @@ export function NoteFormPage({ onLoggedOut }: { onLoggedOut: () => void }) {
const [text, setText] = useState("");
const [isScanning, setIsScanning] = useState(false);
const [scanError, setScanError] = useState<string | null>(null);
const [isDetectingPage, setIsDetectingPage] = useState(false);
const [detectedPage, setDetectedPage] = useState<number | null>(null);
const [pendingImage, setPendingImage] = useState<File | null>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
@ -27,6 +29,7 @@ export function NoteFormPage({ onLoggedOut }: { onLoggedOut: () => void }) {
onSuccess: () => {
setText("");
setPage("");
setDetectedPage(null);
queryClient.invalidateQueries({ queryKey: ["topics"] });
}
});
@ -56,6 +59,9 @@ export function NoteFormPage({ onLoggedOut }: { onLoggedOut: () => void }) {
}
async function handleCropped(image: Blob) {
// The crop usually cuts off the header/footer, so look for the page number
// on the original photo.
const fullPhoto = pendingImage;
setPendingImage(null);
setIsScanning(true);
setScanError(null);
@ -64,9 +70,25 @@ export function NoteFormPage({ onLoggedOut }: { onLoggedOut: () => void }) {
setText((prev) => (prev.trim() ? `${prev}\n${recognized}` : recognized));
} catch {
setScanError("Couldn't recognize text in that photo. Try again with better lighting/focus.");
return;
} finally {
setIsScanning(false);
}
if (!fullPhoto || page) return;
setIsDetectingPage(true);
try {
const found = await recognizePageNumber(fullPhoto);
if (found) {
// Don't overwrite a page the user typed while we were looking.
setPage((prev) => prev || String(found));
setDetectedPage(found);
}
} catch {
// Page detection is a convenience; the user can still type it.
} finally {
setIsDetectingPage(false);
}
}
function handleSubmit(e: FormEvent) {
@ -171,6 +193,10 @@ export function NoteFormPage({ onLoggedOut }: { onLoggedOut: () => void }) {
value={page}
onChange={(e) => setPage(e.target.value)}
/>
{isDetectingPage && <span className="hint">Looking for the page number…</span>}
{detectedPage !== null && String(detectedPage) === page && (
<span className="hint">Detected from the photo — please check.</span>
)}
</label>
{saveNoteMutation.isError && (