a
    
d$                  
   @   s  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 d dlm	Z	 d dl
Z
d dlmZ d dlmZmZmZmZmZ d dlmZ ddlmZ dd	lmZ zd d
lmZ ejZW n ey   ejZY n0 e	je
je	jdk red g dZ e Z!dddddddddd	Z"e#e#dddZ$dd Z%dd Z&ee# dd d!Z'e
j() rPd"nd#d$dfe#ee#e
j*f e+e#d%d&d'Z,d,ee#ee# f e-e+ee
j.e
j/f d)d*d+Z0dS )-    N)AnyUnionList)	packaging)Image)ComposeResize
CenterCropToTensor	Normalize)tqdm   )build_model)SimpleTokenizer)InterpolationModez1.7.1z.PyTorch version 1.7.1 or higher is recommended)available_modelsloadtokenizezwhttps://openaipublic.azureedge.net/clip/models/afeb0e10f9e5a86da6080e35cf09123aca3b358a0c3e3b6c78a7b63bc04b6762/RN50.ptzxhttps://openaipublic.azureedge.net/clip/models/8fa8567bab74a42d41c5915025a8e4538c3bdbe8804a470a72f30b0d94fab599/RN101.ptzyhttps://openaipublic.azureedge.net/clip/models/7e526bd135e493cef0776de27d5f42653e6b4c8bf9e0f653bb11773263205fdd/RN50x4.ptzzhttps://openaipublic.azureedge.net/clip/models/52378b407f34354e150460fe41077663dd5b39c54cd0bfd2b27167a4a06ec9aa/RN50x16.ptzzhttps://openaipublic.azureedge.net/clip/models/be1cfb55d75a9666199fb2206c106743da0f6468c9d327f3e0d0a543a9919d9c/RN50x64.ptz{https://openaipublic.azureedge.net/clip/models/40d365715913c9da98579312b702a82c18be219cc2a73407c4526f58eba950af/ViT-B-32.ptz{https://openaipublic.azureedge.net/clip/models/5806e77cd80f8b59890b7e101eabd078d9fb84e6937f9e85e4ecb61988df416f/ViT-B-16.ptz{https://openaipublic.azureedge.net/clip/models/b8cca3fd41ae0c99ba7e8951adf17d267cdb84cd88be6f7c2e0eca1737a03836/ViT-L-14.ptzhttps://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt)	ZRN50ZRN101ZRN50x4ZRN50x16ZRN50x64zViT-B/32zViT-B/16zViT-L/14zViT-L/14@336px)urlrootc           	   
   C   s  t j|dd t j| }| dd }t j||}t j|r\t j|s\t| dt j|rt	
t|d  |kr|S t| d tj| }t|d~}tt| d	d
dddd<}|d}|sq || |t| qW d    n1 s0    Y  W d    n1 s60    Y  W d    n1 sV0    Y  t	
t|d  |krtd|S )NT)exist_ok/z! exists and is not a regular filerbzH exists, but the SHA256 checksum does not match; re-downloading the filewbzContent-LengthP   ZiBi   )totalZncolsZunitZ
unit_scaleZunit_divisori    zDModel has been downloaded but the SHA256 checksum does not not match)osmakedirspathbasenamesplitjoinexistsisfileRuntimeErrorhashlibZsha256openread	hexdigestwarningswarnurllibrequesturlopenr   intinfogetwriteupdatelen)	r   r   filenameZexpected_sha256Zdownload_targetsourceoutputZloopbuffer r9   R/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/clip/clip.py	_download+   s(    "

pr;   c                 C   s
   |  dS )NZRGB)convert)imager9   r9   r:   _convert_image_to_rgbK   s    r>   c                 C   s&   t t| tdt| tt tddgS )N)interpolation)g3<4'?gwgM?gy{ ?)gB91?gwt.?g	U?)r   r   BICUBICr	   r>   r
   r   )Zn_pxr9   r9   r:   
