
    ij.A                     ,   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
 d dl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mZ d dlmZ  eddg      dd       Z eddg      dd       Z ed      	 dd       Z ed      dd       Z	 ddZy)    N)logging)keras_export)legacy_h5_format)
saving_lib)build_orbax_abstract_pytree)find_latest_orbax_checkpoint)is_orbax_checkpoint)
file_utils)io_utils)h5py)ocpzkeras.saving.save_modelzkeras.models.save_modelc                    |j                  dd      }|j                  dd      }|r[t        |      j                  d      st        |      j                  d      rt        j                  d|        nt        d|       |r%t        d	t        |j                                      t        |      j                  d      rt        j                  d
       t        |      j                  d      }|| }	 | xr t        j                  j                  |      }|r|st        j                  |      }	|	sy|r0t        |      j                  d      rt        j                   | |      S |st        j                   | |d      S t        |      j                  d      rt#        j$                  | |||      S t        d| d      # t        $ r d}Y w xY w)a  Saves a model as a `.keras` file.

    Args:
        model: 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.
        zipped: Whether to save the model as a zipped `.keras`
            archive (default when saving locally), or as an unzipped directory
            (default when saving on the Hugging Face Hub).

    Example:

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

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

    The saved `.keras` file is a `zip` archive that 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.
    include_optimizerTsave_formatF.h5.hdf5.keraszThe `save_format` argument is deprecated in Keras 3. We recommend removing this argument as it can be inferred from the file path. Received: save_format=zThe `save_format` argument is deprecated in Keras 3. Please remove this argument and pass a file path with either `.keras` or `.h5` extension.Received: save_format=z-The following argument(s) are not supported: a  You are saving your model as an HDF5 file via `model.save()` or `keras.saving.save_model(model)`. This file format is considered legacy. We recommend using instead the native Keras format, e.g. `model.save('my_model.keras')` or `keras.saving.save_model(model, 'my_model.keras')`. hf://N)zippeda  Invalid filepath extension for saving. Please add either a `.keras` extension for the native Keras format (recommended) or a `.h5` extension. Use `model.export(filepath)` if you want to export a SavedModel for use with TFLite/TFServing/etc. Received: filepath=.)popstrendswithr   warning
ValueErrorlistkeys
startswithospathexists	TypeErrorr   ask_to_proceed_with_overwriter   
save_modelr   save_model_to_hdf5)
modelfilepath	overwriter   kwargsr   r   is_hfr"   proceeds
             p/var/www/html/emotional.easysim.app/public_html/venv/lib/python3.12/site-packages/keras/src/saving/saving_api.pyr%   r%      s   L 

#6=**]E2Kx=!!"23s8}7M7M8
 OO) *57 ) *57  ;FKKM"#%
 	
 8}./C	
 M$$W-E~)9!9 i88B#h-((2$$UH55$$UHUCC
8}./228Y(9
 	
 	
 'Zq	*   s   8$G GGzkeras.saving.load_modelzkeras.models.load_modelc                    t        |       j                  d      xr t        j                  |       }t	        j
                  |       xr) t	        j                  t	        j                  | d            }t        |       j                  d      }d}	 t	        j                  |       rt	        j
                  |       sz|sx|svt        j                         }t	        j                  |t        j                  j                  |             }t	        j                  | |       t        j                  |      r|} d}|s|s|r3t        j                   | |||      |t#        j$                  |d       S S t        |       j                  d      r3t'        j(                  | |||      |t#        j$                  |d       S S t+        |       r)t-        | |||      |t#        j$                  |d       S S t        |       j                  d      rt/        d	|  d
      t/        d|  d|  d      # |t#        j$                  |d       w w xY w)a  Loads a model saved via `model.save()` or from an Orbax checkpoint.

    Args:
        filepath: `str` or `pathlib.Path` object, path to the saved model file
            or Orbax checkpoint directory.
        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 Keras v3 model format. Defaults to `True`.

    Returns:
        A 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 = keras.Sequential([
        keras.layers.Dense(5, input_shape=(3,)),
        keras.layers.Softmax()])
    model.save("model.keras")
    loaded_model = keras.saving.load_model("model.keras")
    ```

    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`.
    r   zconfig.jsonr   NTcustom_objectscompile	safe_mode)ignore_errorsr   zFile not found: filepath=z<. Please ensure the file is an accessible `.keras` zip file.$File format not supported: filepath=a  . Keras 3 only supports V3 `.keras` files, legacy H5 format files (`.h5` extension). Note that the legacy SavedModel format is not supported by `load_model()` in Keras 3. In order to reload a TensorFlow SavedModel as an inference-only layer in Keras 3, use `keras.layers.TFSMLayer(za, call_endpoint='serving_default')` (note that your `call_endpoint` might have a different name).)r   r   zipfile
is_zipfiler
   isdirr"   joinr   is_remote_pathr   get_temp_dirr    r!   basenamecopy
