
    0h9                        d Z ddlZddlZddlZddlZddlmc mZ ddl	m
Z
 ddlmZ ddlmZ ddlmZ 	 ddlZdZ G d d	      Z G d
 d      Z e
dd      dd       Z e
dd      	 dd       ZddZddZd Zy# e$ r dZY Lw xY w)z#Public API surface for saving APIs.    N)keras_export)
saving_lib)save)io_utilsTc                   "    e Zd ZdZd Zd Zd Zy)SupportReadFromRemoteSupports GCS URIs and other remote paths via a temporary file.

    This is used for `.keras` and H5 files on GCS, CNS and CFS. TensorFlow
    supports remoted saved model out of the box.
    c                 v   t        |d       }t        j                  |      rt        j                  j
                  j                  |      s|dk7  rt        j                         | _	        |}t        s,t        |      j                  d      r|j                  dd      }t        j                  j!                  | j                  j"                  t        j                  j%                  |            | _        t        j                  j
                  j)                  || j&                  d       y d | _	        || _        y )Nsave_formattfgs://
/bigstore/T	overwrite)get_save_formatr   is_remote_pathr   iogfileisdirtempfileTemporaryDirectorytemp_directoryis_ossstr
startswithreplaceospathjoinnamebasenamelocal_filepathcopy)selffilepathr   gs_filepaths       X/var/www/html/engine/venv/lib/python3.12/site-packages/tf_keras/src/saving/saving_api.py__init__zSupportReadFromRemote.__init__,   s    %hDA%%h/EEKK%%h/t#"*"="="?D"Kc(m66w?&..wE"$'',,##(("''*:*:8*D#D EEKK[$*=*=N"&D"*D    c                     | j                   S Nr#   r%   s    r(   	__enter__zSupportReadFromRemote.__enter__?       """r*   c                 R    | j                   | j                   j                          y y r,   )r   cleanupr%   exc_type	exc_value	tracebacks       r(   __exit__zSupportReadFromRemote.__exit__B   s%    *'') +r*   N__name__
__module____qualname____doc__r)   r/   r7    r*   r(   r   r   %   s    +&#*r*   r   c                   $    e Zd ZdZddZd Zd Zy)SupportWriteToRemoter	   Nc                    t        ||      }|| _        t        j                  |      r|dk7  rt	        j
                         | _        || _        t        s;t        |      j                  d      r!| j                  j                  dd      | _        t        j                  j                  | j                  j                  t        j                  j!                  |            | _        y d | _        d | _        || _        y )Nr   r   r   r   )r   r   r   r   r   r   r   remote_filepathr   r   r   r   r   r   r    r!   r"   r#   )r%   r&   r   r   s       r(   r)   zSupportWriteToRemote.__init__N   s    %hKH"$$X.;$3F"*"="="?D#+D c(m66w?'+';';'C'C\($ #%'',,##(("''*:*:8*D#D #'D#'D "*Dr*   c                     | j                   S r,   r-   r.   s    r(   r/   zSupportWriteToRemote.__enter__`   r0   r*   c                     | j                   et        j                  j                  j	                  | j
                  | j                  | j                         | j                   j                          y y )Nr   )	r   r   r   r   r$   r#   rA   r   r2   r3   s       r(   r7   zSupportWriteToRemote.__exit__c   s[    *EEKK##$$..  
 '') +r*   TNr8   r=   r*   r(   r?   r?   G   s    +$#*r*   r?   zkeras.saving.save_modelzkeras.models.save_modelc                    t        |||      5 }t        ||      }|dk(  rt        j                  dd       |dk(  r	 t        j
                  j                  |      }|r#|s!t        j                  |      }|s
	 ddd       y|r%t        d	t        |j                                      t        j                  | |       n#t        j                  | |f||d|cddd       S 	 ddd       y# t        $ r d}Y w xY w# 1 sw Y   yxY w)
