from __future__ import annotations import math import re from typing import Any import numpy as np from PIL import Image, ImageChops VIEW_ID = "party-name-header-lines-v1" VIEW_INSTRUCTION = " The first image is the complete document. The second image enlarges its first printed lines. Use both views of the same source to read the complete requested name; preserve every digit in the name." _ROLE = re.compile( "\\b(?:seller|merchant|vendor|customer|bill[- ]?to|recipient|payee|payer|guest|organization|business|company|legal)\\b", re.IGNORECASE, ) _OTHER_VALUE = re.compile( "\\b(?:address|number|identifier|code|date|row|label|amount)\\b", re.IGNORECASE ) def fields(schema: dict[str, dict[str, Any]]) -> list[str]: selected = [] for name, spec in schema.items(): instructions = spec.get("instructions", "") if ( spec.get("type") != "text" or spec.get("knowledge") or (not isinstance(instructions, str)) ): continue requested = re.split("[.\\n]", instructions, maxsplit=1)[0] if ( re.search("\\bname\\b", requested, re.IGNORECASE) and _ROLE.search(requested) and (not _OTHER_VALUE.search(requested)) ): selected.append(name) return selected def header_detail( image: Image.Image, *, max_pixels: int = 1600000 ) -> Image.Image | None: if image.mode != "RGB" or image.getpixel((0, 0)) != (255, 255, 255): return None ink = np.asarray(image.convert("L")) < 200 if np.mean(ink) > 0.22: return None edges = np.flatnonzero(np.diff(np.pad(ink.any(axis=1).astype(np.int8), (1, 1)))) bands = edges.reshape(-1, 2).tolist()[:6] if not bands or any((not 8 <= bottom - top <= 32 for (top, bottom) in bands)): return None top = max(0, bands[0][0] - 24) bottom = min(image.height, bands[-1][1] + 24) block = image.crop((0, top, image.width, bottom)) bounds = ImageChops.difference( block, Image.new("RGB", block.size, "white") ).getbbox() if bounds is None: return None (left, right) = (max(0, bounds[0] - 24), min(block.width, bounds[2] + 24)) block = block.crop((left, 0, right, block.height)) scale = min(3.0, math.sqrt(max_pixels / (block.width * block.height))) size = (max(1, int(block.width * scale)), max(1, int(block.height * scale))) return block.resize(size, Image.Resampling.BICUBIC) def views(image: Image.Image, *, max_pixels: int = 1600000) -> tuple[Image.Image, ...]: detail = header_detail(image, max_pixels=max_pixels) return (image, detail) if detail is not None else (image,)