File size: 58,920 Bytes
41b4437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
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'))

        @self.app.route('/')
        def index():
            return render_template("index.html")


        @self.app.route('/home', methods=["GET", "POST"])
        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")


        @self.app.route('/register', methods=["GET", "POST"])
        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."

        @self.app.route('/verify/<otp>')
        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)

        @self.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':
                    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")


        @self.app.route('/forgot', methods=["GET", "POST"])
        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.")


        @self.app.route('/password/<otp>', methods=["GET", "POST"])
        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)


        @self.app.route('/change', methods=["GET", "POST"])
        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'))


        @self.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:
                    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')


        @self.app.route('/form', methods=["GET", "POST"])
        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')


        @self.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":
                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")


        @self.app.route('/result')
        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'])

        @self.app.route('/logout')
        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"))


        @self.app.errorhandler(Exception)
        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


"""