a
    di                     @   s&  d 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 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mZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z# ere rddl$Z$e"%e&Z'ed Z(G d	d
 d
eZ)G dd deZ*ee*j+e*_+e*j+j dur"e*j+j j,dddde*j+_ dS )zI
 Feature extraction saving/loading class for common feature extractors.
    N)UserDict)TYPE_CHECKINGAnyDictOptionalTupleUnion   )custom_object_save)FEATURE_EXTRACTOR_NAMEPushToHubMixin
TensorTypeadd_model_info_to_auto_mapcached_file	copy_funcdownload_urlis_flax_availableis_jax_tensoris_numpy_arrayis_offline_modeis_remote_urlis_tf_availableis_torch_availableis_torch_deviceis_torch_dtypeloggingrequires_backendsZSequenceFeatureExtractorc                       s   e Zd ZdZdeeeef  edee	f d fddZ
eee dddZed	d
dZdd Zdd Zdd Zdd Zdd Zdeeee	f  dddZd dddZ  ZS )BatchFeatureaI  
    Holds the output of the [`~SequenceFeatureExtractor.pad`] and feature extractor specific `__call__` methods.

    This class is derived from a python dictionary and can be used as a dictionary.

    Args:
        data (`dict`):
            Dictionary of lists/arrays/tensors returned by the __call__/pad methods ('input_values', 'attention_mask',
            etc.).
        tensor_type (`Union[None, str, TensorType]`, *optional*):
            You can give a tensor_type here to convert the lists of integers in PyTorch/TensorFlow/Numpy Tensors at
            initialization.
    N)datatensor_typec                    s   t  | | j|d d S )Nr   )super__init__convert_to_tensors)selfr   r   	__class__ n/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/transformers/feature_extraction_utils.pyr"   K   s    zBatchFeature.__init__)itemreturnc                 C   s    t |tr| j| S tddS )z
        If the key is a string, returns the value of the dict associated to `key` ('input_values', 'attention_mask',
        etc.).
        zRIndexing with integers is not available when using Python based feature extractorsN)
isinstancestrr   KeyErrorr$   r)   r'   r'   r(   __getitem__O   s    

zBatchFeature.__getitem__)r)   c                 C   s(   z| j | W S  ty"   tY n0 d S N)r   r-   AttributeErrorr.   r'   r'   r(   __getattr__Y   s    zBatchFeature.__getattr__c                 C   s
   d| j iS Nr   r   r$   r'   r'   r(   __getstate___   s    zBatchFeature.__getstate__c                 C   s   d|v r|d | _ d S r3   r4   )r$   stater'   r'   r(   __setstate__b   s    zBatchFeature.__setstate__c                 C   s
   | j  S r0   )r   keysr5   r'   r'   r(   r9   g   s    zBatchFeature.keysc                 C   s
   | j  S r0   )r   valuesr5   r'   r'   r(   r:   k   s    zBatchFeature.valuesc                 C   s
   | j  S r0   )r   itemsr5   r'   r'   r(   r;   o   s    zBatchFeature.itemsr    c                    s  |du r| S t |tst|}|tjkrLt s6tdddl}|j |j}nv|tjkrt	 sdtdddl
fdd j}nB|tjkrt stdddlm} |j t}nd fdd	 t}|  D ]L\}}z||s |}|| |< W q   |d	krtd
tdY q0 q| S )a5  
        Convert the inner content to tensors.

        Args:
            tensor_type (`str` or [`~utils.TensorType`], *optional*):
                The type of tensors to use. If `str`, should be one of the values of the enum [`~utils.TensorType`]. If
                `None`, no modification is done.
        NzSUnable to convert output to TensorFlow tensors format, TensorFlow is not installed.r   zMUnable to convert output to PyTorch tensors format, PyTorch is not installed.c                    s>   t | ttfr4t| dkr4t | d tjr4t| }  | S )Nr   )r+   listtuplelennpndarrayarraytensor)value)torchr'   r(   	as_tensor   s    *
