File size: 62,847 Bytes
43dfc77 e85d70e 75df9f8 e85d70e 0d1850a 43dfc77 e85d70e 75df9f8 9d92392 e85d70e b4e2bba 43dfc77 75df9f8 43dfc77 75df9f8 43dfc77 e85d70e 43dfc77 e85d70e 43dfc77 e85d70e bd71049 e85d70e b4e2bba 75df9f8 b4e2bba e85d70e 75df9f8 43dfc77 5ae9214 bd71049 5ae9214 d62556c bd71049 d62556c 75df9f8 bd71049 d62556c bd71049 d62556c bd71049 399a90c 75df9f8 bd71049 d62556c 399a90c e85d70e 75df9f8 43dfc77 e85d70e 399a90c e85d70e bd71049 e85d70e 399a90c e85d70e 75df9f8 43dfc77 e85d70e bd71049 0d1850a bd71049 0d1850a e85d70e bd71049 e85d70e f727999 e85d70e bd71049 20d81a7 d62556c bd71049 d62556c 20d81a7 0d1850a e85d70e bd71049 e85d70e b4e2bba 20d81a7 75df9f8 b4e2bba 75df9f8 b4e2bba e85d70e 75df9f8 20d81a7 b4e2bba e85d70e 75df9f8 e85d70e d62556c 0d1850a d62556c e85d70e 1381b2a e85d70e 75df9f8 e85d70e db04261 9dcdd68 db04261 9d92392 f727999 bd71049 db04261 75df9f8 9dcdd68 75df9f8 9dcdd68 db04261 0d1850a db04261 0d1850a db04261 0d1850a 75df9f8 db04261 0d1850a d0cf6f7 5ae9214 0d1850a 5ae9214 0d1850a 5ae9214 d0cf6f7 0d1850a d0cf6f7 0d1850a d0cf6f7 0d1850a d0cf6f7 0d1850a d0cf6f7 5ae9214 0d1850a 5ae9214 a2f7f69 75df9f8 399a90c 03d45a7 399a90c db04261 03d45a7 ef329eb 03d45a7 ef329eb db04261 03d45a7 db04261 ef329eb db04261 5ca7459 ef329eb db04261 5ca7459 db04261 f727999 db04261 f727999 399a90c 5ae9214 bd71049 5ae9214 f727999 5ae9214 f727999 bd71049 5ae9214 0d1850a 5ae9214 f727999 0d1850a 5ae9214 f727999 5ae9214 bd71049 1381b2a 5ae9214 f727999 bd71049 75df9f8 bd71049 d62556c bd71049 9dcdd68 bd71049 d62556c d0cf6f7 ef329eb f727999 ef329eb 5ca7459 ef329eb 5ca7459 f727999 399a90c ef329eb 5ae9214 5ca7459 5ae9214 f727999 5ae9214 f727999 9dcdd68 5ae9214 f727999 5ca7459 d62556c 5ca7459 ef329eb db04261 43885c1 9dcdd68 75df9f8 9dcdd68 75df9f8 9dcdd68 d62556c 9dcdd68 d62556c 9dcdd68 d62556c 9dcdd68 d62556c 9dcdd68 d62556c 9dcdd68 d62556c 9dcdd68 d62556c 9d92392 03d45a7 9d92392 43885c1 9d92392 9dcdd68 bd71049 9dcdd68 bd71049 9dcdd68 bd71049 1381b2a 9dcdd68 1381b2a 9dcdd68 1381b2a 9dcdd68 1381b2a bd71049 9dcdd68 bd71049 d62556c 1381b2a d62556c 9dcdd68 d62556c 9dcdd68 bd71049 9dcdd68 d62556c 9dcdd68 d62556c 9dcdd68 d62556c 75df9f8 e85d70e db04261 0d1850a 9dcdd68 0d1850a 75df9f8 e85d70e 9d92392 f727999 9d92392 75df9f8 bd71049 9d92392 e85d70e d0cf6f7 0d1850a 75df9f8 0d1850a 75df9f8 43dfc77 9d92392 bd71049 d0cf6f7 0d1850a 75df9f8 9d92392 e85d70e 9d92392 e85d70e 75df9f8 e85d70e 9d92392 0d1850a 5ae9214 0d1850a bd71049 75df9f8 bd71049 d62556c bd71049 0d1850a d0cf6f7 5ae9214 d0cf6f7 5ae9214 d0cf6f7 75df9f8 d0cf6f7 0d1850a 5ae9214 0d1850a 75df9f8 0d1850a 43dfc77 0d1850a 5ae9214 75df9f8 d0cf6f7 0d1850a d0cf6f7 0d1850a 5ae9214 d0cf6f7 9dcdd68 bd71049 9dcdd68 bd71049 9dcdd68 1381b2a 9dcdd68 bd71049 9dcdd68 bd71049 1381b2a 9dcdd68 bd71049 9dcdd68 1381b2a 9dcdd68 1381b2a 9dcdd68 1381b2a 9dcdd68 1381b2a 03d45a7 9dcdd68 43dfc77 9dcdd68 399a90c bd71049 d62556c bd71049 0d1850a bd71049 5ae9214 bd71049 75df9f8 5ae9214 9d92392 43dfc77 bd71049 9d92392 bd71049 1381b2a bd71049 f727999 9d92392 5ae9214 75df9f8 0d1850a 1381b2a 0d1850a 5ae9214 bd71049 75df9f8 bd71049 9d92392 5ca7459 5ae9214 5ca7459 bd71049 5ca7459 5ae9214 5ca7459 bd71049 5ca7459 9d92392 5ca7459 9dcdd68 75df9f8 9dcdd68 75df9f8 9dcdd68 75df9f8 9dcdd68 d62556c 399a90c 9d92392 bd71049 d62556c 75df9f8 9d92392 bd71049 0d1850a 1381b2a bd71049 75df9f8 5ae9214 9d92392 399a90c 1381b2a d0cf6f7 75df9f8 d0cf6f7 75df9f8 d0cf6f7 9d92392 d0cf6f7 bd71049 75df9f8 d0cf6f7 f727999 0d1850a d0cf6f7 0d1850a d0cf6f7 0d1850a bd71049 e85d70e bd71049 d0cf6f7 75df9f8 d0cf6f7 d62556c d0cf6f7 bd71049 d0cf6f7 bd71049 9d92392 1381b2a d62556c 0d1850a 9dcdd68 d62556c 5ae9214 1381b2a d0cf6f7 9dcdd68 1381b2a 43dfc77 d62556c 75df9f8 d62556c 1381b2a d62556c 1381b2a d62556c 1381b2a d62556c 1381b2a 75df9f8 1381b2a 9dcdd68 1381b2a 9dcdd68 bd71049 1381b2a bd71049 0d1850a bd71049 d0cf6f7 bd71049 75df9f8 d0cf6f7 bd71049 0d1850a d62556c 75df9f8 bd71049 9d92392 0d1850a d0cf6f7 bd71049 43dfc77 bd71049 75df9f8 bd71049 d0cf6f7 bd71049 d62556c 75df9f8 d62556c 1381b2a d62556c bd71049 9dcdd68 75df9f8 9dcdd68 75df9f8 9dcdd68 bd71049 d62556c 1381b2a bd71049 1381b2a 9dcdd68 1381b2a 9dcdd68 1381b2a 9dcdd68 1381b2a 75df9f8 1381b2a 9dcdd68 1381b2a 9dcdd68 1381b2a bd71049 d62556c 1381b2a d62556c 9dcdd68 1381b2a 9dcdd68 d62556c 75df9f8 d62556c 9dcdd68 d62556c 9dcdd68 d62556c 9dcdd68 d62556c 9dcdd68 d62556c 9dcdd68 75df9f8 9dcdd68 75df9f8 9dcdd68 d62556c 1381b2a 9dcdd68 1381b2a 75df9f8 9dcdd68 1381b2a 9dcdd68 1381b2a d62556c 1381b2a d62556c 75df9f8 d62556c 1381b2a 9dcdd68 1381b2a 9dcdd68 1381b2a 9dcdd68 1381b2a 9dcdd68 1381b2a 9dcdd68 1381b2a 9dcdd68 1381b2a 75df9f8 1381b2a 9dcdd68 d62556c 9d92392 bd71049 75df9f8 bd71049 75df9f8 d0cf6f7 bd71049 0d1850a bd71049 e85d70e 75df9f8 e85d70e 399a90c e85d70e bd71049 e85d70e 75df9f8 d0cf6f7 e85d70e 9d92392 0d1850a 75df9f8 bd71049 75df9f8 d0cf6f7 0d1850a bd71049 0d1850a 9d92392 db04261 e85d70e 9d92392 15dd741 e85d70e 1381b2a e85d70e | 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 | # app.py (Shiny for Python UI + Starlette JSON API, published state persisted to HF Dataset Hub)
from __future__ import annotations
import asyncio
import base64
import json
import os
import hmac
import io
from pathlib import Path
from uuid import uuid4
from urllib.request import Request as URLRequest, urlopen
from urllib.error import HTTPError, URLError
from shiny import App, ui
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import JSONResponse, Response
from starlette.routing import Mount, Route
import smtplib
from email.message import EmailMessage
# -----------------------------------------------------------------------------
# HF Hub persistence (FREE): save/load cards_state.json from a dataset repo
# -----------------------------------------------------------------------------
# Required:
# - Space secret HF_TOKEN = write token
# Optional:
# - Space secret HF_STATE_REPO = "username/models_state"
# If omitted, we infer username from SPACE_ID and use "<user>/models_state"
# -----------------------------------------------------------------------------
HF_TOKEN = (os.environ.get("HF_TOKEN") or "").strip()
HF_STATE_FILE = (os.environ.get("HF_STATE_FILE") or "cards_state.json").strip()
HF_STATE_REPO_TYPE = "dataset"
SECTIONS = ("Models", "Methods", "Miscellaneous")
def _infer_owner_from_space() -> str:
sid = os.environ.get("SPACE_ID") or os.environ.get("HF_SPACE_ID") or ""
if isinstance(sid, str) and "/" in sid:
return sid.split("/", 1)[0].strip()
return ""
def _normalize_section(x) -> str:
s = str(x or "").strip().lower()
mapping = {
"models": "Models",
"model": "Models",
"methods": "Methods",
"method": "Methods",
"miscellaneous": "Miscellaneous",
"misc": "Miscellaneous",
}
return mapping.get(s, "Models")
def _notification_type(section: str) -> str:
s = _normalize_section(section)
return {
"Models": "Model",
"Methods": "Method",
"Miscellaneous": "Miscellaneous",
}.get(s, "Item")
_owner = _infer_owner_from_space()
HF_STATE_REPO = (os.environ.get("HF_STATE_REPO") or (f"{_owner}/models_state" if _owner else "")).strip()
HUB_ENABLED = bool(HF_TOKEN and HF_STATE_REPO)
try:
from huggingface_hub import hf_hub_download, HfApi, CommitOperationAdd
except Exception:
HUB_ENABLED = False
# -----------------------------------------------------------------------------
# Shared persistence for PUBLISHED cards (local cache file + Hub sync)
# -----------------------------------------------------------------------------
def _pick_state_dir() -> Path:
p = Path("/tmp")
p.mkdir(parents=True, exist_ok=True)
return p
STATE_DIR = _pick_state_dir()
STATE_PATH = STATE_DIR / "cards_state.json"
STATE_LOCK = asyncio.Lock()
SERVER_PASSWORD = (os.environ.get("password") or "").strip()
SMTP_HOST = os.environ.get("SMTP_HOST", "").strip()
SMTP_PORT = int(os.environ.get("SMTP_PORT", "587"))
SMTP_USER = os.environ.get("SMTP_USER", "").strip()
SMTP_PASS = os.environ.get("SMTP_PASS", "").strip()
SMTP_FROM = os.environ.get("SMTP_FROM", SMTP_USER).strip()
SMTP_TO = [x.strip() for x in os.environ.get("SMTP_TO", "").split(",") if x.strip()]
EMAIL_ENABLED = bool(SMTP_HOST and SMTP_USER and SMTP_PASS and SMTP_TO)
# -----------------------------------------------------------------------------
# ntfy notifications
# -----------------------------------------------------------------------------
# Optional secrets:
# - NTFY_URL (default: https://ntfy.sh)
# - NTFY_TOPIC (default: Models) -> publishes to https://ntfy.sh/Models
# - NTFY_TOKEN (Bearer auth, optional)
# - NTFY_USER / NTFY_PASS (Basic auth, optional)
# -----------------------------------------------------------------------------
NTFY_URL = (os.environ.get("NTFY_URL") or "https://ntfy.sh").strip().rstrip("/")
NTFY_TOPIC = (os.environ.get("NTFY_TOPIC") or "Models").strip().strip("/")
NTFY_TOKEN = (os.environ.get("NTFY_TOKEN") or "").strip()
NTFY_USER = (os.environ.get("NTFY_USER") or "").strip()
NTFY_PASS = (os.environ.get("NTFY_PASS") or "").strip()
NTFY_ENABLED = bool(NTFY_URL and NTFY_TOPIC)
def _send_email(subject: str, body: str) -> None:
if not EMAIL_ENABLED:
return
msg = EmailMessage()
msg["Subject"] = subject
msg["From"] = SMTP_FROM
msg["To"] = ", ".join(SMTP_TO)
msg.set_content(body)
with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=20) as s:
s.starttls()
s.login(SMTP_USER, SMTP_PASS)
s.send_message(msg)
def _send_ntfy(title: str, body: str, *, tags: list[str] | None = None, priority: int | str | None = None) -> None:
if not NTFY_ENABLED:
return
try:
topic = NTFY_TOPIC.lstrip("/")
url = f"{NTFY_URL}/{topic}"
headers = {
"Content-Type": "text/plain; charset=utf-8",
"Title": title,
}
clean_tags = []
for t in (tags or []):
s = str(t or "").strip().replace(",", " ")
if s:
clean_tags.append(s)
if clean_tags:
headers["Tags"] = ",".join(clean_tags)
if priority is not None:
headers["Priority"] = str(priority)
if NTFY_TOKEN:
headers["Authorization"] = f"Bearer {NTFY_TOKEN}"
elif NTFY_USER and NTFY_PASS:
raw = f"{NTFY_USER}:{NTFY_PASS}".encode("utf-8")
headers["Authorization"] = "Basic " + base64.b64encode(raw).decode("ascii")
req = URLRequest(
url,
data=body.encode("utf-8"),
headers=headers,
method="POST",
)
with urlopen(req, timeout=20) as resp:
resp.read()
except (HTTPError, URLError, OSError):
pass
except Exception:
pass
def _hub_pull_into_local() -> None:
"""If local state missing, download cards_state.json from dataset repo."""
if not HUB_ENABLED:
return
if STATE_PATH.exists():
return
try:
downloaded = hf_hub_download(
repo_id=HF_STATE_REPO,
repo_type=HF_STATE_REPO_TYPE,
filename=HF_STATE_FILE,
token=HF_TOKEN,
)
STATE_PATH.write_text(Path(downloaded).read_text(encoding="utf-8"), encoding="utf-8")
except Exception:
pass
def _hub_push_state(state: dict) -> None:
"""Upload current state JSON to dataset repo."""
if not HUB_ENABLED:
return
try:
api = HfApi(token=HF_TOKEN)
content = json.dumps(state, indent=2, ensure_ascii=False).encode("utf-8")
op = CommitOperationAdd(
path_in_repo=HF_STATE_FILE,
path_or_fileobj=io.BytesIO(content),
)
api.create_commit(
repo_id=HF_STATE_REPO,
repo_type=HF_STATE_REPO_TYPE,
operations=[op],
commit_message="Update cards_state.json",
)
except Exception:
pass
def _normalize_tags(x) -> list[str]:
if x is None:
return []
if isinstance(x, str):
x = [t.strip() for t in x.split(",")]
if not isinstance(x, list):
return []
out: list[str] = []
for t in x:
if t is None:
continue
s = str(t).strip()
if s and s not in out:
out.append(s)
return out
def _new_published_card(payload: dict, *, card_id: str | None = None) -> dict:
return {
"id": card_id or str(uuid4())[:12],
"section": _normalize_section(payload.get("section")),
"model": str(payload.get("model") or "").strip(),
"tags": _normalize_tags(payload.get("tags")),
"how_it_works": str(payload.get("how_it_works") or "").strip(),
"use_cases": str(payload.get("use_cases") or "").strip(),
"link": str(payload.get("link") or "").strip(),
"author": str(payload.get("author") or "").strip(),
}
def _normalize_state(obj: dict) -> dict:
if not isinstance(obj, dict):
obj = {}
version = obj.get("version", 0)
if not isinstance(version, int):
version = 0
cards = obj.get("cards", [])
if not isinstance(cards, list):
cards = []
normalized = []
for c in cards:
if not isinstance(c, dict):
continue
normalized.append(
{
"id": str(c.get("id") or str(uuid4())[:12]),
"section": _normalize_section(c.get("section") or c.get("tab") or c.get("category")),
"model": str(c.get("model") or c.get("title") or ""),
"tags": _normalize_tags(c.get("tags") or c.get("categories") or []),
"how_it_works": str(c.get("how_it_works") or c.get("how") or ""),
"use_cases": str(c.get("use_cases") or c.get("use") or ""),
"link": str(c.get("link") or c.get("resource_url") or ""),
"author": str(c.get("author") or c.get("by") or ""),
}
)
return {"version": version, "cards": normalized}
def _read_state_sync() -> dict:
_hub_pull_into_local()
if not STATE_PATH.exists():
return {"version": 0, "cards": []}
try:
return _normalize_state(json.loads(STATE_PATH.read_text(encoding="utf-8")))
except Exception:
return {"version": 0, "cards": []}
def _write_state_sync(state: dict) -> None:
tmp = STATE_PATH.with_suffix(".tmp")
tmp.write_text(json.dumps(state, indent=2, ensure_ascii=False), encoding="utf-8")
tmp.replace(STATE_PATH)
_hub_push_state(state)
async def get_state() -> dict:
async with STATE_LOCK:
return _read_state_sync()
async def set_state(state: dict) -> None:
async with STATE_LOCK:
_write_state_sync(state)
def _json(data: dict, status_code: int = 200) -> JSONResponse:
return JSONResponse(data, status_code=status_code, headers={"Cache-Control": "no-store"})
def _check_password(request: Request, payload: dict | None = None) -> bool:
if not SERVER_PASSWORD:
return False
provided = request.headers.get("X-Password")
if not provided and isinstance(payload, dict):
provided = payload.get("password")
if not isinstance(provided, str):
return False
return hmac.compare_digest(provided.strip(), SERVER_PASSWORD)
# -----------------------------------------------------------------------------
# API: published cards only
# -----------------------------------------------------------------------------
async def api_cards(request: Request) -> Response:
if request.method == "GET":
return _json(await get_state())
if request.method == "POST":
try:
payload = await request.json()
except Exception:
payload = {}
if not isinstance(payload, dict) or not _check_password(request, payload):
msg = (
"Unauthorized (check Space secret 'password')"
if SERVER_PASSWORD
else "Password not configured"
)
return _json({"error": msg}, status_code=401)
card = _new_published_card(payload)
if not card["model"] or not card["how_it_works"] or not card["use_cases"]:
return _json(
{"error": "Model, How it Works, and Use Cases are required"},
status_code=400,
)
state = await get_state()
state["cards"].append(card)
state["version"] += 1
await set_state(state)
if EMAIL_ENABLED:
subject = f"New {card.get('section', 'Models')} card posted: {card.get('model', '')}"
body = (
f"Section: {card.get('section','')}\n"
f"Model: {card.get('model','')}\n"
f"Tags: {', '.join(card.get('tags', []) or [])}\n"
f"By: {card.get('author','')}\n"
f"Link: {card.get('link','')}\n"
)
asyncio.create_task(asyncio.to_thread(_send_email, subject, body))
if NTFY_ENABLED:
item_type = _notification_type(card.get("section", "Models"))
maker = card.get("author", "").strip() or "Unknown"
name = card.get("model", "").strip() or "Untitled"
title = f"New {item_type} Added"
body = f"{name} by {maker}"
asyncio.create_task(
asyncio.to_thread(
_send_ntfy,
title,
body,
tags=["tada"],
priority=3,
)
)
return _json(state)
return _json({"error": "Method not allowed"}, status_code=405)
async def api_card_id(request: Request) -> Response:
card_id = request.path_params.get("card_id", "")
state = await get_state()
cards = state.get("cards", [])
idx = next((i for i, c in enumerate(cards) if c.get("id") == card_id), None)
if idx is None:
return _json({"error": "Card not found"}, status_code=404)
if request.method == "PUT":
try:
payload = await request.json()
except Exception:
payload = {}
if not isinstance(payload, dict) or not _check_password(request, payload):
msg = "Unauthorized (check Space secret 'password')" if SERVER_PASSWORD else "Password not configured"
return _json({"error": msg}, status_code=401)
updated = _new_published_card(payload, card_id=card_id)
if not updated["model"] or not updated["how_it_works"] or not updated["use_cases"]:
return _json({"error": "Model, How it Works, and Use Cases are required"}, status_code=400)
cards[idx] = updated
state["version"] += 1
await set_state(state)
return _json(state)
if request.method == "DELETE":
if not _check_password(request):
msg = "Unauthorized (check Space secret 'password')" if SERVER_PASSWORD else "Password not configured"
return _json({"error": msg}, status_code=401)
cards.pop(idx)
state["version"] += 1
await set_state(state)
return _json(state)
return _json({"error": "Method not allowed"}, status_code=405)
# -----------------------------------------------------------------------------
# UI
# -----------------------------------------------------------------------------
app_ui = ui.page_fluid(
ui.tags.style(
r"""
:root{
--navy:#062a4d;
--navy2:#041f3a;
--cardBorder:#d8e1ee;
--cardBg:#ffffff;
--muted:#6b778c;
--headerBg:#f3f6fb;
--good:#167d3a;
}
body { background: #f3f6fb; }
input:not([type="checkbox"]):not([type="radio"]),
select {
width: 100%;
box-sizing: border-box;
border: 1px solid #d8e1ee;
border-radius: 12px;
padding: 10px 12px;
font-size: 14px;
outline: none;
background: white;
}
input[readonly]:not([type="checkbox"]):not([type="radio"]) {
background:#f8fafc;
}
select[disabled]{
background:#f8fafc;
}
textarea{
width:100%;
box-sizing:border-box;
border: 1px solid #d8e1ee;
border-radius: 12px;
padding: 10px 12px;
font-size: 14px;
outline: none;
background: white;
resize: none;
overflow: auto;
line-height: 1.25;
}
textarea[readonly]{ background:#f8fafc; }
label{
display:block;
font-size: 12px;
color: var(--muted);
margin: 0 0 5px;
font-weight: 750;
letter-spacing: .2px;
}
.topbar{
background: linear-gradient(0deg, var(--navy2), var(--navy));
padding: 12px 14px;
border-radius: 0 0 14px 14px;
box-shadow: 0 2px 10px rgba(0,0,0,.12);
display:flex;
justify-content:space-between;
align-items:center;
gap: 12px;
margin-bottom: 8px;
}
.top-left{
display:flex;
align-items:center;
gap: 10px;
min-width: 0;
flex: 1 1 auto;
}
.chips-row{
display:flex;
gap: 8px;
align-items:center;
overflow-x:auto;
padding: 2px 4px;
min-width: 0;
flex: 1 1 auto;
}
.chips-row::-webkit-scrollbar{ display:none; }
.chip{
border: 1px solid rgba(255,255,255,.25);
background: rgba(255,255,255,.12);
color: #fff;
border-radius: 999px;
padding: 7px 10px;
font-size: 12px;
font-weight: 850;
cursor: pointer;
user-select:none;
white-space: nowrap;
}
.chip.active{
background: rgba(255,255,255,.95);
color: var(--navy);
border-color: rgba(0,0,0,.08);
}
#clear-filters{
border-radius: 12px;
padding: 9px 12px;
font-weight: 900;
font-size: 13px;
cursor:pointer;
white-space: nowrap;
background: rgba(255,255,255,.12);
color: #fff;
border: 1px solid rgba(255,255,255,.25);
}
#add-btn{
background: white;
color: var(--navy);
border: 1px solid rgba(0,0,0,.08);
border-radius: 12px;
padding: 12px 20px;
font-weight: 950;
font-size: 22px;
line-height: 1;
cursor: pointer;
box-shadow: 0 2px 8px rgba(0,0,0,.14);
flex: 0 0 auto;
}
.section-tabs{
display:flex;
gap: 10px;
padding: 0 16px 10px 16px;
flex-wrap: wrap;
}
.section-tab{
border: 1px solid #d8e1ee;
background: white;
color: #1f2a44;
border-radius: 999px;
padding: 9px 14px;
font-size: 13px;
font-weight: 900;
cursor:pointer;
}
.section-tab.active{
background: var(--navy);
color: white;
border-color: var(--navy);
}
.err{
margin: 0 16px 10px 16px;
padding: 10px 12px;
border-radius: 10px;
background: #fff1f2;
border: 1px solid #fecdd3;
color: #9f1239;
font-size: 13px;
display:none;
}
.cards-grid{
display:grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 22px;
padding: 10px 16px 22px 16px;
width: 100%;
margin: 0;
align-items:start;
}
@media (max-width: 900px){
.cards-grid{ grid-template-columns: 1fr; }
}
.card{
background: var(--cardBg);
border: 1px solid var(--cardBorder);
border-radius: 14px;
box-shadow: 0 1px 0 rgba(0,0,0,.02);
aspect-ratio: 1 / 1;
width: 100%;
overflow: hidden;
display:flex;
flex-direction:column;
min-height: 0;
}
.card-header{
background: var(--headerBg);
display:flex;
align-items:center;
justify-content:space-between;
gap: 10px;
padding: 10px 10px 8px 10px;
border-bottom: 1px solid #eef2f8;
flex: 0 0 auto;
}
.header-left{
display:flex;
align-items:center;
gap: 10px;
flex: 1 1 auto;
min-width: 0;
}
.title-input, .title-text{
flex: 1 1 auto;
min-width: 140px;
border: none;
outline: none;
background: transparent;
padding: 6px 8px;
border-radius: 10px;
font-size: 16px;
font-weight: 650;
color: #1f2a44;
}
.title-input::placeholder{ color: #7b879c; font-weight: 650; }
.card.has-title .title-input{ font-weight: 950; }
.title-input:focus{
background: rgba(255,255,255,.85);
border: 1px solid #d8e1ee;
}
.title-text{ font-weight: 950; }
.tag-bar{
display:flex;
gap: 6px;
align-items:center;
flex: 0 0 auto;
max-width: 52%;
overflow:auto;
padding-bottom: 2px;
}
.tag-bar::-webkit-scrollbar{ display:none; }
.tag-chip{
border: 1px solid #d8e1ee;
background: #fff;
color: #1f2a44;
border-radius: 999px;
padding: 6px 9px;
font-size: 11px;
font-weight: 850;
display:inline-flex;
align-items:center;
gap: 6px;
cursor:pointer;
white-space: nowrap;
}
.tag-chip .rm{ font-weight: 950; opacity: .6; }
.tag-btn{
border: 1px dashed #cfd9ea;
background: transparent;
border-radius: 999px;
padding: 6px 10px;
font-size: 11px;
font-weight: 900;
cursor:pointer;
white-space:nowrap;
}
.hdr-right{
display:flex;
align-items:center;
gap: 8px;
flex: 0 0 auto;
}
.section-pill{
font-size: 11px;
font-weight: 950;
padding: 6px 10px;
border-radius: 999px;
background: #edf4ff;
border: 1px solid #cfe0ff;
color: #1f4d8f;
user-select:none;
}
.draft-badge{
font-size: 11px;
font-weight: 950;
padding: 6px 10px;
border-radius: 999px;
background: #fff7ed;
border: 1px solid #fed7aa;
color: #9a3412;
user-select:none;
}
.post-btn, .edit-btn{
border-radius: 12px;
padding: 8px 12px;
font-weight: 950;
border: 1px solid rgba(0,0,0,.08);
cursor:pointer;
white-space:nowrap;
background: #fff;
color: #1f2a44;
}
.post-btn{
background: #eaf7ef;
color: var(--good);
}
.post-btn:disabled{ opacity: .55; cursor: not-allowed; }
.del-btn{
border: none;
background: transparent;
color: #7b879c;
font-weight: 900;
font-size: 20px;
cursor:pointer;
padding: 0 8px;
flex: 0 0 auto;
}
.card-main{
padding: 12px;
display:flex;
flex-direction:column;
gap: 12px;
flex: 1 1 auto;
min-height: 0;
overflow:hidden;
}
.panel{
display:flex;
flex-direction:column;
flex: 1 1 0;
min-height: 0;
}
.panel textarea{
flex: 1 1 0;
min-height: 0;
}
.card-footer{
padding: 10px 12px 12px 12px;
border-top: 1px solid #eef2f8;
flex: 0 0 auto;
}
.footer-row{
display:flex;
align-items:flex-end;
gap: 10px;
}
.section-col{
flex: 0 0 155px;
min-width: 130px;
}
.link-col{
flex: 1 1 auto;
min-width: 0;
}
.by-col{
flex: 0 0 auto;
display:flex;
align-items:center;
gap: 8px;
white-space: nowrap;
font-size: 12px;
font-weight: 900;
color:#1f2a44;
}
.by-input{
width: 160px;
padding: 8px 10px;
border-radius: 10px;
font-size: 12px;
}
.by-display{
width: 200px;
text-align:right;
font-size: 12px;
font-weight: 900;
color:#1f2a44;
overflow:hidden;
text-overflow: ellipsis;
}
.resource-link{ display:inline-block; margin-top: 8px; font-size: 13px; }
.empty{
margin: 0 16px;
padding: 18px;
background: white;
border: 1px dashed #cfd9ea;
border-radius: 12px;
color: #41516b;
}
.dlg-backdrop{
position: fixed;
inset: 0;
background: rgba(0,0,0,.35);
display:flex;
align-items:center;
justify-content:center;
z-index: 999999;
padding: 14px;
}
.dlg{
width: min(560px, calc(100vw - 28px));
max-height: 80vh;
background: white;
border-radius: 14px;
box-shadow: 0 10px 30px rgba(0,0,0,.25);
display:flex;
flex-direction:column;
overflow:hidden;
}
.dlg .head{
padding: 12px 14px 10px 14px;
border-bottom: 1px solid #eef2f8;
}
.dlg .head h3{ margin: 0 0 6px 0; font-size: 16px; }
.dlg .muted{ color: var(--muted); font-size: 13px; }
.dlg .body{
padding: 12px 14px;
overflow:auto;
}
.dlg .foot{
padding: 10px 14px 12px 14px;
border-top: 1px solid #eef2f8;
display:flex;
gap: 10px;
justify-content:flex-end;
}
.btn{
border-radius: 12px;
padding: 9px 12px;
font-weight: 900;
cursor:pointer;
border: 1px solid #d8e1ee;
background: #ffffff;
}
.btn-primary{
background:#eaf7ef;
border-color:#bbf7d0;
color: var(--good);
}
.btn-danger{
border: 1px solid #fecdd3;
background: #fff1f2;
color: #9f1239;
}
.btn[disabled]{ opacity: .55; cursor: not-allowed; }
.checklist{
display:flex;
flex-direction:column;
gap: 6px;
}
.checkrow{
display:flex;
align-items:center;
gap: 10px;
padding: 6px 8px;
border-radius: 10px;
}
.checkrow:hover{ background:#f6f8fe; }
.checkrow input[type="checkbox"]{ width:auto !important; }
.checkrow .lbl{
font-weight: 850;
font-size: 12px;
color:#1f2a44;
line-height: 1.1;
}
.row{
display:flex;
gap: 10px;
align-items:center;
margin-top: 10px;
}
@media (max-width: 900px){
.footer-row{
flex-wrap: wrap;
align-items:flex-start;
}
.section-col, .link-col, .by-col{
flex: 1 1 100%;
}
.by-display{
width: auto;
text-align: left;
}
}
"""
),
ui.tags.div(
{"class": "topbar"},
ui.tags.div(
{"class": "top-left"},
ui.tags.div({"id": "chips-row", "class": "chips-row"}),
ui.tags.button("Clear", {"id": "clear-filters", "type": "button"}),
),
ui.tags.button("+", {"id": "add-btn", "type": "button"}),
),
ui.tags.div({"id": "section-tabs", "class": "section-tabs"}),
ui.tags.div({"id": "err", "class": "err"}),
ui.tags.div({"id": "grid", "class": "cards-grid"}),
ui.tags.script(
r"""
(() => {
const DRAFTS_KEY = "model_cards_drafts_v6";
const SECTION_KEY = "model_cards_section_v1";
const grid = document.getElementById("grid");
const addBtn = document.getElementById("add-btn");
const errBox = document.getElementById("err");
const chipsRow = document.getElementById("chips-row");
const clearBtn = document.getElementById("clear-filters");
const sectionTabs = document.getElementById("section-tabs");
const SECTIONS = ["Models", "Methods", "Miscellaneous"];
const COMMON_TAGS = [
"Regression","Classification","Boosting","Bagging","Supervised","Unsupervised",
"Clustering","Dimensionality Reduction","Linear","Additive","Deep Learning",
"Neural Net","Transformer","Ensemble","Bayesian","Causal","Multilevel",
"NLP","Tree-based","Black Box"
];
const state = { version: null, published: [] };
let drafts = loadDrafts();
const saveTimers = new Map();
const filterTags = new Set();
let currentSection = normalizeSection(localStorage.getItem(SECTION_KEY) || "Models");
function normalizeSection(s){
const v = String(s || "").trim().toLowerCase();
if(v === "models" || v === "model") return "Models";
if(v === "methods" || v === "method") return "Methods";
if(v === "miscellaneous" || v === "misc") return "Miscellaneous";
return "Models";
}
function saveCurrentSection(){
localStorage.setItem(SECTION_KEY, currentSection);
}
function sectionOptions(selected){
const s = normalizeSection(selected);
return SECTIONS.map(x => (
`<option value="${escapeAttr(x)}" ${x === s ? "selected" : ""}>${escapeHtml(x)}</option>`
)).join("");
}
function showErr(msg){
if(!msg){ errBox.style.display="none"; errBox.textContent=""; return; }
errBox.style.display="block";
errBox.textContent = msg;
}
function escapeHtml(str){
return String(str ?? "")
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll('"', """)
.replaceAll("'", "'");
}
function escapeAttr(str){
return String(str ?? "")
.replaceAll("&", "&")
.replaceAll('"', """)
.replaceAll("<", "<")
.replaceAll(">", ">");
}
async function api(path, opts={}){
const res = await fetch(path, {
headers: { "Content-Type": "application/json", ...(opts.headers || {}) },
cache: "no-store",
...opts
});
const data = await res.json().catch(() => ({}));
if(!res.ok){
throw new Error(data?.error || ("HTTP " + res.status));
}
return data;
}
function uid(){
return "draft_" + (Date.now().toString(36) + Math.random().toString(36).slice(2, 8));
}
function loadDrafts(){
try{
const raw = localStorage.getItem(DRAFTS_KEY);
const arr = JSON.parse(raw || "[]");
if(!Array.isArray(arr)) return [];
return arr.map(d => ({
id: String(d.id || uid()),
section: normalizeSection(d.section || "Models"),
model: String(d.model || ""),
tags: Array.isArray(d.tags) ? d.tags.map(String) : [],
how_it_works: String(d.how_it_works || ""),
use_cases: String(d.use_cases || ""),
link: String(d.link || ""),
author: String(d.author || ""),
}));
}catch(e){
return [];
}
}
function saveDrafts(){
localStorage.setItem(DRAFTS_KEY, JSON.stringify(drafts));
}
function uniq(arr){
const out = [];
const seen = new Set();
for(const x of arr){
const s = String(x || "").trim();
if(!s) continue;
if(seen.has(s)) continue;
seen.add(s);
out.push(s);
}
return out;
}
function tagUniverse(){
const fromPublished = [];
const fromDrafts = [];
for(const c of state.published){
if(normalizeSection(c.section) !== currentSection) continue;
(c.tags || []).forEach(t => fromPublished.push(t));
}
for(const d of drafts){
if(normalizeSection(d.section) !== currentSection) continue;
(d.tags || []).forEach(t => fromDrafts.push(t));
}
return uniq([...COMMON_TAGS, ...fromPublished, ...fromDrafts]).sort((a,b)=>a.localeCompare(b));
}
function passesFilter(card){
if(normalizeSection(card.section) !== currentSection) return false;
if(filterTags.size === 0) return true;
const tags = new Set((card.tags || []).map(String));
for(const f of filterTags){
if(tags.has(f)) return true;
}
return false;
}
function renderSectionTabs(){
sectionTabs.innerHTML = SECTIONS.map(s => {
const active = s === currentSection ? "active" : "";
return `<button class="section-tab ${active}" data-section="${escapeAttr(s)}" type="button">${escapeHtml(s)}</button>`;
}).join("");
sectionTabs.querySelectorAll(".section-tab").forEach(btn => {
btn.addEventListener("click", (e) => {
e.preventDefault();
currentSection = normalizeSection(btn.getAttribute("data-section"));
saveCurrentSection();
renderSectionTabs();
renderFilterChips();
render();
});
});
}
function renderFilterChips(){
const all = tagUniverse();
chipsRow.innerHTML = all.map(t => {
const active = filterTags.has(t) ? "active" : "";
return `<span class="chip ${active}" data-tag="${escapeAttr(t)}">${escapeHtml(t)}</span>`;
}).join("");
chipsRow.querySelectorAll(".chip").forEach(ch => {
ch.addEventListener("click", () => {
const t = ch.getAttribute("data-tag");
if(filterTags.has(t)) filterTags.delete(t);
else filterTags.add(t);
renderFilterChips();
render();
});
});
}
clearBtn.addEventListener("click", (e) => {
e.preventDefault();
filterTags.clear();
renderFilterChips();
render();
});
function openDialog({title, subtitle, bodyHtml, primaryText, primaryClass, canSubmit, onSubmit, onOpen}){
const backdrop = document.createElement("div");
backdrop.className = "dlg-backdrop";
backdrop.innerHTML = `
<div class="dlg" role="dialog" aria-modal="true">
<div class="head">
<h3>${escapeHtml(title)}</h3>
<div class="muted">${escapeHtml(subtitle || "")}</div>
</div>
<div class="body">${bodyHtml}</div>
<div class="foot">
<button class="btn" data-act="cancel" type="button">Cancel</button>
<button class="btn ${primaryClass || ""}" data-act="primary" type="button" disabled>${escapeHtml(primaryText || "Confirm")}</button>
</div>
</div>
`;
document.body.appendChild(backdrop);
const btnCancel = backdrop.querySelector('[data-act="cancel"]');
const btnPrimary = backdrop.querySelector('[data-act="primary"]');
function close(){ backdrop.remove(); }
function refresh(){
try{
btnPrimary.disabled = !(canSubmit ? canSubmit(backdrop) : true);
}catch{
btnPrimary.disabled = true;
}
}
async function submit(){
if(btnPrimary.disabled) return;
try{
await onSubmit(backdrop);
}catch(e){
showErr(String(e.message || e));
return;
}
close();
}
btnCancel.addEventListener("click", (e) => { e.preventDefault(); close(); });
backdrop.addEventListener("click", (e) => { if(e.target === backdrop) close(); });
btnPrimary.addEventListener("click", (e) => { e.preventDefault(); submit(); });
backdrop.addEventListener("keydown", (e) => {
if(e.key === "Enter"){
const active = document.activeElement;
if(active && active.tagName === "TEXTAREA") return;
if(!btnPrimary.disabled){
e.preventDefault();
submit();
}
}
});
refresh();
if(onOpen) onOpen({backdrop, refresh, close});
return { close, refresh };
}
function openTagsDialog({selected, onApply}){
const all = tagUniverse();
const selectedSet = new Set(selected);
const listHtml = all.map(t => {
const checked = selectedSet.has(t) ? "checked" : "";
return `
<div class="checkrow">
<input type="checkbox" class="tg" data-tag="${escapeAttr(t)}" ${checked}/>
<div class="lbl">${escapeHtml(t)}</div>
</div>
`;
}).join("");
openDialog({
title: "Tags",
subtitle: "Check all that apply.",
bodyHtml: `
<div class="checklist">${listHtml}</div>
<div class="row">
<input id="custom" type="text" placeholder="Add custom tag…" />
<button class="btn" id="addCustom" type="button">Add</button>
</div>
`,
primaryText: "Apply",
primaryClass: "btn-primary",
canSubmit: () => true,
onSubmit: async (backdrop) => {
const checked = [];
backdrop.querySelectorAll(".tg").forEach(cb => {
if(cb.checked) checked.push(cb.getAttribute("data-tag"));
});
onApply(checked.filter(Boolean));
},
onOpen: ({backdrop, refresh}) => {
const custom = backdrop.querySelector("#custom");
const addBtn = backdrop.querySelector("#addCustom");
function addCustom(){
const t = (custom.value || "").trim();
if(!t) return;
const wrap = backdrop.querySelector(".checklist");
const row = document.createElement("div");
row.className = "checkrow";
row.innerHTML = `<input type="checkbox" class="tg" data-tag="${escapeAttr(t)}" checked/><div class="lbl">${escapeHtml(t)}</div>`;
wrap.prepend(row);
custom.value = "";
renderFilterChips();
refresh();
}
addBtn.addEventListener("click", (e) => { e.preventDefault(); addCustom(); });
custom.addEventListener("keydown", (e) => {
if(e.key === "Enter"){
e.preventDefault();
addCustom();
}
});
custom.focus();
}
});
}
function draftFilled(d){
return (d.model || "").trim().length > 0
&& (d.how_it_works || "").trim().length > 0
&& (d.use_cases || "").trim().length > 0;
}
function render(){
const visibleDrafts = drafts.filter(passesFilter);
const visiblePublished = state.published.filter(passesFilter);
if(visibleDrafts.length === 0 && visiblePublished.length === 0){
grid.innerHTML = `<div class="empty"><b>No cards in ${escapeHtml(currentSection)}.</b><div>Click the + to add a draft, then Post to publish.</div></div>`;
return;
}
grid.innerHTML = "";
// Drafts
visibleDrafts.forEach((d) => {
const card = document.createElement("div");
card.className = "card";
const modelText = (d.model || "").trim();
if(modelText) card.classList.add("has-title");
let tags = Array.isArray(d.tags) ? d.tags.map(String) : [];
card.innerHTML = `
<div class="card-header">
<div class="header-left">
<input class="title-input" type="text" value="${escapeAttr(d.model)}" placeholder="Model" />
<div class="tag-bar" style="display:${modelText ? "flex" : "none"};">
<span class="tags"></span>
<button class="tag-btn" type="button">Tags</button>
</div>
</div>
<div class="hdr-right">
<span class="section-pill">${escapeHtml(normalizeSection(d.section))}</span>
<span class="draft-badge">Draft</span>
<button class="post-btn" type="button" ${draftFilled(d) ? "" : "disabled"}>Post</button>
<button class="del-btn" type="button" title="Delete draft">×</button>
</div>
</div>
<div class="card-main">
<div class="panel">
<label>How it Works</label>
<textarea class="how">${escapeHtml(d.how_it_works)}</textarea>
</div>
<div class="panel">
<label>Use Cases</label>
<textarea class="use">${escapeHtml(d.use_cases)}</textarea>
</div>
</div>
<div class="card-footer">
<div class="footer-row">
<div class="section-col">
<label>Tab</label>
<select class="section">${sectionOptions(d.section)}</select>
</div>
<div class="link-col">
<label>Link</label>
<input type="text" class="link" value="${escapeAttr(d.link)}" placeholder="https://..." />
<div class="linkwrap"></div>
</div>
<div class="by-col">
<span>By:</span>
<input class="by-input" type="text" value="${escapeAttr(d.author)}" placeholder="name" />
</div>
</div>
</div>
`;
const titleEl = card.querySelector(".title-input");
const howEl = card.querySelector(".how");
const useEl = card.querySelector(".use");
const linkEl = card.querySelector(".link");
const byEl = card.querySelector(".by-input");
const sectionEl = card.querySelector(".section");
const linkWrap = card.querySelector(".linkwrap");
const tagBar = card.querySelector(".tag-bar");
const tagsWrap = card.querySelector(".tags");
const tagBtn = card.querySelector(".tag-btn");
const postBtn = card.querySelector(".post-btn");
const delBtn = card.querySelector(".del-btn");
const sectionPill = card.querySelector(".section-pill");
function updateLink(){
const url = (linkEl.value || "").trim();
linkWrap.innerHTML = url
? `<a class="resource-link" href="${escapeAttr(url)}" target="_blank" rel="noopener noreferrer">Open link</a>`
: "";
}
function getDraft(){
return drafts.find(x => x.id === d.id) || null;
}
function setDraft(patch){
const i = drafts.findIndex(x => x.id === d.id);
if(i === -1) return;
drafts[i] = { ...drafts[i], ...patch };
drafts[i].section = normalizeSection(drafts[i].section);
saveDrafts();
}
function updateHeader(){
const hasTitle = (titleEl.value || "").trim().length > 0;
card.classList.toggle("has-title", hasTitle);
tagBar.style.display = hasTitle ? "flex" : "none";
sectionPill.textContent = normalizeSection(sectionEl.value);
const cur = getDraft();
if(cur) postBtn.disabled = !draftFilled(cur);
}
function renderTags(){
tagsWrap.innerHTML = "";
tags.forEach(t => {
const chip = document.createElement("span");
chip.className = "tag-chip";
chip.innerHTML = `${escapeHtml(t)} <span class="rm">×</span>`;
chip.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
tags = tags.filter(x => x !== t);
setDraft({ tags });
renderTags();
renderFilterChips();
updateHeader();
});
tagsWrap.appendChild(chip);
});
}
function scheduleDraftSave(){
const existing = saveTimers.get(d.id);
if(existing) clearTimeout(existing);
saveTimers.set(d.id, setTimeout(() => {
setDraft({
section: normalizeSection(sectionEl.value || "Models"),
model: titleEl.value || "",
how_it_works: howEl.value || "",
use_cases: useEl.value || "",
link: linkEl.value || "",
author: byEl.value || "",
tags
});
updateLink();
updateHeader();
renderFilterChips();
}, 150));
}
tagBtn.addEventListener("click", (e) => {
e.preventDefault();
e.stopPropagation();
if(!(titleEl.value || "").trim()) return;
openTagsDialog({
selected: tags,
onApply: (next) => {
tags = next.slice();
setDraft({ tags });
renderTags();
renderFilterChips();
updateHeader();
}
});
});
postBtn.addEventListener("click", () => {
const cur = getDraft();
if(!cur || !draftFilled(cur)) return;
openDialog({
title: "Post this card?",
subtitle: "This will publish the card for everyone to see.",
bodyHtml: `
<label>Password</label>
<input type="password" id="pw" value="" />
`,
primaryText: "Post",
primaryClass: "btn-primary",
canSubmit: (b) => (b.querySelector("#pw").value || "").trim().length > 0,
onSubmit: async (b) => {
const password = (b.querySelector("#pw").value || "").trim();
const payload = {
password,
section: cur.section,
model: cur.model,
tags: cur.tags || [],
how_it_works: cur.how_it_works,
use_cases: cur.use_cases,
link: cur.link,
author: cur.author,
};
const data = await api("/api/cards", {
method: "POST",
body: JSON.stringify(payload),
headers: { "X-Password": password },
});
drafts = drafts.filter(x => x.id !== cur.id);
saveDrafts();
state.version = data.version;
state.published = data.cards;
showErr("");
renderSectionTabs();
renderFilterChips();
render();
},
onOpen: ({backdrop, refresh}) => {
const pw = backdrop.querySelector("#pw");
pw.focus();
pw.addEventListener("input", refresh);
}
});
});
delBtn.addEventListener("click", () => {
if(!confirm("Delete this draft? (Only on your computer.)")) return;
drafts = drafts.filter(x => x.id !== d.id);
saveDrafts();
renderSectionTabs();
renderFilterChips();
render();
});
[titleEl, howEl, useEl, linkEl, byEl].forEach(el => el.addEventListener("input", scheduleDraftSave));
sectionEl.addEventListener("change", () => {
setDraft({ section: normalizeSection(sectionEl.value) });
renderSectionTabs();
renderFilterChips();
render();
});
updateLink();
renderTags();
updateHeader();
grid.appendChild(card);
});
// Published
visiblePublished.forEach((c) => {
const card = document.createElement("div");
card.className = "card";
const tags = Array.isArray(c.tags) ? c.tags.map(String) : [];
const section = normalizeSection(c.section);
card.innerHTML = `
<div class="card-header">
<div class="header-left">
<div class="title-text">${escapeHtml(c.model || "")}</div>
<div class="tag-bar">
${tags.map(t => `<span class="tag-chip" style="cursor:default;">${escapeHtml(t)}</span>`).join("")}
</div>
</div>
<div class="hdr-right">
<span class="section-pill">${escapeHtml(section)}</span>
<button class="edit-btn" type="button">Edit</button>
<button class="del-btn" type="button" title="Delete published">×</button>
</div>
</div>
<div class="card-main">
<div class="panel">
<label>How it Works</label>
<textarea readonly>${escapeHtml(c.how_it_works || "")}</textarea>
</div>
<div class="panel">
<label>Use Cases</label>
<textarea readonly>${escapeHtml(c.use_cases || "")}</textarea>
</div>
</div>
<div class="card-footer">
<div class="footer-row">
<div class="section-col">
<label>Tab</label>
<select disabled>${sectionOptions(section)}</select>
</div>
<div class="link-col">
<label>Link</label>
<input readonly value="${escapeAttr(c.link || "")}" />
<div class="linkwrap"></div>
</div>
<div class="by-col">
<div class="by-display">${c.author ? ("By: " + escapeHtml(c.author)) : ""}</div>
</div>
</div>
</div>
`;
const linkWrap = card.querySelector(".linkwrap");
const editBtn = card.querySelector(".edit-btn");
const delBtn = card.querySelector(".del-btn");
const url = (c.link || "").trim();
linkWrap.innerHTML = url
? `<a class="resource-link" href="${escapeAttr(url)}" target="_blank" rel="noopener noreferrer">Open link</a>`
: "";
delBtn.addEventListener("click", () => {
openDialog({
title: "Delete published card?",
subtitle: "This is permanent and affects everyone viewing this Space.",
bodyHtml: `
<div class="checklist" style="margin-bottom:10px;">
<div class="checkrow">
<input type="checkbox" id="c1"/>
<div class="lbl">I understand this is permanent</div>
</div>
<div class="checkrow">
<input type="checkbox" id="c2"/>
<div class="lbl">I confirm I want to delete this card</div>
</div>
</div>
<label>Password</label>
<input type="password" id="pw" value="" />
`,
primaryText: "Delete",
primaryClass: "btn-danger",
canSubmit: (b) => b.querySelector("#c1").checked
&& b.querySelector("#c2").checked
&& (b.querySelector("#pw").value || "").trim().length > 0,
onSubmit: async (b) => {
const password = (b.querySelector("#pw").value || "").trim();
const data = await api(`/api/cards/${encodeURIComponent(c.id)}`, {
method: "DELETE",
headers: { "X-Password": password },
});
state.version = data.version;
state.published = data.cards || [];
showErr("");
renderSectionTabs();
renderFilterChips();
render();
},
onOpen: ({backdrop, refresh}) => {
const pw = backdrop.querySelector("#pw");
const c1 = backdrop.querySelector("#c1");
const c2 = backdrop.querySelector("#c2");
pw.focus();
[pw, c1, c2].forEach(el => el.addEventListener("input", refresh));
[c1, c2].forEach(el => el.addEventListener("change", refresh));
}
});
});
editBtn.addEventListener("click", () => {
let tagsLocal = tags.slice();
openDialog({
title: "Edit & Republish",
subtitle: "Edits go live only after you enter the password and republish.",
bodyHtml: `
<div style="display:grid; gap:10px;">
<div>
<label>Model</label>
<input id="m" type="text" value="${escapeAttr(c.model || "")}" />
</div>
<div>
<label>Tab</label>
<select id="s">${sectionOptions(section)}</select>
</div>
<div>
<label>Tags</label>
<div id="tags" style="display:flex; flex-wrap:wrap; gap:8px; align-items:center;"></div>
<div style="margin-top:8px;">
<button class="tag-btn" id="tagBtn" type="button">Tags</button>
</div>
</div>
<div>
<label>How it Works</label>
<textarea id="h" style="height:90px;">${escapeHtml(c.how_it_works || "")}</textarea>
</div>
<div>
<label>Use Cases</label>
<textarea id="u" style="height:90px;">${escapeHtml(c.use_cases || "")}</textarea>
</div>
<div class="footer-row" style="align-items:flex-end;">
<div class="link-col">
<label>Link</label>
<input id="l" type="text" value="${escapeAttr(c.link || "")}" />
</div>
<div class="by-col" style="padding-bottom:2px;">
<span>By:</span>
<input id="a" class="by-input" type="text" value="${escapeAttr(c.author || "")}" placeholder="name" />
</div>
</div>
<div>
<label>Password</label>
<input id="pw" type="password" value="" />
</div>
</div>
`,
primaryText: "Republish",
primaryClass: "btn-primary",
canSubmit: (b) => (b.querySelector("#pw").value || "").trim().length > 0
&& (b.querySelector("#m").value || "").trim().length > 0
&& (b.querySelector("#h").value || "").trim().length > 0
&& (b.querySelector("#u").value || "").trim().length > 0,
onSubmit: async (b) => {
const password = (b.querySelector("#pw").value || "").trim();
const payload = {
password,
section: normalizeSection(b.querySelector("#s").value || "Models"),
model: b.querySelector("#m").value || "",
tags: tagsLocal,
how_it_works: b.querySelector("#h").value || "",
use_cases: b.querySelector("#u").value || "",
link: b.querySelector("#l").value || "",
author: b.querySelector("#a").value || "",
};
const data = await api(`/api/cards/${encodeURIComponent(c.id)}`, {
method: "PUT",
body: JSON.stringify(payload),
headers: { "X-Password": password },
});
state.version = data.version;
state.published = data.cards || [];
showErr("");
renderSectionTabs();
renderFilterChips();
render();
},
onOpen: ({backdrop, refresh}) => {
const tagsWrap = backdrop.querySelector("#tags");
const tagBtn = backdrop.querySelector("#tagBtn");
const pw = backdrop.querySelector("#pw");
function renderEditTags(){
tagsWrap.innerHTML = "";
tagsLocal.forEach(t => {
const chip = document.createElement("span");
chip.className = "tag-chip";
chip.innerHTML = `${escapeHtml(t)} <span class="rm">×</span>`;
chip.addEventListener("click", (e) => {
e.preventDefault();
tagsLocal = tagsLocal.filter(x => x !== t);
renderEditTags();
renderFilterChips();
refresh();
});
tagsWrap.appendChild(chip);
});
}
tagBtn.addEventListener("click", (e) => {
e.preventDefault();
openTagsDialog({
selected: tagsLocal,
onApply: (next) => {
tagsLocal = next.slice();
renderEditTags();
renderFilterChips();
refresh();
}
});
});
["m","h","u","l","a","pw"].forEach(id => {
backdrop.querySelector("#" + id).addEventListener("input", refresh);
});
backdrop.querySelector("#s").addEventListener("change", refresh);
pw.focus();
renderEditTags();
refresh();
}
});
});
grid.appendChild(card);
});
}
addBtn.addEventListener("click", () => {
drafts.unshift({
id: uid(),
section: currentSection,
model:"",
tags:[],
how_it_works:"",
use_cases:"",
link:"",
author:""
});
saveDrafts();
renderSectionTabs();
renderFilterChips();
render();
});
async function refreshPublished(){
try{
const active = document.activeElement;
const isTyping = active && (active.tagName === "INPUT" || active.tagName === "TEXTAREA" || active.tagName === "SELECT");
if(isTyping) return;
const data = await api("/api/cards", { method: "GET" });
if(data.version !== state.version){
state.version = data.version;
state.published = data.cards || [];
showErr("");
renderSectionTabs();
renderFilterChips();
render();
}
}catch(e){
showErr(String(e.message || e));
}
}
(async () => {
saveCurrentSection();
await refreshPublished();
renderSectionTabs();
renderFilterChips();
render();
setInterval(refreshPublished, 2500);
})();
})();
"""
),
)
def shiny_server(input, output, session):
pass
app_shiny = App(app_ui, shiny_server)
routes = [
Route("/api/cards", endpoint=api_cards, methods=["GET", "POST"]),
Route("/api/cards/{card_id}", endpoint=api_card_id, methods=["PUT", "DELETE"]),
Mount("/", app=app_shiny),
]
app = Starlette(routes=routes) |