Files
mtusi2026lab5/src/infrastructure/media/image_transform.py
T

100 lines
3.6 KiB
Python

"""Изолированный процесс Pillow: полный decode, лимиты памяти/CPU, без S3/БД"""
import hashlib
import json
import resource
import sys
import warnings
from pathlib import Path
from PIL import Image, ImageOps, UnidentifiedImageError
def fit_size(size: tuple[int, int], bound: int) -> tuple[int, int]:
width, height = size
longest = max(width, height)
if longest <= bound:
return size
return max(1, width * bound // longest), max(1, height * bound // longest)
def transform(source: Path, target: Path, max_pixels: int) -> list[dict]:
Image.MAX_IMAGE_PIXELS = max_pixels
warnings.simplefilter("error", Image.DecompressionBombWarning)
with Image.open(source) as image:
if image.format not in {"PNG", "JPEG"}:
raise UnidentifiedImageError("format")
if image.width * image.height > max_pixels:
raise Image.DecompressionBombError("pixels")
image.load() # Включая IDAT PNG: заголовка и CRC недостаточно.
oriented = ImageOps.exif_transpose(image)
try:
if oriented.mode in {"RGBA", "LA"} or "transparency" in oriented.info:
rgba = oriented.convert("RGBA")
clean = Image.new("RGB", rgba.size, "white")
clean.paste(rgba, mask=rgba.getchannel("A"))
rgba.close()
else:
clean = oriented.convert("RGB")
finally:
oriented.close()
clean.info.clear() # EXIF, XMP, ICC не наследуются производными.
result = []
try:
for name, bound, format_, mime, quality in (
("thumbnail", 256, "JPEG", "image/jpeg", 85),
("crop", 128, "JPEG", "image/jpeg", 85),
("optimized", 1280, "WEBP", "image/webp", 80),
):
derived = (
ImageOps.fit(
clean,
(bound, bound),
method=Image.Resampling.LANCZOS,
centering=(0.5, 0.5),
)
if name == "crop"
else clean.resize(fit_size(clean.size, bound), Image.Resampling.LANCZOS)
)
try:
file = target / name
derived.save(file, format_, quality=quality, exif=b"", icc_profile=None)
data = file.read_bytes()
result.append(
dict(
name=name,
content_type=mime,
width=derived.width,
height=derived.height,
size_bytes=len(data),
sha256=hashlib.sha256(data).hexdigest(),
)
)
finally:
derived.close()
finally:
clean.close()
return result
def main() -> int:
source, target, pixels, memory, seconds = sys.argv[1:]
if sys.platform == "linux":
limit = int(memory) * 1024 * 1024
resource.setrlimit(resource.RLIMIT_AS, (limit, limit))
resource.setrlimit(resource.RLIMIT_CPU, (int(seconds), int(seconds) + 1))
try:
variants = transform(Path(source), Path(target), int(pixels))
except (Image.DecompressionBombError, Image.DecompressionBombWarning, MemoryError):
print("image_resource_limit")
return 2
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
print("invalid_image")
return 2
print(json.dumps(variants))
return 0
if __name__ == "__main__":
sys.exit(main())