From 3befe10f5a3318cd08eff0054c166760b5f3b925 Mon Sep 17 00:00:00 2001 From: Stephen Masters Date: Sat, 31 Oct 2026 00:13:01 +0000 Subject: [PATCH] feat(orientation): turn pages upright before OCR with --orient Scans come in on their side or upside down, and an engine reading a page that is not upright returns nonsense. `--orient latin|armenian` on `ocr` and `batch` reads which way up a page is from its ink and turns it before the engine sees it (brief 020). Two questions, in order. Whether the lines run across or down is script-agnostic: the line-direction vote from the Empire on Trial reading site. Which way is up depends on the script, so the caller names it: for Latin, the share of a line's outer ink above it (with the plateau merge and the lines-found guard); for Armenian, which way the open sides of the letters face, after Aradhye (2005). Design research 002 found the Latin measure fails on Armenian, and 003 that the concavity measure works on it and not on Latin. Unsure means untouched: a blank leaf, a dark frame or a share within the margin of a half is read as it is and named. The margins come from the studies' saved per-page readings. The scan is never changed; the engine reads a turned PNG copy, the searchable PDF embeds that copy so its text layer lines up, and the manifest note and an `orientation` run-log event record the turn. Single-page files only. The Armenian measure needs NumPy and OpenCV, in a new `orientation` extra (already transitive through EasyOCR), which `dev` installs so the tests run in CI. The tests draw their pages, so no image needs a licence. Co-authored-by: Yvette Mankerian Co-Authored-By: Claude Opus 5.5 --- docs/guide/command-line.md | 50 ++++ docs/installation.md | 1 + pyproject.toml | 11 +- src/tetrak_ocr/batch.py | 89 ++++++- src/tetrak_ocr/cli.py | 54 ++++- src/tetrak_ocr/errors.py | 17 ++ src/tetrak_ocr/manifest.py | 3 +- src/tetrak_ocr/orientation.py | 442 ++++++++++++++++++++++++++++++++++ tests/ocr/synthetic_pages.py | 113 +++++++++ tests/ocr/test_orientation.py | 317 ++++++++++++++++++++++++ 10 files changed, 1082 insertions(+), 15 deletions(-) create mode 100644 src/tetrak_ocr/orientation.py create mode 100644 tests/ocr/synthetic_pages.py create mode 100644 tests/ocr/test_orientation.py diff --git a/docs/guide/command-line.md b/docs/guide/command-line.md index 1ff13f1..ff48b9e 100644 --- a/docs/guide/command-line.md +++ b/docs/guide/command-line.md @@ -68,6 +68,10 @@ tetrak-ocr ocr scan.jpg --format text --output transcript.txt Without `--format`, `--output` writes the bare transcript, whatever the file is called. +`--orient` turns a page upright before reading it, as `batch` does; see +[turning pages upright](#turning-pages-upright). It reports what it did on +stderr, so stdout stays the transcript. + ## `tetrak-ocr batch` The pipeline's normal mode. It uses three directories under `workspace/`, @@ -243,6 +247,52 @@ No OCR runs and nothing is moved, but the chosen backend's package does have to be installed: the file list depends on which extensions that backend declares it can read. +### Turning pages upright + +```bash +tetrak-ocr batch --backend tesseract-auto --orient latin +tetrak-ocr batch --backend easyocr-hy --orient armenian +``` + +Scans come in on their side or upside down (microfilm shot however the pages +lay, a postcard turned on the glass), and an engine reading a page that is not +upright returns nonsense or nothing. `--orient` reads which way up each page +is from the ink on it, and turns the page before the engine sees it. It asks +two questions: + +1. **Do the lines of text run across or down?** This works for any script. +2. **With the lines across, which way is up?** This depends on the script, + which is why you name it. For `latin`, more ink sits above a line of + writing than below it (ascenders and capitals against descenders). For + `armenian` that is not true, and what tells is which way the open sides of + the letters face. Each measure is wrong on the other script, so name the + script the pages are in. A page that is half one and half the other, such + as a bilingual dictionary, reads as whichever script the measure knows. + +The article [Which way up is Armenian?](https://tetrak.dev/articles/2026/10/which-way-up-armenian/) +has the measurements behind both. + +A page is turned only when both answers are clear. Turning an upright page +upside down would be worse than leaving a sideways one alone, so a blank leaf, +a dark frame or a reading too near even is read as it is, and the batch says +so by name: + +```text + Processing: frame-0042.tif + turned 90° clockwise to read + Processing: frame-0043.tif + orientation unsure (no text to read); read as it is +``` + +The scan itself is never changed. The engine reads a turned copy, a searchable +PDF embeds that copy so its text layer lines up with the page it shows, and +the original moves to `workspace/processed/` exactly as it arrived. The +manifest's `note` column and the run log's `orientation` event record what was +done. Only single-page files are checked; a PDF or a multi-page TIFF is read +as it is. `--orient armenian` needs the `orientation` extra +(`pip install 'tetrak[orientation]'`); `latin` needs nothing beyond the core +install. + ### Tuning Tesseract ```bash diff --git a/docs/installation.md b/docs/installation.md index 696da84..feb4af4 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -63,6 +63,7 @@ well over a gigabyte before any model downloads at first run. | `marker` | `marker` | marker-pdf 1.x | | `vision` | `vision` | `ocrmac`, a wrapper over Apple's Vision framework. macOS only | | `claude` | `claude`, `claude-haiku` | the Anthropic SDK | +| `orientation` | `--orient armenian` | NumPy and OpenCV, which EasyOCR brings in anyway | | `ocr` | everything above except `armenian` | | | `all` | the same as `ocr` | | diff --git a/pyproject.toml b/pyproject.toml index 4cea225..b0b9629 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -99,7 +99,14 @@ docs = [ # Draws the benchmark comparison chart from benchmark.csv. "matplotlib>=3.8", ] -dev = ["pytest>=8.0", "pytest-cov>=5.0", "ruff>=0.5"] +# Turning pages upright before OCR (brief 020). Only `--orient armenian` +# needs these: OpenCV finds the letters whose open sides the measure reads. +# Both already arrive with EasyOCR; declared here for anyone orienting pages +# for Tesseract. Apache 2.0 and BSD -- see the dependency licence audit. +orientation = ["numpy>=1.24", "opencv-python-headless>=4.8"] +# The orientation extra is in dev so that its tests run in CI; it is the one +# extra small enough for that. +dev = ["pytest>=8.0", "pytest-cov>=5.0", "ruff>=0.5", "tetrak[orientation]"] # Composed from the other extras rather than restating them. The hand-written # copy had drifted: it listed pyspellchecker and transformers but not torch, so # `pip install "tetrak[all]"` -- the command the docs lead with -- left @@ -107,7 +114,7 @@ dev = ["pytest>=8.0", "pytest-cov>=5.0", "ruff>=0.5"] # Per-pipeline umbrellas. The individual extras keep their own names -- # `easyocr` and a future `whisper` do not collide, so namespacing them would # churn CI, AGENTS.md and the devcontainer for nothing. -ocr = ["tetrak[claude,easyocr,paddle,paddle-vl,marker,vision,qa]"] +ocr = ["tetrak[claude,easyocr,paddle,paddle-vl,marker,vision,qa,orientation]"] all = ["tetrak[ocr]"] [project.scripts] diff --git a/src/tetrak_ocr/batch.py b/src/tetrak_ocr/batch.py index b292256..0372654 100644 --- a/src/tetrak_ocr/batch.py +++ b/src/tetrak_ocr/batch.py @@ -29,7 +29,8 @@ if TYPE_CHECKING: # pragma: no cover from .qa_score import LowQualityError -from . import outputs, telemetry, triage +from . import orientation, outputs, telemetry, triage +from .errors import MissingFeatureError from .imaging import page_documents from .layout import TextSpan, spans_of from .manifest import DEFAULT_NAME as MANIFEST_NAME @@ -240,6 +241,7 @@ def process_file( pdf_full_size: bool = False, pdf_font: str | None = None, manifest: Manifest | None = None, + orient: str | None = None, ) -> None: """OCR a single file, write Markdown output, and move it to workspace/processed/. @@ -273,14 +275,70 @@ def process_file( 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. + orient: The script to judge which way up the page is by (see + `orientation.SCRIPTS`), or None to read it as it is. + A page that needs turning is read from a turned copy, + which the searchable PDF embeds so its text layer lines + up; the scan itself moves untouched. """ + print(f" Processing: {image_path.name}") + with orientation.upright(image_path, orient) as (read_path, found): + _process_file( + image_path, + read_path, + found if orient else False, + ocr_fn, + triaged=triaged, + quality_gate=quality_gate, + backend=backend, + formats=formats, + pdf_full_size=pdf_full_size, + pdf_font=pdf_font, + manifest=manifest, + ) + + +def _process_file( + image_path: Path, + read_path: Path, + found: orientation.Orientation | bool | None, + ocr_fn: Callable[[Path], str], + triaged: list[str] | None, + quality_gate: bool, + backend: str | None, + formats: list[str] | None, + pdf_full_size: bool, + pdf_font: str | None, + manifest: Manifest | None, +) -> None: + """`process_file` once the page is upright: *read_path* is what to read and + what the outputs embed, *image_path* the scan that moves. *found* is the + orientation reading, None when the file has more than one page and was not + checked, and False when no check was asked for.""" from .qa_score import LowQualityError - print(f" Processing: {image_path.name}") file_info = telemetry.describe_file(image_path) telemetry.record("file_start", backend=backend, **file_info) started = time.perf_counter() + # Said once, then carried into the manifest row of a processed file. + turned = "" + if found is None: + turned = "orientation not checked: more than one page" + elif found: + turned = found.describe() + telemetry.record( + "orientation", + script=found.script, + turn=found.turn, + lines=round(found.lines, 3), + share=None if found.share is None else round(found.share, 3), + unsure=found.unsure, + **file_info, + ) + if turned: + print(f" {turned}") + def _elapsed() -> float: return round(time.perf_counter() - started, 3) @@ -337,11 +395,11 @@ def _triage(exc: "LowQualityError") -> None: try: if per_page: print(f" {pages} pages, transcribing individually for the PDF") - page_transcripts = transcribe_per_page(image_path, ocr_fn) + page_transcripts = transcribe_per_page(read_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) + text = ocr_fn(read_path) spans = spans_of(text) except LowQualityError as exc: if auto_local: @@ -407,7 +465,7 @@ def _triage(exc: "LowQualityError") -> None: written = [ outputs.write( name, - image_path, + read_path, text, PROCESSED_DIR, page_transcripts=page_transcripts, @@ -444,6 +502,7 @@ def _triage(exc: "LowQualityError") -> None: transcript=text, outputs=[_relative(path) for path in written], location=_relative(dest), + **({"note": turned} if turned else {}), ) telemetry.record( @@ -565,6 +624,16 @@ def main(args=None) -> int: "the transcript, the engine that read it, the quality gate's verdict and where the " "files are now, for a spreadsheet or a collections system's CSV import.", ) + parser.add_argument( + "--orient", + choices=orientation.SCRIPTS, + default=None, + metavar="SCRIPT", + help="Turn each page upright before reading it, judging which way is up by the " + f"named script ({', '.join(orientation.SCRIPTS)}). A page is turned only when the " + "reading is clear; the rest are read as they are and named. The scan itself is " + "never changed. Single-page files only; 'armenian' needs the 'orientation' extra.", + ) parser.add_argument( "--dry-run", action="store_true", @@ -609,6 +678,14 @@ def main(args=None) -> int: ) return 1 + # Likewise the orientation extra: checked before the first file, not on it. + if args.orient: + try: + orientation.require(args.orient) + except MissingFeatureError as exc: + print(f"Error: {exc}", file=sys.stderr) + return 1 + if not SCANS_DIR.exists(): print(f"Error: scans directory not found at {SCANS_DIR}", file=sys.stderr) return 1 @@ -673,6 +750,7 @@ def main(args=None) -> int: bytes_total=sum(f.stat().st_size for f in files), scans_dir=str(SCANS_DIR), quality_gate=bool(args.quality_gate), + orient=args.orient, ) if log is not None: print(f"Run log: {log.path} (run {log.run_id})\n") @@ -701,6 +779,7 @@ def main(args=None) -> int: pdf_full_size=args.pdf_full_size, pdf_font=args.pdf_font, manifest=manifest, + orient=args.orient, ) except Exception as exc: print(f" ERROR processing {f.name}: {exc}", file=sys.stderr) diff --git a/src/tetrak_ocr/cli.py b/src/tetrak_ocr/cli.py index 5105fe3..7b9b0ef 100644 --- a/src/tetrak_ocr/cli.py +++ b/src/tetrak_ocr/cli.py @@ -16,7 +16,7 @@ import sys from pathlib import Path -from . import outputs, telemetry, triage +from . import orientation, outputs, telemetry, triage from .errors import OcrPipelineError from .layout import spans_of from .registry import BACKENDS, available @@ -69,6 +69,30 @@ def _cmd_ocr(args: argparse.Namespace) -> int: ) return 2 + # A page that needs turning is read from a turned copy, and the searchable + # PDF embeds that copy so its text layer lines up with what is shown. The + # outputs are still written beside the scan, which is never changed. + if args.orient: + orientation.require(args.orient) + with orientation.upright(path, args.orient) as (source, found): + if args.orient: + print( + f"{path.name}: " + + (found.describe() if found else "orientation not checked: more than one page"), + file=sys.stderr, + ) + return _transcribe(args, ocr, path, source, requested, explicit_pdf_path) + + +def _transcribe( + args: argparse.Namespace, + ocr, + path: Path, + source: Path, + requested: list[str], + explicit_pdf_path: str | None, +) -> int: + """The rest of `ocr`: read *source*, and write what was asked for beside *path*.""" # Same rule as `batch`: a multi-page searchable PDF needs a transcript per # page, and nothing else does, so only that case pays for the per-page # pass. `--output`/stdout get the pages joined. @@ -81,12 +105,12 @@ def _cmd_ocr(args: argparse.Namespace) -> int: page_transcripts = None page_spans = None spans = None - if wants_pdf and page_count(path) > 1: - page_transcripts = transcribe_per_page(path, ocr) + if wants_pdf and page_count(source) > 1: + page_transcripts = transcribe_per_page(source, 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) + text = ocr(source) spans = spans_of(text) if explicit_pdf_path is not None: @@ -94,7 +118,7 @@ def _cmd_ocr(args: argparse.Namespace) -> int: destination = Path(explicit_pdf_path) searchable_pdf_for( - path, + source, text, destination, page_transcripts=page_transcripts, @@ -114,12 +138,12 @@ def _cmd_ocr(args: argparse.Namespace) -> int: if args.output and requested: # One format, one named file: the file is that format, written where # it was asked for, and stdout stays quiet as it does for --output. - written = outputs.write_to(requested[0], path, text, Path(args.output), **options) + written = outputs.write_to(requested[0], source, text, Path(args.output), **options) print(f"Wrote {written}", file=sys.stderr) return 0 for name in requested: - written = outputs.write(name, path, text, path.parent, **options) + written = outputs.write(name, source, text, path.parent, **options) print(f"Wrote {written}", file=sys.stderr) if args.output: @@ -144,6 +168,8 @@ def _cmd_batch(args: argparse.Namespace) -> int: forwarded.append("--with-paddle-vl") if args.quality_gate: forwarded.append("--quality-gate") + if args.orient: + forwarded += ["--orient", args.orient] if args.dry_run: forwarded.append("--dry-run") if args.telemetry: @@ -298,6 +324,18 @@ def add_pdf_flags(parser: argparse.ArgumentParser) -> None: "refused rather than written as black boxes", ) + def add_orient_flag(parser: argparse.ArgumentParser) -> None: + """Turning pages upright before reading, shared by `ocr` and `batch`.""" + parser.add_argument( + "--orient", + choices=orientation.SCRIPTS, + metavar="SCRIPT", + help="turn the page upright before reading it, judging which way is up by " + f"the named script ({', '.join(orientation.SCRIPTS)}). Turned only when the " + "reading is clear; the scan itself is never changed. Single-page files only; " + "'armenian' needs the orientation extra", + ) + p = sub.add_parser("ocr", help="OCR a single file") p.add_argument("path", help="image or PDF to transcribe") p.add_argument("--backend", default="tesseract", choices=BACKENDS) @@ -305,6 +343,7 @@ def add_pdf_flags(parser: argparse.ArgumentParser) -> None: add_tuning_flags(p) add_format_flags(p) add_pdf_flags(p) + add_orient_flag(p) p.set_defaults(func=_cmd_ocr) p = sub.add_parser("batch", help="process everything in workspace/scans/") @@ -341,6 +380,7 @@ def add_pdf_flags(parser: argparse.ArgumentParser) -> None: add_tuning_flags(p) add_format_flags(p) add_pdf_flags(p) + add_orient_flag(p) p.set_defaults(func=_cmd_batch) p = sub.add_parser( diff --git a/src/tetrak_ocr/errors.py b/src/tetrak_ocr/errors.py index 73d6ac5..948aa1d 100644 --- a/src/tetrak_ocr/errors.py +++ b/src/tetrak_ocr/errors.py @@ -35,6 +35,23 @@ def __init__(self, backend: str, extra: str, packages: str) -> None: ) +class MissingFeatureError(OcrPipelineError): + """An option was asked for whose optional dependency is not installed. + + :class:`MissingBackendError` for something that is not a backend, such as + ``--orient armenian``, so the message does not call it one. + """ + + def __init__(self, feature: str, extra: str, packages: str) -> None: + self.feature = feature + self.extra = extra + self.packages = packages + super().__init__( + f"{feature} needs {packages}, not installed here.\n" + f"Install with: pip install 'tetrak[{extra}]'" + ) + + class UnknownBackendError(OcrPipelineError): """A backend name was requested that does not exist.""" diff --git a/src/tetrak_ocr/manifest.py b/src/tetrak_ocr/manifest.py index e3d000d..410e809 100644 --- a/src/tetrak_ocr/manifest.py +++ b/src/tetrak_ocr/manifest.py @@ -65,7 +65,8 @@ - ``outputs``: the files written for it, relative to the workspace and separated by ``;``. - ``location``: where the scan is now, relative to the workspace. -- ``note``: why a file went to triage, or what went wrong. +- ``note``: why a file went to triage, or what went wrong; for a processed + file read with ``--orient``, what was done to turn it upright. - ``run``: the telemetry run id, to find the run's events in the log; empty when telemetry is off. - ``finished_at``: when the file finished, in UTC, ISO 8601. diff --git a/src/tetrak_ocr/orientation.py b/src/tetrak_ocr/orientation.py new file mode 100644 index 0000000..402b24b --- /dev/null +++ b/src/tetrak_ocr/orientation.py @@ -0,0 +1,442 @@ +"""Which way up a page is, read from the ink, and the turn that rights it. + +Scans come in on their side or on their head -- microfilm frames shot however +the pages lay, a postcard turned on the glass -- and nothing in the file says +so. This reads it from the picture, deterministically and with no model, in +two questions asked in order: + +1. **Is there text, and do its lines run across or down?** The page is cut + into a grid, and in each block holding textured ink the variance of the + row sums is set against the variance of the column sums: lines of text + make one peaky and the other flat. The median over the blocks decides, so + a gutter or a page edge that fools a few blocks does not carry the page. + This works for any script (design research 002: 220 of 221 Armenian + pages clear the threshold). It is measured at 2000 px on the long side; + at full resolution the column profile starts to resolve letter strokes + and the ratio shrinks. + +2. **With the lines across, which way is up?** This depends on the script, + which is why the caller names it rather than leaving it to be guessed: + + - **Latin**: more ink sits above a line's body (ascenders, capitals, dots) + than below it (descenders), so the share of a line's outer ink lying + above it is well over a half upright and well under on its head. It + does not hold for Armenian, whose letters put as much ink below the + line as above it (design research 002). + - **Armenian**: which way the open sides of the letters face, after + Aradhye (2005). Background enclosed by a letter's ink on three sides + and open upward (the bowl of ս) outweighs that open downward (the arch + of ո) in every Armenian face measured: 18 registers, every text page + right both ways up (design research 003). The same measure is poor on + Latin print and no better than a coin on handwriting. + + Both want detail, so they are measured at up to 4000 px (design research + 002, finding 4). + +**Unsure means untouched.** Turning a correct page upside down is worse than +leaving a wrong one alone, so a page is turned only when both answers are +clear; otherwise :class:`Orientation` says why not, for a person to check. +The margins below come from the studies' saved per-page readings, not from +judgement: inside them, every reading the studies called wrong falls. + +The Latin measures were written for the Empire on Trial reading site and are +carried here with its two corrections: adjacent maxima in a typeset line's +profile are merged before a line is judged, and an up-share resting on fewer +than half the lines the finder saw is not trusted. +""" + +from __future__ import annotations + +import math +import statistics +from collections.abc import Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path +from tempfile import TemporaryDirectory + +from PIL import Image, ImageChops, ImageFilter, ImageOps + +from .errors import MissingFeatureError, OcrPipelineError + +SCRIPTS = ("latin", "armenian") +"""The scripts whose up/down measure has been measured. Nothing else is offered.""" + +LINES_SIZE = 2000 # longest side for the line-direction vote +UP_SIZE = 4000 # longest side for the up/down measures, which need the detail +GRID = 12 # blocks per side for the line-direction vote +STRIPS = 8 # vertical strips for finding lines; each lies within one column of a spread +LINES_THRESHOLD = 1.0 # |median log variance ratio| needed to call the line direction +MIN_BLOCKS = 8 # textured blocks needed before a page's vote counts +PAPER_MIN = 96 # a median brightness below this is a title card or a void, not paper +MIN_LINES = 5 # lines needed before the Latin up-share is trusted +MIN_COMPONENTS = 50 # letter-sized shapes needed before the Armenian share is trusted + +# How far from a half a share must be before it is believed. Set from the +# studies' per-page results: for Latin, print read at native resolution has +# none wrong and 3 of 36 readings inside 0.05, the Empire on Trial manuscripts +# 2 wrong and 4 inside of 524; for Armenian, 220 text pages have none wrong +# and 10 of 440 readings inside 0.02. +MARGINS = {"latin": 0.05, "armenian": 0.02} + +_TURNS = { + 0: None, + 90: Image.Transpose.ROTATE_270, # PIL turns anticlockwise; this is a quarter turn clockwise + 180: Image.Transpose.ROTATE_180, + 270: Image.Transpose.ROTATE_90, +} + + +@dataclass(frozen=True) +class Orientation: + """What was read from one page, and the turn that rights it.""" + + script: str + turn: int # clockwise degrees that right the page: 0, 90, 180 or 270; 0 when unsure + lines: float # median log(row variance / column variance): > 0 lines run across, < 0 down + blocks: int # textured blocks that voted on the line direction + share: float | None = None # up share with the lines turned across; None when not measured + unsure: str | None = None # why the page is left as it is, or None when the reading is clear + + @property + def sideways(self) -> bool: + return self.blocks >= MIN_BLOCKS and self.lines <= -LINES_THRESHOLD + + def describe(self) -> str: + """One line for a person: what was done, or why nothing was.""" + if self.unsure: + return f"orientation unsure ({self.unsure}); read as it is" + if self.turn: + return f"turned {self.turn}° clockwise to read" + return "upright" + + +def require(script: str) -> None: + """Fail now, not on the first page, if *script* cannot be measured here.""" + if script not in SCRIPTS: + raise ValueError( + f"No orientation measure for '{script}'. Choose from: {', '.join(SCRIPTS)}" + ) + if script == "armenian": + try: + import cv2 # noqa: F401 + import numpy # noqa: F401 + except ImportError: + raise MissingFeatureError( + "--orient armenian", "orientation", "NumPy and OpenCV" + ) from None + + +def turn(image: Image.Image, degrees: int) -> Image.Image: + """Rotate clockwise by a multiple of 90 degrees.""" + method = _TURNS[degrees % 360] + return image.transpose(method) if method is not None else image + + +def detect(image: Image.Image | Path, script: str) -> Orientation: + """How many degrees clockwise turn *image* upright, for a page in *script*. + + An EXIF orientation tag is honoured first, so a frame someone has already + turned is judged as it displays. + """ + require(script) + if isinstance(image, Path): + with Image.open(image) as im: + grey = ImageOps.exif_transpose(im).convert("L") + else: + grey = ImageOps.exif_transpose(image).convert("L") + + small = grey.copy() + small.thumbnail((LINES_SIZE, LINES_SIZE)) + paper = _median(small) + if paper < PAPER_MIN: + return Orientation(script, 0, 0.0, 0, unsure="too dark to be a page of text") + lines, blocks = _line_direction(_ink(small, paper)) + + def unsure(reason: str, share: float | None = None) -> Orientation: + return Orientation(script, 0, lines, blocks, share, unsure=reason) + + if blocks < MIN_BLOCKS: + return unsure("no text to read") + if abs(lines) < LINES_THRESHOLD: + return unsure("the lines run neither clearly across nor clearly down") + + quarter = 90 if lines < 0 else 0 + across = turn(grey, quarter) + across.thumbnail((UP_SIZE, UP_SIZE)) + share = _latin_share(across) if script == "latin" else _armenian_share(across) + if share is None: + return unsure(_FEW[script]) + + margin = MARGINS[script] + if share >= 0.5 + margin: + degrees = quarter + elif share <= 0.5 - margin: + degrees = (quarter + 180) % 360 + else: + return unsure(f"cannot tell which way is up: {share:.2f} is too near a half", share) + return Orientation(script, degrees, lines, blocks, share) + + +_FEW = { + "latin": "too few clear lines of writing to tell which way is up", + "armenian": "too few letters to tell which way is up", +} + + +@contextmanager +def upright(path: Path, script: str | None) -> Iterator[tuple[Path, Orientation | None]]: + """The file to read for *path*, turned upright if it needs it. + + Yields ``(path, None)`` when *script* is None, and when the file holds + more than one page: turning a page inside a document means rewriting the + document, which this does not do. Otherwise yields the reading and the + path to transcribe -- *path* itself when no turn is needed, or a turned + PNG copy with the same stem, in a directory that lasts for the block. The + scan itself is never written to. + + A file that cannot be decoded is reported as unsure rather than raised: + the OCR that follows fails on it with the error that belongs to it. + """ + if script is None: + yield path, None + return + from .imaging import page_count + + if path.suffix.lower() == ".pdf" or page_count(path) > 1: + yield path, None + return + try: + found = detect(path, script) + except OcrPipelineError: + raise + except Exception as exc: + yield path, Orientation(script, 0, 0.0, 0, unsure=f"could not be read: {exc}") + return + if not found.turn: + yield path, found + return + with Image.open(path) as im, TemporaryDirectory(prefix="tetrak-upright-") as tmp: + copy = Path(tmp) / f"{path.stem}.png" + turn(ImageOps.exif_transpose(im), found.turn).save(copy) + yield copy, found + + +# Shared by both questions + + +def _median(grey: Image.Image) -> int: + hist = grey.histogram() + half = sum(hist) / 2 + acc = 0 + for value, count in enumerate(hist): + acc += count + if acc >= half: + return value + return 255 + + +def _ink(grey: Image.Image, paper: int) -> Image.Image: + """Ink as darkness below the local background, 0 to 255, with large dark regions + (the film border, page edges, deep shadow) filled with the paper tone first.""" + w, h = grey.size + # Quarter scale: the regions are big, and MaxFilter is slow. + dark = grey.resize((max(w // 4, 1), max(h // 4, 1)), Image.Resampling.BOX).point( + lambda v: 255 if v < 90 else 0 + ) + region = ( + dark.filter(ImageFilter.BoxBlur(2)) + .point(lambda v: 255 if v > 140 else 0) + .filter(ImageFilter.MaxFilter(5)) + ) + grey = Image.composite( + Image.new("L", grey.size, paper), grey, region.resize((w, h), Image.Resampling.NEAREST) + ) + background = grey.filter(ImageFilter.BoxBlur(12)) + # (background - grey - 15) * 4 + return ImageChops.subtract(background, grey, scale=0.25, offset=-60) + + +def _profile(ink: Image.Image, axis: int) -> list[float]: + """Mean ink per row (axis 0) or per column (axis 1), 0 to 1.""" + w, h = ink.size + strip = ink.resize((1, h) if axis == 0 else (w, 1), Image.Resampling.BOX) + return [v / 255 for v in strip.tobytes()] + + +# Question 1: which way the lines run + + +def _line_direction(ink: Image.Image) -> tuple[float, int]: + w, h = ink.size + bw, bh = w // GRID, h // GRID + votes = [] + for j in range(GRID): + for i in range(GRID): + block = ink.crop((i * bw, j * bh, (i + 1) * bw, (j + 1) * bh)) + rows, cols = _profile(block, 0), _profile(block, 1) + mean = sum(rows) / len(rows) + if not 0.005 <= mean <= 0.5: + continue # bare paper, or a solid + if max(rows) > 8 * mean or max(cols) > 8 * mean: + continue # an edge, not texture + vr, vc = statistics.pvariance(rows), statistics.pvariance(cols) + if vr + vc == 0: + continue + votes.append(math.log((vr + 1e-9) / (vc + 1e-9))) + if not votes: + return 0.0, 0 + return statistics.median(votes), len(votes) + + +# Question 2, Latin: the share of a line's outer ink above it + + +def _latin_share(grey: Image.Image) -> float | None: + """The median up-share over the lines found, or None when it is not to be trusted.""" + paper = _median(grey) + if paper < PAPER_MIN: + return None + share, found, seen = _share_above(_ink(grey, paper)) + if found < seen / 2: + return None # the finder rejected most of the lines it saw: whatever it measured, it was not the page + return share + + +def _smooth(xs: list[float], window: int) -> list[float]: + half = window // 2 + out = [] + acc = sum(xs[:half]) + n = half + for i in range(len(xs)): + if i + half < len(xs): + acc += xs[i + half] + n += 1 + if i - half - 1 >= 0: + acc -= xs[i - half - 1] + n -= 1 + out.append(acc / n) + return out + + +def _lines(rows: list[float]) -> tuple[list[tuple[int, int, int]], list[float], int]: + """Text lines in a row profile as (upper valley, peak, lower valley), keeping only + well-formed ones: a peak at least twice its valleys, each side 3 to 80 rows. Also + returns how many candidate lines there were, well-formed or not.""" + sm = _smooth(rows, 3) + n = len(sm) + peaks: list[int] = [] + for y in range(2, n - 2): + if sm[y] > sm[y - 1] and sm[y] >= sm[y + 1] and sm[y] > 0.01: + if peaks and y - peaks[-1] < 6: + if sm[y] > sm[peaks[-1]]: + peaks[-1] = y + else: + peaks.append(y) + + # A handwritten line is one hump in the profile; a typeset line is a plateau, the + # x-height body flat for ten rows or more, whose wobble reads as two or three maxima + # that the valley test below would then reject in pairs. Two maxima with no dip + # below half the lower of them between them are one line. + merged: list[int] = [] + for p in peaks: + if merged and min(sm[merged[-1] : p + 1]) > 0.5 * min(sm[merged[-1]], sm[p]): + if sm[p] > sm[merged[-1]]: + merged[-1] = p + else: + merged.append(p) + peaks = merged + + def valley(lo: int, hi: int) -> int: + # The middle of the lowest run, so neither side is favoured. + floor = min(sm[lo : hi + 1]) + idx = [y for y in range(lo, hi + 1) if sm[y] <= floor + 1e-9] + return idx[len(idx) // 2] + + lines = [] + candidates = 0 + for k, p in enumerate(peaks): + lo = peaks[k - 1] if k else max(0, p - 80) + hi = peaks[k + 1] if k + 1 < len(peaks) else min(n - 1, p + 80) + a, b = valley(lo, p), valley(p, hi) + if 3 <= p - a <= 80 and 3 <= b - p <= 80: + candidates += 1 + if max(sm[a], sm[b]) <= 0.5 * sm[p]: + lines.append((a, p, b)) + return lines, sm, candidates + + +def _share_above(ink: Image.Image) -> tuple[float | None, int, int]: + """Across all lines found, the median share of outer ink (beyond half the line's + peak height) that lies above the line rather than below it, with the number of + lines it rests on and the number of candidate lines the finder saw.""" + w, h = ink.size + sw = w // STRIPS + shares = [] + seen = 0 + for s in range(STRIPS): + lines, sm, candidates = _lines(_profile(ink.crop((s * sw, 0, (s + 1) * sw, h)), 0)) + seen += candidates + for a, p, b in lines: + half = sm[p] * 0.5 + ha = next((y for y in range(p, a - 1, -1) if sm[y] < half), a) + hb = next((y for y in range(p, b + 1) if sm[y] < half), b) + above, below = sum(sm[a:ha]), sum(sm[hb + 1 : b + 1]) + if above + below > 0: + shares.append(above / (above + below)) + if len(shares) < MIN_LINES: + return None, len(shares), seen + return statistics.median(shares), len(shares), seen + + +# Question 2, Armenian: which way the open sides of the letters face + + +def _armenian_share(grey: Image.Image) -> float | None: + """Concavity area open upward over that open upward or downward, summed over the + letter-sized shapes on the page; None when there are too few to judge.""" + import cv2 + import numpy as np + + pixels = np.asarray(grey) + background = cv2.blur(pixels, (51, 51)) + # Divide out the local background so shading and gutters do not bind to the letters. + norm = np.clip( + pixels.astype(np.float32) / np.maximum(background.astype(np.float32), 1.0) * 200.0, 0, 255 + ).astype(np.uint8) + _, ink = cv2.threshold(norm, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) + + n, labels, stats, _ = cv2.connectedComponentsWithStats(ink, connectivity=8) + body = stats[1:, cv2.CC_STAT_HEIGHT][stats[1:, cv2.CC_STAT_AREA] >= 12] + if len(body) < MIN_COMPONENTS: + return None + median_height = float(np.median(body)) + up = down = kept = 0 + for i in range(1, n): + x, y, w, h, area = stats[i] + # Letter-sized, and not shaped like a rule or a picture. + if area < 12 or not (0.5 * median_height <= h <= 2.5 * median_height): + continue + if w > 4 * h or h > 6 * max(w, 1): + continue + u, d = _open_up_down(labels[y : y + h, x : x + w] == i) + up += u + down += d + kept += 1 + if kept < MIN_COMPONENTS or up + down == 0: + return None + return up / (up + down) + + +def _open_up_down(mask) -> tuple[int, int]: + """Background within one shape enclosed by its ink left, right and on one side + vertically: the area open upward, and the area open downward.""" + import numpy as np + + above = np.maximum.accumulate(mask, axis=0) # ink at or above, per column + below = np.maximum.accumulate(mask[::-1], axis=0)[::-1] + sides = ( + np.maximum.accumulate(mask, axis=1) & np.maximum.accumulate(mask[:, ::-1], axis=1)[:, ::-1] + ) + bg = ~mask & sides + return int((bg & ~above & below).sum()), int((bg & above & ~below).sum()) diff --git a/tests/ocr/synthetic_pages.py b/tests/ocr/synthetic_pages.py new file mode 100644 index 0000000..e1c61cf --- /dev/null +++ b/tests/ocr/synthetic_pages.py @@ -0,0 +1,113 @@ +"""Synthetic page images for the orientation tests. + +Drawn from a seed rather than loaded, so the fast loop needs no data files and +no page needs a licence. Each stands in for what one of +:mod:`tetrak_ocr.orientation`'s measures reads, not for a real hand or face: + +- :func:`latin_page`: lines of zigzag letters, some with a stroke above the + line's body and fewer with one below. That is the asymmetry the Latin + up-share reads. +- :func:`armenian_page`: lines of separate u- and n-shaped letters, more of + them u. That is what the concavity share reads: in Armenian type the shapes + open upward (ս, ւ) outweigh those open downward (ո, ռ). + +Both are upright as drawn; a test turns them. +""" + +from __future__ import annotations + +import random + +from PIL import Image, ImageDraw + +PAPER = 225 +INK = 50 +SIZE = (1400, 2000) + + +def latin_page( + seed: int = 0, + lines: int | None = None, + ascenders: float = 0.45, + descenders: float = 0.12, + size: tuple[int, int] = SIZE, +) -> Image.Image: + """Handwriting-like lines; `ascenders` and `descenders` are the share of + letters with a stroke above or below the body.""" + rng = random.Random(seed) + body = 14 + + def letters(draw: ImageDraw.ImageDraw, x: int, baseline: int) -> int: + word = [] + for _ in range(rng.randint(3, 8)): + w = rng.randint(7, 12) + word += [(x, baseline), (x + w // 2, baseline - body)] + if rng.random() < ascenders: + draw.line( + [(x + w // 2, baseline - body), (x + w // 2, baseline - 2 * body)], + fill=INK, + width=2, + ) + if rng.random() < descenders: + draw.line([(x + w, baseline), (x + w, baseline + body)], fill=INK, width=2) + x += w + word.append((x, baseline)) + draw.line(word, fill=INK, width=2) + return x + + return _page(rng, size, lines, body, letters) + + +def armenian_page( + seed: int = 0, + lines: int | None = None, + open_up: float = 0.65, + size: tuple[int, int] = SIZE, +) -> Image.Image: + """Lines of separate letters, each a u (open upward) or an n (open downward); + `open_up` is the share of u.""" + rng = random.Random(seed) + body = 14 + + def letters(draw: ImageDraw.ImageDraw, x: int, baseline: int) -> int: + for _ in range(rng.randint(3, 8)): + w = rng.randint(8, 12) + top, bottom = baseline - body, baseline + if rng.random() < open_up: + shape = [(x, top), (x, bottom), (x + w, bottom), (x + w, top)] + else: + shape = [(x, bottom), (x, top), (x + w, top), (x + w, bottom)] + draw.line(shape, fill=INK, width=2) + x += w + 4 # a gap, so each letter is its own shape + return x + + return _page(rng, size, lines, body, letters) + + +def _page(rng: random.Random, size, lines, body, letters) -> Image.Image: + w, h = size + margin = 100 + pitch = 4 * body + im = Image.new("L", size, PAPER) + draw = ImageDraw.Draw(im) + baseline = margin + 2 * body + count = 0 + while baseline + 2 * body <= h - margin and (lines is None or count < lines): + right = margin + int((w - 2 * margin) * rng.uniform(0.7, 1.0)) # a ragged line end + x = margin + rng.randint(0, 30) + while x < right: + x = letters(draw, x, baseline) + rng.randint(10, 18) # the gap between words + baseline += pitch + count += 1 + return im + + +def blank(size: tuple[int, int] = SIZE) -> Image.Image: + return Image.new("L", size, PAPER) + + +def title_card(size: tuple[int, int] = SIZE) -> Image.Image: + """A dark frame, as a reel's title card or a void between frames reads.""" + im = Image.new("L", size, 30) + ImageDraw.Draw(im).rectangle((500, 900, 900, 1100), fill=230) + return im diff --git a/tests/ocr/test_orientation.py b/tests/ocr/test_orientation.py new file mode 100644 index 0000000..5dd165d --- /dev/null +++ b/tests/ocr/test_orientation.py @@ -0,0 +1,317 @@ +"""Turning pages upright before OCR (brief 020). + +On synthetic pages from `synthetic_pages.py`, drawn so that each shows the +asymmetry one measure reads. They test that the code does what the measures +say, in every turn; how well the measures do on real pages is design research +002 and 003's question, not these tests'. + +The Armenian measure needs NumPy and OpenCV (the `orientation` extra, which +`dev` installs); its tests skip without them. +""" + +from __future__ import annotations + +import csv +import importlib.util +import sys +from pathlib import Path + +import pytest +import synthetic_pages as pages +from PIL import Image, ImageChops + +from tetrak_ocr import batch, cli, orientation +from tetrak_ocr.batch import main as run_batch +from tetrak_ocr.errors import MissingFeatureError +from tetrak_ocr.orientation import Orientation + +TURNS = [0, 90, 180, 270] + +needs_cv2 = pytest.mark.skipif( + not all(importlib.util.find_spec(name) for name in ("cv2", "numpy")), + reason="needs the orientation extra", +) + + +def same(a: Image.Image, b: Image.Image) -> bool: + return a.size == b.size and ImageChops.difference(a, b).getbbox() is None + + +@pytest.fixture(scope="module") +def latin() -> Image.Image: + return pages.latin_page(seed=1) + + +@pytest.fixture(scope="module") +def armenian() -> Image.Image: + return pages.armenian_page(seed=1) + + +class TestLatin: + @pytest.mark.parametrize("filmed", TURNS) + def test_every_turn_is_righted(self, latin, filmed): + found = orientation.detect(orientation.turn(latin, filmed), "latin") + assert found.unsure is None + assert (found.turn + filmed) % 360 == 0 + assert same(orientation.turn(orientation.turn(latin, filmed), found.turn), latin) + + def test_it_reads_the_ascenders(self): + """More descenders than ascenders reads as a page on its head.""" + found = orientation.detect( + pages.latin_page(seed=2, ascenders=0.1, descenders=0.45), "latin" + ) + assert found.turn == 180 + + def test_an_even_hand_is_left_alone(self): + found = orientation.detect(pages.latin_page(seed=3, ascenders=0.3, descenders=0.3), "latin") + assert found.turn == 0 + assert "near a half" in found.unsure + + def test_a_sparse_page_still_reads(self, latin): + sparse = pages.latin_page(seed=4, lines=3) + assert orientation.detect(orientation.turn(sparse, 90), "latin").turn == 270 + + def test_an_up_share_from_few_of_the_lines_seen_is_not_trusted(self, latin, monkeypatch): + monkeypatch.setattr(orientation, "_share_above", lambda ink: (0.8, 4, 40)) + found = orientation.detect(latin, "latin") + assert found.turn == 0 + assert found.unsure == orientation._FEW["latin"] + + +@needs_cv2 +class TestArmenian: + @pytest.mark.parametrize("filmed", TURNS) + def test_every_turn_is_righted(self, armenian, filmed): + found = orientation.detect(orientation.turn(armenian, filmed), "armenian") + assert found.unsure is None + assert (found.turn + filmed) % 360 == 0 + + def test_it_reads_which_way_the_letters_open(self): + """More n-shapes than u-shapes reads as a page on its head.""" + assert orientation.detect(pages.armenian_page(seed=2, open_up=0.25), "armenian").turn == 180 + + def test_the_two_turns_mirror(self, armenian): + up = orientation.detect(armenian, "armenian").share + down = orientation.detect(orientation.turn(armenian, 180), "armenian").share + assert up + down == pytest.approx(1, abs=1e-9) + + def test_too_few_letters_is_unsure(self, armenian, monkeypatch): + monkeypatch.setattr(orientation, "MIN_COMPONENTS", 10**6) + found = orientation.detect(armenian, "armenian") + assert (found.turn, found.unsure) == (0, orientation._FEW["armenian"]) + + +class TestNothingToRead: + @pytest.mark.parametrize("script", ["latin", "armenian"]) + def test_a_blank_leaf(self, script): + if script == "armenian": + pytest.importorskip("cv2") + found = orientation.detect(pages.blank(), script) + assert (found.turn, found.unsure) == (0, "no text to read") + + def test_a_dark_frame(self): + found = orientation.detect(pages.title_card(), "latin") + assert (found.turn, found.unsure) == (0, "too dark to be a page of text") + + def test_lines_neither_across_nor_down(self, latin, monkeypatch): + monkeypatch.setattr(orientation, "_line_direction", lambda ink: (0.4, 50)) + assert "neither clearly across" in orientation.detect(latin, "latin").unsure + + +class TestExif: + def test_a_turn_already_tagged_is_honoured(self, latin, tmp_path): + """A frame someone has turned with an EXIF tag is judged as it displays.""" + exif = Image.Exif() + exif[0x0112] = 6 # stored a quarter turn left; displays after a quarter turn right + path = tmp_path / "p.jpg" + orientation.turn(latin, 270).save(path, exif=exif, quality=95) + assert orientation.detect(path, "latin").turn == 0 + + +class TestRequire: + def test_an_unmeasured_script_is_refused(self): + with pytest.raises(ValueError, match="syriac"): + orientation.require("syriac") + + def test_armenian_without_the_extra_names_it(self, monkeypatch): + monkeypatch.setitem(sys.modules, "cv2", None) # makes `import cv2` raise ImportError + with pytest.raises(MissingFeatureError, match=r"tetrak\[orientation\]"): + orientation.require("armenian") + + def test_latin_needs_nothing_extra(self, monkeypatch): + monkeypatch.setitem(sys.modules, "cv2", None) + orientation.require("latin") + + +class TestTurn: + def test_turns_are_clockwise(self, latin): + assert same(orientation.turn(latin, 90), latin.rotate(-90, expand=True)) + assert same(orientation.turn(latin, 270), latin.rotate(90, expand=True)) + + def test_zero_is_the_image_itself(self, latin): + assert orientation.turn(latin, 0) is latin + + +class TestLineFinder: + def test_a_plateau_with_two_maxima_is_one_line(self): + """A typeset line's flat body wobbles into two maxima with a shallow dip.""" + line = [0.2, 0.4, 0.6, 0.62, 0.6, 0.55, 0.5, 0.48, 0.5, 0.55, 0.6, 0.62, 0.6, 0.4, 0.2] + found, _, candidates = orientation._lines([0.0] * 20 + line + [0.0] * 20) + assert len(found) == candidates == 1 + + def test_lines_with_a_gap_stay_apart(self): + line = [0.2, 0.5, 0.6, 0.6, 0.6, 0.5, 0.2] + found, _, candidates = orientation._lines( + [0.0] * 20 + line + [0.0] * 10 + line + [0.0] * 20 + ) + assert len(found) == candidates == 2 + + +class TestDescribe: + def test_the_three_outcomes(self): + assert Orientation("latin", 90, -2.0, 50, 0.8).describe() == "turned 90° clockwise to read" + assert Orientation("latin", 0, 2.0, 50, 0.8).describe() == "upright" + assert ( + Orientation("latin", 0, 0.0, 0, unsure="no text to read").describe() + == "orientation unsure (no text to read); read as it is" + ) + + +class TestUpright: + def test_no_script_is_no_check(self, tmp_path): + path = tmp_path / "p.png" + with orientation.upright(path, None) as (read, found): + assert (read, found) == (path, None) + + def test_an_upright_page_is_read_where_it_is(self, latin, tmp_path): + path = tmp_path / "p.png" + latin.save(path) + with orientation.upright(path, "latin") as (read, found): + assert read == path + assert found.turn == 0 + + def test_a_turned_page_is_read_from_an_upright_copy(self, latin, tmp_path): + path = tmp_path / "p.tif" + orientation.turn(latin, 90).save(path) + before = path.read_bytes() + with orientation.upright(path, "latin") as (read, found): + assert found.turn == 270 + assert read != path and read.stem == path.stem and read.suffix == ".png" + with Image.open(read) as copy: + assert same(copy.convert("L"), latin) + assert not read.exists() # the copy goes when the block ends + assert path.read_bytes() == before # and the scan was never written + + def test_a_pdf_is_not_checked(self, tmp_path): + path = tmp_path / "doc.pdf" + path.write_bytes(b"%PDF-1.4\n") + with orientation.upright(path, "latin") as (read, found): + assert (read, found) == (path, None) + + def test_a_multi_page_tiff_is_not_checked(self, latin, tmp_path): + path = tmp_path / "doc.tif" + latin.save(path, save_all=True, append_images=[latin]) + with orientation.upright(path, "latin") as (read, found): + assert (read, found) == (path, None) + + def test_a_file_that_cannot_be_decoded_is_unsure_not_raised(self, tmp_path, monkeypatch): + path = tmp_path / "broken.png" + path.write_bytes(b"not a png") + monkeypatch.setattr("tetrak_ocr.imaging.page_count", lambda p: 1) + with orientation.upright(path, "latin") as (read, found): + assert read == path + assert found.turn == 0 and found.unsure.startswith("could not be read") + + +class TestBatch: + """The OCR is stubbed: what is under test is which file it was handed.""" + + @pytest.fixture + def read_paths(self, monkeypatch) -> list[Path]: + seen: list[Path] = [] + + def ocr(path: Path) -> str: + with Image.open(path) as im: + im.load() + seen.append(path) + return "A transcript" + + monkeypatch.setattr(batch, "build_ocr_fn", lambda *a, **k: ocr) + return seen + + def test_a_sideways_scan_is_read_upright_and_moved_untouched( + self, working_dirs, read_paths, latin, capsys + ): + scan = working_dirs["scans"] / "frame.png" + orientation.turn(latin, 90).save(scan) + before = scan.read_bytes() + manifest = working_dirs["scans"].parent / "manifest.csv" + + assert run_batch(["--orient", "latin", "--manifest", "--no-telemetry"]) == 0 + + (read,) = read_paths + assert read != scan and read.name == "frame.png" # a copy, named for the scan + assert (working_dirs["processed"] / "frame.png").read_bytes() == before + assert "turned 270° clockwise to read" in capsys.readouterr().out + with manifest.open(newline="", encoding="utf-8") as handle: + (row,) = csv.DictReader(handle) + assert row["note"] == "turned 270° clockwise to read" + + def test_without_the_flag_the_scan_is_read_as_it_is(self, working_dirs, read_paths, latin): + scan = working_dirs["scans"] / "frame.png" + orientation.turn(latin, 90).save(scan) + + assert run_batch(["--no-telemetry"]) == 0 + + assert read_paths == [scan] + + def test_the_pdf_embeds_the_upright_copy(self, working_dirs, read_paths, latin, monkeypatch): + """The text layer's boxes are measured on what the OCR read, so the page + the PDF shows must be that too.""" + embedded: list[Path] = [] + monkeypatch.setattr( + batch.outputs, "write", lambda name, source, *a, **k: embedded.append(source) or source + ) + orientation.turn(latin, 180).save(working_dirs["scans"] / "frame.png") + + assert run_batch(["--orient", "latin", "--format", "pdf", "--no-telemetry"]) == 0 + + assert embedded == read_paths + + def test_a_missing_extra_stops_the_run_before_any_file( + self, working_dirs, read_paths, monkeypatch, capsys + ): + scan = working_dirs["scans"] / "frame.png" + scan.touch() + monkeypatch.setitem(sys.modules, "cv2", None) + + assert run_batch(["--orient", "armenian", "--no-telemetry"]) == 1 + + assert scan.exists() and read_paths == [] + assert "tetrak[orientation]" in capsys.readouterr().err + + +class TestOcrCommand: + def test_reads_the_upright_copy_and_says_so(self, latin, tmp_path, monkeypatch, capsys): + seen: list[Path] = [] + monkeypatch.setattr( + batch, "build_ocr_fn", lambda *a, **k: lambda p: seen.append(p) or "text" + ) + scan = tmp_path / "frame.png" + orientation.turn(latin, 270).save(scan) + + assert cli.main(["ocr", str(scan), "--orient", "latin"]) == 0 + + assert seen and seen[0] != scan + captured = capsys.readouterr() + assert "frame.png: turned 90° clockwise to read" in captured.err + assert captured.out.strip() == "text" + + def test_batch_forwards_the_flag(self, monkeypatch): + seen: list[list[str]] = [] + monkeypatch.setattr(batch, "main", lambda args: seen.append(args) or 0) + + assert cli.main(["batch", "--orient", "armenian"]) == 0 + + (forwarded,) = seen + assert forwarded[forwarded.index("--orient") + 1] == "armenian"