o
    i)                     @   s   d dl Z d dlZd dlZd dlmZmZ d dlZddlmZm	Z	 ddl
mZmZmZ ddlmZmZ ddlmZ e r?d dlZeeZG dd	 d	eZdS )
    N)DictOptional   )CONFIG_NAMEPYTORCH_WEIGHTS_NAME)cached_download
hf_hub_urlis_torch_available)HfApiHfFolder)
Repositoryc                   @   s   e Zd Zdd Z		d"dedee defdd	Zd
d Z	e
								d#dee dedee dedededee dee defddZe					d$dee dee dee dee dee dedefd d!ZdS )%ModelHubMixinc                 O   s   dS )a  
        Mix this class with your torch-model class for ease process of saving & loading from huggingface-hub

        Example::

            >>> from huggingface_hub import ModelHubMixin

            >>> class MyModel(nn.Module, ModelHubMixin):
            ...    def __init__(self, **kwargs):
            ...        super().__init__()
            ...        self.config = kwargs.pop("config", None)
            ...        self.layer = ...
            ...    def forward(self, ...)
            ...        return ...

            >>> model = MyModel()
            >>> model.save_pretrained("mymodel", push_to_hub=False) # Saving model weights in the directory
            >>> model.push_to_hub("mymodel", "model-1") # Pushing model-weights to hf-hub

            >>> # Downloading weights from hf-hub & model will be initialized from those weights
            >>> model = MyModel.from_pretrained("username/mymodel@main")
        N )selfargskwargsr   r   T/var/www/edux/Edux_v2/venv/lib/python3.10/site-packages/huggingface_hub/hub_mixin.py__init__   s    zModelHubMixin.__init__NFsave_directoryconfigpush_to_hubc                 K   s   t j|dd t|tr.t j|t}t|d}t	|| W d   n1 s)w   Y  t j|t
}| | |rE| j|fi |S dS )a  
        Saving weights in local directory.

        Parameters:
            save_directory (:obj:`str`):
                Specify directory in which you want to save weights.
            config (:obj:`dict`, `optional`):
                specify config (must be dict) incase you want to save it.
            push_to_hub (:obj:`bool`, `optional`, defaults to :obj:`False`):
                Set it to `True` in case you want to push your weights to huggingface_hub
            model_id (:obj:`str`, `optional`, defaults to :obj:`save_directory`):
                Repo name in huggingface_hub. If not specified, repo name will be same as `save_directory`
            kwargs (:obj:`Dict`, `optional`):
                kwargs will be passed to `push_to_hub`
        T)exist_okwN)osmakedirs
isinstancedictpathjoinr   openjsondumpr   _save_pretrainedr   )r   r   r   r   r   r   fr   r   r   save_pretrained.   s   

zModelHubMixin.save_pretrainedc                 C   s(   t | dr| jn| }t| | dS )zr
        Overwrite this method in case you don't want to save complete model, rather some specific layers
        moduleN)hasattrr%   torchsave
state_dict)r   r   model_to_saver   r   r   r"   T   s   zModelHubMixin._save_pretrainedTcpupretrained_model_name_or_pathstrictmap_locationforce_downloadresume_downloadproxiesuse_auth_token	cache_dirlocal_files_onlyc
              	   K   sv  |}t |}d}t|ddkr|d\}}|t v r.tt|v r.tj|t}n'zt	|t|d}t
