U
    ”Ê¹j[L  ã                   @   sZ  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 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" ddl#m$Z$ e! %e&¡Z'dZ(eƒ �rzd dl)Z(W n$ e*k
�r   d dl+Z,e,j(Z(Y nX e$e$dœdd„Z-d)dd„Z.dd„ Z/dd„ Z0d*e	e1ee2 dœdd„Z3e-d+ee4e	f eee4ef  e1e1eee5e4f  dœdd„ƒZ6dd œd!d"„Z7e"e-dd#ddddddddddddd$œe4ee2 e4ee1 ee4 ee4 ee4 ee1 eeee4 e4f  eeee4 e4f  eeee4 e4f  ee4 e1eee5e4f  e1d%œd&d'„ƒƒZ8G d(d„ deƒZ9dS ),é    N©Úwraps)ÚPath)Úcopytree)ÚAnyÚDictÚListÚOptionalÚUnion)ÚModelHubMixinÚsnapshot_download)Úget_tf_versionÚis_graphviz_availableÚis_pydot_availableÚis_tf_availableÚ	yaml_dumpé   )Ú	constants)ÚHfApi)ÚSoftTemporaryDirectoryÚloggingÚvalidate_hf_hub_args)Ú	CallableT)ÚfnÚreturnc                    s   t ˆ ƒ‡ fdd„ƒ}|S )Nc                    s,   t | dƒstdˆ j› d�ƒ‚ˆ | f|ž|ŽS )NÚhistoryzCannot use 'zp': Keras 3.x is not supported. Please save models manually and upload them using `upload_folder` or `hf upload`.)ÚhasattrÚNotImplementedErrorÚ__name__)ÚmodelÚargsÚkwargs©r   © úZ/var/www/html/bwave/python/venv/lib/python3.8/site-packages/huggingface_hub/keras_mixin.pyÚ_inner+   s
    
ÿz'_requires_keras_2_model.<locals>._innerr   )r   r%   r#   r"   r$   Ú_requires_keras_2_model)   s    r&   Ú 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_keyr#   r#   r$   r.   7   s    þÿr.   c                 C   s`   d}| j dk	r\| j  ¡ }t|ƒ}tj ¡ j|d< d}| ¡ D ]\}}|d|› d|› d�7 }q<|S )z6Parse hyperparameter dictionary into a markdown table.NZtraining_precisionz*| Hyperparameters | Value |
| :-- | :-- |
z| z | z |
)Z	optimizerZ
get_configr.   ÚkerasZmixed_precisionZglobal_policyÚnamer)   )r   ÚtableZoptimizer_paramsr2   r3   r#   r#   r$   Ú_create_hyperparameter_tableT   s    

r7   c                 C   s(   t 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)r4   ÚutilsÚ
plot_model)r   Úsave_directoryr#   r#   r$   Ú_plot_networkb   s    ÷r>   T)Úrepo_dirr<   Úmetadatac                 C   s  |d }|  ¡ rdS t| ƒ}|r6tƒ r6tƒ r6t| |ƒ |dkrBi }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 }|røtj  |› d�¡rø|d7 }|d7 }|d7 }d}|d|› d�7 }|d7 }| |¡ dS )zd
    Creates a model card for the repository.

    Do not overwrite an existing README.md file.
    z	README.mdNr4   Ú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:

Ú
r8   z
 ## Model Plot
z

<details>z$
<summary>View Model Plot</summary>
z./model.pngz
![Model Image](z)
z
</details>)	Úexistsr7   r   r   r>   r   ÚosÚpathÚ
write_text)r   r?   r<   r@   Zreadme_pathZhyperparametersZ
model_cardZpath_to_plotr#   r#   r$   Ú_create_model_cardp   s:    
rG   F)r=   ÚconfigÚinclude_optimizerr<   Útagsc              	   K   s€  t dkrtdƒ‚| jstdƒ‚t|ƒ}|jddd� |r~t|tƒsVtdt	|ƒ› d�ƒ‚|t
j  d¡�}t ||¡ W 5 Q R X i }t|tƒr–||d	< nt|tƒrª|g|d	< | d
d¡}	|	dk	rìt dt¡ d	|krâ|d	  |	¡ n
|	g|d	< | jdk	�rT| jji k�rT|d }
|
 ¡ �r$t dt¡ |
