video.py 4.38 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3

4
5
from dataclasses import dataclass
from functools import lru_cache
6
from typing import Any, ClassVar, Literal
7
8
9
10
11
12

import numpy as np
import numpy.typing as npt
from huggingface_hub import hf_hub_download
from PIL import Image

13
from vllm.utils.import_utils import PlaceholderModule
14

15
16
from .base import get_cache_dir

17
18
19
20
21
try:
    import librosa
except ImportError:
    librosa = PlaceholderModule("librosa")  # type: ignore[assignment]

22
23
24
25
26
27
28

@lru_cache
def download_video_asset(filename: str) -> str:
    """
    Download and open an image from huggingface
    repo: raushan-testing-hf/videos-test
    """
29
    video_directory = get_cache_dir() / "video-example-data"
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    video_directory.mkdir(parents=True, exist_ok=True)

    video_path = video_directory / filename
    video_path_str = str(video_path)
    if not video_path.exists():
        video_path_str = hf_hub_download(
            repo_id="raushan-testing-hf/videos-test",
            filename=filename,
            repo_type="dataset",
            cache_dir=video_directory,
        )
    return video_path_str


def video_to_ndarrays(path: str, num_frames: int = -1) -> npt.NDArray:
Angela Yi's avatar
Angela Yi committed
45
46
    import cv2

47
48
49
50
51
52
    cap = cv2.VideoCapture(path)
    if not cap.isOpened():
        raise ValueError(f"Could not open video file {path}")

    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    frames = []
53
54
55
56
57
58
59
60
61
62

    num_frames = num_frames if num_frames > 0 else total_frames
    frame_indices = np.linspace(0, total_frames - 1, num_frames, dtype=int)
    for idx in range(total_frames):
        ok = cap.grab()  # next img
        if not ok:
            break
        if idx in frame_indices:  # only decompress needed
            ret, frame = cap.retrieve()
            if ret:
63
64
65
                # OpenCV uses BGR format, we need to convert it to RGB
                # for PIL and transformers compatibility
                frames.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
66
67
68

    frames = np.stack(frames)
    if len(frames) < num_frames:
69
70
71
72
        raise ValueError(
            f"Could not read enough frames from video file {path}"
            f" (expected {num_frames} frames, got {len(frames)})"
        )
73
74
75
    return frames


76
def video_to_pil_images_list(path: str, num_frames: int = -1) -> list[Image.Image]:
77
    frames = video_to_ndarrays(path, num_frames)
78
    return [Image.fromarray(frame) for frame in frames]
79
80


81
def video_get_metadata(path: str, num_frames: int = -1) -> dict[str, Any]:
Angela Yi's avatar
Angela Yi committed
82
83
    import cv2

84
85
86
87
88
89
90
91
    cap = cv2.VideoCapture(path)
    if not cap.isOpened():
        raise ValueError(f"Could not open video file {path}")

    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    duration = total_frames / fps if fps > 0 else 0

92
93
94
    if num_frames == -1 or num_frames > total_frames:
        num_frames = total_frames

95
    metadata = {
96
        "total_num_frames": num_frames,
97
        "fps": duration / num_frames,
98
        "duration": duration,
99
100
101
102
103
        "video_backend": "opencv",
        "frames_indices": list(range(num_frames)),
        # extra field used to control hf processor's video
        # sampling behavior
        "do_sample_frames": num_frames == total_frames,
104
105
106
107
    }
    return metadata


108
109
110
VideoAssetName = Literal["baby_reading"]


111
112
@dataclass(frozen=True)
class VideoAsset:
113
    name: VideoAssetName
114
115
    num_frames: int = -1

116
117
118
119
120
121
122
123
    _NAME_TO_FILE: ClassVar[dict[VideoAssetName, str]] = {
        "baby_reading": "sample_demo_1.mp4",
    }

    @property
    def filename(self) -> str:
        return self._NAME_TO_FILE[self.name]

124
125
126
127
    @property
    def video_path(self) -> str:
        return download_video_asset(self.filename)

128
    @property
129
    def pil_images(self) -> list[Image.Image]:
130
        ret = video_to_pil_images_list(self.video_path, self.num_frames)
131
132
133
        return ret

    @property
134
    def np_ndarrays(self) -> npt.NDArray:
135
        ret = video_to_ndarrays(self.video_path, self.num_frames)
136
        return ret
137

138
139
    @property
    def metadata(self) -> dict[str, Any]:
140
        ret = video_get_metadata(self.video_path, self.num_frames)
141
142
        return ret

143
    def get_audio(self, sampling_rate: float | None = None) -> npt.NDArray:
144
145
        """
        Read audio data from the video asset, used in Qwen2.5-Omni examples.
146

147
148
        See also: examples/offline_inference/qwen2_5_omni/only_thinker.py
        """
149
        return librosa.load(self.video_path, sr=sampling_rate)[0]