
    bIgR-                        d dl mZ 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m	Z	m
Z
mZmZ  G d d      Z	 d		 	 	 	 	 	 	 	 	 	 	 d
dZ	 	 	 	 	 	 ddZ	 	 	 	 	 	 ddZy)    )annotationsN)FunctionProto
ModelProto	NodeProtoTensorProtoValueInfoProtoc                      e Zd ZddZed        Zd ZddZddZ	 	 	 	 	 	 	 	 	 	 	 	 ddZ		 	 	 	 	 	 ddZ
d Z	 	 	 	 dd	Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd
Z	 	 	 	 	 	 ddZy)	Extractorc                *   t         j                  j                  |      | _        | j                  j                  | _        | j                  | j                  j                        | _        | j                  | j                  j                        | _	        y N)
onnxshape_inferenceinfer_shapesmodelgraph_build_name2obj_dictinitializerwmap
value_infovimap)selfr   s     G/var/www/html/answerous/venv/lib/python3.12/site-packages/onnx/utils.py__init__zExtractor.__init__   sc    ))66u=
ZZ%%
--djj.D.DE	..tzz/D/DE
    c                B    | D ci c]  }|j                   | c}S c c}w r   )name)objsobjs     r   r   zExtractor._build_name2obj_dict   s    )-.##...s   c                     j                  |      }t        |      }t        |      }||z  }||z
  }|D cg c]  }||   	 }	}|	j                   fd|D                j                  |	      }
|D cg c]  }|
|   	 c}S c c}w c c}w )Nc              3  <   K   | ]  }j                   |     y wr   )r   ).0r   r   s     r   	<genexpr>z1Extractor._collect_new_io_core.<locals>.<genexpr>#   s     O4djj.Os   )r   setextend)r   original_ioio_names_to_extractoriginal_io_maporiginal_io_namess_io_names_to_extractio_names_to_keepnew_io_names_to_addr   new_io_tensorsnew_io_tensors_maps   `          r   _collect_new_io_corezExtractor._collect_new_io_core   s    33K@0 #$7 803DD36GG<LMD/$/MMO;NOO "66~F5HIT"4(II N Js   B4Bc                N    | j                  | j                  j                  |      S r   )r.   r   inputr   namess     r   _collect_new_inputszExtractor._collect_new_inputs)   s    (()9)95AAr   c                N    | j                  | j                  j                  |      S r   )r.   r   outputr1   s     r   _collect_new_outputszExtractor._collect_new_outputs,   s    (():):EBBr   c           	        ||v ry|D cg c]  }|||   j                   v s| }}|D ]$  }|j                  |       |j                  |       & |D ]+  }||   j                  D ]  }	| j	                  |	||||        - yc c}w )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
            nodes (list of nodes): The list of all nodes of the graph
            reachable (set of int): The set of indexes to reachable nodes in `nodes`
            unreachable (set of int): The set of indexes to unreachable nodes in `nodes`
        N)r5   addremover0   _dfs_search_reachable_nodes)
r   node_output_namegraph_input_namesnodes	reachableunreachableindexnodes_to_search
node_indexr   s
             r   r:   z%Extractor._dfs_search_reachable_nodes/   s    $ 00  +
.>%,BUBU.UE
 

 * 	+JMM*%z*	+
 * 	Jj)// 00+UI{	
