From 6e0dc16be88256d1019b2d24d20cde750360ef33 Mon Sep 17 00:00:00 2001 From: Stephen Masters Date: Sat, 24 Oct 2026 13:53:56 +0100 Subject: [PATCH] feat(triage): keep every candidate's transcript and list the queue locally A file held by the quality gate kept only a 500-character excerpt of each candidate transcript in its Markdown manifest, so the decision about it was often made on a fragment and a view of the queue could not show what was never saved (brief 001). `batch` now writes, beside the unchanged manifest, a `.json` record -- every candidate's score, the reason the file was held, when, and where each transcript is -- and each candidate's full transcript as `..txt`. `tetrak-ocr triage` lists the queue from those records, and `--serve` serves it as a page: each file, its best score, the engine and the reason held. The server binds to the loopback address and nothing else, with no flag to bind elsewhere, answers GET for `/` only and serves no files. A directory written by an older release lists its manifests by name, and an empty or missing directory is reported as empty rather than failing. Closes scattercode/tetrak#26 Closes scattercode/tetrak#27 Co-authored-by: Yvette Mankerian Co-Authored-By: Claude Fable 5.1 --- AGENTS.md | 1 + README.md | 6 + docs/guide/command-line.md | 42 +++++- src/tetrak_ocr/batch.py | 25 +++- src/tetrak_ocr/cli.py | 40 ++++- src/tetrak_ocr/triage.py | 299 +++++++++++++++++++++++++++++++++++++ tests/ocr/test_batch.py | 72 +++++++++ tests/ocr/test_cli.py | 41 +++++ tests/ocr/test_triage.py | 188 +++++++++++++++++++++++ 9 files changed, 703 insertions(+), 11 deletions(-) create mode 100644 src/tetrak_ocr/triage.py create mode 100644 tests/ocr/test_triage.py diff --git a/AGENTS.md b/AGENTS.md index 65c5f95..517ff54 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -82,6 +82,7 @@ Everything runs through the `tetrak-ocr` console script. See tetrak-ocr backends # what is installed, and what each needs tetrak-ocr ocr --backend tesseract-auto tetrak-ocr batch --backend auto-local # workspace/: scans/ → processed/, failures to triage/ +tetrak-ocr triage --serve # what triage/ holds, as a page on 127.0.0.1 only tetrak-ocr evaluate --all --save # → evaluation/ocr/benchmark.{csv,md} + runs/ python -m evaluation.ocr.reading_order --save # → evaluation/ocr/reading_order.{csv,md}: column-aware order vs a positioned layer's diff --git a/README.md b/README.md index cf70345..10000a9 100644 --- a/README.md +++ b/README.md @@ -106,6 +106,7 @@ Processing: kar-mi-troupe-poster.jpg quality=0.0618 → TRIAGE: kar-mi-troupe-poster.jpg → TRIAGE: kar-mi-troupe-poster.md + → TRIAGE: kar-mi-troupe-poster.json (+ 4 full transcript(s)) Triaged (1): kar-mi-troupe-poster.jpg Done. 0 file(s) processed, 1 sent to triage. @@ -117,6 +118,11 @@ it. The triage queue is what stops bad transcripts quietly entering a catalogue looking like good ones, and turns "which ones did it get wrong?" into a folder you can actually work through. +Beside the manifest, every candidate's full transcript is kept and a `.json` +record says what scored what and why the file was held. `tetrak-ocr triage` +lists the queue, and `tetrak-ocr triage --serve` shows it as a page on your +own machine only. + ### Output formats By default each transcript is written as Markdown. `--format` asks for others, diff --git a/docs/guide/command-line.md b/docs/guide/command-line.md index 4ac457b..1ff13f1 100644 --- a/docs/guide/command-line.md +++ b/docs/guide/command-line.md @@ -1,6 +1,6 @@ # Using the command line -Installing the package provides one command, `tetrak-ocr`, with four +Installing the package provides one command, `tetrak-ocr`, with five subcommands: | Subcommand | What it does | @@ -8,6 +8,7 @@ subcommands: | `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/` | +| `triage` | List what `batch` held back, or serve it as a local page | | `evaluate` | Benchmark backends against the evaluation corpus (needs a checkout) | `tetrak-ocr --help` and `tetrak-ocr --help` list every flag; the @@ -103,10 +104,17 @@ do not stop the batch: the file is reported and the run carries on. `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. +pipeline diverts the file to `workspace/triage/` along with three kinds of +file, so you can decide whether to rescan, send it to Claude, or transcribe +by hand: + +| File | What it holds | +|---|---| +| `.md` | A manifest for reading: which backends were tried, their scores, and the first 500 characters of each transcript | +| `.json` | A record for software: every candidate's score, the reason the file was held, when, and where each full transcript is | +| `..txt` | Each candidate's transcript, whole | + +[`tetrak-ocr triage`](#tetrak-ocr-triage) lists the queue from the records. `--quality-gate` applies the same threshold to any single named backend: @@ -353,6 +361,30 @@ Processing: king-of-kings-souvenir-1927.pdf the batch pipeline moves into the same directory, and one would silently overwrite the other. Non-PDF sources keep the plain `.pdf`. +## `tetrak-ocr triage` + +What `batch` held back, from the records in `workspace/triage/`: each file, +its best score, the engine that produced it and the reason it was held. + +```bash +tetrak-ocr triage # a table in the terminal +tetrak-ocr triage --serve # the same as a page, at http://127.0.0.1:8321/ +tetrak-ocr triage --serve --port 9000 +tetrak-ocr triage --dir ../other/triage +``` + +`--serve` binds to the loopback address and nothing else, and there is no +flag to change that. The page reads a local directory for the person at the +machine, so there is nothing to authenticate and nothing remote, and it +answers one address, `/`, with GET; it serves no files. It is read-only: +triage stays passive, and the page re-reads the directory on every request, +so it follows a batch that is still running. Stop it with Ctrl-C. + +A directory written by a release before 5.19 holds manifests without +records. Those files are still listed, by name, with a note to read the +manifest; an empty or missing directory is reported as empty rather than as +an error. + ## `tetrak-ocr evaluate` Benchmark backends against the evaluation corpus: every fixture is diff --git a/src/tetrak_ocr/batch.py b/src/tetrak_ocr/batch.py index 2fbad63..b292256 100644 --- a/src/tetrak_ocr/batch.py +++ b/src/tetrak_ocr/batch.py @@ -29,7 +29,7 @@ if TYPE_CHECKING: # pragma: no cover from .qa_score import LowQualityError -from . import outputs, telemetry +from . import outputs, telemetry, triage from .imaging import page_documents from .layout import TextSpan, spans_of from .manifest import DEFAULT_NAME as MANIFEST_NAME @@ -138,15 +138,20 @@ def supported_extensions(backend: str) -> set[str]: return _registry_extensions(backend) -def _send_to_triage(image_path: Path, error: "LowQualityError") -> None: - """Move a file to the triage queue and write its manifest. +def _send_to_triage(image_path: Path, error: "LowQualityError", backend: str | None = None) -> None: + """Move a file to the triage queue and write its manifest and record. The manifest (workspace/triage/.md) contains a score table and a short - excerpt from each backend's transcript for human review. + excerpt from each backend's transcript for human review, and is written + exactly as it always has been. Beside it, :mod:`tetrak_ocr.triage` writes + the record (.json: the scores, the reason, where each transcript + is) and every candidate's full transcript, which the manifest's 500 + character excerpts used to discard. Args: image_path: Original file path (inside workspace/scans/). error: LowQualityError carrying .scores and .transcripts. + backend: The backend the run asked for, recorded with the item. """ TRIAGE_DIR.mkdir(parents=True, exist_ok=True) @@ -169,11 +174,21 @@ def _send_to_triage(image_path: Path, error: "LowQualityError") -> None: manifest_path = TRIAGE_DIR / f"{image_path.stem}.md" manifest_path.write_text("\n".join(lines), encoding="utf-8") + record, *transcripts = triage.hold( + TRIAGE_DIR, + image_path, + error.scores, + error.transcripts, + reason=str(error), + backend=backend, + ) + dest = TRIAGE_DIR / image_path.name shutil.move(str(image_path), dest) print(f" → TRIAGE: {dest.name}") print(f" → TRIAGE: {manifest_path.name}") + print(f" → TRIAGE: {record.name} (+ {len(transcripts)} full transcript(s))") def _relative(path: Path) -> str: @@ -286,7 +301,7 @@ def _record(status: str, **fields) -> None: ) def _triage(exc: "LowQualityError") -> None: - _send_to_triage(image_path, exc) + _send_to_triage(image_path, exc, backend) if triaged is not None: triaged.append(image_path.name) reading["quality_gate"] = "failed" diff --git a/src/tetrak_ocr/cli.py b/src/tetrak_ocr/cli.py index 032aa2d..5105fe3 100644 --- a/src/tetrak_ocr/cli.py +++ b/src/tetrak_ocr/cli.py @@ -16,7 +16,7 @@ import sys from pathlib import Path -from . import outputs, telemetry +from . import outputs, telemetry, triage from .errors import OcrPipelineError from .layout import spans_of from .registry import BACKENDS, available @@ -168,6 +168,19 @@ def _cmd_batch(args: argparse.Namespace) -> int: return batch.main(args=forwarded) +def _cmd_triage(args: argparse.Namespace) -> int: + """List the triage queue, or serve it as a page on the loopback address.""" + from .batch import TRIAGE_DIR + + # The same rule as `batch`: the directory is the user's, resolved against + # the working directory, unless they point somewhere else. + directory = Path(args.dir) if args.dir else TRIAGE_DIR + if args.serve: + return triage.serve(directory, port=args.port) + print(triage.describe(triage.queue(directory), directory)) + return 0 + + def _cmd_evaluate(args: argparse.Namespace) -> int: # The harness lives outside the package, next to the corpus it reads, so # that evaluation data and evaluation code stay together. That also means @@ -330,6 +343,31 @@ def add_pdf_flags(parser: argparse.ArgumentParser) -> None: add_pdf_flags(p) p.set_defaults(func=_cmd_batch) + p = sub.add_parser( + "triage", + help="list what is held in workspace/triage/, or serve it as a local page", + ) + p.add_argument( + "--serve", + action="store_true", + help=f"serve the queue as a page on http://{triage.HOST}:{triage.DEFAULT_PORT}/ " + "until Ctrl-C. Loopback only: nothing remote, nothing to authenticate", + ) + p.add_argument( + "--port", + type=int, + default=triage.DEFAULT_PORT, + metavar="PORT", + help=f"port for --serve (default: {triage.DEFAULT_PORT})", + ) + p.add_argument( + "--dir", + metavar="PATH", + help="the triage directory to read (default: workspace/triage/ under the " + "working directory)", + ) + p.set_defaults(func=_cmd_triage) + # `evaluate` forwards its flags verbatim to the harness, which owns its own # argument parser. REMAINDER cannot do this — argparse rejects a leading # `--flag` before it reaches the positional — so main() uses diff --git a/src/tetrak_ocr/triage.py b/src/tetrak_ocr/triage.py new file mode 100644 index 0000000..c4df254 --- /dev/null +++ b/src/tetrak_ocr/triage.py @@ -0,0 +1,299 @@ +"""The triage queue: what was held, why, and a local page that lists it. + +``batch`` diverts a file whose best transcript falls below the quality floor +into ``workspace/triage/``, with a Markdown manifest a person can read. That +manifest carried a 500-character excerpt of each candidate transcript and +the rest was discarded, so a decision about a page was often made on a +fragment, and a view of the queue could not show what had never been saved +(brief 001, the triage dashboard). + +A held item is now three kinds of file, side by side:: + + .md the manifest, exactly as before + .json the record: every candidate's score, the + reason the file was held, and where each + full transcript is + ..txt each candidate's transcript, whole + +The record is what a view loads; the manifest stays for anyone who reads +the directory directly. Nothing here edits a transcript or moves a file: +triage is passive by design, and this module reads what ``batch`` wrote. + +``tetrak-ocr triage`` prints the queue; ``tetrak-ocr triage --serve`` serves +it as a page. The server binds to the loopback address and nothing else, +takes no option to bind elsewhere, answers GET for one page and refuses +everything else. It reads a local directory for the person sitting at the +machine, so there is nothing to authenticate and nothing remote. +""" + +from __future__ import annotations + +import html +import json +import sys +from dataclasses import dataclass +from datetime import UTC, datetime +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from importlib import metadata +from pathlib import Path + +# The loopback address, and only that. Not a setting: a flag to bind +# elsewhere would be the first step towards the remote, unauthenticated +# service the brief rules out. +HOST = "127.0.0.1" +DEFAULT_PORT = 8321 + +RECORD_SUFFIX = ".json" +MANIFEST_SUFFIX = ".md" +TRANSCRIPT_SUFFIX = ".txt" + + +@dataclass(frozen=True) +class Candidate: + """One backend's attempt at a held file.""" + + backend: str + score: float | None + transcript: str # file name, relative to the triage directory + + +@dataclass(frozen=True) +class Item: + """One held file, as the queue lists it.""" + + stem: str + file: str + reason: str + held_at: str + backend: str | None + best_engine: str | None + best_score: float | None + candidates: tuple[Candidate, ...] + record: Path | None + manifest: Path | None + + +def _version() -> str: + try: + return metadata.version("tetrak") + except metadata.PackageNotFoundError: # pragma: no cover - a checkout without install + return "unknown" + + +def transcript_name(stem: str, backend: str) -> str: + """Where a candidate's full transcript goes, beside the manifest.""" + return f"{stem}.{backend}{TRANSCRIPT_SUFFIX}" + + +def hold( + triage_dir: Path, + image: Path, + scores: dict[str, float], + transcripts: dict[str, str], + reason: str, + backend: str | None = None, +) -> list[Path]: + """Write the record and every full transcript for a file being held. + + Called by ``batch`` beside the Markdown manifest it already writes; this + adds the machine-readable half. *transcripts* are written whole, exactly + as the backends returned them. Returns the paths written, the record + first. + """ + triage_dir.mkdir(parents=True, exist_ok=True) + stem = image.stem + written: list[Path] = [] + candidates = [] + for name, text in transcripts.items(): + path = triage_dir / transcript_name(stem, name) + path.write_text(text, encoding="utf-8") + written.append(path) + candidates.append({"backend": name, "score": scores.get(name), "transcript": path.name}) + + best = max(scores, key=lambda name: scores[name]) if scores else None + record = { + "file": image.name, + "stem": stem, + "reason": reason, + "held_at": datetime.now(UTC).isoformat(timespec="seconds"), + "backend": backend, + "best": None if best is None else {"engine": best, "score": scores[best]}, + "candidates": candidates, + "tetrak_version": _version(), + } + record_path = triage_dir / f"{stem}{RECORD_SUFFIX}" + record_path.write_text( + json.dumps(record, ensure_ascii=False, indent=2) + "\n", encoding="utf-8" + ) + return [record_path, *written] + + +def _from_record(path: Path) -> Item: + data = json.loads(path.read_text(encoding="utf-8")) + best = data.get("best") or {} + manifest = path.with_suffix(MANIFEST_SUFFIX) + return Item( + stem=data.get("stem", path.stem), + file=data.get("file", path.stem), + reason=data.get("reason", ""), + held_at=data.get("held_at", ""), + backend=data.get("backend"), + best_engine=best.get("engine"), + best_score=best.get("score"), + candidates=tuple( + Candidate(c.get("backend", "?"), c.get("score"), c.get("transcript", "")) + for c in data.get("candidates", []) + ), + record=path, + manifest=manifest if manifest.exists() else None, + ) + + +def _from_manifest_only(path: Path) -> Item: + """A file held by a release that wrote the manifest and nothing else.""" + stem = path.stem + held = next((p.name for p in path.parent.iterdir() if p.stem == stem and p != path), stem) + return Item( + stem=stem, + file=held, + reason=f"held before records were written; see {path.name}", + held_at="", + backend=None, + best_engine=None, + best_score=None, + candidates=(), + record=None, + manifest=path, + ) + + +def queue(triage_dir: Path) -> list[Item]: + """Every held item in *triage_dir*, by name. + + An item is a record, or -- for a directory written by an older release + -- a manifest with no record beside it, listed so nothing already in + the queue disappears from the view. A missing directory is an empty + queue, not an error. + """ + if not triage_dir.is_dir(): + return [] + records = {p.stem: p for p in triage_dir.glob(f"*{RECORD_SUFFIX}")} + items = [_from_record(path) for path in records.values()] + items += [ + _from_manifest_only(path) + for path in triage_dir.glob(f"*{MANIFEST_SUFFIX}") + if path.stem not in records + ] + return sorted(items, key=lambda item: item.stem) + + +def _score(item: Item) -> str: + return "–" if item.best_score is None else f"{item.best_score:.4f}" + + +def describe(items: list[Item], triage_dir: Path) -> str: + """The queue as a table for the terminal.""" + if not items: + return f"The triage queue is empty ({triage_dir})." + width = max(len(item.file) for item in items) + lines = [ + f"{len(items)} item(s) in {triage_dir}", + "", + f"{'File':<{width}} {'Best':>7} {'Engine':<14} Reason held", + f"{'-' * width} {'-' * 7} {'-' * 14} {'-' * 11}", + ] + for item in items: + lines.append( + f"{item.file:<{width}} {_score(item):>7} {(item.best_engine or '–'):<14} {item.reason}" + ) + return "\n".join(lines) + + +_STYLE = """ +body { font: 16px/1.5 system-ui, sans-serif; margin: 2rem auto; max-width: 64rem; padding: 0 1rem; color: #1a1a1a; background: #fff; } +h1 { font-size: 1.5rem; margin: 0 0 0.25rem; } +p.meta { color: #555; margin: 0 0 1.5rem; } +table { border-collapse: collapse; width: 100%; } +th, td { text-align: left; vertical-align: top; padding: 0.5rem 0.75rem; border-bottom: 1px solid #ddd; } +th { font-weight: 600; } +td.num { text-align: right; font-variant-numeric: tabular-nums; white-space: nowrap; } +code { font-size: 0.95em; } +""" + + +def render(items: list[Item], triage_dir: Path) -> str: + """The queue as one HTML page: every item, its best score and why it was held.""" + esc = html.escape + head = ( + '\n\n\n\n' + '\n' + "Triage queue · Tetrak OCR\n" + f"\n\n\n

