
    ij2                         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Z G d	 d
      Z	 ddZd Zd Ze j*                  d        Ze j*                  d        Zd Zy)    N)backend)treeconvert_spec_to_tensor)get_input_signature)io_utils)
tensorflowc                 l   t        |      }||nd}|j                  d      st        d|       t        j                         dk(  rt	        | |f||d|S t        j                         dk7  rt        d      t        d| |d	|}|j                  |       |rt        j                  d
| d       yy)a  Export the model as a LiteRT artifact for inference.

    Args:
        model: The Keras model to export.
        filepath: The path to save the exported artifact.
        input_signature: Optional input signature specification. If
            `None`, it will be inferred.
            Note: With the PyTorch backend, dynamic input shapes are not
            supported. Any dynamic dimensions (represented as `None`) will
            be automatically replaced with `1` during export, which may
            cause runtime failures for other shapes. You must explicitly
            pass a fixed static `input_signature` matching your maximum
            runtime shape.
        **kwargs: Additional keyword arguments passed to the exporter.
    NT.tfliteDThe LiteRT export requires the filepath to end with '.tflite'. Got: torch)input_signatureverboser	   z[The LiteRT export API is currently only available with the TensorFlow and PyTorch backends.)modelr   Saved artifact at ''. )	strendswith
ValueErrorr   export_litert_via_torchLiteRTExporterexportr   	print_msg)r   filepathr   r   kwargsactual_verboseexporters          l/var/www/html/emotional.easysim.app/public_html/venv/lib/python3.12/site-packages/keras/src/export/litert.pyexport_litertr       s    , 8}H ' 3WNY''j*
 	

 G#&
 ,"	

 
 	
 L(8
 	

  ' H
 OOH0
"=>     c                   ,    e Zd ZdZ	 ddZd Zd Zd Zy)r   a.  Exporter for the LiteRT (TFLite) format.

    This class handles the conversion of Keras models for LiteRT runtime and
    generates a `.tflite` model file. For efficient inference on mobile and
    embedded devices, it creates a single callable signature based on the
    model's `call()` method.
    Nc                 .    || _         || _        || _        y)a  Initialize the LiteRT exporter.

        Args:
            model: The Keras model to export
            input_signature: Input signature specification (e.g., TensorFlow
                TensorSpec or list of TensorSpec)
            **kwargs: Additional export parameters
        N)r   r   r   )selfr   r   r   s       r   __init__zLiteRTExporter.__init__P   s     
.r!   c                    | j                   t        | j                        | _         t        | j                   t        t
        f      s| j                   g| _         |j                  d      st        d|       | j                  | j                         }t        |d      5 }|j                  |       ddd       |S # 1 sw Y   |S xY w)zExports the Keras model to a TFLite file.

        Args:
            filepath: Output path for the exported model

        Returns:
            Path to exported model
        Nr   r   wb)r   r   r   
