sachithcheruvaturfynd commited on
Commit
0973a1f
1 Parent(s): 88fe3f4

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +299 -0
app.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pickle
2
+ import streamlit as st
3
+ from html_information2 import html2
4
+
5
+ import streamlit as st
6
+
7
+ st.set_page_config(page_title="My App", page_icon=":money_with_wings:", layout="wide", initial_sidebar_state="auto")
8
+ st.header("Frequently Bought Together Recommendations")
9
+
10
+ def read_pickle_files(pickle_file):
11
+ with open(pickle_file, 'rb') as f:
12
+ return pickle.load(f)
13
+
14
+ # Load sephora pickle files
15
+ corrected_fp_growth_results_sephora = read_pickle_files("sephora_corrected_fp_growth_results_cleaned.pkl")
16
+ all_products_with_names_sephora = read_pickle_files ("item_catalog.pkl")
17
+ dictionary_of_transactions_sephora = read_pickle_files("transaction_metadata.pkl")
18
+ images_sephora = read_pickle_files("uid_url_map.pkl")
19
+
20
+ # Load digital pickle files
21
+ corrected_fp_growth_results = read_pickle_files("corrected_fp_growth_results.pkl")
22
+ all_products_with_names = read_pickle_files ("all_products_with_names.pkl")
23
+ dictionary_of_transactions = read_pickle_files("reliance_digital_transactions.pkl")
24
+
25
+ # Dropdown for selecting the dataset
26
+ dataset_choice = st.selectbox(
27
+ "Select A Dataset",
28
+ ["Sephora Order Complete Dataset", "Reliance Digital Order Complete Dataset"]
29
+ )
30
+
31
+ if dataset_choice == "Sephora Order Complete Dataset":
32
+ list_of_products_to_display = {}
33
+ for itemid in (list(all_products_with_names_sephora.keys())): #for items in the total list of items in all transactions
34
+ if itemid in (list(corrected_fp_growth_results_sephora.keys())): #if the item has a result from fp-growth
35
+ list_of_products_to_display[itemid]= all_products_with_names_sephora[itemid] #show it in the drop down menu
36
+
37
+
38
+ name_to_id = {name: product_id for product_id, name in list_of_products_to_display.items()} # Reverse the dictionary to map product names to IDs
39
+ selected_product_name = st.selectbox('Select A Product:', list(name_to_id.keys())) # Create a dropdown menu with the product names
40
+
41
+ # Get the corresponding product_id
42
+ query_id = name_to_id[selected_product_name]
43
+ url = "https://www.sephora.com/"
44
+ st.write("Created using the clickstream order-completed and catalog data from [Sephora.com](%s)" % url)
45
+ query_url = images_sephora[int(query_id)]
46
+ st.image(query_url, width=500)
47
+
48
+
49
+ if dataset_choice == "Reliance Digital Order Complete Dataset":
50
+ list_of_products_to_display = {}
51
+ for itemid in (list(all_products_with_names.keys())): #for items in the total list of items in all transactions
52
+ if itemid in (list(corrected_fp_growth_results.keys())): #if the item has a result from fp-growth
53
+ list_of_products_to_display[itemid]= all_products_with_names[itemid] #show it in the drop down menu
54
+
55
+ name_to_id = {name: product_id for product_id, name in list_of_products_to_display.items()} # Reverse the dictionary to map product names to IDs
56
+ selected_product_name = st.selectbox('Select A Product:', list(name_to_id.keys())) # Create a dropdown menu with the product names
57
+
58
+ # Get the corresponding product_id
59
+ query_id = name_to_id[selected_product_name]
60
+ url = "https://www.reliancedigital.in/"
61
+ st.write("Created using the clickstream order-completed data from [reliancedigital.com](%s)" % url)
62
+
63
+ # Inject custom CSS for the tab headings
64
+ st.markdown(
65
+ """
66
+ <style>
67
+ /* Style the tab container */
68
+ div[data-testid="stTabs"] button {
69
+ background-color: #e0e0e0; /* Light grey background */
70
+ color: #333333; /* Dark grey text color */
71
+ font-size: 18px; /* Increase font size */
72
+ font-weight: bold; /* Make text bold */
73
+ padding: 10px 20px; /* Add some padding to the tabs */
74
+ border-radius: 10px; /* Rounded corners */
75
+ border: none; /* Remove default border */
76
+ margin: 5px; /* Add margin between tabs */
77
+ transition: background-color 0.3s ease; /* Add hover effect */
78
+ }
79
+
80
+ /* Hover effect for tabs */
81
+ div[data-testid="stTabs"] button:hover {
82
+ background-color: #b0b0b0; /* Darker grey on hover */
83
+ color: #333333; /* Keep text color the same */
84
+ }
85
+
86
+ /* Active tab styling */
87
+ div[data-testid="stTabs"] button[aria-selected="true"] {
88
+ background-color: #808080; /* Dark grey for active tab */
89
+ color: white; /* White text for active tab */
90
+ font-size: 20px; /* Larger font size for active tab */
91
+ }
92
+ </style>
93
+ """,
94
+ unsafe_allow_html=True
95
+ )
96
+
97
+ tab2, tab3 = st.tabs(["Frequently Bought Together Demo", "Historical Order Data"])
98
+
99
+ with tab2:
100
+ if dataset_choice == "Sephora Order Complete Dataset":
101
+ if query_id in corrected_fp_growth_results_sephora:
102
+
103
+ # Separate the sorted items into IDs and counts
104
+ item_ids = [item for item in corrected_fp_growth_results_sephora[query_id]]
105
+ item_counts = [corrected_fp_growth_results_sephora[query_id][item] for item in corrected_fp_growth_results_sephora[query_id]]
106
+ item_image = [images_sephora[int(item)] for item in corrected_fp_growth_results_sephora[query_id]]
107
+
108
+ confidence_list = []
109
+ transactions_list_sephora = []
110
+
111
+ for i in dictionary_of_transactions_sephora:
112
+ transactions_list_sephora.append(i["transaction"])
113
+
114
+ transactions_with_querry_item = len([transaction for transaction in transactions_list_sephora if int(query_id) in transaction])
115
+ copurchase_count = []
116
+
117
+ # Generate a list of product names to display
118
+ product_names = []
119
+ for each_item in corrected_fp_growth_results_sephora[query_id]:
120
+ product_names.append(all_products_with_names_sephora[each_item])
121
+
122
+ for reccomended_item in item_ids:
123
+ transactions_with_item_and_query_item = []
124
+ transactions_with_item_and_query_item.extend([transaction for transaction in transactions_list_sephora if (int(reccomended_item) in transaction) and (int(query_id) in transaction)])
125
+ number_of_transactions_with_reccomended_item_and_query_item = len(transactions_with_item_and_query_item)
126
+ copurchase_count.append(number_of_transactions_with_reccomended_item_and_query_item)
127
+ confidence_list.append(number_of_transactions_with_reccomended_item_and_query_item/transactions_with_querry_item)
128
+
129
+ mid_section = ""
130
+ for index, value in enumerate(product_names):
131
+ count_info = f"Co-purchased {copurchase_count[index]}/{transactions_with_querry_item} times"
132
+ item_counts_info = f"item-count {item_counts[index]} "
133
+ confidence_info = f"Confidence: {round(confidence_list[index], 3)}"
134
+
135
+ # Use <br> to display each line separately
136
+ mid_section += f"""<div class="item">
137
+ <div id="image-container"><img src='{item_image[index]}' /></div>
138
+ <p style="font-size: 16px; font-weight: bold; white-space: normal; word-wrap: break-word;">{str(product_names[index])}</p>
139
+ <p>{count_info}<br>{confidence_info}<br></p>
140
+ </div>"""
141
+
142
+
143
+ mid_html = html2 + mid_section + """</div></div></body>"""
144
+ st.markdown(mid_html, unsafe_allow_html=True)
145
+ else:
146
+ st.write("No frequent purchases found for this item.")
147
+
148
+ if dataset_choice == "Reliance Digital Order Complete Dataset":
149
+ if query_id in corrected_fp_growth_results:
150
+
151
+ # Separate the sorted items into IDs and counts
152
+ item_ids = [item for item in corrected_fp_growth_results[query_id]]
153
+ item_counts = [corrected_fp_growth_results[query_id][item] for item in corrected_fp_growth_results[query_id]]
154
+
155
+ confidence_list = []
156
+ transactions_list_digital = []
157
+
158
+ for i in dictionary_of_transactions:
159
+ transactions_list_digital.append(i["transaction"])
160
+
161
+ transactions_with_querry_item = len([transaction for transaction in transactions_list_digital if query_id in transaction])
162
+ copurchase_count = []
163
+
164
+ # Generate a list of product names to display
165
+ product_names = []
166
+ for each_item in corrected_fp_growth_results[query_id]:
167
+ product_names.append(all_products_with_names[each_item])
168
+
169
+ for reccomended_item in item_ids:
170
+ transactions_with_item_and_query_item = []
171
+ transactions_with_item_and_query_item.extend([transaction for transaction in transactions_list_digital if (reccomended_item in transaction) and (query_id in transaction)])
172
+ number_of_transactions_with_reccomended_item_and_query_item = len(transactions_with_item_and_query_item)
173
+ copurchase_count.append(number_of_transactions_with_reccomended_item_and_query_item)
174
+ confidence_list.append(number_of_transactions_with_reccomended_item_and_query_item/transactions_with_querry_item)
175
+
176
+ mid_section = ""
177
+ for index, value in enumerate(product_names):
178
+ count_info = f"Co-purchased {copurchase_count[index]}/{transactions_with_querry_item} times"
179
+ item_counts_info = f"item-count {item_counts[index]} "
180
+ confidence_info = f"Confidence: {round(confidence_list[index], 3)}"
181
+
182
+ # Use <br> to display each line separately
183
+ mid_section += f"""<div class="item">
184
+ <p style="font-size: 16px; font-weight: bold; white-space: normal; word-wrap: break-word;">{str(product_names[index])}</p>
185
+ <p>{count_info}<br>{confidence_info}<br></p>
186
+ </div>"""
187
+
188
+
189
+ mid_html = html2 + mid_section + """</div></div></body>"""
190
+ st.markdown(mid_html, unsafe_allow_html=True)
191
+ else:
192
+ st.write("No frequent purchases found for this item.")
193
+
194
+ with tab3: #historical transactions tab
195
+ if dataset_choice == "Sephora Order Complete Dataset":
196
+ st.subheader("Historical Transactions With Chosen Product (shows maximum 20)")
197
+
198
+ example_transactions = []
199
+ for transaction_dict in dictionary_of_transactions_sephora:
200
+ if int(query_id) in transaction_dict["transaction"]:
201
+ example_transactions.append(transaction_dict)
202
+
203
+ if example_transactions:
204
+ # Begin constructing the carousel for transactions
205
+ for i, transaction in enumerate(example_transactions):
206
+ st.markdown(f"**Transaction {i+1}:** Placed on {transaction['event_timestamp']} by {transaction['user_id']}", unsafe_allow_html=True)
207
+
208
+ transaction_names = []
209
+ for i in transaction["transaction"]:
210
+ transaction_names.append(all_products_with_names_sephora[str(i)])
211
+ item_image = [images_sephora[int(item)] for item in corrected_fp_growth_results_sephora[query_id]]
212
+
213
+
214
+ # Build the HTML for displaying the transaction in a carousel format
215
+ transaction_section = ""
216
+ for index, image_url in enumerate(transaction_names):
217
+ transaction_section += f"""<div class="item">
218
+ <div id="image-container"><img src='{item_image[index]}' /></div>
219
+ <p style="font-size: 16px; font-weight: bold; white-space: normal; word-wrap: break-word;">{str(transaction_names[index])}</p>
220
+ </div>"""
221
+
222
+ # Complete the carousel HTML structure
223
+ transaction_html = html2 + transaction_section + """</div></div></body>"""
224
+
225
+ # Render the carousel for each transaction
226
+ st.markdown(transaction_html, unsafe_allow_html=True)
227
+
228
+ else:
229
+ st.write("No transactions found for this item.")
230
+
231
+
232
+ if dataset_choice == "Reliance Digital Order Complete Dataset":
233
+ st.subheader("Historical Transactions With Chosen Product (shows maximum 20)")
234
+
235
+ example_transactions = []
236
+ for transaction_dict in dictionary_of_transactions:
237
+ if query_id in transaction_dict["transaction"]:
238
+ example_transactions.append(transaction_dict)
239
+
240
+ if example_transactions:
241
+ # Begin constructing the carousel for transactions
242
+ for i, transaction in enumerate(example_transactions):
243
+ st.markdown(f"**Transaction {i+1}:** Placed on {transaction['order_date']} by {transaction['customer_id']} from {transaction['delivery_city']}", unsafe_allow_html=True)
244
+
245
+ transaction_names = []
246
+ for i in transaction["transaction"]:
247
+ transaction_names.append(all_products_with_names[i])
248
+
249
+ # Build the HTML for displaying the transaction in a carousel format
250
+ transaction_section = ""
251
+ for index, image_url in enumerate(transaction_names):
252
+ transaction_section += f"""<div class="item">
253
+ <p style="font-size: 16px; font-weight: bold; white-space: normal; word-wrap: break-word;">{str(transaction_names[index])}</p>
254
+ </div>"""
255
+
256
+ # Complete the carousel HTML structure
257
+ transaction_html = html2 + transaction_section + """</div></div></body>"""
258
+
259
+ # Render the carousel for each transaction
260
+ st.markdown(transaction_html, unsafe_allow_html=True)
261
+
262
+ else:
263
+ st.write("No transactions found for this item.")
264
+
265
+
266
+
267
+ # Inject custom CSS for the 'Know More' button
268
+ st.markdown(
269
+ """
270
+ <style>
271
+ .know-more-button {
272
+ background-color: #808080; /* Dark grey background */
273
+ color: white !important; /* Force white text color */
274
+ font-size: 18px; /* Font size */
275
+ font-weight: bold; /* Bold text */
276
+ padding: 10px 20px; /* Padding */
277
+ border-radius: 10px; /* Rounded corners */
278
+ border: none; /* Remove default border */
279
+ cursor: pointer; /* Mouse pointer */
280
+ text-align: center;
281
+ text-decoration: none; /* Remove underline */
282
+ display: inline-block; /* Make it inline */
283
+ transition: background-color 0.3s ease;
284
+ }
285
+ .know-more-button:hover {
286
+ background-color: #b0b0b0; /* Lighter grey background on hover */
287
+ color: #333333 !important; /* Dark grey text on hover */
288
+ text-decoration: none; /* Keep underline removed on hover */
289
+ }
290
+ </style>
291
+ """,
292
+ unsafe_allow_html=True
293
+ )
294
+
295
+ # Add the 'Know More' button with the link and no underline
296
+ st.markdown(
297
+ '<a href="https://gofynd.quip.com/fOONA5yDkSr2/Frequently-Bought-Together-Recommendations" class="know-more-button">Know More</a>',
298
+ unsafe_allow_html=True
299
+ )