Spaces:
Runtime error
Runtime error
Download app.py from radwaamr1/DesertificationClassification-API: direct link, hf CLI and curl.
- Browser
- Download file 2.2 kB
-
https://huggingface.co/spaces/radwaamr1/DesertificationClassification-API/resolve/main/app.py
- Command line
-
hf download hf://spaces/radwaamr1/DesertificationClassification-API/app.py
-
curl -L -o app.py https://huggingface.co/spaces/radwaamr1/DesertificationClassification-API/resolve/main/app.py
2.2 kB
| # app.py | |
| import gradio as gr | |
| import pandas as pd | |
| import joblib | |
| import numpy as np | |
| from sklearn.base import BaseEstimator, TransformerMixin | |
| # ------------------------------- | |
| # Load saved artifacts | |
| # ------------------------------- | |
| xgb_pipe = joblib.load("xgb_desertification_pipeline.pkl") | |
| le = joblib.load("label_encoder.pkl") | |
| expected_features = joblib.load("feature_names.pkl") | |
| # ------------------------------- | |
| # FeatureFilter class | |
| # ------------------------------- | |
| # Needed in case it's part of the pipeline | |
| 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() | |
| # Keep only expected features | |
| X = X[[c for c in self.expected_features if c in X.columns]] | |
| # Add missing columns with NaN | |
| for c in self.expected_features: | |
| if c not in X.columns: | |
| X[c] = np.nan | |
| return X[self.expected_features] | |
| # ------------------------------- | |
| # Prediction function | |
| # ------------------------------- | |
| def predict_desertification(**kwargs): | |
| # Convert inputs to DataFrame | |
| df = pd.DataFrame([kwargs]) | |
| df = df[expected_features] # reorder columns to match training | |
| # Predict | |
| pred_encoded = xgb_pipe.predict(df) | |
| pred_label = le.inverse_transform(pred_encoded) | |
| pred_proba = xgb_pipe.predict_proba(df).max(axis=1) | |
| return { | |
| "Desertification Level": pred_label[0], | |
| "Confidence": float(pred_proba[0]) | |
| } | |
| # ------------------------------- | |
| # Define Gradio interface | |
| # ------------------------------- | |
| # Separate categorical and numeric inputs if needed | |
| inputs = [] | |
| for feat in expected_features: | |
| if feat == "lc_type1": | |
| inputs.append(gr.Number(label=feat, value=0)) | |
| else: | |
| inputs.append(gr.Number(label=feat, value=0.0)) | |
| # Gradio app | |
| demo = gr.Interface( | |
| fn=predict_desertification, | |
| inputs=inputs, | |
| outputs="json", | |
| title="Desertification Level Predictor", | |
| description="Predict desertification level given soil, climate, and land cover features." | |
| ) | |
| # Launch | |
| demo.launch() | |