
    
NgE                     R   d 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	 ddl
mZmZmZmZmZmZmZmZ ddlmZ ddlmZ ddlZdej        v r e	ej        d         d	          anHd
ej        v r e	ej        d
         dd	          an& e	ej                            d          ddd	          a G d d          ZdeddfdZdefdZdedeeeef         fdZ dede!fdZ"d,dede!defdZ#dededdfdZ$	 	 	 d-dedee         deee                  dee         fd Z%	 d.deded!ee&         defd"Z'	 	 	 	 d/deded!ee&         d#e!d$e!deej(                 fd%Z)	 	 	 	 d/deded!ee&         d#e!d$e!dee         fd&Z*	 	 	 	 	 d0d'ed(ed)ed*ed!ee&         d#e!d$e!deej(                 fd+Z+dS )1zJONNX Model Hub

This implements the python client for the ONNX model hub.
    N)BytesIO)join)IOAnyDictListOptionalSetTuplecast)	HTTPError)urlopen	ONNX_HOMEhubXDG_CACHE_HOMEonnx~z.cachec                   J    e Zd ZdZdeeef         ddfdZdefdZdefdZ	dS )	ModelInfoaM  A class to represent a model's property and metadata in the ONNX Hub.
    It extracts model name, path, sha, tags, etc. from the passed in raw_model_info dict.

    Attributes:
        model: The name of the model.
        model_path: The path to the model, relative to the model zoo (https://github.com/onnx/models/) repo root.
        metadata: Additional metadata of the model, such as the size of the model, IO ports, etc.
        model_sha: The SHA256 digest of the model file.
        tags: A set of tags associated with the model.
        opset: The opset version of the model.
    raw_model_inforeturnNc                 T   t          t          |d                   | _        t          t          |d                   | _        t          t          t          t
          f         |d                   | _        d| _        d| j        v r%t          t          | j        d                   | _        t                      | _	        d| j        v r=t          t          t          t                   | j        d                             | _	        t          t          |d                   | _        || _        dS )zgInitializer.

        Args:
            raw_model_info: A JSON dict containing the model info.
        model
model_pathmetadataN	model_shatagsopset_version)r   strr   r   r   r   r   r   setr   r   intopsetr   )selfr   s     D/var/www/html/ai-engine/env/lib/python3.11/site-packages/onnx/hub.py__init__zModelInfo.__init__*   s     #~g677
sN<$@AA(,T#s(^^J=W(X(X(,$-''!#t}['ABBDN!ee	T]""DcDM&,ABBCCDI#~o>??
.<    c           	      H    d| j          d| j         d| j         d| j         d	S )NzModelInfo(model=z, opset=z, path=z, metadata=))r   r"   r   r   r#   s    r$   __str__zModelInfo.__str__?   s5    u$*uudjuuuueieruuuur&   c                 *    |                                  S N)r*   r)   s    r$   __repr__zModelInfo.__repr__B   s    ||~~r&   )
__name__
__module____qualname____doc__r   r   r   r%   r*   r-    r&   r$   r   r      s        
 
=tCH~ =$ = = = =*v v v v v#      r&   r   new_dirr   c                 
    | a dS )zkSets the current ONNX hub cache location.

    Args:
        new_dir: Location of new model hub cache.
    N_ONNX_HUB_DIR)r3   s    r$   set_dirr7   F   s     MMMr&   c                      t           S )znGets the current ONNX hub cache location.

    Returns:
        The location of the ONNX hub model cache.
    r5   r2   r&   r$   get_dirr9   P   s
     r&   repoc                     |                      d          d                              d          d         }|                      d          d                              d          d         }d| v r|                      d          d         }nd}|||fS )zCGets the repo owner, name and ref from a repo specification string.:r   /   main)splitr:   
repo_owner	repo_namerepo_refs       r$   _parse_repo_inforE   Y   s    C#))#..q1J

