Spaces:
Sleeping
Sleeping
File size: 18,128 Bytes
abdcfa7 |
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 |
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 (aligned to existing schema)."""
def __init__(self, mysql_config):
self.mysql_config = mysql_config
self.test_connection()
self._ensure_default_questionnaire()
# ---------------------- Connection helpers ----------------------
def test_connection(self):
try:
conn = self.get_connection()
if conn:
conn.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):
try:
return mysql.connector.connect(**self.mysql_config)
except Error as e:
logging.error(f"Error connecting to MySQL: {e}")
return None
def execute_query(self, query, params=None, fetch=False):
conn = self.get_connection()
if not conn:
return None
cur = None
try:
cur = conn.cursor(dictionary=True)
cur.execute(query, params or ())
if fetch:
return cur.fetchall()
conn.commit()
return cur.rowcount
except Error as e:
logging.error(f"Error executing query: {e} | SQL: {query} | Params: {params}")
if conn:
conn.rollback()
return None
finally:
if cur: cur.close()
if conn and conn.is_connected(): conn.close()
def execute_query_one(self, query, params=None):
conn = self.get_connection()
if not conn:
return None
cur = None
try:
cur = conn.cursor(dictionary=True)
cur.execute(query, params or ())
return cur.fetchone()
except Error as e:
logging.error(f"Error executing query: {e} | SQL: {query} | Params: {params}")
return None
finally:
if cur: cur.close()
if conn and conn.is_connected(): conn.close()
# ---------------------- One-time ensures ----------------------
def _ensure_default_questionnaire(self):
"""Ensure a 'Default Patient Assessment' row exists in questionnaires."""
try:
row = self.execute_query_one(
"SELECT id FROM questionnaires WHERE name = %s LIMIT 1",
("Default Patient Assessment",)
)
if not row:
self.execute_query(
"INSERT INTO questionnaires (name, description, created_at, updated_at) VALUES (%s, %s, NOW(), NOW())",
("Default Patient Assessment", "Standard patient wound assessment form")
)
logging.info("Created default questionnaire 'Default Patient Assessment'")
except Exception as e:
logging.error(f"Error ensuring default questionnaire: {e}")
# ---------------------- Business ops ----------------------
def save_questionnaire(self, questionnaire_data):
"""
Creates/gets patient in EXISTING `patients` table, then creates a row in `questionnaire_responses`.
Returns the `questionnaire_response_id` (int) or None.
"""
conn = None
cur = None
try:
conn = self.get_connection()
if not conn:
return None
cur = conn.cursor(dictionary=True)
# 1) Create or get patient (EXISTING `patients` table)
patient_id = self._create_or_get_patient(cur, questionnaire_data)
if not patient_id:
raise Exception("Failed to get or create patient")
# 2) Get template questionnaire id
cur.execute("SELECT id FROM questionnaires WHERE name = %s LIMIT 1",
("Default Patient Assessment",))
row = cur.fetchone()
questionnaire_id = row["id"] if row else None
if not questionnaire_id:
raise Exception("Default questionnaire not found")
# 3) Build response_data
response_data = {
'patient_info': {
'name': questionnaire_data.get('patient_name'),
'age': questionnaire_data.get('patient_age'),
'gender': questionnaire_data.get('patient_gender')
},
'wound_details': {
'location': questionnaire_data.get('wound_location'),
'duration': questionnaire_data.get('wound_duration'),
'pain_level': questionnaire_data.get('pain_level'),
'moisture_level': questionnaire_data.get('moisture_level'),
'infection_signs': questionnaire_data.get('infection_signs'),
'diabetic_status': questionnaire_data.get('diabetic_status')
},
'medical_history': {
'previous_treatment': questionnaire_data.get('previous_treatment'),
'medical_history': questionnaire_data.get('medical_history'),
'medications': questionnaire_data.get('medications'),
'allergies': questionnaire_data.get('allergies'),
'additional_notes': questionnaire_data.get('additional_notes')
}
}
practitioner_id = questionnaire_data.get('user_id')
if not practitioner_id:
# Fall back gracefully; your schema expects NOT NULL here.
practitioner_id = 1
# 4) Insert into `questionnaire_responses`
insert_sql = """
INSERT INTO questionnaire_responses
(questionnaire_id, patient_id, practitioner_id, response_data, submitted_at)
VALUES (%s, %s, %s, %s, %s)
"""
cur.execute(insert_sql, (
questionnaire_id,
patient_id, # <-- This is patients.id (BIGINT) and WILL be filled now.
practitioner_id,
json.dumps(response_data, ensure_ascii=False),
datetime.now()
))
response_id = cur.lastrowid
conn.commit()
logging.info(f"β
Saved questionnaire response ID {response_id} (patient_id={patient_id})")
return response_id
except Exception as e:
logging.error(f"β Error saving questionnaire: {e}")
if conn: conn.rollback()
return None
finally:
if cur: cur.close()
if conn: conn.close()
def _create_or_get_patient(self, cur, questionnaire_data):
"""
Works against the EXISTING `patients` table:
columns include id (PK), uuid, name, age (int), gender (varchar), illness, allergy, notes, etc.
Returns patients.id (int).
"""
try:
name = questionnaire_data.get('patient_name')
age = questionnaire_data.get('patient_age')
gender = questionnaire_data.get('patient_gender')
# Try to find an existing patient via (name, age, gender)
cur.execute("""
SELECT id FROM patients
WHERE name = %s AND (age = %s OR %s IS NULL) AND (gender = %s OR %s IS NULL)
LIMIT 1
""", (name, age, age, gender, gender))
row = cur.fetchone()
if row:
return row["id"]
# Create new patient
cur.execute("""
INSERT INTO patients (uuid, name, age, gender, illness, allergy, notes, created_at, updated_at)
VALUES (%s, %s, %s, %s, %s, %s, %s, NOW(), NOW())
""", (
str(uuid.uuid4()),
name,
int(age) if (isinstance(age, (int, float, str)) and str(age).isdigit()) else None,
gender,
questionnaire_data.get('medical_history', ''),
questionnaire_data.get('allergies', ''),
questionnaire_data.get('additional_notes', '')
))
return cur.lastrowid
except Exception as e:
logging.error(f"Error creating/getting patient: {e}")
return None
def _get_patient_uuid(self, patient_id, cur=None):
"""Fetch patients.uuid for a given patients.id (helps when tables store patient_id as VARCHAR uuid)."""
owns_cursor = False
conn = None
try:
if cur is None:
conn = self.get_connection()
if not conn:
return None
cur = conn.cursor(dictionary=True)
owns_cursor = True
cur.execute("SELECT uuid FROM patients WHERE id = %s LIMIT 1", (patient_id,))
row = cur.fetchone()
return row["uuid"] if row else None
except Exception as e:
logging.error(f"Error fetching patient uuid: {e}")
return None
finally:
if owns_cursor and cur: cur.close()
if owns_cursor and conn: conn.close()
def save_wound_image(self, patient_id, image):
"""
Save wound image to filesystem and EXISTING `wound_images` table.
Your `wound_images.patient_id` is VARCHAR, so we store patients.uuid there.
Returns dict {id, filename, path} or None.
"""
try:
# 1) Persist to disk
image_uid = str(uuid.uuid4())
filename = f"wound_{image_uid}.jpg"
os.makedirs("uploads", exist_ok=True)
file_path = os.path.join("uploads", filename)
if hasattr(image, 'save'):
image.save(file_path, format='JPEG', quality=95)
width, height = image.size
file_size = os.path.getsize(file_path)
original_filename = getattr(image, "filename", filename)
elif isinstance(image, str) and os.path.exists(image):
with Image.open(image) as pil:
pil = pil.convert('RGB')
pil.save(file_path, format='JPEG', quality=95)
width, height = pil.size
file_size = os.path.getsize(file_path)
original_filename = os.path.basename(image)
else:
logging.error("Invalid image object/path")
return None
# 2) Resolve patients.uuid (VARCHAR target)
conn = self.get_connection()
if not conn: return None
cur = conn.cursor()
try:
patient_uuid = self._get_patient_uuid(patient_id)
if not patient_uuid:
raise Exception("Patient UUID not found for given patient_id")
# Insert into existing wound_images schema (uuid, patient_id (varchar), image, width, height, etc.)
cur.execute("""
INSERT INTO wound_images (
uuid, patient_id, image, width, height, area, notes, created_at, updated_at
) VALUES (%s, %s, %s, %s, %s, %s, %s, NOW(), NOW())
""", (
str(uuid.uuid4()),
patient_uuid, # VARCHAR column β store patient's UUID
file_path,
str(width),
str(height),
None,
None
))
conn.commit()
image_db_id = cur.lastrowid
logging.info(f"Image saved with ID: {image_db_id}")
return {'id': image_db_id, 'filename': filename, 'path': file_path}
finally:
cur.close()
conn.close()
except Exception as e:
logging.error(f"Image save error: {e}")
return None
def save_analysis(self, questionnaire_response_id, image_id, analysis_data):
"""
Save AI analysis results.
Your live `ai_analyses` table expects `questionnaire_id` (the TEMPLATE), not the response id.
So we first look up the template id from questionnaire_responses and store that.
"""
try:
# Resolve template questionnaire_id from the response
row = self.execute_query_one(
"SELECT questionnaire_id FROM questionnaire_responses WHERE id = %s LIMIT 1",
(questionnaire_response_id,)
)
if not row:
logging.error("No questionnaire_response found for analysis save")
return None
questionnaire_id = row["questionnaire_id"]
query = """
INSERT INTO ai_analyses (
questionnaire_id, image_id, analysis_data, summary,
recommendations, risk_score, risk_level,
processing_time, model_version, created_at
) VALUES (%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 or {}).get('summary', ''),
(analysis_data or {}).get('recommendations', ''),
(analysis_data or {}).get('risk_score', 0),
(analysis_data or {}).get('risk_level', 'Unknown'),
(analysis_data or {}).get('processing_time', 0.0),
(analysis_data or {}).get('model_version', 'v1.0'),
datetime.now()
)
return self.execute_query(query, params, fetch=False)
except Exception as e:
logging.error(f"Analysis save error: {e}")
return None
def get_user_history(self, user_id):
"""
Latest 20 submissions for a practitioner, with optional analysis summary if present.
Aligns to existing schema: joins questionnaire_responses -> questionnaires and LEFT joins ai_analyses (by template).
"""
try:
query = """
SELECT
r.id AS response_id,
r.submitted_at,
p.name AS patient_name,
p.age AS patient_age,
p.gender AS patient_gender,
q.name AS questionnaire_name,
a.risk_level,
a.summary,
a.recommendations
FROM questionnaire_responses r
JOIN patients p ON p.id = r.patient_id
JOIN questionnaires q ON q.id = r.questionnaire_id
LEFT JOIN ai_analyses a ON a.questionnaire_id = r.questionnaire_id
WHERE r.practitioner_id = %s
ORDER BY r.submitted_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 []
# Convenience for existing callers (kept signature)
def create_organization(self, org_data):
try:
query = """INSERT INTO organizations (name, email, phone, country_code, department, location, created_at, updated_at)
VALUES (%s, %s, %s, %s, %s, %s, NOW(), NOW())"""
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', '')
)
rc = self.execute_query(query, params)
if rc:
row = self.execute_query_one(
"SELECT id FROM organizations WHERE name = %s ORDER BY created_at DESC LIMIT 1",
(org_data.get('org_name', ''),)
)
return row['id'] if row else None
return None
except Exception as e:
logging.error(f"Error creating organization: {e}")
return None
def get_organizations(self):
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'}]
# Back-compat helper kept (writes same as save_analysis, minimal data)
def save_analysis_result(self, questionnaire_response_id, analysis_result):
try:
# store under template id like save_analysis()
row = self.execute_query_one(
"SELECT questionnaire_id FROM questionnaire_responses WHERE id = %s LIMIT 1",
(questionnaire_response_id,)
)
if not row:
logging.error("No questionnaire_response found for analysis_result save")
return None
questionnaire_id = row["questionnaire_id"]
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 or {}).get('summary', 'Analysis completed'),
datetime.now()
)
return self.execute_query(query, params)
except Exception as e:
logging.error(f"Error saving analysis result: {e}")
return None
|