z2BatchFeature.convert_to_tensors.<locals>.as_tensorzEUnable to convert output to JAX tensors format, JAX is not installed.c                    sn   t | ttfr`t | d tttjfr`dd | D }tt|dkr`|d u r` dd | D td} tj| |dS )Nr   c                 S   s   g | ]}t |qS r'   )r>   .0valr'   r'   r(   
<listcomp>       zFBatchFeature.convert_to_tensors.<locals>.as_tensor.<locals>.<listcomp>r	   c                 S   s   g | ]}t |qS r'   )r?   asarrayrF   r'   r'   r(   rI      rJ   )dtype)	r+   r<   r=   r?   r@   r>   setobjectrK   )rC   rL   Z
value_lens)rE   r'   r(   rE      s
    $Zoverflowing_valueszKUnable to create tensor returning overflowing values of different lengths. zUnable to create tensor, you should probably activate padding with 'padding=True' to have batched tensors with the same length.)N)r+   r   Z
TENSORFLOWr   ImportErrorZ
tensorflowZconstant	is_tensorZPYTORCHr   rD   ZJAXr   Z	jax.numpynumpyrA   r   r   r;   
ValueError)r$   r   tfrP   ZjnpkeyrC   rB   r'   )rE   rD   r(   r#   r   sL    	




zBatchFeature.convert_to_tensorsr*   c           	      O   s   t | dg ddl}i }|d}|du r~t|dkr~|d }t|rHn6t|tsdt|sdt|trj|}nt	dt| d| 
 D ]J\}}||r|j|i |||< q|dur|j|d||< q|||< q|| _| S )a  
        Send all values to device by calling `v.to(*args, **kwargs)` (PyTorch only). This should support casting in
        different `dtypes` and sending the `BatchFeature` to a different `device`.

        Args:
            args (`Tuple`):
                Will be passed to the `to(...)` function of the tensors.
            kwargs (`Dict`, *optional*):
                Will be passed to the `to(...)` function of the tensors.

        Returns:
            [`BatchFeature`]: The same instance after modification.
        rD   r   Ndevicez*Attempting to cast a BatchFeature to type z. This is not supported.)rV   )r   rD   getr>   r   r+   r,   r   intrR   r;   Zis_floating_pointtor   )	r$   argskwargsrD   Znew_datarV   argkvr'   r'   r(   rY      s&    


zBatchFeature.to)NN)N)__name__
__module____qualname____doc__r   r   r,   r   r   r   r"   r/   r2   r6   r8   r9   r:   r;   r#   rY   __classcell__r'   r'   r%   r(   r   <   s   ,
Ir   c                   @   s&  e Zd ZdZdZdd ZedddZee	ee
jf edd	d
Zd$e	ee
jf e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 edddZeeef dddZee	ee
jf edddZedddZe	ee
jf dddZdd  Zed%d"d#ZdS )&FeatureExtractionMixinz
    This is a feature extraction mixin used to provide saving/loading functionality for sequential and image feature
    extractors.
    Nc                 K   sz   | dd| _| D ]^\}}zt| || W q tyr } z,td| d| d|   |W Y d}~qd}~0 0 qdS )z'Set elements of `kwargs` as attributes.processor_classNz