a  Saves a model as a TensorFlow SavedModel or HDF5 file.

    See the [Serialization and Saving guide](
        https://keras.io/guides/serialization_and_saving/) for details.

    Args:
        model: TF-Keras model instance to be saved.
        filepath: `str` or `pathlib.Path` object. Path where to save the model.
        overwrite: Whether we should overwrite any existing model at the target
            location, or instead ask the user via an interactive prompt.
        save_format: Either `"keras"`, `"tf"`, `"h5"`,
            indicating whether to save the model
            in the native TF-Keras format (`.keras`),
            in the TensorFlow SavedModel format (referred to as "SavedModel"
            below), or in the legacy HDF5 format (`.h5`).
            Defaults to `"tf"` in TF 2.X, and `"h5"` in TF 1.X.

    SavedModel format arguments:
        include_optimizer: Only applied to SavedModel and legacy HDF5 formats.
            If False, do not save the optimizer state. Defaults to True.
        signatures: Only applies to SavedModel format. Signatures to save
            with the SavedModel. See the `signatures` argument in
            `tf.saved_model.save` for details.
        options: Only applies to SavedModel format.
            `tf.saved_model.SaveOptions` object that specifies SavedModel
            saving options.
        save_traces: Only applies to SavedModel format. When enabled, the
            SavedModel will store the function traces for each layer. This
            can be disabled, so that only the configs of each layer are stored.
            Defaults to `True`. Disabling this will decrease serialization time
            and reduce file size, but it requires that all custom layers/models
            implement a `get_config()` method.

    Example:

    ```python
    model = tf.keras.Sequential([
        tf.keras.layers.Dense(5, input_shape=(3,)),
        tf.keras.layers.Softmax()])
    model.save("model.keras")
    loaded_model = tf.keras.saving.load_model("model.keras")
    x = tf.random.uniform((10, 3))
    assert np.allclose(model.predict(x), loaded_model.predict(x))
    ```

    Note that `model.save()` is an alias for `tf.keras.saving.save_model()`.

    The SavedModel or HDF5 file contains:

    - The model's configuration (architecture)
    - The model's weights
    - The model's optimizer's state (if any)

    Thus models can be reinstantiated in the exact same state, without any of
    the code used for model definition or training.

    Note that the model weights may have different scoped names after being
    loaded. Scoped names include the model/layer names, such as
    `"dense_1/kernel:0"`. It is recommended that you use the layer properties to
    access specific variables, e.g. `model.get_layer("dense_1").kernel`.

    __SavedModel serialization format__

    With `save_format="tf"`, the model and all trackable objects attached
    to the it (e.g. layers and variables) are saved as a TensorFlow SavedModel.
    The model config, weights, and optimizer are included in the SavedModel.
    Additionally, for every TF-Keras layer attached to the model, the SavedModel
    stores:

    * The config and metadata -- e.g. name, dtype, trainable status
    * Traced call and loss functions, which are stored as TensorFlow
      subgraphs.

    The traced functions allow the SavedModel format to save and load custom
    layers without the original class definition.

    You can choose to not save the traced functions by disabling the
    `save_traces` option. This will decrease the time it takes to save the model
    and the amount of disk space occupied by the output SavedModel. If you
    enable this option, then you _must_ provide all custom class definitions
    when loading the model. See the `custom_objects` argument in
    `tf.keras.saving.load_model`.
    )r   r   h5zYou are saving your model as an HDF5 file via `model.save()`. This file format is considered legacy. We recommend using instead the native TF-Keras format, e.g. `model.save('my_model.keras')`.   )
stacklevelkerasFNMThe following argument(s) are not supported with the native TF-Keras format: )r?   r   warningswarnr   r   exists	TypeErrorr   ask_to_proceed_with_overwrite
ValueErrorlistkeysr   
save_modellegacy_sm_saving_lib)modelr&   r   r   kwargsr#   rM   proceeds           r(   rS   rS   m   s>   l 

 ) 
