
    1;ji/1                        d dl mZ d dlZd dlZd dlmZ d dlmZ d dlZ	d dl
Z	d dlZ	er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dS )!    )annotationsN)deque)TYPE_CHECKING)FunctionProto
ModelProto	NodeProtoTensorProtoValueInfoProtoc                  ~    e Zd Zd'dZed(d            Zed)d	            Zd*dZd+dZd,dZ	d-dZ
d.dZd/d$Zd0d%Zd&S )1	Extractormodelr   returnNonec                   || _         | j         j        | _        |                     | j        j                  | _        |                     | j        j                  | _        | j                            |                     | j        j                             | j                            |                     | j        j	                             | 
                    | j                  | _        d S N)r   graph_build_name2obj_dictinitializerinitializers
value_infovalue_infosupdateinputoutput_build_output_dictoutmap)selfr   s     D/root/voice-cloning/.venv/lib/python3.11/site-packages/onnx/utils.py__init__zExtractor.__init__   s    
Z%
484M4MJ"5
 5
 7;6O6OJ!7
 7
 	 9 9$*:J K KLLL 9 9$*:K L LMMM&*&=&=dj&I&I    dictc                    d | D             S )Nc                    i | ]
}|j         |S  )name).0objs     r   
<dictcomp>z2Extractor._build_name2obj_dict.<locals>.<dictcomp>*   s    ...##...r    r$   )objss    r   r   zExtractor._build_name2obj_dict(   s    ......r    dict[str, int]c                v    i }t          | j                  D ]!\  }}|j        D ]}|dk    r	||vsJ |||<   "|S )N )	enumeratenoder   )r   output_to_indexindexr.   output_names        r   r   zExtractor._build_output_dict,   sn    *,$UZ00 	5 	5KE4#{ 5 5"$$"/9999/4,,	5
 r    io_names_to_extract	list[str]list[ValueInfoProto]c                      fd|D             }|r%t          dd                    |                      fd|D             S )Nc                &    g | ]}|j         v|S r$   r   r&   r%   r   s     r   
<listcomp>z-Extractor._collect_new_io.<locals>.<listcomp>9   s-     
 
 
D@P4P4PD4P4P4Pr    z3The following names were not found in value_infos: z, c                *    g | ]}j         |         S r$   r7   r8   s     r   r9   z-Extractor._collect_new_io.<locals>.<listcomp>@   s!    GGG4 &GGGr    )
ValueErrorjoin)r   r2   missing_namess   `  r   _collect_new_iozExtractor._collect_new_io7   s}    
 
 
 
0
 
 
  	`diiP]F^F^``   HGGG3FGGGGr    node_output_namestrgraph_input_namesset[str]	reachableset[int]c                    |g}|rp|                                 }||v r|| j        v rJ| j        |         }||vr9|                    |           |d | j        j        |         j        D             z  }|ndS dS )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`
        c                    g | ]
}|d k    |S )r,   r$   )r&   
input_names     r   r9   z9Extractor._dfs_search_reachable_nodes.<locals>.<listcomp>[   s-       &%++ #+++r    N)popr   addr   r.   r   )r   r?   rA   rC   stackcurrent_output_namer0   s          r   _dfs_search_reachable_nodesz%Extractor._dfs_search_reachable_nodesB   s     "" 	"'))++"&777"dk11$78	))MM%(((  *.*/%*@*F   E  	 	 	 	 	r    input_namesoutput_nameslist[NodeProto]c                     t          |          }t                      }|D ]}                     |||            fdt          |          D             S )Nc                4    g | ]}j         j        |         S r$   )r   r.   )r&   r0   r   s     r   r9   z6Extractor._collect_reachable_nodes.<locals>.<listcomp>k   s"    FFF5
&FFFr    )setrL   sorted)r   rM   rN   _input_namesrC   r%   s   `     r   _collect_reachable_nodesz"Extractor._collect_reachable_nodesa   si    
 ;''!ee	  	L 	LD,,T<KKKKFFFFF94E4EFFFFr    nodeslist[FunctionProto]c                \   i }| j         j        D ]}|||j        |j        f<   g }t	          |          }|rv|                                }|j        |j        f|v rP|                    |j        |j        f          }|                    |           |	                    |j
                   |v|S r   )r   	functionsr%   domainr   popleftop_typerH   appendextendr.   )r   rV   function_mapfunctionreferred_local_functionsqueuer.   s          r   !_collect_referred_local_functionsz+Extractor._collect_referred_local_functionsm   s     >@
, 	F 	FH=EL(-9::8: e 	,==??Ddk*l::'++T\4;,GHH(//999X]+++  	, ('r    .tuple[list[TensorProto], list[ValueInfoProto]]c                    t                      |D ]6}                    |j                                       |j                   7 fd j        D             } fd j        D             }t           j        j                  }|dk    rt          d| d          t           j        j
                  }|dk    rt          d| d          ||fS )Nc                2    g | ]}|v j         |         S r$   )r   r&   tall_tensors_namesr   s     r   r9   z8Extractor._collect_reachable_tensors.<locals>.<listcomp>   s3     
 
 
