File size: 2,148 Bytes
6ba8811
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
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  # pylint: disable=import-outside-toplevel

    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)  # Adds a batch dimension

  with torch.no_grad():
    image_features = normalized(model.encode_image(tensor_image).cpu().detach().numpy())
  mediatypepredictions = np.matmul(image_features, text_features.T)  # Transpose text_features
  # or equivalently
  mediatypepredictions = image_features @ text_features.T  # Transpose text_features
  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("_"," ")+" , " #+" - "+ str(r[0])+" , "
  text += mediatype[max_index]
  print(im, text) 
  try:
    image.save(f"./output/{text}.jpg")
  except:
     pass