Spaces:
Running
Running
File size: 83,286 Bytes
fb64168 63b8a00 2feaf5f 63b8a00 fb64168 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 1a49717 63b8a00 fb64168 63b8a00 fb64168 17b7fc2 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 17b7fc2 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 17b7fc2 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 17b7fc2 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 17b7fc2 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 f8ea596 63b8a00 fb64168 63b8a00 |
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 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>EPIC-AMP</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" integrity="sha512-9usAa10IRO0HhonpyAIVpjrylPvoDwiPUiKdWk5t3PyolY1cOd4DSE0Ga+ri4AuTroPR5aQvXU9xC6qOPnzFeg==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="icon" type="image/png" href="favicon.png">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.23/jspdf.plugin.autotable.min.js"></script>
<style>
:root {
--primary-color: #004d40; /* Dark Teal */
--secondary-color: #00897b; /* Teal */
--success-color: #4caf50; /* Green */
--warning-color: #ff9800; /* Orange */
--info-color: #2196f3; /* Blue */
--background-color: #f0f4c3; /* Light Lime */
--text-color: #333; /* Dark Gray */
--container-bg-color: #ffffff; /* White */
--border-color: #bdbdbd; /* Light Gray */
--button-hover-bg: #00695c; /* Darker Teal */
--clear-button-bg: #f44336; /* Red */
--clear-button-hover-bg: #d32f2f; /* Darker Red */
--analyze-button-bg: #00897b; /* Teal */
--analyze-button-hover-bg: #00695c; /* Darker Teal */
}
/* Optional Dark Mode */
.dark-mode {
--primary-color: #b2dfdb; /* Light Teal */
--secondary-color: #4db6ac; /* Medium Teal */
--success-color: #81c784; /* Light Green */
--warning-color: #ffcc80; /* Light Orange */
--info-color: #90caf9; /* Light Blue */
--background-color: #212121; /* Dark Gray */
--text-color: #eee; /* Light Gray */
--container-bg-color: #424242;/* Darker Gray */
--border-color: #616161; /* Medium Gray */
--button-hover-bg: #004d40; /* Dark Teal */
--clear-button-bg: #e57373; /* Light Red */
--clear-button-hover-bg: #f44336; /* Red */
--analyze-button-bg: #4db6ac; /* Medium Teal */
--analyze-button-hover-bg: #009688; /* Teal */
}
body {
font-family: 'Arial', sans-serif;
line-height: 1.6;
margin: 0;
padding: 20px;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
background-color: var(--background-color);
color: var(--text-color);
transition: background-color 0.3s ease, color 0.3s ease;
}
.container {
max-width: 800px;
width: 100%;
padding: 2rem;
background: var(--container-bg-color);
border-radius: 10px;
box-shadow: 0 2px 15px rgba(0,0,0,0.1);
text-align: center;
transition: background-color 0.3s ease;
display: flex;
flex-direction: column;
margin-bottom: 20px;
}
.input-group {
margin-bottom: 1.5rem;
position: relative;
}
#sequence {
width: 100%;
height: 150px;
padding: 1rem;
border: 2px solid var(--border-color);
border-radius: 8px;
font-family: monospace;
font-size: 1rem;
resize: vertical;
transition: border-color 0.3s ease, background-color 0.3s ease;
background-color: var(--container-bg-color);
color: var(--text-color);
box-sizing: border-box;
}
#file-input {
margin-bottom: 1rem;
}
#sequence:focus {
outline: none;
border-color: var(--secondary-color);
}
button {
color: white;
border: none;
padding: 0.8rem 2rem;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
transition: transform 0.2s ease, background-color 0.3s ease;
/* margin-top: 1rem; Removed individual margin-top for buttons */
}
.button-group button{
margin: 0 0.2rem;
}
button:hover {
transform: translateY(-1px);
}
#clear-btn {
background-color: var(--clear-button-bg);
}
#clear-btn:hover {
background-color: var(--clear-button-hover-bg);
}
#predict-btn {
background-color: var(--analyze-button-bg);
min-width: 230px; /* To accommodate count-up text better */
}
#predict-btn:hover {
background-color: var(--analyze-button-hover-bg);
}
.character-count {
text-align: right;
color: var(--text-color);
font-size: 0.9rem;
margin-top: 0.5rem;
}
.error-message {
color: var(--warning-color);
text-align: center;
margin-top: 1rem;
display: none;
}
.result {
margin-top: 1.5rem;
font-size: 1.2rem;
font-weight: bold;
color: var(--primary-color);
text-align: center;
}
.info-icon {
position: absolute;
top: 1rem;
right: 1rem;
font-size: 1.2rem;
color: var(--info-color);
cursor: pointer;
}
.tooltip {
position: absolute;
top: 100%;
right: 0;
background-color: rgba(0, 0, 0, 0.8);
color: white;
padding: 0.5rem;
border-radius: 5px;
display: none;
z-index: 10;
width: 250px;
text-align: left;
font-size: 0.9rem;
line-height: 1.4;
}
.info-icon:hover + .tooltip,
.tooltip:hover {
display: block;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(-10px); }
to { opacity: 1; transform: translateY(0); }
}
.result.show {
animation: fadeIn 0.5s ease forwards;
}
.tabs {
display: flex;
justify-content: center;
margin-bottom: 1rem;
border-bottom: 2px solid var(--border-color);
}
.tab {
padding: 0.5rem 1rem;
margin: 0 0.5rem;
cursor: pointer;
border: 2px solid transparent;
border-radius: 5px 5px 0 0;
background-color: transparent;
color: var(--text-color);
transition: border-color 0.3s ease, background-color 0.3s ease;
display: flex;
align-items: center;
gap: 0.5rem;
}
.tab.active {
border-color: var(--primary-color);
background-color: var(--primary-color);
color: white;
}
.tab-content {
display: none;
padding: 1rem;
text-align: left;
}
.tab-content.active {
display: block;
}
.metrics-table {
width: 100%;
border-collapse: collapse;
margin-top: 1rem;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.metrics-table th, .metrics-table td {
padding: 0.5rem;
border: 1px solid var(--border-color);
text-align: center;
}
.metrics-table th {
background-color: var(--primary-color);
color: white;
font-weight: bold;
text-transform: uppercase;
letter-spacing: 0.05em;
}
.metrics-table td {
padding: 0.8rem 0.5rem;
}
.metrics-table tr:nth-child(even) {
background-color: #f9f9f9;
}
.dark-mode .metrics-table tr:nth-child(even) {
background-color: #555;
}
.logos-container {
display: flex;
justify-content: center;
align-items: center;
margin-bottom: 1rem;
width: 100%;
}
.logos-container img {
transform: scale(1.083);
max-width: 100%;
height: auto;
}
footer {
width: 100%;
padding: 20px;
background-color: var(--container-bg-color);
border-top: 1px solid var(--border-color);
font-size: 0.9rem;
color: var(--text-color);
text-align: center;
box-sizing: border-box;
position: relative;
left: 0;
right: 0;
margin: 0;
width: 100vw;
margin-left: calc(-100vw / 2 + 50%);
margin-right: calc(-100vw / 2 + 50%);
white-space: normal;
overflow-wrap: break-word;
}
footer p, footer address {
margin: 0.5rem 0;
white-space: normal;
overflow-wrap: break-word;
}
.button-group-wrapper { /* New wrapper for buttons and the time info */
display: flex;
flex-direction: column;
align-items: center;
width: 100%;
margin-top: 1rem; /* Spacing for the wrapper itself */
}
#processing-time-info {
font-size: 0.9em;
color: var(--text-color);
margin-bottom: 0.75rem; /* Space between this info and the buttons */
}
.dark-mode #processing-time-info {
color: var(--text-color); /* Ensure dark mode text color is applied */
}
.button-group {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
}
#download-link {
color: var(--secondary-color);
text-decoration: none;
font-weight: bold;
display: block;
margin: 10px auto;
text-align: center;
}
#download-link:hover{
text-decoration: underline;
}
.tab-content h2 {
color: var(--primary-color);
margin-bottom: 0.5rem;
border-bottom: 2px solid var(--secondary-color);
padding-bottom: 0.25rem;
display: inline-block;
}
.tab-content h3 {
color: var(--secondary-color);
margin-top: 1.5rem;
margin-bottom: 0.5rem;
}
.tab-content ul {
list-style: disc;
margin-left: 20px;
padding-left: 0;
}
.tab-content li {
margin-bottom: 0.25rem;
}
.tab-content p {
margin-bottom: 1rem;
line-height: 1.7;
}
#shap-plot-container {
width: 100%;
min-height: 300px;
border: 1px solid var(--border-color);
border-radius: 5px;
margin-top: 1rem;
display: flex;
justify-content: center;
align-items: center;
overflow-x: auto;
}
#shap-plot-container img{
max-width: 100%;
height: auto;
display: block;
}
.results-display-group {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
margin-top: 2rem;
}
.result-box {
border: 1px solid var(--border-color);
border-radius: 8px;
background-color: var(--container-bg-color);
box-shadow: 0 2px 5px rgba(0,0,0,0.05);
overflow: hidden;
color: var(--text-color);
}
.dark-mode .result-box {
background-color: #424242;
border-color: #616161;
}
.result-header {
background-color: var(--primary-color);
color: white;
padding: 0.7rem 1rem;
font-weight: bold;
font-size: 1.1rem;
display: flex;
align-items: center;
gap: 0.8rem;
}
.result-content {
padding: 1rem;
min-height: 50px;
display: flex;
flex-direction: column;
justify-content: center;
text-align: left;
}
.result-content p.info-message {
text-align: center;
margin-bottom: 0;
margin-top: 0;
}
.result-content ul {
margin: 0.5rem 0 0 1.5rem;
padding: 0;
list-style: disc;
}
.result-content ul li {
margin-bottom: 0.25rem;
}
.result-content h4 {
color: var(--secondary-color);
margin-top: 0.5rem;
margin-bottom: 0.5rem;
}
.scrollable-content {
max-height: 400px;
overflow-y: auto;
padding: 1rem;
border: 1px solid var(--border-color);
border-radius: 8px;
margin-top: 1rem;
background-color: var(--background-color);
}
.dark-mode .scrollable-content {
background-color: #333;
border-color: #616161;
}
.scrollable-content h4 {
color: var(--secondary-color);
margin-top: 1rem;
margin-bottom: 0.5rem;
}
.mic-checkbox-group {
margin-top: 1.5rem;
padding: 1rem;
border: 1px solid var(--border-color);
border-radius: 8px;
background-color: var(--container-bg-color);
box-shadow: 0 1px 5px rgba(0,0,0,0.05);
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: 15px;
margin-bottom: 1.5rem;
}
.dark-mode .mic-checkbox-group {
background-color: #424242;
border-color: #616161;
}
.mic-checkbox-container {
display: flex;
align-items: center;
cursor: pointer;
font-size: 1rem;
color: var(--text-color);
user-select: none;
}
.mic-checkbox-container input[type="checkbox"] {
appearance: none;
-webkit-appearance: none;
width: 20px;
height: 20px;
border: 2px solid var(--primary-color);
border-radius: 4px;
margin-right: 8px;
cursor: pointer;
position: relative;
outline: none;
transition: all 0.2s ease-in-out;
}
.mic-checkbox-container input[type="checkbox"]:checked {
background-color: var(--primary-color);
border-color: var(--primary-color);
}
.mic-checkbox-container input[type="checkbox"]:checked::before {
content: '\2713';
display: block;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 14px;
color: white;
}
.mic-checkbox-container .mic-label {
margin-left: 5px;
font-weight: normal;
}
/* Email-related CSS */
#user-email-input-group {
margin-top: 1.5rem;
margin-bottom: 1rem;
}
#user-email {
width: 100%;
padding: 0.7rem;
border: 1px solid var(--border-color);
border-radius: 5px;
box-sizing: border-box;
font-size: 1rem;
color: var(--text-color);
background-color: var(--container-bg-color);
}
#user-email:focus {
outline: none;
border-color: var(--secondary-color);
}
#email-status {
text-align: left;
font-size: 0.9rem;
margin-top: 0.3rem;
min-height: 1.2em;
}
#email-error { /* CSS for the email error div */
color: var(--clear-button-bg); /* Red for errors */
text-align: left;
font-size: 0.9rem;
margin-top: 0.3rem;
display: none; /* Initially hidden */
}
@media (max-width: 768px) {
body {
padding: 10px;
}
.results-display-group {
grid-template-columns: 1fr;
}
footer {
padding-left: 10px;
padding-right: 10px;
margin-left: calc(-50vw + 50%);
margin-right: calc(-50vw / 2 + 50%);
}
}
.team-member-list {
list-style: none;
padding: 0;
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 15px;
}
.team-member-list li {
display: flex;
align-items: center;
gap: 15px;
font-size: 1.1rem;
color: var(--text-color);
background-color: var(--background-color);
padding: 10px 15px;
border-radius: 8px;
box-shadow: 0 1px 3px rgba(0,0,0,0.08);
width: 100%;
box-sizing: border-box;
}
.dark-mode .team-member-list li {
background-color: #333;
box-shadow: 0 1px 3px rgba(255,255,255,0.08);
}
.team-member-list img {
width: 60px;
height: 60px;
border-radius: 50%;
object-fit: cover;
border: 2px solid var(--secondary-color);
flex-shrink: 0;
}
</style>
</head>
<body>
<div class="container">
<div class="logos-container">
<img src="image2.png" alt="Tool Logo">
</div>
<div class="tabs">
<div class="tab active" data-tab="prediction">
<i class="fas fa-search"></i> Prediction
</div>
<div class="tab" data-tab="model">
<i class="fas fa-chart-line"></i> Models' Metrics & Sample run
</div>
<div class="tab" data-tab="about">
<i class="fas fa-info-circle"></i> About
</div>
<div class="tab" data-tab="usage">
<i class="fas fa-book"></i> Usage Guide
</div>
</div>
<div class="tab-content active" id="prediction">
<h2>AMP & MIC Predictor</h2>
<p>Enter an amino acid sequence (between 10 and 100 valid amino acids) or upload a FASTA file to predict AMP class and MIC values.</p>
<div class="input-group">
<input type="file" id="file-input" accept=".fasta,.fa,.fna">
<textarea id="sequence" placeholder="Enter amino acid sequence (10-100 Valid AAs) or upload a FASTA file..." maxlength="100"></textarea>
<div class="character-count">
<span id="char-count">0</span>/100
</div>
<i class="info-icon" id="info-icon">ⓘ</i>
<div class="tooltip">
Enter the amino acid sequence you want to classify or upload a FASTA file. The sequence must be between 10 and 100 characters long and contain only standard amino acid characters (ACDEFGHIKLMNPQRSTVWY).
</div>
</div>
<h3 style="margin-top: 0rem; margin-bottom: 0.5rem;">Select Bacteria for MIC Prediction</h3>
<p style="margin-top: 0; margin-bottom: 1rem;">Choose one or more bacteria for which you'd like to predict the Minimum Inhibitory Concentration (MIC) of the peptide. MIC prediction is only performed if the sequence is classified as an Antimicrobial Peptide (AMP).</p>
<div class="mic-checkbox-group">
<label class="mic-checkbox-container">
<input type="checkbox" id="mic-ecoli" value="e_coli" disabled>
<span class="mic-label">E.coli</span>
</label>
<label class="mic-checkbox-container">
<input type="checkbox" id="mic-paeruginosa" value="p_aeruginosa" disabled>
<span class="mic-label">P. aeruginosa</span>
</label>
<label class="mic-checkbox-container">
<input type="checkbox" id="mic-saureus" value="s_aureus" disabled>
<span class="mic-label">S. aureus</span>
</label>
<label class="mic-checkbox-container">
<input type="checkbox" id="mic-kpneumoniae" value="k_pneumoniae" disabled>
<span class="mic-label">K. pneumoniae</span>
</label>
</div>
<!-- Start of Email Input Section -->
<div class="input-group" id="user-email-input-group" style="margin-top: 1.5rem; margin-bottom: 1rem;">
<label for="user-email" style="display:block; text-align:left; margin-bottom:0.5rem; font-weight:bold;">Please enter your Email Address for detailed results:<span style="color:red;">*</span></label>
<input type="email" id="user-email" placeholder="Enter your email to receive the PDF report" required>
<div id="email-error" class="error-message" style="text-align:left; font-size:0.9rem; margin-top:0.3rem; display:none;"></div>
<div id="email-status" style="text-align:left; font-size:0.9rem; margin-top:0.3rem; min-height: 1.2em;"></div>
</div>
<!-- End of Email Input Section -->
<!-- Wrapper for estimated time and buttons -->
<div class="button-group-wrapper">
<div id="processing-time-info">Estimated processing time: around 30 seconds.</div>
<div class="button-group">
<button id="clear-btn">Clear Input</button> <!-- NO onclick attribute here -->
<button id="predict-btn">Submit</button> <!-- NO onclick attribute here -->
</div>
</div>
<div class="error-message" id="error"></div>
<div class="results-display-group">
<div class="result-box">
<div class="result-header"><i class="fas fa-file-alt"></i>Classification</div>
<div class="result-content" id="amp-classification-output">
<p class="info-message">The prediction will appear here.</p>
</div>
</div>
<div class="result-box">
<div class="result-header"><i class="fas fa-info-circle"></i> Additional Details</div>
<div class="result-content" id="additional-details-output">
<p class="info-message">The detailed report will appear here.</p>
<a id="download-link" style="display: none;">Download Detailed Report (PDF)</a>
</div>
</div>
</div>
</div>
<div class="tab-content" id="model">
<h2>Classifier Metrics</h2>
<p>The following table presents the performance metrics of our antimicrobial peptide classification model. These metrics were obtained on a held-out test set, separate from the training data.</p>
<table class="metrics-table">
<thead>
<tr>
<th>Metric</th>
<th>Value</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Accuracy</td>
<td>0.963</td>
<td>The overall correctness of the model, representing the proportion of correctly classified sequences (both AMP and Non-AMP).</td>
</tr>
<tr>
<td>Precision</td>
<td>0.964</td>
<td>Out of all sequences predicted as AMPs, the proportion that are truly AMPs. A high precision indicates fewer false positives.</td>
</tr>
<tr>
<td>Recall</td>
<td>0.963</td>
<td>Out of all actual AMP sequences, the proportion that the model correctly identifies. A high recall indicates fewer false negatives.</td>
</tr>
<tr>
<td>F1-Score</td>
<td>0.963</td>
<td>The harmonic mean of precision and recall, providing a balanced measure of the model's performance.</td>
</tr>
<tr>
<td>Validation Accuracy</td>
<td>0.968</td>
<td>The accuracy of the model on a separate validation dataset, used during model development to tune hyperparameters.</td>
</tr>
</tbody>
</table>
<h2 style="margin-top: 2rem;">Regressor Metrics (MIC Prediction Models)</h2>
<p>The Minimum Inhibitory Concentration (MIC) prediction is handled by separate regressor models. Their performance metrics for each bacterium are detailed below:</p>
<table class="metrics-table">
<thead>
<tr>
<th>Bacterium</th>
<th>MSE (log)</th>
<th>MSE</th>
<th>R2</th>
<th>MAE</th>
<th>Pearson</th>
<th>Kendall</th>
</tr>
</thead>
<tbody>
<tr>
<td>E.coli</td>
<td>0.0481</td>
<td>0.4864</td>
<td>0.7023</td>
<td>0.1375</td>
<td>0.8394</td>
<td>0.6725</td>
</tr>
<tr>
<td>P. aeruginosa</td>
<td>0.0517</td>
<td>0.5227</td>
<td>0.6864</td>
<td>0.1233</td>
<td>0.8311</td>
<td>0.6922</td>
</tr>
<tr>
<td>S.aureus</td>
<td>0.0517</td>
<td>0.4988</td>
<td>0.6828</td>
<td>0.1472</td>
<td>0.8278</td>
<td>0.6536</td>
</tr>
<tr>
<td>K. pneumoniae</td>
<td>0.0538</td>
<td>0.4292</td>
<td>0.7416</td>
<td>0.1479</td>
<td>0.8693</td>
<td>0.7194</td>
</tr>
</tbody>
</table>
<h2 style="margin-top: 2rem;">Model Interpretability</h2>
<p>To understand how our model makes predictions, we use SHAP (SHapley Additive exPlanations) values globally and LIME (Local Interpretable Model-agnostic Explanations) locally. SHAP values help assess the overall contribution of each feature to model predictions across the dataset, while LIME explains the features influencing a single, specific prediction.</p>
<h3>Global SHAP Plot</h3>
<p>The SHAP plot below visualizes the features that most significantly influence the model's predictions *on average across all data*. Positive SHAP values generally contribute to the sequence being classified as AMP, while negative values contribute to Non-AMP classification.</p>
<div id="shap-plot-container">
<img src="shap.png" alt="SHAP Plot" >
</div>
<h3>Interpretation of Global SHAP Plot</h3>
<div class="scrollable-content">
<p>Based on the SHAP plot, the model's predictions for Antimicrobial Peptides (AMPs) are influenced by a combination of sequence-based, structural, and biophysical features. Here’s a breakdown of the key features and their biological implications:</p>
<h4>A. Sequence-Based Features</h4>
<h5>APAAC13 & APAAC5 (Amphiphilic Pseudo-Amino Acid Composition)</h5>
<ul>
<li><strong>Description:</strong> These features encode hydrophobicity, charge, and side-chain properties, reflecting the amphiphilic nature of the peptide.</li>
<li><strong>Interpretation:<b> Higher APAAC values have a positive SHAP impact, indicating they are predictive of AMP activity. This suggests that the model values amphiphilic sequences, which are crucial for disrupting bacterial membranes.</b></strong></li>
</ul>
<h5>Amino Acid Composition (M, C)</h5>
<ul>
<li><strong>M (Methionine):</strong>
<ul>
<li><strong>Description:</strong> Methionine is often associated with structural stability in peptides.</li>
<li><strong>Interpretation:</strong> The plot suggests Methionine content has a positive influence, possibly contributing to the stability of AMP candidates.</li>
</ul>
</li>
<li><strong>C (Cysteine):</strong>
<ul>
<li><strong>Description:</strong> Cysteine is known for forming disulfide bonds, which can stabilize AMP structures like defensins.</li>
<li><strong>Interpretation:</strong> High cysteine content appears to have a positive SHAP impact. This could be because disulfide-stabilized AMPs often exhibit enhanced antimicrobial action.</li>
</ul>
</li>
</ul>
<h4>B. Structural and Biophysical Features</h4>
<ul>
<li><strong>HydrophobicityD3001:</strong>
<ul>
<li><strong>Description:<b> Represents the overall hydrophobicity of the peptide sequence.</b></strong></li>
<li><strong>Interpretation:</strong> Hydrophobicity is shown to be a critical feature. More hydrophobic peptides are strongly favored for AMP classification, aligning with the understanding that hydrophobicity is essential for membrane insertion and disruption.</li>
</ul>
</li>
<li><strong>PolarityD1001:</strong>
<ul>
<li><strong>Description:<b> Measures the polarity of the peptide sequence.</b></strong></li>
<li><strong>Interpretation:</b> The model considers polarity, likely in balance with hydrophobicity. An optimal AMP efficacy is often linked to having both hydrophobic and polar residues to facilitate membrane interaction and solubility.</li>
</ul>
</li>
<li><strong>Solvent Accessibility (SolventAccessibilityD3001):</strong>
<ul>
<li><strong>Description:</b> Reflects how exposed the residues are to the solvent (water).</li>
<li><strong>Interpretation:</b> Solvent-accessible residues positively contribute to AMP prediction. This might indicate that exposed residues facilitate interaction with bacterial membranes or the surrounding environment.</li>
</ul>
</li>
<li><strong>Charge (ChargeD2001):</strong>
<ul>
<li><strong>Description:<b> Represents the net charge of the peptide.</b></strong></li>
<li><strong>Interpretation:</b> Charge is a significant positive predictor. Most AMPs are cationic, enabling them to interact with negatively charged bacterial membranes. Higher charge, as indicated by positive SHAP values, typically enhances antimicrobial potency.</li>
</ul>
</li>
<li><strong>PolarizabilityD3001 & NormalizedVDWVD3001:<b>
<ul>
<li><strong>Description:<b> These features relate to electronic distribution (Polarizability) and steric effects (NormalizedVDWVD) of the peptide.</b></strong></li>
<li><strong>Interpretation:</b> These properties impact membrane penetration and peptide-membrane interactions. Their positive SHAP values suggest they are important for AMP activity, possibly by influencing how the peptide inserts into and destabilizes membranes.</li>
</ul>
</li>
</ul>
<h4>C. Geary Autocorrelation Features</h4>
<p>Geary autocorrelation descriptors reflect spatial properties of peptides, encoding information about the adhesion and distribution of physicochemical properties along the sequence.</p>
<ul>
<li><strong>GearyAuto_Hydrophobicity30:</strong>
<ul>
<li><strong>Description:</strong> Encodes the clustering of hydrophobic residues within a spatial lag of 30.</li>
<li><strong>Interpretation:<b> Higher values of hydrophobicity autocorrelation are positively associated with AMP prediction. This likely reflects the importance of hydrophobic clustering in forming amphipathic structures, such as α-helices, which are common and effective in AMPs.</b></b></li>
</ul>
</li>
<li><strong>GearyAuto_Steric30 & GearyAuto_Steric29:</strong>
<ul>
<li><strong>Description:</b> Reflect peptide backbone flexibility and steric properties at spatial lags of 30 and 29.</li>
<li><strong>Interpretation:</b> These features have a positive SHAP impact, suggesting that a certain degree of peptide backbone flexibility may be beneficial for AMP action. Flexibility could enhance the peptide's ability to interact with and adapt to diverse bacterial membrane structures.</li>
</ul>
</li>
<li><strong>GearyAuto_ResidueASA30:<b>
<ul>
<li><strong>Description:</strong> Indicates the autocorrelation of accessible surface area of residues at a spatial lag of 30.</li>
<li><strong>Interpretation:<b> Higher autocorrelation of residue accessible surface area is favored. This could mean that a consistent pattern of residue exposure, possibly with higher exposure of charged or polar residues, improves bacterial targeting or membrane interaction.</b></b></li>
</ul>
</li>
</ul>
</div>
<h3>Sample Run</h3>
<p>You can test the model with various sequences to understand its behavior. Here are a few examples:</p>
<ul>
<li><strong>Test 1:</strong> Long Sequence of 99 AAs (P-AMP) - MEKAALIFIGLLLFSTCTQILAQSCNNDSDCTNLKCATKNIKCEQNKCQCLDERYIRA
ISLNTRSPRCNVQSCIDHCKAIGEVIYVCFTYHCYCRKPPM</li>
<li><strong>Test 2:</strong> Long Sequence of 99 AAs (Non-AMP) - MKSLLPLAILAALAVAALCYESHESMESYEVSPFTTRRNANTFISPQQRWHAK
AQERVRELNKPAQEINREACDDYKLCERYALIYGYNAAYNRYFRQR</li>
<li><strong>Test 3:</strong> Short Sequence of 51 AAs (P-AMP) - SLQGGAPNFPQPSQQNGGWQVSPDLGRDDKGNTRGQIEIQNKGKDHDFNAG</li>
<li><strong>Test 4:<b> Short Sequence of 50 AAs (Non-AMP) - MKPLKQKVSITLDEDVIKNLKTLAEECDRSLSQYINLILKEHLKNLDQQ</b></b></li>
<li><strong>Test 5:</strong> Invalid Characters (eg. X) -
MEKAALIFIGLLLFSTCTQILAQSC(XX).</li>
</ul>
</div>
<div class="tab-content" id="about">
<h2>About This Tool</h2>
<p>This web application provides a user-friendly interface for classifying amino acid sequences as either Antimicrobial Peptides (AMPs) or Non-Antimicrobial Peptides (Non-AMPs). AMPs are crucial components of the innate immune system, offering defense against a wide range of pathogens.</p>
<h3>Model Selection Criteria</h3>
<p>To identify the most effective model, our team rigorously evaluated over 225 combinations of feature extraction and selection methods across four different machine learning models for each target organism. The evaluation included both classification and regression tasks, with a focus on predicting antimicrobial activity and estimating minimum inhibitory concentration (MIC) values. The final model was selected based on the following criteria:</p>
<ul>
<li><strong>High Accuracy, F1-score, and Validation Accuracy:</strong> The model achieved excellent performance metrics on a held-out test set, demonstrating its ability to generalize to unseen data.</li>
<li><strong>Robustness to Sequence Length Variations:<b> The model performs consistently well on sequences of varying lengths, within the specified range (10-100 amino acids).</b></strong></li>
<li><strong>Generalization Ability:</strong> The model was trained and evaluated on diverse datasets to ensure its ability to classify a broad range of AMP sequences.</li>
<li><strong>Robust regression capability:<b> Assessed using Mean Squared Error (MSE), R-squared (R²), Pearson correlation, and Kendall’s tau, the model demonstrated strong agreement between predicted and true MIC values.</b></b></li>
</ul>
<h3>Intended Use</h3>
<p>This tool is intended for research and educational purposes. It can be a valuable resource for researchers studying antimicrobial peptides and developing new therapeutic strategies. However, it is not a replacement for laboratory-based experimental validation.</p>
<h3>Our Team</h3>
<ul class="team-member-list">
<li><img src="team-member-1.jpg" alt="Ali Magdi"> Ali Magdi - Computational Biologist</li>
<li><img src="team-member-2.jpg" alt="Ahmed Amr"> Ahmed Amr - Computational Biologist</li>
<li><img src="team-member-3.jpg" alt="Omar Loay"> Omar Loay - Molecular Biologist</li>
<li><img src="team-member-4.jpg" alt="Prof. Eman Badr"> Prof. Eman Badr - Full Professor and Director of BCBU</li>
</ul>
<h3>Acknowledgements</h3>
<p>We extend our gratitude to the following organizations for their support:</p>
<ul>
<li>Bioinformatics and Computational Biology Unit at Zewail City.</li>
<li>The Centre for Genomics at Zewail City.</li>
</ul>
<h3>Contact</h3>
<p>For questions, inquiries, or feedback, please reach out to us at: <a href="mailto:[email protected]">[email protected]</a></p>
</div>
<div class="tab-content" id="usage">
<h2>Usage Guide</h2>
<p>Follow these steps to use the AMP Classifier and Regressors:</p>
<h3>Step 1: Prepare Your Sequence</h3>
<ul>
<li>You can either enter the amino acid sequence directly or upload a FASTA file.</li>
<li>Ensure your sequence contains only standard amino acid characters (ACDEFGHIKLMNPQRSTVWY).</li>
<li>The sequence length must be between 10 and 100 amino acids.</li>
</ul>
<h3>Step 2: Input the Sequence</h3>
<ul>
<li><strong>Direct Input:</strong> Type or paste your sequence into the text area provided.</li>
<li><strong>FASTA File Upload:<b> Click the "Choose File" button and select your .fasta, .fa, or .fna file.</b></b></li>
<li>The character count will update as you type or upload a sequence.</li>
</ul>
<h3>Step 3: Analyze the Sequence</h3>
<ul>
<li>Click the "Submit" button.</li>
<li>A message indicating the estimated processing time will be visible above the buttons, and the button itself will show elapsed time.</li>
</ul>
<h3>Step 4: View the Results</h3>
<ul>
<li>Once the analysis is complete, the prediction (AMP or Non-AMP) will be displayed in the "AMP Classification" box.</li>
<li>A link to "Download Detailed Report (PDF)" will appear in the "Additional Details" box if the report was generated successfully.</li>
</ul>
<h3>Step 5: Clear the Input</h3>
<ul>
<li>To analyze another sequence, click the "Clear Input" button. This will reset the input fields and results.</li>
</ul>
<h3>Troubleshooting</h3>
<ul>
<li><strong>Invalid Characters:</b> If you see an error message about invalid characters, double-check that your sequence contains only standard amino acid characters.</li>
<li><strong>Sequence Length:</strong> Ensure your sequence is between 10 and 100 characters long.</li>
<li><strong>Invalid FASTA Format:<b> If you encounter an error with a FASTA file, make sure the file is correctly formatted.</b></b></li>
</ul>
</div>
</div>
<footer>
<p>© 2025, Bioinformatics and Computational biology Unit, BCBU</p>
<address>
Bioinformatics and Computational biology Unit at Zewail City,<br>
Ahmed Zewail Street, October Gardens, Giza,<br>
Egypt
</address>
</footer>
<script type="module">
import { Client } from "https://esm.sh/@gradio/client";
const GRADIO_HF_SPACE_RAW_URL = "https://huggingface.co/spaces/nonzeroexit/AMP-Classifier";
const GRADIO_PREDICTION_TARGET_ID = "nonzeroexit/AMP-Classifier";
// This Space ID is technically still used in initClient but won't be connected
// for email sending functionality due to being disabled.
const GRADIO_EMAIL_TARGET_ID = "nonzeroexit/amp-email-sender"; // Email backend reference (disabled)
// --- DOM Elements ---
const sequenceInput = document.getElementById('sequence');
const charCount = document.getElementById('char-count');
const errorDiv = document.getElementById('error');
const predictBtn = document.getElementById('predict-btn');
const clearBtn = document.getElementById('clear-btn');
const fileInput = document.getElementById('file-input');
const downloadLink = document.getElementById('download-link');
const ampClassificationOutput = document.getElementById('amp-classification-output');
const additionalDetailsOutput = document.getElementById('additional-details-output');
const micCheckboxes = document.querySelectorAll('.mic-checkbox-group input[type="checkbox"]');
const tabs = document.querySelectorAll('.tab');
const tabContents = document.querySelectorAll('.tab-content');
const userEmailInput = document.getElementById('user-email');
const emailErrorDiv = document.getElementById('email-error');
const emailStatusDiv = document.getElementById('email-status');
let clientInstancePrediction; // Only prediction client will be connected
let clientInstanceEmail = null; // Email client will NOT be connected (explicitly null)
let debounceTimer;
let countUpIntervalId;
// Flag to control email functionality globally
const IS_EMAIL_SENDING_ENABLED = false; // <<< SET TO false TO DISABLE EMAIL SENDING
// --- Utility Functions for Error Display (Defined at top of module scope) ---
function showError(message) {
if(errorDiv) {
errorDiv.textContent = message;
errorDiv.style.display = 'block';
}
}
function clearGeneralError() {
if(errorDiv) {
errorDiv.style.display = 'none';
errorDiv.textContent = '';
}
}
// --- Tab Switching Logic ---
tabs.forEach(tab => {
tab.addEventListener('click', () => {
tabs.forEach(t => t.classList.remove('active'));
tabContents.forEach(c => c.classList.remove('active'));
tab.classList.add('active');
document.getElementById(tab.dataset.tab).classList.add('active');
});
});
// --- Gradio Client Initialization ---
async function initClient() {
try {
// Attempt to connect to the prediction space
clientInstancePrediction = await Client.connect(GRADIO_PREDICTION_TARGET_ID);
console.log("Gradio client for prediction initialized successfully directly to space ID:", GRADIO_PREDICTION_TARGET_ID);
// ONLY CONNECT EMAIL CLIENT IF FEATURE IS ENABLED
if (IS_EMAIL_SENDING_ENABLED) {
clientInstanceEmail = await Client.connect(GRADIO_EMAIL_TARGET_ID);
console.log("Gradio client for email sender initialized successfully directly to space ID:", GRADIO_EMAIL_TARGET_ID);
} else {
console.log("Email sending functionality is disabled, skipping email client connection.");
}
updatePredictButtonState();
} catch (error) {
console.error("Failed to initialize Gradio client for prediction (or email if enabled):", error);
showError(`Failed to connect to a Hugging Face Space. This might be due to incorrect Space IDs, private spaces, or network issues. Error details: ${error.message}`);
// If prediction client fails, or if email is enabled and its client fails, disable the button.
if (predictBtn) predictBtn.disabled = true;
}
}
// --- Initial Setup on Window Load ---
window.onload = function() {
initClient();
if (document.getElementById('info-icon')) {
document.getElementById('info-icon').addEventListener('mouseenter', showTooltip);
document.getElementById('info-icon').addEventListener('mouseleave', hideTooltip);
}
if (fileInput) fileInput.addEventListener('change', handleFileSelect);
if (sequenceInput) {
sequenceInput.addEventListener('input', updateAllInputsAndButtonState);
sequenceInput.addEventListener('paste', handleSequencePaste);
sequenceInput.addEventListener('keypress', handleSequenceKeyPress);
}
// Email input listeners still active for user input and local visual validation
if (userEmailInput) {
userEmailInput.addEventListener('input', updateAllInputsAndButtonState);
}
// Attach event listeners to buttons
if (clearBtn) clearBtn.addEventListener('click', clearInput);
if (predictBtn) predictBtn.addEventListener('click', classifySequenceDebounced);
clearInput();
};
// --- Tooltip Functions ---
function showTooltip() {
const tooltip = document.querySelector('.tooltip');
if (tooltip) tooltip.style.display = 'block';
}
function hideTooltip() {
const tooltip = document.querySelector('.tooltip');
if (tooltip) tooltip.style.display = 'none';
}
// --- Clear Input Function ---
function clearInput() {
if(sequenceInput) sequenceInput.value = '';
if(fileInput) fileInput.value = '';
if(charCount) charCount.textContent = '0';
clearGeneralError();
// Clear email specific fields
if(userEmailInput) userEmailInput.value = '';
if(emailErrorDiv) emailErrorDiv.style.display = 'none';
if(emailStatusDiv) {
if (IS_EMAIL_SENDING_ENABLED) {
emailStatusDiv.textContent = '';
emailStatusDiv.style.color = 'var(--text-color)';
} else {
emailStatusDiv.textContent = 'Email sending is currently disabled by the tool.';
emailStatusDiv.style.color = 'var(--info-color)'; // Neutral info color
}
}
if(downloadLink) {
downloadLink.style.display = 'none';
downloadLink.href = '#';
downloadLink.innerHTML = 'Download Detailed Report (PDF)';
}
if(ampClassificationOutput) ampClassificationOutput.innerHTML = '<p class="info-message">The prediction will appear here.</p>';
if(additionalDetailsOutput) {
additionalDetailsOutput.innerHTML = '<p class="info-message">The detailed report will appear here.</p>';
if(downloadLink && !additionalDetailsOutput.contains(downloadLink)) {
additionalDetailsOutput.appendChild(downloadLink);
}
if(downloadLink) downloadLink.style.display = 'none';
}
if(micCheckboxes) micCheckboxes.forEach(checkbox => {
checkbox.checked = false;
checkbox.disabled = true;
});
if (countUpIntervalId) {
clearInterval(countUpIntervalId);
countUpIntervalId = null;
}
updatePredictButtonState();
if(predictBtn) predictBtn.textContent = 'Submit';
}
// --- File Handling ---
function handleFileSelect(event) {
const file = event.target.files[0];
if (!file) {
if (sequenceInput && sequenceInput.dataset.source === 'file') {
clearInput();
}
return;
}
const allowedExtensions = ['.fasta', '.fa', '.fna'];
const fileName = file.name.toLowerCase();
const isValidExtension = allowedExtensions.some(ext => fileName.endsWith(ext));
if (!isValidExtension) {
showError('Invalid file type. Please upload a .fasta, .fa, or .fna file.');
if(fileInput) fileInput.value = '';
if(micCheckboxes) micCheckboxes.forEach(checkbox => checkbox.disabled = true);
updatePredictButtonState();
return;
}
clearGeneralError();
// Clear email validation error, though it won't block submission
if(emailErrorDiv) emailErrorDiv.style.display = 'none';
const reader = new FileReader();
reader.onload = function(e) {
try {
const parsedSeq = parseFASTA(e.target.result);
if (parsedSeq) {
if(sequenceInput) {
sequenceInput.value = parsedSeq;
sequenceInput.dataset.source = 'file';
}
updateCharacterCount();
updateAllInputsAndButtonState();
} else {
showError("No valid sequence found in FASTA file.");
if(fileInput) fileInput.value = '';
if(sequenceInput) sequenceInput.dataset.source = '';
if(micCheckboxes) micCheckboxes.forEach(checkbox => checkbox.disabled = true);
updatePredictButtonState();
}
} catch (error) {
console.error("Error in FASTA parsing:", error);
showError(error.message || "Error processing FASTA file.");
if(fileInput) fileInput.value = '';
if(sequenceInput) sequenceInput.dataset.source = '';
if(micCheckboxes) micCheckboxes.forEach(checkbox => checkbox.disabled = true);
updatePredictButtonState();
}
};
reader.onerror = function(error) {
console.error("FileReader error:", error);
showError("Error reading file.");
if(fileInput) fileInput.value = '';
if(sequenceInput) sequenceInput.dataset.source = '';
if(micCheckboxes) micCheckboxes.forEach(checkbox => checkbox.disabled = true);
updatePredictButtonState();
};
reader.readAsText(file);
}
function parseFASTA(text) {
const lines = text.trim().split(/[\r\n]+/);
let sequenceData = '';
let headerFound = false;
for (const line of lines) {
const trimmedLine = line.trim();
if (trimmedLine.startsWith('>')) {
if (headerFound && sequenceData) { return sequenceData.toUpperCase(); }
headerFound = true; sequenceData = '';
} else if (headerFound) {
sequenceData += trimmedLine.replace(/\s/g, '');
} else if (!trimmedLine.startsWith('>') && trimmedLine.length > 0) {
sequenceData += trimmedLine.replace(/\s/g, '');
}
}
if (!headerFound && sequenceData) { console.warn("No FASTA header found."); }
else if (!sequenceData && headerFound) { throw new Error("FASTA header found but no sequence.");}
else if (!sequenceData && !headerFound && lines.some(l=>l.trim().length>0) && !lines.some(l=>l.trim().startsWith('>'))){
sequenceData = lines.join('').replace(/\s/g, '');
} else if (!sequenceData && !headerFound && lines.every(l=>l.trim().length === 0)) {
throw new Error("FASTA file is empty.");
}
if (sequenceData) { return sequenceData.toUpperCase(); }
else { throw new Error("No valid sequence found in FASTA."); }
}
// --- Validation Functions ---
function validateSequence(seqToValidate) {
const currentLength = seqToValidate.length;
if (!seqToValidate) {
return { isValid: false, message: "Sequence cannot be empty." };
} else if (/[^ACDEFGHIKLMNPQRSTVWY]/i.test(seqToValidate)) {
return { isValid: false, message: 'Invalid characters in sequence. Only standard amino acid characters (ACDEFGHIKLMNPQRSTVWY) are allowed.' };
} else if (currentLength < 10 || currentLength > 100) {
return { isValid: false, message: `Sequence length (${currentLength}) must be between 10 and 100 characters.` };
}
return { isValid: true, message: "" };
}
function validateEmail(email) {
// Email validation is now only for local display, not blocking submission
if (!email) {
return { isValid: false, message: "Email address is empty." };
}
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
return { isValid: false, message: "Please enter a valid email format." };
}
return { isValid: true, message: "" };
}
// --- Update UI Functions ---
function updateCharacterCount() {
if(!sequenceInput || !charCount) return;
const currentLength = sequenceInput.value.length;
charCount.textContent = currentLength;
charCount.style.color = currentLength > 100 ? 'var(--warning-color)' : 'var(--text-color)';
}
function updateAllInputsAndButtonState() {
updateCharacterCount();
const sequenceValidation = validateSequence(sequenceInput ? sequenceInput.value : '');
const emailValidation = validateEmail(userEmailInput ? userEmailInput.value : '');
if (!sequenceValidation.isValid) {
showError(sequenceValidation.message);
} else {
clearGeneralError();
}
// Display email format errors locally, but don't clear prediction error message
if (!emailValidation.isValid && userEmailInput && userEmailInput.value.length > 0) {
if (emailErrorDiv) {
emailErrorDiv.textContent = emailValidation.message;
emailErrorDiv.style.display = 'block';
}
} else {
if (emailErrorDiv) emailErrorDiv.style.display = 'none';
}
// If email sending is disabled, provide a default status message.
if (emailStatusDiv) {
if (!IS_EMAIL_SENDING_ENABLED) {
emailStatusDiv.textContent = 'Email sending is currently disabled by the tool.';
emailStatusDiv.style.color = 'var(--info-color)';
} else if (userEmailInput && userEmailInput.value.trim() === '') {
// Clear previous status if user input cleared.
emailStatusDiv.textContent = '';
emailStatusDiv.style.color = 'var(--text-color)';
}
}
if(micCheckboxes) micCheckboxes.forEach(checkbox => {
checkbox.disabled = !sequenceValidation.isValid;
if (!sequenceValidation.isValid) checkbox.checked = false;
});
updatePredictButtonState(sequenceValidation.isValid); // Pass only sequence validity
}
function updatePredictButtonState(sequenceIsValid = false) {
if (predictBtn) {
// Button enabled solely on valid sequence input AND successful prediction client connection
predictBtn.disabled = !sequenceIsValid || !clientInstancePrediction;
}
}
// --- Sequence Input Event Handlers ---
function handleSequencePaste(e) {
e.preventDefault();
const paste = (e.clipboardData || window.clipboardData).getData('text');
const cleanPaste = paste.replace(/[\s\r\n]+/g, '').toUpperCase();
const selectionStart = sequenceInput.selectionStart;
const selectionEnd = sequenceInput.selectionEnd;
const currentText = sequenceInput.value;
let newText = currentText.substring(0, selectionStart) + cleanPaste + currentText.substring(selectionEnd);
if (newText.length > parseInt(sequenceInput.maxLength, 10)) {
newText = newText.substring(0, parseInt(sequenceInput.maxLength, 10));
}
sequenceInput.value = newText;
sequenceInput.dataset.source = 'manual';
updateAllInputsAndButtonState();
sequenceInput.selectionStart = sequenceInput.selectionEnd = selectionStart + cleanPaste.length;
}
function handleSequenceKeyPress(e) {
if (e.key.length > 1 || e.ctrlKey || e.metaKey || e.altKey) {
return;
}
if (!/^[ACDEFGHIKLMNPQRSTVWY]$/i.test(e.key)) {
e.preventDefault();
} else {
clearGeneralError();
}
}
// --- Main Prediction Logic ---
async function classifySequenceDebounced() {
clearTimeout(debounceTimer);
debounceTimer = setTimeout(classifySequence, 300);
}
async function classifySequence() {
if (!clientInstancePrediction) {
showError("Classifier service is not ready. Please wait a moment and try again.");
console.error("Gradio client instance for prediction is not initialized when classifySequence called.");
updatePredictButtonState();
return;
}
const currentSequence = sequenceInput ? sequenceInput.value.trim().toUpperCase() : "";
const userEmail = userEmailInput ? userEmailInput.value.trim() : ""; // Still get email, but won't be used for sending
const sequenceValidation = validateSequence(currentSequence);
// const emailValidation = validateEmail(userEmail); // Email validation is now only for local display/info
if (!sequenceValidation.isValid) {
showError(sequenceValidation.message);
updatePredictButtonState();
return;
} else {
clearGeneralError();
}
// Remove email validation check that blocked submission
// if (!emailValidation.isValid && IS_EMAIL_SENDING_ENABLED) {
// if (emailErrorDiv) {
// emailErrorDiv.textContent = emailValidation.message;
// emailErrorDiv.style.display = 'block';
// }
// updatePredictButtonState();
// return;
// } else {
// if (emailErrorDiv) emailErrorDiv.style.display = 'none';
// }
if(emailStatusDiv) {
if (IS_EMAIL_SENDING_ENABLED) {
emailStatusDiv.textContent = '';
emailStatusDiv.style.color = 'var(--text-color)';
} else {
emailStatusDiv.textContent = 'Email sending is currently disabled by the tool.';
emailStatusDiv.style.color = 'var(--info-color)';
}
}
if (predictBtn) predictBtn.disabled = true;
if (ampClassificationOutput) ampClassificationOutput.innerHTML = '<p class="info-message">Analyzing...</p>';
if (additionalDetailsOutput) {
additionalDetailsOutput.innerHTML = '<p class="info-message">Generating detailed report...</p>';
if(downloadLink && !additionalDetailsOutput.contains(downloadLink)) {
additionalDetailsOutput.appendChild(downloadLink);
}
if(downloadLink) downloadLink.style.display = 'none';
}
if (micCheckboxes) micCheckboxes.forEach(checkbox => checkbox.disabled = true);
let secondsElapsed = 0;
if(predictBtn) predictBtn.textContent = `Processing... (${secondsElapsed}s elapsed)`;
if (countUpIntervalId) clearInterval(countUpIntervalId);
countUpIntervalId = setInterval(() => {
secondsElapsed++;
if(predictBtn) predictBtn.textContent = `Processing... (${secondsElapsed}s elapsed)`;
}, 1000);
let micDataForPdfFromPrediction = {};
let ampLabelFromPrediction = 'Unknown';
let ampConfidenceFromPrediction = 0;
let limeFeaturesForPdfFromPrediction = [];
try {
// Call the prediction space client
const classificationResult = await clientInstancePrediction.predict("/predict", [currentSequence]);
console.log("Gradio Result (Prediction):", classificationResult);
if (!classificationResult || !classificationResult.data || typeof classificationResult.data[0] !== 'string') {
throw new Error("Unexpected result format from prediction server.");
}
const rawTextOutput = classificationResult.data[0];
console.log("Raw text output from Gradio (Prediction):\n", rawTextOutput);
const lines = rawTextOutput.split('\n').map(line => line.trim()).filter(Boolean);
const labelRegex = /Prediction:\s*(.+)/i;
const confidenceRegex = /Confidence:\s*([\d.]+)%/i;
const micSectionHeaderRegex = /Predicted MIC Values \(μM\):/i;
const topFeaturesSectionHeaderRegex = /Top Features Influencing Prediction/i;
const micLineRegex = /-\s*([^:]+?):\s*((?:[\d.]+)|(?:Error:.*)|(?:N\/A)|(?:Could not process)|(?:Skipped))/i;
const featureExtractorRegex = /-\s*(.+?)\s*:\s*([+-]?[\d.]+)/i;
const labelMatch = rawTextOutput.match(labelRegex);
if (labelMatch && labelMatch[1]) ampLabelFromPrediction = labelMatch[1];
else console.warn("Could not parse AMP Label from output.");
const confidenceMatch = rawTextOutput.match(confidenceRegex);
if (confidenceMatch && confidenceMatch[1]) ampConfidenceFromPrediction = parseFloat(confidenceMatch[1]) / 100;
else console.warn("Could not parse Confidence from output.");
let currentSection = null;
micDataForPdfFromPrediction = {};
limeFeaturesForPdfFromPrediction = [];
for (const line of lines) {
if (micSectionHeaderRegex.test(line)) { currentSection = 'mic'; continue; }
if (topFeaturesSectionHeaderRegex.test(line)) { currentSection = 'lime_features'; continue; }
if (currentSection === 'mic') {
const micLineMatch = line.match(micLineRegex);
if (micLineMatch && micLineMatch[1] && micLineMatch[2]) {
const bacteriumDisplayName = micLineMatch[1].trim();
const micValueOrError = micLineMatch[2].trim();
micDataForPdfFromPrediction[bacteriumDisplayName] = !isNaN(parseFloat(micValueOrError)) ? parseFloat(micValueOrError) : micValueOrError;
}
} else if (currentSection === 'lime_features') {
const featureMatch = line.match(featureExtractorRegex);
if (featureMatch) {
const featureDescription = featureMatch[1].trim();
const featureValue = parseFloat(featureMatch[2]);
if (!isNaN(featureValue)) {
limeFeaturesForPdfFromPrediction.push({ feature: featureDescription, condition: '', value: featureValue });
} else { console.warn(`Could not parse LIME feature value from line: ${line}`); }
} else {
if (line.trim().length > 0 && !line.includes('---') && !line.toLowerCase().includes("influencing prediction")) {
console.warn(`Line not parsed as LIME feature: ${line}`);
}
}
}
}
// Attempt to generate PDF
let pdfDoc = null;
try {
pdfDoc = await generatePDFReportContent(currentSequence, ampLabelFromPrediction, ampConfidenceFromPrediction, micDataForPdfFromPrediction, limeFeaturesForPdfFromPrediction);
} catch (pdfGenerationError) {
console.error("Error during PDF report content generation:", pdfGenerationError);
showError(`PDF report generation failed: ${pdfGenerationError.message}`);
emailStatusDiv.textContent = 'PDF generation failed, email not sent (functionality disabled).';
emailStatusDiv.style.color = 'var(--clear-button-bg)';
pdfDoc = null; // Ensure pdfDoc is null on error
}
if(ampClassificationOutput) ampClassificationOutput.innerHTML = `<p style="font-size: 1.3rem; font-weight: bold; color: ${ampLabelFromPrediction.toLowerCase().includes('non-amp') ? 'var(--clear-button-bg)' : 'var(--success-color)'}; margin: 0; text-align: center;">${ampLabelFromPrediction}</p>`;
// Logic to handle download link based on PDF generation success
if (additionalDetailsOutput && downloadLink) {
if (pdfDoc) {
const pdfBlob = pdfDoc.output('blob');
const pdfUrl = URL.createObjectURL(pdfBlob);
const pdfFileName = `EPIC-AMP_Report_${currentSequence.substring(0, 10).replace(/[^a-zA-Z0-9]/g, '')}_${new Date().toISOString().slice(0, 10)}.pdf`;
downloadLink.href = pdfUrl;
downloadLink.download = pdfFileName;
downloadLink.innerHTML = `<i class="fas fa-download"></i> Download Report (PDF)`;
downloadLink.style.display = 'block';
additionalDetailsOutput.innerHTML = '<p class="info-message">Detailed report available:</p>';
if (!additionalDetailsOutput.contains(downloadLink)) {
additionalDetailsOutput.appendChild(downloadLink);
}
// --- Email logic based on IS_EMAIL_SENDING_ENABLED flag ---
if (IS_EMAIL_SENDING_ENABLED) {
await sendEmailWithReport(userEmail, pdfBlob, pdfFileName, currentSequence, ampLabelFromPrediction, ampConfidenceFromPrediction);
} else {
console.log("Email sending is disabled. Not attempting to send.");
if(emailStatusDiv) {
emailStatusDiv.textContent = 'Email report generation and sending are currently disabled by the tool.';
emailStatusDiv.style.color = 'var(--info-color)';
}
}
} else {
additionalDetailsOutput.innerHTML = '<p class="info-message" style="color: var(--warning-color);">Could not generate PDF report for download.</p>';
if (downloadLink.parentNode === additionalDetailsOutput) {
downloadLink.style.display = 'none';
}
emailStatusDiv.textContent = 'PDF report could not be generated, email not sent.';
emailStatusDiv.style.color = 'var(--clear-button-bg)';
}
}
if (ampLabelFromPrediction.toLowerCase().includes('amp') && !ampLabelFromPrediction.toLowerCase().includes('non-amp')) {
if(micCheckboxes) micCheckboxes.forEach(checkbox => checkbox.disabled = false);
} else {
if(micCheckboxes) micCheckboxes.forEach(checkbox => { checkbox.checked = false; checkbox.disabled = true; });
}
} catch (error) {
console.error("Error during prediction or processing:", error);
showError(`Prediction failed: ${error.message || "Unknown error."} Please check the Hugging Face Gradio Space for any issues or temporary downtime.`);
if(ampClassificationOutput) ampClassificationOutput.innerHTML = '<p style="text-align: center; color: var(--clear-button-bg);">Error in Prediction</p>';
if(additionalDetailsOutput) {
additionalDetailsOutput.innerHTML = '<p style="text-align: center; color: var(--clear-button-bg);">Detailed report not available (due to prediction error).</p>';
if(downloadLink) {
if(!additionalDetailsOutput.contains(downloadLink)) additionalDetailsOutput.appendChild(downloadLink);
downloadLink.style.display = 'none';
}
}
if (IS_EMAIL_SENDING_ENABLED) {
emailStatusDiv.textContent = `Email not sent due to prediction error: ${error.message}`;
} else {
emailStatusDiv.textContent = `Email sending is disabled. Prediction failed: ${error.message}`;
}
emailStatusDiv.style.color = 'var(--clear-button-bg)';
} finally {
if (countUpIntervalId) { clearInterval(countUpIntervalId); countUpIntervalId = null; }
if (predictBtn) { predictBtn.textContent = 'Submit';}
updatePredictButtonState(); // Ensure button is re-enabled/disabled based on final prediction input state
}
}
// --- Dummy Send Email Function (when disabled) / Original logic (when enabled) ---
async function sendEmailWithReport(email, pdfBlob, fileName, sequence, prediction, confidence) {
if (!emailStatusDiv) return;
if (!IS_EMAIL_SENDING_ENABLED) {
console.log("Email sending is currently disabled. Not proceeding with backend call.");
emailStatusDiv.textContent = 'Email report was NOT sent: Functionality is disabled.';
emailStatusDiv.style.color = 'var(--info-color)';
return;
}
// --- Original email sending logic (ONLY runs if IS_EMAIL_SENDING_ENABLED is true) ---
emailStatusDiv.textContent = 'Sending email...';
emailStatusDiv.style.color = 'var(--info-color)'; // Blue for processing
const reader = new FileReader();
reader.readAsDataURL(pdfBlob);
reader.onloadend = async function() {
const base64data = reader.result;
const base64PdfContent = base64data.split(',')[1]; // Strip "data:application/pdf;base64," prefix
if (!clientInstanceEmail) {
emailStatusDiv.textContent = 'Email service is not ready. Please try again.';
emailStatusDiv.style.color = 'var(--clear-button-bg)';
console.error("Gradio email client instance is not initialized, even though IS_EMAIL_SENDING_ENABLED is true. Check initClient for errors.");
return;
}
try {
const emailResult = await clientInstanceEmail.predict(
"/send_email_report",
[
email, // recipient_email: str (Python)
base64PdfContent, // pdf_content_base64: str (Python)
fileName, // file_name: str (Python)
sequence, // sequence: str (Python)
prediction, // prediction: str (Python)
confidence // confidence: float (Python)
]
);
console.log("Email sending Gradio result:", emailResult);
if (emailResult && emailResult.data && emailResult.data[0]) {
const statusMessage = emailResult.data[0];
if (statusMessage.includes("successfully")) {
emailStatusDiv.textContent = statusMessage;
emailStatusDiv.style.color = 'var(--success-color)';
} else {
emailStatusDiv.textContent = `Failed to send email: ${statusMessage}`;
emailStatusDiv.style.color = 'var(--clear-button-bg)';
}
} else {
emailStatusDiv.textContent = 'Failed to send email: Unexpected response from service.';
emailStatusDiv.style.color = 'var(--clear-button-bg)';
}
} catch (error) {
emailStatusDiv.textContent = `Error communicating with email service: ${error.message}`;
emailStatusDiv.style.color = 'var(--clear-button-bg)';
console.error('Frontend error calling Gradio email API:', error);
}
};
reader.onerror = function(error) {
emailStatusDiv.textContent = `Error reading PDF file for email: ${error.message}`;
emailStatusDiv.style.color = 'var(--clear-button-bg)';
console.error('FileReader error:', error);
};
}
// --- PDF Generation Utility Functions (Unchanged) ---
async function getBase64Image(imgSrc) {
return new Promise((resolve) => {
if (!imgSrc) { resolve(null); return; }
const img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = () => {
if (img.naturalWidth === 0 || img.naturalHeight === 0) {
console.warn(`getBase64Image: Image at "${imgSrc}" has zero dimensions.`);
resolve(null); return;
}
try {
const canvas = document.createElement("canvas");
canvas.width = img.naturalWidth; canvas.height = img.naturalHeight;
const ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
resolve(canvas.toDataURL("image/png"));
} catch (e) {
console.error(`Error converting image "${imgSrc}" to base64:`, e);
resolve(null);
}
};
img.onerror = () => {
console.error(`Failed to load image for base64: "${imgSrc}"`);
resolve(null);
};
img.src = imgSrc;
});
}
async function generatePDFReportContent(sequenceForPdf, predictionForPdf, confidenceForPdf, micResultsForPdf, limeFeaturesForPdf) {
if (typeof window.jspdf === 'undefined' || typeof window.jspdf.jsPDF === 'undefined' || typeof window.jspdf.jsPDF !== 'function') {
console.error("jsPDF library (window.jspdf.jsPDF) is not loaded or not correctly exposed as a function.");
showError("PDF generation library not loaded. Cannot create report.");
return null;
}
const jsPDF = window.jspdf.jsPDF;
let pdf;
try {
pdf = new jsPDF();
if (!pdf || !pdf.internal || !pdf.internal.pageSize || pdf.internal.pageSize.width === undefined || pdf.internal.pageSize.width === null) {
console.error("Critical error: jsPDF instance or its internal properties are invalid.");
showError("PDF generation failed: Invalid PDF object.");
return null;
}
} catch (e) {
console.error("Failed to instantiate jsPDF object:", e);
showError(`PDF generation failed: Could not initialize PDF library. Error: ${e.message}`);
return null;
}
const primaryC = [0,77,64];
const textC=[51,51,51];
const successC=[39,174,96];
const errorC=[231,76,60];
const headerTextC=[44,62,80];
const pageWidth = pdf.internal.pageSize.width;
let yPos = 15;
let toolLogoB64 = null, shapPlotB64 = null;
const toolLogoEl = document.querySelector('.logos-container img');
if (toolLogoEl && toolLogoEl.src) toolLogoB64 = await getBase64Image(toolLogoEl.src);
const shapImgEl = document.querySelector('#shap-plot-container img');
if (shapImgEl && shapImgEl.src) shapPlotB64 = await getBase64Image('shap.png');
if (toolLogoB64) {
const img = new Image(); img.src = toolLogoB64; await new Promise(r=>img.onload=r);
if(img.naturalWidth > 0){
const logoW = pageWidth*0.8, ratio=img.naturalHeight/img.naturalWidth, logoH=logoW*ratio, logoX=(pageWidth-logoW)/2;
pdf.addImage(toolLogoB64,'PNG',logoX,yPos,logoW,logoH); yPos+=logoH+10;
} else {yPos+=15;}
} else { yPos+=15;}
yPos += 5;
pdf.setFont("helvetica","bold"); pdf.setFontSize(28); pdf.setTextColor(headerTextC[0],headerTextC[1],headerTextC[2]);
pdf.text("Anti-microbial Peptides Report",pageWidth/2,yPos,{align:"center"}); yPos+=28+10;
pdf.setFontSize(16); pdf.setTextColor(primaryC[0],primaryC[1],primaryC[2]); pdf.text("Input Sequence:",20,yPos); yPos+=7;
pdf.setFontSize(10); pdf.setTextColor(textC[0],textC[1],textC[2]);
const seqLines=pdf.splitTextToSize(sequenceForPdf,pageWidth-40); pdf.text(seqLines,20,yPos); yPos+=(seqLines.length*(pdf.getFontSize()/pdf.internal.scaleFactor)*1.15)+18;
if(yPos+35 > pdf.internal.pageSize.height-30){pdf.addPage(); yPos=20;}
pdf.setFontSize(16); pdf.setTextColor(primaryC[0],primaryC[1],primaryC[2]); pdf.text("Analysis Summary:",20,yPos); yPos+=8;
const predHead=[['Metric','Value']], predBody=[['Prediction',predictionForPdf],['Confidence',`${(confidenceForPdf*100).toFixed(2)}%`]];
pdf.autoTable({startY:yPos, head:predHead, body:predBody, theme:'striped',
headStyles:{fillColor:primaryC,textColor:255,fontSize:11,fontStyle:'bold',halign:'left'},
bodyStyles:{textColor:textC,fontSize:10,cellPadding:2,lineWidth:0.1,lineColor:[200,200,200]},
columnStyles:{0:{cellWidth:70,halign:'left'},1:{halign:'left',cellWidth:'auto'}},
didParseCell: (data) => {
if(data.section==='body' && data.column.index === 1 && data.row.raw[0]==='Prediction'){
data.cell.styles.fontStyle='bold';
data.cell.styles.textColor = predictionForPdf.toLowerCase().includes('non-amp') ? errorC : successC;
} else if (data.section === 'body' && data.column.index === 1 && data.row.raw[0]==='Confidence'){
data.cell.styles.textColor = successC;
}
}
});
yPos=pdf.lastAutoTable.finalY+20;
const micDataForTable = [];
if (micResultsForPdf && Object.keys(micResultsForPdf).length > 0) {
Object.entries(micResultsForPdf).forEach(([bacterium, micVal]) => {
let isChecked = false;
if(micCheckboxes) {
micCheckboxes.forEach(cb => {
const cbLabel = cb.parentElement.querySelector('.mic-label').textContent.trim();
const normalizedCbLabel = cbLabel.toLowerCase().replace(/[\s.]/g, '');
const normalizedBacteriumName = bacterium.toLowerCase().replace(/[\s.]/g, '');
if (cb.checked && normalizedBacteriumName === normalizedCbLabel) {
isChecked = true;
}
});
}
if(isChecked) {
micDataForTable.push([bacterium, typeof micVal === 'number' ? micVal.toFixed(3) : String(micVal)]);
}
});
}
if(micDataForTable.length > 0){
if(yPos+35 > pdf.internal.pageSize.height-30){pdf.addPage(); yPos=20;}
pdf.setFontSize(16); pdf.setTextColor(primaryC[0],primaryC[1],primaryC[2]); pdf.text("Predicted MIC (µM):",20,yPos); yPos+=8;
pdf.autoTable({startY:yPos, head:[['Bacterium','MIC (µM)']], body:micDataForTable, theme:'striped',
headStyles:{fillColor:primaryC,textColor:255,fontSize:11,fontStyle:'bold',halign:'center'},
columnStyles:{0:{fontStyle:'italic',cellWidth:90,halign:'left'},1:{halign:'right',cellWidth:'auto'}},
styles:{cellPadding:2,fontSize:10,textColor:textC,lineColor:[200,200,200],lineWidth:0.1},
});
yPos=pdf.lastAutoTable.finalY+20;
} else {
if(yPos+25 > pdf.internal.pageSize.height-30){pdf.addPage(); yPos=20;}
pdf.setFontSize(10); pdf.setTextColor(100,100,100);
pdf.text("No MIC prediction displayed (non-AMP, no bacteria selected, or no valid predictions for selected bacteria).", 20, yPos); yPos+=15;
}
if(!limeFeaturesForPdf || limeFeaturesForPdf.length === 0){ limeFeaturesForPdf = []; }
if(limeFeaturesForPdf.length > 0) {
pdf.addPage(); yPos=20;
pdf.setFontSize(16); pdf.setTextColor(primaryC[0],primaryC[1],primaryC[2]);
pdf.text("Top Features Influencing Prediction (Local XAI by LIME)",20,yPos);
yPos+=8;
const limeHead = [['Feature Description','Importance (LIME Weight)']];
const limeBody = limeFeaturesForPdf.sort((a,b)=>Math.abs(b.value)-Math.abs(a.value))
.map(f=>[f.feature, typeof f.value === 'number' ? f.value.toFixed(4) : 'N/A']);
pdf.autoTable({startY:yPos, head:limeHead, body:limeBody, theme:'grid',
headStyles:{fillColor:primaryC,textColor:255,fontSize:10,fontStyle:'bold'},
styles:{fontSize:9,cellPadding:1.5,lineColor:[220,220,220],lineWidth:0.1},
columnStyles:{0:{cellWidth:100},1:{halign:'right'}},
didDrawCell: (data) => {
if(data.column.index===1 && data.row.section === 'body'){
const val = parseFloat(String(data.cell.raw).trim());
if(!isNaN(val)){
if(val > 0) pdf.setTextColor(successC[0],successC[1],successC[2]);
else if (val < 0) pdf.setTextColor(errorC[0],errorC[1],errorC[2]);
}
}
}
});
yPos=pdf.lastAutoTable.finalY+20;
} else {
if(yPos+20 > pdf.internal.pageSize.height-30){pdf.addPage();yPos=20;}
else { pdf.addPage(); yPos=20; }
pdf.setFontSize(10); pdf.setTextColor(100,100,100);
pdf.text("LIME explanation data not available or not generated for this prediction.", 20, yPos); yPos+=15;
}
if (shapPlotB64) {
const img = new Image(); img.src = shapPlotB64; await new Promise(r=>img.onload=r);
if(img.naturalWidth > 0){
let imgW=img.naturalWidth,imgH=img.naturalHeight,ratio=imgW/imgH,maxH=100,maxW=pageWidth-40;
if(imgW>maxW){imgW=maxW;imgH=imgW/ratio;} if(imgH>maxH){imgH=maxH;imgW=imgH*ratio;}
if(yPos+imgH+30 > pdf.internal.pageSize.height-30){pdf.addPage(); yPos=20;}
pdf.setFontSize(16); pdf.setTextColor(primaryC[0],primaryC[1],primaryC[2]);
pdf.text("Global SHAP Feature Importance:",20,yPos);
yPos+=8;
try{pdf.addImage(shapPlotB64,'PNG',(pageWidth-imgW)/2,yPos,imgW,imgH); yPos+=imgH+10;}
catch(e){console.error("Error adding SHAP PDF:",e); yPos+=10;}
}
} else {
if(yPos+20 > pdf.internal.pageSize.height-30){pdf.addPage();yPos=20;}
pdf.setFontSize(10); pdf.setTextColor(100,100,100);
pdf.text("Global SHAP plot image not available for this report.", 20, yPos); yPos+=15;
}
addPageNumbersAndFooter(pdf, pageWidth); // Pass pageWidth to the footer function
pdf.setPage(pdf.internal.getNumberOfPages());
pdf.setFontSize(10); pdf.setTextColor(primaryC[0],primaryC[1],primaryC[2]);
pdf.text("For inquiries: [email protected]", pageWidth/2, pdf.internal.pageSize.height-18, {align:"center"});
return pdf;
}
function addPageNumbersAndFooter(doc, pageWidth) {
const pageCount = doc.internal.getNumberOfPages();
for (let i = 1; i <= pageCount; i++) {
doc.setPage(i);
doc.setFontSize(9); doc.setTextColor(120,120,120);
doc.text(`Page ${i} of ${pageCount}`, doc.internal.pageSize.width - 20, doc.internal.pageSize.height - 7, { align: "right" });
doc.text("Generated by EPIC-AMP @ Zewail City", pageWidth / 2, doc.internal.pageSize.height - 7, { align: "center" });
}
}
</script>
</body>
</html> |