video.py 7.33 KB
Newer Older
1
2
# SPDX-License-Identifier: Apache-2.0

3
import base64
4
from functools import partial
5
6
from io import BytesIO
from pathlib import Path
7
from typing import TYPE_CHECKING, Any, Optional
8
9

import numpy as np
10
import numpy.typing as npt
11
from PIL import Image
12
13
14

from vllm.inputs.registry import InputContext
from vllm.logger import init_logger
15
from vllm.transformers_utils.processor import cached_get_video_processor
16
from vllm.utils import 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
30
31
32
33
logger = init_logger(__name__)


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

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

34
35
    def _get_hf_video_processor(
        self,
36
        model_config: "ModelConfig",
37
        mm_processor_kwargs: Optional[dict[str, Any]] = None,
38
39
40
    ):
        if mm_processor_kwargs is None:
            mm_processor_kwargs = {}
41
42
        return cached_get_video_processor(
            model_config.model,
43
44
            trust_remote_code=model_config.trust_remote_code,
            **mm_processor_kwargs)
45
46
47
48

    def _default_input_mapper(
        self,
        ctx: InputContext,
49
        data: ModalityData[VideoItem],
50
        **mm_processor_kwargs,
51
    ) -> MultiModalKwargs:
52
53
        model_config = ctx.model_config

54
        if isinstance(data, list) and len(data) == 1:
55
            data = data[0]  # type: ignore
56

57
        if isinstance(data, np.ndarray) or is_list_of(data, np.ndarray):
58
59
60
61
            video_processor = self._get_hf_video_processor(
                model_config,
                mm_processor_kwargs,
            )
62
63
            if video_processor is None:
                raise RuntimeError("No HuggingFace processor is available "
64
                                   "to process the video object")
65
            try:
66
67
68
69
                # 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
70
71
                batch_data = video_processor(data, return_tensors="pt").data
            except Exception:
72
                logger.error("Failed to process video (%s)", data)
73
74
                raise

75
            return MultiModalKwargs(batch_data)
76
77
78
79
80

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

    def _default_max_multimodal_tokens(self, ctx: InputContext) -> int:
        return 4096
81
82
83
84
85
86
87


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)
88
89
    # lazy import cv2 to avoid bothering users who only use text models
    import cv2
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
    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
113
114


115
116
117
118
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
class VideoLoader:

    @classmethod
    def load_bytes(self, data: bytes, num_frames: int = -1) -> npt.NDArray:
        raise NotImplementedError


class OpenCVVideoBackend(VideoLoader):

    def get_cv2_video_api(self):
        import cv2.videoio_registry as vr

        api_pref = None
        for backend in vr.getStreamBufferedBackends():
            if not vr.hasBackend(backend):
                continue
            if not vr.isBackendBuiltIn(backend):
                _, abi, api = vr.getStreamBufferedBackendPluginVersion(backend)
                if (abi < 1 or (abi == 1 and api < 2)):
                    continue
            api_pref = backend
            break
        return api_pref

    @classmethod
    def load_bytes(cls, data: bytes, num_frames: int = -1) -> npt.NDArray:
        import cv2

        backend = cls().get_cv2_video_api()
        cap = cv2.VideoCapture(BytesIO(data), backend, [])
        if not cap.isOpened():
            raise ValueError("Could not open video stream")

        total_frames_num = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        full_read = num_frames == -1 or total_frames_num < num_frames
        if full_read:
            frame_idx = list(range(0, total_frames_num))
        else:
            uniform_sampled_frames = np.linspace(0,
                                                 total_frames_num - 1,
                                                 num_frames,
                                                 dtype=int)
            frame_idx = uniform_sampled_frames.tolist()

        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        frames = np.empty((len(frame_idx), height, width, 3), dtype=np.uint8)

        i = 0
        for idx in range(total_frames_num):
            ok = cap.grab()  # next img
            if not ok:
                break
            if idx in frame_idx:  # only decompress needed
                ret, frame = cap.retrieve()
                if ret:
                    frames[i] = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
                    i += 1
        # we expect all frames loaded
        assert i == num_frames
        return frames


178
179
180
181
182
183
184
185
186
187
188
189
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
190
        self.video_loader = OpenCVVideoBackend
191
192

    def load_bytes(self, data: bytes) -> npt.NDArray:
193
        return self.video_loader.load_bytes(data, self.num_frames)
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233

    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)