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

This implements the python client for the ONNX model hub.
    )join)urlopen)	HTTPErrorN)BytesIO)ListOptionalDictAnyTuplecastSetIOZ	ONNX_HOMEZhubZXDG_CACHE_HOMEonnx~z.cachec                   @   sF   e Zd ZdZdeeef ddfddZdefddZdefd	d
Z	dS )	ModelInfoaR  
    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                 C   s   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 rCtt t
t | jd | _	t t|d | _|| _dS )z`
        Parameters:
            raw_model_info: A JSON dict containing the model info.
        model
model_pathmetadataN	model_shatagsZopset_version)r   strr   r   r   r	   r   r   setr   r   intopsetr   )selfr    r   8D:\Projects\ConvertPro\env\Lib\site-packages\onnx/hub.py__init__'   s   


zModelInfo.__init__c                 C   s   d | j| j| j| jS )Nz3ModelInfo(model={}, opset={}, path={}, metadata={}))formatr   r   r   r   r   r   r   r   __str__;   s   zModelInfo.__str__c                 C   s   |   S N)r"   r!   r   r   r   __repr__@   s   zModelInfo.__repr__)
__name__
__module____qualname____doc__r   r   r	   r   r"   r$   r   r   r   r   r      s
    r   new_dirr   c                 C   s   | a dS )zg
    Sets the current ONNX hub cache location

    :param new_dir: location of new model hub cache
    N_ONNX_HUB_DIR)r)   r   r   r   set_dirD   s   r,   c                   C   s   t S )zi
    Gets the current ONNX hub cache location

    :return: The location of the ONNX hub model cache
    r*   r   r   r   r   get_dirN   s   r-   repoc                 C   sV   |  dd }|  dd  dd }d| v r$|  dd  dd }nd}|||fS )zM
    Gets the repo owner, name and ref from a repo specification string.
    /r      :main)splitr.   
repo_owner	repo_namerepo_refr   r   r   _parse_repo_infoW   s   
r8   c                 C   s&   t | \}}}|dko|dko|dkS )z
    Verifies whether the given model repo can be trusted.
    A model repo can be trusted if it matches onnx/models:main.
    r   modelsr2   r8   r4   r   r   r   _verify_repo_refd   s   r;   Flfsc                 C   sB   t | \}}}|rd| d| d| dS d| d| d| dS )a8  
    Gets the base github url from a repo specification string

    :param repo: The location of the model repo in format "user/repo[:branch]".
        If no branch is found will default to "main"
    :param lfs: whether the url is for downloading lfs models
    :return: the base github url for downloading
    z*https://media.githubusercontent.com/media/r/   z"https://raw.githubusercontent.com/r:   )r.   r<   r5   r6   r7   r   r   r   _get_base_urlm   s   	r=   url	file_namec              	   C   s   d}t | 5}t|d}	 ||}|sn|| qW d   n1 s&w   Y  W d   dS W d   dS 1 s>w   Y  dS )z
    Downloads the file with specifed file_name from the url

    :param url: a url of download link
    :param file_name: a specified file name for the downloaded file
    i @  wbTN)r   openreadwrite)r>   r?   
chunk_sizeresponsefchunkr   r   r   _download_file~   s   

PrH   onnx/models:mainr   r   c              
      s   t | }|d }z%t|}dd tttt |D }W d   n1 s'w   Y  W n tyA } ztd| |d}~ww  du rH|n fdd|D }|du rW|S dd |D }	g }
|D ]}d	d |j	D }t
|	|d
krz|
| qb|
S )a  
    Gets the list of model info consistent with a given name and tags

    :param repo: The location of the model repo in format "user/repo[:branch]".
        If no branch is found will default to "main"
    :param model: The name of the model to search for. If `None`, will return all models with matching tags.
    :param tags: A list of tags to filter models by. If `None`, will return all models with matching name.
    :return: list of ModelInfo
    zONNX_HUB_MANIFEST.jsonc                 S   s   g | ]}t |qS r   )r   ).0infor   r   r   
<listcomp>       zlist_models.<locals>.<listcomp>NzCould not find manifest at c                    s"   g | ]}|j    kr|qS r   )r   lowerrJ   mr   r   r   rL      s   " c                 S      h | ]}|  qS r   rN   rJ   tr   r   r   	<setcomp>   rM   zlist_models.<locals>.<setcomp>c                 S   rR   r   rS   rT   r   r   r   rV      rM   r   )r=   r   jsonloadr   r   r   r   AssertionErrorr   lenintersectionappend)r.   r   r   base_urlZmanifest_urlrE   manifestematching_modelsZcanonical_tagsZmatching_info_listrP   Z
model_tagsr   rQ   r   list_models   s,   
 
ra   r   c                    s   t || }|std|   du rt|dd d}|d S  fdd|D }t|dkr@d	d |D }t|  d
  d| |d S )a  
    Gets the model info matching the given name and opset.

    :param model: The name of the onnx model in the manifest. This field is case-sensitive
    :param repo: The location of the model repo in format "user/repo[:branch]".
        If no branch is found will default to "main"
    :param opset: The opset of the model to get. The default of `None` will return the model with largest opset.
    :return: ModelInfo
    zNo models found with name Nc                 S   s   | j  S r#   r   )rP   r   r   r   <lambda>   s    z get_model_info.<locals>.<lambda>)keyc                    s   g | ]	}|j  kr|qS r   rb   rO   rb   r   r   rL      s    z"get_model_info.<locals>.<listcomp>r   c                 S   s   g | ]}|j qS r   rb   rO   r   r   r   rL      s    z has no version with opset z. Valid opsets: )ra   rY   sortedrZ   )r   r.   r   r`   Zselected_modelsZvalid_opsetsr   rb   r   get_model_info   s   

