From 3d28b8761bc2ef3a01b633e58e040ce333b8efdc Mon Sep 17 00:00:00 2001 From: Stephen Masters Date: Thu, 19 Nov 2026 17:47:37 +0000 Subject: [PATCH 1/2] feat(harvest): leave out pages whose transcripts were never checked A page marked proofread on Wikisource may be the scanned file's OCR layer, lightly tidied. Page 232 of Abovyan's first volume had about thirty wrong words in 216 (brief 023). Such a page is worst as training material: a crop teaches only where the reader disagreed with the transcript and the transcript's label was kept. With --screen-wordlist the crop harvester checks each page before cutting. A word is suspect when our reading has different letters and stock Tesseract read our word and not the transcript's; the word lists veto a confusion the two readers share. A page at 1.5 suspects per hundred words or more gives no crops and is listed in summary.json. calibrate_transcript_screen.py measures the screen on the evaluation pages against two unrelated engines agreeing, and on training harvests without cutting anything. At the default limit it leaves out 14 of the 32 worst evaluation pages and 1 of the 85 cleanest. Co-authored-by: Yvette Mankerian Co-Authored-By: Claude Fable 5.2 --- .claude/skills/tetrak-hy-training/SKILL.md | 53 ++++++ scripts/calibrate_transcript_screen.py | 195 +++++++++++++++++++ scripts/harvest_real_crops.py | 139 +++++++++++++- src/tetrak_hy_trainer/transcript_check.py | 207 +++++++++++++++++++++ tests/test_crop_filters.py | 16 ++ tests/test_transcript_check.py | 153 +++++++++++++++ 6 files changed, 753 insertions(+), 10 deletions(-) create mode 100644 scripts/calibrate_transcript_screen.py create mode 100644 src/tetrak_hy_trainer/transcript_check.py create mode 100644 tests/test_transcript_check.py diff --git a/.claude/skills/tetrak-hy-training/SKILL.md b/.claude/skills/tetrak-hy-training/SKILL.md index fdee355..adf08b3 100644 --- a/.claude/skills/tetrak-hy-training/SKILL.md +++ b/.claude/skills/tetrak-hy-training/SKILL.md @@ -254,6 +254,59 @@ teaches the wrong shape, so it fails closed. transcript, so more crops survive alignment. - `bracketed` tier is off by default: spot-checking put its precision near half. Add it only with the `crops.csv` review in hand. +- **Pass `--screen-wordlist` on every harvest** (brief 023), once for each + word list. A page marked proofread is not always a checked one: the + scanned file carries an OCR text layer, Wikisource fills a new page from + it, and a contributor can tidy the obvious damage and mark the page + proofread. Page 232 of Abovyan's first volume had about thirty wrong + words in 216 and had been "proofread" since its only revision. Such a + page is worst as training material, because a crop only teaches when the + reader disagreed with the transcript and the transcript's label was kept. + +**The transcript screen** (`transcript_check.py`). Before any crop is cut, +the page as our reader read it is set against the transcript. A word is +suspect when our reader has different letters there and stock Tesseract +read our reader's word on the page and not the transcript's; the word +lists veto a confusion the two readers share. A page at or over 1.5 +suspects per hundred words gives no crops at all, and `summary.json` lists +it under `transcript_screen.pages_left_out` with the words that condemned +it. It needs the `tesseract` command with its stock `hye` model; a +`TESSDATA_PREFIX` left over from a baseline run is ignored on purpose, +because the non-commercial models may not touch training material. + +What it was measured against, 19 November 2026 +(`scripts/calibrate_transcript_screen.py`, readings kept in +`runs/transcript-screen/`): the words where our reader and a third engine +agree against the transcript, the test Stephen checked by hand on page 232 +(seventeen of seventeen were transcript errors). Over 167 evaluation pages +the two correlate 0.74. At 1.5 the screen leaves out 16 pages: 14 of the +32 worst, 1 of the 85 cleanest. Page 232 scored 3.7 as it stood and 0.0 +corrected. On sixty pages from each of fourteen training sources: + +| Source | Status | Left out | +|---|---|---| +| Abovyan vol. 1 | proofread | 38% | +| Abovyan vol. 2 | proofread | 37% | +| Khatisian | proofread | 15% | +| Faustus | proofread | 13% | +| Encyclopedia vol. 9 | proofread | 12% | +| Kajaznuni, Khrimian, Baronian vol. 10, Toranian | proofread | 5 to 10% | +| Abovyan vol. 3, Otyan, Totovents | validated | 2 to 3% | +| Medical encyclopedia | validated | 0% | + +- **Do not lower the limit to catch more.** At 1.0 the validated sources + lose up to a fifth of their pages. The screen is meant to miss some bad + pages and almost never drop a good one. +- **Do not let the word list count against the transcript.** The first + version did (a rare transcript word against a common reading) and left + out four of the five dictionary pages: a page our reader finds hard gives + many misreadings that happen to be words, and those are the pages the + model most needs. +- **It rests on Tesseract reading the page at all.** Where Tesseract is + weak (Khatisian's cursive italic) the screen sees less, so a low share + left out is not a clean bill for that source. +- **A proofread status is evidence, not proof.** Validated pages measure + about twice as clean as proofread ones, and still carry typos. **Cyrillic and mixed tokens (brief 014).** Under charset v5 a crop whose label has an all-Cyrillic token is kept (v5 and v6 had no class for it and diff --git a/scripts/calibrate_transcript_screen.py b/scripts/calibrate_transcript_screen.py new file mode 100644 index 0000000..0ecf65c --- /dev/null +++ b/scripts/calibrate_transcript_screen.py @@ -0,0 +1,195 @@ +#!/usr/bin/env python3 +"""Measure the transcript screen on the evaluation pages, to set its limit. + +The crop harvester leaves out a page whose transcript has too many words +our reading disputes (:mod:`tetrak_hy_trainer.transcript_check`). "Too +many" is a number, and this script is where it comes from. It reads every +evaluation page exactly as the harvester would -- the same detector and +recogniser, the same reading order, stock Tesseract as the second reader -- +and prints the suspect rate per page beside an independent estimate of how +wrong the transcript is: the words where our reading and a saved +``hye-paddle`` reading agree with each other against the transcript. Two +unrelated engines agreeing is the test that was checked by hand on +Abovyan's page 232 (brief 023), where all seventeen such words were +transcript errors. + +Evaluation pages are only *read* here, which is what evaluation does. No +crop is cut and nothing is written under ``runs/eval``. The hye-paddle +readings are Calfa's, CC BY-NC: they are a yardstick for this measurement +and never an input to the screen itself. + +``--alternate register/page=path`` scores a second transcript for one page, +for example the page as it stood before it was corrected. + +The same reading works on training harvests, to see what the screen would +leave out before a harvest is run: point ``--eval-root`` at ``runs/harvest`` +and pass ``--training-pages``, which skips every held-out page. ``--limit`` +caps the pages read per directory. Each row keeps the reading and the +second reader's words, so a change to the rule can be tried on the saved +file without reading the pages again. + +Prerequisites: easyocr and torch (the sibling library's venv, as for +``harvest_real_crops.py``), the ``tesseract`` command with its stock +``hye`` model, and the word lists of the run. About six seconds a page. + +Run: + ../tetrak-easyocr-armenian/.venv/bin/python scripts/calibrate_transcript_screen.py \\ + --bundle runs/v7-b023-italic/bundle \\ + --wordlist runs/v7-b014/wordlist.tsv.gz \\ + --wordlist runs/v7-b014/wordlist-classical.tsv.gz \\ + --out runs/transcript-screen/calibration.json +""" + +from __future__ import annotations + +import argparse +import importlib.util +import json +import statistics +import sys +from pathlib import Path + +REPO = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(REPO / "src")) + +from tetrak_hy_trainer import heldout, transcript_check, wikisource # noqa: E402 +from tetrak_hy_trainer.transcript_check import aligned_words, letters # noqa: E402 + +REFERENCE_ENGINE = "hye-paddle" + + +def load_harvester(): + spec = importlib.util.spec_from_file_location( + "harvest_real_crops", REPO / "scripts" / "harvest_real_crops.py" + ) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def two_engines_against(transcript: str, ours: str, theirs: str) -> int: + """Words where both readings have the same other word in the transcript's place.""" + words = [word for word in transcript.split() if letters(word)] + first = {id(t): r for t, r in aligned_words(words, ours.split())} + second = {id(t): r for t, r in aligned_words(words, theirs.split())} + return sum( + 1 + for word in words + if id(word) in first + and id(word) in second + and letters(first[id(word)]) == letters(second[id(word)]) != letters(word) + ) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--bundle", type=Path, required=True) + parser.add_argument("--wordlist", type=Path, action="append", required=True) + parser.add_argument("--eval-root", type=Path, default=REPO / "runs" / "eval") + parser.add_argument("--register", action="append", help="only this register; repeatable") + parser.add_argument("--alternate", action="append", default=[], metavar="REGISTER/PAGE=PATH") + parser.add_argument("--out", type=Path, required=True, help="where to write every page's row") + parser.add_argument("--gpu", action="store_true") + parser.add_argument( + "--training-pages", + action="store_true", + help="the root holds training harvests: skip every held-out page", + ) + parser.add_argument("--limit", type=int, default=None, help="pages to read per directory") + args = parser.parse_args() + + if not transcript_check.tesseract_available(): + raise SystemExit("the tesseract command is needed as the second reader") + frequency = transcript_check.load_frequency(args.wordlist) + harvester = load_harvester() + reader = harvester.build_reader(args.bundle, gpu=args.gpu) + alternates = dict(item.split("=", 1) for item in args.alternate) + + rows = [] + for manifest_path in sorted(args.eval_root.glob("*/manifest.json")): + register = manifest_path.parent.name + if args.register and register not in args.register: + continue + manifest = json.loads(manifest_path.read_text(encoding="utf-8")) + index_title = manifest.get("index", "") + if args.training_pages and index_title and heldout.is_held_out(index_title): + continue + read = 0 + for entry in manifest["pages"]: + page = entry["page_number"] + if args.training_pages and heldout.page_is_held_out(index_title, page): + continue + if args.limit is not None and read >= args.limit: + break + image = manifest_path.parent / "images" / f"{page}.jpg" + text = manifest_path.parent / entry["text"] + if not (image.exists() and text.exists()): + continue + read += 1 + reading = harvester.reading_of(harvester.detect_page(reader, image)) + second = transcript_check.tesseract_words(image) + reference_path = manifest_path.parent / "readings" / REFERENCE_ENGINE / f"{page}.txt" + reference = ( + reference_path.read_text(encoding="utf-8") if reference_path.exists() else None + ) + versions = [("", text)] + if f"{register}/{page}" in alternates: + versions.append((" (alternate)", Path(alternates[f"{register}/{page}"]))) + for label, path in versions: + transcript = wikisource.normalise_transcript( + path.read_text(encoding="utf-8"), index_title + ) + check = transcript_check.check_page(transcript, reading, second, frequency) + agreed = ( + two_engines_against(transcript, reading, reference) + if reference is not None + else None + ) + row = { + "register": register, + "page": f"{page}{label}", + "quality": entry.get("quality"), + "words": check.words, + "suspects": len(check.suspects), + "per_hundred": round(check.per_hundred, 2), + "two_engines_per_hundred": ( + round(100 * agreed / check.words, 2) + if agreed is not None and check.words + else None + ), + "examples": [f"{s.transcript}/{s.reader}" for s in check.suspects[:10]], + "transcript_path": str(path), + "reading": reading, + "second_reader": second, + "reference": reference, + } + rows.append(row) + print( + f"{register:30} p{row['page']:<16} words {row['words']:5} " + f"screen {row['per_hundred']:5.2f} two engines " + f"{row['two_engines_per_hundred']}", + flush=True, + ) + + args.out.parent.mkdir(parents=True, exist_ok=True) + args.out.write_text(json.dumps(rows, ensure_ascii=False, indent=1), encoding="utf-8") + + scored = [r for r in rows if r["two_engines_per_hundred"] is not None] + if len(scored) > 2: + xs = [r["per_hundred"] for r in scored] + ys = [r["two_engines_per_hundred"] for r in scored] + bad = [r for r in scored if r["two_engines_per_hundred"] >= 2.0] + clean = [r for r in scored if r["two_engines_per_hundred"] < 1.0] + print(f"\n{len(scored)} pages; correlation {statistics.correlation(xs, ys):.2f}") + print("limit left out of the bad of the clean (bad: two engines >= 2, clean: < 1)") + for limit in (0.75, 1.0, 1.25, 1.5, 2.0): + print( + f"{limit:5.2f} {sum(r['per_hundred'] >= limit for r in scored):8} " + f"{sum(r['per_hundred'] >= limit for r in bad):4}/{len(bad):<5} " + f"{sum(r['per_hundred'] >= limit for r in clean):4}/{len(clean)}" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/harvest_real_crops.py b/scripts/harvest_real_crops.py index add28a5..d6ef639 100644 --- a/scripts/harvest_real_crops.py +++ b/scripts/harvest_real_crops.py @@ -79,6 +79,21 @@ class for it -- and a token mixing Cyrillic with Armenian or Latin Read the model bundle you pass carefully: it decides which words align. A better recogniser matches more of the transcript, so harvest with the newest weights even though the fine-tune starts from them too. + +**Pass ``--screen-wordlist`` on every harvest** (brief 023). A page marked +proofread on Wikisource may be the scanned file's OCR layer, lightly +tidied and never read against the scan, and a crop only teaches when the +reader disagreed with the transcript: the words such a page gets wrong. +With the word lists given, each page is checked before any crop is cut +(:mod:`tetrak_hy_trainer.transcript_check`): where our reading differs +from the transcript and stock Tesseract read the same word we did, the +word is suspect unless the word list knows the transcript's word and not +ours, and a page with too many gives no crops at all. The pages left out are listed in ``summary.json`` with the +words that condemned them, so a source losing many pages is seen. This +needs the ``tesseract`` command with its stock ``hye`` model:: + + ... --screen-wordlist runs/v7-b014/wordlist.tsv.gz \\ + --screen-wordlist runs/v7-b014/wordlist-classical.tsv.gz """ from __future__ import annotations @@ -95,7 +110,14 @@ class for it -- and a token mixing Cyrillic with Armenian or Latin REPO = Path(__file__).resolve().parent.parent sys.path.insert(0, str(REPO / "src")) -from tetrak_hy_trainer import align, charset, heldout, synth, wikisource # noqa: E402 +from tetrak_hy_trainer import ( # noqa: E402 + align, + charset, + heldout, + synth, + transcript_check, + wikisource, +) from tetrak_hy_trainer.align import Detection, Tier # noqa: E402 # Boxes shorter than this are detector noise -- rules, speckle, the edge of @@ -257,6 +279,11 @@ def detect_page(reader, image_path: Path) -> list[Detection]: return detections +def reading_of(detections: list[Detection]) -> str: + """The page as the recogniser read it, in reading order, for the transcript screen.""" + return " ".join(detection.text for detection in align.column_order(detections)) + + def is_line_break_fragment(crop: align.AlignedCrop) -> bool: """Whether the crop's last word is half of a word broken across lines. @@ -372,8 +399,42 @@ def main() -> int: parser.add_argument("--margin-fraction", type=float, default=0.1) parser.add_argument("--max-label-length", type=int, default=DEFAULT_MAX_LABEL_LENGTH) parser.add_argument("--gpu", action="store_true", help="let EasyOCR use a GPU") + parser.add_argument( + "--screen-wordlist", + type=Path, + action="append", + default=None, + help=( + "a wordcount list (repeatable). Turns on the transcript screen: a page " + "whose transcript has too many words that our reading and stock Tesseract " + "both dispute gives no crops; these counts veto a confusion the two readers " + "share (see transcript_check)" + ), + ) + parser.add_argument( + "--screen-limit", + type=float, + default=transcript_check.DEFAULT_MAX_SUSPECTS_PER_HUNDRED, + help="suspect words per hundred at which a page is left out", + ) args = parser.parse_args() + frequency = None + if args.screen_wordlist: + if not transcript_check.tesseract_available(): + raise SystemExit( + "--screen-wordlist needs the tesseract command (with its stock hye model) " + "as the second reader. Install it, or harvest without the screen and say so." + ) + frequency = transcript_check.load_frequency(args.screen_wordlist) + print(f"transcript screen on: {len(frequency)} words counted", flush=True) + else: + print( + "transcript screen OFF: pages are trusted on their proofread status alone. " + "Pass --screen-wordlist.", + flush=True, + ) + tiers = {Tier(name.strip()) for name in args.tiers.split(",") if name.strip()} allowed = set(charset.character_list()) @@ -407,7 +468,8 @@ def main() -> int: cyrillic_kept = 0 mixed_dropped = 0 per_source: dict[str, dict[str, int]] = {} - page_stats: dict[str, dict[str, int]] = {} + page_stats: dict[str, dict[str, int | float]] = {} + screened: list[dict] = [] started = time.time() for position, page in enumerate(pages): @@ -416,11 +478,40 @@ def main() -> int: truth = wikisource.normalise_transcript( page["text_path"].read_text(encoding="utf-8"), page["index"] ) - crops = align.align_page( - detections, - truth, - min_similarity=args.min_similarity, - bracket_span=args.bracket_span, + page_key = f"{page['source']}/{page['page_number']}" + check = None + if frequency is not None: + check = transcript_check.check_page( + truth, + reading_of(detections), + transcript_check.tesseract_words(page["image_path"]), + frequency, + ) + unchecked = check is not None and check.unchecked(args.screen_limit) + if unchecked: + # The whole page, not the suspect words: a page nobody read + # against the scan is wrong in places no screen can see. + screened.append( + { + "page": page_key, + "quality": page.get("quality"), + "words": check.words, + "suspects": len(check.suspects), + "per_hundred": round(check.per_hundred, 2), + "examples": [ + f"{suspect.transcript} / {suspect.reader}" for suspect in check.suspects[:8] + ], + } + ) + crops = ( + [] + if unchecked + else align.align_page( + detections, + truth, + min_similarity=args.min_similarity, + bracket_span=args.bracket_span, + ) ) # The blob test is relative to this page: scans vary in resolution @@ -467,23 +558,43 @@ def main() -> int: cyrillic_kept += page_cyrillic mixed_dropped += page_mixed column_count = len(align.columns(detections)) - page_stats[f"{page['source']}/{page['page_number']}"] = { + page_stats[page_key] = { "boxes": len(detections), "crops": kept, "columns": column_count, "cyrillic": page_cyrillic, "mixed_dropped": page_mixed, } + if check is not None: + page_stats[page_key]["suspects_per_hundred"] = round(check.per_hundred, 2) source = per_source.setdefault( page["source"], - {"pages": 0, "boxes": 0, "crops": 0, "cyrillic": 0, "mixed_dropped": 0}, + { + "pages": 0, + "boxes": 0, + "crops": 0, + "cyrillic": 0, + "mixed_dropped": 0, + "screened": 0, + }, ) source["pages"] += 1 + source["screened"] += unchecked source["boxes"] += len(detections) source["crops"] += kept source["cyrillic"] += page_cyrillic source["mixed_dropped"] += page_mixed + if unchecked: + print( + f" {page['source']} p{page['page_number']} [{split}] LEFT OUT: " + f"{len(check.suspects)} suspect words in {check.words} " + f"({check.per_hundred:.1f} per hundred), e.g. " + + ", ".join(f"{s.transcript}/{s.reader}" for s in check.suspects[:4]), + flush=True, + ) + continue + counts = align.tier_counts(crops) print( f" {page['source']} p{page['page_number']} [{split}] " @@ -535,6 +646,13 @@ def main() -> int: "max_label_length": args.max_label_length, "val_every": args.val_every, }, + "transcript_screen": { + "on": frequency is not None, + "wordlists": [str(path) for path in args.screen_wordlist or []], + "limit_per_hundred": args.screen_limit, + "second_reader": "tesseract hye" if frequency is not None else None, + "pages_left_out": screened, + }, "counts": { "train": len(rows["train"]), "val": len(rows["val"]), @@ -566,7 +684,8 @@ def main() -> int: print( f" {name}: {stats['pages']} pages, {stats['boxes']} boxes, " f"{stats['crops']} crops ({share:.2f}), cyrillic {stats['cyrillic']}, " - f"mixed dropped {stats['mixed_dropped']}", + f"mixed dropped {stats['mixed_dropped']}, " + f"left out by the transcript screen {stats['screened']}", flush=True, ) return 0 if total else 1 diff --git a/src/tetrak_hy_trainer/transcript_check.py b/src/tetrak_hy_trainer/transcript_check.py new file mode 100644 index 0000000..05ed7ac --- /dev/null +++ b/src/tetrak_hy_trainer/transcript_check.py @@ -0,0 +1,207 @@ +"""Was this page's transcript checked against its scan? + +A page marked proofread on Wikisource is supposed to have been read against +the scan by a person. Some were not. ProofreadPage fills a new page from the +OCR text layer inside the scanned file, and a contributor can tidy the +obvious damage, mark the page proofread and move on. What is left reads like +Armenian and is wrong: ``մեղմիին`` for ``մեղմէին``, ``չշաղել`` for ``քաղել``. +Page 232 of Abovyan's first volume carried about thirty such words in 216 +and had been "proofread" since its only revision in 2017 (brief 023). + +Such a page costs twice. As an evaluation page it charges every engine for +reading the print correctly. As a training page it is worse, because a crop +only teaches when the reader disagreed with the transcript and the +transcript's label was kept: exactly the words an unchecked page gets wrong. + +This module measures a page from what the crop harvester already has in +hand. A transcript word is *suspect* when our reader read different letters +there and a second, unrelated reader -- stock Tesseract -- read our +reader's word on the page and not the transcript's. The word list has one +job, a veto: where the transcript's word is common and the readers' is +rare, the two readers share a confusion (``դ`` and ``գ``, ``զ`` and ``ղ``) +and the transcript stands. + +That is not proof for a single word. The *rate* per page is what separates +pages. Measured on 167 evaluation pages against the count of words our +reader and a third engine agree on against the transcript -- the test +checked by hand on page 232, seventeen of seventeen -- it correlates 0.74, +and at the default limit it leaves out sixteen pages: fourteen of the +thirty-two worst, one of the eighty-five cleanest. + +The word list is deliberately not evidence *for* the reader. A first +version counted a rare transcript word against a common reading, and it +left out four of the five dictionary pages: a page our reader finds hard +gives many misreadings that happen to be words, and those are the pages +the model most needs. Requiring the second reader removed that. + +The verdict is for the whole page. A page that fails is unchecked, so its +other words cannot be trusted either: short words such as ``ի`` for ``է`` +never show up as suspects at all. +""" + +from __future__ import annotations + +import difflib +import gzip +import os +import re +import shutil +import subprocess +from collections import Counter +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path + +# Armenian letters only: U+0559 to U+055F are marks and punctuation, and a +# word must not differ from itself by an emphasis mark or a comma. +_NOT_A_LETTER = re.compile(r"[^Ա-Ֆա-և]") + +# A word at or under RARE occurrences in the word lists is one the corpus +# barely knows; at or over COMMON it is established. The gap between them +# is deliberate: a word seen five times decides nothing. +RARE = 2 +COMMON = 10 + +# The second reader's agreement counts only for words this long. Both +# readers confuse the short function words the same way (``և`` read as +# ``ն``, ``կը`` as ``կր``), and agreement there is the shared confusion. +MIN_SECOND_READER_LETTERS = 3 + +# Suspect words per hundred transcript words at which a page is treated as +# unchecked. Set from scripts/calibrate_transcript_screen.py (brief 023): +# at 1.0 the validated sources lose up to a fifth of their pages, which +# their transcripts do not deserve; at 1.5 they lose two or three in a +# hundred while Abovyan's first two volumes lose more than a third. +DEFAULT_MAX_SUSPECTS_PER_HUNDRED = 1.5 + +# Under this many words a rate means nothing: one suspect on a title page +# is not evidence about anything. +MIN_WORDS_FOR_VERDICT = 40 + + +def letters(word: str) -> str: + """The word's Armenian letters, lower case, with ``և`` spelt ``եւ``.""" + return _NOT_A_LETTER.sub("", word).lower().replace("և", "եւ") + + +@dataclass(frozen=True) +class Suspect: + """A transcript word the evidence says the page does not print.""" + + transcript: str + reader: str + + +@dataclass(frozen=True) +class PageCheck: + """What the screen found on one page.""" + + words: int + suspects: tuple[Suspect, ...] + + @property + def per_hundred(self) -> float: + return 100 * len(self.suspects) / self.words if self.words else 0.0 + + def unchecked(self, limit: float = DEFAULT_MAX_SUSPECTS_PER_HUNDRED) -> bool: + """True when the page has too many suspect words to train on.""" + return self.words >= MIN_WORDS_FOR_VERDICT and self.per_hundred >= limit + + +def load_frequency(paths: Iterable[Path]) -> Counter[str]: + """Word counts from one or more ``wordcount`` lists, keyed by letters.""" + frequency: Counter[str] = Counter() + for path in paths: + opener = gzip.open if str(path).endswith(".gz") else open + with opener(path, "rt", encoding="utf-8") as handle: + for line in handle: + word, _, rest = line.rstrip("\n").partition("\t") + count = rest.split("\t")[0] + if count.isdigit(): + frequency[letters(word)] += int(count) + frequency.pop("", None) + return frequency + + +def aligned_words(transcript: Sequence[str], reader: Sequence[str]) -> list[tuple[str, str]]: + """Pair each transcript word with the word the reader has in its place. + + Only one-for-one replacements are paired. Where the reader split a word, + joined two or lost a line, there is no saying which word stands for + which, and a guess would manufacture suspects. + """ + left = [word for word in transcript if letters(word)] + right = [word for word in reader if letters(word)] + matcher = difflib.SequenceMatcher( + None, [letters(w) for w in left], [letters(w) for w in right], autojunk=False + ) + pairs = [] + for operation, a0, a1, b0, b1 in matcher.get_opcodes(): + if operation == "replace" and a1 - a0 == b1 - b0: + pairs.extend(zip(left[a0:a1], right[b0:b1], strict=True)) + return pairs + + +def check_page( + transcript: str, + reader: str, + second_reader: Iterable[str], + frequency: Mapping[str, int] | None = None, +) -> PageCheck: + """Count the transcript words two readers dispute. + + *transcript* and *reader* are the page's text in reading order. + *second_reader* is the words another engine read anywhere on the page; + its order is not used. *frequency* lets the word list veto a suspect + where it knows the transcript's word and not the readers'. + """ + frequency = frequency or {} + transcript_words = [word for word in transcript.split() if letters(word)] + second = {letters(word) for word in second_reader} + found = [] + for theirs, ours in aligned_words(transcript_words, reader.split()): + transcript_letters, reader_letters = letters(theirs), letters(ours) + if ( + transcript_letters == reader_letters + or len(reader_letters) < MIN_SECOND_READER_LETTERS + or reader_letters not in second + or transcript_letters in second + ): + continue + shared_confusion = ( + frequency.get(transcript_letters, 0) >= COMMON + and frequency.get(reader_letters, 0) <= RARE + ) + if not shared_confusion: + found.append(Suspect(theirs, ours)) + return PageCheck(words=len(transcript_words), suspects=tuple(found)) + + +def tesseract_available() -> bool: + """True when the ``tesseract`` command is on the path.""" + return shutil.which("tesseract") is not None + + +def tesseract_words(image_path: Path, language: str = "hye", timeout: float = 300) -> list[str]: + """Every word stock Tesseract reads on the page. + + The second reader has to be independent of ours and free to use on + training material, which the stock ``hye`` model is and the + non-commercial models are not. Its order on the page is not trusted; + callers use the words as a set. + """ + environment = dict(os.environ) + # Homebrew's own tessdata holds the stock model. A TESSDATA_PREFIX left + # over from a baseline run would point at someone else's. + environment.pop("TESSDATA_PREFIX", None) + result = subprocess.run( # noqa: S603 - fixed argv, no shell + ["tesseract", str(image_path), "stdout", "-l", language], # noqa: S607 + capture_output=True, + text=True, + timeout=timeout, + env=environment, + check=False, + ) + if result.returncode != 0: + raise RuntimeError(f"tesseract failed on {image_path}: {result.stderr.strip()[:200]}") + return result.stdout.split() diff --git a/tests/test_crop_filters.py b/tests/test_crop_filters.py index 335b279..2953c15 100644 --- a/tests/test_crop_filters.py +++ b/tests/test_crop_filters.py @@ -64,3 +64,19 @@ def test_an_all_cyrillic_label_is_usable(self, script) -> None: def test_a_greek_stray_is_still_refused(self, script) -> None: allowed = set(charset.character_list()) assert not script.usable(crop("π-greek"), allowed, 60, 40.0) + + +def test_reading_of_takes_the_page_column_by_column(script): + # The transcript screen compares the page as read with the transcript, + # so the reading has to come in the transcript's order: down the left + # column, then down the right. + def box(text, x, y): + return script.Detection(text=text, bbox=(x, y, x + 300, y + 30), confidence=0.9) + + detections = [ + box("աջ վերև", 600, 100), + box("ձախ ներքև", 100, 200), + box("ձախ վերև", 100, 100), + box("աջ ներքև", 600, 200), + ] + assert script.reading_of(detections) == "ձախ վերև ձախ ներքև աջ վերև աջ ներքև" diff --git a/tests/test_transcript_check.py b/tests/test_transcript_check.py new file mode 100644 index 0000000..5546355 --- /dev/null +++ b/tests/test_transcript_check.py @@ -0,0 +1,153 @@ +"""The transcript screen: which words count as suspect, and when a page fails. + +No detector and no Tesseract are needed: the screen is a pure function of +the transcript, what our reader read, the word counts and the words a +second reader saw. The examples are from Abovyan's first volume, page 232, +whose Wikisource transcript was the scanned file's OCR layer lightly tidied +(brief 023). +""" + +from __future__ import annotations + +import gzip + +import pytest + +from tetrak_hy_trainer import transcript_check as check + +FREQUENCY = { + "մեղմէին": 40, + "քաղել": 120, + "արդէն": 900, + "արդին": 30, # a real word too: the ի-for-է slips often are, so no rule may need it rare + "մանաւանդ": 400, + "զհոգի": 60, + "իմ": 5000, + "որ": 9000, +} + + +def test_letters_ignore_marks_case_and_the_ew_ligature(): + assert check.letters("Բարեկա՛մք,") == "բարեկամք" + assert check.letters("և") == check.letters("Եւ") == "եւ" + assert check.letters("1832.") == "" + + +def test_two_readers_against_the_transcript_make_a_suspect(): + page = check.check_page( + "Ձայնք, որ մեղմիին զհոգի իմ", + "Ձայնք, որ մեղմէին զհոգի իմ", + second_reader=["Ձայնք,", "որ", "մեղմէին", "զհոգի", "իմ"], + frequency=FREQUENCY, + ) + assert [(s.transcript, s.reader) for s in page.suspects] == [("մեղմիին", "մեղմէին")] + assert page.words == 5 + + +def test_a_mark_or_a_comma_is_not_a_difference(): + page = check.check_page("Բարեկամք սիրունք,", "Բարեկա՛մք սիրունք.", ["Բարեկա՛մք", "սիրունք."]) + assert page.suspects == () + + +def test_our_reader_alone_is_not_evidence(): + # The word list would have sided with the reading here. It is not asked: + # a page our reader finds hard gives many misreadings that are words, + # and counting them left out four of five dictionary pages. + page = check.check_page( + "Ձայնք, որ մեղմիին զհոգի իմ", + "Ձայնք, որ մեղմէին զհոգի իմ", + second_reader=["Ձայնք,", "որ", "զհոգի", "իմ"], + frequency=FREQUENCY, + ) + assert page.suspects == () + + +def test_the_word_list_is_not_needed(): + page = check.check_page("Օրհասն արդին զիս", "Օրհասն արդէն զիս", ["Օրհասն", "արդէն", "զիս"]) + assert [s.reader for s in page.suspects] == ["արդէն"] + + +def test_a_second_reader_that_also_has_the_transcripts_word_decides_nothing(): + page = check.check_page("Օրհասն արդին զիս", "Օրհասն արդէն զիս", ["արդէն", "արդին"]) + assert page.suspects == () + + +def test_two_readers_sharing_a_confusion_do_not_outvote_the_word_list(): + # Both engines read դ as գ; the word list knows which is the word. + page = check.check_page( + "մանաւանդ որ", "մանաւանգ որ", second_reader=["մանաւանգ", "որ"], frequency=FREQUENCY + ) + assert page.suspects == () + # Without the word list the same two readers are believed. + assert len(check.check_page("մանաւանդ որ", "մանաւանգ որ", ["մանաւանգ", "որ"]).suspects) == 1 + + +def test_short_words_are_never_suspects(): + # և read as ն by both readers is the readers' habit, not a typo. + page = check.check_page("քնար և սրինգ", "քնար ն սրինգ", second_reader=["ն"]) + assert page.suspects == () + + +def test_only_one_for_one_replacements_are_paired(): + # The transcript split one printed word in two; no pair, no suspect. + page = check.check_page("քնար մնա սրե՛լ, ինձ", "քնար մնասցեն ինձ", ["մնասցեն"]) + assert page.suspects == () + assert check.aligned_words(["ա", "բ", "գ"], ["ա", "դ", "գ"]) == [("բ", "դ")] + + +def test_verdict_needs_enough_words_and_enough_suspects(): + suspect = check.Suspect("մեղմիին", "մեղմէին") + assert check.PageCheck(words=200, suspects=(suspect,) * 3).unchecked() + assert not check.PageCheck(words=200, suspects=(suspect,) * 2).unchecked() + # A title page: three suspects in twelve words is not a rate. + assert not check.PageCheck(words=12, suspects=(suspect,) * 3).unchecked() + assert check.PageCheck(words=200, suspects=(suspect,) * 2).unchecked(limit=1.0) + assert check.PageCheck(words=0, suspects=()).per_hundred == 0.0 + + +def test_load_frequency_sums_lists_and_keys_by_letters(tmp_path): + first = tmp_path / "wordlist.tsv.gz" + with gzip.open(first, "wt", encoding="utf-8") as handle: + handle.write("և\t10\nԵւ\t5\nարդէն\t7\textra\n") + second = tmp_path / "classical.tsv" + second.write_text("արդէն\t3\nno-count\n", encoding="utf-8") + frequency = check.load_frequency([first, second]) + assert frequency["եւ"] == 15 + assert frequency["արդէն"] == 10 + assert "" not in frequency + + +def test_tesseract_words_ignores_a_borrowed_tessdata_prefix(monkeypatch, tmp_path): + # A baseline run leaves TESSDATA_PREFIX pointing at a non-commercial + # model's directory; the screen's second reader must be the stock one. + seen = {} + + class Result: + returncode = 0 + stdout = "Ձայնք որ\nմեղմէին" + stderr = "" + + def fake_run(argv, **kwargs): + seen["argv"] = argv + seen["env"] = kwargs["env"] + return Result() + + monkeypatch.setenv("TESSDATA_PREFIX", "/somewhere/else") + monkeypatch.setattr(check.subprocess, "run", fake_run) + words = check.tesseract_words(tmp_path / "page.jpg") + assert words == ["Ձայնք", "որ", "մեղմէին"] + assert "TESSDATA_PREFIX" not in seen["env"] + assert seen["argv"][-2:] == ["-l", "hye"] + + +def test_tesseract_failure_is_an_error_not_an_empty_page(monkeypatch, tmp_path): + # An empty second reading would silently turn the screen into the + # word-list rule alone for that page. + class Result: + returncode = 1 + stdout = "" + stderr = "Error opening data file" + + monkeypatch.setattr(check.subprocess, "run", lambda argv, **kwargs: Result()) + with pytest.raises(RuntimeError, match="tesseract failed"): + check.tesseract_words(tmp_path / "page.jpg") From cdb266ff30b7370bec1fb6185f94ec6e70c41089 Mon Sep 17 00:00:00 2001 From: Stephen Masters Date: Thu, 19 Nov 2026 17:47:58 +0000 Subject: [PATCH 2/2] docs(skill): say how the screen's yardstick was checked Co-authored-by: Yvette Mankerian Co-Authored-By: Claude Fable 5.2 --- .claude/skills/tetrak-hy-training/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.claude/skills/tetrak-hy-training/SKILL.md b/.claude/skills/tetrak-hy-training/SKILL.md index adf08b3..03a9d72 100644 --- a/.claude/skills/tetrak-hy-training/SKILL.md +++ b/.claude/skills/tetrak-hy-training/SKILL.md @@ -277,7 +277,7 @@ because the non-commercial models may not touch training material. What it was measured against, 19 November 2026 (`scripts/calibrate_transcript_screen.py`, readings kept in `runs/transcript-screen/`): the words where our reader and a third engine -agree against the transcript, the test Stephen checked by hand on page 232 +agree against the transcript, the test checked by hand against the scan on page 232 (seventeen of seventeen were transcript errors). Over 167 evaluation pages the two correlate 0.74. At 1.5 the screen leaves out 16 pages: 14 of the 32 worst, 1 of the 85 cleanest. Page 232 scored 3.7 as it stood and 0.0