Spaces:
Sleeping
Sleeping
File size: 65,943 Bytes
c9c46e8 a2b08bf c9c46e8 a31539c c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf c9c46e8 a2b08bf |
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 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 |
import gradio as gr
import os
import re
import logging
import tempfile
import shutil
import base64
from datetime import datetime
from PIL import Image
import html # Import the html module for escaping
from .patient_history import PatientHistoryManager, ReportGenerator
def pil_to_base64(pil_image):
"""Convert PIL Image to base64 data URL"""
import io
import base64
from PIL import Image
if pil_image is None:
return None
try:
# Convert image to RGB if it's not already
if pil_image.mode != 'RGB':
pil_image = pil_image.convert('RGB')
buffer = io.BytesIO()
pil_image.save(buffer, format='PNG')
img_str = base64.b64encode(buffer.getvalue()).decode()
return f"data:image/png;base64,{img_str}"
except Exception as e:
logging.error(f"Error converting PIL image to base64: {e}")
return None
class UIComponents:
def __init__(self, auth_manager, database_manager, wound_analyzer):
self.auth_manager = auth_manager
self.database_manager = database_manager
self.wound_analyzer = wound_analyzer
self.current_user = {}
self.patient_history_manager = PatientHistoryManager(database_manager)
self.report_generator = ReportGenerator()
# Ensure uploads directory exists
if not os.path.exists("uploads"):
os.makedirs("uploads", exist_ok=True)
def image_to_base64(self, image_path):
"""Convert image to base64 data URL for embedding in HTML"""
if not image_path or not os.path.exists(image_path):
return None
try:
with open(image_path, "rb") as image_file:
encoded_string = base64.b64encode(image_file.read()).decode()
# Determine image format
image_ext = os.path.splitext(image_path)[1].lower()
if image_ext in [".jpg", ".jpeg"]:
mime_type = "image/jpeg"
elif image_ext == ".png":
mime_type = "image/png"
elif image_ext == ".gif":
mime_type = "image/gif"
else:
mime_type = "image/png" # Default to PNG
return f"data:{mime_type};base64,{encoded_string}"
except Exception as e:
logging.error(f"Error converting image to base64: {e}")
return None
def markdown_to_html(self, markdown_text):
"""Convert markdown text to proper HTML format with enhanced support"""
if not markdown_text:
return ""
# Escape HTML entities first to prevent issues with special characters
html_text = html.escape(markdown_text)
# Convert headers
html_text = re.sub(r"^### (.*?)$", r"<h3>\1</h3>", html_text, flags=re.MULTILINE)
html_text = re.sub(r"^## (.*?)$", r"<h2>\1</h2>", html_text, flags=re.MULTILINE)
html_text = re.sub(r"^# (.*?)$", r"<h1>\1</h1>", html_text, flags=re.MULTILINE)
# Convert bold text
html_text = re.sub(r"\*\*(.*?)\*\*", r"<strong>\1</strong>", html_text)
# Convert italic text
html_text = re.sub(r"\*(.*?)\*", r"<em>\1</em>", html_text)
# Convert code blocks (triple backticks)
html_text = re.sub(r"```(.*?)```", r"<pre><code>\1</code></pre>", html_text, flags=re.DOTALL)
# Convert inline code (single backticks)
html_text = re.sub(r"`(.*?)`", r"<code>\1</code>", html_text)
# Convert blockquotes
html_text = re.sub(r"^> (.*?)$", r"<blockquote>\1</blockquote>", html_text, flags=re.MULTILINE)
# Convert links
html_text = re.sub(r"\[(.*?)\]\((.*?)\)", r"<a href=\"\2\">\1</a>", html_text)
# Convert horizontal rules
html_text = re.sub(r"^\s*[-*_]{3,}\s*$", r"<hr>", html_text, flags=re.MULTILINE)
# Convert bullet points and handle nested lists (simplified for example)
lines = html_text.split("\n")
in_list = False
result_lines = []
for line in lines:
stripped = line.strip()
if stripped.startswith("- "):
if not in_list:
result_lines.append("<ul>")
in_list = True
result_lines.append(f"<li>{stripped[2:]}</li>")
else:
if in_list:
result_lines.append("</ul>")
in_list = False
if stripped:
result_lines.append(f"<p>{stripped}</p>")
else:
result_lines.append("<br>")
if in_list:
result_lines.append("</ul>")
return "\n".join(result_lines)
def get_organizations_dropdown(self):
"""Get list of organizations for dropdown"""
try:
organizations = self.database_manager.get_organizations()
return [f"{org['org_name']} - {org['location']}" for org in organizations]
except Exception as e:
logging.error(f"Error getting organizations: {e}")
return ["Default Hospital - Location"]
def get_custom_css(self):
return """
/* =================== ORIGINAL SMARTHEAL CSS =================== */
/* Global Styling */
body, html {
margin: 0 !important;
padding: 0 !important;
font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', sans-serif !important;
background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%) !important;
color: #1A202C !important;
line-height: 1.6 !important;
}
/* Professional Header with Logo */
.medical-header {
background: linear-gradient(135deg, #3182ce 0%, #2c5aa0 100%) !important;
color: white !important;
padding: 32px 40px !important;
border-radius: 20px 20px 0 0 !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
margin-bottom: 0 !important;
box-shadow: 0 10px 40px rgba(49, 130, 206, 0.3) !important;
border: none !important;
position: relative !important;
overflow: hidden !important;
}
.medical-header::before {
content: '' !important;
position: absolute !important;
top: 0 !important;
left: 0 !important;
right: 0 !important;
bottom: 0 !important;
background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="rgba(255,255,255,0.1)" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)" /></svg>') !important;
opacity: 0.1 !important;
z-index: 1 !important;
}
.medical-header > * {
position: relative !important;
z-index: 2 !important;
}
.logo {
width: 80px !important;
height: 80px !important;
border-radius: 50% !important;
margin-right: 24px !important;
border: 4px solid rgba(255, 255, 255, 0.3) !important;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2) !important;
background: white !important;
padding: 4px !important;
}
.medical-header h1 {
font-size: 3.5rem !important;
font-weight: 800 !important;
margin: 0 !important;
text-shadow: 2px 2px 8px rgba(0, 0, 0, 0.3) !important;
background: linear-gradient(45deg, #ffffff, #f8f9fa) !important;
-webkit-background-clip: text !important;
-webkit-text-fill-color: transparent !important;
background-clip: text !important;
filter: drop-shadow(2px 2px 4px rgba(0, 0, 0, 0.3)) !important;
}
.medical-header p {
font-size: 1.3rem !important;
margin: 8px 0 0 0 !important;
opacity: 0.95 !important;
font-weight: 500 !important;
text-shadow: 1px 1px 4px rgba(0, 0, 0, 0.2) !important;
}
/* Enhanced Form Styling */
.gr-form {
background: linear-gradient(145deg, #ffffff 0%, #f8f9fa 100%) !important;
border-radius: 20px !important;
padding: 32px !important;
margin: 24px 0 !important;
box-shadow: 0 16px 48px rgba(0, 0, 0, 0.1) !important;
border: 1px solid rgba(229, 62, 62, 0.1) !important;
backdrop-filter: blur(10px) !important;
position: relative !important;
overflow: hidden !important;
}
.gr-form::before {
content: '' !important;
position: absolute !important;
top: 0 !important;
left: 0 !important;
right: 0 !important;
height: 4px !important;
background: linear-gradient(90deg, #e53e3e 0%, #f56565 50%, #e53e3e 100%) !important;
z-index: 1 !important;
}
/* Professional Input Fields */
.gr-textbox, .gr-number {
border-radius: 12px !important;
border: 2px solid #E2E8F0 !important;
background: #FFFFFF !important;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05) !important;
font-size: 1rem !important;
color: #1A202C !important;
padding: 16px 20px !important;
}
.gr-textbox:focus,
.gr-number:focus,
.gr-textbox input:focus,
.gr-number input:focus {
border-color: #E53E3E !important;
box-shadow: 0 0 0 4px rgba(229, 62, 62, 0.1) !important;
background: #FFFFFF !important;
outline: none !important;
transform: translateY(-1px) !important;
}
.gr-textbox input,
.gr-number input {
background: transparent !important;
border: none !important;
outline: none !important;
color: #1A202C !important;
font-size: 1rem !important;
width: 100% !important;
padding: 0 !important;
}
.gr-textbox label,
.gr-number label,
.gr-dropdown label,
.gr-radio label,
.gr-checkbox label {
font-weight: 600 !important;
color: #2D3748 !important;
font-size: 1rem !important;
margin-bottom: 8px !important;
display: block !important;
}
/* Enhanced Button Styling */
button.gr-button,
button.gr-button-primary {
background: linear-gradient(135deg, #E53E3E 0%, #C53030 100%) !important;
color: #FFFFFF !important;
border: none !important;
border-radius: 12px !important;
font-weight: 700 !important;
padding: 16px 32px !important;
font-size: 1.1rem !important;
letter-spacing: 0.5px !important;
text-align: center !important;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
box-shadow: 0 4px 16px rgba(229, 62, 62, 0.3) !important;
position: relative !important;
overflow: hidden !important;
text-transform: uppercase !important;
cursor: pointer !important;
}
button.gr-button::before {
content: '' !important;
position: absolute !important;
top: 0 !important;
left: -100% !important;
width: 100% !important;
height: 100% !important;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.4), transparent) !important;
transition: left 0.5s !important;
}
button.gr-button:hover::before {
left: 100% !important;
}
button.gr-button:hover,
button.gr-button-primary:hover {
background: linear-gradient(135deg, #C53030 0%, #9C2A2A 100%) !important;
box-shadow: 0 8px 32px rgba(229, 62, 62, 0.4) !important;
transform: translateY(-3px) !important;
}
button.gr-button:active,
button.gr-button-primary:active {
transform: translateY(-1px) !important;
box-shadow: 0 4px 16px rgba(229, 62, 62, 0.5) !important;
}
button.gr-button:disabled {
background: #A0AEC0 !important;
color: #718096 !important;
cursor: not-allowed !important;
box-shadow: none !important;
transform: none !important;
}
/* Professional Status Messages */
.status-success {
background: linear-gradient(135deg, #F0FFF4 0%, #E6FFFA 100%) !important;
border: 2px solid #38A169 !important;
color: #22543D !important;
padding: 20px 24px !important;
border-radius: 16px !important;
font-weight: 600 !important;
margin: 16px 0 !important;
box-shadow: 0 8px 24px rgba(56, 161, 105, 0.2) !important;
backdrop-filter: blur(10px) !important;
}
.status-error {
background: linear-gradient(135deg, #FFF5F5 0%, #FED7D7 100%) !important;
border: 2px solid #E53E3E !important;
color: #742A2A !important;
padding: 20px 24px !important;
border-radius: 16px !important;
font-weight: 600 !important;
margin: 16px 0 !important;
box-shadow: 0 8px 24px rgba(229, 62, 62, 0.2) !important;
backdrop-filter: blur(10px) !important;
}
.status-warning {
background: linear-gradient(135deg, #FFFAF0 0%, #FEEBC8 100%) !important;
border: 2px solid #DD6B20 !important;
color: #9C4221 !important;
padding: 20px 24px !important;
border-radius: 16px !important;
font-weight: 600 !important;
margin: 16px 0 !important;
box-shadow: 0 8px 24px rgba(221, 107, 32, 0.2) !important;
backdrop-filter: blur(10px) !important;
}
/* Professional Card Layout */
.medical-card {
background: linear-gradient(145deg, #FFFFFF 0%, #F7FAFC 100%) !important;
border-radius: 20px !important;
padding: 32px !important;
margin: 24px 0 !important;
box-shadow: 0 16px 48px rgba(0, 0, 0, 0.08) !important;
border: 1px solid rgba(229, 62, 62, 0.1) !important;
backdrop-filter: blur(10px) !important;
position: relative !important;
overflow: hidden !important;
}
.medical-card::before {
content: '' !important;
position: absolute !important;
top: 0 !important;
left: 0 !important;
right: 0 !important;
height: 4px !important;
background: linear-gradient(90deg, #E53E3E 0%, #F56565 50%, #E53E3E 100%) !important;
}
.medical-card-title {
font-size: 1.75rem !important;
font-weight: 700 !important;
color: #1A202C !important;
margin-bottom: 24px !important;
padding-bottom: 16px !important;
border-bottom: 2px solid #E53E3E !important;
text-align: center !important;
position: relative !important;
}
.medical-card-title::after {
content: '' !important;
position: absolute !important;
bottom: -2px !important;
left: 50% !important;
transform: translateX(-50%) !important;
width: 60px !important;
height: 4px !important;
background: linear-gradient(90deg, transparent, #E53E3E, transparent) !important;
border-radius: 2px !important;
}
/* Professional Dropdown Styling */
.gr-dropdown {
border-radius: 12px !important;
border: 2px solid #E2E8F0 !important;
background: #FFFFFF !important;
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05) !important;
}
.gr-dropdown:focus,
.gr-dropdown select:focus {
border-color: #E53E3E !important;
box-shadow: 0 0 0 4px rgba(229, 62, 62, 0.1) !important;
outline: none !important;
}
.gr-dropdown select {
background: transparent !important;
border: none !important;
color: #1A202C !important;
font-size: 1rem !important;
padding: 16px 20px !important;
border-radius: 12px !important;
}
/* Radio button styling */
.gr-radio input[type="radio"] {
margin-right: 8px !important;
transform: scale(1.2) !important;
}
.gr-radio label {
display: flex !important;
align-items: center !important;
padding: 8px 0 !important;
font-size: 1rem !important;
line-height: 1.5 !important;
cursor: pointer !important;
color: #1A202C !important;
}
/* Tab styling */
.gr-tab {
color: #1A202C !important;
font-weight: 500 !important;
font-size: 1rem !important;
padding: 12px 20px !important;
background-color: #F7FAFC !important;
}
.gr-tab.selected {
color: #E53E3E !important;
font-weight: 600 !important;
border-bottom: 2px solid #E53E3E !important;
background-color: #FFFFFF !important;
}
/* Image upload styling */
.gr-image {
border: 3px dashed #CBD5E0 !important;
border-radius: 16px !important;
background-color: #F7FAFC !important;
transition: all 0.2s ease !important;
}
.gr-image:hover {
border-color: #E53E3E !important;
background-color: #FFF5F5 !important;
}
/* Analyze button special styling */
#analyze-btn {
background: linear-gradient(135deg, #1B5CF3 0%, #1E3A8A 100%) !important;
color: #FFFFFF !important;
border: none !important;
border-radius: 8px !important;
font-weight: 700 !important;
padding: 14px 28px !important;
font-size: 1.1rem !important;
letter-spacing: 0.5px !important;
text-align: center !important;
transition: all 0.2s ease-in-out !important;
}
#analyze-btn:hover {
background: linear-gradient(135deg, #174ea6 0%, #123b82 100%) !important;
box-shadow: 0 4px 14px rgba(27, 95, 193, 0.4) !important;
transform: translateY(-2px) !important;
}
#analyze-btn:disabled {
background: #A0AEC0 !important;
color: #1A202C !important;
cursor: not-allowed !important;
box-shadow: none !important;
transform: none !important;
}
/* Image gallery styling for better visualization */
.image-gallery {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
margin: 20px 0;
}
.image-item {
background: #f8f9fa;
border-radius: 12px;
padding: 15px;
box-shadow: 0 4px 12px rgba(0,0,0,0.1);
text-align: center;
}
.image-item img {
max-width: 100%;
height: auto;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.15);
}
.image-item h4 {
margin: 15px 0 5px 0;
color: #2d3748;
font-weight: 600;
}
.image-item p {
margin: 0;
color: #666;
font-size: 0.9em;
}
/* Responsive design */
@media (max-width: 768px) {
.medical-header {
padding: 16px !important;
text-align: center !important;
}
.medical-header h1 {
font-size: 2rem !important;
}
.logo {
width: 48px !important;
height: 48px !important;
margin-right: 16px !important;
}
.gr-form {
padding: 16px !important;
margin: 8px 0 !important;
}
button.gr-button,
button.gr-button-primary {
padding: 14px 20px !important;
font-size: 14px !important;
}
.image-gallery {
grid-template-columns: 1fr;
}
}
"""
def create_interface(self):
"""Create the main Gradio interface with original styling and base64 image embedding"""
with gr.Blocks(css=self.get_custom_css(), title="SmartHeal - AI Wound Care Assistant") as app:
# Header with SmartHeal logo (from original)
logo_url = "https://scontent.fccu31-2.fna.fbcdn.net/v/t39.30808-6/275933824_102121829111657_3325198727201325354_n.jpg?_nc_cat=104&ccb=1-7&_nc_sid=6ee11a&_nc_ohc=45krrEUpcSUQ7kNvwGVdiMW&_nc_oc=AdkTdxEC_TkYGiyDkEtTJZ_DFZELW17XKFmWpswmFqGB7JSdvTyWtnrQyLS0USngEiY&_nc_zt=23&_nc_ht=scontent.fccu31-2.fna&_nc_gid=ufAA4Hj5gTRwON5POYzz0Q&oh=00_AfW1-jLEN5RGeggqOvGgEaK_gdg0EDgxf_VhKbZwFLUO0Q&oe=6897A98B"
gr.HTML(f"""
<div class="medical-header">
<img src="{logo_url}" class="logo" alt="SmartHeal Logo">
<div>
<h1>SmartHeal AI</h1>
<p>Advanced Wound Care Analysis & Clinical Support System</p>
</div>
</div>
""")
# Professional disclaimer (from original)
gr.HTML("""
<div style="border: 2px solid #FF6B6B; background-color: #FFE5E5; padding: 15px; border-radius: 12px; margin: 10px 0;">
<h3 style="color: #D63031; margin-top: 0;">β οΈ IMPORTANT DISCLAIMER</h3>
<p><strong>This model is for testing and educational purposes only and is NOT a replacement for professional medical advice.</strong></p>
<p>Information generated may be inaccurate. Always consult a qualified healthcare provider for medical concerns. This AI system uses chain-of-thought reasoning to show its decision-making process, but should never be used as the sole basis for clinical decisions.</p>
<p><em>Uploaded images may be stored and used for testing and model improvement purposes.</em></p>
</div>
""")
# Main interface with conditional visibility (ORIGINAL STRUCTURE)
with gr.Row():
# Professional Authentication Panel (visible when not logged in)
with gr.Column(visible=True) as auth_panel:
gr.HTML("""
<div style="text-align: center; margin: 40px 0;">
<div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 40px; border-radius: 20px; box-shadow: 0 20px 40px rgba(0,0,0,0.1); max-width: 500px; margin: 0 auto;">
<h2 style="color: white; font-size: 2.5rem; margin-bottom: 10px; font-weight: 700;">π₯ SmartHeal Access</h2>
<p style="color: rgba(255,255,255,0.9); font-size: 1.1rem; margin-bottom: 30px;">Secure Healthcare Professional Portal</p>
</div>
</div>
""")
with gr.Tabs():
with gr.Tab("π Professional Login") as login_tab:
gr.HTML("""
<div style="background: white; padding: 40px; border-radius: 16px; box-shadow: 0 8px 32px rgba(0,0,0,0.1); margin: 20px auto; max-width: 450px;">
<div style="text-align: center; margin-bottom: 30px;">
<h3 style="color: #2d3748; font-size: 1.8rem; margin-bottom: 8px;">Welcome Back</h3>
<p style="color: #718096; font-size: 1rem;">Access your professional dashboard</p>
</div>
</div>
""")
login_username = gr.Textbox(
label="π€ Username",
placeholder="Enter your username"
)
login_password = gr.Textbox(
label="π Password",
type="password",
placeholder="Enter your secure password"
)
login_btn = gr.Button(
"π Sign In to Dashboard",
variant="primary",
size="lg"
)
login_status = gr.HTML(
value="<div style='text-align: center; color: #718096; font-size: 0.9rem; margin-top: 15px;'>Enter your credentials to access the system</div>"
)
with gr.Tab("π New Registration") as signup_tab:
gr.HTML("""
<div style="background: white; padding: 40px; border-radius: 16px; box-shadow: 0 8px 32px rgba(0,0,0,0.1); margin: 20px auto; max-width: 450px;">
<div style="text-align: center; margin-bottom: 30px;">
<h3 style="color: #2d3748; font-size: 1.8rem; margin-bottom: 8px;">Create Account</h3>
<p style="color: #718096; font-size: 1rem;">Join the SmartHeal healthcare network</p>
</div>
</div>
""")
signup_username = gr.Textbox(
label="π€ Username",
placeholder="Choose a unique username"
)
signup_email = gr.Textbox(
label="π§ Email Address",
placeholder="Enter your professional email"
)
signup_password = gr.Textbox(
label="π Password",
type="password",
placeholder="Create a strong password"
)
signup_name = gr.Textbox(
label="π¨ββοΈ Full Name",
placeholder="Enter your full professional name"
)
signup_role = gr.Radio(
["practitioner", "organization"],
label="π₯ Account Type",
value="practitioner"
)
# Organization-specific fields
with gr.Group(visible=False) as org_fields:
gr.HTML("<h4 style='color: #2d3748; margin: 20px 0 10px 0;'>π’ Organization Details</h4>")
org_name = gr.Textbox(label="Organization Name", placeholder="Enter organization name")
phone = gr.Textbox(label="Phone Number", placeholder="Enter contact number")
country_code = gr.Textbox(label="Country Code", placeholder="e.g., +1, +44")
department = gr.Textbox(label="Department", placeholder="e.g., Emergency, Surgery")
location = gr.Textbox(label="Location", placeholder="City, State/Province, Country")
# Practitioner-specific fields
with gr.Group(visible=True) as prac_fields:
gr.HTML("<h4 style='color: #2d3748; margin: 20px 0 10px 0;'>π₯ Affiliation</h4>")
organization_dropdown = gr.Dropdown(
choices=self.get_organizations_dropdown(),
label="Select Your Organization"
)
signup_btn = gr.Button(
"β¨ Create Professional Account",
variant="primary",
size="lg"
)
signup_status = gr.HTML(
value="<div style='text-align: center; color: #718096; font-size: 0.9rem; margin-top: 15px;'>Fill in your details to create an account</div>"
)
# Practitioner Interface (hidden initially)
with gr.Column(visible=False) as practitioner_panel:
gr.HTML('<div class="medical-card-title">π©ββοΈ Practitioner Dashboard</div>')
user_info = gr.HTML("")
logout_btn_prac = gr.Button("πͺ Logout", variant="secondary", elem_classes=["logout-btn"])
# Main tabs for different functions
with gr.Tabs():
# WOUND ANALYSIS TAB
with gr.Tab("π¬ Wound Analysis"):
with gr.Row():
with gr.Column(scale=1):
gr.HTML("<h3>π Patient Information</h3>")
patient_name = gr.Textbox(label="Patient Name", placeholder="Enter patient's full name")
patient_age = gr.Number(label="Age", value=30, minimum=0, maximum=120)
patient_gender = gr.Dropdown(
choices=["Male", "Female", "Other"],
label="Gender",
value="Male"
)
gr.HTML("<h3>π©Ή Wound Information</h3>")
wound_location = gr.Textbox(label="Wound Location", placeholder="e.g., Left ankle, Right arm")
wound_duration = gr.Textbox(label="Wound Duration", placeholder="e.g., 2 weeks, 1 month")
pain_level = gr.Slider(
minimum=0, maximum=10, value=5, step=1,
label="Pain Level (0-10)"
)
gr.HTML("<h3>βοΈ Clinical Assessment</h3>")
moisture_level = gr.Dropdown(
choices=["Dry", "Moist", "Wet", "Saturated"],
label="Moisture Level",
value="Moist"
)
infection_signs = gr.Dropdown(
choices=["None", "Mild", "Moderate", "Severe"],
label="Signs of Infection",
value="None"
)
diabetic_status = gr.Dropdown(
choices=["Non-diabetic", "Type 1", "Type 2", "Gestational"],
label="Diabetic Status",
value="Non-diabetic"
)
with gr.Column(scale=1):
gr.HTML("<h3>πΈ Wound Image Upload</h3>")
wound_image = gr.Image(
label="Upload Wound Image",
type="filepath",
elem_classes=["image-upload"]
)
gr.HTML("<h3>π Medical History</h3>")
previous_treatment = gr.Textbox(
label="Previous Treatment",
placeholder="Describe any previous treatments...",
lines=3
)
medical_history = gr.Textbox(
label="Medical History",
placeholder="Relevant medical conditions, surgeries, etc...",
lines=3
)
medications = gr.Textbox(
label="Current Medications",
placeholder="List current medications...",
lines=2
)
allergies = gr.Textbox(
label="Known Allergies",
placeholder="List any known allergies...",
lines=2
)
additional_notes = gr.Textbox(
label="Additional Notes",
placeholder="Any additional clinical observations...",
lines=3
)
analyze_btn = gr.Button("π¬ Analyze Wound", variant="primary", size="lg", elem_id="analyze-btn")
analysis_output = gr.HTML("")
# PATIENT HISTORY TAB
with gr.Tab("π Patient History"):
with gr.Row():
with gr.Column(scale=2):
gr.HTML("<h3>π Patient History Dashboard</h3>")
history_btn = gr.Button("π Load Patient History", variant="primary")
patient_history_output = gr.HTML("")
with gr.Column(scale=1):
gr.HTML("<h3>π Search Specific Patient</h3>")
search_patient_name = gr.Textbox(
label="Patient Name",
placeholder="Enter patient name to search..."
)
search_patient_btn = gr.Button("π Search Patient History", variant="secondary")
specific_patient_output = gr.HTML("")
# Event handlers
def handle_login(username, password):
user_data = self.auth_manager.authenticate_user(username, password)
if user_data:
self.current_user = user_data
return {
auth_panel: gr.update(visible=False),
practitioner_panel: gr.update(visible=True),
login_status: "<div class='status-success'>β
Login successful! Welcome to SmartHeal</div>"
}
else:
return {
login_status: "<div class='status-error'>β Invalid credentials. Please try again.</div>"
}
def handle_signup(username, email, password, name, role, org_name, phone, country_code, department, location, organization_dropdown):
try:
if role == "organization":
org_data = {
'org_name': org_name,
'phone': phone,
'country_code': country_code,
'department': department,
'location': location
}
org_id = self.database_manager.create_organization(org_data)
user_data = {
'username': username,
'email': email,
'password': password,
'name': name,
'role': role,
'org_id': org_id
}
else:
# Extract org_id from dropdown selection
org_id = 1 # Default organization for now
user_data = {
'username': username,
'email': email,
'password': password,
'name': name,
'role': role,
'org_id': org_id
}
if self.auth_manager.create_user(user_data):
return {
signup_status: "<div class='status-success'>β
Account created successfully! Please login.</div>"
}
else:
return {
signup_status: "<div class='status-error'>β Failed to create account. Username or email may already exist.</div>"
}
except Exception as e:
return {
signup_status: f"<div class='status-error'>β Error: {str(e)}</div>"
}
def handle_analysis(patient_name, patient_age, patient_gender, wound_location, wound_duration,
pain_level, moisture_level, infection_signs, diabetic_status, previous_treatment,
medical_history, medications, allergies, additional_notes, wound_image):
try:
if not wound_image:
return "<div class='status-error'>β Please upload a wound image for analysis.</div>"
# Show loading state
loading_html = """
<div style="text-align:center; padding: 30px;">
<div style="display:inline-block; border:4px solid #3182ce; border-radius:50%; border-top-color:transparent; width:40px; height:40px; animation:spin 1s linear infinite;"></div>
<p style="margin-top:15px; color:#3182ce; font-weight:600;">Processing wound analysis...</p>
<style>@keyframes spin {0% {transform:rotate(0deg)} 100% {transform:rotate(360deg)}}</style>
</div>
"""
# 1. Construct questionnaire dictionary for AIProcessor
questionnaire_data = {
'user_id': self.current_user.get('id'),
'age': patient_age,
'diabetic': 'Yes' if diabetic_status != 'Non-diabetic' else 'No',
'allergies': allergies,
'date_of_injury': 'Unknown', # Not collected in this form
'professional_care': 'Yes', # Assumed since using professional interface
'oozing_bleeding': 'None', # Could be mapped from infection_signs
'infection': 'Yes' if infection_signs != 'None' else 'No',
'moisture': moisture_level,
# Additional fields for comprehensive analysis
'patient_name': patient_name,
'patient_gender': patient_gender,
'wound_location': wound_location,
'wound_duration': wound_duration,
'pain_level': pain_level,
'previous_treatment': previous_treatment,
'medical_history': medical_history,
'medications': medications,
'additional_notes': additional_notes
}
# 2. Save questionnaire in DB first
questionnaire_id = self.database_manager.save_questionnaire(questionnaire_data)
# 3. Run AI analysis using the AIProcessor class
try:
logging.info(f"Starting AI analysis for image: {wound_image}")
# Use the AIProcessor analyze_wound method
analysis_result = self.wound_analyzer.analyze_wound(wound_image, questionnaire_data)
if not analysis_result.get('success', False):
raise Exception(analysis_result.get('error', 'Analysis failed for unknown reason'))
# 4. Save AI analysis result to database
self.database_manager.save_analysis_result(questionnaire_id, analysis_result)
# 5. Format comprehensive analysis results with all images
formatted_analysis = self._format_comprehensive_analysis_results(
analysis_result, wound_image, questionnaire_data
)
return formatted_analysis
except Exception as analysis_error:
logging.error(f"AI analysis error: {analysis_error}")
return f"""
<div class='status-error' style='padding: 20px; background: #ffeeee; border-left: 5px solid #ff5555; margin: 20px 0;'>
<h3>β Analysis Error</h3>
<p>There was an error analyzing the wound image:</p>
<pre style='background: #f5f5f5; padding: 10px; border-radius: 5px;'>{str(analysis_error)}</pre>
<p>Please try again with a different image or contact support.</p>
</div>
"""
except Exception as e:
logging.error(f"Analysis handler error: {e}")
return f"<div class='status-error'>β Analysis failed: {str(e)}</div>"
def handle_logout():
self.current_user = {}
return {
auth_panel: gr.update(visible=True),
practitioner_panel: gr.update(visible=False)
}
def toggle_role_fields(role):
if role == "organization":
return {
org_fields: gr.update(visible=True),
prac_fields: gr.update(visible=False)
}
else:
return {
org_fields: gr.update(visible=False),
prac_fields: gr.update(visible=True)
}
def load_patient_history():
try:
user_id = self.current_user.get('id')
if not user_id:
return "<div class='status-error'>β Please login first.</div>"
history_data = self.patient_history_manager.get_user_patient_history(user_id)
formatted_history = self.patient_history_manager.format_history_for_display(history_data)
return formatted_history
except Exception as e:
logging.error(f"Error loading patient history: {e}")
return f"<div class='status-error'>β Error loading history: {str(e)}</div>"
def search_specific_patient(patient_name):
try:
user_id = self.current_user.get('id')
if not user_id:
return "<div class='status-error'>β Please login first.</div>"
if not patient_name.strip():
return "<div class='status-warning'>β οΈ Please enter a patient name to search.</div>"
patient_data = self.patient_history_manager.search_patient_by_name(user_id, patient_name.strip())
if patient_data:
formatted_data = self.patient_history_manager.format_patient_data_for_display(patient_data)
return formatted_data
else:
return f"<div class='status-warning'>β οΈ No records found for patient: {patient_name}</div>"
except Exception as e:
logging.error(f"Error searching patient: {e}")
return f"<div class='status-error'>β Error searching patient: {str(e)}</div>"
# Bind event handlers
login_btn.click(
handle_login,
inputs=[login_username, login_password],
outputs=[auth_panel, practitioner_panel, login_status]
)
signup_btn.click(
handle_signup,
inputs=[signup_username, signup_email, signup_password, signup_name, signup_role,
org_name, phone, country_code, department, location, organization_dropdown],
outputs=[signup_status]
)
signup_role.change(
toggle_role_fields,
inputs=[signup_role],
outputs=[org_fields, prac_fields]
)
analyze_btn.click(
handle_analysis,
inputs=[patient_name, patient_age, patient_gender, wound_location, wound_duration,
pain_level, moisture_level, infection_signs, diabetic_status, previous_treatment,
medical_history, medications, allergies, additional_notes, wound_image],
outputs=[analysis_output]
)
logout_btn_prac.click(
handle_logout,
outputs=[auth_panel, practitioner_panel]
)
history_btn.click(
load_patient_history,
outputs=[patient_history_output]
)
search_patient_btn.click(
search_specific_patient,
inputs=[search_patient_name],
outputs=[specific_patient_output]
)
return app
def _format_comprehensive_analysis_results(self, analysis_result, image_url=None, questionnaire_data=None):
"""Format comprehensive analysis results with all visualization images from AIProcessor."""
try:
# Extract the core analysis results from AIProcessor
success = analysis_result.get('success', False)
if not success:
error_msg = analysis_result.get('error', 'Unknown error')
return f"<div class='status-error'>β Analysis failed: {error_msg}</div>"
visual_analysis = analysis_result.get('visual_analysis', {})
report = analysis_result.get('report', '')
saved_image_path = analysis_result.get('saved_image_path', '')
# Extract wound metrics
wound_type = visual_analysis.get('wound_type', 'Unknown')
length_cm = visual_analysis.get('length_cm', 0)
breadth_cm = visual_analysis.get('breadth_cm', 0)
area_cm2 = visual_analysis.get('surface_area_cm2', 0)
detection_confidence = visual_analysis.get('detection_confidence', 0)
# Get image paths for visualizations
detection_image_path = visual_analysis.get('detection_image_path', '')
segmentation_image_path = visual_analysis.get('segmentation_image_path', '')
original_image_path = visual_analysis.get('original_image_path', '')
# Convert images to base64 for embedding
original_image_base64 = None
detection_image_base64 = None
segmentation_image_base64 = None
# Original uploaded image
if image_url and os.path.exists(image_url):
original_image_base64 = self.image_to_base64(image_url)
elif original_image_path and os.path.exists(original_image_path):
original_image_base64 = self.image_to_base64(original_image_path)
elif saved_image_path and os.path.exists(saved_image_path):
original_image_base64 = self.image_to_base64(saved_image_path)
# Detection visualization
if detection_image_path and os.path.exists(detection_image_path):
detection_image_base64 = self.image_to_base64(detection_image_path)
# Segmentation visualization
if segmentation_image_path and os.path.exists(segmentation_image_path):
segmentation_image_base64 = self.image_to_base64(segmentation_image_path)
# Generate risk assessment from questionnaire data
risk_assessment = self._generate_risk_assessment(questionnaire_data)
risk_level = risk_assessment['risk_level']
risk_score = risk_assessment['risk_score']
risk_factors = risk_assessment['risk_factors']
# Set risk class for styling
risk_class = "low"
if risk_level.lower() == "moderate":
risk_class = "moderate"
elif risk_level.lower() == "high":
risk_class = "high"
# Format risk factors
risk_factors_html = "<ul>" + "".join(f"<li>{factor}</li>" for factor in risk_factors) + "</ul>" if risk_factors else "<p>No specific risk factors identified.</p>"
# Create image gallery
image_gallery_html = ""
if original_image_base64 or detection_image_base64 or segmentation_image_base64:
image_gallery_html = '<div class="image-gallery">'
if original_image_base64:
image_gallery_html += f'''
<div class="image-item">
<img src="{original_image_base64}" alt="Original Wound Image">
<h4>πΈ Original Wound Image</h4>
<p>Uploaded image for analysis</p>
</div>
'''
if detection_image_base64:
image_gallery_html += f'''
<div class="image-item">
<img src="{detection_image_base64}" alt="Wound Detection">
<h4>π― Wound Detection</h4>
<p>AI-detected wound boundaries with {detection_confidence:.1%} confidence</p>
</div>
'''
if segmentation_image_base64:
image_gallery_html += f'''
<div class="image-item">
<img src="{segmentation_image_base64}" alt="Wound Segmentation">
<h4>π Wound Segmentation</h4>
<p>Detailed wound area measurement and analysis</p>
</div>
'''
image_gallery_html += '</div>'
# Convert markdown report to HTML
report_html = ""
if report:
report_html = self.markdown_to_html(report)
# Final comprehensive HTML output
html_output = f"""
<div style="max-width: 1200px; margin: 0 auto; background: white; border-radius: 16px; box-shadow: 0 8px 32px rgba(0,0,0,0.1); overflow: hidden;">
<div style="background: linear-gradient(135deg, #3182ce 0%, #2c5aa0 100%); color: white; padding: 40px; text-align: center;">
<h1 style="margin: 0; font-size: 32px; font-weight: 700;">π¬ SmartHeal AI Comprehensive Analysis</h1>
<p style="margin: 15px 0 0 0; opacity: 0.9; font-size: 18px;">Advanced Computer Vision & Medical AI Assessment</p>
<div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px; margin-top: 20px;">
<p style="margin: 0; font-size: 16px;"><strong>Patient:</strong> {questionnaire_data.get('patient_name', 'Unknown')} | <strong>Analysis Date:</strong> {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}</p>
</div>
</div>
<div style="padding: 40px;">
<div class="status-success" style="margin-bottom: 30px;">
<strong>β
Analysis Status:</strong> Analysis completed successfully with comprehensive wound assessment
</div>
<!-- Image Gallery Section -->
<div style="margin-bottom: 40px;">
<h2 style="color: #2d3748; font-size: 24px; margin-bottom: 20px; border-bottom: 2px solid #e53e3e; padding-bottom: 10px;">πΌοΈ Visual Analysis Gallery</h2>
{image_gallery_html}
</div>
<!-- Wound Detection & Classification -->
<div style="background: #f8f9fa; padding: 30px; border-radius: 12px; margin-bottom: 30px;">
<h2 style="color: #2d3748; margin-top: 0;">π Wound Detection & Classification</h2>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px; margin: 20px 0;">
<div style="background: white; padding: 20px; border-radius: 8px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
<h3 style="color: #3182ce; margin: 0 0 10px 0;">Wound Type</h3>
<p style="font-weight: 600; font-size: 18px; color: #2d3748; margin: 0;">{wound_type}</p>
</div>
<div style="background: white; padding: 20px; border-radius: 8px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
<h3 style="color: #3182ce; margin: 0 0 10px 0;">Detection Confidence</h3>
<p style="font-weight: 600; font-size: 18px; color: #2d3748; margin: 0;">{detection_confidence:.1%}</p>
</div>
<div style="background: white; padding: 20px; border-radius: 8px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
<h3 style="color: #3182ce; margin: 0 0 10px 0;">Location</h3>
<p style="font-weight: 600; font-size: 18px; color: #2d3748; margin: 0;">{questionnaire_data.get('wound_location', 'Not specified')}</p>
</div>
</div>
</div>
<!-- Wound Measurements -->
<div style="background: #e7f5ff; padding: 30px; border-radius: 12px; margin-bottom: 30px;">
<h2 style="color: #2d3748; margin-top: 0;">π Wound Measurements</h2>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 20px; margin: 20px 0;">
<div style="background: white; padding: 20px; border-radius: 8px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
<h3 style="color: #e53e3e; margin: 0 0 10px 0;">Length</h3>
<p style="font-weight: 700; font-size: 24px; color: #2d3748; margin: 0;">{length_cm:.2f} cm</p>
</div>
<div style="background: white; padding: 20px; border-radius: 8px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
<h3 style="color: #e53e3e; margin: 0 0 10px 0;">Width</h3>
<p style="font-weight: 700; font-size: 24px; color: #2d3748; margin: 0;">{breadth_cm:.2f} cm</p>
</div>
<div style="background: white; padding: 20px; border-radius: 8px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
<h3 style="color: #e53e3e; margin: 0 0 10px 0;">Surface Area</h3>
<p style="font-weight: 700; font-size: 24px; color: #2d3748; margin: 0;">{area_cm2:.2f} cmΒ²</p>
</div>
</div>
</div>
<!-- Risk Assessment -->
<div style="background: #fff4e6; padding: 30px; border-radius: 12px; margin-bottom: 30px;">
<h2 style="color: #2d3748; margin-top: 0;">β οΈ Risk Assessment</h2>
<div style="display: flex; align-items: center; margin: 20px 0; flex-wrap: wrap;">
<div style="background: {'#d4edda' if risk_class == 'low' else '#fff3cd' if risk_class == 'moderate' else '#f8d7da'};
color: {'#155724' if risk_class == 'low' else '#856404' if risk_class == 'moderate' else '#721c24'};
padding: 15px 30px;
border-radius: 30px;
font-weight: 700;
font-size: 20px;
text-transform: uppercase;
letter-spacing: 1px;
margin-right: 20px;
margin-bottom: 10px;">
{risk_level} RISK
</div>
<div style="font-size: 18px; color: #2d3748;">
<strong>Risk Score:</strong> {risk_score}/10
</div>
</div>
<div style="background: white; padding: 25px; border-radius: 8px; margin: 15px 0; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">
<h3 style="margin-top: 0; color: #2d3748;">Identified Risk Factors:</h3>
{risk_factors_html}
</div>
</div>
<!-- Patient Information Summary -->
<div style="background: #f0f8f0; padding: 30px; border-radius: 12px; margin-bottom: 30px;">
<h2 style="color: #2d3748; margin-top: 0;">π€ Patient Information Summary</h2>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 15px;">
<div><strong>Age:</strong> {questionnaire_data.get('age', 'Not specified')} years</div>
<div><strong>Gender:</strong> {questionnaire_data.get('patient_gender', 'Not specified')}</div>
<div><strong>Diabetic Status:</strong> {questionnaire_data.get('diabetic', 'Unknown')}</div>
<div><strong>Pain Level:</strong> {questionnaire_data.get('pain_level', 'Not assessed')}/10</div>
<div><strong>Wound Duration:</strong> {questionnaire_data.get('wound_duration', 'Not specified')}</div>
<div><strong>Moisture Level:</strong> {questionnaire_data.get('moisture', 'Not assessed')}</div>
</div>
{f"<div style='margin-top: 20px;'><strong>Medical History:</strong> {questionnaire_data.get('medical_history', 'None provided')}</div>" if questionnaire_data.get('medical_history') else ""}
{f"<div style='margin-top: 10px;'><strong>Current Medications:</strong> {questionnaire_data.get('medications', 'None listed')}</div>" if questionnaire_data.get('medications') else ""}
{f"<div style='margin-top: 10px;'><strong>Known Allergies:</strong> {questionnaire_data.get('allergies', 'None listed')}</div>" if questionnaire_data.get('allergies') else ""}
</div>
<!-- AI Generated Report -->
{f'<div style="background: #f8f9fa; padding: 30px; border-radius: 12px; margin-bottom: 30px;"><h2 style="color: #2d3748; margin-top: 0;">π€ AI-Generated Clinical Report</h2><div style="background: white; padding: 25px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.05);">{report_html}</div></div>' if report_html else ''}
<!-- Important Disclaimers -->
<div style="background: #fff5f5; border: 2px solid #feb2b2; padding: 25px; border-radius: 12px; margin: 30px 0;">
<h3 style="color: #c53030; margin-top: 0;">β οΈ Important Medical Disclaimers</h3>
<ul style="color: #742a2a; line-height: 1.6;">
<li><strong>Not a Medical Diagnosis:</strong> This AI analysis is for informational purposes only and does not constitute medical advice, diagnosis, or treatment.</li>
<li><strong>Professional Consultation Required:</strong> Always consult with qualified healthcare professionals for proper clinical assessment and treatment decisions.</li>
<li><strong>Measurement Accuracy:</strong> All measurements are estimates based on computer vision algorithms and should be verified with clinical tools.</li>
<li><strong>Risk Assessment Limitations:</strong> Risk factors are based on provided information and may not reflect the complete clinical picture.</li>
</ul>
</div>
<!-- Footer -->
<div style="text-align: center; padding: 30px 0; border-top: 2px solid #e2e8f0; margin-top: 30px;">
<p style="color: #6c757d; font-style: italic; font-size: 16px; margin: 0;">
π₯ Analysis completed by <strong>SmartHeal AI</strong> - Advanced Wound Care Assistant<br>
<small>Report generated on {datetime.now().strftime('%B %d, %Y at %I:%M %p')}</small>
</p>
</div>
</div>
</div>
"""
return html_output
except Exception as e:
logging.error(f"Error formatting comprehensive results: {e}")
return f"<div class='status-error'>β Error displaying results: {str(e)}</div>"
def _generate_risk_assessment(self, questionnaire_data):
"""Generate risk assessment based on questionnaire data"""
if not questionnaire_data:
return {'risk_level': 'Unknown', 'risk_score': 0, 'risk_factors': []}
risk_factors = []
risk_score = 0
try:
# Age assessment
age = questionnaire_data.get('age', 0)
if isinstance(age, str):
try:
age = int(age)
except ValueError:
age = 0
if age > 65:
risk_factors.append("Advanced age (>65 years)")
risk_score += 2
elif age > 50:
risk_factors.append("Older adult (50-65 years)")
risk_score += 1
# Diabetic status
diabetic_status = str(questionnaire_data.get('diabetic', '')).lower()
if 'yes' in diabetic_status:
risk_factors.append("Diabetes mellitus")
risk_score += 3
# Infection signs
infection = str(questionnaire_data.get('infection', '')).lower()
if 'yes' in infection:
risk_factors.append("Signs of infection present")
risk_score += 3
# Pain level
pain_level = questionnaire_data.get('pain_level', 0)
if isinstance(pain_level, str):
try:
pain_level = float(pain_level)
except ValueError:
pain_level = 0
if pain_level >= 7:
risk_factors.append("High pain level (β₯7/10)")
risk_score += 2
elif pain_level >= 5:
risk_factors.append("Moderate pain level (5-6/10)")
risk_score += 1
# Wound duration
duration = str(questionnaire_data.get('wound_duration', '')).lower()
if any(term in duration for term in ['month', 'months', 'year', 'years']):
risk_factors.append("Chronic wound (>4 weeks)")
risk_score += 3
# Moisture level
moisture = str(questionnaire_data.get('moisture', '')).lower()
if any(term in moisture for term in ['wet', 'saturated']):
risk_factors.append("Excessive wound exudate")
risk_score += 1
# Medical history analysis
medical_history = str(questionnaire_data.get('medical_history', '')).lower()
if any(term in medical_history for term in ['vascular', 'circulation', 'heart']):
risk_factors.append("Cardiovascular disease")
risk_score += 2
if any(term in medical_history for term in ['immune', 'cancer', 'steroid']):
risk_factors.append("Immune system compromise")
risk_score += 2
if any(term in medical_history for term in ['smoking', 'tobacco']):
risk_factors.append("Smoking history")
risk_score += 2
# Determine risk level
if risk_score >= 8:
risk_level = "Very High"
elif risk_score >= 6:
risk_level = "High"
elif risk_score >= 3:
risk_level = "Moderate"
else:
risk_level = "Low"
return {
'risk_score': risk_score,
'risk_level': risk_level,
'risk_factors': risk_factors
}
except Exception as e:
logging.error(f"Risk assessment error: {e}")
return {
'risk_score': 0,
'risk_level': 'Unknown',
'risk_factors': ['Unable to assess risk due to data processing error']
} |