File size: 1,984 Bytes
ffb9283
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
import joblib
import pandas as pd

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Allows all origins
    allow_credentials=True,
    allow_methods=["*"],  # Allows all methods
    allow_headers=["*"],  # Allows all headers
)

# Load models once at startup
future_spend_model = joblib.load("future_spend_7d.pkl")
spike_model = joblib.load("spike_probability.pkl")
acc_model = joblib.load("acceleration.pkl")
FEATURES = joblib.load("model_features.pkl")

@app.get("/", response_class=HTMLResponse)
def root():
    return """

    <!DOCTYPE html>

    <html>

        <head>

            <title>ML Backend Status</title>

            <style>

                body { font-family: sans-serif; text-align: center; padding-top: 50px; background-color: #f0f2f5; }

                h1 { color: #333; }

                .status { color: green; font-weight: bold; }

                a { text-decoration: none; color: white; background-color: #007bff; padding: 10px 20px; border-radius: 5px; }

                a:hover { background-color: #0056b3; }

            </style>

        </head>

        <body>

            <h1>ML Backend is <span class="status">RUNNING</span></h1>

            <p>The API is active and ready to accept requests.</p>

            <br>

            <a href="/docs">View API Documentation</a>

        </body>

    </html>

    """

@app.post("/predict")
def predict(payload: dict):
    X = pd.DataFrame([payload], columns=FEATURES)

    future_spend = future_spend_model.predict(X)[0]
    spike_prob = spike_model.predict_proba(X)[0][1]
    acceleration = acc_model.predict(X)[0]

    return {
        "future_7d_spend": round(float(future_spend), 2),
        "spike_probability": round(float(spike_prob), 3),
        "acceleration": round(float(acceleration), 2)
    }