Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -6,19 +6,7 @@ pinecone.init(
|
|
6 |
environment="asia-southeast1-gcp-free" # find next to api key
|
7 |
)
|
8 |
|
9 |
-
|
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
|
@@ -31,14 +19,6 @@ fashion = load_dataset(
|
|
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 |
|
@@ -61,14 +41,8 @@ def tokenize_func(text):
|
|
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
|
@@ -80,87 +54,15 @@ model = SentenceTransformer(
|
|
80 |
'sentence-transformers/clip-ViT-B-32',
|
81 |
device=device
|
82 |
)
|
83 |
-
|
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
|
@@ -171,8 +73,9 @@ def hybrid_scale(dense, sparse, alpha: float):
|
|
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 |
|
@@ -195,40 +98,27 @@ def text_to_image(query, alpha, k_results):
|
|
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 = '
|
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('
|
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 |
|
@@ -240,50 +130,15 @@ def img_to_file_list(imgs):
|
|
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':[]}
|
@@ -299,9 +154,10 @@ def fake_text(text, alpha):
|
|
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()
|
305 |
|
306 |
text = gr.Textbox(
|
307 |
value = "讙'讬谞住 讻讞讜诇 诇讙讘专讬诐",
|
@@ -329,11 +185,9 @@ with gr.Blocks() as demo:
|
|
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
|
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')
|
|
|
6 |
environment="asia-southeast1-gcp-free" # find next to api key
|
7 |
)
|
8 |
|
9 |
+
index_name = "hybrid-image-search"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
index = pinecone.GRPCIndex(index_name)
|
11 |
|
12 |
from datasets import load_dataset
|
|
|
19 |
|
20 |
images = fashion["image"]
|
21 |
metadata = fashion.remove_columns("image")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
22 |
|
23 |
import requests
|
24 |
|
|
|
41 |
return tokenizer.convert_ids_to_tokens(token_ids)
|
42 |
|
43 |
bm25 = pinecone_text.BM25(tokenize_func)
|
|
|
|
|
|
|
44 |
bm25.fit(metadata['productDisplayName'])
|
45 |
|
|
|
|
|
|
|
46 |
from sentence_transformers import SentenceTransformer
|
47 |
import transformers.models.clip.image_processing_clip
|
48 |
import torch
|
|
|
54 |
'sentence-transformers/clip-ViT-B-32',
|
55 |
device=device
|
56 |
)
|
57 |
+
|
58 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
59 |
|
60 |
from IPython.core.display import HTML
|
61 |
from io import BytesIO
|
62 |
from base64 import b64encode
|
63 |
import pinecone_text
|
64 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
def hybrid_scale(dense, sparse, alpha: float):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
66 |
if alpha < 0 or alpha > 1:
|
67 |
raise ValueError("Alpha must be between 0 and 1")
|
68 |
# scale sparse and dense vectors to create hybrid search vecs
|
|
|
73 |
hdense = [v * alpha for v in dense]
|
74 |
return hdense, hsparse
|
75 |
|
|
|
76 |
|
77 |
+
|
78 |
+
def text_to_image(query, alpha, k_results):
|
79 |
sparse = bm25.transform_query(query)
|
80 |
dense = model.encode(query).tolist()
|
81 |
|
|
|
98 |
|
99 |
return imgs, description
|
100 |
|
|
|
|
|
|
|
|
|
101 |
|
|
|
|
|
|
|
102 |
|
103 |
counter = {"dir_num": 1}
|
104 |
img_files = {'x':[]}
|
105 |
|
106 |
def img_to_file_list(imgs):
|
|
|
|
|
|
|
107 |
path = "searches"
|
108 |
+
sub_path = './' + path + '/' + 'search' + '_' + str(counter["dir_num"])
|
109 |
|
110 |
# Check whether the specified path exists or not
|
111 |
isExist = os.path.exists('content'+'/'+path)
|
112 |
+
|
113 |
if not isExist:
|
114 |
print("Directory does not exists")
|
115 |
# Create a new directory because it does not exist
|
116 |
+
os.makedirs('.'+'/'+path, exist_ok = True)
|
117 |
print("The new directory is created!")
|
118 |
|
|
|
|
|
|
|
|
|
|
|
119 |
# Check whether the specified path exists or not
|
120 |
isExist = os.path.exists(sub_path)
|
121 |
+
|
122 |
if isExist:
|
123 |
shutil.rmtree(sub_path)
|
124 |
|
|
|
130 |
for img in imgs:
|
131 |
img.save(sub_path+"/img_" + str(i) + ".png","PNG")
|
132 |
img_files['search'+str(counter["dir_num"])].append(sub_path + '/' + 'img_'+ str(i) + ".png")
|
|
|
133 |
i+=1
|
134 |
|
135 |
counter["dir_num"]+=1
|
136 |
|
137 |
return img_files['search'+str(counter["dir_num"]-1)]
|
138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
import gradio as gr
|
140 |
from deep_translator import GoogleTranslator
|
141 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
142 |
|
143 |
counter = {"dir_num": 1}
|
144 |
img_files = {'x':[]}
|
|
|
154 |
img , descr = text_to_image(en_text, alpha, 3)
|
155 |
return descr
|
156 |
|
157 |
+
|
158 |
with gr.Blocks() as demo:
|
159 |
|
160 |
+
with gr.Row():
|
161 |
|
162 |
text = gr.Textbox(
|
163 |
value = "讙'讬谞住 讻讞讜诇 诇讙讘专讬诐",
|
|
|
185 |
def get_select_index(evt: gr.SelectData,text,alpha):
|
186 |
print(evt.index)
|
187 |
eng_text = fake_text(text, alpha)[evt.index]
|
188 |
+
#heb_text = GoogleTranslator(source='en', target='iw').translate(eng_text)
|
189 |
+
return eng_text
|
190 |
+
|
|
|
191 |
gallery.select( fn=get_select_index, inputs=[text,alpha], outputs=selected )
|
192 |
|
193 |
demo.launch()
|
|