3"((--a0I
d{{::c??1%y(**r&   c                 L    t          |           \  }}}|dk    o|dk    o|dk    S )zzVerifies whether the given model repo can be trusted.
    A model repo can be trusted if it matches onnx/models:main.
    r   modelsr?   rE   rA   s       r$   _verify_repo_refrI   d   s7     '7t&<&<#J	8& VyH'<V8vCUVr&   Flfsc                 \    t          |           \  }}}|rd| d| d| dS d| d| d| dS )aT  Gets the base github url from a repo specification string.

    Args:
        repo: The location of the model repo in format
            "user/repo[:branch]". If no branch is found will default to
            "main".
        lfs: Whether the url is for downloading lfs models.

    Returns:
        The base github url for downloading.
    z*https://media.githubusercontent.com/media/r=   z"https://raw.githubusercontent.com/rH   )r:   rJ   rB   rC   rD   s        r$   _get_base_urlrL   l   sd     '7t&<&<#J	8
 a`J````U]````T
TTYTTTTTTr&   url	file_namec                 
   d}t          |           5 }t          |d          5 }	 |                    |          }|sn|                    |           .	 ddd           n# 1 swxY w Y   ddd           dS # 1 swxY w Y   dS )zDownloads the file with specified file_name from the url.

    Args:
        url: A url of download link.
        file_name: A specified file name for the downloaded file.
    i @  wbTN)r   openreadwrite)rM   rN   
chunk_sizeresponsefchunks         r$   _download_filerX      s    J	 4	4#8#8 A	MM*--E GGENNN		                                 s4   A80A A8 A$	$A8'A$	(A88A<?A<onnx/models:mainr   r   c                 .   t          |           }|dz   }	 t          |          5 }d t          j        t	          t
          t                   |                    D             }ddd           n# 1 swxY w Y   n%# t          $ r}t          d|           |d}~ww xY w|nfd|D             }||S d |D             }	g }
|D ]N}d |j	        D             }t          |	                    |                    dk    r|
                    |           O|
S )	a  Gets the list of model info consistent with a given name and tags

    Args:
        repo: The location of the model repo in format
            "user/repo[:branch]". If no branch is found will default to
            "main"
        model: The name of the model to search for. If `None`, will
            return all models with matching tags.
        tags: A list of tags to filter models by. If `None`, will return
            all models with matching name.

    Returns:
        ``ModelInfo``s.
    zONNX_HUB_MANIFEST.jsonc                 ,    g | ]}t          |          S r2   )r   ).0infos     r$   
<listcomp>zlist_models.<locals>.<listcomp>   s+     ) ) )$(	$) ) )r&   NzCould not find manifest at c                 r    g | ]3}|j                                                                         k    1|4S r2   )r   lower)r\   mr   s     r$   r^   zlist_models.<locals>.<listcomp>   s5    FFFAQW]]__%E%Ea%E%E%Er&   c                 6    h | ]}|                                 S r2   r`   r\   ts     r$   	<setcomp>zlist_models.<locals>.<setcomp>   s     ...Aaggii...r&   c                 6    h | ]}|                                 S r2   rc   rd   s     r$   rf   zlist_models.<locals>.<setcomp>   s     000Aaggii000r&   r   )rL   r   jsonloadr   r   r   r   AssertionErrorr   lenintersectionappend)r:   r   r   base_urlmanifest_urlrU   manifestematching_modelscanonical_tagsmatching_info_listra   
model_tagss    `           r$   list_modelsrv      s   & T""H66LR\"" 	h) ),0Id2c7H6M6M,N,N) ) )H	 	 	 	 	 	 	 	 	 	 	 	 	 	 	  R R RI<IIJJPQQR = 	FFFFFFF  |.....N*, ) )00000
~**:6677!;;%%a(((s:   A; =A/#A; /A33A; 6A37A; ;
BBBr"   c                     t          ||           }|st          d|            t          |d           }n3fd|D             }|s#d |D             }t          |  d d|           |d	         S )
a  Gets the model info matching the given name and opset.

    Args:
        model: The name of the onnx model in the manifest. This field is
            case-sensitive
        repo: The location of the model repo in format
            "user/repo[:branch]". If no branch is found will default to
            "main"
        opset: The opset of the model to get. The default of `None` will
            return the model with largest opset.

    Returns:
        ``ModelInfo``.
    zNo models found with name Nc                     | j          S r,   r"   )ra   s    r$   <lambda>z get_model_info.<locals>.<lambda>   s
     r&   )keyc                 *    g | ]}|j         k    |S r2   ry   )r\   ra   r"   s     r$   r^   z"get_model_info.<locals>.<listcomp>   s%    JJJE9I9I19I9I9Ir&   c                     g | ]	}|j         
S r2   ry   )r\   ra   s     r$   r^   z"get_model_info.<locals>.<listcomp>   s    ===AG===r&   z has no version with opset z. Valid opsets: r   )rv   rj   sorted)r   r:   r"   rr   selected_modelsvalid_opsetss     `   r$   get_model_infor      s    " "$..O CA%AABBB} 6H6HIIIJJJJoJJJ 	==_===L ZZUZZLZZ   1r&   force_reloadsilentc           	         t          | ||          }|j                            d          }|j        |j         d|d          |d<   t	          t
          t          j                            |                    }|st          j        	                    |          st          |          sX|sVd| d}t          |t          j                   t          d           t                                                      d	k    rdS t          j        t          j                            |          d
           t%          |d
          }	t          d|  d|            t'          |	|j        z   |           nt          d|  d|            t)          |d          5 }
