a
    Sic>M                     @   s\  d Z ddlZddlm  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edgdd6ddZdd Z dd Z!dd Z"dd  Z#d!d" Z$d#d$ Z%d%d& Z&d'd( Z'ed)gdd7d*d+Z(d,d- Z)d.d/ Z*d0d1 Z+d2d3 Z,d4d5 Z-dS )8z8Deprecated experimental Keras SavedModel implementation.    N)backend)optimizer_v1)optimizer_v2)model_config)saving_utils)utils_v1)	mode_keys)
LazyLoader)
tf_logging)keras_exportmetrics_libzkeras.metrics
models_libzkeras.models
sequentialzkeras.engine.sequentialzsaved_model.jsonz%keras.experimental.export_saved_model)v1Fc                 C   sn   t jddd |r.tjj| |t| |d nt| |||| zt| | W n t	yh   t
d Y n0 dS )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.compat.v1.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.compat.v1.keras.experimental.export_saved_model(model, path)

    # Load the saved keras model back.
    new_model = tf.compat.v1.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")`.   
stacklevel)
signatureszOSkipped saving model JSON, subclassed model does not have get_config() defined.N)warningswarntfsaved_modelsaver   trace_model_call_save_v1_format_export_model_jsonNotImplementedErrorloggingwarning)modelsaved_model_pathcustom_objectsas_textinput_signatureserving_only r%   a/var/www/html/django/DPS/env/lib/python3.9/site-packages/keras/saving/saved_model_experimental.pyexport_saved_model1   s&    F

r'   c                 C   sb   |   }tjjt|tjt}tjj	|d}|
| W d   n1 sT0    Y  dS )z?Saves model configuration as a json string under assets folder.wN)to_jsonr   iogfilejoin_get_or_create_assets_dircompatr"   SAVED_MODEL_FILENAME_JSONGFilewrite)r   r    
model_jsonmodel_json_filepathfr%   r%   r&   r      s    
r   c                 C   s$   t | t|}| j|ddd |S )z@Saves model weights in checkpoint format under variables folder.r   Tsave_format	overwrite)_get_or_create_variables_dir_get_variables_pathsave_weights)r   r    checkpoint_prefixr%   r%   r&   _export_model_variables   s    r<   c           	      C   s   | j s*t| tjr"| js*tdntdtjj	
|}t| |}|| |||d}d}| jrt| jtjtjfrttjj|fi | d}ttjj|fi | n
td ttjj|fi | || dS )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.)builderr   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   r   __internal__r   SavedModelBuilderr<   	optimizerr   TFOptimizerr   OptimizerV2_export_moder   ModeKeysTRAINTESTr   r   PREDICTr   )	r   pathr!   r"   r#   r=   r>   Zexport_argshas_saved_varsr%   r%   r&   r      sF    


r   c                 C   s   t jj|  \}}}|S )z?Returns list of all checkpointed saveable objects in the model.)r   rD   trackingObjectGraphViewserialize_object_graph)r   var_list_r%   r%   r&   _get_var_list   s    rU   c                 C   s   t j| j| j| jdS )N)shapedtypename)r   placeholderrV   rW   rX   )specr%   r%   r&   create_placeholder   s    r[   c              
   C   s  | t jjk}|r.|js.td|j d|  dtjj	 }t
  }	t| t jjk| |du rnd}
ntjt|}
tj||
||d}|r|	tjjjj|jj d}| t jjkr|  |jj}n| t jjkr|  n|  |	tjjjj |j! tjj"   t#|}|r8|$|}|%  n.t&||||	 |$| |j'|ddd d|_(|j)t*j+|  t,|| tjjj-j.|dd	tjj/ |d
 W d   n1 s0    Y  W d   W d   dS 1 s0    Y  W d   n1 s0    Y  dS )a  Exports a model, and optionally saves new vars from the clone model.

    Args:
      mode: A `tf.estimator.ModeKeys` 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.
    zModel z0 does not have an optimizer. Cannot export mode .N)input_tensorsr!   compile_cloner   Tr5   )allow_empty)signature_def_mapsaverinit_optrain_op)0r   rJ   rM   rF   rC   rX   r   r.   r   get_default_graphGraph
