B
    лdH                 @   sJ  d Z ddl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 Z dddddej!j"fddZ#dd Z$dd Z%dd Z&ddddej'ej!j"fddZ(dd  Z)d!d" Z*e+d#krFe*  dS )$ay  Converts checkpoint variables into Const ops in a standalone GraphDef file.

This script is designed to take a GraphDef proto, a SaverDef proto, and a set of
variable values stored in a checkpoint file, and output a GraphDef with all of
the variable ops converted into const ops containing the values of the
variables.

It's useful to do this when we need to load a single file in C++, especially in
environments like mobile or embedded where we may not have access to the
RestoreTensor ops and file loading calls that they rely on.

An example of command-line usage is:
bazel build tensorflow/python/tools:freeze_graph && \
bazel-bin/tensorflow/python/tools/freeze_graph \
--input_graph=some_graph_def.pb \
--input_checkpoint=model.ckpt-8361242 \
--output_graph=/tmp/frozen_graph.pb --output_node_names=softmax

You can also look at freeze_graph_test.py for an example of how to use it.

    N)app)text_format)	graph_pb2)	saver_pb2)MetaGraphDef)checkpoint_management)session)
graph_util)importer)gfile)loader)tag_constants)saved_model_utils)py_checkpoint_reader)saverc             C   s4   x.| j  D ] }|jds(|jdrdS qW dS )zjDetermines if the graph has any variables.

  Args:
    sess: TensorFlow Session.

  Returns:
    Bool.
  VariableZ
VariableOpFT)graphget_operationstype
startswithendswith)sessop r   V/var/www/html/venv/lib/python3.7/site-packages/tensorflow/python/tools/freeze_graph.py_has_no_variables:   s    	r    c                s  ~~|s"t |s"td| d |s.td|rj|rPx2|jjD ]
}d|_q@W n| rjx| jD ]
}d|_q\W | r|tj| dd}t	 .}|rt
j||d}||| n|rt
j|dd}||| |r||d	dd
 nB|r|dkrg }t||| ni }t|}| }dd |j D }d}xb|D ]Z y0|j d }t fdd|D rrd}W n tk
r   w@Y nX || < q@W yt
j||d}W nN tk
r } z.|rtdnt|rtddS |W dd}~X Y nX ||| |r*||d	dd
 |	rB|	d	dd
nd}	|
r^|
d	dd
nd}
|rtj||j|d	dd
|	|
d}n"tj|| |d	dd
|	|
d}W dQ R X |rt |d}|!|j"dd W dQ R X |S )a  Converts all variables in a graph and checkpoint into constants.

  Args:
    input_graph_def: A `GraphDef`.
    input_saver_def: A `SaverDef` (optional).
    input_checkpoint: The prefix of a V1 or V2 checkpoint, with V2 taking
      priority.  Typically the result of `Saver.save()` or that of
      `tf.train.latest_checkpoint()`, regardless of sharded/non-sharded or
      V1/V2.
    output_node_names: The name(s) of the output nodes, comma separated.
    restore_op_name: Unused.
    filename_tensor_name: Unused.
    output_graph: String where to write the frozen `GraphDef`.
    clear_devices: A Bool whether to remove device specifications.
    initializer_nodes: Comma separated string of initializer nodes to run before
                       freezing.
    variable_names_whitelist: The set of variable names to convert (optional, by
                              default, all variables are converted).
    variable_names_denylist: The set of variable names to omit converting
                              to constants (optional).
    input_meta_graph_def: A `MetaGraphDef` (optional),
    input_saved_model_dir: Path to the dir with TensorFlow 'SavedModel' file
                           and variables (optional).
    saved_model_tags: Group of comma separated tag(s) of the MetaGraphDef to
                      load, in string format (optional).
    checkpoint_version: Tensorflow variable file format (saver_pb2.SaverDef.V1
                        or saver_pb2.SaverDef.V2)

  Returns:
    Location of the output_graph_def.
  zInput checkpoint 'z' doesn't exist!z=You need to supply the name of a node to --output_node_names.r   )name)	saver_defwrite_versionT)clear_devices ,Nc             S   s8   g | ]0}|  D ]"}td |jr|jdd qqS )z
