
    
Ng                     t    d dl m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S )    )annotationsN)FunctionProto
ModelProto	NodeProtoTensorProtoValueInfoProtoc                  p    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d#S )+	Extractormodelr   returnNonec                    t           j                            |          | _        | j        j        | _        |                     | j        j                  | _        |                     | j        j                  | _	        d S N)
onnxshape_inferenceinfer_shapesr   graph_build_name2obj_dictinitializerwmap
value_infovimap)selfr   s     F/var/www/html/ai-engine/env/lib/python3.11/site-packages/onnx/utils.py__init__zExtractor.__init__   s^    )66u==
Z%
--dj.DEE	..tz/DEE


    c                    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   c                R  
 |                      |          }t          |          }t          |          }||z  }||z
  }g }|D ]}	|                    ||	                    |D ]"}	|                    | j        |	                    #|                      |          

fd|D             S )Nc                     g | ]
}|         S r   r   )r!   r    new_io_tensors_maps     r   
<listcomp>z2Extractor._collect_new_io_core.<locals>.<listcomp>)   s    IIIT"4(IIIr   )r   setappendr   )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_addnew_io_tensorsr    r'   s             @r   _collect_new_io_corezExtractor._collect_new_io_core   s    33K@@00 #$7 8 803DD36GG$ 	9 	9D!!/$"78888' 	4 	4D!!$*T"23333 "66~FFIIII5HIIIIr   names	list[str]list[ValueInfoProto]c                B    |                      | j        j        |          S r   )r3   r   inputr   r4   s     r   _collect_new_inputszExtractor._collect_new_inputs+   s    (()95AAAr   c                B    |                      | j        j        |          S r   )r3   r   outputr9   s     r   _collect_new_outputszExtractor._collect_new_outputs.   s    (():EBBBr   node_output_namestrgraph_input_namesreachable_nodeslist[NodeProto]c                    ||v rd S | j         j        D ]G}||j        vr||v r|                    |           |j        D ]}|                     |||           Hd S r   )r   noder<   r*   r8   _dfs_search_reachable_nodes)r   r>   r@   rA   rD   r    s         r   rE   z%Extractor._dfs_search_reachable_nodes1   s     000FJO 
	 
	Dt{22&&""4(((
  00+_   
	 
	r   input_namesoutput_namesc                t    g |D ]}|                      ||           fd| j        j        D             }|S )Nc                    g | ]}|v |	S r   r   )r!   nrA   s     r   r(   z6Extractor._collect_reachable_nodes.<locals>.<listcomp>N   s#    DDDqqO/C/C/C/C/Cr   )rE   r   rD   )r   rF   rG   r    nodesrA   s        @r   _collect_reachable_nodesz"Extractor._collect_reachable_nodesE   sX    
   	Q 	QD,,T;PPPPDDDDDJODDDr   c                N      fd}g } |||          }|r |||          }||S )Nc                    g }| D ]]t          fdj        j        D             d           }|r3||vr/|                    |           |                    |j                   ^|S )Nc              3  \   K   | ]&}|j         j        k    |j        j        k    "|V  'd S r   )r    op_typedomain)r!   frD   s     r   	<genexpr>z[Extractor._collect_referred_local_functions.<locals>.find_referred_funcs.<locals>.<genexpr>^   sL        6T\11ah$+6M6M 6M6M6M6M r   )nextr   	functionsr*   extendrD   )rK   referred_local_functions	new_nodesmatch_functionrD   r   s       @r   find_referred_funcszHExtractor._collect_referred_local_functions.<locals>.find_referred_funcsY   s    I : :!%   !%!5  
 " " " :n<T&T&T,33NCCC$$^%8999r   r   )r   rK   rZ   rW   rX   s   `    r   !_collect_referred_local_functionsz+Extractor._collect_referred_local_functionsQ   sf    	 	 	 	 	$ $& ''/GHH	 	Q++I7OPPI  	Q ('r   rK   .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   r(   z8Extractor._collect_reachable_tensors.<locals>.<listcomp>|   s*    QQQ!?P:P:Pty|:P:P:Pr   c                2    g | ]}|v j         |         S r   )r   r_   s     r   r(   z8Extractor._collect_reachable_tensors.<locals>.<listcomp>}   s*    RRR1@Q;Q;Qdjm;Q;Q;Qr   r   zlen_sparse_initializer is z, it must be 0.zlen_quantization_annotation is )r)   updater8   r<   r   r   lenr   sparse_initializer
ValueErrorquantization_annotation)r   rK   rD   r   r   len_sparse_initializerlen_quantization_annotationra   s   `      @r   _collect_reachable_tensorsz$Extractor._collect_reachable_tensorsr   s    '*ee 	2 	2D$$TZ000$$T[1111QQQQQTYQQQRRRRRTZRRR
!$TZ%B!C!C!Q&&T-CTTT   '*$**L&M&M#&!++^2M^^^   J&&r   inputsoutputsr   list[TensorProto]r   local_functionslist[FunctionProto]c                    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_namerU   )	r   r    r   helper
make_graphr   rr   opset_import
make_model)
r   rK   rk   rl   r   r   rn   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:   r=   rL   rj   r[   rz   )
r   rF   rG   rk   rl   rK   r   r   rn   r   s
             r   extract_modelzExtractor.extract_model   s    
 ))+66++L99--k<HH"&"A"A%"H"HZ@@GG  67K_
 
 r   N)r   r   r   r   )r4   r5   r   r6   )r>   r?   r@   r5   rA   rB   r   r   )rF   r5   rG   r5   r   rB   )rK   rB   r   r\   )rK   rB   rk   r6   rl   r6   r   rm   r   r6   rn   ro   r   r   )rF   r5   rG   r5   r   r   )__name__
__module____qualname__r   staticmethodr   r3   r:   r=   rE   rL   r[   rj   rz   r|   r   r   r   r
   r
      s        F F F F / / \/J J J$B B B BC C C C   (
 
 
 
( ( (B' ' ' '05 5 5 5,     r   r
   T
input_pathstr | os.PathLikeoutput_pathrF   r5   rG   check_modelboolr   r   c                   t           j                            |           st          d|            |st          d          |st          d          t          j                            |            t	          j        |           }t          |          }|	                    ||          }t	          j
        ||           |r!t          j                            |           dS dS )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existsrf   r   checkerr   loadr
   r|   save)r   r   rF   rG   r   r   e	extracteds           r   r|   r|      s    , 7>>*%% DBjBBCCC B@AAA DBCCCLZ(((Ij!!E%A\::IIi%%% .  -----. .r   )T)r   r   r   r   rF   r5   rG   r5   r   r   r   r   )
__future__r   r   onnx.checkerr   onnx.helperonnx.shape_inferencer   r   r   r   r   r
   r|   r   r   r   <module>r      s    # " " " " " 				             R R R R R R R R R R R R R R` ` ` ` ` ` ` `P %. %. %. %. %. %. %.r   