kalyan9 commited on
Commit
9876bd8
·
verified ·
1 Parent(s): 8962334

Upload 35 files

Browse files
PRODUCTION_DEPLOYMENT.md ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # HealthGuard-AI Production Deployment Guide
2
+
3
+ This guide provides instructions for deploying the HealthGuard-AI application in a production environment.
4
+
5
+ ## Prerequisites
6
+
7
+ 1. Python 3.8 or higher
8
+ 2. MongoDB Atlas account or local MongoDB instance
9
+ 3. SSL certificates (for HTTPS in production)
10
+ 4. Domain name (optional but recommended)
11
+
12
+ ## Environment Setup
13
+
14
+ ### 1. Clone the Repository
15
+
16
+ ```bash
17
+ git clone <repository-url>
18
+ cd HealthGuard-AI
19
+ ```
20
+
21
+ ### 2. Create Virtual Environment
22
+
23
+ ```bash
24
+ python -m venv venv
25
+ source venv/bin/activate # On Windows: venv\Scripts\activate
26
+ ```
27
+
28
+ ### 3. Install Dependencies
29
+
30
+ ```bash
31
+ pip install -r requirements-prod.txt
32
+ ```
33
+
34
+ ## Configuration
35
+
36
+ ### 1. Environment Variables
37
+
38
+ Create a `.env` file in the project root with the following variables:
39
+
40
+ ```env
41
+ # MongoDB connection string
42
+ MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/database_name
43
+
44
+ # Database name (optional, defaults to healthcare_db)
45
+ MONGODB_DB=healthcare_db
46
+
47
+ # Flask secret key (generate a secure random string)
48
+ SECRET_KEY=your_secret_key_here
49
+
50
+ # SMTP settings for email notifications (optional)
51
+ SMTP_USER=your_email@gmail.com
52
+ SMTP_APP_PASSWORD=your_app_password
53
+ ```
54
+
55
+ ### 2. SSL Configuration
56
+
57
+ For production deployment, configure SSL certificates. You can use Let's Encrypt for free SSL certificates.
58
+
59
+ ## Deployment Options
60
+
61
+ ### Option 1: Using Gunicorn (Recommended for Linux)
62
+
63
+ ```bash
64
+ # Start the application with Gunicorn
65
+ gunicorn --workers 4 --bind 0.0.0.0:7860 --timeout 120 app:app
66
+ ```
67
+
68
+ ### Option 2: Using the Deployment Script
69
+
70
+ ```bash
71
+ # Install dependencies and start the application
72
+ python deployment.py --install-deps
73
+ ```
74
+
75
+ ### Option 3: Using Docker (Coming Soon)
76
+
77
+ Docker support will be added in a future release.
78
+
79
+ ## Production Best Practices
80
+
81
+ ### 1. Security
82
+
83
+ - Use strong, unique passwords for all accounts
84
+ - Enable two-factor authentication where possible
85
+ - Regularly update dependencies
86
+ - Use HTTPS for all communications
87
+ - Restrict access to sensitive files and directories
88
+
89
+ ### 2. Monitoring
90
+
91
+ - Set up logging for application errors
92
+ - Monitor database performance
93
+ - Set up alerts for critical system events
94
+ - Regularly backup the database
95
+
96
+ ### 3. Performance
97
+
98
+ - Use a CDN for static assets
99
+ - Enable caching where appropriate
100
+ - Optimize database queries
101
+ - Use a reverse proxy like Nginx
102
+
103
+ ### 4. Backup and Recovery
104
+
105
+ - Regularly backup the MongoDB database
106
+ - Test backup restoration procedures
107
+ - Keep multiple copies of backups in different locations
108
+
109
+ ## Troubleshooting
110
+
111
+ ### Common Issues
112
+
113
+ 1. **MongoDB Connection Issues**
114
+ - Check if the MongoDB URI is correct
115
+ - Verify network connectivity to the MongoDB server
116
+ - Ensure the IP address is whitelisted in MongoDB Atlas
117
+
118
+ 2. **Model Loading Errors**
119
+ - Verify that all model files are present in the `saved models` directory
120
+ - Check file permissions on model files
121
+
122
+ 3. **Email Sending Issues**
123
+ - Verify SMTP credentials
124
+ - Check if the email account allows less secure apps or app passwords
125
+
126
+ ### Logs
127
+
128
+ Check the application logs for error messages:
129
+
130
+ ```bash
131
+ # Check Gunicorn logs
132
+ tail -f /var/log/gunicorn/error.log
133
+
134
+ # Check application logs
135
+ tail -f app.log
136
+ ```
137
+
138
+ ## Scaling
139
+
140
+ For high-traffic deployments:
141
+
142
+ 1. Use a load balancer to distribute traffic
143
+ 2. Scale the application horizontally by adding more workers
144
+ 3. Use a managed database service for better performance
145
+ 4. Implement caching with Redis or Memcached
146
+
147
+ ## Maintenance
148
+
149
+ Regular maintenance tasks:
150
+
151
+ 1. Update dependencies regularly
152
+ 2. Monitor system resources
153
+ 3. Review and rotate logs
154
+ 4. Test backup and recovery procedures
155
+ 5. Monitor security vulnerabilities
156
+
157
+ ## Support
158
+
159
+ For issues or questions, please contact the development team or check the project documentation.
README.md CHANGED
@@ -1,14 +1,13 @@
1
- ---
2
- title: HealthGuard AI
3
- emoji: 🏃
4
- colorFrom: purple
5
- colorTo: yellow
6
- sdk: gradio
7
- sdk_version: 5.47.2
8
- app_file: app.py
9
- pinned: false
10
- license: mit
11
- short_description: predicts diseases and helps to book doctor appointments
12
- ---
13
-
14
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ ---
2
+ title: HealthGuard AI
3
+ emoji: 🦀
4
+ colorFrom: gray
5
+ colorTo: blue
6
+ sdk: gradio
7
+ sdk_version: 5.47.2
8
+ app_file: app.py
9
+ pinned: false
10
+ license: mit
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
app.py ADDED
@@ -0,0 +1,1703 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 bson.objectid import ObjectId
6
+ from werkzeug.security import generate_password_hash, check_password_hash
7
+ import pandas as pd
8
+ from datetime import datetime, timedelta
9
+ import json
10
+ import io
11
+ from reportlab.lib.pagesizes import letter
12
+ from reportlab.pdfgen import canvas
13
+ from reportlab.lib.units import inch
14
+ import bcrypt
15
+ import pymongo
16
+ from pymongo.errors import ServerSelectionTimeoutError, ConnectionFailure
17
+ import ssl
18
+ import certifi
19
+ import logging
20
+
21
+ # Set up logging
22
+ logging.basicConfig(level=logging.INFO)
23
+ logger = logging.getLogger(__name__)
24
+
25
+ app = Flask(__name__)
26
+ # Read SECRET_KEY from environment; use a fallback only if not provided.
27
+ app.secret_key = os.getenv('SECRET_KEY', 'fallback_secret_key')
28
+
29
+ # Optional .env support for local development. We load it if python-dotenv is available.
30
+ # This keeps secrets out of the repo while making local dev easy via a `.env` file.
31
+ try:
32
+ from dotenv import load_dotenv
33
+ # Load .env from project root silently (no error if not present)
34
+ load_dotenv()
35
+ print("Loaded .env (if present)")
36
+ except Exception:
37
+ # python-dotenv not installed or failed to load; proceed without it
38
+ pass
39
+
40
+ # MongoDB Configuration - safe, environment-driven and non-blocking for builds
41
+ def create_mongo_client():
42
+ """Create a secure MongoDB client for deployment.
43
+
44
+ This implementation reads the connection URI from the environment variable
45
+ MONGODB_URI. If the variable isn't set or the connection fails, the function
46
+ returns None so the application can continue to run in a limited mode.
47
+ """
48
+ uri = os.environ.get('MONGODB_URI')
49
+
50
+ if not uri:
51
+ print("No MONGODB_URI provided - running in limited offline mode.")
52
+ return None
53
+
54
+ try:
55
+ # Try different connection approaches to handle SSL issues
56
+ client_options = [
57
+ {
58
+ 'tls': True,
59
+ 'serverSelectionTimeoutMS': 5000,
60
+ 'connectTimeoutMS': 5000,
61
+ 'socketTimeoutMS': 5000,
62
+ 'tlsCAFile': certifi.where()
63
+ },
64
+ {
65
+ 'tls': True,
66
+ 'tlsAllowInvalidCertificates': True,
67
+ 'tlsAllowInvalidHostnames': True,
68
+ 'serverSelectionTimeoutMS': 5000,
69
+ 'connectTimeoutMS': 5000,
70
+ 'socketTimeoutMS': 5000
71
+ },
72
+ {
73
+ 'tls': True,
74
+ 'ssl': True,
75
+ 'serverSelectionTimeoutMS': 5000,
76
+ 'connectTimeoutMS': 5000,
77
+ 'socketTimeoutMS': 5000
78
+ }
79
+ ]
80
+
81
+ client = None
82
+ last_error = None
83
+
84
+ for options in client_options:
85
+ try:
86
+ client = pymongo.MongoClient(uri, **options)
87
+ # Test the connection (short timeout)
88
+ client.admin.command('ping')
89
+ print("MongoDB connected successfully ✅")
90
+ return client
91
+ except Exception as e:
92
+ last_error = e
93
+ logger.warning(f"MongoDB connection attempt failed with options {options}: {e}")
94
+ continue
95
+
96
+ # If all attempts fail, raise the last error
97
+ if last_error:
98
+ raise last_error
99
+
100
+ except (ServerSelectionTimeoutError, ConnectionFailure, Exception) as e:
101
+ print("MongoDB connection failed ❌", e)
102
+ logger.error(f"MongoDB connection failed: {e}")
103
+ return None
104
+
105
+
106
+ # Create MongoDB client (will be None in environments without DB access)
107
+ mongo_client = create_mongo_client()
108
+
109
+ if mongo_client:
110
+ # Access the database directly
111
+ db = mongo_client.get_database(os.environ.get('MONGODB_DB', 'healthcare_db'))
112
+
113
+ # Create a small wrapper to keep existing code working
114
+ class MongoWrapper:
115
+ def __init__(self, database, client):
116
+ self.db = database
117
+ self.cx = client
118
+
119
+ mongo = MongoWrapper(db, mongo_client)
120
+ print("MongoDB connection established successfully!")
121
+ else:
122
+ # Provide a safe null-wrapper so code that references mongo.db won't crash at import/runtime.
123
+ class _NullCollection:
124
+ def find_one(self, *a, **k):
125
+ return None
126
+ def find(self, *a, **k):
127
+ return []
128
+ def insert_one(self, *a, **k):
129
+ raise RuntimeError("Database not available in this environment")
130
+ def update_one(self, *a, **k):
131
+ raise RuntimeError("Database not available in this environment")
132
+ def delete_one(self, *a, **k):
133
+ raise RuntimeError("Database not available in this environment")
134
+ def count_documents(self, *a, **k):
135
+ return 0
136
+ def aggregate(self, *a, **k):
137
+ return []
138
+
139
+ class _NullDB:
140
+ def __getattr__(self, name):
141
+ return _NullCollection()
142
+
143
+ class _NullMongoWrapper:
144
+ def __init__(self):
145
+ self.db = _NullDB()
146
+ self.cx = None
147
+
148
+ mongo = _NullMongoWrapper()
149
+ print("Failed to establish MongoDB connection. Application will run in limited mode.")
150
+
151
+ # Get the working directory
152
+ working_dir = os.path.dirname(os.path.abspath(__file__))
153
+
154
+ # Load the saved models
155
+ diabetes_model = pickle.load(open(f'{working_dir}/saved models/diabetes_model.sav', 'rb'))
156
+ heart_disease_model = pickle.load(open(f'{working_dir}/saved models/heart_disease_model.sav', 'rb'))
157
+ parkinsons_model = pickle.load(open(f'{working_dir}/saved models/parkinsons_model.sav', 'rb'))
158
+
159
+ # Routes for authentication
160
+ @app.route('/')
161
+ def index():
162
+ return render_template('index.html')
163
+
164
+ @app.route('/register', methods=['GET', 'POST'])
165
+ def register():
166
+ if mongo is None:
167
+ flash('Database connection error. Please contact administrator.', 'error')
168
+ return redirect(url_for('index'))
169
+
170
+ if request.method == 'POST':
171
+ name = request.form['name']
172
+ email = request.form['email']
173
+ phone = request.form['phone']
174
+ password = request.form['password']
175
+ confirm_password = request.form['confirm_password']
176
+ role = request.form.get('role', 'user') # Default to user
177
+ specialization = request.form.get('specialization', '') # For doctors
178
+
179
+ # Validate input
180
+ if not name or not email or not phone or not password:
181
+ flash('All fields are required!', 'error')
182
+ return redirect(url_for('register'))
183
+
184
+ # Check if passwords match
185
+ if password != confirm_password:
186
+ flash('Passwords do not match!', 'error')
187
+ return redirect(url_for('register'))
188
+
189
+ # Check password strength
190
+ if len(password) < 6:
191
+ flash('Password must be at least 6 characters long!', 'error')
192
+ return redirect(url_for('register'))
193
+
194
+ # Check if user already exists
195
+ try:
196
+ existing_user = mongo.db.users.find_one({'email': email})
197
+ if existing_user:
198
+ flash('Email already registered!', 'error')
199
+ return redirect(url_for('register'))
200
+ except Exception as e:
201
+ flash('Database error. Please try again later.', 'error')
202
+ return redirect(url_for('register'))
203
+
204
+ # Hash the password
205
+ try:
206
+ hashed_password = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt())
207
+ except Exception as e:
208
+ flash('Error processing password. Please try again.', 'error')
209
+ return redirect(url_for('register'))
210
+
211
+ # Insert new user into database
212
+ user_data = {
213
+ 'name': name,
214
+ 'email': email,
215
+ 'phone': phone,
216
+ 'password': hashed_password,
217
+ 'role': role, # user or doctor
218
+ 'specialization': specialization if role == 'doctor' else '',
219
+ 'created_at': datetime.now()
220
+ }
221
+
222
+ try:
223
+ result = mongo.db.users.insert_one(user_data)
224
+ if result.inserted_id:
225
+ flash('Registration successful! Please log in.', 'success')
226
+ return redirect(url_for('login'))
227
+ else:
228
+ flash('Registration failed. Please try again later.', 'error')
229
+ return redirect(url_for('register'))
230
+ except Exception as e:
231
+ flash('Registration failed. Please try again later.', 'error')
232
+ return redirect(url_for('register'))
233
+
234
+ return render_template('auth/register.html')
235
+
236
+ @app.route('/login', methods=['GET', 'POST'])
237
+ def login():
238
+ if mongo is None:
239
+ flash('Database connection error. Please contact administrator.', 'error')
240
+ return redirect(url_for('index'))
241
+
242
+ if request.method == 'POST':
243
+ email = request.form['email']
244
+ password = request.form['password']
245
+
246
+ # Validate input
247
+ if not email or not password:
248
+ flash('Email and password are required!', 'error')
249
+ return redirect(url_for('login'))
250
+
251
+ try:
252
+ # Find user in database
253
+ user = mongo.db.users.find_one({'email': email})
254
+
255
+ if user and bcrypt.checkpw(password.encode('utf-8'), user['password']):
256
+ # Set session variables
257
+ session['user_id'] = str(user['_id'])
258
+ session['username'] = user['name']
259
+ session['user_email'] = user['email']
260
+ session['user_role'] = user['role']
261
+
262
+ # Redirect based on role
263
+ if user['role'] == 'admin':
264
+ return redirect(url_for('admin_dashboard'))
265
+ elif user['role'] == 'doctor':
266
+ # send doctors to their appointments view
267
+ return redirect(url_for('doctor_appointments'))
268
+ else:
269
+ return redirect(url_for('user_dashboard'))
270
+ else:
271
+ flash('Invalid email or password!', 'error')
272
+ return redirect(url_for('login'))
273
+ except Exception as e:
274
+ flash('Login failed. Please try again later.', 'error')
275
+ return redirect(url_for('login'))
276
+
277
+ return render_template('auth/login.html')
278
+
279
+ @app.route('/logout')
280
+ def logout():
281
+ session.clear()
282
+ flash('You have been logged out successfully!', 'success')
283
+ return redirect(url_for('index'))
284
+
285
+ @app.route('/forgot-password', methods=['GET', 'POST'])
286
+ def forgot_password():
287
+ if mongo is None:
288
+ flash('Database connection error. Please contact administrator.', 'error')
289
+ return redirect(url_for('index'))
290
+
291
+ if request.method == 'POST':
292
+ email = request.form['email']
293
+ try:
294
+ user = mongo.db.users.find_one({'email': email})
295
+ if not user:
296
+ flash('Email not found!', 'error')
297
+ return redirect(url_for('forgot_password'))
298
+
299
+ # Generate a 6-digit OTP and store it with expiry (10 minutes)
300
+ import random
301
+ otp = '{:06d}'.format(random.randint(0, 999999))
302
+ expiry = datetime.now() + timedelta(minutes=10)
303
+
304
+ # Store OTP in a password_resets collection
305
+ mongo.db.password_resets.update_one(
306
+ {'email': email},
307
+ {'$set': {'otp': otp, 'expiry': expiry}},
308
+ upsert=True
309
+ )
310
+
311
+ # Send OTP via Gmail SMTP using EMAIL_USER/EMAIL_PASSWORD environment variables.
312
+ # We use a small helper in email_utils which wraps SMTP_SSL for secure sending.
313
+ msg_body = f"Your OTP for password reset is: {otp}. It is valid for 10 minutes."
314
+ try:
315
+ from email_utils import send_email
316
+
317
+ send_email(email, 'Password Reset OTP - Multiple Disease Prediction', msg_body)
318
+ except Exception as e:
319
+ print(f"Failed to send OTP email: {e}")
320
+ flash('Failed to send OTP email. Please contact administrator.', 'error')
321
+ return redirect(url_for('forgot_password'))
322
+
323
+ flash('An OTP has been sent to your email. Please enter it to reset your password.', 'success')
324
+ return redirect(url_for('verify_otp'))
325
+ except Exception as e:
326
+ flash('Database error. Please try again later.', 'error')
327
+
328
+ return render_template('auth/forgot_password.html')
329
+
330
+
331
+ @app.route('/verify-otp', methods=['GET', 'POST'])
332
+ def verify_otp():
333
+ if request.method == 'POST':
334
+ email = request.form['email']
335
+ otp = request.form['otp']
336
+ new_password = request.form['new_password']
337
+
338
+ # Validate input
339
+ if not email or not otp or not new_password:
340
+ flash('All fields are required!', 'error')
341
+ return redirect(url_for('verify_otp'))
342
+
343
+ record = mongo.db.password_resets.find_one({'email': email})
344
+ if not record:
345
+ flash('No OTP request found for this email.', 'error')
346
+ return redirect(url_for('verify_otp'))
347
+
348
+ if datetime.now() > record['expiry']:
349
+ flash('OTP has expired. Please request a new one.', 'error')
350
+ return redirect(url_for('forgot_password'))
351
+
352
+ if record['otp'] != otp:
353
+ flash('Invalid OTP. Please try again.', 'error')
354
+ return redirect(url_for('verify_otp'))
355
+
356
+ # Check password strength
357
+ if len(new_password) < 6:
358
+ flash('Password must be at least 6 characters long!', 'error')
359
+ return redirect(url_for('verify_otp'))
360
+
361
+ # Update password for user
362
+ try:
363
+ hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
364
+ except Exception as e:
365
+ flash('Error processing password. Please try again.', 'error')
366
+ return redirect(url_for('verify_otp'))
367
+
368
+ try:
369
+ mongo.db.users.update_one({'email': email}, {'$set': {'password': hashed_password}})
370
+ except Exception as e:
371
+ flash('Failed to update password. Please try again later.', 'error')
372
+ return redirect(url_for('verify_otp'))
373
+
374
+ # Remove the OTP record
375
+ try:
376
+ mongo.db.password_resets.delete_one({'email': email})
377
+ except Exception as e:
378
+ # Log the error but don't fail the operation
379
+ print(f'Failed to delete OTP record: {e}')
380
+
381
+ flash('Password reset successful. Please log in with your new password.', 'success')
382
+ return redirect(url_for('login'))
383
+
384
+ return render_template('auth/verify_otp.html')
385
+
386
+ # Profile Management
387
+ @app.route('/profile', methods=['GET', 'POST'])
388
+ def profile():
389
+ if mongo is None:
390
+ flash('Database connection error. Please contact administrator.', 'error')
391
+ return redirect(url_for('index'))
392
+
393
+ if 'user_id' not in session:
394
+ flash('Please log in to access this page!', 'error')
395
+ return redirect(url_for('login'))
396
+
397
+ try:
398
+ user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
399
+ except Exception as e:
400
+ flash('Database error. Please try again later.', 'error')
401
+ return redirect(url_for('user_dashboard'))
402
+
403
+ if not user:
404
+ flash('User not found!', 'error')
405
+ return redirect(url_for('login'))
406
+
407
+ if request.method == 'POST':
408
+ # Get form data
409
+ name = request.form['name']
410
+ email = request.form['email']
411
+ phone = request.form['phone']
412
+ current_password = request.form['current_password']
413
+ new_password = request.form['new_password']
414
+ confirm_password = request.form['confirm_password']
415
+
416
+ # Validate input
417
+ if not name or not email or not phone or not current_password:
418
+ flash('All required fields must be filled!', 'error')
419
+ return redirect(url_for('profile'))
420
+
421
+ # Verify current password
422
+ if not bcrypt.checkpw(current_password.encode('utf-8'), user['password']):
423
+ flash('Current password is incorrect!', 'error')
424
+ return redirect(url_for('profile'))
425
+
426
+ # Check if email is already taken by another user
427
+ try:
428
+ if email != user['email']:
429
+ existing_user = mongo.db.users.find_one({'email': email, '_id': {'$ne': ObjectId(session['user_id'])}})
430
+ if existing_user:
431
+ flash('Email is already taken by another user!', 'error')
432
+ return redirect(url_for('profile'))
433
+ except Exception as e:
434
+ flash('Database error. Please try again later.', 'error')
435
+ return redirect(url_for('profile'))
436
+
437
+ # Prepare update data
438
+ update_data = {
439
+ 'name': name,
440
+ 'email': email,
441
+ 'phone': phone
442
+ }
443
+
444
+ # Update password if provided
445
+ if new_password:
446
+ if new_password != confirm_password:
447
+ flash('New passwords do not match!', 'error')
448
+ return redirect(url_for('profile'))
449
+
450
+ # Check password strength
451
+ if len(new_password) < 6:
452
+ flash('New password must be at least 6 characters long!', 'error')
453
+ return redirect(url_for('profile'))
454
+
455
+ # Hash new password
456
+ try:
457
+ hashed_password = bcrypt.hashpw(new_password.encode('utf-8'), bcrypt.gensalt())
458
+ update_data['password'] = hashed_password
459
+ except Exception as e:
460
+ flash('Error processing password. Please try again.', 'error')
461
+ return redirect(url_for('profile'))
462
+
463
+ # Update user in database
464
+ try:
465
+ result = mongo.db.users.update_one(
466
+ {'_id': ObjectId(session['user_id'])},
467
+ {'$set': update_data}
468
+ )
469
+
470
+ if result.modified_count > 0:
471
+ # Update session data
472
+ session['username'] = name
473
+ session['user_email'] = email
474
+
475
+ flash('Profile updated successfully!', 'success')
476
+ return redirect(url_for('profile'))
477
+ else:
478
+ flash('No changes were made to your profile.', 'info')
479
+ return redirect(url_for('profile'))
480
+ except Exception as e:
481
+ flash('Profile update failed. Please try again later.', 'error')
482
+ return redirect(url_for('profile'))
483
+
484
+ # Get prediction counts for statistics
485
+ try:
486
+ prediction_count = mongo.db.patient_history.count_documents({'user_id': session['user_id']})
487
+ heart_count = mongo.db.patient_history.count_documents({'user_id': session['user_id'], 'disease_type': 'Heart Disease'})
488
+ diabetes_count = mongo.db.patient_history.count_documents({'user_id': session['user_id'], 'disease_type': 'Diabetes'})
489
+ parkinsons_count = mongo.db.patient_history.count_documents({'user_id': session['user_id'], 'disease_type': "Parkinson's"})
490
+ except Exception as e:
491
+ flash('Database error. Please try again later.', 'error')
492
+ prediction_count = 0
493
+ heart_count = 0
494
+ diabetes_count = 0
495
+ parkinsons_count = 0
496
+
497
+ return render_template('user/profile.html',
498
+ user=user,
499
+ prediction_count=prediction_count,
500
+ heart_count=heart_count,
501
+ diabetes_count=diabetes_count,
502
+ parkinsons_count=parkinsons_count)
503
+
504
+ # User Appointments
505
+ @app.route('/user/appointments', methods=['GET', 'POST'])
506
+ def user_appointments():
507
+ if 'user_id' not in session:
508
+ flash('Please log in to access this page!', 'error')
509
+ return redirect(url_for('login'))
510
+
511
+ if request.method == 'POST':
512
+ # Get form data
513
+ disease_type = request.form['disease_type']
514
+ date_str = request.form['date']
515
+ time = request.form['time']
516
+ notes = request.form['notes']
517
+
518
+ # Get checkbox details (symptoms, purpose of visit)
519
+ details_selected = request.form.getlist('details')
520
+
521
+ # Validate that date is in the future
522
+ appointment_datetime = datetime.strptime(f"{date_str} {time}", '%Y-%m-%d %H:%M')
523
+ if appointment_datetime <= datetime.now():
524
+ flash('Appointment date and time must be in the future!', 'error')
525
+ return redirect(url_for('user_appointments'))
526
+
527
+ # Check for overlapping appointments for the doctor
528
+ # Since appointments are unassigned at booking, we check only for existing identical patient bookings
529
+ existing_appointment = mongo.db.appointments.find_one({
530
+ 'user_id': session['user_id'],
531
+ 'date': datetime.strptime(date_str, '%Y-%m-%d'),
532
+ 'time': time,
533
+ 'status': {'$in': ['pending', 'confirmed']}
534
+ })
535
+
536
+ if existing_appointment:
537
+ flash('This time slot is already booked. Please choose another time.', 'error')
538
+ return redirect(url_for('user_appointments'))
539
+
540
+ # Create appointment data
541
+ appointment_data = {
542
+ 'user_id': session['user_id'],
543
+ 'disease_type': disease_type,
544
+ 'details_selected': details_selected,
545
+ 'date': datetime.strptime(date_str, '%Y-%m-%d'), # Convert to datetime object
546
+ 'time': time,
547
+ 'notes': notes,
548
+ 'status': 'pending',
549
+ # doctor will be set when a doctor confirms the appointment
550
+ 'doctor': '',
551
+ 'doctor_id': '',
552
+ 'created_at': datetime.now()
553
+ }
554
+
555
+ # Insert appointment into database
556
+ mongo.db.appointments.insert_one(appointment_data)
557
+
558
+ flash('Appointment booked successfully! Please wait for confirmation.', 'success')
559
+ return redirect(url_for('user_appointments'))
560
+
561
+ # Get upcoming appointments for the user
562
+ upcoming_appointments = list(mongo.db.appointments.find(
563
+ {'user_id': session['user_id'], 'date': {'$gte': datetime.now()}}
564
+ ).sort('date', 1))
565
+
566
+ # Get user's prediction history to suggest disease types
567
+ prediction_history = list(mongo.db.patient_history.find(
568
+ {'user_id': session['user_id']}
569
+ ).sort('date', -1).limit(10))
570
+
571
+ return render_template('user/appointments.html',
572
+ upcoming_appointments=upcoming_appointments,
573
+ prediction_history=prediction_history)
574
+
575
+ # Cancel Appointment
576
+ @app.route('/user/cancel-appointment/<appointment_id>')
577
+ def cancel_appointment(appointment_id):
578
+ if 'user_id' not in session:
579
+ flash('Please log in to access this page!', 'error')
580
+ return redirect(url_for('login'))
581
+
582
+ # Update appointment status to cancelled
583
+ result = mongo.db.appointments.update_one(
584
+ {'_id': ObjectId(appointment_id), 'user_id': session['user_id']},
585
+ {'$set': {'status': 'cancelled'}}
586
+ )
587
+
588
+ if result.modified_count > 0:
589
+ flash('Appointment cancelled successfully!', 'success')
590
+ else:
591
+ flash('Appointment not found or you do not have permission to cancel it!', 'error')
592
+
593
+ return redirect(url_for('user_appointments'))
594
+
595
+ # Admin Appointments
596
+ @app.route('/admin/appointments')
597
+ def admin_appointments():
598
+ if 'user_id' not in session:
599
+ flash('Please log in to access this page!', 'error')
600
+ return redirect(url_for('login'))
601
+
602
+ # Check if user is admin
603
+ user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
604
+ if user['role'] != 'admin':
605
+ flash('Access denied!', 'error')
606
+ return redirect(url_for('user_dashboard'))
607
+
608
+ # Get pending appointments
609
+ pending_appointments = list(mongo.db.appointments.find(
610
+ {'status': 'pending'}
611
+ ).sort('date', 1))
612
+
613
+ # Add patient information to pending appointments
614
+ for appointment in pending_appointments:
615
+ patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])})
616
+ appointment['patient_name'] = patient['name'] if patient else 'Unknown'
617
+ appointment['patient_email'] = patient['email'] if patient else 'Unknown'
618
+
619
+ # Get confirmed appointments
620
+ confirmed_appointments = list(mongo.db.appointments.find(
621
+ {'status': 'confirmed'}
622
+ ).sort([('date', 1), ('time', 1)]))
623
+
624
+ # Add patient information to confirmed appointments
625
+ for appointment in confirmed_appointments:
626
+ patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])})
627
+ appointment['patient_name'] = patient['name'] if patient else 'Unknown'
628
+ appointment['patient_email'] = patient['email'] if patient else 'Unknown'
629
+
630
+ return render_template('admin/appointments.html',
631
+ pending_appointments=pending_appointments,
632
+ confirmed_appointments=confirmed_appointments)
633
+
634
+ # Confirm Appointment
635
+ @app.route('/admin/appointments/<appointment_id>/confirm', methods=['POST'])
636
+ def confirm_appointment(appointment_id):
637
+ if 'user_id' not in session:
638
+ flash('Please log in to access this page!', 'error')
639
+ return redirect(url_for('login'))
640
+
641
+ # Check if user is admin
642
+ user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
643
+ if user['role'] != 'admin':
644
+ flash('Access denied!', 'error')
645
+ return redirect(url_for('user_dashboard'))
646
+
647
+ # Update appointment status to confirmed
648
+ result = mongo.db.appointments.update_one(
649
+ {'_id': ObjectId(appointment_id)},
650
+ {'$set': {'status': 'confirmed'}}
651
+ )
652
+
653
+ if result.modified_count > 0:
654
+ flash('Appointment confirmed successfully!', 'success')
655
+ else:
656
+ flash('Appointment not found!', 'error')
657
+
658
+ return redirect(url_for('admin_appointments'))
659
+
660
+ # Reject Appointment
661
+ @app.route('/admin/appointments/<appointment_id>/reject', methods=['POST'])
662
+ def reject_appointment(appointment_id):
663
+ if 'user_id' not in session:
664
+ flash('Please log in to access this page!', 'error')
665
+ return redirect(url_for('login'))
666
+
667
+ # Check if user is admin
668
+ user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
669
+ if user['role'] != 'admin':
670
+ flash('Access denied!', 'error')
671
+ return redirect(url_for('user_dashboard'))
672
+
673
+ # Update appointment status to cancelled
674
+ result = mongo.db.appointments.update_one(
675
+ {'_id': ObjectId(appointment_id)},
676
+ {'$set': {'status': 'cancelled'}}
677
+ )
678
+
679
+ if result.modified_count > 0:
680
+ flash('Appointment rejected successfully!', 'success')
681
+ else:
682
+ flash('Appointment not found!', 'error')
683
+
684
+ return redirect(url_for('admin_appointments'))
685
+
686
+ # User dashboard
687
+ @app.route('/user/dashboard')
688
+ def user_dashboard():
689
+ if 'user_id' not in session:
690
+ flash('Please log in to access the dashboard!', 'error')
691
+ return redirect(url_for('login'))
692
+
693
+ # Get user data
694
+ user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
695
+
696
+ # Get recent predictions (limit to 5)
697
+ recent_predictions = list(mongo.db.patient_history.find(
698
+ {'user_id': session['user_id']}
699
+ ).sort('date', -1).limit(5))
700
+
701
+ return render_template('user/dashboard.html',
702
+ user=user,
703
+ recent_predictions=recent_predictions)
704
+
705
+ @app.route('/user/dashboard/data')
706
+ def user_dashboard_data():
707
+ """Return JSON with data for Plotly charts for the logged-in user."""
708
+ if 'user_id' not in session:
709
+ return jsonify({'error': 'Unauthorized'}), 401
710
+
711
+ # 1) Prediction results distribution
712
+ prediction_pipeline = [
713
+ {'$match': {'user_id': session['user_id']}},
714
+ {'$group': {'_id': '$result', 'count': {'$sum': 1}}}
715
+ ]
716
+ prediction_counts = {'positive': 0, 'negative': 0}
717
+ for doc in mongo.db.patient_history.aggregate(prediction_pipeline):
718
+ result = doc.get('_id', '').lower()
719
+ if 'likely' in result:
720
+ prediction_counts['positive'] += doc.get('count', 0)
721
+ else:
722
+ prediction_counts['negative'] += doc.get('count', 0)
723
+
724
+ # 2) Predictions over time (last 30 days)
725
+ from datetime import timedelta
726
+ today = datetime.now()
727
+ start_date = today - timedelta(days=29)
728
+
729
+ trend_pipeline = [
730
+ {'$match': {'user_id': session['user_id'], 'date': {'$gte': start_date}}},
731
+ {'$group': {'_id': {'$dateToString': {'format':'%Y-%m-%d', 'date':'$date'}}, 'count': {'$sum':1}}},
732
+ {'$sort': {'_id': 1}}
733
+ ]
734
+ trend_docs = list(mongo.db.patient_history.aggregate(trend_pipeline))
735
+ # prepare arrays for the last 30 days
736
+ dates = []
737
+ counts = []
738
+ for i in range(30):
739
+ d = (start_date + timedelta(days=i)).strftime('%Y-%m-%d')
740
+ dates.append(d)
741
+ counts.append(0)
742
+ date_index = {dates[i]: i for i in range(len(dates))}
743
+ for doc in trend_docs:
744
+ idx = date_index.get(doc['_id'])
745
+ if idx is not None:
746
+ counts[idx] = doc['count']
747
+
748
+ # 3) Disease type distribution
749
+ disease_pipeline = [
750
+ {'$match': {'user_id': session['user_id']}},
751
+ {'$group': {'_id': '$disease_type', 'count': {'$sum': 1}}}
752
+ ]
753
+ disease_docs = list(mongo.db.patient_history.aggregate(disease_pipeline))
754
+ disease_labels = [d['_id'] for d in disease_docs]
755
+ disease_counts = [d['count'] for d in disease_docs]
756
+
757
+ # 4) Confidence scores distribution
758
+ confidence_pipeline = [
759
+ {'$match': {'user_id': session['user_id']}},
760
+ {'$project': {'range': {'$concat': [
761
+ {'$cond': [{'$lt': ['$confidence', 50]}, '0-49%', '']},
762
+ {'$cond': [{'$and': [{'$gte': ['$confidence', 50]}, {'$lt': ['$confidence', 80]}]}, '50-79%', '']},
763
+ {'$cond': [{'$gte': ['$confidence', 80]}, '80-100%', '']}
764
+ ]}}},
765
+ {'$group': {'_id': '$range', 'count': {'$sum': 1}}}
766
+ ]
767
+ confidence_docs = list(mongo.db.patient_history.aggregate(confidence_pipeline))
768
+ confidence_labels = [d['_id'] for d in confidence_docs if d['_id']]
769
+ confidence_counts = [d['count'] for d in confidence_docs if d['_id']]
770
+
771
+ return jsonify({
772
+ 'predictions': prediction_counts,
773
+ 'trend': {'dates': dates, 'counts': counts},
774
+ 'diseases': {'labels': disease_labels, 'counts': disease_counts},
775
+ 'confidence': {'labels': confidence_labels, 'counts': confidence_counts}
776
+ })
777
+
778
+ # Admin dashboard
779
+ @app.route('/admin/dashboard')
780
+ def admin_dashboard():
781
+ if 'user_id' not in session:
782
+ flash('Please log in to access the dashboard!', 'error')
783
+ return redirect(url_for('login'))
784
+
785
+ # Check if user is admin
786
+ user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
787
+ if user['role'] != 'admin':
788
+ flash('Access denied!', 'error')
789
+ return redirect(url_for('user_dashboard'))
790
+
791
+ # Get statistics
792
+ total_users = mongo.db.users.count_documents({})
793
+ heart_predictions = mongo.db.patient_history.count_documents({'disease_type': 'Heart Disease'})
794
+ diabetes_predictions = mongo.db.patient_history.count_documents({'disease_type': 'Diabetes'})
795
+ parkinsons_predictions = mongo.db.patient_history.count_documents({'disease_type': "Parkinson's"})
796
+
797
+ # Get recent users (limit to 5)
798
+ recent_users = list(mongo.db.users.find().sort('created_at', -1).limit(5))
799
+
800
+ # Get all predictions (limit to 10)
801
+ all_predictions = list(mongo.db.patient_history.find().sort('date', -1).limit(10))
802
+
803
+ # Add user names to predictions
804
+ for prediction in all_predictions:
805
+ user = mongo.db.users.find_one({'_id': ObjectId(prediction['user_id'])})
806
+ prediction['user_name'] = user['name'] if user else 'Unknown'
807
+
808
+ return render_template('admin/dashboard.html',
809
+ total_users=total_users,
810
+ heart_predictions=heart_predictions,
811
+ diabetes_predictions=diabetes_predictions,
812
+ parkinsons_predictions=parkinsons_predictions,
813
+ recent_users=recent_users,
814
+ all_predictions=all_predictions)
815
+
816
+ # Heart Disease Prediction
817
+ @app.route('/user/heart-disease', methods=['GET', 'POST'])
818
+ def heart_disease_prediction():
819
+ if 'user_id' not in session:
820
+ flash('Please log in to access this page!', 'error')
821
+ return redirect(url_for('login'))
822
+
823
+ if request.method == 'POST':
824
+ try:
825
+ # Get form data
826
+ age = float(request.form['age'])
827
+ sex = float(request.form['sex'])
828
+ cp = float(request.form['cp'])
829
+ trestbps = float(request.form['trestbps'])
830
+ chol = float(request.form['chol'])
831
+ fbs = float(request.form['fbs'])
832
+ restecg = float(request.form['restecg'])
833
+ thalach = float(request.form['thalach'])
834
+ exang = float(request.form['exang'])
835
+ oldpeak = float(request.form['oldpeak'])
836
+ slope = float(request.form['slope'])
837
+ ca = float(request.form['ca'])
838
+ thal = float(request.form['thal'])
839
+
840
+ # Create input array for prediction
841
+ input_data = [age, sex, cp, trestbps, chol, fbs, restecg, thalach, exang, oldpeak, slope, ca, thal]
842
+
843
+ # Make prediction
844
+ prediction = heart_disease_model.predict([input_data])
845
+
846
+ # Check if predict_proba is available and properly configured
847
+ try:
848
+ if hasattr(heart_disease_model, 'predict_proba') and callable(getattr(heart_disease_model, 'predict_proba')):
849
+ probability = heart_disease_model.predict_proba([input_data])
850
+ # Determine confidence based on the prediction
851
+ if prediction[0] == 1:
852
+ confidence = probability[0][1] * 100
853
+ else:
854
+ confidence = probability[0][0] * 100
855
+ else:
856
+ # If predict_proba is not available, use a default confidence
857
+ confidence = 90.0 if prediction[0] == 1 else 10.0
858
+ except Exception as e:
859
+ # Handle any errors with predict_proba
860
+ print(f"Warning: predict_proba failed with error: {e}")
861
+ confidence = 90.0 if prediction[0] == 1 else 10.0
862
+
863
+ # Determine result
864
+ if prediction[0] == 1:
865
+ result = "The person is likely to have heart disease"
866
+ else:
867
+ result = "The person is unlikely to have heart disease"
868
+
869
+ # Store prediction in database
870
+ prediction_data = {
871
+ 'user_id': session['user_id'],
872
+ 'disease_type': 'Heart Disease',
873
+ 'input_data': {
874
+ 'age': age,
875
+ 'sex': sex,
876
+ 'cp': cp,
877
+ 'trestbps': trestbps,
878
+ 'chol': chol,
879
+ 'fbs': fbs,
880
+ 'restecg': restecg,
881
+ 'thalach': thalach,
882
+ 'exang': exang,
883
+ 'oldpeak': oldpeak,
884
+ 'slope': slope,
885
+ 'ca': ca,
886
+ 'thal': thal
887
+ },
888
+ 'result': result,
889
+ 'confidence': confidence,
890
+ 'date': datetime.now()
891
+ }
892
+
893
+ mongo.db.patient_history.insert_one(prediction_data)
894
+
895
+ # Add prediction data to session for display
896
+ session['prediction_result'] = {
897
+ 'disease_type': 'Heart Disease',
898
+ 'result': result,
899
+ 'confidence': confidence,
900
+ 'input_data': prediction_data['input_data']
901
+ }
902
+
903
+ return redirect(url_for('prediction_result'))
904
+
905
+ except Exception as e:
906
+ flash(f'Error processing prediction: {str(e)}', 'error')
907
+ return redirect(url_for('heart_disease_prediction'))
908
+
909
+ return render_template('user/heart_disease.html')
910
+
911
+ # Diabetes Prediction
912
+ @app.route('/user/diabetes', methods=['GET', 'POST'])
913
+ def diabetes_prediction():
914
+ if 'user_id' not in session:
915
+ flash('Please log in to access this page!', 'error')
916
+ return redirect(url_for('login'))
917
+
918
+ if request.method == 'POST':
919
+ try:
920
+ # Get form data
921
+ pregnancies = float(request.form['pregnancies'])
922
+ glucose = float(request.form['glucose'])
923
+ blood_pressure = float(request.form['blood_pressure'])
924
+ skin_thickness = float(request.form['skin_thickness'])
925
+ insulin = float(request.form['insulin'])
926
+ bmi = float(request.form['bmi'])
927
+ diabetes_pedigree = float(request.form['diabetes_pedigree'])
928
+ age = float(request.form['age'])
929
+
930
+ # Create input array for prediction
931
+ input_data = [pregnancies, glucose, blood_pressure, skin_thickness, insulin, bmi, diabetes_pedigree, age]
932
+
933
+ # Make prediction
934
+ prediction = diabetes_model.predict([input_data])
935
+
936
+ # Check if predict_proba is available and properly configured
937
+ try:
938
+ if hasattr(diabetes_model, 'predict_proba') and callable(getattr(diabetes_model, 'predict_proba')):
939
+ probability = diabetes_model.predict_proba([input_data])
940
+ # Determine confidence based on the prediction
941
+ if prediction[0] == 1:
942
+ confidence = probability[0][1] * 100
943
+ else:
944
+ confidence = probability[0][0] * 100
945
+ else:
946
+ # If predict_proba is not available, use a default confidence
947
+ confidence = 90.0 if prediction[0] == 1 else 10.0
948
+ except Exception as e:
949
+ # Handle any errors with predict_proba
950
+ print(f"Warning: predict_proba failed with error: {e}")
951
+ confidence = 90.0 if prediction[0] == 1 else 10.0
952
+
953
+ # Determine result
954
+ if prediction[0] == 1:
955
+ result = "The person is likely to have diabetes"
956
+ else:
957
+ result = "The person is unlikely to have diabetes"
958
+
959
+ # Store prediction in database
960
+ prediction_data = {
961
+ 'user_id': session['user_id'],
962
+ 'disease_type': 'Diabetes',
963
+ 'input_data': {
964
+ 'pregnancies': pregnancies,
965
+ 'glucose': glucose,
966
+ 'blood_pressure': blood_pressure,
967
+ 'skin_thickness': skin_thickness,
968
+ 'insulin': insulin,
969
+ 'bmi': bmi,
970
+ 'diabetes_pedigree': diabetes_pedigree,
971
+ 'age': age
972
+ },
973
+ 'result': result,
974
+ 'confidence': confidence,
975
+ 'date': datetime.now()
976
+ }
977
+
978
+ mongo.db.patient_history.insert_one(prediction_data)
979
+
980
+ # Add prediction data to session for display
981
+ session['prediction_result'] = {
982
+ 'disease_type': 'Diabetes',
983
+ 'result': result,
984
+ 'confidence': confidence,
985
+ 'input_data': prediction_data['input_data']
986
+ }
987
+
988
+ return redirect(url_for('prediction_result'))
989
+
990
+ except Exception as e:
991
+ flash(f'Error processing prediction: {str(e)}', 'error')
992
+ return redirect(url_for('diabetes_prediction'))
993
+
994
+ return render_template('user/diabetes.html')
995
+
996
+ # Parkinson's Prediction
997
+ @app.route('/user/parkinsons', methods=['GET', 'POST'])
998
+ def parkinsons_prediction():
999
+ if 'user_id' not in session:
1000
+ flash('Please log in to access this page!', 'error')
1001
+ return redirect(url_for('login'))
1002
+
1003
+ if request.method == 'POST':
1004
+ try:
1005
+ # Get form data
1006
+ fo = float(request.form['fo'])
1007
+ fhi = float(request.form['fhi'])
1008
+ flo = float(request.form['flo'])
1009
+ jitter_percent = float(request.form['jitter_percent'])
1010
+ jitter_abs = float(request.form['jitter_abs'])
1011
+ rap = float(request.form['rap'])
1012
+ ppq = float(request.form['ppq'])
1013
+ ddp = float(request.form['ddp'])
1014
+ shimmer = float(request.form['shimmer'])
1015
+ shimmer_db = float(request.form['shimmer_db'])
1016
+ apq3 = float(request.form['apq3'])
1017
+ apq5 = float(request.form['apq5'])
1018
+ apq = float(request.form['apq'])
1019
+ dda = float(request.form['dda'])
1020
+ nhr = float(request.form['nhr'])
1021
+ hnr = float(request.form['hnr'])
1022
+ rpde = float(request.form['rpde'])
1023
+ dfa = float(request.form['dfa'])
1024
+ spread1 = float(request.form['spread1'])
1025
+ spread2 = float(request.form['spread2'])
1026
+ d2 = float(request.form['d2'])
1027
+ ppe = float(request.form['ppe'])
1028
+
1029
+ # Create input array for prediction
1030
+ input_data = [fo, fhi, flo, jitter_percent, jitter_abs, rap, ppq, ddp, shimmer, shimmer_db,
1031
+ apq3, apq5, apq, dda, nhr, hnr, rpde, dfa, spread1, spread2, d2, ppe]
1032
+
1033
+ # Make prediction
1034
+ prediction = parkinsons_model.predict([input_data])
1035
+
1036
+ # Check if predict_proba is available and properly configured
1037
+ try:
1038
+ if hasattr(parkinsons_model, 'predict_proba') and callable(getattr(parkinsons_model, 'predict_proba')):
1039
+ probability = parkinsons_model.predict_proba([input_data])
1040
+ # Determine confidence based on the prediction
1041
+ if prediction[0] == 1:
1042
+ confidence = probability[0][1] * 100
1043
+ else:
1044
+ confidence = probability[0][0] * 100
1045
+ else:
1046
+ # If predict_proba is not available, use a default confidence
1047
+ confidence = 90.0 if prediction[0] == 1 else 10.0
1048
+ except Exception as e:
1049
+ # Handle any errors with predict_proba
1050
+ print(f"Warning: predict_proba failed with error: {e}")
1051
+ confidence = 90.0 if prediction[0] == 1 else 10.0
1052
+
1053
+ # Determine result
1054
+ if prediction[0] == 1:
1055
+ result = "The person is likely to have Parkinson's disease"
1056
+ else:
1057
+ result = "The person is unlikely to have Parkinson's disease"
1058
+
1059
+ # Store prediction in database
1060
+ prediction_data = {
1061
+ 'user_id': session['user_id'],
1062
+ 'disease_type': "Parkinson's",
1063
+ 'input_data': {
1064
+ 'fo': fo,
1065
+ 'fhi': fhi,
1066
+ 'flo': flo,
1067
+ 'jitter_percent': jitter_percent,
1068
+ 'jitter_abs': jitter_abs,
1069
+ 'rap': rap,
1070
+ 'ppq': ppq,
1071
+ 'ddp': ddp,
1072
+ 'shimmer': shimmer,
1073
+ 'shimmer_db': shimmer_db,
1074
+ 'apq3': apq3,
1075
+ 'apq5': apq5,
1076
+ 'apq': apq,
1077
+ 'dda': dda,
1078
+ 'nhr': nhr,
1079
+ 'hnr': hnr,
1080
+ 'rpde': rpde,
1081
+ 'dfa': dfa,
1082
+ 'spread1': spread1,
1083
+ 'spread2': spread2,
1084
+ 'd2': d2,
1085
+ 'ppe': ppe
1086
+ },
1087
+ 'result': result,
1088
+ 'confidence': confidence,
1089
+ 'date': datetime.now()
1090
+ }
1091
+
1092
+ mongo.db.patient_history.insert_one(prediction_data)
1093
+
1094
+ # Add prediction data to session for display
1095
+ session['prediction_result'] = {
1096
+ 'disease_type': "Parkinson's",
1097
+ 'result': result,
1098
+ 'confidence': confidence,
1099
+ 'input_data': prediction_data['input_data']
1100
+ }
1101
+
1102
+ return redirect(url_for('prediction_result'))
1103
+
1104
+ except Exception as e:
1105
+ flash(f'Error processing prediction: {str(e)}', 'error')
1106
+ return redirect(url_for('parkinsons_prediction'))
1107
+
1108
+ return render_template('user/parkinsons.html')
1109
+
1110
+ # Prediction Result
1111
+ @app.route('/user/result')
1112
+ def prediction_result():
1113
+ if 'user_id' not in session:
1114
+ flash('Please log in to access this page!', 'error')
1115
+ return redirect(url_for('login'))
1116
+
1117
+ if 'prediction_result' not in session:
1118
+ flash('No prediction result found!', 'error')
1119
+ return redirect(url_for('user_dashboard'))
1120
+
1121
+ result = session['prediction_result']
1122
+ return render_template('user/result.html', result=result)
1123
+
1124
+ # Patient History
1125
+ @app.route('/user/history')
1126
+ def patient_history():
1127
+ if 'user_id' not in session:
1128
+ flash('Please log in to access this page!', 'error')
1129
+ return redirect(url_for('login'))
1130
+
1131
+ # Get all predictions for the user
1132
+ history = list(mongo.db.patient_history.find(
1133
+ {'user_id': session['user_id']}
1134
+ ).sort('date', -1))
1135
+
1136
+ return render_template('user/history.html', history=history)
1137
+
1138
+ # Detailed Report
1139
+ @app.route('/user/report/<report_id>')
1140
+ def detailed_report(report_id):
1141
+ if 'user_id' not in session:
1142
+ flash('Please log in to access this page!', 'error')
1143
+ return redirect(url_for('login'))
1144
+
1145
+ # Get the report
1146
+ report = mongo.db.patient_history.find_one(
1147
+ {'_id': ObjectId(report_id), 'user_id': session['user_id']}
1148
+ )
1149
+
1150
+ if not report:
1151
+ flash('Report not found!', 'error')
1152
+ return redirect(url_for('patient_history'))
1153
+
1154
+ return render_template('user/report.html', report=report)
1155
+
1156
+ # Delete Report
1157
+ @app.route('/user/delete-report/<report_id>')
1158
+ def delete_report(report_id):
1159
+ if 'user_id' not in session:
1160
+ flash('Please log in to access this page!', 'error')
1161
+ return redirect(url_for('login'))
1162
+
1163
+ # Delete the report
1164
+ result = mongo.db.patient_history.delete_one(
1165
+ {'_id': ObjectId(report_id), 'user_id': session['user_id']}
1166
+ )
1167
+
1168
+ if result.deleted_count > 0:
1169
+ flash('Report deleted successfully!', 'success')
1170
+ else:
1171
+ flash('Report not found or you do not have permission to delete it!', 'error')
1172
+
1173
+ return redirect(url_for('patient_history'))
1174
+
1175
+ # Download Result as PDF (from session)
1176
+ @app.route('/user/download-result')
1177
+ def download_result():
1178
+ if 'user_id' not in session:
1179
+ flash('Please log in to access this page!', 'error')
1180
+ return redirect(url_for('login'))
1181
+
1182
+ if 'prediction_result' not in session:
1183
+ flash('No prediction result found!', 'error')
1184
+ return redirect(url_for('user_dashboard'))
1185
+
1186
+ result = session['prediction_result']
1187
+
1188
+ # Create PDF in memory
1189
+ buffer = io.BytesIO()
1190
+ c = canvas.Canvas(buffer, pagesize=letter)
1191
+ width, height = letter
1192
+
1193
+ # Add content to PDF
1194
+ c.setFont("Helvetica-Bold", 16)
1195
+ c.drawString(100, height - 50, "Multiple Disease Prediction System")
1196
+
1197
+ c.setFont("Helvetica-Bold", 14)
1198
+ c.drawString(100, height - 100, f"{result['disease_type']} Prediction Report")
1199
+
1200
+ c.setFont("Helvetica", 12)
1201
+ c.drawString(100, height - 130, f"Date: {datetime.now().strftime('%Y-%m-%d %H:%M')}")
1202
+ c.drawString(100, height - 150, f"Result: {result['result']}")
1203
+ c.drawString(100, height - 170, f"Confidence: {result['confidence']:.2f}%")
1204
+
1205
+ # Add input data
1206
+ c.setFont("Helvetica-Bold", 12)
1207
+ c.drawString(100, height - 200, "Input Data:")
1208
+
1209
+ c.setFont("Helvetica", 10)
1210
+ y_position = height - 220
1211
+ for key, value in result['input_data'].items():
1212
+ c.drawString(120, y_position, f"{key.replace('_', ' ').title()}: {value}")
1213
+ y_position -= 15
1214
+ if y_position < 100: # Start new page if needed
1215
+ c.showPage()
1216
+ y_position = height - 100
1217
+
1218
+ # Add disclaimer
1219
+ c.setFont("Helvetica-Oblique", 10)
1220
+ c.drawString(100, 50, "Note: This prediction is based on machine learning algorithms and should not be")
1221
+ c.drawString(100, 35, "considered as a medical diagnosis. Please consult with a healthcare professional.")
1222
+
1223
+ c.save()
1224
+
1225
+ # Prepare response
1226
+ buffer.seek(0)
1227
+ return send_file(
1228
+ buffer,
1229
+ as_attachment=True,
1230
+ download_name=f"{result['disease_type']}_prediction_report.pdf",
1231
+ mimetype='application/pdf'
1232
+ )
1233
+
1234
+ # Download Report as PDF (from database)
1235
+ @app.route('/user/download-report/<report_id>')
1236
+ def download_report(report_id):
1237
+ if 'user_id' not in session:
1238
+ flash('Please log in to access this page!', 'error')
1239
+ return redirect(url_for('login'))
1240
+
1241
+ # Get the report
1242
+ report = mongo.db.patient_history.find_one(
1243
+ {'_id': ObjectId(report_id), 'user_id': session['user_id']}
1244
+ )
1245
+
1246
+ if not report:
1247
+ flash('Report not found!', 'error')
1248
+ return redirect(url_for('patient_history'))
1249
+
1250
+ # Create PDF in memory
1251
+ buffer = io.BytesIO()
1252
+ c = canvas.Canvas(buffer, pagesize=letter)
1253
+ width, height = letter
1254
+
1255
+ # Add content to PDF
1256
+ c.setFont("Helvetica-Bold", 16)
1257
+ c.drawString(100, height - 50, "Multiple Disease Prediction System")
1258
+
1259
+ c.setFont("Helvetica-Bold", 14)
1260
+ c.drawString(100, height - 100, f"{report['disease_type']} Prediction Report")
1261
+
1262
+ c.setFont("Helvetica", 12)
1263
+ c.drawString(100, height - 130, f"Date: {report['date'].strftime('%Y-%m-%d %H:%M')}")
1264
+ c.drawString(100, height - 150, f"Result: {report['result']}")
1265
+ c.drawString(100, height - 170, f"Confidence: {report['confidence']:.2f}%")
1266
+
1267
+ # Add input data
1268
+ c.setFont("Helvetica-Bold", 12)
1269
+ c.drawString(100, height - 200, "Input Data:")
1270
+
1271
+ c.setFont("Helvetica", 10)
1272
+ y_position = height - 220
1273
+ for key, value in report['input_data'].items():
1274
+ c.drawString(120, y_position, f"{key.replace('_', ' ').title()}: {value}")
1275
+ y_position -= 15
1276
+ if y_position < 100: # Start new page if needed
1277
+ c.showPage()
1278
+ y_position = height - 100
1279
+
1280
+ # Add disclaimer
1281
+ c.setFont("Helvetica-Oblique", 10)
1282
+ c.drawString(100, 50, "Note: This prediction is based on machine learning algorithms and should not be")
1283
+ c.drawString(100, 35, "considered as a medical diagnosis. Please consult with a healthcare professional.")
1284
+
1285
+ c.save()
1286
+
1287
+ # Prepare response
1288
+ buffer.seek(0)
1289
+ return send_file(
1290
+ buffer,
1291
+ as_attachment=True,
1292
+ download_name=f"{report['disease_type']}_prediction_report_{report_id}.pdf",
1293
+ mimetype='application/pdf'
1294
+ )
1295
+
1296
+ # Doctor Appointments
1297
+ @app.route('/doctor/appointments')
1298
+ def doctor_appointments():
1299
+ if 'user_id' not in session:
1300
+ flash('Please log in to access this page!', 'error')
1301
+ return redirect(url_for('login'))
1302
+
1303
+ # Check if user is doctor
1304
+ user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
1305
+ if user['role'] != 'doctor':
1306
+ flash('Access denied!', 'error')
1307
+ return redirect(url_for('user_dashboard'))
1308
+
1309
+ # Get pending appointments matching doctor's specialization
1310
+ # Map common specializations to disease keywords to improve matching
1311
+ specialization_map = {
1312
+ 'Cardiologist': ['heart', 'cardio', 'cardiologist'],
1313
+ 'Endocrinologist': ['diabetes', 'endocrine', 'endocrinologist'],
1314
+ "Neurologist": ['parkinson', 'neuro', 'neurologist'],
1315
+ 'General Practitioner': []
1316
+ }
1317
+
1318
+ spec = user.get('specialization', '') or ''
1319
+ keywords = []
1320
+ for key, vals in specialization_map.items():
1321
+ if spec.lower() == key.lower():
1322
+ keywords = vals
1323
+ break
1324
+
1325
+ if keywords:
1326
+ # build regex to match any of the keywords
1327
+ regex_parts = '|'.join([f"{kw}" for kw in keywords])
1328
+ pending_appointments = list(mongo.db.appointments.find({
1329
+ 'disease_type': {'$regex': regex_parts, '$options': 'i'},
1330
+ 'status': 'pending'
1331
+ }).sort('date', 1))
1332
+ else:
1333
+ # fallback: if no specialization or GP, show appointments assigned to this doctor or all pending
1334
+ pending_appointments = list(mongo.db.appointments.find({
1335
+ '$or': [
1336
+ {'doctor': {'$regex': user['name'], '$options': 'i'}},
1337
+ {'status': 'pending'}
1338
+ ]
1339
+ }).sort('date', 1))
1340
+
1341
+ # Add patient information to pending appointments
1342
+ for appointment in pending_appointments:
1343
+ patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])})
1344
+ appointment['patient_name'] = patient['name'] if patient else 'Unknown'
1345
+ appointment['patient_email'] = patient['email'] if patient else 'Unknown'
1346
+
1347
+ # Get confirmed appointments
1348
+ confirmed_appointments = list(mongo.db.appointments.find({
1349
+ 'doctor': {'$regex': user['name'], '$options': 'i'},
1350
+ 'status': 'confirmed'
1351
+ }).sort([('date', 1), ('time', 1)]))
1352
+
1353
+ # Add patient information to confirmed appointments
1354
+ for appointment in confirmed_appointments:
1355
+ patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])})
1356
+ appointment['patient_name'] = patient['name'] if patient else 'Unknown'
1357
+ appointment['patient_email'] = patient['email'] if patient else 'Unknown'
1358
+
1359
+ return render_template('doctor/appointments.html',
1360
+ pending_appointments=pending_appointments,
1361
+ confirmed_appointments=confirmed_appointments,
1362
+ doctor=user)
1363
+
1364
+
1365
+ @app.route('/doctor/dashboard')
1366
+ def doctor_dashboard():
1367
+ if 'user_id' not in session:
1368
+ flash('Please log in to access the dashboard!', 'error')
1369
+ return redirect(url_for('login'))
1370
+ user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
1371
+ if user['role'] != 'doctor':
1372
+ flash('Access denied!', 'error')
1373
+ return redirect(url_for('user_dashboard'))
1374
+
1375
+ return render_template('doctor/dashboard.html')
1376
+
1377
+
1378
+ @app.route('/doctor/dashboard/data')
1379
+ def doctor_dashboard_data():
1380
+ """Return JSON with data for Plotly charts for the logged-in doctor."""
1381
+ if 'user_id' not in session:
1382
+ return jsonify({'error': 'Unauthorized'}), 401
1383
+
1384
+ user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
1385
+ if not user or user.get('role') != 'doctor':
1386
+ return jsonify({'error': 'Forbidden'}), 403
1387
+
1388
+ # specialization keywords (reuse mapping)
1389
+ specialization_map = {
1390
+ 'Cardiologist': ['heart', 'cardio', 'cardiologist'],
1391
+ 'Endocrinologist': ['diabetes', 'endocrine', 'endocrinologist'],
1392
+ "Neurologist": ['parkinson', 'neuro', 'neurologist'],
1393
+ 'General Practitioner': []
1394
+ }
1395
+
1396
+ spec = user.get('specialization', '') or ''
1397
+ keywords = []
1398
+ for key, vals in specialization_map.items():
1399
+ if spec.lower() == key.lower():
1400
+ keywords = vals
1401
+ break
1402
+
1403
+ # build base filter for appointments relevant to this doctor
1404
+ if keywords:
1405
+ regex_parts = '|'.join([f"{kw}" for kw in keywords])
1406
+ base_filter = {'disease_type': {'$regex': regex_parts, '$options': 'i'}}
1407
+ else:
1408
+ base_filter = {}
1409
+
1410
+ # 1) Appointment status counts (for this specialization or assigned to this doctor)
1411
+ status_pipeline = [
1412
+ {'$match': {'$or': [base_filter, {'doctor_id': session['user_id']}]}},
1413
+ {'$group': {'_id': '$status', 'count': {'$sum': 1}}}
1414
+ ]
1415
+ status_counts = { 'pending':0, 'confirmed':0, 'rejected':0, 'cancelled':0 }
1416
+ for doc in mongo.db.appointments.aggregate(status_pipeline):
1417
+ # normalize status key and guard against unexpected values
1418
+ raw_key = doc.get('_id')
1419
+ if raw_key is None:
1420
+ key = 'unknown'
1421
+ else:
1422
+ key = str(raw_key).lower()
1423
+ # assign into known buckets if present, otherwise keep as-is under its key
1424
+ if key in status_counts:
1425
+ status_counts[key] = doc.get('count', 0)
1426
+ else:
1427
+ # for unexpected keys, add them to the dict to avoid key errors downstream
1428
+ status_counts[key] = doc.get('count', 0)
1429
+
1430
+ # 2) Trend: appointments per day for last 30 days
1431
+ from datetime import timedelta
1432
+ today = datetime.now()
1433
+ start_date = today - timedelta(days=29)
1434
+ match_trend = {'date': {'$gte': start_date}}
1435
+ if keywords:
1436
+ match_trend['$or'] = [base_filter, {'doctor_id': session['user_id']}]
1437
+ else:
1438
+ base_filter = {}
1439
+
1440
+ trend_pipeline = [
1441
+ {'$match': match_trend},
1442
+ {'$group': {'_id': {'$dateToString': {'format':'%Y-%m-%d', 'date':'$date'}}, 'count': {'$sum':1}}},
1443
+ {'$sort': {'_id': 1}}
1444
+ ]
1445
+ trend_docs = list(mongo.db.appointments.aggregate(trend_pipeline))
1446
+ # prepare arrays for the last 30 days
1447
+ dates = []
1448
+ counts = []
1449
+ for i in range(30):
1450
+ d = (start_date + timedelta(days=i)).strftime('%Y-%m-%d')
1451
+ dates.append(d)
1452
+ counts.append(0)
1453
+ date_index = {dates[i]: i for i in range(len(dates))}
1454
+ for doc in trend_docs:
1455
+ idx = date_index.get(doc['_id'])
1456
+ if idx is not None:
1457
+ counts[idx] = doc['count']
1458
+
1459
+ # 3) Upcoming schedule: next 10 confirmed appointments for this doctor
1460
+ # use start of today to include today's appointments (date stored as date with 00:00 time)
1461
+ start_of_today = datetime(today.year, today.month, today.day)
1462
+ 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))
1463
+ schedule_times = []
1464
+ schedule_labels = []
1465
+ for a in upcoming_docs:
1466
+ schedule_times.append(a['date'].strftime('%Y-%m-%d') + ' ' + a['time'])
1467
+ # patient name
1468
+ patient = mongo.db.users.find_one({'_id': ObjectId(a['user_id'])})
1469
+ schedule_labels.append(patient['name'] if patient else 'Unknown')
1470
+
1471
+ # 4) Patient distribution: unique patients per month (last 6 months)
1472
+ six_months_ago = today - timedelta(days=180)
1473
+ patient_pipeline = [
1474
+ {'$match': {'doctor_id': session['user_id'], 'status':'confirmed', 'date': {'$gte': six_months_ago}}},
1475
+ {'$group': {'_id': {'month': {'$month':'$date'}, 'year': {'$year':'$date'}}, 'patients': {'$addToSet': '$user_id'}}},
1476
+ {'$project': {'month':'$_id.month','year':'$_id.year','count': {'$size':'$patients'}}},
1477
+ {'$sort': {'year':1, 'month':1}}
1478
+ ]
1479
+ patient_docs = list(mongo.db.appointments.aggregate(patient_pipeline))
1480
+ months = [f"{d['month']}-{d['year']}" for d in patient_docs]
1481
+ patient_counts = [d['count'] for d in patient_docs]
1482
+
1483
+ # 5) Details frequency (checkboxes)
1484
+ # Build a details match that limits to either the specialization OR appointments assigned to this doctor
1485
+ if keywords:
1486
+ details_match = {'$or': [base_filter, {'doctor_id': session['user_id']} ]}
1487
+ else:
1488
+ details_match = {'doctor_id': session['user_id']}
1489
+
1490
+ details_pipeline = [
1491
+ {'$match': details_match},
1492
+ {'$unwind': '$details_selected'},
1493
+ {'$group': {'_id': '$details_selected', 'count': {'$sum': 1}}},
1494
+ {'$sort': {'count': -1}}
1495
+ ]
1496
+ details_docs = list(mongo.db.appointments.aggregate(details_pipeline))
1497
+ details_labels = [d['_id'] for d in details_docs]
1498
+ details_counts = [d['count'] for d in details_docs]
1499
+
1500
+ return jsonify({
1501
+ 'status': status_counts,
1502
+ 'trend': {'dates': dates, 'counts': counts},
1503
+ 'schedule': {'times': schedule_times, 'labels': schedule_labels},
1504
+ 'patient': {'months': months, 'counts': patient_counts},
1505
+ 'details': {'labels': details_labels, 'counts': details_counts}
1506
+ })
1507
+
1508
+ # Confirm Appointment
1509
+ @app.route('/doctor/appointments/<appointment_id>/confirm', methods=['POST'])
1510
+ def doctor_confirm_appointment(appointment_id):
1511
+ if 'user_id' not in session:
1512
+ flash('Please log in to access this page!', 'error')
1513
+ return redirect(url_for('login'))
1514
+
1515
+ # Check if user is doctor
1516
+ user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
1517
+ if user['role'] != 'doctor':
1518
+ flash('Access denied!', 'error')
1519
+ return redirect(url_for('user_dashboard'))
1520
+
1521
+ # Update appointment status to confirmed
1522
+ # Check that the doctor doesn't already have a confirmed appointment at same date/time
1523
+ appointment = mongo.db.appointments.find_one({'_id': ObjectId(appointment_id)})
1524
+ if not appointment:
1525
+ flash('Appointment not found!', 'error')
1526
+ return redirect(url_for('doctor_appointments'))
1527
+
1528
+ # If appointment already has a doctor assigned and it's not this doctor, deny
1529
+ if appointment.get('doctor_id') and appointment.get('doctor_id') != session['user_id']:
1530
+ flash('This appointment has already been assigned to another doctor.', 'error')
1531
+ return redirect(url_for('doctor_appointments'))
1532
+
1533
+ # Check for conflicting confirmed appointments for this doctor
1534
+ conflict = mongo.db.appointments.find_one({
1535
+ 'doctor_id': session['user_id'],
1536
+ 'date': appointment['date'],
1537
+ 'time': appointment['time'],
1538
+ 'status': 'confirmed'
1539
+ })
1540
+
1541
+ if conflict:
1542
+ flash('You already have a confirmed appointment at this date and time.', 'error')
1543
+ return redirect(url_for('doctor_appointments'))
1544
+
1545
+ # Mark appointment as confirmed and assign to this doctor
1546
+ result = mongo.db.appointments.update_one(
1547
+ {'_id': ObjectId(appointment_id)},
1548
+ {'$set': {
1549
+ 'status': 'confirmed',
1550
+ 'doctor_id': session['user_id'],
1551
+ 'doctor': user['name']
1552
+ }}
1553
+ )
1554
+
1555
+ if result.modified_count > 0:
1556
+ flash('Appointment confirmed successfully!', 'success')
1557
+ else:
1558
+ flash('Failed to confirm appointment. It may have been updated by someone else.', 'error')
1559
+
1560
+ return redirect(url_for('doctor_appointments'))
1561
+
1562
+ # Reject Appointment
1563
+ @app.route('/doctor/appointments/<appointment_id>/reject', methods=['POST'])
1564
+ def doctor_reject_appointment(appointment_id):
1565
+ if 'user_id' not in session:
1566
+ flash('Please log in to access this page!', 'error')
1567
+ return redirect(url_for('login'))
1568
+
1569
+ # Check if user is doctor
1570
+ user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
1571
+ if user['role'] != 'doctor':
1572
+ flash('Access denied!', 'error')
1573
+ return redirect(url_for('user_dashboard'))
1574
+
1575
+ # Update appointment status to rejected
1576
+ result = mongo.db.appointments.update_one(
1577
+ {'_id': ObjectId(appointment_id)},
1578
+ {'$set': {
1579
+ 'status': 'rejected',
1580
+ 'doctor_id': session['user_id'],
1581
+ 'doctor': user['name']
1582
+ }}
1583
+ )
1584
+
1585
+ if result.modified_count > 0:
1586
+ flash('Appointment rejected successfully!', 'success')
1587
+ else:
1588
+ flash('Appointment not found!', 'error')
1589
+
1590
+ return redirect(url_for('doctor_appointments'))
1591
+
1592
+ # Chat functionality
1593
+ @app.route('/user/chat/<appointment_id>')
1594
+ def user_chat(appointment_id):
1595
+ if 'user_id' not in session:
1596
+ flash('Please log in to access this page!', 'error')
1597
+ return redirect(url_for('login'))
1598
+
1599
+ # Check if appointment exists and is confirmed
1600
+ appointment = mongo.db.appointments.find_one({
1601
+ '_id': ObjectId(appointment_id),
1602
+ 'user_id': session['user_id'],
1603
+ 'status': 'confirmed'
1604
+ })
1605
+
1606
+ if not appointment:
1607
+ flash('Appointment not found or not confirmed!', 'error')
1608
+ return redirect(url_for('user_appointments'))
1609
+
1610
+ # Get messages for this appointment
1611
+ messages = list(mongo.db.messages.find(
1612
+ {'appointment_id': appointment_id}
1613
+ ).sort('timestamp', 1))
1614
+
1615
+ # Get doctor info
1616
+ doctor = mongo.db.users.find_one({'_id': ObjectId(appointment['doctor_id'])})
1617
+
1618
+ return render_template('user/chat.html',
1619
+ appointment=appointment,
1620
+ messages=messages,
1621
+ doctor=doctor)
1622
+
1623
+ @app.route('/doctor/chat/<appointment_id>')
1624
+ def doctor_chat(appointment_id):
1625
+ if 'user_id' not in session:
1626
+ flash('Please log in to access this page!', 'error')
1627
+ return redirect(url_for('login'))
1628
+
1629
+ # Check if user is doctor
1630
+ user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
1631
+ if user['role'] != 'doctor':
1632
+ flash('Access denied!', 'error')
1633
+ return redirect(url_for('user_dashboard'))
1634
+
1635
+ # Check if appointment exists and is confirmed
1636
+ appointment = mongo.db.appointments.find_one({
1637
+ '_id': ObjectId(appointment_id),
1638
+ 'doctor_id': session['user_id'],
1639
+ 'status': 'confirmed'
1640
+ })
1641
+
1642
+ if not appointment:
1643
+ flash('Appointment not found or not confirmed!', 'error')
1644
+ return redirect(url_for('doctor_appointments'))
1645
+
1646
+ # Get messages for this appointment
1647
+ messages = list(mongo.db.messages.find(
1648
+ {'appointment_id': appointment_id}
1649
+ ).sort('timestamp', 1))
1650
+
1651
+ # Get patient info
1652
+ patient = mongo.db.users.find_one({'_id': ObjectId(appointment['user_id'])})
1653
+
1654
+ return render_template('doctor/chat.html',
1655
+ appointment=appointment,
1656
+ messages=messages,
1657
+ patient=patient)
1658
+
1659
+ # Send message
1660
+ @app.route('/send_message', methods=['POST'])
1661
+ def send_message():
1662
+ if 'user_id' not in session:
1663
+ flash('Please log in to access this page!', 'error')
1664
+ return redirect(url_for('login'))
1665
+
1666
+ appointment_id = request.form['appointment_id']
1667
+ message_text = request.form['message']
1668
+
1669
+ # Check if appointment exists and is confirmed
1670
+ appointment = mongo.db.appointments.find_one({
1671
+ '_id': ObjectId(appointment_id),
1672
+ 'status': 'confirmed'
1673
+ })
1674
+
1675
+ if not appointment:
1676
+ flash('Appointment not found or not confirmed!', 'error')
1677
+ return redirect(url_for('user_dashboard'))
1678
+
1679
+ # Check if user is authorized to send message (patient or doctor)
1680
+ if session['user_id'] not in [str(appointment['user_id']), str(appointment.get('doctor_id', ''))]:
1681
+ flash('Access denied!', 'error')
1682
+ return redirect(url_for('user_dashboard'))
1683
+
1684
+ # Create message
1685
+ message_data = {
1686
+ 'appointment_id': appointment_id,
1687
+ 'sender_id': session['user_id'],
1688
+ 'message_text': message_text,
1689
+ 'timestamp': datetime.now()
1690
+ }
1691
+
1692
+ # Insert message into database
1693
+ mongo.db.messages.insert_one(message_data)
1694
+
1695
+ # Redirect based on user role
1696
+ user = mongo.db.users.find_one({'_id': ObjectId(session['user_id'])})
1697
+ if user['role'] == 'doctor':
1698
+ return redirect(url_for('doctor_chat', appointment_id=appointment_id))
1699
+ else:
1700
+ return redirect(url_for('user_chat', appointment_id=appointment_id))
1701
+
1702
+ if __name__ == "__main__":
1703
+ app.run(host="0.0.0.0", port=7860)
deployment.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Production deployment script for HealthGuard-AI application.
3
+ This script helps with deploying the application in a production environment.
4
+ """
5
+
6
+ import os
7
+ import sys
8
+ import subprocess
9
+ import argparse
10
+ from pathlib import Path
11
+
12
+ def check_environment():
13
+ """Check if all required environment variables are set."""
14
+ required_vars = ['MONGODB_URI', 'SECRET_KEY']
15
+ missing_vars = []
16
+
17
+ for var in required_vars:
18
+ if not os.getenv(var):
19
+ missing_vars.append(var)
20
+
21
+ if missing_vars:
22
+ print(f"Missing required environment variables: {', '.join(missing_vars)}")
23
+ print("Please set these variables before running the application.")
24
+ return False
25
+
26
+ return True
27
+
28
+ def install_dependencies():
29
+ """Install required dependencies."""
30
+ try:
31
+ subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt'])
32
+ print("Dependencies installed successfully.")
33
+ return True
34
+ except subprocess.CalledProcessError as e:
35
+ print(f"Failed to install dependencies: {e}")
36
+ return False
37
+
38
+ def check_models():
39
+ """Check if all required ML models are present."""
40
+ models_dir = Path('saved models')
41
+ required_models = [
42
+ 'diabetes_model.sav',
43
+ 'heart_disease_model.sav',
44
+ 'parkinsons_model.sav'
45
+ ]
46
+
47
+ missing_models = []
48
+ for model in required_models:
49
+ model_path = models_dir / model
50
+ if not model_path.exists():
51
+ missing_models.append(model)
52
+
53
+ if missing_models:
54
+ print(f"Missing required models: {', '.join(missing_models)}")
55
+ print("Please ensure all models are present in the 'saved models' directory.")
56
+ return False
57
+
58
+ return True
59
+
60
+ def start_application(host='0.0.0.0', port=7860):
61
+ """Start the Flask application."""
62
+ try:
63
+ # Import and run the app
64
+ from app import app
65
+ app.run(host=host, port=port, debug=False)
66
+ except Exception as e:
67
+ print(f"Failed to start application: {e}")
68
+ return False
69
+
70
+ return True
71
+
72
+ def main():
73
+ """Main deployment function."""
74
+ parser = argparse.ArgumentParser(description='Deploy HealthGuard-AI application')
75
+ parser.add_argument('--install-deps', action='store_true',
76
+ help='Install dependencies before starting')
77
+ parser.add_argument('--host', default='0.0.0.0',
78
+ help='Host to run the application on')
79
+ parser.add_argument('--port', type=int, default=7860,
80
+ help='Port to run the application on')
81
+
82
+ args = parser.parse_args()
83
+
84
+ print("HealthGuard-AI Production Deployment Script")
85
+ print("=" * 50)
86
+
87
+ # Check environment
88
+ print("Checking environment variables...")
89
+ if not check_environment():
90
+ sys.exit(1)
91
+
92
+ # Install dependencies if requested
93
+ if args.install_deps:
94
+ print("Installing dependencies...")
95
+ if not install_dependencies():
96
+ sys.exit(1)
97
+
98
+ # Check models
99
+ print("Checking ML models...")
100
+ if not check_models():
101
+ sys.exit(1)
102
+
103
+ # Start application
104
+ print(f"Starting application on {args.host}:{args.port}...")
105
+ if not start_application(args.host, args.port):
106
+ sys.exit(1)
107
+
108
+ if __name__ == '__main__':
109
+ main()
email_utils.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import smtplib
3
+ from email.message import EmailMessage
4
+
5
+ EMAIL_USER = os.getenv("EMAIL_USER")
6
+ # Support EMAIL_PASSWORD as either plain text or base64-encoded string.
7
+ # If it's base64-encoded, decode it; otherwise, use the raw value.
8
+ _raw_email_password = os.getenv("EMAIL_PASSWORD")
9
+ EMAIL_PASSWORD = None
10
+ if _raw_email_password:
11
+ # Try base64 decode, fall back to raw string if decode fails or is nonsense
12
+ try:
13
+ import base64 as _b64
14
+ decoded = _b64.b64decode(_raw_email_password).decode()
15
+ # Basic sanity: decoded password should be non-empty
16
+ if decoded:
17
+ EMAIL_PASSWORD = decoded
18
+ else:
19
+ EMAIL_PASSWORD = _raw_email_password
20
+ except Exception:
21
+ EMAIL_PASSWORD = _raw_email_password
22
+
23
+
24
+ def send_email(to_email, subject, body):
25
+ """Send an email using SMTP_SSL (Gmail).
26
+
27
+ Reads EMAIL_USER and EMAIL_PASSWORD from environment variables.
28
+ Raises RuntimeError if credentials are not set.
29
+ """
30
+ if not EMAIL_USER or not EMAIL_PASSWORD:
31
+ raise RuntimeError("Email credentials not configured in environment variables")
32
+
33
+ msg = EmailMessage()
34
+ msg.set_content(body)
35
+ msg["Subject"] = subject
36
+ msg["From"] = EMAIL_USER
37
+ msg["To"] = to_email
38
+
39
+ # Use SMTP_SSL for a secure connection
40
+ with smtplib.SMTP_SSL("smtp.gmail.com", 465) as smtp:
41
+ smtp.login(EMAIL_USER, EMAIL_PASSWORD)
42
+ smtp.send_message(msg)
requirements-prod.txt ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Production requirements for HealthGuard-AI
2
+ # This file includes all dependencies needed for production deployment
3
+
4
+ # Core dependencies
5
+ numpy==1.26.3
6
+ scikit-learn==1.3.2
7
+ flask==2.3.2
8
+ flask-pymongo==2.3.0
9
+ pymongo==4.3.3
10
+ bcrypt==4.0.1
11
+ reportlab==3.6.12
12
+ pandas==2.0.3
13
+ python-dotenv==1.0.0
14
+ dnspython==2.2.1
15
+ certifi==2023.7.22
16
+
17
+ # Production dependencies
18
+ gunicorn==21.2.0
19
+ gevent==23.9.1
20
+
21
+ # Security and monitoring
22
+ psutil==5.9.5
saved models/diabetes_model.sav ADDED
Binary file (27.9 kB). View file
 
saved models/heart_disease_model.sav ADDED
Binary file (1.21 kB). View file
 
saved models/parkinsons_model.sav ADDED
Binary file (12.7 kB). View file
 
start-prod.bat ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ REM Production startup script for HealthGuard-AI on Windows
3
+
4
+ REM Check if we're in the right directory
5
+ if not exist "app.py" (
6
+ echo Error: app.py not found. Please run this script from the project root directory.
7
+ pause
8
+ exit /b 1
9
+ )
10
+
11
+ REM Install production dependencies
12
+ echo Installing production dependencies...
13
+ pip install -r requirements-prod.txt
14
+
15
+ REM Check if models exist
16
+ if not exist "saved models" (
17
+ echo Error: 'saved models' directory not found.
18
+ pause
19
+ exit /b 1
20
+ )
21
+
22
+ REM Check for required models
23
+ set MODELS=diabetes_model.sav heart_disease_model.sav parkinsons_model.sav
24
+ for %%m in (%MODELS%) do (
25
+ if not exist "saved models\%%m" (
26
+ echo Error: Required model file '%%m' not found in 'saved models' directory.
27
+ pause
28
+ exit /b 1
29
+ )
30
+ )
31
+
32
+ REM Start the application with Gunicorn (if available) or fallback to Python
33
+ echo Starting HealthGuard-AI application...
34
+ where gunicorn >nul 2>nul
35
+ if %errorlevel% == 0 (
36
+ gunicorn --workers 4 --bind 0.0.0.0:7860 --timeout 120 app:app
37
+ ) else (
38
+ echo Gunicorn not found, using Python development server...
39
+ python app.py
40
+ )
41
+
42
+ echo Application started successfully!
43
+ pause
start-prod.sh ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Production startup script for HealthGuard-AI
4
+
5
+ # Exit on any error
6
+ set -e
7
+
8
+ # Check if we're in the right directory
9
+ if [ ! -f "app.py" ]; then
10
+ echo "Error: app.py not found. Please run this script from the project root directory."
11
+ exit 1
12
+ fi
13
+
14
+ # Install production dependencies
15
+ echo "Installing production dependencies..."
16
+ pip install -r requirements-prod.txt
17
+
18
+ # Check if models exist
19
+ if [ ! -d "saved models" ]; then
20
+ echo "Error: 'saved models' directory not found."
21
+ exit 1
22
+ fi
23
+
24
+ # Check for required models
25
+ MODELS=("diabetes_model.sav" "heart_disease_model.sav" "parkinsons_model.sav")
26
+ for model in "${MODELS[@]}"; do
27
+ if [ ! -f "saved models/$model" ]; then
28
+ echo "Error: Required model file '$model' not found in 'saved models' directory."
29
+ exit 1
30
+ fi
31
+ done
32
+
33
+ # Start the application with Gunicorn
34
+ echo "Starting HealthGuard-AI application..."
35
+ gunicorn --workers 4 --bind 0.0.0.0:7860 --timeout 120 app:app
36
+
37
+ echo "Application started successfully!"
static/css/style.css ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Light mode variables with new color palette */
2
+ :root {
3
+ /* New color palette */
4
+ --bg-color: #cde8d0; /* Secondary / Cards / Panels - Light Sage */
5
+ --text-color: #333333; /* Text Primary - Charcoal */
6
+ --text-secondary: #666666; /* Text Secondary - Gray */
7
+ --card-bg: #cde8d0; /* Cards / forms */
8
+ --border-color: #ced4da; /* Input borders */
9
+ --header-bg: #006d5b; /* Primary / Header / Navbar - Dark Teal */
10
+ --header-gradient-start: #006d5b;
11
+ --header-gradient-end: #005a4b; /* slightly darker on hover */
12
+ --success-color: #32cd32; /* Success / Accepted - Lime Green */
13
+ --danger-color: #dc143c; /* Danger / Rejected - Crimson */
14
+ --warning-color: #ffb347; /* Warning / Pending - Amber */
15
+ --info-color: #ff6b6b; /* Accent / Buttons / Highlights - Coral */
16
+ --secondary-color: #cde8d0; /* Secondary - Light Sage */
17
+ --accent-color: #cde8d0; /* Secondary - Light Sage */
18
+ --shadow-color: rgba(0,0,0,0.1); /* subtle shadow */
19
+ --chat-sent-bg: #ffd7ba; /* Chat User Bubble - Peach */
20
+ --chat-received-bg: #aaf0d1; /* Chat Doctor Bubble - Mint */
21
+ --chat-user-bubble: #ffd7ba; /* Chat User Bubble - Peach */
22
+ --chat-doctor-bubble: #aaf0d1; /* Chat Doctor Bubble - Mint */
23
+ }
24
+
25
+ .dark-mode {
26
+ --bg-color: #121212;
27
+ --text-color: #e0e0e0;
28
+ --card-bg: #1e1e1e;
29
+ --border-color: #444444;
30
+ --header-bg: #006d5b;
31
+ --header-gradient-start: #006d5b;
32
+ --header-gradient-end: #005a4b;
33
+ --success-color: #32cd32;
34
+ --danger-color: #dc143c;
35
+ --warning-color: #ffb347;
36
+ --info-color: #ff6b6b;
37
+ --secondary-color: #95a5a6;
38
+ --accent-color: #2c3e50;
39
+ --shadow-color: rgba(0, 0, 0, 0.3);
40
+ --chat-sent-bg: #ffd7ba;
41
+ --chat-received-bg: #aaf0d1;
42
+ --chat-user-bubble: #ffd7ba;
43
+ --chat-doctor-bubble: #aaf0d1;
44
+ }
45
+
46
+ body {
47
+ background-color: var(--bg-color);
48
+ color: var(--text-color);
49
+ transition: background-color 0.3s, color 0.3s;
50
+ font-family: 'Poppins', 'Montserrat', 'Raleway', 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
51
+ font-weight: 400;
52
+ line-height: 1.6;
53
+ }
54
+
55
+ .card {
56
+ background: linear-gradient(135deg, #cde8d0, #aaf0d1);
57
+ border: none;
58
+ transition: all 0.3s ease;
59
+ border-radius: 12px;
60
+ box-shadow: 0 8px 20px rgba(0,0,0,0.1);
61
+ padding: 1.5rem;
62
+ margin: 1rem;
63
+ }
64
+
65
+ .card:hover {
66
+ box-shadow: 0 12px 30px rgba(0,0,0,0.15);
67
+ transform: translateY(-5px);
68
+ transition: all 0.3s ease;
69
+ }
70
+
71
+ .navbar {
72
+ background: rgba(0,109,91,0.8) !important;
73
+ backdrop-filter: blur(10px);
74
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
75
+ border-bottom: none;
76
+ transition: all 0.3s ease;
77
+ }
78
+
79
+ .navbar .nav-link:hover {
80
+ transform: scale(1.1);
81
+ transition: all 0.3s ease;
82
+ }
83
+
84
+ .form-control, .form-select {
85
+ background-color: var(--card-bg);
86
+ color: var(--text-color);
87
+ border: 1px solid var(--border-color);
88
+ border-radius: 10px;
89
+ padding: 0.75rem 1rem;
90
+ transition: all 0.3s ease;
91
+ }
92
+
93
+ .form-control:focus, .form-select:focus {
94
+ background-color: var(--card-bg);
95
+ color: var(--text-color);
96
+ border-color: #ff6b6b;
97
+ box-shadow: 0 0 8px #ff6b6b;
98
+ }
99
+
100
+ .btn {
101
+ border-radius: 12px;
102
+ padding: 0.5rem 1.25rem;
103
+ font-weight: 500;
104
+ transition: all 0.3s ease;
105
+ border: none;
106
+ box-shadow: 0 4px 15px rgba(0,0,0,0.2);
107
+ }
108
+
109
+ .btn-primary {
110
+ background: linear-gradient(45deg, #ff6b6b, #ffb347);
111
+ border: none;
112
+ box-shadow: 0 4px 15px rgba(0,0,0,0.2);
113
+ color: #fff;
114
+ }
115
+
116
+ .btn-primary:hover {
117
+ background: linear-gradient(45deg, #ff6b6b, #ffb347);
118
+ transform: translateY(-5px);
119
+ box-shadow: 0 6px 20px rgba(0,0,0,0.3);
120
+ }
121
+
122
+ .btn-secondary {
123
+ background-color: var(--secondary-color);
124
+ color: #333333;
125
+ box-shadow: 0 4px 15px rgba(0,0,0,0.2);
126
+ }
127
+
128
+ .btn-secondary:hover {
129
+ background-color: #a8d8aa;
130
+ transform: translateY(-5px);
131
+ box-shadow: 0 6px 20px rgba(149, 165, 166, 0.4);
132
+ }
133
+
134
+ .btn-outline-primary {
135
+ border: 1px solid var(--header-bg);
136
+ color: var(--header-bg);
137
+ }
138
+
139
+ .btn-outline-primary:hover {
140
+ background-color: var(--header-bg);
141
+ color: #333333;
142
+ }
143
+
144
+ .dashboard-card {
145
+ transition: transform 0.3s, box-shadow 0.3s;
146
+ height: 100%;
147
+ border-radius: 12px;
148
+ border: none;
149
+ box-shadow: 0 8px 20px rgba(0,0,0,0.1);
150
+ background: linear-gradient(135deg, #cde8d0, #aaf0d1);
151
+ padding: 1.5rem;
152
+ margin: 1rem;
153
+ }
154
+
155
+ .dashboard-card:hover {
156
+ transform: translateY(-5px);
157
+ box-shadow: 0 12px 30px rgba(0,0,0,0.15);
158
+ transition: all 0.3s ease;
159
+ }
160
+
161
+ .dashboard-card .card-body {
162
+ padding: 1.5rem;
163
+ }
164
+
165
+ .prediction-form .form-group {
166
+ margin-bottom: 1.25rem;
167
+ }
168
+
169
+ .result-card {
170
+ border-left: 6px solid var(--success-color);
171
+ border-radius: 12px;
172
+ box-shadow: 0 0.25rem 0.5rem var(--shadow-color);
173
+ background: linear-gradient(135deg, #cde8d0, #aaf0d1);
174
+ }
175
+
176
+ .result-card.positive {
177
+ border-left-color: var(--danger-color);
178
+ }
179
+
180
+ .result-card h3 {
181
+ font-weight: 700;
182
+ margin-bottom: 0.5rem;
183
+ }
184
+
185
+ /* Theme toggle removed; dark mode still supported via `.dark-mode` class if needed */
186
+
187
+ .health-tip {
188
+ border-left: 4px solid var(--header-bg);
189
+ padding: 20px;
190
+ margin: 20px 0;
191
+ background-color: var(--accent-color);
192
+ border-radius: 0 8px 8px 0;
193
+ }
194
+
195
+ .health-tip h5 {
196
+ color: var(--header-bg);
197
+ margin-top: 0;
198
+ font-weight: 700;
199
+ }
200
+
201
+ .health-tip ul {
202
+ padding-left: 1.25rem;
203
+ }
204
+
205
+ .health-tip li {
206
+ margin-bottom: 0.5rem;
207
+ }
208
+
209
+ .report-table th {
210
+ background: linear-gradient(135deg, var(--header-gradient-start), var(--header-gradient-end));
211
+ color: #333333;
212
+ border: none;
213
+ font-weight: 700;
214
+ }
215
+
216
+ .report-table tr:hover {
217
+ background-color: var(--accent-color);
218
+ }
219
+
220
+ .jumbotron {
221
+ background: linear-gradient(135deg, var(--header-gradient-start), var(--header-gradient-end));
222
+ color: #333333;
223
+ border-radius: 12px;
224
+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);
225
+ padding: 2.5rem 2rem;
226
+ margin-bottom: 2rem;
227
+ transition: all 0.3s ease;
228
+ }
229
+
230
+ .jumbotron h1 {
231
+ font-weight: 700;
232
+ margin-bottom: 1rem;
233
+ }
234
+
235
+ .jumbotron p {
236
+ font-size: 1.1rem;
237
+ opacity: 0.9;
238
+ }
239
+
240
+ /* Responsive adjustments */
241
+ @media (max-width: 768px) {
242
+ .dashboard-card {
243
+ margin-bottom: 20px;
244
+ }
245
+
246
+ /* theme-toggle removed */
247
+
248
+ .card {
249
+ margin-bottom: 15px;
250
+ }
251
+
252
+ .table-responsive {
253
+ font-size: 0.9rem;
254
+ }
255
+
256
+ .navbar-brand {
257
+ font-size: 1.2rem;
258
+ }
259
+
260
+ .nav-link {
261
+ font-size: 0.9rem;
262
+ }
263
+
264
+ .jumbotron {
265
+ padding: 1.5rem 1.25rem;
266
+ }
267
+ }
268
+
269
+ @media (max-width: 576px) {
270
+ .container {
271
+ padding-left: 10px;
272
+ padding-right: 10px;
273
+ }
274
+
275
+ .card-body {
276
+ padding: 1.25rem;
277
+ }
278
+
279
+ h1 {
280
+ font-size: 1.5rem;
281
+ font-weight: 700;
282
+ }
283
+
284
+ h2 {
285
+ font-size: 1.3rem;
286
+ font-weight: 700;
287
+ }
288
+
289
+ .btn {
290
+ font-size: 0.85rem;
291
+ padding: 0.5rem 1rem;
292
+ }
293
+
294
+ .form-control, .form-select {
295
+ font-size: 0.95rem;
296
+ }
297
+
298
+ .jumbotron {
299
+ padding: 1.25rem 1rem;
300
+ }
301
+
302
+ .jumbotron h1 {
303
+ font-size: 1.5rem;
304
+ }
305
+ }
306
+
307
+ /* Chart container */
308
+ .chart-container {
309
+ position: relative;
310
+ height: 300px;
311
+ width: 100%;
312
+ margin: 20px 0;
313
+ border-radius: 12px;
314
+ overflow: hidden;
315
+ box-shadow: 0 8px 20px rgba(0,0,0,0.1);
316
+ transition: all 0.3s ease;
317
+ background: linear-gradient(135deg, #cde8d0, #aaf0d1);
318
+ padding: 10px;
319
+ }
320
+
321
+ /* Ensure charts shrink on small devices */
322
+ @media (max-width: 768px) {
323
+ .chart-container { height: 220px; }
324
+ }
325
+
326
+ @media (max-width: 576px) {
327
+ .chart-container { height: 180px; }
328
+ .dashboard-card .card-body { padding: 1rem; }
329
+ }
330
+
331
+ /* Chart bars */
332
+ .chart-bar {
333
+ border-radius: 8px;
334
+ transition: all 0.3s ease;
335
+ }
336
+
337
+ .chart-bar:hover {
338
+ transform: scale(1.05);
339
+ }
340
+
341
+ /* Chart tooltips */
342
+ .chart-tooltip {
343
+ background: rgba(0,109,91,0.8);
344
+ backdrop-filter: blur(10px);
345
+ border-radius: 8px;
346
+ box-shadow: 0 4px 12px rgba(0,0,0,0.15);
347
+ padding: 10px;
348
+ color: #333333;
349
+ }
350
+
351
+ /* Badge styles */
352
+ .badge {
353
+ font-size: 0.75em;
354
+ padding: 0.5em 0.75em;
355
+ border-radius: 12px;
356
+ }
357
+
358
+ /* Alert styles */
359
+ .alert {
360
+ border-radius: 8px;
361
+ box-shadow: 0 0.25rem 0.5rem var(--shadow-color);
362
+ border: none;
363
+ padding: 1rem 1.25rem;
364
+ }
365
+
366
+ .alert-success {
367
+ background-color: rgba(50, 205, 50, 0.15);
368
+ color: #32cd32;
369
+ }
370
+
371
+ .alert-danger {
372
+ background-color: rgba(220, 20, 60, 0.15);
373
+ color: #dc143c;
374
+ }
375
+
376
+ .alert-warning {
377
+ background-color: rgba(255, 179, 71, 0.15);
378
+ color: #ffb347;
379
+ }
380
+
381
+ /* Footer */
382
+ footer {
383
+ background-color: var(--card-bg);
384
+ border-top: 1px solid var(--border-color);
385
+ color: var(--text-color);
386
+ padding: 2rem 0;
387
+ margin-top: 3rem;
388
+ }
389
+
390
+ /* Input validation */
391
+ .is-invalid {
392
+ border-color: var(--danger-color) !important;
393
+ box-shadow: 0 0 0 0.25rem rgba(244, 67, 54, 0.25) !important;
394
+ }
395
+
396
+ .invalid-feedback {
397
+ color: var(--danger-color);
398
+ font-size: 0.875rem;
399
+ }
400
+
401
+ /* Button group spacing */
402
+ .btn-group .btn {
403
+ margin-right: 8px;
404
+ }
405
+
406
+ /* Icon sizes */
407
+ .bi {
408
+ width: 1em;
409
+ height: 1em;
410
+ }
411
+
412
+ .bi-lg {
413
+ width: 1.5em;
414
+ height: 1.5em;
415
+ }
416
+
417
+ /* Table adjustments */
418
+ .table th {
419
+ border-top: none;
420
+ font-weight: 700;
421
+ }
422
+
423
+ .table td, .table th {
424
+ vertical-align: middle;
425
+ padding: 0.75rem;
426
+ }
427
+
428
+ /* List group */
429
+ .list-group-item {
430
+ background-color: var(--card-bg);
431
+ border: 1px solid var(--border-color);
432
+ color: var(--text-color);
433
+ border-radius: 8px !important;
434
+ margin-bottom: 0.5rem;
435
+ transition: all 0.3s ease;
436
+ }
437
+
438
+ .list-group-item:hover {
439
+ background-color: var(--accent-color);
440
+ transform: translateX(5px);
441
+ }
442
+
443
+ .list-group-item:first-child {
444
+ border-top-left-radius: 8px;
445
+ border-top-right-radius: 8px;
446
+ }
447
+
448
+ .list-group-item:last-child {
449
+ border-bottom-left-radius: 8px;
450
+ border-bottom-right-radius: 8px;
451
+ margin-bottom: 0;
452
+ }
453
+
454
+ /* Pagination */
455
+ .pagination .page-link {
456
+ background-color: var(--card-bg);
457
+ border: 1px solid var(--border-color);
458
+ color: var(--text-color);
459
+ border-radius: 8px;
460
+ margin: 0 2px;
461
+ transition: all 0.3s ease;
462
+ }
463
+
464
+ .pagination .page-link:hover {
465
+ background-color: var(--accent-color);
466
+ transform: translateY(-2px);
467
+ }
468
+
469
+ .pagination .active .page-link {
470
+ background: linear-gradient(135deg, var(--header-gradient-start), var(--header-gradient-end));
471
+ border-color: var(--header-bg);
472
+ color: #333333;
473
+ }
474
+
475
+ /* Form labels */
476
+ .form-label {
477
+ font-weight: 500;
478
+ margin-bottom: 0.5rem;
479
+ color: var(--text-color);
480
+ }
481
+
482
+ /* Card headers */
483
+ .card-header {
484
+ background-color: transparent;
485
+ border-bottom: 1px solid var(--border-color);
486
+ font-weight: 700;
487
+ padding: 1.25rem 1.5rem;
488
+ border-radius: 12px 12px 0 0 !important;
489
+ }
490
+
491
+ /* Chat styles */
492
+ .chat-container {
493
+ height: 400px;
494
+ display: flex;
495
+ flex-direction: column;
496
+ }
497
+
498
+ .chat-messages {
499
+ flex: 1;
500
+ overflow-y: auto;
501
+ padding: 1rem;
502
+ background-color: var(--accent-color);
503
+ border-radius: 8px;
504
+ margin-bottom: 1rem;
505
+ }
506
+
507
+ .message {
508
+ margin-bottom: 1rem;
509
+ max-width: 80%;
510
+ }
511
+
512
+ .message.sent {
513
+ margin-left: auto;
514
+ }
515
+
516
+ .message.received {
517
+ margin-right: auto;
518
+ }
519
+
520
+ .message-content {
521
+ padding: 0.75rem 1rem;
522
+ border-radius: 12px;
523
+ word-wrap: break-word;
524
+ box-shadow: 0 2px 5px rgba(0,0,0,0.1);
525
+ animation: float 0.3s ease;
526
+ }
527
+
528
+ .message.sent .message-content {
529
+ background-color: var(--chat-user-bubble);
530
+ color: #333333;
531
+ border-bottom-right-radius: 0;
532
+ }
533
+
534
+ .message.received .message-content {
535
+ background-color: var(--chat-doctor-bubble);
536
+ color: #333333;
537
+ border-bottom-left-radius: 0;
538
+ }
539
+
540
+ .message-time {
541
+ font-size: 0.75rem;
542
+ color: var(--secondary-color);
543
+ margin-top: 0.25rem;
544
+ text-align: right;
545
+ }
546
+
547
+ .chat-container .card-footer {
548
+ padding: 1rem 1.25rem;
549
+ }
550
+
551
+ /* Form checks */
552
+ .form-check {
553
+ margin-bottom: 0.5rem;
554
+ }
555
+
556
+ .form-check-input:checked {
557
+ background-color: #ff6b6b;
558
+ border-color: #ff6b6b;
559
+ }
560
+
561
+ @keyframes float {
562
+ 0% { transform: translateY(10px); opacity: 0; }
563
+ 100% { transform: translateY(0); opacity: 1; }
564
+ }
565
+
566
+ @keyframes chartHover {
567
+ 0% { transform: scale(1); }
568
+ 50% { transform: scale(1.05); }
569
+ 100% { transform: scale(1); }
570
+ }
static/js/script.js ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Theme toggle functionality
2
+ document.addEventListener('DOMContentLoaded', function() {
3
+ // Theme toggle removed; dark mode may be toggled by server-side or manual class if needed.
4
+
5
+ // Check for saved theme preference or respect OS preference
6
+
7
+
8
+ // Theme toggle functionality removed per UX requirement.
9
+
10
+ // Form validation for prediction forms
11
+ const predictionForms = document.querySelectorAll('.prediction-form');
12
+ predictionForms.forEach(form => {
13
+ form.addEventListener('submit', function(e) {
14
+ const inputs = this.querySelectorAll('input[type="text"]');
15
+ let isValid = true;
16
+
17
+ inputs.forEach(input => {
18
+ if (!input.value.trim()) {
19
+ input.classList.add('is-invalid');
20
+ isValid = false;
21
+ } else {
22
+ // Check if input is a valid number
23
+ if (isNaN(input.value)) {
24
+ input.classList.add('is-invalid');
25
+ isValid = false;
26
+ } else {
27
+ input.classList.remove('is-invalid');
28
+ }
29
+ }
30
+ });
31
+
32
+ if (!isValid) {
33
+ e.preventDefault();
34
+ // Show a more user-friendly alert
35
+ const alertDiv = document.createElement('div');
36
+ alertDiv.className = 'alert alert-danger alert-dismissible fade show mt-3';
37
+ alertDiv.innerHTML = `
38
+ <strong>Error!</strong> Please fill in all fields with valid numbers.
39
+ <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
40
+ `;
41
+ form.insertBefore(alertDiv, form.firstChild);
42
+ // Remove alert after 5 seconds
43
+ setTimeout(() => {
44
+ if (alertDiv.parentNode) {
45
+ alertDiv.remove();
46
+ }
47
+ }, 5000);
48
+ }
49
+ });
50
+ });
51
+
52
+ // Real-time validation for number inputs
53
+ const numberInputs = document.querySelectorAll('input[type="text"]');
54
+ numberInputs.forEach(input => {
55
+ input.addEventListener('input', function() {
56
+ if (this.value && isNaN(this.value)) {
57
+ this.classList.add('is-invalid');
58
+ } else {
59
+ this.classList.remove('is-invalid');
60
+ }
61
+ });
62
+ });
63
+
64
+ // Confirmation for delete actions
65
+ const deleteButtons = document.querySelectorAll('.delete-btn');
66
+ deleteButtons.forEach(button => {
67
+ button.addEventListener('click', function(e) {
68
+ if (!confirm('Are you sure you want to delete this record? This action cannot be undone.')) {
69
+ e.preventDefault();
70
+ }
71
+ });
72
+ });
73
+
74
+ // Auto-hide alerts after 5 seconds
75
+ const alerts = document.querySelectorAll('.alert');
76
+ alerts.forEach(alert => {
77
+ setTimeout(() => {
78
+ alert.classList.remove('show');
79
+ alert.classList.add('hide');
80
+ }, 5000);
81
+ });
82
+
83
+ // Mobile menu toggle
84
+ const navbarToggler = document.querySelector('.navbar-toggler');
85
+ const navbarCollapse = document.querySelector('.navbar-collapse');
86
+
87
+ if (navbarToggler && navbarCollapse) {
88
+ navbarToggler.addEventListener('click', function() {
89
+ navbarCollapse.classList.toggle('show');
90
+ });
91
+ }
92
+
93
+ // Add animation to cards when they come into view
94
+ const cards = document.querySelectorAll('.card');
95
+ const observer = new IntersectionObserver((entries) => {
96
+ entries.forEach(entry => {
97
+ if (entry.isIntersecting) {
98
+ entry.target.style.opacity = 1;
99
+ entry.target.style.transform = 'translateY(0)';
100
+ }
101
+ });
102
+ }, { threshold: 0.1 });
103
+
104
+ cards.forEach(card => {
105
+ card.style.opacity = 0;
106
+ card.style.transform = 'translateY(20px)';
107
+ card.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
108
+ observer.observe(card);
109
+ });
110
+
111
+ // Add floating animation to new messages
112
+ const messages = document.querySelectorAll('.message');
113
+ messages.forEach(message => {
114
+ message.classList.add('float-animation');
115
+ });
116
+ });
117
+
118
+ // Function to print report
119
+ function printReport() {
120
+ window.print();
121
+ }
122
+
123
+ // Function to download report as PDF
124
+ function downloadPDF() {
125
+ // In a real implementation, this would generate a PDF
126
+ alert('PDF download functionality would be implemented here');
127
+ }
128
+
129
+ // Function to show loading spinner during form submission
130
+ function showLoadingSpinner(form) {
131
+ const submitButton = form.querySelector('button[type="submit"]');
132
+ if (submitButton) {
133
+ submitButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Processing...';
134
+ submitButton.disabled = true;
135
+ }
136
+ }
137
+
138
+ // Add loading spinner to all forms
139
+ document.addEventListener('DOMContentLoaded', function() {
140
+ const forms = document.querySelectorAll('form');
141
+ forms.forEach(form => {
142
+ form.addEventListener('submit', function() {
143
+ showLoadingSpinner(this);
144
+ });
145
+ });
146
+ });
templates/__pycache__/app.cpython-312.pyc ADDED
Binary file (70.9 kB). View file
 
templates/admin/appointments.html ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Manage Appointments - Admin Dashboard{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row">
7
+ <div class="col-12">
8
+ <h2><i class="bi bi-calendar-check"></i> Manage Appointments</h2>
9
+ <p class="lead">Review and manage patient appointments</p>
10
+ </div>
11
+ </div>
12
+
13
+ <div class="row mt-4">
14
+ <div class="col-12">
15
+ <ul class="nav nav-tabs" id="appointmentTabs" role="tablist">
16
+ <li class="nav-item" role="presentation">
17
+ <button class="nav-link active" id="pending-tab" data-bs-toggle="tab" data-bs-target="#pending" type="button" role="tab">Pending Appointments</button>
18
+ </li>
19
+ <li class="nav-item" role="presentation">
20
+ <button class="nav-link" id="confirmed-tab" data-bs-toggle="tab" data-bs-target="#confirmed" type="button" role="tab">Confirmed Appointments</button>
21
+ </li>
22
+ <li class="nav-item" role="presentation">
23
+ <button class="nav-link" id="schedule-tab" data-bs-toggle="tab" data-bs-target="#schedule" type="button" role="tab">My Schedule</button>
24
+ </li>
25
+ </ul>
26
+
27
+ <div class="tab-content" id="appointmentTabsContent">
28
+ <div class="tab-pane fade show active" id="pending" role="tabpanel">
29
+ <div class="card mt-3">
30
+ <div class="card-header">
31
+ <h5 class="card-title mb-0">Pending Appointments</h5>
32
+ </div>
33
+ <div class="card-body">
34
+ {% if pending_appointments %}
35
+ <div class="table-responsive">
36
+ <table class="table table-striped">
37
+ <thead>
38
+ <tr>
39
+ <th>Patient</th>
40
+ <th>Disease/Condition</th>
41
+ <th>Doctor</th>
42
+ <th>Date & Time</th>
43
+ <th>Notes</th>
44
+ <th>Actions</th>
45
+ </tr>
46
+ </thead>
47
+ <tbody>
48
+ {% for appointment in pending_appointments %}
49
+ <tr>
50
+ <td>
51
+ {{ appointment.patient_name }}<br>
52
+ <small class="text-muted">{{ appointment.patient_email }}</small>
53
+ </td>
54
+ <td>{{ appointment.disease_type }}</td>
55
+ <td>{{ appointment.doctor }}</td>
56
+ <td>{{ appointment.date.strftime('%Y-%m-%d') }} at {{ appointment.time }}</td>
57
+ <td>{{ appointment.notes }}</td>
58
+ <td>
59
+ <form method="POST" action="/admin/appointments/{{ appointment._id }}/confirm" class="d-inline">
60
+ <button type="submit" class="btn btn-sm btn-success">
61
+ <i class="bi bi-check-circle"></i> Confirm
62
+ </button>
63
+ </form>
64
+ <form method="POST" action="/admin/appointments/{{ appointment._id }}/reject" class="d-inline">
65
+ <button type="submit" class="btn btn-sm btn-danger">
66
+ <i class="bi bi-x-circle"></i> Reject
67
+ </button>
68
+ </form>
69
+ </td>
70
+ </tr>
71
+ {% endfor %}
72
+ </tbody>
73
+ </table>
74
+ </div>
75
+ {% else %}
76
+ <p class="text-muted">No pending appointments found.</p>
77
+ {% endif %}
78
+ </div>
79
+ </div>
80
+ </div>
81
+
82
+ <div class="tab-pane fade" id="confirmed" role="tabpanel">
83
+ <div class="card mt-3">
84
+ <div class="card-header">
85
+ <h5 class="card-title mb-0">Confirmed Appointments</h5>
86
+ </div>
87
+ <div class="card-body">
88
+ {% if confirmed_appointments %}
89
+ <div class="table-responsive">
90
+ <table class="table table-striped">
91
+ <thead>
92
+ <tr>
93
+ <th>Patient</th>
94
+ <th>Disease/Condition</th>
95
+ <th>Doctor</th>
96
+ <th>Date & Time</th>
97
+ <th>Notes</th>
98
+ <th>Status</th>
99
+ </tr>
100
+ </thead>
101
+ <tbody>
102
+ {% for appointment in confirmed_appointments %}
103
+ <tr>
104
+ <td>
105
+ {{ appointment.patient_name }}<br>
106
+ <small class="text-muted">{{ appointment.patient_email }}</small>
107
+ </td>
108
+ <td>{{ appointment.disease_type }}</td>
109
+ <td>{{ appointment.doctor }}</td>
110
+ <td>{{ appointment.date.strftime('%Y-%m-%d') }} at {{ appointment.time }}</td>
111
+ <td>{{ appointment.notes }}</td>
112
+ <td>
113
+ <span class="badge bg-success">Confirmed</span>
114
+ </td>
115
+ </tr>
116
+ {% endfor %}
117
+ </tbody>
118
+ </table>
119
+ </div>
120
+ {% else %}
121
+ <p class="text-muted">No confirmed appointments found.</p>
122
+ {% endif %}
123
+ </div>
124
+ </div>
125
+ </div>
126
+
127
+ <div class="tab-pane fade" id="schedule" role="tabpanel">
128
+ <div class="card mt-3">
129
+ <div class="card-header">
130
+ <h5 class="card-title mb-0">My Schedule</h5>
131
+ </div>
132
+ <div class="card-body">
133
+ <div class="row">
134
+ <div class="col-md-8">
135
+ <div id="calendar"></div>
136
+ </div>
137
+ <div class="col-md-4">
138
+ <h5>Available Time Slots</h5>
139
+ <div class="list-group">
140
+ <a href="#" class="list-group-item list-group-item-action">
141
+ <div class="d-flex w-100 justify-content-between">
142
+ <h6 class="mb-1">Morning Slots</h6>
143
+ </div>
144
+ <small>9:00 AM - 12:00 PM</small>
145
+ </a>
146
+ <a href="#" class="list-group-item list-group-item-action">
147
+ <div class="d-flex w-100 justify-content-between">
148
+ <h6 class="mb-1">Afternoon Slots</h6>
149
+ </div>
150
+ <small>2:00 PM - 5:00 PM</small>
151
+ </a>
152
+ <a href="#" class="list-group-item list-group-item-action">
153
+ <div class="d-flex w-100 justify-content-between">
154
+ <h6 class="mb-1">Evening Slots</h6>
155
+ </div>
156
+ <small>6:00 PM - 8:00 PM</small>
157
+ </a>
158
+ </div>
159
+
160
+ <div class="mt-4">
161
+ <h5>Quick Actions</h5>
162
+ <button class="btn btn-primary w-100 mb-2">
163
+ <i class="bi bi-plus-circle"></i> Add Time Slot
164
+ </button>
165
+ <button class="btn btn-outline-secondary w-100">
166
+ <i class="bi bi-calendar"></i> Set Availability
167
+ </button>
168
+ </div>
169
+ </div>
170
+ </div>
171
+ </div>
172
+ </div>
173
+ </div>
174
+ </div>
175
+ </div>
176
+ </div>
177
+
178
+ {% endblock %}
179
+
180
+ {% block scripts %}
181
+ <script>
182
+ document.addEventListener('DOMContentLoaded', function() {
183
+ // Simple calendar implementation
184
+ const calendarEl = document.getElementById('calendar');
185
+ if (calendarEl) {
186
+ const today = new Date();
187
+ const month = today.toLocaleString('default', { month: 'long' });
188
+ const year = today.getFullYear();
189
+
190
+ let calendarHTML = `<h5>${month} ${year}</h5>`;
191
+ calendarHTML += '<div class="table-responsive">';
192
+ calendarHTML += '<table class="table table-bordered">';
193
+ calendarHTML += '<thead><tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr></thead>';
194
+ calendarHTML += '<tbody>';
195
+
196
+ // Generate calendar (simplified)
197
+ const daysInMonth = new Date(year, today.getMonth() + 1, 0).getDate();
198
+ const firstDay = new Date(year, today.getMonth(), 1).getDay();
199
+
200
+ let day = 1;
201
+ for (let i = 0; i < 6; i++) {
202
+ calendarHTML += '<tr>';
203
+ for (let j = 0; j < 7; j++) {
204
+ if (i === 0 && j < firstDay) {
205
+ calendarHTML += '<td></td>';
206
+ } else if (day > daysInMonth) {
207
+ calendarHTML += '<td></td>';
208
+ } else {
209
+ const isToday = (day === today.getDate());
210
+ calendarHTML += `<td class="${isToday ? 'table-primary' : ''}">${day}</td>`;
211
+ day++;
212
+ }
213
+ }
214
+ calendarHTML += '</tr>';
215
+ if (day > daysInMonth) break;
216
+ }
217
+
218
+ calendarHTML += '</tbody></table></div>';
219
+ calendarEl.innerHTML = calendarHTML;
220
+ }
221
+ });
222
+ </script>
223
+ {% endblock %}
templates/admin/dashboard.html ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Admin Dashboard - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row">
7
+ <div class="col-12">
8
+ <h2>Admin Dashboard</h2>
9
+ <p class="lead">Welcome, {{ session.username }}! Manage the system and view analytics.</p>
10
+ </div>
11
+ </div>
12
+
13
+ <div class="row mt-4">
14
+ <div class="col-md-3 mb-4">
15
+ <div class="card text-dark bg-primary h-100">
16
+ <div class="card-body">
17
+ <h5 class="card-title"><i class="bi bi-people"></i> Total Users</h5>
18
+ <h2>{{ total_users }}</h2>
19
+ </div>
20
+ </div>
21
+ </div>
22
+
23
+ <div class="col-md-3 mb-4">
24
+ <div class="card text-dark bg-danger h-100">
25
+ <div class="card-body">
26
+ <h5 class="card-title"><i class="bi bi-heart"></i> Heart Predictions</h5>
27
+ <h2>{{ heart_predictions }}</h2>
28
+ </div>
29
+ </div>
30
+ </div>
31
+
32
+ <div class="col-md-3 mb-4">
33
+ <div class="card text-dark bg-warning h-100">
34
+ <div class="card-body">
35
+ <h5 class="card-title"><i class="bi bi-droplet"></i> Diabetes Predictions</h5>
36
+ <h2>{{ diabetes_predictions }}</h2>
37
+ </div>
38
+ </div>
39
+ </div>
40
+
41
+ <div class="col-md-3 mb-4">
42
+ <div class="card text-dark bg-info h-100">
43
+ <div class="card-body">
44
+ <h5 class="card-title"><i class="bi bi-person-circle"></i> Parkinson's Predictions</h5>
45
+ <h2>{{ parkinsons_predictions }}</h2>
46
+ </div>
47
+ </div>
48
+ </div>
49
+
50
+ <!-- Add Appointments Card -->
51
+ <div class="col-md-3 mb-4">
52
+ <div class="card text-dark bg-success h-100">
53
+ <div class="card-body">
54
+ <h5 class="card-title"><i class="bi bi-calendar-check"></i> Appointments</h5>
55
+ <h2>
56
+ {% set pending_count = 0 %}
57
+ {% for appointment in all_predictions %}
58
+ {% if appointment.status == 'pending' %}
59
+ {% set pending_count = pending_count + 1 %}
60
+ {% endif %}
61
+ {% endfor %}
62
+ {{ pending_count }}
63
+ </h2>
64
+ <a href="/admin/appointments" class="text-dark stretched-link">Manage</a>
65
+ </div>
66
+ </div>
67
+ </div>
68
+ </div>
69
+
70
+ <div class="row mt-4">
71
+ <div class="col-md-8 mb-4">
72
+ <div class="card">
73
+ <div class="card-header">
74
+ <h5 class="card-title mb-0"><i class="bi bi-bar-chart"></i> Prediction Analytics</h5>
75
+ </div>
76
+ <div class="card-body">
77
+ <canvas id="predictionChart" height="100"></canvas>
78
+ </div>
79
+ </div>
80
+ </div>
81
+
82
+ <div class="col-md-4 mb-4">
83
+ <div class="card">
84
+ <div class="card-header">
85
+ <h5 class="card-title mb-0"><i class="bi bi-person-lines-fill"></i> Recent Users</h5>
86
+ </div>
87
+ <div class="card-body">
88
+ {% if recent_users %}
89
+ <div class="list-group">
90
+ {% for user in recent_users %}
91
+ <div class="list-group-item">
92
+ <div class="d-flex w-100 justify-content-between">
93
+ <h6 class="mb-1">{{ user.name }}</h6>
94
+ <small>{{ user.created_at.strftime('%Y-%m-%d') }}</small>
95
+ </div>
96
+ <p class="mb-1">{{ user.email }}</p>
97
+ </div>
98
+ {% endfor %}
99
+ </div>
100
+ {% else %}
101
+ <p>No recent users.</p>
102
+ {% endif %}
103
+ </div>
104
+ </div>
105
+ </div>
106
+ </div>
107
+
108
+ <div class="row mt-4">
109
+ <div class="col-12">
110
+ <div class="card">
111
+ <div class="card-header">
112
+ <h5 class="card-title mb-0"><i class="bi bi-clipboard-data"></i> Patient Reports</h5>
113
+ </div>
114
+ <div class="card-body">
115
+ {% if all_predictions %}
116
+ <div class="table-responsive">
117
+ <table class="table table-striped report-table">
118
+ <thead>
119
+ <tr>
120
+ <th>Patient</th>
121
+ <th>Disease</th>
122
+ <th>Date</th>
123
+ <th>Result</th>
124
+ <th>Actions</th>
125
+ </tr>
126
+ </thead>
127
+ <tbody>
128
+ {% for prediction in all_predictions %}
129
+ <tr>
130
+ <td>{{ prediction.user_name }}</td>
131
+ <td>{{ prediction.disease_type }}</td>
132
+ <td>{{ prediction.date.strftime('%Y-%m-%d %H:%M') }}</td>
133
+ <td>{{ prediction.result }}</td>
134
+ <td>
135
+ <a href="/admin/report/{{ prediction._id }}" class="btn btn-sm btn-outline-primary">View</a>
136
+ </td>
137
+ </tr>
138
+ {% endfor %}
139
+ </tbody>
140
+ </table>
141
+ </div>
142
+ {% else %}
143
+ <p>No patient reports available.</p>
144
+ {% endif %}
145
+ </div>
146
+ </div>
147
+ </div>
148
+ </div>
149
+
150
+
151
+
152
+ {% endblock %}
153
+
154
+ {% block scripts %}
155
+ <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
156
+ <script>
157
+ // Create chart with data passed from Flask
158
+ document.addEventListener('DOMContentLoaded', function() {
159
+ const ctx = document.getElementById('predictionChart').getContext('2d');
160
+ const predictionChart = new Chart(ctx, {
161
+ type: 'bar',
162
+ data: {
163
+ labels: ['Heart Disease', 'Diabetes', 'Parkinson\'s'],
164
+ datasets: [{
165
+ label: 'Number of Predictions',
166
+ data: [
167
+ parseInt('{{ heart_predictions }}') || 0,
168
+ parseInt('{{ diabetes_predictions }}') || 0,
169
+ parseInt('{{ parkinsons_predictions }}') || 0
170
+ ],
171
+ backgroundColor: [
172
+ 'rgba(220, 53, 69, 0.7)',
173
+ 'rgba(255, 193, 7, 0.7)',
174
+ 'rgba(23, 162, 184, 0.7)'
175
+ ],
176
+ borderColor: [
177
+ 'rgba(220, 53, 69, 1)',
178
+ 'rgba(255, 193, 7, 1)',
179
+ 'rgba(23, 162, 184, 1)'
180
+ ],
181
+ borderWidth: 1
182
+ }]
183
+ },
184
+ options: {
185
+ scales: {
186
+ y: {
187
+ beginAtZero: true,
188
+ ticks: {
189
+ precision: 0
190
+ }
191
+ }
192
+ }
193
+ }
194
+ });
195
+ });
196
+ </script>
197
+ {% endblock %}
templates/auth/forgot_password.html ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Forgot Password - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row justify-content-center">
7
+ <div class="col-md-6">
8
+ <div class="card">
9
+ <div class="card-header">
10
+ <h3 class="text-center"><i class="bi bi-key"></i> Forgot Password</h3>
11
+ </div>
12
+ <div class="card-body">
13
+ <p class="text-center">Enter your email address and we'll send you a link to reset your password.</p>
14
+ <form method="POST" action="/forgot-password">
15
+ <div class="mb-3">
16
+ <label for="email" class="form-label">Email address</label>
17
+ <input type="email" class="form-control" id="email" name="email" required>
18
+ </div>
19
+ <button type="submit" class="btn btn-primary w-100">Send Reset Link</button>
20
+ </form>
21
+ <div class="text-center mt-3">
22
+ <a href="/login">Back to Login</a>
23
+ </div>
24
+ </div>
25
+ </div>
26
+ </div>
27
+ </div>
28
+ {% endblock %}
templates/auth/login.html ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Login - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row justify-content-center">
7
+ <div class="col-md-6">
8
+ <div class="card">
9
+ <div class="card-header">
10
+ <h3 class="text-center"><i class="bi bi-box-arrow-in-right"></i> Login</h3>
11
+ </div>
12
+ <div class="card-body">
13
+ {% if get_flashed_messages() %}
14
+ {% with messages = get_flashed_messages(with_categories=true) %}
15
+ {% if messages %}
16
+ {% for category, message in messages %}
17
+ {% if message == 'Database connection error. Please contact administrator.' %}
18
+ <div class="alert alert-warning" role="alert">
19
+ <i class="bi bi-exclamation-triangle"></i>
20
+ <strong>Database Connection Issue:</strong> The application is currently running with a local database instead of MongoDB Atlas.
21
+ This is due to SSL/TLS connection issues with your MongoDB Atlas database.
22
+ For production use, please check the README.md file for troubleshooting steps.
23
+ </div>
24
+ {% endif %}
25
+ {% endfor %}
26
+ {% endif %}
27
+ {% endwith %}
28
+ {% endif %}
29
+
30
+ <form method="POST" action="/login">
31
+ <div class="mb-3">
32
+ <label for="email" class="form-label">Email address</label>
33
+ <input type="email" class="form-control" id="email" name="email" required>
34
+ </div>
35
+ <div class="mb-3">
36
+ <label for="password" class="form-label">Password</label>
37
+ <input type="password" class="form-control" id="password" name="password" required>
38
+ </div>
39
+ <div class="mb-3 form-check">
40
+ <input type="checkbox" class="form-check-input" id="remember">
41
+ <label class="form-check-label" for="remember">Remember me</label>
42
+ </div>
43
+ <button type="submit" class="btn btn-primary w-100">Login</button>
44
+ </form>
45
+ <div class="text-center mt-3">
46
+ <a href="/forgot-password">Forgot Password?</a>
47
+ </div>
48
+ <div class="text-center mt-2">
49
+ Don't have an account? <a href="/register">Register here</a>
50
+ </div>
51
+ </div>
52
+ </div>
53
+ </div>
54
+ </div>
55
+ {% endblock %}
templates/auth/register.html ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Register - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row justify-content-center">
7
+ <div class="col-md-6">
8
+ <div class="card">
9
+ <div class="card-header">
10
+ <h3 class="text-center"><i class="bi bi-person-plus"></i> Register</h3>
11
+ </div>
12
+ <div class="card-body">
13
+ {% if get_flashed_messages() %}
14
+ {% with messages = get_flashed_messages(with_categories=true) %}
15
+ {% if messages %}
16
+ {% for category, message in messages %}
17
+ {% if message == 'Database connection error. Please contact administrator.' %}
18
+ <div class="alert alert-warning" role="alert">
19
+ <i class="bi bi-exclamation-triangle"></i>
20
+ <strong>Database Connection Issue:</strong> The application is currently running with a local database instead of MongoDB Atlas.
21
+ This is due to SSL/TLS connection issues with your MongoDB Atlas database.
22
+ For production use, please check the README.md file for troubleshooting steps.
23
+ </div>
24
+ {% endif %}
25
+ {% endfor %}
26
+ {% endif %}
27
+ {% endwith %}
28
+ {% endif %}
29
+
30
+ <form method="POST" action="/register">
31
+ <div class="mb-3">
32
+ <label for="name" class="form-label">Full Name</label>
33
+ <input type="text" class="form-control" id="name" name="name" required>
34
+ </div>
35
+ <div class="mb-3">
36
+ <label for="email" class="form-label">Email address</label>
37
+ <input type="email" class="form-control" id="email" name="email" required>
38
+ </div>
39
+ <div class="mb-3">
40
+ <label for="phone" class="form-label">Phone Number</label>
41
+ <input type="tel" class="form-control" id="phone" name="phone" required>
42
+ </div>
43
+ <div class="mb-3">
44
+ <label for="role" class="form-label">Role</label>
45
+ <select class="form-select" id="role" name="role" onchange="toggleSpecialization()">
46
+ <option value="user">Patient</option>
47
+ <option value="doctor">Doctor</option>
48
+ </select>
49
+ </div>
50
+ <div class="mb-3" id="specializationField" style="display: none;">
51
+ <label for="specialization" class="form-label">Specialization</label>
52
+ <select class="form-select" id="specialization" name="specialization">
53
+ <option value="">Select Specialization</option>
54
+ <option value="Cardiologist">Cardiologist (Heart Disease)</option>
55
+ <option value="Endocrinologist">Endocrinologist (Diabetes)</option>
56
+ <option value="Neurologist">Neurologist (Parkinson's Disease)</option>
57
+ <option value="General Practitioner">General Practitioner</option>
58
+ </select>
59
+ </div>
60
+ <div class="mb-3">
61
+ <label for="password" class="form-label">Password</label>
62
+ <input type="password" class="form-control" id="password" name="password" required>
63
+ <div class="form-text">Password must be at least 6 characters long.</div>
64
+ </div>
65
+ <div class="mb-3">
66
+ <label for="confirm_password" class="form-label">Confirm Password</label>
67
+ <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
68
+ </div>
69
+ <button type="submit" class="btn btn-primary w-100">Register</button>
70
+ </form>
71
+ <div class="text-center mt-3">
72
+ Already have an account? <a href="/login">Login here</a>
73
+ </div>
74
+ </div>
75
+ </div>
76
+ </div>
77
+ </div>
78
+ {% endblock %}
79
+
80
+ {% block scripts %}
81
+ <script>
82
+ function toggleSpecialization() {
83
+ const role = document.getElementById('role').value;
84
+ const specializationField = document.getElementById('specializationField');
85
+
86
+ if (role === 'doctor') {
87
+ specializationField.style.display = 'block';
88
+ } else {
89
+ specializationField.style.display = 'none';
90
+ }
91
+ }
92
+ </script>
93
+ {% endblock %}
templates/auth/verify_otp.html ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Verify OTP - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row justify-content-center">
7
+ <div class="col-md-6">
8
+ <div class="card">
9
+ <div class="card-header">
10
+ <h3 class="text-center">Verify OTP</h3>
11
+ </div>
12
+ <div class="card-body">
13
+ <form method="POST" action="/verify-otp">
14
+ <div class="mb-3">
15
+ <label for="email" class="form-label">Email address</label>
16
+ <input type="email" class="form-control" id="email" name="email" required>
17
+ </div>
18
+ <div class="mb-3">
19
+ <label for="otp" class="form-label">OTP</label>
20
+ <input type="text" class="form-control" id="otp" name="otp" required>
21
+ </div>
22
+ <div class="mb-3">
23
+ <label for="new_password" class="form-label">New Password</label>
24
+ <input type="password" class="form-control" id="new_password" name="new_password" required>
25
+ </div>
26
+ <button type="submit" class="btn btn-primary w-100">Reset Password</button>
27
+ </form>
28
+ </div>
29
+ </div>
30
+ </div>
31
+ </div>
32
+ {% endblock %}
templates/base.html ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>{% block title %}Multiple Disease Prediction System{% endblock %}</title>
7
+ <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
8
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
9
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Montserrat:wght@400;500;600;700&family=Raleway:wght@400;500;600;700&display=swap">
10
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
11
+ {% block head %}{% endblock %}
12
+ </head>
13
+ <body>
14
+ <nav class="navbar navbar-expand-lg navbar-dark">
15
+ <div class="container">
16
+ <a class="navbar-brand" href="/">
17
+ <i class="bi bi-heart-pulse"></i> Health Assistant
18
+ </a>
19
+
20
+ <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
21
+ <span class="navbar-toggler-icon"></span>
22
+ </button>
23
+
24
+ <div class="collapse navbar-collapse" id="navbarNav">
25
+ <ul class="navbar-nav me-auto">
26
+ <li class="nav-item">
27
+ <a class="nav-link" href="/">Home</a>
28
+ </li>
29
+ {% if session.user_id %}
30
+ {% if session.user_role == 'admin' %}
31
+ <li class="nav-item">
32
+ <a class="nav-link" href="/admin/dashboard">Admin Dashboard</a>
33
+ </li>
34
+ <li class="nav-item">
35
+ <a class="nav-link" href="/admin/appointments">Appointments</a>
36
+ </li>
37
+ {% elif session.user_role == 'doctor' %}
38
+ <li class="nav-item">
39
+ <a class="nav-link" href="/doctor/appointments">Doctor Dashboard</a>
40
+ </li>
41
+ {% else %}
42
+ <li class="nav-item">
43
+ <a class="nav-link" href="/user/dashboard">Dashboard</a>
44
+ </li>
45
+ {% endif %}
46
+ {% endif %}
47
+ </ul>
48
+
49
+ <ul class="navbar-nav">
50
+ {% if session.user_id %}
51
+ <li class="nav-item">
52
+ <a class="nav-link" href="/profile">
53
+ <i class="bi bi-person-circle"></i> {{ session.username }}
54
+ </a>
55
+ </li>
56
+ <li class="nav-item">
57
+ <a class="nav-link" href="/logout">
58
+ <i class="bi bi-box-arrow-right"></i> Logout
59
+ </a>
60
+ </li>
61
+ {% else %}
62
+ <li class="nav-item">
63
+ <a class="nav-link" href="/login">
64
+ <i class="bi bi-box-arrow-in-right"></i> Login
65
+ </a>
66
+ </li>
67
+ <li class="nav-item">
68
+ <a class="nav-link" href="/register">
69
+ <i class="bi bi-person-plus"></i> Register
70
+ </a>
71
+ </li>
72
+ {% endif %}
73
+ </ul>
74
+ </div>
75
+ </div>
76
+ </nav>
77
+
78
+ <div class="container mt-4">
79
+ {% with messages = get_flashed_messages(with_categories=true) %}
80
+ {% if messages %}
81
+ {% for category, message in messages %}
82
+ <div class="alert alert-{{ 'danger' if category == 'error' else 'success' }} alert-dismissible fade show" role="alert">
83
+ {{ message }}
84
+ <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
85
+ </div>
86
+ {% endfor %}
87
+ {% endif %}
88
+ {% endwith %}
89
+
90
+ {% block content %}{% endblock %}
91
+ </div>
92
+
93
+ <footer class="bg-light text-center text-lg-start mt-5">
94
+ <div class="container p-4">
95
+ <div class="text-center p-3">
96
+ © 2025 Multiple Disease Prediction System
97
+ </div>
98
+ </div>
99
+ </footer>
100
+
101
+ <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
102
+ <script src="{{ url_for('static', filename='js/script.js') }}"></script>
103
+ {% block scripts %}{% endblock %}
104
+ </body>
105
+ </html>
templates/doctor/appointments.html ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Doctor Appointments - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row">
7
+ <div class="col-12">
8
+ <h2><i class="bi bi-calendar-check"></i> Doctor Appointments</h2>
9
+ <p class="lead">Manage patient appointments</p>
10
+ </div>
11
+ </div>
12
+
13
+ <div class="row mt-4">
14
+ <div class="col-12">
15
+ <ul class="nav nav-tabs" id="appointmentTabs" role="tablist">
16
+ <li class="nav-item" role="presentation">
17
+ <button class="nav-link active" id="pending-tab" data-bs-toggle="tab" data-bs-target="#pending" type="button" role="tab">Pending Appointments</button>
18
+ </li>
19
+ <li class="nav-item" role="presentation">
20
+ <button class="nav-link" id="confirmed-tab" data-bs-toggle="tab" data-bs-target="#confirmed" type="button" role="tab">Confirmed Appointments</button>
21
+ </li>
22
+ <li class="nav-item" role="presentation">
23
+ <button class="nav-link" id="schedule-tab" data-bs-toggle="tab" data-bs-target="#schedule" type="button" role="tab">My Schedule</button>
24
+ </li>
25
+ </ul>
26
+
27
+ <div class="tab-content" id="appointmentTabsContent">
28
+ <div class="tab-pane fade show active" id="pending" role="tabpanel">
29
+ <div class="card mt-3">
30
+ <div class="card-header">
31
+ <h5 class="card-title mb-0">Pending Appointments</h5>
32
+ </div>
33
+ <div class="card-body">
34
+ {% if pending_appointments %}
35
+ <div class="table-responsive">
36
+ <table class="table table-striped">
37
+ <thead>
38
+ <tr>
39
+ <th>Patient</th>
40
+ <th>Disease/Condition</th>
41
+ <th>Details</th>
42
+ <th>Date & Time</th>
43
+ <th>Notes</th>
44
+ <th>Actions</th>
45
+ </tr>
46
+ </thead>
47
+ <tbody>
48
+ {% for appointment in pending_appointments %}
49
+ <tr>
50
+ <td>
51
+ {{ appointment.patient_name }}<br>
52
+ <small class="text-muted">{{ appointment.patient_email }}</small>
53
+ </td>
54
+ <td>{{ appointment.disease_type }}</td>
55
+ <td>
56
+ {% if appointment.details_selected %}
57
+ <ul class="mb-0">
58
+ {% for detail in appointment.details_selected[:3] %}
59
+ <li>{{ detail }}</li>
60
+ {% endfor %}
61
+ {% if appointment.details_selected|length > 3 %}
62
+ <li>+{{ appointment.details_selected|length - 3 }} more</li>
63
+ {% endif %}
64
+ </ul>
65
+ {% endif %}
66
+ </td>
67
+ <td>{{ appointment.date.strftime('%Y-%m-%d') }} at {{ appointment.time }}</td>
68
+ <td>{{ appointment.notes }}</td>
69
+ <td>
70
+ <form method="POST" action="/doctor/appointments/{{ appointment._id }}/confirm" class="d-inline">
71
+ <button type="submit" class="btn btn-sm btn-success">
72
+ <i class="bi bi-check-circle"></i> Confirm
73
+ </button>
74
+ </form>
75
+ <form method="POST" action="/doctor/appointments/{{ appointment._id }}/reject" class="d-inline">
76
+ <button type="submit" class="btn btn-sm btn-danger">
77
+ <i class="bi bi-x-circle"></i> Reject
78
+ </button>
79
+ </form>
80
+ </td>
81
+ </tr>
82
+ {% endfor %}
83
+ </tbody>
84
+ </table>
85
+ </div>
86
+ {% else %}
87
+ <p class="text-muted">No pending appointments found.</p>
88
+ {% endif %}
89
+ </div>
90
+ </div>
91
+ </div>
92
+
93
+ <div class="tab-pane fade" id="confirmed" role="tabpanel">
94
+ <div class="card mt-3">
95
+ <div class="card-header">
96
+ <h5 class="card-title mb-0">Confirmed Appointments</h5>
97
+ </div>
98
+ <div class="card-body">
99
+ {% if confirmed_appointments %}
100
+ <div class="table-responsive">
101
+ <table class="table table-striped">
102
+ <thead>
103
+ <tr>
104
+ <th>Patient</th>
105
+ <th>Disease/Condition</th>
106
+ <th>Date & Time</th>
107
+ <th>Notes</th>
108
+ <th>Actions</th>
109
+ </tr>
110
+ </thead>
111
+ <tbody>
112
+ {% for appointment in confirmed_appointments %}
113
+ <tr>
114
+ <td>
115
+ {{ appointment.patient_name }}<br>
116
+ <small class="text-muted">{{ appointment.patient_email }}</small>
117
+ </td>
118
+ <td>{{ appointment.disease_type }}</td>
119
+ <td>{{ appointment.date.strftime('%Y-%m-%d') }} at {{ appointment.time }}</td>
120
+ <td>{{ appointment.notes }}</td>
121
+ <td>
122
+ <a href="/doctor/chat/{{ appointment._id }}" class="btn btn-sm btn-primary">
123
+ <i class="bi bi-chat"></i> Chat
124
+ </a>
125
+ </td>
126
+ </tr>
127
+ {% endfor %}
128
+ </tbody>
129
+ </table>
130
+ </div>
131
+ {% else %}
132
+ <p class="text-muted">No confirmed appointments found.</p>
133
+ {% endif %}
134
+ </div>
135
+ </div>
136
+ </div>
137
+
138
+ <div class="tab-pane fade" id="schedule" role="tabpanel">
139
+ <div class="card mt-3">
140
+ <div class="card-header">
141
+ <h5 class="card-title mb-0">My Schedule</h5>
142
+ </div>
143
+ <div class="card-body">
144
+ {% if confirmed_appointments %}
145
+ <div class="list-group">
146
+ {% for appointment in confirmed_appointments[:10] %}
147
+ <div class="list-group-item d-flex justify-content-between align-items-start">
148
+ <div>
149
+ <strong>{{ appointment.patient_name }}</strong><br>
150
+ <small class="text-muted">{{ appointment.disease_type }}</small>
151
+ </div>
152
+ <div class="text-end">
153
+ <div>{{ appointment.date.strftime('%Y-%m-%d') }}</div>
154
+ <div class="text-muted">{{ appointment.time }}</div>
155
+ <div class="mt-2">
156
+ <a href="/doctor/chat/{{ appointment._id }}" class="btn btn-sm btn-outline-primary">Chat</a>
157
+ </div>
158
+ </div>
159
+ </div>
160
+ {% endfor %}
161
+ </div>
162
+ {% else %}
163
+ <p class="text-muted">No upcoming confirmed appointments.</p>
164
+ {% endif %}
165
+ </div>
166
+ </div>
167
+ </div>
168
+ </div>
169
+ </div>
170
+ </div>
171
+
172
+ {% endblock %}
173
+
174
+ {% block scripts %}
175
+ <script>
176
+ document.addEventListener('DOMContentLoaded', function() {
177
+ // Simple calendar implementation
178
+ const calendarEl = document.getElementById('calendar');
179
+ if (calendarEl) {
180
+ const today = new Date();
181
+ const month = today.toLocaleString('default', { month: 'long' });
182
+ const year = today.getFullYear();
183
+
184
+ let calendarHTML = `<h5>${month} ${year}</h5>`;
185
+ calendarHTML += '<div class="table-responsive">';
186
+ calendarHTML += '<table class="table table-bordered">';
187
+ calendarHTML += '<thead><tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr></thead>';
188
+ calendarHTML += '<tbody>';
189
+
190
+ // Generate calendar (simplified)
191
+ const daysInMonth = new Date(year, today.getMonth() + 1, 0).getDate();
192
+ const firstDay = new Date(year, today.getMonth(), 1).getDay();
193
+
194
+ let day = 1;
195
+ for (let i = 0; i < 6; i++) {
196
+ calendarHTML += '<tr>';
197
+ for (let j = 0; j < 7; j++) {
198
+ if (i === 0 && j < firstDay) {
199
+ calendarHTML += '<td></td>';
200
+ } else if (day > daysInMonth) {
201
+ calendarHTML += '<td></td>';
202
+ } else {
203
+ const isToday = (day === today.getDate());
204
+ calendarHTML += `<td class="${isToday ? 'table-primary' : ''}">${day}</td>`;
205
+ day++;
206
+ }
207
+ }
208
+ calendarHTML += '</tr>';
209
+ if (day > daysInMonth) break;
210
+ }
211
+
212
+ calendarHTML += '</tbody></table></div>';
213
+ calendarEl.innerHTML = calendarHTML;
214
+ }
215
+ });
216
+ </script>
217
+ {% endblock %}
templates/doctor/chat.html ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Chat with {{ patient.name }} - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row">
7
+ <div class="col-12">
8
+ <h2><i class="bi bi-chat"></i> Chat with {{ patient.name }}</h2>
9
+ <p class="lead">Appointment: {{ appointment.disease_type }} on {{ appointment.date.strftime('%Y-%m-%d') }} at {{ appointment.time }}</p>
10
+ </div>
11
+ </div>
12
+
13
+ <div class="row mt-4">
14
+ <div class="col-md-8">
15
+ <div class="card">
16
+ <div class="card-header">
17
+ <h5 class="card-title mb-0">Conversation</h5>
18
+ </div>
19
+ <div class="card-body chat-container">
20
+ <div class="chat-messages" id="chatMessages">
21
+ {% if messages %}
22
+ {% for message in messages %}
23
+ <div class="message {% if message.sender_id == session.user_id %}sent{% else %}received{% endif %}">
24
+ <div class="message-content">
25
+ {{ message.message_text }}
26
+ </div>
27
+ <div class="message-time">
28
+ {{ message.timestamp.strftime('%Y-%m-%d %H:%M') }}
29
+ </div>
30
+ </div>
31
+ {% endfor %}
32
+ {% else %}
33
+ <p class="text-muted">No messages yet. Start the conversation!</p>
34
+ {% endif %}
35
+ </div>
36
+ </div>
37
+ <div class="card-footer">
38
+ <form method="POST" action="/send_message">
39
+ <input type="hidden" name="appointment_id" value="{{ appointment._id }}">
40
+ <div class="input-group">
41
+ <input type="text" class="form-control" name="message" placeholder="Type your message..." required>
42
+ <button class="btn btn-primary" type="submit">
43
+ <i class="bi bi-send"></i> Send
44
+ </button>
45
+ </div>
46
+ </form>
47
+ </div>
48
+ </div>
49
+ </div>
50
+
51
+ <div class="col-md-4">
52
+ <div class="card">
53
+ <div class="card-header">
54
+ <h5 class="card-title mb-0">Appointment Details</h5>
55
+ </div>
56
+ <div class="card-body">
57
+ <ul class="list-group list-group-flush">
58
+ <li class="list-group-item">
59
+ <strong>Patient:</strong> {{ patient.name }}
60
+ </li>
61
+ <li class="list-group-item">
62
+ <strong>Disease/Condition:</strong> {{ appointment.disease_type }}
63
+ </li>
64
+ <li class="list-group-item">
65
+ <strong>Date & Time:</strong> {{ appointment.date.strftime('%Y-%m-%d') }} at {{ appointment.time }}
66
+ </li>
67
+ <li class="list-group-item">
68
+ <strong>Details:</strong>
69
+ {% if appointment.details_selected %}
70
+ <ul>
71
+ {% for detail in appointment.details_selected %}
72
+ <li>{{ detail }}</li>
73
+ {% endfor %}
74
+ </ul>
75
+ {% else %}
76
+ <span class="text-muted">No details provided</span>
77
+ {% endif %}
78
+ </li>
79
+ <li class="list-group-item">
80
+ <strong>Notes:</strong>
81
+ {% if appointment.notes %}
82
+ {{ appointment.notes }}
83
+ {% else %}
84
+ <span class="text-muted">No notes</span>
85
+ {% endif %}
86
+ </li>
87
+ </ul>
88
+ </div>
89
+ </div>
90
+
91
+ <div class="card mt-4">
92
+ <div class="card-header">
93
+ <h5 class="card-title mb-0">Actions</h5>
94
+ </div>
95
+ <div class="card-body">
96
+ <a href="/doctor/appointments" class="btn btn-primary w-100 mb-2">
97
+ <i class="bi bi-arrow-left"></i> Back to Appointments
98
+ </a>
99
+ <button class="btn btn-outline-secondary w-100">
100
+ <i class="bi bi-printer"></i> Print Prescription
101
+ </button>
102
+ </div>
103
+ </div>
104
+ </div>
105
+ </div>
106
+
107
+ {% endblock %}
108
+
109
+ {% block scripts %}
110
+ <script>
111
+ // Auto-scroll to bottom of chat
112
+ document.addEventListener('DOMContentLoaded', function() {
113
+ const chatMessages = document.getElementById('chatMessages');
114
+ if (chatMessages) {
115
+ chatMessages.scrollTop = chatMessages.scrollHeight;
116
+ }
117
+ });
118
+ </script>
119
+ {% endblock %}
templates/doctor/dashboard.html ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Doctor Dashboard - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row">
7
+ <div class="col-12">
8
+ <h2><i class="bi bi-speedometer2"></i> Doctor Dashboard</h2>
9
+ <p class="lead">Overview of appointments and trends</p>
10
+ </div>
11
+ </div>
12
+
13
+ <div class="row mt-3">
14
+ <div class="col-lg-4 col-md-6">
15
+ <div class="card dashboard-card">
16
+ <div class="card-body">
17
+ <h5>Appointment Status Overview</h5>
18
+ <div id="statusChart" class="chart-container"></div>
19
+ </div>
20
+ </div>
21
+ </div>
22
+
23
+ <div class="col-lg-8 col-md-6">
24
+ <div class="card dashboard-card">
25
+ <div class="card-body">
26
+ <h5>Disease-Specific Appointment Trends</h5>
27
+ <div id="trendChart" class="chart-container"></div>
28
+ </div>
29
+ </div>
30
+ </div>
31
+ </div>
32
+
33
+ <div class="row mt-3">
34
+ <div class="col-lg-8 col-md-12">
35
+ <div class="card dashboard-card">
36
+ <div class="card-body">
37
+ <h5>Upcoming Schedule</h5>
38
+ <div id="scheduleChart" class="chart-container"></div>
39
+ </div>
40
+ </div>
41
+ </div>
42
+
43
+ <div class="col-lg-4 col-md-12">
44
+ <div class="card dashboard-card">
45
+ <div class="card-body">
46
+ <h5>Patient Distribution</h5>
47
+ <div id="patientChart" class="chart-container"></div>
48
+ </div>
49
+ </div>
50
+ </div>
51
+ </div>
52
+
53
+ <div class="row mt-3">
54
+ <div class="col-12">
55
+ <div class="card dashboard-card">
56
+ <div class="card-body">
57
+ <h5>Details / Symptoms Frequency</h5>
58
+ <div id="detailsChart" class="chart-container"></div>
59
+ </div>
60
+ </div>
61
+ </div>
62
+ </div>
63
+
64
+ {% endblock %}
65
+
66
+ {% block scripts %}
67
+ <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
68
+ <script>
69
+ async function fetchData() {
70
+ const res = await fetch('/doctor/dashboard/data');
71
+ return await res.json();
72
+ }
73
+
74
+ function drawCharts(data) {
75
+ // Status Pie / Donut with new color palette
76
+ // ensure keys exist
77
+ const s = data.status || {};
78
+ const pending = s.pending || 0;
79
+ const confirmed = s.confirmed || s.confirmed || 0;
80
+ const rejected = s.rejected || 0;
81
+ const cancelled = s.cancelled || 0;
82
+
83
+ const statusData = [{
84
+ values: [pending, confirmed, rejected, cancelled],
85
+ labels: ['Pending','Confirmed','Rejected','Cancelled'],
86
+ type: 'pie',
87
+ hole: .4,
88
+ marker: {
89
+ colors: ['#ffb347','#32cd32','#dc143c','#6c757d'] // Warning, Success, Danger, Gray
90
+ }
91
+ }];
92
+ Plotly.newPlot('statusChart', statusData, {responsive:true});
93
+
94
+ // Trend area chart with new colors
95
+ const trendDates = (data.trend && data.trend.dates) || [];
96
+ const trendCounts = (data.trend && data.trend.counts) || [];
97
+ const trendData = [{
98
+ x: trendDates,
99
+ y: trendCounts,
100
+ fill: 'tozeroy',
101
+ type: 'scatter',
102
+ mode: 'lines+markers',
103
+ marker: {color: '#006d5b'}, // Primary color
104
+ line: {color: '#006d5b'} // Primary color
105
+ }];
106
+ Plotly.newPlot('trendChart', trendData, {responsive:true});
107
+
108
+ // Upcoming schedule as timeline (bar) with new colors
109
+ const scheduleTimes = (data.schedule && data.schedule.times) || [];
110
+ const scheduleLabels = (data.schedule && data.schedule.labels) || [];
111
+ const scheduleData = [{
112
+ x: scheduleTimes,
113
+ y: scheduleLabels,
114
+ type: 'bar',
115
+ orientation: 'h',
116
+ marker: {color: '#aaf0d1'} // Chat Doctor Bubble color
117
+ }];
118
+ Plotly.newPlot('scheduleChart', scheduleData, {responsive:true, margin: {l: 150}});
119
+
120
+ // Patient distribution bar with new colors
121
+ const patientMonths = (data.patient && data.patient.months) || [];
122
+ const patientCounts = (data.patient && data.patient.counts) || [];
123
+ const patientData = [{
124
+ x: patientMonths,
125
+ y: patientCounts,
126
+ type: 'bar',
127
+ marker: {color: '#006d5b'} // Primary color
128
+ }];
129
+ Plotly.newPlot('patientChart', patientData, {responsive:true});
130
+
131
+ // Details frequency horizontal bar with new colors
132
+ const detailsLabels = (data.details && data.details.labels) || [];
133
+ const detailsCounts = (data.details && data.details.counts) || [];
134
+ // reverse for horizontal display
135
+ const detailsData = [{
136
+ x: [...detailsCounts].reverse(),
137
+ y: [...detailsLabels].reverse(),
138
+ type: 'bar',
139
+ orientation: 'h',
140
+ marker: {color: '#32cd32'} // Success color
141
+ }];
142
+ Plotly.newPlot('detailsChart', detailsData, {responsive:true});
143
+ }
144
+
145
+ fetchData().then(drawCharts).catch(err => console.error(err));
146
+ </script>
147
+ {% endblock %}
templates/index.html ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block content %}
4
+ <div class="jumbotron">
5
+ <div class="container">
6
+ <h1 class="display-4"><i class="bi bi-heart-pulse"></i> Multiple Disease Prediction System</h1>
7
+ <p class="lead">Predict heart disease, diabetes, and Parkinson's using machine learning algorithms.</p>
8
+ {% if not session.user_id %}
9
+ <hr class="my-4">
10
+ <p>Sign up or log in to access our prediction services and track your health history.</p>
11
+ <a class="btn btn-light btn-lg me-2" href="/register" role="button">Register</a>
12
+ <a class="btn btn-outline-light btn-lg" href="/login" role="button">Login</a>
13
+ {% endif %}
14
+ </div>
15
+ </div>
16
+
17
+ <div class="row">
18
+ <div class="col-md-4 mb-4">
19
+ <div class="card dashboard-card h-100">
20
+ <div class="card-body">
21
+ <h5 class="card-title"><i class="bi bi-heart text-danger"></i> Heart Disease Prediction</h5>
22
+ <p class="card-text">Our advanced machine learning model analyzes various health indicators to predict the likelihood of heart disease.</p>
23
+ {% if session.user_id %}
24
+ <a href="/user/heart-disease" class="btn btn-primary">Check Now</a>
25
+ {% else %}
26
+ <a href="/login" class="btn btn-primary">Login to Check</a>
27
+ {% endif %}
28
+ </div>
29
+ </div>
30
+ </div>
31
+
32
+ <div class="col-md-4 mb-4">
33
+ <div class="card dashboard-card h-100">
34
+ <div class="card-body">
35
+ <h5 class="card-title"><i class="bi bi-droplet text-warning"></i> Diabetes Prediction</h5>
36
+ <p class="card-text">Early detection of diabetes is crucial. Our model evaluates key factors to assess your risk of developing diabetes.</p>
37
+ {% if session.user_id %}
38
+ <a href="/user/diabetes" class="btn btn-primary">Check Now</a>
39
+ {% else %}
40
+ <a href="/login" class="btn btn-primary">Login to Check</a>
41
+ {% endif %}
42
+ </div>
43
+ </div>
44
+ </div>
45
+
46
+ <div class="col-md-4 mb-4">
47
+ <div class="card dashboard-card h-100">
48
+ <div class="card-body">
49
+ <h5 class="card-title"><i class="bi bi-person-circle text-info"></i> Parkinson's Prediction</h5>
50
+ <p class="card-text">Detect early signs of Parkinson's disease with our specialized voice analysis model.</p>
51
+ {% if session.user_id %}
52
+ <a href="/user/parkinsons" class="btn btn-primary">Check Now</a>
53
+ {% else %}
54
+ <a href="/login" class="btn btn-primary">Login to Check</a>
55
+ {% endif %}
56
+ </div>
57
+ </div>
58
+ </div>
59
+ </div>
60
+
61
+ <div class="row mt-4">
62
+ <div class="col-12">
63
+ <div class="card">
64
+ <div class="card-body">
65
+ <h5 class="card-title"><i class="bi bi-info-circle"></i> How It Works</h5>
66
+ <ol>
67
+ <li>Create an account or log in to access our prediction services</li>
68
+ <li>Select the disease prediction model you want to use</li>
69
+ <li>Enter the required health information</li>
70
+ <li>Get instant prediction results with health recommendations</li>
71
+ <li>Track your prediction history and health trends over time</li>
72
+ </ol>
73
+ </div>
74
+ </div>
75
+ </div>
76
+ </div>
77
+
78
+ {% endblock %}
templates/user/appointments.html ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Appointments - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row">
7
+ <div class="col-12">
8
+ <h2><i class="bi bi-calendar-check"></i> Appointments</h2>
9
+ <p class="lead">Book and manage your appointments with healthcare professionals</p>
10
+ </div>
11
+ </div>
12
+
13
+ <div class="row mt-4">
14
+ <div class="col-md-8">
15
+ <div class="card">
16
+ <div class="card-header">
17
+ <h5 class="card-title mb-0">Book New Appointment</h5>
18
+ </div>
19
+ <div class="card-body">
20
+ <form method="POST" action="/user/appointments">
21
+ <div class="mb-3">
22
+ <label for="disease_type" class="form-label">Disease/Condition to be Checked</label>
23
+ <select class="form-select" id="disease_type" name="disease_type" required onchange="updateDoctorOptions()">
24
+ <option value="">Select disease/condition</option>
25
+ <option value="Heart Disease">Heart Disease</option>
26
+ <option value="Diabetes">Diabetes</option>
27
+ <option value="Parkinson's Disease">Parkinson's Disease</option>
28
+ <option value="General Checkup">General Checkup</option>
29
+ <option value="Other">Other</option>
30
+ </select>
31
+ {% if prediction_history %}
32
+ <div class="form-text">Based on your prediction history:</div>
33
+ <select class="form-select mt-1" id="prediction_history" onchange="document.getElementById('disease_type').value = this.value; updateDoctorOptions();">
34
+ <option value="">Select from your history...</option>
35
+ {% for prediction in prediction_history %}
36
+ <option value="{{ prediction.disease_type }}">{{ prediction.disease_type }} - {{ prediction.date.strftime('%Y-%m-%d') }}</option>
37
+ {% endfor %}
38
+ </select>
39
+ {% endif %}
40
+ </div>
41
+
42
+ <div class="mb-3">
43
+ <label class="form-label">Details (Symptoms, Purpose of Visit)</label>
44
+ <div class="form-check">
45
+ <input class="form-check-input" type="checkbox" name="details" value="Chest Pain" id="chest_pain">
46
+ <label class="form-check-label" for="chest_pain">Chest Pain</label>
47
+ </div>
48
+ <div class="form-check">
49
+ <input class="form-check-input" type="checkbox" name="details" value="Shortness of Breath" id="shortness_breath">
50
+ <label class="form-check-label" for="shortness_breath">Shortness of Breath</label>
51
+ </div>
52
+ <div class="form-check">
53
+ <input class="form-check-input" type="checkbox" name="details" value="High Blood Pressure" id="high_bp">
54
+ <label class="form-check-label" for="high_bp">High Blood Pressure</label>
55
+ </div>
56
+ <div class="form-check">
57
+ <input class="form-check-input" type="checkbox" name="details" value="High Cholesterol" id="high_cholesterol">
58
+ <label class="form-check-label" for="high_cholesterol">High Cholesterol</label>
59
+ </div>
60
+ <div class="form-check">
61
+ <input class="form-check-input" type="checkbox" name="details" value="Irregular Heartbeat" id="irregular_heartbeat">
62
+ <label class="form-check-label" for="irregular_heartbeat">Irregular Heartbeat</label>
63
+ </div>
64
+ <div class="form-check">
65
+ <input class="form-check-input" type="checkbox" name="details" value="Fatigue" id="fatigue">
66
+ <label class="form-check-label" for="fatigue">Fatigue</label>
67
+ </div>
68
+ <div class="form-check">
69
+ <input class="form-check-input" type="checkbox" name="details" value="Dizziness" id="dizziness">
70
+ <label class="form-check-label" for="dizziness">Dizziness</label>
71
+ </div>
72
+ <div class="form-check">
73
+ <input class="form-check-input" type="checkbox" name="details" value="Nausea" id="nausea">
74
+ <label class="form-check-label" for="nausea">Nausea</label>
75
+ </div>
76
+ <div class="form-check">
77
+ <input class="form-check-input" type="checkbox" name="details" value="Sweating" id="sweating">
78
+ <label class="form-check-label" for="sweating">Sweating</label>
79
+ </div>
80
+ <div class="form-check">
81
+ <input class="form-check-input" type="checkbox" name="details" value="High Blood Sugar" id="high_blood_sugar">
82
+ <label class="form-check-label" for="high_blood_sugar">High Blood Sugar</label>
83
+ </div>
84
+ <div class="form-check">
85
+ <input class="form-check-input" type="checkbox" name="details" value="Frequent Urination" id="frequent_urination">
86
+ <label class="form-check-label" for="frequent_urination">Frequent Urination</label>
87
+ </div>
88
+ <div class="form-check">
89
+ <input class="form-check-input" type="checkbox" name="details" value="Blurred Vision" id="blurred_vision">
90
+ <label class="form-check-label" for="blurred_vision">Blurred Vision</label>
91
+ </div>
92
+ <div class="form-check">
93
+ <input class="form-check-input" type="checkbox" name="details" value="Tremors" id="tremors">
94
+ <label class="form-check-label" for="tremors">Tremors</label>
95
+ </div>
96
+ <div class="form-check">
97
+ <input class="form-check-input" type="checkbox" name="details" value="Slow Movement" id="slow_movement">
98
+ <label class="form-check-label" for="slow_movement">Slow Movement</label>
99
+ </div>
100
+ <div class="form-check">
101
+ <input class="form-check-input" type="checkbox" name="details" value="Balance Problems" id="balance_problems">
102
+ <label class="form-check-label" for="balance_problems">Balance Problems</label>
103
+ </div>
104
+ <div class="form-check">
105
+ <input class="form-check-input" type="checkbox" name="details" value="Speech Difficulties" id="speech_difficulties">
106
+ <label class="form-check-label" for="speech_difficulties">Speech Difficulties</label>
107
+ </div>
108
+ <div class="form-check">
109
+ <input class="form-check-input" type="checkbox" name="details" value="General Checkup" id="general_checkup">
110
+ <label class="form-check-label" for="general_checkup">General Checkup</label>
111
+ </div>
112
+ <div class="form-check">
113
+ <input class="form-check-input" type="checkbox" name="details" value="Follow-up Visit" id="followup_visit">
114
+ <label class="form-check-label" for="followup_visit">Follow-up Visit</label>
115
+ </div>
116
+ </div>
117
+
118
+ <!-- Doctor selection removed: appointments are unassigned on booking
119
+ and will be received by doctors matching the disease specialization.
120
+ The doctor will confirm/reject based on their availability. -->
121
+
122
+ <div class="row">
123
+ <div class="col-md-6 mb-3">
124
+ <label for="date" class="form-label">Appointment Date</label>
125
+ <input type="date" class="form-control" id="date" name="date" required>
126
+ </div>
127
+ <div class="col-md-6 mb-3">
128
+ <label for="time" class="form-label">Appointment Time</label>
129
+ <input type="time" class="form-control" id="time" name="time" required>
130
+ </div>
131
+ </div>
132
+
133
+ <div class="mb-3">
134
+ <label for="notes" class="form-label">Additional Notes/Symptoms</label>
135
+ <textarea class="form-control" id="notes" name="notes" rows="3" placeholder="Describe your symptoms or any additional information..."></textarea>
136
+ </div>
137
+
138
+ <button type="submit" class="btn btn-primary">
139
+ <i class="bi bi-calendar-plus"></i> Book Appointment
140
+ </button>
141
+ </form>
142
+ </div>
143
+ </div>
144
+
145
+ <div class="card mt-4">
146
+ <div class="card-header">
147
+ <h5 class="card-title mb-0">My Appointments</h5>
148
+ </div>
149
+ <div class="card-body">
150
+ {% if upcoming_appointments %}
151
+ <div class="table-responsive">
152
+ <table class="table table-striped">
153
+ <thead>
154
+ <tr>
155
+ <th>Doctor</th>
156
+ <th>Disease/Condition</th>
157
+ <th>Date & Time</th>
158
+ <th>Status</th>
159
+ <th>Actions</th>
160
+ </tr>
161
+ </thead>
162
+ <tbody>
163
+ {% for appointment in upcoming_appointments %}
164
+ <tr>
165
+ <td>{% if appointment.doctor %}{{ appointment.doctor }}{% else %}<em>Unassigned</em>{% endif %}</td>
166
+ <td>{{ appointment.disease_type }}</td>
167
+ <td>{{ appointment.date.strftime('%Y-%m-%d') }} at {{ appointment.time }}</td>
168
+ <td>
169
+ {% if appointment.status == 'pending' %}
170
+ <span class="badge bg-warning">Pending</span>
171
+ {% elif appointment.status == 'confirmed' %}
172
+ <span class="badge bg-success">Confirmed</span>
173
+ {% elif appointment.status == 'rejected' %}
174
+ <span class="badge bg-danger">Rejected</span>
175
+ {% elif appointment.status == 'cancelled' %}
176
+ <span class="badge bg-secondary">Cancelled</span>
177
+ {% endif %}
178
+ </td>
179
+ <td>
180
+ {% if appointment.status == 'pending' %}
181
+ <a href="/user/cancel-appointment/{{ appointment._id }}" class="btn btn-sm btn-outline-danger delete-btn">Cancel</a>
182
+ {% elif appointment.status == 'confirmed' %}
183
+ <a href="/user/chat/{{ appointment._id }}" class="btn btn-sm btn-outline-primary">Chat</a>
184
+ {% endif %}
185
+ </td>
186
+ </tr>
187
+ {% endfor %}
188
+ </tbody>
189
+ </table>
190
+ </div>
191
+ {% else %}
192
+ <p class="text-muted">No upcoming appointments found.</p>
193
+ {% endif %}
194
+ </div>
195
+ </div>
196
+ </div>
197
+
198
+ <div class="col-md-4">
199
+ <div class="card">
200
+ <div class="card-header">
201
+ <h5 class="card-title mb-0">Appointment Information</h5>
202
+ </div>
203
+ <div class="card-body">
204
+ <p>Book appointments by selecting the disease/condition and preferred date/time. Doctors who handle that disease will receive the request anonymously and will confirm or reject based on their availability.</p>
205
+ <ul>
206
+ <li>Select a disease/condition</li>
207
+ <li>Choose relevant symptoms</li>
208
+ <li>Choose a convenient date and time</li>
209
+ <li>Add any relevant symptoms or notes</li>
210
+ <li>Wait for confirmation from a doctor who handles that disease</li>
211
+ </ul>
212
+ <div class="alert alert-info">
213
+ <i class="bi bi-info-circle"></i> Doctors will not be shown during booking. Appointments will be assigned when a doctor confirms the request.
214
+ </div>
215
+ </div>
216
+ </div>
217
+
218
+ <div class="card mt-4">
219
+ <div class="card-header">
220
+ <h5 class="card-title mb-0">Doctor Specializations</h5>
221
+ </div>
222
+ <div class="card-body">
223
+ <div class="d-flex justify-content-between">
224
+ <span>Cardiology</span>
225
+ <span class="text-success"><i class="bi bi-check-circle"></i> Doctors available</span>
226
+ </div>
227
+ <div class="d-flex justify-content-between mt-2">
228
+ <span>Endocrinology</span>
229
+ <span class="text-success"><i class="bi bi-check-circle"></i> Doctors available</span>
230
+ </div>
231
+ <div class="d-flex justify-content-between mt-2">
232
+ <span>Neurology</span>
233
+ <span class="text-warning"><i class="bi bi-exclamation-circle"></i> Limited availability</span>
234
+ </div>
235
+ <div class="d-flex justify-content-between mt-2">
236
+ <span>General Practice</span>
237
+ <span class="text-success"><i class="bi bi-check-circle"></i> Doctors available</span>
238
+ </div>
239
+ </div>
240
+ </div>
241
+ </div>
242
+ </div>
243
+
244
+ {% endblock %}
245
+
246
+ {% block scripts %}
247
+ <script>
248
+ // Set minimum date to tomorrow
249
+ document.addEventListener('DOMContentLoaded', function() {
250
+ const today = new Date();
251
+ const tomorrow = new Date(today);
252
+ tomorrow.setDate(tomorrow.getDate() + 1);
253
+
254
+ // Format as YYYY-MM-DD
255
+ const minDate = tomorrow.toISOString().split('T')[0];
256
+
257
+ // Set the min attribute on the date input
258
+ const dateInput = document.getElementById('date');
259
+ if (dateInput) {
260
+ dateInput.setAttribute('min', minDate);
261
+ }
262
+ });
263
+
264
+ function updateDoctorOptions() {
265
+ const diseaseType = document.getElementById('disease_type').value;
266
+ const doctorOptions = document.querySelectorAll('#doctor option');
267
+
268
+ // Reset all options
269
+ doctorOptions.forEach(option => {
270
+ option.style.display = 'block';
271
+ });
272
+
273
+ // Filter based on disease type
274
+ if (diseaseType === 'Heart Disease') {
275
+ doctorOptions.forEach(option => {
276
+ if (option.classList.contains('heart-disease') || option.classList.contains('general')) {
277
+ option.style.display = 'block';
278
+ } else if (!option.classList.contains('general') && option.value !== '') {
279
+ option.style.display = 'none';
280
+ }
281
+ });
282
+ } else if (diseaseType === 'Diabetes') {
283
+ doctorOptions.forEach(option => {
284
+ if (option.classList.contains('diabetes') || option.classList.contains('general')) {
285
+ option.style.display = 'block';
286
+ } else if (!option.classList.contains('general') && option.value !== '') {
287
+ option.style.display = 'none';
288
+ }
289
+ });
290
+ } else if (diseaseType === "Parkinson's Disease") {
291
+ doctorOptions.forEach(option => {
292
+ if (option.classList.contains('parkinsons') || option.classList.contains('general')) {
293
+ option.style.display = 'block';
294
+ } else if (!option.classList.contains('general') && option.value !== '') {
295
+ option.style.display = 'none';
296
+ }
297
+ });
298
+ }
299
+
300
+ // Reset doctor selection
301
+ document.getElementById('doctor').value = '';
302
+ }
303
+ </script>
304
+ {% endblock %}
templates/user/chat.html ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Chat with {{ doctor.name }} - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row">
7
+ <div class="col-12">
8
+ <h2><i class="bi bi-chat"></i> Chat with {{ doctor.name }}</h2>
9
+ <p class="lead">Appointment: {{ appointment.disease_type }} on {{ appointment.date.strftime('%Y-%m-%d') }} at {{ appointment.time }}</p>
10
+ </div>
11
+ </div>
12
+
13
+ <div class="row mt-4">
14
+ <div class="col-md-8">
15
+ <div class="card">
16
+ <div class="card-header">
17
+ <h5 class="card-title mb-0">Conversation</h5>
18
+ </div>
19
+ <div class="card-body chat-container">
20
+ <div class="chat-messages" id="chatMessages">
21
+ {% if messages %}
22
+ {% for message in messages %}
23
+ <div class="message {% if message.sender_id == session.user_id %}sent{% else %}received{% endif %}">
24
+ <div class="message-content">
25
+ {{ message.message_text }}
26
+ </div>
27
+ <div class="message-time">
28
+ {{ message.timestamp.strftime('%Y-%m-%d %H:%M') }}
29
+ </div>
30
+ </div>
31
+ {% endfor %}
32
+ {% else %}
33
+ <p class="text-muted">No messages yet. Start the conversation!</p>
34
+ {% endif %}
35
+ </div>
36
+ </div>
37
+ <div class="card-footer">
38
+ <form method="POST" action="/send_message">
39
+ <input type="hidden" name="appointment_id" value="{{ appointment._id }}">
40
+ <div class="input-group">
41
+ <input type="text" class="form-control" name="message" placeholder="Type your message..." required>
42
+ <button class="btn btn-primary" type="submit">
43
+ <i class="bi bi-send"></i> Send
44
+ </button>
45
+ </div>
46
+ </form>
47
+ </div>
48
+ </div>
49
+ </div>
50
+
51
+ <div class="col-md-4">
52
+ <div class="card">
53
+ <div class="card-header">
54
+ <h5 class="card-title mb-0">Appointment Details</h5>
55
+ </div>
56
+ <div class="card-body">
57
+ <ul class="list-group list-group-flush">
58
+ <li class="list-group-item">
59
+ <strong>Doctor:</strong> {{ doctor.name }}
60
+ </li>
61
+ <li class="list-group-item">
62
+ <strong>Specialization:</strong> {{ doctor.specialization }}
63
+ </li>
64
+ <li class="list-group-item">
65
+ <strong>Disease/Condition:</strong> {{ appointment.disease_type }}
66
+ </li>
67
+ <li class="list-group-item">
68
+ <strong>Date & Time:</strong> {{ appointment.date.strftime('%Y-%m-%d') }} at {{ appointment.time }}
69
+ </li>
70
+ <li class="list-group-item">
71
+ <strong>Details:</strong>
72
+ {% if appointment.details_selected %}
73
+ <ul>
74
+ {% for detail in appointment.details_selected %}
75
+ <li>{{ detail }}</li>
76
+ {% endfor %}
77
+ </ul>
78
+ {% else %}
79
+ <span class="text-muted">No details provided</span>
80
+ {% endif %}
81
+ </li>
82
+ <li class="list-group-item">
83
+ <strong>Notes:</strong>
84
+ {% if appointment.notes %}
85
+ {{ appointment.notes }}
86
+ {% else %}
87
+ <span class="text-muted">No notes</span>
88
+ {% endif %}
89
+ </li>
90
+ </ul>
91
+ </div>
92
+ </div>
93
+
94
+ <div class="card mt-4">
95
+ <div class="card-header">
96
+ <h5 class="card-title mb-0">Actions</h5>
97
+ </div>
98
+ <div class="card-body">
99
+ <a href="/user/appointments" class="btn btn-primary w-100 mb-2">
100
+ <i class="bi bi-arrow-left"></i> Back to Appointments
101
+ </a>
102
+ <button class="btn btn-outline-secondary w-100">
103
+ <i class="bi bi-printer"></i> Print Prescription
104
+ </button>
105
+ </div>
106
+ </div>
107
+ </div>
108
+ </div>
109
+
110
+ {% endblock %}
111
+
112
+ {% block scripts %}
113
+ <script>
114
+ // Auto-scroll to bottom of chat
115
+ document.addEventListener('DOMContentLoaded', function() {
116
+ const chatMessages = document.getElementById('chatMessages');
117
+ if (chatMessages) {
118
+ chatMessages.scrollTop = chatMessages.scrollHeight;
119
+ }
120
+ });
121
+ </script>
122
+ {% endblock %}
templates/user/dashboard.html ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}User Dashboard - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row">
7
+ <div class="col-12">
8
+ <h2>Welcome, {{ session.username }}!</h2>
9
+ <p class="lead">Here you can access all disease prediction services and view your health reports.</p>
10
+ </div>
11
+ </div>
12
+
13
+ <div class="row mt-4">
14
+ <div class="col-md-3 mb-4">
15
+ <div class="card dashboard-card h-100">
16
+ <div class="card-body">
17
+ <h5 class="card-title"><i class="bi bi-heart text-danger"></i> Heart Disease Prediction</h5>
18
+ <p class="card-text">Analyze various health indicators to predict the likelihood of heart disease.</p>
19
+ <a href="/user/heart-disease" class="btn btn-primary">Check Now</a>
20
+ </div>
21
+ </div>
22
+ </div>
23
+
24
+ <div class="col-md-3 mb-4">
25
+ <div class="card dashboard-card h-100">
26
+ <div class="card-body">
27
+ <h5 class="card-title"><i class="bi bi-droplet text-warning"></i> Diabetes Prediction</h5>
28
+ <p class="card-text">Evaluate key factors to assess your risk of developing diabetes.</p>
29
+ <a href="/user/diabetes" class="btn btn-primary">Check Now</a>
30
+ </div>
31
+ </div>
32
+ </div>
33
+
34
+ <div class="col-md-3 mb-4">
35
+ <div class="card dashboard-card h-100">
36
+ <div class="card-body">
37
+ <h5 class="card-title"><i class="bi bi-person-circle text-info"></i> Parkinson's Prediction</h5>
38
+ <p class="card-text">Detect early signs of Parkinson's disease with our specialized voice analysis model.</p>
39
+ <a href="/user/parkinsons" class="btn btn-primary">Check Now</a>
40
+ </div>
41
+ </div>
42
+ </div>
43
+
44
+ <div class="col-md-3 mb-4">
45
+ <div class="card dashboard-card h-100">
46
+ <div class="card-body">
47
+ <h5 class="card-title"><i class="bi bi-calendar-check text-success"></i> Appointments</h5>
48
+ <p class="card-text">Book and manage appointments with healthcare professionals.</p>
49
+ <a href="/user/appointments" class="btn btn-primary">Manage</a>
50
+ </div>
51
+ </div>
52
+ </div>
53
+ </div>
54
+
55
+ <!-- Visualization Section -->
56
+ <div class="row mt-4">
57
+ <div class="col-lg-6 mb-4">
58
+ <div class="card dashboard-card">
59
+ <div class="card-body">
60
+ <h5>Prediction Results Distribution</h5>
61
+ <div id="predictionChart" class="chart-container"></div>
62
+ </div>
63
+ </div>
64
+ </div>
65
+
66
+ <div class="col-lg-6 mb-4">
67
+ <div class="card dashboard-card">
68
+ <div class="card-body">
69
+ <h5>Disease Type Distribution</h5>
70
+ <div id="diseaseChart" class="chart-container"></div>
71
+ </div>
72
+ </div>
73
+ </div>
74
+ </div>
75
+
76
+ <div class="row mt-4">
77
+ <div class="col-lg-8 mb-4">
78
+ <div class="card dashboard-card">
79
+ <div class="card-body">
80
+ <h5>Prediction Trends (Last 30 Days)</h5>
81
+ <div id="trendChart" class="chart-container"></div>
82
+ </div>
83
+ </div>
84
+ </div>
85
+
86
+ <div class="col-lg-4 mb-4">
87
+ <div class="card dashboard-card">
88
+ <div class="card-body">
89
+ <h5>Confidence Score Distribution</h5>
90
+ <div id="confidenceChart" class="chart-container"></div>
91
+ </div>
92
+ </div>
93
+ </div>
94
+ </div>
95
+
96
+ <div class="row mt-4">
97
+ <div class="col-md-6 mb-4">
98
+ <div class="card">
99
+ <div class="card-header">
100
+ <h5 class="card-title mb-0"><i class="bi bi-clock-history"></i> Recent Predictions</h5>
101
+ </div>
102
+ <div class="card-body">
103
+ {% if recent_predictions %}
104
+ <div class="list-group">
105
+ {% for prediction in recent_predictions %}
106
+ <a href="/user/report/{{ prediction._id }}" class="list-group-item list-group-item-action">
107
+ <div class="d-flex w-100 justify-content-between">
108
+ <h6 class="mb-1">{{ prediction.disease_type }}</h6>
109
+ <small>{{ prediction.date.strftime('%Y-%m-%d %H:%M') }}</small>
110
+ </div>
111
+ <p class="mb-1">{{ prediction.result }}</p>
112
+ </a>
113
+ {% endfor %}
114
+ </div>
115
+ {% else %}
116
+ <p>No predictions yet. Try one of our prediction services!</p>
117
+ {% endif %}
118
+ <a href="/user/history" class="btn btn-outline-primary mt-3">View All Reports</a>
119
+ </div>
120
+ </div>
121
+ </div>
122
+
123
+ <div class="col-md-6 mb-4">
124
+ <div class="card">
125
+ <div class="card-header">
126
+ <h5 class="card-title mb-0"><i class="bi bi-person"></i> Profile</h5>
127
+ </div>
128
+ <div class="card-body">
129
+ <ul class="list-group list-group-flush">
130
+ <li class="list-group-item">
131
+ <strong>Name:</strong> {{ session.username }}
132
+ </li>
133
+ <li class="list-group-item">
134
+ <strong>Email:</strong> {{ session.user_email }}
135
+ </li>
136
+ <li class="list-group-item">
137
+ <strong>Member since:</strong> {{ user.created_at.strftime('%B %d, %Y') }}
138
+ </li>
139
+ </ul>
140
+ <a href="/profile" class="btn btn-outline-primary mt-3">Edit Profile</a>
141
+ </div>
142
+ </div>
143
+ </div>
144
+ </div>
145
+
146
+ {% endblock %}
147
+
148
+ {% block scripts %}
149
+ <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
150
+ <script>
151
+ async function fetchData() {
152
+ const res = await fetch('/user/dashboard/data');
153
+ return await res.json();
154
+ }
155
+
156
+ function drawCharts(data) {
157
+ // Prediction Results Pie Chart
158
+ const positive = data.predictions?.positive || 0;
159
+ const negative = data.predictions?.negative || 0;
160
+
161
+ const predictionData = [{
162
+ values: [positive, negative],
163
+ labels: ['Likely', 'Unlikely'],
164
+ type: 'pie',
165
+ hole: .4,
166
+ marker: {
167
+ colors: ['#dc143c', '#32cd32'] // Danger, Success
168
+ }
169
+ }];
170
+ Plotly.newPlot('predictionChart', predictionData, {responsive:true});
171
+
172
+ // Disease Type Distribution
173
+ const diseaseLabels = data.diseases?.labels || [];
174
+ const diseaseCounts = data.diseases?.counts || [];
175
+
176
+ const diseaseData = [{
177
+ x: diseaseLabels,
178
+ y: diseaseCounts,
179
+ type: 'bar',
180
+ marker: {color: '#006d5b'} // Primary color
181
+ }];
182
+ Plotly.newPlot('diseaseChart', diseaseData, {responsive:true});
183
+
184
+ // Prediction Trends
185
+ const trendDates = data.trend?.dates || [];
186
+ const trendCounts = data.trend?.counts || [];
187
+
188
+ const trendData = [{
189
+ x: trendDates,
190
+ y: trendCounts,
191
+ fill: 'tozeroy',
192
+ type: 'scatter',
193
+ mode: 'lines+markers',
194
+ marker: {color: '#006d5b'}, // Primary color
195
+ line: {color: '#006d5b'} // Primary color
196
+ }];
197
+ Plotly.newPlot('trendChart', trendData, {responsive:true});
198
+
199
+ // Confidence Score Distribution
200
+ const confidenceLabels = data.confidence?.labels || [];
201
+ const confidenceCounts = data.confidence?.counts || [];
202
+
203
+ const confidenceData = [{
204
+ x: confidenceLabels,
205
+ y: confidenceCounts,
206
+ type: 'bar',
207
+ marker: {color: '#ff6b6b'} // Accent color
208
+ }];
209
+ Plotly.newPlot('confidenceChart', confidenceData, {responsive:true});
210
+ }
211
+
212
+ // Fetch data and draw charts when page loads
213
+ document.addEventListener('DOMContentLoaded', function() {
214
+ fetchData().then(drawCharts).catch(err => console.error(err));
215
+ });
216
+ </script>
217
+ {% endblock %}
templates/user/diabetes.html ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Diabetes Prediction - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row">
7
+ <div class="col-12">
8
+ <h2><i class="bi bi-droplet text-warning"></i> Diabetes Prediction</h2>
9
+ <p class="lead">Enter your health information to predict the likelihood of diabetes.</p>
10
+ </div>
11
+ </div>
12
+
13
+ <div class="row mt-4">
14
+ <div class="col-md-8">
15
+ <div class="card">
16
+ <div class="card-header">
17
+ <h5 class="card-title mb-0">Health Information</h5>
18
+ </div>
19
+ <div class="card-body">
20
+ <form method="POST" action="/user/diabetes" class="prediction-form">
21
+ <div class="row">
22
+ <div class="col-md-4 mb-3">
23
+ <label for="pregnancies" class="form-label">Number of Pregnancies</label>
24
+ <input type="text" class="form-control" id="pregnancies" name="pregnancies" required>
25
+ </div>
26
+ <div class="col-md-4 mb-3">
27
+ <label for="glucose" class="form-label">Glucose Level (mg/dL)</label>
28
+ <input type="text" class="form-control" id="glucose" name="glucose" required>
29
+ </div>
30
+ <div class="col-md-4 mb-3">
31
+ <label for="blood_pressure" class="form-label">Blood Pressure (mm Hg)</label>
32
+ <input type="text" class="form-control" id="blood_pressure" name="blood_pressure" required>
33
+ </div>
34
+ </div>
35
+
36
+ <div class="row">
37
+ <div class="col-md-4 mb-3">
38
+ <label for="skin_thickness" class="form-label">Skin Thickness (mm)</label>
39
+ <input type="text" class="form-control" id="skin_thickness" name="skin_thickness" required>
40
+ </div>
41
+ <div class="col-md-4 mb-3">
42
+ <label for="insulin" class="form-label">Insulin Level (mu U/ml)</label>
43
+ <input type="text" class="form-control" id="insulin" name="insulin" required>
44
+ </div>
45
+ <div class="col-md-4 mb-3">
46
+ <label for="bmi" class="form-label">BMI (Body Mass Index)</label>
47
+ <input type="text" class="form-control" id="bmi" name="bmi" required>
48
+ </div>
49
+ </div>
50
+
51
+ <div class="row">
52
+ <div class="col-md-4 mb-3">
53
+ <label for="diabetes_pedigree" class="form-label">Diabetes Pedigree Function</label>
54
+ <input type="text" class="form-control" id="diabetes_pedigree" name="diabetes_pedigree" required>
55
+ </div>
56
+ <div class="col-md-4 mb-3">
57
+ <label for="age" class="form-label">Age (years)</label>
58
+ <input type="text" class="form-control" id="age" name="age" required>
59
+ </div>
60
+ </div>
61
+
62
+ <div class="mt-4">
63
+ <button type="submit" class="btn btn-primary">
64
+ <i class="bi bi-calculator"></i> Predict Diabetes Risk
65
+ </button>
66
+ <a href="/user/dashboard" class="btn btn-secondary">
67
+ <i class="bi bi-speedometer2"></i> Back to Dashboard
68
+ </a>
69
+ </div>
70
+ </form>
71
+ </div>
72
+ </div>
73
+ </div>
74
+
75
+ <div class="col-md-4">
76
+ <div class="card">
77
+ <div class="card-header">
78
+ <h5 class="card-title mb-0">Information</h5>
79
+ </div>
80
+ <div class="card-body">
81
+ <p>This prediction model evaluates key factors to assess your risk of developing diabetes:</p>
82
+ <ul>
83
+ <li>Number of pregnancies</li>
84
+ <li>Glucose and insulin levels</li>
85
+ <li>Blood pressure and BMI</li>
86
+ <li>Family history (pedigree function)</li>
87
+ <li>Age</li>
88
+ </ul>
89
+ <div class="alert alert-info">
90
+ <i class="bi bi-info-circle"></i> Note: This is not a medical diagnosis. Please consult with a healthcare professional for accurate diagnosis.
91
+ </div>
92
+ </div>
93
+ </div>
94
+
95
+ <div class="card mt-4">
96
+ <div class="card-header">
97
+ <h5 class="card-title mb-0">Health Tips</h5>
98
+ </div>
99
+ <div class="card-body">
100
+ <div class="health-tip">
101
+ <h5>Diabetes Prevention</h5>
102
+ <ul>
103
+ <li>Maintain a healthy weight</li>
104
+ <li>Eat a balanced diet rich in fiber</li>
105
+ <li>Limit sugar and refined carbohydrates</li>
106
+ <li>Exercise regularly</li>
107
+ <li>Monitor blood sugar levels</li>
108
+ </ul>
109
+ </div>
110
+ </div>
111
+ </div>
112
+ </div>
113
+ </div>
114
+
115
+ {% endblock %}
templates/user/heart_disease.html ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Heart Disease Prediction - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row">
7
+ <div class="col-12">
8
+ <h2><i class="bi bi-heart text-danger"></i> Heart Disease Prediction</h2>
9
+ <p class="lead">Enter your health information to predict the likelihood of heart disease.</p>
10
+ </div>
11
+ </div>
12
+
13
+ <div class="row mt-4">
14
+ <div class="col-md-8">
15
+ <div class="card">
16
+ <div class="card-header">
17
+ <h5 class="card-title mb-0">Health Information</h5>
18
+ </div>
19
+ <div class="card-body">
20
+ <form method="POST" action="/user/heart-disease" class="prediction-form">
21
+ <div class="row">
22
+ <div class="col-md-4 mb-3">
23
+ <label for="age" class="form-label">Age</label>
24
+ <input type="text" class="form-control" id="age" name="age" required>
25
+ </div>
26
+ <div class="col-md-4 mb-3">
27
+ <label for="sex" class="form-label">Sex</label>
28
+ <select class="form-select" id="sex" name="sex" required>
29
+ <option value="">Select</option>
30
+ <option value="1">Male</option>
31
+ <option value="0">Female</option>
32
+ </select>
33
+ </div>
34
+ <div class="col-md-4 mb-3">
35
+ <label for="cp" class="form-label">Chest Pain Type</label>
36
+ <select class="form-select" id="cp" name="cp" required>
37
+ <option value="">Select</option>
38
+ <option value="0">Typical Angina</option>
39
+ <option value="1">Atypical Angina</option>
40
+ <option value="2">Non-anginal Pain</option>
41
+ <option value="3">Asymptomatic</option>
42
+ </select>
43
+ </div>
44
+ </div>
45
+
46
+ <div class="row">
47
+ <div class="col-md-4 mb-3">
48
+ <label for="trestbps" class="form-label">Resting Blood Pressure (mm Hg)</label>
49
+ <input type="text" class="form-control" id="trestbps" name="trestbps" required>
50
+ </div>
51
+ <div class="col-md-4 mb-3">
52
+ <label for="chol" class="form-label">Serum Cholesterol (mg/dl)</label>
53
+ <input type="text" class="form-control" id="chol" name="chol" required>
54
+ </div>
55
+ <div class="col-md-4 mb-3">
56
+ <label for="fbs" class="form-label">Fasting Blood Sugar > 120 mg/dl</label>
57
+ <select class="form-select" id="fbs" name="fbs" required>
58
+ <option value="">Select</option>
59
+ <option value="1">Yes</option>
60
+ <option value="0">No</option>
61
+ </select>
62
+ </div>
63
+ </div>
64
+
65
+ <div class="row">
66
+ <div class="col-md-4 mb-3">
67
+ <label for="restecg" class="form-label">Resting Electrocardiographic Results</label>
68
+ <select class="form-select" id="restecg" name="restecg" required>
69
+ <option value="">Select</option>
70
+ <option value="0">Normal</option>
71
+ <option value="1">ST-T Wave Abnormality</option>
72
+ <option value="2">Left Ventricular Hypertrophy</option>
73
+ </select>
74
+ </div>
75
+ <div class="col-md-4 mb-3">
76
+ <label for="thalach" class="form-label">Maximum Heart Rate Achieved</label>
77
+ <input type="text" class="form-control" id="thalach" name="thalach" required>
78
+ </div>
79
+ <div class="col-md-4 mb-3">
80
+ <label for="exang" class="form-label">Exercise Induced Angina</label>
81
+ <select class="form-select" id="exang" name="exang" required>
82
+ <option value="">Select</option>
83
+ <option value="1">Yes</option>
84
+ <option value="0">No</option>
85
+ </select>
86
+ </div>
87
+ </div>
88
+
89
+ <div class="row">
90
+ <div class="col-md-4 mb-3">
91
+ <label for="oldpeak" class="form-label">ST Depression Induced by Exercise</label>
92
+ <input type="text" class="form-control" id="oldpeak" name="oldpeak" required>
93
+ </div>
94
+ <div class="col-md-4 mb-3">
95
+ <label for="slope" class="form-label">Slope of Peak Exercise ST Segment</label>
96
+ <select class="form-select" id="slope" name="slope" required>
97
+ <option value="">Select</option>
98
+ <option value="0">Upsloping</option>
99
+ <option value="1">Flat</option>
100
+ <option value="2">Downsloping</option>
101
+ </select>
102
+ </div>
103
+ <div class="col-md-4 mb-3">
104
+ <label for="ca" class="form-label">Number of Major Vessels Colored</label>
105
+ <select class="form-select" id="ca" name="ca" required>
106
+ <option value="">Select</option>
107
+ <option value="0">0</option>
108
+ <option value="1">1</option>
109
+ <option value="2">2</option>
110
+ <option value="3">3</option>
111
+ </select>
112
+ </div>
113
+ </div>
114
+
115
+ <div class="row">
116
+ <div class="col-md-4 mb-3">
117
+ <label for="thal" class="form-label">Thalassemia</label>
118
+ <select class="form-select" id="thal" name="thal" required>
119
+ <option value="">Select</option>
120
+ <option value="0">Normal</option>
121
+ <option value="1">Fixed Defect</option>
122
+ <option value="2">Reversible Defect</option>
123
+ <option value="3">Unknown</option>
124
+ </select>
125
+ </div>
126
+ </div>
127
+
128
+ <button type="submit" class="btn btn-primary">Predict</button>
129
+ <a href="/user/dashboard" class="btn btn-secondary">Back to Dashboard</a>
130
+ </form>
131
+ </div>
132
+ </div>
133
+ </div>
134
+
135
+ <div class="col-md-4">
136
+ <div class="card">
137
+ <div class="card-header">
138
+ <h5 class="card-title mb-0">Information</h5>
139
+ </div>
140
+ <div class="card-body">
141
+ <p>This prediction model analyzes various health indicators to assess the likelihood of heart disease:</p>
142
+ <ul>
143
+ <li>Age and sex</li>
144
+ <li>Chest pain type</li>
145
+ <li>Blood pressure and cholesterol levels</li>
146
+ <li>Electrocardiographic results</li>
147
+ <li>Exercise test results</li>
148
+ </ul>
149
+ <p class="text-muted">Note: This is not a medical diagnosis. Please consult with a healthcare professional for accurate diagnosis.</p>
150
+ </div>
151
+ </div>
152
+
153
+ <div class="card mt-4">
154
+ <div class="card-header">
155
+ <h5 class="card-title mb-0">Health Tips</h5>
156
+ </div>
157
+ <div class="card-body">
158
+ <div class="health-tip">
159
+ <h5>Heart Health</h5>
160
+ <ul>
161
+ <li>Maintain a healthy diet low in saturated fats</li>
162
+ <li>Exercise regularly</li>
163
+ <li>Avoid smoking and excessive alcohol consumption</li>
164
+ <li>Manage stress levels</li>
165
+ <li>Get regular check-ups</li>
166
+ </ul>
167
+ </div>
168
+ </div>
169
+ </div>
170
+ </div>
171
+ </div>
172
+
173
+ {% endblock %}
templates/user/history.html ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}My Reports - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row">
7
+ <div class="col-12">
8
+ <h2><i class="bi bi-clock-history"></i> My Reports</h2>
9
+ <p class="lead">View and manage your prediction history</p>
10
+ </div>
11
+ </div>
12
+
13
+ <div class="row mt-4">
14
+ <div class="col-12">
15
+ <div class="card">
16
+ <div class="card-header">
17
+ <h5 class="card-title mb-0">Prediction History</h5>
18
+ </div>
19
+ <div class="card-body">
20
+ {% if history %}
21
+ <div class="table-responsive">
22
+ <table class="table table-striped report-table">
23
+ <thead>
24
+ <tr>
25
+ <th>Date & Time</th>
26
+ <th>Disease Type</th>
27
+ <th>Result</th>
28
+ <th>Confidence</th>
29
+ <th>Actions</th>
30
+ </tr>
31
+ </thead>
32
+ <tbody>
33
+ {% for record in history %}
34
+ <tr>
35
+ <td>{{ record.date.strftime('%Y-%m-%d %H:%M') }}</td>
36
+ <td>{{ record.disease_type }}</td>
37
+ <td>{{ record.result }}</td>
38
+ <td>{{ "%.2f"|format(record.confidence) }}%</td>
39
+ <td>
40
+ <a href="/user/report/{{ record._id }}" class="btn btn-sm btn-outline-primary">
41
+ <i class="bi bi-eye"></i> View
42
+ </a>
43
+ <a href="/user/download-report/{{ record._id }}" class="btn btn-sm btn-outline-success">
44
+ <i class="bi bi-download"></i> PDF
45
+ </a>
46
+ <a href="/user/delete-report/{{ record._id }}" class="btn btn-sm btn-outline-danger delete-btn">
47
+ <i class="bi bi-trash"></i> Delete
48
+ </a>
49
+ </td>
50
+ </tr>
51
+ {% endfor %}
52
+ </tbody>
53
+ </table>
54
+ </div>
55
+ {% else %}
56
+ <div class="text-center">
57
+ <i class="bi bi-clipboard-x" style="font-size: 3rem;"></i>
58
+ <h4 class="mt-3">No prediction history found</h4>
59
+ <p class="text-muted">Start by making a prediction to see your history here.</p>
60
+ <a href="/user/dashboard" class="btn btn-primary">Go to Dashboard</a>
61
+ </div>
62
+ {% endif %}
63
+ </div>
64
+ </div>
65
+ </div>
66
+ </div>
67
+
68
+ {% endblock %}
templates/user/parkinsons.html ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Parkinson's Prediction - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row">
7
+ <div class="col-12">
8
+ <h2><i class="bi bi-person-circle text-info"></i> Parkinson's Prediction</h2>
9
+ <p class="lead">Enter voice analysis data to predict the likelihood of Parkinson's disease.</p>
10
+ </div>
11
+ </div>
12
+
13
+ <div class="row mt-4">
14
+ <div class="col-md-8">
15
+ <div class="card">
16
+ <div class="card-header">
17
+ <h5 class="card-title mb-0">Voice Analysis Data</h5>
18
+ </div>
19
+ <div class="card-body">
20
+ <form method="POST" action="/user/parkinsons" class="prediction-form">
21
+ <div class="row">
22
+ <div class="col-md-4 mb-3">
23
+ <label for="fo" class="form-label">MDVP:Fo(Hz)</label>
24
+ <input type="text" class="form-control" id="fo" name="fo" required>
25
+ </div>
26
+ <div class="col-md-4 mb-3">
27
+ <label for="fhi" class="form-label">MDVP:Fhi(Hz)</label>
28
+ <input type="text" class="form-control" id="fhi" name="fhi" required>
29
+ </div>
30
+ <div class="col-md-4 mb-3">
31
+ <label for="flo" class="form-label">MDVP:Flo(Hz)</label>
32
+ <input type="text" class="form-control" id="flo" name="flo" required>
33
+ </div>
34
+ </div>
35
+
36
+ <div class="row">
37
+ <div class="col-md-4 mb-3">
38
+ <label for="jitter_percent" class="form-label">MDVP:Jitter(%)</label>
39
+ <input type="text" class="form-control" id="jitter_percent" name="jitter_percent" required>
40
+ </div>
41
+ <div class="col-md-4 mb-3">
42
+ <label for="jitter_abs" class="form-label">MDVP:Jitter(Abs)</label>
43
+ <input type="text" class="form-control" id="jitter_abs" name="jitter_abs" required>
44
+ </div>
45
+ <div class="col-md-4 mb-3">
46
+ <label for="rap" class="form-label">MDVP:RAP</label>
47
+ <input type="text" class="form-control" id="rap" name="rap" required>
48
+ </div>
49
+ </div>
50
+
51
+ <div class="row">
52
+ <div class="col-md-4 mb-3">
53
+ <label for="ppq" class="form-label">MDVP:PPQ</label>
54
+ <input type="text" class="form-control" id="ppq" name="ppq" required>
55
+ </div>
56
+ <div class="col-md-4 mb-3">
57
+ <label for="ddp" class="form-label">Jitter:DDP</label>
58
+ <input type="text" class="form-control" id="ddp" name="ddp" required>
59
+ </div>
60
+ <div class="col-md-4 mb-3">
61
+ <label for="shimmer" class="form-label">MDVP:Shimmer</label>
62
+ <input type="text" class="form-control" id="shimmer" name="shimmer" required>
63
+ </div>
64
+ </div>
65
+
66
+ <div class="row">
67
+ <div class="col-md-4 mb-3">
68
+ <label for="shimmer_db" class="form-label">MDVP:Shimmer(dB)</label>
69
+ <input type="text" class="form-control" id="shimmer_db" name="shimmer_db" required>
70
+ </div>
71
+ <div class="col-md-4 mb-3">
72
+ <label for="apq3" class="form-label">Shimmer:APQ3</label>
73
+ <input type="text" class="form-control" id="apq3" name="apq3" required>
74
+ </div>
75
+ <div class="col-md-4 mb-3">
76
+ <label for="apq5" class="form-label">Shimmer:APQ5</label>
77
+ <input type="text" class="form-control" id="apq5" name="apq5" required>
78
+ </div>
79
+ </div>
80
+
81
+ <div class="row">
82
+ <div class="col-md-4 mb-3">
83
+ <label for="apq" class="form-label">MDVP:APQ</label>
84
+ <input type="text" class="form-control" id="apq" name="apq" required>
85
+ </div>
86
+ <div class="col-md-4 mb-3">
87
+ <label for="dda" class="form-label">Shimmer:DDA</label>
88
+ <input type="text" class="form-control" id="dda" name="dda" required>
89
+ </div>
90
+ <div class="col-md-4 mb-3">
91
+ <label for="nhr" class="form-label">NHR</label>
92
+ <input type="text" class="form-control" id="nhr" name="nhr" required>
93
+ </div>
94
+ </div>
95
+
96
+ <div class="row">
97
+ <div class="col-md-4 mb-3">
98
+ <label for="hnr" class="form-label">HNR</label>
99
+ <input type="text" class="form-control" id="hnr" name="hnr" required>
100
+ </div>
101
+ <div class="col-md-4 mb-3">
102
+ <label for="rpde" class="form-label">RPDE</label>
103
+ <input type="text" class="form-control" id="rpde" name="rpde" required>
104
+ </div>
105
+ <div class="col-md-4 mb-3">
106
+ <label for="dfa" class="form-label">DFA</label>
107
+ <input type="text" class="form-control" id="dfa" name="dfa" required>
108
+ </div>
109
+ </div>
110
+
111
+ <div class="row">
112
+ <div class="col-md-4 mb-3">
113
+ <label for="spread1" class="form-label">Spread1</label>
114
+ <input type="text" class="form-control" id="spread1" name="spread1" required>
115
+ </div>
116
+ <div class="col-md-4 mb-3">
117
+ <label for="spread2" class="form-label">Spread2</label>
118
+ <input type="text" class="form-control" id="spread2" name="spread2" required>
119
+ </div>
120
+ <div class="col-md-4 mb-3">
121
+ <label for="d2" class="form-label">D2</label>
122
+ <input type="text" class="form-control" id="d2" name="d2" required>
123
+ </div>
124
+ </div>
125
+
126
+ <div class="row">
127
+ <div class="col-md-4 mb-3">
128
+ <label for="ppe" class="form-label">PPE</label>
129
+ <input type="text" class="form-control" id="ppe" name="ppe" required>
130
+ </div>
131
+ </div>
132
+
133
+ <button type="submit" class="btn btn-primary">Predict</button>
134
+ <a href="/user/dashboard" class="btn btn-secondary">Back to Dashboard</a>
135
+ </form>
136
+ </div>
137
+ </div>
138
+ </div>
139
+
140
+ <div class="col-md-4">
141
+ <div class="card">
142
+ <div class="card-header">
143
+ <h5 class="card-title mb-0">Information</h5>
144
+ </div>
145
+ <div class="card-body">
146
+ <p>This prediction model analyzes voice characteristics to detect early signs of Parkinson's disease:</p>
147
+ <ul>
148
+ <li>Fundamental frequency variations</li>
149
+ <li>Jitter and shimmer measurements</li>
150
+ <li>Harmonics-to-noise ratio</li>
151
+ <li>Nonlinear dynamical features</li>
152
+ </ul>
153
+ <p class="text-muted">Note: This is not a medical diagnosis. Please consult with a healthcare professional for accurate diagnosis.</p>
154
+ </div>
155
+ </div>
156
+
157
+ <div class="card mt-4">
158
+ <div class="card-header">
159
+ <h5 class="card-title mb-0">Health Tips</h5>
160
+ </div>
161
+ <div class="card-body">
162
+ <div class="health-tip">
163
+ <h5>Parkinson's Management</h5>
164
+ <ul>
165
+ <li>Maintain regular exercise routine</li>
166
+ <li>Practice speech therapy</li>
167
+ <li>Follow a balanced diet</li>
168
+ <li>Get adequate sleep</li>
169
+ <li>Stay socially active</li>
170
+ </ul>
171
+ </div>
172
+ </div>
173
+ </div>
174
+ </div>
175
+ </div>
176
+
177
+ {% endblock %}
templates/user/profile.html ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Profile - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row">
7
+ <div class="col-12">
8
+ <h2><i class="bi bi-person"></i> My Profile</h2>
9
+ <p class="lead">Manage your account information</p>
10
+ </div>
11
+ </div>
12
+
13
+ <div class="row mt-4">
14
+ <div class="col-md-8">
15
+ <div class="card">
16
+ <div class="card-header">
17
+ <h5 class="card-title mb-0">Profile Information</h5>
18
+ </div>
19
+ <div class="card-body">
20
+ <form method="POST" action="/profile">
21
+ <div class="mb-3">
22
+ <label for="name" class="form-label">Full Name</label>
23
+ <input type="text" class="form-control" id="name" name="name" value="{{ user.name }}" required>
24
+ </div>
25
+ <div class="mb-3">
26
+ <label for="email" class="form-label">Email Address</label>
27
+ <input type="email" class="form-control" id="email" name="email" value="{{ user.email }}" required>
28
+ </div>
29
+ <div class="mb-3">
30
+ <label for="phone" class="form-label">Phone Number</label>
31
+ <input type="tel" class="form-control" id="phone" name="phone" value="{{ user.phone }}" required>
32
+ </div>
33
+ <div class="mb-3">
34
+ <label for="current_password" class="form-label">Current Password</label>
35
+ <input type="password" class="form-control" id="current_password" name="current_password" required>
36
+ <div class="form-text">Required to make changes to your profile</div>
37
+ </div>
38
+ <div class="mb-3">
39
+ <label for="new_password" class="form-label">New Password (optional)</label>
40
+ <input type="password" class="form-control" id="new_password" name="new_password">
41
+ <div class="form-text">Leave blank to keep your current password</div>
42
+ </div>
43
+ <div class="mb-3">
44
+ <label for="confirm_password" class="form-label">Confirm New Password</label>
45
+ <input type="password" class="form-control" id="confirm_password" name="confirm_password">
46
+ </div>
47
+ <button type="submit" class="btn btn-primary">Update Profile</button>
48
+ <a href="/user/dashboard" class="btn btn-secondary">Back to Dashboard</a>
49
+ </form>
50
+ </div>
51
+ </div>
52
+ </div>
53
+
54
+ <div class="col-md-4">
55
+ <div class="card">
56
+ <div class="card-header">
57
+ <h5 class="card-title mb-0">Account Information</h5>
58
+ </div>
59
+ <div class="card-body">
60
+ <ul class="list-group list-group-flush">
61
+ <li class="list-group-item">
62
+ <strong>Member since:</strong> {{ user.created_at.strftime('%B %d, %Y') }}
63
+ </li>
64
+ <li class="list-group-item">
65
+ <strong>Total Predictions:</strong> {{ prediction_count }}
66
+ </li>
67
+ <li class="list-group-item">
68
+ <strong>Last Login:</strong> Today
69
+ </li>
70
+ </ul>
71
+ </div>
72
+ </div>
73
+
74
+ <div class="card mt-4">
75
+ <div class="card-header">
76
+ <h5 class="card-title mb-0">Health Statistics</h5>
77
+ </div>
78
+ <div class="card-body">
79
+ <div class="d-flex justify-content-between">
80
+ <span>Heart Predictions:</span>
81
+ <span class="badge bg-danger">{{ heart_count }}</span>
82
+ </div>
83
+ <div class="d-flex justify-content-between mt-2">
84
+ <span>Diabetes Predictions:</span>
85
+ <span class="badge bg-warning">{{ diabetes_count }}</span>
86
+ </div>
87
+ <div class="d-flex justify-content-between mt-2">
88
+ <span>Parkinson's Predictions:</span>
89
+ <span class="badge bg-info">{{ parkinsons_count }}</span>
90
+ </div>
91
+ </div>
92
+ </div>
93
+ </div>
94
+ </div>
95
+
96
+ {% endblock %}
templates/user/report.html ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Detailed Report - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row">
7
+ <div class="col-12">
8
+ <h2><i class="bi bi-clipboard-data"></i> Detailed Report</h2>
9
+ <p class="lead">{{ report.disease_type }} prediction report from {{ report.date.strftime('%Y-%m-%d %H:%M') }}</p>
10
+ </div>
11
+ </div>
12
+
13
+ <div class="row mt-4">
14
+ <div class="col-md-8">
15
+ <div class="card result-card {% if 'likely' in report.result %}positive{% endif %}">
16
+ <div class="card-header">
17
+ <h5 class="card-title mb-0">{{ report.disease_type }} Prediction Report</h5>
18
+ </div>
19
+ <div class="card-body">
20
+ <h3 class="text-center">{{ report.result }}</h3>
21
+ <p class="text-center text-muted">Confidence: {{ "%.2f"|format(report.confidence) }}%</p>
22
+
23
+ <div class="mt-4">
24
+ <h5>Input Data:</h5>
25
+ <div class="table-responsive">
26
+ <table class="table table-bordered">
27
+ <tbody>
28
+ {% for key, value in report.input_data.items() %}
29
+ <tr>
30
+ <td><strong>{{ key.replace('_', ' ').title() }}</strong></td>
31
+ <td>{{ value }}</td>
32
+ </tr>
33
+ {% endfor %}
34
+ </tbody>
35
+ </table>
36
+ </div>
37
+ </div>
38
+
39
+ <div class="mt-4">
40
+ <a href="/user/download-report/{{ report._id }}" class="btn btn-primary">
41
+ <i class="bi bi-download"></i> Download as PDF
42
+ </a>
43
+ <a href="/user/history" class="btn btn-secondary">
44
+ <i class="bi bi-clock-history"></i> Back to History
45
+ </a>
46
+ <a href="/user/delete-report/{{ report._id }}" class="btn btn-danger delete-btn">
47
+ <i class="bi bi-trash"></i> Delete Report
48
+ </a>
49
+ </div>
50
+ </div>
51
+ </div>
52
+ </div>
53
+
54
+ <div class="col-md-4">
55
+ <div class="card">
56
+ <div class="card-header">
57
+ <h5 class="card-title mb-0">Health Recommendations</h5>
58
+ </div>
59
+ <div class="card-body">
60
+ {% if 'likely' in report.result %}
61
+ {% if report.disease_type == 'Heart Disease' %}
62
+ <div class="health-tip">
63
+ <h5>Heart Health Recommendations</h5>
64
+ <ul>
65
+ <li>Consult with a cardiologist immediately</li>
66
+ <li>Follow a heart-healthy diet (low sodium, low saturated fat)</li>
67
+ <li>Engage in regular physical activity</li>
68
+ <li>Monitor blood pressure and cholesterol levels</li>
69
+ <li>Quit smoking if applicable</li>
70
+ <li>Manage stress through relaxation techniques</li>
71
+ <div class="health-tip">
72
+ <h5>Diabetes Management</h5>
73
+ <ul>
74
+ <li>Consult with an endocrinologist or primary care physician</li>
75
+ <li>Monitor blood glucose levels regularly</li>
76
+ <li>Follow a balanced diet with controlled carbohydrate intake</li>
77
+ <li>Engage in regular physical activity</li>
78
+ <li>Maintain a healthy weight</li>
79
+ <li>Take prescribed medications as directed</li>
80
+ </ul>
81
+ </div>
82
+ {% elif report.disease_type == "Parkinson's" %}
83
+ <div class="health-tip">
84
+ <h5>Parkinson's Management</h5>
85
+ <ul>
86
+ <li>Consult with a neurologist specializing in movement disorders</li>
87
+ <li>Consider physical therapy and exercise programs</li>
88
+ <li>Speech therapy for communication difficulties</li>
89
+ <li>Occupational therapy for daily activities</li>
90
+ <li>Join a support group for emotional support</li>
91
+ <li>Follow prescribed medication regimen</li>
92
+ </ul>
93
+ </div>
94
+ {% endif %}
95
+ {% else %}
96
+ <div class="health-tip">
97
+ <h5>Prevention Tips</h5>
98
+ <ul>
99
+ <li>Maintain regular health check-ups</li>
100
+ <li>Follow a balanced diet rich in fruits and vegetables</li>
101
+ <li>Engage in regular physical activity</li>
102
+ <li>Avoid smoking and limit alcohol consumption</li>
103
+ <li>Manage stress levels</li>
104
+ <li>Get adequate sleep</li>
105
+ </ul>
106
+ </div>
107
+ {% endif %}
108
+ </div>
109
+ </div>
110
+
111
+ <div class="card mt-4">
112
+ <div class="card-header">
113
+ <h5 class="card-title mb-0">Important Notice</h5>
114
+ </div>
115
+ <div class="card-body">
116
+ <p class="text-muted">
117
+ This prediction is based on machine learning algorithms and should not be considered as a medical diagnosis.
118
+ Please consult with a qualified healthcare professional for accurate diagnosis and treatment recommendations.
119
+ </p>
120
+ </div>
121
+ </div>
122
+ </div>
123
+ </div>
124
+
125
+
126
+ {% endblock %}
templates/user/result.html ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {% extends "base.html" %}
2
+
3
+ {% block title %}Prediction Result - Multiple Disease Prediction System{% endblock %}
4
+
5
+ {% block content %}
6
+ <div class="row">
7
+ <div class="col-12">
8
+ <h2><i class="bi bi-clipboard-data"></i> Prediction Result</h2>
9
+ <p class="lead">Your {{ result.disease_type }} prediction result</p>
10
+ </div>
11
+ </div>
12
+
13
+ <div class="row mt-4">
14
+ <div class="col-md-8">
15
+ <div class="card result-card {% if 'likely' in result.result %}positive{% endif %}">
16
+ <div class="card-header">
17
+ <h5 class="card-title mb-0">{{ result.disease_type }} Prediction</h5>
18
+ </div>
19
+ <div class="card-body">
20
+ <div class="text-center mb-4">
21
+ <h3 class="{% if 'likely' in result.result %}text-danger{% else %}text-success{% endif %}">
22
+ {{ result.result }}
23
+ </h3>
24
+ <p class="text-muted">
25
+ Confidence: <span class="fw-bold">{{ "%.2f"|format(result.confidence) }}%</span>
26
+ </p>
27
+ </div>
28
+
29
+ <div class="mt-4">
30
+ <h5><i class="bi bi-list-check"></i> Input Data:</h5>
31
+ <div class="table-responsive">
32
+ <table class="table table-bordered">
33
+ <tbody>
34
+ {% for key, value in result.input_data.items() %}
35
+ <tr>
36
+ <td><strong>{{ key.replace('_', ' ').title() }}</strong></td>
37
+ <td>{{ value }}</td>
38
+ </tr>
39
+ {% endfor %}
40
+ </tbody>
41
+ </table>
42
+ </div>
43
+ </div>
44
+
45
+ <div class="mt-4 d-flex flex-wrap gap-2">
46
+ <a href="/user/download-result" class="btn btn-primary">
47
+ <i class="bi bi-download"></i> Download as PDF
48
+ </a>
49
+ <a href="/user/history" class="btn btn-secondary">
50
+ <i class="bi bi-clock-history"></i> View History
51
+ </a>
52
+ <a href="/user/dashboard" class="btn btn-outline-primary">
53
+ <i class="bi bi-speedometer2"></i> Dashboard
54
+ </a>
55
+ </div>
56
+ </div>
57
+ </div>
58
+ </div>
59
+
60
+ <div class="col-md-4">
61
+ <div class="card">
62
+ <div class="card-header">
63
+ <h5 class="card-title mb-0">Health Recommendations</h5>
64
+ </div>
65
+ <div class="card-body">
66
+ {% if 'likely' in result.result %}
67
+ {% if result.disease_type == 'Heart Disease' %}
68
+ <div class="health-tip">
69
+ <h5><i class="bi bi-heart-pulse"></i> Heart Health Recommendations</h5>
70
+ <ul>
71
+ <li>Consult with a cardiologist immediately</li>
72
+ <li>Follow a heart-healthy diet (low sodium, low saturated fat)</li>
73
+ <li>Engage in regular physical activity</li>
74
+ <li>Monitor blood pressure and cholesterol levels</li>
75
+ <li>Quit smoking if applicable</li>
76
+ <li>Manage stress through relaxation techniques</li>
77
+ </ul>
78
+ </div>
79
+ {% elif result.disease_type == 'Diabetes' %}
80
+ <div class="health-tip">
81
+ <h5><i class="bi bi-droplet"></i> Diabetes Management</h5>
82
+ <ul>
83
+ <li>Consult with an endocrinologist or primary care physician</li>
84
+ <li>Monitor blood glucose levels regularly</li>
85
+ <li>Follow a balanced diet with controlled carbohydrate intake</li>
86
+ <li>Engage in regular physical activity</li>
87
+ <li>Maintain a healthy weight</li>
88
+ <li>Take prescribed medications as directed</li>
89
+ </ul>
90
+ </div>
91
+ {% elif result.disease_type == "Parkinson's" %}
92
+ <div class="health-tip">
93
+ <h5><i class="bi bi-person"></i> Parkinson's Management</h5>
94
+ <ul>
95
+ <li>Consult with a neurologist specializing in movement disorders</li>
96
+ <li>Consider physical therapy and exercise programs</li>
97
+ <li>Speech therapy for communication difficulties</li>
98
+ <li>Occupational therapy for daily activities</li>
99
+ <li>Join a support group for emotional support</li>
100
+ <li>Follow prescribed medication regimen</li>
101
+ </ul>
102
+ </div>
103
+ {% endif %}
104
+ {% else %}
105
+ <div class="health-tip">
106
+ <h5><i class="bi bi-shield-check"></i> Prevention Tips</h5>
107
+ <ul>
108
+ <li>Maintain regular health check-ups</li>
109
+ <li>Follow a balanced diet rich in fruits and vegetables</li>
110
+ <li>Engage in regular physical activity</li>
111
+ <li>Avoid smoking and limit alcohol consumption</li>
112
+ <li>Manage stress levels</li>
113
+ <li>Get adequate sleep</li>
114
+ </ul>
115
+ </div>
116
+ {% endif %}
117
+ </div>
118
+ </div>
119
+
120
+ <div class="card mt-4">
121
+ <div class="card-header">
122
+ <h5 class="card-title mb-0">Important Notice</h5>
123
+ </div>
124
+ <div class="card-body">
125
+ <div class="alert alert-warning">
126
+ <i class="bi bi-exclamation-triangle"></i>
127
+ This prediction is based on machine learning algorithms and should not be considered as a medical diagnosis.
128
+ Please consult with a qualified healthcare professional for accurate diagnosis and treatment recommendations.
129
+ </div>
130
+ </div>
131
+ </div>
132
+ </div>
133
+ </div>
134
+
135
+ {% endblock %}