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
3 changes: 2 additions & 1 deletion docs/guide/command-line.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,8 @@ The scoring reads English, and only English: it counts recognised English
words and measures GPT-2 perplexity. A transcript in another script would
score 0.0 however well it was read, so the gate is **skipped, with a message,
for transcripts that are not in the Latin script** rather than sending a
whole Armenian run to triage.
whole Armenian run to triage. `auto-local`'s own gate applies the same rule
to its winning transcript, and the manifest records `skipped` either way.

### The run log

Expand Down
43 changes: 36 additions & 7 deletions src/tetrak_ocr/auto_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,12 @@
per-backend score table, which is what makes the triage manifest worth
reading.

The gate reads English, and only English, so it is skipped -- with a message,
and `last_choice` saying so -- when the winning transcript is not in the
Latin script. It used to be applied regardless, and a well-read Armenian
page scored near zero and went to triage on every run; `--quality-gate`
had the guard and this gate did not.

Backend eligibility:

GPU available + Marker installed:
Expand Down Expand Up @@ -72,7 +78,12 @@
from .backends.tesseract import (
ocr_image as _tesseract_ocr,
)
from .qa_score import MIN_QUALITY_THRESHOLD, LowQualityError, combined_score
from .qa_score import (
MIN_QUALITY_THRESHOLD,
LowQualityError,
combined_score,
scores_english_text,
)


def has_gpu() -> bool:
Expand Down Expand Up @@ -167,10 +178,13 @@ 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
# The engine the last call chose, its raw quality score and what the gate
# made of it, as {"engine": name, "quality": score, "quality_gate": verdict},
# or None before the first call or when every backend failed. The verdict is
# "passed", or "skipped" for a transcript the English-only score cannot
# judge, in which case the score is None: it was computed, and means
# nothing. 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.
Expand Down Expand Up @@ -296,7 +310,9 @@ def ocr_image(path: "Path | str", with_paddle_vl: bool = False) -> str:
Raises:
LowQualityError: If the winning combined score falls below
MIN_QUALITY_THRESHOLD. The exception carries .scores and
.transcripts dicts for triage queue reporting.
.transcripts dicts for triage queue reporting. Not raised for
a winning transcript outside the Latin script, which the score
cannot judge: that is returned with the gate skipped.
"""
global last_choice
last_choice = None
Expand Down Expand Up @@ -360,7 +376,20 @@ 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}
last_choice = {"engine": best_name, "quality": best_raw_score, "quality_gate": "passed"}

# The same guard `batch --quality-gate` applies, for the same reason: the
# metrics are English-only, so a transcript in another script scores 0.0
# however well it was read, and gating on that sent every Armenian page
# to triage while reporting each as poor quality.
if not scores_english_text(transcripts[best_name]):
last_choice.update(quality=None, quality_gate="skipped")
print(
f" [auto-local → {best_name}] quality gate skipped: this transcript is "
"not in the Latin script, and the score would be 0.0 whatever its quality",
file=sys.stderr,
)
return transcripts[best_name]

if best_raw_score < MIN_QUALITY_THRESHOLD:
raise LowQualityError(
Expand Down
5 changes: 4 additions & 1 deletion src/tetrak_ocr/batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,10 @@ def _triage(exc: "LowQualityError") -> None:
raise

if auto_local:
reading.update(_auto_local_choice(), quality_gate="passed")
# auto-local says whether its gate passed or was skipped for a
# transcript outside the Latin script; "passed" is only the default
# for an older last_choice that does not say.
reading.update({"quality_gate": "passed"} | _auto_local_choice())

if quality_gate:
from .qa_score import MIN_QUALITY_THRESHOLD, combined_score, scores_english_text
Expand Down
47 changes: 47 additions & 0 deletions tests/ocr/test_auto_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,3 +509,50 @@ def test_the_winners_spans_come_through(self, monkeypatch: pytest.MonkeyPatch) -

assert result == "the good transcript"
assert spans_of(result) == spans


class TestTheGateOnlyJudgesWhatItCanRead:
"""The gate's score is English-only, so it must not judge another script.

It did: `--quality-gate` had the guard and this gate did not, and a
well-read Armenian page scored near zero and went to triage on every run.
"""

ARMENIAN = "Կիկոսի մահը\nՀովհաննես Թումանյան"

def arrange(self, monkeypatch: pytest.MonkeyPatch, winner: str, score: float) -> None:
monkeypatch.setattr(auto_local, "_paddle_ocr", lambda p: winner)
monkeypatch.setattr(auto_local, "_tesseract_ocr", lambda p, **kw: "")
monkeypatch.setattr(auto_local, "combined_score", lambda text: score if text else 0.0)

def test_a_non_latin_winner_is_returned_with_the_gate_skipped(
self, monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture
) -> None:
self.arrange(monkeypatch, self.ARMENIAN, score=0.0502)

assert auto_local.ocr_image(Path("page.jpg")) == self.ARMENIAN

assert "quality gate skipped" in capsys.readouterr().err
assert auto_local.last_choice == {
"engine": "paddle",
"quality": None,
"quality_gate": "skipped",
}

def test_a_poor_latin_winner_is_still_triaged(self, monkeypatch: pytest.MonkeyPatch) -> None:
"""The guard is for another script, not for poor English."""
self.arrange(monkeypatch, "ISIDE FACTS", score=0.0502)

with pytest.raises(LowQualityError):
auto_local.ocr_image(Path("page.jpg"))

def test_a_good_latin_winner_records_a_pass(self, monkeypatch: pytest.MonkeyPatch) -> None:
self.arrange(monkeypatch, "Inside Facts of Stage and Screen", score=0.4)

auto_local.ocr_image(Path("page.jpg"))

assert auto_local.last_choice == {
"engine": "paddle",
"quality": 0.4,
"quality_gate": "passed",
}
22 changes: 22 additions & 0 deletions tests/ocr/test_manifest.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,28 @@ def ocr(path):
assert (row["backend"], row["engine"]) == ("auto-local", "vision")
assert (row["quality"], row["quality_gate"]) == ("0.2187", "passed")

def test_a_winner_the_gate_could_not_judge(self, working_dirs, manifest_path, monkeypatch):
"""auto-local skips its gate for a transcript outside the Latin script,
and the manifest must say so rather than claiming the gate passed."""
(working_dirs["scans"] / "page.png").touch()

def ocr(path):
auto_local.last_choice = {
"engine": "vision",
"quality": None,
"quality_gate": "skipped",
}
return "Կիկոսի մահը"

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"]) == ("processed", "vision")
assert (row["quality"], row["quality_gate"]) == ("", "skipped")
assert row["transcript"] == "Կիկոսի մահը"

def test_a_file_no_engine_could_read(self, working_dirs, manifest_path, monkeypatch):
(working_dirs["scans"] / "ruined.jpg").touch()

Expand Down
Loading