Implement durable image processing pipeline with outbox and recovery
This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import io
|
||||
import warnings
|
||||
|
||||
from PIL import Image, ImageOps, UnidentifiedImageError
|
||||
|
||||
|
||||
MAX_BYTES = 10_485_760
|
||||
MAX_PIXELS = 40_000_000
|
||||
JPEG_QUALITY = 85
|
||||
WEBP_QUALITY = 82
|
||||
|
||||
|
||||
class InvalidImage(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
def fitted_size(width: int, height: int, limit: int) -> tuple[int, int]:
|
||||
longest = max(width, height)
|
||||
if longest <= limit:
|
||||
return width, height
|
||||
return (
|
||||
max(1, width * limit // longest),
|
||||
max(1, height * limit // longest),
|
||||
)
|
||||
|
||||
|
||||
def encode_variant(name: str, image: Image.Image, fmt: str) -> dict:
|
||||
image.info.clear()
|
||||
output = io.BytesIO()
|
||||
|
||||
if fmt == "JPEG":
|
||||
image.save(
|
||||
output,
|
||||
format="JPEG",
|
||||
quality=JPEG_QUALITY,
|
||||
optimize=True,
|
||||
exif=b"",
|
||||
icc_profile=None,
|
||||
)
|
||||
content_type = "image/jpeg"
|
||||
else:
|
||||
image.save(
|
||||
output,
|
||||
format="WEBP",
|
||||
quality=WEBP_QUALITY,
|
||||
method=4,
|
||||
exif=b"",
|
||||
icc_profile=b"",
|
||||
xmp=b"",
|
||||
)
|
||||
content_type = "image/webp"
|
||||
|
||||
data = output.getvalue()
|
||||
return {
|
||||
"name": name,
|
||||
"content_type": content_type,
|
||||
"size_bytes": len(data),
|
||||
"width": image.width,
|
||||
"height": image.height,
|
||||
"sha256": hashlib.sha256(data).hexdigest(),
|
||||
"data": data,
|
||||
}
|
||||
|
||||
|
||||
def render_variants(data: bytes) -> list[dict]:
|
||||
if not 1 <= len(data) <= MAX_BYTES:
|
||||
raise InvalidImage("invalid_size")
|
||||
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
|
||||
with Image.open(io.BytesIO(data)) as source:
|
||||
if source.format not in ("PNG", "JPEG"):
|
||||
raise InvalidImage("invalid_format")
|
||||
width, height = source.size
|
||||
if width < 1 or height < 1 or width * height > MAX_PIXELS:
|
||||
raise InvalidImage("invalid_dimensions")
|
||||
source.verify()
|
||||
|
||||
with Image.open(io.BytesIO(data)) as source:
|
||||
oriented = ImageOps.exif_transpose(source)
|
||||
try:
|
||||
rgba = oriented.convert("RGBA")
|
||||
try:
|
||||
rgb = Image.new("RGB", rgba.size, "white")
|
||||
alpha = rgba.getchannel("A")
|
||||
try:
|
||||
rgb.paste(rgba, mask=alpha)
|
||||
finally:
|
||||
alpha.close()
|
||||
finally:
|
||||
rgba.close()
|
||||
finally:
|
||||
oriented.close()
|
||||
|
||||
try:
|
||||
variants = []
|
||||
|
||||
size = fitted_size(rgb.width, rgb.height, 256)
|
||||
with rgb.resize(size, Image.Resampling.LANCZOS) as thumb:
|
||||
variants.append(encode_variant("thumbnail", thumb, "JPEG"))
|
||||
|
||||
with ImageOps.fit(
|
||||
rgb,
|
||||
(128, 128),
|
||||
method=Image.Resampling.LANCZOS,
|
||||
centering=(0.5, 0.5),
|
||||
) as crop:
|
||||
variants.append(encode_variant("crop", crop, "JPEG"))
|
||||
|
||||
size = fitted_size(rgb.width, rgb.height, 1280)
|
||||
with rgb.resize(size, Image.Resampling.LANCZOS) as optimized:
|
||||
variants.append(encode_variant("optimized", optimized, "WEBP"))
|
||||
|
||||
return variants
|
||||
finally:
|
||||
rgb.close()
|
||||
|
||||
except (
|
||||
UnidentifiedImageError,
|
||||
Image.DecompressionBombError,
|
||||
Image.DecompressionBombWarning,
|
||||
OSError,
|
||||
SyntaxError,
|
||||
ValueError,
|
||||
) as exc:
|
||||
if isinstance(exc, InvalidImage):
|
||||
raise
|
||||
raise InvalidImage("invalid_image") from None
|
||||
Reference in New Issue
Block a user