
    |-j                        d dl Z d dlZd dlZd dlmZ d dlmZ d dlmZ d dl	Z
d dlmZmZ d dlmZ ddlmZ dd	lmZ dd
lmZ ddlmZmZmZmZ ddlmZmZ ddlmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z) ddl*m+Z+ ddl,m-Z- ddl.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7  e%            rd dl8Z8 e'            rd dl9m:c m;c m<Z=  e            rddlm>Z>  e(j?        e@          ZAdZB e#deB           e-d           G d de                                  ZC e$eCjD                  eC_D        eCjD        jE        .eCjD        jE        F                    ddd          eCjD        _E        dS dS )    N)Callable)partial)Any)create_repois_offline_mode)validate_typed_dict   )custom_object_save)TorchvisionBackend)BatchFeature)ChannelDimensionSizeDictis_vision_availablevalidate_kwargs)UnpackVideosKwargs)IMAGE_PROCESSOR_NAMEPROCESSOR_NAMEVIDEO_PROCESSOR_NAME
TensorTypeadd_start_docstrings	copy_funcis_torch_availableis_torchcodec_availableis_torchvision_v2_availableloggingsafe_load_json_filecached_file)requires)	
VideoInputVideoMetadatagroup_videos_by_shapeinfer_channel_dimension_formatis_valid_video
load_videomake_batched_metadatamake_batched_videosreorder_videos)PILImageResamplinga  
    Args:
        do_resize (`bool`, *optional*, defaults to `self.do_resize`):
            Whether to resize the video's (height, width) dimensions to the specified `size`. Can be overridden by the
            `do_resize` parameter in the `preprocess` method.
        size (`dict`, *optional*, defaults to `self.size`):
            Size of the output video after resizing. Can be overridden by the `size` parameter in the `preprocess`
            method.
        size_divisor (`int`, *optional*, defaults to `self.size_divisor`):
            The size by which to make sure both the height and width can be divided.
        default_to_square (`bool`, *optional*, defaults to `self.default_to_square`):
            Whether to default to a square video when resizing, if size is an int.
        resample (`PILImageResampling`, *optional*, defaults to `self.resample`):
            Resampling filter to use if resizing the video. Only has an effect if `do_resize` is set to `True`. Can be
            overridden by the `resample` parameter in the `preprocess` method.
        do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
            Whether to center crop the video to the specified `crop_size`. Can be overridden by `do_center_crop` in the
            `preprocess` method.
        crop_size (`dict[str, int]` *optional*, defaults to `self.crop_size`):
            Size of the output video after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
            method.
        do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
            Whether to rescale the video by the specified scale `rescale_factor`. Can be overridden by the
            `do_rescale` parameter in the `preprocess` method.
        rescale_factor (`int` or `float`, *optional*, defaults to `self.rescale_factor`):
            Scale factor to use if rescaling the video. Only has an effect if `do_rescale` is set to `True`. Can be
            overridden by the `rescale_factor` parameter in the `preprocess` method.
        do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
            Whether to normalize the video. Can be overridden by the `do_normalize` parameter in the `preprocess`
            method. Can be overridden by the `do_normalize` parameter in the `preprocess` method.
        image_mean (`float` or `list[float]`, *optional*, defaults to `self.image_mean`):
            Mean to use if normalizing the video. This is a float or list of floats the length of the number of
            channels in the video. Can be overridden by the `image_mean` parameter in the `preprocess` method. Can be
            overridden by the `image_mean` parameter in the `preprocess` method.
        image_std (`float` or `list[float]`, *optional*, defaults to `self.image_std`):
            Standard deviation to use if normalizing the video. This is a float or list of floats the length of the
            number of channels in the video. Can be overridden by the `image_std` parameter in the `preprocess` method.
            Can be overridden by the `image_std` parameter in the `preprocess` method.
        do_convert_rgb (`bool`, *optional*, defaults to `self.image_std`):
            Whether to convert the video to RGB.
        video_metadata (`VideoMetadata`, *optional*):
            Metadata of the video containing information about total duration, fps and total number of frames.
        do_sample_frames (`int`, *optional*, defaults to `self.do_sample_frames`):
            Whether to sample frames from the video before processing or to process the whole video.
        num_frames (`int`, *optional*, defaults to `self.num_frames`):
            Maximum number of frames to sample when `do_sample_frames=True`.
        fps (`int` or `float`, *optional*, defaults to `self.fps`):
            Target frames to sample per second when `do_sample_frames=True`.
        return_tensors (`str` or `TensorType`, *optional*):
            Returns stacked tensors if set to `pt, otherwise returns a list of tensors.
        data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
            The channel dimension format for the output video. Can be one of:
            - `"channels_first"` or `ChannelDimension.FIRST`: video in (num_channels, height, width) format.
            - `"channels_last"` or `ChannelDimension.LAST`: video in (height, width, num_channels) format.
            - Unset: Use the channel dimension format of the input video.
        input_data_format (`ChannelDimension` or `str`, *optional*):
            The channel dimension format for the input video. If unset, the channel dimension format is inferred
            from the input video. Can be one of:
            - `"channels_first"` or `ChannelDimension.FIRST`: video in (num_channels, height, width) format.
            - `"channels_last"` or `ChannelDimension.LAST`: video in (height, width, num_channels) format.
            - `"none"` or `ChannelDimension.NONE`: video in (height, width) format.
        device (`torch.device`, *optional*):
            The device to process the videos on. If unset, the device is inferred from the input videos.
        return_metadata (`bool`, *optional*):
            Whether to return video metadata or not.
        z!Constructs a base VideoProcessor.)visiontorchvision)backendsc                       e Zd ZdZdZdZdZdZdZdZ	dZ
dZdZdZdZdZdZdZdZdZdZdZeZdgZdee         ddf fdZdefd	Zd
ddefdZ	 	 dAdede dz  de e!z  dz  fdZ"	 	 dAdedee#z  de$dz  de%dz  de&d         f
dZ'	 	 dAdede(e)z  dz  de(dz  de&d         fdZ* e+e,          dedee         defd            Z-	 dBde&d         de$de$de.ddde$d e.d!e$d"e!d#e$d$e!e&e!         z  dz  d%e!e&e!         z  dz  d&e(e/z  dz  defd'Z0e1	 	 	 	 	 dCd)e(e2j3        z  d*e(e2j3        z  dz  d+e$d,e$d-e(e$z  dz  d.e(fd/            Z4dDd0e(e2j3        z  d1e$fd2Z5e1d)e(e2j3        z  de6e#e(e7f         e#e(e7f         f         fd3            Z8e1d4e#e(e7f         fd5            Z9de#e(e7f         f fd6Z:de(fd7Z;d8e(e2j3        z  fd9Z<d: Z=e1d;e(e2j3        z  fd<            Z>e1dEd>            Z?dBd?e(e&e(         z  e&e&e(                  z  fd@Z@ xZAS )FBaseVideoProcessorNTgp?Fpixel_values_videoskwargsreturnc                 :     t                      j        di | d S )N )super__init__)selfr1   	__class__s     c/var/www/html/banglarbhumi/venv/lib/python3.11/site-packages/transformers/video_processing_utils.pyr6   zBaseVideoProcessor.__init__   s&    ""6"""""    c                      | j         |fi |S N)
preprocess)r7   videosr1   s      r9   __call__zBaseVideoProcessor.__call__   s    tv00000r:   videoztorch.Tensorc                 :   t          j        |          }|j        d         dk    s&|ddddddf         dk                                     s|S |ddddddf         dz  }d|ddddddf         z
  dz  |ddddddf         |dddddddf         z  z   }|S )z
        Converts a video to RGB format.

        Args:
            video (`"torch.Tensor"`):
                The video to convert.

        Returns:
            `torch.Tensor`: The converted video.
           .N   g     o@r	   )tvFgrayscale_to_rgbshapeany)r7   r@   alphas      r9   convert_to_rgbz!BaseVideoProcessor.convert_to_rgb   s     $U++;r?ac1aaal(;c(A'F'F'H'HL c1aaal#e+U3aaa?++s2U3aaa?5KeTWY[Z[Y[]^]^]^`a`a`aTaNb5bbr:   metadata
