U
    di9                  
   @   s  d Z ddlZddlZddlZddlZ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mZmZmZmZ ddlZddlZddlmZ ddlmZmZmZ e rddlmZ dd	lmZmZmZ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. e./e0Z1e*e	e2j3Z4ddddZ5ej6dkr>ej7Z7nej7Z7G dd deddZ8G dd deddZ9G dd deddZ:G dd deddZ;G dd deddZ<G dd de8e9e:e;e<ddZ=G dd de$Z>d d! Z?e)e>j@e>_@e>j@j dk	re>j@j jAd"d#d$d%e>j@_ dS )&z8
Processing saving/loading class for common processors.
    N)Path)AnyDictListOptionalTuple	TypedDictUnion   )custom_object_save)ChannelDimensionis_valid_imageis_vision_available)PILImageResampling)PaddingStrategyPreTokenizedInputPreTrainedTokenizerBase	TextInputTruncationStrategy)CHAT_TEMPLATE_NAMEPROCESSOR_NAMEPushToHubMixin
TensorTypeadd_model_info_to_auto_map"add_model_info_to_custom_pipelinescached_file	copy_funcdirect_transformers_importdownload_urlis_offline_modeis_remote_urlloggingr   ZFeatureExtractionMixinZImageProcessingMixin)ZAutoTokenizerZAutoFeatureExtractorZAutoImageProcessor)      c                   @   s.  e Zd ZU dZeeeeee ee f  e	d< eeeee ee f e	d< eeeeee ee f  e	d< ee
 e	d< ee
eef e	d< ee
eef e	d< ee e	d< ee e	d	< ee
 e	d
< ee e	d< ee
 e	d< ee
 e	d< ee
 e	d< ee
 e	d< ee
 e	d< ee
 e	d< ee
 e	d< ee e	d< dS )
TextKwargsa  
    Keyword arguments for text processing. For extended documentation, check out tokenization_utils_base methods and
    docstrings associated.

    Attributes:
        add_special_tokens (`bool`, *optional*)
            Whether or not to add special tokens when encoding the sequences.
        padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*)
            Activates and controls padding.
        truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*):
            Activates and controls truncation.
        max_length (`int`, *optional*):
            Controls the maximum length to use by one of the truncation/padding parameters.
        stride (`int`, *optional*):
            If set, the overflowing tokens will contain some tokens from the end of the truncated sequence.
        is_split_into_words (`bool`, *optional*):
            Whether or not the input is already pre-tokenized.
        pad_to_multiple_of (`int`, *optional*):
            If set, will pad the sequence to a multiple of the provided value.
        return_token_type_ids (`bool`, *optional*):
            Whether to return token type IDs.
        return_attention_mask (`bool`, *optional*):
            Whether to return the attention mask.
        return_overflowing_tokens (`bool`, *optional*):
            Whether or not to return overflowing token sequences.
        return_special_tokens_mask (`bool`, *optional*):
            Whether or not to return special tokens mask information.
        return_offsets_mapping (`bool`, *optional*):
            Whether or not to return `(char_start, char_end)` for each token.
        return_length (`bool`, *optional*):
            Whether or not to return the lengths of the encoded inputs.
        verbose (`bool`, *optional*):
            Whether or not to print more information and warnings.
        padding_side (`str`, *optional*):
            The side on which padding will be applied.
    Z	text_pairZtext_targetZtext_pair_targetZadd_special_tokenspadding
