abhicodes commited on
Commit
f5881f3
1 Parent(s): 2b24bc1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +565 -1006
app.py CHANGED
@@ -1,1137 +1,696 @@
1
  from flask import Flask, render_template, request, redirect, url_for, session
2
  from nltk.sentiment.vader import SentimentIntensityAnalyzer
3
- from flask_mysqldb import MySQL
4
  import nltk
5
- import io
6
  import bcrypt
7
  import datetime
8
  import json
9
- from flask_mail import *
10
- import random
11
- import smtplib, ssl
12
  from email.message import EmailMessage
13
  import secrets
14
  import string
15
- import time
16
 
17
  nltk.download('vader_lexicon')
18
 
19
- class SmileCheckApp:
20
- def __init__(self):
21
- self.app = Flask(__name__)
22
- self.app.static_folder = 'static'
23
- self.app.static_url_path = '/static'
24
-
25
- self.app.secret_key = "smilecheck-abhi-2023"
26
-
27
- self.app.config['MYSQL_HOST'] = 'sql12.freemysqlhosting.net'
28
- self.app.config['MYSQL_USER'] = 'sql12660485'
29
- self.app.config['MYSQL_PASSWORD'] = 'UxU15DlGpj'
30
- self.app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
31
- self.app.config['MYSQL_PORT'] = 3306
32
-
33
- mysql = MySQL(self.app)
34
-
35
- # @app.before_request
36
- # def before_request():
37
- # if request.path != '/logout' and 'email' in session:
38
- # session.permanent = True
39
- # app.permanent_session_lifetime = datetime.timedelta(minutes=1)
40
- #
41
- # @app.teardown_request
42
- # def teardown_request(exception=None):
43
- # if not session.permanent and 'email' in session: return redirect(url_for('logout'))
44
-
45
- @self.app.route('/')
46
- def index():
47
- return render_template("index.html")
48
-
49
-
50
- @self.app.route('/home', methods=["GET", "POST"])
51
- def home():
52
- if request.method == 'GET':
53
- if 'email' in session:
54
- self.app.config['MYSQL_DB'] = session['database']
55
- curh = mysql.connection.cursor()
56
- if session['usertype'] == 0:
57
- curh.execute("SELECT `assessid`, `name` FROM assessments")
58
- typedata = curh.fetchall()
59
-
60
- curh.execute("SELECT `id`, `type` FROM custom WHERE id=%s", (session['id'],))
61
- given = curh.fetchall()
62
- isdone = []
63
- for give in given:
64
- isdone.append(give['type'])
65
-
66
- typesgiven = []
67
- for type in typedata:
68
- typesgiven.append(type['assessid'])
69
-
70
- curh.execute("SELECT `name`, `happy`, `datetime` FROM `custom`, `assessments` WHERE custom.type = assessments.assessId AND id=%s", (session['id'],))
71
- previous = curh.fetchall()
72
-
73
- return render_template("home.html", typedata=typedata, given=isdone, previous=previous)
74
-
75
- elif session['usertype'] == 1:
76
- return redirect(url_for('admin'))
77
- mysql.connection.commit()
78
- curh.close()
79
- else:
80
- return redirect(url_for('login'))
81
-
82
- if request.method == 'POST':
83
- if 'email' in session:
84
- self.app.config['MYSQL_DB'] = session['database']
85
-
86
- curh = mysql.connection.cursor()
87
-
88
- if 'fname' in request.form:
89
- fname = request.form['fname']
90
- femail = request.form['femail']
91
- feedback = request.form['feedback']
92
- curh.execute("INSERT INTO `feedbacks`(`name`, `email`, `feedback`) VALUES (%s, %s, %s)", (fname, femail, feedback,))
93
- mysql.connection.commit()
94
- curh.close()
95
- session['feed'] = 1
96
- return redirect(url_for('home'))
97
-
98
- curh.execute("SELECT * FROM users WHERE email=%s", (session['email'],))
99
- user = curh.fetchone()
100
-
101
- session['type'] = request.form['type']
102
-
103
- curh.execute("SELECT `id`, `type` FROM custom WHERE id=%s AND type=%s", (session['id'], session['type'],))
104
- given = curh.fetchone()
105
- mysql.connection.commit()
106
- curh.close()
107
-
108
- if given == None:
109
- return redirect(url_for('form'))
110
- else:
111
- return redirect(url_for('result'))
112
-
113
- else:
114
- return redirect(url_for('login'))
115
-
116
- return render_template("home.html")
117
-
118
-
119
- @self.app.route('/register', methods=["GET", "POST"])
120
- def register():
121
- now = datetime.datetime.now()
122
- if request.method == 'GET':
123
- return render_template("register.html", error_code=999, message_code=999)
124
-
125
- if request.method == 'POST':
126
- database = request.form['database']
127
- if database == 'database1':
128
- self.app.config['MYSQL_DB'] = 'test'
129
- session['database'] = self.app.config['MYSQL_DB']
130
- elif database == 'database2':
131
- self.app.config['MYSQL_DB'] = 'test2'
132
- session['database'] = self.app.config['MYSQL_DB']
133
-
134
- name = request.form['name']
135
- email = request.form['email']
136
- cur = mysql.connection.cursor()
137
- cur.execute("SELECT * FROM users WHERE email = %s", (email,))
138
- user = cur.fetchone()
139
- mysql.connection.commit()
140
- cur.close()
141
-
142
- if user:
143
- error = 'Email address already in use. Please use a different email address.'
144
- return render_template('register.html', error=error, error_code=550, message_code=569)
145
- else:
146
- session['name'] = name
147
- session['email'] = email
148
- usertype = 'student'
149
- session['pretype'] = usertype
150
- password = request.form['password'].encode('utf-8')
151
- hash_password = bcrypt.hashpw(password, bcrypt.gensalt())
152
- session['hash'] = hash_password
153
-
154
- msg = EmailMessage()
155
-
156
- # otp = random.randint(100000, 999999)
157
- alphabet = string.ascii_letters + string.digits
158
- otp = 'smilecheck-user-'+''.join(secrets.choice(alphabet) for i in range(30))
159
- session['otp'] = otp
160
- # with open('static\email.html?name={name}&otp={otp}', 'rb') as f:
161
- # html_content = f.read().decode('utf-8')
162
- # msg.set_content(html_content, subtype='html')
163
-
164
- # msg.set_content("The body of the email is here")
165
- msg["Subject"] = "SmileCheck Verification"
166
- msg["From"] = "smilecheck100@gmail.com"
167
- msg["To"] = email
168
- link = f"http://127.0.0.1:5000/verify/{otp}"
169
-
170
- html_content = render_template('email.html', name=name, link=link)
171
- msg.set_content(html_content, subtype='html')
172
-
173
- context = ssl.create_default_context()
174
-
175
- with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
176
- smtp.login('smilecheck23@gmail.com', 'dczcfrdkthwcfoqu')
177
- smtp.send_message(msg)
178
-
179
- return render_template('register.html', message='An Verification Email has been sent to your email address.', message_code=560, error_code=568)
180
 
181
- return redirect(url_for('home'))
182
 
183
- # def getmail():
184
- # if request.method=="POST":
185
- # email = request.form['email']
186
- # code = hashlib.md5(str(random.randint(0, 1000000)).encode()).hexdigest()
187
- # session['code'] = code
188
- # link = f"http://127.0.0.1:5000/verify/{code}"
189
- # send_email(email, link)
190
- # return "A verification email has been sent to your email address. Please click the link in the email to verify your email."
191
-
192
- @self.app.route('/verify/<otp>')
193
- def verify(otp):
194
- now = datetime.datetime.now()
195
- if str(session['otp']) == otp:
196
- self.app.config['MYSQL_DB'] = session['database']
197
-
198
- cur = mysql.connection.cursor()
199
- cur.execute("INSERT INTO users (name, email, password) VALUES (%s,%s,%s)", (session['name'], session['email'], session['hash'],))
200
-
201
- if session['pretype'] == 'student':
202
- cur.execute("UPDATE `users` SET `usertype` = %s WHERE `email`=%s", (0, session['email'],))
203
- session['usertype'] = 0
204
- elif session['pretype'] == 'admin':
205
- cur.execute("UPDATE `users` SET `usertype` = %s WHERE `email`=%s", (1, session['email'],))
206
- session['usertype'] = 1
207
 
208
- # cur.execute("SELECT `id` FROM users WHERE email = %s", (session['email'],))
209
- # uid = cur.fetchone()
210
- # session['id'] = uid['id']
211
- # cur.execute("INSERT INTO session (id, email, action, actionC, datetime) VALUES (%s, %s, %s, %s, %s)", (session['id'], session['email'], 'Logged In - Session Started', 1, now,))
212
- mysql.connection.commit()
213
- cur.close()
214
 
215
- #destroy session['otp'] and session['hash']
216
- session.clear()
217
 
218
- redi = 'login'
219
- return render_template('verify.html', message=111, redirect_url=redi)
 
220
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
  else:
222
- redi = 'register'
223
- return render_template('verify.html', message=999, redirect_url=redi)
224
-
225
- # def send_email(email, link):
226
- # subject = "Verify Your Email"
227
- # body = f"Please click the following link to verify your email: {link}"
228
- # message = f"Subject: {subject}\n\n{body}"
229
- # sender_email = 'legendVI001@gmail.com' # replace with your email
230
- # sender_password = 'ABC321VI01' # replace with your password
231
- #
232
- # with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
233
- # smtp.login(sender_email, sender_password)
234
- # smtp.sendmail(sender_email, email, message)
235
-
236
- @self.app.route('/login', methods=["GET", "POST"])
237
- def login():
238
- if request.method == 'GET':
239
- return render_template("login.html", error_code=999)
240
-
241
- if request.method == 'POST':
242
- now = datetime.datetime.now()
243
- database = request.form['database']
244
- if database == 'database1':
245
- self.app.config['MYSQL_DB'] = 'test'
246
- elif database == 'database2':
247
- self.app.config['MYSQL_DB'] = 'test2'
248
-
249
- email = request.form['email']
250
- password = request.form['password'].encode('utf-8')
251
-
252
- curl = mysql.connection.cursor()
253
- curl.execute("SELECT * FROM users WHERE email=%s", (email,))
254
- user = curl.fetchone()
255
-
256
- if user != None:
257
- if bcrypt.hashpw(password, user["password"].encode('utf-8')) == user["password"].encode('utf-8'):
258
-
259
- curl.execute("SELECT * FROM session WHERE email=%s ORDER BY `datetime` DESC LIMIT 1", (email,))
260
- userses = curl.fetchone()
261
-
262
- if userses == None or userses['actionC']==0:
263
- session['id'] = user['id']
264
- session['name'] = user['name']
265
- session['email'] = user['email']
266
- session['database'] = self.app.config['MYSQL_DB']
267
-
268
- curl.execute("INSERT INTO session (id, email, action, actionC, datetime) VALUES (%s, %s, %s, %s, %s)", (session['id'], session['email'], 'Logged In - Session Started', 1, now,))
269
- mysql.connection.commit()
270
- curl.close()
271
-
272
- if user['usertype'] == 0:
273
- session['usertype'] = 0
274
- return redirect(url_for('home'))
275
- elif user['usertype'] == 1:
276
- session['usertype'] = 1
277
- return redirect(url_for('admin'))
278
-
279
- elif userses['actionC'] == 1:
280
- return render_template("login.html", error="Error: Session already in use.", error_code=450)
281
-
282
- else:
283
- return render_template("login.html", error="Error: Password or Email are incorrect.", error_code=451)
284
-
285
- else:
286
- return render_template("login.html", error="Error: User not found. Please register.", error_code=452)
287
-
288
- mysql.connection.commit()
289
- curl.close()
290
- else:
291
- return render_template("login.html")
292
 
 
 
