qwen-receipt-ocr / src /image_validation.py
melvindave's picture
Support phone JPEG MPO images and clarify accepted formats
134e9f9 verified
Raw History Blame Contribute Delete
1.16 kB
from pathlib import Path
from PIL import Image, ImageOps, UnidentifiedImageError
MAX_IMAGE_PIXELS = 16_000_000
def validate_image(path: str | Path | None) -> Image.Image:
if not path:
raise ValueError("Upload a PNG, JPG/JPEG, or WebP receipt image.")
try:
with Image.open(path) as source:
# Phone JPEGs with multiple pictures can be identified as MPO.
# Pillow opens their primary image, which is the receipt to read.
if source.format not in {"PNG", "JPEG", "MPO", "WEBP"}:
raise ValueError(
f"Only PNG, JPG/JPEG, and WebP images are supported. "
f"Detected format: {source.format or 'unknown'}."
)
if source.width * source.height > MAX_IMAGE_PIXELS:
raise ValueError("Image is too large. Use an image under 16 megapixels.")
source.load()
image = ImageOps.exif_transpose(source).convert("RGB")
except (UnidentifiedImageError, OSError) as exc:
raise ValueError("The image could not be read. Try a different PNG, JPG/JPEG, or WebP file.") from exc
return image