
    bIg.                    n   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 d dlm	Z	m
Z
 d dlmc mZ d dlmZmZmZmZmZ  G d d      ZddZdd	Z	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 dd
Z	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZddZddZd dZ	 	 	 	 	 	 d!dZ	 	 	 	 d"dZd dZ	 	 	 	 d"dZ d dZ!d#dZ"d$dZ#d%dZ$d&dZ%y)'    )annotationsN)chain)CallableIterable)AttributeProtoFunctionProto
GraphProto
ModelProtoTensorProtoc                      e Zd ZddZy)ExternalDataInfoc                H   d| _         d | _        d | _        d | _        d| _        |j
                  D ]#  }t        | |j                  |j                         % | j                  rt        | j                        | _        | j                  rt        | j                        | _        y y )N )
locationoffsetlengthchecksumbasepathexternal_datasetattrkeyvalueint)selftensorentrys      V/var/www/html/answerous/venv/lib/python3.12/site-packages/onnx/external_data_helper.py__init__zExternalDataInfo.__init__   s    )) 	2ED%))U[[1	2 ;;dkk*DK;;dkk*DK     N)r   r   returnNone)__name__
__module____qualname__r    r   r   r   r      s    +r   r   c                   t        |       }t        j                  ||j                  | j                        }t        |d      5 }|j                  r|j                  |j                         |j                  r!|j                  |j                        | _
        n|j                         | _
        ddd       y# 1 sw Y   yxY w)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   base_dirinfoexternal_data_file_path	data_files        r   load_external_data_for_tensorr3   )   s     F#D'GG$-- 
%t	, /	;;NN4;;';;'nnT[[9FO'nn.FO/ / /s   A*B66B?c                    t        |       D ]>  }t        |      st        ||       t        j                  |_        |j                  dd= @ y)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_datar3   r   DEFAULTdata_locationr   )modelr/   r   s      r   load_external_data_for_modelr:   ?   sF     #5) (f%)&(;#.#6#6F $$Q'(r   c                |   | j                  d      st        d| j                  z   dz         | j                  d d = t        j
                  | _        ||t        |      nd |t        |      nd ||dj                         D ]9  \  }}|	| j                  j                         }||_
        t        |      |_        ; y )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   EXTERNALr8   r   itemsaddr   strr   )	r   r   r   r   r   r   kvr   s	            r   set_external_datarD   O   s     ??:&kkWX
 	
 	Q&//F!'!3#f+!'!3#f+ eg
!1 =((,,.EEIa&EK
!r   c                X   t        |       }|rt        |       }|rt        t        j                               }|r,t
        j                  j                  |      rt        d      |}|D ]C  }|j                  d      st        j                  |j                        |k\  s8t        ||       E y|D ]w  }|j                  d      st        j                  |j                        |k\  s8|j                  }t        |      st        t        j                               }t        ||       y y)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_tensorsr5   rA   uuiduuid1ospathisabsr=   r<   sys	getsizeofr.   rD   r*   _is_valid_filename)	r9   all_tensors_to_one_filer   size_thresholdconvert_attributetensors	file_namer   tensor_locations	            r   convert_model_to_external_datarU   m   s    , 'u-G"5)

%	ww}}X& Z  !I 	5F
+MM&//2nD!&)4	5  	;F
+MM&//2nD"(++)/:&)$**,&7O!&/:	;r   c                    t        |       D ]N  }t        |      s|j                  d      st        d      |j                  dd= t
        j                  |_        P y)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)r5   r6   r<   r=   r   r   r7   r8   )r9   r   s     r    convert_model_from_external_datarX      sT     #5) 7f%??:. !@AA$$Q'#.#6#6F 7r   c                   t        |       }t        j                  j                  ||j                        }| j                  d      st        d      t        j                  j                  |      st        |d      5  	 ddd       t        |d      5 }|j                  dd       |j                  [|j                         }|j                  |kD  r!|j                  d|j                  |z
  z         |j                  |j                         |j                         }|j                  | j                         t        | |j                  ||j                         |z
         ddd       y# 1 sw Y   xY w# 1 sw Y   yxY w)	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.   rW   abNzr+br          )r   rI   rJ   joinr   r<   r=   isfiler+   r,   r   tellwriter.   rD   )r   	base_pathr0   r1   r2   	file_sizer   s          r   save_external_datarc      s9    F#D ggll9dmmD ??:&899 77>>12)40 		 