|
                                }ddd           n# 1 swxY w Y   |j        Tt-          j        |                                          }||j        k    s#t3          d|j         d| d|j         d          t7          j        t;          t<          t>                   tA          |                              S )a  Downloads a model by name from the onnx model hub.

    Args:
        model: The name of the onnx model in the manifest. This field is
            case-sensitive
        repo: The location of the model repo in format
            "user/repo[:branch]". If no branch is found will default to
            "main"
        opset: The opset of the model to download. The default of `None`
            automatically chooses the largest opset
        force_reload: Whether to force the model to re-download even if
            its already found in the cache
        silent: Whether to suppress the warning message if the repo is
            not trusted.

    Returns:
        ModelProto or None
    r=   N_The model repo specification _ is not trusted and may contain security vulnerabilities. Only continue if you trust this repo.fileContinue?[y/n]yTexist_okDownloading  to local path Using cached  model from rbThe cached model  has SHA256  while checksum should be h. The model in the hub may have been updated. Use force_reload to download the model from the model hub.)!r   r   r@   r   r   r6   osseppathexistsrI   printsysstderrinputr`   makedirsdirnamerL   rX   rQ   rR   hashlibsha256	hexdigestrj   r   r   ri   r   r   bytesr   )r   r:   r"   r   r   selected_modellocal_model_path_arrlocal_model_pathmsglfs_urlrV   model_bytesdownloaded_shas                r$   ri   ri      s   2 $E477N)4::3??+ 'DD*>r*BDD 		
 M26;;7K+L+LMM E27>>*:;; E%% 	f 	 X$  X  X  XC#CJ''''"###ww}}#%%t
BGOO$455EEEEd++EUEE3CEEFFFw!::<LMMMMCeCC1ACCDDD		%	% ffhh               + 44>>@@!999 9N$8 9 9n 9 9,:,D9 9 9   9T"U)W[%9%9::;;;s   F99F= F=c           	      8   t          | ||          }|j        d                             d          }|j        d         }|| d|d          |d<   t          t          t
          j                            |                    }|st
          j                            |          st          |          sX|sVd| d}	t          |	t          j        	           t          d
           t                                                      dk    rdS t          j        t
          j                            |          d           t#          |d          }
t          d|  d|            t%          |
|j        d         z   |           nt          d|  d|            t'          |d          5 }|                                }ddd           n# 1 swxY w Y   |Jt+          j        |                                          }||k    st1          d|j         d| d| d          t5          j        |          5 }|dt7          |          dz
           }|                    |           ddd           n# 1 swxY w Y   |dz   t          j        |          d         z   }|S )a   Downloads a model along with test data by name from the onnx model hub and returns the directory to which the files have been extracted.

    Args:
        model: The name of the onnx model in the manifest. This field is
            case-sensitive
        repo: The location of the model repo in format
            "user/repo[:branch]". If no branch is found will default to
            "main"
        opset: The opset of the model to download. The default of `None`
            automatically chooses the largest opset
        force_reload: Whether to force the model to re-download even if
            its already found in the cache
        silent: Whether to suppress the warning message if the repo is
            not trusted.

    Returns:
        str or None
    model_with_data_pathr=   model_with_data_shaNr   r   r   r   r   r   r   Tr   r   r   r   r   r   r   r   r   r   r      )r   r   r@   r   r6   r   r   r   r   rI   r   r   r   r   r`   r   r   rL   rX   rQ   rR   r   r   r   rj   r   tarfilerk   
extractalllistdir)r   r:   r"   r   r   r   local_model_with_data_path_arrr   local_model_with_data_pathr   r   rV   model_with_data_bytesr   model_with_data_zippedlocal_model_with_data_dir_pathr   s                    r$   download_model_with_test_datar   #  s   2 $E477N%3%<&eCjj # )12GH& #II%CB%GII 	'	
 "&rv{{#ABB" "  O27>>*DEE O%% 	f 	 X$  X  X  XC#CJ''''"###ww}}#%%t
