
    rh                        d dl Z d dlZd dlZd dlmZ d dlmZmZmZ d dl	Z
ddlmZ ddlmZmZ ddlmZ ddl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$m%Z%m&Z& ddl'm(Z( ddl)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0  e%       rddlm1Z1  e"       rd dl2Z2 e#       rddlm3Z3  e$       rd dl4m5Z6 nd dl7m5Z6  e&jp                  e9      Z:dZ; ede;       e(d       G d de                    Z< ee<jz                        e<_=        e<jz                  j|                  8e<jz                  j|                  j                  ddd      e<jz                  _>        yy)    N)deepcopy)AnyOptionalUnion   )custom_object_save)BatchFeatureget_size_dict)BaseImageProcessorFast)ChannelDimensionSizeDictvalidate_kwargs)UnpackVideosKwargs)VIDEO_PROCESSOR_NAME
TensorTypeadd_start_docstringscached_file	copy_funcdownload_urlis_offline_modeis_remote_urlis_torch_availableis_torchvision_availableis_torchvision_v2_availableis_vision_availablelogging)requires)
VideoInputVideoMetadatagroup_videos_by_shape
load_videomake_batched_videosreorder_videosto_channel_dimension_format)PILImageResampling)pil_torch_interpolation_mapping)
functionala  
    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.
        do_pad (`bool`, *optional*):
            Whether to pad the video to the `(max_height, max_width)` of the videos in the batch.
        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.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	 	 	 d>d	d
dee e!e"f      dee#   dee e#e$f      fdZ%	 	 d?dede!dee e&e'f      de(d
   fdZ) e*e+      dedee   defd       Z,	 	 	 	 	 d@de(d
   de e(e!   e(e"   f   de-de-de.dee#   ded   de-de.de-de-de$d e-d!ee e$e(e$   f      d"ee e$e(e$   f      d#ee-   dee e#e$f      dee#   d$ee e&e/f      d%ed
   def*d&Z0e1	 	 	 	 	 dAd'e e&e2jf                  f   d(ee e&e2jf                  f      d)e-d*e-d+ee e&e-f      d,e&fd-       Z4dBd.e e&e2jf                  f   d/e-fd0Z5e1d'e e&e2jf                  f   de6e"e&e7f   e"e&e7f   f   fd1       Z8e1d2e"e&e7f   fd3       Z9de"e&e7f   fd4Z:de&fd5Z;d6e e&e2jf                  f   fd7Z<d8 Z=e1d9e e&e2jf                  f   fd:       Z>e1dCd;       Z?d<e e&e(e&   f   fd=Z@ xZAS )DBaseVideoProcessorNTgp?pixel_values_videoskwargsreturnc                    t         |           |j                  dd       | _        |j	                         D ]  \  }}	 t        | ||        |j                  d| j                        }|'t        ||j                  d| j                              nd | _	        |j                  d| j                        }|t        |d	      nd | _        t        | j                  j                  j!                               | _        | j"                  D ]E  }|j%                  |      t        | |||          %t        | |t'        t)        | |d                    G y # t        $ r%}t        j                  d| d| d|         |d }~ww xY w)
Nprocessor_classz
Can't set z with value z for sizedefault_to_square)r3   r4   	crop_size)
param_name)super__init__pop_processor_classitemssetattrAttributeErrorloggererrorr3   r
   r4   r5   listvalid_kwargs__annotations__keysmodel_valid_processing_keysgetr   getattr)selfr/   keyvalueerrr3   r5   	__class__s          v/var/www/html/ai-insurance-compliance-backend/venv/lib/python3.12/site-packages/transformers/video_processing_utils.pyr8   zBaseVideoProcessor.__init__   sj    &

