Download code/tt_embgemma/preprocess/video.py from changh95/embeddinggemma-2: direct link, hf CLI and curl.
- Browser
- Download file 2.44 kB
-
https://huggingface.co/changh95/embeddinggemma-2/resolve/main/code/tt_embgemma/preprocess/video.py
- Command line
-
hf download hf://changh95/embeddinggemma-2/code/tt_embgemma/preprocess/video.py
-
curl -L -o video.py https://huggingface.co/changh95/embeddinggemma-2/resolve/main/code/tt_embgemma/preprocess/video.py
2.44 kB
| # 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] | |