
    BVhI                        d 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 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 e+       d      Z, ed e+       d      Z- ed e+       d      Z.dZ/	 	 	 	 d.dZ0d  Z1d! Z2d" Z3d# Z4d$ Z5d% Z6d& Z7d' Z8d/d(Z9d) Z:d* Z;d+ Z<d, Z=d- Z>y)0z8Deprecated experimental Keras SavedModel implementation.    N)
graph_view)session)ops)backend)optimizer_v1)optimizer_v2)model_config)saving_utils)utils_v1)	mode_keys)
LazyLoader)file_io)	variables)gfile)
tf_logging)builder)	constants)save)saver)compat)nestmetrics_libztensorflow.python.keras.metrics
models_libztensorflow.python.keras.models
sequentialz)tensorflow.python.keras.engine.sequentialzsaved_model.jsonc                    t        j                  d       |r-t        j                  | |t	        j
                  | |             nt        | ||||       	 t        | |       y# t        $ r t        j                  d       Y yw xY w)a#	  Exports a `tf.keras.Model` as a Tensorflow SavedModel.

  Note that at this time, subclassed models can only be saved using
  `serving_only=True`.

  The exported `SavedModel` is a standalone serialization of Tensorflow objects,
  and is supported by TF language APIs and the Tensorflow Serving system.
  To load the model, use the function
  `tf.keras.experimental.load_from_saved_model`.

  The `SavedModel` contains:

  1. a checkpoint containing the model weights.
  2. a `SavedModel` proto containing the Tensorflow backend graph. Separate
     graphs are saved for prediction (serving), train, and evaluation. If
     the model has not been compiled, then only the graph computing predictions
     will be exported.
  3. the model's json config. If the model is subclassed, this will only be
     included if the model's `get_config()` method is overwritten.

  Example:

  ```python
  import tensorflow as tf

  # Create a tf.keras model.
  model = tf.keras.Sequential()
  model.add(tf.keras.layers.Dense(1, input_shape=[10]))
  model.summary()

  # Save the tf.keras model in the SavedModel format.
  path = '/tmp/simple_keras_model'
  tf.keras.experimental.export_saved_model(model, path)

  # Load the saved keras model back.
  new_model = tf.keras.experimental.load_from_saved_model(path)
  new_model.summary()
  ```

  Args:
    model: A `tf.keras.Model` to be saved. If the model is subclassed, the flag
      `serving_only` must be set to True.
    saved_model_path: a string specifying the path to the SavedModel directory.
    custom_objects: Optional dictionary mapping string names to custom classes
      or functions (e.g. custom loss functions).
    as_text: bool, `False` by default. Whether to write the `SavedModel` proto
      in text format. Currently unavailable in serving-only mode.
    input_signature: A possibly nested sequence of `tf.TensorSpec` objects, used
      to specify the expected model inputs. See `tf.function` for more details.
    serving_only: bool, `False` by default. When this is true, only the
      prediction graph is saved.

  Raises:
    NotImplementedError: If the model is a subclassed model, and serving_only is
      False.
    ValueError: If the input signature cannot be inferred from the model.
    AssertionError: If the SavedModel directory already exists and isn't empty.
  z`tf.keras.experimental.export_saved_model` is deprecatedand will be removed in a future version. Please use `model.save(..., save_format="tf")` or `tf.keras.models.save_model(..., save_format="tf")`.)
signatureszOSkipped saving model JSON, subclassed model does not have get_config() defined.N)warningswarnsave_libr   r
   trace_model_call_save_v1_format_export_model_jsonNotImplementedErrorloggingwarning)modelsaved_model_pathcustom_objectsas_textinput_signatureserving_onlys         g/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/keras/saving/saved_model_experimental.pyexport_saved_modelr-   =   s    @ -- G H MM00HJ
 E+^W#%-u./	 -OO , --s   A" "BBc                    | j                         }t        j                  j                  t	        |      t        j                  t                    }t        j                  |d      5 }|j                  |       ddd       y# 1 sw Y   yxY w)z?Saves model configuration as a json string under assets folder.wN)to_jsonospathjoin_get_or_create_assets_dirr   r)   SAVED_MODEL_FILENAME_JSONr   Openwrite)r&   r'   
