From 57d8724d69164eb02d58c6141afc27c07733df94 Mon Sep 17 00:00:00 2001 From: Stephen Masters Date: Sat, 24 Oct 2026 12:41:08 +0100 Subject: [PATCH] fix(cli): make ocr --output name the one requested format, or refuse several `ocr --format pdf --output out.pdf` wrote the searchable PDF beside the source and then the bare transcript to out.pdf: a text file with a .pdf name that looked like it had worked. With one format requested -- through --format or the bare --pdf flag -- --output now names that format's file, written by that format's writer through the new outputs.write_to; with several there is no single file to name, so the combination is refused with a message before the OCR runs. Without --format, --output still writes the bare transcript as it always has. Closes scattercode/tetrak#25 Co-authored-by: Yvette Mankerian Co-Authored-By: Claude Fable 5.1 --- docs/guide/command-line.md | 10 +++- src/tetrak_ocr/cli.py | 69 ++++++++++++++++++---------- src/tetrak_ocr/outputs.py | 15 ++++-- tests/ocr/test_cli.py | 94 ++++++++++++++++++++++++++++++++++++++ tests/ocr/test_outputs.py | 11 +++++ 5 files changed, 169 insertions(+), 30 deletions(-) diff --git a/docs/guide/command-line.md b/docs/guide/command-line.md index 694bf8d..1cf1853 100644 --- a/docs/guide/command-line.md +++ b/docs/guide/command-line.md @@ -53,14 +53,20 @@ 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: +With one format, `--output` names that file instead; with more than one +there is no single file to name, so the combination is refused. `--pdf` +also takes an optional path, so a PDF can be named either way: ```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 ocr scan.jpg --format pdf --output catalogue-ready.pdf # the same +tetrak-ocr ocr scan.jpg --format text --output transcript.txt ``` +Without `--format`, `--output` writes the bare transcript, whatever the +file is called. + ## `tetrak-ocr batch` The pipeline's normal mode. It uses three directories under `workspace/`, diff --git a/src/tetrak_ocr/cli.py b/src/tetrak_ocr/cli.py index 31a17b9..032aa2d 100644 --- a/src/tetrak_ocr/cli.py +++ b/src/tetrak_ocr/cli.py @@ -41,15 +41,41 @@ def _cmd_ocr(args: argparse.Namespace) -> int: ocr = build_ocr_fn(args.backend, args.contrast, args.psm, args.auto, args.with_paddle_vl) path = Path(args.path) + # `--pdf PATH` names its own destination, so it stays on the direct route + # rather than going through the format table, which writes beside the + # source under the source's stem. + explicit_pdf_path = args.pdf if isinstance(args.pdf, str) else None + + # Unlike `batch`, this subcommand writes nothing unless asked: its default + # output is stdout. So formats are only those explicitly requested, rather + # than outputs.parse's default of Markdown. + requested = outputs.parse(args.formats) if args.formats else [] + if explicit_pdf_path is None and (args.pdf or args.pdf_full_size or args.pdf_font): + if "pdf" not in requested: + requested = [*requested, "pdf"] + + # `--output` names one file. With one format asked for, it names that + # format's file; with several there is no honest reading of it, so the + # combination is refused -- here, before the OCR runs. It used to write + # every format beside the source and then the bare transcript to the + # named path, whatever its extension: a text file called out.pdf, which + # looked like it had worked. + if args.output and len(requested) > 1: + print( + f"error: --output names one file, but --format asks for {len(requested)}: " + f"{', '.join(requested)}. Name one format, or drop --output and the files " + f"are written beside {path.name}.", + file=sys.stderr, + ) + return 2 + # Same rule as `batch`: a multi-page searchable PDF needs a transcript per # page, and nothing else does, so only that case pays for the per-page # pass. `--output`/stdout get the pages joined. from .batch import transcribe_per_page from .imaging import page_count - wants_pdf = bool(args.formats and "pdf" in outputs.parse(args.formats)) or bool( - args.pdf or args.pdf_full_size or args.pdf_font - ) + wants_pdf = explicit_pdf_path is not None or "pdf" in requested # Spans come off the transcript before anything strips or joins it, as # in `batch.process_file`: a string operation returns a plain str. page_transcripts = None @@ -63,10 +89,6 @@ def _cmd_ocr(args: argparse.Namespace) -> int: text = ocr(path) spans = spans_of(text) - # `--pdf PATH` names its own destination, so it stays on the direct route - # rather than going through the format table, which writes beside the - # source under the source's stem. - explicit_pdf_path = args.pdf if isinstance(args.pdf, str) else None if explicit_pdf_path is not None: from .pdf_output import searchable_pdf_for @@ -81,26 +103,23 @@ def _cmd_ocr(args: argparse.Namespace) -> int: ) print(f"Wrote {destination}", file=sys.stderr) - # Unlike `batch`, this subcommand writes nothing unless asked: its default - # output is stdout. So formats are only those explicitly requested, rather - # than outputs.parse's default of Markdown. - requested = outputs.parse(args.formats) if args.formats else [] - if explicit_pdf_path is None and (args.pdf or args.pdf_full_size or args.pdf_font): - if "pdf" not in requested: - requested = [*requested, "pdf"] + options = dict( + page_transcripts=page_transcripts, + spans=spans, + page_spans=page_spans, + pdf_full_size=args.pdf_full_size, + pdf_font=args.pdf_font, + ) + + if args.output and requested: + # One format, one named file: the file is that format, written where + # it was asked for, and stdout stays quiet as it does for --output. + written = outputs.write_to(requested[0], path, text, Path(args.output), **options) + print(f"Wrote {written}", file=sys.stderr) + return 0 for name in requested: - written = outputs.write( - name, - path, - text, - path.parent, - page_transcripts=page_transcripts, - spans=spans, - page_spans=page_spans, - pdf_full_size=args.pdf_full_size, - pdf_font=args.pdf_font, - ) + written = outputs.write(name, path, text, path.parent, **options) print(f"Wrote {written}", file=sys.stderr) if args.output: diff --git a/src/tetrak_ocr/outputs.py b/src/tetrak_ocr/outputs.py index e7bcc81..78408cb 100644 --- a/src/tetrak_ocr/outputs.py +++ b/src/tetrak_ocr/outputs.py @@ -165,11 +165,20 @@ def write(name: str, source: Path, transcript: str, destination_dir: Path, **opt source whose own extension is also an output format can hit this, which today means PDF alone. """ - key = canonical(name) - ext, writer, _ = _FORMATS[key] + ext = extension(name) stem = source.stem if ext == source.suffix.lower(): stem = f"{stem}.searchable" - destination = destination_dir / f"{stem}{ext}" + return write_to(name, source, transcript, destination_dir / f"{stem}{ext}", **options) + + +def write_to(name: str, source: Path, transcript: str, destination: Path, **options) -> Path: + """Write *transcript* in format *name* to exactly *destination*. + + For a caller that has named the file -- `ocr --output` with one format. + No stem rule and no collision guard apply: the name was chosen, and a + chosen name is honoured whatever its extension says. + """ + _, writer, _ = _FORMATS[canonical(name)] writer(source, transcript, destination, **options) return destination diff --git a/tests/ocr/test_cli.py b/tests/ocr/test_cli.py index 60fc7b8..3bfa678 100644 --- a/tests/ocr/test_cli.py +++ b/tests/ocr/test_cli.py @@ -340,3 +340,97 @@ def recording_write(name, source, transcript, destination_dir, **options): assert seen["page_spans"] is None assert (tmp_path / "scan.txt").read_text() == "hello\n" assert "hello" in capsys.readouterr().out + + +class TestOutputWithFormat: + """`--output` with `--format` names the one file, or is refused. + + It used to write every format beside the source and then the bare + transcript to the named path whatever its extension -- `--format pdf + --output out.pdf` produced a text file called out.pdf that looked like + it had worked. + """ + + @staticmethod + def scan(tmp_path): + from PIL import Image + + img = tmp_path / "scan.png" + Image.new("RGB", (120, 40), "white").save(img) + return img + + @staticmethod + def backend(monkeypatch: pytest.MonkeyPatch, text: str = "hello") -> dict: + calls = {"n": 0} + + def ocr(path): + calls["n"] += 1 + return text + + monkeypatch.setattr(batch, "build_ocr_fn", lambda *a, **k: ocr) + return calls + + def test_one_format_goes_to_the_named_file( + self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture, tmp_path + ) -> None: + img = self.scan(tmp_path) + self.backend(monkeypatch) + out = tmp_path / "elsewhere" / "catalogue.pdf" + out.parent.mkdir() + + assert cli.main(["ocr", str(img), "--format", "pdf", "--output", str(out)]) == 0 + + assert out.read_bytes().startswith(b"%PDF"), "a PDF, not the transcript as text" + assert not (tmp_path / "scan.pdf").exists(), "nothing written beside the source" + assert capsys.readouterr().out == "", "--output keeps stdout quiet" + + def test_the_text_format_is_the_text_writer_not_the_bare_transcript( + self, monkeypatch: pytest.MonkeyPatch, tmp_path + ) -> None: + img = self.scan(tmp_path) + self.backend(monkeypatch) + out = tmp_path / "transcript.txt" + + assert cli.main(["ocr", str(img), "--format", "text", "--output", str(out)]) == 0 + + assert out.read_text(encoding="utf-8") == "hello\n" + assert not (tmp_path / "scan.txt").exists() + + def test_the_bare_pdf_flag_counts_as_the_one_format( + self, monkeypatch: pytest.MonkeyPatch, tmp_path + ) -> None: + img = self.scan(tmp_path) + self.backend(monkeypatch) + out = tmp_path / "named.pdf" + + assert cli.main(["ocr", str(img), "--pdf", "--output", str(out)]) == 0 + + assert out.read_bytes().startswith(b"%PDF") + assert not (tmp_path / "scan.pdf").exists() + + def test_several_formats_are_refused_before_the_ocr_runs( + self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture, tmp_path + ) -> None: + img = self.scan(tmp_path) + calls = self.backend(monkeypatch) + out = tmp_path / "out" + + assert cli.main(["ocr", str(img), "--format", "text,pdf", "--output", str(out)]) == 2 + + err = capsys.readouterr().err + assert "--output" in err and "text, pdf" in err + assert calls["n"] == 0, "refused before paying for the OCR" + assert not out.exists() + assert not (tmp_path / "scan.txt").exists() and not (tmp_path / "scan.pdf").exists() + + def test_output_alone_still_writes_the_bare_transcript( + self, monkeypatch: pytest.MonkeyPatch, tmp_path + ) -> None: + """The pre-existing contract, unchanged: no format, no formatting.""" + img = self.scan(tmp_path) + self.backend(monkeypatch) + out = tmp_path / "anything.pdf" + + assert cli.main(["ocr", str(img), "--output", str(out)]) == 0 + + assert out.read_text(encoding="utf-8") == "hello" diff --git a/tests/ocr/test_outputs.py b/tests/ocr/test_outputs.py index 4fbe724..600f64a 100644 --- a/tests/ocr/test_outputs.py +++ b/tests/ocr/test_outputs.py @@ -109,3 +109,14 @@ def test_the_text_writers_tolerate_the_span_options(self, tmp_path: Path) -> Non assert md.read_text(encoding="utf-8") == "# postcard\n\nsome words\n" assert txt.read_text(encoding="utf-8") == "some words\n" + + def test_write_to_honours_the_name_it_is_given(self, tmp_path: Path) -> None: + """No stem rule and no collision guard: the caller chose the name.""" + source = tmp_path / "postcard.jpg" + source.touch() + chosen = tmp_path / "elsewhere.name" + + written = outputs.write_to("markdown", source, "some words", chosen) + + assert written == chosen + assert chosen.read_text(encoding="utf-8") == "# postcard\n\nsome words\n"