diff --git a/evaluation/ocr/registers.csv b/evaluation/ocr/registers.csv index 847881d..cc79cce 100644 --- a/evaluation/ocr/registers.csv +++ b/evaluation/ocr/registers.csv @@ -1,19 +1,19 @@ register,label,tetrak-hy v7 (ours)_chr,tetrak-hy v7 (ours)_wrd,hye-calfa-n_chr,hye-calfa-n_wrd,hye-paddle_chr,hye-paddle_wrd,marker_chr,marker_wrd,tesseract-hye_chr,tesseract-hye_wrd totovents-works,"Totovents, Works",0.9871,0.9649,0.9844,0.9413,0.9849,0.9405,0.8143,0.8067,0.9383,0.7394 khrimian-works,"Khrimian, Works",0.9813,0.9576,0.9827,0.9383,0.9849,0.9431,0.9161,0.8884,0.9450,0.7983 -medical-encyclopedia,Medical encyclopedia,0.9598,0.9513,0.9753,0.8290,0.3025,0.9331,0.8882,0.9141,0.9730,0.8768 +medical-encyclopedia,Medical encyclopedia,0.9533,0.9558,0.9753,0.8290,0.3025,0.9331,0.8882,0.9141,0.9730,0.8768 otyan-works,"Otyan, Works",0.9854,0.9504,0.9782,0.9291,0.9812,0.9343,0.9200,0.8372,0.9229,0.7270 toranian-erkirner-ew-marder,"Toranian, Erkirner ew marder",0.9699,0.9386,0.9735,0.8380,0.9839,0.9095,0.9715,0.8858,0.9829,0.9014 baronian-vol10,"Baronian, Works",0.9857,0.9373,0.9817,0.9106,0.9834,0.9185,0.8638,0.7869,0.9425,0.7444 tumanyan-elzh5,Tumanyan (academic edition),0.9749,0.9366,0.9503,0.9040,0.9697,0.9130,0.6583,0.7082,0.8887,0.7129 aram-manukyan-documents,"Aram Manukyan, Documents",0.9576,0.9340,0.9598,0.9240,0.9629,0.9407,0.9421,0.9121,0.9335,0.8006 haykakan-tpagrutyun,Armenian printing (Teodik),0.9806,0.9269,0.9706,0.8937,0.9763,0.8991,0.7321,0.6753,0.8990,0.6368 -ase-vol2,Encyclopedia (ASE vol. 2),0.9713,0.9109,0.9600,0.8426,0.3342,0.8648,0.5262,0.8358,0.9456,0.7728 +ase-vol2,Encyclopedia (ASE vol. 2),0.9751,0.9170,0.9600,0.8426,0.3342,0.8648,0.5262,0.8358,0.9456,0.7728 kajaznuni-azg-ew-hayrenik,"Kajaznuni, Azg ew hayrenik",0.9743,0.9005,0.9569,0.8517,0.9763,0.8857,0.6658,0.5721,0.8773,0.6035 faustus-1968,Faustus of Byzantium (1968),0.9649,0.8979,0.9762,0.9138,0.9271,0.9222,0.9188,0.8602,0.9286,0.7157 baronian-azgayin-jojer,"Baronian, Azgayin jojer",0.9770,0.8880,0.9675,0.8528,0.9806,0.8936,0.7403,0.6847,0.8761,0.6112 +abovyan-vol1,"Abovyan, Works vol. 1",0.9208,0.8346,0.9199,0.8712,0.9456,0.9096,0.9028,0.8064,0.8320,0.6069 aghbalyan-criticism,"Aghbalyan, Criticism",0.8963,0.8239,0.8630,0.8010,0.8962,0.8456,0.7711,0.6996,0.8004,0.5864 -abovyan-vol1,"Abovyan, Works vol. 1",0.8999,0.7939,0.9199,0.8712,0.9456,0.9096,0.9028,0.8064,0.8320,0.6069 khatisian-memoirs,"Khatisian, Memoirs",0.9438,0.7616,0.9002,0.7476,0.9782,0.8564,0.7139,0.6167,0.7574,0.3874 dictionary-hy-en,Dictionary (hy–en),0.8234,0.6874,0.4008,0.1092,0.4348,0.4574,0.6628,0.6781,0.3386,0.0462 -mean,Mean over registers,0.9549,0.8919,0.9236,0.8293,0.8590,0.8804,0.8005,0.7746,0.8695,0.6628 +mean,Mean over registers,0.9560,0.8949,0.9236,0.8293,0.8590,0.8804,0.8005,0.7746,0.8695,0.6628 diff --git a/site/content/ocr/reference/engines.md b/site/content/ocr/reference/engines.md index e9b524a..8bc5703 100644 --- a/site/content/ocr/reference/engines.md +++ b/site/content/ocr/reference/engines.md @@ -117,10 +117,12 @@ Since v7, `easyocr-hy` leads both means, and leads word recall on eleven of the seventeen registers. The other six go to Calfa's `hye-paddle`, and five of them are classical: -- **Abovyan's collected works and Khatisian's memoirs:** the two classical - registers v7 reads worst, and `hye-paddle` is well ahead on both, by - 0.12 and 0.10 of word recall. These are the registers to study before - the next run. +- **Khatisian's memoirs and Abovyan's collected works:** `hye-paddle` is + well ahead on both, by 0.10 and 0.08 of word recall. Khatisian is set in + a heavy cursive italic the recogniser has seen little of; Abovyan is a + faint grey photograph, and was 0.04 further behind before the pipeline + began stretching such pages (below). These are the registers to study + before the next run. - **Aghbalyan's criticism, Aram Manukyan's documents and Baronian's *Azgayin jojer*:** `hye-paddle` ahead by between 0.006 and 0.02, within the run-to-run noise on the last two. @@ -148,9 +150,22 @@ Calfa's two models are the strongest of the others. Both are CC BY-NC 2.0, and its word list is CC BY-SA 4.0, as the sources it is counted from require. -Three steps sit between the raw recogniser and those figures, and none is +Four steps sit between the raw recogniser and those figures, and none is retraining: +- **A faint page is stretched first.** A book photographed in grey can + arrive with its ink sixty or seventy grey levels below the paper, and + the detector then breaks words apart and drops letters that no + recogniser can put back. A page whose darkest thousandth of pixels is + lighter than grey level 45 is stretched to full contrast before + detection. That rule looks at the ink and not the paper, because a + register of black ink on toned paper read a little worse stretched. It + fires on three of the seventeen registers: Abovyan gains 0.04 of word + recall, the encyclopedia gains a little on both measures, and the + medical encyclopedia gains a little word recall for a little character + similarity. Every other page reaches the detector untouched. The stock + `easyocr` backend applies the same rule. + - **Two word lists.** The recognition head has no language model. A word whose reading is in neither list, one built from the reformed-orthography transcripts and one from the classical ones with the Nayiri Armenian diff --git a/src/tetrak_ocr/backends/armenian.py b/src/tetrak_ocr/backends/armenian.py index 1becd92..5997fec 100644 --- a/src/tetrak_ocr/backends/armenian.py +++ b/src/tetrak_ocr/backends/armenian.py @@ -64,7 +64,7 @@ from pathlib import Path -from ..imaging import open_image, reject_multi_page +from ..imaging import detector_input, reject_multi_page from ..layout import TextSpan, Transcript, polygon_extent, to_text try: @@ -140,7 +140,10 @@ def ocr_image(path: Path) -> str: order -- column by column where the page has columns. TIFF files are converted to PNG in memory first, because EasyOCR can - have trouble reading multi-strip TIFFs directly. + have trouble reading multi-strip TIFFs directly. A faint page, a grey + photograph whose ink is nowhere near black, is stretched to full + contrast before detection (:func:`tetrak_ocr.imaging.lift_faint_ink`); + any other page reaches the detector unchanged. Args: path: Path to the image file. @@ -170,14 +173,8 @@ def ocr_image(path: Path) -> str: # tetrak_ocr.imaging. reject_multi_page(path, "easyocr-hy") - if path.suffix.lower() in {".tif", ".tiff"}: - import io - - buf = io.BytesIO() - open_image(path).convert("RGB").save(buf, format="PNG") - image_input = buf.getvalue() - else: - image_input = str(path) + # The path as it is, or PNG bytes for a TIFF and for a faint page. + image_input = detector_input(path) reader = _get_reader() results = reader.readtext(image_input, detail=1, paragraph=False, decoder=_decoder) diff --git a/src/tetrak_ocr/backends/easyocr.py b/src/tetrak_ocr/backends/easyocr.py index 4f7af0e..4616401 100644 --- a/src/tetrak_ocr/backends/easyocr.py +++ b/src/tetrak_ocr/backends/easyocr.py @@ -24,7 +24,7 @@ from pathlib import Path -from ..imaging import open_image, reject_multi_page +from ..imaging import detector_input, reject_multi_page from ..layout import TextSpan, Transcript, polygon_extent try: @@ -61,7 +61,11 @@ def ocr_image(path: Path) -> str: with a newline between each recognised region. TIFF files are converted to PNG in memory before processing because - EasyOCR can have trouble reading multi-strip TIFF files directly. + EasyOCR can have trouble reading multi-strip TIFF files directly. A + faint page, a grey photograph whose ink is nowhere near black, is + stretched to full contrast before detection + (:func:`tetrak_ocr.imaging.lift_faint_ink`); any other page reaches the + detector unchanged. Args: path: Path to the image file. @@ -90,15 +94,9 @@ def ocr_image(path: Path) -> str: # return page one as though it were the document. See tetrak_ocr.imaging. reject_multi_page(path, "easyocr") - # Convert TIFF to PNG bytes in memory for reliable loading. - if path.suffix.lower() in {".tif", ".tiff"}: - import io - - buf = io.BytesIO() - open_image(path).convert("RGB").save(buf, format="PNG") - image_input = buf.getvalue() - else: - image_input = str(path) + # The path as it is, or PNG bytes for a TIFF (converted for reliable + # loading) and for a faint page (stretched to full contrast first). + image_input = detector_input(path) reader = _get_reader() results = reader.readtext(image_input, detail=1, paragraph=False) diff --git a/src/tetrak_ocr/imaging.py b/src/tetrak_ocr/imaging.py index ed79c56..6f5d12c 100644 --- a/src/tetrak_ocr/imaging.py +++ b/src/tetrak_ocr/imaging.py @@ -33,13 +33,14 @@ from __future__ import annotations +import io import tempfile from collections.abc import Iterable, Iterator from contextlib import contextmanager from pathlib import Path import sillybos -from PIL import Image +from PIL import Image, ImageOps from sillybos.pillow import pillow_formats from .errors import InputRefusedError, MultiPageNotSupportedError @@ -67,6 +68,21 @@ """The resolution poppler renders at: pdf2image's default, used everywhere.""" +FAINT_INK_LEVEL = 45 +"""A page is faint when even its darkest thousandth of pixels is lighter +than this grey level (0 is black). Measured on 16 November 2026 over the +central three quarters of each page: the pages a contrast stretch helps sit +at 50 or above (a grey photograph of a Soviet edition at 81 to 91, two +encyclopedias at 64 to 134, an 1870s newspaper at 50 to 58), every other +evaluation page at 3 or below, and the darkest print in the corpus's +posters and magazine covers at 40 or below. A page of black ink on toned +paper is not faint by this rule, on purpose: stretching one such register +cost it a little word recall.""" + +MIN_INK_SPAN = 30 +"""...and only when that darkest thousandth is at least this far below the +paper, so a blank leaf photographed in grey is not stretched into noise.""" + RASTER_FORMATS = frozenset({"jpeg", "png", "tiff"}) """What :func:`open_image` accepts: the formats Pillow is allowed to read. A PDF is never handed to Pillow; poppler renders it.""" @@ -112,6 +128,67 @@ def open_image(path: Path) -> Image.Image: return Image.open(path, formats=pillow_formats(policy)) +def _level_below(histogram: list[int], share: float) -> int: + """The grey level at or below which *share* of the pixels lie.""" + budget = sum(histogram) * share + seen = 0 + for level, count in enumerate(histogram): + seen += count + if seen >= budget: + return level + return 255 + + +def lift_faint_ink(image: Image.Image) -> Image.Image | None: + """Stretch a faint page to full contrast; ``None`` for any other page. + + A book photographed rather than scanned can arrive with its ink only + sixty or seventy grey levels below the paper. The text detector then + breaks words apart and drops letters, and no recogniser behind it can + put them back: on ten such pages the stretch alone raised word recall + from 0.794 to 0.830, and it never changed a pixel of a page that was + already black on white. + + The page is judged on its central three quarters, so a dark binding or + a black scanner bed at the edge cannot pass for ink. It is faint when + the darkest thousandth of that region is lighter than + :data:`FAINT_INK_LEVEL` and at least :data:`MIN_INK_SPAN` below the + paper (the level six tenths of the pixels lie under). A faint page is + returned in greyscale with one per cent clipped at each end + (``ImageOps.autocontrast(cutoff=1)``), which is the operation that was + measured. + """ + grey = image.convert("L") + width, height = grey.size + centre = grey.crop( + (round(width * 0.12), round(height * 0.12), round(width * 0.88), round(height * 0.88)) + ) + histogram = centre.histogram() + ink = _level_below(histogram, 0.001) + paper = _level_below(histogram, 0.6) + if ink <= FAINT_INK_LEVEL or paper - ink < MIN_INK_SPAN: + return None + return ImageOps.autocontrast(grey, cutoff=1) + + +def detector_input(path: Path) -> str | bytes: + """What an EasyOCR reader is handed for the scan at *path*. + + The file's own path where the reader can take it as it is, so that an + ordinary page reaches the detector exactly as it always has. PNG bytes + in two cases: a TIFF, because EasyOCR can have trouble with multi-strip + TIFFs, and a faint page, stretched by :func:`lift_faint_ink`. + """ + path = Path(path) + image = open_image(path) + lifted = lift_faint_ink(image) + if lifted is None and path.suffix.lower() not in {".tif", ".tiff"}: + return str(path) + buffer = io.BytesIO() + (lifted if lifted is not None else image.convert("RGB")).save(buffer, format="PNG") + return buffer.getvalue() + + def check_pdf(path: Path) -> int: """Refuse a PDF too long, or with a page too large, to render; else count its pages. diff --git a/tests/ocr/test_faint_ink.py b/tests/ocr/test_faint_ink.py new file mode 100644 index 0000000..a713d66 --- /dev/null +++ b/tests/ocr/test_faint_ink.py @@ -0,0 +1,125 @@ +"""The faint-page rule: which pages are stretched before detection, and +that every other page reaches the reader exactly as it always has. + +The rule was measured on real scans (brief 023); what these pin is its +shape. The pages here are drawn, not scanned: paper at one grey level, a +block of "ink" at another, sized so the ink is the share of the page a +block of text is. +""" + +from __future__ import annotations + +import io +from pathlib import Path + +import pytest +from PIL import Image, ImageDraw + +from tetrak_ocr.backends import armenian +from tetrak_ocr.imaging import FAINT_INK_LEVEL, detector_input, lift_faint_ink + + +def page(paper: int, ink: int | None, *, ink_box=(200, 300, 800, 900)) -> Image.Image: + """A 1000 x 1400 page: *paper* everywhere, *ink* in one block.""" + image = Image.new("L", (1000, 1400), paper) + if ink is not None: + ImageDraw.Draw(image).rectangle(ink_box, fill=ink) + return image + + +class TestWhichPagesAreFaint: + def test_black_on_white_is_left_alone(self) -> None: + assert lift_faint_ink(page(255, 0)) is None + + def test_a_grey_photograph_is_stretched(self) -> None: + """Paper near 160, ink near 95: the page the rule was written for.""" + lifted = lift_faint_ink(page(160, 95)) + assert lifted is not None + assert lifted.mode == "L" + low, high = lifted.getextrema() + assert low <= 5 + assert high >= 250 + + def test_black_ink_on_toned_paper_is_left_alone(self) -> None: + """Toned paper is not faint ink; stretching one such register cost + it word recall, so the rule looks at the ink and not the paper.""" + assert lift_faint_ink(page(162, 8)) is None + + def test_a_sparse_page_of_black_ink_is_left_alone(self) -> None: + """A title page: a few words, properly black. The darkest + thousandth still finds them.""" + sparse = page(250, 0, ink_box=(450, 650, 520, 690)) + assert lift_faint_ink(sparse) is None + + def test_a_blank_grey_leaf_is_left_alone(self) -> None: + """Nothing to lift: stretching it would only amplify the paper.""" + assert lift_faint_ink(page(170, None)) is None + assert lift_faint_ink(page(170, 160)) is None + + def test_a_dark_edge_does_not_pass_for_ink(self) -> None: + """A binding or a scanner bed at the margin is outside the region + the page is judged on, so the faint text is still found faint.""" + image = page(160, 95) + ImageDraw.Draw(image).rectangle((0, 0, 1000, 60), fill=0) + assert lift_faint_ink(image) is not None + + def test_the_threshold_is_where_it_was_measured(self) -> None: + assert lift_faint_ink(page(230, FAINT_INK_LEVEL)) is None + assert lift_faint_ink(page(230, FAINT_INK_LEVEL + 1)) is not None + + def test_a_colour_page_is_judged_in_grey(self) -> None: + colour = Image.merge("RGB", [page(160, 95)] * 3) + assert lift_faint_ink(colour) is not None + + +class TestWhatTheReaderIsHanded: + def test_an_ordinary_page_is_handed_over_as_its_path(self, tmp_path: Path) -> None: + """Not re-encoded, not even opened by the reader differently: the + same string the backends have always passed.""" + scan = tmp_path / "page.png" + page(255, 0).save(scan) + assert detector_input(scan) == str(scan) + + def test_a_faint_page_is_handed_over_stretched(self, tmp_path: Path) -> None: + scan = tmp_path / "faint.jpg" + page(160, 95).save(scan, quality=95) + handed = detector_input(scan) + assert isinstance(handed, bytes) + low, high = Image.open(io.BytesIO(handed)).convert("L").getextrema() + assert low <= 5 + assert high >= 250 + + def test_a_tiff_is_still_converted(self, tmp_path: Path) -> None: + scan = tmp_path / "page.tif" + page(255, 0).save(scan) + handed = detector_input(scan) + assert isinstance(handed, bytes) + assert Image.open(io.BytesIO(handed)).format == "PNG" + + +class TestTheArmenianBackendUsesIt: + @pytest.fixture + def reader(self, monkeypatch: pytest.MonkeyPatch): + class Reader: + seen: list = [] + + def readtext(self, image, **kwargs): + self.seen.append(image) + return [] + + instance = Reader() + monkeypatch.setattr(armenian, "_reader", instance) + monkeypatch.setattr(armenian, "_get_reader", lambda: instance) + return instance + + def test_a_faint_page_reaches_the_detector_stretched(self, reader, tmp_path: Path) -> None: + scan = tmp_path / "faint.png" + page(160, 95).save(scan) + armenian.ocr_image(scan) + assert isinstance(reader.seen[-1], bytes) + + def test_an_ordinary_page_reaches_it_unchanged(self, reader, tmp_path: Path) -> None: + scan = tmp_path / "page.png" + page(255, 0).save(scan) + armenian.ocr_image(scan) + assert reader.seen[-1] == str(scan) diff --git a/tools/dump_layout_spans.py b/tools/dump_layout_spans.py index 9c7ba5c..773a2ab 100644 --- a/tools/dump_layout_spans.py +++ b/tools/dump_layout_spans.py @@ -53,6 +53,8 @@ REPO = Path(__file__).resolve().parent.parent sys.path.insert(0, str(REPO / "src")) +from tetrak_ocr.imaging import detector_input # noqa: E402 + NETWORK_NAME = "tetrak_hy" @@ -102,8 +104,10 @@ def spans_for_page(reader, image: Path) -> list[dict]: otherwise downstream would only make the geometry harder to read. """ spans = [] + # Through the same door as the shipped backend, so a faint page is + # stretched here exactly as it is there. for corners, text, confidence in reader.readtext( - str(image), detail=1, paragraph=False, decoder=DECODER + detector_input(image), detail=1, paragraph=False, decoder=DECODER ): xs = [float(point[0]) for point in corners] ys = [float(point[1]) for point in corners]