+<d C !,,. 	JCc5)	 zz&$)),  tvzzBUW[WmWm7no 		
 JJ{DNN;	MVMby[Ihl ,00A0A0Q0Q0V0V0X+Y(33 	GCzz#*c6#;/c8GD#t,D#EF		G! " z#l5'tfMN	s   E	F  E;;F c                 (     | j                   |fi |S )N)
preprocess)rG   videosr/   s      rL   __call__zBaseVideoProcessor.__call__   s    tv000    videoztorch.Tensorc                    t        j                  |      }|j                  d   dk(  s|ddddddf   dk  j                         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   )Fgrayscale_to_rgbshapeany)rG   rR   alphas      rL   convert_to_rgbz!BaseVideoProcessor.convert_to_rgb   s     ""5);;r?ac1al(;c(A'F'F'HL c1al#e+U3a?++s2U3a?5KeTWY[Z[Y[]^`aTaNb5bbrQ   metadata
num_framesfpsc                    ||t        d      ||n| j                  }||n| j                  }|j                  d   }|#|!|t        d      t	        ||d   z  |z        }||kD  rt        d| d| d      |)t        j                  d|||z        j	                         }n$t        j                  d|      j	                         }||   j                         }|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:
            video (`torch.Tensor`):
                Video that need to be sampled.
            metadata (`VideoMetadata`, *optional*):
                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:
            torch.Tensor:
                Sampled video frames.
        zc`num_frames`, `fps`, and `sample_indices_fn` are mutually exclusive arguments, please use only one!r   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 videor_   z(Video can't be sampled. The `num_frames=z` exceeds `total_num_frames=z`. )
ValueErrorr^   r_   rY   inttorcharange
contiguous)rG   rR   r]   r^   r_   total_num_framesindicess          rL   sample_framesz BaseVideoProcessor.sample_frames   s   4 ?z5u  $.#9Zt
_c$(( ;;q> #/ h  -?#EFJ((::,Fbcsbttwx  !ll1&68H:8UVZZ\Gll1&67;;=Gg))+rQ   rO   video_metadatainput_data_formatc                 d   t        |      }||D cg c]  }|D ]  }|  }}}ndgt        |      z  }g }|D ]k  }t        |t        j                        r>t        |t        j                  |      }t        j                  |      j                         }|j                  |       m ||fS c c}}w )z:
        Prepare the input videos for processing.
        N)r#   len
isinstancenpndarrayr%   r   FIRSTrc   
from_numpyre   append)	rG   rO   ri   rj   
batch_listr]   batch_metadataprocessed_videosrR   s	            rL   _prepare_input_videosz(BaseVideoProcessor._prepare_input_videos$  s     %V,%9Gc:XbcHhchcNc"Vc&k1N 	+E%,3E;K;Q;QSde((/::<##E*	+  // ds   B,c           	         t        |j                         t        | j                  j                  j                               dgz          | j                  j                  D ]  }|j                  |t        | |d              ! |j                  d      }|j                  d      }| j                  |||      \  }} | j                  di |} | j                  di | |j                  d      }t        |t        t        f      r	t        |   n||d<   |j                  d       |j                  d	        | j                  d||d
|S )Nreturn_tensors)captured_kwargsvalid_processor_keysrj   ri   )rO   ri   rj   resampleinterpolationr4   data_format)rO   ri    )r   rC   r@   rA   rB   
setdefaultrF   r9   rv   _further_process_kwargs_validate_preprocess_kwargsrm   r&   rb   r'   _preprocess)rG   rO   r/   
kwarg_namerj   ri   r{   s          rL   rN   zBaseVideoProcessor.preprocess>  sO    	"KKM!%d&7&7&G&G&L&L&N!OScRd!d	
 ++;; 	KJj'$
D*IJ	K #JJ':;$45!%!;!;.L] "< "
 .--77(((262 ::j)9CHOacfNg9h+H5nv 	
 	

&'

=!tWvnWPVWWrQ   do_convert_rgb	do_resizer3   size_divisorr|   zF.InterpolationModedo_center_cropr5   
do_rescaledo_padrescale_factordo_normalize
image_mean	image_stddo_sample_framesrx   devicec           
         |r1t        ||      D cg c]  \  }}| j                  ||||       }}}||D cg c]  }|j                  |       }}t        |      \  }}i }|j	                         D ]4  \  }}|r| j                  |      }|r| j                  ||||      }|||<   6 t        ||      }t        |      \  }}i }|j	                         D ]4  \  }}|r| j                  ||	      }| j                  ||
