Spaces:
Runtime error
Runtime error
File size: 31,787 Bytes
41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 5003121 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 5065afc f5881f3 5065afc f5881f3 5065afc f5881f3 5065afc f5881f3 5065afc f5881f3 5065afc f5881f3 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 5065afc f5881f3 5065afc f5881f3 41b4437 f5881f3 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 2a01ddd 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 5065afc 41b4437 f5881f3 5065afc 41b4437 f5881f3 5065afc f5881f3 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 5065afc f5881f3 5065afc f5881f3 41b4437 f5881f3 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 5065afc f5881f3 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 5065afc 41b4437 f5881f3 41b4437 f5881f3 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 2a01ddd 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 5065afc 41b4437 f5881f3 41b4437 f5881f3 5065afc 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 5065afc 41b4437 f5881f3 41b4437 5065afc f5881f3 41b4437 f5881f3 41b4437 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 5065afc f5881f3 41b4437 f5881f3 41b4437 5065afc f5881f3 41b4437 f5881f3 41b4437 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 5065afc f5881f3 41b4437 f5881f3 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 5065afc f5881f3 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 5065afc 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 5065afc f5881f3 41b4437 5065afc f5881f3 41b4437 5065afc f5881f3 41b4437 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 5065afc f5881f3 41b4437 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 5065afc f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 41b4437 f5881f3 5065afc f5881f3 5065afc f5881f3 5065afc f5881f3 fcdd696 f5881f3 5065afc f5881f3 5065afc f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 f5881f3 fcdd696 5065afc fcdd696 f5881f3 5065afc f5881f3 5065afc f5881f3 5065afc f5881f3 5065afc |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 |
from flask import Flask, render_template, request, redirect, url_for, session
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import mysql.connector
import bcrypt
import datetime
import json
import smtplib
from email.message import EmailMessage
import secrets
import string
mysql = mysql.connector.connect(
host='sql12.freemysqlhosting.net',
user='sql12673861',
password='gURFKWEA9G',
database='sql12673861',
port=3306,
)
app = Flask(__name__)
app.static_folder = 'static'
app.static_url_path = '/static'
app.secret_key = "smilecheck-abhi-2023"
@app.route('/')
def index():
return render_template("index.html")
@app.route('/home', methods=["GET", "POST"])
def home():
if request.method == 'GET':
if 'email' in session:
app.config['MYSQL_DB'] = 'sql12673861'
curh = mysql.cursor()
if session['usertype'] == 0:
curh.execute("SELECT `assessid`, `name` FROM `h_assessments`")
typedata = curh.fetchall()
converted_tuple = tuple({'assessid': item[0], 'name': item[1]} for item in typedata)
curh.execute("SELECT `id`, `type` FROM `h_custom` WHERE id=%s", (session['id'],))
given = curh.fetchall()
isdone = []
for give in given:
isdone.append(give[1])
curh.execute("SELECT `name`, `happy`, `datetime` FROM `h_custom`, `h_assessments` WHERE custom.type = assessments.assessId AND id=%s", (session['id'],))
previous = curh.fetchall()
preprocessed_data = []
for index, row in enumerate(previous):
preprocessed_data.append({
'index': index + 1,
'name': row[0],
'happy': row[1],
'datetime': row[2]
})
return render_template("home.html", typedata=converted_tuple, given=isdone, previous=preprocessed_data )
elif session['usertype'] == 1:
return redirect(url_for('admin'))
mysql.commit()
curh.close()
else:
return redirect(url_for('login'))
if request.method == 'POST':
if 'email' in session:
app.config['MYSQL_DB'] = 'sql12673861'
curh = mysql.cursor()
if 'fname' in request.form:
fname = request.form['fname']
femail = request.form['femail']
feedback = request.form['feedback']
curh.execute("INSERT INTO `h_feedbacks`(`name`, `email`, `feedback`) VALUES (%s, %s, %s)", (fname, femail, feedback,))
mysql.commit()
curh.close()
session['feed'] = 1
return redirect(url_for('home'))
session['type'] = request.form['type']
curh.execute("SELECT `id`, `type` FROM `h_custom` WHERE id=%s AND type=%s", (session['id'], session['type'],))
given = curh.fetchone()
mysql.commit()
curh.close()
if given == None:
return redirect(url_for('form'))
else:
return redirect(url_for('result'))
else:
return redirect(url_for('login'))
return render_template("home.html")
@app.route('/register', methods=["GET", "POST"])
def register():
if request.method == 'GET':
return render_template("register.html", error_code=999, message_code=999)
if request.method == 'POST':
database = request.form['database']
if database == 'database1':
app.config['MYSQL_DB'] = 'sql12673861'
session['database'] = app.config['MYSQL_DB']
elif database == 'database2':
app.config['MYSQL_DB'] = 'sql12673861'
session['database'] = app.config['MYSQL_DB']
name = request.form['name']
email = request.form['email']
cur = mysql.cursor()
cur.execute("SELECT * FROM `h_users` WHERE email = %s", (email,))
user = cur.fetchone()
mysql.commit()
cur.close()
if user:
error = 'Email address already in use. Please use a different email address.'
return render_template('register.html', error=error, error_code=550, message_code=569)
else:
session['name'] = name
session['email'] = email
usertype = 'student'
session['pretype'] = usertype
password = request.form['password'].encode('utf-8')
hash_password = bcrypt.hashpw(password, bcrypt.gensalt())
session['hash'] = hash_password
msg = EmailMessage()
alphabet = string.ascii_letters + string.digits
otp = 'smilecheck-user-'+''.join(secrets.choice(alphabet) for i in range(30))
session['otp'] = otp
msg["Subject"] = "SmileCheck Verification"
msg["From"] = "smilecheck100@gmail.com"
msg["To"] = email
link = f"https://abhicodes-smilecheck.hf.space/verify/{otp}"
html_content = render_template('email.html', name=name, link=link)
msg.set_content(html_content, subtype='html')
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login('smilecheck23@gmail.com', 'dczcfrdkthwcfoqu')
smtp.send_message(msg)
return render_template('register.html', message='An Verification Email has been sent to your email address.', message_code=560, error_code=568)
@app.route('/verify/<otp>')
def verify(otp):
if str(session['otp']) == otp:
app.config['MYSQL_DB'] = 'sql12673861'
cur = mysql.cursor()
cur.execute("INSERT INTO `h_users` (name, email, password) VALUES (%s,%s,%s)", (session['name'], session['email'], session['hash'],))
if session['pretype'] == 'student':
cur.execute("UPDATE `h_users` SET `usertype` = %s WHERE `email`=%s", (0, session['email'],))
session['usertype'] = 0
elif session['pretype'] == 'admin':
cur.execute("UPDATE `h_users` SET `usertype` = %s WHERE `email`=%s", (1, session['email'],))
session['usertype'] = 1
mysql.commit()
cur.close()
session.clear()
redi = 'login'
return render_template('verify.html', message=111, redirect_url=redi)
else:
redi = 'register'
return render_template('verify.html', message=999, redirect_url=redi)
@app.route('/login', methods=["GET", "POST"])
def login():
if request.method == 'GET':
return render_template("login.html", error_code=999)
if request.method == 'POST':
now = datetime.datetime.now()
database = request.form['database']
if database == 'database1':
app.config['MYSQL_DB'] = 'sql12673861'
elif database == 'database2':
app.config['MYSQL_DB'] = 'sql12673861'
email = request.form['email']
password = request.form['password'].encode('utf-8')
curl = mysql.cursor()
curl.execute("SELECT * FROM `h_users` WHERE email=%s", (email,))
user = curl.fetchone()
if user != None:
if bcrypt.hashpw(password, user[4].encode('utf-8')) == user[4].encode('utf-8'):
session['id'] = user[0]
session['name'] = user[2]
session['email'] = user[3]
session['database'] = 'sql12673861'
print(session)
curl.execute("INSERT INTO `h_session` (id, email, action, actionC, datetime) VALUES (%s, %s, %s, %s, %s)", (session['id'], session['email'], 'Logged In - Session Started', 1, now,))
mysql.commit()
curl.close()
if user[1] == 0:
session['usertype'] = 0
return redirect(url_for('home'))
elif user[1] == 1:
session['usertype'] = 1
return redirect(url_for('admin'))
else:
return render_template("login.html", error="Error: Password or Email are incorrect.", error_code=451)
else:
return render_template("login.html", error="Error: User not found. Please register.", error_code=452)
mysql.commit()
curl.close()
else:
return render_template("login.html")
@app.route('/forgot', methods=["GET", "POST"])
def forgot():
if request.method == 'GET':
return render_template("forgot.html")
if request.method == 'POST':
app.config['MYSQL_DB'] = 'sql12673861'
email = request.form['email']
session['email'] = email
curl = mysql.cursor()
curl.execute("SELECT * FROM `h_users` WHERE email=%s", (email,))
user = curl.fetchone()
mysql.commit()
curl.close()
if user != None:
msg = EmailMessage()
name= user[2]
alphabet = string.ascii_letters + string.digits
otp = 'smilecheck-pass-' + ''.join(secrets.choice(alphabet) for i in range(30))
session['otp'] = otp
msg["Subject"] = "SmileCheck Verification"
msg["From"] = "smilecheck100@gmail.com"
msg["To"] = email
link = f"https://abhicodes-smilecheck.hf.space/password/{otp}"
html_content = render_template('pass.html', name=name, link=link)
msg.set_content(html_content, subtype='html')
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login('smilecheck23@gmail.com', 'dczcfrdkthwcfoqu')
smtp.send_message(msg)
return render_template('register.html', message='An Verification Email has been sent to your email address.', message_code=560, error_code=568)
else:
return render_template("forgot.html", mess="No such User Found.")
@app.route('/password/<otp>', methods=["GET", "POST"])
def password(otp):
if str(session['otp']) == otp:
redi = 'change'
return render_template('password.html', message=111, redirect_url=redi)
else:
redi = 'login'
return render_template('password.html', message=999, redirect_url=redi)
@app.route('/change', methods=["GET", "POST"])
def change():
if request.method == 'GET':
return render_template("change.html")
if request.method == 'POST':
app.config['MYSQL_DB'] = 'sql12673861'
password = request.form['password'].encode('utf-8')
hash_password = bcrypt.hashpw(password, bcrypt.gensalt())
curl = mysql.cursor()
curl.execute("UPDATE `h_users` SET `password`=%s WHERE email=%s", (hash_password, session['email'],))
mysql.commit()
curl.close()
session.clear()
return redirect(url_for('login'))
@app.route('/admin', methods=["GET", "POST"])
def admin():
if 'email' in session:
if session['usertype'] == 0:
return redirect(url_for('home'))
else:
return redirect(url_for('login'))
if request.method == 'GET':
if 'email' in session:
app.config['MYSQL_DB'] = 'sql12673861'
cura = mysql.cursor()
cura.execute("SELECT `assessid`, `name` FROM `h_assessments`")
typedata = cura.fetchall()
typedata_tuple = tuple({'assessid': item[0], 'name': item[1]} for item in typedata)
cura.execute("SELECT `id`, `type` FROM `h_custom`")
given = cura.fetchall()
given_tuple = tuple({'id': item[0], 'type': item[1]} for item in given)
isdone = []
for give in given:
isdone.append(give[1])
cura.execute("SELECT `id`, `name`, `email`, `isdone` FROM `h_users` WHERE `usertype` = 0")
res = cura.fetchall()
res_tuple = tuple({'id': item[0], 'name': item[1], 'email': item[2], 'isdone': item[3]} for item in res)
cura.execute("SELECT `assessId`, `name`, `description`, `Questions`, `average` FROM `h_assessments`")
que = cura.fetchall()
que_tuple = tuple({'assessId': item[0], 'name': item[1], 'description': item[2], 'Questions': item[3], 'average': item[4]} for item in que)
cura.execute("SELECT `id`, `type`, `name` FROM `h_custom`, `h_assessments` WHERE h_custom.type = h_assessments.assessId")
abc = cura.fetchall()
abc_tuple = tuple({'id': item[0], 'type': item[1], 'name': item[2]} for item in abc)
ahi = 0.0
for assess in que:
if assess[0] == 101:
ahi = assess[4]
ts = len(res)
tas = len(isdone)
cura.execute("SELECT `name`, `email`, `feedback` FROM `h_feedbacks`")
feeds = cura.fetchall()
feeds_tuple = tuple({'name': item[0], 'email': item[1], 'feedback': item[2]} for item in feeds)
mysql.commit()
cura.close()
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)
if request.method == "POST":
app.config['MYSQL_DB'] = 'sql12673861'
if 'resid' in request.form:
resid = request.form.get('resid')
types = request.form.get('type')
session['id'] = resid
session['type'] = types
return redirect(url_for('result'))
elif 'delete' in request.form:
cura = mysql.cursor()
deleteId = request.form['delete']
cura.execute("DELETE FROM `h_assessments` WHERE `assessId`= %s", (deleteId,))
mysql.commit()
cura.close()
return redirect(url_for('admin'))
return render_template('admin.html')
@app.route('/form', methods=["GET", "POST"])
def form():
if 'email' not in session:
return redirect(url_for('login'))
if request.method == "GET":
app.config['MYSQL_DB'] = 'sql12673861'
typeid = session['type']
curf = mysql.cursor()
curf.execute("SELECT `name`, `description`, `Questions`, `types` FROM `h_assessments` WHERE assessid = %s", (typeid,))
questions = curf.fetchone()
mysql.commit()
curf.close()
return render_template("form.html", questions=questions)
if request.method == "POST":
app.config['MYSQL_DB'] = 'sql12673861'
data = request.form.to_dict()
length = len(request.form)
inp = []
for i in range(0, length):
inp.append(data['inp' + str(i + 1) + ''])
sid_obj = SentimentIntensityAnalyzer()
compound = []
for i in range(0, length):
compound.append(sid_obj.polarity_scores(data['inp' + str(i + 1) + ''])['compound'] * 100)
now = datetime.datetime.now()
cur = mysql.cursor()
query = "INSERT INTO `h_custom` (`Id`, `type`, `response`, `result`, `datetime`) VALUES (%s, %s, %s, %s, %s)"
cur.execute(query, (session['id'], session['type'], json.dumps(inp), json.dumps(compound), now,))
query = "UPDATE `h_users` SET `isdone`=%s WHERE `id`=%s"
cur.execute(query, (1, session['id'],))
cur.execute("SELECT * FROM `h_custom` WHERE id=%s AND type=%s", (session['id'], session['type'],))
res = cur.fetchone()
cur.execute("SELECT qval FROM `h_assessments` WHERE assessId=%s", (session['type'],))
qval = cur.fetchone()
multi = eval(qval[0])
happy = eval(res[4])
for j in range(len(happy)):
happy[j] = happy[j] * multi[j]
min_value = min(compound)
max_value = max(compound)
scaled_values = [(value - min_value) / (max_value - min_value) * 5 for value in compound]
happy_index = round(sum(scaled_values) / len(scaled_values), 2)
query = "UPDATE `h_custom` SET `happy`=%s WHERE `id`=%s AND `type`=%s"
cur.execute(query, (happy_index, session['id'], session['type'],))
cur.execute("SELECT `happy` FROM `h_custom` WHERE type=%s", (session['type'],))
avg_dict = cur.fetchall()
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]]
avg_score = round(sum(avg_list)/len(avg_list), 2)
query = "UPDATE `h_assessments` SET `average`=%s WHERE `assessId`=%s"
cur.execute(query, (avg_score, session['type'],))
mysql.commit()
cur.close()
'''Re-render template...'''
return redirect(url_for('result'))
return redirect(url_for('result'))
@app.route('/custom', methods=["GET", "POST"])
def custom():
if 'email' not in session:
return redirect(url_for('login'))
if request.method == "GET":
if session['usertype'] == 0:
return redirect(url_for('home'))
return render_template('custom.html')
if request.method == "POST":
app.config['MYSQL_DB'] = 'sql12673861'
data = request.form.to_dict()
length = len(request.form)
inp = []
for i in range(0, int((length - 3)/2)):
inp.append(data['inpt' + str(i + 1) + ''])
sid_obj = SentimentIntensityAnalyzer()
compound = []
for i in range(0, int((length - 3)/2)):
compound.append(sid_obj.polarity_scores(data['inpt' + str(i + 1) + ''])['compound'] * 100)
types = []
for i in range(0, int((length - 3) / 2)):
types.append(int(data['select' + str(i + 1) + '']))
for i in range(len(compound)):
if compound[i] < 0:
compound[i] = -1
elif compound[i] >= 0:
compound[i] = 1
name = request.form['name']
describ = request.form['describ']
'''SQL Queries for data storing in database...'''
now = datetime.datetime.now()
cur = mysql.cursor()
query = "INSERT INTO `h_assessments` (`name`, `description`, `Questions`, `types`, `qval`) VALUES (%s, %s, %s, %s, %s)"
cur.execute(query, (name, describ, json.dumps(inp), json.dumps(types), json.dumps(compound),))
mysql.commit()
cur.close()
return redirect(url_for('admin'))
return render_template("custom.html")
@app.route('/result')
def result():
if 'email' not in session:
return redirect(url_for('home'))
app.config['MYSQL_DB'] = 'sql12673861'
curr = mysql.cursor()
curr.execute("SELECT * FROM `h_custom` WHERE id=%s AND type=%s", (session['id'], session['type'],))
res = curr.fetchone()
curr.execute("SELECT `result` FROM `h_custom` WHERE type=%s", (session['type'],))
avg = curr.fetchall()
dynamic = [list(eval(d[0])) for d in avg]
dyna = []
i = 0
for i in range(len(dynamic[i])):
temp2 = 0
for j in range(len(dynamic)):
temp2 = temp2 + dynamic[j][i]
dyna.append(temp2 / len(dynamic))
ques = []
for i in range(1, len(dyna) + 1):
ques.append("Question " + str(i) + "")
curr.execute("SELECT * FROM `h_assessments` WHERE assessid = %s", (session['type'],))
questions = curr.fetchone()
curr.execute("SELECT * FROM `h_suggestions`")
suggests = curr.fetchall()
response = []
mapper = eval(questions[4])
score = eval(res[4])
score_dict = {}
for i in range(len(mapper)):
if mapper[i] not in score_dict:
score_dict[mapper[i]] = []
score_dict[mapper[i]].append(score[i])
result_dict = {}
for key, value in score_dict.items():
temp_score = sum(value) / len(value)
avg_score = round(((temp_score + 100) / 200) * (90 - 10) + 10, 2)
if key == 1101:
if avg_score >= 66:
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]}
elif avg_score >= 30:
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]}
elif avg_score < 30:
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]}
elif key == 1102:
if avg_score >= 66:
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]}
elif avg_score >= 30:
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]}
elif avg_score < 30:
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]}
elif key == 1103:
if avg_score >= 66:
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]}
elif avg_score >= 30:
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]}
elif avg_score < 30:
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]}
elif key == 1104:
if avg_score >= 66:
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]}
elif avg_score >= 30:
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]}
elif avg_score < 30:
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]}
elif key == 1105:
if avg_score >= 66:
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]}
elif avg_score >= 30:
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]}
elif avg_score < 30:
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]}
elif key == 1106:
if avg_score >= 66:
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]}
elif avg_score >= 30:
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]}
elif avg_score < 30:
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]}
elif key == 1107:
if avg_score >= 66:
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]}
elif avg_score >= 30:
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]}
elif avg_score < 30:
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]}
elif key == 1108:
if avg_score >= 66:
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]}
elif avg_score >= 30:
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]}
elif avg_score < 30:
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]}
suggest_dict = dict(sorted(result_dict.items()))
curr.execute(
"SELECT `Questions`,`response`, `result`, `datetime` FROM `h_custom`, `h_assessments` WHERE `id`=%s AND `type`=%s AND h_custom.type = h_assessments.assessId",
(session['id'], session['type'],))
details = curr.fetchone()
mysql.commit()
curr.close()
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)
@app.route('/logout')
def logout():
app.config['MYSQL_DB'] = 'sql12673861'
now = datetime.datetime.now()
curo = mysql.cursor()
if 'id' in session:
curo.execute("INSERT INTO `h_session` (id, email, action, actionC, datetime) VALUES (%s, %s, %s, %s, %s)", (session['id'], session['email'], 'Logged Out - Session Terminated', 0, now,))
else:
curo.execute("INSERT INTO `h_session` (email, action, actionC, datetime) VALUES (%s, %s, %s, %s)", (session['email'], 'Logged Out - Session Terminated', 0, now,))
mysql.commit()
curo.close()
session.clear()
return redirect(url_for("home"))
@app.errorhandler(Exception)
def handle_error(error):
app.logger.error(error)
error_name = error.__class__.__name__
message = f"{error_name}: {str(error)}"
return render_template('error.html', message=message), 500
if __name__=='__main__':
app.run(debug=True, host="0.0.0.0")
# app.run(debug=True) |