B
    лd                 @   sh   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
 Zdd ZdS )z4Utilities to remove unneeded nodes from a GraphDefs.    N)text_format)attr_value_pb2)	graph_pb2)node_def_pb2)
graph_util)gfilec             C   sR  x$|D ]}d|krt d| dqW dd |D }t }x| jD ]}|j|kr||j t }d|_|j|_t	|t
r||j}	|jd tj||	 d n|jd tj|d d	|jkr|jd	 |jd	  d
|jkr|jd
 |jd
  |j|g qD|jt|g qDW |rBtd| dt||}
|
S )af  Removes unused nodes from a GraphDef.

  Args:
    input_graph_def: A graph with nodes we want to prune.
    input_node_names: A list of the nodes we use as inputs.
    output_node_names: A list of the output nodes.
    placeholder_type_enum: The AttrValue enum for the placeholder data type, or
        a list that specifies one value per input node name.

  Returns:
    A `GraphDef` with all unnecessary ops removed.

  Raises:
    ValueError: If any element in `input_node_names` refers to a tensor instead
      of an operation.
    KeyError: If any element in `input_node_names` is not found in the graph.
  :zName 'z1' appears to refer to a Tensor, not an Operation.c             S   s   h | ]}|qS  r	   ).0namer	   r	   Z/var/www/html/venv/lib/python3.7/site-packages/tensorflow/python/tools/strip_unused_lib.py	<setcomp>8   s    zstrip_unused.<locals>.<setcomp>ZPlaceholderZdtype)typeZ_output_shapesshapez*The following input nodes were not found: .)
ValueErrorr   GraphDefnoder   remover   ZNodeDefop
isinstancelistindexattrZCopyFromr   Z	AttrValueextendcopydeepcopyKeyErrorr   Zextract_sub_graph)input_graph_definput_node_namesoutput_node_namesplaceholder_type_enumr   	not_foundZinputs_replaced_graph_defr   Zplaceholder_nodeZinput_node_indexoutput_graph_defr	   r	   r   strip_unused   s<    




r$   c          	   C   s  t | std|  d  dS |s.td dS t }|r>dnd}t | |*}	|rd||	  nt	|	 | W dQ R X t
||d|d|}
|rt |d	}	|	|
  W dQ R X n(t |d
}	|	t|
 W dQ R X tdt|
j  dS )z'Removes unused nodes from a graph file.zInput graph file 'z' does not exist!z=You need to supply the name of a node to --output_node_names.rbrN,wbwz%d ops in the final graph.)r   ZExistsprintr   r   ZGFileZParseFromStringreadr   ZMerger$   splitwriteZSerializeToStringZMessageToStringlenr   )Zinput_graphZinput_binaryZoutput_graphZoutput_binaryr   r    r!   r   modefr#   r	   r	   r   strip_unused_from_filesY   s,    
r2   )__doc__r   Zgoogle.protobufr   Ztensorflow.core.frameworkr   r   r   Ztensorflow.python.frameworkr   Ztensorflow.python.platformr   r$   r2   r	   r	   r	   r   <module>   s   <