Download app.py from Mariamyasser/desertification-forecasting-api: direct link, hf CLI and curl.
- Browser
- Download file 1.98 kB
-
https://huggingface.co/spaces/Mariamyasser/desertification-forecasting-api/resolve/main/app.py
- Command line
-
hf download hf://spaces/Mariamyasser/desertification-forecasting-api/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Mariamyasser/desertification-forecasting-api/resolve/main/app.py
1.98 kB
| import numpy as np | |
| import pandas as pd | |
| import joblib | |
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel | |
| from typing import List, Dict | |
| 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 | |
| # ----------------------------------------- | |
| # Import الكود بتاعك للموديل (forecasting + classification) | |
| # ------------------------------------------------- | |
| from desertification_forecasting import ( | |
| run_pipeline, DYNAMIC_FEATURES, STATIC_FEATURES | |
| ) | |
| # ----------------------------------------- | |
| # Load models | |
| # ------------------------------------------------- | |
| forecast_models = { | |
| f: joblib.load(f"xgb_forecast_{f}.pkl") | |
| for f in DYNAMIC_FEATURES | |
| } | |
| cls_model = joblib.load("xgb_desertification_pipeline.pkl") | |
| label_encoder = joblib.load("label_encoder.pkl") | |
| feature_order = joblib.load("feature_names.pkl") | |
| # ----------------------------------------- | |
| # FastAPI app | |
| # ------------------------------------------------- | |
| app = FastAPI(title="Desertification Forecast API") | |
| class PayloadItem(BaseModel): | |
| metadata: Dict | |
| features: Dict | |
| class ForecastPayload(BaseModel): | |
| data: List[PayloadItem] | |
| def predict(payload: ForecastPayload): | |
| try: | |
| result = run_pipeline( | |
| [item.dict() for item in payload.data] | |
| ) | |
| return result | |
| except Exception as e: | |
| raise HTTPException(status_code=400, detail=str(e)) | |