isinstancelisttupler   r   _convert_to_tfliteopenwrite)r$   r   tflite_modelfs       r   r   zLiteRTExporter.exportb   s     ' $7tzz#BD 
 $..u>$($8$8#9D   +##+*. 
 ..t/C/CD(D! 	"QGGL!	" 	" s   B;;Cc                    ddl m} t        j                         5 }|j	                         }|j                  | j                         |j                  dt        j                  | j                  j                  d      |       |j                  |d       t        j                  j                  j                  |      }t        j                  j                   j"                  t        j                  j                   j$                  g|j&                  _        d|_        | j-                  |       |j/                         cd	d	d	       S # 1 sw Y   y	xY w)
a  Converts the Keras model to TFLite format.

        Uses Keras ExportArchive as an intermediate SavedModel step.
        This aligns with TensorFlow's official Keras 3 TFLite conversion path:
        ExportArchive -> SavedModel -> from_saved_model.

        Args:
            input_signature: Input signature for the model to convert.

        Returns:
            A bytes object containing the serialized TFLite model.
        r   )r   serveF)training)r   )r   TN)	keras.srcr   tempfileTemporaryDirectoryExportArchivetrackr   add_endpoint	functoolspartial__call__	write_outtfliteTFLiteConverterfrom_saved_modelOpsSetTFLITE_BUILTINSSELECT_TF_OPStarget_specsupported_ops&experimental_enable_resource_variables_apply_converter_kwargsconvert)r$   r   keras_exportsaved_model_dirarchive	converters         r   r+   z!LiteRTExporter._convert_to_tflite   s    	5((* 	'o"002GMM$**%  !!$**"5"5F / ! 
 ou=//@@I ..,,3I!!/ @DI<((3$$&'	' 	' 	's   D#EEc                 l   | j                   j                         D ]  \  }}|dk(  ret        |t              rU|j                         D ]A  \  }}t	        |j
                  |      rt        |j
                  ||       4t        d| d       pt	        ||      rt        |||       t        d| d       y)zApply additional converter settings from kwargs.

        Args:
            converter: tf.lite.TFLiteConverter instance to configure

        Raises:
            ValueError: If any kwarg is not a valid converter attribute
        rD   zUnknown target_spec attribute ''zUnknown converter attribute 'N)r   itemsr(   dicthasattrrD   setattrr   )r$   rL   attrvaluespec_key
spec_values         r   rG   z&LiteRTExporter._apply_converter_kwargs   s      ;;,,. 	JKD%}$E4)@,1KKM (Hjy44h?	 5 5xL(=hZqI 	 D)	4/ #@a!HII	Jr!   N)__name__
__module____qualname____doc__r%   r   r+   rG   r   r!   r   r   r   G   s#     $B"'HJr!   r   c                 J   ddl m} ddl m}  |       }t               5  	 ddl}|dk7  rE| j                  D ]6  }	|	j                  j                  j                  d      |	j                  _        8 	  |d      5  |t        |       }t        j                  d |      }
t        |
      }
| j                          t        ||      }t!        |du       5  	  |j"                  | |
fi |}|j)                  |       ddd       ddd       |dk7  rF| j                  D ]6  }	|	j                  j                  j                  |      |	j                  _        8 	 ddd       |durt+        j,                  d
| d       |S # t
        $ r t        d      w xY w# t$        $ r}t'        d	|       |d}~ww xY w# 1 sw Y   xY w# 1 sw Y   xY w# |dk7  rF| j                  D ]6  }	|	j                  j                  j                  |      |	j                  _        8 w w xY w# 1 sw Y   xY w)z1Export Keras model to LiteRT via PyTorch backend.r   )device_scope)
get_deviceNzTo export to LiteRT with the PyTorch backend, you must install the `litert-torch` package. Install via: pip install litert-torchcpuc                     t        | d      S )N   )replace_none_numberr   )xs    r   <lambda>z)export_litert_via_torch.<locals>.<lambda>   s    4QAN r!   FzFailed to convert PyTorch model to LiteRT. Common causes: unsupported operations, dynamic shapes, or complex control flow. Original error: r   r   )keras.src.backend.torch.corer]   r^   _preserve_jax_x64_statelitert_torchImportError	variablesrT   datator   r   map_structurer*   eval_prepare_litert_kwargs_silence_outputrH   	ExceptionRuntimeErrorr   r   r   )r   r   r   r   r   r]   r^   devicerg   vsample_inputslitert_torch_kwargs
edge_modeles                 r   r   r      s0    :7\F
 
!	" 5;	 U?__ 6 ww||u56'	;e$ "0"*&9%&@O $ 2 2N#! !&m 4 

&<L'# %W%56 0
!%9\%9%9!=&4G&
 %%h/0+"0H  ;A#$77<<??6#:AGGL;i5;n e0
"=>Oo  	8 	L % !*/ 01c3
  !!!0 0+"0 "0H  ;A#$77<<??6#:AGGL; g5; 5;s   HE9A
