Source code for mllm_shap.backends.mock.image
"""Deterministic mock backend that sees the coloured squares of images.
@domain backends
@see [[knowledge/architecture/backends]]
@tested-by [[tests/backends/test_mock_image.py]]
"""
import hashlib
import numpy as np
from ...domain.config import GenerationConfig
from ...domain.conversation import ConversationSnapshot, ImagePart
from ...domain.generation import GenerationRecord
from ...masking.image import decode_image
from ...value.generation_records import generation_record_from_text
from .._chat import message_chat_text
from .backend import MockBackend
MIN_SATURATION = 100
"""Smallest channel spread (max minus min, of 255) that makes a pixel coloured;
white, black, grey and the mean fill of a mostly white image stay below it."""
MIN_PIXELS = 64
"""Pixels of one exact colour a square needs to be seen (an 8 by 8 patch)."""
[docs]
class MockImageBackend(MockBackend):
"""Echo text words and answer one token per visible coloured square of an image.
A square is every pixel of one exact saturated colour; it is seen while at
least :data:`MIN_PIXELS` of them remain. Painting a square's cell with any fill
drops exactly its token, so grid players over one square per cell have closed
form Shapley values. Images need the ``image`` extra.
"""
[docs]
async def generate(
self,
snapshot: ConversationSnapshot,
generation: GenerationConfig,
) -> GenerationRecord:
"""Return the seen words of ``snapshot``, at most ``max_new_tokens``."""
words: list[str] = []
for message in snapshot.messages():
words.extend(message_chat_text(message).split())
for part in message.content:
if isinstance(part, ImagePart):
words.extend(_square_tokens(part))
return generation_record_from_text(" ".join(words[: generation.max_new_tokens]))
def _square_tokens(part: ImagePart) -> list[str]:
pixels = decode_image(part.data()).reshape(-1, 3).astype(np.int16)
coloured = pixels[pixels.max(axis=1) - pixels.min(axis=1) >= MIN_SATURATION]
if not len(coloured):
return []
colours, counts = np.unique(coloured, axis=0, return_counts=True)
return [
hashlib.sha256(bytes(colour.astype(np.uint8))).hexdigest()[:4]
for colour, count in zip(colours, counts, strict=True)
if count >= MIN_PIXELS
]