import os import atexit import threading import time import sys import json import pandas as pd import requests from functools import wraps from src.logger import logging # Keep track of files to clean up safely across concurrent requests FILES_TO_CLEANUP = set() cleanup_lock = threading.Lock() def get_base_path(): """Get base path, works for both development and PyInstaller""" if getattr(sys, 'frozen', False): # Running as PyInstaller executable return sys._MEIPASS else: # Running as normal Python script return os.path.abspath(".") def register_for_cleanup(filepath): """Register a file for cleanup when the application exits""" if filepath and os.path.exists(filepath): with cleanup_lock: FILES_TO_CLEANUP.add(filepath) logging.info(f"Registered file for cleanup: {filepath}") def cleanup_file(filepath): """Clean up a single file safely""" try: if filepath and os.path.exists(filepath): os.remove(filepath) logging.info(f"Successfully cleaned up file: {filepath}") with cleanup_lock: FILES_TO_CLEANUP.discard(filepath) return True except Exception as e: logging.error(f"Failed to cleanup file {filepath}: {e}") return False def cleanup_after_download(delay_seconds=30): """ Decorator to register files for cleanup after download. (Refactored: Now delegates actual deletion to the single background periodic worker to prevent thread exhaustion on Hugging Face Spaces). """ def decorator(func): @wraps(func) def wrapper(*args, **kwargs): result = func(*args, **kwargs) # If the function returns a file path, register it for the batch cleanup if isinstance(result, str) and os.path.exists(result): register_for_cleanup(result) logging.info(f"File {result} scheduled for periodic batch cleanup") return result return wrapper return decorator def cleanup_all_files(): """Clean up all registered files""" with cleanup_lock: # Create a copy to avoid mutating the set while iterating files_copy = list(FILES_TO_CLEANUP) cleaned_count = 0 for filepath in files_copy: if cleanup_file(filepath): cleaned_count += 1 logging.info(f"Cleanup completed. Removed {cleaned_count} files.") def cleanup_artifacts_directory(max_age_seconds=600): """Clean up old files in artifacts directory (default: older than 10 minutes)""" try: base_path = get_base_path() artifacts_dir = os.path.join(base_path, "artifacts") if not os.path.exists(artifacts_dir): return current_time = time.time() cleaned_count = 0 for filename in os.listdir(artifacts_dir): filepath = os.path.join(artifacts_dir, filename) if os.path.isfile(filepath): # Check if file is older than the max age threshold if current_time - os.path.getmtime(filepath) > max_age_seconds: if cleanup_file(filepath): cleaned_count += 1 if cleaned_count > 0: logging.info(f"Artifacts directory batch cleanup: removed {cleaned_count} old files") except Exception as e: logging.error(f"Error cleaning artifacts directory: {e}") def ensure_artifacts_directory(): """Ensure artifacts directory exists and return the full path""" try: base_path = get_base_path() artifacts_dir = os.path.join(base_path, "artifacts") os.makedirs(artifacts_dir, exist_ok=True) return artifacts_dir except Exception as e: logging.error(f"Failed to create artifacts directory: {e}") raise # Register cleanup function to run when application exits atexit.register(cleanup_all_files) # Periodically clean up old files def start_periodic_cleanup(): """Start a single background thread for periodic cleanup of old files""" def periodic_worker(): while True: time.sleep(300) # Run sweep every 5 minutes cleanup_artifacts_directory(max_age_seconds=600) # Sweep files older than 10 mins cleanup_thread = threading.Thread(target=periodic_worker, daemon=True) cleanup_thread.start() logging.info("Started central periodic cleanup thread") # ========================================== # DASHBOARD ANALYTICS UTILS # ========================================== def process_dashboard_metrics(records, is_subject_specific: bool): """Processes academic records into a dataframe suitable for dashboard analytics.""" if not records: return None df = pd.DataFrame(records) if is_subject_specific: # Subject specific: use the marks directly df['Total Score'] = df['marks_obtained'] df['Percentage'] = (df['marks_obtained'] / df['total_marks']) * 100 df['Has_Backlog'] = df['marks_obtained'] < (0.40 * df['total_marks']) else: # Overall: Group by student to sum all their subject marks and track backlogs df['Is_Fail_Subject'] = (df['grade'] == 'Fail') | (df['marks_obtained'] < (0.40 * df['total_marks'])) grouped = df.groupby('student_id').agg({ 'marks_obtained': 'sum', 'total_marks': 'sum', 'Is_Fail_Subject': 'any' }).reset_index() grouped['Total Score'] = grouped['marks_obtained'] grouped['Percentage'] = (grouped['marks_obtained'] / grouped['total_marks']) * 100 grouped['Has_Backlog'] = grouped['Is_Fail_Subject'] df = grouped return df def generate_dashboard_data(df, name_map: dict): """Generates the standardized dictionary required by the analyze UI charts.""" if df is None or df.empty: return None # Standardize column names score_col = 'Total Score' perc_col = 'Percentage' name_col = 'NAME' # Map student names df[name_col] = df['student_id'].map(name_map) # Metric Calculations total_students = len(df) avg_score = round(df[score_col].mean(), 2) if total_students > 0 else 0 high_score = df[score_col].max() if total_students > 0 else 0 # Pass percentage considers both cumulative percentage and whether they have any backlog passing_df = df[(df[perc_col] >= 40) & (~df['Has_Backlog'])] if 'Has_Backlog' in df.columns else df[df[perc_col] >= 40] pass_perc = round((len(passing_df) / total_students) * 100, 2) if total_students > 0 else 0 # Preparation for Charts (Grab up to Top 20 for dynamic dropdowns) top_20 = df.nlargest(20, score_col) # Fetch ALL failing or backlog students for the frontend failed_df = df[(df[perc_col] < 40) | (df['Has_Backlog'])].copy() if 'Has_Backlog' in df.columns else df[df[perc_col] < 40].copy() failed_count = len(failed_df) all_failed = failed_df.sort_values(by=score_col, ascending=True) # Lowest scores first return { "total_students": total_students, "pass_percentage": pass_perc, "average_score": avg_score, "highest_score": high_score, "grade_labels": json.dumps(['O (90-100)', 'A+ (75-89)', 'A (60-74)', 'B+ (55-59)', 'B (50-54)', 'C (45-49)', 'D (40-44)', 'F (0-39)']), "grade_counts": json.dumps([ len(df[df[perc_col] >= 90]), len(df[(df[perc_col] >= 75) & (df[perc_col] < 90)]), len(df[(df[perc_col] >= 60) & (df[perc_col] < 75)]), len(df[(df[perc_col] >= 55) & (df[perc_col] < 60)]), len(df[(df[perc_col] >= 50) & (df[perc_col] < 55)]), len(df[(df[perc_col] >= 45) & (df[perc_col] < 50)]), len(df[(df[perc_col] >= 40) & (df[perc_col] < 45)]), len(df[df[perc_col] < 40]) ]), "top_names": json.dumps(top_20[name_col].tolist()), "top_scores": json.dumps(top_20[score_col].tolist()), # Exporting full failure/backlog data to the UI "failed_count": failed_count, "failed_names": json.dumps(all_failed[name_col].tolist()), "failed_scores": json.dumps(all_failed[score_col].tolist()) } # ========================================== # EMAIL NOTIFICATIONS UTILS # ========================================== def send_reset_email(to_email: str, reset_link: str): """Sends a password reset email using a free custom webhook.""" webhook_url = os.environ.get("WEBHOOK_EMAIL_URL") if not webhook_url: logging.error("WEBHOOK_EMAIL_URL is not set in environment variables.") raise Exception("Email configuration missing. Please set WEBHOOK_EMAIL_URL.") body_html = f"""

Password Reset Request

Hello,

You have requested to reset your password for your Rankmate account.

Please click the button below to set a new password:

Reset Password

If you did not request this, please ignore this email.
For your security, this link will expire in 1 hour.


Best regards,
The Rankmate Team

""" payload = { "to": to_email, "subject": "Rankmate - Password Reset Request", "html": body_html } try: response = requests.post(webhook_url, json=payload) response.raise_for_status() logging.info(f"Password reset email sent successfully via Webhook to {to_email}") except requests.exceptions.RequestException as e: logging.error(f"Error sending email via Webhook to {to_email}: {e}") raise Exception(f"Failed to send email. Please try again later.")