
    ij2                         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Zd Zd Zy)    N)backend)treeconvert_spec_to_tensor)get_input_signature)make_tf_tensor_spec)DEFAULT_ENDPOINT_NAME)ExportArchive)patch_tf2onnx)io_utilsc           	      	   |}|d}|$t        |       }|r| j                  st        d      t        |      dk(  rt	        |d   t
              r|d   }n|}t        |      D 	cg c]  \  }}	t        |	dd      xs d|  }
}}	t        j                         dk(  rXdd	l	m
} t        j                  t        |      }t        | |fi |}t                |j                   j#                  ||||
       nt        j                         dk(  rt%        | |||       net        j                         dk(  rBddl}t        j(                  |      }t        |      D 	cg c]  \  }}	t        |	dd      xs d|  }
}}	i }t        |      D ]V  \  }}	t+        |	d      s|	j,                  }i }t        |      D ]  \  }}|	|dk(  rd}nd| d| }|||<    |sO|||
|   <   X t        j                  d |      }t/        d |D              }|rG G d d|j0                  j2                        } || |      }t5        t        j(                  |            }n| }t5        |      }t+        |d      r|j7                          t9        j:                         5  t9        j<                  dd       t9        j<                  dd       t9        j<                  dd       t9        j<                  dd       t9        j<                  dd       t9        j<                  dd|j>                  j@                         t9        j<                  dd|j>                  j@                         t9        j<                  dd |j>                  j@                         t9        j<                  dd!|j>                  j@                         t9        j<                  dd"|j>                  j@                         ddd       |sT	 |||
dd#} |jB                  jD                  ||fi |}t+        |d$      r|jG                          |jI                  |       y	 |}|d%}|||
ddd%d&}|r||d'<    |jB                  jD                  |||fi | ntM        d(      |rtO        jP                  d)| d*       yyc c}	}w c c}	}w # 1 sw Y   xY w# tJ        $ r Y w xY w)+a  Export the model as a ONNX artifact for inference.

    This method lets you export a model to a lightweight ONNX artifact
    that contains the model's forward pass only (its `call()` method)
    and can be served via e.g. ONNX Runtime.

    The original code of the model (including any custom layers you may
    have used) is *no longer* necessary to reload the artifact -- it is
    entirely standalone.

    Args:
        filepath: `str` or `pathlib.Path` object. The path to save the artifact.
        verbose: `bool`. Whether to print a message during export. Defaults to
            `None`, which uses the default value set by different backends and
            formats.
        input_signature: Optional. Specifies the shape and dtype of the model
            inputs. Can be a structure of `keras.InputSpec`, `tf.TensorSpec`,
            `backend.KerasTensor`, or backend tensor. If not provided, it will
            be automatically computed. Defaults to `None`.
        opset_version: Optional. An integer value that specifies the ONNX opset
            version. If not provided, the default version for the backend will
            be used. Defaults to `None`.
        **kwargs: Additional keyword arguments.

    **Note:** This feature is currently supported only with TensorFlow, JAX and
    Torch backends.

    **Note:** The dtype policy must be "float32" for the model. You can further
    optimize the ONNX artifact using the ONNX toolkit. Learn more here:
    [https://onnxruntime.ai/docs/performance/](https://onnxruntime.ai/docs/performance/).

    **Note:** The dynamic shape feature is not yet supported with Torch
    backend. As a result, you must fully define the shapes of the inputs using
    `input_signature`. If `input_signature` is not provided, all instances of
    `None` (such as the batch size) will be replaced with `1`.

    Example:

    ```python
    # Export the model as a ONNX artifact
    model.export("path/to/location", format="onnx")

    # Load the artifact in a different process/environment
    ort_session = onnxruntime.InferenceSession("path/to/location")
    ort_inputs = {
        k.name: v for k, v in zip(ort_session.get_inputs(), input_data)
    }
    predictions = ort_session.run(None, ort_inputs)
    ```
    NTz%The model provided has never called.    r   nameinput_
tensorflow)tf2onnx)opsetoutput_pathjaxtorchshapebatchdim__c                     t        | d      S )Nr   )replace_none_numberr   )xs    j/var/www/html/emotional.easysim.app/public_html/venv/lib/python3.12/site-packages/keras/src/export/onnx.py<lambda>zexport_onnx.<locals>.<lambda>   s    ,QAF     c              3   F   K   | ]  }t        j                  |        y wN)r   	is_nested).0r   s     r   	<genexpr>zexport_onnx.<locals>.<genexpr>   s     E!DNN1-Es   !c                   $     e Zd Z fdZd Z xZS )&export_onnx.<locals>._FlatInputWrapperc                 >    t         |           || _        || _        y r"   )super__init___wrapped
_structure)selfwrapped	structure	__class__s      r   r*   z/export_onnx.<locals>._FlatInputWrapper.__init__   s    G$&$+DM&/DOr    c                     t        j                  | j                  |      }t        |      dk(  r| j	                  |d         S  | j                  | S )Nr   r   )r   pack_sequence_asr,   lenr+   )r-   	flat_argsinputss      r   forwardz.export_onnx.<locals>._FlatInputWrapper.forward   sH    !224??INF6{a'#}}VAY77(4==&11r    )__name__
__module____qualname__r*   r6   __classcell__)r0   s   @r   _FlatInputWrapperr'      s    0
2r    r;   evalignorez4.*\n.*\n*.*\n*.*export will treat it as a constant.*)messagez+.*not properly registered as a submodule,.*z3.*which is what 'get_attr' Nodes typically target.*z2.*underlying reference in the owning GraphModule.*z(.*suppressed about get_attr references.*z+.*Converting a tensor to a Python boolean.*)r>   categoryz+.*Converting a tensor to a Python integer.*z.*Iterating over a tensor.*z!.*Using len to get tensor shape.*z4.*torch.tensor results are registered as constants.*)verboseopset_versioninput_namesdynamooptimizeF)r@   rA   rB   export_paramsdo_constant_foldingrC   dynamic_axeszI`export_onnx` is only compatible with TensorFlow, JAX and Torch backends.zSaved artifact at 'z'.))r   _called
ValueErrorr3   
isinstancelist	enumerategetattrr   keras.src.utils.module_utilsr   r   map_structurer   get_concrete_fnr   convertfrom_function_export_onnx_jaxr   flattenhasattrr   anynnModuletupler<   warningscatch_warningsfilterwarningsjitTracerWarningonnxexportrD   save	ExceptionNotImplementedErrorr   	print_msg)modelfilepathr@   input_signaturerA   kwargsactual_verbosespecs_for_namesispecrB   r   decorated_fnr   
flat_specsrG   	input_idxr   dynamic_dimsdim_idxdim_sizedim_namesample_inputsneeds_wrapperr;   export_modelexport_kwargsonnx_programtorchscript_verboses                                r   export_onnxrz      s   t N-e4emmDEE ?q Z0BD%I)!, * !1At 	fd#3s|3K 
 L(8,,
 'uoHH 	%% 	 	& 	
 
	e	#/=I		g	% \\/2
 %Z0
4 D&$'7VA3<7
 

 (4 	DOIt4)JJEL%.u%5 5!#!|#*%))AgY#?,4L)5 7C[34!	D$ **F

 E}EE
