208 lines
6.3 KiB
Python
208 lines
6.3 KiB
Python
"""Validace, EXIF autorotace, strip metadat a WebP optimalizace obrázků."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import uuid
|
|
import warnings
|
|
from dataclasses import dataclass
|
|
from io import BytesIO
|
|
from pathlib import Path
|
|
from typing import BinaryIO
|
|
|
|
from PIL import Image, ImageOps, UnidentifiedImageError
|
|
|
|
DEFAULT_MAX_UPLOAD_BYTES = 15 * 1024 * 1024
|
|
MAX_IMAGE_PIXELS = 40_000_000
|
|
FULL_MAX_SIDE = 1600
|
|
FULL_QUALITY = 82
|
|
THUMB_MAX_SIDE = 400
|
|
THUMB_QUALITY = 78
|
|
WEBP_METHOD = 4
|
|
_READ_CHUNK_SIZE = 64 * 1024
|
|
|
|
Image.MAX_IMAGE_PIXELS = MAX_IMAGE_PIXELS
|
|
|
|
|
|
class ImageValidationError(ValueError):
|
|
"""Chyba validace nebo dekódování nahraného obrázku."""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ProcessedPhoto:
|
|
"""Výsledek zpracování a uložení dvou WebP variant jedné fotky."""
|
|
|
|
soubor_plny: str
|
|
soubor_nahled: str
|
|
velikost_plny_b: int
|
|
velikost_nahled_b: int
|
|
sirka: int
|
|
vyska: int
|
|
|
|
|
|
def _format_limit_label(max_bytes: int) -> str:
|
|
if max_bytes >= 1024 * 1024 and max_bytes % (1024 * 1024) == 0:
|
|
return f"{max_bytes // (1024 * 1024)} MB"
|
|
if max_bytes >= 1024 and max_bytes % 1024 == 0:
|
|
return f"{max_bytes // 1024} kB"
|
|
return f"{max_bytes} B"
|
|
|
|
|
|
def _read_bounded_bytes(source: bytes | BinaryIO, max_bytes: int) -> bytes:
|
|
if isinstance(source, (bytes, bytearray, memoryview)):
|
|
data = bytes(source)
|
|
if not data:
|
|
raise ImageValidationError("Soubor je prázdný.")
|
|
if len(data) > max_bytes:
|
|
raise ImageValidationError(
|
|
"Soubor překračuje maximální povolenou velikost "
|
|
f"({_format_limit_label(max_bytes)})."
|
|
)
|
|
return data
|
|
|
|
chunks: list[bytes] = []
|
|
total = 0
|
|
while True:
|
|
chunk = source.read(_READ_CHUNK_SIZE)
|
|
if not chunk:
|
|
break
|
|
total += len(chunk)
|
|
if total > max_bytes:
|
|
raise ImageValidationError(
|
|
"Soubor překračuje maximální povolenou velikost "
|
|
f"({_format_limit_label(max_bytes)})."
|
|
)
|
|
chunks.append(chunk)
|
|
|
|
if total == 0:
|
|
raise ImageValidationError("Soubor je prázdný.")
|
|
return b"".join(chunks)
|
|
|
|
|
|
def _normalize_mode(img: Image.Image) -> Image.Image:
|
|
has_alpha = img.mode in {"RGBA", "LA"} or (
|
|
img.mode == "P" and "transparency" in img.info
|
|
)
|
|
target_mode = "RGBA" if has_alpha else "RGB"
|
|
if img.mode == target_mode:
|
|
return img
|
|
return img.convert(target_mode)
|
|
|
|
|
|
def decode_and_prepare(
|
|
source: bytes | BinaryIO,
|
|
*,
|
|
max_bytes: int = DEFAULT_MAX_UPLOAD_BYTES,
|
|
max_pixels: int = MAX_IMAGE_PIXELS,
|
|
) -> Image.Image:
|
|
"""Ověří limit, dekóduje obrázek, provede EXIF rotaci a strip metadat."""
|
|
raw = _read_bounded_bytes(source, max_bytes)
|
|
|
|
try:
|
|
with warnings.catch_warnings():
|
|
warnings.simplefilter("ignore", Image.DecompressionBombWarning)
|
|
with Image.open(BytesIO(raw)) as img:
|
|
width, height = img.size
|
|
if width <= 0 or height <= 0:
|
|
raise ImageValidationError("Obrázek má neplatné rozměry.")
|
|
if width * height > max_pixels:
|
|
raise ImageValidationError(
|
|
"Obrázek má příliš velké rozlišení "
|
|
"(překračuje povolený limit pixelů)."
|
|
)
|
|
|
|
transposed = ImageOps.exif_transpose(img)
|
|
try:
|
|
converted = _normalize_mode(transposed)
|
|
try:
|
|
return Image.frombytes(
|
|
converted.mode,
|
|
converted.size,
|
|
converted.tobytes(),
|
|
)
|
|
finally:
|
|
if converted is not transposed:
|
|
converted.close()
|
|
finally:
|
|
if transposed is not img:
|
|
transposed.close()
|
|
except ImageValidationError:
|
|
raise
|
|
except Image.DecompressionBombError as exc:
|
|
raise ImageValidationError(
|
|
"Obrázek má příliš velké rozlišení "
|
|
"(překračuje povolený limit pixelů)."
|
|
) from exc
|
|
except (UnidentifiedImageError, OSError, SyntaxError, ValueError) as exc:
|
|
raise ImageValidationError(
|
|
"Soubor není platný podporovaný obrázek."
|
|
) from exc
|
|
|
|
|
|
def _resize_variant(img: Image.Image, max_side: int) -> Image.Image:
|
|
resized = img.copy()
|
|
resized.thumbnail((max_side, max_side), Image.Resampling.LANCZOS)
|
|
return resized
|
|
|
|
|
|
def _save_webp(img: Image.Image, path: Path, *, quality: int) -> int:
|
|
img.save(
|
|
path,
|
|
format="WEBP",
|
|
quality=quality,
|
|
method=WEBP_METHOD,
|
|
)
|
|
return path.stat().st_size
|
|
|
|
|
|
def process_and_save_photo(
|
|
source: bytes | BinaryIO,
|
|
media_dir: Path,
|
|
sada_id: int,
|
|
*,
|
|
max_bytes: int = DEFAULT_MAX_UPLOAD_BYTES,
|
|
max_pixels: int = MAX_IMAGE_PIXELS,
|
|
) -> ProcessedPhoto:
|
|
"""Zpracuje obrázek a uloží plnou i náhledovou WebP variantu bez EXIF."""
|
|
clean = decode_and_prepare(
|
|
source,
|
|
max_bytes=max_bytes,
|
|
max_pixels=max_pixels,
|
|
)
|
|
full_img: Image.Image | None = None
|
|
thumb_img: Image.Image | None = None
|
|
|
|
uid = uuid.uuid4().hex
|
|
rel_full = f"{sada_id}/{uid}.webp"
|
|
rel_thumb = f"{sada_id}/{uid}_thumb.webp"
|
|
set_dir = media_dir / str(sada_id)
|
|
full_path = set_dir / f"{uid}.webp"
|
|
thumb_path = set_dir / f"{uid}_thumb.webp"
|
|
|
|
try:
|
|
full_img = _resize_variant(clean, FULL_MAX_SIDE)
|
|
thumb_img = _resize_variant(clean, THUMB_MAX_SIDE)
|
|
sirka, vyska = full_img.size
|
|
|
|
set_dir.mkdir(parents=True, exist_ok=True)
|
|
size_full = _save_webp(full_img, full_path, quality=FULL_QUALITY)
|
|
size_thumb = _save_webp(thumb_img, thumb_path, quality=THUMB_QUALITY)
|
|
|
|
return ProcessedPhoto(
|
|
soubor_plny=rel_full,
|
|
soubor_nahled=rel_thumb,
|
|
velikost_plny_b=size_full,
|
|
velikost_nahled_b=size_thumb,
|
|
sirka=sirka,
|
|
vyska=vyska,
|
|
)
|
|
except Exception:
|
|
full_path.unlink(missing_ok=True)
|
|
thumb_path.unlink(missing_ok=True)
|
|
raise
|
|
finally:
|
|
clean.close()
|
|
if full_img is not None:
|
|
full_img.close()
|
|
if thumb_img is not None:
|
|
thumb_img.close()
|