Spaces:
Sleeping
Sleeping
| # ==================================================== | |
| # main.py - Diabetes Prediction API (Production) | |
| # ==================================================== | |
| from fastapi import FastAPI | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| import numpy as np | |
| import joblib | |
| # ----------------------------- | |
| # Load Trained Model & Scaler | |
| # ----------------------------- | |
| # Ensure these files are in the same directory as this script | |
| scaler = joblib.load("scaler.pkl") | |
| best_model = joblib.load("diabetes_model.pkl") | |
| # ----------------------------- | |
| # Initialize FastAPI app | |
| # ----------------------------- | |
| app = FastAPI( | |
| title="Diabetes Prediction API", | |
| description="Predicts diabetes based on patient data using trained ML model", | |
| version="1.0" | |
| ) | |
| # ----------------------------- | |
| # Enable CORS for all origins (for testing) | |
| # ----------------------------- | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], # Adjust for production to restrict origins | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # ----------------------------- | |
| # Define Input Data Model | |
| # ----------------------------- | |
| class InputData(BaseModel): | |
| Age: float | |
| Sex: float | |
| BMI: float | |
| Glucose: float | |
| BloodPressure: float | |
| Insulin: float | |
| Increased_Thirst: float | |
| Increased_Hunger: float | |
| Fatigue_Tiredness: float | |
| Blurred_Vision: float | |
| Unexplained_Weight_Loss: float | |
| # ----------------------------- | |
| # Prediction Endpoint | |
| # ----------------------------- | |
| def predict(data: InputData): | |
| # Convert input to numpy array | |
| features = np.array([[ | |
| data.Age, | |
| data.Sex, | |
| data.BMI, | |
| data.Glucose, | |
| data.BloodPressure, | |
| data.Insulin, | |
| data.Increased_Thirst, | |
| data.Increased_Hunger, | |
| data.Fatigue_Tiredness, | |
| data.Blurred_Vision, | |
| data.Unexplained_Weight_Loss | |
| ]]) | |
| # Scale the input features | |
| features_scaled = scaler.transform(features) | |
| # Make prediction | |
| prediction = best_model.predict(features_scaled)[0] | |
| # Map prediction to human-readable label | |
| result = "Diabetes" if prediction == 1 else "No Diabetes" | |
| return {"prediction": result} | |
| # ----------------------------- | |
| # Run the API locally (development only) | |
| # ----------------------------- | |
| if __name__ == "__main__": | |
| import uvicorn | |
| uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True) | |