Spaces:
Sleeping
Sleeping
File size: 89,621 Bytes
065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d de3e784 065e391 911d85d 065e391 59f5e9f 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 911d85d 065e391 | 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 | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Analysis - RodSizer</title>
<!-- Favicon -->
<link rel="icon" type="image/png" href="/static/assets/loading_screen.png">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<style>
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
max-width: 1800px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
}
/* --- INFO MODAL --- */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
display: none;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal-content {
background: white;
padding: 30px;
border-radius: 12px;
max-width: 600px;
width: 90%;
box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
position: relative;
}
.modal-close {
position: absolute;
top: 15px;
right: 15px;
border: none;
background: none;
font-size: 24px;
cursor: pointer;
color: #888;
}
.modal-section {
margin-bottom: 20px;
}
.modal-section h3 {
margin-top: 0;
border-bottom: 1px solid #eee;
padding-bottom: 10px;
}
.modal-body {
font-size: 14px;
line-height: 1.6;
color: #333;
}
.modal-body ul {
margin: 10px 0;
padding-left: 20px;
}
.modal-body li {
margin-bottom: 8px;
}
.nav {
margin-bottom: 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
.nav a {
text-decoration: none;
color: #007bff;
font-weight: bold;
}
.container {
display: grid;
grid-template-columns: 3fr 2fr;
gap: 20px;
align-items: start;
height: calc(100vh - 120px);
}
.panel {
background: white;
padding: 15px;
border-radius: 10px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
height: 100%;
overflow: auto;
display: flex;
flex-direction: column;
}
.image-container {
width: 100%;
text-align: center;
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.image-panel-header {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
gap: 12px;
margin-bottom: 4px;
}
.image-panel-header h2 {
margin: 0;
text-align: center;
}
.binary-mask-controls {
display: flex;
align-items: center;
gap: 8px;
justify-self: start;
min-height: 28px;
opacity: 0;
pointer-events: none;
transition: opacity 0.15s ease;
}
.binary-mask-controls.visible {
opacity: 1;
pointer-events: auto;
}
.binary-mask-controls label {
font-size: 11px;
color: #555;
font-weight: 600;
white-space: nowrap;
}
.binary-mask-controls input[type="range"] {
width: 84px;
}
.binary-mask-controls input[type="range"]:disabled {
opacity: 0.55;
cursor: wait;
}
.binary-mask-apply-btn {
border: 1px solid #007bff;
background: #007bff;
color: white;
border-radius: 999px;
padding: 3px 10px;
font-size: 11px;
font-weight: 600;
cursor: pointer;
}
.binary-mask-apply-btn:disabled {
opacity: 0.5;
cursor: default;
}
.binary-mask-value {
min-width: 18px;
text-align: center;
font-size: 11px;
color: #007bff;
font-weight: 700;
}
.binary-mask-status {
min-width: 56px;
font-size: 11px;
color: #666;
}
.image-container img {
max-width: 100%;
max-height: calc(100vh - 220px);
height: auto;
object-fit: contain;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}
.stats-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-bottom: 20px;
}
.stat-card {
background: #f8f9fa;
padding: 10px;
border-radius: 5px;
text-align: center;
}
.stat-value {
font-size: 18px;
font-weight: bold;
color: #007bff;
}
.stat-label {
color: #666;
font-size: 12px;
}
.charts-container {
margin-top: 20px;
}
.chart-wrapper {
height: 200px;
margin-bottom: 20px;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 0;
/* Reset margin */
font-size: 13px;
}
th,
td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #f8f9fa;
position: sticky;
top: 0;
z-index: 1;
}
th.sortable {
cursor: pointer;
user-select: none;
white-space: nowrap;
}
th.sortable:hover {
background-color: #dbe7ff;
}
/* Always-visible sort affordance: a dim arrow on every sortable column,
highlighted (bold, accent colour) on the active sort column. */
th .sort-ind {
font-size: 11px;
margin-left: 3px;
color: #b9c2cc;
font-weight: 700;
}
th .sort-ind.active {
color: #1e5eff;
}
.table-hint {
font-size: 11px;
color: #6c757d;
margin: 0 0 6px 0;
line-height: 1.4;
}
/* Compact the selection table so all columns fit without sideways scroll. */
#dataTable th,
#dataTable td {
padding: 5px 6px;
font-size: 13px;
}
#dataTable th.actions-col,
#dataTable td.actions-col {
padding: 0 2px;
width: 22px;
text-align: center;
}
.row-menu-btn {
border: none;
background: transparent;
color: #adb5bd;
cursor: pointer;
font-size: 16px;
line-height: 1;
padding: 2px 4px;
border-radius: 4px;
}
#dataTable tbody tr:hover .row-menu-btn {
color: #1e5eff;
}
.row-menu-btn:hover {
background: #e9ecef;
color: #1e5eff;
}
.row-menu {
position: fixed;
z-index: 1000;
background: #fff;
border: 1px solid #cfd6dd;
border-radius: 8px;
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.18);
padding: 4px;
min-width: 188px;
}
.row-menu-title {
font-size: 10px;
text-transform: uppercase;
letter-spacing: 0.04em;
color: #8a949e;
padding: 4px 8px 2px;
}
.row-menu button {
display: block;
width: 100%;
text-align: left;
border: none;
background: transparent;
padding: 7px 8px;
font-size: 12px;
border-radius: 5px;
cursor: pointer;
color: #212529;
}
.row-menu button:hover {
background: #eef3ff;
}
.btn {
background-color: #28a745;
color: white;
padding: 12px 20px;
border: none;
border-radius: 5px;
cursor: pointer;
text-decoration: none;
display: inline-block;
margin-top: 10px;
width: 100%;
text-align: center;
box-sizing: border-box;
font-size: 16px;
font-weight: bold;
}
.btn:hover {
background-color: #218838;
}
.btn-primary {
background-color: #007bff;
}
.btn-primary:hover {
background-color: #0056b3;
}
.loading {
text-align: center;
padding: 50px;
font-size: 18px;
color: #666;
}
.hidden {
display: none;
}
.scrollable-table {
flex: 1;
overflow-y: auto;
margin-bottom: 20px;
border: 1px solid #eee;
margin-bottom: 20px;
border: 1px solid #eee;
}
.zoom-btn {
position: absolute;
top: 10px;
right: 10px;
background: rgba(255, 255, 255, 0.9);
border: 1px solid #ccc;
padding: 5px 10px;
cursor: pointer;
z-index: 10;
border-radius: 4px;
font-size: 14px;
display: flex;
align-items: center;
gap: 5px;
}
.image-toggle-btn {
position: absolute;
top: 10px;
right: 100px;
background: rgba(255, 255, 255, 0.9);
border: 1px solid #ccc;
padding: 5px 10px;
cursor: pointer;
z-index: 10;
border-radius: 4px;
font-size: 13px;
}
.zoom-btn.active {
background: #007bff;
color: white;
border-color: #0056b3;
}
.label-toggle-btn {
position: absolute;
top: 10px;
left: 10px;
background: rgba(255, 255, 255, 0.9);
border: 1px solid #ccc;
padding: 5px 10px;
cursor: pointer;
z-index: 10;
border-radius: 4px;
font-size: 13px;
}
.label-toggle-btn.active {
background: #007bff;
color: white;
border-color: #0056b3;
}
.mini-btn {
border: 1px solid #c0392b;
background: #fff;
color: #c0392b;
border-radius: 5px;
padding: 4px 10px;
font-size: 12px;
cursor: pointer;
}
.mini-btn:hover {
background: #c0392b;
color: #fff;
}
.image-wrapper {
position: relative;
overflow: hidden;
width: 100%;
flex: 1;
min-height: 0;
display: flex;
align-items: center;
justify-content: center;
}
#processedImage {
transition: transform 0.1s ease-out;
max-width: 100%;
max-height: calc(100vh - 220px);
height: auto;
object-fit: contain;
display: block;
}
#particleOverlayCanvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 15;
}
/* Scale bar calibration */
.calibration-panel {
background: #fff3cd;
border: 1px solid #ffc107;
border-radius: 5px;
padding: 8px;
margin-bottom: 10px;
font-size: 12px;
}
.calibration-panel h4 {
margin: 0 0 6px 0;
font-size: 13px;
color: #856404;
}
.calibration-panel .cal-option {
margin-bottom: 8px;
padding: 6px;
background: rgba(255,255,255,0.7);
border-radius: 4px;
}
.calibration-panel label {
font-weight: bold;
font-size: 12px;
}
.calibration-panel input[type="number"] {
width: 80px;
padding: 3px 6px;
border: 1px solid #ccc;
border-radius: 3px;
font-size: 12px;
}
.calibration-panel button {
padding: 4px 10px;
font-size: 11px;
border: 1px solid #007bff;
background: #007bff;
color: white;
border-radius: 3px;
cursor: pointer;
}
.calibration-panel button:hover {
background: #0056b3;
}
.calibration-panel button.cal-secondary {
background: #6c757d;
border-color: #6c757d;
}
.calibration-panel button.cal-active {
background: #28a745;
border-color: #28a745;
}
/* Canvas overlay for line drawing */
#scaleCanvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
cursor: crosshair;
z-index: 20;
}
</style>
</head>
<body>
<div class="nav">
<a href="#" id="backLink" onclick="goBack()">← Back to Folder</a>
<h2 id="pageTitle" style="margin: 0; position: absolute; left: 50%; transform: translateX(-50%);">Analysis</h2>
<button onclick="openInstructions()"
style="background: none; border: 1px solid #007bff; color: #007bff; padding: 5px 15px; border-radius: 4px; cursor: pointer;">Instructions</button>
</div>
<!-- Instructions Modal -->
<div id="instrModal" class="modal-overlay" onclick="closeInstructions(event)">
<div class="modal-content" onclick="event.stopPropagation()">
<button class="modal-close" onclick="closeInstructions(event)">×</button>
<div class="modal-section">
<h3>Analysis Instructions</h3>
<div class="modal-body">
<p><strong>1. Review the image:</strong> the centre panel shows detected particles as boxes.
Toggle <em>Show Binary Mask</em> to inspect segmentation, <em>Zoom</em> to look closer, and
<em>Show IDs</em> to label particles (hidden by default so they don't cover small rods).</p>
<p><strong>2. Check the scale:</strong> the calibration source is shown at the top right. If it is
wrong or uncalibrated, click <em>Re-scale</em> and draw a line along the scale bar, or use the
<em>Mask</em> slider to fine-tune how aggressively touching particles are separated.</p>
<p><strong>3. Curate the selection</strong> (right panel <em>Ledger</em>) — exclude clumps, dirt,
or anything that isn't a clean rod:</p>
<ul>
<li><strong>Click a particle on the image</strong> to deselect/reselect it (it flashes).</li>
<li><strong>Sort</strong> any column (e.g. Area ↓) to bring big clumps to the top.</li>
<li><strong>⋮ on a row</strong> bulk-selects/deselects everything above or below it.</li>
<li><strong>Deselect outliers</strong> auto-removes statistical outliers (Tukey 1.5×IQR).</li>
</ul>
<p><strong>4. Update:</strong> press <strong>"Update Particles"</strong> to generate statistics and
histograms from the kept particles.</p>
<p><strong>5. Save & export:</strong></p>
<ul>
<li><strong>Download Excel / PDF:</strong> raw data and a report for this image.</li>
<li><strong>Add to Folder:</strong> confirms these results for the aggregate folder report.</li>
</ul>
</div>
</div>
</div>
</div>
<div id="loading" class="loading">
<div class="spinner"></div>
<p>Processing Image...</p>
</div>
<div id="content" class="container" style="display: none;">
<!-- Column 1: Images (Grouped) -->
<div class="panel">
<div class="image-panel-header">
<div id="binaryMaskControls" class="binary-mask-controls">
<label for="binaryMaskSlider">Mask</label>
<input type="range" id="binaryMaskSlider" min="-6" max="6" step="1" value="0">
<span id="binaryMaskValue" class="binary-mask-value">0</span>
<button id="binaryMaskApplyBtn" class="binary-mask-apply-btn" disabled>Apply</button>
<span id="binaryMaskStatus" class="binary-mask-status"></span>
</div>
<h2 id="imagePanelTitle">Detected Particles</h2>
<div></div>
</div>
<p id="imagePanelHint" style="text-align: center; margin: -4px 0 12px 0; font-size: 13px; color: #666;">
Click on particles to deselect
</p>
<div class="image-container" style="position: relative; flex: 1; overflow: auto;">
<div class="image-wrapper" id="zoomWrapper">
<button class="label-toggle-btn active" onclick="toggleLabels()" id="labelToggleBtn">Show IDs</button>
<button class="image-toggle-btn" onclick="toggleImageView()" id="imageToggleBtn">Show Binary Mask</button>
<button class="zoom-btn" onclick="toggleZoom()" id="zoomToggle">
<span style="font-size: 16px;">🔍</span> Zoom
</button>
<canvas id="particleOverlayCanvas"></canvas>
<canvas id="scaleCanvas" style="display: none;"></canvas>
<img id="processedImage" src="" alt="Detected Particles">
</div>
</div>
</div>
<!-- Column 2: Analysis Selection -->
<div class="panel">
<h2>Selection</h2>
<div
style="background: #e9ecef; padding: 10px; border-radius: 5px; margin-bottom: 10px; text-align: center; font-size: 12px;">
<strong>Calibration:</strong> <span id="calibrationMethod">-</span> <br>
<strong>Pixel Size:</strong> <span id="pixelSize">-</span><span id="pixelSizeUnit"> nm/px</span>
</div>
<div style="margin-bottom: 10px; text-align: center;">
<button id="toggleCalibrationBtn" class="cal-secondary" onclick="toggleCalibrationPanel()"
style="padding: 6px 14px; font-size: 12px;">Re-scale</button>
</div>
<!-- Scale Bar Calibration Panel -->
<div id="calibrationPanel" class="calibration-panel" style="display: none;">
<h4 id="calibrationPanelTitle">Scale Calibration</h4>
<p id="calibrationPanelNote" style="margin: 0 0 8px 0; color: #6b5a00;">You can recalibrate this image at any time.</p>
<div class="cal-option">
<label>Manual</label>
<p style="margin: 4px 0; color: #555;">Draw a line along the scale bar in the image, then enter its length.</p>
<button id="drawLineBtn" onclick="startDrawLine()">Draw Line on Image</button>
<span id="lineStatus" style="margin-left: 6px; color: #888;"></span>
<div style="margin-top: 6px;">
<input type="number" id="scaleNmInput" placeholder="nm" min="1" step="1">
<span style="font-size: 11px;">nm</span>
<button onclick="applyManualScale()" style="margin-left: 4px;">Set Scale</button>
</div>
</div>
</div>
<p class="table-hint">Click a column header to sort ↑/↓. Use <strong>⋮</strong> on a row for bulk select/deselect above & below.</p>
<div style="margin: 0 0 8px 0; display: flex; align-items: center; gap: 8px; flex-wrap: wrap;">
<button type="button" id="deselectOutliersBtn" class="mini-btn" onclick="deselectOutliers()"
title="Deselect particles whose length, width or aspect ratio are statistical outliers (Tukey 1.5×IQR) among the currently selected set">Deselect outliers</button>
<span id="outlierStatus" style="font-size: 11px; color: #6c757d;"></span>
</div>
<div class="scrollable-table">
<table id="dataTable">
<thead>
<tr>
<th><input type="checkbox" id="selectAll" checked onclick="toggleAll(this)" title="Select / deselect all"></th>
<th class="sortable" onclick="sortBy('id')"><span>ID</span><span class="sort-ind" id="ind-id"></span></th>
<th class="sortable" onclick="sortBy('length')"><span id="lengthHeaderLabel">L (nm)</span><span class="sort-ind" id="ind-length"></span></th>
<th class="sortable" onclick="sortBy('width')"><span id="widthHeaderLabel">W (nm)</span><span class="sort-ind" id="ind-width"></span></th>
<th class="sortable" onclick="sortBy('ar')"><span>AR</span><span class="sort-ind" id="ind-ar"></span></th>
<th class="sortable" onclick="sortBy('area')"><span id="areaHeaderLabel">Area (nm²)</span><span class="sort-ind" id="ind-area"></span></th>
<th class="actions-col"></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<!-- Floating per-row bulk-selection menu (positioned in JS) -->
<div id="rowMenu" class="row-menu hidden">
<div class="row-menu-title">Bulk from this row</div>
<button type="button" data-act="sel-above">☑ Select this & above</button>
<button type="button" data-act="desel-above">☐ Deselect this & above</button>
<button type="button" data-act="sel-below">☑ Select this & below</button>
<button type="button" data-act="desel-below">☐ Deselect this & below</button>
</div>
<button id="analyzeBtn" class="btn btn-primary" onclick="calculateAnalysis()">Update Particles ↓</button>
</div>
</div>
<!-- Bottom Section: Analysis Results -->
<div id="analysisResults" class="panel hidden" style="margin-top: 20px;">
<div
style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #eee; padding-bottom: 10px; margin-bottom: 20px;">
<h2 style="margin: 0;">Analysis Statistics</h2>
<button class="btn" style="width: auto; padding: 8px 16px; margin: 0; background-color: #6c757d;"
onclick="scrollToSelection()">↑ Edit Selection</button>
</div>
<div class="stats-grid" style="grid-template-columns: repeat(4, 1fr);"> <!-- 4 Columns for stats now -->
<div class="stat-card">
<div class="stat-value" id="count">-</div>
<div class="stat-label">Count</div>
</div>
<div class="stat-card">
<div class="stat-value" id="meanLength">-</div>
<div class="stat-label" id="meanLengthLabel">Mean L (nm)</div>
</div>
<div class="stat-card">
<div class="stat-value" id="meanWidth">-</div>
<div class="stat-label" id="meanWidthLabel">Mean W (nm)</div>
</div>
<div class="stat-card">
<div class="stat-value" id="meanAR">-</div>
<div class="stat-label">Mean AR</div>
</div>
</div>
<div class="charts-container" style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
<div class="chart-wrapper">
<canvas id="lengthChart"></canvas>
</div>
<div class="chart-wrapper">
<canvas id="widthChart"></canvas>
</div>
</div>
<div style="text-align: center; margin-top: 20px; display: flex; gap: 10px; justify-content: center;">
<a id="downloadExcel" href="#" class="btn" style="width: auto; padding: 12px 40px;">Download Excel
Report</a>
<button onclick="downloadPDF()" class="btn"
style="width: auto; padding: 12px 40px; background-color: #6c757d;">Download PDF Report</button>
<button id="addToFolderBtn" onclick="addToFolderAnalysis()" class="btn"
style="width: auto; padding: 12px 40px; background-color: #28a745; display: none;">Add to Folder
Analysis</button>
</div>
</div>
<script>
// Session isolation (public web build). A random per-browser id scopes
// all storage on the server; auto-appended to every relative API call.
const SESSION_ID = localStorage.getItem('rodsizer_session_id') || (() => {
const id = crypto.randomUUID();
localStorage.setItem('rodsizer_session_id', id);
return id;
})();
const _nativeFetch = window.fetch.bind(window);
window.fetch = (url, opts) => {
if (typeof url === 'string' && url.startsWith('/') && !url.startsWith('//')) {
url += (url.includes('?') ? '&' : '?') + 'session_id=' + SESSION_ID;
}
return _nativeFetch(url, opts);
};
const urlParams = new URLSearchParams(window.location.search);
const imageId = urlParams.get('id');
const folderParam = urlParams.get('folder');
if (folderParam) {
const backLink = document.getElementById('backLink');
backLink.href = `/?folder=${encodeURIComponent(folderParam)}`;
backLink.innerText = `← Back to ${folderParam}`;
// Show Add to Folder button
document.getElementById('addToFolderBtn').style.display = 'inline-block';
}
if (!imageId) {
window.location.href = '/';
}
let lengthChartInstance = null;
let widthChartInstance = null;
let currentData = [];
let currentFilename = "";
let currentIsPlaceholderCalibration = false;
let currentCalibrationInfo = null;
let calibrationPanelOpen = false;
let currentPixelSize = 1;
let currentImageMode = 'processed';
let currentImageUrls = { processed: '', binary: '' };
let currentBinaryMaskTune = 0;
let appliedBinaryMaskTune = 0;
let currentBinaryPreviewUrl = null;
let isBinaryPreviewUpdating = false;
let isApplyingBinaryMask = false;
let pendingBinaryPreviewTune = null;
async function processImage(options = {}) {
try {
const {
manualPixelSize = null,
requestedBarLengthNm = null,
forceReprocess = false,
binaryMaskTune = appliedBinaryMaskTune
} = options;
const resolvedManualPixelSize = manualPixelSize !== null && manualPixelSize !== undefined
? manualPixelSize
: getActiveManualPixelSize();
let url = `/process/${imageId}`;
const params = new URLSearchParams();
params.set('binary_mask_tune', String(binaryMaskTune));
if (resolvedManualPixelSize !== null && resolvedManualPixelSize !== undefined) {
params.set('manual_pixel_size', String(resolvedManualPixelSize));
}
if (requestedBarLengthNm !== null && requestedBarLengthNm !== undefined) {
params.set('requested_bar_length_nm', String(requestedBarLengthNm));
}
if (forceReprocess) {
params.set('force_reprocess', 'true');
}
url += `?${params.toString()}`;
// document.getElementById('loading').style.display = 'block';
// Don't show full screen blocking loading for instant fetch
const response = await fetch(url, { method: 'POST' });
const data = await response.json();
if (response.ok) {
displayResults(data);
} else {
throw new Error(data.detail || 'Server returned error');
}
} catch (error) {
console.error('Error:', error);
alert('Error processing image: ' + error.message);
throw error;
}
}
function displayResults(data) {
document.getElementById('loading').style.display = 'none';
document.getElementById('content').style.display = 'grid';
const keepCurrentImageMode = currentImageMode;
currentData = data.data || [];
currentFilename = data.filename || imageId;
currentIsPlaceholderCalibration = Boolean(data.calibration_info && data.calibration_info.is_placeholder);
currentCalibrationInfo = data.calibration_info || null;
currentPixelSize = data.pixel_size_nm || 1;
currentBinaryMaskTune = Number.isFinite(data.binary_mask_tune) ? Number(data.binary_mask_tune) : currentBinaryMaskTune;
appliedBinaryMaskTune = currentBinaryMaskTune;
currentBinaryPreviewUrl = null;
currentImageUrls = {
processed: data.image_url,
binary: data.binary_url
};
updateBinaryMaskControlsUI();
// Images
// Add timestamp to prevent caching
currentImageMode = keepCurrentImageMode || 'processed';
updateDisplayedImage();
// Download Link
// Download Link
const downloadBtn = document.getElementById('downloadExcel');
// Remove old listeners
downloadBtn.onclick = null;
downloadBtn.removeAttribute('href');
downloadBtn.onclick = downloadFilteredReport;
downloadBtn.style.cursor = 'pointer';
// Calibration
// Calibration
if (currentIsPlaceholderCalibration) {
document.getElementById('pixelSize').textContent = 'N/A';
document.getElementById('pixelSizeUnit').textContent = '';
} else if (data.pixel_size_nm) {
document.getElementById('pixelSize').textContent = data.pixel_size_nm.toFixed(4);
document.getElementById('pixelSizeUnit').textContent = ' nm/px';
} else {
document.getElementById('pixelSize').textContent = '-';
document.getElementById('pixelSizeUnit').textContent = ' nm/px';
}
// Update calibration info
let calibText = data.calibration_info ? data.calibration_info.method : 'Unknown';
if (data.calibration_info && data.calibration_info.description) {
calibText = data.calibration_info.description.replace(/^Calibration:\s*/, '');
} else if (data.calibration_info && data.calibration_info.source_file) {
calibText = `Linked: ${data.calibration_info.source_file}`;
}
document.getElementById('calibrationMethod').textContent = calibText;
updateMeasurementUnits();
// Show calibration panel if needed
showCalibrationPanel(data.calibration_info);
// Table Population — selection is restored from cache inside the
// renderer, the chosen sort order is applied, and particle IDs are
// left untouched (sorting never renumbers rows).
renderSelectionTable();
renderParticleOverlay();
// Automatically Calculate to show graphs immediately
calculateAnalysis(true);
}
function updateDisplayedImage() {
const image = document.getElementById('processedImage');
const timestamp = new Date().getTime();
const isBinary = currentImageMode === 'binary';
const nextBinaryUrl = currentBinaryPreviewUrl || currentImageUrls.binary;
const nextUrl = isBinary ? nextBinaryUrl : currentImageUrls.processed;
const maskControls = document.getElementById('binaryMaskControls');
document.getElementById('imagePanelTitle').textContent = isBinary ? 'Binary Mask' : 'Detected Particles';
document.getElementById('imagePanelHint').textContent = isBinary
? 'Use the small mask slider to separate or reconnect lightly fused regions'
: 'Click on particles to deselect';
document.getElementById('imageToggleBtn').textContent = isBinary ? 'Show Processed Image' : 'Show Binary Mask';
image.alt = isBinary ? 'Binary Mask' : 'Detected Particles';
maskControls.classList.toggle('visible', isBinary);
image.onload = () => {
syncParticleOverlayToImage();
renderParticleOverlay();
};
image.src = `${nextUrl}?t=${timestamp}&session_id=${SESSION_ID}`;
}
function toggleImageView() {
currentImageMode = currentImageMode === 'processed' ? 'binary' : 'processed';
updateDisplayedImage();
}
function getActiveManualPixelSize() {
if (currentCalibrationInfo && currentCalibrationInfo.method === 'manual' && currentPixelSize > 0) {
return currentPixelSize;
}
return null;
}
function updateBinaryMaskControlsUI() {
const slider = document.getElementById('binaryMaskSlider');
const value = document.getElementById('binaryMaskValue');
const applyBtn = document.getElementById('binaryMaskApplyBtn');
slider.value = String(currentBinaryMaskTune);
value.textContent = currentBinaryMaskTune > 0 ? `+${currentBinaryMaskTune}` : String(currentBinaryMaskTune);
applyBtn.disabled = isApplyingBinaryMask || isBinaryPreviewUpdating || currentBinaryMaskTune === appliedBinaryMaskTune;
}
function handleBinaryMaskSliderInput() {
const slider = document.getElementById('binaryMaskSlider');
const nextTune = parseInt(slider.value, 10) || 0;
currentBinaryMaskTune = nextTune;
updateBinaryMaskControlsUI();
if (currentBinaryMaskTune === appliedBinaryMaskTune) {
currentBinaryPreviewUrl = null;
document.getElementById('binaryMaskStatus').textContent = '';
if (currentImageMode === 'binary') {
updateDisplayedImage();
}
}
}
function handleBinaryMaskSliderChange() {
if (currentBinaryMaskTune === appliedBinaryMaskTune) {
return;
}
previewBinaryMask(currentBinaryMaskTune);
}
async function previewBinaryMask(tuneToPreview) {
if (isBinaryPreviewUpdating || isApplyingBinaryMask) {
pendingBinaryPreviewTune = tuneToPreview;
return;
}
const slider = document.getElementById('binaryMaskSlider');
const status = document.getElementById('binaryMaskStatus');
isBinaryPreviewUpdating = true;
slider.disabled = true;
status.textContent = 'Previewing...';
updateBinaryMaskControlsUI();
try {
const params = new URLSearchParams();
params.set('binary_mask_tune', String(tuneToPreview));
const activeManualPixelSize = getActiveManualPixelSize();
if (activeManualPixelSize !== null && activeManualPixelSize !== undefined) {
params.set('manual_pixel_size', String(activeManualPixelSize));
}
const response = await fetch(`/process/${imageId}/binary_preview?${params.toString()}`, { method: 'POST' });
const data = await response.json();
if (!response.ok) {
throw new Error(data.detail || 'Failed to preview binary mask');
}
currentBinaryPreviewUrl = data.binary_preview_url;
currentImageMode = 'binary';
updateDisplayedImage();
status.textContent = 'Preview ready';
} catch (error) {
console.error('Binary preview error:', error);
status.textContent = '';
alert('Error previewing binary mask: ' + error.message);
} finally {
isBinaryPreviewUpdating = false;
slider.disabled = false;
updateBinaryMaskControlsUI();
const nextTune = pendingBinaryPreviewTune;
pendingBinaryPreviewTune = null;
if (nextTune !== null && nextTune !== tuneToPreview) {
previewBinaryMask(nextTune);
}
}
}
async function applyBinaryMaskTune() {
if (isApplyingBinaryMask || currentBinaryMaskTune === appliedBinaryMaskTune) {
return;
}
const slider = document.getElementById('binaryMaskSlider');
const applyBtn = document.getElementById('binaryMaskApplyBtn');
const status = document.getElementById('binaryMaskStatus');
isApplyingBinaryMask = true;
slider.disabled = true;
applyBtn.disabled = true;
status.textContent = 'Applying...';
try {
await processImage({ binaryMaskTune: currentBinaryMaskTune, forceReprocess: true });
currentImageMode = 'binary';
updateDisplayedImage();
status.textContent = '';
} catch (_) {
status.textContent = '';
} finally {
isApplyingBinaryMask = false;
slider.disabled = false;
updateBinaryMaskControlsUI();
}
}
function updateMeasurementUnits() {
const unit = currentIsPlaceholderCalibration ? 'px' : 'nm';
document.getElementById('lengthHeaderLabel').textContent = `L (${unit})`;
document.getElementById('widthHeaderLabel').textContent = `W (${unit})`;
const areaLabel = document.getElementById('areaHeaderLabel');
if (areaLabel) areaLabel.textContent = currentIsPlaceholderCalibration ? 'Area (px²)' : 'Area (nm²)';
document.getElementById('meanLengthLabel').textContent = `Mean L (${unit})`;
document.getElementById('meanWidthLabel').textContent = `Mean W (${unit})`;
}
function toggleCalibrationPanel() {
calibrationPanelOpen = !calibrationPanelOpen;
showCalibrationPanel(currentCalibrationInfo);
}
// --- Selection table: sorting & rendering ------------------------------
// currentSort.key === null keeps the original (backend) order. Sorting
// only reorders the visible rows; each checkbox keeps data-index pointing
// at its currentData entry, so IDs and all index-based logic are intact.
let currentSort = { key: null, dir: 'desc' };
function rodAreaValue(rod) {
const px2 = Number(rod.area_px) || 0;
if (currentPixelSize > 0 && !currentIsPlaceholderCalibration) {
return px2 * currentPixelSize * currentPixelSize; // nm^2
}
return px2; // px^2 (uncalibrated)
}
function formatArea(v) {
// Keep the column narrow: exact for normal particles, compact (k/M)
// for large clumps whose nm² runs into the millions.
if (!isFinite(v)) return '-';
if (v >= 1e6) return (v / 1e6).toFixed(1) + 'M';
if (v >= 1e4) return (v / 1e3).toFixed(0) + 'k';
return Math.round(v).toLocaleString();
}
function captureExcludedIds() {
// Prefer the live checkbox state (so re-sorting preserves the current
// selection); fall back to the cached set on first render.
const checkboxes = document.querySelectorAll('.rod-checkbox');
if (checkboxes.length) {
const excluded = [];
checkboxes.forEach(cb => {
const idx = parseInt(cb.dataset.index, 10);
if (!cb.checked && currentData[idx]) excluded.push(currentData[idx].id);
});
return excluded;
}
return JSON.parse(localStorage.getItem('excluded_' + imageId) || '[]');
}
function sortKeyValue(rod) {
switch (currentSort.key) {
case 'area': return Number(rod.area_px) || 0;
case 'length': return Number(rod.length_nm) || 0;
case 'width': return Number(rod.width_nm) || 0;
case 'ar': return Number(rod.aspect_ratio) || 0;
case 'id': return Number(rod.id) || 0;
default: return 0;
}
}
function renderSelectionTable() {
const tbody = document.querySelector('#dataTable tbody');
if (!tbody) return;
const excludedSet = new Set(captureExcludedIds());
// Pair each rod with its ORIGINAL index, then sort the pairs only.
const order = currentData.map((rod, index) => ({ rod, index }));
if (currentSort.key) {
const dir = currentSort.dir === 'asc' ? 1 : -1;
order.sort((a, b) => {
const va = sortKeyValue(a.rod);
const vb = sortKeyValue(b.rod);
if (va < vb) return -dir;
if (va > vb) return dir;
return a.index - b.index; // stable: fall back to original order
});
}
tbody.innerHTML = '';
order.forEach(({ rod, index }) => {
const tr = document.createElement('tr');
const cbTd = document.createElement('td');
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.className = 'rod-checkbox';
cb.dataset.index = String(index); // original index — never reassigned
cb.checked = !excludedSet.has(rod.id);
cb.addEventListener('change', () => { syncSelectAllState(); triggerParticleFlash(index); });
cbTd.appendChild(cb);
tr.appendChild(cbTd);
[
String(rod.id ?? ''),
Number(rod.length_nm).toFixed(1),
Number(rod.width_nm).toFixed(1),
Number(rod.aspect_ratio).toFixed(1),
formatArea(rodAreaValue(rod)),
].forEach(val => {
const td = document.createElement('td');
td.textContent = val;
tr.appendChild(td);
});
const actTd = document.createElement('td');
actTd.className = 'actions-col';
const menuBtn = document.createElement('button');
menuBtn.type = 'button';
menuBtn.className = 'row-menu-btn';
menuBtn.textContent = '⋮';
menuBtn.title = 'Bulk select/deselect from this row';
menuBtn.dataset.index = String(index);
menuBtn.addEventListener('click', (e) => openRowMenu(e, index));
actTd.appendChild(menuBtn);
tr.appendChild(actTd);
tbody.appendChild(tr);
});
updateSortIndicators();
syncSelectAllState();
}
function sortBy(key) {
if (currentSort.key === key) {
currentSort.dir = currentSort.dir === 'desc' ? 'asc' : 'desc';
} else {
currentSort.key = key;
currentSort.dir = (key === 'id') ? 'asc' : 'desc';
}
renderSelectionTable();
}
function updateSortIndicators() {
['id', 'length', 'width', 'ar', 'area'].forEach(k => {
const el = document.getElementById('ind-' + k);
if (!el) return;
if (currentSort.key === k) {
el.textContent = currentSort.dir === 'asc' ? '▲' : '▼';
el.classList.add('active');
} else {
el.textContent = '↕'; // dim hint that the column is sortable
el.classList.remove('active');
}
});
}
function syncSelectAllState() {
const selectAll = document.getElementById('selectAll');
const all = document.querySelectorAll('.rod-checkbox');
if (!selectAll || !all.length) return;
selectAll.checked = Array.from(all).every(cb => cb.checked);
}
// --- Bulk selection (above / below a row, in current display order) ----
// "above"/"below" follow the visible (sorted) order and include the anchor
// row itself, so e.g. sort by Area ↓ then "Deselect this & above" clears a
// whole block of clumps in one click. IDs are never touched.
function applyBulkSelection(anchorIndex, direction, checked) {
const rows = Array.from(document.querySelectorAll('#dataTable tbody tr'));
const anchorPos = rows.findIndex(tr => {
const cb = tr.querySelector('.rod-checkbox');
return cb && cb.dataset.index === String(anchorIndex);
});
if (anchorPos < 0) return;
rows.forEach((tr, pos) => {
const inRange = direction === 'above' ? pos <= anchorPos : pos >= anchorPos;
if (!inRange) return;
const cb = tr.querySelector('.rod-checkbox');
if (cb) cb.checked = checked;
});
renderParticleOverlay();
syncSelectAllState();
}
let rowMenuAnchorIndex = null;
function openRowMenu(event, index) {
event.stopPropagation();
const menu = document.getElementById('rowMenu');
if (!menu) return;
rowMenuAnchorIndex = index;
menu.classList.remove('hidden');
const btnRect = event.currentTarget.getBoundingClientRect();
const mw = menu.offsetWidth || 190;
const mh = menu.offsetHeight || 140;
let left = btnRect.right - mw;
let top = btnRect.bottom + 4;
if (top + mh > window.innerHeight - 8) top = btnRect.top - mh - 4; // flip up
menu.style.left = `${Math.max(8, left)}px`;
menu.style.top = `${Math.max(8, top)}px`;
}
function closeRowMenu() {
const menu = document.getElementById('rowMenu');
if (menu) menu.classList.add('hidden');
rowMenuAnchorIndex = null;
}
(function initRowMenu() {
const menu = document.getElementById('rowMenu');
if (!menu) return;
menu.querySelectorAll('button[data-act]').forEach(btn => {
btn.addEventListener('click', () => {
if (rowMenuAnchorIndex === null) return;
const act = btn.dataset.act; // e.g. "desel-above"
const checked = act.startsWith('sel-');
const direction = act.endsWith('above') ? 'above' : 'below';
applyBulkSelection(rowMenuAnchorIndex, direction, checked);
closeRowMenu();
});
});
document.addEventListener('click', (e) => {
if (!menu.classList.contains('hidden') &&
!menu.contains(e.target) &&
!e.target.classList.contains('row-menu-btn')) {
closeRowMenu();
}
});
window.addEventListener('resize', closeRowMenu);
const scrollBox = document.querySelector('.scrollable-table');
if (scrollBox) scrollBox.addEventListener('scroll', closeRowMenu);
})();
function toggleAll(source) {
const checkboxes = document.querySelectorAll('.rod-checkbox');
for (let i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = source.checked;
}
renderParticleOverlay();
syncSelectAllState();
}
// --- Auto-deselect statistical outliers (Tukey 1.5 x IQR) ------------
function _quantile(sorted, q) {
if (sorted.length === 0) return NaN;
const pos = (sorted.length - 1) * q;
const base = Math.floor(pos);
const rest = pos - base;
return sorted[base + 1] !== undefined
? sorted[base] + rest * (sorted[base + 1] - sorted[base])
: sorted[base];
}
function setOutlierStatus(msg) {
const el = document.getElementById('outlierStatus');
if (el) el.textContent = msg;
}
function deselectOutliers() {
// Work on the currently-selected particles so it refines an existing
// selection (and respects prior manual exclusions).
const selected = Array.from(document.querySelectorAll('.rod-checkbox'))
.filter(cb => cb.checked)
.map(cb => ({ cb, rod: currentData[parseInt(cb.dataset.index, 10)] }))
.filter(x => x.rod);
if (selected.length < 8) {
setOutlierStatus('Need ≥ 8 selected particles to detect outliers.');
return;
}
// Tukey fences per metric. A particle is an outlier if length, width
// OR aspect ratio falls outside its fence.
const metrics = ['length_nm', 'width_nm', 'aspect_ratio'];
const fences = {};
metrics.forEach(key => {
const vals = selected.map(x => Number(x.rod[key])).filter(Number.isFinite).sort((a, b) => a - b);
const q1 = _quantile(vals, 0.25), q3 = _quantile(vals, 0.75), iqr = q3 - q1;
fences[key] = [q1 - 1.5 * iqr, q3 + 1.5 * iqr];
});
let removed = 0;
selected.forEach(({ cb, rod }) => {
const isOutlier = metrics.some(key => {
const v = Number(rod[key]);
const [lo, hi] = fences[key];
return Number.isFinite(v) && (v < lo || v > hi);
});
if (isOutlier) { cb.checked = false; removed++; }
});
renderParticleOverlay();
syncSelectAllState();
setOutlierStatus(removed
? `Deselected ${removed} outlier${removed > 1 ? 's' : ''} (L/W/AR, 1.5×IQR).`
: 'No statistical outliers found.');
}
function scrollToSelection() {
document.getElementById('content').scrollIntoView({ behavior: 'smooth' });
}
function calculateAnalysis(isAuto = false) {
const checkboxes = document.querySelectorAll('.rod-checkbox');
const includedData = [];
const excludedIds = [];
checkboxes.forEach(cb => {
const index = parseInt(cb.getAttribute('data-index'));
if (cb.checked) {
includedData.push(currentData[index]);
} else {
if (currentData[index]) {
excludedIds.push(currentData[index].id);
}
}
});
// SCA-CACHING: Save excluded IDs to LocalStorage
localStorage.setItem('excluded_' + imageId, JSON.stringify(excludedIds));
// Show Results Section
document.getElementById('analysisResults').classList.remove('hidden');
// Calculate stats
const count = includedData.length;
if (count > 0) {
const lengths = includedData.map(d => d.length_nm);
const widths = includedData.map(d => d.width_nm);
const ars = includedData.map(d => d.aspect_ratio);
const meanLength = lengths.reduce((a, b) => a + b, 0) / count;
const meanWidth = widths.reduce((a, b) => a + b, 0) / count;
const meanAR = ars.reduce((a, b) => a + b, 0) / count;
// Std Dev
const stdLength = Math.sqrt(lengths.map(x => Math.pow(x - meanLength, 2)).reduce((a, b) => a + b, 0) / count);
const stdWidth = Math.sqrt(widths.map(x => Math.pow(x - meanWidth, 2)).reduce((a, b) => a + b, 0) / count);
const stdAR = Math.sqrt(ars.map(x => Math.pow(x - meanAR, 2)).reduce((a, b) => a + b, 0) / count);
document.getElementById('count').textContent = count;
document.getElementById('meanLength').textContent = meanLength.toFixed(1) + ' ± ' + stdLength.toFixed(1);
document.getElementById('meanWidth').textContent = meanWidth.toFixed(1) + ' ± ' + stdWidth.toFixed(1);
document.getElementById('meanAR').textContent = meanAR.toFixed(1) + ' ± ' + stdAR.toFixed(1);
// Update Charts
const unit = currentIsPlaceholderCalibration ? 'px' : 'nm';
lengthChartInstance = createHistogram('lengthChart', `Length Distribution (${unit})`, lengths, lengthChartInstance);
widthChartInstance = createHistogram('widthChart', `Width Distribution (${unit})`, widths, widthChartInstance);
} else {
document.getElementById('count').textContent = "0";
document.getElementById('meanLength').textContent = "-";
document.getElementById('meanWidth').textContent = "-";
document.getElementById('meanAR').textContent = "-";
if (lengthChartInstance) lengthChartInstance.destroy();
if (widthChartInstance) widthChartInstance.destroy();
}
// Scroll to bottom only if manual click
if (!isAuto) {
document.getElementById('analysisResults').scrollIntoView({ behavior: 'smooth' });
}
}
function createHistogram(canvasId, label, data, existingChart) {
if (existingChart) {
existingChart.destroy();
}
const ctx = document.getElementById(canvasId).getContext('2d');
if (!data || data.length === 0) return null;
// Denser binning - use Sturges' rule or at least 20 bins
const binCount = Math.max(20, Math.ceil(1 + 3.322 * Math.log10(data.length)));
const min = Math.min(...data);
const max = Math.max(...data);
let step = (max - min) / binCount;
if (step === 0) step = 1;
const bins = new Array(binCount).fill(0);
const binCenters = [];
for (let i = 0; i < binCount; i++) {
binCenters.push((min + (i + 0.5) * step).toFixed(1));
}
data.forEach(val => {
const binIndex = Math.min(Math.floor((val - min) / step), binCount - 1);
bins[binIndex]++;
});
// Compute Gaussian fit
const mean = data.reduce((a, b) => a + b, 0) / data.length;
const variance = data.reduce((a, b) => a + (b - mean) ** 2, 0) / data.length;
const stdDev = Math.sqrt(variance);
const amplitude = Math.max(...bins);
const gaussianY = binCenters.map(x => {
const xVal = parseFloat(x);
if (stdDev === 0) return 0;
return amplitude * Math.exp(-0.5 * ((xVal - mean) / stdDev) ** 2);
});
return new Chart(ctx, {
type: 'bar',
data: {
labels: binCenters,
datasets: [{
label: label,
data: bins,
backgroundColor: 'rgba(54, 162, 235, 0.5)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1,
barPercentage: 1.0,
categoryPercentage: 1.0,
order: 2
}, {
label: 'Gaussian Fit',
data: gaussianY,
type: 'line',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 2,
pointRadius: 0,
fill: false,
tension: 0.4,
order: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
x: {
ticks: {
maxTicksLimit: 10,
maxRotation: 45
}
},
y: { beginAtZero: true }
},
plugins: {
legend: {
labels: { font: { size: 11 } }
}
}
}
});
}
// --- Zoom Logic ---
let isZoomActive = false;
const processedImage = document.getElementById('processedImage');
const zoomWrapper = document.getElementById('zoomWrapper');
const zoomToggle = document.getElementById('zoomToggle');
const particleOverlayCanvas = document.getElementById('particleOverlayCanvas');
const particleOverlayCtx = particleOverlayCanvas.getContext('2d');
function syncParticleOverlayToImage() {
const img = document.getElementById('processedImage');
if (!img || !img.naturalWidth || !img.naturalHeight) return false;
particleOverlayCanvas.width = img.naturalWidth;
particleOverlayCanvas.height = img.naturalHeight;
particleOverlayCanvas.style.width = `${img.clientWidth}px`;
particleOverlayCanvas.style.height = `${img.clientHeight}px`;
particleOverlayCanvas.style.left = `${img.offsetLeft}px`;
particleOverlayCanvas.style.top = `${img.offsetTop}px`;
return true;
}
function getCheckboxStateByIndex(index) {
const checkbox = document.querySelector(`.rod-checkbox[data-index="${index}"]`);
return checkbox ? checkbox.checked : true;
}
function getParticleBoxPoints(rod) {
const widthPx = rod.width_nm / currentPixelSize;
const lengthPx = rod.length_nm / currentPixelSize;
const angleRad = (rod.orientation_deg || 0) * Math.PI / 180;
const cosA = Math.cos(angleRad);
const sinA = Math.sin(angleRad);
const halfW = widthPx / 2;
const halfL = lengthPx / 2;
const localCorners = [
{ x: -halfW, y: -halfL },
{ x: halfW, y: -halfL },
{ x: halfW, y: halfL },
{ x: -halfW, y: halfL }
];
return localCorners.map(pt => ({
x: rod.centroid_x + pt.x * cosA - pt.y * sinA,
y: rod.centroid_y + pt.x * sinA + pt.y * cosA
}));
}
// Show/hide the ID numbers drawn over the image (they can obscure small
// particles). Hidden by default; drawn on the canvas overlay so the
// toggle is instant.
let showLabels = false;
function toggleLabels() {
showLabels = !showLabels;
const btn = document.getElementById('labelToggleBtn');
btn.textContent = showLabels ? 'Hide IDs' : 'Show IDs';
btn.classList.toggle('active', !showLabels);
renderParticleOverlay();
}
// Two-blink flash on toggle, so a just-(de)selected box is easy to spot.
const particleFlashes = new Map(); // currentData index -> start time (ms)
const FLASH_DURATION_MS = 760;
let flashAnimRunning = false;
function triggerParticleFlash(index) {
particleFlashes.set(index, performance.now());
if (!flashAnimRunning) {
flashAnimRunning = true;
requestAnimationFrame(flashTick);
}
}
function flashTick() {
const now = performance.now();
for (const [idx, start] of particleFlashes) {
if (now - start >= FLASH_DURATION_MS) particleFlashes.delete(idx);
}
renderParticleOverlay();
if (particleFlashes.size > 0) {
requestAnimationFrame(flashTick);
} else {
flashAnimRunning = false;
renderParticleOverlay(); // final clean frame
}
}
function pathParticle(ctx, corners) {
ctx.beginPath();
ctx.moveTo(corners[0].x, corners[0].y);
for (let i = 1; i < corners.length; i++) ctx.lineTo(corners[i].x, corners[i].y);
ctx.closePath();
}
function renderParticleOverlay() {
if (!syncParticleOverlayToImage()) return;
const ctx = particleOverlayCtx;
ctx.clearRect(0, 0, particleOverlayCanvas.width, particleOverlayCanvas.height);
if (!currentData || currentData.length === 0) return;
// The canvas is at full image resolution but shown scaled down, so
// size strokes relative to that ratio to keep them visible.
const img = document.getElementById('processedImage');
const scale = (img && img.clientWidth) ? (particleOverlayCanvas.width / img.clientWidth) : 1;
const baseLine = Math.max(1, scale * 0.7); // thin outlines, vivid colour
const now = performance.now();
currentData.forEach((rod, index) => {
const isSelected = getCheckboxStateByIndex(index);
const corners = getParticleBoxPoints(rod);
pathParticle(ctx, corners);
// Outline only (no interior fill). Solid for kept particles,
// dashed for excluded ones.
ctx.setLineDash(isSelected ? [] : [scale * 6, scale * 5]);
ctx.lineWidth = baseLine;
ctx.strokeStyle = isSelected ? '#0a40ff' : '#ff8c00';
ctx.stroke();
ctx.setLineDash([]);
// Flash highlight (two blinks) right after a toggle — a pulsing
// bright outline with a glow, no interior fill.
const start = particleFlashes.get(index);
if (start !== undefined) {
const t = (now - start) / FLASH_DURATION_MS; // 0..1
const intensity = Math.abs(Math.sin(t * Math.PI * 2)); // two humps
ctx.save();
pathParticle(ctx, corners);
ctx.shadowColor = 'rgba(255,255,255,0.95)';
ctx.shadowBlur = scale * 8 * intensity;
ctx.lineWidth = baseLine + scale * 3.5 * intensity;
ctx.strokeStyle = `rgba(255, 255, 255, ${0.55 + 0.45 * intensity})`;
ctx.stroke();
// Coloured inner stroke so the blink keeps its select/exclude hue.
ctx.shadowBlur = 0;
ctx.lineWidth = baseLine + scale * 1.2 * intensity;
ctx.strokeStyle = isSelected
? `rgba(10, 64, 255, ${0.5 + 0.5 * intensity})`
: `rgba(255, 140, 0, ${0.5 + 0.5 * intensity})`;
ctx.stroke();
ctx.restore();
}
});
// ID numbers, drawn last (on top of all boxes) and only when enabled.
// Outlined white text instead of a filled pill so they obscure the
// particle underneath as little as possible.
if (showLabels) {
const fontPx = Math.max(13 * scale, 11);
ctx.font = `bold ${fontPx}px sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.lineWidth = Math.max(1, scale * 0.9);
ctx.lineJoin = 'round';
currentData.forEach((rod) => {
const label = String(rod.id ?? '');
if (!label) return;
const x = rod.centroid_x, y = rod.centroid_y;
ctx.strokeStyle = 'rgba(0, 0, 0, 0.85)';
ctx.strokeText(label, x, y);
ctx.fillStyle = '#ffffff';
ctx.fillText(label, x, y);
});
ctx.textAlign = 'start';
ctx.textBaseline = 'alphabetic';
}
}
function setImageTransform(origin, scale) {
const targetElements = [processedImage, particleOverlayCanvas, scaleCanvas];
targetElements.forEach(el => {
el.style.transformOrigin = origin;
el.style.transform = scale;
});
}
function toggleZoom() {
isZoomActive = !isZoomActive;
if (isZoomActive) {
zoomToggle.classList.add('active');
zoomWrapper.style.cursor = 'zoom-in';
} else {
zoomToggle.classList.remove('active');
zoomWrapper.style.cursor = 'default';
// Reset
setImageTransform('50% 50%', 'scale(1)');
}
}
zoomWrapper.addEventListener('mousemove', function (e) {
if (!isZoomActive) return;
const rect = zoomWrapper.getBoundingClientRect();
const x = e.clientX - rect.left;
const y = e.clientY - rect.top;
// Calculate percentage
const xPercent = (x / rect.width) * 100;
const yPercent = (y / rect.height) * 100;
setImageTransform(`${xPercent}% ${yPercent}%`, 'scale(2.5)');
});
zoomWrapper.addEventListener('mouseleave', function () {
if (!isZoomActive) return;
setImageTransform('50% 50%', 'scale(1)');
});
async function downloadFilteredReport() {
const checkboxes = document.querySelectorAll('.rod-checkbox');
const selectedIds = [];
checkboxes.forEach(cb => {
if (cb.checked) {
// ID is in column 2 (index 1), but we have full data in currentData by index
const index = parseInt(cb.getAttribute('data-index'));
if (currentData[index]) {
selectedIds.push(currentData[index].id);
}
}
});
if (selectedIds.length === 0) {
alert("Please select at least one particle to export.");
return;
}
try {
downloadBtn = document.getElementById('downloadExcel');
const originalText = downloadBtn.innerText;
downloadBtn.innerText = "Generating Report...";
const response = await fetch('/export', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
image_id: imageId,
selected_ids: selectedIds
})
});
if (response.ok) {
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
// Use filename from response header if possible, or fallback to currentFilename
// But simpler: just use our known filename format
a.download = `${currentFilename || imageId}_detected.xlsx`;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
} else {
const err = await response.json();
alert("Export failed: " + (err.detail || "Unknown error"));
}
downloadBtn.innerText = originalText;
} catch (e) {
console.error(e);
alert("Export failed");
document.getElementById('downloadExcel').innerText = "Download Excel Report";
}
}
async function saveSelectionForFolder() {
if (!currentFolder) {
alert("No folder context available.");
return;
}
const checkboxes = document.querySelectorAll('.rod-checkbox');
const selectedIds = [];
checkboxes.forEach(cb => {
if (cb.checked) {
selectedIds.push(parseInt(cb.getAttribute('data-index'))); // Index maps to original data order? No, ID is safer
// Wait, data-index is index in currentData. Check logic.
// currentData[index].id is the ID.
}
});
// Re-map to actual IDs
const idsToSave = [];
checkboxes.forEach(cb => {
if (cb.checked) {
const idx = cb.getAttribute('data-index');
idsToSave.push(currentData[idx].id);
}
});
try {
const response = await fetch(`/folders/${encodeURIComponent(currentFolder)}/save_selection`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
image_id: imageId,
selected_ids: idsToSave
})
});
if (response.ok) {
alert("Selection saved for Folder Analysis!");
} else {
const err = await response.json();
alert("Error saving: " + err.detail);
}
} catch (e) {
console.error(e);
alert("Failed to save selection.");
}
}
// --- Instructions Modal ---
function openInstructions() {
document.getElementById('instrModal').style.display = 'flex';
}
function closeInstructions(event) {
if (event) event.stopPropagation();
document.getElementById('instrModal').style.display = 'none';
}
async function addToFolderAnalysis() {
if (!folderParam) return;
const checkboxes = document.querySelectorAll('.rod-checkbox');
const selectedIds = [];
checkboxes.forEach(cb => {
if (cb.checked) {
const index = parseInt(cb.getAttribute('data-index'));
if (currentData[index]) {
selectedIds.push(currentData[index].id);
}
}
});
if (selectedIds.length === 0) {
alert("Please select at least one particle.");
return;
}
try {
const btn = document.getElementById('addToFolderBtn');
const originalText = btn.innerText;
btn.innerText = "Saving...";
btn.disabled = true;
const response = await fetch(`/folders/${encodeURIComponent(folderParam)}/save_selection`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
image_id: imageId,
selected_ids: selectedIds
})
});
if (response.ok) {
const res = await response.json();
alert(`Successfully added ${res.count} particles from this image to folder analysis.`);
} else {
const err = await response.json();
alert("Error: " + (err.detail || "Server Error"));
}
btn.innerText = "Add to Folder Analysis";
btn.disabled = false;
} catch (e) {
console.error(e);
alert("Failed to save selection.");
document.getElementById('addToFolderBtn').innerText = "Add to Folder Analysis";
}
}
async function downloadPDF() {
const element = document.getElementById('analysisResults');
// Create a temporary container for PDF generation
const pdfContainer = document.createElement('div');
pdfContainer.style.width = '100%';
pdfContainer.style.background = 'white';
pdfContainer.style.padding = '20px';
// Add Header Info
const title = document.createElement('h2');
title.innerText = `Analysis Report: ${currentFilename}`;
title.style.textAlign = 'center';
title.style.marginBottom = '20px';
pdfContainer.appendChild(title);
// Add the currently displayed image (resized for PDF)
const imgContainer = document.createElement('div');
imgContainer.style.display = 'flex';
imgContainer.style.justifyContent = 'center';
imgContainer.style.marginBottom = '20px';
imgContainer.style.height = '350px';
// Composite the base image with the live overlay (boxes, IDs and the
// current selection state) so the report matches what is on screen.
const img2 = document.createElement('img');
try {
const srcImg = document.getElementById('processedImage');
renderParticleOverlay();
const composite = document.createElement('canvas');
composite.width = srcImg.naturalWidth || particleOverlayCanvas.width;
composite.height = srcImg.naturalHeight || particleOverlayCanvas.height;
const cctx = composite.getContext('2d');
cctx.drawImage(srcImg, 0, 0, composite.width, composite.height);
cctx.drawImage(particleOverlayCanvas, 0, 0, composite.width, composite.height);
img2.src = composite.toDataURL('image/jpeg', 0.9);
} catch (e) {
console.error('Overlay composite failed, using plain image:', e);
img2.src = document.getElementById('processedImage').src;
}
img2.style.maxHeight = '100%';
img2.style.maxWidth = '80%';
img2.style.objectFit = 'contain';
img2.style.transform = 'none';
imgContainer.appendChild(img2);
pdfContainer.appendChild(imgContainer);
// Clone Results Section
const clonedContent = element.cloneNode(true);
// Remove buttons from PDF
const buttons = clonedContent.querySelectorAll('button, a.btn');
buttons.forEach(btn => btn.remove());
// Replace Chart Canvases with Images (Crucial for PDF)
const originalCanvases = element.querySelectorAll('canvas');
const clonedCanvases = clonedContent.querySelectorAll('canvas');
originalCanvases.forEach((origCanvas, index) => {
if (!clonedCanvases[index]) return;
try {
const imgData = origCanvas.toDataURL('image/png');
const img = document.createElement('img');
img.src = imgData;
img.style.width = '100%';
img.style.maxHeight = '200px';
img.style.objectFit = 'contain';
img.style.display = 'block';
const clonedCanvas = clonedCanvases[index];
clonedCanvas.parentNode.replaceChild(img, clonedCanvas);
} catch (e) {
console.error("Chart capture error:", e);
}
});
pdfContainer.appendChild(clonedContent);
const opt = {
margin: 0.5,
filename: `${currentFilename}_report.pdf`,
image: { type: 'jpeg', quality: 0.98 },
html2canvas: { scale: 2, useCORS: true },
jsPDF: { unit: 'in', format: 'letter', orientation: 'landscape' }
};
html2pdf().set(opt).from(pdfContainer).save();
}
// --- Click on particle to toggle checkbox ---
document.getElementById('processedImage').addEventListener('click', function(e) {
if (isZoomActive || isDrawingLine) return;
if (!currentData || currentData.length === 0) return;
const img = this;
const rect = img.getBoundingClientRect();
const scaleX = img.naturalWidth / rect.width;
const scaleY = img.naturalHeight / rect.height;
const clickX = (e.clientX - rect.left) * scaleX;
const clickY = (e.clientY - rect.top) * scaleY;
// Primary hit test: is the click INSIDE a particle's box? Among any
// boxes that contain the point, pick the one whose centre is nearest.
// This makes "click inside the box" reliable regardless of box size.
let targetIdx = -1;
let bestDist = Infinity;
currentData.forEach((rod, idx) => {
if (pointInParticle(clickX, clickY, getParticleBoxPoints(rod))) {
const d = Math.hypot(rod.centroid_x - clickX, rod.centroid_y - clickY);
if (d < bestDist) { bestDist = d; targetIdx = idx; }
}
});
// Fallback: nearest centroid within a small tolerance for near-misses.
if (targetIdx < 0) {
const tol = Math.max(40, img.naturalWidth * 0.015);
let minDist = Infinity;
currentData.forEach((rod, idx) => {
const d = Math.hypot(rod.centroid_x - clickX, rod.centroid_y - clickY);
if (d < minDist) { minDist = d; targetIdx = (d <= tol) ? idx : targetIdx; }
});
}
if (targetIdx >= 0) {
// Look up by data-index (not DOM position) so this still hits the
// right particle when the table is sorted.
const checkbox = document.querySelector(`.rod-checkbox[data-index="${targetIdx}"]`);
if (checkbox) {
checkbox.checked = !checkbox.checked;
syncSelectAllState();
triggerParticleFlash(targetIdx); // two-blink flash on the box
// Briefly flash the matching table row WITHOUT scrolling to it,
// so deselecting several while zoomed in doesn't jump the page.
const row = checkbox.closest('tr');
if (row) {
row.style.background = checkbox.checked ? '#d4edda' : '#f8d7da';
setTimeout(() => { row.style.background = ''; }, 600);
}
}
}
});
// Ray-casting point-in-polygon for the 4-corner rotated box.
function pointInParticle(x, y, pts) {
let inside = false;
for (let i = 0, j = pts.length - 1; i < pts.length; j = i++) {
const xi = pts[i].x, yi = pts[i].y, xj = pts[j].x, yj = pts[j].y;
if (((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)) {
inside = !inside;
}
}
return inside;
}
// --- Scale Bar Calibration ---
let isDrawingLine = false;
let lineStart = null;
let lineEnd = null;
let drawnLinePx = 0;
const scaleCanvas = document.getElementById('scaleCanvas');
const scaleCtx = scaleCanvas.getContext('2d');
function syncScaleCanvasToImage() {
const img = document.getElementById('processedImage');
if (!img || !img.naturalWidth || !img.naturalHeight) return false;
scaleCanvas.width = img.naturalWidth;
scaleCanvas.height = img.naturalHeight;
scaleCanvas.style.width = `${img.clientWidth}px`;
scaleCanvas.style.height = `${img.clientHeight}px`;
scaleCanvas.style.left = `${img.offsetLeft}px`;
scaleCanvas.style.top = `${img.offsetTop}px`;
return true;
}
function showCalibrationPanel(calibInfo) {
const method = calibInfo ? calibInfo.method : 'default';
const needsCalibration = method === 'default' || method === 'uncalibrated' || (calibInfo && calibInfo.is_placeholder);
const panel = document.getElementById('calibrationPanel');
const toggleBtn = document.getElementById('toggleCalibrationBtn');
const title = document.getElementById('calibrationPanelTitle');
const note = document.getElementById('calibrationPanelNote');
if (needsCalibration) {
calibrationPanelOpen = true;
title.textContent = 'Scale Bar Calibration Required';
note.textContent = 'No reliable scale was found. Please set the scale manually.';
toggleBtn.textContent = 'Hide calibration tools';
} else {
title.textContent = 'Scale Calibration';
note.textContent = 'Current calibration looks usable. You can re-scale this image at any time if needed.';
toggleBtn.textContent = calibrationPanelOpen ? 'Hide re-scale tools' : 'Re-scale';
}
panel.style.display = calibrationPanelOpen ? 'block' : 'none';
}
function startDrawLine() {
if (currentImageMode !== 'processed') {
currentImageMode = 'processed';
updateDisplayedImage();
}
isDrawingLine = true;
lineStart = null;
lineEnd = null;
drawnLinePx = 0;
// Disable zoom while drawing
if (isZoomActive) toggleZoom();
if (!syncScaleCanvasToImage()) {
alert('Image is still loading. Please try again in a moment.');
isDrawingLine = false;
return;
}
scaleCanvas.style.display = 'block';
scaleCtx.clearRect(0, 0, scaleCanvas.width, scaleCanvas.height);
document.getElementById('drawLineBtn').classList.add('cal-active');
document.getElementById('drawLineBtn').textContent = 'Drawing... Click start & end points';
document.getElementById('lineStatus').textContent = '';
}
scaleCanvas.addEventListener('mousedown', function(e) {
if (!isDrawingLine) return;
const rect = scaleCanvas.getBoundingClientRect();
const scaleX = scaleCanvas.width / rect.width;
const scaleY = scaleCanvas.height / rect.height;
const x = (e.clientX - rect.left) * scaleX;
const y = (e.clientY - rect.top) * scaleY;
if (!lineStart) {
lineStart = { x, y };
// Draw start point
scaleCtx.clearRect(0, 0, scaleCanvas.width, scaleCanvas.height);
scaleCtx.fillStyle = 'lime';
scaleCtx.beginPath();
scaleCtx.arc(x, y, 6, 0, Math.PI * 2);
scaleCtx.fill();
} else {
lineEnd = { x, y };
// Draw line
scaleCtx.clearRect(0, 0, scaleCanvas.width, scaleCanvas.height);
scaleCtx.strokeStyle = 'lime';
scaleCtx.lineWidth = 3;
scaleCtx.beginPath();
scaleCtx.moveTo(lineStart.x, lineStart.y);
scaleCtx.lineTo(lineEnd.x, lineEnd.y);
scaleCtx.stroke();
drawnLinePx = Math.sqrt(
Math.pow(lineEnd.x - lineStart.x, 2) +
Math.pow(lineEnd.y - lineStart.y, 2)
);
isDrawingLine = false;
document.getElementById('drawLineBtn').classList.remove('cal-active');
document.getElementById('drawLineBtn').textContent = 'Draw Line on Image';
document.getElementById('lineStatus').textContent = `Line: ${Math.round(drawnLinePx)} px`;
}
});
scaleCanvas.addEventListener('mousemove', function(e) {
if (!isDrawingLine || !lineStart) return;
const rect = scaleCanvas.getBoundingClientRect();
const scaleX = scaleCanvas.width / rect.width;
const scaleY = scaleCanvas.height / rect.height;
const x = (e.clientX - rect.left) * scaleX;
const y = (e.clientY - rect.top) * scaleY;
scaleCtx.clearRect(0, 0, scaleCanvas.width, scaleCanvas.height);
scaleCtx.strokeStyle = 'lime';
scaleCtx.lineWidth = 3;
scaleCtx.beginPath();
scaleCtx.moveTo(lineStart.x, lineStart.y);
scaleCtx.lineTo(x, y);
scaleCtx.stroke();
});
async function applyManualScale() {
const nmValue = parseFloat(document.getElementById('scaleNmInput').value);
if (!nmValue || nmValue <= 0) {
alert('Please enter a valid nm value.');
return;
}
if (drawnLinePx <= 0) {
alert('Please draw a line on the scale bar first.');
return;
}
const pixelSize = nmValue / drawnLinePx;
// Hide canvas
scaleCanvas.style.display = 'none';
scaleCtx.clearRect(0, 0, scaleCanvas.width, scaleCanvas.height);
// Reprocess with manual pixel size
document.getElementById('lineStatus').textContent = 'Reprocessing...';
try {
await processImage({
manualPixelSize: pixelSize,
binaryMaskTune: appliedBinaryMaskTune,
forceReprocess: true
});
calibrationPanelOpen = false;
document.getElementById('lineStatus').textContent = '';
} catch (e) {
alert('Error reprocessing: ' + e.message);
}
}
document.getElementById('binaryMaskSlider').addEventListener('input', handleBinaryMaskSliderInput);
document.getElementById('binaryMaskSlider').addEventListener('change', handleBinaryMaskSliderChange);
document.getElementById('binaryMaskApplyBtn').addEventListener('click', applyBinaryMaskTune);
window.addEventListener('resize', function() {
syncParticleOverlayToImage();
renderParticleOverlay();
if (scaleCanvas.style.display === 'block') {
syncScaleCanvasToImage();
}
});
processImage();
</script>
</body>
</html>
|