-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
366 lines (315 loc) · 11.4 KB
/
Copy pathapp.py
File metadata and controls
366 lines (315 loc) · 11.4 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# app.py
from flask import Flask, render_template, request, jsonify
from flask.views import MethodView
import pickle
import numpy as np
from diabetes_dataset import DiabetesDataset
from svm_model import SVMModel
import sys
import traceback
app = Flask(__name__)
# Load and train the best model (SVM - 98.7% accuracy)
try:
print("Loading dataset...", flush=True)
dataset = DiabetesDataset('diabetes.csv')
dataset.load_data()
print("Dataset loaded, preprocessing...", flush=True)
dataset.preprocess()
print("Dataset preprocessed", flush=True)
print("Training SVM model...", flush=True)
model = SVMModel()
model.train(dataset.X_train, dataset.y_train)
print("Model trained successfully", flush=True)
scaler = dataset.scaler
except Exception as e:
print(f"Error during initialization: {e}", flush=True)
traceback.print_exc()
sys.exit(1)
class IndexView(MethodView):
def get(self):
webpage = WebPage()
return webpage.render()
# Register the class-based view
app.add_url_rule('/', view_func=IndexView.as_view('index'))
class WebPage:
def __init__(self):
self.html_content = """
<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Diabetes Prediction System</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.container {
background: white;
border-radius: 10px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
padding: 40px;
max-width: 600px;
width: 100%;
}
h1 {
color: #333;
margin-bottom: 10px;
text-align: center;
}
.subtitle {
color: #666;
text-align: center;
margin-bottom: 30px;
font-size: 14px;
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 5px;
color: #333;
font-weight: 500;
font-size: 14px;
}
input {
width: 100%;
padding: 12px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 14px;
transition: border-color 0.3s;
}
input:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 5px rgba(102, 126, 234, 0.3);
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 15px;
}
button {
width: 100%;
padding: 12px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
border-radius: 5px;
font-size: 16px;
font-weight: bold;
cursor: pointer;
transition: transform 0.2s;
margin-top: 20px;
}
button:hover {
transform: translateY(-2px);
box-shadow: 0 10px 20px rgba(102, 126, 234, 0.4);
}
button:active {
transform: translateY(0);
}
.result {
margin-top: 30px;
padding: 20px;
border-radius: 5px;
text-align: center;
display: none;
}
.result.show {
display: block;
}
.result.high-risk {
background: #fee;
border: 2px solid #f44;
color: #c33;
}
.result.low-risk {
background: #efe;
border: 2px solid #4f4;
color: #3c3;
}
.result h2 {
font-size: 24px;
margin-bottom: 10px;
}
.confidence {
font-size: 14px;
margin-top: 10px;
opacity: 0.8;
}
.loading {
display: none;
text-align: center;
color: #667eea;
}
.spinner {
border: 3px solid #f3f3f3;
border-top: 3px solid #667eea;
border-radius: 50%;
width: 30px;
height: 30px;
animation: spin 1s linear infinite;
margin: 0 auto 10px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div class="container">
<h1>🏥 Diabetes Prediction System</h1>
<p class="subtitle">Enter patient health data to predict diabetes risk</p>
<form id="predictionForm">
<div class="form-row">
<div class="form-group">
<label for="pregnancies">Pregnancies</label>
<input type="number" id="pregnancies" name="pregnancies" min="0" step="1" required>
</div>
<div class="form-group">
<label for="glucose">Glucose (mg/dL)</label>
<input type="number" id="glucose" name="glucose" min="0" step="0.1" required>
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="blood_pressure">Blood Pressure (mmHg)</label>
<input type="number" id="blood_pressure" name="blood_pressure" min="0" step="0.1" required>
</div>
<div class="form-group">
<label for="skin_thickness">Skin Thickness (mm)</label>
<input type="number" id="skin_thickness" name="skin_thickness" min="0" step="0.1" required>
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="insulin">Insulin (mu U/ml)</label>
<input type="number" id="insulin" name="insulin" min="0" step="0.1" required>
</div>
<div class="form-group">
<label for="bmi">BMI (kg/m²)</label>
<input type="number" id="bmi" name="bmi" min="0" step="0.1" required>
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="diabetes_pedigree">Diabetes Pedigree</label>
<input type="number" id="diabetes_pedigree" name="diabetes_pedigree" min="0" step="0.001" required>
</div>
<div class="form-group">
<label for="age">Age (years)</label>
<input type="number" id="age" name="age" min="0" step="1" required>
</div>
</div>
<button type="submit">🔍 Predict Diabetes Risk</button>
</form>
<div class="loading" id="loading">
<div class="spinner"></div>
<p>Analyzing patient data...</p>
</div>
<div class="result" id="result"></div>
</div>
<script>
document.getElementById('predictionForm').addEventListener('submit', async (e) => {
e.preventDefault();
const loading = document.getElementById('loading');
const result = document.getElementById('result');
loading.style.display = 'block';
result.classList.remove('show');
const formData = {
pregnancies: document.getElementById('pregnancies').value,
glucose: document.getElementById('glucose').value,
blood_pressure: document.getElementById('blood_pressure').value,
skin_thickness: document.getElementById('skin_thickness').value,
insulin: document.getElementById('insulin').value,
bmi: document.getElementById('bmi').value,
diabetes_pedigree: document.getElementById('diabetes_pedigree').value,
age: document.getElementById('age').value
};
try {
const response = await fetch('/predict', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
});
const data = await response.json();
if (response.ok) {
const riskClass = data.prediction === 1 ? 'high-risk' : 'low-risk';
result.innerHTML = `
<h2>${data.risk}</h2>
<p>Confidence: ${data.confidence}%</p>
<div class="confidence">
${data.prediction === 1
? '⚠️ Patient shows indicators of diabetes. Medical consultation recommended.'
: '✅ Patient appears to have low diabetes risk based on provided data.'}
</div>
`;
result.className = `result show ${riskClass}`;
} else {
result.innerHTML = `<h2>Error</h2><p>${data.error}</p>`;
result.className = 'result show';
}
} catch (error) {
result.innerHTML = `<h2>Error</h2><p>${error.message}</p>`;
result.className = 'result show';
} finally {
loading.style.display = 'none';
}
});
</script>
</body>
</html>
"""
def render(self):
return self.html_content
@app.route('/predict', methods=['POST'])
def predict():
try:
data = request.json
# Extract patient data (8 features for diabetes dataset)
features = np.array([[
float(data['pregnancies']),
float(data['glucose']),
float(data['blood_pressure']),
float(data['skin_thickness']),
float(data['insulin']),
float(data['bmi']),
float(data['diabetes_pedigree']),
float(data['age'])
]])
# Scale the features
scaled_features = scaler.transform(features)
# Make prediction
prediction = model.model.predict(scaled_features)[0]
probability = model.model.decision_function(scaled_features)[0]
# Convert to confidence percentage (0-100%)
from scipy.special import expit
confidence = round(expit(probability) * 100, 2)
result = {
'prediction': int(prediction),
'risk': 'High Risk' if prediction == 1 else 'Low Risk',
'confidence': confidence
}
return jsonify(result)
except Exception as e:
return jsonify({'error': str(e)}), 400
if __name__ == '__main__':
app.run(debug=True, port=5000)