video.py 5.85 KB
Newer Older
1
2
3
4
import base64
from functools import lru_cache, partial
from io import BytesIO
from pathlib import Path
5
from typing import TYPE_CHECKING, Any, Dict, Optional
6

7
import cv2
8
import numpy as np
9
import numpy.typing as npt
10
from PIL import Image
11
12
13

from vllm.inputs.registry import InputContext
from vllm.logger import init_logger
14
from vllm.transformers_utils.processor import get_video_processor
15
from vllm.transformers_utils.tokenizer import get_tokenizer
16
from vllm.utils import PlaceholderModule, is_list_of
17

18
from .base import MediaIO, ModalityData
19
from .image import ImageMediaIO, ImagePlugin
20
from .inputs import MultiModalKwargs, VideoItem
21

22
23
24
if TYPE_CHECKING:
    from vllm.config import ModelConfig

25
26
27
28
29
try:
    import decord
except ImportError:
    decord = PlaceholderModule("decord")  # type: ignore[assignment]

30
31
32
33
34
35
36
37
38
39
40
41
logger = init_logger(__name__)

cached_get_video_processor = lru_cache(get_video_processor)
cached_get_tokenizer = lru_cache(get_tokenizer)


class VideoPlugin(ImagePlugin):
    """Plugin for video data."""

    def get_data_key(self) -> str:
        return "video"

42
43
    def _get_hf_video_processor(
        self,
44
        model_config: "ModelConfig",
45
46
47
48
        mm_processor_kwargs: Optional[Dict[str, Any]] = None,
    ):
        if mm_processor_kwargs is None:
            mm_processor_kwargs = {}
49
50
        return cached_get_video_processor(
            model_config.model,
51
52
            trust_remote_code=model_config.trust_remote_code,
            **mm_processor_kwargs)
53
54
55
56

    def _default_input_mapper(
        self,
        ctx: InputContext,
57
        data: ModalityData[VideoItem],
58
        **mm_processor_kwargs,
59
    ) -> MultiModalKwargs:
60
61
        model_config = ctx.model_config

62
        if isinstance(data, list) and len(data) == 1:
63
            data = data[0]  # type: ignore
64

65
        if isinstance(data, np.ndarray) or is_list_of(data, np.ndarray):
66
67
68
69
            video_processor = self._get_hf_video_processor(
                model_config,
                mm_processor_kwargs,
            )
70
71
            if video_processor is None:
                raise RuntimeError("No HuggingFace processor is available "
72
                                   "to process the video object")
73
            try:
74
75
76
77
                # NOTE: Similar to image; it may be a good idea to filter and
                # pass mm_processor_kwargs here too, but for now we don't to
                # avoid extra complexity if the initializer and preprocess
                # signatures of the processor don't align
78
79
                batch_data = video_processor(data, return_tensors="pt").data
            except Exception:
80
                logger.error("Failed to process video (%s)", data)
81
82
                raise

83
            return MultiModalKwargs(batch_data)
84
85
86
87
88

        raise TypeError(f"Invalid video type: {type(data)}")

    def _default_max_multimodal_tokens(self, ctx: InputContext) -> int:
        return 4096
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118


def resize_video(frames: npt.NDArray, size: tuple[int, int]) -> npt.NDArray:
    num_frames, _, _, channels = frames.shape
    new_height, new_width = size
    resized_frames = np.empty((num_frames, new_height, new_width, channels),
                              dtype=frames.dtype)
    for i, frame in enumerate(frames):
        resized_frame = cv2.resize(frame, (new_width, new_height))
        resized_frames[i] = resized_frame
    return resized_frames


def rescale_video_size(frames: npt.NDArray, size_factor: float) -> npt.NDArray:
    _, height, width, _ = frames.shape
    new_height = int(height * size_factor)
    new_width = int(width * size_factor)

    return resize_video(frames, (new_height, new_width))


def sample_frames_from_video(frames: npt.NDArray,
                             num_frames: int) -> npt.NDArray:
    total_frames = frames.shape[0]
    if num_frames == -1:
        return frames

    frame_indices = np.linspace(0, total_frames - 1, num_frames, dtype=int)
    sampled_frames = frames[frame_indices, ...]
    return sampled_frames
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188


class VideoMediaIO(MediaIO[npt.NDArray]):

    def __init__(
        self,
        image_io: ImageMediaIO,
        *,
        num_frames: int = 32,
    ) -> None:
        super().__init__()

        self.image_io = image_io
        self.num_frames = num_frames

    def load_bytes(self, data: bytes) -> npt.NDArray:
        vr = decord.VideoReader(BytesIO(data), num_threads=1)
        total_frame_num = len(vr)

        num_frames = self.num_frames
        if total_frame_num > num_frames:
            uniform_sampled_frames = np.linspace(0,
                                                 total_frame_num - 1,
                                                 num_frames,
                                                 dtype=int)
            frame_idx = uniform_sampled_frames.tolist()
        else:
            frame_idx = list(range(0, total_frame_num))

        return vr.get_batch(frame_idx).asnumpy()

    def load_base64(self, media_type: str, data: str) -> npt.NDArray:
        if media_type.lower() == "video/jpeg":
            load_frame = partial(
                self.image_io.load_base64,
                "image/jpeg",
            )

            return np.stack([
                np.array(load_frame(frame_data))
                for frame_data in data.split(",")
            ])

        return self.load_bytes(base64.b64decode(data))

    def load_file(self, filepath: Path) -> npt.NDArray:
        with filepath.open("rb") as f:
            data = f.read()

        return self.load_bytes(data)

    def encode_base64(
        self,
        media: npt.NDArray,
        *,
        video_format: str = "JPEG",
    ) -> str:
        video = media

        if video_format == "JPEG":
            encode_frame = partial(
                self.image_io.encode_base64,
                image_format=video_format,
            )

            return ",".join(
                encode_frame(Image.fromarray(frame)) for frame in video)

        msg = "Only JPEG format is supported for now."
        raise NotImplementedError(msg)