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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pinecone
|
| 2 |
+
|
| 3 |
+
# init connection to pinecone
|
| 4 |
+
pinecone.init(
|
| 5 |
+
api_key="0898750a-ee05-44f1-ac8a-98c5fef92f4a", # app.pinecone.io
|
| 6 |
+
environment="asia-southeast1-gcp-free" # find next to api key
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
# index_name = "hybrid-image-search"
|
| 10 |
+
|
| 11 |
+
# if index_name not in pinecone.list_indexes():
|
| 12 |
+
# # create the index
|
| 13 |
+
# pinecone.create_index(
|
| 14 |
+
# index_name,
|
| 15 |
+
# dimension=512,
|
| 16 |
+
# metric="dotproduct",
|
| 17 |
+
# pod_type="s1"
|
| 18 |
+
# )
|
| 19 |
+
index_name = pinecone.list_indexes()[0]
|
| 20 |
+
print(index_name)
|
| 21 |
+
|
| 22 |
+
index = pinecone.GRPCIndex(index_name)
|
| 23 |
+
|
| 24 |
+
from datasets import load_dataset
|
| 25 |
+
|
| 26 |
+
# load the dataset from huggingface datasets hub
|
| 27 |
+
fashion = load_dataset(
|
| 28 |
+
"ashraq/fashion-product-images-small",
|
| 29 |
+
split='train[:1000]'
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
images = fashion["image"]
|
| 33 |
+
metadata = fashion.remove_columns("image")
|
| 34 |
+
images[900]
|
| 35 |
+
|
| 36 |
+
import pandas as pd
|
| 37 |
+
|
| 38 |
+
metadata = metadata.to_pandas()
|
| 39 |
+
filtered = metadata[ (metadata['gender'] == 'Men') & (metadata['articleType'] == 'Jeans')& (metadata['baseColour'] == 'Blue')]
|
| 40 |
+
print(len(filtered))
|
| 41 |
+
metadata.head()
|
| 42 |
+
|
| 43 |
+
import requests
|
| 44 |
+
|
| 45 |
+
with open('pinecone_text.py' ,'w') as fb:
|
| 46 |
+
fb.write(requests.get('https://storage.googleapis.com/gareth-pinecone-datasets/pinecone_text.py').text)
|
| 47 |
+
|
| 48 |
+
from transformers import BertTokenizerFast
|
| 49 |
+
import pinecone_text
|
| 50 |
+
|
| 51 |
+
# load bert tokenizer from huggingface
|
| 52 |
+
tokenizer = BertTokenizerFast.from_pretrained(
|
| 53 |
+
'bert-base-uncased'
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
def tokenize_func(text):
|
| 57 |
+
token_ids = tokenizer(
|
| 58 |
+
text,
|
| 59 |
+
add_special_tokens=False
|
| 60 |
+
)['input_ids']
|
| 61 |
+
return tokenizer.convert_ids_to_tokens(token_ids)
|
| 62 |
+
|
| 63 |
+
bm25 = pinecone_text.BM25(tokenize_func)
|
| 64 |
+
|
| 65 |
+
tokenize_func('Turtle Check Men Navy Blue Shirt')
|
| 66 |
+
|
| 67 |
+
bm25.fit(metadata['productDisplayName'])
|
| 68 |
+
|
| 69 |
+
display(metadata['productDisplayName'][0])
|
| 70 |
+
bm25.transform_query(metadata['productDisplayName'][0])
|
| 71 |
+
|
| 72 |
+
from sentence_transformers import SentenceTransformer
|
| 73 |
+
import transformers.models.clip.image_processing_clip
|
| 74 |
+
import torch
|
| 75 |
+
|
| 76 |
+
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 77 |
+
|
| 78 |
+
# load a CLIP model from huggingface
|
| 79 |
+
model = SentenceTransformer(
|
| 80 |
+
'sentence-transformers/clip-ViT-B-32',
|
| 81 |
+
device=device
|
| 82 |
+
)
|
| 83 |
+
model
|
| 84 |
+
|
| 85 |
+
dense_vec = model.encode([metadata['productDisplayName'][0]])
|
| 86 |
+
dense_vec.shape
|
| 87 |
+
|
| 88 |
+
#len(fashion)
|
| 89 |
+
|
| 90 |
+
"""##Encode the dataset to index
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
"""
|
| 94 |
+
|
| 95 |
+
# from tqdm.auto import tqdm
|
| 96 |
+
|
| 97 |
+
# batch_size = 200
|
| 98 |
+
|
| 99 |
+
# for i in tqdm(range(0, len(fashion), batch_size)):
|
| 100 |
+
# # find end of batch
|
| 101 |
+
# i_end = min(i+batch_size, len(fashion))
|
| 102 |
+
# # extract metadata batch
|
| 103 |
+
# meta_batch = metadata.iloc[i:i_end]
|
| 104 |
+
# meta_dict = meta_batch.to_dict(orient="records")
|
| 105 |
+
# # concatinate all metadata field except for id and year to form a single string
|
| 106 |
+
# meta_batch = [" ".join(x) for x in meta_batch.loc[:, ~meta_batch.columns.isin(['id', 'year'])].values.tolist()]
|
| 107 |
+
# # extract image batch
|
| 108 |
+
# img_batch = images[i:i_end]
|
| 109 |
+
# # create sparse BM25 vectors
|
| 110 |
+
# sparse_embeds = [bm25.transform_doc(text) for text in meta_batch]
|
| 111 |
+
# # create dense vectors
|
| 112 |
+
# dense_embeds = model.encode(img_batch).tolist()
|
| 113 |
+
# # create unique IDs
|
| 114 |
+
# ids = [str(x) for x in range(i, i_end)]
|
| 115 |
+
|
| 116 |
+
# upserts = []
|
| 117 |
+
# # loop through the data and create dictionaries for uploading documents to pinecone index
|
| 118 |
+
# for _id, sparse, dense, meta in zip(ids, sparse_embeds, dense_embeds, meta_dict):
|
| 119 |
+
# upserts.append({
|
| 120 |
+
# 'id': _id,
|
| 121 |
+
# 'sparse_values': sparse,
|
| 122 |
+
# 'values': dense,
|
| 123 |
+
# 'metadata': meta
|
| 124 |
+
# })
|
| 125 |
+
# # upload the documents to the new hybrid index
|
| 126 |
+
# index.upsert(upserts)
|
| 127 |
+
|
| 128 |
+
# show index description after uploading the documents
|
| 129 |
+
index.describe_index_stats()
|
| 130 |
+
|
| 131 |
+
from IPython.core.display import HTML
|
| 132 |
+
from io import BytesIO
|
| 133 |
+
from base64 import b64encode
|
| 134 |
+
import pinecone_text
|
| 135 |
+
|
| 136 |
+
# function to display product images
|
| 137 |
+
def display_result(image_batch):
|
| 138 |
+
figures = []
|
| 139 |
+
for img in image_batch:
|
| 140 |
+
b = BytesIO()
|
| 141 |
+
img.save(b, format='png')
|
| 142 |
+
figures.append(f'''
|
| 143 |
+
<figure style="margin: 5px !important;">
|
| 144 |
+
<img src="data:image/png;base64,{b64encode(b.getvalue()).decode('utf-8')}" style="width: 90px; height: 120px" >
|
| 145 |
+
</figure>
|
| 146 |
+
''')
|
| 147 |
+
return HTML(data=f'''
|
| 148 |
+
<div style="display: flex; flex-flow: row wrap; text-align: center;">
|
| 149 |
+
{''.join(figures)}
|
| 150 |
+
</div>
|
| 151 |
+
''')
|
| 152 |
+
|
| 153 |
+
def hybrid_scale(dense, sparse, alpha: float):
|
| 154 |
+
"""Hybrid vector scaling using a convex combination
|
| 155 |
+
|
| 156 |
+
alpha * dense + (1 - alpha) * sparse
|
| 157 |
+
|
| 158 |
+
Args:
|
| 159 |
+
dense: Array of floats representing
|
| 160 |
+
sparse: a dict of `indices` and `values`
|
| 161 |
+
alpha: float between 0 and 1 where 0 == sparse only
|
| 162 |
+
and 1 == dense only
|
| 163 |
+
"""
|
| 164 |
+
if alpha < 0 or alpha > 1:
|
| 165 |
+
raise ValueError("Alpha must be between 0 and 1")
|
| 166 |
+
# scale sparse and dense vectors to create hybrid search vecs
|
| 167 |
+
hsparse = {
|
| 168 |
+
'indices': sparse['indices'],
|
| 169 |
+
'values': [v * (1 - alpha) for v in sparse['values']]
|
| 170 |
+
}
|
| 171 |
+
hdense = [v * alpha for v in dense]
|
| 172 |
+
return hdense, hsparse
|
| 173 |
+
|
| 174 |
+
def text_to_image(query, alpha, k_results):
|
| 175 |
+
|
| 176 |
+
sparse = bm25.transform_query(query)
|
| 177 |
+
dense = model.encode(query).tolist()
|
| 178 |
+
|
| 179 |
+
# scale sparse and dense vectors
|
| 180 |
+
hdense, hsparse = hybrid_scale(dense, sparse, alpha=alpha)
|
| 181 |
+
|
| 182 |
+
# search
|
| 183 |
+
result = index.query(
|
| 184 |
+
top_k=k_results,
|
| 185 |
+
vector=hdense,
|
| 186 |
+
sparse_vector=hsparse,
|
| 187 |
+
include_metadata=True
|
| 188 |
+
)
|
| 189 |
+
# used returned product ids to get images
|
| 190 |
+
imgs = [images[int(r["id"])] for r in result["matches"]]
|
| 191 |
+
|
| 192 |
+
description = []
|
| 193 |
+
for x in result["matches"]:
|
| 194 |
+
description.append( x["metadata"]['productDisplayName'] )
|
| 195 |
+
|
| 196 |
+
return imgs, description
|
| 197 |
+
|
| 198 |
+
def show_dir_content():
|
| 199 |
+
for dirname, _, filenames in os.walk('./'):
|
| 200 |
+
for filename in filenames:
|
| 201 |
+
print(os.path.join(dirname, filename))
|
| 202 |
+
|
| 203 |
+
import shutil
|
| 204 |
+
from PIL import Image
|
| 205 |
+
import os
|
| 206 |
+
|
| 207 |
+
counter = {"dir_num": 1}
|
| 208 |
+
img_files = {'x':[]}
|
| 209 |
+
|
| 210 |
+
def img_to_file_list(imgs):
|
| 211 |
+
|
| 212 |
+
os.chdir('/content')
|
| 213 |
+
|
| 214 |
+
path = "searches"
|
| 215 |
+
sub_path = 'content/' + path + '/' + 'search' + '_' + str(counter["dir_num"])
|
| 216 |
+
|
| 217 |
+
# Check whether the specified path exists or not
|
| 218 |
+
isExist = os.path.exists('content'+'/'+path)
|
| 219 |
+
if not isExist:
|
| 220 |
+
print("Directory does not exists")
|
| 221 |
+
# Create a new directory because it does not exist
|
| 222 |
+
os.makedirs('content'+'/'+path, exist_ok = True)
|
| 223 |
+
print("The new directory is created!")
|
| 224 |
+
|
| 225 |
+
#else:
|
| 226 |
+
# os.chdir('/content/'+path)
|
| 227 |
+
|
| 228 |
+
print("Subdir ->The Current working directory is: {0}".format(os.getcwd()))
|
| 229 |
+
|
| 230 |
+
# Check whether the specified path exists or not
|
| 231 |
+
isExist = os.path.exists(sub_path)
|
| 232 |
+
if isExist:
|
| 233 |
+
shutil.rmtree(sub_path)
|
| 234 |
+
|
| 235 |
+
os.makedirs(sub_path, exist_ok = True)
|
| 236 |
+
|
| 237 |
+
img_files = {'search'+str(counter["dir_num"]):[]}
|
| 238 |
+
i = 0
|
| 239 |
+
curr_dir = os.getcwd()
|
| 240 |
+
for img in imgs:
|
| 241 |
+
img.save(sub_path+"/img_" + str(i) + ".png","PNG")
|
| 242 |
+
img_files['search'+str(counter["dir_num"])].append(sub_path + '/' + 'img_'+ str(i) + ".png")
|
| 243 |
+
|
| 244 |
+
i+=1
|
| 245 |
+
|
| 246 |
+
counter["dir_num"]+=1
|
| 247 |
+
|
| 248 |
+
return img_files['search'+str(counter["dir_num"]-1)]
|
| 249 |
+
|
| 250 |
+
#print(os.getcwd())
|
| 251 |
+
# os.chdir('/content/searches')
|
| 252 |
+
# print("The Current working directory is: {0}".format(os.getcwd()))
|
| 253 |
+
# show_dir_content()
|
| 254 |
+
|
| 255 |
+
# imgs2, descr = text_to_image('blue jeans for women', 0.5, 4)
|
| 256 |
+
|
| 257 |
+
# print("The Current working directory is: {0}".format(os.getcwd()))
|
| 258 |
+
# show_dir_content()
|
| 259 |
+
|
| 260 |
+
# img_files = img_to_file_list(imgs2)
|
| 261 |
+
|
| 262 |
+
# display(img_files)
|
| 263 |
+
|
| 264 |
+
# print("The Current working directory is: {0}".format(os.getcwd()))
|
| 265 |
+
# show_dir_content()
|
| 266 |
+
|
| 267 |
+
# shutil.rmtree('/content/searches')
|
| 268 |
+
|
| 269 |
+
# #shutil.rmtree('./content/searches')
|
| 270 |
+
# #print("The Current working directory is: {0}".format(os.getcwd()))
|
| 271 |
+
# #show_dir_content()
|
| 272 |
+
# #counter, img_files = img_to_file_list(imgs1, counter, img_files)
|
| 273 |
+
# #display(img_files)
|
| 274 |
+
|
| 275 |
+
# #counter, img_files = img_to_file_list(imgs2)
|
| 276 |
+
|
| 277 |
+
import gradio as gr
|
| 278 |
+
from deep_translator import GoogleTranslator
|
| 279 |
+
|
| 280 |
+
css = '''
|
| 281 |
+
.gallery img {
|
| 282 |
+
width: 45px;
|
| 283 |
+
height: 60px;
|
| 284 |
+
object-fit: contain;
|
| 285 |
+
}
|
| 286 |
+
'''
|
| 287 |
+
|
| 288 |
+
counter = {"dir_num": 1}
|
| 289 |
+
img_files = {'x':[]}
|
| 290 |
+
|
| 291 |
+
def fake_gan(text, alpha):
|
| 292 |
+
text_eng=GoogleTranslator(source='iw', target='en').translate(text)
|
| 293 |
+
imgs, descr = text_to_image(text_eng, alpha, 3)
|
| 294 |
+
img_files = img_to_file_list(imgs)
|
| 295 |
+
return img_files
|
| 296 |
+
|
| 297 |
+
def fake_text(text, alpha):
|
| 298 |
+
en_text = GoogleTranslator(source='iw', target='en').translate(text)
|
| 299 |
+
img , descr = text_to_image(en_text, alpha, 3)
|
| 300 |
+
return descr
|
| 301 |
+
|
| 302 |
+
with gr.Blocks() as demo:
|
| 303 |
+
|
| 304 |
+
with gr.Row():#variant="compact"):
|
| 305 |
+
|
| 306 |
+
text = gr.Textbox(
|
| 307 |
+
value = "讙'讬谞住 讻讞讜诇 诇讙讘专讬诐",
|
| 308 |
+
label="Enter the product characteristics:",
|
| 309 |
+
#show_label=True,
|
| 310 |
+
#max_lines=1,
|
| 311 |
+
#placeholder="Enter your prompt",
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
alpha = gr.Slider(0, 1, step=0.01, label='Choose alpha:', value = 0.05)
|
| 315 |
+
|
| 316 |
+
with gr.Row():
|
| 317 |
+
btn = gr.Button("Generate image")
|
| 318 |
+
|
| 319 |
+
with gr.Row():
|
| 320 |
+
gallery = gr.Gallery(
|
| 321 |
+
label="Generated images", show_label=False, elem_id="gallery"
|
| 322 |
+
).style(columns=[8], rows=[2], object_fit='scale-down', height='auto')
|
| 323 |
+
|
| 324 |
+
with gr.Row():
|
| 325 |
+
selected = gr.Textbox(label="Product description: ", interactive=False, value = "-----> Description <-------",placeholder="Selected")
|
| 326 |
+
|
| 327 |
+
btn.click(fake_gan, inputs=[text, alpha], outputs=gallery)
|
| 328 |
+
|
| 329 |
+
def get_select_index(evt: gr.SelectData,text,alpha):
|
| 330 |
+
print(evt.index)
|
| 331 |
+
eng_text = fake_text(text, alpha)[evt.index]
|
| 332 |
+
heb_text = GoogleTranslator(source='en', target='iw').translate(eng_text)
|
| 333 |
+
return heb_text
|
| 334 |
+
|
| 335 |
+
#gallery.select( get_select_index, None, selected )
|
| 336 |
+
gallery.select( fn=get_select_index, inputs=[text,alpha], outputs=selected )
|
| 337 |
+
|
| 338 |
+
demo.launch()
|
| 339 |
+
#shutil.rmtree('/content/searches')
|