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
10 changes: 8 additions & 2 deletions docs/guide/command-line.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/`,
Expand Down
69 changes: 44 additions & 25 deletions src/tetrak_ocr/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand All @@ -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:
Expand Down
15 changes: 12 additions & 3 deletions src/tetrak_ocr/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
94 changes: 94 additions & 0 deletions tests/ocr/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
11 changes: 11 additions & 0 deletions tests/ocr/test_outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Loading