||||||	|d}W n tjjyT   td d}Y nw |t v rgtd tj|t}nt	|t|d}t
||||||	|d}|durt|dd	d
}t|}W d   n1 sw   Y  |
d|i | di |
}t j||d}|j||d |  |S )a  
        Instantiate a pretrained pytorch model from a pre-trained model configuration from huggingface-hub.
        The model is set in evaluation mode by default using ``model.eval()`` (Dropout modules are deactivated). To
        train the model, you should first set it back in training mode with ``model.train()``.

        Parameters:
            pretrained_model_name_or_path (:obj:`str` or :obj:`os.PathLike`, `optional`):
                Can be either:
                    - A string, the `model id` of a pretrained model 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``.
                    - You can add `revision` by appending `@` at the end of model_id simply like this: ``dbmdz/bert-base-german-cased@main``
                      Revision is 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.
                    - A path to a `directory` containing model weights saved using
                      :func:`~transformers.PreTrainedModel.save_pretrained`, e.g., ``./my_model_directory/``.
                    - :obj:`None` if you are both providing the configuration and state dictionary (resp. with keyword
                      arguments ``config`` and ``state_dict``).
            cache_dir (:obj:`Union[str, 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 (:obj:`bool`, `optional`, defaults to :obj:`False`):
                Whether or not to force the (re-)download of the model weights and configuration files, overriding the
                cached versions if they exist.
            resume_download (:obj:`bool`, `optional`, defaults to :obj:`False`):
                Whether or not to delete incompletely received files. Will attempt to resume the download if such a
                file exists.
            proxies (:obj:`Dict[str, str], `optional`):
                A dictionary of proxy servers to use by protocol or endpoint, e.g., :obj:`{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
            local_files_only(:obj:`bool`, `optional`, defaults to :obj:`False`):
                Whether or not to only look at local files (i.e., do not try to download the model).
            use_auth_token (:obj:`str` or `bool`, `optional`):
                The token to use as HTTP bearer authorization for remote files. If :obj:`True`, will use the token
                generated when running :obj:`transformers-cli login` (stored in :obj:`~/.huggingface`).
            model_kwargs (:obj:`Dict`, `optional`)::
                model_kwargs will be passed to the model during initialization
        .. note::
            Passing :obj:`use_auth_token=True` is required when you want to use a private model.
        N@   )filenamerevision)r3   r/   r1   r0   r4   r2   z(config.json NOT FOUND in HuggingFace Hubz$LOADING weights from local directoryrzutf-8)encodingr   )r.   )r-   r   )r'   devicelensplitr   listdirr   r   r   r   r   requests
exceptionsRequestExceptionloggerwarningprintr   r   r    loadupdateload_state_dicteval)clsr,   r-   r.   r/   r0   r1   r2   r3   r4   model_kwargsmodel_idr8   config_file
config_url
model_file	model_urlr#   r   modelr)   r   r   r   from_pretrained[   sb   7

	

zModelHubMixin.from_pretrained	add modelrK   repo_urlcommit_messageorganizationprivatereturnc                 C   sN   |du r| }t  }|du rt j||||ddd}t| ||d}|j|dS )a  
        Parameters:
            save_directory (:obj:`Union[str, os.PathLike]`):
                Directory having model weights & config.
            model_id (:obj:`str`, `optional`, defaults to :obj:`save_directory`):
                Repo name in huggingface_hub. If not specified, repo name will be same as `save_directory`
            repo_url (:obj:`str`, `optional`):
                Specify this in case you want to push to existing repo in hub.
            organization (:obj:`str`, `optional`):
                Organization in which you want to push your model.
            private (:obj:`bool`, `optional`):
                private: Whether the model repo should be private (requires a paid huggingface.co account)
            commit_message (:obj:`str`, `optional`, defaults to :obj:`add model`):
                Message to commit while pushing

        Returns:
            url to commit on remote repo.
        NT)rU   rV   	repo_typer   )
clone_fromr2   )rT   )r   	get_tokenr
   create_repor   r   )r   rK   rS   rT   rU   rV   tokenrepor   r   r   r      s   	zModelHubMixin.push_to_hub)NF)Tr+   FFNNNF)NNrR   NN)__name__
__module____qualname__r   strr   r   boolr$   r"   classmethodr   rQ   staticmethodr   r   r   r   r   r      sz    
&	
or   )r    loggingr   typingr   r   r?   	constantsr   r   file_downloadr   r   r	   hf_apir
   r   
repositoryr   r'   	getLoggerr^   rB   objectr   r   r   r   r   <module>   s    
