cloud450 commited on
Commit
80b6a58
·
verified ·
1 Parent(s): 15c9168

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -29
app.py CHANGED
@@ -1,29 +1,60 @@
1
- from fastapi import FastAPI
2
- import joblib
3
- import pandas as pd
4
-
5
- app = FastAPI()
6
-
7
- # Load models once at startup
8
- future_spend_model = joblib.load("future_spend_7d.pkl")
9
- spike_model = joblib.load("spike_probability.pkl")
10
- acc_model = joblib.load("acceleration.pkl")
11
- FEATURES = joblib.load("model_features.pkl")
12
-
13
- @app.get("/")
14
- def root():
15
- return {"status": "ML backend running"}
16
-
17
- @app.post("/predict")
18
- def predict(payload: dict):
19
- X = pd.DataFrame([payload], columns=FEATURES)
20
-
21
- future_spend = future_spend_model.predict(X)[0]
22
- spike_prob = spike_model.predict_proba(X)[0][1]
23
- acceleration = acc_model.predict(X)[0]
24
-
25
- return {
26
- "future_7d_spend": round(float(future_spend), 2),
27
- "spike_probability": round(float(spike_prob), 3),
28
- "acceleration": round(float(acceleration), 2)
29
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, HTTPException
2
+ import joblib
3
+ import pandas as pd
4
+ from typing import Dict
5
+
6
+ app = FastAPI(
7
+ title="Spending Risk ML Backend",
8
+ description="Predicts future spend, spike risk, and spending acceleration",
9
+ version="1.0.0"
10
+ )
11
+
12
+ # -----------------------------
13
+ # Load models ONCE at startup
14
+ # -----------------------------
15
+ try:
16
+ future_spend_model = joblib.load("future_spend_7d.pkl")
17
+ spike_model = joblib.load("spike_probability.pkl")
18
+ acceleration_model = joblib.load("acceleration.pkl")
19
+ FEATURES = joblib.load("model_features.pkl")
20
+ except Exception as e:
21
+ raise RuntimeError(f"❌ Model loading failed: {e}")
22
+
23
+ # -----------------------------
24
+ # Health check (HF requirement)
25
+ # -----------------------------
26
+ @app.get("/")
27
+ def health_check():
28
+ return {
29
+ "status": "running",
30
+ "service": "spending-risk-backend"
31
+ }
32
+
33
+ # -----------------------------
34
+ # Prediction endpoint
35
+ # -----------------------------
36
+ @app.post("/predict")
37
+ def predict(payload: Dict):
38
+ try:
39
+ # 1. Build feature vector safely
40
+ # Missing features -> default 0
41
+ input_row = {feat: payload.get(feat, 0) for feat in FEATURES}
42
+ X = pd.DataFrame([input_row])
43
+
44
+ # 2. Predictions
45
+ future_spend = float(future_spend_model.predict(X)[0])
46
+ spike_prob = float(spike_model.predict_proba(X)[0][1])
47
+ acceleration = float(acceleration_model.predict(X)[0])
48
+
49
+ # 3. Response (frontend-friendly)
50
+ return {
51
+ "future_7d_spend": round(future_spend, 2),
52
+ "spike_probability": round(spike_prob, 3),
53
+ "acceleration": round(acceleration, 2)
54
+ }
55
+
56
+ except Exception as e:
57
+ raise HTTPException(
58
+ status_code=400,
59
+ detail=f"Prediction failed: {str(e)}"
60
+ )