a
    Sicn                      @   s  d Z ddlZddlZddlZddlZddl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l)m*Z* ddl+m,Z- e. e/dddZ0dCe$j1e2e j3dddZ4dDe$j1e2e j3dddZ5ej6rbdZ7ne(8dZ7ej9:e7s~dZ7dd  Z;e-d!G d"d# d#ej<Z=eej>ej?d$d$e j@e$jAe$jAd$d$ddf	d%d&ZBeej>ejCd'd( ZDd)d* ZEdEd,d-ZFeejGejHdFd.d/ZIdGd0d1ZJe$jAdejKejLdd+d$d$d$d$dd$dddd$d+d+d+d$dd$d$dd$d$dd$d$d$d$d$f d2d3ZMeejGejNd4d5 ZOeejGejNd6d7 ZPeejGejQd8d9 ZReejGejSd:d; ZTe-d<gd=e*Udd>d?d@ ZVdAdB ZWdS )Hz1Converts a frozen graph into a TFLite FlatBuffer.    N)lite_constants)util)	wrap_toco)	Component)convert_phase)ConverterError)SubComponent)metrics_wrapper)model_flags_pb2)toco_flags_pb2)	types_pb2)flatbuffer_utils)dtypes)tensor_shape)resource_loader)deprecation)	tf_export)conversion_flagsreturnc                 C   s(   t jt jg}| j|v s | j|v o&| j S )a7  Checks if the `quantized_input_stats` flag is required for conversion.

  Args:
    conversion_flags: A protocol buffer describing the conversion process.

  Returns:
    True, if the `inference_type` or the `inference_input_type` is a quantized
    type and it is not post training quantization, else False.
  )
_types_pb2QUANTIZED_UINT8QUANTIZED_INT8inference_typeinference_input_typepost_training_quantize)r   Zquantized_inference_types r   Z/var/www/html/django/DPS/env/lib/python3.9/site-packages/tensorflow/lite/python/convert.py"_is_quantized_input_stats_required.   s    
r    )tf_typeusager   c                 C   s   t jtjt jtjt jtjt jtj	t j
tjt jtjt jtjt jtjt jtjt jtjt jtjt jtjt jtjt jtjt jtji}| | }|du rt!d"| ||S )a  Convert tensor type from tf type to tflite type.

  Args:
    tf_type: TensorFlow type.
    usage: Text describing the reason for invoking this function.

  Raises:
    ValueError: If `tf_type` is unsupported.

  Returns:
    tflite_type: TFLite type. Refer to lite/toco/types.proto.
  N6Unsupported TensorFlow type `{0}` provided for the {1})#r   float16r   FLOAT16float32FLOATfloat64FLOAT64int8INT8int16INT16uint16UINT16int32INT32int64INT64uint8UINT8uint32UINT32uint64UINT64stringSTRINGboolBOOL	complex64	COMPLEX64
complex128
COMPLEX128get
ValueErrorformatr   r    mappingZtflite_typer   r   r   %convert_tensor_tf_type_to_tflite_typeA   s0    
rE   c                 C   sJ   t jtjt jtjt jtjt jtj	i}|
| }|du rFtd| ||S )a!  Convert inference type from tf type to tflite type.

  Args:
    tf_type: TensorFlow type.
    usage: Text describing the reason for invoking this function.

  Raises:
    ValueError: If `tf_type` is unsupported.

  Returns:
    tflite_type: TFLite type. Refer to lite/toco/types.proto.
  Nr!   )r   r$   r   r%   r2   r   r(   r   r*   QUANTIZED_INT16r@   rA   rB   rC   r   r   r   (convert_inference_tf_type_to_tflite_typek   s    
rG   z../toco/python/toco_from_protosZtoco_from_protosc                 C   s:   | d u rdS t | tr6zt| W S  ty4   Y n0 | S )Nr   )
isinstancebytessixensure_textUnicodeDecodeError)outputr   r   r   _try_convert_to_unicode   s    
rN   zlite.OpsSetc                   @   s4   e Zd ZdZdZdZdZdZdd Ze	dd	 Z
d
S )OpsSetzEnum class defining the sets of ops available to generate TFLite models.

  WARNING: Experimental interface, subject to change.
  TFLITE_BUILTINSSELECT_TF_OPSTFLITE_BUILTINS_INT8;EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8c                 C   s
   t | jS N)strvalue)selfr   r   r   __str__   s    zOpsSet.__str__c                   C   s   dd t tD S )z6Returns a list of OpsSet options as a list of strings.c                 S   s   g | ]}t |qS r   )rU   ).0optionr   r   r   
