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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
53 changes: 53 additions & 0 deletions docs/guide/command-line.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
12 changes: 12 additions & 0 deletions src/tetrak_ocr/auto_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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(
Expand Down
91 changes: 91 additions & 0 deletions src/tetrak_ocr/batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

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

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

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

Expand All @@ -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,
Expand All @@ -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:
Expand All @@ -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

Expand All @@ -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",
Expand All @@ -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(
Expand Down Expand Up @@ -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
Expand All @@ -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,
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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)

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

Expand All @@ -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)
Expand Down
15 changes: 15 additions & 0 deletions src/tetrak_ocr/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
Loading
Loading