o
    ?eI                     @   sL  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re*  dS 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)convert_to_constants)importer)gfile)loader)tag_constants)saved_model_utils)py_checkpoint_reader)saverc                 C   s2   | j  D ]}|jds|jdr dS q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   e/home/www/facesmatcher.com/pyenv/lib/python3.10/site-packages/tensorflow/python/tools/freeze_graph.py_has_no_variables:   s
   	r    c                    s  ~~|st |std| d |std|r1|r&|jjD ]}d|_qn| r1| jD ]}d|_q+| r:tj| dd}t	 }|rPt
j||d}||| n|rnt
j|dd}||| |rm||d	dd
 n|r~|du rvg }t||| n{i }t|}| }dd |j D }d}|D ]' z|j d }t fdd|D rd}W n	 ty   Y qw || < qz	t
j||d}W n ty } z|rtdt|rtd|d}~ww ||| |r||d	dd
 |	r|	d	dd
nd}	|
r|
d	dd
nd}
|r+tj||j|d	dd
|	|
d}ntj|| |d	dd
|	|
d}W d   n	1 sGw   Y  |rpt |d}|!|j"dd W d   |S 1 skw   Y  |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 | ]}|  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    | ]} |v 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_nodesr0   variable_names_denylistinput_meta_graph_definput_saved_model_dirsaved_model_tagscheckpoint_versionr4   _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   .



Y
rQ   c                 C   s   t | std|  d t }|rdnd}t | |#}|r(||  nt	| | W d   |S W d   |S 1 sCw   Y  |S )z2Parses input tensorflow graph into GraphDef proto.zInput graph file '' does not exist!rbrN)
r   ExistsIOErrorr   ZGraphDefr>   ParseFromStringreadr   Merge)input_graphinput_binaryr@   moderP   r   r   r   _parse_input_graph_proto   s   


r]   c                 C   s   t | std|  d t }|rdnd}t | |}|r'||  nt| | W d   n1 s9w   Y  t	d|   |S )z6Parses input tensorflow graph into MetaGraphDef proto.zInput meta graph file 'rR   rS   rT   NzLoaded meta graph file ')
r   rU   rV   r   r>   rW   rX   r   rY   print)rZ   r[   rI   r\   rP   r   r   r   _parse_input_meta_graph_proto   s   
r_   c                 C   s   t | std|  d |rdnd}t | |'}t }|r(||  nt	| | W d   |S W d   |S 1 sCw   Y  |S )z2Parses input tensorflow Saver into SaverDef proto.zInput saver file 'rR   rS   rT   N)
r   rU   rV   r>   r   SaverDefrW   rX   r   rY   )input_saverr[   r\   rP   r   r   r   r   _parse_input_saver_proto  s   


rb   c                 C   s   d}|rt ||j}n| rt| |}d}|rt||}d}|r%t||}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"   )rL   )	r   Zget_meta_graph_defr3   r]   r_   rb   rQ   r9   r'   )rZ   ra   r[   rB   rC   rD   rE   rF   r    rG   r0   rH   input_meta_graphrJ   rK   rL   r@   rI   rA   r   r   r   freeze_graph  sD   /

re   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)rL   r   r`   ZV1V2r2   re   rZ   ra   r[   rB   rC   rD   rE   rF   r    rG   r0   rH   rd   rJ   rK   )unused_argsflagsrL   r   r   r   mainh  s   



rk   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>|  s    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_versionrg   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   rq   rr   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 r+   )rk   )ri   rj   r   r   rp     s   
 r   )rk   argvN)argparseArgumentParserregisteradd_argumentstrintparse_known_argsr   r8   sysrw   )parserZunparsedZmy_mainr   rv   r   run_mainy  s   	r   __main__),__doc__rx   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   r6   r   r`   rh   rQ   r]   r_   rb   ZSERVINGre   rk   r   __name__r   r   r   r   <module>   sV   
 '
Nm
