HealthGuard-AI / app.py
kalyan9's picture
Update app.py
d49d951 verified
Raw History Blame Contribute Delete
74.9 kB
import os import pickle from flask import Flask, render_template, request, redirect, url_for, session, jsonify, send_file, flash from flask_pymongo import PyMongo from flask_session import Session from bson.objectid import ObjectId from werkzeug.security import generate_password_hash, check_password_hash import pandas as pd from datetime import datetime, timedelta import json import io from reportlab.lib.pagesizes import letter from reportlab.pdfgen import canvas from reportlab.lib.units import inch import bcrypt import pymongo from pymongo.errors import ServerSelectionTimeoutError, ConnectionFailure import ssl import certifi import logging # Set up comprehensive logging try: from logging_config import setup_logging, log_request_info logger = setup_logging() print("Comprehensive logging configured successfully") except Exception as e: # Fallback to basic logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.warning(f"Failed to configure comprehensive logging: {e}") app = Flask(__name__) # CRITICAL: Use a STRONG, FIXED secret key for session signing # This is ESSENTIAL for session persistence on Hugging Face Spaces # NEVER use a default or weak key - it will cause session loss app.secret_key = os.environ.get("SECRET_KEY") or "a_very_strong_static_key_here_change_this_before_production_DO_NOT_USE_DEFAULT" # Session configuration for production - Enhanced for Hugging Face Spaces # # CRITICAL Hugging Face Spaces Issue: # # Sessions don't persist because: # 1. Spaces are serverless containers # 2. Default Flask SESSION_TYPE='null' only keeps session in memory per request # 3. After redirect, session data is gone -> app thinks user is not logged in # # Solution: Use filesystem-based sessions so session data persists across requests # # Configuration details: # - SESSION_TYPE='filesystem' - Store sessions in filesystem instead of memory # - SESSION_FILE_DIR - Directory for session files (uses /tmp for HF Spaces) # - SESSION_PERMANENT=True - Make sessions permanent # - SESSION_USE_SIGNER=True - Add cryptographic signing for security # # FIX FOR WERKZEUG COMPATIBILITY ISSUE: # Added SESSION_SERIALIZER to use custom JSON serializer instead of pickle # This resolves the "cannot use a string pattern on a bytes-like object" error # MODEL VERSION WARNINGS: # The warnings about sklearn model versions are just warnings and won't break functionality. # The models should still work correctly even with the version mismatch. # For production, retrain models with the current scikit-learn version (1.3.2). from datetime import timedelta # Determine session directory - use /tmp for HF Spaces or local tmp session_dir = '/tmp/flask_session' if os.path.exists('/tmp') else './flask_session' try: os.makedirs(session_dir, exist_ok=True) except: session_dir = None # Will use default temp directory # Custom JSON serializer for Flask-Session to avoid pickle/Werkzeug issues class JSONSerializer: def dumps(self, obj): return json.dumps(obj) def loads(self, data): if isinstance(data, bytes): data = data.decode('utf-8') return json.loads(data) # CRITICAL: Proper session configuration for Hugging Face Spaces # Use SameSite=None and Secure=True so cookies are sent when the app is embedded # in an iframe or used behind proxies (like Hugging Face Spaces). Optionally # set SESSION_COOKIE_DOMAIN via env if you need to scope cookies to a domain. app.config.update( SECRET_KEY=os.environ.get("SECRET_KEY") or "a_very_strong_static_key_here_change_this_before_production_DO_NOT_USE_DEFAULT", # CRITICAL: These settings are required for Hugging Face Spaces SESSION_COOKIE_SECURE=True, # MUST be True for HTTPS (HF Spaces uses HTTPS) SESSION_COOKIE_HTTPONLY=True, # IMPORTANT: use 'None' to allow cross-site cookies (iframe). Browsers require # SameSite=None together with Secure=True for cross-site cookie delivery. SESSION_COOKIE_SAMESITE='None', # Optional domain for the session cookie (set via env). Useful in some deployments. SESSION_COOKIE_DOMAIN=os.environ.get('SESSION_COOKIE_DOMAIN') or None, PERMANENT_SESSION_LIFETIME=timedelta(hours=1), # Filesystem session storage for Hugging Face Spaces SESSION_TYPE='filesystem', SESSION_FILE_DIR=session_dir, SESSION_FILE_THRESHOLD=500, SESSION_FILE_MODE=0o600, SESSION_PERMANENT=True, SESSION_USE_SIGNER=True, # Adds extra security SESSION_SERIALIZER=JSONSerializer() # FIX: Use JSON instead of pickle ) # Initialize session Session(app) # Ensure session directory exists try: session_dir = app.config.get('SESSION_FILE_DIR') if session_dir: os.makedirs(session_dir, exist_ok=True) print(f"Session directory ensured: {session_dir}") except Exception as e: print(f"Warning: Could not create session directory: {e}") # FIX: Add ProxyFix for Hugging Face Spaces from werkzeug.middleware.proxy_fix import ProxyFix app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1) # Optional .env support for local development try: from dotenv import load_dotenv load_dotenv() print("Loaded .env (if present)") except Exception: pass # Import debug routes try: from debug_routes import add_debug_routes add_debug_routes(app) print("Debug routes added successfully") except Exception as e: print(f"Failed to add debug routes: {e}") # MongoDB Configuration (keep your existing code) def create_mongo_client(): """Create a secure MongoDB client for deployment.""" uri = os.environ.get('MONGODB_URI') if not uri: print("No MONGODB_URI provided - running in limited offline mode.") return None try: client_options = [ { 'tls': True, 'serverSelectionTimeoutMS': 5000, 'connectTimeoutMS': 5000, 'socketTimeoutMS': 5000, 'tlsCAFile': certifi.where() }, { 'tls': True, 'tlsAllowInvalidCertificates': True, 'tlsAllowInvalidHostnames': True, 'serverSelectionTimeoutMS': 5000, 'connectTimeoutMS': 5000, 'socketTimeoutMS': 5000 }, { 'tls': True, 'ssl': True, 'serverSelectionTimeoutMS': 5000, 'connectTimeoutMS': 5000, 'socketTimeoutMS': 5000 } ] client = None last_error = None for options in client_options: try: client = pymongo.MongoClient(uri, **options) client.admin.command('ping') print("MongoDB connected successfully ✅") return client except Exception as e: last_error = e logger.warning(f"MongoDB connection attempt failed with options {options}: {e}") continue if last_error: raise last_error except (ServerSelectionTimeoutError, ConnectionFailure, Exception) as e: print("MongoDB connection failed ❌", e) logger.error(f"MongoDB connection failed: {e}") return None # Create MongoDB client mongo_client = create_mongo_client() if mongo_client: db = mongo_client.get_database(os.environ.get('MONGODB_DB', 'healthcare_db')) class MongoWrapper: def __init__(self, database, client): self.db = database self.cx = client mongo = MongoWrapper(db, mongo_client) print("MongoDB connection established successfully!") else: class _NullCollection: def find_one(self, *a, **k): return None def find(self, *a, **k): return [] def insert_one(self, *a, **k): raise RuntimeError("Database not available in this environment") def update_one(self, *a, **k): raise RuntimeError("Database not available in this environment") def delete_one(self, *a, **k): raise RuntimeError("Database not available in this environment") def count_documents(self, *a, **k): return 0 def aggregate(self, *a, **k): return [] class _NullDB: def __getattr__(self, name): return _NullCollection() class _NullMongoWrapper: def __init__(self): self.db = _NullDB() self.cx = None mongo = _NullMongoWrapper() print("Failed to establish MongoDB connection. Application will run in limited mode.") # Get the working directory working_dir = os.path.dirname(os.path.abspath(__file__)) # Load the saved models diabetes_model = pickle.load(open(f'{working_dir}/saved models/diabetes_model.sav', 'rb')) heart_disease_model = pickle.load(open(f'{working_dir}/saved models/heart_disease_model.sav', 'rb')) parkinsons_model = pickle.load(open(f'{working_dir}/saved models/parkinsons_model.sav', 'rb')) # FIX: Enhanced session debugging @app.before_request def before_request(): if request.endpoint and not request.endpoint.startswith('static'): logger.info(f"=== BEFORE REQUEST ===") logger.info(f"Endpoint: {request.endpoint}") logger.info(f"Method: {request.method}") logger.info(f"Session ID: {session.get('_id', 'No session ID')}") logger.info(f"Session Data: {dict(session)}") logger.info(f"User ID in session: {session.get('user_id')}") logger.info(f"Cookies: {request.cookies}") logger.info(f"======================") @app.after_request def after_request(response): if request.endpoint and not request.endpoint.startswith('static'): logger.info(f"=== AFTER REQUEST ===") logger.info(f"Status: {response.status_code}") logger.info(f"Session modified: {session.modified}") logger.info(f"Session Data: {dict(session)}") logger.info(f"=====================") return response # FIX: Add session persistence middleware @app.before_request def make_session_permanent(): session.permanent = True # Refresh session on each request to keep it alive session.modified = True # Routes for authentication @app.route('/') def index(): return render_template('index.html') @app.route('/register', methods=['GET', 'POST']) def register(): if mongo is None: flash('Database connection error. Please contact administrator.', 'error') return redirect(url_for('index')) if request.method == 'POST': name = request.form['name'] email = request.form['email'] phone = request.form['phone'] password = request.form['password'] confirm_password = request.form['confirm_password'] role = request.form.get('role', 'user') # Default to user specialization = request.form.get('specialization', '') # For doctors # Validate input if not name or not email or not phone or not password: flash('All fields are required!', 'error') return redirect(url_for('register')) # Check if passwords match if password != confirm_password: flash('Passwords do not match!', 'error') return redirect(url_for('register')) # Check password strength if len(password) < 6: flash('Password must be at least 6 characters long!', 'error') return redirect(url_for('register')) # Check if user already exists try: existing_user = mongo.db.users.find_one({'email': email}) if existing_user: flash('Email already registered!', 'error') return redirect(url_for('register')) except Exception as e: flash('Database error. Please try again later.', 'error') return redirect(url_for('register')) # Hash the password try: hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) except Exception as e: flash('Error processing password. Please try again.', 'error') return redirect(url_for('register')) # Insert new user into database user_data = { 'name': name, 'email': email, 'phone': phone, 'password': hashed_password, 'role': role, # user or doctor 'specialization': specialization if role == 'doctor' else '', 'created_at': datetime.now() } try: result = mongo.db.users.insert_one(user_data) if result.acknowledged: flash('Registration successful! Please log in.', 'success') return redirect(url_for('login')) else: flash('Registration failed. Please try again later.', 'error') return redirect(url_for('register')) except Exception as e: flash(f'Registration failed: {str(e)}', 'error') return redirect(url_for('register')) return render_template('auth/register.html') @app.route('/login', methods=['GET', 'POST']) def login(): logger.info(f"Login request method: {request.method}") logger.info(f"Session before login processing: {dict(session)}") logger.info(f"Request headers: {dict(request.headers)}") # CRITICAL: Do not clear session on GET request to /login # Only clear session on explicit logout if mongo is None: logger.error("Database connection is None") flash('Database connection error. Please contact administrator.', 'error') return redirect(url_for('index')) if request.method == 'POST': email = request.form['email'] password = request.form['password'] logger.info(f"Login attempt - Email: {email}") logger.info(f"Form data: email={email}, password={'[REDACTED]' if password else 'None'}") # Validate input if not email or not password: logger.warning("Email and password are required") flash('Email and password are required!', 'error') return redirect(url_for('login')) try: # Find user in database logger.info("Searching for user in database...") user = mongo.db.users.find_one({'email': email}) logger.info(f"User found: {user is not None}") if user and bcrypt.checkpw(password.encode('utf-8'), user['password']): logger.info("Password verified successfully") # Set session variables session['user_id'] = str(user['_id']) session['username'] = user['name'] session['user_email'] = user['email'] session['user_role'] = user['role'] session.permanent = True # Make session permanent logger.info(f"Session after login: {dict(session)}") # CRITICAL: Ensure session is properly saved before redirect # Force session to be saved session.modified = True # CRITICAL: Set response headers for proper cookie handling # Redirect based on role if user['role'] == 'admin': redirect_url = url_for('admin_dashboard') elif user['role'] == 'doctor': # send doctors to their appointments view redirect_url = url_for('doctor_appointments') else: redirect_url = url_for('user_dashboard') logger.info(f"Redirecting to: {redirect_url}") # Session has been marked modified and permanent above. Return a # normal redirect and let Flask-Session set the cookie header. response = redirect(redirect_url) logger.info(f"Response headers (pre-send): {dict(response.headers)}") return response else: logger.warning("Invalid credentials") flash('Invalid email or password!', 'error') return redirect(url_for('login')) except Exception as e: logger.error(f"Login error: {e}", exc_info=True) flash('Login failed. Please try again later.', 'error') return redirect(url_for('login')) logger.info(f"Session on GET request: {dict(session)}") return render_template('auth/login.html') @app.route('/logout') def logout(): logger.info("=== LOGOUT ===") session.clear() flash('You have been logged out successfully!', 'success') response = redirect(url_for('index')) # Clear session cookie response.set_cookie('session', '', expires=0) return response @app.route('/forgot-password', methods=['GET', 'POST']) def forgot_password(): if mongo is None: flash('Database connection error. Please contact administrator.', 'error') return redirect(url_for('index')) if request.method == 'POST': email = request.form['email'] try: user = mongo.db.users.find_one({'email': email}) if not user: flash('Email not found!', 'error') return redirect(url_for('forgot_password')) # Generate a 6-digit OTP and store it with expiry (10 minutes) import random otp = '{:06d}'.format(random.randint(0, 999999)) expiry = datetime.now() + timedelta(minutes=10) # Store OTP in a password_resets collection mongo.db.password_resets.update_one( {'email': email}, {'$set': {'otp': otp, 'expiry': expiry}}, upsert=True ) # Send OTP via Gmail SMTP using EMAIL_USER/EMAIL_PASSWORD environment variables. # We use a small helper in email_utils which wraps SMTP_SSL for secure sending. msg_body = f"Your OTP for password reset is: {otp}. It is valid for 10 minutes." try: from email_utils import send_email send_email(email, 'Password Reset OTP - Multiple Disease Prediction', msg_body) except Exception as e: print(f"Failed to send OTP email: {e}") flash('Failed to send OTP email. Please contact administrator.', 'error') return redirect(url_for('forgot_password')) flash('An OTP has been sent to your email. Please enter it to reset your password.', 'success') return redirect(url_for('verify_otp')) except Exception as e: flash('Database error. Please try again later.', 'error') return render_template('auth/forgot_password.html') @app.route('/verify-otp', methods=['GET', 'POST']) def verify_otp(): if request.method == 'POST': email = request.form['email'] otp = request.form['otp'] new_password = request.form['new_password'] # Validate input if not email or not otp or not new_password: flash('All fields are required!', 'error') return redirect(url_for('verify_otp')) record = mongo.db.password_resets.find_one({'email': email}) if not record: flash('No OTP request found for this email.', 'error') return redirect(url_for('verify_otp')) if datetime.now() > record['expiry']: flash('OTP has expired. Please request a new one.', 'error') return redirect(url_for('forgot_password')) if record['otp'] != otp: flash('Invalid OTP. Please try again.', 'error') return redirect(url_for('verify_otp')) # Check password strength if len(new_password) < 6: flash('Password must be at least 6 characters long!', 'error') return redirect(url_for('verify_otp')) # Update password for user try: hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt()) except Exception as e: flash('Error processing password. Please try again.', 'error') return redirect(url_for('verify_otp')) try: mongo.db.users.update_one({'email': email}, {'$set': {'password': hashed_password}}) except Exception as e: flash('Failed to update password. Please try again later.', 'error') return redirect(url_for('verify_otp')) # Remove the OTP record try: mongo.db.password_resets.delete_one({'email': email}) except Exception as e: # Log the error but don't fail the operation print(f'Failed to delete OTP record: {e}') flash('Password reset successful. Please log in with your new password.', 'success') return redirect(url_for('login')) return render_template('auth/verify_otp.html') # Profile Management @app.route('/profile', methods=['GET', 'POST']) def profile(): if mongo is None: flash('Database connection error. Please contact administrator.', 'error') return redirect(url_for('index')) if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) try: user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])}) except Exception as e: flash('Database error. Please try again later.', 'error') return redirect(url_for('user_dashboard')) if not user: flash('User not found!', 'error') return redirect(url_for('login')) if request.method == 'POST': # Get form data name = request.form['name'] email = request.form['email'] phone = request.form['phone'] current_password = request.form['current_password'] new_password = request.form['new_password'] confirm_password = request.form['confirm_password'] # Validate input if not name or not email or not phone or not current_password: flash('All required fields must be filled!', 'error') return redirect(url_for('profile')) # Verify current password if not bcrypt.checkpw(current_password.encode('utf-8'), user['password']): flash('Current password is incorrect!', 'error') return redirect(url_for('profile')) # Check if email is already taken by another user try: if email != user['email']: existing_user = mongo.db.users.find_one({'email': email, '_id': {'$ne': ObjectId(session['user_id'])}}) if existing_user: flash('Email is already taken by another user!', 'error') return redirect(url_for('profile')) except Exception as e: flash('Database error. Please try again later.', 'error') return redirect(url_for('profile')) # Prepare update data update_data = { 'name': name, 'email': email, 'phone': phone } # Update password if provided if new_password: if new_password != confirm_password: flash('New passwords do not match!', 'error') return redirect(url_for('profile')) # Check password strength if len(new_password) < 6: flash('New password must be at least 6 characters long!', 'error') return redirect(url_for('profile')) # Hash new password try: hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt()) update_data['password'] = hashed_password except Exception as e: flash('Error processing password. Please try again.', 'error') return redirect(url_for('profile')) # Update user in database try: result = mongo.db.users.update_one( {'_id': ObjectId(session['user_id'])}, {'$set': update_data} ) if result.modified_count > 0: # Update session data session['username'] = name session['user_email'] = email flash('Profile updated successfully!', 'success') return redirect(url_for('profile')) else: flash('No changes were made to your profile.', 'info') return redirect(url_for('profile')) except Exception as e: flash('Profile update failed. Please try again later.', 'error') return redirect(url_for('profile')) # Get prediction counts for statistics try: prediction_count = mongo.db.patient_history.count_documents({'user_id': session['user_id']}) heart_count = mongo.db.patient_history.count_documents({'user_id': session['user_id'], 'disease_type': 'Heart Disease'}) diabetes_count = mongo.db.patient_history.count_documents({'user_id': session['user_id'], 'disease_type': 'Diabetes'}) parkinsons_count = mongo.db.patient_history.count_documents({'user_id': session['user_id'], 'disease_type': "Parkinson's"}) except Exception as e: flash('Database error. Please try again later.', 'error') prediction_count = 0 heart_count = 0 diabetes_count = 0 parkinsons_count = 0 return render_template('user/profile.html', user=user, prediction_count=prediction_count, heart_count=heart_count, diabetes_count=diabetes_count, parkinsons_count=parkinsons_count) # User Appointments @app.route('/user/appointments', methods=['GET', 'POST']) def user_appointments(): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) if request.method == 'POST': # Get form data disease_type = request.form['disease_type'] date_str = request.form['date'] time = request.form['time'] notes = request.form['notes'] # Get checkbox details (symptoms, purpose of visit) details_selected = request.form.getlist('details') # Validate that date is in the future appointment_datetime = datetime.strptime(f"{date_str} {time}", '%Y-%m-%d %H:%M') if appointment_datetime <= datetime.now(): flash('Appointment date and time must be in the future!', 'error') return redirect(url_for('user_appointments')) # Check for overlapping appointments for the doctor # Since appointments are unassigned at booking, we check only for existing identical patient bookings existing_appointment = mongo.db.appointments.find_one({ 'user_id': session['user_id'], 'date': datetime.strptime(date_str, '%Y-%m-%d'), 'time': time, 'status': {'$in': ['pending', 'confirmed']} }) if existing_appointment: flash('This time slot is already booked. Please choose another time.', 'error') return redirect(url_for('user_appointments')) # Create appointment data appointment_data = { 'user_id': session['user_id'], 'disease_type': disease_type, 'details_selected': details_selected, 'date': datetime.strptime(date_str, '%Y-%m-%d'), # Convert to datetime object 'time': time, 'notes': notes, 'status': 'pending', # doctor will be set when a doctor confirms the appointment 'doctor': '', 'doctor_id': '', 'created_at': datetime.now() } # Insert appointment into database mongo.db.appointments.insert_one(appointment_data) flash('Appointment booked successfully! Please wait for confirmation.', 'success') return redirect(url_for('user_appointments')) # Get upcoming appointments for the user upcoming_appointments = list(mongo.db.appointments.find( {'user_id': session['user_id'], 'date': {'$gte': datetime.now()}} ).sort('date', 1)) # Get user's prediction history to suggest disease types prediction_history = list(mongo.db.patient_history.find( {'user_id': session['user_id']} ).sort('date', -1).limit(10)) return render_template('user/appointments.html', upcoming_appointments=upcoming_appointments, prediction_history=prediction_history) # Cancel Appointment @app.route('/user/cancel-appointment/<appointment_id>') def cancel_appointment(appointment_id): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) # Update appointment status to cancelled result = mongo.db.appointments.update_one( {'_id': ObjectId(appointment_id), 'user_id': session['user_id']}, {'$set': {'status': 'cancelled'}} ) if result.modified_count > 0: flash('Appointment cancelled successfully!', 'success') else: flash('Appointment not found or you do not have permission to cancel it!', 'error') return redirect(url_for('user_appointments')) # Admin Appointments @app.route('/admin/appointments') def admin_appointments(): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) # Check if user is admin user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])}) if user['role'] != 'admin': flash('Access denied!', 'error') return redirect(url_for('user_dashboard')) # Get pending appointments pending_appointments = list(mongo.db.appointments.find( {'status': 'pending'} ).sort('date', 1)) # Add patient information to pending appointments for appointment in pending_appointments: patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])}) appointment['patient_name'] = patient['name'] if patient else 'Unknown' appointment['patient_email'] = patient['email'] if patient else 'Unknown' # Get confirmed appointments confirmed_appointments = list(mongo.db.appointments.find( {'status': 'confirmed'} ).sort([('date', 1), ('time', 1)])) # Add patient information to confirmed appointments for appointment in confirmed_appointments: patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])}) appointment['patient_name'] = patient['name'] if patient else 'Unknown' appointment['patient_email'] = patient['email'] if patient else 'Unknown' return render_template('admin/appointments.html', pending_appointments=pending_appointments, confirmed_appointments=confirmed_appointments) # Confirm Appointment @app.route('/admin/appointments/<appointment_id>/confirm', methods=['POST']) def confirm_appointment(appointment_id): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) # Check if user is admin user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])}) if user['role'] != 'admin': flash('Access denied!', 'error') return redirect(url_for('user_dashboard')) # Update appointment status to confirmed result = mongo.db.appointments.update_one( {'_id': ObjectId(appointment_id)}, {'$set': {'status': 'confirmed'}} ) if result.modified_count > 0: flash('Appointment confirmed successfully!', 'success') else: flash('Appointment not found!', 'error') return redirect(url_for('admin_appointments')) # Reject Appointment @app.route('/admin/appointments/<appointment_id>/reject', methods=['POST']) def reject_appointment(appointment_id): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) # Check if user is admin user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])}) if user['role'] != 'admin': flash('Access denied!', 'error') return redirect(url_for('user_dashboard')) # Update appointment status to cancelled result = mongo.db.appointments.update_one( {'_id': ObjectId(appointment_id)}, {'$set': {'status': 'cancelled'}} ) if result.modified_count > 0: flash('Appointment rejected successfully!', 'success') else: flash('Appointment not found!', 'error') return redirect(url_for('admin_appointments')) # User dashboard - KEEPING THE BETTER IMPLEMENTATION @app.route('/user/dashboard') def user_dashboard(): logger.info(f"=== DASHBOARD REQUEST ===") logger.info(f"Session data: {dict(session)}") logger.info(f"User ID in session: {session.get('user_id')}") # Check if user is logged in if 'user_id' not in session: logger.warning("No user_id in session, redirecting to login") flash('Please log in to access the dashboard!', 'error') return redirect(url_for('login')) # Verify user exists in database try: user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])}) logger.info(f"User from database: {user is not None}") except Exception as e: logger.error(f"Error fetching user from database: {e}", exc_info=True) user = None if not user: logger.warning("User not found in database, clearing session and redirecting") session.clear() flash('User not found. Please log in again.', 'error') return redirect(url_for('login')) # CRITICAL: Ensure session stays alive session.permanent = True session.modified = True # Get recent predictions try: recent_predictions = list(mongo.db.patient_history.find( {'user_id': session['user_id']} ).sort('date', -1).limit(5)) logger.info(f"Found {len(recent_predictions)} recent predictions") except Exception as e: logger.error(f"Error fetching recent predictions: {e}", exc_info=True) recent_predictions = [] logger.info(f"Rendering dashboard for user: {user['name']}") return render_template('user/dashboard.html', user=user, recent_predictions=recent_predictions) @app.route('/user/dashboard/data') def user_dashboard_data(): """Return JSON with data for Plotly charts for the logged-in user.""" if 'user_id' not in session: return jsonify({'error': 'Unauthorized'}), 401 # 1) Prediction results distribution prediction_pipeline = [ {'$match': {'user_id': session['user_id']}}, {'$group': {'_id': '$result', 'count': {'$sum': 1}}} ] prediction_counts = {'positive': 0, 'negative': 0} for doc in mongo.db.patient_history.aggregate(prediction_pipeline): result = doc.get('_id', '').lower() if 'likely' in result: prediction_counts['positive'] += doc.get('count', 0) else: prediction_counts['negative'] += doc.get('count', 0) # 2) Predictions over time (last 30 days) from datetime import timedelta today = datetime.now() start_date = today - timedelta(days=29) trend_pipeline = [ {'$match': {'user_id': session['user_id'], 'date': {'$gte': start_date}}}, {'$group': {'_id': {'$dateToString': {'format':'%Y-%m-%d', 'date':'$date'}}, 'count': {'$sum':1}}}, {'$sort': {'_id': 1}} ] trend_docs = list(mongo.db.patient_history.aggregate(trend_pipeline)) # prepare arrays for the last 30 days dates = [] counts = [] for i in range(30): d = (start_date + timedelta(days=i)).strftime('%Y-%m-%d') dates.append(d) counts.append(0) date_index = {dates[i]: i for i in range(len(dates))} for doc in trend_docs: idx = date_index.get(doc['_id']) if idx is not None: counts[idx] = doc['count'] # 3) Disease type distribution disease_pipeline = [ {'$match': {'user_id': session['user_id']}}, {'$group': {'_id': '$disease_type', 'count': {'$sum': 1}}} ] disease_docs = list(mongo.db.patient_history.aggregate(disease_pipeline)) disease_labels = [d['_id'] for d in disease_docs] disease_counts = [d['count'] for d in disease_docs] # 4) Confidence scores distribution confidence_pipeline = [ {'$match': {'user_id': session['user_id']}}, {'$project': {'range': {'$concat': [ {'$cond': [{'$lt': ['$confidence', 50]}, '0-49%', '']}, {'$cond': [{'$and': [{'$gte': ['$confidence', 50]}, {'$lt': ['$confidence', 80]}]}, '50-79%', '']}, {'$cond': [{'$gte': ['$confidence', 80]}, '80-100%', '']} ]}}}, {'$group': {'_id': '$range', 'count': {'$sum': 1}}} ] confidence_docs = list(mongo.db.patient_history.aggregate(confidence_pipeline)) confidence_labels = [d['_id'] for d in confidence_docs if d['_id']] confidence_counts = [d['count'] for d in confidence_docs if d['_id']] return jsonify({ 'predictions': prediction_counts, 'trend': {'dates': dates, 'counts': counts}, 'diseases': {'labels': disease_labels, 'counts': disease_counts}, 'confidence': {'labels': confidence_labels, 'counts': confidence_counts} }) # Admin dashboard @app.route('/admin/dashboard') def admin_dashboard(): if 'user_id' not in session: flash('Please log in to access the dashboard!', 'error') return redirect(url_for('login')) # Check if user is admin user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])}) if user['role'] != 'admin': flash('Access denied!', 'error') return redirect(url_for('user_dashboard')) # Get statistics total_users = mongo.db.users.count_documents({}) heart_predictions = mongo.db.patient_history.count_documents({'disease_type': 'Heart Disease'}) diabetes_predictions = mongo.db.patient_history.count_documents({'disease_type': 'Diabetes'}) parkinsons_predictions = mongo.db.patient_history.count_documents({'disease_type': "Parkinson's"}) # Get recent users (limit to 5) recent_users = list(mongo.db.users.find().sort('created_at', -1).limit(5)) # Get all predictions (limit to 10) all_predictions = list(mongo.db.patient_history.find().sort('date', -1).limit(10)) # Add user names to predictions for prediction in all_predictions: user = mongo.db.users.find_one({'_id': ObjectId(prediction['user_id'])}) prediction['user_name'] = user['name'] if user else 'Unknown' return render_template('admin/dashboard.html', total_users=total_users, heart_predictions=heart_predictions, diabetes_predictions=diabetes_predictions, parkinsons_predictions=parkinsons_predictions, recent_users=recent_users, all_predictions=all_predictions) # Heart Disease Prediction @app.route('/user/heart-disease', methods=['GET', 'POST']) def heart_disease_prediction(): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) if request.method == 'POST': try: # Get form data age = float(request.form['age']) sex = float(request.form['sex']) cp = float(request.form['cp']) trestbps = float(request.form['trestbps']) chol = float(request.form['chol']) fbs = float(request.form['fbs']) restecg = float(request.form['restecg']) thalach = float(request.form['thalach']) exang = float(request.form['exang']) oldpeak = float(request.form['oldpeak']) slope = float(request.form['slope']) ca = float(request.form['ca']) thal = float(request.form['thal']) # Create input array for prediction input_data = [age, sex, cp, trestbps, chol, fbs, restecg, thalach, exang, oldpeak, slope, ca, thal] # Make prediction prediction = heart_disease_model.predict([input_data]) # Check if predict_proba is available and properly configured try: if hasattr(heart_disease_model, 'predict_proba') and callable(getattr(heart_disease_model, 'predict_proba')): probability = heart_disease_model.predict_proba([input_data]) # Determine confidence based on the prediction if prediction[0] == 1: confidence = probability[0][1] * 100 else: confidence = probability[0][0] * 100 else: # If predict_proba is not available, use a default confidence confidence = 90.0 if prediction[0] == 1 else 10.0 except Exception as e: # Handle any errors with predict_proba print(f"Warning: predict_proba failed with error: {e}") confidence = 90.0 if prediction[0] == 1 else 10.0 # Determine result if prediction[0] == 1: result = "The person is likely to have heart disease" else: result = "The person is unlikely to have heart disease" # Store prediction in database prediction_data = { 'user_id': session['user_id'], 'disease_type': 'Heart Disease', 'input_data': { 'age': age, 'sex': sex, 'cp': cp, 'trestbps': trestbps, 'chol': chol, 'fbs': fbs, 'restecg': restecg, 'thalach': thalach, 'exang': exang, 'oldpeak': oldpeak, 'slope': slope, 'ca': ca, 'thal': thal }, 'result': result, 'confidence': confidence, 'date': datetime.now() } mongo.db.patient_history.insert_one(prediction_data) # Add prediction data to session for display session['prediction_result'] = { 'disease_type': 'Heart Disease', 'result': result, 'confidence': confidence, 'input_data': prediction_data['input_data'] } return redirect(url_for('prediction_result')) except Exception as e: flash(f'Error processing prediction: {str(e)}', 'error') return redirect(url_for('heart_disease_prediction')) return render_template('user/heart_disease.html') # Diabetes Prediction @app.route('/user/diabetes', methods=['GET', 'POST']) def diabetes_prediction(): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) if request.method == 'POST': try: # Get form data pregnancies = float(request.form['pregnancies']) glucose = float(request.form['glucose']) blood_pressure = float(request.form['blood_pressure']) skin_thickness = float(request.form['skin_thickness']) insulin = float(request.form['insulin']) bmi = float(request.form['bmi']) diabetes_pedigree = float(request.form['diabetes_pedigree']) age = float(request.form['age']) # Create input array for prediction input_data = [pregnancies, glucose, blood_pressure, skin_thickness, insulin, bmi, diabetes_pedigree, age] # Make prediction prediction = diabetes_model.predict([input_data]) # Check if predict_proba is available and properly configured try: if hasattr(diabetes_model, 'predict_proba') and callable(getattr(diabetes_model, 'predict_proba')): probability = diabetes_model.predict_proba([input_data]) # Determine confidence based on the prediction if prediction[0] == 1: confidence = probability[0][1] * 100 else: confidence = probability[0][0] * 100 else: # If predict_proba is not available, use a default confidence confidence = 90.0 if prediction[0] == 1 else 10.0 except Exception as e: # Handle any errors with predict_proba print(f"Warning: predict_proba failed with error: {e}") confidence = 90.0 if prediction[0] == 1 else 10.0 # Determine result if prediction[0] == 1: result = "The person is likely to have diabetes" else: result = "The person is unlikely to have diabetes" # Store prediction in database prediction_data = { 'user_id': session['user_id'], 'disease_type': 'Diabetes', 'input_data': { 'pregnancies': pregnancies, 'glucose': glucose, 'blood_pressure': blood_pressure, 'skin_thickness': skin_thickness, 'insulin': insulin, 'bmi': bmi, 'diabetes_pedigree': diabetes_pedigree, 'age': age }, 'result': result, 'confidence': confidence, 'date': datetime.now() } mongo.db.patient_history.insert_one(prediction_data) # Add prediction data to session for display session['prediction_result'] = { 'disease_type': 'Diabetes', 'result': result, 'confidence': confidence, 'input_data': prediction_data['input_data'] } return redirect(url_for('prediction_result')) except Exception as e: flash(f'Error processing prediction: {str(e)}', 'error') return redirect(url_for('diabetes_prediction')) return render_template('user/diabetes.html') # Parkinson's Prediction @app.route('/user/parkinsons', methods=['GET', 'POST']) def parkinsons_prediction(): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) if request.method == 'POST': try: # Get form data fo = float(request.form['fo']) fhi = float(request.form['fhi']) flo = float(request.form['flo']) jitter_percent = float(request.form['jitter_percent']) jitter_abs = float(request.form['jitter_abs']) rap = float(request.form['rap']) ppq = float(request.form['ppq']) ddp = float(request.form['ddp']) shimmer = float(request.form['shimmer']) shimmer_db = float(request.form['shimmer_db']) apq3 = float(request.form['apq3']) apq5 = float(request.form['apq5']) apq = float(request.form['apq']) dda = float(request.form['dda']) nhr = float(request.form['nhr']) hnr = float(request.form['hnr']) rpde = float(request.form['rpde']) dfa = float(request.form['dfa']) spread1 = float(request.form['spread1']) spread2 = float(request.form['spread2']) d2 = float(request.form['d2']) ppe = float(request.form['ppe']) # Create input array for prediction input_data = [fo, fhi, flo, jitter_percent, jitter_abs, rap, ppq, ddp, shimmer, shimmer_db, apq3, apq5, apq, dda, nhr, hnr, rpde, dfa, spread1, spread2, d2, ppe] # Make prediction prediction = parkinsons_model.predict([input_data]) # Check if predict_proba is available and properly configured try: if hasattr(parkinsons_model, 'predict_proba') and callable(getattr(parkinsons_model, 'predict_proba')): probability = parkinsons_model.predict_proba([input_data]) # Determine confidence based on the prediction if prediction[0] == 1: confidence = probability[0][1] * 100 else: confidence = probability[0][0] * 100 else: # If predict_proba is not available, use a default confidence confidence = 90.0 if prediction[0] == 1 else 10.0 except Exception as e: # Handle any errors with predict_proba print(f"Warning: predict_proba failed with error: {e}") confidence = 90.0 if prediction[0] == 1 else 10.0 # Determine result if prediction[0] == 1: result = "The person is likely to have Parkinson's disease" else: result = "The person is unlikely to have Parkinson's disease" # Store prediction in database prediction_data = { 'user_id': session['user_id'], 'disease_type': "Parkinson's", 'input_data': { 'fo': fo, 'fhi': fhi, 'flo': flo, 'jitter_percent': jitter_percent, 'jitter_abs': jitter_abs, 'rap': rap, 'ppq': ppq, 'ddp': ddp, 'shimmer': shimmer, 'shimmer_db': shimmer_db, 'apq3': apq3, 'apq5': apq5, 'apq': apq, 'dda': dda, 'nhr': nhr, 'hnr': hnr, 'rpde': rpde, 'dfa': dfa, 'spread1': spread1, 'spread2': spread2, 'd2': d2, 'ppe': ppe }, 'result': result, 'confidence': confidence, 'date': datetime.now() } mongo.db.patient_history.insert_one(prediction_data) # Add prediction data to session for display session['prediction_result'] = { 'disease_type': "Parkinson's", 'result': result, 'confidence': confidence, 'input_data': prediction_data['input_data'] } return redirect(url_for('prediction_result')) except Exception as e: flash(f'Error processing prediction: {str(e)}', 'error') return redirect(url_for('parkinsons_prediction')) return render_template('user/parkinsons.html') # Prediction Result @app.route('/user/result') def prediction_result(): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) if 'prediction_result' not in session: flash('No prediction result found!', 'error') return redirect(url_for('user_dashboard')) result = session['prediction_result'] return render_template('user/result.html', result=result) # Patient History @app.route('/user/history') def patient_history(): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) # Get all predictions for the user history = list(mongo.db.patient_history.find( {'user_id': session['user_id']} ).sort('date', -1)) return render_template('user/history.html', history=history) # Detailed Report @app.route('/user/report/<report_id>') def detailed_report(report_id): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) # Get the report report = mongo.db.patient_history.find_one( {'_id': ObjectId(report_id), 'user_id': session['user_id']} ) if not report: flash('Report not found!', 'error') return redirect(url_for('patient_history')) return render_template('user/report.html', report=report) # Delete Report @app.route('/user/delete-report/<report_id>') def delete_report(report_id): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) # Delete the report result = mongo.db.patient_history.delete_one( {'_id': ObjectId(report_id), 'user_id': session['user_id']} ) if result.deleted_count > 0: flash('Report deleted successfully!', 'success') else: flash('Report not found or you do not have permission to delete it!', 'error') return redirect(url_for('patient_history')) # Download Result as PDF (from session) @app.route('/user/download-result') def download_result(): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) if 'prediction_result' not in session: flash('No prediction result found!', 'error') return redirect(url_for('user_dashboard')) result = session['prediction_result'] # Create PDF in memory buffer = io.BytesIO() c = canvas.Canvas(buffer, pagesize=letter) width, height = letter # Add content to PDF c.setFont("Helvetica-Bold", 16) c.drawString(100, height - 50, "Multiple Disease Prediction System") c.setFont("Helvetica-Bold", 14) c.drawString(100, height - 100, f"{result['disease_type']} Prediction Report") c.setFont("Helvetica", 12) c.drawString(100, height - 130, f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M')}") c.drawString(100, height - 150, f"Result: {result['result']}") c.drawString(100, height - 170, f"Confidence: {result['confidence']:.2f}%") # Add input data c.setFont("Helvetica-Bold", 12) c.drawString(100, height - 200, "Input Data:") c.setFont("Helvetica", 10) y_position = height - 220 for key, value in result['input_data'].items(): c.drawString(120, y_position, f"{key.replace('_', ' ').title()}: {value}") y_position -= 15 if y_position < 100: # Start new page if needed c.showPage() y_position = height - 100 # Add disclaimer c.setFont("Helvetica-Oblique", 10) c.drawString(100, 50, "Note: This prediction is based on machine learning algorithms and should not be") c.drawString(100, 35, "considered as a medical diagnosis. Please consult with a healthcare professional.") c.save() # Prepare response buffer.seek(0) return send_file( buffer, as_attachment=True, download_name=f"{result['disease_type']}_prediction_report.pdf", mimetype='application/pdf' ) # Download Report as PDF (from database) @app.route('/user/download-report/<report_id>') def download_report(report_id): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) # Get the report report = mongo.db.patient_history.find_one( {'_id': ObjectId(report_id), 'user_id': session['user_id']} ) if not report: flash('Report not found!', 'error') return redirect(url_for('patient_history')) # Create PDF in memory buffer = io.BytesIO() c = canvas.Canvas(buffer, pagesize=letter) width, height = letter # Add content to PDF c.setFont("Helvetica-Bold", 16) c.drawString(100, height - 50, "Multiple Disease Prediction System") c.setFont("Helvetica-Bold", 14) c.drawString(100, height - 100, f"{report['disease_type']} Prediction Report") c.setFont("Helvetica", 12) c.drawString(100, height - 130, f"Date: {report['date'].strftime('%Y-%m-%d %H:%M')}") c.drawString(100, height - 150, f"Result: {report['result']}") c.drawString(100, height - 170, f"Confidence: {report['confidence']:.2f}%") # Add input data c.setFont("Helvetica-Bold", 12) c.drawString(100, height - 200, "Input Data:") c.setFont("Helvetica", 10) y_position = height - 220 for key, value in report['input_data'].items(): c.drawString(120, y_position, f"{key.replace('_', ' ').title()}: {value}") y_position -= 15 if y_position < 100: # Start new page if needed c.showPage() y_position = height - 100 # Add disclaimer c.setFont("Helvetica-Oblique", 10) c.drawString(100, 50, "Note: This prediction is based on machine learning algorithms and should not be") c.drawString(100, 35, "considered as a medical diagnosis. Please consult with a healthcare professional.") c.save() # Prepare response buffer.seek(0) return send_file( buffer, as_attachment=True, download_name=f"{report['disease_type']}_prediction_report_{report_id}.pdf", mimetype='application/pdf' ) # Doctor Appointments @app.route('/doctor/appointments') def doctor_appointments(): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) # Check if user is doctor user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])}) if user['role'] != 'doctor': flash('Access denied!', 'error') return redirect(url_for('user_dashboard')) # Get pending appointments matching doctor's specialization # Map common specializations to disease keywords to improve matching specialization_map = { 'Cardiologist': ['heart', 'cardio', 'cardiologist'], 'Endocrinologist': ['diabetes', 'endocrine', 'endocrinologist'], "Neurologist": ['parkinson', 'neuro', 'neurologist'], 'General Practitioner': [] } spec = user.get('specialization', '') or '' keywords = [] for key, vals in specialization_map.items(): if spec.lower() == key.lower(): keywords = vals break if keywords: # build regex to match any of the keywords regex_parts = '|'.join([f"{kw}" for kw in keywords]) pending_appointments = list(mongo.db.appointments.find({ 'disease_type': {'$regex': regex_parts, '$options': 'i'}, 'status': 'pending' }).sort('date', 1)) else: # fallback: if no specialization or GP, show appointments assigned to this doctor or all pending pending_appointments = list(mongo.db.appointments.find({ '$or': [ {'doctor': {'$regex': user['name'], '$options': 'i'}}, {'status': 'pending'} ] }).sort('date', 1)) # Add patient information to pending appointments for appointment in pending_appointments: patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])}) appointment['patient_name'] = patient['name'] if patient else 'Unknown' appointment['patient_email'] = patient['email'] if patient else 'Unknown' # Get confirmed appointments confirmed_appointments = list(mongo.db.appointments.find({ 'doctor': {'$regex': user['name'], '$options': 'i'}, 'status': 'confirmed' }).sort([('date', 1), ('time', 1)])) # Add patient information to confirmed appointments for appointment in confirmed_appointments: patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])}) appointment['patient_name'] = patient['name'] if patient else 'Unknown' appointment['patient_email'] = patient['email'] if patient else 'Unknown' return render_template('doctor/appointments.html', pending_appointments=pending_appointments, confirmed_appointments=confirmed_appointments, doctor=user) @app.route('/doctor/dashboard') def doctor_dashboard(): if 'user_id' not in session: flash('Please log in to access the dashboard!', 'error') return redirect(url_for('login')) user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])}) if user['role'] != 'doctor': flash('Access denied!', 'error') return redirect(url_for('user_dashboard')) return render_template('doctor/dashboard.html') @app.route('/doctor/dashboard/data') def doctor_dashboard_data(): """Return JSON with data for Plotly charts for the logged-in doctor.""" if 'user_id' not in session: return jsonify({'error': 'Unauthorized'}), 401 user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])}) if not user or user.get('role') != 'doctor': return jsonify({'error': 'Forbidden'}), 403 # specialization keywords (reuse mapping) specialization_map = { 'Cardiologist': ['heart', 'cardio', 'cardiologist'], 'Endocrinologist': ['diabetes', 'endocrine', 'endocrinologist'], "Neurologist": ['parkinson', 'neuro', 'neurologist'], 'General Practitioner': [] } spec = user.get('specialization', '') or '' keywords = [] for key, vals in specialization_map.items(): if spec.lower() == key.lower(): keywords = vals break # build base filter for appointments relevant to this doctor if keywords: regex_parts = '|'.join([f"{kw}" for kw in keywords]) base_filter = {'disease_type': {'$regex': regex_parts, '$options': 'i'}} else: base_filter = {} # 1) Appointment status counts (for this specialization or assigned to this doctor) status_pipeline = [ {'$match': {'$or': [base_filter, {'doctor_id': session['user_id']}]}}, {'$group': {'_id': '$status', 'count': {'$sum': 1}}} ] status_counts = { 'pending':0, 'confirmed':0, 'rejected':0, 'cancelled':0 } for doc in mongo.db.appointments.aggregate(status_pipeline): # normalize status key and guard against unexpected values raw_key = doc.get('_id') if raw_key is None: key = 'unknown' else: key = str(raw_key).lower() # assign into known buckets if present, otherwise keep as-is under its key if key in status_counts: status_counts[key] = doc.get('count', 0) else: # for unexpected keys, add them to the dict to avoid key errors downstream status_counts[key] = doc.get('count', 0) # 2) Trend: appointments per day for last 30 days from datetime import timedelta today = datetime.now() start_date = today - timedelta(days=29) match_trend = {'date': {'$gte': start_date}} if keywords: match_trend['$or'] = [base_filter, {'doctor_id': session['user_id']}] else: base_filter = {} trend_pipeline = [ {'$match': match_trend}, {'$group': {'_id': {'$dateToString': {'format':'%Y-%m-%d', 'date':'$date'}}, 'count': {'$sum':1}}}, {'$sort': {'_id': 1}} ] trend_docs = list(mongo.db.appointments.aggregate(trend_pipeline)) # prepare arrays for the last 30 days dates = [] counts = [] for i in range(30): d = (start_date + timedelta(days=i)).strftime('%Y-%m-%d') dates.append(d) counts.append(0) date_index = {dates[i]: i for i in range(len(dates))} for doc in trend_docs: idx = date_index.get(doc['_id']) if idx is not None: counts[idx] = doc['count'] # 3) Upcoming schedule: next 10 confirmed appointments for this doctor # use start of today to include today's appointments (date stored as date with 00:00 time) start_of_today = datetime(today.year, today.month, today.day) 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)) schedule_times = [] schedule_labels = [] for a in upcoming_docs: schedule_times.append(a['date'].strftime('%Y-%m-%d') + ' ' + a['time']) # patient name patient = mongo.db.users.find_one({'_id': ObjectId(a['user_id'])}) schedule_labels.append(patient['name'] if patient else 'Unknown') # 4) Patient distribution: unique patients per month (last 6 months) six_months_ago = today - timedelta(days=180) patient_pipeline = [ {'$match': {'doctor_id': session['user_id'], 'status':'confirmed', 'date': {'$gte': six_months_ago}}}, {'$group': {'_id': {'month': {'$month':'$date'}, 'year': {'$year':'$date'}}, 'patients': {'$addToSet': '$user_id'}}}, {'$project': {'month':'$_id.month','year':'$_id.year','count': {'$size':'$patients'}}}, {'$sort': {'year':1, 'month':1}} ] patient_docs = list(mongo.db.appointments.aggregate(patient_pipeline)) months = [f"{d['month']}-{d['year']}" for d in patient_docs] patient_counts = [d['count'] for d in patient_docs] # 5) Details frequency (checkboxes) # Build a details match that limits to either the specialization OR appointments assigned to this doctor if keywords: details_match = {'$or': [base_filter, {'doctor_id': session['user_id']} ]} else: details_match = {'doctor_id': session['user_id']} details_pipeline = [ {'$match': details_match}, {'$unwind': '$details_selected'}, {'$group': {'_id': '$details_selected', 'count': {'$sum': 1}}}, {'$sort': {'count': -1}} ] details_docs = list(mongo.db.appointments.aggregate(details_pipeline)) details_labels = [d['_id'] for d in details_docs] details_counts = [d['count'] for d in details_docs] return jsonify({ 'status': status_counts, 'trend': {'dates': dates, 'counts': counts}, 'schedule': {'times': schedule_times, 'labels': schedule_labels}, 'patient': {'months': months, 'counts': patient_counts}, 'details': {'labels': details_labels, 'counts': details_counts} }) # Confirm Appointment @app.route('/doctor/appointments/<appointment_id>/confirm', methods=['POST']) def doctor_confirm_appointment(appointment_id): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) # Check if user is doctor user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])}) if user['role'] != 'doctor': flash('Access denied!', 'error') return redirect(url_for('user_dashboard')) # Update appointment status to confirmed # Check that the doctor doesn't already have a confirmed appointment at same date/time appointment = mongo.db.appointments.find_one({'_id': ObjectId(appointment_id)}) if not appointment: flash('Appointment not found!', 'error') return redirect(url_for('doctor_appointments')) # If appointment already has a doctor assigned and it's not this doctor, deny if appointment.get('doctor_id') and appointment.get('doctor_id') != session['user_id']: flash('This appointment has already been assigned to another doctor.', 'error') return redirect(url_for('doctor_appointments')) # Check for conflicting confirmed appointments for this doctor conflict = mongo.db.appointments.find_one({ 'doctor_id': session['user_id'], 'date': appointment['date'], 'time': appointment['time'], 'status': 'confirmed' }) if conflict: flash('You already have a confirmed appointment at this date and time.', 'error') return redirect(url_for('doctor_appointments')) # Mark appointment as confirmed and assign to this doctor result = mongo.db.appointments.update_one( {'_id': ObjectId(appointment_id)}, {'$set': { 'status': 'confirmed', 'doctor_id': session['user_id'], 'doctor': user['name'] }} ) if result.modified_count > 0: flash('Appointment confirmed successfully!', 'success') else: flash('Failed to confirm appointment. It may have been updated by someone else.', 'error') return redirect(url_for('doctor_appointments')) # Reject Appointment @app.route('/doctor/appointments/<appointment_id>/reject', methods=['POST']) def doctor_reject_appointment(appointment_id): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) # Check if user is doctor user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])}) if user['role'] != 'doctor': flash('Access denied!', 'error') return redirect(url_for('user_dashboard')) # Update appointment status to rejected result = mongo.db.appointments.update_one( {'_id': ObjectId(appointment_id)}, {'$set': { 'status': 'rejected', 'doctor_id': session['user_id'], 'doctor': user['name'] }} ) if result.modified_count > 0: flash('Appointment rejected successfully!', 'success') else: flash('Appointment not found!', 'error') return redirect(url_for('doctor_appointments')) # Chat functionality @app.route('/user/chat/<appointment_id>') def user_chat(appointment_id): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) # Check if appointment exists and is confirmed appointment = mongo.db.appointments.find_one({ '_id': ObjectId(appointment_id), 'user_id': session['user_id'], 'status': 'confirmed' }) if not appointment: flash('Appointment not found or not confirmed!', 'error') return redirect(url_for('user_appointments')) # Get messages for this appointment messages = list(mongo.db.messages.find( {'appointment_id': appointment_id} ).sort('timestamp', 1)) # Get doctor info doctor = mongo.db.users.find_one({'_id': ObjectId(appointment['doctor_id'])}) return render_template('user/chat.html', appointment=appointment, messages=messages, doctor=doctor) @app.route('/doctor/chat/<appointment_id>') def doctor_chat(appointment_id): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) # Check if user is doctor user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])}) if user['role'] != 'doctor': flash('Access denied!', 'error') return redirect(url_for('user_dashboard')) # Check if appointment exists and is confirmed appointment = mongo.db.appointments.find_one({ '_id': ObjectId(appointment_id), 'doctor_id': session['user_id'], 'status': 'confirmed' }) if not appointment: flash('Appointment not found or not confirmed!', 'error') return redirect(url_for('doctor_appointments')) # Get messages for this appointment messages = list(mongo.db.messages.find( {'appointment_id': appointment_id} ).sort('timestamp', 1)) # Get patient info patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])}) return render_template('doctor/chat.html', appointment=appointment, messages=messages, patient=patient) # Send message @app.route('/send_message', methods=['POST']) def send_message(): if 'user_id' not in session: flash('Please log in to access this page!', 'error') return redirect(url_for('login')) appointment_id = request.form['appointment_id'] message_text = request.form['message'] # Check if appointment exists and is confirmed appointment = mongo.db.appointments.find_one({ '_id': ObjectId(appointment_id), 'status': 'confirmed' }) if not appointment: flash('Appointment not found or not confirmed!', 'error') return redirect(url_for('user_dashboard')) # Check if user is authorized to send message (patient or doctor) if session['user_id'] not in [str(appointment['user_id']), str(appointment.get('doctor_id', ''))]: flash('Access denied!', 'error') return redirect(url_for('user_dashboard')) # Create message message_data = { 'appointment_id': appointment_id, 'sender_id': session['user_id'], 'message_text': message_text, 'timestamp': datetime.now() } # Insert message into database mongo.db.messages.insert_one(message_data) # Redirect based on user role user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])}) if user['role'] == 'doctor': return redirect(url_for('doctor_chat', appointment_id=appointment_id)) else: return redirect(url_for('user_chat', appointment_id=appointment_id)) if __name__ == "__main__": app.run(host="0.0.0.0", port=7860)
import os
import pickle
from flask import Flask, render_template, request, redirect, url_for, session, jsonify, send_file, flash
from flask_pymongo import PyMongo
from flask_session import Session
from bson.objectid import ObjectId
from werkzeug.security import generate_password_hash, check_password_hash
import pandas as pd
from datetime import datetime, timedelta
import json
import io
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.units import inch
import bcrypt
import pymongo
from pymongo.errors import ServerSelectionTimeoutError, ConnectionFailure
import ssl
import certifi
import logging
# Set up comprehensive logging
try:
from logging_config import setup_logging, log_request_info
logger = setup_logging()
print("Comprehensive logging configured successfully")
except Exception as e:
# Fallback to basic logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.warning(f"Failed to configure comprehensive logging: {e}")
app = Flask(__name__)
# CRITICAL: Use a STRONG, FIXED secret key for session signing
# This is ESSENTIAL for session persistence on Hugging Face Spaces
# NEVER use a default or weak key - it will cause session loss
app.secret_key = os.environ.get("SECRET_KEY") or "a_very_strong_static_key_here_change_this_before_production_DO_NOT_USE_DEFAULT"
# Session configuration for production - Enhanced for Hugging Face Spaces
#
# CRITICAL Hugging Face Spaces Issue:
#
# Sessions don't persist because:
# 1. Spaces are serverless containers
# 2. Default Flask SESSION_TYPE='null' only keeps session in memory per request
# 3. After redirect, session data is gone -> app thinks user is not logged in
#
# Solution: Use filesystem-based sessions so session data persists across requests
#
# Configuration details:
# - SESSION_TYPE='filesystem' - Store sessions in filesystem instead of memory
# - SESSION_FILE_DIR - Directory for session files (uses /tmp for HF Spaces)
# - SESSION_PERMANENT=True - Make sessions permanent
# - SESSION_USE_SIGNER=True - Add cryptographic signing for security
#
# FIX FOR WERKZEUG COMPATIBILITY ISSUE:
# Added SESSION_SERIALIZER to use custom JSON serializer instead of pickle
# This resolves the "cannot use a string pattern on a bytes-like object" error
# MODEL VERSION WARNINGS:
# The warnings about sklearn model versions are just warnings and won't break functionality.
# The models should still work correctly even with the version mismatch.
# For production, retrain models with the current scikit-learn version (1.3.2).
from datetime import timedelta
# Determine session directory - use /tmp for HF Spaces or local tmp
session_dir = '/tmp/flask_session' if os.path.exists('/tmp') else './flask_session'
try:
os.makedirs(session_dir, exist_ok=True)
except:
session_dir = None # Will use default temp directory
# Custom JSON serializer for Flask-Session to avoid pickle/Werkzeug issues
class JSONSerializer:
def dumps(self, obj):
return json.dumps(obj)
def loads(self, data):
if isinstance(data, bytes):
data = data.decode('utf-8')
return json.loads(data)
# CRITICAL: Proper session configuration for Hugging Face Spaces
# Use SameSite=None and Secure=True so cookies are sent when the app is embedded
# in an iframe or used behind proxies (like Hugging Face Spaces). Optionally
# set SESSION_COOKIE_DOMAIN via env if you need to scope cookies to a domain.
app.config.update(
SECRET_KEY=os.environ.get("SECRET_KEY") or "a_very_strong_static_key_here_change_this_before_production_DO_NOT_USE_DEFAULT",
# CRITICAL: These settings are required for Hugging Face Spaces
SESSION_COOKIE_SECURE=True, # MUST be True for HTTPS (HF Spaces uses HTTPS)
SESSION_COOKIE_HTTPONLY=True,
# IMPORTANT: use 'None' to allow cross-site cookies (iframe). Browsers require
# SameSite=None together with Secure=True for cross-site cookie delivery.
SESSION_COOKIE_SAMESITE='None',
# Optional domain for the session cookie (set via env). Useful in some deployments.
SESSION_COOKIE_DOMAIN=os.environ.get('SESSION_COOKIE_DOMAIN') or None,