File size: 3,112 Bytes
08d2a21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
"""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()