
    Si/1                        S SK Jr  S SKrS SKrS SKJr  S SKJr  S SKr	S SK
r	S SKr	\(       a  S SKJrJrJrJrJr   " S S5      r  S             SS jjr      SS	 jr      SS
 jrg)    )annotationsN)deque)TYPE_CHECKING)FunctionProto
ModelProto	NodeProtoTensorProtoValueInfoProtoc                      \ rS rSrSS jr\SS j5       r\SS j5       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)	Extractor   c                &   Xl         U R                   R                  U l        U R                  U R                  R                  5      U l        U R                  U R                  R
                  5      U l        U R                  R                  U R                  U R                  R                  5      5        U R                  R                  U R                  U R                  R                  5      5        U R                  U R                  5      U l        g N)modelgraph_build_name2obj_dictinitializerinitializers
value_infovalue_infosupdateinputoutput_build_output_dictoutmap)selfr   s     I/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/onnx/utils.py__init__Extractor.__init__   s    
ZZ%%
484M4MJJ""5
 7;6O6OJJ!!7
 	 9 9$**:J:J KL 9 9$**:K:K LM&*&=&=djj&I    c                F    U  Vs0 s H  oR                   U_M     sn$ s  snf r   )name)objsobjs     r   r   Extractor._build_name2obj_dict(   s     )-.##...s   c                    0 n[        U R                  5       H+  u  p#UR                   H  nUS:X  a  M  XA;  d   eX!U'   M     M-     U$ )N )	enumeratenoder   )r   output_to_indexindexr)   output_names        r   r   Extractor._build_output_dict,   sQ    *,$UZZ0KE#{{"$"999/4,	  + 1 r    c                    U Vs/ s H  o"U R                   ;  d  M  UPM     nnU(       a  [        SSR                  U5       35      eU Vs/ s H  o R                   U   PM     sn$ s  snf s  snf )Nz3The following names were not found in value_infos: z, )r   
ValueErrorjoin)r   io_names_to_extractr"   missing_namess       r   _collect_new_ioExtractor._collect_new_io7   s     1
0T@P@P4PD0 	 
 EdiiP]F^E_`  4GG3F4  &3FGG
 Hs   A'A'A,c                J   U/nU(       a  UR                  5       nXR;   a  M  XPR                  ;   ad  U R                  U   nXc;  aP  UR                  U5        UU R                  R                  U   R
                   Vs/ s H  nUS:w  d  M  UPM     sn-  nU(       a  M  ggs  snf )a  Helper function to find nodes which are connected to an output

Arguments:
    node_output_name (str): The name of the output
    graph_input_names (set of string): The names of all inputs of the graph
    reachable (set of int): The set of indexes to reachable nodes in `nodes`
r'   N)popr   addr   r)   r   )r   node_output_namegraph_input_names	reachablestackcurrent_output_namer+   
input_names           r   _dfs_search_reachable_nodes%Extractor._dfs_search_reachable_nodesB   s     """'))+"7"kk1$78)MM%(*.**//%*@*F*F*FJ%+ #*F E es   <
B 
B c                    [        U5      n[        5       nU H  nU R                  XSU5        M     [        U5       Vs/ s H  o`R                  R                  U   PM     sn$ s  snf r   )setr>   sortedr   r)   )r   input_namesoutput_names_input_namesr:   r"   r+   s          r   _collect_reachable_nodes"Extractor._collect_reachable_nodesa   s[    
 ;'!e	 D,,TK ! 5;94EF4E5

&4EFFFs   "A#c                   0 nU R                   R                   H  nX2UR                  UR                  4'   M     / n[	        U5      nU(       a  UR                  5       nUR                  UR                  4U;   aS  UR                  UR                  UR                  45      nUR                  U5        UR                  UR                  5        U(       a  M  U$ r   )r   	functionsr"   domainr   popleftop_typer6   appendextendr)   )r   nodesfunction_mapfunctionreferred_local_functionsqueuer)   s          r   !_collect_referred_local_functions+Extractor._collect_referred_local_functionsm   s     >@

