"""HuggingFace image processor for the Mistral two-encoder contrastive model. The default transform is ``keep_ratio``, which preserves each image's aspect ratio, since the model accepts variable resolutions. This processor wraps :func:`image_transforms.build_transform` so the three transforms (``squash`` / ``center_crop`` / ``keep_ratio``), any resolution, and the cv2 / bicubic resampler choice are all reachable through the standard ``AutoImageProcessor`` API, and the choice round-trips through ``preprocessor_config.json``. ``keep_ratio`` yields a rectangular, per-image-varying tensor, so ``preprocess`` returns the batch as an unstacked list of tensors (the model's packed path consumes ``get_image_features([...])``). ``squash`` / ``center_crop`` are fixed-size and return a stacked ``(N, 3, size, size)`` tensor. """ from collections.abc import Callable from functools import cache from typing import Any, ClassVar import torch from PIL import Image from transformers.image_processing_base import BatchFeature from transformers.image_processing_utils import BaseImageProcessor from transformers.processing_utils import ImagesKwargs from .image_transforms import GRID_UNIT, TransformKind, build_transform class MistralContrastiveImageProcessorKwargs(ImagesKwargs, total=False): """Declares the custom init kwargs so transformers>=5 routes them through ``__init__`` (validated) instead of setting them afterwards with a backward-compatibility warning.""" transform: str use_cv2_resize: bool _VALID_TRANSFORMS = tuple(TransformKind) # squash / center_crop emit exactly size x size; the side must tile the ViT (multiple of # patch_size * spatial_merge_size). keep_ratio rounds each side to GRID_UNIT internally, so any # size is fine for it. _FIXED_SIZE_TRANSFORMS = frozenset({"squash", "center_crop"}) @cache def _cached_build_transform(transform: str, size: int, use_cv2_resize: bool) -> Callable[[Image.Image | torch.Tensor], torch.Tensor]: """Built transforms are stateless and reusable, so cache one per unique config rather than rebuilding the torchvision Compose on every ``preprocess`` call. Kept module-level (not on the instance) so it never leaks into ``__dict__`` / ``preprocessor_config.json``.""" return build_transform(TransformKind(transform), size, use_cv2_resize) class MistralContrastiveImageProcessor(BaseImageProcessor): model_input_names: ClassVar[list[str]] = ["pixel_values"] valid_kwargs = MistralContrastiveImageProcessorKwargs def __init__( self, transform: str = "keep_ratio", size: int = 448, use_cv2_resize: bool = True, **kwargs: Any, ) -> None: super().__init__(**kwargs) assert transform in _VALID_TRANSFORMS, f"Unknown transform {transform!r}; expected one of {_VALID_TRANSFORMS}" if transform in _FIXED_SIZE_TRANSFORMS: assert size % GRID_UNIT == 0, ( f"{transform} emits {size}x{size}, which must be a multiple of {GRID_UNIT} " f"(patch_size * spatial_merge_size) to tile the ViT; got size={size}" ) self.transform = transform self.size = size self.use_cv2_resize = use_cv2_resize def preprocess( self, images: Image.Image | list[Image.Image] | torch.Tensor | list[torch.Tensor], return_tensors: str | None = None, ) -> BatchFeature: # Accepts PIL images or uint8 RGB tensors: one (3, H, W) frame, or a (T, 3, H, W) # stack such as torchcodec's ``get_frames_at(...).data``. if isinstance(images, Image.Image): images = [images] elif isinstance(images, torch.Tensor): assert images.ndim in (3, 4), ( f"Expected a (3, H, W) or (T, 3, H, W) tensor, got shape {tuple(images.shape)}" ) images = [images] if images.ndim == 3 else list(images) transform = _cached_build_transform(self.transform, self.size, self.use_cv2_resize) pixel_values = [transform(image) for image in images] # keep_ratio produces per-image-varying sizes that cannot be stacked or coerced by # BatchFeature; keep them as a list and skip tensor conversion. if self.transform == "keep_ratio": return BatchFeature(data={"pixel_values": pixel_values}, tensor_type=None) stacked = torch.stack(pixel_values) return BatchFeature(data={"pixel_values": stacked}, tensor_type=return_tensors) MistralContrastiveImageProcessor.register_for_auto_class("AutoImageProcessor")