num_framesfpsc                    ||t          d          ||n| j        }||n| j        }|j        }|4|2||j        t          d          t	          ||j        z  |z            }||k    rt          d| d| d          |,t          j        d|||z                                            }n't          j        d|                                          }|S )a%  
        Default sampling function which uniformly samples the desired number of frames between 0 and total number of frames.
        If `fps` is passed along with metadata, `fps` frames per second are sampled uniformty. Arguments `num_frames`
        and `fps` are mutually exclusive.

        Args:
            metadata (`VideoMetadata`):
                Metadata of the video containing information about total duration, fps and total number of frames.
            num_frames (`int`, *optional*):
                Maximum number of frames to sample. Defaults to `self.num_frames`.
            fps (`int` or `float`, *optional*):
                Target frames to sample per second. Defaults to `self.fps`.

        Returns:
            np.ndarray:
                Indices to sample video frames.
        Nzc`num_frames`, `fps`, and `sample_indices_fn` are mutually exclusive arguments, please use only one!zAsked to sample `fps` frames per second but no video metadata was provided which is required when sampling with `fps`. Please pass in `VideoMetadata` object or use a fixed `num_frames` per input videoz(Video can't be sampled. The `num_frames=z` exceeds `total_num_frames=z`. r   )
ValueErrorrL   rM   total_num_framesinttorcharange)r7   rK   rL   rM   r1   rP   indicess          r9   sample_framesz BaseVideoProcessor.sample_frames   s"   0 ?z5u   $.#9ZZt
_cc$(#4 #/8<#7 h   -<sBCCJ(((x:xxcsxxx   !l1&68H:8UVVZZ\\GGl1&677;;==Gr:   r>   video_metadatado_sample_framessample_indices_fnc                 8    t          |          }t          ||          }t          |d                   rd|rbg }g }t          ||          D ]H\  }} ||          }	|	|_        |                    ||	                    |                    |           I|}|}n}t          |d                   sht          |d         t                    r3 fd                     |          D             }|rt          d          n 
                    ||          \  }}||fS )zB
        Decode input videos and sample frames if needed.
        )rV   r   )rK   c                 T    g | ]$}t          j        fd |D             d          %S )c                 :    g | ]}                     |          S r4   )process_image).0imager7   s     r9   
