Spaces:
Sleeping
Sleeping
File size: 93,369 Bytes
9aa4b61 | 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 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 | """
SWAN Menopause Stage Prediction & Forecasting โ Gradio UI
Hugging Face Spaces deployment-ready.
Run locally: python app.py
Deploy: Push to a HF Space with SDK=gradio
Output structure (per execution):
swan_ml_output/
<YYYYMMDD_HHMMSS>/
charts/ โ PNG visualizations
predictions/ โ CSV result files
reports/ โ TXT summary reports
"""
import os
import json
import warnings
from datetime import datetime
from pathlib import Path
from typing import Optional
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
warnings.filterwarnings("ignore")
# โโ Gradio โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
import gradio as gr
# โโ Local ML module โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
try:
from menopause import (
MenopauseForecast,
SymptomCycleForecaster,
load_forecast_model,
)
_MODULE_AVAILABLE = True
except ImportError:
_MODULE_AVAILABLE = False
# โโ Model loading โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
FORECAST_DIR = os.environ.get("FORECAST_DIR", "swan_ml_output")
OUTPUT_BASE = Path(FORECAST_DIR)
_forecast: Optional[MenopauseForecast] = None # type: ignore[type-arg]
_metadata: dict = {}
def _load_models():
"""Attempt to load saved joblib pipelines. Returns (success, message)."""
global _forecast, _metadata
if not _MODULE_AVAILABLE:
return False, "menopause.py not found. Make sure it is in the same directory."
meta_path = Path(FORECAST_DIR) / "forecast_metadata.json"
rf_path = Path(FORECAST_DIR) / "rf_pipeline.pkl"
lr_path = Path(FORECAST_DIR) / "lr_pipeline.pkl"
if not all(p.exists() for p in (meta_path, rf_path, lr_path)):
return (
False,
f"Model artifacts not found in '{FORECAST_DIR}'. "
"Run `python menopause.py` to train and save the models first.",
)
try:
_forecast = load_forecast_model(FORECAST_DIR)
with open(meta_path) as fh:
_metadata = json.load(fh)
return True, f"โ
Models loaded โ {len(_metadata.get('feature_names', []))} features"
except Exception as exc:
return False, f"Error loading models: {exc}"
_MODEL_OK, _MODEL_MSG = _load_models()
# โโ Output directory management โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _make_run_dir() -> Path:
"""Create and return a unique timestamped run directory under swan_ml_output/."""
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
run_dir = OUTPUT_BASE / ts
(run_dir / "charts").mkdir(parents=True, exist_ok=True)
(run_dir / "predictions").mkdir(parents=True, exist_ok=True)
(run_dir / "reports").mkdir(parents=True, exist_ok=True)
return run_dir
def _get_file_path(file_obj) -> Optional[str]:
"""
Safely extract a file-system path from a Gradio file component value.
Gradio โค 3.x โ returns a file-like object with a .name attribute.
Gradio 4.x โ returns a str path (or NamedString subclass).
This helper handles both.
"""
if file_obj is None:
return None
if hasattr(file_obj, "name"):
return file_obj.name
return str(file_obj)
# โโ Constants & helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
STAGE_COLORS = {"pre": "#16a34a", "peri": "#d97706", "post": "#7c3aed"}
STAGE_EMOJI = {"pre": "๐ข", "peri": "๐ก", "post": "๐ฃ"}
STAGE_LABELS = {
"pre": "Pre-Menopausal",
"peri": "Peri-Menopausal",
"post": "Post-Menopausal",
}
STAGE_INFO = {
"pre": {
"title": "Pre-Menopausal",
"description": "Regular menstrual cycles with typical hormonal fluctuations. Ovarian function is normal.",
"symptoms": ["Regular periods", "Normal hormone levels", "Potential mild PMS"],
"guidance": "Maintain regular check-ups. Track your cycle and note any changes.",
},
"peri": {
"title": "Peri-Menopausal (Transition)",
"description": "Hormonal changes begin โ estrogen and progesterone levels fluctuate. Cycles become irregular.",
"symptoms": ["Irregular periods", "Hot flashes", "Sleep disturbances", "Mood changes", "Night sweats"],
"guidance": "Consult your healthcare provider. Lifestyle adjustments (diet, exercise, sleep) can help.",
},
"post": {
"title": "Post-Menopausal",
"description": "12+ months since last menstrual period. Estrogen remains at consistently lower levels.",
"symptoms": ["No periods", "Possible continued hot flashes", "Vaginal dryness", "Bone density changes"],
"guidance": "Focus on bone health, cardiovascular health, and regular screenings. Discuss HRT options.",
},
}
# Feature descriptions keyed by the model's canonical feature names
FEATURE_DESCRIPTIONS = {
"PAIN17": "Pain indicator (visit-specific)",
"PAINTW17": "Pain two-week indicator",
"PAIN27": "Secondary pain indicator",
"PAINTW27": "Secondary pain two-week indicator",
"SLEEP17": "Sleep disturbance pattern 1",
"SLEEP27": "Sleep disturbance pattern 2",
"BCOHOTH7": "Birth control โ other method",
"EXERCIS7": "General exercise indicator",
"EXERHAR7": "Vigorous exercise",
"EXEROST7": "Osteoporosis exercise",
"EXERMEN7": "Exercise โ mental health",
"EXERLOO7": "Exercise lookalike",
"EXERMEM7": "Exercise โ memory",
"EXERPER7": "Exercise perception",
"EXERGEN7": "General exercise type",
"EXERWGH7": "Weight exercise",
"EXERADV7": "Exercise advice indicator",
"EXEROTH7": "Other exercise",
"EXERSPE7": "Specific exercise",
"ABBLEED7": "Abnormal bleeding (0=no, 1=yes)", # โ correct feature name
"BLEEDNG7": "Bleeding pattern",
"LMPDAY7": "Last menstrual period day",
"DEPRESS7": "Depression indicator",
"SEX17": "Sexual activity indicator 1",
"SEX27": "Sexual activity indicator 2",
"SEX37": "Sexual activity indicator 3",
"SEX47": "Sexual activity indicator 4",
"SEX57": "Sexual activity indicator 5",
"SEX67": "Sexual activity indicator 6",
"SEX77": "Sexual activity indicator 7",
"SEX87": "Sexual activity indicator 8",
"SEX97": "Sexual activity indicator 9",
"SEX107": "Sexual activity indicator 10",
"SEX117": "Sexual activity indicator 11",
"SEX127": "Sexual activity indicator 12",
"SMOKERE7": "Smoking status",
"HOTFLAS7": "Hot flash severity (1=none, 5=very severe)",
"NUMHOTF7": "Number of hot flashes per week",
"BOTHOTF7": "How bothersome are hot flashes",
"IRRITAB7": "Irritability level",
"VAGINDR7": "Vaginal dryness",
"MOODCHG7": "Mood change frequency",
"SLEEPQL7": "Sleep quality score",
"PHYSILL7": "Physical illness indicators",
"HOTHEAD7": "Hot flashes with headache",
"EXER12H7": "Exercise in last 12 hours",
"ALCO24H7": "Alcohol in last 24h",
"AGE7": "Age (years)",
"RACE": "Race (1=White, 2=Black, 3=Chinese, 4=Japanese, 5=Hispanic)",
"LANGINT7": "Interview language indicator",
}
def _confidence_color(conf: float) -> str:
if conf >= 0.8:
return "#16a34a"
elif conf >= 0.6:
return "#d97706"
return "#dc2626"
# โโ Chart builders โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _make_proba_chart(
probabilities: dict,
predicted_stage: str,
save_path: Optional[Path] = None,
) -> plt.Figure:
"""Horizontal bar chart for stage probabilities. Optionally saves PNG."""
fig, ax = plt.subplots(figsize=(6, 3.5))
fig.patch.set_facecolor("#1a1a2e")
ax.set_facecolor("#16213e")
stages = list(probabilities.keys())
probs = [probabilities[s] * 100 for s in stages]
colors = [STAGE_COLORS.get(s, "#607d8b") for s in stages]
edge_colors = ["white" if s == predicted_stage else "none" for s in stages]
lws = [2.5 if s == predicted_stage else 0 for s in stages]
bars = ax.barh(stages, probs, color=colors, edgecolor=edge_colors,
linewidth=lws, height=0.5, zorder=3)
for bar, prob in zip(bars, probs):
ax.text(
min(prob + 1, 98), bar.get_y() + bar.get_height() / 2,
f"{prob:.1f}%",
va="center", ha="left", color="white", fontsize=11, fontweight="bold",
)
labels = [STAGE_LABELS.get(s, s) for s in stages]
ax.set_yticks(range(len(stages)))
ax.set_yticklabels(labels, color="white", fontsize=10)
ax.set_xlim(0, 105)
ax.tick_params(colors="white", labelsize=11)
ax.spines[["top", "right", "left", "bottom"]].set_visible(False)
ax.xaxis.set_visible(False)
for spine in ax.spines.values():
spine.set_color("#333")
ax.set_title("Stage Probabilities", color="white", fontsize=12,
pad=10, fontweight="bold")
ax.grid(axis="x", color="#333", linestyle="--", linewidth=0.5, zorder=0)
fig.tight_layout()
if save_path:
fig.savefig(save_path, dpi=150, bbox_inches="tight",
facecolor=fig.get_facecolor())
return fig
def _make_cycle_chart(
cycle_day: int,
cycle_length: int = 28,
hot_prob: float = None,
mood_prob: float = None,
save_path: Optional[Path] = None,
) -> plt.Figure:
"""Circular cycle-day visualization. Optionally saves PNG."""
fig, ax = plt.subplots(figsize=(5, 5), subplot_kw=dict(polar=True))
fig.patch.set_facecolor("#1a1a2e")
ax.set_facecolor("#16213e")
days = np.linspace(0, 2 * np.pi, cycle_length, endpoint=False)
for i, d in enumerate(days):
phase = i / cycle_length
color = plt.cm.RdYlGn(1 - phase)
ax.bar(d, 1, width=2 * np.pi / cycle_length * 0.9,
bottom=0.5, color=color, alpha=0.4, zorder=1)
if cycle_day is not None:
angle = (cycle_day - 1) / cycle_length * 2 * np.pi
ax.scatter([angle], [1.05], s=200, color="#ff6b6b", zorder=5, linewidths=2)
ax.annotate(
f"Day {cycle_day}",
xy=(angle, 1.05), xytext=(0, 0),
textcoords="offset points", ha="center", va="center",
color="white", fontsize=12, fontweight="bold",
)
ax.set_rticks([])
ax.set_xticks([i * 2 * np.pi / 4 for i in range(4)])
ax.set_xticklabels(["Day 1", "Day 7", "Day 14", "Day 21"],
color="#aaa", fontsize=9)
ax.set_yticklabels([])
ax.spines["polar"].set_color("#333")
ax.grid(color="#333", linewidth=0.5)
title = "Cycle Position"
if hot_prob is not None:
title += f"\n๐ฅ {hot_prob:.0%} ๐ค {mood_prob:.0%}"
ax.set_title(title, color="white", fontsize=11, pad=20, fontweight="bold")
fig.tight_layout()
if save_path:
fig.savefig(save_path, dpi=150, bbox_inches="tight",
facecolor=fig.get_facecolor())
return fig
def _make_batch_summary_chart(results_df: pd.DataFrame,
save_path: Optional[Path] = None) -> None:
"""Stage distribution + confidence histogram for batch runs. Saves PNG."""
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
fig.patch.set_facecolor("#1a1a2e")
# Stage distribution pie
stage_counts = results_df["predicted_stage"].value_counts()
colors = [STAGE_COLORS.get(s, "#607d8b") for s in stage_counts.index]
ax1.set_facecolor("#16213e")
wedges, texts, autotexts = ax1.pie(
stage_counts.values, labels=stage_counts.index,
colors=colors, autopct="%1.0f%%",
textprops={"color": "white", "fontsize": 10},
)
for at in autotexts:
at.set_color("white")
ax1.set_title("Stage Distribution", color="white", fontsize=11, fontweight="bold")
# Confidence histogram
ax2.set_facecolor("#16213e")
if "confidence" in results_df.columns:
conf = results_df["confidence"].dropna()
ax2.hist(conf, bins=min(10, len(conf)), color="#3B82F6",
edgecolor="#1a1a2e", alpha=0.8)
ax2.axvline(0.8, color="#4CAF50", linestyle="--",
linewidth=1.5, label="High (0.80)")
ax2.axvline(0.6, color="#FF9800", linestyle="--",
linewidth=1.5, label="Med (0.60)")
ax2.legend(fontsize=8, labelcolor="white", facecolor="#0d0d1a")
ax2.set_xlabel("Confidence", color="#aaa", fontsize=9)
ax2.set_ylabel("Count", color="#aaa", fontsize=9)
ax2.tick_params(colors="white", labelsize=9)
for sp in ["top", "right"]:
ax2.spines[sp].set_visible(False)
for sp in ["left", "bottom"]:
ax2.spines[sp].set_color("#333")
ax2.set_title("Confidence Distribution", color="white",
fontsize=11, fontweight="bold")
fig.tight_layout()
if save_path:
fig.savefig(save_path, dpi=150, bbox_inches="tight",
facecolor=fig.get_facecolor())
plt.close(fig)
# โโ Text report writers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _write_single_stage_report(
path: Path,
stage: str,
confidence: float,
probabilities: dict,
model: str,
comparison: dict,
input_features: dict,
):
lines = [
"=" * 60,
"SWAN MENOPAUSE STAGE PREDICTION REPORT",
f"Generated : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
"=" * 60,
"",
f"Predicted Stage : {STAGE_LABELS.get(stage, stage)}",
f"Model : {model}",
f"Confidence : {confidence:.1%}",
"",
"Stage Probabilities:",
]
for s, p in probabilities.items():
bar = "โ" * int(p * 20)
lines.append(f" {s:<6} : {p:.4f} {bar}")
lines += [
"",
"Model Comparison:",
f" RandomForest โ {comparison['RandomForest']['stage']}"
f" ({comparison['RandomForest'].get('confidence', 0):.1%})",
f" LogisticRegression โ {comparison['LogisticRegression']['stage']}"
f" ({comparison['LogisticRegression'].get('confidence', 0):.1%})",
"",
"Input Features (non-NaN):",
]
for k, v in input_features.items():
if v is not None and not (isinstance(v, float) and np.isnan(v)):
lines.append(f" {k:<12} = {v}")
lines += [
"",
"โ ๏ธ For research/educational use only. Not a clinical diagnosis.",
"=" * 60,
]
path.write_text("\n".join(lines), encoding="utf-8")
def _write_batch_report(
path: Path,
results: pd.DataFrame,
model: str,
run_dir: Path,
):
total = len(results)
dist = results["predicted_stage"].value_counts().to_dict() \
if "predicted_stage" in results.columns else {}
if "confidence" in results.columns:
conf = results["confidence"]
mean_c = conf.mean(); min_c = conf.min(); max_c = conf.max()
high = int((conf > 0.8).sum())
medium = int(((conf > 0.6) & (conf <= 0.8)).sum())
low = int((conf <= 0.6).sum())
else:
mean_c = min_c = max_c = high = medium = low = 0
lines = [
"=" * 60,
"SWAN BATCH STAGE PREDICTION REPORT",
f"Generated : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
f"Model : {model}",
"=" * 60,
"",
f"Total Individuals : {total}",
"",
"Stage Distribution:",
]
for stage in ["pre", "peri", "post"]:
count = dist.get(stage, 0)
pct = count / total * 100 if total else 0
lines.append(f" {stage:<6} : {count} ({pct:.1f}%)")
lines += [
"",
"Confidence Scores:",
f" Mean : {mean_c:.4f}",
f" Min : {min_c:.4f}",
f" Max : {max_c:.4f}",
"",
"Confidence Distribution:",
f" High (>0.80) : {high}/{total} ({high/total*100:.1f}%)" if total else " N/A",
f" Medium (0.60-0.80) : {medium}/{total} ({medium/total*100:.1f}%)" if total else " N/A",
f" Low (โค0.60) : {low}/{total} ({low/total*100:.1f}%)" if total else " N/A",
"",
f"Output Directory : {run_dir}",
"",
"โ ๏ธ For research/educational use only. Not a clinical diagnosis.",
"=" * 60,
]
path.write_text("\n".join(lines), encoding="utf-8")
def _write_symptom_report(
path: Path,
individual_id: str,
lmp: str,
target_date: str,
cycle_day: int,
cycle_length: int,
hot_prob: float,
hot_pred: bool,
mood_prob: float,
mood_pred: bool,
):
hp = float(hot_prob) if (hot_prob is not None and not np.isnan(hot_prob)) else 0.0
mp = float(mood_prob) if (mood_prob is not None and not np.isnan(mood_prob)) else 0.0
lines = [
"=" * 60,
"SWAN SYMPTOM CYCLE FORECAST REPORT",
f"Generated : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
"=" * 60,
"",
f"Individual : {individual_id or 'N/A'}",
f"LMP : {lmp}",
f"Target Date : {target_date or 'Today'}",
f"Cycle Length : {cycle_length} days",
f"Cycle Day : {cycle_day}",
"",
"Symptom Probabilities:",
f" Hot Flash : {hp:.4f} {'[ELEVATED RISK]' if hot_pred else '[LOW RISK]'}",
f" Mood Change : {mp:.4f} {'[ELEVATED RISK]' if mood_pred else '[LOW RISK]'}",
"",
"โ ๏ธ For research/educational use only. Not a clinical diagnosis.",
"=" * 60,
]
path.write_text("\n".join(lines), encoding="utf-8")
def _write_batch_symptom_report(
path: Path,
results: pd.DataFrame,
cycle_length: int,
run_dir: Path,
):
total = len(results)
hot_flags = int(results["hotflash_pred"].sum()) \
if "hotflash_pred" in results.columns else 0
mood_flags = int(results["mood_pred"].sum()) \
if "mood_pred" in results.columns else 0
mean_hot = float(results["hotflash_prob"].mean()) \
if "hotflash_prob" in results.columns else 0.0
mean_mood = float(results["mood_prob"].mean()) \
if "mood_prob" in results.columns else 0.0
lines = [
"=" * 60,
"SWAN BATCH SYMPTOM FORECAST REPORT",
f"Generated : {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
f"Cycle Length : {cycle_length} days",
"=" * 60,
"",
f"Total Individuals : {total}",
f"Hot Flash Risk : {hot_flags}/{total} elevated",
f"Mood Change Risk : {mood_flags}/{total} elevated",
f"Avg Hot Flash Prob : {mean_hot:.4f}",
f"Avg Mood Prob : {mean_mood:.4f}",
"",
f"Output Directory : {run_dir}",
"",
"โ ๏ธ For research/educational use only. Not a clinical diagnosis.",
"=" * 60,
]
path.write_text("\n".join(lines), encoding="utf-8")
# โโ Core prediction functions โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def predict_single_stage(
age, race, langint,
hot_flash, num_hot_flash, bothersome_hf,
sleep_quality, depression_indicator, mood_change, irritability,
pain_indicator, abbleed, vaginal_dryness, lmp_day,
model_choice,
):
"""
Single-person stage prediction.
Returns (stage_html, chart_fig, conf_note, compare_html, csv_download_path).
"""
if not _MODEL_OK:
return f"โ ๏ธ {_MODEL_MSG}", None, "Models unavailable.", "", None
# Build feature dict using the model's canonical feature names
def _v(x):
return float(x) if x is not None else np.nan
feature_dict = {
"AGE7": _v(age),
"RACE": _v(race),
"LANGINT7": _v(langint),
"HOTFLAS7": _v(hot_flash),
"NUMHOTF7": _v(num_hot_flash),
"BOTHOTF7": _v(bothersome_hf),
"SLEEPQL7": _v(sleep_quality),
"DEPRESS7": _v(depression_indicator),
"MOODCHG7": _v(mood_change),
"IRRITAB7": _v(irritability),
"PAIN17": _v(pain_indicator),
"ABBLEED7": _v(abbleed), # โ correct feature name (was ABLEED7)
"VAGINDR7": _v(vaginal_dryness),
"LMPDAY7": _v(lmp_day) if lmp_day else np.nan,
}
try:
result = _forecast.predict_single(feature_dict, model=model_choice, return_proba=True)
stage = result["stage"]
confidence = result.get("confidence") or 0.0
proba = result.get("probabilities") or {}
# โโ Create timestamped run directory โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
run_dir = _make_run_dir()
# โโ Save probability chart (PNG) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
chart_path = run_dir / "charts" / "stage_probabilities.png"
chart_fig = _make_proba_chart(proba, stage, save_path=chart_path) if proba else None
# โโ Save prediction CSV โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
pred_row = {
"predicted_stage": stage,
"model": model_choice,
"confidence": round(confidence, 4),
**{f"prob_{k}": round(v, 4) for k, v in proba.items()},
"timestamp": datetime.now().isoformat(),
}
csv_path = run_dir / "predictions" / "stage_prediction.csv"
pd.DataFrame([pred_row]).to_csv(csv_path, index=False)
# โโ Model comparison โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
comparison = _forecast.compare_models(feature_dict)
rf_stage = comparison["RandomForest"]["stage"]
lr_stage = comparison["LogisticRegression"]["stage"]
agree = rf_stage == lr_stage
# โโ Save text report โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
txt_path = run_dir / "reports" / "prediction_summary.txt"
_write_single_stage_report(
txt_path, stage, confidence, proba,
model_choice, comparison, feature_dict,
)
# โโ Build result card HTML โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
info = STAGE_INFO.get(stage, {})
emoji = STAGE_EMOJI.get(stage, "โช")
color = STAGE_COLORS.get(stage, "#607d8b")
conf_color = _confidence_color(confidence)
symptom_tags = "".join(
f'<span style="background:{color}14;color:{color};padding:4px 10px;'
f'border-radius:20px;border:1px solid {color}44;font-size:12px;'
f'font-weight:500">{s}</span>'
for s in info.get("symptoms", [])
)
stage_html = f"""
<div class="result-card" style="border-left:4px solid {color}">
<div style="display:flex;align-items:center;gap:12px;margin-bottom:16px;flex-wrap:wrap">
<span style="font-size:40px;flex-shrink:0">{emoji}</span>
<div style="flex:1;min-width:140px">
<div style="color:#6b7280;font-size:12px;text-transform:uppercase;letter-spacing:2px">
Predicted Stage
</div>
<div style="color:{color};font-size:26px;font-weight:700">
{STAGE_LABELS.get(stage, stage)}
</div>
</div>
<div style="text-align:right;flex-shrink:0">
<div style="color:#6b7280;font-size:11px">Confidence</div>
<div style="color:{conf_color};font-size:28px;font-weight:700">
{confidence:.0%}
</div>
</div>
</div>
<hr style="border:none;border-top:1px solid #e2e8f0;margin:12px 0">
<p style="color:#374151;font-size:14px;margin:8px 0">
{info.get('description', '')}
</p>
<div style="margin-top:12px">
<div style="color:#6b7280;font-size:11px;text-transform:uppercase;
letter-spacing:1px;margin-bottom:6px">Common Symptoms</div>
<div style="display:flex;flex-wrap:wrap;gap:6px">{symptom_tags}</div>
</div>
<div style="background:{color}0d;border-left:3px solid {color};
padding:10px 14px;margin-top:14px;border-radius:0 8px 8px 0">
<span style="color:{color};font-size:12px;font-weight:600">๐ก Guidance: </span>
<span style="color:#374151;font-size:13px">{info.get('guidance', '')}</span>
</div>
<div style="color:#9ca3af;font-size:11px;margin-top:12px">
Model: {model_choice} ยท {datetime.now().strftime('%Y-%m-%d %H:%M')}
</div>
</div>
"""
# Confidence note
if confidence >= 0.8:
conf_note = "โ
High confidence โ the model is quite certain about this stage."
elif confidence >= 0.6:
conf_note = ("โ ๏ธ Moderate confidence โ consider providing more feature values "
"or consulting a clinician.")
else:
conf_note = ("๐ด Low confidence โ prediction is uncertain; "
"clinical consultation is strongly recommended.")
# Model comparison panel + run-dir info
compare_html = f"""
<div class="result-card" style="margin-top:0">
<div style="color:#6b7280;font-size:11px;text-transform:uppercase;
letter-spacing:1px;margin-bottom:10px;font-weight:600">
Model Comparison
</div>
<div class="stat-grid-2">
<div class="stat-item" style="border-top:3px solid #16a34a">
<div style="color:#16a34a;font-size:11px;font-weight:600">Random Forest</div>
<div style="color:#111827;font-size:17px;margin-top:4px">
{STAGE_EMOJI.get(rf_stage,'')} {STAGE_LABELS.get(rf_stage, rf_stage)}
</div>
<div style="color:#6b7280;font-size:12px">
{comparison['RandomForest'].get('confidence', 0):.0%} confidence
</div>
</div>
<div class="stat-item" style="border-top:3px solid #2563eb">
<div style="color:#2563eb;font-size:11px;font-weight:600">
Logistic Regression
</div>
<div style="color:#111827;font-size:17px;margin-top:4px">
{STAGE_EMOJI.get(lr_stage,'')} {STAGE_LABELS.get(lr_stage, lr_stage)}
</div>
<div style="color:#6b7280;font-size:12px">
{comparison['LogisticRegression'].get('confidence', 0):.0%} confidence
</div>
</div>
</div>
<div style="margin-top:10px;padding:8px;border-radius:8px;
background:{'#d1fae5' if agree else '#fef2f2'};
color:{'#065f46' if agree else '#9f1239'};
font-size:13px;text-align:center;font-weight:500">
{"โ
Both models agree โ prediction is robust"
if agree else
"โ ๏ธ Models disagree โ interpret with caution"}
</div>
<div class="output-path-box">
<div class="output-path-title">๐ Outputs saved to:</div>
<div class="output-path-dir">{run_dir}/</div>
<div class="output-path-files">
charts/stage_probabilities.png<br>
predictions/stage_prediction.csv<br>
reports/prediction_summary.txt
</div>
</div>
</div>
"""
return stage_html, chart_fig, conf_note, compare_html, str(csv_path)
except Exception as exc:
return f"โ Prediction error: {exc}", None, "", "", None
def predict_batch_stage(file, model_choice):
"""
Batch stage prediction from uploaded CSV.
Returns (csv_download_path, summary_html, preview_df).
"""
if not _MODEL_OK:
return None, f"โ ๏ธ {_MODEL_MSG}", None
if file is None:
return None, "Please upload a CSV file.", None
file_path = _get_file_path(file)
try:
df = pd.read_csv(file_path)
except Exception as exc:
return None, f"Could not read CSV: {exc}", None
if df.empty:
return None, "Uploaded CSV is empty.", None
# Identify ID column
id_col_candidates = ["individual", "Individual", "ID", "id",
"SWANID", "subject", "Subject"]
id_col = next((c for c in id_col_candidates if c in df.columns), None)
# Validate features
feature_names = _metadata.get("feature_names", [])
matching = [c for c in df.columns if c in feature_names]
missing_pct = 1 - len(matching) / max(len(feature_names), 1)
warnings_list = []
if not matching:
return None, (
"โ No matching feature columns found. "
"Please include columns from the training feature set "
"(see 'Feature Reference' tab)."
), None
if missing_pct > 0.5:
warnings_list.append(
f"โ ๏ธ {missing_pct:.0%} of training features are missing โ "
"prediction accuracy may be reduced."
)
try:
results = _forecast.predict_batch(df, model=model_choice, return_proba=True)
# Insert individual ID
if id_col:
results.insert(0, "individual", df[id_col].values)
else:
results.insert(0, "individual",
[f"Row_{i+1}" for i in range(len(results))])
results["model"] = model_choice
results["notes"] = ""
if "confidence" in results.columns:
low_mask = results["confidence"] < 0.6
results.loc[low_mask, "notes"] = "Low confidence โ review manually"
# โโ Create timestamped run directory โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
run_dir = _make_run_dir()
# โโ Save predictions CSV โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
csv_path = run_dir / "predictions" / "batch_stage_predictions.csv"
results.to_csv(csv_path, index=False)
# โโ Save confidence/distribution chart (PNG) โโโโโโโโโโโโโโโโโโโโโโโโโโ
chart_path = run_dir / "charts" / "batch_summary_chart.png"
_make_batch_summary_chart(results, save_path=chart_path)
# โโ Save text report โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
txt_path = run_dir / "reports" / "batch_summary.txt"
_write_batch_report(txt_path, results, model_choice, run_dir)
# โโ Build summary HTML โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
total = len(results)
dist = results["predicted_stage"].value_counts().to_dict()
mean_conf = results["confidence"].mean() \
if "confidence" in results.columns else 0.0
high_conf = int((results["confidence"] > 0.8).sum()) \
if "confidence" in results.columns else 0
dist_bars = ""
for stage in ["pre", "peri", "post"]:
count = dist.get(stage, 0)
pct = count / total * 100
dist_bars += f"""
<div style="margin:6px 0">
<div style="display:flex;justify-content:space-between;margin-bottom:2px">
<span style="color:#374151;font-size:13px">
{STAGE_EMOJI.get(stage,'')} {STAGE_LABELS.get(stage, stage)}
</span>
<span style="color:#6b7280;font-size:12px">{count} ({pct:.0f}%)</span>
</div>
<div style="background:#e2e8f0;border-radius:4px;height:8px">
<div style="background:{STAGE_COLORS.get(stage,'#6b7280')};
width:{pct}%;height:8px;border-radius:4px"></div>
</div>
</div>"""
warn_html = "".join(
f'<div style="color:#d97706;font-size:12px;margin-top:4px">{w}</div>'
for w in warnings_list
)
summary_html = f"""
<div class="result-card">
<div style="color:#111827;font-size:16px;font-weight:700;margin-bottom:14px">
๐ Batch Results โ {total} individuals
</div>
{warn_html}
<div class="stat-grid-3">
<div class="stat-item">
<div class="stat-label">Total</div>
<div class="stat-value">{total}</div>
</div>
<div class="stat-item">
<div class="stat-label">Avg Confidence</div>
<div class="stat-value" style="color:{_confidence_color(mean_conf)}">
{mean_conf:.0%}
</div>
</div>
<div class="stat-item">
<div class="stat-label">High Conf (>80%)</div>
<div class="stat-value" style="color:#16a34a">{high_conf}/{total}</div>
</div>
</div>
<div style="margin-top:12px">{dist_bars}</div>
<div class="output-path-box">
<div class="output-path-title">๐ Outputs saved to:</div>
<div class="output-path-dir">{run_dir}/</div>
<div class="output-path-files">
predictions/batch_stage_predictions.csv<br>
charts/batch_summary_chart.png<br>
reports/batch_summary.txt
</div>
</div>
</div>
"""
return str(csv_path), summary_html, results.head(20)
except Exception as exc:
return None, f"โ Batch prediction error: {exc}", None
def predict_symptoms(individual_id, lmp_input, target_date_input, cycle_length):
"""
Cycle-based symptom forecasting (single person).
Returns (result_html, chart_fig, csv_download_path).
"""
if not lmp_input:
return "Please enter your Last Menstrual Period date.", None, None
try:
cycle_length = int(cycle_length) if cycle_length else 28
fore = SymptomCycleForecaster(cycle_length=cycle_length)
target_date = target_date_input if target_date_input else None
result = fore.predict_single(lmp=lmp_input, target_date=target_date)
cycle_day = result.get("cycle_day")
hot_prob = result.get("hotflash_prob", 0)
hot_pred = result.get("hotflash_pred", False)
mood_prob = result.get("mood_prob", 0)
mood_pred = result.get("mood_pred", False)
# Safe float helpers
hp = float(hot_prob) if (hot_prob is not None and not np.isnan(hot_prob)) else 0.0
mp = float(mood_prob) if (mood_prob is not None and not np.isnan(mood_prob)) else 0.0
# โโ Create timestamped run directory โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
run_dir = _make_run_dir()
# โโ Save cycle chart (PNG) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
chart_path = run_dir / "charts" / "cycle_position.png"
chart_fig = _make_cycle_chart(
cycle_day, cycle_length, hp, mp, save_path=chart_path
)
# โโ Save forecast CSV โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
csv_path = run_dir / "predictions" / "symptom_forecast.csv"
lmp_note = ""
try:
int(str(lmp_input).strip())
lmp_note = "LMP inferred as day-of-month; interpret with caution"
except (ValueError, TypeError):
pass
pd.DataFrame([{
"individual": individual_id or "N/A",
"LMP": lmp_input,
"date": target_date_input or datetime.now().strftime("%Y-%m-%d"),
"cycle_day": cycle_day,
"hotflash_prob": round(hp, 6),
"hotflash_pred": bool(hot_pred),
"mood_prob": round(mp, 6),
"mood_pred": bool(mood_pred),
"notes": lmp_note,
}]).to_csv(csv_path, index=False)
# โโ Save text report โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
txt_path = run_dir / "reports" / "symptom_summary.txt"
_write_symptom_report(
txt_path, individual_id, lmp_input, target_date_input,
cycle_day, cycle_length, hp, hot_pred, mp, mood_pred,
)
# โโ Build result HTML โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _prob_bar(prob, label, color):
pct = min(prob * 100, 100)
return f"""
<div style="margin:10px 0">
<div style="display:flex;justify-content:space-between;margin-bottom:4px">
<span style="color:#374151;font-size:14px">{label}</span>
<span style="color:{color};font-size:16px;font-weight:700">{pct:.0f}%</span>
</div>
<div style="background:#e2e8f0;border-radius:6px;height:10px">
<div style="background:{color};width:{pct}%;height:10px;
border-radius:6px;transition:width 0.5s"></div>
</div>
</div>"""
hot_alert = "๐ด Elevated risk" if hot_pred else "๐ข Low risk"
mood_alert = "๐ด Elevated risk" if mood_pred else "๐ข Low risk"
html = f"""
<div class="result-card">
<div style="color:#111827;font-size:18px;font-weight:700;margin-bottom:4px">
{individual_id or 'Forecast'} โ Cycle Day {cycle_day or '?'}
</div>
<div style="color:#6b7280;font-size:13px;margin-bottom:20px">
LMP: {lmp_input} | Target: {target_date_input or 'Today'}
| Cycle: {cycle_length} days
</div>
{_prob_bar(hp, '๐ฅ Hot Flash Probability', '#ef4444')}
<div style="color:#6b7280;font-size:12px;margin:-6px 0 10px 2px">{hot_alert}</div>
{_prob_bar(mp, '๐ค Mood Change Probability', '#7c3aed')}
<div style="color:#6b7280;font-size:12px;margin:-6px 0 10px 2px">{mood_alert}</div>
<div style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;
padding:12px;margin-top:14px;font-size:12px;color:#6b7280">
โน๏ธ Probabilities are computed from a cycle-phase model (Gaussian heuristic).
They represent symptom likelihood based on cycle day, not a clinical diagnosis.
</div>
<div class="output-path-box">
<div class="output-path-title">๐ Outputs saved to:</div>
<div class="output-path-dir">{run_dir}/</div>
<div class="output-path-files">
charts/cycle_position.png<br>
predictions/symptom_forecast.csv<br>
reports/symptom_summary.txt
</div>
</div>
</div>
"""
return html, chart_fig, str(csv_path)
except Exception as exc:
return f"โ Error: {exc}", None, None
def predict_symptoms_batch(file, lmp_col_name, date_col_name, cycle_length):
"""
Batch symptom forecasting from CSV.
Returns (csv_download_path, summary_html, preview_df).
"""
if file is None:
return None, "Please upload a CSV file.", None
file_path = _get_file_path(file)
try:
df = pd.read_csv(file_path)
except Exception as exc:
return None, f"Could not read CSV: {exc}", None
if lmp_col_name not in df.columns:
return None, (
f"LMP column '{lmp_col_name}' not found in CSV. "
f"Columns present: {list(df.columns)}"
), None
try:
cycle_length = int(cycle_length) if cycle_length else 28
fore = SymptomCycleForecaster(cycle_length=cycle_length)
date_col = date_col_name \
if (date_col_name and date_col_name in df.columns) else None
results = fore.predict_df(df, lmp_col=lmp_col_name, date_col=date_col)
# โโ Add notes column (flag day-of-month LMP rows) โโโโโโโโโโโโโโโโโโโโโ
def _lmp_note(val):
try:
int(str(val).strip())
return "LMP inferred as day-of-month; interpret with caution"
except (ValueError, TypeError):
return ""
results["notes"] = df[lmp_col_name].apply(_lmp_note)
# โโ Create timestamped run directory โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
run_dir = _make_run_dir()
# โโ Save predictions CSV โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
csv_path = run_dir / "predictions" / "batch_symptom_forecast.csv"
results.to_csv(csv_path, index=False)
# โโ Save text report โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
txt_path = run_dir / "reports" / "batch_symptom_summary.txt"
_write_batch_symptom_report(txt_path, results, cycle_length, run_dir)
# โโ Build summary HTML โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
total = len(results)
hot_flags = int(results["hotflash_pred"].sum()) \
if "hotflash_pred" in results.columns else 0
mood_flags = int(results["mood_pred"].sum()) \
if "mood_pred" in results.columns else 0
mean_hot = float(results["hotflash_prob"].mean()) \
if "hotflash_prob" in results.columns else 0.0
mean_mood = float(results["mood_prob"].mean()) \
if "mood_prob" in results.columns else 0.0
summary_html = f"""
<div class="result-card">
<div style="color:#111827;font-size:16px;font-weight:700;margin-bottom:14px">
๐ Symptom Forecast โ {total} individuals
</div>
<div class="stat-grid-3">
<div class="stat-item">
<div class="stat-label">Total</div>
<div class="stat-value">{total}</div>
</div>
<div class="stat-item">
<div class="stat-label">๐ฅ Hot Flash Risk</div>
<div class="stat-value" style="color:#ef4444">{hot_flags}</div>
</div>
<div class="stat-item">
<div class="stat-label">๐ค Mood Risk</div>
<div class="stat-value" style="color:#7c3aed">{mood_flags}</div>
</div>
</div>
<div class="stat-grid-2">
<div class="stat-item">
<div class="stat-label">Avg Hot Flash Prob</div>
<div class="stat-value" style="color:#ef4444;font-size:18px">
{mean_hot:.1%}
</div>
</div>
<div class="stat-item">
<div class="stat-label">Avg Mood Prob</div>
<div class="stat-value" style="color:#7c3aed;font-size:18px">
{mean_mood:.1%}
</div>
</div>
</div>
<div class="output-path-box">
<div class="output-path-title">๐ Outputs saved to:</div>
<div class="output-path-dir">{run_dir}/</div>
<div class="output-path-files">
predictions/batch_symptom_forecast.csv<br>
reports/batch_symptom_summary.txt
</div>
</div>
</div>
"""
return str(csv_path), summary_html, results
except Exception as exc:
return None, f"โ Error: {exc}", None
# โโ Feature reference & model status โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def get_feature_reference() -> str:
feature_names = _metadata.get("feature_names", list(FEATURE_DESCRIPTIONS.keys()))
rows = ""
for i, f in enumerate(feature_names[:60]):
desc = FEATURE_DESCRIPTIONS.get(f, f.split("_")[0])
rows += f"""
<tr>
<td class="feature-num">{i + 1}</td>
<td class="feature-code">{f}</td>
<td class="feature-desc">{desc}</td>
</tr>"""
remaining = len(feature_names) - 60
if remaining > 0:
rows += f"""
<tr>
<td colspan="3" style="padding:8px;color:#9ca3af;font-size:12px;text-align:center">
โฆ and {remaining} more features (one-hot encoded categories)
</td>
</tr>"""
return f"""
<div class="feature-table-wrap">
<div style="color:#111827;font-size:16px;font-weight:700;margin-bottom:14px">
๐ Training Features ({len(feature_names)} total after encoding)
</div>
<table>
<thead>
<tr>
<th>#</th>
<th>Feature</th>
<th>Description</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
</div>
"""
def get_model_status() -> str:
if _MODEL_OK:
fc = len(_metadata.get("feature_names", []))
sc = _metadata.get("stage_classes", ["pre", "peri", "post"])
badges = "".join(
f'<span style="background:{STAGE_COLORS.get(s,"#607d8b")}18;'
f'color:{STAGE_COLORS.get(s,"#555")};padding:4px 12px;'
f'border-radius:20px;border:1px solid {STAGE_COLORS.get(s,"#607d8b")}44;'
f'font-size:13px;font-weight:600">{STAGE_EMOJI.get(s,"")} {s}</span>'
for s in sc
)
return f"""
<div class="status-card">
<div style="display:flex;align-items:center;gap:10px;margin-bottom:14px">
<span style="font-size:24px">โ
</span>
<div>
<div style="color:#059669;font-size:16px;font-weight:700">
Models Loaded Successfully
</div>
<div style="color:#6b7280;font-size:12px">Ready for predictions</div>
</div>
</div>
<div class="stat-grid-3">
<div class="stat-item">
<div class="stat-label">Features</div>
<div class="stat-value">{fc}</div>
</div>
<div class="stat-item">
<div class="stat-label">Models</div>
<div class="stat-value">2</div>
</div>
<div class="stat-item">
<div class="stat-label">Stages</div>
<div class="stat-value">{len(sc)}</div>
</div>
</div>
<div style="margin-top:14px">
<div style="color:#6b7280;font-size:11px;text-transform:uppercase;
letter-spacing:0.5px;margin-bottom:6px">Available Stages</div>
<div style="display:flex;gap:8px;flex-wrap:wrap">{badges}</div>
</div>
</div>
"""
return f"""
<div class="status-card">
<div style="display:flex;align-items:center;gap:10px;margin-bottom:10px">
<span style="font-size:24px">โ ๏ธ</span>
<div>
<div style="color:#dc2626;font-size:16px;font-weight:700">
Models Not Loaded
</div>
<div style="color:#6b7280;font-size:12px">{_MODEL_MSG}</div>
</div>
</div>
<div style="background:#fef2f2;border:1px solid #fecaca;border-radius:8px;
padding:12px;color:#9f1239;font-size:13px">
To train and save models:<br>
<code style="background:#1e293b;color:#a3e635;padding:4px 8px;border-radius:4px;
margin-top:6px;display:inline-block">python menopause.py</code>
<br><br>
This generates <code style="background:#e2e8f0;padding:2px 5px;border-radius:3px;
color:#1e293b">swan_ml_output/rf_pipeline.pkl</code>,
<code style="background:#e2e8f0;padding:2px 5px;border-radius:3px;
color:#1e293b">lr_pipeline.pkl</code>, and
<code style="background:#e2e8f0;padding:2px 5px;border-radius:3px;
color:#1e293b">forecast_metadata.json</code>.
</div>
</div>
"""
# โโ Education content โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
EDUCATION_HTML = """
<div class="edu-card">
<h2>๐ธ Understanding Menopause</h2>
<p>Menopause is a natural biological process marking the end of menstrual cycles.
It is officially diagnosed after 12 consecutive months without a menstrual period
and typically occurs in women in their late 40s to early 50s.</p>
<h3>Three Stages</h3>
<div class="stage-cards-grid">
<div class="stage-card-pre">
<div style="color:#16a34a;font-weight:700;margin-bottom:8px">๐ข Pre-Menopause</div>
<p style="font-size:13px;margin:0;color:#374151">Regular ovarian function. Periods are predictable.
Hormones (estrogen, progesterone) follow a consistent monthly pattern.</p>
</div>
<div class="stage-card-peri">
<div style="color:#d97706;font-weight:700;margin-bottom:8px">๐ก Peri-Menopause</div>
<p style="font-size:13px;margin:0;color:#374151">Transition phase โ usually begins in the mid-40s.
Hormone levels fluctuate. Periods become irregular.
Hot flashes and sleep issues may begin.</p>
</div>
<div class="stage-card-post">
<div style="color:#7c3aed;font-weight:700;margin-bottom:8px">๐ฃ Post-Menopause</div>
<p style="font-size:13px;margin:0;color:#374151">12+ months after the last period.
Lower estrogen levels. Risk factors for osteoporosis and
cardiovascular disease increase.</p>
</div>
</div>
<h3>Common Symptoms by Stage</h3>
<table style="width:100%;border-collapse:collapse;font-size:13px">
<thead>
<tr style="background:#f8fafc">
<th style="padding:8px;text-align:left;color:#6b7280;font-weight:600">Symptom</th>
<th style="padding:8px;text-align:center;color:#16a34a;font-weight:600">Pre</th>
<th style="padding:8px;text-align:center;color:#d97706;font-weight:600">Peri</th>
<th style="padding:8px;text-align:center;color:#7c3aed;font-weight:600">Post</th>
</tr>
</thead>
<tbody>
<tr style="border-bottom:1px solid #e2e8f0">
<td style="padding:8px;color:#374151">Hot flashes</td>
<td style="text-align:center;color:#9ca3af">โ</td>
<td style="text-align:center">โ
</td>
<td style="text-align:center">โ
</td>
</tr>
<tr style="border-bottom:1px solid #e2e8f0">
<td style="padding:8px;color:#374151">Irregular periods</td>
<td style="text-align:center;color:#9ca3af">โ</td>
<td style="text-align:center">โ
</td>
<td style="text-align:center;color:#9ca3af">N/A</td>
</tr>
<tr style="border-bottom:1px solid #e2e8f0">
<td style="padding:8px;color:#374151">Sleep disturbances</td>
<td style="text-align:center;color:#6b7280">Mild</td>
<td style="text-align:center">โ
</td>
<td style="text-align:center">โ
</td>
</tr>
<tr style="border-bottom:1px solid #e2e8f0">
<td style="padding:8px;color:#374151">Mood changes</td>
<td style="text-align:center;color:#6b7280">PMS</td>
<td style="text-align:center">โ
</td>
<td style="text-align:center;color:#6b7280">Possible</td>
</tr>
<tr style="border-bottom:1px solid #e2e8f0">
<td style="padding:8px;color:#374151">Vaginal dryness</td>
<td style="text-align:center;color:#9ca3af">โ</td>
<td style="text-align:center;color:#6b7280">Possible</td>
<td style="text-align:center">โ
</td>
</tr>
<tr>
<td style="padding:8px;color:#374151">Bone density changes</td>
<td style="text-align:center;color:#9ca3af">โ</td>
<td style="text-align:center;color:#6b7280">Begins</td>
<td style="text-align:center">โ
</td>
</tr>
</tbody>
</table>
<h3>About This Tool</h3>
<p style="font-size:13px">This application uses machine learning models trained on the
SWAN (Study of Women's Health Across the Nation) dataset โ a landmark multisite,
multiethnic longitudinal study. The models were trained on self-reported symptom and
behavioral data to predict menopausal stage.</p>
<div class="disclaimer-box">
โ ๏ธ <strong style="color:#d97706">Disclaimer:</strong>
This tool is for educational and research purposes only.
Predictions should not substitute clinical diagnosis.
Always consult a qualified healthcare provider for medical advice.
</div>
</div>
"""
# โโ Gradio UI โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
CUSTOM_CSS = """
/* โโ Force light mode โ disable Gradio dark theme entirely โโโโโโโโโโโโโ */
:root {
color-scheme: light only !important;
}
/* Fallback: if Gradio somehow sets .dark, override every key variable */
body.dark,
body.dark .gradio-container {
--body-background-fill: #f0f4f8 !important;
--background-fill-primary: #ffffff !important;
--background-fill-secondary: #f8fafc !important;
--border-color-primary: #e2e8f0 !important;
--border-color-accent: #3b82f6 !important;
--color-accent: #2563eb !important;
--color-accent-soft: #eff6ff !important;
--input-background-fill: #ffffff !important;
--input-border-color: #d1d5db !important;
--label-text-color: #374151 !important;
--block-label-text-color: #374151 !important;
--block-title-text-color: #111827 !important;
--body-text-color: #111827 !important;
--body-text-color-subdued: #6b7280 !important;
--link-text-color: #2563eb !important;
--button-primary-background-fill: #2563eb !important;
--button-primary-text-color: #ffffff !important;
--button-secondary-background-fill: #ffffff !important;
--button-secondary-text-color: #374151 !important;
--tab-text-color: #374151 !important;
--tab-text-color-selected: #2563eb !important;
color: #111827 !important;
background-color: #f0f4f8 !important;
}
/* โโ Core โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
.gradio-container {
max-width: 1200px !important;
margin: 0 auto !important;
font-family: 'Segoe UI', system-ui, -apple-system, sans-serif !important;
background: #f0f4f8 !important;
}
/* โโ Header banner โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
.header-banner {
background: linear-gradient(135deg, #faf5ff 0%, #fff0f9 50%, #eff6ff 100%);
border: 1px solid #e9d5ff;
border-radius: 16px;
padding: 28px 32px;
margin-bottom: 20px;
box-shadow: 0 2px 8px rgba(139,92,246,0.08);
position: relative;
overflow: hidden;
}
.header-banner::before {
content: '';
position: absolute;
top: -40%; right: -5%;
width: 280px; height: 280px;
background: radial-gradient(circle, rgba(139,92,246,0.08) 0%, transparent 70%);
pointer-events: none;
}
/* โโ Reusable info boxes โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
.info-box {
background: #f8fafc;
border: 1px solid #e2e8f0;
border-left: 3px solid #3b82f6;
border-radius: 8px;
padding: 12px 16px;
color: #475569;
font-size: 13px;
margin-bottom: 16px;
line-height: 1.5;
}
.info-box code {
background: #e2e8f0;
color: #1e293b;
padding: 1px 5px;
border-radius: 3px;
font-family: monospace;
font-size: 0.9em;
}
.section-label {
color: #2563eb;
font-size: 12px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.6px;
margin-bottom: 10px;
margin-top: 10px;
}
.format-hint {
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 8px;
padding: 14px;
margin-top: 10px;
font-size: 12px;
color: #475569;
}
.format-hint-title { color: #2563eb; font-weight: 600; margin-bottom: 6px; }
.format-hint pre { color: #475569; margin: 0; font-size: 11px; white-space: pre-wrap; }
.format-hint-note { color: #94a3b8; font-size: 11px; margin-top: 8px; }
.placeholder-msg { color: #9ca3af; text-align: center; padding: 40px; font-size: 14px; }
.section-divider { border: none; border-top: 1px solid #e2e8f0; margin: 24px 0; }
.batch-section-label { color: #2563eb; font-size: 14px; font-weight: 600; margin-bottom: 12px; }
/* โโ Result & summary cards โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
.result-card {
background: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 16px;
padding: 24px;
box-shadow: 0 1px 4px rgba(0,0,0,0.06);
font-family: 'Segoe UI', system-ui, sans-serif;
}
.stat-grid-3 { display:grid; grid-template-columns:repeat(3,1fr); gap:12px; margin:14px 0; }
.stat-grid-2 { display:grid; grid-template-columns:1fr 1fr; gap:10px; margin-top:10px; }
.stat-item { background:#f8fafc; border:1px solid #e2e8f0; padding:12px; border-radius:8px; text-align:center; }
.stat-label { color:#6b7280; font-size:11px; text-transform:uppercase; letter-spacing:0.4px; }
.stat-value { color:#111827; font-size:22px; font-weight:700; line-height:1.2; margin-top:2px; }
.output-path-box { background:#f0fdf4; border:1px solid #bbf7d0; border-radius:8px; padding:10px 14px; margin-top:12px; font-family:monospace; }
.output-path-title { color:#059669; font-size:12px; font-weight:600; }
.output-path-dir { color:#065f46; font-size:11px; margin-top:4px; }
.output-path-files { color:#6b7280; font-size:10px; margin-top:4px; line-height:1.6; }
/* โโ Code blocks โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
.code-block {
background: #1e293b;
color: #a3e635;
border-radius: 8px;
padding: 12px;
font-size: 12px;
font-family: monospace;
white-space: pre;
overflow-x: auto;
}
/* โโ Setup instructions card โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
.setup-card { background:#ffffff; border:1px solid #e2e8f0; border-radius:12px; padding:20px; margin-top:16px; font-family:'Segoe UI',system-ui,sans-serif; }
.setup-title { color:#111827; font-size:15px; font-weight:700; margin-bottom:12px; }
.setup-step { color:#374151; font-size:13px; line-height:1.8; }
.setup-step strong { color:#2563eb; }
/* โโ Education โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
.edu-card { background:#ffffff; border:1px solid #e2e8f0; border-radius:16px; padding:28px; font-family:'Segoe UI',system-ui,sans-serif; color:#374151; line-height:1.7; }
.edu-card h2 { color:#111827; font-size:22px; margin-top:0; }
.edu-card h3 { color:#7c3aed; font-size:16px; margin-top:20px; }
.stage-cards-grid { display:grid; grid-template-columns:repeat(3,1fr); gap:16px; margin:14px 0; }
.stage-card-pre { background:#f0fdf4; border-top:4px solid #16a34a; padding:16px; border-radius:10px; }
.stage-card-peri { background:#fffbeb; border-top:4px solid #d97706; padding:16px; border-radius:10px; }
.stage-card-post { background:#faf5ff; border-top:4px solid #7c3aed; padding:16px; border-radius:10px; }
.disclaimer-box { background:#fffbeb; border-left:3px solid #d97706; padding:12px 16px; border-radius:0 8px 8px 0; margin-top:14px; font-size:13px; color:#374151; }
/* โโ Feature reference table โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
.feature-table-wrap { background:#ffffff; border:1px solid #e2e8f0; border-radius:12px; padding:20px; max-height:500px; overflow-y:auto; font-family:'Segoe UI',system-ui,sans-serif; }
.feature-table-wrap table { width:100%; border-collapse:collapse; }
.feature-table-wrap thead tr { background:#f8fafc; }
.feature-table-wrap th { padding:8px; color:#6b7280; font-size:11px; text-align:left; text-transform:uppercase; letter-spacing:0.4px; }
.feature-table-wrap tr { border-bottom:1px solid #e2e8f0; }
.feature-table-wrap td { padding:8px; }
.feature-code { color:#2563eb; font-family:monospace; font-size:13px; }
.feature-desc { color:#374151; font-size:12px; }
.feature-num { color:#9ca3af; font-size:12px; }
/* โโ Model status card โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
.status-card { background:#ffffff; border:1px solid #e2e8f0; border-radius:12px; padding:20px; font-family:'Segoe UI',system-ui,sans-serif; }
/* โโ Footer โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
.app-footer { text-align:center; color:#9ca3af; font-size:11px; margin-top:24px; padding:16px; border-top:1px solid #e2e8f0; }
.app-footer a { color:#2563eb; text-decoration:none; }
/* โโ Responsive โ Tablet (โค 768 px) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
@media (max-width: 768px) {
.gradio-container { padding: 8px !important; }
.header-banner { padding: 16px 20px !important; margin-bottom: 12px !important; }
.header-status-badge { display: none !important; }
.stat-grid-3 { grid-template-columns: 1fr !important; }
.stat-grid-2 { grid-template-columns: 1fr !important; }
.stage-cards-grid { grid-template-columns: 1fr !important; }
}
/* โโ Responsive โ Mobile (โค 480 px) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ */
@media (max-width: 480px) {
.header-banner h1 { font-size: 18px !important; }
.result-card { padding: 16px !important; }
.edu-card { padding: 16px !important; }
.setup-card { padding: 14px !important; }
}
"""
HEADER_HTML = """
<div class="header-banner">
<div style="display:flex;align-items:center;gap:16px;flex-wrap:wrap">
<div style="font-size:48px;flex-shrink:0">๐ธ</div>
<div style="flex:1;min-width:200px">
<h1 style="margin:0;font-size:26px;font-weight:800;
background:linear-gradient(135deg,#7c3aed,#db2777);
-webkit-background-clip:text;-webkit-text-fill-color:transparent">
SWAN Menopause Prediction
</h1>
<p style="margin:4px 0 0;color:#6b7280;font-size:13px">
AI-powered menopausal stage prediction & symptom forecasting ยท
Based on the SWAN dataset
</p>
</div>
<div class="header-status-badge" style="text-align:right;flex-shrink:0">
<div style="background:#ffffff;border:1px solid #e2e8f0;border-radius:8px;
padding:8px 16px;display:inline-block;box-shadow:0 1px 3px rgba(0,0,0,0.06)">
<div style="color:#9ca3af;font-size:10px;text-transform:uppercase;letter-spacing:1px">
Status
</div>
<div style="color:{color};font-size:13px;font-weight:600">{status}</div>
</div>
</div>
</div>
</div>
""".format(
color = "#059669" if _MODEL_OK else "#dc2626",
status = "Models Ready โ
" if _MODEL_OK else "Models Needed โ ๏ธ",
)
# โโ Force-light-mode JS (runs on every page load) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# Removes Gradio's .dark class, locks localStorage to "light", and uses a
# MutationObserver to prevent the class from being re-applied โ works on
# HuggingFace Spaces regardless of the user's OS/browser dark-mode setting.
FORCE_LIGHT_JS = """
function() {
const forceLightMode = () => {
if (document.body.classList.contains('dark')) {
document.body.classList.remove('dark');
}
};
// Apply immediately
forceLightMode();
// Lock Gradio's stored preference
try { localStorage.setItem('theme', 'light'); } catch(e) {}
// Watch for Gradio trying to re-add .dark and block it
new MutationObserver(function(mutations) {
mutations.forEach(function(m) {
if (m.attributeName === 'class') forceLightMode();
});
}).observe(document.body, { attributes: true, attributeFilter: ['class'] });
}
"""
# โโ App builder โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def build_app():
with gr.Blocks(
css = CUSTOM_CSS,
js = FORCE_LIGHT_JS,
title = "SWAN Menopause Prediction",
theme = gr.themes.Soft(
primary_hue = "blue",
neutral_hue = "slate",
).set(
# โโ Body โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
body_background_fill = "#f0f4f8",
body_background_fill_dark = "#f0f4f8",
body_text_color = "#111827",
body_text_color_dark = "#111827",
body_text_color_subdued = "#6b7280",
body_text_color_subdued_dark = "#6b7280",
# โโ Panel / block backgrounds โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
background_fill_primary = "#ffffff",
background_fill_primary_dark = "#ffffff",
background_fill_secondary = "#f8fafc",
background_fill_secondary_dark = "#f8fafc",
block_background_fill = "#ffffff",
block_background_fill_dark = "#ffffff",
block_border_color = "#e2e8f0",
block_border_color_dark = "#e2e8f0",
block_label_background_fill = "#f8fafc",
block_label_background_fill_dark= "#f8fafc",
block_label_text_color = "#374151",
block_label_text_color_dark = "#374151",
block_title_text_color = "#111827",
block_title_text_color_dark = "#111827",
# โโ Inputs โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
input_background_fill = "#ffffff",
input_background_fill_dark = "#ffffff",
input_background_fill_focus = "#ffffff",
input_background_fill_focus_dark= "#ffffff",
input_border_color = "#d1d5db",
input_border_color_dark = "#d1d5db",
input_border_color_focus = "#3b82f6",
input_border_color_focus_dark = "#3b82f6",
input_placeholder_color = "#9ca3af",
input_placeholder_color_dark = "#9ca3af",
# โโ Borders โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
border_color_primary = "#e2e8f0",
border_color_primary_dark = "#e2e8f0",
border_color_accent = "#3b82f6",
border_color_accent_dark = "#3b82f6",
# โโ Buttons โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
button_primary_background_fill = "#2563eb",
button_primary_background_fill_dark = "#2563eb",
button_primary_background_fill_hover = "#1d4ed8",
button_primary_background_fill_hover_dark = "#1d4ed8",
button_primary_text_color = "#ffffff",
button_primary_text_color_dark = "#ffffff",
button_secondary_background_fill = "#ffffff",
button_secondary_background_fill_dark = "#ffffff",
button_secondary_background_fill_hover = "#f1f5f9",
button_secondary_background_fill_hover_dark="#f1f5f9",
button_secondary_text_color = "#374151",
button_secondary_text_color_dark = "#374151",
button_secondary_border_color = "#e2e8f0",
button_secondary_border_color_dark = "#e2e8f0",
# โโ Checkbox / Radio โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
checkbox_background_color = "#ffffff",
checkbox_background_color_dark = "#ffffff",
checkbox_background_color_selected = "#2563eb",
checkbox_background_color_selected_dark = "#2563eb",
checkbox_border_color = "#d1d5db",
checkbox_border_color_dark = "#d1d5db",
checkbox_border_color_focus = "#3b82f6",
checkbox_border_color_focus_dark = "#3b82f6",
# โโ Slider โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
slider_color = "#2563eb",
slider_color_dark = "#2563eb",
# โโ Table โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
table_odd_background_fill = "#f8fafc",
table_odd_background_fill_dark = "#f8fafc",
table_even_background_fill = "#ffffff",
table_even_background_fill_dark = "#ffffff",
table_border_color = "#e2e8f0",
table_border_color_dark = "#e2e8f0",
# โโ Links โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
link_text_color = "#2563eb",
link_text_color_dark = "#2563eb",
link_text_color_hover = "#1d4ed8",
link_text_color_hover_dark = "#1d4ed8",
link_text_color_visited = "#7c3aed",
link_text_color_visited_dark = "#7c3aed",
# โโ Accent โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
color_accent_soft = "#eff6ff",
color_accent_soft_dark = "#eff6ff",
),
) as app:
gr.HTML(HEADER_HTML)
with gr.Tabs():
# โโ TAB 1: Single Stage Prediction โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Tab("๐ฎ Stage Prediction"):
gr.HTML("""
<div class="info-box">
Fill in the fields below to predict menopausal stage for a single individual.
All fields are optional โ the pipeline handles missing values automatically.
A timestamped output folder is created in
<code>swan_ml_output/</code> for every run.
</div>""")
with gr.Row():
# โโ Input column โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Column(scale=2):
with gr.Group():
gr.HTML('<div class="section-label">Demographics</div>')
with gr.Row():
age = gr.Slider(
minimum=35, maximum=75, value=48, step=1,
label="Age (AGE7)",
)
race = gr.Dropdown(
choices=[1, 2, 3, 4, 5], value=1,
label="Race (RACE)",
info="1=White, 2=Black, 3=Chinese, 4=Japanese, 5=Hispanic",
)
langint = gr.Dropdown(
choices=[1, 2, 3], value=1,
label="Interview Language (LANGINT7)",
info="1=English, 2=Spanish, 3=Other",
)
with gr.Group():
gr.HTML('<div class="section-label">Vasomotor Symptoms</div>')
with gr.Row():
hot_flash = gr.Slider(
minimum=1, maximum=5, value=1, step=1,
label="Hot Flash Severity (HOTFLAS7)",
info="1=None, 5=Very severe",
)
num_hot_flash = gr.Slider(
minimum=0, maximum=15, value=0, step=1,
label="# Hot Flashes/Week (NUMHOTF7)",
)
bothersome_hf = gr.Slider(
minimum=1, maximum=4, value=1, step=1,
label="How Bothersome (BOTHOTF7)",
info="1=Not at all, 4=Extremely",
)
with gr.Group():
gr.HTML('<div class="section-label">Sleep & Mood</div>')
with gr.Row():
sleep_quality = gr.Slider(
minimum=1, maximum=5, value=2, step=1,
label="Sleep Quality (SLEEPQL7)",
info="1=Very good, 5=Very poor",
)
depression = gr.Slider(
minimum=0, maximum=4, value=0, step=1,
label="Depression Indicator (DEPRESS7)",
info="0=No, higher=more severe",
)
with gr.Row():
mood_change = gr.Slider(
minimum=1, maximum=5, value=1, step=1,
label="Mood Changes (MOODCHG7)",
info="1=None, 5=Severe",
)
irritability = gr.Slider(
minimum=1, maximum=5, value=1, step=1,
label="Irritability (IRRITAB7)",
)
with gr.Group():
gr.HTML('<div class="section-label">Physical & Gynaecological</div>')
with gr.Row():
pain = gr.Slider(
minimum=0, maximum=5, value=0, step=1,
label="Pain Indicator (PAIN17)",
)
abbleed = gr.Dropdown(
choices=[0, 1, 2], value=0,
label="Abnormal Bleeding (ABBLEED7)",
info="0=No, 1=Yes, 2=Unsure",
)
with gr.Row():
vaginal_dryness = gr.Slider(
minimum=0, maximum=5, value=0, step=1,
label="Vaginal Dryness (VAGINDR7)",
)
lmp_day = gr.Number(
value=None,
label="LMP Day (LMPDAY7)",
info="Day of last menstrual period (optional)",
)
model_choice = gr.Radio(
choices=["RandomForest", "LogisticRegression"],
value="RandomForest",
label="Model",
info="RandomForest: higher accuracy | "
"LogisticRegression: more interpretable",
)
predict_btn = gr.Button(
"๐ฎ Predict Stage", variant="primary", size="lg"
)
# โโ Output column โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Column(scale=3):
result_html = gr.HTML(
'<div class="placeholder-msg">Fill in the form and click Predict Stage</div>'
)
result_chart = gr.Plot(label="Stage Probabilities")
confidence_note = gr.Textbox(
label="Confidence Note", interactive=False, lines=2
)
compare_html = gr.HTML()
stage_download = gr.File(
label="Download Prediction CSV", interactive=False
)
predict_btn.click(
fn = predict_single_stage,
inputs = [
age, race, langint,
hot_flash, num_hot_flash, bothersome_hf,
sleep_quality, depression, mood_change, irritability,
pain, abbleed, vaginal_dryness, lmp_day,
model_choice,
],
outputs = [
result_html, result_chart, confidence_note,
compare_html, stage_download,
],
)
# โโ TAB 2: Batch Stage Prediction โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Tab("๐ Batch Stage Prediction"):
gr.HTML("""
<div class="info-box">
Upload a CSV file with individual feature values for batch prediction.
Results + charts + a summary report are saved to a timestamped folder
inside <code>swan_ml_output/</code>.
</div>""")
with gr.Row():
with gr.Column(scale=1):
batch_file = gr.File(
label="Upload stage_input.csv",
file_types=[".csv"],
)
batch_model = gr.Radio(
choices=["RandomForest", "LogisticRegression"],
value="RandomForest",
label="Model",
)
gr.HTML("""
<div class="format-hint">
<div class="format-hint-title">Expected CSV Format</div>
<pre>individual,AGE7,RACE,HOTFLAS7,...
Person_001,48,1,2,...
Person_002,52,2,1,...</pre>
<div class="format-hint-note">
See the test-csv/ folder for an approved example.
</div>
</div>""")
batch_predict_btn = gr.Button(
"๐ Run Batch Prediction", variant="primary"
)
with gr.Column(scale=2):
batch_summary_html = gr.HTML(
'<div class="placeholder-msg">Upload a CSV to begin</div>'
)
batch_download = gr.File(
label="Download Predictions CSV", interactive=False
)
batch_results_df = gr.DataFrame(
label="Results Preview (first 20 rows)",
interactive=False,
)
batch_predict_btn.click(
fn = predict_batch_stage,
inputs = [batch_file, batch_model],
outputs = [batch_download, batch_summary_html, batch_results_df],
)
# โโ TAB 3: Symptom Forecast โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Tab("๐ Symptom Forecast"):
gr.HTML("""
<div class="info-box">
Predict hot flash and mood change probability based on cycle day
(calculated from Last Menstrual Period date).
All outputs are saved to a timestamped folder inside
<code>swan_ml_output/</code>.
</div>""")
with gr.Row():
with gr.Column(scale=1):
sym_individual = gr.Textbox(
label="Individual ID (optional)",
placeholder="e.g., Patient_001",
)
sym_lmp = gr.Textbox(
label="Last Menstrual Period (LMP)",
placeholder="2026-01-15 or 15 (day of month)",
info="Full date (YYYY-MM-DD) or day-of-month integer",
)
sym_date = gr.Textbox(
label="Target Date (optional)",
placeholder="2026-02-27 (defaults to today)",
info="Date to forecast for (YYYY-MM-DD)",
)
sym_cycle = gr.Slider(
minimum=21, maximum=40, value=28, step=1,
label="Cycle Length (days)",
)
sym_predict_btn = gr.Button(
"๐ Forecast Symptoms", variant="primary"
)
with gr.Column(scale=2):
sym_result_html = gr.HTML(
'<div class="placeholder-msg">Enter LMP date and click Forecast</div>'
)
sym_chart = gr.Plot(label="Cycle Position")
sym_download = gr.File(
label="Download Forecast CSV", interactive=False
)
sym_predict_btn.click(
fn = predict_symptoms,
inputs = [sym_individual, sym_lmp, sym_date, sym_cycle],
outputs = [sym_result_html, sym_chart, sym_download],
)
gr.HTML('<hr class="section-divider">')
gr.HTML('<div class="batch-section-label">๐ Batch Symptom Forecasting</div>')
with gr.Row():
with gr.Column(scale=1):
sym_batch_file = gr.File(
label="Upload symptoms_input.csv",
file_types=[".csv"],
)
sym_lmp_col = gr.Textbox(
label="LMP Column Name", value="LMP"
)
sym_date_col = gr.Textbox(
label="Date Column Name (optional)", value="date"
)
sym_cycle_batch = gr.Slider(
minimum=21, maximum=40, value=28, step=1,
label="Default Cycle Length",
)
sym_batch_btn = gr.Button(
"๐ Run Batch Forecast", variant="primary"
)
with gr.Column(scale=2):
sym_batch_summary = gr.HTML(
'<div class="placeholder-msg">Upload a CSV to begin</div>'
)
sym_batch_download = gr.File(
label="Download Symptom Forecast CSV", interactive=False
)
sym_batch_df = gr.DataFrame(
label="Results Preview",
interactive=False,
)
sym_batch_btn.click(
fn = predict_symptoms_batch,
inputs = [
sym_batch_file, sym_lmp_col,
sym_date_col, sym_cycle_batch,
],
outputs = [sym_batch_download, sym_batch_summary, sym_batch_df],
)
# โโ TAB 4: Education โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Tab("๐ Menopause Education"):
gr.HTML(EDUCATION_HTML)
# โโ TAB 5: Feature Reference โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Tab("๐ฌ Feature Reference"):
gr.HTML("""
<div class="info-box">
Canonical list of features used by the trained models
(from <code>forecast_metadata.json</code>).
For batch CSV uploads, column names must match these feature names.
</div>""")
gr.HTML(get_feature_reference())
# โโ TAB 6: Model Status โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
with gr.Tab("โ๏ธ Model Status"):
gr.HTML(get_model_status())
gr.HTML("""
<div class="setup-card">
<div class="setup-title">๐ Setup Instructions</div>
<div class="setup-step">
<p><strong>Step 1 โ Train models:</strong></p>
<pre class="code-block">python menopause.py</pre>
<p><strong>Step 2 โ Verify artifacts:</strong></p>
<pre class="code-block">ls swan_ml_output/
# rf_pipeline.pkl lr_pipeline.pkl forecast_metadata.json</pre>
<p><strong>Step 3 โ Run this app:</strong></p>
<pre class="code-block">python app.py</pre>
<p><strong>Step 4 โ Deploy on Hugging Face Spaces:</strong></p>
<pre class="code-block">git lfs install
git lfs track "*.pkl"
git add .
git commit -m "SWAN menopause prediction app"
git push</pre>
<p><strong>Output folder structure (per run):</strong></p>
<pre class="code-block">swan_ml_output/
<YYYYMMDD_HHMMSS>/
charts/ ← PNG visualizations
predictions/ ← CSV result files
reports/ ← TXT summary reports</pre>
</div>
</div>
""")
gr.HTML("""
<div class="app-footer">
SWAN Menopause Prediction App ยท Built with Gradio ยท
For research & educational use only ยท Not for clinical diagnosis ยท
<a href="https://www.swanstudy.org/" target="_blank">SWAN Study</a>
</div>""")
return app
# โโ Entry point โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
if __name__ == "__main__":
demo = build_app()
demo.launch(
server_name = "0.0.0.0",
server_port = int(os.environ.get("PORT", 7860)),
share = False,
show_error = True,
)
|