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)}"}