from fastapi import FastAPI from pydantic import BaseModel import pandas as pd import joblib from datetime import datetime import numpy as np from sklearn.base import BaseEstimator, TransformerMixin import sys class FeatureFilter(BaseEstimator, TransformerMixin): def __init__(self, expected_features): self.expected_features = expected_features def fit(self, X, y=None): return self def transform(self, X): X = X.copy() X = X[[c for c in self.expected_features if c in X.columns]] for c in self.expected_features: if c not in X.columns: X[c] = np.nan return X[self.expected_features] # 🔥 السطر ده هو المفتاح sys.modules["__main__"].FeatureFilter = FeatureFilter # Load artifacts model = joblib.load("xgb_desertification_pipeline.pkl") label_encoder = joblib.load("label_encoder.pkl") expected_features = joblib.load("feature_names.pkl") app = FastAPI(title="Desertification Prediction API") class PredictionRequest(BaseModel): year: int month: int sand: float silt: float clay: float soc: float ph: float bdod: float cec: float ndvi: float t2m_c: float td2m_c: float rh_pct: float tp_m: float ssrd_jm2: float lc_type1: int nitrogen: float phosphorus: float potassium: float latitude: float longitude: float @app.get("/") def root(): return { "message": "Desertification Prediction API is running", "endpoint": "/predict", "method": "POST" } @app.post("/predict") def predict(request: PredictionRequest): data = request.dict() df = pd.DataFrame([data]) df = df[expected_features] pred_encoded = model.predict(df) pred_label = label_encoder.inverse_transform(pred_encoded)[0] confidence = model.predict_proba(df).max(axis=1)[0] return { "prediction": { "desertification_level": pred_label, "confidence": float(confidence) } }