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|
+
import requests
|
| 4 |
+
from bs4 import BeautifulSoup
|
| 5 |
+
import urllib.parse
|
| 6 |
+
|
| 7 |
+
import streamlit as st
|
| 8 |
+
import uuid
|
| 9 |
+
|
| 10 |
+
import warnings
|
| 11 |
+
|
| 12 |
+
warnings.filterwarnings('ignore')
|
| 13 |
+
|
| 14 |
+
# Importing Custom Modules
|
| 15 |
+
from folder_management import create_folder, remove_files_folder
|
| 16 |
+
from sqlite_database import create_insert_table, query_table
|
| 17 |
+
|
| 18 |
+
'''
|
| 19 |
+
This Module will, for a particular keyword and publisherid combo query data from bizrate.com store it
|
| 20 |
+
in bizrate.db. And then generate Top 50 recommendation from it and Store it in RecSysData.db
|
| 21 |
+
|
| 22 |
+
'''
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# Function Definitions
|
| 26 |
+
def tag_to_list(tag_name, soup):
|
| 27 |
+
if tag_name == 'Image':
|
| 28 |
+
tag_list = soup.find_all(tag_name, {'xsize': '400'})
|
| 29 |
+
else:
|
| 30 |
+
tag_list = soup.find_all(tag_name)
|
| 31 |
+
|
| 32 |
+
return pd.Series([item.text for item in tag_list])
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def loadRSS(filepath, keyword, publisherid):
|
| 36 |
+
url = filepath
|
| 37 |
+
resp = requests.get(url)
|
| 38 |
+
with open('bizrate/' + keyword + "_" + publisherid + '.xml', 'wb') as f:
|
| 39 |
+
f.write(resp.content)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def remove_dollar_comma(row):
|
| 43 |
+
try:
|
| 44 |
+
row = row.split('$')[1]
|
| 45 |
+
row = row.replace(',', '')
|
| 46 |
+
row = float(row)
|
| 47 |
+
except AttributeError:
|
| 48 |
+
return row
|
| 49 |
+
return row
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def url_decode(url):
|
| 53 |
+
return urllib.parse.unquote(url.split('?t=')[1])
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def query_bizrate(keyword, publisherid='725895', search_results=500):
|
| 57 |
+
file_path = 'http://catalog.bizrate.com/services/catalog/v1/api/product?apiKey=c942e4e24d0859a748b4d1c07c1c3df1' \
|
| 58 |
+
'&publisherId={}&placementId=1&categoryId=&keyword={' \
|
| 59 |
+
'}&productId=&productIdType=&offersOnly=true&merchantId=&brandId=&biddedOnly=&minPrice=&maxPrice' \
|
| 60 |
+
'=&minMarkdown=&zipCode=&freeShipping=&start=0&results={' \
|
| 61 |
+
'}&startOffers=0&resultsOffers=0&sort=relevancy_desc&attFilter=&attWeights=&attributeId' \
|
| 62 |
+
'=&resultsAttribute=10&resultsAttributeValues=10&showAttributes=&showProductAttributes' \
|
| 63 |
+
'=&minRelevancyScore=1000&maxAge=&showRawUrl=&showUnitPricing=&useSecureImageDomain' \
|
| 64 |
+
'=&useSecureLinkDomain=&reviews=none&format=xml&callback=callback'.format(publisherid,
|
| 65 |
+
keyword,
|
| 66 |
+
search_results)
|
| 67 |
+
|
| 68 |
+
loadRSS(file_path, keyword, publisherid) # stores data as xml file in RecSysData Folder
|
| 69 |
+
|
| 70 |
+
with open('bizrate/' + keyword + "_" + publisherid + '.xml', 'r', errors='ignore') as f:
|
| 71 |
+
file = f.read()
|
| 72 |
+
|
| 73 |
+
soup = BeautifulSoup(file, 'xml')
|
| 74 |
+
|
| 75 |
+
# cols = ['title', 'Brand', 'mature', 'description', 'manufacturer', 'url', 'Image', 'Skus', 'upc', 'gtin', 'ean13',
|
| 76 |
+
# 'detailUrl',
|
| 77 |
+
# 'price', 'originalPrice', 'markdownPercent', 'totalPrice', 'bidded', 'merchantProductId',
|
| 78 |
+
# 'merchantName', 'merchantLogoUrl', 'condition', 'stock', 'shipAmount', 'shipType', 'relevancy']
|
| 79 |
+
|
| 80 |
+
cols = ['title', 'Brand', 'url', 'Image', 'Skus', 'price', 'originalPrice', 'markdownPercent', 'totalPrice',
|
| 81 |
+
'condition', 'stock', 'relevancy']
|
| 82 |
+
|
| 83 |
+
df_product = pd.DataFrame({'title': pd.Series(dtype='object'),
|
| 84 |
+
'Brand': pd.Series(dtype='object'),
|
| 85 |
+
'url': pd.Series(dtype='object'),
|
| 86 |
+
'Image': pd.Series(dtype='object'),
|
| 87 |
+
'Skus': pd.Series(dtype='object'),
|
| 88 |
+
'price': pd.Series(dtype='object'),
|
| 89 |
+
'originalPrice': pd.Series(dtype='object'),
|
| 90 |
+
'markdownPercent': pd.Series(dtype='object'),
|
| 91 |
+
'totalPrice': pd.Series(dtype='object'),
|
| 92 |
+
'condition': pd.Series(dtype='object'),
|
| 93 |
+
'stock': pd.Series(dtype='object'),
|
| 94 |
+
'relevancy': pd.Series(dtype='object')})
|
| 95 |
+
for col in cols:
|
| 96 |
+
df_product[col] = tag_to_list(col, soup)
|
| 97 |
+
df_product.dropna(subset=['Skus'], inplace=True)
|
| 98 |
+
df_product['Skus'] = df_product['Skus'].astype('object')
|
| 99 |
+
|
| 100 |
+
# Inserting the DataFrame into the bizrate DB into the corresponding table
|
| 101 |
+
create_insert_table(db_name='bizrate', table_name=keyword + "_" + publisherid, df=df_product)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def recommend(keyword, publisherid='725895', relevancy_filter=False, price_filter=True, discount_filter=False,
|
| 105 |
+
condition_filter='NEW', stock_filter='IN', n_rec=50):
|
| 106 |
+
|
| 107 |
+
# Querying required data from the bizrate database
|
| 108 |
+
df_product = query_table(db_name='bizrate', table_name=keyword + "_" + publisherid)
|
| 109 |
+
|
| 110 |
+
'''df_sku = pd.read_excel('df_sku.xlsx')
|
| 111 |
+
sku_list = list(df_product['Skus'].unique())
|
| 112 |
+
df_session = pd.read_excel('df_session.xlsx')
|
| 113 |
+
session_id = list(df_session['ID'])[-1]
|
| 114 |
+
for sku in sku_list:
|
| 115 |
+
df_row = pd.DataFrame({'SessionID': session_id, 'Keyword': selected_keyword, 'Skus': sku, 'Count': 0}, index=[0])
|
| 116 |
+
df_sku = pd.concat([df_sku, df_row], ignore_index=True)
|
| 117 |
+
df_sku.to_excel('df_sku.xlsx', index = False)'''
|
| 118 |
+
|
| 119 |
+
df_product['price'] = df_product['price'].map(remove_dollar_comma)
|
| 120 |
+
df_product['originalPrice'] = df_product['originalPrice'].map(remove_dollar_comma)
|
| 121 |
+
df_product['totalPrice'] = df_product['totalPrice'].map(remove_dollar_comma)
|
| 122 |
+
# df_product['shipAmount'] = df_product['shipAmount'].map(remove_dollar_comma)
|
| 123 |
+
df_product['markdownPercent'] = df_product['markdownPercent'].astype('float')
|
| 124 |
+
df_product['relevancy'] = df_product['relevancy'].astype('float')
|
| 125 |
+
|
| 126 |
+
# Sorting the Results
|
| 127 |
+
df_product = df_product.sort_values(by=['relevancy', 'price', 'markdownPercent'],
|
| 128 |
+
ascending=[relevancy_filter, price_filter, discount_filter], na_position='last')
|
| 129 |
+
|
| 130 |
+
# Filtering the Results
|
| 131 |
+
# condition_filter = st.sidebar.selectbox("Condition of the Product: ", list(df_product['condition'].unique()))
|
| 132 |
+
# stock_filter = st.sidebar.selectbox("Stock of Products: ", list(df_product['stock'].unique()))
|
| 133 |
+
|
| 134 |
+
filter_condition = (df_product['condition'] == condition_filter) & (df_product['stock'] == stock_filter)
|
| 135 |
+
df_product = df_product[filter_condition]
|
| 136 |
+
|
| 137 |
+
# Top N Recommendations
|
| 138 |
+
top_n_rec = df_product.head(n_rec)
|
| 139 |
+
|
| 140 |
+
# Inserting the DataFrame into the bizrate DB into the corresponding table
|
| 141 |
+
create_insert_table(db_name='RecSysData', table_name=keyword + "_" + publisherid, df=top_n_rec)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# Main Program
|
| 145 |
+
#selected_keyword = 'aquaman'
|
| 146 |
+
#publisher_id = '725895'
|
| 147 |
+
#query_bizrate(selected_keyword, publisher_id, 100)
|
| 148 |
+
#recommend(selected_keyword, publisher_id)
|
| 149 |
+
|
| 150 |
+
# list_keywords = ['aquaman', 'superman', 'batman', 'shoes', 'electronics', 'wallet', 'movies', 'books']
|
| 151 |
+
#
|
| 152 |
+
# for selected_keyword in list_keywords:
|
| 153 |
+
# query_bizrate(selected_keyword)
|
| 154 |
+
# recommend(selected_keyword)
|