Spaces:
Sleeping
Sleeping
| from flask import Flask, request, jsonify, render_template | |
| import joblib | |
| import pandas as pd | |
| import numpy as np | |
| import os | |
| app = Flask(__name__) | |
| MODEL_PATH = "model.pkl" | |
| def load_model(): | |
| try: | |
| return joblib.load(MODEL_PATH) | |
| except Exception as e: | |
| print(f"[WARN] Could not load model: {e}") | |
| return None | |
| model = load_model() | |
| def index(): | |
| return render_template("index.html") | |
| def predict(): | |
| try: | |
| data = request.get_json() | |
| study = float(data.get("study_hours_per_day", 4)) | |
| phone = float(data.get("phone_usage_hours", 3)) | |
| social = float(data.get("social_media_hours", 2)) | |
| sleep = float(data.get("sleep_hours", 7)) | |
| notif = float(data.get("notifications", 50)) | |
| # Social can't exceed phone time | |
| social = min(social, phone) | |
| # Derive stress_level from notifications (1-10 scale) | |
| stress_level = min(10, max(1, round(notif / 20))) | |
| features = pd.DataFrame( | |
| [[study, phone, social, sleep, stress_level]], | |
| columns=['study_hours_per_day','phone_usage_hours', | |
| 'social_media_hours','sleep_hours','stress_level'] | |
| ) | |
| if model: | |
| prediction = int(model.predict(features)[0]) | |
| else: | |
| prediction = 0 if phone > 7 else 1 | |
| score = ((phone * 6) + (social * 8) + (notif * 0.08)) / 2 | |
| score = round(max(0.0, min(100.0, score)), 1) | |
| risk = min(100.0, score + 10) if prediction == 0 else max(0.0, score - 10) | |
| risk = round(risk, 1) | |
| productivity = round(max(0.0, min(100.0, 100 - score + (study * 2))), 1) | |
| return jsonify({ | |
| "prediction": prediction, | |
| "is_focused": prediction == 1, | |
| "score": score, | |
| "risk": risk, | |
| "productivity": productivity, | |
| "inputs": { | |
| "study": study, "phone": phone, "social": social, | |
| "sleep": sleep, "notifications": notif, "stress_level": stress_level | |
| } | |
| }) | |
| except Exception as e: | |
| return jsonify({"error": str(e)}), 400 | |
| if __name__ == "__main__": | |
| port = int(os.environ.get("PORT", 7860)) | |
| app.run(debug=False, host="0.0.0.0", port=port) | |