BGOO$>??$OOOOd++OUOO3MOOPPPn-.DEE&	
 	
 	
 	

 	MeMM1KMMNNN	($	/	/ )1 !) ) ) ) ) ) ) ) ) ) ) ) ) ) ) & (=>>HHJJ!444 9N$8 9 9n 9 9,?9 9 9   
0	1	1 J5K)C.//!33*
& 	))*HIIIJ J J J J J J J J J J J J J J 	'
	
*3
4
4Q
7	8   s$   'GGG30I//I36I3network_modelpreprocessing_modelnetwork_repopreprocessing_repoc                 j   t          |||||          }|t          d|           t          | ||||          }|t          d|            t                      }	i }
i }|j        D ]5}|j        dk    rdn|j        }|	                    |           |j        |
|<   6|j        D ]5}|j        dk    rdn|j        }|	                    |           |j        ||<   6d}d}|	D ]^}|dk    r||         }|
|         }||v rA||
v r=||         ||         k    r+t          d| d|  d	| d
||          d|
|          d          _||k    rLt          j	        
                    ||          }|j        |_        t          j                            |           nQ||k    rKt          j	        
                    ||          }|j        |_        t          j                            |           d t          |j        j        |j        j                  D             }t          j                            |||          }|S )a  Builds a composite model including data preprocessing by downloading a network and a preprocessing model
    and combine it into a single model

    Args:
        network_model: The name of the onnx model in the manifest.
        preprocessing_model: The name of the preprocessing model.
        network_repo: The location of the model repo in format
            "user/repo[:branch]". If no branch is found will default to
            "main"
        preprocessing_repo: The location of the proprocessing model repo in format
            "user/repo[:branch]". If no branch is found will default to
            "main"
        opset: The opset of the model to download. The default of `None`
            automatically chooses the largest opset
        force_reload: Whether to force the model to re-download even if
            its already found in the cache
        silent: Whether to suppress the warning message if the repo is
            not trusted.

    Returns:
        ModelProto or None
    Nz(Could not load the preprocessing model: z"Could not load the network model:  zai.onnxr   zCan not merge z and z: because they contain different opset versions for domain z (z) and z\). Only the default domain can be automatically converted to the highest version of the two.c                 0    g | ]\  }}|j         |j         fS r2   )name)r\   	out_entryin_entrys      r$   r^   z(load_composite_model.<locals>.<listcomp>  s5       Ix 
'  r&   )io_map)ri   RuntimeErrorr    opset_importdomainaddversion
ValueErrorr   version_converterconvert_version
ir_versioncheckercheck_modelzipgraphoutputr   composemerge_models)r   r   r   r   r"   r   r   preprocessingnetworkall_domainsdomains_to_version_network domains_to_version_preprocessingopset_import_entryr   preprocessing_opset_versionnetwork_opset_versionr   model_with_preprocessings                     r$   load_composite_modelr   {  s"   > /f M L7JLL
 
 	
 =,|VLLGOOOPPPEEK1379$%2 H H+2b88II>P>W 	 	-?-G"6**+8 N N+2b88II>P>W 	 	3E3M(00"$  Y*J6*R'$>v$F!!66644408/78 8 M!4 M M= M M7=M MAabhAiM M1&9M M M   #%:::(880
 
 +5  ))))	!<	<	<.>>0
 
 $+#5   /// #&}':'A7=CV#W#W  F
  $|88wv  9     $#r&   )F)rY   NN)rY   N)rY   NFF)rY   rY   NFF),r1   r   rh   r   r   r   ior   os.pathr   typingr   r   r   r   r	   r
   r   r   urllib.errorr   urllib.requestr   r   environr6   r   
expanduserr   r   r7   r9   rE   boolrI   rL   rX   rv   r!   r   
ModelProtori   r   r   r2   r&   r$   <module>r      sr      				 



              B B B B B B B B B B B B B B B B B B B B " " " " " " " " " " " " "*DK0%88MM##D$45vuEEMMD++C00(FEJJM& & & & & & & &RS T        +3 +5c3#7 + + + +W3 W4 W W W WU U U$ U3 U U U U&      $ # $. .
.C=. 49
. 
)_	. . . .d HL 7?}   F #>< ><><
>< C=>< 	><
 >< do>< >< >< ><F #U  U U 
U  C=U  	U 
 U  c]U  U  U  U v +0c$ c$c$c$ c$ 	c$
 C=c$ c$ c$ doc$ c$ c$ c$ c$ c$r&   