<listcomp>       z&OpsSet.get_options.<locals>.<listcomp>)listrO   r   r   r   r   get_options   s    zOpsSet.get_optionsN)__name__
__module____qualname____doc__rP   rQ   rR   rS   rX   staticmethodr^   r   r   r   r   rO      s   rO   Fc
           
      C   s$   t | |||t|t|||||	
S )a  Quantize `input_data_str` with calibration results.

  Args:
    input_data_str: Input data in serialized form (e.g. a TFLITE model with
      calibration results).
    disable_per_channel: Bool indicating whether to do per-channel or per-tensor
      quantization
    fully_quantize: Bool indicating whether to fully quantize the model. Besides
      model body, the input/output will be quantized as well.
    inference_type: Data type for the activations. The default value is int8.
    input_data_type: Data type for the inputs. The default value is float32.
    output_data_type: Data type for the outputs. The default value is float32.
    enable_numeric_verify: Experimental. Subject to change. Bool indicating
      whether to add NumericVerify ops into the debug mode quantized model.
    enable_whole_model_verify: Experimental. Subject to change. Bool indicating
      whether to add verification for layer by layer, or on whole model. When
      disabled (per-layer) float and quantized ops will be run from same input
      (output of previous quantized layer). When enabled, float and quantized
      ops will run with respective float and quantized output of previous ops.
    denylisted_ops: Experimental. Subject to change. Set of ops to denylist.
    denylisted_nodes: Experimental. Subject to change. Set of notes to denylist.

  Returns:
    Quantized model in serialized form (e.g. a TFLITE model) with floating-point
    inputs and outputs.
  )r   Z"wrapped_experimental_mlir_quantizerE   )
input_data_strZdisable_per_channelZfully_quantizer   Zinput_data_typeZoutput_data_typeZenable_numeric_verifyZenable_whole_model_verifyZdenylisted_opsZdenylisted_nodesr   r   r   mlir_quantize   s    %re   c                 C   s
   t | S )zSparsify `input_data_str` to encode sparse tensor with proper format.

  Args:
    input_data_str: Input data in serialized form (e.g. a TFLITE model).

  Returns:
    Sparsified model in serialized form (e.g. a TFLITE model).
  )r   Z"wrapped_experimental_mlir_sparsify)rd   r   r   r   mlir_sparsify   s    
rf   c                 C   s
   t | S )a  Register the given custom opdefs to the TensorFlow global op registry.

  Args:
    custom_opdefs_list: String representing the custom ops OpDefs that are
      included in the GraphDef.

  Returns:
    True if the registration is successfully completed.
  )r   Zwrapped_register_custom_opdefs)Zcustom_opdefs_listr   r   r   register_custom_opdefs  s    
rg   Tc           	   
   C   s|   |st snzt| ||||}|W S  tyl } z4tt|}t D ]}|| qD|W Y d}~n
d}~0 0 t	| |||S )ac  Converts `input_data_str` to a TFLite model.

  Args:
    model_flags_str: Serialized proto describing model properties, see
      `model_flags.proto`.
    conversion_flags_str: Serialized proto describing conversion properties, see
      `toco/toco_flags.proto`.
    input_data_str: Input data in serialized form (e.g. a graphdef is common, or
      it can be hlo text or proto)
    debug_info_str: Serialized `GraphDebugInfo` proto describing logging
      information. (default None)
    enable_mlir_converter: Enables MLIR-based conversion. (default True)

  Returns:
    Converted model in serialized form (e.g. a TFLITE model is common).
  Raises:
    ConverterError: When conversion fails in TFLiteConverter, usually due to
      ops not being supported.
    RuntimeError: When conversion fails, an exception is raised with the error
      message embedded.
  N)
