cloud450 commited on
Commit
52b3ad3
·
verified ·
1 Parent(s): 80b6a58

Upload main.py

Browse files
Files changed (1) hide show
  1. main.py +61 -0
main.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ )
61
+