Files
mtusi2026lab6/src/image_variants.py
T
Самохвалов Андрей Ремович c60b3e652b feat: Carry runnable lab5 business stack into lab6 (U1)
Import committed lab5 baseline 03899d7 via git archive: API replicas,
PostgreSQL, private S3, RabbitMQ, publisher, worker, migrations, and hooks.
Preserve lab6 contracts and the separate telemetry stack. Static checks pass;
Docker runtime integration remains pending.
2026-10-02 14:43:04 +03:00

84 lines
3.2 KiB
Python

"""Deterministic, bounded image variants for one accepted PNG or JPEG."""
import hashlib
from io import BytesIO
from PIL import Image, ImageOps, UnidentifiedImageError
MAX_BYTES = 10 * 1024 * 1024
MAX_PIXELS = 40_000_000
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
class InvalidImage(ValueError):
pass
def _fit(image: Image.Image, bound: int) -> Image.Image:
factor = min(1, bound / max(image.size))
size = (max(1, int(image.width * factor)), max(1, int(image.height * factor)))
return image.resize(size, Image.Resampling.LANCZOS) if size != image.size else image
def _jpeg(image: Image.Image) -> bytes:
output = BytesIO()
image.save(output, format="JPEG", quality=85, optimize=True)
return output.getvalue()
def _variant(data: bytes, content_type: str, image: Image.Image) -> dict:
return {
"data": data,
"content_type": content_type,
"size_bytes": len(data),
"width": image.width,
"height": image.height,
"sha256": hashlib.sha256(data).hexdigest(),
}
def render(data: bytes, content_type: str) -> dict[str, dict]:
"""Preserve original bytes; orient, flatten alpha, strip metadata on derivatives."""
if not 0 < len(data) <= MAX_BYTES or content_type not in {"image/png", "image/jpeg"}:
raise InvalidImage("invalid original")
try:
with Image.open(BytesIO(data)) as source:
if {"PNG": "image/png", "JPEG": "image/jpeg"}.get(source.format) != content_type:
raise InvalidImage("wrong image type")
if source.width * source.height > MAX_PIXELS:
raise InvalidImage("too many pixels")
source.load()
original_size = source.size
oriented = ImageOps.exif_transpose(source)
if oriented.mode in {"RGBA", "LA", "P"}:
rgba = oriented.convert("RGBA")
image = Image.new("RGB", rgba.size, "white")
image.paste(rgba, mask=rgba.getchannel("A"))
else:
image = oriented.convert("RGB")
thumbnail = _fit(image, 256)
side = min(image.size)
left = (image.width - side) // 2
top = (image.height - side) // 2
crop = image.resize(
(128, 128), Image.Resampling.LANCZOS,
box=(left, top, left + side, top + side),
)
optimized = _fit(image, 1280)
webp = BytesIO()
optimized.save(webp, format="WEBP", quality=82, method=4)
return {
"original": {
"data": data, "content_type": content_type,
"size_bytes": len(data), "width": original_size[0], "height": original_size[1],
"sha256": hashlib.sha256(data).hexdigest(),
},
"thumbnail": _variant(_jpeg(thumbnail), "image/jpeg", thumbnail),
"crop": _variant(_jpeg(crop), "image/jpeg", crop),
"optimized": _variant(webp.getvalue(), "image/webp", optimized),
}
except (UnidentifiedImageError, OSError, SyntaxError, Image.DecompressionBombError) as exc:
raise InvalidImage("image decoding failed") from exc