<listcomp>zKBaseVideoProcessor._decode_and_sample_videos.<locals>.<listcomp>.<listcomp>  s'     O O Ou!3!3E!:!: O O Or:   r   )dim)rR   stack)r]   imagesr7   s     r9   r_   z@BaseVideoProcessor._decode_and_sample_videos.<locals>.<listcomp>  sN        K O O O O O O OUVWWW  r:   zUSampling frames from a list of images is not supported! Set `do_sample_frames=False`.rX   )r(   r'   r%   zipframes_indicesappend
isinstancelistfetch_imagesrO   fetch_videos)
r7   r>   rV   rW   rX   sampled_videossampled_metadatar@   rK   rT   s
   `         r9   _decode_and_sample_videosz,BaseVideoProcessor._decode_and_sample_videos  ss    %V,,.vnUUU &)$$ 	h)9 	hN!#&v~#>#> 2 2x++X>>>*1'%%eGn555 ''1111#F-NNq	** 	h&)T** h   "&"3"3F";";   $ $o  
 *.):):6Uf):)g)g&~%%r:   input_data_formatdevicec                    g }|D ]}t          |t          j                  r&t          j        |                                          }|t          |          }|t          j        k    r*|	                    dddd                                          }||
                    |          }|                    |           |S )z:
        Prepare the input videos for processing.
        Nr   rC   r	      )rg   npndarrayrR   
from_numpy
contiguousr$   r   LASTpermutetorf   )r7   r>   rn   ro   processed_videosr@   s         r9   _prepare_input_videosz(BaseVideoProcessor._prepare_input_videos*  s      	+ 	+E%,, =(//::<< !($B5$I$I! $4$999aAq11<<>>!((##E****r:   c           	      (   t          |                                t          | j        j                                                  dgz              t          | j        |           | j        j        D ]'}|                    |t          | |d                      (|                    d          }|                    d          }|                    d          }|                    d          }|rt          | j
        fi |nd }|                     ||||          \  }}|                     |||          } | j        di |} | j        di | |                    d	           |                    d
          }	 | j        dd|i|}
|	r||
d<   |
S )Nreturn_tensors)captured_kwargsvalid_processor_keysrn   rW   ro   rV   )rV   rW   rX   )r>   rn   ro   data_formatreturn_metadatar>   r4   )r   keysrh   valid_kwargs__annotations__r   
setdefaultgetattrpopr   rU   rm   rz   _standardize_kwargs_validate_preprocess_kwargs_preprocess)r7   r>   r1   
kwarg_namern   rW   ro   rV   rX   r   preprocessed_videoss              r9   r=   zBaseVideoProcessor.preprocessG  s    	"KKMM!%d&7&G&L&L&N&N!O!OScRd!d	
 	
 	
 	
 	D-v666 +; 	K 	KJj'$
D*I*IJJJJ"JJ':;;!::&899H%%$455EU_GD$6AA&AAA[_!%!?!?)-/	 "@ "
 "
 ++6M^gm+nn))33F33((226222 	

=!!! **%677.d.GGfGGG 	C4B 01""r:   do_convert_rgb	do_resizesizeresamplez7PILImageResampling | tvF.InterpolationMode | int | Nonedo_center_crop	crop_size
do_rescalerescale_factordo_normalize
image_mean	image_stdr|   c           	         t          |          \  }}i }|                                D ];\  }}|r|                     |          }|r|                     |||          }|||<   <t	          ||          }t          |          \  }}i }|                                D ]<\  }}|r|                     ||          }|                     |||	|
||          }|||<   =t	          ||          }t          d|i|          S )N)r   r   r0   )datatensor_type)r#   itemsrJ   resizer)   center_croprescale_and_normalizer   )r7   r>   r   r   r   r   r   r   r   r   r   r   r   r|   r1   grouped_videosgrouped_videos_indexresized_videos_groupedrG   stacked_videosresized_videosprocessed_videos_groupedry   s                          r9   r   zBaseVideoProcessor._preprocessv  sT   $ 0EV/L/L,,!#%3%9%9%;%; 	; 	;!E> E!%!4!4^!D!D [!%^$QY!Z!Z,:"5))'(>@TUU 0E^/T/T,,#% %3%9%9%;%; 	= 	=!E> M!%!1!1.)!L!L!77
NL*V_ N /=$U++)*BDXYY"79I!JXfggggr:   mainpretrained_model_name_or_path	cache_dirforce_downloadlocal_files_onlytokenrevisionc                 v    ||d<   ||d<   ||d<   ||d<   |||d<    | j         |fi |\  }} | j        |fi |S )aK  
        Instantiate a type of [`~video_processing_utils.VideoProcessorBase`] from an video processor.

        Args:
            pretrained_model_name_or_path (`str` or `os.PathLike`):
                This can be either:

                - a string, the *model id* of a pretrained video hosted inside a model repo on
                  huggingface.co.
                - a path to a *directory* containing a video processor file saved using the
                  [`~video_processing_utils.VideoProcessorBase.save_pretrained`] method, e.g.,
                  `./my_model_directory/`.
                - a path to a saved video processor JSON *file*, e.g.,
                  `./my_model_directory/video_preprocessor_config.json`.
            cache_dir (`str` or `os.PathLike`, *optional*):
                Path to a directory in which a downloaded pretrained model video processor should be cached if the
                standard cache should not be used.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force to (re-)download the video processor files and override the cached versions if
                they exist.
            proxies (`dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, e.g., `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}.` The proxies are used on each request.
            token (`str` or `bool`, *optional*):
                The token to use as HTTP bearer authorization for remote files. If `True`, or not specified, will use
                the token generated when running `hf auth login` (stored in `~/.huggingface`).
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, or a commit id, since we use a
                git-based system for storing models and other artifacts on huggingface.co, so `revision` can be any
                identifier allowed by git.


                <Tip>

                To test a pull request you made on the Hub, you can pass `revision="refs/pr/<pr_number>"`.

                </Tip>

            return_unused_kwargs (`bool`, *optional*, defaults to `False`):
                If `False`, then this function returns just the final video processor object. If `True`, then this
                functions returns a `Tuple(video_processor, unused_kwargs)` where *unused_kwargs* is a dictionary
                consisting of the key/value pairs whose keys are not video processor attributes: i.e., the part of
                `kwargs` which has not been used to update `video_processor` and is otherwise ignored.
            subfolder (`str`, *optional*, defaults to `""`):
                In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
                specify the folder name here.
            kwargs (`dict[str, Any]`, *optional*):
                The values in kwargs of any keys which are video processor attributes will be used to override the
                loaded values. Behavior concerning key/value pairs whose keys are *not* video processor attributes is
                controlled by the `return_unused_kwargs` keyword parameter.

        Returns:
            A video processor of type [`~video_processing_utils.ImagVideoProcessorBase`].

        Examples:

        ```python
        # We can't instantiate directly the base class *VideoProcessorBase* so let's show the examples on a
        # derived class: *LlavaOnevisionVideoProcessor*
        video_processor = LlavaOnevisionVideoProcessor.from_pretrained(
            "llava-hf/llava-onevision-qwen2-0.5b-ov-hf"
        )  # Download video_processing_config from huggingface.co and cache.
        video_processor = LlavaOnevisionVideoProcessor.from_pretrained(
            "./test/saved_model/"
        )  # E.g. video processor (or model) was saved using *save_pretrained('./test/saved_model/')*
        video_processor = LlavaOnevisionVideoProcessor.from_pretrained("./test/saved_model/video_preprocessor_config.json")
        video_processor = LlavaOnevisionVideoProcessor.from_pretrained(
            "llava-hf/llava-onevision-qwen2-0.5b-ov-hf", do_normalize=False, foo=False
        )
        assert video_processor.do_normalize is False
        video_processor, unused_kwargs = LlavaOnevisionVideoProcessor.from_pretrained(
            "llava-hf/llava-onevision-qwen2-0.5b-ov-hf", do_normalize=False, foo=False, return_unused_kwargs=True
        )
        assert video_processor.do_normalize is False
        assert unused_kwargs == {"foo": False}
        ```r   r   r   r   Nr   )get_video_processor_dict	from_dict)	clsr   r   r   r   r   r   r1   video_processor_dicts	            r9   from_pretrainedz"BaseVideoProcessor.from_pretrained  s{    n ({#1 %5!"%z#F7O'Cs'CDa'l'lek'l'l$fs}1<<V<<<r:   save_directorypush_to_hubc           	         t           j                            |          rt          d| d          t          j        |d           |r}|                    dd          }|                    d|                    t           j        j                  d                   }t          |fd	di|j	        }| 
                    |          }| j        t          | || 
           t           j                            |t                    }|                     |           t                               d|            |r-|                     |||||                    d                     |gS )aq  
        Save an video processor object to the directory `save_directory`, so that it can be re-loaded using the
        [`~video_processing_utils.VideoProcessorBase.from_pretrained`] class method.

        Args:
            save_directory (`str` or `os.PathLike`):
                Directory where the video processor JSON file will be saved (will be created if it does not exist).
            push_to_hub (`bool`, *optional*, defaults to `False`):
                Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
                repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
                namespace).
            kwargs (`dict[str, Any]`, *optional*):
                Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
        zProvided path (z#) should be a directory, not a fileT)exist_okcommit_messageNrepo_idr   )configzVideo processor saved in r   )r   r   )ospathisfileAssertionErrormakedirsr   splitsepr   r   _get_files_timestamps_auto_classr
   joinr   to_json_fileloggerinfo_upload_modified_filesget)r7   r   r   r1   r   r   files_timestampsoutput_video_processor_files           r9   save_pretrainedz"BaseVideoProcessor.save_pretrained  sw    7>>.)) 	h !f>!f!f!fggg
