Files
mtusi2026lab5/src/app/pipeline.py
T

98 lines
4.6 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.
"""Обработка изображений (pipeline_version=1): thumbnail, crop, optimized.
Правила (contracts/README.md):
* thumbnail: JPEG, вписан в 256x256 с сохранением пропорций, БЕЗ увеличения, EXIF orientation применяется, alpha — на белый
фон; размеры округляются вниз, минимум 1 px (320x200 -> 256x160); качество 85, метаданные не сохраняются;
* crop: JPEG, центрированный квадрат 128x128 (маленькие исходники допускается увеличивать), качество 85;
* optimized: WebP, вписан в 1280x1280 без увеличения, quality=80 method=4, EXIF/ICC не сохраняются (ориентация применена).
Память: JPEG декодируется через draft (масштабирование при декодировании), число пикселей ограничено MAX_IMAGE_PIXELS.
"""
import hashlib
import io
import math
from PIL import Image, ImageOps
from . import config
Image.MAX_IMAGE_PIXELS = None
PIPELINE_VERSION = 1
JPEG_QUALITY = 85
WEBP_QUALITY = 80
class PermanentError(Exception):
"""Постоянная ошибка входных данных: повтор не поможет (-> failed, error_code)."""
def __init__(self, code):
super().__init__(code)
self.code = code
def _flatten(img):
"""RGBA/LA/P с прозрачностью -> RGB на белом фоне."""
if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
rgba = img.convert("RGBA")
background = Image.new("RGB", rgba.size, (255, 255, 255))
background.paste(rgba, mask=rgba.getchannel("A"))
return background
return img.convert("RGB")
def _fit_size(width, height, box, upscale=False):
scale = min(box / width, box / height)
if not upscale:
scale = min(scale, 1.0)
return max(1, math.floor(width * scale)), max(1, math.floor(height * scale))
def _encode(img, fmt, **params):
buf = io.BytesIO()
img.save(buf, fmt, **params)
data = buf.getvalue()
return data, hashlib.sha256(data).hexdigest()
def process(fileobj):
"""Возвращает список вариантов: dict(name, content_type, data, sha256, width, height). Бросает PermanentError."""
try:
fileobj.seek(0)
src = Image.open(fileobj)
fmt = src.format
width, height = src.size
if fmt not in ("PNG", "JPEG"):
raise PermanentError("invalid_image")
if width * height > config.MAX_IMAGE_PIXELS:
raise PermanentError("image_too_large")
if fmt == "JPEG" and width > 2560 and height > 2560:
# экономия памяти: JPEG декодируется сразу в масштабе 1/2 (результат всё равно вписывается в 1280x1280)
src.draft("RGB", (width // 2, height // 2))
src.load()
img = ImageOps.exif_transpose(src)
except PermanentError:
raise
except MemoryError:
raise
except Exception:
raise PermanentError("invalid_image") from None
base = _flatten(img)
out = []
# thumbnail
tw, th = _fit_size(base.width, base.height, 256)
thumb = base.resize((tw, th), Image.LANCZOS) if (tw, th) != base.size else base
data, sha = _encode(thumb, "JPEG", quality=JPEG_QUALITY, optimize=True)
out.append({"name": "thumbnail", "content_type": "image/jpeg", "data": data, "sha256": sha, "width": tw, "height": th})
# crop 128x128 (центрированный квадрат)
side = min(base.width, base.height)
left, top = (base.width - side) // 2, (base.height - side) // 2
crop = base.crop((left, top, left + side, top + side)).resize((128, 128), Image.LANCZOS)
data, sha = _encode(crop, "JPEG", quality=JPEG_QUALITY, optimize=True)
out.append({"name": "crop", "content_type": "image/jpeg", "data": data, "sha256": sha, "width": 128, "height": 128})
# optimized WebP (прозрачность сохраняется)
opt_src = img.convert("RGBA") if (img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info)) else base
ow, oh = _fit_size(opt_src.width, opt_src.height, 1280)
opt = opt_src.resize((ow, oh), Image.LANCZOS) if (ow, oh) != opt_src.size else opt_src
data, sha = _encode(opt, "WEBP", quality=WEBP_QUALITY, method=4)
out.append({"name": "optimized", "content_type": "image/webp", "data": data, "sha256": sha, "width": ow, "height": oh})
return out