| import faiss |
| import numpy as np |
| from autofaiss import build_index |
| import open_clip |
| import torch |
| import pandas as pd |
| import pickle |
| import numpy as np |
| from PIL import Image |
| import glob |
|
|
|
|
| import os |
|
|
|
|
|
|
| df = pd.read_parquet("laioncocoknn367.parquet") |
| print(df) |
| texts = df['caption'].tolist() |
|
|
|
|
|
|
| model, _, transform = open_clip.create_model_and_transforms("hf-hub:laion/CLIP-ViT-B-32-256x256-DataComp-s34B-b86K") |
|
|
| def normalized(a, axis=-1, order=2): |
| import numpy as np |
|
|
| l2 = np.atleast_1d(np.linalg.norm(a, order, axis)) |
| l2[l2 == 0] = 1 |
| return a / np.expand_dims(l2, axis) |
|
|
|
|
|
|
|
|
| index = faiss.read_index("laioncocoknn367.index", faiss.IO_FLAG_MMAP | faiss.IO_FLAG_READ_ONLY) |
|
|
|
|
| files =glob.glob("/images/*.jpg") |
| mediatype = ["movie still HQ depth-of-field", "painting","drawing","realistic photo, photograph","CGI - computer graphics - 3D", "powerpoint slide - text - ebook", "pixelart, pixelated retro video game, low resolution", "ASCII", "cartoon", "stockphoto", "beautiful anime still, no text", "meme", "selfie", "beautiful artwork" , "wallpaper, HD, 4k"] |
| tokenizer = open_clip.get_tokenizer('ViT-B-32') |
|
|
| with torch.no_grad(), torch.cuda.amp.autocast(): |
| text_features = normalized(model.encode_text(tokenizer(mediatype)).cpu().detach().numpy()) |
|
|
|
|
| for im in files: |
| |
| image = Image.open(im) |
|
|
| tensor_image = transform(image).unsqueeze(0) |
|
|
| with torch.no_grad(): |
| image_features = normalized(model.encode_image(tensor_image).cpu().detach().numpy()) |
| mediatypepredictions = np.matmul(image_features, text_features.T) |
| |
| mediatypepredictions = image_features @ text_features.T |
| max_index = np.argmax(mediatypepredictions) |
| query_vector = image_features |
| k =1 |
| distances, indices = index.search(query_vector, k) |
|
|
| results = list(zip(distances[0], indices[0])) |
| text="" |
| for r in results: |
| text +=texts[r[1]].replace("_"," ")+" , " |
| text += mediatype[max_index] |
| print(im, text) |
| try: |
| image.save(f"./output/{text}.jpg") |
| except: |
| pass |