o
    pi~                     @   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 ddlmZmZmZmZ ddlZddlmZmZ ddlmZmZmZmZ ddlmZ d	d
lmZ d	dlm Z m!Z!m"Z"m#Z#m$Z$m%Z% e%&e'Z(e)dZ*G dd de	Z+G dd dZ,dd Z-dd Z.G dd de,Z/dS )z%ConfigMixin base class and utilities.    N)OrderedDict)Path)AnyDictTupleUnion)create_repohf_hub_download)EntryNotFoundErrorRepositoryNotFoundErrorRevisionNotFoundErrorvalidate_hf_hub_args)	HTTPError   )__version__)HUGGINGFACE_CO_RESOLVE_ENDPOINTDummyObject	deprecateextract_commit_hashhttp_user_agentloggingzconfig\.(.*)\.jsonc                       sT   e Zd Z fddZdd Zdd Zdd Zd	d
 Z fddZ fddZ	  Z
S )
FrozenDictc                    s:   t  j|i | |  D ]
\}}t| || qd| _d S )NT)super__init__itemssetattr_FrozenDict__frozen)selfargskwargskeyvalue	__class__ [/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/diffusers/configuration_utils.pyr   8   s   
zFrozenDict.__init__c                 O      t d| jj d)Nz$You cannot use ``__delitem__`` on a 
 instance.	Exceptionr#   __name__r   r   r   r$   r$   r%   __delitem__@      zFrozenDict.__delitem__c                 O   r&   )Nz#You cannot use ``setdefault`` on a r'   r(   r+   r$   r$   r%   
setdefaultC   r-   zFrozenDict.setdefaultc                 O   r&   )NzYou cannot use ``pop`` on a r'   r(   r+   r$   r$   r%   popF   r-   zFrozenDict.popc                 O   r&   )NzYou cannot use ``update`` on a r'   r(   r+   r$   r$   r%   updateI   r-   zFrozenDict.updatec                    6   t | dr| jrtd| jj dt || d S N__frozenz$You cannot use ``__setattr__`` on a r'   )hasattrr   r)   r#   r*   r   __setattr__r   namer!   r"   r$   r%   r5   L      zFrozenDict.__setattr__c                    r1   r2   )r4   r   r)   r#   r*   r   __setitem__r6   r"   r$   r%   r9   Q   r8   zFrozenDict.__setitem__)r*   
__module____qualname__r   r,   r.   r/   r0   r5   r9   __classcell__r$   r$   r"   r%   r   7   s    r   c                   @   sF  e Zd ZdZdZg ZdZg Zdd Zde	de
fdd	Zd&d
ee	ejf defddZed'deeee	e
f f fddZedd Zee		d(dee	ejf deee	e
f ee	e
f f fddZedd Zedd Zedee	ejf fddZdd Zedee	e
f fdd Zde	fd!d"Z d#ee	ejf fd$d%Z!dS ))ConfigMixina  
    Base class for all configuration classes. All configuration parameters are stored under `self.config`. Also
    provides the [`~ConfigMixin.from_config`] and [`~ConfigMixin.save_config`] methods for loading, downloading, and
    saving classes that inherit from [`ConfigMixin`].

    Class attributes:
        - **config_name** (`str`) -- A filename under which the config should stored when calling
          [`~ConfigMixin.save_config`] (should be overridden by parent class).
        - **ignore_for_config** (`List[str]`) -- A list of attributes that should not be saved in the config (should be
          overridden by subclass).
        - **has_compatibles** (`bool`) -- Whether the class has compatible classes (should be overridden by subclass).
        - **_deprecated_kwargs** (`List[str]`) -- Keyword arguments that are deprecated. Note that the `init` function
          should only have a `kwargs` argument if at least one argument is deprecated (should be overridden by
          subclass).
    NFc                 K   st   | j d u rtd| j d|dd  t| ds|}nt| j}i | j|}td| d|  t	|| _d S )NzMake sure that z' has defined a class name `config_name`r   _internal_dictzUpdating config from z to )
config_nameNotImplementedErrorr#   r/   r4   dictr>   loggerdebugr   )r   r   internal_dictprevious_dictr$   r$   r%   register_to_confign   s   


