File size: 11,390 Bytes
9ed01de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
import torch
import os
import numpy as np
import faiss
import open_clip
import functools
import re
from tqdm import tqdm
import ipdb

from torch.utils.data import DataLoader


def contains_special_characters(text):
    # check if non-ASCII characters exist
    if re.search(r'[^\x00-\x7F]', text):
        return True
    return False

def check_texts_for_special_characters(texts):
    results = []
    for i, text in enumerate(texts):
        if contains_special_characters(text):
            results.append(f"Text {i}: Contains special characters")
    return results

def clean_text(text):
    # remove non-ASCII
    text = re.sub(r'[^\x00-\x7F]+', '', text)  
    # remove redundent space
    text = re.sub(r'\s+', ' ', text)  
    # remove space at the beginning and end of texts
    text = text.strip()
    return text

def clean_texts(texts):
    return [clean_text(text) for text in texts]




def load_ori_query(coco_class_path):
    with open(coco_class_path, 'r') as file:
        coco_classes = [line.strip() for line in file.readlines()] 

    def add_article_to_classes(class_list):
        result = []
        for item in class_list:
            # Check if the first letter of the item is a vowel (a, e, i, o, u)
            if item[0].lower() in 'aeiou':
                result.append(f"an {item}")
            else:
                result.append(f"a {item}")
        return result

    a_cls_list = add_article_to_classes(coco_classes)

    an_image_showing_list = [f"an image showing {cls}" for cls in coco_classes]

    return a_cls_list, an_image_showing_list



def load_index(index_dir):
    print(os.getcwd())
    index_path = os.path.join(index_dir, 'faiss_IVPQ_PCA.index')
    index = faiss.read_index(index_path)

    # Load the transformations
    norm1 = faiss.read_VectorTransform(os.path.join(index_dir, 'norm1.bin'))
    do_pca = os.path.exists(os.path.join(index_dir, 'pca.bin'))
    if do_pca:
        pca = faiss.read_VectorTransform(os.path.join(index_dir, 'pca.bin'))
        norm2 = faiss.read_VectorTransform(os.path.join(index_dir, 'norm2.bin'))

    def feat_transform(x):
        x = norm1.apply_py(x)
        if do_pca:
            x = pca.apply_py(x)
            x = norm2.apply_py(x)
        return x

    img_ids = np.load(os.path.join(index_dir, 'img_ids.npy'))

    return index, feat_transform, img_ids


def load_model(config_name, weight_path):
    device = "cuda" if torch.cuda.is_available() else "cpu"
    model, _, transform = open_clip.create_model_and_transforms(config_name, pretrained=weight_path)
    tokenizer = open_clip.get_tokenizer(config_name)

    if device == 'cpu':
        model = model.float().to(device) # CPU does not support half precision operations
    else:
        model = model.to(device)
    model.eval()
    return model, tokenizer




def get_text_list_feature(query_list, ai_config, weight_path):
    '''
    query_list: n classes, each class has k queries !
    '''
    
    device = "cuda" if torch.cuda.is_available() else "cpu"
    model, tokenizer = load_model(ai_config, weight_path)

    
    text_list = [tokenizer(query).to(device) for query in query_list]

    with torch.no_grad():
        text_feats = [model.encode_text(text) for text in text_list]

    text_feats = [text.cpu().numpy() for text in text_feats]
    return text_feats




def get_text_feature(query_list, ai_config, weight_path):
    '''
    query_list: n queries !
    '''
    
    device = "cuda" if torch.cuda.is_available() else "cpu"
    model, tokenizer = load_model(ai_config, weight_path)

    text_list = tokenizer(query_list).to(device) 

    num = text_list.shape[0]
    batch_size = 1000 # 5000  

    with torch.no_grad():   
        text_feats = []
        for i in tqdm(range(0, num, batch_size)):
            text_feats.append(model.encode_text(text_list[i:i + batch_size]))
        #text_feats = model.encode_text(text_list) 
        text_feats = torch.cat(text_feats, dim=0)

    del model
    torch.cuda.empty_cache()

    return text_feats.cpu().numpy() 




