o
    ?eaZ                     @   s~  d 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 Zdd Zejdd Zdd Zdd Zdd Z dd Z!dd  Z"d!d" Z#	#d8d$d%Z$d&d' Z%d(d) Z&d*d+ Z'd,d- Z(ed.d/edd0d1					d9d2d/Z)	#d:d3d4Z*			5			#d;d6d7Z+dS )<z3A utility function for importing TensorFlow graphs.    N)	graph_pb2)tf2)pywrap_tf_session)
c_api_utildevice)errors)function)op_def_registry)ops)tensor)control_flow_util)compat)deprecated_args)	tf_exportc                 C   s
   |  dS )N^)
startswith)Z
input_name r   e/home/www/facesmatcher.com/pyenv/lib/python3.10/site-packages/tensorflow/python/framework/importer.py_IsControlInput"   s   
r   c              	   C   s   |  d}t|dkr.zt|d }W n ty'   td| d|d  dw |d |fS t|dkr:|d dfS td|  d	t|d  )
a  Parses a tensor name into an operation name and output index.

  This function will canonicalize tensor names as follows:

  * "foo:0"       -> ("foo", 0)
  * "foo:7"       -> ("foo", 7)
  * "foo"         -> ("foo", 0)
  * "foo:bar:baz" -> ValueError

  Args:
    tensor_name: The name of a tensor.

  Returns:
    A tuple containing the operation name, and the output index.

  Raises:
    ValueError: If `tensor_name' cannot be interpreted as the name of a tensor.
  :      zCannot convert zX to a tensor name. Second component of the name following the `:` should be an int. Got .r   zCannot convert 'zN' to a tensor name. Tensor names should not contain more than 1 `:`. Obtained )splitlenint
ValueError)Ztensor_name
componentsZoutput_indexr   r   r   _ParseTensorName'   s   




r   c                 c   sF    | rt |  dV  W d   dS 1 sw   Y  dS dV  dS )z=Applies the given device only if device is not None or empty.N)r   r   r   r   r   r   _MaybeDeviceM   s   "
r    c                 C   sp   t | tjs z| }t } | | W | S  ty   tdw | jD ]}t|j}|du r0q#t	|| q#| S )z3Type-checks and possibly canonicalizes `graph_def`.z.Argument `graph_def` must be a GraphDef proto.N)

isinstancer   ZGraphDefZ	MergeFrom	TypeErrornoder
   getop_SetDefaultAttrValues)	graph_defZold_graph_defr#   op_defr   r   r   _ProcessGraphDefParamW   s   

r)   c                 C   s^   | du ri } | S t | tstdt| j tdd |  D s-tdt|   | S )z3Type-checks and possibly canonicalizes `input_map`.Nz4Argument `input_map` must be a dictionary. Obtained c                 s       | ]	}t |tjV  qd S Nr!   r   Zbytes_or_text_types).0kr   r   r   	<genexpr>}       
z(_ProcessInputMapParam.<locals>.<genexpr>zBAll keys for argument `input_map` must be strings. Obtained keys: )r!   dictr"   type__name__allkeyslist)	input_mapr   r   r   _ProcessInputMapParamu   s   	

r8   c                 C   s@   | du rdS t dd | D std|  dtdd | D S )z9Type-checks and possibly canonicalizes `return_elements`.Nc                 s   r*   r+   r,   r-   xr   r   r   r/      r0   z._ProcessReturnElementsParam.<locals>.<genexpr>z?Argument `return_elements` must be a list of strings. Obtained r   c                 s   s    | ]}t |V  qd S r+   r   as_strr9   r   r   r   r/      s    )r4   r"   tuple)return_elementsr   r   r   _ProcessReturnElementsParam   s   
r?   c                 C   s"   |j D ]}| |jkr|  S qd S r+   )attrname)Z	attr_namer(   attr_defr   r   r   _FindAttrInOpDef   s
   

rC   c                 C   s   dd | j D }|jD ]>}|j |v rIt|j }|du rq||j  }t|jD ]!}t||du rHt||}|rH|drH|j| |jkrH|j|= q'qdS )a   Removes unknown default attrs according to `producer_op_list`.

  Removes any unknown attrs in `graph_def` (i.e. attrs that do not appear in
  registered OpDefs) that have a default value in `producer_op_list`.

  Args:
    producer_op_list: OpList proto.
    graph_def: GraphDef proto
  c                 S   s   i | ]}|j |qS r   )rA   )r-   r%   r   r   r   
<dictcomp>   s    z'_RemoveDefaultAttrs.<locals>.<dictcomp>Ndefault_value)	r%   r#   r
   r$   r6   r@   rC   HasFieldrE   )producer_op_listr'   Zproducer_op_dictr#   r(   Zproducer_op_defkeyrB   r   r   r   _RemoveDefaultAttrs   s    




rI   c                 C   sh   t dd | D s2| dkrtdtd dd | D }W d   |S 1 s-w   Y  |S )	a  Ensures all input map values are tensors.

  This should be called from inside the import name scope.

  Args:
    name: the `name` argument passed to import_graph_def
    input_map: the `input_map` argument passed to import_graph_def.

  Returns:
    An possibly-updated version of `input_map`.

  Raises:
    ValueError: if input map values cannot be converted due to empty name scope.
  c                 s   r*   r+   )r!   r   ZTensor)r-   vr   r   r   r/      s    z)_ConvertInputMapValues.<locals>.<genexpr> ztf.import_graph_def() requires a non-empty `name` if `input_map` contains non-Tensor values. Try calling tf.convert_to_tensor() on `input_map` values before calling tf.import_graph_def().Z_inputsc                 S   s   i | ]
\}}|t |qS r   )r   Zconvert_to_tensor)r-   r.   rJ   r   r   r   rD      s    z*_ConvertInputMapValues.<locals>.<dictcomp>N)r4   valuesr   r   
name_scopeitems)rA   r7   r   r   r   _ConvertInputMapValues   s   
rO   Fc                 C   s  t | | t | d t | | | D ];\}}t|}|dr:t|dd }| j	}	t 
| ||	 qt|\}}
t|}| }t | ||
| q|pUg D ]"}d|v rot|\}}t|}t | || qVt | t| qVt | | dS )z1Populates the TF_ImportGraphDefOptions `options`.Tr   r   Nr   )c_apiZ!TF_ImportGraphDefOptionsSetPrefixZ(TF_ImportGraphDefOptionsSetUniquifyNamesZ.TF_ImportGraphDefOptionsSetPropagateDeviceSpecrN   r   r<   r   Z_as_tf_outputoperZ.TF_ImportGraphDefOptionsRemapControlDependencyr   Z'TF_ImportGraphDefOptionsAddInputMappingZ'TF_ImportGraphDefOptionsAddReturnOutputZ*TF_ImportGraphDefOptionsAddReturnOperationZ8TF_ImportGraphDefOptionsSetValidateColocationConstraints)optionsprefixr7   r>   validate_colocation_constraintspropagate_device_specZ	input_srcZ	input_dstZsrc_nameZdst_opZsrc_idxZ
dst_outputrA   Zop_nameindexr   r   r    _PopulateTFImportGraphDefOptions   s<   





rW   c           
   
   C   s  i }| j ddD ].}|j}|d t|}|r|||< qt| | | W d   n1 s1w   Y  q| D ]C\}}d}|D ]3}z| |}	W n tyi   t	
 s\t| r^Y qCtd| d|j w |	jrvtj|	j} qwqC|r~|| q;dS )z3Processes the newly-added TF_Operations in `graph`.F)Zcompute_devicesrK   NzSpecified colocation to an op: z+ that does not exist during import for op: )Z_add_new_tf_operationsr   Z_set_device_GetColocationNamesr    Z_apply_device_functionsrN   Z_get_operation_by_nameKeyErrorr   enabledr   ZEnableControlFlowV2r   rA   pydevZ
DeviceSpecZfrom_string)
graphZcolocation_pairsZnew_opZoriginal_devicecolocation_namesr%   Zcoloc_op_listZcoloc_deviceZcoloc_op_nameZcoloc_opr   r   r   _ProcessNewOps   s>   




r^   c                 C   sn   g }z|  d}W n
 ty   Y dS w |D ]}t|}|dr4|tdd }|| jkr4|| q|S )z<Returns names of the ops that `op` should be colocated with._classNzloc:@)Zget_attrr   r   r<   r   r   rA   append)r%   r]   Zclass_valuesvalZcolocation_node_namer   r   r   rX   )  s   



rX   c           	      C   sp   t |}t |}g }d}d}| D ]#}d|v r'||||  |d7 }q||||  |d7 }q|S )a  Returns the requested return elements from results.

  Args:
    requested_return_elements: list of strings of operation and tensor names
    graph: Graph
    results: wrapped TF_ImportGraphDefResults

  Returns:
    list of `Operation` and/or `Tensor` objects
  r   r   r   )rP   Z%TF_ImportGraphDefResultsReturnOutputsZ(TF_ImportGraphDefResultsReturnOperationsr`   Z_get_tensor_by_tf_outputZ_get_operation_by_tf_operation)	Zrequested_return_elementsr\   resultsZreturn_outputsZreturn_opersZcombined_return_elementsZoutputs_idxZ	opers_idxrA   r   r   r   _GatherReturnElements:  s    



