Team Ai
Apppublic

David310/Detect_AI-generated_Image

sourceHugging Faceupdated 2y agoView on Hugging Face
4likes
clip.cpython-310.pyc110 linesDownload Raw Back to __pycache__
1o

2�N�d�$�@s�ddlZddlZddlZddlZddlmZmZmZddlm	Z	ddl3Z4ddlmZddl
mZmZmZmZmZddlmZddlmZdd	lmZzdd5l
mZejZWneyaejZYnwe	j�e6j�e	j�d�krte�d�gd
�Z e�Z!dddddddddd�	Z"de#de#fdd�Z$dd�Z%dd�Z&d ee#fd!d"�Z'e7j(�)�r�d#nd$d%dfd&e#d'ee#e8j*fd(e+d)e#fd*d+�Z,d2d-ee#ee#fd.e-d/e+d ee9j.e10j/ffd0d1�Z0dS)3�N)�Any�Union�List)�	packaging)�Image)�Compose�Resize�11CenterCrop�ToTensor�	Normalize)�tqdm�)�build_model)�SimpleTokenizer)�InterpolationModez1.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.ptz�https://openaipublic.azureedge.net/clip/models/3035c92b350959924f9f00213499208652fc7ea050643e8b385c2dac08641f02/ViT-L-14-336px.pt)	�RN50ZRN101ZRN50x4ZRN50x16ZRN50x64zViT-B/32zViT-B/16zViT-L/14zViT-L/14@336px�url�rootc	12Cs�tj|dd�tj�|�}|�d�d}tj�||�}tj�|�r.tj�|�s.t|�d���tj�|�rLt	�13t|d�����
�|krD|St�|�d��tj�|��S}t|d��>}tt|���d	��d14dddd
��}	|�d�}|ssn
|�|�|�t|��qkWd�n1s�wYWd�n1s�wYWd�n1s�wYt	�15t|d�����
�|kr�td��|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�wbzContent-Length�PZiBi)�total�ncols�unit�16unit_scale�unit_divisori zDModel has been downloaded but the SHA256 checksum does not not match)�os�makedirs�path�basename�split�join�exists�isfile�RuntimeError�hashlib�sha256�open�read�	hexdigest�warnings�warn�urllib�request�urlopenr�int�info�get�write�update�len)	rr�filenameZexpected_sha256Zdownload_target�source�output�loop�buffer�r@�:/nobackup2/utkarsh/UniversalFakeDetect/models/clip/clip.py�	_download+s8"1718�����19rBcCs20|�d�S)N�RGB)�convert)�imager@r@rA�_convert_image_to_rgbKs21rFcCs&tt|td�t|�tt�tdd�g�S)N)�
interpolation)g3<�4'��?gwg��M�?gy{�� �?)g��B�91�?g�w�t.��?g��	U��?)rr�BICUBICr	rFr22r)Zn_pxr@r@rA�23_transformOs24�rI�returncCstt���S)z*Returns the names of available CLIP models)�list�_MODELS�keysr@r@r@rArYsr�cuda�cpuF�name�device�jit�
download_rootc
	s�|tvrtt||ptj�d��}ntj�|�r|}ntd|�dt�����t|d��8}zt	j25j||r5�ndd���}d}Wnty[|rRt
�d|�d	��d26}t	j|dd�}YnwWd�n1sfwY|s�t|ps|������}t��dkr�|��|t|jj�fSt	j27j�fdd�gd
�}dd�|j�d�D�d��fdd�}	|�|	�|	|j�|	|j�t��dkr�t	j28jdd�gd
�}29t|30j�d����d}|� ���fdd�}|�|�||j�||j�|��|t|j�!��fS)a�Load a CLIP model31 32    Parameters33    ----------34    name : str35        A model name listed by `clip.available_models()`, or the path to a model checkpoint containing the state_dict36 37    device : Union[str, torch.device]38        The device to put the loaded model39 40    jit : bool41        Whether to load the optimized JIT model or more hackable non-JIT model (default).42 43    download_root: str44        path to download the model files; by default, it uses "~/.cache/clip"45 46    Returns47    -------48    model : torch.nn.Module49        The CLIP model50 51    preprocess : Callable[[PIL.Image], torch.Tensor]52        A torchvision transform that converts a PIL image into a tensor that the returned model can take as its input53    z
~/.cache/clipzModel z not found; available models = rrO)�map_locationNzFile z6 is not a JIT archive. Loading as a state dict insteadFcst�g��t����S�N)�torch�ones�torQr@)rQr@rA�<lambda>�szload.<locals>.<lambda>)�example_inputscSsg|]54}dt|�vr|�qS)�Device)�repr)�.0�nr@r@rA�55<listcomp>�szload.<locals>.<listcomp>�prim::Constant�����cs�z
t|d�r56|jgng}Wntyg}Ynwt|d�r%|�|jj�|D]}|�d�D]}d|��vrDt|d��d�rD|�	��q.q'dS)N�graph�forward1r`�valuerN)57�hasattrrbr*�appendrc�findAllNodes�attributeNames�str�58startswith�copyAttributes)�module�graphsrb�node)�device_noder@rA�patch_device�s�5960���zload.<locals>.patch_devicecSst�g���SrU)rVrW�floatr@r@r@rArY�s�aten::tor
cs�z
t|d�r61|jgng}Wntyg}Ynwt|d�r%|�|jj�|D](}|�d�D] }t|���}dD]}||��ddkrM||���	��q8q.q'dS)Nrbrcrr)r
�rd�)62rerbr*rfrcrgrK�inputsrnrk)rlrmrbrnru�i)�63float_noder@rA�patch_float�s"�64����zload.<locals>.patch_float)"rLrBr"r$�65expanduserr)r*rr-rVrRr�evalr0r1r�66state_dictrXrirqrI�visualZinput_resolution�tracerbrg�apply�encode_imageZencode_textrK�findNoderurn�item)
rPrQrRrSZ67model_path�opened_file�modelr{Z
device_holderrpZfloat_holderZfloat_inputrxr@)rQrorwrAr^sL���686970717273r�M�texts�context_length�truncatecs�t|t�r|g}tjd�tjd���fdd�|D�}tj�tj�tj�d�kr5tj	t74|�|tjd�}ntj	t75|�|tjd�}t
|�D]0\}}t76|�|krg|r[|d|�}�|d<ntd	||�d77|����t�|�||dt78|��f<qD|S)a�79    Returns the tokenized representation of given input string(s)80 81    Parameters82    ----------83    texts : Union[str, List[str]]84        An input string or a list of input strings to tokenize85 86    context_length : int87        The context length to use; all CLIP models use 77 as the context length88 89    truncate: bool90        Whether to truncate the text in case its encoding is longer than the context length91 92    Returns93    -------94    A two-dimensional tensor containing the resulting tokens, shape = [number of input strings, context_length].95    We return LongTensor when torch version is <1.8.0, since older index_select requires indices to be long.96    z<|startoftext|>z
<|endoftext|>cs"g|]
}�gt�|��g�qSr@)�97_tokenizer�encode)r]�text�Z	eot_tokenZ	sot_tokenr@rAr_�s"ztokenize.<locals>.<listcomp>z1.8.0)�dtypeNrazInput z  is too long for context length )�98isinstancerir��encoderr�version�parserV�__version__�zerosr:�longr5�	enumerater*�tensor)r�r�r�Z99all_tokens�resultrv�tokensr@r�rAr�s 100101102103r)r�F)1r+r"r2r0�typingrrr�
pkg_resourcesrrV�PILr�torchvision.transformsrrr	r104rrr�rZsimple_tokenizerrZ105_TokenizerrrH�ImportErrorr�r�r�r1�__all__r�rLrirBrFrIrrN�is_availablerQ�boolrr5�	IntTensor�106LongTensorrr@r@r@rA�<module>sL107108�109�
 110:8g