from __future__ import annotations import hashlib import json from pathlib import Path from PIL import Image from .models import SUPPORTED_EXTENSIONS MIME_BY_EXTENSION = { ".webp": "image/webp", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", } class MediaValidationError(ValueError): pass def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def validate_image_file(path: Path) -> dict[str, object]: if not path.exists(): raise MediaValidationError(f"Media file not found: {path}") if not path.is_file(): raise MediaValidationError(f"Media path is not a file: {path}") suffix = path.suffix.lower() if suffix not in SUPPORTED_EXTENSIONS: raise MediaValidationError( f"Unsupported media extension {suffix!r}: {path}. " "Supported: .webp, .png, .jpg, .jpeg" ) expected_mime = MIME_BY_EXTENSION[suffix] try: with Image.open(path) as image: image.verify() with Image.open(path) as image: width, height = image.size actual_format = (image.format or "").upper() except Exception as exc: raise MediaValidationError( f"Invalid/corrupt image file {path}: {exc}" ) from exc allowed_formats = { ".png": {"PNG"}, ".jpg": {"JPEG"}, ".jpeg": {"JPEG"}, ".webp": {"WEBP"}, } if actual_format not in allowed_formats[suffix]: raise MediaValidationError( f"File content does not match extension for {path}: " f"extension={suffix}, detected={actual_format}" ) stat = path.stat() return { "mime_type": expected_mime, "width": width, "height": height, "file_size": stat.st_size, "sha256": sha256_file(path), } def load_manifest(path: Path): from .models import MediaManifest try: payload = json.loads(path.read_text(encoding="utf-8")) except Exception as exc: raise MediaValidationError( f"Failed to parse media manifest {path}: {exc}" ) from exc try: return MediaManifest.model_validate(payload) except Exception as exc: raise MediaValidationError( f"Invalid media manifest {path}: {exc}" ) from exc