/part_\d+/:r   )valuesresearchr   split).0r   tensorr   r   r   
<listcomp>   s   z0freeze_graph_with_def_protos.<locals>.<listcomp>Fz:0c             3   s   | ]} |kV  qd S )Nr   )r(   r   )keyr   r   	<genexpr>   s    z/freeze_graph_with_def_protos.<locals>.<genexpr>)var_listr   zModels containing partition variables cannot be converted from checkpoint files. Please pass in a SavedModel using the flag --input_saved_model_dir.zuNo variables were found in this model. It is likely the model was frozen previously. You cannot freeze a graph twice.r   )variable_names_whitelistZvariable_names_blacklistwb)Zdeterministic)#r   Zcheckpoint_exists
ValueError	graph_defnodeZdevicer
   Zimport_graph_defr   Session	saver_libZSaverrestoreZimport_meta_graphrunreplacer'   r   loadr   ZNewCheckpointReaderZget_variable_to_shape_mapr   r   Zget_tensor_by_nameanyKeyError	TypeErrorr   r	   Zconvert_variables_to_constantsr   GFilewriteZSerializeToString)input_graph_definput_saver_definput_checkpointoutput_node_namesrestore_op_namefilename_tensor_nameoutput_graphr    initializer_nodesr.   variable_names_denylistinput_meta_graph_definput_saved_model_dirsaved_model_tagscheckpoint_versionr2   _r   r   Zrestorerr-   readerZvar_to_shape_mapZall_partition_variable_namesZhas_partition_varr)   eZoutput_graph_deffr   )r+   r   freeze_graph_with_def_protosI   s    .








rO   c          	   C   sn   t | std|  d t }|r*dnd}t | |*}|rP||  nt	| | W dQ R X |S )z2Parses input tensorflow graph into GraphDef proto.zInput graph file 'z' does not exist!rbrN)
r   ExistsIOErrorr   ZGraphDefr<   ParseFromStringreadr   Merge)input_graphinput_binaryr>   moderN   r   r   r   _parse_input_graph_proto   s    
rZ   c          	   C   sx   t | std|  d t }|r(dnd}t | |*}|rN||  nt| | W dQ R X t	d|   |S )z6Parses input tensorflow graph into MetaGraphDef proto.zInput meta graph file 'z' does not exist!rP   rQ   NzLoaded meta graph file ')
r   rR   rS   r   r<   rT   rU   r   rV   print)rW   rX   rG   rY   rN   r   r   r   _parse_input_meta_graph_proto   s    
r\   c          	   C   sn   t | std|  d |r"dnd}t | |2}t }|rP||  nt	| | W dQ R X |S )z2Parses input tensorflow Saver into SaverDef proto.zInput saver file 'z' does not exist!rP   rQ   N)
r   rR   rS   r<   r   SaverDefrT   rU   r   rV   )input_saverrX   rY   rN   r   r   r   r   _parse_input_saver_proto  s    
r_   c             C   s   d}|rt ||j}n| r&t| |}d}|r8t||}d}|rJt||}t|||||||||	|
|||dd |dddD |dS )ag  Converts all variables in a graph and checkpoint into constants.

  Args:
    input_graph: A `GraphDef` file to load.
    input_saver: A TensorFlow Saver file.
    input_binary: A Bool. True means input_graph is .pb, False indicates .pbtxt.
    input_checkpoint: The prefix of a V1 or V2 checkpoint, with V2 taking
      priority.  Typically the result of `Saver.save()` or that of
      `tf.train.latest_checkpoint()`, regardless of sharded/non-sharded or
      V1/V2.
    output_node_names: The name(s) of the output nodes, comma separated.
    restore_op_name: Unused.
    filename_tensor_name: Unused.
    output_graph: String where to write the frozen `GraphDef`.
    clear_devices: A Bool whether to remove device specifications.
    initializer_nodes: Comma separated list of initializer nodes to run before
                       freezing.
    variable_names_whitelist: The set of variable names to convert (optional, by
                              default, all variables are converted),
    variable_names_denylist: The set of variable names to omit converting
                              to constants (optional).
    input_meta_graph: A `MetaGraphDef` file to load (optional).
    input_saved_model_dir: Path to the dir with TensorFlow 'SavedModel' file and
                           variables (optional).
    saved_model_tags: Group of comma separated tag(s) of the MetaGraphDef to
                      load, in string format.
    checkpoint_version: Tensorflow variable file format (saver_pb2.SaverDef.V1
                        or saver_pb2.SaverDef.V2).
  Returns:
    String that is the location of frozen GraphDef.
  Nc             S   s   g | ]}|r|qS r   r   )r(   tagr   r   r   r*   d  s    z freeze_graph.<locals>.<listcomp>r!   r   r"   )rJ   )	r   Zget_meta_graph_defr1   rZ   r\   r_   rO   r7   r'   )rW   r^   rX   r@   rA   rB   rC   rD   r    rE   r.   rF   input_meta_graphrH   rI   rJ   r>   rG   r?   r   r   r   freeze_graph  s:    /

rb   c             C   s~   |j dkrtjj}n"|j dkr(tjj}ntd|j  t|j|j|j	|j
|j|j|j|j|j|j|j|j|j|j|j| d S )N      z3Invalid checkpoint version (must be '1' or '2'): %d)rJ   r   r]   ZV1V2r0   rb   rW   r^   rX   r@   rA   rB   rC   rD   r    rE   r.   rF   ra   rH   rI   )unused_argsflagsrJ   r   r   r   mainh  s    