truncation
max_lengthZstrideZis_split_into_wordspad_to_multiple_ofZreturn_token_type_idsreturn_attention_maskZreturn_overflowing_tokensZreturn_special_tokens_maskZreturn_offsets_mappingZreturn_lengthverboseZpadding_sideN)__name__
__module____qualname____doc__r   r	   r   r   r   __annotations__boolstrr   r   int r3   r3   A/tmp/pip-unpacked-wheel-bm_b0l5e/transformers/processing_utils.pyr$   Q   s&   
%  r$   F)totalc                   @   s  e Zd ZU dZee ed< eeee	f  ed< ee	 ed< eeee	f  ed< ee
de	f  ed< ee ed< ee ed	< ee ed
< ee
eee f  ed< ee
eee f  ed< ee ed< eeee	f  ed< ee ed< ee ed< ee
eef  ed< dS )ImagesKwargsaW  
    Keyword arguments for image processing. For extended documentation, check the appropriate ImageProcessor
    class methods and docstrings.

    Attributes:
        do_resize (`bool`, *optional*):
            Whether to resize the image.
        size (`Dict[str, int]`, *optional*):
            Resize the shorter side of the input to `size["shortest_edge"]`.
        size_divisor (`int`, *optional*):
            The size by which to make sure both the height and width can be divided.
        crop_size (`Dict[str, int]`, *optional*):
            Desired output size when applying center-cropping.
        resample (`PILImageResampling`, *optional*):
            Resampling filter to use if resizing the image.
        do_rescale (`bool`, *optional*):
            Whether to rescale the image by the specified scale `rescale_factor`.
        rescale_factor (`int` or `float`, *optional*):
            Scale factor to use if rescaling the image.
        do_normalize (`bool`, *optional*):
            Whether to normalize the image.
        image_mean (`float` or `List[float]`, *optional*):
            Mean to use if normalizing the image.
        image_std (`float` or `List[float]`, *optional*):
            Standard deviation to use if normalizing the image.
        do_pad (`bool`, *optional*):
            Whether to pad the image to the `(max_height, max_width)` of the images in the batch.
        pad_size (`Dict[str, int]`, *optional*):
            The size `{"height": int, "width" int}` to pad the images to.
        do_center_crop (`bool`, *optional*):
            Whether to center crop the image.
        data_format (`ChannelDimension` or `str`, *optional*):
            The channel dimension format for the output image.
        input_data_format (`ChannelDimension` or `str`, *optional*):
            The channel dimension format for the input image.
    	do_resizesizesize_divisorZ	crop_sizer   resample
do_rescalerescale_factordo_normalize
image_mean	image_stddo_padZpad_sizedo_center_cropdata_formatinput_data_formatN)r+   r,   r-   r.   r   r0   r/   r   r1   r2   r	   floatr   r   r3   r3   r3   r4   r6      s    
%r6   c                   @   s   e Zd ZU dZee ed< eeee	f  ed< ee	 ed< ed ed< ee ed< ee
 ed< ee ed	< eee
ee
 f  ed
< eee
ee
 f  ed< ee ed< ee ed< ee ed< eeeef  ed< dS )VideosKwargsa  
    Keyword arguments for video processing.

    Attributes:
        do_resize (`bool`):
            Whether to resize the image.
        size (`Dict[str, int]`, *optional*):
            Resize the shorter side of the input to `size["shortest_edge"]`.
        size_divisor (`int`, *optional*):
            The size by which to make sure both the height and width can be divided.
        resample (`PILImageResampling`, *optional*):
            Resampling filter to use if resizing the image.
        do_rescale (`bool`, *optional*):
            Whether to rescale the image by the specified scale `rescale_factor`.
        rescale_factor (`int` or `float`, *optional*):
            Scale factor to use if rescaling the image.
        do_normalize (`bool`, *optional*):
            Whether to normalize the image.
        image_mean (`float` or `List[float]`, *optional*):
            Mean to use if normalizing the image.
        image_std (`float` or `List[float]`, *optional*):
            Standard deviation to use if normalizing the image.
        do_pad (`bool`, *optional*):
            Whether to pad the image to the `(max_height, max_width)` of the images in the batch.
        do_center_crop (`bool`, *optional*):
            Whether to center crop the image.
        data_format (`ChannelDimension` or `str`, *optional*):
            The channel dimension format for the output image.
        input_data_format (`ChannelDimension` or `str`, *optional*):
            The channel dimension format for the input image.
    r7   r8   r9   r   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   N)r+   r,   r-   r.   r   r0   r/   r   r1   r2   rD   r	   r   r   r3   r3   r3   r4   rE      s   
 rE   c                   @   s   e Zd ZU dZee ed< eedee	 ed eee	  f  ed< eee
eef  ed< ee ed< ee
 ed< ee ed< ee
 ed	< d
