-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.py
345 lines (221 loc) · 7.88 KB
/
server.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
from flask import Flask,jsonify,request
from flask_restful import Api,Resource
import numpy as nm
from pymongo import MongoClient
import pandas as pd
import pandas as pd
import pandas as pdd
import plotly.express as px
from sklearn.cluster import KMeans
from yellowbrick.cluster import KElbowVisualizer
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from yellowbrick.cluster import KElbowVisualizer
#finding optimal number of clusters using the elbow method
from sklearn.cluster import KMeans
import matplotlib
import json
matplotlib.use('SVG')
from flask_cors import CORS, cross_origin
app = Flask(__name__)
api = Api(app)
# importing libraries
client = MongoClient('mongodb+srv://kartikgamot2003:[email protected]/')
db = client.flask_db
todos = db.Database
@app.route('/getProduct',methods=['POST'])
@cross_origin()
def findd():
print("here")
content = request.json
giftName = content['Gift']
print(giftName)
product_cursor = todos.find({"Gift":giftName}).limit(1)
product = next(product_cursor, None)
product['_id'] = str(product['_id'])
return jsonify(product);
def getMappingDictionary(unique_data):
mappingDictionary = {}
for i in range(len(unique_data)):
mappingDictionary[unique_data[i]] = i
return mappingDictionary
@app.route('/addEntry',methods=['POST'])
@cross_origin()
def okk():
content = request.json
print(content)
age = content['age']
gender =content['gender']
intrest =content['interest']
relatioship = content['relationship']
occasion = content['occasion']
budget = content['budget']
rating = content['rating']
Link = content['Link']
Image_Link = content['ImageLink']
MaxBudget = content['budget']
GiftName = content['Gift']
user_input = {
'Age':[age],
'Gender':[gender],
'Relationship':[relatioship],
'Occasion':[occasion],
'Budget':[budget],
'MaxBudget':[MaxBudget],
'Gift':[GiftName],
'Rating':[rating],
'Link':[Link],
'Image Link':[Image_Link],
'Interest':[intrest]
}
todos.insert_one(user_input)
todos.delete_many({"Gift":"https//amazon.com"})
return "ok"
@app.route('/getGift',methods=['POST'])
@cross_origin()
def ok():
content = request.json
age = content['age']
gender =content['gender']
intrest =content['interest']
relatioship = content['relationship']
occasion = content['occasion']
budget = content['budget']
# todos.delete_many({})
user_input = {
'Age':age,
'Gender':gender,
'Relationship':relatioship,
'Occasion':occasion,
'Budget':budget,
'MaxBudget':500,
'Gift':"https//amazon.com",
'Rating':1,
'Link':"https//amazon.com",
'Image Link':"https//amazon.com",
'Interest':intrest
}
todos.insert_one(user_input)
k = todos.find({},{"_id":0})
dataset = pd.DataFrame(list(k))
# print(dataset)
# # print(user_input)
# dataset = pd.read_csv('dataset.csv')
# neww = pdd.DataFrame(user_input);
# neww.to_csv('dataset.csv', mode='a', index=False, header=False)
# p = pd.read_json('dataset.json')
# p.to_csv()
# print(p)
# # dataset.head(150)
# function to create a dictionary of unique values of column mapped to numerical values
def getMappingDictionary(unique_data):
mappingDictionary = {}
for i in range(len(unique_data)):
mappingDictionary[unique_data[i]] = i
return mappingDictionary
def getUniqueDataList(columnName):
return list(set(dataset[columnName]))
def modifyDatasetColumn(columnName, mapping_dict):
dataset[columnName] = dataset[columnName].map(mapping_dict)
def modifyDataset(columnName):
unique_columnValues = getUniqueDataList(columnName)
# print(unique_columnValues)
mapping_dict = getMappingDictionary(unique_columnValues)
# print(mapping_dict)
modifyDatasetColumn(columnName,mapping_dict)
modifyDataset('Gender')
# print(dataset.head())
modifyDataset('Interest')
# dataset.head()
df = pd.DataFrame(dataset)
newdf = df.copy()
# extract headers from the database
dataframe_headers = dataset.columns.values
# drop unnecessary columns from dataframe
df.drop(['Relationship','Occasion','Budget','MaxBudget','Gift','Rating','Link','Image Link'],axis=1, inplace=True)
# print(df)
new_headers = df.columns.values
# print(df)
model = KMeans()
visualizer = KElbowVisualizer(model, k=(1, 10))
# Fit the data to the visualizer
visualizer.fit(df)
# # Display the elbow plot
# visualizer.show()
k= visualizer.elbow_value_
# print(k)
#training the K-means model on a dataset
kmeans = KMeans(n_clusters = k, init='k-means++', random_state= 42)
customer_segments = kmeans.fit_predict(df)
# [df['Age'].iloc[-1]]
# Create a new customer and predict the segment it belongs to
input_customer_data = {
'Age': [df['Age'].iloc[-1]],
'Gender':[df['Gender'].iloc[-1]],
'Interest': [df['Interest'].iloc[-1]],
}
new_customer = pd.DataFrame(input_customer_data)
new_customer_segment = kmeans.predict(new_customer[new_headers])
new_customer_segment[0]
labels = kmeans.labels_
centroids = kmeans.cluster_centers_
df2 = pd.DataFrame()
df2.index.name = 'id'
df2['Relationship']= newdf.iloc[:,2]
df2['Occasion']= newdf.iloc[:,3]
df2['Budget']= newdf.iloc[:,5]
df2['Interest']= newdf.iloc[:,10]
df2['Gift']= newdf.iloc[:,6]
df2['Rating']= newdf.iloc[:,7]
df2['Link'] = newdf.iloc[:,8]
df2['Image Link'] = newdf.iloc[:,9]
df2['Cluster']= customer_segments
Newdata = pd.DataFrame()
Newdata=df2[df2['Cluster'] == new_customer_segment[0]]
# Newdata
Newdata.index.name = '_id'
# dataset['Relationship'].iloc[-1]
recommended_products = Newdata[Newdata['Rating'] >= 2.5]
temp = recommended_products
print("occasion data", occasion)
print("interest data", intrest)
if( len(temp)>5):
temp = recommended_products[recommended_products['Interest'] == intrest]
if(len(temp)>5):
recommended_products=temp
if( len(recommended_products)>5):
temp = recommended_products[recommended_products['Occasion'] == occasion]
if(len(temp)>5):
recommended_products=temp
if(len(recommended_products)>5):
temp = recommended_products[recommended_products['Relationship'] == relatioship]
if(len(temp)>5):
recommended_products=temp
# temp = recommended_products[recommended_products['Budget'] >= 0]
# if(len(temp)>=5):
# recommended_products=temp
# temp = recommended_products[recommended_products['MaxBudget'] <= (50000+5000)]
# if(len(temp)>=5):
# recommended_products=temp
recommended_products = recommended_products.sort_values(by=['Rating'],ascending=False)
# print(recommended_products['Gift'])
final_data = []
# print(recommended_products['Gift'])
def checkDuplicate(row):
for i in final_data:
if i['Gift']==row['Gift']:
return False
return True
i=8
for index, row in recommended_products.iterrows():
data = {}
if i>0 and checkDuplicate(row):
data['Gift'] = row['Gift']
data['ImageLink'] = row['Image Link']
data['Link'] = row['Link']
data['Rating'] = row['Rating']
final_data.append(data)
i=i-1
return jsonify(final_data)
if __name__ == "__main__":
app.run(debug=True)