Spaces:
Runtime error
Runtime error
from flask import Flask, render_template, request, redirect, url_for, session | |
from nltk.sentiment.vader import SentimentIntensityAnalyzer | |
from flask_mysqldb import MySQL | |
import nltk | |
import io | |
import bcrypt | |
import datetime | |
import json | |
from flask_mail import * | |
import random | |
import smtplib, ssl | |
from email.message import EmailMessage | |
import secrets | |
import string | |
import time | |
nltk.download('vader_lexicon') | |
class SmileCheckApp: | |
def __init__(self): | |
self.app = Flask(__name__) | |
self.app.static_folder = 'static' | |
self.app.static_url_path = '/static' | |
self.app.secret_key = "smilecheck-abhi-2023" | |
self.app.config['MYSQL_HOST'] = 'localhost' | |
self.app.config['MYSQL_USER'] = 'root' | |
self.app.config['MYSQL_PASSWORD'] = '' | |
self.app.config['MYSQL_CURSORCLASS'] = 'DictCursor' | |
self.app.config['MYSQL_PORT'] = 3306 | |
mysql = MySQL(self.app) | |
# @app.before_request | |
# def before_request(): | |
# if request.path != '/logout' and 'email' in session: | |
# session.permanent = True | |
# app.permanent_session_lifetime = datetime.timedelta(minutes=1) | |
# | |
# @app.teardown_request | |
# def teardown_request(exception=None): | |
# if not session.permanent and 'email' in session: return redirect(url_for('logout')) | |
def index(): | |
return render_template("index.html") | |
def home(): | |
if request.method == 'GET': | |
if 'email' in session: | |
self.app.config['MYSQL_DB'] = session['database'] | |
curh = mysql.connection.cursor() | |
if session['usertype'] == 0: | |
curh.execute("SELECT `assessid`, `name` FROM assessments") | |
typedata = curh.fetchall() | |
curh.execute("SELECT `id`, `type` FROM custom WHERE id=%s", (session['id'],)) | |
given = curh.fetchall() | |
isdone = [] | |
for give in given: | |
isdone.append(give['type']) | |
typesgiven = [] | |
for type in typedata: | |
typesgiven.append(type['assessid']) | |
curh.execute("SELECT `name`, `happy`, `datetime` FROM `custom`, `assessments` WHERE custom.type = assessments.assessId AND id=%s", (session['id'],)) | |
previous = curh.fetchall() | |
return render_template("home.html", typedata=typedata, given=isdone, previous=previous) | |
elif session['usertype'] == 1: | |
return redirect(url_for('admin')) | |
mysql.connection.commit() | |
curh.close() | |
else: | |
return redirect(url_for('login')) | |
if request.method == 'POST': | |
if 'email' in session: | |
self.app.config['MYSQL_DB'] = session['database'] | |
curh = mysql.connection.cursor() | |
if 'fname' in request.form: | |
fname = request.form['fname'] | |
femail = request.form['femail'] | |
feedback = request.form['feedback'] | |
curh.execute("INSERT INTO `feedbacks`(`name`, `email`, `feedback`) VALUES (%s, %s, %s)", (fname, femail, feedback,)) | |
mysql.connection.commit() | |
curh.close() | |
session['feed'] = 1 | |
return redirect(url_for('home')) | |
curh.execute("SELECT * FROM users WHERE email=%s", (session['email'],)) | |
user = curh.fetchone() | |
session['type'] = request.form['type'] | |
curh.execute("SELECT `id`, `type` FROM custom WHERE id=%s AND type=%s", (session['id'], session['type'],)) | |
given = curh.fetchone() | |
mysql.connection.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") | |
def register(): | |
now = datetime.datetime.now() | |
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': | |
self.app.config['MYSQL_DB'] = 'test' | |
session['database'] = self.app.config['MYSQL_DB'] | |
elif database == 'database2': | |
self.app.config['MYSQL_DB'] = 'test2' | |
session['database'] = self.app.config['MYSQL_DB'] | |
name = request.form['name'] | |
email = request.form['email'] | |
cur = mysql.connection.cursor() | |
cur.execute("SELECT * FROM users WHERE email = %s", (email,)) | |
user = cur.fetchone() | |
mysql.connection.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() | |
# otp = random.randint(100000, 999999) | |
alphabet = string.ascii_letters + string.digits | |
otp = 'smilecheck-user-'+''.join(secrets.choice(alphabet) for i in range(30)) | |
session['otp'] = otp | |
# with open('static\email.html?name={name}&otp={otp}', 'rb') as f: | |
# html_content = f.read().decode('utf-8') | |
# msg.set_content(html_content, subtype='html') | |
# msg.set_content("The body of the email is here") | |
msg["Subject"] = "SmileCheck Verification" | |
msg["From"] = "[email protected]" | |
msg["To"] = email | |
link = f"http://127.0.0.1:5000/verify/{otp}" | |
html_content = render_template('email.html', name=name, link=link) | |
msg.set_content(html_content, subtype='html') | |
context = ssl.create_default_context() | |
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: | |
smtp.login('[email protected]', '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) | |
return redirect(url_for('home')) | |
# def getmail(): | |
# if request.method=="POST": | |
# email = request.form['email'] | |
# code = hashlib.md5(str(random.randint(0, 1000000)).encode()).hexdigest() | |
# session['code'] = code | |
# link = f"http://127.0.0.1:5000/verify/{code}" | |
# send_email(email, link) | |
# return "A verification email has been sent to your email address. Please click the link in the email to verify your email." | |
def verify(otp): | |
now = datetime.datetime.now() | |
if str(session['otp']) == otp: | |
self.app.config['MYSQL_DB'] = session['database'] | |
cur = mysql.connection.cursor() | |
cur.execute("INSERT INTO users (name, email, password) VALUES (%s,%s,%s)", (session['name'], session['email'], session['hash'],)) | |
if session['pretype'] == 'student': | |
cur.execute("UPDATE `users` SET `usertype` = %s WHERE `email`=%s", (0, session['email'],)) | |
session['usertype'] = 0 | |
elif session['pretype'] == 'admin': | |
cur.execute("UPDATE `users` SET `usertype` = %s WHERE `email`=%s", (1, session['email'],)) | |
session['usertype'] = 1 | |
# cur.execute("SELECT `id` FROM users WHERE email = %s", (session['email'],)) | |
# uid = cur.fetchone() | |
# session['id'] = uid['id'] | |
# 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,)) | |
mysql.connection.commit() | |
cur.close() | |
#destroy session['otp'] and session['hash'] | |
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) | |
# def send_email(email, link): | |
# subject = "Verify Your Email" | |
# body = f"Please click the following link to verify your email: {link}" | |
# message = f"Subject: {subject}\n\n{body}" | |
# sender_email = '[email protected]' # replace with your email | |
# sender_password = 'ABC321VI01' # replace with your password | |
# | |
# with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: | |
# smtp.login(sender_email, sender_password) | |
# smtp.sendmail(sender_email, email, message) | |
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': | |
self.app.config['MYSQL_DB'] = 'test' | |
elif database == 'database2': | |
self.app.config['MYSQL_DB'] = 'test2' | |
email = request.form['email'] | |
password = request.form['password'].encode('utf-8') | |
curl = mysql.connection.cursor() | |
curl.execute("SELECT * FROM users WHERE email=%s", (email,)) | |
user = curl.fetchone() | |
if user != None: | |
if bcrypt.hashpw(password, user["password"].encode('utf-8')) == user["password"].encode('utf-8'): | |
curl.execute("SELECT * FROM session WHERE email=%s ORDER BY `datetime` DESC LIMIT 1", (email,)) | |
userses = curl.fetchone() | |
if userses == None or userses['actionC']==0: | |
session['id'] = user['id'] | |
session['name'] = user['name'] | |
session['email'] = user['email'] | |
session['database'] = self.app.config['MYSQL_DB'] | |
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,)) | |
mysql.connection.commit() | |
curl.close() | |
if user['usertype'] == 0: | |
session['usertype'] = 0 | |
return redirect(url_for('home')) | |
elif user['usertype'] == 1: | |
session['usertype'] = 1 | |
return redirect(url_for('admin')) | |
elif userses['actionC'] == 1: | |
return render_template("login.html", error="Error: Session already in use.", error_code=450) | |
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.connection.commit() | |
curl.close() | |
else: | |
return render_template("login.html") | |
def forgot(): | |
if request.method == 'GET': | |
return render_template("forgot.html") | |
if request.method == 'POST': | |
now = datetime.datetime.now() | |
self.app.config['MYSQL_DB'] = 'test' | |
email = request.form['email'] | |
session['email'] = email | |
curl = mysql.connection.cursor() | |
curl.execute("SELECT * FROM users WHERE email=%s", (email,)) | |
user = curl.fetchone() | |
mysql.connection.commit() | |
curl.close() | |
if user != None: | |
msg = EmailMessage() | |
name= user['name'] | |
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"] = "[email protected]" | |
msg["To"] = email | |
link = f"http://127.0.0.1:5000/password/{otp}" | |
html_content = render_template('pass.html', name=name, link=link) | |
msg.set_content(html_content, subtype='html') | |
context = ssl.create_default_context() | |
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: | |
smtp.login('[email protected]', '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.") | |
def password(otp): | |
now = datetime.datetime.now() | |
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) | |
def change(): | |
if request.method == 'GET': | |
return render_template("change.html") | |
if request.method == 'POST': | |
self.app.config['MYSQL_DB'] = 'test' | |
password = request.form['password'].encode('utf-8') | |
hash_password = bcrypt.hashpw(password, bcrypt.gensalt()) | |
curl = mysql.connection.cursor() | |
curl.execute("UPDATE `users` SET `password`=%s WHERE email=%s", (hash_password, session['email'],)) | |
user = curl.fetchone() | |
mysql.connection.commit() | |
curl.close() | |
session.clear() | |
return redirect(url_for('login')) | |
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: | |
self.app.config['MYSQL_DB'] = session['database'] | |
cura = mysql.connection.cursor() | |
cura.execute("SELECT `assessid`, `name` FROM assessments") | |
typedata = cura.fetchall() | |
cura.execute("SELECT `id`, `type` FROM custom") | |
given = cura.fetchall() | |
isdone = [] | |
for give in given: | |
isdone.append(give['type']) | |
cura.execute("SELECT `id`, `name`, `email`, `isdone` FROM `users` WHERE `usertype` = 0") | |
res = cura.fetchall() | |
cura.execute("SELECT `assessId`, `name`, `description`, `Questions`, `average` FROM `assessments`") | |
que = cura.fetchall() | |
cura.execute("SELECT `id`, `type`, `name` FROM `custom`, `assessments` WHERE custom.type = assessments.assessId") | |
abc = cura.fetchall() | |
ahi = 0.0 | |
for assess in que: | |
if assess['assessId'] == 101: | |
ahi = assess['average'] | |
ts = len(res) | |
tas = len(isdone) | |
cura.execute("SELECT `name`, `email`, `feedback` FROM `feedbacks`") | |
feeds = cura.fetchall() | |
mysql.connection.commit() | |
cura.close() | |
return render_template("admin.html", typedata=typedata, given=given, result=res, assess=que, abc=abc, ts=ts, ahi=ahi, tas=tas, feeds= feeds) | |
if request.method == "POST": | |
self.app.config['MYSQL_DB'] = session['database'] | |
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.connection.cursor() | |
deleteId = request.form['delete'] | |
cura.execute("DELETE FROM `assessments` WHERE `assessId`= %s", (deleteId,)) | |
mysql.connection.commit() | |
cura.close() | |
return redirect(url_for('admin')) | |
# cura = mysql.connection.cursor() | |
# cura.execute("SELECT * FROM `result` WHERE `id` = %s", (resid,)) | |
# chart = cura.fetchone() | |
# | |
# cura.execute("SELECT * FROM `assessments` WHERE `assessid` = %s", (type,)) | |
# chart = cura.fetchone() | |
# mysql.connection.commit() | |
# cura.close() | |
# | |
# return render_template('result.html') | |
return render_template('admin.html') | |
def form(): | |
if 'email' not in session: | |
return redirect(url_for('login')) | |
if request.method == "GET": | |
self.app.config['MYSQL_DB'] = session['database'] | |
typeid = session['type'] | |
curf = mysql.connection.cursor() | |
curf.execute("SELECT `name`, `description`, `Questions`, `types` FROM assessments WHERE assessid = %s", (typeid,)) | |
questions = curf.fetchone() | |
mysql.connection.commit() | |
curf.close() | |
return render_template("form.html", questions=questions) | |
if request.method == "POST": | |
self.app.config['MYSQL_DB'] = session['database'] | |
email = session["email"] | |
'''Sentiment analysis for each response...''' | |
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): | |
# locals()[f"sentiment_dict{i}"] = sid_obj.polarity_scores(data['inp'+ (i+1) +'']) | |
compound.append(sid_obj.polarity_scores(data['inp' + str(i + 1) + ''])['compound'] * 100) | |
'''SQL Queries for data storing in database...''' | |
now = datetime.datetime.now() | |
cur = mysql.connection.cursor() | |
query = "INSERT INTO `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 `users` SET `isdone`=%s WHERE `id`=%s" | |
cur.execute(query, (1, session['id'],)) | |
cur.execute("SELECT * FROM `custom` WHERE id=%s AND type=%s", (session['id'], session['type'],)) | |
res = cur.fetchone() | |
cur.execute("SELECT qval FROM `assessments` WHERE assessId=%s", (session['type'],)) | |
qval = cur.fetchone() | |
happy = [] | |
multi = [] | |
multi = eval(qval['qval']) | |
happy = eval(res['result']) | |
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) | |
# happy_score = round(sum(happy) / len(happy), 4) | |
query = "UPDATE `custom` SET `happy`=%s WHERE `id`=%s AND `type`=%s" | |
cur.execute(query, (happy_index, session['id'], session['type'],)) | |
cur.execute("SELECT `happy` FROM `custom` WHERE type=%s", (session['type'],)) | |
avg_dict = cur.fetchall() | |
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']] | |
avg_score = round(sum(avg_list)/len(avg_list), 2) | |
query = "UPDATE `assessments` SET `average`=%s WHERE `assessId`=%s" | |
cur.execute(query, (avg_score, session['type'],)) | |
mysql.connection.commit() | |
cur.close() | |
'''Re-render template...''' | |
return redirect(url_for('result')) | |
#*********************************************** Further optimization.... | |
# form_data = request.form.to_dict() | |
#*********************************************** | |
# | |
# inp1 = request.form.get("inp1") | |
# inp2 = request.form.get("inp2") | |
# inp3 = request.form.get("inp3") | |
# inp4 = request.form.get("inp4") | |
# inp5 = request.form.get("inp5") | |
# inp6 = request.form.get("inp6") | |
# inp7 = request.form.get("inp7") | |
# inp8 = request.form.get("inp8") | |
# inp9 = request.form.get("inp9") | |
# inp10 = request.form.get("inp10") | |
# | |
# sid_obj = SentimentIntensityAnalyzer() | |
# | |
# sentiment_dict1 = sid_obj.polarity_scores(inp1) | |
# sentiment_dict2 = sid_obj.polarity_scores(inp2) | |
# sentiment_dict3 = sid_obj.polarity_scores(inp3) | |
# sentiment_dict4 = sid_obj.polarity_scores(inp4) | |
# sentiment_dict5 = sid_obj.polarity_scores(inp5) | |
# sentiment_dict6 = sid_obj.polarity_scores(inp6) | |
# sentiment_dict7 = sid_obj.polarity_scores(inp7) | |
# sentiment_dict8 = sid_obj.polarity_scores(inp8) | |
# sentiment_dict9 = sid_obj.polarity_scores(inp9) | |
# sentiment_dict10 = sid_obj.polarity_scores(inp10) | |
# # negative = sentiment_dict['neg'] | |
# # neutral = sentiment_dict['neu'] | |
# # positive = sentiment_dict['pos'] | |
# compound1 = sentiment_dict1['compound'] * 100 | |
# compound2 = sentiment_dict2['compound'] * 100 | |
# compound3 = sentiment_dict3['compound'] * 100 | |
# compound4 = sentiment_dict4['compound'] * 100 | |
# compound5 = sentiment_dict5['compound'] * 100 | |
# compound6 = sentiment_dict6['compound'] * 100 | |
# compound7 = sentiment_dict7['compound'] * 100 | |
# compound8 = sentiment_dict8['compound'] * 100 | |
# compound9 = sentiment_dict9['compound'] * 100 | |
# compound10 = sentiment_dict10['compound'] * 100 | |
# | |
# # _________________________________________________________________________________________________________# | |
# | |
# '''Matlab Plots...''' | |
# | |
# x = ["Q1", "Q2", "Q3", "Q4", "Q5", "Q6", "Q7", "Q8", "Q9", "Q10"] | |
# y = [compound1, compound2, compound3, compound4, compound5, compound6, compound7, compound8, compound9, compound10] | |
# fig, ax = plt.subplots() | |
# plt.bar(x, y) | |
# fig.set_size_inches(10, 6) | |
# img_name = str(session['id']) | |
# fig.savefig('' + img_name + '.png', dpi=384, transparent=True) | |
# with open('' + img_name + '.png', 'rb') as f: | |
# img = f.read() | |
# | |
# # _________________________________________________________________________________________________________# | |
# | |
# '''SQL Queries for data storing in database...''' | |
# | |
# now = datetime.datetime.now() | |
# cur = mysql.connection.cursor() | |
# | |
# 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)" | |
# cur.execute(query, (session['id'], inp1, inp2, inp3, inp4, inp5, inp6, inp7, inp8, inp9, inp10, now)) | |
# | |
# 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)" | |
# cur.execute(query, (session['id'], compound1, compound2, compound3, compound4, compound5, compound6, compound7, compound8, compound9, compound10, img, now)) | |
# | |
# query = "UPDATE `users` SET `isdone`=%s WHERE `id`=%s" | |
# cur.execute(query, (1, session['id'],)) | |
# | |
# mysql.connection.commit() | |
# cur.close() | |
# '''Retrival of data...''' | |
# query = "SELECT Image FROM testy WHERE Id = %s" | |
# cur.execute(query, (103)) | |
# row = cur.fetchone() | |
# img = Image.open(io.BytesIO(row[0])) | |
# cur.close() | |
# | |
# plt.imshow(img) | |
# plt.show() | |
# _________________________________________________________________________________________________________# | |
return redirect(url_for('result')) | |
# def index(): | |
# if request.method == "POST": | |
# | |
# '''Matlab Plots...''' | |
# x = ["a", "b", "c", "d"] | |
# y = [85,90,70,75] | |
# fig, ax = plt.subplots() | |
# plt.bar(x, y) | |
# fig.set_size_inches(10, 6) | |
# fig.savefig('foo.png', dpi=384, transparent=True) | |
# with open('foo.png', 'rb') as f: | |
# img = f.read() | |
# # _________________________________________________________________________________________________________# | |
# | |
# '''SQL Queries for data storing in database...''' | |
# cur = mysql.connection.cursor() | |
# query = "INSERT INTO `testy` (`Id`, `Q1`, `Q2`, `Q3`, `Image`) VALUES (%s, %s, %s, %s, %s)" | |
# cur.execute(query, (103, 2, 3, 1, img)) | |
# mysql.connection.commit() | |
# | |
# query = "SELECT Image FROM testy WHERE Id = %s" | |
# cur.execute(query, (103,)) | |
# row = cur.fetchone() | |
# img = Image.open(io.BytesIO(row[0])) | |
# cur.close() | |
# | |
# plt.imshow(img) | |
# plt.show() | |
# # _________________________________________________________________________________________________________# | |
# | |
# | |
# '''Sentiment analysis for each response...''' | |
# inp = request.form.get("inp1") | |
# name = request.form.get("name") | |
# sid_obj = SentimentIntensityAnalyzer() | |
# # score = sid.polarity_scores(inp) | |
# # if score["neg"] > 0: | |
# # return render_template('home.html', message="Negative") | |
# # if score["neg"] == 0: | |
# # return render_template('home.html', message="Neutral") | |
# # else: | |
# # return render_template('home.html', message="Positive") | |
# | |
# sentiment_dict = sid_obj.polarity_scores(inp) | |
# negative = sentiment_dict['neg'] | |
# neutral = sentiment_dict['neu'] | |
# positive = sentiment_dict['pos'] | |
# compound = sentiment_dict['compound'] | |
# | |
# return render_template('home.html', message=sentiment_dict['compound'], names=name) | |
# | |
# # if sentiment_dict['compound'] >= 0.05: | |
# # return render_template('home.html', message="Positive") | |
# # | |
# # elif sentiment_dict['compound'] <= - 0.05: | |
# # return render_template('home.html', message="Negative") | |
# # | |
# # else: | |
# # return render_template('home.html', message="Neutral") | |
# | |
# # _________________________________________________________________________________________________________# | |
# | |
# return render_template('home.html') | |
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": | |
self.app.config['MYSQL_DB'] = session['database'] | |
email = session["email"] | |
'''Sentiment analysis for each response...''' | |
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.connection.cursor() | |
query = "INSERT INTO `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.connection.commit() | |
cur.close() | |
return redirect(url_for('admin')) | |
return render_template("custom.html") | |
def result(): | |
if 'email' not in session: | |
return redirect(url_for('home')) | |
self.app.config['MYSQL_DB'] = session['database'] | |
curr = mysql.connection.cursor() | |
curr.execute("SELECT * FROM `custom` WHERE id=%s AND type=%s", (session['id'], session['type'],)) | |
res = curr.fetchone() | |
curr.execute("SELECT result FROM `custom` WHERE type=%s", (session['type'],)) | |
avg = curr.fetchall() | |
# curr.execute("SELECT qval FROM `assessments` WHERE assessId=%s", (session['type'],)) | |
# qval = curr.fetchone() | |
dynamic = [list(eval(d['result'])) for d in avg] | |
# Personal Average per questions will be compared.... | |
# average = [] | |
# multi = [] | |
# multi = eval(qval['qval']) | |
# for i in range(len(avg)): | |
# temp = eval(avg[i]['result']) | |
# for j in range(len(temp)): | |
# temp[j] = temp[j] * multi[j] | |
# average.append(sum(temp) / len(temp)) | |
#Compute Happiness Index | |
# happy = [] | |
# multi = [] | |
# multi = eval(qval['qval']) | |
# happy = eval(res['result']) | |
# for j in range(len(happy)): | |
# happy[j] = happy[j] * multi[j] | |
# happy_score = round(sum(happy) / len(happy), 4) | |
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 assessments WHERE assessid = %s", (session['type'],)) | |
questions = curr.fetchone() | |
curr.execute("SELECT * FROM suggestions") | |
suggests = curr.fetchall() | |
response = [] | |
mapper = eval(questions['types']) | |
score = eval(res['result']) | |
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['good'])) for d in suggests if d['idtype'] == 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['average'])) for d in suggests if d['idtype'] == 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['bad'])) for d in suggests if d['idtype'] == 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['good'])) for d in suggests if d['idtype'] == 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['average'])) for d in suggests if d['idtype'] == 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['bad'])) for d in suggests if d['idtype'] == 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['good'])) for d in suggests if d['idtype'] == 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['average'])) for d in suggests if d['idtype'] == 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['bad'])) for d in suggests if d['idtype'] == 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['good'])) for d in suggests if d['idtype'] == 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['average'])) for d in suggests if d['idtype'] == 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['bad'])) for d in suggests if d['idtype'] == 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['good'])) for d in suggests if d['idtype'] == 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['average'])) for d in suggests if d['idtype'] == 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['bad'])) for d in suggests if d['idtype'] == 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['good'])) for d in suggests if d['idtype'] == 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['average'])) for d in suggests if d['idtype'] == 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['bad'])) for d in suggests if d['idtype'] == 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['good'])) for d in suggests if d['idtype'] == 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['average'])) for d in suggests if d['idtype'] == 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['bad'])) for d in suggests if d['idtype'] == 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['good'])) for d in suggests if d['idtype'] == 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['average'])) for d in suggests if d['idtype'] == 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['bad'])) for d in suggests if d['idtype'] == 1108]} | |
suggest_dict = dict(sorted(result_dict.items())) | |
# for i in range(len(score)): | |
# if score[i] == 999: | |
# response.append({'none'}) | |
# | |
# elif score[i] >= 66: | |
# if mapper[i] == 1101: | |
# new_dict = { | |
# 'domain': 'Psychological well being', | |
# 'describ': 'Refers to an individual`s mental state and overall happiness, including feelings of fulfillment, purpose, and contentment.', | |
# 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1101] | |
# } | |
# elif mapper[i] == 1102: | |
# new_dict = { | |
# 'domain': 'Health aspects', | |
# 'describ': 'Refers to an individual`s physical health, including factors such as nutrition, exercise, and access to medical care.', | |
# 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1102] | |
# } | |
# elif mapper[i] == 1103: | |
# new_dict = { | |
# 'domain': 'Time management', | |
# 'describ': 'Refers to an individual`s ability to effectively manage their time and prioritize tasks to maximize productivity and reduce stress.', | |
# 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1103] | |
# } | |
# elif mapper[i] == 1104: | |
# new_dict = { | |
# 'domain': 'Educational standards', | |
# 'describ': 'Refers to the quality of education provided in a given community, including factors such as curriculum, teaching quality, and access to resources.', | |
# 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1104] | |
# } | |
# elif mapper[i] == 1105: | |
# new_dict = { | |
# 'domain': 'Cultural diversity', | |
# 'describ': 'Refers to the range of cultures, beliefs, and practices within a given community, and the level of acceptance and celebration of diversity.', | |
# 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1105] | |
# } | |
# elif mapper[i] == 1106: | |
# new_dict = { | |
# 'domain': 'Social well-being', | |
# 'describ': 'Social well-being refers to the quality of an individual`s social interactions, relationships, and sense of community belonging.', | |
# 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1106] | |
# } | |
# elif mapper[i] == 1107: | |
# new_dict = { | |
# 'domain': 'Good governance', | |
# 'describ': 'Refers to the effectiveness and transparency of governing systems and institutions in promoting the well-being of all members of a community.', | |
# 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1107] | |
# } | |
# elif mapper[i] == 1108: | |
# new_dict = { | |
# 'domain': 'Community vitality', | |
# 'describ': 'Refers to the health and vibrancy of a community, including factors such as social cohesion, civic engagement, and access to resources.', | |
# 'suggest': [list(eval(d['good'])) for d in suggests if d['idtype'] == 1108] | |
# } | |
# response.append(new_dict) | |
# | |
# elif score[i] >= 40: | |
# if mapper[i] == 1101: | |
# new_dict = { | |
# 'domain': 'Psychological well being', | |
# 'describ': 'Refers to an individual`s mental state and overall happiness, including feelings of fulfillment, purpose, and contentment.', | |
# 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1101] | |
# } | |
# elif mapper[i] == 1102: | |
# new_dict = { | |
# 'domain': 'Health aspects', | |
# 'describ': 'Refers to an individual`s physical health, including factors such as nutrition, exercise, and access to medical care.', | |
# 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1102] | |
# } | |
# elif mapper[i] == 1103: | |
# new_dict = { | |
# 'domain': 'Time management', | |
# 'describ': 'Refers to an individual`s ability to effectively manage their time and prioritize tasks to maximize productivity and reduce stress.', | |
# 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1103] | |
# } | |
# elif mapper[i] == 1104: | |
# new_dict = { | |
# 'domain': 'Educational standards', | |
# 'describ': 'Refers to the quality of education provided in a given community, including factors such as curriculum, teaching quality, and access to resources.', | |
# 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1104] | |
# } | |
# elif mapper[i] == 1105: | |
# new_dict = { | |
# 'domain': 'Cultural diversity', | |
# 'describ': 'Refers to the range of cultures, beliefs, and practices within a given community, and the level of acceptance and celebration of diversity.', | |
# 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1105] | |
# } | |
# elif mapper[i] == 1106: | |
# new_dict = { | |
# 'domain': 'Social well-being', | |
# 'describ': 'Social well-being refers to the quality of an individual`s social interactions, relationships, and sense of community belonging.', | |
# 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1106] | |
# } | |
# elif mapper[i] == 1107: | |
# new_dict = { | |
# 'domain': 'Good governance', | |
# 'describ': 'Refers to the effectiveness and transparency of governing systems and institutions in promoting the well-being of all members of a community.', | |
# 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1107] | |
# } | |
# elif mapper[i] == 1108: | |
# new_dict = { | |
# 'domain': 'Community vitality', | |
# 'describ': 'Refers to the health and vibrancy of a community, including factors such as social cohesion, civic engagement, and access to resources.', | |
# 'suggest': [list(eval(d['average'])) for d in suggests if d['idtype'] == 1108] | |
# } | |
# response.append(new_dict) | |
# | |
# elif score[i] < 40: | |
# if mapper[i] == 1101: | |
# new_dict = { | |
# 'domain': 'Psychological well being', | |
# 'describ': 'Refers to an individual`s mental state and overall happiness, including feelings of fulfillment, purpose, and contentment.', | |
# 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1101] | |
# } | |
# elif mapper[i] == 1102: | |
# new_dict = { | |
# 'domain': 'Health aspects', | |
# 'describ': 'Refers to an individual`s physical health, including factors such as nutrition, exercise, and access to medical care.', | |
# 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1102] | |
# } | |
# elif mapper[i] == 1103: | |
# new_dict = { | |
# 'domain': 'Time management', | |
# 'describ': 'Refers to an individual`s ability to effectively manage their time and prioritize tasks to maximize productivity and reduce stress.', | |
# 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1103] | |
# } | |
# elif mapper[i] == 1104: | |
# new_dict = { | |
# 'domain': 'Educational standards', | |
# 'describ': 'Refers to the quality of education provided in a given community, including factors such as curriculum, teaching quality, and access to resources.', | |
# 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1104] | |
# } | |
# elif mapper[i] == 1105: | |
# new_dict = { | |
# 'domain': 'Cultural diversity', | |
# 'describ': 'Refers to the range of cultures, beliefs, and practices within a given community, and the level of acceptance and celebration of diversity.', | |
# 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1105] | |
# } | |
# elif mapper[i] == 1106: | |
# new_dict = { | |
# 'domain': 'Social well-being', | |
# 'describ': 'Social well-being refers to the quality of an individual`s social interactions, relationships, and sense of community belonging.', | |
# 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1106] | |
# } | |
# elif mapper[i] == 1107: | |
# new_dict = { | |
# 'domain': 'Good governance', | |
# 'describ': 'Refers to the effectiveness and transparency of governing systems and institutions in promoting the well-being of all members of a community.', | |
# 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1107] | |
# } | |
# elif mapper[i] == 1108: | |
# new_dict = { | |
# 'domain': 'Community vitality', | |
# 'describ': 'Refers to the health and vibrancy of a community, including factors such as social cohesion, civic engagement, and access to resources.', | |
# 'suggest': [list(eval(d['bad'])) for d in suggests if d['idtype'] == 1108] | |
# } | |
# response.append(new_dict) | |
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'],)) | |
details = curr.fetchone() | |
mysql.connection.commit() | |
curr.close() | |
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) | |
# @app.route('/customresult') | |
# def customresult(): | |
# app.config['MYSQL_DB'] = session['database'] | |
# curr = mysql.connection.cursor() | |
# curr.execute("SELECT * FROM `custom` WHERE id=%s", (session['id'],)) | |
# res = curr.fetchone() | |
# mysql.connection.commit() | |
# curr.close() | |
# | |
# ques = [] | |
# for i in range(1, len(res)): | |
# ques.append("Q"+ str(i) +"") | |
# | |
# return render_template("customresult.html", ques=ques, res1=res['response'], res2=res['result'], res3=res['datetime']) | |
def logout(): | |
self.app.config['MYSQL_DB'] = session['database'] | |
now = datetime.datetime.now() | |
curo = mysql.connection.cursor() | |
if 'id' in session: | |
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,)) | |
else: | |
curo.execute("INSERT INTO session (email, action, actionC, datetime) VALUES (%s, %s, %s, %s)", (session['email'], 'Logged Out - Session Terminated', 0, now,)) | |
mysql.connection.commit() | |
curo.close() | |
session.clear() | |
return redirect(url_for("home")) | |
def handle_error(error): | |
self.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__': | |
my_app = SmileCheckApp() | |
my_app.app.run(debug=True) | |
# app.run(debug=True) | |
""" | |
python -m flask run | |
Vader | |
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. | |
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. | |
@app.route('/submit', methods=['POST']) | |
def handle_submit(): | |
if 'form1' in request.form: | |
# Handle form1 submission code here | |
return 'Form 1 submitted successfully' | |
elif 'form2' in request.form: | |
# Handle form2 submission code here | |
return 'Form 2 submitted successfully' | |
else: | |
# Handle case where neither form1 nor form2 were submitted | |
return 'Invalid form submission' | |
<form method="post" action="/submit"> | |
<!-- Form 1 fields here --> | |
<button type="submit" name="form1">Submit Form 1</button> | |
</form> | |
<form method="post" action="/submit"> | |
<!-- Form 2 fields here --> | |
<button type="submit" name="form2">Submit Form 2</button> | |
</form> | |
if there are two forms in my html template i want run two different flask codes with post request from each form | |
no within a single app route but with two different forms | |
""" |