o
    oi"%                     @  s   d dl mZ d dlZd dlZd dlZd dlZd dlmZmZ d dl	Z	d dl
mZ d dlmZ d dlmZmZ d dlmZ g dZeeZG d	d
 d
eZdddZ	ddddZdddZdS )    )annotationsN)AnyOptional)kornia_config)numpy)onnxrequests)CachedDownloader)
ONNXLoaderadd_metadataio_name_conversionc                   @  sZ   e Zd ZdZeddddZedd ddZed!ddZed"ddZ	ed"ddZ
dS )#r
   z_Manages ONNX models, handling local caching, downloading from Hugging Face, and loading models.Turlstrdownloadboolkwargsr   returndict[str, Any]c                 K  s   | dr3| j|tj|d f|dd|}t|}t|}|W  d   S 1 s.w   Y  |s=td| dtd| d)	ad  Load JSON config from the specified URL.

        Args:
            url: The URL of the preprocessor config to load.
            download: If True, the config will be downloaded if it's not already in the local cache.
            kwargs: Additional download arguments.

        Returns:
            dict[str, Any]: The loaded preprocessor config.

        )zhttp:zhttps:z.jsonr   suffixNzFile `z)` not found. You may set `download=True`.z` not found.)	
startswithdownload_to_cacheospathsplitopenjsonloadRuntimeError)clsr   r   r   	file_pathf	json_data r$   E/home/ubuntu/.local/lib/python3.10/site-packages/kornia/onnx/utils.pyload_config(   s"   


 zONNXLoader.load_configF
model_name	with_dataonnx.ModelProtoc           	      K  s  | dr^|tdd }d| d}|ddp%tjtj|dd }|	d|i | j
||dd f|dd	|}|rYd| d
}| j
||dd f|d
d	| t|S | dsh| dr|ddpptj}|	d|i | j
|tj|d f|dd	|}|r|dd d
 }| j
|tj|d dd d
 f|d
d	| t|S tj|rt|S td| d)a  Load an ONNX model from the local cache or downloads it from Hugging Face if necessary.

        Args:
            model_name: The name of the ONNX model or operator. For Hugging Face-hosted models,
                use the format 'hf://model_name'. Valid `model_name` can be found on
                https://huggingface.co/kornia/ONNX_models.
                Or a URL to the ONNX model.
            download: If True, the model will be downloaded from Hugging Face if it's not already in the local cache.
            cache_dir: The directory where the model should be cached.
                Defaults to None, which will use a default `{kornia_config.hub_onnx_dir}` directory.
            with_data: If True, the model will be loaded with its `.onnx_data` weights.
            **kwargs: Additional arguments to pass to the download method, if needed.

        Returns:
            onnx.ModelProto: The loaded ONNX model.

        zhf://Nz7https://huggingface.co/kornia/ONNX_models/resolve/main/z.onnx	cache_dir/r      r   z
.onnx_datazhttp://zhttps://r   zFile z
 not found)r   lengetr   r   joinr   hub_onnx_dirr   updater   r   r   exists
ValueError)	r    r'   r   r(   r   r   r*   r!   url_datar$   r$   r%   
load_modelF   sf   



zONNXLoader.load_modelfolderlist[dict[str, Any]]c                 C  s:   d|  }t j|dd}|jdkr| S td|j )zFetch the contents of the Hugging Face repository using the Hugging Face API.

        Returns:
            A list of all files in the repository as dictionaries containing file details.

        z?https://huggingface.co/api/models/kornia/ONNX_models/tree/main/
   )timeout   z%Failed to fetch repository contents: )r   r/   status_coder   r4   )r7   r   responser$   r$   r%   _fetch_repo_contents   s
   

zONNXLoader._fetch_repo_contentsNonec                 C  &   |  d}dd |D }t| dS )z[List all available ONNX operators in the 'operators' folder of the Hugging Face repository.	operatorsc                 S     g | ]}|d  qS r   r$   .0filer$   r$   r%   
<listcomp>       z-ONNXLoader.list_operators.<locals>.<listcomp>Nr>   pprintpp)r    repo_contentsrA   r$   r$   r%   list_operators      
zONNXLoader.list_operatorsc                 C  r@   )zUList all available ONNX models in the 'models' folder of the Hugging Face repository.modelsc                 S  rB   rC   r$   rD   r$   r$   r%   rG      rH   z*ONNXLoader.list_models.<locals>.<listcomp>NrI   )r    rL   rO   r$   r$   r%   list_models   rN   zONNXLoader.list_modelsN)T)r   r   r   r   r   r   r   r   )TF)r'   r   r   r   r(   r   r   r)   )r7   r   r   r8   )r   r?   )__name__
__module____qualname____doc__classmethodr&   r6   staticmethodr>   rM   rP   r$   r$   r$   r%   r
   %   s    =	r
   
onnx_modelr)   io_name_mappingdict[str, str]r   c                 C  s&  t t| jjD ]}| jj| j}||v r|| | jj| _qt t| jjD ]}| jj| j}||v r=|| | jj| _q't t| jjD ]&}t t| jj| jD ]}| jj| j| |v rk|| | jj| j|< qSqFt t| jj| jD ]}| jj| j| |v r|| | jj| j|< qx| S )zConvert the input and output names of an ONNX model to 'input' and 'output'.

    Args:
        onnx_model: The ONNX model to convert.
        io_name_mapping: A dictionary mapping the original input and output names to the new ones.

    )ranger.   graphinputnameoutputnode)rW   rX   iin_nameout_namejr$   r$   r%   r      s*   r   additional_metadataOptional[list[tuple[str, str]]]c                 C  sF   |du rg }ddt jfg|D ]\}}| j }||_t||_q| S )a  Add metadata to an ONNX model.

    The metadata includes the source library (set to "kornia"), the version of kornia,
    and any additional metadata provided as a list of key-value pairs.

    Args:
        onnx_model: The ONNX model to add metadata to.
        additional_metadata: A list of tuples, where each tuple contains a key and a value
            for the additional metadata to add to the ONNX model.

    Returns:
        The ONNX model with the added metadata.

    N)sourcekorniaversion)rg   __version__metadata_propsaddkeyr   value)rW   rd   rl   rm   rj   r$   r$   r%   r      s   
r   	onnx_typer   r   c              	   C  sF   t jt jt jt jt jt jt jt jd}| |vrt	d|  d||  S )N)ztensor(float)ztensor(float16)ztensor(double)ztensor(int32)ztensor(int64)ztensor(uint8)ztensor(int8)ztensor(bool)z
ONNX type z not understood)
npfloat32float16float64int32int64uint8int8bool_	TypeError)rn   type_mappingr$   r$   r%   onnx_type_to_numpy   s   
rz   )rW   r)   rX   rY   r   r)   )N)rW   r)   rd   re   r   r)   )rn   r   r   r   )
__future__r   r   loggingr   rJ   typingr   r   rg   kornia.configr   kornia.core.externalr   ro   r   r   kornia.utils.downloadr	   __all__	getLoggerrQ   loggerr
   r   r   rz   r$   r$   r$   r%   <module>   s&   
 
%