%&qDU?U?UDa ?U?U?Ur    c                2    g | ]}|v j         |         S r$   r7   rg   s     r   r9   z8Extractor._collect_reachable_tensors.<locals>.<listcomp>   s3     
 
 
$%QBS=S=SDQ=S=S=Sr    r   zlen_sparse_initializer is z, it must be 0.zlen_quantization_annotation is )rR   r   r   r   r   r   lenr   sparse_initializerr;   quantization_annotation)r   rV   r.   r   r   len_sparse_initializerlen_quantization_annotationri   s   `      @r   _collect_reachable_tensorsz$Extractor._collect_reachable_tensors   s=    '*ee 	2 	2D$$TZ000$$T[1111
 
 
 
 
*.*;
 
 

 
 
 
 
)-)9
 
 

 "%TZ%B!C!C!Q&&T-CTTT   '*$**L&M&M#&!++^2M^^^   J&&r    inputsoutputsr   list[TensorProto]r   local_functionsc                    d| j         j        z   dz   }t          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_namerY   )	r   r%   onnxhelper
make_graphr   rw   opset_import
make_model)
r   rV   rq   rr   r   r   rt   r%   r   metas
             r   _make_modelzExtractor._make_model   s     "DJO3c9&&4kj ' 
 
 */!Z47(	
 
 {%e44t444r    c                   |                      |          }|                      |          }|                     ||          }|                     |          \  }}|                     |          }|                     ||||||          S r   )r>   rU   rp   rc   r   )	r   rM   rN   rq   rr   rV   r   r   rt   s	            r   extract_modelzExtractor.extract_model   s    
 %%k22&&|44--k<HH"&"A"A%"H"HZ@@GG67K_
 
 	
r    N)r   r   r   r   )r   r!   )r   r*   )r2   r3   r   r4   )r?   r@   rA   rB   rC   rD   r   r   )rM   r3   rN   r3   r   rO   )rV   rO   r   rW   )rV   rO   r   rd   )rV   rO   rq   r4   rr   r4   r   rs   r   r4   rt   rW   r   r   )rM   r3   rN   r3   r   r   )__name__
__module____qualname__r   staticmethodr   r   r>   rL   rU   rc   rp   r   r   r$   r    r   r   r      s        J J J J / / / \/    \	H 	H 	H 	H   >
G 
G 
G 
G( ( ( (.' ' ' '45 5 5 5*
 
 
 
 
 
r    r   T
input_pathstr | os.PathLikeoutput_pathrM   r3   rN   check_modelboolinfer_shapesr   r   c                P   t           j                            |           st          d|            |st          d          |st          d          |st          d          t	          |          t	          t          |                    k    rt          d          t	          |          t	          t          |                    k    rt          d          |rt          j                            |            |rgt           j        	                    |           t          j        j
        k    r5t          j                            | |           t          j        |          }n|rjt          j        | d          }t          j                            |          }t           j                            |           }t          j        ||           nt          j        |           }t#          |          }|                    ||          }	|	                                t          j        j
        k    r;t           j                            |          d	z   }
t          j        |	|d
|
           nt          j        |	|           |r!t          j                            |           dS dS )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;   rk   rR   rz   checkerr   getsizeMAXIMUM_PROTOBUFshape_inferenceinfer_shapes_pathloadr   dirnameload_external_data_for_modelr   r   ByteSizebasenamesave)r   r   rM   rN   r   r   r   base_dire	extractedr   s              r   r   r      sg   4 7>>*%% DBjBBCCC B@AAA CABBB DBCCC
;3s;//0000KLLL
<CL 1 12222LMMM -  ,,, 	&
33dl6SSS..z;GGG	+&&	 &	*???$11%887??:..)%::::	*%%%A\::Idl;;;7##K007:	)[xXXXXX	)[))) .  -----. .r    tartarfile.TarFilebaselist[tarfile.TarInfo]c                   g }| D ]}t           j                            ||j                  }t           j                            |          }t           j                            |          }|                    |          st          d| d          |                                s|                                rt          d| d          |	                    |           |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   r<   r%   abspath
startswithRuntimeErrorissymislnkr]   )r   r   resultmembermember_pathabs_base
abs_members          r   _tar_members_filterr     s     F  gll4557??4((W__[11
$$X.. 	Sk S S S   <<>> 	V\\^^ 	Ek E E E   	fMr    model_tar_pathlocal_model_with_data_dir_pathc                   t          j        |           5 }t          t           d          r|                    |d           n%|                    |t	          ||                     ddd           dS # 1 swxY w Y   dS )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   )r   r   model_with_data_zippeds      r   _extract_model_safer   $  s      
n	%	% )?7M** 
	"--3F .     #--3+*,J  .                    s   AA55A9<A9)TT)r   r   r   r   rM   r3   rN   r3   r   r   r   r   r   r   )r   r   r   r   r   r   )r   r   r   r   r   r   )
__future__r   r   r   collectionsr   typingr   onnx.checkerrz   onnx.helperonnx.shape_inferenceonnx.onnx_pbr   r   r   r	   r
   r   r   r   r   r$   r    r   <module>r      sK   # " " " " " 				                                             f
 f
 f
 f
 f
 f
 f
 f
\ @. @. @. @. @.F   >     r    