NT2222 	J#ZZ(8$??NjjN,@,@,M,Mb,QRRG!'CCDCFCCKG#99.II 't^DAAAA ')gll>CW&X&X#5666M0KMMNNN 	'' -jj)) (    ,,,r:   c                    |                     dd          |                     dd          |                     dd          |                     dd          |                     dd          |                     dd          |                     d	d
          |                     dd          }|                     dd          }d|d||d<   t                      rst                              d           dt	                    t
          j                                      }t
          j                                      r}d}d}nt          }	 t          t          d          }f
d|t          fD             }	|	r|	d         nd}n1# t          $ r  t          $ r t          d d d| d          w xY wd}
|t          |          }d|v r|d         }
||
t          |          }
|
t          d d d| d          |rt                              d|            n t                              d| d|            |
|fS )a  
        From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a
        video processor of type [`~video_processing_utils.VideoProcessorBase`] using `from_dict`.

        Parameters:
            pretrained_model_name_or_path (`str` or `os.PathLike`):
                The identifier of the pre-trained checkpoint from which we want the dictionary of parameters.
            subfolder (`str`, *optional*, defaults to `""`):
                In case the relevant files are located inside a subfolder of the model repo on huggingface.co, you can
                specify the folder name here.

        Returns:
            `tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the video processor object.
        r   Nr   Fproxiesr   r   r   	subfolder _from_pipeline
_from_autovideo processor)	file_typefrom_auto_classusing_pipelinez+Offline mode: forcing local_files_only=TrueT
filenamer   r   r   r   r   
user_agentr   r   %_raise_exceptions_for_missing_entriesc                 N   
 g | ]!}t          |
	d           x	 "S )Fr   r   )r]   r   r   r   r   r   r   resolved_filer   r   r   r   s     r9   r_   z?BaseVideoProcessor.get_video_processor_dict.<locals>.<listcomp>s  sm     2 2 2 )49%-&/+9$+-="''1%-&/BG* * *     "     r:   r   z Can't load video processor for 'z'. If you were trying to load it from 'https://huggingface.co/models', make sure you don't have a local directory with the same name. Otherwise, make sure 'z2' is the correct path to a directory containing a z filevideo_processorzloading configuration file z from cache at )r   r   r   r   strr   r   isdirr   r   r   r   r   OSError	Exceptionr   )r   r   r1   from_pipeliner   is_localresolved_video_processor_fileresolved_processor_filevideo_processor_fileresolved_video_processor_filesr   processor_dictr   r   r   r   r   r   r   r   r   s    `          @@@@@@@@@r9   r   z+BaseVideoProcessor.get_video_processor_dict6  s   $ JJ{D11	$4e<<**Y--

7D))!::&8%@@::j$//JJ{B//	

