forked from mtusi2026/mtusi2026lab5
198 lines
12 KiB
Python
198 lines
12 KiB
Python
"""lab5: обработка картинок worker (imaging.py, sandbox.py) — проверки внутри образа (там есть Pillow).
|
||
|
||
make imaging-test == docker compose --profile tools run --rm imaging-test
|
||
|
||
Уровень 3–4 (contracts/README.md, «Фоновая обработка»):
|
||
- геометрия: thumbnail вписан в 256×256 без увеличения, размеры вниз, минимум 1 px (320×200 -> 256×160);
|
||
crop — центральный квадрат 128×128 (маленькие увеличиваются); optimized — WebP в 1280×1280 без увеличения;
|
||
- EXIF-ориентация применяется (фото «на боку» в вариантах стоит правильно);
|
||
- прозрачность накладывается на белый в JPEG, а WebP её сохраняет;
|
||
- EXIF, GPS, XMP и ICC-профиль в варианты не попадают;
|
||
- 16-битные, палитровые, CMYK-картинки обрабатываются;
|
||
- одинаковый вход даёт одинаковые байты (повтор задания идемпотентен);
|
||
- лимиты worker: пиксели (до декодирования), память (RLIMIT_AS дочернего процесса), время (SIGKILL).
|
||
"""
|
||
import hashlib
|
||
import io
|
||
import os
|
||
import struct
|
||
import tempfile
|
||
import time
|
||
import unittest
|
||
import zlib
|
||
from pathlib import Path
|
||
|
||
from PIL import Image, ImageCms, ImageOps
|
||
|
||
from messenger import imaging, sandbox
|
||
|
||
FIXTURE = Path(__file__).resolve().parents[2] / "tests" / "fixtures" / "sample.png"
|
||
|
||
|
||
def _chunk(kind, data):
|
||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||
|
||
|
||
def big_rgba_png(width, height):
|
||
"""Большой RGBA PNG без Pillow (нули сжимаются в килобайты), чтобы проверить лимиты памяти."""
|
||
compressor = zlib.compressobj(1)
|
||
row = b"\x00" + bytes(width * 4)
|
||
data = b"".join(compressor.compress(row) for _ in range(height)) + compressor.flush()
|
||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)
|
||
return b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", data) + _chunk(b"IEND", b"")
|
||
|
||
|
||
class ImagingTest(unittest.TestCase):
|
||
def setUp(self):
|
||
self.tmp = tempfile.TemporaryDirectory()
|
||
self.dir = self.tmp.name
|
||
|
||
def tearDown(self):
|
||
self.tmp.cleanup()
|
||
|
||
def save(self, image, fmt, **kwargs):
|
||
path = os.path.join(self.dir, f"in-{len(os.listdir(self.dir))}.{fmt.lower()}")
|
||
image.save(path, fmt, **kwargs)
|
||
return path
|
||
|
||
def run_variants(self, path, content_type, params=imaging.Params()):
|
||
out = os.path.join(self.dir, f"out-{len(os.listdir(self.dir))}")
|
||
result = imaging.process(path, out, content_type, params)
|
||
return {v["name"]: v for v in result["variants"]}
|
||
|
||
def opened(self, variant):
|
||
img = Image.open(variant["path"])
|
||
img.load()
|
||
return img
|
||
|
||
def test_fixture_variants(self):
|
||
variants = self.run_variants(str(FIXTURE), "image/png")
|
||
expected = {"thumbnail": ("JPEG", (256, 160)), "crop": ("JPEG", (128, 128)), "optimized": ("WEBP", (320, 200))}
|
||
for name, (fmt, size) in expected.items():
|
||
img = self.opened(variants[name])
|
||
self.assertEqual((img.format, img.size), (fmt, size), name)
|
||
self.assertEqual((variants[name]["width"], variants[name]["height"]), size)
|
||
self.assertEqual(variants[name]["size_bytes"], os.path.getsize(variants[name]["path"]))
|
||
print("\n fixture 320×200 -> thumbnail JPEG 256×160, crop JPEG 128×128, optimized WebP 320×200")
|
||
|
||
def test_geometry(self):
|
||
cases = {(3000, 1000): ((256, 85), (1280, 426)), (1000, 3000): ((85, 256), (426, 1280)),
|
||
(10, 5): ((10, 5), (10, 5)), (5000, 10): ((256, 1), (1280, 2)),
|
||
(256, 256): ((256, 256), (256, 256)), (257, 256): ((256, 255), (257, 256)),
|
||
(2000, 1999): ((256, 255), (1280, 1279))}
|
||
for (w, h), (thumb, optimized) in cases.items():
|
||
with self.subTest(size=(w, h)):
|
||
variants = self.run_variants(self.save(Image.new("RGB", (w, h), (90, 120, 150)), "PNG"), "image/png")
|
||
self.assertEqual(self.opened(variants["thumbnail"]).size, thumb)
|
||
self.assertEqual(self.opened(variants["optimized"]).size, optimized)
|
||
self.assertEqual(self.opened(variants["crop"]).size, (128, 128)) # маленькие увеличиваются
|
||
|
||
def test_exif_orientation_is_applied(self):
|
||
img = Image.new("RGB", (400, 200), (0, 0, 255))
|
||
img.paste((255, 0, 0), (0, 0, 200, 200)) # левая половина красная
|
||
exif = Image.Exif()
|
||
exif[imaging.EXIF_ORIENTATION] = 6 # «повернуть на 90° по часовой» при показе
|
||
path = self.save(img, "JPEG", exif=exif.tobytes(), quality=95)
|
||
with Image.open(path) as source:
|
||
reference = ImageOps.exif_transpose(source) # как картинку покажет просмотрщик
|
||
variants = self.run_variants(path, "image/jpeg")
|
||
thumb = self.opened(variants["thumbnail"])
|
||
self.assertEqual((reference.size, thumb.size), ((200, 400), (128, 256)))
|
||
top, bottom = thumb.getpixel((64, 20)), thumb.getpixel((64, 236))
|
||
self.assertGreater(top[0], 200) # красная половина — сверху, как у reference
|
||
self.assertGreater(bottom[2], 200)
|
||
self.assertEqual(reference.getpixel((100, 20))[0] > 200, True)
|
||
self.assertEqual(self.opened(variants["optimized"]).size, (200, 400))
|
||
print("\n EXIF orientation 6: stored 400×200 -> variants 128×256 / 200×400, upright like a viewer shows it")
|
||
|
||
def test_alpha_is_white_in_jpeg_and_kept_in_webp(self):
|
||
transparent = Image.new("RGBA", (100, 80), (0, 0, 0, 0))
|
||
variants = self.run_variants(self.save(transparent, "PNG"), "image/png")
|
||
for name in ("thumbnail", "crop"):
|
||
pixel = self.opened(variants[name]).convert("RGB").getpixel((5, 5))
|
||
self.assertTrue(all(c >= 250 for c in pixel), f"{name}: {pixel}")
|
||
webp = self.opened(variants["optimized"])
|
||
self.assertEqual((webp.mode, webp.getpixel((5, 5))[3]), ("RGBA", 0))
|
||
palette = Image.new("P", (60, 40), 0)
|
||
palette.putpalette([0, 0, 0] * 256)
|
||
variants = self.run_variants(self.save(palette, "PNG", transparency=0), "image/png")
|
||
self.assertTrue(all(c >= 250 for c in self.opened(variants["thumbnail"]).convert("RGB").getpixel((3, 3))))
|
||
|
||
def test_metadata_is_stripped(self):
|
||
exif = Image.Exif()
|
||
exif[0x010F] = "Camera Maker"
|
||
exif[0x8825] = {1: "N", 2: (55.0, 45.0, 0.0)} # GPS-координаты
|
||
icc = ImageCms.ImageCmsProfile(ImageCms.createProfile("sRGB")).tobytes()
|
||
path = self.save(Image.new("RGB", (300, 200), (10, 200, 30)), "JPEG", exif=exif.tobytes(), icc_profile=icc)
|
||
with Image.open(path) as source:
|
||
self.assertIn("exif", source.info)
|
||
self.assertIn("icc_profile", source.info)
|
||
for name, variant in self.run_variants(path, "image/jpeg").items():
|
||
data = Path(variant["path"]).read_bytes()
|
||
img = self.opened(variant)
|
||
self.assertNotIn("exif", img.info, name)
|
||
self.assertNotIn("icc_profile", img.info, name)
|
||
self.assertNotIn(b"Exif\x00\x00", data, name)
|
||
self.assertNotIn(b"ICC_PROFILE", data, name)
|
||
self.assertNotIn(b"Camera Maker", data, name)
|
||
|
||
def test_modes(self):
|
||
sixteen = Image.new("I;16", (300, 200), 32768)
|
||
variants = self.run_variants(self.save(sixteen, "PNG"), "image/png")
|
||
self.assertAlmostEqual(self.opened(variants["thumbnail"]).getpixel((10, 10)), 128, delta=2)
|
||
cmyk = self.save(Image.new("CMYK", (300, 200), (0, 255, 255, 0)), "JPEG")
|
||
thumb = self.opened(self.run_variants(cmyk, "image/jpeg")["thumbnail"]).convert("RGB")
|
||
self.assertGreater(thumb.getpixel((10, 10))[0], 200) # красный остался красным
|
||
for mode in ("1", "L", "LA", "P", "RGB", "RGBA"):
|
||
with self.subTest(mode=mode):
|
||
variants = self.run_variants(self.save(Image.new(mode, (64, 48)), "PNG"), "image/png")
|
||
self.assertEqual(self.opened(variants["thumbnail"]).size, (64, 48))
|
||
|
||
def test_same_input_same_bytes(self):
|
||
first = self.run_variants(str(FIXTURE), "image/png")
|
||
second = self.run_variants(str(FIXTURE), "image/png")
|
||
self.assertEqual({k: v["sha256"] for k, v in first.items()}, {k: v["sha256"] for k, v in second.items()})
|
||
for variant in first.values():
|
||
self.assertEqual(hashlib.sha256(Path(variant["path"]).read_bytes()).hexdigest(), variant["sha256"])
|
||
|
||
def test_broken_jpeg_scan_is_invalid(self):
|
||
good = io.BytesIO()
|
||
Image.new("RGB", (64, 48), (200, 100, 50)).save(good, "JPEG")
|
||
data = good.getvalue()
|
||
sos = data.index(b"\xff\xda")
|
||
length = int.from_bytes(data[sos + 2:sos + 4], "big")
|
||
broken = data[:sos + 2 + length] + bytes((i * 37 + 11) % 255 for i in range(300)) + b"\xff\xd9"
|
||
path = os.path.join(self.dir, "broken.jpg")
|
||
Path(path).write_bytes(broken)
|
||
with Image.open(path) as lenient:
|
||
lenient.load() # Pillow такой файл молча «декодирует»...
|
||
with self.assertRaises(imaging.InvalidImage): # ...а строгая проверка libjpeg-turbo — нет
|
||
imaging.process(path, os.path.join(self.dir, "o"), "image/jpeg")
|
||
|
||
def test_limits_in_child_process(self):
|
||
path = os.path.join(self.dir, "big.png")
|
||
Path(path).write_bytes(big_rgba_png(6000, 6000)) # 36 млн пикселей RGBA
|
||
params = imaging.Params()
|
||
started = time.monotonic()
|
||
result = sandbox.run(path, os.path.join(self.dir, "ok"), "image/png", params, timeout=60, memory_limit_mb=640)
|
||
normal = time.monotonic() - started
|
||
self.assertEqual({v["name"] for v in result["variants"]}, {"thumbnail", "crop", "optimized"})
|
||
with self.assertRaises(imaging.ImageTooLarge): # память: RLIMIT_AS 200 МиБ
|
||
sandbox.run(path, os.path.join(self.dir, "m"), "image/png", params, timeout=60, memory_limit_mb=200)
|
||
started = time.monotonic()
|
||
with self.assertRaises(sandbox.ProcessingTimeout): # время: SIGKILL дочернему процессу
|
||
sandbox.run(path, os.path.join(self.dir, "t"), "image/png", params, timeout=0.2, memory_limit_mb=640)
|
||
killed_after = time.monotonic() - started
|
||
self.assertLess(killed_after, 2)
|
||
with self.assertRaises(imaging.ImageTooLarge): # пиксели: до декодирования
|
||
imaging.process(str(FIXTURE), os.path.join(self.dir, "p"), "image/png", imaging.Params(max_pixels=1000))
|
||
direct = imaging.process(str(FIXTURE), os.path.join(self.dir, "d"), "image/png")
|
||
child = sandbox.run(str(FIXTURE), os.path.join(self.dir, "c"), "image/png", params, 60, 640)
|
||
self.assertEqual([v["sha256"] for v in direct["variants"]], [v["sha256"] for v in child["variants"]])
|
||
print(f"\n 36 Mpx RGBA in a child process: ok in {normal:.2f} s with 640 MiB; MemoryError -> image_too_large "
|
||
f"with 200 MiB; timeout 0.2 s -> killed after {killed_after:.2f} s; 1000 px limit -> image_too_large")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main(verbosity=2)
|