-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2528 lines (2097 loc) · 95.3 KB
/
app.py
File metadata and controls
2528 lines (2097 loc) · 95.3 KB
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
"""
FastAPI application for AI-based Exam System
Contains all API routes and web endpoints
"""
from fastapi import FastAPI, Request, Form, HTTPException, Depends, status
from contextlib import asynccontextmanager
from fastapi.responses import HTMLResponse, JSONResponse, RedirectResponse, Response
from fastapi.templating import Jinja2Templates
from fastapi.security import HTTPBasic
from typing import Dict, Optional
import json
import uuid
import os
import sqlite3
import threading
from datetime import datetime, timedelta
from fastapi import File, UploadFile
from fastapi.staticfiles import StaticFiles
import shutil
from pathlib import Path
from utils import (
ExamSystem, ExamSession, AdminSession,
create_admin_session, verify_admin_session,
convert_utc_to_bangladesh, order_questions_by_type,
group_questions_by_section_for_navigation, validate_form_data,
generate_safe_filename
)
from db import db
from evaluation_queue import init_evaluation_queue, get_evaluation_queue
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Get environment variables
API_KEY = os.getenv("API_KEY")
API_KEY_BACKUP = os.getenv("API_KEY_BACKUP") # Backup API key for failover
ADMIN_SECRET_KEY = os.getenv("ADMIN_SECRET_KEY")
ADMIN_SESSION_TIMEOUT = 30 # Session timeout in minutes
UPLOAD_DIR = Path("uploads/images")
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Lifecycle events (startup and shutdown)"""
print("🚀 Starting application...")
# Start background evaluation queue
# Note: evaluation_queue is initialized later in this file but will be available at runtime
if 'evaluation_queue' in globals():
evaluation_queue.start()
print("✅ Background evaluation queue started")
# Recover active exam sessions from database
if 'recover_exam_sessions' in globals():
recover_exam_sessions()
# Recover pending evaluations from database
if 'recover_pending_evaluations' in globals():
recover_pending_evaluations()
yield
print("🛑 Shutting down application...")
if 'evaluation_queue' in globals():
evaluation_queue.stop()
print("✅ Background evaluation queue stopped")
app = FastAPI(title="Admin-Controlled Exam System", lifespan=lifespan)
templates = Jinja2Templates(directory="templates", auto_reload=True)
security = HTTPBasic()
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
# Initialize exam system with primary and backup API keys
exam_system = ExamSystem(API_KEY, API_KEY_BACKUP)
# Initialize evaluation queue for background processing
# Rate limit: 10 requests per minute to prevent API quota exhaustion
evaluation_queue = init_evaluation_queue(
exam_system=exam_system,
db=db,
requests_per_minute=1
)
# In-memory session storage (exam_sessions now backed by database for persistence)
# Thread-safe session management using locks
_exam_sessions_lock = threading.Lock()
_admin_sessions_lock = threading.Lock()
exam_sessions = {} # Cache for quick access, but database is source of truth
admin_sessions = {}
def get_exam_session(session_id: str) -> Optional[ExamSession]:
"""Thread-safe getter for exam sessions"""
with _exam_sessions_lock:
return exam_sessions.get(session_id)
def set_exam_session(session_id: str, session: ExamSession):
"""Thread-safe setter for exam sessions"""
with _exam_sessions_lock:
exam_sessions[session_id] = session
def delete_exam_session(session_id: str):
"""Thread-safe deletion for exam sessions"""
with _exam_sessions_lock:
if session_id in exam_sessions:
del exam_sessions[session_id]
def get_admin_session(session_id: str) -> Optional[AdminSession]:
"""Thread-safe getter for admin sessions"""
with _admin_sessions_lock:
return admin_sessions.get(session_id)
def set_admin_session(session_id: str, session: AdminSession):
"""Thread-safe setter for admin sessions"""
with _admin_sessions_lock:
admin_sessions[session_id] = session
def delete_admin_session(session_id: str):
"""Thread-safe deletion for admin sessions"""
with _admin_sessions_lock:
if session_id in admin_sessions:
del admin_sessions[session_id]
def recover_exam_sessions():
"""
Recover active exam sessions from database after server restart.
This ensures candidates can continue their exams even if the server restarts.
"""
try:
active_sessions = db.get_all_active_exam_sessions()
if not active_sessions:
print("✅ No active exam sessions to recover")
return
print(f"🔄 Recovering {len(active_sessions)} active exam sessions from database...")
recovered_count = 0
for session_data in active_sessions:
try:
# Recreate the in-memory ExamSession object using thread-safe setter
set_exam_session(session_data['session_id'], ExamSession(
session_id=session_data['session_id'],
candidate_name=session_data['candidate_name'],
candidate_id=session_data['candidate_id'],
exam_id=session_data['exam_id'],
started_at=datetime.fromisoformat(session_data['started_at']) if isinstance(session_data['started_at'], str) else session_data['started_at'],
time_limit=session_data['time_limit']
))
recovered_count += 1
print(f" ✅ Recovered session for {session_data['candidate_name']}")
except Exception as e:
print(f" ❌ Failed to recover session {session_data['session_id']}: {e}")
print(f"✅ Recovered {recovered_count}/{len(active_sessions)} exam sessions")
# Also clean up expired sessions
expired_count = db.cleanup_expired_exam_sessions(extra_minutes=60)
if expired_count > 0:
print(f"🧹 Cleaned up {expired_count} expired exam sessions")
except Exception as e:
print(f"❌ Error recovering exam sessions: {e}")
def recover_pending_evaluations():
"""
Recover pending evaluations from database after server restart.
This ensures NO DATA IS LOST even if the server crashes or restarts.
"""
try:
pending_results = db.get_pending_results_for_recovery()
if not pending_results:
print("✅ No pending evaluations to recover")
return
print(f"🔄 Recovering {len(pending_results)} pending evaluations from database...")
recovered_count = 0
for result in pending_results:
try:
success = evaluation_queue.add_task(
result_id=result['result_id'],
session_id=result['session_id'],
exam_id=result['exam_id'],
candidate_name=result['candidate_name'],
candidate_id=result['candidate_id'],
answers=result['answers'],
questions=result['questions'],
negative_marking_config=result['negative_marking_config'],
show_feedback=result['show_feedback'],
multi_select_scoring_mode=result.get('multi_select_scoring_mode', 'partial'),
priority=0 # High priority for recovered tasks
)
if success:
recovered_count += 1
print(f" ✅ Recovered: {result['candidate_name']} ({result['result_id'][:8]}...)")
else:
print(f" ⚠️ Failed to recover: {result['candidate_name']}")
except Exception as e:
print(f" ❌ Error recovering {result['candidate_name']}: {str(e)}")
print(f"🎉 Recovery complete: {recovered_count}/{len(pending_results)} evaluations re-queued")
except Exception as e:
print(f"❌ Error during evaluation recovery: {str(e)}")
# Startup and shutdown events are now handled by lifespan context manager
# Helper Functions for Session Management
def safe_error_message(e: Exception, context: str = "operation") -> str:
"""
Generate a safe error message that doesn't expose internal details.
Logs the full error for debugging but returns a generic message to users.
"""
import traceback
# Log the full error for debugging
print(f"❌ Error during {context}: {str(e)}")
traceback.print_exc()
# Return generic message to user
return f"An error occurred during {context}. Please try again or contact the administrator."
def get_admin_session_from_request(request: Request) -> Optional[str]:
"""Get admin session ID from request cookies"""
return request.cookies.get("admin_session")
async def verify_admin_access(request: Request):
"""Dependency to verify admin access"""
session_id = get_admin_session_from_request(request)
# Use thread-safe verification with lock
if not session_id or not verify_admin_session(session_id, admin_sessions, ADMIN_SESSION_TIMEOUT, lock=_admin_sessions_lock):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Admin access required"
)
return session_id
# Candidate Routes
@app.get("/", response_class=HTMLResponse)
async def home(request: Request):
"""Home page for candidates"""
return templates.TemplateResponse("candidate_home.html", {
"request": request
})
@app.get("/exam/{exam_link}", response_class=HTMLResponse)
async def exam_page(request: Request, exam_link: str):
"""Exam page for candidates"""
exam = db.get_exam_by_link(exam_link)
if not exam:
return templates.TemplateResponse("candidate_home.html", {
"request": request,
"error": "This exam is either invalid, has been deactivated, or is no longer available. Please contact the administrator for assistance."
})
return templates.TemplateResponse("exam_start.html", {
"request": request,
"exam": exam,
"exam_link": exam_link
})
@app.get("/exam/{exam_link}/results", response_class=HTMLResponse)
async def exam_results_lookup_page(request: Request, exam_link: str):
"""Page for candidates to look up their results using candidate ID"""
exam = db.get_exam_by_link(exam_link)
if not exam:
return templates.TemplateResponse("candidate_home.html", {
"request": request,
"error": "Invalid exam link. Please check the link and try again."
})
return templates.TemplateResponse("result_lookup.html", {
"request": request,
"exam": exam,
"exam_link": exam_link
})
@app.post("/exam/{exam_link}/results", response_class=HTMLResponse)
async def lookup_exam_results(request: Request, exam_link: str):
"""Look up results using candidate ID"""
exam = db.get_exam_by_link(exam_link)
if not exam:
return templates.TemplateResponse("candidate_home.html", {
"request": request,
"error": "Invalid exam link."
})
form_data = await request.form()
candidate_id = form_data.get("candidate_id", "").strip()
if not candidate_id:
return templates.TemplateResponse("result_lookup.html", {
"request": request,
"exam": exam,
"exam_link": exam_link,
"error": "Please enter your Candidate ID."
})
# Look up the result
result = db.lookup_candidate_result(exam_link, candidate_id)
if not result:
return templates.TemplateResponse("result_lookup.html", {
"request": request,
"exam": exam,
"exam_link": exam_link,
"error": "No results found for this Candidate ID. Please check your ID and try again."
})
# Redirect to the results page
return RedirectResponse(url=f"/results/{result['result_id']}", status_code=303)
@app.post("/exam/{exam_link}/start", response_class=HTMLResponse)
async def start_exam(request: Request, exam_link: str):
"""Start exam for candidate with proper question ordering and live session tracking"""
exam = db.get_exam_by_link(exam_link)
if not exam:
return templates.TemplateResponse("candidate_home.html", {
"request": request,
"error": "Invalid exam link. Please check the link and try again."
})
# Get form data
form_data = await request.form()
candidate_name = form_data.get("candidate_name", "").strip()
candidate_id = form_data.get("candidate_id", "").strip()
# Validate form data
if not candidate_name or not candidate_id:
return templates.TemplateResponse("exam_start.html", {
"request": request,
"exam": exam,
"exam_link": exam_link,
"error": "Please fill in both your name and candidate ID."
})
# Check if candidate has already submitted this exam
if db.has_candidate_submitted_exam(exam['id'], candidate_id):
return templates.TemplateResponse("exam_already_submitted.html", {
"request": request,
"exam": exam,
"exam_link": exam_link,
"candidate_id": candidate_id,
"message": "You have already submitted this exam. Each candidate can only take the exam once."
})
# Check if candidate has an active session (resume functionality)
existing_session_id = db.has_candidate_active_session(exam['id'], candidate_id)
if existing_session_id:
# Candidate has an active session, recover it
db_session = db.get_exam_session(existing_session_id)
if db_session:
session_id = existing_session_id
set_exam_session(session_id, ExamSession(
session_id=db_session['session_id'],
candidate_name=db_session['candidate_name'],
candidate_id=db_session['candidate_id'],
exam_id=db_session['exam_id'],
started_at=datetime.fromisoformat(db_session['started_at']) if isinstance(db_session['started_at'], str) else db_session['started_at'],
time_limit=db_session['time_limit']
))
print(f"🔄 Resuming existing session for {candidate_name} ({candidate_id})")
# Get questions and continue with existing session
questions = db.get_exam_questions(exam['id'])
questions = order_questions_by_type(questions)
sections = group_questions_by_section_for_navigation(questions)
# Get previously saved answers
saved_answers = db_session.get('answers_data', {})
if isinstance(saved_answers, str):
import json as json_module
saved_answers = json_module.loads(saved_answers) if saved_answers else {}
return templates.TemplateResponse("exam_page.html", {
"request": request,
"exam": exam,
"questions": questions,
"sections": sections,
"session_id": session_id,
"candidate_name": db_session['candidate_name'],
"time_limit": db_session['time_limit'],
"saved_answers": saved_answers,
"resumed": True
})
# Create new exam session using thread-safe setter
session_id = str(uuid.uuid4())
set_exam_session(session_id, ExamSession(
session_id=session_id,
candidate_name=candidate_name,
candidate_id=candidate_id,
exam_id=exam['id'],
started_at=datetime.now(),
time_limit=exam['time_limit']
))
# Create persistent exam session in database (survives server restart)
db.create_exam_session(
session_id=session_id,
exam_id=exam['id'],
candidate_name=candidate_name,
candidate_id=candidate_id,
time_limit=exam['time_limit']
)
# Create live session in database (for admin monitoring)
db.create_live_session(session_id, exam['id'], candidate_name, candidate_id)
# Get questions for the exam
questions = db.get_exam_questions(exam['id'])
# Order questions by type: MCQ → Short → Essay
ordered_questions = order_questions_by_type(questions)
# Get sections structure for navigation
sections_by_type = group_questions_by_section_for_navigation(ordered_questions)
print(f"📝 Exam started with {len(ordered_questions)} questions ordered by type")
print(f"📊 Sections for navigation: {list(sections_by_type.keys())}")
print(f"🔴 Live session created for {candidate_name} ({candidate_id})")
return templates.TemplateResponse("exam_page.html", {
"request": request,
"session_id": session_id,
"candidate_name": candidate_name,
"candidate_id": candidate_id,
"exam": exam,
"questions": ordered_questions,
"sections": sections_by_type
})
@app.post("/exam/submit", response_class=HTMLResponse)
async def submit_exam(request: Request):
"""
Submit exam answers with background queue-based evaluation.
This new implementation:
1. Saves answers immediately to database
2. Queues evaluation for background processing
3. Redirects candidate to status page (they can leave)
4. Evaluation happens in background with rate limiting and retries
"""
form_data = await request.form()
session_id = form_data.get("session_id")
client_time_taken = form_data.get("time_taken", "00:00") # Client-reported time (not trusted)
print(f"📄 Processing exam submission for session: {session_id}")
if not session_id:
print(f"❌ No session ID provided")
return templates.TemplateResponse("exam_error.html", {
"request": request,
"error_title": "Session Not Found",
"error_message": "No exam session was found. This may happen if you've already submitted your exam or your session has expired.",
"error_type": "session_not_found"
}, status_code=404)
# Try to get session from memory first (thread-safe), then from database
session = get_exam_session(session_id)
if not session:
# Session not in memory, try to recover from database
print(f"🔄 Session not in memory, checking database: {session_id}")
db_session = db.get_exam_session(session_id)
if db_session and not db_session.get('is_submitted'):
# Recover session from database using thread-safe setter
session = ExamSession(
session_id=db_session['session_id'],
candidate_name=db_session['candidate_name'],
candidate_id=db_session['candidate_id'],
exam_id=db_session['exam_id'],
started_at=datetime.fromisoformat(db_session['started_at']) if isinstance(db_session['started_at'], str) else db_session['started_at'],
time_limit=db_session['time_limit']
)
set_exam_session(session_id, session)
print(f"✅ Session recovered from database for {session.candidate_name}")
else:
# Check if it was already submitted
is_already_submitted = db_session and db_session.get('is_submitted')
print(f"❌ Invalid session ID: {session_id} (already_submitted: {is_already_submitted})")
if is_already_submitted:
# Already submitted - show success page instead of error
return templates.TemplateResponse("exam_already_submitted.html", {
"request": request,
"candidate_name": db_session.get('candidate_name', 'Candidate'),
"candidate_id": db_session.get('candidate_id', 'N/A'),
"message": "Your exam has already been submitted successfully. You cannot submit again."
})
else:
return templates.TemplateResponse("exam_error.html", {
"request": request,
"error_title": "Session Not Found",
"error_message": "Your exam session was not found. This may happen if the session has expired or there was a technical issue. Please contact the administrator if you believe this is an error.",
"error_type": "session_not_found"
}, status_code=404)
exam = db.get_exam_by_id(session.exam_id)
questions = db.get_exam_questions(session.exam_id)
# SERVER-SIDE TIME ENFORCEMENT
# Check if the exam time has expired (with 1 minute grace period for network latency)
time_elapsed = datetime.now() - session.started_at
time_limit_seconds = session.time_limit * 60
grace_period_seconds = 60 # 1 minute grace period
max_allowed_seconds = time_limit_seconds + grace_period_seconds
if time_elapsed.total_seconds() > max_allowed_seconds:
print(f"⏰ Exam time exceeded for {session.candidate_name}: elapsed {time_elapsed.total_seconds():.0f}s, limit {time_limit_seconds}s")
# Still accept the submission but log the overtime
overtime_minutes = (time_elapsed.total_seconds() - time_limit_seconds) / 60
print(f"⚠️ Candidate {session.candidate_name} submitted {overtime_minutes:.1f} minutes after time limit")
# Calculate actual time taken (capped at time limit for fairness)
actual_time_seconds = min(time_elapsed.total_seconds(), time_limit_seconds)
# Format server-side time_taken as MM:SS (used instead of client-reported time)
time_taken_minutes = int(actual_time_seconds // 60)
time_taken_seconds = int(actual_time_seconds % 60)
time_taken = f"{time_taken_minutes:02d}:{time_taken_seconds:02d}"
print(f"⏱️ Server-side time taken: {time_taken} (client reported: {client_time_taken})")
# IMMEDIATELY end live session when submission starts
print(f"🔴 Ending live session for {session.candidate_name}")
db.end_live_session(session_id)
# Extract candidate answers (handling both single-select and multi-select MCQs)
candidate_answers = {}
processed_keys = set()
for key in form_data.keys():
if key.startswith("question_") and key not in processed_keys:
processed_keys.add(key)
question_id = key.replace("question_", "")
# Get all values for this key (handles checkbox multi-select)
values = form_data.getlist(key)
if len(values) == 1:
# Single value (radio button or textarea)
candidate_answers[question_id] = values[0]
elif len(values) > 1:
# Multiple values (checkboxes for multi-select MCQ)
# Store as comma-separated string for compatibility
candidate_answers[question_id] = ','.join(values)
print(f"📊 Received {len(candidate_answers)} answers from {session.candidate_name}")
# Check if feedback should be shown
show_feedback = exam.get('show_feedback', True)
try:
# Step 1: Save submission immediately (answers are safe!)
result_id = db.save_exam_submission_for_queue(
session_id=session_id,
exam_id=session.exam_id,
candidate_name=session.candidate_name,
candidate_id=session.candidate_id,
answers=candidate_answers,
time_taken=time_taken,
questions=questions
)
if not result_id:
raise Exception("Failed to save exam submission")
print(f"✅ Answers saved immediately for {session.candidate_name} (Result ID: {result_id[:8]}...)")
# Step 2: Queue for background evaluation
negative_marking_config = exam.get('negative_marking_config', {})
multi_select_scoring_mode = exam.get('multi_select_scoring_mode', 'partial')
queue_success = evaluation_queue.add_task(
result_id=result_id,
session_id=session_id,
exam_id=session.exam_id,
candidate_name=session.candidate_name,
candidate_id=session.candidate_id,
answers=candidate_answers,
questions=questions,
negative_marking_config=negative_marking_config,
show_feedback=show_feedback,
multi_select_scoring_mode=multi_select_scoring_mode
)
if queue_success:
print(f"📋 Evaluation queued for {session.candidate_name}")
else:
print(f"⚠️ Queue failed, but answers are saved for {session.candidate_name}")
# Clean up in-memory session (thread-safe)
delete_exam_session(session_id)
# Mark database session as submitted and clean up
db.mark_exam_session_submitted(session_id)
# Step 3: Redirect to status page
# Candidate can now close the browser - their answers are safe!
return templates.TemplateResponse("evaluation_status.html", {
"request": request,
"result_id": result_id,
"candidate_name": session.candidate_name,
"candidate_id": session.candidate_id,
"exam_title": exam['title'],
"time_taken": time_taken,
"show_feedback": show_feedback,
"status": "pending",
"message": "Your exam has been submitted successfully! Your answers are being evaluated."
})
except Exception as e:
print(f"❌ Error during exam submission: {str(e)}")
# Ensure live session is ended
db.end_live_session(session_id)
# Clean up in-memory session (thread-safe)
delete_exam_session(session_id)
# Mark database session as submitted (even on error, prevent resubmission)
db.mark_exam_session_submitted(session_id)
# Show error page but reassure candidate
return templates.TemplateResponse("candidate_submission_complete.html", {
"request": request,
"candidate_name": session.candidate_name,
"candidate_id": session.candidate_id,
"exam_title": exam['title'],
"time_taken": time_taken,
"error": "There was an issue processing your submission. Please contact the administrator."
})
# Admin Routes
@app.get("/admin/login", response_class=HTMLResponse)
async def admin_login_page(request: Request):
"""Admin login page"""
return templates.TemplateResponse("admin_login.html", {"request": request})
@app.post("/admin/login")
async def admin_login(request: Request, secret_key: str = Form(...)):
"""Process admin login"""
if secret_key == ADMIN_SECRET_KEY:
session_id = create_admin_session(ADMIN_SESSION_TIMEOUT)
# Use thread-safe setter for admin session
set_admin_session(session_id, AdminSession(
session_id=session_id,
created_at=datetime.now(),
expires_at=datetime.now() + timedelta(minutes=ADMIN_SESSION_TIMEOUT)
))
response = RedirectResponse(url="/admin", status_code=303)
response.set_cookie(
key="admin_session",
value=session_id,
max_age=ADMIN_SESSION_TIMEOUT * 60,
httponly=True,
secure=False,
samesite="lax"
)
return response
else:
return templates.TemplateResponse("admin_login.html", {
"request": request,
"error": "Invalid secret key. Please try again."
})
@app.get("/admin/logout")
async def admin_logout(request: Request):
"""Logout admin user"""
session_id = get_admin_session_from_request(request)
if session_id:
# Use thread-safe deletion for admin session
delete_admin_session(session_id)
response = RedirectResponse(url="/", status_code=303)
response.delete_cookie("admin_session")
return response
@app.get("/admin", response_class=HTMLResponse)
async def admin_dashboard(request: Request, session_id: str = Depends(verify_admin_access)):
"""Admin dashboard"""
try:
exams = db.get_all_exams()
recent_results = db.get_recent_exam_results(20)
# Clean up stale sessions
db.cleanup_stale_sessions(30)
return templates.TemplateResponse("admin_dashboard.html", {
"request": request,
"exams": exams,
"recent_results": recent_results
})
except Exception as e:
# Log the full error for debugging but don't expose to user
print(f"❌ Error in admin dashboard: {str(e)}")
import traceback
traceback.print_exc()
return HTMLResponse("""
<html><body>
<h1>Admin Dashboard Error</h1>
<p>An unexpected error occurred while loading the dashboard. Please try again later.</p>
<p>If this problem persists, please contact the system administrator.</p>
<p><a href="/admin/login">Back to Login</a></p>
</body></html>
""", status_code=500)
@app.get("/admin/create-exam", response_class=HTMLResponse)
async def create_exam_page(request: Request, session_id: str = Depends(verify_admin_access)):
"""Create new exam page"""
return templates.TemplateResponse("create_exam.html", {
"request": request
})
@app.post("/admin/create-exam", response_class=HTMLResponse)
async def create_exam(request: Request, session_id: str = Depends(verify_admin_access)):
"""Create exam and generate questions with sections support"""
form_data = await request.form()
try:
# Extract form fields
department = form_data.get("department", "").strip()
position = form_data.get("position", "").strip()
title = form_data.get("title", "").strip()
description = form_data.get("description", "").strip()
time_limit = int(form_data.get("time_limit", "120"))
instructions = form_data.get("instructions", "").strip()
generation_method = form_data.get("generation_method", "ai").strip()
exam_language = form_data.get("exam_language", "english").strip()
show_feedback = form_data.get("show_feedback") == "on"
# Extract AI generation instructions
difficulty_level = form_data.get("difficulty_level", "medium").strip()
ai_custom_instructions = form_data.get("ai_custom_instructions", "").strip()
# Parse sections structure and negative marking config
sections_structure = json.loads(form_data.get("sections_structure", "{}"))
negative_marking_config = json.loads(form_data.get("negative_marking_config", "{}"))
# Multi-select scoring mode: 'partial' or 'strict'
multi_select_scoring_mode = form_data.get("multi_select_scoring_mode", "partial").strip()
# MCQ options count (2-6, default 4)
mcq_options_count = int(form_data.get("mcq_options_count", "4"))
mcq_options_count = max(2, min(6, mcq_options_count)) # Clamp to 2-6
# Add custom syllabus to sections
for section_name in sections_structure.keys():
syllabus_field = f"{section_name}_syllabus"
if syllabus_field in form_data:
syllabus_content = form_data.get(syllabus_field, "").strip()
if syllabus_content:
sections_structure[section_name]['syllabus'] = syllabus_content
print(f"📊 Creating exam: {title}")
print(f"🌍 Language: {exam_language}")
print(f"💬 Feedback enabled: {show_feedback}")
print(f"🎯 Difficulty level: {difficulty_level}")
print(f"📝 Custom AI instructions: {ai_custom_instructions[:100] if ai_custom_instructions else 'None'}...")
print(f"➖ Negative marking config: {negative_marking_config}")
print(f"☑️ Multi-select scoring mode: {multi_select_scoring_mode}")
print(f"🔢 MCQ options count: {mcq_options_count}")
# Validate form data
is_valid, error_message = validate_form_data({
'department': department,
'position': position,
'title': title,
'time_limit': time_limit
})
if not is_valid:
return templates.TemplateResponse("create_exam.html", {
"request": request,
"error": error_message
})
# Validate at least one section has questions
total_questions = sum(
section_config.get('mcq_count', 0) +
section_config.get('short_count', 0) +
section_config.get('essay_count', 0)
for section_config in sections_structure.values()
)
if total_questions == 0:
return templates.TemplateResponse("create_exam.html", {
"request": request,
"error": "Please add at least one question by enabling sections and setting question counts."
})
except (ValueError, TypeError, json.JSONDecodeError) as e:
return templates.TemplateResponse("create_exam.html", {
"request": request,
"error": f"Invalid input format: {str(e)}"
})
# Create exam in database
try:
exam_id = db.create_exam(
title=title, department=department, position=position, description=description,
time_limit=time_limit, instructions=instructions, question_structure={},
sections_structure=sections_structure, show_feedback=show_feedback,
negative_marking_config=negative_marking_config, exam_language=exam_language,
multi_select_scoring_mode=multi_select_scoring_mode
)
if not exam_id:
return templates.TemplateResponse("create_exam.html", {
"request": request,
"error": "Failed to create exam in database. Please try again."
})
print(f"✅ Exam created with ID: {exam_id}")
# Separate sections by generation mode
ai_sections = {}
manual_sections = {}
for section_type, section_config in sections_structure.items():
section_mode = section_config.get('generation_mode', generation_method)
if section_mode == 'ai':
ai_sections[section_type] = section_config
else:
manual_sections[section_type] = section_config
print(f"🤖 AI sections: {list(ai_sections.keys())}")
print(f"✍️ Manual sections: {list(manual_sections.keys())}")
question_count = 0
failed_sections = []
# Process AI-generated sections
if ai_sections:
print(f"🤖 Generating questions using AI for {len(ai_sections)} sections in {exam_language}")
generation_result = exam_system.generate_exam_questions_by_sections(
department, position, ai_sections, exam_language,
difficulty_level=difficulty_level,
custom_instructions=ai_custom_instructions,
mcq_options_count=mcq_options_count
)
# Handle successful sections
generated_sections = generation_result.get('questions', {})
for section_type, questions in generated_sections.items():
print(f"💾 Saving {len(questions)} AI-generated questions for {section_type}")
# Mark section as successfully generated
sections_structure[section_type]['generation_status'] = 'generated'
sections_structure[section_type]['last_generated'] = datetime.now().isoformat()
for question in questions:
question_id = db.save_exam_question(exam_id, question, section_type)
if question_id:
question_count += 1
if generated_sections:
print(f"✅ Saved {question_count} AI-generated questions")
# Handle failed sections - create placeholders
failed_sections = generation_result.get('failed_sections', [])
if failed_sections:
print(f"⚠️ AI generation failed for sections: {', '.join(failed_sections)}")
for section_type in failed_sections:
# Mark section as failed and move to manual
sections_structure[section_type]['generation_status'] = 'failed'
manual_sections[section_type] = ai_sections[section_type]
# Process manual sections (create placeholders)
if manual_sections:
print(f"📝 Creating placeholder questions for {len(manual_sections)} manual/failed sections")
for section_type, section_config in manual_sections.items():
# Mark generation status for manual sections
if section_type not in failed_sections:
sections_structure[section_type]['generation_status'] = 'manual'
# Create MCQ placeholders
for i in range(section_config.get('mcq_count', 0)):
placeholder_question = {
'type': 'mcq',
'question': f'[MCQ Question {question_count + 1}] - Edit this question or click "Regenerate Section" to generate with AI',
'options': ['Option A', 'Option B', 'Option C', 'Option D'],
'correct_answer': 0,
'marks': section_config.get('mcq_marks', 1),
'explanation': 'Add explanation here'
}
if db.save_exam_question(exam_id, placeholder_question, section_type):
question_count += 1
# Create Short Answer placeholders
for i in range(section_config.get('short_count', 0)):
placeholder_question = {
'type': 'short',
'question': f'[Short Answer Question {question_count + 1}] - Edit this question or click "Regenerate Section" to generate with AI',
'expected_answer': 'Expected answer guidelines here',
'evaluation_criteria': 'Evaluation criteria here',
'marks': section_config.get('short_marks', 1)
}
if db.save_exam_question(exam_id, placeholder_question, section_type):
question_count += 1
# Create Essay placeholders
for i in range(section_config.get('essay_count', 0)):
placeholder_question = {
'type': 'essay',
'question': f'[Essay Question {question_count + 1}] - Edit this question or click "Regenerate Section" to generate with AI',
'expected_answer': 'Expected answer structure here',
'evaluation_criteria': 'Detailed evaluation criteria here',
'marks': section_config.get('essay_marks', 1)
}
if db.save_exam_question(exam_id, placeholder_question, section_type):
question_count += 1
print(f"✅ Created placeholder questions for manual/failed sections")
# Update sections_structure with generation status
db.update_sections_structure(exam_id, sections_structure)
print(f"✅ Total {question_count} questions created")
if question_count == 0:
return templates.TemplateResponse("create_exam.html", {
"request": request,
"error": "Failed to create questions. Please try again."
})
# Redirect with appropriate flags
redirect_url = f"/admin/edit-exam/{exam_id}"
if manual_sections or failed_sections:
# Add flags to indicate manual editing needed and which sections failed
redirect_url += "?manual=1"
if failed_sections:
redirect_url += f"&failed={','.join(failed_sections)}"
return RedirectResponse(url=redirect_url, status_code=303)
except Exception as e:
error_msg = safe_error_message(e, "exam creation")
return templates.TemplateResponse("create_exam.html", {
"request": request,
"error": error_msg
})
@app.get("/admin/edit-exam/{exam_id}", response_class=HTMLResponse)
async def edit_exam_page(request: Request, exam_id: str, session_id: str = Depends(verify_admin_access)):
"""Edit exam questions page"""
exam = db.get_exam_by_id(exam_id)
if not exam:
raise HTTPException(status_code=404, detail="Exam not found")
manual_mode = request.query_params.get("manual") == "1"
failed_sections_param = request.query_params.get("failed", "")
failed_sections = failed_sections_param.split(",") if failed_sections_param else []
sections = db.get_exam_questions_by_section(exam_id)
sections_structure = exam.get('sections_structure', {})
# Convert to flat list for template and ensure images are loaded
questions = []
for section_type, section_questions in sections.items():
for question in section_questions:
question['section_type'] = section_type