%h< $MM7  '!7 i"@@P5) )6  88<V[[]8K7LN  !!%8 (22 $'	
 G) )@ 9A) )*  +) )s5   .C>C-C>AC>-C;8C>:C;;C>>Dzkeras.saving.load_modelzkeras.models.load_modelc                 f   t        |       5 }t        |      j                  d      r^t        j                  |      rI|r%t        dt        |j                                      t        j                  ||||      cddd       S t        j                  |f||d|cddd       S # 1 sw Y   yxY w)a  Loads a model saved via `model.save()`.

    Args:
        filepath: `str` or `pathlib.Path` object, path to the saved model file.
        custom_objects: Optional dictionary mapping names
            (strings) to custom classes or functions to be
            considered during deserialization.
        compile: Boolean, whether to compile the model after loading.
        safe_mode: Boolean, whether to disallow unsafe `lambda` deserialization.
            When `safe_mode=False`, loading an object has the potential to
            trigger arbitrary code execution. This argument is only
            applicable to the TF-Keras v3 model format. Defaults to True.

    SavedModel format arguments:
        options: Only applies to SavedModel format.
            Optional `tf.saved_model.LoadOptions` object that specifies
            SavedModel loading options.

    Returns:
        A TF-Keras model instance. If the original model was compiled,
        and the argument `compile=True` is set, then the returned model
        will be compiled. Otherwise, the model will be left uncompiled.

    Example:

    ```python
    model = tf.keras.Sequential([
        tf.keras.layers.Dense(5, input_shape=(3,)),
        tf.keras.layers.Softmax()])
    model.save("model.keras")
    loaded_model = tf.keras.saving.load_model("model.keras")
    x = tf.random.uniform((10, 3))
    assert np.allclose(model.predict(x), loaded_model.predict(x))
    ```

    Note that the model variables may have different name values
    (`var.name` property, e.g. `"dense_1/kernel:0"`) after being reloaded.
    It is recommended that you use layer attributes to
    access specific variables, e.g. `model.get_layer("dense_1").kernel`.
    .kerasrJ   )custom_objectscompile	safe_modeN)rZ   r[   )r   r   endswithzipfile
is_zipfilerP   rQ   rR   r   
load_modelrT   )r&   rZ   r[   r\   rV   r#   s         r(   r`   r`      s    Z 
x	( 
N~''1g6H6H7
  88<V[[]8K7LN  ((-#	
 
" $..
)
 	
#
 
 
s   A/B'B''B0c                    t        ||      5 }t        |      j                  d      r\	 t        j                  j                  |      }|r#|s!t        j                  |      }|s
	 d d d        y t        j                  | |       nt        j                  | |fd|i| d d d        y # t        $ r d}Y kw xY w# 1 sw Y   y xY w)Nr   .weights.h5Fr   )r?   r   r]   r   r   rM   rN   r   rO   r   save_weights_onlyrT   save_weights)rU   r&   r   rV   r#   rM   rW   s          r(   rd   rd   5  s    	h)	< ~''67 i"@@P  ((? --~1:>D 
   s4   B8B'	B8.0B8'B52B84B55B88Cc                 ~   t        |      5 }t        |      j                  d      r.t        j                  |      rt        j                  | ||       nUt        |      j                  d      rt        j                  | ||       n"t        j                  | |fd|i|cd d d        S d d d        y # 1 sw Y   y xY w)NrY   )skip_mismatchrb   rf   )	r   r   r]   r^   r_   r   load_weights_onlyrT   load_weights)rU   r&   rf   rV   r#   s        r(   rh   rh   I  s    	x	( N~''1g6H6H7
 ((~]  ))-8((~] (44~5BFL   s   BB33B<c                    |r9|dk(  ry|dk(  rt        j                         ryy|dv ry|dv ryt        d|       t        |       j	                  d      rt        j                         ryyt        |       j	                  d	      ryt
        t        | t
        j                        ryt        j                  j                  j                         ryy)
Nkeras_v3rI   rF   )rF   hdf5)r   
tensorflowr   z^Unknown `save_format` argument. Expected one of 'keras', 'tf', or 'h5'. Received: save_format=rY   )z.h5z.hdf5)r   saving_v3_enabledrP   r   r]   h5py
isinstanceFiler   __internal__tf2enabled)r&   r   s     r(   r   r   \  s    *$'!++-.(..%%0M3
 	
 8}h''')
8}./Jx; 
""$r*   rD   )NTT)T)F)r<   r   r   rK   r^   tensorflow.compat.v2compatv2r    tensorflow.python.util.tf_exportr   tf_keras.src.savingr   tf_keras.src.saving.legacyr   rT   tf_keras.src.utilsr   rn   ImportErrorr   r   r?   rS   r`   rd   rh   r   r=   r*   r(   <module>r|      s    * 	    ! ! 9 * C ' 
* *D#* #*L ')BC~ D~B ')BC;?B
 DB
J(&'{	  Ds   A< <BB