From scanned book spreads to useful text
ybBookExtraction · Local book digitisation with page references and visible quality checks.
The problem: a scan is not yet a useful document
A scanned book often arrives as a PDF of two-page spreads. Text bends into the binding, printed page numbers differ from PDF indexes, and searching or quoting a passage means working through images. I built ybBookExtraction to turn those scans into readable text while keeping a path back to the source page.
For books you own, for your own use
This tool is intended for digitising books you own, for your own personal use. This page describes the software and its development; source books and digitised editions are not distributed here.
From a spread to individual pages
A local vision model identifies page boundaries, covers and the spine. The pipeline splits spreads, corrects perspective and applies bounded straightening to curved text lines. Tesseract then performs OCR. Printed page numbers are read from the image and checked against the sequence; uncertain numbers are flagged rather than filled in from a guess.
Scanned PDF spreads
→ Local page and cover analysis
→ Page splitting and image correction
→ OCR and printed page numbers
→ Markdown, PDFs and quality reportThree ways to use the result
Markdown provides readable paragraphs, page boundaries and source references. A searchable image PDF preserves the corrected page images with an OCR text layer. An optional reconstructed PDF places selectable Unicode text and separate image regions using the saved OCR geometry. Both PDF variants can now use one consistent page size across the whole book.
The reconstructed version is a first heuristic implementation. It estimates typography and image regions; exact fonts, italics, complex illustrations and overlapping text can differ from the original. The image PDF and raw material remain available for comparison.
One page size across the book
New exports default to an estimated common page size derived from ordinary body pages. You can also choose A5, B5 or a custom size in millimetres, or keep the individual source sizes. Text, images and OCR layers are scaled together proportionally and centred with margins. The automatic estimate describes the digital output; it does not establish the original book’s physical dimensions.
Optional calibration, with content checks
An experimental calibration mode tries a bounded set of bleed-through filtering and typography settings on a sample before a full export. It reserves separate validation pages and asks a local vision model to compare the source, corrected page and rendered reconstruction. A cleaner-looking page cannot compensate for detected content loss. Failed or inconclusive calibration blocks the automatic full run.
Calibration is off by default. This first implementation reuses existing OCR and searches export settings; it does not repair failed page splits or freely optimise OCR and geometry. Real-model assessment quality remains to be verified before recommending unattended use.
Keep the evidence, reuse the work
Each export includes a page index and a quality report. Uncertain geometry, low OCR confidence and numbering anomalies stay visible. Original PDFs are preserved. When OCR fails, the image export retains the page and the text export marks the failure.
Expensive stages are cached separately. An interrupted job can resume, and changes to Markdown cleanup or PDF reconstruction can reuse valid earlier analysis and OCR. The aim is to improve an export without repeatedly processing the whole book.
Current status
The development pipeline has processed one complete book: 134 source PDF pages produced 268 main pages and a separate spine appendix. The project documentation now records 158 passing automated tests. New functionality includes a common PDF page format and an opt-in calibration workflow for reconstruction settings.
The earlier full-book export provides the baseline evidence: it reported uncertain page segments, numbering anomalies and 73 pages with additional reconstruction warnings. A separate common-format revision preserved all 268 pages, text operators, image data and page labels. The new calibration control flow has been tested with synthetic evidence and a mocked quality judge; its real-model judgments still need validation on the target Mac. Full page coverage and a technically valid PDF do not establish that every word or illustration is correct.
Local processing on Apple Silicon
Page analysis runs locally with MLX, with image processing and OCR on the same Mac. After initial tool and model downloads, the processing workflow can run offline. The current pilot uses a 4-bit vision model on a Mac with 48 GB unified memory.
The installer currently requires at least 32 GB of physical memory and recommends 48 GB for the default model; 32 GB has not been validated as a reliable configuration. A complete fresh installation on a clean Mac has not yet been tested. This remains a command-line lab project rather than a packaged public release.
What this explores
The useful role for local AI here is one step in an inspectable document workflow: identify geometry, preserve source references, expose uncertainty and reuse the work already done. The result is a personal reading and reference copy whose quality can be checked page by page.
Technical deep dive
Architecture: a Python pipeline with a local vision worker
The command-line process coordinates a persistent SQLite task history, cached files and two execution environments. A long-lived MLX-VLM worker loads the vision model once and accepts layout-analysis requests over JSON Lines. A separate CPU worker handles image processing, Tesseract and PDF operations. Opt-in calibration uses a separate multi-image quality worker in the local MLX environment. Model diagnostics go to a separate log so they do not corrupt the JSON protocol.
Optional preparation: sample → calibration profiles → held-out validation
→ approved book profile, or stop
1. Manifest and import Python + Poppler pdfinfo
2. Page rendering Poppler pdftoppm
3. Layout analysis Gemma 4 → MLX-VLM → MLX / Metal GPU
4. Split and correction Pillow + NumPy + OpenCV
5. OCR and profile choice Tesseract + quality scoring
6. Printed page numbers Sequence checks + margin OCR
7. Optional reconstruction OpenCV + FontTools + pypdf
8. Common PDF page format Proportional fit and centring
9. Conditional full audit Required for a calibrated run
10. Export and validation Markdown + PDFs + JSON / HTML reports
Calibration reuses completed stages or prepares a limited sample.1. Import and render two image variants
A JSON manifest sets the PDF order, OCR languages and reading direction. Import checks the files with pdfinfo and records content hashes and page counts. Each source PDF page is rendered independently: the default full-resolution image is 300 DPI, while the analysis variant is limited to 1,800 pixels on its longest side. Keeping these variants separate lets layout analysis use a smaller image while OCR retains detail.
2. The model, MLX and Metal
The current configured vision model is lmstudio-community/gemma-4-26B-A4B-it-QAT-MLX-4bit. It is loaded directly from local model files with mlx_vlm.load; there is no inference-server request in this path. The development setup reuses a Python runtime and model originally installed with LM Studio, but LM Studio itself does not need to be running. The installer can instead create a separate local environment.
MLX is the array-computation framework used by the model runtime. In this implementation, the worker checks Metal availability and explicitly selects the GPU. MLX-VLM supplies model loading, image preprocessing, the chat template and generation. The known development versions are MLX 0.32.0, MLX-VLM 0.6.5 and Transformers 5.14.1; these versions are pinned in the installation requirements.
Model: Gemma 4 26B-A4B IT QAT · MLX 4-bit
Image cap: 1,280 px on the longest side before model preprocessing
Generation limit: 1,600 tokens
Temperature: 0.0
Requested seed: 0
Thinking: disabled in the chat template
MLX memory limit: 28 GiB
Worker timeout: 240 seconds per reply
Analysis attempts: at most 2The memory setting is a configured MLX allocation limit, not a measurement of total process memory or a guarantee that the machine cannot run out of memory. A fixed seed and zero temperature also do not establish reproducibility across different runtime versions or hardware. The worker enables offline model loading and disables remote model code; normal processing has no cloud-model fallback.
3. Structured geometry, validated before use
The vision prompt asks for physical page polygons, the binding crease, cover roles and an optional spine polygon. It explicitly asks the model not to transcribe or summarise the book, and treats text inside the image as document content. The current model configuration uses coordinates on a 0–1000 scale. The parser normalises them before mapping the geometry back to the full-resolution page image.
The returned JSON is parsed and checked for valid geometry and layout consistency. Raw model responses and diagnostic overlays are retained. A prompt alone cannot guarantee correct boundaries: uncertain or invalid geometry remains visible, and the pipeline preserves unresolved source imagery instead of silently assuming a split down the middle.
4. Split, correct and compare OCR profiles
The validated polygons drive page splitting. Covers, body pages and the spine keep separate roles, and the spine is exported as an appendix. OpenCV applies perspective correction and estimates curved text baselines from connected text regions. A bounded vertical deformation grid is accepted only when its mapping remains monotonic and the measured curvature improves. This is a two-dimensional image method; it cannot recover letters hidden in a binding.
The pipeline can try original, conservative and strong profiles, with at most three profile attempts per page. Each combines image correction with OCR. Tesseract normally uses automatic page segmentation, a single-block mode for the strong profile, and sparse-text handling for front covers and spine text. Languages come from the book manifest, for example Swedish and English; missing language data stops the operation rather than silently changing language.
Profile selection combines OCR confidence, text preservation, character patterns, edge contacts, geometry and remaining curvature. More recognised characters alone do not make a result better. The first clearly acceptable result can stop further attempts. Raw text, word boxes, confidence values, selected images and transformation data remain available for inspection.
5. Recover printed page numbers without inventing them
Source-PDF index, exported page order and printed page number are distinct fields. OCR observations and recurring header/footer positions help identify printed numbers. Where a reliable sequence provides a likely location, a separate margin-crop OCR pass tries to read the number again. The expected sequence guides validation; it does not by itself authorise filling in a missing number. Conflicts and unreadable numbers stay flagged.
6. Optional calibration before the full export
Calibration starts from compatible completed page evidence or prepares a limited sample. The default target is about 20 book pages, extended to at most 40 when observed page types or risks need representation. Whole spreads and detected near-duplicates stay in the same subset. About 20 percent is held out for independent validation. This sampling does not prove coverage of every illustration, footnote or meaningful emphasis style.
The quality worker uses the configured local vision model in a different role from layout analysis. It receives two or three evidence images: the source spread, selected corrected page and rendered reconstruction, plus a separate footer comparison where required. It requests structured findings for text, numbers, punctuation, figures, reading order, footnotes, emphasis and geometry. Calibration judgments use a 1,536-pixel image cap and up to 4,096 generated tokens, with temperature zero and thinking disabled.
Before judging candidates, the worker must pass six synthetic controls covering unchanged content, a removed negation, changed digits or decimals, a missing figure and a missing footnote. These checks catch some obvious failures; they do not establish reliable detection of subtle errors in real books. Using the same configured model for layout and quality assessment can also produce correlated mistakes.
A deterministic search tries at most six distinct combinations of bleed-through threshold and normalized or positional typography. A profile with filtering disabled is always included. Known filtered words require individual evidence; ambiguous or legitimate text removal blocks approval. Mechanical checks and complete validated model judgments must pass before a candidate reaches held-out validation. A failed or uncertain content check cannot be offset by an aesthetic score.
Sample target: 20 book pages, up to 40 with coverage additions
Export profiles: at most 6
Quality-model calls: at most 160, including retries and controls
Technical attempts: at most 2 per task
Elapsed-time budget: 7,200 seconds
New working-data budget: 12 GiB
Full-run audit budget: 80 additional quality-model calls
Outcomes: passed / failed / inconclusive / interruptedValidation calls are reserved before profile search. Time and disk limits are checked at task boundaries, so an in-progress tool call may need to finish or time out before a stop is reported. A passed profile is frozen with source, model, code and evidence identities. An unchanged cached profile is reused only after those dependencies are checked.
./run.sh calibrate --manifest manifests/example-book.json --sample-pages 20
./run.sh process --manifest manifests/example-book.json \
--calibrate auto --pdf-mode bothThe standard processing mode remains calibration off. The new implementation has CPU and control-flow tests with a mocked judge. Its actual MLX content assessments and false-positive/false-negative behaviour on the development books remain unverified. It is an experimental gate with explicit uncertainty, not a guarantee of faithful transcription.
7. Reconstruct a PDF from text and separate images
The searchable image PDF keeps the selected page raster and its OCR layer. In reconstruction, OpenCV separates candidate image regions from known OCR text, and pypdf places visible Unicode text and cropped images using the original corrected-page geometry. The final common-format step transforms this content to the selected output canvas. FontTools checks the local TrueType font’s embedding restrictions and supplies font metrics; the PDF embeds the font and a ToUnicode mapping for copying and searching.
The default reconstructed typography places complete OCR lines with natural character widths and shared size classes. An alternative positional mode places words closer to their OCR boxes. A configurable local-contrast filter can suppress faint bleed-through, but can also remove legitimate faint content. If text overlaps a detected picture, local inpainting estimates the background under the removed text; that operation is reported. Small illustrations, typography and complex overlaps remain known limitations.
Markdown cleanup is independent of PDF reconstruction. It joins likely line-end hyphenations within a page and preserves paragraph and page markers. Raw OCR is retained, text is not rewritten by a language model, and words are not silently moved across page boundaries.
8. Fit every page to a common canvas
The default page-size mode is auto. It estimates width and height from median dimensions of usable body pages, excluding covers and obvious size outliers when sufficient evidence exists. Explicit A- or B-series sizes and custom width × height values in millimetres are supported. Source mode retains individual page dimensions. The auto mode does not snap to the nearest paper standard, and rendered pixel dimensions do not verify the original physical book size.
pypdf applies one uniform scale and a centring offset to each page. The image, text and OCR layer move together; page boxes are updated consistently and labels are preserved. No content is cropped or stretched differently along the horizontal and vertical axes. A foldout can therefore appear smaller with additional margins. The export records the estimate, sample pages and transforms in page-format.json.
./run.sh process --pdf-mode both --page-size auto
./run.sh process --pdf-mode both --page-size A5
./run.sh process --pdf-mode both --page-size B5
./run.sh process --pdf-mode both --page-size 130x200
./run.sh process --pdf-mode both --page-size sourcePage-format selection is an export setting: valid rendering, layout analysis, OCR and reconstructed page artifacts can be reused. A separately verified revision of the development book reduced 39 distinct page sizes to one common format across 268 pages while preserving text operators, image data and page labels. This verifies the transformation, not the correctness of the underlying OCR.
9. Audit calibrated full runs before committing the export
When a passed calibration profile is used, every reconstructed page receives mechanical integrity checks. Pages with risk flags, newly observed characteristics, images or filtered content receive fresh visual judgments under a separate call budget. A critical failure, unresolved judgment or exhausted audit budget blocks committing the calibrated export. The report states how many pages were visually reviewed; the remaining pages are not claimed to be verified character by character.
Calibration reports preserve sample membership, candidate settings, mechanical measurements, model responses, malformed judgments and preview PDFs. Full-run reports connect the approved profile to the audit outcome. A failed or inconclusive calibration does not launch the automatic full run or replace a previous working export.
10. Cache identity, recovery and export checks
SQLite records runs and page-level task states. A process lock prevents simultaneous writers to the same workspace. Cached artifacts are identified with SHA-256 hashes of relevant inputs, settings, code and runtime dependencies. Vision-model identity includes its inference assets; OCR identity includes the language data. Completed artifacts are committed atomically and checked before reuse.
The dependency boundaries matter: changing OCR language invalidates OCR and downstream work; changing PDF reconstruction or Markdown rules can reuse valid rendering, geometry and OCR. The worker retains its loaded model during a run, while the on-disk cache can avoid model calls entirely on an unchanged rerun. These are different mechanisms: persistent stage caching is not a claim that a model prompt cache makes every request free.
book.md Readable text with page references
book.pages.pdf Searchable image reference
book.reconstructed.pdf Optional text-and-image reconstruction
book.spine.md Separate spine appendix
pages.json Page identities, order and observed numbers
page-format.json Canvas estimate and per-page transforms
quality.json / .html Quality flags and coverage
reconstruction.json Optional region and reconstruction report
run.json Run settings and export provenance
assets/ Images, OCR and transformation evidence
Calibrated runs also include the approved profile, sample report
and full-run audit report.Exports are written to a new timestamped directory and published locally only after the requested version is complete and PDF page counts have been checked. Technical verification also covers page sizes, ordering, embedded fonts and Unicode text against the saved OCR, with reported filtering exceptions. These checks complement inspection of representative rendered pages; they cannot prove that the OCR matches every word of the original.