_deprecated_conversion_binaryr   Zwrapped_toco_convert	Exceptionr   rU   _metrics_wrapperZretrieve_collected_errorsZappend_error!_run_deprecated_conversion_binary)	model_flags_strconversion_flags_strrd   debug_info_strenable_mlir_converterZ	model_streZconverter_errorZ
error_datar   r   r   convert  s"    rq   c                 C   s  t jtdu rtdd\}}}}ztjdd}tjdd}	tjdd}
tjdd~}|j}|
j}|	j}|j}|	|  || |
t	
| |r|nd}t|ts||d n
|| W d   n1 s0    Y  W d   n1 s0    Y  W d   n1 s$0    Y  W d   n1 sD0    Y  tjdd}|j}W d   n1 sx0    Y  t||||d|g}d	|}t d
k}tj|dtjtj| d}| \}}|j}|dkrXt|dV}| W  d   W ||||fD ].}zt| W n ttfy<   Y n0 qS 1 sL0    Y  n t|}t|}td||f W ||||fD ].}zt| W n ttfy   Y n0 qn>||||fD ].}zt| W n ttfy   Y n0 q0 dS )a  Convert `input_data_str` using deprecated conversion binary.

  Args:
    model_flags_str: Serialized proto describing model properties, see
      `model_flags.proto`.
    conversion_flags_str: Serialized proto describing TFLite converter
      properties, see `toco/toco_flags.proto`.
    input_data_str: Input data in serialized form (e.g. a graphdef is common)
    debug_info_str: Serialized `GraphDebugInfo` proto describing logging
      information. (default None)

  Returns:
    Converted model in serialized form (e.g. a TFLITE model is common).
  Raises:
    ConverterError: When cannot find the deprecated conversion binary.
    RuntimeError: When conversion fails, an exception is raised with the error
      message embedded.
  Naz  Could not find `toco_from_protos` binary, make sure
your virtualenv bin directory or pip local bin directory is in your path.
In particular, if you have installed TensorFlow with --user, make sure you
add the install directory to your path.

For example:
Linux: export PATH=$PATH:~/.local/bin/
Mac: export PATH=$PATH:~/Library/Python/<version#>/bin

Alternative, use virtualenv.)NNNNF)deleter   zutf-8z--debug_proto_file={} WindowsT)shellstdoutstderr	close_fdsr   rbzSee console for info.
%s
%s
)	distutilsspawnfind_executablerh   r   	_tempfileNamedTemporaryFilenamewriterJ   ensure_binaryrH   rI   encoderB   join	_platformsystem_subprocessPopenPIPESTDOUTcommunicate
returncodeopenread_osunlinkOSError	TypeErrorrN   )rl   rm   rd   rn   Zconversion_filenameZmodel_filenameZinput_filenameZoutput_filenameZfp_conversionZfp_modelZfp_inputZfp_debugdebug_filenamefpcmdcmdlineZ
is_windowsprocrv   rw   exitcodefilenamer   r   r   rk   >  s    




	
&


rk   c                 K   sH   t  }| |_||_|r||_||_|r4|j| |rD|j| |S )a  Builds the model flags object from params.

  Args:
    change_concat_input_ranges: Boolean to change behavior of min/max ranges for
      inputs and outputs of the concat operator for quantized models. Changes
      the ranges of concat operator overlap when true. (default False)
    allow_nonexistent_arrays: Allow specifying array names that don't exist or
      are unused in the final graph. (default False)
    saved_model_dir: Filepath of the saved model to be converted. This value
      will be non-empty only when the saved model import path will be used.
      Otherwises, the graph def-based conversion will be processed.
    saved_model_version: SavedModel file format version of The saved model file
      to be converted. This value will be set only when the SavedModel import
      path will be used.
    saved_model_tags: Set of string saved model tags, formatted in the
      comma-separated value. This value will be set only when the SavedModel
      import path will be used.
    saved_model_exported_names: Names to be exported (default: export all) when
      the saved model import path is on. This value will be set only when the
      SavedModel import path will be used.

  Returns:
    model_flags: protocol buffer describing the model.
  )	_model_flags_pb2
