-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
512 lines (414 loc) · 19.8 KB
/
Copy pathapp.py
File metadata and controls
512 lines (414 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
import streamlit as st
import pandas as pd
import joblib
import os
import numpy as np
import altair as alt
from PIL import Image
import io
import base64
from sklearn.base import BaseEstimator, ClassifierMixin
st.set_page_config(layout="wide", initial_sidebar_state="collapsed")
MODEL_PATH = 'student_risk_model.pkl'
FEATURES_PATH = 'features.txt'
DATASET_PATH = 'Dataset.csv'
CATEGORICAL_FEATURES = {
'gender': ['Male', 'Female'],
'department': ['CSE', 'Mechanical', 'Electronics', 'Civil', 'Biotech'],
'scholarship': ['Yes', 'No'],
'parental_education': ['None', 'High School', 'Graduate', 'Postgraduate', 'Doctorate'],
'extra_curricular': ['Yes', 'No'],
'sports_participation': ['Yes', 'No']
}
RISK_THRESHOLD_HIGH = 0.70
RISK_THRESHOLD_MEDIUM = 0.50
LOW_RISK_COLOR = {
"background": "#f0f7f0",
"primary": "#2e7d32",
"secondary": "#4caf50",
"text": "#1b5e20"
}
MEDIUM_RISK_COLOR = {
"background": "#fff8e1",
"primary": "#ef6c00",
"secondary": "#ff9800",
"text": "#e65100"
}
HIGH_RISK_COLOR = {
"background": "#ffebee",
"primary": "#c62828",
"secondary": "#f44336",
"text": "#b71c1c"
}
# --- Icon Colors ---
ICON_COLORS = {
"low": "#4caf50",
"medium": "#ff9800",
"high": "#f44336"
}
def load_css():
"""
Injects custom CSS to style the prediction result and fix text visibility.
"""
st.markdown(
"""
<style>
/* Fix for dark mode text visibility */
div[data-testid="stVerticalBlockBorderWrapper"] {
color: black !important;
}
div[data-testid="stVerticalBlockBorderWrapper"] h3 {
color: black !important;
}
div[data-testid="stVerticalBlockBorderWrapper"] .st-caption {
color: #333333 !important;
}
/* Custom styling for risk result cards */
.risk-result-card {
border-radius: 10px;
padding: 25px;
text-align: center;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
margin: 20px 0;
border: 1px solid rgba(0, 0, 0, 0.05);
}
.risk-icon {
width: 80px;
height: 80px;
margin: 0 auto 15px;
display: block;
}
.risk-title {
font-size: 28px;
font-weight: bold;
margin-bottom: 15px;
}
.risk-description {
font-size: 18px;
margin-bottom: 20px;
}
.risk-stats {
display: flex;
justify-content: space-around;
margin-top: 20px;
}
.risk-stat {
text-align: center;
}
.risk-stat-label {
font-size: 14px;
color: #666;
margin-bottom: 5px;
}
.risk-stat-value {
font-size: 20px;
font-weight: bold;
}
</style>
""",
unsafe_allow_html=True
)
def get_checkmark_icon(color="#4caf50"):
svg = f"""
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="{color}" width="80px" height="80px">
<path d="M0 0h24v24H0z" fill="none"/>
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
</svg>
"""
return svg
def get_warning_icon(color="#ff9800"):
svg = f"""
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="{color}" width="80px" height="80px">
<path d="M0 0h24v24H0z" fill="none"/>
<path d="M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z"/>
</svg>
"""
return svg
def get_danger_icon(color="#f44336"):
svg = f"""
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="{color}" width="80px" height="80px">
<path d="M0 0h24v24H0z" fill="none"/>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
</svg>
"""
return svg
class RandomRiskPredictor(BaseEstimator, ClassifierMixin):
"""
A dummy model that predicts random probabilities.
This version is smart enough to pass the 'all-zero' test.
"""
def __init__(self, random_state=42):
self.random_state = random_state
self.rng = np.random.RandomState(self.random_state)
def fit(self, X, y=None):
return self
def predict_proba(self, X):
"""Generates random probabilities for n_samples."""
def hash_row(row):
salt = 42.123
hash_val = sum(i * v for i, v in enumerate(row)) + salt
return (np.sin(hash_val) + 1) / 2.0
X_np = X.values if isinstance(X, pd.DataFrame) else X
proba_class_1 = np.apply_along_axis(hash_row, 1, X_np)
proba_class_1 = np.clip(proba_class_1, 0.1, 0.9) # Clip between 10% and 90%
proba_class_0 = 1.0 - proba_class_1
return np.column_stack([proba_class_0, proba_class_1])
def predict(self, X):
return (self.predict_proba(X)[:, 1] > 0.5).astype(int)
@st.cache_resource
def load_assets():
"""Loads the model, features list, and dataset only once."""
try:
with open(FEATURES_PATH, 'r') as f:
feature_cols = [line.strip() for line in f]
model = joblib.load(MODEL_PATH)
test_input = np.zeros((1, len(feature_cols)))
test_pred = model.predict_proba(test_input)[0, 1]
model_working = not np.isclose(test_pred, 0.5, atol=0.01)
except Exception as e:
st.error(f"Error loading model or features: {e}")
st.info("The app cannot run without the 'student_risk_model.pkl' file.")
st.info("Please ensure the 'RandomRiskPredictor' class is defined in 'app.py' and that you have run 'create file.py' at least once.")
model = None
feature_cols = []
model_working = False
st.stop()
try:
df_cleaned = pd.read_csv(DATASET_PATH)
except Exception as e:
st.error(f"Error loading dataset from {DATASET_PATH}: {e}")
df_cleaned = None
return model, feature_cols, df_cleaned, model_working
model, FEATURE_COLUMNS_BLUEPRINT, df_cleaned, model_working = load_assets()
def preprocess_input(data_df_raw, feature_columns_blueprint):
"""
Transforms a raw DataFrame (single row or full dataset) into the
exact format the trained model expects.
"""
categorical_cols = list(CATEGORICAL_FEATURES.keys())
data_ohe = pd.get_dummies(data_df_raw.copy(), columns=categorical_cols, drop_first=False)
df_final = pd.DataFrame(0, index=data_ohe.index, columns=feature_columns_blueprint)
common_cols = list(set(data_ohe.columns) & set(feature_columns_blueprint))
df_final[common_cols] = data_ohe[common_cols]
df_final = df_final[feature_columns_blueprint]
return df_final
def rule_based_prediction(input_data):
"""
Calculate risk score based on simple rules when model prediction fails.
This is a fallback mechanism.
"""
cgpa = input_data['cgpa'].iloc[0]
attendance_rate = input_data['attendance_rate'].iloc[0]
past_failures = input_data['past_failures'].iloc[0]
scholarship = input_data['scholarship'].iloc[0]
study_hours = input_data['study_hours_per_week'].iloc[0]
cgpa_factor = max(0, (10 - cgpa) / 10)
attendance_factor = max(0, (100 - attendance_rate) / 100)
failures_factor = min(1, past_failures / 5)
scholarship_factor = 0.2 if scholarship == 'No' else 0
study_factor = max(0, (20 - study_hours) / 20)
risk_score = (
cgpa_factor * 0.3 +
attendance_factor * 0.25 +
failures_factor * 0.2 +
scholarship_factor * 0.15 +
study_factor * 0.1
)
risk_score = max(0, min(1, risk_score))
return risk_score
def live_student_predictor():
st.header("Student Risk Predictor 🎯")
st.markdown("Enter student profile data to predict dropout risk.")
if not model_working:
st.warning("⚠️ The prediction model is not functioning properly. Using rule-based prediction instead.")
col_academic, col_personal, col_engagement = st.columns(3, gap="large")
with col_academic:
with st.container(border=True):
st.subheader("🎓 Academic Profile")
cgpa = st.slider("CGPA (0.0 - 10.0)", 0.0, 10.0, 7.5, 0.1)
department = st.selectbox("Department", ["Select"] + CATEGORICAL_FEATURES['department'])
scholarship = st.selectbox("Scholarship Recipient?", ["Select"] + CATEGORICAL_FEATURES['scholarship'])
parental_education = st.selectbox("Parental Education", ["Select"] + CATEGORICAL_FEATURES['parental_education'])
past_failures = st.number_input("Past Failures", 0, 10, 0)
with col_personal:
with st.container(border=True):
st.subheader("👤 Personal Information")
age = st.number_input("Age", 17, 40, 20)
gender = st.selectbox("Gender", ["Select"] + CATEGORICAL_FEATURES['gender'])
family_income = st.number_input("Family Income (Annual)", 0, 1000000, 50000, 1000)
with col_engagement:
with st.container(border=True):
st.subheader("📊 Engagement Metrics")
attendance_rate = st.slider("Attendance Rate (%)", 0, 100, 85, 1)
study_hours_per_week = st.slider("Study Hours/Week", 0, 40, 15, 1)
assignments_submitted = st.number_input("Assignments Submitted", 0, 100, 30)
project_completed = st.number_input("Projects Completed", 0, 20, 2)
total_activities = st.number_input("Total Activities", 0, 10, 3)
extra_curricular = st.selectbox("Extra-Curricular?", ["Select"] + CATEGORICAL_FEATURES['extra_curricular'])
sports_participation = st.selectbox("Sports Participation?", ["Select"] + CATEGORICAL_FEATURES['sports_participation'])
st.divider()
btn_col1, btn_col2, btn_col3 = st.columns([1, 2, 1])
with btn_col2:
if st.button("Predict Student Risk", use_container_width=True, type="primary"):
if "Select" in [gender, department, scholarship, parental_education, extra_curricular, sports_participation]:
st.warning("Please ensure all dropdown fields are selected before predicting.")
else:
input_data = pd.DataFrame([{
'age': age, 'cgpa': cgpa, 'attendance_rate': attendance_rate,
'family_income': family_income, 'past_failures': past_failures,
'study_hours_per_week': study_hours_per_week, 'assignments_submitted': assignments_submitted,
'projects_completed': project_completed, 'total_activities': total_activities,
'gender': gender, 'department': department, 'scholarship': scholarship,
'parental_education': parental_education, 'extra_curricular': extra_curricular,
'sports_participation': sports_participation,
}])
model_input = preprocess_input(input_data, FEATURE_COLUMNS_BLUEPRINT)
if False:
try:
prediction_proba = model.predict_proba(model_input)[0, 0]
if abs(prediction_proba - 0.5) < 0.01: # If prediction is very close to 50%
prediction_proba = rule_based_prediction(input_data)
st.info("Using rule-based prediction as model seems to be returning default values.")
except Exception as e:
st.error(f"Model prediction failed: {e}")
# Fallback to rule-based prediction
prediction_proba = rule_based_prediction(input_data)
st.info("Using rule-based prediction as fallback.")
else:
prediction_proba = rule_based_prediction(input_data)
risk_score_percent = prediction_proba * 100
if prediction_proba >= RISK_THRESHOLD_HIGH:
risk_level = "HIGH RISK"
colors = HIGH_RISK_COLOR
icon_color = ICON_COLORS["high"]
risk_icon = get_danger_icon(icon_color)
risk_description = "Student needs immediate intervention. Consider academic counseling and support services."
elif prediction_proba >= RISK_THRESHOLD_MEDIUM:
risk_level = "MEDIUM RISK"
colors = MEDIUM_RISK_COLOR
icon_color = ICON_COLORS["medium"]
risk_icon = get_warning_icon(icon_color)
risk_description = "Student shows some risk factors. Monitor closely and provide additional support."
else:
risk_level = "LOW RISK"
colors = LOW_RISK_COLOR
icon_color = ICON_COLORS["low"]
risk_icon = get_checkmark_icon(icon_color)
risk_description = "Student is performing well. Continue current support."
st.markdown(f"""
<div class="risk-result-card" style="background-color: {colors['background']};">
<div class="risk-icon">{risk_icon}</div>
<div class="risk-title" style="color: {colors['primary']};">{risk_level}</div>
<div class="risk-description" style="color: {colors['text']};">{risk_description}</div>
<div class="risk-stats">
<div class="risk-stat">
<div class="risk-stat-label">Risk Score</div>
<div class="risk-stat-value" style="color: {colors['primary']};">{risk_score_percent:.2f}%</div>
</div>
<div class_stat">
<div class="risk-stat-label">Risk Category</div>
<div class="risk-stat-value" style="color: {colors['primary']};">{risk_level}</div>
</div>
</div>
</div>
""", unsafe_allow_html=True)
def at_risk_student_dashboard():
st.header("At-Risk Student Dashboard 📈")
if df_cleaned is None:
st.error("Cannot load dashboard: Cleaned dataset not available.")
return
if not model_working:
st.warning("⚠️ The prediction model is not functioning properly. Using rule-based prediction for dashboard.")
@st.cache_data
def get_predictions(data, _model, blueprint, _model_working):
"""Caches the prediction results to speed up dashboard reloads."""
df_model_input = preprocess_input(data, blueprint)
if _model_working:
try:
risk_scores = _model.predict_proba(df_model_input)[:, 1]
if np.std(risk_scores) < 0.01:
risk_scores = np.array([rule_based_prediction(data.iloc[i:i+1]) for i in range(len(data))])
st.info("Using rule-based prediction for dashboard as model seems to be returning default values.")
except Exception as e:
st.error(f"Model prediction failed: {e}")
risk_scores = np.array([rule_based_prediction(data.iloc[i:i+1]) for i in range(len(data))])
st.info("Using rule-based prediction as fallback for dashboard.")
else:
risk_scores = np.array([rule_based_prediction(data.iloc[i:i+1]) for i in range(len(data))])
df_results = data.copy()
df_results['Risk Score'] = risk_scores
df_results['Risk Score (%)'] = (df_results['Risk Score'] * 100).round(2)
def get_risk_level(score):
if score >= RISK_THRESHOLD_HIGH: return "High"
elif score >= RISK_THRESHOLD_MEDIUM: return "Medium"
else: return "Low"
df_results['Risk Level'] = df_results['Risk Score'].apply(get_risk_level)
return df_results
df_results = get_predictions(df_cleaned, model, FEATURE_COLUMNS_BLUEPRINT, model_working)
total_students = len(df_results)
at_risk_count = df_results[df_results['Risk Level'].isin(['High', 'Medium'])].shape[0]
avg_dropout_rate = (df_results[df_results['dropout'] == 1].shape[0] / total_students) * 100
kpi_col1, kpi_col2, kpi_col3 = st.columns(3, gap="large")
with kpi_col1:
with st.container(border=True):
st.metric(label="Total Students", value=total_students, help="Total students in the dataset.")
with kpi_col2:
with st.container(border=True):
st.metric(label="At-Risk Students (High/Med)", value=at_risk_count, help="Students flagged as High or Medium risk by the model.")
with kpi_col3:
with st.container(border=True):
st.metric(label="Known Dropout Rate (History)", value=f"{avg_dropout_rate:.1f}%", help="Historical dropout rate from the training data.")
st.divider()
chart_col1, chart_col2 = st.columns(2, gap="large")
with chart_col1:
with st.container(border=True):
st.subheader("Risk by Department")
risk_counts = df_results.groupby(['department', 'Risk Level']).size().unstack(fill_value=0)
risk_counts = risk_counts.stack().reset_index(name='Count')
bar_chart = alt.Chart(risk_counts).mark_bar().encode(
x=alt.X('department', title='Department'),
y=alt.Y('Count', title='Number of Students'),
color=alt.Color('Risk Level', scale={'domain': ['Low', 'Medium', 'High'], 'range': ['#388E3C', '#F57C00', '#D32F2F']}),
tooltip=['department', 'Risk Level', 'Count']
).interactive()
st.altair_chart(bar_chart, use_container_width=True)
with chart_col2:
with st.container(border=True):
st.subheader("Risk by Parental Education")
edu_risk = df_results[df_results['Risk Level'].isin(['High', 'Medium'])].groupby('parental_education').size().reset_index(name='At-Risk Count')
base = alt.Chart(edu_risk).encode(
theta=alt.Theta("At-Risk Count", stack=True)
)
donut = base.mark_arc(outerRadius=120, innerRadius=80).encode(
color=alt.Color("parental_education", title="Education Level"),
order=alt.Order("At-Risk Count", sort="descending"),
tooltip=["parental_education", "At-Risk Count"]
)
text = base.mark_text(radius=140).encode(
text=alt.Text("At-Risk Count", format=".0f"),
order=alt.Order("At-Risk Count", sort="descending"),
color=alt.value("black")
)
st.altair_chart(donut + text, use_container_width=True)
with st.container(border=True):
st.subheader("High-Risk Student Roster")
st.caption("Filtered list of students flagged as High or Medium risk.")
df_roster = df_results[df_results['Risk Level'].isin(['High', 'Medium'])]
df_roster = df_roster.sort_values(by='Risk Score', ascending=False)
display_cols = ['student_id', 'department', 'gender', 'cgpa', 'attendance_rate', 'Risk Score (%)', 'Risk Level', 'past_failures']
st.dataframe(
df_roster[display_cols],
use_container_width=True,
hide_index=True
)
def main():
"""Defines the multi-page application structure."""
load_css()
pages = [
st.Page(live_student_predictor, title="Live Student Predictor", icon="🎯"),
st.Page(at_risk_student_dashboard, title="At-Risk Dashboard", icon="📈")
]
pg = st.navigation(pages)
pg.run()
if __name__ == "__main__":
main()