Can't set z with value z for )pop_processor_classr;   setattrr1   loggererror)r$   r[   rT   rC   errr'   r'   r(   r"      s    zFeatureExtractionMixin.__init__)re   c                 C   s
   || _ dS )z%Sets processor class as an attribute.N)rg   )r$   re   r'   r'   r(   _set_processor_class   s    z+FeatureExtractionMixin._set_processor_class)pretrained_model_name_or_pathr*   c                 K   s(   | j |fi |\}}| j|fi |S )a  
        Instantiate a type of [`~feature_extraction_utils.FeatureExtractionMixin`] from a feature extractor, *e.g.* a
        derived class of [`SequenceFeatureExtractor`].

        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. Valid model ids can be located at the root-level, like `bert-base-uncased`, or
                  namespaced under a user or organization name, like `dbmdz/bert-base-german-cased`.
                - a path to a *directory* containing a feature extractor file saved using the
                  [`~feature_extraction_utils.FeatureExtractionMixin.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`.
            cache_dir (`str` or `os.PathLike`, *optional*):
                Path to a directory in which a downloaded pretrained model feature extractor 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 feature extractor files and override the cached versions
                if they exist.
            resume_download (`bool`, *optional*, defaults to `False`):
                Whether or not to delete incompletely received file. Attempts to resume the download if such a file
                exists.
            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.
            use_auth_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 `huggingface-cli 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 feature extractor object. If `True`, then this
                functions returns a `Tuple(feature_extractor, unused_kwargs)` where *unused_kwargs* is a dictionary
                consisting of the key/value pairs whose keys are not feature extractor attributes: i.e., the part of
                `kwargs` which has not been used to update `feature_extractor` and is otherwise ignored.
            kwargs (`Dict[str, Any]`, *optional*):
                The values in kwargs of any keys which are feature extractor attributes will be used to override the
                loaded values. Behavior concerning key/value pairs whose keys are *not* feature extractor attributes is
                controlled by the `return_unused_kwargs` keyword parameter.

        Returns:
            A feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`].

        Examples:

        ```python
        # We can't instantiate directly the base class *FeatureExtractionMixin* nor *SequenceFeatureExtractor* so let's show the examples on a
        # derived class: *Wav2Vec2FeatureExtractor*
        feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
            "facebook/wav2vec2-base-960h"
        )  # Download feature_extraction_config from huggingface.co and cache.
        feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
            "./test/saved_model/"
        )  # E.g. feature_extractor (or model) was saved using *save_pretrained('./test/saved_model/')*
        feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained("./test/saved_model/preprocessor_config.json")
        feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(
            "facebook/wav2vec2-base-960h", return_attention_mask=False, foo=False
        )
        assert feature_extractor.return_attention_mask is False
        feature_extractor, unused_kwargs = Wav2Vec2FeatureExtractor.from_pretrained(
            "facebook/wav2vec2-base-960h", return_attention_mask=False, foo=False, return_unused_kwargs=True
        )
        assert feature_extractor.return_attention_mask is False
        assert unused_kwargs == {"foo": False}
        ```)get_feature_extractor_dict	from_dict)clsrm   r[   feature_extractor_dictr'   r'   r(   from_pretrained   s    Rz&FeatureExtractionMixin.from_pretrainedF)save_directorypush_to_hubc                 K   s   t j|rtd| dt j|dd |rp|dd}|d|t jjd }| j|fi |}| 	|}| j
durt| || d	 t j|t}| | td
|  |r| j|||||dd |gS )a[  
        Save a feature_extractor object to the directory `save_directory`, so that it can be re-loaded using the
        [`~feature_extraction_utils.FeatureExtractionMixin.from_pretrained`] class method.

        Args:
            save_directory (`str` or `os.PathLike`):
                Directory where the feature extractor 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:
                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_id)configzFeature extractor saved in use_auth_token)rv   token)ospathisfileAssertionErrormakedirsrf   splitsepZ_create_repoZ_get_files_timestamps_auto_classr
   joinr   to_json_fileri   infoZ_upload_modified_filesrW   )r$   rs   rt   r[   rv   rw   Zfiles_timestampsZoutput_feature_extractor_filer'   r'   r(   save_pretrainedV  s,    


z&FeatureExtractionMixin.save_pretrainedc                 K   s(  | dd}| dd}| dd}| dd}| dd}| dd}| d	d}	| d
d}
| dd}d|d}|
dur|
|d< t r|std d}t|}tj|}tj|rtj|t	}tj
|r|}d}nt|r|}t|}njt	}z t||||||||||	d
}W nD ty2    Y n0 ty`   td| d| dt	 dY n0 zFt|ddd}| }W d   n1 s0    Y  t|}W n& tjy   td| dY n0 |rtd|  ntd| d|  d|v r |s t|d ||d< ||fS )a6  
        From a `pretrained_model_name_or_path`, resolve to a dictionary of parameters, to be used for instantiating a
        feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`] 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.

        Returns:
            `Tuple[Dict, Dict]`: The dictionary(ies) that will be used to instantiate the feature extractor object.
        	cache_dirNforce_downloadFresume_downloadproxiesrz   local_files_onlyrevisionZ_from_pipelineZ
