
    BVhuP                     .   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Z#d Z$ e"dg       d        Z%d+dZ&ejN                  fdZ(d Z)d Z*d+dZ+d+dZ, e"g d        e jZ                  d!      d"               Z. e"d#g       d$        Z/ e"d%d&g       e j`                  dd'      d+d(              Z1 G d) d*e2      Z3y),zNLoader implementation for SavedModel with hermetic, language-neutral exports.
    N)message)text_format)graph_debug_info_pb2)meta_graph_pb2)saved_model_pb2)ops)file_io)	variables)
tf_logging)	constants)path_helpers)signature_def_utils)
utils_impl)metrics)saver)compat)deprecation)	tf_exportloaderc           	         t        |       }t        j                  t        j                  |       t
        j                        }t        j                         }t        j                  |      rDt        j                  |d      5 }	 |j                  |j                                	 ddd       ||fS ||fS # t        j                  $ r}t        d| d| d      d}~ww xY w# 1 sw Y   ||fS xY w)a`  Reads the savedmodel as well as the graph debug info.

  Args:
    export_dir: Directory containing the SavedModel and GraphDebugInfo files.

  Returns:
    `SavedModel` and `GraphDebugInfo` protocol buffers.

  Raises:
    IOError: If the saved model file does not exist, or cannot be successfully
    parsed. Missing graph debug info file is fine.
  rbCannot parse file : .N)parse_saved_modelr	   joinr   get_debug_dirr   DEBUG_INFO_FILENAME_PBr   GraphDebugInfofile_existsFileIOParseFromStringreadr   DecodeErrorIOError)
export_dirsaved_modeldebug_info_path
debug_info
debug_filees         Y/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/python/saved_model/loader_impl.py!parse_saved_model_with_debug_infor-   .   s     "*-+LL  ,&&(/ $224*)		. D*D"":??#45D z	""+z	""    D*?*;2aSBCCDD z	""s*   C!B44CCCC!!C-z*__internal__.saved_model.parse_saved_model)v1c           
         t        j                  t        j                  t        j                  |             t        j                  t
        j                              }t        j                  t        j                  t        j                  |             t        j                  t
        j                              }t        j                  t        j                  t        j                  |             t        j                  t
        j                              }t        j                         }t        j                  |      rCt        j                  |d      5 }|j                         }ddd       	 |j                         |S t        j                  |      rWt        j                  |d      5 }|j                         }ddd       	 t'        j(                  j+                  d      |       |S t#        d|  t.        j0                  j2                   dt
        j                   d	t
        j                   d
      # 1 sw Y   xY w# t        j                   $ r!}t#        d| dt%        |       d      |d}~ww xY w# 1 sw Y   xY w# t&        j,                  $ r!}t#        d| dt%        |       d      |d}~ww xY w)a9  Reads the savedmodel.pb or savedmodel.pbtxt file containing `SavedModel`.

  Args:
    export_dir: String or Pathlike, path to the directory containing the
    SavedModel file.

  Returns:
    A `SavedModel` protocol buffer.

  Raises:
    IOError: If the file does not exist, or cannot be successfully parsed.
  r   Nr   r   r   zutf-8z#SavedModel file does not exist at: {|})r	   r   r   as_bytespath_to_strr   SAVED_MODEL_FILENAME_PBTXTSAVED_MODEL_FILENAME_PBSAVED_MODEL_FILENAME_CPBr   
SavedModelr    r!   r#   r"   r   r$   r%   strr   Parsedecode
ParseErrorospathsep)r&   path_to_pbtxt
path_to_pbpath_to_cpbr'   ffile_contentr+   s           r,   r   r   K   s9    ,,oof((45ooi::;=- ||oof((45ooi778:* oof((45ooi889;+
  **,+$	
D	) QVVXlI!!,/ 
 =)	t	, VVXlL++G4kB 
	 
