
    BVh+                         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Z
dZd	Zd
ZdZ G d de      Z G d d      Z e	d      dd       Zy)a  TensorFlow Authoring tool package for TFLite compatibility.

WARNING: The package is experimental and subject to change.

This package provides a way to check TFLite compatibility at model authoring
time.

Example:
    @tf.lite.experimental.authoring.compatible
    @tf.function(input_signature=[
        tf.TensorSpec(shape=[None], dtype=tf.float32)
    ])
    def f(x):
      return tf.cosh(x)

    result = f(tf.constant([0.0]))

    > COMPATIBILITY WARNING: op 'tf.Cosh' require(s) "Select TF Ops" for model
    > conversion for TensorFlow Lite.
    > Op: tf.Cosh
    >   - tensorflow/python/framework/op_def_library.py:xxx
    >   - tensorflow/python/ops/gen_math_ops.py:xxx
    >   - simple_authoring.py:xxx
    N)converter_error_data_pb2)convert)lite)	tf_exportzCustom ops: zTF Select ops: zCOMPATIBILITY ERRORzCOMPATIBILITY WARNINGz)tensorflow/python/framework/func_graph.pyc                       e Zd ZdZy)CompatibilityErrorz6Raised when an error occurs with TFLite compatibility.N)__name__
__module____qualname____doc__     Z/home/dcms/DCMS/lib/python3.12/site-packages/tensorflow/lite/python/authoring/authoring.pyr   r   6   s    >r   r   c                   `    e Zd ZdZ	 	 	 ddZd Zd Zd Zd Zd Z	d	 Z
d
 Zd Zd Zd Zd Zy)_CompatiblezdA decorator class to check TFLite compatibility created by `lite.experimental.authoring.compatible`.Nc                     t        j                  | |       || _        d| _        d| _        g | _        || _        || _        || _        y)a  Initialize the decorator object.

    Here is the description of the object variables.
    - _func     : decorated function.
    - _obj_func : for class object, we need to use this object to provide `self`
                  instance as 1 first argument.
    - _verified : whether the compatibility is checked or not.

    Args:
      target: decorated function.
      converter_target_spec : target_spec of TFLite converter parameter.
      converter_allow_custom_ops : allow_custom_ops of TFLite converter
          parameter.
      raise_exception : to raise an exception on compatibility issues.
          User need to use get_compatibility_log() to check details.
    NF)		functoolsupdate_wrapper_func	_obj_func	_verified_log_messages_raise_exception_converter_target_spec_converter_allow_custom_ops)selftargetconverter_target_specconverter_allow_custom_opsraise_exceptions        r   __init__z_Compatible.__init__>   sI    * T6*DJDNDND+D"7D'AD$r   c                 H    | j                   j                  ||      | _        | S )zA Python descriptor interface.)r   __get__r   )r   instanceclss      r   r#   z_Compatible.__get__\   s    ZZ''#6DNKr   c                 J    | j                   | j                   S | j                  S )zoReturns decorated function object.

    For a class method, use self._obj_func to provide `self` instance.
    )r   r   r   s    r   	_get_funcz_Compatible._get_funca   s"    
 ~~!^^ZZr   c                    | j                   s| j                         } |j                  |i |}t        j                  j                  |g|      }| j                  | j                  |_        | j                  | j                  |_	        	 |j                          d| _          | j                         |i |S # t        j                  $ r}| j                  |       Y d}~Fd}~ww xY w# d| _         w xY w)zCalls decorated function object.

    Also verifies if the function is compatible with TFLite.

    Returns:
      A execution result of the decorated function.
    NT)r   r(   get_concrete_functionr   TFLiteConverterV2from_concrete_functionsr   target_specr   allow_custom_opsr   ConverterError_decode_error)r   argskwargsmodelconcrete_func	convertererrs          r   __call__z_Compatible.__call__k   s     >>nne1e114B6Bm((@@/5"i 
	$	$	0 $ ; ;			)	)	5%)%E%E	" 4>>T,V,, ##  3  s*   B8 8C&C!C) !C&&C) )	C2c                 B     | j                         j                  |i |S )z6Returns a concrete function of the decorated function.)r(   r*   )r   r1   r2   s      r   r*   z!_Compatible.get_concrete_function   s!    14>>114B6BBr   c                 b   g }t        |j                        D ]  }|j                  t        j                  j
                  k(  r@|j                  d|j                  j                   d|j                  j                          j|j                  t        |              dj                  |      }|S )z/Dump location of ConveterError.errors.location.z  - :
)reversedcalltyper   ConverterErrorDataCALLSITELOCappendsourcefilenamelinestrjoin)r   location	callstacksingle_callcallstack_dumps        r   _get_location_stringz _Compatible._get_location_string   s    I. +
--
"
5
5
A
AB;%%../q1C1C1H1H0IJ	L 	[)*+ YYy)Nr   c                     t        dt        |            D ]3  }| j                  ||         }d||    d| d}| j                  |       5 y)z#Dump the list of ops and locations.r   zOp: r;   N)rangelenrK   _log)r   ops	locationsirJ   
err_strings         r   _dump_error_detailsz_Compatible._dump_error_details   sU    1c#h 001>n#a&N#326j
ii
r   c                 T   t        |      j                         D ]  }|j                  t              r0|t	        t              d }t
         d| d}| j                  |       H|j                  t              s^|t	        t              d }t         d| d}| j                  |        y)z/Parses the given legacy ConverterError for OSS.N: op '' is(are) not natively supported by TensorFlow Lite. You need to provide a custom operator. https://www.tensorflow.org/lite/guide/ops_customw' require(s) "Select TF Ops" for model conversion for TensorFlow Lite. https://www.tensorflow.org/lite/guide/ops_select)	rE   
splitlines
startswith_CUSTOM_OPS_HDRrN   _AUTHORING_ERROR_HDRrO   _TF_OPS_HDR_AUTHORING_WARNING_HDR)r   r6   rD   
custom_opsrS   tf_opss         r   _decode_error_legacyz _Compatible._decode_error_legacy   s    C##% 		)#o./0
#$F:, 7I I 	 			*??;'c+&'(%&fVH 5? ? 	 			*!r   c                 n   g }g }g }g }g }|j                   D ]  }|j                  t        j                  j                  k(  rA|j                  |j                  j                         |j                  |j                         l|j                  t        j                  j                  k(  rA|j                  |j                  j                         |j                  |j                         |j                  t        j                  j                  k(  r|j                  |j                  j                         | j                  |j                  j                         d          | j                  | j                  |j                        dz          {| j                  t         d|j                          | j                  | j                  |j                        dz           |rIdj!                  t#        |            }t         d| d}| j                  |       | j%                  ||       |rIdj!                  t#        |            }	t&         d|	 d}| j                  |       | j%                  ||       |r8dj!                  t#        |            }
t&         d|
 d}| j                  |       y	y	)
zEParses the given ConverterError which has detailed error information.r   r;   z: z, rV   rW   rX   zf' aren't compatible with TensorFlow Lite GPU delegate. https://www.tensorflow.org/lite/performance/gpuN)errors
error_coder   r?   ERROR_NEEDS_CUSTOM_OPSrA   operatornamerG   ERROR_NEEDS_FLEX_OPSERROR_GPU_NOT_COMPATIBLErO   error_messagerY   rK   r\   rF   sortedrT   r^   )r   r6   r_   custom_ops_locationr`   tf_ops_locationgpu_not_compatible_opscustom_ops_strrS   
tf_ops_strnot_compatible_ops_strs              r   _decode_converter_errorz#_Compatible._decode_converter_error   sW   JFOzz B	3FF]]	]#,,++,""3<<0>>5HH]]]cll''(s||,>>5HHaaa%%cll&7&78 			###..034		$++CLL9D@A 			)*"S->->,?@A		$++CLL9D@A'B* yy
!34n!"&(8 9G G  ii

