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
6 changes: 2 additions & 4 deletions src/tetrak_ocr/backends/armenian.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 2 additions & 4 deletions src/tetrak_ocr/backends/claude.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down
6 changes: 2 additions & 4 deletions src/tetrak_ocr/backends/easyocr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 2 additions & 4 deletions src/tetrak_ocr/backends/paddle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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())
Expand Down
27 changes: 14 additions & 13 deletions src/tetrak_ocr/backends/tesseract.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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"]
Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -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)


Expand Down Expand Up @@ -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']})")
Expand Down
6 changes: 2 additions & 4 deletions src/tetrak_ocr/backends/vision.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
19 changes: 19 additions & 0 deletions src/tetrak_ocr/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
113 changes: 109 additions & 4 deletions src/tetrak_ocr/imaging.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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:
Comment on lines +83 to +84
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():
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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()


Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand Down
12 changes: 9 additions & 3 deletions src/tetrak_ocr/orientation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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:
Expand All @@ -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
Expand Down
Loading
Loading