sumit1901 commited on
Commit
80320be
·
1 Parent(s): 02438db

Added some authentication,ui,and database improvements

Browse files
.gitignore CHANGED
@@ -4,4 +4,5 @@ build/
4
  dist/
5
  __pycache__/
6
  *.pyc
7
- keys.txt
 
 
4
  dist/
5
  __pycache__/
6
  *.pyc
7
+ keys.txt
8
+ *.env
api/auth.py CHANGED
@@ -1,4 +1,5 @@
1
  import os
 
2
  from fastapi import APIRouter, Request, Form
3
  from fastapi.responses import HTMLResponse, RedirectResponse
4
  from fastapi.templating import Jinja2Templates
@@ -15,8 +16,12 @@ router = APIRouter(tags=["Authentication"])
15
  # Initialize templates specifically for these routes
16
  templates = Jinja2Templates(directory="templates")
17
 
18
- # Setup serializer for tokens
19
- SECRET_KEY = os.environ.get("SECRET_KEY", "super-secret-rankmate-key-change-in-prod")
 
 
 
 
20
  serializer = URLSafeTimedSerializer(SECRET_KEY)
21
 
22
 
@@ -228,6 +233,11 @@ async def reset_password_post(
228
  @router.get('/admin/register', response_class=HTMLResponse)
229
  async def admin_register_get(request: Request):
230
  logging.info("Accessed Admin Registration page")
 
 
 
 
 
231
  return templates.TemplateResponse(request=request, name="admin_register.html", context={"request": request})
232
 
233
  @router.post('/admin/register')
@@ -235,10 +245,25 @@ async def admin_register_post(
235
  request: Request,
236
  name: str = Form(...),
237
  email: str = Form(...),
238
- password: str = Form(...)
 
239
  ):
240
  logging.info(f"Attempting admin registration for email: {email}")
241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  if not name or not email or not password:
243
  logging.warning("Admin Registration Failed: Missing required fields.")
244
  return templates.TemplateResponse(request=request, name="admin_register.html", context={"request": request, "error": "All fields are required."})
 
1
  import os
2
+ import secrets
3
  from fastapi import APIRouter, Request, Form
4
  from fastapi.responses import HTMLResponse, RedirectResponse
5
  from fastapi.templating import Jinja2Templates
 
16
  # Initialize templates specifically for these routes
17
  templates = Jinja2Templates(directory="templates")
18
 
19
+ # Setup serializer for tokens (Emergency Fix: Removed hardcoded fallback)
20
+ SECRET_KEY = os.environ.get("SECRET_KEY")
21
+ if not SECRET_KEY:
22
+ logging.warning("CRITICAL: SECRET_KEY environment variable is missing. Using a volatile random key. Password reset links will invalidate on server restart.")
23
+ SECRET_KEY = secrets.token_hex(32)
24
+
25
  serializer = URLSafeTimedSerializer(SECRET_KEY)
26
 
27
 
 
233
  @router.get('/admin/register', response_class=HTMLResponse)
234
  async def admin_register_get(request: Request):
235
  logging.info("Accessed Admin Registration page")
236
+
237
+ # Optional: Display a warning if the setup token is not configured
238
+ if not os.environ.get("ADMIN_SETUP_TOKEN"):
239
+ return HTMLResponse("Admin registration is completely disabled server-side. Set the ADMIN_SETUP_TOKEN environment variable to enable it.", status_code=403)
240
+
241
  return templates.TemplateResponse(request=request, name="admin_register.html", context={"request": request})
242
 
243
  @router.post('/admin/register')
 
245
  request: Request,
246
  name: str = Form(...),
247
  email: str = Form(...),
248
+ password: str = Form(...),
249
+ admin_token: str = Form(None)
250
  ):
251
  logging.info(f"Attempting admin registration for email: {email}")
252
 
253
+ # Emergency Fix: Super Admin Registration Restriction
254
+ expected_token = os.environ.get("ADMIN_SETUP_TOKEN")
255
+
256
+ # Allow passing the token via form OR via URL parameter (?token=YOUR_TOKEN)
257
+ provided_token = admin_token or request.query_params.get("token")
258
+
259
+ if not expected_token:
260
+ logging.critical("Admin registration attempted but ADMIN_SETUP_TOKEN is not configured in environment.")
261
+ return templates.TemplateResponse(request=request, name="admin_register.html", context={"request": request, "error": "Admin registration is disabled. Set ADMIN_SETUP_TOKEN to enable."})
262
+
263
+ if provided_token != expected_token:
264
+ logging.warning(f"Unauthorized admin registration attempt for {email}. Token mismatch.")
265
+ return templates.TemplateResponse(request=request, name="admin_register.html", context={"request": request, "error": "Unauthorized: Invalid admin setup token."})
266
+
267
  if not name or not email or not password:
268
  logging.warning("Admin Registration Failed: Missing required fields.")
269
  return templates.TemplateResponse(request=request, name="admin_register.html", context={"request": request, "error": "All fields are required."})
api/routes.py CHANGED
@@ -107,4 +107,57 @@ def api_delete_user(request: Request, user_id: str):
107
  raise HTTPException(status_code=404, detail="User not found")
108
  except Exception as e:
109
  logging.error(f"Error deleting user: {e}")
110
- raise HTTPException(status_code=400, detail=str(e))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  raise HTTPException(status_code=404, detail="User not found")
108
  except Exception as e:
109
  logging.error(f"Error deleting user: {e}")
110
+ raise HTTPException(status_code=400, detail=str(e))
111
+ # ==========================================
112
+ # PHASE C: DYNAMIC DASHBOARD DROPDOWNS
113
+ # ==========================================
114
+
115
+ @router.get("/classes")
116
+ def api_get_classes_for_year(request: Request, academic_year: str):
117
+ """Fetches classes for the cascading dropdown based on academic year."""
118
+ user = request.session.get("user")
119
+ if not user:
120
+ raise HTTPException(status_code=401, detail="Unauthorized")
121
+
122
+ logging.info(f"API Request: Fetch classes for year {academic_year} by {user.get('name')}")
123
+ db = crud.get_db()
124
+
125
+ query = {
126
+ "school_id": user["school_id"],
127
+ "academic_year": academic_year
128
+ }
129
+
130
+ if user.get("department_id"):
131
+ query["department_id"] = ObjectId(user["department_id"])
132
+
133
+ try:
134
+ classes = list(db.classes.find(query, {"name": 1, "_id": 1}))
135
+ # Convert ObjectId to string for JSON serialization
136
+ for c in classes:
137
+ c["_id"] = str(c["_id"])
138
+ return classes
139
+ except Exception as e:
140
+ logging.error(f"Error fetching classes: {e}")
141
+ raise HTTPException(status_code=500, detail="Database error")
142
+
143
+ @router.get("/subjects")
144
+ def api_get_subjects_for_class(request: Request, class_id: str):
145
+ """Fetches subjects taught to a specific class for the cascading dropdown."""
146
+ user = request.session.get("user")
147
+ if not user:
148
+ raise HTTPException(status_code=401, detail="Unauthorized")
149
+
150
+ logging.info(f"API Request: Fetch subjects for class {class_id} by {user.get('name')}")
151
+ db = crud.get_db()
152
+
153
+ try:
154
+ query = {
155
+ "school_id": user["school_id"],
156
+ "class_id": ObjectId(class_id)
157
+ }
158
+ # Fetch unique subjects assigned to this class
159
+ subjects = list(db.subjects.find(query, {"code": 1, "name": 1, "_id": 0}))
160
+ return subjects
161
+ except Exception as e:
162
+ logging.error(f"Error fetching subjects: {e}")
163
+ raise HTTPException(status_code=500, detail="Database error")
api/ui.py CHANGED
@@ -80,13 +80,32 @@ async def finalize_get(request: Request):
80
  user = request.session.get("user")
81
  name = user.get("name") if user else "Guest"
82
  logging.info(f"UI Route accessed: Finalize (/finalize) by user: {name}")
83
- return templates.TemplateResponse(request=request, name="finalize.html", context={"request": request, "user": user})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
  @router.post('/finalize')
86
  async def finalize_post(
87
  request: Request,
88
  processed_file: UploadFile = File(...),
89
- academic_year: str = Form(None)
 
90
  ):
91
  logging.info("Starting finalization process...")
92
  try:
