a
    d_                     @   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 ddlmZmZmZmZmZmZmZ eeZdd Zeeejf d	d
dZdd Zdd Zdd Zdd Z dd Z!d$eeejf eeeeejf  e"e"eeeef  eee"ef  ee e"ee ee dddZ#d%eeeejf eeeejf  e"e"eeeef  eee"ef  ee e"ee ee dddZ$d&ddZ%dd  Z&d!Z'd"d# Z(dS )'z3Utilities to dynamically load objects from the Hub.    N)Path)DictOptionalUnion   )HF_MODULES_CACHE TRANSFORMERS_DYNAMIC_MODULE_NAMEcached_fileextract_commit_hashis_offline_modeloggingtry_to_load_from_cachec                  C   sP   t tjv rdS tjt  tjt dd tt d } |  sL|   t	
  dS )z_
    Creates the cache directory for modules with an init, and adds it to the Python path.
    NTexist_ok__init__.py)r   syspathappendosmakedirsr   existstouch	importlibinvalidate_caches)	init_path r   j/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/transformers/dynamic_module_utils.pyinit_hf_modules(   s    
r   )namec                 C   sX   t   tt|  }|j s&t|j tj|dd |d }| sT|  t	
  dS )zF
    Creates a dynamic module in the cache directory for modules.
    Tr   r   N)r   r   r   parentr   create_dynamic_moduler   r   r   r   r   )r   Zdynamic_module_pathr   r   r   r   r    8   s    

r    c                 C   sj   t | ddd}| }W d   n1 s,0    Y  tjd|tjd}|tjd|tjd7 }tt|S )z
    Get the list of modules that are relatively imported in a module file.

    Args:
        module_file (`str` or `os.PathLike`): The module file to inspect.
    rutf-8encodingNz^\s*import\s+\.(\S+)\s*$flagsz^\s*from\s+\.(\S+)\s+import)openreadrefindall	MULTILINElistset)module_filefcontentZrelative_importsr   r   r   get_relative_importsH   s
    &r1   c                    s   d}| g}g  |sg }|D ]}| t| qt| jfdd|D } fdd|D }dd |D }t|dk}  | q S )a)  
    Get the list of all files that are needed for a given module. Note that this function recurses through the relative
    imports (if a imports b and b imports c, it will return module files for b and c).

    Args:
        module_file (`str` or `os.PathLike`): The module file to inspect.
    Fc                    s   g | ]}t  | qS r   )str).0m)module_pathr   r   
<listcomp>m       z-get_relative_import_files.<locals>.<listcomp>c                    s   g | ]}| vr|qS r   r   r3   r/   )all_relative_importsr   r   r6   n   r7   c                 S   s   g | ]}| d qS ).pyr   r8   r   r   r   r6   o   r7   r   )extendr1   r   r   len)r.   Z	no_changeZfiles_to_checkZnew_importsr/   Znew_import_filesr   )r9   r5   r   get_relative_import_filesZ   s    
r=   c                 C   s   t | ddd}| }W d   n1 s,0    Y  tjdd|tjtjB d}tjd|tjd}|tjd	|tjd7 }d
d |D }tt|S )zA
    Extracts all the libraries that are imported in a file.
    r!   r"   r#   Nz \s*try\s*:\s*.*?\s*except\s*.*?: r%   z^\s*import\s+(\S+)\s*$z^\s*from\s+(\S+)\s+importc                 S   s$   g | ]}| d s|d d qS ).r   )
startswithsplit)r3   impr   r   r   r6      r7   zget_imports.<locals>.<listcomp>)	r'   r(   r)   subr+   DOTALLr*   r,   r-   )filenamer/   r0   importsr   r   r   get_importsw   s    &rG   c              	   C   sx   t | }g }|D ]0}zt| W q ty>   || Y q0 qt|dkrptdd| dd| dt| S )zi
    Check if the current Python environment contains all the libraries that are imported in a file.
    r   z\This modeling file requires the following packages that were not found in your environment: z, z. Run `pip install  `)rG   r   import_moduleImportErrorr   r<   joinr1   )rE   rF   Zmissing_packagesrB   r   r   r   check_imports   s     rM   c                 C   s$   | tjjd}t|}t|| S )zY
    Import a module on the cache directory for modules and extract a class from it.
    r?   )replacer   r   sepr   rJ   getattr)
