forked from linkong/planet
96 lines
3.3 KiB
Python
96 lines
3.3 KiB
Python
"""Validated raster uploads and content-addressed, bounded card-size derivatives."""
|
|
|
|
import hashlib
|
|
import io
|
|
import re
|
|
import warnings
|
|
from uuid import uuid4
|
|
from pathlib import Path
|
|
import os
|
|
|
|
from fastapi import HTTPException
|
|
from PIL import Image, ImageOps, UnidentifiedImageError
|
|
|
|
from app.schemas.card_images import CardImageAsset
|
|
from app.services.card_image_defaults import REPO_ROOT
|
|
|
|
ASSET_DIR = Path(
|
|
os.environ.get("PLANET_CARD_IMAGE_DIR", str(REPO_ROOT / "data/earth-card-images"))
|
|
).resolve()
|
|
MAX_UPLOAD_BYTES = 12 * 1024 * 1024
|
|
MAX_PIXELS = 32_000_000
|
|
FILE_PATTERN = re.compile(r"^[a-f0-9]{64}-(?:original\.(?:jpg|png|webp)|(?:640|1280)\.webp)$")
|
|
FORMATS = {"JPEG": "jpg", "PNG": "png", "WEBP": "webp"}
|
|
|
|
|
|
def uploaded_path(filename: str) -> Path:
|
|
if not FILE_PATTERN.fullmatch(filename):
|
|
raise HTTPException(404, "Image not found")
|
|
return ASSET_DIR / filename
|
|
|
|
|
|
def store_image(content: bytes, title: str) -> CardImageAsset:
|
|
if len(content) > MAX_UPLOAD_BYTES:
|
|
raise HTTPException(413, "Image must be 12 MiB or smaller")
|
|
try:
|
|
with warnings.catch_warnings():
|
|
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
|
image = Image.open(io.BytesIO(content))
|
|
extension = FORMATS.get(image.format)
|
|
if (
|
|
not extension
|
|
or image.width * image.height > MAX_PIXELS
|
|
or getattr(image, "is_animated", False)
|
|
):
|
|
raise ValueError("Unsupported or oversized raster")
|
|
image.load()
|
|
image = ImageOps.exif_transpose(image).convert(
|
|
"RGBA" if "A" in image.getbands() or "transparency" in image.info else "RGB"
|
|
)
|
|
except (
|
|
UnidentifiedImageError,
|
|
OSError,
|
|
ValueError,
|
|
Image.DecompressionBombError,
|
|
Image.DecompressionBombWarning,
|
|
) as error:
|
|
raise HTTPException(
|
|
422, "Use a valid, still JPEG, PNG or WebP image below 32 megapixels"
|
|
) from error
|
|
digest = hashlib.sha256(content).hexdigest()
|
|
ASSET_DIR.mkdir(parents=True, exist_ok=True)
|
|
original = f"{digest}-original.{extension}"
|
|
original_path = uploaded_path(original)
|
|
if not original_path.exists():
|
|
temporary = original_path.with_suffix(f".{uuid4().hex}.tmp")
|
|
temporary.write_bytes(content)
|
|
temporary.replace(original_path)
|
|
variants = {}
|
|
for size, content in render_variants(image).items():
|
|
filename = f"{digest}-{size}.webp"
|
|
path = uploaded_path(filename)
|
|
if not path.exists():
|
|
temporary = path.with_suffix(f".{uuid4().hex}.tmp")
|
|
temporary.write_bytes(content)
|
|
temporary.replace(path)
|
|
variants[size] = f"/api/v1/earth/card-images/files/{filename}"
|
|
return CardImageAsset(
|
|
id=f"upload-{digest[:24]}",
|
|
title=title or "Image",
|
|
url=f"/api/v1/earth/card-images/files/{original}",
|
|
variants=variants,
|
|
width=image.width,
|
|
height=image.height,
|
|
)
|
|
|
|
|
|
def render_variants(image: Image.Image) -> dict[str, bytes]:
|
|
result = {}
|
|
for size in (640, 1280):
|
|
resized = image.copy()
|
|
resized.thumbnail((size, size), Image.Resampling.LANCZOS)
|
|
buffer = io.BytesIO()
|
|
resized.save(buffer, format="WEBP", quality=93, method=4)
|
|
result[str(size)] = buffer.getvalue()
|
|
return result
|