U
    +-eI                     @   s  d dl m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mZ d dlmZmZ d dlmZ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  e!e"Z#e rd dl$Z%d$ddZ&dd Z'dd Z(d%ee)ee* dddZ+d&ee,ef eee,ef  e)e)eee-e,f  dddZ.ddddZ/e ddddddddddddddde,ee* e,e)ee, ee, ee, ee) eeee, e,f  eeee, e,f  eeee, e,f  ee, e)eee-e,f  e)d d!d"Z0G d#d deZ1dS )'    N)Path)copytree)AnyDictListOptionalUnion)ModelHubMixinsnapshot_download)get_tf_versionis_graphviz_availableis_pydot_availableis_tf_available	yaml_dump   )CONFIG_NAME)HfApi)SoftTemporaryDirectoryloggingvalidate_hf_hub_args c                 C   sd   g }|   D ]N\}}|r&| d| n|}t|tjrL|t||   q|||f qt|S )a  Flatten a nested dictionary.
    Reference: https://stackoverflow.com/a/6027615/10319735

    Args:
        dictionary (`dict`):
            The nested dictionary to be flattened.
        parent_key (`str`):
            The parent key to be prefixed to the children keys.
            Necessary for recursing over the nested dictionary.

    Returns:
        The flattened dictionary.
    .)items
isinstancecollectionsMutableMappingextend_flatten_dictappenddict)
dictionaryZ
parent_keyr   keyvalueZnew_key r#   \/var/www/html/Darija-Ai-Train/env/lib/python3.8/site-packages/huggingface_hub/keras_mixin.pyr      s    r   c                 C   sd   | j dk	r\| j  }t|}tjj j|d< d}| D ]\}}|d| d| d7 }q:nd}|S )z6Parse hyperparameter dictionary into a markdown table.NZtraining_precisionz*| Hyperparameters | Value |
| :-- | :-- |
z| z | z |
)	Z	optimizerZ
get_configr   tfkerasZmixed_precisionZglobal_policynamer   )modelZoptimizer_paramstabler!   r"   r#   r#   r$   _create_hyperparameter_table:   s    

