Spaces:
Running
Running
File size: 95,577 Bytes
80a1334 aae35f1 80a1334 aae35f1 80a1334 aae35f1 80a1334 aae35f1 80a1334 aae35f1 80a1334 aae35f1 80a1334 aae35f1 80a1334 aae35f1 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 cc3e139 80a1334 cc3e139 dd39987 cc3e139 80a1334 cc3e139 80a1334 cc3e139 80a1334 cc3e139 80a1334 cc3e139 80a1334 5c394f2 cc3e139 80a1334 cc3e139 80a1334 e3f7eb9 80a1334 dd39987 cc3e139 80a1334 cc3e139 80a1334 cc3e139 ce6da3c cc3e139 ce6da3c 232dbeb cc3e139 10769e2 cc3e139 d51bcea cc3e139 10769e2 cc3e139 10769e2 d51bcea 10769e2 d51bcea cc3e139 10769e2 cc3e139 10769e2 80a1334 cc3e139 80a1334 cc3e139 10769e2 80a1334 10769e2 cc3e139 10769e2 cc3e139 80a1334 232dbeb cc3e139 80a1334 cc3e139 80a1334 cc3e139 80a1334 cc3e139 80a1334 cc3e139 80a1334 5c394f2 4bf314f cc3e139 80a1334 cc3e139 80a1334 cc3e139 80a1334 cc3e139 80a1334 e3a4ed5 80a1334 cc3e139 80a1334 cc3e139 80a1334 4d30b8d f98b48a e3f7eb9 f98b48a e3f7eb9 80a1334 e3f7eb9 f98b48a 80a1334 4d30b8d e3f7eb9 80a1334 e3f7eb9 80a1334 cc3e139 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 cc3e139 80a1334 cc3e139 e3f7eb9 cc3e139 80a1334 cc3e139 80a1334 dd39987 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 cc3e139 80a1334 cc3e139 80a1334 cc3e139 e3f7eb9 80a1334 cc3e139 80a1334 cc3e139 80a1334 5c394f2 cc3e139 80a1334 cc3e139 80a1334 e3a4ed5 2956194 80a1334 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 fba2633 e3a4ed5 551c807 bb306b0 f98b48a ce6da3c f98b48a ce6da3c f98b48a aae35f1 ce6da3c cc3e139 ce6da3c cc3e139 ce6da3c cc3e139 ce6da3c cc3e139 e3f7eb9 232dbeb cc3e139 e3f7eb9 aae35f1 cc3e139 aae35f1 cc3e139 aae35f1 8d5dd22 aae35f1 8d5dd22 aae35f1 8d5dd22 aae35f1 80a1334 e3f7eb9 cc3e139 e3f7eb9 80a1334 d51bcea e3f7eb9 cc3e139 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 2956194 e3f7eb9 cc3e139 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 2956194 e3f7eb9 80a1334 cc3e139 80a1334 cc3e139 f98b48a 80a1334 e3f7eb9 80a1334 e3f7eb9 f98b48a e3f7eb9 80a1334 cc3e139 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 e3f7eb9 80a1334 5985f91 80a1334 5985f91 80a1334 5985f91 80a1334 5985f91 80a1334 5985f91 80a1334 e3f7eb9 80a1334 5985f91 80a1334 5985f91 80a1334 5985f91 80a1334 5985f91 80a1334 5985f91 80a1334 5985f91 80a1334 e3f7eb9 5985f91 e3f7eb9 80a1334 e3f7eb9 80a1334 cc3e139 80a1334 cc3e139 80a1334 cc3e139 80a1334 cc3e139 80a1334 cc3e139 80a1334 e3f7eb9 cc3e139 e3f7eb9 80a1334 7b1516c cc3e139 ce6da3c cc3e139 ce6da3c 80a1334 cc3e139 ce6da3c cc3e139 80a1334 e3f7eb9 80a1334 7b1516c cc3e139 80a1334 11e1a4e 80a1334 |
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 |
import os
import logging
import gradio as gr
from dotenv import load_dotenv
import google.generativeai as genai
from auto_diffusers import AutoDiffusersGenerator
from simple_memory_calculator import SimpleMemoryCalculator
load_dotenv()
# Configure logging for Gradio app
logger = logging.getLogger(__name__)
class GradioAutodiffusers:
def __init__(self):
logger.info("Initializing GradioAutodiffusers")
self.api_key = os.getenv('GOOGLE_API_KEY')
if not self.api_key:
logger.error("GOOGLE_API_KEY not found in environment variables")
raise ValueError("GOOGLE_API_KEY not found in .env file")
logger.debug(f"API key found, length: {len(self.api_key)}")
try:
self.generator = AutoDiffusersGenerator(self.api_key)
logger.info("AutoDiffusersGenerator initialized successfully")
except Exception as e:
logger.error(f"Failed to initialize AutoDiffusersGenerator: {e}")
raise
try:
self.memory_calculator = SimpleMemoryCalculator()
logger.info("SimpleMemoryCalculator initialized successfully")
except Exception as e:
logger.error(f"Failed to initialize SimpleMemoryCalculator: {e}")
raise
# Default settings
self.current_model = 'gemini-2.5-flash-preview-05-20'
self.temperature = 0.7
self.max_output_tokens = 8192
self.top_p = 0.9
self.top_k = 40
logger.debug(f"Default model settings: {self.current_model}, temp={self.temperature}")
def update_model_settings(self, model_name, temperature, max_output_tokens, top_p, top_k):
"""Update Gemini model settings."""
logger.info(f"Updating model settings: {model_name}")
logger.debug(f"New settings: temp={temperature}, max_tokens={max_output_tokens}, top_p={top_p}, top_k={top_k}")
try:
self.current_model = model_name
self.temperature = temperature
self.max_output_tokens = max_output_tokens
self.top_p = top_p
self.top_k = top_k
# Update the generator's model with new settings
genai.configure(api_key=self.api_key)
generation_config = genai.types.GenerationConfig(
temperature=temperature,
max_output_tokens=max_output_tokens,
top_p=top_p,
top_k=top_k
)
self.generator.model = genai.GenerativeModel(model_name, generation_config=generation_config)
logger.info("Model settings updated successfully")
return f"✅ Model updated to {model_name} with new settings"
except Exception as e:
logger.error(f"Failed to update model settings: {e}")
return f"❌ Failed to update model: {str(e)}"
def get_generation_prompt(self, model_name, prompt_text, image_size, num_inference_steps, hardware_specs, optimization_profile):
"""Get the actual prompt that will be sent to Gemini API."""
return self.generator._create_generation_prompt(
model_name, prompt_text, image_size, num_inference_steps,
hardware_specs, optimization_profile
)
def analyze_model_memory(self, model_name, vram_gb):
"""Analyze model memory requirements and provide recommendations."""
try:
if not vram_gb:
vram_gb = 8 # Default
memory_info = self.memory_calculator.get_model_memory_requirements(model_name)
recommendations = self.memory_calculator.get_memory_recommendation(model_name, float(vram_gb))
formatted_info = self.memory_calculator.format_memory_info(model_name)
return memory_info, recommendations, formatted_info
except Exception as e:
error_msg = f"Error analyzing model memory: {str(e)}"
return {'error': error_msg}, {'error': error_msg}, error_msg
def generate_code_with_manual_specs(self,
gpu_name,
vram_gb,
ram_gb,
platform,
model_name,
prompt_text,
dtype_selection,
width,
height,
inference_steps,
memory_analysis=None):
"""Generate optimized code with manual hardware specifications."""
try:
# Create manual hardware specs
# Parse dtype selection
if dtype_selection == "Auto":
user_dtype = None
else:
user_dtype = f"torch.{dtype_selection}"
manual_specs = {
'platform': platform,
'architecture': 'manual_input',
'cpu_count': 8, # Default
'python_version': '3.11',
'cuda_available': 'nvidia' in gpu_name.lower() if gpu_name else False,
'mps_available': platform == 'Darwin' and 'apple' in gpu_name.lower() if gpu_name else False,
'torch_version': '2.0+',
'manual_input': True,
'ram_gb': int(ram_gb) if ram_gb else 16,
'user_dtype': user_dtype
}
# Add GPU info if provided
if gpu_name and vram_gb:
manual_specs['gpu_info'] = [{
'name': gpu_name,
'memory_mb': int(vram_gb) * 1024
}]
if 'nvidia' in gpu_name.lower():
manual_specs['cuda_available'] = True
manual_specs['cuda_device_count'] = 1
manual_specs['cuda_device_name'] = gpu_name
manual_specs['cuda_memory'] = int(vram_gb)
else:
manual_specs['gpu_info'] = None
# Generate optimized code with manual specs and memory analysis
optimized_code = self.generator.generate_optimized_code(
model_name=model_name,
prompt_text=prompt_text,
image_size=(int(height), int(width)),
num_inference_steps=int(inference_steps),
use_manual_specs=True,
manual_specs=manual_specs,
memory_analysis=memory_analysis
)
# Clean up any markdown formatting
if optimized_code.startswith('```python'):
optimized_code = optimized_code[9:]
if optimized_code.endswith('```'):
optimized_code = optimized_code[:-3]
return optimized_code.strip()
except Exception as e:
return f"Error generating code: {str(e)}"
def create_gradio_interface():
"""Create and configure the Gradio interface."""
app = GradioAutodiffusers()
with gr.Blocks(
title="Auto-Diffusers Code Generator",
theme=gr.themes.Soft(
primary_hue="violet",
secondary_hue="blue",
neutral_hue="slate",
radius_size=gr.themes.sizes.radius_lg,
font=[gr.themes.GoogleFont("Poppins"), gr.themes.GoogleFont("Inter"), "system-ui", "sans-serif"]
).set(
background_fill_primary="*neutral_25",
background_fill_secondary="*neutral_50",
block_background_fill="rgba(255, 255, 255, 0.95)",
block_border_width="0px",
block_shadow="0 8px 32px rgba(0, 0, 0, 0.08)",
panel_background_fill="rgba(255, 255, 255, 0.9)",
button_primary_background_fill="*primary_500",
button_primary_background_fill_hover="*primary_600",
button_secondary_background_fill="rgba(255, 255, 255, 0.8)",
button_secondary_background_fill_hover="rgba(255, 255, 255, 0.95)"
),
css="""
/* Global Styles */
.gradio-container {
background: #fef7f5 !important;
min-height: 100vh;
font-family: 'Georgia', 'Times New Roman', serif !important;
}
/* Dark mode global background */
@media (prefers-color-scheme: dark) {
.gradio-container {
background: #1a1a1a !important;
}
}
.dark,
.gradio-container.dark,
html.dark,
body.dark {
background: #1a1a1a !important;
}
.dark .gradio-container,
.gradio-container.dark,
html.dark .gradio-container,
body.dark .gradio-container {
background: #1a1a1a !important;
}
/* Remove main tag margin and center */
main {
margin: 0 auto !important;
max-width: 100% !important;
}
.main-container {
max-width: 1400px;
margin: 0 auto;
padding: 0.5rem 0.1rem;
/* Removed position: relative that can interfere with dropdown positioning */
}
/* Paper Card Effects */
.glass-card {
background: #fefcfa !important;
border: 1px solid #f4e6e1 !important;
border-radius: 12px !important;
margin-bottom: 0.5rem !important;
padding: 0.5rem !important;
border-top: 3px solid #f0c5b8 !important;
}
.ultra-glass {
background: #fefcfa !important;
border: 1px solid #f4e6e1 !important;
border-radius: 12px !important;
margin-bottom: 0.5rem !important;
padding: 0.5rem !important;
border-left: 4px solid #f0c5b8 !important;
}
/* Dark mode group cards */
@media (prefers-color-scheme: dark) {
.glass-card {
background: #2a2a2a !important;
border: 1px solid #404040 !important;
border-top: 3px solid #666 !important;
}
.ultra-glass {
background: #2a2a2a !important;
border: 1px solid #404040 !important;
border-left: 4px solid #666 !important;
}
}
.dark .glass-card,
.gradio-container.dark .glass-card,
html.dark .glass-card,
body.dark .glass-card {
background: #2a2a2a !important;
border: 1px solid #404040 !important;
border-top: 3px solid #666 !important;
}
.dark .ultra-glass,
.gradio-container.dark .ultra-glass,
html.dark .ultra-glass,
body.dark .ultra-glass {
background: #2a2a2a !important;
border: 1px solid #404040 !important;
border-left: 4px solid #666 !important;
}
/* Paper Header */
.hero-header {
background: #fdf5f3 !important;
border: 2px solid #f4e6e1 !important;
border-radius: 16px !important;
margin-bottom: 1rem !important;
position: relative;
overflow: hidden;
width: 100% !important;
max-width: 100% !important;
box-sizing: border-box !important;
}
/* Dark mode hero header */
@media (prefers-color-scheme: dark) {
.hero-header {
background: #2a2a2a !important;
border: 2px solid #404040 !important;
}
}
.dark .hero-header,
.gradio-container.dark .hero-header,
html.dark .hero-header,
body.dark .hero-header {
background: #2a2a2a !important;
border: 2px solid #404040 !important;
}
/* Dark mode hero header text */
@media (prefers-color-scheme: dark) {
.hero-header h1 {
color: #e5e5e5 !important;
}
.hero-header h2 {
color: #b3b3b3 !important;
}
.hero-header span {
background: #2a2a2a !important;
color: #e5e5e5 !important;
border: 1px solid #404040 !important;
}
}
.dark .hero-header h1,
.gradio-container.dark .hero-header h1,
html.dark .hero-header h1,
body.dark .hero-header h1 {
color: #e5e5e5 !important;
}
.dark .hero-header h2,
.gradio-container.dark .hero-header h2,
html.dark .hero-header h2,
body.dark .hero-header h2 {
color: #b3b3b3 !important;
}
.dark .hero-header span,
.gradio-container.dark .hero-header span,
html.dark .hero-header span,
body.dark .hero-header span {
background: #2a2a2a !important;
color: #e5e5e5 !important;
border: 1px solid #404040 !important;
}
/* Paper Buttons */
.generate-btn {
background: #e67e5a !important;
border: 2px solid #d96b47 !important;
color: #fefcfa !important;
font-weight: 600 !important;
font-size: 1.3rem !important;
padding: 1.2rem 2.5rem !important;
border-radius: 12px !important;
transition: all 0.3s ease !important;
font-family: 'Georgia', serif !important;
letter-spacing: 0.5px !important;
}
/* View Prompt Button */
.view-prompt-btn {
background: #f4e6e1 !important;
border: 1px solid #e8a491 !important;
color: #5a3a2a !important;
font-weight: 500 !important;
font-size: 0.9rem !important;
padding: 0.5rem 1rem !important;
border-radius: 8px !important;
transition: all 0.2s ease !important;
font-family: 'Georgia', serif !important;
margin-bottom: 0.5rem !important;
}
.view-prompt-btn:hover {
background: #f0c5b8 !important;
}
/* Modal Overlay - simple approach */
.modal-overlay {
position: fixed !important;
top: 0 !important;
left: 0 !important;
width: 100vw !important;
height: 100vh !important;
background: rgba(0, 0, 0, 0.5) !important;
z-index: 9999 !important;
justify-content: center !important;
align-items: center !important;
padding: 2rem !important;
box-sizing: border-box !important;
}
/* Show as flex only when visible class is present */
.modal-overlay.visible {
display: flex !important;
}
/* Modal Content - with dark mode support */
.modal-content {
background: #fefcfa !important;
border: 2px solid #f0c5b8 !important;
border-radius: 16px !important;
max-width: 90vw !important;
max-height: 80vh !important;
width: 800px !important;
padding: 2rem !important;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5) !important;
overflow: hidden !important;
flex-direction: column !important;
color: #2d3748 !important;
}
/* Modal Header */
.modal-header {
justify-content: space-between !important;
align-items: center !important;
margin-bottom: 1rem !important;
padding-bottom: 1rem !important;
border-bottom: 1px solid #f0c5b8 !important;
}
.modal-header h3 {
color: #2d3748 !important;
margin: 0 !important;
}
/* Modal Close Button */
.modal-close-btn {
background: #f4e6e1 !important;
border: 1px solid #e8a491 !important;
color: #5a3a2a !important;
font-weight: 700 !important;
font-size: 1.2rem !important;
padding: 0.4rem 0.6rem !important;
border-radius: 6px !important;
min-width: 2rem !important;
height: 2rem !important;
align-items: center !important;
justify-content: center !important;
}
.modal-close-btn:hover {
background: #f0c5b8 !important;
}
/* Prompt Container */
.prompt-container {
background: #fcf3f0 !important;
border: 1px solid #f0c5b8 !important;
border-radius: 8px !important;
max-height: 400px !important;
overflow-y: auto !important;
flex: 1 !important;
}
/* Dark mode overrides for system dark mode */
@media (prefers-color-scheme: dark) {
.modal-content {
background: #1a1a1a !important;
border: 2px solid #404040 !important;
color: #e5e5e5 !important;
}
.modal-header {
border-bottom: 1px solid #404040 !important;
}
.modal-header h3 {
color: #e5e5e5 !important;
}
.modal-close-btn {
background: #404040 !important;
border: 1px solid #666 !important;
color: #e5e5e5 !important;
}
.modal-close-btn:hover {
background: #555 !important;
}
.prompt-container {
background: #2a2a2a !important;
border: 1px solid #404040 !important;
}
}
/* Gradio dark mode overrides */
.dark .modal-content,
.gradio-container.dark .modal-content,
html.dark .modal-content,
body.dark .modal-content {
background: #1a1a1a !important;
border: 2px solid #404040 !important;
color: #e5e5e5 !important;
}
.dark .modal-header,
.gradio-container.dark .modal-header,
html.dark .modal-header,
body.dark .modal-header {
border-bottom: 1px solid #404040 !important;
}
.dark .modal-header h3,
.gradio-container.dark .modal-header h3,
html.dark .modal-header h3,
body.dark .modal-header h3 {
color: #e5e5e5 !important;
}
.dark .modal-close-btn,
.gradio-container.dark .modal-close-btn,
html.dark .modal-close-btn,
body.dark .modal-close-btn {
background: #404040 !important;
border: 1px solid #666 !important;
color: #e5e5e5 !important;
}
.dark .modal-close-btn:hover,
.gradio-container.dark .modal-close-btn:hover,
html.dark .modal-close-btn:hover,
body.dark .modal-close-btn:hover {
background: #555 !important;
}
.dark .prompt-container,
.gradio-container.dark .prompt-container,
html.dark .prompt-container,
body.dark .prompt-container {
background: #2a2a2a !important;
border: 1px solid #404040 !important;
}
.generate-btn:hover {
background: #d96b47 !important;
transform: translateY(-1px) !important;
}
.generate-btn:active {
transform: translateY(0px) !important;
}
/* Paper Section Headers */
.section-header {
background: #f9f0ec !important;
border: 1px solid #f0c5b8 !important;
border-radius: 8px !important;
padding: 0.7rem !important;
margin-bottom: 0.5rem !important;
}
/* Dark mode section headers */
@media (prefers-color-scheme: dark) {
.section-header {
background: #333333 !important;
border: 1px solid #555 !important;
}
}
.dark .section-header,
.gradio-container.dark .section-header,
html.dark .section-header,
body.dark .section-header {
background: #333333 !important;
border: 1px solid #555 !important;
}
/* Dark mode section header text */
@media (prefers-color-scheme: dark) {
.section-header p {
color: #f0f0f0 !important;
}
}
.dark .section-header p,
.gradio-container.dark .section-header p,
html.dark .section-header p,
body.dark .section-header p {
color: #f0f0f0 !important;
}
/* Paper Inputs */
input[type="text"],
input[type="number"],
textarea {
background: #fefcfa !important;
border: 2px solid #f4e6e1 !important;
border-radius: 8px !important;
padding: 0.8rem 1.2rem !important;
font-weight: 500 !important;
color: #5a3a2a !important;
font-family: 'Georgia', serif !important;
font-size: 1rem !important;
}
input[type="text"]:focus,
input[type="number"]:focus,
textarea:focus {
background: #fefcfa !important;
border-color: #e8a491 !important;
outline: none !important;
}
/* Dark mode inputs */
@media (prefers-color-scheme: dark) {
input[type="text"],
input[type="number"],
textarea {
background: #2a2a2a !important;
border: 2px solid #404040 !important;
color: #e5e5e5 !important;
}
input[type="text"]:focus,
input[type="number"]:focus,
textarea:focus {
background: #2a2a2a !important;
border-color: #666 !important;
}
}
.dark input[type="text"],
.dark input[type="number"],
.dark textarea,
.gradio-container.dark input[type="text"],
.gradio-container.dark input[type="number"],
.gradio-container.dark textarea,
html.dark input[type="text"],
html.dark input[type="number"],
html.dark textarea,
body.dark input[type="text"],
body.dark input[type="number"],
body.dark textarea {
background: #2a2a2a !important;
border: 2px solid #404040 !important;
color: #e5e5e5 !important;
}
.dark input[type="text"]:focus,
.dark input[type="number"]:focus,
.dark textarea:focus,
.gradio-container.dark input[type="text"]:focus,
.gradio-container.dark input[type="number"]:focus,
.gradio-container.dark textarea:focus,
html.dark input[type="text"]:focus,
html.dark input[type="number"]:focus,
html.dark textarea:focus,
body.dark input[type="text"]:focus,
body.dark input[type="number"]:focus,
body.dark textarea:focus {
background: #2a2a2a !important;
border-color: #666 !important;
}
/* CRITICAL: Reset all problematic CSS for dropdowns */
label:has(+ [data-testid="dropdown"]),
div:has([data-testid="dropdown"]),
[data-testid="dropdown"],
[data-testid="dropdown"] *,
.gradio-dropdown,
.gradio-dropdown * {
position: static !important;
transform: none !important;
backdrop-filter: none !important;
filter: none !important;
}
/* AGGRESSIVE FIX: Override ALL possible transparency sources */
* {
--dropdown-bg: #ffffff !important;
--dropdown-opacity: 1 !important;
}
/* Target every possible dropdown element with maximum specificity */
.gradio-container [data-testid="dropdown"] div[role="listbox"],
.gradio-container .gradio-dropdown .dropdown-content,
.gradio-container .dropdown-menu,
.gradio-container div[role="listbox"],
.gradio-container .svelte-1gfkn6j,
body [data-testid="dropdown"] div[role="listbox"],
body .dropdown-menu,
body div[role="listbox"],
html [data-testid="dropdown"] div[role="listbox"] {
background: #ffffff !important;
background-color: #ffffff !important;
opacity: 1 !important;
position: absolute !important;
z-index: 99999 !important;
border: 2px solid #d1d5db !important;
border-radius: 8px !important;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.25) !important;
max-height: 200px !important;
overflow-y: auto !important;
backdrop-filter: none !important;
filter: none !important;
background-image: none !important;
background-blend-mode: normal !important;
/* Force solid with CSS variables */
background: var(--dropdown-bg, #ffffff) !important;
opacity: var(--dropdown-opacity, 1) !important;
}
/* Aggressive option styling */
.gradio-container [data-testid="dropdown"] div[role="listbox"] > *,
.gradio-container .dropdown-menu > *,
.gradio-container div[role="listbox"] > *,
body [data-testid="dropdown"] div[role="listbox"] > *,
body .dropdown-menu > *,
body div[role="listbox"] > * {
background: #ffffff !important;
background-color: #ffffff !important;
padding: 0.75rem 1rem !important;
color: #1f2937 !important;
cursor: pointer !important;
opacity: 1 !important;
border: none !important;
margin: 0 !important;
display: block !important;
width: 100% !important;
text-align: left !important;
}
/* Ensure dropdown menus appear correctly with SOLID background */
[data-testid="dropdown"] div[role="listbox"],
.gradio-dropdown .dropdown-content,
.dropdown-menu,
div[role="listbox"],
.svelte-1gfkn6j,
.gradio-container div[role="listbox"] {
position: absolute !important;
z-index: 9999 !important;
background: #ffffff !important;
background-color: #ffffff !important;
opacity: 1 !important;
border: 1px solid #d1d5db !important;
border-radius: 8px !important;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15) !important;
max-height: 200px !important;
overflow-y: auto !important;
backdrop-filter: none !important;
/* Force solid background */
background-image: none !important;
background-blend-mode: normal !important;
}
/* Dropdown option styling - SOLID background for each option */
[data-testid="dropdown"] div[role="listbox"] > *,
.dropdown-menu > *,
div[role="listbox"] > *,
.svelte-1gfkn6j > * {
background: #ffffff !important;
background-color: #ffffff !important;
padding: 0.5rem 0.75rem !important;
color: #374151 !important;
cursor: pointer !important;
transition: background-color 0.2s ease !important;
opacity: 1 !important;
}
/* Dropdown option hover effect */
[data-testid="dropdown"] div[role="listbox"] > *:hover,
.dropdown-menu > *:hover,
div[role="listbox"] > *:hover {
background: #f3f4f6 !important;
color: #1f2937 !important;
}
/* Dropdown option selected state */
[data-testid="dropdown"] div[role="listbox"] > *[aria-selected="true"],
.dropdown-menu > *.selected,
div[role="listbox"] > *[aria-selected="true"] {
background: #e0e7ff !important;
color: #3730a3 !important;
}
/* Paper Code Areas */
.code-container {
background: #f9f0ec !important;
border: 1px solid #f0c5b8 !important;
border-radius: 8px !important;
overflow: hidden !important;
}
/* Dark mode code container */
@media (prefers-color-scheme: dark) {
.code-container {
background: #1a1a1a !important;
border: 1px solid #404040 !important;
}
}
.dark .code-container,
.gradio-container.dark .code-container,
html.dark .code-container,
body.dark .code-container {
background: #1a1a1a !important;
border: 1px solid #404040 !important;
}
/* Force text selection on ALL code elements */
.code-container,
.code-container *,
.code-container textarea,
.code-container input,
.code-container .cm-editor,
.code-container .cm-content,
.code-container .cm-line {
user-select: text !important;
-webkit-user-select: text !important;
-moz-user-select: text !important;
-ms-user-select: text !important;
cursor: text !important;
}
/* Make selection visible */
.code-container .cm-editor ::selection {
background: #3b82f6 !important;
color: white !important;
}
.code-container .cm-editor ::-moz-selection {
background: #3b82f6 !important;
color: white !important;
}
/* Make cursor visible */
.code-container .cm-cursor {
border-color: #3b82f6 !important;
border-width: 2px !important;
opacity: 1 !important;
visibility: visible !important;
}
/* Ensure selection works in CodeMirror */
.code-container .cm-selectionBackground {
background: #3b82f6 !important;
opacity: 0.3 !important;
}
/* Make sure focused state is visible */
.code-container .cm-focused {
outline: 2px solid #3b82f6 !important;
outline-offset: 2px !important;
}
/* Code textbox styling */
.code-container textarea {
background: #ffffff !important;
border: none !important;
border-radius: 4px !important;
font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Roboto Mono', 'Fira Code', monospace !important;
font-size: 14px !important;
line-height: 1.5 !important;
padding: 1.5rem !important;
color: #2d3748 !important;
font-weight: 500 !important;
resize: vertical !important;
white-space: pre !important;
overflow-wrap: normal !important;
word-break: normal !important;
}
/* Dark mode code textbox styling */
@media (prefers-color-scheme: dark) {
.code-container textarea {
background: #2a2a2a !important;
color: #e5e5e5 !important;
}
}
.dark .code-container textarea,
.gradio-container.dark .code-container textarea,
html.dark .code-container textarea,
body.dark .code-container textarea {
background: #2a2a2a !important;
color: #e5e5e5 !important;
}
/* Enable soft wrapping for code content */
.code-container .cm-content {
white-space: pre-wrap !important;
padding: 1.5rem !important;
color: #5a3a2a !important;
font-size: 14px !important;
font-weight: 500 !important;
}
.code-container .cm-focused {
outline: none !important;
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.3) !important;
}
.code-container .cm-line {
padding-left: 0.5rem !important;
white-space: pre-wrap !important;
word-wrap: break-word !important;
overflow-wrap: break-word !important;
}
/* Force wrapping ONLY - NO SCROLLING */
.code-container .cm-editor {
white-space: pre-wrap !important;
overflow-x: hidden !important;
}
.code-container .cm-scroller {
overflow-x: hidden !important;
width: 100% !important;
}
.code-container .cm-editor .cm-content {
white-space: pre-wrap !important;
word-break: break-all !important;
overflow-wrap: anywhere !important;
width: 100% !important;
max-width: 100% !important;
}
.code-container .cm-editor .cm-line {
white-space: pre-wrap !important;
word-break: break-all !important;
overflow-wrap: anywhere !important;
width: 100% !important;
max-width: 100% !important;
box-sizing: border-box !important;
}
/* Force the entire code container to have no horizontal overflow */
.code-container,
.code-container * {
overflow-x: hidden !important;
max-width: 100% !important;
}
/* Moderate syntax highlighting for Python */
.code-container .cm-keyword { color: #7c3aed !important; }
.code-container .cm-string { color: #059669 !important; }
.code-container .cm-comment { color: #6b7280 !important; font-style: italic !important; }
.code-container .cm-number { color: #dc2626 !important; }
.code-container .cm-variable { color: #1e40af !important; }
.code-container .cm-function { color: #7c2d12 !important; }
.code-container .cm-operator { color: #374151 !important; }
/* Paper Code header */
.code-container label {
background: #f5e6e0 !important;
color: #5a3a2a !important;
padding: 0.75rem 1.25rem !important;
border-radius: 8px 8px 0 0 !important;
font-weight: 700 !important;
font-size: 1.1rem !important;
margin: 0 !important;
border: none !important;
border-bottom: 1px solid #f0c5b8 !important;
font-family: 'Georgia', serif !important;
}
/* Dark mode code header */
@media (prefers-color-scheme: dark) {
.code-container label {
background: #404040 !important;
color: #e5e5e5 !important;
border-bottom: 1px solid #666 !important;
}
}
.dark .code-container label,
.gradio-container.dark .code-container label,
html.dark .code-container label,
body.dark .code-container label {
background: #404040 !important;
color: #e5e5e5 !important;
border-bottom: 1px solid #666 !important;
}
/* Custom scrollbar for code area */
.code-container .cm-scroller::-webkit-scrollbar {
width: 6px !important;
height: 6px !important;
}
.code-container .cm-scroller::-webkit-scrollbar-track {
background: rgba(243, 244, 246, 0.8) !important;
border-radius: 3px !important;
}
.code-container .cm-scroller::-webkit-scrollbar-thumb {
background: rgba(156, 163, 175, 0.8) !important;
border-radius: 3px !important;
}
.code-container .cm-scroller::-webkit-scrollbar-thumb:hover {
background: rgba(107, 114, 128, 0.9) !important;
}
/* Paper Line numbers */
.code-container .cm-lineNumbers {
background: #f5e6e0 !important;
color: #b8847a !important;
border-right: 1px solid #f0c5b8 !important;
padding-right: 0.5rem !important;
}
.code-container .cm-lineNumbers .cm-gutterElement {
color: #b8847a !important;
font-weight: 400 !important;
}
/* Paper Memory Cards */
.memory-card {
background: #fcf3f0 !important;
border: 1px solid #f4e6e1 !important;
border-radius: 12px !important;
padding: 0.7rem !important;
border-left: 4px solid #e8a491 !important;
}
/* Dark mode memory cards */
@media (prefers-color-scheme: dark) {
.memory-card {
background: #2a2a2a !important;
border: 1px solid #404040 !important;
border-left: 4px solid #666 !important;
}
}
.dark .memory-card,
.gradio-container.dark .memory-card,
html.dark .memory-card,
body.dark .memory-card {
background: #2a2a2a !important;
border: 1px solid #404040 !important;
border-left: 4px solid #666 !important;
}
/* Paper Labels */
label {
font-weight: 600 !important;
color: #5a3a2a !important;
font-size: 1.1rem !important;
font-family: 'Georgia', serif !important;
}
/* Dark mode labels */
@media (prefers-color-scheme: dark) {
label {
color: #e5e5e5 !important;
}
}
.dark label,
.gradio-container.dark label,
html.dark label,
body.dark label {
color: #e5e5e5 !important;
}
/* Memory Analysis Spacing */
.memory-analysis-spacing {
padding-top: 1rem !important;
border-top: 1px solid rgba(226, 232, 240, 0.6) !important;
}
/* FINAL OVERRIDE: Nuclear option for dropdown transparency */
[role="listbox"] {
background: white !important;
opacity: 1 !important;
}
[role="listbox"] > * {
background: white !important;
opacity: 1 !important;
}
/* Gradio-specific nuclear option */
.gradio-app [role="listbox"],
.gradio-app [role="listbox"] > * {
background: #ffffff !important;
background-color: #ffffff !important;
opacity: 1 !important;
}
/* Last resort: override all possible transparent backgrounds */
div[style*="background"] {
background: unset !important;
}
[role="listbox"][style*="background"] {
background: #ffffff !important;
}
/* Dark mode dropdown styling - enhanced for dropdown items */
@media (prefers-color-scheme: dark) {
[data-testid="dropdown"] div[role="listbox"],
.dropdown-menu,
div[role="listbox"],
div[id*="dropdown-options"],
div[aria-labelledby*="dropdown"] {
background: #2a2a2a !important;
background-color: #2a2a2a !important;
border: 2px solid #404040 !important;
}
[data-testid="dropdown"] div[role="listbox"] > *,
.dropdown-menu > *,
div[role="listbox"] > *,
div[id*="dropdown-options"] > *,
div[aria-labelledby*="dropdown"] > *,
div[role="option"],
[role="option"] {
background: #2a2a2a !important;
background-color: #2a2a2a !important;
color: #e5e5e5 !important;
}
[data-testid="dropdown"] div[role="listbox"] > *:hover,
.dropdown-menu > *:hover,
div[role="listbox"] > *:hover,
div[id*="dropdown-options"] > *:hover,
div[aria-labelledby*="dropdown"] > *:hover,
div[role="option"]:hover,
[role="option"]:hover {
background: #404040 !important;
color: #ffffff !important;
}
[role="listbox"][style*="background"] {
background: #2a2a2a !important;
}
}
/* Gradio dark mode dropdown styling - enhanced for dropdown items */
.dark [data-testid="dropdown"] div[role="listbox"],
.dark .dropdown-menu,
.dark div[role="listbox"],
.dark div[id*="dropdown-options"],
.dark div[aria-labelledby*="dropdown"],
.gradio-container.dark [data-testid="dropdown"] div[role="listbox"],
.gradio-container.dark .dropdown-menu,
.gradio-container.dark div[role="listbox"],
.gradio-container.dark div[id*="dropdown-options"],
.gradio-container.dark div[aria-labelledby*="dropdown"],
html.dark [data-testid="dropdown"] div[role="listbox"],
html.dark .dropdown-menu,
html.dark div[role="listbox"],
html.dark div[id*="dropdown-options"],
html.dark div[aria-labelledby*="dropdown"],
body.dark [data-testid="dropdown"] div[role="listbox"],
body.dark .dropdown-menu,
body.dark div[role="listbox"],
body.dark div[id*="dropdown-options"],
body.dark div[aria-labelledby*="dropdown"] {
background: #2a2a2a !important;
background-color: #2a2a2a !important;
border: 2px solid #404040 !important;
}
.dark [data-testid="dropdown"] div[role="listbox"] > *,
.dark .dropdown-menu > *,
.dark div[role="listbox"] > *,
.dark div[id*="dropdown-options"] > *,
.dark div[aria-labelledby*="dropdown"] > *,
.dark div[role="option"],
.dark [role="option"],
.gradio-container.dark [data-testid="dropdown"] div[role="listbox"] > *,
.gradio-container.dark .dropdown-menu > *,
.gradio-container.dark div[role="listbox"] > *,
.gradio-container.dark div[id*="dropdown-options"] > *,
.gradio-container.dark div[aria-labelledby*="dropdown"] > *,
.gradio-container.dark div[role="option"],
.gradio-container.dark [role="option"],
html.dark [data-testid="dropdown"] div[role="listbox"] > *,
html.dark .dropdown-menu > *,
html.dark div[role="listbox"] > *,
html.dark div[id*="dropdown-options"] > *,
html.dark div[aria-labelledby*="dropdown"] > *,
html.dark div[role="option"],
html.dark [role="option"],
body.dark [data-testid="dropdown"] div[role="listbox"] > *,
body.dark .dropdown-menu > *,
body.dark div[role="listbox"] > *,
body.dark div[id*="dropdown-options"] > *,
body.dark div[aria-labelledby*="dropdown"] > *,
body.dark div[role="option"],
body.dark [role="option"] {
background: #2a2a2a !important;
background-color: #2a2a2a !important;
color: #e5e5e5 !important;
}
.dark [data-testid="dropdown"] div[role="listbox"] > *:hover,
.dark .dropdown-menu > *:hover,
.dark div[role="listbox"] > *:hover,
.dark div[id*="dropdown-options"] > *:hover,
.dark div[aria-labelledby*="dropdown"] > *:hover,
.dark div[role="option"]:hover,
.dark [role="option"]:hover,
.gradio-container.dark [data-testid="dropdown"] div[role="listbox"] > *:hover,
.gradio-container.dark .dropdown-menu > *:hover,
.gradio-container.dark div[role="listbox"] > *:hover,
.gradio-container.dark div[id*="dropdown-options"] > *:hover,
.gradio-container.dark div[aria-labelledby*="dropdown"] > *:hover,
.gradio-container.dark div[role="option"]:hover,
.gradio-container.dark [role="option"]:hover,
html.dark [data-testid="dropdown"] div[role="listbox"] > *:hover,
html.dark .dropdown-menu > *:hover,
html.dark div[role="listbox"] > *:hover,
html.dark div[id*="dropdown-options"] > *:hover,
html.dark div[aria-labelledby*="dropdown"] > *:hover,
html.dark div[role="option"]:hover,
html.dark [role="option"]:hover,
body.dark [data-testid="dropdown"] div[role="listbox"] > *:hover,
body.dark .dropdown-menu > *:hover,
body.dark div[role="listbox"] > *:hover,
body.dark div[id*="dropdown-options"] > *:hover,
body.dark div[aria-labelledby*="dropdown"] > *:hover,
body.dark div[role="option"]:hover,
body.dark [role="option"]:hover {
background: #404040 !important;
color: #ffffff !important;
}
.dark [role="listbox"][style*="background"],
.gradio-container.dark [role="listbox"][style*="background"],
html.dark [role="listbox"][style*="background"],
body.dark [role="listbox"][style*="background"] {
background: #2a2a2a !important;
}
/* Dark mode dropdown trigger/button styling */
@media (prefers-color-scheme: dark) {
[data-testid="dropdown"],
.gradio-dropdown,
select {
background: #2a2a2a !important;
border: 2px solid #404040 !important;
color: #e5e5e5 !important;
}
[data-testid="dropdown"] button,
.gradio-dropdown button,
[data-testid="dropdown"] > div,
.gradio-dropdown > div {
background: #2a2a2a !important;
color: #e5e5e5 !important;
border: 2px solid #404040 !important;
}
}
.dark [data-testid="dropdown"],
.dark .gradio-dropdown,
.dark select,
.gradio-container.dark [data-testid="dropdown"],
.gradio-container.dark .gradio-dropdown,
.gradio-container.dark select,
html.dark [data-testid="dropdown"],
html.dark .gradio-dropdown,
html.dark select,
body.dark [data-testid="dropdown"],
body.dark .gradio-dropdown,
body.dark select {
background: #2a2a2a !important;
border: 2px solid #404040 !important;
color: #e5e5e5 !important;
}
.dark [data-testid="dropdown"] button,
.dark .gradio-dropdown button,
.dark [data-testid="dropdown"] > div,
.dark .gradio-dropdown > div,
.gradio-container.dark [data-testid="dropdown"] button,
.gradio-container.dark .gradio-dropdown button,
.gradio-container.dark [data-testid="dropdown"] > div,
.gradio-container.dark .gradio-dropdown > div,
html.dark [data-testid="dropdown"] button,
html.dark .gradio-dropdown button,
html.dark [data-testid="dropdown"] > div,
html.dark .gradio-dropdown > div,
body.dark [data-testid="dropdown"] button,
body.dark .gradio-dropdown button,
body.dark [data-testid="dropdown"] > div,
body.dark .gradio-dropdown > div {
background: #2a2a2a !important;
color: #e5e5e5 !important;
border: 2px solid #404040 !important;
}
/* Specific dropdown structure targeting - system dark mode */
@media (prefers-color-scheme: dark) {
.wrap.svelte-1hfxrpf,
.wrap-inner.svelte-1hfxrpf,
.secondary-wrap.svelte-1hfxrpf,
input[role="listbox"].svelte-1hfxrpf {
background: #2a2a2a !important;
color: #e5e5e5 !important;
border-color: #404040 !important;
}
}
/* Specific dropdown structure targeting - Gradio dark mode */
.dark .wrap.svelte-1hfxrpf,
.dark .wrap-inner.svelte-1hfxrpf,
.dark .secondary-wrap.svelte-1hfxrpf,
.dark input[role="listbox"].svelte-1hfxrpf,
.gradio-container.dark .wrap.svelte-1hfxrpf,
.gradio-container.dark .wrap-inner.svelte-1hfxrpf,
.gradio-container.dark .secondary-wrap.svelte-1hfxrpf,
.gradio-container.dark input[role="listbox"].svelte-1hfxrpf,
html.dark .wrap.svelte-1hfxrpf,
html.dark .wrap-inner.svelte-1hfxrpf,
html.dark .secondary-wrap.svelte-1hfxrpf,
html.dark input[role="listbox"].svelte-1hfxrpf,
body.dark .wrap.svelte-1hfxrpf,
body.dark .wrap-inner.svelte-1hfxrpf,
body.dark .secondary-wrap.svelte-1hfxrpf,
body.dark input[role="listbox"].svelte-1hfxrpf {
background: #2a2a2a !important;
color: #e5e5e5 !important;
border-color: #404040 !important;
}
</script>
<script>
// Fix CodeMirror text selection and accordion titles after page loads
document.addEventListener('DOMContentLoaded', function() {
setTimeout(function() {
// Find all CodeMirror editors
const editors = document.querySelectorAll('.code-container .cm-editor');
editors.forEach(editor => {
// Enable text selection on CodeMirror
editor.style.userSelect = 'text';
editor.style.webkitUserSelect = 'text';
editor.style.mozUserSelect = 'text';
// Find the content area
const content = editor.querySelector('.cm-content');
if (content) {
content.style.userSelect = 'text';
content.style.webkitUserSelect = 'text';
content.style.mozUserSelect = 'text';
}
// Add event listeners to ensure selection works
editor.addEventListener('mousedown', function(e) {
e.stopPropagation();
});
});
// Fix accordion title font sizes - focus on first span only
const accordionButtons = document.querySelectorAll('button.label-wrap, button[class*="label-wrap"]');
accordionButtons.forEach(button => {
// Find and style the text span (first span child) - this is the most important part
const textSpan = button.querySelector('span:first-child');
if (textSpan) {
textSpan.style.fontSize = '1.5rem';
textSpan.style.fontWeight = '900';
textSpan.style.fontFamily = 'Georgia, serif';
textSpan.style.color = '#2d1810';
textSpan.style.textShadow = '0 1px 2px rgba(0,0,0,0.2)';
textSpan.style.letterSpacing = '0.5px';
textSpan.style.lineHeight = '1.3';
// Force override any existing styles
textSpan.style.setProperty('font-size', '1.5rem', 'important');
textSpan.style.setProperty('font-weight', '900', 'important');
textSpan.style.setProperty('font-family', 'Georgia, serif', 'important');
}
});
}, 1000);
});
</script>
<style>
/* Specific accordion title styling - target the first span */
button.label-wrap span:first-child,
button.label-wrap.svelte-1w6vloh span:first-child,
.label-wrap span:first-child,
button.label-wrap > span:first-child,
button[class*="label-wrap"] span:first-child {
font-size: 1.5rem !important;
font-weight: 900 !important;
color: #2d1810 !important;
font-family: 'Georgia', serif !important;
line-height: 1.3 !important;
text-shadow: 0 1px 2px rgba(0,0,0,0.2) !important;
letter-spacing: 0.5px !important;
text-transform: none !important;
}
/* Dark mode accordion title styling - system dark mode */
@media (prefers-color-scheme: dark) {
button.label-wrap span:first-child,
button.label-wrap.svelte-1w6vloh span:first-child,
.label-wrap span:first-child,
button.label-wrap > span:first-child,
button[class*="label-wrap"] span:first-child {
color: #e5e5e5 !important;
text-shadow: 0 1px 2px rgba(255,255,255,0.1) !important;
}
button.label-wrap {
background: #2a2a2a !important;
border: 1px solid #404040 !important;
}
button.label-wrap:hover {
background: #353535 !important;
}
}
/* Dark mode accordion title styling - Gradio dark mode */
.dark button.label-wrap span:first-child,
.gradio-container.dark button.label-wrap span:first-child,
html.dark button.label-wrap span:first-child,
body.dark button.label-wrap span:first-child,
.dark button.label-wrap.svelte-1w6vloh span:first-child,
.gradio-container.dark button.label-wrap.svelte-1w6vloh span:first-child,
html.dark button.label-wrap.svelte-1w6vloh span:first-child,
body.dark button.label-wrap.svelte-1w6vloh span:first-child,
.dark .label-wrap span:first-child,
.gradio-container.dark .label-wrap span:first-child,
html.dark .label-wrap span:first-child,
body.dark .label-wrap span:first-child {
color: #e5e5e5 !important;
text-shadow: 0 1px 2px rgba(255,255,255,0.1) !important;
}
.dark button.label-wrap,
.gradio-container.dark button.label-wrap,
html.dark button.label-wrap,
body.dark button.label-wrap {
background: #2a2a2a !important;
border: 1px solid #404040 !important;
}
.dark button.label-wrap:hover,
.gradio-container.dark button.label-wrap:hover,
html.dark button.label-wrap:hover,
body.dark button.label-wrap:hover {
background: #353535 !important;
}
/* Additional targeting for accordion buttons */
button.label-wrap {
background: #f9f0ec !important;
padding: 0.7rem 1rem !important;
border-radius: 8px !important;
border: 1px solid #f0c5b8 !important;
}
button.label-wrap:hover {
background: #f5e6e0 !important;
}
/* Accordion title styling - focus on readability */
.gradio-accordion .label-wrap,
.gradio-accordion summary,
.gradio-accordion details summary,
details summary,
details > summary,
[data-testid="accordion"] summary,
[data-testid="accordion"] .label-wrap {
font-weight: 900 !important;
color: #2d1810 !important;
font-family: 'Georgia', serif !important;
line-height: 1.3 !important;
text-shadow: 0 1px 2px rgba(0,0,0,0.1) !important;
padding: 1rem 1.5rem !important;
background: #f5f1e8 !important;
border-radius: 8px !important;
letter-spacing: 0.5px !important;
text-transform: none !important;
}
/* Even more specific accordion targeting */
.gradio-container details summary,
.gradio-container .gradio-accordion summary,
.gradio-container [role="button"] {
font-weight: 900 !important;
color: #2d1810 !important;
font-family: 'Georgia', serif !important;
text-shadow: 0 1px 2px rgba(0,0,0,0.1) !important;
background: #f5f1e8 !important;
padding: 1rem 1.5rem !important;
border-radius: 8px !important;
letter-spacing: 0.5px !important;
}
/* Accordion hover states for better interaction */
.gradio-accordion summary:hover,
details summary:hover {
background: #f0ead7 !important;
color: #1a0f08 !important;
}
/* Accordion container styling */
.gradio-accordion,
details {
background: #fefdfb !important;
border: 2px solid #f0ede6 !important;
border-radius: 12px !important;
margin-bottom: 1rem !important;
}
.gradio-accordion[open],
details[open] {
border-color: #e8dcc6 !important;
background: #fefdfb !important;
}
/* Mobile Responsive Styles */
@media (max-width: 768px) {
body, html, main {
padding: 5px !important;
margin: 0 !important;
}
.gradio-container {
padding: 5px !important;
margin: 0 !important;
}
/* Set left/right margins to 1px for mobile */
.gradio-container > * {
margin-left: 1px !important;
margin-right: 1px !important;
}
/* Adjust hero header for mobile */
.hero-header {
padding: 1rem 0.5rem !important;
margin-bottom: 1rem !important;
}
.hero-header h1 {
font-size: 1.8rem !important;
}
.hero-header h2 {
font-size: 1rem !important;
}
.hero-header p {
font-size: 0.9rem !important;
}
/* Mobile-friendly glass panels */
.glass-panel {
margin: 0.5rem 0 !important;
padding: 1rem !important;
border-radius: 12px !important;
}
/* Responsive button sizing */
.primary-button {
padding: 0.8rem 2rem !important;
font-size: 1rem !important;
}
/* Mobile code container */
.code-container {
margin: 0 !important;
border-radius: 8px !important;
}
/* Stack columns on mobile */
.gradio-row {
flex-direction: column !important;
}
}
/* Small mobile devices */
@media (max-width: 480px) {
.main-container {
margin: 0 1px !important;
padding: 0.5rem !important;
}
.hero-header {
padding: 1.5rem 0.5rem !important;
}
.hero-header h1 {
font-size: 2rem !important;
}
.hero-header h2 {
font-size: 1.2rem !important;
}
.glass-panel {
padding: 0.8rem !important;
margin: 0.25rem 0 !important;
}
}
"""
) as interface:
with gr.Column(elem_classes="main-container"):
# Ultra Premium Header
gr.HTML("""
<div class="hero-header" style="text-align: center; padding: 1rem;">
<h1 style="color: #5a3a2a; font-size: 2rem; margin: 0 0 0.2rem 0; font-weight: 600; font-family: 'Georgia', serif;">
✨ Auto Diffusers Config
</h1>
<h2 style="color: #8b5a4f; font-size: 1rem; margin: 0 0 0.5rem 0; font-weight: 500; font-style: italic; font-family: 'Georgia', serif;">
Hardware-Optimized Code Generator
</h2>
<span style="display: inline-block; background: #fefcfa; padding: 0.3rem 0.8rem; border-radius: 8px; color: #5a3a2a; font-size: 0.85rem; border: 1px solid #f4e6e1; font-family: 'Georgia', serif; font-style: italic; font-weight: 500;">
🤖 Powered by Google Gemini 2.5
</span>
</div>
""")
# Main Content Area
# Hardware Selection Section
with gr.Group(elem_classes="glass-card"):
with gr.Accordion("⚙️ Hardware Specifications", open=False) as hardware_accordion:
gr.HTML("""
<div class="section-header" style="text-align: center;">
<p style="margin: 0; color: #6a443a; font-size: 1.1rem; font-weight: 600; font-family: 'Georgia', serif;">
Configure your system hardware for optimal code generation
</p>
</div>
""")
# Platform, VRAM, and RAM in a single row
with gr.Row():
platform = gr.Dropdown(
choices=["Linux", "Darwin", "Windows"],
label="🖥️ Platform",
value="Linux",
info="Your operating system"
)
vram_gb = gr.Number(
label="🎯 VRAM (GB)",
value=8,
minimum=0,
maximum=200,
info="GPU memory available"
)
ram_gb = gr.Number(
label="💻 System RAM (GB)",
value=16,
minimum=4,
maximum=256,
info="Total system memory"
)
# GPU configuration on separate lines
gpu_vendor = gr.Dropdown(
choices=[
"Custom (Manual Input)",
"NVIDIA Consumer (GeForce RTX)",
"NVIDIA Professional (RTX A-Series)",
"NVIDIA Data Center",
"Apple Silicon",
"AMD",
"Intel",
"CPU Only"
],
label="🎮 GPU Vendor/Category",
value="Custom (Manual Input)",
info="Select your GPU category"
)
gpu_series = gr.Dropdown(
choices=[],
label="📊 GPU Series",
visible=False,
interactive=True,
info="Choose your GPU series"
)
gpu_model = gr.Dropdown(
choices=[],
label="🔧 GPU Model",
visible=False,
interactive=True,
info="Select your specific GPU model"
)
gpu_name = gr.Textbox(
label="Selected GPU",
visible=False
)
# Model Configuration Section
with gr.Group(elem_classes="glass-card"):
with gr.Accordion("🤖 Model Configuration", open=True) as model_accordion:
gr.HTML("""
<div class="section-header" style="text-align: center;">
<p style="margin: 0; color: #6a443a; font-size: 1.1rem; font-weight: 600; font-family: 'Georgia', serif;">
Configure the AI model and generation parameters
</p>
</div>
""")
# Model Name - Full width on its own row
model_name = gr.Textbox(
label="🏷️ Model Name",
value="black-forest-labs/FLUX.1-schnell",
placeholder="e.g., black-forest-labs/FLUX.1-schnell",
info="HuggingFace model identifier"
)
# Other parameters in 4-column layout
with gr.Row():
width = gr.Number(
label="📏 Width (px)",
value=1360,
minimum=256,
maximum=2048,
step=64,
info="Image width"
)
height = gr.Number(
label="📐 Height (px)",
value=768,
minimum=256,
maximum=2048,
step=64,
info="Image height"
)
dtype_selection = gr.Dropdown(
choices=["Auto", "float32", "float16", "bfloat16"],
label="⚡ dtype",
value="Auto",
info="Precision mode"
)
inference_steps = gr.Number(
label="🔄 Inf. Steps",
value=4,
minimum=1,
maximum=50,
info="Denoising steps"
)
memory_analysis_output = gr.Markdown(
value="✨ Select a model and configure your hardware to see memory requirements and optimization recommendations.",
elem_classes="memory-analysis-spacing"
)
# Generate Button
with gr.Row():
with gr.Column():
generate_btn = gr.Button(
"✨ Generate Optimized Code",
variant="primary",
size="lg",
elem_classes="generate-btn"
)
# Generated Code Section
with gr.Group(elem_classes="ultra-glass"):
# Hidden button to show prompt (only visible after generation)
with gr.Row():
view_prompt_btn = gr.Button(
"🔍 View Actual Prompt Sent to Gemini",
variant="secondary",
size="sm",
visible=False,
elem_classes="view-prompt-btn"
)
# Code Output - back to Code component with better selection
code_output = gr.Code(
label="Generated Code",
language="python",
lines=20,
interactive=True,
show_label=True,
elem_classes="code-container",
show_line_numbers=False,
wrap_lines=True,
value="# Your optimized diffusion code will appear here after generation\n# Click 'Generate Optimized Code' to create hardware-specific Python code\n\nprint('Ready to generate AI art with optimized performance!')"
)
# Modal with CSS styling
with gr.Group(visible=False, elem_classes="modal-overlay") as prompt_modal:
with gr.Column(elem_classes="modal-content"):
with gr.Row(elem_classes="modal-header"):
gr.Markdown("### 📋 Actual Prompt Sent to Gemini API")
close_modal_btn = gr.Button("×", variant="secondary", size="sm", elem_classes="modal-close-btn")
prompt_display = gr.Code(
label="Full Prompt",
language="markdown",
lines=20,
interactive=False,
show_label=False,
elem_classes="prompt-container",
value=""
)
def on_gpu_vendor_change(vendor):
"""Handle GPU vendor selection and update series dropdown."""
if vendor == "Custom (Manual Input)":
return (gr.update(visible=False, choices=[]),
gr.update(visible=False, choices=[]),
"", gr.update())
elif vendor == "CPU Only":
return (gr.update(visible=False, choices=[]),
gr.update(visible=False, choices=[]),
"", 0)
elif vendor == "NVIDIA Consumer (GeForce RTX)":
return (gr.update(visible=True, choices=["RTX 50 Series", "RTX 40 Series", "RTX 30 Series"]),
gr.update(visible=False, choices=[]),
"", gr.update())
elif vendor == "NVIDIA Professional (RTX A-Series)":
return (gr.update(visible=True, choices=["RTX A6000 Series", "RTX A5000 Series", "RTX A4000 Series"]),
gr.update(visible=False, choices=[]),
"", gr.update())
elif vendor == "NVIDIA Data Center":
return (gr.update(visible=True, choices=["Blackwell (B-Series)", "Hopper (H-Series)", "Ada Lovelace (L-Series)", "Ampere (A-Series)", "Volta/Tesla"]),
gr.update(visible=False, choices=[]),
"", gr.update())
elif vendor == "Apple Silicon":
return (gr.update(visible=True, choices=["M4 Series", "M3 Series", "M2 Series", "M1 Series"]),
gr.update(visible=False, choices=[]),
"", gr.update())
elif vendor == "AMD":
return (gr.update(visible=True, choices=["Radeon RX 7000", "Radeon RX 6000", "Instinct MI Series"]),
gr.update(visible=False, choices=[]),
"", gr.update())
elif vendor == "Intel":
return (gr.update(visible=True, choices=["Arc A-Series"]),
gr.update(visible=False, choices=[]),
"", gr.update())
else:
return (gr.update(visible=False, choices=[]),
gr.update(visible=False, choices=[]),
"", gr.update())
def on_gpu_series_change(vendor, series):
"""Handle GPU series selection and update model dropdown."""
models = []
if vendor == "NVIDIA Consumer (GeForce RTX)":
if series == "RTX 50 Series":
models = ["RTX 5090 (32GB)", "RTX 5080 (16GB)", "RTX 5070 Ti (16GB)", "RTX 5070 (12GB)", "RTX 5060 Ti (16GB)", "RTX 5060 (12GB)"]
elif series == "RTX 40 Series":
models = ["RTX 4090 (24GB)", "RTX 4080 Super (16GB)", "RTX 4070 Ti Super (16GB)", "RTX 4070 Super (12GB)", "RTX 4070 (12GB)", "RTX 4060 Ti (16GB)", "RTX 4060 Ti (8GB)", "RTX 4060 (8GB)"]
elif series == "RTX 30 Series":
models = ["RTX 3090 Ti (24GB)", "RTX 3090 (24GB)", "RTX 3080 Ti (12GB)", "RTX 3080 (12GB)", "RTX 3080 (10GB)", "RTX 3070 Ti (8GB)", "RTX 3070 (8GB)", "RTX 3060 Ti (8GB)", "RTX 3060 (12GB)"]
elif vendor == "NVIDIA Professional (RTX A-Series)":
if series == "RTX A6000 Series":
models = ["RTX A6000 (48GB)", "RTX A6000 Ada (48GB)", "RTX 6000 Ada (48GB)"]
elif series == "RTX A5000 Series":
models = ["RTX A5000 (24GB)", "RTX A5500 (24GB)", "RTX 5000 Ada (32GB)"]
elif series == "RTX A4000 Series":
models = ["RTX A4000 (16GB)", "RTX A4500 (20GB)", "RTX 4000 Ada (20GB)", "RTX 4000 SFF Ada (20GB)"]
elif vendor == "NVIDIA Data Center":
if series == "Blackwell (B-Series)":
models = ["B200 (192GB)", "B100 (192GB)", "GB200 NVL72 (192GB per GPU)"]
elif series == "Hopper (H-Series)":
models = ["H200 (141GB)", "H100 SXM (80GB)", "H100 PCIe (80GB)"]
elif series == "Ada Lovelace (L-Series)":
models = ["L40S (48GB)", "L40 (48GB)", "L4 (24GB)"]
elif series == "Ampere (A-Series)":
models = ["A100 SXM (80GB)", "A100 PCIe (80GB)", "A100 PCIe (40GB)", "A40 (48GB)", "A30 (24GB)", "A16 (16GB)", "A10 (24GB)"]
elif series == "Volta/Tesla":
models = ["V100 SXM2 (32GB)", "V100 PCIe (16GB)", "P100 (16GB)"]
elif vendor == "Apple Silicon":
if series == "M4 Series":
models = ["M4 Max (128GB Unified)", "M4 Pro (64GB Unified)", "M4 (32GB Unified)"]
elif series == "M3 Series":
models = ["M3 Ultra (192GB Unified)", "M3 Max (128GB Unified)", "M3 Pro (36GB Unified)", "M3 (24GB Unified)"]
elif series == "M2 Series":
models = ["M2 Ultra (192GB Unified)", "M2 Max (96GB Unified)", "M2 Pro (32GB Unified)", "M2 (24GB Unified)"]
elif series == "M1 Series":
models = ["M1 Ultra (128GB Unified)", "M1 Max (64GB Unified)", "M1 Pro (32GB Unified)", "M1 (16GB Unified)"]
elif vendor == "AMD":
if series == "Radeon RX 7000":
models = ["RX 7900 XTX (24GB)", "RX 7900 XT (20GB)"]
elif series == "Radeon RX 6000":
models = ["RX 6900 XT (16GB)"]
elif series == "Instinct MI Series":
models = ["Instinct MI300X (192GB)", "Instinct MI250X (128GB)", "Instinct MI100 (32GB)"]
elif vendor == "Intel":
if series == "Arc A-Series":
models = ["Arc A770 (16GB)", "Arc A750 (8GB)"]
return gr.update(visible=True, choices=models)
def on_gpu_model_change(model):
"""Handle GPU model selection and auto-fill values."""
if not model or model == "":
return "", gr.update()
# Extract GPU name and VRAM from model
if "(" in model and "GB" in model:
gpu_name_part = model.split(" (")[0]
vram_part = model.split("(")[1].split("GB")[0]
try:
vram_value = int(vram_part)
except:
vram_value = 8
return gpu_name_part, vram_value
else:
return model, gr.update()
def get_final_gpu_name(vendor, series, model):
"""Get the final GPU name based on vendor selection."""
if vendor == "Custom (Manual Input)":
return "Custom GPU"
elif vendor == "CPU Only":
return ""
elif model and "(" in model and "GB" in model:
return model.split(" (")[0]
elif model:
return model
else:
return vendor if vendor != "Custom (Manual Input)" else "Custom GPU"
def update_hardware_accordion_title(platform, gpu_vendor, gpu_model, vram_gb, ram_gb):
"""Update hardware accordion title with current configuration."""
final_gpu = get_final_gpu_name(gpu_vendor, "", gpu_model)
if not final_gpu:
final_gpu = gpu_vendor if gpu_vendor != "Custom (Manual Input)" else "Custom GPU"
# Extract GPU name and VRAM for cleaner display
gpu_display = final_gpu
if gpu_model and "(" in gpu_model and "GB" in gpu_model:
# Extract clean GPU name with VRAM from model selection
gpu_display = gpu_model
elif final_gpu and vram_gb:
gpu_display = f"{final_gpu} ({vram_gb}GB)"
return f"⚙️ Hardware: {platform} | {gpu_display} | {ram_gb}GB RAM"
def update_model_accordion_title(model_name, dtype_selection, width, height, inference_steps, memory_analysis_text=""):
"""Update model accordion title with current configuration including memory info."""
model_short = model_name.split("/")[-1] if "/" in model_name else model_name
dtype_short = dtype_selection
# Extract memory info for title
memory_info = ""
if memory_analysis_text and not memory_analysis_text.startswith("Select a model") and "Error" not in memory_analysis_text:
lines = memory_analysis_text.split('\n')
for line in lines:
if "Memory Requirements:" in line or "estimated" in line.lower():
if "GB" in line:
import re
gb_match = re.search(r'(\d+\.?\d*)\s*GB', line)
if gb_match:
memory_info = f" | {gb_match.group(1)}GB req"
break
return f"🤖 Model: {model_short} | {dtype_short} | {width}×{height} | {inference_steps} steps{memory_info}"
# State to track last processed model name
last_processed_model = gr.State(value="")
def update_memory_analysis(model_name, vram_gb, last_model):
"""Update memory analysis based on selections."""
if not model_name or not model_name.strip():
return "Select a model to see memory requirements.", ""
# Check if model name has actually changed
if model_name == last_model and last_model != "":
# Return current analysis without API call (model hasn't changed)
return gr.update(), last_model
if not vram_gb or vram_gb <= 0:
return f"**Model:** {model_name}\n\nConfigure your GPU to see memory analysis.", model_name
try:
memory_info, recommendations, formatted_info = app.analyze_model_memory(model_name, vram_gb)
# Check if there was an error in the memory analysis
if isinstance(memory_info, dict) and 'error' in memory_info:
# Extract just the core error message
error_msg = str(memory_info['error'])
if "Error analyzing model memory:" in error_msg:
error_msg = error_msg.replace("Error analyzing model memory:", "").strip()
return f"**Note:** {error_msg} (API error)", model_name
return formatted_info, model_name
except Exception as e:
# Simple error message for any other exceptions
error_msg = str(e)
return f"**Note:** {error_msg} (API error)", model_name
# Connect GPU dropdown change handlers with memory analysis updates
gpu_vendor.change(
on_gpu_vendor_change,
inputs=[gpu_vendor],
outputs=[gpu_series, gpu_model, gpu_name, vram_gb]
).then(
update_memory_analysis,
inputs=[model_name, vram_gb, last_processed_model],
outputs=[memory_analysis_output, last_processed_model]
)
gpu_series.change(
on_gpu_series_change,
inputs=[gpu_vendor, gpu_series],
outputs=[gpu_model]
)
gpu_model.change(
on_gpu_model_change,
inputs=[gpu_model],
outputs=[gpu_name, vram_gb]
).then(
update_memory_analysis,
inputs=[model_name, vram_gb, last_processed_model],
outputs=[memory_analysis_output, last_processed_model]
)
# Update memory analysis when model name is submitted (Enter) or loses focus, or VRAM changes
model_name.submit(
update_memory_analysis,
inputs=[model_name, vram_gb, last_processed_model],
outputs=[memory_analysis_output, last_processed_model]
)
model_name.blur(
update_memory_analysis,
inputs=[model_name, vram_gb, last_processed_model],
outputs=[memory_analysis_output, last_processed_model]
)
vram_gb.change(
update_memory_analysis,
inputs=[model_name, vram_gb, last_processed_model],
outputs=[memory_analysis_output, last_processed_model]
)
# Load initial memory analysis on startup
interface.load(
update_memory_analysis,
inputs=[model_name, vram_gb, last_processed_model],
outputs=[memory_analysis_output, last_processed_model]
)
# Create wrapper functions that return gr.update for accordion labels
def update_hardware_accordion(platform, gpu_vendor, gpu_model, vram_gb, ram_gb):
title = update_hardware_accordion_title(platform, gpu_vendor, gpu_model, vram_gb, ram_gb)
return gr.update(label=title)
def update_model_accordion(model_name, dtype_selection, width, height, inference_steps, memory_analysis_text=""):
title = update_model_accordion_title(model_name, dtype_selection, width, height, inference_steps, memory_analysis_text)
return gr.update(label=title)
# Load initial accordion titles on startup
interface.load(
update_hardware_accordion,
inputs=[platform, gpu_vendor, gpu_model, vram_gb, ram_gb],
outputs=hardware_accordion
)
interface.load(
update_model_accordion,
inputs=[model_name, dtype_selection, width, height, inference_steps, memory_analysis_output],
outputs=model_accordion
)
# Accordion title update event handlers
# Hardware accordion title updates
for component in [platform, gpu_vendor, gpu_model, vram_gb, ram_gb]:
component.change(
update_hardware_accordion,
inputs=[platform, gpu_vendor, gpu_model, vram_gb, ram_gb],
outputs=hardware_accordion
)
# Model accordion title updates (including memory analysis)
model_name.submit(
update_model_accordion,
inputs=[model_name, dtype_selection, width, height, inference_steps, memory_analysis_output],
outputs=model_accordion
)
model_name.blur(
update_model_accordion,
inputs=[model_name, dtype_selection, width, height, inference_steps, memory_analysis_output],
outputs=model_accordion
)
for component in [dtype_selection, width, height, inference_steps]:
component.change(
update_model_accordion,
inputs=[model_name, dtype_selection, width, height, inference_steps, memory_analysis_output],
outputs=model_accordion
)
# Update model accordion when memory analysis changes
memory_analysis_output.change(
update_model_accordion,
inputs=[model_name, dtype_selection, width, height, inference_steps, memory_analysis_output],
outputs=model_accordion
)
def create_code_summary(generated_code, model_name, final_gpu_name, vram_gb):
"""Create a concise summary of the generated code."""
if generated_code.startswith("Error"):
return "❌ **Code Generation Failed** - See error details in the code output below."
# Analyze the generated code to extract key optimizations
optimizations = []
if "torch.float16" in generated_code or "fp16" in generated_code.lower():
optimizations.append("FP16 precision")
if "torch.bfloat16" in generated_code or "bf16" in generated_code.lower():
optimizations.append("BF16 precision")
if "enable_model_cpu_offload" in generated_code:
optimizations.append("CPU offloading")
if "enable_sequential_cpu_offload" in generated_code:
optimizations.append("Sequential CPU offload")
if "low_cpu_mem_usage=True" in generated_code:
optimizations.append("Low CPU memory usage")
if "torch.compile" in generated_code:
optimizations.append("Torch compile")
if "attention_slicing" in generated_code:
optimizations.append("Attention slicing")
if "vae_slicing" in generated_code:
optimizations.append("VAE slicing")
device = "CUDA" if "cuda" in generated_code else "MPS" if "mps" in generated_code else "CPU"
summary = f"""
### ✅ Code Generated Successfully
**Model:** `{model_name}`
**Hardware:** {final_gpu_name} ({vram_gb}GB) - {device}
**Optimizations:** {', '.join(optimizations) if optimizations else 'Standard configuration'}
**Key Features:**
- Memory-optimized pipeline loading
- Hardware-specific device configuration
- Performance tuning for your GPU
- Ready-to-run diffusion code
"""
return summary
def strip_comments(code):
"""Remove all comments from the code for collapsed view."""
if not code:
return code
lines = code.split('\n')
filtered_lines = []
for line in lines:
stripped = line.strip()
# Skip comment-only lines and empty lines
if stripped.startswith('#') or stripped == '':
continue
# For lines with inline comments, keep only the code part
if '#' in line and not stripped.startswith('#'):
code_part = line.split('#')[0].rstrip()
if code_part.strip(): # Only add if there's actual code
filtered_lines.append(code_part)
else:
filtered_lines.append(line)
return '\n'.join(filtered_lines)
def generate_with_combined_gpu_name(gpu_vendor, gpu_series, gpu_model, vram_gb, ram_gb, platform, model_name, dtype_selection, width, height, inference_steps):
"""Generate code with the correct GPU name from multi-level selection, including memory analysis."""
final_gpu_name = get_final_gpu_name(gpu_vendor, gpu_series, gpu_model)
# Constant prompt text
prompt_text = "A cat holding a sign that says hello world"
# STEP 1: Perform memory analysis BEFORE code generation
memory_analysis_data = None
memory_header = ""
try:
if model_name and vram_gb and vram_gb > 0:
memory_info, recommendations, _ = app.analyze_model_memory(model_name, vram_gb)
# Package memory analysis for Gemini API
memory_analysis_data = {
'memory_info': memory_info,
'recommendations': recommendations
}
# Create header for the generated code
def get_optimization_strategy(recommendations):
"""Generate optimization strategy text based on recommendations."""
strategies = []
if recommendations.get('cpu_offload'):
strategies.append("CPU offloading")
if recommendations.get('sequential_offload'):
strategies.append("Sequential CPU offload")
if recommendations.get('attention_slicing'):
strategies.append("Attention slicing")
if recommendations.get('vae_slicing'):
strategies.append("VAE slicing")
precision = recommendations.get('recommended_precision', 'float16')
if precision:
strategies.append(f"{precision} precision")
if not strategies:
# No special optimizations needed
if recommendations.get('recommendations') and any('Full model can fit' in rec for rec in recommendations.get('recommendations', [])):
return "Full VRAM utilization with optimal performance"
else:
return "Standard optimization"
return ", ".join(strategies)
optimization_strategy = get_optimization_strategy(recommendations)
memory_header = f"""# Memory Analysis for {model_name}:
# GPU: {final_gpu_name if final_gpu_name else 'Not specified'} ({vram_gb}GB VRAM)
# Model Memory Requirements: {memory_info.get('estimated_inference_memory_fp16_gb', 'Unknown')} GB
# Recommendation: {', '.join(recommendations.get('recommendations', ['N/A']))}
# Optimization Strategy: {optimization_strategy}
"""
except Exception as e:
memory_header = f"""# Memory Analysis for {model_name}:
# GPU: {final_gpu_name if final_gpu_name else 'Not specified'} ({vram_gb}GB VRAM)
# Note: Memory analysis failed - {str(e)}
"""
# STEP 2: Get the actual prompt that will be sent to Gemini
actual_prompt = app.get_generation_prompt(
model_name, prompt_text, (int(height), int(width)), int(inference_steps),
{
'platform': platform,
'architecture': 'manual_input',
'cpu_count': 8,
'python_version': '3.11',
'cuda_available': 'nvidia' in final_gpu_name.lower() if final_gpu_name else False,
'mps_available': platform == 'Darwin' and 'apple' in final_gpu_name.lower() if final_gpu_name else False,
'torch_version': '2.0+',
'manual_input': True,
'ram_gb': int(ram_gb) if ram_gb else 16,
'user_dtype': f"torch.{dtype_selection}" if dtype_selection != "Auto" else None,
'gpu_info': [{'name': final_gpu_name, 'memory_mb': int(vram_gb) * 1024}] if final_gpu_name and vram_gb else None
},
optimization_profile="balanced"
)
# STEP 3: Generate the optimized code WITH memory analysis information
generated_code = app.generate_code_with_manual_specs(
final_gpu_name, vram_gb, ram_gb, platform,
model_name, prompt_text, dtype_selection, width, height, inference_steps,
memory_analysis_data
)
# STEP 4: Prepend memory analysis header to the generated code
final_code = memory_header + generated_code if memory_header and not generated_code.startswith("Error") else generated_code
# STEP 5: Create code summary
summary = create_code_summary(generated_code, model_name, final_gpu_name, vram_gb)
return summary, final_code, actual_prompt
# Add states for tracking code view and storing full code
code_collapsed = gr.State(value=False)
full_code_storage = gr.State(value="")
prompt_storage = gr.State(value="")
def generate_and_store_code(gpu_vendor, gpu_series, gpu_model, vram_gb, ram_gb, platform, model_name, dtype_selection, width, height, inference_steps):
"""Generate code and return code for display and full code for storage."""
summary, full_code, actual_prompt = generate_with_combined_gpu_name(
gpu_vendor, gpu_series, gpu_model, vram_gb, ram_gb, platform,
model_name, dtype_selection, width, height, inference_steps
)
# Show the view prompt button after generation and close accordions
return (full_code, full_code, False, gr.update(visible=True), actual_prompt,
gr.update(open=False), gr.update(open=False)) # display_code, stored_code, reset_collapsed_state, show_button, prompt, close_hardware_accordion, close_model_accordion
# Modal functions with CSS class control
def show_modal(prompt):
return gr.update(visible=True, elem_classes="modal-overlay visible"), prompt
def hide_modal():
print("Close modal button clicked!") # Debug
return gr.update(visible=False, elem_classes="modal-overlay"), ""
# Generate button click
generate_btn.click(
generate_and_store_code,
inputs=[
gpu_vendor, gpu_series, gpu_model, vram_gb, ram_gb, platform,
model_name, dtype_selection, width, height, inference_steps
],
outputs=[code_output, full_code_storage, code_collapsed, view_prompt_btn, prompt_storage, hardware_accordion, model_accordion]
)
# View prompt button click
view_prompt_btn.click(
show_modal,
inputs=[prompt_storage],
outputs=[prompt_modal, prompt_display]
)
# Close modal button click
close_modal_btn.click(
hide_modal,
outputs=[prompt_modal, prompt_display]
)
return interface
def main():
"""Launch the Gradio application."""
try:
interface = create_gradio_interface()
interface.launch(
server_name="0.0.0.0",
server_port=7860,
share=True,
show_error=True
)
except Exception as e:
print(f"Error launching Gradio app: {e}")
print("Make sure you have set GOOGLE_API_KEY in your .env file")
if __name__ == "__main__":
main() |