jddd��}tj| jj|ddd� W 5 Q R X t| |||ƒ t jj| |fd|i|—Ž dS )aL  
    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/blob/main/modelcard.md?plain=1).
        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).
    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: 'ú'ÚwrJ   Ú	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.zutf-8)Úencodingé   )ÚindentÚ	sort_keysrI   )r4   ÚImportErrorZbuiltÚ
ValueErrorr   Úmkdirr*   r0   ÚRuntimeErrorÚtyper   ZCONFIG_NAMEÚopenÚjsonÚdumpÚlistÚstrÚpopÚwarningsÚwarnÚFutureWarningr/   r   rC   ÚUserWarningrG   ÚmodelsZ
save_model)r   r=   rH   rI   r<   rJ   Úmodel_save_kwargsÚfr@   rO   rE   r#   r#   r$   Úsave_pretrained_kerasœ   sJ    #




þ

þ rf   ÚKerasModelHubMixin)r   c                  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.
        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.
    )rg   Zfrom_pretrained)r    r!   r#   r#   r$   Úfrom_pretrained_kerasð   s    2rh   z'Push Keras model using huggingface_hub.)rH   Úcommit_messageÚprivateÚapi_endpointÚtokenÚbranchÚ	create_prÚallow_patternsÚignore_patternsÚdelete_patternsÚlog_dirrI   rJ   r<   )Úrepo_idrH   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rI   rJ   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*):
            Whether the repository created should be private.
            If `None` (default), the repo will be public unless the organization's default is 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
            `hf auth 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/blob/main/modelcard.md?plain=1).
        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)rs   rl   rj   rL   )rH   rI   rJ   r<   Nzlogs/*Zlogsr   )
Z	repo_typers   Zfolder_pathri   rl   Úrevisionrn   ro   rp   rq   )r   Zcreate_repors   r   r   rf   r*   r]   r/   r   Zupload_folder)r   rs   rH   ri   rj   rk   rl   rm   rn   ro   rp   rq   rr   rI   rJ   r<   rd   ÚapiÚtmpZ
saved_pathr#   r#   r$   Úpush_to_hub_keras%  sH    P
þúùÿÿú	
örw   c                   @   s8   e Zd ZdZdd„ Zedeeee	f  dœdd„ƒZ
dS )	rg   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)rf   )Úselfr=   r#   r#   r$   Ú_save_pretrainedÅ  s    z#KerasModelHubMixin._save_pretrainedN)rH   c
                 K   sL   t dkrtdƒ‚tj |¡s2t|||dtƒ d�}n|}t j |¡}|	|_	|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.
        Nz>Called a TensorFlow-specific function but could not import it.r4   )rs   rt   Ú	cache_dirrA   Zlibrary_version)
r4   rT   rD   rE   Úisdirr   r   rc   Z
load_modelrH   )ÚclsZmodel_idrt   rz   Zforce_downloadÚproxiesZresume_downloadZlocal_files_onlyrl   rH   Zmodel_kwargsZstorage_folderr   r#   r#   r$   Ú_from_pretrainedÈ  s    ûz#KerasModelHubMixin._from_pretrained)N)r   Ú
__module__Ú__qualname__Ú__doc__ry   Úclassmethodr	   r   r]   r   r~   r#   r#   r#   r$   rg   ¡  s   # ö
ö)r'   )TN)NFTN):Úcollections.abcÚabcr+   rZ   rD   r_   Ú	functoolsr   Úpathlibr   Úshutilr   Útypingr   r   r   r	   r
   Zhuggingface_hubr   r   Zhuggingface_hub.utilsr   r   r   r   r   r'   r   Zhf_apir   r;   r   r   r   Zutils._typingr   Z
get_loggerr   Úloggerr4   Ztf_kerasrT   Z
tensorflowÚtfr&   r.   r7   r>   Úboolr0   rG   r]   r\   rf   rh   rw   rg   r#   r#   r#   r$   Ú<module>   sž   

  üü,    ú
úS5ïïz