diff --git a/AGENTS.md b/AGENTS.md index 2a59b58..65c5f95 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -83,6 +83,7 @@ tetrak-ocr backends # what is installed, and what each tetrak-ocr ocr --backend tesseract-auto tetrak-ocr batch --backend auto-local # workspace/: scans/ → processed/, failures to triage/ tetrak-ocr evaluate --all --save # → evaluation/ocr/benchmark.{csv,md} + runs/ +python -m evaluation.ocr.reading_order --save # → evaluation/ocr/reading_order.{csv,md}: column-aware order vs a positioned layer's pytest -m "not slow" # the fast loop; what CI gates on pytest # adds the corpus-backed threshold tests @@ -122,6 +123,15 @@ uniformity is what lets `registry.py`, the batch pipeline and the harness treat backends interchangeably; a backend that needs a different signature needs an adapter, not a special case in the callers. +**A backend that computes boxes returns them inside that string.** `vision`, +`easyocr`, `easyocr-hy` and `paddle` return `layout.Transcript`, a `str` +subclass carrying one `TextSpan` per recognised region -- pixels from the +top-left corner, in the engine's own order; the others return a plain `str`. +Callers take the geometry with `layout.spans_of(text)`, which gives `None` +for a plain string, and `batch` and `cli` hand it to every output writer as +the `spans` and `page_spans` options. Take the spans off before any string +operation: `.strip()` and `join` return a plain `str` and lose them. + **Missing extras raise `MissingBackendError`, not `ImportError`.** Each backend module sets `_IMPORT_OK` rather than exiting at import time, so the registry can report which extra to install. Keep that pattern when adding a backend — diff --git a/docs/guide/python-api.md b/docs/guide/python-api.md index 8bbb222..e681aac 100644 --- a/docs/guide/python-api.md +++ b/docs/guide/python-api.md @@ -104,6 +104,35 @@ ocr = build_ocr_fn("tesseract-auto", contrast=3.0) # auto PSM, your contrast ocr = build_ocr_fn("auto-local", with_paddle_vl=True) ``` +## Positioned spans + +Four backends -- `vision`, `easyocr`, `easyocr-hy` and `paddle` -- know where +each recognised region sits on the page. They return the same string as +before, but as `tetrak_ocr.layout.Transcript`, a `str` subclass carrying one +`TextSpan` per region: the text, its box as `(left, top, right, bottom)` in +pixels from the top-left corner, and the engine's confidence on a 0-100 +scale. Take them off with `spans_of`, which returns `None` for a backend that +has none: + +```python +from pathlib import Path +from tetrak_ocr.layout import reading_order, spans_of +from tetrak_ocr.registry import get_backend + +text = get_backend("easyocr")(Path("scan.jpg")) +spans = spans_of(text) # a list of TextSpan, or None for marker, claude and tesseract +if spans: + for span in reading_order(spans): + print(span.bbox, span.text) +``` + +The spans are in the engine's own order; `reading_order` arranges them as a +person reads the page, column by column. Any string operation on the +transcript returns a plain `str`, so take the spans off before stripping or +joining it. `auto-local` returns the winning backend's transcript whole, spans +included. The output writers receive them as the `spans` and `page_spans` +options; the text and PDF formats ignore them. + ## Fan-out and the quality gate `auto-local` runs every eligible local engine on a file, scores each diff --git a/evaluation/ocr/__init__.py b/evaluation/ocr/__init__.py index 4b2302e..4c663fb 100644 --- a/evaluation/ocr/__init__.py +++ b/evaluation/ocr/__init__.py @@ -3,4 +3,8 @@ `harness.py` scores every installed backend over `corpus/images/` against the reference transcripts in `corpus/expected/`, and writes `benchmark.csv`, which the documentation site reads at build time. + +`reading_order.py` scores the column-aware ordering of each span-carrying +backend's regions against the line order a positioned layer reads back as, +on the same fixtures, and writes `reading_order.csv` for the site likewise. """ diff --git a/evaluation/ocr/reading_order.csv b/evaluation/ocr/reading_order.csv new file mode 100644 index 0000000..e063c11 --- /dev/null +++ b/evaluation/ocr/reading_order.csv @@ -0,0 +1,55 @@ +fixture,backend,layout,engine_chr,engine_wrd,linesort_chr,linesort_wrd,column_chr,column_wrd,transcript_chr,transcript_wrd +inside-facts-1930-cover,vision,multi-column,0.5810,0.8331,0.4570,0.8331,0.4570,0.8331,0.4354,0.8219 +inside-facts-1930-page-six,vision,multi-column,0.3065,0.8431,0.3089,0.8431,0.6647,0.8431,0.6016,0.8396 +kinema-theater-ad-1920,vision,multi-column,0.9519,0.8856,0.4191,0.8856,0.8799,0.8856,0.8386,0.8686 +mean,vision,multi-column,0.6131,0.8540,0.3950,0.8540,0.6672,0.8540,0.6252,0.8434 +bancroft-magician-poster,vision,single-column,0.7442,0.5000,0.6744,0.5000,0.6744,0.5000,0.6744,0.5000 +carthay-circle-postcard-back,vision,single-column,0.8976,0.8333,0.9606,0.8333,0.6850,0.8333,0.6850,0.8333 +carthay-circle-premiere,vision,single-column,0.8715,0.8571,0.8715,0.8571,0.8715,0.8571,0.8715,0.8571 +chinese-theatre-triptych-postcard,vision,single-column,0.8936,1.0000,0.7064,1.0000,0.6298,1.0000,0.6298,1.0000 +graumans-chinese-theatre,vision,single-column,0.7342,0.3750,0.7342,0.3750,0.7342,0.3750,0.7342,0.3750 +greek-theatre-night,vision,single-column,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000,0.0000 +hollywood-boulevard-east,vision,single-column,0.7232,0.3889,0.7232,0.3889,0.7232,0.3889,0.7232,0.3889 +hollywood-boulevard-west,vision,single-column,0.5981,0.4333,0.5981,0.4333,0.5483,0.4333,0.5483,0.4333 +hollywood-music-box-playbill-1926,vision,single-column,0.7219,0.7655,0.7400,0.7655,0.7400,0.7655,0.7077,0.7655 +kar-mi-troupe-poster,vision,single-column,0.3082,0.3961,0.2949,0.3961,0.2829,0.3961,0.2802,0.3961 +over-the-fence-poster,vision,single-column,0.4725,0.3182,0.4725,0.3182,0.4725,0.3182,0.4725,0.3182 +parlor-match-poster,vision,single-column,0.7139,0.7188,0.8215,0.7188,0.8215,0.7188,0.8215,0.7188 +thurston-magician-poster,vision,single-column,0.7402,0.6296,0.6762,0.6296,0.6263,0.6296,0.6263,0.6296 +mean,vision,single-column,0.6476,0.5551,0.6364,0.5551,0.6007,0.5551,0.5981,0.5551 +inside-facts-1930-cover,easyocr,multi-column,0.4130,0.7080,0.4111,0.7080,0.7762,0.7080,0.4130,0.7080 +inside-facts-1930-page-six,easyocr,multi-column,0.3013,0.7778,0.2978,0.7778,0.7026,0.7778,0.3013,0.7778 +kinema-theater-ad-1920,easyocr,multi-column,0.4175,0.6653,0.4342,0.6653,0.7902,0.6653,0.4175,0.6653 +mean,easyocr,multi-column,0.3773,0.7170,0.3810,0.7170,0.7563,0.7170,0.3773,0.7170 +bancroft-magician-poster,easyocr,single-column,0.3970,0.1364,0.5094,0.1364,0.5393,0.1364,0.3970,0.1364 +carthay-circle-postcard-back,easyocr,single-column,0.7860,0.6250,0.7773,0.6250,0.7686,0.6250,0.7860,0.6250 +carthay-circle-premiere,easyocr,single-column,0.8701,0.7143,0.8701,0.7143,0.8701,0.7143,0.8701,0.7143 +chinese-theatre-triptych-postcard,easyocr,single-column,0.5044,0.6667,0.7080,0.6667,0.5310,0.6667,0.5044,0.6667 +graumans-chinese-theatre,easyocr,single-column,0.7168,0.5000,0.8439,0.5000,0.8439,0.5000,0.7168,0.5000 +greek-theatre-night,easyocr,single-column,0.9486,0.7500,0.8800,0.7500,0.9486,0.7500,0.9486,0.7500 +hollywood-boulevard-east,easyocr,single-column,0.7240,0.4444,0.7240,0.4444,0.7240,0.4444,0.7240,0.4444 +hollywood-boulevard-west,easyocr,single-column,0.5660,0.3000,0.5660,0.3000,0.4654,0.3000,0.5660,0.3000 +hollywood-music-box-playbill-1926,easyocr,single-column,0.5032,0.3948,0.4974,0.3948,0.4974,0.3948,0.5032,0.3948 +kar-mi-troupe-poster,easyocr,single-column,0.1239,0.3913,0.2529,0.3913,0.2401,0.3913,0.1239,0.3913 +over-the-fence-poster,easyocr,single-column,0.4896,0.2273,0.4896,0.2273,0.4896,0.2273,0.4896,0.2273 +parlor-match-poster,easyocr,single-column,0.6687,0.4375,0.6505,0.4375,0.4802,0.4375,0.6687,0.4375 +thurston-magician-poster,easyocr,single-column,0.7353,0.5185,0.6691,0.5185,0.6691,0.5185,0.7353,0.5185 +mean,easyocr,single-column,0.6180,0.4697,0.6491,0.4697,0.6206,0.4697,0.6180,0.4697 +inside-facts-1930-cover,paddle,multi-column,0.5009,0.9414,0.4849,0.9414,0.8435,0.9414,0.5009,0.9414 +inside-facts-1930-page-six,paddle,multi-column,0.2953,0.9693,0.2751,0.9693,0.8063,0.9693,0.2953,0.9693 +kinema-theater-ad-1920,paddle,multi-column,0.4907,0.9280,0.4509,0.9280,0.7336,0.9280,0.4907,0.9280 +mean,paddle,multi-column,0.4290,0.9462,0.4036,0.9462,0.7945,0.9462,0.4290,0.9462 +bancroft-magician-poster,paddle,single-column,0.5467,0.3182,0.5467,0.3182,0.6574,0.3182,0.5467,0.3182 +carthay-circle-postcard-back,paddle,single-column,0.2844,0.6250,0.2844,0.6250,0.2844,0.6250,0.2844,0.6250 +carthay-circle-premiere,paddle,single-column,0.0885,0.0000,0.0885,0.0000,0.0885,0.0000,0.0885,0.0000 +chinese-theatre-triptych-postcard,paddle,single-column,0.7850,0.7333,0.7196,0.7333,0.5421,0.7333,0.7850,0.7333 +graumans-chinese-theatre,paddle,single-column,0.7386,0.1875,0.6477,0.1875,0.7273,0.1875,0.7386,0.1875 +greek-theatre-night,paddle,single-column,0.9114,0.5000,0.9114,0.5000,0.9114,0.5000,0.9114,0.5000 +hollywood-boulevard-east,paddle,single-column,0.6352,0.4444,0.6352,0.4444,0.6524,0.4444,0.6352,0.4444 +hollywood-boulevard-west,paddle,single-column,0.5759,0.4333,0.5882,0.4333,0.5882,0.4333,0.5759,0.4333 +hollywood-music-box-playbill-1926,paddle,single-column,0.7777,0.9086,0.9003,0.9086,0.9003,0.9086,0.7777,0.9086 +kar-mi-troupe-poster,paddle,single-column,0.2741,0.3816,0.2927,0.3816,0.2582,0.3816,0.2741,0.3816 +over-the-fence-poster,paddle,single-column,0.6355,0.4545,0.6075,0.4545,0.5047,0.4545,0.6355,0.4545 +parlor-match-poster,paddle,single-column,0.6806,0.3125,0.7582,0.3125,0.7582,0.3125,0.6806,0.3125 +thurston-magician-poster,paddle,single-column,0.7372,0.4444,0.6788,0.4444,0.6715,0.4444,0.7372,0.4444 +mean,paddle,single-column,0.5901,0.4418,0.5892,0.4418,0.5803,0.4418,0.5901,0.4418 diff --git a/evaluation/ocr/reading_order.md b/evaluation/ocr/reading_order.md new file mode 100644 index 0000000..51e7169 --- /dev/null +++ b/evaluation/ocr/reading_order.md @@ -0,0 +1,87 @@ +# Reading order of positioned output + +Generated by `python -m evaluation.ocr.reading_order --save`. Do not edit. + +The same spans serialised four ways and scored against the ground +truth: character similarity / word recall. `engine` is the order the +engine reported, `linesort` is lines top to bottom with no column +awareness (what a word-positioned layer reads back as), `column` is +`layout.reading_order`, and `transcript` is what `ocr_image` returns. +Word recall must not move between the first three. + +## Multi-column fixtures, mean per backend + +| Backend | engine | linesort | column | transcript | +|---|---:|---:|---:|---:| +| `vision` | 0.613 / 0.854 | 0.395 / 0.854 | 0.667 / 0.854 | 0.625 / 0.843 | +| `easyocr` | 0.377 / 0.717 | 0.381 / 0.717 | 0.756 / 0.717 | 0.377 / 0.717 | +| `paddle` | 0.429 / 0.946 | 0.404 / 0.946 | 0.794 / 0.946 | 0.429 / 0.946 | + +## vision + +| Fixture | engine | linesort | column | transcript | +|---|---:|---:|---:|---:| +| `inside-facts-1930-cover` | 0.581 / 0.833 | 0.457 / 0.833 | 0.457 / 0.833 | 0.435 / 0.822 | +| `inside-facts-1930-page-six` | 0.306 / 0.843 | 0.309 / 0.843 | 0.665 / 0.843 | 0.602 / 0.840 | +| `kinema-theater-ad-1920` | 0.952 / 0.886 | 0.419 / 0.886 | 0.880 / 0.886 | 0.839 / 0.869 | +| *mean, multi-column* | 0.613 / 0.854 | 0.395 / 0.854 | 0.667 / 0.854 | 0.625 / 0.843 | +| `bancroft-magician-poster` | 0.744 / 0.500 | 0.674 / 0.500 | 0.674 / 0.500 | 0.674 / 0.500 | +| `carthay-circle-postcard-back` | 0.898 / 0.833 | 0.961 / 0.833 | 0.685 / 0.833 | 0.685 / 0.833 | +| `carthay-circle-premiere` | 0.872 / 0.857 | 0.872 / 0.857 | 0.872 / 0.857 | 0.872 / 0.857 | +| `chinese-theatre-triptych-postcard` | 0.894 / 1.000 | 0.706 / 1.000 | 0.630 / 1.000 | 0.630 / 1.000 | +| `graumans-chinese-theatre` | 0.734 / 0.375 | 0.734 / 0.375 | 0.734 / 0.375 | 0.734 / 0.375 | +| `greek-theatre-night` | 0.000 / 0.000 | 0.000 / 0.000 | 0.000 / 0.000 | 0.000 / 0.000 | +| `hollywood-boulevard-east` | 0.723 / 0.389 | 0.723 / 0.389 | 0.723 / 0.389 | 0.723 / 0.389 | +| `hollywood-boulevard-west` | 0.598 / 0.433 | 0.598 / 0.433 | 0.548 / 0.433 | 0.548 / 0.433 | +| `hollywood-music-box-playbill-1926` | 0.722 / 0.766 | 0.740 / 0.766 | 0.740 / 0.766 | 0.708 / 0.766 | +| `kar-mi-troupe-poster` | 0.308 / 0.396 | 0.295 / 0.396 | 0.283 / 0.396 | 0.280 / 0.396 | +| `over-the-fence-poster` | 0.473 / 0.318 | 0.473 / 0.318 | 0.473 / 0.318 | 0.473 / 0.318 | +| `parlor-match-poster` | 0.714 / 0.719 | 0.822 / 0.719 | 0.822 / 0.719 | 0.822 / 0.719 | +| `thurston-magician-poster` | 0.740 / 0.630 | 0.676 / 0.630 | 0.626 / 0.630 | 0.626 / 0.630 | +| *mean, single-column* | 0.648 / 0.555 | 0.636 / 0.555 | 0.601 / 0.555 | 0.598 / 0.555 | + +## easyocr + +| Fixture | engine | linesort | column | transcript | +|---|---:|---:|---:|---:| +| `inside-facts-1930-cover` | 0.413 / 0.708 | 0.411 / 0.708 | 0.776 / 0.708 | 0.413 / 0.708 | +| `inside-facts-1930-page-six` | 0.301 / 0.778 | 0.298 / 0.778 | 0.703 / 0.778 | 0.301 / 0.778 | +| `kinema-theater-ad-1920` | 0.418 / 0.665 | 0.434 / 0.665 | 0.790 / 0.665 | 0.418 / 0.665 | +| *mean, multi-column* | 0.377 / 0.717 | 0.381 / 0.717 | 0.756 / 0.717 | 0.377 / 0.717 | +| `bancroft-magician-poster` | 0.397 / 0.136 | 0.509 / 0.136 | 0.539 / 0.136 | 0.397 / 0.136 | +| `carthay-circle-postcard-back` | 0.786 / 0.625 | 0.777 / 0.625 | 0.769 / 0.625 | 0.786 / 0.625 | +| `carthay-circle-premiere` | 0.870 / 0.714 | 0.870 / 0.714 | 0.870 / 0.714 | 0.870 / 0.714 | +| `chinese-theatre-triptych-postcard` | 0.504 / 0.667 | 0.708 / 0.667 | 0.531 / 0.667 | 0.504 / 0.667 | +| `graumans-chinese-theatre` | 0.717 / 0.500 | 0.844 / 0.500 | 0.844 / 0.500 | 0.717 / 0.500 | +| `greek-theatre-night` | 0.949 / 0.750 | 0.880 / 0.750 | 0.949 / 0.750 | 0.949 / 0.750 | +| `hollywood-boulevard-east` | 0.724 / 0.444 | 0.724 / 0.444 | 0.724 / 0.444 | 0.724 / 0.444 | +| `hollywood-boulevard-west` | 0.566 / 0.300 | 0.566 / 0.300 | 0.465 / 0.300 | 0.566 / 0.300 | +| `hollywood-music-box-playbill-1926` | 0.503 / 0.395 | 0.497 / 0.395 | 0.497 / 0.395 | 0.503 / 0.395 | +| `kar-mi-troupe-poster` | 0.124 / 0.391 | 0.253 / 0.391 | 0.240 / 0.391 | 0.124 / 0.391 | +| `over-the-fence-poster` | 0.490 / 0.227 | 0.490 / 0.227 | 0.490 / 0.227 | 0.490 / 0.227 | +| `parlor-match-poster` | 0.669 / 0.438 | 0.650 / 0.438 | 0.480 / 0.438 | 0.669 / 0.438 | +| `thurston-magician-poster` | 0.735 / 0.519 | 0.669 / 0.519 | 0.669 / 0.519 | 0.735 / 0.519 | +| *mean, single-column* | 0.618 / 0.470 | 0.649 / 0.470 | 0.621 / 0.470 | 0.618 / 0.470 | + +## paddle + +| Fixture | engine | linesort | column | transcript | +|---|---:|---:|---:|---:| +| `inside-facts-1930-cover` | 0.501 / 0.941 | 0.485 / 0.941 | 0.844 / 0.941 | 0.501 / 0.941 | +| `inside-facts-1930-page-six` | 0.295 / 0.969 | 0.275 / 0.969 | 0.806 / 0.969 | 0.295 / 0.969 | +| `kinema-theater-ad-1920` | 0.491 / 0.928 | 0.451 / 0.928 | 0.734 / 0.928 | 0.491 / 0.928 | +| *mean, multi-column* | 0.429 / 0.946 | 0.404 / 0.946 | 0.794 / 0.946 | 0.429 / 0.946 | +| `bancroft-magician-poster` | 0.547 / 0.318 | 0.547 / 0.318 | 0.657 / 0.318 | 0.547 / 0.318 | +| `carthay-circle-postcard-back` | 0.284 / 0.625 | 0.284 / 0.625 | 0.284 / 0.625 | 0.284 / 0.625 | +| `carthay-circle-premiere` | 0.088 / 0.000 | 0.088 / 0.000 | 0.088 / 0.000 | 0.088 / 0.000 | +| `chinese-theatre-triptych-postcard` | 0.785 / 0.733 | 0.720 / 0.733 | 0.542 / 0.733 | 0.785 / 0.733 | +| `graumans-chinese-theatre` | 0.739 / 0.188 | 0.648 / 0.188 | 0.727 / 0.188 | 0.739 / 0.188 | +| `greek-theatre-night` | 0.911 / 0.500 | 0.911 / 0.500 | 0.911 / 0.500 | 0.911 / 0.500 | +| `hollywood-boulevard-east` | 0.635 / 0.444 | 0.635 / 0.444 | 0.652 / 0.444 | 0.635 / 0.444 | +| `hollywood-boulevard-west` | 0.576 / 0.433 | 0.588 / 0.433 | 0.588 / 0.433 | 0.576 / 0.433 | +| `hollywood-music-box-playbill-1926` | 0.778 / 0.909 | 0.900 / 0.909 | 0.900 / 0.909 | 0.778 / 0.909 | +| `kar-mi-troupe-poster` | 0.274 / 0.382 | 0.293 / 0.382 | 0.258 / 0.382 | 0.274 / 0.382 | +| `over-the-fence-poster` | 0.636 / 0.455 | 0.607 / 0.455 | 0.505 / 0.455 | 0.636 / 0.455 | +| `parlor-match-poster` | 0.681 / 0.312 | 0.758 / 0.312 | 0.758 / 0.312 | 0.681 / 0.312 | +| `thurston-magician-poster` | 0.737 / 0.444 | 0.679 / 0.444 | 0.672 / 0.444 | 0.737 / 0.444 | +| *mean, single-column* | 0.590 / 0.442 | 0.589 / 0.442 | 0.580 / 0.442 | 0.590 / 0.442 | diff --git a/evaluation/ocr/reading_order.py b/evaluation/ocr/reading_order.py new file mode 100644 index 0000000..7f4d7aa --- /dev/null +++ b/evaluation/ocr/reading_order.py @@ -0,0 +1,297 @@ +#!/usr/bin/env python3 +"""Score the column-aware reading order a positioned output would carry. + +Brief 008 built a word-positioned text layer for the searchable PDF, +measured it and dropped it: on the two *Inside Facts* newsprint pages it +cost about 0.27 character similarity against the plain transcript, because +a layer laid down word by word reads back top to bottom across the page +and interleaves the columns. The figures are in the docstring of +:mod:`tetrak_ocr.pdf_output`. ALTO and hOCR are positioned by definition, +so before either is written the question is whether the column-aware pass +in :mod:`tetrak_ocr.layout` closes that gap. This harness answers it. + +For every backend that carries spans and every raster fixture, the *same* +spans are serialised four ways and each is scored against the ground truth +in ``evaluation/ocr/corpus/expected/``: + + engine the regions in the order the engine reported them -- the + floor, and the only order a backend has without layout + linesort visual lines top to bottom and left to right, with no + column awareness: what a word-positioned layer reads back + as, and the construction brief 008 measured + column ``layout.reading_order`` -- recursive XY-cut, the pass a + positioned writer would apply before emitting its regions + transcript what ``ocr_image`` returns today: the plain-text output. + For ``vision`` that is already column-ordered and + de-hyphenated; for ``easyocr`` and ``paddle`` it is engine + order, so those two columns coincide + +Two metrics, and the pairing is the point. Character similarity is +order-sensitive and is what reading order exists to move. Word recall is +order-insensitive and must be **identical** across the first three +serialisations, which emit the same tokens in a different sequence; a +column that moves it is losing or duplicating text, not reordering it. It +is printed beside every score as that tripwire. The transcript column may +differ by de-hyphenation, which puts words back. + +Fixtures are the raster corpus: the three span-carrying backends read no +PDFs, so the newsprint PDFs cannot be measured here. The multi-column +fixtures are named in :data:`MULTI_COLUMN`; the rest are the control, where +a column-aware pass has nothing to find and must change nothing. + +Usage: + python -m evaluation.ocr.reading_order # measure, print + python -m evaluation.ocr.reading_order --save # write reading_order.{csv,md} + python -m evaluation.ocr.reading_order --backend paddle --fixture kinema-theater-ad-1920 + +Writes ``evaluation/ocr/reading_order.csv``, which the site renders through +the ``{{< reading-order >}}`` shortcode, and a Markdown summary beside it. +It does not touch ``evaluation/ocr/runs/``: that directory is the +benchmark's versioned history and the product ledger is built from it. +""" + +from __future__ import annotations + +import argparse +import csv +import statistics +import sys +from collections.abc import Callable +from pathlib import Path + +from tetrak_ocr.accuracy import character_similarity, word_recall +from tetrak_ocr.layout import TextSpan, group_lines, reading_order, spans_of +from tetrak_ocr.registry import get_backend, is_available + +from .harness import EVAL_DIR, available_pairs + +RESULTS_CSV = EVAL_DIR / "reading_order.csv" +RESULTS_MD = EVAL_DIR / "reading_order.md" + +# The backends whose ocr_image returns a Transcript carrying spans, and read +# the corpus's language. `easyocr-hy` carries spans too, but it is the +# Armenian recogniser and these fixtures are English: it would measure the +# ordering of text it cannot read. +SPAN_BACKENDS: tuple[str, ...] = ("vision", "easyocr", "paddle") + +# The raster fixtures with more than one column of text, by inspection. +# Everything else in the raster corpus -- postcards, posters, the playbill, +# which is one centred column with dot-leader cast lists -- is the control. +MULTI_COLUMN: frozenset[str] = frozenset( + { + # Dense newsprint: a masthead over classified-style column blocks. + "inside-facts-1930-cover", + # The same issue's inside page: running columns of trade news. + "inside-facts-1930-page-six", + # A display ad: a narrow programme column in small type beside the + # headline block, with prose fragments set around the illustration. + "kinema-theater-ad-1920", + } +) + +STRATEGIES: dict[str, Callable[[list[TextSpan]], str]] = { + "engine": lambda spans: "\n".join(span.text for span in spans), + "linesort": lambda spans: "\n".join( + " ".join(span.text for span in line) for line in group_lines(spans) + ), + "column": lambda spans: " ".join(span.text for span in reading_order(spans)), +} +# Scored alongside the three above, from the text rather than the spans. +TRANSCRIPT = "transcript" +COLUMNS: tuple[str, ...] = (*STRATEGIES, TRANSCRIPT) +LAYOUTS: tuple[str, ...] = ("multi-column", "single-column") +MEAN = "mean" + +FIELDNAMES: tuple[str, ...] = ( + "fixture", + "backend", + "layout", + *(f"{name}_{metric}" for name in COLUMNS for metric in ("chr", "wrd")), +) + + +def layout_of(stem: str) -> str: + return "multi-column" if stem in MULTI_COLUMN else "single-column" + + +def raster_pairs() -> list[tuple[Path, Path]]: + """Every corpus fixture the span-carrying backends can read: no PDFs.""" + return [(image, expected) for image, expected in available_pairs() if image.suffix != ".pdf"] + + +def score(spans: list[TextSpan], transcript: str, expected: str) -> dict[str, float]: + """Both metrics for every serialisation of one page's spans.""" + texts = {name: strategy(spans) for name, strategy in STRATEGIES.items()} + texts[TRANSCRIPT] = transcript + scores: dict[str, float] = {} + for name, text in texts.items(): + scores[f"{name}_chr"] = character_similarity(text, expected) + scores[f"{name}_wrd"] = word_recall(text, expected) + return scores + + +def measure( + pairs: list[tuple[Path, Path]], backends: tuple[str, ...] | list[str] +) -> list[dict[str, object]]: + """Run each backend over each fixture and score every serialisation.""" + rows: list[dict[str, object]] = [] + for backend in backends: + if not is_available(backend): + print(f" {backend}: not installed, skipped", file=sys.stderr) + continue + ocr = get_backend(backend) + for image, expected_path in pairs: + print(f" {backend:<8} {image.name}", end=" ", flush=True) + transcript = ocr(image) + spans = spans_of(transcript) + if spans is None: + print("-- no spans, skipped") + continue + expected = expected_path.read_text(encoding="utf-8") + scores = score(spans, transcript, expected) + print(f"column {scores['column_chr']:.3f} vs linesort {scores['linesort_chr']:.3f}") + rows.append( + {"fixture": image.stem, "backend": backend, "layout": layout_of(image.stem)} + | scores + ) + return rows + + +def with_means(rows: list[dict[str, object]]) -> list[dict[str, object]]: + """*rows* with a mean row per backend and layout appended after its group. + + The means are computed here and written out, rather than left to the + site to derive: the page then holds no arithmetic, only the CSV's cells. + """ + out: list[dict[str, object]] = [] + for backend in dict.fromkeys(str(row["backend"]) for row in rows): + for layout in LAYOUTS: + group = [row for row in rows if row["backend"] == backend and row["layout"] == layout] + if not group: + continue + out.extend(sorted(group, key=lambda row: str(row["fixture"]))) + out.append( + {"fixture": MEAN, "backend": backend, "layout": layout} + | { + key: statistics.fmean(float(row[key]) for row in group) + for key in FIELDNAMES[3:] + } + ) + return out + + +def _format(row: dict[str, object]) -> dict[str, str]: + return { + key: f"{value:.4f}" if isinstance(value, float) else str(value) + for key, value in row.items() + } + + +def write(rows: list[dict[str, object]], csv_path: Path, md_path: Path) -> None: + """Write the table as CSV, and a Markdown summary beside it.""" + rows = with_means(rows) + with csv_path.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=FIELDNAMES) + writer.writeheader() + writer.writerows(_format(row) for row in rows) + + def table(selected: list[dict[str, object]], first: str) -> list[str]: + lines = [ + f"| {first} | " + " | ".join(COLUMNS) + " |", + "|---|" + "---:|" * len(COLUMNS), + ] + for row in selected: + label = str(row[first.lower()]) + label = f"*{label}, {row['layout']}*" if label == MEAN else f"`{label}`" + cells = " | ".join( + f"{float(row[f'{name}_chr']):.3f} / {float(row[f'{name}_wrd']):.3f}" + for name in COLUMNS + ) + lines.append(f"| {label} | {cells} |") + return lines + + lines = [ + "# Reading order of positioned output", + "", + "Generated by `python -m evaluation.ocr.reading_order --save`. Do not edit.", + "", + "The same spans serialised four ways and scored against the ground", + "truth: character similarity / word recall. `engine` is the order the", + "engine reported, `linesort` is lines top to bottom with no column", + "awareness (what a word-positioned layer reads back as), `column` is", + "`layout.reading_order`, and `transcript` is what `ocr_image` returns.", + "Word recall must not move between the first three.", + "", + "## Multi-column fixtures, mean per backend", + "", + *table( + [row for row in rows if row["fixture"] == MEAN and row["layout"] == "multi-column"], + "Backend", + ), + ] + for backend in dict.fromkeys(str(row["backend"]) for row in rows): + lines += [ + "", + f"## {backend}", + "", + *table([row for row in rows if row["backend"] == backend], "Fixture"), + ] + md_path.write_text("\n".join(lines) + "\n", encoding="utf-8") + + +def _print(rows: list[dict[str, object]]) -> None: + for backend in dict.fromkeys(str(row["backend"]) for row in rows): + print(f"\n{backend}") + header = f" {'fixture':<36}" + "".join(f"{name:>22}" for name in COLUMNS) + print(header) + print(f" {'':<36}" + "".join(f"{'chr / wrd':>22}" for _ in COLUMNS)) + print(" " + "-" * (len(header) - 2)) + for row in with_means(rows): + if row["backend"] != backend: + continue + label = str(row["fixture"]) + if label == MEAN: + label = f"MEAN {row['layout']}" + cells = "".join( + f"{float(row[f'{name}_chr']):>12.4f} /{float(row[f'{name}_wrd']):>8.4f}" + for name in COLUMNS + ) + print(f" {label:<36}{cells}") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--save", action="store_true", help="write reading_order.csv and .md") + parser.add_argument( + "--backend", action="append", choices=SPAN_BACKENDS, help="only this backend; repeatable" + ) + parser.add_argument("--fixture", action="append", help="only this fixture stem; repeatable") + args = parser.parse_args(argv) + + if args.save and (args.backend or args.fixture): + # A partial table would overwrite the full one and look complete. + print("--save measures everything; drop --backend and --fixture", file=sys.stderr) + return 2 + + pairs = raster_pairs() + if args.fixture: + wanted = {Path(name).stem for name in args.fixture} + pairs = [pair for pair in pairs if pair[0].stem in wanted] + if not pairs: + known = ", ".join(image.stem for image, _ in raster_pairs()) + print(f"no such raster fixture; known: {known}", file=sys.stderr) + return 2 + + rows = measure(pairs, args.backend or SPAN_BACKENDS) + if not rows: + print("nothing measured", file=sys.stderr) + return 1 + _print(rows) + if args.save: + write(rows, RESULTS_CSV, RESULTS_MD) + print(f"\nWrote {RESULTS_CSV.name} and {RESULTS_MD.name}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/site/config/_default/hugo.toml b/site/config/_default/hugo.toml index 58b11ef..658e628 100644 --- a/site/config/_default/hugo.toml +++ b/site/config/_default/hugo.toml @@ -129,6 +129,13 @@ capitalizeListTitles = false source = "../evaluation/ocr/registers.csv" target = "assets/evaluation/registers.csv" + # Read at build time by the {{< reading-order >}} shortcode. Written by + # evaluation/ocr/reading_order.py, which needs the span-carrying engines + # installed, so like registers.csv it is committed rather than recomputed. + [[module.mounts]] + source = "../evaluation/ocr/reading_order.csv" + target = "assets/evaluation/reading_order.csv" + # Pulled into content/licensing.md by {{< include >}}, so the published page # and the file GitHub shows beside the LICENSE cannot drift apart. [[module.mounts]] diff --git a/site/content/research/in-depth.md b/site/content/research/in-depth.md index 1ce68f2..ff72fdc 100644 --- a/site/content/research/in-depth.md +++ b/site/content/research/in-depth.md @@ -160,6 +160,73 @@ full-text search it is adequate. Which number matters depends on whether you are building a reading edition or a search index, and that is your question rather than ours — which is why we never collapse the two into one score. +### Column-aware ordering closes most of that gap + +Brief 008 measured the obvious construction for a positioned text layer — +each word's text laid invisibly over the word — and dropped it from the +searchable PDF. A layer like that reads back top to bottom across the page, +so on the two *Inside Facts* pages it scored a fraction of the plain +transcript. ALTO and hOCR are positioned by definition, which made the next +question whether the column-aware pass in `tetrak_ocr.layout`, built for +two-column Armenian pages, undoes that interleaving on this corpus. + +It was measured on the same boxes rather than by re-running anything. The +engines that compute a box per region — Vision, EasyOCR, PaddleOCR and the +Armenian recogniser — now carry those boxes out with the transcript, and +[`evaluation/ocr/reading_order.py`](https://github.com/scattercode/tetrak/blob/main/evaluation/ocr/reading_order.py) +serialises one set of spans four ways: as the engine reported them, sorted +into lines with no column awareness (what a positioned layer reads back as), +through the column-aware pass, and the plain transcript the backend ships. +Each is scored against the ground truth. Word recall is identical across +the first three by construction, which is the check that the pass reorders +text rather than losing any; it is in the CSV beside every score. + +{{< reading-order >}} + +On the three multi-column fixtures the column-aware order lifts EasyOCR and +PaddleOCR from the line sort's interleaving to the best local reading order +measured on those pages. The `easyocr` and `paddle` columns of the benchmark +above do not show it, because both backends still ship engine order as +their transcript — the gain is available to a positioned writer now, and to +the transcripts as a separate, measured change. + +Vision is the exception, and an instructive one. It groups text before it +returns it, so its engine order is already well ahead of the line sort, and +on the *Inside Facts* cover the pass makes it worse: the cut finds a column +boundary in a masthead that reads straight across. Its transcript column +also trails the column-aware one, because the backend passes its own, +coarser line tolerance rather than the layout module's adaptive default; +that is a second measured change waiting to be made. + +{{< tabs >}} +{{< tab "PaddleOCR" >}} +{{< reading-order view="full" backend="paddle" >}} +{{< /tab >}} +{{< tab "EasyOCR" >}} +{{< reading-order view="full" backend="easyocr" >}} +{{< /tab >}} +{{< tab "Vision" >}} +{{< reading-order view="full" backend="vision" >}} +{{< /tab >}} +{{< /tabs >}} + +The control matters as much as the result. On the single-column fixtures +the pass is close to neutral on average and a little behind the plain line +sort, and on a few pages it costs more than a little: the postcard reverse, +whose message and address sides it reads as columns, and the triptych +postcard, whose three captions it reads down rather than across. Those are +pages with side-by-side regions that are not columns, and a cut that cannot +tell the difference is what would have to change before the pass is applied +to every transcript unconditionally. + +For positioned output the verdict is that the ordering is good enough to +ship. ALTO and hOCR are consumed by coordinate, so the order governs only +the text stream a reader or an indexer extracts, and on the pages where that +order matters the pass gains far more than it loses on the pages where it +does not. A positioned writer should apply it. What the cut needs next is a +guard for pages without columns, measured on the control set here, and that +is the prerequisite for the plain transcripts to take the same route. + ### Tuning beat switching `tesseract-auto` averages 0.41/0.63, ahead of EasyOCR at 0.35/0.60 — a @@ -553,6 +620,10 @@ little else. - **Nothing here generalises beyond archival print** of this era, condition and script. Whether the pipeline works on other scripts is untested — an open Armenian Tesseract model exists and would make the cheapest first experiment. +- **The column-aware pass is measured but not applied to the EasyOCR and + PaddleOCR transcripts.** It would lift both on newsprint and cost a little on + pages with side-by-side regions that are not columns; a guard for those, + scored on the single-column control, is the prerequisite. ## Reproducing all of this diff --git a/site/layouts/partials/reading-order.html b/site/layouts/partials/reading-order.html new file mode 100644 index 0000000..b28b7ce --- /dev/null +++ b/site/layouts/partials/reading-order.html @@ -0,0 +1,142 @@ +{{- /* + The reading-order table, read from evaluation/ocr/reading_order.csv at + build time. + + The harness (evaluation/ocr/reading_order.py) serialises each span-carrying + backend's spans four ways on every raster fixture and scores each against + the ground truth. The research page argues from those figures; it holds + no copy of them, for the reason partials/benchmark.html gives. + + The CSV carries one row per (fixture, backend) and a `mean` row per backend + and layout group, computed by the harness -- so nothing here does + arithmetic, it only selects cells. + + Context: a dict of + view - "summary" (default): a row per backend, the mean over the + multi-column fixtures for each serialisation; or "full", every + fixture for one backend + backend - which backend the full view shows; required there + metric - "chr" (default) or "wrd" + boldBest - false to suppress the best-per-row marking +*/ -}} + +{{- $res := resources.Get "evaluation/reading_order.csv" }} +{{- if not $res }} + {{- errorf "reading-order: evaluation/ocr/reading_order.csv is not mounted -- check [module.mounts] in config/_default/hugo.toml" }} +{{- end }} +{{- $csv := $res.Content | transform.Unmarshal (dict "format" "csv" "delimiter" ",") }} +{{- $header := index $csv 0 }} +{{- $rows := after 1 $csv }} + +{{- $col := dict }} +{{- range $i, $name := $header }} + {{- $col = merge $col (dict $name $i) }} +{{- end }} +{{- $fixture := index $col "fixture" }} +{{- $backendCol := index $col "backend" }} +{{- $layoutCol := index $col "layout" }} + +{{- $metric := .metric | default "chr" }} +{{- if not (in (slice "chr" "wrd") $metric) }} + {{- errorf "reading-order: metric must be \"chr\" or \"wrd\", got %q" $metric }} +{{- end }} +{{- $view := .view | default "summary" }} +{{- if not (in (slice "summary" "full") $view) }} + {{- errorf "reading-order: view must be \"summary\" or \"full\", got %q" $view }} +{{- end }} +{{- $boldBest := ne .boldBest false }} + +{{- /* The serialisations, in the order the harness scores them. */ -}} +{{- $strategies := slice "engine" "linesort" "column" "transcript" }} +{{- $labels := dict "engine" "Engine order" "linesort" "Line sort" "column" "Column-aware" "transcript" "Transcript" }} + +{{- /* The multi-column fixtures, counted rather than written down. */ -}} +{{- $multi := slice }} +{{- range $rows }} + {{- if and (eq (index . $layoutCol) "multi-column") (ne (index . $fixture) "mean") }} + {{- $stem := index . $fixture }} + {{- if not (in $multi $stem) }}{{ $multi = $multi | append $stem }}{{ end }} + {{- end }} +{{- end }} + +{{- /* Which rows this view shows. Decided per row while rendering rather + than collected first: `append` spreads a slice argument, and a row is + a slice of cells, so building a filtered list of rows is the one thing + Hugo's append cannot do cleanly. */ -}} +{{- $backend := .backend }} +{{- if and (eq $view "full") (not $backend) }} + {{- errorf "reading-order: the full view needs a backend" }} +{{- end }} +{{- $shown := 0 }} +{{- range $rows }} + {{- if eq $view "summary" }} + {{- if and (eq (index . $fixture) "mean") (eq (index . $layoutCol) "multi-column") }}{{ $shown = add $shown 1 }}{{ end }} + {{- else if eq (index . $backendCol) $backend }}{{ $shown = add $shown 1 }}{{ end }} +{{- end }} +{{- if not $shown }} + {{- errorf "reading-order: no rows for backend %q in reading_order.csv" $backend }} +{{- end }} + +
+ + + + + {{- range $strategies }} + + {{- end }} + + + + {{- range $rows }} + {{- $row := . }} + {{- $isMean := eq (index $row $fixture) "mean" }} + {{- $wanted := false }} + {{- if eq $view "summary" }} + {{- $wanted = and $isMean (eq (index $row $layoutCol) "multi-column") }} + {{- else }} + {{- $wanted = eq (index $row $backendCol) $backend }} + {{- end }} + {{- if $wanted }} + {{- $best := -1.0 }} + {{- if $boldBest }} + {{- range $strategies }} + {{- $v := float (index $row (index $col (printf "%s_%s" . $metric))) }} + {{- if gt $v $best }}{{ $best = $v }}{{ end }} + {{- end }} + {{- end }} + + + {{- range $strategies }} + {{- $v := float (index $row (index $col (printf "%s_%s" . $metric))) }} + + {{- end }} + + {{- end }} + {{- end }} + +
{{ if eq $view "summary" }}Backend{{ else }}Fixture{{ end }}{{ index $labels . }}
+ {{- if eq $view "summary" -}} + {{ index $row $backendCol }} + {{- else if $isMean -}} + Mean, {{ index $row $layoutCol }} + {{- else -}} + {{ index $row $fixture }} + {{- end -}} + + {{- printf "%.3f" $v -}} +
+
+ +

