radwaamr1 commited on
Commit
894e34d
·
verified ·
1 Parent(s): ffccef2

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +46 -55
  2. requirements.txt +7 -6
app.py CHANGED
@@ -1,62 +1,53 @@
1
- # app.py
2
-
3
- import gradio as gr
4
  import pandas as pd
5
  import joblib
6
  import numpy as np
7
- from sklearn.base import BaseEstimator, TransformerMixin
8
-
9
- # -------------------------------
10
- # Define custom class BEFORE loading
11
- # -------------------------------
12
- class FeatureFilter(BaseEstimator, TransformerMixin):
13
- def __init__(self, expected_features):
14
- self.expected_features = expected_features
15
-
16
- def fit(self, X, y=None):
17
- return self
18
-
19
- def transform(self, X):
20
- X = X.copy()
21
- # Keep only expected features
22
- X = X[[c for c in self.expected_features if c in X.columns]]
23
- # Add missing columns with NaN
24
- for c in self.expected_features:
25
- if c not in X.columns:
26
- X[c] = np.nan
27
- return X[self.expected_features]
28
 
29
- # -------------------------------
30
- # Load artifacts
31
- # -------------------------------
32
  xgb_pipe = joblib.load("xgb_desertification_pipeline.pkl")
33
- le = joblib.load("label_encoder.pkl")
34
- expected_features = joblib.load("feature_names.pkl")
35
-
36
- # -------------------------------
37
- # Prediction function
38
- # -------------------------------
39
- def predict_desertification(**kwargs):
40
- df = pd.DataFrame([kwargs])
41
- df = df[expected_features] # reorder columns
42
- pred_encoded = xgb_pipe.predict(df)
43
- pred_label = le.inverse_transform(pred_encoded)
44
- pred_proba = xgb_pipe.predict_proba(df).max(axis=1)
45
- return {
46
- "Desertification Level": pred_label[0],
47
- "Confidence": float(pred_proba[0])
48
- }
49
-
50
- # -------------------------------
51
- # Gradio interface
52
- # -------------------------------
53
- inputs = [gr.Number(label=f, value=0.0) for f in expected_features]
54
-
55
- demo = gr.Interface(
56
- fn=predict_desertification,
57
- inputs=inputs,
58
- outputs="json",
59
- title="Desertification Level Predictor"
60
  )
61
 
62
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ from pydantic import BaseModel
 
3
  import pandas as pd
4
  import joblib
5
  import numpy as np
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
+ # ----------------------------
8
+ # Load pipeline and encoders
9
+ # ----------------------------
10
  xgb_pipe = joblib.load("xgb_desertification_pipeline.pkl")
11
+ feature_names = joblib.load("feature_names.pkl")
12
+ label_encoder = joblib.load("label_encoder.pkl")
13
+
14
+ # ----------------------------
15
+ # FastAPI app
16
+ # ----------------------------
17
+ app = FastAPI(
18
+ title="Desertification Classification API",
19
+ description="Predict desertification classes from input features.",
20
+ version="1.0"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  )
22
 
23
+ # ----------------------------
24
+ # Input data model
25
+ # ----------------------------
26
+ class PredictionRequest(BaseModel):
27
+ features: dict # e.g., {"feature1": value1, "feature2": value2, ...}
28
+
29
+ # ----------------------------
30
+ # Health check
31
+ # ----------------------------
32
+ @app.get("/health")
33
+ async def health_check():
34
+ return {"status": "healthy"}
35
+
36
+ # ----------------------------
37
+ # Prediction endpoint
38
+ # ----------------------------
39
+ @app.post("/predict")
40
+ async def predict(request: PredictionRequest):
41
+ # Convert input to DataFrame
42
+ try:
43
+ df = pd.DataFrame([request.features], columns=feature_names)
44
+ except Exception as e:
45
+ return {"error": f"Invalid input features. {str(e)}"}
46
+
47
+ # Predict
48
+ try:
49
+ pred_encoded = xgb_pipe.predict(df)
50
+ pred_label = label_encoder.inverse_transform(pred_encoded)
51
+ return {"prediction": pred_label[0]}
52
+ except Exception as e:
53
+ return {"error": f"Prediction failed. {str(e)}"}
requirements.txt CHANGED
@@ -1,6 +1,7 @@
1
- gradio
2
- pandas
3
- numpy
4
- scikit-learn
5
- xgboost
6
- joblib
 
 
1
+ fastapi==0.104.1
2
+ uvicorn==0.24.0
3
+ scikit-learn==1.6.1
4
+ xgboost==3.1.2
5
+ pandas==2.3.3
6
+ numpy==1.26.4
7
+ joblib==1.3.2