-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
204 lines (171 loc) · 9.54 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
from os import getenv
from flask import Flask, render_template, url_for, request, redirect, Markup, make_response
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from dotenv import load_dotenv
import uuid
import json
import pymysql
# ml imports
import pickle
import pandas as pd
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.model_selection import train_test_split
load_dotenv()
mysql_user = getenv('MYSQL_USER')
mysql_pass = getenv('MYSQL_PASS')
deploy_url = getenv('DEPLOYMENT_URL')
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://' + \
mysql_user+':'+mysql_pass+'@localhost/globalsalesdata'
db = SQLAlchemy(app)
app.app_context().push()
class Tokens(db.Model):
id = db.Column(db.String(36), primary_key=True)
session = db.Column(db.String(36))
sts = db.Column(db.Boolean, default=False)
date_created = db.Column(db.DateTime, default=datetime.utcnow)
def __repr__(self):
return '<Task %r>' % self.id
@app.errorhandler(404)
def page_not_found(e):
return redirect('/generatetoken')
@app.route('/generatetoken', methods=['POST', 'GET'])
def gentoken(active=False, dashboard=False, report=False, story=False, deactivate=False, ml=False, generatetoken=True, activateaccount=False,
toasts=[], toastdata=[]):
if request.method == 'POST':
newid = uuid.uuid4()
newuser = Tokens(id=str(newid))
try:
db.session.add(newuser)
db.session.commit()
return {"token_id": str(newid)}
except:
return {"token_id": "Error : something when wrong"}
else:
return render_template('generatetoken.html', active=active, dashboard=dashboard, report=report, story=story, deactivate=deactivate, ml=ml, generatetoken=generatetoken, activateaccount=activateaccount, toasts=toasts, toastdata=toastdata, deploy_url=deploy_url)
@app.route('/activateacc', methods=['POST', 'GET'])
def activateacc(active=False, dashboard=False, report=False, story=False, deactivate=False, ml=False, generatetoken=False, activateaccount=True,
toasts=[], toastdata=[]):
if request.method == 'POST':
tokenid = request.form['tokenid']
toactivate = Tokens.query.get_or_404(tokenid)
if toactivate.sts == False:
toactivate.sts = True
sesid = uuid.uuid4()
toactivate.session = str(sesid)
db.session.commit()
toasts = ['success']
toastdata = [Markup('Successfully activated your account')]
active = True
activateaccount = False
dashboard = True
res = make_response(render_template('dashboard.html', active=active, dashboard=dashboard, report=report, story=story, deactivate=deactivate,
ml=ml, generatetoken=generatetoken, activateaccount=activateaccount, toasts=toasts, toastdata=toastdata, deploy_url=deploy_url))
res.set_cookie('tokenid', tokenid)
res.set_cookie('sessionid', str(sesid))
return res
else:
toasts = ['warning']
toastdata = [Markup('The Token has already been utilized <br> Please <a href="' +
deploy_url+'/generatetoken" class="link-text">generate new one</a>')]
return render_template('activateacc.html', active=active, dashboard=dashboard, report=report, story=story, deactivate=deactivate, ml=ml, generatetoken=generatetoken, activateaccount=activateaccount, toasts=toasts, toastdata=toastdata, deploy_url=deploy_url)
else:
return render_template('activateacc.html', active=active, dashboard=dashboard, report=report, story=story, deactivate=deactivate, ml=ml, generatetoken=generatetoken, activateaccount=activateaccount, toasts=toasts, toastdata=toastdata, deploy_url=deploy_url)
@app.route('/dashboard')
def dashboard(active=False, dashboard=True, report=False, story=False, deactivate=False, ml=False, generatetoken=False, activateaccount=False,
toasts=[], toastdata=[]):
sesid = request.cookies.get('sessionid', '')
if sesid != '':
row = Tokens.query.filter_by(session=sesid).first()
if row is None:
return gentoken(toasts=['danger'], toastdata=[Markup('bad session')])
else:
active = True
return render_template('dashboard.html', active=active, dashboard=dashboard, report=report, story=story, deactivate=deactivate, ml=ml, generatetoken=generatetoken, activateaccount=activateaccount, toasts=toasts, toastdata=toastdata, deploy_url=deploy_url)
else:
return gentoken(toasts=['warning'], toastdata=[Markup('no session available <br> please activate account or <a href="'+deploy_url+'/generatetoken" class="link-text">generate new token</a>')])
@app.route('/deactivate')
def deactivate(active=False, dashboard=False, report=False, story=False, deactivate=True, ml=False, generatetoken=False, activateaccount=False,
toasts=[], toastdata=[]):
sesid = request.cookies.get('sessionid', '')
row = Tokens.query.filter_by(session=sesid).first()
if row is None:
return gentoken(toasts=['danger'], toastdata=[Markup('bad session')])
else:
db.session.delete(row)
db.session.commit()
deactivate = False
geenratetoken = True
toasts = ['success']
toastdata = ['Successfully Deactivated your token.']
res = make_response(render_template('generatetoken.html', active=active, dashboard=dashboard, report=report, story=story, deactivate=deactivate,
ml=ml, generatetoken=generatetoken, activateaccount=activateaccount, toasts=toasts, toastdata=toastdata, deploy_url=deploy_url))
res.set_cookie('tokenid', '')
res.set_cookie('sessionid', '')
return res
@app.route('/story')
def story(active=False, dashboard=False, report=False, story=True, deactivate=False, ml=False, generatetoken=False, activateaccount=False,
toasts=[], toastdata=[]):
sesid = request.cookies.get('sessionid', '')
if sesid != '':
row = Tokens.query.filter_by(session=sesid).first()
if row is None:
return gentoken(toasts=['danger'], toastdata=[Markup('bad session')])
else:
active = True
return render_template('story.html', active=active, dashboard=dashboard, report=report, story=story, deactivate=deactivate, ml=ml, generatetoken=generatetoken, activateaccount=activateaccount, toasts=toasts, toastdata=toastdata, deploy_url=deploy_url)
else:
return gentoken(toasts=['warning'], toastdata=[Markup('no session available <br> please activate account or <a href="'+deploy_url+'/generatetoken" class="link-text">generate new token</a>')])
@app.route('/report')
def report(active=False, dashboard=False, report=True, story=False, deactivate=False, ml=False, generatetoken=False, activateaccount=False,
toasts=[], toastdata=[]):
sesid = request.cookies.get('sessionid', '')
if sesid != '':
row = Tokens.query.filter_by(session=sesid).first()
if row is None:
return gentoken(toasts=['danger'], toastdata=[Markup('bad session')])
else:
active = True
return render_template('report.html', active=active, dashboard=dashboard, report=report, story=story, deactivate=deactivate, ml=ml, generatetoken=generatetoken, activateaccount=activateaccount, toasts=toasts, toastdata=toastdata, deploy_url=deploy_url)
else:
return gentoken(toasts=['warning'], toastdata=[Markup('no session available <br> please activate account or <a href="'+deploy_url+'/generatetoken" class="link-text">generate new token</a>')])
@app.route('/ml')
def ml(active=False, dashboard=False, report=False, story=False, deactivate=False, ml=True, generatetoken=False, activateaccount=False,
toasts=[], toastdata=[]):
sesid = request.cookies.get('sessionid', '')
if sesid != '':
row = Tokens.query.filter_by(session=sesid).first()
if row is None:
return gentoken(toasts=['danger'], toastdata=[Markup('bad session')])
else:
active = True
return render_template('ml.html', active=active, dashboard=dashboard, report=report, story=story, deactivate=deactivate, ml=ml, generatetoken=generatetoken, activateaccount=activateaccount, toasts=toasts, toastdata=toastdata, deploy_url=deploy_url)
else:
return gentoken(toasts=['warning'], toastdata=[Markup('no session available <br> please activate account or <a href="'+deploy_url+'/generatetoken" class="link-text">generate new token</a>')])
# ml functions
@app.route('/mljson')
def mljson():
with open("static/pkl/data.json", encoding="utf8") as f:
final_out_data = json.load(f)
return final_out_data
# ml evalution function
def findAccuracy(value):
col_name = ['Ship Mode', 'Segment', 'City', 'State', 'Country', 'Market', 'Region',
'Category', 'Sub-Category', 'Product Name', 'Sales', 'Quantity',
'Discount', 'Profit', 'Shipping Cost', 'Item Value']
final_data = {}
for i in range(len(col_name)):
final_data[col_name[i]] = [value[col_name[i]]]
# data frame
dataFrame = pd.DataFrame(final_data)
file = "static/pkl/finalModel.pkl"
fileObject2 = open(file, "rb")
model = pickle.load(fileObject2, encoding='binary')
return model.predict(dataFrame)[0]
@app.route('/ml-evaluate', methods=['POST'])
def mlEvaluate():
return {"accuracy": int(findAccuracy(request.get_json(force=True)))}
if __name__ == "__main__":
app.run(debug=True)