
    Ph{-                       d Z 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m	Z	m
Z
mZmZmZmZ ddlZddlZddlZddlmZmZmZ ddlmZmZmZ ej4                  	 	 	 	 	 	 	 	 dd       Zej4                  dd       Zej4                  dd	       Zej4                  	 	 	 	 	 	 	 	 	 	 dd
       Zej4                  	 	 	 	 	 	 dd       Zej4                  	 	 	 	 	 	 dd       Z y)zPUtilities for manipulating the onnx and onnx-script dependencies and ONNX proto.    )annotationsN)AnyListMappingSetTupleUnion)
_constants_exporter_stateserrors)	_beartype	jit_utilsregistrationc                   	 ddl }t        j                  j	                  |d|z         }t        j
                  |d       t        | t        j                  j	                  |d      t        j                  j                  i        t        j                  j	                  |d      }t        j                  j                  |      rt        j                  |       t        j
                  |       |j                  |       }	t        t        |	j                   j"                  |            D ]7  \  }
\  }}t%        ||t        j                  j	                  |d	|
 d
             9 t        t        |	j                   j&                  |            D ]7  \  }
\  }}t%        ||t        j                  j	                  |d|
 d
             9 |S # t        $ r}t        d      |d}~ww xY w)u  Export an ONNX model as a self contained ONNX test case.

    The test case contains the model and the inputs/outputs data. The directory structure
    is as follows:

    dir
    ├── test_<name>
    │   ├── model.onnx
    │   └── test_data_set_0
    │       ├── input_0.pb
    │       ├── input_1.pb
    │       ├── output_0.pb
    │       └── output_1.pb

    Args:
        model_bytes: The ONNX model in bytes.
        inputs_data: The inputs data, nested data structure of numpy.ndarray.
        outputs_data: The outputs data, nested data structure of numpy.ndarray.

    Returns:
        The path to the test case directory.
    r   Nz<Export test case to ONNX format failed: Please install ONNX.test_T)exist_ok
model.onnxtest_data_set_0input_z.pboutput_)onnxImportErrorospathjoinmakedirs_export_filer   ExportTypesPROTOBUF_FILEexistsshutilrmtreeload_model_from_string	enumeratezipgraphinputexport_dataoutput)model_bytesinputs_dataoutputs_datanamedirr   exctest_case_dirdata_set_dirprotoiinput_protor'   output_protor)   s                  pC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\torch/onnx/_internal/onnx_proto_utils.pyexport_as_test_caser7      s{   4 GGLLgn5MKK-
]L1$$22
	 77<</@AL	ww~~l#l#KK''4E#,S1B1BK-P#QKE;\VA3c?(ST $R%.s5;;3E3E|/T%U!!L&FL"'',,|wqcQTEU*VW &V 3  J
	s   G 	G GG c                   	 ddl }ddl m} t        t        j
                  j                  | d      d      5 }|j                         }ddd       t        j
                  j                  | d      }i }t        j                  t        j
                  j                  |d            }|D ]1  }	|j                  |	      }
|j                  |
      ||
j                  <   3 i }t        j                  t        j
                  j                  |d	            }|D ]1  }|j                  |      }
|j                  |
      ||
j                  <   3 ||fS # t        $ r}t        d      |d}~ww xY w# 1 sw Y   "xY w)
u  Load a self contained ONNX test case from a directory.

    The test case must contain the model and the inputs/outputs data. The directory structure
    should be as follows:

    dir
    ├── test_<name>
    │   ├── model.onnx
    │   └── test_data_set_0
    │       ├── input_0.pb
    │       ├── input_1.pb
    │       ├── output_0.pb
    │       └── output_1.pb

    Args:
        dir: The directory containing the test case.

    Returns:
        model_bytes: The ONNX model in bytes.
        inputs: the inputs data, mapping from input name to numpy.ndarray.
        outputs: the outputs data, mapping from output name to numpy.ndarray.
    r   Nnumpy_helperz<Load test case from ONNX format failed: Please install ONNX.r   rbr   z
input_*.pbzoutput_*.pb)r   r:   r   openr   r   r   readglobload_tensorto_arrayr-   )r.   r   r:   r/   fr*   test_data_dirinputsinput_files
input_filetensoroutputsoutput_filesoutput_files                 r6   load_test_caserJ   K   s:   0% 
bggll3-t	4ffh 
5 GGLL&78MF))BGGLLEFK!
!!*-*33F;v{{ " G99RWW\\-GHL#!!+.+44V< $ ''+  J
	
 
5	4s"   
E
 E'
	E$EE$'E1c                :   	 ddl m} t        |d      5 }|j                  j                  d      r;|j                  |j                  | |j                        j                                n |j                  j                  d      r:|j                  |j                  | |j                        j                                n|j                  j                  d      r:|j                  |j                  | |j                        j                                nV|j                  j                  d	      sJ |j                  |j                  | |j                        j                                ddd       y# t        $ r}t        d      |d}~ww xY w# 1 sw Y   yxY w)
a0  Export data to ONNX protobuf format.

    Args:
        data: The data to export, nested data structure of numpy.ndarray.
        value_info_proto: The ValueInfoProto of the data. The type of the ValueInfoProto
            determines how the data is stored.
        f: The file to write the data to.
    r   r9   z7Export data to ONNX format failed: Please install ONNX.Nwbmap_typesequence_typeoptional_typetensor_type)r   r:   r   r<   typeHasFieldwrite	from_dictr-   SerializeToString	from_listfrom_optional
from_array)datavalue_info_protorA   r:   r/   opened_files         r6   r(   r(   ~   sb   % 
a+  ))*5&&t-=-B-BCUUW ""++O<&&t-=-B-BCUUW ""++O<***//##% $((11-@@@''.>.C.CDVVX# 
  E
	
 
