From 2093b26c57dcbb352fd618522e5394426c978e04 Mon Sep 17 00:00:00 2001 From: Stephen Masters Date: Fri, 9 Oct 2026 13:52:42 +0100 Subject: [PATCH] docs: move the user guide to Sphinx and stub the site reference page The Sphinx site on GitHub Pages was a bare CLI and API reference, and the Hugo site carried a hand-written command-line page and a second, script-generated API page that duplicated autodoc. Both could drift from the code, and the hand-written one already had. The Sphinx site is now the user guide: installation, a quick start, guides to the command line, backend choice and the Python API, three tutorials (batching an archive, Armenian material, building a pipeline from the library), and the generated reference. Every claim was checked against the source rather than copied from the old pages. MyST heading anchors are enabled so the guide can link between its own headings. The site's /reference/cli/ page is a stub that keeps its URL and the /batch/ alias, gains a /reference/api/ alias, shows the four essential commands and links into the guide. tools/generate_api_docs.py, the `generated` shortcode, the gen:api build step and their gitignore, markdownlint and browser-test entries are gone. The site build still needs the package installed, for the band table, and the comments that said otherwise now say why. Two links on the engines page pointed into the cut pages; they point at the guide. markdownlint now covers docs/ as well. Co-authored-by: Yvette Mankerian Co-Authored-By: Claude Fable 5.1 --- .claude/skills/tetrak-ocr-design/SKILL.md | 5 +- .github/workflows/docs.yml | 20 +- .gitignore | 5 +- CLAUDE.md | 49 ++-- README.md | 2 +- docs/api.md | 5 +- docs/cli.md | 5 +- docs/conf.py | 17 +- docs/guide/backends.md | 165 +++++++++++ docs/guide/command-line.md | 323 ++++++++++++++++++++++ docs/guide/python-api.md | 294 ++++++++++++++++++++ docs/index.md | 63 ++++- docs/installation.md | 164 +++++++++++ docs/quickstart.md | 119 ++++++++ docs/tutorials/armenian.md | 148 ++++++++++ docs/tutorials/batch-an-archive.md | 231 ++++++++++++++++ docs/tutorials/scripting.md | 154 +++++++++++ site/.markdownlint-cli2.yaml | 5 +- site/content/_index.md | 5 +- site/content/reference/_index.md | 4 +- site/content/reference/cli.md | 264 +++--------------- site/content/reference/engines.md | 6 +- site/content/tutorial.md | 2 +- site/layouts/shortcodes/generated.html | 12 - site/package.json | 7 +- site/tests/site.spec.ts | 7 - tools/generate_api_docs.py | 172 ------------ 27 files changed, 1776 insertions(+), 477 deletions(-) create mode 100644 docs/guide/backends.md create mode 100644 docs/guide/command-line.md create mode 100644 docs/guide/python-api.md create mode 100644 docs/installation.md create mode 100644 docs/quickstart.md create mode 100644 docs/tutorials/armenian.md create mode 100644 docs/tutorials/batch-an-archive.md create mode 100644 docs/tutorials/scripting.md delete mode 100644 site/layouts/shortcodes/generated.html delete mode 100644 tools/generate_api_docs.py diff --git a/.claude/skills/tetrak-ocr-design/SKILL.md b/.claude/skills/tetrak-ocr-design/SKILL.md index e59fa66..476cfc2 100644 --- a/.claude/skills/tetrak-ocr-design/SKILL.md +++ b/.claude/skills/tetrak-ocr-design/SKILL.md @@ -276,7 +276,6 @@ is what makes this easy to get wrong. | `{{< tabs >}}{{< tab "macOS" >}}…{{< /tab >}}{{< /tabs >}}` | Tabbed content. The tab label is a **positional** argument | | `{{< include "LICENSING.md" >}}` | Inlines a file from the repo — positional, repo-root relative | | `{{< people >}}{{< person name="…" role="…" linkedin="handle" >}}…{{< /person >}}{{< /people >}}` | The about page's bios. `linkedin` is the **profile handle**, not the URL | -| `{{% generated %}}` | Marks a page as machine-written — used by the API reference | Both `figure` and `lightbox` call `errorf` when the asset is missing, so a bad path fails the build rather than shipping a broken image. @@ -373,7 +372,7 @@ defect is reintroduced. ## Build-time over runtime The site's priority is a fast page for the reader; a longer build is an -acceptable trade. The benchmark table, the search index, the API reference and +acceptable trade. The benchmark table, the search index, the band table and every image are built. JavaScript is reserved for what genuinely needs the browser: the search modal, the theme toggle, copy buttons, the lightbox. @@ -384,6 +383,6 @@ All run from `site/`: ```bash cd site npm run lint # ESLint, Stylelint, markdownlint -npm run build # Hugo, after regenerating the API reference +npm run build # Hugo, after regenerating the diagrams and the band table npx playwright test # starts its own server ``` diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index c578877..7dc14fb 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -17,9 +17,9 @@ # NODE_VERSION 24 # PYTHON_VERSION 3.11 # -# `pip install -e .` is not optional: prebuild regenerates -# content/reference/api.md by importing the installed package, and that file is -# gitignored rather than committed. The core dependency set is deliberately +# `pip install -e .` is not optional: prebuild runs tools/generate_tuning_data.py, +# which imports tetrak_ocr.backends.tuning to publish the auto-configuration +# bands into site/data/tuning.toml. The core dependency set is deliberately # light (Pillow, pytesseract, pdf2image, python-dotenv) -- the heavy OCR # backends are extras and are not installed for a docs build. name: Docs @@ -86,18 +86,18 @@ jobs: cache: npm cache-dependency-path: site/package-lock.json - # The API reference is generated by importing the package and reading its - # docstrings, so the package has to be installed, not just the site deps. - # Without it the generator now exits 1 rather than publishing a page of - # "Not documented" placeholders behind a green build. + # The band table is generated by importing the package, so the package + # has to be installed, not just the site deps. Without it the generator + # exits 1 rather than publishing a page with no bands behind a green + # build. - uses: actions/setup-python@v7 with: python-version: "3.11" cache: pip - name: Install the package - # From the repository root: pyproject.toml is there, and the API - # reference is generated by importing the installed package. + # From the repository root: pyproject.toml is there, and the band + # table is generated by importing the installed package. working-directory: . run: pip install -e . @@ -162,7 +162,7 @@ jobs: - name: Diagrams are rendered and committed run: node scripts/render-mermaid.mjs --check - # `npm run build` regenerates content/reference/api.md and then runs Hugo. + # `npm run build` regenerates the band table and then runs Hugo. # Hugo comes from the hugo-extended npm package, so there is no separate # install step and the version is pinned in package-lock.json. # diff --git a/.gitignore b/.gitignore index eee52dc..fd6d468 100644 --- a/.gitignore +++ b/.gitignore @@ -56,9 +56,6 @@ node_modules/ .hugo_build.lock hugo_stats.json -# Generated reference page. Rebuilt from docstrings before every build, so -# committing it would just be a second copy to go stale. -/site/content/reference/api.md test-results/ playwright-report/ @@ -68,7 +65,7 @@ tools/.image-cache/ # Sphinx build output and autosummary-generated module stubs. Regenerated by # sphinx-build on every build; committing them would be a second copy to go -# stale, same reasoning as /site/content/reference/api.md above. +# stale. /docs/_build/ /docs/generated/ diff --git a/CLAUDE.md b/CLAUDE.md index d52b905..344b690 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -2,13 +2,16 @@ Guidance for Claude Code when working in this repository. -This file is orientation and conventions. The reference material — backend -behaviour, routing, benchmark results, method and its caveats — lives in -`site/content/` and is published to Cloudflare Pages at https://tetrak.dev/. When you -need the detail, read the -site page rather than expecting to find it here, and when you change behaviour, -update that page rather than restating it here. Anything documented in two -places will drift. +This file is orientation and conventions. The documentation lives in two +places, split by what each can keep honest. How to install and use the +package — the user guide, tutorials, and the CLI and API reference generated +from the code — is `docs/`, a Sphinx site published to GitHub Pages at each +release. The research — the corpus, what each engine was measured to do, +routing, benchmark results, method and its caveats — is `site/content/`, the +Hugo site at https://tetrak.dev/. When you need the detail, read the page +rather than expecting to find it here, and when you change behaviour, update +the page rather than restating it here. Anything documented in two places +will drift. ## What this repository is @@ -69,7 +72,7 @@ EasyOCR, PaddleOCR and Marker download model weights on first use (~100 MB, ## Commands Everything runs through the `tetrak-ocr` console script. See -[`site/content/reference/cli.md`](site/content/reference/cli.md) for the full surface. +[`docs/guide/command-line.md`](docs/guide/command-line.md) for the full surface. ```bash tetrak-ocr backends # what is installed, and what each needs @@ -84,7 +87,7 @@ ruff format src tests evaluation tools cd site && npm run start # the site at :1313 cd site && npm run lint # eslint, stylelint, markdownlint; covers functions/ too -cd site && npm run build # regenerates the API reference, then Hugo +cd site && npm run build # regenerates the band table, then Hugo cd site && npx playwright test # browser checks; starts its own server python tools/generate_presentation.py # → collateral/*.pptx (gitignored), Tetrak-themed, from the benchmark python tools/generate_expected.py # regenerate ground truth; needs an API key @@ -279,7 +282,7 @@ help text and validation from that table. A writer takes `(source, transcript, destination, **options)` and must tolerate options meant for another format, because one dict is passed to all of them. Add an alias to `_ALIASES` only for a spelling people will actually type. Document it in -[`site/content/reference/cli.md`](site/content/reference/cli.md). +[`docs/guide/command-line.md`](docs/guide/command-line.md). **A telemetry event** — call `telemetry.record("", **fields)` from wherever the fact is known. The sink is process-global and a no-op when no run @@ -364,9 +367,18 @@ the page showed after the first post-split chore merge. So a change under To redeploy by hand, dispatch from `main` with the tag as an input (`gh workflow run sphinx-docs.yml --ref main -f tag=5.14.1`): the `github-pages` environment admits deployments from `main` only, so a dispatch -against the tag ref builds correctly and is then refused. It is scoped -strictly to the CLI and Python API reference; narrative content stays on the -Hugo site. +against the tag ref builds correctly and is then refused. + +What goes where: `docs/` is everything about *using* the package — +installation, the command line and Python API guides, the tutorials, and the +reference generated from the parser and the docstrings. The Hugo site is the +research: the corpus, the engines as measured, routing, results and method, +and the articles. The site's `/reference/cli/` page is a stub that links to +the guide; the generated API page it used to carry (`tools/generate_api_docs.py`) +was retired in favour of Sphinx's, so the two could not drift. Build the +Sphinx site locally with `pip install -e '.[apidocs]'` and +`sphinx-build -W -b html docs docs/_build/html`; `-W` is what CI runs, so a +warning is a failure. The Cloudflare Pages project: @@ -381,11 +393,12 @@ The Cloudflare Pages project: Two things make that build command work, and both are load-bearing: -- **`pip install -e .` comes first.** `prebuild` regenerates - `site/content/reference/api.md` by importing the installed package. The file - is gitignored, so without the install the build fails rather than shipping a - page of placeholders. Only the core dependencies are installed — the heavy OCR - backends are extras and a docs build does not need them. +- **`pip install -e .` comes first.** `prebuild` runs + `tools/generate_tuning_data.py`, which imports `tetrak_ocr.backends.tuning` + to publish the auto-configuration bands into `site/data/tuning.toml`. + Without the install the generator exits 1 rather than shipping a page with + no bands. Only the core dependencies are installed — the heavy OCR backends + are extras and a docs build does not need them. - **The mermaid SVGs are committed.** `prebuild` also runs `scripts/render-mermaid.mjs`, which now exits early when every diagram already has its rendered SVG. Cloudflare's build image has no browser and no way to diff --git a/README.md b/README.md index 8f9c145..edfe757 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ material — postcards, posters, playbills, programmes and trade papers. > Install it as `pip install tetrak`. The command it provides is still > `tetrak-ocr`, so every command below is unchanged. -**📖 [Full documentation](https://tetrak.dev/)** +**📖 [User guide and reference](https://scattercode.github.io/tetrak/)** · **[Research and benchmark](https://tetrak.dev/)** No single OCR engine wins across document types. Tetrak's answer is not to make you choose: point it at a folder and it runs several engines per file, scores diff --git a/docs/api.md b/docs/api.md index 0a3ffd8..263e1da 100644 --- a/docs/api.md +++ b/docs/api.md @@ -1,4 +1,7 @@ -# Python API +# Python API reference + +Every public module, function and class, generated from the docstrings. For +how the pieces fit together, see [using the Python API](guide/python-api.md). ```{eval-rst} .. autosummary:: diff --git a/docs/cli.md b/docs/cli.md index 3bfa699..d7d552c 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -1,6 +1,7 @@ -# Command line +# Command line reference -Installing the package provides a `tetrak-ocr` command. +Every subcommand and flag, generated from the parser. For what the flags +are for, see [using the command line](guide/command-line.md). ```{argparse} :module: tetrak_ocr.cli diff --git a/docs/conf.py b/docs/conf.py index c158b10..ebd07bf 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,8 +1,11 @@ -"""Sphinx configuration for the tetrak CLI/API reference. - -Published to GitHub Pages by .github/workflows/sphinx-docs.yml. Scoped to -CLI + Python API reference only -- narrative content (corpus, engines, -routing, licensing) lives on the Hugo site at https://tetrak.dev/. +"""Sphinx configuration for the tetrak user guide and reference. + +Published to GitHub Pages by .github/workflows/sphinx-docs.yml, at each +release. This site is how to use the package: installation, the command +line and Python API guides, tutorials, and the CLI and API reference +generated from the code. The research -- the corpus, what each engine was +measured to do, the routing evidence, the articles -- lives on the Hugo site +at https://tetrak.dev/, which links here for everything operational. """ from __future__ import annotations @@ -44,6 +47,10 @@ napoleon_numpy_docstring = True source_suffix = {".rst": "restructuredtext", ".md": "markdown"} +# The guide links to headings on other pages (`command-line.md#the-run-log`). +# MyST only resolves those when it generates anchors for headings; three +# levels covers every heading the guide links to. +myst_heading_anchors = 3 root_doc = "index" html_theme = "furo" diff --git a/docs/guide/backends.md b/docs/guide/backends.md new file mode 100644 index 0000000..a44f808 --- /dev/null +++ b/docs/guide/backends.md @@ -0,0 +1,165 @@ +# Choosing a backend + +Every backend exposes the same interface, so they are interchangeable and +selected by name with `--backend`. Seven engines, plus `auto-local`, a +strategy built on top of them. + +| Backend | Extra | PDFs | What it is | +|---|---|:--:|---| +| `tesseract` | core | ✓ | The classical engine. Fast, offline, predictable: the baseline everything else is measured against | +| `tesseract-auto` | core | ✓ | The same engine, but inspecting each image first to pick a contrast factor and page-segmentation mode per file | +| `vision` | `[vision]` | ✗ | Apple's Vision framework. macOS only, ships with the OS: no weights, no download, no network | +| `easyocr` | `[easyocr]` | ✗ | Deep-learning detector and recogniser. Handles varied contrast and awkward grounds | +| `easyocr-hy` | `[armenian]` | ✗ | EasyOCR's detector with our own Armenian recogniser behind it. See [Armenian material](#armenian-material) | +| `paddle` | `[paddle]` | ✗ | Deep-learning detector and recogniser aimed at dense small text | +| `paddle-vl` | `[paddle-vl]` | ✓ | Document vision-language model. Reads PDFs and multi-page TIFFs; strongest local engine measured, but minutes per page | +| `marker` | `[marker]` | ✓ | Layout-aware document conversion, the only local backend that models reading order | +| `claude` | `[claude]` | ✓ | The Anthropic vision API. Reads material no local tool can | +| `auto-local` | `[qa]` | ✓ | **The recommended default.** Runs the viable local engines, scores each, keeps the best | + +The measurements behind every claim on this page are on +[tetrak.dev](https://tetrak.dev/): the [engines +page](https://tetrak.dev/reference/engines/) for each backend's measured +strengths and failure cases, and the [research](https://tetrak.dev/research/) +for the full benchmark and what it does and does not establish. Figures are +deliberately not repeated here, where nothing would keep them current. + +## Which to name + +- **`tesseract-auto` over `tesseract`, always**, if you are naming a + Tesseract backend by hand. Per-image tuning takes the same engine from + nothing to a usable transcript on some of the corpus. +- **`auto-local` when you would rather not choose.** It is the best local + option measured on the corpus and also the slowest, because it runs + several engines per file. +- **`vision` is the strongest local engine measured on this corpus**, and + the fastest worth using: the model ships with macOS, so there are no + weights to download and no slow first call. It cannot read PDFs, and it + has no Armenian, Greek, Hebrew, Georgian or Indic support. +- **`marker` is slow and GPU-gated inside `auto-local`.** It is the only + local engine that gets multi-column newsprint into the right reading + order, and it is much the most expensive engine in the set. +- **`claude` sends your images to an API** and needs `ANTHROPIC_API_KEY`, + which rules it out for confidential material. It also does not reproduce + between runs: it recovers the same words and orders them differently. It + is the thing to reach for on decorative and hand-lettered type, where + local engines collapse. +- **The deep-learning backends download weights on first run** and hold them + in memory afterwards, so the first call is slow and later ones are not. + That is fine for batch work and poor for one-shot interactive use. + +## What `auto-local` does + +`auto-local` is a strategy rather than an engine. For every file it: + +1. **Works out which engines can read it**: what you have installed, + whether a GPU is present (Marker is gated on one), the platform (Vision + is macOS only), and whether the file is a PDF (Vision, EasyOCR and + PaddleOCR cannot read those). +2. **Runs each of them in turn.** Sequentially, on purpose: these engines + are individually heavy on CPU and RAM and several hold model singletons, + so running three at once costs predictability rather than buying speed. +3. **Scores every transcript** with a reference-free quality score: + dictionary coverage multiplied by inverse log-perplexity under GPT-2. No + ground truth is needed, which is what makes it work on material nobody + has transcribed. +4. **Keeps the highest scorer**, after adjusting for how much text each + candidate recovered relative to the longest, so a noisy transcript cannot + win on word count alone. + +The pool, in the order the engines run: + +| | Images | PDFs | +|---|---|---| +| GPU present and Marker installed | Marker, Vision, EasyOCR, PaddleOCR, Tesseract-auto | Marker, Tesseract-auto | +| No GPU | Vision, EasyOCR, PaddleOCR, Tesseract-auto | Tesseract-auto | + +Each only if installed. Tesseract-auto is always there, so it is the floor +rather than a choice. With `--with-paddle-vl`, PaddleOCR-VL joins both lists +and runs first; it is opt-in because it runs in minutes where the rest of +the pool runs in seconds. + +The winner then passes the quality gate. If its raw score falls below the +floor the file goes to [triage](command-line.md#the-triage-queue) with the +whole score table, which is what makes the triage manifest worth reading. +`--quality-gate` applies the same floor to any single backend. + +The scoring reads English only. On Armenian or any other non-Latin +material, `auto-local` cannot rank its candidates, so name the backend +instead. + +## Supported files + +JPEG, PNG and TIFF everywhere; PDF on `tesseract`, `tesseract-auto`, +`paddle-vl`, `marker`, `claude` and `auto-local`. The batch pipeline filters +`workspace/scans/` by the chosen backend's supported extensions, so a PDF is +silently skipped under `easyocr`, `easyocr-hy`, `paddle` or `vision`; +`--dry-run` makes that visible. + +**Multi-page TIFF is read in full or refused by name.** Pillow opens such a +file at frame 0 and says nothing about the rest, so the rule in this package +is that a multi-frame image is either read page by page or refused with +`MultiPageNotSupportedError`, which names the file, the page count and a +backend that will read it, rather than returning the cover as though it were +the whole document. The Tesseract backends and PaddleOCR-VL read every +page; the others refuse, and the batch pipeline's per-page route for +searchable PDFs is the way to put the rest of them to work on one. + +## What a run costs + +`auto-local` runs several engines per file and Marker is much the most +expensive of them, so a batch can take far longer than the file count +suggests. **Cost tracks the amount of text recovered**, not the page count +and not the file size: the recognition models decode token by token, per +region, so a dense ten-page trade weekly costs more than a 21-page +souvenir programme of light pages, and a single-page playbill of small type +costs more than a postcard. Estimate a job from how much text is on the +pages, not how many pages there are. + +If a run is taking longer than expected, `tail -f workspace/telemetry.jsonl` +shows which file and which backend it is on, with the elapsed seconds for +every engine that has finished; see [the run +log](command-line.md#the-run-log). + +To trade quality for speed, name a cheap backend instead of `auto-local`, +and keep the triage queue with `--quality-gate`: + +```bash +tetrak-ocr batch --backend tesseract-auto --quality-gate +``` + +Asking for a searchable PDF on a multi-page document roughly doubles its OCR +time, because it has to be transcribed page by page; see [multi-page +documents](command-line.md#multi-page-documents). + +## Armenian material + +`easyocr-hy` is stock EasyOCR with a different recogniser: `tetrak_hy`, +trained for the Armenian script by +[tetrak-hy-trainer](https://github.com/scattercode/tetrak-hy-trainer) and +published as +[tetrak-easyocr-armenian](https://pypi.org/project/tetrak-easyocr-armenian/). +Detection is untouched, since EasyOCR's CRAFT detector already finds Armenian +text; reading it was the missing half. Stock EasyOCR reads essentially +nothing on Armenian. + +Three steps sit between the raw recogniser and its output, and none is +retraining: a **word list** that corrects out-of-vocabulary readings from the +recogniser's own alternatives; a **script fold** that turns the Latin +look-alikes the recogniser sometimes emits inside an Armenian word back into +Armenian; and a **reading-order** pass that reads each column to its foot +before starting the next, and rejoins words a line break hyphenated. + +```bash +pip install 'tetrak[armenian]' +tetrak-ocr ocr page.png --backend easyocr-hy +``` + +The recogniser's weights download on first use, pinned to one immutable +revision per release and checksum-verified. No PDFs: convert pages to images +first. The [Armenian tutorial](../tutorials/armenian.md) walks through a +whole book. + +Tesseract can also read Armenian if its `hye` language data is installed, +through the `lang` argument of the Python API; the command line does not +expose it. diff --git a/docs/guide/command-line.md b/docs/guide/command-line.md new file mode 100644 index 0000000..9fdbd7b --- /dev/null +++ b/docs/guide/command-line.md @@ -0,0 +1,323 @@ +# Using the command line + +Installing the package provides one command, `tetrak-ocr`, with four +subcommands: + +| Subcommand | What it does | +|---|---| +| `backends` | List every backend and whether this environment can run it | +| `ocr` | Transcribe a single file, to stdout or to files beside it | +| `batch` | Transcribe everything in `workspace/scans/` | +| `evaluate` | Benchmark backends against the evaluation corpus (needs a checkout) | + +`tetrak-ocr --help` and `tetrak-ocr --help` list every flag; the +[command line reference](../cli.md) has the same text. This page is about +what the flags are for. + +Errors the package raises itself are printed as one line beginning +`error:` with the thing to do about it, such as which extra to install, +and the command exits 1. Unrecognised arguments exit 2. + +## `tetrak-ocr backends` + +```console +$ tetrak-ocr backends + ✓ tesseract + ✓ tesseract-auto + · claude (extra not installed) + ✓ auto-local +``` + +`✓` means installed and usable; `·` means the optional extra is missing. +The check is "can this actually run", not "is the package present": +`auto-local` reports as missing without the `qa` extra, and `paddle-vl` +reports as missing when `paddleocr` is installed but the pipeline it builds +cannot be constructed. + +## `tetrak-ocr ocr` + +Transcribe one file. The default is stdout; `--output` writes a file instead. + +```bash +tetrak-ocr ocr scan.jpg +tetrak-ocr ocr scan.jpg --backend tesseract-auto +tetrak-ocr ocr programme.pdf --backend marker --output programme.md +tetrak-ocr ocr faded.jpg --contrast 3.5 --psm 6 +``` + +`--backend` defaults to `tesseract`. [Choosing a backend](backends.md) is +about which to name; the short answer is `tesseract-auto` over `tesseract` +whenever you are naming a Tesseract backend by hand, and `auto-local` when +you would rather not choose. + +`--format` and the `--pdf` flags, described under [output formats](#output-formats) +below, write files beside the source under its stem and leave stdout alone. +`--pdf` here takes an optional path, so a single file can be named rather than +placed: + +```bash +tetrak-ocr ocr scan.jpg --pdf # scan.pdf beside it +tetrak-ocr ocr scan.jpg --pdf catalogue-ready.pdf # or name it +``` + +## `tetrak-ocr batch` + +The pipeline's normal mode. It uses three directories under `workspace/`, +resolved against your **current working directory**, so run it from the +folder holding your scans: + +```text +workspace/ + scans/ input: put files here + processed/ output: transcript plus the original, side by side + triage/ quarantine: files whose transcript was too poor to trust +``` + +```bash +tetrak-ocr batch --backend auto-local +``` + +For each supported file in `workspace/scans/`, the pipeline runs OCR, writes +`workspace/processed/.md`, and moves the original to +`workspace/processed/.`. Keeping the transcript beside its source +means a transcript is never orphaned from the image it came from, and +`workspace/scans/` being empty afterwards means "what is still to do?" is a +question with an answer. + +Only extensions the chosen backend supports are picked up. EasyOCR, +PaddleOCR and Vision skip PDFs, because they cannot read them; a +[dry run](#dry-runs) shows what would be skipped. + +The exit code is 0 when every file was processed or triaged, and 1 if any +file raised an error or `workspace/scans/` does not exist. Errors on one file +do not stop the batch: the file is reported and the run carries on. + +### The triage queue + +`auto-local` refuses to return a transcript whose quality score falls below +the floor (0.10, `MIN_QUALITY_THRESHOLD`). When that happens the batch +pipeline diverts the file to `workspace/triage/` along with a manifest, +`workspace/triage/.md`, recording which backends were tried, their +scores, and the first 500 characters of each transcript, so you can decide +whether to rescan, send it to Claude, or transcribe by hand. + +`--quality-gate` applies the same threshold to any single named backend: + +```bash +tetrak-ocr batch --backend tesseract-auto --quality-gate +``` + +It is opt-in for single backends because it changes which files reach +`workspace/processed/`. It needs the `qa` extra, which is checked before the +first file rather than discovered halfway through a run. + +The scoring reads English, and only English: it counts recognised English +words and measures GPT-2 perplexity. A transcript in another script would +score 0.0 however well it was read, so the gate is **skipped, with a message, +for transcripts that are not in the Latin script** rather than sending a +whole Armenian run to triage. + +### The run log + +Every batch appends to `workspace/telemetry.jsonl`, one JSON object per +line, flushed per line, so `tail -f` is a live progress view: + +```bash +tail -f workspace/telemetry.jsonl +``` + +`auto-local` prints its score table only after every backend has finished, so +without this a forty-minute file is indistinguishable from a hung one. The +log carries `run_start`, `file_start`, one `backend_finish` per engine in the +fan-out, `page_finish` when a document is transcribed page by page, +`file_finish` and `run_finish`, each with the file's path, size, type and +page count, and each backend's elapsed seconds. + +```json +{"event": "backend_finish", "file": "camera-1919.pdf", "backend": "marker", + "seconds": 2246.8, "score": 0.31, "pages": 10, "bytes": 3475030} +``` + +Because it accumulates, the log is also the dataset for asking which engines +are worth their time on your material: + +```bash +# median seconds per backend, slowest first +jq -rs 'map(select(.event=="backend_finish")) + | group_by(.backend)[] + | [.[0].backend, (length), (map(.seconds) | add / length | floor)] + | @tsv' workspace/telemetry.jsonl | sort -k3 -rn +``` + +| Flag | Effect | +|---|---| +| `--telemetry PATH` | Write the log somewhere other than the default | +| `--no-telemetry` | Do not write it | +| `TETRAK_NO_TELEMETRY=1` | The same, as an environment variable | + +A logging failure never fails a run: the log disables itself, warns once, +and the batch carries on. + +### Dry runs + +```bash +tetrak-ocr batch --backend tesseract --dry-run +``` + +Lists what would be processed without touching anything, and, just as +useful, what would be **skipped** because the chosen backend cannot read it. +The pipeline filters `workspace/scans/` by the backend's supported +extensions, so a PDF simply vanishes under `easyocr` or `paddle`; a dry run +is where that becomes visible. + +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. + +### Tuning Tesseract + +```bash +tetrak-ocr batch --backend tesseract --contrast 3.0 --psm 6 +tetrak-ocr batch --backend tesseract --auto +``` + +`--contrast` (default 2.0; try 3.0 for faded originals) and `--psm` (default +3; 3 is automatic layout, 6 a single uniform block, 11 sparse text) apply to +the Tesseract backends only. Passing them with another backend prints a note +rather than silently ignoring them. `--auto` picks both per image from the +image's own statistics and is usually better than either default; naming +`tesseract-auto` is the same thing. A value you give explicitly wins over the +automatic one. + +### Adding PaddleOCR-VL to the pool + +```bash +tetrak-ocr batch --backend auto-local --with-paddle-vl +``` + +PaddleOCR-VL measures as the strongest local backend and wins where the rest +of the pool is weakest, on dense multi-column pages, but it costs minutes per +page rather than seconds, and fan-out would pay that on every file. So it is +opt-in. The flag needs the `paddle-vl` extra and only means anything to +`auto-local`; to run the engine on its own, name it with `--backend paddle-vl`. + +## Output formats + +One OCR pass can be written several ways. `--format` (or `-f`) names the set; +it is repeatable and comma-separated, and `md`, `txt`, `plain` and +`plaintext` are accepted as aliases. + +| Format | Writes | For | +|---|---|---| +| `markdown` | `.md` | The default: the transcript under a heading | +| `text` | `.txt` | Bare transcript, for anything that will parse it | +| `pdf` | `.pdf` | Invisible text layer over the scan, for catalogue indexing | + +```bash +tetrak-ocr batch --backend auto-local --format markdown,pdf +tetrak-ocr batch --backend auto-local -f markdown -f pdf # identical +tetrak-ocr batch --backend auto-local --format text # .txt only +``` + +`--format` is a **full specification**: naming `pdf` alone writes a PDF and +no Markdown. The OCR runs once regardless of how many formats are asked for, +so the second and third cost a file write rather than another pass. + +`--pdf` predates it and stays additive, so existing commands keep working: on +`batch` it means `--format markdown,pdf`, and combined with `--format` it adds +`pdf` to whatever was named. On `ocr`, which writes nothing unless asked, +`--pdf` writes the PDF and nothing else. + +### Searchable PDFs + +The `pdf` format writes the scan with the transcript embedded as an +invisible text layer. That single file is what makes a transcript indexable +in Preservica Starter, CONTENTdm, Omeka and AtoM without asking a vendor for +anything, and it is the accessibility output too: the layer an indexer reads +is the layer a screen reader reads. + +The PDF is an **access copy**: images past 2400px on the long edge are +downsampled and JPEG-encoded, which takes a 1.1 MB postcard scan to a PDF an +institution can actually serve. `--pdf-full-size` embeds the source +untouched instead, for when the PDF is the deliverable rather than a +derivative. Both flags imply `--pdf`. + +The text layer carries whichever backend's transcript the run produced, so +it matches the `.md` sidecar exactly. Read it back with `pdftotext -raw`; +plain `pdftotext` reflows and de-hyphenates, so the two will not look +identical through it. + +The text is laid over the page rather than positioned word by word, so +selecting text in a viewer will not align with the words on the scan. That +is deliberate: a word-positioned layer measured markedly worse on reading +order, the thing a screen reader announces, on multi-column material. + +```{warning} +**Scripts the font cannot encode.** The built-in font covers Western +European text; a system Unicode font is used automatically where one is +needed and present. Where neither can encode the transcript the PDF is +refused, because the alternative is a page of black boxes that extracts as +nothing. Point `--pdf-font` at a TrueType font that covers the script. +``` + +### Multi-page documents + +A searchable PDF needs one transcript per **page**; a backend returns one per +**document**. So the `pdf` format on a multi-page PDF or TIFF transcribes it +page by page, splitting the document into single pages, which keeps the text +layer that Marker reads instead of OCR-ing, then laying each page's words +onto the page they came from. + +That costs **roughly twice the OCR time**, and it is inherent per-document +work in the engine rather than overhead that can be removed. It is paid only +when both conditions hold: the `pdf` format was requested, *and* the document +has more than one page. + +```bash +tetrak-ocr batch --backend auto-local --pdf # multi-page: ~2x, gets a PDF +tetrak-ocr batch --backend auto-local # multi-page: normal speed, no PDF +``` + +The `.md` and `.txt` come from the same pass with the pages joined, so no +document is ever transcribed twice. When the per-page route is taken the run +says so, and the log records each page as it lands: + +```text +Processing: king-of-kings-souvenir-1927.pdf + 21 pages, transcribing individually for the PDF +``` + +**Naming.** A PDF transcribed to a searchable PDF is written as +`.searchable.pdf`. It would otherwise collide with the original, which +the batch pipeline moves into the same directory, and one would silently +overwrite the other. Non-PDF sources keep the plain `.pdf`. + +## `tetrak-ocr evaluate` + +Benchmark backends against the evaluation corpus: every fixture is +transcribed and scored against its committed ground truth on character +similarity and word recall. + +```bash +tetrak-ocr evaluate --backend tesseract-auto +tetrak-ocr evaluate --all +tetrak-ocr evaluate --all --save +tetrak-ocr evaluate --backend vision --save --merge +``` + +This one needs a checkout of the repository: the corpus is not shipped in the +package, and running it elsewhere says so rather than failing obscurely. +`--all` runs every backend you have installed, side by side. `--save` writes +`evaluation/ocr/benchmark.{csv,md}` plus a dated, git-linked snapshot under +`evaluation/ocr/runs/`. `--merge`, for a single-backend run, splices that +backend's column into the committed benchmark without re-measuring the +others, which costs hours and real API spend on `claude`; it refuses if the +corpus has changed since. + +The flags are passed straight through to the harness, so +`tetrak-ocr evaluate --help` prints the harness's own help. + +```{note} +`--save` overwrites the committed benchmark with whatever it managed to run. +On a partial install, keep the output rather than committing it. +``` diff --git a/docs/guide/python-api.md b/docs/guide/python-api.md new file mode 100644 index 0000000..8bbb222 --- /dev/null +++ b/docs/guide/python-api.md @@ -0,0 +1,294 @@ +# Using the Python API + +Everything the command line does is a call into `tetrak_ocr`, and the package +is built to be used as a library: a missing optional dependency raises an +exception naming the extra to install rather than exiting the process, the +run log is a no-op until you start one, and every backend has the same shape. +This page covers the surface a caller reaches for. The [API +reference](../api.md) is generated from the docstrings and has the rest. + +## Resolve a backend + +Every backend exposes the same callable, `ocr_image(path) -> str`. Resolve +one by name through the registry rather than importing it directly, so that +a missing extra becomes an actionable error instead of a `NameError` from +deep inside the call: + +```python +from pathlib import Path +from tetrak_ocr.registry import get_backend + +ocr = get_backend("tesseract-auto") +text = ocr(Path("scan.jpg")) +``` + +The registry also answers what this machine can run: + +```python +from tetrak_ocr.registry import BACKENDS, available, is_available, supported_extensions + +BACKENDS # every name the package knows, in order +available() # the ones whose dependencies are installed here +is_available("vision") # one of them +supported_extensions("easyocr") # {'.jpg', '.jpeg', '.png', '.tif', '.tiff'} +``` + +`available()` is what `tetrak-ocr backends` prints, and the check is "can +this actually run": `auto-local` is absent without the `qa` extra. + +## Errors + +Every exception the package raises is a subclass of +`tetrak_ocr.OcrPipelineError`, so one `except` catches the lot: + +| Exception | Raised when | +|---|---| +| `UnknownBackendError` | The name does not exist. Carries `.known`, the valid names | +| `MissingBackendError` | The backend exists but its extra is not installed. Carries `.extra`, and its message is the `pip install` line | +| `UnknownFormatError` | An output format name does not exist. Carries `.valid` | +| `MultiPageNotSupportedError` | A multi-frame TIFF was given to a backend that reads only frame 0. Carries `.pages` and `.use_instead`, a backend that will read it | +| `MultiPagePdfError` | A searchable PDF was asked for on a multi-page document without per-page transcripts | + +Which makes falling back across backends straightforward: + +```python +from tetrak_ocr import MissingBackendError +from tetrak_ocr.registry import get_backend + +for name in ("vision", "easyocr", "tesseract-auto"): + try: + ocr = get_backend(name) + except MissingBackendError: + continue + break +``` + +The backends themselves raise `FileNotFoundError` for a missing file and +`ValueError` for an extension they do not support. + +## Backend options + +The `ocr_image(path) -> str` contract is fixed; some backends take optional +keyword arguments on top of it. + +**Tesseract** (`tesseract` and `tesseract-auto`) takes `contrast`, `psm`, +`auto` and `lang`. A value left as `None` with `auto=True` is filled from the +image's own statistics; a value you give wins. `lang` is a Tesseract language +code such as `"hye"` or `"hye+eng"`, which the command line does not expose: + +```python +ocr = get_backend("tesseract") +ocr(Path("faded.jpg"), contrast=3.0, psm=6) +ocr(Path("faded.jpg"), auto=True) # the same as tesseract-auto +ocr(Path("armenian.png"), auto=True, lang="hye") # needs Tesseract's hye data installed +``` + +**Vision** takes `languages`, a list of codes such as `["en-GB"]`, and +`recognition_level`, `"accurate"` (the default) or `"fast"`. Naming a +language is usually worth it on archival material, because auto-detection +on a page with little text can pick wrongly and the failure is silent. +`tetrak_ocr.backends.vision.supported_languages()` lists what this Mac's +Vision build can recognise; Apple publishes no list. + +**auto-local** takes `with_paddle_vl=True` to admit PaddleOCR-VL to the pool. + +`tetrak_ocr.batch.build_ocr_fn` is the command line's way of applying the +Tesseract and auto-local options to any backend name: it returns a +one-argument callable, and prints a note when an option is ignored by the +backend you named. + +```python +from tetrak_ocr.batch import build_ocr_fn + +ocr = build_ocr_fn("tesseract-auto", contrast=3.0) # auto PSM, your contrast +ocr = build_ocr_fn("auto-local", with_paddle_vl=True) +``` + +## Fan-out and the quality gate + +`auto-local` runs every eligible local engine on a file, scores each +transcript, and returns the best. When even the best falls below the quality +floor it raises `LowQualityError`, which carries the whole score table: + +```python +from tetrak_ocr.qa_score import LowQualityError +from tetrak_ocr.registry import get_backend + +ocr = get_backend("auto-local") +try: + text = ocr(path) +except LowQualityError as exc: + for backend, score in exc.scores.items(): + print(backend, round(score, 4), exc.transcripts[backend][:80]) +``` + +`exc.scores` and `exc.transcripts` are dicts keyed by backend name, for every +backend that ran. That is what the batch pipeline writes into a triage +manifest. + +The scoring is available on its own, for applying the same gate to any +transcript. It needs the `qa` extra, and it reads English only: + +```python +from tetrak_ocr import qa_score + +qa_score.is_available() # True when the qa extra is installed +qa_score.scores_english_text(text) # False for a transcript in another script +qa_score.combined_score(text) # dictionary coverage x inverse log-perplexity +qa_score.MIN_QUALITY_THRESHOLD # 0.10, the floor the pipeline applies +``` + +`combined_score` returns 0.0 for empty or letterless text, which is correct: +such output *is* poor. It also returns roughly 0.0 for a perfectly good +Armenian transcript, which is not, so check `scores_english_text` before +gating material that may not be English. `dictionary_coverage` and +`perplexity_score` are exposed separately. + +## Writing outputs + +`tetrak_ocr.outputs` is the format table the command line's `--format` reads +from. `write` takes a format name, the source file, the transcript and a +destination directory, and returns the path it wrote; the filename is the +source's stem plus the format's extension: + +```python +from tetrak_ocr import outputs + +for name in outputs.parse(["markdown,pdf"]): # ['markdown', 'pdf'] + written = outputs.write(name, source, text, Path("out")) +``` + +`outputs.FORMATS` lists the canonical names, `outputs.parse` resolves aliases +and both the repeated and comma-separated spellings, and +`outputs.extension(name)` gives the suffix. A PDF transcribed to the `pdf` +format is written as `.searchable.pdf`, so it cannot overwrite its own +source. + +The PDF writer takes three options through `write(..., **options)`: +`page_transcripts`, a list with one string per page, required for a +multi-page document; `pdf_full_size=True` to embed the source image untouched +rather than a downsampled access copy; and `pdf_font`, a path to a TrueType +font for scripts the built-in font cannot encode. Without a font that can +encode the transcript it raises `tetrak_ocr.pdf_output.PdfFontError` rather +than writing black boxes. + +`tetrak_ocr.pdf_output.searchable_pdf_for(path, transcript, destination, +page_transcripts=..., full_size=..., font_path=...)` is the same writer +with an explicit destination, for when the file should not be named after +its source. + +## Multi-page documents + +`tetrak_ocr.imaging` is where pages are counted and split, for PDFs and for +multi-frame TIFFs alike: + +```python +from tetrak_ocr.imaging import page_count, page_documents, iter_pages + +page_count(path) # without rendering anything + +with page_documents(path) as pages: # one single-page file per page, in a temp dir + transcripts = [ocr(page) for page in pages] + +for image in iter_pages(path): # each page as a Pillow image + ... +``` + +`page_documents` is a context manager; the files it yields are deleted on +exit. Splitting a PDF into single-page PDFs, rather than rasterising it, +keeps the text layer that Marker reads instead of OCR-ing. A single-page +document yields itself unchanged. + +`tetrak_ocr.batch.transcribe_per_page(path, ocr_fn)` does exactly the loop +above, with a `page_finish` event in the run log per page. It is what the +pipeline uses to build a multi-page searchable PDF: + +```python +from tetrak_ocr.batch import transcribe_per_page + +pages = transcribe_per_page(path, ocr) +text = "\n\n".join(t.strip() for t in pages if t.strip()) +outputs.write("pdf", path, text, Path("out"), page_transcripts=pages) +``` + +## The batch pipeline from code + +`tetrak_ocr.batch` is the `batch` subcommand. Its three directories are +module-level `Path`s relative to the current working directory +(`SCANS_DIR`, `PROCESSED_DIR`, `TRIAGE_DIR` under `WORKSPACE_DIR`), and the +tests drive a temporary directory by reassigning them. + +`process_file` does everything the pipeline does for one file: OCR, the +quality gate, every requested format, the move into `workspace/processed/`, +the triage manifest if it came to that, and the run-log events. + +```python +from tetrak_ocr import batch + +ocr = batch.build_ocr_fn("auto-local") +triaged: list[str] = [] +for path in sorted(batch.SCANS_DIR.iterdir()): + batch.process_file( + path, + ocr, + triaged=triaged, + backend="auto-local", + formats=["markdown", "pdf"], + ) +``` + +`quality_gate=True` applies the floor to a single backend's transcript, the +way `--quality-gate` does. To run the whole subcommand with its own argument +parsing, `batch.main(args=["--backend", "auto-local", "--pdf"])` returns the +exit code. + +## The run log + +`tetrak_ocr.telemetry` is the JSON Lines log that `batch` writes. It is +process-global and a no-op until a run is started, which is what keeps the +library usable as a library: + +```python +from tetrak_ocr import telemetry + +log = telemetry.start_run(backend="vision", files=12) # or start_run(path) +with telemetry.timed("backend_finish", backend="vision", **telemetry.describe_file(path)): + text = ocr(path) +telemetry.record("file_finish", outcome="processed", **telemetry.describe_file(path)) +telemetry.finish_run(processed=12) +``` + +`start_run` returns `None`, and every call stays a no-op, when +`TETRAK_NO_TELEMETRY` is set. `describe_file` gives the file's path, size, +type and page count so every event describes a file the same way. `timed` +emits its event with the elapsed seconds whether or not the block raised. A +logging failure never raises into your code: the log disables itself and +warns once. + +## Measuring against ground truth + +`tetrak_ocr.accuracy` is what the evaluation harness scores with, and it is +usable on your own material once you have a reference transcript: + +```python +from tetrak_ocr.accuracy import character_similarity, word_recall + +character_similarity(actual, expected) # 0.0 to 1.0, difflib ratio after normalisation +word_recall(actual, expected) # fraction of expected words present in actual +``` + +Both normalise first: lowercase, collapsed whitespace, and Armenian +punctuation folded onto its ASCII look-alikes, so trivial formatting +differences do not move the score. `normalise` is exposed for applying the +same treatment elsewhere. + +## The installed version + +```python +import tetrak_ocr + +tetrak_ocr.__version__ +``` + +Written from the git tag at build time; it reads `0+unknown` from an +unbuilt checkout. diff --git a/docs/index.md b/docs/index.md index 4ff216e..ad78232 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,13 +1,68 @@ -# tetrak +# Tetrak -CLI and Python API reference for [tetrak-ocr](https://github.com/scattercode/tetrak). +Local-first OCR for archival material: postcards, posters, playbills, +programmes and trade papers. Point it at a folder and it runs several engines +per file, scores what each one produced, keeps the best, and quarantines +anything it could not read well enough to trust. Everything runs on your +machine unless you explicitly ask for the Claude backend. -For research, tutorials and background on the project, see the main site at -[tetrak.dev](https://tetrak.dev/). +This site is the user guide and reference for the `tetrak` package: how to +install it, how to drive it from the command line and from Python, and what +every command, flag and function does. It is built from the released code at +each release, so what it describes is the version on PyPI. + +The research behind the tool lives on [tetrak.dev](https://tetrak.dev/): the +evaluation corpus, what each engine was measured to do and where it fails, the +evidence behind the routing, and the articles. + +## In two minutes + +```bash +pip install 'tetrak[qa]' # the package, plus quality scoring +brew install tesseract poppler # macOS; see Installation for Linux + +tetrak-ocr backends # what this machine can run +tetrak-ocr ocr scan.jpg # one file, to stdout + +mkdir -p workspace/scans +cp ~/archive/*.jpg workspace/scans/ +tetrak-ocr batch --backend auto-local # a folder, best engine per file +``` + +Transcripts land in `workspace/processed/` beside the originals; anything too +poor to trust goes to `workspace/triage/` with a note saying what was tried. +The [quick start](quickstart.md) walks through that output. ```{toctree} +:caption: Getting started +:maxdepth: 1 + +installation +quickstart +``` + +```{toctree} +:caption: User guide :maxdepth: 2 +guide/command-line +guide/backends +guide/python-api +``` + +```{toctree} +:caption: Tutorials +:maxdepth: 1 + +tutorials/batch-an-archive +tutorials/armenian +tutorials/scripting +``` + +```{toctree} +:caption: Reference +:maxdepth: 1 + cli api ``` diff --git a/docs/installation.md b/docs/installation.md new file mode 100644 index 0000000..7622af4 --- /dev/null +++ b/docs/installation.md @@ -0,0 +1,164 @@ +# Installation + +Tetrak is a Python package. It needs Python 3.11 or later, two system tools +that are not Python packages, and whichever optional OCR engines you intend to +use. + +## The package + +```bash +pip install tetrak +``` + +The distribution is `tetrak`; the command it installs is `tetrak-ocr`, and +the import package is `tetrak_ocr`. A plain install gives you Tesseract (via +`pytesseract`), image handling, PDF rasterisation and the searchable-PDF +writer: enough to process a folder of scans offline. + +Most people want more than that. The install we recommend adds quality +scoring, which is what turns on `auto-local`, the backend that runs every +engine you have and keeps the best transcript per file: + +```bash +pip install 'tetrak[qa]' +``` + +`[qa]` installs no extra *engines*. With core plus `[qa]`, `auto-local` is +choosing between one engine. Add the extras below to give it a choice. + +## System dependencies + +Two things must be installed separately, because they are binaries rather +than Python packages. **Tesseract** is the OCR engine itself; `pytesseract` +only wraps it. **Poppler** provides `pdftoppm`, which `pdf2image` shells out +to when rasterising PDF pages. Without poppler, PDF input fails with +`PDFPageCountError`, which does not look like a missing-poppler problem. + +macOS: + +```bash +brew install tesseract poppler +``` + +Debian or Ubuntu: + +```bash +sudo apt-get install tesseract-ocr poppler-utils +``` + +## Optional backends + +Every heavy engine is an extra, so you install only what you intend to use. +The difference is not marginal: the core install is a few tens of megabytes, +while `[all]` pulls PyTorch, PaddlePaddle and several sets of model weights, +well over a gigabyte before any model downloads at first run. + +| Extra | Enables | What it installs | +|---|---|---| +| `qa` | `auto-local`, `--quality-gate` | pyspellchecker, transformers, torch | +| `easyocr` | `easyocr` | EasyOCR | +| `armenian` | `easyocr-hy` | our Armenian recogniser, as an EasyOCR custom network (pulls in EasyOCR) | +| `paddle` | `paddle` | PaddleOCR and PaddlePaddle | +| `paddle-vl` | `paddle-vl` | PaddleOCR-VL, the document vision-language model in the same package | +| `marker` | `marker` | marker-pdf 1.x | +| `vision` | `vision` | `ocrmac`, a wrapper over Apple's Vision framework. macOS only | +| `claude` | `claude` | the Anthropic SDK | +| `ocr` | everything above except `armenian` | | +| `all` | the same as `ocr` | | + +```bash +pip install 'tetrak[qa,easyocr]' # a choice of two local engines +pip install 'tetrak[qa,vision]' # on a Mac: the strongest local engine measured +pip install 'tetrak[all]' # everything, several gigabytes +pip install 'tetrak[armenian]' # Armenian material +``` + +If you ask for a backend you have not installed, the error names the extra +rather than raising `ModuleNotFoundError`: + +```console +$ tetrak-ocr ocr scan.jpg --backend paddle +error: The 'paddle' backend needs the 'paddleocr' and 'paddlepaddle' packages, not installed here. +Install with: pip install 'tetrak[paddle]' +``` + +```{warning} +The `marker` extra is copyleft. `marker-pdf` and its Surya models are, as of +writing, GPL-3.0, with a commercial-use exception offered by their author. +That does not affect Tetrak itself, since extras are optional dependencies +resolved at install time and never vendored, but it does affect anyone +redistributing a bundle that includes them. Check the current terms upstream; +licence terms change. See [licensing](https://tetrak.dev/reference/licensing/). +``` + +## Model weights + +The deep-learning backends download their weights on first use and cache them +locally, so the first call in a fresh environment is slow and later ones are +not. Approximate sizes: + +| Backend | Download | Cached under | +|---|---|---| +| `easyocr` | ~100 MB | `~/.EasyOCR/` | +| `easyocr-hy` | ~15 MB for the recogniser, plus EasyOCR's detector | the EasyOCR cache | +| `paddle` | ~100 MB | `~/.paddleocr/` | +| `paddle-vl` | ~1 GB | `~/.paddlex/official_models/` | +| `marker` | ~500 MB to 1 GB | `~/.cache/marker/`, or the Hugging Face cache | +| `auto-local` (`qa`) | ~500 MB for GPT-2, used by the quality score | `~/.cache/huggingface/` | + +`vision` downloads nothing: the model ships with macOS. `tesseract` uses the +language data installed with the Tesseract binary. + +## Check what you have + +```console +$ tetrak-ocr backends + ✓ tesseract + ✓ tesseract-auto + · claude (extra not installed) + · easyocr (extra not installed) + ✓ easyocr-hy + · paddle (extra not installed) + · paddle-vl (extra not installed) + · marker (extra not installed) + ✓ vision + ✓ auto-local +``` + +A tick means installed and usable here; a dot names an extra that is +missing. The list is honest about more than packages: `auto-local` reports +as missing without the `qa` extra, because it cannot score transcripts +without it, and `vision` never appears usable off macOS. + +To see which release is installed: + +```bash +python -c "import tetrak_ocr; print(tetrak_ocr.__version__)" +``` + +## API credentials + +Only the Claude backend makes network calls. It needs an API key, read with +`python-dotenv` from a `.env` file in your working directory, or from the +environment: + +```bash +ANTHROPIC_API_KEY=sk-ant-... +``` + +If you are not using `claude`, nothing else in the package needs this. + +## For development + +```bash +git clone https://github.com/scattercode/tetrak.git +cd tetrak +python3 -m venv .venv && source .venv/bin/activate +pip install -e '.[dev]' # add extras as needed: [dev,all,armenian] is everything +pytest -m "not slow" +``` + +`-m "not slow"` skips the tests that read the evaluation corpus and invoke a +real OCR engine; it runs in well under a second. The evaluation corpus and +harness live in `evaluation/` and are not part of the installed package, so +`tetrak-ocr evaluate` only works from a checkout. diff --git a/docs/quickstart.md b/docs/quickstart.md new file mode 100644 index 0000000..93f3dd5 --- /dev/null +++ b/docs/quickstart.md @@ -0,0 +1,119 @@ +# Quick start + +Ten minutes from an installed package to a transcribed folder. It assumes you +have [installed](installation.md) the package with the `qa` extra and the two +system tools. + +## Transcribe one file + +```bash +tetrak-ocr ocr scan.jpg +``` + +That prints the transcript to stdout using Tesseract, the backend every +install has. To pick a different engine, name it: + +```bash +tetrak-ocr ocr scan.jpg --backend tesseract-auto # Tesseract, tuned per image +tetrak-ocr ocr scan.jpg --backend vision # Apple Vision, on a Mac +tetrak-ocr ocr programme.pdf --backend marker --output programme.md +``` + +`tesseract-auto` is worth knowing about straight away: it is the same engine +as `tesseract`, but it inspects each image first and picks a contrast factor +and page-segmentation mode to suit it. On faded or reversed-out material +that is the difference between a transcript and nothing at all. + +## Batch a folder + +This is what the tool is built to do. It works out of three directories +under `workspace/`, resolved against your current working directory, so run +it from the folder that holds your project: + +```text +workspace/ + scans/ input: put files here + processed/ output: transcript beside the original + triage/ quarantine: anything too poor to trust +``` + +```bash +mkdir -p workspace/scans +cp ~/archive/*.jpg workspace/scans/ +tetrak-ocr batch --backend auto-local +``` + +`auto-local` is a strategy rather than an engine. For every file it works +out which installed engines can read it, runs each in turn, scores every +transcript without needing a reference, and keeps the highest scorer. While +it runs you will see one score table per file, one row per engine that +ran, with the winner named underneath: + +```text + Processing: carthay-circle-premiere.jpg + Backend Quality Words Effective Time + -------------- ------- ----- --------- -------- + vision … + tesseract-auto … + [auto-local → vision] effective=… quality=… + → carthay-circle-premiere.jpg + → carthay-circle-premiere.md +``` + +When it finishes, each file that cleared the quality floor is in +`workspace/processed/` as a Markdown transcript, with the original moved in +beside it so the two can never be separated: + +```text +workspace/processed/ + carthay-circle-premiere.jpg ← the original, moved from scans/ + carthay-circle-premiere.md ← the transcript +``` + +`workspace/scans/` is left empty, so "what is still in scans?" always has a +meaningful answer. + +## When it cannot read something + +A failed transcript looks exactly like a successful one from the outside: it +is still a `.md` file with words in it. So a file whose best transcript still +scores below the quality floor does not reach `processed/` at all. It goes to +`workspace/triage/`, with a manifest recording every backend that was tried, +what each scored, and the first 500 characters each produced: + +```text + Processing: kar-mi-troupe-poster.jpg + → TRIAGE: kar-mi-troupe-poster.jpg + → TRIAGE: kar-mi-troupe-poster.md + +Triaged (1): kar-mi-troupe-poster.jpg +Done. 0 file(s) processed, 1 sent to triage. +``` + +The triage folder is the list of things to rescan, send to a vision model, or +transcribe by hand. The point is that bad transcripts do not quietly enter a +catalogue looking like good ones. + +## Ask for a searchable PDF + +A catalogue needs the transcript inside the file it indexes. The `pdf` +format writes the scan with the transcript embedded as an invisible text +layer, which is what Preservica, CONTENTdm, Omeka and AtoM index, and what a +screen reader reads: + +```bash +tetrak-ocr batch --backend auto-local --pdf +``` + +That writes `workspace/processed/.pdf` alongside the Markdown. The OCR +runs once however many formats you ask for. + +## Where next + +- [Using the command line](guide/command-line.md): every subcommand, the + output formats, the run log, dry runs and the evaluation harness. +- [Choosing a backend](guide/backends.md): what each engine is for, what + `auto-local` actually does, and what a run costs. +- [Batch an archive](tutorials/batch-an-archive.md): the full walk-through, + from an empty workspace to catalogue-ready PDFs and a worked triage queue. +- [Using the Python API](guide/python-api.md): the same pipeline from code. diff --git a/docs/tutorials/armenian.md b/docs/tutorials/armenian.md new file mode 100644 index 0000000..a5141a7 --- /dev/null +++ b/docs/tutorials/armenian.md @@ -0,0 +1,148 @@ +# Transcribe Armenian material + +A walk through a scanned Armenian book with `easyocr-hy`, the backend built +around our own Armenian recogniser. It assumes the package is +[installed](../installation.md) with Tesseract and poppler. + +Stock OCR engines read essentially nothing on Armenian: EasyOCR's recogniser +has never seen the script, and Apple's Vision framework has no Armenian at +all. `easyocr-hy` keeps EasyOCR's detector, which already finds Armenian +text, and swaps in `tetrak_hy`, a recogniser trained for the script. Where +it stands against the other Armenian engines, register by register, is on +[tetrak.dev](https://tetrak.dev/reference/engines/#armenian-with-our-own-recogniser). + +## 1. Install the recogniser + +```bash +pip install 'tetrak[armenian]' +tetrak-ocr backends +``` + +`easyocr-hy` should now carry a tick. The extra installs +`tetrak-easyocr-armenian`, which depends on EasyOCR, so there is nothing +else to add. The recogniser's weights (about 15 MB) and EasyOCR's detector +weights download on the first call and are cached, pinned to one immutable +revision per release and checksum-verified. + +## 2. Turn the scan into pages + +`easyocr-hy` reads JPEG, PNG and TIFF, one page at a time; it does not read +PDFs, and it refuses a multi-page TIFF rather than reading its first page +and calling that the book. So the first step for a scanned PDF is to +rasterise it, which poppler's `pdftoppm` does: + +```bash +mkdir -p workspace/scans +pdftoppm -r 300 -png book.pdf workspace/scans/book +ls workspace/scans +``` + +```text +book-01.png book-02.png book-03.png ... +``` + +300 dpi is a sensible default for printed books. The pages are named with a +zero-padded number, so they sort in order. + +## 3. Read one page + +```bash +tetrak-ocr ocr workspace/scans/book-01.png --backend easyocr-hy +``` + +The transcript comes out one line per recognised line, in reading order: +where the page is set in columns, each column is read to its foot before the +next begins, and words a line break hyphenated are rejoined. Inside an +Armenian word, Latin look-alikes the recogniser sometimes emits (an `h` for +`հ`, a colon for the Armenian full stop `։`) are folded back to Armenian, +and out-of-vocabulary readings are corrected from the recogniser's own +alternatives against a word list built from proofread Wikisource transcripts +and the Nayiri lexicon. + +## 4. Read the book + +```bash +tetrak-ocr batch --backend easyocr-hy +``` + +Each page's transcript lands in `workspace/processed/book-NN.md` with the +image moved in beside it. + +Two things are different from an English run, and both are deliberate: + +**Do not use `auto-local`.** Its quality score counts recognised English +words and measures perplexity under an English language model, so it +cannot rank Armenian candidates; a perfectly good transcript scores 0.0. +Name the backend instead. + +**`--quality-gate` is skipped, with a message.** The same score is what the +gate applies, so on a transcript that is not in the Latin script the +pipeline says so and writes the file rather than diverting an entire +Armenian run to triage and reporting every page as poor: + +```text + quality gate skipped: this transcript is not in the Latin script, and the score would be 0.0 whatever its quality +``` + +Pages with a Latin heading or a run of Russian in the apparatus are still +treated as Armenian: the check is on the share of letters, and half is the +boundary, so a page has to be mostly Latin before the gate applies. + +## 5. Make a searchable PDF + +The `pdf` format embeds the transcript as an invisible text layer, which is +what a catalogue indexes. The text layer needs a font that can encode +Armenian. The built-in font cannot; a system Unicode font is used +automatically where one is present (Arial Unicode on macOS, for example), +and where none is found the PDF is **refused** rather than written as a page +of black boxes. Point `--pdf-font` at any TrueType font that covers the +script: + +```bash +tetrak-ocr batch --backend easyocr-hy --pdf --pdf-font /path/to/NotoSansArmenian-Regular.ttf +``` + +Noto Sans Armenian and DejaVu Sans both cover it. Check the layer with +`pdftotext -raw`, which keeps the order the layer was written in: + +```bash +pdftotext -raw workspace/processed/book-01.pdf - | head +``` + +## 6. Measure it, if you have a reference + +With a proofread transcript of a page, Tetrak's own metrics say how the +backend did on it. They are what the evaluation harness scores with: + +```python +from pathlib import Path +from tetrak_ocr.accuracy import character_similarity, word_recall + +actual = Path("workspace/processed/book-01.md").read_text(encoding="utf-8") +expected = Path("reference/book-01.txt").read_text(encoding="utf-8") + +print(f"character similarity {character_similarity(actual, expected):.3f}") +print(f"word recall {word_recall(actual, expected):.3f}") +``` + +Both normalise before comparing: lowercase, collapsed whitespace, and the +Armenian full stop `։` and the one-dot leader `․` folded onto their ASCII +look-alikes, so a reference typed with ASCII punctuation is not penalised. + +## Tesseract, as a second opinion + +Tesseract reads Armenian too, if its `hye` language data is installed +(`brew install tesseract-lang` on macOS; `apt-get install tesseract-ocr-hye` +on Debian or Ubuntu). The command line does not expose a language flag, but +the Python API does: + +```python +from pathlib import Path +from tetrak_ocr.registry import get_backend + +ocr = get_backend("tesseract") +text = ocr(Path("workspace/scans/book-01.png"), auto=True, lang="hye") +``` + +`auto=True` is `tesseract-auto`: it picks a contrast factor and +page-segmentation mode from the image before reading it. diff --git a/docs/tutorials/batch-an-archive.md b/docs/tutorials/batch-an-archive.md new file mode 100644 index 0000000..7164e56 --- /dev/null +++ b/docs/tutorials/batch-an-archive.md @@ -0,0 +1,231 @@ +# Batch an archive + +A walk through the pipeline on a folder of scans, from an empty workspace to +catalogue-ready PDFs and a worked triage queue. It assumes you have +[installed](../installation.md) the package with the `qa` extra, Tesseract +and poppler, and at least one more engine for `auto-local` to choose +between: `[vision]` on a Mac, or `[easyocr]` anywhere. + +If you have a checkout of the repository, the evaluation corpus under +`evaluation/ocr/corpus/images/` is a ready-made folder of material chosen to +break OCR in different ways, and the commands below use it. Any folder of +JPEG, PNG, TIFF or PDF scans works the same way. + +## 1. Set up the workspace + +The pipeline works out of `workspace/` in your current directory, so start +from the folder you want to keep the transcripts in: + +```bash +mkdir -p workspace/scans +cp evaluation/ocr/corpus/images/* workspace/scans/ +``` + +## 2. See what would happen + +Before running anything expensive, ask what a backend would do with the +folder: + +```bash +tetrak-ocr batch --backend auto-local --dry-run +``` + +```text +Backend: auto-local (dry run) +Would process 23 file(s): + bancroft-magician-poster.jpg + camera-1919.pdf + carthay-circle-postcard-back.png + ... +``` + +Now the same for an engine that cannot read PDFs: + +```bash +tetrak-ocr batch --backend easyocr --dry-run +``` + +```text +Would skip 7 file(s) easyocr cannot read: + camera-1919.pdf + christmas-carol-1887.pdf + ... +``` + +That is the thing a dry run exists to show. The pipeline filters the folder +by what the backend declares it can read, so without this a PDF would simply +vanish from an `easyocr` run and nothing would say so. + +## 3. Run it + +```bash +tetrak-ocr batch --backend auto-local +``` + +The header names the run log, then each file gets a block. For a file that +is read well: + +```text + Processing: carthay-circle-postcard-back.png + Backend Quality Words Effective Time + -------------- ------- ----- --------- -------- + vision … + easyocr … + tesseract-auto … + [auto-local → vision] effective=… quality=… + → carthay-circle-postcard-back.png + → carthay-circle-postcard-back.md +``` + +One row per engine that ran: its raw quality score, how many words it +recovered, its score adjusted for that word count (which is what the winner +is chosen on), and how long it took. The last column is the one to watch +when a run is slow; it says which engine is spending the time. + +For a file nothing reads acceptably, the block ends differently: + +```text + Processing: kar-mi-troupe-poster.jpg + … + → TRIAGE: kar-mi-troupe-poster.jpg + → TRIAGE: kar-mi-troupe-poster.md +``` + +And the run ends with a summary: + +```text +Triaged (1): kar-mi-troupe-poster.jpg +Done. 22 file(s) processed, 1 sent to triage. +``` + +That poster is a vaudeville chromolithograph with hand-lettered display type +arched over an illustration, colour on colour. Local engines read almost +nothing on it, and that is the limit of shape-matching OCR rather than a +misconfiguration. It is worth seeing once. + +## 4. Watch a long run + +`auto-local` prints a file's score table only after every engine has +finished with it, so a file that takes forty minutes looks exactly like one +that has hung. The run log is the live view. In another terminal: + +```bash +tail -f workspace/telemetry.jsonl +``` + +Each line is one event. `file_start` says which file the run is on, one +`backend_finish` per engine says how long it took and what it scored, and +`file_finish` says where the file went. Once a run has accumulated, the log +answers which engines are worth their time on your material; see [the run +log](../guide/command-line.md#the-run-log) for a `jq` query that ranks them. + +## 5. Read the output + +```text +workspace/ + scans/ empty + processed/ + carthay-circle-postcard-back.png the original, moved here + carthay-circle-postcard-back.md its transcript + ... + triage/ + kar-mi-troupe-poster.jpg the original, moved here + kar-mi-troupe-poster.md the manifest + telemetry.jsonl +``` + +The transcript is the text under a heading: + +```markdown +# carthay-circle-postcard-back + +POST CARD +... +``` + +The triage manifest is a different kind of file. It records what every +engine produced and how each scored, so that the decision about what to do +next can be made without re-running anything: + +```markdown +# kar-mi-troupe-poster + +## Quality scores + +| Backend | Score | +|---|---| +| vision | … | +| easyocr | … | +| tesseract-auto | … | + +## Transcript excerpts + +### vision + +… +``` + +What to do with a triaged file is a judgement, and the manifest is there to +inform it. The usual options are to rescan at a higher resolution, to send +it to the Claude backend (which reads decorative and hand-lettered type that +local engines cannot, at the cost of sending the image to an API), or to +transcribe it by hand. The point of the queue is that this judgement is made +by a person, rather than a bad transcript entering the catalogue looking like +a good one. + +## 6. Send the triage queue to Claude + +The `claude` backend needs the `[claude]` extra and `ANTHROPIC_API_KEY` in +`.env` or the environment. Move the triaged originals back into the input +folder and run the single backend over them: + +```bash +mkdir -p done && mv workspace/triage/*.md done/ # keep the manifests +mv workspace/triage/*.jpg workspace/scans/ +tetrak-ocr batch --backend claude +``` + +Claude's transcripts go to `workspace/processed/` beside the others. Two +things to know before relying on it: it does not reproduce between runs, +recovering the same words in a different order, and it is the one backend +that sends your images off the machine. + +## 7. Produce catalogue-ready PDFs + +A catalogue indexes the file it holds, so the transcript needs to be inside +it. The `pdf` format writes the scan with the transcript as an invisible +text layer, which is what Preservica, CONTENTdm, Omeka and AtoM index and +what a screen reader reads. Run the batch with it from the start: + +```bash +tetrak-ocr batch --backend auto-local --format markdown,pdf +``` + +or, equivalently, `--pdf`. For a single-page scan that costs a file write. +For the 21-page programme it costs about twice the OCR time, because a +searchable PDF needs a transcript per page and the engine returns one per +document, so the pipeline transcribes it page by page and says so: + +```text + Processing: king-of-kings-souvenir-1927.pdf + 21 pages, transcribing individually for the PDF +``` + +It is written as `king-of-kings-souvenir-1927.searchable.pdf`, so it cannot +overwrite the original moved in beside it. Check the text layer with +`pdftotext -raw`, which preserves the order the layer was written in: + +```bash +pdftotext -raw workspace/processed/king-of-kings-souvenir-1927.searchable.pdf - | head +``` + +The PDF is an access copy: large images are downsampled and JPEG-encoded to +a size an institution can serve. Add `--pdf-full-size` when the PDF is the +deliverable rather than a derivative. + +## Where next + +- [Choosing a backend](../guide/backends.md) for what `auto-local` ran and + why, and when to name an engine instead. +- [Using the command line](../guide/command-line.md) for every flag. +- [Build your own pipeline](scripting.md) for the same run from Python. diff --git a/docs/tutorials/scripting.md b/docs/tutorials/scripting.md new file mode 100644 index 0000000..0e32d8d --- /dev/null +++ b/docs/tutorials/scripting.md @@ -0,0 +1,154 @@ +# Build your own pipeline + +The `batch` subcommand is one arrangement of the package's parts. When your +material needs a different one (a different folder layout, a fallback order +of your own, transcripts written somewhere other than beside the source, or a +score kept rather than acted on), the same parts assemble from Python in a +few dozen lines. This tutorial builds that script. [Using the Python +API](../guide/python-api.md) describes each piece in more detail. + +The script will: + +1. pick the best backend this machine has, falling back down a list; +2. walk a folder, taking only the files that backend can read; +3. transcribe each one, page by page where a searchable PDF needs it; +4. score the transcript where the score means something; +5. write Markdown, plain text and a searchable PDF for each file; +6. keep a run log, and report what scored poorly at the end. + +## The script + +```python +#!/usr/bin/env python3 +"""Transcribe every scan in SOURCE into DESTINATION, with a fallback across backends.""" + +from __future__ import annotations + +import sys +from pathlib import Path + +from tetrak_ocr import MissingBackendError, outputs, qa_score, telemetry +from tetrak_ocr.batch import transcribe_per_page +from tetrak_ocr.imaging import page_count +from tetrak_ocr.registry import get_backend, supported_extensions + +# Best first. Vision ships with macOS and is the strongest local engine +# measured; EasyOCR is the fallback elsewhere; Tesseract is always present. +PREFERRED = ("vision", "easyocr", "tesseract-auto") +FORMATS = ("markdown", "text", "pdf") + + +def choose_backend(): + """The first preferred backend whose extra is installed here.""" + for name in PREFERRED: + try: + return name, get_backend(name) + except MissingBackendError: + continue + raise SystemExit(f"none of {', '.join(PREFERRED)} is installed") + + +def transcribe(path: Path, ocr) -> tuple[str, list[str] | None]: + """The transcript, and the per-page transcripts when there is more than one page.""" + if page_count(path) > 1: + pages = transcribe_per_page(path, ocr) + return "\n\n".join(t.strip() for t in pages if t.strip()), pages + return ocr(path), None + + +def main(source: Path, destination: Path) -> int: + name, ocr = choose_backend() + readable = supported_extensions(name) + files = sorted(p for p in source.iterdir() if p.suffix.lower() in readable) + destination.mkdir(parents=True, exist_ok=True) + + telemetry.start_run(destination / "telemetry.jsonl", backend=name, files=len(files)) + print(f"{name}: {len(files)} file(s)") + + poor: list[str] = [] + for path in files: + info = telemetry.describe_file(path) + with telemetry.timed("file_finish", backend=name, **info): + text, pages = transcribe(path, ocr) + + # The score reads English only, so apply it only where it can + # say something, and record it rather than acting on it. + if qa_score.is_available() and qa_score.scores_english_text(text): + score = qa_score.combined_score(text) + telemetry.record("scored", score=round(score, 4), **info) + if score < qa_score.MIN_QUALITY_THRESHOLD: + poor.append(path.name) + + for fmt in FORMATS: + outputs.write(fmt, path, text, destination, page_transcripts=pages) + print(f" {path.name}") + + telemetry.finish_run(files=len(files), poor=len(poor)) + if poor: + print(f"\nscored below {qa_score.MIN_QUALITY_THRESHOLD}: {', '.join(poor)}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main(Path(sys.argv[1]), Path(sys.argv[2]))) +``` + +```bash +python transcribe.py ~/archive/scans out/ +``` + +## What each part is doing + +**Choosing a backend.** `get_backend` raises `MissingBackendError` when the +extra is not installed, so a preference list is a loop with a `continue`. +The error's message is the `pip install` line, which is worth printing if +you decide to stop instead of falling back. + +**Taking only readable files.** `supported_extensions(name)` is the +backend's own declaration. Filtering on it is what stops a PDF reaching +Vision, which cannot read one; the `batch` subcommand does the same, and +`--dry-run` is how it shows you the result. + +**Page by page when it matters.** A searchable PDF needs one transcript per +page and a backend returns one per document, so `transcribe_per_page` splits +the document into single pages and transcribes each. It costs roughly twice a +whole-document pass, which is why the script only takes that route when +`page_count` says there is more than one page. It also means a multi-page +TIFF reaches Vision one frame at a time, where the whole file would have been +refused. + +**Scoring without acting.** `combined_score` is the reference-free quality +score `auto-local` ranks with. Here it is kept in the run log and reported +at the end, so the decision about what to do with a poor transcript is left +to a person. `scores_english_text` guards it: on an Armenian page the score +would be 0.0 whatever the quality. + +**Writing formats.** `outputs.write` names the file after the source's stem +and the format's extension, and writes `.searchable.pdf` when the +source is itself a PDF. `page_transcripts` is ignored by the text formats +and required by the PDF one for a multi-page document; passing it to all of +them is fine, because every writer tolerates options meant for another. + +**The run log.** `start_run` opens the JSON Lines file and `finish_run` +closes it; between them, `timed` wraps each file with an event carrying the +elapsed seconds, success or not, and `record` adds anything else worth +keeping. `describe_file` gives every event the same file fields. With +`TETRAK_NO_TELEMETRY=1` in the environment every one of these is a no-op. + +## Variations + +- **Let `auto-local` choose, and catch its refusal.** Replace the preference + list with `get_backend("auto-local")` and wrap the call in + `except LowQualityError as exc`: `exc.scores` and `exc.transcripts` hold + every engine's result, which is what the `batch` subcommand writes into a + triage manifest. +- **Tune Tesseract.** `tetrak_ocr.batch.build_ocr_fn("tesseract-auto", + contrast=3.0)` returns a one-argument callable with the options applied, + so it drops into the script where `ocr` is. +- **Name the PDF's font.** For a script the built-in font cannot encode, + pass `pdf_font="/path/to/font.ttf"` through `outputs.write`; without a + font that can encode the transcript the PDF is refused with `PdfFontError`. +- **Re-use the pipeline's own file handling.** `tetrak_ocr.batch.process_file` + does all of the above for one file, with the triage manifest and the move + into `workspace/processed/`; it is the function the `batch` subcommand + calls per file. diff --git a/site/.markdownlint-cli2.yaml b/site/.markdownlint-cli2.yaml index db46759..e1f84d4 100644 --- a/site/.markdownlint-cli2.yaml +++ b/site/.markdownlint-cli2.yaml @@ -1,8 +1,9 @@ # Matches scattercode.dev, with two additions for this repo. ignores: - ../CLAUDE.md - # Generated from docstrings before every build, and gitignored. - - content/reference/api.md + # Sphinx output and the autosummary stubs it generates; both gitignored. + - ../docs/_build/** + - ../docs/generated/** config: MD013: false diff --git a/site/content/_index.md b/site/content/_index.md index 0fe62d5..86df72f 100644 --- a/site/content/_index.md +++ b/site/content/_index.md @@ -126,7 +126,8 @@ a four-step quick start. - **[Reference](reference/cli/)** - The command line and the [Python API](reference/api/): the backend - registry, accuracy scoring, and custom routing. + The corpus, the engines as measured, routing and licensing, and where + the [user guide](https://scattercode.github.io/tetrak/) documents the + command line and the Python API. diff --git a/site/content/reference/_index.md b/site/content/reference/_index.md index 629ff16..c9e0f7c 100644 --- a/site/content/reference/_index.md +++ b/site/content/reference/_index.md @@ -12,6 +12,6 @@ engine does and does not do, how routing decides, and the command line. and honest failure cases, including multi-page TIFF handling. - **[Routing](routing/)** — the fan-out decision table, the auto-configuration bands, the quality score and the triage gate. -- **[Command line](cli/)** — every command and flag. -- **[Python API](api/)** — generated from the package's own docstrings. +- **[Command line and Python API](cli/)** — the essentials, and where the + user guide and the generated reference live. - **[Licensing](licensing/)** — the MIT/CC-BY split covering the code and the corpus. diff --git a/site/content/reference/cli.md b/site/content/reference/cli.md index f927dfd..5dca6ce 100644 --- a/site/content/reference/cli.md +++ b/site/content/reference/cli.md @@ -1,233 +1,47 @@ --- -title: "Command line" +title: "Command line and Python API" kicker: "Reference" -aliases: ["/batch/"] +aliases: ["/batch/", "/reference/api/"] --- -Installing the package provides an `tetrak-ocr` command. +How to install and drive the package is documented in the +[user guide](https://scattercode.github.io/tetrak/), which is built from the +released code at each release, so it describes the version on PyPI and +cannot drift from it. The reference pages here are the things the code +cannot document about itself: [the corpus](corpus/), [the engines](engines/) +as measured, [routing](routing/) and [licensing](licensing/). -## `tetrak-ocr backends` - -List every backend and whether this environment can run it. `✓` means -installed and usable; `·` means the optional extra is missing. - -```console -$ tetrak-ocr backends - ✓ tesseract - ✓ tesseract-auto - · claude (extra not installed) - ✓ auto-local -``` - -## `tetrak-ocr ocr` - -Transcribe a single file to stdout, or to `--output`. - -```bash -tetrak-ocr ocr scan.jpg -tetrak-ocr ocr scan.jpg --backend tesseract-auto -tetrak-ocr ocr programme.pdf --backend marker --output programme.md -tetrak-ocr ocr faded.jpg --contrast 3.5 --psm 6 -``` - -`--contrast`, `--psm` and `--auto` tune Tesseract per image. Any backend that -does not use them says so rather than dropping them silently. - -### Output formats - -One OCR pass can be written several ways. `--format` names the set; it is -repeatable and comma-separated, and `md`, `txt` and `plaintext` are accepted as -aliases. - -| Format | Writes | For | -|---|---|---| -| `markdown` | `.md` | The default — transcript under a heading | -| `text` | `.txt` | Bare transcript, for anything that will parse it | -| `pdf` | `.pdf` | Invisible text layer over the scan, for catalogue indexing | - -```bash -tetrak-ocr batch --backend auto-local --format markdown,pdf -tetrak-ocr batch --backend auto-local -f markdown -f pdf # identical -tetrak-ocr batch --backend auto-local --format text # .txt only -``` - -`--format` is a **full specification**: naming `pdf` alone writes a PDF and no -Markdown. The OCR itself runs once regardless of how many formats are asked -for, so the second and third cost a file write rather than another pass. - -`--pdf` predates it and stays additive, so existing commands keep working: it -means `--format markdown,pdf`. - -On `tetrak-ocr ocr`, which prints to stdout by default, `--format` writes the -named files beside the source and leaves stdout alone. - -### Searchable PDFs - -The `pdf` format writes the scan with the transcript embedded as an invisible -text layer. That single file is what makes a transcript indexable in Preservica -Starter, CONTENTdm, Omeka and AtoM without asking a vendor for anything, and -it is the accessibility output too: the layer an indexer reads is the layer a -screen reader reads. - -```bash -tetrak-ocr ocr scan.jpg --pdf # scan.pdf beside it -tetrak-ocr ocr scan.jpg --pdf catalogue-ready.pdf # or name it -tetrak-ocr batch --backend auto-local --pdf # workspace/processed/.pdf -tetrak-ocr batch --backend auto-local -f pdf # the PDF alone, no .md -``` - -The PDF is an **access copy**: images past 2400px are downsampled and -JPEG-encoded, which takes a 1.1MB postcard scan to a 171KB PDF an institution -can actually serve. `--pdf-full-size` embeds the source untouched instead, for -when the PDF is the deliverable rather than a derivative. - -The text layer carries whichever backend's transcript the run produced, so it -matches the `.md` sidecar exactly. Read it back with `pdftotext -raw`; plain -`pdftotext` reflows and de-hyphenates, so the two will not look identical -through it. - -### Multi-page documents - -A searchable PDF needs one transcript per **page**; a backend returns one per -**document**. So the `pdf` format on a multi-page PDF or TIFF transcribes it -page by page — splitting a PDF into single-page PDFs, which keeps the text -layer that Marker reads instead of OCR-ing, then laying each page's words onto -the page they came from. - -That costs **roughly 2× the OCR time**, and it is inherent per-document work in -the engine rather than overhead that can be removed. It is paid only when both -conditions hold — the `pdf` format was requested, *and* the document has more -than one page: - -```bash -tetrak-ocr batch --backend auto-local --pdf # multi-page: ~2x, gets a PDF -tetrak-ocr batch --backend auto-local # multi-page: normal speed, no PDF -``` - -The `.md` and `.txt` come from the same pass, with the pages joined, so no -document is ever transcribed twice. When the per-page route is taken the run -says so, and the log records each page as it lands: - -```text -Processing: king-of-kings-souvenir-1927.pdf - 21 pages, transcribing individually for the PDF -``` - -**Naming.** A PDF transcribed to a searchable PDF is written as -`.searchable.pdf`. It would otherwise collide with the original, which -the batch pipeline moves into the same directory — and one would silently -overwrite the other. Non-PDF sources keep the plain `.pdf`. - -{{< note kind="warning" title="One thing it still refuses" >}} -**Scripts the font cannot encode.** The built-in font covers Western European -text; a system Unicode font is used automatically where one is needed and -present. Where neither can encode the transcript the PDF is refused, because -the alternative is a page of black boxes that extracts as nothing. Point -`--pdf-font` at a TrueType font that covers the script. -{{< /note >}} - -The text is laid over the page rather than positioned word by word, so -selecting text in a viewer will not align with the words on the scan. That is -deliberate: a word-positioned layer measured markedly worse on reading order — -the thing a screen reader announces — on multi-column material. - -## `tetrak-ocr batch` - -Three directories under `workspace/`, resolved against your **current working -directory** — so run it from the folder holding your scans: - -```text -workspace/ - scans/ input — put files here - processed/ output — transcript plus the original, side by side - triage/ quarantine — files whose transcript was too poor to trust -``` - -```bash -tetrak-ocr batch --backend auto-local -``` - -For each supported file in `workspace/scans/`, the pipeline runs OCR, writes -`workspace/processed/.md`, and moves the original to -`workspace/processed/.`. -Keeping the transcript beside its source means a transcript is never orphaned -from the image it came from. - -Only extensions the chosen backend supports are picked up — EasyOCR and -PaddleOCR skip PDFs, because they cannot read them. - -### The triage queue - -`auto-local` refuses to return a transcript whose quality score falls below -the floor. When that happens the batch pipeline diverts the file to -`workspace/triage/` along with a manifest recording which backends were tried, -their scores, and an excerpt of each transcript — so you can decide whether to -rescan, send it to Claude, or transcribe by hand. `--quality-gate` applies the -same threshold to any single named backend. The reasoning is on [from findings -to design](../research/in-depth/#what-the-evidence-built). - -### The run log - -Every batch appends to `workspace/telemetry.jsonl`, one JSON object per line, -flushed per line so `tail -f` is a live progress view: - -```bash -tail -f workspace/telemetry.jsonl -``` - -`auto-local` prints its score table only after every backend has finished, so -without this a forty-minute file is indistinguishable from a hung one. The log -carries `run_start`, `file_start`, one `backend_finish` per engine in the -fan-out, `file_finish` and `run_finish` — each with the file's path, size, type -and page count, and each backend's elapsed seconds. - -| Flag | Effect | -|---|---| -| `--telemetry PATH` | Write the log somewhere other than the default | -| `--no-telemetry` | Do not write it | -| `TETRAK_NO_TELEMETRY=1` | The same, as an environment variable | - -A logging failure never fails a run: the log disables itself, warns once, and -the batch carries on. - -### Dry runs - -```bash -tetrak-ocr batch --backend tesseract --dry-run -``` - -Lists what would be processed without touching anything — and, just as useful, -what would be **skipped** because the chosen backend cannot read it. The batch -pipeline filters `workspace/scans/` by the backend's supported extensions, so a -PDF simply vanishes under `easyocr` or `paddle`; a dry run is where that -becomes visible. - -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. - -### Tuning Tesseract +In brief, installing the package provides one command: ```bash -tetrak-ocr batch --backend tesseract --contrast 3.0 --psm 6 -tetrak-ocr batch --backend tesseract --auto -``` - -`--contrast` and `--psm` apply only to Tesseract; passing them with another -backend prints a note rather than silently ignoring them. `--auto` picks both -per image, and is usually better than either default — see -[the engines](engines/#tesseract-and-auto-configuration). - -## `tetrak-ocr evaluate` - -Benchmark backends against the evaluation corpus. Flags are passed straight -through to the harness. +pip install 'tetrak[qa]' # plus: brew install tesseract poppler -```bash -tetrak-ocr evaluate --backend tesseract-auto -tetrak-ocr evaluate --all -tetrak-ocr evaluate --all --save -``` - -This one needs a checkout — the corpus is not shipped in the package, so -running it elsewhere reports that rather than failing obscurely. +tetrak-ocr backends # what this machine can run +tetrak-ocr ocr scan.jpg --backend tesseract-auto +tetrak-ocr batch --backend auto-local # workspace/scans/ → processed/, failures to triage/ +tetrak-ocr evaluate --all --save # the benchmark, from a checkout +``` + +The guide covers the rest: + +- [Installation](https://scattercode.github.io/tetrak/installation.html) — the + package, the optional backend extras and what each pulls in, the system + dependencies, model weights and credentials. +- [Quick start](https://scattercode.github.io/tetrak/quickstart.html) — one + file, then a folder, and what comes back. +- [Using the command line](https://scattercode.github.io/tetrak/guide/command-line.html) + — every subcommand, the output formats and searchable PDFs, the triage + queue, the run log, dry runs and the evaluation harness. +- [Choosing a backend](https://scattercode.github.io/tetrak/guide/backends.html) + — what each engine is for, what `auto-local` does, and what a run costs. +- [Using the Python API](https://scattercode.github.io/tetrak/guide/python-api.html) + — the registry, the errors, backend options, fan-out and the quality + gate, outputs, multi-page documents, the batch pipeline and the run log + from code. +- Tutorials — [batch an archive](https://scattercode.github.io/tetrak/tutorials/batch-an-archive.html), + [transcribe Armenian material](https://scattercode.github.io/tetrak/tutorials/armenian.html) + and [build your own pipeline](https://scattercode.github.io/tetrak/tutorials/scripting.html). +- [Command line reference](https://scattercode.github.io/tetrak/cli.html) and + [Python API reference](https://scattercode.github.io/tetrak/api.html) — + every flag and every public function, generated from the parser and the + docstrings. diff --git a/site/content/reference/engines.md b/site/content/reference/engines.md index 6e58b2c..4fe2a77 100644 --- a/site/content/reference/engines.md +++ b/site/content/reference/engines.md @@ -6,7 +6,8 @@ aliases: ["/backends/", "/research/backends/"] Seven engines behind one interface, plus two strategies built on them. Every one exposes `ocr_image(path) -> str`, so they are interchangeable; resolve one by -name through the [registry](api/#registry) rather than importing it directly. +name through the [registry](https://scattercode.github.io/tetrak/guide/python-api.html#resolve-a-backend) +rather than importing it directly. | Backend | Extra needed | PDFs | Best at | |---|---|:--:|---| @@ -371,7 +372,8 @@ in the engine rather than removable overhead — reusing one Marker converter across the pages was measured and changed nothing. The cost is only paid when the `pdf` format is asked for on a document with -more than one page. See [the CLI reference](cli/#multi-page-documents). +more than one page. See [multi-page documents](https://scattercode.github.io/tetrak/guide/command-line.html#multi-page-documents) +in the user guide. {{< /note >}} The measurements behind all of this, including the experiments that came to diff --git a/site/content/tutorial.md b/site/content/tutorial.md index 628ea44..e8bb202 100644 --- a/site/content/tutorial.md +++ b/site/content/tutorial.md @@ -167,4 +167,4 @@ Provenance and rights for each are on [the corpus page](reference/corpus/). - [Choosing a tool](research/in-depth/#choosing-a-tool-for-your-own-material) — which backend for which document, with the evidence - [Results](research/in-depth/#the-results) — the full benchmark, including a retracted finding - [Method](research/in-depth/#the-weakness-at-the-centre-of-the-method) — what the numbers do and do not establish -- [Python API](reference/api/) — driving the backends from code +- [Python API](https://scattercode.github.io/tetrak/guide/python-api.html) — driving the backends from code, in the user guide diff --git a/site/layouts/shortcodes/generated.html b/site/layouts/shortcodes/generated.html deleted file mode 100644 index 93ca92c..0000000 --- a/site/layouts/shortcodes/generated.html +++ /dev/null @@ -1,12 +0,0 @@ -{{- /* - Marks a page as machine-generated, so a reader knows not to edit it and an - editor knows where the source is. -*/ -}} - diff --git a/site/package.json b/site/package.json index 4081868..1729d25 100644 --- a/site/package.json +++ b/site/package.json @@ -12,11 +12,10 @@ "lint:scripts": "eslint assets/js scripts eslint.config.mjs --no-error-on-unmatched-pattern", "lint:functions": "cd .. && eslint --config site/eslint.config.mjs functions --no-error-on-unmatched-pattern", "prepare": "cd .. && lefthook install || true", - "gen:api": "sh -c 'PY=../.venv/bin/python; [ -x \"$PY\" ] || PY=$(command -v python3); \"$PY\" ../tools/generate_api_docs.py'", - "prestart": "npm run -s gen:api && npm run -s gen:diagrams && npm run -s gen:bands", - "prebuild": "npm run -s gen:api && npm run -s gen:diagrams && npm run -s gen:bands", + "prestart": "npm run -s gen:diagrams && npm run -s gen:bands", + "prebuild": "npm run -s gen:diagrams && npm run -s gen:bands", "test:browser": "playwright test", - "lint:markdown": "markdownlint-cli2 \"../*.md\" \"content/**/*.md\"", + "lint:markdown": "markdownlint-cli2 \"../*.md\" \"content/**/*.md\" \"../docs/**/*.md\"", "audit:deps": "npm audit --audit-level=high", "postbuild": "node scripts/check-build-output.mjs", "gen:diagrams": "node scripts/render-mermaid.mjs", diff --git a/site/tests/site.spec.ts b/site/tests/site.spec.ts index 909e84a..04640c7 100644 --- a/site/tests/site.spec.ts +++ b/site/tests/site.spec.ts @@ -173,13 +173,6 @@ test("copy buttons attach to code blocks", async ({ page }) => { await expect(page.locator(".copy-btn").first()).toBeVisible(); }); -test("the API reference is generated from docstrings", async ({ page }) => { - await page.goto("reference/api/"); - await expect(page.locator(".generated-note")).toBeVisible(); - // A signature can only be here if the generator introspected the package. - await expect(page.locator("h3").first()).toContainText("get_backend"); -}); - /** * Every page on the site, read from the sitemap Hugo generates, so a page added * later is covered without anyone remembering to list it here. diff --git a/tools/generate_api_docs.py b/tools/generate_api_docs.py deleted file mode 100644 index 8ad6b76..0000000 --- a/tools/generate_api_docs.py +++ /dev/null @@ -1,172 +0,0 @@ -#!/usr/bin/env python3 -"""Generate the Python API reference from the package's own docstrings. - -Replaces mkdocstrings, which had no Hugo equivalent. Walks the public surface -of each documented module and emits Markdown into content/reference/, so -docstrings stay the single source of truth and the page cannot drift from the -code. - -Deliberately not a general-purpose autodoc tool. It documents what a caller of -this package actually reaches for -- module docstrings, public functions and -classes, their signatures and their docstrings -- and stops there. Rendering -every private helper would produce a page nobody reads and would bury the six -things that matter. - -Prerequisites: - The package importable -- `pip install -e .` -- and nothing else. It reads - signatures with `inspect`, so it needs the modules to import, which is why - every backend records a missing dependency in `_IMPORT_OK` rather than - raising. - -Run: - python tools/generate_api_docs.py - - Also runs automatically before Hugo via `npm run build`, the way velostevie - runs extract-gps. -""" - -from __future__ import annotations - -import importlib -import inspect -import sys -from pathlib import Path - -REPO_ROOT = Path(__file__).resolve().parent.parent -# The Hugo site lives in site/; the package it documents is at the root. -SITE_ROOT = REPO_ROOT / "site" -OUTPUT = SITE_ROOT / "content" / "reference" / "api.md" - -# Module -> the heading it appears under. Ordered as a reader meets them: -# resolve a backend, run it, score the result, route on the score, batch it, -# handle the errors. -MODULES: list[tuple[str, str]] = [ - ("tetrak_ocr.registry", "Registry"), - ("tetrak_ocr.accuracy", "Accuracy metrics"), - ("tetrak_ocr.qa_score", "Quality scoring"), - ("tetrak_ocr.imaging", "Image and frame handling"), - ("tetrak_ocr.auto_local", "Auto-local routing"), - ("tetrak_ocr.outputs", "Output formats"), - ("tetrak_ocr.telemetry", "Telemetry"), - ("tetrak_ocr.batch", "Batch pipeline"), - ("tetrak_ocr.errors", "Errors"), -] - -PREAMBLE = """--- -title: "Python API" -kicker: "Reference" ---- - -{{% generated %}} - -Resolve a backend by name rather than importing one directly — the registry -reports a missing optional dependency as an actionable error instead of -`ModuleNotFoundError`. - -```python -from pathlib import Path -from tetrak_ocr.registry import get_backend - -ocr = get_backend("tesseract-auto") -text = ocr(Path("scan.jpg")) -``` -""" - - -def is_public(name: str, obj: object, module_name: str) -> bool: - """Public, and defined here rather than imported from somewhere else. - - Without the module check every `from x import y` would be re-documented at - each import site, which is how autodoc output becomes noise. - """ - if name.startswith("_"): - return False - if not (inspect.isfunction(obj) or inspect.isclass(obj)): - return False - return getattr(obj, "__module__", None) == module_name - - -def signature_of(obj: object) -> str: - try: - return str(inspect.signature(obj)) - except (ValueError, TypeError): - # Builtins and C extensions have no introspectable signature. Better an - # empty pair of brackets than a crash mid-build. - return "(…)" - - -def render_member(name: str, obj: object, kind: str) -> list[str]: - lines = [f"### `{name}{signature_of(obj)}`", ""] - doc = inspect.getdoc(obj) - if doc: - lines += [doc, ""] - else: - lines += [f"*No docstring. This {kind} is public and undocumented.*", ""] - return lines - - -def render_module(module_name: str, heading: str) -> list[str]: - module = importlib.import_module(module_name) - lines = [f"## {heading}", "", f"`{module_name}`", ""] - - # The module docstring carries the reasoning -- why fan-out is sequential, - # why the quality gate is where it is. That is the part worth publishing. - doc = inspect.getdoc(module) - if doc: - lines += [doc, ""] - - members = [ - (name, obj) for name, obj in vars(module).items() if is_public(name, obj, module_name) - ] - # Source order rather than alphabetical: the author's ordering usually - # tracks how the pieces are meant to be met. - members.sort( - key=lambda item: getattr(item[1], "__code__", None) and item[1].__code__.co_firstlineno or 0 - ) - - for name, obj in members: - lines += render_member(name, obj, "class" if inspect.isclass(obj) else "function") - - return lines - - -def main() -> int: - out: list[str] = [PREAMBLE] - missing: list[str] = [] - - for module_name, heading in MODULES: - try: - out.append("\n".join(render_module(module_name, heading))) - except ImportError as exc: - # A module whose optional extra is absent is skipped with a note - # rather than silently omitted -- a reference page with a hole in - # it and no explanation is worse than one that says why. - missing.append(f"{module_name} ({exc})") - out.append( - f"## {heading}\n\n*Not documented: `{module_name}` could not be imported.*\n" - ) - - # Every module failing means the package is not importable at all -- a - # setup problem, not a missing optional extra. Writing a page of "Not - # documented" placeholders and exiting 0 is how a hollow reference gets - # published while the build stays green; it happened once already. - if len(missing) == len(MODULES): - print( - "generate_api_docs: could not import tetrak_ocr at all.\n" - " Install the package first: pip install -e .\n" - " Refusing to write a reference page with no content in it.", - file=sys.stderr, - ) - return 1 - - OUTPUT.parent.mkdir(parents=True, exist_ok=True) - OUTPUT.write_text("\n".join(out), encoding="utf-8") - - print(f"Wrote {OUTPUT.relative_to(REPO_ROOT)} from {len(MODULES) - len(missing)} modules") - for m in missing: - print(f" ! skipped {m}") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main())