a
    d9*                     @   s   d Z ddlZddlmZ ddlmZ ddlmZ ddlm	Z	m
Z
mZmZ eeZeeejZdd	d
dZG dd de	Ze
eje_ejj durejj jddddej_ dS )z9
 Processing saving/loading class for common processors.
    N)Path   )custom_object_save)PreTrainedTokenizerBase)PushToHubMixin	copy_funcdirect_transformers_importloggingr   ZFeatureExtractionMixinZImageProcessingMixin)ZAutoTokenizerZAutoFeatureExtractorZAutoImageProcessorc                   @   sv   e Zd ZdZddgZdZdZdZdd Zdd Z	de
d
ddZedd ZedddZedd Zedd ZdS )ProcessorMixinza
    This is a mixin used to provide saving/loading functionality for all processor classes.
    Zfeature_extractor	tokenizerNc              	   O   s0  |D ]}|| j vrtd| dqt|| j D ]*\}}||v rRtd| dq0|||< q0t|t| j krtdt| j  dd| j  dt| d| D ]\}}t| | d	}t	||}t
|trt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, z. Got z arguments instead._classc                 s   s    | ]}|d urt t|V  qd S Ngetattrtransformers_module.0n r   f/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/transformers/processing_utils.py	<genexpr>K       z*ProcessorMixin.__init__.<locals>.<genexpr>zReceived a z for argument z, but a z was expected.)
attributes	TypeErrorziplen
ValueErrorjoinitemsr   AUTO_TO_BASE_CLASS_MAPPINGget
isinstancetupler   type__name__setattr)selfargskwargskeyargattribute_name
class_nameZproper_classr   r   r   __init__4   s0    



zProcessorMixin.__init__c                    s0    fdd j D }d|} jj d| S )Nc              	      s&   g | ]}d | dt t | qS )z- z: )reprr   )r   namer'   r   r   
<listcomp>W   r   z+ProcessorMixin.__repr__.<locals>.<listcomp>
z:
)r   r   	__class__r%   )r'   Zattributes_reprr   r1   r   __repr__V   s    
zProcessorMixin.__repr__F)push_to_hubc                    s  t j|dd |rT|dd}|d|t jjd } j|fi |} |} jdur fdd j	D }d	d |D }t
 ||d
  j	D ]0}	t |	}
t|
dr|
 jj |
| q jdur j	D ] }	t |	}
t|
tr|
jd= q|r j|||||dd d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:
                Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
        T)exist_okcommit_messageNrepo_idc                    s   g | ]}t  |qS r   )r   )r   r,   r1   r   r   r2   }   r   z2ProcessorMixin.save_pretrained.<locals>.<listcomp>c                 S   s    g | ]}t |tr|jn|qS r   )r"   r   init_kwargs)r   ar   r   r   r2   ~   r   )config_set_processor_classZauto_mapZuse_auth_token)r8   token)osmakedirspopsplitpathsepZ_create_repoZ_get_files_timestamps_auto_classr   r   r   hasattrr>   r4   r%   save_pretrainedr"   r   r;   Z_upload_modified_filesr!   )r'   Zsave_directoryr6   r)   r8   r9   Zfiles_timestampsattrsZconfigsr,   	attributer   r1   r   rH   [   s8    









zProcessorMixin.save_pretrainedc                 K   s   | j |fi |}| | 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. 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
                  [`~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`].
        )_get_arguments_from_pretrained)clspretrained_model_name_or_pathr)   r(   r   r   r   from_pretrained   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.)	r"   strr%   Ztransformers.models.automodelsautorG   r   rF   )rL   Z
auto_classZauto_moduler   r   r   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 ur`|d }qt|d }n
tt|}||j|fi | q
|S )Nr   c                 s   s$   | ]}|d urt t|nd V  qd S r   r   r   r   r   r   r      r   z@ProcessorMixin._get_arguments_from_pretrained.<locals>.<genexpr>use_fastTr   r   )r   r   r"   r#   r!   r   appendrN   )	rL   rM   r)   r(   r,   r-   classesrT   Zattribute_classr   r   r   rK      s    




z-ProcessorMixin._get_arguments_from_pretrainedc                 C   s   t | | jd }t |dd S )Nr   model_input_names)r   r   )r'   Zfirst_attributer   r   r   rW      s    z ProcessorMixin.model_input_names)F)rO   )r%   
__module____qualname____doc__r   Zfeature_extractor_classZtokenizer_classrF   r.   r5   boolrH   classmethodrN   rS   rK   propertyrW   r   r   r   r   r
   (   s    ">
!
r
   	processorrO   zprocessor files)objectZobject_classZobject_files)rZ   r@   pathlibr   Zdynamic_module_utilsr   Ztokenization_utils_baser   utilsr   r   r   r	   Z
get_loggerr%   logger__file__parentr   r    r
   r6   formatr   r   r   r   <module>   s$   
 F