Spaces:
Running on Zero
Running on Zero
File size: 192,445 Bytes
e9017a4 028a9fb e9017a4 028a9fb e9017a4 60496a4 e9017a4 baef816 e9017a4 60496a4 e9017a4 028a9fb e9017a4 60496a4 e9017a4 028a9fb e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 028a9fb e9017a4 028a9fb e9017a4 028a9fb e9017a4 028a9fb e9017a4 028a9fb e9017a4 028a9fb e9017a4 028a9fb e9017a4 028a9fb e9017a4 60496a4 028a9fb 60496a4 028a9fb 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 028a9fb e9017a4 028a9fb e9017a4 cf10489 e9017a4 cf10489 e9017a4 cf10489 e9017a4 cf10489 e9017a4 cf10489 e9017a4 cf10489 e9017a4 cf10489 e9017a4 cf10489 e9017a4 60496a4 e9017a4 baef816 e9017a4 028a9fb 60496a4 028a9fb e9017a4 fa01890 e9017a4 fa01890 e9017a4 fa01890 e9017a4 60496a4 e9017a4 fa01890 e9017a4 fa01890 e9017a4 fa01890 e9017a4 60496a4 e9017a4 8fce9f2 e9017a4 8fce9f2 e9017a4 cf10489 e9017a4 d590f1a cf10489 d590f1a cf10489 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 8fce9f2 dba8ed1 8fce9f2 dba8ed1 8fce9f2 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 dba8ed1 e9017a4 4296095 e9017a4 4296095 f42085f 4296095 e9017a4 4296095 e9017a4 f42085f e9017a4 60496a4 cf10489 4296095 e9017a4 cf10489 f42085f cf10489 f42085f 4296095 60496a4 4296095 f42085f 4296095 f42085f 4296095 e9017a4 4296095 e9017a4 f42085f 4296095 f42085f 4296095 f42085f 4296095 e9017a4 f42085f e9017a4 4296095 d590f1a e9017a4 f42085f e9017a4 f42085f 4296095 e9017a4 4296095 f42085f 4296095 f42085f e9017a4 f42085f 4296095 e9017a4 f42085f 4296095 f42085f e9017a4 f42085f 4296095 f42085f e9017a4 4296095 e9017a4 028a9fb e9017a4 fa01890 028a9fb dba8ed1 028a9fb dba8ed1 028a9fb dba8ed1 028a9fb 60496a4 e9017a4 8fce9f2 e9017a4 028a9fb dba8ed1 60496a4 e9017a4 cf10489 f42085f cf10489 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 f42085f d590f1a f42085f dba8ed1 f42085f fa01890 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 4296095 e9017a4 4296095 e9017a4 60496a4 e9017a4 4296095 e9017a4 f42085f e9017a4 cf10489 4296095 cf10489 4296095 cf10489 4296095 cf10489 4296095 cf10489 d590f1a cf10489 d590f1a 4296095 cf10489 4296095 d590f1a e9017a4 cf10489 f42085f cf10489 f42085f cf10489 f42085f cf10489 f42085f cf10489 f42085f cf10489 f42085f e9017a4 cf10489 e9017a4 cf10489 e9017a4 cf10489 e9017a4 cf10489 e9017a4 f42085f cf10489 4296095 cf10489 e9017a4 4296095 cf10489 f42085f cf10489 f42085f cf10489 e9017a4 f42085f cf10489 e9017a4 4296095 e9017a4 cf10489 4296095 e9017a4 4296095 cf10489 e9017a4 f42085f cf10489 4296095 e9017a4 f42085f cf10489 4296095 e9017a4 4296095 f42085f cf10489 f42085f cf10489 f42085f cf10489 f42085f 4296095 cf10489 f42085f e9017a4 8fce9f2 e9017a4 8fce9f2 e9017a4 8fce9f2 e9017a4 8fce9f2 e9017a4 8fce9f2 e9017a4 8fce9f2 e9017a4 8fce9f2 e9017a4 8fce9f2 e9017a4 d590f1a e9017a4 d590f1a e9017a4 d590f1a e9017a4 d590f1a e9017a4 d590f1a e9017a4 d590f1a e9017a4 d590f1a e9017a4 cf10489 f42085f cf10489 f42085f cf10489 4296095 cf10489 e9017a4 f42085f cf10489 4296095 f42085f e9017a4 f42085f e9017a4 cf10489 e9017a4 cf10489 e9017a4 cf10489 e9017a4 f42085f e9017a4 f42085f cf10489 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 e9017a4 cf10489 e9017a4 cf10489 e9017a4 cf10489 e9017a4 cf10489 e9017a4 60496a4 cf10489 e9017a4 cf10489 e9017a4 cf10489 e9017a4 60496a4 e9017a4 60496a4 e9017a4 cf10489 60496a4 cf10489 e9017a4 fa01890 e9017a4 8fce9f2 e9017a4 60496a4 e9017a4 4296095 60496a4 8fce9f2 cf10489 4296095 f42085f 4296095 e9017a4 8fce9f2 cf10489 8fce9f2 60496a4 8fce9f2 60496a4 8fce9f2 cf10489 4296095 e9017a4 8fce9f2 cf10489 f42085f 8fce9f2 dba8ed1 8fce9f2 cf10489 f42085f e9017a4 d590f1a e9017a4 d590f1a e9017a4 8fce9f2 cf10489 4296095 d590f1a e9017a4 4296095 d590f1a e9017a4 4296095 e9017a4 4296095 e9017a4 4296095 d590f1a 4296095 e9017a4 cf10489 4296095 d590f1a 4296095 d590f1a 4296095 d590f1a e9017a4 cf10489 e9017a4 4296095 cf10489 4296095 cf10489 4296095 dba8ed1 e9017a4 cf10489 e9017a4 cf10489 e9017a4 cf10489 e9017a4 8fce9f2 e9017a4 60496a4 028a9fb 60496a4 e9017a4 028a9fb e9017a4 028a9fb e9017a4 028a9fb e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 60496a4 e9017a4 028a9fb e9017a4 60496a4 e9017a4 028a9fb dba8ed1 028a9fb 8fce9f2 e9017a4 fa01890 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 | """Qwen-Image-2.1 Uncensored All-In-One LoRA Studio.
Base Model: KasugaiSakura/Qwen-Image-2.1-Uncensored-Abenzerps-GGUF (qwen-image-2.1-UC-Q4_K_M.gguf)
Powered by Hugging Face ZeroGPU with on-demand All-In-One LoRAs and Dynamic Hub Explorer.
"""
# Rule 1: import spaces FIRST before importing torch or any CUDA-touching library
import importlib.util
import math
import os
# Configure memory allocator before heavy operations
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
def safe_float(val, fallback: float = 1.0, min_val: float | None = 0.0, max_val: float | None = 1.5) -> float:
"""Safely coerce any value to a finite float within [min_val, max_val]."""
try:
if val is None or val == "":
f = fallback
else:
f = float(val)
if math.isnan(f) or math.isinf(f):
f = fallback
except (ValueError, TypeError):
f = fallback
if min_val is not None:
f = max(min_val, f)
if max_val is not None:
f = min(max_val, f)
return float(f)
def safe_int(val, fallback: int, min_val: int | None = None, max_val: int | None = None) -> int:
"""Safely coerce any value to a bounded int."""
try:
if val is None or val == "":
i = fallback
else:
f = float(val)
if math.isnan(f) or math.isinf(f):
i = fallback
else:
i = int(round(f))
except (ValueError, TypeError, OverflowError):
i = fallback
if min_val is not None:
i = max(min_val, i)
if max_val is not None:
i = min(max_val, i)
return int(i)
DEFAULT_LORA = "Viggle Turbo (6-Step Acceleration)"
AUTO = "Auto · Match Input Image (or 1024²)"
CUSTOM = "Custom · Set Width & Height"
MODEL_GGUF = "Uncensored GGUF (Q4_K_M)"
MODEL_ORIGINAL = "Qwen Original (BF16)"
BASE_MODEL_CHOICES = [MODEL_GGUF, MODEL_ORIGINAL]
CURRENT_LOADED_MODEL = None
def calculate_dimensions(area, ratio):
w = max(32, int((area * ratio) ** 0.5) // 32 * 32)
h = max(32, int((area / ratio) ** 0.5) // 32 * 32)
return w, h, None
RATIOS = [
("1:1", 1.0),
("16:9", 16 / 9),
("9:16", 9 / 16),
("4:3", 4 / 3),
("3:4", 3 / 4),
("3:2", 3 / 2),
("2:3", 2 / 3),
("21:9", 21 / 9),
]
def _bucket(area):
sizes = {}
for name, ratio in RATIOS:
width, height, _ = calculate_dimensions(area * area, ratio)
sizes[f"{name} · {width}×{height} ({area}² area)"] = (width, height)
return sizes
SIZES = {
AUTO: None,
**_bucket(1024),
**_bucket(1536),
**_bucket(2048),
CUSTOM: None,
}
MAX_SEED = 2**31 - 1
def estimate_duration(prompt="", mode="Text to Image", ref_image_1=None, ref_image_2=None,
lora_adapter=DEFAULT_LORA, lora_strength=1.0,
custom_repo="", custom_file="", aspect_ratio=AUTO,
steps=6, seed=42, randomize_seed=True,
custom_width=1024, custom_height=1024,
base_model=MODEL_GGUF, *args, **kwargs):
"""Estimate needed GPU runtime (in seconds) to avoid over-reserving ZeroGPU quota."""
base_time = 15.0
step_val = safe_int(steps, fallback=6, min_val=1, max_val=40)
lora_strength = safe_float(lora_strength, fallback=1.0, min_val=0.0, max_val=1.5)
step_factor = step_val / 20.0
is_two_ref = mode == "Transform & Swap (2 Refs)" and ref_image_1 is not None and ref_image_2 is not None
is_one_ref = mode == "Edit Image (1 Ref)" and ref_image_1 is not None
ref_factor = 1.35 if is_two_ref else (1.15 if is_one_ref else 1.0)
is_swap = (base_model and CURRENT_LOADED_MODEL and str(base_model) != str(CURRENT_LOADED_MODEL))
swap_allowance = 30.0 if is_swap else 0.0
est = (base_time * step_factor * ref_factor) + swap_allowance
duration = min(120, max(15, int(round(est))))
print(f"[spaces] dynamic duration estimated: {duration}s (steps={step_val}, mode={mode}, lora={lora_adapter}, base={base_model})", flush=True)
return duration
if importlib.util.find_spec("spaces"):
import spaces
gpu = spaces.GPU(duration=estimate_duration, size="xlarge")
else:
gpu = lambda fn: fn # noqa: E731
import copy
import hashlib
import html as _html
import json
import random
import subprocess
import sys
import tempfile
import time
from pathlib import Path
import gradio as gr
from PIL import Image, ImageOps, ImageDraw, PngImagePlugin
from huggingface_hub import HfApi, hf_hub_download
# ============================================================
# Defensive Slider Preprocessing Guard
# ============================================================
_orig_slider_preprocess = gr.Slider.preprocess
def _safe_slider_preprocess(self, payload):
if payload is None or (isinstance(payload, float) and (math.isnan(payload) or math.isinf(payload))):
payload = self.value if self.value is not None else (self.minimum if self.minimum is not None else 0.0)
return _orig_slider_preprocess(self, payload)
gr.Slider.preprocess = _safe_slider_preprocess
IS_PREVIEW = os.environ.get("UI_PREVIEW") == "1"
# ============================================================
# Model & Checkpoint Configuration (Uncensored GGUF)
# ============================================================
MODEL_ID = "KasugaiSakura/Qwen-Image-2.1-Uncensored-Abenzerps-GGUF"
CHECKPOINT = os.environ.get("QWEN_GGUF_CHECKPOINT", "qwen-image-2.1-UC-Q4_K_M.gguf")
COMPANION_ID = "Qwen/Qwen-Image-2.1"
COMPANION_REVISION = "790c92633540aa0cb11d9abf19eb46d861714758"
HF_TOKEN = os.environ.get("HF_TOKEN")
SHA256_CHECKSUMS = {
"qwen-image-2.1-UC-Q4_K_M.gguf": "e79c8a009f2ecbdb6c70fd663d9aea9ee304a0d91f347e4169a756b8ad141b41",
"qwen-image-2.1-UC-Q4_0.gguf": "13f59f20656efc0aa385d03c1fcac1a9dc2ad6e5ccc0ea9bfe1d6ac636f2c5b9",
"qwen-image-2.1-UC-Q5_K_M.gguf": "af0bf278cf16d204fb31c384dc82fd41dca82d976b15fe9305a60c726fd6f821",
"qwen-image-2.1-UC-Q6_K.gguf": "e14bb312109333b3d73b92ad9b9ac8b29b51f2edca1e7b86d1af1981bf1c4ee3",
"qwen-image-2.1-UC-Q8_0.gguf": "cde456c72ea3ecebfc1be783300e972711d875e0c5f1bed33d42b66b156affa8",
"qwen-image-2.1-UC-BF16.gguf": "f151c683a8aed4b310777017ebbbe3f2180f1180f7867115171adb7d50b0762a",
}
MODES = ["Text to Image", "Edit Image (1 Ref)", "Transform & Swap (2 Refs)", "Transparent PNG"]
# ============================================================
# Curated All-In-One LoRA Specifications & Triggers
# ============================================================
NONE_LORA = "None (Base Uncensored)"
CUSTOM_HF_LORA = "Custom HuggingFace LoRA..."
EXPLORED_LORA = "Dynamic Hugging Face LoRA"
FACE_PROMPT = (
"head_swap: start with <image1> as the base image, keeping its lighting, environment, and background. "
"remove the head from <image1> completely and replace it with the head from <image2>, strictly preserving "
"the hair, eye color, nose structure from <image2>. copy the direction of the eye, head rotation, micro "
"expressions from <image1>, high quality, sharp details, 4k"
)
BODY_PROMPT = (
"body_swap: start with <image1> as the base image, keeping its lighting, environment, and background. "
"replace the body from <image1> with the body from <image2>, strictly preserving the clothing, body shape "
"and proportions from <image2>. copy the pose, direction of the eye, head rotation, micro expressions "
"from <image1>"
)
RESTORE_PROMPT = (
"Restore the photo: remove blur, noise and compression artifacts and recover sharp, natural detail, "
"keeping the same composition, people and colors."
)
ADAPTER_SPECS = {
"Real Characters & Anatomy": {
"repo": "WarmBloodAban/Qwen-Image-2.1-LoRAs",
"weights": "Qwen2.1_Anything2RealCharacters.safetensors",
"adapter_name": "real_characters_anatomy",
"default_strength": 0.85,
"default_steps": 28,
"preset_prompt": "photorealistic portrait, natural human anatomy, detailed skin pores, realistic body proportions, soft lighting",
"category": "Anatomy & Realism",
},
"Face / Head Swap (BFS 2.1)": {
"repo": "Alissonerdx/BFS-Best-Face-Swap",
"weights": "bfs_head_v1.1_qwen_2.1.safetensors",
"adapter_name": "bfs_head_21",
"default_strength": 1.0,
"default_steps": 6,
"mode": "Transform & Swap (2 Refs)",
"requires_two_images": True,
"image1_label": "Image 1 (Base Body / Scene)",
"image2_label": "Image 2 (Face Donor to transfer)",
"exact_prompt": True,
"preset_prompt": FACE_PROMPT,
"category": "Face & Identity",
},
"Face / Head Swap - Strong Expression (BFS alt)": {
"repo": "Alissonerdx/BFS-Best-Face-Swap",
"weights": "bfs_head_v1.1_alternative_qwen_2.1.safetensors",
"adapter_name": "bfs_head_21_alt",
"default_strength": 1.0,
"default_steps": 6,
"mode": "Transform & Swap (2 Refs)",
"requires_two_images": True,
"image1_label": "Image 1 (Base Body / Scene)",
"image2_label": "Image 2 (Face Donor to transfer)",
"exact_prompt": True,
"preset_prompt": FACE_PROMPT,
"category": "Face & Identity",
},
"Pose / Body Swap (BFS Body 2.1)": {
"repo": "Alissonerdx/BFS-Best-Face-Swap",
"weights": "bfs_body_swap_v1.0_qwen_2.1.safetensors",
"adapter_name": "bfs_body_21",
"default_strength": 1.0,
"default_steps": 6,
"mode": "Transform & Swap (2 Refs)",
"requires_two_images": True,
"image1_label": "Image 1 (Base Scene / Person)",
"image2_label": "Image 2 (Pose & Body Reference)",
"exact_prompt": True,
"preset_prompt": BODY_PROMPT,
"category": "Anatomy & Realism",
},
"Upscale / Restore (Restore LoRA 2.1)": {
"repo": "ausboss/Qwen-Image-2.1-Restore-LoRA",
"weights": "qwen-image-2.1-restore.safetensors",
"adapter_name": "restore_21",
"default_strength": 1.0,
"default_steps": 25,
"mode": "Edit Image (1 Ref)",
"auto_resize_mp": 2.0,
"exact_prompt": True,
"preset_prompt": RESTORE_PROMPT,
"category": "Utility",
},
"Light Restoration (Natural Exposure)": {
"repo": "prithivMLmods/Qwen-Image-2.1-Natural-Exposure-LoRA",
"weights": "Qwen-Image-2.1-Natural-Exposure-LoRA-4000.safetensors",
"adapter_name": "natural_exposure",
"default_strength": 0.8,
"default_steps": 30,
"mode": "Edit Image (1 Ref)",
"exact_prompt": True,
"preset_prompt": "Transform the image with balanced neutral exposure and realistic studio lighting",
"category": "Lighting",
},
"Photo Aesthetics & Skin Details": {
"repo": "SimpleTuner/Qwen-Image-2.1-LoRA-photo-aesthetics-v2",
"weights": "pytorch_lora_weights.safetensors",
"adapter_name": "photo_aesthetics_v2",
"default_strength": 0.8,
"default_steps": 28,
"preset_prompt": "DSLR quality photo, natural skin texture, depth of field, 85mm lens, high resolution",
"category": "Lighting & Realism",
},
"Casual Phone Photo Realism": {
"repo": "19nbrown/qwen-image-2.1-casual-phone-photo-style-lora",
"weights": "qwen-image-2.1-casual-phone-photo-style-lora.safetensors",
"adapter_name": "phone_photo_realism",
"default_strength": 0.85,
"default_steps": 28,
"preset_prompt": "candid snapshot, phone camera aesthetic, natural ambient light, unedited authentic photo",
"category": "Lighting & Realism",
},
"Outfit & Fashion Swap": {
"repo": "ausboss/Qwen-Image-2.1-Outfit-Swap-Consistency-LoRA",
"weights": "qwen-image-2.1-outfit-swap.safetensors",
"adapter_name": "outfit_swap_21",
"default_strength": 0.9,
"default_steps": 28,
"preset_prompt": "outfit_swap: replace clothing with consistent detailed fashion garments",
"category": "Utility",
},
"Skin Retouch (base model, no LoRA)": {
"no_lora": True,
"default_strength": 1.0,
"default_steps": 30,
"mode": "Edit Image (1 Ref)",
"exact_prompt": True,
"preset_prompt": (
"Retouch the skin: remove blemishes, shine and uneven tone while keeping natural pores and texture. "
"Keep the identity, expression, pose, lighting and background unchanged."
),
"category": "Utility",
},
"Anime Consistency": {
"repo": "WarmBloodAban/Qwen-Image-2.1-LoRAs",
"weights": "Qwen2.1_Anime_consistency.safetensors",
"adapter_name": "anime_consistency",
"default_strength": 0.85,
"default_steps": 28,
"preset_prompt": "masterpiece, highly detailed anime illustration, vibrant colors, expressive eyes",
"category": "Style",
},
"Viggle Turbo (6-Step Acceleration)": {
"repo": "Viggle/Qwen-Image-2.1-viggle-turbo",
"weights": "Qwen-Image-2.1-viggle-turbo-v0.3-6step-lora-r256.safetensors",
"adapter_name": "viggle_turbo",
"default_strength": 1.0,
"default_steps": 6,
"preset_prompt": "",
"category": "Turbo Speed",
},
}
LORA_CHOICES = [NONE_LORA] + list(ADAPTER_SPECS.keys()) + [CUSTOM_HF_LORA, EXPLORED_LORA]
LOADED_ADAPTERS = set()
# ============================================================
# Pipeline Initialization (Dual Base Model: GGUF & Original BF16)
# ============================================================
try:
import torch
from safetensors.torch import load_file as safetensors_load_file
except ImportError:
torch = None
safetensors_load_file = None
pipe = None
base_scheduler = None
turbo_scheduler = None
CURRENT_LOADED_MODEL = None
def load_pipeline_for_model(model_name: str = MODEL_GGUF):
"""Load or lazily swap the base model pipeline. Frees previous model first to honor ZeroGPU memory limits."""
global pipe, base_scheduler, turbo_scheduler, CURRENT_LOADED_MODEL, LOADED_ADAPTERS
if IS_PREVIEW or torch is None:
CURRENT_LOADED_MODEL = model_name
return
# Check if already loaded
if pipe is not None and CURRENT_LOADED_MODEL == model_name:
return
# 1. Cleanly free old pipeline from VRAM before allocating new one
if pipe is not None:
print(f"[model] Freeing previous model ({CURRENT_LOADED_MODEL}) from VRAM...", flush=True)
try:
del pipe
except Exception:
pass
pipe = None
base_scheduler = None
turbo_scheduler = None
LOADED_ADAPTERS.clear()
if torch.cuda.is_available():
torch.cuda.empty_cache()
try:
from accelerate import init_empty_weights
from diffusers import QwenImage21Pipeline, QwenImage21Transformer2DModel, FlowMatchEulerDiscreteScheduler
if model_name == MODEL_GGUF:
from diffusers.models.model_loading_utils import load_gguf_checkpoint
from diffusers.quantizers.gguf.utils import dequantize_gguf_tensor
print(f"[model] Loading GGUF checkpoint {CHECKPOINT} from {MODEL_ID}...", flush=True)
checkpoint_path = hf_hub_download(MODEL_ID, CHECKPOINT, token=HF_TOKEN)
if CHECKPOINT in SHA256_CHECKSUMS:
with open(checkpoint_path, "rb") as f:
checksum = hashlib.file_digest(f, "sha256").hexdigest()
if checksum != SHA256_CHECKSUMS[CHECKPOINT]:
raise RuntimeError(f"Checksum verification failed for {CHECKPOINT}! Got {checksum}")
print(f"Checksum verified: {checksum}", flush=True)
weights = load_gguf_checkpoint(checkpoint_path)
for name in list(weights.keys()):
weights[name] = dequantize_gguf_tensor(weights[name]).to(torch.bfloat16)
config = QwenImage21Transformer2DModel.load_config(
COMPANION_ID, subfolder="transformer", revision=COMPANION_REVISION, token=HF_TOKEN
)
with init_empty_weights():
transformer = QwenImage21Transformer2DModel.from_config(config)
transformer.load_state_dict(weights, strict=True, assign=True)
transformer.eval().requires_grad_(False)
print(f"[model] Loaded {len(weights)} tensors into QwenImage21Transformer2DModel.", flush=True)
del weights
pipe = QwenImage21Pipeline.from_pretrained(
COMPANION_ID,
revision=COMPANION_REVISION,
transformer=transformer,
torch_dtype=torch.bfloat16,
token=HF_TOKEN,
).to("cuda")
else:
# Original Qwen/Qwen-Image-2.1 BF16 Base Model (official weights)
print(f"[model] Loading original BF16 base pipeline from {COMPANION_ID}...", flush=True)
pipe = QwenImage21Pipeline.from_pretrained(
COMPANION_ID,
revision=COMPANION_REVISION,
torch_dtype=torch.bfloat16,
token=HF_TOKEN,
).to("cuda")
# Patch visual embed forward optimization
try:
patch_embed = pipe.text_encoder.model.visual.patch_embed
def _patch_embed_forward(hidden_states):
proj = patch_embed.proj
weight = proj.weight.reshape(proj.weight.shape[0], -1)
return hidden_states.to(weight.dtype).flatten(1) @ weight.T + proj.bias
patch_embed.forward = _patch_embed_forward
print("[model] patch_embed fast path initialized.", flush=True)
except Exception as exc:
print(f"[model] patch_embed fast path notice: {exc!r}", flush=True)
# Base and Turbo Schedulers
base_scheduler = pipe.scheduler
try:
turbo_scheduler = FlowMatchEulerDiscreteScheduler.from_config(pipe.scheduler.config, shift_terminal=None)
print("[model] turbo_scheduler (shift_terminal=None) initialized.", flush=True)
except Exception as exc:
print(f"[model] turbo_scheduler notice: {exc!r}", flush=True)
turbo_scheduler = None
CURRENT_LOADED_MODEL = model_name
print(f"[model] Base model successfully loaded: {model_name}", flush=True)
except Exception as e:
print(f"[model] Error initializing base model {model_name}: {e}", flush=True)
pipe = None
base_scheduler = None
turbo_scheduler = None
CURRENT_LOADED_MODEL = None
raise
if not IS_PREVIEW and torch is not None:
try:
load_pipeline_for_model(MODEL_GGUF)
except Exception as e:
print(f"[init] Initial pipeline load failed: {e}", flush=True)
else:
print("[preview] UI Preview mode active (model weights and CUDA skipped).", flush=True)
CURRENT_LOADED_MODEL = MODEL_GGUF
def turbo_sigmas(steps: int):
"""Viggle's raw sigma nodes: keep 0.875/0.75/0.5/0.25, add steps in the 1 -> 0.875 segment."""
steps = min(max(int(steps), 4), 8)
if steps == 4:
return steps, [1.0, 0.75, 0.5, 0.25]
return steps, [1.0 - 0.125 * i / (steps - 4) for i in range(steps - 4)] + [0.875, 0.75, 0.5, 0.25]
def load_bfs_state_dict(repo: str, weight_name: str):
"""Load BFS (Best Face Swap) LoRA and split ComfyUI's fused `img_mlp.gate_up` into diffusers' two linears.
ComfyUI fuses the SwiGLU gate and up projections (gate rows first). A LoRA on the fused
layer is W += B @ A with B stacked [gate; up], so both halves share A and B splits in two.
diffusers' Qwen LoRA converter strips the `diffusion_model.` prefix but does not do this split.
"""
local_path = hf_hub_download(repo_id=repo, filename=weight_name, token=HF_TOKEN)
sd = safetensors_load_file(local_path)
out = {}
for k, v in sd.items():
if ".img_mlp.gate_up." in k:
gate_k = k.replace(".gate_up.", ".gate_layer.")
up_k = k.replace(".gate_up.", ".proj.")
if "lora_B" in k:
gate, up = v.chunk(2, dim=0)
out[gate_k], out[up_k] = gate.contiguous(), up.contiguous()
else:
out[gate_k], out[up_k] = v, v.clone()
else:
out[k] = v
return out
# ============================================================
# LoRA Adapter Loading Helpers
# ============================================================
def _adapter_present(adapter_name: str) -> bool:
try:
listing = pipe.get_list_adapters()
except Exception:
return False
return any(adapter_name in names for names in listing.values())
def _to_peft_transformer_keys(state_dict: dict) -> dict:
norm = {}
for k, v in state_dict.items():
if not isinstance(v, torch.Tensor):
continue
if k.endswith((".diff", ".diff_b")):
continue
if k.startswith("diffusion_model."):
k = k[len("diffusion_model."):]
norm[k] = v
out = {}
for k, v in norm.items():
if k.endswith(".lora_down.weight"):
base = k[: -len(".lora_down.weight")]
up = norm.get(f"{base}.lora_up.weight")
if up is None:
continue
rank = int(v.shape[0])
alpha = norm.get(f"{base}.alpha", norm.get(f"{base}.lora_alpha"))
scale = float(alpha) / rank if alpha is not None else 1.0
out[f"transformer.{base}.lora_A.weight"] = v
out[f"transformer.{base}.lora_B.weight"] = up * scale if scale != 1.0 else up
elif k.endswith((".lora_A.weight", ".lora_B.weight")):
out[f"transformer.{k}"] = v
return out
def _load_lora_with_fallback(repo: str, weight_name: str, adapter_name: str):
# Specialized loader for BFS (Best Face Swap) ComfyUI SwiGLU format
if "Alissonerdx/BFS-Best-Face-Swap" in repo or "bfs_" in weight_name.lower():
try:
print(f"[lora] Loading BFS LoRA with ComfyUI SwiGLU split: {repo} / {weight_name}", flush=True)
split_sd = load_bfs_state_dict(repo, weight_name)
pipe.load_lora_weights(split_sd, adapter_name=adapter_name)
if _adapter_present(adapter_name):
print(f"[lora] BFS '{adapter_name}' loaded successfully via SwiGLU converter.", flush=True)
return
except Exception as e:
print(f"[lora] BFS custom loader notice: {e}, attempting native loader...", flush=True)
try:
pipe.load_lora_weights(repo, weight_name=weight_name, adapter_name=adapter_name, token=HF_TOKEN)
except Exception as e:
print(f"[lora] Native loader notice for '{adapter_name}': {e}", flush=True)
if _adapter_present(adapter_name):
print(f"[lora] '{adapter_name}' loaded via native loader.", flush=True)
return
print(f"[lora] Native loader did not register '{adapter_name}', attempting manual conversion...", flush=True)
local_path = hf_hub_download(repo_id=repo, filename=weight_name, token=HF_TOKEN)
raw = safetensors_load_file(local_path)
sd = _to_peft_transformer_keys(raw)
if not sd:
raise gr.Error(f"LoRA '{weight_name}': No recognizable LoRA tensors found in file.")
module_names = {n for n, _ in pipe.transformer.named_modules()}
a_suffix = ".lora_A.weight"
matched = sum(1 for k in sd if k.endswith(a_suffix) and k[len("transformer."): -len(a_suffix)] in module_names)
total = sum(1 for k in sd if k.endswith(a_suffix))
if matched == 0:
raise gr.Error(f"LoRA '{adapter_name}' is not compatible with Qwen-Image-2.1 (0/{total} layers matched).")
try:
pipe.load_lora_weights(sd, adapter_name=adapter_name)
except Exception as e:
raise gr.Error(f"Failed to bind LoRA '{adapter_name}': {e}")
if not _adapter_present(adapter_name):
raise gr.Error(f"LoRA '{adapter_name}' failed to register in the pipeline.")
print(f"[lora] '{adapter_name}' successfully loaded via manual conversion.", flush=True)
def ensure_adapter_ready(selected_lora: str, custom_repo: str = "", custom_file: str = "") -> tuple[str, float]:
selected_lora = str(selected_lora or "")
if pipe is None or IS_PREVIEW:
return (selected_lora if selected_lora != NONE_LORA and selected_lora else ""), 1.0
if selected_lora == NONE_LORA or not selected_lora:
return "", 1.0
if selected_lora in (CUSTOM_HF_LORA, EXPLORED_LORA):
repo = (custom_repo or "").strip()
file = (custom_file or "").strip()
if not repo or not file:
raise gr.Error("Please provide both a Hugging Face Repo ID and LoRA filename.")
adapter_name = f"custom_{hashlib.md5((repo + file).encode()).hexdigest()[:8]}"
if adapter_name not in LOADED_ADAPTERS or not _adapter_present(adapter_name):
print(f"[lora] Loading custom LoRA {repo} / {file}...", flush=True)
_load_lora_with_fallback(repo, file, adapter_name)
LOADED_ADAPTERS.add(adapter_name)
return adapter_name, 1.0
spec = ADAPTER_SPECS.get(selected_lora)
if not spec or spec.get("no_lora"):
return "", 1.0
adapter_name = spec["adapter_name"]
if adapter_name not in LOADED_ADAPTERS or not _adapter_present(adapter_name):
print(f"[lora] Loading {selected_lora} ({spec['repo']} / {spec['weights']})...", flush=True)
_load_lora_with_fallback(spec["repo"], spec["weights"], adapter_name)
LOADED_ADAPTERS.add(adapter_name)
return adapter_name, safe_float(spec.get("default_strength"), fallback=1.0, min_val=0.0, max_val=1.5)
# ============================================================
# Hugging Face Hub Dynamic LoRA Explorer
# ============================================================
hf_api = HfApi(token=HF_TOKEN)
def search_hf_loras(query: str = ""):
q = (query or "").strip()
queries_to_try = []
if q:
queries_to_try.extend([f"qwen {q}", f"qwen-image {q}", q])
queries_to_try.extend(["qwen-image-2.1-lora", "qwen lora", "qwen-image-2.1"])
seen = set()
models = []
for s in queries_to_try:
try:
for m in hf_api.list_models(search=s, limit=15):
if m.id not in seen:
seen.add(m.id)
models.append(m)
if len(models) >= 15:
break
except Exception as e:
print(f"[explorer] Search partial error for '{s}': {e}", flush=True)
lora_models = []
for m in models:
is_lora = "lora" in m.id.lower() or any("lora" in str(t).lower() for t in (m.tags or []))
if is_lora or q:
lora_models.append(m)
if not lora_models:
lora_models = models[:10]
choices = [f"{m.id} (likes: {m.likes or 0})" for m in lora_models]
val = choices[0] if choices else None
return gr.update(choices=choices, value=val)
def fetch_repo_safetensors(selected_display: str):
selected_display = (selected_display or "").strip()
if not selected_display:
return gr.update(choices=[], value=None)
repo_id = selected_display.split(" (likes:")[0].strip()
try:
files = hf_api.list_repo_files(repo_id, token=HF_TOKEN)
st_files = [f for f in files if f.endswith(".safetensors")]
if not st_files:
return gr.update(choices=["(No .safetensors found)"], value="(No .safetensors found)")
return gr.update(choices=st_files, value=st_files[0])
except Exception as e:
print(f"[explorer] Error fetching files for {repo_id}: {e}", flush=True)
return gr.update(choices=[], value=None)
def apply_explorer_selection(model_display: str, filename: str):
model_display = (model_display or "").strip()
filename = (filename or "").strip()
if not model_display or not filename or "(No .safetensors" in filename:
raise gr.Error("Please search, select a repository and a valid .safetensors file first.")
repo_id = model_display.split(" (likes:")[0].strip()
status = make_status_banner(EXPLORED_LORA, custom_repo=repo_id, custom_file=filename, strength=1.0)
gr.Info(f"Loaded community LoRA '{filename}' from '{repo_id}'!")
return gr.update(value=EXPLORED_LORA), repo_id, filename, safe_float(1.0, 1.0), status
def apply_custom_selection(repo: str, filename: str):
repo = (repo or "").strip()
filename = (filename or "").strip()
if not repo or not filename:
raise gr.Error("Please enter both a Hugging Face Repo ID and a .safetensors filename.")
status = make_status_banner(CUSTOM_HF_LORA, custom_repo=repo, custom_file=filename, strength=1.0)
gr.Info(f"Loaded custom LoRA '{filename}' from '{repo}'!")
return gr.update(value=CUSTOM_HF_LORA), safe_float(1.0, 1.0), status
def make_status_banner(selected_lora: str, custom_repo: str = "", custom_file: str = "", strength: float = 1.0, base_model: str = MODEL_GGUF) -> str:
selected_lora = (selected_lora or "").strip()
custom_repo = (custom_repo or "").strip()
custom_file = (custom_file or "").strip()
base_model = base_model or MODEL_GGUF
s = safe_float(strength, fallback=1.0, min_val=0.0, max_val=1.5)
base_desc = "Uncensored GGUF Q4_K_M" if base_model == MODEL_GGUF else "Qwen Original BF16"
if selected_lora == NONE_LORA or not selected_lora:
return f'<span class="status-indicator base"></span> <strong style="font-weight:600;">Base Model:</strong> <span>{base_desc} (No LoRA)</span>'
if selected_lora == EXPLORED_LORA:
clean_repo = custom_repo.split("/")[-1] if "/" in custom_repo else custom_repo
return f'<span class="status-indicator active"></span> <strong style="font-weight:600;">Community LoRA:</strong> <span>{clean_repo}</span> <span style="opacity:0.4;">·</span> <span>Weight: {s:.2f}</span> <span style="opacity:0.4;">·</span> <span style="font-size:11px;opacity:0.75;">[{base_desc}]</span>'
if selected_lora == CUSTOM_HF_LORA:
clean_repo = custom_repo.split("/")[-1] if "/" in custom_repo else custom_repo
return f'<span class="status-indicator custom"></span> <strong style="font-weight:600;">Custom LoRA:</strong> <span>{clean_repo}</span> <span style="opacity:0.4;">·</span> <span>Weight: {s:.2f}</span> <span style="opacity:0.4;">·</span> <span style="font-size:11px;opacity:0.75;">[{base_desc}]</span>'
return f'<span class="status-indicator active"></span> <strong style="font-weight:600;">Active LoRA:</strong> <span>{selected_lora}</span> <span style="opacity:0.4;">·</span> <span>Weight: {s:.2f}</span> <span style="opacity:0.4;">·</span> <span style="font-size:11px;opacity:0.75;">[{base_desc}]</span>'
def apply_curated(choice_key: str, current_prompt: str):
choice_key = str(choice_key or "")
current_prompt = str(current_prompt or "")
spec = ADAPTER_SPECS.get(choice_key, {})
preset = spec.get("preset_prompt", "")
new_prompt = current_prompt
if spec.get("exact_prompt") and preset:
new_prompt = preset
elif preset and not current_prompt.strip():
new_prompt = preset
elif preset and preset not in current_prompt:
new_prompt = f"{current_prompt}, {preset}" if current_prompt.strip() else preset
strength = safe_float(spec.get("default_strength"), fallback=1.0, min_val=0.0, max_val=1.5)
steps = safe_int(spec.get("default_steps"), fallback=30, min_val=4, max_val=40)
mode = spec.get("mode", gr.update())
img2_label = gr.update(label=spec.get("image2_label", "Image 2 (Face Donor / Pose Reference)"))
status = make_status_banner(choice_key, strength=strength)
return new_prompt, choice_key, strength, steps, mode, img2_label, status
# ============================================================
# Prompt Presets & Templates Manager
# ============================================================
PROMPT_PRESETS = [
("Real Anatomy", "hyperrealistic 8k raw photograph, anatomically correct human body, perfect hands with 5 fingers, micro skin texture, cinematic lighting", True),
("Body Swap", "seamless body swap composite, maintaining exact facial features and skin tone match, photo studio lighting, high resolution", True),
("Face Swap", "high precision face identity transfer, identical eyes, nose, lips and facial structure, photorealistic blend", True),
("Studio Light", "professional studio portrait, 3-point rim lighting, soft shadow falloff, Hasselblad medium format camera, 85mm lens f/1.4", False),
("Phone Photo", "unfiltered candid smartphone photograph, natural daytime sunlight, subtle film grain, authentic real-life snapshot", False),
("Restore Photo", "restored vintage photograph, ultra high definition remaster, noise removed, rich color grade, crystal sharp focus", False),
]
MAX_PRESETS = 100
PRESET_STORAGE_KEY = "qwen_presets"
DEFAULT_PRESETS = [{"label": l, "text": t, "favorite": f} for l, t, f in PROMPT_PRESETS]
def normalize_presets(raw) -> list:
if isinstance(raw, dict):
raw = raw.get("presets", [])
if not isinstance(raw, list):
return []
out, seen = [], set()
for x in raw:
if not isinstance(x, dict):
continue
label = str(x.get("label", "")).strip()[:40]
text = str(x.get("text", x.get("prompt", ""))).strip()[:4000]
if not label or not text or label in seen:
continue
seen.add(label)
out.append({"label": label, "text": text, "favorite": bool(x.get("favorite", x.get("fav", False)))})
if len(out) >= MAX_PRESETS:
break
return out
def _chip(p: dict) -> str:
label = _html.escape(p["label"], quote=True)
text = _html.escape(p["text"], quote=True)
tip = _html.escape(p["text"][:200], quote=True)
fav = p.get("favorite", False)
fav_cls = "pp-fav is-on" if fav else "pp-fav"
star_svg = (
'<svg class="pp-star-svg filled" width="12" height="12" viewBox="0 0 24 24" fill="#f59e0b" stroke="#f59e0b" stroke-width="2"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>'
if fav
else '<svg class="pp-star-svg outline" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>'
)
return (
f'<div class="pp-item" data-label="{label}" data-text="{text}">'
f'<button type="button" class="pp-use" title="{tip}">{label}</button>'
f'<button type="button" class="{fav_cls}" title="Toggle favorite">{star_svg}</button></div>'
)
def render_presets_html(presets) -> str:
presets = normalize_presets(presets)
sorted_presets = sorted(presets, key=lambda x: not x.get("favorite", False))
chips_html = "".join(_chip(p) for p in sorted_presets)
return f'<div id="presets-list" class="pp-list">{chips_html}</div>'
def apply_preset_cmd(cmd: str, presets) -> list:
presets = normalize_presets(presets)
try:
data = json.loads(cmd or "")
except Exception:
return presets
if not isinstance(data, dict):
return presets
op = data.get("op")
if op == "fav":
for p in presets:
if p["label"] == data.get("label"):
p["favorite"] = not p["favorite"]
elif op == "order":
labels = data.get("labels") or []
by_label = {p["label"]: p for p in presets}
ordered = [by_label[l] for l in labels if l in by_label]
used = {p["label"] for p in ordered}
ordered += [p for p in presets if p["label"] not in used]
presets = ordered
return presets
def save_custom_preset(label: str, prompt: str, presets):
presets = normalize_presets(presets)
label = (label or "").strip()[:40]
text = (prompt or "").strip()
if not label:
raise gr.Error("Please type a name for the template.")
if not text:
raise gr.Error("The prompt box is empty, nothing to save.")
if len(text) > 4000:
raise gr.Error("Prompt is too long (max 4000 characters).")
for p in presets:
if p["label"] == label:
p["text"] = text
break
else:
if len(presets) >= MAX_PRESETS:
raise gr.Error(f"Maximum {MAX_PRESETS} presets reached. Please delete one first.")
presets.append({"label": label, "text": text, "favorite": False})
gr.Info(f"Template '{label}' saved.")
return presets, ""
def delete_custom_preset(label: str, presets):
if not label:
raise gr.Error("Please select a template to delete.")
cleaned = [p for p in normalize_presets(presets) if p["label"] != label]
gr.Info(f"Template '{label}' deleted.")
return cleaned
def reset_presets():
gr.Info("Templates reset to defaults.")
return copy.deepcopy(DEFAULT_PRESETS)
def export_presets(presets):
presets = normalize_presets(presets)
if not presets:
raise gr.Error("No presets to export.")
path = os.path.join(tempfile.mkdtemp(prefix="qwen_presets_"), "qwen_presets.json")
with open(path, "w", encoding="utf-8") as f:
json.dump({"version": 1, "presets": presets}, f, ensure_ascii=False, indent=2)
return path
def import_presets(file_path, mode: str, presets):
if not file_path:
raise gr.Error("Please choose a .json file to import.")
path = file_path if isinstance(file_path, str) else getattr(file_path, "name", "")
try:
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
except Exception as e:
raise gr.Error(f"Invalid JSON file: {e}")
incoming = normalize_presets(data)
if not incoming:
raise gr.Error('No valid templates found. Each template needs a "label" and a "text".')
if mode == "Replace all":
result = incoming
else:
result = normalize_presets(presets)
index = {p["label"]: i for i, p in enumerate(result)}
for p in incoming:
if p["label"] in index:
result[index[p["label"]]] = p
else:
result.append(p)
result = result[:MAX_PRESETS]
gr.Info(f"Imported {len(incoming)} template(s) successfully.")
return result
# ============================================================
# Main Inference Function
# ============================================================
@gpu
def generate(
prompt: str,
mode: str = "Text to Image",
ref_image_1: Image.Image | None = None,
ref_image_2: Image.Image | None = None,
lora_adapter: str = DEFAULT_LORA,
lora_strength: float = 1.0,
custom_repo: str = "",
custom_file: str = "",
aspect_ratio: str = AUTO,
steps: int = 6,
seed: int = 42,
randomize_seed: bool = True,
custom_width: int = 1024,
custom_height: int = 1024,
base_model: str = MODEL_GGUF,
progress: gr.Progress = gr.Progress(track_tqdm=True),
*args,
**kwargs,
) -> tuple[Image.Image, str, str, str, str]:
prompt = (prompt or "").strip()
lora_strength = safe_float(lora_strength, fallback=1.0, min_val=0.0, max_val=1.5)
steps = safe_int(steps, fallback=6, min_val=4, max_val=40)
seed = safe_int(seed, fallback=42, min_val=0, max_val=MAX_SEED)
custom_width = safe_int(custom_width, fallback=1024, min_val=256, max_val=2048)
custom_height = safe_int(custom_height, fallback=1024, min_val=256, max_val=2048)
base_model = str(base_model or MODEL_GGUF)
if base_model not in BASE_MODEL_CHOICES:
base_model = MODEL_GGUF
# Lazy swap base model if requested model differs from currently loaded one
if not IS_PREVIEW and torch is not None and CURRENT_LOADED_MODEL != base_model:
load_pipeline_for_model(base_model)
if not prompt:
raise gr.Error("Please enter a prompt describing your image.")
if len(prompt) > 4000:
raise gr.Error("Prompt is too long. Please keep under 4000 characters.")
if mode not in MODES:
raise gr.Error(f"Invalid mode: {mode}")
if aspect_ratio not in SIZES:
raise gr.Error(f"Invalid aspect ratio: {aspect_ratio}")
if steps is None or not (4 <= int(steps) <= 40):
raise gr.Error("Inference steps must be between 4 and 40.")
if mode == "Edit Image (1 Ref)" and ref_image_1 is None:
raise gr.Error("Please upload Reference Image 1 for single-image edit mode.")
if mode == "Transform & Swap (2 Refs)":
if ref_image_1 is None or ref_image_2 is None:
raise gr.Error("Please upload both Reference Image 1 (Base) and Image 2 (Donor/Pose) for this mode.")
actual_seed = random.randint(0, MAX_SEED) if randomize_seed else int(seed)
# Determine output width and height
if aspect_ratio == CUSTOM:
width = max(32, int(custom_width) // 32 * 32)
height = max(32, int(custom_height) // 32 * 32)
elif aspect_ratio == AUTO or SIZES.get(aspect_ratio) is None:
if ref_image_1 is not None:
w0, h0 = ref_image_1.size
# Normalize to standard ~1024x1024 area while preserving exact aspect ratio
target_area = 1024 * 1024
ratio = max(0.2, min(5.0, w0 / max(1, h0)))
width, height, _ = calculate_dimensions(target_area, ratio)
else:
width, height = 1024, 1024
else:
width, height = SIZES[aspect_ratio]
# UI Preview Mode (when CUDA/weights skipped)
if pipe is None or IS_PREVIEW:
start_time = time.perf_counter()
img = Image.new("RGB", (width, height), color=(26, 24, 38))
draw = ImageDraw.Draw(img)
draw.text((40, 40), "[PREVIEW] GRADIO UI PREVIEW (NO MODEL DOWNLOADED)", fill=(255, 215, 0))
draw.text((40, 80), f"Prompt: {prompt[:90]}...", fill=(240, 240, 245))
draw.text((40, 120), f"Base: {base_model} | LoRA: {lora_adapter}", fill=(135, 206, 250))
draw.text((40, 160), f"Mode: {mode} | Size: {width}x{height} | Steps: {steps} | Seed: {actual_seed}", fill=(200, 200, 220))
draw.text((40, 200), f"Active LoRA: {lora_adapter} (Strength: {lora_strength})", fill=(144, 238, 144))
if ref_image_1:
draw.text((40, 240), "Reference Image 1: Loaded", fill=(221, 160, 221))
if ref_image_2:
draw.text((40, 270), "Reference Image 2: Loaded", fill=(221, 160, 221))
draw.text((40, 310), "Rendered successfully in ~0.05s!", fill=(180, 180, 180))
elapsed = time.perf_counter() - start_time
result = img
else:
# Prepare LoRA adapters & acceleration scheduler
active_adapter, base_strength = ensure_adapter_ready(lora_adapter, custom_repo, custom_file)
is_turbo_speed = (int(steps) <= 8)
sigmas = None
infer_steps = int(steps)
if active_adapter:
effective_strength = float(lora_strength) * base_strength
# If fast turbo steps (<= 8) and active adapter is NOT viggle_turbo itself, stack viggle_turbo under it!
if is_turbo_speed and active_adapter != "viggle_turbo":
turbo_adapter, _ = ensure_adapter_ready("Viggle Turbo (6-Step Acceleration)")
if turbo_adapter:
pipe.set_adapters([active_adapter, turbo_adapter], adapter_weights=[effective_strength, 1.0])
if turbo_scheduler is not None:
pipe.scheduler = turbo_scheduler
infer_steps, sigmas = turbo_sigmas(int(steps))
active_lora_desc = f"{lora_adapter} (scale={round(effective_strength, 2)}) + Viggle Turbo 6-step stacked"
else:
pipe.set_adapters([active_adapter], adapter_weights=[effective_strength])
active_lora_desc = f"{lora_adapter} (scale={round(effective_strength, 2)})"
elif active_adapter == "viggle_turbo":
pipe.set_adapters([active_adapter], adapter_weights=[effective_strength])
if turbo_scheduler is not None:
pipe.scheduler = turbo_scheduler
infer_steps, sigmas = turbo_sigmas(int(steps))
active_lora_desc = f"{lora_adapter} (scale={round(effective_strength, 2)})"
else:
# Base model (higher steps, e.g. 25-30)
pipe.set_adapters([active_adapter], adapter_weights=[effective_strength])
if base_scheduler is not None:
pipe.scheduler = base_scheduler
active_lora_desc = f"{lora_adapter} (scale={round(effective_strength, 2)})"
else:
try:
pipe.disable_lora()
except Exception:
pass
if base_scheduler is not None:
pipe.scheduler = base_scheduler
active_lora_desc = "None (Base Model)"
effective_prompt = prompt
if mode == "Transparent PNG":
effective_prompt = (
"This is an RGBA image with transparency. " + prompt
+ " The image has alpha channel and the background is transparent."
)
spec = ADAPTER_SPECS.get(lora_adapter, {})
call_kwargs = {}
if sigmas is not None:
call_kwargs["sigmas"] = sigmas
if mode == "Edit Image (1 Ref)":
img = ImageOps.exif_transpose(ref_image_1).convert("RGBA" if mode == "Transparent PNG" else "RGB")
# Always ensure the condition image matches generation width & height
img = img.resize((width, height), Image.LANCZOS)
call_kwargs["image"] = img
elif mode == "Transform & Swap (2 Refs)":
img1 = ImageOps.exif_transpose(ref_image_1).convert("RGB").resize((width, height), Image.LANCZOS)
img2 = ImageOps.exif_transpose(ref_image_2).convert("RGB").resize((width, height), Image.LANCZOS)
call_kwargs["image"] = [img1, img2]
try:
start_time = time.perf_counter()
with torch.inference_mode():
result = pipe(
prompt=effective_prompt,
width=width,
height=height,
num_inference_steps=infer_steps,
generator=torch.Generator("cuda").manual_seed(actual_seed),
**call_kwargs,
).images[0]
elapsed = time.perf_counter() - start_time
except gr.Error:
raise
except Exception as e:
import traceback
traceback.print_exc()
err_str = str(e)
if "out of memory" in err_str.lower() or "cuda oom" in err_str.lower():
if torch is not None and hasattr(torch, "cuda") and torch.cuda.is_available():
torch.cuda.empty_cache()
raise gr.Error("GPU Memory Exceeded! Silakan gunakan resolusi lebih rendah (1024x1024) atau kurangi langkah inferensi.")
raise gr.Error(f"Inference Error: {err_str}")
status_str = f"seed `{actual_seed}` · {result.width}×{result.height} · {steps} steps · {elapsed:.2f}s · Base: `{base_model}` · LoRA: `{lora_adapter}`"
temp_dir = tempfile.gettempdir()
temp_dl_path = os.path.join(temp_dir, f"qwen_{actual_seed}_{result.width}x{result.height}.png")
result.save(temp_dl_path, "PNG")
idb_payload = json.dumps({
"prompt": prompt,
"seed": actual_seed,
"steps": int(steps),
"width": result.width,
"height": result.height,
"lora": lora_adapter,
"mode": mode,
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"nonce": random.random(),
}, ensure_ascii=False)
return result, temp_dl_path, status_str, prompt, idb_payload
def update_mode_ui(mode: str):
is_edit_1 = mode == "Edit Image (1 Ref)"
is_swap_2 = mode == "Transform & Swap (2 Refs)"
show_section = is_edit_1 or is_swap_2
return (
gr.update(visible=show_section),
gr.update(visible=show_section),
gr.update(visible=is_swap_2),
)
# ============================================================
# UI Theme & Assets
# ============================================================
THEME = gr.themes.Monochrome(
radius_size="sm",
text_size="sm",
font=[gr.themes.GoogleFont("Plus Jakarta Sans"), "system-ui", "-apple-system", "sans-serif"],
font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"],
).set(
background_fill_secondary="transparent",
background_fill_secondary_dark="transparent",
block_background_fill="transparent",
block_background_fill_dark="transparent",
block_border_width="0px",
block_border_width_dark="0px",
block_label_background_fill="transparent",
block_label_background_fill_dark="transparent",
panel_border_width="0px",
panel_border_width_dark="0px",
panel_background_fill="transparent",
panel_background_fill_dark="transparent",
border_color_primary="transparent",
border_color_primary_dark="transparent",
form_gap_width="12px",
checkbox_label_background_fill="transparent",
checkbox_label_background_fill_dark="transparent",
checkbox_label_border_width="0px",
checkbox_label_border_width_dark="0px",
input_background_fill="*background_fill_primary",
input_border_color="*neutral_200",
input_border_color_dark="*neutral_800",
button_primary_background_fill="*neutral_950",
button_primary_background_fill_dark="*neutral_50",
button_primary_text_color="*neutral_50",
button_primary_text_color_dark="*neutral_950",
button_secondary_background_fill="*neutral_100",
button_secondary_background_fill_dark="*neutral_800",
button_secondary_text_color="*neutral_900",
button_secondary_text_color_dark="*neutral_100",
button_secondary_border_color="*neutral_200",
button_secondary_border_color_dark="*neutral_700",
)
FONT_HEAD = """
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:ital,wght@0,300;0,400;0,500;0,600;0,700;0,800;1,400;1,600&family=JetBrains+Mono:wght@400;500;600&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/lucide@latest/dist/umd/lucide.min.js"></script>
<script src="https://unpkg.com/lucide@latest"></script>
"""
HEAD_JS = """
<script src="https://cdn.jsdelivr.net/npm/sortablejs@1.15.2/Sortable.min.js"></script>
<script>
(function () {
function field(id) {
return document.querySelector('#' + id + ' textarea, #' + id + ' input');
}
function setValue(el, value) {
var proto = el.tagName === 'TEXTAREA' ? window.HTMLTextAreaElement.prototype
: window.HTMLInputElement.prototype;
Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, value);
el.dispatchEvent(new Event('input', { bubbles: true }));
}
function sendCmd(obj) {
var el = field('pp-cmd');
if (!el) { return; }
obj.nonce = Date.now() + '-' + Math.random();
setValue(el, JSON.stringify(obj));
}
document.addEventListener('click', function (e) {
var useBtn = e.target.closest ? e.target.closest('.pp-use') : null;
if (useBtn) {
var item = useBtn.closest('.pp-item');
var prompt = field('prompt-box');
if (item && prompt) { setValue(prompt, item.getAttribute('data-text') || ''); }
return;
}
var favBtn = e.target.closest ? e.target.closest('.pp-fav') : null;
if (favBtn) {
var it = favBtn.closest('.pp-item');
if (it) { sendCmd({ op: 'fav', label: it.getAttribute('data-label') }); }
}
});
function initSortables() {
if (!window.Sortable) { return; }
document.querySelectorAll('.pp-sortable').forEach(function (list) {
if (list.getAttribute('data-pp-init') === '1') { return; }
list.setAttribute('data-pp-init', '1');
new Sortable(list, {
animation: 150,
handle: '.pp-handle',
ghostClass: 'pp-ghost',
touchStartThreshold: 3,
onEnd: function () {
var labels = Array.prototype.map.call(
list.querySelectorAll('.pp-item'),
function (n) { return n.getAttribute('data-label'); }
);
sendCmd({ op: 'order', labels: labels });
}
});
});
}
var pending = false;
new MutationObserver(function () {
if (pending) { return; }
pending = true;
window.requestAnimationFrame(function () { pending = false; initSortables(); });
}).observe(document.documentElement, { childList: true, subtree: true });
window.addEventListener('load', initSortables);
// ============================================================
// Client-Side Prompt History (LocalStorage, synced with index.html)
// ============================================================
var PROMPT_HIST_KEY = 'qwen_prompt_history';
window.promptHistory = [];
try {
var rawHist = localStorage.getItem(PROMPT_HIST_KEY);
if (rawHist) {
var parsed = JSON.parse(rawHist);
window.promptHistory = Array.isArray(parsed) ? parsed : [];
}
} catch(e) { window.promptHistory = []; }
window.renderPromptHistory = function() {
var box = document.getElementById('history-list-box') || document.getElementById('history-list');
var badge = document.getElementById('history-count-badge');
if (!box) return;
if (badge) {
badge.textContent = window.promptHistory.length + ' saved';
}
if (!window.promptHistory || window.promptHistory.length === 0) {
box.innerHTML = '<div style="font-size: 12px; color: var(--muted-foreground); font-style: italic; padding: 6px 0;">No prompt history yet. Prompts you generate will be saved here automatically.</div>';
return;
}
var html = '<div style="display: flex; flex-direction: column; gap: 6px; max-height: 180px; overflow-y: auto; padding-right: 4px;">';
window.promptHistory.forEach(function(item, idx) {
var text = typeof item === 'string' ? item : (item.text || '');
var time = (item && item.timestamp) ? item.timestamp : 'Recent';
var escaped = text.replace(/"/g, '"').replace(/'/g, ''');
html += '<div class="history-item" onclick="window.loadHistoryPrompt(' + idx + ')" style="display: flex; align-items: center; justify-content: space-between; padding: 6px 10px; border-radius: 8px; border: 1px solid var(--border); background: var(--secondary); cursor: pointer; transition: all 0.15s ease;">';
html += '<div style="display: flex; align-items: center; gap: 8px; min-width: 0; flex: 1;">';
html += '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="flex-shrink:0; opacity:0.6;"><polyline points="9 10 4 15 9 20"/><path d="M20 4v7a4 4 0 0 1-4 4H4"/></svg>';
html += '<span style="font-size: 12px; color: var(--foreground); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;" title="' + escaped + '">' + escaped + '</span>';
html += '</div>';
html += '<button type="button" onclick="event.stopPropagation(); window.deleteHistoryPrompt(' + idx + ');" style="background: none; border: none; color: var(--muted-foreground); cursor: pointer; padding: 2px 6px; font-size: 11px; margin-left: 8px;" title="Delete">✕</button>';
html += '</div>';
});
html += '</div>';
box.innerHTML = html;
};
window.loadHistoryPrompt = function(idx) {
var item = window.promptHistory[idx];
var text = typeof item === 'string' ? item : (item ? item.text : '');
if (text) {
var tb = document.querySelector('#prompt-box textarea, #prompt-box input, textarea[data-testid="textbox"], textarea');
if (tb) {
setValue(tb, text);
}
}
};
window.deleteHistoryPrompt = function(idx) {
window.promptHistory.splice(idx, 1);
localStorage.setItem(PROMPT_HIST_KEY, JSON.stringify(window.promptHistory));
window.renderPromptHistory();
};
window.clearPromptHistory = function() {
window.promptHistory = [];
localStorage.setItem(PROMPT_HIST_KEY, JSON.stringify([]));
window.renderPromptHistory();
};
window.addPromptToHistory = function(text) {
if (!text || !text.trim()) return;
var clean = text.trim();
var existingIdx = -1;
for (var i = 0; i < window.promptHistory.length; i++) {
var cur = typeof window.promptHistory[i] === 'string' ? window.promptHistory[i] : (window.promptHistory[i].text || '');
if (cur.toLowerCase() === clean.toLowerCase()) {
existingIdx = i;
break;
}
}
if (existingIdx !== -1) {
window.promptHistory.splice(existingIdx, 1);
}
window.promptHistory.unshift({
id: Date.now(),
text: clean,
timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
});
if (window.promptHistory.length > 50) window.promptHistory.pop();
localStorage.setItem(PROMPT_HIST_KEY, JSON.stringify(window.promptHistory));
window.renderPromptHistory();
};
// ============================================================
// Client-Side Private Browser Gallery (IndexedDB)
// ============================================================
var DB_NAME = 'QwenStudioDB';
var DB_VERSION = 1;
var STORE_NAME = 'generations';
var currentDbItems = [];
function openDB() {
return new Promise(function(resolve, reject) {
var req = indexedDB.open(DB_NAME, DB_VERSION);
req.onupgradeneeded = function(e) {
var db = e.target.result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME, { keyPath: 'id' });
}
};
req.onsuccess = function(e) { resolve(e.target.result); };
req.onerror = function(e) { reject(e.target.error); };
});
}
function addGenerationToDB(item) {
return openDB().then(function(db) {
return new Promise(function(resolve, reject) {
var tx = db.transaction(STORE_NAME, 'readwrite');
var store = tx.objectStore(STORE_NAME);
item.id = Date.now();
var req = store.add(item);
req.onsuccess = function() { resolve(req.result); };
req.onerror = function(e) { reject(e.target.error); };
});
});
}
function getAllGenerationsFromDB() {
return openDB().then(function(db) {
return new Promise(function(resolve, reject) {
var tx = db.transaction(STORE_NAME, 'readonly');
var store = tx.objectStore(STORE_NAME);
var req = store.getAll();
req.onsuccess = function() {
var list = req.result || [];
list.sort(function(a, b) { return b.id - a.id; });
resolve(list);
};
req.onerror = function(e) { reject(e.target.error); };
});
});
}
function deleteGenerationFromDB(id) {
return openDB().then(function(db) {
return new Promise(function(resolve, reject) {
var tx = db.transaction(STORE_NAME, 'readwrite');
var store = tx.objectStore(STORE_NAME);
var req = store.delete(Number(id));
req.onsuccess = function() { resolve(); };
req.onerror = function(e) { reject(e.target.error); };
});
});
}
function clearAllGenerationsFromDB() {
return openDB().then(function(db) {
return new Promise(function(resolve, reject) {
var tx = db.transaction(STORE_NAME, 'readwrite');
var store = tx.objectStore(STORE_NAME);
var req = store.clear();
req.onsuccess = function() { resolve(); };
req.onerror = function(e) { reject(e.target.error); };
});
});
}
function getItemImageUrl(item) {
if (!item) return '';
if (item.blob && typeof Blob !== 'undefined' && item.blob instanceof Blob) {
try { return URL.createObjectURL(item.blob); } catch(e) {}
}
if (typeof item.blob === 'string') return item.blob;
if (item.img_data) return item.img_data;
if (item.url) return item.url;
return '';
}
function renderGalleryFromDB() {
var grid = document.getElementById('idb-gallery-grid');
var countLabel = document.getElementById('idb-count-label');
if (!grid) { return Promise.resolve(); }
return getAllGenerationsFromDB().then(function(items) {
currentDbItems = items || [];
if (countLabel) {
countLabel.innerHTML = '<svg class="lucide-sm" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:inline-block;vertical-align:middle;margin-right:6px;"><rect width="20" height="8" x="2" y="2" rx="2" ry="2"/><rect width="20" height="8" x="2" y="14" rx="2" ry="2"/><line x1="6" x2="6.01" y1="6" y2="6"/><line x1="6" x2="6.01" y1="18" y2="18"/></svg>Browser Storage: ' + currentDbItems.length + ' image(s) (100% Private, 0 KB on Space)';
}
if (!currentDbItems || currentDbItems.length === 0) {
grid.innerHTML = '<div class="idb-empty">No images saved in your browser yet. Generated images will be saved automatically here.</div>';
return;
}
var html = currentDbItems.map(function(item) {
var url = getItemImageUrl(item);
var res = (item.width || 1024) + '×' + (item.height || 1024);
var seed = item.seed !== undefined ? item.seed : '';
var steps = item.steps !== undefined ? item.steps : 6;
return (
'<div class="idb-card" data-id="' + item.id + '">' +
'<div class="idb-thumb-wrap">' +
'<img class="idb-thumb" src="' + url + '" alt="Saved image ' + item.id + '" loading="lazy" />' +
'<div class="idb-card-overlay">' +
'<button type="button" class="idb-btn-sm" onclick="window.openIdbModal(' + item.id + ')"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:inline-block;vertical-align:middle;margin-right:4px;"><path d="M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7Z"/><circle cx="12" cy="12" r="3"/></svg>View</button>' +
'<button type="button" class="idb-btn-sm" onclick="window.downloadIdbItem(' + item.id + ')"><svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:inline-block;vertical-align:middle;margin-right:4px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/></svg>Save</button>' +
'</div>' +
'</div>' +
'<div class="idb-meta">' +
'<span class="idb-meta-res">' + res + '</span>' +
'<span class="idb-meta-steps">' + steps + 'st</span>' +
'<span class="idb-meta-seed">#' + seed + '</span>' +
'</div>' +
'</div>'
);
}).join('');
grid.innerHTML = html;
}).catch(function(err) {
console.warn('[idb] Render error:', err);
});
}
window.openIdbModal = function(id) {
var item = currentDbItems.find(function(x) { return x.id === Number(id); });
if (!item) { return; }
var modal = document.getElementById('idb-modal');
var img = document.getElementById('idb-modal-img');
var meta = document.getElementById('idb-modal-meta');
var dl = document.getElementById('idb-modal-dl');
var usePrompt = document.getElementById('idb-modal-use-prompt');
var deleteBtn = document.getElementById('idb-modal-delete');
var url = getItemImageUrl(item);
img.src = url;
dl.href = url;
dl.download = 'qwen_' + (item.seed || 'out') + '_' + (item.width || 1024) + 'x' + (item.height || 1024) + '.png';
meta.innerHTML =
'<div class="idb-modal-prompt"><strong>Prompt:</strong> ' + (item.prompt || '') + '</div>' +
'<div class="idb-modal-tags">' +
'<span><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:inline-block;vertical-align:middle;margin-right:3px;"><rect width="18" height="18" x="3" y="3" rx="2"/><path d="M3 9h18"/><path d="M9 21V9"/></svg>' + (item.width || 1024) + '×' + (item.height || 1024) + '</span>' +
'<span><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:inline-block;vertical-align:middle;margin-right:3px;"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>' + (item.steps || 6) + ' steps</span>' +
'<span><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:inline-block;vertical-align:middle;margin-right:3px;"><circle cx="12" cy="12" r="3"/><circle cx="19" cy="5" r="2"/><circle cx="5" cy="19" r="2"/></svg>Seed: ' + (item.seed || 0) + '</span>' +
'<span><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:inline-block;vertical-align:middle;margin-right:3px;"><path d="m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z"/><path d="m22 12.5-9.17 4.16a2 2 0 0 1-1.66 0L2 12.5"/><path d="m22 17.5-9.17 4.16a2 2 0 0 1-1.66 0L2 17.5"/></svg>LoRA: ' + (item.lora || 'Base') + '</span>' +
'<span><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:inline-block;vertical-align:middle;margin-right:3px;"><circle cx="12" cy="12" r="10"/><path d="m10 15 5-3-5-3v6Z"/></svg>' + (item.mode || 'Text to Image') + '</span>' +
'<span><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:inline-block;vertical-align:middle;margin-right:3px;"><circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 14 14"/></svg>' + (item.timestamp || '') + '</span>' +
'</div>';
usePrompt.onclick = function() {
var promptBox = document.querySelector('#prompt-box textarea, #prompt-box input, textarea[data-testid="textbox"], textarea');
if (promptBox && item.prompt) {
setValue(promptBox, item.prompt);
}
window.closeIdbModal();
};
deleteBtn.onclick = function() {
if (confirm('Delete this image from your private browser storage?')) {
deleteGenerationFromDB(item.id).then(function() {
window.closeIdbModal();
renderGalleryFromDB();
});
}
};
modal.style.display = 'flex';
};
window.closeIdbModal = function() {
var modal = document.getElementById('idb-modal');
if (modal) { modal.style.display = 'none'; }
};
window.downloadIdbItem = function(id) {
var item = currentDbItems.find(function(x) { return x.id === Number(id); });
if (!item) { return; }
var url = getItemImageUrl(item);
if (!url) return;
var a = document.createElement('a');
a.href = url;
a.download = 'qwen_' + (item.seed || 'out') + '_' + (item.width || 1024) + 'x' + (item.height || 1024) + '.png';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
};
var savedImageKeys = new Set();
var isAutoSaving = false;
function autoSaveGeneratedImage() {
if (isAutoSaving) return;
var container = document.getElementById('output-image');
if (!container) return;
var img = container.querySelector('img');
if (!img || !img.src || img.src === '' || img.src.endsWith('#') || savedImageKeys.has(img.src)) {
return;
}
if (img.src.startsWith('data:image/svg') || img.src.includes('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')) {
return;
}
if (!img.complete || img.naturalWidth <= 1) {
img.onload = function() { autoSaveGeneratedImage(); };
return;
}
var currentSrc = img.src;
savedImageKeys.add(currentSrc);
isAutoSaving = true;
var promptVal = '';
var usedEl = document.querySelector('#used-prompt textarea, #used-prompt input');
if (usedEl && usedEl.value && usedEl.value.trim()) {
promptVal = usedEl.value.trim();
}
if (!promptVal) {
var pEl = document.querySelector('#prompt-box textarea, #prompt-box input, textarea[data-testid="textbox"], textarea');
if (pEl && pEl.value && pEl.value.trim()) promptVal = pEl.value.trim();
}
if (!promptVal && window.pendingGenerationPrompt) {
promptVal = window.pendingGenerationPrompt;
}
if (promptVal && window.addPromptToHistory) {
window.addPromptToHistory(promptVal);
}
var seedVal = Math.floor(Math.random() * 100000000);
var stepsVal = 6;
var widthVal = img.naturalWidth || 1024;
var heightVal = img.naturalHeight || 1024;
var loraVal = 'Viggle Turbo (6-Step Acceleration)';
var modeVal = 'Text to Image';
var trigEl = document.querySelector('#idb-trigger textarea, #idb-trigger input');
if (trigEl && trigEl.value) {
try {
var parsed = JSON.parse(trigEl.value);
if (parsed) {
if (parsed.prompt) promptVal = parsed.prompt;
if (parsed.seed !== undefined) seedVal = parsed.seed;
if (parsed.steps !== undefined) stepsVal = parsed.steps;
if (parsed.width !== undefined) widthVal = parsed.width;
if (parsed.height !== undefined) heightVal = parsed.height;
if (parsed.lora) loraVal = parsed.lora;
if (parsed.mode) modeVal = parsed.mode;
}
} catch(e) {}
} else {
var infoEl = document.getElementById('info');
if (infoEl) {
var infoText = infoEl.innerText || infoEl.textContent || '';
var seedM = infoText.match(/seed `?(\\d+)`?/i);
if (seedM) seedVal = parseInt(seedM[1]);
var resM = infoText.match(/(\\d+)[\\s*×x](\\d+)/i);
if (resM) { widthVal = parseInt(resM[1]); heightVal = parseInt(resM[2]); }
var stepsM = infoText.match(/(\\d+)\\s*steps/i);
if (stepsM) stepsVal = parseInt(stepsM[1]);
var loraM = infoText.match(/LoRA:\\s*`?([^`\\n·]+)`?/i);
if (loraM) loraVal = loraM[1].trim();
}
}
function doSave(blob) {
if (!blob || blob.size === 0) {
isAutoSaving = false;
return;
}
addGenerationToDB({
blob: blob,
prompt: promptVal,
seed: seedVal,
steps: stepsVal,
width: widthVal,
height: heightVal,
lora: loraVal,
mode: modeVal,
timestamp: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
}).then(function() {
console.log('[idb] Generation saved successfully to browser storage!');
isAutoSaving = false;
renderGalleryFromDB();
}).catch(function(err) {
console.warn('[idb] Save error:', err);
isAutoSaving = false;
});
}
fetch(currentSrc).then(function(res) {
return res.blob();
}).then(function(blob) {
doSave(blob);
}).catch(function(err) {
try {
var canvas = document.createElement('canvas');
canvas.width = img.naturalWidth || widthVal;
canvas.height = img.naturalHeight || heightVal;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
canvas.toBlob(function(b) {
doSave(b);
}, 'image/png');
} catch(e) {
console.error('[idb] Canvas draw failed:', e);
isAutoSaving = false;
}
});
}
function initIdbListener() {
var output = document.getElementById('output-image');
if (output) {
new MutationObserver(function() {
autoSaveGeneratedImage();
}).observe(output, { childList: true, subtree: true, attributes: true, attributeFilter: ['src'] });
}
var trigger = document.getElementById('idb-trigger');
if (trigger) {
new MutationObserver(function() {
autoSaveGeneratedImage();
}).observe(trigger, { childList: true, subtree: true, characterData: true });
var inputEl = trigger.querySelector('textarea, input');
if (inputEl) {
inputEl.addEventListener('input', autoSaveGeneratedImage);
inputEl.addEventListener('change', autoSaveGeneratedImage);
}
}
var usedPrompt = document.getElementById('used-prompt');
if (usedPrompt) {
new MutationObserver(function() {
autoSaveGeneratedImage();
}).observe(usedPrompt, { childList: true, subtree: true });
}
}
document.addEventListener('click', function(e) {
if (e.target && e.target.id === 'idb-clear-btn') {
if (confirm('Are you sure you want to delete all saved images from your browser storage?')) {
clearAllGenerationsFromDB().then(function() {
renderGalleryFromDB();
});
}
}
});
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') { window.closeIdbModal(); }
});
// ============================================================
// Dark / Light Mode Switcher
// ============================================================
function setTheme(mode) {
var isDark = mode === 'dark';
document.documentElement.classList.toggle('dark', isDark);
document.body.classList.toggle('dark', isDark);
var container = document.querySelector('.gradio-container');
if (container) {
container.classList.toggle('dark', isDark);
}
localStorage.setItem('qwen_theme', mode);
var icon = document.getElementById('theme-toggle-icon');
if (icon) {
if (isDark) {
icon.innerHTML = '<circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/>';
} else {
icon.innerHTML = '<path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"/>';
}
}
if (window.lucide) { window.lucide.createIcons(); }
}
window.toggleTheme = function() {
var isDark = document.documentElement.classList.contains('dark') || document.body.classList.contains('dark');
setTheme(isDark ? 'light' : 'dark');
};
function initTheme() {
var saved = localStorage.getItem('qwen_theme');
var isDark = saved ? saved === 'dark' : true;
setTheme(isDark ? 'dark' : 'light');
}
// ============================================================
// Robust Dynamic Lucide & Inline Vector Icon Engine
// ============================================================
var INLINE_SVGS = {
'wand-2': '<svg class="lucide-svg" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72"/><path d="m14 7 3 3"/><path d="M5 6v4"/><path d="M19 14v4"/><path d="M10 2v2"/><path d="M7 8H3"/><path d="M21 16h-4"/><path d="M11 3H9"/></svg>',
'layers': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 2 7 12 12 22 7 12 2"/><polyline points="2 17 12 22 22 17"/><polyline points="2 12 12 17 22 12"/></svg>',
'image': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg>',
'repeat': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m17 2 4 4-4 4"/><path d="M3 11v-1a4 4 0 0 1 4-4h14"/><path d="m7 22-4-4 4-4"/><path d="M21 13v1a4 4 0 0 1-4 4H3"/></svg>',
'sparkles': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/><path d="M5 3v4"/><path d="M19 17v4"/><path d="M3 5h4"/><path d="M17 19h4"/></svg>',
'user': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>',
'smile': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" x2="9.01" y1="9" y2="9"/><line x1="15" x2="15.01" y1="9" y2="9"/></svg>',
'sun': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/></svg>',
'camera': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"/><circle cx="12" cy="13" r="3"/></svg>',
'shirt': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20.38 3.46 16 2a4 4 0 0 1-8 0L3.62 3.46a2 2 0 0 0-1.34 2.23l.58 3.47a1 1 0 0 0 .99.84H6v10c0 1.1.9 2 2 2h8a2 2 0 0 0 2-2V10h2.15a1 1 0 0 0 .99-.84l.58-3.47a2 2 0 0 0-1.34-2.23z"/></svg>',
'palette': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="13.5" cy="6.5" r=".5" fill="currentColor"/><circle cx="17.5" cy="10.5" r=".5" fill="currentColor"/><circle cx="8.5" cy="7.5" r=".5" fill="currentColor"/><circle cx="6.5" cy="12.5" r=".5" fill="currentColor"/><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z"/></svg>',
'zap': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#f59e0b" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>',
'search': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>',
'rocket': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z"/><path d="m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z"/><path d="M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0"/><path d="M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5"/></svg>',
'sliders': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="4" x2="4" y1="21" y2="14"/><line x1="4" x2="4" y1="10" y2="3"/><line x1="12" x2="12" y1="21" y2="12"/><line x1="12" x2="12" y1="8" y2="3"/><line x1="20" x2="20" y1="21" y2="16"/><line x1="20" x2="20" y1="12" y2="3"/><line x1="1" x2="7" y1="14" y2="14"/><line x1="9" x2="15" y1="8" y2="8"/><line x1="17" x2="23" y1="16" y2="16"/></svg>',
'bookmark': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"/></svg>',
'bookmark-plus': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z"/><line x1="12" x2="12" y1="7" y2="13"/><line x1="9" x2="15" y1="10" y2="10"/></svg>',
'trash-2': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg>',
'download': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/></svg>',
'upload': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" x2="12" y1="3" y2="15"/></svg>',
'rotate-ccw': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>',
'hard-drive': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="22" x2="2" y1="12" y2="12"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z"/><line x1="6" x2="6.01" y1="16" y2="16"/><line x1="10" x2="10.01" y1="16" y2="16"/></svg>',
'wrench': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>',
'history': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><polyline points="12 7 12 12 15 15"/></svg>',
'pen-tool': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m12 19 7-7 3 3-7 7-3-3z"/><path d="m18 13-1.5-7.5L2 2l3.5 14.5L13 18l5-5z"/><circle cx="11" cy="11" r="2"/></svg>',
'file-output': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M4 7V4a2 2 0 0 1 2-2h8.5L20 7.5V20a2 2 0 0 1-2 2h-6"/><polyline points="9 15 12 18 15 15"/><line x1="12" x2="12" y1="12" y2="18"/></svg>',
'database': '<svg class="lucide-svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14c0 1.66 4 3 9 3s9-1.34 9-3V5"/><path d="M3 12c0 1.66 4 3 9 3s9-1.34 9-3"/></svg>'
};
var ICON_MAP = {
// Action Buttons
'Generate Image': 'wand-2',
'Search Models': 'search',
'Apply Selected LoRA': 'rocket',
'Apply This LoRA': 'rocket',
'Apply Custom LoRA': 'sliders',
'Save Current Prompt': 'bookmark-plus',
'Delete Template': 'trash-2',
'Clear History': 'trash-2',
'Use Selected as Ref 1': 'image',
'Use Selected as Ref 2': 'repeat',
'Clear Library': 'trash-2',
// Curated LoRA Buttons
'Real Anatomy': 'user',
'Body Swap': 'repeat',
'Face Swap': 'smile',
'Studio Light': 'sun',
'Phone Photo': 'camera',
'Restore Photo': 'image',
'Outfit Swap': 'shirt',
'Anime': 'palette',
'Viggle Turbo (6-Step Fast)': 'zap',
'Viggle Turbo': 'zap',
// Tabs
'Curated Presets': 'sparkles',
'Hugging Face Live Explorer': 'search',
'Custom Repo ID': 'wrench',
// Accordions
'Base Model Architecture': 'database',
'Base Model': 'database',
'Generation Mode': 'layers',
'Reference Images & Media Inputs': 'image',
'Prompt Description': 'wand-2',
'Prompt History': 'history',
'Prompt Templates & Presets': 'bookmark',
'LoRA Adapters & Acceleration': 'zap',
'Generation Settings': 'sliders',
'Generated Result & Canvas Viewport': 'sparkles',
'Generated Result & Canvas': 'sparkles',
'Output Download & Model Prompt': 'file-output',
'Output Download': 'file-output',
'Private Browser Gallery (IndexedDB)': 'hard-drive',
'Private Browser Gallery': 'hard-drive',
'Media Library': 'image'
};
var MODE_ICON_MAP = {
'Uncensored GGUF (Q4_K_M)': 'database',
'Qwen Original (BF16)': 'sparkles',
'Text to Image': 'layers',
'Edit Image (1 Ref)': 'image',
'Edit Image': 'image',
'Transform & Swap (2 Refs)': 'repeat',
'Transform & Swap': 'repeat',
'Transparent PNG': 'sparkles'
};
function createIconElement(iconName, extraClass) {
var span = document.createElement('span');
span.className = 'lucide-injected-wrap ' + (extraClass || '');
if (INLINE_SVGS[iconName]) {
span.innerHTML = INLINE_SVGS[iconName];
} else {
span.innerHTML = '<i data-lucide="' + iconName + '" class="lucide-injected"></i>';
}
return span;
}
function injectLucideIcons() {
// 1. Generation Mode Radio Labels & suppress circles
document.querySelectorAll('#mode-selector label, .mode-radio-group label, .gr-radio label, [data-testid="radio-group"] label').forEach(function(lbl) {
// Actively remove/hide native circle indicators
var inp = lbl.querySelector('input');
if (inp) {
inp.style.setProperty('display', 'none', 'important');
inp.style.setProperty('visibility', 'hidden', 'important');
inp.style.setProperty('position', 'absolute', 'important');
inp.style.setProperty('opacity', '0', 'important');
}
var circ = lbl.querySelector('.circle');
if (circ) {
circ.style.setProperty('display', 'none', 'important');
circ.style.setProperty('visibility', 'hidden', 'important');
}
lbl.querySelectorAll('svg:not(.lucide-svg)').forEach(function(s) {
if (!s.closest('.lucide-injected-wrap')) {
s.style.setProperty('display', 'none', 'important');
}
});
if (lbl.classList.contains('lucide-done') || lbl.querySelector('.lucide-injected-wrap')) return;
var txt = (lbl.innerText || lbl.textContent || '').trim().toLowerCase();
for (var mode in MODE_ICON_MAP) {
if (txt.indexOf(mode.toLowerCase()) !== -1) {
lbl.classList.add('lucide-done');
lbl.insertBefore(createIconElement(MODE_ICON_MAP[mode], 'radio-icon'), lbl.firstChild);
break;
}
}
});
// 2. Action, LoRA, and Form Buttons
document.querySelectorAll('button').forEach(function(btn) {
if (btn.classList.contains('lucide-done') || btn.querySelector('.lucide-injected-wrap') ||
btn.querySelector('svg') || btn.id === 'idb-clear-btn' || btn.classList.contains('idb-btn-danger') ||
btn.classList.contains('idb-modal-close') || btn.classList.contains('shadcn-theme-btn') ||
btn.classList.contains('pp-use') || btn.classList.contains('pp-fav') ||
btn.classList.contains('label-wrap') || btn.classList.contains('svelte-e5lyqv')) {
return;
}
var txt = (btn.innerText || btn.textContent || '').trim().toLowerCase();
for (var key in ICON_MAP) {
var kLower = key.toLowerCase();
if (txt === kLower || txt.indexOf(kLower) === 0 || txt.includes(kLower)) {
btn.classList.add('lucide-done');
btn.insertBefore(createIconElement(ICON_MAP[key], 'btn-icon'), btn.firstChild);
break;
}
}
});
// 3. Navigation Tabs
document.querySelectorAll('button[role="tab"], button.tab-item, .tab-nav button, .tabs > div > button').forEach(function(tab) {
if (tab.classList.contains('lucide-done') || tab.querySelector('.lucide-injected-wrap')) return;
var txt = (tab.innerText || tab.textContent || '').trim().toLowerCase();
for (var key in ICON_MAP) {
if (txt.indexOf(key.toLowerCase()) !== -1) {
tab.classList.add('lucide-done');
tab.insertBefore(createIconElement(ICON_MAP[key], 'tab-icon'), tab.firstChild);
break;
}
}
});
// 4. Accordion Headers (Case-insensitive matching for Gradio 6)
document.querySelectorAll('.label-wrap, button.label-wrap, .gr-accordion button, .accordion-header, summary').forEach(function(acc) {
if (acc.classList.contains('lucide-done') || acc.querySelector('.lucide-injected-wrap')) return;
var target = acc.querySelector('span:first-child') || acc.querySelector('.label') || acc;
var txt = (target.innerText || target.textContent || acc.innerText || acc.textContent || '').trim().toLowerCase();
for (var key in ICON_MAP) {
if (txt.indexOf(key.toLowerCase()) !== -1) {
acc.classList.add('lucide-done');
var iconEl = createIconElement(ICON_MAP[key], 'acc-icon');
if (target !== acc) {
target.insertBefore(iconEl, target.firstChild);
} else {
acc.insertBefore(iconEl, acc.firstChild);
}
break;
}
}
});
if (window.lucide && window.lucide.createIcons) {
try { window.lucide.createIcons(); } catch(e) {}
}
}
var pendingIcons = false;
new MutationObserver(function () {
if (pendingIcons) { return; }
pendingIcons = true;
window.requestAnimationFrame(function () {
pendingIcons = false;
injectLucideIcons();
initSliderGuards();
});
}).observe(document.documentElement, { childList: true, subtree: true });
// Auto-expand and ensure visibility of any Gradio Toast notifications
new MutationObserver(function () {
var toastMsgs = document.querySelectorAll('.toast-messages');
for (var i = 0; i < toastMsgs.length; i++) {
toastMsgs[i].style.setProperty('display', 'flex', 'important');
}
}).observe(document.documentElement, { childList: true, subtree: true });
// ============================================================
// Client-Side Slider & Number Guard: prevent empty / null values
// ============================================================
var SLIDER_DEFAULTS = {
'lora-strength': '1.0',
'steps-slider': '6',
'seed-number': '42'
};
function guardSliderInput(input) {
if (!input) return;
var val = input.value;
if (val === '' || val === null || val === undefined || isNaN(Number(val))) {
var fallback = '1.0';
var container = input.closest ? input.closest('#lora-strength, #steps-slider, #seed-number, .gradio-slider, .gradio-number') : null;
if (container && container.id && SLIDER_DEFAULTS[container.id]) {
fallback = SLIDER_DEFAULTS[container.id];
} else if (input.min !== undefined && input.min !== '') {
fallback = input.min;
}
setValue(input, fallback);
}
}
function initSliderGuards() {
document.querySelectorAll('.gradio-slider input, .gradio-number input, #lora-strength input, #steps-slider input, #seed-number input').forEach(function(inp) {
if (inp.getAttribute('data-guard-init') === '1') return;
inp.setAttribute('data-guard-init', '1');
inp.addEventListener('blur', function() { guardSliderInput(inp); });
inp.addEventListener('change', function() { guardSliderInput(inp); });
});
}
document.addEventListener('click', function(e) {
// Accordion toggle -> refresh gallery & prompt history immediately
var acc = e.target.closest ? e.target.closest('#prompt-history-accordion, #acc-gallery, .label-wrap, summary') : null;
if (acc) {
setTimeout(function() {
if (window.renderPromptHistory) window.renderPromptHistory();
if (window.renderGalleryFromDB) window.renderGalleryFromDB();
}, 50);
setTimeout(function() {
if (window.renderPromptHistory) window.renderPromptHistory();
if (window.renderGalleryFromDB) window.renderGalleryFromDB();
}, 250);
}
var genBtn = e.target.closest ? e.target.closest('#generate-btn, button#generate-btn') : null;
if (genBtn) {
document.querySelectorAll('.gradio-slider input, .gradio-number input, #lora-strength input, #steps-slider input, #seed-number input').forEach(guardSliderInput);
var p = '';
var tb = document.querySelector('#prompt-box textarea, #prompt-box input, textarea[data-testid="textbox"], textarea');
if (tb && tb.value) p = tb.value.trim();
if (p) {
window.pendingGenerationPrompt = p;
if (window.addPromptToHistory) {
window.addPromptToHistory(p);
}
}
var pollCount = 0;
var pollInterval = setInterval(function() {
pollCount++;
if (window.autoSaveGeneratedImage) window.autoSaveGeneratedImage();
if (pollCount > 120) clearInterval(pollInterval);
}, 500);
}
}, true);
window.toggleAllAccordions = function(expand) {
var target = expand ? 'true' : 'false';
var headers = document.querySelectorAll('.gr-accordion > .label-wrap, .label-wrap, button.label-wrap, .accordion-header, summary');
headers.forEach(function(btn) {
var isExpanded = btn.getAttribute('aria-expanded');
if (isExpanded === null) {
var parent = btn.closest('.gr-accordion, .accordion, details');
if (parent) {
if (parent.tagName === 'DETAILS') {
isExpanded = parent.open ? 'true' : 'false';
} else {
isExpanded = (parent.classList.contains('open') || !parent.classList.contains('closed')) ? 'true' : 'false';
}
}
}
if (isExpanded !== target) {
btn.click();
}
});
setTimeout(function() {
if (window.renderGalleryFromDB) window.renderGalleryFromDB();
if (window.renderPromptHistory) window.renderPromptHistory();
}, 100);
};
function startIdb() {
initTheme();
initIdbListener();
renderGalleryFromDB();
if (window.renderPromptHistory) { window.renderPromptHistory(); }
injectLucideIcons();
initSliderGuards();
window.renderGalleryFromDB = renderGalleryFromDB;
window.renderPromptHistory = renderPromptHistory;
window.addPromptToHistory = addPromptToHistory;
window.autoSaveGeneratedImage = autoSaveGeneratedImage;
window.toggleAllAccordions = window.toggleAllAccordions;
}
if (document.readyState === 'loading') {
window.addEventListener('DOMContentLoaded', startIdb);
} else {
setTimeout(startIdb, 200);
}
window.addEventListener('load', startIdb);
})();
</script>
"""
CONTAINER_HEAD_CSS = """
<script>
(function() {
// Proactive cleanup of any corrupt or empty localStorage keys
try {
['qwen_studio_prompt_history_v1', 'qwen_studio_presets_v1', 'qwen_presets'].forEach(function(k) {
var v = localStorage.getItem(k);
if (v !== null) {
if (!v || v.trim() === '') {
localStorage.removeItem(k);
} else {
try { JSON.parse(v); } catch(e) { localStorage.removeItem(k); }
}
}
});
} catch(e) {}
var saved = localStorage.getItem('qwen_theme');
var isDark = saved ? saved === 'dark' : true;
if (isDark) {
document.documentElement.classList.add('dark');
if (document.body) { document.body.classList.add('dark'); }
} else {
document.documentElement.classList.remove('dark');
if (document.body) { document.body.classList.remove('dark'); }
}
})();
</script>
<style>
/* Outer Canvas Layout: Center Gradio app, no horizontal overflow */
body, html {
background-color: var(--background, #09090b) !important;
margin: 0 !important;
padding: 0 !important;
font-family: var(--font-sans, 'Plus Jakarta Sans', sans-serif) !important;
overflow-x: hidden !important;
max-width: 100vw !important;
box-sizing: border-box !important;
}
gradio-app {
display: flex !important;
flex-direction: column !important;
align-items: center !important;
width: 100% !important;
min-height: 100vh !important;
background-color: var(--background, #09090b) !important;
overflow-x: hidden !important;
max-width: 100vw !important;
box-sizing: border-box !important;
}
/* Gradio Default Container Width applies; strictly centered without forcing 1440px widening */
.gradio-container,
.gradio-container-6-31-0,
.gradio-container.svelte-99kmwu,
.main.app,
.main.fillable,
.gradio-container .main,
.gradio-container main.contain,
#studio-header,
#main-grid {
width: 100% !important;
margin-left: auto !important;
margin-right: auto !important;
box-sizing: border-box !important;
}
/* Critical Head Styles for Exact Parity */
/* Universal Eradication of Gradio Form / Styler Gray Backgrounds & Outlines */
div.styler,
.styler,
fieldset,
fieldset.form,
.form,
div.form,
div.gr-form,
.block.form,
.gr-form,
label.container,
.input-container,
div[data-testid="row"] > .form,
div[data-testid="row"] > .styler {
background: transparent !important;
background-color: transparent !important;
border: none !important;
box-shadow: none !important;
padding: 0 !important;
border-radius: 0 !important;
overflow: visible !important;
}
div.styler > :not(.absolute),
.styler > :not(.absolute),
.form > :not(.absolute) {
border: none !important;
border-radius: var(--radius, 8px) !important;
}
#main-grid > #left-controls,
#main-grid > #right-preview,
#left-controls,
#right-preview,
div#left-controls,
div#right-preview,
div#left-controls.block,
div#right-preview.block {
background: var(--card) !important;
background-color: var(--card) !important;
border: 1px solid var(--border) !important;
border-radius: 8px !important;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.05) !important;
padding: 24px !important;
box-sizing: border-box !important;
}
#idb-trigger {
display: none !important;
}
.gr-accordion,
div.gr-accordion,
.studio-section,
div.studio-section,
.accordion,
[data-testid="accordion"] {
border: none !important;
border-top: none !important;
border-left: none !important;
border-right: none !important;
border-bottom: 1px solid var(--border) !important;
border-radius: 0 !important;
background: transparent !important;
background-color: transparent !important;
box-shadow: none !important;
padding: 0 0 16px 0 !important;
margin: 0 0 16px 0 !important;
width: 100% !important;
}
.gr-accordion.no-border,
.studio-section.no-border,
.gr-accordion:last-child,
.studio-section:last-child {
border-bottom: none !important;
padding-bottom: 0 !important;
margin-bottom: 0 !important;
}
.gr-accordion > button.label-wrap,
.studio-section > button.label-wrap,
button.label-wrap,
.label-wrap {
background: transparent !important;
background-color: transparent !important;
border: none !important;
padding: 0 0 8px 0 !important;
margin: 0 !important;
width: 100% !important;
display: flex !important;
align-items: center !important;
justify-content: space-between !important;
font-size: 0.75rem !important;
font-weight: 600 !important;
text-transform: uppercase !important;
letter-spacing: 0.05em !important;
color: var(--foreground) !important;
cursor: pointer !important;
}
#mode-selector input,
.mode-radio-group input,
.gr-radio input,
[data-testid="radio-group"] input,
input[type="radio"],
#mode-selector .circle,
.mode-radio-group .circle,
.gr-radio .circle,
[data-testid="radio-group"] .circle,
#mode-selector svg.circle,
.gr-radio svg.circle,
#mode-selector span:has(input),
.mode-radio-group span:has(input),
.gr-radio span:has(input) {
display: none !important;
visibility: hidden !important;
width: 0 !important;
height: 0 !important;
margin: 0 !important;
padding: 0 !important;
position: absolute !important;
opacity: 0 !important;
pointer-events: none !important;
-webkit-appearance: none !important;
appearance: none !important;
}
/* Ensure Gradio Toast notifications are always prominent, visible, and legible */
.toast-wrap,
.toast-wrap.svelte-1qhecvt,
div[class*="toast-wrap"] {
z-index: 9999999 !important;
position: fixed !important;
top: 20px !important;
right: 20px !important;
max-width: 440px !important;
width: auto !important;
display: flex !important;
flex-direction: column !important;
gap: 10px !important;
pointer-events: auto !important;
}
.toast-item,
.toast-item.svelte-1qhecvt {
width: 100% !important;
max-width: 440px !important;
display: block !important;
}
.toast-body,
.toast-body.svelte-irmu64,
div[class*="toast-body"] {
background: #ffffff !important;
background-color: #ffffff !important;
color: #09090b !important;
border: 1px solid #e4e4e7 !important;
border-radius: 8px !important;
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.2), 0 8px 10px -6px rgba(0, 0, 0, 0.1) !important;
opacity: 1 !important;
visibility: visible !important;
overflow: hidden !important;
display: flex !important;
flex-direction: column !important;
pointer-events: auto !important;
min-width: 300px !important;
}
.dark .toast-body,
.dark .toast-body.svelte-irmu64,
.dark div[class*="toast-body"],
:root.dark .toast-body {
background: #18181b !important;
background-color: #18181b !important;
color: #fafafa !important;
border: 1px solid #27272a !important;
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.5), 0 8px 10px -6px rgba(0, 0, 0, 0.3) !important;
}
.toast-body.error,
div[class*="toast-body"].error,
div[class*="toast-body"][class*="error"] {
border-left: 5px solid #ef4444 !important;
}
.toast-body.warning,
div[class*="toast-body"].warning {
border-left: 5px solid #f59e0b !important;
}
.toast-body.success,
div[class*="toast-body"].success {
border-left: 5px solid #10b981 !important;
}
.toast-header,
.toast-header.svelte-irmu64 {
padding: 10px 14px 6px 14px !important;
display: flex !important;
align-items: center !important;
}
.toast-title,
.toast-title.svelte-irmu64 {
color: #09090b !important;
font-weight: 700 !important;
font-size: 0.875rem !important;
}
.dark .toast-title,
.dark .toast-title.svelte-irmu64 {
color: #fafafa !important;
}
.toast-messages,
.toast-messages.svelte-irmu64 {
padding: 0 14px 12px 14px !important;
display: flex !important;
flex-direction: column !important;
}
.toast-message-text,
.toast-message-text.svelte-irmu64 {
color: #3f3f46 !important;
font-size: 0.8125rem !important;
line-height: 1.5 !important;
font-weight: 500 !important;
word-break: break-word !important;
}
.dark .toast-message-text,
.dark .toast-message-text.svelte-irmu64 {
color: #d4d4d8 !important;
}
.toast-close,
.toast-close.svelte-irmu64 {
color: #71717a !important;
opacity: 0.8 !important;
cursor: pointer !important;
}
.toast-close:hover {
opacity: 1 !important;
color: #09090b !important;
}
.dark .toast-close:hover {
color: #fafafa !important;
}
</style>
"""
COMBINED_HEAD = FONT_HEAD + CONTAINER_HEAD_CSS + HEAD_JS
CUSTOM_CSS = """
/* Tailwind Standard CSS Variables */
:root {
--font-sans: 'Plus Jakarta Sans', system-ui, -apple-system, sans-serif;
--font-mono: 'JetBrains Mono', monospace;
/* Uniform Radius Scale */
--radius-sm: 6px;
--radius: 8px;
--radius-md: 8px;
--radius-lg: 12px;
--radius-full: 9999px;
/* Tailwind Neutral / Zinc Palette - Light Mode */
--background: #ffffff;
--foreground: #09090b;
--card: #ffffff;
--card-foreground: #09090b;
--popover: #ffffff;
--popover-foreground: #09090b;
--primary: #18181b;
--primary-foreground: #fafafa;
--secondary: #f4f4f5;
--secondary-foreground: #18181b;
--muted: #f4f4f5;
--muted-foreground: #71717a;
--accent: #e4e4e7;
--accent-foreground: #18181b;
--destructive: #ef4444;
--destructive-foreground: #fafafa;
--border: #e4e4e7;
--border-hover: #a1a1aa;
--input: #e4e4e7;
--ring: #18181b;
}
.dark, :root.dark, body.dark, gradio-app.dark, html.dark {
/* Tailwind Neutral / Zinc Palette - Dark Mode */
--background: #09090b;
--foreground: #fafafa;
--card: #121215;
--card-foreground: #fafafa;
--popover: #121215;
--popover-foreground: #fafafa;
--primary: #fafafa;
--primary-foreground: #18181b;
--secondary: #1a1a1e;
--secondary-foreground: #fafafa;
--muted: #1a1a1e;
--muted-foreground: #a1a1aa;
--accent: #24242a;
--accent-foreground: #fafafa;
--destructive: #7f1d1d;
--destructive-foreground: #fafafa;
--border: #2e2e34;
--border-hover: #52525b;
--input: #2e2e34;
--ring: #d4d4d8;
}
/* Global Font & Layout */
body, html {
font-family: var(--font-sans) !important;
background-color: var(--background) !important;
color: var(--foreground) !important;
letter-spacing: -0.011em !important;
line-height: 1.5 !important;
transition: background-color 0.2s ease, color 0.2s ease;
}
/* Default Gradio Container: centered without forcing 1440px */
.gradio-container {
width: 100% !important;
margin-left: auto !important;
margin-right: auto !important;
padding: 20px 16px !important;
background-color: var(--background) !important;
color: var(--foreground) !important;
font-family: var(--font-sans) !important;
box-sizing: border-box !important;
overflow-x: hidden !important;
}
@media (min-width: 640px) {
.gradio-container {
padding: 24px 20px !important;
}
}
@media (min-width: 1024px) {
.gradio-container {
padding: 24px 24px !important;
}
}
/* Remove default prose 65ch width cap everywhere in Gradio */
.prose {
max-width: 100% !important;
width: 100% !important;
}
/* Ensure the navbar wrapper spans 100% width of container with tight spacing to sections */
#studio-header,
div:has(> #studio-header),
div:has(#studio-header),
.gradio-container > .block:has(.shadcn-header),
.gradio-container > div:has(.shadcn-header),
div:has(.shadcn-header),
.prose:has(.shadcn-header),
.html-container:has(.shadcn-header) {
width: 100% !important;
max-width: 100% !important;
padding: 0 !important;
margin: 18px auto 10px auto !important;
border: none !important;
background: transparent !important;
box-shadow: none !important;
box-sizing: border-box !important;
}
/* Section Toolbar: Collapse / Expand All Buttons */
.section-toolbar {
display: flex !important;
align-items: center !important;
justify-content: flex-end !important;
gap: 8px !important;
margin: 0 auto 12px auto !important;
width: 100% !important;
max-width: 100% !important;
box-sizing: border-box !important;
}
.section-toggle-btn {
display: inline-flex !important;
align-items: center !important;
gap: 6px !important;
padding: 6px 12px !important;
font-size: 0.75rem !important;
font-weight: 500 !important;
border-radius: var(--radius-sm, 6px) !important;
border: 1px solid var(--border) !important;
background: var(--card) !important;
color: var(--muted-foreground) !important;
cursor: pointer !important;
transition: all 0.15s ease !important;
line-height: 1 !important;
}
.section-toggle-btn:hover {
background: var(--secondary) !important;
color: var(--foreground) !important;
border-color: var(--ring, var(--primary)) !important;
}
/* Smaller Uploaded Image Previews */
#ref-img-1,
#ref-img-2 {
max-height: 240px !important;
}
#ref-img-1 img,
#ref-img-2 img {
max-height: 220px !important;
object-fit: contain !important;
background-color: var(--secondary) !important;
}
/* Shadcn Header - Exact width match with main-grid */
.shadcn-header {
display: flex !important;
align-items: center !important;
justify-content: space-between !important;
padding: 14px 20px !important;
margin: 0 !important;
border: 1px solid var(--border) !important;
border-radius: var(--radius) !important;
background: var(--card) !important;
width: 100% !important;
max-width: 100% !important;
box-sizing: border-box !important;
}
.shadcn-header-left {
display: flex;
align-items: center;
gap: 16px;
flex-wrap: wrap;
}
.shadcn-brand {
display: flex;
align-items: center;
gap: 12px;
}
/* NO SHADOW AND NO BORDER ON LOGO */
.shadcn-brand-icon {
width: 32px;
height: 32px;
display: flex;
align-items: center;
justify-content: center;
background: transparent !important;
border: none !important;
box-shadow: none !important;
padding: 0 !important;
margin: 0 !important;
flex-shrink: 0;
}
.shadcn-brand-icon:hover {
border: none !important;
box-shadow: none !important;
transform: none !important;
}
.qwen-logo-svg {
width: 32px;
height: 32px;
display: block;
}
.shadcn-brand-title {
font-size: 1.125rem;
font-weight: 700;
letter-spacing: -0.02em;
color: var(--foreground);
line-height: 1.25;
}
.shadcn-brand-desc {
font-size: 0.8125rem;
color: var(--muted-foreground);
}
.shadcn-badges {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.shadcn-badge {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 0.75rem;
font-weight: 500;
padding: 4px 10px;
border-radius: var(--radius-sm);
line-height: 1;
}
.shadcn-badge-outline {
border: 1px solid var(--border);
background: var(--background);
color: var(--foreground);
}
.shadcn-badge-accent {
background: var(--secondary);
color: var(--foreground);
border: 1px solid var(--border);
}
.shadcn-badge-muted {
background: var(--muted);
color: var(--muted-foreground);
border: 1px solid var(--border);
}
.badge-icon {
width: 12px;
height: 12px;
opacity: 0.85;
}
.shadcn-theme-btn {
display: inline-flex;
align-items: center;
gap: 8px;
background: var(--card);
color: var(--foreground);
border: 1px solid var(--border);
padding: 8px 12px;
border-radius: var(--radius-md);
font-size: 0.8125rem;
font-weight: 500;
cursor: pointer;
transition: all 0.15s ease;
}
.shadcn-theme-btn:hover {
background: var(--secondary);
border-color: var(--muted-foreground);
}
/* Main Grid Layout */
#main-grid {
display: grid !important;
grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr) !important;
gap: 20px !important;
align-items: start !important;
width: 100% !important;
max-width: 100% !important;
box-sizing: border-box !important;
margin: 0 auto !important;
}
@media (max-width: 1024px) {
#main-grid {
grid-template-columns: 1fr !important;
gap: 16px !important;
}
}
#main-grid > #left-controls,
#main-grid > #right-preview,
#left-controls,
#right-preview,
div#left-controls,
div#right-preview,
div#left-controls.block,
div#right-preview.block {
display: flex !important;
flex-direction: column !important;
gap: 0 !important;
background: var(--card) !important;
background-color: var(--card) !important;
border: 1px solid var(--border) !important;
border-radius: var(--radius-lg, 8px) !important;
box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.05) !important;
padding: 24px !important;
box-sizing: border-box !important;
transition: border-color 0.15s ease !important;
}
#left-controls:hover, #right-preview:hover {
border-color: var(--border-hover) !important;
}
/* Strip generic Gradio block wrappers and form stylers from having gray backgrounds/borders */
.block,
.prose,
.html-container,
div[data-testid="block"],
div.styler,
.styler,
fieldset,
fieldset.form,
.form,
div.form,
div.gr-form,
.block.form,
.gr-form,
label.container,
.input-container,
div[data-testid="row"] > .form,
div[data-testid="row"] > .styler {
background: transparent !important;
background-color: transparent !important;
border: none !important;
box-shadow: none !important;
padding: 0 !important;
border-radius: 0 !important;
}
div.styler > :not(.absolute),
.styler > :not(.absolute),
.form > :not(.absolute) {
border: none !important;
border-radius: var(--radius, 8px) !important;
}
/* SECTION ACCORDIONS (Inside the 2 master cards) */
.gr-accordion,
div.gr-accordion,
.studio-section,
div.studio-section,
.accordion,
[data-testid="accordion"] {
border: none !important;
border-top: none !important;
border-left: none !important;
border-right: none !important;
border-bottom: 1px solid var(--border) !important;
border-radius: 0 !important;
background: transparent !important;
background-color: transparent !important;
padding: 0 0 16px 0 !important;
margin: 0 0 16px 0 !important;
box-shadow: none !important;
width: 100% !important;
box-sizing: border-box !important;
}
.studio-section.no-border,
.gr-accordion.no-border,
.accordion.no-border,
.studio-section:last-child,
.gr-accordion:last-child,
.no-border {
border-bottom: none !important;
padding-bottom: 0 !important;
margin-bottom: 0 !important;
}
.gr-accordion > button.label-wrap,
.studio-section > button.label-wrap,
button.label-wrap,
.label-wrap {
display: flex !important;
align-items: center !important;
justify-content: space-between !important;
width: 100% !important;
background: transparent !important;
background-color: transparent !important;
border: none !important;
box-shadow: none !important;
padding: 0 0 10px 0 !important;
margin: 0 !important;
cursor: pointer !important;
font-family: var(--font-sans) !important;
font-size: 0.75rem !important;
font-weight: 600 !important;
text-transform: uppercase !important;
letter-spacing: 0.05em !important;
color: var(--foreground) !important;
transition: opacity 0.15s ease !important;
}
.gr-accordion > button.label-wrap:hover,
button.label-wrap:hover {
opacity: 0.8 !important;
}
.studio-section-header {
display: flex !important;
align-items: center !important;
justify-content: space-between !important;
width: 100% !important;
margin-bottom: 10px !important;
padding: 0 !important;
background: transparent !important;
border: none !important;
}
.studio-section-title {
font-size: 0.75rem !important;
font-weight: 600 !important;
text-transform: uppercase !important;
letter-spacing: 0.05em !important;
color: var(--foreground) !important;
display: inline-flex !important;
align-items: center !important;
gap: 8px !important;
}
.studio-section-desc {
display: none !important;
}
.tab-helper {
font-size: 0.8125rem;
color: var(--muted-foreground);
display: block;
margin-bottom: 8px;
}
/* Radio Group: Clean Segmented Controls with 8px radius */
#mode-selector,
.mode-radio-group,
.gr-radio,
[data-testid="radio-group"],
.gradio-radio {
display: grid !important;
grid-template-columns: repeat(4, minmax(0, 1fr)) !important;
gap: 8px !important;
width: 100% !important;
margin-top: 4px !important;
margin-bottom: 4px !important;
border: none !important;
background: transparent !important;
padding: 0 !important;
box-shadow: none !important;
}
@media (max-width: 640px) {
#mode-selector,
.mode-radio-group,
.gr-radio,
[data-testid="radio-group"],
.gradio-radio {
grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
}
}
#mode-selector .wrap,
.mode-radio-group .wrap,
.gr-radio .wrap,
[data-testid="radio-group"] .wrap {
display: contents !important;
border: none !important;
background: transparent !important;
}
#mode-selector label,
.mode-radio-group label,
.gr-radio label,
[data-testid="radio-group"] label {
height: 38px !important;
min-height: 38px !important;
max-height: 38px !important;
padding: 0 10px !important;
border: 1px solid var(--border) !important;
border-radius: var(--radius) !important;
background-color: var(--background) !important;
color: var(--foreground) !important;
font-size: 0.75rem !important;
font-weight: 500 !important;
cursor: pointer !important;
transition: all 0.15s ease !important;
display: inline-flex !important;
align-items: center !important;
justify-content: center !important;
gap: 6px !important;
text-align: center !important;
box-sizing: border-box !important;
margin: 0 !important;
}
#mode-selector label:hover,
.mode-radio-group label:hover,
.gr-radio label:hover,
[data-testid="radio-group"] label:hover {
background-color: var(--secondary) !important;
border-color: var(--border-hover) !important;
}
#mode-selector label.selected,
#mode-selector label:has(input:checked),
.mode-radio-group label.selected,
.mode-radio-group label:has(input:checked),
.gr-radio label.selected,
.gr-radio label:has(input:checked),
[data-testid="radio-group"] label.selected,
[data-testid="radio-group"] label:has(input:checked) {
background-color: var(--primary) !important;
color: var(--primary-foreground) !important;
border-color: var(--primary) !important;
font-weight: 600 !important;
}
#mode-selector label.selected svg,
#mode-selector label:has(input:checked) svg,
.mode-radio-group label.selected svg,
.mode-radio-group label:has(input:checked) svg,
.gr-radio label.selected svg,
.gr-radio label:has(input:checked) svg,
[data-testid="radio-group"] label.selected svg,
[data-testid="radio-group"] label:has(input:checked) svg {
stroke: var(--primary-foreground) !important;
}
/* Completely remove the radio circle in all Gradio versions */
#mode-selector input,
.mode-radio-group input,
.gr-radio input,
.gr-radio input[type="radio"],
input[type="radio"],
.gr-radio .circle,
.gr-radio svg.circle,
.gr-radio span:has(input),
.gr-radio span:first-child:not(.lucide-injected-wrap),
[data-testid="radio-group"] input,
[data-testid="radio-group"] .circle,
[data-testid="radio-group"] span:has(input),
#mode-selector .circle,
.mode-radio-group .circle {
display: none !important;
visibility: hidden !important;
width: 0 !important;
height: 0 !important;
margin: 0 !important;
padding: 0 !important;
position: absolute !important;
opacity: 0 !important;
pointer-events: none !important;
-webkit-appearance: none !important;
appearance: none !important;
}
/* Inputs & Form Controls: 8px Radius, standard padding */
textarea, input[type="text"], input[type="number"], select {
font-family: var(--font-sans) !important;
background-color: var(--background) !important;
color: var(--foreground) !important;
border: 1px solid var(--border) !important;
border-radius: var(--radius) !important;
font-size: 0.875rem !important;
padding: 8px 12px !important;
line-height: 1.5 !important;
transition: border-color 0.15s ease, box-shadow 0.15s ease !important;
}
textarea:focus, input:focus, select:focus {
border-color: var(--ring) !important;
box-shadow: 0 0 0 1px var(--ring) !important;
outline: none !important;
}
/* Buttons: 8px Radius */
button.primary, button.gr-button-primary, #generate-btn {
background-color: var(--primary) !important;
color: var(--primary-foreground) !important;
border: 1px solid var(--primary) !important;
border-radius: var(--radius) !important;
font-family: var(--font-sans) !important;
font-weight: 600 !important;
font-size: 0.9375rem !important;
padding: 10px 20px !important;
box-shadow: 0 1px 2px 0 rgba(0, 0, 0, 0.05) !important;
transition: all 0.15s ease !important;
width: 100% !important;
margin-top: 4px !important;
margin-bottom: 2px !important;
cursor: pointer !important;
}
button.primary:hover, button.gr-button-primary:hover, #generate-btn:hover {
opacity: 0.92 !important;
transform: translateY(-1px) !important;
}
button.primary:active, #generate-btn:active {
transform: translateY(0) !important;
}
button.secondary, button.gr-button-secondary, .gr-button:not(.primary) {
background-color: var(--secondary) !important;
color: var(--secondary-foreground) !important;
border: 1px solid var(--border) !important;
border-radius: var(--radius) !important;
font-family: var(--font-sans) !important;
font-weight: 500 !important;
font-size: 0.8125rem !important;
padding: 7px 12px !important;
transition: all 0.15s ease !important;
cursor: pointer !important;
}
button.secondary:hover, .gr-button:not(.primary):hover {
background-color: var(--accent) !important;
border-color: var(--muted-foreground) !important;
}
/* Studio Form Field Labels */
.studio-field-label {
font-size: 0.8125rem !important;
font-weight: 600 !important;
color: var(--foreground) !important;
margin-top: 10px !important;
margin-bottom: 4px !important;
display: block !important;
line-height: 1.25 !important;
letter-spacing: -0.01em !important;
}
div:has(> .studio-field-label),
.prose:has(> .studio-field-label) {
margin: 0 !important;
padding: 0 !important;
}
/* Form Action Grid: 2-Column Table Grid for Input + Action Button */
.form-action-grid {
display: grid !important;
grid-template-columns: minmax(0, 1fr) 200px !important;
gap: 10px !important;
align-items: center !important;
width: 100% !important;
margin-top: 2px !important;
margin-bottom: 12px !important;
}
.form-action-grid > div,
.form-action-grid > .form,
.form-action-grid > .block {
margin: 0 !important;
padding: 0 !important;
border: none !important;
background: transparent !important;
width: 100% !important;
}
.form-action-grid .block {
padding: 0 !important;
margin: 0 !important;
border: none !important;
background: transparent !important;
}
.form-action-grid label.container,
.form-action-grid .input-container {
padding: 0 !important;
margin: 0 !important;
border: none !important;
}
/* Standardized 40px height on both Column 1 (input) and Column 2 (button) */
.form-action-grid textarea,
.form-action-grid input[type="text"]:not(.wrap input),
.form-action-grid input[type="number"],
.form-action-grid select {
height: 40px !important;
min-height: 40px !important;
max-height: 40px !important;
line-height: 1.5 !important;
padding: 8px 12px !important;
font-size: 0.875rem !important;
box-sizing: border-box !important;
margin: 0 !important;
}
/* ============================================================
Universal Dropdown Styling:
- Outer container (.block / .gradio-dropdown) is completely transparent with no border/padding
- Colored wrapper (.wrap) is strictly 40px height, 8px radius, border & background
- Inner wrap (.wrap-inner) & secondary wrap fill 100% width and 100% height of wrapper
- Inner input is 100% width and 100% height, completely borderless & transparent
- Chevron icon is pinned cleanly to the far right end of the colored wrapper
============================================================ */
.gradio-dropdown,
.gr-dropdown,
[data-testid="dropdown"],
.block.gradio-dropdown {
width: 100% !important;
border: none !important;
box-shadow: none !important;
background: transparent !important;
background-color: transparent !important;
padding: 0 !important;
margin: 0 !important;
}
.gradio-dropdown > label,
.gr-dropdown > label,
[data-testid="dropdown"] > label {
width: 100% !important;
background: transparent !important;
background-color: transparent !important;
border: none !important;
padding: 0 !important;
margin: 0 !important;
}
/* Colored wrapper element */
.gradio-dropdown .wrap,
.gr-dropdown .wrap,
[data-testid="dropdown"] .wrap,
.form-action-grid .gradio-dropdown .wrap {
width: 100% !important;
height: 40px !important;
min-height: 40px !important;
max-height: 40px !important;
border: 1px solid var(--border) !important;
background-color: var(--background) !important;
border-radius: var(--radius, 8px) !important;
box-sizing: border-box !important;
display: flex !important;
align-items: center !important;
padding: 0 12px !important;
margin: 0 !important;
box-shadow: none !important;
position: relative !important;
overflow: hidden !important;
}
.gradio-dropdown .wrap:focus-within,
.gr-dropdown .wrap:focus-within,
[data-testid="dropdown"] .wrap:focus-within {
border-color: var(--ring) !important;
box-shadow: 0 0 0 1px var(--ring) !important;
}
/* Inner wrap: match 100% width and height of the colored wrapper */
.gradio-dropdown .wrap-inner,
.gr-dropdown .wrap-inner,
[data-testid="dropdown"] .wrap-inner,
.form-action-grid .gradio-dropdown .wrap-inner {
width: 100% !important;
height: 100% !important;
min-height: 100% !important;
max-height: 100% !important;
display: flex !important;
align-items: center !important;
justify-content: space-between !important;
gap: 8px !important;
padding: 0 !important;
margin: 0 !important;
border: none !important;
background: transparent !important;
background-color: transparent !important;
box-shadow: none !important;
box-sizing: border-box !important;
}
/* Secondary wrap: match 100% height and flex width */
.gradio-dropdown .secondary-wrap,
.gr-dropdown .secondary-wrap,
[data-testid="dropdown"] .secondary-wrap,
.form-action-grid .gradio-dropdown .secondary-wrap {
flex: 1 1 auto !important;
width: 100% !important;
height: 100% !important;
min-height: 100% !important;
max-height: 100% !important;
display: flex !important;
align-items: center !important;
padding: 0 !important;
margin: 0 !important;
border: none !important;
background: transparent !important;
background-color: transparent !important;
box-sizing: border-box !important;
}
/* Reset dropdown inner input: 100% width & height, zero borders/padding conflicts */
.gradio-dropdown input,
.gradio-dropdown input[type="text"],
.gr-dropdown input,
.gr-dropdown input[type="text"],
[data-testid="dropdown"] input,
[data-testid="dropdown"] input[type="text"],
.gradio-dropdown .secondary-wrap input,
.gr-dropdown .secondary-wrap input,
.form-action-grid .gradio-dropdown input {
width: 100% !important;
height: 100% !important;
min-height: 100% !important;
max-height: 100% !important;
line-height: 38px !important;
background: transparent !important;
background-color: transparent !important;
border: none !important;
border-radius: 0 !important;
box-shadow: none !important;
outline: none !important;
color: var(--foreground) !important;
font-size: 0.875rem !important;
padding: 0 !important;
margin: 0 !important;
box-sizing: border-box !important;
cursor: pointer !important;
}
.gradio-dropdown input:focus,
.gr-dropdown input:focus,
[data-testid="dropdown"] input:focus {
border: none !important;
box-shadow: none !important;
outline: none !important;
background: transparent !important;
background-color: transparent !important;
}
/* Pin Chevron Icon to Far Right Edge of Wrapper */
.gradio-dropdown svg,
.gr-dropdown svg,
.gradio-dropdown .dropdown-arrow,
.gr-dropdown .dropdown-arrow,
.gradio-dropdown .icon,
.gr-dropdown .icon,
[data-testid="dropdown"] svg,
[data-testid="dropdown"] .icon,
[data-testid="dropdown"] .dropdown-arrow {
margin-left: auto !important;
flex-shrink: 0 !important;
display: inline-flex !important;
align-items: center !important;
justify-content: center !important;
color: var(--muted-foreground) !important;
pointer-events: none !important;
width: 16px !important;
height: 16px !important;
}
/* Dropdown Choices Menu */
.gradio-dropdown ul.options,
.gr-dropdown ul.options,
[data-testid="dropdown"] ul.options,
.options {
background-color: var(--background) !important;
border: 1px solid var(--border) !important;
border-radius: var(--radius, 8px) !important;
color: var(--foreground) !important;
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.4) !important;
z-index: 1000 !important;
}
.gradio-dropdown ul.options li,
.gr-dropdown ul.options li,
[data-testid="dropdown"] ul.options li,
.options li {
color: var(--foreground) !important;
padding: 8px 12px !important;
font-size: 0.875rem !important;
}
.gradio-dropdown ul.options li:hover,
.gr-dropdown ul.options li:hover,
[data-testid="dropdown"] ul.options li:hover,
.options li:hover,
.options li.selected {
background-color: var(--secondary) !important;
color: var(--foreground) !important;
}
.form-action-grid button,
.form-action-grid .action-btn,
.form-action-grid .gr-button {
height: 40px !important;
min-height: 40px !important;
max-height: 40px !important;
width: 100% !important;
padding: 0 16px !important;
font-size: 0.8125rem !important;
font-weight: 500 !important;
display: inline-flex !important;
align-items: center !important;
justify-content: center !important;
gap: 6px !important;
margin: 0 !important;
white-space: nowrap !important;
box-sizing: border-box !important;
background-color: var(--secondary) !important;
color: var(--secondary-foreground) !important;
border: 1px solid var(--border) !important;
border-radius: var(--radius) !important;
transition: all 0.15s ease !important;
cursor: pointer !important;
}
.form-action-grid button:hover,
.form-action-grid .action-btn:hover {
background-color: var(--accent) !important;
border-color: var(--foreground) !important;
}
.form-action-grid .btn-delete-template:hover {
background-color: rgba(239, 68, 68, 0.1) !important;
color: #ef4444 !important;
border-color: #ef4444 !important;
}
/* LoRA and Generation Settings Rows: Clean transparent gap layout */
#acc-lora .form,
#acc-lora .styler,
#acc-settings .form,
#acc-settings .styler,
div:has(> #lora-dropdown),
div:has(> #aspect-ratio-dropdown) {
display: flex !important;
flex-direction: row !important;
gap: 16px !important;
background: transparent !important;
border: none !important;
box-shadow: none !important;
padding: 0 !important;
margin: 4px 0 12px 0 !important;
align-items: center !important;
width: 100% !important;
}
@media (max-width: 640px) {
#acc-lora .form,
#acc-lora .styler,
#acc-settings .form,
#acc-settings .styler {
flex-direction: column !important;
gap: 8px !important;
}
}
/* Sliders: Clean 8px styling with mono numeric readout */
.gradio-slider,
.gradio-slider.block {
background: transparent !important;
border: none !important;
box-shadow: none !important;
padding: 0 !important;
margin: 0 !important;
}
.gradio-slider .head {
display: flex !important;
align-items: center !important;
justify-content: space-between !important;
margin-bottom: 4px !important;
}
.gradio-slider .head span,
.gradio-slider label span,
.gradio-dropdown label span,
.gradio-number label span {
font-size: 0.75rem !important;
font-weight: 600 !important;
color: var(--foreground) !important;
letter-spacing: -0.01em !important;
}
.gradio-slider .head input[type="number"],
.gradio-slider input[type="number"] {
font-family: var(--font-mono) !important;
font-size: 0.75rem !important;
color: var(--muted-foreground) !important;
background-color: var(--background) !important;
border: 1px solid var(--border) !important;
border-radius: var(--radius-sm, 6px) !important;
padding: 2px 6px !important;
height: 24px !important;
width: 52px !important;
text-align: right !important;
box-sizing: border-box !important;
}
.gradio-slider input[type="range"] {
accent-color: var(--primary) !important;
cursor: pointer !important;
height: 6px !important;
border-radius: 9999px !important;
width: 100% !important;
}
/* Number Inputs: 40px height, mono, crisp border */
.gradio-number,
.gradio-number.block {
background: transparent !important;
border: none !important;
box-shadow: none !important;
padding: 0 !important;
margin: 0 !important;
}
.gradio-number input[type="number"] {
height: 40px !important;
min-height: 40px !important;
max-height: 40px !important;
background-color: var(--background) !important;
color: var(--foreground) !important;
border: 1px solid var(--border) !important;
border-radius: var(--radius, 8px) !important;
box-sizing: border-box !important;
font-family: var(--font-mono) !important;
font-size: 0.875rem !important;
padding: 8px 12px !important;
}
/* Seed & Checkbox Row Grid: Perfect 40px height alignment */
.seed-action-grid,
.seed-action-grid .styler,
.seed-action-grid .form,
.seed-action-grid fieldset {
display: flex !important;
flex-direction: row !important;
gap: 16px !important;
align-items: flex-end !important;
width: 100% !important;
margin-top: 2px !important;
margin-bottom: 8px !important;
background: transparent !important;
border: none !important;
padding: 0 !important;
}
.seed-action-grid .gradio-number {
flex: 1 1 auto !important;
margin: 0 !important;
padding: 0 !important;
}
.seed-action-grid .gradio-checkbox,
.seed-action-grid .gradio-checkbox.block {
flex: 0 0 auto !important;
background: transparent !important;
border: none !important;
padding: 0 !important;
margin: 0 !important;
}
.seed-action-grid .gr-checkbox,
.seed-action-grid label.checkbox-container,
.seed-action-grid label.checkbox,
.seed-action-grid .gradio-checkbox label,
.seed-action-grid label {
height: 40px !important;
min-height: 40px !important;
max-height: 40px !important;
display: inline-flex !important;
align-items: center !important;
gap: 8px !important;
margin: 0 !important;
padding: 0 !important;
cursor: pointer !important;
background: transparent !important;
background-color: transparent !important;
border: none !important;
box-shadow: none !important;
color: var(--foreground) !important;
font-size: 0.8125rem !important;
font-weight: 500 !important;
}
.seed-action-grid input[type="checkbox"] {
width: 16px !important;
height: 16px !important;
min-width: 16px !important;
min-height: 16px !important;
border: 1px solid var(--border) !important;
border-radius: 4px !important;
accent-color: var(--foreground) !important;
background-color: var(--background) !important;
margin: 0 !important;
padding: 0 !important;
cursor: pointer !important;
display: inline-block !important;
visibility: visible !important;
opacity: 1 !important;
position: static !important;
}
/* Used Prompt Textarea (Exact parity with index.html) */
#used-prompt,
#used-prompt.block,
#used-prompt label,
#used-prompt .container,
#used-prompt .wrap,
#used-prompt > div {
background: transparent !important;
background-color: transparent !important;
border: none !important;
box-shadow: none !important;
padding: 0 !important;
margin: 0 0 12px 0 !important;
width: 100% !important;
}
#used-prompt span,
#used-prompt label > span {
font-size: 0.75rem !important;
font-weight: 600 !important;
color: var(--foreground) !important;
letter-spacing: -0.01em !important;
margin-bottom: 4px !important;
display: block !important;
}
#used-prompt textarea,
#used-prompt textarea:disabled,
#used-prompt textarea[readonly] {
background-color: var(--secondary) !important;
color: var(--muted-foreground) !important;
border: 1px solid var(--border) !important;
border-radius: var(--radius, 8px) !important;
font-family: var(--font-mono) !important;
font-size: 0.75rem !important;
line-height: 1.5 !important;
padding: 10px 12px !important;
resize: none !important;
width: 100% !important;
box-sizing: border-box !important;
opacity: 1 !important;
cursor: text !important;
}
@media (max-width: 640px) {
.form-action-grid {
grid-template-columns: 1fr !important;
gap: 8px !important;
}
}
/* Curated LoRA Presets: Symmetrical 3x3 Grid */
.curated-grid {
display: grid !important;
grid-template-columns: repeat(3, minmax(0, 1fr)) !important;
gap: 8px !important;
width: 100% !important;
margin-top: 6px !important;
margin-bottom: 6px !important;
}
.curated-grid button {
width: 100% !important;
margin: 0 !important;
padding: 8px 8px !important;
font-size: 0.8125rem !important;
border-radius: var(--radius) !important;
display: inline-flex !important;
align-items: center !important;
justify-content: center !important;
white-space: nowrap !important;
overflow: hidden !important;
text-overflow: ellipsis !important;
}
@media (max-width: 640px) {
.curated-grid {
grid-template-columns: repeat(2, minmax(0, 1fr)) !important;
}
}
/* Accordions: Card Accordion with clean divider */
.gr-accordion,
div.gr-accordion,
.studio-section,
div.studio-section,
.accordion,
[data-testid="accordion"] {
border: none !important;
border-top: none !important;
border-left: none !important;
border-right: none !important;
border-bottom: 1px solid var(--border) !important;
border-radius: 0 !important;
background-color: transparent !important;
padding: 0 0 16px 0 !important;
margin: 0 0 16px 0 !important;
box-sizing: border-box !important;
box-shadow: none !important;
width: 100% !important;
}
.gr-accordion.no-border,
.studio-section.no-border,
.accordion.no-border,
[data-testid="accordion"].no-border,
.no-border {
border-bottom: none !important;
padding-bottom: 0 !important;
margin-bottom: 0 !important;
}
.gr-accordion > button.label-wrap,
.studio-section > button.label-wrap,
.accordion > .label-wrap,
.label-wrap,
button.label-wrap,
summary,
.accordion-header {
padding: 0 0 8px 0 !important;
cursor: pointer !important;
background: transparent !important;
background-color: transparent !important;
font-size: 0.75rem !important;
font-weight: 600 !important;
text-transform: uppercase !important;
letter-spacing: 0.05em !important;
color: var(--foreground) !important;
display: flex !important;
align-items: center !important;
justify-content: flex-start !important;
gap: 8px !important;
width: 100% !important;
text-align: left !important;
transition: opacity 0.15s ease !important;
}
.gr-accordion > button.label-wrap:hover,
.studio-section > button.label-wrap:hover,
.accordion > .label-wrap:hover,
.label-wrap:hover,
button.label-wrap:hover {
opacity: 0.8 !important;
background: transparent !important;
}
.accordion > .label-wrap *,
.label-wrap * {
text-align: left !important;
}
.accordion > .label-wrap .label,
.label-wrap .label,
.accordion > .label-wrap > span:not(.icon),
.label-wrap > span:not(.icon) {
display: inline-flex !important;
align-items: center !important;
gap: 8px !important;
text-align: left !important;
justify-content: flex-start !important;
margin: 0 !important;
flex: none !important;
}
.accordion > .label-wrap .lucide-injected-wrap.acc-icon,
.label-wrap .lucide-injected-wrap.acc-icon {
width: 15px !important;
height: 15px !important;
margin: 0 4px 0 0 !important;
display: inline-flex !important;
vertical-align: middle !important;
flex-shrink: 0 !important;
}
/* Push caret / chevron cleanly to the far right end */
.accordion > .label-wrap .icon,
.label-wrap .icon,
.accordion > .label-wrap > svg:last-child,
.label-wrap > svg:last-child,
.accordion > .label-wrap > div:last-child:has(svg),
.label-wrap > div:last-child:has(svg),
.accordion > .label-wrap > span:last-child:has(svg),
.label-wrap > span:last-child:has(svg) {
margin-left: auto !important;
display: inline-flex !important;
align-items: center !important;
justify-content: center !important;
}
/* Nested Accordion: Inner Card */
.accordion .accordion {
border: 1px solid var(--border) !important;
border-radius: var(--radius) !important;
background-color: var(--secondary) !important;
padding: 10px 14px !important;
margin: 10px 0 0 0 !important;
}
/* Tabs: Flat Underline Tabs */
.tabs {
border: none !important;
background: transparent !important;
margin: 10px 0 !important;
}
.tab-nav {
display: flex !important;
border-bottom: 1px solid var(--border) !important;
background: transparent !important;
padding: 0 !important;
gap: 4px !important;
}
button.tab-item {
font-family: var(--font-sans) !important;
font-size: 0.8125rem !important;
font-weight: 500 !important;
color: var(--muted-foreground) !important;
border: none !important;
border-bottom: 2px solid transparent !important;
background: transparent !important;
padding: 8px 12px !important;
border-radius: var(--radius) var(--radius) 0 0 !important;
transition: all 0.15s ease !important;
margin-bottom: -1px !important;
display: inline-flex !important;
align-items: center !important;
gap: 6px !important;
}
button.tab-item:hover {
color: var(--foreground) !important;
}
button.tab-item.selected {
color: var(--foreground) !important;
border-bottom: 2px solid var(--foreground) !important;
background: transparent !important;
font-weight: 600 !important;
}
.tab-content {
padding: 12px 0 0 0 !important;
background: transparent !important;
overflow-x: hidden !important;
}
/* LoRA Status Banner: 8px Radius */
#lora-status-banner {
padding: 8px 12px;
border-radius: var(--radius) !important;
background: var(--secondary);
border: 1px solid var(--border);
font-size: 0.8125rem;
color: var(--secondary-foreground);
margin: 4px 0 8px 0;
display: flex;
align-items: center;
gap: 8px;
}
.status-indicator {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50% !important;
margin-right: 6px;
vertical-align: middle;
}
.status-indicator.base { background: #a1a1aa; }
.status-indicator.active { background: #10b981; }
.status-indicator.custom { background: #3b82f6; }
/* Output Image / Canvas Viewport: 8px Radius */
#output-image {
border: 1px dashed var(--border) !important;
border-radius: var(--radius-lg) !important;
background-color: var(--secondary) !important;
min-height: 480px !important;
height: 500px !important;
display: flex !important;
flex-direction: column !important;
align-items: center !important;
justify-content: center !important;
overflow: hidden !important;
position: relative !important;
transition: all 0.2s ease !important;
margin-top: 4px !important;
margin-bottom: 8px !important;
}
#output-image:hover {
border-color: var(--border-hover) !important;
}
#output-image .image-container {
height: 100% !important;
width: 100% !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
background: transparent !important;
}
#output-image img {
max-height: 480px !important;
width: auto !important;
object-fit: contain !important;
border-radius: var(--radius) !important;
}
#output-image .empty {
display: flex !important;
flex-direction: column !important;
align-items: center !important;
justify-content: center !important;
gap: 12px !important;
color: var(--muted-foreground) !important;
padding: 40px !important;
}
#output-image .empty::before {
content: "";
display: block;
width: 44px;
height: 44px;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%2371717a' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Crect width='18' height='18' x='3' y='3' rx='2' ry='2'%3E%3C/rect%3E%3Ccircle cx='9' cy='9' r='2'%3E%3C/circle%3E%3Cpath d='m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21'%3E%3C/path%3E%3C/svg%3E");
background-size: contain;
background-repeat: no-repeat;
opacity: 0.6;
}
#output-image .empty::after {
content: "Canvas Preview\\A Generated image will render here with full resolution";
white-space: pre-line;
text-align: center;
font-size: 0.875rem;
font-weight: 500;
color: var(--muted-foreground);
line-height: 1.4;
}
#output-image .empty svg {
display: none !important;
}
/* Download file component: 8px Radius */
#download-file {
border: 1px solid var(--border) !important;
border-radius: var(--radius) !important;
background: var(--background) !important;
padding: 6px 12px !important;
margin-top: 4px !important;
margin-bottom: 6px !important;
}
#download-file .file-preview {
background: transparent !important;
border: none !important;
}
#download-file .empty {
min-height: 44px !important;
padding: 8px 12px !important;
}
/* Prompt sent to model: 8px Radius */
#used-prompt {
margin-top: 6px !important;
}
#used-prompt textarea {
font-family: var(--font-mono) !important;
font-size: 0.8125rem !important;
color: var(--muted-foreground) !important;
background: var(--secondary) !important;
border: 1px solid var(--border) !important;
border-radius: var(--radius) !important;
}
/* Injected SVG Icons */
.lucide-injected-wrap {
display: inline-flex !important;
align-items: center !important;
justify-content: center !important;
vertical-align: middle !important;
margin-right: 6px !important;
flex-shrink: 0 !important;
line-height: 1 !important;
}
.lucide-injected-wrap svg {
display: block !important;
width: 14px !important;
height: 14px !important;
stroke: currentColor !important;
}
.lucide-injected-wrap.acc-icon svg {
width: 15px !important;
height: 15px !important;
margin-right: 2px !important;
}
.lucide-injected-wrap.radio-icon svg {
width: 13px !important;
height: 13px !important;
}
#generate-btn .lucide-injected-wrap svg {
width: 18px !important;
height: 18px !important;
margin-right: 4px !important;
}
/* Prompt Presets Hidden Bridge - Clip only the textbox itself, never parent containers */
#pp-cmd,
#pp-cmd textarea,
#pp-cmd input {
position: absolute !important;
width: 1px !important;
height: 1px !important;
padding: 0 !important;
margin: -1px !important;
overflow: hidden !important;
clip: rect(0, 0, 0, 0) !important;
white-space: nowrap !important;
border: 0 !important;
opacity: 0 !important;
pointer-events: none !important;
}
.pp-wrap { display: flex; flex-direction: column; gap: 8px; margin: 4px 0 12px 0; }
.pp-section { font-weight: 600; font-size: 0.8125rem; color: var(--foreground); display: flex; align-items: center; gap: 6px; }
.pp-hint { font-weight: 400; color: var(--muted-foreground); font-size: 0.75rem; }
.pp-empty { color: var(--muted-foreground); font-size: 0.8125rem; padding: 4px 0; font-style: italic; }
.pp-list {
display: flex !important;
flex-wrap: wrap !important;
gap: 6px !important;
margin: 4px 0 12px 0 !important;
}
.pp-item {
display: inline-flex !important;
align-items: center !important;
border: 1px solid var(--border) !important;
border-radius: var(--radius) !important;
background-color: var(--secondary) !important;
color: var(--foreground) !important;
overflow: hidden !important;
transition: all 0.15s ease !important;
font-size: 0.75rem !important;
}
.pp-item:hover {
border-color: var(--foreground) !important;
}
.pp-use {
border: none !important;
background: transparent !important;
cursor: pointer !important;
padding: 5px 9px !important;
font-size: 0.75rem !important;
color: inherit !important;
font-weight: 500 !important;
font-family: var(--font-sans) !important;
}
.pp-use:hover {
background-color: var(--accent) !important;
}
.pp-fav {
border: none !important;
background: transparent !important;
cursor: pointer !important;
padding: 5px 7px !important;
font-size: 0.75rem !important;
color: var(--muted-foreground) !important;
transition: all 0.15s ease !important;
display: inline-flex !important;
align-items: center !important;
justify-content: center !important;
}
.pp-fav:hover {
color: #f59e0b !important;
background-color: var(--accent) !important;
}
.pp-fav.is-on {
color: #f59e0b !important;
}
.pp-star-svg {
display: block !important;
}
.pp-fav.is-on .pp-star-svg {
fill: #f59e0b !important;
stroke: #f59e0b !important;
}
.pp-fav:not(.is-on) .pp-star-svg {
stroke: currentColor !important;
fill: none !important;
}
.pp-ghost { opacity: 0.35; }
/* Private Browser Gallery (IndexedDB) */
#idb-gallery-wrap {
margin-top: 4px;
display: flex;
flex-direction: column;
gap: 12px;
}
.idb-toolbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 10px 12px;
background: var(--secondary);
border: 1px solid var(--border);
border-radius: var(--radius);
font-size: 0.75rem;
}
.idb-count {
font-weight: 500;
color: var(--foreground);
display: flex;
align-items: center;
gap: 6px;
font-size: 0.75rem;
}
.idb-btn-danger, #idb-clear-btn {
background: #ef4444 !important;
color: #ffffff !important;
border: 1px solid #ef4444 !important;
border-radius: var(--radius) !important;
padding: 5px 12px !important;
font-size: 0.75rem !important;
font-weight: 500 !important;
cursor: pointer !important;
display: inline-flex !important;
align-items: center !important;
gap: 6px !important;
transition: all 0.15s ease !important;
}
.idb-btn-danger:hover, #idb-clear-btn:hover {
background: #dc2626 !important;
color: #ffffff !important;
border-color: #dc2626 !important;
}
.idb-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
gap: 12px;
max-height: 480px;
overflow-y: auto;
padding: 2px;
}
.idb-empty {
grid-column: 1 / -1;
text-align: center;
font-style: italic;
color: var(--muted-foreground);
font-size: 0.75rem;
padding: 24px 0;
}
/* Studio Footer */
.studio-footer {
width: 100% !important;
max-width: 100% !important;
margin: 32px auto 16px auto !important;
padding: 16px 0 !important;
text-align: center !important;
font-size: 0.75rem !important;
color: var(--muted-foreground) !important;
border-top: 1px solid var(--border) !important;
display: flex !important;
align-items: center !important;
justify-content: center !important;
gap: 16px !important;
flex-wrap: wrap !important;
}
text-align: center;
padding: 24px 12px;
color: var(--muted-foreground);
font-size: 0.8125rem;
font-style: italic;
border: 1px dashed var(--border);
border-radius: var(--radius-md);
}
.idb-card {
position: relative;
border: 1px solid var(--border);
border-radius: var(--radius-md);
overflow: hidden;
background: var(--card);
transition: transform 0.15s ease, box-shadow 0.15s ease, border-color 0.15s ease;
}
.idb-card:hover {
transform: translateY(-2px);
border-color: var(--foreground);
box-shadow: 0 4px 12px -2px rgba(0, 0, 0, 0.12);
}
.idb-thumb-wrap {
position: relative;
width: 100%;
aspect-ratio: 1;
background: var(--secondary);
overflow: hidden;
}
.idb-thumb {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.idb-card-overlay {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.65);
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
opacity: 0;
transition: opacity 0.15s ease;
}
.idb-card:hover .idb-card-overlay {
opacity: 1;
}
.idb-btn-sm {
background: rgba(255, 255, 255, 0.95);
color: #09090b;
border: none;
border-radius: var(--radius-sm);
padding: 4px 8px;
font-size: 0.6875rem;
font-weight: 600;
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 4px;
transition: transform 0.1s ease;
}
.idb-btn-sm:hover {
transform: scale(1.05);
background: #ffffff;
}
.idb-meta {
padding: 6px 8px;
display: flex;
align-items: center;
justify-content: space-between;
font-family: var(--font-mono);
font-size: 0.6875rem;
color: var(--muted-foreground);
background: var(--card);
border-top: 1px solid var(--border);
}
/* Lightbox Modal */
.idb-modal {
position: fixed;
inset: 0;
z-index: 99999;
display: flex;
align-items: center;
justify-content: center;
padding: 20px;
}
.idb-modal-backdrop {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.75);
backdrop-filter: blur(4px);
}
.idb-modal-content {
position: relative;
z-index: 10;
max-width: 900px;
width: 100%;
max-height: 90vh;
background: var(--card);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
overflow: hidden;
box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.2);
display: flex;
flex-direction: column;
}
.idb-modal-close {
position: absolute;
top: 12px;
right: 12px;
z-index: 20;
width: 28px;
height: 28px;
border-radius: var(--radius-full);
background: rgba(0, 0, 0, 0.65);
color: #ffffff;
border: none;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: background 0.15s ease;
}
.idb-modal-close:hover {
background: #ef4444;
}
.idb-modal-img-wrap {
display: flex;
align-items: center;
justify-content: center;
background: #000000;
max-height: 58vh;
overflow: hidden;
}
#idb-modal-img {
max-height: 58vh;
max-width: 100%;
object-fit: contain;
}
.idb-modal-info {
padding: 14px 18px;
display: flex;
flex-direction: column;
gap: 10px;
background: var(--card);
}
.idb-modal-prompt {
font-size: 0.8125rem;
max-height: 72px;
overflow-y: auto;
line-height: 1.4;
padding: 8px 12px;
background: var(--secondary);
border: 1px solid var(--border);
border-radius: var(--radius-md);
color: var(--foreground);
}
.idb-modal-tags {
display: flex;
flex-wrap: wrap;
gap: 6px;
font-size: 0.75rem;
font-family: var(--font-mono);
color: var(--muted-foreground);
}
.idb-modal-tags span {
background: var(--secondary);
border: 1px solid var(--border);
padding: 3px 8px;
border-radius: var(--radius-sm);
display: inline-flex;
align-items: center;
gap: 4px;
}
.idb-modal-actions {
display: flex;
gap: 8px;
margin-top: 2px;
}
.idb-btn-primary {
background: var(--primary) !important;
color: var(--primary-foreground) !important;
text-decoration: none;
padding: 8px 16px;
border-radius: var(--radius-md);
font-size: 0.8125rem;
font-weight: 600;
display: inline-flex;
align-items: center;
gap: 6px;
}
.idb-btn-primary:hover {
opacity: 0.9;
}
.idb-btn-secondary {
background: var(--secondary);
color: var(--secondary-foreground);
border: 1px solid var(--border);
padding: 8px 14px;
border-radius: var(--radius-md);
font-size: 0.8125rem;
font-weight: 500;
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 6px;
}
.idb-btn-secondary:hover {
background: var(--accent);
}
/* Ensure Gradio Toast notifications are always prominent, visible, and legible */
.toast-wrap,
.toast-wrap.svelte-1qhecvt,
div[class*="toast-wrap"] {
z-index: 9999999 !important;
position: fixed !important;
top: 20px !important;
right: 20px !important;
max-width: 440px !important;
width: auto !important;
display: flex !important;
flex-direction: column !important;
gap: 10px !important;
pointer-events: auto !important;
}
.toast-item,
.toast-item.svelte-1qhecvt {
width: 100% !important;
max-width: 440px !important;
display: block !important;
}
.toast-body,
.toast-body.svelte-irmu64,
div[class*="toast-body"] {
background: #ffffff !important;
background-color: #ffffff !important;
color: #09090b !important;
border: 1px solid #e4e4e7 !important;
border-radius: 8px !important;
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.2), 0 8px 10px -6px rgba(0, 0, 0, 0.1) !important;
opacity: 1 !important;
visibility: visible !important;
overflow: hidden !important;
display: flex !important;
flex-direction: column !important;
pointer-events: auto !important;
min-width: 300px !important;
}
.dark .toast-body,
.dark .toast-body.svelte-irmu64,
.dark div[class*="toast-body"],
:root.dark .toast-body {
background: #18181b !important;
background-color: #18181b !important;
color: #fafafa !important;
border: 1px solid #27272a !important;
box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.5), 0 8px 10px -6px rgba(0, 0, 0, 0.3) !important;
}
.toast-body.error,
div[class*="toast-body"].error,
div[class*="toast-body"][class*="error"] {
border-left: 5px solid #ef4444 !important;
}
.toast-body.warning,
div[class*="toast-body"].warning {
border-left: 5px solid #f59e0b !important;
}
.toast-body.success,
div[class*="toast-body"].success {
border-left: 5px solid #10b981 !important;
}
.toast-header,
.toast-header.svelte-irmu64 {
padding: 10px 14px 6px 14px !important;
display: flex !important;
align-items: center !important;
}
.toast-title,
.toast-title.svelte-irmu64 {
color: #09090b !important;
font-weight: 700 !important;
font-size: 0.875rem !important;
}
.dark .toast-title,
.dark .toast-title.svelte-irmu64 {
color: #fafafa !important;
}
.toast-messages,
.toast-messages.svelte-irmu64 {
padding: 0 14px 12px 14px !important;
display: flex !important;
flex-direction: column !important;
}
.toast-message-text,
.toast-message-text.svelte-irmu64 {
color: #3f3f46 !important;
font-size: 0.8125rem !important;
line-height: 1.5 !important;
font-weight: 500 !important;
word-break: break-word !important;
}
.dark .toast-message-text,
.dark .toast-message-text.svelte-irmu64 {
color: #d4d4d8 !important;
}
.toast-close,
.toast-close.svelte-irmu64 {
color: #71717a !important;
opacity: 0.8 !important;
cursor: pointer !important;
}
.toast-close:hover {
opacity: 1 !important;
color: #09090b !important;
}
.dark .toast-close:hover {
color: #fafafa !important;
}
"""
# ============================================================
# Gradio Blocks Application
# ============================================================
with gr.Blocks(title="Qwen Image 2.1 Uncensored All-In-One LoRA Studio") as demo:
gr.HTML("""
<header class="shadcn-header">
<div class="shadcn-header-left">
<div class="shadcn-brand">
<div class="shadcn-brand-icon">
<svg class="qwen-logo-svg" viewBox="0 0 24 24" fill="currentColor" fill-rule="evenodd" xmlns="http://www.w3.org/2000/svg">
<path d="M12.604 1.34c.393.69.784 1.382 1.174 2.075a.18.18 0 00.157.091h5.552c.174 0 .322.11.446.327l1.454 2.57c.19.337.24.478.024.837-.26.43-.513.864-.76 1.3l-.367.658c-.106.196-.223.28-.04.512l2.652 4.637c.172.301.111.494-.043.77-.437.785-.882 1.564-1.335 2.34-.159.272-.352.375-.68.37-.777-.016-1.552-.01-2.327.016a.099.099 0 00-.081.05 575.097 575.097 0 01-2.705 4.74c-.169.293-.38.363-.725.364-.997.003-2.002.004-3.017.002a.537.537 0 01-.465-.271l-1.335-2.323a.09.09 0 00-.083-.049H4.982c-.285.03-.553-.001-.805-.092l-1.603-2.77a.543.543 0 01-.002-.54l1.207-2.12a.198.198 0 000-.197 550.951 550.951 0 01-1.875-3.272l-.79-1.395c-.16-.31-.173-.496.095-.965.465-.813.927-1.625 1.387-2.436.132-.234.304-.334.584-.335a338.3 338.3 0 012.589-.001.124.124 0 00.107-.063l2.806-4.895a.488.488 0 01.422-.246c.524-.001 1.053 0 1.583-.006L11.704 1c.341-.003.724.032.9.34zm-3.432.403a.06.06 0 00-.052.03L6.254 6.788a.157.157 0 01-.135.078H3.253c-.056 0-.07.025-.041.074l5.81 10.156c.025.042.013.062-.034.063l-2.795.015a.218.218 0 00-.2.116l-1.32 2.31c-.044.078-.021.118.068.118l5.716.008c.046 0 .08.02.104.061l1.403 2.454c.046.081.092.082.139 0l5.006-8.76.783-1.382a.055.055 0 01.096 0l1.424 2.53a.122.122 0 00.107.062l2.763-.02a.04.04 0 00.035-.02.041.041 0 000-.04l-2.9-5.086a.108.108 0 010-.113l.293-.507 1.12-1.977c.024-.041.012-.062-.035-.062H9.2c-.059 0-.073-.026-.043-.077l1.434-2.505a.107.107 0 000-.114L9.225 1.774a.06.06 0 00-.053-.031zm6.29 8.02c.046 0 .058.02.034.06l-.832 1.465-2.613 4.585a.056.056 0 01-.05.029.058.058 0 01-.05-.029L8.498 9.841c-.02-.034-.01-.052.028-.054l.216-.012 6.722-.012z"/>
</svg>
</div>
<div>
<div class="shadcn-brand-title">Qwen Studio 2.1</div>
<div class="shadcn-brand-desc">Uncensored GGUF Diffusion & LoRA Speed Hub</div>
</div>
</div>
<div class="shadcn-badges">
<span class="shadcn-badge shadcn-badge-outline">
<svg class="badge-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
Uncensored GGUF Q4_K_M
</span>
<span class="shadcn-badge shadcn-badge-accent">
<svg class="badge-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>
Viggle Turbo (6 Steps)
</span>
<span class="shadcn-badge shadcn-badge-muted">
<svg class="badge-icon" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect width="20" height="8" x="2" y="2" rx="2" ry="2"/><rect width="20" height="8" x="2" y="14" rx="2" ry="2"/><line x1="6" x2="6.01" y1="6" y2="6"/><line x1="6" x2="6.01" y1="18" y2="18"/></svg>
Private Browser IndexedDB
</span>
</div>
</div>
<div class="shadcn-header-right">
<button type="button" class="shadcn-theme-btn" onclick="window.toggleTheme()" title="Toggle Dark/Light Mode">
<svg id="theme-toggle-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="4"/><path d="M12 2v2"/><path d="M12 20v2"/><path d="m4.93 4.93 1.41 1.41"/><path d="m17.66 17.66 1.41 1.41"/><path d="M2 12h2"/><path d="M20 12h2"/><path d="m6.34 17.66-1.41 1.41"/><path d="m19.07 4.93-1.41 1.41"/></svg>
<span class="shadcn-theme-label">Theme</span>
</button>
</div>
</header>
""", elem_id="studio-header")
# Section Toolbar: Collapse / Expand All
gr.HTML("""
<div id="section-toolbar" class="section-toolbar">
<button type="button" class="section-toggle-btn" onclick="window.toggleAllAccordions(false)" title="Collapse All Sections">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 15 5-5 5 5"/></svg>
<span>Collapse All</span>
</button>
<button type="button" class="section-toggle-btn" onclick="window.toggleAllAccordions(true)" title="Expand All Sections">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m7 9 5 5 5-5"/></svg>
<span>Expand All</span>
</button>
</div>
""", elem_id="section-toolbar-container")
with gr.Row(elem_id="main-grid"):
# LEFT COLUMN
with gr.Column(scale=6, elem_id="left-controls"):
# Section 0: Base Model Architecture
with gr.Accordion("Base Model Architecture", open=True, elem_id="acc-base-model", elem_classes=["studio-section"]):
base_model_selector = gr.Radio(
choices=BASE_MODEL_CHOICES,
value=MODEL_GGUF,
label="Base Model Architecture",
show_label=False,
elem_id="base-model-selector",
elem_classes=["mode-radio-group"],
container=False,
)
# Section 1: Generation Mode
with gr.Accordion("Generation Mode", open=True, elem_id="acc-mode", elem_classes=["studio-section"]):
mode_selector = gr.Radio(
choices=MODES,
value=MODES[0],
label="Generation Mode",
show_label=False,
elem_id="mode-selector",
elem_classes=["mode-radio-group"],
container=False,
)
# Section 2: Reference Images & Media Library (Hidden on Text to Image & Transparent PNG)
with gr.Accordion("Reference Images & Media Inputs", open=True, visible=False, elem_id="reference-section", elem_classes=["studio-section"]) as ref_section:
with gr.Row():
ref_img_1 = gr.Image(
label="Reference Image 1 (Base / Target)",
type="pil",
elem_id="ref-img-1",
scale=1,
height=220,
)
ref_img_2 = gr.Image(
label="Reference Image 2 (Donor / Pose Reference)",
type="pil",
visible=False,
elem_id="ref-img-2",
scale=1,
height=220,
)
# Media Library (Batch Staging & Asset Pool) Accordion
with gr.Accordion("Media Library (Batch Staging & Asset Pool)", open=True, elem_id="media-library-accordion"):
gr.HTML("""
<div style="font-size: 11px; color: var(--muted-foreground); margin-bottom: 8px;">
Upload multiple photos at once. Click any thumbnail below, then click <strong>Use as Ref 1</strong> or <strong>Use as Ref 2</strong>.
</div>
""")
batch_upload = gr.File(
label="Batch Upload Images (Asset Pool)",
file_count="multiple",
file_types=["image"],
type="filepath",
)
library_gallery = gr.Gallery(
label="Staged Media Library",
columns=[2, 4],
rows=2,
height=160,
allow_preview=True,
elem_id="library-gallery",
)
selected_lib_file = gr.State(None)
with gr.Row(elem_classes=["form-action-grid"]):
use_ref1_btn = gr.Button("Use Selected as Ref 1", size="sm", elem_classes=["action-btn"])
use_ref2_btn = gr.Button("Use Selected as Ref 2", size="sm", elem_classes=["action-btn"])
clear_library_btn = gr.Button("Clear Library", size="sm", elem_classes=["action-btn", "btn-delete-template"])
# Section 3: Prompt Description
with gr.Accordion("Prompt Description", open=True, elem_id="acc-prompt", elem_classes=["studio-section"]):
prompt = gr.Textbox(
elem_id="prompt-box",
label="Prompt",
show_label=False,
lines=3,
max_lines=6,
placeholder="Describe your vision, character, scene, or requested edit in rich detail...",
)
# Section 4: Prompt History
with gr.Accordion("Prompt History", open=False, elem_id="prompt-history-accordion", elem_classes=["studio-section"]):
prompt_history_state = gr.State([])
history_html = gr.HTML(
'<div id="history-header" style="display:flex;justify-content:space-between;align-items:center;margin-bottom:8px;"><span id="history-count-badge" style="font-size:11px;font-family:monospace;padding:2px 8px;border-radius:9999px;background:var(--secondary);border:1px solid var(--border);color:var(--muted-foreground);">0 saved</span></div><div id="history-list-box" style="font-size: 12px; color: var(--muted-foreground); font-style: italic;">No prompt history yet. Prompts you generate will be saved here automatically.</div>',
elem_id="history-html"
)
with gr.Row():
clear_history_btn = gr.Button("Clear History", size="sm", elem_classes=["action-btn", "btn-delete-template"])
# Section 5: Prompt Templates & Presets
with gr.Accordion("Prompt Templates & Presets", open=True, elem_id="acc-presets", elem_classes=["studio-section"]):
presets_state = gr.State(DEFAULT_PRESETS)
presets_html = gr.HTML(render_presets_html(DEFAULT_PRESETS), elem_id="pp-html")
pp_cmd = gr.Textbox(elem_id="pp-cmd", show_label=False, container=False, lines=1)
gr.HTML('<div class="studio-field-label">Template Name</div>')
with gr.Row(elem_classes=["form-action-grid"]):
preset_name = gr.Textbox(
show_label=False,
placeholder="e.g. Cyberpunk Portrait (same name = overwrite)",
scale=3,
container=False,
)
save_preset_btn = gr.Button("Save Current Prompt", scale=1, elem_classes=["action-btn"])
gr.HTML('<div class="studio-field-label">Select Template to Delete</div>')
with gr.Row(elem_classes=["form-action-grid"]):
delete_dropdown = gr.Dropdown(
choices=[x["label"] for x in DEFAULT_PRESETS],
value=None,
show_label=False,
scale=3,
container=False,
)
delete_preset_btn = gr.Button("Delete Template", scale=1, elem_classes=["action-btn", "btn-delete-template"])
# Section 6: LoRA Adapters & Acceleration
with gr.Accordion("LoRA Adapters & Acceleration", open=True, elem_id="acc-lora", elem_classes=["studio-section"]):
with gr.Row():
lora_dropdown = gr.Dropdown(
label="LoRA Adapter",
choices=LORA_CHOICES,
value=DEFAULT_LORA,
scale=7,
elem_id="lora-dropdown",
)
lora_strength = gr.Slider(
label="LoRA Strength",
minimum=0.0,
maximum=1.5,
step=0.05,
value=1.0,
scale=5,
elem_id="lora-strength",
)
lora_status_banner = gr.Markdown(
make_status_banner(DEFAULT_LORA, strength=1.0),
elem_id="lora-status-banner",
)
with gr.Tabs(elem_id="lora-source-tabs"):
with gr.Tab("Curated Presets", id="tab-curated"):
gr.Markdown(
"<span class='tab-helper'>Click any button to configure the LoRA, steps, mode, and prompt triggers:</span>"
)
with gr.Row(elem_classes=["curated-grid"]):
btn_real_anatomy = gr.Button("Real Anatomy", size="sm")
btn_body_swap = gr.Button("Body Swap", size="sm")
btn_face_swap = gr.Button("Face Swap", size="sm")
btn_natural_exp = gr.Button("Studio Light", size="sm")
btn_phone_photo = gr.Button("Phone Photo", size="sm")
btn_restore = gr.Button("Restore Photo", size="sm")
btn_outfit = gr.Button("Outfit Swap", size="sm")
btn_anime = gr.Button("Anime", size="sm")
btn_viggle_turbo = gr.Button("Viggle Turbo (6-Step Fast)", variant="secondary", size="sm")
with gr.Tab("Hugging Face Live Explorer", id="tab-explorer"):
gr.Markdown(
"<span class='tab-helper'>Search and test ANY community LoRA for Qwen-Image-2.1 live from Hugging Face Hub:</span>"
)
gr.HTML('<div class="studio-field-label">Search Community LoRAs</div>')
with gr.Row(elem_classes=["form-action-grid"]):
explorer_search = gr.Textbox(
show_label=False,
placeholder="e.g. anatomy, realism, portrait, lighting, swap, 80s",
scale=3,
container=False,
)
explorer_btn = gr.Button("Search Models", scale=1, elem_classes=["action-btn"])
with gr.Row():
explorer_models = gr.Dropdown(label="Found Repositories", choices=[], interactive=True, scale=1)
explorer_files = gr.Dropdown(label="Safetensors Weights File", choices=[], interactive=True, scale=1)
with gr.Row():
explorer_apply = gr.Button("Apply Selected LoRA", variant="primary", scale=1)
with gr.Tab("Custom Repo ID", id="tab-custom"):
gr.Markdown(
"<span class='tab-helper'>Direct manual entry for any Hugging Face model repo and weights filename:</span>"
)
with gr.Row():
custom_repo = gr.Textbox(
label="Hugging Face Repo ID",
placeholder="e.g. WarmBloodAban/Qwen-Image-2.1-LoRAs",
scale=1,
)
custom_file = gr.Textbox(
label="Weights Filename (.safetensors)",
placeholder="e.g. Qwen2.1_Anything2RealCharacters.safetensors",
scale=1,
)
with gr.Row():
custom_apply_btn = gr.Button("Apply Custom LoRA", variant="secondary")
# Section 7: Generation Settings
with gr.Accordion("Generation Settings (Resolution, Steps, Seed)", open=True, elem_id="acc-settings", elem_classes=["studio-section", "no-border"]):
with gr.Row():
aspect_ratio_dropdown = gr.Dropdown(
label="Aspect Ratio & Resolution",
choices=list(SIZES.keys()),
value=AUTO,
scale=3,
elem_id="aspect-ratio-dropdown",
)
steps_slider = gr.Slider(
label="Inference Steps",
minimum=4,
maximum=40,
value=6,
step=1,
scale=3,
elem_id="steps-slider",
)
with gr.Row(visible=False) as custom_row:
custom_width = gr.Slider(label="Custom Width", minimum=256, maximum=2048, step=32, value=1024, scale=1)
custom_height = gr.Slider(label="Custom Height", minimum=256, maximum=2048, step=32, value=1024, scale=1)
with gr.Row(elem_classes=["seed-action-grid"]):
seed_number = gr.Number(label="Seed", value=42, precision=0, scale=3, elem_id="seed-number")
randomize_seed_cb = gr.Checkbox(label="Randomize Seed", value=True, scale=1, elem_id="randomize-seed-cb")
# Section 8: Generate Button (Full Width of left master card)
run = gr.Button("Generate Image", variant="primary", size="lg", elem_id="generate-btn")
# RIGHT COLUMN
with gr.Column(scale=6, elem_id="right-preview"):
# Section R1: Canvas & Result Viewport
with gr.Accordion("Generated Result & Canvas Viewport", open=True, elem_id="acc-canvas", elem_classes=["studio-section"]):
output_image = gr.Image(
label="Generated Result",
show_label=False,
type="pil",
height=500,
interactive=False,
format="png",
elem_id="output-image",
)
# Section R2: Download & Model Prompt
with gr.Accordion("Output Download & Model Prompt", open=True, elem_id="acc-details", elem_classes=["studio-section"]):
download_file = gr.File(
label="Download High-Res Output",
interactive=False,
elem_id="download-file",
)
info = gr.Markdown()
used_prompt = gr.Textbox(label="Prompt sent to the model", lines=2, interactive=False, elem_id="used-prompt")
idb_trigger = gr.Textbox(elem_id="idb-trigger", visible=True, container=False)
# Section R3: Private Browser Gallery (IndexedDB)
with gr.Accordion("Private Browser Gallery (IndexedDB)", open=True, elem_id="acc-gallery", elem_classes=["studio-section", "no-border"]):
idb_gallery_html = gr.HTML("""
<div id="idb-gallery-wrap">
<div class="idb-toolbar">
<span id="idb-count-label" class="idb-count"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5V19A9 3 0 0 0 21 19V5"/><path d="M3 12A9 3 0 0 0 21 12"/></svg>Browser Storage: 0 image(s) (100% Private, 0 KB on Space)</span>
<button type="button" id="idb-clear-btn" class="idb-btn-danger"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>Clear Storage</button>
</div>
<div id="idb-gallery-grid" class="idb-grid">
<div class="idb-empty">No images saved in your browser yet. Generated images will be saved automatically here.</div>
</div>
</div>
<!-- Lightbox Modal for Zoom & Inspection -->
<div id="idb-modal" class="idb-modal" style="display:none;">
<div class="idb-modal-backdrop" onclick="window.closeIdbModal()"></div>
<div class="idb-modal-content">
<button type="button" class="idb-modal-close" onclick="window.closeIdbModal()"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
<div class="idb-modal-img-wrap">
<img id="idb-modal-img" src="" alt="Enlarged view">
</div>
<div class="idb-modal-info">
<div id="idb-modal-meta" class="idb-modal-meta"></div>
<div class="idb-modal-actions">
<a id="idb-modal-dl" href="" download="qwen_generated.png" class="idb-btn-primary"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:inline-block;vertical-align:middle;margin-right:5px;"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/></svg>Download High-Res</a>
<button type="button" id="idb-modal-use-prompt" class="idb-btn-secondary"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:inline-block;vertical-align:middle;margin-right:5px;"><rect width="8" height="4" x="8" y="2" rx="1" ry="1"/><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/></svg>Use Prompt</button>
<button type="button" id="idb-modal-delete" class="idb-btn-danger"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="display:inline-block;vertical-align:middle;margin-right:5px;"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/></svg>Delete</button>
</div>
</div>
</div>
</div>
""")
gr.HTML("""
<footer class="studio-footer">
<span>Qwen Studio 2.1 Viggle Turbo</span>
<span>•</span>
<span>100% Client-Side Storage</span>
<span>•</span>
<span>Shadcn Monochromatic UI</span>
</footer>
""")
# -------------------------------------------------------------
# Event Bindings: Prompt Presets & Templates
# -------------------------------------------------------------
pp_cmd.input(
fn=apply_preset_cmd,
inputs=[pp_cmd, presets_state],
outputs=[presets_state],
queue=False,
show_progress="hidden",
)
save_preset_btn.click(
fn=save_custom_preset,
inputs=[preset_name, prompt, presets_state],
outputs=[presets_state, preset_name],
queue=False,
)
delete_preset_btn.click(
fn=delete_custom_preset,
inputs=[delete_dropdown, presets_state],
outputs=[presets_state],
queue=False,
)
def _refresh_preset_widgets(presets):
cleaned = normalize_presets(presets)
return render_presets_html(cleaned), gr.update(choices=[x["label"] for x in cleaned], value=None)
presets_state.change(
fn=_refresh_preset_widgets,
inputs=[presets_state],
outputs=[presets_html, delete_dropdown],
queue=False,
show_progress="hidden",
)
# -------------------------------------------------------------
# Event Bindings: Mode UI Updates
# -------------------------------------------------------------
mode_selector.change(
fn=update_mode_ui,
inputs=[mode_selector],
outputs=[ref_section, ref_img_1, ref_img_2],
)
# -------------------------------------------------------------
# Event Bindings: Media Library (Batch Staging & Asset Pool)
# -------------------------------------------------------------
def on_batch_upload(files, current_gallery):
if not files:
return current_gallery or []
current_paths = []
for x in (current_gallery or []):
if isinstance(x, (list, tuple)):
current_paths.append(x[0])
elif isinstance(x, dict) and "image" in x:
current_paths.append(x["image"].get("path"))
else:
current_paths.append(str(x))
new_items = []
for f in files:
p = f.name if hasattr(f, "name") else str(f)
if p and p not in current_paths:
new_items.append(p)
return (current_gallery or []) + new_items
batch_upload.change(
fn=on_batch_upload,
inputs=[batch_upload, library_gallery],
outputs=[library_gallery],
)
def on_gallery_select(evt: gr.SelectData):
val = evt.value
if isinstance(val, dict) and "image" in val:
return val["image"].get("path")
elif isinstance(val, (list, tuple)):
return val[0]
return str(val) if val else None
library_gallery.select(
fn=on_gallery_select,
outputs=[selected_lib_file],
)
use_ref1_btn.click(
fn=lambda f: f,
inputs=[selected_lib_file],
outputs=[ref_img_1],
)
use_ref2_btn.click(
fn=lambda f: f,
inputs=[selected_lib_file],
outputs=[ref_img_2],
)
clear_library_btn.click(
fn=lambda: ([], None),
outputs=[library_gallery, selected_lib_file],
)
clear_history_btn.click(
fn=None,
js="() => { window.clearPromptHistory(); }",
)
# -------------------------------------------------------------
# Event Bindings: Curated LoRA Buttons
# -------------------------------------------------------------
btn_real_anatomy.click(
lambda p: apply_curated("Real Characters & Anatomy", p),
inputs=[prompt],
outputs=[prompt, lora_dropdown, lora_strength, steps_slider, mode_selector, ref_img_2, lora_status_banner],
)
btn_body_swap.click(
lambda p: apply_curated("Pose / Body Swap (BFS Body 2.1)", p),
inputs=[prompt],
outputs=[prompt, lora_dropdown, lora_strength, steps_slider, mode_selector, ref_img_2, lora_status_banner],
)
btn_face_swap.click(
lambda p: apply_curated("Face / Head Swap (BFS 2.1)", p),
inputs=[prompt],
outputs=[prompt, lora_dropdown, lora_strength, steps_slider, mode_selector, ref_img_2, lora_status_banner],
)
btn_natural_exp.click(
lambda p: apply_curated("Light Restoration (Natural Exposure)", p),
inputs=[prompt],
outputs=[prompt, lora_dropdown, lora_strength, steps_slider, mode_selector, ref_img_2, lora_status_banner],
)
btn_phone_photo.click(
lambda p: apply_curated("Casual Phone Photo Realism", p),
inputs=[prompt],
outputs=[prompt, lora_dropdown, lora_strength, steps_slider, mode_selector, ref_img_2, lora_status_banner],
)
btn_restore.click(
lambda p: apply_curated("Upscale / Restore (Restore LoRA 2.1)", p),
inputs=[prompt],
outputs=[prompt, lora_dropdown, lora_strength, steps_slider, mode_selector, ref_img_2, lora_status_banner],
)
btn_outfit.click(
lambda p: apply_curated("Outfit & Fashion Swap", p),
inputs=[prompt],
outputs=[prompt, lora_dropdown, lora_strength, steps_slider, mode_selector, ref_img_2, lora_status_banner],
)
btn_anime.click(
lambda p: apply_curated("Anime Consistency", p),
inputs=[prompt],
outputs=[prompt, lora_dropdown, lora_strength, steps_slider, mode_selector, ref_img_2, lora_status_banner],
)
btn_viggle_turbo.click(
lambda p: apply_curated("Viggle Turbo (6-Step Acceleration)", p),
inputs=[prompt],
outputs=[prompt, lora_dropdown, lora_strength, steps_slider, mode_selector, ref_img_2, lora_status_banner],
)
# -------------------------------------------------------------
# Event Bindings: LoRA Explorer & Custom LoRA
# -------------------------------------------------------------
explorer_btn.click(
fn=search_hf_loras,
inputs=[explorer_search],
outputs=[explorer_models],
)
explorer_models.change(
fn=fetch_repo_safetensors,
inputs=[explorer_models],
outputs=[explorer_files],
)
explorer_apply.click(
fn=apply_explorer_selection,
inputs=[explorer_models, explorer_files],
outputs=[lora_dropdown, custom_repo, custom_file, lora_strength, lora_status_banner],
)
custom_apply_btn.click(
fn=apply_custom_selection,
inputs=[custom_repo, custom_file],
outputs=[lora_dropdown, lora_strength, lora_status_banner],
)
def on_lora_change(selected_lora, current_prompt, current_strength, current_steps, repo, file, base_m):
selected_lora = str(selected_lora or "")
new_prompt = str(current_prompt or "")
repo = str(repo or "").strip()
file = str(file or "").strip()
base_m = str(base_m or MODEL_GGUF)
spec = ADAPTER_SPECS.get(selected_lora)
strength = safe_float(current_strength, fallback=1.0, min_val=0.0, max_val=1.5)
steps = safe_int(current_steps, fallback=6, min_val=4, max_val=40)
mode_upd = gr.update()
img2_upd = gr.update()
if spec:
preset = spec.get("preset_prompt", "")
if spec.get("exact_prompt") and preset:
new_prompt = preset
elif preset and not new_prompt.strip():
new_prompt = preset
if "default_strength" in spec and spec["default_strength"] is not None:
strength = safe_float(spec["default_strength"], fallback=strength, min_val=0.0, max_val=1.5)
if "default_steps" in spec and spec["default_steps"] is not None:
steps = safe_int(spec["default_steps"], fallback=steps, min_val=4, max_val=40)
if spec.get("mode"):
mode_upd = gr.update(value=spec["mode"])
if spec.get("image2_label"):
img2_upd = gr.update(label=spec["image2_label"])
status = make_status_banner(selected_lora, repo, file, strength, base_model=base_m)
return new_prompt, strength, steps, mode_upd, img2_upd, status
lora_dropdown.change(
on_lora_change,
inputs=[lora_dropdown, prompt, lora_strength, steps_slider, custom_repo, custom_file, base_model_selector],
outputs=[prompt, lora_strength, steps_slider, mode_selector, ref_img_2, lora_status_banner],
)
lora_strength.change(
lambda lora, repo, file, s, bm: make_status_banner(lora, repo, file, safe_float(s, fallback=1.0), base_model=bm),
inputs=[lora_dropdown, custom_repo, custom_file, lora_strength, base_model_selector],
outputs=[lora_status_banner],
show_progress="hidden",
)
base_model_selector.change(
lambda bm, lora, repo, file, s: make_status_banner(lora, repo, file, safe_float(s, fallback=1.0), base_model=bm),
inputs=[base_model_selector, lora_dropdown, custom_repo, custom_file, lora_strength],
outputs=[lora_status_banner],
)
# -------------------------------------------------------------
# Event Bindings: Generation, Gallery & App Load
# -------------------------------------------------------------
def on_aspect_ratio_change(val, w, h):
is_custom = val == CUSTOM
size = SIZES.get(val)
new_w = safe_int(size[0] if size else w, fallback=1024, min_val=256, max_val=2048)
new_h = safe_int(size[1] if size else h, fallback=1024, min_val=256, max_val=2048)
return gr.update(visible=is_custom), new_w, new_h
aspect_ratio_dropdown.change(
on_aspect_ratio_change,
inputs=[aspect_ratio_dropdown, custom_width, custom_height],
outputs=[custom_row, custom_width, custom_height],
)
randomize_seed_cb.change(lambda on: gr.update(interactive=not on), inputs=randomize_seed_cb, outputs=seed_number)
run.click(
generate,
inputs=[
prompt, mode_selector, ref_img_1, ref_img_2,
lora_dropdown, lora_strength, custom_repo, custom_file,
aspect_ratio_dropdown, steps_slider, seed_number, randomize_seed_cb,
custom_width, custom_height, base_model_selector,
],
outputs=[output_image, download_file, info, used_prompt, idb_trigger],
js="""(...args) => {
try {
var p = (args && args.length > 0 && typeof args[0] === 'string' && args[0].trim()) ? args[0].trim() : '';
if (!p) {
var el = document.querySelector('#prompt-box textarea, #prompt-box input, textarea[data-testid="textbox"], textarea');
if (el && el.value) p = el.value.trim();
}
if (p) {
window.pendingGenerationPrompt = p;
if (window.addPromptToHistory) {
window.addPromptToHistory(p);
}
}
} catch(e) { console.error('Prompt history error:', e); }
return args;
}""",
)
demo.load(
fn=_refresh_preset_widgets,
inputs=[presets_state],
outputs=[presets_html, delete_dropdown],
queue=False,
show_progress="hidden",
)
if __name__ == "__main__":
demo.launch(theme=THEME, css=CUSTOM_CSS, head=COMBINED_HEAD, show_error=True)
|