def print_scores(aesthetics, faiss_smi):
    # np.set_printoptions(precision=3, suppress=False, floatmode='fixed')
    aesthetics = np.array(aesthetics)
    average_aesthetics = np.around(np.mean(aesthetics, axis=0), decimals=3)

    faiss_smi = np.array(faiss_smi)
    average_similarities = np.around(np.mean(faiss_smi, axis=0), decimals=3)

    avg_aes, std_aes = np.mean(aesthetics), np.std(aesthetics)
    avg_smi, std_smi = np.mean(faiss_smi), np.std(faiss_smi)
    
    print("avg aesthetics for each completion:", ' '.join(map(str, average_aesthetics)))
    print("avg aesthetics over all images: {:.3f}".format(avg_aes))
    print("std aesthetics over all images: {:.3f}".format(std_aes))
    print("avg similarities for each completion:", ' '.join(map(str, average_similarities)))
    print("avg similarities over all images: {:.3f}".format(avg_smi))
    print("std similarities over all images: {:.3f}".format(std_smi))
    print("---------------------------------------------------------------------------")



def print_scores_iqa(aesthetics, faiss_smi, iqas):
    # np.set_printoptions(precision=3, suppress=False, floatmode='fixed')
    aesthetics = np.array(aesthetics)
    average_aesthetics = np.around(np.mean(aesthetics, axis=0), decimals=3)

    faiss_smi = np.array(faiss_smi)
    average_similarities = np.around(np.mean(faiss_smi, axis=0), decimals=3)

    iqas = np.array(iqas)
    average_iqas = np.around(np.mean(iqas, axis=0), decimals=3)
    
    
    avg_aes, std_aes = np.mean(aesthetics), np.std(aesthetics)
    avg_smi, std_smi = np.mean(faiss_smi), np.std(faiss_smi)
    avg_iqa, std_iqa = np.mean(iqas), np.std(iqas)
    
    print("avg aesthetics for each completion:", ' '.join(map(str, average_aesthetics)))
    print("avg aesthetics over all images: {:.3f}".format(avg_aes))
    print("std aesthetics over all images: {:.3f}".format(std_aes))
    print("avg similarities for each completion:", ' '.join(map(str, average_similarities)))
    print("avg similarities over all images: {:.3f}".format(avg_smi))
    print("std similarities over all images: {:.3f}".format(std_smi))
    
    print("avg IQA for each completion:", ' '.join(map(str, average_iqas)))
    print("avg IQA over all images: {:.3f}".format(avg_iqa))
    print("std IQA over all images: {:.3f}".format(std_iqa))
    print("---------------------------------------------------------------------------")



def get_scores(img_list, dis_list, loaded_data, img_ids):

    aesthetics_score = loaded_data["aesthetics_score"]
    strImagehash = loaded_data["strImagehash"]

    img_hash_list = []     
    for imgs in img_list:          
        img_hash = [[img_ids[idx] for idx in img] for img in imgs]   #  imgs: [10, 100], img: [100]
        img_hash_list.append(img_hash)      

    aesthetics = []
    for each_class in img_hash_list:   # for each class in 80 classes
        avg_aesthetic = []
        for each_completion in each_class:   # for each completion in 10 completions
            aes_score = []
            # img_hash_set = set(each_completion)    # 100 retrieved images
            # indices = [i for i, hash_str in enumerate(strImagehash) if hash_str in img_hash_set]

            indices = [strImagehash.index(s) if s in strImagehash else None for s in each_completion]
            aes_score = [aesthetics_score[iii] if iii is not None else aesthetics_score.mean() for iii in indices]
            # torch.tensor(4.9504)    aesthetics_score.mean()
            aes_score = torch.stack(aes_score)
            
            avg_aesthetic.append(aes_score.mean())
        aesthetics.append(torch.stack(avg_aesthetic))
    aesthetics = torch.stack(aesthetics)

    faiss_smi = [[each_completion.mean() for each_completion in each_class] for each_class in dis_list]
    faiss_smi = torch.tensor(faiss_smi)     # faiss_smi: [80, 10]

    return aesthetics, faiss_smi, img_hash_list




