tourism-deploy / app.py
singhina's picture
Upload app.py with huggingface_hub
6adbfc5 verified
import os
import xgboost as xgb
import pandas as pd
from fastapi import FastAPI
from pydantic import BaseModel
from typing import Dict, Any
from huggingface_hub import hf_hub_download
MODEL_REPO_ID = "singhina/tourism-tuned-model"
HF_TOKEN = os.environ.get("HF_TOKEN") # read token from Space secret
# Download model + features from HF Hub
model_file = hf_hub_download(repo_id=MODEL_REPO_ID, filename="best_xgb.json",
repo_type="model", token=HF_TOKEN)
features_file = hf_hub_download(repo_id=MODEL_REPO_ID, filename="features.txt",
repo_type="model", token=HF_TOKEN)
# Load ordered features
with open(features_file, "r") as f:
FEATURE_NAMES = [line.strip() for line in f if line.strip()]
# Load trained booster
booster = xgb.Booster()
booster.load_model(model_file)
app = FastAPI(title="Tourism Package Prediction API", version="1.0.0")
@app.get("/")
def root():
return {"ok": True, "message": "Tourism Purchase Predictor (XGBoost) is live."}
@app.get("/health")
def health():
return {"status": "healthy"}
class CustomerInput(BaseModel):
data: Dict[str, Any]
@app.post("/predict")
def predict(input: CustomerInput):
row = input.data
# Fill missing features with 0.0
full_row = {name: 0.0 for name in FEATURE_NAMES}
for k, v in row.items():
if k in full_row:
try:
full_row[k] = float(v)
except Exception:
full_row[k] = float(str(v).strip().lower() in ["true","1","yes"])
df = pd.DataFrame([full_row])[FEATURE_NAMES].astype(float)
dmat = xgb.DMatrix(df)
proba = float(booster.predict(dmat)[0])
pred = int(proba >= 0.5)
return {"probability": proba, "prediction": pred}