cd14 laumiulun commited on
Commit
8af42e2
·
0 Parent(s):

Duplicate from loxzdigital/Model-IO-Space

Browse files

Co-authored-by: Andy Lau <laumiulun@users.noreply.huggingface.co>

.gitattributes ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ftz filter=lfs diff=lfs merge=lfs -text
6
+ *.gz filter=lfs diff=lfs merge=lfs -text
7
+ *.h5 filter=lfs diff=lfs merge=lfs -text
8
+ *.joblib filter=lfs diff=lfs merge=lfs -text
9
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
10
+ *.model filter=lfs diff=lfs merge=lfs -text
11
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
12
+ *.npy filter=lfs diff=lfs merge=lfs -text
13
+ *.npz filter=lfs diff=lfs merge=lfs -text
14
+ *.onnx filter=lfs diff=lfs merge=lfs -text
15
+ *.ot filter=lfs diff=lfs merge=lfs -text
16
+ *.parquet filter=lfs diff=lfs merge=lfs -text
17
+ *.pickle filter=lfs diff=lfs merge=lfs -text
18
+ *.pkl filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pt filter=lfs diff=lfs merge=lfs -text
21
+ *.pth filter=lfs diff=lfs merge=lfs -text
22
+ *.rar filter=lfs diff=lfs merge=lfs -text
23
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
24
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
25
+ *.tflite filter=lfs diff=lfs merge=lfs -text
26
+ *.tgz filter=lfs diff=lfs merge=lfs -text
27
+ *.wasm filter=lfs diff=lfs merge=lfs -text
28
+ *.xz filter=lfs diff=lfs merge=lfs -text
29
+ *.zip filter=lfs diff=lfs merge=lfs -text
30
+ *.zst filter=lfs diff=lfs merge=lfs -text
31
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
.streamlit/config.toml ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ [theme]
2
+ base="dark"
3
+ #primaryColor="#a40303"
4
+ #backgroundColor="#FFF"
5
+ #textColor="#ffffff"
6
+ #secondaryBackgroundColor="#126072"
7
+
8
+ [browser]
9
+ gatherUsageStats = false
README.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Model IO Space
3
+ emoji: ✉️
4
+ colorFrom: pink
5
+ colorTo: yellow
6
+ sdk: streamlit
7
+ sdk_version: 1.10.0
8
+ app_file: app.py
9
+ pinned: false
10
+ duplicated_from: loxzdigital/Model-IO-Space
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py ADDED
@@ -0,0 +1,422 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import numpy as np
3
+ import pandas as pd
4
+ import PIL
5
+ import torch
6
+ # import streamlit_analytics
7
+ import torchvision.transforms as transforms
8
+
9
+ import pickle
10
+
11
+ # AWS
12
+ import boto3
13
+ import botocore
14
+ from botocore import UNSIGNED
15
+ from botocore.config import Config
16
+
17
+ # Plotly and Bokeh
18
+ import plotly.graph_objects as go
19
+ from bokeh.models.widgets import Div
20
+
21
+
22
+ def convert_percentage(score):
23
+ rounded_probability = str(np.round(score*100,2)) + "%"
24
+ return rounded_probability
25
+
26
+ def url_button(button_name,url):
27
+ if st.button(button_name):
28
+ js = """window.open('{url}')""".format(url=url) # New tab or window
29
+ html = '<img src onerror="{}">'.format(js)
30
+ div = Div(text=html)
31
+ st.bokeh_chart(div)
32
+
33
+ def table_data():
34
+ # creating table data
35
+ field = [
36
+ 'Data Scientist',
37
+ 'Dataset',
38
+ 'Algorithm',
39
+ 'Framework',
40
+ 'Ensemble',
41
+ 'Domain',
42
+ 'Model Size'
43
+ ]
44
+
45
+ data = [
46
+ 'Andy Lau',
47
+ 'Stanford Cars Dataset',
48
+ 'Deep Learning Convolutional Neural Network: ResNet50',
49
+ 'Pytorch',
50
+ 'XGBoost',
51
+ 'ResNet Image Classification',
52
+ '76.55 KB'
53
+ ]
54
+
55
+ data = {
56
+ 'Field':field,
57
+ 'Data':data
58
+ }
59
+
60
+ df = pd.DataFrame.from_dict(data)
61
+
62
+ return df
63
+
64
+
65
+ def create_box(text,label):
66
+ st.markdown(f'<p style="background-color:#d2e4f6;padding: 5px 5px;border-radius:10px;font-size:24px;"><center><b>{text}</b>: {label}</center></p>', unsafe_allow_html=True)
67
+
68
+ def create_table():
69
+ # creating table data
70
+ field = [
71
+ 'Data Scientist',
72
+ 'Dataset',
73
+ 'Algorithm',
74
+ 'Framework',
75
+ 'Ensemble',
76
+ 'Domain',
77
+ 'Model Size'
78
+ ]
79
+
80
+ data = [
81
+ 'Andy Lau',
82
+ 'Stanford Cars Dataset',
83
+ 'Deep Learning Convolutional Neural Network: ResNet50',
84
+ 'Pytorch',
85
+ 'XGBoost',
86
+ 'ResNet Image Classification',
87
+ '76.55 KB'
88
+ ]
89
+
90
+ data = {
91
+ 'Field':field,
92
+ 'Data':data
93
+ }
94
+
95
+ df = pd.DataFrame.from_dict(data)
96
+
97
+
98
+ header_color = ['#0f4d60','#1c8d99']
99
+ cell_color = ['rgba(15,77,96,0.25)','rgba(28,141,153,0.33)']
100
+
101
+ # Create figures
102
+ fig = go.Figure(data=[go.Table(
103
+ header=dict(values=list(df.columns),
104
+ fill_color=header_color,
105
+ font=dict(color='white', size=15),
106
+ align='left'),
107
+ cells=dict(values=[df.Field, df.Data],
108
+ fill_color=header_color,
109
+ font=dict(color='white', size=15),
110
+ align='left'))
111
+ ])
112
+ # Make the header dissapear
113
+ fig.for_each_trace(lambda t: t.update(header_fill_color = 'rgba(0,0,0,0)'))
114
+
115
+ return fig
116
+
117
+
118
+ class SaveFeatures():
119
+ features=None
120
+ def __init__(self, m):
121
+ self.hook = m.register_forward_hook(self.hook_fn)
122
+ self.features = None
123
+ def hook_fn(self, module, input, output):
124
+ out = output.detach().cpu().numpy()
125
+ if isinstance(self.features, type(None)):
126
+ self.features = out
127
+ else:
128
+ self.features = np.row_stack((self.features, out))
129
+ def remove(self):
130
+ self.hook.remove()
131
+
132
+
133
+ def read_image_from_s3(bucket, key):
134
+ """Load image file from s3.
135
+
136
+ Parameters
137
+ ----------
138
+ bucket: string
139
+ Bucket name
140
+ key : string
141
+ Path in s3
142
+
143
+ Returns
144
+ -------
145
+ np array
146
+ Image array
147
+ """
148
+ s3 = boto3.resource('s3',config=Config(signature_version=UNSIGNED))
149
+ bucket = s3.Bucket(bucket)
150
+ object = bucket.Object(key)
151
+ response = object.get()
152
+ file_stream = response['Body']
153
+ im = PIL.Image.open(file_stream).convert('RGB')
154
+ return im
155
+
156
+
157
+
158
+ # ---- Title Screen -----------
159
+
160
+ def add_bg_from_url():
161
+ st.markdown(
162
+ f"""
163
+ <style>
164
+ .stApp {{
165
+ background-image: linear-gradient(#0A3144,#126072,#1C8D99);
166
+ background-attachment: fixed;
167
+ background-size: cover;
168
+ color: white;
169
+ }}
170
+ </style>
171
+ """,
172
+ unsafe_allow_html=True
173
+ )
174
+
175
+
176
+ st.set_page_config(layout="wide")
177
+ if 'user_counts' not in st.session_state:
178
+ st.session_state['user_counts'] = 0
179
+
180
+ # add_bg_from_url()
181
+
182
+ # st.session_state.user_counts +=1 # Increase usercounter
183
+
184
+
185
+ # col1, col2 = st.columns([10,1])
186
+ # with col1:
187
+ # st.markdown("""
188
+ # <style>
189
+ # .big-font {
190
+ # font-size:50px !important;
191
+ # }
192
+ # </style>
193
+ # """, unsafe_allow_html=True)
194
+ # st.markdown('<p class="big-font">Image Optimization: Email Industry</p>', unsafe_allow_html=True)
195
+ st.markdown('# Image Optimization: Email Industry')
196
+
197
+ # with col2:
198
+ # st.write(st.session_state.user_counts)
199
+
200
+ # image = Image.Open('figures/ModelIO.png')
201
+
202
+ # col1, col2, col3 = st.columns([1,1,1])
203
+
204
+ # with col2:
205
+ # img = PIL.Image.open('figures/IO.png')
206
+ # st.image(img)
207
+ # with col2:
208
+ # html3 = f"""
209
+ # <div class="total-dc"">
210
+ # <p>Total DC: £<p>
211
+ # <p>TEST<p>
212
+ # </div>
213
+
214
+ # """
215
+ # st.markdown(html3, unsafe_allow_html=True)
216
+ # st.markdown('#### Data Scientist')
217
+
218
+ stats_col1, stats_col2, stats_col3, stats_col4 = st.columns([1,1,1,1])
219
+
220
+ # with stats_col1:
221
+ # # st.markdown(' **Production**: Ready',unsafe_allow_html=True)
222
+ # create_box('Production','Ready')
223
+ # with stats_col2:
224
+ # create_box('Accuracy','91%')
225
+ # with stats_col3:
226
+ # create_box('Speed','2.18 ms')
227
+ # with stats_col4:
228
+ # # st.markdown(' **Industry**: Email Marketing')
229
+ # create_box('Industry','Email Marketing')
230
+
231
+ # st.markdown("""
232
+ # <style>
233
+ # div[data-testid="metric-container"] {
234
+ # background-color: rgba(28, 131, 225, 0.1);
235
+ # border: 1px solid rgba(28, 131, 225, 0.1);
236
+ # padding: 5% 5% 5% 10%;
237
+ # border-radius: 5px;
238
+ # color: rgb(30, 103, 119);
239
+ # overflow-wrap: break-word;
240
+ # }
241
+
242
+ # /* breakline for metric text */
243
+ # div[data-testid="metric-container"] > label[data-testid="stMetricLabel"] > div {
244
+ # overflow-wrap: break-word;
245
+ # white-space: break-spaces;
246
+ # color: red;
247
+ # }
248
+ # </style>
249
+ # """
250
+ # , unsafe_allow_html=True)
251
+ with stats_col1:
252
+ st.metric(label="Production", value="Ready")
253
+ with stats_col2:
254
+ st.metric(label="Accuracy", value="91%")
255
+
256
+ with stats_col3:
257
+ st.metric(label="Speed", value="2.18 ms")
258
+
259
+ with stats_col4:
260
+ st.metric(label="Industry", value="Email")
261
+
262
+
263
+ # ---- Model Information -----------
264
+ # info_col1, info_col2, info_col3 = st.columns([1,1,1])
265
+ with st.sidebar:
266
+ with st.expander('Model Description', expanded=False):
267
+ img = PIL.Image.open('figures/IO.png')
268
+ st.image(img)
269
+ st.markdown('Adding an image to an email campaign that will provide optimal engagement metrics can be challenging. How do you know which image to upload to your HTML, that will make an impact or significantly move the needle? And why would this image garner the best engagement? This model seeks to help campaign engineers understand which images affect their user engagement rate the most. The specific model is implemented using ResNet 18 and ResNet 34 for image embeddings extraction, and then we used these image embeddings as further inputs into a Gradient Boosted Tree model to generate probabilities on a user-specified target variable. The base model was adapted to car images and accurately predicted the user engagement rates with 91% accuracy. This model is adaptable for any large-scale marketing campaign using images. This model will identify the best images for optimal engagement for an email marketing campaign and serve engagement metrics prior to campaign launch. The model serves up several different images in milliseconds, so the campaign engineer understands which image to select in the campaign for optimized engagement.')
270
+
271
+ with st.expander('Model Information', expanded=False):
272
+ hide_table_row_index = """
273
+ <style>
274
+ thead tr th:first-child {display:none}
275
+ tbody th {display:none}
276
+ </style>
277
+ """
278
+ st.markdown(hide_table_row_index, unsafe_allow_html=True)
279
+ st.table(table_data())
280
+
281
+ url_button('Model Homepage','https://www.loxz.com/#/models/IO')
282
+ url_button('Full Report','https://resources.loxz.com/reports/image-optimization-model')
283
+ url_button('Amazon Market Place','https://aws.amazon.com/marketplace')
284
+
285
+
286
+
287
+
288
+ uploaded_file = st.file_uploader("Upload an image", type=["png", "jpg", "jpeg"])
289
+
290
+ if uploaded_file is not None:
291
+ upload_img = PIL.Image.open(uploaded_file)
292
+ else:
293
+ upload_img = None
294
+
295
+
296
+ # Drop down menu
297
+ target_variables = ['Open Rate',
298
+ 'Click Through Open Rate',
299
+ 'Revenue Generated per Email',
300
+ 'Conversion Rate']
301
+ campaign_types = ['Abandoned Cart',
302
+ 'Newsletter',
303
+ 'Promotional',
304
+ 'Survey',
305
+ 'Transactional',
306
+ 'Webinar',
307
+ 'Engagement',
308
+ 'Review_Request',
309
+ 'Product_Announcement']
310
+
311
+ industry_types =['Energy',
312
+ 'Entertainment',
313
+ 'Finance and Banking',
314
+ 'Healthcare',
315
+ 'Hospitality',
316
+ 'Real Estate', 'Retail', 'Software and Technology']
317
+
318
+
319
+ target = st.selectbox('Target Variables',target_variables, index=0)
320
+ campaign = st.selectbox('Campaign Types',campaign_types, index=0)
321
+ industry = st.selectbox('Industry Types',industry_types, index=0)
322
+
323
+
324
+ if st.button('Generate Predictions'):
325
+ if upload_img is None:
326
+ st.error('Please upload an image')
327
+ else:
328
+ placeholder = st.empty()
329
+ placeholder.write("Loading Data...")
330
+
331
+ # Starting Predictions
332
+
333
+ data = pd.read_csv('data/wrangled_data_v2.csv', index_col=0)
334
+ data_mod = data.copy()
335
+ data_mod = data[(data.campain_type == campaign) & (data.industry == industry)]
336
+
337
+ embeddings_df = pd.read_csv('data/embeddings_df.csv',index_col=0)
338
+ embeddings_df = embeddings_df.iloc[data.index]
339
+
340
+
341
+ # Transform to tensor
342
+ # transforming user input PIL Image to tensor
343
+ # single_img_path = list(uploaded_image.value.keys())[0]
344
+ single_image = upload_img.convert('RGB') # converting grayscale images to RGB
345
+ # st.image(single_image, caption='Uploaded Image', width=300)
346
+
347
+ my_transforms = transforms.Compose([
348
+ transforms.Resize((224,224)),
349
+ transforms.ToTensor()
350
+ ])
351
+
352
+ image_tensor = my_transforms(single_image).unsqueeze(0) # transforming into tensor, unsqueeze to match input batch size dimensions
353
+
354
+ placeholder.write('Loading Model...')
355
+
356
+ model_path = 'model/my_checkpoint1.pth'
357
+ model = torch.load(model_path,map_location=torch.device('cpu'))
358
+ model.eval()
359
+ image_imbeddings = SaveFeatures(list(model._modules.items())[-1][1])
360
+
361
+ with torch.no_grad():
362
+ outputs = model(image_tensor) # switched for cpu: image_tensor.cuda() (no cuda)
363
+ img_embeddings = image_imbeddings.features[0]
364
+
365
+
366
+ xgb_model = pickle.load(open("model/xgb_grid_model.pkl", "rb"))
367
+ col_names = ['Abarth', 'Cab', 'Convertible', 'Coupe', 'GS', 'Hatchback', 'IPL', 'Minivan', 'R', 'SRT-8', 'SRT8', 'SS', 'SUV', 'Sedan', 'SuperCab', 'Superleggera', 'Type-S', 'Van', 'Wagon', 'XKR', 'Z06', 'ZR1']
368
+ img_df = pd.DataFrame([img_embeddings], columns=col_names)
369
+
370
+ #####
371
+ # Getting Probabilities for Subsetted Dataframe
372
+ full_df_probs = xgb_model.predict_proba(embeddings_df)
373
+ full_df_probs = [i[1] for i in full_df_probs]
374
+ prob_series = pd.Series(full_df_probs, index= embeddings_df.index)
375
+
376
+ # 2 from each
377
+ top_10 = prob_series.sort_values(ascending=False)[:20]
378
+ random_4_from_top_10 = top_10.sample(replace=False,n=1)
379
+
380
+ # 2 from top 10 to 100
381
+ top_10_100 = prob_series.sort_values(ascending=False)[20:100]
382
+ random_4_from_top_10_100 = top_10_100.sample(replace=False,n=1)
383
+
384
+ alternate_probs = pd.concat([random_4_from_top_10, random_4_from_top_10_100], axis=0)
385
+
386
+ ######
387
+ # Making predictions on user input and displaying results:
388
+ img_pred = xgb_model.predict(img_df)[0]
389
+ img_proba = xgb_model.predict_proba(img_df)[0][1]
390
+ max_prob_dict = {}
391
+ max_prob_dict['current_image'] = img_proba
392
+ for i in range(len(alternate_probs)):
393
+ max_prob_dict['Alternate Image '+ str(i+1)] = alternate_probs.values[i]
394
+
395
+ st.write('Below are the probabilities if alternate recommended images were used')
396
+
397
+ st.subheader('Original Image Probability')
398
+ st.image(upload_img,caption = convert_percentage(img_proba),width=300)
399
+
400
+
401
+ img_index_1 = alternate_probs.index[0]
402
+ img_path_1 = data.iloc[img_index_1][0]
403
+
404
+ img_index_2 = alternate_probs.index[1]
405
+ img_path_2 = data.iloc[img_index_2][0]
406
+
407
+ bucket = 'lozx-public-data'
408
+ file_base = 'Model-IO/'
409
+ im_1 = read_image_from_s3(bucket, file_base + img_path_1)
410
+ im_2 = read_image_from_s3(bucket, file_base + img_path_2)
411
+
412
+
413
+ alt_col1, alt_col2 = st.columns([1,1])
414
+ with alt_col1:
415
+ st.subheader("Alternate Image 1")
416
+ st.image(im_1, caption=convert_percentage(alternate_probs.values[0]),width=300);
417
+ with alt_col2:
418
+ st.subheader("Alternate Image 2")
419
+ st.image(im_2, caption=convert_percentage(alternate_probs.values[1]), width=300);
420
+
421
+
422
+ placeholder.empty()
data/embeddings_df.csv ADDED
The diff for this file is too large to render. See raw diff
 
data/wrangled_data_v2.csv ADDED
The diff for this file is too large to render. See raw diff
 
figures/IO.png ADDED
model/my_checkpoint1.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:449641440be8207a96c214f5d58e360dec822debddb244b3905c12b5fc174166
3
+ size 85342809
model/xgb_grid_model.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c2869adf4748e3ddebcb57cd67c6adfdb19b2fb223c3bb5c6dfdd5bca69888d5
3
+ size 66920
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ xgboost==0.90
4
+ boto3
5
+ botocore
6
+ plotly
7
+ bokeh==2.4.1
8
+ scikit-learn