@@ -102,6 +121,8 @@ async def finalize_post(
102
  logging.info(f"User '{user_session['name']}' is logged in. Attempting database ingestion.")
103
  if academic_year:
104
  user_session['academic_year'] = academic_year
 
 
105
  else:
106
  logging.info("User is a Guest. Skipping database ingestion.")
107
 
@@ -124,9 +145,10 @@ async def finalize_post(
124
  media_type='text/csv'
125
  )
126
 
127
- except ValueError:
128
- logging.error("Finalization Failed: Invalid max_marks value provided.")
129
- raise HTTPException(status_code=400, detail="Invalid max_marks value")
 
130
  except Exception as e:
131
  logging.error(f"Critical Error during finalization: {e}")
132
  raise HTTPException(status_code=500, detail="Internal server error")
 
80
  user = request.session.get("user")
81
  name = user.get("name") if user else "Guest"
82
  logging.info(f"UI Route accessed: Finalize (/finalize) by user: {name}")
83
+
84
+ # --- NEW: Fetch classes for the dropdown based on the user's school and department ---
85
+ classes = []
86
+ if user and user.get("school_id"):
87
+ try:
88
+ db = db_instance.get_db()
89
+ query = {"school_id": user["school_id"]}
90
+ if user.get("department_id"):
91
+ query["department_id"] = ObjectId(user["department_id"])
92
+
93
+ classes = list(db.classes.find(query))
94
+ except Exception as e:
95
+ logging.error(f"Failed to fetch classes for finalize page: {e}")
96
+
97
+ return templates.TemplateResponse(
98
+ request=request,
99
+ name="finalize.html",
100
+ context={"request": request, "user": user, "classes": classes}
101
+ )
102
 
103
  @router.post('/finalize')
104
  async def finalize_post(
105
  request: Request,
106
  processed_file: UploadFile = File(...),
107
+ academic_year: str = Form(None),
108
+ class_id: str = Form(None)
109
  ):
110
  logging.info("Starting finalization process...")
111
  try:
 
121
  logging.info(f"User '{user_session['name']}' is logged in. Attempting database ingestion.")
122
  if academic_year:
123
  user_session['academic_year'] = academic_year
124
+ if class_id:
125
+ user_session['class_id'] = class_id
126
  else:
127
  logging.info("User is a Guest. Skipping database ingestion.")
128
 
 
145
  media_type='text/csv'
146
  )
147
 
148
+ except ValueError as ve:
149
+ # Pass Validation errors to UI (handled in finalize.py)
150
+ logging.error(f"Finalization Validation Failed: {ve}")
151
+ raise HTTPException(status_code=400, detail=str(ve))
152
  except Exception as e:
153
  logging.error(f"Critical Error during finalization: {e}")
154
  raise HTTPException(status_code=500, detail="Internal server error")
application.py CHANGED
@@ -3,6 +3,7 @@ import socket
3
  import webbrowser
4
  import time
5
  import uvicorn
 
6
  from contextlib import asynccontextmanager
7
  from fastapi import FastAPI
8
  from fastapi.staticfiles import StaticFiles
@@ -62,13 +63,14 @@ async def lifespan(app: FastAPI):
62
  # Initialize FastAPI app
63
  app = FastAPI(title="Student Performance Analyzer", lifespan=lifespan)
64
 
65
- # ✅ FIX: Add this middleware (THIS solves your HTTPS issue)
 
 
 
 
66
 
67
- # Fetch the secret key
68
- SECRET_KEY = os.environ.get("SECRET_KEY", "super-secret-rankmate-key-change-in-prod")
69
-
70
- # Session middleware
71
- app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY, same_site="none", https_only="True")
72
 
73
  app.add_middleware(ProxyHeadersMiddleware, trusted_hosts="*")
74
  # Static files
 
3
  import webbrowser
4
  import time
5
  import uvicorn
6
+ import secrets
7
  from contextlib import asynccontextmanager
8
  from fastapi import FastAPI
9
  from fastapi.staticfiles import StaticFiles
 
63
  # Initialize FastAPI app
64
  app = FastAPI(title="Student Performance Analyzer", lifespan=lifespan)
65
 
66
+ # Fetch the secret key (Emergency Fix: Removed hardcoded fallback)
67
+ SECRET_KEY = os.environ.get("SECRET_KEY")
68
+ if not SECRET_KEY:
69
+ print("⚠️ [SECURITY] SECRET_KEY environment variable is missing. Using a volatile random key.")
70
+ SECRET_KEY = secrets.token_hex(32)
71
 
72
+ # Session middleware (Emergency Fix: https_only must be a boolean, not a string)
73
+ app.add_middleware(SessionMiddleware, secret_key=SECRET_KEY, same_site="none", https_only=True)
 
 
 
74
 
75
  app.add_middleware(ProxyHeadersMiddleware, trusted_hosts="*")
76
  # Static files
database/crud.py CHANGED
@@ -208,11 +208,35 @@ def get_or_create_student(student_data: dict) -> str:
208
  logging.info(f"Student created successfully with Mongo ID: {result.inserted_id}")
209
  return str(result.inserted_id)
210
 
211
- # --- NEW BULK UPSERT FUNCTIONS ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  def bulk_upsert_subjects(subjects_data: List[dict]) -> Dict[str, str]:
213
  """
214
- Bulk upserts subjects and returns a mapping of a unique key to the Subject's ObjectId string.
215
- Unique key format: '{school_id}_{class_id}_{code}'
216
  """
217
  if not subjects_data:
218
  return {}
@@ -221,9 +245,9 @@ def bulk_upsert_subjects(subjects_data: List[dict]) -> Dict[str, str]:
221
  db = get_db()
222
  operations = []
223
 
224
- # Deduplicate input data to avoid conflicting operations
225
  unique_subjects = {}
226
  for s in subjects_data:
 
227
  key = f"{s['school_id']}_{str(s['class_id'])}_{s['code']}"
228
  unique_subjects[key] = s
229
 
@@ -248,7 +272,6 @@ def bulk_upsert_subjects(subjects_data: List[dict]) -> Dict[str, str]:
248
  result = db.subjects.bulk_write(operations)
249
  logging.info(f"Subjects bulk upsert complete. Matched: {result.matched_count}, Upserted: {result.upserted_count}")
250
 
