o
    hvL                  "   @   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 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 rzd dl)Z(W n e*y   d dl+Z,e,j(Z(Y nw de$de$fddZ-d8ddZ.dd Z/dd Z0		d9de	de1dee2 fddZ3e-				d:dee4e	f d eee4ef  d!e1de1d"eee5e4f  f
d#d$Z6d;d&d'Z7e"e-dd(ddddddddddddd)d*e4d ee2 d+e4d,ee1 d-ee4 d.ee4 d/ee4 d0ee1 d1eeee4 e4f  d2eeee4 e4f  d3eeee4 e4f  d4ee4 d!e1d"eee5e4f  de1fd5d6Z8G d7d% 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                    s2   t | dstd j d | g|R i |S )NhistoryzCannot use 'z}': Keras 3.x is not supported. Please save models manually and upload them using `upload_folder` or `huggingface-cli upload`.)hasattrNotImplementedError__name__)modelargskwargsr    o/var/www/html/construction_image-detection-poc/venv/lib/python3.10/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 ]'\}}|r| d| n|}t|tjr&|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)
dictionary
parent_keyr)   keyvaluenew_keyr#   r#   r$   r.   7   s   r.   c                 C   s`   d}| j dur.| j  }t|}tj j|d< d}| D ]\}}|d| d| d7 }q|S )z6Parse hyperparameter dictionary into a markdown table.Ntraining_precisionz*| Hyperparameters | Value |
| :-- | :-- |
z| z | z |
)	optimizer
get_configr.   kerasmixed_precisionglobal_policynamer)   )r   tableoptimizer_paramsr3   r4   r#   r#   r$   _create_hyperparameter_tableT   s   

r?   c                 C   s(   t jj| | dddddddd d	 d S )N
/model.pngFTTB`   )to_fileshow_shapes
show_dtypeshow_layer_namesrankdirexpand_nesteddpilayer_range)r9   utils
plot_model)r   save_directoryr#   r#   r$   _plot_networkb   s   
rN   Trepo_dirrL   metadatac                 C   s  |d }|  r
dS t| }|rt rt rt| | |du r!i }d|d< d}|t|dd7 }|d7 }|d7 }|d	7 }|d
7 }|durW|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.mdNr9   library_namez---
F)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>)	existsr?   r   r   rN   r   ospath
write_text)r   rO   rL   rP   readme_pathhyperparameters
model_cardpath_to_plotr#   r#   r$   _create_model_cardp   s:   
r\   FrM   configinclude_optimizertagsc                 K   s  t du rtd| jstdt|}|jddd |rIt|ts+tdt	| d|t
j d}t|| W d   n1 sDw   Y  i }t|trU||d	< n
t|tr_|g|d	< |d
d}	|	durtdt d	|v r{|d	 |	 n|	g|d	< | jdur| jji kr|d }
|
 rtdt |
jddd}tj| jj|ddd W d   n1 sw   Y  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: ''wr_   	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_keysr^   )r9   ImportErrorbuilt
ValueErrorr   mkdirr*   r0   RuntimeErrortyper   CONFIG_NAMEopenjsondumpliststrpopwarningswarnFutureWarningr/   r   rT   UserWarningr\   models
save_model)r   rM   r]   r^   rL   r_   model_save_kwargsfrP   rd   rV   r#   r#   r$   save_pretrained_keras   sN   #






r~   KerasModelHubMixinc                  O   s   t j| i |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.

    </Tip>
    )r   from_pretrained)r    r!   r#   r#   r$   from_pretrained_keras   s   5r   z'Push Keras model using huggingface_hub.)r]   commit_messageprivateapi_endpointtokenbranch	create_prallow_patternsignore_patternsdelete_patternslog_dirr^   r_   rL   repo_idr   r   r   r   r   r   r   r   r   r   c                K   s   t |d}|j|||ddj}t K}t|| }t| |f||||d| |durG|du r1g n	t|tr9|gn|}|d t	||d  |j
d|||||||	|
|d	
W  d   S 1 s`w   Y  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
            `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/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.
    )endpointT)r   r   r   ra   )r]   r^   r_   rL   Nzlogs/*logsr   )
	repo_typer   folder_pathr   r   revisionr   r   r   r   )r   create_repor   r   r   r~   r*   rt   r/   r   upload_folder)r   r   r]   r   r   r   r   r   r   r   r   r   r   r^   r_   rL   r|   apitmp
saved_pathr#   r#   r$   push_to_hub_keras(  sJ   
P
	$r   c                   @   s:   e Zd ZdZdd Ze	ddeeee	f  fddZ
dS )	r   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~   )selfrM   r#   r#   r$   _save_pretrained  s   z#KerasModelHubMixin._save_pretrainedNr]   c
                 K   sL   t du rtdtj|st|||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.r9   )r   r   	cache_dirrQ   library_version)
r9   ri   rU   rV   isdirr   r   rz   
load_modelr]   )clsmodel_idr   r   force_downloadproxiesresume_downloadlocal_files_onlyr   r]   model_kwargsstorage_folderr   r#   r#   r$   _from_pretrained  s   z#KerasModelHubMixin._from_pretrainedr   )r   
__module____qualname____doc__r   classmethodr	   r   rt   r   r   r#   r#   r#   r$   r     s    #
)r'   )TN)NFTN)r   r   ):collections.abcabcr+   rq   rU   rv   	functoolsr   pathlibr   shutilr   typingr   r   r   r	   r
   huggingface_hubr   r   huggingface_hub.utilsr   r   r   r   r   r'   r   hf_apir   rK   r   r   r   utils._typingr   
get_loggerr   loggerr9   tf_kerasri   
tensorflowtfr&   r.   r?   rN   boolr0   r\   rt   rs   r~   r   r   r   r#   r#   r#   r$   <module>   s    



,

S8	
z