z+>?99VF^,j#$F:, 7= =  ii

v7#yy0F)GH#$F+A*B C< <  ii
 r   c                     t        |d      r| j                  |       n| j                  |       | j                  r.| j                  r!t        dt        | j                               yy)zEParses the given ConverterError and generates compatibility warnings.rc   zCompatibilityException at N)hasattrrr   ra   r   r   r   reprr   )r   r6   s     r   r0   z_Compatible._decode_error   s^    sH
""3'
$!3!3!;D<L;MNOO "4r   c                 P    | j                   j                  |       t        |       y)z0Log and print authoring warning / error message.N)r   rA   print)r   messages     r   rO   z_Compatible._log   s    g&	'Nr   c                 H    | j                   st        d      | j                  S )a  Returns list of compatibility log messages.

    WARNING: This method should only be used for unit tests.

    Returns:
      The list of log messages by the recent compatibility check.
    Raises:
      RuntimeError: when the compatibility was NOT checked.
    z'target compatibility isn't verified yet)r   RuntimeErrorr   r'   s    r   get_compatibility_logz!_Compatible.get_compatibility_log   s#     >>BCCr   )NNF)r	   r
   r   r   r!   r#   r(   r7   r*   rK   rT   ra   rr   r0   rO   r{   r   r   r   r   r   ;   sP    l &**.$	B<
-8C(4lP
r   r   z&lite.experimental.authoring.compatiblec                 4    | fd}|S t        | fi S )a  Wraps `tf.function` into a callable function with TFLite compatibility checking.

  Example:

  ```python
  @tf.lite.experimental.authoring.compatible
  @tf.function(input_signature=[
      tf.TensorSpec(shape=[None], dtype=tf.float32)
  ])
  def f(x):
      return tf.cosh(x)

  result = f(tf.constant([0.0]))
  # COMPATIBILITY WARNING: op 'tf.Cosh' require(s) "Select TF Ops" for model
  # conversion for TensorFlow Lite.
  # Op: tf.Cosh
  #   - tensorflow/python/framework/op_def_library.py:748
  #   - tensorflow/python/ops/gen_math_ops.py:2458
  #   - <stdin>:6
  ```

  WARNING: Experimental interface, subject to change.

  Args:
    target: A `tf.function` to decorate.
    converter_target_spec : target_spec of TFLite converter parameter.
    **kwargs: The keyword arguments of the decorator class _Compatible.

  Returns:
     A callable object of `tf.lite.experimental.authoring._Compatible`.
  c                     t        | fi S )Nr   )r   r   r2   s    r   wrapperzcompatible.<locals>.wrapper)  s    !6A&AAr   r~   )r   r   r2   r   s    `` r   
compatibler     s)    B ^BNv4???r   )NN)r   r   %tensorflow.compiler.mlir.lite.metricsr   tensorflow.lite.pythonr   r    tensorflow.python.util.tf_exportr   
_tf_exportr[   r]   r\   r^   _FUNC_GRAPH_SRC_PATH	Exceptionr   r   r   r   r   r   <module>r      sn   0  J * ' D !, 0 B  
I IX 45%@ 6%@r   