ModelFlagschange_concat_input_rangesallow_nonexistent_arrayssaved_model_dirsaved_model_versionsaved_model_tagsextendsaved_model_exported_names)r   r   r   r   r   r   _model_flagsr   r   r   build_model_flags  s    r   c            "      K   sP  t  }!t| dd|!_|r*t|dd|!_n|!j|!_||!_||!_|rV|d |!_|d |!_||!_	||!_
||!_||!_|	|!_|
r~|
|!_||!_|rtj|v rd|!_t|tjhkrd|!_|r||!_|r|!j| ||!_||!_||!_||!_||!_|rt|dd|!_||!_||!_ |r|!j!| ||!_"||!_#||!_$||!_%||!_&|r@||!_'||!_(||!_)|!S )aX  Builds protocol buffer describing a conversion of a model.

  Typically this is to convert from TensorFlow GraphDef to TFLite, in which
  case the default `input_format` and `output_format` are sufficient.

  Args:
    inference_type: Data type of numeric arrays, excluding the input layer.
      (default tf.float32, must be in {tf.float32, tf.int8, tf.uint8})
    inference_input_type: Data type of the numeric arrays in the input layer. If
      `inference_input_type` is in {tf.int8, tf.uint8}, then
      `quantized_input_stats` must be provided. (default is the value assigned
      to `inference_type`, must be in {tf.float32, tf.int8, tf.uint8})
    input_format: Type of data to read. (default TENSORFLOW_GRAPHDEF, must be in
      {TENSORFLOW_GRAPHDEF})
    output_format: Output file format. (default TFLITE, must be in {TFLITE,
      GRAPHVIZ_DOT})
    default_ranges_stats: Tuple of integers representing (min, max) range values
      for all arrays without a specified range. Intended for experimenting with
      quantization via "dummy quantization". (default None)
    drop_control_dependency: Boolean indicating whether to drop control
      dependencies silently. This is due to TFLite not supporting control
      dependencies. (default True)
    reorder_across_fake_quant: Boolean indicating whether to reorder FakeQuant
      nodes in unexpected locations. Used when the location of the FakeQuant
      nodes is preventing graph transformations necessary to convert the graph.
      Results in a graph that differs from the quantized training graph,
      potentially causing differing arithmetic behavior. (default False)
    allow_custom_ops: Boolean indicating whether to allow custom operations.
      When false any unknown operation is an error. When true, custom ops are
      created for any op that is unknown. The developer will need to provide
      these to the TensorFlow Lite runtime with a custom resolver. (default
      False)
    post_training_quantize: Boolean indicating whether to quantize the weights
      of the converted float model. Model size will be reduced and there will be
      latency improvements (at the cost of accuracy). (default False)
    quantize_to_float16: Boolean indicating whether to convert float buffers to
      float16. (default False)
    dump_graphviz_dir: Full filepath of folder to dump the graphs at various
      stages of processing GraphViz .dot files. Preferred over
      --output_format=GRAPHVIZ_DOT in order to keep the requirements of the
      output file. (default None)
    dump_graphviz_video: Boolean indicating whether to dump the graph after
      every graph transformation. (default False)
    target_ops: Experimental flag, subject to change. Set of OpsSet options
      indicating which converter to use. (default set([OpsSet.TFLITE_BUILTINS]))
    conversion_summary_dir: A string, the path to the generated conversion logs.
    select_user_tf_ops: List of user's defined TensorFlow ops need to be
      supported in the TensorFlow Lite runtime. These ops will be supported as
      select TensorFlow ops.
    allow_all_select_tf_ops: If True, automatically add all TF ops (including
      custom TF ops) to the converted model as flex ops.
    enable_tflite_resource_variables: Experimental flag, subject to change.
      Enables conversion of resource variables. (default False)
    unfold_batchmatmul: Whether to unfold tf.BatchMatMul to a set of
      tfl.fully_connected ops. If not, translate to tfl.batch_matmul.
    lower_tensor_list_ops: Whether to lower tensor list ops to builtin ops. If
      not, use Flex tensor list ops.
    default_to_single_batch_in_tensor_list_ops: Whether to force to use batch
      size one when the tensor list ops has the unspecified batch size.
    accumulation_type: Data type of the accumulators in quantized inference.
      Typically used for float16 quantization and is either fp16 or fp32.
    allow_bfloat16: Whether the converted model supports reduced precision
      inference with the bfloat16 type.
    unfold_large_splat_constant: Whether to unfold large splat constant tensors
      in the flatbuffer model to reduce size.
    supported_backends: List of TFLite backends which needs to check
      compatibility.
    disable_per_channel_quantization: Disable per-channel quantized weights for
      dynamic range quantization. Only per-tensor quantization will be used.
    enable_mlir_dynamic_range_quantizer: Enable MLIR dynamic range quantization.
      If False, the old converter dynamic range quantizer is used.
    tf_quantization_mode: Indicates the mode of TF Quantization when the output
      model is used for TF Quantization.
    disable_infer_tensor_range: Disable infering tensor ranges.
    use_fake_quant_num_bits: Allow quantization parameters to be calculated from
      num_bits attribute.
    enable_dynamic_update_slice: Enable to convert to DynamicUpdateSlice op.
      (default: False).
    preserve_assert_op: Whether to preserve `TF::AssertOp` (default: False).
    guarantee_all_funcs_one_use: Whether to clone functions so that each
      function only has a single use. This option will be helpful if the
      conversion fails when the `PartitionedCall` or `StatefulPartitionedCall`
      can't be properly inlined (default: False).

  Returns:
    conversion_flags: protocol buffer describing the conversion process.
  Raises:
    ValueError, if the input tensor type is unknown.
  zinference_type flagr    zinference_input_type flagr      Tzaccumulation_type flag)*_conversion_flags_pb2	TocoFlagsrG   r   r   input_formatoutput_formatdefault_ranges_mindefault_ranges_maxdrop_control_dependencyreorder_across_fake_quantallow_custom_opsr   quantize_to_float16dump_graphviz_dirdump_graphviz_include_videorO   rQ   enable_select_tf_opssetforce_select_tf_opsconversion_summary_dirselect_user_tf_opsr   allow_all_select_tf_ops enable_tflite_resource_variablesunfold_batchmatmullower_tensor_list_ops*default_to_single_batch_in_tensor_list_opsrE   accumulation_typeallow_bfloat16unfold_large_splat_constantsupported_backends disable_per_channel_quantization#enable_mlir_dynamic_range_quantizerenable_dynamic_update_slicepreserve_assert_opguarantee_all_funcs_one_usetf_quantization_modedisable_infer_tensor_rangeuse_fake_quant_num_bits)"r   r   r   r   Zdefault_ranges_statsr   r   r   r   r   r   Zdump_graphviz_videoZ
