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)