File size: 2,304 Bytes
a8315e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/predict", methods=["POST"])
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)