File size: 1,581 Bytes
dc7d8aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations
from typing import Any
from PIL import Image, ImageChops

COPY_INSTRUCTION = " Copy the complete printed value verbatim, including every digit, punctuation and suffix. Do not shorten, sanitize or canonicalize it."


def preserve_scalar_fields(
    fields: dict[str, dict[str, Any]],
) -> dict[str, dict[str, Any]]:
    return {
        name: {**spec, "instructions": spec.get("instructions", "") + COPY_INSTRUCTION}
        if spec.get("type") == "text"
        and (not spec.get("knowledge"))
        and isinstance(spec.get("instructions", ""), str)
        else spec
        for (name, spec) in fields.items()
    }


def focus_document(
    image: Image.Image, *, max_pixels: int = 1600000, max_scale: float = 2.0
) -> Image.Image:
    if image.mode != "RGB":
        return image
    bounds = ImageChops.difference(
        image, Image.new("RGB", image.size, "white")
    ).getbbox()
    if bounds is None:
        return image
    (left, top, right, bottom) = bounds
    bounds = (
        max(0, left - 24),
        max(0, top - 24),
        min(image.width, right + 24),
        min(image.height, bottom + 24),
    )
    (width, height) = (bounds[2] - bounds[0], bounds[3] - bounds[1])
    if width * height > image.width * image.height / 2:
        return image
    scale = min(max_scale, (max_pixels / (width * height)) ** 0.5)
    if scale <= 1:
        return image
    focused = image.crop(bounds)
    return focused.resize(
        (max(1, int(width * scale)), max(1, int(height * scale))),
        Image.Resampling.BICUBIC,
    )