2EHHOO 
2 -UODL!$,,}"=>M L!-0M<($$& .	##O ##F ##N ##M ##"M ##F00
 ##F00
 ##600
 ##<00
 ##O00U.	f   .%2#."	!  1uzz00 - 3@  <4 ))+!!(+ 	<%? #( +*&!#'
 ,8M.)

-	
5B	
 "
 	

 0
"=> {D
h.	 .	L  s,   $RR#ER)+AR5 )R25	S Sc           	      l    ddl }ddl}ddlm} t	        j
                        }t        |      D 	cg c]  \  }}	t        |	dd      xs d|  }
}}	g }t        |      D ]  \  }}	g }t        |	j                        D ]7  \  }}||j                  |dk(  rdnd| d|        '|j                  |       9 |j                  |j                  t        |      |j                  |	j                                       fd	}|
d
t        |      d}|||d<    |j                  |fd|i| yc c}	}w )zExport a JAX-backend Keras model to ONNX using jax2onnx.

    Converts the model directly from JAX to ONNX without going through
    TensorFlow, avoiding the deprecated jax2tf options (``enable_xla``
    and ``native_serialization``).
    r   N)jax2onnxr   r   r   r   r   c                  v    t        j                  |       }t        |      dk(  r |d   d      S  |ddiS )Nr   r   F)trainingr~   )r   r2   r3   )r4   argsrg   re   s     r   
predict_fnz$_export_onnx_jax.<locals>.predict_fn?  sA    $$_i@t9>a511d+U++r    file)rB   return_moder   r   r5   )r   numpyrN   r|   r   rT   rL   rM   r   appendShapeDtypeStructrY   dtypestrto_onnx)re   rf   rg   rA   r   npr|   rn   rk   rl   flat_input_names
jax_inputsr   rq   dimr   rw   s   ` `              r   rS   rS     sN    5 o.J
 !,At 	fd#3s|3  JZ( 	
4%djj1 	"LGS{1WD1WI:NOS!		"
 	  urxx

/CD	
	
, (8}M
  !.gHZD
DmDGs   D0c                     t               } |j                  t        | |fi | t        j                         dk(  r|j	                          |j                  t              S )z0Get the `tf.function` associated with the model.r   )r
   track_and_add_endpointr	   r   _filter_and_track_resources_get_concrete_fn)re   rg   rh   export_archives       r   rP   rP   P  sW    "_N)N))uo9? L(224**+@AAr    )NNN)rZ   	keras.srcr   r   keras.src.export.export_utilsr   r   r   keras.src.export.saved_modelr	   r
   keras.src.export.tf2onnx_libr   keras.src.utilsr   rz   rS   rP    r    r   <module>r      sB       @ = = > 6 6 $ I?X3ElBr    