Spaces:
Running
Running
File size: 22,854 Bytes
185c377 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 |
import mysql.connector
from mysql.connector import Error
import logging
from datetime import datetime
import json
import uuid
import os
from PIL import Image
class DatabaseManager:
"""Database operations manager for SmartHeal application"""
def __init__(self, mysql_config):
"""Initialize database manager with MySQL configuration"""
self.mysql_config = mysql_config
self.test_connection()
def test_connection(self):
"""Test database connection"""
try:
connection = self.get_connection()
if connection:
connection.close()
logging.info("β
Database connection successful")
else:
logging.error("β Database connection failed")
except Exception as e:
logging.error(f"Database connection test failed: {e}")
def get_connection(self):
"""Get a database connection"""
try:
connection = mysql.connector.connect(**self.mysql_config)
return connection
except Error as e:
logging.error(f"Error connecting to MySQL: {e}")
return None
def execute_query(self, query, params=None, fetch=False):
"""Execute a query and return results if fetch=True"""
connection = self.get_connection()
if not connection:
return None
cursor = None
try:
cursor = connection.cursor(dictionary=True)
cursor.execute(query, params or ())
if fetch:
result = cursor.fetchall()
else:
connection.commit()
result = cursor.rowcount
return result
except Error as e:
logging.error(f"Error executing query: {e}")
if connection:
connection.rollback()
return None
finally:
if cursor:
cursor.close()
if connection and connection.is_connected():
connection.close()
def execute_query_one(self, query, params=None):
"""Execute a query and return one result"""
connection = self.get_connection()
if not connection:
return None
cursor = None
try:
cursor = connection.cursor(dictionary=True)
cursor.execute(query, params or ())
result = cursor.fetchone()
return result
except Error as e:
logging.error(f"Error executing query: {e}")
return None
finally:
if cursor:
cursor.close()
if connection and connection.is_connected():
connection.close()
def create_tables(self):
"""Create all required database tables"""
tables = {
"users": """
CREATE TABLE IF NOT EXISTS users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) UNIQUE NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
password VARCHAR(255) NOT NULL,
name VARCHAR(100) NOT NULL,
role ENUM('practitioner', 'organization') NOT NULL,
org INT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_login TIMESTAMP NULL,
is_active BOOLEAN DEFAULT TRUE,
INDEX idx_username (username),
INDEX idx_email (email),
INDEX idx_role (role)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
""",
"organizations": """
CREATE TABLE IF NOT EXISTS organizations (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(200) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
phone VARCHAR(20),
country_code VARCHAR(10),
department VARCHAR(100),
location VARCHAR(200),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
is_active BOOLEAN DEFAULT TRUE,
INDEX idx_name (name),
INDEX idx_email (email)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
""",
"questionnaires": """
CREATE TABLE IF NOT EXISTS questionnaires (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
patient_name VARCHAR(100) NOT NULL,
patient_age INT,
patient_gender ENUM('Male', 'Female', 'Other'),
wound_location VARCHAR(200),
wound_duration VARCHAR(100),
pain_level INT DEFAULT 0,
previous_treatment TEXT,
medical_history TEXT,
medications TEXT,
allergies TEXT,
additional_notes TEXT,
moisture_level VARCHAR(50),
infection_signs VARCHAR(50),
diabetic_status VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_user_id (user_id),
INDEX idx_patient_name (patient_name),
INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
""",
"wound_images": """
CREATE TABLE IF NOT EXISTS wound_images (
id INT AUTO_INCREMENT PRIMARY KEY,
questionnaire_id INT NOT NULL,
image_url VARCHAR(500) NOT NULL,
original_filename VARCHAR(255),
file_size INT,
image_width INT,
image_height INT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_questionnaire_id (questionnaire_id),
INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
""",
"ai_analyses": """
CREATE TABLE IF NOT EXISTS ai_analyses (
id INT AUTO_INCREMENT PRIMARY KEY,
questionnaire_id INT NOT NULL,
image_id INT,
analysis_data TEXT,
summary TEXT,
recommendations TEXT,
risk_score INT DEFAULT 0,
risk_level ENUM('Low', 'Moderate', 'High', 'Unknown') DEFAULT 'Unknown',
wound_type VARCHAR(100),
wound_dimensions VARCHAR(100),
processing_time DECIMAL(5,2),
model_version VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_questionnaire_id (questionnaire_id),
INDEX idx_risk_level (risk_level),
INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
""",
"analysis_sessions": """
CREATE TABLE IF NOT EXISTS analysis_sessions (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
questionnaire_id INT NOT NULL,
image_id INT,
analysis_id INT,
session_duration DECIMAL(5,2),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
INDEX idx_user_id (user_id),
INDEX idx_created_at (created_at)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
"""
}
for table_name, table_sql in tables.items():
try:
result = self.execute_query(table_sql)
if result is not None:
logging.info(f"Table '{table_name}' created or already exists")
except Exception as e:
logging.error(f"Error creating table '{table_name}': {e}")
def save_questionnaire(self, questionnaire_data):
"""
Save questionnaire response using the default questionnaire.
This fixes the foreign key constraint issue by using an existing questionnaire ID.
"""
connection = None
cursor = None
try:
connection = self.get_connection()
if not connection:
return None
cursor = connection.cursor()
# (1) Create or get patient
patient_id = self._create_or_get_patient(cursor, questionnaire_data)
if not patient_id:
raise Exception("Failed to get or create patient")
# (2) Get default questionnaire ID
cursor.execute("SELECT id FROM questionnaires WHERE name = 'Default Patient Assessment' LIMIT 1")
questionnaire_row = cursor.fetchone()
if not questionnaire_row:
# Create default questionnaire if it doesn't exist
cursor.execute("""
INSERT INTO questionnaires (name, description, created_at)
VALUES ('Default Patient Assessment', 'Standard patient wound assessment form', NOW())
""")
connection.commit()
questionnaire_id = cursor.lastrowid
else:
questionnaire_id = questionnaire_row[0]
# (3) Prepare response_data JSON
response_data = {
'patient_info': {
'name': questionnaire_data['patient_name'],
'age': questionnaire_data['patient_age'],
'gender': questionnaire_data['patient_gender']
},
'wound_details': {
'location': questionnaire_data['wound_location'],
'duration': questionnaire_data['wound_duration'],
'pain_level': questionnaire_data['pain_level'],
'moisture_level': questionnaire_data['moisture_level'],
'infection_signs': questionnaire_data['infection_signs'],
'diabetic_status': questionnaire_data['diabetic_status']
},
'medical_history': {
'previous_treatment': questionnaire_data['previous_treatment'],
'medical_history': questionnaire_data['medical_history'],
'medications': questionnaire_data['medications'],
'allergies': questionnaire_data['allergies'],
'additional_notes': questionnaire_data['additional_notes']
}
}
# (4) Insert into questionnaire_responses with correct foreign key
insert_resp = """
INSERT INTO questionnaire_responses
(questionnaire_id, patient_id, practitioner_id, response_data, submitted_at)
VALUES (%s, %s, %s, %s, %s)
"""
cursor.execute(insert_resp, (
questionnaire_id, # Use the existing questionnaire ID
patient_id,
questionnaire_data['user_id'],
json.dumps(response_data),
datetime.now()
))
response_id = cursor.lastrowid
connection.commit()
logging.info(f"β
Saved response ID {response_id} for questionnaire {questionnaire_id}")
return response_id
except Exception as e:
logging.error(f"β Error saving questionnaire: {e}")
if connection:
connection.rollback()
return None
finally:
if cursor:
cursor.close()
if connection:
connection.close()
def _create_or_get_patient(self, cursor, questionnaire_data):
"""Create or get existing patient record"""
try:
# Check if patient exists
select_query = """
SELECT id FROM patients
WHERE name = %s AND age = %s AND gender = %s
"""
cursor.execute(select_query, (
questionnaire_data['patient_name'],
questionnaire_data['patient_age'],
questionnaire_data['patient_gender']
))
existing_patient = cursor.fetchone()
if existing_patient:
return existing_patient[0]
# Create new patient
import uuid
insert_query = """
INSERT INTO patients (
uuid, name, age, gender, illness, allergy, notes, created_at
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
"""
patient_uuid = str(uuid.uuid4())
cursor.execute(insert_query, (
patient_uuid,
questionnaire_data['patient_name'],
questionnaire_data['patient_age'],
questionnaire_data['patient_gender'],
questionnaire_data.get('medical_history', ''),
questionnaire_data.get('allergies', ''),
questionnaire_data.get('additional_notes', ''),
datetime.now()
))
return cursor.lastrowid
except Exception as e:
logging.error(f"Error creating/getting patient: {e}")
return None
def _create_wound_record(self, cursor, patient_id, questionnaire_data):
"""Create wound record"""
try:
import uuid
wound_uuid = str(uuid.uuid4())
query = """
INSERT INTO wounds (
uuid, patient_id, position, category, moisture, infection,
notes, created_at
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
"""
cursor.execute(query, (
wound_uuid,
str(patient_id),
questionnaire_data.get('wound_location', ''),
'Assessment', # Default category
questionnaire_data.get('moisture_level', ''),
questionnaire_data.get('infection_signs', ''),
questionnaire_data.get('additional_notes', ''),
datetime.now()
))
return cursor.lastrowid
except Exception as e:
logging.error(f"Error creating wound record: {e}")
return None
def save_wound_image(self, patient_id, image):
"""Save wound image to filesystem and database"""
try:
import uuid
import os
# Generate unique filename
image_id = str(uuid.uuid4())
filename = f"wound_{image_id}.jpg"
file_path = os.path.join("uploads", filename)
# Ensure uploads directory exists
os.makedirs("uploads", exist_ok=True)
# Save image to disk
if hasattr(image, 'save'):
image.save(file_path, format='JPEG', quality=95)
# Get image dimensions
width, height = image.size
# Save to database using proper wound_images table structure
query = """
INSERT INTO wound_images (
uuid, patient_id, image, width, height, created_at
) VALUES (%s, %s, %s, %s, %s, %s)
"""
params = (
str(uuid.uuid4()),
str(patient_id),
file_path,
str(width),
str(height),
datetime.now()
)
connection = self.get_connection()
if not connection:
return None
try:
cursor = connection.cursor()
cursor.execute(query, params)
connection.commit()
image_db_id = cursor.lastrowid
logging.info(f"Image saved with ID: {image_db_id}")
return {
'id': image_db_id,
'filename': filename,
'path': file_path
}
except Error as e:
logging.error(f"Error saving image to database: {e}")
connection.rollback()
return None
finally:
cursor.close()
connection.close()
else:
logging.error("Invalid image object")
return None
except Exception as e:
logging.error(f"Image save error: {e}")
return None
def save_analysis(self, questionnaire_id, image_id, analysis_data):
"""Save AI analysis results to database"""
try:
query = """
INSERT INTO ai_analyses (
questionnaire_id, image_id, analysis_data, summary,
recommendations, risk_score, risk_level, wound_type,
wound_dimensions, processing_time, model_version, created_at
) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
"""
params = (
questionnaire_id,
image_id,
json.dumps(analysis_data) if analysis_data else None,
analysis_data.get('summary', ''),
analysis_data.get('recommendations', ''),
analysis_data.get('risk_score', 0),
analysis_data.get('risk_level', 'Unknown'),
analysis_data.get('wound_type', ''),
analysis_data.get('wound_dimensions', ''),
analysis_data.get('processing_time', 0.0),
analysis_data.get('model_version', 'v1.0'),
datetime.now()
)
connection = self.get_connection()
if not connection:
return None
try:
cursor = connection.cursor()
cursor.execute(query, params)
connection.commit()
analysis_id = cursor.lastrowid
logging.info(f"Analysis saved with ID: {analysis_id}")
return analysis_id
except Error as e:
logging.error(f"Error saving analysis: {e}")
connection.rollback()
return None
finally:
cursor.close()
connection.close()
except Exception as e:
logging.error(f"Analysis save error: {e}")
return None
def get_user_history(self, user_id):
"""Get user's analysis history"""
try:
query = """
SELECT
q.patient_name,
q.wound_location,
q.created_at,
a.risk_level,
a.summary,
a.recommendations
FROM questionnaires q
LEFT JOIN ai_analyses a ON q.id = a.questionnaire_id
WHERE q.user_id = %s
ORDER BY q.created_at DESC
LIMIT 20
"""
result = self.execute_query(query, (user_id,), fetch=True)
return result or []
except Exception as e:
logging.error(f"Error fetching user history: {e}")
return []
def get_organizations(self):
"""Get list of all organizations"""
try:
query = "SELECT id, name as org_name, location FROM organizations ORDER BY name"
result = self.execute_query(query, fetch=True)
return result or [{'id': 1, 'org_name': 'Default Hospital', 'location': 'Default Location'}]
except Exception as e:
logging.error(f"Error getting organizations: {e}")
return [{'id': 1, 'org_name': 'Default Hospital', 'location': 'Default Location'}]
def create_organization(self, org_data):
"""Create a new organization"""
try:
query = """INSERT INTO organizations (name, email, phone, country_code, department, location, created_at)
VALUES (%s, %s, %s, %s, %s, %s, %s)"""
params = (
org_data.get('org_name', ''),
org_data.get('email', ''),
org_data.get('phone', ''),
org_data.get('country_code', ''),
org_data.get('department', ''),
org_data.get('location', ''),
datetime.now()
)
result = self.execute_query(query, params)
if result:
# Get the created organization ID
org_id = self.execute_query_one(
"SELECT id FROM organizations WHERE name = %s ORDER BY created_at DESC LIMIT 1",
(org_data.get('org_name', ''),)
)
return org_id['id'] if org_id else None
return None
except Exception as e:
logging.error(f"Error creating organization: {e}")
return None
def save_analysis_result(self, questionnaire_id, analysis_result):
"""Save analysis result to database"""
try:
query = """INSERT INTO ai_analyses (questionnaire_id, analysis_data, summary, created_at)
VALUES (%s, %s, %s, %s)"""
params = (
questionnaire_id,
json.dumps(analysis_result) if analysis_result else None,
analysis_result.get('summary', 'Analysis completed'),
datetime.now()
)
result = self.execute_query(query, params)
return result
except Exception as e:
logging.error(f"Error saving analysis result: {e}")
return None |