-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstreamlit_webapp.py
300 lines (238 loc) · 9.92 KB
/
streamlit_webapp.py
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
##### PREPARATIONS
# libraries
import gc
import pickle
import os
import sys
import urllib.request
import requests
import numpy as np
import pandas as pd
import streamlit as st
from PIL import Image
import cv2
import torch
from scipy.stats import percentileofscore
# download with progress bar
mybar = None
def show_progress(block_num, block_size, total_size):
global mybar
if mybar is None:
mybar = st.progress(0.0)
downloaded = block_num * block_size / total_size
if downloaded <= 1.0:
mybar.progress(downloaded)
else:
mybar.progress(1.0)
##### CONFIG
# page config
st.set_page_config(
page_title="Score your pet!",
page_icon="🐾",
layout="centered",
initial_sidebar_state="collapsed",
menu_items=None,
)
##### HEADER
# title
st.title("How cute is your pet?")
# image cover
cover_image = Image.open(
requests.get(
"https://storage.googleapis.com/kaggle-competitions/kaggle/25383/logos/header.png?t=2021-08-31-18-49-29",
stream=True,
).raw
)
st.image(cover_image)
# description
st.write(
"This app uses deep learning to estimate a pawpularity score of custom pet photos. Pawpularity is a metric used by [PetFinder](https://petfinder.my/) to judge the pet's attractiveness, which translates to more clicks for the pet profile."
)
##### PARAMETERS
# header
st.header("Score your own pet")
# photo upload
pet_image = st.file_uploader("1. Upload your pet photo.")
if pet_image is not None:
# check image format
image_path = "app/tmp/" + pet_image.name
if (
(".jpg" not in image_path)
and (".JPG" not in image_path)
and (".jpeg" not in image_path)
and (".bmp" not in image_path)
):
st.error("Please upload .jpeg, .jpg or .bmp file.")
else:
# save image to folder
with open(image_path, "wb") as f:
f.write(pet_image.getbuffer())
# display pet image
st.success("Pet photo uploaded.")
# privacy toogle
choice = st.radio(
"2. Make the result public?",
[
"Yes. Others may see your pet photo.",
"No. Scoring will be done privately.",
],
)
# model selection
model_name = st.selectbox(
"3. Choose a model for scoring your pet.",
["EfficientNet B3", "Swin Transformer"],
)
##### MODELING
# compute pawpularity
if st.button("Compute pawpularity"):
# check if image is uploaded
if pet_image is None:
st.error("Please upload a pet image first.")
else:
# specify paths
if model_name == "EfficientNet B3":
weight_path = "https://github.com/kozodoi/pet_pawpularity/releases/download/0.1/enet_b3.pth"
model_path = "app/models/enet_b3/"
elif model_name == "EfficientNet B5":
weight_path = "https://github.com/kozodoi/pet_pawpularity/releases/download/0.1/enet_b5.pth"
model_path = "app/models/enet_b5/"
elif model_name == "Swin Transformer":
weight_path = "https://github.com/kozodoi/pet_pawpularity/releases/download/0.1/swin_base.pth"
model_path = "app/models/swin_base/"
# download model weights
if not os.path.isfile(model_path + "pytorch_model.pth"):
with st.spinner(
"Downloading model weights. This is done once and can take a minute..."
):
urllib.request.urlretrieve(
weight_path, model_path + "pytorch_model.pth", show_progress
)
# compute predictions
with st.spinner("Computing prediction..."):
# clear memory
gc.collect()
# load config
config = pickle.load(open(model_path + "configuration.pkl", "rb"))
# initialize model
model = get_model(
config, pretrained=model_path + "pytorch_model.pth"
)
model.eval()
# define augmentations
augs = get_augs(config)
# process pet image
pet_image = cv2.imread(image_path)
pet_image = cv2.cvtColor(pet_image, cv2.COLOR_BGR2RGB)
image = augs(image=pet_image)["image"]
# compute prediction
pred = model(torch.unsqueeze(image, 0))
score = np.round(100 * pred.detach().numpy()[0][0], 2)
# compute percentile
oof = pd.read_csv(model_path + "oof.csv")
percent = np.round(
percentileofscore(oof["pred"].values * 100, score), 2
)
# display results
col1, col2 = st.columns(2)
col1.image(cv2.resize(pet_image, (256, 256)))
col2.metric("Pawpularity", score)
col2.metric("Percentile", str(percent) + "%")
col2.write(
"**Note:** pawpularity ranges from 0 to 100. Scroll down to read more about the metric and the implemented models."
)
# save results
if choice == "Yes. Others may see your pet photo.":
# load results
results = pd.read_csv("app/results.csv")
# save resized image
example_img = cv2.imread(image_path)
example_img = cv2.cvtColor(example_img, cv2.COLOR_BGR2RGB)
example_path = "app/images/example_{}.jpg".format(
len(results) + 1
)
cv2.imwrite(example_path, img=example_img)
# write score to results
row = pd.DataFrame(
{
"path": [example_path],
"score": [score],
"model": [model_name],
}
)
results = pd.concat([results, row], axis=0)
results.to_csv("app/results.csv", index=False)
# delete old image
if os.path.isfile(
"app/images/example_{}.jpg".format(len(results) - 3)
):
os.remove(
"app/images/example_{}.jpg".format(len(results) - 3)
)
# clear memory
del config, model, augs, image
gc.collect()
# celebrate
st.success("Well done! Thanks for scoring your pet :)")
##### RESULTS
# header
st.header("Recent results")
with st.expander("See results for three most recently scored pets"):
# find most recent files
results = pd.read_csv("app/results.csv")
if len(results) > 3:
results = results.tail(3).reset_index(drop=True)
# display images in columns
cols = st.columns(len(results))
for col_idx, col in enumerate(cols):
with col:
st.write("**Pawpularity:** ", results["score"][col_idx])
example_img = cv2.imread(results["path"][col_idx])
example_img = cv2.resize(example_img, (256, 256))
st.image(example_img)
st.write("**Model:** ", results["model"][col_idx])
##### DOCUMENTATION
# header
st.header("More information")
# models
with st.expander("Learn more about the models"):
st.write(
"The app uses one of the two computer vision models to score the pet photo. The models are implemented in PyTorch."
)
st.table(
pd.DataFrame(
{
"model": ["Swin Transfomer", "EfficientNet B3"],
"architecture": [
"swin_base_patch4_window7_224",
"tf_efficientnet_b3_ns",
],
"image size": ["224 x 224", "300 x 300"],
}
)
)
# metric
with st.expander("Learn more about the metric"):
st.write(
"Pawpularity is a metric used by [PetFinder.my](https://petfinder.my/), which is a Malaysia's leading animal welfare platform. Pawpularity serves as a proxy for the photo's attractiveness, which translates to more page views for the pet profile.The pawpularity metric ranges from 0 to 100. Click [here](https://www.kaggle.com/c/petfinder-pawpularity-score/discussion/274106) to read more about the metric."
)
# models
with st.expander("Learn more about image processing"):
st.write(
"Before feeding the image to the model, we apply the following transformations:"
)
st.write("1. Resizing the image to square shape.")
st.write("2. Normalizing RGB pixels to ImageNet values.")
st.write("3. Converting the image to a PyTorch tensor.")
##### CONTACT
# header
st.header("Contact")
# website link
st.write(
"Check out [my website](https://kozodoi.me) for ML blog, academic publications, Kaggle solutions and more of my work."
)
# profile links
st.write(
"[](https://www.linkedin.com/in/kozodoi/) [](https://www.twitter.com/n_kozodoi) [](https://www.kaggle.com/kozodoi) [](https://www.github.com/kozodoi) [](https://scholar.google.com/citations?user=58tMuD0AAAAJ&hl=en) [](https://www.researchgate.net/profile/Nikita_Kozodoi) [](https://www.buymeacoffee.com/kozodoi)"
)
# copyright
st.text("© 2022 Nikita Kozodoi")