class_namer5   moduler   r   r   get_class_in_module   s    
rS   F)pretrained_model_name_or_pathr.   	cache_dirforce_downloadresume_downloadproxiesuse_auth_tokenrevisionlocal_files_only	repo_type_commit_hashc                 C   s  t  r|std d}t| } tj| }|rD| tjjd }n"| 	dtjj}t
| |||
|	d}g }z8t| |||||||||	|
d}|s||kr|| W n, ty   td| d|  d	  Y n0 t|}ttjj | }t| tt| }|| tjjd kr||  r8t|t|| sPt|||  t  |D ]Z}| d
}tj| |}||  rt|t|| sTt|||  t  qTnt||
}|| }|tjj | }t| ||  st|||  t  |D ]L}|| d
  st| | d
||||||||d
 || d
 qt|dkr|du rddd |D }|	du rdn|	 d}d| |  }td| d| d tj||S )a
  
    Prepares Downloads a module from a local folder or a distant repo and returns its path inside the cached
    Transformers module.

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

            - a string, the *model id* of a pretrained model configuration 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 configuration file saved using the
              [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.

        module_file (`str`):
            The name of the module file containing the class to look for.
        cache_dir (`str` or `os.PathLike`, *optional*):
            Path to a directory in which a downloaded pretrained model configuration 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 configuration 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`, 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.
        local_files_only (`bool`, *optional*, defaults to `False`):
            If `True`, will only try to load the tokenizer configuration from local files.
        repo_type (`str`, *optional*):
            Specify the repo type (useful when downloading from a space for instance).

    <Tip>

    Passing `use_auth_token=True` is required when you want to use a private model.

    </Tip>

    Returns:
        `str`: The path to the module inside the cache.
    z+Offline mode: forcing local_files_only=TrueT/)rU   rZ   r\   )	rU   rV   rX   rW   r[   rY   rZ   r\   r]   zCould not locate the z inside r?   r:   )rU   rV   rW   rX   rY   rZ   r[   r]   r   N
c                 S   s   g | ]}d | qS )z- r   r8   r   r   r   r6   A  r7   z*get_cached_module_file.<locals>.<listcomp>r>   zs/zhttps://huggingface.co/z9A new version of the following files was downloaded from z:
z
. Make sure to double-check they do not contain any added malicious code. To avoid downloading new versions of the code file, you can pin a revision.) r   loggerinfor2   r   r   isdirrA   rO   rN   r   r	   r   EnvironmentErrorerrorrM   r   r    r   r   r   filecmpcmpshutilcopyr   r   rL   r
   get_cached_module_filer<   warning)rT   r.   rU   rV   rW   rX   rY   rZ   r[   r\   r]   is_local	submoduleZcached_moduleZ	new_filesZresolved_module_fileZmodules_neededZfull_submoduleZsubmodule_pathZmodule_neededZmodule_needed_fileZcommit_hashZrepo_type_strurlr   r   r   rj      s    =




rj   )class_referencerT   rU   rV   rW   rX   rY   rZ   r[   r\   code_revisionc                 K   sp   d| v r|  d\}} n|}|  d\}}|
du r>||kr>|}
t||d ||||||
||	d
}t||ddS )a
  
    Extracts a class from a module file, present in the local folder or repository of a model.

    <Tip warning={true}>

    Calling this function will execute the code in the module file found locally or downloaded from the Hub. It should
    therefore only be called on trusted repos.

    </Tip>

    Args:
        class_reference (`str`):
            The full name of the class to load, including its module and optionally its repo.
        pretrained_model_name_or_path (`str` or `os.PathLike`):
            This can be either:

            - a string, the *model id* of a pretrained model configuration 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 configuration file saved using the
              [`~PreTrainedTokenizer.save_pretrained`] method, e.g., `./my_model_directory/`.

            This is used when `class_reference` does not specify another repo.
        module_file (`str`):
            The name of the module file containing the class to look for.
        class_name (`str`):
            The name of the class to import in the module.
        cache_dir (`str` or `os.PathLike`, *optional*):
            Path to a directory in which a downloaded pretrained model configuration 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 configuration 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`, 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.
        local_files_only (`bool`, *optional*, defaults to `False`):
            If `True`, will only try to load the tokenizer configuration from local files.
        repo_type (`str`, *optional*):
            Specify the repo type (useful when downloading from a space for instance).
        code_revision (`str`, *optional*, defaults to `"main"`):
            The specific revision to use for the code on the Hub, if the code leaves in a different repository than the
            rest of the model. 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>

    Passing `use_auth_token=True` is required when you want to use a private model.

    </Tip>

    Returns:
        `type`: The class, dynamically imported from the module.

    Examples:

    ```python
    # Download module `modeling.py` from huggingface.co and cache then extract the class `MyBertModel` from this
    # module.
    cls = get_class_from_dynamic_module("modeling.MyBertModel", "sgugger/my-bert-model")

    # Download module `modeling.py` from a given repo and cache then extract the class `MyBertModel` from this
    # module.
    cls = get_class_from_dynamic_module("sgugger/my-bert-model--modeling.MyBertModel", "sgugger/another-bert-model")
    ```z--r?   Nr:   )rU   rV   rW   rX   rY   rZ   r[   r\   r>   )rA   rj   rS   rN   )ro   rT   rU   rV   rW   rX   rY   rZ   r[   r\   rp   kwargsZrepo_idr.   rQ   Zfinal_moduler   r   r   get_class_from_dynamic_moduleM  s&    Yrr   c           	         s    j dkr&td  d| d dS  fdd}t|ttfrT|D ]}|| qDn|durd|| g }tj j  j}t	|t	|j
 }t|| || t|D ],}t	|t	|j
 }t|| || q|S )a  
    Save the modeling files corresponding to a custom model/configuration/tokenizer etc. in a given folder. Optionally
    adds the proper fields in a config.

    Args:
        obj (`Any`): The object for which to save the module files.
        folder (`str` or `os.PathLike`): The folder where to save.
        config (`PretrainedConfig` or dictionary, `optional`):
            A config in which to register the auto_map corresponding to this custom object.
    __main__z We can't save the code defining z in z as it's been defined in __main__. You should put this code in a separate module so we can include it in the saved folder and make it easier to share via the Hub.Nc           
         s
   j j}|dd }| d j j }d|v rd }d } j jdr| d j j }t dd d urt d}|j}|dd }| d|j }n| d j j }||f}t| tr| di }	||	 j	< |	| d< n*t| dd d ur|| j
 j	< n j	|i| _
