
    /jK                       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Zd dlm	Z	 d dl
mZmZ d dlmZ d dlmc mZ d dlmZmZmZmZmZ erd dlmZmZ  eh d          Z ee          ZdZ d	Z! G d
 d          Z"dKdZ#dddLdZ$dMdZ%dNd!Z&	 	 	 	 dOdPd)Z'	 	 	 	 dQdRd0Z(dSd1Z)dTd3Z*dUd6Z+dVd;Z,dWd>Z-dUd?Z.dXdBZ/dUdCZ0dYdEZ1dZdFZ2d[dHZ3d\dJZ4dS )]    )annotationsN)chain)IOTYPE_CHECKING)AttributeProtoFunctionProto
GraphProto
ModelProtoTensorProto)CallableIterable>   lengthoffsetbasepathchecksumlocation
   d   c                      e Zd ZddZdS )ExternalDataInfotensorr   returnNonec                   d| _         d | _        d | _        d | _        d| _        t                      }d}|j        D ]}|j        t          v rt          | |j        |j
                   ,|dz  }t          |          t          k     rK|j        d t                   }t          |j                  t          k    r|dz  }|                    |           |rht          |          }|t          |          z
  }t!          |          }|dk    r	|d| dz  }t#          j        d| d|j        d	t(           d
           | j        Ct+          | j                  | _        | j        dk     rt-          d| j         d|j                  | j        Ct+          | j                  | _        | j        dk     r!t-          d| j         d|j                  d S d S )N r      z...z and z morez&Ignoring unknown external data key(s) z for tensor z. Allowed keys:    )
stacklevelz/External data offset must be non-negative, got z/External data length must be non-negative, got )r   r   r   r   r   setexternal_datakey_ALLOWED_EXTERNAL_DATA_KEYSsetattrvaluelen_MAX_UNKNOWN_KEYS_IN_WARNING_MAX_KEY_DISPLAY_LENGTHaddsortedreprwarningswarnname_SORTED_ALLOWED_KEYSint
ValueError)	selfr   unknown_keysunknown_key_countentry	truncatedshownextrakey_lists	            ^/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/onnx/external_data_helper.py__init__zExternalDataInfo.__init__3   s-   !$) 
	0 
	0Ey777ei5555!Q&!|$$'CCC %	*B+B*B CI59~~(???!U*	 $$Y/// 	<((E%E

2EE{{Hqyy0E0000M8 8 8$k8 8!58 8 	    ;"dk**DK{Q 2dk 2 2"(+2 2  
 ;"dk**DK{Q 2dk 2 2"(+2 2   #"    N)r   r   r   r   )__name__
__module____qualname__r:    r;   r9   r   r   2   s(        0 0 0 0 0 0r;   r   	data_file	IO[bytes]infotensor_namestrr   bytesc           
        t          j        |                                           j        }|j        B|j        |k    rt          d|j         d| d|          |                     |j                   |j        Z|j        |j        nd}||z
  }|j        |k    r t          d|j         d| d| d|          |                     |j                  S |                                 S )	a  Validate offset/length against actual file size and read data.

    Layer 3 defense-in-depth (CWE-400): prevents memory exhaustion even if the
    model was crafted via direct protobuf APIs that bypass Python parsing.

    Returns the raw bytes read from the file.
    NzExternal data offset (z) exceeds file size (z) for tensor r   zExternal data length (z) exceeds available data (z bytes from offset )	osfstatfilenost_sizer   r0   seekr   read)r@   rB   rC   	file_size
read_start	availables         r9   #_validate_external_data_file_boundsrP   f   s/    ))++,,4I{;""< < << <,7< <   	t{###{$(K$;T[[

*	;"". . .. .2<. .). .  
 ~~dk***>>r;   Tcheck_existsbase_dir	data_pathrR   boolc          	     4   t           j                            |           }t           j                            |          }|                    |t           j        z             s$||k    rt          j        d|d|d|d          t           j                            |          rt          j        d|d|d          |rWt           j                            |          r8t          j	        |          j
        dk    rt          j        d|d|d          |S )	u   Validate that an external data path is safe to open.

    Performs three security checks:
    1. Canonical path containment — resolved path must stay within base_dir.
    2. Symlink rejection — final-component symlinks are not allowed.
    3. Hardlink count — files with multiple hard links are rejected.

    Args:
        base_dir: The model base directory that data_path must be contained in.
        data_path: The external data file path to validate.
        tensor_name: Tensor name for error messages.
        check_exists: If True (default), check hardlink count. Set to False
            for save-side paths where the file may not exist yet.

    Returns:
        The validated data_path (unchanged).

    Raises:
        onnx.checker.ValidationError: If any security check fails.
    Tensor z  external data path resolves to z& which is outside the model directory .z external data path z? is a symbolic link, which is not allowed for security reasons.r   zD has multiple hard links, which is not allowed for security reasons.)rG   pathrealpath
