File size: 2,537 Bytes
9df094d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# ====================================================
# 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
# -----------------------------
@app.post("/predict")
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)