||||      }|||<   6 t        ||      }|rt        j                  |d      n|}t        d|i|      S c c}}w c c}w )N)r]   r^   r_   )r3   r   r|   r   )dimr.   )datatensor_type)ziprh   tor!   r;   r\   resizer$   center_croprescale_and_normalizerc   stackr	   )rG   rO   ri   r   r   r3   r   r|   r   r5   r   r   r   r   r   r   r   r_   r^   rx   r   rR   r]   grouped_videosgrouped_videos_indexresized_videos_groupedrY   stacked_videosresized_videosprocessed_videos_groupedru   s                                  rL   r   zBaseVideoProcessor._preprocessb  s   .  (+6>'B#E8 ""58
X["\F  4:;5ehhv&;F; 0EV/L,,!#%3%9%9%; 	;!E>!%!4!4^!D!%"LXe "- " -;"5)	; ((>@TU 0E^/T,,#% %3%9%9%; 	=!E>!%!1!1.)!L!77
NL*V_N /=$U+	= **BDXYCQ5;;'7Q?Wg"79I!JXfggO <s
   EE
pretrained_model_name_or_path	cache_dirforce_downloadlocal_files_onlytokenrevisionc                    ||d<   ||d<   ||d<   ||d<   |j                  dd      }|)t        j                  dt               |t	        d      |}|||d	<    | j
                  |fi |\  }	} | j                  |	fi |S )
a  
        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 or url to a saved video processor JSON *file*, e.g.,
                  `./my_model_directory/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.
            resume_download:
                Deprecated and ignored. All downloads are now resumed by default when possible.
                Will be removed in v5 of Transformers.
            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/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   use_auth_tokenNrThe `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.V`token` and `use_auth_token` are both specified. Please set only the argument `token`.r   )r9   warningswarnFutureWarningra   get_video_processor_dict	from_dict)
clsr   r   r   r   r   r   r/   r   video_processor_dicts
             rL   from_pretrainedz"BaseVideoProcessor.from_pretrained  s    t ({#1 %5!"%z$4d;%MM E   l  #E#F7O'Cs'C'CDa'lek'l$fs}}1<V<<rQ   save_directorypush_to_hubc           	      4   |j                  dd      }|;t        j                  dt               |j	                  d      t        d      ||d<   t        j                  j                  |      rt        d| d      t        j                  |d	       |rr|j                  d
