Files
mtusi2026lab7-fork/src/imaging.py
T

275 lines
13 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.
"""Варианты изображения (lab5) и их изолированное вычисление.
Варианты pipeline_version=1 (параметры фиксированы, вывод детерминирован для
одной версии Pillow/libjpeg/libwebp, поэтому повтор той же job пишет те же байты):
thumbnail JPEG, вписан в 256x256 с сохранением пропорций, без увеличения,
размеры округляются вниз (минимум 1 px): 320x200 -> 256x160.
quality=85, optimize, baseline, 4:2:0.
crop JPEG 128x128: центрированный квадрат min(w,h) оригинала, масштаб
до 128 (маленькие исходники увеличиваются). quality=85.
optimized WebP, вписан в 1280x1280 без увеличения, quality=80, method=4.
Уменьшение размера каждого маленького файла НЕ обещается.
Для всех вариантов: EXIF orientation применяется до вычисления размеров;
прозрачность (RGBA/LA/P с tRNS) компонуется на белый фон; EXIF и XMP НЕ
копируются (Pillow сохраняет их только при явной передаче exif=/xmp=), ICC-профиль
сохраняется, чтобы не исказить цвет широкого охвата.
Ограничения ресурсов worker (недоверенный файл, даже прошедший проверки API):
* bytes: staging-объект больше MAX_UPLOAD_BYTES не читается (worker.py);
* pixels: размеры читаются из заголовка до декодирования; > MAX_IMAGE_PIXELS -> отказ;
* память: обработка идёт в отдельном процессе с RLIMIT_AS = WORKER_IMAGE_MEMORY_MB;
MemoryError/убийство процесса -> постоянная ошибка resource_limit;
* время: процесс убивается через WORKER_IMAGE_TIMEOUT_SECONDS (временная ошибка,
повтор ограничен JOB_MAX_ATTEMPTS); RLIMIT_CPU — страховка.
Процессы создаёт forkserver: чистый однопоточный родитель, без унаследованных
соединений PostgreSQL/Redis и потоков worker.
"""
import hashlib
import io
import multiprocessing
import os
import resource
import signal
from typing import Dict, Tuple
from PIL import Image, ImageFile, ImageOps
ImageFile.LOAD_TRUNCATED_IMAGES = False
THUMB_BOX = 256
CROP_SIDE = 128
OPTIMIZED_BOX = 1280
JPEG_QUALITY = 85
WEBP_QUALITY = 80
WEBP_METHOD = 4
VARIANT_TYPES = {"thumbnail": "image/jpeg", "crop": "image/jpeg", "optimized": "image/webp"}
VARIANT_EXT = {"thumbnail": "jpg", "crop": "jpg", "optimized": "webp"}
# EXIF orientation 5..8 поворачивает изображение на 90°: ширина и высота меняются.
SWAPPING_ORIENTATIONS = {5, 6, 7, 8}
class ImageFailure(Exception):
"""Постоянная ошибка: повтор того же файла даст тот же результат."""
def __init__(self, code: str, message: str = "") -> None:
super().__init__(message or code)
self.code = code
class ImageTimeout(Exception):
"""Обработка не уложилась в WORKER_IMAGE_TIMEOUT_SECONDS (временная ошибка)."""
def fit_within(width: int, height: int, box: int) -> Tuple[int, int]:
"""Вписать в box x box без увеличения; целочисленно, округление вниз, минимум 1."""
if width <= box and height <= box:
return width, height
if width >= height:
return box, max(1, height * box // width)
return max(1, width * box // height), box
def _orientation(img: Image.Image) -> int:
try:
return int(img.getexif().get(0x0112, 1) or 1)
except Exception:
return 1
def _has_alpha(img: Image.Image) -> bool:
return img.mode in ("RGBA", "LA", "PA") or "transparency" in img.info
def _working_mode(img: Image.Image) -> Image.Image:
"""RGB или RGBA без лишних копий: уже подходящий режим не конвертируется
(convert в тот же режим всё равно копирует кадр — на 40 Мп это +160 MiB)."""
if img.mode in ("RGB", "RGBA") and not (img.mode == "RGB" and "transparency" in img.info):
return img
return img.convert("RGBA" if _has_alpha(img) else "RGB")
def _flatten(img: Image.Image) -> Image.Image:
"""Уже УМЕНЬШЕННЫЙ вариант -> RGB: альфа компонуется на белый фон.
Масштабирование RGBA в Pillow идёт с premultiplied alpha, ореолов нет."""
if img.mode != "RGBA":
return img
background = Image.new("RGB", img.size, (255, 255, 255))
background.paste(img, mask=img.getchannel("A"))
return background
def _encode(img: Image.Image, fmt: str, icc) -> bytes:
out = io.BytesIO()
extra = {"icc_profile": icc} if icc else {}
if fmt == "JPEG":
img.save(out, "JPEG", quality=JPEG_QUALITY, optimize=True, progressive=False,
subsampling="4:2:0", **extra)
else:
img.save(out, "WEBP", quality=WEBP_QUALITY, method=WEBP_METHOD, lossless=False, **extra)
return out.getvalue()
def render(data: bytes, max_pixels: int) -> Dict[str, Tuple[bytes, int, int, str]]:
"""{name: (bytes, width, height, content_type)} для thumbnail, crop, optimized."""
Image.MAX_IMAGE_PIXELS = None # свой лимит ниже, до декодирования
try:
img = Image.open(io.BytesIO(data), formats=("PNG", "JPEG")) # lab7: только PNG/JPEG-плагины
if img.format not in ("PNG", "JPEG"):
raise ImageFailure("invalid_image", "unsupported format")
raw_w, raw_h = img.size
if raw_w < 1 or raw_h < 1 or raw_w * raw_h > max_pixels:
raise ImageFailure("invalid_image", "too many pixels")
orientation = _orientation(img)
icc = img.info.get("icc_profile")
# Целевые размеры считаются по ОРИЕНТИРОВАННОМУ оригиналу.
w, h = (raw_h, raw_w) if orientation in SWAPPING_ORIENTATIONS else (raw_w, raw_h)
thumb_size = fit_within(w, h, THUMB_BOX)
opt_size = fit_within(w, h, OPTIMIZED_BOX)
if img.format == "JPEG":
# Декодирование сразу в уменьшенном масштабе (1/2..1/8): память и время
# пропорциональны нужному размеру. draft выбирает масштаб >= запрошенного.
want = (opt_size[1], opt_size[0]) if orientation in SWAPPING_ORIENTATIONS else opt_size
img.draft("RGB", want)
img.load()
img = ImageOps.exif_transpose(img) # копия только если orientation != 1
base = _working_mode(img)
del img
bw, bh = base.size
result: Dict[str, Tuple[bytes, int, int, str]] = {}
# Сначала масштабирование (reducing_gap: быстрый целочисленный reduce, затем
# LANCZOS), потом компоновка альфы на белый — уже на маленьком кадре.
thumb = _flatten(base.resize(thumb_size, Image.LANCZOS, reducing_gap=3.0)
if base.size != thumb_size else base)
result["thumbnail"] = (_encode(thumb, "JPEG", icc),) + thumb.size + ("image/jpeg",)
del thumb
side = min(bw, bh)
left, top = (bw - side) // 2, (bh - side) // 2
crop = _flatten(base.resize((CROP_SIDE, CROP_SIDE), Image.LANCZOS, box=(left, top, left + side, top + side),
reducing_gap=3.0 if side > CROP_SIDE else None))
result["crop"] = (_encode(crop, "JPEG", icc),) + crop.size + ("image/jpeg",)
del crop
opt = _flatten(base.resize(opt_size, Image.LANCZOS, reducing_gap=3.0) if base.size != opt_size else base)
result["optimized"] = (_encode(opt, "WEBP", icc),) + opt.size + ("image/webp",)
return result
except ImageFailure:
raise
except MemoryError:
raise ImageFailure("resource_limit", "memory limit exceeded")
except (OSError, SyntaxError, ValueError, EOFError, Image.DecompressionBombError) as exc:
raise ImageFailure("invalid_image", type(exc).__name__)
def sha256_hex(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
# ---------------------------------------------------------------- sandbox
def _child(conn, memory_mb: int, cpu_seconds: int, max_pixels: int) -> None:
"""Тело дочернего процесса: лимиты -> получить байты -> вычислить -> отправить."""
try:
limit = memory_mb * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
resource.setrlimit(resource.RLIMIT_CPU, (cpu_seconds, cpu_seconds + 1))
except (ValueError, OSError):
pass
signal.signal(signal.SIGTERM, signal.SIG_DFL)
try:
data = conn.recv_bytes()
result = render(data, max_pixels)
del data
peak_mb = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024.0
conn.send(("ok", (result, peak_mb)))
except ImageFailure as exc:
conn.send(("fail", exc.code))
except MemoryError:
try:
conn.send(("fail", "resource_limit"))
except Exception:
pass
except Exception as exc: # неожиданное — тоже постоянная ошибка обработки
try:
conn.send(("fail", "processing_failed:" + type(exc).__name__))
except Exception:
pass
finally:
conn.close()
class Sandbox:
def __init__(self, memory_mb: int, timeout: float, max_pixels: int) -> None:
self.memory_mb = memory_mb
self.timeout = timeout
self.max_pixels = max_pixels
self.last_peak_mb = 0.0
method = "forkserver" if "forkserver" in multiprocessing.get_all_start_methods() else "spawn"
self.ctx = multiprocessing.get_context(method)
if method == "forkserver":
self.ctx.set_forkserver_preload(["src.imaging"])
def render(self, data: bytes) -> Dict[str, Tuple[bytes, int, int, str]]:
parent, child = self.ctx.Pipe(duplex=True)
proc = self.ctx.Process(
target=_child,
args=(child, self.memory_mb, int(self.timeout) + 5, self.max_pixels),
daemon=True,
)
proc.start()
child.close()
try:
parent.send_bytes(data)
if not parent.poll(self.timeout):
raise ImageTimeout()
try:
status, value = parent.recv()
except (EOFError, OSError):
# Процесс умер без ответа: OOM/RLIMIT (SIGKILL/SIGSEGV при нехватке памяти).
proc.join(1)
raise ImageFailure("resource_limit", "worker subprocess died (exit %s)" % proc.exitcode)
if status == "ok":
result, self.last_peak_mb = value
return result
code = str(value)
if code.startswith("processing_failed"):
raise ImageFailure("processing_failed", code)
raise ImageFailure(code)
finally:
parent.close()
if proc.is_alive():
proc.kill()
proc.join(5)
def main() -> None:
"""Самопроверка: python -m src.imaging FILE [--memory-mb N] [--timeout S]."""
import argparse
import json
parser = argparse.ArgumentParser()
parser.add_argument("file")
parser.add_argument("--memory-mb", type=int, default=1024)
parser.add_argument("--timeout", type=float, default=30)
parser.add_argument("--max-pixels", type=int, default=40_000_000)
args = parser.parse_args()
with open(args.file, "rb") as f:
data = f.read()
try:
box = Sandbox(args.memory_mb, args.timeout, args.max_pixels)
out = box.render(data)
print(json.dumps({**{k: {"bytes": len(v[0]), "width": v[1], "height": v[2], "type": v[3]}
for k, v in out.items()}, "peak_rss_mb": round(box.last_peak_mb, 1)}))
except ImageFailure as exc:
print(json.dumps({"failed": exc.code}))
except ImageTimeout:
print(json.dumps({"failed": "timeout"}))
if __name__ == "__main__":
main()