Spaces:
Runtime error
Runtime error
File size: 128,059 Bytes
e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 4b828b4 e105e80 1535508 e105e80 a4493b3 e105e80 a4493b3 e105e80 d3e6b6b e105e80 |
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 |
import asyncio
import base64
import importlib
import io
import logging
import os
from datetime import datetime
import gradio as gr
import httpx
from PIL import Image
import config
importlib.reload(config)
from config import CONFIG, get_api_headers, get_api_url
from models import (
TaskSubmission, ImageToImageSubmission, PhotoStyleSubmission,
InteriorDesignRenderingSubmission, WatermarkRemovalSubmission,
LineArtConversionSubmission, AnimeToRealSubmission, RealToAnimeSubmission,
ImageOutpaintingSubmission, FiveViewGenerationSubmission, Figure3DSubmission,
CharacterFigureCollaborationSubmission
)
from examples_config import (
TEXT_TO_IMAGE_EXAMPLES_WITH_RESULTS,
FIVE_VIEW_GENERATION_EXAMPLES_WITH_RESULTS,
FIGURE_3D_EXAMPLES_WITH_RESULTS,
CHARACTER_FIGURE_COLLABORATION_EXAMPLES_WITH_RESULTS,
IMAGE_OUTPAINTING_EXAMPLES_WITH_RESULTS,
LINE_ART_CONVERSION_EXAMPLES_WITH_RESULTS,
ANIME_TO_REAL_EXAMPLES_WITH_RESULTS,
REAL_TO_ANIME_EXAMPLES_WITH_RESULTS,
INTERIOR_DESIGN_EXAMPLES_WITH_RESULTS
)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
PHOTO_STYLE_DISPLAY_MAPPING = {
"camera_movement": "📹 Camera Movement",
"relighting": "💡 Relighting",
"camera_zoom": "🔍 Camera Zoom",
"product_photo": "📦 Professional Product Photography",
"miniature": "🏠 Tilt-Shift Miniature",
"reflection": "🪞 Reflection Addition",
"pose_change": "🎭 Pose & Viewpoint Change"
}
def preset_key_to_display_name(preset_key: str) -> str:
return PHOTO_STYLE_DISPLAY_MAPPING.get(preset_key, preset_key)
def display_name_to_preset_key(display_name: str) -> str:
for key, value in PHOTO_STYLE_DISPLAY_MAPPING.items():
if value == display_name:
return key
return display_name
PHOTO_STYLE_CHOICES = [
(preset_key_to_display_name(key), key)
for key in PHOTO_STYLE_DISPLAY_MAPPING.keys()
]
INTERIOR_DESIGN_STYLE_MAPPING = {
"japanese_wabi_sabi": "🏯 Japanese Wabi-Sabi",
"nordic_cozy": "🏔️ Nordic Cozy",
"italian_luxury": "🇮🇹 Italian Luxury",
"parisian_apartment": "🗼 Parisian Apartment"
}
def interior_style_key_to_display_name(style_key: str) -> str:
return INTERIOR_DESIGN_STYLE_MAPPING.get(style_key, style_key)
def display_name_to_interior_style_key(display_name: str) -> str:
for key, value in INTERIOR_DESIGN_STYLE_MAPPING.items():
if value == display_name:
return key
return display_name
INTERIOR_DESIGN_STYLE_CHOICES = [
(interior_style_key_to_display_name(key), key)
for key in INTERIOR_DESIGN_STYLE_MAPPING.keys()
]
# 3D Figure Style Mapping
FIGURE_3D_STYLE_MAPPING = {
"professional_lighting": "💡 Professional Lighting Scene",
"collector_shelf": "📚 Collector's Display Scene",
"desktop_display": "💻 Desktop Display Scene"
}
FIGURE_3D_STYLE_CHOICES = [
(display_name, key) for key, display_name in FIGURE_3D_STYLE_MAPPING.items()
]
# ============================================================================
# Utility Functions
# ============================================================================
def pil_to_base64(pil_image: Image.Image) -> str:
buffer = io.BytesIO()
pil_image.save(buffer, format='PNG')
image_data = buffer.getvalue()
return base64.b64encode(image_data).decode('utf-8')
def resize_image_if_needed(image: Image.Image, max_size: int = 1536, min_size: int = 512) -> Image.Image:
width, height = image.size
# Check if resize is needed
if max(width, height) <= max_size and min(width, height) >= min_size:
return image
# Calculate new dimensions
if max(width, height) > max_size:
ratio = max_size / max(width, height)
new_width = int(width * ratio)
new_height = int(height * ratio)
else:
ratio = min_size / min(width, height)
new_width = int(width * ratio)
new_height = int(height * ratio)
return image.resize((new_width, new_height), Image.Resampling.LANCZOS)
async def submit_task_with_retry(endpoint: str, payload: dict, task_name: str, max_retries: int = 60) -> dict:
"""
Submit task with intelligent retry mechanism for 429 errors
Args:
endpoint: API endpoint
payload: Request payload
task_name: Task name for user-friendly messages
max_retries: Maximum retry attempts (default: 60 for 5 minutes)
Returns:
API response dict
Raises:
Exception: User-friendly error messages only
"""
import asyncio
base_delay = 5.0 # Start with 5 seconds
max_delay = 30.0 # Cap at 30 seconds
for attempt in range(max_retries + 1):
try:
async with httpx.AsyncClient(timeout=CONFIG.API_TIMEOUT) as client:
response = await client.post(
get_api_url(endpoint),
json=payload,
headers=get_api_headers()
)
if response.status_code == 429:
if attempt < max_retries:
delay = min(base_delay * (1.5 ** attempt), max_delay)
logger.info(f"System busy, retrying {task_name} in {delay:.1f}s (attempt {attempt + 1}/{max_retries + 1})")
await asyncio.sleep(delay)
continue
else:
raise Exception("The system is currently busy, please try again later")
elif response.status_code >= 500:
logger.error(f"Server error {response.status_code} for {task_name}")
raise Exception("Service temporarily unavailable, please try again later")
elif response.status_code >= 400:
logger.error(f"Client error {response.status_code} for {task_name}")
raise Exception("Invalid request parameters, please check your input")
# Success
response.raise_for_status()
return response.json()
except httpx.TimeoutException:
logger.error(f"Timeout error for {task_name}")
raise Exception("Network timeout, please check your connection")
except httpx.ConnectError:
logger.error(f"Connection error for {task_name}")
raise Exception("Unable to connect to the server, please try again later")
except Exception as e:
if any(msg in str(e) for msg in ["System is currently busy", "Service temporarily unavailable", "Invalid request parameters", "Network connection timeout", "Unable to connect to server"]):
# Re-raise user-friendly messages (English messages for detection)
raise
else:
# Log technical error but show user-friendly message
logger.error(f"Unexpected error submitting {task_name}: {e}")
raise Exception("An error occurred while submitting the task, please try again later")
# Should never reach here
raise Exception("The system is currently busy, please try again later")
async def submit_text_to_image_task(prompt: str, resolution: str) -> dict:
"""Submit text-to-image task to backend API with intelligent retry"""
# Parse resolution
width, height = 1024, 1024 # Default
if "1024x1024" in resolution:
width, height = 1024, 1024
elif "1152x896" in resolution:
width, height = 1152, 896
elif "896x1152" in resolution:
width, height = 896, 1152
elif "1344x768" in resolution:
width, height = 1344, 768
elif "768x1344" in resolution:
width, height = 768, 1344
elif "1216x832" in resolution:
width, height = 1216, 832
elif "1536x640" in resolution:
width, height = 1536, 640
# Create submission
submission = TaskSubmission(
prompt=prompt,
width=width,
height=height
)
return await submit_task_with_retry(
endpoint="api/v1/tasks/",
payload=submission.to_api_payload(),
task_name="Text to Image"
)
async def get_task_status(task_id: str) -> dict:
"""Get task status from backend API"""
try:
async with httpx.AsyncClient(timeout=30) as client:
response = await client.get(
get_api_url(f"api/v1/tasks/{task_id}"),
headers=get_api_headers()
)
response.raise_for_status()
return response.json()
except Exception as e:
logger.error(f"Error getting task status: {e}")
raise
async def get_task_result(task_id: str) -> dict:
"""Get task result from backend API"""
try:
async with httpx.AsyncClient(timeout=30) as client:
response = await client.get(
get_api_url(f"api/v1/tasks/{task_id}/result"),
headers=get_api_headers()
)
response.raise_for_status()
return response.json()
except Exception as e:
logger.error(f"Error getting task result: {e}")
raise
async def load_image_from_result(result_data: dict) -> Image.Image:
"""Load PIL Image from task result data via URL download only"""
if not result_data:
raise ValueError("No result data received")
result_url = result_data.get("result_url")
logger.info(f"🔗 Result URL: {result_url}")
if not result_url:
logger.error(f"❌ No result_url in response. Available fields: {list(result_data.keys())}")
raise ValueError("No result_url found in result")
if not result_url.startswith("http"):
raise ValueError(f"Invalid URL format: {result_url}")
try:
logger.info(f"📥 Downloading image from: {result_url}")
async with httpx.AsyncClient(timeout=60.0) as client:
response = await client.get(result_url)
logger.info(f"📊 HTTP response status: {response.status_code}")
response.raise_for_status()
# Check content length
content_length = len(response.content)
logger.info(f"📦 Content size: {content_length} bytes")
if content_length < 1024: # Less than 1KB is suspicious
raise ValueError("Downloaded content too small to be a valid image")
return Image.open(io.BytesIO(response.content))
except Exception as e:
logger.error(f"Error downloading image from {result_url}: {e}")
raise
def create_placeholder_image(prompt: str, resolution: str) -> Image.Image:
"""Create a placeholder image for examples"""
try:
# Parse resolution to get dimensions
if "1024x1024" in resolution:
width, height = 1024, 1024
elif "1280x1024" in resolution:
width, height = 1280, 1024
else:
width, height = 1024, 1024
# Create a simple placeholder image
img = Image.new('RGB', (width, height), color='#f5f5f5')
return img
except Exception as e:
logger.error(f"Error creating placeholder image: {e}")
return Image.new('RGB', (1024, 1024), color='#f5f5f5')
def create_placeholder_image_inline(prompt: str, resolution: str) -> Image.Image:
"""Create a placeholder image for examples"""
try:
# Parse resolution to get dimensions
if "1024x1024" in resolution:
width, height = 1024, 1024
elif "1152x896" in resolution:
width, height = 1152, 896
elif "896x1152" in resolution:
width, height = 896, 1152
else:
width, height = 1024, 1024
# Create a simple placeholder image
img = Image.new('RGB', (width, height), color='lightgray')
return img
except Exception:
# Fallback to default size
return Image.new('RGB', (1024, 1024), color='lightgray')
def load_example_result(prompt: str, resolution: str, result_path: str = None):
"""Load example result image for text-to-image"""
try:
# Find matching example in TEXT_TO_IMAGE_EXAMPLES_WITH_RESULTS
for example_prompt, example_resolution, example_path in TEXT_TO_IMAGE_EXAMPLES_WITH_RESULTS:
if example_prompt == prompt and example_resolution == resolution:
if os.path.exists(example_path):
logger.info(f"Loading example result: {example_path}")
return Image.open(example_path)
else:
logger.warning(f"Example image not found: {example_path}")
return create_placeholder_image_inline(prompt, resolution)
# If no matching example found, create placeholder
logger.warning(f"No matching example found for: {prompt[:50]}...")
return create_placeholder_image_inline(prompt, resolution)
except Exception as e:
logger.error(f"Error loading example result: {e}")
return create_placeholder_image_inline(prompt, resolution)
def load_line_art_example_result(input_image_path, result_path = None):
"""Load line art conversion example images"""
try:
input_image = None
if isinstance(input_image_path, Image.Image):
input_image = input_image_path
logger.info(f"Using PIL.Image object for line art input (cache mode): {input_image.size}")
elif isinstance(input_image_path, str):
if os.path.exists(input_image_path):
logger.info(f"Loading line art input image: {input_image_path}")
input_image = Image.open(input_image_path)
else:
logger.warning(f"Line art input image not found: {input_image_path}")
input_image = create_placeholder_image_inline("Input Image", "1024x1024")
else:
logger.warning(f"Unexpected input_image_path type: {type(input_image_path)}")
input_image = create_placeholder_image_inline("Input Image", "1024x1024")
result_image = None
if isinstance(result_path, Image.Image):
result_image = result_path
logger.info(f"Using PIL.Image object for line art result (cache mode): {result_image.size}")
return (input_image, result_image)
from examples_config import LINE_ART_CONVERSION_EXAMPLES_WITH_RESULTS
if isinstance(input_image_path, str):
search_path = input_image_path
for example_input, example_path in LINE_ART_CONVERSION_EXAMPLES_WITH_RESULTS:
if example_input == search_path:
if os.path.exists(example_path):
logger.info(f"Loading line art example result: {example_path}")
result_image = Image.open(example_path)
return (input_image, result_image)
else:
image_size = input_image.size
logger.info(f"Cache mode: identifying example by image size: {image_size}")
size_to_result = {
(474, 845): "examples/results/line_art_example1.jpg",
(720, 1104): "examples/results/line_art_example2.jpg",
(736, 1308): "examples/results/line_art_example3.jpg",
}
result_path = size_to_result.get(image_size)
if result_path and os.path.exists(result_path):
logger.info(f"Loading line art result by size mapping: {result_path}")
result_image = Image.open(result_path)
return (input_image, result_image)
# If no matching example is found, create a placeholder
logger.warning(f"No matching line art example found")
result_image = create_placeholder_image_inline("Line Art Result", "1024x1024")
return (input_image, result_image)
except Exception as e:
logger.error(f"Error loading line art example: {e}")
input_placeholder = create_placeholder_image_inline("Input Image", "1024x1024")
result_placeholder = create_placeholder_image_inline("Line Art Result", "1024x1024")
return (input_placeholder, result_placeholder)
def load_anime_to_real_example_result(input_image_path, result_path=None):
"""
Load example for Anime to Real: input image and pre-generated result image
Simplified version using fixed paths (since only one example exists)
"""
try:
logger.info(f"=== ANIME FUNCTION CALLED ===")
logger.info(f"Args: {input_image_path}, {result_path}")
# 简化版本:直接使用固定路径
input_path = "examples/anime_input/example1.jpg"
result_path_fixed = "examples/results/anime_to_real_example1.jpg"
logger.info(f"Loading fixed paths: {input_path}, {result_path_fixed}")
# Load input image
if os.path.exists(input_path):
input_image = Image.open(input_path)
logger.info(f"Input loaded: {input_image.size}")
else:
logger.error(f"Input not found: {input_path}")
input_image = create_placeholder_image_inline("Input Error", "512x512")
# Load result image
if os.path.exists(result_path_fixed):
result_image = Image.open(result_path_fixed)
logger.info(f"Result loaded: {result_image.size}")
else:
logger.error(f"Result not found: {result_path_fixed}")
result_image = create_placeholder_image_inline("Result Error", "512x512")
logger.info(f"=== RETURNING: {input_image.size}, {result_image.size} ===")
return (input_image, result_image)
except Exception as e:
logger.error(f"Error loading anime to real example: {e}", exc_info=True)
input_placeholder = create_placeholder_image_inline("Anime Input", "1024x1024")
result_placeholder = create_placeholder_image_inline("Real Person Result", "1024x1024")
logger.info(f"=== Returning with error placeholders ===")
return (input_placeholder, result_placeholder)
def load_real_to_anime_example_result(input_image_path, result_path=None):
"""Load example for Real to Anime conversion"""
try:
input_image = None
if isinstance(input_image_path, Image.Image):
input_image = input_image_path
logger.info(f"Using PIL.Image object for real to anime input (cache mode): {input_image.size}")
elif isinstance(input_image_path, str):
if os.path.exists(input_image_path):
logger.info(f"Loading real to anime input image: {input_image_path}")
input_image = Image.open(input_image_path)
else:
logger.warning(f"Real to anime input image not found: {input_image_path}")
input_image = create_placeholder_image_inline("Input Image", "1024x1024")
else:
logger.warning(f"Unexpected input_image_path type: {type(input_image_path)}")
input_image = create_placeholder_image_inline("Input Image", "1024x1024")
result_image = None
if isinstance(result_path, Image.Image):
result_image = result_path
logger.info(f"Using PIL.Image object for real to anime result (cache mode): {result_image.size}")
return (input_image, result_image)
from examples_config import REAL_TO_ANIME_EXAMPLES_WITH_RESULTS
if isinstance(input_image_path, str):
search_path = input_image_path
for example_input, example_result in REAL_TO_ANIME_EXAMPLES_WITH_RESULTS:
if example_input == search_path:
if os.path.exists(example_result):
logger.info(f"Loading real to anime example result: {example_result}")
result_image = Image.open(example_result)
return (input_image, result_image)
else:
image_size = input_image.size
logger.info(f"Cache mode: identifying real to anime example by image size: {image_size}")
size_to_result = {
(736, 1104): "examples/results/real_to_anime_example1.jpg",
(736, 946): "examples/results/real_to_anime_example2.jpg",
(1206, 796): "examples/results/real_to_anime_example3.jpg",
}
result_path_mapped = size_to_result.get(image_size)
if result_path_mapped and os.path.exists(result_path_mapped):
logger.info(f"Loading real to anime result by size mapping: {result_path_mapped}")
result_image = Image.open(result_path_mapped)
return (input_image, result_image)
# If no matching example is found, create a placeholder
logger.warning(f"No matching real to anime example found")
result_image = create_placeholder_image_inline("Anime Style Result", "1024x1024")
return (input_image, result_image)
except Exception as e:
logger.error(f"Error loading real to anime example: {e}", exc_info=True)
input_placeholder = create_placeholder_image_inline("Real Photo Input", "1024x1024")
result_placeholder = create_placeholder_image_inline("Anime Style Result", "1024x1024")
return (input_placeholder, result_placeholder)
def load_dual_output_example(input_path, param1=None, param2=None):
"""Load example with both input and result images - enhanced version for different use cases"""
try:
# Handle input image
if isinstance(input_path, Image.Image):
input_image = input_path
elif isinstance(input_path, str) and os.path.exists(input_path):
input_image = Image.open(input_path)
else:
input_image = create_placeholder_image_inline("Input", "1024x1024")
# Try to find result image from various examples configs
result_image = None
if isinstance(input_path, str):
# Check different examples configs to find matching result
from examples_config import (
IMAGE_OUTPAINTING_EXAMPLES_WITH_RESULTS,
INTERIOR_DESIGN_EXAMPLES_WITH_RESULTS
)
# Try image outpainting examples first
for example in IMAGE_OUTPAINTING_EXAMPLES_WITH_RESULTS:
if example[0] == input_path and len(example) > 3:
result_path = example[3] # Result is at index 3
if os.path.exists(result_path):
result_image = Image.open(result_path)
logger.info(f"Found outpainting result: {result_path}")
break
# Try interior design examples if not found
if not result_image:
for example in INTERIOR_DESIGN_EXAMPLES_WITH_RESULTS:
if example[0] == input_path and len(example) > 2:
result_path = example[2] # Result is at index 2
if os.path.exists(result_path):
result_image = Image.open(result_path)
logger.info(f"Found interior design result: {result_path}")
break
if not result_image:
result_image = create_placeholder_image_inline("Result", "1024x1024")
return input_image, result_image
except Exception as e:
logger.error(f"Error loading dual output example: {e}")
placeholder = create_placeholder_image_inline("Error", "1024x1024")
return placeholder, placeholder
def load_five_view_example(input_path):
"""Load five view generation example with input and result images"""
try:
# Handle input image
if isinstance(input_path, Image.Image):
input_image = input_path
elif isinstance(input_path, str) and os.path.exists(input_path):
input_image = Image.open(input_path)
else:
input_image = create_placeholder_image_inline("Input", "1024x1024")
# Try to find result from FIVE_VIEW_GENERATION_EXAMPLES_WITH_RESULTS
from examples_config import FIVE_VIEW_GENERATION_EXAMPLES_WITH_RESULTS
result_image = None
# When Gradio caches examples, it passes PIL Image objects, not file paths
# We need to match by image size or use the first available result
if isinstance(input_path, Image.Image):
# For PIL Image inputs (cache mode), use the first available result
if len(FIVE_VIEW_GENERATION_EXAMPLES_WITH_RESULTS) > 0:
result_path_found = FIVE_VIEW_GENERATION_EXAMPLES_WITH_RESULTS[0][1]
if os.path.exists(result_path_found):
result_image = Image.open(result_path_found)
logger.info(f"Found five view result: {result_path_found}")
elif isinstance(input_path, str):
for example in FIVE_VIEW_GENERATION_EXAMPLES_WITH_RESULTS:
if example[0] == input_path and len(example) > 1:
result_path_found = example[1]
if os.path.exists(result_path_found):
result_image = Image.open(result_path_found)
logger.info(f"Found five view result: {result_path_found}")
break
if not result_image:
result_image = create_placeholder_image_inline("Five View Result", "1024x1024")
return input_image, result_image
except Exception as e:
logger.error(f"Error loading five view example: {e}")
placeholder = create_placeholder_image_inline("Error", "1024x1024")
return placeholder, placeholder
def load_figure_3d_example(input_image_path, figure_style: str, resolution: str = "square - 1024x1024 (1:1)", result_path=None):
"""
Load 3D figure generation example input image and pre-generated result image
Supports two modes:
1. Runtime mode: input_image_path is a string path, result_path is a string path
2. Cache generation mode: input_image_path is a PIL.Image object, result_path is a PIL.Image object
"""
try:
# 1. 处理输入图片 - 支持字符串路径和PIL.Image对象
input_image = None
if isinstance(input_image_path, Image.Image):
# Cache mode: directly use PIL.Image object
input_image = input_image_path
logger.info(f"Using PIL.Image object for input (cache mode): {input_image.size}")
elif isinstance(input_image_path, str):
# 运行时模式:从路径加载图片
if os.path.exists(input_image_path):
logger.info(f"Loading figure 3D input image: {input_image_path}")
input_image = Image.open(input_image_path)
else:
logger.warning(f"Figure 3D input image not found: {input_image_path}")
input_image = create_placeholder_image("Input Image", "1024x1024")
else:
logger.warning(f"Unexpected input_image_path type: {type(input_image_path)}")
input_image = create_placeholder_image("Input Image", "1024x1024")
# 2. Handle result image - supports string path and PIL.Image object
result_image = None
if isinstance(result_path, Image.Image):
# Cache mode: directly use PIL.Image object
result_image = result_path
logger.info(f"Using PIL.Image object for result (cache mode): {result_image.size}")
elif isinstance(result_path, str):
# 运行时模式:从路径加载结果图片
if os.path.exists(result_path):
logger.info(f"Loading figure 3D result image: {result_path}")
result_image = Image.open(result_path)
else:
logger.warning(f"Figure 3D result image not found: {result_path}")
result_image = create_placeholder_image("Result Image", "1024x1024")
else:
# 尝试从FIGURE_3D_EXAMPLES_WITH_RESULTS中查找匹配的结果
from examples_config import FIGURE_3D_EXAMPLES_WITH_RESULTS
result_image = None
# 当Gradio缓存examples时,它传递PIL Image对象,不是文件路径
# 我们需要通过风格匹配或使用第一个可用结果
if isinstance(input_image_path, Image.Image):
# 对于PIL Image输入(缓存模式),通过风格查找结果
for example in FIGURE_3D_EXAMPLES_WITH_RESULTS:
if len(example) >= 3 and example[1] == figure_style:
result_path_found = example[2]
if os.path.exists(result_path_found):
result_image = Image.open(result_path_found)
logger.info(f"Found figure 3D result by style: {result_path_found}")
break
elif isinstance(input_image_path, str):
# 对于字符串路径输入,精确匹配
for example in FIGURE_3D_EXAMPLES_WITH_RESULTS:
if len(example) >= 3 and example[0] == input_image_path and example[1] == figure_style:
result_path_found = example[2]
if os.path.exists(result_path_found):
result_image = Image.open(result_path_found)
logger.info(f"Found figure 3D result: {result_path_found}")
break
if not result_image:
result_image = create_placeholder_image("Figure 3D Result", "1024x1024")
return input_image, figure_style, resolution, result_image
except Exception as e:
logger.error(f"Error loading figure 3D example: {e}")
placeholder = create_placeholder_image_inline("Error", "1024x1024")
return placeholder, figure_style, resolution, placeholder
def load_character_figure_collaboration_example(input_image_path, result_path=None):
"""
Load character figure collaboration example input image and pre-generated result image
Args:
input_image_path: Path to input image or PIL.Image object
result_path: Path to result image or PIL.Image object
Returns:
tuple: (input_image, result_image)
"""
try:
# 1. 处理输入图片 - 支持字符串路径和PIL.Image对象
input_image = None
if isinstance(input_image_path, Image.Image):
# Cache mode: directly use PIL.Image object
input_image = input_image_path
logger.info(f"Using PIL.Image object for input (cache mode): {input_image.size}")
elif isinstance(input_image_path, str):
# 运行时模式:从路径加载图片
if os.path.exists(input_image_path):
logger.info(f"Loading character figure collaboration input image: {input_image_path}")
input_image = Image.open(input_image_path)
else:
logger.warning(f"Character figure collaboration input image not found: {input_image_path}")
input_image = create_placeholder_image("Input Image", "1024x1024")
else:
logger.warning(f"Unexpected input_image_path type: {type(input_image_path)}")
input_image = create_placeholder_image("Input Image", "1024x1024")
# 2. Handle result image - 完全按照Line Art的模式
result_image = None
if isinstance(result_path, Image.Image):
# Cache mode: directly use PIL.Image object
result_image = result_path
logger.info(f"Using PIL.Image object for result (cache mode): {result_image.size}")
return input_image, result_image
from examples_config import CHARACTER_FIGURE_COLLABORATION_EXAMPLES_WITH_RESULTS
if isinstance(input_image_path, str):
# 运行时模式:通过输入路径查找匹配的结果
search_path = input_image_path
for example_input, example_result in CHARACTER_FIGURE_COLLABORATION_EXAMPLES_WITH_RESULTS:
if example_input == search_path:
if os.path.exists(example_result):
logger.info(f"Loading character figure collaboration example result: {example_result}")
result_image = Image.open(example_result)
return input_image, result_image
else:
# Cache mode: 通过图片尺寸匹配(完全按照Line Art的模式)
image_size = input_image.size
logger.info(f"Cache mode: identifying character figure collaboration example by image size: {image_size}")
# 创建尺寸到结果图片的映射(完全按照Line Art的模式)
size_to_result = {
(1206, 776): "examples/results/character_figure_collaboration_example1.jpg",
(1320, 1920): "examples/results/character_figure_collaboration_example2.jpg",
(1536, 2200): "examples/results/character_figure_collaboration_example3.jpg",
(1206, 1787): "examples/results/character_figure_collaboration_example4.jpg",
}
result_path = size_to_result.get(image_size)
if result_path and os.path.exists(result_path):
logger.info(f"Loading character figure collaboration result by size mapping: {result_path}")
result_image = Image.open(result_path)
return input_image, result_image
# If no matching example is found, create a placeholder
logger.warning(f"No matching character figure collaboration example found")
result_image = create_placeholder_image_inline("Character Figure Collaboration Result", "1024x1024")
return input_image, result_image
except Exception as e:
logger.error(f"Error loading character figure collaboration example: {e}")
placeholder = create_placeholder_image_inline("Error", "1024x1024")
return placeholder, placeholder
def load_outpainting_example_result(input_image_path, expand_height, expand_width, result_path=None):
"""
Load outpainting example input image, parameters, and pre-generated result image
Args:
input_image_path: input image path or PIL.Image object
expand_height: outpainting height percentage
expand_width: outpainting width percentage
result_path: result image path or PIL.Image object
Returns:
Tuple[Image.Image, float, float, Image.Image]: (输入图片, 扩展高度, 扩展宽度, 结果图片)
"""
try:
# 确保参数是正确的数字类型(防止缓存序列化问题)
expand_height = float(expand_height)
expand_width = float(expand_width)
# 处理输入图片
if isinstance(input_image_path, str) and os.path.exists(input_image_path):
input_image = Image.open(input_image_path)
logger.info(f"Loading outpainting input image: {input_image_path}")
elif isinstance(input_image_path, Image.Image):
input_image = input_image_path
logger.info(f"Using PIL.Image object for outpainting input (cache mode): {input_image.size}")
else:
input_image = create_placeholder_image_inline("Input Image", "1024x1024")
# Handle result image
if isinstance(result_path, Image.Image):
# 缓存生成模式:直接使用PIL.Image对象
result_image = result_path
logger.info(f"Using PIL.Image object for outpainting result (cache mode): {result_image.size}")
return (input_image, expand_height, expand_width, result_image)
elif isinstance(result_path, str) and os.path.exists(result_path):
result_image = Image.open(result_path)
logger.info(f"Loading outpainting result from path: {result_path}")
return (input_image, expand_height, expand_width, result_image)
# Runtime mode: find result image from IMAGE_OUTPAINTING_EXAMPLES_WITH_RESULTS
from examples_config import IMAGE_OUTPAINTING_EXAMPLES_WITH_RESULTS
if isinstance(input_image_path, str):
# 运行时模式:精确匹配路径和参数
search_path = input_image_path
for example_input, example_height, example_width, example_result in IMAGE_OUTPAINTING_EXAMPLES_WITH_RESULTS:
if example_input == search_path and abs(example_height - expand_height) < 0.01 and abs(example_width - expand_width) < 0.01:
if os.path.exists(example_result):
logger.info(f"Loading outpainting example result: {example_result}")
result_image = Image.open(example_result)
return (input_image, expand_height, expand_width, result_image)
else:
# Cache mode: identify example by image size and parameters
image_size = input_image.size
logger.info(f"Cache mode: identifying outpainting example by image size: {image_size} and params: height={expand_height}, width={expand_width}")
# 预定义的尺寸和参数映射(根据实际图片尺寸和参数)
size_param_to_result = {
((1070, 1906), 0.2, 0.3): "examples/results/outpainting_example1.jpg", # example1: 原始测试图片
((960, 1200), 0.2, 0.4): "examples/results/outpainting_example2.jpg", # example2: 日式住宅
((641, 1200), 0.5, 0.2): "examples/results/outpainting_example3.jpg", # example3: 人物自拍
}
# Find matching result
key = (image_size, expand_height, expand_width)
if key in size_param_to_result:
result_path_mapped = size_param_to_result[key]
if os.path.exists(result_path_mapped):
logger.info(f"Loading outpainting result by size and param mapping: {result_path_mapped}")
result_image = Image.open(result_path_mapped)
return (input_image, expand_height, expand_width, result_image)
# If no matching result is found, use the first available result
logger.info("Using first available outpainting result")
for example_input, example_height, example_width, example_result in IMAGE_OUTPAINTING_EXAMPLES_WITH_RESULTS:
if os.path.exists(example_result):
logger.info(f"Loading first available outpainting result: {example_result}")
result_image = Image.open(example_result)
return (input_image, expand_height, expand_width, result_image)
# As a fallback: create a placeholder
logger.info("No outpainting results found, creating placeholder")
result_image = create_placeholder_image_inline("Outpainting Result", "1536x1024")
return (input_image, expand_height, expand_width, result_image)
except Exception as e:
logger.error(f"Error loading outpainting example: {e}", exc_info=True)
input_placeholder = create_placeholder_image_inline("Input Image", "1024x1024")
result_placeholder = create_placeholder_image_inline("Outpainting Result", "1536x1024")
return (input_placeholder, 0.2, 0.2, result_placeholder)
def load_outpainting_example_for_gradio(input_image_path, expand_height, expand_width, result_path):
"""
Designed specifically for Gradio Examples to ensure input-output counts match
Args:
input_image_path: input image path or PIL.Image object
expand_height: outpainting height percentage
expand_width: outpainting width percentage
result_path: result image path (from examples config)
Returns:
Tuple[Image.Image, float, float, Image.Image]: (input image, outpaint height, outpaint width, result image)
"""
try:
# 确保参数是正确的数字类型
expand_height = float(expand_height)
expand_width = float(expand_width)
# 调用原有的加载函数,传入result_path
result = load_outpainting_example_result(input_image_path, expand_height, expand_width, result_path)
# 确保返回4个值
if len(result) == 4:
return result
else:
logger.error(f"load_outpainting_example_result returned {len(result)} values, expected 4")
# 创建默认返回值
input_placeholder = create_placeholder_image_inline("Input Image", "1024x1024")
result_placeholder = create_placeholder_image_inline("Outpainting Result", "1536x1024")
return (input_placeholder, expand_height, expand_width, result_placeholder)
except Exception as e:
logger.error(f"Error in load_outpainting_example_for_gradio: {e}", exc_info=True)
# 创建默认返回值
input_placeholder = create_placeholder_image_inline("Input Image", "1024x1024")
result_placeholder = create_placeholder_image_inline("Outpainting Result", "1536x1024")
return (input_placeholder, float(expand_height), float(expand_width), result_placeholder)
def load_interior_design_example_result(input_image_path, design_style: str, result_path=None):
"""
Load interior design rendering example input image and pre-generated result image
Supports two modes:
1. Runtime mode: input_image_path is a string path, result_path is a string path
2. Cache generation mode: input_image_path is a PIL.Image object, result_path is a PIL.Image object
"""
try:
# 1. 处理输入图片 - 支持字符串路径和PIL.Image对象
input_image = None
if isinstance(input_image_path, Image.Image):
# Cache mode: directly use PIL.Image object
input_image = input_image_path
logger.info(f"Using PIL.Image object for input (cache mode): {input_image.size}")
elif isinstance(input_image_path, str):
# 运行时模式:从路径加载图片
if os.path.exists(input_image_path):
logger.info(f"Loading interior design input image: {input_image_path}")
input_image = Image.open(input_image_path)
else:
logger.warning(f"Interior design input image not found: {input_image_path}")
input_image = create_placeholder_image("Input Image", "1024x1024")
else:
logger.warning(f"Unexpected input_image_path type: {type(input_image_path)}")
input_image = create_placeholder_image("Input Image", "1024x1024")
# 2. Handle result image - supports string path and PIL.Image object
result_image = None
if isinstance(result_path, Image.Image):
# 缓存生成模式:直接使用PIL.Image对象
result_image = result_path
logger.info(f"Using PIL.Image object for result (cache mode): {result_image.size}")
return (input_image, result_image)
# 运行时模式:从INTERIOR_DESIGN_EXAMPLES_WITH_RESULTS查找结果图片
from examples_config import INTERIOR_DESIGN_EXAMPLES_WITH_RESULTS
# 对于运行时模式,需要用字符串路径进行匹配
search_path = input_image_path if isinstance(input_image_path, str) else "examples/interior_input.png"
for example_input, example_style, example_path in INTERIOR_DESIGN_EXAMPLES_WITH_RESULTS:
if example_input == search_path and example_style == design_style:
if os.path.exists(example_path):
logger.info(f"Loading interior design example result: {example_path}")
result_image = Image.open(example_path)
return (input_image, result_image)
else:
logger.warning(f"Interior design example result not found: {example_path}")
result_image = create_placeholder_image("Interior Design Result", "1280x1024")
return (input_image, result_image)
# If no matching example is found, create a placeholder
logger.warning(f"No matching interior design example found for: {search_path}, {design_style}")
result_image = create_placeholder_image("Interior Design Result", "1280x1024")
return (input_image, result_image)
except Exception as e:
logger.error(f"Error loading interior design example: {e}")
input_placeholder = create_placeholder_image("Input Image", "1024x1024")
result_placeholder = create_placeholder_image("Interior Design Result", "1280x1024")
return (input_placeholder, result_placeholder)
# Task submission functions for all AI features
async def submit_image_to_image_task(pil_image: Image.Image) -> dict:
"""Submit image-to-image task to backend API"""
processed_image = resize_image_if_needed(pil_image, max_size=1536, min_size=512)
base64_data = pil_to_base64(processed_image)
submission = ImageToImageSubmission(image_data=base64_data)
return await submit_task_with_retry(
endpoint="api/v1/tasks/image-to-image",
payload=submission.to_api_payload(),
task_name="Image Conversion"
)
async def submit_photo_style_task(pil_image: Image.Image, style_preset: str) -> dict:
"""Submit photo style transfer task to backend API"""
processed_image = resize_image_if_needed(pil_image, max_size=1536, min_size=512)
base64_data = pil_to_base64(processed_image)
submission = PhotoStyleSubmission(image_data=base64_data, style_preset=style_preset)
return await submit_task_with_retry(
endpoint="api/v1/tasks/photo-style",
payload=submission.to_api_payload(),
task_name="Photo Style Transfer"
)
async def submit_interior_design_task(pil_image: Image.Image, design_style: str) -> dict:
"""Submit interior design rendering task to backend API"""
processed_image = resize_image_if_needed(pil_image, max_size=1536, min_size=512)
base64_data = pil_to_base64(processed_image)
submission = InteriorDesignRenderingSubmission(image_data=base64_data, design_style=design_style)
return await submit_task_with_retry(
endpoint="api/v1/tasks/interior-design-rendering",
payload=submission.to_api_payload(),
task_name="Interior Design Rendering"
)
async def submit_watermark_removal_task(pil_image: Image.Image) -> dict:
"""Submit watermark removal task to backend API"""
processed_image = resize_image_if_needed(pil_image, max_size=1536, min_size=512)
base64_data = pil_to_base64(processed_image)
submission = WatermarkRemovalSubmission(image_data=base64_data)
return await submit_task_with_retry(
endpoint="api/v1/tasks/watermark-removal",
payload=submission.to_api_payload(),
task_name="Watermark Removal"
)
async def submit_line_art_task(pil_image: Image.Image) -> dict:
"""Submit line art conversion task to backend API"""
processed_image = resize_image_if_needed(pil_image, max_size=1536, min_size=512)
base64_data = pil_to_base64(processed_image)
submission = LineArtConversionSubmission(image_data=base64_data)
return await submit_task_with_retry(
endpoint="api/v1/tasks/line-art-conversion",
payload=submission.to_api_payload(),
task_name="Line Art Conversion"
)
async def submit_image_outpainting_task(pil_image: Image.Image, expand_height: float, expand_width: float) -> dict:
"""Submit image outpainting task to backend API"""
processed_image = resize_image_if_needed(pil_image, max_size=1536, min_size=512)
base64_data = pil_to_base64(processed_image)
submission = ImageOutpaintingSubmission(
image_data=base64_data,
expand_height=expand_height,
expand_width=expand_width
)
return await submit_task_with_retry(
endpoint="api/v1/tasks/image-outpainting",
payload=submission.to_api_payload(),
task_name="Image Outpainting"
)
async def submit_anime_to_real_task(pil_image: Image.Image) -> dict:
"""Submit anime to real conversion task to backend API"""
processed_image = resize_image_if_needed(pil_image, max_size=1536, min_size=512)
base64_data = pil_to_base64(processed_image)
submission = AnimeToRealSubmission(image_data=base64_data)
return await submit_task_with_retry(
endpoint="api/v1/tasks/anime-to-real",
payload=submission.to_api_payload(),
task_name="Anime to Real"
)
async def submit_real_to_anime_task(pil_image: Image.Image) -> dict:
"""Submit real to anime conversion task to backend API"""
processed_image = resize_image_if_needed(pil_image, max_size=1536, min_size=512)
base64_data = pil_to_base64(processed_image)
submission = RealToAnimeSubmission(image_data=base64_data)
return await submit_task_with_retry(
endpoint="api/v1/tasks/real-to-anime",
payload=submission.to_api_payload(),
task_name="Real to Anime"
)
async def submit_five_view_generation_task(input_image: Image.Image) -> dict:
"""Submit five-view generation task to backend API"""
# Convert PIL image to base64
processed_image = input_image.convert("RGB")
base64_data = pil_to_base64(processed_image)
submission = FiveViewGenerationSubmission(image_data=base64_data)
return await submit_task_with_retry(
endpoint="api/v1/tasks/five-view-generation",
payload=submission.to_api_payload(),
task_name="Five-View Generation"
)
async def submit_figure_3d_generation_task(input_image: Image.Image, figure_style: str, resolution: str) -> dict:
"""Submit 2D to 3D figure generation task to backend API"""
# Convert PIL image to base64
processed_image = input_image.convert("RGB")
base64_data = pil_to_base64(processed_image)
submission = Figure3DSubmission(
image_data=base64_data,
figure_style=figure_style,
resolution=resolution
)
return await submit_task_with_retry(
endpoint="api/v1/tasks/figure-3d-generation",
payload=submission.to_api_payload(),
task_name="2D to 3D Figure"
)
async def submit_character_figure_collaboration_task(input_image: Image.Image) -> dict:
"""Submit character figure collaboration task to backend API"""
# Convert PIL image to base64
processed_image = input_image.convert("RGB")
base64_data = pil_to_base64(processed_image)
submission = CharacterFigureCollaborationSubmission(
image_data=base64_data
)
return await submit_task_with_retry(
endpoint="api/v1/tasks/character-figure-collaboration",
payload=submission.to_api_payload(),
task_name="Character Figure Collaboration"
)
# ============================================================================
# UI Configuration and Theme Setup
# ============================================================================
def create_custom_theme():
"""Create a clean light theme using Gradio's Default theme"""
return gr.themes.Default(
primary_hue=gr.themes.colors.blue,
secondary_hue=gr.themes.colors.gray,
neutral_hue=gr.themes.colors.slate,
font=[gr.themes.GoogleFont("Inter"), "ui-sans-serif", "system-ui", "sans-serif"],
font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "Consolas", "monospace"],
)
# ============================================================================
# AI Processing Functions
# ============================================================================
# Global task tracking
CURRENT_TASK_ID = None
TASK_CANCELLED = False
def cancel_current_task():
"""Cancel the current running task"""
global TASK_CANCELLED # pylint: disable=global-statement
TASK_CANCELLED = True
logger.info("Task cancellation requested")
return (
gr.update(visible=True), # generate_btn
gr.update(visible=False), # cancel_btn
"Task cancelled" # status_info
)
async def generate_text_to_image(prompt: str, resolution: str, progress=None):
"""Generate image from text prompt"""
global CURRENT_TASK_ID, TASK_CANCELLED # pylint: disable=global-statement
try:
TASK_CANCELLED = False
if not prompt.strip():
yield None, "❌ Please enter an image description", "", True, False
return
logger.info(f"Starting text-to-image generation: {prompt[:50]}...")
start_time = datetime.now()
yield (
None,
"🚀 Submitting task to AI server...",
"**Tip**: The AI is processing your description and preparing to create...",
False,
True
)
try:
task_data = await submit_text_to_image_task(prompt, resolution)
task_id = task_data.get("task_id")
CURRENT_TASK_ID = task_id
if not task_id:
raise Exception("Server did not return a task ID")
logger.info(f"Task submitted successfully: {task_id}")
except Exception as e:
logger.error(f"Task submission failed: {e}")
error_message = str(e) if any(msg in str(e) for msg in ["System is currently busy", "Service temporarily unavailable", "Invalid request parameters", "Network connection timeout", "Unable to connect to server", "Task submission failed"]) else "Task submission failed, please try again later"
yield (
None,
f"❌ {error_message}",
"**Tip**: If the system is busy, please wait a moment and try again",
True,
False
)
return
# Poll for completion
max_attempts = CONFIG.MAX_POLL_ATTEMPTS
poll_interval = CONFIG.POLL_INTERVAL
for attempt in range(max_attempts):
if TASK_CANCELLED:
yield (
None,
"Task cancelled",
"",
True,
False
)
return
try:
status_data = await get_task_status(task_id)
status = status_data.get("status", "unknown")
elapsed_time = (datetime.now() - start_time).total_seconds()
progress_percent = min(95, (attempt / max_attempts) * 100)
if progress:
progress(progress_percent / 100, f"Generating... ({elapsed_time:.0f}s)")
if status == "completed":
# Get result
result_data = await get_task_result(task_id)
result_image = await load_image_from_result(result_data)
logger.info(f"Generation completed in {elapsed_time:.1f}s")
yield (
result_image,
"✓ Image generated!",
f"Generation time: {elapsed_time:.1f} s",
True,
False
)
return
elif status == "failed":
error_msg = status_data.get("error", "Unknown error")
yield (
None,
f"❌ Generation failed: {error_msg}",
"",
True,
False
)
return
# Update status with helpful tips
tips = [
"💡 Tip: More detailed descriptions lead to more accurate images",
"🎨 Creating: The AI is drawing a unique image based on your description",
"⏱️ Please wait: Complex images take more time to refine",
"🔥 Almost done: The AI is adding final touches"
]
tip_index = min(attempt // 5, len(tips) - 1)
yield (
None,
f"🎨 AI is generating the image... ({elapsed_time:.0f}s)",
tips[tip_index],
False,
True
)
await asyncio.sleep(poll_interval)
except Exception as e:
logger.error(f"Error polling task status: {e}")
yield (
None,
"❌ Status query failed. Please try again later.",
"",
True,
False
)
return
# Timeout
yield (
None,
"Timeout: Generation timed out, please try again later",
"",
True,
False
)
except Exception as e:
logger.error(f"Unexpected error in text-to-image generation: {e}")
yield (
None,
"❌ An unexpected error occurred during generation. Please try again later.",
"",
True,
False
)
async def generic_image_processing(
input_image: Image.Image,
task_name: str,
submit_func,
submit_args: tuple = (),
progress=None
):
"""Generic image processing function for all AI features"""
global CURRENT_TASK_ID, TASK_CANCELLED # pylint: disable=global-statement
try:
TASK_CANCELLED = False
if input_image is None:
yield None, f"❌ Please upload an image", "", True, False
return
logger.info(f"Starting {task_name} processing...")
start_time = datetime.now()
yield (
None,
f"🚀 Submitting {task_name} task to the AI server...",
f"**Tip**: The AI is analyzing your image and preparing to start {task_name}...",
False,
True
)
try:
task_data = await submit_func(input_image, *submit_args)
task_id = task_data.get("task_id")
CURRENT_TASK_ID = task_id
if not task_id:
raise Exception("Server did not return a task ID")
logger.info(f"{task_name} task submitted successfully: {task_id}")
except Exception as e:
logger.error(f"{task_name} task submission failed: {e}")
# Show user-friendly error message
error_message = str(e) if any(msg in str(e) for msg in ["System is currently busy", "Service temporarily unavailable", "Invalid request parameters", "Network connection timeout", "Unable to connect to server", "Task submission failed"]) else "Task submission failed, please try again later"
yield (
None,
f"❌ {error_message}",
"**Tip**: If the system is busy, please wait a moment and try again",
True,
False
)
return
# Poll for completion
max_attempts = CONFIG.MAX_POLL_ATTEMPTS
poll_interval = CONFIG.POLL_INTERVAL
for attempt in range(max_attempts):
if TASK_CANCELLED:
yield (
None,
"Task cancelled",
"",
True,
False
)
return
try:
status_data = await get_task_status(task_id)
status = status_data.get("status", "unknown")
elapsed_time = (datetime.now() - start_time).total_seconds()
progress_percent = min(95, (attempt / max_attempts) * 100)
if progress:
progress(progress_percent / 100, f"Processing... ({elapsed_time:.0f}s)")
if status == "completed":
# Get result
result_data = await get_task_result(task_id)
result_image = await load_image_from_result(result_data)
logger.info(f"{task_name} completed in {elapsed_time:.1f}s")
yield (
result_image,
f"✓ {task_name} completed!",
f"Processing time: {elapsed_time:.1f} s",
True,
False
)
return
elif status == "failed":
error_msg = status_data.get("error", "Unknown error")
yield (
None,
f"❌ {task_name} failed: {error_msg}",
"",
True,
False
)
return
# Update status with task-specific tips
task_tips = {
"Image Conversion": ["🔄 Processing: analyzing image features", "🎯 Optimizing: applying advanced image processing"],
"Five-View Generation": ["👁️ Analyzing: understanding facial and pose features", "🔄 Generating: creating multiple viewpoints"],
"Photo Style Transfer": ["📸 Stylizing: applying professional photography techniques", "✨ Enhancing: optimizing lighting and colors"],
"Interior Design Rendering": ["🏠 Designing: composing interior layout", "🎨 Rendering: adding furniture and decor"],
"Watermark Removal": ["🚫 Detecting: locating watermark areas", "🔧 Repairing: intelligently inpainting background"],
"Line Art Conversion": ["✏️ Outlining: extracting contours", "🎨 Refining: improving line details"],
"Image Outpainting": ["📐 Extending: adding coherent border content", "🔄 Blending: ensuring seamless continuity"],
"Anime to Real": ["👤 Converting: mapping anime features to realistic ones", "🎭 Refining: adjusting facial details"],
"Real to Anime": ["🎌 Stylizing: applying anime art style", "✨ Enhancing: optimizing anime effects"]
}
tips = task_tips.get(task_name, ["🔄 Processing: AI is working hard", "⏱️ Please wait: almost done"])
tip_index = min(attempt // 8, len(tips) - 1)
yield (
None,
f"🎨 AI is processing {task_name}... ({elapsed_time:.0f}s)",
tips[tip_index],
False,
True
)
await asyncio.sleep(poll_interval)
except Exception as e:
logger.error(f"Error polling {task_name} task status: {e}")
yield (
None,
"❌ Status query failed. Please try again later.",
"",
True,
False
)
return
# Timeout
yield (
None,
f"Timeout: {task_name} timed out, please try again later",
"",
True,
False
)
except Exception as e:
logger.error(f"Unexpected error in {task_name}: {e}")
yield (
None,
f"❌ An unexpected error occurred during {task_name}. Please try again later.",
"",
True,
False
)
# Specific AI processing functions
async def generate_image_to_image(input_image: Image.Image, progress=None):
"""Generate image from image conversion"""
async for result in generic_image_processing(
input_image, "Image to Image", submit_image_to_image_task, (), progress
):
yield result
async def generate_photo_style(input_image: Image.Image, style_preset: str, progress=None):
"""Apply photo style transfer"""
async for result in generic_image_processing(
input_image, "Photo Style Transfer", submit_photo_style_task, (style_preset,), progress
):
yield result
async def generate_interior_design(input_image: Image.Image, design_style: str, progress=None):
"""Generate interior design rendering"""
async for result in generic_image_processing(
input_image, "Interior Design Rendering", submit_interior_design_task, (design_style,), progress
):
yield result
async def generate_watermark_removal(input_image: Image.Image, progress=None):
"""Remove watermark from image"""
async for result in generic_image_processing(
input_image, "Watermark Removal", submit_watermark_removal_task, (), progress
):
yield result
async def generate_line_art(input_image: Image.Image, progress=None):
"""Convert image to line art"""
async for result in generic_image_processing(
input_image, "Line Art Conversion", submit_line_art_task, (), progress
):
yield result
async def generate_image_outpainting(
input_image: Image.Image, expand_height: float, expand_width: float, progress=None
):
"""Expand image boundaries"""
async for result in generic_image_processing(
input_image, "Image Outpainting", submit_image_outpainting_task,
(expand_height, expand_width), progress
):
yield result
async def generate_anime_to_real(input_image: Image.Image, progress=None):
"""Convert anime character to real person"""
async for result in generic_image_processing(
input_image, "Anime to Real", submit_anime_to_real_task, (), progress
):
yield result
async def generate_real_to_anime(input_image: Image.Image, progress=None):
"""Convert real person to anime character"""
async for result in generic_image_processing(
input_image, "Real to Anime", submit_real_to_anime_task, (), progress
):
yield result
# Five view generation needs special handling
async def generate_five_view(input_image: Image.Image, progress=None):
"""Generate five view angles from portrait"""
async for result in generic_image_processing(
input_image, "Five-View Generation", submit_five_view_generation_task, (), progress
):
yield result
async def generate_figure_3d(input_image: Image.Image, figure_style: str, resolution: str, progress=None):
"""Generate 3D figure from 2D character image"""
async for result in generic_image_processing(
input_image, "2D to 3D Figure", submit_figure_3d_generation_task, (figure_style, resolution), progress
):
yield result
# Character figure collaboration generation
async def generate_character_figure_collaboration(input_image: Image.Image, progress=None):
"""Generate character figure collaboration image"""
async for result in generic_image_processing(
input_image, "Character Figure Collaboration", submit_character_figure_collaboration_task, (), progress
):
yield result
def placeholder_handler(*args):
"""Placeholder function for AI processing"""
# Suppress unused arguments warning
_ = args
return "Feature under development, stay tuned!", gr.update(visible=True)
def create_text_to_image_interface():
"""Create text-to-image interface"""
with gr.Column():
gr.Markdown("## 📝 Text to Image")
gr.Markdown("Enter a textual description and let AI generate an image for you")
with gr.Row():
with gr.Column(scale=2):
prompt_input = gr.Textbox(
label="Image Description",
placeholder="Describe the image you want in detail, e.g., a cute cat playing in a garden, anime style, high-quality details",
lines=4,
max_lines=6
)
resolution_input = gr.Dropdown(
label="Resolution",
choices=[
"portrait - 896x1152 (3:4)",
"square - 1024x1024 (1:1)",
"landscape - 1152x896 (4:3)"
],
value="square - 1024x1024 (1:1)",
interactive=True
)
with gr.Row():
generate_btn = gr.Button("🚀 Generate Image", variant="primary", scale=2)
cancel_btn = gr.Button("Cancel", variant="secondary", scale=1, visible=False)
status_info = gr.Markdown("")
with gr.Column(scale=3):
result_image = gr.Image(
label="Result",
show_label=True,
show_download_button=True,
show_share_button=True
)
image_info = gr.Markdown("Waiting for image generation...")
# Bind events
generate_btn.click(
fn=generate_text_to_image,
inputs=[prompt_input, resolution_input],
outputs=[result_image, status_info, image_info, generate_btn, cancel_btn],
show_progress=True
)
cancel_btn.click(
fn=cancel_current_task,
outputs=[generate_btn, cancel_btn, status_info],
queue=False
)
return gr.Column()
def switch_to_function(function_name: str):
"""Switch to a specific function and show its interface"""
if function_name == "text_to_image":
interface_html = """
<div id="text-to-image-interface">
<h2>📝 Text to Image</h2>
<p>Enter a textual description and let AI generate an image for you</p>
<div>
<p><strong>How to use:</strong></p>
<ul>
<li>Describe the image you want in detail in the input box below</li>
<li>Select an appropriate resolution</li>
<li>Click the "Generate Image" button to start</li>
<li>Generation typically takes 3–10 minutes; please wait patiently</li>
</ul>
</div>
</div>
"""
else:
function_info = {
"image_convert": "Processing: Image to Image - Upload an image for intelligent transformation",
"five_view": "👁️ Five-View Generation - Upload a portrait to generate 5 viewpoints",
"photo_style": "Photo Style Transfer - Apply professional photography styles",
"interior": "Interior Design Rendering - Upload a white model to generate design renders",
"watermark": "Watermark Removal - Detect and remove watermarks intelligently",
"line_art": "Line Art Conversion - Convert photos into clean line art",
"expand": "Image Outpainting - Extend image boundaries coherently",
"anime_to_real": "Anime to Real - Convert anime characters to realistic humans",
"real_to_anime": "Real to Anime - Convert real photos to anime style"
}
description = function_info.get(function_name, "Unknown function")
interface_html = (
f"<div class='welcome-container'>"
f"<h2 class='welcome-title'>{description}</h2><p class='welcome-subtitle'>Feature under development, stay tuned!</p></div>"
)
# Hide welcome content and show dynamic content
return (
gr.update(visible=False), # welcome_content
gr.update(visible=True), # dynamic_content
interface_html
)
# ============================================================================
# Main UI Creation
# ============================================================================
def create_main_interface():
"""Create the main Gradio interface with sidebar layout"""
# Create custom theme
custom_theme = create_custom_theme()
# No custom CSS or JavaScript - use Gradio's default styling
with gr.Blocks(
title=CONFIG.APP_TITLE,
theme=custom_theme,
fill_width=True
) as interface:
# Main layout with sidebar using Row and Column
with gr.Row():
# Sidebar column
with gr.Column(scale=1, min_width=250):
gr.Markdown("# AI Toolbox")
gr.Markdown("Choose a feature below to get started")
# Creation Tools group
gr.Markdown("## Creation Tools")
with gr.Group():
text_to_image_btn = gr.Button("Text to Image", size="sm", variant="secondary")
image_convert_btn = gr.Button("Image to Image", size="sm", variant="secondary")
five_view_btn_sidebar = gr.Button("Five-View Generation", size="sm", variant="secondary")
figure_3d_btn_sidebar = gr.Button("2D to 3D Figure", size="sm", variant="secondary")
character_figure_btn_sidebar = gr.Button("Character Figure Collaboration", size="sm", variant="secondary")
gr.Markdown("---")
# Style Transfer group
gr.Markdown("## Style Transfer")
with gr.Group():
photo_style_btn_sidebar = gr.Button("Photo Style", size="sm", variant="secondary")
interior_btn_sidebar = gr.Button("Interior Design", size="sm", variant="secondary")
gr.Markdown("---")
# Image Processing group
gr.Markdown("## Image Processing")
with gr.Group():
watermark_btn_sidebar = gr.Button("Watermark Removal", size="sm", variant="secondary")
line_art_btn_sidebar = gr.Button("Line Art Conversion", size="sm", variant="secondary")
expand_btn_sidebar = gr.Button("Image Outpainting", size="sm", variant="secondary")
gr.Markdown("---")
# Anime Conversion group
gr.Markdown("## Anime Conversion")
with gr.Group():
anime_to_real_btn_sidebar = gr.Button("Anime to Real", size="sm", variant="secondary")
real_to_anime_btn_sidebar = gr.Button("Real to Anime", size="sm", variant="secondary")
# Main content area
with gr.Column(scale=4):
# 欢迎页面 - 使用推荐的elem_id方法
welcome_content = gr.HTML("""
<div id=\"welcome-page\">
<h1 class=\"app-title\">AI Image Generator</h1>
<p class=\"app-subtitle\">Select a feature on the left to start your AI creation journey</p>
<div class=\"feature-grid\">
<div class=\"feature-card\">
<h3>Creation Tools</h3>
<p>Text to Image, Image to Image, Multi-view Generation</p>
</div>
<div class=\"feature-card\">
<h3>Style Transfer</h3>
<p>Photo Style, Interior Design</p>
</div>
<div class=\"feature-card\">
<h3>Image Processing</h3>
<p>Watermark Removal, Line Art, Outpainting</p>
</div>
<div class=\"feature-card\">
<h3>Anime Conversion</h3>
<p>Anime to Real, Real to Anime</p>
</div>
</div>
</div>
""", elem_id="welcome-container")
# Dynamic content area (initially hidden)
dynamic_content = gr.HTML(visible=False)
# 文本生成图像功能区域(初始隐藏)
with gr.Column(visible=False) as text_to_image_interface:
gr.Markdown("## 📝 Text to Image")
gr.Markdown("Enter a textual description and let AI generate an image for you")
with gr.Row():
with gr.Column(scale=2):
prompt_input = gr.Textbox(
label="Image Description",
placeholder="Describe the image you want in detail, e.g., a cute cat playing in a garden, anime style, high-quality details",
lines=4,
max_lines=6
)
resolution_input = gr.Dropdown(
label="Resolution",
choices=[
"portrait - 768x1344 (9:16)",
"portrait - 896x1152 (3:4)",
"square - 1024x1024 (1:1)",
"landscape - 1152x896 (4:3)",
"landscape - 1216x832 (3:2)",
"landscape - 1344x768 (16:9)",
"landscape - 1536x640 (21:9)"
],
value="square - 1024x1024 (1:1)",
interactive=True
)
with gr.Row():
generate_btn = gr.Button("Generate Image", variant="primary", scale=2)
cancel_btn = gr.Button("Cancel", variant="secondary", scale=1, visible=False)
status_info = gr.Markdown("")
with gr.Column(scale=3):
result_image = gr.Image(
label="Result",
show_label=True,
show_download_button=True,
show_share_button=True
)
image_info = gr.Markdown("""
### 💡 Tips
- Be descriptive: the more detailed the description, the better the results
- Style keywords: e.g., \"high-definition photography\", \"anime style\", \"oil painting style\"
- Composition: describe subject pose, scene layout, and lighting
- Quality hints: e.g., \"4K quality\", \"high-detail\", \"professional photography\"
- Processing time: typically 3–10 minutes. Please wait patiently
""", visible=True)
# 添加文本生成图像的examples
text_to_image_examples_input_only = [[example[0], example[1]] for example in TEXT_TO_IMAGE_EXAMPLES_WITH_RESULTS]
gr.Examples(
examples=text_to_image_examples_input_only,
inputs=[prompt_input, resolution_input],
outputs=result_image,
fn=load_example_result,
label="Example Prompts - Click to preview",
examples_per_page=6,
cache_examples=True
)
# 图像转换功能区域(初始隐藏)
with gr.Column(visible=False) as image_convert_interface:
gr.Markdown("## Image to Image")
gr.Markdown("Upload an image and let AI intelligently transform it")
with gr.Row():
with gr.Column(scale=2):
convert_input = gr.Image(
label="Upload Image",
type="pil",
sources=["upload", "clipboard"],
height=250
)
with gr.Row():
convert_btn = gr.Button("Transform Image", variant="primary", scale=2)
convert_cancel_btn = gr.Button("Cancel", variant="secondary", scale=1, visible=False)
convert_status = gr.Markdown("")
with gr.Column(scale=3):
convert_result = gr.Image(
label="Transformed Result",
show_label=True,
show_download_button=True,
show_share_button=True
)
convert_info = gr.Markdown("""
### 💡 Tips
- Supported formats: PNG, JPEG, JPG, WEBP
- Recommended size: 512x512 to 1536x1536 pixels
- File size: recommended under 10MB
- Image quality: higher clarity yields better results
- Processing time: typically 1–3 minutes
""", visible=True)
# 五视角生成功能区域(初始隐藏)
with gr.Column(visible=False) as five_view_interface:
gr.Markdown("## Five-View Generation")
gr.Markdown("Upload a portrait to generate 5 different viewpoints")
with gr.Row():
with gr.Column(scale=2):
five_view_input = gr.Image(
label="Upload Portrait",
type="pil",
sources=["upload", "clipboard"],
height=250
)
with gr.Row():
five_view_btn = gr.Button("Generate Five Views", variant="primary", scale=2)
five_view_cancel_btn = gr.Button("Cancel", variant="secondary", scale=1, visible=False)
five_view_status = gr.Markdown("")
with gr.Column(scale=3):
five_view_result = gr.Image(
label="Five-View Result",
show_label=True,
show_download_button=True,
show_share_button=True
)
five_view_info = gr.Markdown("""
### 💡 Tips
- Portrait: upload a clear portrait (front-facing preferred)
- Supported types: real persons, anime/game characters
- Recommended size: 512x512 to 1024x1024 pixels
- Background: simple backgrounds work better
- Processing time: typically 1–3 minutes. Please wait patiently
""", visible=True)
# 添加五视角生成的examples
five_view_examples_input_only = [[example[0]] for example in FIVE_VIEW_GENERATION_EXAMPLES_WITH_RESULTS]
gr.Examples(
examples=five_view_examples_input_only,
inputs=[five_view_input],
outputs=[five_view_input, five_view_result],
fn=load_five_view_example,
label="💡 Five-View Examples - Click to preview",
examples_per_page=3,
cache_examples=True
)
# 2D转3D手办功能区域(初始隐藏)
with gr.Column(visible=False) as figure_3d_interface:
gr.Markdown("## 2D to 3D Figure Generation")
gr.Markdown("Convert 2D character images into 3D figure renders with various scene styles")
with gr.Row():
with gr.Column(scale=2):
figure_3d_input = gr.Image(
label="Upload 2D Character Image",
type="pil",
sources=["upload", "clipboard"],
height=250
)
figure_3d_style = gr.Dropdown(
label="Select Figure Style",
choices=FIGURE_3D_STYLE_CHOICES,
value="professional_lighting",
info="Choose the 3D figure scene style"
)
figure_3d_resolution = gr.Dropdown(
label="Resolution",
choices=[
"portrait - 768x1344 (9:16)",
"portrait - 896x1152 (3:4)",
"square - 1024x1024 (1:1)",
"landscape - 1152x896 (4:3)",
"landscape - 1216x832 (3:2)",
"landscape - 1344x768 (16:9)",
"landscape - 1536x640 (21:9)"
],
value="square - 1024x1024 (1:1)",
info="Choose the output image resolution"
)
with gr.Row():
figure_3d_btn = gr.Button("Generate 3D Figure", variant="primary", scale=2)
figure_3d_cancel_btn = gr.Button("Cancel", variant="secondary", scale=1, visible=False)
figure_3d_status = gr.Markdown("")
with gr.Column(scale=3):
figure_3d_result = gr.Image(
label="3D Figure Result",
show_label=True,
show_download_button=True,
show_share_button=True
)
figure_3d_info = gr.Markdown("""
### 💡 Tips
- Character: upload clear 2D character images (anime, game characters, illustrations)
- Supported formats: PNG, JPEG, JPG, WEBP
- Recommended size: 512x512 to 1536x1536 pixels
- File size: under 10MB recommended
- Processing time: typically 1–3 minutes
- Scene styles: professional lighting, collector shelf, desktop display, miniature adventure, Alice's tea party
""", visible=True)
# 添加3D手办生成的examples - 使用不同分辨率展示多样性
figure_3d_examples_input_only = [
[FIGURE_3D_EXAMPLES_WITH_RESULTS[0][0], FIGURE_3D_EXAMPLES_WITH_RESULTS[0][1], "square - 1024x1024 (1:1)"],
[FIGURE_3D_EXAMPLES_WITH_RESULTS[1][0], FIGURE_3D_EXAMPLES_WITH_RESULTS[1][1], "landscape - 1152x896 (4:3)"] if len(FIGURE_3D_EXAMPLES_WITH_RESULTS) > 1 else [FIGURE_3D_EXAMPLES_WITH_RESULTS[0][0], FIGURE_3D_EXAMPLES_WITH_RESULTS[0][1], "landscape - 1152x896 (4:3)"],
[FIGURE_3D_EXAMPLES_WITH_RESULTS[2][0], FIGURE_3D_EXAMPLES_WITH_RESULTS[2][1], "portrait - 896x1152 (3:4)"] if len(FIGURE_3D_EXAMPLES_WITH_RESULTS) > 2 else [FIGURE_3D_EXAMPLES_WITH_RESULTS[0][0], FIGURE_3D_EXAMPLES_WITH_RESULTS[0][1], "portrait - 896x1152 (3:4)"],
[FIGURE_3D_EXAMPLES_WITH_RESULTS[3][0], FIGURE_3D_EXAMPLES_WITH_RESULTS[3][1], "landscape - 1344x768 (16:9)"] if len(FIGURE_3D_EXAMPLES_WITH_RESULTS) > 3 else [FIGURE_3D_EXAMPLES_WITH_RESULTS[0][0], FIGURE_3D_EXAMPLES_WITH_RESULTS[0][1], "landscape - 1344x768 (16:9)"],
[FIGURE_3D_EXAMPLES_WITH_RESULTS[4][0], FIGURE_3D_EXAMPLES_WITH_RESULTS[4][1], "portrait - 768x1344 (9:16)"] if len(FIGURE_3D_EXAMPLES_WITH_RESULTS) > 4 else [FIGURE_3D_EXAMPLES_WITH_RESULTS[0][0], FIGURE_3D_EXAMPLES_WITH_RESULTS[0][1], "portrait - 768x1344 (9:16)"]
][:len(FIGURE_3D_EXAMPLES_WITH_RESULTS)]
gr.Examples(
examples=figure_3d_examples_input_only,
inputs=[figure_3d_input, figure_3d_style, figure_3d_resolution],
outputs=[figure_3d_input, figure_3d_style, figure_3d_resolution, figure_3d_result],
fn=load_figure_3d_example,
label="🎨 3D Figure Examples - Click to preview different styles",
examples_per_page=5,
cache_examples=True
)
# 人物手办合影功能区域(初始隐藏)
with gr.Column(visible=False) as character_figure_collaboration_interface:
gr.Markdown("## Character Figure Collaboration")
gr.Markdown("Generate collaboration photos between characters and figures")
with gr.Row():
with gr.Column(scale=2):
character_figure_input = gr.Image(
label="Upload Character Full-Body Photo",
type="pil",
sources=["upload", "clipboard"],
height=250
)
with gr.Row():
character_figure_btn = gr.Button("Generate Collaboration Photo", variant="primary", scale=2)
character_figure_cancel_btn = gr.Button("Cancel", variant="secondary", scale=1, visible=False)
character_figure_status = gr.Markdown("")
with gr.Column(scale=3):
character_figure_result = gr.Image(
label="Collaboration Result",
show_label=True,
show_download_button=True,
show_share_button=True
)
character_figure_info = gr.Markdown("""
### 💡 Tips
- Upload clear full-body character photos (real person or virtual character)
- Supported formats: PNG, JPEG, JPG, WEBP
- Recommended size: 512x512 to 1536x1536 pixels
- File size: under 10MB recommended
- Processing time: typically 1–3 minutes
- The AI will generate a collaboration photo with the character and a figure
""", visible=True)
# 添加人物手办合影的examples
if CHARACTER_FIGURE_COLLABORATION_EXAMPLES_WITH_RESULTS: # 只有当有examples时才显示
gr.Examples(
examples=CHARACTER_FIGURE_COLLABORATION_EXAMPLES_WITH_RESULTS,
inputs=[character_figure_input],
outputs=[character_figure_input, character_figure_result],
fn=load_character_figure_collaboration_example,
label="🎨 Character Figure Collaboration Examples - Click to preview",
examples_per_page=5,
cache_examples=True
)
# 摄影风格转换功能区域(初始隐藏)
with gr.Column(visible=False) as photo_style_interface:
gr.Markdown("## Photo Style Transfer")
gr.Markdown("Apply professional photography styles to your photos")
with gr.Row():
with gr.Column(scale=2):
photo_style_input = gr.Image(
label="Upload Photo",
type="pil",
sources=["upload", "clipboard"],
height=250
)
photo_style_dropdown = gr.Dropdown(
label="Select Photo Style",
choices=PHOTO_STYLE_CHOICES,
value="camera_movement",
info="Choose the photography style to apply"
)
with gr.Row():
photo_style_btn = gr.Button("Apply Style", variant="primary", scale=2)
photo_style_cancel_btn = gr.Button("Cancel", variant="secondary", scale=1, visible=False)
photo_style_status = gr.Markdown("")
with gr.Column(scale=3):
photo_style_result = gr.Image(
label="Style Transfer Result",
show_label=True,
show_download_button=True,
show_share_button=True
)
photo_style_info = gr.Markdown("""
### 💡 Tips
- Photo types: portraits, landscapes, product photos, etc.
- Recommended quality: higher resolution photos yield better results
- Style selection: choose a style that matches the photo type
- Lighting: well-lit photos convert better
- Processing time: typically 1–2 minutes
""", visible=True)
# 室内设计渲染功能区域(初始隐藏)
with gr.Column(visible=False) as interior_interface:
gr.Markdown("## Interior Design Rendering")
gr.Markdown("Upload a white model interior image to generate design renders")
with gr.Row():
with gr.Column(scale=2):
interior_input = gr.Image(
label="Upload Interior White Model",
type="pil",
sources=["upload", "clipboard"],
height=250
)
interior_style = gr.Dropdown(
label="Select Interior Style",
choices=INTERIOR_DESIGN_STYLE_CHOICES,
value="japanese_wabi_sabi", # keep default key
info="Choose the interior design style to apply"
)
with gr.Row():
interior_btn = gr.Button("Render Design", variant="primary", scale=2)
interior_cancel_btn = gr.Button("Cancel", variant="secondary", scale=1, visible=False)
interior_status = gr.Markdown("")
with gr.Column(scale=3):
interior_result = gr.Image(
label="Rendered Result",
show_label=True,
show_download_button=True,
show_share_button=True
)
interior_info = gr.Markdown("""
### 💡 Tips
- Input: upload a white model or line art of the interior
- Style description: describe the desired design style in detail
- Space type: living room, bedroom, kitchen, office, etc.
- Style keywords: modern minimalism, Nordic, classic Chinese, etc.
- Processing time: typically 2–5 minutes
""", visible=True)
# 添加室内设计的examples
interior_design_examples_input_only = [[example[0], example[1]] for example in INTERIOR_DESIGN_EXAMPLES_WITH_RESULTS]
gr.Examples(
examples=interior_design_examples_input_only,
inputs=[interior_input, interior_style],
outputs=[interior_input, interior_result],
fn=load_interior_design_example_result,
label="💡 Interior Design Examples - Click to preview",
examples_per_page=4,
cache_examples=True
)
# 水印移除功能区域(初始隐藏)
with gr.Column(visible=False) as watermark_interface:
gr.Markdown("## Watermark Removal")
gr.Markdown("Intelligently detect and remove watermarks from images")
with gr.Row():
with gr.Column(scale=2):
watermark_input = gr.Image(
label="Upload Image with Watermark",
type="pil",
sources=["upload", "clipboard"],
height=250
)
with gr.Row():
watermark_btn = gr.Button("Remove Watermark", variant="primary", scale=2)
watermark_cancel_btn = gr.Button("Cancel", variant="secondary", scale=1, visible=False)
watermark_status = gr.Markdown("")
with gr.Column(scale=3):
watermark_result = gr.Image(
label="Watermark Removal Result",
show_label=True,
show_download_button=True,
show_share_button=True
)
watermark_info = gr.Markdown("""
### 💡 Tips
- Watermark types: supports text and icon watermarks
- Image quality: higher quality images yield better results
- Watermark location: AI will automatically detect and remove
- Background complexity: simpler backgrounds remove better
- Processing time: typically 1–3 minutes
""", visible=True)
# 线稿转换功能区域(初始隐藏)
with gr.Column(visible=False) as line_art_interface:
gr.Markdown("## Line Art Conversion")
gr.Markdown("Convert your photo into clean line art")
with gr.Row():
with gr.Column(scale=2):
line_art_input = gr.Image(
label="Upload Photo",
type="pil",
sources=["upload", "clipboard"],
height=250
)
with gr.Row():
line_art_btn = gr.Button("Convert to Line Art", variant="primary", scale=2)
line_art_cancel_btn = gr.Button("Cancel", variant="secondary", scale=1, visible=False)
line_art_status = gr.Markdown("")
with gr.Column(scale=3):
line_art_result = gr.Image(
label="Line Art Result",
show_label=True,
show_download_button=True,
show_share_button=True
)
line_art_info = gr.Markdown("""
### 💡 Tips
- Photo types: portraits, landscapes, architecture, objects
- Image clarity: higher clarity yields better line art
- Contrast: higher contrast improves line extraction
- Complexity: rich details produce better line art
- Processing time: typically 1–2 minutes
""", visible=True)
# 添加线稿转换的examples
gr.Examples(
examples=LINE_ART_CONVERSION_EXAMPLES_WITH_RESULTS,
inputs=[line_art_input],
outputs=[line_art_input, line_art_result],
fn=load_line_art_example_result,
label="💡 Line Art Examples - Click to preview",
examples_per_page=3,
cache_examples=True
)
# 图像扩展功能区域(初始隐藏)
with gr.Column(visible=False) as expand_interface:
gr.Markdown("## Image Outpainting")
gr.Markdown("Intelligently extend image boundaries while keeping content coherent")
with gr.Row():
with gr.Column(scale=2):
expand_input = gr.Image(
label="Upload Image to Outpaint",
type="pil",
sources=["upload", "clipboard"],
height=250
)
expand_height = gr.Slider(
label="Outpaint Height (%)",
minimum=0.0,
maximum=1.0,
value=0.2,
step=0.1,
interactive=True,
info="Percentage to extend vertically"
)
expand_width = gr.Slider(
label="Outpaint Width (%)",
minimum=0.0,
maximum=1.0,
value=0.3,
step=0.1,
interactive=True,
info="Percentage to extend horizontally"
)
with gr.Row():
expand_btn = gr.Button("Outpaint Image", variant="primary", scale=2)
expand_cancel_btn = gr.Button("Cancel", variant="secondary", scale=1, visible=False)
expand_status = gr.Markdown("")
with gr.Column(scale=3):
expand_result = gr.Image(
label="Outpainting Result",
show_label=True,
show_download_button=True,
show_share_button=True
)
expand_info = gr.Markdown("""
### 💡 Tips
- Direction: choose which sides to extend (top/bottom/left/right)
- Pixel amount: 64–512 pixels recommended; too large may impact quality
- Edges: richer edge content yields more natural results
- Coherence: AI will fill in content consistent with the original
- Processing time: typically 2–4 minutes
""", visible=True)
# 图像扩展Examples - 修复inputs/outputs匹配问题
gr.Examples(
examples=IMAGE_OUTPAINTING_EXAMPLES_WITH_RESULTS,
inputs=[expand_input, expand_height, expand_width, expand_result],
outputs=[expand_input, expand_height, expand_width, expand_result],
fn=load_outpainting_example_for_gradio,
label="💡 Outpainting Examples - Click to preview",
examples_per_page=3,
cache_examples=False # Disable caching to avoid serialization issues
)
# 二次元转真人功能区域(初始隐藏)
with gr.Column(visible=False) as anime_to_real_interface:
gr.Markdown("## Anime to Real")
gr.Markdown("Convert anime characters to realistic humans")
with gr.Row():
with gr.Column(scale=2):
anime_to_real_input = gr.Image(
label="Upload Anime Character",
type="pil",
sources=["upload", "clipboard"],
height=250
)
with gr.Row():
anime_to_real_btn = gr.Button("Convert to Real", variant="primary", scale=2)
anime_to_real_cancel_btn = gr.Button("Cancel", variant="secondary", scale=1, visible=False)
anime_to_real_status = gr.Markdown("")
with gr.Column(scale=3):
anime_to_real_result = gr.Image(
label="Anime to Real Result",
show_label=True,
show_download_button=True,
show_share_button=True
)
anime_to_real_info = gr.Markdown("""
### 💡 Tips
- Anime character: supports various anime/game characters
- Facial features: clearer facial features yield better conversion
- Image quality: higher-quality anime images perform better
- Character type: humanoid characters convert best
- Processing time: typically 1–3 minutes
""", visible=True)
# 添加二次元转真人的examples
gr.Examples(
examples=ANIME_TO_REAL_EXAMPLES_WITH_RESULTS,
inputs=[anime_to_real_input],
outputs=[anime_to_real_input, anime_to_real_result],
fn=load_anime_to_real_example_result,
label="💡 Anime to Real Examples - Click to preview",
examples_per_page=1,
cache_examples=True
)
# 真人转动漫功能区域(初始隐藏)
with gr.Column(visible=False) as real_to_anime_interface:
gr.Markdown("## Real to Anime")
gr.Markdown("Convert real photos into anime style")
with gr.Row():
with gr.Column(scale=2):
real_to_anime_input = gr.Image(
label="Upload Real Photo",
type="pil",
sources=["upload", "clipboard"],
height=250
)
with gr.Row():
real_to_anime_btn = gr.Button("Convert to Anime", variant="primary", scale=2)
real_to_anime_cancel_btn = gr.Button("Cancel", variant="secondary", scale=1, visible=False)
real_to_anime_status = gr.Markdown("")
with gr.Column(scale=3):
real_to_anime_result = gr.Image(
label="Real to Anime Result",
show_label=True,
show_download_button=True,
show_share_button=True
)
real_to_anime_info = gr.Markdown("""
### 💡 Tips
- Real photo: upload a clear portrait
- Lighting: evenly lit photos work better
- Pose: front or side portraits convert best
- Background: simple backgrounds help the subject stand out
- Processing time: typically 1–3 minutes
""", visible=True)
# 添加真人转动漫的examples
gr.Examples(
examples=REAL_TO_ANIME_EXAMPLES_WITH_RESULTS,
inputs=[real_to_anime_input],
outputs=[real_to_anime_input, real_to_anime_result],
fn=load_real_to_anime_example_result,
label="💡 Real to Anime Examples - Click to preview",
examples_per_page=3,
cache_examples=True
)
# Bind events to sidebar buttons within the Blocks context
# pylint: disable=no-member
# Define all interfaces in consistent order for interface switching
all_interface_outputs = [
welcome_content, # 0
dynamic_content, # 1
text_to_image_interface, # 2
image_convert_interface, # 3
five_view_interface, # 4
figure_3d_interface, # 5
character_figure_collaboration_interface, # 6
photo_style_interface, # 7
interior_interface, # 8
watermark_interface, # 9
line_art_interface, # 10
expand_interface, # 11
anime_to_real_interface, # 12
real_to_anime_interface # 13
]
# Helper function to show specific interface
def show_interface(interface_index):
"""Show specific interface by index, hide all others"""
updates = []
for i in range(len(all_interface_outputs)):
if i == interface_index:
updates.append(gr.update(visible=True))
else:
updates.append(gr.update(visible=False))
return tuple(updates)
# Text-to-image events
text_to_image_btn.click(
fn=lambda: show_interface(2), # text_to_image_interface is at index 2
outputs=all_interface_outputs
)
generate_btn.click(
fn=generate_text_to_image,
inputs=[prompt_input, resolution_input],
outputs=[result_image, status_info, image_info, generate_btn, cancel_btn],
show_progress=True
)
cancel_btn.click(
fn=cancel_current_task,
outputs=[generate_btn, cancel_btn, status_info],
queue=False
)
# Image convert events
image_convert_btn.click(
fn=lambda: show_interface(3), # image_convert_interface is at index 3
outputs=all_interface_outputs
)
convert_btn.click(
fn=generate_image_to_image,
inputs=[convert_input],
outputs=[convert_result, convert_status, convert_info, convert_btn, convert_cancel_btn],
show_progress=True
)
convert_cancel_btn.click(
fn=cancel_current_task,
outputs=[convert_btn, convert_cancel_btn, convert_status],
queue=False
)
# Five view events
five_view_btn_sidebar.click(
fn=lambda: show_interface(4), # five_view_interface is at index 4
outputs=all_interface_outputs
)
five_view_btn.click(
fn=generate_five_view,
inputs=[five_view_input],
outputs=[five_view_result, five_view_status, five_view_info, five_view_btn, five_view_cancel_btn],
show_progress=True
)
five_view_cancel_btn.click(
fn=cancel_current_task,
outputs=[five_view_btn, five_view_cancel_btn, five_view_status],
queue=False
)
# Figure 3D events
figure_3d_btn_sidebar.click(
fn=lambda: show_interface(5), # figure_3d_interface is at index 5
outputs=all_interface_outputs
)
figure_3d_btn.click(
fn=generate_figure_3d,
inputs=[figure_3d_input, figure_3d_style, figure_3d_resolution],
outputs=[figure_3d_result, figure_3d_status, figure_3d_info, figure_3d_btn, figure_3d_cancel_btn],
show_progress=True
)
figure_3d_cancel_btn.click(
fn=cancel_current_task,
outputs=[figure_3d_btn, figure_3d_cancel_btn, figure_3d_status],
queue=False
)
# Character Figure Collaboration events
character_figure_btn_sidebar.click(
fn=lambda: show_interface(6), # character_figure_collaboration_interface is at index 6
outputs=all_interface_outputs
)
character_figure_btn.click(
fn=generate_character_figure_collaboration,
inputs=[character_figure_input],
outputs=[character_figure_result, character_figure_status, character_figure_info, character_figure_btn, character_figure_cancel_btn],
show_progress=True
)
character_figure_cancel_btn.click(
fn=cancel_current_task,
outputs=[character_figure_btn, character_figure_cancel_btn, character_figure_status],
queue=False
)
# Photo style events
photo_style_btn_sidebar.click(
fn=lambda: show_interface(7), # photo_style_interface is at index 7
outputs=all_interface_outputs
)
photo_style_btn.click(
fn=generate_photo_style,
inputs=[photo_style_input, photo_style_dropdown],
outputs=[photo_style_result, photo_style_status, photo_style_info, photo_style_btn, photo_style_cancel_btn],
show_progress=True
)
photo_style_cancel_btn.click(
fn=cancel_current_task,
outputs=[photo_style_btn, photo_style_cancel_btn, photo_style_status],
queue=False
)
# Interior design events
interior_btn_sidebar.click(
fn=lambda: show_interface(8), # interior_interface is at index 8
outputs=all_interface_outputs
)
interior_btn.click(
fn=generate_interior_design,
inputs=[interior_input, interior_style],
outputs=[interior_result, interior_status, interior_info, interior_btn, interior_cancel_btn],
show_progress=True
)
interior_cancel_btn.click(
fn=cancel_current_task,
outputs=[interior_btn, interior_cancel_btn, interior_status],
queue=False
)
# Watermark removal events
watermark_btn_sidebar.click(
fn=lambda: show_interface(9), # watermark_interface is at index 9
outputs=all_interface_outputs
)
watermark_btn.click(
fn=generate_watermark_removal,
inputs=[watermark_input],
outputs=[watermark_result, watermark_status, watermark_info, watermark_btn, watermark_cancel_btn],
show_progress=True
)
watermark_cancel_btn.click(
fn=cancel_current_task,
outputs=[watermark_btn, watermark_cancel_btn, watermark_status],
queue=False
)
# Line art events
line_art_btn_sidebar.click(
fn=lambda: show_interface(10), # line_art_interface is at index 10
outputs=all_interface_outputs
)
line_art_btn.click(
fn=generate_line_art,
inputs=[line_art_input],
outputs=[line_art_result, line_art_status, line_art_info, line_art_btn, line_art_cancel_btn],
show_progress=True
)
line_art_cancel_btn.click(
fn=cancel_current_task,
outputs=[line_art_btn, line_art_cancel_btn, line_art_status],
queue=False
)
# Expand events
expand_btn_sidebar.click(
fn=lambda: show_interface(11), # expand_interface is at index 11
outputs=all_interface_outputs
)
expand_btn.click(
fn=generate_image_outpainting,
inputs=[expand_input, expand_height, expand_width],
outputs=[expand_result, expand_status, expand_info, expand_btn, expand_cancel_btn],
show_progress=True
)
expand_cancel_btn.click(
fn=cancel_current_task,
outputs=[expand_btn, expand_cancel_btn, expand_status],
queue=False
)
# Anime to real events
anime_to_real_btn_sidebar.click(
fn=lambda: show_interface(12), # anime_to_real_interface is at index 12
outputs=all_interface_outputs
)
anime_to_real_btn.click(
fn=generate_anime_to_real,
inputs=[anime_to_real_input],
outputs=[
anime_to_real_result, anime_to_real_status, anime_to_real_info,
anime_to_real_btn, anime_to_real_cancel_btn
],
show_progress=True
)
anime_to_real_cancel_btn.click(
fn=cancel_current_task,
outputs=[anime_to_real_btn, anime_to_real_cancel_btn, anime_to_real_status],
queue=False
)
# Real to anime events
real_to_anime_btn_sidebar.click(
fn=lambda: show_interface(13), # real_to_anime_interface is at index 13
outputs=all_interface_outputs
)
real_to_anime_btn.click(
fn=generate_real_to_anime,
inputs=[real_to_anime_input],
outputs=[
real_to_anime_result, real_to_anime_status, real_to_anime_info,
real_to_anime_btn, real_to_anime_cancel_btn
],
show_progress=True
)
real_to_anime_cancel_btn.click(
fn=cancel_current_task,
outputs=[real_to_anime_btn, real_to_anime_cancel_btn, real_to_anime_status],
queue=False
)
# pylint: enable=no-member
return interface, {
# Sidebar buttons
'text_to_image_btn': text_to_image_btn,
'image_convert_btn': image_convert_btn,
'five_view_btn_sidebar': five_view_btn_sidebar,
'figure_3d_btn_sidebar': figure_3d_btn_sidebar,
'character_figure_btn_sidebar': character_figure_btn_sidebar,
'photo_style_btn_sidebar': photo_style_btn_sidebar,
'interior_btn_sidebar': interior_btn_sidebar,
'watermark_btn_sidebar': watermark_btn_sidebar,
'line_art_btn_sidebar': line_art_btn_sidebar,
'expand_btn_sidebar': expand_btn_sidebar,
'anime_to_real_btn_sidebar': anime_to_real_btn_sidebar,
'real_to_anime_btn_sidebar': real_to_anime_btn_sidebar,
# Main content areas
'welcome_content': welcome_content,
'dynamic_content': dynamic_content,
# All interface components
'text_to_image_interface': text_to_image_interface,
'image_convert_interface': image_convert_interface,
'five_view_interface': five_view_interface,
'figure_3d_interface': figure_3d_interface,
'character_figure_collaboration_interface': character_figure_collaboration_interface,
'photo_style_interface': photo_style_interface,
'interior_interface': interior_interface,
'watermark_interface': watermark_interface,
'line_art_interface': line_art_interface,
'expand_interface': expand_interface,
'anime_to_real_interface': anime_to_real_interface,
'real_to_anime_interface': real_to_anime_interface,
# Text-to-image components
'prompt_input': prompt_input,
'resolution_input': resolution_input,
'generate_btn': generate_btn,
'cancel_btn': cancel_btn,
'result_image': result_image,
'status_info': status_info,
'image_info': image_info,
# Image convert components
'convert_input': convert_input,
'convert_btn': convert_btn,
'convert_cancel_btn': convert_cancel_btn,
'convert_result': convert_result,
'convert_status': convert_status,
'convert_info': convert_info,
# Five view components
'five_view_input': five_view_input,
'five_view_btn': five_view_btn,
'five_view_cancel_btn': five_view_cancel_btn,
'five_view_result': five_view_result,
'five_view_status': five_view_status,
'five_view_info': five_view_info,
# Photo style components
'photo_style_input': photo_style_input,
'photo_style_dropdown': photo_style_dropdown,
'photo_style_btn': photo_style_btn,
'photo_style_cancel_btn': photo_style_cancel_btn,
'photo_style_result': photo_style_result,
'photo_style_status': photo_style_status,
'photo_style_info': photo_style_info,
# Interior design components
'interior_input': interior_input,
'interior_style': interior_style,
'interior_btn': interior_btn,
'interior_cancel_btn': interior_cancel_btn,
'interior_result': interior_result,
'interior_status': interior_status,
'interior_info': interior_info,
# Watermark removal components
'watermark_input': watermark_input,
'watermark_btn': watermark_btn,
'watermark_cancel_btn': watermark_cancel_btn,
'watermark_result': watermark_result,
'watermark_status': watermark_status,
'watermark_info': watermark_info,
# Line art conversion components
'line_art_input': line_art_input,
'line_art_btn': line_art_btn,
'line_art_cancel_btn': line_art_cancel_btn,
'line_art_result': line_art_result,
'line_art_status': line_art_status,
'line_art_info': line_art_info,
# Image expansion components
'expand_input': expand_input,
'expand_height': expand_height,
'expand_width': expand_width,
'expand_btn': expand_btn,
'expand_cancel_btn': expand_cancel_btn,
'expand_result': expand_result,
'expand_status': expand_status,
'expand_info': expand_info,
# Anime to real components
'anime_to_real_input': anime_to_real_input,
'anime_to_real_btn': anime_to_real_btn,
'anime_to_real_cancel_btn': anime_to_real_cancel_btn,
'anime_to_real_result': anime_to_real_result,
'anime_to_real_status': anime_to_real_status,
'anime_to_real_info': anime_to_real_info,
# Real to anime components
'real_to_anime_input': real_to_anime_input,
'real_to_anime_btn': real_to_anime_btn,
'real_to_anime_cancel_btn': real_to_anime_cancel_btn,
'real_to_anime_result': real_to_anime_result,
'real_to_anime_status': real_to_anime_status,
'real_to_anime_info': real_to_anime_info
}
# Create the main interface
demo, components = create_main_interface()
# =========================================================================
# Security Configuration
# =========================================================================
try:
from fastapi import Request
from starlette.responses import PlainTextResponse
app = demo.app # Gradio's underlying FastAPI app
@app.middleware("http")
async def block_gradio_settings(request: Request, call_next):
path = request.url.path.lower()
# Block known and future settings-related paths aggressively
blocked_keywords = (
"/settings",
"/studio",
"/screen",
"/record",
)
if any(k in path for k in blocked_keywords):
return PlainTextResponse("404 Not Found", status_code=404)
return await call_next(request)
print("🔐 Server-level interceptor enabled: /settings and related internal pages will return 404")
except Exception as _e:
# If anything goes wrong, do not block app startup; log only
print(f"⚠️ Failed to install Settings route interceptor: {_e}")
# ============================================================================
# Launch Configuration
# ============================================================================
if __name__ == "__main__":
# Setup server configuration
SERVER_NAME_CONFIG = CONFIG.SERVER_HOST
SERVER_PORT_CONFIG = CONFIG.SERVER_PORT
SHARE_CONFIG = CONFIG.ENABLE_SHARE
# Print startup information
print(f"🚀 Starting {CONFIG.APP_TITLE}")
print(f"🌐 Access URL: http://{SERVER_NAME_CONFIG}:{SERVER_PORT_CONFIG}")
if SHARE_CONFIG:
print("🔗 Public share: enabled")
else:
print("💡 Tip: Local access only (more secure)")
# Launch the application
print("🚀 Launching AI Image Generator...")
print(f"📍 Server: {SERVER_NAME_CONFIG}:{SERVER_PORT_CONFIG}")
print("🎨 Forced light theme: enabled")
print("🔒 Debug mode: disabled")
try:
demo.launch(
server_name=SERVER_NAME_CONFIG,
server_port=SERVER_PORT_CONFIG,
share=SHARE_CONFIG,
debug=False, # Force disable debug mode
show_error=False, # Hide error details for production
quiet=False # Show basic launch info
)
except Exception as e:
print(f"❌ Launch failed: {e}")
import traceback
traceback.print_exc()
|