
    ߔ9iI              !       t   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jB                  e"      Z# e       rd dl$Z%d*dZ&d Z'd Z(	 	 d+dede)dee*   fdZ+	 	 	 	 d,dee,ef   deee,ef      de)de)deee-e,f      f
dZ.d-dZ/e dddddddddddddddde,dee*   de,de)d ee,   d!ee,   d"ee,   d#ee)   d$eeee,   e,f      d%eeee,   e,f      d&eeee,   e,f      d'ee,   de)deee-e,f      de)fd(       Z0 G d) de      Z1y).    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_argsc                    g }| j                         D ]g  \  }}|r| d| n|}t        |t        j                        r*|j	                  t        ||      j                                U|j                  ||f       i 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_keys         e/var/www/html/backtest/airagagent/rag_env/lib/python3.12/site-packages/huggingface_hub/keras_mixin.pyr   r      s     E &&( 
+
U+5ZL#'3e[778LL %'	 LL'5)*
+ ;    c                 &   | j                   | j                   j                         }t        |      }t        j                  j
                  j                         j                  |d<   d}|j                         D ]  \  }}|d| d| dz  } |S d}|S )z6Parse hyperparameter dictionary into a markdown table.Ntraining_precisionz*| Hyperparameters | Value |
| :-- | :-- |
z| z | z |
)		optimizer
get_configr   tfkerasmixed_precisionglobal_policynamer   )modeloptimizer_paramstabler#   r$   s        r&   _create_hyperparameter_tabler4   :   s    " ??557()9:131I1I1W1W1Y1^1^-.>*002 	.JCr#c%--E	. L Lr'   c                 n    t         j                  j                  j                  | | dddddddd 	       y )N
/model.pngFTTB`   )to_fileshow_shapes
show_dtypeshow_layer_namesrankdirexpand_nesteddpilayer_range)r,   r-   utils
plot_model)r1   save_directorys     r&   _plot_networkrD   I   s@    HHNN!"*-  
r'   Trepo_dirrB   metadatac                    t        |       }|r t               rt               rt        | |       |i }| d}d|d<   d}|t	        |d      z  }|dz  }|dz  }|d	z  }|d
z  }||dz  }|dz  }|dz  }||z  }|dz  }|rAt
        j                  j                  | d      r|dz  }|dz  }|dz  }d}|d| dz  }|dz  }t
        j                  j                  |      r(t        |dd      5 }|j                         }	ddd       n|}	t        |dd      5 }|j                  	       ddd       y# 1 sw Y   2xY w# 1 sw Y   yxY w)z2
    Creates a model card for the repository.
    Nz
/README.mdr-   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:


r6   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)r4   r   r   rD   r   ospathexistsopenreadwrite)
r1   rE   rB   rF   hyperparametersreadme_path
model_cardpath_to_plotfreadmes
             r&   _create_model_cardr]   W   s    359O+-2D2FeX&Jj)K&H^J)H??J'JGGJQQJRRJ"11
88
VV
o%
d
bggnnz%<=**
m#
>>
$),s;;
n$
	ww~~k"+sV4 	VVXF	 	 	k3	1 Q	 		 	 s   -D2D>2D;>EFrC   configinclude_optimizertagsc                 6   t               rddl}nt        d      | j                  st	        d      t        |      }|j                  dd       |r_t        |t              st        dt        |       d      |t        z  j                  d	      5 }t        j                  ||       ddd       i }	t        |t              r||	d
<   nt        |t               r|g|	d
<   |j#                  dd      }
|
9t%        j&                  dt(               d
|	v r|	d
   j+                  |
       n|
g|	d
<   | j,                  | j,                  j,                  i k7  rx|dz  }|j/                         rt%        j&                  dt0               |j                  d	d      5 }t        j                  | j,                  j,                  |dd       ddd       t3        | |||	        |j4                  j6                  j8                  | |fd|i| y# 1 sw Y   [xY w# 1 sw Y   OxY w)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: ''rO   r`   	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.rP   rM      )indent	sort_keysr_   )r   
tensorflowImportErrorbuilt
ValueErrorr   mkdirr   r    RuntimeErrortyper   rT   jsondumpliststrpopwarningswarnFutureWarningr   historyrS   UserWarningr]   r-   models
save_model)r1   rC   r^   r_   rB   r`   model_save_kwargsr,   r[   rF   re   rR   s               r&   save_pretrained_kerasr}      s   D Z[[;;FGG.)N5 &$'!bcghncobppqrss{*005 	!IIfa 	! H$	D#	 6!%%k48IL	
 XV##I. ){HV}} ==  B&!N2D{{}p 31 NQ		%--//1MN unj(CBHHOOunoHYo]noA	! 	!8N Ns   H.HHHKerasModelHubMixinc                  ,    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.
        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>
    )r~   from_pretrained)argskwargss     r&   from_pretrained_kerasr      s    p --t>v>>r'   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`   rB   repo_idr   r   r   r   r   r   r   r   r   r   c                   t        |      }|j                  |||d      j                  }t               5 }t	        |      |z  }t        | |f||||d| |9|g nt        |t              r|gn|}|j                  d       t        ||dz         |j                  d|||||||	|
