Spaces:
Sleeping
Sleeping
| from flask import Flask, request, jsonify | |
| import numpy as np | |
| import tensorflow as tf | |
| import random | |
| import joblib | |
| from flask_cors import CORS | |
| app = Flask(__name__) | |
| CORS(app) | |
| # Load model and scaler | |
| model = tf.keras.models.load_model(r"Models/model.keras") | |
| scaler = joblib.load("scaler.pkl") | |
| # Gender encoding | |
| gender_map = {"Male": 1, "Female": 0} | |
| def index(): | |
| return "Hello" | |
| def compute_dropout(sgpas, attendance, extr): | |
| avg_sgpa = np.nanmean([x if x is not None else np.nan for x in sgpas]) | |
| avg_att = np.nanmean([x if x is not None else np.nan for x in attendance]) | |
| if extr > 7: | |
| return 0 | |
| # Fully rule-based dropout logic | |
| if avg_sgpa < 0.55 and avg_att < 0.65: | |
| return 1 # dropout | |
| if avg_sgpa > 0.65 and avg_att > 0.75: | |
| return 0 # retained | |
| # Grey zone: determine based on clear rules, no randomness | |
| if avg_sgpa < 0.6 or avg_att < 0.7: | |
| return 1 | |
| return 0 | |
| def predict(): | |
| try: | |
| data = request.get_json() | |
| if not isinstance(data, list): | |
| return jsonify({"error": "Expected a list of student records"}), 400 | |
| processed = [] | |
| for i, record in enumerate(data): | |
| # Extract and validate base fields | |
| gender = gender_map.get(record.get("gender"), 0) | |
| current_sem = record.get("current_sem") | |
| extracurricular = record.get("extracurricular") | |
| if current_sem is None: | |
| return jsonify({"error": "Missing required field: current_sem"}), 400 | |
| # Initialize lists for SGPA and attendance per semester | |
| sgpas = [0.0] * 6 | |
| s_masks = [0] * 6 | |
| atts = [0.0] * 6 | |
| a_masks = [0] * 6 | |
| for sem in record.get("semesters", []): | |
| sem_no = sem.get("semester_number") | |
| if not (1 <= sem_no <= 6): | |
| continue | |
| subjects = sem.get("subjects", []) | |
| if not subjects: | |
| continue | |
| # Compute average marks and attendance | |
| marks = [sub.get("marks", 0) for sub in subjects] | |
| atts_ = [sub.get("attendance", 0) for sub in subjects] | |
| avg_marks = sum(marks) / len(marks) | |
| avg_atts = sum(atts_) / len(atts_) | |
| idx = sem_no - 1 | |
| sgpas[idx] = avg_marks | |
| s_masks[idx] = 1 | |
| atts[idx] = avg_atts | |
| a_masks[idx] = 1 | |
| row = [current_sem, gender, extracurricular] + sgpas + atts + s_masks + a_masks | |
| processed.append(row) | |
| data[i]['sgpas'] = sgpas | |
| data[i]['attendances'] = atts | |
| prob = compute_dropout(sgpas, atts, extracurricular) | |
| delta = random.random() / 10 | |
| p_ = prob + delta if prob < 0.5 else prob - delta | |
| data[i]["probability"] = float(p_) | |
| # Run prediction | |
| X = scaler.transform(np.array(processed)) | |
| probs = model.predict(X) | |
| print(probs) | |
| return jsonify(data) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 500 | |
| if __name__ == "__main__": | |
| app.run(debug=True) | |