Spaces:
Sleeping
Sleeping
| 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") | |
| 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> | |
| """ | |
| 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) | |
| } | |