forked from mtusi2026/mtusi2026lab6
Port final lab 5 validation, session and PNG recovery fixes
This commit is contained in:
@@ -5,10 +5,12 @@ import warnings
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import ProcessPoolExecutor
|
||||
from concurrent.futures.process import BrokenProcessPool
|
||||
from contextlib import closing
|
||||
from dataclasses import dataclass
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
from PIL import Image, ImageChops, ImageOps
|
||||
from PIL.PngImagePlugin import PngImageFile
|
||||
|
||||
from messenger.attachments.application.ports import Rendition
|
||||
from messenger.attachments.domain.errors import (
|
||||
@@ -27,6 +29,7 @@ from messenger.attachments.domain.variants import (
|
||||
THUMBNAIL_BOX,
|
||||
fit,
|
||||
)
|
||||
from messenger.attachments.infrastructure.png import SIGNATURE, read_png_header, verify_png_pixels
|
||||
from messenger.shared.application.errors import Unavailable
|
||||
|
||||
KINDS = {"PNG": ImageKind.PNG, "JPEG": ImageKind.JPEG}
|
||||
@@ -38,6 +41,8 @@ JPEG = {1: {"quality": 85, "optimize": True}, 2: {"quality": 90, "optimize": Tru
|
||||
WEBP = {1: {"quality": 80, "method": 4}, 2: {"quality": 85, "method": 4}}
|
||||
ENCODINGS = {"JPEG": (ImageKind.JPEG.value, "jpg"), "WEBP": ("image/webp", "webp")}
|
||||
REDUCING_GAP = 3.0
|
||||
PNG_WIDE_DEPTH = 16
|
||||
COLOR_TILE_SIDE = 256
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
@@ -60,6 +65,7 @@ class PillowImageInspector:
|
||||
|
||||
def _inspect(self, data: bytes, declared: ImageKind) -> ImageInfo:
|
||||
try:
|
||||
header = read_png_header(data) if data.startswith(SIGNATURE) else None
|
||||
image = Image.open(BytesIO(data), formats=tuple(KINDS))
|
||||
except BOMBS as error:
|
||||
raise PayloadTooLarge("изображение больше допустимого числа пикселей") from error
|
||||
@@ -67,28 +73,87 @@ class PillowImageInspector:
|
||||
raise UnsupportedImage("содержимое не является изображением PNG или JPEG") from error
|
||||
with image:
|
||||
kind = KINDS[str(image.format)]
|
||||
width, height = image.size
|
||||
width, height = image.size if header is None else header[:2]
|
||||
if kind is not declared:
|
||||
raise UnsupportedImage("содержимое не совпадает с заявленным Content-Type")
|
||||
if width * height > self._max_pixels:
|
||||
raise PayloadTooLarge("изображение больше допустимого числа пикселей")
|
||||
try:
|
||||
if kind is ImageKind.JPEG:
|
||||
if header is None:
|
||||
image.draft("RGB", (width // JPEG_SCALE or 1, height // JPEG_SCALE or 1))
|
||||
image.load()
|
||||
else:
|
||||
image.verify()
|
||||
verify_png_pixels(data, header)
|
||||
except Exception as error:
|
||||
raise UnsupportedImage("изображение повреждено или обрезано") from error
|
||||
return ImageInfo(kind, width, height)
|
||||
|
||||
|
||||
def map_tiles(
|
||||
image: Image.Image, mode: str, transform: Callable[[Image.Image], Image.Image]
|
||||
) -> Image.Image:
|
||||
result = Image.new(mode, image.size)
|
||||
for y in range(0, image.height, COLOR_TILE_SIDE):
|
||||
for x in range(0, image.width, COLOR_TILE_SIDE):
|
||||
box = (
|
||||
x,
|
||||
y,
|
||||
min(x + COLOR_TILE_SIDE, image.width),
|
||||
min(y + COLOR_TILE_SIDE, image.height),
|
||||
)
|
||||
with closing(image.crop(box)) as tile, closing(transform(tile)) as transformed:
|
||||
result.paste(transformed, box)
|
||||
return result
|
||||
|
||||
|
||||
def rgb_mask(image: Image.Image, color: tuple[int, ...]) -> Image.Image:
|
||||
return map_tiles(image, "L", lambda tile: rgb_tile_mask(tile, color))
|
||||
|
||||
|
||||
def rgb_tile_mask(image: Image.Image, color: tuple[int, ...]) -> Image.Image:
|
||||
mask = Image.new("L", image.size, 255)
|
||||
for channel, value in zip("RGB", color, strict=True):
|
||||
mask = ImageChops.multiply(
|
||||
mask, image.getchannel(channel).point([255 if i == value else 0 for i in range(256)])
|
||||
)
|
||||
return mask
|
||||
|
||||
|
||||
def apply_png_transparency(image: PngImageFile, data: bytes) -> None:
|
||||
if (transparent := image.info.get("transparency")) is None:
|
||||
return
|
||||
depth = read_png_header(data)[2]
|
||||
if image.mode == "L" and depth in (2, 4):
|
||||
image.info["transparency"] = transparent * 255 // ((1 << depth) - 1)
|
||||
elif image.mode == "RGB" and depth == PNG_WIDE_DEPTH:
|
||||
with closing(PngImageFile(BytesIO(data))) as low:
|
||||
low.tile = [tile._replace(args="RGB;16L") for tile in low.tile]
|
||||
mask = rgb_mask(low, tuple(value & 255 for value in transparent))
|
||||
with (
|
||||
closing(mask),
|
||||
closing(rgb_mask(image, tuple(value >> 8 for value in transparent))) as high,
|
||||
closing(ImageChops.multiply(mask, high)) as combined,
|
||||
):
|
||||
image.paste((255, 255, 255), mask=combined)
|
||||
image.info.pop("transparency")
|
||||
|
||||
|
||||
def flatten(image: Image.Image) -> Image.Image:
|
||||
if image.mode == "RGB" and "transparency" not in image.info:
|
||||
return image
|
||||
return map_tiles(image, "RGB", flatten_tile)
|
||||
|
||||
|
||||
def flatten_tile(image: Image.Image) -> Image.Image:
|
||||
if image.mode in WIDE_MODES:
|
||||
image = image.convert("I").point(lambda value: value / 256, "L")
|
||||
if image.mode == "P":
|
||||
image = image.convert("RGBA" if "transparency" in image.info else "RGB")
|
||||
if image.mode in ALPHA_MODES:
|
||||
image = image.convert("I")
|
||||
if (transparent := image.info.pop("transparency", None)) is not None:
|
||||
mask = [0] * 65536
|
||||
mask[transparent] = 255
|
||||
image.paste(65535, mask=image.point(mask, "L"))
|
||||
image = image.point(lambda value: value / 256, "L")
|
||||
if image.mode in ALPHA_MODES or "transparency" in image.info:
|
||||
image = image.convert("RGBA")
|
||||
if image.mode == "RGBA":
|
||||
background = Image.new("RGB", image.size, "white")
|
||||
@@ -116,12 +181,17 @@ def decoded(data: bytes, max_pixels: int) -> tuple[Image.Image, int, int]:
|
||||
width, height = image.size
|
||||
if width * height > max_pixels:
|
||||
raise UnreadableImage("изображение больше допустимого числа пикселей")
|
||||
if isinstance(image, PngImageFile):
|
||||
apply_png_transparency(image, data)
|
||||
image.draft(None, fit(width, height, OPTIMIZED_BOX))
|
||||
stored = image.size
|
||||
ImageOps.exif_transpose(image, in_place=True)
|
||||
if image.size != stored:
|
||||
width, height = height, width
|
||||
return flatten(image), width, height
|
||||
upright = flatten(image)
|
||||
if upright is not image:
|
||||
image.close()
|
||||
return upright, width, height
|
||||
except UnreadableImage, MemoryError:
|
||||
raise
|
||||
except Exception as error:
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import struct
|
||||
import zlib
|
||||
from collections.abc import Iterator
|
||||
|
||||
type PngHeader = tuple[int, int, int, int, int, int, int]
|
||||
|
||||
SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||||
HEADER_BYTES = 13
|
||||
CHUNK_OVERHEAD = 12
|
||||
BLOCK_BYTES = 65_536
|
||||
MAX_FILTER = 4
|
||||
PIXELS = {
|
||||
0: (1, (1, 2, 4, 8, 16)),
|
||||
2: (3, (8, 16)),
|
||||
3: (1, (1, 2, 4, 8)),
|
||||
4: (2, (8, 16)),
|
||||
6: (4, (8, 16)),
|
||||
}
|
||||
ADAM7 = (
|
||||
(0, 0, 8, 8),
|
||||
(4, 0, 8, 8),
|
||||
(0, 4, 4, 8),
|
||||
(2, 0, 4, 4),
|
||||
(0, 2, 2, 4),
|
||||
(1, 0, 2, 2),
|
||||
(0, 1, 1, 2),
|
||||
)
|
||||
|
||||
|
||||
def _chunks(data: bytes) -> Iterator[tuple[bytes, memoryview]]:
|
||||
view = memoryview(data)
|
||||
offset = len(SIGNATURE)
|
||||
while offset + CHUNK_OVERHEAD <= len(data):
|
||||
size = struct.unpack_from(">I", data, offset)[0]
|
||||
kind = data[offset + 4 : offset + 8]
|
||||
start, end = offset + 8, offset + 8 + size
|
||||
if end + 4 > len(data):
|
||||
raise ValueError("truncated PNG chunk")
|
||||
yield kind, view[start:end]
|
||||
if kind == b"IEND":
|
||||
return
|
||||
offset = end + 4
|
||||
raise ValueError("missing PNG end")
|
||||
|
||||
|
||||
def read_png_header(data: bytes) -> PngHeader:
|
||||
chunks = _chunks(data)
|
||||
kind, header = next(chunks)
|
||||
if kind != b"IHDR" or len(header) != HEADER_BYTES:
|
||||
raise ValueError("invalid first PNG header")
|
||||
if any(kind == b"IHDR" for kind, _ in chunks):
|
||||
raise ValueError("duplicate PNG header")
|
||||
return struct.unpack(">IIBBBBB", header)
|
||||
|
||||
|
||||
def _scanlines(header: PngHeader) -> Iterator[tuple[int, int]]:
|
||||
width, height, depth, color, compression, filtering, interlace = header
|
||||
samples, depths = PIXELS[color]
|
||||
if depth not in depths or compression or filtering or interlace not in (0, 1):
|
||||
raise ValueError("invalid PNG header")
|
||||
passes = ADAM7 if interlace else ((0, 0, 1, 1),)
|
||||
for x, y, dx, dy in passes:
|
||||
columns, rows = (width - x + dx - 1) // dx, (height - y + dy - 1) // dy
|
||||
if columns > 0 and rows > 0:
|
||||
stride = 1 + (columns * samples * depth + 7) // 8
|
||||
yield stride, stride * rows
|
||||
|
||||
|
||||
def _idat(data: bytes) -> Iterator[memoryview]:
|
||||
started = ended = False
|
||||
for kind, payload in _chunks(data):
|
||||
if kind == b"IDAT":
|
||||
if ended:
|
||||
raise ValueError("nonconsecutive PNG image data")
|
||||
started = True
|
||||
for position in range(0, len(payload), BLOCK_BYTES):
|
||||
yield payload[position : position + BLOCK_BYTES]
|
||||
elif started:
|
||||
ended = True
|
||||
|
||||
|
||||
def _inflate(data: bytes) -> Iterator[bytes]:
|
||||
decoder = zlib.decompressobj()
|
||||
for block in _idat(data):
|
||||
if decoder.eof:
|
||||
continue
|
||||
pending = block
|
||||
while True:
|
||||
decoded = decoder.decompress(pending, BLOCK_BYTES)
|
||||
yield decoded
|
||||
pending = decoder.unconsumed_tail
|
||||
if decoder.eof or (not pending and len(decoded) < BLOCK_BYTES):
|
||||
break
|
||||
if not decoder.eof:
|
||||
raise ValueError("incomplete PNG compressed data")
|
||||
|
||||
|
||||
def verify_png_pixels(data: bytes, header: PngHeader) -> None:
|
||||
passes = _scanlines(header)
|
||||
stride, remaining = next(passes)
|
||||
offset = 0
|
||||
for decoded in _inflate(data):
|
||||
cursor = 0
|
||||
while cursor < len(decoded):
|
||||
if not remaining:
|
||||
stride, remaining = next(passes, (0, 0))
|
||||
offset = 0
|
||||
if not remaining:
|
||||
raise ValueError("extra PNG pixel data")
|
||||
size = min(remaining, len(decoded) - cursor)
|
||||
filters = decoded[cursor + (-offset % stride) : cursor + size : stride]
|
||||
if max(filters, default=0) > MAX_FILTER:
|
||||
raise ValueError("invalid PNG filter")
|
||||
cursor += size
|
||||
offset += size
|
||||
remaining -= size
|
||||
if remaining or next(passes, None) is not None:
|
||||
raise ValueError("incomplete PNG pixel data")
|
||||
Reference in New Issue
Block a user