startswithseponnx_checkerValidationErrorislinkexistsstatst_nlink)rS   rT   rC   rR   	real_base	real_paths         r9   _validate_external_data_pathre      ss   6   **I  ++I	BF 233 
	Y8N8N*Qk Q QQ QBKQ Q Q
 
 	
 
w~~i   
*Nk N N N N N
 
 	
  
y11 
bgi6H6H6QTU6U6U*Sk S S S S S
 
 	
 r;   r   r   r   c                   t          |           }t          j        ||j        | j                  }t
          j        }t          t
          d          r|t
          j        z  }t          j	        ||          }t          j
        |d          5 }t          ||| j                  | _        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.
    
O_NOFOLLOWrbN)r   	c_checker_resolve_external_data_locationr   r-   rG   O_RDONLYhasattrrg   openfdopenrP   raw_data)r   rS   rB   external_data_file_path
open_flagsfdr@   s          r9   load_external_data_for_tensorrs      s     F##D'G$-  Jr<   $bm#
	(*	5	5B	2t		 
	=tV[
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
s   
B33B7:B7modelr
   c                    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_datars   r   DEFAULTdata_locationr    )rt   rS   r   s      r9   load_external_data_for_modelrz      s`     #5)) ( (f%% 	()&(;;;#.#6F $QQQ'( (r;   r   r   
int | Noner   r   
str | Noner   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 )Nro   rW   zH does not have raw_data field. Cannot set external data for this tensor.)r   r   r   r   r   )HasFieldr0   r-   r    r   EXTERNALry   r/   itemsr(   r!   rD   r$   )	r   r   r   r   r   r   kvr4   s	            r9   set_external_datar      s     ??:&& 
kXY
 
 	
 	QQQ&/F!'!3#f+++!'!3#f+++  egg
! 
!1 =(,,..EEIa&&EK
! 
!r;      Fall_tensors_to_one_filesize_thresholdr/   convert_attributec                   t          |           }|rt          |           }|rt          t          j                              dz   }|rbt
          j                            |          rt          d          t
          j        	                    |          rt          d| 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

    Raise:
        ValueError: If location is not a relative path.
        FileExistsError: If a file already exists in location.
    z.datazDlocation must be a relative path that is relative to the model path.zExternal data file exists in rX   ro   N)_get_initializer_tensorsrv   rD   uuiduuid1rG   rY   isabsr0   r`   FileExistsErrorr~   sys	getsizeofro   r   r-   _is_valid_filename)	rt   r   r   r   r   tensors	file_namer   tensor_locations	            r9   convert_model_to_external_datar      s   4 'u--G *"5)) ;
%%/	 	!w}}X&&  Z   w~~h'' S%&Qh&Q&Q&QRRR 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.
    ro   raw_data field doesn't exist.N)rv   rw   r~   r0   r    r   rx   ry   )rt   r   s     r9    convert_model_from_external_datar   9  st     #5)) 7 7f%% 	7??:.. B !@AAA$QQQ'#.#6F 7 7r;   	base_pathc           	        t          |           }t          j        |j                  }|                                r't          j        d| j        d|j        d|          d|j        v r(t          j        d| j        d|d|j        d          |j        dv r%t          j        d| j        d	|j        d
          t          j
                            ||j                  }t          ||| j        d           |                     d          st          j        d          t          j        t          j        z  }t!          t          d          r|t          j        z  }t          j        ||d          }t          j        |d          5 }|                    dd           |j        Y|                                }|j        |k    r |                    d|j        |z
  z             |                    |j                   |                                }	|                    | j                   t3          | |j        |	|                                |	z
             ddd           dS # 1 swxY w Y   dS )a  Writes tensor data to an external file according to information in the `external_data` field.
    The function checks the external is a valid name and located in folder `base_path`.

    Arguments:
        tensor (TensorProto): Tensor object to be serialized
        base_path: System path of a folder where tensor data is to be stored

    Raises:
        ValueError: If the external file is invalid.
    rW   zC is external and must not be defined with an absolute path such as z, base_path=..z* is external and must be placed in folder z, '..' is not needed in rX   )rX   r   z is external and its name z is invalid.TrQ   ro   r   rg   i  zr+br   r   N    )r   pathlibPathr   is_absoluter]   r^   r-   partsrG   rY   joinre   r~   O_CREATO_RDWRrl   rg   rm   rn   rK   r   tellwritero   r   )
