Spaces:
Sleeping
Sleeping
Upload 8 files
Browse files
app.py
CHANGED
|
@@ -1,38 +1,59 @@
|
|
| 1 |
-
from fastapi import FastAPI
|
| 2 |
-
from fastapi.
|
| 3 |
-
import
|
| 4 |
-
import
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from fastapi.responses import HTMLResponse
|
| 3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
+
import joblib
|
| 5 |
+
import pandas as pd
|
| 6 |
+
|
| 7 |
+
app = FastAPI()
|
| 8 |
+
|
| 9 |
+
app.add_middleware(
|
| 10 |
+
CORSMiddleware,
|
| 11 |
+
allow_origins=["*"], # Allows all origins
|
| 12 |
+
allow_credentials=True,
|
| 13 |
+
allow_methods=["*"], # Allows all methods
|
| 14 |
+
allow_headers=["*"], # Allows all headers
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# Load models once at startup
|
| 18 |
+
future_spend_model = joblib.load("future_spend_7d.pkl")
|
| 19 |
+
spike_model = joblib.load("spike_probability.pkl")
|
| 20 |
+
acc_model = joblib.load("acceleration.pkl")
|
| 21 |
+
FEATURES = joblib.load("model_features.pkl")
|
| 22 |
+
|
| 23 |
+
@app.get("/", response_class=HTMLResponse)
|
| 24 |
+
def root():
|
| 25 |
+
return """
|
| 26 |
+
<!DOCTYPE html>
|
| 27 |
+
<html>
|
| 28 |
+
<head>
|
| 29 |
+
<title>ML Backend Status</title>
|
| 30 |
+
<style>
|
| 31 |
+
body { font-family: sans-serif; text-align: center; padding-top: 50px; background-color: #f0f2f5; }
|
| 32 |
+
h1 { color: #333; }
|
| 33 |
+
.status { color: green; font-weight: bold; }
|
| 34 |
+
a { text-decoration: none; color: white; background-color: #007bff; padding: 10px 20px; border-radius: 5px; }
|
| 35 |
+
a:hover { background-color: #0056b3; }
|
| 36 |
+
</style>
|
| 37 |
+
</head>
|
| 38 |
+
<body>
|
| 39 |
+
<h1>ML Backend is <span class="status">RUNNING</span></h1>
|
| 40 |
+
<p>The API is active and ready to accept requests.</p>
|
| 41 |
+
<br>
|
| 42 |
+
<a href="/docs">View API Documentation</a>
|
| 43 |
+
</body>
|
| 44 |
+
</html>
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
@app.post("/predict")
|
| 48 |
+
def predict(payload: dict):
|
| 49 |
+
X = pd.DataFrame([payload], columns=FEATURES)
|
| 50 |
+
|
| 51 |
+
future_spend = future_spend_model.predict(X)[0]
|
| 52 |
+
spike_prob = spike_model.predict_proba(X)[0][1]
|
| 53 |
+
acceleration = acc_model.predict(X)[0]
|
| 54 |
+
|
| 55 |
+
return {
|
| 56 |
+
"future_7d_spend": round(float(future_spend), 2),
|
| 57 |
+
"spike_probability": round(float(spike_prob), 3),
|
| 58 |
+
"acceleration": round(float(acceleration), 2)
|
| 59 |
+
}
|