Aluode/PerceptionLabPortable
0
1# coding=utf-82# Copyright 2025 The HuggingFace Inc. team. All rights reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""Fast Video processor class for InternVL."""16 17from typing import Optional, Union18 19import torch20from torchvision.transforms.v2 import functional as F21 22from ...image_processing_utils import BatchFeature23from ...image_utils import OPENAI_CLIP_MEAN, OPENAI_CLIP_STD, PILImageResampling, SizeDict24from ...processing_utils import Unpack, VideosKwargs25from ...utils import TensorType26from ...video_processing_utils import BaseVideoProcessor27from ...video_utils import VideoMetadata, group_videos_by_shape, reorder_videos28 29 30class InternVLVideoProcessorInitKwargs(VideosKwargs):31 initial_shift: Union[bool, float, int]32 33 34class InternVLVideoProcessor(BaseVideoProcessor):35 resample = PILImageResampling.BICUBIC36 image_mean = OPENAI_CLIP_MEAN37 image_std = OPENAI_CLIP_STD38 size = {"height": 384, "width": 384}39 do_resize = True40 do_rescale = True41 do_normalize = True42 do_convert_rgb = True43 initial_shift = True44 do_sample_frames = False # Set to False for BC, recommended to set `True` in new models45 valid_kwargs = InternVLVideoProcessorInitKwargs46 model_input_names = ["pixel_values_videos"]47 48 def __init__(self, **kwargs: Unpack[InternVLVideoProcessorInitKwargs]):49 super().__init__(**kwargs)50 51 def sample_frames(52 self,53 metadata: VideoMetadata,54 num_frames: Optional[int] = None,55 fps: Optional[Union[int, float]] = None,56 initial_shift: Optional[Union[bool, float, int]] = None,57 **kwargs,58 ):59 """60 Default sampling function which uniformly samples the desired number of frames between 0 and total number of frames.61 If `fps` is passed along with metadata, `fps` frames per second are sampled uniformty. Arguments `num_frames`62 and `fps` are mutually exclusive.63 64 Args:65 metadata (`VideoMetadata`):66 Metadata of the video containing information about total duration, fps and total number of frames.67 num_frames (`int`, *optional*):68 Maximum number of frames to sample. Defaults to `self.num_frames`.69 fps (`int` or `float`, *optional*):70 Target frames to sample per second. Defaults to `self.fps`.71 initial_shift (`bool`, `float` or `int`, defaults to `self.initial_shift`):72 The initial shift to apply when sampling frames. If `True`, the shift is set so that frames are sampled from the middle of the video.73 74 Returns:75 np.ndarray:76 Indices to sample video frames.77 """78 num_frames = num_frames if num_frames is not None else self.num_frames79 initial_shift = initial_shift if initial_shift is not None else self.initial_shift80 total_num_frames = metadata.total_num_frames81 82 # If num_frames is not given but fps is, calculate num_frames from fps83 if num_frames is None and fps is not None:84 if metadata is None or metadata.fps is None:85 raise ValueError(86 "Asked to sample `fps` frames per second but no video metadata was provided which is required when sampling with `fps`. "87 "Please pass in `VideoMetadata` object or use a fixed `num_frames` per input video"88 )89 num_frames = int(total_num_frames / metadata.fps * fps)90 91 if initial_shift is True:92 initial_shift = total_num_frames / num_frames / 293 94 if num_frames > total_num_frames:95 raise ValueError(96 f"Video can't be sampled. The `num_frames={num_frames}` exceeds `total_num_frames={total_num_frames}`. "97 )98 99 indices = torch.arange(initial_shift, total_num_frames, total_num_frames / num_frames).int()100 return indices101 102 def _preprocess(103 self,104 videos: list["torch.Tensor"],105 do_convert_rgb: bool,106 do_resize: bool,107 size: SizeDict,108 interpolation: Optional["F.InterpolationMode"],109 do_center_crop: bool,110 crop_size: SizeDict,111 do_rescale: bool,112 rescale_factor: float,113 do_normalize: bool,114 image_mean: Optional[Union[float, list[float]]],115 image_std: Optional[Union[float, list[float]]],116 return_tensors: Optional[Union[str, TensorType]] = None,117 **kwargs,118 ) -> BatchFeature:119 # Group videos by size for batched resizing120 grouped_videos, grouped_videos_index = group_videos_by_shape(videos)121 resized_videos_grouped = {}122 for shape, stacked_videos in grouped_videos.items():123 if do_convert_rgb:124 stacked_videos = self.convert_to_rgb(stacked_videos)125 if do_resize:126 stacked_videos = self.resize(stacked_videos, size=size, interpolation=interpolation)127 resized_videos_grouped[shape] = stacked_videos128 resized_videos = reorder_videos(resized_videos_grouped, grouped_videos_index)129 130 # Group videos by size for further processing131 # Needed in case do_resize is False, or resize returns videos with different sizes132 grouped_videos, grouped_videos_index = group_videos_by_shape(resized_videos)133 processed_videos_grouped = {}134 for shape, stacked_videos in grouped_videos.items():135 if do_center_crop:136 stacked_videos = self.center_crop(stacked_videos, crop_size)137 # Fused rescale and normalize138 stacked_videos = self.rescale_and_normalize(139 stacked_videos, do_rescale, rescale_factor, do_normalize, image_mean, image_std140 )141 processed_videos_grouped[shape] = stacked_videos142 143 processed_videos = reorder_videos(processed_videos_grouped, grouped_videos_index)144 processed_videos = torch.stack(processed_videos, dim=0) if return_tensors else processed_videos145 146 return BatchFeature(data={"pixel_values_videos": processed_videos}, tensor_type=return_tensors)147 148 149__all__ = ["InternVLVideoProcessor"]150 