251
- # Fetch all matched subjects to return their generated/existing IDs
252
  or_conditions = [
253
  {"code": s["code"], "class_id": ObjectId(s["class_id"]), "school_id": s["school_id"]}
254
  for s in unique_subjects.values()
@@ -265,8 +288,7 @@ def bulk_upsert_subjects(subjects_data: List[dict]) -> Dict[str, str]:
265
 
266
  def bulk_upsert_students(students_data: List[dict]) -> Dict[str, str]:
267
  """
268
- Bulk upserts students and returns a mapping of unique key to Student ObjectId string.
269
- Unique key format: '{school_id}_{class_id}_{roll_number}'
270
  """
271
  if not students_data:
272
  return {}
@@ -275,7 +297,6 @@ def bulk_upsert_students(students_data: List[dict]) -> Dict[str, str]:
275
  db = get_db()
276
  operations = []
277
 
278
- # Deduplicate input data to avoid conflicting operations
279
  unique_students = {}
280
  for st in students_data:
281
  key = f"{st['school_id']}_{str(st['class_id'])}_{st['roll_number']}"
@@ -305,7 +326,6 @@ def bulk_upsert_students(students_data: List[dict]) -> Dict[str, str]:
305
  result = db.students.bulk_write(operations)
306
  logging.info(f"Students bulk upsert complete. Matched: {result.matched_count}, Upserted: {result.upserted_count}")
307
 
308
- # Fetch the generated/existing IDs
309
  or_conditions = []
310
  for st in unique_students.values():
311
  cond = {
@@ -327,7 +347,7 @@ def bulk_upsert_students(students_data: List[dict]) -> Dict[str, str]:
327
  return id_map
328
 
329
  def insert_academic_records_bulk(records: List[dict]) -> int:
330
- """Inserts or updates a large batch of records from the parsed CSV."""
331
  if not records:
332
  logging.warning("Bulk insert called but records list is empty. Skipping.")
333
  return 0
@@ -344,15 +364,14 @@ def insert_academic_records_bulk(records: List[dict]) -> int:
344
  if "class_id" in doc: doc["class_id"] = ObjectId(doc["class_id"])
345
  if "department_id" in doc: doc["department_id"] = ObjectId(doc["department_id"])
346
 
 
 
 
347
  filter_query = {
348
  "school_id": doc["school_id"],
349
  "student_id": doc["student_id"],
350
- "subject_id": doc["subject_id"],
351
- "academic_year": doc["academic_year"],
352
  }
353
-
354
- if "department_id" in doc:
355
- filter_query["department_id"] = doc["department_id"]
356
 
357
  update_query = {
358
  "$set": doc
@@ -362,7 +381,7 @@ def insert_academic_records_bulk(records: List[dict]) -> int:
362
 
363
  if operations:
364
  result = db.academic_records.bulk_write(operations)
365
- logging.info(f"Bulk upsert complete. Matched: {result.matched_count}, Modified: {result.modified_count}, Inserted: {result.upserted_count}")
366
  return len(operations)
367
 
368
  return 0
 
208
  logging.info(f"Student created successfully with Mongo ID: {result.inserted_id}")
209
  return str(result.inserted_id)
210
 
211
+ # --- NEW: SMART ROUTING HELPER FUNCTIONS ---
212
+
213
+ def get_historical_subject_record(school_id: str, subject_code: str) -> Optional[dict]:
214
+ """SMART ROUTING: Checks if a subject code already belongs to a historical class."""
215
+ db = get_db()
216
+ subject = db.subjects.find_one({"school_id": school_id, "code": subject_code})
217
+ if subject:
218
+ subject["_id"] = str(subject["_id"])
219
+ subject["class_id"] = str(subject["class_id"])
220
+ return subject
221
+
222
+ def get_historical_student_record(school_id: str, roll_number: str, historical_class_id: str) -> Optional[dict]:
223
+ """SMART ROUTING: Fetches a student's past record tied to a specific historical class."""
224
+ db = get_db()
225
+ student = db.students.find_one({
226
+ "school_id": school_id,
227
+ "roll_number": roll_number,
228
+ "class_id": ObjectId(historical_class_id)
229
+ })
230
+ if student:
231
+ student["_id"] = str(student["_id"])
232
+ student["class_id"] = str(student["class_id"])
233
+ return student
234
+
235
+ # --- UPDATED BULK UPSERT FUNCTIONS ---
236
+
237
  def bulk_upsert_subjects(subjects_data: List[dict]) -> Dict[str, str]:
238
  """
239
+ Bulk upserts subjects, handling dynamic class_ids for backlogs.
 
240
  """
241
  if not subjects_data:
242
  return {}
 
245
  db = get_db()
246
  operations = []
247
 
 
248
  unique_subjects = {}
249
  for s in subjects_data:
250
+ # Key now safely includes the dynamic class_id for backlog handling
251
  key = f"{s['school_id']}_{str(s['class_id'])}_{s['code']}"
252
  unique_subjects[key] = s
253
 
 
272
  result = db.subjects.bulk_write(operations)
273
  logging.info(f"Subjects bulk upsert complete. Matched: {result.matched_count}, Upserted: {result.upserted_count}")
274
 
 
275
  or_conditions = [
276
  {"code": s["code"], "class_id": ObjectId(s["class_id"]), "school_id": s["school_id"]}
277
  for s in unique_subjects.values()
 
288
 
289
  def bulk_upsert_students(students_data: List[dict]) -> Dict[str, str]:
290
  """
291
+ Bulk upserts students, handling dynamic class_ids for backlogs.
 
292
  """
293
  if not students_data:
294
  return {}
 
297
  db = get_db()
298
  operations = []
299
 
 
300
  unique_students = {}
301
  for st in students_data:
302
  key = f"{st['school_id']}_{str(st['class_id'])}_{st['roll_number']}"
 
326
  result = db.students.bulk_write(operations)
327
  logging.info(f"Students bulk upsert complete. Matched: {result.matched_count}, Upserted: {result.upserted_count}")
328
 
 
329
  or_conditions = []
330
  for st in unique_students.values():
331
  cond = {
 
347
  return id_map
348
 
349
  def insert_academic_records_bulk(records: List[dict]) -> int:
350
+ """True Upsert: Overwrites backlog marks if a record for the student+subject already exists."""
351
  if not records:
352
  logging.warning("Bulk insert called but records list is empty. Skipping.")
353
  return 0
 
364
  if "class_id" in doc: doc["class_id"] = ObjectId(doc["class_id"])
365
  if "department_id" in doc: doc["department_id"] = ObjectId(doc["department_id"])
366
 
367
+ # TRUE UPSERT LOGIC: We match ONLY on Student + Subject.
368
+ # This ensures if they clear a backlog, the old record is updated with new marks,
369
+ # instead of creating a duplicate row in the DB.
370
  filter_query = {
371
  "school_id": doc["school_id"],
372
  "student_id": doc["student_id"],
373
+ "subject_id": doc["subject_id"]
 
374
  }
 
 
 
375
 
376
  update_query = {
377
  "$set": doc
 
381
 
382
  if operations:
383
  result = db.academic_records.bulk_write(operations)
384
+ logging.info(f"Bulk upsert complete. Matched/Updated: {result.matched_count}, Inserted: {result.upserted_count}")
385
  return len(operations)
386
 
387
  return 0
src/components/finalize.py CHANGED
@@ -3,6 +3,7 @@ import numpy as np
3
  import sys
4
  import os
5
  import uuid
 
6
  from fastapi import UploadFile
7
  from src.logger import logging
8
  from src.exception import CustomException
@@ -17,19 +18,16 @@ except ImportError:
17
 
18
  def add_total_score_column(df):
19
  try:
20
- # Define strictly which columns are NOT subject marks
21
  metadata = ["PRN", "NAME", "Seat No", "Rank"]
22
  subj_cols = [col for col in df.columns if col not in metadata]
23
 
24
- # Filter out subjects that have max_marks set to None (Non-credit courses)
25
  valid_subj_cols = []
26
  for col in subj_cols:
27
  subject_info = SUBJECT_MAP.get(col, {})
28
  if isinstance(subject_info, dict) and subject_info.get("max_marks") is None:
29
- continue # Skip adding marks for non-credit courses
30
  valid_subj_cols.append(col)
31
 
32
- # Ensure only numeric columns are summed for valid subjects
33
  if valid_subj_cols:
34
  df['Total Score'] = pd.to_numeric(df[valid_subj_cols].stack(), errors='coerce').unstack().sum(axis=1)
35
  else:
@@ -45,21 +43,18 @@ def add_percentage_column(df):
45
  metadata = ["PRN", "NAME", "Seat No", "Rank", "Total Score"]
46
  subj_cols = [col for col in df.columns if col not in metadata]
47
 
48
- # Dynamically calculate total max marks based on the subjects a student took
49
  def calculate_student_max_marks(row):
50
  total_max = 0
51
  for col in subj_cols:
52
- # Check if the student actually has marks for this subject
53
  if pd.notna(row.get(col)) and str(row.get(col)).strip() != "":
54
  subject_info = SUBJECT_MAP.get(col, {})
55
  if isinstance(subject_info, dict):
56
  max_m = subject_info.get("max_marks")
57
- # Only add to denominator if the course is explicitly graded
58
  if max_m is not None:
59
  total_max += max_m
60
  else:
61
- total_max += 100 # Fallback for unknown subjects not in map
62
- return total_max if total_max > 0 else 100 # Prevent division by zero fallback
63
 
64
  df['Total Max Marks'] = df.apply(calculate_student_max_marks, axis=1)
65
  df['Percentage'] = np.round((df['Total Score'] / df['Total Max Marks']) * 100, 2)
@@ -72,30 +67,86 @@ def add_percentage_column(df):
72
  def process_and_store_db(df: pd.DataFrame, session_data: dict):
73
  """
74
  Performs the wide-to-long transformation for the database using bulk operations.
75
- Extracts individual subject marks and maps them to subject_id.
76
  """
77
  try:
78
  if not crud:
79
  logging.error("CRUD module not found. Skipping DB insertion.")
80
  return
81
 
82
- # Fetch IDs from the session (the user's ID is the teacher's ID)
83
  school_id = session_data.get("school_id")
84
- teacher_id = session_data.get("id") # Match the session key from auth.py
85
- department_id = session_data.get("department_id") # Extract department ID
86
-
87
- # Provide a valid dummy ObjectId for class_id since it's not in the UI yet
88
- class_id = session_data.get("class_id", "65b9c0f9e1b2c3d4e5f6a7c0")
89
-
90
- # Dynamically fetch Academic Year and Semester selected from the UI
91
  academic_year = session_data.get("academic_year", "2024-2025")
 
92
 
93
- logging.info(f"Database Ingestion Context -> School: {school_id}, Dept: {department_id}, Teacher: {teacher_id}, Year: {academic_year}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
 
 
 
 
95
  metadata_cols = ["PRN", "NAME", "Seat No", "Rank", "Total Score", "Total Max Marks", "Percentage"]
96
  subject_cols = [col for col in df.columns if col not in metadata_cols]
97
 
98
- # --- PHASE 1: PREPARE DATA FOR BULK UPSERT ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  students_to_upsert = []
100
  subjects_to_upsert = []
101
  unique_subject_codes = set()
@@ -104,25 +155,30 @@ def process_and_store_db(df: pd.DataFrame, session_data: dict):
104
  roll_number = str(row.get("PRN", row.get("Seat No", "UNKNOWN")))
105
  student_name = str(row.get("NAME", "Unknown"))
106
 
107
- students_to_upsert.append({
108
- "roll_number": roll_number,
109
- "name": student_name,
110
- "class_id": class_id,
111
- "school_id": school_id,
112
- "department_id": department_id
113
- })
 
 
 
 
 
 
 
 
114
 
115
  for subj_code in subject_cols:
116
  marks_obtained = row.get(subj_code)
117
  if pd.isna(marks_obtained):
118
  continue
119
- try:
120
- float(marks_obtained)
121
- except ValueError:
122
- continue
123
-
124
  if subj_code not in unique_subject_codes:
125
  unique_subject_codes.add(subj_code)
 
126
 
127
  subject_info = SUBJECT_MAP.get(subj_code, {})
128
  if isinstance(subject_info, dict):
@@ -133,28 +189,20 @@ def process_and_store_db(df: pd.DataFrame, session_data: dict):
133
  subjects_to_upsert.append({
134
  "code": subj_code,
135
  "name": subj_name,
136
- "class_id": class_id,
137
  "teacher_id": teacher_id,
138
  "school_id": school_id
139
  })
140
 
141
- # --- PHASE 2: EXECUTE BULK UPSERTS & GET ID MAPS ---
142
- logging.info("Executing Master Data Bulk Upserts...")
143
  student_id_map = crud.bulk_upsert_students(students_to_upsert)
144
  subject_id_map = crud.bulk_upsert_subjects(subjects_to_upsert)
145
 
146
- # --- PHASE 3: BUILD FACT TABLE RECORDS (In-Memory Linking) ---
147
  records_to_insert = []
148
  for _, row in df.iterrows():
149
  roll_number = str(row.get("PRN", row.get("Seat No", "UNKNOWN")))
150
-
151
- # Reconstruct the unique key matching the one in crud.py
152
- student_key = f"{school_id}_{str(class_id)}_{roll_number}"
153
- student_id = student_id_map.get(student_key)
154
-
155
- if not student_id:
156
- logging.warning(f"Failed to resolve student ID for {roll_number}. Skipping record.")
157
- continue
158
 
159
  for subj_code in subject_cols:
160
  marks_obtained = row.get(subj_code)
@@ -165,18 +213,27 @@ def process_and_store_db(df: pd.DataFrame, session_data: dict):
165
  except ValueError:
166
  continue
167
 
168
- # Reconstruct the unique subject key
169
- subject_key = f"{school_id}_{str(class_id)}_{subj_code}"
 
 
 
 
170
  subject_id = subject_id_map.get(subject_key)
171
 
172
- if not subject_id:
173
  continue
174
 
175
- # Map the code to the full name and extract dynamic max marks
 
 
 
 
 
 
176
  subject_info = SUBJECT_MAP.get(subj_code, {})
177
  if isinstance(subject_info, dict):
178
  subj_name = subject_info.get("name", subj_code)
179
- # Use fallback 100 for DB if it's a non-credit course to prevent divide-by-zero errors in DB
180
  subject_max_marks = float(subject_info.get("max_marks") or 100.0)
181
  else:
182
  subj_name = subject_info
@@ -189,11 +246,11 @@ def process_and_store_db(df: pd.DataFrame, session_data: dict):
189
  "student_id": student_id,
190
  "teacher_id": teacher_id,
191
  "subject_id": subject_id,
192
- "class_id": class_id,
193
  "department_id": department_id,
194
  "subject_code": subj_code,
195
  "subject_name": subj_name,
196
- "academic_year": academic_year,
197
  "marks_obtained": marks_obtained,
198
  "total_marks": subject_max_marks,
199
  "grade": grade,
@@ -201,16 +258,20 @@ def process_and_store_db(df: pd.DataFrame, session_data: dict):
201
  }
202
  records_to_insert.append(record)
203
 
204
- # --- PHASE 4: BULK INSERT ACADEMIC RECORDS ---
205
  if records_to_insert:
206
  inserted_count = crud.insert_academic_records_bulk(records_to_insert)
207
- logging.info(f"Successfully parsed subjects and inserted {inserted_count} academic records into DB!")
208
 
 
 
 
 
209
  except Exception as e:
210
  logging.error(f"Error during DB extraction/insertion process: {e}")
211
  raise CustomException(e, sys)
212
 
213
- @cleanup_after_download(delay_seconds=60) # Clean up after 60 seconds
214
  def generate_rank_list(processed_file: UploadFile, session_data: dict = None):
215
  try:
216
  if processed_file:
@@ -218,35 +279,33 @@ def generate_rank_list(processed_file: UploadFile, session_data: dict = None):
218
 
219
  logging.info("Started generating rank list...")
220
 
221
- # Ensure artifacts directory exists
222
  artifacts_dir = ensure_artifacts_directory()
223
  csv_path = os.path.join(artifacts_dir, f"ranks_of_student_{uuid.uuid4().hex}.csv")
224
-
225
- logging.info(f"The Ranked CSV file will be saved to: {csv_path}")
226
 
227
- # Read the file-like object from FastAPI's UploadFile
228
  df = pd.read_csv(processed_file.file)
229
  df = add_total_score_column(df)
230
- df = add_percentage_column(df) # Dynamic calculation handles the math now
231
  df = df.sort_values(by='Percentage', ascending=False).reset_index(drop=True)
232
  df.index += 1
233
  df.index.name = 'Rank'
234
 
235
  # --- DATABASE INGESTION BLOCK ---
236
- # If the user is logged in, session_data will be provided, triggering DB storage
237
  if session_data:
238
  logging.info("Authorized user detected. Initiating database insertion...")
239
- process_and_store_db(df, session_data)
 
240
  else:
241
  logging.info("Public user detected. Skipping database insertion.")
242
 
243
- # Optional: Map the subject codes to full names in the final downloaded CSV too
244
  df = map_subject_codes_to_names(df)
245
 
246
  df.to_csv(csv_path)
247
  logging.info(f"Rank list successfully generated with {len(df)} students.")
248
  return csv_path
249
 
 
 
 
250
  except Exception as e:
251
  logging.critical(f"Unexpected error occurred in generate_rank_list(): {e}")
252
  raise CustomException(e, sys)
 
3
  import sys
4
  import os
5
  import uuid
6
+ from bson import ObjectId
7
  from fastapi import UploadFile
8
  from src.logger import logging
9
  from src.exception import CustomException
 
18
 
19
  def add_total_score_column(df):
20
  try:
 
21
  metadata = ["PRN", "NAME", "Seat No", "Rank"]
22
  subj_cols = [col for col in df.columns if col not in metadata]
23
 
 
24
  valid_subj_cols = []
25
  for col in subj_cols:
26
  subject_info = SUBJECT_MAP.get(col, {})
27
  if isinstance(subject_info, dict) and subject_info.get("max_marks") is None:
28
+ continue
29
  valid_subj_cols.append(col)
30
 
 
31
  if valid_subj_cols:
32
  df['Total Score'] = pd.to_numeric(df[valid_subj_cols].stack(), errors='coerce').unstack().sum(axis=1)
33
  else:
 
43
  metadata = ["PRN", "NAME", "Seat No", "Rank", "Total Score"]
44
  subj_cols = [col for col in df.columns if col not in metadata]
45
 
 
46
  def calculate_student_max_marks(row):
47
  total_max = 0
48
  for col in subj_cols:
 
49
  if pd.notna(row.get(col)) and str(row.get(col)).strip() != "":
50
  subject_info = SUBJECT_MAP.get(col, {})
51
  if isinstance(subject_info, dict):
52
  max_m = subject_info.get("max_marks")
 
53
  if max_m is not None:
54
  total_max += max_m
55
  else:
56
+ total_max += 100
57
+ return total_max if total_max > 0 else 100
58
 
59
  df['Total Max Marks'] = df.apply(calculate_student_max_marks, axis=1)
60
  df['Percentage'] = np.round((df['Total Score'] / df['Total Max Marks']) * 100, 2)
 
67
  def process_and_store_db(df: pd.DataFrame, session_data: dict):
68
  """
69
  Performs the wide-to-long transformation for the database using bulk operations.
70
+ Includes Hard Validation and Smart Routing for backlogs.
71
  """
72
  try:
73
  if not crud:
74
  logging.error("CRUD module not found. Skipping DB insertion.")
75
  return
76
 
 
77
  school_id = session_data.get("school_id")
78
+ teacher_id = session_data.get("id")
79
+ department_id = session_data.get("department_id")
 
 
 
 
 
80
  academic_year = session_data.get("academic_year", "2024-2025")
81
+ class_id = session_data.get("class_id")
82
 
83
+ db = crud.get_db()
84
+
85
+ # Resolve class_id
86
+ if not class_id:
87
+ try:
88
+ query = {"school_id": school_id, "academic_year": academic_year}
89
+ if department_id:
90
+ query["department_id"] = ObjectId(department_id)
91
+
92
+ existing_class = db.classes.find_one(query)
93
+ if existing_class:
94
+ class_id = str(existing_class["_id"])
95
+ else:
96
+ class_data = {
97
+ "name": "General Class",
98
+ "semester": 1,
99
+ "academic_year": academic_year,
100
+ "department_id": department_id,
101
+ "class_teacher_id": teacher_id,
102
+ "school_id": school_id
103
+ }
104
+ class_id = crud.create_class(class_data)
105
+ except Exception as e:
106
+ logging.error(f"Failed to dynamically resolve class_id: {e}")
107
+ class_id = str(ObjectId())
108
 
109
+ # --- PRE-FLIGHT CHECK: HARD VALIDATION ---
110
+ current_class = db.classes.find_one({"_id": ObjectId(class_id)})
111
+ class_name = current_class.get("name", "").upper() if current_class else ""
112
+
113
  metadata_cols = ["PRN", "NAME", "Seat No", "Rank", "Total Score", "Total Max Marks", "Percentage"]
114
  subject_cols = [col for col in df.columns if col not in metadata_cols]
115
 
116
+ has_sy = False
117
+ has_ty = False
118
+ for subj_code in subject_cols:
119
+ if "-" in str(subj_code):
120
+ parts = str(subj_code).split("-")
121
+ if len(parts) > 1 and parts[-1]:
122
+ first_digit = parts[-1][0]
123
+ if first_digit == '2': has_sy = True # e.g., BCA-231
124
+ elif first_digit == '3': has_ty = True # e.g., BCA-351
125
+
126
+ # Block Level Mismatches (Uploading advanced subjects into lower classes)
127
+ if "FY" in class_name and (has_sy or has_ty):
128
+ raise ValueError(f"Upload Blocked: You selected {class_name}, but the ledger contains Second/Third Year subjects. Please select the correct Class.")
129
+ if "SY" in class_name and has_ty:
130
+ raise ValueError(f"Upload Blocked: You selected {class_name}, but the ledger contains Third Year subjects. Please select the correct Class.")
131
+
132
+ # --- PHASE 1: SMART ROUTING & CONFLICT DETECTION ---
133
+ subject_routing_map = {}
134
+ for subj_code in subject_cols:
135
+ hist_subj = crud.get_historical_subject_record(school_id, subj_code)
136
+
137
+ if hist_subj and hist_subj["class_id"] != class_id:
138
+ # Conflict Check: Does this subject already belong to another class in the SAME year?
139
+ hist_class = db.classes.find_one({"_id": ObjectId(hist_subj["class_id"])})
140
+ if hist_class and hist_class.get("academic_year") == academic_year:
141
+ raise ValueError(f"Upload Blocked: Subject '{subj_code}' already belongs to class '{hist_class.get('name')}' for the {academic_year} academic year. Did you select the wrong class/year?")
142
+
143
+ # If it passed the check, it's a Backlog from a previous year! Route it back.
144
+ subject_routing_map[subj_code] = hist_subj["class_id"]
145
+ logging.info(f"Smart Routing: Backlog '{subj_code}' routed to historical class {hist_subj['class_id']}.")
146
+ else:
147
+ subject_routing_map[subj_code] = class_id
148
+
149
+ # --- PHASE 2: PREPARE DATA FOR BULK UPSERT ---
150
  students_to_upsert = []
151
  subjects_to_upsert = []
152
  unique_subject_codes = set()
 
155
  roll_number = str(row.get("PRN", row.get("Seat No", "UNKNOWN")))
156
  student_name = str(row.get("NAME", "Unknown"))
157
 
158
+ # A student might be present in the current class AND their historical backlog classes
159
+ target_class_ids = set()
160
+ for subj_code in subject_cols:
161
+ marks_obtained = row.get(subj_code)
162
+ if pd.notna(marks_obtained) and str(marks_obtained).strip() != "":
163
+ target_class_ids.add(subject_routing_map[subj_code])
164
+
165
+ for target_class_id in target_class_ids:
166
+ students_to_upsert.append({
167
+ "roll_number": roll_number,
168
+ "name": student_name,
169
+ "class_id": target_class_id,
170
+ "school_id": school_id,
171
+ "department_id": department_id
172
+ })
173
 
174
  for subj_code in subject_cols:
175
  marks_obtained = row.get(subj_code)
176
  if pd.isna(marks_obtained):
177
  continue
178
+
 
 
 
 
179
  if subj_code not in unique_subject_codes:
180
  unique_subject_codes.add(subj_code)
181
+ target_class_id = subject_routing_map[subj_code]
182
 
183
  subject_info = SUBJECT_MAP.get(subj_code, {})
184
  if isinstance(subject_info, dict):
 
189
  subjects_to_upsert.append({
190
  "code": subj_code,
191
  "name": subj_name,
192
+ "class_id": target_class_id,
193
  "teacher_id": teacher_id,
194
  "school_id": school_id
195
  })
196
 
197
+ # --- PHASE 3: EXECUTE BULK UPSERTS & GET ID MAPS ---
198
+ logging.info("Executing Master Data Bulk Upserts with Smart Routing...")
199
  student_id_map = crud.bulk_upsert_students(students_to_upsert)
200
  subject_id_map = crud.bulk_upsert_subjects(subjects_to_upsert)
201
 
202
+ # --- PHASE 4: BUILD FACT TABLE RECORDS ---
203
  records_to_insert = []
204
  for _, row in df.iterrows():
205
  roll_number = str(row.get("PRN", row.get("Seat No", "UNKNOWN")))
 
 
 
 
 
 
 
 
206
 
207
  for subj_code in subject_cols:
208
  marks_obtained = row.get(subj_code)
 
213
  except ValueError:
214
  continue
215
 
216
+ target_class_id = subject_routing_map[subj_code]
217
+
218
+ student_key = f"{school_id}_{str(target_class_id)}_{roll_number}"
219
+ student_id = student_id_map.get(student_key)
220
+
221
+ subject_key = f"{school_id}_{str(target_class_id)}_{subj_code}"
222
  subject_id = subject_id_map.get(subject_key)
223
 
224
+ if not student_id or not subject_id:
225
  continue
226
 
227
+ # Ensure backlogs retain the historical academic year
228
+ target_class_year = academic_year
229
+ if target_class_id != class_id:
230
+ hist_class = db.classes.find_one({"_id": ObjectId(target_class_id)})
231
+ if hist_class:
232
+ target_class_year = hist_class.get("academic_year", academic_year)
233
+
234
  subject_info = SUBJECT_MAP.get(subj_code, {})
235
  if isinstance(subject_info, dict):
236
  subj_name = subject_info.get("name", subj_code)
 
237
  subject_max_marks = float(subject_info.get("max_marks") or 100.0)
238
  else:
239
  subj_name = subject_info
 
246
  "student_id": student_id,
247
  "teacher_id": teacher_id,
248
  "subject_id": subject_id,
249
+ "class_id": target_class_id,
250
  "department_id": department_id,
251
  "subject_code": subj_code,
252
  "subject_name": subj_name,
253
+ "academic_year": target_class_year,
254
  "marks_obtained": marks_obtained,
255
  "total_marks": subject_max_marks,
256
  "grade": grade,
 
258
  }
259
  records_to_insert.append(record)
260
 
261
+ # --- PHASE 5: BULK INSERT/UPDATE ACADEMIC RECORDS ---
262
  if records_to_insert:
263
  inserted_count = crud.insert_academic_records_bulk(records_to_insert)
264
+ logging.info(f"Successfully routed and upserted {inserted_count} academic records into DB!")
265
 
266
+ except ValueError as ve:
267
+ # Pass validation errors cleanly to the frontend
268
+ logging.warning(f"Validation Blocked Upload: {ve}")
269
+ raise CustomException(str(ve), sys)
270
  except Exception as e:
271
  logging.error(f"Error during DB extraction/insertion process: {e}")
272
  raise CustomException(e, sys)
273
 
274
+ @cleanup_after_download(delay_seconds=60)
275
  def generate_rank_list(processed_file: UploadFile, session_data: dict = None):
276
  try:
277
  if processed_file:
 
279
 
280
  logging.info("Started generating rank list...")
281
 
 
282
  artifacts_dir = ensure_artifacts_directory()
283
  csv_path = os.path.join(artifacts_dir, f"ranks_of_student_{uuid.uuid4().hex}.csv")
 
 
284
 
 
285
  df = pd.read_csv(processed_file.file)
286
  df = add_total_score_column(df)
287
+ df = add_percentage_column(df)
288
  df = df.sort_values(by='Percentage', ascending=False).reset_index(drop=True)
289
  df.index += 1
290
  df.index.name = 'Rank'
291
 
292
  # --- DATABASE INGESTION BLOCK ---
 
293
  if session_data:
294
  logging.info("Authorized user detected. Initiating database insertion...")
295
+ # If process_and_store_db raises a ValueError, it will be caught below
296
+ process_and_store_db(df, session_data)
297
  else:
298
  logging.info("Public user detected. Skipping database insertion.")
299
 
 
300
  df = map_subject_codes_to_names(df)
301
 
302
  df.to_csv(csv_path)
303
  logging.info(f"Rank list successfully generated with {len(df)} students.")
304
  return csv_path
305
 
306
+ except CustomException:
307
+ # Re-raise so the API layer can send the exact error back to the user
308
+ raise
309
  except Exception as e:
310
  logging.critical(f"Unexpected error occurred in generate_rank_list(): {e}")
311
  raise CustomException(e, sys)
src/utils.py CHANGED
@@ -1,5 +1,4 @@
1
  import os
2
- import tempfile
3
  import atexit
4
  import threading
5
  import time
@@ -10,9 +9,9 @@ import requests
10
  from functools import wraps
11
  from src.logger import logging
12
 
13
- # Keep track of files to clean up
14
  FILES_TO_CLEANUP = set()
15
-
16
 
17
  def get_base_path():
18
  """Get base path, works for both development and PyInstaller"""
@@ -23,72 +22,61 @@ def get_base_path():
23
  # Running as normal Python script
24
  return os.path.abspath(".")
25
 
26
-
27
  def register_for_cleanup(filepath):
28
  """Register a file for cleanup when the application exits"""
29
  if filepath and os.path.exists(filepath):
30
- FILES_TO_CLEANUP.add(filepath)
 
31
  logging.info(f"Registered file for cleanup: {filepath}")
32
 
33
-
34
  def cleanup_file(filepath):
35
  """Clean up a single file safely"""
36
  try:
37
  if filepath and os.path.exists(filepath):
38
  os.remove(filepath)
39
  logging.info(f"Successfully cleaned up file: {filepath}")
40
- FILES_TO_CLEANUP.discard(filepath)
 
41
  return True
42
  except Exception as e:
43
  logging.error(f"Failed to cleanup file {filepath}: {e}")
44
  return False
45
 
46
-
47
- def delayed_cleanup(filepath, delay_seconds=30):
48
- """Clean up file after a delay to allow download completion"""
49
- def cleanup_worker():
50
- try:
51
- time.sleep(delay_seconds)
52
- cleanup_file(filepath)
53
- except Exception as e:
54
- logging.error(f"Error in delayed cleanup thread: {e}")
55
-
56
- cleanup_thread = threading.Thread(target=cleanup_worker)
57
- cleanup_thread.daemon = True
58
- cleanup_thread.start()
59
- logging.info(f"Scheduled delayed cleanup for: {filepath} in {delay_seconds} seconds")
60
-
61
-
62
  def cleanup_after_download(delay_seconds=30):
63
- """Decorator to cleanup files after download with configurable delay"""
 
 
 
 
64
  def decorator(func):
65
  @wraps(func)
66
  def wrapper(*args, **kwargs):
67
  result = func(*args, **kwargs)
68
 
69
- # If the function returns a file path, schedule it for cleanup
70
  if isinstance(result, str) and os.path.exists(result):
71
  register_for_cleanup(result)
72
- delayed_cleanup(result, delay_seconds)
73
- logging.info(f"File {result} scheduled for cleanup after download")
74
 
75
  return result
76
  return wrapper
77
  return decorator
78
 
79
-
80
  def cleanup_all_files():
81
  """Clean up all registered files"""
 
 
 
 
82
  cleaned_count = 0
83
- for filepath in list(FILES_TO_CLEANUP):
84
  if cleanup_file(filepath):
85
  cleaned_count += 1
86
 
87
  logging.info(f"Cleanup completed. Removed {cleaned_count} files.")
88
 
89
-
90
- def cleanup_artifacts_directory():
91
- """Clean up old files in artifacts directory (older than 1 hour)"""
92
  try:
93
  base_path = get_base_path()
94
  artifacts_dir = os.path.join(base_path, "artifacts")
@@ -102,45 +90,41 @@ def cleanup_artifacts_directory():
102
  for filename in os.listdir(artifacts_dir):
103
  filepath = os.path.join(artifacts_dir, filename)
104
  if os.path.isfile(filepath):
105
- # Check if file is older than 1 hour (3600 seconds)
106
- if current_time - os.path.getmtime(filepath) > 3600:
107
  if cleanup_file(filepath):
108
  cleaned_count += 1
109
 
110
- logging.info(f"Artifacts directory cleanup: removed {cleaned_count} old files")
 
111
  except Exception as e:
112
  logging.error(f"Error cleaning artifacts directory: {e}")
113
 
114
-
115
  def ensure_artifacts_directory():
116
  """Ensure artifacts directory exists and return the full path"""
117
  try:
118
  base_path = get_base_path()
119
  artifacts_dir = os.path.join(base_path, "artifacts")
120
  os.makedirs(artifacts_dir, exist_ok=True)
121
- logging.info(f"Artifacts directory ensured at: {artifacts_dir}")
122
  return artifacts_dir
123
  except Exception as e:
124
  logging.error(f"Failed to create artifacts directory: {e}")
125
  raise
126
 
127
-
128
  # Register cleanup function to run when application exits
129
  atexit.register(cleanup_all_files)
130
 
131
-
132
  # Periodically clean up old files
133
  def start_periodic_cleanup():
134
- """Start periodic cleanup of old files"""
135
  def periodic_worker():
136
  while True:
137
- time.sleep(3600) # Run every hour
138
- cleanup_artifacts_directory()
139
 
140
- cleanup_thread = threading.Thread(target=periodic_worker)
141
- cleanup_thread.daemon = True
142
  cleanup_thread.start()
143
- logging.info("Started periodic cleanup thread")
144
 
145
  # ==========================================
146
  # DASHBOARD ANALYTICS UTILS
 
1
  import os
 
2
  import atexit
3
  import threading
4
  import time
 
9
  from functools import wraps
10
  from src.logger import logging
11
 
12
+ # Keep track of files to clean up safely across concurrent requests
13
  FILES_TO_CLEANUP = set()
14
+ cleanup_lock = threading.Lock()
15
 
16
  def get_base_path():
17
  """Get base path, works for both development and PyInstaller"""
 
22
  # Running as normal Python script
23
  return os.path.abspath(".")
24
 
 
25
  def register_for_cleanup(filepath):
26
  """Register a file for cleanup when the application exits"""
27
  if filepath and os.path.exists(filepath):
28
+ with cleanup_lock:
29
+ FILES_TO_CLEANUP.add(filepath)
30
  logging.info(f"Registered file for cleanup: {filepath}")
31
 
 
32
  def cleanup_file(filepath):
33
  """Clean up a single file safely"""
34
  try:
35
  if filepath and os.path.exists(filepath):
36
  os.remove(filepath)
37
  logging.info(f"Successfully cleaned up file: {filepath}")
38
+ with cleanup_lock:
39
+ FILES_TO_CLEANUP.discard(filepath)
40
  return True
41
  except Exception as e:
42
  logging.error(f"Failed to cleanup file {filepath}: {e}")
43
  return False
44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  def cleanup_after_download(delay_seconds=30):
46
+ """
47
+ Decorator to register files for cleanup after download.
48
+ (Refactored: Now delegates actual deletion to the single background periodic worker
49
+ to prevent thread exhaustion on Hugging Face Spaces).
50
+ """
51
  def decorator(func):
52
  @wraps(func)
53
  def wrapper(*args, **kwargs):
54
  result = func(*args, **kwargs)
55
 
56
+ # If the function returns a file path, register it for the batch cleanup
57
  if isinstance(result, str) and os.path.exists(result):
58
  register_for_cleanup(result)
59
+ logging.info(f"File {result} scheduled for periodic batch cleanup")
 
60
 
61
  return result
62
  return wrapper
63
  return decorator
64
 
 
65
  def cleanup_all_files():
66
  """Clean up all registered files"""
67
+ with cleanup_lock:
68
+ # Create a copy to avoid mutating the set while iterating
69
+ files_copy = list(FILES_TO_CLEANUP)
70
+
71
  cleaned_count = 0
72
+ for filepath in files_copy:
73
  if cleanup_file(filepath):
74
  cleaned_count += 1
75
 
76
  logging.info(f"Cleanup completed. Removed {cleaned_count} files.")
77
 
78
+ def cleanup_artifacts_directory(max_age_seconds=600):
79
+ """Clean up old files in artifacts directory (default: older than 10 minutes)"""
 
80
  try:
81
  base_path = get_base_path()
82
  artifacts_dir = os.path.join(base_path, "artifacts")
 
90
  for filename in os.listdir(artifacts_dir):
91
  filepath = os.path.join(artifacts_dir, filename)
92
  if os.path.isfile(filepath):
93
+ # Check if file is older than the max age threshold
94
+ if current_time - os.path.getmtime(filepath) > max_age_seconds:
95
  if cleanup_file(filepath):
96
  cleaned_count += 1
97
 
98
+ if cleaned_count > 0:
99
+ logging.info(f"Artifacts directory batch cleanup: removed {cleaned_count} old files")
100
  except Exception as e:
101
  logging.error(f"Error cleaning artifacts directory: {e}")
102
 
 
103
  def ensure_artifacts_directory():
104
  """Ensure artifacts directory exists and return the full path"""
105
  try:
106
  base_path = get_base_path()
107
  artifacts_dir = os.path.join(base_path, "artifacts")
108
  os.makedirs(artifacts_dir, exist_ok=True)
 
109
  return artifacts_dir
110
  except Exception as e:
111
  logging.error(f"Failed to create artifacts directory: {e}")
112
  raise
113
 
 
114
  # Register cleanup function to run when application exits
115
  atexit.register(cleanup_all_files)
116
 
 
117
  # Periodically clean up old files
118
  def start_periodic_cleanup():
119
+ """Start a single background thread for periodic cleanup of old files"""
120
  def periodic_worker():
121
  while True:
122
+ time.sleep(300) # Run sweep every 5 minutes
123
+ cleanup_artifacts_directory(max_age_seconds=600) # Sweep files older than 10 mins
124
 
125
+ cleanup_thread = threading.Thread(target=periodic_worker, daemon=True)
 
126
  cleanup_thread.start()
127
+ logging.info("Started central periodic cleanup thread")
128
 
129
  # ==========================================
130
  # DASHBOARD ANALYTICS UTILS
static/js/analyze.js CHANGED
@@ -69,6 +69,10 @@ document.addEventListener("DOMContentLoaded", function() {
69
  },
70
  options: {
71
  responsive: true,
 
 
 
 
72
  scales: {
73
  y: {
74
  beginAtZero: true,
@@ -91,7 +95,31 @@ document.addEventListener("DOMContentLoaded", function() {
91
  cornerRadius: 8
92
  }
93
  }
94
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
  });
96
  }
97
 
@@ -150,7 +178,7 @@ document.addEventListener("DOMContentLoaded", function() {
150
 
151
  const count = parseInt(selectEl.value, 10);
152
 
153
- // Dynamically slice the cached top 20 list sent from the backend
154
  topChartInstance.data.labels = chartData.topNames.slice(0, count);
155
  topChartInstance.data.datasets[0].data = chartData.topScores.slice(0, count);
156
 
 
69
  },
70
  options: {
71
  responsive: true,
72
+ // Add a little padding to the top so the numbers don't get cut off
73
+ layout: {
74
+ padding: { top: 20 }
75
+ },
76
  scales: {
77
  y: {
78
  beginAtZero: true,
 
95
  cornerRadius: 8
96
  }
97
  }
98
+ },
99
+ // NEW: Custom inline plugin to draw numbers on top of the bars
100
+ plugins: [{
101
+ id: 'topLabels',
102
+ afterDatasetsDraw(chart, args, pluginOptions) {
103
+ const { ctx } = chart;
104
+ ctx.save();
105
+ ctx.font = "bold 13px 'Poppins', sans-serif";
106
+ ctx.fillStyle = "#6b7280"; // Matches the muted axis label color
107
+ ctx.textAlign = 'center';
108
+ ctx.textBaseline = 'bottom';
109
+
110
+ chart.data.datasets.forEach((dataset, i) => {
111
+ const meta = chart.getDatasetMeta(i);
112
+ meta.data.forEach((bar, index) => {
113
+ const data = dataset.data[index];
114
+ // Only draw the number if it is greater than 0
115
+ if (data > 0) {
116
+ ctx.fillText(data, bar.x, bar.y - 5);
117
+ }
118
+ });
119
+ });
120
+ ctx.restore();
121
+ }
122
+ }]
123
  });
124
  }
125
 
 
178
 
179
  const count = parseInt(selectEl.value, 10);
180
 
181
+ // Dynamically slice the cached top list sent from the backend
182
  topChartInstance.data.labels = chartData.topNames.slice(0, count);
183
  topChartInstance.data.datasets[0].data = chartData.topScores.slice(0, count);
184
 
templates/analyze.html CHANGED
@@ -26,20 +26,31 @@
26
  </div>
27
 
28
  <form action="/analyze" method="POST" class="d-flex flex-wrap align-items-end gap-3 mb-0">
29
- <div style="min-width: 160px;">
 
30
  <label class="form-label theme-label mb-1" style="font-size: 0.8rem; letter-spacing: 0.5px;">Academic Year</label>
31
- <select name="academic_year" class="form-select theme-input py-2" required>
32
- <option value="2021-2022">2021-2022</option>
33
  <option value="2022-2023">2022-2023</option>
34
  <option value="2023-2024">2023-2024</option>
35
  <option value="2024-2025">2024-2025</option>
36
  <option value="2025-2026">2025-2026</option>
 
 
 
 
 
 
 
 
37
  </select>
38
  </div>
39
 
40
  <div style="min-width: 240px;">
41
- <label class="form-label theme-label mb-1" style="font-size: 0.8rem; letter-spacing: 0.5px;">Subject Code</label>
42
- <input type="text" name="subject_code" class="form-control theme-input py-2" placeholder="e.g., BCA-111 (Leave blank)">
 
 
43
  </div>
44
 
45
  <div class="d-flex gap-2">
@@ -52,6 +63,12 @@
52
  </div>
53
 
54
  <div class="container mt-4 dashboard-container">
 
 
 
 
 
 
55
  {% if data %}
56
  <div class="row mb-4">
57
  <div class="col-md-3"><div class="stat-card stat-primary shadow-sm"><h6>Students Analyzed</h6><h3>{{ data.total_students }}</h3></div></div>
@@ -114,7 +131,7 @@
114
  </div>
115
  </div>
116
  </div>
117
- {% else %}
118
  <div class="empty-state shadow-sm border-0 mt-5">
119
  <h5 class="text-muted mb-0">Select your filters above to generate live performance insights from the database.</h5>
120
  </div>
@@ -124,18 +141,89 @@
124
 
125
  {% block scripts %}
126
  <script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
127
  function downloadRanks() {
128
- const year = document.querySelector('select[name="academic_year"]').value;
129
- const subjectCode = document.querySelector('input[name="subject_code"]').value.trim();
130
- let url = `/export_db_ranks?academic_year=${year}`;
 
 
 
 
 
 
 
131
  if (subjectCode !== "") url += `&subject_code=${encodeURIComponent(subjectCode)}`;
132
  window.location.href = url;
133
  }
134
 
135
  function downloadFailed() {
136
- const year = document.querySelector('select[name="academic_year"]').value;
137
- const subjectCode = document.querySelector('input[name="subject_code"]').value.trim();
138
- let url = `/export_db_ranks?academic_year=${year}&failed_only=true`;
 
 
 
 
 
 
 
139
  if (subjectCode !== "") url += `&subject_code=${encodeURIComponent(subjectCode)}`;
140
  window.location.href = url;
141
  }
@@ -177,17 +265,13 @@
177
  const selectFailed = document.getElementById('failedCountSelect');
178
 
179
  if (rawChartData.failedCount === 0) {
180
- // Celebration state!
181
  container.innerHTML = `
182
  <div style="font-size: 3rem; margin-bottom: 10px;">🎉</div>
183
  <h5 class="text-success fw-bold">Woohoo!</h5>
184
  <p class="text-muted mt-2" style="font-size: 0.95rem;">No one failed. Excellent overall performance!</p>
185
  `;
186
  } else {
187
- // Show controls
188
  failedControls.style.setProperty('display', 'flex', 'important');
189
-
190
- // Build dropdown options dynamically based on failed count
191
  selectFailed.innerHTML = '';
192
  const totalFailed = rawChartData.failedCount;
193
 
@@ -202,7 +286,6 @@
202
  }
203
  }
204
 
205
- // Initial render
206
  updateFailedList();
207
  }
208
  } catch (e) {
@@ -210,7 +293,6 @@
210
  }
211
  });