293
 
294
- @self.app.route('/forgot', methods=["GET", "POST"])
295
- def forgot():
296
- if request.method == 'GET':
297
- return render_template("forgot.html")
298
 
299
- if request.method == 'POST':
300
- now = datetime.datetime.now()
301
- self.app.config['MYSQL_DB'] = 'test'
302
 
303
- email = request.form['email']
304
- session['email'] = email
 
 
305
 
306
- curl = mysql.connection.cursor()
307
- curl.execute("SELECT * FROM users WHERE email=%s", (email,))
308
- user = curl.fetchone()
 
 
 
 
 
309
 
310
- mysql.connection.commit()
311
- curl.close()
 
 
 
 
 
312
 
313
- if user != None:
314
- msg = EmailMessage()
 
 
 
 
 
 
 
 
 
315
 
316
- name= user['name']
317
 
318
- alphabet = string.ascii_letters + string.digits
319
- otp = 'smilecheck-pass-' + ''.join(secrets.choice(alphabet) for i in range(30))
320
- session['otp'] = otp
321
- msg["Subject"] = "SmileCheck Verification"
322
- msg["From"] = "smilecheck100@gmail.com"
323
- msg["To"] = email
324
- link = f"http://127.0.0.1:5000/password/{otp}"
325
 
326
- html_content = render_template('pass.html', name=name, link=link)
327
- msg.set_content(html_content, subtype='html')
 
 
328
 
329
- context = ssl.create_default_context()
 
330
 
331
- with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
332
- smtp.login('smilecheck23@gmail.com', 'dczcfrdkthwcfoqu')
333
- smtp.send_message(msg)
334
 
335
- return render_template('register.html', message='An Verification Email has been sent to your email address.', message_code=560, error_code=568)
336
 
337
- else:
338
- return render_template("forgot.html", mess="No such User Found.")
339
 
 
 
 
 
340
 
341
- @self.app.route('/password/<otp>', methods=["GET", "POST"])
342
- def password(otp):
343
- now = datetime.datetime.now()
344
- if str(session['otp']) == otp:
345
- redi = 'change'
346
- return render_template('password.html', message=111, redirect_url=redi)
347
- else:
348
- redi = 'login'
349
- return render_template('password.html', message=999, redirect_url=redi)
350
 
 
 
 
 
 
 
351
 
352
- @self.app.route('/change', methods=["GET", "POST"])
353
- def change():
354
- if request.method == 'GET':
355
- return render_template("change.html")
356
 
357
- if request.method == 'POST':
358
- self.app.config['MYSQL_DB'] = 'test'
359
 
360
- password = request.form['password'].encode('utf-8')
361
- hash_password = bcrypt.hashpw(password, bcrypt.gensalt())
362
 
363
- curl = mysql.connection.cursor()
364
- curl.execute("UPDATE `users` SET `password`=%s WHERE email=%s", (hash_password, session['email'],))
365
- user = curl.fetchone()
366
 
367
- mysql.connection.commit()
368
- curl.close()
369
 
370
- session.clear()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
 
372
- return redirect(url_for('login'))
 
 
373
 
 
 
374
 
375
- @self.app.route('/admin', methods=["GET", "POST"])
376
- def admin():
377
- if 'email' in session:
378
- if session['usertype'] == 0:
 
 
 
 
 
 
 
 
 
379
  return redirect(url_for('home'))
 
 
 
 
380
  else:
381
- return redirect(url_for('login'))
382
 
383
- if request.method == 'GET':
384
- if 'email' in session:
385
- self.app.config['MYSQL_DB'] = session['database']
386
- cura = mysql.connection.cursor()
387
- cura.execute("SELECT `assessid`, `name` FROM assessments")
388
- typedata = cura.fetchall()
389
- cura.execute("SELECT `id`, `type` FROM custom")
390
- given = cura.fetchall()
391
 
392
- isdone = []
393
- for give in given:
394
- isdone.append(give['type'])
 
395
 
396
- cura.execute("SELECT `id`, `name`, `email`, `isdone` FROM `users` WHERE `usertype` = 0")
397
- res = cura.fetchall()
398
 
399
- cura.execute("SELECT `assessId`, `name`, `description`, `Questions`, `average` FROM `assessments`")
400
- que = cura.fetchall()
 
 
401
 
402
- cura.execute("SELECT `id`, `type`, `name` FROM `custom`, `assessments` WHERE custom.type = assessments.assessId")
403
- abc = cura.fetchall()
404
 
405
- ahi = 0.0
406
- for assess in que:
407
- if assess['assessId'] == 101:
408
- ahi = assess['average']
409
 
410
- ts = len(res)
411
- tas = len(isdone)
 
412
 
413
- cura.execute("SELECT `name`, `email`, `feedback` FROM `feedbacks`")
414
- feeds = cura.fetchall()
415
 
416
- mysql.connection.commit()
417
- cura.close()
418
 
419
- return render_template("admin.html", typedata=typedata, given=given, result=res, assess=que, abc=abc, ts=ts, ahi=ahi, tas=tas, feeds= feeds)
420
 
421
- if request.method == "POST":
422
- self.app.config['MYSQL_DB'] = session['database']
 
 
 
 
 
423
 
424
- if 'resid' in request.form:
425
- resid = request.form.get('resid')
426
- types = request.form.get('type')
427
 
428
- session['id'] = resid
429
- session['type'] = types
 
430
 
431
- return redirect(url_for('result'))
432
 
433
- elif 'delete' in request.form:
434
- cura = mysql.connection.cursor()
435
- deleteId = request.form['delete']
436
- cura.execute("DELETE FROM `assessments` WHERE `assessId`= %s", (deleteId,))
437
- mysql.connection.commit()
438
- cura.close()
439
- return redirect(url_for('admin'))
440
 
441
- # cura = mysql.connection.cursor()
442
- # cura.execute("SELECT * FROM `result` WHERE `id` = %s", (resid,))
443
- # chart = cura.fetchone()
444
- #
445
- # cura.execute("SELECT * FROM `assessments` WHERE `assessid` = %s", (type,))
446
- # chart = cura.fetchone()
447
- # mysql.connection.commit()
448
- # cura.close()
449
- #
450
- # return render_template('result.html')
451
 
452
- return render_template('admin.html')
 
 
 
 
 
 
 
453
 
454
 
455
- @self.app.route('/form', methods=["GET", "POST"])
456
- def form():
457
- if 'email' not in session:
458
- return redirect(url_for('login'))
459
 
460
- if request.method == "GET":
461
- self.app.config['MYSQL_DB'] = session['database']
462
- typeid = session['type']
463
- curf = mysql.connection.cursor()
464
- curf.execute("SELECT `name`, `description`, `Questions`, `types` FROM assessments WHERE assessid = %s", (typeid,))
465
- questions = curf.fetchone()
466
- mysql.connection.commit()
467
- curf.close()
468
 
469
- return render_template("form.html", questions=questions)
 
470
 
471
- if request.method == "POST":
472
- self.app.config['MYSQL_DB'] = session['database']
473
 
474
- email = session["email"]
 
475
 
476
- '''Sentiment analysis for each response...'''
477
 
478
- data = request.form.to_dict()
479
 
480
- length = len(request.form)
481
- inp = []
482
- for i in range(0, length):
483
- inp.append(data['inp' + str(i + 1) + ''])
484
 
485
- sid_obj = SentimentIntensityAnalyzer()
 
 
 
 
 
 
486
 
487
- compound = []
488
- for i in range(0, length):
489
- # locals()[f"sentiment_dict{i}"] = sid_obj.polarity_scores(data['inp'+ (i+1) +''])
490
- compound.append(sid_obj.polarity_scores(data['inp' + str(i + 1) + ''])['compound'] * 100)
491
 
492
- '''SQL Queries for data storing in database...'''
493
 
494
- now = datetime.datetime.now()
495
- cur = mysql.connection.cursor()
496
 
497
- query = "INSERT INTO `custom` (`Id`, `type`, `response`, `result`, `datetime`) VALUES (%s, %s, %s, %s, %s)"
498
- cur.execute(query, (session['id'], session['type'], json.dumps(inp), json.dumps(compound), now,))
499
 
500
- query = "UPDATE `users` SET `isdone`=%s WHERE `id`=%s"
501
- cur.execute(query, (1, session['id'],))
502
 
503
- cur.execute("SELECT * FROM `custom` WHERE id=%s AND type=%s", (session['id'], session['type'],))
504
- res = cur.fetchone()
505
 
506
- cur.execute("SELECT qval FROM `assessments` WHERE assessId=%s", (session['type'],))
507
- qval = cur.fetchone()
 
508
 
509
- happy = []
510
- multi = []
511
- multi = eval(qval['qval'])
512
- happy = eval(res['result'])
513
- for j in range(len(happy)):
514
- happy[j] = happy[j] * multi[j]
515
 
516
- min_value = min(compound)
517
- max_value = max(compound)
518
- scaled_values = [(value - min_value) / (max_value - min_value) * 5 for value in compound]
519
 
520
- happy_index = round(sum(scaled_values) / len(scaled_values), 2)
521
- # happy_score = round(sum(happy) / len(happy), 4)
522
 
523
- query = "UPDATE `custom` SET `happy`=%s WHERE `id`=%s AND `type`=%s"
524
- cur.execute(query, (happy_index, session['id'], session['type'],))
525
 
526
- cur.execute("SELECT `happy` FROM `custom` WHERE type=%s", (session['type'],))
527
- avg_dict = cur.fetchall()
528
 
