Render crop and optimized variants next to the thumbnail
The worker decodes the original once (JPEG draft down to the optimized box, EXIF orientation applied in place, alpha composed on white) and encodes three variants: the 256 px thumbnail, a centred 128x128 JPEG crop that may upscale and a WebP fitted into 1280x1280 without upscaling, quality 80, method 4. No EXIF, ICC or XMP is written. The byte limit is checked before decoding. ready is set by the transaction that stores all three rows, so a partial set is never published. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
045d631c12
commit
431b82fd43
@@ -35,3 +35,7 @@ class UploadAborted(AttachmentError):
|
||||
|
||||
class UnreadableImage(AttachmentError):
|
||||
pass
|
||||
|
||||
|
||||
class ImageTooDemanding(AttachmentError):
|
||||
pass
|
||||
|
||||
@@ -2,7 +2,11 @@ from dataclasses import dataclass
|
||||
from uuid import UUID
|
||||
|
||||
THUMBNAIL = "thumbnail"
|
||||
CROP = "crop"
|
||||
OPTIMIZED = "optimized"
|
||||
THUMBNAIL_BOX = 256
|
||||
CROP_SIDE = 128
|
||||
OPTIMIZED_BOX = 1280
|
||||
VARIANTS_PREFIX = "variants/"
|
||||
|
||||
|
||||
|
||||
@@ -39,7 +39,11 @@ from messenger.attachments.application.queries import GetAttachment, OpenAttachm
|
||||
from messenger.attachments.config import AttachmentsSettings, PipelineSettings
|
||||
from messenger.attachments.domain.jobs import RetryPolicy
|
||||
from messenger.attachments.infrastructure.faults import EnvironmentFaults
|
||||
from messenger.attachments.infrastructure.images import PillowImageInspector, PillowVariantRenderer
|
||||
from messenger.attachments.infrastructure.images import (
|
||||
PillowImageInspector,
|
||||
PillowVariantRenderer,
|
||||
RenderLimits,
|
||||
)
|
||||
from messenger.attachments.infrastructure.postgres import (
|
||||
PostgresAttachmentDirectory,
|
||||
PostgresAttachmentsUnitOfWork,
|
||||
@@ -170,7 +174,8 @@ class PipelineProvider(Provider):
|
||||
class WorkerProvider(Provider):
|
||||
@provide(scope=Scope.APP)
|
||||
def renderer(self, settings: PipelineSettings) -> VariantRenderer:
|
||||
return PillowVariantRenderer(settings.max_image_pixels, settings.worker_concurrency)
|
||||
limits = RenderLimits(settings.max_upload_bytes, settings.max_image_pixels)
|
||||
return PillowVariantRenderer(limits, settings.worker_concurrency)
|
||||
|
||||
@provide(scope=Scope.APP)
|
||||
def faults(self, settings: PipelineSettings, logger: Logger) -> Faults:
|
||||
|
||||
@@ -1,20 +1,43 @@
|
||||
import asyncio
|
||||
import warnings
|
||||
from dataclasses import dataclass
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from messenger.attachments.application.ports import Rendition
|
||||
from messenger.attachments.domain.errors import PayloadTooLarge, UnreadableImage, UnsupportedImage
|
||||
from messenger.attachments.domain.errors import (
|
||||
ImageTooDemanding,
|
||||
PayloadTooLarge,
|
||||
UnreadableImage,
|
||||
UnsupportedImage,
|
||||
)
|
||||
from messenger.attachments.domain.values import ImageInfo, ImageKind
|
||||
from messenger.attachments.domain.variants import THUMBNAIL, THUMBNAIL_BOX, fit
|
||||
from messenger.attachments.domain.variants import (
|
||||
CROP,
|
||||
CROP_SIDE,
|
||||
OPTIMIZED,
|
||||
OPTIMIZED_BOX,
|
||||
THUMBNAIL,
|
||||
THUMBNAIL_BOX,
|
||||
fit,
|
||||
)
|
||||
|
||||
KINDS = {"PNG": ImageKind.PNG, "JPEG": ImageKind.JPEG}
|
||||
BOMBS = (Image.DecompressionBombError, Image.DecompressionBombWarning)
|
||||
JPEG_SCALE = 8
|
||||
WIDE_MODES = frozenset({"I", "I;16", "I;16B", "I;16L", "I;16N"})
|
||||
ALPHA_MODES = frozenset({"LA", "La", "PA", "RGBa"})
|
||||
JPEG_QUALITY = 85
|
||||
JPEG = {"quality": 85, "optimize": True}
|
||||
WEBP = {"quality": 80, "method": 4}
|
||||
ENCODINGS = {"JPEG": (ImageKind.JPEG.value, "jpg"), "WEBP": ("image/webp", "webp")}
|
||||
REDUCING_GAP = 3.0
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class RenderLimits:
|
||||
max_bytes: int
|
||||
max_pixels: int
|
||||
|
||||
|
||||
class PillowImageInspector:
|
||||
@@ -68,35 +91,56 @@ def flatten(image: Image.Image) -> Image.Image:
|
||||
return image if image.mode == "RGB" else image.convert("RGB")
|
||||
|
||||
|
||||
def jpeg(name: str, image: Image.Image, box: int) -> Rendition:
|
||||
size = fit(image.width, image.height, box)
|
||||
scaled = image if size == image.size else image.resize(size, Image.Resampling.LANCZOS)
|
||||
def scaled(image: Image.Image, size: tuple[int, int]) -> Image.Image:
|
||||
if size == image.size:
|
||||
return image
|
||||
return image.resize(size, Image.Resampling.LANCZOS, reducing_gap=REDUCING_GAP)
|
||||
|
||||
|
||||
def encoded(name: str, image: Image.Image, kind: str, **options: object) -> Rendition:
|
||||
buffer = BytesIO()
|
||||
scaled.save(buffer, "JPEG", quality=JPEG_QUALITY, optimize=True)
|
||||
return Rendition(name, ImageKind.JPEG.value, "jpg", buffer.getvalue(), *size)
|
||||
image.save(buffer, kind, **options)
|
||||
content_type, extension = ENCODINGS[kind]
|
||||
return Rendition(name, content_type, extension, buffer.getvalue(), *image.size)
|
||||
|
||||
|
||||
def render_variants(data: bytes, max_pixels: int) -> list[Rendition]:
|
||||
def decoded(data: bytes, max_pixels: int) -> tuple[Image.Image, int, int]:
|
||||
try:
|
||||
with Image.open(BytesIO(data), formats=tuple(KINDS)) as image:
|
||||
if image.width * image.height > max_pixels:
|
||||
raise UnreadableImage("изображение больше допустимого числа пикселей")
|
||||
image.load()
|
||||
upright = flatten(ImageOps.exif_transpose(image))
|
||||
except UnreadableImage:
|
||||
image = Image.open(BytesIO(data), formats=tuple(KINDS))
|
||||
width, height = image.size
|
||||
if width * height > max_pixels:
|
||||
raise UnreadableImage("изображение больше допустимого числа пикселей")
|
||||
image.draft(None, fit(width, height, OPTIMIZED_BOX))
|
||||
stored = image.size
|
||||
ImageOps.exif_transpose(image, in_place=True)
|
||||
if image.size != stored:
|
||||
width, height = height, width
|
||||
return flatten(image), width, height
|
||||
except UnreadableImage, MemoryError:
|
||||
raise
|
||||
except Exception as error:
|
||||
raise UnreadableImage("изображение не декодируется") from error
|
||||
return [jpeg(THUMBNAIL, upright, THUMBNAIL_BOX)]
|
||||
|
||||
|
||||
def render_variants(data: bytes, limits: RenderLimits) -> list[Rendition]:
|
||||
if len(data) > limits.max_bytes:
|
||||
raise ImageTooDemanding("оригинал больше допустимого размера")
|
||||
upright, width, height = decoded(data, limits.max_pixels)
|
||||
square = ImageOps.fit(upright, (CROP_SIDE, CROP_SIDE), Image.Resampling.LANCZOS)
|
||||
return [
|
||||
encoded(THUMBNAIL, scaled(upright, fit(width, height, THUMBNAIL_BOX)), "JPEG", **JPEG),
|
||||
encoded(CROP, square, "JPEG", **JPEG),
|
||||
encoded(OPTIMIZED, scaled(upright, fit(width, height, OPTIMIZED_BOX)), "WEBP", **WEBP),
|
||||
]
|
||||
|
||||
|
||||
class PillowVariantRenderer:
|
||||
__slots__ = ("_max_pixels", "_slots")
|
||||
__slots__ = ("_limits", "_slots")
|
||||
|
||||
def __init__(self, max_pixels: int, concurrency: int) -> None:
|
||||
self._max_pixels = max_pixels
|
||||
def __init__(self, limits: RenderLimits, concurrency: int) -> None:
|
||||
self._limits = limits
|
||||
self._slots = asyncio.Semaphore(concurrency)
|
||||
|
||||
async def render(self, data: bytes, pipeline_version: int) -> list[Rendition]:
|
||||
async with self._slots:
|
||||
return await asyncio.to_thread(render_variants, data, self._max_pixels)
|
||||
return await asyncio.to_thread(render_variants, data, self._limits)
|
||||
|
||||
Reference in New Issue
Block a user