s#   E4 EF4	F=F		FFc                   |t         j                  j                  k(  rKt        |      dk(  sJ t        j
                  j                  |d      5 }|j                  |        ddd       y|t         j                  j                  t         j                  j                  hv r|t         j                  j                  k(  rt        j                  nt        j                  }t        j                  |d|      5 }|j                  t        j                   |        |j#                         D ]  \  }}|j                  ||        	 ddd       y|t         j                  j$                  k(  r_t'        |t(        j*                        st,        j.                  j1                  |      st3        dt5        |             t,        j.                  j7                  |      st-        j8                  |       t,        j.                  j;                  |t        j                         }	t        j
                  j                  |	d      5 }|j                  |        ddd       |j#                         D ]_  \  }}t,        j.                  j;                  ||      }
t        j
                  j                  |
d      5 }|j                  |       ddd       a yt3        d      # 1 sw Y   yxY w# 1 sw Y   yxY w# 1 sw Y   xY w# 1 sw Y   xY w)z4export/write model bytes into directory/protobuf/zipr   rL   Nw)compressionzQf should be directory when export_type is set to DIRECTORY, instead get type(f): zUnknown export type)r   r   r   lentorchserialization_open_file_likerS   ZIP_ARCHIVECOMPRESSED_ZIP_ARCHIVEzipfileZIP_DEFLATED
ZIP_STOREDZipFilewritestrr
   ONNX_ARCHIVE_MODEL_PROTO_NAMEitems	DIRECTORY
isinstanceioBytesIOr   r   isdir
ValueErrorrQ   r    r   r   )r*   rA   export_type
export_mapr[   r^   zkvmodel_proto_fileweight_proto_files              r6   r   r      sY    &22@@@:!###  00D9[k* :9	$$00$$;; 
 .::QQQ   ## 	
 __Q=JJz??M"((*1

1a  + >= 
(44>>	>a$BGGMM!,<cdhijdkclm  ww~~a KKN77<<:+S+ST  001A4HKk* I $$&DAq "Q 2$$44!4!!!$  ' .//E :9 >= IH
 s1   K4AK9K))K5KK&)K25K>	c                2   	 ddl }|j	                  |       }t               }t               }t        |j                  |||       |r+|j                  j                  |       |j                         } | S # t        $ r}t        j                  d      |d}~ww xY w)zAInsert model-included custom onnx-script function into ModelProtor   NzModule onnx is not installed!)r   r   r   OnnxExporterErrorr#   listset_find_onnxscript_opr&   	functionsextendrU   )r*   custom_opsetsr   emodel_protoonnx_function_listincluded_node_funcs          r6   _add_onnxscript_fnr      s    O --k:K -}>P $$%78!3351  O&&'FGQNOs   A2 2	B;BBc                0   | j                   D ]  }|j                  dz   |j                  z   }|j                  D ]'  }|j                  t        |j                  |||       ) t        j                  j                  |      }|j                  st        j                  |j                        rt        j                  |j                        rt        j                  |j                        r|||vs|j                  |j                  d      }|j                  |      }	|	@t        |	d      r2|	j                         }
|j!                  |
       |j#                  |       Yt%        j&                  |||r|j)                               d       ||fS )zYRecursively iterate ModelProto to find ONNXFunction op as it may contain control flow Op.z::N   to_function_proto)nodedomainop_type	attributegr}   r   registryget_function_groupr   is_atenis_primis_onnxgethasattrr   appendaddr   UnsupportedOperatorErrorget_min_supported)graph_protor   r   r   r   	node_kindattronnx_function_groupspecified_versiononnx_fnonnx_function_protos              r6   r}   r}      ss      KK$&5	NNDvv!#FF.?Q # +33FFyQ KK%%dkk2%%dkk2%%dkk2#/!33 - 1 1$++q A)--.?@G" 7$78*1*C*C*E'&--.AB&**9511!& $557 
  = !J 111    )r*   bytesr-   strr.   r   returnr   )r.   r   r   zTuple[bytes, Any, Any])rA   r   r   None)
r*   r   rA   zUnion[io.BytesIO, str]rr   r   rs   zMapping[str, bytes]r   r   )r*   r   r   Mapping[str, int]r   r   )r   zSet[str]r   r   r   r   )!__doc__
__future__r   r>   rn   r   r!   re   typingr   r   r   r   r   r	   r`   torch.jit._tracetorch.serialization
torch.onnxr
   r   r   torch.onnx._internalr   r   r   beartyper7   rJ   r(   r   r   r}    r   r6   <module>r      sZ   V "  	 	   8 8    ; ; C C 449<4CF44 4n /( /(d # #L .0.0.0 .0 $	.0
 
.0 .0b   $     F ,2 ,2 %,2 	,2 ,2r   