File size: 2,596 Bytes
d07d826
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f1509c0
d07d826
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
91
92
93
94
95
import pandas as pd
import numpy as np
import os
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)

# Global variables 
model = None
scaler = None

# Initilize Model
def initialize_model():
    global model, scaler
    
    # Locate CSV File
    possible_paths = ["diabetes.csv", "src/diabetes.csv", "../diabetes.csv"]
    data_path = None
    for path in possible_paths:
        if os.path.exists(path):
            data_path = path
            break
            
    if not data_path:
        print("❌ CRITICAL: 'diabetes.csv' not found.")
        return

    # Load and Prepare Data
    try:
        df = pd.read_csv(data_path)
        X = df.drop('Outcome', axis=1)
        y = df['Outcome']
        
        # Scaling (Crucial for KNN)
        scaler = StandardScaler()
        X_scaled = scaler.fit_transform(X)
        
        # rain KNN Model
        X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
        model = KNeighborsClassifier(n_neighbors=9)
        model.fit(X_train, y_train)
        print("✅ Model trained successfully.")
        
    except Exception as e:
        print(f"❌ Error initializing model: {e}")

# Run initialization 
initialize_model()

# File Routes 

@app.route('/')
def home():
    return render_template('index.html')

@app.route('/predict', methods=['POST'])
def predict():
    if not model:
        return jsonify({'error': 'Model not loaded'}), 500

    try:
        data = request.json
        
        # Do not change the Order 
        input_features = [
            float(data['Pregnancies']),
            float(data['Glucose']),
            float(data['BloodPressure']),
            float(data['SkinThickness']),
            float(data['Insulin']),
            float(data['BMI']),
            float(data['DiabetesPedigreeFunction']),
            float(data['Age'])
        ]
        
        # Scale input
        features_scaled = scaler.transform([input_features])
        
        # Predict
        prediction = model.predict(features_scaled)
        prob = model.predict_proba(features_scaled)
        
        result = int(prediction[0])
        confidence = prob[0][result] * 100
        
        return jsonify({'prediction': result, 'confidence': confidence})

    except Exception as e:
        return jsonify({'error': str(e)}), 400

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7860)