add level 4

This commit is contained in:
Матвей
2026-10-26 10:29:54 +03:00
parent df15ab0967
commit ff33b8a7c2
9 changed files with 265 additions and 40 deletions
+55 -16
View File
@@ -5,11 +5,12 @@ from io import BytesIO
import json
import logging
import os
import random
from uuid import UUID
from PIL import Image, ImageOps
from .broker import QUEUE, _connection
from .broker import QUEUE, _connection, publish_dlq
from .config import load_settings
from .storage.postgres import PostgresStore
from .storage.s3 import S3Settings, S3Store
@@ -32,21 +33,55 @@ def thumbnail(data: bytes) -> tuple[bytes, int, int]:
return output.getvalue(), image.width, image.height
async def process(store: PostgresStore, s3: S3Store, payload: dict) -> None:
def variants(data: bytes, max_pixels: int = 40_000_000) -> list[tuple[str, bytes, str, int, int]]:
"""Render required variants without preserving EXIF or other input metadata."""
with Image.open(BytesIO(data), formats=("PNG", "JPEG")) as source:
if source.width * source.height > max_pixels:
raise ValueError("image exceeds configured pixel limit")
image = ImageOps.exif_transpose(source).convert("RGBA")
white = Image.new("RGBA", image.size, "white")
white.alpha_composite(image)
rgb = white.convert("RGB")
thumb = rgb.copy()
thumb.thumbnail((256, 256), Image.Resampling.LANCZOS)
thumbnail_out = BytesIO(); thumb.save(thumbnail_out, "JPEG", quality=85, optimize=True)
side = min(rgb.width, rgb.height)
left, top = (rgb.width - side) // 2, (rgb.height - side) // 2
crop = rgb.crop((left, top, left + side, top + side)).resize((128, 128), Image.Resampling.LANCZOS)
crop_out = BytesIO(); crop.save(crop_out, "JPEG", quality=85, optimize=True)
optimized = rgb.copy()
optimized.thumbnail((1280, 1280), Image.Resampling.LANCZOS)
optimized_out = BytesIO(); optimized.save(optimized_out, "WEBP", quality=80, method=4)
return [
("thumbnail", thumbnail_out.getvalue(), "image/jpeg", thumb.width, thumb.height),
("crop", crop_out.getvalue(), "image/jpeg", 128, 128),
("optimized", optimized_out.getvalue(), "image/webp", optimized.width, optimized.height),
]
async def process(store: PostgresStore, s3: S3Store, payload: dict, lease_seconds: int) -> None:
attachment_id = UUID(payload["attachment_id"])
attachment = await store.claim_attachment_job(attachment_id)
attachment = await store.claim_attachment_job(attachment_id, lease_seconds)
if attachment is None:
return
original_key = f"originals/{attachment_id}"
variant_key = f"variants/{attachment_id}/thumbnail.jpg"
await s3.copy(attachment["staging_key"], original_key, attachment["content_type"])
original = await s3.download_key(attachment["staging_key"], attachment["size_bytes"], attachment["sha256"])
rendered, width, height = await asyncio.to_thread(thumbnail, original)
await s3.put(variant_key, BytesIO(rendered), len(rendered), "image/jpeg")
await store.complete_attachment_job(attachment_id, original_key, {
"object_key": variant_key, "content_type": "image/jpeg", "size_bytes": len(rendered),
"width": width, "height": height, "sha256": sha256(rendered).hexdigest(),
})
rendered = await asyncio.wait_for(
asyncio.to_thread(variants, original, s3.settings.max_pixels), timeout=lease_seconds
)
metadata = []
for name, content, content_type, width, height in rendered:
extension = "webp" if name == "optimized" else "jpg"
object_key = f"variants/{attachment_id}/{name}.{extension}"
await s3.put(object_key, BytesIO(content), len(content), content_type)
metadata.append({"name": name, "object_key": object_key, "content_type": content_type,
"size_bytes": len(content), "width": width, "height": height,
"sha256": sha256(content).hexdigest()})
await store.complete_attachment_job(attachment_id, original_key, metadata)
await s3.delete(attachment["staging_key"])
@@ -65,20 +100,24 @@ def main() -> None:
payload = json.loads(body)
if payload["type"] != "attachment.process.v1" or payload["schema_version"] != 1:
raise ValueError("unexpected broker payload")
asyncio.run(process(store, s3, payload))
asyncio.run(process(store, s3, payload, max(1, int(os.environ.get("JOB_TIMEOUT_SECONDS", "60")))))
except Exception:
logging.exception("job failed")
try:
attachment_id = UUID(payload["attachment_id"])
attempt = int(payload.get("attempt", 1))
delay = min(60.0, float(2 ** min(attempt, 6))) * random.uniform(0.5, 1.5)
retry = asyncio.run(store.retry_attachment_job(
attachment_id, max(1, int(os.environ.get("JOB_MAX_ATTEMPTS", "5")))
attachment_id, max(1, int(os.environ.get("JOB_MAX_ATTEMPTS", "5"))), delay
))
except Exception:
retry = False
if retry:
ch.basic_nack(method.delivery_tag, requeue=True)
else:
ch.basic_ack(method.delivery_tag)
if not retry:
try:
asyncio.run(publish_dlq(payload))
except Exception:
logging.exception("could not publish failed job to DLQ")
ch.basic_ack(method.delivery_tag)
else:
ch.basic_ack(method.delivery_tag)