,,H=E(--9: -8: e==?Ddkk*l:'++T\\4;;,GH(//9X]]+ e ('r    c                >   [        5       nU H9  nUR                  UR                  5        UR                  UR                  5        M;     U R                   Vs/ s H  oDU;   d  M
  U R                  U   PM     nnU R
                   Vs/ s H  oDU;   d  M
  U R
                  U   PM     nn[        U R                  R                  5      nUS:w  a  [        SU S35      e[        U R                  R                  5      nUS:w  a  [        SU S35      eXV4$ s  snf s  snf )Nr   zlen_sparse_initializer is z, it must be 0.zlen_quantization_annotation is )rA   r   r   r   r   r   lenr   sparse_initializerr/   quantization_annotation)	r   rO   all_tensors_namesr)   tr   r   len_sparse_initializerlen_quantization_annotations	            r   _collect_reachable_tensors$Extractor._collect_reachable_tensors   s5    '*eD$$TZZ0$$T[[1  +/*;*;
*;QDU?U Da *; 	 
 *.)9)9
)9ABS=SDQ)9 	 
 "%TZZ%B%B!C!Q&,-C,DOT  '*$***L*L&M#&!+12M1No^  &&!

s   	D%D	DDc           	        SU R                   R                  -   S-   n[        R                  R	                  XX#XES9nU R
                  R                  U R
                  R                  SUS.n	[        R                  R                  " U40 U	D6$ )NzExtracted from {})r   r   zonnx.utils.extract_model)
ir_versionopset_importsproducer_namerI   )	r   r"   onnxhelper
make_graphr   rb   opset_import
make_model)
r   rO   inputsoutputsr   r   local_functionsr"   r   metas
             r   _make_modelExtractor._make_model   s     "DJJOO3c9&&k ' 
 **//!ZZ447(	
 {{%%e4t44r    c                    U R                  U5      nU R                  U5      nU R                  X5      nU R                  U5      u  pgU R                  U5      nU R	                  XSXFXx5      $ r   )r3   rF   r^   rT   rn   )	r   rC   rD   rj   rk   rO   r   r   rl   s	            r   extract_modelExtractor.extract_model   sq    
 %%k2&&|4--kH"&"A"A%"H@@G7
 	
r    )r   r   r   r   r   N)r   r   returnNone)rs   dict)rs   zdict[str, int])r1   	list[str]rs   list[ValueInfoProto])r8   strr9   zset[str]r:   zset[int]rs   rt   )rC   rv   rD   rv   rs   list[NodeProto])rO   ry   rs   list[FunctionProto])rO   ry   rs   z.tuple[list[TensorProto], list[ValueInfoProto]])rO   ry   rj   rw   rk   rw   r   zlist[TensorProto]r   rw   rl   rz   rs   r   )rC   rv   rD   rv   rs   r   )__name__
__module____qualname____firstlineno__r   staticmethodr   r   r3   r>   rF   rT   r^   rn   rq   __static_attributes__ r    r   r   r      s   J / /  	H $ 	
 
>
G
G  
G 
	
