"""Image pipeline v1. Runs in a CHILD process with hard CPU/address-space limits (called by worker.py). python -m src.imgproc Writes thumbnail.jpg, crop.jpg, optimized.webp and prints JSON metadata on stdout. Exit codes: 0 ok, 2 invalid image, 3 too many pixels, 4 out of memory, other = unexpected (treated as transient). """ from __future__ import annotations import hashlib import json import os import resource import sys from pathlib import Path from PIL import Image, ImageOps MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000")) THUMB_BOX, CROP_SIZE, OPT_BOX = 256, 128, 1280 JPEG_QUALITY, WEBP_QUALITY = 85, 80 # documented in REPORT.md EXIT_INVALID, EXIT_TOO_LARGE, EXIT_OOM = 2, 3, 4 def fit_box(w: int, h: int, box: int) -> tuple[int, int]: """Fit (w,h) into box x box, keep aspect ratio, never upscale, floor, min 1 px. Integer math: 320x200 -> 256x160.""" if w <= box and h <= box: return w, h if w >= h: return box, max(1, h * box // w) return max(1, w * box // h), box def flatten_on_white(img: Image.Image) -> Image.Image: """RGB image; any alpha is composited on white (JPEG has no alpha).""" if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info): rgba = img.convert("RGBA") bg = Image.new("RGB", rgba.size, (255, 255, 255)) bg.paste(rgba, mask=rgba.getchannel("A")) return bg return img.convert("RGB") def save(img: Image.Image, path: Path, fmt: str, **opts) -> dict: img.save(path, fmt, **opts) # no exif=/icc_profile= passed => metadata is stripped data = path.read_bytes() return {"size_bytes": len(data), "width": img.width, "height": img.height, "sha256": hashlib.sha256(data).hexdigest()} def process(src: Path, out: Path) -> dict: with Image.open(src) as img: if img.format not in ("PNG", "JPEG"): raise ValueError("unsupported format") if img.width < 1 or img.height < 1: raise ValueError("empty image") if img.width * img.height > MAX_IMAGE_PIXELS: # decided from the header, before any pixel buffer exists raise OverflowError("too many pixels") img.load() base = ImageOps.exif_transpose(img) # apply EXIF orientation once; result has no orientation tag base.load() result = {} # thumbnail: JPEG, fit 256x256, no upscale, alpha -> white flat = flatten_on_white(base) t = flat.resize(fit_box(*flat.size, THUMB_BOX), Image.LANCZOS) if fit_box(*flat.size, THUMB_BOX) != flat.size else flat result["thumbnail"] = {"content_type": "image/jpeg", **save(t, out / "thumbnail.jpg", "JPEG", quality=JPEG_QUALITY, optimize=True)} # crop: JPEG, centered square 128x128 (small sources may be upscaled) c = ImageOps.fit(flat, (CROP_SIZE, CROP_SIZE), Image.LANCZOS, centering=(0.5, 0.5)) result["crop"] = {"content_type": "image/jpeg", **save(c, out / "crop.jpg", "JPEG", quality=JPEG_QUALITY, optimize=True)} # optimized: WebP, fit 1280x1280, no upscale, keeps alpha, lossy q=80, no EXIF/ICC o = base if base.mode in ("RGB", "RGBA") else (base.convert("RGBA") if "A" in base.getbands() or base.mode == "P" else base.convert("RGB")) size = fit_box(*o.size, OPT_BOX) if size != o.size: o = o.resize(size, Image.LANCZOS) result["optimized"] = {"content_type": "image/webp", **save(o, out / "optimized.webp", "WEBP", quality=WEBP_QUALITY, method=4)} return result def main() -> int: mem_mb, cpu_s = int(os.getenv("IMG_MEMORY_MB", "1024")), int(os.getenv("IMG_CPU_SECONDS", "60")) resource.setrlimit(resource.RLIMIT_AS, (mem_mb * 1024 * 1024, mem_mb * 1024 * 1024)) resource.setrlimit(resource.RLIMIT_CPU, (cpu_s, cpu_s + 5)) Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS try: print(json.dumps(process(Path(sys.argv[1]), Path(sys.argv[2])))) return 0 except OverflowError: return EXIT_TOO_LARGE except Image.DecompressionBombError: return EXIT_TOO_LARGE except MemoryError: return EXIT_OOM except (ValueError, OSError, SyntaxError, Image.UnidentifiedImageError): return EXIT_INVALID if __name__ == "__main__": sys.exit(main())