o
    i elP                     @   s  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d Z$e"dg ddd Z%d6ddZ&ej'fddZ(d d! Z)d"d# Z*d6d$d%Z+d6d&d'Z,e"g d(de -d)d*d+ Z.e"d,g dd-d. Z/e"d/d0gde 0dd1d6d2d3Z1G d4d5 d5e2Z3dS )7zNLoader 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                 C   s   t | }tt| tj}t }t	|rRt
|d-}z	||  W n tjy? } ztd| d| dd}~ww W d   ||fS 1 sMw   Y  ||fS )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e r*   X/var/www/myenv/lib/python3.10/site-packages/tensorflow/python/saved_model/loader_impl.py!parse_saved_model_with_debug_info.   s&   

r,   z*__internal__.saved_model.parse_saved_model)v1c              
   C   s  t tt| ttj}t tt| ttj}t tt| ttj}t	
 }t |rwt |d}| }W d   n1 sNw   Y  z|| W |S  tjyv } ztd| dt| d|d}~ww t |rt |d}| }W d   n1 sw   Y  zt|d| W |S  tjy } ztd| dt| d|d}~ww td|  tjj dtj d	tj d
)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)   r*   r*   r+   r   K   sT   






r   c                 C   s   |j }i }g }|jr|j}ntj|v r-|tj jj}|D ]}t }|| |	| qt
t| ttj}	|D ]}|jj}
|rJd||
f }
t
t|	t|j||
< q<|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.
  z%s/%s)collection_defasset_file_defr   
ASSETS_KEYany_listvaluer   AssetFileDefUnpackappendr   r   r   r1   ASSETS_DIRECTORYtensor_infonamefilename)r$   meta_graph_def_to_loadimport_scoperC   asset_tensor_dictasset_protosassets_any_protoasset_any_protoasset_protoassets_directorytensor_namer*   r*   r+   get_asset_tensors~   s.   



rX   c                 C   sV   | j }d}||v r)|| jj}t|dkr"tdt| d| dt|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   )rC   	node_listrG   lenRuntimeErrorr   get_collection)rO   init_op_keyrC   init_opinit_op_listr*   r*   r+   _get_main_op_tensor   s   
ra   c                 C   s
   t | |S N)ra   )meta_graph_defop_keyr*   r*   r+   _get_op_from_collection   s   
re   c                 C   s"   || j v rt| j | ||S dS )z>Retrieve op stored in the imported meta graph's signature def.N)signature_defr   load_op_from_signature_def)rc   op_signature_keyrP   r*   r*   r+   _get_op_from_signature_def   s   

ri   c                 C   s&   t | tj|pt| tjpt| tjS rb   )ri   r   INIT_OP_SIGNATURE_KEYre   MAIN_OP_KEYLEGACY_INIT_OP_KEY)rc   rP   r*   r*   r+   get_init_op   s   

rm   c                 C   s&   t | tj|}|d u rt| tj}|S rb   )ri   r   TRAIN_OP_SIGNATURE_KEYre   TRAIN_OP_KEY)rc   rP   train_opr*   r*   r+   get_train_op   s   rq   ) saved_model.contains_saved_modelz'saved_model.maybe_saved_model_directory.saved_model.loader.maybe_saved_model_directoryrs   c                 C   s0   t | tj}t | tj}t |pt |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   r3   r4   r   )r$   txt_pathpb_pathr*   r*   r+   maybe_saved_model_directory   s   rv   rr   c                 C   s   t | tjrt| } 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fspathrv   )r$   r*   r*   r+   contains_saved_model   s   
rz   zsaved_model.loadzsaved_model.loader.loadz"Use `tf.saved_model.load` instead.c                 K   s   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$   rP   saver_kwargsr   r*   r*   r+   r|     s   Br|   c                   @   sl   e Zd ZdZdd Zedd Zedd Zedd	 Zd
d Z	dddZ
dddZdddZdddZdS )r{   z<Load graphs and restore variable values from a `SavedModel`.c                 C   s    || _ t|| _t|| _dS )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$   r*   r*   r+   __init__\  s   zSavedModelLoader.__init__c                 C      | j S )z$Directory containing the SavedModel.)r   r   r*   r*   r+   r$   g     zSavedModelLoader.export_dirc                 C   r   )z"Path to variable checkpoint files.)r   r   r*   r*   r+   variables_pathl  r   zSavedModelLoader.variables_pathc                 C   r   )z3SavedModel object parsed from the export directory.)r   r   r*   r*   r+   r%   q  r   zSavedModelLoader.saved_modelc                 C   st   d}d}g }| j jD ]}|t|jj t|jjt|kr%|}d} nq
|s8tdt|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_graphsrJ   setmeta_info_defr~   r\   r7   strip)r   r~   found_matchrO   available_tagsrc   r*   r*   r+   get_meta_graph_def_from_tagsv  s"   z-SavedModelLoader.get_meta_graph_def_from_tagsNc                 K   sd   |  |}tjdkrt|dd |  tj|fd|i|W  d   S 1 s+w   Y  dS )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littlerP   N)r   sys	byteordersaved_model_utilsswap_function_tensor_content
as_defaulttf_saver'_import_meta_graph_with_return_elements)r   graphr~   rP   r   rc   r*   r*   r+   
load_graph  s   


$zSavedModelLoader.load_graphc                 C   s   |j  3 |du rtj|dstd nt|tjr$|	|| j
 ntdW d   dS W d   dS 1 s;w   Y  dS )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
   inforw   r   Saverrestorer   
ValueError)r   r}   r   rP   r*   r*   r+   restore_variables  s   
"z"SavedModelLoader.restore_variablesc                 C   s|   |  |}|j * t| j||d}t||}|dur,|j|g|d W d   dS W d   dS 1 s7w   Y  dS )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.
    )rP   N)fetches	feed_dict)r   r   r   rX   r   rm   run)r   r}   r~   rP   rc   asset_tensors_dictionaryr_   r*   r*   r+   run_init_ops  s   

"zSavedModelLoader.run_init_opsc           	      K   s   t | j}tt |j $ | j|j||fi |\}}| ||| | 	||| W d   n1 s6w   Y  | 
|}t|jdkrW|jd drWtjdd |S tjdd |S )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.
    NrY   r   object_graph_def2)write_version1)r   r   r   IncrementReadApi_LOADER_LABELr   r   r   r   r   r   r[   r   HasFieldIncrementRead)	r   r}   r~   rP   r   saved_model_protor   _rc   r*   r*   r+   r|     s"   



zSavedModelLoader.loadrb   )__name__
__module____qualname____doc__r   propertyr$   r   r%   r   r   r   r   r|   r*   r*   r*   r+   r{   Y  s    





r{   rb   )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   rX   rk   ra   re   ri   rm   rq   deprecated_endpointsrv   rz   
deprecatedr|   objectr{   r*   r*   r*   r+   <module>   s\   


2,





B