as_defaultr   learning_phase_scoperK   nestmap_structurer[   r   clone_and_build_modeladd_to_collection	GraphKeysGLOBAL_STEP
iterations_make_train_functiontrain_function
updates_oprL   _make_test_function_make_predict_functionget_collection_ref
UPDATE_OPSextendstate_updatesSessionrU   load_weightsassert_existing_objects_matched"_assert_same_non_optimizer_objectsr:   _has_saved_variablesadd_meta_graphmodel_utilsEXPORT_TAG_MAP_create_signature_def_maptrainSaverlocal_variables_initializer)moderO   r=   r   r!   r>   r#   r^   model_graphgr]   clonerc   Zclone_var_liststatusr%   r%   r&   rI      st    









&rI   c                 C   s&  dd t | j| jD }| jr8dd | jD }|| dd t | j| jD }t	| }t
tjjtjjjj}t
 }|dur| D ]6\}}	t|	tjr||	j |	 |	jd f||< q||}|D ]}
tjjtjjjj|
 qtj||| jr| jnd|d}tj|||tjj kdS )	z.Creates a SignatureDef map from a Keras model.c                 S   s   i | ]\}}||qS r%   r%   .0rX   xr%   r%   r&   
<dictcomp>p      z-_create_signature_def_map.<locals>.<dictcomp>c                 S   s&   i | ]}|d ur|j dd |qS )N:r   )rX   split)r   r   r%   r%   r&   r   r  s   c                 S   s   i | ]\}}||qS r%   r%   r   r%   r%   r&   r   v  s   Nr   )predictionslossmetrics)export_outputsr$   )!zipinput_namesinputsrF   _targetsupdateoutput_namesoutputsr   extract_model_metricssetr   r.   r   get_collectionrl   LOCAL_VARIABLESitemsr@   r   Metric	variablesresultupdates
differencerk   r~   export_outputs_for_mode
total_lossbuild_all_signature_defsr   rJ   rM   )r   r   Zinputs_dicttargets_dictZoutputs_dictr   
local_varsZvars_to_addkeyvaluevr   r%   r%   r&   r   n  sF    



r   c                 C   s   dS )z;Asserts model and clone contain the same trackable objects.Tr%   )r   r   r   Zclone_graphr%   r%   r&   r{     s    r{   z(keras.experimental.load_from_saved_modelc                 C   s   t jddd tjjtj| tjtjj	tjt
}tjj|d}| }W d   n1 sj0    Y  tj||d}tjjtj| tjtjjtjtjj}|| |S )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.compat.v1.keras.experimental.export_saved_model(model, path)

    # Load the saved keras model back.
    new_model = tf.compat.v1.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`.r   r   rN)r!   )r   r   r   r*   r+   r,   r.   as_bytesr   ASSETS_DIRECTORYr/   r0   readr   model_from_jsonr"   VARIABLES_DIRECTORYVARIABLES_FILENAMEry   )r    r!   r3   r4   r2   r   r;   r%   r%   r&   load_from_saved_model  s*    %

&

r   c                 C   s   t | }tjj| |S )zBReturn variables sub-directory, or create one if it doesn't exist.)_get_variables_dirr   r*   r+   makedirs)
export_dirvariables_dirr%   r%   r&   r8     s    r8   c                 C   s$   t jjt j| t jt jjS )z1Return variables sub-directory in the SavedModel.)r   r*   r+   r,   r.   r"   r   r   r   r%   r%   r&   r     s    
r   c                 C   s(   t jjt jt| t jt jjS )zCReturn the variables path, used as the prefix for checkpoint files.)	r   r*   r+   r,   r.   r"   r   r   r   r   r%   r%   r&   r9     s    r9   c                 C   s   t | }tjj| |S )z?Return assets sub-directory, or create one if it doesn't exist.)_get_assets_dirr   r*   r+   r   )r   assets_destination_dirr%   r%   r&   r-     s    r-   c                 C   s$   t jjt j| t jt jjS )z1Return path to asset directory in the SavedModel.)r   r*   r+   r,   r.   r"   r   r   r   r%   r%   r&   r     s    
r   )NFNF)N).__doc__r   Ztensorflow.compat.v2r.   v2r   kerasr   Zkeras.optimizersr   keras.optimizers.optimizer_v2r   Zkeras.savingr   r   r   r~   keras.utilsr   keras.utils.generic_utilsr	   tensorflow.python.platformr
   r    tensorflow.python.util.tf_exportr   globalsr   r   r   r/   r'   r   r<   r   rU   r[   rI   r   r{   r   r8   r   r9   r-   r   r%   r%   r%   r&   <module>   sJ   
    `Dw.
C	