%u	- Tq!;;"!(I{{Y&y)@ ABNN4;;'!(&$--9IF9RST T		 	T Ts   =E*CE6*E36E?c                >    t        t        |       t        |             S )z=Scan an ONNX model for all tensors and return as an iterator.)r   rF   _get_attribute_tensors)onnx_model_protos    r   r5   r5      s!     !12/0 r   c              #     K   | j                   t        j                  k(  r || j                        E d{    | j                   t        j                  k(  r"| j
                  D ]  } ||      E d{     yy7 D7 
w)zICreate an iterator through processing ONNX model attributes with functor.N)typer   GRAPHgGRAPHSgraphs)	attributefuncgraphs      r   _recursive_attribute_processorrp      sp      ~~---	$$$~~...%% 	#EE{""	# / 	% #s!   3A>A:;A>1A<2	A><A>c             #     K   t        | t              r| j                  E d{    | j                  D ]+  }|j                  D ]  }t        |t              E d{     - y7 ?7 w)zICreate an iterator of initializer tensors from ONNX model graph/function.N)
isinstancer	   initializernoderm   rp   #_get_initializer_tensors_from_graphgraph_or_functionrt   rm   s      r   ru   ru      sm      #Z0$0000!&&  	I5>  	 	1s!    A&A"5A&A$
A&$A&c              #     K   t        | j                        E d{    | j                  D ]  }t        |      E d{     y7 )7 	w)z:Create an iterator of initializer tensors from ONNX model.N)ru   ro   	functions!_get_attribute_tensors_from_graphrf   functions     r   rF   rF      sH     23C3I3IJJJ$.. ?4X>>>? K>   A	A!A	AA	A	c             #     K   | j                   D ]^  }|j                  D ]M  }|j                  d      r|j                   |j                  E d{    t        |t              E d{    O ` y7 !7 w)zSCreate an iterator of tensors from node attributes of an ONNX model graph/function.tN)rt   rm   r<   r   rR   rp   rz   rv   s      r   rz   rz      sz      "&&  	I!!#&kk! ((((5<  		 )s$   AA5A1A5'A3(
A53A5c              #     K   t        | j                        E d{    | j                  D ]  }t        |      E d{     y7 )7 	w)zDCreate an iterator of tensors from node attributes of an ONNX model.N)rz   ro   ry   r{   s     r   re   re     sH     01A1G1GHHH$.. ?4X>>>? I>r}   c                d    t        j                  d      }|j                  |       }t        |      S )z8Utility to check whether the provided filename is valid.z^[^<>:;,?"*|/]+$)recompilematchbool)filenameexpr   s      r   rN   rN     s)    
**'
(CIIhE;r   c                b    | j                  d      xr | j                  t        j                  k(  S )z?Returns true if the tensor stores data in an external location.r8   )r<   r8   r   r>   )r   s    r   r6   r6     s.     	( 	9  K$8$88r   c                x    t        | j                        D ]"  \  }}|j                  |k(  s| j                  |= $ y)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   	field_keyifields       r   remove_external_data_fieldr     s<     f223 (599	!$$Q'(r   c                    t        |       D ]=  }t        |      s|j                  d      s!t        ||       |j	                  d       ? | 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.   )r5   r6   r<   rc   
ClearField)r9   filepathr   s      r   write_external_data_tensorsr   ,  sL     #5) *
 f%&//**Evx0j)* Lr   )r   r   r/   rA   r    r!   )r9   r
   r/   rA   r    r!   )NNNN)r   r   r   rA   r   
int | Noner   r   r   
str | Noner   r   r    r!   )TNi   F)r9   r
   rO   r   r   r   rP   r   rQ   r   r    r!   )r9   r
   r    r!   )r   r   ra   rA   r    r!   )rf   r
   r    Iterable[TensorProto])rm   r   rn   z-Callable[[GraphProto], Iterable[TensorProto]]r    r   )rw   zGraphProto | FunctionProtor    r   )r   rA   r    r   )r   r   r    r   )r   r   r   rA   r    r!   )r9   r
   r   rA   r    r
   )&
__future__r   rI   r   rL   rG   	itertoolsr   typingr   r   onnx.onnx_cpp2py_export.checkeronnx_cpp2py_exportcheckerr(   onnx.onnx_pbr   r   r	   r
   r   r   r3   r:   rD   rU   rX   rc   r5   rp   ru   rF   rz   re   rN   r6   r   r   r%   r   r   <module>r      sX   # 	 	 
   % 3 3 + +$/,(& !!! ! 	!
 ! ! 
!@ %)#1;1;!1; 1; 	1;
 1; 
1;h7 TD##%R##
1

?1?(r   