212
 
213
- // Helper function used by analyze.js to get sliced top performers
214
  function getTopPerformersSlice() {
215
  if (!rawChartData) return { names: [], scores: [] };
216
  const count = parseInt(document.getElementById('topCountSelect').value);
@@ -220,7 +302,6 @@
220
  };
221
  }
222
 
223
- // Called when the "Needs Focus" dropdown changes
224
  function updateFailedList() {
225
  if (!rawChartData) return;
226
 
 
26
  </div>
27
 
28
  <form action="/analyze" method="POST" class="d-flex flex-wrap align-items-end gap-3 mb-0">
29
+
30
+ <div style="min-width: 150px;">
31
  <label class="form-label theme-label mb-1" style="font-size: 0.8rem; letter-spacing: 0.5px;">Academic Year</label>
32
+ <select name="academic_year" id="yearSelect" class="form-select theme-input py-2" required>
33
+ <option value="" disabled selected>-- Select Year --</option>
34
  <option value="2022-2023">2022-2023</option>
35
  <option value="2023-2024">2023-2024</option>
36
  <option value="2024-2025">2024-2025</option>
37
  <option value="2025-2026">2025-2026</option>
38
+ <option value="2026-2027">2026-2027</option>
39
+ </select>
40
+ </div>
41
+
42
+ <div style="min-width: 180px;">
43
+ <label class="form-label theme-label mb-1" style="font-size: 0.8rem; letter-spacing: 0.5px;">Class</label>
44
+ <select name="class_id" id="classSelect" class="form-select theme-input py-2" required disabled>
45
+ <option value="" disabled selected>-- Select Class --</option>
46
  </select>
47
  </div>
48
 
49
  <div style="min-width: 240px;">
50
+ <label class="form-label theme-label mb-1" style="font-size: 0.8rem; letter-spacing: 0.5px;">Subject</label>
51
+ <select name="subject_code" id="subjectSelect" class="form-select theme-input py-2" disabled>
52
+ <option value="" selected>Overall (All Subjects)</option>
53
+ </select>
54
  </div>
55
 
56
  <div class="d-flex gap-2">
 
63
  </div>
64
 
65
  <div class="container mt-4 dashboard-container">
66
+ {% if error %}
67
+ <div class="empty-state shadow-sm border-0 mt-5 p-4" style="background-color: #ffebee; border-radius: 10px;">
68
+ <h5 class="text-danger mb-0">{{ error }}</h5>
69
+ </div>
70
+ {% endif %}
71
+
72
  {% if data %}
73
  <div class="row mb-4">
74
  <div class="col-md-3"><div class="stat-card stat-primary shadow-sm"><h6>Students Analyzed</h6><h3>{{ data.total_students }}</h3></div></div>
 
131
  </div>
132
  </div>
133
  </div>
134
+ {% elif not error %}
135
  <div class="empty-state shadow-sm border-0 mt-5">
136
  <h5 class="text-muted mb-0">Select your filters above to generate live performance insights from the database.</h5>
137
  </div>
 
141
 
142
  {% block scripts %}
143
  <script>
144
+ // --- Cascading Dropdown Logic ---
145
+ document.getElementById('yearSelect').addEventListener('change', async function() {
146
+ const year = this.value;
147
+ const classSelect = document.getElementById('classSelect');
148
+ const subjectSelect = document.getElementById('subjectSelect');
149
+
150
+ // Reset and show loading state
151
+ classSelect.innerHTML = '<option value="" disabled selected>Loading classes...</option>';
152
+ classSelect.disabled = true;
153
+ subjectSelect.innerHTML = '<option value="" selected>Overall (All Subjects)</option>';
154
+ subjectSelect.disabled = true;
155
+
156
+ try {
157
+ // Fetch classes for this year
158
+ const response = await fetch(`/api/v1/classes?academic_year=${year}`);
159
+ const classes = await response.json();
160
+
161
+ classSelect.innerHTML = '<option value="" disabled selected>-- Select Class --</option>';
162
+ if (classes.length === 0) {
163
+ classSelect.innerHTML += '<option value="" disabled>No classes found for this year</option>';
164
+ } else {
165
+ classes.forEach(cls => {
166
+ classSelect.innerHTML += `<option value="${cls._id}">${cls.name}</option>`;
167
+ });
168
+ classSelect.disabled = false;
169
+ }
170
+ } catch (error) {
171
+ console.error("Error fetching classes:", error);
172
+ classSelect.innerHTML = '<option value="" disabled selected>Error loading classes</option>';
173
+ }
174
+ });
175
+
176
+ document.getElementById('classSelect').addEventListener('change', async function() {
177
+ const classId = this.value;
178
+ const subjectSelect = document.getElementById('subjectSelect');
179
+
180
+ subjectSelect.innerHTML = '<option value="" selected>Loading subjects...</option>';
181
+ subjectSelect.disabled = true;
182
+
183
+ try {
184
+ // Fetch subjects taught to this specific class
185
+ const response = await fetch(`/api/v1/subjects?class_id=${classId}`);
186
+ const subjects = await response.json();
187
+
188
+ subjectSelect.innerHTML = '<option value="" selected>Overall (All Subjects)</option>';
189
+ subjects.forEach(sub => {
190
+ subjectSelect.innerHTML += `<option value="${sub.code}">${sub.name} (${sub.code})</option>`;
191
+ });
192
+ subjectSelect.disabled = false;
193
+ } catch (error) {
194
+ console.error("Error fetching subjects:", error);
195
+ subjectSelect.innerHTML = '<option value="" selected>Overall (All Subjects)</option>';
196
+ subjectSelect.disabled = false;
197
+ }
198
+ });
199
+
200
+ // --- CSV Export Logic ---
201
  function downloadRanks() {
202
+ const year = document.getElementById('yearSelect').value;
203
+ const classId = document.getElementById('classSelect').value;
204
+ const subjectCode = document.getElementById('subjectSelect').value.trim();
205
+
206
+ if(!year || !classId) {
207
+ alert("Please select both an Academic Year and a Class to export data.");
208
+ return;
209
+ }
210
+
211
+ let url = `/export_db_ranks?academic_year=${year}&class_id=${classId}`;
212
  if (subjectCode !== "") url += `&subject_code=${encodeURIComponent(subjectCode)}`;
213
  window.location.href = url;
214
  }
215
 
216
  function downloadFailed() {
217
+ const year = document.getElementById('yearSelect').value;
218
+ const classId = document.getElementById('classSelect').value;
219
+ const subjectCode = document.getElementById('subjectSelect').value.trim();
220
+
221
+ if(!year || !classId) {
222
+ alert("Please select both an Academic Year and a Class to export data.");
223
+ return;
224
+ }
225
+
226
+ let url = `/export_db_ranks?academic_year=${year}&class_id=${classId}&failed_only=true`;
227
  if (subjectCode !== "") url += `&subject_code=${encodeURIComponent(subjectCode)}`;
228
  window.location.href = url;
229
  }
 
265
  const selectFailed = document.getElementById('failedCountSelect');
266
 
267
  if (rawChartData.failedCount === 0) {
 
268
  container.innerHTML = `
269
  <div style="font-size: 3rem; margin-bottom: 10px;">🎉</div>
270
  <h5 class="text-success fw-bold">Woohoo!</h5>
271
  <p class="text-muted mt-2" style="font-size: 0.95rem;">No one failed. Excellent overall performance!</p>
272
  `;
273
  } else {
 
274
  failedControls.style.setProperty('display', 'flex', 'important');
 
 
275
  selectFailed.innerHTML = '';
276
  const totalFailed = rawChartData.failedCount;
277
 
 
286
  }
287
  }