_transformO   s    
rA   )returnc                   C   s   t t S )z*Returns the names of available CLIP models)list_MODELSkeysr9   r9   r9   r:   r   Y   s    r   cudacpuF)namedevicejitdownload_rootc              	      s  | t v r$tt |  |ptjd}n(tj| r6| }ntd|  dt  t|dp}z$t	j
j||rj ndd }d}W n: ty   |rtd| d	 d
}t	j|dd}Y n0 W d   n1 s0    Y  |st|p|  }t dkr|  |t|jjfS t	j
j fddg d}dd |jdD d fdd}	||	 |	|j |	|j t dkrt	j
jdd g d}
t|
jd d }|  fdd}|| ||j ||j |  |t|j! f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

    device : Union[str, torch.device]
        The device to put the loaded model

    jit : bool
        Whether to load the optimized JIT model or more hackable non-JIT model (default).

    download_root: str
        path to download the model files; by default, it uses "~/.cache/clip"

    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
    z~/.cache/clipzModel z not found; available models = r   rG   )Zmap_locationNzFile z6 is not a JIT archive. Loading as a state dict insteadFc                      s   t g t  S N)torchonestorI   r9   )rI   r9   r:   <lambda>       zload.<locals>.<lambda>)Zexample_inputsc                 S   s   g | ]}d t |v r|qS )ZDevice)repr).0nr9   r9   r:   
<listcomp>   rQ   zload.<locals>.<listcomp>prim::Constantc                    s   zt | dr| jgng }W n ty0   g }Y n0 t | drJ|| jj |D ]<}|dD ],}d| v r\t|d dr\|	  q\qNd S )Ngraphforward1rV   valuerF   )
hasattrrX   r%   appendrY   findAllNodesZattributeNamesstr
startswithcopyAttributes)modulegraphsrX   node)device_noder9   r:   patch_device   s    

zload.<locals>.patch_devicec                   S   s   t g  S rL   )rM   rN   floatr9   r9   r9   r:   rP      rQ   aten::tor   c                    s   zt | dr| jgng }W n ty0   g }Y n0 t | drJ|| jj |D ]P}|dD ]@}t| }dD ]*}||  d dkrp||  	  qpq\qNd S )NrX   rY   rg   )r      rZ      )
r[   rX   r%   r\   rY   r]   rC   inputsrc   r`   )ra   rb   rX   rc   rj   i)
float_noder9   r:   patch_float   s    

zload.<locals>.patch_float)"rD   r;   r   r   
expanduserr$   r%   r   r'   rM   rJ   r   evalr*   r+   r   
state_dictrO   r^   rf   rA   ZvisualZinput_resolutiontracerX   r]   ZapplyZencode_imageZencode_textrC   ZfindNoderj   rc   item)rH   rI   rJ   rK   Z
model_pathZopened_filemodelrp   Zdevice_holderre   Zfloat_holderZfloat_inputrm   r9   )rI   rd   rl   r:   r   ^   sF    2





r   M   )textscontext_lengthtruncaterB   c                    s   t | tr| g} tjd tjd   fdd| D }tjtjtjdk rjtj	t
||tjd}ntj	t
||tjd}t|D ]`\}}t
||kr|r|d| } |d< ntd	| |  d
| t|||dt
|f< q|S )a  
    Returns the tokenized representation of given input string(s)

    Parameters
    ----------
    texts : Union[str, List[str]]
        An input string or a list of input strings to tokenize

    context_length : int
        The context length to use; all CLIP models use 77 as the context length

    truncate: bool
        Whether to truncate the text in case its encoding is longer than the context length

    Returns
    -------
    A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].
    We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.
    z<|startoftext|>z<|endoftext|>c                    s"   g | ]}gt |  g qS r9   )
_tokenizerencode)rS   textZ	eot_tokenZ	sot_tokenr9   r:   rU      rQ   ztokenize.<locals>.<listcomp>z1.8.0)ZdtypeNrW   zInput z  is too long for context length )
isinstancer^   rx   encoderr   versionparserM   __version__zerosr4   longr/   	enumerater%   Ztensor)ru   rv   rw   Z
all_tokensresultrk   tokensr9   r{   r:   r      s     



r   )rt   F)1r&   r   r,   r*   typingr   r   r   pkg_resourcesr   rM   ZPILr   Ztorchvision.transformsr   r   r	   r
   r   r   rs   r   Zsimple_tokenizerr   Z
_Tokenizerr   r@   ImportErrorr~   r   r   r+   __all__rx   rD   r^   r;   r>   rA   r   rF   Zis_availablerI   boolr   r/   Z	IntTensorZ
LongTensorr   r9   r9   r9   r:   <module>   sH   

 
6g