diff --git a/src/tetrak_ocr/backends/armenian.py b/src/tetrak_ocr/backends/armenian.py index 922e767..0be1bf5 100644 --- a/src/tetrak_ocr/backends/armenian.py +++ b/src/tetrak_ocr/backends/armenian.py @@ -58,9 +58,7 @@ from pathlib import Path -from PIL import Image - -from ..imaging import reject_multi_page +from ..imaging import open_image, reject_multi_page from ..layout import TextSpan, Transcript, polygon_extent, to_text try: @@ -166,7 +164,7 @@ def ocr_image(path: Path) -> str: import io buf = io.BytesIO() - Image.open(path).convert("RGB").save(buf, format="PNG") + open_image(path).convert("RGB").save(buf, format="PNG") image_input = buf.getvalue() else: image_input = str(path) diff --git a/src/tetrak_ocr/backends/claude.py b/src/tetrak_ocr/backends/claude.py index 1a1eed3..e83a076 100644 --- a/src/tetrak_ocr/backends/claude.py +++ b/src/tetrak_ocr/backends/claude.py @@ -24,7 +24,7 @@ import base64 from pathlib import Path -from ..imaging import reject_multi_page +from ..imaging import open_image, reject_multi_page try: import anthropic @@ -105,10 +105,8 @@ def _to_base64(path: Path) -> tuple[str, str]: elif suffix in {".tif", ".tiff"}: from io import BytesIO - from PIL import Image - buf = BytesIO() - Image.open(path).save(buf, format="PNG") + open_image(path).save(buf, format="PNG") return base64.standard_b64encode(buf.getvalue()).decode(), "image/png" elif suffix == ".pdf": return base64.standard_b64encode(path.read_bytes()).decode(), "application/pdf" diff --git a/src/tetrak_ocr/backends/easyocr.py b/src/tetrak_ocr/backends/easyocr.py index 84d207f..4f7af0e 100644 --- a/src/tetrak_ocr/backends/easyocr.py +++ b/src/tetrak_ocr/backends/easyocr.py @@ -24,9 +24,7 @@ from pathlib import Path -from PIL import Image - -from ..imaging import reject_multi_page +from ..imaging import open_image, reject_multi_page from ..layout import TextSpan, Transcript, polygon_extent try: @@ -97,7 +95,7 @@ def ocr_image(path: Path) -> str: import io buf = io.BytesIO() - Image.open(path).convert("RGB").save(buf, format="PNG") + open_image(path).convert("RGB").save(buf, format="PNG") image_input = buf.getvalue() else: image_input = str(path) diff --git a/src/tetrak_ocr/backends/paddle.py b/src/tetrak_ocr/backends/paddle.py index 53beb27..d8316c1 100644 --- a/src/tetrak_ocr/backends/paddle.py +++ b/src/tetrak_ocr/backends/paddle.py @@ -25,9 +25,7 @@ import os from pathlib import Path -from PIL import Image - -from ..imaging import reject_multi_page +from ..imaging import open_image, reject_multi_page from ..layout import TextSpan, Transcript, polygon_extent # PaddlePaddle's C++ layer reads these as glog initialises, which happens @@ -122,7 +120,7 @@ def ocr_image(path: Path) -> str: import tempfile buf = io.BytesIO() - Image.open(path).convert("RGB").save(buf, format="PNG") + open_image(path).convert("RGB").save(buf, format="PNG") buf.seek(0) with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp: tmp.write(buf.read()) diff --git a/src/tetrak_ocr/backends/tesseract.py b/src/tetrak_ocr/backends/tesseract.py index 3ad5897..8a028b3 100644 --- a/src/tetrak_ocr/backends/tesseract.py +++ b/src/tetrak_ocr/backends/tesseract.py @@ -18,7 +18,7 @@ import pytesseract from PIL import Image, ImageEnhance, ImageOps, ImageStat -from ..imaging import frame_count, iter_frames, pdf_renderer +from ..imaging import frame_count, iter_frames, open_image, streamed_pages from . import tuning # File extensions this module can handle. @@ -186,7 +186,7 @@ def ocr_image( # to every page -- see _ocr_image_file for why that is the conservative # choice rather than a measured one. if auto and (contrast is None or psm is None): - with Image.open(path) as image: + with open_image(path) as image: config = analyse_image(image) contrast = contrast if contrast is not None else config["contrast"] psm = psm if psm is not None else config["psm"] @@ -225,7 +225,7 @@ def _ocr_image_file( pages = frame_count(path) if pages == 1: - with Image.open(path) as image: + with open_image(path) as image: return pytesseract.image_to_string( preprocess(image, contrast), config=f"--psm {psm}", lang=lang ) @@ -271,20 +271,21 @@ def _ocr_pdf( the comparison before assuming the defaults still win — a PDF-specific band set may become worth fitting once there is enough material to fit it to. """ - # Imported through the shared helper so a missing renderer is explained - # the same way wherever it is hit. - convert_from_path = pdf_renderer() - # `auto` is intentionally unused here — see the docstring for the measured # comparison that settled it. contrast = contrast if contrast is not None else DEFAULT_CONTRAST psm = psm if psm is not None else DEFAULT_PSM - pages = convert_from_path(path) - page_texts = [ - pytesseract.image_to_string(preprocess(page, contrast), config=f"--psm {psm}", lang=lang) - for page in pages - ] + # Streamed, a page at a time, and checked before anything renders: the + # list convert_from_path returns held every page at once, so a long PDF + # or one with an enormous page exhausted memory before the first was read. + with streamed_pages(path) as pages: + page_texts = [ + pytesseract.image_to_string( + preprocess(page, contrast), config=f"--psm {psm}", lang=lang + ) + for page in pages + ] return "\n\n".join(page_texts) @@ -327,7 +328,7 @@ def _ocr_pdf( args = parser.parse_args() if args.analyse: - img = Image.open(args.path) + img = open_image(args.path) info = analyse_image(img) print(f"Image analysis: {args.path.name}") print(f" StdDev: {info['stddev']:.1f} (contrast → {info['contrast']})") diff --git a/src/tetrak_ocr/backends/vision.py b/src/tetrak_ocr/backends/vision.py index 56f78f5..c0cfa5d 100644 --- a/src/tetrak_ocr/backends/vision.py +++ b/src/tetrak_ocr/backends/vision.py @@ -51,9 +51,7 @@ import sys from pathlib import Path -from PIL import Image - -from ..imaging import reject_multi_page +from ..imaging import open_image, reject_multi_page from ..layout import TextSpan, Transcript, to_text # Two separate reasons this backend may be unavailable, and they need to be @@ -177,7 +175,7 @@ def ocr_image( # Hand Pillow's decoded image over rather than the path. Vision reads a # narrower set of TIFF variants than Pillow does, and the conversion is # the same one the EasyOCR backend makes for the same reason. - with Image.open(path) as image: + with open_image(path) as image: prepared = image.convert("RGB") # Captured inside the block: the boxes Vision returns are normalised, # and turning them back into pixels needs the size they were measured diff --git a/src/tetrak_ocr/errors.py b/src/tetrak_ocr/errors.py index 0db759e..ba5892f 100644 --- a/src/tetrak_ocr/errors.py +++ b/src/tetrak_ocr/errors.py @@ -141,3 +141,22 @@ def __init__(self, path: Path, pages: int) -> None: f"Refusing rather than putting every page's text on page one. Transcribe " f"without --pdf, or split the file into single pages first." ) + + +class InputRefusedError(OcrPipelineError): + """A file was refused before any decoder read more than its header. + + Raised for a file that is not one of the formats Tetrak reads, whatever + its name says, or that is larger than any real scan: more pixels than + :data:`tetrak_ocr.imaging.MAX_PIXELS`, more pages than + :data:`tetrak_ocr.imaging.MAX_PDF_PAGES`, or a PDF page that would render + past the pixel limit. Image libraries have had flaws that a crafted file + triggers just by being opened (Pillow's EPS and FlashPix readers, October + 2026), and a decompression bomb exhausts memory before anything fails + cleanly, so the refusal comes first and says why. + """ + + def __init__(self, path: Path, reason: str) -> None: + self.path = path + self.reason = reason + super().__init__(f"{path.name}: refused before reading. {reason}") diff --git a/src/tetrak_ocr/imaging.py b/src/tetrak_ocr/imaging.py index e5f1325..a1ab9b9 100644 --- a/src/tetrak_ocr/imaging.py +++ b/src/tetrak_ocr/imaging.py @@ -17,6 +17,14 @@ :class:`MultiPageNotSupportedError`, which names the file, the page count and a backend that will read it — rather than returning page one as though that were the document. + +It is also where every file is opened, so it is where files are refused. +:func:`open_image` lets Pillow run only the readers for the formats Tetrak +supports, so a PostScript or FlashPix file renamed ``.png`` never reaches +the readers whose flaws ran commands in October 2026, and refuses an image +with more pixels than any real scan. :func:`check_pdf` does the same for a +PDF's page count and page sizes, from poppler's ``pdfinfo``, before a page is +rendered. See the Tetrak vault's note on checking an image before OCR. """ from __future__ import annotations @@ -28,7 +36,98 @@ from PIL import Image -from .errors import MultiPageNotSupportedError +from .errors import InputRefusedError, MultiPageNotSupportedError + +ALLOWED_FORMATS = ("JPEG", "PNG", "TIFF") +"""The only Pillow readers Tetrak lets run: those for SUPPORTED_EXTENSIONS. +A PDF is never handed to Pillow; poppler renders it.""" + +MAX_PIXELS = 89_478_485 +"""The most pixels in one image or rendered page: Pillow's own warning +threshold, and 2.3 times the largest scan Tetrak has read (38.7 million, +an Armenian page at 600 dpi). Enforced here, not left to Pillow's global, +so that a program which raises the global cannot raise it for us.""" + +MAX_PDF_PAGES = 500 +"""The most pages in one PDF: three times the longest book read so far +(166 pages). Rendering streams page by page, so this bounds the time and the +temporary disk a run takes rather than its memory.""" + +PDF_RENDER_DPI = 200 +"""The resolution poppler renders at: pdf2image's default, used everywhere.""" + + +def _check_pixels(path: Path, image: Image.Image) -> None: + if image.width * image.height > MAX_PIXELS: + raise InputRefusedError( + path, + f"{image.width} x {image.height} is {image.width * image.height:,} pixels; " + f"the limit is {MAX_PIXELS:,}.", + ) + + +def open_image(path: Path) -> Image.Image: + """Open a raster scan with only Tetrak's readers, refusing an oversized one. + + Pillow decides what a file is from its contents, not its name, and then + runs the reader for that format. Passing ``formats`` means only the + JPEG, PNG and TIFF readers can be chosen, whatever the file claims to be. + Only the header has been read when the size is checked; the pixels are + decoded later, on first use. + + Raises: + InputRefusedError: If the file is not JPEG, PNG or TIFF, or has more + pixels than :data:`MAX_PIXELS`. + """ + try: + image = Image.open(path, formats=ALLOWED_FORMATS) + except Image.UnidentifiedImageError: + raise InputRefusedError( + path, f"It is not one of the formats Tetrak reads ({', '.join(ALLOWED_FORMATS)})." + ) from None + try: + _check_pixels(Path(path), image) + except InputRefusedError: + image.close() + raise + return image + + +def check_pdf(path: Path) -> int: + """Refuse a PDF too long, or with a page too large, to render; else count its pages. + + Reads poppler's ``pdfinfo``, which parses the document's structure without + rendering anything. A page's size is in points (1/72 inch), so its pixels + at :data:`PDF_RENDER_DPI` are known before poppler allocates them. + + Raises: + InputRefusedError: If poppler cannot read the file, it has more pages + than :data:`MAX_PDF_PAGES`, or a page would render to more pixels + than :data:`MAX_PIXELS`. + """ + from pdf2image import pdfinfo_from_path + + try: + pages = int(pdfinfo_from_path(str(path))["Pages"]) + except Exception as exc: + raise InputRefusedError(path, f"poppler could not read it as a PDF ({exc}).") from None + if pages > MAX_PDF_PAGES: + raise InputRefusedError(path, f"It has {pages} pages; the limit is {MAX_PDF_PAGES}.") + info = pdfinfo_from_path(str(path), first_page=1, last_page=pages) + for key, value in info.items(): + # "Page 3 size": "408 x 559.44 pts", with a paper name after on some. + if not (key.startswith("Page") and key.endswith("size")): + continue + width, _, height = str(value).split()[:3] + pixels = (float(width) / 72 * PDF_RENDER_DPI) * (float(height) / 72 * PDF_RENDER_DPI) + if pixels > MAX_PIXELS: + page = key.split()[1] + raise InputRefusedError( + path, + f"Page {page} is {value}, which renders to {pixels:,.0f} pixels at " + f"{PDF_RENDER_DPI} dpi; the limit is {MAX_PIXELS:,}.", + ) + return pages def pdf_renderer(): @@ -65,7 +164,7 @@ def frame_count(path: Path) -> int: routes. It never raises, so it is safe to call as a guard. """ try: - with Image.open(path) as image: + with open_image(path) as image: frames = int(getattr(image, "n_frames", 1)) if frames == 1: return 1 @@ -141,10 +240,12 @@ def iter_frames(path: Path) -> Iterator[Image.Image]: one open file that `seek` mutates in place, so a caller that collected them without copying would end up holding several references to the last frame. """ - with Image.open(path) as image: + with open_image(path) as image: for index in range(int(getattr(image, "n_frames", 1))): image.seek(index) if _is_page(image): + # Frame 0 was checked on opening; each later one has its own size. + _check_pixels(path, image) yield image.copy() @@ -193,11 +294,14 @@ def streamed_pages(path: Path) -> Iterator[Iterator[Image.Image]]: return convert_from_path = pdf_renderer() + check_pdf(path) with tempfile.TemporaryDirectory(prefix="tetrak-render-") as tmp: # fmt="ppm" is what pdf2image writes natively, so nothing is re-encoded # on the way to disk. - yield _release_after_use(convert_from_path(path, output_folder=tmp, fmt="ppm")) + yield _release_after_use( + convert_from_path(path, output_folder=tmp, fmt="ppm", dpi=PDF_RENDER_DPI) + ) @contextmanager @@ -235,6 +339,7 @@ def page_documents(path: Path) -> Iterator[list[Path]]: # down, and each one prints "Cannot close object, library is # destroyed. This may cause a memory leak!". A 21-page document # opens 22 of them. + check_pdf(path) pages = [] source = pdfium.PdfDocument(path) try: diff --git a/src/tetrak_ocr/orientation.py b/src/tetrak_ocr/orientation.py index 402b24b..17b2068 100644 --- a/src/tetrak_ocr/orientation.py +++ b/src/tetrak_ocr/orientation.py @@ -57,7 +57,8 @@ from PIL import Image, ImageChops, ImageFilter, ImageOps -from .errors import MissingFeatureError, OcrPipelineError +from .errors import InputRefusedError, MissingFeatureError, OcrPipelineError +from .imaging import open_image SCRIPTS = ("latin", "armenian") """The scripts whose up/down measure has been measured. Nothing else is offered.""" @@ -141,7 +142,7 @@ def detect(image: Image.Image | Path, script: str) -> Orientation: """ require(script) if isinstance(image, Path): - with Image.open(image) as im: + with open_image(image) as im: grey = ImageOps.exif_transpose(im).convert("L") else: grey = ImageOps.exif_transpose(image).convert("L") @@ -208,6 +209,11 @@ def upright(path: Path, script: str | None) -> Iterator[tuple[Path, Orientation return try: found = detect(path, script) + except InputRefusedError as exc: + # Refused, not missing a feature: the OCR that follows refuses it too, + # with the same reason, which is where the run should hear it. + yield path, Orientation(script, 0, 0.0, 0, unsure=f"could not be read: {exc}") + return except OcrPipelineError: raise except Exception as exc: @@ -216,7 +222,7 @@ def upright(path: Path, script: str | None) -> Iterator[tuple[Path, Orientation if not found.turn: yield path, found return - with Image.open(path) as im, TemporaryDirectory(prefix="tetrak-upright-") as tmp: + with open_image(path) as im, TemporaryDirectory(prefix="tetrak-upright-") as tmp: copy = Path(tmp) / f"{path.stem}.png" turn(ImageOps.exif_transpose(im), found.turn).save(copy) yield copy, found diff --git a/src/tetrak_ocr/pdf_output.py b/src/tetrak_ocr/pdf_output.py index 97d2bab..aa3ecda 100644 --- a/src/tetrak_ocr/pdf_output.py +++ b/src/tetrak_ocr/pdf_output.py @@ -63,6 +63,12 @@ # physical original rather than absurdly large. _ASSUMED_DPI = 300 +# Below this a recorded DPI is not a scan's: Pillow reports (1, 1) for a TIFF +# that carries no resolution, which made a 200 x 300 pixel page 200 x 300 +# inches, and a page that size renders to 2.4 billion pixels when the PDF is +# read back (imaging.check_pdf now refuses it). +_MIN_PLAUSIBLE_DPI = 50 + # The access derivative. NDNP and the Internet Archive both ship the PDF as an # access copy beside a preservation master, and a 600dpi archival TIFF makes a # PDF no small institution can serve from its website. @@ -209,6 +215,8 @@ def _page_size(image: Image.Image) -> tuple[float, float]: dpi = image.info.get("dpi") x_dpi = float(dpi[0]) if dpi and dpi[0] else _ASSUMED_DPI y_dpi = float(dpi[1]) if dpi and len(dpi) > 1 and dpi[1] else x_dpi + if min(x_dpi, y_dpi) < _MIN_PLAUSIBLE_DPI: + x_dpi = y_dpi = _ASSUMED_DPI return image.width / x_dpi * 72.0, image.height / y_dpi * 72.0 diff --git a/tests/ocr/test_input_limits.py b/tests/ocr/test_input_limits.py new file mode 100644 index 0000000..ff6d30a --- /dev/null +++ b/tests/ocr/test_input_limits.py @@ -0,0 +1,119 @@ +"""Files refused before any decoder reads past the header. + +Pillow picks its reader from a file's contents, not its name, so the only +gate that counts is the list of readers it may use. These build every file in +memory with Pillow itself; the PDF cases need poppler's ``pdfinfo`` and skip +without it. +""" + +import shutil +from pathlib import Path + +import pytest +from PIL import Image + +from tetrak_ocr import imaging +from tetrak_ocr.errors import InputRefusedError +from tetrak_ocr.imaging import check_pdf, iter_frames, open_image, streamed_pages +from tetrak_ocr.pdf_output import _page_size + +needs_poppler = pytest.mark.skipif( + shutil.which("pdfinfo") is None, reason="pdfinfo (poppler) reads the PDF's structure" +) + + +def page(width: int = 200, height: int = 300) -> Image.Image: + return Image.new("RGB", (width, height), "white") + + +class TestFormats: + def test_a_supported_scan_opens(self, tmp_path: Path) -> None: + path = tmp_path / "postcard.png" + page().save(path) + + with open_image(path) as image: + assert image.format == "PNG" + + def test_a_file_whose_name_lies_is_refused(self, tmp_path: Path) -> None: + """A GIF called .png: Pillow would read it as a GIF if allowed to.""" + path = tmp_path / "postcard.png" + page().save(path, format="GIF") + + with pytest.raises(InputRefusedError, match="not one of the formats"): + open_image(path) + + def test_a_postscript_file_never_reaches_the_eps_reader(self, tmp_path: Path) -> None: + """The October 2026 flaw's path: an EPS header behind a raster name.""" + path = tmp_path / "scan.jpg" + path.write_bytes(b"%!PS-Adobe-3.0 EPSF-3.0\n%%BoundingBox: 0 0 10 10\n") + + with pytest.raises(InputRefusedError, match="not one of the formats"): + open_image(path) + + +class TestPixels: + def test_an_image_over_the_limit_is_refused(self, tmp_path, monkeypatch) -> None: + monkeypatch.setattr(imaging, "MAX_PIXELS", 200 * 300 - 1) + path = tmp_path / "poster.png" + page().save(path) + + with pytest.raises(InputRefusedError, match="the limit is 59,999"): + open_image(path) + + def test_a_later_tiff_frame_over_the_limit_is_refused(self, tmp_path, monkeypatch) -> None: + """Each frame has its own size; checking frame 0 alone is not enough.""" + monkeypatch.setattr(imaging, "MAX_PIXELS", 200 * 300) + path = tmp_path / "register.tif" + page().save(path, save_all=True, append_images=[page(400, 600)]) + + frames = iter_frames(path) + next(frames).close() + with pytest.raises(InputRefusedError, match="400 x 600"): + next(frames) + + +@needs_poppler +class TestPdf: + def test_a_sane_pdf_is_counted(self, tmp_path: Path) -> None: + path = tmp_path / "programme.pdf" + page().save(path, save_all=True, append_images=[page()], resolution=300) + + assert check_pdf(path) == 2 + + def test_a_pdf_over_the_page_limit_is_refused(self, tmp_path, monkeypatch) -> None: + monkeypatch.setattr(imaging, "MAX_PDF_PAGES", 1) + path = tmp_path / "programme.pdf" + page().save(path, save_all=True, append_images=[page()], resolution=300) + + with pytest.raises(InputRefusedError, match="2 pages; the limit is 1"): + check_pdf(path) + + def test_a_page_too_large_to_render_is_refused_before_rendering(self, tmp_path: Path) -> None: + """200 x 300 pixels at 1 dpi is a page 200 x 300 inches.""" + path = tmp_path / "poster.pdf" + page().save(path, resolution=1) + + with pytest.raises(InputRefusedError, match="Page 1 is 14400 x 21600 pts"): + with streamed_pages(path): + pass + + def test_a_file_poppler_cannot_read_is_refused(self, tmp_path: Path) -> None: + path = tmp_path / "broken.pdf" + path.write_bytes(b"not a pdf at all") + + with pytest.raises(InputRefusedError, match="could not read it as a PDF"): + check_pdf(path) + + +class TestPageSize: + def test_pillows_one_dpi_for_no_resolution_is_not_believed(self) -> None: + image = page() + image.info["dpi"] = (1, 1) + + assert _page_size(image) == (48.0, 72.0) + + def test_a_real_resolution_is_kept(self) -> None: + image = page(600, 900) + image.info["dpi"] = (600, 600) + + assert _page_size(image) == (72.0, 108.0) diff --git a/tests/ocr/test_multi_page.py b/tests/ocr/test_multi_page.py index 71f2243..4f109ba 100644 --- a/tests/ocr/test_multi_page.py +++ b/tests/ocr/test_multi_page.py @@ -27,8 +27,8 @@ def scan(width: int = 200, height: int = 300) -> Image.Image: return Image.new("RGB", (width, height), "white") -def multi_frame_tiff(path: Path, frames: int = 3) -> Path: - first, *rest = [scan() for _ in range(frames)] +def multi_frame_tiff(path: Path, frames: int = 3, width: int = 200, height: int = 300) -> Path: + first, *rest = [scan(width, height) for _ in range(frames)] first.save(path, save_all=True, append_images=rest) return path @@ -128,7 +128,9 @@ def test_a_caller_owned_image_is_not_closed(self, tmp_path: Path) -> None: class TestWritingAMultiPageSearchablePdf: def test_each_page_carries_its_own_text(self, tmp_path: Path) -> None: - source = multi_frame_tiff(tmp_path / "pamphlet.tif", frames=3) + # A postcard's size at the assumed 300 dpi: the 200 x 300 default is + # two-thirds of an inch wide, too narrow for "SECOND PAGE" to fit. + source = multi_frame_tiff(tmp_path / "pamphlet.tif", frames=3, width=1200, height=1800) out = tmp_path / "out.pdf" searchable_pdf_for( diff --git a/tests/ocr/test_ocr_tesseract.py b/tests/ocr/test_ocr_tesseract.py index f3e2ac5..f018193 100644 --- a/tests/ocr/test_ocr_tesseract.py +++ b/tests/ocr/test_ocr_tesseract.py @@ -138,14 +138,17 @@ def test_lang_reaches_every_pdf_page(self, tmp_path, monkeypatch): calls = self._capture_calls(monkeypatch) - def fake_convert_from_path(path): + def fake_convert_from_path(path, **kwargs): from PIL import Image return [Image.new("RGB", (60, 20), "white"), Image.new("RGB", (60, 20), "white")] import pdf2image + from tetrak_ocr import imaging + monkeypatch.setattr(pdf2image, "convert_from_path", fake_convert_from_path) + monkeypatch.setattr(imaging, "check_pdf", lambda path: 2) pdf = tmp_path / "doc.pdf" pdf.write_bytes(b"%PDF-fake")