rh   c                 sx  t  } | dddd  | jdtddd | jd	tdd
d | jdtddd | jdtddd | jdtddd | jddddddd | jdtddd | jdtddd | jdtddd | jd ddddd!d | jd"tdd#d | jd$tdd%d | jd&tdd'd | jd(tdd)d | jd*tdd+d | jd,td-d.d |  \ } fd/d}tj|t	j
d0 g| d1 d2S )3zMain function of freeze_graph.r   boolc             S   s   |   dkS )Ntrue)lower)vr   r   r   <lambda>|      zrun_main.<locals>.<lambda>z--input_graphr   z#TensorFlow 'GraphDef' file to load.)r   defaulthelpz--input_saverzTensorFlow saver file to load.z--input_checkpointz"TensorFlow variables file to load.z--checkpoint_versionrd   zTensorflow variable file formatz--output_graphzOutput 'GraphDef' file name.z--input_binary?TFz-Whether the input files are in binary format.)nargsconstr   ro   rp   z--output_node_namesz.The name of the output nodes, comma separated.z--restore_op_namezsave/restore_allzg      The name of the master restore operator. Deprecated, unused by updated       loading code.
      z--filename_tensor_namezsave/Const:0zl      The name of the tensor holding the save path. Deprecated, unused by       updated loading code.
      z--clear_devicesz(Whether to remove device specifications.z--initializer_nodeszAComma separated list of initializer nodes to run before freezing.z--variable_names_whitelistz      Comma separated list of variables to convert to constants. If specified,       only those variables will be converted to constants.      z--variable_names_denylistzN      Comma separated list of variables to skip converting to constants.      z--input_meta_graphz'TensorFlow 'MetaGraphDef' file to load.z--input_saved_model_dirz@Path to the dir with TensorFlow 'SavedModel' file and variables.z--saved_model_tagsZservez      Group of tag(s) of the MetaGraphDef to load, in string format,      separated by ','. For tag-set contains multiple tags, all tags       must be passed in.      c                s
   t |  S )N)rh   )rf   )rg   r   r   rm     rn   r   )rh   argvN)argparseArgumentParserregisteradd_argumentstrintparse_known_argsr   r6   sysrt   )parserZunparsedZmy_mainr   )rg   r   run_mainy  s    r~   __main__),__doc__ru   r%   r|   Zabslr   Zgoogle.protobufr   Ztensorflow.core.frameworkr   Ztensorflow.core.protobufr   Z'tensorflow.core.protobuf.meta_graph_pb2r   Ztensorflow.python.checkpointr   Ztensorflow.python.clientr   Ztensorflow.python.frameworkr	   r
   Ztensorflow.python.platformr   Ztensorflow.python.saved_modelr   r   Ztensorflow.python.toolsr   Ztensorflow.python.trainingr   r   r4   r   r]   re   rO   rZ   r\   r_   ZSERVINGrb   rh   r~   __name__r   r   r   r   <module>#   sN    ?m