d S )Nr?   r^   	TokenizerZFastslow_tokenizer_classauto_map)	__class__
__module__rA   __name__endswithrP   
isinstancedictgetZ_auto_classrv   )
_configmodule_nameZlast_moduleZ	full_nameru   Zfast_tokenizer_classZslow_tokenizerZslow_tok_module_nameZlast_slow_tok_modulerv   objr   r   _set_auto_map_in_config  s,    



z3custom_object_save.<locals>._set_auto_map_in_config)rx   ra   rk   r{   r,   tupler   modules__file__r   r   rh   ri   r   r=   )	r   folderconfigr   cfgresultZobject_file	dest_fileZneeded_filer   r   r   custom_object_save  s*    
 
r   c                 C   s   t dd S )Na  Loading this model requires you to execute the configuration file in that repo on your local machine. We asked if it was okay but did not get an answer. Make sure you have read the code there to avoid malicious use, then set the option `trust_remote_code=True` to remove this error.)
ValueError)signumframer   r   r   _raise_timeout_error  s    r      c                 C   s   | d u r|rd} n|rt dkrttjt tt  | d u rxtd| d| d}| dv rfd} q6| dv r6d} q6td n|rtd d  |r|s| std| d	| S )
NFr   zLoading zl requires to execute some code in that repo, you can inspect the content of the repository at https://hf.co/zX. You can dismiss this prompt by passing `trust_remote_code=True`.
Do you accept? [y/N] )yesy1T)non0r>   z requires you to execute the configuration file in that repo on your local machine. Make sure you have read the code there to avoid malicious use, then set the option `trust_remote_code=True` to remove this error.)TIME_OUT_REMOTE_CODEsignalSIGALRMr   alarminputlowerr   )Ztrust_remote_codeZ
model_nameZhas_local_codeZhas_remote_codeZanswerr   r   r   resolve_trust_remote_code  s0    


r   )	NFFNNNFNN)	NFFNNNFNN)N))__doc__rf   r   r   r)   rh   r   r   pathlibr   typingr   r   r   utilsr   r   r	   r
   r   r   r   Z
get_loggerry   ra   r   r2   PathLiker    r1   r=   rG   rM   rS   boolrj   rr   r   r   r   r   r   r   r   r   <module>   s   $
          )         q
I