Files
mtusi2026lab6/app/image_worker.py
T

96 lines
3.6 KiB
Python

"""Disposable, resource-limited image decoder. No app credentials/config.
Usage: python -m app.image_worker INPUT OUTPUT_DIR. Result is manifest.json.
All input comes from a trusted staging object selected by the worker in PG.
"""
from __future__ import annotations
import hashlib
import json
import math
import os
from pathlib import Path
import sys
import warnings
def fit_size(width: int, height: int, limit: int) -> tuple[int, int]:
largest = max(width, height)
if largest <= limit:
return width, height
return max(1, width * limit // largest), max(1, height * limit // largest)
def convert(source: Path, directory: Path) -> list[dict]:
from PIL import Image, ImageOps
Image.MAX_IMAGE_PIXELS = int(os.getenv("MAX_IMAGE_PIXELS", "40000000"))
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(source) as opened:
if opened.format not in {"PNG", "JPEG"}:
raise ValueError("invalid_image")
if opened.width * opened.height > Image.MAX_IMAGE_PIXELS:
raise ValueError("image_too_large")
opened.load()
oriented = ImageOps.exif_transpose(opened)
# Detach metadata and use fixed output modes. The original file
# itself is never rewritten; EXIF orientation affects variants only.
image = oriented.convert("RGBA" if "A" in oriented.getbands() or
"transparency" in oriented.info else "RGB")
oriented.close()
image.info.clear()
if image.mode == "RGBA":
rgb = Image.new("RGB", image.size, "white")
rgb.paste(image, mask=image.getchannel("A"))
else:
rgb = image
variants = []
def save(name, result, filename, content_type, **options):
path = directory / filename
result.info.clear()
result.save(path, **options)
data = path.read_bytes()
variants.append({"name": name, "filename": filename, "content_type": content_type,
"width": result.width, "height": result.height,
"size_bytes": len(data), "sha256": hashlib.sha256(data).hexdigest()})
if result is not rgb and result is not image:
result.close()
save("thumbnail", rgb.resize(fit_size(*rgb.size, 256), Image.Resampling.LANCZOS),
"thumbnail.jpg", "image/jpeg", format="JPEG", quality=85, optimize=True)
save("crop", ImageOps.fit(rgb, (128, 128), method=Image.Resampling.LANCZOS,
centering=(0.5, 0.5)),
"crop.jpg", "image/jpeg", format="JPEG", quality=85, optimize=True)
save("optimized", image.resize(fit_size(*image.size, 1280), Image.Resampling.LANCZOS),
"optimized.webp", "image/webp", format="WEBP", quality=80, method=4)
if rgb is not image:
rgb.close()
image.close()
return variants
def main() -> int:
# Linux container limits are inherited by every native decoder. Parent
# enforces a wall timeout and kills/reaps this process on expiration.
if sys.platform == "linux":
import resource
memory = int(os.getenv("WORKER_MEMORY_MB", "768")) * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (memory, memory))
cpu = math.ceil(float(os.getenv("JOB_TIMEOUT_SECONDS", "30"))) + 1
resource.setrlimit(resource.RLIMIT_CPU, (cpu, cpu))
try:
source, directory = Path(sys.argv[1]), Path(sys.argv[2])
manifest = convert(source, directory)
(directory / "manifest.json").write_text(json.dumps(manifest), encoding="utf-8")
return 0
except MemoryError:
return 21
except Exception:
return 20
if __name__ == "__main__":
raise SystemExit(main())