load_modelshutilrmtreer   load_model_from_hdf5r	   !_load_model_from_orbax_checkpointr   )	r(   r0   r1   r2   is_keras_zipis_keras_dirr+   tmp_dir
local_paths	            r-   r=   r=   }   s:   H x=))(3 8J8J9L ##H- *2C2C-03L M$$W-EGA7 %%h/$$X.  --/G#"''2B2B82LMJ OOHj1 !!*-%#<5((-#	X MM'6 M x=!!"23#88-#	J MM'6 ; x(4-#	8 MM'6 + ]##H-+H: 6   6xj A+ * 0
0  MM'6 s   CH( ,2H( 9H( -;H( (Izkeras.saving.save_weightsc                 h   t        |      }||j                  d      st        d|       ||j                  d      st        d|       	 t        j                  j                  |      }|r|st        j                  |      }|sy t        j                  | ||fi | y # t        $ r d}Y Bw xY w)N.weights.h5z;The filename must end in `.weights.h5`. Received: filepath=)z
weights.h5zweights.jsonz`The filename must end in `.weights.json` when `max_shard_size` is specified. Received: filepath=F)r   r   r   r    r!   r"   r#   r   r$   r   save_weights_only)r'   r(   r)   max_shard_sizer*   filepath_strr"   r,   s           r-   save_weightsrK      s     x=Ll&;&;M&J"".1
 	
 
	#L,A,A&- --9N<
 	
) i88F  .KFK  s   B# #B10B1zkeras.saving.load_weightsc                    t              }|j                  dd       }|j                  dd       }|rt        d|       |j                  d      r9|t        d       |t        d       t	        j
                  | |       y |j                  d      s|j                  d	      r*|t        d       t	        j
                  | ||
       y |j                  d      s|j                  d      r|t        d       t        j                  st        d      t        j                  d      5 }d|j                  vrd|v rt	        j                  |d      }|rt        j                  || |       nt        j                  || |       d d d        y t              rt              t!        j"                        }t%        fd|D              }	|	rt'              }
n}
t)        |
| j+                               }t-        j.                  |
t1        |            }|d   }| j3                  |       y t        d d      # 1 sw Y   y xY w)Nobjects_to_skipby_namezInvalid keyword arguments: r   zF`objects_to_skip` only supports loading '.weights.h5' files.Received: zI`by_name` only supports loading legacy '.h5' or '.hdf5' files. Received: )skip_mismatchrG   z.weights.json)rO   rM   r   r   zWLoading HDF5 files requires the h5py package. You can install it via `pip install h5py`rlayer_namesmodel_weightsc              3      K   | ]?  }t        j                  t        j                  |            xr |j                          A y w)N)r
   r7   r8   isdigit).0itemr(   s     r-   	<genexpr>zload_weights.<locals>.<genexpr>M  s=      
 Z__Xt<=P$,,.P
s   AA)pytreerX   r4   z. Keras 3 only supports V3 `.keras` files, `.weights.h5` files, legacy H5 format files (`.h5` extension), or Orbax checkpoints.)r   r   r   r   r   load_weights_onlyr   	availableImportErrorFileattrssafe_get_h5_groupr   $load_weights_from_hdf5_group_by_nameload_weights_from_hdf5_groupr	   r
   listdiranyr   r   get_state_treer   load_checkpointablesdictset_state_tree)r'   r(   rO   r*   rJ   rM   rN   fitemshas_step_subdirscheckpoint_pathabstract_pytreeloaded_checkpointablesloaded_states    `            r-   load_weightsrn   
  s   x=L jj!2D9OjjD)G6vh?@@X&&%J(  $$,:/ 
 	$$8=	
 
		}	-1F1F2 $$,:/  	$$'+		
 
		u	%)>)>w)G&%J(  ~~<  YYx% 
	AGG+10D00OD EEum !==um
	 
	 
X	&x= ""8, 

 

 :8DO 'O 6U113
 "%!9!9T9"
 .h7 	\*28* =7 7
 	
Y
	 
	s   :AIIc                 :   t        j                          t        |       }t        t        j
                  j                  |            }t         j                  j                  |       }g d}t        j                         5  t        |j                  |      j                  j                               }d|vrt        d      |j                  |ddi      }	t!        j"                  |	d   d   |||      }
t%        ||
j'                               }d|i}d	|v rd|d	<   |j                  ||      }|d   }|j)                  d	      }ddd       |D ci c]  }|v r|||    }}
j+                  |       t!        j,                  |
       |
S # 1 sw Y   IxY wc c}w )
a  Load a model from an Orbax checkpoint directory.

    `model_config` is stored as its own checkpointable (separate from
    `pytree`), so loading proceeds in two simple steps:

      1. Load the `model_config` checkpointable to obtain the model
         configuration string and rebuild the model.
      2. Load the `pytree` checkpointable (all arrays).  When a JAX
         distribution is active, an abstract pytree with target
         shardings is provided so that Orbax reshards arrays onto the
         current layout.
    )	directory)trainable_variablesnon_trainable_variablesoptimizer_variablesmetrics_variablesmodel_configzqCheckpoint does not contain model configuration. This checkpoint may have been saved with save_weights_only=True.Nconfigr/   rX   assets)r   
initializer   intr    r!   r;   trainingCheckpointerContextsetcheckpointables_metadatametadatar   r   rd   r   _model_from_configr   rc   getrf   _load_assets_from_dict)r(   r0   r1   r2   rj   stepcheckpointervariable_keys
saved_keysconfig_loadedr'   rk   requestloadedcomposite_stateassets_datakey
state_trees                     r-   rA   rA   p  s     NN 38<Orww01D <<,,x,@LM 
 $+ 11$7@@EEG


 +*  %99>4(
 --.)(3)	
 6U113
 _-z! $GH224A *jj*I$+P !/! 	_S!!J  
$ %%e[9Le$+ $+Ls    CFFF)TN)NTT)F)r    r>   r5   abslr   keras.src.api_exportr   keras.src.legacy.savingr   keras.src.savingr   keras.src.saving.orbax_utilr   r   r	   keras.src.utilsr
   r   keras.src.utils.module_utilsr   r   r%   r=   rK   rn   rA        r-   <module>r      s    	    - 4 ' C D ; & $ - , (*CDEf FfR (*CDEm7 Fm7` )*48L +L6 )*b
 +b
L <@Rr   