Spaces:
Sleeping
Sleeping
File size: 81,445 Bytes
c97fd8c b580996 c97fd8c 66072f5 c97fd8c 66072f5 c97fd8c 66072f5 c97fd8c 66072f5 c97fd8c 66072f5 c97fd8c 66072f5 c97fd8c 66072f5 c97fd8c 66072f5 c97fd8c 66072f5 c97fd8c 66072f5 c97fd8c 66072f5 c97fd8c 66072f5 c97fd8c e50c059 66072f5 e50c059 939e83e 66072f5 c97fd8c 939e83e c97fd8c 939e83e c97fd8c 939e83e c97fd8c 30c2354 c97fd8c 17f07e4 b2fd496 30c2354 af7b1cd c97fd8c d361fe3 c97fd8c d361fe3 c97fd8c 17f07e4 af7b1cd 17f07e4 683fc34 17f07e4 c97fd8c d361fe3 c97fd8c d361fe3 af7b1cd c97fd8c 17f07e4 c97fd8c af7b1cd c97fd8c 17f07e4 c97fd8c d361fe3 af7b1cd d361fe3 17f07e4 d361fe3 af7b1cd d361fe3 c97fd8c af7b1cd c97fd8c 64968dc c97fd8c 64968dc c97fd8c 64968dc c97fd8c 64968dc c97fd8c 64968dc c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c d361fe3 c97fd8c d361fe3 af7b1cd c97fd8c 17f07e4 c97fd8c af7b1cd c97fd8c d361fe3 af7b1cd d361fe3 af7b1cd d361fe3 af7b1cd d361fe3 af7b1cd c97fd8c d361fe3 af7b1cd d361fe3 af7b1cd d361fe3 af7b1cd d361fe3 af7b1cd c97fd8c 17f07e4 d361fe3 17f07e4 c97fd8c 17f07e4 c97fd8c 17f07e4 c97fd8c 17f07e4 c97fd8c af7b1cd c97fd8c 7d4f9c6 17f07e4 c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c 64968dc c97fd8c 64968dc c97fd8c af7b1cd c97fd8c af7b1cd 17f07e4 c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c 30c2354 c97fd8c af7b1cd 17f07e4 c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c 30c2354 c97fd8c af7b1cd c97fd8c d361fe3 af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c af7b1cd c97fd8c d361fe3 af7b1cd 1e96998 83e00e2 51366a9 83e00e2 0bb8319 83e00e2 51366a9 83e00e2 51366a9 83e00e2 51366a9 83e00e2 51366a9 1e96998 39470a2 1e96998 51366a9 1e96998 b580996 83e00e2 de03bfb 83e00e2 51366a9 83e00e2 1e96998 39470a2 1e96998 556e9c0 1e96998 51366a9 83e00e2 bba4141 1e96998 bba4141 1e96998 bba4141 1e96998 bba4141 1e96998 bba4141 1e96998 bba4141 51366a9 83e00e2 1e96998 08dade9 1e96998 08dade9 1e96998 08dade9 1e96998 08dade9 1e96998 08dade9 1e96998 08dade9 1e96998 39470a2 1e96998 51366a9 83e00e2 51366a9 83e00e2 0bb8319 39470a2 83e00e2 51366a9 83e00e2 51366a9 83e00e2 51366a9 83e00e2 51366a9 83e00e2 51366a9 83e00e2 51366a9 83e00e2 51366a9 83e00e2 51366a9 83e00e2 51366a9 83e00e2 51366a9 dd394a0 83e00e2 de03bfb 83e00e2 51366a9 83e00e2 51366a9 83e00e2 51366a9 83e00e2 51366a9 dd394a0 51366a9 83e00e2 51366a9 83e00e2 de03bfb 51366a9 83e00e2 de03bfb 51366a9 83e00e2 dd394a0 1e96998 |
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 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 |
import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta
import requests
import json
import numpy as np
import math
import base64
# =================== CONFIG =====================
st.set_page_config(
page_title="Fatigue Analyzer - Advanced Fatigue Anfalytics",
page_icon="🛡️", # Safety icon
layout="wide",
initial_sidebar_state="expanded"
)
# =================== LOGO =====================
logo_path = "btech.png" # File logo
def get_base64(file_path):
with open(file_path, "rb") as f:
data = f.read()
return base64.b64encode(data).decode()
try:
logo_base64 = get_base64(logo_path)
logo_html = f'<img src="data:image/png;base64,{logo_base64}" style="max-height: 80px; max-width: 120px;">'
except FileNotFoundError:
st.warning(f"Logo file '{logo_path}' not found. Using placeholder text.")
logo_html = '<div style="font-size: 18px; font-weight: bold; color: #2c3e50;">BTECH</div>'
# # =================== GLOBAL CSS =====================
# st.markdown("""
# <style>
# body {
# background-color: #f6f8fa;
# }
# /* ===== HEADER WRAPPER ===== */
# .header-container {
# display: flex;
# justify-content: space-between;
# align-items: center;
# padding: 25px 35px;
# background: white; /* Latar belakang utama diubah menjadi putih */
# border-radius: 0 0 14px 14px; /* Rounded bottom only */
# box-shadow: 0 5px 18px rgba(0,0,0,0.15); /* Bayangan lebih lembut */
# border: 1px solid #e0e0e0; /* Border tipis untuk definisi */
# margin-bottom: 25px;
# position: relative;
# overflow: hidden; /* Ensure rounded corners clip content */
# }
# /* Optional: Subtle pattern or texture overlay (optional, can be removed) */
# /* .header-container::before {
# content: "";
# position: absolute;
# top: 0;
# left: 0;
# right: 0;
# bottom: 0;
# background: linear-gradient(45deg, rgba(255,255,255,0.03) 25%, transparent 25%, transparent 50%, rgba(255,255,255,0.03) 50%, rgba(255,255,255,0.03) 75%, transparent 75%, transparent);
# background-size: 20px 20px;
# pointer-events: none;
# } */
# /* ===== HEADER TEXT ===== */
# .header-title {
# color: #2c3e50; /* Teks header diubah agar kontras dengan latar putih */
# font-family: 'Segoe UI', sans-serif;
# flex-grow: 1; /* Allow text to take up available space */
# margin-right: 20px; /* Space between text and logo */
# text-align: left;
# }
# .header-title h1 {
# font-size: 2.7em;
# font-weight: 650;
# margin: 0;
# text-shadow: 1px 1px 2px rgba(0,0,0,0.1); /* Bayangan teks lebih lembut */
# }
# .header-title p {
# font-size: 1.25em;
# opacity: 0.85; /* Sedikit transparan untuk subjudul */
# margin-top: 6px;
# font-style: italic;
# color: #34495e; /* Warna subjudul disesuaikan */
# }
# /* ===== LOGO WRAPPER ===== */
# .header-logo {
# display: flex;
# align-items: center;
# justify-content: flex-end; /* Align logo to the right within its container */
# flex-shrink: 0; /* Prevent logo container from shrinking */
# }
# /* ===== LOGO STYLE ===== */
# .header-logo img {
# border-radius: 10px;
# border: 2px solid rgba(44, 62, 80, 0.15); /* Border logo disesuaikan */
# box-shadow: 0 3px 10px rgba(0,0,0,0.1); /* Bayangan logo lebih lembut */
# max-height: 80px; /* Set max height */
# max-width: 120px; /* Set max width */
# }
# /* ===== METRIC CARDS ===== */
# .metric-card {
# background: #ffffff;
# padding: 18px 22px;
# border-radius: 12px;
# border-left: 6px solid #1e3c72;
# box-shadow: 0 3px 8px rgba(0,0,0,0.10);
# transition: 0.25s ease-in-out;
# }
# .metric-card:hover {
# transform: translateY(-4px);
# box-shadow: 0 6px 15px rgba(0,0,0,0.18);
# }
# /* ===== INSIGHT BOX ===== */
# .insight-box {
# background: #fafafa;
# padding: 18px;
# border-radius: 12px;
# border-left: 6px solid #ff6b6b;
# margin: 15px 0;
# box-shadow: 0 2px 6px rgba(0,0,0,0.08);
# }
# /* ===== RISK MATRIX ===== */
# .risk-matrix {
# border-collapse: collapse;
# width: 100%;
# margin: 20px 0;
# }
# .risk-matrix th, .risk-matrix td {
# border: 1px solid #ddd;
# padding: 12px;
# text-align: center;
# }
# .risk-matrix th {
# background-color: #f2f2f2;
# }
# .critical { background-color: #ffcccc; font-weight: bold; }
# .high { background-color: #ffebcc; }
# .medium { background-color: #ffffcc; }
# .low { background-color: #e6ffe6; }
# /* ===== CHAT UI ===== */
# .chat-container {
# background: white;
# padding: 20px;
# border-radius: 12px;
# height: 400px;
# overflow-y: auto;
# border: 1px solid #ccc;
# }
# .user-message {
# background: #e3f2fd;
# color: black;
# padding: 12px;
# border-radius: 12px;
# margin: 10px 0;
# text-align: right;
# border: 1px solid #bbdefb;
# }
# .ai-message {
# background: #f5f5f5;
# color: black;
# padding: 12px;
# border-radius: 12px;
# margin: 10px 0;
# text-align: left;
# border: 1px solid #e0e0e0;
# }
# /* ===== INPUT BOX ===== */
# .chat-box, .user-question, .ai-answer {
# background: white;
# border: 1px solid #ccc;
# border-radius: 10px;
# padding: 12px;
# margin-bottom: 12px;
# }
# /* ===== FOOTER ===== */
# .footer {
# text-align: center;
# padding: 20px;
# color: gray;
# font-size: 0.9em;
# }
# /* ===== HOVER EFFECTS ===== */
# .metric-card:hover, .insight-box:hover {
# box-shadow: 0 6px 15px rgba(0,0,0,0.2);
# transition: all 0.3s ease-in-out;
# }
# </style>
# """, unsafe_allow_html=True)
# # =================== HEADER =====================
# st.markdown(f"""
# <div class="header-container">
# <div class="header-title">
# <h1>Safety Analysis and AI - Advanced Fatigue Analysis</h1>
# <p>Proactive Safety Intelligence for Mining Operations</p>
# </div>
# <div class="header-logo">
# {logo_html}
# </div>
# </div>
# """, unsafe_allow_html=True)
# =================== GLOBAL CSS =====================
st.markdown("""
<style>
body {
background-color: #f6f8fa;
}
/* ===== HEADER WRAPPER ===== */
.header-container {
display: flex;
justify-content: space-between; /* Logo di kanan, teks di tengah */
align-items: center;
padding: 25px 35px;
background: white;
border-radius: 0 0 14px 14px;
box-shadow: 0 5px 18px rgba(0,0,0,0.15);
border: 1px solid #e0e0e0;
margin-bottom: 25px;
position: relative;
}
/* ===== HEADER TEXT ===== */
.header-title {
flex: 1; /* Mengambil ruang sebanyak mungkin */
display: flex;
flex-direction: column;
align-items: center; /* Center horizontal */
justify-content: center; /* Center vertical */
text-align: center;
}
.header-title h1 {
font-size: 2.7em;
font-weight: 650;
margin: 0;
text-shadow: 1px 1px 2px rgba(0,0,0,0.1);
color: #2c3e50;
}
.header-title p {
font-size: 1.25em;
opacity: 0.85;
margin-top: 6px;
font-style: italic;
color: #34495e;
}
/* ===== LOGO WRAPPER ===== */
.header-logo {
display: flex;
align-items: center;
justify-content: flex-end;
flex-shrink: 0;
}
.header-logo img {
border-radius: 10px;
border: 2px solid rgba(44, 62, 80, 0.15);
box-shadow: 0 3px 10px rgba(0,0,0,0.1);
max-height: 80px;
max-width: 120px;
}
/* Metric cards, insight box, dll. tetap sama... */
</style>
""", unsafe_allow_html=True)
# =================== HEADER =====================
st.markdown(f"""
<div class="header-container">
<div class="header-title">
<h1>Safety Analysis and AI - Advanced Fatigue Analysis</h1>
<p>Proactive Safety Intelligence for Mining Operations</p>
</div>
<div class="header-logo">
{logo_html} <!-- Logo tetap di kanan -->
</div>
</div>
""", unsafe_allow_html=True)
# # ... (Kode selanjutnya disalin dari bagian bawah file Anda, misalnya LOAD DATA ke bawah)
# # =================== LOAD DATA ======================
@st.cache_data
def load_data():
try:
# ==================================
# 1. LOAD CSV & NORMALIZE COLUMNS
# ==================================
df = pd.read_csv("data.csv")
original_columns = df.columns.tolist()
# Normalize: lower, strip, underscore
df.columns = (
df.columns.astype(str)
.str.strip()
.str.lower()
.str.replace(r"\s+", "_", regex=True)
)
# ==================================
# 2. AUTO-DETECT COLUMNS (case-insensitive)
# ==================================
col_operator = next((c for c in df.columns if "operator" in c or "driver" in c), None)
col_shift = next((c for c in df.columns if "shift" in c), None)
# ✅ FIX: Search for normalized "parent_fleet", NOT original "Parent Fleet"
col_fleet_type = next((c for c in df.columns if "parent_fleet" in c), None)
col_fleet_no = next((c for c in df.columns if "fleet_number" in c), None)
# ==================================
# 3. DERIVE COLUMNS
# ==================================
# Unit Number
if col_fleet_no:
df["unit_no"] = df[col_fleet_no].astype(str).str.split("-", n=1).str[-1].str.strip()
else:
df["unit_no"] = "UNKNOWN"
# Speed
col_speed = None
for orig in original_columns:
norm = orig.lower().replace(" ", "_")
if "(in_km/hour).1" in norm or "speed" in norm:
if norm in df.columns:
col_speed = norm
break
if not col_speed:
col_speed = next((c for c in df.columns if "speed" in c), None)
# Time
time_cols = [c for c in df.columns if "gmt" in c and "wita" in c]
if len(time_cols) >= 2:
df["start"] = pd.to_datetime(df[time_cols[0]], errors="coerce")
df["end"] = pd.to_datetime(df[time_cols[1]], errors="coerce")
elif len(time_cols) == 1:
df["start"] = pd.to_datetime(df[time_cols[0]], errors="coerce")
df["end"] = df["start"] + pd.Timedelta(minutes=1)
else:
df["start"] = pd.NaT
df["end"] = pd.NaT
# Time features
if not df["start"].isna().all():
df["hour"] = df["start"].dt.hour
df["date"] = df["start"].dt.date
df["day_of_week"] = df["start"].dt.day_name()
# df["week"], df["month"], df["year"] — optional, not used in filters
else:
df["hour"] = 0
df["date"] = None
# Shift as int
if col_shift:
df[col_shift] = pd.to_numeric(df[col_shift], errors="coerce").astype("Int64")
# ✅ FIX: CREATE site & group_model HERE (not in sidebar!)
if col_fleet_type:
# Split ONCE on first '-', keep FULL left part (e.g., "Amsterdam - CAT789" → "AMSTERDAM")
split = df[col_fleet_type].astype(str).str.split("-", n=1, expand=True)
df["site"] = split[0].str.strip().str.upper()
df["group_model"] = split[1].str.strip().fillna("UNKNOWN").replace("", "UNKNOWN")
else:
df["site"] = "UNKNOWN"
df["group_model"] = "UNKNOWN"
return df, col_operator, col_shift, col_fleet_type, col_speed, col_fleet_no
except Exception as e:
st.error(f"Error loading data: {e}")
return pd.DataFrame(), None, None, None, None, None
# ==================================
# CALL load_data()
# ==================================
df, col_operator, col_shift, col_fleet_type, col_speed, col_fleet_no = load_data()
df_original_full = df.copy()
if df.empty:
st.stop()
st.success("Data Loaded Successfully")
df_full_report = df.copy()
# =================== FILTERS (Sidebar) =====================
filter_dict = {}
st.sidebar.markdown(
"""
<div style="
font-family: 'Segoe UI', sans-serif;
font-size: 1.35em;
font-weight: 600;
color: #2c3e50;
padding: 10px 0 14px 0;
text-align: center;
border-bottom: 2px solid #3498db;
margin-bottom: 16px;
">
Filter if Need Specific Conditions
</div>
""",
unsafe_allow_html=True
)
with st.sidebar.form("filters_form"):
# ---------------- Date Range ----------------
if 'date' in df.columns and not df['date'].isna().all():
min_date = pd.to_datetime(df['date']).min().date()
max_date = pd.to_datetime(df['date']).max().date()
date_range = st.date_input("Select Date Range", (min_date, max_date))
filter_dict['date_range'] = date_range
else:
filter_dict['date_range'] = (None, None)
# ✅ FIXED: Use df['site'] & df['group_model'] (already created in load_data)
# ---------------- Site Filter ----------------
all_sites = sorted(df['site'].dropna().unique())
selected_site = st.selectbox(
"Filter Site",
options=[None] + all_sites,
format_func=lambda x: "All" if x is None else x
)
filter_dict['site'] = selected_site
# ---------------- Group Model Filter ✅ NOW WORKING ----------------
all_models = sorted(df['group_model'].dropna().unique())
selected_model = st.selectbox(
"Filter Group Model",
options=[None] + all_models,
format_func=lambda x: "All" if x is None else x
)
filter_dict['group_model'] = selected_model
# ---------------- Shift ----------------
if col_shift:
shifts = sorted(df[col_shift].dropna().unique())
selected_shift = st.selectbox(
f"Select {col_shift.replace('_', ' ').title()}",
options=[None] + shifts,
format_func=lambda x: "All" if x is None else f"Shift {x}"
)
filter_dict['shift'] = selected_shift
else:
filter_dict['shift'] = None
# ---------------- Operator ----------------
if col_operator:
ops = sorted(df[col_operator].dropna().unique())
selected_op = st.selectbox(
f"Select {col_operator.replace('_', ' ').title()}",
options=[None] + ops,
format_func=lambda x: "All" if x is None else x
)
filter_dict['operator'] = selected_op
else:
filter_dict['operator'] = None
# ---------------- Hour ----------------
if 'hour' in df.columns and not df['hour'].isna().all():
hours = sorted(df['hour'].dropna().unique())
hour_range = st.slider("Select Hour Range", int(min(hours)), int(max(hours)), (int(min(hours)), int(max(hours))))
filter_dict['hour_range'] = hour_range
else:
filter_dict['hour_range'] = (0, 23)
# ---------------- Unit No ----------------
if 'unit_no' in df.columns:
units = sorted(df['unit_no'].dropna().unique())
selected_unit = st.selectbox("Select Unit Number", [None] + units, format_func=lambda x: "All" if x is None else x)
filter_dict['unit_no'] = selected_unit
else:
filter_dict['unit_no'] = None
# ---------------- Submit ----------------
apply_filters = st.form_submit_button("Apply Filters")
# =================== APPLY FILTERS =====================
if apply_filters:
# Filter Date Range
if filter_dict.get('date_range'):
start_date, end_date = filter_dict['date_range']
df = df[(df['date'] >= start_date) & (df['date'] <= end_date)]
# Filter Site
if filter_dict.get('site') is not None:
df = df[df['site'] == filter_dict['site']]
# Filter Group Model
if filter_dict.get('group_model') is not None:
df = df[df['group_model'] == filter_dict['group_model']]
# Filter Shift
if filter_dict.get('shift') is not None:
df = df[df[col_shift] == filter_dict['shift']]
# Filter Operator
if filter_dict.get('operator') is not None:
df = df[df[col_operator] == filter_dict['operator']]
# Filter Hour Range
if filter_dict.get('hour_range'):
hr_start, hr_end = filter_dict['hour_range']
df = df[(df['hour'] >= hr_start) & (df['hour'] <= hr_end)]
# Filter Unit No
if filter_dict.get('unit_no') is not None:
df = df[df[col_fleet_no] == filter_dict['unit_no']]
# Sisanya dari kode Anda (Visualisasi, dll.) tetap sama
# Objective 1
# ===================== GLOBAL FUNCTION: Hour Category Labels =====================
def hour_range_label_full(hour):
if not (0 <= hour < 24):
return 'Unknown'
if 6 <= hour < 9:
return 'Shift 1 Morning Early (6-9)'
elif 9 <= hour < 12:
return 'Shift 1 Morning Late (9-12)'
elif 12 <= hour < 15:
return 'Shift 1 Afternoon Early (12-15)'
elif 15 <= hour < 18:
return 'Shift 1 Afternoon Late (15-18)'
elif 18 <= hour < 21:
return 'Shift 2 Evening Early (18-21)'
elif 21 <= hour < 24:
return 'Shift 2 Evening Late (21-24)'
elif 0 <= hour < 3:
return 'Shift 2 Dawn Early (0-3)'
elif 3 <= hour < 6:
return 'Shift 2 Dawn Late (3-6)'
return 'Unknown'
# ===================== MAIN VISUALIZATION =====================
st.subheader("OBJECTIVE 1: Want to see fatigue patterns across different shifts?")
if 'start' in df.columns and not df.empty:
try:
# --- Data Preparation ---
df_local = df.copy()
if not pd.api.types.is_datetime64_any_dtype(df_local['start']):
df_local['start'] = pd.to_datetime(df_local['start'], errors='coerce')
df_local = df_local.dropna(subset=['start'])
df_local['hour'] = df_local['start'].dt.hour
# --- COLOR MAP: KUNING-ORANGE (Shift 1), BIRU (Shift 2) ---
color_map_full = {
'Shift 1 Morning Early (6-9)': '#FFEB3B', # Yellow 300
'Shift 1 Morning Late (9-12)': '#FFC107', # Amber 300
'Shift 1 Afternoon Early (12-15)': '#FF9800', # Orange 300
'Shift 1 Afternoon Late (15-18)': '#F57C00', # Deep Orange 300
'Shift 2 Evening Early (18-21)': '#42A5F5', # Light Blue 300
'Shift 2 Evening Late (21-24)': '#1976D2', # Blue 300
'Shift 2 Dawn Early (0-3)': '#0288D1', # Cyan 300
'Shift 2 Dawn Late (3-6)': '#01579B', # Blue 800
}
# --- Define intervals in analog-clock order (12→3→6→9) ---
intervals_shift1 = [(12, 15), (15, 18), (6, 9), (9, 12)]
labels_shift1 = [
'Shift 1 Afternoon Early (12-15)',
'Shift 1 Afternoon Late (15-18)',
'Shift 1 Morning Early (6-9)',
'Shift 1 Morning Late (9-12)',
]
intervals_shift2 = [(0, 3), (3, 6), (18, 21), (21, 24)]
labels_shift2 = [
'Shift 2 Dawn Early (0-3)',
'Shift 2 Dawn Late (3-6)',
'Shift 2 Evening Early (18-21)',
'Shift 2 Evening Late (21-24)',
]
# --- Compute frequencies ---
def compute_counts(intervals):
counts = []
for start_h, end_h in intervals:
cnt = df_local[(df_local['hour'] >= start_h) & (df_local['hour'] < end_h)].shape[0]
counts.append(cnt)
return counts
freq_shift1 = compute_counts(intervals_shift1)
freq_shift2 = compute_counts(intervals_shift2)
# --- Polar geometry ---
theta_midpoints = [45, 135, 225, 315] # centers of 90° segments
bar_width = [90] * 4
angular_tick_vals = [0, 90, 180, 270] # fixed angle positions
# ✅ CUSTOM TICK LABELS PER SHIFT (sesuai permintaan Anda)
angular_tick_text_shift1 = ["12", "15", "6/18", "9"] # 0°, 90°, 180°, 270°
angular_tick_text_shift2 = ["24", "3", "18/6", "21"] # 0°=24, 90°=3, 180°=6, 270°=21
# --- Independent radial scales ---
max_r1 = max(freq_shift1) if freq_shift1 and max(freq_shift1) > 0 else 1
max_r2 = max(freq_shift2) if freq_shift2 and max(freq_shift2) > 0 else 1
# ============== FIGURE: SHIFT 1 (KUNING-ORANGE) ==============
fig1 = go.Figure()
fig1.add_trace(go.Barpolar(
r=freq_shift1,
theta=theta_midpoints,
width=bar_width,
marker_color=[color_map_full.get(lbl, '#FFEB3B') for lbl in labels_shift1],
marker_line_color="black",
marker_line_width=1.5,
opacity=0.93,
hovertemplate="<b>%{text}</b><br>Fatigue Incidents: %{r}<extra></extra>",
text=labels_shift1,
))
fig1.update_layout(
title=dict(text="Shift 1 (06:00–18:00)", font=dict(size=18, color="#FF9800", family="Segoe UI")),
polar=dict(
bgcolor="rgba(255,248,225,0.7)",
angularaxis=dict(
rotation=90, # 12 at top
direction="clockwise",
tickmode='array',
tickvals=angular_tick_vals,
ticktext=angular_tick_text_shift1, # ✅ 12, 15, 6, 9
tickfont=dict(size=14, color="#5D4037", weight="bold"),
showline=True,
linewidth=1.2,
linecolor="#FFD54F",
),
radialaxis=dict(
visible=True,
showticklabels=True,
tickfont=dict(size=11),
angle=45,
gridcolor="#FFE082",
gridwidth=0.8,
range=[0, max_r1 * 1.15],
)
),
showlegend=False,
height=550,
width=550,
margin=dict(t=65, b=40, l=40, r=40),
font=dict(family="Segoe UI, -apple-system, sans-serif"),
)
# ============== FIGURE: SHIFT 2 (BIRU) ==============
fig2 = go.Figure()
fig2.add_trace(go.Barpolar(
r=freq_shift2,
theta=theta_midpoints,
width=bar_width,
marker_color=[color_map_full.get(lbl, '#42A5F5') for lbl in labels_shift2],
marker_line_color="black",
marker_line_width=1.5,
opacity=0.93,
hovertemplate="<b>%{text}</b><br>Fatigue Incidents: %{r}<extra></extra>",
text=labels_shift2,
))
fig2.update_layout(
title=dict(text="Shift 2 (18:00–06:00)", font=dict(size=18, color="#1976D2", family="Segoe UI")),
polar=dict(
bgcolor="rgba(230,245,255,0.7)",
angularaxis=dict(
rotation=90,
direction="clockwise",
tickmode='array',
tickvals=angular_tick_vals,
ticktext=angular_tick_text_shift2, # ✅ 24, 3, 6, 21
tickfont=dict(size=14, color="#0D47A1", weight="bold"),
showline=True,
linewidth=1.2,
linecolor="#64B5F6",
),
radialaxis=dict(
visible=True,
showticklabels=True,
tickfont=dict(size=11),
angle=45,
gridcolor="#BBDEFB",
gridwidth=0.8,
range=[0, max_r2 * 1.15], # ✅ SKALA INDEPENDEN
)
),
showlegend=False,
height=550,
width=550,
margin=dict(t=65, b=40, l=40, r=40),
font=dict(family="Segoe UI, -apple-system, sans-serif"),
)
# ============== EXPLANATION — URUTAN KRONOLOGIS, REMARK TETAP ==============
st.markdown("""
<div style="
background: linear-gradient(135deg, #FFFDE7 0%, #E3F2FD 100%);
padding: 20px;
border-radius: 12px;
border-left: 5px solid #FF9800;
margin: 22px 0;
box-shadow: 0 3px 10px rgba(0,0,0,0.06);
">
<h4 style="color:#1976D2; margin:0 0 14px 0; display:flex; align-items:center;">
<span style="background:#FF9800; color:white; width:26px; height:26px; border-radius:50%;
display:inline-flex; align-items:center; justify-content:center; margin-right:10px; font-weight:bold;">!</span>
⚠️ Clockwise Time Mapping (Analog Layout)
</h4>
<table style="width:100%; font-size:14px; border-collapse:collapse; color:#424242;">
<tr style="background-color:#FFF8E1;">
<th style="padding:8px; text-align:left; width:25%;">Time Block</th>
<th style="padding:8px; text-align:left;">Shift 1 (Day)</th>
<th style="padding:8px; text-align:left;">Shift 2 (Night)</th>
</tr>
<tr>
<td style="padding:8px; font-weight:bold;">1st Block</td>
<td><b>06 → 09</b></td>
<td><b>18 → 21</b> (Shift Start)</td>
</tr>
<tr style="background-color:#F5F9FF;">
<td style="padding:8px; font-weight:bold;">2nd Block</td>
<td><b>09 → 12</b></td>
<td><b>21 → 24</b> (Alertness Decline)</td>
</tr>
<tr>
<td style="padding:8px; font-weight:bold;">3rd Block</td>
<td><b>12 → 15</b></td>
<td><b>24 → 03</b> (Circadian Nadir)</td>
</tr>
<tr style="background-color:#F5F9FF;">
<td style="padding:8px; font-weight:bold;">4th Block</td>
<td><b>15 → 18</b></td>
<td><b>03 → 06</b></td>
</tr>
</table>
<p style="margin-top:12px; font-size:13px; color:#546E7A;">
<b>Scale is independent per shift</b> — bar length shows relative risk <i>within</i> the shift.
</p>
</div>
""", unsafe_allow_html=True)
# ============== RENDER CHARTS HORIZONTALLY (NO OVERLAP) ==============
col1, col2 = st.columns(2)
with col1:
st.plotly_chart(fig1, use_container_width=True, config={'displayModeBar': False})
with col2:
st.plotly_chart(fig2, use_container_width=True, config={'displayModeBar': False})
# ============== FOOTNOTE (SEMINAR-READY) ==============
st.caption(
" *Safety Insight*: Highest fatigue risk occurs during **24→06** (Shift 2) — aligns with circadian trough (Czeisler, 1999). "
)
except Exception as e:
st.error(f"⚠️ Rendering error: {e}")
st.code(f"{type(e).__name__}: {str(e)}", language="python")
else:
st.info("⏳ Awaiting data... Ensure column `'start'` contains valid timestamps (e.g., '2025-06-15 14:30:00').")
#Objective
#
#Objective 1
st.subheader("OBJECTIVE 2: How does operator energy fluctuate from start to finish of each shift?")
if 'start' in df.columns and not df.empty:
try:
df_local = df.copy()
df_local['hour'] = df_local['start'].dt.hour
df_local['date'] = df_local['start'].dt.normalize()
# Kategorisasi jam menggunakan fungsi global
df_local['hour_category'] = df_local['hour'].apply(hour_range_label_full)
color_map = {
'Shift 1 Morning Early (6-9)': '#FFEB3B',
'Shift 1 Morning Late (9-12)': '#FFC107',
'Shift 1 Afternoon Early (12-15)':'#FF9800',
'Shift 1 Afternoon Late (15-18)': '#F57C00',
'Shift 2 Evening Early (18-21)': '#42A5F5',
'Shift 2 Evening Late (21-24)': '#1976D2',
'Shift 2 Dawn Early (0-3)': '#0288D1',
'Shift 2 Dawn Late (3-6)': '#01579B',
'Unknown': '#E0E0E0'
}
# Hitung jumlah fatigue per hari dan kategori jam
daily_by_cat = df_local.groupby(['date', 'hour_category']).size().reset_index(name='fatigue_count')
# --- TAMBAHAN: Ambil dominant hour_category per hari untuk Objective 3 ---
# Kita gunakan data df_local yang sudah memiliki hour_category
daily_dominant_cat = df_local.groupby('date')['hour_category'].agg(
lambda x: x.value_counts().idxmax()
).reset_index()
daily_dominant_cat.rename(columns={'hour_category': 'dominant_hour_category'}, inplace=True)
# --- END TAMBAHAN ---
all_dates = pd.date_range(start=daily_by_cat['date'].min(), end=daily_by_cat['date'].max(), freq='D')
all_cats = list(color_map.keys())
full_index = pd.MultiIndex.from_product([all_dates, all_cats], names=['date', 'hour_category'])
daily_by_cat = daily_by_cat.set_index(['date', 'hour_category']).reindex(full_index, fill_value=0).reset_index()
daily_by_cat['day_of_week_num'] = daily_by_cat['date'].dt.dayofweek
daily_by_cat['week_start'] = daily_by_cat['date'] - pd.to_timedelta(daily_by_cat['day_of_week_num'], unit='d')
daily_by_cat['week_label'] = daily_by_cat['week_start'].dt.strftime('Week %U')
fig = px.bar(
daily_by_cat,
x='date',
y='fatigue_count',
color='hour_category',
title="Daily Fatigue Alerts by Detailed Hour Category",
color_discrete_map=color_map,
labels={'fatigue_count': 'Fatigue Alerts', 'date': 'Date'},
hover_data={'fatigue_count': True, 'week_label': True}
)
fig.update_layout(
barmode='stack',
xaxis_title="Date",
yaxis_title="Fatigue Alerts",
height=400,
legend_title="Hour Category"
)
unique_weeks = daily_by_cat['week_start'].unique()
shapes = []
week_labels = []
bg_colors = ['#f0e6ff', '#e6f0ff', '#e6fff0', '#fff0e6', '#ffe6e6', '#f0ffe6', '#e6e6ff']
for i, week in enumerate(sorted(unique_weeks)):
week_days = daily_by_cat[daily_by_cat['week_start'] == week]['date']
if len(week_days) > 0:
start_date = week_days.min()
end_date = week_days.max()
shapes.append(dict(
type="rect",
xref="x",
yref="paper",
x0=start_date,
x1=end_date,
y0=0,
y1=1,
fillcolor=bg_colors[i % len(bg_colors)],
opacity=0.2,
layer="below",
line_width=0,
))
week_labels.append(
dict(
xref='x',
yref='paper',
x=start_date + (end_date - start_date) / 2,
y=1.02,
text=f"Week {week.strftime('%U')}",
showarrow=False,
font=dict(size=10),
xanchor='center',
yanchor='bottom'
)
)
fig.update_layout(shapes=shapes, annotations=week_labels)
st.plotly_chart(fig, use_container_width=True)
except Exception as e:
st.error(f"⚠️ Error in Daily Fatigue by Detailed Hour Category: {e}")
else:
st.info("ℹ️ Insufficient time data to display this visualization.")
# =================== OBJECTIVE 3: Daily Roster Insight per Week (Scatter Plot) =====================
# =================== OBJECTIVE 3: Daily Roster Insight per Week (Scatter Plot) =====================
st.subheader("OBJECTIVE 3: Looking for patterns in your team’s weekly roster?")
if not df.empty and col_operator in df.columns and col_shift and col_shift in df.columns:
try:
df['date'] = pd.to_datetime(df['date'])
# Hitung total event per hari
daily_totals = df.groupby('date').size().reset_index(name='total_count')
# Ambil dominant shift per hari
dominant_shift = df.groupby('date')[col_shift].agg(lambda x: x.value_counts().idxmax()).reset_index()
dominant_shift.rename(columns={col_shift: 'dominant_shift'}, inplace=True)
daily_analysis = daily_totals.merge(dominant_shift, on='date', how='left')
daily_analysis['week_start'] = daily_analysis['date'] - pd.to_timedelta(daily_analysis['date'].dt.weekday, unit='d')
summary = []
weekly_groups = daily_analysis.groupby('week_start')
for week_start, week_data in weekly_groups:
# Urutkan data berdasarkan tanggal dalam minggu ini
week_data_sorted = week_data.sort_values('date').reset_index(drop=True)
for idx, row in week_data_sorted.iterrows():
current_date = row['date']
current_shift = row['dominant_shift']
current_count = row['total_count']
# --- CARI DATA DI HARI SEBELUM DAN SESUDAH (BERDASARKAN TANGGAL, BUKAN INDEKS) ---
prev_date = current_date - pd.Timedelta(days=1)
next_date = current_date + pd.Timedelta(days=1)
# Cari shift di hari sebelumnya
prev_row = week_data_sorted[week_data_sorted['date'] == prev_date]
prev_shift = prev_row['dominant_shift'].iloc[0] if not prev_row.empty else None
# Cari shift di hari berikutnya
next_row = week_data_sorted[week_data_sorted['date'] == next_date]
next_shift = next_row['dominant_shift'].iloc[0] if not next_row.empty else None
# ---- LOGIKA REMARK BERDASARKAN PERUBAHAN SHIFT DALAM MINGGU YANG SAMA----
# Awal Roster: Ada data di hari sebelumnya (prev_date) dalam minggu, dan shift-nya berbeda
# Akhir Roster: Ada data di hari berikutnya (next_date) dalam minggu, dan shift-nya berbeda
# Bukan Awal/Akhir: Ada data di hari sebelumnya ATAU berikutnya, dan shift-nya sama
# Unknown: Tidak ada data di hari sebelumnya (prev_date) DAN tidak ada data di hari berikutnya (next_date) dalam minggu yang sama
if pd.isna(current_shift):
remark = "Unknown"
elif prev_shift is not None and prev_shift != current_shift:
remark = "Start of Roster"
elif next_shift is not None and next_shift != current_shift:
remark = "End of Roster"
elif (prev_shift is not None and prev_shift == current_shift) or (next_shift is not None and next_shift == current_shift):
remark = "Neither Start nor End of Roster"
elif prev_shift is None and next_shift is None:
remark = "Unknown"
else:
remark = "Unknown"
# --- Operator dari data df (YANG SUDAH DIFILTER) ---
df_orig_for_date = df[df['date']==current_date] # Gunakan df yang difilter
if not df_orig_for_date.empty:
peak_nik_counts = df_orig_for_date[col_operator].value_counts()
peak_nik = peak_nik_counts.index[0] if not peak_nik_counts.empty else "N/A"
else:
peak_nik = "N/A"
summary.append({
'week_start': week_start,
'date': current_date,
'day_name': current_date.strftime('%A'),
'total_count': current_count,
'shift_category': current_shift,
'remark': remark,
'operator': peak_nik
})
summary_df = pd.DataFrame(summary)
if not summary_df.empty:
# Buat color map untuk remark (sesuai permintaan Anda)
color_map_remark = {
'Start of Roster': '#ffcccc', # Merah muda
'End of Roster': '#cce5ff', # Biru muda
'Neither Start nor End of Roster': '#fff2cc', # Kuning muda
'Unknown': '#c0c0c0' # Abu-abu muda
}
# ===== SCATTER PLOT (WARNA BERDASARKAN remark) =====
fig = px.scatter(
summary_df,
x='date',
y='remark',
color='remark', # Warna berdasarkan remark (satu-satunya kolom di sumbu Y)
color_discrete_map=color_map_remark, # Gunakan color_map_remark
size='total_count',
hover_data=['shift_category', 'operator', 'total_count'],
title="Daily Roster Status by Date and Trend",
category_orders={'remark': ['Start of Roster', 'End of Roster', 'Neither Start nor End of Roster', 'Unknown']}
)
fig.update_layout(height=450, xaxis_title="Date", yaxis_title="Roster Status")
st.plotly_chart(fig, use_container_width=True)
# ===== TABEL =====
table_df = summary_df.rename(columns={
'week_start':'Week Start',
'day_name':'Day',
'date':'Date',
'total_count':'Event Count',
'shift_category':'Dominant Shift',
'remark':'Roster Status',
'operator':'Operator'
})
def highlight_remark(row):
colors = {
'Start of Roster':'background-color: #ffcccc',
'End of Roster':'background-color: #cce5ff',
'Neither Start nor End of Roster':'background-color: #fff2cc',
'Unknown':'background-color: #c0c0c0'
}
return [colors.get(row['Roster Status'], '') for _ in row]
st.dataframe(table_df.style.apply(highlight_remark, axis=1), use_container_width=True)
else:
st.info("ℹ️ No daily data to analyze.")
except Exception as e:
st.error(f"Error in Daily Roster Insight: {e}")
else:
if col_shift is None:
st.info("ℹ️ Shift column not found, cannot display Daily Roster Insight.")
elif col_shift not in df.columns:
st.info(f"ℹ️ Column '{col_shift}' not found in the filtered data, cannot display Daily Roster Insight.")
else:
st.info("ℹ️ Insufficient data (date, operator, or shift column not found) to display daily roster insight.")
# import plotly.express as px
# from datetime import datetime
st.subheader("OBJECTIVE 4: How is the Fatigue Event Risk Map per Operator?")
import math
import plotly.express as px
try:
# ============================
# 1. PREPROCESS & COPY DF
# ============================
df_local = df.copy()
df_local['date_only'] = df_local['start'].dt.normalize()
df_local['week_number'] = df_local['date_only'].dt.isocalendar().week
df_local['week_label'] = "Week " + df_local['week_number'].astype(str)
# Unit cleanup
df_local['unit_no'] = (
df_local[col_fleet_no]
.astype(str)
.str.split("-", n=1).str[-1].str.strip()
)
if 'id' not in df_local.columns:
st.error("❌ Column 'id' not found!")
st.stop()
# ============================
# 2. FILTER 8 MINGGU TERAKHIR
# ============================
df_local['week_num_int'] = df_local['week_number'].astype(int)
unique_weeks = sorted(df_local['week_num_int'].unique())
selected_last8 = unique_weeks[-8:] if len(unique_weeks) >= 8 else unique_weeks
df_8w = df_local[df_local['week_num_int'].isin(selected_last8)].copy()
# =====================================
# 3. FREQUENCY PER OPERATOR PER MINGGU
# =====================================
weekly_freq = (
df_8w.groupby([col_operator, 'week_label'])['id']
.nunique()
.reset_index(name='weekly_frequency')
)
# ============================================
# 4. SUMMARY FREQUENCY & CEIL AVERAGE FREQ
# ============================================
freq_summary = (
weekly_freq
.groupby(col_operator)['weekly_frequency']
.agg(['sum', 'mean', 'count'])
.reset_index()
.rename(columns={
'sum': 'frequency_by_shift',
'mean': 'avg_frequency',
'count': 'frequency_by_weeks'
})
)
freq_summary['avg_frequency'] = freq_summary['avg_frequency'].apply(lambda x: math.ceil(x))
# ================================
# 5. RATA-RATA SPEED PER OPERATOR
# ================================
speed_summary = (
df_8w.groupby(col_operator)[col_speed]
.mean()
.reset_index(name='avg_speed')
)
# =====================
# 6. GABUNGKAN DATA
# =====================
risk_matrix = freq_summary.merge(speed_summary, on=col_operator, how='left')
risk_matrix = risk_matrix.rename(columns={col_operator: "Operator Name"})
# ================================
# 7. Tentukan Quadrant untuk Count
# ================================
def assign_quadrant(row):
if row['avg_frequency'] >= 2.5 and row['avg_speed'] >= 20:
return "Quadrant I – Prevent at Source"
elif row['avg_frequency'] < 2.5 and row['avg_speed'] >= 20:
return "Quadrant II – Detect & Monitor"
elif row['avg_frequency'] >= 2.5 and row['avg_speed'] < 20:
return "Quadrant III – Monitor"
else:
return "Quadrant IV – Low Control"
risk_matrix['quadrant'] = risk_matrix.apply(assign_quadrant, axis=1)
quadrant_count = risk_matrix['quadrant'].value_counts().reindex([
"Quadrant I – Prevent at Source",
"Quadrant II – Detect & Monitor",
"Quadrant III – Monitor",
"Quadrant IV – Low Control"
], fill_value=0)
# ================================
# 8. VISUAL SCATTER PLOT
# ================================
fig = px.scatter(
risk_matrix,
x='avg_frequency',
y='avg_speed',
hover_name="Operator Name",
title="Operator Risk Matrix: Frequency vs Speed",
size=[12] * len(risk_matrix),
size_max=15
)
max_x = risk_matrix['avg_frequency'].max() + 1
max_y = risk_matrix['avg_speed'].max() + 1
# ================================
# 9. Quadrant Coloring
# ================================
fig.add_shape(type="rect", x0=2.5, x1=max_x, y0=20, y1=max_y,
fillcolor="rgba(255,0,0,0.25)", line_width=0) # I
fig.add_shape(type="rect", x0=0, x1=2.5, y0=20, y1=max_y,
fillcolor="rgba(255,150,50,0.25)", line_width=0) # II
fig.add_shape(type="rect", x0=2.5, x1=max_x, y0=0, y1=20,
fillcolor="rgba(255,200,200,0.25)", line_width=0) # III
fig.add_shape(type="rect", x0=0, x1=2.5, y0=0, y1=20,
fillcolor="rgba(0,120,255,0.15)", line_width=0) # IV
# Garis batas
fig.add_vline(x=2.5, line_dash="dash", line_color="black")
fig.add_hline(y=20, line_dash="dash", line_color="black")
# ================================
# 10. Tampilkan Count di Quadrant
# ================================
fig.add_annotation(
x=2.5 + (max_x-2.5)/2, y=20 + (max_y-20)/2,
text=f"<b>{quadrant_count['Quadrant I – Prevent at Source']}</b>",
showarrow=False, font=dict(size=20, color="red")
)
fig.add_annotation(
x=2.5/2, y=20 + (max_y-20)/2,
text=f"<b>{quadrant_count['Quadrant II – Detect & Monitor']}</b>",
showarrow=False, font=dict(size=20, color="orange")
)
fig.add_annotation(
x=2.5 + (max_x-2.5)/2, y=0 + (20-0)/2,
text=f"<b>{quadrant_count['Quadrant III – Monitor']}</b>",
showarrow=False, font=dict(size=20, color="darkred")
)
fig.add_annotation(
x=2.5/2, y=0 + (20-0)/2,
text=f"<b>{quadrant_count['Quadrant IV – Low Control']}</b>",
showarrow=False, font=dict(size=20, color="blue")
)
# ================================
# 11. Label Quadrant
# ================================
fig.add_annotation(x=4, y=max_y-2, text="Quadrant I<br>Prevent at Source",
showarrow=False, font=dict(size=12))
fig.add_annotation(x=1.25, y=max_y-2, text="Quadrant II<br>Detect & Monitor",
showarrow=False, font=dict(size=12))
fig.add_annotation(x=4, y=5, text="Quadrant III<br>Monitor",
showarrow=False, font=dict(size=12))
fig.add_annotation(x=1.25, y=5, text="Quadrant IV<br>Low Control",
showarrow=False, font=dict(size=12))
fig.update_xaxes(dtick=1)
fig.update_layout(
xaxis_title="Average Frequency (Ceil)",
yaxis_title="Average Speed (km/h)",
height=650
)
st.plotly_chart(fig, use_container_width=True)
# ================================
# 12. DISPLAY TABLE
# ================================
st.subheader("Operator Hazard Summary Table (8 Weeks Observed)")
table_display = (
risk_matrix[[
"Operator Name",
"frequency_by_shift",
"avg_frequency",
"frequency_by_weeks",
"avg_speed",
"quadrant"
]]
.rename(columns={
"frequency_by_shift": "Frequency by Shift",
"avg_frequency": "Avg Frequency",
"frequency_by_weeks": "Frequency by Weeks",
"avg_speed": "Avg Speed"
})
)
st.dataframe(
table_display.sort_values("Avg Frequency", ascending=False),
use_container_width=True
)
except Exception as e:
st.error(f"⚠️ Error Risk Map Objective 4: {e}")
st.exception(e)
# ... (kode sebelumnya tetap sama) ...
# ... (kode sebelumnya tetap sama) ...
# ... (kode sebelumnya tetap sama) ...
# =================== OBJECTIVE 5: Operator Fatigue Risk Gradient Dashboard =====================
# ... (kode sebelumnya tetap sama) ...
st.subheader("OBJECTIVE 5:See your team’s Fatigue Hazard Profile!")
# Custom CSS — tetap seperti sebelumnya (sudah sesuai preferensi)
st.markdown("""
<style>
.big-title {
font-size: 28px;
font-weight: bold;
color: #ffffff;
text-align: center;
margin-bottom: 10px;
background: linear-gradient(135deg, #2c3e50, #1a252c);
padding: 15px;
border-radius: 10px;
box-shadow: 0 4px 15px rgba(0,0,0,0.3);
}
.subnote {
font-size: 16px;
color: #7f8c8d;
text-align: center;
margin-bottom: 20px;
}
.section-divider {
height: 2px;
background: linear-gradient(to right, #3498db, #2ecc71, #f1c40f, #e74c3c);
margin: 20px 0;
}
.legend-container {
display: flex;
gap: 15px;
margin: 15px 0;
}
.legend-box {
background: white;
border: 1px solid #ddd;
border-radius: 8px;
padding: 15px;
flex: 1;
min-width: 300px;
box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}
.legend-title {
font-weight: bold;
color: #2c3e50;
margin-bottom: 10px;
font-size: 14px;
border-bottom: 1px solid #eee;
padding-bottom: 5px;
}
.legend-item {
display: flex;
align-items: center;
margin: 5px 0;
font-size: 12px;
}
.legend-color {
width: 18px;
height: 18px;
border-radius: 3px;
margin-right: 8px;
border: 1px solid #ccc;
}
.ai-insight-box {
background: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 8px;
padding: 15px;
margin: 10px 0;
color: #2c3e50;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.ai-insight-title {
font-weight: bold;
color: #2c3e50;
margin-bottom: 8px;
font-size: 14px;
background: #e9ecef;
padding: 8px;
border-radius: 5px;
border-left: 4px solid #495057;
}
.trend-up {
color: #e74c3c;
font-weight: bold;
}
.trend-down {
color: #27ae60;
font-weight: bold;
}
.recommendation-box {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border: 1px solid #4a5568;
border-radius: 8px;
padding: 15px;
margin: 10px 0;
color: white;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}
.recommendation-title {
font-weight: bold;
color: white;
margin-bottom: 8px;
font-size: 14px;
background: rgba(255,255,255,0.2);
padding: 8px;
border-radius: 5px;
border-left: 4px solid white;
}
.recommendation-reason {
font-size: 12px;
margin-top: 10px;
padding: 8px;
background: rgba(255,255,255,0.1);
border-radius: 5px;
border-left: 3px solid rgba(255,255,255,0.3);
}
</style>
""", unsafe_allow_html=True)
# ===============================================================
# LOGIC UTAMA
# ===============================================================
if df.empty:
st.info("No data available after applying filters.")
else:
try:
required = [col_operator, col_fleet_type, "start"]
if not all(c in df.columns for c in required if c is not None):
st.warning("Required columns (operator, fleet_type, start) are missing.")
st.stop()
df_op = df[[col_operator, col_fleet_type, "start"]].dropna()
if df_op.empty:
st.info("No operator data after filtering.")
st.stop()
if col_operator is None:
st.error("Operator column could not be auto-detected. Please check your data.")
st.stop()
df_op["year_week"] = df_op["start"].dt.strftime("%Y-W%U")
# Fuzzy match fleet names
fleet_clean = df_op[col_fleet_type].str.strip().str.upper()
df_op["is_ob"] = fleet_clean.str.contains(r"OB HAULLER", na=False)
df_op["is_coal"] = fleet_clean.str.contains(r"HAULING COAL", na=False)
ob_data = df_op[df_op["is_ob"]]
coal_data = df_op[df_op["is_coal"]]
def get_top10_with_slope(data):
if data.empty:
return pd.DataFrame()
if col_operator not in data.columns:
st.error(f"Operator column '{col_operator}' not found in data subset.")
return pd.DataFrame()
weekly = data.groupby([col_operator, "year_week"]).size().reset_index(name="weekly_sum")
metrics = []
for nik, grp in weekly.groupby(col_operator):
if pd.isna(nik):
continue
grp = grp.sort_values("year_week")
counts = grp["weekly_sum"].values
weeks = np.arange(len(counts))
weekly_avg = counts.mean()
total_events = counts.sum()
n_weeks = len(counts)
if n_weeks >= 2:
x_mean = weeks.mean()
y_mean = counts.mean()
numerator = np.sum((weeks - x_mean) * (counts - y_mean))
denominator = np.sum((weeks - x_mean) ** 2)
slope = numerator / denominator if denominator != 0 else 0.0
else:
slope = 0.0 # One Time Event
metrics.append({
col_operator: nik,
"weekly_avg": weekly_avg,
"slope": slope,
"total_events": total_events,
"n_weeks": n_weeks
})
if not metrics:
return pd.DataFrame()
return pd.DataFrame(metrics).nlargest(10, "weekly_avg")
top_ob = get_top10_with_slope(ob_data)
top_coal = get_top10_with_slope(coal_data)
def get_all_operators_with_slope(data):
if data.empty:
return pd.DataFrame()
if col_operator not in data.columns:
return pd.DataFrame()
weekly = data.groupby([col_operator, "year_week"]).size().reset_index(name="weekly_sum")
metrics = []
for nik, grp in weekly.groupby(col_operator):
if pd.isna(nik):
continue
grp = grp.sort_values("year_week")
counts = grp["weekly_sum"].values
weeks = np.arange(len(counts))
weekly_avg = counts.mean()
total_events = counts.sum()
n_weeks = len(counts)
if n_weeks >= 2:
slope = np.cov(weeks, counts)[0, 1] / np.var(weeks) if np.var(weeks) != 0 else 0.0
else:
slope = 0.0
metrics.append({
col_operator: nik,
"weekly_avg": weekly_avg,
"slope": slope,
"total_events": total_events,
"n_weeks": n_weeks
})
return pd.DataFrame(metrics) if metrics else pd.DataFrame()
all_ob = get_all_operators_with_slope(ob_data)
all_coal = get_all_operators_with_slope(coal_data)
# ===============================================================
# LEGEND — UPDATED: Stable → One Time Event, Gray → Yellow
# ===============================================================
st.subheader("Hazard Gradient Legend")
st.markdown("""
<div class="legend-container">
<div class="legend-box">
<div class="legend-title">Worsening Trends (Positive Slope):</div>
<div class="legend-item">
<div class="legend-color" style="background-color: #d32f2f;"></div>
<span>Very High Worsening (≥1.5)</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background-color: #e57373;"></div>
<span>High Worsening (1.0–1.5)</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background-color: #ef9a9a;"></div>
<span>Moderate Worsening (0.5–1.0)</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background-color: #ffcdd2;"></div>
<span>Slight Worsening (0–0.5)</span>
</div>
</div>
<div class="legend-box">
<div class="legend-title">Improving Trends (Negative Slope):</div>
<div class="legend-item">
<div class="legend-color" style="background-color: #388e3c;"></div>
<span>Excellent Improvement (≤−1.5)</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background-color: #81c784;"></div>
<span>Great Improvement (−1.5 to −1.0)</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background-color: #a5d6a7;"></div>
<span>Good Improvement (−1.0 to −0.5)</span>
</div>
<div class="legend-item">
<div class="legend-color" style="background-color: #c8e6c9;"></div>
<span>Slight Improvement (−0.5 to 0)</span>
</div>
</div>
<div class="legend-box">
<div class="legend-title">One-Time Events (Zero Slope):</div>
<div class="legend-item">
<div class="legend-color" style="background-color: #FFD700;"></div>
<span>One Time Event (0)</span>
</div>
<br>
<i>Note: Applies when an operator has data in only one week — slope is set to 0 by definition.</i>
</div>
</div>
""", unsafe_allow_html=True)
# ===============================================================
# PLOT FUNCTION — UPDATED: color for slope=0 is now #FFD700
# ===============================================================
def plot_chart(data, title):
if data.empty:
fig = go.Figure()
fig.add_annotation(
text="No Data",
x=0.5, y=0.5,
showarrow=False,
font_size=16
)
fig.update_layout(height=350, title=dict(text=title, x=0.5))
return fig
data_sorted = data.sort_values('weekly_avg', ascending=False)
def get_color(slope):
if slope == 0:
return "#FFD700" # ✅ Kuning untuk One Time Event
elif slope > 0:
if slope < 0.5:
return "#ffcdd2"
elif slope < 1.0:
return "#ef9a9a"
elif slope < 1.5:
return "#e57373"
else:
return "#d32f2f"
else: # slope < 0
if slope > -0.5:
return "#c8e6c9"
elif slope > -1.0:
return "#a5d6a7"
elif slope > -1.5:
return "#81c784"
else:
return "#388e3c"
colors = [get_color(s) for s in data_sorted["slope"]]
bar_trace = go.Bar(
x=data_sorted[col_operator].astype(str),
y=data_sorted["weekly_avg"],
marker=dict(
color=colors,
line=dict(width=2, color="rgba(0,0,0,0.2)")
),
text=[f"{v:.1f}" for v in data_sorted["weekly_avg"]],
textposition="outside",
hovertemplate=(
"<b>%{x}</b><br>" +
"Weekly Avg: %{y:.2f}<br>" +
"Trend Slope: %{customdata[0]:+.3f}<br>" +
"Total Events: %{customdata[1]}<br>" +
"Weeks Active: %{customdata[2]}<br>" +
"<extra></extra>"
),
customdata=np.stack([data_sorted["slope"], data_sorted["total_events"], data_sorted["n_weeks"]], axis=-1)
)
fig = go.Figure(bar_trace)
fig.update_layout(
title=dict(text=f"<b>{title}</b>", x=0.5),
height=450,
margin=dict(l=50, r=20, t=60, b=120),
xaxis_title="<b>Operator Name</b>",
yaxis_title="<b>Weekly Avg Events</b>",
font=dict(family="Segoe UI", size=12),
bargap=0.3,
plot_bgcolor="rgba(0,0,0,0)",
paper_bgcolor="rgba(0,0,0,0)",
xaxis=dict(tickangle=45)
)
return fig
# ===============================================================
# CHARTS
# ===============================================================
col1, col2 = st.columns(2)
with col1:
st.plotly_chart(plot_chart(top_ob, "OB HAULER Operators (Hazard Gradient)"), use_container_width=True)
with col2:
st.plotly_chart(plot_chart(top_coal, "HAULING COAL Operators (Hazard Gradient)"), use_container_width=True)
# ===============================================================
# AI INSIGHTS — tetap dalam bahasa Inggris, tanpa emoticon
# ===============================================================
col_insight1, col_insight2 = st.columns(2)
with col_insight1:
if not top_ob.empty:
st.markdown("### OB HAULER Analysis")
ob_worsening = len(top_ob[top_ob['slope'] > 0])
ob_improving = len(top_ob[top_ob['slope'] < 0])
ob_one_time = len(top_ob[top_ob['slope'] == 0])
ob_avg_risk = top_ob['weekly_avg'].mean()
ob_max_risk = top_ob['weekly_avg'].max()
ob_insights = []
if ob_worsening > ob_improving:
ob_insights.append(f"{ob_worsening} out of 10 top risk operators are showing <span class='trend-up'>worsening</span> trends.")
else:
ob_insights.append(f"{ob_improving} out of 10 top risk operators are showing <span class='trend-down'>improvement</span>.")
if ob_one_time > 0:
ob_insights.append(f"{ob_one_time} operators are classified as <b>One Time Event</b> (single-week activity).")
ob_insights.append(f"Average risk: {ob_avg_risk:.2f} events/week (max: {ob_max_risk:.2f}).")
for insight in ob_insights:
st.markdown(f"""
<div class="ai-insight-box">
<div class="ai-insight-title">Hazard Summary</div>
<p>{insight}</p>
</div>
""", unsafe_allow_html=True)
else:
st.info("No OB HAULER data for analysis.")
with col_insight2:
if not top_coal.empty:
st.markdown("### HAULING COAL Analysis")
coal_worsening = len(top_coal[top_coal['slope'] > 0])
coal_improving = len(top_coal[top_coal['slope'] < 0])
coal_one_time = len(top_coal[top_coal['slope'] == 0])
coal_avg_risk = top_coal['weekly_avg'].mean()
coal_max_risk = top_coal['weekly_avg'].max()
coal_insights = []
if coal_worsening > coal_improving:
coal_insights.append(f"{coal_worsening} out of 10 top risk operators are showing <span class='trend-up'>worsening</span> trends.")
else:
coal_insights.append(f"{coal_improving} out of 10 top risk operators are showing <span class='trend-down'>improvement</span>.")
if coal_one_time > 0:
coal_insights.append(f"{coal_one_time} operators are classified as <b>One Time Event</b> (single-week activity).")
coal_insights.append(f"Average risk: {coal_avg_risk:.2f} events/week (max: {coal_max_risk:.2f}).")
for insight in coal_insights:
st.markdown(f"""
<div class="ai-insight-box">
<div class="ai-insight-title">Hazard Summary</div>
<p>{insight}</p>
</div>
""", unsafe_allow_html=True)
else:
st.info("No HAULING COAL data for analysis.")
# ===============================================================
# RECOMMENDATIONS
# ===============================================================
col_rec1, col_rec2 = st.columns(2)
def generate_recommendations(top_ob, top_coal):
rec = {}
if not top_ob.empty:
w = len(top_ob[top_ob['slope'] > 0])
ot = len(top_ob[top_ob['slope'] == 0])
avg = top_ob['weekly_avg'].mean()
if w > 5:
r = "Prioritize fatigue intervention for operators with worsening trends."
reason = "High proportion of deteriorating operators signals emerging fatigue risks."
elif ot > 4:
r = "Validate data completeness — high One Time Event count may indicate reporting gaps."
reason = "Operators with single-week data cannot yield reliable trend analysis."
elif avg > 8:
r = "Review scheduling and rest protocols to reduce event frequency."
reason = "Elevated average event rate increases cumulative fatigue exposure."
else:
r = "Maintain current protocols with targeted monitoring."
reason = "Risk profile is stable; focus on sustaining safe practices."
rec['ob'] = r
rec['ob_reason'] = reason
if not top_coal.empty:
w = len(top_coal[top_coal['slope'] > 0])
ot = len(top_coal[top_coal['slope'] == 0])
avg = top_coal['weekly_avg'].mean()
if w > 5:
r = "Prioritize fatigue intervention for operators with worsening trends."
reason = "High proportion of deteriorating operators signals emerging fatigue risks."
elif ot > 4:
r = "Validate data completeness — high One Time Event count may indicate reporting gaps."
reason = "Operators with single-week data cannot yield reliable trend analysis."
elif avg > 8:
r = "Review scheduling and rest protocols to reduce event frequency."
reason = "Elevated average event rate increases cumulative fatigue exposure."
else:
r = "Maintain current protocols with targeted monitoring."
reason = "Risk profile is stable; focus on sustaining safe practices."
rec['coal'] = r
rec['coal_reason'] = reason
return rec
ai_rec = generate_recommendations(top_ob, top_coal)
with col_rec1:
if 'ob' in ai_rec:
st.markdown("### OB HAULER Recommendations")
st.markdown(f"""
<div class="recommendation-box">
<div class="recommendation-title">Action Plan</div>
<div>{ai_rec['ob']}</div>
<div class="recommendation-reason">AI Reasoning: {ai_rec['ob_reason']}</div>
</div>
""", unsafe_allow_html=True)
else:
st.info("No OB HAULER recommendations.")
with col_rec2:
if 'coal' in ai_rec:
st.markdown("### HAULING COAL Recommendations")
st.markdown(f"""
<div class="recommendation-box">
<div class="recommendation-title">Action Plan</div>
<div>{ai_rec['coal']}</div>
<div class="recommendation-reason">AI Reasoning: {ai_rec['coal_reason']}</div>
</div>
""", unsafe_allow_html=True)
else:
st.info("No HAULING COAL recommendations.")
except Exception as e:
st.error(f"Error in Top 10 Operator analysis: {str(e)}")
st.exception(e) # optionally show full traceback during dev
import re # Tambahkan ini jika belum ada
# =================== OBJECTIVE 6: Automated Insights & AI Recommendations =====================
st.subheader("OBJECTIVE 6: Instant Insights & Recommendations")
# Membagi tampilan menjadi dua kolom
col_insights, col_recs = st.columns(2)
# Kolom kiri: Insights by Advanced Analytics
with col_insights:
st.subheader("Insights by Advanced Analytics")
# 1. Critical Hour Analysis (2-5 AM)
critical_hours = [2, 3, 4, 5]
critical_alerts = df[df['hour'].isin(critical_hours)]
critical_pct = (len(critical_alerts) / len(df)) * 100 if len(df) > 0 else 0
st.markdown(f"**Critical Hour Risk (3-6 AM)**")
bg_color = "#ffcccc" if critical_pct > 50 else "#ffebcc" if critical_pct > 25 else "#ffffcc" if critical_pct > 10 else "#e6ffe6"
# Tampilkan jumlah dan persentase dalam satu div
st.markdown(
f"""
<div style="background-color: {bg_color}; padding: 10px; border-radius: 8px; margin-bottom: 10px;">
<div style="font-size: 24px; font-weight: bold; color: #000000;">
{len(critical_alerts)}
</div>
<div style="color: #d32f2f; font-size: 16px; font-weight: bold; margin-top: -10px;">
↑ {critical_pct:.1f}% of total alerts
</div>
</div>
""",
unsafe_allow_html=True
)
# Gunakan st.markdown untuk warning/info dengan persentase berwarna merah tebal
if critical_pct > 10:
st.markdown(
f"<span style='color:#d32f2f; font-weight:bold;'>⚠️ High risk: {critical_pct:.1f}% of fatigue alerts occur during critical hours (3-6 AM). This is a known circadian dip period.</span>",
unsafe_allow_html=True
)
else:
st.markdown(
f"<span style='color:#d32f2f; font-weight:bold;'>✅ {critical_pct:.1f}% of alerts occur during critical hours. This is within acceptable range.</span>",
unsafe_allow_html=True
)
# 2. High-Speed Fatigue Analysis (Environmental Risk)
if col_speed and col_speed in df.columns:
high_speed_threshold = 20
high_speed_fatigue = df[df[col_speed] >= high_speed_threshold] if high_speed_threshold > 0 else pd.DataFrame()
high_speed_pct = (len(high_speed_fatigue) / len(df)) * 100 if len(df) > 0 else 0
st.markdown(f"**High-Speed Fatigue Risk (Speed > {high_speed_threshold:.0f} km/h)**")
# Tampilkan jumlah dan persentase dalam satu div
st.markdown(
f"""
<div style="background-color: #f0f8ff; padding: 10px; border-radius: 8px; margin-bottom: 10px; border-left: 5px solid #007BFF;">
<div style="font-size: 24px; font-weight: bold; color: #000000;">
{len(high_speed_fatigue)}
</div>
<div style="color: #d32f2f; font-size: 16px; font-weight: bold; margin-top: -10px;">
↑ {high_speed_pct:.1f}% of total alerts
</div>
</div>
""",
unsafe_allow_html=True
)
# Gunakan st.markdown untuk warning/info dengan persentase berwarna merah tebal
if high_speed_pct > 20:
st.markdown(
f"<span style='color:#d32f2f; font-weight:bold;'>⚠️ High risk: {high_speed_pct:.1f}% of fatigue alerts occur at high speeds. This increases accident severity potential.</span>",
unsafe_allow_html=True
)
else:
st.markdown(
f"<span style='color:#d32f2f; font-weight:bold;'>✅ {high_speed_pct:.1f}% of alerts occur at high speeds. This is within acceptable range.</span>",
unsafe_allow_html=True
)
else:
st.info("Speed data not available for High-Speed Fatigue Analysis.")
# 3. Shift Pattern Analysis
if col_shift and col_shift in df.columns:
shift_counts = df[col_shift].value_counts()
st.markdown(f"**Shift Pattern Risk**")
for shift_val in shift_counts.index:
shift_pct = (shift_counts[shift_val] / len(df)) * 100
# Tampilkan jumlah dan persentase dalam satu div dengan warna latar belakang seragam
st.markdown(
f"""
<div style="background-color: #f0f8ff; padding: 10px; border-radius: 8px; margin-bottom: 10px; border-left: 5px solid #007BFF;">
<div style="font-size: 24px; font-weight: bold; color: #000000;">Shift {shift_val}</div>
<div style="font-size: 28px; font-weight: bold; color: #000000; margin: 10px 0;">
{shift_counts[shift_val]}
</div>
<div style="color: #d32f2f; font-size: 16px; font-weight: bold; margin-top: -10px;">
↑ {shift_pct:.1f}% of total alerts
</div>
</div>
""",
unsafe_allow_html=True
)
# Gunakan st.markdown untuk warning/info dengan persentase berwarna merah tebal
if shift_pct > 50:
st.markdown(
f"<span style='color:#d32f2f; font-weight:bold;'>⚠️ Shift {shift_val} has disproportionately high alerts ({shift_pct:.1f}%). Review shift scheduling and workload.</span>",
unsafe_allow_html=True
)
else:
st.markdown(
f"<span style='color:#d32f2f; font-weight:bold;'>✅ Shift {shift_val} alert distribution is acceptable ({shift_pct:.1f}%).</span>",
unsafe_allow_html=True
)
else:
st.info("Shift data not available for Shift Pattern Analysis.")
# 4. Operator Risk Profiling
if col_operator and col_operator in df.columns:
operator_alerts = df[col_operator].value_counts()
top_risk_operators = operator_alerts.head(5) # Top 5 operators by alerts
st.markdown("**High-Risk Operator Identification**")
# Warna berdasarkan ranking 1–5
colors = ["#d32f2f", "#e57373", "#ef9a9a", "#ffcdd2", "#ffe1e4"]
for idx, (op_name, count) in enumerate(top_risk_operators.items()):
op_pct = (count / len(df)) * 100
color = colors[idx] if idx < len(colors) else colors[-1]
# Teks normal untuk nama dan jumlah alert
st.markdown(f"**Operator:** {op_name} \n**Alerts:** {count}")
# Hanya 'Share' yang berwarna sesuai ranking
st.markdown(
f"<span style='font-weight:600'>Share:</span> "
f"<span style='color:{color}; font-weight:700'>{op_pct:.1f}% of total alerts</span>",
unsafe_allow_html=True
)
# Risk message (tetap gunakan component Streamlit agar konsisten)
if op_pct > 5:
st.warning(f"Operator {op_name} has high fatigue risk ({op_pct:.1f}%). Consider coaching or rest plan.")
else:
st.info(f"Operator {op_name} fatigue risk is within acceptable range ({op_pct:.1f}%).")
else:
st.info("Operator data not available for Operator Risk Profiling.")
# Kolom kanan: AI Recommendations
with col_recs:
st.subheader("Recommendations")
ai_recs = []
insights_found = []
# Peak hour
if "hour" in df.columns and not df.empty:
peak_hour = df["hour"].value_counts().idxmax()
critical_hours = [2, 3, 4, 5]
if peak_hour in critical_hours:
insights_found.append(f" Most fatigue risk occurs at **{peak_hour}:00** — during critical circadian low period (3-6 AM). Consider enhanced monitoring.")
else:
insights_found.append(f"Most fatigue risk occurs at **{peak_hour}:00** — likely due to circadian drop.")
# Risk shift
if col_shift and not df.empty:
worst_shift = df[col_shift].value_counts().idxmax()
insights_found.append(f" Highest fatigue recorded in **Shift {worst_shift}** — review scheduling & workload.")
# Worst operator
if col_operator and not df.empty:
worst_operator = df[col_operator].value_counts().idxmax()
insights_found.append(f" Operator at highest risk: **{worst_operator}** — suggested coaching or rest plan.")
# Duration risk
if "duration_sec" in df.columns and not df.empty:
avg_duration = df["duration_sec"].mean()
if not pd.isna(avg_duration) and avg_duration > 10:
insights_found.append(" Long fatigue event duration suggests slow response — improve alerting training.")
# Generate recommendations based on found insights
if insights_found:
if any("circadian low" in i.lower() for i in insights_found):
ai_recs.append({
"recommendation": "Deploy enhanced fatigue monitoring systems (e.g., EOR) specifically during 3-6 AM shifts.",
"data_point": f"Critical Hour Alerts: {len(critical_alerts)} ({critical_pct:.1f}% of total alerts)",
"reason": "High percentage of alerts occurring during the known circadian low period (3-6 AM) indicates increased risk during these hours."
})
if any("shift" in i.lower() for i in insights_found):
ai_recs.append({
"recommendation": "Review shift rotation schedules to minimize consecutive high-risk shifts.",
"data_point": f"Shift {worst_shift} Alerts: {df[col_shift].value_counts()[worst_shift]} ({(df[col_shift].value_counts()[worst_shift] / len(df)) * 100:.1f}% of total alerts)",
"reason": f"The identified high-risk shift ({worst_shift}) has the highest number of fatigue alerts, suggesting scheduling or workload issues."
})
if any("operator" in i.lower() for i in insights_found):
ai_recs.append({
"recommendation": "Initiate individual coaching or mandatory rest periods for high-risk operators.",
"data_point": f"Operator {worst_operator} Alerts: {df[col_operator].value_counts()[worst_operator]} ({(df[col_operator].value_counts()[worst_operator] / len(df)) * 100:.1f}% of total alerts)",
"reason": f"The identified high-risk operator ({worst_operator}) has the highest number of fatigue alerts, indicating a need for targeted intervention."
})
if any("duration" in i.lower() for i in insights_found):
ai_recs.append({
"recommendation": "Review and improve alert response protocols and training.",
"data_point": f"Average Fatigue Event Duration: {avg_duration:.2f} seconds",
"reason": "Long average duration suggests potential delays in response time or alert acknowledgment, requiring protocol review."
})
if any("high-speed" in i.lower() for i in insights_found):
ai_recs.append({
"recommendation": "Implement speed management strategies in conjunction with fatigue monitoring.",
"data_point": f"High-Speed Fatigue Events: {len(high_speed_fatigue)} ({high_speed_pct:.1f}% of total alerts)",
"reason": "A significant percentage of alerts occur at high speeds, increasing accident severity risk. Speed control is crucial."
})
if not ai_recs:
ai_recs.append({
"recommendation": "Data quality is sufficient. Focus on implementing recommendations from Objectives 1-5.",
"data_point": "General Data Quality Check",
"reason": "No specific high-impact insights were automatically identified from the aggregated data in this section."
})
for rec in ai_recs:
# Ambil data_point dan ganti teks persentase di dalamnya menjadi warna merah
data_point_text = rec['data_point']
# Ganti pola persentase (X.X%) dengan span warna merah
# Cari pola seperti "1.6%", "21.2%", dll.
data_point_colored = re.sub(r'(\d+\.?\d*%)', r'<span style="color: red;">\1</span>', data_point_text)
# Ambil reason dan lakukan hal yang sama
reason_text = rec['reason']
reason_colored = re.sub(r'(\d+\.?\d*%)', r'<span style="color: red;">\1</span>', reason_text)
# Tampilkan rekomendasi dengan teks persentase berwarna merah
st.markdown(f"""
<div style="
background: #f8f9fa;
border: 1px solid #dee2e6;
border-radius: 8px;
padding: 15px;
margin: 10px 0;
color: #2c3e50;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
display: flex;
flex-direction: column;
justify-content: space-between;
">
<div style="
font-weight: bold;
color: #2c3e50;
margin-bottom: 8px;
font-size: 14px;
background: #e9ecef;
padding: 8px;
border-radius: 5px;
border-left: 4px solid #495057;
">AI Recommendation</div>
<div style="padding-top: 8px; font-size: 14px; margin-bottom: 10px;">
<strong>Action:</strong> {rec['recommendation']}
</div>
<div style="font-size: 12px; padding: 8px; background: #e9ecef; border-radius: 5px; margin-top: 5px;">
<strong>Data Point:</strong> {data_point_colored}
</div>
<div style="font-size: 12px; padding: 8px; background: #f1f1f1; border-radius: 5px; margin-top: 5px;">
<strong>AI Reasoning:</strong> {reason_colored}
</div>
</div>
""", unsafe_allow_html=True)
else:
st.info("No specific data points available for AI recommendations. Ensure relevant columns (hour, shift, operator, duration, speed) are present and populated.")
# ================= FOOTER ===========================
st.markdown("---")
st.markdown('<div class="footer">FatigueAnalyzer - Transforming Mining Safety with Intelligent Analytics | Contact: info@bukittechnology.com</div>', unsafe_allow_html=True)
|