
    SiK                    .   S SK Jr  S SKrS SKrS SKrS SKrS SKrS SKrS SKJ	r	  S SK
JrJr  S SKJr  S SKJs  Jr  S SKJrJrJrJrJr  \(       a  S SKJrJr  \" 1 Sk5      r\" \5      rSr S	r! " S
 S5      r"        S S jr#SS.         S!S jjr$S"S jr%S#S jr&    S$             S%S jjr'    S&           S'S jjr(S(S jr)S)S jr*S*S jr+      S+S jr,S,S jr-S*S jr.    S-S jr/S*S jr0S.S jr1S/S jr2S0S jr3S1S jr4g)2    )annotationsN)chain)IOTYPE_CHECKING)AttributeProtoFunctionProto
GraphProto
ModelProtoTensorProto)CallableIterable>   lengthoffsetbasepathchecksumlocation
   d   c                      \ rS rSrSS jrSrg)ExternalDataInfo2   c                   SU l         S U l        S U l        S U l        SU l        [        5       nSnUR                   H  nUR                  [        ;   a"  [        XR                  UR                  5        M9  US-  n[        U5      [        :  d  MS  UR                  S [         n[        UR                  5      [        :  a  US-  nUR                  U5        M     U(       a`  [        U5      nU[        U5      -
  n[!        U5      nUS:  a	  USU S3-  n["        R$                  " SU SUR&                  < S	[(         3S
S9  U R                  bP  [+        U R                  5      U l        U R                  S:  a&  [-        SU R                   SUR&                  < 35      eU R                  bQ  [+        U R                  5      U l        U R                  S:  a&  [-        SU R                   SUR&                  < 35      eg g )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)	selftensorunknown_keysunknown_key_countentry	truncatedshownextrakey_lists	            X/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/onnx/external_data_helper.py__init__ExternalDataInfo.__init__3   s   !$))Eyy77ii5!Q&!|$'CC %		*B+B CI599~(??!U*	 $$Y/ * <(E%E
2EE{HqyeE7%00MM8
 C$kk_ -!!5 68 	 ;;"dkk*DK{{Q Edkk] S""(++2 
 ;;"dkk*DK{{Q Edkk] S""(++2   #    )r   r   r   r   r   N)r0   r   returnNone)__name__
__module____qualname____firstlineno__r9   __static_attributes__ r;   r8   r   r   2   s    0r;   r   c           
        [         R                  " U R                  5       5      R                  nUR                  bJ  UR                  U:  a  [        SUR                   SU SU< 35      eU R                  UR                  5        UR                  bl  UR                  b  UR                  OSnX4-
  nUR                  U:  a"  [        SUR                   SU SU SU< 35      eU R                  UR                  5      $ U R                  5       $ )zValidate 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.
z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   r.   seekr   read)	data_fileinfotensor_name	file_size
read_start	availables         r8   #_validate_external_data_file_boundsrQ   f   s    ))+,44I{{;;"( 6;mK?<  	t{{#{{$(KK$;T[[
*	;;"( 6;1* >)_. 
 ~~dkk**>>r;   Tcheck_existsc          	        [         R                  R                  U 5      n[         R                  R                  U5      nUR                  U[         R                  -   5      (       d(  XT:w  a#  [
        R                  " SU< SU< SU< S35      e[         R                  R                  U5      (       a  [
        R                  " SU< SU< S35      eU(       ag  [         R                  R                  U5      (       aC  [         R                  " U5      R                  S:  a  [
        R                  " SU< SU< S35      eU$ )	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.)rE   pathrealpath
startswithseponnx_checkerValidationErrorislinkexistsstatst_nlink)base_dir	data_pathrM   rS   	real_base	real_paths         r8   _validate_external_data_pathre      s#   6   *I  +I	BFF 233	8N**k_$DmA)aQ
 	
 
ww~~i  **k_$8 FM N
 	
 y11bggi6H6Q6QTU6U**k_$8 FR S
 	
 r;   c                   [        U 5      n[        R                  " XR                  U R                  5      n[
        R                  n[        [
        S5      (       a  U[
        R                  -  n[
        R                  " X45      n[
        R                  " US5       n[        XbU R                  5      U l        SSS5        g! , (       d  f       g= f)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+   rE   O_RDONLYhasattrrg   openfdopenrQ   raw_data)r0   ra   rL   external_data_file_path
open_flagsfdrK   s          r8   load_external_data_for_tensorrs      s     F#D'GG-- Jr<  bmm#
	(	5B	2t		=V[[
 
		s   C
Cc                    [        U 5       HD  n[        U5      (       d  M  [        X!5        [        R                  Ul        UR                  SS2	 MF     g)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   )modelra   r0   s      r8   load_external_data_for_modelrz      sB     #5)f%%)&;#.#6#6F $$Q' *r;   c                   U R                  S5      (       d  [        SU R                  -   S-   5      eU R                  S S 2	 [        R
                  U l        UUb  [        U5      OS Ub  [        U5      OS UUS.R                  5        H:  u  pgUc  M
  U R                  R                  5       nXhl
        [        U5      Ul        M<     g )Nro   rU   zH does not have raw_data field. Cannot set external data for this tensor.)r   r   r   r   r   )HasFieldr.   r+   r   r   EXTERNALrx   r-   itemsr&   r   strr"   )	r0   r   r   r   r   r   kvr3   s	            r8   set_external_datar      s     ??:&&kkXY
 	
 	Q&//F!'!3#f+!'!3#f+ eg =((,,.EIa&EKr;   c                "   [        U 5      nU(       a  [        U 5      nU(       a  [        [        R                  " 5       5      S-   nU(       ad  [
        R                  R                  U5      (       a  [        S5      e[
        R                  R                  U5      (       a  [        SU S35      eUnU HL  nUR                  S5      (       d  M  [        R                  " UR                  5      U:  d  MA  [        Xv5        MN     gU H  nUR                  S5      (       d  M  [        R                  " UR                  5      U:  d  MA  UR                   n[#        U5      (       d  [        [        R                  " 5       5      n[        Xx5        M     g)aN  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 rV   ro   N)_get_initializer_tensorsru   r   uuiduuid1rE   rW   isabsr.   r^   FileExistsErrorr|   sys	getsizeofro   r   r+   _is_valid_filename)	ry   all_tensors_to_one_filer   size_thresholdconvert_attributetensors	file_namer0   tensor_locations	            r8   convert_model_to_external_datar      s   4 'u-G"5)

%/	ww}}X&& Z  ww~~h''%(EhZq&QRR IF
++MM&//2nD!&4  F
++MM&//2nD"(++)/::&)$**,&7O!&: r;   c                    [        U 5       HZ  n[        U5      (       d  M  UR                  S5      (       d  [        S5      eUR                  SS2	 [
        R                  Ul        M\     g)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)ru   rv   r|   r.   r   r   rw   rx   )ry   r0   s     r8    convert_model_from_external_datar   9  sU     #5)f%%??:.. !@AA$$Q'#.#6#6F  *r;   c           	        [        U 5      n[        R                  " UR                  5      nUR	                  5       (       a6  [
        R                  " SU R                  < SUR                  < SU< 35      eSUR                  ;   a7  [
        R                  " SU R                  < SU< SUR                  < S35      eUR                  S;   a3  [
        R                  " SU R                  < S	UR                  < S
35      e[        R                  R                  XR                  5      n[        XU R                  SS9  U R                  S5      (       d  [
        R                  " S5      e[        R                  [        R                  -  n[!        [        S5      (       a  U[        R"                  -  n[        R$                  " XES5      n[        R&                  " US5       nUR)                  SS5        UR*                  b\  UR-                  5       nUR*                  U:  a!  UR/                  SUR*                  U-
  -  5        UR)                  UR*                  5        UR-                  5       n	UR/                  U R0                  5        [3        XR                  XR-                  5       U	-
  5        SSS5        g! , (       d  f       g= f)az  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.
rU   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 rV   )rV   r   z is external and its name z is invalid.TrR   ro   r   rg   i  zr+br   r   N    )r   pathlibPathr   is_absoluter[   r\   r+   partsrE   rW   joinre   r|   O_CREATO_RDWRrl   rg   rm   rn   rI   r   tellwritero   r   )
r0   	base_pathrL   location_pathrp   rq   rr   rK   rN   r   s
             r8   save_external_datar   I  s8    F#D LL/M  ""**fkk_ %--1]],= >"'
 	

 }"""**fkk_$Nm3DMM3DAG
 	
 [(**fkk_$>}}|-
 	

 !ggll9mmD !FKKd
 ??:&&**+JKK bii'Jr<  bmm#
	(e	<B 
2u	q!;;"!(I{{Y&y)@ ABNN4;;'!(&--9IF9RS 
		s   "CJ99
Kc                >    [        [        U 5      [        U 5      5      $ )z=Scan an ONNX model for all tensors and return as an iterator.)r   r   _get_attribute_tensorsonnx_model_protos    r8   ru   ru     s!     !12/0 r;   c              #    #    U R                   [        R                  :X  a  U" U R                  5       Sh  vN   U R                   [        R                  :X  a$  U R
                   H  nU" U5       Sh  vN   M     gg NG N7f)zICreate an iterator through processing ONNX model attributes with functor.N)typer   GRAPHgGRAPHSgraphs)	attributefuncgraphs      r8   _recursive_attribute_processorr     si      ~~---	$$$~~...%%EE{"" & / 	% #s!   4BA><B3B 4B Bc             #     #    U R                    Sh  vN   U R                   H.  nUR                   H  n[        U[        5       Sh  vN   M     M0     g NC N7f)z@Create an iterator of initializer tensors from ONNX model graph.N)initializernoder   r   #_get_initializer_tensors_from_graph)r   r   r   s      r8   r   r     sR         

I5>   (  !s!   AA5AA	AAc              #  J   #    [        U R                  5       Sh  vN   g N7f)z:Create an iterator of initializer tensors from ONNX model.N)r   r   r   s    r8   r   r     s     23C3I3IJJJs   #!#c             #     #    U R                    Hf  nUR                   HS  nUR                  S5      (       a  UR                  v   UR                   Sh  vN   [        U[        5       Sh  vN   MU     Mh     g N% N7f)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)graph_or_functionr   r   s      r8   r   r     sq      "&&I!!#&&kk! ((((5<  	 ( ' )s$   AA>A:A>,A<-A><A>c              #     #    [        U R                  5       Sh  vN   U R                   H  n[        U5       Sh  vN   M     g N+ N7f)zDCreate an iterator of tensors from node attributes of an ONNX model.N)r   r   	functions)r   functions     r8   r   r     sA     01A1G1GHHH$..4X>>> / I>s   AA!AA	
A	Ac                f    [         R                  " S5      nUR                  U 5      n[        U5      $ )z8Utility to check whether the provided filename is valid.z^[^<>:;,?"*|/]+$)recompilematchbool)filenameexpr   s      r8   r   r     s)    
**'
(CIIhE;r;   c                l    U R                  S5      =(       a    U R                  [        R                  :H  $ )z?Returns true if the tensor stores data in an external location.rx   )r|   rx   r   r}   )r0   s    r8   rv   rv     s.     	( 	9  K$8$88r;   c                ~    [        U R                  5       H$  u  p#UR                  U:X  d  M  U R                  U	 M&     g)zRemoves 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   )r0   	field_keyifields       r8   remove_external_data_fieldr     s5     f22399	!$$Q' 4r;   c                    [        U 5       HI  n[        U5      (       d  M  UR                  S5      (       d  M-  [        X!5        UR	                  S5        MK     U $ )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   )ru   rv   r|   r   
ClearField)ry   filepathr0   s      r8   write_external_data_tensorsr     sK     #5)
 f%%&//**E*Ev0j) * Lr;   )rK   z	IO[bytes]rL   r   rM   r   r<   bytes)
ra   r   rb   r   rM   r   rS   r   r<   r   )r0   r   ra   r   r<   r=   )ry   r
   ra   r   r<   r=   )NNNN)r0   r   r   r   r   
int | Noner   r   r   
str | Noner   r   r<   r=   )TNi   F)ry   r
   r   r   r   r   r   r-   r   r   r<   r=   )ry   r
   r<   r=   )r0   r   r   r   r<   r=   )r   r
   r<   Iterable[TensorProto])r   r   r   z-Callable[[GraphProto], Iterable[TensorProto]]r<   r   )r   r	   r<   r   )r   zGraphProto | FunctionProtor<   r   )r   r   r<   r   )r0   r   r<   r   )r0   r   r   r   r<   r=   )ry   r
   r   r   r<   r
   )5
__future__r   rE   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   rQ   re   rs   rz   r   r   r   r   ru   r   r   r   r   r   r   rv   r   r   rC   r;   r8   <module>r      s   # 	  	 
    $ # 3 3  2  (<  9: !  1 1h  
    	 P ,,, ,
 , 	,^
2(& !!! ! 	!
 ! ! 
!@ %)#7;7;!7; 7; 	7;
 7; 
7;t7 ?TD##%R##K
1?(r;   