
    
NgR-                     |   d dl Z d dlZd dlZd dlZd dlmZ d dlmZmZm	Z	 d dl
mc mZ d dlmZmZmZmZ  G d d          Zdeded	dfd
Zdeded	dfdZ	 	 	 	 d.dedede	e         de	e         de	e         de	e         d	dfdZ	 	 	 	 d/dedede	e         deded	dfdZded	dfdZdeded	dfdZded	ee         fdZded eegee         f         d	ee         fd!Zd"ed	ee         fd#Zded	ee         fd$Z d"ed	ee         fd%Z!ded	ee         fd&Z"d'ed	efd(Z#ded	efd)Z$ded*ed	dfd+Z%ded,ed	efd-Z&dS )0    N)chain)CallableIterableOptional)AttributeProto
GraphProto
ModelProtoTensorProtoc                       e Zd ZdeddfdZdS )ExternalDataInfotensorreturnNc                    d| _         d | _        d | _        d | _        d| _        |j        D ]}t          | |j        |j                   | j        rt          | j                  | _        | j        rt          | j                  | _        d S d S )N )
locationoffsetlengthchecksumbasepathexternal_datasetattrkeyvalueint)selfr   entrys      U/var/www/html/ai-engine/env/lib/python3.11/site-packages/onnx/external_data_helper.py__init__zExternalDataInfo.__init__   s    ) 	2 	2ED%)U[1111; 	+dk**DK; 	+dk**DKKK	+ 	+    )__name__
__module____qualname__r
   r    r   r   r   r      s6        +{ +t + + + + + +r   r   r   base_dirr   c                 x   t          |           }t          j        ||j        | j                  }t          |d          5 }|j        r|                    |j                   |j        r |	                    |j                  | _
        n|	                                | _
        ddd           dS # 1 swxY w Y   dS )zLoads data from an external file for tensor.
    Ideally TensorProto should not hold any raw data but if it does it will be ignored.

    Arguments:
        tensor: a TensorProto object.
        base_dir: directory that contains the external data.
    rbN)r   	c_checker_resolve_external_data_locationr   nameopenr   seekr   readraw_data)r   r$   infoexternal_data_file_path	data_files        r   load_external_data_for_tensorr1   !   s     F##D'G$-  
