ml / main.py
mk6783336's picture
Upload 7 files
8117f1e verified
# FILE: main.py
# Install requirements first:
# pip install fastapi uvicorn scikit-learn joblib numpy
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import joblib
import numpy as np
# 1. Initialize the App
app = FastAPI(title="Diabetes Prediction API", version="1.0.0")
# Enable CORS for Flutter app
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# 2. Load the Trained Model
# (Ensure the .pkl file is in the same folder)
model = joblib.load('diabetes_model_professional.pkl')
# 3. Define the Data Structure (Input Validation)
class PatientData(BaseModel):
pregnancies: int
glucose: float
blood_pressure: float
skin_thickness: float
insulin: float
bmi: float
pedigree: float
age: int
@app.get("/")
def home():
return {"status": "online", "message": "Diabetes Prediction API is running"}
@app.post("/predict")
def predict_diabetes(data: PatientData):
# Prepare data for the model
features = [[
data.pregnancies,
data.glucose,
data.blood_pressure,
data.skin_thickness,
data.insulin,
data.bmi,
data.pedigree,
data.age
]]
# Get the raw probability (0 to 1)
probability = model.predict_proba(features)[0][1]
# APPLY THE PROFESSIONAL THRESHOLD (0.35)
# We use the lower threshold we discovered in your analysis to minimize missed cases
threshold = 0.35
is_diabetic = probability >= threshold
return {
"prediction": "Diabetic" if is_diabetic else "Healthy",
"risk_score": round(float(probability) * 100, 2), # Return as percentage
"risk_level": "High" if probability > 0.6 else "Moderate" if is_diabetic else "Low",
"alert": "Patient requires further clinical screening." if is_diabetic else "Patient appears healthy."
}
# To start: uvicorn main:app --reload --host 0.0.0.0