d      }|j                  d|j                  t        j                  j                        d         } | j                  |fi |}| j                  |      }| j                  t!        | ||        t        j                  j#                  |t$              }| j'                  |       t(        j+                  d|        |r%| j-                  ||j	                  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.
        r   Nr   r   r   zProvided path (z#) should be a directory, not a fileT)exist_okcommit_messagerepo_id)configzVideo processor saved in )r   r   )r9   r   r   r   rE   ra   ospathisfileAssertionErrormakedirssplitsep_create_repo_get_files_timestamps_auto_classr   joinr   to_json_filer>   info_upload_modified_files)	rG   r   r   r/   r   r   r   files_timestampsoutput_video_processor_files	            rL   save_pretrainedz"BaseVideoProcessor.save_pretrained  s     $4d;%MM E zz'". l  -F7O77>>.) ?>2BBe!fgg
NT2#ZZ(8$?NjjN,@,@,Mb,QRG'd'':6:G#99.I 't^DA ')ggll>CW&X#56/0K/LMN'' -jj) (  ,,,rQ   c                 n   |j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  dd      }|j                  d	d      }	|j                  d
d      }
|j                  dd      }|j                  dd      }|j                  dd      }|)t        j                  dt               |t	        d      |}d|d}|||d<   t               r|	st        j                  d       d}	t        |      }t        j                  j                  |      }t        j                  j                  |      r|}d}n6t        |      r|}t        |      }n	 t        }t!        |||||||	|||
|      }	 t)        |dd      5 }|j+                         }ddd       t-        j.                        }|rt        j                  d"|        ||fS t        j                  d" d#|        ||fS # t"        $ r0 d}t!        |||||||	|||
|      }t        j%                  d       Y t"        $ r  t&        $ r t#        d| d| dt         d      w xY w# 1 sw Y   xY w# t,        j0                  $ r t#        d | d!      w xY w)$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resume_downloadproxiesr   r   r   r   	subfolder _from_pipeline
_from_autor   r   video processor)	file_typefrom_auto_classusing_pipelinez+Offline mode: forcing local_files_only=TrueT)	r   r   r   r   r   r   
user_agentr   r   zpreprocessor_config.jsonaA  You have video processor config saved in `preprocessor.json` file which is deprecated. Video processor configs should be saved in their own `video_preprocessor.json` file. You can rename the file or load and save the processor back which renames it automatically. Loading from `preprocessor.json` will be removed in v5.0.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rutf-8encodingz"It looks like the config file at 'z' is not a valid JSON file.zloading configuration file z from cache at )r9   r   r   r   ra   r   r>   r   strr   r   isdirr   r   r   r   r   OSErrorwarning_once	ExceptionopenreadjsonloadsJSONDecodeError)r   r   r/   r   r   r   r   r   r   r   r   r   from_pipeliner   r   is_localresolved_video_processor_filevideo_processor_filereadertextr   s                        rL   r   z+BaseVideoProcessor.get_video_processor_dictS  s.   $ JJ{D1	$4e< **%6=**Y-

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

#3T: **\59%MM E   l  #E#4Y
$+8J'(%5KKEF#(+,I(J%77==!>?77>>78,I)H89#@ ,89V,W)2 (<$0;1('#1#$3%5)%'1-^		3S7K %v{{}%#'::d#3  KK56S5TUV
 $V++ KK-.B-C?SpRqr $V++g  'A$0;1('#1#$3%5)%'1- ##P    67T6U V99V8W X//C.DEK % % ## 	45R4SSno 	s6   	H &J 4JJ 6J+JJ
J #J4r   c                    |j                         }|j                  dd      }d|v rd|v r|j                  d      |d<   d|v rd|v r|j                  d      |d<    | di |}g }|j                         D ]0  \  }}t        ||      st	        |||       |j                  |       2 |D ]  }|j                  |d        t        j                  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_kwargsFr3   r5   NzVideo processor r~   )copyr9   r;   hasattrr<   rr   r>   r   )r   r   r/   r   video_processor	to_removerH   rI   s           rL   r   zBaseVideoProcessor.from_dict  s   "  488:%zz*@%H
 V*> >+1::f+= (& [4H%H06

;0G -5 45 	 ,,. 	&JC,e4  %	&  	"CJJsD!	" 	&&789"F**""rQ   c                     t        | j                        }|j                  dd       |j                  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.
        rD   N_valid_kwargs_namesvideo_processor_type)r   __dict__r9   rK   __name__)rG   outputs     rL   to_dictzBaseVideoProcessor.to_dict  sJ     $--(

0$7

($/)-)@)@%&rQ   c                    | j                         }|j                         D ]3  \  }}t        |t        j                        s!|j                         ||<   5 |j                  dd      }|||d<   t        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.
        r:   Nr2      T)indent	sort_keys
)	r   r;   rm   rn   ro   tolistr9   r   dumps)rG   
dictionaryrH   rI   r:   s        rL   to_json_stringz!BaseVideoProcessor.to_json_string  s     \\^
$**, 	1JC%,"',,.
3	1 &>>*<dC',<J()zz*Q$?$FFrQ   json_file_pathc                     t        |dd      5 }|j                  | j                                ddd       y# 1 sw Y   yxY w)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.
        wr   r   N)r   writer   )rG   r  writers      rL   r   zBaseVideoProcessor.to_json_file%  s<     .#8 	0FLL,,./	0 	0 	0s	    8Ac                 T    | j                   j                   d| j                          S )N )rK   r   r   )rG   s    rL   __repr__zBaseVideoProcessor.__repr__0  s(    ..))*!D,?,?,A+BCCrQ   	json_filec                     t        |dd      5 }|j                         }ddd       t        j                        } | di |S # 1 sw Y   &xY w)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.
        r   r   r   Nr~   )r   r   r   r   )r   r	  r   r   r   s        rL   from_json_filez!BaseVideoProcessor.from_json_file3  sP     )S73 	!v;;=D	!#zz$/*)**	! 	!s   AAc                     t        |t              s|j                  }ddlmc m} t        ||      st        | d      || _        y)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.)	rm   r   r   transformers.models.automodelsautor   ra   r   )r   