S )AudioKwargsa  
    Keyword arguments for audio processing.

    Attributes:
        sampling_rate (`int`, *optional*):
            The sampling rate at which the `raw_speech` input was sampled.
        raw_speech (`np.ndarray`, `List[float]`, `List[np.ndarray]`, `List[List[float]]`):
            The sequence or batch of sequences to be padded. Each sequence can be a numpy array, a list of float
            values, a list of numpy arrays or a list of list of float values. Must be mono channel audio, not
            stereo, i.e. single float per timestep.
        padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*):
            Select a strategy to pad the returned sequences (according to the model's padding side and padding
            index) among:

            - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single
                sequence if provided).
            - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
                acceptable input length for the model if that argument is not provided.
            - `False` or `'do_not_pad'`
        max_length (`int`, *optional*):
            Maximum length of the returned list and optionally padding length (see above).
        truncation (`bool`, *optional*):
            Activates truncation to cut input sequences longer than *max_length* to *max_length*.
        pad_to_multiple_of (`int`, *optional*):
            If set, will pad the sequence to a multiple of the provided value.
        return_attention_mask (`bool`, *optional*):
            Whether or not [`~ASTFeatureExtractor.__call__`] should return `attention_mask`.
    Zsampling_ratez
np.ndarrayZ
raw_speechr%   r'   r&   r(   r)   N)r+   r,   r-   r.   r   r2   r/   r	   r   rD   r0   r1   r   r3   r3   r3   r4   rF      s   
(rF   c                   @   s"   e Zd ZU eeeef  ed< dS )CommonKwargsZreturn_tensorsN)r+   r,   r-   r   r	   r1   r   r/   r3   r3   r3   r4   rG     s   
rG   c                   @   sb   e Zd ZU dZejZeed< ejZeed< e	jZ
e	ed< ejZeed< ejZeed< dS )ProcessingKwargsa'  
    Base class for kwargs passing to processors.
    A model should have its own `ModelProcessorKwargs` class that inherits from `ProcessingKwargs` to provide:
        1) Additional typed keys and that this model requires to process inputs.
        2) Default values for existing keys under a `_defaults` attribute.
    New keys have to be defined as follows to ensure type hinting is done correctly.

    ```python
    # adding a new image kwarg for this model
    class ModelImagesKwargs(ImagesKwargs, total=False):
        new_image_kwarg: Optional[bool]

    class ModelProcessorKwargs(ProcessingKwargs, total=False):
        images_kwargs: ModelImagesKwargs
        _defaults = {
            "images_kwargs: {
                "new_image_kwarg": False,
            }
            "text_kwargs": {
                "padding": "max_length",
            },
        }

    ```

    For Python 3.8 compatibility, when inheriting from this class and overriding one of the kwargs,
    you need to manually update the __annotations__ dictionary. This can be done as follows:

    ```python
    class CustomProcessorKwargs(ProcessingKwargs, total=False):
        images_kwargs: CustomImagesKwargs

    CustomProcessorKwargs.__annotations__["images_kwargs"] = CustomImagesKwargs  # python 3.8 compatibility
    ```python

    common_kwargstext_kwargsimages_kwargsvideos_kwargsaudio_kwargsN)r+   r,   r-   r.   rG   r/   rI   r$   rJ   r6   rK   rE   rL   rF   rM   r3   r3   r3   r4   rH     s   
&rH   c                
   @   s  e Zd ZU dZddgZdgZg Zee e	d< dZ
dZdZg Zee e	d< dd	 Zeeef d
ddZed
ddZeeejf dddZdd Zd3edddZeeeejf eeeef eeef f dddZeeeef dddZd4eee eeef ddd Z ed5eeejf eeeejf  eeeeeef  ed"d#d$Z!ed6d&d'Z"ed(d) Z#e$d*d+ Z%e&d,d- Z'd.d/ Z(d7eeeeef   ee eed0d1d2Z)dS )8ProcessorMixinza
    This is a mixin used to provide saving/loading functionality for all processor classes.
    feature_extractor	tokenizerchat_templateoptional_call_argsNvalid_kwargsc           	   	   O   sR  | j D ]}t| |||d  q|D ]}|| jkr$td| dq$t|| jD ]*\}}||krrtd| dqP|||< qPt|t| jkrtdt| j dd| j dt| d|	 D ]\}}t