529
- avg_list = [d['happy'] for d in avg_dict if isinstance(d['happy'], float)] + [item for d in avg_dict if isinstance(d['happy'], (list, tuple)) for item in d['happy']]
530
 
531
- avg_score = round(sum(avg_list)/len(avg_list), 2)
 
 
 
532
 
533
- query = "UPDATE `assessments` SET `average`=%s WHERE `assessId`=%s"
534
- cur.execute(query, (avg_score, session['type'],))
535
 
536
- mysql.connection.commit()
537
- cur.close()
538
 
539
- '''Re-render template...'''
540
 
541
- return redirect(url_for('result'))
 
 
 
 
 
 
 
 
 
 
 
 
 
542
 
543
- #*********************************************** Further optimization....
544
- # form_data = request.form.to_dict()
545
- #***********************************************
546
- #
547
- # inp1 = request.form.get("inp1")
548
- # inp2 = request.form.get("inp2")
549
- # inp3 = request.form.get("inp3")
550
- # inp4 = request.form.get("inp4")
551
- # inp5 = request.form.get("inp5")
552
- # inp6 = request.form.get("inp6")
553
- # inp7 = request.form.get("inp7")
554
- # inp8 = request.form.get("inp8")
555
- # inp9 = request.form.get("inp9")
556
- # inp10 = request.form.get("inp10")
557
- #
558
- # sid_obj = SentimentIntensityAnalyzer()
559
- #
560
- # sentiment_dict1 = sid_obj.polarity_scores(inp1)
561
- # sentiment_dict2 = sid_obj.polarity_scores(inp2)
562
- # sentiment_dict3 = sid_obj.polarity_scores(inp3)
563
- # sentiment_dict4 = sid_obj.polarity_scores(inp4)
564
- # sentiment_dict5 = sid_obj.polarity_scores(inp5)
565
- # sentiment_dict6 = sid_obj.polarity_scores(inp6)
566
- # sentiment_dict7 = sid_obj.polarity_scores(inp7)
567
- # sentiment_dict8 = sid_obj.polarity_scores(inp8)
568
- # sentiment_dict9 = sid_obj.polarity_scores(inp9)
569
- # sentiment_dict10 = sid_obj.polarity_scores(inp10)
570
- # # negative = sentiment_dict['neg']
571
- # # neutral = sentiment_dict['neu']
572
- # # positive = sentiment_dict['pos']
573
- # compound1 = sentiment_dict1['compound'] * 100
574
- # compound2 = sentiment_dict2['compound'] * 100
575
- # compound3 = sentiment_dict3['compound'] * 100
576
- # compound4 = sentiment_dict4['compound'] * 100
577
- # compound5 = sentiment_dict5['compound'] * 100
578
- # compound6 = sentiment_dict6['compound'] * 100
579
- # compound7 = sentiment_dict7['compound'] * 100
580
- # compound8 = sentiment_dict8['compound'] * 100
581
- # compound9 = sentiment_dict9['compound'] * 100
582
- # compound10 = sentiment_dict10['compound'] * 100
583
- #
584
- # # _________________________________________________________________________________________________________#
585
- #
586
- # '''Matlab Plots...'''
587
- #
588
- # x = ["Q1", "Q2", "Q3", "Q4", "Q5", "Q6", "Q7", "Q8", "Q9", "Q10"]
589
- # y = [compound1, compound2, compound3, compound4, compound5, compound6, compound7, compound8, compound9, compound10]
590
- # fig, ax = plt.subplots()
591
- # plt.bar(x, y)
592
- # fig.set_size_inches(10, 6)
593
- # img_name = str(session['id'])
594
- # fig.savefig('' + img_name + '.png', dpi=384, transparent=True)
595
- # with open('' + img_name + '.png', 'rb') as f:
596
- # img = f.read()
597
- #
598
- # # _________________________________________________________________________________________________________#
599
- #
600
- # '''SQL Queries for data storing in database...'''
601
- #
602
- # now = datetime.datetime.now()
603
- # cur = mysql.connection.cursor()
604
- #
605
- # query = "INSERT INTO `testy` (`Id`, `Q1`, `Q2`, `Q3`, `Q4`, `Q5`, `Q6`, `Q7`, `Q8`, `Q9`, `Q10`, `datetime`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
606
- # cur.execute(query, (session['id'], inp1, inp2, inp3, inp4, inp5, inp6, inp7, inp8, inp9, inp10, now))
607
- #
608
- # query = "INSERT INTO `result` (`id`, `R1`, `R2`, `R3`, `R4`, `R5`, `R6`, `R7`, `R8`, `R9`, `R10`, `image`, `datetime`) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
609
- # cur.execute(query, (session['id'], compound1, compound2, compound3, compound4, compound5, compound6, compound7, compound8, compound9, compound10, img, now))
610
- #
611
- # query = "UPDATE `users` SET `isdone`=%s WHERE `id`=%s"
612
- # cur.execute(query, (1, session['id'],))
613
- #
614
- # mysql.connection.commit()
615
- # cur.close()
616
-
617
- # '''Retrival of data...'''
618
- # query = "SELECT Image FROM testy WHERE Id = %s"
619
- # cur.execute(query, (103))
620
- # row = cur.fetchone()
621
- # img = Image.open(io.BytesIO(row[0]))
622
- # cur.close()
623
- #
624
- # plt.imshow(img)
625
- # plt.show()
626
-
627
- # _________________________________________________________________________________________________________#
628
  return redirect(url_for('result'))
629
- # def index():
630
- # if request.method == "POST":
631
- #
632
- # '''Matlab Plots...'''
633
- # x = ["a", "b", "c", "d"]
634
- # y = [85,90,70,75]
635
- # fig, ax = plt.subplots()
636
- # plt.bar(x, y)
637
- # fig.set_size_inches(10, 6)
638
- # fig.savefig('foo.png', dpi=384, transparent=True)
639
- # with open('foo.png', 'rb') as f:
640
- # img = f.read()
641
- # # _________________________________________________________________________________________________________#
642
- #
643
- # '''SQL Queries for data storing in database...'''
644
- # cur = mysql.connection.cursor()
645
- # query = "INSERT INTO `testy` (`Id`, `Q1`, `Q2`, `Q3`, `Image`) VALUES (%s, %s, %s, %s, %s)"
646
- # cur.execute(query, (103, 2, 3, 1, img))
647
- # mysql.connection.commit()
648
- #
649
- # query = "SELECT Image FROM testy WHERE Id = %s"
650
- # cur.execute(query, (103,))
651
- # row = cur.fetchone()
652
- # img = Image.open(io.BytesIO(row[0]))
653
- # cur.close()
654
- #
655
- # plt.imshow(img)
656
- # plt.show()
657
- # # _________________________________________________________________________________________________________#
658
- #
659
- #
660
- # '''Sentiment analysis for each response...'''
661
- # inp = request.form.get("inp1")
662
- # name = request.form.get("name")
663
- # sid_obj = SentimentIntensityAnalyzer()
664
- # # score = sid.polarity_scores(inp)
665
- # # if score["neg"] > 0:
666
- # # return render_template('home.html', message="Negative")
667
- # # if score["neg"] == 0:
668
- # # return render_template('home.html', message="Neutral")
669
- # # else:
670
- # # return render_template('home.html', message="Positive")
671
- #
672
- # sentiment_dict = sid_obj.polarity_scores(inp)
673
- # negative = sentiment_dict['neg']
674
- # neutral = sentiment_dict['neu']
675
- # positive = sentiment_dict['pos']
676
- # compound = sentiment_dict['compound']
677
- #
678
- # return render_template('home.html', message=sentiment_dict['compound'], names=name)
679
- #
680
- # # if sentiment_dict['compound'] >= 0.05:
681
- # # return render_template('home.html', message="Positive")
682
- # #
683
- # # elif sentiment_dict['compound'] <= - 0.05:
684
- # # return render_template('home.html', message="Negative")
685
- # #
686
- # # else:
687
- # # return render_template('home.html', message="Neutral")
688
- #
689
- # # _________________________________________________________________________________________________________#
690
- #
691
- # return render_template('home.html')
692
-
693
-
694
- @self.app.route('/custom', methods=["GET", "POST"])
695
- def custom():
696
- if 'email' not in session:
697
- return redirect(url_for('login'))
698
-
699
- if request.method == "GET":
700
- if session['usertype'] == 0:
701
- return redirect(url_for('home'))
702
 
703
- return render_template('custom.html')
 
 
 
 
 
 
704
 
705
- if request.method == "POST":
706
- self.app.config['MYSQL_DB'] = session['database']
707
- email = session["email"]
708
 
709
- '''Sentiment analysis for each response...'''
710
 
711
- data = request.form.to_dict()
 
 
 
712
 
713
- length = len(request.form)
714
- inp = []
715
- for i in range(0, int((length - 3)/2)):
716
- inp.append(data['inpt' + str(i + 1) + ''])
 
 
717
 
718
- sid_obj = SentimentIntensityAnalyzer()
 
719
 
720
- compound = []
721
- for i in range(0, int((length - 3)/2)):
722
- compound.append(sid_obj.polarity_scores(data['inpt' + str(i + 1) + ''])['compound'] * 100)
723
 
724
- types = []
725
- for i in range(0, int((length - 3) / 2)):
726
- types.append(int(data['select' + str(i + 1) + '']))
727
 
728
- for i in range(len(compound)):
729
- if compound[i] < 0:
730
- compound[i] = -1
731
- elif compound[i] >= 0:
732
- compound[i] = 1
733
 
734
- name = request.form['name']
735
- describ = request.form['describ']
 
 
736
 
737
- '''SQL Queries for data storing in database...'''
738
 
739
- now = datetime.datetime.now()
740
- cur = mysql.connection.cursor()
 
741
 
742
- query = "INSERT INTO `assessments` (`name`, `description`, `Questions`, `types`, `qval`) VALUES (%s, %s, %s, %s, %s)"
743
- cur.execute(query, (name, describ, json.dumps(inp), json.dumps(types), json.dumps(compound),))
744
 
745
- mysql.connection.commit()
746
- cur.close()
747
 
748
- return redirect(url_for('admin'))
 
749
 
750
- return render_template("custom.html")
 
751
 
 
 
752
 
753
- @self.app.route('/result')
754
- def result():
755
- if 'email' not in session:
756
- return redirect(url_for('home'))
757
 