zConfigMixin.register_to_configr7   returnc                 C   s   d| j v ot| j d |}|| j v }|r;|s;d| dt| j d| dt| j d| d}tdd	|d
d | j| S tdt| j d| d)aW  The only reason we overwrite `getattr` here is to gracefully deprecate accessing
        config attributes directly. See https://github.com/huggingface/diffusers/pull/3129

        This function is mostly copied from PyTorch's __getattr__ overwrite:
        https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
        r>   zAccessing config attribute `z` directly via 'z1' object attribute is deprecated. Please access 'z' over 'z1's config object instead, e.g. 'scheduler.config.z'.zdirect config name access1.0.0Fstandard_warn'z' object has no attribute ')__dict__r4   typer*   r   r>   AttributeError)r   r7   is_in_configis_attributedeprecation_messager$   r$   r%   __getattr__   s   
0
zConfigMixin.__getattr__save_directorypush_to_hubc           
      K   s   t j|rtd| dt j|dd t j|| j}| | t	d|  |rf|
dd}|
dd	}|
d
d	}|
dd}|
d|t jjd }	t|	d||dj}	| j||	|||d dS dS )aI  
        Save a configuration object to the directory specified in `save_directory` so that it can be reloaded using the
        [`~ConfigMixin.from_config`] class method.

        Args:
            save_directory (`str` or `os.PathLike`):
                Directory where the configuration JSON file is 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 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 keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
        zProvided path (z#) should be a directory, not a fileT)exist_okzConfiguration saved in commit_messageNprivateF	create_prtokenrepo_id)rU   rW   rY   )rY   rV   rX   )ospathisfileAssertionErrormakedirsjoinr?   to_json_filerB   infor/   splitsepr   rZ   _upload_folder)
r   rS   rT   r   output_config_filerV   rW   rX   rY   rZ   r$   r$   r%   save_config   s*   

zConfigMixin.save_configconfigc           
      K   s2  d|v r	| d}|du rtdt|tsKd}d| jv r&|d|  d7 }nd| jv r6|d	|  d
|  d7 }tdd|dd | jd|dd|\}}| j|fi |\}}}d|v rb| d|d< | jD ]}||v rr| |||< qe| di |}	d|v r| j|d< |	j	di | i ||}|r|	|fS |	S )a
  
        Instantiate a Python class from a config dictionary.

        Parameters:
            config (`Dict[str, Any]`):
                A config dictionary from which the Python class is instantiated. Make sure to only load configuration
                files of compatible classes.
            return_unused_kwargs (`bool`, *optional*, defaults to `False`):
                Whether kwargs that are not consumed by the Python class should be returned or not.
            kwargs (remaining dictionary of keyword arguments, *optional*):
                Can be used to update the configuration object (after it is loaded) and initiate the Python class.
                `**kwargs` are passed directly to the underlying scheduler/model's `__init__` method and eventually
                overwrite the same named arguments in `config`.

        Returns:
            [`ModelMixin`] or [`SchedulerMixin`]:
                A model or scheduler object instantiated from a config dictionary.

        Examples:

        ```python
        >>> from diffusers import DDPMScheduler, DDIMScheduler, PNDMScheduler

        >>> # Download scheduler from huggingface.co and cache.
        >>> scheduler = DDPMScheduler.from_pretrained("google/ddpm-cifar10-32")

        >>> # Instantiate DDIM scheduler class with same config as DDPM
        >>> scheduler = DDIMScheduler.from_config(scheduler.config)

        >>> # Instantiate PNDM scheduler class with same config as DDPM
        >>> scheduler = PNDMScheduler.from_config(scheduler.config)
        ```
        pretrained_model_name_or_pathNzFPlease make sure to provide a config as the first positional argument.zJIt is deprecated to pass a pretrained model name or path to `from_config`.	Schedulerz3If you were trying to load a scheduler, please use z.from_pretrained(...) instead. Otherwise, please make sure to pass a configuration dictionary instead. This functionality will be removed in v1.0.0.Modelz/If you were trying to load a model, please use z.load_config(...) followed by z.from_config(...) instead. Otherwise, please make sure to pass a configuration dictionary instead. This functionality will be removed in v1.0.0.zconfig-passed-as-pathrH   FrI   T)rj   return_unused_kwargsdtype_class_namer$   )
