a
    d                     @   s   d Z ddlZddlZddlmZmZmZ ddlZddlm	Z	m
Z
 ddlmZmZmZ ddlmZmZmZ dd	gZee d
ddZdeee eeeejf  ee ddd	ZdS )z OpenAI pretrained model functions

Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
    N)ListOptionalUnion   )OPENAI_DATASET_MEANOPENAI_DATASET_STD)"build_model_from_openai_state_dictconvert_weights_to_lpget_cast_dtype)get_pretrained_urllist_pretrained_models_by_tagdownload_pretrained_from_urllist_openai_modelsload_openai_model)returnc                   C   s   t dS )z*Returns the names of available CLIP modelsopenai)r    r   r   Y/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/open_clip/openai.pyr      s    )name	precisiondevice	cache_dirc           	      C   sV  |du rt j rdnd}|du r2|dkr.dnd}t| drPtt| d|d}n(tj| rb| }ntd|  d	t	  zt j
j|dd
 }d}W n  ty   t j|dd
}Y n0 t|}zt|p| |d}W n6 ty   dd |d  D }t||d}Y n0 ||}|dkrB|  |dkrBt|t jd t|j_t|j_|S )a  Load a CLIP model

    Parameters
    ----------
    name : str
        A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict
    precision: str
        Model precision, if None defaults to 'fp32' if device == 'cpu' else 'fp16'.
    device : Union[str, torch.device]
        The device to put the loaded model
    cache_dir : Optional[str]
        The directory to cache the downloaded model weights

    Returns
    -------
    model : torch.nn.Module
        The CLIP model
    preprocess : Callable[[PIL.Image], torch.Tensor]
        A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input
    NcudacpuZfp32Zfp16r   )r   zModel z not found; available models = )Zmap_location)
cast_dtypec                 S   s   i | ]\}}|d d |qS )   Nr   ).0kvr   r   r   
<dictcomp>K       z%load_openai_model.<locals>.<dictcomp>
state_dictZbf16)Zdtype)torchr   Zis_availabler   r   ospathisfileRuntimeErrorr   Zjitloadevalr
   r   r!   KeyErroritemstofloatr	   Zbfloat16r   visualZ
image_meanr   Z	image_std)	r   r   r   r   Z
model_pathmodelr!   r   sdr   r   r   r      s8    



)NNN)__doc__r#   warningstypingr   r   r   r"   	constantsr   r   r.   r   r	   r
   Z
pretrainedr   r   r   __all__strr   r   r   r   r   r   r   <module>   s$      