G(( 
(.'' 
8'455 %5 &	5
 '5 )5 -5 
5*

  
 
	
r    r   c                J   [         R                  R                  U 5      (       d  [        SU  35      eU(       d  [        S5      eU(       d  [        S5      eU(       d  [        S5      e[	        U5      [	        [        U5      5      :w  a  [        S5      e[	        U5      [	        [        U5      5      :w  a  [        S5      eU(       a  [        R                  R                  U 5        U(       aq  [         R                  R                  U 5      [        R                  R                  :  a6  [        R                  R                  X5        [        R                  " U5      nOU(       aj  [        R                  " U SS9n[        R                  R                  U5      n[         R                  R                  U 5      n[        R                   " Xg5        O[        R                  " U 5      n[#        U5      nUR%                  X#5      n	U	R'                  5       [        R                  R                  :  a9  [         R                  R)                  U5      S	-   n
[        R*                  " XS
U
S9  O[        R*                  " X5        U(       a   [        R                  R                  U5        gg)a  Extracts sub-model from an ONNX model.

The sub-model is defined by the names of the input and output tensors *exactly*.

Note: For control-flow operators, e.g. If and Loop, the _boundary of sub-model_,
which is defined by the input and output tensors, should not _cut through_ the
subgraph that is connected to the _main graph_ as attributes of these operators.

Note: When the extracted model size is larger than 2GB, the extra data will be saved in "output_path.data".

Arguments:
    input_path (str | os.PathLike): The path to original ONNX model.
    output_path (str | os.PathLike): The path to save the extracted ONNX model.
    input_names (list of string): The names of the input tensors that to be extracted.
    output_names (list of string): The names of the output tensors that to be extracted.
    check_model (bool): Whether to run model checker on the original model and the extracted model.
    infer_shapes (bool): Whether to infer the shapes of the original model.
zInvalid input model path: z%Output model path shall not be empty!z&Input tensor names shall not be empty!z'Output tensor names shall not be empty!z0Duplicate names found in the input tensor names.z1Duplicate names found in the output tensor names.F)load_external_dataz.dataT)save_as_external_datalocationN)ospathexistsr/   rW   rA   re   checkercheck_modelgetsizeMAXIMUM_PROTOBUFshape_inferenceinfer_shapes_pathloadinfer_shapesdirnameload_external_data_for_modelr   rq   ByteSizebasenamesave)
input_pathoutput_pathrC   rD   r   r   r   base_dire	extractedr   s              r   rq   rq      s   4 77>>*%%5j\BCC@AAABBBCC
;3s;/00KLL
<CL 122LMM  ,
3dll6S6SS..zG		+&			*?$$11%877??:.))%:		*%%A:Idll;;;77##K07:		)xX		))  - r    c                   / nU  H  n[         R                  R                  XR                  5      n[         R                  R	                  U5      n[         R                  R	                  U5      nUR                  U5      (       d  [        SU S35      eUR                  5       (       d  UR                  5       (       a  [        SU S35      eUR                  U5        M     U$ )zCheck that the content of ``tar`` will be extracted safely

Args:
    tar: The tarball file
    base: The directory where the tarball will be extracted

Returns:
    list of tarball members
zThe tarball member z^ in downloading model contains directory traversal sequence which may contain harmful payload.zP in downloading model contains symbolic links which may contain harmful payload.)
r   r   r0   r"   abspath
startswithRuntimeErrorissymislnkrM   )tarbaseresultmembermember_pathabs_base
abs_members          r   _tar_members_filterr     s     Fggll4577??4(WW__[1
$$X..%k] 3R S  <<>>V\\^^%k] 3D E  	f  Mr    c                    [         R                  " U 5       n[        [         S5      (       a  UR                  USS9  OUR                  U[	        X!5      S9  SSS5        g! , (       d  f       g= f)a)  Safely extracts a tar file to a specified directory.

This function ensures that the extraction process mitigates against
directory traversal vulnerabilities by validating or sanitizing paths
within the tar file. It also provides compatibility for different versions
of the tarfile module by checking for the availability of certain attributes
or methods before invoking them.

Args:
    model_tar_path: The path to the tar file to be extracted.
    local_model_with_data_dir_path: The directory path where the tar file
  contents will be extracted to.
data_filterdata)r   filter)r   membersN)tarfileopenhasattr
extractallr   )model_tar_pathlocal_model_with_data_dir_pathmodel_with_data_zippeds      r   _extract_model_safer   $  sg      
n	%)?7M**"--3F .  #--3+* .  
&	%	%s   A A  
A.)TT)r   str | os.PathLiker   r   rC   rv   rD   rv   r   boolr   r   rs   rt   )r   ztarfile.TarFiler   r   rs   zlist[tarfile.TarInfo])r   r   r   r   rs   rt   )
__future__r   r   r   collectionsr   typingr   onnx.checkerre   onnx.helperonnx.shape_inferenceonnx.onnx_pbr   r   r   r	   r
   r   rq   r   r   r   r    r   <module>r      s    # 	        f
 f
\ @.!@."@. @. 	@.
 @. @. 
@.F	 1>%GX	r    