rc   c                 C   sb   | j |jksJ |jD ]#}|j}|dr.| j| }|du s%|ddu r.| j| |j qdS )z>Set any default attr values in `node_def` that aren't present.rE   Nvalue)r%   rA   r@   rF   Z
WhichOneofZCopyFromrE   )Znode_defr(   rB   rH   rd   r   r   r   r&   W  s   


r&   zgraph_util.import_graph_defimport_graph_defzfPlease file an issue at https://github.com/tensorflow/tensorflow/issues if you depend on this feature.op_dictc                 C   s   ~t | ||||dS )a  Imports the graph from `graph_def` into the current default `Graph`.

  This function provides a way to import a serialized TensorFlow
  [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)
  protocol buffer, and extract individual objects in the `GraphDef` as
  `tf.Tensor` and `tf.Operation` objects. Once extracted,
  these objects are placed into the current default `Graph`. See
  `tf.Graph.as_graph_def` for a way to create a `GraphDef`
  proto.

  Args:
    graph_def: A `GraphDef` proto containing operations to be imported into
      the default graph.
    input_map: A dictionary mapping input names (as strings) in `graph_def`
      to `Tensor` objects. The values of the named input tensors in the
      imported graph will be re-mapped to the respective `Tensor` values.
    return_elements: A list of strings containing operation names in
      `graph_def` that will be returned as `Operation` objects; and/or
      tensor names in `graph_def` that will be returned as `Tensor` objects.
    name: (Optional.) A prefix that will be prepended to the names in
      `graph_def`. Note that this does not apply to imported function names.
      Defaults to `"import"`.
    op_dict: (Optional.) Deprecated, do not use.
    producer_op_list: (Optional.) An `OpList` proto with the (possibly stripped)
      list of `OpDef`s used by the producer of the graph. If provided,
      unrecognized attrs for ops in `graph_def` that have their default value
      according to `producer_op_list` will be removed. This will allow some more
      `GraphDef`s produced by later binaries to be accepted by earlier binaries.

  Returns:
    A list of `Operation` and/or `Tensor` objects from the imported graph,
    corresponding to the names in `return_elements`,
    and None if `returns_elements` is None.

  Raises:
    TypeError: If `graph_def` is not a `GraphDef` proto,
      `input_map` is not a dictionary mapping strings to `Tensor` objects,
      or `return_elements` is not a list of strings.
    ValueError: If `input_map`, or `return_elements` contains names that
      do not appear in `graph_def`, or `graph_def` is not well-formed (e.g.
      it refers to an unknown tensor).
  )r7   r>   rA   rG   _import_graph_def_internal)r'   r7   r>   rA   rf   rG   r   r   r   re   b  s   4c                 C   s   t | d||dS )zCLike import_graph_def but does not validate colocation constraints.F)rT   rA   rU   rg   )r'   rA   rU   r   r   r   import_graph_def_for_function  s   ri   Tc                 C   s  t | } t|}t|}|durt||  t }t|d| }|r3|ds,J |dd }	nd}	t	||}W d   n1 sDw   Y  t
 }
