Spaces:
Running on Zero
Running on Zero
Download src/image_validation.py from melvindave/qwen-receipt-ocr: direct link, hf CLI and curl.
- Browser
- Download file 1.16 kB
-
https://huggingface.co/spaces/melvindave/qwen-receipt-ocr/resolve/main/src/image_validation.py
- Command line
-
hf download hf://spaces/melvindave/qwen-receipt-ocr/src/image_validation.py
-
curl -L -o image_validation.py https://huggingface.co/spaces/melvindave/qwen-receipt-ocr/resolve/main/src/image_validation.py
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 | |