Folio Orient
Folio Orient estimates how far to turn a scanned page so its printed text reads upright. A 422 KiB ONNX model reads small patches of type and votes on the quarter-turn. A projection-based estimator then measures fine tilt within ±8°. Both stages run on a CPU. They require a page image and work offline after download.
Try a scan in Folio Straighten
To evaluate your own orientation or OCR pipeline on 120 paired scans, use the reference images, transcriptions and scoring script in Scan Recovery Bench.
Historical Bengali print
On 32 historical Bengali pages from the British Library, Folio Orient selected the wrong reading direction on 52 of its 53 accepted views at the default 0.70 agreement threshold. Tesseract's orientation and script detector accepted 119 of 128 views at confidence 15 and got all 119 right. For scans like these, use Tesseract OSD and review its low-confidence pages. With the same Bengali recognizer on 15 transcribed pages, character error was 61.6% on the displayed scans, 72.1% after Folio correction and 22.8% after OSD correction. The four test poses are repeated observations of each page. British Library source · Bengali specialist, diagnostics and local reader
Check the OCR on a scanned PDF
To check a turn against the print, try the Field notes sample. In the PDF text-layer reviewer, confirm the proposed turn on page 2 and download the corrected PDF. Open that copy in Folio Find, enter North Bridge, and search page 2. The phrase appears in the heading and in the stream-gauge line. Select either result to inspect it on the scan. Review the sample PDF · Open Folio Find
Folio OCR Inspector searches the stored PDF text or reads a printed word from the scan. The bundled ledger shows why the distinction matters. On page 2, searching the text layer finds 875 where the scan reads 124. The offline HTML report shows the original cell beside each result. For a list of names or numbers, the image search reads each selected page once. Install the inspector and try the ledger
Compare a scan before and after fresh OCR, including when a search hit disappears or the two PDFs use different page numbers. The offline viewer shows the print and stored words side by side. Read the Bear River Canal example
For a PDF with sideways or stale hidden text, inspect the stored glyph directions page by page and compare flagged locations with the scan. PDF text-layer review and field-notes example
For handwritten registers, the manuscript checkpoint includes examples of an accepted turn and a sparse page that needs review. Folio Orient for manuscripts
Install and rotate an image
The wheel includes the rotation and reflection models. Install it in your Python environment, then give the CLI a scan and a new output path.
With the Hugging Face CLI (hf) installed, download the model configuration and wheel installer. The installer reads the pinned wheel revision from config.json and pip checks its SHA-256 digest. For pip without the Hub CLI, use the versioned wheel.
hf download foliokestrel/folio-orient config.json install_wheel.py --local-dir folio-orient-install
python folio-orient-install/install_wheel.py
folio-orient scan.jpg --output upright.png
For a source checkout with a bundled sample scan, run the following commands.
python -m pip install huggingface_hub
hf download foliokestrel/folio-orient --local-dir folio-orient
cd folio-orient
python -m pip install -r requirements.txt
python folio_orient.py examples/scan.jpg --output upright.png
The example takes a 90° clockwise turn followed by about 3° clockwise of fine correction. Replace the input with your scan. Use --no-deskew for quarter-turns only. --fast first reads up to eight patches at one scale and falls back to the full scan when the vote is weak. Python callers can set fast=True on estimate().
from PIL import Image
from folio_orient import PageOrienter, correct
orienter = PageOrienter() # Reuse the session across pages.
with Image.open("scan.jpg") as page:
estimate = orienter.estimate(page)
print(estimate)
upright = correct(page, estimate)
upright.save("corrected.png")
| Output | Interpretation |
|---|---|
quarter_turn_cw |
Clockwise correction in degrees, one of 0, 90, 180 or 270. A null value means the patch selector found too little signal. |
deskew_cw |
Signed clockwise correction after the quarter-turn. A null value means fine tilt was skipped or had an ambiguous peak. |
agreement |
Mean patch softmax score for the winning turn, on a 0–1 scale. Treat it as a ranking score. |
patches |
Number of image patches contributing to the vote, up to 24. |
The CLI and correct() apply the two rotations when the quarter-turn score reaches 0.70. Below that threshold the output keeps the input's visible orientation. The CLI includes the decision in its accepted field. Adjust the threshold with --min-agreement or the min_agreement argument to correct(). Preview faint print, illustrations and unusual layouts before applying corrections in bulk.
Recover mirrored print
For backwards text, use the separate eight-way classifier. It estimates whether to flip the visible page left-right and how far to turn it afterward. Run it without an output path to see the proposed operation and agreement score.
folio-orient-reflect scan.tif
folio-orient-reflect scan.tif --output restored.png
The default 0.90 cutoff favors manual review. At the optional --min-agreement 0.70 setting, all 2,496 accepted transforms were correct across 4,080 views of printed books, newspapers and contemporary PDFs. The same setting accepted only nine of 205 assigned views of typewritten Dutch radio bulletins and made one incorrect flip. Reflection results, limitations and Python API
For typewritten scans, the optional typewriter checkpoint accepted more corrections on Dutch radio bulletins and French archival pages. It uses the same CLI and requires a separate 423 KiB download. Typewriter checkpoint and evaluation
Rotate a multipage PDF
Install the optional PDF dependency and inspect the suggested quarter-turn for each page. The command prints one JSON object per page, including the existing PDF rotation, the suggested correction, and the acceptance decision.
python -m pip install pypdfium2
folio-orient-pdf scanned-volume.pdf
folio-orient-pdf scanned-volume.pdf --output corrected-volume.pdf
With --output, the helper renders a preview to estimate orientation and updates the PDF page rotation for accepted pages. The result retains embedded images and selectable text. PDF page rotation works in multiples of 90°. For fine tilt, use the image workflow above.
Measured performance
Each source page was tested at all four quarter-turns, with and without an additional tilt. Counts below treat those as eight related views per page. An accepted view met the default 0.70 score threshold.
| Source | Printed pages | Views | Default mode, correct / accepted | Fast mode, correct / accepted |
|---|---|---|---|---|
| Historical book scans, six volumes | 68 | 544 | 526 / 526 | 526 / 526 |
| Contemporary PDFs, six categories | 139 | 1,112 | 900 / 906 | 911 / 917 |
Both modes sent all 224 views of 28 historical plates, covers or blank/show-through pages to review. The contemporary failures came from two patent pages, one with Korean text and diagrams and one dominated by formulas. In the default mode on the 139 PDFs, the median single-thread CPU time for a quarter-turn estimate was 76 ms. Fast mode reduced it to 22 ms, with a 97 ms 95th percentile because uncertain pages also need the full pass.
OCR after correction. We tested Tesseract 5.5.4 on 67 historical pages with reference transcriptions. On one rotated and tilted view per page, corpus character error rate was 47.81% with default OCR, 21.83% with Tesseract’s built-in orientation detection, and 6.41% after Folio correction followed by default OCR. On the original scans it was 4.72%. We chose paper-colored padding after investigating empty OCR on gray-paper pages in this same set. These measurements describe this archive and OCR configuration. Evaluation methods, limitations and per-page results
With the model and settings fixed, we tested a second archive of 48 Finnish newspaper pages. All 48 quarter-turns were correct. Tesseract corpus character error was 72.98% on the rotated and tilted inputs, 34.70% after correction with white padding, 28.80% with paper-colored padding, and 25.95% on the original scans. Matching the paper color recovered all nine empty OCR results. Individual pages varied, with 23 better, 24 worse and one tied versus white. Newspaper study and per-page counts
When to review a page
Folio Orient was trained on horizontal Latin-script print. Inspect handwriting, sparse pages, formulas, and other scripts. The score measures patch agreement and can be high even for an incorrect proposal. Fine deskew assumes parallel text lines. Page curvature and perspective distortion need other methods.
How it works
- Apply EXIF orientation, composite transparency on white, and make two grayscale previews with target long edges of 900 and 1,600 pixels. Upscaling is capped at 2×.
- At each scale, sample 96 × 96 patches on a grid. Favor patches with contrast and ink gradients along both axes. Keep at most 12 across different parts of the page.
- Standardize each patch, run the eight-layer convolutional network, and average the four-class softmax vectors. Logit indices correspond to the clockwise correction
[0, 90, 180, 270]. The ONNX inputpatcheshas shape[N, 1, 96, 96]and dtype float32. The outputlogitshas shape[N, 4]. - For fine tilt, score candidate angles by how sharply the ink aligns into text lines. The image helper uses an exact transpose for quarter-turns and expands the output canvas for fine rotations. Exposed corners use the median color along the source edge, which avoids a bright frame around gray paper. Pass
fillcolor="white"tocorrect()to select white padding.
Reproduce training and evaluation
The training script renders original procedural text with 13 open font families from a pinned Google Fonts revision. It draws 8,192 texture tiles, holds out 256, and trains for 3,000 AdamW steps with batches of 192. Augmentations include quarter-turns, small tilt, blur/downsampling, changes in stroke width, inversion and noise. Fonts are downloaded with their SIL Open Font Licenses. Font source revision
# Install PyTorch with CUDA support in a private environment for training.
python -m pip install -r requirements.txt torch onnx
python training/synthetic.py tiles.npy --font-dir fonts
python training/train.py tiles.npy checkpoint
python training/export.py checkpoint/weights.pt rebuilt.onnx
# Evaluation needs only the inference dependencies and the public scan download.
python evaluation/sample_scans.py scans
python evaluation/evaluate.py scans model.onnx predictions.json
python evaluation/measure_skew.py skew.json
# Optional single-threaded comparison with the pinned Paddle ONNX conversion.
python -m pip install opencv-python-headless
OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 python evaluation/compare.py scans comparison.json
Credits and license
Folio Kestrel releases the model, wheel and original code under Apache 2.0. The example comes from Cuvier and Valenciennes, Histoire naturelle des poissons, volume 10 (1835), supplied by Harvard’s Ernst Mayr Library and digitized by BHL. BHL records the volume as public domain. We converted the sample to grayscale, resized it, and added a known tilt and quarter-turn. IMPACT / BHL produced the CC BY 3.0 transcriptions used in evaluation, distributed by FineBooks. Original scan · BHL item · IMPACT ground truth
- Downloads last month
- 55