758
- self.app.config['MYSQL_DB'] = session['database']
759
- curr = mysql.connection.cursor()
760
-
761
- curr.execute("SELECT * FROM `custom` WHERE id=%s AND type=%s", (session['id'], session['type'],))
762
- res = curr.fetchone()
763
-
764
- curr.execute("SELECT result FROM `custom` WHERE type=%s", (session['type'],))
765
- avg = curr.fetchall()
766
-
767
- # curr.execute("SELECT qval FROM `assessments` WHERE assessId=%s", (session['type'],))
768
- # qval = curr.fetchone()
769
-
770
- dynamic = [list(eval(d['result'])) for d in avg]
771
-
772
- # Personal Average per questions will be compared....
773
- # average = []
774
- # multi = []
775
- # multi = eval(qval['qval'])
776
- # for i in range(len(avg)):
777
- # temp = eval(avg[i]['result'])
778
- # for j in range(len(temp)):
779
- # temp[j] = temp[j] * multi[j]
780
- # average.append(sum(temp) / len(temp))
781
-
782
- #Compute Happiness Index
783
- # happy = []
784
- # multi = []
785
- # multi = eval(qval['qval'])
786
- # happy = eval(res['result'])
787
- # for j in range(len(happy)):
788
- # happy[j] = happy[j] * multi[j]
789
- # happy_score = round(sum(happy) / len(happy), 4)
790
-
791
- dyna = []
792
- i = 0
793
- for i in range(len(dynamic[i])):
794
- temp2 = 0
795
- for j in range(len(dynamic)):
796
- temp2 = temp2 + dynamic[j][i]
797
- dyna.append(temp2 / len(dynamic))
798
-
799
-
800
- ques = []
801
- for i in range(1, len(dyna)+1):
802
- ques.append("Question " + str(i) + "")
803
-
804
- curr.execute("SELECT * FROM assessments WHERE assessid = %s", (session['type'],))
805
- questions = curr.fetchone()
806
-
807
- curr.execute("SELECT * FROM suggestions")
808
- suggests = curr.fetchall()
809
- response = []
810
- mapper = eval(questions['types'])
811
- score = eval(res['result'])
812
-
813
- score_dict = {}
814
- for i in range(len(mapper)):
815
- if mapper[i] not in score_dict:
816
- score_dict[mapper[i]] = []
817
- score_dict[mapper[i]].append(score[i])
818
-
819
- result_dict = {}
820
-
821
- for key, value in score_dict.items():
822
- temp_score = sum(value) / len(value)
823
- avg_score = round(((temp_score + 100) / 200) * (90 - 10) + 10, 2)
824
- if key == 1101:
825
- if avg_score >= 66:
826
- result_dict[key] = {"average_score": avg_score, "name": "Psychological well being", "description": "Refers to an individual`s mental state and overall happiness, including feelings of fulfillment, purpose, and contentment.", "suggestions_text": [list(eval(d['good'])) for d in suggests if d['idtype'] == 1101]}
827
- elif avg_score >= 30:
828
- result_dict[key] = {"average_score": avg_score, "name": "Psychological well being", "description": "Refers to an individual`s mental state and overall happiness, including feelings of fulfillment, purpose, and contentment.", "suggestions_text": [list(eval(d['average'])) for d in suggests if d['idtype'] == 1101]}
829
- elif avg_score < 30:
830
- result_dict[key] = {"average_score": avg_score, "name": "Psychological well being", "description": "Refers to an individual`s mental state and overall happiness, including feelings of fulfillment, purpose, and contentment.", "suggestions_text": [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1101]}
831
-
832
- elif key == 1102:
833
- if avg_score >= 66:
834
- result_dict[key] = {"average_score": avg_score, "name": "Health aspects", "description": "Refers to an individual`s physical health, including factors such as nutrition, exercise, and access to medical care.", "suggestions_text": [list(eval(d['good'])) for d in suggests if d['idtype'] == 1102]}
835
- elif avg_score >= 30:
836
- result_dict[key] = {"average_score": avg_score, "name": "Health aspects", "description": "Refers to an individual`s physical health, including factors such as nutrition, exercise, and access to medical care.", "suggestions_text": [list(eval(d['average'])) for d in suggests if d['idtype'] == 1102]}
837
- elif avg_score < 30:
838
- result_dict[key] = {"average_score": avg_score, "name": "Health aspects", "description": "Refers to an individual`s physical health, including factors such as nutrition, exercise, and access to medical care.", "suggestions_text": [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1102]}
839
-
840
- elif key == 1103:
841
- if avg_score >= 66:
842
- result_dict[key] = {"average_score": avg_score, "name": "Time management", "description": "Refers to an individual`s ability to effectively manage their time and prioritize tasks to maximize productivity and reduce stress.", "suggestions_text": [list(eval(d['good'])) for d in suggests if d['idtype'] == 1103]}
843
- elif avg_score >= 30:
844
- result_dict[key] = {"average_score": avg_score, "name": "Time management", "description": "Refers to an individual`s ability to effectively manage their time and prioritize tasks to maximize productivity and reduce stress.", "suggestions_text": [list(eval(d['average'])) for d in suggests if d['idtype'] == 1103]}
845
- elif avg_score < 30:
846
- result_dict[key] = {"average_score": avg_score, "name": "Time management", "description": "Refers to an individual`s ability to effectively manage their time and prioritize tasks to maximize productivity and reduce stress.", "suggestions_text": [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1103]}
847
-
848
- elif key == 1104:
849
- if avg_score >= 66:
850
- result_dict[key] = {"average_score": avg_score, "name": "Educational standards", "description": "Refers to the quality of education provided in a given community, including factors such as curriculum, teaching quality, and access to resources.", "suggestions_text": [list(eval(d['good'])) for d in suggests if d['idtype'] == 1104]}
851
- elif avg_score >= 30:
852
- result_dict[key] = {"average_score": avg_score, "name": "Educational standards", "description": "Refers to the quality of education provided in a given community, including factors such as curriculum, teaching quality, and access to resources.", "suggestions_text": [list(eval(d['average'])) for d in suggests if d['idtype'] == 1104]}
853
- elif avg_score < 30:
854
- result_dict[key] = {"average_score": avg_score, "name": "Educational standards", "description": "Refers to the quality of education provided in a given community, including factors such as curriculum, teaching quality, and access to resources.", "suggestions_text": [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1104]}
855
-
856
- elif key == 1105:
857
- if avg_score >= 66:
858
- result_dict[key] = {"average_score": avg_score, "name": "Cultural diversity", "description": "Refers to the range of cultures, beliefs, and practices within a given community, and the level of acceptance and celebration of diversity.", "suggestions_text": [list(eval(d['good'])) for d in suggests if d['idtype'] == 1105]}
859
- elif avg_score >= 30:
860
- result_dict[key] = {"average_score": avg_score, "name": "Cultural diversity", "description": "Refers to the range of cultures, beliefs, and practices within a given community, and the level of acceptance and celebration of diversity.", "suggestions_text": [list(eval(d['average'])) for d in suggests if d['idtype'] == 1105]}
861
- elif avg_score < 30:
862
- result_dict[key] = {"average_score": avg_score, "name": "Cultural diversity", "description": "Refers to the range of cultures, beliefs, and practices within a given community, and the level of acceptance and celebration of diversity.", "suggestions_text": [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1105]}
863
-
864
- elif key == 1106:
865
- if avg_score >= 66:
866
- result_dict[key] = {"average_score": avg_score, "name": "Social well-being", "description": "Social well-being refers to the quality of an individual`s social interactions, relationships, and sense of community belonging.", "suggestions_text": [list(eval(d['good'])) for d in suggests if d['idtype'] == 1106]}
867
- elif avg_score >= 30:
868
- result_dict[key] = {"average_score": avg_score, "name": "Social well-being", "description": "Social well-being refers to the quality of an individual`s social interactions, relationships, and sense of community belonging.", "suggestions_text": [list(eval(d['average'])) for d in suggests if d['idtype'] == 1106]}
869
- elif avg_score < 30:
870
- result_dict[key] = {"average_score": avg_score, "name": "Social well-being", "description": "Social well-being refers to the quality of an individual`s social interactions, relationships, and sense of community belonging.", "suggestions_text": [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1106]}
871
-
872
- elif key == 1107:
873
- if avg_score >= 66:
874
- result_dict[key] = {"average_score": avg_score, "name": "Good governance", "description": "Refers to the effectiveness and transparency of governing systems and institutions in promoting the well-being of all members of a community.", "suggestions_text": [list(eval(d['good'])) for d in suggests if d['idtype'] == 1107]}
875
- elif avg_score >= 30:
876
- result_dict[key] = {"average_score": avg_score, "name": "Good governance", "description": "Refers to the effectiveness and transparency of governing systems and institutions in promoting the well-being of all members of a community.", "suggestions_text": [list(eval(d['average'])) for d in suggests if d['idtype'] == 1107]}
877
- elif avg_score < 30:
878
- result_dict[key] = {"average_score": avg_score, "name": "Good governance", "description": "Refers to the effectiveness and transparency of governing systems and institutions in promoting the well-being of all members of a community.", "suggestions_text": [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1107]}
879
-
880
- elif key == 1108:
881
- if avg_score >= 66:
882
- result_dict[key] = {"average_score": avg_score, "name": "Community vitality", "description": "Refers to the health and vibrancy of a community, including factors such as social cohesion, civic engagement, and access to resources.", "suggestions_text": [list(eval(d['good'])) for d in suggests if d['idtype'] == 1108]}
883
- elif avg_score >= 30:
884
- result_dict[key] = {"average_score": avg_score, "name": "Community vitality", "description": "Refers to the health and vibrancy of a community, including factors such as social cohesion, civic engagement, and access to resources.", "suggestions_text": [list(eval(d['average'])) for d in suggests if d['idtype'] == 1108]}
885
- elif avg_score < 30:
886
- result_dict[key] = {"average_score": avg_score, "name": "Community vitality", "description": "Refers to the health and vibrancy of a community, including factors such as social cohesion, civic engagement, and access to resources.", "suggestions_text": [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1108]}
887
-
888
- suggest_dict = dict(sorted(result_dict.items()))
889
-
890
- # for i in range(len(score)):
891
- # if score[i] == 999:
892
- # response.append({'none'})
893
- #
894
- # elif score[i] >= 66:
895
- # if mapper[i] == 1101:
896
- # new_dict = {
897
- # 'domain': 'Psychological well being',
898
- # 'describ': 'Refers to an individual`s mental state and overall happiness, including feelings of fulfillment, purpose, and contentment.',
899
- # 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1101]
900
- # }
901
- # elif mapper[i] == 1102:
902
- # new_dict = {
903
- # 'domain': 'Health aspects',
904
- # 'describ': 'Refers to an individual`s physical health, including factors such as nutrition, exercise, and access to medical care.',
905
- # 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1102]
906
- # }
907
- # elif mapper[i] == 1103:
908
- # new_dict = {
909
- # 'domain': 'Time management',
910
- # 'describ': 'Refers to an individual`s ability to effectively manage their time and prioritize tasks to maximize productivity and reduce stress.',
911
- # 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1103]
912
- # }
913
- # elif mapper[i] == 1104:
914
- # new_dict = {
915
- # 'domain': 'Educational standards',
916
- # 'describ': 'Refers to the quality of education provided in a given community, including factors such as curriculum, teaching quality, and access to resources.',
917
- # 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1104]
918
- # }
919
- # elif mapper[i] == 1105:
920
- # new_dict = {
921
- # 'domain': 'Cultural diversity',
922
- # 'describ': 'Refers to the range of cultures, beliefs, and practices within a given community, and the level of acceptance and celebration of diversity.',
923
- # 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1105]
924
- # }
925
- # elif mapper[i] == 1106:
926
- # new_dict = {
927
- # 'domain': 'Social well-being',
928
- # 'describ': 'Social well-being refers to the quality of an individual`s social interactions, relationships, and sense of community belonging.',
929
- # 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1106]
930
- # }
931
- # elif mapper[i] == 1107:
932
- # new_dict = {
933
- # 'domain': 'Good governance',
934
- # 'describ': 'Refers to the effectiveness and transparency of governing systems and institutions in promoting the well-being of all members of a community.',
935
- # 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1107]
936
- # }
937
- # elif mapper[i] == 1108:
938
- # new_dict = {
939
- # 'domain': 'Community vitality',
940
- # 'describ': 'Refers to the health and vibrancy of a community, including factors such as social cohesion, civic engagement, and access to resources.',
941
- # 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1108]
942
- # }
943
- # response.append(new_dict)
944
- #
945
- # elif score[i] >= 40:
946
- # if mapper[i] == 1101:
947
- # new_dict = {
948
- # 'domain': 'Psychological well being',
949
- # 'describ': 'Refers to an individual`s mental state and overall happiness, including feelings of fulfillment, purpose, and contentment.',
950
- # 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1101]
951
- # }
952
- # elif mapper[i] == 1102:
953
- # new_dict = {
954
- # 'domain': 'Health aspects',
955
- # 'describ': 'Refers to an individual`s physical health, including factors such as nutrition, exercise, and access to medical care.',
956
- # 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1102]
957
- # }
958
- # elif mapper[i] == 1103:
959
- # new_dict = {
960
- # 'domain': 'Time management',
961
- # 'describ': 'Refers to an individual`s ability to effectively manage their time and prioritize tasks to maximize productivity and reduce stress.',
962
- # 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1103]
963
- # }
964
- # elif mapper[i] == 1104:
965
- # new_dict = {
966
- # 'domain': 'Educational standards',
967
- # 'describ': 'Refers to the quality of education provided in a given community, including factors such as curriculum, teaching quality, and access to resources.',
968
- # 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1104]
969
- # }
970
- # elif mapper[i] == 1105:
971
- # new_dict = {
972
- # 'domain': 'Cultural diversity',
973
- # 'describ': 'Refers to the range of cultures, beliefs, and practices within a given community, and the level of acceptance and celebration of diversity.',
974
- # 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1105]
975
- # }
976
- # elif mapper[i] == 1106:
977
- # new_dict = {
978
- # 'domain': 'Social well-being',
979
- # 'describ': 'Social well-being refers to the quality of an individual`s social interactions, relationships, and sense of community belonging.',
980
- # 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1106]
981
- # }
982
- # elif mapper[i] == 1107:
983
- # new_dict = {
984
- # 'domain': 'Good governance',
985
- # 'describ': 'Refers to the effectiveness and transparency of governing systems and institutions in promoting the well-being of all members of a community.',
986
- # 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1107]
987
- # }
988
- # elif mapper[i] == 1108:
989
- # new_dict = {
990
- # 'domain': 'Community vitality',
991
- # 'describ': 'Refers to the health and vibrancy of a community, including factors such as social cohesion, civic engagement, and access to resources.',
992
- # 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1108]
993
- # }
994
- # response.append(new_dict)
995
- #
996
- # elif score[i] < 40:
997
- # if mapper[i] == 1101:
998
- # new_dict = {
999
- # 'domain': 'Psychological well being',
1000
- # 'describ': 'Refers to an individual`s mental state and overall happiness, including feelings of fulfillment, purpose, and contentment.',
1001
- # 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1101]
1002
- # }
1003
- # elif mapper[i] == 1102:
1004
- # new_dict = {
1005
- # 'domain': 'Health aspects',
1006
- # 'describ': 'Refers to an individual`s physical health, including factors such as nutrition, exercise, and access to medical care.',
1007
- # 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1102]
1008
- # }
1009
- # elif mapper[i] == 1103:
1010
- # new_dict = {
1011
- # 'domain': 'Time management',
1012
- # 'describ': 'Refers to an individual`s ability to effectively manage their time and prioritize tasks to maximize productivity and reduce stress.',
1013
- # 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1103]
1014
- # }
1015
- # elif mapper[i] == 1104:
1016
- # new_dict = {
1017
- # 'domain': 'Educational standards',
1018
- # 'describ': 'Refers to the quality of education provided in a given community, including factors such as curriculum, teaching quality, and access to resources.',
1019
- # 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1104]
1020
- # }
1021
- # elif mapper[i] == 1105:
1022
- # new_dict = {
1023
- # 'domain': 'Cultural diversity',
1024
- # 'describ': 'Refers to the range of cultures, beliefs, and practices within a given community, and the level of acceptance and celebration of diversity.',
1025
- # 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1105]
1026
- # }
1027
- # elif mapper[i] == 1106:
1028
- # new_dict = {
1029
- # 'domain': 'Social well-being',
1030
- # 'describ': 'Social well-being refers to the quality of an individual`s social interactions, relationships, and sense of community belonging.',
1031
- # 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1106]
1032
- # }
1033
- # elif mapper[i] == 1107:
1034
- # new_dict = {
1035
- # 'domain': 'Good governance',
1036
- # 'describ': 'Refers to the effectiveness and transparency of governing systems and institutions in promoting the well-being of all members of a community.',
1037
- # 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1107]
1038
- # }
1039
- # elif mapper[i] == 1108:
1040
- # new_dict = {
1041
- # 'domain': 'Community vitality',
1042
- # 'describ': 'Refers to the health and vibrancy of a community, including factors such as social cohesion, civic engagement, and access to resources.',
1043
- # 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1108]
1044
- # }
1045
- # response.append(new_dict)
1046
-
1047
- curr.execute("SELECT `Questions`,`response`, `result`, `datetime` FROM `custom`, `assessments` WHERE `id`=%s AND `type`=%s AND custom.type = assessments.assessId", (session['id'], session['type'],))
1048
- details = curr.fetchone()
1049
-
1050
- mysql.connection.commit()
1051
- curr.close()
1052
-
1053
- return render_template("result.html", ques=ques, res1=res['response'], res2=res['result'], res3=res['datetime'], res4=res['happy'], res5=dyna, res6=response, res7=suggest_dict, res8=questions, res9=details)
1054
-
1055
- # @app.route('/customresult')
1056
- # def customresult():
1057
- # app.config['MYSQL_DB'] = session['database']
1058
- # curr = mysql.connection.cursor()
1059
- # curr.execute("SELECT * FROM `custom` WHERE id=%s", (session['id'],))
1060
- # res = curr.fetchone()
1061
- # mysql.connection.commit()
1062
- # curr.close()
1063
- #
1064
- # ques = []
1065
- # for i in range(1, len(res)):
1066
- # ques.append("Q"+ str(i) +"")
1067
- #
1068
- # return render_template("customresult.html", ques=ques, res1=res['response'], res2=res['result'], res3=res['datetime'])
1069
-
1070
- @self.app.route('/logout')
1071
- def logout():
1072
- self.app.config['MYSQL_DB'] = session['database']
1073
- now = datetime.datetime.now()
1074
- curo = mysql.connection.cursor()
1075
- if 'id' in session:
1076
- curo.execute("INSERT INTO session (id, email, action, actionC, datetime) VALUES (%s, %s, %s, %s, %s)", (session['id'], session['email'], 'Logged Out - Session Terminated', 0, now,))
1077
- else:
1078
- curo.execute("INSERT INTO session (email, action, actionC, datetime) VALUES (%s, %s, %s, %s)", (session['email'], 'Logged Out - Session Terminated', 0, now,))
1079
 