| | d	}t||}t|trtd
d |D }n
t
t|}t||s@tdt|j d| d| dt| || qd S )NzUnexpected keyword argument .z!Got multiple values for argument zThis processor requires z arguments: , z. Got z arguments instead._classc                 s   s    | ]}|d k	rt t|V  qd S Ngetattrtransformers_module.0nr3   r3   r4   	<genexpr>~  s      z*ProcessorMixin.__init__.<locals>.<genexpr>zReceived a z for argument z, but a z was expected.)optional_attributessetattrpop
attributes	TypeErrorziplen
ValueErrorjoinitemsrY   AUTO_TO_BASE_CLASS_MAPPINGget
isinstancetuplerZ   typer+   )	selfargskwargsZoptional_attributekeyargattribute_name
class_nameZproper_classr3   r3   r4   __init__c  s0    


(
zProcessorMixin.__init__returnc                    s   t j}tj}|j fdd D   dg7   fdd| D }jj	|d< d|krj|d= d|krx|d= d	|kr|d	= d
|kr|d
= dd | D }|S )z
        Serializes this instance to a Python dictionary.

        Returns:
            `Dict[str, Any]`: Dictionary of all the attributes that make up this processor instance.
        c                    s   g | ]}| j jkr|qS r3   )	__class__rb   )r\   xrn   r3   r4   
<listcomp>  s      z*ProcessorMixin.to_dict.<locals>.<listcomp>auto_mapc                    s   i | ]\}}| kr||qS r3   r3   r\   kv)attrs_to_saver3   r4   
<dictcomp>  s       z*ProcessorMixin.to_dict.<locals>.<dictcomp>processor_classrP   Zimage_processorrO   rQ   c                 S   s,   i | ]$\}}t |ts|jjd ks||qS )ZBeamSearchDecoderCTC)rk   r   rx   r+   r}   r3   r3   r4   r     s
   
  )
copydeepcopy__dict__inspect	signatureru   
parametersrh   rx   r+   )rn   outputsigr3   )r   rn   r4   to_dict  s&    
zProcessorMixin.to_dictc                 C   s   |   }tj|dddd 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.
           Tindent	sort_keys
)r   jsondumps)rn   
dictionaryr3   r3   r4   to_json_string  s    zProcessorMixin.to_json_string)json_file_pathc              	   C   s,   t |ddd}||   W 5 Q R X 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 processor instance's parameters will be saved.
        wutf-8encodingN)openwriter   )rn   r   writerr3   r3   r4   to_json_file  s    zProcessorMixin.to_json_filec                    s:    fdd j D }d|} jj d| d   S )Nc              	      s&   g | ]}d | dt t | qS )z- z: )reprrY   )r\   namerz   r3   r4   r{     s     z+ProcessorMixin.__repr__.<locals>.<listcomp>r   z:
z

)rb   rg   rx   r+   r   )rn   Zattributes_reprr3   rz   r4   __repr__  s    
zProcessorMixin.__repr__F)push_to_hubc              	      s0  | dd}|dk	r@tdt |dddk	r8td||d< tj|dd |r| dd}| d	|tj	j
d
 } j|f|} |} jdk	rԇ fdd jD }dd |D }	|	  t ||	d  jD ]2}
