Spaces:
Sleeping
Sleeping
File size: 139,350 Bytes
84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 deb06d0 860bc17 84db019 5db20e9 84db019 c73c351 5db20e9 c73c351 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 1295dcf 84db019 5db20e9 84db019 5db20e9 1295dcf 5db20e9 84db019 c73c351 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 ec8d664 5db20e9 84db019 ec8d664 5db20e9 84db019 5db20e9 4e6c3d7 5db20e9 84db019 5db20e9 ec8d664 5db20e9 ec8d664 5db20e9 ec8d664 5db20e9 ec8d664 5db20e9 ec8d664 5db20e9 ec8d664 5db20e9 84db019 5db20e9 ec8d664 5db20e9 84db019 5db20e9 84db019 ec8d664 5db20e9 1295dcf 5db20e9 1295dcf 5db20e9 e3184ce 5db20e9 e3184ce 5db20e9 1295dcf deb06d0 5db20e9 deb06d0 1295dcf 5db20e9 1295dcf 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 deb06d0 5db20e9 860bc17 5db20e9 1295dcf 5db20e9 1295dcf 5db20e9 84db019 5db20e9 84db019 5db20e9 1295dcf 5db20e9 1295dcf 5db20e9 c73c351 84db019 860bc17 84db019 c73c351 5db20e9 84db019 5db20e9 deb06d0 5db20e9 c73c351 84db019 5db20e9 84db019 c73c351 84db019 5db20e9 c73c351 1295dcf 5db20e9 1295dcf 5db20e9 deb06d0 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 c73c351 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 c73c351 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 e3184ce 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 e3184ce 5db20e9 84db019 5db20e9 e3184ce 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 e3184ce 5db20e9 1295dcf 5db20e9 e3184ce 1295dcf 5db20e9 1295dcf 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 1295dcf ec8d664 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 4e6c3d7 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 84db019 5db20e9 1295dcf 5db20e9 4e6c3d7 5db20e9 84db019 5db20e9 1295dcf 5db20e9 1295dcf 5db20e9 1295dcf c73c351 5db20e9 84db019 5db20e9 84db019 5db20e9 | 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 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 | from __future__ import annotations
import gzip
import hashlib
import io
import json
import logging
import math
import os
import platform
import re
import shutil
import subprocess
import sys
import tempfile
import time
import zipfile
from collections import Counter, defaultdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple
from urllib.parse import unquote
import numpy as np
import pandas as pd
import streamlit as st
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
# ============================================================
# App configuration
#
# This file is a single-file build. It merges what used to be three files
# (the Streamlit app, codon_bias_extras.py, and genome_figures_extra.py)
# into one module, so the tool has no external local-file dependency and
# deploys the same way from a single script.
# ============================================================
APP_NAME = "Bulamarwa"
APP_SUFFIX = "Genomics Suite"
APP_TITLE = f"{APP_NAME} {APP_SUFFIX}"
APP_TAGLINE = "Genome Annotation, AMR, Virulence and Codon Usage Analysis"
APP_VERSION = "2.1.0"
RUN_SCHEMA_VERSION = "1.1"
APP_SUBTITLE = (
"A reproducible bacterial genome analysis platform for standardized annotation, antimicrobial resistance gene screening, "
"virulence gene screening, secondary metabolite gene cluster detection, genome composition analysis, "
"codon usage bias analysis, and publication quality reporting."
)
st.set_page_config(
page_title=f"{APP_TITLE} | {APP_TAGLINE}",
page_icon="\U0001F9EC",
layout="wide",
)
MAX_UPLOAD_MB = int(os.getenv("MAX_UPLOAD_MB", "500"))
MAX_DECOMPRESSED_MB = int(os.getenv("MAX_DECOMPRESSED_MB", "2000"))
COMMAND_TIMEOUT_SECONDS = int(os.getenv("COMMAND_TIMEOUT_SECONDS", "7200"))
APP_LOG_LEVEL = os.getenv("APP_LOG_LEVEL", "INFO").upper()
SUPPORTED_EXTENSIONS = {".fa", ".fasta", ".fna", ".fas", ".ffn", ".txt", ".gz"}
DEFAULT_VFDB_DB_PREFIX = Path(os.getenv("VFDB_DB_PREFIX", "/opt/vfdb/vfdb_nt"))
DEFAULT_AMR_DB_PREFIX = Path(os.getenv("AMR_DB_PREFIX", "/opt/amr/amr_nt"))
DEFAULT_BAKTA_DB = Path(os.getenv("BAKTA_DB", "/opt/bakta/db"))
logging.basicConfig(
level=getattr(logging, APP_LOG_LEVEL, logging.INFO),
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
LOGGER = logging.getLogger("bulamarwa_genomics_suite")
GENETIC_CODE = {
"TTT":"F","TTC":"F","TTA":"L","TTG":"L","TCT":"S","TCC":"S","TCA":"S","TCG":"S",
"TAT":"Y","TAC":"Y","TAA":"*","TAG":"*","TGT":"C","TGC":"C","TGA":"*","TGG":"W",
"CTT":"L","CTC":"L","CTA":"L","CTG":"L","CCT":"P","CCC":"P","CCA":"P","CCG":"P",
"CAT":"H","CAC":"H","CAA":"Q","CAG":"Q","CGT":"R","CGC":"R","CGA":"R","CGG":"R",
"ATT":"I","ATC":"I","ATA":"I","ATG":"M","ACT":"T","ACC":"T","ACA":"T","ACG":"T",
"AAT":"N","AAC":"N","AAA":"K","AAG":"K","AGT":"S","AGC":"S","AGA":"R","AGG":"R",
"GTT":"V","GTC":"V","GTA":"V","GTG":"V","GCT":"A","GCC":"A","GCA":"A","GCG":"A",
"GAT":"D","GAC":"D","GAA":"E","GAG":"E","GGT":"G","GGC":"G","GGA":"G","GGG":"G",
}
STOP_CODONS = {"TAA", "TAG", "TGA"}
START_CODONS = {"ATG", "GTG", "TTG"}
AA_TO_CODONS = defaultdict(list)
for codon, aa in GENETIC_CODE.items():
if aa != "*":
AA_TO_CODONS[aa].append(codon)
AA_NAMES = {
"A": "Ala", "R": "Arg", "N": "Asn", "D": "Asp", "C": "Cys",
"Q": "Gln", "E": "Glu", "G": "Gly", "H": "His", "I": "Ile",
"L": "Leu", "K": "Lys", "M": "Met", "F": "Phe", "P": "Pro",
"S": "Ser", "T": "Thr", "W": "Trp", "Y": "Tyr", "V": "Val",
}
DNA_COMPLEMENT = str.maketrans("ACGTNacgtn", "TGCANtgcan")
# Shared color palette for all figures in this file, kept consistent across
# both the general genome plots and the codon-bias plots.
PALETTE = {
"primary": "#2c5f8a", "secondary": "#c45a3b", "accent": "#3b8c6e",
"warm": "#d9a23b", "purple": "#7a5ba6", "neutral": "#6b6b6b",
"light": "#d9e2ec",
}
def set_pub_style() -> None:
"""Shared matplotlib style for publication quality figures."""
plt.rcParams.update({
"figure.dpi": 150,
"savefig.dpi": 300,
"font.family": "sans-serif",
"font.sans-serif": ["DejaVu Sans", "Arial", "Helvetica"],
"font.size": 10,
"axes.titlesize": 13,
"axes.titleweight": "bold",
"axes.labelsize": 11,
"axes.edgecolor": "#444444",
"axes.linewidth": 0.9,
"legend.fontsize": 9,
"legend.frameon": False,
"xtick.labelsize": 9,
"ytick.labelsize": 9,
"axes.spines.top": False,
"axes.spines.right": False,
"figure.facecolor": "white",
"axes.facecolor": "white",
})
set_pub_style()
# ============================================================
# Codon usage bias module
#
# This section replaces the former codon_bias_extras.py. It supplies the
# per-gene codon indices (GC1/GC2/GC3/GC12, ENc, PR2 ratios), the ENc plot,
# the neutrality plot, the PR2 bias plot, amino acid composition, and the
# RSCU heatmap. The functions are grouped under the CodonBias class purely
# for a tidy call site (cbe.method(...)); each method is self-contained.
# ============================================================
class CodonBias:
"""Codon usage bias calculations and figures used across the workbench."""
@staticmethod
def read_fasta_pairs(path: Path) -> List[Tuple[str, str]]:
pairs: List[Tuple[str, str]] = []
header: Optional[str] = None
chunks: List[str] = []
with open(path, "r", encoding="utf-8", errors="ignore") as fh:
for raw in fh:
line = raw.rstrip()
if not line:
continue
if line.startswith(">"):
if header is not None:
pairs.append((header, "".join(chunks).upper()))
header = line[1:].split()[0]
chunks = []
else:
chunks.append(line)
if header is not None:
pairs.append((header, "".join(chunks).upper()))
return pairs
@staticmethod
def _enc_from_counts(codon_counts: Mapping[str, int]) -> float:
"""Wright's effective number of codons (ENc) from a codon count dict."""
family_F = defaultdict(list)
for aa, codons in AA_TO_CODONS.items():
if len(codons) <= 1:
continue
total = sum(codon_counts.get(c, 0) for c in codons)
if total <= 1:
continue
p2 = sum((codon_counts.get(c, 0) / total) ** 2 for c in codons)
F = (total * p2 - 1) / (total - 1)
if F > 0:
family_F[len(codons)].append(F)
def mean_f(k):
vals = family_F.get(k, [])
return float(np.mean(vals)) if vals else np.nan
F2, F3, F4, F6 = mean_f(2), mean_f(3), mean_f(4), mean_f(6)
available = [x for x in [F2, F3, F4, F6] if not np.isnan(x) and x > 0]
if not available:
return np.nan
fallback = float(np.mean(available))
F2 = F2 if (not np.isnan(F2) and F2 > 0) else fallback
F3 = F3 if (not np.isnan(F3) and F3 > 0) else fallback
F4 = F4 if (not np.isnan(F4) and F4 > 0) else fallback
F6 = F6 if (not np.isnan(F6) and F6 > 0) else fallback
enc = 2 + 9 / F2 + 1 / F3 + 5 / F4 + 3 / F6
return float(min(max(enc, 20), 61))
@classmethod
def per_gene_codon_indices(
cls,
cds_pairs: Sequence[Tuple[str, str]],
input_file: str,
min_codons: int = 100,
) -> pd.DataFrame:
"""Per-gene GC1/GC2/GC3/GC12, ENc, and PR2 ratios.
Only genes with at least min_codons sense codons are kept, which is
standard practice for stable per-gene ENc estimates.
"""
rows: List[Dict[str, Any]] = []
for gene_id, raw_seq in cds_pairs:
s = re.sub(r"[^ACGT]", "", str(raw_seq).upper())
usable = len(s) - (len(s) % 3)
if usable < min_codons * 3:
continue
counts: Counter = Counter()
g1 = c1 = g2 = c2 = g3 = c3 = a3 = t3 = 0
n_codons = 0
for i in range(0, usable, 3):
codon = s[i:i + 3]
if codon not in GENETIC_CODE:
continue
b1, b2, b3 = codon[0], codon[1], codon[2]
if b1 == "G":
g1 += 1
elif b1 == "C":
c1 += 1
if b2 == "G":
g2 += 1
elif b2 == "C":
c2 += 1
if b3 == "G":
g3 += 1
elif b3 == "C":
c3 += 1
elif b3 == "A":
a3 += 1
elif b3 == "T":
t3 += 1
if codon not in STOP_CODONS:
counts[codon] += 1
n_codons += 1
if n_codons < min_codons:
continue
gc1 = 100.0 * (g1 + c1) / n_codons
gc2 = 100.0 * (g2 + c2) / n_codons
gc3 = 100.0 * (g3 + c3) / n_codons
gc12 = (gc1 + gc2) / 2.0
gc_total = 100.0 * (g1 + c1 + g2 + c2 + g3 + c3) / (3 * n_codons)
enc = cls._enc_from_counts(counts)
pr2_x = (g3 / (g3 + c3)) if (g3 + c3) else np.nan # G3 / (G3 + C3)
pr2_y = (a3 / (a3 + t3)) if (a3 + t3) else np.nan # A3 / (A3 + T3)
rows.append({
"input_file": input_file,
"gene_id": str(gene_id),
"codon_count": n_codons,
"length_nt": n_codons * 3,
"GC_percent": round(gc_total, 4),
"GC1_percent": round(gc1, 4),
"GC2_percent": round(gc2, 4),
"GC3_percent": round(gc3, 4),
"GC12_percent": round(gc12, 4),
"ENc": round(enc, 4) if not np.isnan(enc) else np.nan,
"PR2_G3_over_G3C3": round(pr2_x, 6) if not np.isnan(pr2_x) else np.nan,
"PR2_A3_over_A3T3": round(pr2_y, 6) if not np.isnan(pr2_y) else np.nan,
})
return pd.DataFrame(rows)
@staticmethod
def amino_acid_composition_from_cds(
cds_pairs: Sequence[Tuple[str, str]],
input_file: str,
) -> pd.DataFrame:
counts: Counter = Counter()
total = 0
for _, raw_seq in cds_pairs:
s = re.sub(r"[^ACGT]", "", str(raw_seq).upper())
usable = len(s) - (len(s) % 3)
for i in range(0, usable, 3):
aa = GENETIC_CODE.get(s[i:i + 3], "X")
if aa in AA_NAMES:
counts[aa] += 1
total += 1
rows = []
for aa, name in AA_NAMES.items():
c = counts.get(aa, 0)
rows.append({
"input_file": input_file,
"amino_acid": aa,
"amino_acid_name": name,
"count": int(c),
"percent": round(100.0 * c / total, 5) if total else 0.0,
})
return pd.DataFrame(rows).sort_values("percent", ascending=False).reset_index(drop=True)
@staticmethod
def fig_rscu_heatmap(rscu_df: pd.DataFrame, isolate: str):
sub = rscu_df[rscu_df["input_file"] == isolate].copy()
if sub.empty:
return None
matrix = sub.pivot(index="amino_acid", columns="codon", values="RSCU").fillna(0)
if matrix.empty:
return None
fig, ax = plt.subplots(
figsize=(max(10, matrix.shape[1] * 0.28), max(4.5, matrix.shape[0] * 0.28)),
dpi=300,
)
im = ax.imshow(matrix.values, aspect="auto", cmap="RdBu_r", vmin=0, vmax=2)
ax.set_title(f"RSCU heatmap: {isolate}")
ax.set_xlabel("Codon")
ax.set_ylabel("Amino acid")
ax.set_xticks(np.arange(matrix.shape[1]))
ax.set_xticklabels(matrix.columns, rotation=90, fontsize=7)
ax.set_yticks(np.arange(matrix.shape[0]))
ax.set_yticklabels(matrix.index, fontsize=8)
cbar = fig.colorbar(im, ax=ax, fraction=0.025, pad=0.01)
cbar.set_label("RSCU")
fig.tight_layout()
return fig
@staticmethod
def _enc_expected(gc3_fraction: float) -> float:
"""Wright's expected ENc under no selection for a given GC3 fraction."""
s = gc3_fraction
denom = s ** 2 + (1 - s) ** 2
if denom == 0:
return 61.0
return 2 + s + 29.0 / denom
@classmethod
def fig_enc_plot(cls, per_gene_df: pd.DataFrame, isolate: str):
sub = per_gene_df[per_gene_df["input_file"] == isolate].dropna(subset=["ENc", "GC3_percent"])
if sub.empty:
return None
fig, ax = plt.subplots(figsize=(7.5, 5.5), dpi=300)
x = sub["GC3_percent"].to_numpy(dtype=float) / 100.0
ax.scatter(x, sub["ENc"], s=16, alpha=0.6, color=PALETTE["primary"],
edgecolor="none", label="Genes")
grid = np.linspace(0.0, 1.0, 300)
expected = [cls._enc_expected(v) for v in grid]
ax.plot(grid, expected, linestyle="--", linewidth=1.4, color=PALETTE["secondary"],
label="Expected (no selection)")
ax.set_title(f"ENc plot: {isolate}")
ax.set_xlabel("GC3 (fraction)")
ax.set_ylabel("Effective number of codons")
ax.set_xlim(0, 1)
ax.set_ylim(20, 61.5)
ax.legend()
ax.grid(alpha=0.25, linestyle="--")
fig.tight_layout()
return fig
@staticmethod
def fig_neutrality_plot(per_gene_df: pd.DataFrame, isolate: str):
sub = per_gene_df[per_gene_df["input_file"] == isolate].dropna(
subset=["GC3_percent", "GC12_percent"]
)
if len(sub) < 3:
return None
x = sub["GC3_percent"].to_numpy(dtype=float) / 100.0
y = sub["GC12_percent"].to_numpy(dtype=float) / 100.0
slope, intercept = np.polyfit(x, y, 1)
predicted = slope * x + intercept
ss_res = float(np.sum((y - predicted) ** 2))
ss_tot = float(np.sum((y - y.mean()) ** 2))
r2 = 1 - ss_res / ss_tot if ss_tot else np.nan
fig, ax = plt.subplots(figsize=(7.5, 5.5), dpi=300)
ax.scatter(x, y, s=16, alpha=0.6, color=PALETTE["accent"], edgecolor="none", label="Genes")
order = np.argsort(x)
ax.plot(x[order], predicted[order], linestyle="--", linewidth=1.4, color=PALETTE["secondary"],
label=f"Fit: slope = {slope:.3f}, R\u00b2 = {r2:.3f}")
ax.set_title(f"Neutrality plot: {isolate}")
ax.set_xlabel("GC3 (fraction)")
ax.set_ylabel("GC12 (fraction)")
ax.legend()
ax.grid(alpha=0.25, linestyle="--")
fig.tight_layout()
return fig, {"slope": float(slope), "intercept": float(intercept), "r2": float(r2)}
@staticmethod
def fig_pr2_plot(per_gene_df: pd.DataFrame, isolate: str):
sub = per_gene_df[per_gene_df["input_file"] == isolate].dropna(
subset=["PR2_G3_over_G3C3", "PR2_A3_over_A3T3"]
)
if sub.empty:
return None
fig, ax = plt.subplots(figsize=(6.2, 6.0), dpi=300)
ax.scatter(
sub["PR2_G3_over_G3C3"], sub["PR2_A3_over_A3T3"],
s=16, alpha=0.6, color=PALETTE["purple"], edgecolor="none",
)
ax.axvline(0.5, linestyle="--", linewidth=1, color=PALETTE["neutral"])
ax.axhline(0.5, linestyle="--", linewidth=1, color=PALETTE["neutral"])
ax.set_title(f"PR2 bias plot: {isolate}")
ax.set_xlabel("G3 / (G3 + C3)")
ax.set_ylabel("A3 / (A3 + T3)")
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
fig.tight_layout()
return fig
@staticmethod
def fig_amino_acid_composition(aa_df: pd.DataFrame, isolate: str):
sub = aa_df[aa_df["input_file"] == isolate].sort_values("percent", ascending=False)
if sub.empty:
return None
label_col = "amino_acid_name" if "amino_acid_name" in sub.columns else "amino_acid"
fig, ax = plt.subplots(figsize=(9, 5.5), dpi=300)
ax.bar(sub[label_col], sub["percent"], color=PALETTE["accent"], edgecolor="white", linewidth=0.6)
ax.set_title(f"Amino acid composition: {isolate}")
ax.set_xlabel("Amino acid")
ax.set_ylabel("Percent of residues")
plt.setp(ax.get_xticklabels(), rotation=45, ha="right")
fig.tight_layout()
return fig
cbe = CodonBias()
# ============================================================
# Circular genome map and nucleotide composition donut
#
# This section replaces the former genome_figures_extra.py. It adds a
# CGView-style circular genome overview (GC content and GC skew rings) and a
# refined nucleotide composition donut, both wired into the main figure set.
# ============================================================
def fig_nucleotide_donut(genome_df: pd.DataFrame):
"""Donut chart of A, T, G, C, N proportions across all analysed genomes."""
if genome_df.empty:
return None
totals = genome_df[["A", "T", "G", "C", "N"]].sum()
values = totals.to_numpy(dtype=float)
if values.sum() <= 0:
return None
labels = list(totals.index)
colors = [PALETTE["primary"], "#5a8fc4", PALETTE["secondary"], PALETTE["warm"], PALETTE["neutral"]]
fig, ax = plt.subplots(figsize=(6, 6), dpi=300)
wedges, _ = ax.pie(
values, colors=colors, startangle=90, counterclock=False,
wedgeprops={"width": 0.42, "edgecolor": "white", "linewidth": 2},
)
total = values.sum()
legend_labels = [f"{label} {v / total * 100:.1f}%" for label, v in zip(labels, values)]
ax.legend(wedges, legend_labels, loc="center", frameon=False, fontsize=11)
ax.set_title("Genome nucleotide composition")
return fig
def _smooth(values: np.ndarray, k: int = 3) -> np.ndarray:
if k <= 1 or len(values) < k:
return values
kernel = np.ones(k) / k
return np.convolve(values, kernel, mode="same")
def fig_circular_genome(window_df: pd.DataFrame, isolate: str, genome_gc_mean: Optional[float] = None):
"""Circular genome map for the longest contig of one isolate.
Outer ring: windowed GC content deviation from the genome mean.
Inner ring: windowed GC skew, accent color for positive, purple for negative.
Requires at least six GC windows on the longest contig; otherwise returns
None rather than drawing a misleading sparse map.
"""
sub = window_df[window_df["input_file"] == isolate]
if sub.empty:
return None
longest = sub.groupby("contig_id")["end"].max().sort_values(ascending=False).index[0]
sub = sub[sub["contig_id"] == longest].sort_values("midpoint").copy()
if len(sub) < 6:
return None
n = len(sub)
theta = np.linspace(0, 2 * np.pi, n, endpoint=False)
width = 2 * np.pi / n
gc = sub["GC_percent"].to_numpy(dtype=float)
gc_mean = genome_gc_mean if genome_gc_mean is not None else float(np.mean(gc))
gc_dev = _smooth(gc - gc_mean)
skew = _smooth(sub["GC_skew"].to_numpy(dtype=float))
fig = plt.figure(figsize=(7.6, 7.6), dpi=300)
ax = fig.add_subplot(111, projection="polar")
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
ax.axis("off")
gc_inner, gc_outer = 2.4, 3.4
skew_inner, skew_outer = 1.3, 2.2
max_dev = max(1e-6, float(np.max(np.abs(gc_dev))))
for t, d in zip(theta, gc_dev):
h = (abs(d) / max_dev) * (gc_outer - gc_inner) / 2
base = (gc_inner + gc_outer) / 2
if d >= 0:
ax.bar(t, h, width=width, bottom=base, color=PALETTE["primary"], edgecolor="none", alpha=0.9)
else:
ax.bar(t, h, width=width, bottom=base - h, color=PALETTE["warm"], edgecolor="none", alpha=0.9)
max_skew = max(1e-6, float(np.max(np.abs(skew))))
for t, s in zip(theta, skew):
h = (abs(s) / max_skew) * (skew_outer - skew_inner) / 2
base = (skew_inner + skew_outer) / 2
if s >= 0:
ax.bar(t, h, width=width, bottom=base, color=PALETTE["accent"], edgecolor="none", alpha=0.9)
else:
ax.bar(t, h, width=width, bottom=base - h, color=PALETTE["purple"], edgecolor="none", alpha=0.9)
for r in [(gc_inner + gc_outer) / 2, (skew_inner + skew_outer) / 2]:
ax.plot(np.linspace(0, 2 * np.pi, 200), [r] * 200, color="#bbbbbb", linewidth=0.6, linestyle="--")
ax.set_ylim(0, gc_outer + 0.3)
contig_len = int(sub["end"].max())
for frac in [0, 0.25, 0.5, 0.75]:
ang = frac * 2 * np.pi
ax.plot([ang, ang], [0.9, gc_outer + 0.1], color="#dddddd", linewidth=0.6)
ax.text(ang, gc_outer + 0.25, f"{int(contig_len * frac / 1000)} kb",
ha="center", va="center", fontsize=8, color="#555555")
ax.text(0, 0, f"{isolate}\n{contig_len / 1e6:.2f} Mb\nGC {gc_mean:.1f}%",
ha="center", va="center", fontsize=10, weight="bold")
fig.suptitle(f"Circular genome map: {longest}", fontsize=13, weight="bold", y=0.98)
handles = [
Patch(color=PALETTE["primary"], label="GC above mean"),
Patch(color=PALETTE["warm"], label="GC below mean"),
Patch(color=PALETTE["accent"], label="GC skew +"),
Patch(color=PALETTE["purple"], label="GC skew -"),
]
ax.legend(handles=handles, loc="upper right", bbox_to_anchor=(1.18, 1.12), frameon=False, fontsize=8.5)
return fig
# AMRFinderPlus organism strings. Passing the correct one enables point mutation
# calls as well as acquired gene calls. An unknown genus returns an empty string,
# which makes AMRFinderPlus run without the organism specific module.
AMRFINDER_ORGANISMS = {
"escherichia": "Escherichia",
"shigella": "Escherichia",
"salmonella": "Salmonella",
"klebsiella pneumoniae": "Klebsiella_pneumoniae",
"klebsiella oxytoca": "Klebsiella_oxytoca",
"acinetobacter baumannii": "Acinetobacter_baumannii",
"pseudomonas aeruginosa": "Pseudomonas_aeruginosa",
"staphylococcus aureus": "Staphylococcus_aureus",
"enterococcus faecalis": "Enterococcus_faecalis",
"enterococcus faecium": "Enterococcus_faecium",
"campylobacter": "Campylobacter",
"streptococcus pneumoniae": "Streptococcus_pneumoniae",
"streptococcus pyogenes": "Streptococcus_pyogenes",
"streptococcus agalactiae": "Streptococcus_agalactiae",
"neisseria gonorrhoeae": "Neisseria_gonorrhoeae",
"neisseria meningitidis": "Neisseria_meningitidis",
"vibrio cholerae": "Vibrio_cholerae",
"clostridioides difficile": "Clostridioides_difficile",
"enterobacter cloacae": "Enterobacter_cloacae",
"serratia marcescens": "Serratia_marcescens",
}
_AMRFINDER_ORGANISM_CACHE: Optional[set] = None
def amrfinder_supported_organisms() -> set:
"""Read organism modules from the installed AMRFinderPlus database."""
global _AMRFINDER_ORGANISM_CACHE
if _AMRFINDER_ORGANISM_CACHE is not None:
return _AMRFINDER_ORGANISM_CACHE
if not command_available("amrfinder"):
_AMRFINDER_ORGANISM_CACHE = set()
return _AMRFINDER_ORGANISM_CACHE
code, out, err = run_command(["amrfinder", "--list_organisms"], timeout=120)
text = out or err
organisms = set()
if code == 0:
for raw in text.splitlines():
line = raw.strip()
if not line or line.startswith("#"):
continue
token = line.split()[0]
if re.fullmatch(r"[A-Za-z][A-Za-z0-9_]+", token):
organisms.add(token)
_AMRFINDER_ORGANISM_CACHE = organisms
return organisms
def supported_amrfinder_organism(genus, species):
genus_text = str(genus).strip()
species_text = str(species).strip()
g = genus_text.lower()
s = species_text.lower()
full = f"{g} {s}".strip()
candidate = AMRFINDER_ORGANISMS.get(full) or AMRFINDER_ORGANISMS.get(g, "")
available = amrfinder_supported_organisms()
if candidate and (not available or candidate in available):
return candidate
normalized_candidates = [
f"{genus_text}_{species_text}".strip("_"),
genus_text,
]
available_lower = {value.lower(): value for value in available}
for value in normalized_candidates:
if value.lower() in available_lower:
return available_lower[value.lower()]
return ""
# ============================================================
# Session state
# ============================================================
def init_state():
defaults = {
"run_complete": False,
"zip_bytes": None,
"log_text": "",
"tables": {},
"figures_png": {},
"reports": {},
"manifest": {},
}
for key, val in defaults.items():
if key not in st.session_state:
st.session_state[key] = val
init_state()
def clear_results():
for key in ["run_complete", "zip_bytes", "log_text", "tables", "figures_png", "reports", "manifest"]:
if key in st.session_state:
del st.session_state[key]
init_state()
st.rerun()
# ============================================================
# General helpers
# ============================================================
def command_available(name: str) -> bool:
return shutil.which(name) is not None
def run_command(
cmd: Sequence[str],
cwd: Optional[Path] = None,
timeout: Optional[int] = None,
env: Optional[Mapping[str, str]] = None,
) -> Tuple[int, str, str]:
"""Execute an external command without a shell and with a hard timeout.
Returning a tuple preserves compatibility with the existing workflow while
adding duration, timeout, and executable validation information to stderr.
"""
if not isinstance(cmd, (list, tuple)) or not cmd:
return 1, "", "Command must be a non-empty sequence of arguments."
args = [str(x) for x in cmd]
executable = args[0]
if shutil.which(executable) is None:
return 127, "", f"Executable not found on PATH: {executable}"
started = time.monotonic()
try:
result = subprocess.run(
args,
cwd=str(cwd) if cwd is not None else None,
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
check=False,
timeout=timeout or COMMAND_TIMEOUT_SECONDS,
env=dict(os.environ, **dict(env or {})),
shell=False,
)
duration = time.monotonic() - started
stderr = result.stderr or ""
stderr += f"\n[bulamarwa] elapsed_seconds={duration:.3f}"
return result.returncode, result.stdout or "", stderr
except subprocess.TimeoutExpired as exc:
duration = time.monotonic() - started
stdout = exc.stdout.decode("utf-8", "replace") if isinstance(exc.stdout, bytes) else (exc.stdout or "")
stderr = exc.stderr.decode("utf-8", "replace") if isinstance(exc.stderr, bytes) else (exc.stderr or "")
stderr += (
f"\nCommand timed out after {timeout or COMMAND_TIMEOUT_SECONDS} seconds. "
f"elapsed_seconds={duration:.3f}"
)
return 124, stdout, stderr
except Exception as exc:
LOGGER.exception("External command failed before completion")
return 1, "", f"{type(exc).__name__}: {exc}"
def sha256_path(path: Path, chunk_size: int = 1024 * 1024) -> str:
digest = hashlib.sha256()
with open(path, "rb") as handle:
while True:
block = handle.read(chunk_size)
if not block:
break
digest.update(block)
return digest.hexdigest()
def utc_now_iso() -> str:
return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
def sanitize_text(text: str, fallback="sample"):
text = str(text).strip()
text = re.sub(r"[^A-Za-z0-9._-]+", "_", text)
text = text.strip("._-")
return text or fallback
def validate_extension(filename: str) -> bool:
suffixes = [s.lower() for s in Path(filename).suffixes]
return any(s in SUPPORTED_EXTENSIONS for s in suffixes)
def read_uploaded_to_path(uploaded_file, outdir: Path) -> Path:
outdir.mkdir(parents=True, exist_ok=True)
out = outdir / sanitize_text(uploaded_file.name, "uploaded.fasta")
with open(out, "wb") as f:
f.write(uploaded_file.getbuffer())
return out
def decompress_if_needed(path: Path, outdir: Path) -> Path:
if not path.name.lower().endswith(".gz"):
return path
out = outdir / sanitize_text(path.stem, "decompressed.fasta")
max_bytes = MAX_DECOMPRESSED_MB * 1024 * 1024
written = 0
try:
with gzip.open(path, "rb") as fin, open(out, "wb") as fout:
while True:
block = fin.read(1024 * 1024)
if not block:
break
written += len(block)
if written > max_bytes:
raise ValueError(
f"Decompressed input exceeds the configured limit of "
f"{MAX_DECOMPRESSED_MB} MB."
)
fout.write(block)
except Exception:
out.unlink(missing_ok=True)
raise
return out
def normalize_fasta(input_path: Path, outdir: Path) -> Path:
"""Validate and normalize nucleotide FASTA without silently inventing data."""
output_path = outdir / f"{sanitize_text(input_path.stem)}_normalized.fasta"
records: List[Tuple[str, str]] = []
current_header: Optional[str] = None
seq_parts: List[str] = []
with open(input_path, "r", encoding="utf-8", errors="replace") as fin:
for line_number, raw in enumerate(fin, start=1):
line = raw.strip()
if not line:
continue
if line.startswith(">"):
if current_header is not None:
records.append((current_header, "".join(seq_parts)))
current_header = re.sub(r"\s+", " ", line[1:].strip())
if not current_header:
current_header = f"sequence_{len(records) + 1}"
seq_parts = []
continue
if current_header is None:
raise ValueError(
f"Sequence data were found before the first FASTA header at line {line_number}."
)
cleaned = re.sub(r"\s+", "", line).upper().replace(".", "N").replace("-", "N")
invalid = sorted(set(cleaned) - set("ACGTNRYKMSWBDHV"))
if invalid:
raise ValueError(
f"Unsupported nucleotide symbol(s) {', '.join(invalid)} at line {line_number}. "
"Accepted IUPAC DNA symbols are ACGTNRYKMSWBDHV."
)
seq_parts.append(cleaned)
if current_header is not None:
records.append((current_header, "".join(seq_parts)))
if not records:
raise ValueError("No FASTA records were detected. Every record must begin with '>'.")
seen: Counter = Counter()
with open(output_path, "w", encoding="utf-8", newline="\n") as fout:
for index, (header, sequence) in enumerate(records, start=1):
if not sequence:
raise ValueError(f"FASTA record {index} ({header}) contains no sequence.")
primary_id = header.split()[0]
seen[primary_id] += 1
if seen[primary_id] > 1:
header = f"{primary_id}_duplicate_{seen[primary_id]} " + " ".join(header.split()[1:])
header = header.strip()
fout.write(f">{header}\n")
for start in range(0, len(sequence), 80):
fout.write(sequence[start:start + 80] + "\n")
return output_path
def read_fasta_records(fasta_path: Path) -> List[Dict[str, str]]:
records: List[Dict[str, str]] = []
current_id: Optional[str] = None
current_desc = ""
parts: List[str] = []
with open(fasta_path, "r", encoding="utf-8", errors="replace") as handle:
for raw in handle:
line = raw.strip()
if not line:
continue
if line.startswith(">"):
if current_id is not None:
sequence = "".join(parts).upper()
if not sequence:
raise ValueError(f"FASTA record {current_id} contains no sequence.")
records.append({
"id": current_id,
"description": current_desc,
"sequence": sequence,
})
current_desc = line[1:].strip()
current_id = current_desc.split()[0]
parts = []
else:
parts.append(line.upper())
if current_id is not None:
sequence = "".join(parts).upper()
if not sequence:
raise ValueError(f"FASTA record {current_id} contains no sequence.")
records.append({
"id": current_id,
"description": current_desc,
"sequence": sequence,
})
return records
def fasta_quality_summary(records: Sequence[Mapping[str, str]], input_file: str) -> pd.DataFrame:
total = sum(len(str(record["sequence"])) for record in records)
ambiguous = sum(
sum(base not in {"A", "C", "G", "T"} for base in str(record["sequence"]).upper())
for record in records
)
return pd.DataFrame([{
"input_file": input_file,
"records": len(records),
"total_bases": total,
"ambiguous_bases": ambiguous,
"ambiguous_percent": round((ambiguous / total * 100) if total else 0.0, 6),
"empty_records": 0,
"duplicate_primary_ids_after_normalization": 0,
}])
def reverse_complement(seq: str) -> str:
return seq.translate(DNA_COMPLEMENT)[::-1]
def dataframe_to_csv_bytes(df: pd.DataFrame) -> bytes:
return df.to_csv(index=False).encode("utf-8")
def st_show_image(data, caption: Optional[str] = None) -> None:
"""Display an image full width across Streamlit versions.
st.image only accepted use_container_width from a fairly recent Streamlit
release; older builds (still common in pinned conda environments) raise a
TypeError for it and expect use_column_width instead. Try the current
argument first, then fall back, so the app runs the same way regardless
of which Streamlit build is deployed.
"""
try:
st.image(data, caption=caption, use_container_width=True)
except TypeError:
st.image(data, caption=caption, use_column_width=True)
def human_bp(n):
n = int(n)
if n >= 1_000_000:
return f"{n / 1_000_000:.2f} Mb"
if n >= 1_000:
return f"{n / 1_000:.2f} kb"
return f"{n} bp"
# ============================================================
# Genome statistics
# ============================================================
def nxx(lengths, fraction):
ordered = sorted([int(x) for x in lengths if int(x) > 0], reverse=True)
if not ordered:
return 0, 0
cutoff = sum(ordered) * fraction
cumulative = 0
for i, length in enumerate(ordered, start=1):
cumulative += length
if cumulative >= cutoff:
return length, i
return 0, 0
def genome_composition(records):
seq = "".join(r["sequence"] for r in records).upper()
total = len(seq)
counts = Counter(seq)
a = counts.get("A", 0)
t = counts.get("T", 0)
g = counts.get("G", 0)
c = counts.get("C", 0)
n = counts.get("N", 0)
ambiguous = sum(counts.get(x, 0) for x in "RYKMSWBDHV")
valid = a + t + g + c + n + ambiguous
gc = g + c
at = a + t
cpg = seq.count("CG")
cpg_expected = (c * g / total) if total else 0
lengths = [len(r["sequence"]) for r in records]
n50, l50 = nxx(lengths, 0.50)
n75, l75 = nxx(lengths, 0.75)
n90, l90 = nxx(lengths, 0.90)
return {
"contigs": len(records),
"total_bases": total,
"A": a,
"T": t,
"G": g,
"C": c,
"N": n,
"ambiguous_bases": ambiguous,
"invalid_or_removed_bases": max(0, total - valid),
"GC_percent": round((gc / total * 100) if total else 0, 4),
"AT_percent": round((at / total * 100) if total else 0, 4),
"N_percent": round((n / total * 100) if total else 0, 4),
"GC_skew": round(((g - c) / gc) if gc else 0, 6),
"AT_skew": round(((a - t) / at) if at else 0, 6),
"CpG_observed": cpg,
"CpG_OE": round((cpg / cpg_expected) if cpg_expected else 0, 6),
"largest_contig": max(lengths) if lengths else 0,
"smallest_contig": min(lengths) if lengths else 0,
"mean_contig_length": round(float(np.mean(lengths)), 2) if lengths else 0,
"median_contig_length": round(float(np.median(lengths)), 2) if lengths else 0,
"N50": n50,
"L50": l50,
"N75": n75,
"L75": l75,
"N90": n90,
"L90": l90,
}
def contig_statistics(records, input_file):
rows = []
for rec in records:
seq = rec["sequence"].upper()
length = len(seq)
g = seq.count("G")
c = seq.count("C")
n = seq.count("N")
rows.append({
"input_file": input_file,
"contig_id": rec["id"],
"contig_length": length,
"GC_percent": round(((g + c) / length * 100) if length else 0, 4),
"N_percent": round((n / length * 100) if length else 0, 4),
})
return pd.DataFrame(rows)
def window_statistics(records, input_file, window):
rows = []
for rec in records:
seq = rec["sequence"].upper()
for start in range(0, len(seq), window):
w = seq[start:start + window]
if not w:
continue
g = w.count("G")
c = w.count("C")
a = w.count("A")
t = w.count("T")
gc = g + c
at = a + t
rows.append({
"input_file": input_file,
"contig_id": rec["id"],
"start": start + 1,
"end": start + len(w),
"midpoint": start + len(w) // 2,
"window_size": len(w),
"GC_percent": round((gc / len(w) * 100) if w else 0, 4),
"GC_skew": round(((g - c) / gc) if gc else 0, 6),
"AT_skew": round(((a - t) / at) if at else 0, 6),
})
return pd.DataFrame(rows)
# ============================================================
# Standardized genome annotation
# ============================================================
def bakta_available() -> bool:
return command_available("bakta")
def bakta_version() -> str:
if not bakta_available():
return "Bakta not available."
code, out, err = run_command(["bakta", "--version"], timeout=120)
return (out or err or "Bakta version could not be determined.").strip()
def bakta_database_available() -> bool:
return DEFAULT_BAKTA_DB.exists() and any(DEFAULT_BAKTA_DB.iterdir())
def run_bakta(
fasta_path,
outdir,
prefix,
genus,
species,
threads,
locus_tag,
compliant,
):
"""Run Bakta when both the executable and a database are available."""
if not bakta_available():
return {
"success": False,
"skipped": True,
"engine": "bakta",
"mode": "unavailable",
"log": "Bakta is not available in this environment.",
"outdir": Path(outdir),
}
if not bakta_database_available():
return {
"success": False,
"skipped": True,
"engine": "bakta",
"mode": "database_unavailable",
"log": f"Bakta database was not detected at {DEFAULT_BAKTA_DB}.",
"outdir": Path(outdir),
}
outdir = Path(outdir)
outdir.mkdir(parents=True, exist_ok=True)
cmd = [
"bakta",
"--db", str(DEFAULT_BAKTA_DB),
"--output", str(outdir),
"--prefix", prefix,
"--threads", str(max(1, int(threads))),
"--force",
]
if str(genus).strip():
cmd.extend(["--genus", str(genus).strip()])
if str(species).strip():
cmd.extend(["--species", str(species).strip()])
if str(locus_tag).strip():
cmd.extend(["--locus-tag", sanitize_text(locus_tag).upper()[:24]])
if compliant:
cmd.append("--compliant")
cmd.append(str(fasta_path))
code, out, err = run_command(cmd)
log = "COMMAND:\n" + " ".join(cmd) + "\n\nSTDOUT:\n" + out + "\n\nSTDERR:\n" + err
gff_candidates = list(outdir.glob("*.gff3")) + list(outdir.glob("*.gff"))
ffn_candidates = list(outdir.glob("*.ffn"))
success = code == 0 and bool(gff_candidates) and bool(ffn_candidates)
return {
"success": success,
"skipped": False,
"engine": "bakta",
"mode": "full" if success else "failed",
"log": log,
"outdir": outdir,
}
def choose_annotation_engine(requested: str, kingdom: str) -> str:
requested = str(requested).strip()
if requested == "Bakta":
return "Bakta"
if requested == "Prokka":
return "Prokka"
if str(kingdom).lower() == "bacteria" and bakta_available() and bakta_database_available():
return "Bakta"
return "Prokka"
# ============================================================
# Prokka annotation (robust: full, then --noanno fallback)
# ============================================================
def prokka_version():
if not command_available("prokka"):
return "Prokka not available."
code, out, err = run_command(["prokka", "--version"])
return (out or err or "Prokka version could not be determined.").strip()
def _prokka_files_present(outdir, prefix):
outdir = Path(outdir)
for ext in ["gff", "ffn", "faa"]:
if (outdir / f"{prefix}.{ext}").exists():
continue
if list(outdir.glob(f"*.{ext}")):
continue
return False
return True
def _prokka_command(fasta_path, outdir, prefix, genus, species, kingdom, threads,
locus_tag, compliant, addgenes, noanno):
cmd = [
"prokka",
"--outdir", str(outdir),
"--prefix", prefix,
"--kingdom", kingdom,
"--genus", genus,
"--species", species,
"--cpus", str(threads),
"--force",
]
if locus_tag.strip():
cmd.extend(["--locustag", sanitize_text(locus_tag).upper()[:12]])
if compliant:
cmd.append("--compliant")
if addgenes:
cmd.append("--addgenes")
if noanno:
cmd.append("--noanno")
cmd.append(str(fasta_path))
return cmd
def run_prokka(fasta_path, outdir, prefix, genus, species, kingdom, threads,
locus_tag, compliant, addgenes):
"""Run Prokka. Try full annotation, then retry once with --noanno so gene
prediction still completes if the product search step fails on the host."""
if not command_available("prokka"):
return {"success": False, "skipped": True, "mode": "unavailable",
"log": "Prokka is not available in this environment.", "outdir": outdir}
outdir = Path(outdir)
outdir.mkdir(parents=True, exist_ok=True)
cmd = _prokka_command(fasta_path, outdir, prefix, genus, species, kingdom,
threads, locus_tag, compliant, addgenes, noanno=False)
code, out, err = run_command(cmd)
log_full = "COMMAND:\n" + " ".join(cmd) + "\n\nSTDOUT:\n" + out + "\n\nSTDERR:\n" + err
if code == 0 and _prokka_files_present(outdir, prefix):
return {"success": True, "skipped": False, "mode": "full",
"log": log_full, "outdir": outdir}
# Fallback: clean and retry with --noanno at one cpu
if outdir.exists():
shutil.rmtree(outdir)
outdir.mkdir(parents=True, exist_ok=True)
cmd2 = _prokka_command(fasta_path, outdir, prefix, genus, species, kingdom,
1, locus_tag, compliant, addgenes, noanno=True)
code2, out2, err2 = run_command(cmd2)
log_noanno = "COMMAND:\n" + " ".join(cmd2) + "\n\nSTDOUT:\n" + out2 + "\n\nSTDERR:\n" + err2
combined = (
"FIRST ATTEMPT (full annotation) did not complete. Retried with --noanno.\n"
+ "=" * 70 + "\n" + log_full + "\n" + "=" * 70 + "\nSECOND ATTEMPT (--noanno):\n" + log_noanno
)
if code2 == 0 and _prokka_files_present(outdir, prefix):
return {"success": True, "skipped": False, "mode": "noanno",
"log": combined, "outdir": outdir}
return {"success": False, "skipped": False, "mode": "failed",
"log": combined, "outdir": outdir}
def parse_gff_attributes(attr):
attributes = {}
for item in str(attr).strip().split(";"):
if not item or "=" not in item:
continue
key, value = item.split("=", 1)
attributes[unquote(key.strip())] = unquote(value.strip())
return attributes
def parse_prokka_gff(gff_path, input_file):
if not Path(gff_path).exists():
return pd.DataFrame()
rows = []
with open(gff_path, "r", encoding="utf-8", errors="ignore") as f:
for line in f:
if line.startswith("#"):
if line.startswith("##FASTA"):
break
continue
parts = line.rstrip("\n").split("\t")
if len(parts) != 9:
continue
seqid, source, feature_type, start, end, score, strand, phase, attrs = parts
attr = parse_gff_attributes(attrs)
try:
start_i = int(start)
end_i = int(end)
length = abs(end_i - start_i) + 1
except Exception:
start_i, end_i, length = np.nan, np.nan, np.nan
rows.append({
"input_file": input_file,
"contig_id": seqid,
"source": source,
"feature_type": feature_type,
"start": start_i,
"end": end_i,
"length_bp": length,
"strand": strand,
"gene": attr.get("gene", ""),
"locus_tag": attr.get("locus_tag", attr.get("ID", "")),
"product": attr.get("product", ""),
"inference": attr.get("inference", ""),
})
return pd.DataFrame(rows)
def annotation_summary(feature_df, input_file, genome_length):
if feature_df.empty:
return pd.DataFrame([{
"input_file": input_file,
"total_features": 0,
"CDS": 0,
"genes": 0,
"rRNA": 0,
"tRNA": 0,
"tmRNA": 0,
"repeat_region": 0,
"hypothetical_proteins": 0,
"functional_CDS": 0,
"hypothetical_percent": 0,
"coding_density_percent": 0,
"CDS_per_Mb": 0,
}])
counts = feature_df["feature_type"].value_counts().to_dict()
cds = feature_df[feature_df["feature_type"] == "CDS"].copy()
total_cds_length = cds["length_bp"].dropna().sum() if not cds.empty else 0
product_lower = cds["product"].fillna("").str.lower() if not cds.empty else pd.Series(dtype=str)
hypothetical = int(product_lower.str.contains("hypothetical protein", regex=False).sum()) if not cds.empty else 0
functional = int(len(cds) - hypothetical) if not cds.empty else 0
return pd.DataFrame([{
"input_file": input_file,
"total_features": int(len(feature_df)),
"CDS": int(counts.get("CDS", 0)),
"genes": int(counts.get("gene", 0)),
"rRNA": int(counts.get("rRNA", 0)),
"tRNA": int(counts.get("tRNA", 0)),
"tmRNA": int(counts.get("tmRNA", 0)),
"repeat_region": int(counts.get("repeat_region", 0)),
"hypothetical_proteins": hypothetical,
"functional_CDS": functional,
"hypothetical_percent": round((hypothetical / len(cds) * 100) if len(cds) else 0, 4),
"coding_density_percent": round((total_cds_length / genome_length * 100) if genome_length else 0, 4),
"CDS_per_Mb": round((len(cds) / (genome_length / 1_000_000)) if genome_length else 0, 4),
"mean_CDS_length": round(float(cds["length_bp"].mean()), 2) if len(cds) else 0,
"median_CDS_length": round(float(cds["length_bp"].median()), 2) if len(cds) else 0,
}])
# ============================================================
# Secondary metabolite gene clusters (antiSMASH)
# ============================================================
def antismash_available() -> bool:
return command_available("antismash")
def antismash_version() -> str:
if not antismash_available():
return "antiSMASH not available."
code, out, err = run_command(["antismash", "--version"])
return (out or err or "antiSMASH version could not be determined.").strip()
def run_antismash(fasta_path, outdir, prefix, taxon="bacteria", threads=1):
"""Run antiSMASH on a nucleotide FASTA using prodigal gene finding."""
if not antismash_available():
return {"success": False, "skipped": True, "log": "antiSMASH not available.", "outdir": outdir}
outdir = Path(outdir)
outdir.mkdir(parents=True, exist_ok=True)
cmd = [
"antismash",
"--taxon", taxon,
"--genefinding-tool", "prodigal",
"--cpus", str(max(1, int(threads))),
"--output-dir", str(outdir),
"--output-basename", prefix,
str(fasta_path),
]
code, out, err = run_command(cmd)
log = "COMMAND:\n" + " ".join(cmd) + "\n\nSTDOUT:\n" + out + "\n\nSTDERR:\n" + err
return {"success": code == 0, "skipped": False, "log": log, "outdir": outdir}
def parse_antismash_results(outdir, prefix, input_file):
"""Read antiSMASH JSON regions. Falls back to counting region GenBank files."""
outdir = Path(outdir)
rows = []
json_path = outdir / f"{prefix}.json"
if not json_path.exists():
matches = list(outdir.glob("*.json"))
json_path = matches[0] if matches else None
if json_path and json_path.exists():
try:
with open(json_path, "r", encoding="utf-8", errors="ignore") as fh:
data = json.load(fh)
for rec in data.get("records", []):
rec_id = rec.get("id") or rec.get("name") or "unknown"
for i, area in enumerate(rec.get("areas", []) or [], start=1):
products = area.get("products") or area.get("product") or []
if isinstance(products, str):
products = [products]
rows.append({
"input_file": input_file,
"contig_id": rec_id,
"region": f"region_{i}",
"start": area.get("start", ""),
"end": area.get("end", ""),
"bgc_types": ", ".join(products) if products else "unspecified",
"n_products": len(products),
})
except Exception as exc:
LOGGER.warning("Could not parse antiSMASH JSON %s: %s", json_path, exc)
if not rows:
for gbk in sorted(outdir.glob(f"{prefix}*.region*.gbk")):
rows.append({
"input_file": input_file,
"contig_id": gbk.stem,
"region": gbk.stem.split(".")[-1],
"start": "",
"end": "",
"bgc_types": "see region file",
"n_products": 1,
})
return pd.DataFrame(rows)
# ============================================================
# BLAST database and screening
# ============================================================
def db_exists(prefix: Path) -> bool:
"""Detect BLAST nucleotide databases in legacy and BLASTDB v5 layouts."""
prefix = Path(prefix)
candidates = [
f"{prefix}.nsq", f"{prefix}.nin", f"{prefix}.nhr",
f"{prefix}.ndb", f"{prefix}.not", f"{prefix}.ntf", f"{prefix}.nto",
f"{prefix}.00.nsq", f"{prefix}.00.nin", f"{prefix}.00.nhr",
f"{prefix}.00.ndb", f"{prefix}.00.not", f"{prefix}.00.ntf", f"{prefix}.00.nto",
]
return any(Path(candidate).exists() for candidate in candidates)
def build_temp_blast_db(reference_upload, outdir: Path, db_name: str):
if reference_upload is None:
return None
if not command_available("makeblastdb"):
raise RuntimeError("makeblastdb is not available. Install ncbi-blast+ in the Docker image.")
raw = read_uploaded_to_path(reference_upload, outdir)
dec = decompress_if_needed(raw, outdir)
norm = normalize_fasta(dec, outdir)
prefix = outdir / db_name
code, out, err = run_command(["makeblastdb", "-in", str(norm), "-dbtype", "nucl", "-out", str(prefix), "-parse_seqids"])
if code != 0:
code, out, err = run_command(["makeblastdb", "-in", str(norm), "-dbtype", "nucl", "-out", str(prefix)])
if code != 0:
raise RuntimeError(f"makeblastdb failed for {db_name}.\n{err}\n{out}")
return prefix
def resolve_database(default_prefix: Path, uploaded_reference, workdir: Path, db_name: str):
if uploaded_reference is not None:
return build_temp_blast_db(uploaded_reference, workdir, db_name)
if db_exists(default_prefix):
return default_prefix
return None
def run_blastn(query_fasta, db_prefix, output_tsv, evalue, max_targets, threads, task):
if not command_available("blastn"):
raise RuntimeError("blastn is not available. Install ncbi-blast+ in the Docker image.")
cmd = [
"blastn",
"-task", task,
"-query", str(query_fasta),
"-db", str(db_prefix),
"-evalue", str(evalue),
"-max_target_seqs", str(max_targets),
"-num_threads", str(max(1, int(threads))),
"-dust", "yes",
"-soft_masking", "true",
"-outfmt", "6 qseqid sseqid stitle pident length mismatch gapopen qstart qend sstart send evalue bitscore qlen slen",
"-out", str(output_tsv),
]
code, out, err = run_command(cmd)
log = "COMMAND:\n" + " ".join(cmd) + "\n\nSTDOUT:\n" + out + "\n\nSTDERR:\n" + err
if code != 0:
raise RuntimeError(f"BLASTN failed.\n{log}")
return log
def parse_reference_header(stitle, db_type):
title = re.sub(r"\s+", " ", str(stitle).strip())
organism = "Unknown"
accession = "Unknown"
m = re.search(r"\[([^\]]+)\]\s*$", title)
if m:
organism = m.group(1).strip()
title2 = re.sub(r"\[[^\]]+\]\s*$", "", title).strip()
else:
title2 = title
tokens = title2.split()
if tokens:
accession = tokens[0]
pipe_parts = [p.strip() for p in title2.split("|") if p.strip()]
candidate = pipe_parts[-1].split()[0] if pipe_parts else accession
if db_type == "AMR":
gene_symbol = re.sub(r"[^A-Za-z0-9_()./-]", "", candidate) or accession
product = title2
else:
first = tokens[0] if tokens else "Unknown"
gene_symbol = first if re.fullmatch(r"[A-Za-z0-9_.()/-]{2,50}", first) else "Unknown"
product = title2
return gene_symbol, product, organism, accession
def infer_functional_group(product, db_type):
text = str(product).lower()
if db_type == "AMR":
groups = {
"Beta-lactam resistance": ["beta-lactam", "betalactam", "bla", "carbapenem", "cephalosporin", "penicillin", "oxa", "ctx-m", "tem", "shv", "ndm", "kpc", "vim", "imp"],
"Aminoglycoside resistance": ["aminoglycoside", "aac", "aad", "aph", "ant("],
"Fluoroquinolone resistance": ["quinolone", "fluoroquinolone", "qnr", "gyr", "parc", "pare"],
"Tetracycline resistance": ["tetracycline", "tet("],
"Macrolide resistance": ["macrolide", "erm", "mph", "mef", "msr"],
"Sulfonamide resistance": ["sulfonamide", "sulphonamide", "sul1", "sul2", "sul3"],
"Trimethoprim resistance": ["trimethoprim", "dfr"],
"Colistin resistance": ["colistin", "mcr"],
"Vancomycin resistance": ["vancomycin", "vana", "vanb", "vanc"],
"Efflux-mediated resistance": ["efflux", "acr", "mex", "emr", "mdf", "ade", "oqx"],
"Chloramphenicol resistance": ["chloramphenicol", "cat", "flo"],
"Rifampicin resistance": ["rifampicin", "rifampin", "rpo"],
}
for group, words in groups.items():
if any(w in text for w in words):
return group
return "AMR other or unclassified"
groups = {
"Adhesion": ["adhesin", "fimbr", "pil", "pili", "curli", "intimin", "attachment", "adherence"],
"Toxin": ["toxin", "enterotoxin", "cytotoxin", "hemolysin", "haemolysin", "leukotoxin", "shiga", "exotoxin"],
"Secretion system": ["type iii", "type iv", "type vi", "secret", "injectisome", "effector"],
"Capsule": ["capsule", "capsular", "polysaccharide", "k antigen"],
"Iron acquisition": ["siderophore", "iron", "heme", "haem", "ferric", "ferrous"],
"Motility": ["flagell", "motility", "chemotaxis"],
"Invasion": ["invasion", "internalin", "invasin"],
"Immune evasion": ["serum resistance", "complement", "immune evasion", "antiphagocytic"],
"Biofilm": ["biofilm", "pellicle", "matrix"],
"Enzyme": ["protease", "lipase", "hyaluronidase", "neuraminidase", "collagenase"],
}
for group, words in groups.items():
if any(w in text for w in words):
return group
return "Other or unclassified"
def load_and_filter_blast(
blast_tsv,
input_file,
db_type,
min_identity,
min_reference_coverage,
min_alignment_bp=0,
):
"""Filter nucleotide database hits using reference-gene coverage.
The query is an assembled genome contig. Therefore, alignment length divided
by the full contig length is not a valid gene-detection filter. The relevant
completeness measure is coverage of the reference AMR or virulence sequence.
"""
cols = [
"qseqid", "sseqid", "stitle", "pident", "length", "mismatch", "gapopen",
"qstart", "qend", "sstart", "send", "evalue", "bitscore", "qlen", "slen"
]
if not Path(blast_tsv).exists() or Path(blast_tsv).stat().st_size == 0:
return pd.DataFrame(columns=cols)
df = pd.read_csv(blast_tsv, sep="\t", header=None, names=cols)
numeric_cols = [
"pident", "length", "mismatch", "gapopen", "qstart", "qend",
"sstart", "send", "evalue", "bitscore", "qlen", "slen",
]
for column in numeric_cols:
df[column] = pd.to_numeric(df[column], errors="coerce")
df["contig_coverage_pct"] = (
df["length"] / df["qlen"].replace(0, np.nan) * 100
).round(3)
df["reference_coverage_pct"] = (
df["length"] / df["slen"].replace(0, np.nan) * 100
).round(3)
# Backward-compatible aliases retained for existing output consumers.
df["query_coverage_pct"] = df["contig_coverage_pct"]
df["subject_coverage_pct"] = df["reference_coverage_pct"]
df = df[
(df["pident"] >= float(min_identity))
& (df["reference_coverage_pct"] >= float(min_reference_coverage))
& (df["length"] >= int(min_alignment_bp))
].copy()
if df.empty:
return df
parsed = df["stitle"].apply(lambda value: parse_reference_header(value, db_type))
df["gene_symbol"] = [value[0] for value in parsed]
df["product_name"] = [value[1] for value in parsed]
df["source_organism"] = [value[2] for value in parsed]
df["reference_accession"] = [value[3] for value in parsed]
df["functional_group"] = df["product_name"].apply(
lambda value: infer_functional_group(value, db_type)
)
df["database"] = db_type
df["input_file"] = input_file
df["detection_source"] = f"BLASTN {db_type}"
df = df.sort_values(
["bitscore", "pident", "reference_coverage_pct"],
ascending=[False, False, False],
)
df = df.drop_duplicates(
subset=["input_file", "qseqid", "sseqid", "database"],
keep="first",
)
return df
def apply_species_filter(df, species_text, mode):
if df.empty or not str(species_text).strip():
return df
q = str(species_text).strip().lower()
organisms = df["source_organism"].astype(str).str.lower()
if mode == "Exact species":
return df[organisms.str.strip() == q].copy()
if mode == "Genus-level":
genus = q.split()[0]
return df[organisms.str.contains(genus, regex=False)].copy()
return df[organisms.str.contains(q, regex=False)].copy()
# ============================================================
# NCBI AMRFinderPlus
# ============================================================
def amrfinder_available() -> bool:
return command_available("amrfinder")
def amrfinder_version() -> str:
if not amrfinder_available():
return "AMRFinderPlus not available."
code, out, err = run_command(["amrfinder", "-V"])
text = (out or err or "").strip()
return text if text else "AMRFinderPlus version could not be determined."
def run_amrfinderplus(fasta_path, output_tsv, threads=1, organism=""):
"""Run NCBI AMRFinderPlus on assembled nucleotide sequence.
The --plus option adds selected virulence, stress, biocide, heat, acid, and
metal resistance genes to the core AMR calls. The function retries without the
organism flag, then without the threads flag, so that an unsupported flag does
not stop the run. A missing AMRFinderPlus database is reported as a clear error.
"""
if not amrfinder_available():
raise RuntimeError("AMRFinderPlus is not available. Install ncbi-amrfinderplus in the Docker image.")
def build_cmd(use_threads, use_organism):
cmd = ["amrfinder", "-n", str(fasta_path), "--plus", "-o", str(output_tsv)]
if use_threads:
cmd.extend(["--threads", str(max(1, int(threads)))])
if use_organism and str(organism).strip():
cmd.extend(["--organism", str(organism).strip()])
return cmd
attempts = [
build_cmd(True, True),
build_cmd(True, False), # drop organism if it is rejected
build_cmd(False, False), # drop threads if it is rejected
]
last_log = ""
for cmd in attempts:
code, out, err = run_command(cmd)
last_log = "COMMAND:\n" + " ".join(cmd) + "\n\nSTDOUT:\n" + out + "\n\nSTDERR:\n" + err
low = (err or "").lower()
if ("no amrfinder database" in low) or ("amrfinder -u" in low) or ("please run" in low and "database" in low):
raise RuntimeError(
"AMRFinderPlus database is not installed. Run 'amrfinder -u' during the Docker build "
"so the database is present before deployment.\n" + last_log
)
if code == 0:
return last_log
raise RuntimeError("AMRFinderPlus failed after retries.\n" + last_log)
def _first_existing_col(df, candidates):
lower_map = {c.lower().strip(): c for c in df.columns}
for cand in candidates:
if cand.lower().strip() in lower_map:
return lower_map[cand.lower().strip()]
for c in df.columns:
cl = c.lower().strip()
if any(cand.lower().strip() in cl for cand in candidates):
return c
return None
def parse_amrfinderplus_output(output_tsv, input_file):
"""Convert AMRFinderPlus TSV output into the same long format used for the
virulence and AMR tables in this app."""
output_tsv = Path(output_tsv)
if not output_tsv.exists() or output_tsv.stat().st_size == 0:
return pd.DataFrame()
df = pd.read_csv(output_tsv, sep="\t")
if df.empty:
return pd.DataFrame()
gene_col = _first_existing_col(df, ["Gene symbol", "Gene", "Element symbol"])
seq_col = _first_existing_col(df, ["Sequence name", "Name of closest sequence", "Protein name", "Element name"])
contig_col = _first_existing_col(df, ["Contig id", "Contig", "Sequence identifier"])
start_col = _first_existing_col(df, ["Start"])
stop_col = _first_existing_col(df, ["Stop", "End"])
strand_col = _first_existing_col(df, ["Strand"])
type_col = _first_existing_col(df, ["Element type", "Type"])
subtype_col = _first_existing_col(df, ["Element subtype", "Subtype"])
class_col = _first_existing_col(df, ["Class"])
subclass_col = _first_existing_col(df, ["Subclass"])
method_col = _first_existing_col(df, ["Method"])
coverage_col = _first_existing_col(df, ["% Coverage of reference sequence", "Coverage of reference sequence", "Coverage"])
identity_col = _first_existing_col(df, ["% Identity to reference sequence", "Identity to reference sequence", "Identity"])
accession_col = _first_existing_col(df, ["Accession of closest sequence", "Accession"])
rows = []
for _, row in df.iterrows():
element_type = str(row.get(type_col, "") if type_col else "")
element_subtype = str(row.get(subtype_col, "") if subtype_col else "")
cls = str(row.get(class_col, "") if class_col else "")
subclass = str(row.get(subclass_col, "") if subclass_col else "")
method = str(row.get(method_col, "") if method_col else "")
text = " ".join([element_type, element_subtype, cls, subclass, method]).lower()
if "virulence" in text or element_type.lower().strip() == "virulence":
database = "Virulence"
elif any(x in text for x in ["stress", "biocide", "metal", "heat", "acid"]):
database = "Stress_Biocide"
else:
database = "AMR"
gene = str(row.get(gene_col, "Unknown") if gene_col else "Unknown")
product = str(row.get(seq_col, "") if seq_col else "")
functional_group = subclass or cls or element_subtype or element_type or infer_functional_group(product + " " + gene, "AMR" if database == "AMR" else "VFDB")
try:
identity = float(row.get(identity_col, 0)) if identity_col else 0.0
except Exception:
identity = 0.0
try:
coverage = float(row.get(coverage_col, 0)) if coverage_col else 0.0
except Exception:
coverage = 0.0
try:
start = int(row.get(start_col, 0)) if start_col else 0
except Exception:
start = 0
try:
stop = int(row.get(stop_col, 0)) if stop_col else 0
except Exception:
stop = 0
rows.append({
"qseqid": str(row.get(contig_col, "Unknown") if contig_col else "Unknown"),
"sseqid": gene,
"stitle": product,
"pident": identity,
"length": abs(stop - start) + 1 if start and stop else 0,
"mismatch": np.nan,
"gapopen": np.nan,
"qstart": start,
"qend": stop,
"sstart": np.nan,
"send": np.nan,
"evalue": np.nan,
"bitscore": np.nan,
"qlen": np.nan,
"slen": np.nan,
"contig_coverage_pct": np.nan,
"reference_coverage_pct": coverage,
"query_coverage_pct": np.nan,
"subject_coverage_pct": coverage,
"gene_symbol": gene,
"product_name": product,
"source_organism": "NCBI AMRFinderPlus reference",
"reference_accession": str(row.get(accession_col, "") if accession_col else ""),
"functional_group": functional_group,
"database": database,
"input_file": input_file,
"detection_source": "NCBI AMRFinderPlus --plus",
"element_type": element_type,
"element_subtype": element_subtype,
"class": cls,
"subclass": subclass,
"method": method,
})
return pd.DataFrame(rows)
# ============================================================
# Codon usage and ORF analysis
# ============================================================
def find_orfs(records, input_file, min_aa=90, max_orfs_per_contig=10000):
"""Linear-time six-frame fallback ORF prediction.
Annotator-derived CDS should be preferred. This fallback is intentionally
conservative and reports only the first complete ORF between a start and
in-frame stop codon.
"""
rows = []
for rec in records:
forward = rec["sequence"].upper()
seq_len = len(forward)
def scan(sequence, strand):
found = 0
for frame in range(3):
current_start = None
for position in range(frame, len(sequence) - 2, 3):
codon = sequence[position:position + 3]
if current_start is None:
if codon in START_CODONS:
current_start = position
continue
if codon in STOP_CODONS:
nt_len = position + 3 - current_start
aa_len = nt_len // 3
if aa_len >= int(min_aa):
if strand == 1:
start = current_start + 1
end = position + 3
orf_seq = sequence[current_start:position + 3]
else:
start = seq_len - (position + 3) + 1
end = seq_len - current_start
orf_seq = reverse_complement(
sequence[current_start:position + 3]
)
rows.append({
"input_file": input_file,
"contig_id": rec["id"],
"orf_id": f"{rec['id']}_ORF_{strand}_{start}_{end}",
"start": start,
"end": end,
"strand": strand,
"length_nt": nt_len,
"length_aa": aa_len,
"sequence": orf_seq,
"prediction_source": "internal_complete_orf_fallback",
})
found += 1
if found >= int(max_orfs_per_contig):
break
current_start = None
scan(forward, 1)
scan(reverse_complement(forward), -1)
return pd.DataFrame(rows)
def codon_counts_from_sequences(sequences):
counts = Counter()
for seq in sequences:
s = re.sub(r"[^ACGT]", "", str(seq).upper())
usable = len(s) - (len(s) % 3)
for i in range(0, usable, 3):
codon = s[i:i + 3]
if codon in GENETIC_CODE and codon not in STOP_CODONS:
counts[codon] += 1
return counts
def compute_rscu(codon_counts, input_file):
rows = []
total = max(1, sum(codon_counts.values()))
for aa, codons in sorted(AA_TO_CODONS.items()):
aa_total = sum(codon_counts.get(c, 0) for c in codons)
expected = aa_total / len(codons) if codons else 0
for codon in sorted(codons):
obs = codon_counts.get(codon, 0)
rows.append({
"input_file": input_file,
"amino_acid": aa,
"codon": codon,
"count": int(obs),
"frequency_per_1000": round(obs / total * 1000, 5),
"RSCU": round((obs / expected) if expected else 0, 5),
"GC3": 1 if codon[2] in {"G", "C"} else 0,
})
return pd.DataFrame(rows)
def compute_enc(codon_counts):
family_F = defaultdict(list)
for aa, codons in AA_TO_CODONS.items():
if len(codons) <= 1:
continue
total = sum(codon_counts.get(c, 0) for c in codons)
if total <= 1:
continue
p2 = sum((codon_counts.get(c, 0) / total) ** 2 for c in codons)
F = (total * p2 - 1) / (total - 1)
family_F[len(codons)].append(F)
def mean_f(k):
vals = family_F.get(k, [])
return float(np.mean(vals)) if vals else np.nan
F2, F3, F4, F6 = mean_f(2), mean_f(3), mean_f(4), mean_f(6)
available = [x for x in [F2, F3, F4, F6] if not np.isnan(x) and x > 0]
if not available:
return 0
fallback = float(np.mean(available))
F2 = F2 if not np.isnan(F2) and F2 > 0 else fallback
F3 = F3 if not np.isnan(F3) and F3 > 0 else fallback
F4 = F4 if not np.isnan(F4) and F4 > 0 else fallback
F6 = F6 if not np.isnan(F6) and F6 > 0 else fallback
enc = 2 + 9 / F2 + 1 / F3 + 5 / F4 + 3 / F6
return round(float(min(max(enc, 20), 61)), 4)
def load_cai_weights(uploaded):
if uploaded is None:
return {}
text = uploaded.getvalue().decode("utf-8", errors="replace")
df = pd.read_csv(io.StringIO(text))
df.columns = [c.strip().lower() for c in df.columns]
codon_col = "codon" if "codon" in df.columns else df.columns[0]
weight_col = "weight" if "weight" in df.columns else "cai_weight" if "cai_weight" in df.columns else df.columns[1]
weights = {}
for _, row in df.iterrows():
codon = str(row[codon_col]).upper().replace("U", "T").strip()
try:
val = float(row[weight_col])
except Exception:
continue
if codon in GENETIC_CODE:
weights[codon] = max(0.0, min(1.0, val))
return weights
def compute_cai(codon_counts, weights):
weighted_log_sum = 0.0
included_codons = 0
for codon, count in codon_counts.items():
weight = float(weights.get(codon, 0))
if weight > 0 and int(count) > 0:
weighted_log_sum += int(count) * math.log(weight)
included_codons += int(count)
if included_codons == 0:
return 0.0
return round(float(math.exp(weighted_log_sum / included_codons)), 6)
def codon_analysis(records, input_file, min_orf_aa, cai_weights, cds_pairs=None):
"""Codon analysis. Uses annotator CDS (cds_pairs) when available, otherwise
the naive ORF finder. Returns orf table, RSCU table, codon stats, per-gene
indices, and amino acid composition."""
if cds_pairs:
seqs = [s for _, s in cds_pairs]
orf_df = pd.DataFrame([
{"input_file": input_file, "gene_id": gid, "length_nt": len(s),
"length_aa": len(s) // 3, "source": "annotator_cds"}
for gid, s in cds_pairs
])
else:
orf_table = find_orfs(records, input_file, min_aa=min_orf_aa)
if not orf_table.empty:
seqs = orf_table["sequence"].tolist()
cds_pairs = list(zip(orf_table["orf_id"].tolist(), seqs))
orf_df = orf_table.drop(columns=["sequence"], errors="ignore")
else:
seqs = [r["sequence"] for r in records]
cds_pairs = [(r["id"], r["sequence"]) for r in records]
orf_df = pd.DataFrame()
counts = codon_counts_from_sequences(seqs)
rscu = compute_rscu(counts, input_file)
total_codons = int(sum(counts.values()))
gc3 = sum(v for codon, v in counts.items() if codon[2] in {"G", "C"})
stats = pd.DataFrame([{
"input_file": input_file,
"predicted_ORFs_used": int(len(cds_pairs)),
"total_sense_codons": total_codons,
"GC3_percent": round((gc3 / total_codons * 100) if total_codons else 0, 4),
"effective_number_of_codons_ENc": compute_enc(counts),
"CAI": compute_cai(counts, cai_weights) if cai_weights else 0,
}])
per_gene = cbe.per_gene_codon_indices(cds_pairs, input_file, min_codons=100)
aa_comp = cbe.amino_acid_composition_from_cds(cds_pairs, input_file)
return orf_df, rscu, stats, per_gene, aa_comp
def find_annotation_file(outdir, prefix, suffixes):
outdir = Path(outdir)
for suffix in suffixes:
candidate = outdir / f"{prefix}{suffix}"
if candidate.exists():
return candidate
for suffix in suffixes:
matches = sorted(outdir.glob(f"*{suffix}"))
if matches:
return matches[0]
return None
def read_annotation_cds(annotation_outdir, prefix):
"""Return coding nucleotide sequences from Bakta or Prokka output."""
ffn = find_annotation_file(annotation_outdir, prefix, [".ffn"])
if ffn is None:
return None
try:
return cbe.read_fasta_pairs(ffn)
except Exception as exc:
LOGGER.warning("Could not parse annotation CDS file %s: %s", ffn, exc)
return None
# Backward-compatible function name for downstream users.
read_prokka_cds = read_annotation_cds
# ============================================================
# Summary tables
# ============================================================
def build_detection_summary(hit_df, db_type):
columns = [
"database", "functional_group", "number_of_hits", "unique_genes",
"mean_identity_pct", "mean_reference_coverage_pct",
]
if hit_df.empty:
return pd.DataFrame(columns=columns)
if db_type == "VFDB":
sub = hit_df[hit_df["database"].isin(["VFDB", "Virulence"])].copy()
else:
sub = hit_df[hit_df["database"] == db_type].copy()
if sub.empty:
return pd.DataFrame(columns=columns)
coverage_col = (
"reference_coverage_pct"
if "reference_coverage_pct" in sub.columns
else "subject_coverage_pct"
)
out = sub.groupby("functional_group", dropna=False).agg(
number_of_hits=("functional_group", "size"),
unique_genes=("gene_symbol", pd.Series.nunique),
mean_identity_pct=("pident", "mean"),
mean_reference_coverage_pct=(coverage_col, "mean"),
).reset_index()
out.insert(0, "database", db_type)
for column in ["mean_identity_pct", "mean_reference_coverage_pct"]:
out[column] = out[column].round(3)
return out.sort_values(
["number_of_hits", "unique_genes"],
ascending=[False, False],
)
def format_hit_table(hit_df):
columns = [
"input_file", "database", "detection_source", "contig_id", "gene_symbol",
"product_name", "functional_group", "identity_pct",
"reference_coverage_pct", "contig_coverage_pct", "alignment_length_bp",
"bitscore", "evalue", "reference_organism", "reference_accession",
"query_start", "query_end", "reference_start", "reference_end",
]
if hit_df.empty:
return pd.DataFrame(columns=columns)
out = hit_df.rename(columns={
"qseqid": "contig_id",
"pident": "identity_pct",
"length": "alignment_length_bp",
"source_organism": "reference_organism",
"qstart": "query_start",
"qend": "query_end",
"sstart": "reference_start",
"send": "reference_end",
}).copy()
if "reference_coverage_pct" not in out:
out["reference_coverage_pct"] = out.get("subject_coverage_pct", np.nan)
if "contig_coverage_pct" not in out:
out["contig_coverage_pct"] = out.get("query_coverage_pct", np.nan)
if "detection_source" not in out:
out["detection_source"] = out["database"].astype(str)
for column in columns:
if column not in out:
out[column] = np.nan
return out[columns].sort_values(
["input_file", "database", "bitscore", "identity_pct"],
ascending=[True, True, False, False],
na_position="last",
)
def build_isolate_summary(genome_df, annotation_df, hit_df, codon_df):
base = genome_df.copy()
if not annotation_df.empty:
base = base.merge(annotation_df, on="input_file", how="left")
for db_type in ["VFDB", "AMR"]:
if hit_df.empty:
base[f"{db_type}_hits"] = 0
base[f"{db_type}_unique_genes"] = 0
base[f"{db_type}_functional_groups"] = 0
base[f"{db_type}_mean_identity_pct"] = 0.0
else:
if db_type == "VFDB":
sub = hit_df[hit_df["database"].isin(["VFDB", "Virulence"])]
else:
sub = hit_df[hit_df["database"] == db_type]
grouped = sub.groupby("input_file").agg(
hits=("gene_symbol", "size"),
unique_genes=("gene_symbol", pd.Series.nunique),
functional_groups=("functional_group", pd.Series.nunique),
mean_identity_pct=("pident", "mean"),
).reset_index()
grouped = grouped.rename(columns={
"hits": f"{db_type}_hits",
"unique_genes": f"{db_type}_unique_genes",
"functional_groups": f"{db_type}_functional_groups",
"mean_identity_pct": f"{db_type}_mean_identity_pct",
})
base = base.merge(grouped, on="input_file", how="left")
if not codon_df.empty:
base = base.merge(codon_df, on="input_file", how="left")
for col in base.columns:
if col.endswith("_hits") or col.endswith("_unique_genes") or col.endswith("_functional_groups"):
base[col] = base[col].fillna(0).astype(int)
for col in base.columns:
if col.endswith("_mean_identity_pct"):
base[col] = base[col].fillna(0).round(3)
return base.fillna(0)
def generate_report_paragraph(row):
return (
f"The analysed genome file {row.get('input_file')} contained {int(row.get('contigs', 0))} contig(s) "
f"with a total size of {int(row.get('total_bases', 0)):,} bp, GC content of {float(row.get('GC_percent', 0)):.2f}%, "
f"N50 of {int(row.get('N50', 0)):,} bp and L50 of {int(row.get('L50', 0))}. "
f"Standardized annotation identified {int(row.get('CDS', 0))} CDS, {int(row.get('rRNA', 0))} rRNA, "
f"{int(row.get('tRNA', 0))} tRNA, and {int(row.get('hypothetical_proteins', 0))} hypothetical proteins. "
f"Virulence screening detected {int(row.get('VFDB_hits', 0))} virulence associated hit(s), "
f"while antimicrobial resistance screening detected {int(row.get('AMR_hits', 0))} AMR associated hit(s) after applying the selected identity and coverage thresholds. "
f"Codon usage analysis detected {int(row.get('predicted_ORFs_used', 0))} predicted ORF(s), "
f"with GC3 of {float(row.get('GC3_percent', 0)):.2f}% and ENc of {float(row.get('effective_number_of_codons_ENc', 0)):.2f}. "
f"These outputs provide genome composition, annotation, AMR, virulence, and codon bias evidence for downstream comparative genomics and methodological reporting."
)
# ============================================================
# Figures
# ============================================================
def style_axes(ax):
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
def fig_to_png_bytes(fig):
buf = io.BytesIO()
fig.savefig(buf, format="png", dpi=300, bbox_inches="tight")
buf.seek(0)
return buf.read()
def fig_to_pdf_bytes(fig):
buf = io.BytesIO()
fig.savefig(buf, format="pdf", bbox_inches="tight")
buf.seek(0)
return buf.read()
def fig_contig_distribution(contig_df):
if contig_df.empty:
return None
fig, ax = plt.subplots(figsize=(8, 5), dpi=300)
ax.hist(contig_df["contig_length"], bins=30, color=PALETTE["primary"], edgecolor="white")
ax.set_title("Contig length distribution")
ax.set_xlabel("Contig length bp")
ax.set_ylabel("Frequency")
style_axes(ax)
return fig
def fig_top_contigs(contig_df):
if contig_df.empty:
return None
plot = contig_df.sort_values("contig_length", ascending=False).head(30).copy()
plot["rank"] = range(1, len(plot) + 1)
fig, ax = plt.subplots(figsize=(8, 5), dpi=300)
ax.bar(plot["rank"], plot["contig_length"], color=PALETTE["primary"], edgecolor="white")
ax.set_title("Top contig lengths")
ax.set_xlabel("Contig rank")
ax.set_ylabel("Length bp")
style_axes(ax)
return fig
def fig_gc_by_contig(contig_df):
if contig_df.empty:
return None
plot = contig_df.sort_values("contig_length", ascending=False).head(60).copy()
fig, ax = plt.subplots(figsize=(8, 5), dpi=300)
ax.scatter(plot["contig_length"], plot["GC_percent"], alpha=0.8, color=PALETTE["accent"])
ax.set_title("Contig length and GC content")
ax.set_xlabel("Contig length bp")
ax.set_ylabel("GC content percent")
style_axes(ax)
return fig
def fig_feature_counts(feature_df):
if feature_df.empty:
return None
counts = feature_df["feature_type"].value_counts().reset_index()
counts.columns = ["feature_type", "count"]
fig, ax = plt.subplots(figsize=(8, 5), dpi=300)
ax.bar(counts["feature_type"], counts["count"], color=PALETTE["primary"], edgecolor="white")
ax.set_title("Annotated genomic feature classes")
ax.set_xlabel("Feature type")
ax.set_ylabel("Count")
ax.tick_params(axis="x", rotation=45)
style_axes(ax)
return fig
def fig_cds_length(feature_df):
if feature_df.empty:
return None
cds = feature_df[feature_df["feature_type"] == "CDS"]
if cds.empty:
return None
fig, ax = plt.subplots(figsize=(8, 5), dpi=300)
ax.hist(cds["length_bp"].dropna(), bins=40, color=PALETTE["primary"], edgecolor="white")
ax.set_title("CDS length distribution")
ax.set_xlabel("CDS length bp")
ax.set_ylabel("Frequency")
style_axes(ax)
return fig
def fig_hypothetical_status(feature_df):
if feature_df.empty:
return None
cds = feature_df[feature_df["feature_type"] == "CDS"]
if cds.empty:
return None
product_lower = cds["product"].fillna("").str.lower()
hypothetical = int(product_lower.str.contains("hypothetical protein", regex=False).sum())
functional = int(len(cds) - hypothetical)
fig, ax = plt.subplots(figsize=(6.5, 5), dpi=300)
ax.bar(["Functional CDS", "Hypothetical CDS"], [functional, hypothetical],
color=[PALETTE["accent"], PALETTE["secondary"]], edgecolor="white")
ax.set_title("Functional annotation status")
ax.set_ylabel("Number of CDS")
style_axes(ax)
return fig
def fig_detection_groups(summary_df, title):
if summary_df.empty:
return None
plot = summary_df.head(15).copy()
fig, ax = plt.subplots(figsize=(9, 5.5), dpi=300)
ax.bar(plot["functional_group"], plot["number_of_hits"], color=PALETTE["secondary"], edgecolor="white")
ax.set_title(title)
ax.set_xlabel("Functional group")
ax.set_ylabel("Number of hits")
ax.tick_params(axis="x", rotation=45, labelsize=9)
style_axes(ax)
return fig
def fig_identity_coverage(hit_df, db_type):
if hit_df.empty:
return None
sub = hit_df[hit_df["database"] == db_type]
if sub.empty:
return None
fig, ax = plt.subplots(figsize=(7.8, 5.5), dpi=300)
coverage_col = "reference_coverage_pct" if "reference_coverage_pct" in sub.columns else "subject_coverage_pct"
ax.scatter(sub[coverage_col], sub["pident"], alpha=0.8, color=PALETTE["primary"])
ax.set_title(f"{db_type} hit quality")
ax.set_xlabel("Reference sequence coverage percent")
ax.set_ylabel("Identity percent")
style_axes(ax)
return fig
def fig_top_genes(hit_df, db_type):
if hit_df.empty:
return None
sub = hit_df[hit_df["database"] == db_type]
if sub.empty:
return None
counts = sub["gene_symbol"].fillna("Unknown").replace("", "Unknown").value_counts().head(15)
fig, ax = plt.subplots(figsize=(9, 6), dpi=300)
ax.barh(counts.index[::-1], counts.values[::-1], color=PALETTE["accent"], edgecolor="white")
ax.set_title(f"Top detected {db_type} genes")
ax.set_xlabel("Number of hits")
ax.set_ylabel("Gene")
style_axes(ax)
return fig
def fig_amr_class_counts(hit_df):
"""AMR hits per resistance class. Uses the AMRFinderPlus class column when
present, with a fallback to functional_group for BLAST only rows."""
if hit_df is None or hit_df.empty:
return None
sub = hit_df[hit_df["database"] == "AMR"].copy()
if sub.empty:
return None
if "class" in sub.columns:
class_label = sub["class"].fillna("").astype(str).str.strip()
else:
class_label = pd.Series([""] * len(sub), index=sub.index)
fallback = sub["functional_group"].fillna("Unclassified").astype(str).str.strip()
class_label = class_label.where(class_label != "", fallback).replace("", "Unclassified")
counts = class_label.value_counts().head(20)
if counts.empty:
return None
fig, ax = plt.subplots(figsize=(9, 6), dpi=300)
ax.barh(counts.index[::-1], counts.values[::-1], color=PALETTE["secondary"], edgecolor="white")
ax.set_title("AMR gene hits per resistance class")
ax.set_xlabel("Number of hits")
ax.set_ylabel("Resistance class")
style_axes(ax)
return fig
def fig_top_virulence_genes(hit_df):
if hit_df.empty:
return None
sub = hit_df[hit_df["database"].isin(["VFDB", "Virulence"])]
if sub.empty:
return None
counts = sub["gene_symbol"].fillna("Unknown").replace("", "Unknown").value_counts().head(15)
fig, ax = plt.subplots(figsize=(9, 6), dpi=300)
ax.barh(counts.index[::-1], counts.values[::-1], color=PALETTE["accent"], edgecolor="white")
ax.set_title("Top detected virulence genes")
ax.set_xlabel("Number of hits")
ax.set_ylabel("Gene")
style_axes(ax)
return fig
def fig_virulence_identity_coverage(hit_df):
if hit_df.empty:
return None
sub = hit_df[hit_df["database"].isin(["VFDB", "Virulence"])]
if sub.empty:
return None
fig, ax = plt.subplots(figsize=(7.8, 5.5), dpi=300)
coverage_col = "reference_coverage_pct" if "reference_coverage_pct" in sub.columns else "subject_coverage_pct"
ax.scatter(sub[coverage_col], sub["pident"], alpha=0.8, color=PALETTE["primary"])
ax.set_title("Virulence hit quality")
ax.set_xlabel("Reference sequence coverage percent")
ax.set_ylabel("Identity percent")
style_axes(ax)
return fig
def fig_heatmap(hit_df, db_type, basis):
if hit_df.empty:
return None
sub = hit_df[hit_df["database"] == db_type]
if sub.empty or sub["input_file"].nunique() < 2:
return None
col = "gene_symbol" if basis == "Gene" else "functional_group"
matrix = pd.crosstab(sub["input_file"], sub[col])
if matrix.empty:
return None
matrix = matrix.loc[:, matrix.sum(axis=0).sort_values(ascending=False).head(30).index]
fig, ax = plt.subplots(figsize=(max(8, matrix.shape[1] * 0.45), max(4.5, matrix.shape[0] * 0.55)), dpi=300)
im = ax.imshow(matrix.values, aspect="auto", cmap="viridis")
ax.set_title(f"{db_type} comparative heatmap")
ax.set_xlabel(col)
ax.set_ylabel("Genome")
ax.set_xticks(np.arange(matrix.shape[1]))
ax.set_yticks(np.arange(matrix.shape[0]))
ax.set_xticklabels(matrix.columns, rotation=60, ha="right", fontsize=8)
ax.set_yticklabels(matrix.index, fontsize=8)
cbar = fig.colorbar(im, ax=ax)
cbar.set_label("Hit count")
return fig
def fig_virulence_heatmap(hit_df, basis):
"""Comparative virulence heatmap that includes both BLAST VFDB hits and
AMRFinderPlus virulence rows."""
if hit_df is None or hit_df.empty:
return None
sub = hit_df[hit_df["database"].isin(["VFDB", "Virulence"])].copy()
if sub.empty or sub["input_file"].nunique() < 2:
return None
col = "gene_symbol" if basis == "Gene" else "functional_group"
matrix = pd.crosstab(sub["input_file"], sub[col])
if matrix.empty:
return None
matrix = matrix.loc[:, matrix.sum(axis=0).sort_values(ascending=False).head(30).index]
fig, ax = plt.subplots(figsize=(max(8, matrix.shape[1] * 0.45), max(4.5, matrix.shape[0] * 0.55)), dpi=300)
im = ax.imshow(matrix.values, aspect="auto", cmap="viridis")
ax.set_title("Virulence comparative heatmap")
ax.set_xlabel(col)
ax.set_ylabel("Genome")
ax.set_xticks(np.arange(matrix.shape[1]))
ax.set_yticks(np.arange(matrix.shape[0]))
ax.set_xticklabels(matrix.columns, rotation=60, ha="right", fontsize=8)
ax.set_yticklabels(matrix.index, fontsize=8)
cbar = fig.colorbar(im, ax=ax)
cbar.set_label("Hit count")
return fig
def fig_bgc_types(smc_df):
if smc_df is None or smc_df.empty:
return None
types = []
for v in smc_df["bgc_types"].fillna(""):
for t in str(v).split(","):
t = t.strip()
if t and t not in ("unspecified", "see region file"):
types.append(t)
if not types:
return None
counts = pd.Series(Counter(types)).sort_values(ascending=False).head(15)
fig, ax = plt.subplots(figsize=(9, 5.5), dpi=300)
ax.bar(counts.index, counts.values, color=PALETTE["purple"], edgecolor="white")
ax.set_title("Predicted secondary metabolite BGC types")
ax.set_xlabel("Biosynthetic gene cluster type")
ax.set_ylabel("Number of regions")
ax.tick_params(axis="x", rotation=45, labelsize=9)
style_axes(ax)
return fig
def fig_rscu(rscu_df, isolate):
if rscu_df.empty:
return None
sub = rscu_df[rscu_df["input_file"] == isolate]
if sub.empty:
return None
sub = sub.sort_values(["amino_acid", "codon"])
fig, ax = plt.subplots(figsize=(13, 5.8), dpi=300)
ax.bar(sub["codon"], sub["RSCU"], color=PALETTE["primary"], edgecolor="white")
ax.axhline(1.0, linestyle="--", linewidth=1, color=PALETTE["neutral"])
ax.set_title(f"Relative synonymous codon usage: {isolate}")
ax.set_xlabel("Codon")
ax.set_ylabel("RSCU")
ax.tick_params(axis="x", rotation=90, labelsize=8)
style_axes(ax)
return fig
def fig_window_gc(window_df, isolate):
if window_df.empty:
return None
sub = window_df[window_df["input_file"] == isolate]
if sub.empty:
return None
longest = sub.groupby("contig_id")["end"].max().sort_values(ascending=False).index[0]
sub = sub[sub["contig_id"] == longest]
fig, ax = plt.subplots(figsize=(10, 4.8), dpi=300)
ax.plot(sub["midpoint"], sub["GC_percent"], linewidth=1.8, color=PALETTE["primary"])
ax.set_title(f"Window GC profile: {isolate} | {longest}")
ax.set_xlabel("Position bp")
ax.set_ylabel("GC percent")
ax.grid(alpha=0.25, linestyle="--")
style_axes(ax)
return fig
def fig_gc_skew(window_df, isolate):
if window_df.empty:
return None
sub = window_df[window_df["input_file"] == isolate]
if sub.empty:
return None
longest = sub.groupby("contig_id")["end"].max().sort_values(ascending=False).index[0]
sub = sub[sub["contig_id"] == longest].copy()
sub["cumulative_GC_skew"] = sub["GC_skew"].cumsum()
fig, ax = plt.subplots(figsize=(10, 4.8), dpi=300)
ax.plot(sub["midpoint"], sub["cumulative_GC_skew"], linewidth=1.8, color=PALETTE["secondary"])
ax.axhline(0, linewidth=0.8, color=PALETTE["neutral"])
ax.set_title(f"Cumulative GC skew: {isolate} | {longest}")
ax.set_xlabel("Position bp")
ax.set_ylabel("Cumulative GC skew")
ax.grid(alpha=0.25, linestyle="--")
style_axes(ax)
return fig
def collect_figures(tables, heatmap_basis):
figures = {}
genome_df = tables.get("genome_statistics", pd.DataFrame())
contig_df = tables.get("contig_statistics", pd.DataFrame())
feature_df = tables.get("annotation_feature_table", pd.DataFrame())
hit_df = tables.get("raw_hit_table", pd.DataFrame())
vf_summary = tables.get("virulence_summary", pd.DataFrame())
amr_summary = tables.get("amr_summary", pd.DataFrame())
rscu_df = tables.get("rscu_table", pd.DataFrame())
window_df = tables.get("window_gc_skew", pd.DataFrame())
per_gene_df = tables.get("per_gene_codon_indices", pd.DataFrame())
aa_df = tables.get("amino_acid_composition", pd.DataFrame())
smc_df = tables.get("secondary_metabolite_clusters", pd.DataFrame())
fig_builders = {
"figure_01_nucleotide_composition": lambda: fig_nucleotide_donut(genome_df),
"figure_02_contig_length_distribution": lambda: fig_contig_distribution(contig_df),
"figure_03_top_contig_lengths": lambda: fig_top_contigs(contig_df),
"figure_04_gc_content_by_contig": lambda: fig_gc_by_contig(contig_df),
"figure_05_feature_type_counts": lambda: fig_feature_counts(feature_df),
"figure_06_cds_length_distribution": lambda: fig_cds_length(feature_df),
"figure_07_functional_annotation_status": lambda: fig_hypothetical_status(feature_df),
"figure_08_virulence_functional_groups": lambda: fig_detection_groups(vf_summary, "Virulence hits by functional group"),
"figure_09_amr_resistance_groups": lambda: fig_detection_groups(amr_summary, "AMR hits by resistance class"),
"figure_10_virulence_identity_coverage": lambda: fig_virulence_identity_coverage(hit_df),
"figure_11_amr_identity_coverage": lambda: fig_identity_coverage(hit_df, "AMR"),
"figure_12_top_virulence_genes": lambda: fig_top_virulence_genes(hit_df),
"figure_13_top_amr_genes": lambda: fig_top_genes(hit_df, "AMR"),
"figure_14_virulence_heatmap": lambda: fig_virulence_heatmap(hit_df, heatmap_basis),
"figure_15_amr_heatmap": lambda: fig_heatmap(hit_df, "AMR", heatmap_basis),
"figure_16_secondary_metabolite_bgc_types": lambda: fig_bgc_types(smc_df),
"figure_17_amr_resistance_class_counts": lambda: fig_amr_class_counts(hit_df),
}
for name, builder in fig_builders.items():
try:
fig = builder()
if fig is not None:
figures[name] = fig
except Exception as exc:
LOGGER.warning("Figure generation failed for %s: %s", name, exc)
if not rscu_df.empty:
for isolate in sorted(rscu_df["input_file"].unique())[:5]:
fig = fig_rscu(rscu_df, isolate)
if fig is not None:
figures[f"figure_rscu_{sanitize_text(isolate)}"] = fig
try:
fig = cbe.fig_rscu_heatmap(rscu_df, isolate)
if fig is not None:
figures[f"figure_rscu_heatmap_{sanitize_text(isolate)}"] = fig
except Exception as exc:
LOGGER.warning("RSCU heatmap generation failed for %s: %s", isolate, exc)
# Codon bias methodological figures per isolate
if not per_gene_df.empty:
for isolate in sorted(per_gene_df["input_file"].unique())[:5]:
try:
f = cbe.fig_enc_plot(per_gene_df, isolate)
if f is not None:
figures[f"figure_enc_plot_{sanitize_text(isolate)}"] = f
except Exception as exc:
LOGGER.warning("ENc plot generation failed for %s: %s", isolate, exc)
try:
res = cbe.fig_neutrality_plot(per_gene_df, isolate)
if res is not None:
figures[f"figure_neutrality_plot_{sanitize_text(isolate)}"] = res[0]
except Exception as exc:
LOGGER.warning("Neutrality plot generation failed for %s: %s", isolate, exc)
try:
f = cbe.fig_pr2_plot(per_gene_df, isolate)
if f is not None:
figures[f"figure_pr2_plot_{sanitize_text(isolate)}"] = f
except Exception as exc:
LOGGER.warning("PR2 plot generation failed for %s: %s", isolate, exc)
# Amino acid composition per isolate
if not aa_df.empty:
for isolate in sorted(aa_df["input_file"].unique())[:5]:
try:
f = cbe.fig_amino_acid_composition(aa_df, isolate)
if f is not None:
figures[f"figure_amino_acid_composition_{sanitize_text(isolate)}"] = f
except Exception as exc:
LOGGER.warning("Amino acid composition figure failed for %s: %s", isolate, exc)
if not window_df.empty:
genome_gc_by_isolate = {}
if not genome_df.empty and "input_file" in genome_df.columns:
genome_gc_by_isolate = dict(zip(genome_df["input_file"], genome_df["GC_percent"]))
for isolate in sorted(window_df["input_file"].unique())[:5]:
fig = fig_window_gc(window_df, isolate)
if fig is not None:
figures[f"figure_gc_profile_{sanitize_text(isolate)}"] = fig
fig = fig_gc_skew(window_df, isolate)
if fig is not None:
figures[f"figure_cumulative_gc_skew_{sanitize_text(isolate)}"] = fig
try:
fig = fig_circular_genome(window_df, isolate, genome_gc_mean=genome_gc_by_isolate.get(isolate))
if fig is not None:
figures[f"figure_circular_genome_map_{sanitize_text(isolate)}"] = fig
except Exception as exc:
LOGGER.warning("Circular genome map generation failed for %s: %s", isolate, exc)
return figures
# ============================================================
# Output ZIP
# ============================================================
def make_zip(tables, reports, figures, logs, manifest):
mem = io.BytesIO()
with zipfile.ZipFile(mem, "w", compression=zipfile.ZIP_DEFLATED) as zf:
for name, df in tables.items():
if df is not None:
zf.writestr(f"tables/{sanitize_text(name)}.csv", df.to_csv(index=False))
for name, text in reports.items():
zf.writestr(f"reports/{sanitize_text(name)}.txt", text + "\n")
for name, fig in figures.items():
zf.writestr(f"figures/png/{sanitize_text(name)}.png", fig_to_png_bytes(fig))
zf.writestr(f"figures/pdf/{sanitize_text(name)}.pdf", fig_to_pdf_bytes(fig))
for name, text in logs.items():
zf.writestr(f"logs/{sanitize_text(name)}.txt", text)
zf.writestr("metadata/run_manifest.json", json.dumps(manifest, indent=2))
zf.writestr("README_OUTPUTS.txt", (
f"{APP_TITLE} v{APP_VERSION}\n\n"
"This ZIP archive contains FASTA quality control, genome statistics, Bakta or Prokka annotation summaries, AMR and virulence gene screening results, "
"secondary metabolite gene cluster predictions, codon usage analysis including per-gene ENc, neutrality, and PR2 analyses, "
"amino acid composition, window based GC and skew analysis, a circular genome map, manuscript ready result paragraphs, logs, and publication quality "
"figures in PNG and PDF formats.\n"
))
mem.seek(0)
return mem.read()
# ============================================================
# UI
# ============================================================
st.markdown(f"## {APP_TITLE}")
st.caption(f"{APP_TAGLINE} | Version {APP_VERSION} | Run schema {RUN_SCHEMA_VERSION}")
st.write(APP_SUBTITLE)
with st.expander("Methodological scope and interpretation", expanded=False):
st.write(
"The tool performs genome level analysis from bacterial FASTA files. Bakta is preferred for standardized bacterial annotation when its database is available, with Prokka as a compatible fallback. "
"Virulence and AMR detection use built-in NCBI AMRFinderPlus --plus where available, as well as optional nucleotide homology searches against user supplied or preinstalled BLAST databases. "
"Secondary metabolite gene clusters are predicted with antiSMASH where available. "
"Codon usage bias is reported with RSCU, ENc, GC3, and the standard per-gene ENc plot, neutrality plot, and PR2 plot. "
"For BLAST-based gene detection, completeness is measured against the reference gene sequence rather than the full genome contig. "
"Results are predictions and should be interpreted with database provenance, selected thresholds, genome quality, species context, and phenotype data where available."
)
with st.sidebar:
st.header("Analysis modules")
run_annotation = st.checkbox("Run standardized genome annotation", value=True)
run_vfdb = st.checkbox("Detect virulence genes", value=True)
run_amr = st.checkbox("Detect AMR genes", value=True)
run_smc = st.checkbox("Detect secondary metabolites (antiSMASH)", value=False)
run_codon = st.checkbox("Run codon usage analysis", value=True)
run_windows = st.checkbox("Run window GC and skew analysis", value=True)
st.header("Annotation parameters")
annotation_engine = st.selectbox(
"Annotation engine",
["Auto (Bakta preferred)", "Bakta", "Prokka"],
index=0,
help="Auto uses Bakta for bacterial genomes when its database is available, otherwise Prokka.",
)
genus = st.text_input("Genus", value="Escherichia")
species = st.text_input("Species", value="coli")
kingdom = st.selectbox("Kingdom", ["Bacteria", "Archaea", "Viruses"], index=0)
locus_tag = st.text_input("Locus tag", value="BGA")
prokka_compliant = st.checkbox("Use Prokka compliant mode", value=False)
prokka_addgenes = st.checkbox("Add gene features", value=True)
st.header("BLAST thresholds")
min_identity = st.slider("Minimum nucleotide identity percent", 50.0, 100.0, 90.0, 1.0)
min_reference_cov = st.slider(
"Minimum reference gene coverage percent",
20.0,
100.0,
80.0,
1.0,
help="Coverage is calculated against the AMR or virulence reference sequence, not the full genome contig.",
)
min_alignment_bp = st.number_input(
"Minimum aligned length bp",
min_value=0,
max_value=10000,
value=100,
step=10,
)
evalue = st.selectbox("E value", [1e-5, 1e-10, 1e-20, 1e-30, 1e-50], index=2)
max_targets = st.slider("Maximum target hits per query", 1, 100, 10, 1)
blast_task = st.selectbox("BLASTN task", ["megablast", "blastn"], index=0)
st.header("Species filtering")
st.caption("Applies to BLAST results only. AMRFinderPlus results are not filtered by organism.")
species_filter_text = st.text_input("Reference organism filter", value="")
species_filter_mode = st.selectbox("Filter mode", ["Contains text", "Genus-level", "Exact species"], index=0)
st.header("Database options")
st.caption("Upload database FASTA files if prebuilt databases are not installed in the Docker image.")
vfdb_upload = st.file_uploader("Optional VFDB nucleotide FASTA", type=["fa", "fasta", "fna", "fas", "txt", "gz"], key="vfdb_ref")
amr_upload = st.file_uploader("Optional AMR nucleotide FASTA", type=["fa", "fasta", "fna", "fas", "txt", "gz"], key="amr_ref")
st.header("Codon and window settings")
min_orf_aa = st.slider("Minimum ORF length aa", 30, 300, 90, 10)
cai_upload = st.file_uploader("Optional CAI weight CSV", type=["csv"])
window_size = st.number_input("Window size bp", min_value=500, max_value=100000, value=5000, step=500)
heatmap_basis = st.selectbox("Comparative heatmap basis", ["Gene", "Functional group"], index=0)
threads = st.slider("CPU threads", 1, max(1, os.cpu_count() or 2), min(4, max(1, os.cpu_count() or 2)), 1)
with st.expander("Deployment status", expanded=False):
st.write(f"Application version: {APP_VERSION}")
st.write(f"Bakta available: {bakta_available()}")
st.write(f"Bakta version: {bakta_version()}")
st.write(f"Bakta database detected: {bakta_database_available()} at {DEFAULT_BAKTA_DB}")
st.write(f"Prokka available: {command_available('prokka')}")
st.write(f"Prokka version: {prokka_version()}")
st.write(f"blastn available: {command_available('blastn')}")
st.write(f"makeblastdb available: {command_available('makeblastdb')}")
st.write(f"AMRFinderPlus available: {amrfinder_available()}")
st.write(f"AMRFinderPlus version: {amrfinder_version()}")
st.write(f"antiSMASH available: {antismash_available()}")
st.write(f"antiSMASH version: {antismash_version()}")
st.write(f"Streamlit XSRF protection enabled: {st.get_option('server.enableXsrfProtection')}")
st.write(f"Streamlit CORS enabled: {st.get_option('server.enableCORS')}")
st.write(f"Streamlit max upload size MB: {st.get_option('server.maxUploadSize')}")
st.write(f"Installed VFDB database detected: {db_exists(DEFAULT_VFDB_DB_PREFIX)} at {DEFAULT_VFDB_DB_PREFIX}")
st.write(f"Installed AMR database detected: {db_exists(DEFAULT_AMR_DB_PREFIX)} at {DEFAULT_AMR_DB_PREFIX}")
uploaded_files = st.file_uploader(
"Upload one or more bacterial genome FASTA files",
type=["fa", "fasta", "fna", "fas", "ffn", "txt", "gz"],
accept_multiple_files=True,
)
c1, c2 = st.columns(2)
run_clicked = c1.button("Run complete genome analysis", type="primary", use_container_width=True)
clear_clicked = c2.button("Clear results", use_container_width=True)
if clear_clicked:
clear_results()
if run_clicked:
if not uploaded_files:
st.error("Please upload at least one bacterial genome FASTA file.")
else:
invalid = [f.name for f in uploaded_files if not validate_extension(f.name)]
total_size_mb = sum(f.size for f in uploaded_files) / (1024 * 1024)
if invalid:
st.error("Unsupported file type detected: " + ", ".join(invalid))
elif total_size_mb > MAX_UPLOAD_MB:
st.error(f"Uploaded files exceed the configured limit of {MAX_UPLOAD_MB} MB.")
else:
progress = st.progress(0)
status = st.empty()
annotation_modes = {}
try:
all_genome_stats = []
all_fasta_quality = []
input_provenance = []
all_contigs = []
all_windows = []
all_features = []
all_annotation_summaries = []
all_hits = []
all_orfs = []
all_rscu = []
all_codon_stats = []
all_per_gene = []
all_aa = []
all_smc = []
logs = {}
with tempfile.TemporaryDirectory() as tmp:
tmpdir = Path(tmp)
raw_dir = tmpdir / "raw"
prepared_dir = tmpdir / "prepared"
db_dir = tmpdir / "databases"
blast_dir = tmpdir / "blast"
annotation_root = tmpdir / "annotation"
antismash_root = tmpdir / "antismash"
for p in [raw_dir, prepared_dir, db_dir, blast_dir, annotation_root, antismash_root]:
p.mkdir(parents=True, exist_ok=True)
status.info("Preparing built-in AMRFinderPlus and optional BLAST databases.")
vfdb_prefix = resolve_database(DEFAULT_VFDB_DB_PREFIX, vfdb_upload, db_dir, "vfdb_uploaded") if run_vfdb else None
amr_prefix = resolve_database(DEFAULT_AMR_DB_PREFIX, amr_upload, db_dir, "amr_uploaded") if run_amr else None
use_amrfinderplus = (run_vfdb or run_amr) and amrfinder_available()
if run_vfdb and vfdb_prefix is None and use_amrfinderplus:
st.info("No VFDB BLAST database was found, so virulence screening will use the built-in NCBI AMRFinderPlus --plus detector. Upload VFDB FASTA or install a VFDB BLAST database only if you specifically want VFDB based screening.")
if run_amr and amr_prefix is None and use_amrfinderplus:
st.info("No AMR BLAST database was found, so AMR screening will use the built-in NCBI AMRFinderPlus detector.")
# Report missing detectors per module, rather than one combined
# message, so the guidance only names the module(s) that were
# actually requested and are genuinely unavailable.
missing_amr = run_amr and amr_prefix is None and not use_amrfinderplus
missing_vfdb = run_vfdb and vfdb_prefix is None and not use_amrfinderplus
if missing_amr or missing_vfdb:
missing_labels = []
if missing_amr:
missing_labels.append("AMR")
if missing_vfdb:
missing_labels.append("virulence")
joined = " or ".join(missing_labels)
st.error(
f"No {joined} detector is available. The Docker image must install "
"ncbi-amrfinderplus, or you must upload VFDB and AMR FASTA databases. "
f"{'AMR' if missing_amr else 'Virulence'} screening will be skipped for this run "
"until one of the options below is in place."
)
with st.expander("How to fix this", expanded=False):
st.markdown(
"**Option 1: install NCBI AMRFinderPlus in the Docker image (covers both AMR and virulence).**\n"
"```\nmicromamba install -n genomics -c bioconda -c conda-forge ncbi-amrfinderplus\namrfinder -u\n```\n"
"The `amrfinder -u` step downloads the reference database and must run during "
"the image build, before deployment, since this app does not have outbound "
"internet access to fetch it at request time.\n\n"
"**Option 2: install ncbi-blast+ and mount preinstalled BLAST databases.**\n"
"Build nucleotide BLAST databases with `makeblastdb -dbtype nucl` and place them "
f"at the paths configured by the `VFDB_DB_PREFIX` (currently `{DEFAULT_VFDB_DB_PREFIX}`) "
f"and `AMR_DB_PREFIX` (currently `{DEFAULT_AMR_DB_PREFIX}`) environment variables.\n\n"
"**Option 3: upload a reference FASTA directly in this session.**\n"
"Use the 'Database options' section in the sidebar to upload a VFDB and/or AMR "
"nucleotide FASTA file. The app will build a temporary BLAST database from it "
"for this run only.\n\n"
"If you do not need this module, you can also simply turn off "
f"'{'Detect AMR genes' if missing_amr else 'Detect virulence genes'}' "
"in the sidebar to stop seeing this message."
)
cai_weights = load_cai_weights(cai_upload) if run_codon else {}
used_sample_prefixes = set()
for idx, uploaded in enumerate(uploaded_files, start=1):
status.info(f"Analysing {uploaded.name}")
progress.progress(int((idx - 1) / len(uploaded_files) * 100))
sample_prefix = sanitize_text(Path(uploaded.name).stem)
if sample_prefix in used_sample_prefixes:
sample_prefix = f"{sample_prefix}_{idx}"
used_sample_prefixes.add(sample_prefix)
raw_path = read_uploaded_to_path(uploaded, raw_dir)
input_provenance.append({
"file_name": uploaded.name,
"size_bytes": int(raw_path.stat().st_size),
"sha256": sha256_path(raw_path),
})
dec_path = decompress_if_needed(raw_path, prepared_dir)
fasta_path = normalize_fasta(dec_path, prepared_dir)
records = read_fasta_records(fasta_path)
all_fasta_quality.append(
fasta_quality_summary(records, uploaded.name)
)
if not records:
raise ValueError(f"No FASTA records were found in {uploaded.name}")
comp = genome_composition(records)
comp["input_file"] = uploaded.name
all_genome_stats.append(comp)
contigs = contig_statistics(records, uploaded.name)
all_contigs.append(contigs)
if run_windows:
all_windows.append(window_statistics(records, uploaded.name, int(window_size)))
annotation_cds = None
if run_annotation:
selected_engine = choose_annotation_engine(annotation_engine, kingdom)
annotation_out = annotation_root / sample_prefix
if selected_engine == "Bakta":
result = run_bakta(
fasta_path=fasta_path,
outdir=annotation_out,
prefix=sample_prefix,
genus=genus,
species=species,
threads=int(threads),
locus_tag=locus_tag,
compliant=prokka_compliant,
)
if not result.get("success") and annotation_engine.startswith("Auto"):
result = run_prokka(
fasta_path=fasta_path,
outdir=annotation_out,
prefix=sample_prefix,
genus=genus,
species=species,
kingdom=kingdom,
threads=int(threads),
locus_tag=locus_tag,
compliant=prokka_compliant,
addgenes=prokka_addgenes,
)
result["engine"] = "prokka"
else:
result = run_prokka(
fasta_path=fasta_path,
outdir=annotation_out,
prefix=sample_prefix,
genus=genus,
species=species,
kingdom=kingdom,
threads=int(threads),
locus_tag=locus_tag,
compliant=prokka_compliant,
addgenes=prokka_addgenes,
)
result["engine"] = "prokka"
engine_name = result.get("engine", selected_engine.lower())
logs[f"annotation_{engine_name}_{sample_prefix}"] = result.get("log", "")
annotation_modes[uploaded.name] = {
"engine": engine_name,
"mode": result.get("mode"),
"success": bool(result.get("success")),
}
if result.get("mode") == "noanno":
st.warning(
f"{uploaded.name}: Prokka completed in --noanno fallback mode. "
"Gene prediction is available, but CDS product annotation is limited."
)
if not result.get("success"):
st.warning(
f"{uploaded.name}: annotation did not complete. "
"Genome composition and enabled independent modules will continue."
)
gff_path = find_annotation_file(
result["outdir"],
sample_prefix,
[".gff3", ".gff"],
)
feature_df = (
parse_prokka_gff(gff_path, uploaded.name)
if gff_path is not None
else pd.DataFrame()
)
all_features.append(feature_df)
all_annotation_summaries.append(
annotation_summary(
feature_df,
uploaded.name,
comp["total_bases"],
)
)
annotation_cds = read_annotation_cds(
result["outdir"],
sample_prefix,
)
if run_codon:
orfs, rscu, codon_stats, per_gene, aa_comp = codon_analysis(
records, uploaded.name, min_orf_aa, cai_weights, cds_pairs=annotation_cds
)
all_orfs.append(orfs)
all_rscu.append(rscu)
all_codon_stats.append(codon_stats)
all_per_gene.append(per_gene)
all_aa.append(aa_comp)
# Secondary metabolite gene clusters (antiSMASH)
if run_smc and antismash_available():
smc_out = antismash_root / sample_prefix
res_smc = run_antismash(fasta_path, smc_out, sample_prefix, taxon="bacteria", threads=int(threads))
logs[f"antismash_{sample_prefix}"] = res_smc["log"]
if res_smc["success"]:
all_smc.append(parse_antismash_results(res_smc["outdir"], sample_prefix, uploaded.name))
else:
st.warning(f"{uploaded.name}: antiSMASH did not complete. See the logs.")
elif run_smc and not antismash_available():
st.info("antiSMASH is not installed, so secondary metabolite detection was skipped. Install antismash in the Docker image to enable it.")
# 1) Built-in NCBI AMRFinderPlus: AMR + virulence + stress/biocide/metal
if use_amrfinderplus:
amr_tsv = blast_dir / f"{sample_prefix}_amrfinderplus.tsv"
organism = supported_amrfinder_organism(genus, species)
try:
logs[f"amrfinderplus_{sample_prefix}"] = run_amrfinderplus(
fasta_path, amr_tsv, threads=int(threads), organism=organism
)
amr_hits = parse_amrfinderplus_output(amr_tsv, uploaded.name)
if not amr_hits.empty:
keep_dbs = []
if run_amr:
keep_dbs += ["AMR", "Stress_Biocide"]
if run_vfdb:
keep_dbs += ["Virulence"]
amr_hits = amr_hits[amr_hits["database"].isin(keep_dbs)]
# No species filter here. AMRFinderPlus rows do not carry a
# source organism, so the filter would remove them all.
if not amr_hits.empty:
all_hits.append(amr_hits)
except Exception as exc:
logs[f"amrfinderplus_{sample_prefix}"] = f"AMRFinderPlus failed: {exc}"
st.warning(f"{uploaded.name}: AMRFinderPlus detection failed. See the logs for details.")
# 2) Optional BLAST homology search against installed or uploaded databases
for db_type, db_prefix in [("VFDB", vfdb_prefix), ("AMR", amr_prefix)]:
if db_prefix is None:
continue
out_tsv = blast_dir / f"{sample_prefix}_{db_type}.tsv"
try:
logs[f"blast_{db_type}_{sample_prefix}"] = run_blastn(
fasta_path,
db_prefix,
out_tsv,
evalue,
max_targets,
int(threads),
blast_task,
)
df = load_and_filter_blast(
out_tsv,
uploaded.name,
db_type,
min_identity,
min_reference_cov,
min_alignment_bp,
)
df = apply_species_filter(df, species_filter_text, species_filter_mode)
if not df.empty:
all_hits.append(df)
except Exception as exc:
logs[f"blast_{db_type}_{sample_prefix}"] = f"BLAST failed: {exc}"
progress.progress(100)
status.success("Analysis completed.")
genome_df = pd.DataFrame(all_genome_stats)
fasta_quality_df = pd.concat(all_fasta_quality, ignore_index=True) if all_fasta_quality else pd.DataFrame()
contig_df = pd.concat(all_contigs, ignore_index=True) if all_contigs else pd.DataFrame()
window_df = pd.concat(all_windows, ignore_index=True) if all_windows else pd.DataFrame()
feature_df = pd.concat(all_features, ignore_index=True) if all_features else pd.DataFrame()
annotation_df = pd.concat(all_annotation_summaries, ignore_index=True) if all_annotation_summaries else pd.DataFrame()
hit_df = pd.concat(all_hits, ignore_index=True) if all_hits else pd.DataFrame()
detailed_hits = format_hit_table(hit_df)
vf_summary = build_detection_summary(hit_df, "VFDB")
amr_summary = build_detection_summary(hit_df, "AMR")
orf_df = pd.concat(all_orfs, ignore_index=True) if all_orfs else pd.DataFrame()
rscu_df = pd.concat(all_rscu, ignore_index=True) if all_rscu else pd.DataFrame()
codon_df = pd.concat(all_codon_stats, ignore_index=True) if all_codon_stats else pd.DataFrame()
per_gene_df = pd.concat(all_per_gene, ignore_index=True) if all_per_gene else pd.DataFrame()
aa_df = pd.concat(all_aa, ignore_index=True) if all_aa else pd.DataFrame()
smc_df = pd.concat(all_smc, ignore_index=True) if all_smc else pd.DataFrame()
isolate_summary = build_isolate_summary(genome_df, annotation_df, hit_df, codon_df)
reports = {}
for _, row in isolate_summary.iterrows():
reports[f"{sanitize_text(row['input_file'])}_manuscript_result_paragraph"] = generate_report_paragraph(row)
tables = {
"isolate_summary": isolate_summary,
"genome_statistics": genome_df,
"fasta_quality_control": fasta_quality_df,
"contig_statistics": contig_df,
"window_gc_skew": window_df,
"annotation_summary": annotation_df,
"annotation_feature_table": feature_df,
"raw_hit_table": hit_df,
"detailed_gene_hits": detailed_hits,
"virulence_summary": vf_summary,
"amr_summary": amr_summary,
"secondary_metabolite_clusters": smc_df,
"predicted_orfs": orf_df,
"rscu_table": rscu_df,
"codon_usage_statistics": codon_df,
"per_gene_codon_indices": per_gene_df,
"amino_acid_composition": aa_df,
}
figures = collect_figures(tables, heatmap_basis)
manifest = {
"tool": APP_TITLE,
"tool_version": APP_VERSION,
"schema_version": RUN_SCHEMA_VERSION,
"analysis_date_utc": utc_now_iso(),
"run_id": hashlib.sha256((utc_now_iso() + "|" + "|".join(f.name for f in uploaded_files)).encode("utf-8")).hexdigest()[:16],
"input_files": input_provenance,
"runtime": {
"python_version": sys.version.split()[0],
"platform": platform.platform(),
"cpu_count": os.cpu_count(),
},
"annotation_modes": annotation_modes,
"modules": {
"genome_annotation": run_annotation,
"requested_annotation_engine": annotation_engine,
"virulence_screening": run_vfdb,
"amr_screening": run_amr,
"secondary_metabolites": run_smc,
"codon_usage": run_codon,
"window_gc_skew": run_windows,
},
"thresholds": {
"min_identity_percent": min_identity,
"min_reference_coverage_percent": min_reference_cov,
"min_alignment_length_bp": int(min_alignment_bp),
"evalue": evalue,
"max_targets": max_targets,
"blast_task": blast_task,
},
"software_status": {
"bakta_available": bakta_available(),
"bakta_version": bakta_version(),
"bakta_database_available": bakta_database_available(),
"bakta_database_path": str(DEFAULT_BAKTA_DB),
"prokka_available": command_available("prokka"),
"prokka_version": prokka_version(),
"blastn_available": command_available("blastn"),
"makeblastdb_available": command_available("makeblastdb"),
"amrfinderplus_available": amrfinder_available(),
"amrfinderplus_version": amrfinder_version(),
"antismash_available": antismash_available(),
"antismash_version": antismash_version(),
},
"database_status": {
"preinstalled_vfdb_detected": db_exists(DEFAULT_VFDB_DB_PREFIX),
"preinstalled_amr_detected": db_exists(DEFAULT_AMR_DB_PREFIX),
"uploaded_vfdb_used": vfdb_upload is not None,
"uploaded_amr_used": amr_upload is not None,
},
}
zip_bytes = make_zip(tables, reports, figures, logs, manifest)
figures_png = {name: fig_to_png_bytes(fig) for name, fig in figures.items()}
for fig in figures.values():
plt.close(fig)
st.session_state.run_complete = True
st.session_state.tables = tables
st.session_state.reports = reports
st.session_state.figures_png = figures_png
st.session_state.zip_bytes = zip_bytes
st.session_state.manifest = manifest
st.session_state.log_text = "\n\n".join([f"===== {k} =====\n{v}" for k, v in logs.items()])
except Exception as exc:
st.exception(exc)
if st.session_state.run_complete:
tables = st.session_state.tables
reports = st.session_state.reports
isolate_summary = tables.get("isolate_summary", pd.DataFrame())
detailed_hits = tables.get("detailed_gene_hits", pd.DataFrame())
vf_summary = tables.get("virulence_summary", pd.DataFrame())
amr_summary = tables.get("amr_summary", pd.DataFrame())
codon_df = tables.get("codon_usage_statistics", pd.DataFrame())
rscu_df = tables.get("rscu_table", pd.DataFrame())
genome_df = tables.get("genome_statistics", pd.DataFrame())
contig_df = tables.get("contig_statistics", pd.DataFrame())
window_df = tables.get("window_gc_skew", pd.DataFrame())
feature_df = tables.get("annotation_feature_table", pd.DataFrame())
per_gene_df = tables.get("per_gene_codon_indices", pd.DataFrame())
aa_df = tables.get("amino_acid_composition", pd.DataFrame())
smc_df = tables.get("secondary_metabolite_clusters", pd.DataFrame())
st.markdown("---")
st.subheader("Overall summary")
m1, m2, m3, m4, m5 = st.columns(5)
m1.metric("Genome files", isolate_summary.shape[0])
m2.metric("Total bases", f"{int(isolate_summary['total_bases'].sum()):,}" if "total_bases" in isolate_summary else "0")
m3.metric("Mean GC percent", f"{float(isolate_summary['GC_percent'].mean()):.2f}" if "GC_percent" in isolate_summary else "0")
m4.metric("Virulence hits", f"{int(isolate_summary['VFDB_hits'].sum()):,}" if "VFDB_hits" in isolate_summary else "0")
m5.metric("AMR hits", f"{int(isolate_summary['AMR_hits'].sum()):,}" if "AMR_hits" in isolate_summary else "0")
tab1, tab2, tab3, tab_smc, tab4, tab5, tab6 = st.tabs([
"Summary",
"Annotation",
"Virulence and AMR",
"Secondary metabolites",
"Codon and composition",
"Figures",
"Downloads",
])
with tab1:
st.dataframe(isolate_summary, use_container_width=True, height=360)
if reports:
selected = st.selectbox("Select result paragraph", list(reports.keys()))
st.info(reports[selected])
with tab2:
st.markdown("### Annotation summary")
st.dataframe(tables.get("annotation_summary", pd.DataFrame()), use_container_width=True, height=260)
st.markdown("### Annotation feature table")
st.dataframe(feature_df, use_container_width=True, height=460)
with tab3:
st.markdown("### Detailed virulence and AMR gene hits")
if detailed_hits.empty:
st.warning("No virulence or AMR hits passed the selected thresholds, or no detector was available.")
else:
st.dataframe(detailed_hits, use_container_width=True, height=460)
c1, c2 = st.columns(2)
with c1:
st.markdown("### Virulence summary")
st.dataframe(vf_summary, use_container_width=True, height=300)
with c2:
st.markdown("### AMR summary")
st.dataframe(amr_summary, use_container_width=True, height=300)
with tab_smc:
st.markdown("### Predicted secondary metabolite biosynthetic gene clusters")
if smc_df is None or smc_df.empty:
st.warning("No secondary metabolite clusters were detected, or antiSMASH was not enabled or installed.")
else:
st.dataframe(smc_df, use_container_width=True, height=420)
with tab4:
st.markdown("### Genome statistics")
st.dataframe(genome_df, use_container_width=True, height=280)
st.markdown("### Contig statistics")
st.dataframe(contig_df, use_container_width=True, height=280)
st.markdown("### Window GC and skew")
st.dataframe(window_df, use_container_width=True, height=280)
st.markdown("### Codon usage statistics")
st.dataframe(codon_df, use_container_width=True, height=220)
st.markdown("### Per-gene codon indices (ENc, GC3, GC12, PR2)")
st.dataframe(per_gene_df, use_container_width=True, height=300)
st.markdown("### Amino acid composition")
st.dataframe(aa_df, use_container_width=True, height=300)
st.markdown("### RSCU table")
st.dataframe(rscu_df, use_container_width=True, height=360)
with tab5:
if not st.session_state.figures_png:
st.info("No figures were generated.")
else:
for name, png in st.session_state.figures_png.items():
st_show_image(png, caption=name)
with tab6:
st.markdown("### Download complete report")
st.download_button(
"Download complete ZIP report",
data=st.session_state.zip_bytes,
file_name="bulamarwa_genomics_suite_report.zip",
mime="application/zip",
use_container_width=True,
)
st.markdown("### Download individual tables")
cols = st.columns(3)
table_items = list(tables.items())
for i, (name, df) in enumerate(table_items):
with cols[i % 3]:
st.download_button(
f"{name}.csv",
dataframe_to_csv_bytes(df),
file_name=f"{sanitize_text(name)}.csv",
mime="text/csv",
use_container_width=True,
)
with st.expander("Run manifest"):
st.json(st.session_state.manifest)
if st.session_state.log_text:
with st.expander("Tool logs"):
st.text(st.session_state.log_text)
else:
st.info(
"Upload bacterial genome FASTA files, configure the modules, then run the complete genome analysis. "
"For Hugging Face deployment, use a Docker Space so that Bakta or Prokka, ncbi-blast+, ncbi-amrfinderplus, and antiSMASH can be installed."
)
st.caption(
f"{APP_TITLE} v{APP_VERSION}. Interpretation note: AMR, virulence, and secondary metabolite results are prediction based. They do not replace phenotypic antimicrobial susceptibility testing, experimental virulence assays, or chemical confirmation of metabolites."
) |