s
   BBc                    t        |      }t        | j                  j                        }t               }t        t	        t        |                  }|D ]  }| j                  |||||        t        |      D cg c]  }||   	 }}|S c c}w r   )r#   listr   noderangelenr:   sorted)	r   input_namesoutput_names_input_namesr=   r>   r?   r   rB   s	            r   _collect_reachable_nodesz"Extractor._collect_reachable_nodesU   s    
 ;'TZZ__%!e	 #E#e*$5 6  	D,,lE9k	
 6<I5FGzz"GG Hs   ;Bc                D      fd}g } |||      }|r |||      }|r|S )Nc                    g }| D ]_  t        fdj                  j                  D        d       }|s/||vs4|j                  |       |j	                  |j
                         a |S )Nc              3     K   | ]8  }|j                   j                  k(  r|j                  j                  k(  r| : y wr   )r   op_typedomain)r!   frE   s     r   r"   z[Extractor._collect_referred_local_functions.<locals>.find_referred_funcs.<locals>.<genexpr>s   s8      66T\\1ahh$++6M s   >A)nextr   	functionsappendr$   rE   )r=   referred_local_functions	new_nodesmatch_functionrE   r   s       @r   find_referred_funcszHExtractor._collect_referred_local_functions.<locals>.find_referred_funcsn   st    I :!%!%!5!5
 " "n<T&T,33NC$$^%8%89: r    )r   r=   rY   rV   rW   s   `    r   !_collect_referred_local_functionsz+Extractor._collect_referred_local_functionsf   s:    	$ $& '/GH	+I7OPI  ('r   c                $   t               }|D ]8  }|j                  |j                         |j                  |j                         : | j                  D cg c]  }||v s| j                  |    }}| j
                  D cg c]  }||v s| j
                  |    }}t        | j                  j                        }|dk7  rt        d| d      t        | j                  j                        }|dk7  rt        d| d      ||fS c c}w c c}w )Nr   zlen_sparse_initializer is z, it must be 0.zlen_quantization_annotation is )r#   updater0   r5   r   r   rG   r   sparse_initializer
ValueErrorquantization_annotation)	r   r=   all_tensors_namesrE   tr   r   len_sparse_initializerlen_quantization_annotations	            r   _collect_reachable_tensorsz$Extractor._collect_reachable_tensors   s    '*e 	2D$$TZZ0$$T[[1	2 .2YYQ!?P:Ptyy|QQ-1ZZR1@Q;QdjjmR
R!$TZZ%B%B!C!Q&,-C,DOT  '*$***L*L&M#&!+12M1No^  J&& RRs   	D D	DDc                "   d| j                   j                  z   dz   }t        j                  j	                  ||||||      }| j
                  j                  | j
                  j                  d|d}	t        j                  j                  |fi |	S )NzExtracted from {})r   r   zonnx.utils.extract_model)
ir_versionopset_importsproducer_namerT   )	r   r   r   helper
make_graphr   rh   opset_import
make_model)
r   r=   inputsoutputsr   r   local_functionsr   r   metas
             r   _make_modelzExtractor._make_model   s     "DJJOO3c9&&4kj ' 

 **//!ZZ447(	
 {{%%e4t44r   c                    | j                  |      }| j                  |      }| j                  ||      }| j                  |      \  }}| j	                  |      }| j                  ||||||      }	|	S r   )r3   r6   rL   re   r[   rs   )
r   rI   rJ   ro   rp   r=   r   r   rq   r   s
             r   extract_modelzExtractor.extract_model   s    
 ))+6++L9--k<H"&"A"A%"HZ@@G  67K_
 r   N)r   r   returnNone)r2   	list[str]rv   list[ValueInfoProto])r;   strr<   zset[str]r=   list[NodeProto]r>   set[int]r?   r|   rv   rw   )rI   rx   rJ   rx   rv   r{   )r=   r{   rv   z.tuple[list[TensorProto], list[ValueInfoProto]])r=   r{   ro   ry   rp   ry   r   zlist[TensorProto]r   ry   rq   zlist[FunctionProto]rv   r   )rI   rx   rJ   rx   rv   r   )__name__
__module____qualname__r   staticmethodr   r.   r3   r6   r:   rL   r[   re   rs   ru   rZ   r   r   r
   r
      s   F / /JBC$$ $$ 	$
 $ $ 
$L   
	"(B'' 
8'055 %5 &	5
 '5 )5 -5 
5,   
	r   r
   c                   t         j                  j                  |       st        d|        |st        d      |st        d      t        j
                  j                  |        t	        j                  |       }t        |      }|j                  ||      }t	        j                  ||       |r t        j
                  j                  |       yy)a5  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.

    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 extracted model.
    zInvalid input model path: z%Output model path shall not be empty!z'Output tensor names shall not be empty!N)ospathexistsr_   r   checkercheck_modelloadr
   ru   save)
input_pathoutput_pathrI   rJ   r   r   e	extracteds           r   ru   ru      s    , 77>>*%5j\BCC@AABCCLLZ(IIj!E%A\:IIIi%  - r   c                   g }| D ]  }t         j                  j                  ||j                        }t         j                  j	                  |      }t         j                  j	                  |      }|j                  |      st        d| d      |j                         s|j                         rt        d| d      |j                  |        |S )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   joinr   abspath
startswithRuntimeErrorissymislnkrU   )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                    t        j                  |       5 }t        t         d      r|j                  |d       n|j                  |t	        ||             ddd       y# 1 sw Y   yxY w)aQ  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     sp      
n	% )?7M*"--3F .  #--3+*,J .   s   AA!!A*)T)r   str | os.PathLiker   r   rI   rx   rJ   rx   r   boolrv   rw   )r   ztarfile.TarFiler   r   rv   zlist[tarfile.TarInfo])r   r   r   r   rv   rw   )
__future__r   r   r   onnx.checkerr   onnx.helperonnx.shape_inferencer   r   r   r   r   r
   ru   r   r   rZ   r   r   <module>r      s    # 	     R Rt tx %.!%."%. %. 	%.
 %. 
%.P	 1>%GX	r   