t |
}t|dr| jj || qڈ jdk	rF jD ]$}
t |
}t|tr |jd= q tj	|t}tj	|t}  } jdk	rtj d jidddd }t!|ddd}|"| W 5 Q R X t#$d|  t%|& dhkr '| t#$d|  |r j(|||||dd t%|& dhkr*g S |gS )a  
        Saves the attributes of this processor (feature extractor, tokenizer...) in the specified directory so that it
        can be reloaded using the [`~ProcessorMixin.from_pretrained`] method.

        <Tip>

        This class method is simply calling [`~feature_extraction_utils.FeatureExtractionMixin.save_pretrained`] and
        [`~tokenization_utils_base.PreTrainedTokenizerBase.save_pretrained`]. Please refer to the docstrings of the
        methods above for more information.

        </Tip>

        Args:
            save_directory (`str` or `os.PathLike`):
                Directory where the feature extractor JSON file and the tokenizer files will be saved (directory 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.
        use_auth_tokenNrThe `use_auth_token` argument is deprecated and will be removed in v5 of Transformers. Please use `token` instead.tokenV`token` and `use_auth_token` are both specified. Please set only the argument `token`.T)exist_okcommit_messagerepo_idc                    s   g | ]}t  |qS r3   )rY   )r\   rs   rz   r3   r4   r{     s     z2ProcessorMixin.save_pretrained.<locals>.<listcomp>c                 S   s    g | ]}t |tr|jn|qS r3   )rk   r   init_kwargs)r\   ar3   r3   r4   r{     s     )config_set_processor_classr|   rQ   r   r   r   r   r   r   zchat template saved in r   zprocessor saved in )r   r   ))ra   warningswarnFutureWarningrj   rf   osmakedirssplitpathsepZ_create_repoZ_get_files_timestamps_auto_classrb   appendr   rY   hasattrr   rx   r+   save_pretrainedrk   r   r   rg   r   r   r   rQ   r   r   r   r   loggerinfosetkeysr   Z_upload_modified_files)rn   Zsave_directoryr   rp   r   r   r   Zfiles_timestampsattrsZconfigsrs   	attributeZoutput_processor_fileZoutput_chat_template_fileprocessor_dictZchat_template_json_stringr   r3   rz   r4   r     sn    







zProcessorMixin.save_pretrained)pretrained_model_name_or_pathrw   c                 K   s  | dd}| dd}| dd}| dd}| dd}| dd}| d	d}	| d
d}
| dd}| dd}d|d}|dk	r||d< t r|std d}t|}tj|}tj|rtj|t	}tj|d}tj
|r|}d}d}nt|r|}t|}d}nt	}t}zDt||||||||||	|
dd}t||||||||||	|
dd}W nH tk
r    Y n2 tk
r   td| d| dt	 dY nX d}|dk	rt|ddd}| }W 5 Q R X t|d }||d< |dkri |fS z0t|ddd}| }W 5 Q R X t|}W n( tjk
rd   td| dY nX |r~td|  ntd| d |  d|kr|d dk	rtd! |sd"|krt|d" ||d"< d#|krt|d# ||d#< ||fS )$a  
        From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a
        processor of type [`~processing_utils.ProcessingMixin`] using `from_args_and_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 processor object.
        	cache_dirNforce_downloadFresume_downloadproxiesr   local_files_onlyrevision	subfolder Z_from_pipelineZ
_from_auto	processor)	file_typefrom_auto_classZusing_pipelinez+Offline mode: forcing local_files_only=TrueTzchat_template.json)
r   r   r   r   r   r   
user_agentr   r   Z%_raise_exceptions_for_missing_entrieszCan't load 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rr   r   rQ   z"It looks like the config file at 'z' is not a valid JSON file.zloading configuration file z from cache at zChat templates should be in a 'chat_template.json' file but found key='chat_template' in the processor's config. Make sure to move your template to its own file.r|   Zcustom_pipelines)ra   r   r   r   r1   r   r   isdirrg   r   isfiler    r   r   r   EnvironmentError	Exceptionr   readr   loadsJSONDecodeErrorwarning_oncer   r   )clsr   rp   r   r   r   r   r   r   r   r   Zfrom_pipeliner   r   is_localZprocessor_fileZchat_template_fileZresolved_processor_fileZresolved_chat_template_filerQ   readertextr   r3   r3   r4   get_processor_dict2  s    










 
 z!ProcessorMixin.get_processor_dict)r   c           	      K   s   |  }|dd}|dd}d|kr.|d= d|kr<|d= | j|| jd}| ||}|dk	rjt|d| t| D ] }t||rvt|||| qv|| t	
d|  |r||fS |S dS )	a  
        Instantiates a type of [`~processing_utils.ProcessingMixin`] from a Python dictionary of parameters.

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

        Returns:
            [`~processing_utils.ProcessingMixin`]: The processor object instantiated from those
            parameters.
        return_unused_kwargsFrQ   Nr   r|   )processor_configrS   z
Processor )r   ra   validate_init_kwargsrS   r`   r   r   r   updater   r   )	r   ro   r   rp   r   rQ   unused_kwargsr   rq   r3   r3   r4   from_args_and_dict  s&    


