alexandrecorreia commited on
Commit
63613eb
·
1 Parent(s): fab9683

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +255 -0
app.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+ import gradio as gr
4
+ from gradio.themes import Size, GoogleFont
5
+ import sys
6
+ import pandas as pd
7
+ import webbrowser
8
+ from marqo import Client
9
+ from PIL import Image
10
+ import urllib.request
11
+ from PIL import Image
12
+ import requests
13
+ import matplotlib.pyplot as plt
14
+
15
+ from transformers import CLIPProcessor, CLIPModel
16
+
17
+ model = CLIPModel.from_pretrained("patrickjohncyh/fashion-clip")
18
+ processor = CLIPProcessor.from_pretrained("patrickjohncyh/fashion-clip")
19
+
20
+ # sys.path.insert(1, 'C:/Users/Alexandre/Documents/University/5_Ano/Estagio/repos_1')
21
+
22
+ # Create custom Color objects for our primary, secondary, and neutral colors
23
+ primary_color = gr.themes.colors.slate
24
+ secondary_color = gr.themes.colors.rose
25
+ neutral_color = gr.themes.colors.stone # Assuming black for text
26
+ # Set the sizes
27
+ spacing_size = gr.themes.sizes.spacing_md
28
+ radius_size = gr.themes.sizes.radius_md
29
+ text_size = gr.themes.sizes.text_md
30
+ # Set the fonts
31
+ font = GoogleFont("Source Sans Pro")
32
+ font_mono = GoogleFont("IBM Plex Mono")
33
+ # Create the theme
34
+ theme = gr.themes.Base(
35
+ primary_hue=primary_color,
36
+ secondary_hue=secondary_color,
37
+ neutral_hue=neutral_color,
38
+ spacing_size=spacing_size,
39
+ radius_size=radius_size,
40
+ text_size=text_size,
41
+ font=font,
42
+ font_mono=font_mono
43
+ )
44
+
45
+ def load_image(image_input):
46
+ image_input.save("../../../Documents/images/img_path.jpg")
47
+ os.system('docker cp "../../../Documents/images/img_path.jpg" marqo:"/images/images/"')
48
+
49
+
50
+ def search_images(query, best_seller_score_weight):
51
+ client = Client()
52
+ result = client.index("multimodal").search(query, score_modifiers = {
53
+ "add_to_score": [{"field_name": "best_seller_score","weight": best_seller_score_weight/1000}],
54
+ }, searchable_attributes=['primary_image'], device="cpu", limit=5)
55
+ imgs = [r for r in result["hits"]]
56
+
57
+ return imgs
58
+
59
+ def get_labels_probs(labels, image):
60
+ inputs = processor(text=labels, images=image, return_tensors="pt", padding=True)
61
+
62
+ outputs = model(**inputs)
63
+ logits_per_image = outputs.logits_per_image # this is the image-text similarity score
64
+ probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
65
+
66
+ return probs.tolist()[0]
67
+
68
+ def get_bar_plot(labels, probs):
69
+ fig, ax = plt.subplots()
70
+ bar_container = ax.bar(labels, probs)
71
+ ax.set(ylabel='frequency', title='Labels probabilities\n', ylim=(0, 1))
72
+ ax.bar_label(bar_container, fmt='{:,.4f}')
73
+
74
+ return fig
75
+
76
+ css = """
77
+ .gradio-container {background-color: beige}
78
+ button.gallery-item {background-color: grey}
79
+ .label {background-color: grey; width: 80px}
80
+ h1 {background-color: grey; width: 180px}
81
+ """
82
+
83
+ # css = """
84
+ # .gradio-container {background-color: beige}
85
+ # .gallery-item {
86
+ # """
87
+
88
+ with gr.Blocks(theme=theme, title="New Look", css=css) as demo:
89
+ gr.Markdown(
90
+ """
91
+ <div style="vertical-align: middle">
92
+ <div style="float: left">
93
+ <img src="https://1000logos.net/wp-content/uploads/2021/05/New-Look-logo.png" alt=""
94
+ width="250" height="250">
95
+ </div>
96
+ </div>
97
+ """)
98
+
99
+ # gr.Markdown(
100
+ # """
101
+ # # Hello World!
102
+ # Start typing below to see the output.
103
+ # """, primary_color=gr.themes.colors.stone, secondary_color=gr.themes.colors.stone, neutral_color=gr.themes.colors.stone)
104
+
105
+ with gr.Tab(label="Search for images"):
106
+ # with gr.TabItem(label="Search for images"):
107
+
108
+ with gr.Row().style(equal_height=False):
109
+ text_input = gr.Text(label="Search with text:")
110
+ text_relevance = gr.Slider(label="Text search relevance", minimum = -5, maximum = 5, value = 1, step = 1)
111
+ image_input = gr.Image(type="pil", label="Search with an image")
112
+ image_relevance = gr.Slider(label="Image search relevance", minimum = -5, maximum = 5, value = 1, step = 1)
113
+ with gr.Row():
114
+ gr.Examples(["Green", "Red", "Blue", "Sleeveless", "V-Neck", "Long dress, sleeveless, red"], text_input)
115
+ gr.Markdown()
116
+ gr.Examples(
117
+ ["../../../Documents/images/2272.jpg",
118
+ "../../../Documents/images/2697.jpg"],
119
+ image_input)
120
+ gr.Markdown()
121
+ # with gr.Row().style(equal_height=False):
122
+ # gr.Markdown()
123
+ # image_input = gr.Image(type="pil", label="Search with an image")
124
+ # image_relevance = gr.Slider(label="Image search relevance", minimum = -5, maximum = 5, value = 1, step = 1)
125
+ # gr.Markdown(scale=10)
126
+ # with gr.Row():
127
+ # gr.Markdown()
128
+ # gr.Examples(
129
+ # ["../../../Documents/images/2272.jpg",
130
+ # "../../../Documents/images/2697.jpg"],
131
+ # image_input)
132
+ # gr.Markdown()
133
+ # gr.Markdown()
134
+
135
+ with gr.Row():
136
+ gr.Markdown()
137
+ best_seller_score_weight = gr.Slider(label = "Best seller relevance", minimum=-1, maximum=1, value=0, step=0.01)
138
+ gr.Markdown()
139
+
140
+
141
+
142
+ # image_input = gr.Image(type="pil", label="Search with an image")
143
+ # image_relevance = gr.Slider(label="Image search relevance", minimum = -5, maximum = 5, value = 1, step = 1)
144
+ with gr.Row():
145
+ gr.Markdown()
146
+ search_button = gr.Button(value="Search")
147
+ gr.Markdown()
148
+
149
+ with gr.Row():
150
+ image_res_1 = gr.Image(type="pil")
151
+ image_res_2 = gr.Image(type="pil")
152
+ image_res_3 = gr.Image(type="pil")
153
+ image_res_4 = gr.Image(type="pil")
154
+ image_res_5 = gr.Image(type="pil")
155
+ response = gr.Text()
156
+
157
+ with gr.Tab(label="Search for images"):
158
+ labels_input = gr.Text(label="List of labels")
159
+ gr.Examples(
160
+ ["shirt, dress, shoe",
161
+ "short_sleeve, long_sleeve, three_quarter_sleeve, sleeveless, bell_sleeve"],
162
+ labels_input)
163
+ with gr.Row():
164
+ image_labels_input = gr.Image(type="pil", label="Image to compute")
165
+ bar_plot = gr.Plot()
166
+ with gr.Row():
167
+ gr.Examples(
168
+ ["../../../Documents/images/2272.jpg",
169
+ "../../../Documents/images/2697.jpg"],
170
+ image_labels_input)
171
+ gr.Markdown()
172
+ compute_button = gr.Button(value="Compute")
173
+
174
+ response_labels = gr.Text()
175
+
176
+ with gr.Tab(label="Choose dataset"):
177
+ gr.Markdown("# Choose Dataset")
178
+ with gr.Row():
179
+ gr.Dropdown(["New Look Dresses", "New Look All"], label="Available datasets")
180
+ gr.Markdown()
181
+ gr.Markdown()
182
+ with gr.Row():
183
+ gr.Button("Select")
184
+ gr.Markdown()
185
+ gr.Markdown()
186
+
187
+
188
+ def search(text_input, image_input, text_relevance, image_relevance, best_seller_score_weight):
189
+ if text_input == "" and image_input == None:
190
+ empty_response = [None] * 5
191
+ empty_response.append("")
192
+ return empty_response
193
+
194
+ if text_input == "":
195
+ load_image(image_input)
196
+ query = "/images/images/img_path.jpg"
197
+ elif image_input == None:
198
+ query = text_input
199
+ else:
200
+ query = dict()
201
+ load_image(image_input)
202
+ query["/images/images/img_path.jpg"] = image_relevance
203
+ query[text_input] = text_relevance
204
+
205
+ list_image_results = []
206
+ response = search_images(query, best_seller_score_weight)
207
+ for i in range(len(response)):
208
+ urllib.request.urlretrieve(response[i]["primary_image"], "../../../Documents/images/img_res_path_" + str(i) + ".jpg")
209
+ list_image_results.append(Image.open(r"../../../Documents/images/img_res_path_" + str(i) + r".jpg"))
210
+
211
+ return list_image_results[0], list_image_results[1], list_image_results[2], list_image_results[3], list_image_results[4], response
212
+
213
+ def get_labels(labels_input, image_labels_input):
214
+ labels_probs = get_labels_probs(labels_input.split(","), image_labels_input)
215
+ bar_plot = get_bar_plot(labels_input.split(","), labels_probs)
216
+ return bar_plot, labels_probs
217
+
218
+
219
+ search_button.click(
220
+ search, [text_input, image_input, text_relevance, image_relevance, best_seller_score_weight], [image_res_1, image_res_2, image_res_3, image_res_4, image_res_5, response]
221
+ )
222
+
223
+ compute_button.click(
224
+ get_labels, [labels_input, image_labels_input], [bar_plot, response_labels]
225
+ )
226
+
227
+ # image_input.upload(
228
+ # user, image_input, image_input
229
+ # ).then(
230
+ # respond, response, [image_res_1, image_res_2, image_res_3, image_res_4, image_res_5, response]
231
+ # )
232
+
233
+
234
+ # response = isComplete_state.change(
235
+ # lambda: gr.update(interactive=False), None, [user_input], queue=False
236
+ # ).then(
237
+ # respond_itinerary, [chatbot, isComplete_state, dataCollected_state], [chatbot, map, result_df]
238
+ # ).then(
239
+ # lambda: gr.update(visible=True), None, [map], queue=False
240
+ # ).then(
241
+ # lambda: gr.update(visible=True), None, [result_df], queue=False
242
+ # ).then(
243
+ # lambda: gr.update(visible=False), None, [text_map_before_itinerary], queue=False
244
+ # )
245
+
246
+ # response.then(
247
+ # lambda: gr.update(interactive=True), None, [user_input], queue=False
248
+ # )
249
+
250
+ # if map != None:
251
+ # map.update(visible=True)
252
+ # result_df.update(visible=True)
253
+
254
+ demo.queue()
255
+ demo.launch()