File size: 81,815 Bytes
b2e192e 3776079 b2e192e fe88653 3776079 c8da835 3776079 fe88653 3776079 b2e192e c8da835 b2e192e fe88653 5190a0b b2e192e fe88653 c8da835 5190a0b fe88653 5190a0b fe88653 c8da835 fe88653 c8da835 fe88653 5190a0b fe88653 b2e192e 5190a0b fe88653 5190a0b c8da835 5190a0b fe88653 5190a0b fe88653 3776079 5190a0b fe88653 3776079 5190a0b fe88653 3776079 5190a0b fe88653 b2e192e c8da835 fe88653 5190a0b fe88653 3776079 c8da835 3776079 fe88653 5190a0b c8da835 b2e192e 5190a0b fe88653 c8da835 5190a0b fe88653 5190a0b fe88653 c8da835 5190a0b fe88653 5190a0b fe88653 5190a0b dc2c50b fe88653 c8da835 b2e192e 5190a0b fe88653 b2e192e fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 2923fbe fe88653 b2e192e fe88653 c8da835 78f1ee5 c8da835 78f1ee5 c8da835 78f1ee5 b2e192e fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 78f1ee5 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 b2e192e 3776079 b2e192e 3776079 b2e192e 3776079 b2e192e 3776079 b2e192e 3776079 b2e192e 3776079 b2e192e 3776079 b2e192e 3776079 b2e192e 3776079 b2e192e 3776079 b2e192e 3776079 c8da835 78f1ee5 c8da835 78f1ee5 c8da835 7496748 c8da835 2923fbe c8da835 dc2c50b c8da835 dc2c50b c8da835 5190a0b fe88653 c8da835 fe88653 c8da835 5190a0b c8da835 fe88653 c8da835 fe88653 5190a0b 3776079 b2e192e c8da835 fe88653 b2e192e c8da835 fe88653 c8da835 fe88653 b2e192e c8da835 fe88653 c8da835 fe88653 c8da835 b2e192e fe88653 5190a0b fe88653 b2e192e 3776079 fe88653 3776079 fe88653 3776079 5190a0b b2e192e 5190a0b b2e192e c8da835 5190a0b b2e192e c8da835 5190a0b b2e192e 3776079 fe88653 3776079 fe88653 3776079 fe88653 3776079 fe88653 3776079 b2e192e fe88653 3776079 b2e192e fe88653 3776079 b2e192e 3776079 b2e192e 3776079 b2e192e 3776079 b2e192e 3776079 2923fbe fe88653 2923fbe 5190a0b c8da835 fe88653 3776079 c8da835 3776079 c8da835 3776079 5190a0b 3776079 fe88653 3776079 fe88653 3776079 c8da835 3776079 5190a0b 3776079 5190a0b b2e192e fe88653 5190a0b b2e192e c8da835 fe88653 b2e192e c8da835 fe88653 b2e192e fe88653 b2e192e fe88653 b2e192e fe88653 b2e192e fe88653 78f1ee5 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 c8da835 fe88653 5190a0b fe88653 5190a0b 78f1ee5 c8da835 fe88653 78f1ee5 c8da835 fe88653 78f1ee5 fe88653 5190a0b fe88653 5190a0b fe88653 5190a0b c8da835 5190a0b c8da835 fe88653 3776079 fe88653 3776079 fe88653 7496748 fe88653 7496748 fe88653 5190a0b fe88653 5190a0b fe88653 5190a0b fe88653 c8da835 fe88653 5190a0b fe88653 5190a0b fe88653 5190a0b b2e192e 39bc663 |
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 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 |
import streamlit as st
import pandas as pd
import numpy as np
import joblib
import pickle
from PIL import Image
import io
import os
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime
import base64
from fpdf import FPDF
import tempfile
# Set page config first
st.set_page_config(
page_title="SehatAI - Smart Healthcare Triage",
page_icon="🏥",
layout="wide",
initial_sidebar_state="collapsed"
)
# Professional CSS Styling with Pakistan theme colors
def local_css():
st.markdown("""
<style>
.main-header {
font-size: 3.5rem;
color: #1f77b4;
text-align: center;
margin-bottom: 0.5rem;
font-weight: 800;
background: linear-gradient(135deg, #00401A, #00612A, #008000);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
text-shadow: 0px 4px 8px rgba(0,0,0,0.2);
font-family: 'Arial', sans-serif;
}
.quote-section {
background: linear-gradient(135deg, #00401A 0%, #00612A 100%);
color: white;
padding: 25px;
border-radius: 20px;
text-align: center;
margin: 20px 0;
box-shadow: 0 8px 25px rgba(0,0,0,0.15);
border: 3px solid #008000;
}
.quote-text {
font-size: 1.4rem;
font-weight: 600;
margin-bottom: 10px;
font-style: italic;
}
.quote-author {
font-size: 1.1rem;
opacity: 0.9;
}
.section-container {
background: white;
padding: 30px;
border-radius: 20px;
box-shadow: 0 8px 25px rgba(0,0,0,0.1);
margin-bottom: 30px;
border: 2px solid #e0e0e0;
transition: all 0.3s ease;
}
.section-container:hover {
box-shadow: 0 12px 35px rgba(0,0,0,0.15);
transform: translateY(-2px);
}
.metric-card {
background: linear-gradient(135deg, #00401A 0%, #00612A 100%);
color: white;
padding: 25px;
border-radius: 15px;
text-align: center;
box-shadow: 0 6px 15px rgba(0,0,0,0.2);
transition: all 0.3s ease;
}
.metric-card:hover {
transform: translateY(-3px);
box-shadow: 0 10px 25px rgba(0,0,0,0.3);
}
.risk-high {
background: linear-gradient(135deg, #ff6b6b, #ee5a52);
color: white;
padding: 25px;
border-radius: 15px;
border-left: 8px solid #dc3545;
box-shadow: 0 6px 15px rgba(220,53,69,0.4);
}
.risk-medium {
background: linear-gradient(135deg, #ffd93d, #ffcd3c);
color: #333;
padding: 25px;
border-radius: 15px;
border-left: 8px solid #ffc107;
box-shadow: 0 6px 15px rgba(255,193,7,0.4);
}
.risk-low {
background: linear-gradient(135deg, #6bcf7f, #28a745);
color: white;
padding: 25px;
border-radius: 15px;
border-left: 8px solid #20c997;
box-shadow: 0 6px 15px rgba(40,167,69,0.4);
}
.priority-box {
border: 4px solid #00612A;
padding: 30px;
border-radius: 20px;
margin: 20px 0;
background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
box-shadow: 0 8px 25px rgba(0,0,0,0.15);
}
.stButton button {
width: 100%;
background: linear-gradient(45deg, #00401A, #00612A);
color: white;
font-weight: bold;
border: none;
padding: 16px 32px;
border-radius: 12px;
font-size: 1.2rem;
transition: all 0.3s ease;
box-shadow: 0 6px 15px rgba(0,64,26,0.4);
}
.stButton button:hover {
transform: translateY(-3px);
box-shadow: 0 10px 25px rgba(0,64,26,0.5);
background: linear-gradient(45deg, #00612A, #00401A);
}
.chat-message {
padding: 15px;
border-radius: 15px;
margin: 10px 0;
border: 2px solid #e0e0e0;
}
.user-message {
background: linear-gradient(135deg, #00401A, #00612A);
color: white;
margin-left: 20%;
text-align: right;
}
.bot-message {
background: linear-gradient(135deg, #f8f9fa, #e9ecef);
color: #333;
margin-right: 20%;
}
.language-selector {
position: absolute;
top: 20px;
right: 20px;
z-index: 1000;
}
.pakistan-flag {
background: linear-gradient(135deg, #00401A, #00612A, #FFFFFF);
padding: 5px 15px;
border-radius: 20px;
color: white;
font-weight: bold;
margin: 0 10px;
}
</style>
""", unsafe_allow_html=True)
# Initialize session state
def init_session_state():
if 'patient_data' not in st.session_state:
st.session_state.patient_data = {}
if 'risk_scores' not in st.session_state:
st.session_state.risk_scores = {}
if 'assessment_history' not in st.session_state:
st.session_state.assessment_history = []
if 'chat_history' not in st.session_state:
st.session_state.chat_history = []
if 'current_language' not in st.session_state:
st.session_state.current_language = 'English'
# Healthcare quotes database
HEALTHCARE_QUOTES = [
{
'english': "Health is the crown on the well person's head that only the ill can see.",
'urdu': "صحت ایک تاج ہے جو تندرست انسان کے سر پر ہوتا ہے جسے صرف بیمار ہی دیکھ سکتے ہیں۔",
'author': "Robin Sharma"
},
{
'english': "The first wealth is health. Take care of your body, it's the only place you have to live.",
'urdu': "پہلی دولت صحت ہے۔ اپنے جسم کا خیال رکھیں، یہ وہ واحد جگہ ہے جہاں آپ کو رہنا ہے۔",
'author': "Ralph Waldo Emerson"
},
{
'english': "A healthy outside starts from the inside. Prevention is better than cure.",
'urdu': "ایک صحت مند باہر کی طرف اندر سے شروع ہوتی ہے۔ بچاؤ علاج سے بہتر ہے۔",
'author': "Robert Urich"
},
{
'english': "Your body hears everything your mind says. Stay positive for better health.",
'urdu': "آپ کا جسم وہ سب کچھ سنتا ہے جو آپ کا دماغ کہتا ہے۔ بہتر صحت کے لیے مثبت رہیں۔",
'author': "Naomi Judd"
},
{
'english': "The greatest of follies is to sacrifice health for any other kind of happiness.",
'urdu': "سب سے بڑی بیوقوفی صحت کو کسی دوسری قسم کی خوشی کے لیے قربان کرنا ہے۔",
'author': "Arthur Schopenhauer"
}
]
class HealthcareChatbot:
def __init__(self):
self.medical_knowledge_base = {
'heart_disease': {
'symptoms': ["Chest pain or discomfort", "Shortness of breath", "Pain in arms, neck, jaw", "Nausea", "Fatigue", "Dizziness"],
'risk_factors': ["High blood pressure", "High cholesterol", "Smoking", "Diabetes", "Obesity", "Family history", "Physical inactivity"],
'prevention': ["Healthy diet low in saturated fats", "Regular exercise 30 mins daily", "No smoking", "Weight management", "Stress management", "Regular check-ups"],
'emergency_signs': ["Severe chest pain", "Difficulty breathing", "Fainting", "Rapid heartbeat", "Pain spreading to arms/shoulders"]
},
'diabetes': {
'symptoms': ["Increased thirst and hunger", "Frequent urination", "Fatigue", "Blurred vision", "Slow healing wounds", "Unexplained weight loss"],
'risk_factors': ["Family history", "Overweight (BMI > 25)", "High blood pressure", "Physical inactivity", "Age over 45", "Gestational diabetes history"],
'prevention': ["Balanced diet with controlled carbs", "Regular physical activity", "Weight management", "Blood sugar monitoring", "Regular health screenings"],
'emergency_signs': ["Blood sugar >300 mg/dL or <70 mg/dL", "Confusion or disorientation", "Fruity breath odor", "Rapid breathing", "Loss of consciousness"]
},
'hypertension': {
'symptoms': ["Headaches", "Dizziness", "Blurred vision", "Shortness of breath", "Chest pain", "Nosebleeds"],
'risk_factors': ["Family history", "Age over 65", "Obesity", "High salt intake", "Stress", "Alcohol consumption", "Smoking"],
'prevention': ["DASH diet (low sodium)", "Regular aerobic exercise", "Weight management", "Stress reduction", "Limit alcohol", "No smoking"],
'emergency_signs': ["Severe headache", "Chest pain", "Difficulty breathing", "Vision changes", "Confusion", "Seizures"]
},
'general_health': {
'nutrition': ["Eat 5-9 servings of fruits/vegetables daily", "Choose whole grains over refined", "Include lean proteins", "Stay hydrated (8-10 glasses water)", "Limit processed foods and sugar"],
'exercise': ["150 mins moderate exercise weekly", "Strength training 2x weekly", "Stay active throughout day", "Include flexibility exercises", "Get adequate rest between workouts"],
'lifestyle': ["7-9 hours quality sleep nightly", "Stress management techniques", "No smoking", "Limit alcohol to 1-2 drinks/day", "Regular health check-ups"],
'prevention': ["Annual physical exams", "Vaccinations up to date", "Regular hand washing", "Sun protection", "Mental health care"]
}
}
def get_response(self, user_input, language='English'):
user_input = user_input.lower().strip()
# Greeting patterns
if any(word in user_input for word in ['hello', 'hi', 'hey', 'salam', 'السلام علیکم']):
return self._format_greeting_response(language)
# Heart disease related queries
if any(word in user_input for word in ['heart', 'cardiac', 'chest pain', 'cholesterol', 'دل', 'سینے میں درد']):
return self._format_heart_response(language)
# Diabetes related queries
elif any(word in user_input for word in ['diabetes', 'sugar', 'glucose', 'insulin', 'ذیابیطس', 'شوگر']):
return self._format_diabetes_response(language)
# Hypertension related queries
elif any(word in user_input for word in ['blood pressure', 'hypertension', 'bp', 'بلڈ پریشر', 'ہائی بلڈ پریشر']):
return self._format_hypertension_response(language)
# Nutrition and diet
elif any(word in user_input for word in ['diet', 'nutrition', 'food', 'eating', 'غذا', 'کھانا']):
return self._format_nutrition_response(language)
# Exercise and fitness
elif any(word in user_input for word in ['exercise', 'workout', 'fitness', 'gym', 'ورزش', 'جم']):
return self._format_exercise_response(language)
# Symptoms assessment
elif any(word in user_input for word in ['symptom', 'pain', 'fever', 'headache', 'علامت', 'درد']):
return self._format_symptoms_response(language)
# Medication queries
elif any(word in user_input for word in ['medicine', 'medication', 'drug', 'treatment', 'دوا', 'علاج']):
return self._format_medication_response(language)
# Emergency situations
elif any(word in user_input for word in ['emergency', 'urgent', 'help', 'ہنگامی', 'فوری']):
return self._format_emergency_response(language)
# General health queries
elif any(word in user_input for word in ['health', 'wellness', 'prevention', 'صحت', 'تندرستی']):
return self._format_general_health_response(language)
# Default response for unknown queries
else:
return self._format_default_response(language)
def _format_greeting_response(self, language):
if language == 'English':
return """
**🤖 Welcome to SehatAI Health Assistant!**
I'm here to help you with:
• Heart health and cardiovascular diseases
• Diabetes and blood sugar management
• Blood pressure and hypertension
• Nutrition and diet advice
• Exercise and fitness guidance
• Symptom assessment
• General health and wellness
Please ask me specific health-related questions, and I'll provide detailed, helpful information.
*Note: I'm an AI assistant. For serious medical concerns, always consult a qualified healthcare professional.*
"""
else:
return """
**🤖 سیحت اے آئی ہیلتھ اسسٹنٹ میں خوش آمدید!**
میں آپ کی مدد کے لیے یہاں ہوں:
• دل کی صحت اور قلبی امراض
• ذیابیطس اور بلڈ شوگر مینجمنٹ
• بلڈ پریشر اور ہائی بلڈ پریشر
• غذائیت اور غذا کے مشورے
• ورزش اور فٹنس گائیڈنس
• علامات کی تشخیص
• عام صحت اور تندرستی
براہ کرم مجھ سے مخصوص صحت سے متعلق سوالات پوچھیں، اور میں تفصیلی، مددگار معلومات فراہم کروں گا۔
*نوٹ: میں ایک AI اسسٹنٹ ہوں۔ سنگین طبی مسائل کے لیے، ہمیشہ کوالیفائیڈ ہیلتھ کیئر پروفیشنل سے مشورہ کریں۔*
"""
def _format_heart_response(self, language):
knowledge = self.medical_knowledge_base['heart_disease']
if language == 'English':
return f"""
**❤️ Comprehensive Heart Health Information**
**🚨 Common Symptoms:**
{chr(10).join(['• ' + symptom for symptom in knowledge['symptoms']])}
**⚠️ Risk Factors:**
{chr(10).join(['• ' + factor for factor in knowledge['risk_factors']])}
**🛡️ Prevention Strategies:**
{chr(10).join(['• ' + tip for tip in knowledge['prevention']])}
**🚑 Emergency Warning Signs (Seek Immediate Care):**
{chr(10).join(['• ' + sign for sign in knowledge['emergency_signs']])}
**📊 Recommended Monitoring:**
• Regular blood pressure checks
• Cholesterol levels annually if high risk
• ECG if symptoms present
• Stress test if recommended by doctor
*🔬 Clinical Note: Early detection saves lives. Regular check-ups are crucial for heart health.*
"""
else:
return f"""
**❤️ دل کی صحت کی جامع معلومات**
**🚨 عام علامات:**
{chr(10).join(['• ' + symptom for symptom in ['سینے میں درد یا بے چینی', 'سانس لینے میں دشواری', 'بازوؤں، گردن، جبڑے میں درد', 'متلی', 'تھکاوٹ', 'چکر آنا']])}
**⚠️ خطرے کے عوامل:**
{chr(10).join(['• ' + factor for factor in ['ہائی بلڈ پریشر', 'ہائی کولیسٹرول', 'سگریٹ نوشی', 'ذیابیطس', 'موٹاپا', 'خاندانی تاریخ', 'جسمانی غیر فعالیت']])}
**🛡️ بچاؤ کی حکمت عملی:**
{chr(10).join(['• ' + tip for tip in ['سیر شدہ چکنائی سے پاک صحت مند غذا', 'روزانہ 30 منٹ باقاعدہ ورزش', 'سگریٹ نوشی سے پرہیز', 'وزن کا انتظام', 'تناؤ کا انتظام', 'باقاعدہ چیک اپ']])}
**🚑 ہنگامی انتباہی علامات (فوری علاج حاصل کریں):**
{chr(10).join(['• ' + sign for sign in ['شدید سینے میں درد', 'سانس لینے میں شدید دشواری', 'بیہوش ہونا', 'تیز دل کی دھڑکن', 'بازو/کندھوں میں پھیلنے والا درد']])}
**📊 تجویز کردہ نگرانی:**
• بلڈ پریشر کی باقاعدہ جانچ
• اگر خطرہ زیادہ ہو تو سالانہ کولیسٹرول کی سطح
• اگر علامات موجود ہوں تو ECG
• اگر ڈاکٹر تجویز کرے تو اسٹریس ٹیسٹ
*🔬 کلینیکل نوٹ: ابتدائی تشخیص جان بچاتی ہے۔ دل کی صحت کے لیے باقاعدہ چیک اپ بہت ضروری ہیں۔*
"""
def _format_diabetes_response(self, language):
knowledge = self.medical_knowledge_base['diabetes']
if language == 'English':
return f"""
**🩺 Comprehensive Diabetes Information**
**🚨 Common Symptoms:**
{chr(10).join(['• ' + symptom for symptom in knowledge['symptoms']])}
**⚠️ Risk Factors:**
{chr(10).join(['• ' + factor for factor in knowledge['risk_factors']])}
**🛡️ Prevention & Management:**
{chr(10).join(['• ' + tip for tip in knowledge['prevention']])}
**🚑 Emergency Signs (Seek Immediate Care):**
{chr(10).join(['• ' + sign for sign in knowledge['emergency_signs']])}
**📊 Monitoring Guidelines:**
• Fasting blood sugar: 80-130 mg/dL
• Post-meal blood sugar: <180 mg/dL
• HbA1c: <7.0% (quarterly if uncontrolled)
• Regular foot and eye examinations
*🔬 Clinical Note: Consistent monitoring and lifestyle management are key to diabetes control.*
"""
else:
return f"""
**🩺 ذیابیطس کی جامع معلومات**
**🚨 عام علامات:**
{chr(10).join(['• ' + symptom for symptom in ['زیادہ پیاس اور بھوک لگنا', 'بار بار پیشاب آنا', 'تھکاوٹ', 'دھندلا نظر آنا', 'زخموں کا دیر سے بھرنا', 'بے وجہ وزن میں کمی']])}
**⚠️ خطرے کے عوامل:**
{chr(10).join(['• ' + factor for factor in ['خاندانی تاریخ', 'وزن زیادہ ہونا (BMI > 25)', 'ہائی بلڈ پریشر', 'جسمانی غیر فعالیت', '45 سال سے زیادہ عمر', 'حمل کی ذیابیطس کی تاریخ']])}
**🛡️ بچاؤ اور انتظام:**
{chr(10).join(['• ' + tip for tip in ['کنٹرول کاربوہائیڈریٹ کے ساتھ متوازن غذا', 'باقاعدہ جسمانی سرگرمی', 'وزن کا انتظام', 'بلڈ شوگر مانیٹرنگ', 'باقاعدہ صحت کی اسکریننگ']])}
**🚑 ہنگامی علامات (فوری علاج حاصل کریں):**
{chr(10).join(['• ' + sign for sign in ['بلڈ شوگر >300 mg/dL یا <70 mg/dL', 'الجھن یا بے ترتیبی', 'پھل کی سی بو والی سانس', 'تیز سانس لینا', 'ہوش کا ضیاع']])}
**📊 نگرانی کے رہنما اصول:**
• فاسٹنگ بلڈ شوگر: 80-130 mg/dL
• کھانے کے بعد بلڈ شوگر: <180 mg/dL
• HbA1c: <7.0% (اگر کنٹرول نہ ہو تو سہ ماہی)
• پاؤں اور آنکھوں کا باقاعدہ معائنہ
*🔬 کلینیکل نوٹ: مستقل نگرانی اور طرز زندگی کا انتظام ذیابیطس کے کنٹرول کی کلید ہے۔*
"""
def _format_hypertension_response(self, language):
knowledge = self.medical_knowledge_base['hypertension']
if language == 'English':
return f"""
**💓 Comprehensive Blood Pressure Information**
**🚨 Common Symptoms:**
{chr(10).join(['• ' + symptom for symptom in knowledge['symptoms']])}
**⚠️ Risk Factors:**
{chr(10).join(['• ' + factor for factor in knowledge['risk_factors']])}
**🛡️ Prevention & Control:**
{chr(10).join(['• ' + tip for tip in knowledge['prevention']])}
**🚑 Hypertensive Emergency Signs:**
{chr(10).join(['• ' + sign for sign in knowledge['emergency_signs']])}
**📊 Blood Pressure Classification:**
• Normal: <120/80 mmHg
• Elevated: 120-129/<80 mmHg
• Stage 1 Hypertension: 130-139/80-89 mmHg
• Stage 2 Hypertension: ≥140/90 mmHg
*🔬 Clinical Note: Silent killer - often no symptoms. Regular monitoring is essential.*
"""
else:
return f"""
**💓 بلڈ پریشر کی جامع معلومات**
**🚨 عام علامات:**
{chr(10).join(['• ' + symptom for symptom in ['سر درد', 'چکر آنا', 'دھندلا نظر آنا', 'سانس لینے میں دشواری', 'سینے میں درد', 'ناک سے خون آنا']])}
**⚠️ خطرے کے عوامل:**
{chr(10).join(['• ' + factor for factor in ['خاندانی تاریخ', '65 سال سے زیادہ عمر', 'موٹاپا', 'زیادہ نمک کا استعمال', 'تناؤ', 'شراب کا استعمال', 'سگریٹ نوشی']])}
**🛡️ بچاؤ اور کنٹرول:**
{chr(10).join(['• ' + tip for tip in ['ڈیش ڈائٹ (کم سوڈیم)', 'باقاعدہ ایروبک ورزش', 'وزن کا انتظام', 'تناؤ میں کمی', 'شراب کو محدود کریں', 'سگریٹ نوشی سے پرہیز']])}
**🚑 ہائی بلڈ پریشر کی ہنگامی علامات:**
{chr(10).join(['• ' + sign for sign in ['شدید سر درد', 'سینے میں درد', 'سانس لینے میں دشواری', 'بینائی میں تبدیلی', 'الجھن', 'دورے']])}
**📊 بلڈ پریشر کی درجہ بندی:**
• نارمل: <120/80 mmHg
• بلند: 120-129/<80 mmHg
• اسٹیج 1 ہائی بلڈ پریشر: 130-139/80-89 mmHg
• اسٹیج 2 ہائی بلڈ پریشر: ≥140/90 mmHg
*🔬 کلینیکل نوٹ: خاموش قاتل - اکثر کوئی علامات نہیں ہوتیں۔ باقاعدہ نگرانی ضروری ہے۔*
"""
def _format_nutrition_response(self, language):
knowledge = self.medical_knowledge_base['general_health']
if language == 'English':
return f"""
**🍎 Comprehensive Nutrition Guide**
**🥦 Healthy Eating Principles:**
{chr(10).join(['• ' + tip for tip in knowledge['nutrition']])}
**🎯 Specific Recommendations:**
• **Heart Health**: Mediterranean diet, omega-3 rich foods
• **Diabetes**: Controlled carb intake, high fiber
• **Hypertension**: Low sodium (<2300mg/day), potassium-rich foods
• **Weight Management**: Calorie control, portion management
**🚫 Foods to Limit:**
• Processed and packaged foods
• Sugary drinks and sweets
• High sodium snacks
• Saturated and trans fats
**💡 Pakistani Dietary Adaptations:**
• Choose whole wheat chapati over refined flour
• Include lentils (daal) and legumes regularly
• Use healthy cooking oils (canola, olive)
• Limit ghee and butter usage
*Remember: Balanced nutrition is foundation of good health.*
"""
else:
return f"""
**🍎 غذائیت کی جامع گائیڈ**
**🥦 صحت مند کھانے کے اصول:**
{chr(10).join(['• ' + tip for tip in ['روزانہ 5-9 سرونگ پھل/سبزیاں کھائیں', 'ریفائنڈ کی بجائے سارا اناج منتخب کریں', 'لیان پروٹین شامل کریں', 'ہائیڈریٹ رہیں (8-10 گلاس پانی)', 'پراسیسڈ فوڈز اور چینی کو محدود کریں']])}
**🎯 مخصوص سفارشات:**
• **دل کی صحت**: بحیرہ روم کی غذا، اومیگا 3 سے بھرپور غذائیں
• **ذیابیطس**: کنٹرول کاربوہائیڈریٹ انٹیک، زیادہ فائبر
• **ہائی بلڈ پریشر**: کم سوڈیم (<2300mg/day)، پوٹاشیم سے بھرپور غذائیں
• **وزن کا انتظام**: کیلوری کنٹرول، حصے کا انتظام
**🚫 محدود کرنے والی غذائیں:**
• پراسیسڈ اور پیکجڈ فوڈز
• میٹھے مشروبات اور مٹھائیاں
• ہائی سوڈیم اسنیکس
• سیر شدہ اور ٹرانس فیٹس
**💡 پاکستانی غذائی موافقت:**
• ریفائنڈ آٹے کی بجائے whole wheat چپاتی منتخب کریں
• دالوں اور پھلیوں کو باقاعدہ شامل کریں
• صحت مند ککنگ آئلز (کینولا، زیتون) استعمال کریں
• گھی اور مکھن کے استعمال کو محدود کریں
*یاد رکھیں: متوازن غذائیت اچھی صحت کی بنیاد ہے۔*
"""
def _format_exercise_response(self, language):
knowledge = self.medical_knowledge_base['general_health']
if language == 'English':
return f"""
**💪 Comprehensive Exercise Guide**
**🏃♂️ Exercise Recommendations:**
{chr(10).join(['• ' + tip for tip in knowledge['exercise']])}
**🎯 Disease-Specific Exercise:**
• **Heart Health**: 30 mins moderate cardio daily
• **Diabetes**: Combination of cardio and strength training
• **Hypertension**: Regular aerobic exercise
• **Weight Management**: 300+ mins moderate exercise weekly
**🌞 Pakistani Climate Considerations:**
• Exercise in cooler morning/evening hours
• Stay hydrated with water and electrolytes
• Wear light, breathable clothing
• Listen to your body in hot weather
**🔄 Exercise Types:**
• **Cardio**: Walking, jogging, cycling, swimming
• **Strength**: Weight training, resistance bands
• **Flexibility**: Yoga, stretching
• **Balance**: Tai chi, balance exercises
*Important: Consult doctor before starting new exercise program.*
"""
else:
return f"""
**💪 ورزش کی جامع گائیڈ**
**🏃♂️ ورزش کی سفارشات:**
{chr(10).join(['• ' + tip for tip in ['ہفتے میں 150 منٹ اعتدال پسند ورزش', 'ہفتے میں 2 بار طاقت کی تربیت', 'پورے دن متحرک رہیں', 'لچک کی ورزشیں شامل کریں', 'ورک آؤٹس کے درمیان مناسب آرام حاصل کریں']])}
**🎯 بیماری کی مخصوص ورزش:**
• **دل کی صحت**: روزانہ 30 منٹ اعتدال پسند کارڈیو
• **ذیابیطس**: کارڈیو اور طاقت کی تربیت کا مجموعہ
• **ہائی بلڈ پریشر**: باقاعدہ ایروبک ورزش
• **وزن کا انتظام**: ہفتے میں 300+ منٹ اعتدال پسند ورزش
**🌞 پاکستانی آب و ہوا کے تحفظات:**
• ٹھنڈے صبح/شام کے اوقات میں ورزش کریں
• پانی اور الیکٹرولائٹس کے ساتھ ہائیڈریٹ رہیں
• ہلکے، ہوا دار کپڑے پہنیں
• گرم موسم میں اپنے جسم کی بات سنیں
**🔄 ورزش کی اقسام:**
• **کارڈیو**: چہل قدمی، جاگنگ، سائیکل چلانا، تیراکی
• **طاقت**: وزن کی تربیت، مزاحمتی بینڈ
• **لچک**: یوگا، اسٹریچنگ
• **توازن**: تائی چی، توازن کی ورزشیں
*اہم: نئی ورزش پروگرام شروع کرنے سے پہلے ڈاکٹر سے مشورہ کریں۔*
"""
def _format_symptoms_response(self, language):
if language == 'English':
return """
**🔍 Symptom Assessment Guidance**
**🩺 When to Seek Medical Care:**
• Persistent fever above 103°F (39.4°C)
• Difficulty breathing or chest pain
• Severe abdominal pain
• Sudden dizziness, weakness, or confusion
• Unexplained weight loss (>10% body weight)
• Symptoms lasting more than 2 weeks
• Worsening of chronic conditions
**🏠 Self-Care Tips:**
• Rest and adequate hydration
• Monitor symptoms and temperature regularly
• Use over-the-counter medications as directed
• Apply cold/heat packs as appropriate
• Maintain proper nutrition
**🚨 Emergency Warning Signs (Go to ER):**
• Difficulty breathing or shortness of breath
• Chest pain or pressure lasting >5 minutes
• Severe bleeding that doesn't stop
• Sudden severe pain anywhere in body
• Loss of consciousness or fainting
• Sudden vision changes
• Difficulty speaking or confusion
*⚠️ Important: This is general guidance. Always consult healthcare professional for proper diagnosis.*
"""
else:
return """
**🔍 علامات کی تشخیص کی رہنمائی**
**🩺 طبی دیکھ بھال کب حاصل کریں:**
• 103°F (39.4°C) سے اوپر مستقل بخار
• سانس لینے میں دشواری یا سینے میں درد
• شدید پیٹ کا درد
• اچانک چکر آنا، کمزوری، یا الجھن
• بے وجہ وزن میں کمی (>10% جسمانی وزن)
• 2 ہفتے سے زیادہ علامات برقرار رہنا
• دائمی حالات کا بگڑنا
**🏠 خود کی دیکھ بھال کے نکات:**
• آرام اور مناسب ہائیڈریشن
• علامات اور درجہ حرارت کی باقاعدہ نگرانی
• ہدایت کے مطابق اوور دی کاؤنٹر ادویات استعمال کریں
• حسب مناسب کولڈ/ہیٹ پیکس لگائیں
• مناسب غذائیت برقرار رکھیں
**🚨 ہنگامی انتباہی علامات (ایمرجنسی روم جائیں):**
• سانس لینے میں دشواری یا سانس کی قلت
• 5 منٹ سے زیادہ سینے میں درد یا دباؤ
• شدید خون بہنا جو رک نہیں رہا
• جسم میں کہیں بھی اچانک شدید درد
• ہوش کا ضیاع یا بیہوشی
• اچانک بینائی میں تبدیلی
• بولنے میں دشواری یا الجھن
*⚠️ اہم: یہ عام رہنمائی ہے۔ مناسب تشخیص کے لیے ہمیشہ ہیلتھ کیئر پروفیشنل سے مشورہ کریں۔*
"""
def _format_medication_response(self, language):
if language == 'English':
return """
**💊 Medication Safety & Information**
**📋 General Medication Guidelines:**
• Take medications exactly as prescribed
• Never share prescriptions with others
• Keep updated medication list with you
• Inform all doctors about all medications
• Understand purpose and side effects of each medicine
**⚠️ Common Medication Categories:**
• **Heart**: Beta-blockers, ACE inhibitors, statins
• **Diabetes**: Metformin, insulin, SGLT2 inhibitors
• **Hypertension**: Diuretics, calcium channel blockers
• **Pain**: NSAIDs, acetaminophen (use cautiously)
**🚨 Medication Warning Signs:**
• Severe allergic reactions (rash, swelling)
• Difficulty breathing after taking medicine
• Severe stomach pain or vomiting
• Unusual bleeding or bruising
• Confusion or hallucinations
**💡 Important Reminders:**
• Don't stop medications without doctor's advice
• Report side effects to your doctor
• Keep medications in original containers
• Check expiration dates regularly
*Note: Always follow your healthcare provider's specific instructions.*
"""
else:
return """
**💊 دوائیوں کی حفاظت اور معلومات**
**📋 عام دوائیوں کے رہنما اصول:**
• دوائیں بالکل تجویز کردہ طریقے سے لیں
• کبھی بھی دوسروں کے ساتھ نسخے شیئر نہ کریں
• اپنے ساتھ اپ ڈیٹ شدہ دوائیوں کی فہرست رکھیں
• تمام ڈاکٹروں کو تمام دوائیوں کے بارے میں بتائیں
• ہر دوا کے مقصد اور مضر اثرات کو سمجھیں
**⚠️ عام دوائیوں کی اقسام:**
• **دل**: بیٹا بلاکرز، ACE inhibitors، statins
• **ذیابیطس**: میٹفارمن، انسولین، SGLT2 inhibitors
• **ہائی بلڈ پریشر**: ڈائیوریٹکس، کیلشیم چینل بلاکرز
• **درد**: NSAIDs، acetaminophen (احتیاط سے استعمال کریں)
**🚨 دوائیوں کی انتباہی علامات:**
• شدید الرجک رد عمل (خارش، سوجن)
• دوا لینے کے بعد سانس لینے میں دشواری
• شدید پیٹ میں درد یا الٹی
• غیر معمولی خون بہنا یا چوٹ لگنا
• الجھن یا توہمات
**💡 اہم یاد دہانیاں:**
• ڈاکٹر کے مشورے کے بغیر دوائیں بند نہ کریں
• اپنے ڈاکٹر کو مضر اثرات کی رپورٹ کریں
• دوائیں اصل کنٹینرز میں رکھیں
• میعاد ختم ہونے کی تاریخوں کو باقاعدگی سے چیک کریں
*نوٹ: ہمیشہ اپنے ہیلتھ کیئر فراہم کرنے والے کی مخصوص ہدایات پر عمل کریں۔*
"""
def _format_emergency_response(self, language):
if language == 'English':
return """
**🚨 EMERGENCY MEDICAL GUIDANCE**
**📞 Immediate Actions Required:**
• Call emergency services (1122 in Pakistan)
• Don't drive yourself to hospital
• Keep patient calm and comfortable
• Have medical information ready
• Don't give food or drink
**🏥 When to Go to Emergency Room:**
• Chest pain or pressure
• Difficulty breathing
• Severe bleeding
• Sudden weakness or paralysis
• Severe burns
• Poisoning or overdose
• Seizures
• Severe allergic reactions
**🆘 First Aid Basics:**
• **CPR**: Start if no breathing/pulse (30 compressions: 2 breaths)
• **Bleeding**: Apply direct pressure
• **Choking**: Perform Heimlich maneuver
• **Burns**: Cool with running water
• **Fainting**: Lay flat, elevate legs
**📋 Emergency Preparedness:**
• Keep emergency numbers handy
• Know location of nearest hospital
• Have medical history documented
• Keep medications list updated
*⚠️ THIS IS EMERGENCY GUIDANCE ONLY. SEEK PROFESSIONAL MEDICAL HELP IMMEDIATELY.*
"""
else:
return """
**🚨 ہنگامی طبی رہنمائی**
**📞 فوری کارروائی کی ضرورت ہے:**
• ہنگامی خدمات کو کال کریں (پاکستان میں 1122)
• خود ہسپتال نہ جائیں
• مریض کو پرسکون اور آرام دہ رکھیں
• طبی معلومات تیار رکھیں
• کھانا یا پانی نہ دیں
**🏥 ایمرجنسی روم کب جائیں:**
• سینے میں درد یا دباؤ
• سانس لینے میں دشواری
• شدید خون بہنا
• اچانک کمزوری یا فالج
• شدید جلنے
• زہر یا اوور ڈوز
• دورے
• شدید الرجک رد عمل
**🆘 فرسٹ ایڈ کی بنیادی باتیں:**
• **CPR**: اگر سانس/پلس نہ ہو تو شروع کریں (30 کمپریشن: 2 سانس)
• **خون بہنا**: براہ راست دباؤ ڈالیں
• **گلا گھٹنا**: ہیملک مانور انجام دیں
• **جلنے**: پانی سے ٹھنڈا کریں
• **بیہوشی**: سیدھا لیٹائیں، ٹانگیں اونچی کریں
**📋 ہنگامی تیاری:**
• ہنگامی نمبرز ہاتھ میں رکھیں
• قریبی ہسپتال کا مقام جانیں
• طبی تاریخ دستاویزی شکل میں رکھیں
• دوائیوں کی فہرست اپ ڈیٹ رکھیں
*⚠️ یہ صرف ہنگامی رہنمائی ہے۔ فوری طور پر پیشہ ورانہ طبی مدد حاصل کریں۔*
"""
def _format_general_health_response(self, language):
knowledge = self.medical_knowledge_base['general_health']
if language == 'English':
return f"""
**🌿 Comprehensive Health & Wellness Guide**
**💚 Lifestyle Recommendations:**
{chr(10).join(['• ' + tip for tip in knowledge['lifestyle']])}
**🛡️ Preventive Healthcare:**
{chr(10).join(['• ' + tip for tip in knowledge['prevention']])}
**🎯 Health Monitoring Schedule:**
• **Daily**: Blood pressure (if hypertensive), blood sugar (if diabetic)
• **Weekly**: Weight, exercise minutes
• **Monthly**: Self-examinations (skin, breasts, testicles)
• **Annual**: Complete physical, blood tests, dental checkup
• **As recommended**: Cancer screenings, vision/hearing tests
**🌟 Healthy Habits for Pakistan:**
• Drink filtered/boiled water
• Eat fresh, locally available fruits and vegetables
• Practice good food hygiene
• Get adequate sunlight exposure (vitamin D)
• Maintain social connections and mental wellbeing
*Remember: Small consistent changes lead to lasting health improvements!*
"""
else:
return f"""
**🌿 صحت اور تندرستی کی جامع گائیڈ**
**💚 طرز زندگی کی سفارشات:**
{chr(10).join(['• ' + tip for tip in ['رات میں 7-9 گھنٹے معیاری نیند', 'تناؤ کے انتظام کی تکنیکیں', 'سگریٹ نوشی سے پرہیز', 'شراب کو 1-2 ڈرنکس/دن تک محدود کریں', 'باقاعدہ صحت کی جانچ']])}
**🛡️ احتیاطی ہیلتھ کیئر:**
{chr(10).join(['• ' + tip for tip in ['سالانہ جسمانی امتحانات', 'ویکسینیشن اپ ڈیٹ', 'باقاعدہ ہاتھ دھونا', 'سورج سے تحفظ', 'ذہنی صحت کی دیکھ بھال']])}
**🎯 صحت کی نگرانی کا شیڈول:**
• **روزانہ**: بلڈ پریشر (اگر ہائی بلڈ پریشر ہو)، بلڈ شوگر (اگر ذیابیطس ہو)
• **ہفتہ وار**: وزن، ورزش کے منٹ
• **ماہانہ**: خود معائنہ (جلد، چھاتی، خصیے)
• **سالانہ**: مکمل جسمانی، خون کے ٹیسٹ، دانتوں کا چیک اپ
• **جیسا کہ تجویز کیا گیا ہے**: کینسر کی اسکریننگ، بینائی/سماعت کے ٹیسٹ
**🌟 پاکستان کے لیے صحت مند عادات:**
• فلٹر/ابلا ہوا پانی پیئیں
• تازہ، مقامی طور پر دستیاب پھل اور سبزیاں کھائیں
• اچھی غذا کی حفظان صحت کی مشق کریں
• مناسب سورج کی روشنی (وٹامن ڈی) حاصل کریں
• سماجی رابطے اور ذہنی تندرستی برقرار رکھیں
*یاد رکھیں: چھوٹی مسلسل تبدیلیاں پائیدار صحت کی بہتری کا باعث بنتی ہیں!*
"""
def _format_default_response(self, language):
if language == 'English':
return """
**🤖 SehatAI Health Assistant**
I understand you're asking about health topics. I'm specially trained to help with:
**💚 Common Health Areas:**
• Heart disease and cardiovascular health
• Diabetes management and prevention
• Blood pressure control
• Nutrition and dietary guidance
• Exercise and physical activity
• Symptom assessment
• Medication information
• Emergency situations
• General wellness and prevention
**💡 How to Get Better Answers:**
Please ask specific questions like:
• "What are the symptoms of heart disease?"
• "How to manage diabetes?"
• "What foods help lower blood pressure?"
• "Exercise recommendations for beginners"
• "When to go to emergency room?"
I'll provide detailed, accurate medical information to help you make informed health decisions.
*⚠️ Remember: I'm an AI assistant. For personal medical advice, always consult qualified healthcare professionals.*
"""
else:
return """
**🤖 سیحت اے آئی ہیلتھ اسسٹنٹ**
میں سمجھتا ہوں کہ آپ صحت کے موضوعات کے بارے میں پوچھ رہے ہیں۔ میں خاص طور پر مدد کے لیے تربیت یافتہ ہوں:
**💚 عام صحت کے شعبے:**
• دل کی بیماری اور قلبی صحت
• ذیابیطس کا انتظام اور روک تھام
• بلڈ پریشر کنٹرول
• غذائیت اور غذائی رہنمائی
• ورزش اور جسمانی سرگرمی
• علامات کی تشخیص
• دوائیوں کی معلومات
• ہنگامی حالات
• عام تندرستی اور روک تھام
**💡 بہتر جوابات کیسے حاصل کریں:**
براہ کرم مخصوص سوالات پوچھیں جیسے:
• "دل کی بیماری کی علامات کیا ہیں؟"
• "ذیابیطس کا انتظام کیسے کریں؟"
• "کون سی غذائیں بلڈ پریشر کم کرنے میں مدد کرتی ہیں؟"
• "ابتدائی افراد کے لیے ورزش کی سفارشات"
• "ایمرجنسی روم کب جائیں؟"
میں آپ کو معلوماتی صحت کے فیصلے کرنے میں مدد کے لیے تفصیلی، درست طبی معلومات فراہم کروں گا۔
*⚠️ یاد رکھیں: میں ایک AI اسسٹنٹ ہوں۔ ذاتی طبی مشورے کے لیے، ہمیشہ کوالیفائیڈ ہیلتھ کیئر پروفیشنلز سے مشورہ کریں۔*
"""
class PDFReportGenerator:
def __init__(self):
self.pdf = FPDF()
self.pdf.set_auto_page_break(auto=True, margin=15)
def generate_report(self, patient_data, risk_scores, language='English'):
self.pdf.add_page()
# Title
self.pdf.set_font('Arial', 'B', 16)
if language == 'English':
self.pdf.cell(0, 10, 'SEHATAI MEDICAL ASSESSMENT REPORT', 0, 1, 'C')
else:
# For Urdu, we'll use English to avoid encoding issues
self.pdf.cell(0, 10, 'SEHATAI MEDICAL ASSESSMENT REPORT', 0, 1, 'C')
self.pdf.ln(10)
# Patient Information
self.pdf.set_font('Arial', 'B', 12)
self.pdf.cell(0, 10, 'Patient Information:', 0, 1)
self.pdf.set_font('Arial', '', 10)
patient_info = [
f"Name: {self._safe_encode(patient_data.get('name', 'Not provided'))}",
f"Age: {patient_data.get('age', 'Not provided')} years",
f"Gender: {self._safe_encode(patient_data.get('gender', 'Not provided'))}",
f"Contact: {self._safe_encode(patient_data.get('contact', 'Not provided'))}"
]
for info in patient_info:
self.pdf.cell(0, 8, info, 0, 1)
self.pdf.ln(5)
# Clinical Parameters
self.pdf.set_font('Arial', 'B', 12)
self.pdf.cell(0, 10, 'Clinical Parameters:', 0, 1)
self.pdf.set_font('Arial', '', 10)
clinical_info = [
f"Blood Pressure: {patient_data.get('bp_systolic', 'N/A')}/{patient_data.get('bp_diastolic', 'N/A')} mmHg",
f"Heart Rate: {patient_data.get('heart_rate', 'N/A')} bpm",
f"Cholesterol: {patient_data.get('cholesterol', 'N/A')} mg/dL",
f"Glucose: {patient_data.get('glucose', 'N/A')} mg/dL",
f"BMI: {patient_data.get('bmi', 'N/A')}"
]
for info in clinical_info:
self.pdf.cell(0, 8, info, 0, 1)
self.pdf.ln(5)
# Symptoms
self.pdf.set_font('Arial', 'B', 12)
self.pdf.cell(0, 10, 'Reported Symptoms:', 0, 1)
self.pdf.set_font('Arial', '', 10)
symptoms = patient_data.get('symptoms', {})
symptom_list = [
f"Chest Pain: {'Yes' if symptoms.get('chest_pain') else 'No'}",
f"Shortness of Breath: {'Yes' if symptoms.get('shortness_breath') else 'No'}",
f"Palpitations: {'Yes' if symptoms.get('palpitations') else 'No'}",
f"Fatigue: {'Yes' if symptoms.get('fatigue') else 'No'}",
f"Dizziness: {'Yes' if symptoms.get('dizziness') else 'No'}",
f"Blurred Vision: {'Yes' if symptoms.get('blurred_vision') else 'No'}"
]
for symptom in symptom_list:
self.pdf.cell(0, 8, symptom, 0, 1)
self.pdf.ln(5)
# Risk Assessment
self.pdf.set_font('Arial', 'B', 12)
self.pdf.cell(0, 10, 'Risk Assessment Results:', 0, 1)
self.pdf.set_font('Arial', '', 10)
risk_info = [
f"Heart Disease Risk: {risk_scores.get('heart', 0):.1%}",
f"Diabetes Risk: {risk_scores.get('diabetes', 0):.1%}",
f"Hypertension Risk: {risk_scores.get('hypertension', 0):.1%}",
f"Overall Priority Score: {risk_scores.get('priority', 0):.1%}"
]
for info in risk_info:
self.pdf.cell(0, 8, info, 0, 1)
self.pdf.ln(5)
# Recommendation
self.pdf.set_font('Arial', 'B', 12)
self.pdf.cell(0, 10, 'Clinical Recommendation:', 0, 1)
self.pdf.set_font('Arial', '', 10)
recommendation = self._safe_encode(risk_scores.get('recommendation', 'No recommendation available'))
self.pdf.multi_cell(0, 8, recommendation)
self.pdf.ln(10)
# Footer
self.pdf.set_font('Arial', 'I', 8)
self.pdf.cell(0, 10, f'Generated by SehatAI on: {datetime.now().strftime("%Y-%m-%d %H:%M")}', 0, 1, 'C')
return self.pdf.output(dest='S').encode('latin1', 'replace')
def _safe_encode(self, text):
"""Safely encode text for PDF generation"""
if text is None:
return ""
try:
return str(text)
except:
return "Encoding error"
# Load ML models with error handling
@st.cache_resource(show_spinner=False)
def load_models():
models = {}
scalers = {}
try:
# Load heart disease model
if os.path.exists('heart_model.pkl'):
models['heart'] = joblib.load('heart_model.pkl')
st.success("✅ Heart disease model loaded successfully")
else:
st.warning("⚠️ Heart model file not found, using rule-based assessment")
models['heart'] = None
except Exception as e:
st.warning(f"⚠️ Error loading heart model: {str(e)}")
models['heart'] = None
try:
# Load diabetes model
if os.path.exists('diabeties_model.pkl'):
models['diabetes'] = joblib.load('diabeties_model.pkl')
st.success("✅ Diabetes model loaded successfully")
else:
st.warning("⚠️ Diabetes model file not found, using rule-based assessment")
models['diabetes'] = None
except Exception as e:
st.warning(f"⚠️ Error loading diabetes model: {str(e)}")
models['diabetes'] = None
try:
# Load hypertension model
if os.path.exists('hypertension_model.pkl'):
models['hypertension'] = joblib.load('hypertension_model.pkl')
st.success("✅ Hypertension model loaded successfully")
else:
st.warning("⚠️ Hypertension model file not found, using rule-based assessment")
models['hypertension'] = None
except Exception as e:
st.warning(f"⚠️ Error loading hypertension model: {str(e)}")
models['hypertension'] = None
# Load scalers
try:
if os.path.exists('scaler.pkl'):
scalers['default'] = joblib.load('scaler.pkl')
st.success("✅ Scaler loaded successfully")
except:
st.warning("⚠️ Scaler not available, using standard scaling")
scalers['default'] = None
return models, scalers
def calculate_priority_score(heart_risk, diabetes_risk, hypertension_risk):
"""Calculate integrated priority score with clinical weighting"""
# Clinical severity weighting
priority = (
heart_risk * 0.45 + # Highest weight for cardiac issues
diabetes_risk * 0.25 + # Medium weight for diabetes
hypertension_risk * 0.30 # Medium weight for hypertension
)
return min(1.0, priority) # Cap at 1.0
def get_priority_recommendation(priority_score, language='English'):
"""Get priority-based recommendation with clinical thresholds"""
if priority_score >= 0.75:
if language == 'Urdu':
return "EMERGENCY_CARE", "اعلی ترجیح - فوری ہنگامی علاج کی ضرورت", "risk-high"
else:
return "EMERGENCY_CARE", "High Priority - Immediate Emergency Care Required", "risk-high"
elif priority_score >= 0.55:
if language == 'Urdu':
return "SAME_DAY_CONSULT", "درمیانی ترجیح - اسی دن مشورہ ضروری", "risk-medium"
else:
return "SAME_DAY_CONSULT", "Medium Priority - Same Day Consultation Required", "risk-medium"
else:
if language == 'Urdu':
return "ROUTINE_APPOINTMENT", "کم ترجیح - روٹین اپائنٹمنٹ", "risk-low"
else:
return "ROUTINE_APPOINTMENT", "Low Priority - Routine Appointment", "risk-low"
def validate_patient_data(age, bp_systolic, bp_diastolic, heart_rate):
"""Validate patient data for realistic clinical values"""
errors = []
if age < 1 or age > 120:
errors.append("Age must be between 1 and 120 years")
if bp_systolic < 70 or bp_systolic > 250:
errors.append("Systolic BP must be between 70 and 250 mmHg")
if bp_diastolic < 40 or bp_diastolic > 150:
errors.append("Diastolic BP must be between 40 and 150 mmHg")
if heart_rate < 30 or heart_rate > 200:
errors.append("Heart rate must be between 30 and 200 bpm")
return errors
def predict_with_models(age, bp_systolic, bp_diastolic, heart_rate, cholesterol, glucose, bmi, symptoms, models, scalers):
"""Predict risks using loaded ML models"""
heart_risk, diabetes_risk, hypertension_risk = 0.0, 0.0, 0.0
try:
# Prepare features for heart model
if models['heart'] is not None:
heart_features = np.array([[
age, bp_systolic, cholesterol, heart_rate,
symptoms['chest_pain'], symptoms['shortness_breath'],
symptoms['palpitations'], bmi, glucose
]])
if scalers.get('default') is not None:
heart_features = scalers['default'].transform(heart_features)
heart_risk = models['heart'].predict_proba(heart_features)[0][1]
else:
heart_risk = predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
except Exception as e:
heart_risk = predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
try:
# Prepare features for diabetes model
if models['diabetes'] is not None:
diabetes_features = np.array([[
age, glucose, bmi, cholesterol,
symptoms['fatigue'], symptoms['blurred_vision'],
bp_systolic, heart_rate
]])
if scalers.get('default') is not None:
diabetes_features = scalers['default'].transform(diabetes_features)
diabetes_risk = models['diabetes'].predict_proba(diabetes_features)[0][1]
else:
diabetes_risk = predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
except Exception as e:
diabetes_risk = predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
try:
# Prepare features for hypertension model
if models['hypertension'] is not None:
hypertension_features = np.array([[
age, bp_systolic, bp_diastolic, bmi,
symptoms['dizziness'], symptoms['palpitations'],
heart_rate, cholesterol
]])
if scalers.get('default') is not None:
hypertension_features = scalers['default'].transform(hypertension_features)
hypertension_risk = models['hypertension'].predict_proba(hypertension_features)[0][1]
else:
hypertension_risk = predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
except Exception as e:
hypertension_risk = predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms)
return heart_risk, diabetes_risk, hypertension_risk
def predict_risk_rule_based_heart(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms):
"""Rule-based heart risk prediction"""
risk = 0.0
# Age factor
if age > 60: risk += 0.25
elif age > 45: risk += 0.15
elif age > 30: risk += 0.05
# Blood pressure factor
if bp_systolic > 180 or bp_diastolic > 120: risk += 0.30
elif bp_systolic > 140 or bp_diastolic > 90: risk += 0.20
elif bp_systolic > 130 or bp_diastolic > 85: risk += 0.10
# Cholesterol factor
if cholesterol > 240: risk += 0.20
elif cholesterol > 200: risk += 0.10
# BMI factor
if bmi > 35: risk += 0.15
elif bmi > 30: risk += 0.10
elif bmi > 25: risk += 0.05
# Glucose factor
if glucose > 200: risk += 0.10
elif glucose > 126: risk += 0.05
# Symptom factors
if symptoms['chest_pain']: risk += 0.25
if symptoms['shortness_breath']: risk += 0.15
if symptoms['palpitations']: risk += 0.10
return min(0.95, risk)
def predict_risk_rule_based_diabetes(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms):
"""Rule-based diabetes risk prediction"""
risk = 0.0
# Age factor
if age > 50: risk += 0.20
elif age > 40: risk += 0.10
elif age > 30: risk += 0.05
# Glucose factor (most important)
if glucose > 200: risk += 0.40
elif glucose > 126: risk += 0.30
elif glucose > 100: risk += 0.15
# BMI factor
if bmi > 35: risk += 0.25
elif bmi > 30: risk += 0.15
elif bmi > 25: risk += 0.08
# Blood pressure factor
if bp_systolic > 140 or bp_diastolic > 90: risk += 0.10
# Symptom factors
if symptoms['fatigue']: risk += 0.10
if symptoms['blurred_vision']: risk += 0.08
return min(0.95, risk)
def predict_risk_rule_based_hypertension(age, bp_systolic, bp_diastolic, cholesterol, glucose, bmi, symptoms):
"""Rule-based hypertension risk prediction"""
risk = 0.0
# Blood pressure factor (most important)
if bp_systolic > 180 or bp_diastolic > 120: risk += 0.50
elif bp_systolic > 140 or bp_diastolic > 90: risk += 0.35
elif bp_systolic > 130 or bp_diastolic > 85: risk += 0.20
# Age factor
if age > 60: risk += 0.15
elif age > 45: risk += 0.08
# BMI factor
if bmi > 30: risk += 0.15
elif bmi > 25: risk += 0.08
# Symptom factors
if symptoms['dizziness']: risk += 0.10
if symptoms['palpitations']: risk += 0.08
return min(0.95, risk)
def create_download_link(pdf_data, filename, text):
"""Create a download link for PDF"""
b64 = base64.b64encode(pdf_data).decode()
href = f'<a href="data:application/octet-stream;base64,{b64}" download="{filename}">{text}</a>'
return href
def main():
# Load custom CSS
local_css()
init_session_state()
# Load ML models
with st.spinner("🔄 Loading AI models..."):
models, scalers = load_models()
# Initialize chatbot
chatbot = HealthcareChatbot()
# Language selector at top right with Pakistan flag colors
col_lang, col_space = st.columns([1, 5])
with col_lang:
st.markdown('<div class="pakistan-flag">🇵🇰</div>', unsafe_allow_html=True)
language = st.selectbox("Language", ["English", "Urdu"], key="language_selector", label_visibility="collapsed")
st.session_state.current_language = language
# Main header with new name
st.markdown('<h1 class="main-header">🏥 SehatAI</h1>', unsafe_allow_html=True)
if language == "English":
st.markdown('<h3 style="text-align: center; color: #00612A; margin-bottom: 20px;">Smart Healthcare Triage & Risk Assessment System</h3>', unsafe_allow_html=True)
else:
st.markdown('<h3 style="text-align: center; color: #00612A; margin-bottom: 20px;">ذہین ہیلتھ کیئر ٹریج اور خطرے کی تشخیص کا نظام</h3>', unsafe_allow_html=True)
# Display random healthcare quote
import random
quote = random.choice(HEALTHCARE_QUOTES)
st.markdown(f'''
<div class="quote-section">
<div class="quote-text">"{quote['english']}"</div>
<div class="quote-text">"{quote['urdu']}"</div>
<div class="quote-author">- {quote['author']}</div>
</div>
''', unsafe_allow_html=True)
# Create tabs
if language == "English":
tab_names = ["Patient Assessment", "Health Assistant", "Medical Reports"]
else:
tab_names = ["مریض تشخیص", "ہیلتھ اسسٹنٹ", "طبی رپورٹس"]
tab1, tab2, tab3 = st.tabs(tab_names)
with tab1:
# Patient Assessment Form
st.markdown('<div class="section-container">', unsafe_allow_html=True)
if language == "English":
st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">👨⚕️ Comprehensive Patient Assessment</h2>', unsafe_allow_html=True)
st.write("Complete the following form for comprehensive patient risk assessment and priority scoring")
else:
st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">👨⚕️ جامع مریض تشخیص</h2>', unsafe_allow_html=True)
st.write("جامع مریض کے خطرے کی تشخیص اور ترجیحی اسکورنگ کے لیے درج ذیل فارم کو مکمل کریں")
with st.form("patient_assessment_form"):
col1, col2 = st.columns(2)
with col1:
# Basic Information
if language == "English":
st.subheader("Personal Information")
name = st.text_input("Full Name", placeholder="Enter patient's full name")
age = st.number_input("Age", min_value=1, max_value=120, value=45,
help="Patient's age in years")
gender = st.selectbox("Gender", ["Male", "Female", "Other"])
contact = st.text_input("Contact Number", placeholder="03XX-XXXXXXX")
else:
st.subheader("ذاتی معلومات")
name = st.text_input("مکمل نام", placeholder="مریض کا مکمل نام درج کریں")
age = st.number_input("عمر", min_value=1, max_value=120, value=45,
help="مریض کی عمر سالوں میں")
gender = st.selectbox("جنس", ["مرد", "عورت", "دیگر"])
contact = st.text_input("رابطہ نمبر", placeholder="03XX-XXXXXXX")
with col2:
# Vital Signs
if language == "English":
st.subheader("Clinical Parameters")
bp_systolic = st.slider("Blood Pressure (systolic)",
min_value=70, max_value=250, value=120,
help="Systolic blood pressure in mmHg")
bp_diastolic = st.slider("Blood Pressure (diastolic)",
min_value=40, max_value=150, value=80,
help="Diastolic blood pressure in mmHg")
heart_rate = st.slider("Heart Rate (bpm)",
min_value=30, max_value=200, value=72,
help="Heart beats per minute")
cholesterol = st.slider("Cholesterol Level (mg/dL)",
min_value=100, max_value=400, value=180)
glucose = st.slider("Blood Glucose (mg/dL)",
min_value=50, max_value=500, value=95)
bmi = st.slider("BMI", min_value=15.0, max_value=40.0, value=23.5, step=0.1)
else:
st.subheader("کلینیکل پیرامیٹرز")
bp_systolic = st.slider("بلڈ پریشر (سسٹولک)",
min_value=70, max_value=250, value=120,
help="سسٹولک بلڈ پریشر mmHg میں")
bp_diastolic = st.slider("بلڈ پریشر (ڈائیسٹولک)",
min_value=40, max_value=150, value=80,
help="ڈائیسٹولک بلڈ پریشر mmHg میں")
heart_rate = st.slider("دل کی دھڑکن (bpm)",
min_value=30, max_value=200, value=72,
help="دل کی دھڑکن فی منٹ")
cholesterol = st.slider("کولیسٹرول کی سطح (mg/dL)",
min_value=100, max_value=400, value=180)
glucose = st.slider("خون میں گلوکوز (mg/dL)",
min_value=50, max_value=500, value=95)
bmi = st.slider("باڈی ماس انڈیکس", min_value=15.0, max_value=40.0, value=23.5, step=0.1)
# Symptoms Section
if language == "English":
st.subheader("Reported Symptoms")
col3, col4 = st.columns(2)
with col3:
chest_pain = st.checkbox("Chest Pain or Discomfort")
shortness_breath = st.checkbox("Shortness of Breath")
palpitations = st.checkbox("Heart Palpitations")
with col4:
fatigue = st.checkbox("Persistent Fatigue")
dizziness = st.checkbox("Dizziness or Lightheadedness")
blurred_vision = st.checkbox("Blurred Vision")
else:
st.subheader("رپورٹ کردہ علامات")
col3, col4 = st.columns(2)
with col3:
chest_pain = st.checkbox("سینے میں درد یا بے چینی")
shortness_breath = st.checkbox("سانس لینے میں دشواری")
palpitations = st.checkbox("دل کی دھڑکن میں اضافہ")
with col4:
fatigue = st.checkbox("مسلسل تھکاوٹ")
dizziness = st.checkbox("چکر آنا یا سر ہلکا محسوس ہونا")
blurred_vision = st.checkbox("دھندلا نظر آنا")
# Assessment Button
if language == "English":
assess_button = st.form_submit_button("🚀 Calculate Risk Score & Priority",
use_container_width=True)
else:
assess_button = st.form_submit_button("🚀 خطرے کا اسکور اور ترجیح معلوم کریں",
use_container_width=True)
if assess_button:
# Validate inputs
validation_errors = validate_patient_data(age, bp_systolic, bp_diastolic, heart_rate)
if validation_errors:
for error in validation_errors:
st.error(f"❌ {error}")
else:
try:
with st.spinner("🔍 Analyzing patient data and calculating risks..."):
# Prepare symptoms dictionary
symptoms_dict = {
'chest_pain': chest_pain,
'shortness_breath': shortness_breath,
'palpitations': palpitations,
'fatigue': fatigue,
'dizziness': dizziness,
'blurred_vision': blurred_vision
}
# Store patient data
st.session_state.patient_data = {
'name': name,
'age': age,
'gender': gender,
'contact': contact,
'bp_systolic': bp_systolic,
'bp_diastolic': bp_diastolic,
'heart_rate': heart_rate,
'cholesterol': cholesterol,
'glucose': glucose,
'bmi': bmi,
'symptoms': symptoms_dict
}
# Predict risks using ML models
heart_risk, diabetes_risk, hypertension_risk = predict_with_models(
age, bp_systolic, bp_diastolic, heart_rate,
cholesterol, glucose, bmi, symptoms_dict, models, scalers
)
# Calculate integrated priority score
priority_score = calculate_priority_score(
heart_risk, diabetes_risk, hypertension_risk
)
priority_level, recommendation, risk_class = get_priority_recommendation(
priority_score, language
)
# Store results
st.session_state.risk_scores = {
'heart': heart_risk,
'diabetes': diabetes_risk,
'hypertension': hypertension_risk,
'priority': priority_score,
'recommendation': recommendation,
'level': priority_level
}
# Add to assessment history
st.session_state.assessment_history.append({
'timestamp': datetime.now(),
'patient_data': st.session_state.patient_data.copy(),
'risk_scores': st.session_state.risk_scores.copy()
})
# Display results
st.markdown("---")
st.success("✅ Risk assessment completed successfully!")
# Risk Scores Visualization
if language == "English":
st.subheader("📊 Disease Risk Assessment Dashboard")
else:
st.subheader("📊 بیماری کے خطرے کی تشخیص ڈیش بورڈ")
col5, col6, col7, col8 = st.columns(4)
risk_metrics = [
(heart_risk, "Heart Disease", "❤️", "#FF6B6B"),
(diabetes_risk, "Diabetes", "🩺", "#4ECDC4"),
(hypertension_risk, "Hypertension", "💓", "#45B7D1"),
(priority_score, "Priority Score", "🎯", "#96CEB4")
]
for (value, title, emoji, color), col in zip(risk_metrics, [col5, col6, col7, col8]):
with col:
fig = go.Figure(go.Indicator(
mode = "gauge+number+delta",
value = value,
domain = {'x': [0, 1], 'y': [0, 1]},
title = {'text': f"{emoji} {title}", 'font': {'size': 14}},
gauge = {
'axis': {'range': [0, 1], 'tickwidth': 1},
'bar': {'color': color},
'steps': [
{'range': [0, 0.3], 'color': "lightgreen"},
{'range': [0.3, 0.7], 'color': "yellow"},
{'range': [0.7, 1], 'color': "red"}
],
'threshold': {
'line': {'color': "black", 'width': 4},
'thickness': 0.75,
'value': 0.7
}
}
))
fig.update_layout(height=250, margin=dict(l=10, r=10, t=50, b=10))
st.plotly_chart(fig, use_container_width=True)
# Priority Recommendation
st.markdown(f'<div class="priority-box {risk_class}">', unsafe_allow_html=True)
if language == "English":
st.markdown(f"## 🎯 Clinical Priority Recommendation")
st.markdown(f"### {recommendation}")
st.markdown(f"**Overall Risk Score:** `{priority_score:.3f}`")
st.markdown(f"**Recommended Action:** `{priority_level.replace('_', ' ').title()}`")
# Additional clinical guidance
if priority_level == "EMERGENCY_CARE":
st.warning("🚨 **Immediate Action Required:** Patient should be directed to emergency department without delay.")
elif priority_level == "SAME_DAY_CONSULT":
st.info("ℹ️ **Urgent Consultation:** Schedule appointment within 24 hours.")
else:
st.success("✅ **Routine Care:** Schedule within regular appointment system.")
else:
st.markdown(f"## 🎯 کلینیکل ترجیحی سفارش")
st.markdown(f"### {recommendation}")
st.markdown(f"**کل خطرے کا اسکور:** `{priority_score:.3f}`")
st.markdown(f"**سفارش کردہ عمل:** `{priority_level.replace('_', ' ').title()}`")
if priority_level == "EMERGENCY_CARE":
st.warning("🚨 **فوری کارروائی ضروری:** مریض کو بغیر کسی تاخیر کے ایمرجنسی ڈیپارٹمنٹ بھیجا جائے۔")
elif priority_level == "SAME_DAY_CONSULT":
st.info("ℹ️ **فوری مشاورت:** 24 گھنٹے کے اندر اپائنٹمنٹ شیڈول کریں۔")
else:
st.success("✅ **روٹین کیئر:** معمول کی اپائنٹمنٹ سسٹم کے اندر شیڈول کریں۔")
st.markdown('</div>', unsafe_allow_html=True)
except Exception as e:
st.error(f"❌ Error in risk assessment: {str(e)}")
st.markdown('</div>', unsafe_allow_html=True)
with tab2:
# Healthcare Chatbot
st.markdown('<div class="section-container">', unsafe_allow_html=True)
if language == "English":
st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">💬 SehatAI Health Assistant</h2>', unsafe_allow_html=True)
st.write("Ask health-related questions and get instant, reliable medical information")
else:
st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">💬 سیحت اے آئی ہیلتھ اسسٹنٹ</h2>', unsafe_allow_html=True)
st.write("صحت سے متعلق سوالات پوچھیں اور فوری، قابل اعتماد طبی معلومات حاصل کریں")
# Display chat history
for message in st.session_state.chat_history:
if message["role"] == "user":
st.markdown(f'<div class="chat-message user-message"><strong>You:</strong> {message["content"]}</div>', unsafe_allow_html=True)
else:
st.markdown(f'<div class="chat-message bot-message"><strong>🤖 Health Assistant:</strong> {message["content"]}</div>', unsafe_allow_html=True)
# Chat input
if prompt := st.chat_input(
"Type your health question here..." if language == "English"
else "اپنا صحت کا سوال یہاں ٹائپ کریں..."
):
# Add user message to chat history
st.session_state.chat_history.append({"role": "user", "content": prompt})
# Generate bot response
with st.spinner("💭 Analyzing your question..." if language == "English" else "💭 آپ کا سوال تجزیہ ہو رہا ہے..."):
response = chatbot.get_response(prompt, language)
st.session_state.chat_history.append({"role": "assistant", "content": response})
# Limit chat history to last 10 messages
if len(st.session_state.chat_history) > 10:
st.session_state.chat_history = st.session_state.chat_history[-10:]
st.rerun()
# Quick action buttons
if language == "English":
st.subheader("Quick Health Topics")
else:
st.subheader("فوری صحت کے موضوعات")
col_qa1, col_qa2, col_qa3, col_qa4 = st.columns(4)
with col_qa1:
if st.button("❤️ Heart Health", use_container_width=True):
st.session_state.chat_history.append({
"role": "user",
"content": "Tell me about heart disease symptoms and prevention"
})
st.rerun()
with col_qa2:
if st.button("🩺 Diabetes", use_container_width=True):
st.session_state.chat_history.append({
"role": "user",
"content": "What are diabetes symptoms and management strategies?"
})
st.rerun()
with col_qa3:
if st.button("💓 Blood Pressure", use_container_width=True):
st.session_state.chat_history.append({
"role": "user",
"content": "How to control high blood pressure naturally?"
})
st.rerun()
with col_qa4:
if st.button("🍎 Nutrition", use_container_width=True):
st.session_state.chat_history.append({
"role": "user",
"content": "What is a healthy diet for heart health?"
})
st.rerun()
# Additional quick actions
col_qa5, col_qa6, col_qa7, col_qa8 = st.columns(4)
with col_qa5:
if st.button("💪 Exercise", use_container_width=True):
st.session_state.chat_history.append({
"role": "user",
"content": "Exercise recommendations for beginners"
})
st.rerun()
with col_qa6:
if st.button("🔍 Symptoms", use_container_width=True):
st.session_state.chat_history.append({
"role": "user",
"content": "When should I seek emergency medical care?"
})
st.rerun()
with col_qa7:
if st.button("💊 Medications", use_container_width=True):
st.session_state.chat_history.append({
"role": "user",
"content": "General medication safety guidelines"
})
st.rerun()
with col_qa8:
if st.button("🚨 Emergency", use_container_width=True):
st.session_state.chat_history.append({
"role": "user",
"content": "What are emergency warning signs?"
})
st.rerun()
st.markdown('</div>', unsafe_allow_html=True)
with tab3:
# Medical Reports
st.markdown('<div class="section-container">', unsafe_allow_html=True)
if language == "English":
st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">📋 Medical Reports & Analytics</h2>', unsafe_allow_html=True)
st.write("Download comprehensive medical reports and view assessment analytics")
else:
st.markdown('<h2 style="color: #00401A; border-bottom: 3px solid #00401A; padding-bottom: 10px;">📋 طبی رپورٹس اور تجزیات</h2>', unsafe_allow_html=True)
st.write("جامع طبی رپورٹس ڈاؤن لوڈ کریں اور تشخیص کے تجزیات دیکھیں")
if st.session_state.assessment_history:
# Latest assessment
latest_assessment = st.session_state.assessment_history[-1]
# Download PDF report
if language == "English":
st.subheader("Download Patient Report")
else:
st.subheader("مریض رپورٹ ڈاؤن لوڈ کریں")
pdf_generator = PDFReportGenerator()
pdf_data = pdf_generator.generate_report(
latest_assessment['patient_data'],
latest_assessment['risk_scores'],
language
)
if language == "English":
st.markdown(create_download_link(pdf_data, "sehatai_medical_report.pdf", "📥 Download Medical Report (PDF)"), unsafe_allow_html=True)
else:
st.markdown(create_download_link(pdf_data, "sehatai_medical_report.pdf", "📥 طبی رپورٹ ڈاؤن لوڈ کریں (PDF)"), unsafe_allow_html=True)
# Analytics Section
if language == "English":
st.subheader("Assessment Analytics")
else:
st.subheader("تشخیص کے تجزیات")
col_anal1, col_anal2, col_anal3 = st.columns(3)
with col_anal1:
st.metric(
"Total Assessments" if language == "English" else "کل تشخیص",
len(st.session_state.assessment_history)
)
with col_anal2:
latest_priority = latest_assessment['risk_scores']['priority']
st.metric(
"Current Priority Score" if language == "English" else "موجودہ ترجیحی اسکور",
f"{latest_priority:.1%}"
)
with col_anal3:
high_risk_count = sum(1 for assess in st.session_state.assessment_history
if assess['risk_scores']['priority'] > 0.7)
st.metric(
"High Risk Cases" if language == "English" else "اعلی خطرہ والے معاملات",
high_risk_count
)
# Risk distribution chart
if len(st.session_state.assessment_history) > 1:
risk_data = pd.DataFrame([
{
'Heart Risk': assess['risk_scores']['heart'],
'Diabetes Risk': assess['risk_scores']['diabetes'],
'Hypertension Risk': assess['risk_scores']['hypertension'],
'Assessment': i+1
} for i, assess in enumerate(st.session_state.assessment_history[-5:])
])
fig = px.line(risk_data, x='Assessment', y=['Heart Risk', 'Diabetes Risk', 'Hypertension Risk'],
title="Risk Trend Analysis" if language == "English" else "خطرے کے رجحان کا تجزیہ",
color_discrete_map={
'Heart Risk': '#FF6B6B',
'Diabetes Risk': '#4ECDC4',
'Hypertension Risk': '#45B7D1'
})
st.plotly_chart(fig, use_container_width=True)
else:
if language == "English":
st.info("👆 Complete a patient assessment to generate reports and view analytics")
else:
st.info("👆 رپورٹس تیار کرنے اور تجزیات دیکھنے کے لیے مریض کی تشخیص مکمل کریں")
st.markdown('</div>', unsafe_allow_html=True)
if __name__ == "__main__":
main() |