target_opsr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   build_conversion_flags  sv    z


r   c                 K   s   t f i |}tf i |}|dd}|dd}t|D ]Z\}	\}
}|j }t|rx|rp||	 \|_|_nt	d|
|_
|jjttt| q<|r|D ]}
|j|
 q|r|D ]}
|j|
 qt| | |  d|d}|S )a  "Convert a frozen GraphDef that can't be loaded in TF.

  Conversion can be customized by providing arguments that are forwarded to
  `build_model_flags` and `build_conversion_flags` (see documentation).

  Args:
    input_data: Input data (i.e. often `sess.graph_def`),
    input_arrays_with_shape: Tuple of strings representing input tensor names
      and list of integers representing input shapes
      (e.g., [("foo" : [1, 16, 16, 3])]). Use only when graph cannot be loaded
        into TensorFlow and when `input_tensors` is None.
    output_arrays: List of output tensors to freeze graph with. Use only when
      graph cannot be loaded into TensorFlow and when `output_tensors` is None.
    control_output_arrays: Control output node names. This is used when
      converting a Graph with no output tensors. For example, if the graph's
      last operation is a Print op, just specify that op's name in this field.
      This can be used together with the `output_arrays` parameter.
    **kwargs: See `build_model_flags` and `build_conversion_flags`.

  Returns:
    The converted data. For example if TFLite was the destination, then
    this will be a tflite flatbuffer in a bytes array.

  Raises:
    Defined in `build_conversion_flags`.
  ro   Tquantized_input_statsNzThe `quantized_input_stats` flag must be defined when either `inference_type` flag or `inference_input_type` flag is set to tf.int8 or tf.uint8.rn   ro   )r   r   r@   	enumerateinput_arraysaddr   