z!ProcessorMixin.from_args_and_dict)ModelProcessorKwargstokenizer_init_kwargsrw   c                    s  i i i i i d}i i i i i d t  } D ]d}|j|i   |< |j| j D ]8}||krTt| j|rxt| j|n|| }| | |< qTq*|	  t |t | }	|D ]}|j| j D ]}||kr|| 
|d}
|
dkr(||	kr(td| d| dn||kr$||d}
nd}
|
dkr|
|| |< || qqt fdd|D r| D ]H\}}| krj| D ]*\}}||kr||| |< || qqjn&|D ] }||kr|| |d |< q|D ]}|| 	|d  q|S )	a  
        Method to merge dictionaries of kwargs cleanly separated by modality within a Processor instance.
        The order of operations is as follows:
            1) kwargs passed as before have highest priority to preserve BC.
                ```python
                high_priority_kwargs = {"crop_size" = {"height": 222, "width": 222}, "padding" = "max_length"}
                processor(..., **high_priority_kwargs)
                ```
            2) kwargs passed as modality-specific kwargs have second priority. This is the recommended API.
                ```python
                processor(..., text_kwargs={"padding": "max_length"}, images_kwargs={"crop_size": {"height": 222, "width": 222}}})
                ```
            3) kwargs passed during instantiation of a modality processor have fourth priority.
                ```python
                tokenizer = tokenizer_class(..., {"padding": "max_length"})
                image_processor = image_processor_class(...)
                processor(tokenizer, image_processor) # will pass max_length unless overriden by kwargs at call
                ```
            4) defaults kwargs specified at processor level have lowest priority.
                ```python
                class MyProcessingKwargs(ProcessingKwargs, CommonKwargs, TextKwargs, ImagesKwargs, total=False):
                    _defaults = {
                        "text_kwargs": {
                            "padding": "max_length",
                            "max_length": 64,
                        },
                    }
                ```
        Args:
            ModelProcessorKwargs (`ProcessingKwargs`):
                Typed dictionary of kwargs specifically required by the model passed.
            tokenizer_init_kwargs (`Dict`, *optional*):
                Dictionary of kwargs the tokenizer was instantiated with and need to take precedence over defaults.

        Returns:
            output_kwargs (`Dict`):
                Dictionary of per-modality kwargs to be passed to each modality-specific processor.

        )rJ   rK   rM   rL   rI   Z	__empty__zKeyword argument z+ was passed two times:
in a dictionary for z and as a **kwarg.c                 3   s   | ]}| kV  qd S rW   r3   )r\   rq   Zdefault_kwargsr3   r4   r^   b  s     z/ProcessorMixin._merge_kwargs.<locals>.<genexpr>rI   )r   	_defaultsrj   r   r/   r   r   rP   rY   r   ra   rf   addanyrh   )rn   r   r   rp   Zoutput_kwargsZ	used_keysZmodalityZmodality_keyvalueZnon_modality_kwargsZkwarg_valueZsubdictsubkeyZsubvaluerq   r3   r   r4   _merge_kwargs  sf    /	






zProcessorMixin._merge_kwargsmain)r   r   r   r   r   r   c                 K   s   ||d< ||d< ||d< ||d< | dd}|dk	rTtdt |dk	rPtd|}|dk	rd||d	< | j|f|}	| j|f|\}
}| j|	|
f|S )
a[  
        Instantiate a processor associated with a pretrained model.

        <Tip>

        This class method is simply calling the feature extractor
        [`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`], image processor
        [`~image_processing_utils.ImageProcessingMixin`] and the tokenizer
        [`~tokenization_utils_base.PreTrainedTokenizer.from_pretrained`] methods. Please refer to the docstrings of the
        methods above for more information.

        </Tip>

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

                - a string, the *model id* of a pretrained feature_extractor hosted inside a model repo on
                  huggingface.co.
                - a path to a *directory* containing a feature extractor file saved using the
                  [`~SequenceFeatureExtractor.save_pretrained`] method, e.g., `./my_model_directory/`.
                - a path or url to a saved feature extractor JSON *file*, e.g.,
                  `./my_model_directory/preprocessor_config.json`.
            **kwargs
                Additional keyword arguments passed along to both
                [`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`] and
                [`~tokenization_utils_base.PreTrainedTokenizer.from_pretrained`].
        r   r   r   r   r   Nr   r   r   )ra   r   r   r   rf   _get_arguments_from_pretrainedr   r   )r   r   r   r   r   r   r   rp   r   ro   r   r3   r3   r4   from_pretrainedu  s(    'zProcessorMixin.from_pretrainedAutoProcessorc                 C   sD   t |ts|j}ddlm  m} t||s:t| d|| _dS )a  
        Register this class with a given auto class. This should only be used for custom feature extractors as the ones
        in the library are already mapped with `AutoProcessor`.

        <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 `"AutoProcessor"`):
                The auto class to register this new feature extractor with.
        r   Nz is not a valid auto class.)	rk   r1   r+   Ztransformers.models.automodelsautor   rf   r   )r   Z