r*   c                 C   s*   t jjj| | dddddddd d	 d S )N
/model.pngFTTB`   )Zto_fileZshow_shapesZ
show_dtypeZshow_layer_namesZrankdirZexpand_nestedZdpiZlayer_range)r%   r&   utils
plot_model)r(   save_directoryr#   r#   r$   _plot_networkI   s    r1   T)repo_dirr/   metadatac           
   	   C   sL  t | }|r"t r"t r"t| | |dkr.i }| d}d|d< d}|t|dd7 }|d7 }|d7 }|d	7 }|d
7 }|dk	r|d7 }|d7 }|d7 }||7 }|d7 }|rtj| dr|d7 }|d7 }|d7 }d}|d| d7 }|d7 }tj|r t|ddd}|	 }	W 5 Q R X n|}	t|ddd}|
|	 W 5 Q R X dS )z2
    Creates a model card for the repository.
    Nz
/README.mdr&   library_namez---
F)Zdefault_flow_stylez/
## Model description

More information needed
z9
## Intended uses & limitations

More information needed
z:
## Training and evaluation data

More information needed
z
## Training procedure
z
### Training hyperparameters
z;
The following hyperparameters were used during training:


r+   z
 ## Model Plot
z

<details>z$
<summary>View Model Plot</summary>
z./model.pngz
![Model Image](z)
z
</details>rutf8encodingwutf-8)r*   r   r   r1   r   ospathexistsopenreadwrite)
r(   r2   r/   r3   ZhyperparametersZreadme_pathZ
model_cardZpath_to_plotfZreadmer#   r#   r$   _create_model_cardW   s@    	

rC   F)r0   configinclude_optimizerr/   tagsc              	   K   s  t  rddl}ntd| js&tdt|}|jddd |rt|ts^t	dt
| d|t d	}t|| W 5 Q R X i }	t|tr||	d
< nt|tr|g|	d
< |dd}
|
dk	rtdt d
|	kr|	d
 |
 n
|
g|	d
< | jdk	rZ| jji krZ|d }| r*tdt |jd	dd}tj| jj|ddd W 5 Q R X t| |||	 |jjj| |fd|i| dS )aE  
    Saves a Keras model to save_directory in SavedModel format. Use this if
    you're using the Functional or Sequential APIs.

    Args:
        model (`Keras.Model`):
            The [Keras
            model](https://www.tensorflow.org/api_docs/python/tf/keras/Model)
            you'd like to save. The model must be compiled and built.
        save_directory (`str` or `Path`):
            Specify directory in which you want to save the Keras model.
        config (`dict`, *optional*):
            Configuration object to be saved alongside the model weights.
        include_optimizer(`bool`, *optional*, defaults to `False`):
            Whether or not to include optimizer in serialization.
        plot_model (`bool`, *optional*, defaults to `True`):
            Setting this to `True` will plot the model and put it in the model
            card. Requires graphviz and pydot to be installed.
        tags (Union[`str`,`list`], *optional*):
            List of tags that are related to model or string of a single tag. See example tags
            [here](https://github.com/huggingface/hub-docs/blame/main/modelcard.md).
        model_save_kwargs(`dict`, *optional*):
            model_save_kwargs will be passed to
            [`tf.keras.models.save_model()`](https://www.tensorflow.org/api_docs/python/tf/keras/models/save_model).
    r   Nz>Called a Tensorflow-specific function but could not import it.z+Model should be built before trying to saveT)parentsexist_okzAProvided config to save_pretrained_keras should be a dict. Got: ''r:   rF   	task_namez>`task_name` input argument is deprecated. Pass `tags` instead.zhistory.jsonzZ`history.json` file already exists, it will be overwritten by the history of this version.r;   r8      )indent	sort_keysrE   )r   
tensorflowImportErrorZbuilt
ValueErrorr   mkdirr   r   RuntimeErrortyper   r?   jsondumpliststrpopwarningswarnFutureWarningr   historyr>   UserWarningrC   r&   modelsZ
save_model)r(   r0   rD   rE   r/   rF   model_save_kwargsr%   rB   r3   rJ   r=   r#   r#   r$   save_pretrained_keras   sL    "







 r`   KerasModelHubMixin)returnc                  O   s   t j| |S )a  
    Instantiate a pretrained Keras model from a pre-trained model from the Hub.
    The model is expected to be in `SavedModel` format.

    Args:
        pretrained_model_name_or_path (`str` or `os.PathLike`):
            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
                  [`~transformers.PreTrainedModel.save_pretrained`], e.g.,
                  `./my_model_directory/`.
                - `None` if you are both providing the configuration and state
                  dictionary (resp. with keyword arguments `config` and
                  `state_dict`).
        force_download (`bool`, *optional*, defaults to `False`):
            Whether to force the (re-)download of the model weights and
            configuration files, overriding the cached versions if they exist.
        resume_download (`bool`, *optional*, defaults to `False`):
            Whether to delete incompletely received files. Will attempt 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.
        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 `transformers-cli
            login` (stored in `~/.huggingface`).
        cache_dir (`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.
        local_files_only(`bool`, *optional*, defaults to `False`):
            Whether to only look at local files (i.e., do not try to download
            the model).
        model_kwargs (`Dict`, *optional*):
            model_kwargs will be passed to the model during initialization

    <Tip>

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

    </Tip>
    )ra   Zfrom_pretrained)argskwargsr#   r#   r$   from_pretrained_keras   s    8re   z'Push Keras model using huggingface_hub.)rD   commit_messageprivateapi_endpointtokenbranch	create_prallow_patternsignore_patternsdelete_patternslog_dirrE   rF   r/   )repo_idrD   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rE   rF   r/   c                K   s   t |d}|j|||ddj}t }t|| }t| |f||||d| |dk	r|dkrbg nt|trr|gn|}|d t	||d  |j
d|||||||	|
|d	
W  5 Q R  S Q R X dS )
a  
    Upload model checkpoint to the Hub.

    Use `allow_patterns` and `ignore_patterns` to precisely filter which files should be pushed to the hub. Use
    `delete_patterns` to delete existing remote files in the same commit. See [`upload_folder`] reference for more
    details.

    Args:
        model (`Keras.Model`):
            The [Keras model](`https://www.tensorflow.org/api_docs/python/tf/keras/Model`) you'd like to push to the
            Hub. The model must be compiled and built.
        repo_id (`str`):
                ID of the repository to push to (example: `"username/my-model"`).
        commit_message (`str`, *optional*, defaults to "Add Keras model"):
            Message to commit while pushing.
        private (`bool`, *optional*, defaults to `False`):
            Whether the repository created should be private.
        api_endpoint (`str`, *optional*):
            The API endpoint to use when pushing the model to the hub.
        token (`str`, *optional*):
            The token to use as HTTP bearer authorization for remote files. If
            not set, will use the token set when logging in with
            `huggingface-cli login` (stored in `~/.huggingface`).
        branch (`str`, *optional*):
            The git branch on which to push the model. This defaults to
            the default branch as specified in your repository, which
            defaults to `"main"`.
        create_pr (`boolean`, *optional*):
            Whether or not to create a Pull Request from `branch` with that commit.
            Defaults to `False`.
        config (`dict`, *optional*):
            Configuration object to be saved alongside the model weights.
        allow_patterns (`List[str]` or `str`, *optional*):
            If provided, only files matching at least one pattern are pushed.
        ignore_patterns (`List[str]` or `str`, *optional*):
            If provided, files matching any of the patterns are not pushed.
        delete_patterns (`List[str]` or `str`, *optional*):
            If provided, remote files matching any of the patterns will be deleted from the repo.
        log_dir (`str`, *optional*):
            TensorBoard logging directory to be pushed. The Hub automatically
            hosts and displays a TensorBoard instance if log files are included
            in the repository.
        include_optimizer (`bool`, *optional*, defaults to `False`):
            Whether or not to include optimizer during serialization.
        tags (Union[`list`, `str`], *optional*):
            List of tags that are related to model or string of a single tag. See example tags
            [here](https://github.com/huggingface/hub-docs/blame/main/modelcard.md).
        plot_model (`bool`, *optional*, defaults to `True`):
            Setting this to `True` will plot the model and put it in the model
            card. Requires graphviz and pydot to be installed.
        model_save_kwargs(`dict`, *optional*):
            model_save_kwargs will be passed to
            [`tf.keras.models.save_model()`](https://www.tensorflow.org/api_docs/python/tf/keras/models/save_model).

    Returns:
        The url of the commit of your model in the given repository.
    )ZendpointT)rp   ri   rg   rH   )rD   rE   rF   r/   Nzlogs/*Zlogsr(   )
Z	repo_typerp   Zfolder_pathrf   ri   revisionrk   rl   rm   rn   )r   Zcreate_reporp   r   r   r`   r   rW   r   r   Zupload_folder)r(   rp   rD   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rE   rF   r/   r_   apitmpZ
saved_pathr#   r#   r$   push_to_hub_keras  sH    N
	
rt   c                   @   s$   e Zd ZdZdd Zedd ZdS )ra   aA  
    Implementation of [`ModelHubMixin`] to provide model Hub upload/download
    capabilities to Keras models.


    ```python
    >>> import tensorflow as tf
    >>> from huggingface_hub import KerasModelHubMixin


    >>> class MyModel(tf.keras.Model, KerasModelHubMixin):
    ...     def __init__(self, **kwargs):
    ...         super().__init__()
    ...         self.config = kwargs.pop("config", None)
    ...         self.dummy_inputs = ...
    ...         self.layer = ...

    ...     def call(self, *args):
    ...         return ...


    >>> # Initialize and compile the model as you normally would
    >>> model = MyModel()
    >>> model.compile(...)
    >>> # Build the graph by training it or passing dummy inputs
    >>> _ = model(model.dummy_inputs)
    >>> # Save model weights to local directory
    >>> model.save_pretrained("my-awesome-model")
    >>> # Push model weights to the Hub
    >>> model.push_to_hub("my-awesome-model")
    >>> # Download and initialize weights from the Hub
    >>> model = MyModel.from_pretrained("username/super-cool-model")
    ```
    c                 C   s   t | | d S )N)r`   )selfr0   r#   r#   r$   _save_pretrained  s    z#KerasModelHubMixin._save_pretrainedc	                 K   sf   t  rddl}
ntd|	dd}tj|sFt|||dt d}n|}|
j	j
j|f|	}||_|S )a   Here we just call [`from_pretrained_keras`] function so both the mixin and
        functional APIs stay in sync.

                TODO - Some args above aren't used since we are calling
                snapshot_download instead of hf_hub_download.
        r   Nz>Called a TensorFlow-specific function but could not import it.rD   r&   )rp   rq   	cache_dirr4   Zlibrary_version)r   rN   rO   rX   r<   r=   isdirr
   r   r&   r^   Z
load_modelrD   )clsZmodel_idrq   rw   Zforce_downloadproxiesZresume_downloadZlocal_files_onlyri   Zmodel_kwargsr%   cfgZstorage_folderr(   r#   r#   r$   _from_pretrained  s     
z#KerasModelHubMixin._from_pretrainedN)__name__
__module____qualname____doc__rv   classmethodr|   r#   r#   r#   r$   ra     s   #)r   )TN)NFTN)2collections.abcabcr   rT   r<   rY   pathlibr   shutilr   typingr   r   r   r   r   Zhuggingface_hubr	   r
   Zhuggingface_hub.utilsr   r   r   r   r   	constantsr   Zhf_apir   r.   r   r   r   Z
get_loggerr}   loggerrN   r%   r   r*   r1   boolr   rC   rW   rV   r`   re   rt   ra   r#   r#   r#   r$   <module>   s   

  0    
U;y