-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
486 lines (423 loc) · 19.9 KB
/
Copy pathapp.py
File metadata and controls
486 lines (423 loc) · 19.9 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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
from flask import Flask, render_template, request, redirect, url_for, flash, session, jsonify, send_from_directory
import numpy as np
import pandas as pd
import joblib
from sklearn.preprocessing import StandardScaler
from datetime import datetime
import os
import sqlite3
from sklearn.ensemble import RandomForestClassifier
app = Flask(__name__)
app.secret_key = 'your_secret_key'
# Load the diabetes prediction model and scaler
model = joblib.load('diabetes_model.pkl')
scaler = joblib.load('scaler.pkl')
# Load models for detailed health check
cardio_model = joblib.load('cardio_model.pkl')
nephropathy_model = joblib.load('nephropathy_model.pkl')
neuropathy_model = joblib.load('neuropathy_model.pkl')
retinopathy_model = joblib.load('retinopathy_model.pkl')
liver_model = joblib.load('liver_model.pkl')
# Initialize database
def init_db():
conn = sqlite3.connect('predictions.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS predictions
(id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT,
prediction INTEGER,
probability REAL,
features TEXT)''')
conn.commit()
conn.close()
init_db()
@app.route('/')
def home():
if os.path.exists(os.path.join(app.static_folder, 'react', 'index.html')):
return send_from_directory(os.path.join(app.static_folder, 'react'), 'index.html')
return render_template('input.html')
@app.route('/assets/<path:path>')
def serve_react_assets(path):
return send_from_directory(os.path.join(app.static_folder, 'react', 'assets'), path)
@app.route('/favicon.svg')
def serve_react_favicon():
return send_from_directory(os.path.join(app.static_folder, 'react'), 'favicon.svg')
@app.route('/icons.svg')
def serve_react_icons():
return send_from_directory(os.path.join(app.static_folder, 'react'), 'icons.svg')
@app.route('/predict', methods=['POST'])
def predict():
try:
# Extract features from form
features = [
float(request.form['glucose']),
float(request.form['blood_pressure']),
float(request.form['skin_thickness']),
float(request.form['insulin']),
float(request.form['bmi']),
float(request.form['waist_circumference']),
float(request.form['diabetes_pedigree']),
float(request.form['age'])
]
# Define normal ranges for each feature
normal_ranges = {
'glucose': {'min': 70, 'max': 140}, # Normal fasting glucose range
'blood_pressure': {'min': 60, 'max': 90}, # Normal diastolic BP range
'skin_thickness': {'min': 10, 'max': 50}, # Normal skin thickness range
'insulin': {'min': 20, 'max': 200}, # Normal insulin range
'bmi': {'min': 18.5, 'max': 24.9}, # Normal BMI range
'waist_circumference': {'min': 60, 'max': 100}, # Normal waist circumference range
'diabetes_pedigree': {'min': 0.1, 'max': 1.0}, # Normal pedigree function range
'age': {'min': 18, 'max': 65} # Normal age range for assessment
}
# Calculate risk score based on ranges
risk_score = 0
total_factors = len(features)
# Check each feature against normal ranges
for i, (feature_name, value) in enumerate(zip(normal_ranges.keys(), features)):
normal_min = normal_ranges[feature_name]['min']
normal_max = normal_ranges[feature_name]['max']
# Calculate how far the value is from normal range
if value < normal_min:
# Calculate risk based on how far below normal
deviation = (normal_min - value) / normal_min
risk_score += min(deviation, 1.0) # Cap at 1.0
elif value > normal_max:
# Calculate risk based on how far above normal
deviation = (value - normal_max) / normal_max
risk_score += min(deviation, 1.0) # Cap at 1.0
# Calculate average risk score
average_risk = risk_score / total_factors
# Scale features for model prediction
features_scaled = scaler.transform([features])
# Get model prediction
model_prediction = int(model.predict(features_scaled)[0])
model_probability = float(model.predict_proba(features_scaled)[0][1] * 100)
# Combine model prediction with range-based risk
if average_risk > 0.5 or model_probability > 60: # High risk if either condition is met
prediction = 1
probability = max(average_risk * 100, model_probability)
else:
prediction = 0
probability = min((1 - average_risk) * 100, 100 - model_probability)
# Save to database
conn = sqlite3.connect('predictions.db')
c = conn.cursor()
c.execute('INSERT INTO predictions (timestamp, prediction, probability, features) VALUES (?, ?, ?, ?)',
(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), prediction, probability, str(features)))
conn.commit()
conn.close()
# Render the result template with prediction and probability
return render_template('result.html',
prediction=prediction,
probability=round(probability, 2))
except Exception as e:
print(f"Error in predict route: {str(e)}") # Add debug logging
flash(f'Error: {str(e)}')
return redirect(url_for('home'))
@app.route('/result')
def result():
# Get the latest prediction from the database
conn = sqlite3.connect('predictions.db')
c = conn.cursor()
c.execute('SELECT prediction, probability FROM predictions ORDER BY timestamp DESC LIMIT 1')
result = c.fetchone()
conn.close()
if result:
prediction, probability = result
return render_template('result.html',
prediction=prediction,
probability=round(probability, 2))
else:
flash('No prediction results found')
return redirect(url_for('home'))
@app.route('/detailed-result')
def detailed_result():
# This route seems to be based on the detailed_predictions table, which we decided to remove for now.
# We will rely on the session for the latest detailed prediction results.
flash('This route is currently inactive.')
return redirect(url_for('detailed_check'))
@app.route('/detailed-check', methods=['GET'])
def detailed_check():
return render_template('detailed_check.html')
@app.route('/run-detailed-prediction', methods=['POST'])
def run_detailed_prediction():
print("=== Reached run_detailed_prediction route ===")
try:
# Extract features for each condition with default values of 0 for empty fields
cardio_features = [
float(request.form.get('chest_pain', 0)),
float(request.form.get('shortness_breath', 0)),
float(request.form.get('irregular_heartbeat', 0)),
float(request.form.get('swelling_legs', 0)),
float(request.form.get('fatigue', 0)),
float(request.form.get('blood_pressure', 0) or 0), # Handle empty string
float(request.form.get('cholesterol', 0) or 0) # Handle empty string
]
nephropathy_features = [
float(request.form.get('proteinuria', 0)),
float(request.form.get('swelling_ankles', 0)),
float(request.form.get('fatigue_neph', 0)),
float(request.form.get('nausea', 0)),
float(request.form.get('creatinine_level', 0) or 0), # Handle empty string
float(request.form.get('urine_output', 0) or 0) # Handle empty string
]
retinopathy_features = [
float(request.form.get('blurred_vision', 0)),
float(request.form.get('floaters', 0)),
float(request.form.get('dark_spots', 0)),
float(request.form.get('vision_loss', 0)),
float(request.form.get('eye_pain', 0)),
float(request.form.get('glucose_level', 0) or 0), # Handle empty string
float(request.form.get('duration_diabetes', 0) or 0) # Handle empty string
]
neuropathy_features = [
float(request.form.get('numbness', 0)),
float(request.form.get('tingling', 0)),
float(request.form.get('burning_pain', 0)),
float(request.form.get('muscle_weakness', 0)),
float(request.form.get('balance_problems', 0))
]
liver_features = [
float(request.form.get('abdominal_pain', 0)),
float(request.form.get('fatigue_liver', 0)),
float(request.form.get('nausea_liver', 0)),
float(request.form.get('jaundice', 0)),
float(request.form.get('swelling_abdomen', 0)),
float(request.form.get('ast_level', 0) or 0), # Handle empty string
float(request.form.get('alt_level', 0) or 0) # Handle empty string
]
# Make predictions for each condition
cardio_risk = int(cardio_model.predict([cardio_features])[0])
cardio_probability = float(cardio_model.predict_proba([cardio_features])[0][1] * 100)
nephropathy_risk = int(nephropathy_model.predict([nephropathy_features])[0])
nephropathy_probability = float(nephropathy_model.predict_proba([nephropathy_features])[0][1] * 100)
retinopathy_risk = int(retinopathy_model.predict([retinopathy_features])[0])
retinopathy_probability = float(retinopathy_model.predict_proba([retinopathy_features])[0][1] * 100)
neuropathy_risk = int(neuropathy_model.predict([neuropathy_features])[0])
neuropathy_probability = float(neuropathy_model.predict_proba([neuropathy_features])[0][1] * 100)
liver_risk = int(liver_model.predict([liver_features])[0])
liver_probability = float(liver_model.predict_proba([liver_features])[0][1] * 100)
# Store results in session
session['detailed_results'] = {
'cardio_risk': cardio_risk,
'cardio_probability': round(cardio_probability, 2),
'nephropathy_risk': nephropathy_risk,
'nephropathy_probability': round(nephropathy_probability, 2),
'retinopathy_risk': retinopathy_risk,
'retinopathy_probability': round(retinopathy_probability, 2),
'neuropathy_risk': neuropathy_risk,
'neuropathy_probability': round(neuropathy_probability, 2),
'liver_risk': liver_risk,
'liver_probability': round(liver_probability, 2)
}
# Redirect to the new view-last-detailed-report route
return redirect(url_for('view_last_detailed_report'))
except Exception as e:
import traceback
print("\n=== Error in run_detailed_prediction route ===")
traceback.print_exc()
print("===========================================")
flash(f'Error processing prediction: {str(e)}')
return redirect(url_for('detailed_check'))
@app.route('/view-last-detailed-report')
def view_last_detailed_report():
if 'detailed_results' in session:
results = session['detailed_results']
return render_template('detailed_report.html', **results)
else:
flash('No detailed health assessment results found. Please submit the form first.')
return redirect(url_for('detailed_check'))
@app.route('/records')
def records():
conn = sqlite3.connect('predictions.db')
c = conn.cursor()
c.execute('SELECT id, timestamp, prediction, probability, features FROM predictions ORDER BY timestamp DESC')
records = []
for row in c.fetchall():
records.append({
'id': row[0],
'timestamp': row[1],
'prediction': row[2],
'probability': row[3],
'features': row[4]
})
conn.close()
return render_template('records.html', records=records)
@app.route('/delete_record/<int:record_id>', methods=['POST'])
def delete_record(record_id):
try:
conn = sqlite3.connect('predictions.db')
c = conn.cursor()
c.execute('DELETE FROM predictions WHERE id = ?', (record_id,))
conn.commit()
conn.close()
flash('Record deleted successfully')
except Exception as e:
flash(f'Error deleting record: {str(e)}')
return redirect(url_for('records'))
# ==================== REACT JSON API ENDPOINTS ====================
@app.route('/api/predict', methods=['POST'])
def api_predict():
try:
data = request.json
features = [
float(data['glucose']),
float(data['blood_pressure']),
float(data['skin_thickness']),
float(data['insulin']),
float(data['bmi']),
float(data['waist_circumference']),
float(data['diabetes_pedigree']),
float(data['age'])
]
normal_ranges = {
'glucose': {'min': 70, 'max': 140},
'blood_pressure': {'min': 60, 'max': 90},
'skin_thickness': {'min': 10, 'max': 50},
'insulin': {'min': 20, 'max': 200},
'bmi': {'min': 18.5, 'max': 24.9},
'waist_circumference': {'min': 60, 'max': 100},
'diabetes_pedigree': {'min': 0.1, 'max': 1.0},
'age': {'min': 18, 'max': 65}
}
risk_score = 0
total_factors = len(features)
for i, (feature_name, value) in enumerate(zip(normal_ranges.keys(), features)):
normal_min = normal_ranges[feature_name]['min']
normal_max = normal_ranges[feature_name]['max']
if value < normal_min:
deviation = (normal_min - value) / normal_min
risk_score += min(deviation, 1.0)
elif value > normal_max:
deviation = (value - normal_max) / normal_max
risk_score += min(deviation, 1.0)
average_risk = risk_score / total_factors
features_scaled = scaler.transform([features])
model_prediction = int(model.predict(features_scaled)[0])
model_probability = float(model.predict_proba(features_scaled)[0][1] * 100)
if average_risk > 0.5 or model_probability > 60:
prediction = 1
probability = max(average_risk * 100, model_probability)
else:
prediction = 0
probability = min((1 - average_risk) * 100, 100 - model_probability)
# Save to database
conn = sqlite3.connect('predictions.db')
c = conn.cursor()
c.execute('INSERT INTO predictions (timestamp, prediction, probability, features) VALUES (?, ?, ?, ?)',
(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), prediction, probability, str(features)))
conn.commit()
conn.close()
return jsonify({
'status': 'success',
'prediction': prediction,
'probability': round(probability, 2)
})
except Exception as e:
return jsonify({'status': 'error', 'message': str(e)}), 400
@app.route('/api/records', methods=['GET'])
def api_records():
try:
conn = sqlite3.connect('predictions.db')
c = conn.cursor()
c.execute('SELECT id, timestamp, prediction, probability, features FROM predictions ORDER BY timestamp DESC')
records = []
for row in c.fetchall():
records.append({
'id': row[0],
'timestamp': row[1],
'prediction': row[2],
'probability': round(row[3], 2),
'features': row[4]
})
conn.close()
return jsonify({'status': 'success', 'records': records})
except Exception as e:
return jsonify({'status': 'error', 'message': str(e)}), 400
@app.route('/api/delete_record/<int:record_id>', methods=['POST'])
def api_delete_record(record_id):
try:
conn = sqlite3.connect('predictions.db')
c = conn.cursor()
c.execute('DELETE FROM predictions WHERE id = ?', (record_id,))
conn.commit()
conn.close()
return jsonify({'status': 'success', 'message': 'Record deleted successfully'})
except Exception as e:
return jsonify({'status': 'error', 'message': str(e)}), 400
@app.route('/api/run-detailed-prediction', methods=['POST'])
def api_run_detailed_prediction():
try:
data = request.json
cardio_features = [
float(data.get('chest_pain', 0)),
float(data.get('shortness_breath', 0)),
float(data.get('irregular_heartbeat', 0)),
float(data.get('swelling_legs', 0)),
float(data.get('fatigue', 0)),
float(data.get('blood_pressure', 0) or 0),
float(data.get('cholesterol', 0) or 0)
]
nephropathy_features = [
float(data.get('proteinuria', 0)),
float(data.get('swelling_ankles', 0)),
float(data.get('fatigue_neph', 0)),
float(data.get('nausea', 0)),
float(data.get('creatinine_level', 0) or 0),
float(data.get('urine_output', 0) or 0)
]
retinopathy_features = [
float(data.get('blurred_vision', 0)),
float(data.get('floaters', 0)),
float(data.get('dark_spots', 0)),
float(data.get('vision_loss', 0)),
float(data.get('eye_pain', 0)),
float(data.get('glucose_level', 0) or 0),
float(data.get('duration_diabetes', 0) or 0)
]
neuropathy_features = [
float(data.get('numbness', 0)),
float(data.get('tingling', 0)),
float(data.get('burning_pain', 0)),
float(data.get('muscle_weakness', 0)),
float(data.get('balance_problems', 0))
]
liver_features = [
float(data.get('abdominal_pain', 0)),
float(data.get('fatigue_liver', 0)),
float(data.get('nausea_liver', 0)),
float(data.get('jaundice', 0)),
float(data.get('swelling_abdomen', 0)),
float(data.get('ast_level', 0) or 0),
float(data.get('alt_level', 0) or 0)
]
cardio_risk = int(cardio_model.predict([cardio_features])[0])
cardio_probability = float(cardio_model.predict_proba([cardio_features])[0][1] * 100)
nephropathy_risk = int(nephropathy_model.predict([nephropathy_features])[0])
nephropathy_probability = float(nephropathy_model.predict_proba([nephropathy_features])[0][1] * 100)
retinopathy_risk = int(retinopathy_model.predict([retinopathy_features])[0])
retinopathy_probability = float(retinopathy_model.predict_proba([retinopathy_features])[0][1] * 100)
neuropathy_risk = int(neuropathy_model.predict([neuropathy_features])[0])
neuropathy_probability = float(neuropathy_model.predict_proba([neuropathy_features])[0][1] * 100)
liver_risk = int(liver_model.predict([liver_features])[0])
liver_probability = float(liver_model.predict_proba([liver_features])[0][1] * 100)
return jsonify({
'status': 'success',
'results': {
'cardio_risk': cardio_risk,
'cardio_probability': round(cardio_probability, 2),
'nephropathy_risk': nephropathy_risk,
'nephropathy_probability': round(nephropathy_probability, 2),
'retinopathy_risk': retinopathy_risk,
'retinopathy_probability': round(retinopathy_probability, 2),
'neuropathy_risk': neuropathy_risk,
'neuropathy_probability': round(neuropathy_probability, 2),
'liver_risk': liver_risk,
'liver_probability': round(liver_probability, 2)
}
})
except Exception as e:
return jsonify({'status': 'error', 'message': str(e)}), 400
if __name__ == '__main__':
app.run(debug=True)