Spaces:
Runtime error
Runtime error
Delete app.py
Browse files
app.py
DELETED
|
@@ -1,1766 +0,0 @@
|
|
| 1 |
-
import os
|
| 2 |
-
import pickle
|
| 3 |
-
from flask import Flask, render_template, request, redirect, url_for, session, jsonify, send_file, flash
|
| 4 |
-
from flask_pymongo import PyMongo
|
| 5 |
-
from flask_session import Session
|
| 6 |
-
from bson.objectid import ObjectId
|
| 7 |
-
from werkzeug.security import generate_password_hash, check_password_hash
|
| 8 |
-
import pandas as pd
|
| 9 |
-
from datetime import datetime, timedelta
|
| 10 |
-
import json
|
| 11 |
-
import io
|
| 12 |
-
from reportlab.lib.pagesizes import letter
|
| 13 |
-
from reportlab.pdfgen import canvas
|
| 14 |
-
from reportlab.lib.units import inch
|
| 15 |
-
import bcrypt
|
| 16 |
-
import pymongo
|
| 17 |
-
from pymongo.errors import ServerSelectionTimeoutError, ConnectionFailure
|
| 18 |
-
import ssl
|
| 19 |
-
import certifi
|
| 20 |
-
import logging
|
| 21 |
-
|
| 22 |
-
# Set up logging
|
| 23 |
-
logging.basicConfig(level=logging.INFO)
|
| 24 |
-
logger = logging.getLogger(__name__)
|
| 25 |
-
|
| 26 |
-
app = Flask(__name__)
|
| 27 |
-
# Read SECRET_KEY from environment; use a fallback only if not provided.
|
| 28 |
-
app.secret_key = os.getenv('SECRET_KEY', 'fallback_secret_key')
|
| 29 |
-
|
| 30 |
-
# Session configuration for production
|
| 31 |
-
from datetime import timedelta
|
| 32 |
-
app.config.update(
|
| 33 |
-
SESSION_COOKIE_SECURE=False, # Set to True if using HTTPS
|
| 34 |
-
SESSION_COOKIE_HTTPONLY=True,
|
| 35 |
-
SESSION_COOKIE_SAMESITE='Lax',
|
| 36 |
-
PERMANENT_SESSION_LIFETIME=timedelta(hours=1),
|
| 37 |
-
# Filesystem session storage for Hugging Face Spaces
|
| 38 |
-
SESSION_TYPE='filesystem',
|
| 39 |
-
SESSION_FILE_DIR='/tmp/flask_session',
|
| 40 |
-
SESSION_FILE_THRESHOLD=500,
|
| 41 |
-
SESSION_FILE_MODE=0o600,
|
| 42 |
-
SESSION_PERMANENT=True
|
| 43 |
-
)
|
| 44 |
-
|
| 45 |
-
# Initialize session
|
| 46 |
-
Session(app)
|
| 47 |
-
|
| 48 |
-
# Create session directory if it doesn't exist
|
| 49 |
-
try:
|
| 50 |
-
os.makedirs('/tmp/flask_session', exist_ok=True)
|
| 51 |
-
except:
|
| 52 |
-
pass # Ignore if can't create, will use default temp directory
|
| 53 |
-
|
| 54 |
-
# If deploying behind a proxy, uncomment the following lines:
|
| 55 |
-
# from werkzeug.middleware.proxy_fix import ProxyFix
|
| 56 |
-
# app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)
|
| 57 |
-
|
| 58 |
-
# Optional .env support for local development. We load it if python-dotenv is available.
|
| 59 |
-
# This keeps secrets out of the repo while making local dev easy via a `.env` file.
|
| 60 |
-
try:
|
| 61 |
-
from dotenv import load_dotenv
|
| 62 |
-
# Load .env from project root silently (no error if not present)
|
| 63 |
-
load_dotenv()
|
| 64 |
-
print("Loaded .env (if present)")
|
| 65 |
-
except Exception:
|
| 66 |
-
# python-dotenv not installed or failed to load; proceed without it
|
| 67 |
-
pass
|
| 68 |
-
|
| 69 |
-
# MongoDB Configuration - safe, environment-driven and non-blocking for builds
|
| 70 |
-
def create_mongo_client():
|
| 71 |
-
"""Create a secure MongoDB client for deployment.
|
| 72 |
-
|
| 73 |
-
This implementation reads the connection URI from the environment variable
|
| 74 |
-
MONGODB_URI. If the variable isn't set or the connection fails, the function
|
| 75 |
-
returns None so the application can continue to run in a limited mode.
|
| 76 |
-
"""
|
| 77 |
-
uri = os.environ.get('MONGODB_URI')
|
| 78 |
-
|
| 79 |
-
if not uri:
|
| 80 |
-
print("No MONGODB_URI provided - running in limited offline mode.")
|
| 81 |
-
return None
|
| 82 |
-
|
| 83 |
-
try:
|
| 84 |
-
# Try different connection approaches to handle SSL issues
|
| 85 |
-
client_options = [
|
| 86 |
-
{
|
| 87 |
-
'tls': True,
|
| 88 |
-
'serverSelectionTimeoutMS': 5000,
|
| 89 |
-
'connectTimeoutMS': 5000,
|
| 90 |
-
'socketTimeoutMS': 5000,
|
| 91 |
-
'tlsCAFile': certifi.where()
|
| 92 |
-
},
|
| 93 |
-
{
|
| 94 |
-
'tls': True,
|
| 95 |
-
'tlsAllowInvalidCertificates': True,
|
| 96 |
-
'tlsAllowInvalidHostnames': True,
|
| 97 |
-
'serverSelectionTimeoutMS': 5000,
|
| 98 |
-
'connectTimeoutMS': 5000,
|
| 99 |
-
'socketTimeoutMS': 5000
|
| 100 |
-
},
|
| 101 |
-
{
|
| 102 |
-
'tls': True,
|
| 103 |
-
'ssl': True,
|
| 104 |
-
'serverSelectionTimeoutMS': 5000,
|
| 105 |
-
'connectTimeoutMS': 5000,
|
| 106 |
-
'socketTimeoutMS': 5000
|
| 107 |
-
}
|
| 108 |
-
]
|
| 109 |
-
|
| 110 |
-
client = None
|
| 111 |
-
last_error = None
|
| 112 |
-
|
| 113 |
-
for options in client_options:
|
| 114 |
-
try:
|
| 115 |
-
client = pymongo.MongoClient(uri, **options)
|
| 116 |
-
# Test the connection (short timeout)
|
| 117 |
-
client.admin.command('ping')
|
| 118 |
-
print("MongoDB connected successfully ✅")
|
| 119 |
-
return client
|
| 120 |
-
except Exception as e:
|
| 121 |
-
last_error = e
|
| 122 |
-
logger.warning(f"MongoDB connection attempt failed with options {options}: {e}")
|
| 123 |
-
continue
|
| 124 |
-
|
| 125 |
-
# If all attempts fail, raise the last error
|
| 126 |
-
if last_error:
|
| 127 |
-
raise last_error
|
| 128 |
-
|
| 129 |
-
except (ServerSelectionTimeoutError, ConnectionFailure, Exception) as e:
|
| 130 |
-
print("MongoDB connection failed ❌", e)
|
| 131 |
-
logger.error(f"MongoDB connection failed: {e}")
|
| 132 |
-
return None
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
# Create MongoDB client (will be None in environments without DB access)
|
| 136 |
-
mongo_client = create_mongo_client()
|
| 137 |
-
|
| 138 |
-
if mongo_client:
|
| 139 |
-
# Access the database directly
|
| 140 |
-
db = mongo_client.get_database(os.environ.get('MONGODB_DB', 'healthcare_db'))
|
| 141 |
-
|
| 142 |
-
# Create a small wrapper to keep existing code working
|
| 143 |
-
class MongoWrapper:
|
| 144 |
-
def __init__(self, database, client):
|
| 145 |
-
self.db = database
|
| 146 |
-
self.cx = client
|
| 147 |
-
|
| 148 |
-
mongo = MongoWrapper(db, mongo_client)
|
| 149 |
-
print("MongoDB connection established successfully!")
|
| 150 |
-
else:
|
| 151 |
-
# Provide a safe null-wrapper so code that references mongo.db won't crash at import/runtime.
|
| 152 |
-
class _NullCollection:
|
| 153 |
-
def find_one(self, *a, **k):
|
| 154 |
-
return None
|
| 155 |
-
def find(self, *a, **k):
|
| 156 |
-
return []
|
| 157 |
-
def insert_one(self, *a, **k):
|
| 158 |
-
raise RuntimeError("Database not available in this environment")
|
| 159 |
-
def update_one(self, *a, **k):
|
| 160 |
-
raise RuntimeError("Database not available in this environment")
|
| 161 |
-
def delete_one(self, *a, **k):
|
| 162 |
-
raise RuntimeError("Database not available in this environment")
|
| 163 |
-
def count_documents(self, *a, **k):
|
| 164 |
-
return 0
|
| 165 |
-
def aggregate(self, *a, **k):
|
| 166 |
-
return []
|
| 167 |
-
|
| 168 |
-
class _NullDB:
|
| 169 |
-
def __getattr__(self, name):
|
| 170 |
-
return _NullCollection()
|
| 171 |
-
|
| 172 |
-
class _NullMongoWrapper:
|
| 173 |
-
def __init__(self):
|
| 174 |
-
self.db = _NullDB()
|
| 175 |
-
self.cx = None
|
| 176 |
-
|
| 177 |
-
mongo = _NullMongoWrapper()
|
| 178 |
-
print("Failed to establish MongoDB connection. Application will run in limited mode.")
|
| 179 |
-
|
| 180 |
-
# Get the working directory
|
| 181 |
-
working_dir = os.path.dirname(os.path.abspath(__file__))
|
| 182 |
-
|
| 183 |
-
# Load the saved models
|
| 184 |
-
diabetes_model = pickle.load(open(f'{working_dir}/saved models/diabetes_model.sav', 'rb'))
|
| 185 |
-
heart_disease_model = pickle.load(open(f'{working_dir}/saved models/heart_disease_model.sav', 'rb'))
|
| 186 |
-
parkinsons_model = pickle.load(open(f'{working_dir}/saved models/parkinsons_model.sav', 'rb'))
|
| 187 |
-
|
| 188 |
-
# Request debugging
|
| 189 |
-
@app.before_request
|
| 190 |
-
def before_request():
|
| 191 |
-
if request.endpoint and not request.endpoint.startswith('static'):
|
| 192 |
-
print(f"Request: {request.method} {request.url}")
|
| 193 |
-
print(f"Session: {dict(session)}")
|
| 194 |
-
print(f"Cookies: {request.cookies}")
|
| 195 |
-
|
| 196 |
-
@app.after_request
|
| 197 |
-
def after_request(response):
|
| 198 |
-
if request.endpoint and not request.endpoint.startswith('static'):
|
| 199 |
-
print(f"Response: {response.status_code} for {request.url}")
|
| 200 |
-
return response
|
| 201 |
-
|
| 202 |
-
# Routes for authentication
|
| 203 |
-
@app.route('/')
|
| 204 |
-
def index():
|
| 205 |
-
return render_template('index.html')
|
| 206 |
-
|
| 207 |
-
@app.route('/register', methods=['GET', 'POST'])
|
| 208 |
-
def register():
|
| 209 |
-
if mongo is None:
|
| 210 |
-
flash('Database connection error. Please contact administrator.', 'error')
|
| 211 |
-
return redirect(url_for('index'))
|
| 212 |
-
|
| 213 |
-
if request.method == 'POST':
|
| 214 |
-
name = request.form['name']
|
| 215 |
-
email = request.form['email']
|
| 216 |
-
phone = request.form['phone']
|
| 217 |
-
password = request.form['password']
|
| 218 |
-
confirm_password = request.form['confirm_password']
|
| 219 |
-
role = request.form.get('role', 'user') # Default to user
|
| 220 |
-
specialization = request.form.get('specialization', '') # For doctors
|
| 221 |
-
|
| 222 |
-
# Validate input
|
| 223 |
-
if not name or not email or not phone or not password:
|
| 224 |
-
flash('All fields are required!', 'error')
|
| 225 |
-
return redirect(url_for('register'))
|
| 226 |
-
|
| 227 |
-
# Check if passwords match
|
| 228 |
-
if password != confirm_password:
|
| 229 |
-
flash('Passwords do not match!', 'error')
|
| 230 |
-
return redirect(url_for('register'))
|
| 231 |
-
|
| 232 |
-
# Check password strength
|
| 233 |
-
if len(password) < 6:
|
| 234 |
-
flash('Password must be at least 6 characters long!', 'error')
|
| 235 |
-
return redirect(url_for('register'))
|
| 236 |
-
|
| 237 |
-
# Check if user already exists
|
| 238 |
-
try:
|
| 239 |
-
existing_user = mongo.db.users.find_one({'email': email})
|
| 240 |
-
if existing_user:
|
| 241 |
-
flash('Email already registered!', 'error')
|
| 242 |
-
return redirect(url_for('register'))
|
| 243 |
-
except Exception as e:
|
| 244 |
-
flash('Database error. Please try again later.', 'error')
|
| 245 |
-
return redirect(url_for('register'))
|
| 246 |
-
|
| 247 |
-
# Hash the password
|
| 248 |
-
try:
|
| 249 |
-
hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
|
| 250 |
-
except Exception as e:
|
| 251 |
-
flash('Error processing password. Please try again.', 'error')
|
| 252 |
-
return redirect(url_for('register'))
|
| 253 |
-
|
| 254 |
-
# Insert new user into database
|
| 255 |
-
user_data = {
|
| 256 |
-
'name': name,
|
| 257 |
-
'email': email,
|
| 258 |
-
'phone': phone,
|
| 259 |
-
'password': hashed_password,
|
| 260 |
-
'role': role, # user or doctor
|
| 261 |
-
'specialization': specialization if role == 'doctor' else '',
|
| 262 |
-
'created_at': datetime.now()
|
| 263 |
-
}
|
| 264 |
-
|
| 265 |
-
try:
|
| 266 |
-
result = mongo.db.users.insert_one(user_data)
|
| 267 |
-
if result.inserted_id:
|
| 268 |
-
flash('Registration successful! Please log in.', 'success')
|
| 269 |
-
return redirect(url_for('login'))
|
| 270 |
-
else:
|
| 271 |
-
flash('Registration failed. Please try again later.', 'error')
|
| 272 |
-
return redirect(url_for('register'))
|
| 273 |
-
except Exception as e:
|
| 274 |
-
flash('Registration failed. Please try again later.', 'error')
|
| 275 |
-
return redirect(url_for('register'))
|
| 276 |
-
|
| 277 |
-
return render_template('auth/register.html')
|
| 278 |
-
|
| 279 |
-
@app.route('/login', methods=['GET', 'POST'])
|
| 280 |
-
def login():
|
| 281 |
-
print(f"Login request method: {request.method}")
|
| 282 |
-
print(f"Session before login processing: {dict(session)}")
|
| 283 |
-
|
| 284 |
-
if mongo is None:
|
| 285 |
-
flash('Database connection error. Please contact administrator.', 'error')
|
| 286 |
-
return redirect(url_for('index'))
|
| 287 |
-
|
| 288 |
-
if request.method == 'POST':
|
| 289 |
-
email = request.form['email']
|
| 290 |
-
password = request.form['password']
|
| 291 |
-
|
| 292 |
-
print(f"Login attempt - Email: {email}")
|
| 293 |
-
|
| 294 |
-
# Validate input
|
| 295 |
-
if not email or not password:
|
| 296 |
-
flash('Email and password are required!', 'error')
|
| 297 |
-
return redirect(url_for('login'))
|
| 298 |
-
|
| 299 |
-
try:
|
| 300 |
-
# Find user in database
|
| 301 |
-
user = mongo.db.users.find_one({'email': email})
|
| 302 |
-
print(f"User found: {user is not None}")
|
| 303 |
-
|
| 304 |
-
if user and bcrypt.checkpw(password.encode('utf-8'), user['password']):
|
| 305 |
-
print("Password verified successfully")
|
| 306 |
-
# Set session variables
|
| 307 |
-
session['user_id'] = str(user['_id'])
|
| 308 |
-
session['username'] = user['name']
|
| 309 |
-
session['user_email'] = user['email']
|
| 310 |
-
session['user_role'] = user['role']
|
| 311 |
-
|
| 312 |
-
print(f"Session after login: {dict(session)}")
|
| 313 |
-
|
| 314 |
-
# Redirect based on role
|
| 315 |
-
if user['role'] == 'admin':
|
| 316 |
-
redirect_url = url_for('admin_dashboard')
|
| 317 |
-
elif user['role'] == 'doctor':
|
| 318 |
-
# send doctors to their appointments view
|
| 319 |
-
redirect_url = url_for('doctor_appointments')
|
| 320 |
-
else:
|
| 321 |
-
redirect_url = url_for('user_dashboard')
|
| 322 |
-
|
| 323 |
-
print(f"Redirecting to: {redirect_url}")
|
| 324 |
-
return redirect(redirect_url)
|
| 325 |
-
else:
|
| 326 |
-
print("Invalid credentials")
|
| 327 |
-
flash('Invalid email or password!', 'error')
|
| 328 |
-
return redirect(url_for('login'))
|
| 329 |
-
except Exception as e:
|
| 330 |
-
print(f"Login error: {e}")
|
| 331 |
-
flash('Login failed. Please try again later.', 'error')
|
| 332 |
-
return redirect(url_for('login'))
|
| 333 |
-
|
| 334 |
-
print(f"Session on GET request: {dict(session)}")
|
| 335 |
-
return render_template('auth/login.html')
|
| 336 |
-
|
| 337 |
-
@app.route('/logout')
|
| 338 |
-
def logout():
|
| 339 |
-
session.clear()
|
| 340 |
-
flash('You have been logged out successfully!', 'success')
|
| 341 |
-
return redirect(url_for('index'))
|
| 342 |
-
|
| 343 |
-
@app.route('/forgot-password', methods=['GET', 'POST'])
|
| 344 |
-
def forgot_password():
|
| 345 |
-
if mongo is None:
|
| 346 |
-
flash('Database connection error. Please contact administrator.', 'error')
|
| 347 |
-
return redirect(url_for('index'))
|
| 348 |
-
|
| 349 |
-
if request.method == 'POST':
|
| 350 |
-
email = request.form['email']
|
| 351 |
-
try:
|
| 352 |
-
user = mongo.db.users.find_one({'email': email})
|
| 353 |
-
if not user:
|
| 354 |
-
flash('Email not found!', 'error')
|
| 355 |
-
return redirect(url_for('forgot_password'))
|
| 356 |
-
|
| 357 |
-
# Generate a 6-digit OTP and store it with expiry (10 minutes)
|
| 358 |
-
import random
|
| 359 |
-
otp = '{:06d}'.format(random.randint(0, 999999))
|
| 360 |
-
expiry = datetime.now() + timedelta(minutes=10)
|
| 361 |
-
|
| 362 |
-
# Store OTP in a password_resets collection
|
| 363 |
-
mongo.db.password_resets.update_one(
|
| 364 |
-
{'email': email},
|
| 365 |
-
{'$set': {'otp': otp, 'expiry': expiry}},
|
| 366 |
-
upsert=True
|
| 367 |
-
)
|
| 368 |
-
|
| 369 |
-
# Send OTP via Gmail SMTP using EMAIL_USER/EMAIL_PASSWORD environment variables.
|
| 370 |
-
# We use a small helper in email_utils which wraps SMTP_SSL for secure sending.
|
| 371 |
-
msg_body = f"Your OTP for password reset is: {otp}. It is valid for 10 minutes."
|
| 372 |
-
try:
|
| 373 |
-
from email_utils import send_email
|
| 374 |
-
|
| 375 |
-
send_email(email, 'Password Reset OTP - Multiple Disease Prediction', msg_body)
|
| 376 |
-
except Exception as e:
|
| 377 |
-
print(f"Failed to send OTP email: {e}")
|
| 378 |
-
flash('Failed to send OTP email. Please contact administrator.', 'error')
|
| 379 |
-
return redirect(url_for('forgot_password'))
|
| 380 |
-
|
| 381 |
-
flash('An OTP has been sent to your email. Please enter it to reset your password.', 'success')
|
| 382 |
-
return redirect(url_for('verify_otp'))
|
| 383 |
-
except Exception as e:
|
| 384 |
-
flash('Database error. Please try again later.', 'error')
|
| 385 |
-
|
| 386 |
-
return render_template('auth/forgot_password.html')
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
@app.route('/verify-otp', methods=['GET', 'POST'])
|
| 390 |
-
def verify_otp():
|
| 391 |
-
if request.method == 'POST':
|
| 392 |
-
email = request.form['email']
|
| 393 |
-
otp = request.form['otp']
|
| 394 |
-
new_password = request.form['new_password']
|
| 395 |
-
|
| 396 |
-
# Validate input
|
| 397 |
-
if not email or not otp or not new_password:
|
| 398 |
-
flash('All fields are required!', 'error')
|
| 399 |
-
return redirect(url_for('verify_otp'))
|
| 400 |
-
|
| 401 |
-
record = mongo.db.password_resets.find_one({'email': email})
|
| 402 |
-
if not record:
|
| 403 |
-
flash('No OTP request found for this email.', 'error')
|
| 404 |
-
return redirect(url_for('verify_otp'))
|
| 405 |
-
|
| 406 |
-
if datetime.now() > record['expiry']:
|
| 407 |
-
flash('OTP has expired. Please request a new one.', 'error')
|
| 408 |
-
return redirect(url_for('forgot_password'))
|
| 409 |
-
|
| 410 |
-
if record['otp'] != otp:
|
| 411 |
-
flash('Invalid OTP. Please try again.', 'error')
|
| 412 |
-
return redirect(url_for('verify_otp'))
|
| 413 |
-
|
| 414 |
-
# Check password strength
|
| 415 |
-
if len(new_password) < 6:
|
| 416 |
-
flash('Password must be at least 6 characters long!', 'error')
|
| 417 |
-
return redirect(url_for('verify_otp'))
|
| 418 |
-
|
| 419 |
-
# Update password for user
|
| 420 |
-
try:
|
| 421 |
-
hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
|
| 422 |
-
except Exception as e:
|
| 423 |
-
flash('Error processing password. Please try again.', 'error')
|
| 424 |
-
return redirect(url_for('verify_otp'))
|
| 425 |
-
|
| 426 |
-
try:
|
| 427 |
-
mongo.db.users.update_one({'email': email}, {'$set': {'password': hashed_password}})
|
| 428 |
-
except Exception as e:
|
| 429 |
-
flash('Failed to update password. Please try again later.', 'error')
|
| 430 |
-
return redirect(url_for('verify_otp'))
|
| 431 |
-
|
| 432 |
-
# Remove the OTP record
|
| 433 |
-
try:
|
| 434 |
-
mongo.db.password_resets.delete_one({'email': email})
|
| 435 |
-
except Exception as e:
|
| 436 |
-
# Log the error but don't fail the operation
|
| 437 |
-
print(f'Failed to delete OTP record: {e}')
|
| 438 |
-
|
| 439 |
-
flash('Password reset successful. Please log in with your new password.', 'success')
|
| 440 |
-
return redirect(url_for('login'))
|
| 441 |
-
|
| 442 |
-
return render_template('auth/verify_otp.html')
|
| 443 |
-
|
| 444 |
-
# Profile Management
|
| 445 |
-
@app.route('/profile', methods=['GET', 'POST'])
|
| 446 |
-
def profile():
|
| 447 |
-
if mongo is None:
|
| 448 |
-
flash('Database connection error. Please contact administrator.', 'error')
|
| 449 |
-
return redirect(url_for('index'))
|
| 450 |
-
|
| 451 |
-
if 'user_id' not in session:
|
| 452 |
-
flash('Please log in to access this page!', 'error')
|
| 453 |
-
return redirect(url_for('login'))
|
| 454 |
-
|
| 455 |
-
try:
|
| 456 |
-
user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
|
| 457 |
-
except Exception as e:
|
| 458 |
-
flash('Database error. Please try again later.', 'error')
|
| 459 |
-
return redirect(url_for('user_dashboard'))
|
| 460 |
-
|
| 461 |
-
if not user:
|
| 462 |
-
flash('User not found!', 'error')
|
| 463 |
-
return redirect(url_for('login'))
|
| 464 |
-
|
| 465 |
-
if request.method == 'POST':
|
| 466 |
-
# Get form data
|
| 467 |
-
name = request.form['name']
|
| 468 |
-
email = request.form['email']
|
| 469 |
-
phone = request.form['phone']
|
| 470 |
-
current_password = request.form['current_password']
|
| 471 |
-
new_password = request.form['new_password']
|
| 472 |
-
confirm_password = request.form['confirm_password']
|
| 473 |
-
|
| 474 |
-
# Validate input
|
| 475 |
-
if not name or not email or not phone or not current_password:
|
| 476 |
-
flash('All required fields must be filled!', 'error')
|
| 477 |
-
return redirect(url_for('profile'))
|
| 478 |
-
|
| 479 |
-
# Verify current password
|
| 480 |
-
if not bcrypt.checkpw(current_password.encode('utf-8'), user['password']):
|
| 481 |
-
flash('Current password is incorrect!', 'error')
|
| 482 |
-
return redirect(url_for('profile'))
|
| 483 |
-
|
| 484 |
-
# Check if email is already taken by another user
|
| 485 |
-
try:
|
| 486 |
-
if email != user['email']:
|
| 487 |
-
existing_user = mongo.db.users.find_one({'email': email, '_id': {'$ne': ObjectId(session['user_id'])}})
|
| 488 |
-
if existing_user:
|
| 489 |
-
flash('Email is already taken by another user!', 'error')
|
| 490 |
-
return redirect(url_for('profile'))
|
| 491 |
-
except Exception as e:
|
| 492 |
-
flash('Database error. Please try again later.', 'error')
|
| 493 |
-
return redirect(url_for('profile'))
|
| 494 |
-
|
| 495 |
-
# Prepare update data
|
| 496 |
-
update_data = {
|
| 497 |
-
'name': name,
|
| 498 |
-
'email': email,
|
| 499 |
-
'phone': phone
|
| 500 |
-
}
|
| 501 |
-
|
| 502 |
-
# Update password if provided
|
| 503 |
-
if new_password:
|
| 504 |
-
if new_password != confirm_password:
|
| 505 |
-
flash('New passwords do not match!', 'error')
|
| 506 |
-
return redirect(url_for('profile'))
|
| 507 |
-
|
| 508 |
-
# Check password strength
|
| 509 |
-
if len(new_password) < 6:
|
| 510 |
-
flash('New password must be at least 6 characters long!', 'error')
|
| 511 |
-
return redirect(url_for('profile'))
|
| 512 |
-
|
| 513 |
-
# Hash new password
|
| 514 |
-
try:
|
| 515 |
-
hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
|
| 516 |
-
update_data['password'] = hashed_password
|
| 517 |
-
except Exception as e:
|
| 518 |
-
flash('Error processing password. Please try again.', 'error')
|
| 519 |
-
return redirect(url_for('profile'))
|
| 520 |
-
|
| 521 |
-
# Update user in database
|
| 522 |
-
try:
|
| 523 |
-
result = mongo.db.users.update_one(
|
| 524 |
-
{'_id': ObjectId(session['user_id'])},
|
| 525 |
-
{'$set': update_data}
|
| 526 |
-
)
|
| 527 |
-
|
| 528 |
-
if result.modified_count > 0:
|
| 529 |
-
# Update session data
|
| 530 |
-
session['username'] = name
|
| 531 |
-
session['user_email'] = email
|
| 532 |
-
|
| 533 |
-
flash('Profile updated successfully!', 'success')
|
| 534 |
-
return redirect(url_for('profile'))
|
| 535 |
-
else:
|
| 536 |
-
flash('No changes were made to your profile.', 'info')
|
| 537 |
-
return redirect(url_for('profile'))
|
| 538 |
-
except Exception as e:
|
| 539 |
-
flash('Profile update failed. Please try again later.', 'error')
|
| 540 |
-
return redirect(url_for('profile'))
|
| 541 |
-
|
| 542 |
-
# Get prediction counts for statistics
|
| 543 |
-
try:
|
| 544 |
-
prediction_count = mongo.db.patient_history.count_documents({'user_id': session['user_id']})
|
| 545 |
-
heart_count = mongo.db.patient_history.count_documents({'user_id': session['user_id'], 'disease_type': 'Heart Disease'})
|
| 546 |
-
diabetes_count = mongo.db.patient_history.count_documents({'user_id': session['user_id'], 'disease_type': 'Diabetes'})
|
| 547 |
-
parkinsons_count = mongo.db.patient_history.count_documents({'user_id': session['user_id'], 'disease_type': "Parkinson's"})
|
| 548 |
-
except Exception as e:
|
| 549 |
-
flash('Database error. Please try again later.', 'error')
|
| 550 |
-
prediction_count = 0
|
| 551 |
-
heart_count = 0
|
| 552 |
-
diabetes_count = 0
|
| 553 |
-
parkinsons_count = 0
|
| 554 |
-
|
| 555 |
-
return render_template('user/profile.html',
|
| 556 |
-
user=user,
|
| 557 |
-
prediction_count=prediction_count,
|
| 558 |
-
heart_count=heart_count,
|
| 559 |
-
diabetes_count=diabetes_count,
|
| 560 |
-
parkinsons_count=parkinsons_count)
|
| 561 |
-
|
| 562 |
-
# User Appointments
|
| 563 |
-
@app.route('/user/appointments', methods=['GET', 'POST'])
|
| 564 |
-
def user_appointments():
|
| 565 |
-
if 'user_id' not in session:
|
| 566 |
-
flash('Please log in to access this page!', 'error')
|
| 567 |
-
return redirect(url_for('login'))
|
| 568 |
-
|
| 569 |
-
if request.method == 'POST':
|
| 570 |
-
# Get form data
|
| 571 |
-
disease_type = request.form['disease_type']
|
| 572 |
-
date_str = request.form['date']
|
| 573 |
-
time = request.form['time']
|
| 574 |
-
notes = request.form['notes']
|
| 575 |
-
|
| 576 |
-
# Get checkbox details (symptoms, purpose of visit)
|
| 577 |
-
details_selected = request.form.getlist('details')
|
| 578 |
-
|
| 579 |
-
# Validate that date is in the future
|
| 580 |
-
appointment_datetime = datetime.strptime(f"{date_str} {time}", '%Y-%m-%d %H:%M')
|
| 581 |
-
if appointment_datetime <= datetime.now():
|
| 582 |
-
flash('Appointment date and time must be in the future!', 'error')
|
| 583 |
-
return redirect(url_for('user_appointments'))
|
| 584 |
-
|
| 585 |
-
# Check for overlapping appointments for the doctor
|
| 586 |
-
# Since appointments are unassigned at booking, we check only for existing identical patient bookings
|
| 587 |
-
existing_appointment = mongo.db.appointments.find_one({
|
| 588 |
-
'user_id': session['user_id'],
|
| 589 |
-
'date': datetime.strptime(date_str, '%Y-%m-%d'),
|
| 590 |
-
'time': time,
|
| 591 |
-
'status': {'$in': ['pending', 'confirmed']}
|
| 592 |
-
})
|
| 593 |
-
|
| 594 |
-
if existing_appointment:
|
| 595 |
-
flash('This time slot is already booked. Please choose another time.', 'error')
|
| 596 |
-
return redirect(url_for('user_appointments'))
|
| 597 |
-
|
| 598 |
-
# Create appointment data
|
| 599 |
-
appointment_data = {
|
| 600 |
-
'user_id': session['user_id'],
|
| 601 |
-
'disease_type': disease_type,
|
| 602 |
-
'details_selected': details_selected,
|
| 603 |
-
'date': datetime.strptime(date_str, '%Y-%m-%d'), # Convert to datetime object
|
| 604 |
-
'time': time,
|
| 605 |
-
'notes': notes,
|
| 606 |
-
'status': 'pending',
|
| 607 |
-
# doctor will be set when a doctor confirms the appointment
|
| 608 |
-
'doctor': '',
|
| 609 |
-
'doctor_id': '',
|
| 610 |
-
'created_at': datetime.now()
|
| 611 |
-
}
|
| 612 |
-
|
| 613 |
-
# Insert appointment into database
|
| 614 |
-
mongo.db.appointments.insert_one(appointment_data)
|
| 615 |
-
|
| 616 |
-
flash('Appointment booked successfully! Please wait for confirmation.', 'success')
|
| 617 |
-
return redirect(url_for('user_appointments'))
|
| 618 |
-
|
| 619 |
-
# Get upcoming appointments for the user
|
| 620 |
-
upcoming_appointments = list(mongo.db.appointments.find(
|
| 621 |
-
{'user_id': session['user_id'], 'date': {'$gte': datetime.now()}}
|
| 622 |
-
).sort('date', 1))
|
| 623 |
-
|
| 624 |
-
# Get user's prediction history to suggest disease types
|
| 625 |
-
prediction_history = list(mongo.db.patient_history.find(
|
| 626 |
-
{'user_id': session['user_id']}
|
| 627 |
-
).sort('date', -1).limit(10))
|
| 628 |
-
|
| 629 |
-
return render_template('user/appointments.html',
|
| 630 |
-
upcoming_appointments=upcoming_appointments,
|
| 631 |
-
prediction_history=prediction_history)
|
| 632 |
-
|
| 633 |
-
# Cancel Appointment
|
| 634 |
-
@app.route('/user/cancel-appointment/<appointment_id>')
|
| 635 |
-
def cancel_appointment(appointment_id):
|
| 636 |
-
if 'user_id' not in session:
|
| 637 |
-
flash('Please log in to access this page!', 'error')
|
| 638 |
-
return redirect(url_for('login'))
|
| 639 |
-
|
| 640 |
-
# Update appointment status to cancelled
|
| 641 |
-
result = mongo.db.appointments.update_one(
|
| 642 |
-
{'_id': ObjectId(appointment_id), 'user_id': session['user_id']},
|
| 643 |
-
{'$set': {'status': 'cancelled'}}
|
| 644 |
-
)
|
| 645 |
-
|
| 646 |
-
if result.modified_count > 0:
|
| 647 |
-
flash('Appointment cancelled successfully!', 'success')
|
| 648 |
-
else:
|
| 649 |
-
flash('Appointment not found or you do not have permission to cancel it!', 'error')
|
| 650 |
-
|
| 651 |
-
return redirect(url_for('user_appointments'))
|
| 652 |
-
|
| 653 |
-
# Admin Appointments
|
| 654 |
-
@app.route('/admin/appointments')
|
| 655 |
-
def admin_appointments():
|
| 656 |
-
if 'user_id' not in session:
|
| 657 |
-
flash('Please log in to access this page!', 'error')
|
| 658 |
-
return redirect(url_for('login'))
|
| 659 |
-
|
| 660 |
-
# Check if user is admin
|
| 661 |
-
user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
|
| 662 |
-
if user['role'] != 'admin':
|
| 663 |
-
flash('Access denied!', 'error')
|
| 664 |
-
return redirect(url_for('user_dashboard'))
|
| 665 |
-
|
| 666 |
-
# Get pending appointments
|
| 667 |
-
pending_appointments = list(mongo.db.appointments.find(
|
| 668 |
-
{'status': 'pending'}
|
| 669 |
-
).sort('date', 1))
|
| 670 |
-
|
| 671 |
-
# Add patient information to pending appointments
|
| 672 |
-
for appointment in pending_appointments:
|
| 673 |
-
patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])})
|
| 674 |
-
appointment['patient_name'] = patient['name'] if patient else 'Unknown'
|
| 675 |
-
appointment['patient_email'] = patient['email'] if patient else 'Unknown'
|
| 676 |
-
|
| 677 |
-
# Get confirmed appointments
|
| 678 |
-
confirmed_appointments = list(mongo.db.appointments.find(
|
| 679 |
-
{'status': 'confirmed'}
|
| 680 |
-
).sort([('date', 1), ('time', 1)]))
|
| 681 |
-
|
| 682 |
-
# Add patient information to confirmed appointments
|
| 683 |
-
for appointment in confirmed_appointments:
|
| 684 |
-
patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])})
|
| 685 |
-
appointment['patient_name'] = patient['name'] if patient else 'Unknown'
|
| 686 |
-
appointment['patient_email'] = patient['email'] if patient else 'Unknown'
|
| 687 |
-
|
| 688 |
-
return render_template('admin/appointments.html',
|
| 689 |
-
pending_appointments=pending_appointments,
|
| 690 |
-
confirmed_appointments=confirmed_appointments)
|
| 691 |
-
|
| 692 |
-
# Confirm Appointment
|
| 693 |
-
@app.route('/admin/appointments/<appointment_id>/confirm', methods=['POST'])
|
| 694 |
-
def confirm_appointment(appointment_id):
|
| 695 |
-
if 'user_id' not in session:
|
| 696 |
-
flash('Please log in to access this page!', 'error')
|
| 697 |
-
return redirect(url_for('login'))
|
| 698 |
-
|
| 699 |
-
# Check if user is admin
|
| 700 |
-
user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
|
| 701 |
-
if user['role'] != 'admin':
|
| 702 |
-
flash('Access denied!', 'error')
|
| 703 |
-
return redirect(url_for('user_dashboard'))
|
| 704 |
-
|
| 705 |
-
# Update appointment status to confirmed
|
| 706 |
-
result = mongo.db.appointments.update_one(
|
| 707 |
-
{'_id': ObjectId(appointment_id)},
|
| 708 |
-
{'$set': {'status': 'confirmed'}}
|
| 709 |
-
)
|
| 710 |
-
|
| 711 |
-
if result.modified_count > 0:
|
| 712 |
-
flash('Appointment confirmed successfully!', 'success')
|
| 713 |
-
else:
|
| 714 |
-
flash('Appointment not found!', 'error')
|
| 715 |
-
|
| 716 |
-
return redirect(url_for('admin_appointments'))
|
| 717 |
-
|
| 718 |
-
# Reject Appointment
|
| 719 |
-
@app.route('/admin/appointments/<appointment_id>/reject', methods=['POST'])
|
| 720 |
-
def reject_appointment(appointment_id):
|
| 721 |
-
if 'user_id' not in session:
|
| 722 |
-
flash('Please log in to access this page!', 'error')
|
| 723 |
-
return redirect(url_for('login'))
|
| 724 |
-
|
| 725 |
-
# Check if user is admin
|
| 726 |
-
user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
|
| 727 |
-
if user['role'] != 'admin':
|
| 728 |
-
flash('Access denied!', 'error')
|
| 729 |
-
return redirect(url_for('user_dashboard'))
|
| 730 |
-
|
| 731 |
-
# Update appointment status to cancelled
|
| 732 |
-
result = mongo.db.appointments.update_one(
|
| 733 |
-
{'_id': ObjectId(appointment_id)},
|
| 734 |
-
{'$set': {'status': 'cancelled'}}
|
| 735 |
-
)
|
| 736 |
-
|
| 737 |
-
if result.modified_count > 0:
|
| 738 |
-
flash('Appointment rejected successfully!', 'success')
|
| 739 |
-
else:
|
| 740 |
-
flash('Appointment not found!', 'error')
|
| 741 |
-
|
| 742 |
-
return redirect(url_for('admin_appointments'))
|
| 743 |
-
|
| 744 |
-
# User dashboard
|
| 745 |
-
@app.route('/user/dashboard')
|
| 746 |
-
def user_dashboard():
|
| 747 |
-
print(f"Dashboard request - Session: {dict(session)}")
|
| 748 |
-
print(f"User ID in session: {session.get('user_id')}")
|
| 749 |
-
|
| 750 |
-
if 'user_id' not in session:
|
| 751 |
-
print("No user_id in session, redirecting to login")
|
| 752 |
-
flash('Please log in to access the dashboard!', 'error')
|
| 753 |
-
return redirect(url_for('login'))
|
| 754 |
-
|
| 755 |
-
# Get user data
|
| 756 |
-
user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
|
| 757 |
-
print(f"User from database: {user}")
|
| 758 |
-
|
| 759 |
-
# Get recent predictions (limit to 5)
|
| 760 |
-
recent_predictions = list(mongo.db.patient_history.find(
|
| 761 |
-
{'user_id': session['user_id']}
|
| 762 |
-
).sort('date', -1).limit(5))
|
| 763 |
-
|
| 764 |
-
return render_template('user/dashboard.html',
|
| 765 |
-
user=user,
|
| 766 |
-
recent_predictions=recent_predictions)
|
| 767 |
-
|
| 768 |
-
@app.route('/user/dashboard/data')
|
| 769 |
-
def user_dashboard_data():
|
| 770 |
-
"""Return JSON with data for Plotly charts for the logged-in user."""
|
| 771 |
-
if 'user_id' not in session:
|
| 772 |
-
return jsonify({'error': 'Unauthorized'}), 401
|
| 773 |
-
|
| 774 |
-
# 1) Prediction results distribution
|
| 775 |
-
prediction_pipeline = [
|
| 776 |
-
{'$match': {'user_id': session['user_id']}},
|
| 777 |
-
{'$group': {'_id': '$result', 'count': {'$sum': 1}}}
|
| 778 |
-
]
|
| 779 |
-
prediction_counts = {'positive': 0, 'negative': 0}
|
| 780 |
-
for doc in mongo.db.patient_history.aggregate(prediction_pipeline):
|
| 781 |
-
result = doc.get('_id', '').lower()
|
| 782 |
-
if 'likely' in result:
|
| 783 |
-
prediction_counts['positive'] += doc.get('count', 0)
|
| 784 |
-
else:
|
| 785 |
-
prediction_counts['negative'] += doc.get('count', 0)
|
| 786 |
-
|
| 787 |
-
# 2) Predictions over time (last 30 days)
|
| 788 |
-
from datetime import timedelta
|
| 789 |
-
today = datetime.now()
|
| 790 |
-
start_date = today - timedelta(days=29)
|
| 791 |
-
|
| 792 |
-
trend_pipeline = [
|
| 793 |
-
{'$match': {'user_id': session['user_id'], 'date': {'$gte': start_date}}},
|
| 794 |
-
{'$group': {'_id': {'$dateToString': {'format':'%Y-%m-%d', 'date':'$date'}}, 'count': {'$sum':1}}},
|
| 795 |
-
{'$sort': {'_id': 1}}
|
| 796 |
-
]
|
| 797 |
-
trend_docs = list(mongo.db.patient_history.aggregate(trend_pipeline))
|
| 798 |
-
# prepare arrays for the last 30 days
|
| 799 |
-
dates = []
|
| 800 |
-
counts = []
|
| 801 |
-
for i in range(30):
|
| 802 |
-
d = (start_date + timedelta(days=i)).strftime('%Y-%m-%d')
|
| 803 |
-
dates.append(d)
|
| 804 |
-
counts.append(0)
|
| 805 |
-
date_index = {dates[i]: i for i in range(len(dates))}
|
| 806 |
-
for doc in trend_docs:
|
| 807 |
-
idx = date_index.get(doc['_id'])
|
| 808 |
-
if idx is not None:
|
| 809 |
-
counts[idx] = doc['count']
|
| 810 |
-
|
| 811 |
-
# 3) Disease type distribution
|
| 812 |
-
disease_pipeline = [
|
| 813 |
-
{'$match': {'user_id': session['user_id']}},
|
| 814 |
-
{'$group': {'_id': '$disease_type', 'count': {'$sum': 1}}}
|
| 815 |
-
]
|
| 816 |
-
disease_docs = list(mongo.db.patient_history.aggregate(disease_pipeline))
|
| 817 |
-
disease_labels = [d['_id'] for d in disease_docs]
|
| 818 |
-
disease_counts = [d['count'] for d in disease_docs]
|
| 819 |
-
|
| 820 |
-
# 4) Confidence scores distribution
|
| 821 |
-
confidence_pipeline = [
|
| 822 |
-
{'$match': {'user_id': session['user_id']}},
|
| 823 |
-
{'$project': {'range': {'$concat': [
|
| 824 |
-
{'$cond': [{'$lt': ['$confidence', 50]}, '0-49%', '']},
|
| 825 |
-
{'$cond': [{'$and': [{'$gte': ['$confidence', 50]}, {'$lt': ['$confidence', 80]}]}, '50-79%', '']},
|
| 826 |
-
{'$cond': [{'$gte': ['$confidence', 80]}, '80-100%', '']}
|
| 827 |
-
]}}},
|
| 828 |
-
{'$group': {'_id': '$range', 'count': {'$sum': 1}}}
|
| 829 |
-
]
|
| 830 |
-
confidence_docs = list(mongo.db.patient_history.aggregate(confidence_pipeline))
|
| 831 |
-
confidence_labels = [d['_id'] for d in confidence_docs if d['_id']]
|
| 832 |
-
confidence_counts = [d['count'] for d in confidence_docs if d['_id']]
|
| 833 |
-
|
| 834 |
-
return jsonify({
|
| 835 |
-
'predictions': prediction_counts,
|
| 836 |
-
'trend': {'dates': dates, 'counts': counts},
|
| 837 |
-
'diseases': {'labels': disease_labels, 'counts': disease_counts},
|
| 838 |
-
'confidence': {'labels': confidence_labels, 'counts': confidence_counts}
|
| 839 |
-
})
|
| 840 |
-
|
| 841 |
-
# Admin dashboard
|
| 842 |
-
@app.route('/admin/dashboard')
|
| 843 |
-
def admin_dashboard():
|
| 844 |
-
if 'user_id' not in session:
|
| 845 |
-
flash('Please log in to access the dashboard!', 'error')
|
| 846 |
-
return redirect(url_for('login'))
|
| 847 |
-
|
| 848 |
-
# Check if user is admin
|
| 849 |
-
user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
|
| 850 |
-
if user['role'] != 'admin':
|
| 851 |
-
flash('Access denied!', 'error')
|
| 852 |
-
return redirect(url_for('user_dashboard'))
|
| 853 |
-
|
| 854 |
-
# Get statistics
|
| 855 |
-
total_users = mongo.db.users.count_documents({})
|
| 856 |
-
heart_predictions = mongo.db.patient_history.count_documents({'disease_type': 'Heart Disease'})
|
| 857 |
-
diabetes_predictions = mongo.db.patient_history.count_documents({'disease_type': 'Diabetes'})
|
| 858 |
-
parkinsons_predictions = mongo.db.patient_history.count_documents({'disease_type': "Parkinson's"})
|
| 859 |
-
|
| 860 |
-
# Get recent users (limit to 5)
|
| 861 |
-
recent_users = list(mongo.db.users.find().sort('created_at', -1).limit(5))
|
| 862 |
-
|
| 863 |
-
# Get all predictions (limit to 10)
|
| 864 |
-
all_predictions = list(mongo.db.patient_history.find().sort('date', -1).limit(10))
|
| 865 |
-
|
| 866 |
-
# Add user names to predictions
|
| 867 |
-
for prediction in all_predictions:
|
| 868 |
-
user = mongo.db.users.find_one({'_id': ObjectId(prediction['user_id'])})
|
| 869 |
-
prediction['user_name'] = user['name'] if user else 'Unknown'
|
| 870 |
-
|
| 871 |
-
return render_template('admin/dashboard.html',
|
| 872 |
-
total_users=total_users,
|
| 873 |
-
heart_predictions=heart_predictions,
|
| 874 |
-
diabetes_predictions=diabetes_predictions,
|
| 875 |
-
parkinsons_predictions=parkinsons_predictions,
|
| 876 |
-
recent_users=recent_users,
|
| 877 |
-
all_predictions=all_predictions)
|
| 878 |
-
|
| 879 |
-
# Heart Disease Prediction
|
| 880 |
-
@app.route('/user/heart-disease', methods=['GET', 'POST'])
|
| 881 |
-
def heart_disease_prediction():
|
| 882 |
-
if 'user_id' not in session:
|
| 883 |
-
flash('Please log in to access this page!', 'error')
|
| 884 |
-
return redirect(url_for('login'))
|
| 885 |
-
|
| 886 |
-
if request.method == 'POST':
|
| 887 |
-
try:
|
| 888 |
-
# Get form data
|
| 889 |
-
age = float(request.form['age'])
|
| 890 |
-
sex = float(request.form['sex'])
|
| 891 |
-
cp = float(request.form['cp'])
|
| 892 |
-
trestbps = float(request.form['trestbps'])
|
| 893 |
-
chol = float(request.form['chol'])
|
| 894 |
-
fbs = float(request.form['fbs'])
|
| 895 |
-
restecg = float(request.form['restecg'])
|
| 896 |
-
thalach = float(request.form['thalach'])
|
| 897 |
-
exang = float(request.form['exang'])
|
| 898 |
-
oldpeak = float(request.form['oldpeak'])
|
| 899 |
-
slope = float(request.form['slope'])
|
| 900 |
-
ca = float(request.form['ca'])
|
| 901 |
-
thal = float(request.form['thal'])
|
| 902 |
-
|
| 903 |
-
# Create input array for prediction
|
| 904 |
-
input_data = [age, sex, cp, trestbps, chol, fbs, restecg, thalach, exang, oldpeak, slope, ca, thal]
|
| 905 |
-
|
| 906 |
-
# Make prediction
|
| 907 |
-
prediction = heart_disease_model.predict([input_data])
|
| 908 |
-
|
| 909 |
-
# Check if predict_proba is available and properly configured
|
| 910 |
-
try:
|
| 911 |
-
if hasattr(heart_disease_model, 'predict_proba') and callable(getattr(heart_disease_model, 'predict_proba')):
|
| 912 |
-
probability = heart_disease_model.predict_proba([input_data])
|
| 913 |
-
# Determine confidence based on the prediction
|
| 914 |
-
if prediction[0] == 1:
|
| 915 |
-
confidence = probability[0][1] * 100
|
| 916 |
-
else:
|
| 917 |
-
confidence = probability[0][0] * 100
|
| 918 |
-
else:
|
| 919 |
-
# If predict_proba is not available, use a default confidence
|
| 920 |
-
confidence = 90.0 if prediction[0] == 1 else 10.0
|
| 921 |
-
except Exception as e:
|
| 922 |
-
# Handle any errors with predict_proba
|
| 923 |
-
print(f"Warning: predict_proba failed with error: {e}")
|
| 924 |
-
confidence = 90.0 if prediction[0] == 1 else 10.0
|
| 925 |
-
|
| 926 |
-
# Determine result
|
| 927 |
-
if prediction[0] == 1:
|
| 928 |
-
result = "The person is likely to have heart disease"
|
| 929 |
-
else:
|
| 930 |
-
result = "The person is unlikely to have heart disease"
|
| 931 |
-
|
| 932 |
-
# Store prediction in database
|
| 933 |
-
prediction_data = {
|
| 934 |
-
'user_id': session['user_id'],
|
| 935 |
-
'disease_type': 'Heart Disease',
|
| 936 |
-
'input_data': {
|
| 937 |
-
'age': age,
|
| 938 |
-
'sex': sex,
|
| 939 |
-
'cp': cp,
|
| 940 |
-
'trestbps': trestbps,
|
| 941 |
-
'chol': chol,
|
| 942 |
-
'fbs': fbs,
|
| 943 |
-
'restecg': restecg,
|
| 944 |
-
'thalach': thalach,
|
| 945 |
-
'exang': exang,
|
| 946 |
-
'oldpeak': oldpeak,
|
| 947 |
-
'slope': slope,
|
| 948 |
-
'ca': ca,
|
| 949 |
-
'thal': thal
|
| 950 |
-
},
|
| 951 |
-
'result': result,
|
| 952 |
-
'confidence': confidence,
|
| 953 |
-
'date': datetime.now()
|
| 954 |
-
}
|
| 955 |
-
|
| 956 |
-
mongo.db.patient_history.insert_one(prediction_data)
|
| 957 |
-
|
| 958 |
-
# Add prediction data to session for display
|
| 959 |
-
session['prediction_result'] = {
|
| 960 |
-
'disease_type': 'Heart Disease',
|
| 961 |
-
'result': result,
|
| 962 |
-
'confidence': confidence,
|
| 963 |
-
'input_data': prediction_data['input_data']
|
| 964 |
-
}
|
| 965 |
-
|
| 966 |
-
return redirect(url_for('prediction_result'))
|
| 967 |
-
|
| 968 |
-
except Exception as e:
|
| 969 |
-
flash(f'Error processing prediction: {str(e)}', 'error')
|
| 970 |
-
return redirect(url_for('heart_disease_prediction'))
|
| 971 |
-
|
| 972 |
-
return render_template('user/heart_disease.html')
|
| 973 |
-
|
| 974 |
-
# Diabetes Prediction
|
| 975 |
-
@app.route('/user/diabetes', methods=['GET', 'POST'])
|
| 976 |
-
def diabetes_prediction():
|
| 977 |
-
if 'user_id' not in session:
|
| 978 |
-
flash('Please log in to access this page!', 'error')
|
| 979 |
-
return redirect(url_for('login'))
|
| 980 |
-
|
| 981 |
-
if request.method == 'POST':
|
| 982 |
-
try:
|
| 983 |
-
# Get form data
|
| 984 |
-
pregnancies = float(request.form['pregnancies'])
|
| 985 |
-
glucose = float(request.form['glucose'])
|
| 986 |
-
blood_pressure = float(request.form['blood_pressure'])
|
| 987 |
-
skin_thickness = float(request.form['skin_thickness'])
|
| 988 |
-
insulin = float(request.form['insulin'])
|
| 989 |
-
bmi = float(request.form['bmi'])
|
| 990 |
-
diabetes_pedigree = float(request.form['diabetes_pedigree'])
|
| 991 |
-
age = float(request.form['age'])
|
| 992 |
-
|
| 993 |
-
# Create input array for prediction
|
| 994 |
-
input_data = [pregnancies, glucose, blood_pressure, skin_thickness, insulin, bmi, diabetes_pedigree, age]
|
| 995 |
-
|
| 996 |
-
# Make prediction
|
| 997 |
-
prediction = diabetes_model.predict([input_data])
|
| 998 |
-
|
| 999 |
-
# Check if predict_proba is available and properly configured
|
| 1000 |
-
try:
|
| 1001 |
-
if hasattr(diabetes_model, 'predict_proba') and callable(getattr(diabetes_model, 'predict_proba')):
|
| 1002 |
-
probability = diabetes_model.predict_proba([input_data])
|
| 1003 |
-
# Determine confidence based on the prediction
|
| 1004 |
-
if prediction[0] == 1:
|
| 1005 |
-
confidence = probability[0][1] * 100
|
| 1006 |
-
else:
|
| 1007 |
-
confidence = probability[0][0] * 100
|
| 1008 |
-
else:
|
| 1009 |
-
# If predict_proba is not available, use a default confidence
|
| 1010 |
-
confidence = 90.0 if prediction[0] == 1 else 10.0
|
| 1011 |
-
except Exception as e:
|
| 1012 |
-
# Handle any errors with predict_proba
|
| 1013 |
-
print(f"Warning: predict_proba failed with error: {e}")
|
| 1014 |
-
confidence = 90.0 if prediction[0] == 1 else 10.0
|
| 1015 |
-
|
| 1016 |
-
# Determine result
|
| 1017 |
-
if prediction[0] == 1:
|
| 1018 |
-
result = "The person is likely to have diabetes"
|
| 1019 |
-
else:
|
| 1020 |
-
result = "The person is unlikely to have diabetes"
|
| 1021 |
-
|
| 1022 |
-
# Store prediction in database
|
| 1023 |
-
prediction_data = {
|
| 1024 |
-
'user_id': session['user_id'],
|
| 1025 |
-
'disease_type': 'Diabetes',
|
| 1026 |
-
'input_data': {
|
| 1027 |
-
'pregnancies': pregnancies,
|
| 1028 |
-
'glucose': glucose,
|
| 1029 |
-
'blood_pressure': blood_pressure,
|
| 1030 |
-
'skin_thickness': skin_thickness,
|
| 1031 |
-
'insulin': insulin,
|
| 1032 |
-
'bmi': bmi,
|
| 1033 |
-
'diabetes_pedigree': diabetes_pedigree,
|
| 1034 |
-
'age': age
|
| 1035 |
-
},
|
| 1036 |
-
'result': result,
|
| 1037 |
-
'confidence': confidence,
|
| 1038 |
-
'date': datetime.now()
|
| 1039 |
-
}
|
| 1040 |
-
|
| 1041 |
-
mongo.db.patient_history.insert_one(prediction_data)
|
| 1042 |
-
|
| 1043 |
-
# Add prediction data to session for display
|
| 1044 |
-
session['prediction_result'] = {
|
| 1045 |
-
'disease_type': 'Diabetes',
|
| 1046 |
-
'result': result,
|
| 1047 |
-
'confidence': confidence,
|
| 1048 |
-
'input_data': prediction_data['input_data']
|
| 1049 |
-
}
|
| 1050 |
-
|
| 1051 |
-
return redirect(url_for('prediction_result'))
|
| 1052 |
-
|
| 1053 |
-
except Exception as e:
|
| 1054 |
-
flash(f'Error processing prediction: {str(e)}', 'error')
|
| 1055 |
-
return redirect(url_for('diabetes_prediction'))
|
| 1056 |
-
|
| 1057 |
-
return render_template('user/diabetes.html')
|
| 1058 |
-
|
| 1059 |
-
# Parkinson's Prediction
|
| 1060 |
-
@app.route('/user/parkinsons', methods=['GET', 'POST'])
|
| 1061 |
-
def parkinsons_prediction():
|
| 1062 |
-
if 'user_id' not in session:
|
| 1063 |
-
flash('Please log in to access this page!', 'error')
|
| 1064 |
-
return redirect(url_for('login'))
|
| 1065 |
-
|
| 1066 |
-
if request.method == 'POST':
|
| 1067 |
-
try:
|
| 1068 |
-
# Get form data
|
| 1069 |
-
fo = float(request.form['fo'])
|
| 1070 |
-
fhi = float(request.form['fhi'])
|
| 1071 |
-
flo = float(request.form['flo'])
|
| 1072 |
-
jitter_percent = float(request.form['jitter_percent'])
|
| 1073 |
-
jitter_abs = float(request.form['jitter_abs'])
|
| 1074 |
-
rap = float(request.form['rap'])
|
| 1075 |
-
ppq = float(request.form['ppq'])
|
| 1076 |
-
ddp = float(request.form['ddp'])
|
| 1077 |
-
shimmer = float(request.form['shimmer'])
|
| 1078 |
-
shimmer_db = float(request.form['shimmer_db'])
|
| 1079 |
-
apq3 = float(request.form['apq3'])
|
| 1080 |
-
apq5 = float(request.form['apq5'])
|
| 1081 |
-
apq = float(request.form['apq'])
|
| 1082 |
-
dda = float(request.form['dda'])
|
| 1083 |
-
nhr = float(request.form['nhr'])
|
| 1084 |
-
hnr = float(request.form['hnr'])
|
| 1085 |
-
rpde = float(request.form['rpde'])
|
| 1086 |
-
dfa = float(request.form['dfa'])
|
| 1087 |
-
spread1 = float(request.form['spread1'])
|
| 1088 |
-
spread2 = float(request.form['spread2'])
|
| 1089 |
-
d2 = float(request.form['d2'])
|
| 1090 |
-
ppe = float(request.form['ppe'])
|
| 1091 |
-
|
| 1092 |
-
# Create input array for prediction
|
| 1093 |
-
input_data = [fo, fhi, flo, jitter_percent, jitter_abs, rap, ppq, ddp, shimmer, shimmer_db,
|
| 1094 |
-
apq3, apq5, apq, dda, nhr, hnr, rpde, dfa, spread1, spread2, d2, ppe]
|
| 1095 |
-
|
| 1096 |
-
# Make prediction
|
| 1097 |
-
prediction = parkinsons_model.predict([input_data])
|
| 1098 |
-
|
| 1099 |
-
# Check if predict_proba is available and properly configured
|
| 1100 |
-
try:
|
| 1101 |
-
if hasattr(parkinsons_model, 'predict_proba') and callable(getattr(parkinsons_model, 'predict_proba')):
|
| 1102 |
-
probability = parkinsons_model.predict_proba([input_data])
|
| 1103 |
-
# Determine confidence based on the prediction
|
| 1104 |
-
if prediction[0] == 1:
|
| 1105 |
-
confidence = probability[0][1] * 100
|
| 1106 |
-
else:
|
| 1107 |
-
confidence = probability[0][0] * 100
|
| 1108 |
-
else:
|
| 1109 |
-
# If predict_proba is not available, use a default confidence
|
| 1110 |
-
confidence = 90.0 if prediction[0] == 1 else 10.0
|
| 1111 |
-
except Exception as e:
|
| 1112 |
-
# Handle any errors with predict_proba
|
| 1113 |
-
print(f"Warning: predict_proba failed with error: {e}")
|
| 1114 |
-
confidence = 90.0 if prediction[0] == 1 else 10.0
|
| 1115 |
-
|
| 1116 |
-
# Determine result
|
| 1117 |
-
if prediction[0] == 1:
|
| 1118 |
-
result = "The person is likely to have Parkinson's disease"
|
| 1119 |
-
else:
|
| 1120 |
-
result = "The person is unlikely to have Parkinson's disease"
|
| 1121 |
-
|
| 1122 |
-
# Store prediction in database
|
| 1123 |
-
prediction_data = {
|
| 1124 |
-
'user_id': session['user_id'],
|
| 1125 |
-
'disease_type': "Parkinson's",
|
| 1126 |
-
'input_data': {
|
| 1127 |
-
'fo': fo,
|
| 1128 |
-
'fhi': fhi,
|
| 1129 |
-
'flo': flo,
|
| 1130 |
-
'jitter_percent': jitter_percent,
|
| 1131 |
-
'jitter_abs': jitter_abs,
|
| 1132 |
-
'rap': rap,
|
| 1133 |
-
'ppq': ppq,
|
| 1134 |
-
'ddp': ddp,
|
| 1135 |
-
'shimmer': shimmer,
|
| 1136 |
-
'shimmer_db': shimmer_db,
|
| 1137 |
-
'apq3': apq3,
|
| 1138 |
-
'apq5': apq5,
|
| 1139 |
-
'apq': apq,
|
| 1140 |
-
'dda': dda,
|
| 1141 |
-
'nhr': nhr,
|
| 1142 |
-
'hnr': hnr,
|
| 1143 |
-
'rpde': rpde,
|
| 1144 |
-
'dfa': dfa,
|
| 1145 |
-
'spread1': spread1,
|
| 1146 |
-
'spread2': spread2,
|
| 1147 |
-
'd2': d2,
|
| 1148 |
-
'ppe': ppe
|
| 1149 |
-
},
|
| 1150 |
-
'result': result,
|
| 1151 |
-
'confidence': confidence,
|
| 1152 |
-
'date': datetime.now()
|
| 1153 |
-
}
|
| 1154 |
-
|
| 1155 |
-
mongo.db.patient_history.insert_one(prediction_data)
|
| 1156 |
-
|
| 1157 |
-
# Add prediction data to session for display
|
| 1158 |
-
session['prediction_result'] = {
|
| 1159 |
-
'disease_type': "Parkinson's",
|
| 1160 |
-
'result': result,
|
| 1161 |
-
'confidence': confidence,
|
| 1162 |
-
'input_data': prediction_data['input_data']
|
| 1163 |
-
}
|
| 1164 |
-
|
| 1165 |
-
return redirect(url_for('prediction_result'))
|
| 1166 |
-
|
| 1167 |
-
except Exception as e:
|
| 1168 |
-
flash(f'Error processing prediction: {str(e)}', 'error')
|
| 1169 |
-
return redirect(url_for('parkinsons_prediction'))
|
| 1170 |
-
|
| 1171 |
-
return render_template('user/parkinsons.html')
|
| 1172 |
-
|
| 1173 |
-
# Prediction Result
|
| 1174 |
-
@app.route('/user/result')
|
| 1175 |
-
def prediction_result():
|
| 1176 |
-
if 'user_id' not in session:
|
| 1177 |
-
flash('Please log in to access this page!', 'error')
|
| 1178 |
-
return redirect(url_for('login'))
|
| 1179 |
-
|
| 1180 |
-
if 'prediction_result' not in session:
|
| 1181 |
-
flash('No prediction result found!', 'error')
|
| 1182 |
-
return redirect(url_for('user_dashboard'))
|
| 1183 |
-
|
| 1184 |
-
result = session['prediction_result']
|
| 1185 |
-
return render_template('user/result.html', result=result)
|
| 1186 |
-
|
| 1187 |
-
# Patient History
|
| 1188 |
-
@app.route('/user/history')
|
| 1189 |
-
def patient_history():
|
| 1190 |
-
if 'user_id' not in session:
|
| 1191 |
-
flash('Please log in to access this page!', 'error')
|
| 1192 |
-
return redirect(url_for('login'))
|
| 1193 |
-
|
| 1194 |
-
# Get all predictions for the user
|
| 1195 |
-
history = list(mongo.db.patient_history.find(
|
| 1196 |
-
{'user_id': session['user_id']}
|
| 1197 |
-
).sort('date', -1))
|
| 1198 |
-
|
| 1199 |
-
return render_template('user/history.html', history=history)
|
| 1200 |
-
|
| 1201 |
-
# Detailed Report
|
| 1202 |
-
@app.route('/user/report/<report_id>')
|
| 1203 |
-
def detailed_report(report_id):
|
| 1204 |
-
if 'user_id' not in session:
|
| 1205 |
-
flash('Please log in to access this page!', 'error')
|
| 1206 |
-
return redirect(url_for('login'))
|
| 1207 |
-
|
| 1208 |
-
# Get the report
|
| 1209 |
-
report = mongo.db.patient_history.find_one(
|
| 1210 |
-
{'_id': ObjectId(report_id), 'user_id': session['user_id']}
|
| 1211 |
-
)
|
| 1212 |
-
|
| 1213 |
-
if not report:
|
| 1214 |
-
flash('Report not found!', 'error')
|
| 1215 |
-
return redirect(url_for('patient_history'))
|
| 1216 |
-
|
| 1217 |
-
return render_template('user/report.html', report=report)
|
| 1218 |
-
|
| 1219 |
-
# Delete Report
|
| 1220 |
-
@app.route('/user/delete-report/<report_id>')
|
| 1221 |
-
def delete_report(report_id):
|
| 1222 |
-
if 'user_id' not in session:
|
| 1223 |
-
flash('Please log in to access this page!', 'error')
|
| 1224 |
-
return redirect(url_for('login'))
|
| 1225 |
-
|
| 1226 |
-
# Delete the report
|
| 1227 |
-
result = mongo.db.patient_history.delete_one(
|
| 1228 |
-
{'_id': ObjectId(report_id), 'user_id': session['user_id']}
|
| 1229 |
-
)
|
| 1230 |
-
|
| 1231 |
-
if result.deleted_count > 0:
|
| 1232 |
-
flash('Report deleted successfully!', 'success')
|
| 1233 |
-
else:
|
| 1234 |
-
flash('Report not found or you do not have permission to delete it!', 'error')
|
| 1235 |
-
|
| 1236 |
-
return redirect(url_for('patient_history'))
|
| 1237 |
-
|
| 1238 |
-
# Download Result as PDF (from session)
|
| 1239 |
-
@app.route('/user/download-result')
|
| 1240 |
-
def download_result():
|
| 1241 |
-
if 'user_id' not in session:
|
| 1242 |
-
flash('Please log in to access this page!', 'error')
|
| 1243 |
-
return redirect(url_for('login'))
|
| 1244 |
-
|
| 1245 |
-
if 'prediction_result' not in session:
|
| 1246 |
-
flash('No prediction result found!', 'error')
|
| 1247 |
-
return redirect(url_for('user_dashboard'))
|
| 1248 |
-
|
| 1249 |
-
result = session['prediction_result']
|
| 1250 |
-
|
| 1251 |
-
# Create PDF in memory
|
| 1252 |
-
buffer = io.BytesIO()
|
| 1253 |
-
c = canvas.Canvas(buffer, pagesize=letter)
|
| 1254 |
-
width, height = letter
|
| 1255 |
-
|
| 1256 |
-
# Add content to PDF
|
| 1257 |
-
c.setFont("Helvetica-Bold", 16)
|
| 1258 |
-
c.drawString(100, height - 50, "Multiple Disease Prediction System")
|
| 1259 |
-
|
| 1260 |
-
c.setFont("Helvetica-Bold", 14)
|
| 1261 |
-
c.drawString(100, height - 100, f"{result['disease_type']} Prediction Report")
|
| 1262 |
-
|
| 1263 |
-
c.setFont("Helvetica", 12)
|
| 1264 |
-
c.drawString(100, height - 130, f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M')}")
|
| 1265 |
-
c.drawString(100, height - 150, f"Result: {result['result']}")
|
| 1266 |
-
c.drawString(100, height - 170, f"Confidence: {result['confidence']:.2f}%")
|
| 1267 |
-
|
| 1268 |
-
# Add input data
|
| 1269 |
-
c.setFont("Helvetica-Bold", 12)
|
| 1270 |
-
c.drawString(100, height - 200, "Input Data:")
|
| 1271 |
-
|
| 1272 |
-
c.setFont("Helvetica", 10)
|
| 1273 |
-
y_position = height - 220
|
| 1274 |
-
for key, value in result['input_data'].items():
|
| 1275 |
-
c.drawString(120, y_position, f"{key.replace('_', ' ').title()}: {value}")
|
| 1276 |
-
y_position -= 15
|
| 1277 |
-
if y_position < 100: # Start new page if needed
|
| 1278 |
-
c.showPage()
|
| 1279 |
-
y_position = height - 100
|
| 1280 |
-
|
| 1281 |
-
# Add disclaimer
|
| 1282 |
-
c.setFont("Helvetica-Oblique", 10)
|
| 1283 |
-
c.drawString(100, 50, "Note: This prediction is based on machine learning algorithms and should not be")
|
| 1284 |
-
c.drawString(100, 35, "considered as a medical diagnosis. Please consult with a healthcare professional.")
|
| 1285 |
-
|
| 1286 |
-
c.save()
|
| 1287 |
-
|
| 1288 |
-
# Prepare response
|
| 1289 |
-
buffer.seek(0)
|
| 1290 |
-
return send_file(
|
| 1291 |
-
buffer,
|
| 1292 |
-
as_attachment=True,
|
| 1293 |
-
download_name=f"{result['disease_type']}_prediction_report.pdf",
|
| 1294 |
-
mimetype='application/pdf'
|
| 1295 |
-
)
|
| 1296 |
-
|
| 1297 |
-
# Download Report as PDF (from database)
|
| 1298 |
-
@app.route('/user/download-report/<report_id>')
|
| 1299 |
-
def download_report(report_id):
|
| 1300 |
-
if 'user_id' not in session:
|
| 1301 |
-
flash('Please log in to access this page!', 'error')
|
| 1302 |
-
return redirect(url_for('login'))
|
| 1303 |
-
|
| 1304 |
-
# Get the report
|
| 1305 |
-
report = mongo.db.patient_history.find_one(
|
| 1306 |
-
{'_id': ObjectId(report_id), 'user_id': session['user_id']}
|
| 1307 |
-
)
|
| 1308 |
-
|
| 1309 |
-
if not report:
|
| 1310 |
-
flash('Report not found!', 'error')
|
| 1311 |
-
return redirect(url_for('patient_history'))
|
| 1312 |
-
|
| 1313 |
-
# Create PDF in memory
|
| 1314 |
-
buffer = io.BytesIO()
|
| 1315 |
-
c = canvas.Canvas(buffer, pagesize=letter)
|
| 1316 |
-
width, height = letter
|
| 1317 |
-
|
| 1318 |
-
# Add content to PDF
|
| 1319 |
-
c.setFont("Helvetica-Bold", 16)
|
| 1320 |
-
c.drawString(100, height - 50, "Multiple Disease Prediction System")
|
| 1321 |
-
|
| 1322 |
-
c.setFont("Helvetica-Bold", 14)
|
| 1323 |
-
c.drawString(100, height - 100, f"{report['disease_type']} Prediction Report")
|
| 1324 |
-
|
| 1325 |
-
c.setFont("Helvetica", 12)
|
| 1326 |
-
c.drawString(100, height - 130, f"Date: {report['date'].strftime('%Y-%m-%d %H:%M')}")
|
| 1327 |
-
c.drawString(100, height - 150, f"Result: {report['result']}")
|
| 1328 |
-
c.drawString(100, height - 170, f"Confidence: {report['confidence']:.2f}%")
|
| 1329 |
-
|
| 1330 |
-
# Add input data
|
| 1331 |
-
c.setFont("Helvetica-Bold", 12)
|
| 1332 |
-
c.drawString(100, height - 200, "Input Data:")
|
| 1333 |
-
|
| 1334 |
-
c.setFont("Helvetica", 10)
|
| 1335 |
-
y_position = height - 220
|
| 1336 |
-
for key, value in report['input_data'].items():
|
| 1337 |
-
c.drawString(120, y_position, f"{key.replace('_', ' ').title()}: {value}")
|
| 1338 |
-
y_position -= 15
|
| 1339 |
-
if y_position < 100: # Start new page if needed
|
| 1340 |
-
c.showPage()
|
| 1341 |
-
y_position = height - 100
|
| 1342 |
-
|
| 1343 |
-
# Add disclaimer
|
| 1344 |
-
c.setFont("Helvetica-Oblique", 10)
|
| 1345 |
-
c.drawString(100, 50, "Note: This prediction is based on machine learning algorithms and should not be")
|
| 1346 |
-
c.drawString(100, 35, "considered as a medical diagnosis. Please consult with a healthcare professional.")
|
| 1347 |
-
|
| 1348 |
-
c.save()
|
| 1349 |
-
|
| 1350 |
-
# Prepare response
|
| 1351 |
-
buffer.seek(0)
|
| 1352 |
-
return send_file(
|
| 1353 |
-
buffer,
|
| 1354 |
-
as_attachment=True,
|
| 1355 |
-
download_name=f"{report['disease_type']}_prediction_report_{report_id}.pdf",
|
| 1356 |
-
mimetype='application/pdf'
|
| 1357 |
-
)
|
| 1358 |
-
|
| 1359 |
-
# Doctor Appointments
|
| 1360 |
-
@app.route('/doctor/appointments')
|
| 1361 |
-
def doctor_appointments():
|
| 1362 |
-
if 'user_id' not in session:
|
| 1363 |
-
flash('Please log in to access this page!', 'error')
|
| 1364 |
-
return redirect(url_for('login'))
|
| 1365 |
-
|
| 1366 |
-
# Check if user is doctor
|
| 1367 |
-
user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
|
| 1368 |
-
if user['role'] != 'doctor':
|
| 1369 |
-
flash('Access denied!', 'error')
|
| 1370 |
-
return redirect(url_for('user_dashboard'))
|
| 1371 |
-
|
| 1372 |
-
# Get pending appointments matching doctor's specialization
|
| 1373 |
-
# Map common specializations to disease keywords to improve matching
|
| 1374 |
-
specialization_map = {
|
| 1375 |
-
'Cardiologist': ['heart', 'cardio', 'cardiologist'],
|
| 1376 |
-
'Endocrinologist': ['diabetes', 'endocrine', 'endocrinologist'],
|
| 1377 |
-
"Neurologist": ['parkinson', 'neuro', 'neurologist'],
|
| 1378 |
-
'General Practitioner': []
|
| 1379 |
-
}
|
| 1380 |
-
|
| 1381 |
-
spec = user.get('specialization', '') or ''
|
| 1382 |
-
keywords = []
|
| 1383 |
-
for key, vals in specialization_map.items():
|
| 1384 |
-
if spec.lower() == key.lower():
|
| 1385 |
-
keywords = vals
|
| 1386 |
-
break
|
| 1387 |
-
|
| 1388 |
-
if keywords:
|
| 1389 |
-
# build regex to match any of the keywords
|
| 1390 |
-
regex_parts = '|'.join([f"{kw}" for kw in keywords])
|
| 1391 |
-
pending_appointments = list(mongo.db.appointments.find({
|
| 1392 |
-
'disease_type': {'$regex': regex_parts, '$options': 'i'},
|
| 1393 |
-
'status': 'pending'
|
| 1394 |
-
}).sort('date', 1))
|
| 1395 |
-
else:
|
| 1396 |
-
# fallback: if no specialization or GP, show appointments assigned to this doctor or all pending
|
| 1397 |
-
pending_appointments = list(mongo.db.appointments.find({
|
| 1398 |
-
'$or': [
|
| 1399 |
-
{'doctor': {'$regex': user['name'], '$options': 'i'}},
|
| 1400 |
-
{'status': 'pending'}
|
| 1401 |
-
]
|
| 1402 |
-
}).sort('date', 1))
|
| 1403 |
-
|
| 1404 |
-
# Add patient information to pending appointments
|
| 1405 |
-
for appointment in pending_appointments:
|
| 1406 |
-
patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])})
|
| 1407 |
-
appointment['patient_name'] = patient['name'] if patient else 'Unknown'
|
| 1408 |
-
appointment['patient_email'] = patient['email'] if patient else 'Unknown'
|
| 1409 |
-
|
| 1410 |
-
# Get confirmed appointments
|
| 1411 |
-
confirmed_appointments = list(mongo.db.appointments.find({
|
| 1412 |
-
'doctor': {'$regex': user['name'], '$options': 'i'},
|
| 1413 |
-
'status': 'confirmed'
|
| 1414 |
-
}).sort([('date', 1), ('time', 1)]))
|
| 1415 |
-
|
| 1416 |
-
# Add patient information to confirmed appointments
|
| 1417 |
-
for appointment in confirmed_appointments:
|
| 1418 |
-
patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])})
|
| 1419 |
-
appointment['patient_name'] = patient['name'] if patient else 'Unknown'
|
| 1420 |
-
appointment['patient_email'] = patient['email'] if patient else 'Unknown'
|
| 1421 |
-
|
| 1422 |
-
return render_template('doctor/appointments.html',
|
| 1423 |
-
pending_appointments=pending_appointments,
|
| 1424 |
-
confirmed_appointments=confirmed_appointments,
|
| 1425 |
-
doctor=user)
|
| 1426 |
-
|
| 1427 |
-
|
| 1428 |
-
@app.route('/doctor/dashboard')
|
| 1429 |
-
def doctor_dashboard():
|
| 1430 |
-
if 'user_id' not in session:
|
| 1431 |
-
flash('Please log in to access the dashboard!', 'error')
|
| 1432 |
-
return redirect(url_for('login'))
|
| 1433 |
-
user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
|
| 1434 |
-
if user['role'] != 'doctor':
|
| 1435 |
-
flash('Access denied!', 'error')
|
| 1436 |
-
return redirect(url_for('user_dashboard'))
|
| 1437 |
-
|
| 1438 |
-
return render_template('doctor/dashboard.html')
|
| 1439 |
-
|
| 1440 |
-
|
| 1441 |
-
@app.route('/doctor/dashboard/data')
|
| 1442 |
-
def doctor_dashboard_data():
|
| 1443 |
-
"""Return JSON with data for Plotly charts for the logged-in doctor."""
|
| 1444 |
-
if 'user_id' not in session:
|
| 1445 |
-
return jsonify({'error': 'Unauthorized'}), 401
|
| 1446 |
-
|
| 1447 |
-
user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
|
| 1448 |
-
if not user or user.get('role') != 'doctor':
|
| 1449 |
-
return jsonify({'error': 'Forbidden'}), 403
|
| 1450 |
-
|
| 1451 |
-
# specialization keywords (reuse mapping)
|
| 1452 |
-
specialization_map = {
|
| 1453 |
-
'Cardiologist': ['heart', 'cardio', 'cardiologist'],
|
| 1454 |
-
'Endocrinologist': ['diabetes', 'endocrine', 'endocrinologist'],
|
| 1455 |
-
"Neurologist": ['parkinson', 'neuro', 'neurologist'],
|
| 1456 |
-
'General Practitioner': []
|
| 1457 |
-
}
|
| 1458 |
-
|
| 1459 |
-
spec = user.get('specialization', '') or ''
|
| 1460 |
-
keywords = []
|
| 1461 |
-
for key, vals in specialization_map.items():
|
| 1462 |
-
if spec.lower() == key.lower():
|
| 1463 |
-
keywords = vals
|
| 1464 |
-
break
|
| 1465 |
-
|
| 1466 |
-
# build base filter for appointments relevant to this doctor
|
| 1467 |
-
if keywords:
|
| 1468 |
-
regex_parts = '|'.join([f"{kw}" for kw in keywords])
|
| 1469 |
-
base_filter = {'disease_type': {'$regex': regex_parts, '$options': 'i'}}
|
| 1470 |
-
else:
|
| 1471 |
-
base_filter = {}
|
| 1472 |
-
|
| 1473 |
-
# 1) Appointment status counts (for this specialization or assigned to this doctor)
|
| 1474 |
-
status_pipeline = [
|
| 1475 |
-
{'$match': {'$or': [base_filter, {'doctor_id': session['user_id']}]}},
|
| 1476 |
-
{'$group': {'_id': '$status', 'count': {'$sum': 1}}}
|
| 1477 |
-
]
|
| 1478 |
-
status_counts = { 'pending':0, 'confirmed':0, 'rejected':0, 'cancelled':0 }
|
| 1479 |
-
for doc in mongo.db.appointments.aggregate(status_pipeline):
|
| 1480 |
-
# normalize status key and guard against unexpected values
|
| 1481 |
-
raw_key = doc.get('_id')
|
| 1482 |
-
if raw_key is None:
|
| 1483 |
-
key = 'unknown'
|
| 1484 |
-
else:
|
| 1485 |
-
key = str(raw_key).lower()
|
| 1486 |
-
# assign into known buckets if present, otherwise keep as-is under its key
|
| 1487 |
-
if key in status_counts:
|
| 1488 |
-
status_counts[key] = doc.get('count', 0)
|
| 1489 |
-
else:
|
| 1490 |
-
# for unexpected keys, add them to the dict to avoid key errors downstream
|
| 1491 |
-
status_counts[key] = doc.get('count', 0)
|
| 1492 |
-
|
| 1493 |
-
# 2) Trend: appointments per day for last 30 days
|
| 1494 |
-
from datetime import timedelta
|
| 1495 |
-
today = datetime.now()
|
| 1496 |
-
start_date = today - timedelta(days=29)
|
| 1497 |
-
match_trend = {'date': {'$gte': start_date}}
|
| 1498 |
-
if keywords:
|
| 1499 |
-
match_trend['$or'] = [base_filter, {'doctor_id': session['user_id']}]
|
| 1500 |
-
else:
|
| 1501 |
-
base_filter = {}
|
| 1502 |
-
|
| 1503 |
-
trend_pipeline = [
|
| 1504 |
-
{'$match': match_trend},
|
| 1505 |
-
{'$group': {'_id': {'$dateToString': {'format':'%Y-%m-%d', 'date':'$date'}}, 'count': {'$sum':1}}},
|
| 1506 |
-
{'$sort': {'_id': 1}}
|
| 1507 |
-
]
|
| 1508 |
-
trend_docs = list(mongo.db.appointments.aggregate(trend_pipeline))
|
| 1509 |
-
# prepare arrays for the last 30 days
|
| 1510 |
-
dates = []
|
| 1511 |
-
counts = []
|
| 1512 |
-
for i in range(30):
|
| 1513 |
-
d = (start_date + timedelta(days=i)).strftime('%Y-%m-%d')
|
| 1514 |
-
dates.append(d)
|
| 1515 |
-
counts.append(0)
|
| 1516 |
-
date_index = {dates[i]: i for i in range(len(dates))}
|
| 1517 |
-
for doc in trend_docs:
|
| 1518 |
-
idx = date_index.get(doc['_id'])
|
| 1519 |
-
if idx is not None:
|
| 1520 |
-
counts[idx] = doc['count']
|
| 1521 |
-
|
| 1522 |
-
# 3) Upcoming schedule: next 10 confirmed appointments for this doctor
|
| 1523 |
-
# use start of today to include today's appointments (date stored as date with 00:00 time)
|
| 1524 |
-
start_of_today = datetime(today.year, today.month, today.day)
|
| 1525 |
-
upcoming_docs = list(mongo.db.appointments.find({'doctor_id': session['user_id'], 'status':'confirmed', 'date': {'$gte': start_of_today}}).sort([('date',1),('time',1)]).limit(10))
|
| 1526 |
-
schedule_times = []
|
| 1527 |
-
schedule_labels = []
|
| 1528 |
-
for a in upcoming_docs:
|
| 1529 |
-
schedule_times.append(a['date'].strftime('%Y-%m-%d') + ' ' + a['time'])
|
| 1530 |
-
# patient name
|
| 1531 |
-
patient = mongo.db.users.find_one({'_id': ObjectId(a['user_id'])})
|
| 1532 |
-
schedule_labels.append(patient['name'] if patient else 'Unknown')
|
| 1533 |
-
|
| 1534 |
-
# 4) Patient distribution: unique patients per month (last 6 months)
|
| 1535 |
-
six_months_ago = today - timedelta(days=180)
|
| 1536 |
-
patient_pipeline = [
|
| 1537 |
-
{'$match': {'doctor_id': session['user_id'], 'status':'confirmed', 'date': {'$gte': six_months_ago}}},
|
| 1538 |
-
{'$group': {'_id': {'month': {'$month':'$date'}, 'year': {'$year':'$date'}}, 'patients': {'$addToSet': '$user_id'}}},
|
| 1539 |
-
{'$project': {'month':'$_id.month','year':'$_id.year','count': {'$size':'$patients'}}},
|
| 1540 |
-
{'$sort': {'year':1, 'month':1}}
|
| 1541 |
-
]
|
| 1542 |
-
patient_docs = list(mongo.db.appointments.aggregate(patient_pipeline))
|
| 1543 |
-
months = [f"{d['month']}-{d['year']}" for d in patient_docs]
|
| 1544 |
-
patient_counts = [d['count'] for d in patient_docs]
|
| 1545 |
-
|
| 1546 |
-
# 5) Details frequency (checkboxes)
|
| 1547 |
-
# Build a details match that limits to either the specialization OR appointments assigned to this doctor
|
| 1548 |
-
if keywords:
|
| 1549 |
-
details_match = {'$or': [base_filter, {'doctor_id': session['user_id']} ]}
|
| 1550 |
-
else:
|
| 1551 |
-
details_match = {'doctor_id': session['user_id']}
|
| 1552 |
-
|
| 1553 |
-
details_pipeline = [
|
| 1554 |
-
{'$match': details_match},
|
| 1555 |
-
{'$unwind': '$details_selected'},
|
| 1556 |
-
{'$group': {'_id': '$details_selected', 'count': {'$sum': 1}}},
|
| 1557 |
-
{'$sort': {'count': -1}}
|
| 1558 |
-
]
|
| 1559 |
-
details_docs = list(mongo.db.appointments.aggregate(details_pipeline))
|
| 1560 |
-
details_labels = [d['_id'] for d in details_docs]
|
| 1561 |
-
details_counts = [d['count'] for d in details_docs]
|
| 1562 |
-
|
| 1563 |
-
return jsonify({
|
| 1564 |
-
'status': status_counts,
|
| 1565 |
-
'trend': {'dates': dates, 'counts': counts},
|
| 1566 |
-
'schedule': {'times': schedule_times, 'labels': schedule_labels},
|
| 1567 |
-
'patient': {'months': months, 'counts': patient_counts},
|
| 1568 |
-
'details': {'labels': details_labels, 'counts': details_counts}
|
| 1569 |
-
})
|
| 1570 |
-
|
| 1571 |
-
# Confirm Appointment
|
| 1572 |
-
@app.route('/doctor/appointments/<appointment_id>/confirm', methods=['POST'])
|
| 1573 |
-
def doctor_confirm_appointment(appointment_id):
|
| 1574 |
-
if 'user_id' not in session:
|
| 1575 |
-
flash('Please log in to access this page!', 'error')
|
| 1576 |
-
return redirect(url_for('login'))
|
| 1577 |
-
|
| 1578 |
-
# Check if user is doctor
|
| 1579 |
-
user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
|
| 1580 |
-
if user['role'] != 'doctor':
|
| 1581 |
-
flash('Access denied!', 'error')
|
| 1582 |
-
return redirect(url_for('user_dashboard'))
|
| 1583 |
-
|
| 1584 |
-
# Update appointment status to confirmed
|
| 1585 |
-
# Check that the doctor doesn't already have a confirmed appointment at same date/time
|
| 1586 |
-
appointment = mongo.db.appointments.find_one({'_id': ObjectId(appointment_id)})
|
| 1587 |
-
if not appointment:
|
| 1588 |
-
flash('Appointment not found!', 'error')
|
| 1589 |
-
return redirect(url_for('doctor_appointments'))
|
| 1590 |
-
|
| 1591 |
-
# If appointment already has a doctor assigned and it's not this doctor, deny
|
| 1592 |
-
if appointment.get('doctor_id') and appointment.get('doctor_id') != session['user_id']:
|
| 1593 |
-
flash('This appointment has already been assigned to another doctor.', 'error')
|
| 1594 |
-
return redirect(url_for('doctor_appointments'))
|
| 1595 |
-
|
| 1596 |
-
# Check for conflicting confirmed appointments for this doctor
|
| 1597 |
-
conflict = mongo.db.appointments.find_one({
|
| 1598 |
-
'doctor_id': session['user_id'],
|
| 1599 |
-
'date': appointment['date'],
|
| 1600 |
-
'time': appointment['time'],
|
| 1601 |
-
'status': 'confirmed'
|
| 1602 |
-
})
|
| 1603 |
-
|
| 1604 |
-
if conflict:
|
| 1605 |
-
flash('You already have a confirmed appointment at this date and time.', 'error')
|
| 1606 |
-
return redirect(url_for('doctor_appointments'))
|
| 1607 |
-
|
| 1608 |
-
# Mark appointment as confirmed and assign to this doctor
|
| 1609 |
-
result = mongo.db.appointments.update_one(
|
| 1610 |
-
{'_id': ObjectId(appointment_id)},
|
| 1611 |
-
{'$set': {
|
| 1612 |
-
'status': 'confirmed',
|
| 1613 |
-
'doctor_id': session['user_id'],
|
| 1614 |
-
'doctor': user['name']
|
| 1615 |
-
}}
|
| 1616 |
-
)
|
| 1617 |
-
|
| 1618 |
-
if result.modified_count > 0:
|
| 1619 |
-
flash('Appointment confirmed successfully!', 'success')
|
| 1620 |
-
else:
|
| 1621 |
-
flash('Failed to confirm appointment. It may have been updated by someone else.', 'error')
|
| 1622 |
-
|
| 1623 |
-
return redirect(url_for('doctor_appointments'))
|
| 1624 |
-
|
| 1625 |
-
# Reject Appointment
|
| 1626 |
-
@app.route('/doctor/appointments/<appointment_id>/reject', methods=['POST'])
|
| 1627 |
-
def doctor_reject_appointment(appointment_id):
|
| 1628 |
-
if 'user_id' not in session:
|
| 1629 |
-
flash('Please log in to access this page!', 'error')
|
| 1630 |
-
return redirect(url_for('login'))
|
| 1631 |
-
|
| 1632 |
-
# Check if user is doctor
|
| 1633 |
-
user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
|
| 1634 |
-
if user['role'] != 'doctor':
|
| 1635 |
-
flash('Access denied!', 'error')
|
| 1636 |
-
return redirect(url_for('user_dashboard'))
|
| 1637 |
-
|
| 1638 |
-
# Update appointment status to rejected
|
| 1639 |
-
result = mongo.db.appointments.update_one(
|
| 1640 |
-
{'_id': ObjectId(appointment_id)},
|
| 1641 |
-
{'$set': {
|
| 1642 |
-
'status': 'rejected',
|
| 1643 |
-
'doctor_id': session['user_id'],
|
| 1644 |
-
'doctor': user['name']
|
| 1645 |
-
}}
|
| 1646 |
-
)
|
| 1647 |
-
|
| 1648 |
-
if result.modified_count > 0:
|
| 1649 |
-
flash('Appointment rejected successfully!', 'success')
|
| 1650 |
-
else:
|
| 1651 |
-
flash('Appointment not found!', 'error')
|
| 1652 |
-
|
| 1653 |
-
return redirect(url_for('doctor_appointments'))
|
| 1654 |
-
|
| 1655 |
-
# Chat functionality
|
| 1656 |
-
@app.route('/user/chat/<appointment_id>')
|
| 1657 |
-
def user_chat(appointment_id):
|
| 1658 |
-
if 'user_id' not in session:
|
| 1659 |
-
flash('Please log in to access this page!', 'error')
|
| 1660 |
-
return redirect(url_for('login'))
|
| 1661 |
-
|
| 1662 |
-
# Check if appointment exists and is confirmed
|
| 1663 |
-
appointment = mongo.db.appointments.find_one({
|
| 1664 |
-
'_id': ObjectId(appointment_id),
|
| 1665 |
-
'user_id': session['user_id'],
|
| 1666 |
-
'status': 'confirmed'
|
| 1667 |
-
})
|
| 1668 |
-
|
| 1669 |
-
if not appointment:
|
| 1670 |
-
flash('Appointment not found or not confirmed!', 'error')
|
| 1671 |
-
return redirect(url_for('user_appointments'))
|
| 1672 |
-
|
| 1673 |
-
# Get messages for this appointment
|
| 1674 |
-
messages = list(mongo.db.messages.find(
|
| 1675 |
-
{'appointment_id': appointment_id}
|
| 1676 |
-
).sort('timestamp', 1))
|
| 1677 |
-
|
| 1678 |
-
# Get doctor info
|
| 1679 |
-
doctor = mongo.db.users.find_one({'_id': ObjectId(appointment['doctor_id'])})
|
| 1680 |
-
|
| 1681 |
-
return render_template('user/chat.html',
|
| 1682 |
-
appointment=appointment,
|
| 1683 |
-
messages=messages,
|
| 1684 |
-
doctor=doctor)
|
| 1685 |
-
|
| 1686 |
-
@app.route('/doctor/chat/<appointment_id>')
|
| 1687 |
-
def doctor_chat(appointment_id):
|
| 1688 |
-
if 'user_id' not in session:
|
| 1689 |
-
flash('Please log in to access this page!', 'error')
|
| 1690 |
-
return redirect(url_for('login'))
|
| 1691 |
-
|
| 1692 |
-
# Check if user is doctor
|
| 1693 |
-
user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
|
| 1694 |
-
if user['role'] != 'doctor':
|
| 1695 |
-
flash('Access denied!', 'error')
|
| 1696 |
-
return redirect(url_for('user_dashboard'))
|
| 1697 |
-
|
| 1698 |
-
# Check if appointment exists and is confirmed
|
| 1699 |
-
appointment = mongo.db.appointments.find_one({
|
| 1700 |
-
'_id': ObjectId(appointment_id),
|
| 1701 |
-
'doctor_id': session['user_id'],
|
| 1702 |
-
'status': 'confirmed'
|
| 1703 |
-
})
|
| 1704 |
-
|
| 1705 |
-
if not appointment:
|
| 1706 |
-
flash('Appointment not found or not confirmed!', 'error')
|
| 1707 |
-
return redirect(url_for('doctor_appointments'))
|
| 1708 |
-
|
| 1709 |
-
# Get messages for this appointment
|
| 1710 |
-
messages = list(mongo.db.messages.find(
|
| 1711 |
-
{'appointment_id': appointment_id}
|
| 1712 |
-
).sort('timestamp', 1))
|
| 1713 |
-
|
| 1714 |
-
# Get patient info
|
| 1715 |
-
patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])})
|
| 1716 |
-
|
| 1717 |
-
return render_template('doctor/chat.html',
|
| 1718 |
-
appointment=appointment,
|
| 1719 |
-
messages=messages,
|
| 1720 |
-
patient=patient)
|
| 1721 |
-
|
| 1722 |
-
# Send message
|
| 1723 |
-
@app.route('/send_message', methods=['POST'])
|
| 1724 |
-
def send_message():
|
| 1725 |
-
if 'user_id' not in session:
|
| 1726 |
-
flash('Please log in to access this page!', 'error')
|
| 1727 |
-
return redirect(url_for('login'))
|
| 1728 |
-
|
| 1729 |
-
appointment_id = request.form['appointment_id']
|
| 1730 |
-
message_text = request.form['message']
|
| 1731 |
-
|
| 1732 |
-
# Check if appointment exists and is confirmed
|
| 1733 |
-
appointment = mongo.db.appointments.find_one({
|
| 1734 |
-
'_id': ObjectId(appointment_id),
|
| 1735 |
-
'status': 'confirmed'
|
| 1736 |
-
})
|
| 1737 |
-
|
| 1738 |
-
if not appointment:
|
| 1739 |
-
flash('Appointment not found or not confirmed!', 'error')
|
| 1740 |
-
return redirect(url_for('user_dashboard'))
|
| 1741 |
-
|
| 1742 |
-
# Check if user is authorized to send message (patient or doctor)
|
| 1743 |
-
if session['user_id'] not in [str(appointment['user_id']), str(appointment.get('doctor_id', ''))]:
|
| 1744 |
-
flash('Access denied!', 'error')
|
| 1745 |
-
return redirect(url_for('user_dashboard'))
|
| 1746 |
-
|
| 1747 |
-
# Create message
|
| 1748 |
-
message_data = {
|
| 1749 |
-
'appointment_id': appointment_id,
|
| 1750 |
-
'sender_id': session['user_id'],
|
| 1751 |
-
'message_text': message_text,
|
| 1752 |
-
'timestamp': datetime.now()
|
| 1753 |
-
}
|
| 1754 |
-
|
| 1755 |
-
# Insert message into database
|
| 1756 |
-
mongo.db.messages.insert_one(message_data)
|
| 1757 |
-
|
| 1758 |
-
# Redirect based on user role
|
| 1759 |
-
user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
|
| 1760 |
-
if user['role'] == 'doctor':
|
| 1761 |
-
return redirect(url_for('doctor_chat', appointment_id=appointment_id))
|
| 1762 |
-
else:
|
| 1763 |
-
return redirect(url_for('user_chat', appointment_id=appointment_id))
|
| 1764 |
-
|
| 1765 |
-
if __name__ == "__main__":
|
| 1766 |
-
app.run(host="0.0.0.0", port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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