Rankmate / src /components /finalize.py
sumit1901's picture
Made major changes in ui and functionality to handle the ledger
7e03cc0
Raw History Blame Contribute Delete
15.7 kB
import pandas as pd
import numpy as np
import sys
import os
import uuid
from bson import ObjectId
from fastapi import UploadFile
from src.logger import logging
from src.exception import CustomException
from src.utils import cleanup_after_download, ensure_artifacts_directory
from src.subject_mapping import SUBJECT_MAP
# Import DB CRUD operations
try:
from database import crud
except ImportError:
crud = None
def build_dynamic_subject_map(department_id: str = None) -> dict:
"""
Merges the hardcoded SUBJECT_MAP with any custom templates
created by the department in the database.
"""
dynamic_map = {}
# 1. Load Hardcoded Subjects
for code, info in SUBJECT_MAP.items():
if isinstance(info, dict):
dynamic_map[code] = {
"name": info.get("name", code),
"semester": info.get("semester"),
"max_marks": float(info.get("max_marks") or 100.0)
}
else:
dynamic_map[code] = {
"name": info,
"semester": None,
"max_marks": 100.0
}
# 2. Overwrite with Department Custom Subjects
if department_id and crud:
try:
custom_subjects = crud.get_department_subjects(department_id)
for subj in custom_subjects:
dynamic_map[subj["code"]] = {
"name": subj["name"],
"semester": subj.get("semester"),
"max_marks": float(subj.get("max_marks") or 100.0)
}
except Exception as e:
logging.error(f"Failed to fetch custom subjects for department {department_id}: {e}")
return dynamic_map
def add_total_score_column(df: pd.DataFrame, subject_map: dict):
try:
metadata = ["PRN", "NAME", "Seat No", "Rank"]
subj_cols = [col for col in df.columns if col not in metadata]
valid_subj_cols = []
for col in subj_cols:
subject_info = subject_map.get(col, {})
# If we explicitly defined max_marks as None in the map, skip it
if "max_marks" in subject_info and subject_info.get("max_marks") is None:
continue
valid_subj_cols.append(col)
if valid_subj_cols:
df['Total Score'] = pd.to_numeric(df[valid_subj_cols].stack(), errors='coerce').unstack().sum(axis=1)
else:
df['Total Score'] = 0
return df
except Exception as e:
logging.error(f"Failed to add Total score column: {e}")
raise CustomException(e, sys)
def add_percentage_column(df: pd.DataFrame, subject_map: dict):
try:
metadata = ["PRN", "NAME", "Seat No", "Rank", "Total Score"]
subj_cols = [col for col in df.columns if col not in metadata]
def calculate_student_max_marks(row):
total_max = 0
for col in subj_cols:
if pd.notna(row.get(col)) and str(row.get(col)).strip() != "":
subject_info = subject_map.get(col, {})
total_max += subject_info.get("max_marks", 100.0)
return total_max if total_max > 0 else 100.0
df['Total Max Marks'] = df.apply(calculate_student_max_marks, axis=1)
df['Percentage'] = np.round((df['Total Score'] / df['Total Max Marks']) * 100, 2)
return df
except Exception as e:
logging.error(f"Failed to add Percentage column: {e}")
raise CustomException(e, sys)
def parse_academic_year(year_str: str, offset_years: int):
"""Dynamically shifts an academic year backwards or forwards."""
try:
parts = year_str.split("-")
return f"{int(parts[0]) + offset_years}-{int(parts[1]) + offset_years}"
except:
return year_str
def get_class_level_info(class_name: str):
"""Extracts the year level and prefix from a class name."""
c = str(class_name).upper()
if "FY" in c or "FIRST" in c: return 1, "FY" if "FY" in c else "FIRST"
elif "SY" in c or "SECOND" in c: return 2, "SY" if "SY" in c else "SECOND"
elif "TY" in c or "THIRD" in c: return 3, "TY" if "TY" in c else "THIRD"
elif "FOURTH" in c: return 4, "FOURTH"
return None, class_name
def process_and_store_db(df: pd.DataFrame, session_data: dict, subject_map: dict):
"""
Performs the wide-to-long transformation for the database using bulk operations.
Includes Smart Time-Travel Routing for backlogs and N+1 query optimization.
"""
try:
if not crud:
logging.error("CRUD module not found. Skipping DB insertion.")
return
school_id = session_data.get("school_id")
teacher_id = session_data.get("id")
department_id = session_data.get("department_id")
target_class_name = session_data.get("class_name", "General Class")
academic_year = session_data.get("academic_year", "2024-2025")
target_level, base_prefix = get_class_level_info(target_class_name)
db = crud.get_db()
class_cache = {} # Map (name, year) -> class_id
class_year_lookup = {} # Map class_id -> academic_year
def get_or_create_class(c_name, c_year):
cache_key = f"{c_name}_{c_year}"
if cache_key in class_cache:
return class_cache[cache_key]
query = {"school_id": school_id, "academic_year": c_year, "name": c_name}
if department_id: query["department_id"] = ObjectId(department_id)
existing = db.classes.find_one(query)
if existing:
cid = str(existing["_id"])
else:
c_data = {
"name": c_name,
"semester": 1,
"academic_year": c_year,
"department_id": department_id,
"class_teacher_id": teacher_id,
"school_id": school_id
}
cid = crud.create_class(c_data)
class_cache[cache_key] = cid
class_year_lookup[cid] = c_year
return cid
# Base target class
class_id = get_or_create_class(target_class_name, academic_year)
metadata_cols = ["PRN", "NAME", "Seat No", "Rank", "Total Score", "Total Max Marks", "Percentage"]
subject_cols = [col for col in df.columns if col not in metadata_cols]
# --- PRE-FLIGHT CHECK ---
for subj_code in subject_cols:
subj_info = subject_map.get(subj_code, {})
sem = subj_info.get("semester")
subj_level = None
if sem in [1, 2]: subj_level = 1
elif sem in [3, 4]: subj_level = 2
elif sem in [5, 6]: subj_level = 3
elif sem in [7, 8]: subj_level = 4
if target_level and subj_level and subj_level > target_level:
raise ValueError(f"Upload Blocked: You selected {target_class_name}, but the ledger contains advanced subjects (Sem {sem}).")
# --- PHASE 1: DYNAMIC TIME-TRAVEL ROUTING ---
subject_routing_map = {}
for subj_code in subject_cols:
sem = subject_map.get(subj_code, {}).get("semester")
subj_level = None
subj_prefix = None
if sem in [1, 2]: subj_level, subj_prefix = 1, "FY"
elif sem in [3, 4]: subj_level, subj_prefix = 2, "SY"
elif sem in [5, 6]: subj_level, subj_prefix = 3, "TY"
elif sem in [7, 8]: subj_level, subj_prefix = 4, "FOURTH"
if target_level and subj_level and subj_level < target_level:
# Time-travel: calculate exact historical class
offset = subj_level - target_level
routed_year = parse_academic_year(academic_year, offset)
routed_class_name = target_class_name.upper().replace(base_prefix, subj_prefix)
routed_class_id = get_or_create_class(routed_class_name, routed_year)
subject_routing_map[subj_code] = routed_class_id
else:
# Fallback to current class
subject_routing_map[subj_code] = class_id
# --- PHASE 2: PREPARE DATA FOR BULK UPSERT ---
students_to_upsert = []
subjects_to_upsert = []
unique_subject_codes = set()
for _, row in df.iterrows():
roll_number = str(row.get("PRN", row.get("Seat No", "UNKNOWN")))
student_name = str(row.get("NAME", "Unknown"))
target_class_ids = set()
for subj_code in subject_cols:
marks_obtained = row.get(subj_code)
if pd.notna(marks_obtained) and str(marks_obtained).strip() != "":
target_class_ids.add(subject_routing_map[subj_code])
for target_class_id in target_class_ids:
students_to_upsert.append({
"roll_number": roll_number,
"name": student_name,
"class_id": target_class_id,
"school_id": school_id,
"department_id": department_id
})
for subj_code in subject_cols:
marks_obtained = row.get(subj_code)
if pd.isna(marks_obtained):
continue
if subj_code not in unique_subject_codes:
unique_subject_codes.add(subj_code)
target_class_id = subject_routing_map[subj_code]
subj_name = subject_map.get(subj_code, {}).get("name", subj_code)
subjects_to_upsert.append({
"code": subj_code,
"name": subj_name,
"class_id": target_class_id,
"teacher_id": teacher_id,
"school_id": school_id
})
# --- PHASE 3: EXECUTE BULK UPSERTS & GET ID MAPS ---
logging.info("Executing Master Data Bulk Upserts with Time-Travel Routing...")
student_id_map = crud.bulk_upsert_students(students_to_upsert)
subject_id_map = crud.bulk_upsert_subjects(subjects_to_upsert)
# --- PHASE 4: BUILD FACT TABLE RECORDS (Instant Cache Access) ---
records_to_insert = []
for _, row in df.iterrows():
roll_number = str(row.get("PRN", row.get("Seat No", "UNKNOWN")))
for subj_code in subject_cols:
marks_obtained = row.get(subj_code)
if pd.isna(marks_obtained):
continue
try:
marks_obtained = float(marks_obtained)
except ValueError:
continue
target_class_id = subject_routing_map[subj_code]
student_key = f"{school_id}_{str(target_class_id)}_{roll_number}"
student_id = student_id_map.get(student_key)
subject_key = f"{school_id}_{str(target_class_id)}_{subj_code}"
subject_id = subject_id_map.get(subject_key)
if not student_id or not subject_id:
continue
# Fetch year from fast local dictionary cache
target_class_year = class_year_lookup.get(target_class_id, academic_year)
subject_info = subject_map.get(subj_code, {})
subj_name = subject_info.get("name", subj_code)
subject_max_marks = subject_info.get("max_marks", 100.0)
subject_semester = subject_info.get("semester")
grade = "Pass" if marks_obtained >= (0.40 * subject_max_marks) else "Fail"
record = {
"school_id": school_id,
"student_id": student_id,
"teacher_id": teacher_id,
"subject_id": subject_id,
"class_id": target_class_id,
"department_id": department_id,
"subject_code": subj_code,
"subject_name": subj_name,
"academic_year": target_class_year,
"semester": subject_semester,
"marks_obtained": marks_obtained,
"total_marks": subject_max_marks,
"grade": grade,
"attendance_percentage": 0.0
}
records_to_insert.append(record)
# --- PHASE 5: BULK INSERT/UPDATE ACADEMIC RECORDS ---
if records_to_insert:
inserted_count = crud.insert_academic_records_bulk(records_to_insert)
logging.info(f"Successfully routed and upserted {inserted_count} academic records into DB!")
except ValueError as ve:
# Pass validation errors cleanly to the frontend
logging.warning(f"Validation Blocked Upload: {ve}")
raise CustomException(str(ve), sys)
except Exception as e:
logging.error(f"Error during DB extraction/insertion process: {e}")
raise CustomException(e, sys)
@cleanup_after_download(delay_seconds=60)
def generate_rank_list(processed_file: UploadFile, session_data: dict = None):
try:
if processed_file:
logging.info(f"Received processed file for finalization: {processed_file.filename}")
logging.info("Started generating rank list...")
artifacts_dir = ensure_artifacts_directory()
csv_path = os.path.join(artifacts_dir, f"ranks_of_student_{uuid.uuid4().hex}.csv")
df = pd.read_csv(processed_file.file)
if "Rank" in df.columns or "Percentage" in df.columns:
raise ValueError("you already have the ranked list and precentage you can't use this file.")
# Build dynamic subject map based on user's department
department_id = session_data.get("department_id") if session_data else None
dynamic_subject_map = build_dynamic_subject_map(department_id)
df = add_total_score_column(df, dynamic_subject_map)
df = add_percentage_column(df, dynamic_subject_map)
df = df.sort_values(by='Percentage', ascending=False).reset_index(drop=True)
df.index += 1
df.index.name = 'Rank'
if session_data:
logging.info("Authorized user detected. Initiating database insertion...")
process_and_store_db(df, session_data, dynamic_subject_map)
else:
logging.info("Public user detected. Skipping database insertion.")
# Map codes to names using the new dynamic map
rename_map = {code: info["name"] for code, info in dynamic_subject_map.items() if code in df.columns}
df = df.rename(columns=rename_map)
df.to_csv(csv_path)
logging.info(f"Rank list successfully generated with {len(df)} students.")
return csv_path
except ValueError as ve:
raise ve
except CustomException:
raise
except Exception as e:
logging.critical(f"Unexpected error occurred in generate_rank_list(): {e}")
raise CustomException(e, sys)