Spaces:
Sleeping
Sleeping
| # main.py — FastAPI model service | |
| # Run: uvicorn main:app --reload | |
| # Requires: pip install fastapi uvicorn pydantic joblib pandas | |
| from fastapi import FastAPI | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| from typing import List, Dict, Any | |
| import pandas as pd | |
| import joblib | |
| import os | |
| # Path to your saved pipeline from the notebook | |
| MODEL_PATH = os.getenv("MODEL_PATH", "diabetes_prediction_model_20251007.pkl") | |
| pipe = joblib.load(MODEL_PATH) | |
| # Feature schema expected by the pipeline (must match training) | |
| NUMERIC_FEATURES = ['age','alcohol_consumption_per_week', 'physical_activity_minutes_per_week', | |
| 'diet_score', 'bmi', 'cholesterol_total', 'insulin_level', 'map', 'glucose_fasting'] | |
| CATEGORICAL_FEATURES = ['gender', 'ethnicity', 'education_level', 'income_level', 'employment_status', | |
| 'smoking_status', 'family_history_diabetes', 'hypertension_history', 'cardiovascular_history'] | |
| ALL_FEATURES = NUMERIC_FEATURES + CATEGORICAL_FEATURES | |
| class Batch(BaseModel): | |
| data: List[Dict[str, Any]] | |
| app = FastAPI() | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], allow_credentials=True, | |
| allow_methods=["*"], allow_headers=["*"], | |
| ) | |
| def health(): | |
| return {"status": "ok"} | |
| def features(): | |
| return {"features": ALL_FEATURES} | |
| def predict_batch(batch: Batch): | |
| X = pd.DataFrame(batch.data) | |
| # Ensure all expected columns exist | |
| for col in ALL_FEATURES: | |
| if col not in X.columns: | |
| X[col] = 0 | |
| # Reorder and type-hints (numerics safe-cast, categoricals to str) | |
| X = X[ALL_FEATURES].copy() | |
| for col in NUMERIC_FEATURES: | |
| X[col] = pd.to_numeric(X[col], errors="coerce").fillna(0) | |
| for col in CATEGORICAL_FEATURES: | |
| X[col] = X[col].astype(str).fillna("Unknown") | |
| probs = pipe.predict_proba(X)[:, 1].tolist() | |
| return {"probabilities": probs} |