H/G	7AF=F1F&F17F=?G	AH9FH	F.	F)	)F.	.F11F:6F==G	G		AHHH"c                 L   i }t        |      | j                         D ]  \  }}|v s|||<    d| v rd|vrt        | d   |      }|||d<   t        fd| D              }|r?t        dhz        }t	        ddj                  |       ddj                  |       d      |S )zDPrepare litert_torch conversion kwargs from user-provided arguments.optimizationsquant_configc              3   4   K   | ]  }|vr	|d k7  r|  yw)ry   Nr   ).0keyvalid_litert_torch_argss     r   	<genexpr>z)_prepare_litert_kwargs.<locals>.<genexpr>  s)      --#2H 	s   zBUnsupported arguments for LiteRT export with the PyTorch backend: z, z. Supported arguments are: .)_get_litert_torch_kwarg_namesrO   '_create_quant_config_from_optimizationssortedr   join)	r   rg   ru   krs   	quant_cfgunsupported_argssupported_argsr~   s	           @r   rn   rn   	  s    ;LI '1''%&"' & ^;N%N;?#\
	  2;/  
  7?:K KL		"234 5IIn-.a1
 	
 r!   c                     t        j                  | j                        j                  D ch c]  }|dvr|
 c}S c c}w )N>   modulesample_argssample_kwargs)inspect	signaturerH   
parameters)rg   names     r   r   r   )  sD     %%l&:&:;FFAA 	  s   <c               #      K   	 dd l } | j                  j                  }	 d  | | j                  j	                  d|       y y # t        $ r d } d }Y 4w xY w# | | j                  j	                  d|       w w xY ww)Nr   jax_enable_x64)jaxconfigr   rh   update)r   original_x64s     r   rf   rf   1  s     1
 zz00>?JJ.=    ?JJ.= s=   A:A A:A  A:AA:AA:!A77A:c              #     K   | sd  y t        j                  t        j                               5  t        j                  t        j                               5  d  d d d        d d d        y # 1 sw Y   xY w# 1 sw Y   y xY wwrW   )
contextlibredirect_stdoutioStringIOredirect_stderr)should_silences    r   ro   ro   B  sh     		#	#BKKM	2 ''6 		 	 	 s4   /B(A;A/A;&	B/A8	4A;;B Bc                 .   | sy	 ddl m} ddl m} ddlm} 	 t        j                  j                  j                  }t        t        j                  j                  dd      }t        t        j                  j                  dd      }|| v }|xr || v }	|xr || v }
|s|	s|
r=|xr |	xs |
 }|
xs |	} |||d	
      } |       }|j                  |        ||      S y# t
        $ r t        j                  d       Y yw xY w# t
        t        f$ r Y yw xY w)z;Translate TFLite optimizations to litert_torch QuantConfig.Nr   )PT2EQuantizer)!get_symmetric_quantization_config)QuantConfigzPWarning: litert_torch quantization modules not available. Skipping quantization.OPTIMIZE_FOR_SIZEOPTIMIZE_FOR_LATENCYF)is_per_channel
is_dynamicis_qat)pt2e_quantizer)$litert_torch.quantize.pt2e_quantizerr   r   "litert_torch.quantize.quant_configr   rh   r   r   r=   r>   OptimizeDEFAULTgetattrAttributeError
set_global)ry   rg   r   r   r   optimize_defaultoptimize_sizeoptimize_latencyhas_defaulthas_sizehas_latencyr   r   quant_config_obj	quantizers                  r   r   r   M  s6   F	
 	C77++33 0 02EtL"GG4d
 #m3K?-!?H"H'7='HKh+ B(*Ak%B
$0<)!
 "O	-.)44G  %	
  ( s#   C A.D C?>C?DD)NN)r   r9   r   r   r4   r3   r   r   keras.src.export.export_utilsr   r   keras.src.utilsr   keras.src.utils.module_utilsr	   r=   r    r   r   rn   r   contextmanagerrf   ro   r   r   r!   r   <module>r      s       	    @ = $ 9 	5?pvJ vJt 48FR@ > >   .r!   