Mistral-Multimodal-Embed-1B / processing_mistral_contrastive.py
brevitech's picture
Unmodified mirror of mistralai/Mistral-Multimodal-Embed-1B@bfdaf7bd6fd6
08d2a21 verified
Raw History Blame Contribute Delete
3.11 kB
"""Text, image, and video preprocessing for Mistral Multimodal Embed."""
import numpy as np
import torch
from transformers.feature_extraction_utils import BatchFeature
from transformers.image_transforms import to_pil_image
from transformers.image_utils import make_flat_list_of_images
from transformers.processing_utils import ProcessorMixin, VideosKwargs
from transformers.video_processing_utils import BaseVideoProcessor
from .image_transforms import TransformKind, build_transform
class MistralContrastiveVideoProcessorKwargs(VideosKwargs, total=False):
transform: str
use_cv2_resize: bool
class MistralContrastiveVideoProcessor(BaseVideoProcessor):
model_input_names = ["videos"]
valid_kwargs = MistralContrastiveVideoProcessorKwargs
size = {"longest_edge": 224}
transform = "keep_ratio"
use_cv2_resize = True
do_sample_frames = True
num_frames = 16
def sample_frames(self, metadata, num_frames=None, fps=None, **kwargs):
if fps is not None:
return super().sample_frames(metadata, num_frames=num_frames, fps=fps, **kwargs)
count = self.num_frames if num_frames is None else num_frames
if count < 1 or metadata.total_num_frames < 1:
raise ValueError("Video sampling requires at least one frame.")
return np.linspace(0, metadata.total_num_frames - 1, count).round().astype(int)
def _preprocess(self, videos, size, transform, use_cv2_resize, **kwargs):
process_frame = build_transform(TransformKind(transform), size.longest_edge or size.height, use_cv2_resize)
clips = [torch.stack([process_frame(frame) for frame in video]) for video in videos]
return BatchFeature({"videos": clips})
class MistralContrastiveProcessor(ProcessorMixin):
def __init__(self, image_processor, tokenizer, video_processor):
super().__init__(image_processor, tokenizer, video_processor)
def __call__(self, text=None, images=None, videos=None, **kwargs):
if text is None and images is None and videos is None:
raise ValueError("Provide text, images, or videos to encode.")
kwargs = self._merge_kwargs(
self.valid_processor_kwargs, tokenizer_init_kwargs=self.tokenizer.init_kwargs, **kwargs
)
inputs = BatchFeature()
if text is not None:
inputs.update(self.tokenizer(text, **kwargs["text_kwargs"]))
if images is not None:
images = make_flat_list_of_images(self.image_processor.fetch_images(images))
images = [to_pil_image(image) for image in images]
inputs.update(self.image_processor(images, **kwargs["images_kwargs"]))
if videos is not None:
inputs.update(self.video_processor(videos, **kwargs["videos_kwargs"]))
if text is not None:
# The joint forward names this argument differently from get_video_features.
inputs["video_pixel_values"] = inputs.pop("videos")
return inputs
MistralContrastiveVideoProcessor.register_for_auto_class()
MistralContrastiveProcessor.register_for_auto_class()