forked from mtusi2026/mtusi2026lab5
feat: add crop and optimized variants, implement idempotent worker
This commit is contained in:
+9
-1
@@ -287,12 +287,20 @@ async def download_attachment(attachment_id: UUID, variant: str = Query("origina
|
||||
raise HTTPException(409, "Attachment not ready")
|
||||
|
||||
key = att.s3_key
|
||||
mime = att.content_type
|
||||
|
||||
if variant == "thumbnail":
|
||||
key = f"{att.s3_key}_thumb.jpg"
|
||||
mime = "image/jpeg"
|
||||
elif variant == "crop":
|
||||
key = f"{att.s3_key}_crop.jpg"
|
||||
mime = "image/jpeg"
|
||||
elif variant == "optimized":
|
||||
key = f"{att.s3_key}_opt.webp"
|
||||
mime = "image/webp"
|
||||
|
||||
obj = s3.get_object(Bucket=BUCKET, Key=key)
|
||||
content = obj["Body"].read()
|
||||
mime = "image/jpeg" if variant == "thumbnail" else att.content_type
|
||||
return Response(content=content, media_type=mime)
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
+56
-14
@@ -28,13 +28,17 @@ async def process_attachment(task: dict):
|
||||
if not att:
|
||||
return
|
||||
|
||||
# идемпотентность: если уже обработано, пропускаем
|
||||
if att.status == "ready" and len(att.variants) == 3:
|
||||
return
|
||||
|
||||
try:
|
||||
# получаем оригинал
|
||||
obj = s3.get_object(Bucket=BUCKET, Key=s3_key)
|
||||
content = obj["Body"].read()
|
||||
img = Image.open(io.BytesIO(content))
|
||||
|
||||
# убираем прозрачность (композируем на белый)
|
||||
# убираем прозрачность (композируем на белый) и разворачиваем по exif
|
||||
img = ImageOps.exif_transpose(img)
|
||||
if img.mode in ("RGBA", "LA"):
|
||||
background = Image.new("RGB", img.size, (255, 255, 255))
|
||||
@@ -43,29 +47,67 @@ async def process_attachment(task: dict):
|
||||
elif img.mode != "RGB":
|
||||
img = img.convert("RGB")
|
||||
|
||||
# делаем thumbnail 256x256
|
||||
variants_meta = []
|
||||
|
||||
# --- 1. Thumbnail (256x256, вписанный) ---
|
||||
thumb = img.copy()
|
||||
thumb.thumbnail((256, 256), Image.Resampling.LANCZOS)
|
||||
thumb_bytes = io.BytesIO()
|
||||
thumb.save(thumb_bytes, format="JPEG")
|
||||
thumb_data = thumb_bytes.getvalue()
|
||||
|
||||
# сохраняем в s3
|
||||
thumb_key = f"{s3_key}_thumb.jpg"
|
||||
s3.put_object(Bucket=BUCKET, Key=thumb_key, Body=thumb_data, ContentType="image/jpeg")
|
||||
|
||||
# обновляем статус и метаданные
|
||||
thumb_sha = hashlib.sha256(thumb_data).hexdigest()
|
||||
att.status = "ready"
|
||||
att.error_code = None
|
||||
att.variants = [{
|
||||
s3.put_object(Bucket=BUCKET, Key=f"{s3_key}_thumb.jpg", Body=thumb_data, ContentType="image/jpeg")
|
||||
variants_meta.append({
|
||||
"name": "thumbnail",
|
||||
"content_type": "image/jpeg",
|
||||
"width": thumb.width,
|
||||
"height": thumb.height,
|
||||
"size_bytes": len(thumb_data),
|
||||
"sha256": thumb_sha
|
||||
}]
|
||||
"sha256": hashlib.sha256(thumb_data).hexdigest()
|
||||
})
|
||||
|
||||
# --- 2. Crop (128x128, центрированный квадрат) ---
|
||||
crop_img = img.copy()
|
||||
width, height = crop_img.size
|
||||
min_dim = min(width, height)
|
||||
left = (width - min_dim) / 2
|
||||
top = (height - min_dim) / 2
|
||||
right = (width + min_dim) / 2
|
||||
bottom = (height + min_dim) / 2
|
||||
crop_img = crop_img.crop((left, top, right, bottom))
|
||||
crop_img = crop_img.resize((128, 128), Image.Resampling.LANCZOS)
|
||||
crop_bytes = io.BytesIO()
|
||||
crop_img.save(crop_bytes, format="JPEG")
|
||||
crop_data = crop_bytes.getvalue()
|
||||
s3.put_object(Bucket=BUCKET, Key=f"{s3_key}_crop.jpg", Body=crop_data, ContentType="image/jpeg")
|
||||
variants_meta.append({
|
||||
"name": "crop",
|
||||
"content_type": "image/jpeg",
|
||||
"width": 128,
|
||||
"height": 128,
|
||||
"size_bytes": len(crop_data),
|
||||
"sha256": hashlib.sha256(crop_data).hexdigest()
|
||||
})
|
||||
|
||||
# --- 3. Optimized (WebP, до 1280x1280 без увеличения) ---
|
||||
opt_img = img.copy()
|
||||
opt_img.thumbnail((1280, 1280), Image.Resampling.LANCZOS)
|
||||
opt_bytes = io.BytesIO()
|
||||
opt_img.save(opt_bytes, format="WEBP", quality=85)
|
||||
opt_data = opt_bytes.getvalue()
|
||||
s3.put_object(Bucket=BUCKET, Key=f"{s3_key}_opt.webp", Body=opt_data, ContentType="image/webp")
|
||||
variants_meta.append({
|
||||
"name": "optimized",
|
||||
"content_type": "image/webp",
|
||||
"width": opt_img.width,
|
||||
"height": opt_img.height,
|
||||
"size_bytes": len(opt_data),
|
||||
"sha256": hashlib.sha256(opt_data).hexdigest()
|
||||
})
|
||||
|
||||
# обновляем БД
|
||||
att.status = "ready"
|
||||
att.error_code = None
|
||||
att.variants = variants_meta
|
||||
att.updated_at = datetime.now(timezone.utc)
|
||||
await session.commit()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user