Files
mtusi2026lab5/app/images.py
T

183 lines
8.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Image inspection and variant rendering.
Thumbnail: JPEG, fit inside 256×256, no upscale, EXIF orientation applied, alpha on white.
Crop: JPEG, centered square resized to 128×128; upscale is allowed.
Optimized: WebP, fit inside 1280×1280, no upscale. Quality and metadata policy live in
pipeline_params and are recorded in the report.
"""
from __future__ import annotations
import io
import math
from dataclasses import dataclass
from PIL import Image, ImageOps, UnidentifiedImageError
PNG_MAGIC = b"\x89PNG\r\n\x1a\n"
_SOF = {0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF}
class ImageRejected(Exception):
def __init__(self, status: int, code: str, message: str):
super().__init__(message)
self.status = status
self.code = code
self.message = message
@dataclass(frozen=True)
class PipelineParams:
version: int
jpeg_quality: int
crop_quality: int
webp_quality: int
webp_method: int
def pipeline_params(version: int) -> PipelineParams:
"""Version 1 is the course pipeline. Version 2 changes only quality, so a stale
writer can be detected by checksum without changing geometry."""
if version == 1:
return PipelineParams(1, jpeg_quality=85, crop_quality=85, webp_quality=80, webp_method=6)
if version == 2:
return PipelineParams(2, jpeg_quality=60, crop_quality=70, webp_quality=50, webp_method=4)
raise ImageRejected(400, "invalid_request", "Неизвестная версия pipeline")
def _png_size(data: bytes) -> tuple[int, int]:
if len(data) < 24 or data[:8] != PNG_MAGIC or data[12:16] != b"IHDR":
raise ImageRejected(415, "unsupported_media_type", "Файл не является корректным PNG")
if b"IEND" not in data:
raise ImageRejected(415, "unsupported_media_type", "PNG повреждён")
width = int.from_bytes(data[16:20], "big")
height = int.from_bytes(data[20:24], "big")
return width, height
def _jpeg_size(data: bytes) -> tuple[int, int]:
if len(data) < 4 or data[:2] != b"\xff\xd8":
raise ImageRejected(415, "unsupported_media_type", "Файл не является корректным JPEG")
index = 2
while index < len(data):
if data[index] != 0xFF:
raise ImageRejected(415, "unsupported_media_type", "JPEG повреждён")
while index < len(data) and data[index] == 0xFF:
index += 1
if index >= len(data):
break
marker = data[index]
index += 1
if marker in {0xD8, 0xD9, 0xDA} or marker == 0x01 or 0xD0 <= marker <= 0xD7:
if marker in {0xD9, 0xDA}:
break
continue
if index + 2 > len(data):
break
length = int.from_bytes(data[index:index + 2], "big")
if length < 2 or index + length > len(data):
raise ImageRejected(415, "unsupported_media_type", "JPEG повреждён")
if marker in _SOF:
if length < 8:
raise ImageRejected(415, "unsupported_media_type", "JPEG повреждён")
height = int.from_bytes(data[index + 3:index + 5], "big")
width = int.from_bytes(data[index + 5:index + 7], "big")
return width, height
index += length
raise ImageRejected(415, "unsupported_media_type", "Не удалось прочитать размеры JPEG")
def inspect_upload(data: bytes, declared: str, max_bytes: int, max_pixels: int) -> tuple[str, int, int]:
"""Validate a client upload from headers and the container, before a full decode."""
if len(data) > max_bytes:
raise ImageRejected(413, "payload_too_large", "Превышен размер файла")
if not data:
raise ImageRejected(415, "unsupported_media_type", "Пустое изображение")
if declared == "image/png":
if not data.startswith(PNG_MAGIC):
raise ImageRejected(415, "unsupported_media_type", "Содержимое не соответствует PNG")
width, height = _png_size(data)
content_type = "image/png"
elif declared == "image/jpeg":
if not data.startswith(b"\xff\xd8\xff"):
raise ImageRejected(415, "unsupported_media_type", "Содержимое не соответствует JPEG")
width, height = _jpeg_size(data)
content_type = "image/jpeg"
else:
raise ImageRejected(415, "unsupported_media_type", "Допустимы только PNG и JPEG")
if width < 1 or height < 1:
raise ImageRejected(415, "unsupported_media_type", "Некорректные размеры изображения")
if width > max_pixels or height > max_pixels or width * height > max_pixels:
raise ImageRejected(413, "payload_too_large", "Превышено число пикселей")
return content_type, width, height
def fit_inside(width: int, height: int, box: int, allow_upscale: bool) -> tuple[int, int]:
scale = min(box / width, box / height)
if not allow_upscale:
scale = min(scale, 1.0)
return max(1, math.floor(width * scale)), max(1, math.floor(height * scale))
def _to_rgb_white(image: Image.Image) -> Image.Image:
if image.mode == "RGB":
return image
if image.mode == "P" and "transparency" in image.info:
image = image.convert("RGBA")
if image.mode in {"RGBA", "LA"}:
rgba = image.convert("RGBA")
background = Image.new("RGB", rgba.size, (255, 255, 255))
background.paste(rgba, mask=rgba.getchannel("A"))
return background
return image.convert("RGB")
def decode_image(data: bytes, max_pixels: int) -> Image.Image:
Image.MAX_IMAGE_PIXELS = max_pixels
try:
image = Image.open(io.BytesIO(data))
width, height = image.size
if width < 1 or height < 1 or width * height > max_pixels:
raise ImageRejected(413, "payload_too_large", "Превышено число пикселей")
image = ImageOps.exif_transpose(image)
width, height = image.size
if width * height > max_pixels:
raise ImageRejected(413, "payload_too_large", "Превышено число пикселей")
image.load()
except ImageRejected:
raise
except (UnidentifiedImageError, Image.DecompressionBombError, OSError, ValueError) as exc:
raise ImageRejected(415, "unsupported_media_type", "Изображение повреждено") from exc
return _to_rgb_white(image)
def _jpeg_bytes(image: Image.Image, quality: int) -> bytes:
buffer = io.BytesIO()
image.save(buffer, format="JPEG", quality=quality, optimize=True, progressive=False)
return buffer.getvalue()
def _webp_bytes(image: Image.Image, quality: int, method: int) -> bytes:
buffer = io.BytesIO()
image.save(buffer, format="WEBP", quality=quality, method=method, lossless=False, exact=False)
return buffer.getvalue()
def render_variants(source: Image.Image, params: PipelineParams) -> dict[str, dict]:
width, height = source.size
thumb_w, thumb_h = fit_inside(width, height, 256, allow_upscale=False)
thumbnail = source if (thumb_w, thumb_h) == (width, height) else source.resize((thumb_w, thumb_h), Image.Resampling.LANCZOS)
side = min(width, height)
left = (width - side) // 2
top = (height - side) // 2
crop = source.crop((left, top, left + side, top + side)).resize((128, 128), Image.Resampling.LANCZOS)
opt_w, opt_h = fit_inside(width, height, 1280, allow_upscale=False)
optimized = source if (opt_w, opt_h) == (width, height) else source.resize((opt_w, opt_h), Image.Resampling.LANCZOS)
thumb_bytes = _jpeg_bytes(thumbnail, params.jpeg_quality)
crop_bytes = _jpeg_bytes(crop, params.crop_quality)
webp_bytes = _webp_bytes(optimized, params.webp_quality, params.webp_method)
return {
"thumbnail": {"bytes": thumb_bytes, "content_type": "image/jpeg", "width": thumb_w, "height": thumb_h},
"crop": {"bytes": crop_bytes, "content_type": "image/jpeg", "width": 128, "height": 128},
"optimized": {"bytes": webp_bytes, "content_type": "image/webp", "width": opt_w, "height": opt_h},
}