|
j}t||	|||| | Z t
|  ?}z#|j }t|||}W d   n1 s~w   Y  t
|}W n tjy } ztt|d}~ww W d   n1 sw   Y  t| W d   n1 sw   Y  | jr| jjrt| j}|D ]}|| qt|j }|rdd |D }d!|}td	| d
|du rdS t"|||j S )ag	  Imports the graph from `graph_def` into the current default `Graph`.

  This function provides a way to import a serialized TensorFlow
  [`GraphDef`](https://www.tensorflow.org/code/tensorflow/core/framework/graph.proto)
  protocol buffer, and extract individual objects in the `GraphDef` as
  `tf.Tensor` and `tf.Operation` objects. Once extracted,
  these objects are placed into the current default `Graph`. See
  `tf.Graph.as_graph_def` for a way to create a `GraphDef`
  proto.

  Args:
    graph_def: A `GraphDef` proto containing operations to be imported into the
      default graph.
    input_map: A dictionary mapping input names (as strings) in `graph_def` to
      `Tensor` objects. The values of the named input tensors in the imported
      graph will be re-mapped to the respective `Tensor` values.
    return_elements: A list of strings containing operation names in `graph_def`
      that will be returned as `Operation` objects; and/or tensor names in
      `graph_def` that will be returned as `Tensor` objects.
    validate_colocation_constraints: Whether to validate colocation constraints.
    name: (Optional.) A prefix that will be prepended to the names in
      `graph_def`. Note that this does not apply to imported function names.
      Defaults to `"import"`.
    producer_op_list: (Optional.) An `OpList` proto with the (possibly stripped)
      list of `OpDef`s used by the producer of the graph. If provided,
      unrecognized attrs for ops in `graph_def` that have their default value
      according to `producer_op_list` will be removed. This will allow some more
      `GraphDef`s produced by later binaries to be accepted by earlier binaries.
    propagate_device_spec: Whether to propagate assigned device information
      when importing a graph from a GraphDef into the current default `Graph`.

  Returns:
    A list of `Operation` and/or `Tensor` objects from the imported graph,
    corresponding to the names in `return_elements`,
    and None if `returns_elements` is None.

  Raises:
    TypeError: If `graph_def` is not a `GraphDef` proto,
      `input_map` is not a dictionary mapping strings to `Tensor` objects,
      or `return_elements` is not a list of strings.
    ValueError: If `input_map`, or `return_elements` contains names that
      do not appear in `graph_def`, or `graph_def` is not well-formed (e.g.
      it refers to an unknown tensor).
  Nimport/rK   c                 S   s   g | ]}t |qS r   r;   )r-   sr   r   r   