r/   
ValueError
isinstancerA   r*   r   load_configextract_init_dict_deprecated_kwargsrF   )
clsri   rm   r   rQ   	init_dictunused_kwargshidden_dictdeprecated_kwargmodelr$   r$   r%   from_config   sB   %






zConfigMixin.from_configc                 O   s,   d|  d}t dd|dd | j|i |S )Nz8 The function get_config_dict is deprecated. Please use zE.load_config instead. This function will be removed in version v1.0.0get_config_dictrH   FrI   )r   rr   )ru   r   r   rQ   r$   r$   r%   r|     s   
zConfigMixin.get_config_dictrj   c                 K   s  | dd}| dd}| dd}| dd}| dd}	| d	d}
| d
d}| dd}| dd}| dd}| di }i |ddi}t|}t|}| jdu r[tdtj|rd|}ntj|r|durtjtj	||| jrtj	||| j}ntjtj	|| jrtj	|| j}nt
d| j d| dzt|| j|||	||
|||||d}W np ty   t
| d ty   t
| d| d ty   t
| d| j d ty } z
t
d| d| d}~w ty   t
dt d| d| j d t
y)   t
d | d!| d"| j d#w z| |}t|}W n tjtfyH   t
d$| d%w |sQ|sQ|S |f}|r\||f7 }|rd||f7 }|S )&a
  
        Load a model or scheduler configuration.

        Parameters:
            pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
                Can be either:

                    - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
                      the Hub.
                    - A path to a *directory* (for example `./my_model_directory`) containing model weights saved with
                      [`~ConfigMixin.save_config`].

            cache_dir (`Union[str, os.PathLike]`, *optional*):
                Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
                is not used.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force the (re-)download of the model weights and configuration files, overriding the
                cached versions if they exist.
            proxies (`Dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
            output_loading_info(`bool`, *optional*, defaults to `False`):
                Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
            local_files_only (`bool`, *optional*, defaults to `False`):
                Whether to only load local model weights and configuration files or not. If set to `True`, the model
                won't be downloaded from the Hub.
            token (`str` or *bool*, *optional*):
                The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
                `diffusers-cli login` (stored in `~/.huggingface`) is used.
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
                allowed by Git.
            subfolder (`str`, *optional*, defaults to `""`):
                The subfolder location of a model file within a larger model repository on the Hub or locally.
            return_unused_kwargs (`bool`, *optional*, defaults to `False):
                Whether unused keyword arguments of the config are returned.
            return_commit_hash (`bool`, *optional*, defaults to `False):
                Whether the `commit_hash` of the loaded configuration are returned.

        Returns:
            `dict`:
                A dictionary of all the parameters stored in a JSON configuration file.

        	cache_dirN	local_dirlocal_dir_use_symlinksautoforce_downloadFproxiesrY   local_files_onlyrevisionmirror	subfolder
user_agent	file_typeri   z`self.config_name` is not defined. Note that one should not load a config from `ConfigMixin`. Please make sure to define `config_name` in a class inheriting from `ConfigMixin`zError no file named z found in directory .)filenamer}   r   r   r   rY   r   r   r   r~   r   z is not a local folder and is not a valid model identifier listed on 'https://huggingface.co/models'
If this is a private repository, make sure to pass a token having permission to this repo with `token` or log in with `huggingface-cli login`.z is not a valid git identifier (branch name, tag name or commit id) that exists for this model name. Check the model page at 'https://huggingface.co/z' for available revisions.z& does not appear to have a file named z:There was a specific connection error when trying to load z:
zWe couldn't connect to 'zM' to load this model, couldn't find it in the cached files and it looks like z- is not the path to a directory containing a z file.
Checkout your internet connection or see how to run the library in offline mode at 'https://huggingface.co/docs/diffusers/installation#offline-mode'.zCan't load config 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 filez"It looks like the config file at 'z' is not a valid JSON file.)r/   r   strr?   rp   r\   r]   r^   isdirra   EnvironmentErrorr	   r   r   r
   r   r   _dict_from_json_filer   jsonJSONDecodeErrorUnicodeDecodeError)ru   rj   rm   return_commit_hashr   r}   r~   r   r   r   rY   r   r   _r   r   config_fileerrconfig_dictcommit_hashoutputsr$   r$   r%   rr     s   5




zConfigMixin.load_configc                 C   s   t tt| jj S N)setrA   inspect	signaturer   
parameterskeys)input_classr$   r$   r%   _get_init_keys  s   zConfigMixin._get_init_keysc              	      s  | dg fdd| D }t| }| | }|d d|v r*|d t| dr:| jD ]}|| q2t| jdkrH|t	| j }t
tdd }| jr_d	d
 |  D }ng }t	  |D ]}| |}	 |	 qf | |    fdd| D }|d| j}
t|
tr|
| jkrt||
rt||
}| || fdd| D }nt|
tst|
ttfstddd | D }i |D ](}||v r||v r||||< ||v r|||< q||v r|||< qt|dkrtd| d| j d| j d t	 }t|| dkr*t||  d i ||}fdd| D }||fS )N_use_default_valuesc                    s&   i | ]\}}| vr|d kr||qS )r   r$   .0kv)used_defaultsr$   r%   
<dictcomp>  s   & z1ConfigMixin.extract_init_dict.<locals>.<dictcomp>r   r   _flax_internal_argsr   r   c                 S   s   g | ]	}t |ts|qS r$   )rq   r   )r   cr$   r$   r%   
<listcomp>      z1ConfigMixin.extract_init_dict.<locals>.<listcomp>c                       i | ]\}}| vr||qS r$   r$   r   )expected_keys_comp_clsr$   r%   r         ro   c                    r   r$   r$   r   )unexpected_keys_from_origr$   r%   r     r   z\Make sure that the `_class_name` is of type string or list of string (for custom pipelines).c                 S       i | ]\}}| d s||qS r   
startswithr   r$   r$   r%   r          zThe config attributes z were passed to z?, but are not expected and will be ignored. Please verify your z configuration file.zG was not found in config. Values will be initialized to default values.c                    r   r$   r$   r   )rv   r$   r%   r   #  r   )getr   rA   r   remover4   r   lenignore_for_configr   	importlibimport_moduler*   rd   has_compatibles_get_compatiblesunionr/   rq   r   getattrlisttuplerp   rB   warningr?   r   rc   )ru   r   r   original_dictexpected_keysargdiffusers_librarycompatible_classesr   expected_keys_corig_cls_nameorig_clsr    passed_keysrw   hidden_config_dictr$   )r   rv   r   r   r%   rs     sv   








zConfigMixin.extract_init_dict	json_filec                 C   s@   t |ddd}| }W d    n1 sw   Y  t|S )Nrutf-8encoding)openreadr   loads)ru   r   readertextr$   r$   r%   r   '  s   

z ConfigMixin._dict_from_json_filec                 C   s   | j j d|   S )N )r#   r*   to_json_stringr   r$   r$   r%   __repr__-  s   zConfigMixin.__repr__c                 C   s   | j S )z
        Returns the config of the class as a frozen dictionary

        Returns:
            `Dict[str, Any]`: Config of the class.
        )r>   r   r$   r$   r%   ri   0  s   zConfigMixin.configc                    sr   t | dr| jni }| jj|d< t|d< dd   fdd| D }|dd	 |d
d	 tj|dddd S )z
        Serializes the configuration instance to a JSON string.

        Returns:
            `str`:
                String containing all the attributes that make up the configuration instance in JSON format.
        r>   ro   _diffusers_versionc                 S   s.   t | tjr|  } | S t | tr|  } | S r   )rq   npndarraytolistr   as_posix)r!   r$   r$   r%   to_json_saveableF  s   
z4ConfigMixin.to_json_string.<locals>.to_json_saveablec                    s   i | ]	\}}| |qS r$   r$   r   r   r$   r%   r   M  r   z.ConfigMixin.to_json_string.<locals>.<dictcomp>_ignore_filesNr      T)indent	sort_keys
)	r4   r>   r#   r*   r   r   r/   r   dumps)r   r   r$   r   r%   r   :  s   zConfigMixin.to_json_stringjson_file_pathc                 C   sB   t |ddd}||   W d   dS 1 sw   Y  dS )z
        Save the configuration instance's parameters to a JSON file.

        Args:
            json_file_path (`str` or `os.PathLike`):
                Path to the JSON file to save a configuration instance's parameters.
        wr   r   N)r   writer   )r   r   writerr$   r$   r%   rb   T  s   "zConfigMixin.to_json_file)FNF)FF)"r*   r:   r;   __doc__r?   r   r   rt   rF   r   r   rR   r   r\   PathLikeboolrh   classmethodr   r   r{   r|   r   r   rr   staticmethodr   rs   r   r   propertyri   r   rb   r$   r$   r$   r%   r=   W   sD    *"Y
 $

_	r=   c                    s   t   fdd}|S )a  
    Decorator to apply on the init of classes inheriting from [`ConfigMixin`] so that all the arguments are
    automatically sent to `self.register_for_config`. To ignore a specific argument accepted by the init but that
    shouldn't be registered in the config, use the `ignore_for_config` class variable

    Warning: Once decorated, all private arguments (beginning with an underscore) are trashed and not sent to the init!
    c                    s*  dd |  D dd |  D }t| ts!td| jj dt| dg  i t} fddt	|j
  D }t|| D ]\}}||< qC fdd|  D  tt t d	krxtt t d
< i |t| ddi  | g|R i  d S )Nc                 S   r   r   r   r   r$   r$   r%   r   l  r   z:register_to_config.<locals>.inner_init.<locals>.<dictcomp>c                 S   s    i | ]\}}| d r||qS r   r   r   r$   r$   r%   r   m  r   &`@register_for_config` was applied to A init method, but this class does not inherit from `ConfigMixin`.r   c                    s,   i | ]\}\}}|d kr| vr||j qS )r   )default)r   ir7   p)ignorer$   r%   r   x  s    &c                    s.   i | ]\}}| vr|vr| ||qS r$   )r   )r   r   r   r   init_kwargs
new_kwargsr$   r%   r     s
    r   r   rF   r$   )r   rq   r=   RuntimeErrorr#   r*   r   r   r   	enumerater   zipr   r0   r   r   r   )r   r   r   config_init_kwargsr   r   r   r7   initr   r%   
inner_initi  s0   



	z&register_to_config.<locals>.inner_init)	functoolswraps)r   r  r$   r   r%   rF   `  s   	%rF   c                    s&   | j  t  fdd}|| _ | S )Nc                    s&  t | tstd| jj dt| }t| }i }|D ] }|j	| j
