This commit is contained in:
2026-11-22 17:59:11 +03:00
parent 7e1780be67
commit 813fc03da5
18 changed files with 1859 additions and 265 deletions
+108 -17
View File
@@ -1,14 +1,32 @@
"""JPEG thumbnail for pipeline v1. Crop and WebP belong to the next grade."""
"""Derivatives for pipeline v1.
thumbnail: JPEG quality 85, fit inside 256×256, never upscaled, EXIF orientation applied,
alpha composited on white. 320×200 becomes 256×160.
crop: JPEG quality 85, centered square resized to 128×128. Sources smaller than 128 px
are scaled up. Orientation and alpha match the thumbnail.
optimized: WebP quality 80, encoder method 4, fit inside 1280×1280, never upscaled.
EXIF is not written. A small source is not promised to get smaller.
Bytes are capped at 10 MiB and pixels at 40 million before decode. The worker container
memory limit is the hard cap around that.
"""
import io
from typing import Tuple
from typing import Dict, Tuple
from PIL import Image, ImageOps, UnidentifiedImageError
from .images import MAX_IMAGE_PIXELS
from .errors import ApiError
from .images import MAX_IMAGE_PIXELS, MAX_UPLOAD_BYTES, inspect_image
THUMBNAIL_BOX = 256
# Pillow's default 75 is fine for a preview; the contract only fixes the pixel size.
_JPEG_QUALITY = 85
THUMBNAIL_JPEG_QUALITY = 85
CROP_SIDE = 128
CROP_JPEG_QUALITY = 85
OPTIMIZED_BOX = 1280
OPTIMIZED_WEBP_QUALITY = 80
OPTIMIZED_WEBP_METHOD = 4
class ImageRejected(Exception):
@@ -36,29 +54,102 @@ def _on_white(image: Image.Image) -> Image.Image:
return background
def make_thumbnail(data: bytes) -> Tuple[bytes, int, int]:
"""Return JPEG bytes and the size actually written. 320×200 becomes 256×160."""
def _encode(image: Image.Image, fmt: str, **options) -> bytes:
"""Save a metadata-free copy. The caller's image is left open."""
bare = Image.frombytes(image.mode, image.size, image.tobytes())
try:
buffer = io.BytesIO()
bare.save(buffer, format=fmt, **options)
return buffer.getvalue()
finally:
bare.close()
def _fitted(base: Image.Image, box: int) -> Tuple[Image.Image, int, int]:
width, height = _fit(base.width, base.height, box)
if (width, height) == base.size:
return base, width, height
return base.resize((width, height), Image.Resampling.LANCZOS), width, height
def _jpeg_box(base: Image.Image, box: int, quality: int) -> Dict[str, object]:
image, width, height = _fitted(base, box)
try:
blob = _encode(image, 'JPEG', quality=quality)
finally:
if image is not base:
image.close()
return {'content_type': 'image/jpeg', 'width': width, 'height': height, 'data': blob}
def _crop(base: Image.Image) -> Dict[str, object]:
side = min(base.width, base.height)
left = (base.width - side) // 2
top = (base.height - side) // 2
square = base if side == base.width and side == base.height else base.crop((left, top, left + side, top + side))
try:
sized = square if square.size == (CROP_SIDE, CROP_SIDE) else square.resize(
(CROP_SIDE, CROP_SIDE), Image.Resampling.LANCZOS
)
try:
blob = _encode(sized, 'JPEG', quality=CROP_JPEG_QUALITY)
finally:
if sized is not square:
sized.close()
finally:
if square is not base:
square.close()
return {'content_type': 'image/jpeg', 'width': CROP_SIDE, 'height': CROP_SIDE, 'data': blob}
def _webp(base: Image.Image) -> Dict[str, object]:
image, width, height = _fitted(base, OPTIMIZED_BOX)
try:
blob = _encode(image, 'WEBP', quality=OPTIMIZED_WEBP_QUALITY, method=OPTIMIZED_WEBP_METHOD)
finally:
if image is not base:
image.close()
return {'content_type': 'image/webp', 'width': width, 'height': height, 'data': blob}
def render_variants(data: bytes) -> Dict[str, Dict[str, object]]:
"""Decode once and return thumbnail, crop and optimized. Raises ImageRejected."""
if len(data) > MAX_UPLOAD_BYTES:
raise ImageRejected()
try:
inspect_image(data)
except ApiError:
raise ImageRejected() from None
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
source = Image.open(io.BytesIO(data))
owned = [source]
try:
oriented = ImageOps.exif_transpose(source)
if oriented is not source:
source.close()
owned.append(oriented)
source = oriented
source.load()
width, height = source.size
if width <= 0 or height <= 0 or width * height > MAX_IMAGE_PIXELS:
raise ImageRejected()
fitted = _fit(width, height, THUMBNAIL_BOX)
if fitted != (width, height):
source = source.resize(fitted, Image.Resampling.LANCZOS)
rgb = _on_white(source)
buffer = io.BytesIO()
rgb.save(buffer, format='JPEG', quality=_JPEG_QUALITY)
return buffer.getvalue(), fitted[0], fitted[1]
base = _on_white(source)
if base is not source:
owned.append(base)
return {
'thumbnail': _jpeg_box(base, THUMBNAIL_BOX, THUMBNAIL_JPEG_QUALITY),
'crop': _crop(base),
'optimized': _webp(base),
}
except ImageRejected:
raise
except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError):
except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError, MemoryError):
raise ImageRejected() from None
finally:
source.close()
for image in owned:
image.close()
def make_thumbnail(data: bytes) -> Tuple[bytes, int, int]:
"""JPEG thumbnail bytes and the size actually written. 320×200 becomes 256×160."""
item = render_variants(data)['thumbnail']
return item['data'], int(item['width']), int(item['height'])