+ {{ if eq $metric "chr" }}Character similarity — order-sensitive, the metric + reading order moves.{{ else }}Word recall — order-insensitive, so the first + three columns must agree.{{ end }} + {{ if eq $view "summary" }}Means over the {{ len $multi }} multi-column + fixtures, {{ else }}Every raster fixture for {{ $backend }}, + {{ end }}generated from evaluation/ocr/reading_order.csv at + build time. The same spans in four orders: as the engine reported them, + sorted into lines with no column awareness, ordered by the column-aware + pass, and the plain transcript the backend ships. + {{ if $boldBest }}Bold marks the best in each row.{{ end }} +

diff --git a/site/layouts/shortcodes/reading-order.html b/site/layouts/shortcodes/reading-order.html new file mode 100644 index 0000000..46ba730 --- /dev/null +++ b/site/layouts/shortcodes/reading-order.html @@ -0,0 +1,15 @@ +{{- /* + The reading-order table, read from evaluation/ocr/reading_order.csv at + build time. The markup is in partials/reading-order.html. + + Usage: + {{< reading-order >}} mean per backend over the multi-column fixtures + {{< reading-order view="full" backend="paddle" >}} every raster fixture for one backend + {{< reading-order metric="wrd" >}} word recall instead of character similarity + {{< reading-order bold-best="false" >}} without the best-in-row marking +*/ -}} +{{- partial "reading-order.html" (dict + "view" (.Get "view") + "backend" (.Get "backend") + "metric" (.Get "metric") + "boldBest" (ne (.Get "bold-best") "false")) -}} diff --git a/site/tests/site.spec.ts b/site/tests/site.spec.ts index 0ab1ff2..01866ca 100644 --- a/site/tests/site.spec.ts +++ b/site/tests/site.spec.ts @@ -743,3 +743,41 @@ test("the summary view carries both metrics and derives its register count", asy `${registerCount} evaluation registers`, ); }); + +test("the reading-order table agrees with the CSV it is generated from", async ({ page }) => { + // Same discipline as the register tables: the research page argues from + // these cells, so the rendered numbers must be the harness's, not a copy. + const csv = readFileSync(join("..", "evaluation", "ocr", "reading_order.csv"), "utf8") + .trim() + .split(/\r?\n/) + .map((line) => line.split(",")); + const header = csv[0]; + const means = csv.slice(1).filter((row) => row[0] === "mean" && row[2] === "multi-column"); + const strategies = ["engine", "linesort", "column", "transcript"]; + expect(means.length).toBeGreaterThan(0); + + await page.goto("research/in-depth/"); + const table = page.locator("table.benchmark--reading-order").first(); + await expect(table).toBeVisible(); + await expect(table.locator("thead th")).toHaveCount(strategies.length + 1); + await expect(table.locator("tbody tr")).toHaveCount(means.length); + + for (const [index, row] of means.entries()) { + const tr = table.locator("tbody tr").nth(index); + await expect(tr.locator("th")).toHaveText(row[1]); + for (const [column, strategy] of strategies.entries()) { + const expected = Number(row[header.indexOf(`${strategy}_chr`)]).toFixed(3); + await expect(tr.locator("td").nth(column)).toHaveText(expected); + } + // Every cell marked best carries the row's maximum. Ties are real here: + // easyocr and paddle ship engine order as their transcript, so those two + // columns are the same text and the same score. + const values = strategies.map((strategy) => Number(row[header.indexOf(`${strategy}_chr`)])); + const best = Math.max(...values).toFixed(3); + const marked = tr.locator(".is-best"); + await expect(marked.first()).toHaveText(best); + for (let n = 0; n < (await marked.count()); n++) { + await expect(marked.nth(n)).toHaveText(best); + } + } +}); diff --git a/src/tetrak_ocr/auto_local.py b/src/tetrak_ocr/auto_local.py index fd42a4b..b3b68bc 100644 --- a/src/tetrak_ocr/auto_local.py +++ b/src/tetrak_ocr/auto_local.py @@ -289,7 +289,9 @@ def ocr_image(path: "Path | str", with_paddle_vl: bool = False) -> str: reads acceptably reaches the triage queue instead of being written out. Returns: - Extracted text as a string. + Extracted text as a string -- the winning backend's transcript + exactly as it returned it, so the positioned spans a backend carries + (see :class:`~tetrak_ocr.layout.Transcript`) come through with it. Raises: LowQualityError: If the winning combined score falls below diff --git a/src/tetrak_ocr/backends/armenian.py b/src/tetrak_ocr/backends/armenian.py index 7f9799b..922e767 100644 --- a/src/tetrak_ocr/backends/armenian.py +++ b/src/tetrak_ocr/backends/armenian.py @@ -61,7 +61,7 @@ from PIL import Image from ..imaging import reject_multi_page -from ..layout import TextSpan, to_text +from ..layout import TextSpan, Transcript, polygon_extent, to_text try: import tetrak_hy @@ -113,19 +113,15 @@ def _spans(results) -> list[TextSpan]: here, at the point the text enters the pipeline, so everything downstream sees Armenian rather than a mixture of scripts. """ - spans = [] - for box, text, confidence in results: - xs = [float(point[0]) for point in box] - ys = [float(point[1]) for point in box] - spans.append( - TextSpan( - text=tetrak_hy.fold_script(text), - bbox=(min(xs), min(ys), max(xs), max(ys)), - # EasyOCR reports 0-1; TextSpan documents 0-100. - confidence=float(confidence) * 100, - ) + return [ + TextSpan( + text=tetrak_hy.fold_script(text), + bbox=polygon_extent(box), + # EasyOCR reports 0-1; TextSpan documents 0-100. + confidence=float(confidence) * 100, ) - return spans + for box, text, confidence in results + ] def ocr_image(path: Path) -> str: @@ -142,7 +138,9 @@ def ocr_image(path: Path) -> str: path: Path to the image file. Returns: - The page's text, one recognised line per line of output. + The page's text, one recognised line per line of output, as a + :class:`~tetrak_ocr.layout.Transcript` carrying one folded span per + detected region in the detector's order. Raises: ValueError: If the file extension is not supported. @@ -175,7 +173,8 @@ def ocr_image(path: Path) -> str: reader = _get_reader() results = reader.readtext(image_input, detail=1, paragraph=False, decoder=_decoder) - return to_text(_spans(results)) + spans = _spans(results) + return Transcript(to_text(spans), spans) if __name__ == "__main__": diff --git a/src/tetrak_ocr/backends/easyocr.py b/src/tetrak_ocr/backends/easyocr.py index 0472beb..84d207f 100644 --- a/src/tetrak_ocr/backends/easyocr.py +++ b/src/tetrak_ocr/backends/easyocr.py @@ -27,6 +27,7 @@ from PIL import Image from ..imaging import reject_multi_page +from ..layout import TextSpan, Transcript, polygon_extent try: import easyocr @@ -68,7 +69,9 @@ def ocr_image(path: Path) -> str: path: Path to the image file. Returns: - Extracted text as a single string, one recognised region per line. + Extracted text as a single string, one recognised region per line -- + a :class:`~tetrak_ocr.layout.Transcript` carrying one span per + region, with the detector's box in pixels from the top-left corner. Raises: ValueError: If the file extension is not supported. @@ -100,8 +103,31 @@ def ocr_image(path: Path) -> str: image_input = str(path) reader = _get_reader() - results = reader.readtext(image_input, detail=0, paragraph=False) - return "\n".join(results) + results = reader.readtext(image_input, detail=1, paragraph=False) + return _transcript(results) + + +def _transcript(results) -> Transcript: + """The text this backend has always returned, now carrying its boxes. + + ``detail=0`` returned the recognised texts alone, in detector order. + ``detail=1`` returns the same texts in the same order, each beside the + region's four-point polygon and its confidence -- EasyOCR builds the + detailed result either way and strips it for ``detail=0``. Joining the + texts is therefore byte-identical to what this backend wrote before, so + the benchmark column does not move, and the geometry that was being + thrown away rides along as spans. + """ + spans = [ + TextSpan( + text=text, + bbox=polygon_extent(box), + # EasyOCR reports 0-1; TextSpan documents 0-100. + confidence=float(confidence) * 100, + ) + for box, text, confidence in results + ] + return Transcript("\n".join(span.text for span in spans), spans) if __name__ == "__main__": diff --git a/src/tetrak_ocr/backends/paddle.py b/src/tetrak_ocr/backends/paddle.py index cbae807..53beb27 100644 --- a/src/tetrak_ocr/backends/paddle.py +++ b/src/tetrak_ocr/backends/paddle.py @@ -28,6 +28,7 @@ from PIL import Image from ..imaging import reject_multi_page +from ..layout import TextSpan, Transcript, polygon_extent # PaddlePaddle's C++ layer reads these as glog initialises, which happens # during the import below -- so they are set before it rather than after, where @@ -91,7 +92,9 @@ def ocr_image(path: Path) -> str: path: Path to the image file. Returns: - Extracted text as a single string, one recognised region per line. + Extracted text as a single string, one recognised region per line -- + a :class:`~tetrak_ocr.layout.Transcript` carrying one span per + region, with the detector's box in pixels from the top-left corner. Raises: ValueError: If the file extension is not supported. @@ -137,13 +140,49 @@ def ocr_image(path: Path) -> str: if cleanup: os.unlink(image_input) - texts = [] - if results: - for page in results: - if isinstance(page, dict) and "rec_texts" in page: - texts.extend(page["rec_texts"]) + return _transcript(results) - return "\n".join(texts) + +def _transcript(results) -> Transcript: + """Text and boxes from PaddleOCR's result pages. + + Each page is a dict with ``rec_texts`` and, beside it, ``rec_polys`` (a + four-point polygon per text) and ``rec_scores`` (0-1). The text is the + same join of ``rec_texts`` this backend has always returned, so the + benchmark column does not move; the polygons were in the same dict all + along and were simply never read. + + Geometry is attached only where it lines up. A page whose polygon count + does not match its text count contributes spans without boxes rather + than text paired with the wrong box -- a span with no box cannot be + positioned, which is honest, where a wrong box is a silent error. + """ + texts: list[str] = [] + spans: list[TextSpan] = [] + for page in results or (): + if not (isinstance(page, dict) and "rec_texts" in page): + continue + page_texts = [str(text) for text in page["rec_texts"]] + texts.extend(page_texts) + + polys = page.get("rec_polys") + if polys is None or len(polys) != len(page_texts): + spans.extend(TextSpan(text=text) for text in page_texts) + continue + scores = page.get("rec_scores") + if scores is None or len(scores) != len(page_texts): + scores = [None] * len(page_texts) + for text, poly, score in zip(page_texts, polys, scores, strict=True): + spans.append( + TextSpan( + text=text, + bbox=polygon_extent(poly), + # Paddle reports 0-1; TextSpan documents 0-100. + confidence=None if score is None else float(score) * 100, + ) + ) + + return Transcript("\n".join(texts), spans) if __name__ == "__main__": diff --git a/src/tetrak_ocr/backends/vision.py b/src/tetrak_ocr/backends/vision.py index 27ce1d1..56f78f5 100644 --- a/src/tetrak_ocr/backends/vision.py +++ b/src/tetrak_ocr/backends/vision.py @@ -54,7 +54,7 @@ from PIL import Image from ..imaging import reject_multi_page -from ..layout import TextSpan, to_text +from ..layout import TextSpan, Transcript, to_text # Two separate reasons this backend may be unavailable, and they need to be # distinguished: `ocrmac` is importable on any platform but only *works* on @@ -135,7 +135,9 @@ def ocr_image( recognition_level: ``"accurate"`` (default) or ``"fast"``. Returns: - Extracted text, one recognised region per line. + Extracted text, one recognised region per line, as a + :class:`~tetrak_ocr.layout.Transcript` carrying one span per region + with its box in pixels from the top-left corner. Raises: RuntimeError: If Vision is not available on this machine. @@ -226,18 +228,22 @@ def to_spans(annotations: list, width: int, height: int) -> list[TextSpan]: return spans -def _to_reading_order(annotations: list, width: int = 1, height: int = 1) -> str: +def _to_reading_order(annotations: list, width: int = 1, height: int = 1) -> Transcript: """Join recognised regions top-to-bottom, then left-to-right. The ordering itself lives in :mod:`tetrak_ocr.layout` now, because the PDF writer needs the same rule -- the order text is emitted in *is* the order a screen reader announces it. Multi-column layouts are no better solved here than by the other single-pass backends; that is what `marker` is for. + + The spans the text was ordered from travel with it, in Vision's own + order, for the positioned writers; the text is unchanged. """ + spans = to_spans(annotations, width, height) # 1% of page height, the constant this backend arrived at by experiment on # its own material, passed explicitly rather than left to layout's adaptive # default. The default is finer, and on a dense multi-column page it splits # lines this backend has always merged -- a real change to a published # score, which does not belong in a refactor. Revisit it as a measured # change if it is worth making. - return to_text(to_spans(annotations, width, height), line_tolerance=0.01 * height) + return Transcript(to_text(spans, line_tolerance=0.01 * height), spans) diff --git a/src/tetrak_ocr/batch.py b/src/tetrak_ocr/batch.py index 3d0e9dd..e2eef63 100644 --- a/src/tetrak_ocr/batch.py +++ b/src/tetrak_ocr/batch.py @@ -31,6 +31,7 @@ from . import outputs, telemetry from .imaging import page_documents +from .layout import TextSpan, spans_of from .manifest import DEFAULT_NAME as MANIFEST_NAME from .manifest import Manifest, ManifestError from .registry import BACKENDS, get_backend @@ -252,7 +253,10 @@ def process_file( formats: Output formats to write, defaulting to Markdown alone. Every requested format is written for the same transcript -- the OCR runs once regardless of how many - are asked for. + are asked for. A backend that computes boxes returns + them with the transcript (see `layout.Transcript`), and + they reach every writer as the `spans` and `page_spans` + options; a backend without them passes None. manifest: Where to append this file's row, if anywhere. """ from .qa_score import LowQualityError @@ -308,14 +312,22 @@ def _triage(exc: "LowQualityError") -> None: pages = file_info.get("pages", 1) per_page = bool(formats) and "pdf" in formats and pages > 1 page_transcripts: list[str] | None = None + # The positioned spans, taken off the transcript the moment it arrives: + # a string operation returns a plain str, so the strip-and-join below + # would lose them. Per page when the document was read per page -- + # coordinates belong to a page image -- and for the document otherwise. + spans: list[TextSpan] | None = None + page_spans: list[list[TextSpan] | None] | None = None try: if per_page: print(f" {pages} pages, transcribing individually for the PDF") page_transcripts = transcribe_per_page(image_path, ocr_fn) + page_spans = [spans_of(t) for t in page_transcripts] text = "\n\n".join(t.strip() for t in page_transcripts if t.strip()) else: text = ocr_fn(image_path) + spans = spans_of(text) except LowQualityError as exc: if auto_local: reading.update(_auto_local_choice()) @@ -381,6 +393,8 @@ def _triage(exc: "LowQualityError") -> None: text, PROCESSED_DIR, page_transcripts=page_transcripts, + spans=spans, + page_spans=page_spans, pdf_full_size=pdf_full_size, pdf_font=pdf_font, ) diff --git a/src/tetrak_ocr/cli.py b/src/tetrak_ocr/cli.py index 851e3ae..31a17b9 100644 --- a/src/tetrak_ocr/cli.py +++ b/src/tetrak_ocr/cli.py @@ -18,6 +18,7 @@ from . import outputs, telemetry from .errors import OcrPipelineError +from .layout import spans_of from .registry import BACKENDS, available @@ -49,12 +50,18 @@ def _cmd_ocr(args: argparse.Namespace) -> int: wants_pdf = bool(args.formats and "pdf" in outputs.parse(args.formats)) or bool( args.pdf or args.pdf_full_size or args.pdf_font ) + # Spans come off the transcript before anything strips or joins it, as + # in `batch.process_file`: a string operation returns a plain str. page_transcripts = None + page_spans = None + spans = None if wants_pdf and page_count(path) > 1: page_transcripts = transcribe_per_page(path, ocr) + page_spans = [spans_of(t) for t in page_transcripts] text = "\n\n".join(t.strip() for t in page_transcripts if t.strip()) else: text = ocr(path) + spans = spans_of(text) # `--pdf PATH` names its own destination, so it stays on the direct route # rather than going through the format table, which writes beside the @@ -89,6 +96,8 @@ def _cmd_ocr(args: argparse.Namespace) -> int: text, path.parent, page_transcripts=page_transcripts, + spans=spans, + page_spans=page_spans, pdf_full_size=args.pdf_full_size, pdf_font=args.pdf_font, ) diff --git a/src/tetrak_ocr/layout.py b/src/tetrak_ocr/layout.py index e75e149..828bcaf 100644 --- a/src/tetrak_ocr/layout.py +++ b/src/tetrak_ocr/layout.py @@ -1,18 +1,28 @@ -"""Positioned text: the vocabulary shared by the backends and the PDF writer. - -An OCR engine knows more than the string it returns: four of the six backends -here compute a box per recognised region and then discard it, because the -registry contract is `-> str`. This module is where that information has a -shape, so the backends that keep it can agree on what it means. - -Two backends read through it: the vision backend, whose reading-order logic -this originally was, lifted out and tested, and `easyocr-hy`, which needs the -column handling because the Armenian pages it exists for are set in two -columns. It is deliberately not wired into the searchable PDF -writer: a *positioned* text layer measured worse on reading order than the -plain transcript, badly so on multi-column pages, and that is what a screen -reader announces. See brief 008 (searchable PDF). The boxes become -load-bearing at ALTO/hOCR, where coordinates are the whole point. +"""Positioned text: the vocabulary shared by the backends and the output writers. + +An OCR engine knows more than the string it returns: four of the backends +here -- vision, easyocr, paddle and easyocr-hy -- compute a box per +recognised region. The registry contract is `-> str` and stays so: a backend +that has boxes returns a :class:`Transcript`, a string that carries its +:class:`TextSpan` list alongside the text, and a backend that has none +returns a plain string. Every caller that wants the text is unchanged; a +caller that wants the geometry asks :func:`spans_of`. This module is where +that information has a shape, so the backends that keep it agree on what it +means. + +Two backends order their text through it: the vision backend, whose +reading-order logic this originally was, lifted out and tested, and +`easyocr-hy`, which needs the column handling because the Armenian pages it +exists for are set in two columns. The ordering is deliberately not wired +into the searchable PDF writer: a *positioned* text layer measured worse on +reading order than the plain transcript, badly so on multi-column pages, and +that is what a screen reader announces. See brief 008 (searchable PDF). The +boxes become load-bearing at ALTO/hOCR, where coordinates are the whole +point, which is why the spans now travel with the transcript rather than +being thrown away at the backend's boundary. Whether :func:`reading_order` +is good enough to carry a positioned output is a measured question: +``evaluation/ocr/reading_order.py`` scores it against the line order a +positioned layer reads back as, per backend and fixture. Standard library only, so the fast tests can use it with no OCR stack installed. @@ -45,6 +55,7 @@ from __future__ import annotations import statistics +from collections.abc import Iterable, Sequence from dataclasses import dataclass @@ -80,6 +91,69 @@ def height(self) -> float: return (self.bbox[3] - self.bbox[1]) if self.bbox else 0.0 +class Transcript(str): + """A backend's text, carrying the positioned spans it was built from. + + A ``str`` first: it is what every backend returns, so the registry + contract ``ocr_image(path) -> str`` holds, and the batch pipeline, the + quality gate, the harness and auto-local's winner selection all treat it + as the string it is. The spans ride along for the callers that want them + -- the positioned output writers -- and ``auto-local`` hands back + whichever candidate's transcript won, spans included, without knowing + they are there. That is the reason for a subclass rather than a second + return value: nothing between the backend and the writer has to change + to let the geometry through. + + ``spans`` is the engine's regions as it reported them, in **its** order, + with boxes in pixels from a top-left origin (see the module docstring). + They are not re-ordered here: :func:`reading_order` is a separate, + measured pass, and a writer that needs it applies it. :func:`to_text` + may also have rejoined a word hyphenated across two spans, so the text + and the spans do not pair one-to-one -- the text is the transcript, the + spans are the geometry. + + **Any string operation returns a plain ``str``.** ``transcript.strip()`` + has no spans, and neither does ``"\\n".join(pages)``. Take them off with + :func:`spans_of` before transforming the text, which is what the callers + in ``batch`` and ``cli`` do. + """ + + spans: list[TextSpan] + + def __new__(cls, text: str, spans: Iterable[TextSpan] = ()) -> Transcript: + self = super().__new__(cls, text) + self.spans = list(spans) + return self + + +def spans_of(text: str) -> list[TextSpan] | None: + """The spans carried by *text*, or None when the backend returned a plain string. + + The one place callers reach for the geometry, so a plain ``str`` and a + :class:`Transcript` are handled by the same line of code and nobody tests + the type. An empty list is a real answer -- the engine ran and found no + regions -- where None means the engine had no boxes to give. + + Returned as a copy, so a writer that sorts or filters its list cannot + disturb the next writer's. + """ + return list(text.spans) if isinstance(text, Transcript) else None + + +def polygon_extent(points: Iterable[Sequence[float]]) -> tuple[float, float, float, float]: + """The axis-aligned ``(left, top, right, bottom)`` enclosing a polygon. + + EasyOCR and PaddleOCR report each region as a four-point polygon that + follows a slanted line; ``TextSpan.bbox`` is an axis-aligned box, so the + polygon's extent is taken. On a straight page the two are the same box; + on a skewed one the extent is a little taller than the type and never + narrower. The points may be any sequence of pairs, numpy rows included. + """ + xs = [float(point[0]) for point in points] + ys = [float(point[1]) for point in points] + return (min(xs), min(ys), max(xs), max(ys)) + + def _default_tolerance(spans: list[TextSpan]) -> float: """How far apart two spans can sit vertically and still be one line. diff --git a/src/tetrak_ocr/outputs.py b/src/tetrak_ocr/outputs.py index 9bd07c6..e7bcc81 100644 --- a/src/tetrak_ocr/outputs.py +++ b/src/tetrak_ocr/outputs.py @@ -11,7 +11,21 @@ ``source`` is the file that was transcribed, which the text formats ignore and the PDF writer needs (it embeds the scan). ``options`` carries format-specific settings; a writer must tolerate options meant for a different format, because -the caller passes one dict to all of them. +the caller passes one dict to all of them. The pipeline and the ``ocr`` +subcommand pass the same set to every writer:: + + page_transcripts one string per page of a multi-page document, or None + spans the backend's positioned spans for the document -- + ``layout.TextSpan``, pixels, top-left origin, in the + engine's own order -- or None when the backend has none + (see ``layout.Transcript`` and ``layout.spans_of``) + page_spans one such list, or None, per page, when the document was + read page by page; ``spans`` is then None + pdf_full_size the searchable PDF's own settings + pdf_font + +The text writers ignore the spans. They exist for the positioned formats -- +ALTO, hOCR -- where the coordinates are the output. Adding a format means adding one entry to ``_FORMATS`` and nothing else: the CLI takes its choices, its help text and its validation from this table, the @@ -54,6 +68,10 @@ def _write_pdf(source: Path, transcript: str, destination: Path, **options) -> N Imported lazily: the PDF path pulls in Pillow's PDF machinery and a font, which nobody writing Markdown should pay for. + + The ``spans`` option is deliberately not used. A word-positioned text + layer was measured and rejected for this format -- see the + :mod:`tetrak_ocr.pdf_output` module docstring. """ from .pdf_output import searchable_pdf_for diff --git a/src/tetrak_ocr/pdf_output.py b/src/tetrak_ocr/pdf_output.py index bb30e2b..97d2bab 100644 --- a/src/tetrak_ocr/pdf_output.py +++ b/src/tetrak_ocr/pdf_output.py @@ -29,6 +29,11 @@ coordinates are the point rather than a side effect. See brief 008 (searchable PDF). +Whether the column-aware pass in :mod:`tetrak_ocr.layout` closes that gap +is measured by ``evaluation/ocr/reading_order.py``, per backend and per +fixture, beside the figures above: the same spans scored in line order and +in column-aware order, against the plain transcript. + The consequence worth knowing: the text layer is byte-identical to the sidecar, and selecting text in a viewer will not align with the words on the page. """ diff --git a/tests/ocr/test_armenian.py b/tests/ocr/test_armenian.py index efbe92b..e4f85d2 100644 --- a/tests/ocr/test_armenian.py +++ b/tests/ocr/test_armenian.py @@ -201,3 +201,27 @@ def make(**kwargs): self.read(tmp_path) assert len(library.calls) == 1 assert reader.decoders == ["beamsearch", "beamsearch"] + + +class TestPositionedOutput: + """The spans the text was ordered from leave the backend with it.""" + + def test_the_transcript_carries_the_folded_spans( + self, stub_tetrak_hy, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + from tetrak_ocr.layout import spans_of + + class Reader: + def readtext(self, image, **kwargs): + return [region("hայ", 100, 200, 260, 210), region("ա", 100, 230, 260, 240)] + + monkeypatch.setattr(armenian, "_reader", Reader()) + page = tmp_path / "page.png" + Image.new("RGB", (20, 20), "white").save(page) + + transcript = armenian.ocr_image(page) + + assert transcript == "հայ\nա" + spans = spans_of(transcript) + assert [s.text for s in spans] == ["հայ", "ա"], "folded, like the text" + assert spans[0].bbox == (100.0, 200.0, 260.0, 210.0) diff --git a/tests/ocr/test_auto_local.py b/tests/ocr/test_auto_local.py index 640db4a..cd3f96f 100644 --- a/tests/ocr/test_auto_local.py +++ b/tests/ocr/test_auto_local.py @@ -483,3 +483,29 @@ def test_asking_for_it_uninstalled_is_not_an_error( ] assert "paddle-vl" not in names assert names # and the rest of the pool still runs + + +class TestSpansPassThrough: + """The winner's transcript is returned as the backend produced it. + + A backend with boxes returns a `Transcript`; nothing here knows or needs + to, and the spans reach the caller because the string is returned whole + rather than rebuilt. + """ + + def test_the_winners_spans_come_through(self, monkeypatch: pytest.MonkeyPatch) -> None: + from tetrak_ocr.layout import TextSpan, Transcript, spans_of + + spans = [TextSpan(text="the good transcript", bbox=(0.0, 0.0, 10.0, 10.0))] + monkeypatch.setattr( + auto_local, "_paddle_ocr", lambda p: Transcript("the good transcript", spans) + ) + monkeypatch.setattr(auto_local, "_tesseract_ocr", lambda p, **kw: "the bad transcript") + monkeypatch.setattr( + auto_local, "combined_score", lambda text: 0.9 if "good" in text else 0.2 + ) + + result = auto_local.ocr_image(Path("scan.jpg")) + + assert result == "the good transcript" + assert spans_of(result) == spans diff --git a/tests/ocr/test_batch.py b/tests/ocr/test_batch.py index aec809e..cdadf56 100644 --- a/tests/ocr/test_batch.py +++ b/tests/ocr/test_batch.py @@ -25,6 +25,7 @@ from tetrak_ocr.backends.tesseract import DEFAULT_CONTRAST, DEFAULT_PSM, SUPPORTED_EXTENSIONS from tetrak_ocr.batch import build_ocr_fn from tetrak_ocr.batch import main as run_batch +from tetrak_ocr.layout import TextSpan, Transcript def _write_legible_image(path: Path, text: str = "HELLO ARCHIVE") -> None: @@ -331,3 +332,49 @@ def test_a_non_latin_transcript_is_not_triaged(self, working_dirs, monkeypatch, assert (working_dirs["processed"] / "page.png").exists() assert not (working_dirs["triage"] / "page.png").exists() assert "quality gate skipped" in capsys.readouterr().err + + +class TestSpansReachTheWriters: + """A backend's positioned spans travel to every writer; a plain string gives None. + + The text outputs must not change either way. The spans are for the + positioned formats, and the Markdown a batch has always written is the + same byte for byte whichever kind of backend produced the transcript. + """ + + @staticmethod + def _run(monkeypatch, working_dirs, result) -> tuple[dict, str]: + """Process one file with a backend returning *result*; report the + options every writer received and the Markdown written.""" + from tetrak_ocr import batch, outputs + + monkeypatch.setattr(batch, "build_ocr_fn", lambda *a, **k: lambda path: result) + seen: dict = {} + original = outputs.write + + def recording_write(name, source, transcript, destination_dir, **options): + seen.update(options) + return original(name, source, transcript, destination_dir, **options) + + monkeypatch.setattr(outputs, "write", recording_write) + (working_dirs["scans"] / "page.png").touch() + + assert run_batch(["--backend", "tesseract"]) == 0 + + return seen, (working_dirs["processed"] / "page.md").read_text(encoding="utf-8") + + def test_a_backend_with_boxes_hands_them_to_the_writers(self, working_dirs, monkeypatch): + spans = [TextSpan(text="words", bbox=(1.0, 2.0, 3.0, 4.0))] + + seen, markdown = self._run(monkeypatch, working_dirs, Transcript("words", spans)) + + assert seen["spans"] == spans + assert seen["page_spans"] is None + assert markdown == "# page\n\nwords\n" + + def test_a_backend_without_boxes_hands_over_none(self, working_dirs, monkeypatch): + seen, markdown = self._run(monkeypatch, working_dirs, "words") + + assert seen["spans"] is None + assert seen["page_spans"] is None + assert markdown == "# page\n\nwords\n" diff --git a/tests/ocr/test_cli.py b/tests/ocr/test_cli.py index bdf4e5f..60fc7b8 100644 --- a/tests/ocr/test_cli.py +++ b/tests/ocr/test_cli.py @@ -308,3 +308,35 @@ def test_the_retired_backend_is_no_longer_accepted( with pytest.raises(SystemExit): cli.main(["ocr", str(img), "--backend", "auto-local-fast"]) + + +class TestOcrSubcommandSpans: + """`ocr` hands a backend's spans to the writers the same way `batch` does.""" + + def test_spans_reach_the_writers( + self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture, tmp_path + ) -> None: + from tetrak_ocr import outputs + from tetrak_ocr.layout import TextSpan, Transcript + + spans = [TextSpan(text="hello", bbox=(0.0, 0.0, 10.0, 10.0))] + monkeypatch.setattr( + batch, "build_ocr_fn", lambda *a, **k: lambda path: Transcript("hello", spans) + ) + seen: dict = {} + original = outputs.write + + def recording_write(name, source, transcript, destination_dir, **options): + seen.update(options) + return original(name, source, transcript, destination_dir, **options) + + monkeypatch.setattr(outputs, "write", recording_write) + img = tmp_path / "scan.png" + img.touch() + + assert cli.main(["ocr", str(img), "--format", "text"]) == 0 + + assert seen["spans"] == spans + assert seen["page_spans"] is None + assert (tmp_path / "scan.txt").read_text() == "hello\n" + assert "hello" in capsys.readouterr().out diff --git a/tests/ocr/test_easyocr.py b/tests/ocr/test_easyocr.py new file mode 100644 index 0000000..e5576de --- /dev/null +++ b/tests/ocr/test_easyocr.py @@ -0,0 +1,88 @@ +"""Tests for the stock EasyOCR backend. + +Accuracy belongs in the benchmark. What these pin is the contract around the +one change this backend has had: it asks `readtext` for the detailed result +instead of the bare texts, so the boxes reach the caller as spans. The text +must be byte for byte what `detail=0` gave -- the benchmark column must not +move -- and the geometry beside it must arrive in the package's convention. + +`easyocr` is stubbed: CI installs no heavy backends, and these need geometry +and string handling, not weights. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +from PIL import Image + +from tetrak_ocr.backends import easyocr +from tetrak_ocr.layout import Transcript, spans_of + + +def region(text: str, left: float, top: float, right: float, bottom: float, conf: float = 0.9): + """One `readtext(detail=1)` result: a four-point polygon, the text, a confidence.""" + return ([[left, top], [right, top], [right, bottom], [left, bottom]], text, conf) + + +class TestTranscript: + def test_the_text_is_what_detail_zero_returned(self) -> None: + """`readtext(detail=0)` is `[item[1] for item in result]`. Joining those + is the output this backend has always produced, and still does.""" + results = [region("first", 0, 0, 10, 10), region("second", 0, 20, 10, 30)] + detail_zero = [text for _, text, _ in results] + + assert easyocr._transcript(results) == "\n".join(detail_zero) + + def test_the_spans_carry_the_boxes_in_detector_order(self) -> None: + """The engine's order, not a reading order: ordering is a separate, + measured pass that the writer applies.""" + results = [region("lower", 0, 20, 10, 30), region("upper", 0, 0, 10, 10)] + + spans = spans_of(easyocr._transcript(results)) + + assert [s.text for s in spans] == ["lower", "upper"] + assert spans[0].bbox == (0.0, 20.0, 10.0, 30.0) + + def test_a_polygon_becomes_its_axis_aligned_extent(self) -> None: + skewed = ([[10, 0], [30, 4], [28, 14], [8, 10]], "slant", 0.9) + assert spans_of(easyocr._transcript([skewed]))[0].bbox == (8.0, 0.0, 30.0, 14.0) + + def test_confidence_is_rescaled_to_the_documented_range(self) -> None: + """EasyOCR reports 0-1; TextSpan documents 0-100.""" + spans = spans_of(easyocr._transcript([region("a", 0, 0, 10, 10, conf=0.25)])) + assert spans[0].confidence == 25.0 + + def test_no_regions_is_an_empty_transcript_with_no_spans(self) -> None: + transcript = easyocr._transcript([]) + assert transcript == "" + assert spans_of(transcript) == [] + + +class TestOcrImage: + """The reader is asked for the detailed result, and it reaches the caller.""" + + def test_the_result_reaches_the_caller_as_a_transcript( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + seen: dict = {} + + class Reader: + def readtext(self, image, **kwargs): + seen.update(kwargs) + return [region("hello", 0, 0, 50, 10), region("world", 0, 20, 50, 30)] + + monkeypatch.setattr(easyocr, "_reader", Reader()) + page = tmp_path / "page.png" + Image.new("RGB", (60, 40), "white").save(page) + + transcript = easyocr.ocr_image(page) + + assert seen["detail"] == 1, "detail=0 is the texts alone; the boxes need detail=1" + assert isinstance(transcript, Transcript) + assert transcript == "hello\nworld" + assert [s.bbox for s in spans_of(transcript)] == [ + (0.0, 0.0, 50.0, 10.0), + (0.0, 20.0, 50.0, 30.0), + ] diff --git a/tests/ocr/test_layout.py b/tests/ocr/test_layout.py index 05f8358..390a625 100644 --- a/tests/ocr/test_layout.py +++ b/tests/ocr/test_layout.py @@ -5,10 +5,13 @@ from tetrak_ocr.layout import ( TextSpan, + Transcript, dehyphenate, find_gutter, group_lines, + polygon_extent, reading_order, + spans_of, to_text, xy_cut_lines, ) @@ -394,3 +397,67 @@ def test_to_text_rejoins_but_reading_order_cannot() -> None: assert to_text(spans) == "Արագածոտն" assert [s.text for s in reading_order(spans)] == ["Արագա-", "ծոտն"] + + +class TestTranscript: + """The carrier that lets a backend keep its boxes behind a `-> str` contract.""" + + def test_it_is_the_string_it_carries(self) -> None: + transcript = Transcript("hello\nworld", [span("hello", 10, 50), span("world", 10, 80)]) + + assert transcript == "hello\nworld" + assert isinstance(transcript, str) + assert transcript.splitlines() == ["hello", "world"] + assert len(transcript) == len("hello\nworld") + + def test_spans_of_returns_what_the_backend_computed(self) -> None: + spans = [span("hello", 10, 50)] + assert spans_of(Transcript("hello", spans)) == spans + + def test_a_plain_string_has_no_spans(self) -> None: + """A backend without boxes returns a str; the caller sees None, not an error.""" + assert spans_of("hello") is None + + def test_no_regions_is_an_empty_list_not_none(self) -> None: + """The engine ran and found nothing -- a different answer from 'cannot say'.""" + assert spans_of(Transcript("")) == [] + + def test_string_operations_return_a_plain_str(self) -> None: + """The trap the docstring warns of, pinned so it stays documented: the + callers take the spans off before stripping or joining.""" + transcript = Transcript(" hello ", [span("hello", 10, 50)]) + + assert spans_of(transcript.strip()) is None + assert spans_of("\n\n".join([transcript, transcript])) is None + + def test_spans_are_copied_out(self) -> None: + """One writer sorting its list must not reorder the next writer's.""" + transcript = Transcript("b\na", [span("b", 10, 80), span("a", 10, 50)]) + + spans_of(transcript).reverse() + + assert [s.text for s in spans_of(transcript)] == ["b", "a"] + + def test_the_text_need_not_pair_with_the_spans(self) -> None: + """to_text rejoins a word hyphenated across two spans, so the text is + the transcript and the spans are the geometry -- two things, not one + list in two shapes.""" + spans = [span("trans-", 10, 50), span("cript", 10, 80)] + + transcript = Transcript(to_text(spans), spans) + + assert transcript == "transcript" + assert len(spans_of(transcript)) == 2 + + +class TestPolygonExtent: + def test_an_upright_box_is_its_own_extent(self) -> None: + assert polygon_extent([[5, 7], [25, 7], [25, 27], [5, 27]]) == (5.0, 7.0, 25.0, 27.0) + + def test_a_skewed_polygon_takes_its_outer_edges(self) -> None: + """A slanted line's polygon leans; the box is the smallest upright one around it.""" + assert polygon_extent([[10, 0], [30, 4], [28, 14], [8, 10]]) == (8.0, 0.0, 30.0, 14.0) + + def test_the_result_is_floats_whatever_was_given(self) -> None: + """Detectors report integer pixels; everything downstream does float arithmetic.""" + assert all(isinstance(v, float) for v in polygon_extent(((1, 2), (3, 4)))) diff --git a/tests/ocr/test_outputs.py b/tests/ocr/test_outputs.py index 5351634..4fbe724 100644 --- a/tests/ocr/test_outputs.py +++ b/tests/ocr/test_outputs.py @@ -94,3 +94,18 @@ def test_extension_lookup(self) -> None: assert outputs.extension("markdown") == ".md" assert outputs.extension("txt") == ".txt" assert outputs.extension("pdf") == ".pdf" + + def test_the_text_writers_tolerate_the_span_options(self, tmp_path: Path) -> None: + """Every writer receives `spans` and `page_spans`. The text formats + ignore them and write exactly what they always did.""" + from tetrak_ocr.layout import TextSpan + + source = tmp_path / "postcard.jpg" + source.touch() + spans = [TextSpan(text="some words", bbox=(0.0, 0.0, 10.0, 10.0))] + + md = outputs.write("markdown", source, "some words", tmp_path, spans=spans, page_spans=None) + txt = outputs.write("text", source, "some words", tmp_path, spans=None, page_spans=[spans]) + + assert md.read_text(encoding="utf-8") == "# postcard\n\nsome words\n" + assert txt.read_text(encoding="utf-8") == "some words\n" diff --git a/tests/ocr/test_paddle.py b/tests/ocr/test_paddle.py new file mode 100644 index 0000000..5a3880a --- /dev/null +++ b/tests/ocr/test_paddle.py @@ -0,0 +1,104 @@ +"""Tests for the PaddleOCR backend. + +Accuracy belongs in the benchmark. What these pin is the contract around the +result handling: the text is the same join of `rec_texts` it has always been, +and the polygons that sat beside it in the result dict -- read by nothing +until now -- arrive as spans in the package's convention, attached only where +they line up with the texts. + +PaddleOCR is stubbed: CI installs no heavy backends, and the pipeline is +never constructed. +""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +from PIL import Image + +from tetrak_ocr.backends import paddle +from tetrak_ocr.layout import Transcript, spans_of + + +def page(texts, polys=None, scores=None) -> dict: + """One result page, shaped like PaddleOCR 3's OCRResult: a dict with these keys.""" + result = {"rec_texts": list(texts)} + if polys is not None: + result["rec_polys"] = polys + if scores is not None: + result["rec_scores"] = scores + return result + + +def poly(left: float, top: float, right: float, bottom: float) -> list[list[float]]: + return [[left, top], [right, top], [right, bottom], [left, bottom]] + + +class TestTranscript: + def test_the_text_is_the_join_of_rec_texts(self) -> None: + """What the backend wrote before, byte for byte, pages included.""" + results = [page(["one", "two"]), page(["three"])] + assert paddle._transcript(results) == "one\ntwo\nthree" + + def test_the_spans_carry_the_polygons_and_scores(self) -> None: + results = [ + page( + ["a", "b"], + polys=[poly(0, 0, 10, 10), poly(0, 20, 10, 30)], + scores=[0.5, 1.0], + ) + ] + + spans = spans_of(paddle._transcript(results)) + + assert [(s.text, s.bbox, s.confidence) for s in spans] == [ + ("a", (0.0, 0.0, 10.0, 10.0), 50.0), + ("b", (0.0, 20.0, 10.0, 30.0), 100.0), + ] + + def test_polygons_that_do_not_line_up_give_text_without_boxes(self) -> None: + """A wrong box is a silent error; no box is an honest one.""" + results = [page(["a", "b"], polys=[poly(0, 0, 10, 10)])] + + transcript = paddle._transcript(results) + + assert transcript == "a\nb" + assert [s.bbox for s in spans_of(transcript)] == [None, None] + + def test_scores_that_do_not_line_up_are_dropped_but_the_boxes_kept(self) -> None: + results = [page(["a"], polys=[poly(0, 0, 10, 10)], scores=[])] + + spans = spans_of(paddle._transcript(results)) + + assert spans[0].bbox == (0.0, 0.0, 10.0, 10.0) + assert spans[0].confidence is None + + def test_pages_not_shaped_like_a_result_are_skipped(self) -> None: + """What the backend did before: anything without `rec_texts` is ignored.""" + results = [{"something": "else"}, "not a dict", page(["kept"])] + assert paddle._transcript(results) == "kept" + + def test_empty_results_give_an_empty_transcript(self) -> None: + assert paddle._transcript(None) == "" + assert paddle._transcript([]) == "" + assert spans_of(paddle._transcript([])) == [] + + +class TestOcrImage: + def test_the_result_reaches_the_caller_as_a_transcript( + self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path + ) -> None: + class Engine: + def predict(self, target): + return [page(["hello"], polys=[poly(1, 2, 3, 4)], scores=[0.9])] + + monkeypatch.setattr(paddle, "_ocr_instance", Engine()) + image = tmp_path / "scan.png" + Image.new("RGB", (10, 10), "white").save(image) + + transcript = paddle.ocr_image(image) + + assert isinstance(transcript, Transcript) + assert transcript == "hello" + assert spans_of(transcript)[0].bbox == (1.0, 2.0, 3.0, 4.0) diff --git a/tests/ocr/test_reading_order.py b/tests/ocr/test_reading_order.py new file mode 100644 index 0000000..3a3cfbe --- /dev/null +++ b/tests/ocr/test_reading_order.py @@ -0,0 +1,126 @@ +"""Tests for the reading-order harness. + +The harness decides whether positioned output can ship, so what is pinned +here is that it measures what it says: that the line sort reproduces the +interleaving brief 008 found, that the column-aware pass undoes it on the +same spans, that word recall cannot tell the two apart, and that the save +path writes a table the site can read. Fast: synthetic spans, no engine. +""" + +from __future__ import annotations + +import csv +from pathlib import Path + +from evaluation.ocr import reading_order as harness +from tetrak_ocr.layout import TextSpan + + +def two_column_page(rows: int = 6) -> tuple[list[TextSpan], str]: + """Spans in *engine* order, which happens to interleave the columns, and + the truth a person would read: the left column, then the right.""" + spans = [] + for row in range(rows): + bottom = 200 + row * 30 + spans.append(TextSpan(text=f"L{row}", bbox=(100, bottom - 10, 260, bottom))) + spans.append(TextSpan(text=f"R{row}", bbox=(500, bottom - 10, 660, bottom))) + truth = "\n".join([f"L{r}" for r in range(rows)] + [f"R{r}" for r in range(rows)]) + return spans, truth + + +class TestStrategies: + def test_the_line_sort_interleaves_the_columns(self) -> None: + """The construction brief 008 measured: a positioned layer reads back + top to bottom across the page.""" + spans, _ = two_column_page() + assert harness.STRATEGIES["linesort"](spans).split("\n")[:2] == ["L0 R0", "L1 R1"] + + def test_the_column_aware_pass_reads_a_column_to_its_foot(self) -> None: + spans, truth = two_column_page() + assert harness.STRATEGIES["column"](spans) == truth.replace("\n", " ") + + def test_engine_order_is_untouched(self) -> None: + spans, _ = two_column_page() + assert harness.STRATEGIES["engine"](spans).split("\n")[:3] == ["L0", "R0", "L1"] + + +class TestScore: + def test_character_similarity_separates_the_orders_and_word_recall_cannot(self) -> None: + """The pairing the harness prints: chr moves with order, wrd is the + tripwire that must stay put across serialisations of the same tokens.""" + spans, truth = two_column_page() + + scores = harness.score(spans, harness.STRATEGIES["engine"](spans), truth) + + assert scores["column_chr"] == 1.0 + assert scores["linesort_chr"] < scores["column_chr"] + assert scores["engine_wrd"] == scores["linesort_wrd"] == scores["column_wrd"] == 1.0 + assert scores["transcript_chr"] == scores["engine_chr"] + + def test_every_column_is_scored(self) -> None: + spans, truth = two_column_page() + assert set(harness.score(spans, "", truth)) == set(harness.FIELDNAMES[3:]) + + +class TestClassification: + def test_the_multi_column_fixtures_are_rasters_in_the_corpus(self) -> None: + """A stem that drifts from the corpus would silently shrink the set.""" + if not harness.raster_pairs(): + return # no corpus checked out + stems = {image.stem for image, _ in harness.raster_pairs()} + assert harness.MULTI_COLUMN <= stems + + def test_pdfs_are_excluded(self) -> None: + assert all(image.suffix != ".pdf" for image, _ in harness.raster_pairs()) + + +def synthetic_rows() -> list[dict[str, object]]: + def row(fixture: str, backend: str, layout: str, column: float) -> dict[str, object]: + scores = {f"{name}_chr": 0.5 for name in harness.COLUMNS} | { + f"{name}_wrd": 0.9 for name in harness.COLUMNS + } + scores["column_chr"] = column + return {"fixture": fixture, "backend": backend, "layout": layout} | scores + + return [ + row("news-b", "paddle", "multi-column", 0.8), + row("news-a", "paddle", "multi-column", 0.6), + row("postcard", "paddle", "single-column", 0.9), + row("news-a", "vision", "multi-column", 0.7), + ] + + +class TestSave: + def test_means_follow_each_group_and_are_the_groups_mean(self) -> None: + rows = harness.with_means(synthetic_rows()) + + labels = [(r["backend"], r["layout"], r["fixture"]) for r in rows] + assert labels == [ + ("paddle", "multi-column", "news-a"), + ("paddle", "multi-column", "news-b"), + ("paddle", "multi-column", "mean"), + ("paddle", "single-column", "postcard"), + ("paddle", "single-column", "mean"), + ("vision", "multi-column", "news-a"), + ("vision", "multi-column", "mean"), + ] + assert rows[2]["column_chr"] == 0.7 + + def test_the_csv_and_markdown_are_written_and_readable(self, tmp_path: Path) -> None: + csv_path, md_path = tmp_path / "reading_order.csv", tmp_path / "reading_order.md" + + harness.write(synthetic_rows(), csv_path, md_path) + + with csv_path.open(encoding="utf-8") as handle: + table = list(csv.DictReader(handle)) + assert table[0].keys() == set(harness.FIELDNAMES) + means = [r for r in table if r["fixture"] == "mean"] + assert [(r["backend"], r["layout"]) for r in means] == [ + ("paddle", "multi-column"), + ("paddle", "single-column"), + ("vision", "multi-column"), + ] + assert means[0]["column_chr"] == "0.7000" + markdown = md_path.read_text(encoding="utf-8") + assert "Do not edit" in markdown + assert "## paddle" in markdown and "## vision" in markdown diff --git a/tests/ocr/test_vision.py b/tests/ocr/test_vision.py index 306f69e..e2d3ca5 100644 --- a/tests/ocr/test_vision.py +++ b/tests/ocr/test_vision.py @@ -18,6 +18,7 @@ import pytest from tetrak_ocr.backends import vision +from tetrak_ocr.layout import spans_of pytestmark = pytest.mark.skipif(sys.platform != "darwin", reason="Vision is macOS-only") @@ -109,3 +110,23 @@ def test_armenian_is_not_available(self) -> None: complaint about Vision. If a future macOS adds it, this fails and the docstring needs revisiting.""" assert not [c for c in vision.supported_languages() if c.startswith("hy")] + + +class TestPositionedOutput: + """The boxes Vision reports leave the backend with the text, not behind it.""" + + def test_the_spans_travel_with_the_text(self) -> None: + annotations = [ + ("bottom", 0.5, (0.1, 0.1, 0.2, 0.05)), + ("top", 0.99, (0.1, 0.9, 0.2, 0.05)), + ] + + transcript = vision._to_reading_order(annotations, width=1000, height=2000) + + assert transcript == "top\nbottom" + spans = spans_of(transcript) + assert [s.text for s in spans] == ["bottom", "top"], "the engine's order, not reading order" + # Pixels, top-left origin: the inversion from Apple's bottom-left + # normalised box happened at the boundary, once. + assert spans[1].bbox == pytest.approx((100.0, 100.0, 300.0, 200.0)) + assert spans[0].confidence == pytest.approx(50.0)