_from_autofeature extractor)	file_typefrom_auto_classZusing_pipelinez+Offline mode: forcing local_files_only=TrueT)r   r   r   r   r   rz   
user_agentr   z"Can't load feature extractor 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 Zauto_map)rf   r   ri   r   r,   r|   r}   isdirr   r   r~   r   r   r   EnvironmentError	ExceptionopenreadjsonloadsJSONDecodeErrorr   )rp   rm   r[   r   r   r   r   rz   r   r   Zfrom_pipeliner   r   is_localZfeature_extractor_fileZresolved_feature_extractor_filereadertextrq   r'   r'   r(   rn     s    





(

z1FeatureExtractionMixin.get_feature_extractor_dict)rq   r*   c                 K   s   | dd}| f i |}g }| D ](\}}t||r&t||| || q&|D ]}| |d qTtd|  |r||fS |S dS )a	  
        Instantiates a type of [`~feature_extraction_utils.FeatureExtractionMixin`] from a Python dictionary of
        parameters.

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

        Returns:
            [`~feature_extraction_utils.FeatureExtractionMixin`]: The feature extractor object instantiated from those
            parameters.
        return_unused_kwargsFNzFeature extractor )rf   r;   hasattrrh   appendri   r   )rp   rq   r[   r   Zfeature_extractorZ	to_removerT   rC   r'   r'   r(   ro     s    
z FeatureExtractionMixin.from_dictrU   c                 C   s   t | j}| 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 feature extractor instance.
        Zfeature_extractor_type)copydeepcopy__dict__r&   r_   )r$   outputr'   r'   r(   to_dict  s    zFeatureExtractionMixin.to_dict)	json_filer*   c                 C   sN   t |ddd}| }W d   n1 s,0    Y  t|}| f i |S )a  
        Instantiates a feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`] 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 feature extractor of type [`~feature_extraction_utils.FeatureExtractionMixin`]: The feature_extractor
            object instantiated from that JSON file.
        r   r   r   N)r   r   r   r   )rp   r   r   r   rq   r'   r'   r(   from_json_file  s    &
z%FeatureExtractionMixin.from_json_filec                 C   sb   |   }| D ] \}}t|tjr| ||< q|dd}|durN||d< 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.
        rg   Nre      T)indent	sort_keys
)	r   r;   r+   r?   r@   tolistrf   r   dumps)r$   
dictionaryrT   rC   rg   r'   r'   r(   to_json_string,  s    z%FeatureExtractionMixin.to_json_string)json_file_pathc                 C   s@   t |ddd}||   W d   n1 s20    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 feature_extractor instance's parameters will be saved.
        wr   r   N)r   writer   )r$   r   writerr'   r'   r(   r   A  s    z#FeatureExtractionMixin.to_json_filec                 C   s   | j j d|   S )N )r&   r_   r   r5   r'   r'   r(   __repr__L  s    zFeatureExtractionMixin.__repr__AutoFeatureExtractorc                 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 `AutoFeatureExtractor`.

        <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 `"AutoFeatureExtractor"`):
                The auto class to register this new feature extractor with.
        r   Nz is not a valid auto class.)	r+   r,   r_   Ztransformers.models.automodelsautor   rR   r   )rp   Z
auto_classZauto_moduler'   r'   r(   register_for_auto_classO  s    

z.FeatureExtractionMixin.register_for_auto_class)F)r   )r_   r`   ra   rb   r   r"   r,   rl   classmethodr   r|   PathLikePreTrainedFeatureExtractorrr   boolr   r   r   r   rn   ro   r   r   r   r   r   r   r'   r'   r'   r(   rd      s.   U0a$rd   r   r   zfeature extractor file)rN   Zobject_classZobject_files)-rb   r   r   r|   collectionsr   typingr   r   r   r   r   r   rQ   r?   Zdynamic_module_utilsr
   utilsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rD   Z
get_loggerr_   ri   r   r   rd   rt   formatr'   r'   r'   r(   <module>   s0    P
 -   