-j\"''++
Y112!,,
-R	12 2   I(Bs1vha@AqHI  !! L(r#a&CD!KLsH   H;1I /I>	%J
 ;II;I66I;>J
J>J99J>c                    |j                   }i }g }|j                  r|j                  }nvt        j                  |v rd|t        j                     j                  j
                  }|D ]8  }t        j                         }|j                  |       |j                  |       : t        j                  t        j                  |       t        j                  t        j                              }	|D ]j  }|j                  j                   }
|r|d|
}
t        j                  t        j                  |	      t        j                  |j"                              ||
<   l |S )a  Gets the asset tensors, if defined in the meta graph def to load.

  Args:
    export_dir: Directory where the SavedModel is located.
    meta_graph_def_to_load: The meta graph def from the SavedModel to be loaded.
    import_scope: Optional `string` -- if specified, prepend this followed by
        '/' to all returned asset tensor names.

  Returns:
    A dictionary of asset tensors, keyed by the name of the asset tensor. The
    value in the map corresponds to the absolute path of the asset file.
  /)collection_defasset_file_defr   
ASSETS_KEYany_listvaluer   AssetFileDefUnpackappendr	   r   r   r3   ASSETS_DIRECTORYtensor_infonamefilename)r&   meta_graph_def_to_loadimport_scoperG   asset_tensor_dictasset_protosassets_any_protoasset_any_protoasset_protoassets_directorytensor_names              r,   get_asset_tensorsr\   ~   s+    *88.,**)88L~-%i&:&:;DDJJ+ '"//1k[)+&' \\ooj!6??93M3M#NP " /k))..K+[9k%,\\(),,-&/k"	/ 
    c                     | j                   }d}||v rZ||   j                  j                  }t        |      dk7  rt	        dt        |       d| d      t        j                  |      d   }|S )a  Gets the main op tensor, if one exists.

  Args:
    meta_graph_def_to_load: The meta graph def from the SavedModel to be loaded.
    init_op_key: name of the collection to check; should be one of MAIN_OP_KEY
      or the deprecated LEGACY_INIT_OP_KEY

  Returns:
    The main op tensor, if it exists and `None` otherwise.

  Raises:
    RuntimeError: If the collection def corresponding to the main op key has
        other than exactly one tensor.
  N   z/Expected exactly one SavedModel init op. Found r   r   r   )rG   	node_listrK   lenRuntimeErrorr   get_collection)rS   init_op_keyrG   init_opinit_op_lists        r,   _get_main_op_tensorrg      s      *88.'N"!+.88>>L
<A ""%l"3!4B|nAG H H  -a0G	.r]   c                     t        | |      S N)rg   )meta_graph_defop_keys     r,   _get_op_from_collectionrl      s    	^V	44r]   c                 h    || j                   v r$t        j                  | j                   |   ||      S y)z>Retrieve op stored in the imported meta graph's signature def.N)signature_defr   load_op_from_signature_def)rj   op_signature_keyrT   s      r,   _get_op_from_signature_defrq      s=    55599$$%568H  r]   c                     t        | t        j                  |      xs6 t        | t        j                        xs t        | t        j
                        S ri   )rq   r   INIT_OP_SIGNATURE_KEYrl   MAIN_OP_KEYLEGACY_INIT_OP_KEY)rj   rT   s     r,   get_init_oprv      sL    