Triage queue

\n" + ) + if not items: + return ( + head + + f'

{esc(str(triage_dir))}

\n' + + "

The triage queue is empty.

\n\n\n" + ) + rows = [] + for item in items: + rows.append( + "" + f"{esc(item.file)}" + f'{esc(_score(item))}' + f"{esc(item.best_engine or '–')}" + f"{esc(item.reason)}" + f"{esc(item.held_at or '–')}" + f'{len(item.candidates)}' + "" + ) + return ( + head + f'

{len(items)} item(s) in {esc(str(triage_dir))}

\n' + "\n" + "\n" + "\n" + "\n".join(rows) + "\n\n
FileBest scoreEngineReason heldHeld atCandidates
\n\n\n" + ) + + +class _Handler(BaseHTTPRequestHandler): + """GET / and nothing else. The queue is re-read on every request, so the + page follows the directory while a batch is still running.""" + + triage_dir: Path # set on the subclass make_server builds + + def do_GET(self) -> None: # noqa: N802 - http.server's naming + if self.path.split("?", 1)[0] != "/": + self.send_error(404, "Only / is served") + return + body = render(queue(self.triage_dir), self.triage_dir).encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args) -> None: # noqa: A002 - http.server's signature + print(f" {self.address_string()} {format % args}", file=sys.stderr) + + +def make_server(triage_dir: Path, port: int = DEFAULT_PORT) -> ThreadingHTTPServer: + """A server for the queue page, bound to the loopback address. + + Port 0 asks the OS for a free one, which is what the tests use; the + address it actually bound is ``server.server_address``. + """ + handler = type("TriageHandler", (_Handler,), {"triage_dir": Path(triage_dir)}) + return ThreadingHTTPServer((HOST, port), handler) + + +def serve(triage_dir: Path, port: int = DEFAULT_PORT) -> int: + """Serve the queue page until interrupted.""" + with make_server(triage_dir, port) as server: + host, bound = server.server_address[:2] + print(f"Serving the triage queue at http://{host}:{bound}/ (Ctrl-C to stop)") + try: + server.serve_forever() + except KeyboardInterrupt: + print("\nStopped.") + return 0 diff --git a/tests/ocr/test_batch.py b/tests/ocr/test_batch.py index cdadf56..4aea904 100644 --- a/tests/ocr/test_batch.py +++ b/tests/ocr/test_batch.py @@ -378,3 +378,75 @@ def test_a_backend_without_boxes_hands_over_none(self, working_dirs, monkeypatch assert seen["spans"] is None assert seen["page_spans"] is None assert markdown == "# page\n\nwords\n" + + +class TestWhatTriageKeeps: + """A held file keeps every candidate's full transcript and a record. + + The manifest carried a 500-character excerpt of each candidate and + discarded the rest, so a decision was often made on a fragment and a + view could not show what was never saved (brief 001). The manifest + itself is unchanged for anyone who reads the directory directly. + """ + + LONG = "word " * 300 # three times the excerpt + + def hold(self, working_dirs, monkeypatch) -> None: + from tetrak_ocr import batch + from tetrak_ocr.qa_score import LowQualityError + + def ocr(path): + raise LowQualityError( + "Best transcript (vision, score=0.0724) is below threshold 0.1000", + scores={"vision": 0.0724, "easyocr": 0.0, "tesseract-auto": 0.0101}, + transcripts={"vision": self.LONG, "easyocr": "", "tesseract-auto": "noise"}, + ) + + monkeypatch.setattr(batch, "build_ocr_fn", lambda *a, **k: ocr) + (working_dirs["scans"] / "faint.png").touch() + assert run_batch(["--backend", "auto-local"]) == 0 + + def test_every_candidate_transcript_is_written_whole(self, working_dirs, monkeypatch): + self.hold(working_dirs, monkeypatch) + triage = working_dirs["triage"] + + assert (triage / "faint.vision.txt").read_text(encoding="utf-8") == self.LONG + assert (triage / "faint.easyocr.txt").read_text(encoding="utf-8") == "" + assert (triage / "faint.tesseract-auto.txt").read_text(encoding="utf-8") == "noise" + + def test_the_record_carries_the_scores_and_the_reason(self, working_dirs, monkeypatch): + import json + + self.hold(working_dirs, monkeypatch) + + record = json.loads((working_dirs["triage"] / "faint.json").read_text(encoding="utf-8")) + assert record["backend"] == "auto-local" + assert record["best"] == {"engine": "vision", "score": 0.0724} + assert [c["backend"] for c in record["candidates"]] == [ + "vision", + "easyocr", + "tesseract-auto", + ] + assert ( + record["reason"] == "Best transcript (vision, score=0.0724) is below threshold 0.1000" + ) + + def test_the_markdown_manifest_is_unchanged(self, working_dirs, monkeypatch): + """Byte for byte what it was before the record existed.""" + self.hold(working_dirs, monkeypatch) + + manifest = (working_dirs["triage"] / "faint.md").read_text(encoding="utf-8") + + assert manifest == ( + "# faint\n\n## Quality scores\n\n| Backend | Score |\n|---|---|\n" + "| vision | 0.0724 |\n| easyocr | 0.0000 |\n| tesseract-auto | 0.0101 |\n\n" + "## Transcript excerpts\n\n" + f"### vision\n\n{self.LONG.strip()[:500]}\n\n" + "### easyocr\n\n\n\n" + "### tesseract-auto\n\nnoise\n" + ) + + def test_the_scan_moves_with_them(self, working_dirs, monkeypatch): + self.hold(working_dirs, monkeypatch) + assert (working_dirs["triage"] / "faint.png").exists() + assert not (working_dirs["scans"] / "faint.png").exists() diff --git a/tests/ocr/test_cli.py b/tests/ocr/test_cli.py index 3bfa678..fb5dfa6 100644 --- a/tests/ocr/test_cli.py +++ b/tests/ocr/test_cli.py @@ -434,3 +434,44 @@ def test_output_alone_still_writes_the_bare_transcript( assert cli.main(["ocr", str(img), "--output", str(out)]) == 0 assert out.read_text(encoding="utf-8") == "hello" + + +class TestTriageSubcommand: + def test_lists_an_empty_queue_without_error( + self, capsys: pytest.CaptureFixture, tmp_path + ) -> None: + assert cli.main(["triage", "--dir", str(tmp_path / "nothing")]) == 0 + assert "empty" in capsys.readouterr().out + + def test_lists_what_is_held(self, capsys: pytest.CaptureFixture, tmp_path) -> None: + from tetrak_ocr import triage + + image = tmp_path / "faint.png" + image.touch() + triage.hold(tmp_path / "t", image, {"vision": 0.0724}, {"vision": "x"}, reason="poor") + + assert cli.main(["triage", "--dir", str(tmp_path / "t")]) == 0 + + out = capsys.readouterr().out + assert "faint.png" in out and "0.0724" in out and "poor" in out + + def test_serve_reaches_the_server_with_its_directory_and_port( + self, monkeypatch: pytest.MonkeyPatch, tmp_path + ) -> None: + from tetrak_ocr import triage + + seen: dict = {} + monkeypatch.setattr( + triage, "serve", lambda directory, port: (seen.update(dir=directory, port=port), 0)[1] + ) + + assert cli.main(["triage", "--serve", "--dir", str(tmp_path), "--port", "0"]) == 0 + + assert seen == {"dir": tmp_path, "port": 0} + + def test_there_is_no_way_to_bind_beyond_loopback(self, capsys: pytest.CaptureFixture) -> None: + """No --host flag, by design: the page reads a local directory for the + person at the machine, and binding elsewhere would need the + authentication the brief rules out.""" + assert cli.main(["triage", "--serve", "--host", "0.0.0.0"]) == 2 + assert "unrecognized arguments: --host" in capsys.readouterr().err diff --git a/tests/ocr/test_triage.py b/tests/ocr/test_triage.py new file mode 100644 index 0000000..ff9461e --- /dev/null +++ b/tests/ocr/test_triage.py @@ -0,0 +1,188 @@ +"""Tests for the triage queue: the record batch writes and the page that lists it. + +What is pinned: that a held file keeps every candidate's transcript whole +rather than a 500-character excerpt, that the record carries what a view +needs without parsing Markdown, that the queue reads older directories +without losing anything, and that the server binds to the loopback address +and nothing else. Fast: no engine, and the server gets a free port. +""" + +from __future__ import annotations + +import json +import threading +from pathlib import Path +from urllib.error import HTTPError +from urllib.request import urlopen + +import pytest + +from tetrak_ocr import triage + +LONG = "word " * 300 # 1,500 characters: three times the old excerpt + + +def held(tmp_path: Path, stem: str = "faint", scores=None, transcripts=None) -> Path: + """Hold one file with two candidates, the way batch does, and return the directory.""" + image = tmp_path / "scans" / f"{stem}.png" + image.parent.mkdir(exist_ok=True) + image.touch() + triage.hold( + tmp_path / "triage", + image, + scores if scores is not None else {"vision": 0.0724, "easyocr": 0.0}, + transcripts if transcripts is not None else {"vision": LONG, "easyocr": ""}, + reason="Best transcript (vision, score=0.0724) is below threshold 0.1000", + backend="auto-local", + ) + return tmp_path / "triage" + + +class TestHold: + def test_every_transcript_is_kept_whole(self, tmp_path: Path) -> None: + """The manifest's excerpt stops at 500 characters; this does not.""" + directory = held(tmp_path) + + assert (directory / "faint.vision.txt").read_text(encoding="utf-8") == LONG + assert (directory / "faint.easyocr.txt").read_text(encoding="utf-8") == "" + + def test_the_record_says_what_a_view_needs(self, tmp_path: Path) -> None: + directory = held(tmp_path) + + record = json.loads((directory / "faint.json").read_text(encoding="utf-8")) + + assert record["file"] == "faint.png" + assert record["reason"].startswith("Best transcript (vision") + assert record["backend"] == "auto-local" + assert record["best"] == {"engine": "vision", "score": 0.0724} + assert record["candidates"] == [ + {"backend": "vision", "score": 0.0724, "transcript": "faint.vision.txt"}, + {"backend": "easyocr", "score": 0.0, "transcript": "faint.easyocr.txt"}, + ] + assert record["held_at"] + assert record["tetrak_version"] + + def test_the_paths_written_are_returned_record_first(self, tmp_path: Path) -> None: + image = tmp_path / "page.png" + image.touch() + + written = triage.hold(tmp_path / "t", image, {"a": 0.01}, {"a": "x"}, reason="poor") + + assert [p.name for p in written] == ["page.json", "page.a.txt"] + assert all(p.exists() for p in written) + + +class TestQueue: + def test_lists_held_items_by_name(self, tmp_path: Path) -> None: + directory = held(tmp_path, "zebra") + held(tmp_path, "apple", scores={"paddle": 0.05}, transcripts={"paddle": "x"}) + + items = triage.queue(directory) + + assert [item.stem for item in items] == ["apple", "zebra"] + assert items[1].best_engine == "vision" + assert items[1].best_score == 0.0724 + assert [c.backend for c in items[1].candidates] == ["vision", "easyocr"] + + def test_an_older_manifest_without_a_record_is_still_listed(self, tmp_path: Path) -> None: + """A directory written before records existed must not look empty.""" + directory = tmp_path / "triage" + directory.mkdir() + (directory / "old.md").write_text("# old\n", encoding="utf-8") + (directory / "old.jpg").touch() + + (item,) = triage.queue(directory) + + assert (item.file, item.best_score, item.record) == ("old.jpg", None, None) + assert "old.md" in item.reason + + def test_a_missing_directory_is_an_empty_queue(self, tmp_path: Path) -> None: + assert triage.queue(tmp_path / "nowhere") == [] + + def test_scans_and_transcripts_are_not_items(self, tmp_path: Path) -> None: + directory = held(tmp_path) + (directory / "faint.png").touch() + + assert len(triage.queue(directory)) == 1 + + +class TestRendering: + def test_an_empty_queue_is_a_plain_message(self, tmp_path: Path) -> None: + page = triage.render([], tmp_path) + assert "The triage queue is empty." in page + assert " None: + directory = held(tmp_path) + + page = triage.render(triage.queue(directory), directory) + + assert "faint.png" in page + assert "0.0724" in page + assert "is below threshold 0.1000" in page + + def test_names_and_reasons_are_escaped(self, tmp_path: Path) -> None: + directory = held(tmp_path, "a None: + directory = held(tmp_path) + + text = triage.describe(triage.queue(directory), directory) + + assert "faint.png" in text and "0.0724" in text and "vision" in text + assert "empty" in triage.describe([], directory) + + +class TestServer: + @pytest.fixture + def server(self, tmp_path: Path): + directory = held(tmp_path) + server = triage.make_server(directory, port=0) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + yield server + finally: + server.shutdown() + server.server_close() + + def test_binds_to_the_loopback_address_only(self, server) -> None: + """Brief 001: nothing remote, so nothing to authenticate. There is no + flag to bind elsewhere, and this pins that the default is loopback.""" + assert server.server_address[0] == "127.0.0.1" + assert triage.HOST == "127.0.0.1" + + def test_serves_the_queue_page(self, server) -> None: + host, port = server.server_address[:2] + + with urlopen(f"http://{host}:{port}/") as response: + page = response.read().decode("utf-8") + content_type = response.headers["Content-Type"] + + assert content_type.startswith("text/html") + assert "faint.png" in page + assert "0.0724" in page + + def test_serves_nothing_else(self, server) -> None: + host, port = server.server_address[:2] + + with pytest.raises(HTTPError) as excinfo: + urlopen(f"http://{host}:{port}/faint.png") + assert excinfo.value.code == 404 + + def test_an_empty_queue_is_a_page_not_an_error(self, tmp_path: Path) -> None: + server = triage.make_server(tmp_path / "empty", port=0) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + host, port = server.server_address[:2] + with urlopen(f"http://{host}:{port}/") as response: + assert response.status == 200 + assert "The triage queue is empty." in response.read().decode("utf-8") + finally: + server.shutdown() + server.server_close()