mean_value	std_valuerA   r   shapedimsr   r]   mapintoutput_arraysappendcontrol_output_arraysrq   SerializeToString)
input_dataZinput_arrays_with_shaper   r   kwargsr   r   ro   r   idxr   r   input_arraydatar   r   r   convert_graphdef_with_arrays  s:    
r   c                 K   s  t f i |}tf i |}|dd}|dd}|dd}|dd}	|dd}
t|D ]\}}|j }|r|j|_nt||_t	|j
dd	|_t|r|	r|	| \|_|_n
td
 |du r|j}n|| }|jdurLg }|D ]B}|du st|tjr$|jdu r$|d q|t| q|jj| d|j_q`d|j_q`|D ].}|rt|j|j n|jt| qZt| | |  |
r|
 nd|d}|S )a  Convert a frozen GraphDef model using the TF Lite converter.

  Conversion can be customized by providing arguments that are forwarded to
  `build_model_flags` and `build_conversion_flags` (see documentation).

  Args:
    input_data: Input data (i.e. often `sess.graph_def`),
   input_tensors: List of input tensors. Type and shape are computed using
     `foo.shape` and `foo.dtype`.
    output_tensors: List of output tensors (only .name is used from this).
    **kwargs: See `build_model_flags` and `build_conversion_flags`.

  Returns:
    The converted data. For example if TFLite was the destination, then
    this will be a tflite flatbuffer in a bytes array.

  Raises:
    Defined in `build_conversion_flags`.
  r   Ninput_shapesro   Tr   
debug_infoz"input type of the TensorFlow modelr   zTStatistics for quantized inputs were expected, but not specified; continuing anyway.Fr   )r   r   r@   r   r   r   r   r   Zget_tensor_namerE   dtype	data_typer   r   r   warningswarnr   rankrH   r   	DimensionrV   r   r   r   r   unknown_rankr   rq   r   )r   input_tensorsoutput_tensorsr   r   r   r   r   ro   r   r   r   input_tensorr   r   r   dimoutput_tensorr   r   r   r   convert_graphdef  s`    






r   c                  K   s:   t f i | }tf i | }t| | dddd}|S )z.Converts a SavedModel using TF Lite converter.NTrd   rn   ro   )r   r   rq   r   )r   r   r   r   r   r   r   convert_saved_model#  s    r   c           	      K   sn   t  }d|_|rt jj|_n
t jj|_|D ]}|j }||_q,t	f i |}t
| | | ddd}|S )z6Converts a Jax hlo-based model using TFLite converter.TNr   )r   r   Zuse_hlo_importZ	HLO_PROTOZhlo_file_typeZHLO_TEXTr   r   r   r   rq   r   )	Zinput_contentinput_namesZis_proto_formatr   r   
input_namer   r   r   r   r   r   convert_jax_hlo2  s"    