#3T:: **\599#4YY
$+8J'( 	$%5 	$KKEFFF#(+,I(J(J%7==!>??7>>788 8	,I)&*#HH#7 2 +61+'#1#%5)%':?+ + +'2 2 2 2 2 2 2 2 2 2 2 2 2%9;O$P2 2 2.* :Xa2155]a .-        K7T K K9VK K 0DK K K    $".01HIIN N22'56G'H$(49M9U#67T#U#U 'G3P G G5RG G ,@G G G    	KKU6SUUVVVVKKr.BrrSprr   $V++s   %A	F/ /.Gr   c           	      ~    |                                 }|                    dd          }|                     fd|                                D                          d	i |}g }t	          t          |                                                    D ]Z}t          ||          rH| j        j	        vr:t          |||                    |d                     |                    |           [|r&t                              d j         d| d           t                              d|            |r||fS |S )
a  
        Instantiates a type of [`~video_processing_utils.VideoProcessorBase`] from a Python dictionary of parameters.

        Args:
            video_processor_dict (`dict[str, Any]`):
                Dictionary that will be used to instantiate the video processor object. Such a dictionary can be
                retrieved from a pretrained checkpoint by leveraging the
                [`~video_processing_utils.VideoProcessorBase.to_dict`] method.
            kwargs (`dict[str, Any]`):
                Additional parameters from which to initialize the video processor object.

        Returns:
            [`~video_processing_utils.VideoProcessorBase`]: The video processor object instantiated from those
            parameters.
        return_unused_kwargsFc                 8    i | ]\  }}|j         j        v ||S r4   )r   r   )r]   kvr   s      r9   
