File size: 2,439 Bytes
5c33f00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# SPDX-License-Identifier: Apache-2.0
"""Video preprocessing = ``EmbeddingGemma2VideoProcessor``: sample frames at ``fps`` (default 1) from decoded frames
with metadata (source fps, duration), cap at ``max_frames`` (default 32, uniform re-sampling), then every frame is an
image with ``max_soft_tokens`` (default 140) budget. Without a source fps every frame is kept (official warning
path). The token sequence has one ``<boi> + n x <|video|> + <eoi>`` block per frame (no timestamps)."""

from __future__ import annotations

from typing import List, Optional

import numpy as np

from .. import model_spec as S
from .image import Patches, patchify, to_uint8_chw


def sample_indices(total: int, src_fps: Optional[float], duration: Optional[float], fps: Optional[float] = 1.0,
                   max_frames: Optional[int] = 32, overflow: str = "uniform") -> np.ndarray:
    if total <= 0:
        raise ValueError("video has no frames")
    if fps is not None and (src_fps is None or duration is None):
        fps = None
    if fps is None:
        idx = np.arange(total, dtype=int)
    else:
        step = src_fps / fps
        n = max(1, int(duration * fps))
        idx = np.array([min(total - 1, int(i * step)) for i in range(n)], dtype=int)
    if max_frames is not None and len(idx) > max_frames:
        if overflow == "truncate":
            idx = idx[:max_frames]
        elif overflow == "uniform":
            idx = idx[np.linspace(0, len(idx) - 1, max_frames, dtype=int)]
        else:
            raise ValueError("overflow must be 'uniform' or 'truncate'")
    return idx


def preprocess_video(frames, src_fps: Optional[float] = None, duration: Optional[float] = None, fps: float = 1.0,
                     max_frames: int = 32, max_soft_tokens: int = S.V_DEFAULT_VIDEO_TOKENS,
                     overflow: str = "uniform") -> List[Patches]:
    """frames: [T, H, W, 3 or 4] uint8 array (or list of HxWx3 / HxWx4 arrays / PIL images) -> list of per-frame
    Patches; transparency is composited onto white like images (image.to_uint8_chw)."""
    if max_soft_tokens not in S.V_SOFT_TOKENS:
        raise ValueError(f"max_soft_tokens must be one of {S.V_SOFT_TOKENS}")
    T = len(frames)
    if duration is None and src_fps:
        duration = T / float(src_fps)
    idx = sample_indices(T, src_fps, duration, fps, max_frames, overflow)
    return [patchify(to_uint8_chw(frames[int(i)]), max_soft_tokens) for i in idx]