diff --git a/README.md b/README.md index 7516ae2..0a0e99c 100644 --- a/README.md +++ b/README.md @@ -153,6 +153,19 @@ document costs about twice as much** under this format, because it has to be transcribed page by page to put each page's words on the right page — see [below](#multi-page-documents-cost-about-twice-as-much). +### The CSV manifest (beta) + +`--manifest` appends a row per file to `workspace/manifest.csv`: the +transcript, the engine that read it, the quality gate's verdict, and where its +files are now, triaged files included. It is for a spreadsheet, or a +collections system's CSV import. The columns may still change; the +[command-line guide](https://scattercode.github.io/tetrak/guide/command-line.html#the-csv-manifest-beta) +lists them. + +```bash +tetrak-ocr batch --backend auto-local --pdf --manifest +``` + ### The run log Every batch appends to `workspace/telemetry.jsonl` — one JSON object per line, diff --git a/docs/guide/command-line.md b/docs/guide/command-line.md index 9fdbd7b..a213710 100644 --- a/docs/guide/command-line.md +++ b/docs/guide/command-line.md @@ -158,6 +158,59 @@ jq -rs 'map(select(.event=="backend_finish")) A logging failure never fails a run: the log disables itself, warns once, and the batch carries on. +### The CSV manifest (beta) + +`--manifest` appends a row per file to `workspace/manifest.csv`: what was +read, by which engine, what the quality gate made of it, and where the files +are now. The run log is for watching a run and measuring it; the manifest is +for the people who receive its output, to open in a spreadsheet or to import +into a collections system that takes a CSV, such as Omeka S's CSV Import. + +It is not the triage manifest above: that is one report per triaged file; +this is one table for the whole workspace. + +```bash +tetrak-ocr batch --backend auto-local --pdf --manifest +``` + +Two of its rows, with the transcript shortened: + +```text +file,status,backend,engine,quality,quality_gate,transcript,outputs,location,note,run,finished_at,tetrak_version +graumans-chinese-theatre.jpg,processed,auto-local,vision,0.2356,passed,"THE CHINESE THEATRE. HOLLYWOOD. …",processed/graumans-chinese-theatre.md;processed/graumans-chinese-theatre.pdf,processed/graumans-chinese-theatre.jpg,,20261016T135228Z-5c09,2026-10-16T13:52:37+00:00,5.14.1 +inside-facts-1930-cover-ruined.jpg,triage,auto-local,vision,0.0724,failed,,triage/inside-facts-1930-cover-ruined.md,triage/inside-facts-1930-cover-ruined.jpg,"Best transcript (vision, score=0.0724) is below threshold 0.1000",20261016T135228Z-5c09,2026-10-16T13:52:48+00:00,5.14.1 +``` + +| Column | What it holds | +|---|---| +| `file` | The scan's file name, as it was in `scans/` | +| `status` | `processed`, `triage` or `error` | +| `backend` | The backend the run asked for | +| `engine` | The engine whose transcript was kept or rejected: under `auto-local`, the one that won | +| `quality` | The transcript's quality score, when it was scored | +| `quality_gate` | `passed`, `failed`, `skipped` (not in the Latin script, so not scoreable) or `off` | +| `transcript` | The full transcript. Empty for a file in triage, so importing the manifest never imports a rejected reading | +| `outputs` | The files written for it, relative to `workspace/`, separated by `;` | +| `location` | Where the scan is now, relative to `workspace/` | +| `note` | Why a file went to triage, or what went wrong | +| `run` | The run's id in the run log, when there is one | +| `finished_at` | When the file finished, in UTC | +| `tetrak_version` | The Tetrak release that read it | + +It is appended to across runs, as `workspace/processed/` grows, and every +file gets a row whatever became of it, so the manifest is also the list of +what still needs a person. `--manifest PATH` writes it elsewhere. + +**It is a beta.** The columns may change before it is declared stable, so +read them by the header, not by position. A manifest whose header differs +from this version's is refused before any scan is touched; move it aside, or +name a new file. Comments on what the columns should be are welcome. + +The file is UTF-8 without a byte-order mark, which is what import tools +expect. Excel guesses the encoding of a CSV opened by double-clicking it and +can get non-Latin transcripts wrong; open it with *Data > From Text/CSV* +instead. + ### Dry runs ```bash diff --git a/src/tetrak_ocr/auto_local.py b/src/tetrak_ocr/auto_local.py index 91c5cfe..fd42a4b 100644 --- a/src/tetrak_ocr/auto_local.py +++ b/src/tetrak_ocr/auto_local.py @@ -167,6 +167,15 @@ def has_gpu() -> bool: # constant's reach. LENGTH_WEIGHT = 0.8 +# The engine the last call chose and its raw quality score, as +# {"engine": name, "quality": score}, or None before the first call or when +# every backend failed. Set on a triaged file too, since the choice was made +# before the gate rejected it. The batch manifest reads it: `ocr_image` returns +# a transcript alone, by the fixed backend contract, so the choice has no other +# way out. Process-global like the telemetry sink, and for the same reason; +# the fan-out is sequential, so there is no concurrent caller to confuse. +last_choice: dict | None = None + def _effective_score(score: float, word_count: int, max_words: int) -> float: """Return `score` adjusted for `word_count` relative to `max_words`. @@ -287,6 +296,8 @@ def ocr_image(path: "Path | str", with_paddle_vl: bool = False) -> str: MIN_QUALITY_THRESHOLD. The exception carries .scores and .transcripts dicts for triage queue reporting. """ + global last_choice + last_choice = None path = Path(path) candidates = _build_candidates(path, with_paddle_vl=with_paddle_vl) @@ -347,6 +358,7 @@ def ocr_image(path: "Path | str", with_paddle_vl: bool = False) -> str: # Use the raw combined_score for the quality threshold — the triage gate # should reflect output quality, not quality × length. best_raw_score = scores[best_name] + last_choice = {"engine": best_name, "quality": best_raw_score} if best_raw_score < MIN_QUALITY_THRESHOLD: raise LowQualityError( diff --git a/src/tetrak_ocr/batch.py b/src/tetrak_ocr/batch.py index e8f4e21..3d0e9dd 100644 --- a/src/tetrak_ocr/batch.py +++ b/src/tetrak_ocr/batch.py @@ -15,6 +15,7 @@ tetrak-ocr batch --backend auto-local tetrak-ocr batch --backend claude tetrak-ocr batch --backend tesseract --contrast 3.0 + tetrak-ocr batch --backend auto-local --manifest # and workspace/manifest.csv """ import argparse @@ -30,6 +31,8 @@ from . import outputs, telemetry from .imaging import page_documents +from .manifest import DEFAULT_NAME as MANIFEST_NAME +from .manifest import Manifest, ManifestError from .registry import BACKENDS, get_backend from .registry import supported_extensions as _registry_extensions @@ -172,6 +175,25 @@ def _send_to_triage(image_path: Path, error: "LowQualityError") -> None: print(f" → TRIAGE: {manifest_path.name}") +def _relative(path: Path) -> str: + """*path* relative to the workspace, for the manifest; as given if outside it.""" + try: + return str(path.relative_to(SCANS_DIR.parent)) + except ValueError: + return str(path) + + +def _auto_local_choice() -> dict: + """The engine auto-local chose for the file just read, and its score. + + Read from the module only if something already imported it, which + running auto-local does: importing it here would pull in the scorer for + runs that never use it. + """ + module = sys.modules.get(f"{__package__}.auto_local") + return dict(getattr(module, "last_choice", None) or {}) + + def transcribe_per_page(image_path: Path, ocr_fn: Callable[[Path], str]) -> list[str]: """Transcribe *image_path* one page at a time, returning a text per page. @@ -201,6 +223,7 @@ def process_file( formats: list[str] | None = None, pdf_full_size: bool = False, pdf_font: str | None = None, + manifest: Manifest | None = None, ) -> None: """OCR a single file, write Markdown output, and move it to workspace/processed/. @@ -230,6 +253,7 @@ def process_file( Every requested format is written for the same transcript -- the OCR runs once regardless of how many are asked for. + manifest: Where to append this file's row, if anywhere. """ from .qa_score import LowQualityError @@ -241,10 +265,33 @@ def process_file( def _elapsed() -> float: return round(time.perf_counter() - started, 3) + # What the manifest row says about the reading, filled in as it is known. + # auto-local scores and gates every file itself; a single backend is + # scored only under --quality-gate. + auto_local = backend == "auto-local" + reading: dict = { + "engine": backend or "", + "quality": None, + "quality_gate": "" if auto_local else "off", + } + + def _record(status: str, **fields) -> None: + if manifest is not None: + manifest.write( + file=image_path.name, status=status, backend=backend or "", **reading, **fields + ) + def _triage(exc: "LowQualityError") -> None: _send_to_triage(image_path, exc) if triaged is not None: triaged.append(image_path.name) + reading["quality_gate"] = "failed" + _record( + "triage", + outputs=[_relative(TRIAGE_DIR / f"{image_path.stem}.md")], + location=_relative(TRIAGE_DIR / image_path.name), + note=str(exc), + ) telemetry.record( "file_finish", backend=backend, @@ -270,6 +317,8 @@ def _triage(exc: "LowQualityError") -> None: else: text = ocr_fn(image_path) except LowQualityError as exc: + if auto_local: + reading.update(_auto_local_choice()) _triage(exc) return except Exception as exc: @@ -282,8 +331,12 @@ def _triage(exc: "LowQualityError") -> None: reason=str(exc), **file_info, ) + _record("error", location=_relative(image_path), note=f"{type(exc).__name__}: {exc}") raise + if auto_local: + reading.update(_auto_local_choice(), quality_gate="passed") + if quality_gate: from .qa_score import MIN_QUALITY_THRESHOLD, combined_score, scores_english_text @@ -294,6 +347,7 @@ def _triage(exc: "LowQualityError") -> None: # mean anything. quality_gate = scores_english_text(text) if not quality_gate: + reading["quality_gate"] = "skipped" print( " quality gate skipped: this transcript is not in the Latin script, " "and the score would be 0.0 whatever its quality", @@ -303,6 +357,8 @@ def _triage(exc: "LowQualityError") -> None: if quality_gate: score = combined_score(text) print(f" quality={score:.4f}") + reading["quality"] = score + reading["quality_gate"] = "passed" if score < MIN_QUALITY_THRESHOLD: label = backend or "backend" _triage( @@ -341,6 +397,7 @@ def _triage(exc: "LowQualityError") -> None: reason=str(exc), **file_info, ) + _record("error", location=_relative(image_path), note=f"{type(exc).__name__}: {exc}") raise dest = PROCESSED_DIR / image_path.name @@ -350,6 +407,13 @@ def _triage(exc: "LowQualityError") -> None: for path in written: print(f" → {path.name}") + _record( + "processed", + transcript=text, + outputs=[_relative(path) for path in written], + location=_relative(dest), + ) + telemetry.record( "file_finish", backend=backend, @@ -459,6 +523,16 @@ def main(args=None) -> int: "extends the same threshold to any single backend. The scoring is English-only, so " "it is skipped for a transcript in another script rather than failing it.", ) + parser.add_argument( + "--manifest", + nargs="?", + const=True, + default=None, + metavar="PATH", + help=f"Beta. Append a row per file to a CSV manifest (default: workspace/{MANIFEST_NAME}): " + "the transcript, the engine that read it, the quality gate's verdict and where the " + "files are now, for a spreadsheet or a collections system's CSV import.", + ) parser.add_argument( "--dry-run", action="store_true", @@ -507,6 +581,18 @@ def main(args=None) -> int: print(f"Error: scans directory not found at {SCANS_DIR}", file=sys.stderr) return 1 + # Checked before anything moves, like the qa extra: a manifest that cannot + # take this version's rows should stop the run, not half of it. + manifest = None + if args.manifest: + path = SCANS_DIR.parent / MANIFEST_NAME if args.manifest is True else Path(args.manifest) + manifest = Manifest(path) + try: + manifest.check() + except ManifestError as exc: + print(f"Error: {exc}", file=sys.stderr) + return 1 + extensions = supported_extensions(args.backend) files = sorted(f for f in SCANS_DIR.iterdir() if f.is_file() and f.suffix.lower() in extensions) @@ -558,6 +644,10 @@ def main(args=None) -> int: ) if log is not None: print(f"Run log: {log.path} (run {log.run_id})\n") + if manifest is not None: + manifest.run = log.run_id + if manifest is not None: + print(f"Manifest: {manifest.path} (beta)\n") run_started = time.perf_counter() @@ -578,6 +668,7 @@ def main(args=None) -> int: formats=formats, pdf_full_size=args.pdf_full_size, pdf_font=args.pdf_font, + manifest=manifest, ) except Exception as exc: print(f" ERROR processing {f.name}: {exc}", file=sys.stderr) diff --git a/src/tetrak_ocr/cli.py b/src/tetrak_ocr/cli.py index 8f85643..851e3ae 100644 --- a/src/tetrak_ocr/cli.py +++ b/src/tetrak_ocr/cli.py @@ -122,6 +122,10 @@ def _cmd_batch(args: argparse.Namespace) -> int: forwarded += ["--telemetry", args.telemetry] if args.no_telemetry: forwarded.append("--no-telemetry") + if args.manifest is True: + forwarded.append("--manifest") + elif args.manifest: + forwarded += ["--manifest", args.manifest] for name in args.formats or []: forwarded += ["--format", name] if args.pdf or args.pdf_full_size or args.pdf_font: @@ -282,6 +286,17 @@ def add_pdf_flags(parser: argparse.ArgumentParser) -> None: "one JSON object per line, tail it to watch a long batch", ) p.add_argument("--no-telemetry", action="store_true", help="do not write the run log") + p.add_argument( + "--manifest", + nargs="?", + const=True, + default=None, + metavar="PATH", + help="beta: append a row per file to a CSV manifest (default: " + "workspace/manifest.csv) with its transcript, the engine that read it, " + "the quality gate's verdict and where its files are, for a spreadsheet " + "or a collections system's CSV import", + ) add_tuning_flags(p) add_format_flags(p) add_pdf_flags(p) diff --git a/src/tetrak_ocr/manifest.py b/src/tetrak_ocr/manifest.py new file mode 100644 index 0000000..e3d000d --- /dev/null +++ b/src/tetrak_ocr/manifest.py @@ -0,0 +1,137 @@ +"""The batch's CSV manifest: one row per file, for a spreadsheet or an import. + +Not the triage manifest, the per-file report `batch` writes beside a +triaged scan; this is one table for the whole workspace. + +**Beta.** The columns may change before this is declared stable; the header +row is what to rely on, never a column's position. + +Where the telemetry log is for watching a run and measuring it, the manifest +is for the people who receive its output. A small archive keeps its +catalogue in a spreadsheet; a collections system imports a CSV (Omeka S's CSV +Import, among others). Either way the question is the same: for each scan, +what was read, by which engine, did it pass the quality gate, and where are +the files now. A triaged or failed file gets a row too, so the manifest is +also the list of what still needs a person. + +The file is appended to, one row per file as it finishes, so it grows with +the workspace across runs, as `workspace/processed/` does. The header is +written when the file is new. A file whose header is not this version's is +refused before any scan is touched, rather than given rows that do not line +up with its columns. + +UTF-8 without a byte-order mark, which is what import tools expect. Excel +reads a UTF-8 file without a BOM as the local code page when it is +double-clicked; import it through *Data > From Text/CSV* instead to keep +non-Latin transcripts intact. +""" + +from __future__ import annotations + +import csv +from datetime import UTC, datetime +from importlib import metadata +from pathlib import Path + +COLUMNS = ( + "file", + "status", + "backend", + "engine", + "quality", + "quality_gate", + "transcript", + "outputs", + "location", + "note", + "run", + "finished_at", + "tetrak_version", +) +"""The manifest's columns, in order. + +- ``file``: the scan's file name, as it was in ``scans/``. +- ``status``: ``processed``, ``triage`` or ``error``. +- ``backend``: the backend the run asked for. +- ``engine``: the engine whose transcript was kept or rejected. The same as + ``backend``, except under ``auto-local``, where it is the one that won. +- ``quality``: the transcript's quality score, from 0 to 1, when it was + scored; empty when it was not. +- ``quality_gate``: ``passed``, ``failed``, ``skipped`` (a transcript not in + the Latin script, which the English-only score cannot judge) or ``off``. +- ``transcript``: the full transcript of a processed file. Empty for a file + sent to triage, so that importing the manifest never imports a reading the + gate rejected; the triage report beside the scan has the excerpts. +- ``outputs``: the files written for it, relative to the workspace and + separated by ``;``. +- ``location``: where the scan is now, relative to the workspace. +- ``note``: why a file went to triage, or what went wrong. +- ``run``: the telemetry run id, to find the run's events in the log; empty + when telemetry is off. +- ``finished_at``: when the file finished, in UTC, ISO 8601. +- ``tetrak_version``: the Tetrak release that read it. +""" + +DEFAULT_NAME = "manifest.csv" + + +class ManifestError(Exception): + """The manifest cannot be appended to as it stands.""" + + +def _version() -> str: + try: + return metadata.version("tetrak") + except metadata.PackageNotFoundError: # pragma: no cover - a bare checkout + return "unknown" + + +class Manifest: + """Appends rows to a manifest CSV, writing its header when it is new.""" + + def __init__(self, path: Path, run: str | None = None): + self.path = Path(path) + self.run = run or "" + self.version = _version() + + def check(self) -> None: + """Refuse a file that already has a different header. + + Called before the batch starts, so a mismatch is found before any + scan is moved. + """ + if not self.path.exists() or self.path.stat().st_size == 0: + return + with self.path.open(newline="", encoding="utf-8") as handle: + header = next(csv.reader(handle), []) + if tuple(header) != COLUMNS: + raise ManifestError( + f"{self.path} has different columns from this version of Tetrak's " + "manifest. Move it aside or name another file with --manifest PATH." + ) + + def write(self, **fields: object) -> None: + """Append one row. Unknown fields are a programming error.""" + unknown = set(fields) - set(COLUMNS) + if unknown: + raise ValueError(f"not manifest columns: {', '.join(sorted(unknown))}") + row = { + "run": self.run, + "finished_at": datetime.now(UTC).isoformat(timespec="seconds"), + "tetrak_version": self.version, + **fields, + } + quality = row.get("quality") + if isinstance(quality, float): + row["quality"] = f"{quality:.4f}" + outputs = row.get("outputs") + if isinstance(outputs, (list, tuple)): + row["outputs"] = ";".join(str(p) for p in outputs) + + new = not self.path.exists() or self.path.stat().st_size == 0 + self.path.parent.mkdir(parents=True, exist_ok=True) + with self.path.open("a", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=COLUMNS, restval="") + if new: + writer.writeheader() + writer.writerow(row) diff --git a/tests/ocr/test_manifest.py b/tests/ocr/test_manifest.py new file mode 100644 index 0000000..c7115ba --- /dev/null +++ b/tests/ocr/test_manifest.py @@ -0,0 +1,266 @@ +"""The batch manifest: one CSV row per file (beta). + +The OCR is stubbed throughout, as in `test_batch.py`'s quality-gate tests: +what is under test is what the row says about each outcome, not whether an +engine reads the page. +""" + +from __future__ import annotations + +import csv +from pathlib import Path + +import pytest + +from tetrak_ocr import auto_local, batch, cli, qa_score +from tetrak_ocr.batch import main as run_batch +from tetrak_ocr.manifest import COLUMNS, Manifest, ManifestError +from tetrak_ocr.qa_score import LowQualityError + + +def _rows(path: Path) -> list[dict[str, str]]: + with path.open(newline="", encoding="utf-8") as handle: + return list(csv.DictReader(handle)) + + +@pytest.fixture +def manifest_path(working_dirs) -> Path: + """Where `--manifest` writes by default: beside scans/, in the workspace.""" + return working_dirs["scans"].parent / "manifest.csv" + + +@pytest.fixture +def reads(monkeypatch): + """Make every file read as *text*, or raise *error*.""" + + def _reads(text: str = "A clean transcript", error: Exception | None = None): + def ocr(path): + if error is not None: + raise error + return text + + monkeypatch.setattr(batch, "build_ocr_fn", lambda *a, **k: ocr) + + return _reads + + +def _gate(monkeypatch, score: float) -> None: + monkeypatch.setattr(qa_score, "combined_score", lambda _text: score) + monkeypatch.setattr(qa_score, "is_available", lambda: True) + + +class TestOffByDefault: + def test_no_manifest_unless_asked_for(self, working_dirs, manifest_path, reads): + (working_dirs["scans"] / "page.png").touch() + reads() + + assert run_batch(["--no-telemetry"]) == 0 + + assert not manifest_path.exists() + + +class TestRows: + def test_a_processed_file(self, working_dirs, manifest_path, reads): + (working_dirs["scans"] / "page.png").touch() + reads("Matinees Wednesday, Saturday\nand Sunday") + + assert run_batch(["--manifest", "--no-telemetry"]) == 0 + + (row,) = _rows(manifest_path) + assert row["file"] == "page.png" + assert row["status"] == "processed" + assert row["backend"] == row["engine"] == "tesseract" + assert row["quality"] == "" + assert row["quality_gate"] == "off" + assert row["transcript"] == "Matinees Wednesday, Saturday\nand Sunday" + assert row["location"] == "processed/page.png" + assert row["tetrak_version"] + assert row["finished_at"].endswith("+00:00") + + def test_the_outputs_are_listed(self, working_dirs, manifest_path, reads): + (working_dirs["scans"] / "page.png").touch() + reads() + + run_batch(["--manifest", "--no-telemetry", "--format", "markdown,text"]) + + (row,) = _rows(manifest_path) + assert row["outputs"] == "processed/page.md;processed/page.txt" + + def test_a_scored_file_that_passes(self, working_dirs, manifest_path, reads, monkeypatch): + (working_dirs["scans"] / "page.png").touch() + reads() + _gate(monkeypatch, 0.4321) + + run_batch(["--manifest", "--no-telemetry", "--quality-gate"]) + + (row,) = _rows(manifest_path) + assert (row["status"], row["quality"], row["quality_gate"]) == ( + "processed", + "0.4321", + "passed", + ) + + def test_a_triaged_file_has_no_transcript( + self, working_dirs, manifest_path, reads, monkeypatch + ): + """Importing the manifest must never import a reading the gate rejected.""" + (working_dirs["scans"] / "faint.png").touch() + reads("unreadable smudge") + _gate(monkeypatch, 0.01) + + assert run_batch(["--manifest", "--no-telemetry", "--quality-gate"]) == 0 + + (row,) = _rows(manifest_path) + assert row["status"] == "triage" + assert row["quality"] == "0.0100" + assert row["quality_gate"] == "failed" + assert row["transcript"] == "" + assert row["location"] == "triage/faint.png" + assert row["outputs"] == "triage/faint.md" + assert "below threshold" in row["note"] + + def test_a_transcript_the_gate_cannot_judge( + self, working_dirs, manifest_path, reads, monkeypatch + ): + (working_dirs["scans"] / "page.png").touch() + reads("Հայկական Սովետական Հանրագիտարան") + _gate(monkeypatch, 0.0) + + run_batch(["--manifest", "--no-telemetry", "--quality-gate"]) + + (row,) = _rows(manifest_path) + assert (row["status"], row["quality_gate"]) == ("processed", "skipped") + assert row["transcript"] == "Հայկական Սովետական Հանրագիտարան" + + def test_a_failed_file(self, working_dirs, manifest_path, reads): + (working_dirs["scans"] / "broken.png").touch() + reads(error=RuntimeError("engine fell over")) + + assert run_batch(["--manifest", "--no-telemetry"]) == 1 + + (row,) = _rows(manifest_path) + assert row["status"] == "error" + assert row["location"] == "scans/broken.png" + assert row["note"] == "RuntimeError: engine fell over" + + +class TestAutoLocal: + """auto-local's choice of engine, which its transcript alone cannot carry.""" + + def test_the_winning_engine_is_named(self, working_dirs, manifest_path, monkeypatch): + (working_dirs["scans"] / "page.png").touch() + + def ocr(path): + auto_local.last_choice = {"engine": "vision", "quality": 0.2187} + return "Grauman's Chinese" + + monkeypatch.setattr(batch, "build_ocr_fn", lambda *a, **k: ocr) + + run_batch(["--backend", "auto-local", "--manifest", "--no-telemetry"]) + + (row,) = _rows(manifest_path) + assert (row["backend"], row["engine"]) == ("auto-local", "vision") + assert (row["quality"], row["quality_gate"]) == ("0.2187", "passed") + + def test_a_file_no_engine_could_read(self, working_dirs, manifest_path, monkeypatch): + (working_dirs["scans"] / "ruined.jpg").touch() + + def ocr(path): + auto_local.last_choice = {"engine": "vision", "quality": 0.0724} + raise LowQualityError( + "Best transcript (vision, score=0.0724) is below threshold 0.1000", + scores={"vision": 0.0724, "easyocr": 0.0}, + transcripts={"vision": "ISIDE FACTS", "easyocr": ""}, + ) + + monkeypatch.setattr(batch, "build_ocr_fn", lambda *a, **k: ocr) + + run_batch(["--backend", "auto-local", "--manifest", "--no-telemetry"]) + + (row,) = _rows(manifest_path) + assert (row["status"], row["engine"], row["quality"]) == ("triage", "vision", "0.0724") + assert row["quality_gate"] == "failed" + assert row["transcript"] == "" + + +class TestTheFile: + def test_it_is_appended_to_across_runs(self, working_dirs, manifest_path, reads): + reads() + for name in ("one.png", "two.png"): + (working_dirs["scans"] / name).touch() + run_batch(["--manifest", "--no-telemetry"]) + + assert [row["file"] for row in _rows(manifest_path)] == ["one.png", "two.png"] + assert manifest_path.read_text(encoding="utf-8").count("file,status,") == 1 + + def test_the_header_is_the_columns(self, working_dirs, manifest_path, reads): + (working_dirs["scans"] / "page.png").touch() + reads() + + run_batch(["--manifest", "--no-telemetry"]) + + with manifest_path.open(newline="", encoding="utf-8") as handle: + assert tuple(next(csv.reader(handle))) == COLUMNS + + def test_a_path_can_be_named(self, working_dirs, tmp_path, reads): + (working_dirs["scans"] / "page.png").touch() + reads() + elsewhere = tmp_path / "reports" / "june.csv" + + run_batch(["--manifest", str(elsewhere), "--no-telemetry"]) + + assert [row["file"] for row in _rows(elsewhere)] == ["page.png"] + + def test_a_different_header_is_refused_before_anything_moves( + self, working_dirs, manifest_path, reads + ): + (working_dirs["scans"] / "page.png").touch() + reads() + manifest_path.write_text("filename,text\nold.png,hello\n", encoding="utf-8") + + assert run_batch(["--manifest", "--no-telemetry"]) == 1 + + assert (working_dirs["scans"] / "page.png").exists() + assert manifest_path.read_text(encoding="utf-8") == "filename,text\nold.png,hello\n" + + def test_the_run_is_the_telemetry_run(self, working_dirs, manifest_path, reads, tmp_path): + (working_dirs["scans"] / "page.png").touch() + reads() + log = tmp_path / "telemetry.jsonl" + + run_batch(["--manifest", "--telemetry", str(log)]) + + (row,) = _rows(manifest_path) + assert row["run"] and row["run"] in log.read_text(encoding="utf-8") + + def test_an_unknown_column_is_a_bug(self, tmp_path): + with pytest.raises(ValueError, match="not manifest columns"): + Manifest(tmp_path / "m.csv").write(file="a.png", colour="red") + + def test_check_passes_a_new_or_empty_file(self, tmp_path): + Manifest(tmp_path / "absent.csv").check() + (tmp_path / "empty.csv").touch() + Manifest(tmp_path / "empty.csv").check() + + def test_check_refuses_another_header(self, tmp_path): + (tmp_path / "m.csv").write_text("a,b\n", encoding="utf-8") + with pytest.raises(ManifestError): + Manifest(tmp_path / "m.csv").check() + + +class TestTheCommandLine: + def test_batch_forwards_the_flag(self, working_dirs, manifest_path, reads): + (working_dirs["scans"] / "page.png").touch() + reads() + + assert cli.main(["batch", "--manifest", "--no-telemetry"]) == 0 + + assert [row["file"] for row in _rows(manifest_path)] == ["page.png"] + + def test_batch_forwards_a_path(self, working_dirs, tmp_path, reads): + (working_dirs["scans"] / "page.png").touch() + reads() + + assert cli.main(["batch", "--manifest", str(tmp_path / "m.csv"), "--no-telemetry"]) == 0 + + assert (tmp_path / "m.csv").exists()