def get_scores_prompt(img_list, dis_list, loaded_data, img_ids):

    aesthetics_score = loaded_data["aesthetics_score"]
    strImagehash = loaded_data["strImagehash"]

    img_hash_list = []     
    for imgs in img_list:          
        img_hash = [[img_ids[idx] for idx in img] for img in imgs]   #  imgs: [10, 100], img: [100]
        img_hash_list.append(img_hash)      

    aesthetics_all = []
    for each_class in img_hash_list:   # for each class in 80 classes
        aesthetic = []
        for each_completion in each_class:   # for each completion in 10 completions
            aes_score = []
            # img_hash_set = set(each_completion)    # 100 retrieved images
            # indices = [i for i, hash_str in enumerate(strImagehash) if hash_str in img_hash_set]

            indices = [strImagehash.index(s) if s in strImagehash else None for s in each_completion]
            aes_score = [aesthetics_score[iii] if iii is not None else aesthetics_score.mean() for iii in indices]
            # torch.tensor(4.9504)    aesthetics_score.mean()
            aes_score = torch.stack(aes_score)
            
            aesthetic.append(aes_score)
        aesthetics_all.append(torch.stack(aesthetic))
    aesthetics_all = torch.stack(aesthetics_all)

    faiss_smi = [[each_completion for each_completion in each_class] for each_class in dis_list]
    faiss_smi = torch.tensor(faiss_smi)     # faiss_smi: [80, 10]

    return aesthetics_all, faiss_smi



def image_retrive(sear_k, index, q_feats, loaded_data, img_ids):

    img_list = []
    dis_list = []
    for q_feat in q_feats:
        D, I = index.search(q_feat, sear_k)         # D, I: [10, 100]
        img_list.append(I)          # img_list {[10, 100], [10, 100], [10, 100]}, len(80)
        dis_list.append(D)          # dis_list {[10, 100], [10, 100], [10, 100]}, len(80)

    aesthetics, faiss_smi, img_hash_list = get_scores(img_list, dis_list, loaded_data, img_ids)
    # ipdb.set_trace()
    
    print_scores(aesthetics, faiss_smi)
    return img_hash_list, dis_list





def image_retrive_prompt(sear_k, index, q_feats, loaded_data, img_ids):
    img_list = []
    dis_list = []
    for q_feat in q_feats:
        D, I = index.search(q_feat, sear_k)         # D, I: [10, 100]
        img_list.append(I)          # img_list {[10, 100], [10, 100], [10, 100]}, len(80)
        dis_list.append(D)          # dis_list {[10, 100], [10, 100], [10, 100]}, len(80)
    ipdb.set_trace()

    aesthetics, faiss_smi = get_scores_prompt(img_list, dis_list, loaded_data, img_ids)
    return aesthetics.squeeze().squeeze(), faiss_smi.squeeze().squeeze()



def get_faiss_sim(sear_k, index, q_feats, img_ids, use_gpu):

    if use_gpu:
        res = faiss.StandardGpuResources()
        index = faiss.index_cpu_to_gpu(res, 0, index)

        
        num = q_feats.shape[0]
        batch_size = 100000 # 1000000
        
        img_hash_list = []
        faiss_smi = []

        for i in tqdm(range(0, num, batch_size)):
            D, I = index.search(q_feats[i:i + batch_size], sear_k)   
            img_hash_list.append(img_ids[I.squeeze()])
            faiss_smi.append(torch.from_numpy(D.squeeze()))

        faiss_smi = torch.cat(faiss_smi, dim=0)
        
        return faiss_smi, img_hash_list

    D, I = index.search(q_feats, sear_k) 
    img_hash_list = img_ids[I.squeeze()]        
    faiss_smi = torch.from_numpy(D.squeeze())  
    
    return faiss_smi, img_hash_list