Spaces:
Runtime error
Runtime error
Upload app.py
Browse files
app.py
CHANGED
|
@@ -7,12 +7,37 @@ import numpy as np
|
|
| 7 |
from datetime import datetime
|
| 8 |
|
| 9 |
# =========================
|
| 10 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
# =========================
|
| 12 |
xgb_pipe = joblib.load("xgb_desertification_pipeline.pkl")
|
| 13 |
label_encoder = joblib.load("label_encoder.pkl")
|
| 14 |
expected_features = joblib.load("feature_names.pkl")
|
| 15 |
|
|
|
|
|
|
|
|
|
|
| 16 |
app = FastAPI(title="Desertification Prediction API")
|
| 17 |
|
| 18 |
# =========================
|
|
@@ -24,7 +49,7 @@ class PredictionRequest(BaseModel):
|
|
| 24 |
metadata: Dict[str, Any] | None = None
|
| 25 |
|
| 26 |
# =========================
|
| 27 |
-
# Health check
|
| 28 |
# =========================
|
| 29 |
@app.get("/health")
|
| 30 |
def health():
|
|
|
|
| 7 |
from datetime import datetime
|
| 8 |
|
| 9 |
# =========================
|
| 10 |
+
# Custom transformer used in pipeline
|
| 11 |
+
# =========================
|
| 12 |
+
from sklearn.base import BaseEstimator, TransformerMixin
|
| 13 |
+
|
| 14 |
+
class FeatureFilter(BaseEstimator, TransformerMixin):
|
| 15 |
+
def __init__(self, expected_features):
|
| 16 |
+
self.expected_features = expected_features
|
| 17 |
+
|
| 18 |
+
def fit(self, X, y=None):
|
| 19 |
+
return self
|
| 20 |
+
|
| 21 |
+
def transform(self, X):
|
| 22 |
+
X = X.copy()
|
| 23 |
+
# keep only expected features
|
| 24 |
+
X = X[[c for c in self.expected_features if c in X.columns]]
|
| 25 |
+
# add missing features as NaN
|
| 26 |
+
for c in self.expected_features:
|
| 27 |
+
if c not in X.columns:
|
| 28 |
+
X[c] = np.nan
|
| 29 |
+
return X[self.expected_features]
|
| 30 |
+
|
| 31 |
+
# =========================
|
| 32 |
+
# Load model artifacts
|
| 33 |
# =========================
|
| 34 |
xgb_pipe = joblib.load("xgb_desertification_pipeline.pkl")
|
| 35 |
label_encoder = joblib.load("label_encoder.pkl")
|
| 36 |
expected_features = joblib.load("feature_names.pkl")
|
| 37 |
|
| 38 |
+
# =========================
|
| 39 |
+
# FastAPI app
|
| 40 |
+
# =========================
|
| 41 |
app = FastAPI(title="Desertification Prediction API")
|
| 42 |
|
| 43 |
# =========================
|
|
|
|
| 49 |
metadata: Dict[str, Any] | None = None
|
| 50 |
|
| 51 |
# =========================
|
| 52 |
+
# Health check endpoint
|
| 53 |
# =========================
|
| 54 |
@app.get("/health")
|
| 55 |
def health():
|