Compare commits
2 commits
42f6b63715
...
316afee730
| Author | SHA1 | Date | |
|---|---|---|---|
| 316afee730 | |||
| 366d43a13c |
3 changed files with 112 additions and 1 deletions
|
|
@ -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 {
|
||||
|
|
|
|||
65
client/src/lib/pageNumber.ts
Normal file
65
client/src/lib/pageNumber.ts
Normal 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;
|
||||
}
|
||||
|
|
@ -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 && (
|
||||
|
|
|
|||
Loading…
Reference in a new issue