-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
268 lines (220 loc) · 10.3 KB
/
app.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
import numpy as np
import pandas as pd
from flask import Flask, request, render_template,session
import pickle
from flask_mysqldb import MySQL
import MySQLdb.cursors
import matplotlib.pyplot as plt
import matplotlib.axes._axes as axes
import threading
def predict_churn(tenure,logindevice, citytier,warehouse, gender, numdevice, score, maritalstatus,numaddress,complain,lastorder, cashback, avg, paymentmode, ordercat ):
prediction = {
'Tenure': tenure,
'PreferredLoginDevice': logindevice,
'CityTier': citytier,
'WarehouseToHome': warehouse,
'Gender': gender,
'NumberOfDeviceRegistered': numdevice,
'SatisfactionScore': score,
'MaritalStatus': maritalstatus,
'NumberOfAddress': numaddress,
'Complain': complain,
'DaySinceLastOrder': lastorder,
'CashbackAmount': cashback,
'avg_cashbk_per_order': avg,
'PreferredPaymentMode_CC': 1 if paymentmode == 'CC' else 0,
'PreferredPaymentMode_COD': 1 if paymentmode == 'COD' else 0,
'PreferredPaymentMode_DC': 1 if paymentmode == 'DC' else 0,
'PreferredPaymentMode_E wallet': 1 if paymentmode == 'E wallet' else 0,
'PreferredPaymentMode_UPI': 1 if paymentmode == 'UPI' else 0,
'PreferedOrderCat_Fashion': 1 if ordercat == 'Fashion' else 0,
'PreferedOrderCat_Grocery': 1 if ordercat == 'Grocery' else 0,
'PreferedOrderCat_Laptop': 1 if ordercat == 'Laptop' else 0,
'PreferedOrderCat_Mobile': 1 if ordercat == 'Mobile' else 0,
'PreferedOrderCat_Others': 1 if ordercat == 'Others' else 0,
}
print(prediction)
df = pd.DataFrame(prediction,index=[0])
print(df)
pred=model.predict(df)
return pred
# making prediction
app = Flask(__name__)
app.secret_key = 'asdsdfsdfs13sdf_df%&'
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = ''
app.config['MYSQL_DB'] = 'ecommerce'
mysql = MySQL(app)
model = pickle.load(open('rfmodel.pkl', 'rb'))
@app.route('/')
def home():
return render_template('home.html')
@app.route('/predict',methods=['POST'])
def predict():
'''
For rendering results on HTML GUI
'''
if request.method == 'POST':
tenure = int(request.form['tenure'])
warehouse = int(request.form['warehousetohome'])
numdevice = int(request.form['numdevices'])
numaddress = int(request.form['numaddress'])
lastorder = int(request.form['lastorder'])
cashback = int(request.form['cashbackamount'])
ordercount=int(request.form['ordercount'])
logindevice = request.form['logindevice']
citytier = int(request.form['citytier'])
paymentmode = request.form['paymentmode']
ordercat = request.form['ordercat']
score = int(request.form['satisfactionscore'])
maritalstatus =request.form['maritalstatus']
gender = request.form['gender']
complain = int(request.form['complain'])
avg=cashback/ordercount
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
prediction = predict_churn(tenure,logindevice, citytier,warehouse, gender, numdevice, score, maritalstatus,numaddress,complain,lastorder, cashback, avg, paymentmode, ordercat)
if(prediction==1):
pred='Will Churn'
else:
pred='Will Not Churn'
if logindevice==1:
logindevice='Mobile Phone'
else:
logindevice='Laptop'
if gender==1:
gender="Male"
else:
gender="Female"
if citytier==1:
citytier="Tier 1"
elif citytier==2:
citytier="Tier 2"
else:
citytier="Tier 3"
if complain==1:
complain="Yes"
else:
complain="No"
if maritalstatus==0:
maritalstatus="Divorced"
elif maritalstatus==1:
maritalstatus="Married"
else:
maritalstatus="Single"
if paymentmode=="DC":
paymentmode="Debit Card"
elif paymentmode=="CC":
paymentmode="Credit Card"
elif paymentmode=="COD":
paymentmode="Cash On Delivery"
cursor.execute('INSERT INTO prediction VALUES (NULL, % s, % s, % s, % s, % s, % s, % s, % s, % s, % s, % s, % s,%s,%s,%s,%s)', (tenure,logindevice,citytier,warehouse,gender,numdevice,score,maritalstatus,numaddress,complain,lastorder,cashback,avg,paymentmode,ordercat,pred))
mysql.connection.commit()
return render_template('churnpred.html', prediction=prediction,display="none",display_a="block")
@app.route('/login',methods=['POST'])
def login():
msg = ''
if request.method == 'POST' and 'username' in request.form and 'password' in request.form:
username= request.form['username']
password= request.form['password']
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM admin WHERE username = % s AND password = % s', (username, password, ))
account = cursor.fetchone()
query = """SELECT * FROM prediction"""
cursor.execute(query)
rows = cursor.fetchall()
if rows==[]:
no=0
churn=0
not_churn=0
else:
df = pd.DataFrame(rows)
churn_percentage = df['Churn'].value_counts()['Will Churn'] / df['Churn'].value_counts().sum() * 100
churn=df['Churn'].value_counts()['Will Churn']
not_churn=df['Churn'].value_counts()['Will Not Churn']
no=df.Id.nunique()
# Create a thread to create the Matplotlib GUI
def create_plot():
churn_pie = df['Churn'].value_counts().plot.pie(labels=['Will Not Churn','Will Churn'], figsize=(5,5), autopct=lambda p: '{:.1f}%'.format(p))
churn_pie.plot()
plt.savefig('./static/images/churn_pie.png')
thread = threading.Thread(target=create_plot)
thread.start()
if account:
session['loggedin'] = True
#session['id'] = account['id']
session['username'] = account['username']
msg = 'Logged in successfully !'
return render_template('dashboard.html', msg = msg,no=no,churn=churn,not_churn=not_churn,churn_pie='./static/images/churn_pie.png',churn_percentage=churn_percentage)
else:
msg = 'Incorrect username / password !'
return render_template('login.html', msg = msg)
@app.route('/signup',methods=['POST'])
def signup():
if request.method == 'POST' and 'username' in request.form and 'email' in request.form and 'password' in request.form:
username= request.form['username']
password= request.form['password']
email=request.form['email']
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('INSERT INTO admin VALUES ( % s, % s, % s)', (username,email,password))
mysql.connection.commit()
return render_template('login.html')
@app.route("/logout")
@app.route("/logout")
def logout():
session['loggedin']=False
return render_template("home.html")
@app.route("/view")
def view():
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM prediction')
data = cursor.fetchall()
print(data)
mysql.connection.commit()
return render_template("view.html",data=data)
@app.route("/loginpage")
def loginpage():
#session['loggedin,methods=['POST']False
return render_template("login.html")
@app.route("/churnpred")
def churnpred():
#session['loggedin,methods=['POST']False
return render_template("churnpred.html")
@app.route('/dashboard')
def dashboard():
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
query = """SELECT * FROM prediction"""
cursor.execute(query)
rows = cursor.fetchall()
df = pd.DataFrame(rows)
churn_percentage = df['Churn'].value_counts()['Will Churn'] / df['Churn'].value_counts().sum() * 100
churn=df['Churn'].value_counts()['Will Churn']
not_churn=df['Churn'].value_counts()['Will Not Churn']
no=df.Id.nunique()
# Create a thread to create the Matplotlib GUI
def create_plot():
churn_pie = df['Churn'].value_counts().plot.pie(labels=['Will Not Churn','Will Churn'], figsize=(5,5), autopct=lambda p: '{:.1f}%'.format(p))
churn_pie.plot()
plt.savefig('./static/images/churn_pie.png')
thread = threading.Thread(target=create_plot)
thread.start()
# Create the pie chart in the main thread
# churn_pie = df['Churn'].value_counts().plot.pie(labels=['Will Not Churn','Will Churn'], figsize=(5,5))
# churn_pie.plot()
# plt.savefig('./static/images/churn_pie.png')
return render_template('dashboard.html',no=no,churn=churn,not_churn=not_churn,churn_pie='./static/images/churn_pie.png',churn_percentage=churn_percentage)
@app.route("/search",methods=['POST'])
def search():
if request.method == 'POST' and 'custid' in request.form:
cust_id= request.form['custid']
cursor = mysql.connection.cursor(MySQLdb.cursors.DictCursor)
cursor.execute('SELECT * FROM prediction where Id={}'.format(cust_id))
data = cursor.fetchall()
print(data)
mysql.connection.commit()
return render_template("custpred.html",data=data)
@app.route("/view1")
def view1():
return render_template("customerno.html")
if __name__ == "__main__":
app.run(debug=True)