model_jsonmodel_json_filepathfs        r,   r"   r"      sj    }}* 01nn./1 zz%s+ qGGJ  s   'BBc                 Z    t        |       t        |      }| j                  |dd       |S )z@Saves model weights in checkpoint format under variables folder.tfTsave_format	overwrite)_get_or_create_variables_dir_get_variables_pathsave_weights)r&   r'   checkpoint_prefixs      r,   _export_model_variablesrD      s3    /0)*:;&DDI	    c                    | j                   s<t        | t        j                        r| j                  st        d      t        d      t        j                  |      }t        | |      }|| |||d}d}| j                  rt        | j                  t        j                  t        j                  f      rMt        t         j"                  j$                  |fi | d}t        t         j"                  j&                  |fi | nt)        j*                  d       t        t         j"                  j,                  |fi | |j/                  |       y)z&Exports model to v1 SavedModel format.zWeights for sequential model have not yet been created. Weights are created when the Model is first called on inputs or `build()` is called with an `input_shape`, or the first layer in the model has `input_shape` during construction.zZSubclassed models can only be exported for serving. Please set argument serving_only=True.)r   r&   r(   checkpoint_pathr*   FTzModel was compiled with an optimizer, but the optimizer is not from `tf.train` (e.g. `tf.train.AdagradOptimizer`). Only the serving graph was exported. The train and evaluate graphs were not added to the SavedModel.N)_is_graph_network
isinstancer   
Sequentialbuilt
ValueErrorr#   saved_model_builder_SavedModelBuilderrD   	optimizerr   TFOptimizerr   OptimizerV2_export_moder   ModeKeysTRAINTESTr$   r%   PREDICTr   )	r&   r2   r(   r)   r*   r   rG   export_argshas_saved_varss	            r,   r!   r!      s)   		 	 %../ [[ > ? 	?  () )  2248' ,E48/ $#1$3$3	5+ .
__%//L$<$<$0$<$<$> ?9%%++^K{Kn9%%**NJkJoo
 y!!))>I[I	,,wrE   c                 T    t        j                  |       j                         \  }}}|S )z?Returns list of all checkpointed saveable objects in the model.)r   ObjectGraphViewserialize_object_graph)r&   var_list_s      r,   _get_var_listr^      s&    --e4KKM.(Aq	/rE   c                 n    t        j                  | j                  | j                  | j                        S )N)shapedtypename)r   placeholderr`   ra   rb   )specs    r,   create_placeholderre      s#    			4::TZZdii	PPrE   c                    | t         j                  j                  k7  }|r|j                  st	        d| z        t        j                         }t        j                         j                         5 }	t        j                  | t         j                  j                  k(        5  |d}
nt        j                  t        |      }
t        j!                  ||
||      }|r>|	j#                  t
        j$                  j&                  |j                  j(                         d}| t         j                  j                  k(  r'|j+                          |j,                  j.                  }n>| t         j                  j0                  k(  r|j3                          n|j5                          |	j7                  t
        j$                  j8                        j;                  |j<                         t?        j@                         j                         5  tC        |      }|r"|jE                  |      }|jG                          n:tI        ||||	       |jE                  |       |jK                  |dd       d|_&        |jO                  tP        jR                  |    tU        ||       tW        jX                  |d      t[        j\                         |       ddd       	 ddd       ddd       y# 1 sw Y   xY w# 1 sw Y   nxY wddd       y# 1 sw Y   yxY w)	a  Exports a model, and optionally saves new vars from the clone model.

  Args:
    mode: A `KerasModeKeys` string.
    has_saved_vars: A `boolean` indicating whether the SavedModel has already
      exported variables.
    builder: A `SavedModelBuilder` object.
    model: A `tf.keras.Model` object.
    custom_objects: A dictionary mapping string names to custom classes
      or functions.
    checkpoint_path: String path to checkpoint.
    input_signature: Nested TensorSpec containing the expected inputs. Can be
      `None`, in which case the signature will be inferred from the model.

  Raises:
    ValueError: If the train/eval mode is being exported, but the model does
      not have an optimizer.
  z7Model does not have an optimizer. Cannot export mode %sN)input_tensorsr(   compile_cloner<   Tr=   )allow_empty)signature_def_mapr   init_optrain_op)/r   rS   rV   rO   rL   r   get_default_graphGraph
as_defaultr   learning_phase_scoperT   r   map_structurere   r   clone_and_build_modeladd_to_collection	GraphKeysGLOBAL_STEP
iterations_make_train_functiontrain_function
updates_oprU   _make_test_function_make_predict_functionget_collection_ref
UPDATE_OPSextendstate_updatesr   Sessionr^   load_weightsassert_existing_objects_matched"_assert_same_non_optimizer_objectsrB   _has_saved_variablesadd_meta_graphmodel_utilsEXPORT_TAG_MAP_create_signature_def_map	saver_libSaverr   local_variables_initializer)moderX   r   r&   r(   rG   r*   rh   model_graphgrg   clonerl   clone_var_liststatuss                  r,   rR   rR      s   * 9--555-5??
ADHJ J %%'+
yy{ @1g&B&B
i  &&&'( @ m(();_Mm ,,]># - %E #--33U__5O5OP Hy!!'''  "%%00h	##((	(!""$11299%:M:MN			%	%	'  $U+n	##O4..0 	+5+uaH 	?+ 	?M'+$ 

$
$T
*5eTB 	 
 779  	/ B A@ @ @>   ?@ @ @ @ @s>   01K?!E!K*CK	K*K?K'#K**K3	/K??Lc                 |   t        | j                  | j                        D ci c]  \  }}||
 }}}| j                  rI| j                  D ci c]#  }||j
                  j                  d      d   |% }}|j                  |       t        | j                  | j                        D ci c]  \  }}||
 }}}t        j                  |       }t        t        j                  t        j                  j                               }t               }	|p|j#                         D ]]  \  }
}t%        |t&        j(                        s!|	j                  |j*                         |j-                         |j.                  d   f||
<   _ |	j1                  |      }	|	D ]0  }t        j2                  t        j                  j                   |       2 t5        j6                  ||| j                  r| j8                  nd|      }t5        j:                  |||t<        j>                  j@                  k(        S c c}}w c c}w c c}}w )z.Creates a SignatureDef map from a Keras model.N:r   )predictionslossmetrics)export_outputsr+   )!zipinput_namesinputsrO   _targetsrb   splitupdateoutput_namesoutputsr
   extract_model_metricssetr   get_collectionrt   LOCAL_VARIABLESitemsrI   r   Metricr   resultupdates
differencers   r   export_outputs_for_mode
total_lossbuild_all_signature_defsr   rS   rV   )r&   r   rb   xinputs_dicttargets_dictoutputs_dictr   
local_varsvars_to_addkeyvaluevr   s                 r,   r   r   D  s   (+E,=,=u||(LMWT1qM+M
__"^^>q} FFLL%a(!+ >L >|$!$U%7%7!GIdA ' I, I..u5'
 3%%cmm&C&CDE*+mmo :
U	E;--	.5??+a(89	: &&z2+ <a#--77;< 66
$5D	.
 
	-	-#I..666
9 9= N>Is   H-(H3,H8c                      y)z;Asserts model and clone contain the same trackable objects.T )r&   r   r   clone_graphs       r,   r   r   j  s     
rE   c                    t        j                  d       t        j                  j	                  t        j                  |       t        j                  t        j                        t        j                  t                    }t        j                  |d      5 }|j                         }ddd       t        j                  |      }t        j                  j	                  t        j                  |       t        j                  t        j                         t        j                  t        j"                              }|j%                  |       |S # 1 sw Y   xY w)a  Loads a keras Model from a SavedModel created by `export_saved_model()`.

  This function reinstantiates model state by:
  1) loading model topology from json (this will eventually come
     from metagraph).
  2) loading model weights from checkpoint.

  Example:

  ```python
  import tensorflow as tf

  # Create a tf.keras model.
  model = tf.keras.Sequential()
  model.add(tf.keras.layers.Dense(1, input_shape=[10]))
  model.summary()

  # Save the tf.keras model in the SavedModel format.
  path = '/tmp/simple_keras_model'
  tf.keras.experimental.export_saved_model(model, path)

  # Load the saved keras model back.
  new_model = tf.keras.experimental.load_from_saved_model(path)
  new_model.summary()
  ```

  Args:
    saved_model_path: a string specifying the path to an existing SavedModel.
    custom_objects: Optional dictionary mapping names
        (strings) to custom classes or functions to be
        considered during deserialization.

  Returns:
    a keras.Model instance.
  z`tf.keras.experimental.load_from_saved_model` is deprecatedand will be removed in a future version. Please switch to `tf.keras.models.load_model`.rN)r(   )r   r   r1   r2   r3   r   as_bytesr   ASSETS_DIRECTORYr5   r   r6   readr	   model_from_jsonr)   VARIABLES_DIRECTORYVARIABLES_FILENAMEr   )r'   r(   r9   r:   r8   r&   rC   s          r,   load_from_saved_modelr   q  s    H -- A B oo&'ooi001oo/02 zz%s+ qJ

&
&1% ggllnn%&nnY223nnY1124 &'	, s   EEc                 F    t        |       }t        j                  |       |S )zBReturn variables sub-directory, or create one if it doesn't exist.)_get_variables_dirr   recursive_create_dir)
export_dirvariables_dirs     r,   r@   r@     s     $Z0-	}-	rE   c                     t         j                  j                  t        j                  |       t        j                  t
        j                              S )z1Return variables sub-directory in the SavedModel.)r1   r2   r3   r   r)   r   r   r   s    r,   r   r     s5    	nnZ nnY223
5 5rE   c                     t         j                  j                  t        j                  t        |             t        j                  t        j                              S )zCReturn the variables path, used as the prefix for checkpoint files.)r1   r2   r3   r   r)   r   r   r   r   s    r,   rA   rA     s;    	nn'
34nnY112
4 4rE   c                 F    t        |       }t        j                  |       |S )z?Return assets sub-directory, or create one if it doesn't exist.)_get_assets_dirr   r   )r   assets_destination_dirs     r,   r4   r4     s"    *:6	56	rE   c                     t         j                  j                  t        j                  |       t        j                  t
        j                              S )z1Return path to asset directory in the SavedModel.)r1   r2   r3   r   r)   r   r   r   s    r,   r   r     s5    	nnZ nnY//0
2 2rE   )NFNF)N)?__doc__r1   r   tensorflow.python.checkpointr   tensorflow.python.clientr   tensorflow.python.frameworkr   tensorflow.python.kerasr   r   $tensorflow.python.keras.optimizer_v2r   tensorflow.python.keras.savingr	   r
   r   r   tensorflow.python.keras.utilsr   +tensorflow.python.keras.utils.generic_utilsr   tensorflow.python.lib.ior   tensorflow.python.opsr   tensorflow.python.platformr   r   r$   tensorflow.python.saved_modelr   rM   r   r   r   tensorflow.python.trainingr   r   tensorflow.python.utilr   r   globalsr   r   r   r5   r-   r"   rD   r!   r^   re   rR   r   r   r   r@   r   rA   r4   r   r   rE   r,   <module>r      s    ? 	  3 , + + 0 = 7 7 B 3 B , + , < H 3 : 9 ) ' 	:<gi8:
')/1
 / 
 '+$'+$)Q-h6rQ[|#9L7z54 2rE   