r   zlite.toco_convert)v1z#Use `lite.TFLiteConverter` instead.c                 O   s*   | dd|d< t| ||g|R i |S )a  Convert a TensorFlow GraphDef to TFLite.

  This function is deprecated. Please use `tf.lite.TFLiteConverter` API instead.
  Conversion can be customized by providing arguments that are forwarded to
  `build_model_flags` and `build_conversion_flags` (see documentation for
  details).
  Args:
    input_data: Input data (i.e. often `sess.graph_def`).
    input_tensors: List of input tensors. Type and shape are computed using
      `foo.shape` and `foo.dtype`.
    output_tensors: List of output tensors (only .name is used from this).
    *args: See `build_model_flags` and `build_conversion_flags`.
    **kwargs: See `build_model_flags` and `build_conversion_flags`.

  Returns:
    The converted TensorFlow Lite model in a bytes array.

  Raises:
    Defined in `convert`.
  ro   F)r@   r   )r   r   r   argsr   r   r   r   toco_convertL  s    r   c                    s  t |  t } jD ] }t }|jD ]`}|jdu r8q(t|jD ]D\}}|jdurn|t|jk rn|j| rnqB|j	| j
r|qB|| qBq(|jD ]D}|jdur|jD ]}|| q|jdur|jD ]}|| qq|jdur|jD ]}|| q|jdur|jD ]}|| q|D ]}	||j	|	 j qq| D ]T}
|
dk s j|
 jdu st j|
 jts j|
 jjdkrB||
 qBt|}t| fddd i }t|D ]\}}||v r֐q j| }||d d D ]T}||v rq j| }|jj|jjkr$ q|jj|jjkr:q|||< qq jD ]X}|jD ]J}|jdu rnqZ|jD ],}|j	| j}
|
|v rt||
 |j	| _qtqZqP|D ]}d j| _qt  S )a  "Generates a new model byte array after deduplicating readonly buffers.

  This function should be invoked after the model optimization toolkit. The
  model optimization toolkit assumes that each tensor object owns its each
  buffer separately.

  Args:
    tflite_model: TFLite flatbuffer in a byte array to be deduplicated.

  Returns:
    TFLite flatbuffer in a bytes array, processed with the deduplication method.

  Nr   c                    s    j |  jj S rT   )buffersr   tobytes)r   modelr   r   <lambda>  r\   z.deduplicate_readonly_buffers.<locals>.<lambda>)keyr   )r   Zconvert_bytearray_to_objectr   	subgraphs	operatorsinputsr   ZmutatingVariableInputslentensorsZ
isVariabler   outputsdiscardintermediatesbuffercopyr   r   rH   r]   sizesortedZconvert_object_to_bytearray)Ztflite_modelZread_only_buffer_indicessubgraphZread_only_input_tensor_indicesopiZinput_tensor_idxZoutput_tensor_idxZintermediate_tensor_idx
tensor_idx
buffer_idxZduplicate_buffer_mapZbuffer_i_idxZbuffer_iZbuffer_j_idxZbuffer_jr   r   r   r   r   deduplicate_readonly_buffersh  s    




















r  )r   )r   )NT)N)FFNr   NN)Xrb   distutils.spawnrz   enumosr   platformr   
subprocessr   tempfiler}   r   rJ   tensorflow.lite.pythonr   r   r   Z$tensorflow.lite.python.convert_phaser   r   r   r   Z&tensorflow.lite.python.metrics.wrapperr	   rj   tensorflow.lite.tocor
   r   r   r   r   r   Ztensorflow.lite.toolsr   tensorflow.python.frameworkr   r   tensorflow.python.platformr   Z_resource_loadertensorflow.python.utilr    tensorflow.python.util.tf_exportr   
_tf_exportr   r:   r   DTyperU   
IODataTyperE   rG   "EXPERIMENTAL_USE_TOCO_API_DIRECTLYrh   get_path_to_datafilepathexistsrN   EnumrO   ZOPTIMIZE_TFLITE_MODELZQUANTIZEr   r$   re   ZSPARSIFYrf   rg   rq   ZCONVERT_TF_TO_TFLITE_MODELZ+CONVERT_GRAPHDEF_USING_DEPRECATED_CONVERTERrk   r   TENSORFLOW_GRAPHDEFTFLITEr   ZCONVERT_GRAPHDEFr   r   ZCONVERT_SAVED_MODELr   ZCONVERT_JAX_HLOr   
deprecatedr   r  r   r   r   r   <module>   s   + (,
  
/ m      
,
 6
@
Q



