svjack commited on
Commit
825cf2e
·
1 Parent(s): a47fad3

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +226 -0
app.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ !pip install "deepsparse-nightly==1.6.0.20231007"
3
+ !pip install "deepsparse[image_classification]"
4
+ !pip install opencv-python-headless
5
+ !pip uninstall numpy -y
6
+ !pip install numpy
7
+ !pip install gradio
8
+ !pip install pandas
9
+ '''
10
+
11
+ import os
12
+
13
+ os.system("pip uninstall numpy -y")
14
+ os.system("pip install numpy")
15
+ os.system("pip install pandas")
16
+
17
+ import gradio as gr
18
+ import sys
19
+ from uuid import uuid1
20
+ from PIL import Image
21
+ from zipfile import ZipFile
22
+ import pathlib
23
+ import shutil
24
+ import pandas as pd
25
+ import deepsparse
26
+ import json
27
+ import numpy as np
28
+
29
+ rn50_embedding_pipeline_default = deepsparse.Pipeline.create(
30
+ task="embedding-extraction",
31
+ base_task="image-classification", # tells the pipeline to expect images and normalize input with ImageNet means/stds
32
+ model_path="zoo:cv/classification/resnet_v1-50/pytorch/sparseml/imagenet/channel20_pruned75_quant-none-vnni",
33
+ #emb_extraction_layer=-1, # extracts last layer before projection head and softmax
34
+ )
35
+
36
+ rn50_embedding_pipeline_last_1 = deepsparse.Pipeline.create(
37
+ task="embedding-extraction",
38
+ base_task="image-classification", # tells the pipeline to expect images and normalize input with ImageNet means/stds
39
+ model_path="zoo:cv/classification/resnet_v1-50/pytorch/sparseml/imagenet/channel20_pruned75_quant-none-vnni",
40
+ emb_extraction_layer=-1, # extracts last layer before projection head and softmax
41
+ )
42
+
43
+ rn50_embedding_pipeline_last_2 = deepsparse.Pipeline.create(
44
+ task="embedding-extraction",
45
+ base_task="image-classification", # tells the pipeline to expect images and normalize input with ImageNet means/stds
46
+ model_path="zoo:cv/classification/resnet_v1-50/pytorch/sparseml/imagenet/channel20_pruned75_quant-none-vnni",
47
+ emb_extraction_layer=-2, # extracts last layer before projection head and softmax
48
+ )
49
+
50
+ rn50_embedding_pipeline_last_3 = deepsparse.Pipeline.create(
51
+ task="embedding-extraction",
52
+ base_task="image-classification", # tells the pipeline to expect images and normalize input with ImageNet means/stds
53
+ model_path="zoo:cv/classification/resnet_v1-50/pytorch/sparseml/imagenet/channel20_pruned75_quant-none-vnni",
54
+ emb_extraction_layer=-3, # extracts last layer before projection head and softmax
55
+ )
56
+
57
+ rn50_embedding_pipeline_dict = {
58
+ "0": rn50_embedding_pipeline_default,
59
+ "1": rn50_embedding_pipeline_last_1,
60
+ "2": rn50_embedding_pipeline_last_2,
61
+ "3": rn50_embedding_pipeline_last_3
62
+ }
63
+
64
+ def zip_ims(g):
65
+ from uuid import uuid1
66
+ if g is None:
67
+ return None
68
+ l = list(map(lambda x: x["name"], g))
69
+ if not l:
70
+ return None
71
+ zip_file_name ="tmp.zip"
72
+ with ZipFile(zip_file_name ,"w") as zipObj:
73
+ for ele in l:
74
+ zipObj.write(ele, "{}.png".format(uuid1()))
75
+ #zipObj.write(file2.name, "file2")
76
+ return zip_file_name
77
+
78
+ def unzip_ims_func(zip_file_name, choose_model,
79
+ rn50_embedding_pipeline_dict = rn50_embedding_pipeline_dict):
80
+ print("call file")
81
+ if zip_file_name is None:
82
+ return json.dumps({}), None
83
+ print("zip_file_name :")
84
+ print(zip_file_name)
85
+ unzip_path = "img_dir"
86
+ if os.path.exists(unzip_path):
87
+ shutil.rmtree(unzip_path)
88
+ with ZipFile(zip_file_name) as archive:
89
+ archive.extractall(unzip_path)
90
+ im_name_l = pd.Series(
91
+ list(pathlib.Path(unzip_path).rglob("*.png")) + \
92
+ list(pathlib.Path(unzip_path).rglob("*.jpg")) + \
93
+ list(pathlib.Path(unzip_path).rglob("*.jpeg"))
94
+ ).map(str).values.tolist()
95
+ rn50_embedding_pipeline = rn50_embedding_pipeline_dict[choose_model]
96
+ embeddings = rn50_embedding_pipeline(images=im_name_l)
97
+ im_l = pd.Series(im_name_l).map(Image.open).values.tolist()
98
+ if os.path.exists(unzip_path):
99
+ shutil.rmtree(unzip_path)
100
+ im_name_l = pd.Series(im_name_l).map(lambda x: x.split("/")[-1]).values.tolist()
101
+ return json.dumps({
102
+ "names": im_name_l,
103
+ "embs": embeddings.embeddings[0]
104
+ }), im_l
105
+
106
+
107
+ def emb_img_func(im, choose_model,
108
+ rn50_embedding_pipeline_dict = rn50_embedding_pipeline_dict):
109
+ print("call im :")
110
+ if im is None:
111
+ return json.dumps({})
112
+ im_obj = Image.fromarray(im)
113
+ im_name = "{}.png".format(uuid1())
114
+ im_obj.save(im_name)
115
+ rn50_embedding_pipeline = rn50_embedding_pipeline_dict[choose_model]
116
+ embeddings = rn50_embedding_pipeline(images=[im_name])
117
+ os.remove(im_name)
118
+ return json.dumps({
119
+ "names": [im_name],
120
+ "embs": embeddings.embeddings[0]
121
+ })
122
+
123
+ def image_grid(imgs, rows, cols):
124
+ assert len(imgs) <= rows*cols
125
+ w, h = imgs[0].size
126
+ grid = Image.new('RGB', size=(cols*w, rows*h))
127
+ grid_w, grid_h = grid.size
128
+
129
+ for i, img in enumerate(imgs):
130
+ grid.paste(img, box=(i%cols*w, i//cols*h))
131
+ return grid
132
+
133
+ def expand2square(pil_img, background_color):
134
+ width, height = pil_img.size
135
+ if width == height:
136
+ return pil_img
137
+ elif width > height:
138
+ result = Image.new(pil_img.mode, (width, width), background_color)
139
+ result.paste(pil_img, (0, (width - height) // 2))
140
+ return result
141
+ else:
142
+ result = Image.new(pil_img.mode, (height, height), background_color)
143
+ result.paste(pil_img, ((height - width) // 2, 0))
144
+ return result
145
+
146
+ def image_click(images, evt: gr.SelectData,
147
+ choose_model,
148
+ rn50_embedding_pipeline_dict = rn50_embedding_pipeline_dict,
149
+ top_k = 5
150
+ ):
151
+
152
+ images = json.loads(images.model_dump_json())
153
+ images = list(map(lambda x: {"name": x["image"]["path"]}, images))
154
+
155
+ img_selected = images[evt.index]
156
+ pivot_image_path = images[evt.index]['name']
157
+
158
+ im_name_l = list(map(lambda x: x["name"], images))
159
+ rn50_embedding_pipeline = rn50_embedding_pipeline_dict[choose_model]
160
+ embeddings = rn50_embedding_pipeline(images=im_name_l)
161
+ json_text = json.dumps({
162
+ "names": im_name_l,
163
+ "embs": embeddings.embeddings[0]
164
+ })
165
+
166
+ assert type(json_text) == type("")
167
+ assert type(pivot_image_path) in [type(""), type(0)]
168
+ dd_obj = json.loads(json_text)
169
+ names = dd_obj["names"]
170
+ embs = dd_obj["embs"]
171
+
172
+ assert pivot_image_path in names
173
+ corr_df = pd.DataFrame(np.asarray(embs).T).corr()
174
+ corr_df.columns = names
175
+ corr_df.index = names
176
+ arr_l = []
177
+ for i, r in corr_df.iterrows():
178
+ arr_ll = sorted(r.to_dict().items(), key = lambda t2: t2[1], reverse = True)
179
+ arr_l.append(arr_ll)
180
+ top_k = min(len(corr_df), top_k)
181
+ cols = pd.Series(arr_l[names.index(pivot_image_path)]).map(lambda x: x[0]).values.tolist()[:top_k]
182
+ corr_array_df = pd.DataFrame(arr_l).applymap(lambda x: x[0])
183
+ corr_array_df.index = names
184
+ #### corr_array
185
+ corr_array = corr_array_df.loc[cols].iloc[:, :top_k].values
186
+ l_list = pd.Series(corr_array.reshape([-1])).values.tolist()
187
+ l_dist_list = []
188
+ for ele in l_list:
189
+ if ele not in l_dist_list:
190
+ l_dist_list.append(ele)
191
+ return l_dist_list, l_list
192
+
193
+
194
+ with gr.Blocks() as demo:
195
+ with gr.Row():
196
+ choose_model = gr.Radio(choices=["0", "1", "2", "3"],
197
+ value="0", label="Choose embedding layer", elem_id="layer_radio")
198
+ with gr.Row():
199
+ with gr.Column():
200
+ inputs_0 = gr.Image(label = "Input Image for embed")
201
+ button_0 = gr.Button("Image button")
202
+ with gr.Column():
203
+ inputs_1 = gr.File(label = "Input Images zip file for embed")
204
+ button_1 = gr.Button("Image File button")
205
+ with gr.Row():
206
+ with gr.Column():
207
+ g_outputs = gr.Gallery(label='Output gallery', elem_id="gallery",
208
+ columns=[5],object_fit="contain", height="auto")
209
+ outputs = gr.Text(label = "Output Embeddings")
210
+ with gr.Column():
211
+ sdg_outputs = gr.Gallery(label='Sort Distinct gallery', elem_id="gallery",
212
+ columns=[5],object_fit="contain", height="auto")
213
+ sg_outputs = gr.Gallery(label='Sort gallery', elem_id="gallery",
214
+ columns=[5],object_fit="contain", height="auto")
215
+
216
+
217
+ button_0.click(fn = emb_img_func, inputs = [inputs_0, choose_model], outputs = outputs)
218
+ button_1.click(fn = unzip_ims_func, inputs = [inputs_1, choose_model],
219
+ outputs = [outputs, g_outputs])
220
+
221
+ g_outputs.select(image_click,
222
+ inputs = [g_outputs, choose_model],
223
+ outputs = [sdg_outputs, sg_outputs],)
224
+
225
+
226
+ demo.launch("0.0.0.0")