1080
- mysql.connection.commit()
1081
- curo.close()
1082
- session.clear()
1083
- return redirect(url_for("home"))
1084
 
 
 
1085
 
1086
- @self.app.errorhandler(Exception)
1087
- def handle_error(error):
1088
- self.app.logger.error(error)
1089
- error_name = error.__class__.__name__
1090
- message = f"{error_name}: {str(error)}"
1091
- return render_template('error.html', message=message), 500
1092
 
 
1093
 
1094
- if __name__=='__main__':
1095
- my_app = SmileCheckApp()
1096
- my_app.app.run(debug=True)
1097
- # app.run(debug=True)
1098
 
 
 
1099
 
1100
- """
1101
- python -m flask run
1102
 
1103
- Vader
1104
- VADER (Valence Aware Dictionary and Sentiment Reasoner) is a lexicon and rule-based sentiment analysis tool that is specifically designed to detect sentiments expressed in social media.
1105
 
1106
- It's disheartening to see so much suffering and injustice in the world. From poverty and inequality to violence and discrimination, there are so many deep-rooted problems that seem almost insurmountable. It can be hard to maintain hope and optimism when faced with so much negativity, and it's all too easy to feel powerless in the face of such overwhelming challenges. The daily news cycle can be overwhelming, with constant reports of tragedy and heartbreak, and it's easy to feel as though the world is an increasingly dangerous and hopeless place. Despite all this, however, we must continue to work towards a better future and hold onto the belief that change is possible.
1107
 
1108
- @app.route('/submit', methods=['POST'])
1109
- def handle_submit():
1110
- if 'form1' in request.form:
1111
- # Handle form1 submission code here
1112
- return 'Form 1 submitted successfully'
1113
- elif 'form2' in request.form:
1114
- # Handle form2 submission code here
1115
- return 'Form 2 submitted successfully'
1116
- else:
1117
- # Handle case where neither form1 nor form2 were submitted
1118
- return 'Invalid form submission'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1119
 
 
 
1120
 
1121
- <form method="post" action="/submit">
1122
- <!-- Form 1 fields here -->
1123
- <button type="submit" name="form1">Submit Form 1</button>
1124
- </form>
1125
 
1126
- <form method="post" action="/submit">
1127
- <!-- Form 2 fields here -->
1128
- <button type="submit" name="form2">Submit Form 2</button>
1129
- </form>
1130
 
 
 
1131
 
1132
- if there are two forms in my html template i want run two different flask codes with post request from each form
 
1133
 
1134
- no within a single app route but with two different forms
1135
 
 
1136
 
1137
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from flask import Flask, render_template, request, redirect, url_for, session
2
  from nltk.sentiment.vader import SentimentIntensityAnalyzer
 
3
  import nltk
4
+ import mysql.connector
5
  import bcrypt
6
  import datetime
7
  import json
8
+ import smtplib
 
 
9
  from email.message import EmailMessage
10
  import secrets
11
  import string
 
12
 
13
  nltk.download('vader_lexicon')
14
 
15
+ mysql = mysql.connector.connect(
16
+ host='localhost',
17
+ user='root',
18
+ password='',
19
+ database='test',
20
+ port=3306,
21
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
 
23
 
24
+ app = Flask(__name__)
25
+ app.static_folder = 'static'
26
+ app.static_url_path = '/static'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
 
28
+ app.secret_key = "smilecheck-abhi-2023"
 
 
 
 
 
29
 
 
 
30
 
31
+ @app.route('/')
32
+ def index():
33
+ return render_template("index.html")
34
 
35
+
36
+ @app.route('/home', methods=["GET", "POST"])
37
+ def home():
38
+ if request.method == 'GET':
39
+ if 'email' in session:
40
+ app.config['MYSQL_DB'] = 'test'
41
+ curh = mysql.cursor()
42
+ if session['usertype'] == 0:
43
+ curh.execute("SELECT `assessid`, `name` FROM assessments")
44
+ typedata = curh.fetchall()
45
+
46
+ converted_tuple = tuple({'assessid': item[0], 'name': item[1]} for item in typedata)
47
+
48
+ curh.execute("SELECT `id`, `type` FROM custom WHERE id=%s", (session['id'],))
49
+ given = curh.fetchall()
50
+ isdone = []
51
+ for give in given:
52
+ isdone.append(give[1])
53
+
54
+ curh.execute("SELECT `name`, `happy`, `datetime` FROM `custom`, `assessments` WHERE custom.type = assessments.assessId AND id=%s", (session['id'],))
55
+ previous = curh.fetchall()
56
+
57
+ preprocessed_data = []
58
+ for index, row in enumerate(previous):
59
+ preprocessed_data.append({
60
+ 'index': index + 1,
61
+ 'name': row[0],
62
+ 'happy': row[1],
63
+ 'datetime': row[2]
64
+ })
65
+
66
+ return render_template("home.html", typedata=converted_tuple, given=isdone, previous=preprocessed_data )
67
+
68
+ elif session['usertype'] == 1:
69
+ return redirect(url_for('admin'))
70
+ mysql.commit()
71
+ curh.close()
72
+ else:
73
+ return redirect(url_for('login'))
74
+
75
+ if request.method == 'POST':
76
+ if 'email' in session:
77
+ app.config['MYSQL_DB'] = 'test'
78
+
79
+ curh = mysql.cursor()
80
+
81
+ if 'fname' in request.form:
82
+ fname = request.form['fname']
83
+ femail = request.form['femail']
84
+ feedback = request.form['feedback']
85
+ curh.execute("INSERT INTO `feedbacks`(`name`, `email`, `feedback`) VALUES (%s, %s, %s)", (fname, femail, feedback,))
86
+ mysql.commit()
87
+ curh.close()
88
+ session['feed'] = 1
89
+ return redirect(url_for('home'))
90
+
91
+
92
+ session['type'] = request.form['type']
93
+
94
+ curh.execute("SELECT `id`, `type` FROM custom WHERE id=%s AND type=%s", (session['id'], session['type'],))
95
+ given = curh.fetchone()
96
+ mysql.commit()
97
+ curh.close()
98
+
99
+ if given == None:
100
+ return redirect(url_for('form'))
101
  else:
102
+ return redirect(url_for('result'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
+ else:
105
+ return redirect(url_for('login'))
106
 
107
+ return render_template("home.html")
 
 
 
108
 
 
 
 
109
 
110
+ @app.route('/register', methods=["GET", "POST"])
111
+ def register():
112
+ if request.method == 'GET':
113
+ return render_template("register.html", error_code=999, message_code=999)
114
 
115
+ if request.method == 'POST':
116
+ database = request.form['database']
117
+ if database == 'database1':
118
+ app.config['MYSQL_DB'] = 'test'
119
+ session['database'] = app.config['MYSQL_DB']
120
+ elif database == 'database2':
121
+ app.config['MYSQL_DB'] = 'test2'
122
+ session['database'] = app.config['MYSQL_DB']
123
 
124
+ name = request.form['name']
125
+ email = request.form['email']
126
+ cur = mysql.cursor()
127
+ cur.execute("SELECT * FROM users WHERE email = %s", (email,))
128
+ user = cur.fetchone()
129
+ mysql.commit()
130
+ cur.close()
131
 
132
+ if user:
133
+ error = 'Email address already in use. Please use a different email address.'
134
+ return render_template('register.html', error=error, error_code=550, message_code=569)
135
+ else:
136
+ session['name'] = name
137
+ session['email'] = email
138
+ usertype = 'student'
139
+ session['pretype'] = usertype
140
+ password = request.form['password'].encode('utf-8')
141
+ hash_password = bcrypt.hashpw(password, bcrypt.gensalt())
142
+ session['hash'] = hash_password
143
 
144
+ msg = EmailMessage()
145
 
146
+ alphabet = string.ascii_letters + string.digits
147
+ otp = 'smilecheck-user-'+''.join(secrets.choice(alphabet) for i in range(30))
148
+ session['otp'] = otp
 
 
 
 
149
 
150
+ msg["Subject"] = "SmileCheck Verification"
151
+ msg["From"] = "smilecheck100@gmail.com"
152
+ msg["To"] = email
153
+ link = f"http://127.0.0.1:5000/verify/{otp}"
154
 
155
+ html_content = render_template('email.html', name=name, link=link)
156
+ msg.set_content(html_content, subtype='html')
157
 
158
+ with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
159
+ smtp.login('smilecheck23@gmail.com', 'dczcfrdkthwcfoqu')
160
+ smtp.send_message(msg)
161
 
162
+ return render_template('register.html', message='An Verification Email has been sent to your email address.', message_code=560, error_code=568)
163
 
 
 
164
 
165
+ @app.route('/verify/<otp>')
166
+ def verify(otp):
167
+ if str(session['otp']) == otp:
168
+ app.config['MYSQL_DB'] = 'test'
169
 
170
+ cur = mysql.cursor()
171
+ cur.execute("INSERT INTO users (name, email, password) VALUES (%s,%s,%s)", (session['name'], session['email'], session['hash'],))
 
 
 
 
 
 
 
172
 
173
+ if session['pretype'] == 'student':
174
+ cur.execute("UPDATE `users` SET `usertype` = %s WHERE `email`=%s", (0, session['email'],))
175
+ session['usertype'] = 0
176
+ elif session['pretype'] == 'admin':
177
+ cur.execute("UPDATE `users` SET `usertype` = %s WHERE `email`=%s", (1, session['email'],))
178
+ session['usertype'] = 1
179
 
180
+ mysql.commit()
181
+ cur.close()
 
 
182
 
183
+ session.clear()
 
184
 
185
+ redi = 'login'
186
+ return render_template('verify.html', message=111, redirect_url=redi)
187
 
188
+ else:
189
+ redi = 'register'
190
+ return render_template('verify.html', message=999, redirect_url=redi)
191
 
 
 
192
 
193
+ @app.route('/login', methods=["GET", "POST"])
194
+ def login():
195
+ if request.method == 'GET':
196
+ return render_template("login.html", error_code=999)
197
+
198
+ if request.method == 'POST':
199
+ now = datetime.datetime.now()
200
+ database = request.form['database']
201
+ if database == 'database1':
202
+ app.config['MYSQL_DB'] = 'test'
203
+ elif database == 'database2':
204
+ app.config['MYSQL_DB'] = 'test2'
205
+
206
+ email = request.form['email']
207
+ password = request.form['password'].encode('utf-8')
208
 
209
+ curl = mysql.cursor()
210
+ curl.execute("SELECT * FROM users WHERE email=%s", (email,))
211
+ user = curl.fetchone()
212
 
213
+ if user != None:
214
+ if bcrypt.hashpw(password, user[4].encode('utf-8')) == user[4].encode('utf-8'):
215
 
216
+ session['id'] = user[0]
217
+ session['name'] = user[2]
218
+ session['email'] = user[3]
219
+ session['database'] = 'test'
220
+
221
+ print(session)
222
+
223
+ curl.execute("INSERT INTO session (id, email, action, actionC, datetime) VALUES (%s, %s, %s, %s, %s)", (session['id'], session['email'], 'Logged In - Session Started', 1, now,))
224
+ mysql.commit()
225
+ curl.close()
226
+
227
+ if user[1] == 0:
228
+ session['usertype'] = 0
229
  return redirect(url_for('home'))
230
+ elif user[1] == 1:
231
+ session['usertype'] = 1
232
+ return redirect(url_for('admin'))
233
+
234
  else:
235
+ return render_template("login.html", error="Error: Password or Email are incorrect.", error_code=451)
236
 
237
+ else:
238
+ return render_template("login.html", error="Error: User not found. Please register.", error_code=452)
 
 
 
 
 
 
239
 
240
+ mysql.commit()
241
+ curl.close()
242
+ else:
243
+ return render_template("login.html")
244
 
 
 
245
 
246
+ @app.route('/forgot', methods=["GET", "POST"])
247
+ def forgot():
248
+ if request.method == 'GET':
249
+ return render_template("forgot.html")
250
 
251
+ if request.method == 'POST':
252
+ app.config['MYSQL_DB'] = 'test'
253
 
254
+ email = request.form['email']
255
+ session['email'] = email
 
 
256
 
257
+ curl = mysql.cursor()
258
+ curl.execute("SELECT * FROM users WHERE email=%s", (email,))
259
+ user = curl.fetchone()
260
 
261
+ mysql.commit()
262
+ curl.close()
263
 
264
+ if user != None:
265
+ msg = EmailMessage()
266
 
267
+ name= user[2]
268
 
269
+ alphabet = string.ascii_letters + string.digits
270
+ otp = 'smilecheck-pass-' + ''.join(secrets.choice(alphabet) for i in range(30))
271
+ session['otp'] = otp
272
+ msg["Subject"] = "SmileCheck Verification"
273
+ msg["From"] = "smilecheck100@gmail.com"
274
+ msg["To"] = email
275
+ link = f"http://127.0.0.1:5000/password/{otp}"
276
 
277
+ html_content = render_template('pass.html', name=name, link=link)
278
+ msg.set_content(html_content, subtype='html')
 
279
 
280
+ with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
281
+ smtp.login('smilecheck23@gmail.com', 'dczcfrdkthwcfoqu')
282
+ smtp.send_message(msg)
283
 
284
+ return render_template('register.html', message='An Verification Email has been sent to your email address.', message_code=560, error_code=568)
285
 
286
+ else:
287
+ return render_template("forgot.html", mess="No such User Found.")
 
 
 
 
 
288
 
 
 
 
 
 
 
 
 
 
 
289
 
290
+ @app.route('/password/<otp>', methods=["GET", "POST"])
291
+ def password(otp):
292
+ if str(session['otp']) == otp:
293
+ redi = 'change'
294
+ return render_template('password.html', message=111, redirect_url=redi)
295
+ else:
296
+ redi = 'login'
297
+ return render_template('password.html', message=999, redirect_url=redi)
298
 
299
 
300
+ @app.route('/change', methods=["GET", "POST"])
301
+ def change():
302
+ if request.method == 'GET':
303
+ return render_template("change.html")
304
 
305
+ if request.method == 'POST':
306
+ app.config['MYSQL_DB'] = 'test'
 
 
 
 
 
 
307
 
308
+ password = request.form['password'].encode('utf-8')
309
+ hash_password = bcrypt.hashpw(password, bcrypt.gensalt())
310
 
311
+ curl = mysql.cursor()
312
+ curl.execute("UPDATE `users` SET `password`=%s WHERE email=%s", (hash_password, session['email'],))
313
 
314
+ mysql.commit()
315
+ curl.close()
316
 
317
+ session.clear()
318
 
319
+ return redirect(url_for('login'))
320
 
 
 
 
 
321
 
322
+ @app.route('/admin', methods=["GET", "POST"])
323
+ def admin():
324
+ if 'email' in session:
325
+ if session['usertype'] == 0:
326
+ return redirect(url_for('home'))
327
+ else:
328
+ return redirect(url_for('login'))
329
 
330
+ if request.method == 'GET':
331
+ if 'email' in session:
332
+ app.config['MYSQL_DB'] = 'test'
 
333
 
334
+ cura = mysql.cursor()
335
 
336
+ cura.execute("SELECT `assessid`, `name` FROM assessments")
337
+ typedata = cura.fetchall()
338
 
339
+ typedata_tuple = tuple({'assessid': item[0], 'name': item[1]} for item in typedata)
 
340
 
341
+ cura.execute("SELECT `id`, `type` FROM custom")
342
+ given = cura.fetchall()
343
 
344
+ given_tuple = tuple({'id': item[0], 'type': item[1]} for item in given)
 
345
 
346
+ isdone = []
347
+ for give in given:
348
+ isdone.append(give[1])
349
 
350
+ cura.execute("SELECT `id`, `name`, `email`, `isdone` FROM `users` WHERE `usertype` = 0")
351
+ res = cura.fetchall()
 
 
 
 
352
 
353
+ res_tuple = tuple({'id': item[0], 'name': item[1], 'email': item[2], 'isdone': item[3]} for item in res)
 
 
354
 
355
+ cura.execute("SELECT `assessId`, `name`, `description`, `Questions`, `average` FROM `assessments`")
356
+ que = cura.fetchall()
357
 
358
+ que_tuple = tuple({'assessId': item[0], 'name': item[1], 'description': item[2], 'Questions': item[3], 'average': item[4]} for item in que)
 
359
 
360
+ cura.execute("SELECT `id`, `type`, `name` FROM `custom`, `assessments` WHERE custom.type = assessments.assessId")
361
+ abc = cura.fetchall()
362
 
363
+ abc_tuple = tuple({'id': item[0], 'type': item[1], 'name': item[2]} for item in abc)
364
 
365
+ ahi = 0.0
366
+ for assess in que:
367
+ if assess[0] == 101:
368
+ ahi = assess[4]
369
 
370
+ ts = len(res)
371
+ tas = len(isdone)
372
 
373
+ cura.execute("SELECT `name`, `email`, `feedback` FROM `feedbacks`")
374
+ feeds = cura.fetchall()
375
 
376
+ feeds_tuple = tuple({'name': item[0], 'email': item[1], 'feedback': item[2]} for item in feeds)
377
 
378
+ mysql.commit()
379
+ cura.close()
380
+
381
+ return render_template("admin.html", typedata=typedata_tuple, given=given_tuple, result=res_tuple, assess=que_tuple, abc=abc_tuple, ts=ts, ahi=ahi, tas=tas, feeds= feeds_tuple)
382
+
383
+ if request.method == "POST":
384
+ app.config['MYSQL_DB'] = 'test'
385
+
386
+ if 'resid' in request.form:
387
+ resid = request.form.get('resid')
388
+ types = request.form.get('type')
389
+
390
+ session['id'] = resid
391
+ session['type'] = types
392
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
393
  return redirect(url_for('result'))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
394
 
395
+ elif 'delete' in request.form:
396
+ cura = mysql.cursor()
397
+ deleteId = request.form['delete']
398
+ cura.execute("DELETE FROM `assessments` WHERE `assessId`= %s", (deleteId,))
399
+ mysql.commit()
400
+ cura.close()
401
+ return redirect(url_for('admin'))
402
 
403
+ return render_template('admin.html')
 
 
404
 
 
405
 
406
+ @app.route('/form', methods=["GET", "POST"])
407
+ def form():
408
+ if 'email' not in session:
409
+ return redirect(url_for('login'))
410
 
411
+ if request.method == "GET":
412
+ app.config['MYSQL_DB'] = 'test'
413
+ typeid = session['type']
414
+ curf = mysql.cursor()
415
+ curf.execute("SELECT `name`, `description`, `Questions`, `types` FROM assessments WHERE assessid = %s", (typeid,))
416
+ questions = curf.fetchone()
417
 
418
+ mysql.commit()
419
+ curf.close()
420
 
421
+ return render_template("form.html", questions=questions)
 
 
422
 
423
+ if request.method == "POST":
424
+ app.config['MYSQL_DB'] = 'test'
 
425
 
426
+ data = request.form.to_dict()
 
 
 
 
427
 
428
+ length = len(request.form)
429
+ inp = []
430
+ for i in range(0, length):
431
+ inp.append(data['inp' + str(i + 1) + ''])
432
 
433
+ sid_obj = SentimentIntensityAnalyzer()
434
 
435
+ compound = []
436
+ for i in range(0, length):
437
+ compound.append(sid_obj.polarity_scores(data['inp' + str(i + 1) + ''])['compound'] * 100)
438
 
439
+ now = datetime.datetime.now()
440
+ cur = mysql.cursor()
441
 
442
+ query = "INSERT INTO `custom` (`Id`, `type`, `response`, `result`, `datetime`) VALUES (%s, %s, %s, %s, %s)"
443
+ cur.execute(query, (session['id'], session['type'], json.dumps(inp), json.dumps(compound), now,))
444
 
445
+ query = "UPDATE `users` SET `isdone`=%s WHERE `id`=%s"
446
+ cur.execute(query, (1, session['id'],))
447
 
448
+ cur.execute("SELECT * FROM `custom` WHERE id=%s AND type=%s", (session['id'], session['type'],))
449
+ res = cur.fetchone()
450
 
451
+ cur.execute("SELECT qval FROM `assessments` WHERE assessId=%s", (session['type'],))
452
+ qval = cur.fetchone()
453
 
454
+ multi = eval(qval[0])
455
+ happy = eval(res[4])
456
+ for j in range(len(happy)):
457
+ happy[j] = happy[j] * multi[j]
458
 
459
+ min_value = min(compound)
460
+ max_value = max(compound)
461
+ scaled_values = [(value - min_value) / (max_value - min_value) * 5 for value in compound]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
462
 
463
+ happy_index = round(sum(scaled_values) / len(scaled_values), 2)
 
 
 
464
 
465
+ query = "UPDATE `custom` SET `happy`=%s WHERE `id`=%s AND `type`=%s"
466
+ cur.execute(query, (happy_index, session['id'], session['type'],))
467
 
468
+ cur.execute("SELECT `happy` FROM `custom` WHERE type=%s", (session['type'],))
469
+ avg_dict = cur.fetchall()
 
 
 
 
470
 
471
+ avg_list = [d[0] for d in avg_dict if isinstance(d[0], float)] + [item for d in avg_dict if isinstance(d[0], (list, tuple)) for item in d[0]]
472
 
473
+ avg_score = round(sum(avg_list)/len(avg_list), 2)
 
 
 
474
 
475
+ query = "UPDATE `assessments` SET `average`=%s WHERE `assessId`=%s"
476
+ cur.execute(query, (avg_score, session['type'],))
477
 
478
+ mysql.commit()
479
+ cur.close()
480
 
481
+ '''Re-render template...'''
 
482
 
483
+ return redirect(url_for('result'))
484
 
485
+ return redirect(url_for('result'))
486
+
487
+
488
+ @app.route('/custom', methods=["GET", "POST"])
489
+ def custom():
490
+ if 'email' not in session:
491
+ return redirect(url_for('login'))
492
+
493
+ if request.method == "GET":
494
+ if session['usertype'] == 0:
495
+ return redirect(url_for('home'))
496
+
497
+ return render_template('custom.html')
498
+
499
+ if request.method == "POST":
500
+ app.config['MYSQL_DB'] = 'test'
501
+
502
+ data = request.form.to_dict()
503
+
504
+ length = len(request.form)
505
+ inp = []
506
+ for i in range(0, int((length - 3)/2)):
507
+ inp.append(data['inpt' + str(i + 1) + ''])
508
+
509
+ sid_obj = SentimentIntensityAnalyzer()
510
+
511
+ compound = []
512
+ for i in range(0, int((length - 3)/2)):
513
+ compound.append(sid_obj.polarity_scores(data['inpt' + str(i + 1) + ''])['compound'] * 100)
514
+
515
+ types = []
516
+ for i in range(0, int((length - 3) / 2)):
517
+ types.append(int(data['select' + str(i + 1) + '']))
518
+
519
+ for i in range(len(compound)):
520
+ if compound[i] < 0:
521
+ compound[i] = -1
522
+ elif compound[i] >= 0:
523
+ compound[i] = 1
524
 
525
+ name = request.form['name']
526
+ describ = request.form['describ']
527
 
528
+ '''SQL Queries for data storing in database...'''
 
 
 
529
 
530
+ now = datetime.datetime.now()
531
+ cur = mysql.cursor()
 
 
532
 
533
+ query = "INSERT INTO `assessments` (`name`, `description`, `Questions`, `types`, `qval`) VALUES (%s, %s, %s, %s, %s)"
534
+ cur.execute(query, (name, describ, json.dumps(inp), json.dumps(types), json.dumps(compound),))
535
 
536
+ mysql.commit()
537
+ cur.close()
538
 
539
+ return redirect(url_for('admin'))
540
 
541
+ return render_template("custom.html")
542
 
543
+
544
+ @app.route('/result')
545
+ def result():
546
+ if 'email' not in session:
547
+ return redirect(url_for('home'))
548
+
549
+ app.config['MYSQL_DB'] = 'test'
550
+ curr = mysql.cursor()
551
+
552
+ curr.execute("SELECT * FROM `custom` WHERE id=%s AND type=%s", (session['id'], session['type'],))
553
+ res = curr.fetchone()
554
+
555
+ curr.execute("SELECT result FROM `custom` WHERE type=%s", (session['type'],))
556
+ avg = curr.fetchall()
557
+
558
+ avg_tuple = tuple({'result': item[0]} for item in avg)
559
+
560
+ dynamic = [list(eval(d[0])) for d in avg]
561
+
562
+ dyna = []
563
+ i = 0
564
+ for i in range(len(dynamic[i])):
565
+ temp2 = 0
566
+ for j in range(len(dynamic)):
567
+ temp2 = temp2 + dynamic[j][i]
568
+ dyna.append(temp2 / len(dynamic))
569
+
570
+
571
+ ques = []
572
+ for i in range(1, len(dyna)+1):
573
+ ques.append("Question " + str(i) + "")
574
+
575
+ curr.execute("SELECT * FROM assessments WHERE assessid = %s", (session['type'],))
576
+ questions = curr.fetchone()
577
+
578
+ curr.execute("SELECT * FROM suggestions")
579
+ suggests = curr.fetchall()
580
+ response = []
581
+ mapper = eval(questions[4])
582
+ score = eval(res[4])
583
+
584
+ score_dict = {}
585
+ for i in range(len(mapper)):
586
+ if mapper[i] not in score_dict:
587
+ score_dict[mapper[i]] = []
588
+ score_dict[mapper[i]].append(score[i])
589
+
590
+ result_dict = {}
591
+
592
+ for key, value in score_dict.items():
593
+ temp_score = sum(value) / len(value)
594
+ avg_score = round(((temp_score + 100) / 200) * (90 - 10) + 10, 2)
595
+ if key == 1101:
596
+ if avg_score >= 66:
597
+ result_dict[key] = {"average_score": avg_score, "name": "Psychological well being", "description": "Refers to an individual`s mental state and overall happiness, including feelings of fulfillment, purpose, and contentment.", "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1101]}
598
+ elif avg_score >= 30:
599
+ result_dict[key] = {"average_score": avg_score, "name": "Psychological well being", "description": "Refers to an individual`s mental state and overall happiness, including feelings of fulfillment, purpose, and contentment.", "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1101]}
600
+ elif avg_score < 30:
601
+ result_dict[key] = {"average_score": avg_score, "name": "Psychological well being", "description": "Refers to an individual`s mental state and overall happiness, including feelings of fulfillment, purpose, and contentment.", "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1101]}
602
+
603
+ elif key == 1102:
604
+ if avg_score >= 66:
605
+ result_dict[key] = {"average_score": avg_score, "name": "Health aspects", "description": "Refers to an individual`s physical health, including factors such as nutrition, exercise, and access to medical care.", "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1102]}
606
+ elif avg_score >= 30:
607
+ result_dict[key] = {"average_score": avg_score, "name": "Health aspects", "description": "Refers to an individual`s physical health, including factors such as nutrition, exercise, and access to medical care.", "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1102]}
608
+ elif avg_score < 30:
609
+ result_dict[key] = {"average_score": avg_score, "name": "Health aspects", "description": "Refers to an individual`s physical health, including factors such as nutrition, exercise, and access to medical care.", "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1102]}
610
+
611
+ elif key == 1103:
612
+ if avg_score >= 66:
613
+ result_dict[key] = {"average_score": avg_score, "name": "Time management", "description": "Refers to an individual`s ability to effectively manage their time and prioritize tasks to maximize productivity and reduce stress.", "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1103]}
614
+ elif avg_score >= 30:
615
+ result_dict[key] = {"average_score": avg_score, "name": "Time management", "description": "Refers to an individual`s ability to effectively manage their time and prioritize tasks to maximize productivity and reduce stress.", "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1103]}
616
+ elif avg_score < 30:
617
+ result_dict[key] = {"average_score": avg_score, "name": "Time management", "description": "Refers to an individual`s ability to effectively manage their time and prioritize tasks to maximize productivity and reduce stress.", "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1103]}
618
+
619
+ elif key == 1104:
620
+ if avg_score >= 66:
621
+ result_dict[key] = {"average_score": avg_score, "name": "Educational standards", "description": "Refers to the quality of education provided in a given community, including factors such as curriculum, teaching quality, and access to resources.", "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1104]}
622
+ elif avg_score >= 30:
623
+ result_dict[key] = {"average_score": avg_score, "name": "Educational standards", "description": "Refers to the quality of education provided in a given community, including factors such as curriculum, teaching quality, and access to resources.", "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1104]}
624
+ elif avg_score < 30:
625
+ result_dict[key] = {"average_score": avg_score, "name": "Educational standards", "description": "Refers to the quality of education provided in a given community, including factors such as curriculum, teaching quality, and access to resources.", "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1104]}
626
+
627
+ elif key == 1105:
628
+ if avg_score >= 66:
629
+ result_dict[key] = {"average_score": avg_score, "name": "Cultural diversity", "description": "Refers to the range of cultures, beliefs, and practices within a given community, and the level of acceptance and celebration of diversity.", "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1105]}
630
+ elif avg_score >= 30:
631
+ result_dict[key] = {"average_score": avg_score, "name": "Cultural diversity", "description": "Refers to the range of cultures, beliefs, and practices within a given community, and the level of acceptance and celebration of diversity.", "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1105]}
632
+ elif avg_score < 30:
633
+ result_dict[key] = {"average_score": avg_score, "name": "Cultural diversity", "description": "Refers to the range of cultures, beliefs, and practices within a given community, and the level of acceptance and celebration of diversity.", "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1105]}
634
+
635
+ elif key == 1106:
636
+ if avg_score >= 66:
637
+ result_dict[key] = {"average_score": avg_score, "name": "Social well-being", "description": "Social well-being refers to the quality of an individual`s social interactions, relationships, and sense of community belonging.", "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1106]}
638
+ elif avg_score >= 30:
639
+ result_dict[key] = {"average_score": avg_score, "name": "Social well-being", "description": "Social well-being refers to the quality of an individual`s social interactions, relationships, and sense of community belonging.", "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1106]}
640
+ elif avg_score < 30:
641
+ result_dict[key] = {"average_score": avg_score, "name": "Social well-being", "description": "Social well-being refers to the quality of an individual`s social interactions, relationships, and sense of community belonging.", "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1106]}
642
+
643
+ elif key == 1107:
644
+ if avg_score >= 66:
645
+ result_dict[key] = {"average_score": avg_score, "name": "Good governance", "description": "Refers to the effectiveness and transparency of governing systems and institutions in promoting the well-being of all members of a community.", "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1107]}
646
+ elif avg_score >= 30:
647
+ result_dict[key] = {"average_score": avg_score, "name": "Good governance", "description": "Refers to the effectiveness and transparency of governing systems and institutions in promoting the well-being of all members of a community.", "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1107]}
648
+ elif avg_score < 30:
649
+ result_dict[key] = {"average_score": avg_score, "name": "Good governance", "description": "Refers to the effectiveness and transparency of governing systems and institutions in promoting the well-being of all members of a community.", "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1107]}
650
+
651
+ elif key == 1108:
652
+ if avg_score >= 66:
653
+ result_dict[key] = {"average_score": avg_score, "name": "Community vitality", "description": "Refers to the health and vibrancy of a community, including factors such as social cohesion, civic engagement, and access to resources.", "suggestions_text": [list(eval(d[3])) for d in suggests if d[0] == 1108]}
654
+ elif avg_score >= 30:
655
+ result_dict[key] = {"average_score": avg_score, "name": "Community vitality", "description": "Refers to the health and vibrancy of a community, including factors such as social cohesion, civic engagement, and access to resources.", "suggestions_text": [list(eval(d[2])) for d in suggests if d[0] == 1108]}
656
+ elif avg_score < 30:
657
+ result_dict[key] = {"average_score": avg_score, "name": "Community vitality", "description": "Refers to the health and vibrancy of a community, including factors such as social cohesion, civic engagement, and access to resources.", "suggestions_text": [list(eval(d[1])) for d in suggests if d[0] == 1108]}
658
+
659
+ suggest_dict = dict(sorted(result_dict.items()))
660
+
661
+ curr.execute("SELECT `Questions`,`response`, `result`, `datetime` FROM `custom`, `assessments` WHERE `id`=%s AND `type`=%s AND custom.type = assessments.assessId", (session['id'], session['type'],))
662
+ details = curr.fetchone()
663
+
664
+ mysql.commit()
665
+ curr.close()
666
+
667
+ return render_template("result.html", ques=ques, res1=res[3], res2=res[4], res3=res[6], res4=res[5], res5=dyna, res6=response, res7=suggest_dict, res8=questions, res9=details)
668
+
669
+
670
+ @app.route('/logout')
671
+ def logout():
672
+ app.config['MYSQL_DB'] = 'test'
673
+ now = datetime.datetime.now()
674
+ curo = mysql.cursor()
675
+ if 'id' in session:
676
+ curo.execute("INSERT INTO session (id, email, action, actionC, datetime) VALUES (%s, %s, %s, %s, %s)", (session['id'], session['email'], 'Logged Out - Session Terminated', 0, now,))
677
+ else:
678
+ curo.execute("INSERT INTO session (email, action, actionC, datetime) VALUES (%s, %s, %s, %s)", (session['email'], 'Logged Out - Session Terminated', 0, now,))
679
+
680
+ mysql.commit()
681
+ curo.close()
682
+ session.clear()
683
+ return redirect(url_for("home"))
684
+
685
+
686
+ @app.errorhandler(Exception)
687
+ def handle_error(error):
688
+ app.logger.error(error)
689
+ error_name = error.__class__.__name__
690
+ message = f"{error_name}: {str(error)}"
691
+ return render_template('error.html', message=message), 500
692
+
693
+
694
+ if __name__=='__main__':
695
+ app.run(debug=True, host="0.0.0.0")
696
+ # app.run(debug=True)