radwaamr1 commited on
Commit
36c46c3
·
verified ·
1 Parent(s): 20d48b6

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +65 -37
  2. requirements.txt +3 -4
app.py CHANGED
@@ -1,45 +1,73 @@
1
- from fastapi import FastAPI
2
- from pydantic import BaseModel
3
- from typing import Dict, Any
4
  import pandas as pd
5
  import joblib
6
- from datetime import datetime
 
7
 
8
- # Import custom class before loading the pipeline
9
- from custom import FeatureFilter
10
-
11
- # Load model artifacts
12
  xgb_pipe = joblib.load("xgb_desertification_pipeline.pkl")
13
- label_encoder = joblib.load("label_encoder.pkl")
14
  expected_features = joblib.load("feature_names.pkl")
15
 
16
- # FastAPI app
17
- app = FastAPI(title="Desertification Prediction API")
18
-
19
- # Input schema
20
- class PredictionRequest(BaseModel):
21
- success: bool
22
- features: Dict[str, Any]
23
- metadata: Dict[str, Any] | None = None
24
-
25
- # Health check endpoint
26
- @app.get("/health")
27
- def health():
28
- return {"status": "ok", "timestamp": datetime.now().isoformat()}
29
-
30
- # Prediction endpoint
31
- @app.post("/predict")
32
- def predict(request: PredictionRequest):
33
- input_df = pd.DataFrame([request.features])
34
- input_df = input_df.reindex(columns=expected_features)
35
- pred_encoded = xgb_pipe.predict(input_df)[0]
36
- pred_label = label_encoder.inverse_transform([pred_encoded])[0]
37
- pred_proba = float(xgb_pipe.predict_proba(input_df).max())
 
 
 
 
 
 
 
 
 
 
38
  return {
39
- "success": True,
40
- "prediction": {
41
- "desertification_level": pred_label,
42
- "confidence": round(pred_proba, 4)
43
- },
44
- "metadata": request.metadata
45
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ import gradio as gr
 
3
  import pandas as pd
4
  import joblib
5
+ import numpy as np
6
+ from sklearn.base import BaseEstimator, TransformerMixin
7
 
8
+ # -------------------------------
9
+ # Load saved artifacts
10
+ # -------------------------------
 
11
  xgb_pipe = joblib.load("xgb_desertification_pipeline.pkl")
12
+ le = joblib.load("label_encoder.pkl")
13
  expected_features = joblib.load("feature_names.pkl")
14
 
15
+ # -------------------------------
16
+ # FeatureFilter class
17
+ # -------------------------------
18
+ # Needed in case it's part of the pipeline
19
+ class FeatureFilter(BaseEstimator, TransformerMixin):
20
+ def __init__(self, expected_features):
21
+ self.expected_features = expected_features
22
+
23
+ def fit(self, X, y=None):
24
+ return self
25
+
26
+ def transform(self, X):
27
+ X = X.copy()
28
+ # Keep only expected features
29
+ X = X[[c for c in self.expected_features if c in X.columns]]
30
+ # Add missing columns with NaN
31
+ for c in self.expected_features:
32
+ if c not in X.columns:
33
+ X[c] = np.nan
34
+ return X[self.expected_features]
35
+
36
+ # -------------------------------
37
+ # Prediction function
38
+ # -------------------------------
39
+ def predict_desertification(**kwargs):
40
+ # Convert inputs to DataFrame
41
+ df = pd.DataFrame([kwargs])
42
+ df = df[expected_features] # reorder columns to match training
43
+ # Predict
44
+ pred_encoded = xgb_pipe.predict(df)
45
+ pred_label = le.inverse_transform(pred_encoded)
46
+ pred_proba = xgb_pipe.predict_proba(df).max(axis=1)
47
  return {
48
+ "Desertification Level": pred_label[0],
49
+ "Confidence": float(pred_proba[0])
 
 
 
 
50
  }
51
+
52
+ # -------------------------------
53
+ # Define Gradio interface
54
+ # -------------------------------
55
+ # Separate categorical and numeric inputs if needed
56
+ inputs = []
57
+ for feat in expected_features:
58
+ if feat == "lc_type1":
59
+ inputs.append(gr.Number(label=feat, value=0))
60
+ else:
61
+ inputs.append(gr.Number(label=feat, value=0.0))
62
+
63
+ # Gradio app
64
+ demo = gr.Interface(
65
+ fn=predict_desertification,
66
+ inputs=inputs,
67
+ outputs="json",
68
+ title="Desertification Level Predictor",
69
+ description="Predict desertification level given soil, climate, and land cover features."
70
+ )
71
+
72
+ # Launch
73
+ demo.launch()
requirements.txt CHANGED
@@ -1,7 +1,6 @@
1
- fastapi
2
- uvicorn
3
- scikit-learn
4
- xgboost
5
  pandas
6
  numpy
 
 
7
  joblib
 
1
+ gradio
 
 
 
2
  pandas
3
  numpy
4
+ scikit-learn
5
+ xgboost
6
  joblib