-
Notifications
You must be signed in to change notification settings - Fork 100
/
app.py
1835 lines (1711 loc) · 75.5 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
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
from flask import Flask, request, render_template, flash, redirect, url_for,session, logging, send_file, jsonify, Response, render_template_string
from flask_mysqldb import MySQL
from wtforms import Form, StringField, TextAreaField, PasswordField, validators, DateTimeField, BooleanField, IntegerField, DecimalField, HiddenField, SelectField, RadioField
from flask_wtf import FlaskForm
from flask_wtf.file import FileField, FileRequired, FileAllowed
from flask_mail import Mail, Message
from functools import wraps
from werkzeug.utils import secure_filename
from coolname import generate_slug
from datetime import timedelta, datetime
from objective import ObjectiveTest
from subjective import SubjectiveTest
from deepface import DeepFace
import pandas as pd
import stripe
import operator
import functools
import math, random
import csv
import cv2
import numpy as np
import json
import base64
from wtforms_components import TimeField
from wtforms.fields.html5 import DateField
from wtforms.validators import ValidationError, NumberRange
from flask_session import Session
from flask_cors import CORS, cross_origin
import camera
app = Flask(__name__)
app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PORT'] = 3308
app.config['MYSQL_PASSWORD'] = 'your pwd'
app.config['MYSQL_DB'] = 'quizapp'
app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
app.config['MAIL_SERVER']='smtp.stackmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USERNAME'] = '[email protected]'
app.config['MAIL_PASSWORD'] = 'password'
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
app.config['SESSION_COOKIE_SAMESITE'] = "None"
app.config['SESSION_TYPE'] = 'filesystem'
app.config["TEMPLATES_AUTO_RELOAD"] = True
stripe_keys = {
"secret_key": "dummy",
"publishable_key": "dummy",
}
stripe.api_key = stripe_keys["secret_key"]
mail = Mail(app)
sess = Session()
sess.init_app(app)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
app.secret_key= 'sem6project'
mysql = MySQL(app)
sender = '[email protected]'
YOUR_DOMAIN = 'http://localhost:5000'
@app.before_request
def make_session_permanent():
session.permanent = True
def user_role_professor(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
if session['user_role']=="teacher":
return f(*args, **kwargs)
else:
flash('You dont have privilege to access this page!','danger')
return render_template("404.html")
else:
flash('Unauthorized, Please login!','danger')
return redirect(url_for('login'))
return wrap
def user_role_student(f):
@wraps(f)
def wrap(*args, **kwargs):
if 'logged_in' in session:
if session['user_role']=="student":
return f(*args, **kwargs)
else:
flash('You dont have privilege to access this page!','danger')
return render_template("404.html")
else:
flash('Unauthorized, Please login!','danger')
return redirect(url_for('login'))
return wrap
@app.route("/config")
@user_role_professor
def get_publishable_key():
stripe_config = {"publicKey": stripe_keys["publishable_key"]}
return jsonify(stripe_config)
@app.route('/video_feed', methods=['GET','POST'])
@user_role_student
def video_feed():
if request.method == "POST":
imgData = request.form['data[imgData]']
testid = request.form['data[testid]']
voice_db = request.form['data[voice_db]']
proctorData = camera.get_frame(imgData)
jpg_as_text = proctorData['jpg_as_text']
mob_status =proctorData['mob_status']
person_status = proctorData['person_status']
user_move1 = proctorData['user_move1']
user_move2 = proctorData['user_move2']
eye_movements = proctorData['eye_movements']
cur = mysql.connection.cursor()
results = cur.execute('INSERT INTO proctoring_log (email, name, test_id, voice_db, img_log, user_movements_updown, user_movements_lr, user_movements_eyes, phone_detection, person_status, uid) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',
(dict(session)['email'], dict(session)['name'], testid, voice_db, jpg_as_text, user_move1, user_move2, eye_movements, mob_status, person_status,dict(session)['uid']))
mysql.connection.commit()
cur.close()
if(results > 0):
return "recorded image of video"
else:
return "error in video"
@app.route('/window_event', methods=['GET','POST'])
@user_role_student
def window_event():
if request.method == "POST":
testid = request.form['testid']
cur = mysql.connection.cursor()
results = cur.execute('INSERT INTO window_estimation_log (email, test_id, name, window_event, uid) values(%s,%s,%s,%s,%s)', (dict(session)['email'], testid, dict(session)['name'], 1, dict(session)['uid']))
mysql.connection.commit()
cur.close()
if(results > 0):
return "recorded window"
else:
return "error in window"
@app.route('/create-checkout-session', methods=['POST'])
def create_checkout_session():
try:
checkout_session = stripe.checkout.Session.create(
payment_method_types=['card'],
line_items=[
{
'price_data': {
'currency': 'inr',
'unit_amount': 499*100,
'product_data': {
'name': 'Basic Exam Plan of 10 units',
'images': ['https://i.imgur.com/LsvO3kL_d.webp?maxwidth=760&fidelity=grand'],
},
},
'quantity': 1,
},
],
mode='payment',
success_url=YOUR_DOMAIN + '/success',
cancel_url=YOUR_DOMAIN + '/cancelled',
)
return jsonify({'id': checkout_session.id})
except Exception as e:
return jsonify(error=str(e)), 403
@app.route("/livemonitoringtid")
@user_role_professor
def livemonitoringtid():
cur = mysql.connection.cursor()
results = cur.execute('SELECT * from teachers where email = %s and uid = %s and proctoring_type = 1', (session['email'], session['uid']))
if results > 0:
cresults = cur.fetchall()
now = datetime.now()
now = now.strftime("%Y-%m-%d %H:%M:%S")
now = datetime.strptime(now,"%Y-%m-%d %H:%M:%S")
testids = []
for a in cresults:
if datetime.strptime(str(a['start']),"%Y-%m-%d %H:%M:%S") <= now and datetime.strptime(str(a['end']),"%Y-%m-%d %H:%M:%S") >= now:
testids.append(a['test_id'])
cur.close()
return render_template("livemonitoringtid.html", cresults = testids)
else:
return render_template("livemonitoringtid.html", cresults = None)
@app.route('/live_monitoring', methods=['GET','POST'])
@user_role_professor
def live_monitoring():
if request.method == 'POST':
testid = request.form['choosetid']
return render_template('live_monitoring.html',testid = testid)
else:
return render_template('live_monitoring.html',testid = None)
@app.route("/success")
@user_role_professor
def success():
cur = mysql.connection.cursor()
cur.execute('UPDATE users set examcredits = examcredits+10 where email = %s and uid = %s', (session['email'], session['uid']))
mysql.connection.commit()
cur.close()
return render_template("success.html")
@app.route("/cancelled")
@user_role_professor
def cancelled():
return render_template("cancelled.html")
@app.route("/payment")
@user_role_professor
def payment():
cur = mysql.connection.cursor()
cur.execute('SELECT examcredits FROM USERS where email = %s and uid = %s', (session['email'], session['uid']))
callresults = cur.fetchone()
cur.close()
return render_template("payment.html", key = stripe_keys['publishable_key'], callresults = callresults)
@app.route('/')
def index():
return render_template('index.html')
@app.errorhandler(404)
def not_found(e):
return render_template("404.html")
@app.errorhandler(500)
def internal_error(error):
return render_template("500.html")
@app.route('/calc')
def calc():
return render_template('calc.html')
@app.route('/report_professor')
@user_role_professor
def report_professor():
return render_template('report_professor.html')
@app.route('/student_index')
@user_role_student
def student_index():
return render_template('student_index.html')
@app.route('/professor_index')
@user_role_professor
def professor_index():
return render_template('professor_index.html')
@app.route('/faq')
def faq():
return render_template('faq.html')
@app.route('/report_student')
@user_role_student
def report_student():
return render_template('report_student.html')
@app.route('/report_professor_email', methods=['GET','POST'])
@user_role_professor
def report_professor_email():
if request.method == 'POST':
careEmail = "[email protected]"
cname = session['name']
cemail = session['email']
ptype = request.form['prob_type']
cquery = request.form['rquery']
msg1 = Message('PROBLEM REPORTED', sender = sender, recipients = [careEmail])
msg1.body = " ".join(["NAME:", cname, "PROBLEM TYPE:", ptype ,"EMAIL:", cemail, "", "QUERY:", cquery])
mail.send(msg1)
flash('Your Problem has been recorded.', 'success')
return render_template('report_professor.html')
@app.route('/report_student_email', methods=['GET','POST'])
@user_role_student
def report_student_email():
if request.method == 'POST':
careEmail = "[email protected]"
cname = session['name']
cemail = session['email']
ptype = request.form['prob_type']
cquery = request.form['rquery']
msg1 = Message('PROBLEM REPORTED', sender = sender, recipients = [careEmail])
msg1.body = " ".join(["NAME:", cname, "PROBLEM TYPE:", ptype ,"EMAIL:", cemail, "", "QUERY:", cquery])
mail.send(msg1)
flash('Your Problem has been recorded.', 'success')
return render_template('report_student.html')
@app.route('/contact', methods=['GET','POST'])
def contact():
if request.method == 'POST':
careEmail = "[email protected]"
cname = request.form['cname']
cemail = request.form['cemail']
cquery = request.form['cquery']
msg1 = Message('Hello', sender = sender, recipients = [cemail])
msg2 = Message('Hello', sender = sender, recipients = [careEmail])
msg1.body = "YOUR QUERY WILL BE PROCESSED! WITHIN 24 HOURS"
msg2 = Message('Hello', sender = sender, recipients = [careEmail])
msg2.body = " ".join(["NAME:", cname, "EMAIL:", cemail, "QUERY:", cquery])
mail.send(msg1)
mail.send(msg2)
flash('Your Query has been recorded.', 'success')
return render_template('contact.html')
@app.route('/lostpassword', methods=['GET','POST'])
def lostpassword():
if request.method == 'POST':
lpemail = request.form['lpemail']
cur = mysql.connection.cursor()
results = cur.execute('SELECT * from users where email = %s' , [lpemail])
if results > 0:
sesOTPfp = generateOTP()
session['tempOTPfp'] = sesOTPfp
session['seslpemail'] = lpemail
msg1 = Message('MyProctor.ai - OTP Verification for Lost Password', sender = sender, recipients = [lpemail])
msg1.body = "Your OTP Verfication code for reset password is "+sesOTPfp+"."
mail.send(msg1)
return redirect(url_for('verifyOTPfp'))
else:
return render_template('lostpassword.html',error="Account not found.")
return render_template('lostpassword.html')
@app.route('/verifyOTPfp', methods=['GET','POST'])
def verifyOTPfp():
if request.method == 'POST':
fpOTP = request.form['fpotp']
fpsOTP = session['tempOTPfp']
if(fpOTP == fpsOTP):
return redirect(url_for('lpnewpwd'))
return render_template('verifyOTPfp.html')
@app.route('/lpnewpwd', methods=['GET','POST'])
def lpnewpwd():
if request.method == 'POST':
npwd = request.form['npwd']
cpwd = request.form['cpwd']
slpemail = session['seslpemail']
if(npwd == cpwd ):
cur = mysql.connection.cursor()
cur.execute('UPDATE users set password = %s where email = %s', (npwd, slpemail))
mysql.connection.commit()
cur.close()
session.clear()
return render_template('login.html',success="Your password was successfully changed.")
else:
return render_template('login.html',error="Password doesn't matched.")
return render_template('lpnewpwd.html')
@app.route('/generate_test')
@user_role_professor
def generate_test():
return render_template('generatetest.html')
@app.route('/changepassword_professor')
@user_role_professor
def changepassword_professor():
return render_template('changepassword_professor.html')
@app.route('/changepassword_student')
@user_role_student
def changepassword_student():
return render_template('changepassword_student.html')
def generateOTP() :
digits = "0123456789"
OTP = ""
for i in range(5) :
OTP += digits[math.floor(random.random() * 10)]
return OTP
@app.route('/register', methods=['GET','POST'])
def register():
if request.method == 'POST':
name = request.form['name']
email = request.form['email']
password = request.form['password']
user_type = request.form['user_type']
imgdata = request.form['image_hidden']
session['tempName'] = name
session['tempEmail'] = email
session['tempPassword'] = password
session['tempUT'] = user_type
session['tempImage'] = imgdata
sesOTP = generateOTP()
session['tempOTP'] = sesOTP
msg1 = Message('MyProctor.ai - OTP Verification', sender = sender, recipients = [email])
msg1.body = "New Account opening - Your OTP Verfication code is "+sesOTP+"."
mail.send(msg1)
return redirect(url_for('verifyEmail'))
return render_template('register.html')
@app.route('/login', methods=['GET','POST'])
def login():
if request.method == 'POST':
email = request.form['email']
password_candidate = request.form['password']
user_type = request.form['user_type']
imgdata1 = request.form['image_hidden']
cur = mysql.connection.cursor()
results1 = cur.execute('SELECT uid, name, email, password, user_type, user_image from users where email = %s and user_type = %s and user_login = 0' , (email,user_type))
if results1 > 0:
cresults = cur.fetchone()
imgdata2 = cresults['user_image']
password = cresults['password']
name = cresults['name']
uid = cresults['uid']
nparr1 = np.frombuffer(base64.b64decode(imgdata1), np.uint8)
nparr2 = np.frombuffer(base64.b64decode(imgdata2), np.uint8)
image1 = cv2.imdecode(nparr1, cv2.COLOR_BGR2GRAY)
image2 = cv2.imdecode(nparr2, cv2.COLOR_BGR2GRAY)
img_result = DeepFace.verify(image1, image2, enforce_detection = False)
if img_result["verified"] == True and password == password_candidate:
results2 = cur.execute('UPDATE users set user_login = 1 where email = %s' , [email])
mysql.connection.commit()
if results2 > 0:
session['logged_in'] = True
session['email'] = email
session['name'] = name
session['user_role'] = user_type
session['uid'] = uid
if user_type == "student":
return redirect(url_for('student_index'))
else:
return redirect(url_for('professor_index'))
else:
error = 'Error Occurred!'
return render_template('login.html', error=error)
else:
error = 'Either Image not Verified or you have entered Invalid password or Already login'
return render_template('login.html', error=error)
cur.close()
else:
error = 'Already Login or Email was not found!'
return render_template('login.html', error=error)
return render_template('login.html')
@app.route('/verifyEmail', methods=['GET','POST'])
def verifyEmail():
if request.method == 'POST':
theOTP = request.form['eotp']
mOTP = session['tempOTP']
dbName = session['tempName']
dbEmail = session['tempEmail']
dbPassword = session['tempPassword']
dbUser_type = session['tempUT']
dbImgdata = session['tempImage']
if(theOTP == mOTP):
cur = mysql.connection.cursor()
ar = cur.execute('INSERT INTO users(name, email, password, user_type, user_image, user_login) values(%s,%s,%s,%s,%s,%s)', (dbName, dbEmail, dbPassword, dbUser_type, dbImgdata,0))
mysql.connection.commit()
if ar > 0:
flash("Thanks for registering! You are sucessfully verified!.")
return redirect(url_for('login'))
else:
flash("Error Occurred!")
return redirect(url_for('login'))
cur.close()
session.clear()
else:
return render_template('register.html',error="OTP is incorrect.")
return render_template('verifyEmail.html')
@app.route('/changepassword', methods=["GET", "POST"])
def changePassword():
if request.method == "POST":
oldPassword = request.form['oldpassword']
newPassword = request.form['newpassword']
cur = mysql.connection.cursor()
results = cur.execute('SELECT * from users where email = %s and uid = %s', (session['email'], session['uid']))
if results > 0:
data = cur.fetchone()
password = data['password']
usertype = data['user_type']
if(password == oldPassword):
cur.execute("UPDATE users SET password = %s WHERE email = %s", (newPassword, session['email']))
mysql.connection.commit()
msg="Changed successfully"
flash('Changed successfully.', 'success')
cur.close()
if usertype == "student":
return render_template("student_index.html", success=msg)
else:
return render_template("professor_index.html", success=msg)
else:
error = "Wrong password"
if usertype == "student":
return render_template("student_index.html", error=error)
else:
return render_template("professor_index.html", error=error)
else:
return redirect(url_for('/'))
@app.route('/logout', methods=["GET", "POST"])
def logout():
cur = mysql.connection.cursor()
lbr = cur.execute('UPDATE users set user_login = 0 where email = %s and uid = %s',(session['email'],session['uid']))
mysql.connection.commit()
if lbr > 0:
session.clear()
return "success"
else:
return "error"
def examcreditscheck():
cur = mysql.connection.cursor()
results = cur.execute('SELECT examcredits from users where examcredits >= 1 and email = %s and uid = %s', (session['email'], session['uid']))
if results > 0:
return True
class QAUploadForm(FlaskForm):
subject = StringField('Subject')
topic = StringField('Topic')
doc = FileField('CSV Upload', validators=[FileRequired()])
start_date = DateField('Start Date')
start_time = TimeField('Start Time', default=datetime.utcnow()+timedelta(hours=5.5))
end_date = DateField('End Date')
end_time = TimeField('End Time', default=datetime.utcnow()+timedelta(hours=5.5))
duration = IntegerField('Duration(in min)')
password = PasswordField('Exam Password', [validators.Length(min=3, max=6)])
proctor_type = RadioField('Proctoring Type', choices=[('0','Automatic Monitoring'),('1','Live Monitoring')])
def validate_end_date(form, field):
if field.data < form.start_date.data:
raise ValidationError("End date must not be earlier than start date.")
def validate_end_time(form, field):
start_date_time = datetime.strptime(str(form.start_date.data) + " " + str(form.start_time.data),"%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %H:%M")
end_date_time = datetime.strptime(str(form.end_date.data) + " " + str(field.data),"%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %H:%M")
if start_date_time >= end_date_time:
raise ValidationError("End date time must not be earlier/equal than start date time")
def validate_start_date(form, field):
if datetime.strptime(str(form.start_date.data) + " " + str(form.start_time.data),"%Y-%m-%d %H:%M:%S") < datetime.now():
raise ValidationError("Start date and time must not be earlier than current")
@app.route('/create_test_lqa', methods = ['GET', 'POST'])
@user_role_professor
def create_test_lqa():
form = QAUploadForm()
if request.method == 'POST' and form.validate_on_submit():
test_id = generate_slug(2)
filename = secure_filename(form.doc.data.filename)
filestream = form.doc.data
filestream.seek(0)
ef = pd.read_csv(filestream)
fields = ['qid','q','marks']
df = pd.DataFrame(ef, columns = fields)
cur = mysql.connection.cursor()
ecc = examcreditscheck()
if ecc:
for row in df.index:
cur.execute('INSERT INTO longqa(test_id,qid,q,marks,uid) values(%s,%s,%s,%s,%s)', (test_id, df['qid'][row], df['q'][row], df['marks'][row], session['uid']))
cur.connection.commit()
start_date = form.start_date.data
end_date = form.end_date.data
start_time = form.start_time.data
end_time = form.end_time.data
start_date_time = str(start_date) + " " + str(start_time)
end_date_time = str(end_date) + " " + str(end_time)
duration = int(form.duration.data)*60
password = form.password.data
subject = form.subject.data
topic = form.topic.data
proctor_type = form.proctor_type.data
cur.execute('INSERT INTO teachers (email, test_id, test_type, start, end, duration, show_ans, password, subject, topic, neg_marks, calc, proctoring_type, uid) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',
(dict(session)['email'], test_id, "subjective", start_date_time, end_date_time, duration, 0, password, subject, topic, 0, 0, proctor_type, session['uid']))
mysql.connection.commit()
cur.execute('UPDATE users SET examcredits = examcredits-1 where email = %s and uid = %s', (session['email'],session['uid']))
mysql.connection.commit()
cur.close()
flash(f'Exam ID: {test_id}', 'success')
return redirect(url_for('professor_index'))
else:
flash("No exam credits points are found! Please pay it!")
return redirect(url_for('professor_index'))
return render_template('create_test_lqa.html' , form = form)
class UploadForm(FlaskForm):
subject = StringField('Subject')
topic = StringField('Topic')
doc = FileField('CSV Upload', validators=[FileRequired()])
start_date = DateField('Start Date')
start_time = TimeField('Start Time', default=datetime.utcnow()+timedelta(hours=5.5))
end_date = DateField('End Date')
end_time = TimeField('End Time', default=datetime.utcnow()+timedelta(hours=5.5))
calc = BooleanField('Enable Calculator')
neg_mark = DecimalField('Enable negative marking in % ', validators=[NumberRange(min=0, max=100)])
duration = IntegerField('Duration(in min)')
password = PasswordField('Exam Password', [validators.Length(min=3, max=6)])
proctor_type = RadioField('Proctoring Type', choices=[('0','Automatic Monitoring'),('1','Live Monitoring')])
def validate_end_date(form, field):
if field.data < form.start_date.data:
raise ValidationError("End date must not be earlier than start date.")
def validate_end_time(form, field):
start_date_time = datetime.strptime(str(form.start_date.data) + " " + str(form.start_time.data),"%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %H:%M")
end_date_time = datetime.strptime(str(form.end_date.data) + " " + str(field.data),"%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %H:%M")
if start_date_time >= end_date_time:
raise ValidationError("End date time must not be earlier/equal than start date time")
def validate_start_date(form, field):
if datetime.strptime(str(form.start_date.data) + " " + str(form.start_time.data),"%Y-%m-%d %H:%M:%S") < datetime.now():
raise ValidationError("Start date and time must not be earlier than current")
class TestForm(Form):
test_id = StringField('Exam ID')
password = PasswordField('Exam Password')
img_hidden_form = HiddenField(label=(''))
@app.route('/create-test', methods = ['GET', 'POST'])
@user_role_professor
def create_test():
form = UploadForm()
if request.method == 'POST' and form.validate_on_submit():
test_id = generate_slug(2)
filename = secure_filename(form.doc.data.filename)
filestream = form.doc.data
filestream.seek(0)
ef = pd.read_csv(filestream)
fields = ['qid','q','a','b','c','d','ans','marks']
df = pd.DataFrame(ef, columns = fields)
cur = mysql.connection.cursor()
ecc = examcreditscheck()
if ecc:
for row in df.index:
cur.execute('INSERT INTO questions(test_id,qid,q,a,b,c,d,ans,marks,uid) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)', (test_id, df['qid'][row], df['q'][row], df['a'][row], df['b'][row], df['c'][row], df['d'][row], df['ans'][row], df['marks'][row], session['uid']))
cur.connection.commit()
start_date = form.start_date.data
end_date = form.end_date.data
start_time = form.start_time.data
end_time = form.end_time.data
start_date_time = str(start_date) + " " + str(start_time)
end_date_time = str(end_date) + " " + str(end_time)
neg_mark = int(form.neg_mark.data)
calc = int(form.calc.data)
duration = int(form.duration.data)*60
password = form.password.data
subject = form.subject.data
topic = form.topic.data
proctor_type = form.proctor_type.data
cur.execute('INSERT INTO teachers (email, test_id, test_type, start, end, duration, show_ans, password, subject, topic, neg_marks, calc,proctoring_type, uid) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',
(dict(session)['email'], test_id, "objective", start_date_time, end_date_time, duration, 1, password, subject, topic, neg_mark, calc, proctor_type, session['uid']))
mysql.connection.commit()
cur.execute('UPDATE users SET examcredits = examcredits-1 where email = %s and uid = %s', (session['email'],session['uid']))
mysql.connection.commit()
cur.close()
flash(f'Exam ID: {test_id}', 'success')
return redirect(url_for('professor_index'))
else:
flash("No exam credits points are found! Please pay it!")
return redirect(url_for('professor_index'))
return render_template('create_test.html' , form = form)
class PracUploadForm(FlaskForm):
subject = StringField('Subject')
topic = StringField('Topic')
questionprac = StringField('Question')
marksprac = IntegerField('Marks')
start_date = DateField('Start Date')
start_time = TimeField('Start Time', default=datetime.utcnow()+timedelta(hours=5.5))
end_date = DateField('End Date')
end_time = TimeField('End Time', default=datetime.utcnow()+timedelta(hours=5.5))
duration = IntegerField('Duration(in min)')
compiler = SelectField(u'Compiler/Interpreter', choices=[('11', 'C'), ('27', 'C#'), ('1', 'C++'),('114', 'Go'),('10', 'Java'),('47', 'Kotlin'),('56', 'Node.js'),
('43', 'Objective-C'),('29', 'PHP'),('54', 'Perl-6'),('116', 'Python 3x'),('117', 'R'),('17', 'Ruby'),('93', 'Rust'),('52', 'SQLite-queries'),('40', 'SQLite-schema'),
('39', 'Scala'),('85', 'Swift'),('57', 'TypeScript')])
password = PasswordField('Exam Password', [validators.Length(min=3, max=10)])
proctor_type = RadioField('Proctoring Type', choices=[('0','Automatic Monitoring'),('1','Live Monitoring')])
def validate_end_date(form, field):
if field.data < form.start_date.data:
raise ValidationError("End date must not be earlier than start date.")
def validate_end_time(form, field):
start_date_time = datetime.strptime(str(form.start_date.data) + " " + str(form.start_time.data),"%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %H:%M")
end_date_time = datetime.strptime(str(form.end_date.data) + " " + str(field.data),"%Y-%m-%d %H:%M:%S").strftime("%Y-%m-%d %H:%M")
if start_date_time >= end_date_time:
raise ValidationError("End date time must not be earlier/equal than start date time")
def validate_start_date(form, field):
if datetime.strptime(str(form.start_date.data) + " " + str(form.start_time.data),"%Y-%m-%d %H:%M:%S") < datetime.now():
raise ValidationError("Start date and time must not be earlier than current")
@app.route('/create_test_pqa', methods = ['GET', 'POST'])
@user_role_professor
def create_test_pqa():
form = PracUploadForm()
if request.method == 'POST' and form.validate_on_submit():
test_id = generate_slug(2)
ecc = examcreditscheck()
print(ecc)
if ecc:
test_id = generate_slug(2)
compiler = form.compiler.data
questionprac = form.questionprac.data
marksprac = int(form.marksprac.data)
cur = mysql.connection.cursor()
cur.execute('INSERT INTO practicalqa(test_id,qid,q,compiler,marks,uid) values(%s,%s,%s,%s,%s,%s)', (test_id, 1, questionprac, compiler, marksprac, session['uid']))
mysql.connection.commit()
start_date = form.start_date.data
end_date = form.end_date.data
start_time = form.start_time.data
end_time = form.end_time.data
start_date_time = str(start_date) + " " + str(start_time)
end_date_time = str(end_date) + " " + str(end_time)
duration = int(form.duration.data)*60
password = form.password.data
subject = form.subject.data
topic = form.topic.data
proctor_type = form.proctor_type.data
cur.execute('INSERT INTO teachers (email, test_id, test_type, start, end, duration, show_ans, password, subject, topic, neg_marks, calc, proctoring_type, uid) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)',
(dict(session)['email'], test_id, "practical", start_date_time, end_date_time, duration, 0, password, subject, topic, 0, 0, proctor_type, session['uid']))
mysql.connection.commit()
cur.execute('UPDATE users SET examcredits = examcredits-1 where email = %s and uid = %s', (session['email'],session['uid']))
mysql.connection.commit()
cur.close()
flash(f'Exam ID: {test_id}', 'success')
return redirect(url_for('professor_index'))
else:
flash("No exam credits points are found! Please pay it!")
return redirect(url_for('professor_index'))
return render_template('create_prac_qa.html' , form = form)
@app.route('/deltidlist', methods=['GET'])
@user_role_professor
def deltidlist():
cur = mysql.connection.cursor()
results = cur.execute('SELECT * from teachers where email = %s and uid = %s', (session['email'], session['uid']))
if results > 0:
cresults = cur.fetchall()
now = datetime.now()
now = now.strftime("%Y-%m-%d %H:%M:%S")
now = datetime.strptime(now,"%Y-%m-%d %H:%M:%S")
testids = []
for a in cresults:
if datetime.strptime(str(a['start']),"%Y-%m-%d %H:%M:%S") > now:
testids.append(a['test_id'])
cur.close()
return render_template("deltidlist.html", cresults = testids)
else:
return render_template("deltidlist.html", cresults = None)
@app.route('/deldispques', methods=['GET','POST'])
@user_role_professor
def deldispques():
if request.method == 'POST':
tidoption = request.form['choosetid']
et = examtypecheck(tidoption)
if et['test_type'] == "objective":
cur = mysql.connection.cursor()
cur.execute('SELECT * from questions where test_id = %s and uid = %s', (tidoption,session['uid']))
callresults = cur.fetchall()
cur.close()
return render_template("deldispques.html", callresults = callresults, tid = tidoption)
elif et['test_type'] == "subjective":
cur = mysql.connection.cursor()
cur.execute('SELECT * from longqa where test_id = %s and uid = %s', (tidoption,session['uid']))
callresults = cur.fetchall()
cur.close()
return render_template("deldispquesLQA.html", callresults = callresults, tid = tidoption)
elif et['test_type'] == "practical":
cur = mysql.connection.cursor()
cur.execute('SELECT * from practicalqa where test_id = %s and uid = %s', (tidoption,session['uid']))
callresults = cur.fetchall()
cur.close()
return render_template("deldispquesPQA.html", callresults = callresults, tid = tidoption)
else:
flash("Some Error Occured!")
return redirect(url_for('/deltidlist'))
@app.route('/delete_questions/<testid>', methods=['GET', 'POST'])
@user_role_professor
def delete_questions(testid):
et = examtypecheck(testid)
if et['test_type'] == "objective":
cur = mysql.connection.cursor()
msg = ''
if request.method == 'POST':
testqdel = request.json['qids']
if testqdel:
if ',' in testqdel:
testqdel = testqdel.split(',')
for getid in testqdel:
cur.execute('DELETE FROM questions WHERE test_id = %s and qid =%s and uid = %s', (testid,getid,session['uid']))
mysql.connection.commit()
resp = jsonify('<span style=\'color:green;\'>Questions deleted successfully</span>')
resp.status_code = 200
return resp
else:
cur.execute('DELETE FROM questions WHERE test_id = %s and qid =%s and uid = %s', (testid,testqdel,session['uid']))
mysql.connection.commit()
resp = jsonify('<span style=\'color:green;\'>Questions deleted successfully</span>')
resp.status_code = 200
return resp
elif et['test_type'] == "subjective":
cur = mysql.connection.cursor()
msg = ''
if request.method == 'POST':
testqdel = request.json['qids']
if testqdel:
if ',' in testqdel:
testqdel = testqdel.split(',')
for getid in testqdel:
cur.execute('DELETE FROM longqa WHERE test_id = %s and qid =%s and uid = %s', (testid,getid,session['uid']))
mysql.connection.commit()
resp = jsonify('<span style=\'color:green;\'>Questions deleted successfully</span>')
resp.status_code = 200
return resp
else:
cur.execute('DELETE FROM longqa WHERE test_id = %s and qid =%s and uid = %s', (testid,testqdel,session['uid']))
mysql.connection.commit()
resp = jsonify('<span style=\'color:green;\'>Questions deleted successfully</span>')
resp.status_code = 200
return resp
elif et['test_type'] == "practical":
cur = mysql.connection.cursor()
msg = ''
if request.method == 'POST':
testqdel = request.json['qids']
if testqdel:
if ',' in testqdel:
testqdel = testqdel.split(',')
for getid in testqdel:
cur.execute('DELETE FROM practicalqa WHERE test_id = %s and qid =%s and uid = %s', (testid,getid,session['uid']))
mysql.connection.commit()
resp = jsonify('<span style=\'color:green;\'>Questions deleted successfully</span>')
resp.status_code = 200
return resp
else:
cur.execute('DELETE FROM questions WHERE test_id = %s and qid =%s and uid = %s', (testid,testqdel,session['uid']))
mysql.connection.commit()
resp = jsonify('<span style=\'color:green;\'>Questions deleted successfully</span>')
resp.status_code = 200
return resp
else:
flash("Some Error Occured!")
return redirect(url_for('/deltidlist'))
@app.route('/<testid>/<qid>')
@user_role_professor
def del_qid(testid, qid):
cur = mysql.connection.cursor()
results = cur.execute('DELETE FROM questions where test_id = %s and qid = %s and uid = %s', (testid,qid,session['uid']))
mysql.connection.commit()
if results>0:
msg="Deleted successfully"
flash('Deleted successfully.', 'success')
cur.close()
return render_template("deldispques.html", success=msg)
else:
return redirect(url_for('/deldispques'))
@app.route('/updatetidlist', methods=['GET'])
@user_role_professor
def updatetidlist():
cur = mysql.connection.cursor()
results = cur.execute('SELECT * from teachers where email = %s and uid = %s', (session['email'],session['uid']))
if results > 0:
cresults = cur.fetchall()
now = datetime.now()
now = now.strftime("%Y-%m-%d %H:%M:%S")
now = datetime.strptime(now,"%Y-%m-%d %H:%M:%S")
testids = []
for a in cresults:
if datetime.strptime(str(a['start']),"%Y-%m-%d %H:%M:%S") > now:
testids.append(a['test_id'])
cur.close()
return render_template("updatetidlist.html", cresults = testids)
else:
return render_template("updatetidlist.html", cresults = None)
@app.route('/updatedispques', methods=['GET','POST'])
@user_role_professor
def updatedispques():
if request.method == 'POST':
tidoption = request.form['choosetid']
et = examtypecheck(tidoption)
if et['test_type'] == "objective":
cur = mysql.connection.cursor()
cur.execute('SELECT * from questions where test_id = %s and uid = %s', (tidoption,session['uid']))
callresults = cur.fetchall()
cur.close()
return render_template("updatedispques.html", callresults = callresults)
elif et['test_type'] == "subjective":
cur = mysql.connection.cursor()
cur.execute('SELECT * from longqa where test_id = %s and uid = %s', (tidoption,session['uid']))
callresults = cur.fetchall()
cur.close()
return render_template("updatedispquesLQA.html", callresults = callresults)
elif et['test_type'] == "practical":
cur = mysql.connection.cursor()
cur.execute('SELECT * from practicalqa where test_id = %s and uid = %s', (tidoption,session['uid']))
callresults = cur.fetchall()
cur.close()
return render_template("updatedispquesPQA.html", callresults = callresults)
else:
flash('Error Occured!')
return redirect(url_for('updatetidlist'))
@app.route('/update/<testid>/<qid>', methods=['GET','POST'])
@user_role_professor
def update_quiz(testid, qid):
if request.method == 'GET':
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM questions where test_id = %s and qid =%s and uid = %s', (testid,qid,session['uid']))
uresults = cur.fetchall()
mysql.connection.commit()
return render_template("updateQuestions.html", uresults=uresults)
if request.method == 'POST':
ques = request.form['ques']
ao = request.form['ao']
bo = request.form['bo']
co = request.form['co']
do = request.form['do']
anso = request.form['anso']
markso = request.form['mko']
cur = mysql.connection.cursor()
cur.execute('UPDATE questions SET q = %s, a = %s, b = %s, c = %s, d = %s, ans = %s, marks = %s where test_id = %s and qid = %s and uid = %s', (ques,ao,bo,co,do,anso,markso,testid,qid,session['uid']))
cur.connection.commit()
flash('Updated successfully.', 'success')
cur.close()
return redirect(url_for('updatetidlist'))
else:
flash('ERROR OCCURED.', 'error')
return redirect(url_for('updatetidlist'))
@app.route('/updateLQA/<testid>/<qid>', methods=['GET','POST'])
@user_role_professor
def update_lqa(testid, qid):
if request.method == 'GET':
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM longqa where test_id = %s and qid =%s and uid = %s', (testid,qid,session['uid']))
uresults = cur.fetchall()
mysql.connection.commit()
return render_template("updateQuestionsLQA.html", uresults=uresults)
if request.method == 'POST':
ques = request.form['ques']
markso = request.form['mko']
cur = mysql.connection.cursor()
cur.execute('UPDATE longqa SET q = %s, marks = %s where test_id = %s and qid = %s and uid = %s', (ques,markso,testid,qid,session['uid']))
cur.connection.commit()
flash('Updated successfully.', 'success')
cur.close()
return redirect(url_for('updatetidlist'))
else:
flash('ERROR OCCURED.', 'error')
return redirect(url_for('updatetidlist'))
@app.route('/updatePQA/<testid>/<qid>', methods=['GET','POST'])
@user_role_professor
def update_PQA(testid, qid):
if request.method == 'GET':
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM practicalqa where test_id = %s and qid =%s and uid = %s', (testid,qid,session['uid']))
uresults = cur.fetchall()
mysql.connection.commit()
return render_template("updateQuestionsPQA.html", uresults=uresults)
if request.method == 'POST':
ques = request.form['ques']
markso = request.form['mko']
cur = mysql.connection.cursor()
cur.execute('UPDATE practicalqa SET q = %s, marks = %s where test_id = %s and qid = %s and uid = %s', (ques,markso,testid,qid,session['uid']))
cur.connection.commit()
flash('Updated successfully.', 'success')
cur.close()
return redirect(url_for('updatetidlist'))
else:
flash('ERROR OCCURED.', 'error')
return redirect(url_for('updatetidlist'))
@app.route('/viewquestions', methods=['GET'])
@user_role_professor
def viewquestions():
cur = mysql.connection.cursor()
results = cur.execute('SELECT test_id from teachers where email = %s and uid = %s', (session['email'],session['uid']))
if results > 0:
cresults = cur.fetchall()
cur.close()
return render_template("viewquestions.html", cresults = cresults)
else:
return render_template("viewquestions.html", cresults = None)
def examtypecheck(tidoption):
cur = mysql.connection.cursor()
cur.execute('SELECT test_type from teachers where test_id = %s and email = %s and uid = %s', (tidoption,session['email'],session['uid']))
callresults = cur.fetchone()