
     Ti                    `   S SK Jr  S SKJrJrJr  S SKrS SKrS SKJ	r	J
r
JrJrJr  S SKrS SKJr  SrSr1 SkrS	 rS S
 jrS rS rS rS!S jrS rS"S jrS#S jrS$S jrS%S jrS&S jr S'S jr!S(S jr"S)S jr#S*S jr$S+S jr% " S S5      r&    S,S jr' S-SSSSS.         S.S jjjr(g)/    )annotations)AnyOptionalSequenceN)FunctionProto
GraphProto
ModelProtoTensorProtoValueInfoProto)type_annotationz       >#   asifinisoranddefdelfornottryNoneTrueelifelsefrompasswithFalseasyncawaitbreakclassraisewhileyieldassertexceptglobalimportlambdareturnfinallycontinuenonlocalc                B   U R                   S:X  d   S5       eU R                  S   nUR                  S5      (       d  gUR                  nUR                  [
        R                  [
        R                  1;   a  [        UR                  5      nUS:X  a<  [        R                  R                  U5      R                  S5      n[        US   5      $ US:X  aK  UR                  S   S:  a8  [        R                  R                  U5      n[        UR!                  5       5      $ g)a(  Given an ONNX Constant-op node, returns a string representation of
the constant-value in ONNXScript, if a compact representation is possible.
Returns None otherwise.
Supports only FLOAT/INT64 values and scalars and small rank-1 tensors.
This needs to be reconciled with the ONNXScript converter.
ConstantzExpected a constant noder   tN      )op_type	attributeHasFieldr3   	data_typer
   FLOATINT64lendimsonnxnumpy_helperto_arrayreshapestrreprtolist)
const_nodeattrtensor_protorankarraynparrays         ]/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/onnxscript/backend/onnx_export.py_get_const_reprrL   9   s     +G-GG+"D==66L+"3"3[5F5F!GG<$$%19%%..|<DDQGEuQx= 19**1-1''00>G())    c                H   [        U [        5      (       a  U R                  n [        U [        5      (       d   eU S:w  d   eU [        ;   a  SU  3$ U S   nUR                  5       (       d  US:X  d  SU  3n S nSR                  U  Vs/ s H
  o2" U5      PM     sn5      $ s  snf )aO  Converts given name into a valid python variable names.
Handles names that clash with python keywords and common issues seen in ONNX models:
* Identifiers like "5" (that do not start with an alpha character)
* Identifiers that contain a dot like "layers.0.foo"
This is a simple heuristic, and doesn't guarantee it avoids name-clashes.
 r_r   ___c                @    U R                  5       (       d  U S:X  a  U $ S$ )z(Replace invalid character by underscore.rQ   )isalnum)chars    rK   rename_char+_cleanup_variable_name.<locals>.rename_charb   s    43;tAcArM   )
isinstancer   namerB   kwlistisalphajoin)rY   firstrV   cs       rK   _cleanup_variable_namer_   P   s     $''yydC    2::v~D6{GEMMOOD6{B 77D1DqKND1221s   Bc                    ^ 0 mU4S jn U $ )zSReturns a renamer used to create short new names  (like v0, v1, ...) for variables.c                j   > [        U 5      nUT;   a  TU   $ S[        T5      S-    3nUc   eUTU'   U$ )Nvr4   )r_   r<   )rY   var_namenew_namevariable_namess      rK   renamer(_make_short_name_mapper.<locals>.renamerm   sR    )$/~%!(++s>*Q./0####+x rM    )rf   re   s    @rK   _make_short_name_mapperri   i   s    %'N NrM   c                >    [         R                  R                  U SS9$ )z9Converts a onnx type into a type defined by *onnxscript*.F)
reversible)
onnxscript
onnx_typesonnx_type_to_onnxscript_repr)	onnx_types    rK   _translate_typerp   z   s      ==iTY=ZZrM   c           
     6   SS jnSSR                  U  Vs/ s H
  o2" U5      PM     sn5       S3nU(       aT  [        US   [        5      (       a<  USSR                  U Vs/ s H  n[        UR                  5      PM     sn5       S3-  nU S3$ s  snf s  snf )	z'Produce the script-functions signature.c                    [        U [        5      (       a-  [        U R                  5       S[	        U R
                  5       3$ [        U 5      $ Nz: )rX   r   r_   rY   rp   type)inps    rK   	input_sig'_translate_signature.<locals>.input_sig   sA    c>**,SXX67r/#((:S9TUU &c**rM   (, )r   z -> (:)ru   ValueInfoProto | str)r\   rX   r   rp   rt   )inputsoutputsrv   xresults        rK   _translate_signaturer      s    + &9&QIaL&9:;1=F:gaj.99E$))g$Ng_QVV%<g$NOPPQRRXQ< :$Ns   B
!Bc                v    SS jnU  Vs/ s H
  o!" U5      PM     nnSR                  U5      nSU-   S-   $ s  snf )Nc                l    [          S[        U R                  5       S[        U R                  5       S3$ )N'z': ,)_SINGLE_INDENTr_   rY   rp   rt   )
value_infos    rK   _translate_value_info5_translate_value_infos.<locals>._translate_value_info   s5     !#9*//#J"K3_i_n_nOoNppqrrrM   
z{
z
})r   r   r-   rB   )r\   )value_infosr   r   lineslines_joineds        rK   _translate_value_infosr      sG    s 0;;{!"1%{E;99U#L<%'' <s   6c                v    [        U [        5      (       a   U R                  S5      $ U $ ! [         a     U $ f = f)Nzutf-8)rX   bytesdecodeUnicodeDecodeError)ss    rK   _to_strr      sC    !U	88G$$ H " 	H	s   * 
88c                P    U R                  S5      =(       a    U R                  S:g  $ )Nref_attr_namerO   )r8   r   )rF   s    rK   _is_attribute_refr      s!    ==)Fd.@.@B.FFrM   c                   U R                   [        R                  R                  :X  a  U R                  $ U R                   [        R                  R
                  :X  a  U R                  $ U R                   [        R                  R                  :X  a  [        U R                  5      $ U R                   [        R                  R                  :X  aQ  U R                  n[        R                  R                  U5      (       a  U$ [        R                  R                  U5      $ U R                   [        R                  R                   :X  a  [#        U R$                  5      $ U R                   [        R                  R&                  :X  a  [#        U R(                  5      $ U R                   [        R                  R*                  :X  a#  [#        [-        [        U R.                  5      5      $ [1        SU < S35      e)Nz'Unable to return a value for attribute .)rt   r>   AttributeProtor:   fINTiSTRINGr   r   TENSORr3   external_data_helperuses_external_datar?   r@   FLOATSlistfloatsINTSintsSTRINGSmapstringsNotImplementedError)rF   rG   s     rK   _attribute_valuer      sS   yyD''---vvyyD''+++vvyyD''...tvvyyD''...vv$$77EE$$--l;;
 yyD''...DKK  yyD'',,,DIIyyD''///C.//  GxqQ
RRrM   c                   U R                  S UR                   5       5        U R                  S UR                   5       5        U R                  S UR                   5       5        UR                   H  n[        X5        M     g)z,Adds the names used in a graph to given set.c              3  8   #    U  H  oR                   v   M     g 7fNrY   .0r   s     rK   	<genexpr>._update_names_used_in_graph.<locals>.<genexpr>   s     -A   c              3  8   #    U  H  oR                   v   M     g 7fr   r   r   s     rK   r   r      s     .Ar   c              3  8   #    U  H  oR                   v   M     g 7fr   r   r   s     rK   r   r      s     3!2A!2r   N)updateinputoutputinitializernode_update_names_used_in_node)namesgraphr   s      rK   _update_names_used_in_graphr      s\    	LL---	LL...	LL3!2!233

"5/ rM   c                (   U R                  UR                  5        U R                  UR                  5        UR                   HL  nUR	                  S5      (       a  [        XR                  5        UR                   H  n[        X5        M     MN     g )Ng)r   r   r   r7   r8   r   r   graphs)r   r   rF   r   s       rK   r   r      sa    	LL	LL=='vv6A'1  rM   c                    U R                  UR                  5        U R                  UR                  5        UR                   H  n[	        X5        M     g r   )r   r   r   r   r   )r   funr   s      rK   _update_names_used_in_functionr      s8    	LL	LL"5/ rM   c                0    [        5       n[        X5        U$ r   )setr   )r   r   s     rK   _names_used_in_functionr      s    eE"5.LrM   c                d    U[        U R                  5      :  =(       a    U R                  U   S:g  $ )z6Returns True iff the node has an input at given index.rO   )r<   r   )r   indexs     rK   	has_inputr      s(    3tzz?">tzz%'8B'>>rM   c                L    U R                   U:H  =(       a    U R                  S;   $ )N   rO   ai.onnx)r6   domain)r   r6   s     rK   
is_onnx_opr      s    <<7"Et{{o'EErM   c                Z    [        5       nUR                   H  n[        X#5        M     X;   $ )z:Returns True iff the given name is used in the graph body.)r   r   r   )rY   r   r   r   s       rK   _is_used_in_graph_bodyr      s)     eE

"5/ =rM   c                   U R                   S   R                  nU R                  S   R                  nU R                   H  n[	        US5      (       aZ  [        UR                   5      S:X  aA  [        UR                  5      S:X  a(  UR                   S   U:X  a  UR                  S   U:X  a  Mn  [        5       n[        XC5        X;   d  X$;   d  M    g   g)z+Returns True iff loop requires a condition.r4   r   IdentityTF)r   rY   r   r   r   r<   r   r   )r   cond_incond_outr   r   s        rK   _cond_is_used_in_loop_bodyr      s    kk!n!!G||A##H

dJ''C

Oq,@SEUYZEZzz!}'DKKNh,F%"5/("3  rM   c                  .   \ rS rSrSr          SS jrS rS rS rSS jr	S r
SS	 jrSS
 jrS rSS jrS rSS jrSS jrSS jrS S jr    S!S jr    S"S jrS#S jrS#S jrS$S jr        S%S jr    S&S jr      S'S jrSrg)(	_Exporteri  z7Class used for recursive traversal of Proto structures.c                   X l         U(       a  [        5       nO[        nU R                  U5      U l        X0l        0 U l        0 U l        [        5       U l	        / U l
        X@l        0 U l        g r   )use_operatorsri   r_   _handle_attrname_conflict_rename_variableinline_const	constants_attr_renamingr   _names_used_name_remappingsskip_initializersskipped_initializers)selfrenamer   r   r   rename_functions         rK   __init___Exporter.__init__  sd     +57O4O $ > > O()+57%(U 79!2AC!rM   c                   ^ ^ UU 4S jnU$ )z?Add ref-attr-name-conflict handling logic to renaming function.c                  > T" U 5      nUTR                   ;  a  U$ TR                   U   nUb  U$ SnUnUTR                  ;   a  U SU 3nUS-  nUTR                  ;   a  M  UTR                   U'   TR                  R                  U5        U$ )Nr   rQ   r4   )r   r   add)rY   rd   	alternatecounter	candidaterf   r   s        rK   new_renamer8_Exporter._handle_attrname_conflict.<locals>.new_renamer!  s    t}Ht222++H5I$  G It///'j'3	1 t/// -6D)  +rM   rh   )r   rf   r   s   `` rK   r   #_Exporter._handle_attrname_conflict  s    	" rM   c                    [        U[        5      (       a  UR                  nUS:X  a  g[        U R                  5       H  nX;   d  M
  X!   s  $    U R                  U5      $ )z9Converts an ONNX variable name to a python variable name.rO   r   )rX   r   rY   reversedr   r   )r   varscopes      rK   _translate_onnx_var_Exporter._translate_onnx_var4  sW    c>**((C"9d334E|z! 5 $$S))rM   c                `    XR                   ;   a  U R                   U   $ U R                  U5      $ )z6Translates a reference to an ONNX variable (a r-value))r   r   )r   r   s     rK   _translate_onnx_var_ref!_Exporter._translate_onnx_var_ref?  s,    .. >>#&&'',,rM   c                &    US;   a  g[        U5      $ )Nr   opset)r_   )r   r   s     rK   _rename_domain_Exporter._rename_domainF  s    _$%f--rM   c                ,    U R                  U5       U 3$ r   )r   )r   r   versions      rK   _make_opset_name_Exporter._make_opset_nameK  s    %%f-.wi88rM   c           	         [        U5      nU(       aJ  Uc  Sn[        U[        5      (       d  [        SU< SU< SU< S35      eU R	                  X5      nU SU 3$ U$ )z]Generate name to be used for called op/function in a node or for a generated script function.r4   zversion must be an integer not z for domain=z
 and name=r   )r_   rX   int	TypeErrorr  )r   r   r  rY   r   r   s         rK   _make_callee_name_Exporter._make_callee_nameN  s|     &d+gs++5g[VJ W  $xq*  ))&:EWAdV$$rM   c                v   / n[        US5      (       a  UR                   H  nU R                  (       aw  SnUR                   H  nXg-  nM	     U[        :  aT  U R                  UR                  5      nXR                  ;   a  [        SUR                  < S35      eXPR                  U'   M  [        R                  R                  S/ U R                  UR                  5      /US9n	U R                  XUS9n
U
(       d  M  UR                  U
5        M     [        US5      (       a$  [        UR                  5      S	:  a  [!        S
5      eUR"                   HP  n	U R                  XUS9nU(       d  M  U	R                  (       a  USU	R                   3-  nUR                  U5        MR     SR%                  U5      nU$ )zxTranslates a graph body into python.
The graph may be the main graph (of a model) or a subgraph (of a Loop or If node).
r   r4   zInitializer z, is already present in skipped_initializers.r2   )valueindentsparse_initializerr   z0Unable to convert sparse_initilizer into python.  # r   )hasattrr   r   r=   _SMALL_TENSOR_SIZEr   rY   r   RuntimeErrorr>   helper	make_node_translate_nodeappendr<   r  r   r   r\   )r   r   opsetsr  codeinitsizedinit_py_namer   pyinitpynodefinals                rK   _translate_graph_body_Exporter._translate_graph_body^  s    5-(())))D!YY	 '00'+'?'?		'J'+D+DD".".tyym;g h#  CG11,? {{,,--dii89	 -  --d6-J6KK'+ *, 5.//C8P8P4QTU4U%&XYYJJD))$v)FFv99TYYK00FF#  		$rM   c           
        / nUR                    GH  n[        U5      (       a)  UR                  UR                  UR                  45        M=  [        U5      n[        U[        [        45      (       a(  UR                  UR                  [        U5      45        M  [        U[        R                  5      (       a  UR                  R                  n[        UR                  5      S:X  aA  SU S[        UR!                  5       5      R#                  SS5      R#                  SS5       S3nOeSU S	[%        UR                  5      < S
[        UR'                  5       R!                  5       5      R#                  SS5      R#                  SS5       S3nUR                  UR                  U45        GM  [        U[(        5      (       a  [*        R,                  R/                  U5      nUR                  =(       d    SnSnXh< SUR                   S[%        UR0                  5      < 3-  nUSUR2                  < 3-  nUR4                  (       a  USUR4                  < 3-  nUR6                  (       a  USUR6                  < 3-  nUS-  nUR                  UR                  U45        GM  UR                  UR                  [        U5      45        GM     SR9                  S U 5       5      $ )Nr   zmake_tensor("value", z, dims=[], vals=[nanznp.naninfznp.infz])z, dims=z, vals=rz   r
  zexternal_tensor(ry   z	, offset=z	, length=c              3  4   #    U  H  u  pU S U 3v   M     g7f)=Nrh   )r   krb   s      rK   r   2_Exporter._translate_attributes.<locals>.<genexpr>  s     ;
A3as
s   )r7   r   r  rY   r   r   rX   rB   r   rC   npndarrayr3   r9   r<   shaperD   replacer   ravelr
   r>   r   ExternalDataInfor=   locationoffsetlengthr\   )	r   r   
attributesatr
  
onnx_dtypetextmetadatarY   s	            rK   _translate_attributes_Exporter._translate_attributes  ss   
..B $$!!277B,<,<"=>$R(E%#u..!!277DK"89%,,TT^^
u{{#q(/
| <!!%elln!5!=!=eX!N!V!VW\^f!g hhjl  0
|74CTBW X  $U[[]%9%9%; < D DUH U ] ]^cem noopr  !!277D/2%--44EEeLzz,W)("U__$5RUZZ8H7KLL"X..122??i':;;D??i':;;D!!277D/2rwwU45G !J yy;
;;;rM   c                b   [         U-  nU R                  UR                  S   5      nU SU S3/n[        UR                  5      S:w  a0  [        SUR                  < S[        UR                  5       S35      eUR                  nUS   R                  S:X  a  US   R                  US	   R                  pOUS	   R                  US   R                  pUR                  U R                  U	UUS	-   S
95        UR                  U R                  UR                  U	R                  US	-   5      5        UR                  U S35        UR                  U R                  UUUS	-   S
95        UR                  U R                  UR                  UR                  US	-   5      5        SR                  U5      $ )z!Translates a node If into python.r   zif r{      zNode z expected two attributes not r   else_branchr4   r  zelse:r   )r   r   r   r<   r7   r  r6   rY   r   r  r  extend_emit_assignr   r\   )
r   r   r  r  sindentcondr  attsr:  then_branchs
             rK   _translate_if_Exporter._translate_if  s    6)++DJJqM:)3tfA&'t~~!#''DSEXDYYZ[  ~~7<<=('+Awyy$q'))'+Awyy$q'))&&z ' 	
 	D%%dkk;3E3EvPQzRSwiu%&&&z ' 	
 	D%%dkk;3E3EvPQzRSyyrM   c                   ^ ^^ U 4S jm[         U-  mSUU4S jjn[        U[        [        45      (       a	  U" X5      /$ [	        X5       VVs/ s H  u  pVU" XV5      PM     snn$ s  snnf )Nc                h   > [        U [        5      (       a  U R                  n TR                  U 5      $ r   )rX   r   rY   r   )r   r   s    rK   to_var&_Exporter._emit_assign.<locals>.to_var  s*    !^,,FF++A..rM   c                .   > T T" U 5       ST" U5       3$ )N = rh   )lhs_varrhs_varr=  rE  s     rK   assign&_Exporter._emit_assign.<locals>.assign  s"    Yvg/s6'?2CDDrM   )rI  rB   rJ  rB   )r   rX   rB   r   zip)	r   lhsrhsr  rK  r   yr=  rE  s	   `      @@rK   r<  _Exporter._emit_assign  sd    	/
 !6)	E 	E cC0113$%%),S7q777s   A&c           	        UR                   S   R                  n[        U-  n/ nUR                  S   R                  n[        US5      (       a!  SnU R                  UR                  S   5      n	O[        Xt5      nSn	U R                  U5      n
UR                  S   R                  nUR                  S   R                  nU R                  U5      nSn[        US5      (       a/  UR                  U R                  XR                  S   U5      5        O[        U5      n[        [        UR                  5      S-
  S5      nUR                  SS nUR                  SS nUR                  SUS-    nUR                  SU nUR                  U R                  UUU5      5        UR                  (       a  SUR                  -   nOSnU(       aE  U(       d>  UR                  U SU
 S	U	 S
U 35        U R                  U5      U R                  S   U'   OU(       d!  U(       a  UR                  U SU SU 35        OU(       a^  U(       aW  UR                  U SU
 S	U	 S
U 35        UR                  U [         SU S35        UR                  U [        S-   S35        O[!        SUR"                  < S35      eUR                  U R%                  UUUS-   S95        U(       a$  UR                  U R                  XUS-   5      5        UR                  U R                  UUUS-   5      5        UR                  U R                  UUU5      5        SR'                  U5      $ )z#Translates a node Loop into python.r   TNr4   r9  r  rO   zfor z
 in range():zwhile r{   zif not r#   zUnable to export loop type z0 into python because there is no stop condition.r  r   )r7   r   r   r   rY   r   r   r   r   r;  r<  r   maxr<   r  r   r  r6   r  r\   )r   r   r  r  bodyr=  rowsonnx_iter_varuse_iter_varn_iteriter_varr   r   py_conduse_loop_condnum_state_vars
actual_ins
formal_insformal_outsactual_outs	node_names                        rK   _translate_loop_Exporter._translate_loop  s   ~~a "" 6) 

1**T1L--djjm<F1-FLF++M:**Q-$$;;q>&&**73T1KK))'::a=&IJ6t<M S_q0!4ZZ^
ZZ^
kk!nq&89kk!N3D%%j*fEF99*IIKK7)4zF82i[QR 372J2J72SD!!"%h/-KK7)6'!I;?@mKK7)4zF82i[QRKK7)N#377)1EFKK7)NQ$6#7u=>-dll-= >. . 
 	&&z ' 	
 KK))'VaZHID%%j+vzJKD%%k:vFG yyrM   c                    [        5       e)z#Translates a node Scan into python.)r   )r   r   r  r  s       rK   _translate_scan_Exporter._translate_scan.  s    !##rM   c                   [        U[        5      (       a  US   nOUnU R                  (       aD  UR                  S:X  a4  [	        U5      nUb&  [        U5      U R                  UR                  S   '   gUR                  S;   az  UR                  S:X  a  U R                  XBUS9$ UR                  S:X  a  U R                  XBUS9$ UR                  S	:X  a  U R                  XBUS9$ [        S
UR                  < S35      e[        S UR                   5       5      (       a  [        S
UR                  < S35      eSSSSSSSSSSSSSS.n[        U-  nU R                  (       ar  UR                  U;   ab  U U R!                  UR                  S   5       SSXdR                      S3R#                  [%        U R&                  UR(                  5      5       3$ U R+                  UR,                  X$R,                     UR                  SS9nU R/                  U5      n	[1        UR(                  5      S:  a  [1        U	5      S:  a  SU	 3n	/ n
[3        UR                  5       HA  u  pUS ;   a  U
R5                  S!U 35        M!  U
R5                  U R!                  U5      5        MC     UR(                   Vs/ s H  oR'                  U5      PM     nnUR                  S":X  a?  [1        UR(                  5      S#:X  a&  [1        UR                  5      S#:X  a  U
S   US   :X  a  gUSR#                  U
5      SUS$SR#                  U5      U	S%/nSR#                  U5      $ s  snf )&N	onnx_noder2   r   rO   >   IfLoopScanrk  r  rl  rm  zUnable to export node type z into python.c              3     #    U  HH  n[        US 5      =(       a0    UR                  =(       a    UR                  R                  5       S:  v   MJ     g7f)r   r   N)r  r   ByteSize)r   atts     rK   r   ,_Exporter._translate_node.<locals>.<genexpr>E  s8     ^~wsC CSUUCsuu~~/?!/CC~s   AA+-*@/z**&|>z==<z>=z<=)AddSubMulMatMulDivPowAndOrGreaterEqualLesserGreaterOrEqualLessOrEqualrH   Tr   ry   )rO   NrQ   r   r4   rx   rz   )rX   dictr   r6   rL   rB   r   r   rA  rd  rg  r  anyr7   r   r   r   r\   r   r   r   r  r   r6  r<   	enumerater  )r   rj  r  r  r   valopsr=  callee_nameattributes_stroutput_namesr   or   input_namesr4  s                   rK   r  _Exporter._translate_node2  s-   i&&[)DD!;!$'C14St{{1~.<<11||t#))$v)FF||v%++D+HH||v%++D+HH!<T\\<LMZ[[^t~~^^^!<T\\<LMZ[["
 !6)$,,#"5)D44T[[^DESLL)*!,223t7S7SUYU_U_3`abd ,,KK,dll - 
 33D9tzz?Q3~#6#:!.!12N"$dkk*DAJ##asG,##D$<$<Q$?@	 + AE

K
133A6
K <<:%#djj/Q*>3t{{CSWXCXA+a.0IIl#IIk"	
 wwt}# Ls   .Mc                R    US;   a  SU S3$ U R                  X5      nU SU SU S3$ )Nr   z'from onnxscript.onnx_opset import opsetr   z
 = Opset('z', )
)r  )r   r   r  varnames       rK   _translate_opset_import!_Exporter._translate_opset_import|  sB    _$<WIRHH++F<GYjG9C@@rM   c           	         SR                  U Vs/ s H(  o R                  UR                  UR                  5      PM*     sn5      $ s  snf )NrO   )r\   r  r   r  )r   opset_importsr   s      rK   _translate_opset_imports"_Exporter._translate_opset_imports  s=     wwHUV1))!((AII>V
 	
Vs   /Ac                  ^ [        TS5      (       at  U R                  TR                  5      n[        T[        5      (       aB  [        U4S jTR                   5       5      (       d  X R                  TR                  S5      -  nU$ g)Nopset_importc              3  T   >#    U  H  oR                   TR                   :H  v   M     g 7fr   )r   )r   r   protos     rK   r   8_Exporter._translate_opset_imports_of.<locals>.<genexpr>  s     P=O88u||3=Os   %(r4   rO   )r  r  r  rX   r   r  r  r   )r   r  r4  s    ` rK   _translate_opset_imports_of%_Exporter._translate_opset_imports_of  sm     5.))001C1CDD%//PU=O=OPPP88qIIDKrM   c                L  ^ ^ [        U5      mSU U4S jjnUR                   Vs/ s H  nT R                  U5      PM     nnUR                   Vs/ s H
  o2" U5      PM     nnSR	                  XE-   5      n[        UR                  5      S:  a  SnOSnSU SU 3$ s  snf s  snf )	z%Generate signature for FunctionProto.c                   > S TR                   U '   TR                  R                  U 5        TR                  U [        R
                  R                  5      n[        R                  " U5      nU  SU 3$ rs   )	r   r   r   getr>   r   r   r   !onnx_attr_type_to_onnxscript_repr)	attr_namert   typerepr   type_maps      rK   attr_sig9_Exporter._translate_function_signature.<locals>.attr_sig  sd    -1D	*  +<<	4+>+>+B+BCD%GGMG[7),,rM   ry   r   z:
   # Attribute parameters default-values not handled yet.rO   rx   rS  )r  rB   r-   rB   )_attribute_param_typesr   r   r7   r\   r<   attribute_proto)	r   funprotor  r   r}   attrsinput_and_attrsmessager  s	   `       @rK   _translate_function_signature'_Exporter._translate_function_signature  s    )(3	- 	- 8@~~F~!$**1-~F&.&8&89&8!&89))FN3x''(1,SGG?#2gY// G9s   BB!c           	     j  ^ ^ 0 nUR                    H  nUR                  X#R                  '   M     0 T l        [	        U5      nU Vs/ s H  nT R                  U5      PM     nn[        U5      T l        / mSU4S jjnT R                  UR                  S5      nU" SU S35        T R                  UR                  SUR                  5      n	T R                  U5      n
U" SU	 U
 35        UR                  (       a  U" SUR                   S35        T R                  R                  0 5        UR                   H  nU" T R!                  XSS95        M     S	R#                  U 4S
 jUR$                   5       5      nU" SU 35        T R                  R'                  5         SR#                  T5      $ s  snf )z'Generate python code for FunctionProto.c                (   > TR                  U 5        g r   r  liner   s    rK   add_line/_Exporter._translate_function.<locals>.add_line      MM$rM   r4   z@script(rz   def z    """"""r  ry   c              3  F   >#    U  H  nTR                  U5      v   M     g 7fr   r   r   r   r   s     rK   r   0_Exporter._translate_function.<locals>.<genexpr>  s     !W!$":":1"="=   !z    return r   r  rB   r-   r   )r  r  r   r   r   r   r   r   r  r  rY   r  
doc_stringr   r  r   r  r\   r   pop)r   r  r  importedused_proto_namesr   renamed_names_usedr  
opset_namefun_namefun_sigr   return_valuesr   s   `            @rK   _translate_function_Exporter._translate_function  s    --H&.&6&6F??# . 28<CSTCSad66q9CST12	  **8??A>
8J<q)*))(//1hmmL44X>4z'+,wx223378$$R(MMDT))$q)AB "		!Wx!WW;}o./!!#yy  ) Us   F0c           	       ^ ^ UR                   n0 nUR                   H  nUR                  XER                  '   M     Uc  [	        UR
                  5      n/ mSU4S jjnT R                  (       a	  Sn[        nOSnSnU" U S35        U" U SU [        UR                  UR                  5       35        U[        -   nUR                  n	U	(       a  U" U SU	 S35        U" T R                  X4US95        S	R                  U 4S
 jUR                   5       5      n
U" U SU
 35        SR                  T5      nT R                  (       a'  [        UR                   5      nT R#                  XU5      $ U$ )Nc                (   > TR                  U 5        g r   r  r  s    rK   r   '_Exporter._translate_graph.<locals>.add  r  rM   r9  r4   rO   z	@script()r  r  r  ry   c              3  F   >#    U  H  nTR                  U5      v   M     g 7fr   r  r  s     rK   r   -_Exporter._translate_graph.<locals>.<genexpr>  s     !T|!$":":1"="=|r  zreturn r   r  )r   r  r  r   r_   rY   r   r   r   r   r   r  r  r\   r   r   r   _substitute_initializers)r   modelfunction_namer   r  r  r   indent_levelr  docr  scriptr   r   s   `            @rK   _translate_graph_Exporter._translate_graph  sV   **H&.&6&6F??# + 25::>M	  !!L#FLFvhi !vhd=/*>u{{ELL*Y)Z[\.(6(#cU#&'D&&u\&JK		!Tu||!TTvhgm_-.6"$$01A1ABK00TTrM   c                p  ^^	 U R                   R                  5       n[        mSR                  U4S jU 5       5      nSU4S jjm	SR                  U	4S jU R                   R	                  5        5       5      nSR                  U4S jU 5       5      nSU SU SU S	T S
U ST SU ST SU ST ST S3$ )Nr   c              3  2   >#    U  H  nT U S 3v   M     g7fr   Nrh   r   r   rR   s     rK   r   5_Exporter._substitute_initializers.<locals>.<genexpr>  s     *K
1bT!A;
s   c                  > SR                  S UR                   5       5      nUR                  [        R                  :X  a
  T U  SU S3$ UR                  [        R
                  :X  a
  T U  SU S3$ [        SUR                   S35      e)	Nr   c              3  8   #    U  H  n[        U5      v   M     g 7fr   )rB   )r   r  s     rK   r   L_Exporter._substitute_initializers.<locals>.generate_rand.<locals>.<genexpr>  s     8ZSVVZr   z = np.random.rand(z).astype(np.float32)z& = np.random.randint(-128, 127, size=(z,), dtype=np.int8)z4Unable to generate random initializer for data type r   )r\   r=   r9   r
   r:   INT8r   )rY   r
  r*  rR   s      rK   generate_rand9_Exporter._substitute_initializers.<locals>.generate_rand  s    HH8UZZ88E+"3"33dV#5eW<PQQ+"2"22dV#I%Pbcc%FuFWWXY rM   c              3  8   >#    U  H  u  pT" X5      v   M     g 7fr   rh   )r   keyr
  r  s      rK   r   r    s      .
8Y*#M#%%8Ys   c              3  6   >#    U  H  nT T U S 3v   M     g7fr  rh   r  s     rK   r   r    s     3XZrd2$qcOZs   z
value_infos = z

def make_model(
z
):
z

zmodel = z).to_model_proto(value_infos=value_infos)
z4return model

def make_model_with_random_weights():
zmodel = make_model(
r  zreturn model
)rY   rB   r
  r
   r-   rB   )r   keysr   r\   items)
r   r  script_function_namer   
init_namesinitializers_as_paramsrandom_initializer_valuesindented_initializers_as_paramsrR   r  s
           @@rK   r  "_Exporter._substitute_initializers  s     ..335
!%*K
*K!K	 %)II .
8<8Q8Q8W8W8Y.
 %
! +/))3XZ3X*X'm     	H!" #       ! "  ! 	rM   c                   [        U[        5      (       a  UR                  nOUn[        5       n[	        UR
                  5      [	        UR                  5      -    HO  n[        US5      (       d  M  [        UR                  5      nUR                  SSS9S   nUR                  U5        MQ     [        U5      nU(       a  SSR                  U5      -   $ g)	z7Generate import statements for types used in the graph.rt   [r4   )maxsplitr   z"from onnxscript.onnx_types import ry   rO   )rX   r	   r   r   r   r   r   r  rp   rt   splitr   sortedr\   )r   r  graph_or_function
used_typesr3   tsitssorted_typess           rK   _import_onnx_types_Exporter._import_onnx_types  s     eZ(( % %"u
'--.6G6N6N1OOAq&!!$QVV,hhsQh/2s#	 P j)7$))L:QQQrM   c                `  ^ / mSU4S jjnU" S5        U" S5        U" S5        U" S5        U" S5        U" U R                  U5      5        [        U[        5      (       aK  UR                   Vs/ s H  o@R	                  U5      PM     nnUR                  U R                  X5      5        O)[        U[        5      (       d   eU R	                  U5      /nU" U R                  U5      5        TR                  U5        U" S5        SR                  T5      nS	U;   a  [        S
U 35      eU$ s  snf )Nc                (   > TR                  U 5        g r   r  r  s    rK   r   _Exporter.export.<locals>.add,  r  rM   zimport numpy as npzfrom onnx import TensorProtoz#from onnx.helper import make_tensorz.from onnxscript import script, external_tensorz#from onnxscript.values import OpsetrO   r   z
returnzThe produced code is wrong.
r  )r  rX   r	   	functionsr  r  r  r   r  r;  r\   SyntaxError)r   r  r  r   r   translated_functionsr  r   s          @rK   export_Exporter.export'  s    	  	 !*+12<=12D##E*+eZ((IN#YA$<$<Q$? #Y ''(=(=e(STe]3333$($<$<U$C#D  	D,,U34*+B		&! =eWEFF! $Zs   .D+)	r   r   r   r   r   r   r   r   r   N)
r   boolr   r  r   r  r   r  r-   r   )r   rB   r-   rB   )F)r   )r   rB   r  r  r-   rB   )r  z!Sequence[onnx.OperatorSetIdProto]r-   rB   )r  z'ModelProto | FunctionProto | GraphProtor-   rB   )r  onnx.FunctionProtor-   rB   )r  zonnx.ModelProtor  Optional[str]r-   rB   )r  rB   r  rB   r   rB   r-   rB   )r  z6onnx.ModelProto | onnx.GraphProto | onnx.FunctionProtor-   rB   )r  z$onnx.ModelProto | onnx.FunctionProtor  r
  r-   rB   )__name__
__module____qualname____firstlineno____doc__r   r   r   r   r   r  r  r  r6  rA  r<  rd  rg  r  r  r  r  r  r  r  r  r  r  __static_attributes__rh   rM   rK   r   r     s   ADD.2DBFD[_D	D&,	*-.
9 &P'<R!F8KZ$HTA
>
	
	<			0*!: D((14(CF(	(TK	(!9!JW!	!rM   r   c                h   ^^^ 0 mSUU4S jjmSU4S jjmU R                    H  nT" U5        M     T$ )zPCompute mapping from (names of) attribute parameters of function to their types.c                  > U R                    H  n[        U5      (       a  UR                  TUR                  '   M.  UR                  [        R
                  R                  :X  a  T" UR                  5        Mj  UR                  [        R
                  R                  :X  d  M  UR                   H  nT" U5        M     M     g r   )
r7   r   rt   r   r>   r   GRAPHr   GRAPHSr   )r   rF   r   r  visit_graphs      rK   
visit_node*_attribute_param_types.<locals>.visit_nodeQ  s    NND &&/3yy++,d11777DFF#d11888![[E& ) #rM   c                <   > U R                    H  nT" U5        M     g r   r  )r   r   r  s     rK   r  +_attribute_param_types.<locals>.visit_graph[  s    JJDt rM   )r   onnx.NodeProtor-   r   )r   zonnx.GraphProtor-   r   r  )r  r   r  r  r  s     @@@rK   r  r  K  s6     H' ' 4 OrM   Fr   r   r   r   c                   [        U [        5      (       a  [        R                  " U 5      n [        U [        [
        45      (       d  [        S[        U 5      < S35      e[        UUUUS9nUR                  X5      $ )a  Exports an ONNX model to the *python* syntax.

Args:
    model_onnx: string or ONNX graph
    rename: rename the names to get shorter names
    function_name: main function name
    use_operators: use Python operators.
    inline_const: replace ONNX constants inline if compact
    skip_initializers: generated script will not include initializers.
      Instead, a function that generates the model, given initializer values, is generated,
      along with one that generates random values for the initializers.

Returns:
    python code
The following example shows what a python code creating a graph
implementing the KMeans would look like.
.. runpython::
    :showcode:
    :process:
    import numpy as np
    from sklearn.cluster import KMeans
    from mlprodict.onnx_conv import to_onnx
    from mlprodict.onnx_tools.onnx_export import export2python
    X = np.arange(20).reshape(10, 2).astype(np.float32)
    tr = KMeans(n_clusters=2)
    tr.fit(X)
    onx = to_onnx(tr, X, target_opset=14)
    code = export2python(onx)
    print(code)
z&The function expects a ModelProto not r   r  )
rX   rB   r>   loadr	   r   r  rt   r   r  )
model_onnxr  r   r   r   r   exporters          rK   export2pythonr   d  su    N *c""YYz*
j:}"=>>@jAQ@TTUVWW#!+	H ??:55rM   )rY   r|   r-   rB   )r   zSequence[ValueInfoProto]r-   rB   )rF   onnx.AttributeProtor-   r  )rF   r!  )r   set[str]r   r   r-   r   )r   r"  r   r  r-   r   )r   r"  r   r   r-   r   )r   r   r-   r"  )r   r  r   r  r-   r  )r   r  r6   rB   r-   r  )rY   rB   r   r   r-   r  )r   r   r-   r  )r  r	  r-   z,dict[str, onnx.AttributeProto.AttributeType]r   )
r  r
  r   r  r   r  r   r  r   r  ))
__future__r   typingr   r   r   numpyr(  r>   r   r   r	   r
   r   onnxscript.onnx_typesrl   onnxscript._internalr   r   r  rZ   rL   r_   ri   rp   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   rh   rM   rK   <module>r(     s    # * *   S S  0 $
N.32"[
"(GS>020?
F"@	 @	F 16 $(36 #36 36 	36
 36 36 36rM   