# ==================================================== # 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 import os # ----------------------------- # Load Trained Model & Scaler # ----------------------------- MODEL_FILE = "diabetes_model.pkl" SCALER_FILE = "scaler.pkl" if not os.path.exists(MODEL_FILE) or not os.path.exists(SCALER_FILE): raise FileNotFoundError("Model or scaler file not found. Make sure both exist in the same directory.") scaler = joblib.load(SCALER_FILE) best_model = joblib.load(MODEL_FILE) # ----------------------------- # 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 # ----------------------------- app.add_middleware( CORSMiddleware, allow_origins=["*"], # For production, replace '*' with allowed domains 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 # ----------------------------- @app.post("/predict") def predict(data: InputData): try: # 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 features features_scaled = scaler.transform(features) # Predict prediction = best_model.predict(features_scaled)[0] result = "Diabetes" if prediction == 1 else "No Diabetes" return {"prediction": result} except Exception as e: return {"error": str(e)} # ----------------------------- # Run the API locally # ----------------------------- if __name__ == "__main__": import uvicorn uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True)