|	
      cddd       S # 1 sw Y   yxY w)
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.
    )endpointT)r   r   r   rc   )r^   r_   r`   rB   Nzlogs/*logsr1   )
	repo_typer   folder_pathr   r   revisionr   r   r   r   )r   create_repor   r   r   r}   r   rs   r   r   upload_folder)r1   r   r^   r   r   r   r   r   r   r   r   r   r   r_   r`   rB   r|   apitmp
saved_paths                       r&   push_to_hub_kerasr     s   \ 
&CoogUGVZo[ccG 
 	! %
S#Y(
	
 /!	
  	
  #*  "/37 %%(  ""8,Wj612  "))++ ! 
5%
 %
 %
s   A6B66B?c                   &    e Zd ZdZd Zed        Zy)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                     t        | |       y )N)r}   )selfrC   s     r&   _save_pretrainedz#KerasModelHubMixin._save_pretrained  s    dN3r'   c	                 .   t               rddl}
nt        d      |	j                  dd      }t        j
                  j                  |      st        |||dt                     }n|} |
j                  j                  j                  |fi |	}||_        |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.r^   r-   )r   r   	cache_dirrH   library_version)r   ri   rj   rt   rQ   rR   isdirr   r   r-   rz   
load_modelr^   )clsmodel_idr   r   force_downloadproxiesresume_downloadlocal_files_onlyr   model_kwargsr,   cfgstorage_folderr1   s                 r&   _from_pretrainedz#KerasModelHubMixin._from_pretrained  s    & #^__ x. ww}}X&. !#$ . 0N &N***>J\J r'   N)__name__
__module____qualname____doc__r   classmethodr    r'   r&   r~   r~     s!    !F4 + +r'   ) )TN)NFTN)returnr~   )2collections.abcabcr   rp   rQ   ru   pathlibr   shutilr   typingr   r   r   r   r	   huggingface_hubr
   r   huggingface_hub.utilsr   r   r   r   r   	constantsr   hf_apir   rA   r   r   r   
get_loggerr   loggerri   r,   r   r4   rD   boolr    r]   rs   rr   r}   r   r   r~   r   r'   r&   <module>r      s\   %  	    3 3 <  #  H H 
		H	%:" #	** * tn	*` (,#'+Rp#t)$Rp T#s(^$Rp 	Rp
 Rp 5s#
$Rpj8?v 
 "C"&  $6:7;7;!#'+#v
v
 TN	v

 v
 v
 3-v
 C=v
 SMv
 ~v
 U49c>23v
 eDIsN34v
 eDIsN34v
 c]v
 v
  5s#
$!v
" #v
 v
rS Sr'   