auto_classZauto_moduler3   r3   r4   register_for_auto_class  s    

z&ProcessorMixin.register_for_auto_classc           	      K   s   g }| j D ]~}t| | d}t|trjtdd |D }|dd}|r`|d d k	r`|d }qt|d }n
tt|}||j|f| q
|S )NrV   c                 s   s$   | ]}|d k	rt t|nd V  qd S rW   rX   r[   r3   r3   r4   r^     s     z@ProcessorMixin._get_arguments_from_pretrained.<locals>.<genexpr>use_fastTr
   r   )rb   rY   rk   rl   rj   rZ   r   r   )	r   r   rp   ro   rs   rt   classesr   Zattribute_classr3   r3   r4   r     s    




z-ProcessorMixin._get_arguments_from_pretrainedc                 C   s   t | | jd }t |dd S )Nr   model_input_names)rY   rb   )rn   Zfirst_attributer3   r3   r4   r     s    z ProcessorMixin.model_input_namesc                    sR      }i }t|t| }|rNd|}td| d  fdd|D }|S )NrU   zISome kwargs in processor config are unused and will not have any effect: z. c                    s   i | ]}| | qS r3   r3   )r\   r~   r   r3   r4   r     s      z7ProcessorMixin.validate_init_kwargs.<locals>.<dictcomp>)r   r   rg   r   warning)r   rS   Zkwargs_from_configr   Zunused_keysZunused_key_strr3   r   r4   r     s    

z#ProcessorMixin.validate_init_kwargsc                 G   sh   t |rtd t |t | jkrRtdt | j dd| j dt | ddd t|| jD S )	a  
        Matches optional positional arguments to their corresponding names in `optional_call_args`
        in the processor class in the order they are passed to the processor call.

        Note that this should only be used in the `__call__` method of the processors with special
        arguments. Special arguments are arguments that aren't `text`, `images`, `audio`, nor `videos`
        but also aren't passed to the tokenizer, image processor, etc. Examples of such processors are:
            - `CLIPSegProcessor`
            - `LayoutLMv2Processor`
            - `OwlViTProcessor`

        Also note that passing by position to the processor call is now deprecated and will be disallowed
        in future versions. We only have this for backward compatibility.

        Example:
            Suppose that the processor class has `optional_call_args = ["arg_name_1", "arg_name_2"]`.
            And we define the call method as:
            ```python
            def __call__(
                self,
                text: str,
                images: Optional[ImageInput] = None,
                *arg,
                audio=None,
                videos=None,
            )
            ```

            Then, if we call the processor as:
            ```python
            images = [...]
            processor("What is common in these images?", images, arg_value_1, arg_value_2)
            ```

            Then, this method will return:
            ```python
            {
                "arg_name_1": arg_value_1,
                "arg_name_2": arg_value_2,
            }
            ```
            which we could then pass as kwargs to `self._merge_kwargs`
        zPassing positional arguments to the processor call is now deprecated and will be disallowed in v4.47. Please pass all arguments as keyword arguments.zExpected *at most* zK optional positional arguments in processor callwhich will be matched with  z+ in the order they are passed.However, got z positional arguments instead.Please pass all arguments as keyword arguments instead (e.g. `processor(arg_name_1=..., arg_name_2=...))`.c                 S   s   i | ]\}}||qS r3   r3   )r\   	arg_valueZarg_namer3   r3   r4   r   +  s      zJProcessorMixin.prepare_and_validate_optional_call_args.<locals>.<dictcomp>)re   r   r   rR   rf   rg   rd   )rn   ro   r3   r3   r4   'prepare_and_validate_optional_call_args  s    ,(z6ProcessorMixin.prepare_and_validate_optional_call_args)conversationrQ   tokenizerw   c                 K   s<   |dkr"| j dk	r| j }ntd| jj|f||d|S )a  
        Similar to the `apply_chat_template` method on tokenizers, this method applies a Jinja template to input
        conversations to turn them into a single tokenizable string.

        Args:
            conversation (`List[Dict, str, str]`):
                The conversation to format.
            chat_template (`Optional[str]`, *optional*):
                The Jinja template to use for formatting the conversation. If not provided, the tokenizer's
                chat template is used.
            tokenize (`bool`, *optional*, defaults to `False`):
                Whether to tokenize the output or not.
            **kwargs:
                Additional keyword arguments
        NzNo chat template is set for this processor. Please either set the `chat_template` attribute, or provide a chat template as an argument. See https://huggingface.co/docs/transformers/main/en/chat_templating for more information.)rQ   r   )rQ   rf   rP   apply_chat_template)rn   r   rQ   r   rp   r3   r3   r4   r   -  s    
 z"ProcessorMixin.apply_chat_template)F)N)NFFNr   )r   )NF)*r+   r,   r-   r.   rb   r_   rR   r   r1   r/   Zfeature_extractor_classZtokenizer_classr   rS   ru   r   r   r   r   r	   r   PathLiker   r   r0   r   classmethodr   r   r   rH   r   r   r   r   r   propertyr   staticmethodr   r   r   r3   r3   r3   r4   rN   T  st   