v r'qt|jtjkr5d ||j	< qt| |j	||j	< qi ||}d|v rN|d t|D ]\}}	|| j	}
|	||
< qRtt| t| dkr|tt| t| |d< t| ddi |  | g|R i | d S )Nr   r   rn   r   r   rF   r$   )rq   r=   r   r#   r*   rA   r   dataclassesfieldsr7   r   rM   r   _MISSING_TYPEr   r/   r   r   r   r   r   )r   r   r   r   r  default_kwargsfieldr   r   r   r7   original_initr$   r%   r     s.   




z%flax_register_to_config.<locals>.init)r   r  r  )ru   r   r$   r	  r%   flax_register_to_config  s
   (r  c                   @   s4   e Zd ZdZeddeeeee	f f fddZ
dS )LegacyConfigMixinz
    A subclass of `ConfigMixin` to resolve class mapping from legacy classes (like `Transformer2DModel`) to more
    pipeline-specific classes (like `DiTTransformer2DModel`).
    NFri   c                 K   s*   ddl m} ||| }|j||fi |S )Nr   )_fetch_remapped_cls_from_config)models.model_loading_utilsr  r{   )ru   ri   rm   r   r  remapped_classr$   r$   r%   r{     s   
zLegacyConfigMixin.from_configr   )r*   r:   r;   r   r   r   r   r   r   r   r{   r$   r$   r$   r%   r    s    &r  )0r   r  r  r   r   r   r\   recollectionsr   pathlibr   typingr   r   r   r   numpyr   huggingface_hubr   r	   huggingface_hub.utilsr
   r   r   r   requestsr    r   utilsr   r   r   r   r   r   
get_loggerr*   rB   compile_re_configuration_filer   r=   rF   r  r  r$   r$   r$   r%   <module>   s8    


     20