$i55|E P
!.)2G2G
HP ".)2N2N
OQr]   c                 t    t        | t        j                  |      }|t        | t        j                        }|S ri   )rq   r   TRAIN_OP_SIGNATURE_KEYrl   TRAIN_OP_KEY)rj   rT   train_ops      r,   get_train_opr{      s7    'i66F(&~y7M7MNH	/r]   ) saved_model.contains_saved_modelz'saved_model.maybe_saved_model_directory.saved_model.loader.maybe_saved_model_directoryr}   c                 `   t        j                  | t        j                        }t        j                  | t        j                        }t        j                  | t        j
                        }t        j                  |      xs, t        j                  |      xs t        j                  |      S )a8  Checks whether the provided export directory could contain a SavedModel.

  Note that the method does not load any data by itself. If the method returns
  `false`, the export directory definitely does not contain a SavedModel. If the
  method returns `true`, the export directory may contain a SavedModel but
  provides no guarantee that it can be loaded.

  Args:
    export_dir: Absolute string path to possible export location. For example,
                '/my/foo/model'.

  Returns:
    True if the export directory contains SavedModel files, False otherwise.
  )r	   r   r   r5   r6   r7   r    )r&   txt_pathpb_pathcpb_paths       r,   maybe_saved_model_directoryr      s    , \\*i&J&JK(LLY%F%FG'\\*i&H&HI((# '			W	%'			X	&r]   r|   c                 v    t        | t        j                        rt        j                  |       } t	        |       S )a1  Checks whether the provided export directory could contain a SavedModel.

  Note that the method does not load any data by itself. If the method returns
  `false`, the export directory definitely does not contain a SavedModel. If the
  method returns `true`, the export directory may contain a SavedModel but
  provides no guarantee that it can be loaded.

  Args:
    export_dir: Absolute path to possible export location. For example,
                '/my/foo/model'.

  Returns:
    True if the export directory contains SavedModel files, False otherwise.
  )
isinstancer=   PathLikefspathr   )r&   s    r,   contains_saved_modelr     s+      
BKK(:&J	$Z	00r]   zsaved_model.loadzsaved_model.loader.loadz"Use `tf.saved_model.load` instead.c                 B    t        |      } |j                  | ||fi |S )ax
  Loads the model from a SavedModel as specified by tags.

  Args:
    sess: The TensorFlow session to restore the variables.
    tags: Set of string tags to identify the required MetaGraphDef. These should
        correspond to the tags used when saving the variables using the
        SavedModel `save()` API.
    export_dir: Directory in which the SavedModel protocol buffer and variables
        to be loaded are located.
    import_scope: Optional `string` -- if specified, prepend this string
        followed by '/' to all loaded tensor names. This scope is applied to
        tensor instances loaded into the passed session, but it is *not* written
        through to the static `MetaGraphDef` protocol buffer that is returned.
    **saver_kwargs: Optional keyword arguments passed through to Saver.

  Returns:
    The `MetaGraphDef` protocol buffer loaded in the provided session. This
    can be used to further extract signature-defs, collection-defs, etc.

  Raises:
    RuntimeError: MetaGraphDef associated with the tags cannot be found.

  @compatibility(TF2)

  `tf.compat.v1.saved_model.load` or `tf.compat.v1.saved_model.loader.load` is
  not compatible with eager execution. Please use `tf.saved_model.load` instead
  to load your model. You can refer to the [SavedModel guide]
  (https://www.tensorflow.org/guide/saved_model) for more information as well as
  "Importing SavedModels from TensorFlow 1.x" in the [`tf.saved_model.load`]
  (https://www.tensorflow.org/api_docs/python/tf/saved_model/load) docstring.

  #### How to Map Arguments

  | TF1 Arg Name          | TF2 Arg Name    | Note                       |
  | :-------------------- | :-------------- | :------------------------- |
  | `sess`                | Not supported   | -                          |
  | `tags`                | `tags`          | -                          |
  | `export_dir`          | `export_dir`    | -                          |
  | `import_scope`        | Not supported   | Name scopes are not needed.
  :                       :                 : By default, variables are  :
  :                       :                 : associated with the loaded :
  :                       :                 : object and function names  :
  :                       :                 : are deduped.               :
  | `saver_kwargs`        | Not supported   | -                          |

  #### Before & After Usage Example

  Before:

  ```
  with tf.compat.v1.Session(graph=tf.Graph()) as sess:
    tf.compat.v1.saved_model.loader.load(sess, ["foo-tag"], export_dir)
  ```

  After:

  ```
  model = tf.saved_model.load(export_dir, tags=["foo-tag"])
  ```
  @end_compatibility
  )SavedModelLoaderload)sesstagsr&   rT   saver_kwargsr   s         r,   r   r     s)    D J'&	T4	>	>>r]   c                   l    e Zd ZdZd Zed        Zed        Zed        Zd Z	ddZ
dd	Zdd
ZddZy)r   z<Load graphs and restore variable values from a `SavedModel`.c                 f    || _         t        j                  |      | _        t	        |      | _        y)zCreates a `SavedModelLoader`.

    Args:
      export_dir: Directory in which the SavedModel protocol buffer and
        variables to be loaded are located.
    N)_export_dirr   get_variables_path_variables_pathr   _saved_model)selfr&   s     r,   __init__zSavedModelLoader.__init___  s,     "D':::FD)*5Dr]   c                     | j                   S )z$Directory containing the SavedModel.)r   r   s    r,   r&   zSavedModelLoader.export_dirj  s     r]   c                     | j                   S )z"Path to variable checkpoint files.)r   r   s    r,   variables_pathzSavedModelLoader.variables_patho  s     r]   c                     | j                   S )z3SavedModel object parsed from the export directory.)r   r   s    r,   r'   zSavedModelLoader.saved_modelt  s     r]   c                 ^   d}d}g }| j                   j                  D ]a  }|j                  t        |j                  j
                               t        |j                  j
                        t        |      k(  s]|}d} n |s*t        dt        |      j                  d       d| d      |S )a  Return MetaGraphDef with the exact specified tags.

    Args:
      tags: A list or set of string tags that identify the MetaGraphDef.

    Returns:
      MetaGraphDef with the same tags.

    Raises:
      RuntimeError: if no metagraphs were found with the associated tags.
    FNTz"MetaGraphDef associated with tags z[]z8 could not be found in SavedModel, with available tags 'ze'. To inspect available tag-sets in the SavedModel, please use the SavedModel CLI: `saved_model_cli`.)	r   meta_graphsrN   setmeta_info_defr   rb   r9   strip)r   r   found_matchrS   available_tagsrj   s         r,   get_meta_graph_def_from_tagsz-SavedModelLoader.get_meta_graph_def_from_tagsy  s     K!N++77 C < < A ABC	^))..	/3t9	<!/ .s4yt/D.E F OOP P
 "!r]   Nc                     | j                  |      }t        j                  dk(  rt        j                  |dd       |j                         5  t        j                  |fd|i|cddd       S # 1 sw Y   yxY w)a  Load ops and nodes from SavedModel MetaGraph into graph.

    Args:
      graph: tf.Graph object.
      tags: a set of string tags identifying a MetaGraphDef.
      import_scope: Optional `string` -- if specified, prepend this string
        followed by '/' to all loaded tensor names. This scope is applied to
        tensor instances loaded into the passed session, but it is *not* written
        through to the static `MetaGraphDef` protocol buffer that is returned.
      **saver_kwargs: keyword arguments to pass to tf.train.import_meta_graph.

    Returns:
      A tuple of
        * Saver defined by the MetaGraph, which can be used to restore the
          variable values.
        * List of `Operation`/`Tensor` objects returned from
          `tf.import_graph_def` (may be `None`).
    biglittlerT   N)r   sys	byteordersaved_model_utilsswap_function_tensor_content
as_defaulttf_saver'_import_meta_graph_with_return_elements)r   graphr   rT   r   rj   s         r,   
load_graphzSavedModelLoader.load_graph  s~    & 66t<N
}}44^X5:<				 E==
E'3E7CEE E Es   A..A7c                 B   |j                   j                         5  |,t        j                  |      st	        j
                  d       nBt        |t        j                        r|j                  || j                         nt        d      ddd       y# 1 sw Y   yxY w)a  Restore SavedModel variable values into the session.

    Args:
      sess: tf.compat.v1.Session to restore variable values.
      saver: a tf.compat.v1.train.Saver object. Can be None if there are no
        variables in graph. This may be the saver returned by the load_graph()
        function, or a default `tf.compat.v1.train.Saver()`.
      import_scope: Optional `string` -- if specified, prepend this string
        followed by '/' to all loaded tensor names. This scope is applied to
        tensor instances loaded into the passed session, but it is *not* written
        through to the static `MetaGraphDef` protocol buffer that is returned.

    Raises:
      ValueError: if no saver was passed to the saver argument, and there are
        variables in the graph.
    N)scopezHThe specified SavedModel has no variables; no checkpoints were restored.zNo tf.train.Saver object was passed to the function `SavedModelLoader.restore_variables`. Since there are variables in the graph, a saver is required.)r   r   r
   _all_saveable_objectsr   infor   r   Saverrestorer   
ValueError)r   r   r   rT   s       r,   restore_variablesz"SavedModelLoader.restore_variables  s    " 
			  0
---LA 5 	6eX^^,dD001/0 	00 0 0s   A1BBc                     | j                  |      }|j                  j                         5  t        | j                  ||      }t        ||      }||j                  |g|       ddd       y# 1 sw Y   yxY w)a  Run initialization ops defined in the `MetaGraphDef`.

    Args:
      sess: tf.compat.v1.Session to restore variable values.
      tags: a set of string tags identifying a MetaGraphDef.
      import_scope: Optional `string` -- if specified, prepend this string
        followed by '/' to all loaded tensor names. This scope is applied to
        tensor instances loaded into the passed session, but it is *not* written
        through to the static `MetaGraphDef` protocol buffer that is returned.
    )rT   N)fetches	feed_dict)r   r   r   r\   r   rv   run)r   r   r   rT   rj   asset_tensors_dictionaryre   s          r,   run_init_opszSavedModelLoader.run_init_ops  s}     66t<N				  H!2


N"G NL9g		'.FGH H Hs   ;A00A9c                 :   t        | j                        }t        j                  t               |j
                  j                         5   | j                  |j
                  ||fi |\  }}| j                  |||       | j                  |||       ddd       | j                  |      }t        |j                        dk(  r6|j                  d   j                  d      rt        j                  d       |S t        j                  d       |S # 1 sw Y   xY w)a  Load the MetaGraphDef graph and restore variable values into the session.

    Args:
      sess: tf.compat.v1.Session to restore variable values.
      tags: a set of string tags identifying a MetaGraphDef.
      import_scope: Optional `string` -- if specified, prepend this string
        followed by '/' to all loaded tensor names. This scope is applied to
        tensor instances loaded into the passed session, but it is *not* written
        through to the static `MetaGraphDef` protocol buffer that is returned.
      **saver_kwargs: keyword arguments to pass to tf.train.import_meta_graph.

    Returns:
      `MetagraphDef` proto of the graph that was loaded.
    Nr_   r   object_graph_def2)write_version1)r   r   r   IncrementReadApi_LOADER_LABELr   r   r   r   r   r   ra   r   HasFieldIncrementRead)	r   r   r   rT   r   saved_model_protor   _rj   s	            r,   r   zSavedModelLoader.load  s     *$*:*:;]+				  2 T< 1#/1heQ
T5,7
dL1	2
 66t<N))*a/%%a(112DE#.  #.2 2s   	A	DDri   )__name__
__module____qualname____doc__r   propertyr&   r   r'   r   r   r   r   r    r]   r,   r   r   \  sa    D	6        "<E60<H*r]   r   ri   )4r   r=   r   google.protobufr   r   tensorflow.core.frameworkr   tensorflow.core.protobufr   r   tensorflow.python.frameworkr   tensorflow.python.lib.ior	   tensorflow.python.opsr
   tensorflow.python.platformr   tensorflow.python.saved_modelr   r   r   r   r   0tensorflow.python.saved_model.pywrap_saved_modelr   tensorflow.python.trainingr   r   tensorflow.python.utilr   r    tensorflow.python.util.tf_exportr   r   r-   r   r\   rt   rg   rl   rq   rv   r{   deprecated_endpointsr   r   
deprecatedr   objectr   r   r]   r,   <module>r      s;   
 
 # ' : 3 4 + , + 1 3 6 = I D 8 ) . 6 #: 7B?/ @/d(X )2(=(=65Q   
 "!!4662 -"51 61( !#<=>(*??* ???Dhv hr]   