&(f 0 
|     ?


=  rN   c                    s   t ddd fdd fdddd	 }||  }| }||} |}|rd|rd| |fS | d
krp|s|d
kr||s|r|rtd || fS tdd
S )a  
    For backward compatibility: reverse the order of `images` and `text` inputs if they are swapped.
    This method should only be called for processors where `images` and `text` have been swapped for uniformization purposes.
    Note that this method assumes that two `None` inputs are valid inputs. If this is not the case, it should be handled
    in the processor's `__call__` method before calling this method.
    rv   c                 S   s   t | to| dS )Nhttp)rk   r1   
startswith)valr3   r3   r4   is_urlZ  s    z1_validate_images_text_input_order.<locals>.is_urlc                    s@   t | ttfr(| D ]} |s dS qnt| s<| s<dS dS )NFT)rk   listrl   r   )Zimgsimg)$_is_valid_images_input_for_processorr  r3   r4   r  ]  s    
zO_validate_images_text_input_order.<locals>._is_valid_images_input_for_processorc                    sD   t | trdS t | ttfr@t| dkr,dS | D ]} |  S dS )NTr   F)rk   r1   r  rl   re   )tZt_s)"_is_valid_text_input_for_processorr3   r4   r	  h  s    
zM_validate_images_text_input_order.<locals>._is_valid_text_input_for_processorc                 S   s   || p| d kS rW   r3   )inputZ	validatorr3   r3   r4   	_is_validu  s    z4_validate_images_text_input_order.<locals>._is_validNzYou may have used the wrong order for inputs. `images` should be passed before `text`. The `images` and `text` inputs will be swapped. This behavior will be deprecated in transformers v4.47.zGInvalid input type. Check that `images` and/or `text` are valid inputs.)r0   r   r   rf   )Zimagesr   r  Zimages_is_validZimages_is_textZtext_is_validZtext_is_imagesr3   )r  r	  r  r4   !_validate_images_text_input_orderR  s     

 r  r   r   zprocessor files)objectZobject_classZobject_files)Br.   r   r   r   r   systypingr   pathlibr   r   r   r   r   r   r   r	   ZnumpynpZtyping_extensionsZdynamic_module_utilsr   Zimage_utilsr   r   r   r   Ztokenization_utils_baser   r   r   r   r   utilsr   r   r   r   r   r   r   r   r   r   r   r    r!   Z
get_loggerr+   r   __file__parentrZ   ri   version_infoZUnpackr$   r6   rE   rF   rG   rH   rN   r  r   formatr3   r3   r3   r4   <module>   s^   $<
:70'7      :  