Spaces:
Runtime error
Runtime error
Download app.py from radwaamr1/Desertification-Classification-API: direct link, hf CLI and curl.
- Browser
- Download file 1.56 kB
-
https://huggingface.co/spaces/radwaamr1/Desertification-Classification-API/resolve/main/app.py
- Command line
-
hf download hf://spaces/radwaamr1/Desertification-Classification-API/app.py
-
curl -L -o app.py https://huggingface.co/spaces/radwaamr1/Desertification-Classification-API/resolve/main/app.py
1.56 kB
| from fastapi import FastAPI | |
| from pydantic import BaseModel | |
| import pandas as pd | |
| import joblib | |
| import numpy as np | |
| # ---------------------------- | |
| # Load pipeline and encoders | |
| # ---------------------------- | |
| xgb_pipe = joblib.load("xgb_desertification_pipeline.pkl") | |
| feature_names = joblib.load("feature_names.pkl") | |
| label_encoder = joblib.load("label_encoder.pkl") | |
| # ---------------------------- | |
| # FastAPI app | |
| # ---------------------------- | |
| app = FastAPI( | |
| title="Desertification Classification API", | |
| description="Predict desertification classes from input features.", | |
| version="1.0" | |
| ) | |
| # ---------------------------- | |
| # Input data model | |
| # ---------------------------- | |
| class PredictionRequest(BaseModel): | |
| features: dict # e.g., {"feature1": value1, "feature2": value2, ...} | |
| # ---------------------------- | |
| # Health check | |
| # ---------------------------- | |
| async def health_check(): | |
| return {"status": "healthy"} | |
| # ---------------------------- | |
| # Prediction endpoint | |
| # ---------------------------- | |
| async def predict(request: PredictionRequest): | |
| # Convert input to DataFrame | |
| try: | |
| df = pd.DataFrame([request.features], columns=feature_names) | |
| except Exception as e: | |
| return {"error": f"Invalid input features. {str(e)}"} | |
| # Predict | |
| try: | |
| pred_encoded = xgb_pipe.predict(df) | |
| pred_label = label_encoder.inverse_transform(pred_encoded) | |
| return {"prediction": pred_label[0]} | |
| except Exception as e: | |
| return {"error": f"Prediction failed. {str(e)}"} | |