Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions docs/guide/command-line.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/`,
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` | |

Expand Down
11 changes: 9 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -99,15 +99,22 @@ 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
# auto-local unavailable, which is the one backend the docs recommend.
# 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]
Expand Down
89 changes: 84 additions & 5 deletions src/tetrak_ocr/batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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/.

Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -407,7 +465,7 @@ def _triage(exc: "LowQualityError") -> None:
written = [
outputs.write(
name,
image_path,
read_path,
text,
PROCESSED_DIR,
page_transcripts=page_transcripts,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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)
Expand Down
54 changes: 47 additions & 7 deletions src/tetrak_ocr/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -81,20 +105,20 @@ 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:
from .pdf_output import searchable_pdf_for

destination = Path(explicit_pdf_path)
searchable_pdf_for(
path,
source,
text,
destination,
page_transcripts=page_transcripts,
Expand All @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -298,13 +324,26 @@ 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)
p.add_argument("--output", help="write to this file instead of stdout")
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/")
Expand Down Expand Up @@ -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(
Expand Down
Loading
Loading