LightOnOCR / render.py
Bapt120's picture
LightOnOCR-3 demo
18115ce verified
Raw History Blame Contribute Delete
1.9 kB
"""Turn an uploaded PDF or image into the page image the model sees."""
from __future__ import annotations
from pathlib import Path
from PIL import Image
# Longest edge used to render the training data; the model applies no further resizing, so this
# is the effective inference resolution. 1540 px works too but scores slightly lower.
DEFAULT_LONGEST_EDGE = 2048
IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff", ".gif"}
def is_pdf(path: str | Path) -> bool:
return Path(path).suffix.lower() == ".pdf"
def fit(image: Image.Image, longest_edge: int | None = DEFAULT_LONGEST_EDGE) -> Image.Image:
"""Downscale so that max(width, height) <= longest_edge. Never upscales."""
if longest_edge is None:
return image
w, h = image.size
scale = longest_edge / max(w, h)
if scale >= 1:
return image
return image.resize((max(1, round(w * scale)), max(1, round(h * scale))), Image.Resampling.LANCZOS)
def page_count(path: str | Path) -> int:
"""Number of pages of a PDF; 1 for an image."""
if not is_pdf(path):
return 1
import pypdfium2 as pdfium
pdf = pdfium.PdfDocument(str(path))
try:
return len(pdf)
finally:
pdf.close()
def render_page(path: str | Path, page: int = 1, longest_edge: int = DEFAULT_LONGEST_EDGE) -> Image.Image:
"""Page ``page`` (1-based) of a PDF rendered at the given longest edge, or the image itself, fitted."""
if not is_pdf(path):
with Image.open(path) as im:
return fit(im.convert("RGB"), longest_edge)
import pypdfium2 as pdfium
pdf = pdfium.PdfDocument(str(path))
try:
index = min(max(page, 1), len(pdf)) - 1
pdf_page = pdf[index]
w, h = pdf_page.get_size() # points
return pdf_page.render(scale=longest_edge / max(w, h)).to_pil().convert("RGB")
finally:
pdf.close()