auto_classauto_modules      rL   register_for_auto_classz*BaseVideoProcessor.register_for_auto_classF  sC      *c*#,,J66{J/
|+FGHH$rQ   video_url_or_urlsc                     t        |t              r|D cg c]  }| j                  |       c}S t        |t              rt	        |      S t        dt        |             c c}w )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.
        z=only a single or a list of entries is supported but got type=)rm   r@   fetch_videosr   r"   	TypeErrortype)rG   r  xs      rL   r  zBaseVideoProcessor.fetch_videos`  sc     '.2CDQD%%a(DD)3//00[\`ar\s[tuvv	 Es   A")NNN)NN)NNNNN)NFFNmain)F)AutoVideoProcessor)Br   
__module____qualname__r   r{   r   r   r3   r   r4   r5   r   r   r   r   r   r   r   r   r_   r^   ri   r   rA   model_input_namesr   r8   r	   rP   r   r\   r   r   r    dictrb   floatrh   r   r   r@   rv   r   BASE_VIDEO_PROCESSOR_DOCSTRINGrN   boolr   r   r   classmethodr   PathLiker   r   tupler   r   r   r   r   r   r  r  r  r  __classcell__)rK   s   @rL   r-   r-      s    KHJIDLIINFJNLN
CJNL./G!5 G$ G>1L 1 
8 :>$(+/77 5!4567 SM	7
 eCJ'(7x )-DH	00 &0 $E#/?*?$@A	0
 
n	04 89!X!X &!X 
	!X :!Xh ,0+/$(;?+/+@h^$@h d=14:=>@h 	@h
 @h @h sm@h   56@h @h @h @h @h @h @h U5$u+#567@h  E%e"456!@h" #4.#@h$ eCJ'(%@h& SM'@h( !sJ!78)@h* (+@h, 
-@hD  8<$!&,0o=',S"++-='>o= E#r{{"234o= 	o=
 o= c4i()o= o= o=b;-eC4D.E ;-TX ;-z ,,1#r{{2B,C,	tCH~tCH~-	., ,B *#T#s(^ *# *#Xc3h G G*	05bkk1A+B 	0D +uS"++-='> + +$ % %2weCcN.C wrQ   r-   r   r  zvideo processor file)objectobject_classobject_files)@r   r   r   r   r   typingr   r   r   numpyrn   dynamic_module_utilsr   image_processing_utilsr	   r
   image_processing_utils_fastr   image_utilsr   r   r   processing_utilsr   r   utilsr   r   r   r   r   r   r   r   r   r   r   r   r   utils.import_utilsr   video_utilsr   r    r!   r"   r#   r$   r%   r&   rc   r'   torchvision.transforms.v2r(   rW   torchvision.transforms
get_loggerr   r>   r   r-   r   __doc__formatr~   rQ   rL   <module>r8     sH     	   ' '  4 @ 
 3    )   /<"$=:			H	%@"l F '" 
,-Tw/ Tw .	
Twn "++=+I+I!J  !!))5-?-K-K-S-S-Z-Z /CRh .[ .""* 6rQ   