%t	,	, /	; 	(NN4;'''; 	/'nnT[99FOO'nn..FO/ / / / / / / / / / / / / / / / / /s    A"B//B36B3modelc                     t          |           D ]<}t          |          r+t          ||           t          j        |_        |j        dd= =dS )zLoads external tensors into model

    Arguments:
        model: ModelProto to load external data to
        base_dir: directory that contains external data
    N)_get_all_tensorsuses_external_datar1   r
   DEFAULTdata_locationr   )r2   r$   r   s      r   load_external_data_for_modelr8   7   s`     #5)) ( (f%% 	()&(;;;#.#6F $QQQ'( (r   r   r   r   r   r   c                    |                      d          st          d| j        z   dz             | j        d d = t          j        | _        ||t          |          nd |t          |          nd ||d                                D ];\  }}|4| j        	                                }||_
        t          |          |_        <d S )Nr-   zTensor zGdoes not have raw_data field. Cannot set external data for this tensor.)r   r   r   r   r   )HasField
ValueErrorr)   r   r
   EXTERNALr7   r   itemsaddr   strr   )	r   r   r   r   r   r   kvr   s	            r   set_external_datarB   G   s     ??:&& 
kWX
 
 	
 	QQQ&/F!'!3#f+++!'!3#f+++  egg
! 
!1 =(,,..EEIa&&EK
! 
!r   T   Fall_tensors_to_one_filesize_thresholdconvert_attributec                 z   t          |           }|rt          |           }|rt          t          j                              }|r0t
          j                            |          rt          d          |}|D ]D}|	                    d          r-t          j        |j                  |k    rt          ||           EdS |D ]z}|	                    d          rct          j        |j                  |k    rF|j        }t          |          s t          t          j                              }t          ||           {dS )a  Call to set all tensors with raw data as external data. This call should precede 'save_model'.
    'save_model' saves all the tensors data as external data after calling this function.

    Arguments:
        model (ModelProto): Model to be converted.
        all_tensors_to_one_file (bool): If true, save all tensors to one external file specified by location.
            If false, save each tensor to a file named with the tensor name.
        location: specify the external file relative to the model that all tensors to save to.
            Path is relative to the model path.
            If not specified, will use the model name.
        size_threshold: Threshold for size of data. Only when tensor's data is >= the size_threshold
            it will be converted to external data. To convert every tensor with raw data to external data set size_threshold=0.
        convert_attribute (bool): If true, convert all tensors to external data
                       If false, convert only non-attribute tensors to external data
    zDlocation must be a relative path that is relative to the model path.r-   N)_get_initializer_tensorsr4   r?   uuiduuid1ospathisabsr;   r:   sys	getsizeofr-   rB   r)   _is_valid_filename)	r2   rD   r   rE   rF   tensors	file_namer   tensor_locations	            r   convert_model_to_external_datarT   e   sQ   , 'u--G *"5)) ;
%%	 	!w}}X&&  Z   !I 	5 	5F
++5M&/22nDD!&)444	5 	5  	; 	;F
++;M&/22nDD"(+)/:: 8&)$*,,&7&7O!&/:::	; 	;r   c                     t          |           D ]P}t          |          r?|                    d          st          d          |j        dd= t
          j        |_        QdS )zCall to set all tensors which use external data as embedded data.
    save_model saves all the tensors data as embedded data after
    calling this function.

    Arguments:
        model (ModelProto): Model to be converted.
    r-   raw_data field doesn't exist.N)r4   r5   r:   r;   r   r
   r6   r7   )r2   r   s     r    convert_model_from_external_datarW      st     #5)) 7 7f%% 	7??:.. B !@AAA$QQQ'#.#6F 7 7r   	base_pathc                 8   t          |           }t          j                            ||j                  }|                     d          st          d          t          j                            |          s)t          |d          5  	 ddd           n# 1 swxY w Y   t          |d          5 }|	                    dd           |j
        Y|                                }|j
        |k    r |                    d|j
        |z
  z             |	                    |j
                   |                                }|                    | j                   t          | |j        ||                                |z
             ddd           dS # 1 swxY w Y   dS )	zWrites tensor data to an external file according to information in the `external_data` field.

    Arguments:
        tensor (TensorProto): Tensor object to be serialized
        base_path: System path of a folder where tensor data is to be stored
    r-   rV   abNzr+br          )r   rK   rL   joinr   r:   r;   isfiler*   r+   r   tellwriter-   rB   )r   rX   r.   r/   r0   	file_sizer   s          r   save_external_datarb      s	    F##D gll9dmDD ??:&& :8999 7>>122 )400 	 		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 
%u	-	- Tq!;"!((I{Y&&y)@ ABBBNN4;'''!!(((&$-9I9IF9RSSST T T T T T T T T T T T T T T T T Ts%   BBB1CFFFonnx_model_protoc                 V    t          t          |           t          |                     S )z=Scan an ONNX model for all tensors and return as an iterator.)r   rH   _get_attribute_tensorsrc   s    r   r4   r4      s,     !122/00  r   	attributefuncc              #      K   | j         t          j        k    r || j                  E d{V  | j         t          j        k    r| j        D ]} ||          E d{V  dS dS )zICreate an iterator through processing ONNX model attributes with functor.N)typer   GRAPHgGRAPHSgraphs)rg   rh   graphs      r   _recursive_attribute_processorrp      s       ~---4	$$$$$$$$$~...% 	# 	#EtE{{"""""""" /.	# 	#r   onnx_model_proto_graphc              #      K   | j         E d{V  | j        D ]'}|j        D ]}t          |t                    E d{V  (dS )z@Create an iterator of initializer tensors from ONNX model graph.N)initializernoderg   rp   #_get_initializer_tensors_from_graphrq   rt   rg   s      r   ru   ru      s       &11111111&+   	 	I5>         	 r   c              #   >   K   t          | j                  E d{V  dS )z:Create an iterator of initializer tensors from ONNX model.N)ru   ro   rf   s    r   rH   rH      s0      23C3IJJJJJJJJJJJr   c              #      K   | j         D ]R}|j        D ]H}|                    d          r	|j        V  |j        E d{V  t          |t                    E d{V  ISdS )zJCreate an iterator of tensors from node attributes of an ONNX model graph.tN)rt   rg   r:   ry   rQ   rp   !_get_attribute_tensors_from_graphrv   s      r   rz   rz      s       '+   	 	I!!#&& "k!!! ((((((((5<         		 r   c              #   >   K   t          | j                  E d{V  dS )zDCreate an iterator of tensors from node attributes of an ONNX model.N)rz   ro   rf   s    r   re   re      s0      01A1GHHHHHHHHHHHr   filenamec                 r    t          j        d          }|                    |           }t          |          S )z8Utility to check whether the provided filename is valid.z^[^<>:;,?"*|/]+$)recompilematchbool)r|   expr   s      r   rP   rP     s/    
*'
(
(CIIhE;;r   c                 V    |                      d          o| j        t          j        k    S )z?Returns true if the tensor stores data in an external location.r7   )r:   r7   r
   r<   )r   s    r   r5   r5   	  s+     	(( 	9 K$88r   	field_keyc                 `    t          | j                  D ]\  }}|j        |k    r| j        |= dS )a  Removes a field from a Tensor's external_data key-value store.

    Modifies tensor object in place.

    Arguments:
        tensor (TensorProto): Tensor object from which value will be removed
        field_key (string): The key of the field to be removed
    N)	enumerater   r   )r   r   ifields       r   remove_external_data_fieldr     sE     f233 ( (59	!!$Q'( (r   filepathc                     t          |           D ]K}t          |          r:|                    d          r%t          ||           |                    d           L| S )a  Serializes data for all the tensors which have data location set to TensorProto.External.

    Note: This function also strips basepath information from all tensors' external_data fields.

    Arguments:
        model (ModelProto): Model object which is the source of tensors to serialize.
        filepath: System path to the directory which should be treated as base path for external data.

    Returns:
        ModelProto: The modified model object.
    r-   )r4   r5   r:   rb   
ClearField)r2   r   r   s      r   write_external_data_tensorsr     sj     #5)) * *
 f%% 	*&//**E*E 	*vx000j)))Lr   )NNNN)TNrC   F)'rK   r~   rN   rI   	itertoolsr   typingr   r   r   onnx.onnx_cpp2py_export.checkeronnx_cpp2py_exportcheckerr'   onnx.onnx_pbr   r   r	   r
   r   r?   r1   r8   r   rB   r   rT   rW   rb   r4   rp   ru   rH   rz   re   rP   r5   r   r   r#   r   r   <module>r      s   
			 				 



        / / / / / / / / / / 3 3 3 3 3 3 3 3 3 L L L L L L L L L L L L+ + + + + + + +$/+ / / / / / /,(
 (c (d ( ( ( (& ! ""! !!! SM! SM	!
 sm! sm! 
! ! ! !@ %)"#1; 1;1;!1; sm1; 	1;
 1; 
1; 1; 1; 1;h7J 74 7 7 7 7 T{ Ts Tt T T T TDz h{6K    ##%-zlH[<Q.Q%R#k# # # #	&	k	 	 	 	Kz Kh{>S K K K K
&k   IZ IH[<Q I I I I
     { t    ({ (s (t ( ( ( (z S Z      r   