File size: 2,032 Bytes
ead223c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
679d410
 
 
 
 
 
 
 
ead223c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
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)
        }
    }