<listcomp>  s    
z._import_graph_def_internal.<locals>.<listcomp>z, z;Attempted to map inputs that were not found in graph_def: [])#r)   r8   r?   rI   r   Zget_default_graphrM   rL   endswithrO   r   ZScopedTFImportGraphDefOptionsrR   rW   Z_mutation_lockZ	tf_bufferZSerializeToStringZ_c_graphr$   rP   Z!TF_GraphImportGraphDefWithResultsZScopedTFImportGraphDefResultsr   ZInvalidArgumentErrorr   strr^   Zlibraryr	   Zfrom_libraryZadd_to_graphZ:TF_ImportGraphDefResultsMissingUnusedInputMappings_wrapperrb   joinrc   )r'   r7   r>   rT   rA   rG   rU   r\   scoperS   Zscoped_optionsrR   Z
serializedZc_graphrb   eZ	functionsfZmissing_unused_input_keysZmissing_keysr   r   r   rh     sr   4




rh   )F)NNNNN)NF)NNTNNF),__doc__
contextlibZtensorflow.core.frameworkr   Ztensorflow.pythonr   Ztensorflow.python.clientr   rP   Ztensorflow.python.frameworkr   r   r[   r   r	   r
   r   r   Ztensorflow.python.opsr   Ztensorflow.python.utilr   Z"tensorflow.python.util.deprecationr   Z tensorflow.python.util.tf_exportr   r   r   contextmanagerr    r)   r8   r?   rC   rI   rO   rW   r^   rX   rc   r&   re   ri   rh   r   r   r   r   <module>   sf   &
	!
$4:
