Spaces:
Runtime error
Runtime error
File size: 1,560 Bytes
894e34d 7ed4e27 894e34d ffccef2 894e34d 7ed4e27 894e34d | 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 | from fastapi import FastAPI
from pydantic import BaseModel
import pandas as pd
import joblib
import numpy as np
# ----------------------------
# Load pipeline and encoders
# ----------------------------
xgb_pipe = joblib.load("xgb_desertification_pipeline.pkl")
feature_names = joblib.load("feature_names.pkl")
label_encoder = joblib.load("label_encoder.pkl")
# ----------------------------
# FastAPI app
# ----------------------------
app = FastAPI(
title="Desertification Classification API",
description="Predict desertification classes from input features.",
version="1.0"
)
# ----------------------------
# Input data model
# ----------------------------
class PredictionRequest(BaseModel):
features: dict # e.g., {"feature1": value1, "feature2": value2, ...}
# ----------------------------
# Health check
# ----------------------------
@app.get("/health")
async def health_check():
return {"status": "healthy"}
# ----------------------------
# Prediction endpoint
# ----------------------------
@app.post("/predict")
async def predict(request: PredictionRequest):
# Convert input to DataFrame
try:
df = pd.DataFrame([request.features], columns=feature_names)
except Exception as e:
return {"error": f"Invalid input features. {str(e)}"}
# Predict
try:
pred_encoded = xgb_pipe.predict(df)
pred_label = label_encoder.inverse_transform(pred_encoded)
return {"prediction": pred_label[0]}
except Exception as e:
return {"error": f"Prediction failed. {str(e)}"}
|