"""Thumbnail minting: small JPEG covers stored under datasets/{project}/thumbs/. Pure resize (testable without R2) is separated from R2 IO. Failures never raise: the card falls back to the full image via _thumbnail_url. """ from __future__ import annotations import asyncio from io import BytesIO from shared import keys, r2 from shared.logger import get_logger from src.core.config import get_settings log = get_logger("danagble.thumbnails") def resize_to_thumbnail(data: bytes, max_side: int = 512, quality: int = 70) -> bytes: from PIL import Image as PILImage with PILImage.open(BytesIO(data)) as im: im = im.convert("RGB") im.thumbnail((max_side, max_side), PILImage.LANCZOS) buf = BytesIO() im.save(buf, "JPEG", quality=quality, optimize=True) return buf.getvalue() # Immutable: keys are unique per image, safe to cache for a year. IMMUTABLE = "public, max-age=31536000, immutable" MICRO_SIDE = 128 MICRO_QUALITY = 65 async def mint_thumbnails_for_image(project_id: str, image_id: str, r2_key: str) -> dict[str, str | None]: """Download original -> resize 512 + 128 -> upload both. Never raises.""" s = get_settings() out: dict[str, str | None] = {"thumbnail": None, "small": None} if not s.thumbnail_enabled: return out try: original: bytes = await asyncio.to_thread(r2.get_bytes, r2_key) big = await asyncio.to_thread( resize_to_thumbnail, original, s.thumbnail_max_side, s.thumbnail_quality) small = await asyncio.to_thread( resize_to_thumbnail, original, MICRO_SIDE, MICRO_QUALITY) thumb_key = keys.thumbnail_key(project_id, image_id) small_key = keys.thumbnail_small_key(project_id, image_id) await asyncio.to_thread(r2.put_bytes, thumb_key, big, "image/jpeg", IMMUTABLE) await asyncio.to_thread(r2.put_bytes, small_key, small, "image/jpeg", IMMUTABLE) log.info("minted thumbnails %s (%dB) + %s (%dB)", thumb_key, len(big), small_key, len(small)) out["thumbnail"] = thumb_key out["small"] = small_key return out except Exception as e: log.warning("thumbnail mint failed key=%s: %s", r2_key, e) return out async def mint_thumbnail_for_image(project_id: str, image_id: str, r2_key: str) -> str | None: """Legacy single-size wrapper (kept for callers migrating off it).""" return (await mint_thumbnails_for_image(project_id, image_id, r2_key))["thumbnail"]