o
    i 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)
input_name r   S/var/www/myenv/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)tensor_name
components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   GraphDef	MergeFrom	TypeErrornoder
   getop_SetDefaultAttrValues)	graph_def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   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   	

r?   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   r0   r1   r2   r4   xr   r   r   r6      r7   z._ProcessReturnElementsParam.<locals>.<genexpr>z?Argument `return_elements` must be a list of strings. Obtained r   c                 s   s    | ]}t |V  qd S r1   r   as_strr@   r   r   r   r6      s    )r;   r'   tuple)return_elementsr   r   r   _ProcessReturnElementsParam   s   
rF   c                 C   s"   |j D ]}| |jkr|  S qd S r1   )attrname)	attr_namer.   attr_defr   r   r   _FindAttrInOpDef   s
   

rK   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   )rH   )r4   r*   r   r   r   
<dictcomp>   s    z'_RemoveDefaultAttrs.<locals>.<dictcomp>Ndefault_value)	r*   r(   r
   r)   r=   rG   rK   HasFieldrM   )producer_op_listr,   producer_op_dictr(   r.   producer_op_defkeyrJ   r   r   r   _RemoveDefaultAttrs   s   




rS   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   r0   r1   )r$   r   Tensor)r4   vr   r   r   r6      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()._inputsc                 S   s   i | ]
\}}|t |qS r   )r   convert_to_tensor)r4   r5   rU   r   r   r   rL      s    z*_ConvertInputMapValues.<locals>.<dictcomp>N)r;   valuesr   r   
name_scopeitems)rH   r>   r   r   r   _ConvertInputMapValues   s   
r\   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_api!TF_ImportGraphDefOptionsSetPrefix(TF_ImportGraphDefOptionsSetUniquifyNames.TF_ImportGraphDefOptionsSetPropagateDeviceSpecr[   r   rC   r   _as_tf_outputoper.TF_ImportGraphDefOptionsRemapControlDependencyr"   'TF_ImportGraphDefOptionsAddInputMapping'TF_ImportGraphDefOptionsAddReturnOutput*TF_ImportGraphDefOptionsAddReturnOperation8TF_ImportGraphDefOptionsSetValidateColocationConstraints)optionsprefixr>   rE   validate_colocation_constraintspropagate_device_spec	input_src	input_dstsrc_namedst_opsrc_idx
dst_outputrH   op_nameindexr   r   r    _PopulateTFImportGraphDefOptions   s<   





rt   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} nqC|r~|| q;dS )z3Processes the newly-added TF_Operations in `graph`.F)compute_devicesrV   NzSpecified colocation to an op: z+ that does not exist during import for op: )_add_new_tf_operationsr   _set_device_GetColocationNamesr#   _apply_device_functionsr[   _get_operation_by_nameKeyErrorr   enabledr   EnableControlFlowV2r   rH   pydev
DeviceSpecfrom_string)
graphcolocation_pairsnew_oporiginal_devicecolocation_namesr*   coloc_op_listcoloc_devicecoloc_op_name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:@)get_attrr   r   rC   r   r   rH   append)r*   r   class_valuesval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   )r]   %TF_ImportGraphDefResultsReturnOutputs(TF_ImportGraphDefResultsReturnOperationsr   _get_tensor_by_tf_output_get_operation_by_tf_operation)	requested_return_elementsr   resultsreturn_outputsreturn_operscombined_return_elementsoutputs_idx	opers_idxrH   r   r   r   _GatherReturnElements:  s    



r   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.rM   Nvalue)r*   rH   rG   rN   
WhichOneofCopyFromrM   )node_defr.   rJ   rR   r   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).
  )r>   rE   rH   rO   _import_graph_def_internal)r,   r>   rE   rH   r   rO   r   r   r   r   b  s   4c                 C   s   t | d||dS )zCLike import_graph_def but does not validate colocation constraints.F)rj   rH   rk   r   )r,   rH   rk   r   r   r   import_graph_def_for_function  s   r   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/rV   c                 S   s   g | ]}t |qS r   rB   )r4   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/   r?   rF   rS   r   get_default_graphrZ   rY   endswithr\   r   ScopedTFImportGraphDefOptionsrh   rt   _mutation_lock	tf_bufferSerializeToString_c_graphr)   r]   !TF_GraphImportGraphDefWithResultsScopedTFImportGraphDefResultsr   InvalidArgumentErrorr   strr   libraryr	   from_libraryadd_to_graph:TF_ImportGraphDefResultsMissingUnusedInputMappings_wrapperr   joinr   )r,   r>   rE   rj   rH   rO   rk   r   scoperi   scoped_optionsrh   
serializedc_graphr   e	functionsfmissing_unused_input_keysmissing_keysr   r   r   r     sr   4




r   )F)NNNNN)NF)NNTNNF),__doc__
contextlibtensorflow.core.frameworkr   tensorflow.pythonr   tensorflow.python.clientr   r]   tensorflow.python.frameworkr   r   r~   r   r	   r
   r   r   tensorflow.python.opsr   tensorflow.python.utilr   "tensorflow.python.util.deprecationr    tensorflow.python.util.tf_exportr   r   r"   contextmanagerr#   r/   r?   rF   rK   rS   r\   rt   r   rx   r   r+   r   r   r   r   r   r   r   <module>   sf   &
	!
$4:
