o
    ?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   Zget_debug_dirr   ZDEBUG_INFO_FILENAME_PBr   ZGraphDebugInfofile_existsFileIOParseFromStringreadr   DecodeErrorIOError)
export_dirsaved_modelZdebug_info_pathZ
debug_infoZ
debug_filee r$   j/home/www/facesmatcher.com/pyenv/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_bytesZpath_to_strr   SAVED_MODEL_FILENAME_PBTXTSAVED_MODEL_FILENAME_PBZSAVED_MODEL_FILENAME_CPBr   Z
SavedModelr   r   r   r   r   r   r    strr   ParsedecodeZ
ParseErrorospathsep)r!   Zpath_to_pbtxtZ
path_to_pbZpath_to_cpbr"   fZ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_defZasset_file_defr   Z
ASSETS_KEYZany_listvaluer   ZAssetFileDefZUnpackappendr   r   r   r+   ZASSETS_DIRECTORYZtensor_infonamefilename)r!   meta_graph_def_to_loadimport_scoper5   Zasset_tensor_dictZasset_protosZassets_any_protoZasset_any_protoZasset_protoZassets_directoryZtensor_namer$   r$   r%   get_asset_tensors~   s.   



r<   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   )r5   Z	node_listr6   lenRuntimeErrorr   Zget_collection)r:   Zinit_op_keyr5   init_opZinit_op_listr$   r$   r%   _get_main_op_tensor   s   
rA   c                 C   s
   t | |S N)rA   )meta_graph_defZop_keyr$   r$   r%   _get_op_from_collection   s   
rD   c                 C   s"   || j v rt| j | ||S dS )z>Retrieve op stored in the imported meta graph's signature def.N)Zsignature_defr   Zload_op_from_signature_def)rC   Zop_signature_keyr;   r$   r$   r%   _get_op_from_signature_def   s   

rE   c                 C   s&   t | tj|pt| tjpt| tjS rB   )rE   r   ZINIT_OP_SIGNATURE_KEYrD   MAIN_OP_KEYZLEGACY_INIT_OP_KEY)rC   r;   r$   r$   r%   get_init_op   s   

rG   c                 C   s&   t | tj|}|d u rt| tj}|S rB   )rE   r   ZTRAIN_OP_SIGNATURE_KEYrD   ZTRAIN_OP_KEY)rC   r;   Ztrain_opr$   r$   r%   get_train_op   s   rH   ) saved_model.contains_saved_modelz'saved_model.maybe_saved_model_directory.saved_model.loader.maybe_saved_model_directoryrJ   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   r,   r-   r   )r!   Ztxt_pathZpb_pathr$   r$   r%   maybe_saved_model_directory   s   rK   rI   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.
  )
isinstancer1   PathLikefspathrK   )r!   r$   r$   r%   contains_saved_model   s   
rO   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!   r;   saver_kwargsr   r$   r$   r%   rQ     s   BrQ   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 )rP   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   Z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.)rU   rX   r$   r$   r%   r!   g     zSavedModelLoader.export_dirc                 C   rZ   )z"Path to variable checkpoint files.)rV   r[   r$   r$   r%   variables_pathl  r\   zSavedModelLoader.variables_pathc                 C   rZ   )z3SavedModel object parsed from the export directory.)rW   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} q&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`.)	rW   meta_graphsr7   setZmeta_info_defrS   r?   r.   strip)rX   rS   found_matchr:   Z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littler;   N)rb   sys	byteordersaved_model_utilsZswap_function_tensor_content
as_defaulttf_saverZ'_import_meta_graph_with_return_elements)rX   graphrS   r;   rT   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.)rj   rh   r	   Z_all_saveable_objectsr
   inforL   ri   ZSaverrestorerV   
ValueError)rX   rR   r   r;   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.
    )r;   N)ZfetchesZ	feed_dict)rb   rj   rh   r<   rU   rG   run)rX   rR   rS   r;   rC   Z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.
    Nr=   r   Zobject_graph_def2)Zwrite_version1)r   rU   r   ZIncrementReadApi_LOADER_LABELrj   rh   rk   rp   rr   rb   r>   r^   ZHasFieldZIncrementRead)	rX   rR   rS   r;   rT   Zsaved_model_protor   _rC   r$   r$   r%   rQ     s"   



zSavedModelLoader.loadrB   )__name__
__module____qualname____doc__rY   propertyr!   r]   r"   rb   rk   rp   rr   rQ   r$   r$   r$   r%   rP   Y  s    





rP   rB   )4rz   r1   re   Zgoogle.protobufr   r   Ztensorflow.core.frameworkr   Ztensorflow.core.protobufr   r   Ztensorflow.python.frameworkr   Ztensorflow.python.lib.ior   Ztensorflow.python.opsr	   Ztensorflow.python.platformr
   Ztensorflow.python.saved_modelr   r   r   r   rg   Z0tensorflow.python.saved_model.pywrap_saved_modelr   Ztensorflow.python.trainingr   ri   Ztensorflow.python.utilr   r   Z tensorflow.python.util.tf_exportr   ru   r&   r   r<   rF   rA   rD   rE   rG   rH   Zdeprecated_endpointsrK   rO   
deprecatedrQ   objectrP   r$   r$   r$   r%   <module>   s\   


2,



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