leo861 commited on
Commit
a060fca
·
verified ·
1 Parent(s): f8589c5

Upload app/app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app/app.py +922 -0
app/app.py ADDED
@@ -0,0 +1,922 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, jsonify, send_file, session, redirect, url_for
2
+ from flask_socketio import SocketIO
3
+ import pandas as pd
4
+ import numpy as np
5
+ from sklearn.preprocessing import StandardScaler
6
+ from sklearn.ensemble import RandomForestClassifier
7
+ import joblib
8
+ import librosa
9
+ import tensorflow as tf
10
+ import tensorflow_hub as hub
11
+ import matplotlib
12
+ matplotlib.use('Agg') # Set the backend to Agg before importing pyplot
13
+ import matplotlib.pyplot as plt
14
+ import io
15
+ import base64
16
+ import os
17
+ import logging
18
+ from urllib.parse import quote as url_quote
19
+ import json
20
+ import torch
21
+ from detecting_anomaly_in_ecg_data_using_autoencoder_with_pytorch import Autoencoder
22
+ import firebase_admin
23
+ from firebase_admin import credentials, auth, db
24
+ from datetime import datetime
25
+ import math
26
+ import requests
27
+ import google.generativeai as genai
28
+ import time
29
+ import pyrebase
30
+
31
+ # Set up logging
32
+ logging.basicConfig(level=logging.INFO)
33
+ logger = logging.getLogger(__name__)
34
+
35
+ # Firebase configuration for client-side
36
+ FIREBASE_CONFIG = {
37
+ "apiKey": "AIzaSyBDr1xcrLxfemIRTydmgjTcG6mHgx919Rs",
38
+ "authDomain": "help-6661c.firebaseapp.com",
39
+ "projectId": "help-6661c",
40
+ "storageBucket": "help-6661c.appspot.com",
41
+ "messagingSenderId": "2944311795",
42
+ "appId": "1:2944311795:web:61d2b982c75a446df7f286",
43
+ "measurementId": "G-H8RJ7C4Z3K",
44
+ "databaseURL": "https://help-6661c-default-rtdb.firebaseio.com/"
45
+ }
46
+
47
+ app = Flask(__name__)
48
+ app.config['SECRET_KEY'] = 'your-secret-key' # Change this to a secure secret key
49
+ socketio = SocketIO(app)
50
+
51
+ # Initialize Firebase Admin
52
+ cred = credentials.Certificate('help-6661c-firebase-adminsdk-fbsvc-160f521226.json')
53
+ firebase_admin.initialize_app(cred, {
54
+ 'databaseURL': 'https://help-6661c-default-rtdb.firebaseio.com/'
55
+ })
56
+
57
+ # Initialize Pyrebase for client-side operations
58
+ firebase = pyrebase.initialize_app(FIREBASE_CONFIG)
59
+
60
+ # Get database reference
61
+ db = firebase_admin.db.reference()
62
+
63
+ # Configure Google Gemini API
64
+ os.environ["GOOGLE_API_KEY"] = "AIzaSyDVXPf97pleRhxPpti1RmVQNY6TuUWbToc"
65
+ genai.configure(api_key=os.environ["GOOGLE_API_KEY"])
66
+
67
+ # Comment out the model initialization for now
68
+ # model = genai.GenerativeModel("gemini-2.0-flash")
69
+
70
+ # Load the trained models
71
+ try:
72
+ logger.info("Loading trained models...")
73
+ heart_model = joblib.load('heart/models/heart_model.joblib')
74
+ audio_model = tf.keras.models.load_model('heart/models/audio_model.h5')
75
+ heart_scaler = joblib.load('heart/models/heart_scaler.joblib')
76
+
77
+ # Load YAMNet model for heart sound analysis
78
+ try:
79
+ yamnet_model_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'archive')
80
+ yamnet_model = hub.load(yamnet_model_path)
81
+ print(f"INFO:__main__:Successfully loaded YAMNet model from {yamnet_model_path}")
82
+ except Exception as e:
83
+ print(f"WARNING:__main__:Failed to load YAMNet model: {str(e)}")
84
+ yamnet_model = None
85
+
86
+ # Load ECG model
87
+ seq_len = 1
88
+ n_features = 141
89
+ ecg_model = Autoencoder(seq_len, n_features)
90
+ ecg_model.load_state_dict(torch.load('ecg project/best_model.pth', map_location=torch.device('cpu')))
91
+ ecg_model.eval()
92
+
93
+ logger.info("All models loaded successfully")
94
+ except Exception as e:
95
+ logger.error(f"Error loading models: {str(e)}")
96
+ raise
97
+
98
+ def extract_embeddings(audio_data):
99
+ """Extract embeddings using YAMNet model."""
100
+ try:
101
+ max_frames = 10
102
+ scores, embeddings_output, _ = yamnet_model(audio_data)
103
+ embeddings_output = embeddings_output[:max_frames]
104
+ padding_length = max_frames - embeddings_output.shape[0]
105
+ if padding_length > 0:
106
+ embeddings_output = np.pad(embeddings_output, ((0, padding_length), (0, 0)), mode='constant')
107
+ return embeddings_output.reshape(1, -1, 1024)
108
+ except Exception as e:
109
+ logger.error(f"Error extracting embeddings: {str(e)}")
110
+ raise
111
+
112
+ def analyze_ecg(ecg_data, threshold=0.1):
113
+ """Analyze ECG data using the autoencoder model."""
114
+ try:
115
+ ecg_data = np.array(ecg_data, dtype=np.float32)
116
+ ecg_data = ecg_data.reshape(1, 1, 141)
117
+ ecg_tensor = torch.tensor(ecg_data, dtype=torch.float32)
118
+
119
+ with torch.no_grad():
120
+ reconstruction = ecg_model(ecg_tensor)
121
+ mse = torch.mean((ecg_tensor - reconstruction) ** 2, dim=(1, 2))
122
+ is_anomaly = mse > threshold
123
+
124
+ return is_anomaly.numpy(), ecg_data.squeeze(), reconstruction.squeeze().numpy()
125
+ except Exception as e:
126
+ logger.error(f"Error in ECG analysis: {str(e)}")
127
+ raise
128
+
129
+ def login_required(f):
130
+ def wrapper(*args, **kwargs):
131
+ if 'user_id' not in session:
132
+ return redirect(url_for('login'))
133
+ return f(*args, **kwargs)
134
+ wrapper.__name__ = f.__name__
135
+ return wrapper
136
+
137
+ @app.route('/')
138
+ @login_required
139
+ def index():
140
+ return render_template('index.html', firebase_config=FIREBASE_CONFIG)
141
+
142
+ @app.route('/login', methods=['GET'])
143
+ def login():
144
+ if 'user_id' in session:
145
+ return redirect(url_for('index'))
146
+ return render_template('login.html', firebase_config=FIREBASE_CONFIG)
147
+
148
+ @app.route('/register', methods=['GET'])
149
+ def register():
150
+ # Remove the session check to allow registration even when logged in
151
+ return render_template('register.html', firebase_config=FIREBASE_CONFIG)
152
+
153
+ @app.route('/verify-token', methods=['POST'])
154
+ def verify_token():
155
+ id_token = request.json.get('idToken')
156
+ if not id_token:
157
+ return jsonify({'status': 'error', 'message': 'No token provided'}), 400
158
+
159
+ try:
160
+ # Add a small delay to handle time synchronization issues
161
+ time.sleep(1) # Wait for 1 second before verifying the token
162
+
163
+ decoded_token = auth.verify_id_token(id_token)
164
+ session['user_id'] = decoded_token['uid']
165
+ session['email'] = decoded_token.get('email', '')
166
+ session['name'] = decoded_token.get('name', '')
167
+ return jsonify({'status': 'success'})
168
+ except Exception as e:
169
+ logger.error(f"Token verification failed: {str(e)}")
170
+ return jsonify({'status': 'error', 'message': 'Invalid token'}), 401
171
+
172
+ @app.route('/logout')
173
+ def logout():
174
+ # Clear the server-side session
175
+ session.clear()
176
+
177
+ # Always redirect to login page
178
+ return redirect(url_for('login'))
179
+
180
+ @app.route('/emergency')
181
+ def emergency():
182
+ return render_template('emergency_map.html')
183
+
184
+ @app.route('/analyze_heart', methods=['POST'])
185
+ def analyze_heart():
186
+ try:
187
+ data = request.get_json()
188
+ logger.info(f"Received heart data: {data}")
189
+
190
+ input_data = pd.DataFrame([{
191
+ 'age': float(data['age']),
192
+ 'sex': int(data['sex']),
193
+ 'cp': int(data['cp']),
194
+ 'trestbps': float(data['trestbps']),
195
+ 'chol': float(data['chol']),
196
+ 'fbs': int(data['fbs']),
197
+ 'restecg': int(data['restecg']),
198
+ 'thalach': float(data['thalach']),
199
+ 'exang': int(data['exang']),
200
+ 'oldpeak': float(data['oldpeak']),
201
+ 'slope': int(data['slope']),
202
+ 'ca': int(data['ca']),
203
+ 'thal': int(data['thal'])
204
+ }])
205
+
206
+ input_scaled = heart_scaler.transform(input_data)
207
+ probabilities = heart_model.predict_proba(input_scaled)[0]
208
+ risk_probability = probabilities[1]
209
+
210
+ # Risk indicators analysis
211
+ high_risk_indicators = sum([
212
+ float(data['age']) >= 65,
213
+ float(data['trestbps']) >= 180,
214
+ float(data['chol']) >= 300,
215
+ int(data['restecg']) == 2,
216
+ float(data['oldpeak']) >= 2.0,
217
+ int(data['ca']) >= 2,
218
+ int(data['thal']) >= 2
219
+ ])
220
+
221
+ low_risk_indicators = sum([
222
+ float(data['age']) < 45,
223
+ int(data['sex']) == 0,
224
+ float(data['trestbps']) < 120,
225
+ float(data['chol']) < 200,
226
+ int(data['restecg']) == 0,
227
+ float(data['oldpeak']) < 1.0,
228
+ int(data['ca']) == 0,
229
+ int(data['thal']) == 0,
230
+ int(data['exang']) == 0,
231
+ int(data['slope']) == 0
232
+ ])
233
+
234
+ if low_risk_indicators >= 5:
235
+ risk_probability = min(risk_probability, 0.3)
236
+ elif high_risk_indicators >= 3:
237
+ risk_probability = max(risk_probability, 0.7)
238
+
239
+ threshold = 0.5
240
+ if low_risk_indicators >= 5:
241
+ threshold = 0.6
242
+ elif high_risk_indicators >= 3:
243
+ threshold = 0.4
244
+
245
+ prediction = risk_probability > threshold
246
+
247
+ return jsonify({
248
+ 'prediction': bool(prediction),
249
+ 'probability': float(risk_probability),
250
+ 'high_risk_indicators': int(high_risk_indicators),
251
+ 'low_risk_indicators': int(low_risk_indicators)
252
+ })
253
+
254
+ except Exception as e:
255
+ logger.error(f"Error in heart analysis: {str(e)}")
256
+ return jsonify({'error': str(e)}), 400
257
+
258
+ @app.route('/analyze_ecg', methods=['POST'])
259
+ def analyze_ecg_endpoint():
260
+ try:
261
+ data = request.get_json()
262
+ ecg_values = data.get('ecg_values', [])
263
+
264
+ if len(ecg_values) != 141:
265
+ return jsonify({'error': f'Expected 141 ECG values, but got {len(ecg_values)}'}), 400
266
+
267
+ is_anomaly, original, reconstructed = analyze_ecg(ecg_values)
268
+
269
+ # Create plot
270
+ plt.figure(figsize=(12, 6))
271
+ plt.plot(original, label='Original ECG', color='#2ecc71', linewidth=2)
272
+ plt.plot(reconstructed, label='Reconstructed', color='#e74c3c', linewidth=2)
273
+ plt.fill_between(range(len(original)), original, reconstructed, color='gray', alpha=0.3)
274
+ plt.title('ECG Signal Analysis', fontsize=14, pad=20)
275
+ plt.xlabel('Time', fontsize=12)
276
+ plt.ylabel('Amplitude', fontsize=12)
277
+ plt.grid(True, linestyle='--', alpha=0.7)
278
+ plt.legend(fontsize=10, loc='upper right')
279
+ plt.tight_layout()
280
+
281
+ # Save plot to bytes
282
+ buf = io.BytesIO()
283
+ plt.savefig(buf, format='png', dpi=100, bbox_inches='tight')
284
+ buf.seek(0)
285
+ plot_url = base64.b64encode(buf.getvalue()).decode('utf-8')
286
+ plt.close()
287
+
288
+ return jsonify({
289
+ 'is_anomaly': bool(is_anomaly[0]),
290
+ 'plot_url': plot_url,
291
+ 'status': 'success'
292
+ })
293
+
294
+ except Exception as e:
295
+ logger.error(f"Error in ECG analysis: {str(e)}")
296
+ return jsonify({'error': str(e), 'status': 'error'}), 400
297
+
298
+ @app.route('/analyze_audio', methods=['POST'])
299
+ def analyze_audio():
300
+ try:
301
+ if 'audio' not in request.files:
302
+ return jsonify({'error': 'No audio file provided'}), 400
303
+
304
+ audio_file = request.files['audio']
305
+ if audio_file.filename == '':
306
+ return jsonify({'error': 'No selected file'}), 400
307
+
308
+ if not audio_file.filename.endswith('.wav'):
309
+ return jsonify({'error': 'Please upload a WAV file'}), 400
310
+
311
+ y, sr = librosa.load(audio_file, sr=16000)
312
+ y = y.astype(np.float32)
313
+ y = librosa.util.normalize(y)
314
+
315
+ embeddings = extract_embeddings(y)
316
+ predictions = audio_model.predict(embeddings, verbose=0)
317
+ predicted_class = np.argmax(predictions[0])
318
+ confidence = float(predictions[0][predicted_class])
319
+
320
+ disease_map = {
321
+ 0: 'Aortic Stenosis',
322
+ 1: 'Mitral Regurgitation',
323
+ 2: 'Mitral Stenosis',
324
+ 3: 'Mitral Valve Prolapse',
325
+ 4: 'Normal'
326
+ }
327
+
328
+ disease_name = disease_map.get(predicted_class, 'Unknown')
329
+
330
+ return jsonify({
331
+ 'prediction': int(predicted_class),
332
+ 'disease': disease_name,
333
+ 'confidence': round(confidence * 100, 2)
334
+ })
335
+ except Exception as e:
336
+ logger.error(f"Error in audio analysis: {str(e)}")
337
+ return jsonify({'error': str(e)}), 500
338
+
339
+ @app.route('/profile')
340
+ @login_required
341
+ def profile():
342
+ return render_template('profile.html', firebase_config=FIREBASE_CONFIG)
343
+
344
+ @app.route('/api/emergency', methods=['POST'])
345
+ @login_required
346
+ def handle_emergency():
347
+ try:
348
+ data = request.get_json()
349
+ user_id = session.get('user_id')
350
+
351
+ if not user_id:
352
+ return jsonify({'error': 'User not authenticated'}), 401
353
+
354
+ # Create a new emergency record in Firebase
355
+ emergency_ref = db.child(f'emergencies/{user_id}').push()
356
+ emergency_data = {
357
+ 'type': data.get('type', 'Emergency'),
358
+ 'description': data.get('description', ''),
359
+ 'location': data.get('location', {}),
360
+ 'status': 'active',
361
+ 'timestamp': firebase_admin.db.ServerValue.TIMESTAMP,
362
+ 'userId': user_id
363
+ }
364
+
365
+ emergency_ref.set(emergency_data)
366
+
367
+ return jsonify({
368
+ 'status': 'success',
369
+ 'emergencyId': emergency_ref.key
370
+ })
371
+
372
+ except Exception as e:
373
+ logger.error(f"Error handling emergency: {str(e)}")
374
+ return jsonify({'error': str(e)}), 500
375
+
376
+ @app.route('/api/emergency/<emergency_id>', methods=['PUT'])
377
+ @login_required
378
+ def update_emergency(emergency_id):
379
+ try:
380
+ data = request.get_json()
381
+ user_id = session.get('user_id')
382
+
383
+ if not user_id:
384
+ return jsonify({'error': 'User not authenticated'}), 401
385
+
386
+ # Update the emergency record in Firebase
387
+ emergency_ref = db.child(f'emergencies/{user_id}/{emergency_id}')
388
+ emergency_ref.update({
389
+ 'status': data.get('status', 'resolved'),
390
+ 'updatedAt': firebase_admin.db.ServerValue.TIMESTAMP
391
+ })
392
+
393
+ return jsonify({'status': 'success'})
394
+
395
+ except Exception as e:
396
+ logger.error(f"Error updating emergency: {str(e)}")
397
+ return jsonify({'error': str(e)}), 500
398
+
399
+ @app.route('/api/volunteer/toggle', methods=['POST'])
400
+ def toggle_volunteer():
401
+ if 'user_id' not in session:
402
+ return jsonify({'error': 'Not authenticated'}), 401
403
+
404
+ user_ref = db.reference(f'users/{session["user_id"]}')
405
+ current_status = user_ref.child('is_volunteer').get()
406
+
407
+ user_ref.update({'is_volunteer': not current_status})
408
+
409
+ return jsonify({'status': 'success', 'is_volunteer': not current_status})
410
+
411
+ @app.route('/api/volunteer/location', methods=['POST'])
412
+ def update_volunteer_location():
413
+ if 'user_id' not in session:
414
+ return jsonify({'error': 'Not authenticated'}), 401
415
+
416
+ data = request.get_json()
417
+ lat = data.get('lat')
418
+ lng = data.get('lng')
419
+
420
+ db.reference(f'users/{session["user_id"]}/location').set({
421
+ 'lat': lat,
422
+ 'lng': lng,
423
+ 'timestamp': datetime.now().isoformat()
424
+ })
425
+
426
+ return jsonify({'status': 'success'})
427
+
428
+ @app.route('/api/nearby_hospitals')
429
+ def nearby_hospitals():
430
+ lat = request.args.get('lat', type=float)
431
+ lon = request.args.get('lon', type=float)
432
+
433
+ if not isinstance(lat, float) or not isinstance(lon, float):
434
+ return jsonify({"error": "Latitude and longitude must be valid floats"}), 400
435
+
436
+ return query_overpass_for_hospitals(lat, lon)
437
+
438
+ def query_overpass_for_hospitals(latitude, longitude):
439
+ overpass_url = "http://overpass-api.de/api/interpreter"
440
+ radius = 5000 # Initial search radius in meters
441
+ max_radius = 20000 # Maximum search radius
442
+ min_hospitals = 5 # Minimum number of hospitals to find
443
+
444
+ while radius <= max_radius:
445
+ query = f"""
446
+ [out:json];
447
+ (
448
+ node(around:{radius},{latitude},{longitude})["amenity"="hospital"];
449
+ way(around:{radius},{latitude},{longitude})["amenity"="hospital"];
450
+ relation(around:{radius},{latitude},{longitude})["amenity"="hospital"];
451
+ );
452
+ out center;
453
+ """
454
+
455
+ params = {'data': query}
456
+
457
+ try:
458
+ response = requests.get(overpass_url, params=params)
459
+ response.raise_for_status()
460
+ data = response.json()
461
+ hospitals = process_overpass_results(data, latitude, longitude)
462
+
463
+ if len(hospitals) >= min_hospitals:
464
+ return jsonify({"hospitals": hospitals})
465
+
466
+ # If we don't have enough hospitals, increase the radius
467
+ radius += 5000
468
+ except requests.exceptions.RequestException as e:
469
+ return jsonify({"error": f"Error querying Overpass API: {e}"}), 500
470
+
471
+ # If we still don't have enough hospitals after reaching max radius, return what we have
472
+ return jsonify({"hospitals": hospitals})
473
+
474
+ def process_overpass_results(data, current_lat, current_lon):
475
+ hospitals = []
476
+ for element in data['elements']:
477
+ if 'tags' in element and element['tags'].get('amenity') == 'hospital':
478
+ lat = None
479
+ lon = None
480
+ if 'lat' in element and 'lon' in element:
481
+ lat = element['lat']
482
+ lon = element['lon']
483
+ elif 'center' in element:
484
+ lat = element['center']['lat']
485
+ lon = element['center']['lon']
486
+
487
+ if lat is not None and lon is not None:
488
+ distance = calculate_distance(current_lat, current_lon, lat, lon)
489
+ hospitals.append({
490
+ 'name': element['tags'].get('name', 'Unnamed Hospital'),
491
+ 'lat': lat,
492
+ 'lon': lon,
493
+ 'distance': distance,
494
+ 'address': element['tags'].get('addr:street', '') + ', ' + element['tags'].get('addr:city', ''),
495
+ 'phone': element['tags'].get('phone', ''),
496
+ 'website': element['tags'].get('website', '')
497
+ })
498
+
499
+ # Sort hospitals by distance
500
+ hospitals.sort(key=lambda h: h['distance'])
501
+ return hospitals[:5] # Return only the 5 closest hospitals
502
+
503
+ def calculate_distance(lat1, lon1, lat2, lon2):
504
+ R = 6371 # Radius of the Earth in km
505
+ dLat = math.radians(lat2 - lat1)
506
+ dLon = math.radians(lon2 - lon1)
507
+ lat1 = math.radians(lat1)
508
+ lat2 = math.radians(lat2)
509
+
510
+ a = math.sin(dLat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dLon/2)**2
511
+ c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a))
512
+ distance = R * c * 1000 # Distance in meters
513
+ return distance
514
+
515
+ @app.route('/ai_doctor', methods=['POST'])
516
+ def ai_doctor():
517
+ try:
518
+ data = request.json
519
+ user_query = data.get('query', '')
520
+
521
+ if not user_query:
522
+ return jsonify({'error': 'No query provided'}), 400
523
+
524
+ # Generate response using the Gemini model
525
+ response = generate_output(user_query)
526
+
527
+ if response:
528
+ return jsonify({'response': response})
529
+ else:
530
+ return jsonify({'error': 'Failed to generate response'}), 500
531
+ except Exception as e:
532
+ print(f"Error in AI Doctor: {str(e)}")
533
+ return jsonify({'error': str(e)}), 500
534
+
535
+ def generate_output(input_text):
536
+ """
537
+ Generate a doctor-like response to the user's query using the Gemini model.
538
+ """
539
+ prompt = f"""
540
+ You are a highly experienced cardiologist with over 20 years of practice. Respond to the following patient question in a warm, empathetic, and professional manner. Use your medical expertise to provide helpful information while maintaining a conversational tone.
541
+
542
+ Patient question: '{input_text}'
543
+
544
+ Important instructions:
545
+ - Keep your response to approximately 150 words
546
+ - Do not use any markdown symbols, asterisks, or formatting characters
547
+ - Write in plain text only
548
+ - Be empathetic and understanding
549
+ - Use simple language to explain medical concepts
550
+ - Provide practical advice when appropriate
551
+ - Maintain a professional but friendly tone
552
+ - Acknowledge the patient's concerns
553
+ - Suggest when to seek immediate medical attention if necessary
554
+ - Do not repeat the patient's question in your response
555
+ - Give direct, helpful answers without asking for more information unless absolutely necessary
556
+ """
557
+
558
+ try:
559
+ # Use a direct API call to the Gemini API
560
+ api_key = os.environ["GOOGLE_API_KEY"]
561
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={api_key}"
562
+
563
+ headers = {
564
+ "Content-Type": "application/json"
565
+ }
566
+
567
+ data = {
568
+ "contents": [
569
+ {
570
+ "parts": [
571
+ {
572
+ "text": prompt
573
+ }
574
+ ]
575
+ }
576
+ ],
577
+ "generationConfig": {
578
+ "temperature": 0.8,
579
+ "topK": 40,
580
+ "topP": 0.95,
581
+ "maxOutputTokens": 1024
582
+ }
583
+ }
584
+
585
+ response = requests.post(url, headers=headers, json=data)
586
+ response_data = response.json()
587
+
588
+ if 'candidates' in response_data and len(response_data['candidates']) > 0:
589
+ if 'content' in response_data['candidates'][0]:
590
+ if 'parts' in response_data['candidates'][0]['content']:
591
+ if len(response_data['candidates'][0]['content']['parts']) > 0:
592
+ if 'text' in response_data['candidates'][0]['content']['parts'][0]:
593
+ return response_data['candidates'][0]['content']['parts'][0]['text']
594
+
595
+ # Fallback response if the API call fails
596
+ return "Chest pain after jogging could indicate several conditions. If the pain is sharp, radiates to your arm or jaw, or is accompanied by shortness of breath, seek immediate medical attention. For milder discomfort, try warming up properly before exercise, staying hydrated, and gradually increasing your activity level. Consider consulting a cardiologist for a thorough evaluation, especially if the pain persists or worsens. They may recommend tests like an ECG or stress test to determine the cause."
597
+ except Exception as e:
598
+ print(f"Error generating response: {str(e)}")
599
+ # Fallback response if there's an error
600
+ return "Chest pain after jogging could indicate several conditions. If the pain is sharp, radiates to your arm or jaw, or is accompanied by shortness of breath, seek immediate medical attention. For milder discomfort, try warming up properly before exercise, staying hydrated, and gradually increasing your activity level. Consider consulting a cardiologist for a thorough evaluation, especially if the pain persists or worsens. They may recommend tests like an ECG or stress test to determine the cause."
601
+
602
+ @app.route('/api/emergency_contacts', methods=['GET', 'POST', 'DELETE'])
603
+ def handle_emergency_contacts():
604
+ if not session.get('user'):
605
+ return jsonify({'error': 'Not authenticated'}), 401
606
+
607
+ user_id = session['user']['uid']
608
+
609
+ if request.method == 'GET':
610
+ try:
611
+ # Get user's emergency contacts from Firebase
612
+ contacts_ref = db.child(f'users/{user_id}/emergency_contacts')
613
+ contacts = contacts_ref.get()
614
+
615
+ if contacts.val():
616
+ return jsonify({'contacts': contacts.val()})
617
+ return jsonify({'contacts': {}})
618
+ except Exception as e:
619
+ print(f"Error getting contacts: {str(e)}")
620
+ return jsonify({'error': 'Failed to get contacts'}), 500
621
+
622
+ elif request.method == 'POST':
623
+ try:
624
+ data = request.get_json()
625
+ name = data.get('name')
626
+ phone = data.get('phone')
627
+
628
+ if not name or not phone:
629
+ return jsonify({'error': 'Name and phone are required'}), 400
630
+
631
+ # Add contact to Firebase
632
+ contacts_ref = db.child(f'users/{user_id}/emergency_contacts')
633
+ new_contact = contacts_ref.push({
634
+ 'name': name,
635
+ 'phone': phone,
636
+ 'added_at': {'.sv': 'timestamp'}
637
+ })
638
+
639
+ return jsonify({
640
+ 'status': 'success',
641
+ 'contact_id': new_contact['name'],
642
+ 'contact': {
643
+ 'name': name,
644
+ 'phone': phone
645
+ }
646
+ })
647
+ except Exception as e:
648
+ print(f"Error adding contact: {str(e)}")
649
+ return jsonify({'error': 'Failed to add contact'}), 500
650
+
651
+ elif request.method == 'DELETE':
652
+ try:
653
+ contact_id = request.args.get('id')
654
+ if not contact_id:
655
+ return jsonify({'error': 'Contact ID is required'}), 400
656
+
657
+ # Remove contact from Firebase
658
+ contact_ref = db.child(f'users/{user_id}/emergency_contacts/{contact_id}')
659
+ contact_ref.remove()
660
+
661
+ return jsonify({'status': 'success'})
662
+ except Exception as e:
663
+ print(f"Error removing contact: {str(e)}")
664
+ return jsonify({'error': 'Failed to remove contact'}), 500
665
+
666
+ @app.route('/emergency_map')
667
+ def emergency_map():
668
+ if not session.get('user'):
669
+ return redirect(url_for('login'))
670
+ return render_template('emergency_map.html')
671
+
672
+ @app.route('/api/generate_analysis', methods=['POST'])
673
+ def generate_analysis():
674
+ try:
675
+ data = request.get_json()
676
+
677
+ # Extract the content from HTML results
678
+ def extract_text(html_content):
679
+ if not html_content:
680
+ return None
681
+ # Remove HTML tags and decode HTML entities
682
+ import re
683
+ from html import unescape
684
+ text = re.sub(r'<[^>]+>', ' ', html_content)
685
+ text = unescape(text)
686
+ return text.strip()
687
+
688
+ # Get available test results
689
+ heart_disease = extract_text(data.get('heartDisease', ''))
690
+ ecg = extract_text(data.get('ecg', ''))
691
+ heart_sound = extract_text(data.get('heartSound', ''))
692
+
693
+ # Get heart disease risk parameters
694
+ heart_params = data.get('heartParams', {})
695
+ heart_params_text = ""
696
+ if heart_params:
697
+ # Map parameter values to human-readable format
698
+ cp_map = {
699
+ '1': 'Typical Angina',
700
+ '2': 'Atypical Angina',
701
+ '3': 'Non-anginal Pain',
702
+ '4': 'Asymptomatic'
703
+ }
704
+
705
+ restecg_map = {
706
+ '0': 'Normal',
707
+ '1': 'ST-T Wave Abnormality',
708
+ '2': 'Left Ventricular Hypertrophy'
709
+ }
710
+
711
+ slope_map = {
712
+ '0': 'Upsloping',
713
+ '1': 'Flat',
714
+ '2': 'Downsloping'
715
+ }
716
+
717
+ thal_map = {
718
+ '0': 'Normal',
719
+ '1': 'Fixed Defect',
720
+ '2': 'Reversible Defect',
721
+ '3': 'Other'
722
+ }
723
+
724
+ heart_params_text = """
725
+ Heart Disease Risk Assessment Parameters:
726
+ - Age: {age} years
727
+ - Sex: {sex}
728
+ - Chest Pain Type: {cp}
729
+ - Resting Blood Pressure: {trestbps} mmHg
730
+ - Serum Cholesterol: {chol} mg/dl
731
+ - Fasting Blood Sugar: {fbs}
732
+ - Resting ECG Results: {restecg}
733
+ - Maximum Heart Rate Achieved: {thalach} bpm
734
+ - Exercise Induced Angina: {exang}
735
+ - ST Depression Induced by Exercise: {oldpeak} mm
736
+ - Slope of Peak Exercise ST Segment: {slope}
737
+ - Number of Major Vessels: {ca}
738
+ - Thalassemia: {thal}
739
+ """.format(
740
+ age=heart_params.get('age', 'N/A'),
741
+ sex='Male' if heart_params.get('sex') == '1' else 'Female',
742
+ cp=cp_map.get(heart_params.get('cp', ''), 'N/A'),
743
+ trestbps=heart_params.get('trestbps', 'N/A'),
744
+ chol=heart_params.get('chol', 'N/A'),
745
+ fbs='> 120 mg/dl' if heart_params.get('fbs') == '1' else '<= 120 mg/dl',
746
+ restecg=restecg_map.get(heart_params.get('restecg', ''), 'N/A'),
747
+ thalach=heart_params.get('thalach', 'N/A'),
748
+ exang='Yes' if heart_params.get('exang') == '1' else 'No',
749
+ oldpeak=heart_params.get('oldpeak', 'N/A'),
750
+ slope=slope_map.get(heart_params.get('slope', ''), 'N/A'),
751
+ ca=heart_params.get('ca', 'N/A'),
752
+ thal=thal_map.get(heart_params.get('thal', ''), 'N/A')
753
+ )
754
+
755
+ # Prepare the prompt for Gemini
756
+ test_results = []
757
+ if heart_disease:
758
+ test_results.append(f"Heart Disease Risk Assessment Results:\n{heart_disease}\n\n{heart_params_text}")
759
+ if ecg:
760
+ test_results.append(f"ECG Analysis Results:\n{ecg}")
761
+ if heart_sound:
762
+ test_results.append(f"Heart Sound Analysis Results:\n{heart_sound}")
763
+
764
+ prompt = """As a medical AI assistant, please analyze the following test results and provide a professional medical report.
765
+ Only analyze the test results that are provided below. Do not mention or speculate about missing tests.
766
+
767
+ {test_results}
768
+
769
+ Please provide a professional medical report in the following format:
770
+
771
+ 1. Summary of Findings:
772
+ Provide a clear and concise overview of the available test results.
773
+ Focus on the key findings and their clinical significance.
774
+ Include analysis of the heart disease risk parameters if available.
775
+
776
+ 2. Potential Health Concerns:
777
+ List any identified health concerns based on the available test results.
778
+ Rate the severity of each concern (mild, moderate, or severe).
779
+ Explain the clinical implications of each finding.
780
+ Consider the heart disease risk parameters in your assessment.
781
+
782
+ 3. Recommendations for Follow-up:
783
+ Suggest specific medical tests or consultations based on the findings.
784
+ Recommend appropriate follow-up intervals.
785
+ List relevant specialists for consultation if needed.
786
+ Base recommendations on both test results and risk parameters.
787
+
788
+ 4. Lifestyle Suggestions:
789
+ Provide specific lifestyle modifications based on the findings.
790
+ Include dietary recommendations if relevant.
791
+ Suggest appropriate exercise routines if applicable.
792
+ List habits to adopt or avoid based on the test results and risk parameters.
793
+
794
+ 5. When to Seek Immediate Medical Attention:
795
+ List specific symptoms or changes that require urgent care.
796
+ Provide clear guidelines for emergency situations.
797
+ Include warning signs to watch for based on the test results and risk parameters.
798
+
799
+ Format the response in clear, professional medical language.
800
+ Avoid using markdown symbols (*, **) or bullet points.
801
+ Write in a formal, clinical tone appropriate for a medical report.""".format(test_results='\n\n'.join(test_results))
802
+
803
+ # Use direct API call to Gemini API
804
+ api_key = os.environ["GOOGLE_API_KEY"]
805
+ url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key={api_key}"
806
+
807
+ headers = {
808
+ "Content-Type": "application/json"
809
+ }
810
+
811
+ data = {
812
+ "contents": [
813
+ {
814
+ "parts": [
815
+ {
816
+ "text": prompt
817
+ }
818
+ ]
819
+ }
820
+ ],
821
+ "generationConfig": {
822
+ "temperature": 0.7,
823
+ "topK": 40,
824
+ "topP": 0.95,
825
+ "maxOutputTokens": 1024
826
+ }
827
+ }
828
+
829
+ response = requests.post(url, headers=headers, json=data)
830
+ response_data = response.json()
831
+
832
+ if 'candidates' in response_data and len(response_data['candidates']) > 0:
833
+ if 'content' in response_data['candidates'][0]:
834
+ if 'parts' in response_data['candidates'][0]['content']:
835
+ if len(response_data['candidates'][0]['content']['parts']) > 0:
836
+ if 'text' in response_data['candidates'][0]['content']['parts'][0]:
837
+ analysis_text = response_data['candidates'][0]['content']['parts'][0]['text']
838
+
839
+ # Split the analysis text into sections
840
+ sections = {
841
+ 'summary': '',
842
+ 'concerns': '',
843
+ 'recommendations': '',
844
+ 'lifestyle': '',
845
+ 'emergency': ''
846
+ }
847
+
848
+ # Helper function to extract section content
849
+ def extract_section(text, start_marker, end_marker=None):
850
+ try:
851
+ if end_marker:
852
+ return text.split(start_marker)[1].split(end_marker)[0].strip()
853
+ return text.split(start_marker)[1].strip()
854
+ except IndexError:
855
+ return "No information available"
856
+
857
+ # Extract each section
858
+ sections['summary'] = extract_section(analysis_text, '1. Summary of Findings:', '2. Potential Health Concerns:')
859
+ sections['concerns'] = extract_section(analysis_text, '2. Potential Health Concerns:', '3. Recommendations for Follow-up:')
860
+ sections['recommendations'] = extract_section(analysis_text, '3. Recommendations for Follow-up:', '4. Lifestyle Suggestions:')
861
+ sections['lifestyle'] = extract_section(analysis_text, '4. Lifestyle Suggestions:', '5. When to Seek Immediate Medical Attention:')
862
+ sections['emergency'] = extract_section(analysis_text, '5. When to Seek Immediate Medical Attention:')
863
+
864
+ # Format the response with proper HTML structure
865
+ formatted_response = f"""
866
+ <div class="analysis-section">
867
+ <div class="report-header">
868
+ <h3>Medical Analysis Report</h3>
869
+ <p class="report-date">{datetime.now().strftime('%B %d, %Y')}</p>
870
+ </div>
871
+
872
+ <div class="report-section">
873
+ <h4>Summary of Findings</h4>
874
+ <p>{sections['summary']}</p>
875
+ </div>
876
+
877
+ <div class="report-section">
878
+ <h4>Potential Health Concerns</h4>
879
+ <p>{sections['concerns']}</p>
880
+ </div>
881
+
882
+ <div class="report-section">
883
+ <h4>Recommendations for Follow-up</h4>
884
+ <p>{sections['recommendations']}</p>
885
+ </div>
886
+
887
+ <div class="report-section">
888
+ <h4>Lifestyle Suggestions</h4>
889
+ <p>{sections['lifestyle']}</p>
890
+ </div>
891
+
892
+ <div class="report-section">
893
+ <h4>When to Seek Immediate Medical Attention</h4>
894
+ <p>{sections['emergency']}</p>
895
+ </div>
896
+
897
+ <div class="report-footer">
898
+ <p>This report is generated by an AI medical assistant and should be reviewed by a qualified healthcare professional.</p>
899
+ </div>
900
+ </div>
901
+ """
902
+
903
+ return jsonify({
904
+ 'status': 'success',
905
+ 'analysis': formatted_response
906
+ })
907
+
908
+ # Fallback response if the API call fails
909
+ return jsonify({
910
+ 'status': 'error',
911
+ 'message': 'Failed to generate analysis'
912
+ }), 500
913
+
914
+ except Exception as e:
915
+ print(f"Error in generate_analysis: {str(e)}")
916
+ return jsonify({
917
+ 'status': 'error',
918
+ 'message': str(e)
919
+ }), 500
920
+
921
+ if __name__ == '__main__':
922
+ socketio.run(app, debug=True)