Source code for mllm_shap.masking.image

"""Image bytes to pixels and back; render image players by filling absent regions.

@domain masking
@see [[knowledge/architecture/masking]]
@tested-by [[tests/masking/test_image_masking.py]]
"""

import hashlib
import io
from collections.abc import Sequence
from typing import Literal

import numpy as np
from numpy.typing import NDArray

from ..alignment.io import require
from ..domain.conversation import ConversationSnapshot, ImagePart, Message, Turn
from ..domain.players import PlayerSpan

Box = tuple[int, int, int, int]
"""Pixel box ``(left, top, right, bottom)``, right and bottom exclusive."""

ImageFill = Literal["grey", "mean", "blur", "noise"]
"""Fill of absent image regions (mid-grey, the image's mean colour, a blurred copy of
the image, or noise seeded by the image bytes)."""

BLUR_FRACTION = 1 / 16
"""Gaussian blur radius of the ``blur`` fill as a fraction of the longer side."""


[docs] def decode_image(data: bytes) -> NDArray[np.uint8]: """Decode encoded image bytes to an ``(height, width, 3)`` RGB array. Raises: ValueError: If ``data`` is not an image Pillow can read. """ image_module = require("PIL.Image") try: with image_module.open(io.BytesIO(data)) as image: return np.asarray(image.convert("RGB"), dtype=np.uint8) except (OSError, image_module.UnidentifiedImageError) as exc: msg = "could not decode the image bytes" raise ValueError(msg) from exc
[docs] def encode_png(pixels: NDArray[np.uint8]) -> bytes: """Encode an ``(height, width, 3)`` RGB array as PNG bytes, the same every time.""" image_module = require("PIL.Image") buffer = io.BytesIO() image_module.fromarray(np.ascontiguousarray(pixels, dtype=np.uint8), "RGB").save( buffer, format="PNG" ) return buffer.getvalue()
[docs] def render_images( snapshot: ConversationSnapshot, spans: Sequence[PlayerSpan], present: Sequence[bool], fill: ImageFill | None, ) -> ConversationSnapshot: """Paint the ``region`` of every absent image player with ``fill``. ``fill=None`` is the ``delete`` policy: it drops an image whose players are all absent and cover it whole. Images without absent players keep their bytes. Raises: ValueError: If ``fill`` is ``None`` and a region player covers only part of its image, which cannot be cut out. """ players: dict[tuple[int, int], list[tuple[tuple[Box, ...], bool]]] = {} for span, keep in zip(spans, present, strict=True): if span.region is not None: key = (span.message_index, span.part) players.setdefault(key, []).append((span.region, keep)) if not players: return snapshot turns: list[Turn] = [] index = 0 for turn in snapshot.turns: messages: list[Message] = [] for message in turn.messages: own = {part: found for (i, part), found in players.items() if i == index} messages.append(_edit(message, own, fill) if own else message) index += 1 turns.append(Turn(messages=tuple(messages))) return ConversationSnapshot.from_turns(tuple(turns))
def _edit( message: Message, parts: dict[int, list[tuple[tuple[Box, ...], bool]]], fill: ImageFill | None, ) -> Message: images = [p for p in message.content if isinstance(p, ImagePart)] dropped: set[int] = set() for part, found in sorted(parts.items()): absent = [box for region, keep in found if not keep for box in region] if fill is not None and not absent: continue pixels = decode_image(images[part].data()) if fill is None: height, width = pixels.shape[:2] if any(_area(region) != width * height for region, _ in found): msg = ( "the delete policy cannot cut a region out of an image; use pad " "or neutral with an image_fill, or whole-image players" ) raise ValueError(msg) if not any(keep for _, keep in found): dropped.add(part) continue source = _fill_pixels(images[part].data(), pixels, fill) painted = pixels.copy() for left, top, right, bottom in absent: painted[top:bottom, left:right] = source[top:bottom, left:right] message = message.with_media(ImagePart(encode_png(painted)), part) if not dropped: return message kept, seen = [], -1 for item in message.content: if isinstance(item, ImagePart): seen += 1 if seen in dropped: continue kept.append(item) return Message(role=message.role, content=tuple(kept), speaker=message.speaker) def _area(region: tuple[Box, ...]) -> int: return sum((right - left) * (bottom - top) for left, top, right, bottom in region) def _fill_pixels( data: bytes, pixels: NDArray[np.uint8], fill: ImageFill ) -> NDArray[np.uint8]: """Return a full-size image of ``fill`` for ``pixels``.""" match fill: case "grey": return np.full_like(pixels, 128) case "mean": mean = np.round(pixels.reshape(-1, 3).mean(axis=0)) return np.broadcast_to(mean.astype(np.uint8), pixels.shape).copy() case "blur": image_module = require("PIL.Image") filters = require("PIL.ImageFilter") radius = max(pixels.shape[:2]) * BLUR_FRACTION blurred = image_module.fromarray(pixels, "RGB").filter( filters.GaussianBlur(radius) ) return np.asarray(blurred, dtype=np.uint8) case "noise": seed = int.from_bytes(hashlib.sha256(data).digest()[:8], "little") rng = np.random.default_rng(seed) return rng.integers(0, 256, size=pixels.shape, dtype=np.uint8) case _ as unreachable: msg = f"unsupported image fill: {unreachable!r}" raise AssertionError(msg)