288
 
 
289
  updateFailedList();
290
  }
291
  } catch (e) {
 
293
  }
294
  });
295
 
 
296
  function getTopPerformersSlice() {
297
  if (!rawChartData) return { names: [], scores: [] };
298
  const count = parseInt(document.getElementById('topCountSelect').value);
 
302
  };
303
  }
304
 
 
305
  function updateFailedList() {
306
  if (!rawChartData) return;
307
 
templates/finalize.html CHANGED
@@ -49,26 +49,42 @@
49
  <div class="upload-box">
50
  <h3>Upload Metadata</h3>
51
  <p>Upload custom student data (names, classes) to get the .csv file with ranks of each student</p>
 
 
 
 
 
 
 
52
  <form action="/finalize" method="post" enctype="multipart/form-data">
53
  <input type="file" name="processed_file" accept=".csv" style="margin: 15px 0; width: 100%;" required/>
54
- <!-- <h5 style="font-family: 'Times New Roman', Times, serif; color: var(--text-dark); font-weight: normal;">
55
- Maximum Marks = <input type="number" name="max_marks" min="100" style="padding: 5px; border-radius: 5px; border: 1px solid #ccc;" required> -->
56
- </h5>
57
 
58
  {% if user %}
59
  <div style="margin: 15px 0; text-align: left;">
 
60
  <h5 style="font-family: 'Times New Roman', Times, serif; color: var(--text-dark); font-weight: normal; margin-bottom: 5px;">
61
  Academic Year
62
  </h5>
63
- <select name="academic_year" required style="width: 100%; padding: 8px; border-radius: 5px; border: 1px solid #ccc;">
64
- <option value="" disabled selected>Select Academic Year</option>
65
- <option value="2021-2022">2021-2022</option>
66
  <option value="2022-2023">2022-2023</option>
67
  <option value="2023-2024">2023-2024</option>
68
  <option value="2024-2025">2024-2025</option>
69
  <option value="2025-2026">2025-2026</option>
70
  <option value="2026-2027">2026-2027</option>
 
 
 
 
 
 
 
 
 
 
 
71
  </select>
 
72
  </div>
73
  {% endif %}
74
 
 
49
  <div class="upload-box">
50
  <h3>Upload Metadata</h3>
51
  <p>Upload custom student data (names, classes) to get the .csv file with ranks of each student</p>
52
+
53
+ {% if error %}
54
+ <div style="background-color: #ffebee; color: #c62828; padding: 10px; border-radius: 5px; margin-bottom: 15px; font-weight: bold;">
55
+ {{ error }}
56
+ </div>
57
+ {% endif %}
58
+
59
  <form action="/finalize" method="post" enctype="multipart/form-data">
60
  <input type="file" name="processed_file" accept=".csv" style="margin: 15px 0; width: 100%;" required/>
 
 
 
61
 
62
  {% if user %}
63
  <div style="margin: 15px 0; text-align: left;">
64
+
65
  <h5 style="font-family: 'Times New Roman', Times, serif; color: var(--text-dark); font-weight: normal; margin-bottom: 5px;">
66
  Academic Year
67
  </h5>
68
+ <select name="academic_year" required style="width: 100%; padding: 8px; border-radius: 5px; border: 1px solid #ccc; margin-bottom: 15px;">
69
+ <option value="" disabled selected>-- Select Academic Year --</option>
 
70
  <option value="2022-2023">2022-2023</option>
71
  <option value="2023-2024">2023-2024</option>
72
  <option value="2024-2025">2024-2025</option>
73
  <option value="2025-2026">2025-2026</option>
74
  <option value="2026-2027">2026-2027</option>
75
+ <option value="2027-2028">2027-2028</option>
76
+ </select>
77
+
78
+ <h5 style="font-family: 'Times New Roman', Times, serif; color: var(--text-dark); font-weight: normal; margin-bottom: 5px;">
79
+ Select Class
80
+ </h5>
81
+ <select name="class_id" required style="width: 100%; padding: 8px; border-radius: 5px; border: 1px solid #ccc;">
82
+ <option value="" disabled selected>-- Select a Class --</option>
83
+ {% for cls in classes %}
84
+ <option value="{{ cls._id }}">{{ cls.name }}</option>
85
+ {% endfor %}
86
  </select>
87
+
88
  </div>
89
  {% endif %}
90