r   r   rB   location_pathrp   rq   rr   r@   rM   r   s
             r9   save_external_datar   I  s    F##D L//M  "" 
*'fk ' '-1]' '"' '
 
 	

 }"""*Gfk G GG G48MG G G
 
 	
 [((*-fk - -}- - -
 
 	

 !gll9dmDD !*FKd   
 ??:&& L*+JKKK bi'Jr<   $bm#
	(*e	<	<B 
2u		 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   CI//I36I3onnx_model_protoIterable[TensorProto]c                V    t          t          |           t          |                     S )z=Scan an ONNX model for all tensors and return as an iterator.)r   r   _get_attribute_tensorsr   s    r9   rv   rv     s,     !122/00  r;   	attributer   func-Callable[[GraphProto], Iterable[TensorProto]]c              #     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)r   r   graphs      r9   _recursive_attribute_processorr     s       ~---4	$$$$$$$$$~...% 	# 	#EtE{{"""""""" /.	# 	#r;   r   r	   c             #     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noder   r   #_get_initializer_tensors_from_graph)r   r   r   s      r9   r   r     s              
   	 	I5>         	 r;   c              #  >   K   t          | j                  E d{V  dS )z:Create an iterator of initializer tensors from ONNX model.N)r   r   r   s    r9   r   r     s0      23C3IJJJJJJJJJJJr;   graph_or_functionGraphProto | FunctionProtoc             #     K   | j         D ]R}|j        D ]H}|                    d          r	|j        V  |j        E d{V  t          |t                    E d{V  ISdS )zSCreate an iterator of tensors from node attributes of an ONNX model graph/function.tN)r   r   r~   r   r   r   !_get_attribute_tensors_from_graph)r   r   r   s      r9   r   r     s       "&   	 	I!!#&& "k!!! ((((((((5<         		 r;   c              #  |   K   t          | j                  E d{V  | j        D ]}t          |          E d{V  dS )zDCreate an iterator of tensors from node attributes of an ONNX model.N)r   r   	functions)r   functions     r9   r   r     si      01A1GHHHHHHHHH$. ? ?4X>>>>>>>>>>? ?r;   filenamec                r    t          j        d          }|                    |           }t          |          S )z8Utility to check whether the provided filename is valid.z^[^<>:;,?"*|/]+$)recompilematchrU   )r   expr   s      r9   r   r     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.ry   )r~   ry   r   r   )r   s    r9   rw   rw     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       r9   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.
    ro   )rv   rw   r~   r   
ClearField)rt   r   r   s      r9   write_external_data_tensorsr     sj     #5)) * *
 f%% 	*&//**E*E 	*vx000j)))Lr;   )r@   rA   rB   r   rC   rD   r   rE   )
rS   rD   rT   rD   rC   rD   rR   rU   r   rD   )r   r   rS   rD   r   r   )rt   r
   rS   rD   r   r   )NNNN)r   r   r   rD   r   r{   r   r{   r   r|   r   r|   r   r   )TNr   F)rt   r
   r   rU   r   r|   r   r/   r   rU   r   r   )rt   r
   r   r   )r   r   r   rD   r   r   )r   r
   r   r   )r   r   r   r   r   r   )r   r	   r   r   )r   r   r   r   )r   rD   r   rU   )r   r   r   rU   )r   r   r   rD   r   r   )rt   r
   r   rD   r   r
   )5
__future__r   rG   r   r   r   r   r+   	itertoolsr   typingr   r   onnx.checkercheckerr]   onnx.onnx_cpp2py_export.checkeronnx_cpp2py_exportri   onnx.onnx_pbr   r   r	   r
   r   collections.abcr   r   	frozensetr"   r)   r.   r&   r'   r   rP   re   rs   rz   r   r   r   r   rv   r   r   r   r   r   r   rw   r   r   r?   r;   r9   <module>r      s'   # " " " " " 				  				 



         $ $ $ $ $ $ $ $ # # # # # # 3 3 3 3 3 3 3 3 3               322222222  (i<<<   v9:: !  1 1 1 1 1 1 1 1h       P , , , , , ,^
 
 
 
2( ( ( (& ! ! ! ! !@ %)#7; 7; 7; 7; 7;t7 7 7 7 ?T ?T ?T ?TD   # # # #   K K K K
   ? ? ? ?      ( ( ( (     r;   