File size: 1,902 Bytes
18115ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""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()