rf   force_reloadsilentc                 C   sr  t | ||}|jd}|jdur|j d|d  |d< tttj|}|s.tj	|spt
|sM|sMd|}t|tjd td t  dkrMdS tjtj|d	d
 t|d	}	td|  d|  t|	|j | n
td|  d|  t|d}
|
 }W d   n1 sw   Y  |jdurt| }||jkstd||jtttt t |S )aq  
    Downloads a model by name from the onnx model hub

    :param model: The name of the onnx model in the manifest. This field is case-sensitive
    :param repo: The location of the model repo in format "user/repo[:branch]".
        If no branch is found will default to "main"
    :param opset: The opset of the model to download. The default of `None` automatically chooses the largest opset
    :param force_reload: Whether to force the model to re-download even if its already found in the cache
    :param silent: Whether to suppress the warning message if the repo is not trusted.
    :return: ModelProto or None
    r/   N_zThe model repo specification "{}" is not trusted and may contain security vulnerabilities. Only continue if you trust this repo.)filezContinue?[y/n]yT)exist_okzDownloading z to local path zUsing cached z model from rbzThe cached model has SHA256 {} while checksum should be {}. The model in the hub may have been updated. Use force_reload to download the model from the model hub.)!rf   r   r3   r   r   r+   osseppathexistsr;   r    printsysstderrinputrN   makedirsdirnamer=   rH   rA   rB   hashlibsha256	hexdigestrY   r   rX   r   r   bytesr   )r   r.   r   rg   rh   Zselected_modelZlocal_model_path_arrZlocal_model_pathmsgZlfs_urlrF   Zmodel_bytesZdownloaded_shar   r   r   rX      s<   





rX   )F)rI   NN)rI   N)rI   NFF))r(   Zos.pathr   urllib.requestr   urllib.errorr   rW   ro   ry   ior   typingr   r   r   r	   r
   r   r   r   r   rt   environr+   rq   
expanduserr   r   r,   r-   r8   boolr;   r=   rH   ra   r   rf   Z
ModelProtorX   r   r   r   r   <module>   sf   (

+
		

 $