File size: 10,491 Bytes
48322a4
 
 
 
 
 
 
02438db
48322a4
 
 
80320be
48322a4
80320be
48322a4
 
 
 
 
 
 
 
 
 
 
 
 
80320be
 
48322a4
 
 
 
 
 
 
 
80320be
 
48322a4
 
 
 
 
 
80320be
 
 
 
 
48322a4
 
 
 
 
80320be
48322a4
 
80320be
48322a4
 
 
 
 
 
 
80320be
 
 
 
48322a4
80320be
48322a4
 
 
 
 
80320be
 
48322a4
 
 
 
 
 
 
 
 
 
 
 
 
80320be
 
48322a4
 
 
80320be
 
48322a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80320be
48322a4
 
80320be
 
48322a4
80320be
48322a4
80320be
48322a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
991b37e
48322a4
991b37e
 
 
48322a4
 
991b37e
 
48322a4
991b37e
48322a4
 
991b37e
48322a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
991b37e
 
 
 
48322a4
 
 
 
991b37e
 
48322a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
991b37e
48322a4
 
 
3205f71
 
 
 
 
 
 
02438db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3205f71
 
02438db
 
 
 
 
 
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
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"""

    <div style="font-family: sans-serif; padding: 20px;">

        <h2>Password Reset Request</h2>

        <p>Hello,</p>

        <p>You have requested to reset your password for your Rankmate account.</p>

        <p>Please click the button below to set a new password:</p>

        <a href="{reset_link}" style="display: inline-block; padding: 10px 20px; background-color: #6366f1; color: #ffffff; text-decoration: none; border-radius: 5px;">Reset Password</a>

        <p style="margin-top: 20px; font-size: 0.9em; color: #666;">If you did not request this, please ignore this email.<br>

        For your security, this link will expire in 1 hour.</p>

        <hr style="border: none; border-top: 1px solid #eaeaea; margin: 20px 0;">

        <p style="font-size: 0.8em; color: #999;">Best regards,<br>The Rankmate Team</p>

    </div>

    """

    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.")