<dictcomp>z0BaseVideoProcessor.from_dict.<locals>.<dictcomp>  s/    $n$n$ndaSM]MmHmHmQHmHmHmr:   NzImage processor z	: kwargs z were applied for backward compatibility. To avoid this warning, add them to valid_kwargs: create a custom TypedDict extending ImagesKwargs with these keys and set it as the `valid_kwargs` class attribute.zVideo processor r4   )copyr   updater   reversedrh   r   hasattrr   r   setattrrf   r   warning_once__name__r   )r   r   r1   r   r   
extra_keyskeys   `      r9   r   zBaseVideoProcessor.from_dict  sx   "  488::%zz*@%HH##$n$n$n$nfllnn$n$n$nooo#55 455 
D//00 	' 	'C,, 'C<L<\1\1\fjjd.C.CDDD!!#&&& 	b3< b b* b b b   	888999 	#"F**""r:   c                     t                                                      }|                    dd           | j        j        |d<   |S )z
        Serializes this instance to a Python dictionary.

        Returns:
            `dict[str, Any]`: Dictionary of all the attributes that make up this video processor instance.
        image_processor_typeNvideo_processor_type)r5   to_dictr   r8   r   )r7   filtered_dictr8   s     r9   r   zBaseVideoProcessor.to_dict  sE     ))0$777040G,-r:   c                     |                                  }|                                D ]6\  }}t          |t          j                  r|                                ||<   7t          j        |dd          dz   S )z
        Serializes this instance to a JSON string.

        Returns:
            `str`: String containing all the attributes that make up this feature_extractor instance in JSON format.
        rq   T)indent	sort_keys
)r   r   rg   rr   rs   tolistjsondumps)r7   
dictionaryr   values       r9   to_json_stringz!BaseVideoProcessor.to_json_string  sr     \\^^
$**,, 	1 	1JC%,, 1"',,..
3z*Q$???$FFr:   json_file_pathc                     t          |dd          5 }|                    |                                            ddd           dS # 1 swxY w Y   dS )z
        Save this instance to a JSON file.

        Args:
            json_file_path (`str` or `os.PathLike`):
                Path to the JSON file in which this image_processor instance's parameters will be saved.
        wutf-8encodingN)openwriter  )r7   r  writers      r9   r   zBaseVideoProcessor.to_json_file  s     .#888 	0FLL,,..///	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0s   (AAAc                 H    | j         j         d|                                  S )N )r8   r   r  )r7   s    r9   __repr__zBaseVideoProcessor.__repr__  s'    .)CCD,?,?,A,ACCCr:   	json_filec                     t          |dd          5 }|                                }ddd           n# 1 swxY w Y   t          j        |          } | di |S )a  
        Instantiates a video processor of type [`~video_processing_utils.VideoProcessorBase`] from the path to a JSON
        file of parameters.

        Args:
            json_file (`str` or `os.PathLike`):
                Path to the JSON file containing the parameters.

        Returns:
            A video processor of type [`~video_processing_utils.VideoProcessorBase`]: The video_processor object
            instantiated from that JSON file.
        rr  r	  Nr4   )r  readr   loads)r   r  readertextr   s        r9   from_json_filez!BaseVideoProcessor.from_json_file  s     )S7333 	!v;;==D	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	!#z$//s**)***s   488AutoVideoProcessorc                     t          |t                    s|j        }ddlmc m} t          ||          st          | d          || _        dS )a	  
        Register this class with a given auto class. This should only be used for custom video processors as the ones
        in the library are already mapped with `AutoVideoProcessor `.

        <Tip warning={true}>

        This API is experimental and may have some slight breaking changes in the next releases.

        </Tip>

        Args:
            auto_class (`str` or `type`, *optional*, defaults to `"AutoVideoProcessor "`):
                The auto class to register this new video processor with.
        r   Nz is not a valid auto class.)	rg   r   r   transformers.models.automodelsautor   rO   r   )r   
auto_classauto_modules      r9   register_for_auto_classz*BaseVideoProcessor.register_for_auto_class  sn      *c** 	-#,J666666666{J// 	I
GGGHHH$r:   video_url_or_urlsc                      d}t                      st          j        d           d}t          |t                    r#t	          t           fd|D                        S t          ||          S )z
        Convert a single or a list of urls into the corresponding `np.array` objects.

        If a single url is passed, the return value will be a single object. If a list is passed a list of objects is
        returned.
        
torchcodecz`torchcodec` is not installed and cannot be used to decode the video by default. Falling back to `torchvision`. Note that `torchvision` decoding is deprecated and will be removed in future versions. r,   c                 >    g | ]}                     |           S )rc   )rj   )r]   xrX   r7   s     r9   r_   z3BaseVideoProcessor.fetch_videos.<locals>.<listcomp>D  s.    sss\]d//EV/WWsssr:   )backendrX   )r   warningswarnrg   rh   rd   r&   )r7   r!  rX   r&  s   ` ` r9   rj   zBaseVideoProcessor.fetch_videos4  s     &(( 	$MI   $G'.. 	gsssssarssstuuu/Teffffr:   )NNr<   )NFFNr   )F)r  )Br   
__module____qualname__r   r   r   r   r   size_divisordefault_to_squarer   r   r   r   r   r   r   rW   rM   rL   rV   r   r   r   model_input_namesr   r6   r   r?   r!   rJ   r"   rQ   floatrU   dictboolr   rh   rm   r   r   rz   r   BASE_VIDEO_PROCESSOR_DOCSTRINGr=   r   r   r   classmethodr   PathLiker   r   tupler   r   r   r   r  r   r  r  r   rj   __classcell__)r8   s   @r9   r/   r/      s        KHJIDLIINJNLN
CJNOL./#!5 #$ # # # # # #1L 1 1 1 1 
   8 "&"&	3 33 $J3 5[4	3 3 3 3r )--1&& &&&& &,&& +	&&
 $d?&& 
n	&& && && &&V <@!	     !11D8  d
	 
 
n	       : & *#*# &*# 
	*# *# *# *#t 37+h +h^$+h +h 	+h
 +h L+h +h +h +h +h +h DK'$.+h 4;&-+h j(4/+h  
!+h +h +h +hZ  /3$!&#'`= `='*R['8`= $t+`= 	`=
 `= TzD `= `= `= `= [`=D.- .-cBK.? .-d .- .- .- .-` {,,/"+,={,	tCH~tCH~-	.{, {, {, [{,z &#T#s(^ &# &# &# [&#Pc3h      G G G G G	03+< 	0 	0 	0 	0D D D +sR['8 + + + [+$ % % % [%2g gcDIoT#Y.O g g g g g g g gr:   r/   r   r  zvideo processor file)objectobject_classobject_files)Gr   r   r'  collections.abcr   	functoolsr   typingr   numpyrr   huggingface_hubr   r   huggingface_hub.dataclassesr   dynamic_module_utilsr
   image_processing_backendsr   image_processing_utilsr   image_utilsr   r   r   r   processing_utilsr   r   utilsr   r   r   r   r   r   r   r   r   r   r   	utils.hubr   utils.import_utilsr    video_utilsr!   r"   r#   r$   r%   r&   r'   r(   r)   rR   $torchvision.transforms.v2.functional
transformsv2
functionalrE   r*   
get_loggerr   r   r1  r/   r   __doc__formatr4   r:   r9   <module>rO     s    				  $ $ $ $ $ $                 8 8 8 8 8 8 8 8 ; ; ; ; ; ; 4 4 4 4 4 4 9 9 9 9 9 9 0 0 0 0 0 0            3 2 2 2 2 2 2 2                          # " " " " " ( ( ( ( ( (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
  LLL   7666666666666 0////// 
	H	%	%A" H '"  
,---p
g p
g p
g p
g p
g+ p
g p
g .-	 
p
gf "++=+I!J!J  !)5-?-K-S-Z-Z /CRh .[ . ."*** 65r:   