-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
265 lines (186 loc) · 8.94 KB
/
main.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
from flask import Flask
from flask_socketio import SocketIO
from flask_sqlalchemy import SQLAlchemy
from hashlib import sha256
from pathlib import Path
import pandas as pd
import numpy as np
import tensorflow as tf
import flask
import secrets
import json
import random
import time
import pickle
class eeg_data_collection():
def __init__(self, age=10, gender=0):
# eeg_data = eeg.collect().extend([age, gender])
self.sample_eeg_data = [
[56.0, 43.0, 278.0, 301963.0, 90612.0, 33735.0, 23991.0, 27946.0, 45097.0, 33228.0, 8293.0, 10, 0],
[40.0, 35.0, -50.0, 73787.0, 28083.0, 1439.0, 2240.0, 2746.0, 3687.0, 5293.0, 2740.0, 10, 0],
[47.0, 57.0, -5.0, 2012240.0, 129350.0, 61236.0, 17084.0, 11488.0, 62462.0, 49960.0, 33932.0, 10, 0]
]
self.eeg_data = pd.DataFrame()
def get_eeg(self):
selected = pd.DataFrame(self.sample_eeg_data[random.randint(0, 2)])
self.eeg_data = pd.concat([self.eeg_data, selected], ignore_index=True).groupby(level=0).mean()
def return_eeg_data(self):
return self.eeg_data
def encode_pass(pwd: str) -> str:
return sha256(pwd.encode()).hexdigest()
if __name__ == '__main__':
start = False
saved_model = str(Path('__file__').resolve().parent) + r'\Model\Model_Data\Model.h5'
saved_stdscaler = str(Path('__file__').resolve().parent) + r'\Model\Model_Data\StandardScaler.pkl'
model = tf.keras.models.load_model(saved_model)
with open(saved_stdscaler, 'rb') as f:
sc = pickle.load(f)
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///site.db'
app.config['SECRET_KEY'] = secrets.token_urlsafe(16)
socketio = SocketIO(app, async_mode='threading')
db = SQLAlchemy(app)
class Database(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(), unique=False, nullable=False)
rno = db.Column(db.String(), unique=True, nullable=False)
pwd = db.Column(db.String(), unique=False, nullable=False)
ts = db.Column(db.String(), unique=False, nullable=False)
@app.before_request
def only_once():
if 'name' not in flask.session:
flask.session['name'] = ''
flask.session['logged'] = False
flask.session['test'] = False
flask.session['id'] = None
data_add = {
'name': ['Samyak', 'Yugayu', 'Empty'],
'rno': ['12345', '11111', '00000'],
'pwd': [encode_pass('Samyak'), encode_pass('Yugayu'), encode_pass('Empty')],
'ts': [json.dumps({'Test1': 8}), json.dumps({'Test1': 7, 'Test2': 2}), json.dumps({})]
}
db.drop_all()
db.create_all()
for i in range(len(list(data_add.values())[0])):
db.session.add(Database(name=data_add['name'][i], rno=data_add['rno'][i], pwd=data_add['pwd'][i], ts=data_add['ts'][i]))
db.session.commit()
@app.route('/login/', methods=['GET', 'POST'])
def login():
global start
start = False
if flask.session['logged'] is True:
return flask.redirect(flask.url_for('main'))
if flask.request.method == 'POST':
name = flask.request.form['name']
rno = flask.request.form['roll']
pwd = encode_pass(flask.request.form['password'])
if name != '' and rno != '' and pwd != encode_pass(''):
if Database.query.filter_by(name=name, rno=rno, pwd=pwd).all():
flask.session['logged'] = True
flask.session['name'] = name
flask.session['id'] = Database.query.filter_by(name=name, rno=rno, pwd=pwd).one().id
return flask.redirect(flask.url_for('main'))
return flask.render_template('index.html', _name=name, rno=rno, error='Invalid entry!')
return flask.render_template('index.html', _name=name, rno=rno, error='One or more fields are empty.')
return flask.render_template('index.html', _name='', rno='', error='')
@app.route('/logout/')
def logout():
flask.session['logged'] = False
flask.session['name'] = ''
flask.session['id'] = None
flask.session['test'] = False
return flask.redirect(flask.url_for('main'))
@app.route('/<name>/')
def account(name):
global start
start = False
if flask.session['logged'] is not False and name == flask.session['name']:
if Database.query.get(flask.session['id']).ts == json.dumps({}):
return flask.redirect(flask.url_for('notification', name=name))
messages = {
'Consistantly good': 'Congrats! Your are performing well!',
'Decent': 'Your scores are below average.',
'Bad': 'Your scores are really low, and maybe at risk of dyslexia.'
}
test_values = list(json.loads(Database.query.get(flask.session['id']).ts).values())
avg = sum(test_values) / len(test_values)
percent = avg * 10
not_hide = True
pass_url = ''
if percent >= 70:
gm = list(messages.keys())[0]
m = list(messages.values())[0]
not_hide = False
elif 30 < percent < 70:
gm = list(messages.keys())[1]
m = list(messages.values())[1]
pass_url = flask.url_for('tips')
else:
gm = list(messages.keys())[2]
m = list(messages.values())[2]
pass_url = flask.url_for('specialists')
return flask.render_template('report.html', pass_url=pass_url, tips_value=not_hide, _value=percent, _list=test_values, gist_message=gm, test_message=m, name=name)
return flask.redirect(flask.url_for('main'))
@app.route('/<name>/notification/', methods=['GET', 'POST'])
def notification(name):
global start
start = False
if flask.session['logged'] is not False and name == flask.session['name']:
num = len(json.loads(Database.query.get(flask.session['id']).ts)) + 1
if flask.request.method == 'POST':
start = True
flask.session['test'] = True
return flask.redirect(flask.url_for('take_test', name=flask.session['name']))
return flask.render_template('notification.html', val=num)
return flask.redirect(flask.url_for('main'))
@app.route('/tips/')
def tips():
if flask.session['logged'] is True:
return flask.render_template('tips.html')
return flask.redirect(flask.url_for('main'))
@app.route('/specialists/')
def specialists():
if flask.session['logged'] is True:
return flask.render_template('doctor.html')
return flask.redirect(flask.url_for('main'))
@app.route('/<name>/test/', methods=['GET', 'POST'])
def take_test(name):
global start, sc, model, saved_stdscaler
if flask.session['logged'] is not False and name == flask.session['name']:
if flask.session['test'] is False:
return flask.redirect(flask.url_for('main'))
eeg = eeg_data_collection()
start = True
def eeg_func():
while start:
eeg.get_eeg()
time.sleep(1)
socketio.start_background_task(eeg_func)
if flask.request.method == 'POST':
flask.session['test'] = False
start = False
corr_ans = ['benny', 'forest', 'picnic', 'sandwich', 'sally']
ans = [flask.request.form[f'ans{i}'] for i in range(1, 6)]
scored = 0
for i, a in enumerate(ans):
if corr_ans[i] in a.lower(): scored += 1
data = eeg.return_eeg_data()
value = np.squeeze(model.predict([sc.transform(data.to_numpy().T)])) * 30
percent = (scored/5) * 70
percent = round(percent + value, 2)
data_dict = json.loads(Database.query.get(flask.session['id']).ts)
data_dict[f'Test{len(data_dict) + 1}'] = round(percent/10)
data_dict = json.dumps(data_dict)
Database.query.get(flask.session['id']).ts = data_dict
db.session.commit()
return flask.redirect(flask.url_for('main'))
return flask.render_template('test.html')
return flask.redirect(flask.url_for('main'))
@app.route('/')
def main():
global start
start = False
if flask.session['logged'] is False:
return flask.redirect(flask.url_for('login'))
return flask.redirect(flask.url_for('account', name=flask.session['name']))
socketio.run(app, host='0.0.0.0', port=80)