Spaces:
Runtime error
Runtime error
File size: 104,755 Bytes
2857cf3 ae10cda 2857cf3 ae10cda 2857cf3 ae10cda 2857cf3 ae10cda 2857cf3 ae10cda 2857cf3 ae10cda 2857cf3 ae10cda 2857cf3 ae10cda 2857cf3 ae10cda 2857cf3 ae10cda 2857cf3 ae10cda 2857cf3 ae10cda 2857cf3 ae10cda 2857cf3 09df1fe 2857cf3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 | from __future__ import annotations
from collections.abc import Callable
import io
import importlib
import os
import subprocess
import sys
from pathlib import Path
from types import SimpleNamespace
from typing import NoReturn, cast
import apprc as rc
import pytest
from rich.console import Console
from typer.testing import CliRunner
import kneiff.cli.comfy as cli_comfy
import kneiff.cli.dataset as cli_dataset
from kneiff.config import (
COMFY_I2I_LORA_1_ENV_KEY,
COMFY_I2I_LORA_2_ENV_KEY,
COMFY_I2I_LORA_ENV_KEY,
COMFY_I2I_LORA_STRENGTH_1_ENV_KEY,
COMFY_I2I_LORA_STRENGTH_2_ENV_KEY,
COMFY_I2I_LORA_STRENGTH_ENV_KEY,
COMFY_I2I_MODEL_DUO_ENV_KEY,
COMFY_I2I_MODEL_SOLO_ENV_KEY,
COMFY_LORAS_DIR_1_ENV_KEY,
COMFY_LORAS_DIR_2_ENV_KEY,
COMFY_MODELS_DIR_ENV_KEY,
COMFY_OUTPUT_DIR_ENV_KEY,
COMFY_POLL_INTERVAL_SECONDS_ENV_KEY,
COMFY_PROMPT_TIMEOUT_SECONDS_ENV_KEY,
COMFY_UPSCALE_MODEL_ENV_KEY,
COMFY_UPSCALE_DENOISE_BASE_ENV_KEY,
COMFY_UPSCALE_LORA_ENV_KEY,
COMFY_UPSCALE_LORA_STRENGTH_ENV_KEY,
COMFY_UPSCALE_LORA_TOKEN_ENV_KEY,
COMFY_UPSCALE_REFINER_CLIP_ENV_KEY,
COMFY_UPSCALE_REFINER_CLIP_TYPE_ENV_KEY,
COMFY_UPSCALE_REFINER_UNET_ENV_KEY,
COMFY_UPSCALE_REFINER_VAE_ENV_KEY,
COMFY_URL_ENV_KEY,
COMFY_T2I_LORA_DUO_1_ENV_KEY,
COMFY_T2I_LORA_DUO_2_ENV_KEY,
COMFY_T2I_LORA_SOLO_ENV_KEY,
COMFY_T2I_LORA_STRENGTH_DUO_1_ENV_KEY,
COMFY_T2I_LORA_STRENGTH_DUO_2_ENV_KEY,
COMFY_T2I_LORA_STRENGTH_SOLO_ENV_KEY,
COMFY_T2I_MODEL_DUO_ENV_KEY,
COMFY_T2I_MODEL_SOLO_ENV_KEY,
DEFAULT_COMFY_UPSCALE_MODEL,
DEFAULT_COMFY_UPSCALE_DENOISE_BASE,
DEFAULT_COMFY_UPSCALE_LORA,
DEFAULT_COMFY_UPSCALE_LORA_STRENGTH,
DEFAULT_COMFY_UPSCALE_LORA_TOKEN,
DEFAULT_COMFY_UPSCALE_REFINER_CLIP,
DEFAULT_COMFY_UPSCALE_REFINER_CLIP_TYPE,
DEFAULT_COMFY_UPSCALE_REFINER_UNET,
DEFAULT_COMFY_UPSCALE_REFINER_VAE,
KNF_APPRC_TOML_ENV_KEY,
KNEIFF_RC,
ComfyConfig,
KneiffConfig,
LEGACY_COMFY_UPSCALE_Z_IMAGE_REFINER_CLIP,
LEGACY_COMFY_UPSCALE_Z_IMAGE_REFINER_CLIP_TYPE,
LEGACY_COMFY_UPSCALE_Z_IMAGE_REFINER_UNET,
LEGACY_COMFY_UPSCALE_Z_IMAGE_REFINER_VAE,
)
from kneiff.infer.comfy.client import ComfyUploadedImage
from kneiff.progress import ProgressUpdate
import kneiff.utils.image.tag_jtp3 as tag_jtp3
from tests._cli_helpers import invoke_cli
pytestmark = pytest.mark.usefixtures("isolated_cli_project")
SHOWCASE_PROMPTS_PATH = (
Path(__file__).parent / "fixtures" / "projects" / "aurora" / "prompts.knf.yaml"
)
def _write_noob_showcase_prompts(path: Path) -> None:
"""Write one standalone catalog usable by NOOB CLI routing tests."""
path.write_text(
"""
version: 1
defaults:
seed: 123
prompts:
- id: aurora_portrait
uses: [showcase, training_validation]
captions:
nlg:
- Aurora_Fox portrait
pony:
- score_9, Aurora_Fox, portrait
noob:
- Aurora_Fox, portrait
""",
encoding="utf-8",
)
_DEFAULT_COMFY_INPUT_OPTIONS = {
("UpscaleModelLoader", "model_name"): (
DEFAULT_COMFY_UPSCALE_MODEL,
"local-upscaler.safetensors",
"cli-upscaler.safetensors",
"4x-test.safetensors",
),
("UNETLoader", "unet_name"): (
DEFAULT_COMFY_UPSCALE_REFINER_UNET,
LEGACY_COMFY_UPSCALE_Z_IMAGE_REFINER_UNET,
"z-image.safetensors",
),
("CLIPLoader", "clip_name"): (
DEFAULT_COMFY_UPSCALE_REFINER_CLIP,
LEGACY_COMFY_UPSCALE_Z_IMAGE_REFINER_CLIP,
"qwen.safetensors",
),
("CLIPLoader", "type"): (
DEFAULT_COMFY_UPSCALE_REFINER_CLIP_TYPE,
LEGACY_COMFY_UPSCALE_Z_IMAGE_REFINER_CLIP_TYPE,
),
("VAELoader", "vae_name"): (
DEFAULT_COMFY_UPSCALE_REFINER_VAE,
LEGACY_COMFY_UPSCALE_Z_IMAGE_REFINER_VAE,
),
}
class _FakeComfyModelClient:
def __init__(
self,
server_url: str,
options: dict[tuple[str, str], tuple[str, ...]],
) -> None:
self.server_url = server_url.rstrip("/")
self.options = options
self.input_option_requests: list[tuple[str, str]] = []
def input_options(self, node_class: str, input_name: str) -> tuple[str, ...]:
key = (node_class, input_name)
self.input_option_requests.append(key)
return self.options.get(key, ())
class _CapturedShowcaseProgress:
"""Record aggregate CLI progress without rendering a terminal bar."""
def __init__(
self,
title: str,
total: int,
console: Console | None,
) -> None:
self.title = title
self.total = total
self.console = console
self.advances: list[str | None] = []
self.exit_error: type[BaseException] | None = None
def __enter__(self) -> _CapturedShowcaseProgress:
return self
def __exit__(self, *exc_info: object) -> None:
error_type = exc_info[0]
self.exit_error = (
error_type
if isinstance(error_type, type) and issubclass(error_type, BaseException)
else None
)
def advance(self, text: str | None = None, *, amount: int = 1) -> None:
self.advances.extend([text] * amount)
def step(self, text: str, *, amount: int = 1) -> None:
self.total += amount
self.advance(text, amount=amount)
def apply(self, update: ProgressUpdate) -> None:
"""Record one shared progress update."""
self.total += update.additional_total
self.advance(update.description, amount=update.advance)
def _capturing_showcase_progress_factory(
reporters: list[_CapturedShowcaseProgress],
) -> Callable[..., _CapturedShowcaseProgress]:
def create(
title: str,
total: int = 0,
console: Console | None = None,
) -> _CapturedShowcaseProgress:
reporter = _CapturedShowcaseProgress(title, total, console)
reporters.append(reporter)
return reporter
return create
def _install_fake_comfy_model_client(
monkeypatch: pytest.MonkeyPatch,
*,
options: dict[tuple[str, str], tuple[str, ...]] | None = None,
) -> _FakeComfyModelClient:
client = _FakeComfyModelClient(
"http://127.0.0.1:8188",
options or dict(_DEFAULT_COMFY_INPUT_OPTIONS),
)
monkeypatch.setattr(cli_comfy, "ComfyUiClient", lambda server_url: client)
return client
@pytest.fixture(autouse=True)
def _isolate_comfy_env(monkeypatch: pytest.MonkeyPatch) -> None:
import kneiff.infer.comfy.showcase_grid as showcase_grid_module
owner = rc.schema.owner_for(ComfyConfig)
for field in owner.fields:
monkeypatch.delenv(owner.env_key(field.name), raising=False)
monkeypatch.setattr(
showcase_grid_module,
"write_showcase_grid",
lambda rows, output_subfolder, filename, **kwargs: ComfyUploadedImage(
name=filename,
subfolder=output_subfolder,
type="output",
),
)
def test_cli_help_smoke() -> None:
runner = CliRunner()
for args in (
["--help"],
["comfy", "--help"],
["comfy", "showcase", "--help"],
["comfy", "upscale", "--help"],
["comfy", "outpaint", "--help"],
["comfy", "t2i", "--help"],
["comfy", "t2i", "solo", "--help"],
["comfy", "t2i", "duo", "--help"],
["config", "--help"],
["config", "paths", "--help"],
["config", "show", "--help"],
["config", "doctor", "--help"],
["config", "setup", "--help"],
["config", "set", "--help"],
["config", "edit", "--help"],
["config", "app", "--help"],
["config", "app", "init", "--help"],
["config", "storage", "--help"],
["config", "storage", "add", "--help"],
["config", "storage", "list", "--help"],
["config", "storage", "remove", "--help"],
["img", "--help"],
["img", "tag", "--help"],
["llm", "--help"],
["llm", "prompt", "--help"],
["dataset", "--help"],
["dataset", "aspects", "--help"],
["dataset", "describe", "--help"],
["model", "--help"],
["model", "convert", "--help"],
["train", "--help"],
["train", "start", "--help"],
["train", "prepare", "--help"],
["train", "runs", "--help"],
["train", "review", "--help"],
["train", "grid", "--help"],
):
result = invoke_cli(runner, args)
assert result.exit_code == 0
def test_comfy_t2i_help_exposes_preset_specific_options() -> None:
runner = CliRunner()
solo = invoke_cli(runner, ["comfy", "t2i", "solo", "--help"])
duo = invoke_cli(runner, ["comfy", "t2i", "duo", "--help"])
assert solo.exit_code == 0
assert "--pipeline" in solo.output
assert "--activation-token-1" in solo.output
assert "--t2i-lora-strength-1" in solo.output
assert "--num-cleanups" in solo.output
assert "--i2i-model" in solo.output
assert "--i2i-lora-strength" in solo.output
assert duo.exit_code == 0
assert "--activation-token-2" in duo.output
assert "--num-cleanups" in duo.output
assert "--i2i-lora-strength-2" in duo.output
def test_comfy_t2i_solo_requires_pipeline_outside_an_interactive_terminal() -> None:
runner = CliRunner()
result = invoke_cli(runner, ["comfy", "t2i", "solo", "studio portrait"])
assert result.exit_code == 2
assert "--pipeline" in result.output
def test_showcase_workflow_picker_keeps_project_order_without_duplicates() -> None:
picker_names = cli_comfy._workflow_picker_preset_names(
["pony", "project-only", "anima", "pony", "noob", "project-only"]
)
assert picker_names == ["pony", "project-only", "anima", "noob"]
def test_cli_root_help_shows_canonical_image_group_only() -> None:
runner = CliRunner()
result = invoke_cli(runner, ["--help"])
assert result.exit_code == 0
assert "│ img" in result.output
assert "│ image" not in result.output
assert "infer" not in result.output
def test_image_group_alias_is_removed() -> None:
runner = CliRunner()
result = invoke_cli(runner, ["image", "--help"])
assert result.exit_code != 0
assert "No such command 'image'" in result.output
def test_infer_group_is_removed() -> None:
runner = CliRunner()
result = invoke_cli(runner, ["infer", "--help"])
assert result.exit_code != 0
assert "No such command 'infer'" in result.output
def test_config_uses_native_apprc_index_path(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
monkeypatch.delenv(KNF_APPRC_TOML_ENV_KEY, raising=False)
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config-home"))
expected_path = tmp_path / "config-home" / "knf" / "knf.apprc.toml"
assert KNEIFF_RC.spec.index_env_key == KNF_APPRC_TOML_ENV_KEY
assert KNEIFF_RC.spec.default_index_path() == expected_path
assert KNEIFF_RC.spec.index_path() == expected_path
def test_cli_help_shows_batch_config_and_resume_run_usage() -> None:
runner = CliRunner()
start_result = invoke_cli(runner, ["train", "start", "--help"])
prepare_result = invoke_cli(runner, ["train", "prepare", "--help"])
dataset_result = invoke_cli(runner, ["dataset", "plan", "--help"])
assert start_result.exit_code == 0
assert "[CONFIG]..." in start_result.output
assert "knf train start CONFIG..." in start_result.output
assert "knf train start CONFIG... --resume RUN" in start_result.output
assert "Pass RUN after --resume" in start_result.output
assert prepare_result.exit_code == 0
assert "[CONFIG]..." in prepare_result.output
assert dataset_result.exit_code == 0
assert "[CONFIG]..." in dataset_result.output
def test_comfy_showcase_help_shows_prompt_field() -> None:
runner = CliRunner()
output_option = "--" + "output"
result = invoke_cli(runner, ["comfy", "showcase", "--help"])
assert result.exit_code == 0
assert "--lora" in result.output
assert "--training" in result.output
assert "[STEPS]..." in result.output
assert "--prompts" in result.output
assert "--prompt-field" in result.output
assert output_option not in result.output
assert "auto" in result.output
assert "packaged preset" in result.output
assert "noob-nova" in result.output
assert "showcase_<preset>.workflow.json" in result.output
def test_comfy_upscale_help_describes_directory_inputs() -> None:
runner = CliRunner()
result = invoke_cli(runner, ["comfy", "upscale", "--help"])
normalized_help = " ".join(result.output.replace("│", " ").split())
assert result.exit_code == 0
assert "One or more image files or directories to upscale." in normalized_help
assert "Directory inputs are scanned recursively by default." in normalized_help
assert "Include images in nested subdirectories" in normalized_help
assert "--recursive" in result.output
assert "--no-recursive" in result.output
def test_comfy_outpaint_help_describes_packaged_file_only_workflows() -> None:
runner = CliRunner()
result = invoke_cli(runner, ["comfy", "outpaint", "--help"])
normalized_help = " ".join(result.output.replace("│", " ").split())
assert result.exit_code == 0
assert "Omit them to consume newline-delimited SOURCE/... paths from stdin" in (
normalized_help
)
assert "Directory inputs are rejected" in normalized_help
assert "--workflow" in result.output
assert "--safe-border" in result.output
assert "without ComfyUI inference" in normalized_help
assert "--seed" in result.output
def test_comfy_t2i_solo_help_uses_positional_prompt() -> None:
runner = CliRunner()
result = invoke_cli(runner, ["comfy", "t2i", "solo", "--help"])
normalized_help = " ".join(result.output.replace("│", " ").split())
assert result.exit_code == 0
assert "comfy t2i solo [OPTIONS] PROMPT" in normalized_help
assert "Scene request used to generate reviewed prompts." in normalized_help
def test_model_showcase_command_is_removed() -> None:
runner = CliRunner()
result = invoke_cli(runner, ["model", "showcase", "--help"])
assert result.exit_code != 0
def test_comfy_config_schema_declares_custom_prefix_fields() -> None:
owner = rc.schema.owner_for(ComfyConfig)
expected_env_keys = {
"url": COMFY_URL_ENV_KEY,
"models_dir": COMFY_MODELS_DIR_ENV_KEY,
"loras_dir_1": COMFY_LORAS_DIR_1_ENV_KEY,
"loras_dir_2": COMFY_LORAS_DIR_2_ENV_KEY,
"output_dir": COMFY_OUTPUT_DIR_ENV_KEY,
"t2i_model_solo": COMFY_T2I_MODEL_SOLO_ENV_KEY,
"t2i_lora_solo": COMFY_T2I_LORA_SOLO_ENV_KEY,
"t2i_lora_strength_solo": COMFY_T2I_LORA_STRENGTH_SOLO_ENV_KEY,
"i2i_model_solo": COMFY_I2I_MODEL_SOLO_ENV_KEY,
"i2i_lora": COMFY_I2I_LORA_ENV_KEY,
"i2i_lora_strength": COMFY_I2I_LORA_STRENGTH_ENV_KEY,
"t2i_model_duo": COMFY_T2I_MODEL_DUO_ENV_KEY,
"t2i_lora_duo_1": COMFY_T2I_LORA_DUO_1_ENV_KEY,
"t2i_lora_duo_2": COMFY_T2I_LORA_DUO_2_ENV_KEY,
"t2i_lora_strength_duo_1": COMFY_T2I_LORA_STRENGTH_DUO_1_ENV_KEY,
"t2i_lora_strength_duo_2": COMFY_T2I_LORA_STRENGTH_DUO_2_ENV_KEY,
"i2i_model_duo": COMFY_I2I_MODEL_DUO_ENV_KEY,
"i2i_lora_1": COMFY_I2I_LORA_1_ENV_KEY,
"i2i_lora_2": COMFY_I2I_LORA_2_ENV_KEY,
"i2i_lora_strength_1": COMFY_I2I_LORA_STRENGTH_1_ENV_KEY,
"i2i_lora_strength_2": COMFY_I2I_LORA_STRENGTH_2_ENV_KEY,
"upscale_model": COMFY_UPSCALE_MODEL_ENV_KEY,
"upscale_refiner_unet": COMFY_UPSCALE_REFINER_UNET_ENV_KEY,
"upscale_refiner_clip": COMFY_UPSCALE_REFINER_CLIP_ENV_KEY,
"upscale_refiner_clip_type": COMFY_UPSCALE_REFINER_CLIP_TYPE_ENV_KEY,
"upscale_refiner_vae": COMFY_UPSCALE_REFINER_VAE_ENV_KEY,
"upscale_lora": COMFY_UPSCALE_LORA_ENV_KEY,
"upscale_lora_token": COMFY_UPSCALE_LORA_TOKEN_ENV_KEY,
"upscale_lora_strength": COMFY_UPSCALE_LORA_STRENGTH_ENV_KEY,
"upscale_denoise_base": COMFY_UPSCALE_DENOISE_BASE_ENV_KEY,
"prompt_timeout_seconds": COMFY_PROMPT_TIMEOUT_SECONDS_ENV_KEY,
"poll_interval_seconds": COMFY_POLL_INTERVAL_SECONDS_ENV_KEY,
}
assert owner in KNEIFF_RC.spec.owners
assert {
field.name: owner.env_key(field.name) for field in owner.fields
} == expected_env_keys
for field_name in expected_env_keys:
assert owner.config_path_text(field_name) == f"comfy.{field_name}"
def test_kneiff_config_uses_comfy_defaults(
monkeypatch: pytest.MonkeyPatch,
) -> None:
for env_key in (
COMFY_URL_ENV_KEY,
COMFY_MODELS_DIR_ENV_KEY,
COMFY_LORAS_DIR_1_ENV_KEY,
COMFY_LORAS_DIR_2_ENV_KEY,
COMFY_OUTPUT_DIR_ENV_KEY,
COMFY_T2I_MODEL_SOLO_ENV_KEY,
COMFY_T2I_LORA_SOLO_ENV_KEY,
COMFY_T2I_LORA_STRENGTH_SOLO_ENV_KEY,
COMFY_I2I_MODEL_SOLO_ENV_KEY,
COMFY_I2I_LORA_ENV_KEY,
COMFY_I2I_LORA_STRENGTH_ENV_KEY,
COMFY_T2I_MODEL_DUO_ENV_KEY,
COMFY_T2I_LORA_DUO_1_ENV_KEY,
COMFY_T2I_LORA_DUO_2_ENV_KEY,
COMFY_T2I_LORA_STRENGTH_DUO_1_ENV_KEY,
COMFY_T2I_LORA_STRENGTH_DUO_2_ENV_KEY,
COMFY_I2I_MODEL_DUO_ENV_KEY,
COMFY_I2I_LORA_1_ENV_KEY,
COMFY_I2I_LORA_2_ENV_KEY,
COMFY_I2I_LORA_STRENGTH_1_ENV_KEY,
COMFY_I2I_LORA_STRENGTH_2_ENV_KEY,
COMFY_UPSCALE_MODEL_ENV_KEY,
COMFY_UPSCALE_REFINER_UNET_ENV_KEY,
COMFY_UPSCALE_REFINER_CLIP_ENV_KEY,
COMFY_UPSCALE_REFINER_CLIP_TYPE_ENV_KEY,
COMFY_UPSCALE_REFINER_VAE_ENV_KEY,
COMFY_UPSCALE_LORA_ENV_KEY,
COMFY_UPSCALE_LORA_TOKEN_ENV_KEY,
COMFY_UPSCALE_LORA_STRENGTH_ENV_KEY,
COMFY_UPSCALE_DENOISE_BASE_ENV_KEY,
COMFY_PROMPT_TIMEOUT_SECONDS_ENV_KEY,
COMFY_POLL_INTERVAL_SECONDS_ENV_KEY,
):
monkeypatch.delenv(env_key, raising=False)
config = KneiffConfig().comfy
assert config.url == "http://127.0.0.1:8188"
assert config.models_dir == ""
assert config.loras_dir_1 == ""
assert config.loras_dir_2 == ""
assert config.output_dir == ""
assert config.t2i_lora_strength_solo == 1.0
assert config.i2i_lora_strength == 1.0
assert config.t2i_lora_strength_duo_1 == 1.0
assert config.t2i_lora_strength_duo_2 == 1.0
assert config.i2i_lora_strength_1 == 1.0
assert config.i2i_lora_strength_2 == 1.0
assert config.upscale_model == DEFAULT_COMFY_UPSCALE_MODEL
assert config.upscale_refiner_unet == DEFAULT_COMFY_UPSCALE_REFINER_UNET
assert config.upscale_refiner_clip == DEFAULT_COMFY_UPSCALE_REFINER_CLIP
assert config.upscale_refiner_clip_type == DEFAULT_COMFY_UPSCALE_REFINER_CLIP_TYPE
assert config.upscale_refiner_vae == DEFAULT_COMFY_UPSCALE_REFINER_VAE
assert config.upscale_lora == DEFAULT_COMFY_UPSCALE_LORA
assert config.upscale_lora_token == DEFAULT_COMFY_UPSCALE_LORA_TOKEN
assert config.upscale_lora_strength == DEFAULT_COMFY_UPSCALE_LORA_STRENGTH
assert config.upscale_denoise_base == DEFAULT_COMFY_UPSCALE_DENOISE_BASE
assert config.prompt_timeout_seconds == 3600.0
assert config.poll_interval_seconds == 1.0
def test_kneiff_config_uses_comfy_env_values(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv(COMFY_URL_ENV_KEY, "http://comfy.example")
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, "/models")
monkeypatch.setenv(COMFY_LORAS_DIR_1_ENV_KEY, "/models/models/loras/project")
monkeypatch.setenv(COMFY_UPSCALE_MODEL_ENV_KEY, "4x-test.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_REFINER_UNET_ENV_KEY, "z-image.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_REFINER_CLIP_ENV_KEY, "qwen.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_REFINER_CLIP_TYPE_ENV_KEY, "lumina2")
monkeypatch.setenv(COMFY_UPSCALE_REFINER_VAE_ENV_KEY, "ae.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_LORA_ENV_KEY, "project/character.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_LORA_TOKEN_ENV_KEY, "char_token")
monkeypatch.setenv(COMFY_UPSCALE_LORA_STRENGTH_ENV_KEY, "0.75")
monkeypatch.setenv(COMFY_UPSCALE_DENOISE_BASE_ENV_KEY, "0.18")
monkeypatch.setenv(COMFY_PROMPT_TIMEOUT_SECONDS_ENV_KEY, "12.5")
monkeypatch.setenv(COMFY_POLL_INTERVAL_SECONDS_ENV_KEY, "0.25")
config = KneiffConfig().comfy
assert config == ComfyConfig(
url="http://comfy.example",
models_dir="/models",
loras_dir_1="/models/models/loras/project",
upscale_model="4x-test.safetensors",
upscale_refiner_unet="z-image.safetensors",
upscale_refiner_clip="qwen.safetensors",
upscale_refiner_clip_type="lumina2",
upscale_refiner_vae="ae.safetensors",
upscale_lora="project/character.safetensors",
upscale_lora_token="char_token",
upscale_lora_strength=0.75,
upscale_denoise_base=0.18,
prompt_timeout_seconds=12.5,
poll_interval_seconds=0.25,
)
def test_kneiff_config_loads_every_t2i_environment_field(
monkeypatch: pytest.MonkeyPatch,
) -> None:
values = {
COMFY_LORAS_DIR_1_ENV_KEY: "primary",
COMFY_LORAS_DIR_2_ENV_KEY: "partner",
COMFY_OUTPUT_DIR_ENV_KEY: "/comfy/output",
COMFY_T2I_MODEL_SOLO_ENV_KEY: "solo-model.safetensors",
COMFY_T2I_LORA_SOLO_ENV_KEY: "solo-lora.safetensors",
COMFY_T2I_LORA_STRENGTH_SOLO_ENV_KEY: "0.11",
COMFY_I2I_MODEL_SOLO_ENV_KEY: "solo-edit.safetensors",
COMFY_I2I_LORA_ENV_KEY: "solo-edit-lora.safetensors",
COMFY_I2I_LORA_STRENGTH_ENV_KEY: "0.22",
COMFY_T2I_MODEL_DUO_ENV_KEY: "duo-model.safetensors",
COMFY_T2I_LORA_DUO_1_ENV_KEY: "duo-one.safetensors",
COMFY_T2I_LORA_DUO_2_ENV_KEY: "duo-two.safetensors",
COMFY_T2I_LORA_STRENGTH_DUO_1_ENV_KEY: "0.33",
COMFY_T2I_LORA_STRENGTH_DUO_2_ENV_KEY: "0.44",
COMFY_I2I_MODEL_DUO_ENV_KEY: "duo-edit.safetensors",
COMFY_I2I_LORA_1_ENV_KEY: "edit-one.safetensors",
COMFY_I2I_LORA_2_ENV_KEY: "edit-two.safetensors",
COMFY_I2I_LORA_STRENGTH_1_ENV_KEY: "0.55",
COMFY_I2I_LORA_STRENGTH_2_ENV_KEY: "0.66",
}
for key, value in values.items():
monkeypatch.setenv(key, value)
config = KneiffConfig().comfy
assert config.loras_dir_1 == "primary"
assert config.loras_dir_2 == "partner"
assert config.output_dir == "/comfy/output"
assert config.t2i_model_solo == "solo-model.safetensors"
assert config.t2i_lora_solo == "solo-lora.safetensors"
assert config.t2i_lora_strength_solo == 0.11
assert config.i2i_model_solo == "solo-edit.safetensors"
assert config.i2i_lora == "solo-edit-lora.safetensors"
assert config.i2i_lora_strength == 0.22
assert config.t2i_model_duo == "duo-model.safetensors"
assert config.t2i_lora_duo_1 == "duo-one.safetensors"
assert config.t2i_lora_duo_2 == "duo-two.safetensors"
assert config.t2i_lora_strength_duo_1 == 0.33
assert config.t2i_lora_strength_duo_2 == 0.44
assert config.i2i_model_duo == "duo-edit.safetensors"
assert config.i2i_lora_1 == "edit-one.safetensors"
assert config.i2i_lora_2 == "edit-two.safetensors"
assert config.i2i_lora_strength_1 == 0.55
assert config.i2i_lora_strength_2 == 0.66
def test_removed_comfy_loras_dir_environment_key_is_ignored(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv(COMFY_LORAS_DIR_1_ENV_KEY, raising=False)
monkeypatch.setenv("COMFY_LORAS_DIR", "legacy-directory")
assert KneiffConfig().comfy.loras_dir_1 == ""
def test_kneiff_config_rejects_invalid_comfy_float_env(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.setenv(COMFY_PROMPT_TIMEOUT_SECONDS_ENV_KEY, "slow")
with pytest.raises(ExceptionGroup, match="ComfySettings") as exc_info:
KneiffConfig()
assert "prompt_timeout_seconds" in repr(exc_info.value)
def test_cli_config_error_is_concise_and_does_not_expose_secrets(
tmp_path: Path,
isolated_cli_storage: Path,
) -> None:
secret = "CLI_CONFIG_SECRET_SENTINEL_7a91"
env = os.environ.copy()
env.update(
{
"COMFY_PROMPT_TIMEOUT_SECONDS": "slow",
"KNF_LMSTUDIO_API_KEY": secret,
"KNF_STORAGE": str(isolated_cli_storage),
"XDG_CONFIG_HOME": str(tmp_path / "config-home"),
}
)
result = subprocess.run(
[
sys.executable,
"-m",
"kneiff.cli.app",
"--skip-dotenv-layers",
"dataset",
"plan",
],
capture_output=True,
text=True,
check=False,
env=env,
)
output = result.stdout + result.stderr
assert result.returncode == 2
assert "Invalid Kneiff runtime config" in output
assert "prompt_timeout_seconds" in output
assert secret not in output
assert "Traceback" not in output
def test_non_cli_bundle_resolves_named_storage_after_apprc_bootstrap(
tmp_path: Path,
) -> None:
config_home = tmp_path / "config-home"
storage_root = tmp_path / "named-storage"
storage_root.mkdir()
(storage_root / ".env.apprc-storage").touch()
index_path = config_home / "knf" / "knf.apprc.toml"
rc.storage.register_storage(
name="demo",
root=storage_root,
path=index_path,
storage_env_filename=KNEIFF_RC.spec.storage_env_filename,
)
env = os.environ.copy()
env.update(
{
"KNF_STORAGE": "demo",
"XDG_CONFIG_HOME": str(config_home),
}
)
result = subprocess.run(
[
sys.executable,
"-c",
(
"from kneiff.config import KNEIFF_RC, KneiffConfig; "
"KNEIFF_RC.bootstrap(); "
"print(KneiffConfig().storage.root)"
),
],
capture_output=True,
text=True,
check=False,
env=env,
)
assert result.returncode == 0, result.stdout + result.stderr
assert result.stdout.strip() == str(storage_root.resolve())
def test_cli_rejects_unknown_log_level() -> None:
runner = CliRunner()
result = invoke_cli(
runner,
["--log-level", "verbose-ish", "dataset", "plan"],
)
assert result.exit_code == 2
assert "Unknown logging level: verbose-ish" in result.output
def test_comfy_showcase_requires_storage(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
monkeypatch.delenv("KNF_STORAGE", raising=False)
monkeypatch.delenv(KNF_APPRC_TOML_ENV_KEY, raising=False)
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config-home"))
prompts_path = tmp_path / "prompts.yaml"
prompts_path.write_text(
"""
version: 1
defaults:
seed: 123
prompts:
- id: first
uses: [showcase]
captions:
nlg:
- prose prompt
pony:
- pony tags
""",
encoding="utf-8",
)
runner = CliRunner()
result = invoke_cli(
runner,
[
"comfy",
"showcase",
"-w",
"pony",
"-p",
str(prompts_path),
],
)
assert result.exit_code != 0
assert "KNF_STORAGE is required" in result.output
def test_comfy_upscale_uses_storage_local_env(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
isolated_cli_storage: Path,
) -> None:
import kneiff.infer.comfy.upscale as upscale_module
from kneiff.infer.comfy.upscale import (
ComfyUpscaleRequest,
ComfyUpscaleResult,
)
(isolated_cli_storage / ".env.apprc-storage").write_text(
(
f'{COMFY_UPSCALE_MODEL_ENV_KEY}="local-upscaler.safetensors"\n'
f'{COMFY_UPSCALE_LORA_ENV_KEY}="missing.safetensors"\n'
f'{COMFY_UPSCALE_LORA_TOKEN_ENV_KEY}="env_token"\n'
),
encoding="utf-8",
)
monkeypatch.delenv(COMFY_UPSCALE_MODEL_ENV_KEY, raising=False)
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
requests: list[ComfyUpscaleRequest] = []
def fake_run_upscale(
request: ComfyUpscaleRequest,
**kwargs: object,
) -> tuple[ComfyUpscaleResult, ...]:
requests.append(request)
return ()
monkeypatch.setattr(upscale_module, "run_upscale", fake_run_upscale)
_install_fake_comfy_model_client(monkeypatch)
runner = CliRunner()
result = invoke_cli(runner, ["comfy", "upscale", str(image_path), "--fast"])
assert result.exit_code == 0, result.output
assert requests[0].upscale_model == "local-upscaler.safetensors"
assert requests[0].fast is True
assert requests[0].lora is None
def test_comfy_upscale_uses_one_aggregate_prompt_progress_task(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
import kneiff.infer.comfy.upscale as upscale_module
from kneiff.infer.comfy.upscale import (
ComfyUpscaleRequest,
ComfyUpscaleResult,
ProgressCallback as ResultCallback,
)
from kneiff.progress import ProgressCallback as WorkProgressCallback
first = tmp_path / "first.png"
second = tmp_path / "second.png"
first.write_bytes(b"image")
second.write_bytes(b"image")
reporters: list[_CapturedShowcaseProgress] = []
def fake_run_upscale(
request: ComfyUpscaleRequest,
*,
progress: ResultCallback | None = None,
work_progress: WorkProgressCallback | None = None,
**kwargs: object,
) -> tuple[ComfyUpscaleResult, ...]:
del kwargs
results: list[ComfyUpscaleResult] = []
for index, path in enumerate(request.inputs, start=1):
result = ComfyUpscaleResult(
input_path=path,
prompt_id=f"prompt-{index}",
filename_prefix=f"output-{index}",
history={},
)
results.append(result)
if work_progress is not None:
work_progress(
ProgressUpdate(
f"Image {index}/2 · {path.name}",
advance=1,
)
)
if progress is not None:
progress(result)
return tuple(results)
monkeypatch.setattr(upscale_module, "run_upscale", fake_run_upscale)
monkeypatch.setattr(
cli_comfy,
"CliProgress",
_capturing_showcase_progress_factory(reporters),
)
_install_fake_comfy_model_client(monkeypatch)
result = invoke_cli(
CliRunner(),
[
"comfy",
"upscale",
str(first),
str(second),
"--fast",
"--model",
"cli-upscaler.safetensors",
],
)
assert result.exit_code == 0, result.output
assert len(reporters) == 1
assert reporters[0].title == "ComfyUI upscale"
assert reporters[0].total == 2
assert reporters[0].advances == [
"Image 1/2 · first.png",
"Image 2/2 · second.png",
]
assert f"{first}: output-1" in result.output
assert f"{second}: output-2" in result.output
def test_dataset_aspects_streams_pruned_paths_with_dynamic_progress(
monkeypatch: pytest.MonkeyPatch,
) -> None:
import kneiff.training.lora.simpletuner_resolution_report as aspect_report
reporters: list[_CapturedShowcaseProgress] = []
progress_descriptions = [
"Validated dataset paths",
"Checking manifest image paths 1/2",
"Built 2 planned geometry variants",
"Read source dimensions 1/1",
"Built SimpleTuner artifacts",
"Analyzing backend fullbody 1/1",
]
def fake_dataset_plan(*_args: object) -> cli_dataset.DatasetSyncPlan:
return cast(
cli_dataset.DatasetSyncPlan,
SimpleNamespace(dataset_name="ready"),
)
def fake_build_aspects_analysis(
plan: cli_dataset.DatasetSyncPlan,
*,
process_count: int,
progress: _CapturedShowcaseProgress,
) -> aspect_report.SimpleTunerAspectAnalysis:
assert plan.dataset_name == "ready"
assert process_count == 2
progress.step("Validated dataset paths")
progress.apply(
ProgressUpdate(
"Checking manifest image paths 1/2",
advance=1,
additional_total=2,
)
)
progress.apply(
ProgressUpdate(
"Built 2 planned geometry variants",
advance=1,
additional_total=1,
)
)
progress.apply(
ProgressUpdate(
"Read source dimensions 1/1",
advance=1,
additional_total=1,
)
)
progress.step("Built SimpleTuner artifacts")
progress.apply(
ProgressUpdate(
"Analyzing backend fullbody 1/1",
advance=1,
additional_total=1,
)
)
return cast(aspect_report.SimpleTunerAspectAnalysis, object())
monkeypatch.setattr(cli_dataset, "_dataset_plan_from_cli", fake_dataset_plan)
monkeypatch.setattr(
cli_dataset,
"_build_dataset_aspects_analysis",
fake_build_aspects_analysis,
)
monkeypatch.setattr(
aspect_report,
"format_simpletuner_aspect_analysis",
lambda _analysis: "Aspect report",
)
monkeypatch.setattr(
aspect_report,
"pruned_aspect_bucket_source_paths",
lambda _analysis: ("SOURCE/0-FULLBODY/scene.png",),
)
monkeypatch.setattr(
cli_dataset,
"CliProgress",
_capturing_showcase_progress_factory(reporters),
)
result = invoke_cli(
CliRunner(),
["dataset", "aspects", "ready", "--processes", "2"],
)
assert result.exit_code == 0, result.output
assert result.stdout == "SOURCE/0-FULLBODY/scene.png\n"
assert "Aspect report" in result.stderr
assert len(reporters) == 1
assert reporters[0].title == "dataset aspects: ready"
assert reporters[0].total == 7
assert reporters[0].advances == progress_descriptions
assert reporters[0].exit_error is None
def test_comfy_outpaint_consumes_dataset_aspect_source_stream(
isolated_cli_project: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
from PIL import Image
import kneiff.infer.comfy.outpaint as outpaint_module
source_path = isolated_cli_project / "SOURCE" / "0-FULLBODY" / "scene.png"
source_path.parent.mkdir(parents=True, exist_ok=True)
Image.new("RGB", (640, 960), color="white").save(source_path)
requests: list[outpaint_module.ComfyOutpaintRequest] = []
def fake_run_outpaint(
request: outpaint_module.ComfyOutpaintRequest,
**_kwargs: object,
) -> tuple[outpaint_module.ComfyOutpaintResult, ...]:
requests.append(request)
return ()
monkeypatch.setattr(outpaint_module, "run_outpaint", fake_run_outpaint)
result = invoke_cli(
CliRunner(),
["comfy", "outpaint", "-w", "willy"],
input="SOURCE/0-FULLBODY/scene.png\n",
)
assert result.exit_code == 0, result.output
assert requests[0].inputs == (source_path.resolve(),)
assert requests[0].square_fraction == 0.25
def test_comfy_outpaint_safe_border_writes_pipeable_local_outputs_without_comfyui(
isolated_cli_project: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
from PIL import Image
source_path = isolated_cli_project / "SOURCE" / "0-FULLBODY" / "scene.png"
source_path.parent.mkdir(parents=True, exist_ok=True)
Image.new("RGB", (601, 800), color="white").save(source_path)
output_root = isolated_cli_project / "safe-border-output"
monkeypatch.setenv(COMFY_OUTPUT_DIR_ENV_KEY, str(output_root))
def fail_comfy_client(*_args: object, **_kwargs: object) -> NoReturn:
raise AssertionError("--safe-border must not construct a ComfyUI client")
monkeypatch.setattr(cli_comfy, "ComfyUiClient", fail_comfy_client)
result = invoke_cli(
CliRunner(),
["comfy", "outpaint", "--safe-border"],
input="SOURCE/0-FULLBODY/scene.png\n",
)
assert result.exit_code == 0, result.output
written_paths = tuple(Path(line) for line in result.stdout.splitlines())
assert len(written_paths) == 1
assert written_paths[0].parent.parent == output_root
assert written_paths[0].parent.name.count("-") == 2
assert "-safe-border-1" in written_paths[0].name
assert written_paths[0].is_file()
assert "Wrote 1 safe-border result" in result.stderr
explicit_result = invoke_cli(
CliRunner(),
["comfy", "outpaint", str(source_path), "--safe-border"],
input="",
)
assert explicit_result.exit_code == 0, explicit_result.output
explicit_path = Path(explicit_result.stdout.strip())
assert explicit_path.is_file()
assert explicit_path.parent.parent == output_root
def test_comfy_outpaint_safe_border_from_pruned_aspects_needs_no_workflow(
isolated_cli_project: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
from PIL import Image
import kneiff.datasets.export.aspect_analysis as aspect_analysis
import kneiff.infer.comfy.outpaint as outpaint_module
import kneiff.training.lora.simpletuner_resolution_report as aspect_report
source_path = isolated_cli_project / "SOURCE" / "0-FULLBODY" / "scene.png"
source_path.parent.mkdir(parents=True, exist_ok=True)
Image.new("RGB", (640, 960), color="white").save(source_path)
config_path = isolated_cli_project / "configs" / "ANIMA.knf.yaml"
config_path.parent.mkdir(parents=True, exist_ok=True)
config_path.write_text(
'mappings:\n fullbody:\n - "0-FULLBODY"\n',
encoding="utf-8",
)
output_root = isolated_cli_project / "safe-border-output"
monkeypatch.setenv(COMFY_OUTPUT_DIR_ENV_KEY, str(output_root))
requests: list[outpaint_module.SafeBorderRequest] = []
def fake_build_aspect_analysis(
plan: object,
*,
process_count: int,
progress_callback: object,
) -> object:
assert getattr(plan, "dataset_name") == "ANIMA"
assert process_count == 1
assert callable(progress_callback)
return object()
def fake_run_safe_border(
request: outpaint_module.SafeBorderRequest,
**_kwargs: object,
) -> tuple[outpaint_module.SafeBorderResult, ...]:
requests.append(request)
return ()
monkeypatch.setattr(
aspect_analysis,
"build_dataset_aspect_analysis",
fake_build_aspect_analysis,
)
monkeypatch.setattr(
aspect_report,
"pruned_aspect_bucket_source_paths",
lambda _analysis: ("SOURCE/0-FULLBODY/scene.png",),
)
monkeypatch.setattr(outpaint_module, "run_safe_border", fake_run_safe_border)
result = invoke_cli(
CliRunner(),
[
"comfy",
"outpaint",
"-a",
"--aspects-config",
"ANIMA",
"--safe-border",
"--square-fraction",
"0.5",
],
input="",
)
assert result.exit_code == 0, result.output
assert requests[0].inputs == (source_path.resolve(),)
assert requests[0].output_dir == output_root.resolve()
assert requests[0].square_fraction == 0.5
@pytest.mark.parametrize(
"inference_option",
[
("--workflow", "willy"),
("--url", "http://comfy.test"),
("--seed", "42"),
],
)
def test_comfy_outpaint_safe_border_rejects_inference_only_options(
isolated_cli_project: Path,
inference_option: tuple[str, str],
) -> None:
from PIL import Image
source_path = isolated_cli_project / "SOURCE" / "0-FULLBODY" / "scene.png"
source_path.parent.mkdir(parents=True, exist_ok=True)
Image.new("RGB", (640, 960), color="white").save(source_path)
result = invoke_cli(
CliRunner(),
[
"comfy",
"outpaint",
str(source_path),
"--safe-border",
*inference_option,
],
input="",
)
assert result.exit_code != 0
normalized_output = " ".join(result.output.replace("│", " ").split())
assert "--safe-border cannot be combined" in normalized_output
def test_comfy_outpaint_safe_border_requires_configured_local_output_root(
isolated_cli_project: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
from PIL import Image
source_path = isolated_cli_project / "SOURCE" / "0-FULLBODY" / "scene.png"
source_path.parent.mkdir(parents=True, exist_ok=True)
Image.new("RGB", (640, 960), color="white").save(source_path)
monkeypatch.setenv(COMFY_OUTPUT_DIR_ENV_KEY, "")
result = invoke_cli(
CliRunner(),
["comfy", "outpaint", str(source_path), "--safe-border"],
input="",
)
assert result.exit_code != 0
assert f"Set {COMFY_OUTPUT_DIR_ENV_KEY} to use --safe-border" in result.output
def test_comfy_outpaint_interrupt_exits_after_requesting_cancellation(
isolated_cli_project: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
from PIL import Image
import kneiff.infer.comfy.outpaint as outpaint_module
source_path = isolated_cli_project / "SOURCE" / "0-FULLBODY" / "scene.png"
source_path.parent.mkdir(parents=True, exist_ok=True)
Image.new("RGB", (640, 960), color="white").save(source_path)
def interrupted_run_outpaint(_request: object, **_kwargs: object) -> None:
raise KeyboardInterrupt
monkeypatch.setattr(outpaint_module, "run_outpaint", interrupted_run_outpaint)
result = invoke_cli(
CliRunner(),
["comfy", "outpaint", str(source_path), "-w", "willy"],
input="",
)
assert result.exit_code == 130, result.output
assert "requested cancellation of its ComfyUI jobs" in result.stderr
def test_comfy_outpaint_from_pruned_aspects_resolves_and_outpaints_sources(
isolated_cli_project: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
from PIL import Image
import kneiff.datasets.export.aspect_analysis as aspect_analysis
import kneiff.infer.comfy.outpaint as outpaint_module
import kneiff.training.lora.simpletuner_resolution_report as aspect_report
source_path = isolated_cli_project / "SOURCE" / "0-FULLBODY" / "scene.png"
source_path.parent.mkdir(parents=True, exist_ok=True)
Image.new("RGB", (640, 960), color="white").save(source_path)
config_path = isolated_cli_project / "configs" / "ANIMA.knf.yaml"
config_path.parent.mkdir(parents=True, exist_ok=True)
config_path.write_text(
'mappings:\n fullbody:\n - "0-FULLBODY"\n',
encoding="utf-8",
)
requests: list[outpaint_module.ComfyOutpaintRequest] = []
def fake_build_aspect_analysis(
plan: object,
*,
process_count: int,
progress_callback: object,
) -> object:
assert getattr(plan, "dataset_name") == "ANIMA"
assert process_count == 1
assert callable(progress_callback)
return object()
def fake_run_outpaint(
request: outpaint_module.ComfyOutpaintRequest,
**_kwargs: object,
) -> tuple[outpaint_module.ComfyOutpaintResult, ...]:
requests.append(request)
return ()
monkeypatch.setattr(
aspect_analysis,
"build_dataset_aspect_analysis",
fake_build_aspect_analysis,
)
monkeypatch.setattr(
aspect_report,
"pruned_aspect_bucket_source_paths",
lambda _analysis: ("SOURCE/0-FULLBODY/scene.png",),
)
monkeypatch.setattr(outpaint_module, "run_outpaint", fake_run_outpaint)
result = invoke_cli(
CliRunner(),
[
"comfy",
"outpaint",
"-a",
"--aspects-config",
"ANIMA",
"-w",
"willy",
"--square-fraction",
"0.5",
],
input="",
)
assert result.exit_code == 0, result.output
assert "ANIMA: found 1 physically pruned source image(s)." in result.stderr
assert requests[0].inputs == (source_path.resolve(),)
assert requests[0].square_fraction == 0.5
def test_comfy_outpaint_from_pruned_aspects_empty_result_is_a_noop(
isolated_cli_project: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
import kneiff.datasets.export.aspect_analysis as aspect_analysis
import kneiff.training.lora.simpletuner_resolution_report as aspect_report
config_path = isolated_cli_project / "configs" / "ANIMA.knf.yaml"
config_path.parent.mkdir(parents=True, exist_ok=True)
config_path.write_text(
'mappings:\n fullbody:\n - "0-FULLBODY"\n',
encoding="utf-8",
)
monkeypatch.setattr(
aspect_analysis,
"build_dataset_aspect_analysis",
lambda *_args, **_kwargs: object(),
)
monkeypatch.setattr(
aspect_report,
"pruned_aspect_bucket_source_paths",
lambda _analysis: (),
)
result = invoke_cli(
CliRunner(),
["comfy", "outpaint", "-a"],
input="",
)
assert result.exit_code == 0, result.output
assert "No source images are physically pruned" in result.stderr
def test_comfy_outpaint_rejects_pruned_aspects_with_other_input_modes(
isolated_cli_project: Path,
) -> None:
from PIL import Image
source_path = isolated_cli_project / "SOURCE" / "0-FULLBODY" / "scene.png"
source_path.parent.mkdir(parents=True, exist_ok=True)
Image.new("RGB", (640, 960), color="white").save(source_path)
config_path = isolated_cli_project / "configs" / "ANIMA.knf.yaml"
config_path.parent.mkdir(parents=True, exist_ok=True)
config_path.write_text(
'mappings:\n fullbody:\n - "0-FULLBODY"\n',
encoding="utf-8",
)
result = invoke_cli(
CliRunner(),
["comfy", "outpaint", "-a", str(source_path), "-w", "willy"],
input="",
)
assert result.exit_code != 0
normalized_output = " ".join(result.output.replace("│", " ").split())
assert "cannot be combined with positional image inputs" in normalized_output
piped_result = invoke_cli(
CliRunner(),
["comfy", "outpaint", "-a", "-w", "willy"],
input="SOURCE/0-FULLBODY/scene.png\n",
)
assert piped_result.exit_code != 0
normalized_piped_output = " ".join(piped_result.output.replace("│", " ").split())
assert "cannot be combined with positional image inputs" in normalized_piped_output
def test_comfy_outpaint_empty_source_stream_is_a_successful_noop(
isolated_cli_project: Path,
) -> None:
del isolated_cli_project
result = invoke_cli(
CliRunner(),
["comfy", "outpaint"],
input="",
)
assert result.exit_code == 0, result.output
assert "No outpaint source images received on stdin" in result.stderr
def test_comfy_outpaint_rejects_positional_images_and_source_stream(
isolated_cli_project: Path,
) -> None:
from PIL import Image
source_path = isolated_cli_project / "SOURCE" / "0-FULLBODY" / "scene.png"
source_path.parent.mkdir(parents=True, exist_ok=True)
Image.new("RGB", (640, 960), color="white").save(source_path)
result = invoke_cli(
CliRunner(),
["comfy", "outpaint", str(source_path), "-w", "willy"],
input="SOURCE/0-FULLBODY/scene.png\n",
)
assert result.exit_code != 0
normalized_output = " ".join(result.output.replace("│", " ").split())
assert (
"either positional image files or piped SOURCE/... paths" in normalized_output
)
def test_comfy_upscale_requires_storage(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
monkeypatch.delenv("KNF_STORAGE", raising=False)
monkeypatch.delenv(KNF_APPRC_TOML_ENV_KEY, raising=False)
monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "config-home"))
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
runner = CliRunner()
result = invoke_cli(
runner,
[
"comfy",
"upscale",
str(image_path),
"--model",
"cli-upscaler.safetensors",
"--fast",
],
)
assert result.exit_code != 0
assert "KNF_STORAGE is required" in result.output
def test_comfy_upscale_quality_uses_brain_off_defaults(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
import kneiff.infer.comfy.upscale as upscale_module
from kneiff.infer.comfy.upscale import (
ComfyUpscaleRequest,
ComfyUpscaleResult,
)
for env_key in (
COMFY_UPSCALE_MODEL_ENV_KEY,
COMFY_UPSCALE_REFINER_UNET_ENV_KEY,
COMFY_UPSCALE_REFINER_CLIP_ENV_KEY,
COMFY_UPSCALE_REFINER_CLIP_TYPE_ENV_KEY,
COMFY_UPSCALE_REFINER_VAE_ENV_KEY,
COMFY_UPSCALE_LORA_ENV_KEY,
COMFY_UPSCALE_LORA_TOKEN_ENV_KEY,
COMFY_UPSCALE_LORA_STRENGTH_ENV_KEY,
COMFY_UPSCALE_DENOISE_BASE_ENV_KEY,
):
monkeypatch.delenv(env_key, raising=False)
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
requests: list[ComfyUpscaleRequest] = []
def fake_run_upscale(
request: ComfyUpscaleRequest,
**kwargs: object,
) -> tuple[ComfyUpscaleResult, ...]:
requests.append(request)
return ()
monkeypatch.setattr(upscale_module, "run_upscale", fake_run_upscale)
_install_fake_comfy_model_client(monkeypatch)
runner = CliRunner()
result = invoke_cli(
runner, ["--skip-dotenv-layers", "comfy", "upscale", str(image_path)]
)
assert result.exit_code == 0, result.output
assert requests[0].upscale_model == DEFAULT_COMFY_UPSCALE_MODEL
assert requests[0].quality_workflow == "krea2"
assert requests[0].refiner is not None
assert requests[0].refiner.unet == DEFAULT_COMFY_UPSCALE_REFINER_UNET
assert requests[0].refiner.clip == DEFAULT_COMFY_UPSCALE_REFINER_CLIP
def test_comfy_upscale_z_image_uses_legacy_defaults(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
import kneiff.infer.comfy.upscale as upscale_module
from kneiff.infer.comfy.upscale import (
ComfyUpscaleRequest,
ComfyUpscaleResult,
)
for env_key in (
COMFY_UPSCALE_MODEL_ENV_KEY,
COMFY_UPSCALE_REFINER_UNET_ENV_KEY,
COMFY_UPSCALE_REFINER_CLIP_ENV_KEY,
COMFY_UPSCALE_REFINER_CLIP_TYPE_ENV_KEY,
COMFY_UPSCALE_REFINER_VAE_ENV_KEY,
COMFY_UPSCALE_LORA_ENV_KEY,
COMFY_UPSCALE_LORA_TOKEN_ENV_KEY,
COMFY_UPSCALE_LORA_STRENGTH_ENV_KEY,
COMFY_UPSCALE_DENOISE_BASE_ENV_KEY,
):
monkeypatch.delenv(env_key, raising=False)
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
requests: list[ComfyUpscaleRequest] = []
def fake_run_upscale(
request: ComfyUpscaleRequest,
**kwargs: object,
) -> tuple[ComfyUpscaleResult, ...]:
requests.append(request)
return ()
monkeypatch.setattr(upscale_module, "run_upscale", fake_run_upscale)
_install_fake_comfy_model_client(monkeypatch)
runner = CliRunner()
result = invoke_cli(
runner,
["--skip-dotenv-layers", "comfy", "upscale", str(image_path), "-z"],
)
assert result.exit_code == 0, result.output
assert requests[0].quality_workflow == "z-image"
assert requests[0].refiner is not None
assert requests[0].refiner.unet == LEGACY_COMFY_UPSCALE_Z_IMAGE_REFINER_UNET
assert requests[0].refiner.clip == LEGACY_COMFY_UPSCALE_Z_IMAGE_REFINER_CLIP
assert requests[0].refiner.clip_type == (
LEGACY_COMFY_UPSCALE_Z_IMAGE_REFINER_CLIP_TYPE
)
assert requests[0].refiner.vae == LEGACY_COMFY_UPSCALE_Z_IMAGE_REFINER_VAE
def test_comfy_upscale_quality_rejects_unavailable_default_non_interactive(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
for env_key in (
COMFY_UPSCALE_MODEL_ENV_KEY,
COMFY_UPSCALE_REFINER_UNET_ENV_KEY,
COMFY_UPSCALE_REFINER_CLIP_ENV_KEY,
COMFY_UPSCALE_REFINER_CLIP_TYPE_ENV_KEY,
COMFY_UPSCALE_REFINER_VAE_ENV_KEY,
COMFY_UPSCALE_LORA_ENV_KEY,
COMFY_UPSCALE_LORA_TOKEN_ENV_KEY,
COMFY_UPSCALE_LORA_STRENGTH_ENV_KEY,
COMFY_UPSCALE_DENOISE_BASE_ENV_KEY,
):
monkeypatch.delenv(env_key, raising=False)
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
options = dict(_DEFAULT_COMFY_INPUT_OPTIONS)
options[("UNETLoader", "unet_name")] = ("other-unet.safetensors",)
_install_fake_comfy_model_client(monkeypatch, options=options)
runner = CliRunner()
result = invoke_cli(
runner, ["--skip-dotenv-layers", "comfy", "upscale", str(image_path)]
)
assert result.exit_code != 0
assert COMFY_UPSCALE_REFINER_UNET_ENV_KEY in result.output
assert DEFAULT_COMFY_UPSCALE_REFINER_UNET in result.output
assert "--fast" in result.output
def test_comfy_upscale_quality_cli_passes_refiner_and_lora(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
import kneiff.infer.comfy.upscale as upscale_module
from kneiff.infer.comfy.upscale import (
ComfyUpscaleRequest,
ComfyUpscaleResult,
)
models_dir = tmp_path / "models"
lora_path = models_dir / "models" / "loras" / "character.safetensors"
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(b"lora")
env_lora_path = models_dir / "models" / "loras" / "env-character.safetensors"
env_lora_path.write_bytes(b"lora")
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
monkeypatch.setenv(COMFY_UPSCALE_MODEL_ENV_KEY, "4x-test.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_REFINER_UNET_ENV_KEY, "z-image.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_REFINER_CLIP_ENV_KEY, "qwen.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_LORA_ENV_KEY, "env-character.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_LORA_TOKEN_ENV_KEY, "env_token")
monkeypatch.setenv(COMFY_UPSCALE_LORA_STRENGTH_ENV_KEY, "0.9")
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
requests: list[ComfyUpscaleRequest] = []
def fake_run_upscale(
request: ComfyUpscaleRequest,
**kwargs: object,
) -> tuple[ComfyUpscaleResult, ...]:
requests.append(request)
return ()
monkeypatch.setattr(upscale_module, "run_upscale", fake_run_upscale)
_install_fake_comfy_model_client(monkeypatch)
runner = CliRunner()
result = invoke_cli(
runner,
[
"comfy",
"upscale",
str(image_path),
"--style",
"flat",
"--lora",
"character.safetensors",
"--token",
"char_token",
"--lora-strength",
"0.4",
"--seed",
"123",
],
)
assert result.exit_code == 0, result.output
assert requests[0].fast is False
assert requests[0].style == "flat"
assert requests[0].refiner is not None
assert requests[0].refiner.unet == "z-image.safetensors"
assert requests[0].lora is not None
assert requests[0].lora.lora_name == "character.safetensors"
assert requests[0].lora.activation_token == "char_token"
assert requests[0].lora.strength == 0.4
assert requests[0].seed_root == 123
def test_comfy_upscale_quality_uses_configured_lora_path_chain(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
import kneiff.infer.comfy.upscale as upscale_module
from kneiff.infer.comfy.upscale import (
ComfyUpscaleRequest,
ComfyUpscaleResult,
)
models_dir = tmp_path / "models"
lora_path = models_dir / "models" / "loras" / "5th-ZI-1" / "2400.safetensors"
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(b"lora")
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
monkeypatch.setenv(COMFY_LORAS_DIR_1_ENV_KEY, "5th-ZI-1")
monkeypatch.setenv(COMFY_UPSCALE_LORA_ENV_KEY, "2400.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_LORA_TOKEN_ENV_KEY, "env_token")
monkeypatch.setenv(COMFY_UPSCALE_LORA_STRENGTH_ENV_KEY, "0.8")
monkeypatch.setenv(COMFY_UPSCALE_DENOISE_BASE_ENV_KEY, "0.18")
monkeypatch.setenv(COMFY_UPSCALE_MODEL_ENV_KEY, "4x-test.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_REFINER_UNET_ENV_KEY, "z-image.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_REFINER_CLIP_ENV_KEY, "qwen.safetensors")
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
requests: list[ComfyUpscaleRequest] = []
def fake_run_upscale(
request: ComfyUpscaleRequest,
**kwargs: object,
) -> tuple[ComfyUpscaleResult, ...]:
requests.append(request)
return ()
monkeypatch.setattr(upscale_module, "run_upscale", fake_run_upscale)
_install_fake_comfy_model_client(monkeypatch)
runner = CliRunner()
result = invoke_cli(runner, ["comfy", "upscale", str(image_path), "-d", "0.19"])
assert result.exit_code == 0, result.output
assert requests[0].lora is not None
assert requests[0].lora.lora_name == "5th-ZI-1/2400.safetensors"
assert requests[0].lora.activation_token == "env_token"
assert requests[0].lora.strength == 0.8
assert requests[0].denoise_base == 0.19
def test_comfy_upscale_quality_allows_configured_lora_without_token(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
import kneiff.infer.comfy.upscale as upscale_module
from kneiff.infer.comfy.upscale import (
ComfyUpscaleRequest,
ComfyUpscaleResult,
)
models_dir = tmp_path / "models"
lora_path = models_dir / "models" / "loras" / "character.safetensors"
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(b"lora")
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
monkeypatch.setenv(COMFY_UPSCALE_LORA_ENV_KEY, "character.safetensors")
monkeypatch.delenv(COMFY_UPSCALE_LORA_TOKEN_ENV_KEY, raising=False)
monkeypatch.setenv(COMFY_UPSCALE_MODEL_ENV_KEY, "4x-test.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_REFINER_UNET_ENV_KEY, "z-image.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_REFINER_CLIP_ENV_KEY, "qwen.safetensors")
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
requests: list[ComfyUpscaleRequest] = []
def fake_run_upscale(
request: ComfyUpscaleRequest,
**kwargs: object,
) -> tuple[ComfyUpscaleResult, ...]:
requests.append(request)
return ()
monkeypatch.setattr(upscale_module, "run_upscale", fake_run_upscale)
_install_fake_comfy_model_client(monkeypatch)
runner = CliRunner()
result = invoke_cli(
runner, ["--skip-dotenv-layers", "comfy", "upscale", str(image_path)]
)
assert result.exit_code == 0, result.output
assert requests[0].lora is not None
assert requests[0].lora.activation_token == ""
def test_comfy_upscale_cli_requires_token_with_lora(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
models_dir = tmp_path / "models"
lora_path = models_dir / "models" / "loras" / "character.safetensors"
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(b"lora")
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
monkeypatch.setenv(COMFY_UPSCALE_MODEL_ENV_KEY, "4x-test.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_REFINER_UNET_ENV_KEY, "z-image.safetensors")
monkeypatch.setenv(COMFY_UPSCALE_REFINER_CLIP_ENV_KEY, "qwen.safetensors")
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
_install_fake_comfy_model_client(monkeypatch)
runner = CliRunner()
result = invoke_cli(
runner,
[
"comfy",
"upscale",
str(image_path),
"--lora",
"character.safetensors",
],
)
assert result.exit_code != 0
assert "--token" in result.output
def test_comfy_upscale_fast_rejects_explicit_quality_options(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
_install_fake_comfy_model_client(monkeypatch)
runner = CliRunner()
result = invoke_cli(
runner,
[
"comfy",
"upscale",
str(image_path),
"--fast",
"--lora",
"character.safetensors",
],
)
assert result.exit_code != 0
assert "--fast" in result.output
assert "LoRA options" in result.output
def test_comfy_upscale_fast_rejects_z_image_workflow(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
runner = CliRunner()
result = invoke_cli(
runner,
[
"comfy",
"upscale",
str(image_path),
"--fast",
"-z",
],
)
assert result.exit_code != 0
assert "--z-image" in result.output
assert "--fast" in result.output
def test_comfy_upscale_explicit_unavailable_model_is_strict(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
_install_fake_comfy_model_client(monkeypatch)
monkeypatch.setattr(cli_comfy, "interactive_available", lambda console: True)
runner = CliRunner()
result = invoke_cli(
runner,
[
"comfy",
"upscale",
str(image_path),
"--model",
"missing-upscaler.safetensors",
"--fast",
],
)
assert result.exit_code != 0
assert "missing-upscaler.safetensors" in result.output
assert "Requested upscale model" in result.output
assert "Selected upscale model" not in result.output
def test_comfy_upscale_interactive_model_picker_is_current_run_only(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
import kneiff.infer.comfy.upscale as upscale_module
from kneiff.infer.comfy.upscale import (
ComfyUpscaleRequest,
ComfyUpscaleResult,
)
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
monkeypatch.delenv(COMFY_UPSCALE_MODEL_ENV_KEY, raising=False)
requests: list[ComfyUpscaleRequest] = []
options = dict(_DEFAULT_COMFY_INPUT_OPTIONS)
options[("UpscaleModelLoader", "model_name")] = (
"first-upscaler.safetensors",
"chosen-upscaler.safetensors",
)
actions = iter(("down", "select"))
def fake_run_upscale(
request: ComfyUpscaleRequest,
**kwargs: object,
) -> tuple[ComfyUpscaleResult, ...]:
requests.append(request)
return ()
monkeypatch.setattr(upscale_module, "run_upscale", fake_run_upscale)
_install_fake_comfy_model_client(monkeypatch, options=options)
monkeypatch.setattr(cli_comfy, "interactive_available", lambda console: True)
monkeypatch.setattr(cli_comfy, "read_picker_action", lambda: next(actions))
runner = CliRunner()
result = invoke_cli(runner, ["comfy", "upscale", str(image_path), "--fast"])
assert result.exit_code == 0, result.output
assert requests[0].upscale_model == "chosen-upscaler.safetensors"
assert KneiffConfig().comfy.upscale_model == DEFAULT_COMFY_UPSCALE_MODEL
assert "Selected upscale model: chosen-upscaler.safetensors" in result.output
def test_comfy_upscale_interactive_lora_token_prompt(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
import kneiff.infer.comfy.upscale as upscale_module
from kneiff.infer.comfy.upscale import (
ComfyUpscaleRequest,
ComfyUpscaleResult,
)
models_dir = tmp_path / "models"
lora_path = models_dir / "models" / "loras" / "character.safetensors"
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(b"lora")
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
for env_key in (
COMFY_UPSCALE_MODEL_ENV_KEY,
COMFY_UPSCALE_REFINER_UNET_ENV_KEY,
COMFY_UPSCALE_REFINER_CLIP_ENV_KEY,
COMFY_UPSCALE_REFINER_CLIP_TYPE_ENV_KEY,
COMFY_UPSCALE_REFINER_VAE_ENV_KEY,
COMFY_UPSCALE_LORA_ENV_KEY,
COMFY_UPSCALE_LORA_TOKEN_ENV_KEY,
COMFY_UPSCALE_LORA_STRENGTH_ENV_KEY,
COMFY_UPSCALE_DENOISE_BASE_ENV_KEY,
):
monkeypatch.delenv(env_key, raising=False)
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
requests: list[ComfyUpscaleRequest] = []
def fake_run_upscale(
request: ComfyUpscaleRequest,
**kwargs: object,
) -> tuple[ComfyUpscaleResult, ...]:
requests.append(request)
return ()
monkeypatch.setattr(upscale_module, "run_upscale", fake_run_upscale)
_install_fake_comfy_model_client(monkeypatch)
monkeypatch.setattr(cli_comfy, "interactive_available", lambda console: True)
runner = CliRunner()
result = invoke_cli(
runner,
[
"--skip-dotenv-layers",
"comfy",
"upscale",
str(image_path),
"--lora",
"character.safetensors",
],
input="char_token\n",
)
assert result.exit_code == 0, result.output
assert requests[0].lora is not None
assert requests[0].lora.activation_token == "char_token"
def test_comfy_showcase_cli_uses_preset_prompt_field(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
import kneiff.infer.comfy.showcase as showcase_module
from kneiff.infer.comfy.showcase import (
ShowcaseRunRequest,
ShowcaseRunResult,
)
prompts_path = tmp_path / "prompts.yaml"
prompts_path.write_text(
"""
version: 1
defaults:
seed: 123
prompts:
- id: first
uses: [showcase]
captions:
nlg:
- prose prompt
pony:
- pony tags
noob:
- noob tags
""",
encoding="utf-8",
)
requests: list[ShowcaseRunRequest] = []
def fake_run_showcase(
request: ShowcaseRunRequest,
**kwargs: object,
) -> ShowcaseRunResult:
requests.append(request)
return ShowcaseRunResult(results=())
monkeypatch.setattr(showcase_module, "run_showcase", fake_run_showcase)
runner = CliRunner()
result = invoke_cli(
runner,
[
"comfy",
"showcase",
"-w",
"pony",
"-p",
str(prompts_path),
],
)
assert result.exit_code == 0, result.output
assert requests[0].workflow_source.name == "showcase_pony.workflow.json"
assert requests[0].prompt_field == "pony"
assert requests[0].showcase_model == "pony"
assert [prompt.id for prompt in requests[0].prompt_catalog.prompts] == ["first"]
assert result.output.count("Generating 1 showcase image...") == 1
assert result.output.count("Showcase complete") == 1
result = invoke_cli(
runner,
[
"comfy",
"showcase",
"-w",
"noob-willy",
"-p",
str(prompts_path),
],
)
assert result.exit_code == 0, result.output
assert requests[1].workflow_source.name == "showcase_noob-willy.workflow.json"
assert requests[1].prompt_field == "noob"
assert requests[1].showcase_model == "noob"
def test_comfy_showcase_progress_stops_incomplete_after_generation_failure(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
import kneiff.infer.comfy.showcase as showcase_module
from kneiff.infer.comfy.showcase import (
ShowcasePromptResult,
ShowcaseRunRequest,
)
from kneiff.infer.comfy.showcase_runner import select_showcase_prompts
prompts_path = tmp_path / "prompts.yaml"
prompts_path.write_text(
"""
version: 1
defaults:
seed: 123
prompts:
- id: first
uses: [showcase]
captions:
nlg:
- prose prompt
""",
encoding="utf-8",
)
reporters: list[_CapturedShowcaseProgress] = []
def fail_run_showcase(
request: ShowcaseRunRequest,
*,
progress: Callable[[ShowcasePromptResult], None] | None = None,
) -> NoReturn:
prompts, _skipped = select_showcase_prompts(
request.prompt_catalog,
request.prompt_field,
)
prompt = prompts[0]
if progress is not None:
progress(
ShowcasePromptResult(
prompt=prompt,
prompt_id="queued-first",
filename_prefix="first",
files=(),
)
)
raise RuntimeError("generation broke")
monkeypatch.setattr(showcase_module, "run_showcase", fail_run_showcase)
monkeypatch.setattr(
cli_comfy,
"CliProgress",
_capturing_showcase_progress_factory(reporters),
)
result = invoke_cli(
CliRunner(),
["comfy", "showcase", "--workflow", "anima", "-p", str(prompts_path)],
)
assert result.exit_code == 1
assert reporters[0].total == 1
assert reporters[0].advances == ["first"]
assert reporters[0].exit_error is RuntimeError
assert "Showcase failed: generation broke" in result.output
assert "Showcase complete" not in result.output
def test_comfy_showcase_cli_infers_willy_noob_lora(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
isolated_cli_project: Path,
) -> None:
import kneiff.infer.comfy.showcase as showcase_module
from kneiff.infer.comfy.showcase import (
ShowcaseRunRequest,
ShowcaseRunResult,
)
models_dir = tmp_path / "comfyui-models"
lora_path = (
models_dir
/ "models"
/ "loras"
/ "_ladybird"
/ "Rook_Kaefer-v1_0-NOOB-Willy.comfyui.safetensors"
)
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(b"lora")
_write_noob_showcase_prompts(isolated_cli_project / "prompts.knf.yaml")
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
requests: list[ShowcaseRunRequest] = []
def fake_run_showcase(
request: ShowcaseRunRequest,
**kwargs: object,
) -> ShowcaseRunResult:
requests.append(request)
return ShowcaseRunResult(results=())
monkeypatch.setattr(showcase_module, "run_showcase", fake_run_showcase)
runner = CliRunner()
result = invoke_cli(
runner,
[
"comfy",
"showcase",
"--workflow",
"auto",
"--lora",
"_ladybird/Rook_Kaefer-v1_0-NOOB-Willy.comfyui.safetensors",
],
)
assert result.exit_code == 0, result.output
assert requests[0].workflow_source.name == "showcase_noob-willy.workflow.json"
catalog = requests[0].prompt_catalog
prompt_ids = [prompt.id for prompt in catalog.prompts]
assert prompt_ids[0] == "character_reference"
assert "aurora_portrait" in prompt_ids
assert catalog.overlay_prompt_count == 1
assert catalog.resolved_prompt_count == catalog.core_prompt_count + 1
assert requests[0].lora_name == (
"_ladybird/Rook_Kaefer-v1_0-NOOB-Willy.comfyui.safetensors"
)
assert requests[0].prompt_field == "noob"
assert requests[0].workflow_name == "noob-willy"
assert "Prompt sources" in result.output
assert "Workflow noob-willy" in result.output
assert "Outputs" in result.output
assert "Showcase complete" in result.output
def test_comfy_showcase_cli_prompts_for_workflow_when_omitted(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
import kneiff.infer.comfy.showcase as showcase_module
from kneiff.infer.comfy.showcase import (
ShowcaseRunRequest,
ShowcaseRunResult,
)
models_dir = tmp_path / "comfyui-models"
lora_path = (
models_dir
/ "models"
/ "loras"
/ "_ladybird"
/ "Rook_Kaefer-v1_0-NOOB-Willy.comfyui.safetensors"
)
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(b"lora")
prompts_path = tmp_path / "noob-prompts.yaml"
_write_noob_showcase_prompts(prompts_path)
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
monkeypatch.setattr(cli_comfy, "interactive_available", lambda console: True)
actions = iter(("down", "select"))
monkeypatch.setattr(cli_comfy, "read_picker_action", lambda: next(actions))
requests: list[ShowcaseRunRequest] = []
def fake_run_showcase(
request: ShowcaseRunRequest,
**kwargs: object,
) -> ShowcaseRunResult:
requests.append(request)
return ShowcaseRunResult(results=())
monkeypatch.setattr(showcase_module, "run_showcase", fake_run_showcase)
runner = CliRunner()
result = invoke_cli(
runner,
[
"comfy",
"showcase",
"--lora",
"_ladybird/Rook_Kaefer-v1_0-NOOB-Willy.comfyui.safetensors",
"--prompts",
str(prompts_path),
],
)
assert result.exit_code == 0, result.output
assert requests[0].workflow_source.name == "showcase_noob-willy.workflow.json"
assert requests[0].workflow_name == "noob-willy"
assert requests[0].prompt_field == "noob"
def test_comfy_showcase_cli_prompts_for_generic_noob_workflow(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
import kneiff.infer.comfy.showcase as showcase_module
from kneiff.infer.comfy.showcase import (
ShowcaseRunRequest,
ShowcaseRunResult,
)
models_dir = tmp_path / "comfyui-models"
lora_path = (
models_dir
/ "models"
/ "loras"
/ "_ladybird"
/ "Rook_Kaefer-v1_0-NOOB.comfyui.safetensors"
)
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(b"lora")
prompts_path = tmp_path / "noob-prompts.yaml"
_write_noob_showcase_prompts(prompts_path)
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
monkeypatch.setattr(cli_comfy, "interactive_available", lambda console: True)
actions = iter(("down", "select"))
monkeypatch.setattr(cli_comfy, "read_picker_action", lambda: next(actions))
requests: list[ShowcaseRunRequest] = []
def fake_run_showcase(
request: ShowcaseRunRequest,
**kwargs: object,
) -> ShowcaseRunResult:
requests.append(request)
return ShowcaseRunResult(results=())
monkeypatch.setattr(showcase_module, "run_showcase", fake_run_showcase)
runner = CliRunner()
result = invoke_cli(
runner,
[
"comfy",
"showcase",
"--workflow",
"auto",
"--lora",
"_ladybird/Rook_Kaefer-v1_0-NOOB.comfyui.safetensors",
"--prompts",
str(prompts_path),
],
)
assert result.exit_code == 0, result.output
assert requests[0].workflow_source.name == "showcase_noob-chenkin.workflow.json"
assert requests[0].workflow_name == "noob-chenkin"
assert "Selected workflow: noob-chenkin" in result.output
def test_comfy_showcase_cli_rejects_generic_noob_auto_non_interactive(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
models_dir = tmp_path / "comfyui-models"
lora_path = (
models_dir
/ "models"
/ "loras"
/ "_ladybird"
/ "Rook_Kaefer-v1_0-NOOB.comfyui.safetensors"
)
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(b"lora")
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
runner = CliRunner()
result = invoke_cli(
runner,
[
"comfy",
"showcase",
"--workflow",
"auto",
"--lora",
"_ladybird/Rook_Kaefer-v1_0-NOOB.comfyui.safetensors",
"--prompts",
str(SHOWCASE_PROMPTS_PATH),
],
)
assert result.exit_code != 0
assert "LoRA matches multiple workflows" in result.output
assert "noob-willy" in result.output
assert "noob-chenkin" in result.output
assert "noob-base" in result.output
assert "noob-nova" in result.output
assert "noob-scrimblosauce" in result.output
assert "pass --workflow" in result.output
def test_comfy_showcase_cli_prompts_when_packaged_workflow_is_missing(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
import kneiff.infer.comfy.showcase as showcase_module
from kneiff.infer.comfy.showcase import (
ShowcaseRunRequest,
ShowcaseRunResult,
ShowcaseWorkflowPreset,
)
import kneiff.infer.comfy.workflow_presets as workflow_presets
prompts_path = tmp_path / "prompts.yaml"
prompts_path.write_text(
"""
version: 1
defaults:
seed: 123
prompts:
- id: first
uses: [showcase]
captions:
nlg:
- prose prompt
""",
encoding="utf-8",
)
models_dir = tmp_path / "comfyui-models"
lora_path = models_dir / "models" / "loras" / "_ladybird" / "rook.safetensors"
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(b"lora")
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
monkeypatch.setitem(
workflow_presets.SHOWCASE_WORKFLOW_PRESETS,
"pony",
ShowcaseWorkflowPreset(
name="pony",
workflow_filename="missing_pony.workflow.json",
prompt_field="pony",
),
)
monkeypatch.setattr(cli_comfy, "interactive_available", lambda console: True)
monkeypatch.setattr(cli_comfy, "read_picker_action", lambda: "select")
requests: list[ShowcaseRunRequest] = []
def fake_run_showcase(
request: ShowcaseRunRequest,
**kwargs: object,
) -> ShowcaseRunResult:
requests.append(request)
return ShowcaseRunResult(results=())
monkeypatch.setattr(showcase_module, "run_showcase", fake_run_showcase)
runner = CliRunner()
result = invoke_cli(
runner,
[
"comfy",
"showcase",
"--workflow",
"pony",
"--lora",
"_ladybird/rook.safetensors",
"--prompts",
str(prompts_path),
],
)
assert result.exit_code == 0, result.output
assert requests[0].workflow_source.name == "showcase_anima.workflow.json"
assert requests[0].workflow_name == "anima"
assert "Selected workflow: anima" in result.output
def test_comfy_showcase_lora_picker_descends_into_directories(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
models_dir = tmp_path / "comfyui-models"
lora_path = models_dir / "models" / "loras" / "nested" / "rook.safetensors"
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(b"lora")
actions = iter(("select", "down", "select"))
output = io.StringIO()
monkeypatch.setattr(cli_comfy, "read_picker_action", lambda: next(actions))
selected = cli_comfy.select_showcase_lora_interactively(
models_dir,
console=Console(file=output, force_terminal=False),
)
assert selected == "nested/rook.safetensors"
assert "nested/" in output.getvalue()
def test_comfy_showcase_lora_picker_starts_in_configured_directory(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
models_dir = tmp_path / "comfyui-models"
start_dir = models_dir / "models" / "loras" / "_ladybird" / "v1_0"
lora_path = start_dir / "rook.safetensors"
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(b"lora")
output = io.StringIO()
monkeypatch.setattr(cli_comfy, "read_picker_action", lambda: "select")
selected = cli_comfy.select_showcase_lora_interactively(
models_dir,
console=Console(file=output, force_terminal=False),
start_dir=start_dir,
)
assert selected == "_ladybird/v1_0/rook.safetensors"
assert "Directory: _ladybird/v1_0" in output.getvalue()
def test_comfy_showcase_lora_picker_start_dir_env_rejects_missing_directory(
tmp_path: Path,
) -> None:
models_dir = tmp_path / "comfyui-models"
missing_dir = models_dir / "models" / "loras" / "_ladybird" / "v1_0"
config = ComfyConfig(
models_dir=str(models_dir),
loras_dir_1=str(missing_dir),
)
with pytest.raises(ValueError, match="COMFY_LORAS_DIR_1 directory not found"):
cli_comfy._resolve_comfy_loras_start_dir(models_dir, config=config)
def test_comfy_showcase_lora_picker_start_dir_env_rejects_outside_lora_root(
tmp_path: Path,
) -> None:
models_dir = tmp_path / "comfyui-models"
outside_dir = tmp_path / "other-loras"
outside_dir.mkdir()
config = ComfyConfig(
models_dir=str(models_dir),
loras_dir_1=str(outside_dir),
)
with pytest.raises(ValueError, match="COMFY_LORAS_DIR_1 must be below"):
cli_comfy._resolve_comfy_loras_start_dir(models_dir, config=config)
def test_comfy_showcase_training_picker_uses_step_and_cleans_staged_lora(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
isolated_cli_project: Path,
) -> None:
import kneiff.infer.comfy.showcase as showcase_module
from kneiff.infer.comfy.showcase import ShowcaseRunRequest, ShowcaseRunResult
output_root = (
isolated_cli_project
/ "TRAINING"
/ "ANIMA_1"
/ "_simpletuner-output"
/ "checkpoint-100"
)
output_root.mkdir(parents=True)
(output_root / "pytorch_lora_weights.safetensors").write_bytes(b"raw")
preferred_path = output_root / "pytorch_lora_weights.comfyui.safetensors"
preferred_path.write_bytes(b"comfyui")
second_step = output_root.parent / "checkpoint-200" / "weights.safetensors"
second_step.parent.mkdir()
second_step.write_bytes(b"second-step")
models_dir = tmp_path / "comfyui-models"
(models_dir / "models" / "loras").mkdir(parents=True)
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
monkeypatch.setattr(cli_comfy, "interactive_available", lambda console: True)
actions = iter(("select", "down", "select"))
monkeypatch.setattr(cli_comfy, "read_picker_action", lambda: next(actions))
requests: list[ShowcaseRunRequest] = []
staged_paths: list[Path] = []
def fake_run_showcase(
request: ShowcaseRunRequest,
**kwargs: object,
) -> ShowcaseRunResult:
requests.append(request)
assert request.lora_name is not None
staged_path = models_dir / "models" / "loras" / request.lora_name
assert staged_path.read_bytes() == b"comfyui"
staged_paths.append(staged_path)
return ShowcaseRunResult(results=())
monkeypatch.setattr(showcase_module, "run_showcase", fake_run_showcase)
result = invoke_cli(
CliRunner(),
[
"comfy",
"showcase",
"-t",
"100",
"200",
"100",
"--workflow",
"anima",
],
)
assert result.exit_code == 0, result.output
assert len(requests) == 1
assert requests[0].lora_name is not None
assert requests[0].lora_name.endswith(
"ANIMA_1/_simpletuner-output/checkpoint-100/"
"pytorch_lora_weights.comfyui.safetensors"
)
assert "Selected TRAINING LoRA:" in result.output
assert not staged_paths[0].exists()
assert not (models_dir / "models" / "loras" / ".kneiff-training").exists()
def test_comfy_showcase_training_hides_root_exports_without_checkpoint_steps(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
isolated_cli_project: Path,
) -> None:
import kneiff.infer.comfy.showcase as showcase_module
from kneiff.infer.comfy.showcase import ShowcaseRunRequest, ShowcaseRunResult
output_root = isolated_cli_project / "TRAINING" / "ANIMA_1" / "_simpletuner-output"
output_root.mkdir(parents=True)
root_lora = output_root / "root.comfyui.safetensors"
root_lora.write_bytes(b"root")
models_dir = tmp_path / "comfyui-models"
(models_dir / "models" / "loras").mkdir(parents=True)
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
monkeypatch.setattr(cli_comfy, "interactive_available", lambda console: True)
requests: list[ShowcaseRunRequest] = []
def fake_run_showcase(
request: ShowcaseRunRequest,
**kwargs: object,
) -> ShowcaseRunResult:
requests.append(request)
return ShowcaseRunResult(results=())
monkeypatch.setattr(showcase_module, "run_showcase", fake_run_showcase)
result = invoke_cli(
CliRunner(),
["comfy", "showcase", "-t", "--workflow", "anima"],
)
assert result.exit_code != 0
assert "No checkpoint-<step> LoRA outputs" in result.output
assert not requests
def test_comfy_showcase_training_runs_every_selected_lora_in_one_grid(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
isolated_cli_project: Path,
) -> None:
import kneiff.infer.comfy.showcase as showcase_module
import kneiff.infer.comfy.showcase_grid as showcase_grid_module
from kneiff.infer.comfy.showcase import (
ShowcasePromptResult,
ShowcaseRunRequest,
ShowcaseRunResult,
)
from kneiff.infer.comfy.showcase_grid import ShowcaseGridRow
from kneiff.infer.comfy.showcase_runner import select_showcase_prompts
output_root = isolated_cli_project / "TRAINING" / "ANIMA_1" / "_simpletuner-output"
for step in (100, 200):
lora_path = (
output_root
/ f"checkpoint-{step}"
/ "pytorch_lora_weights.comfyui.safetensors"
)
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(str(step).encode("ascii"))
models_dir = tmp_path / "comfyui-models"
(models_dir / "models" / "loras").mkdir(parents=True)
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
monkeypatch.setattr(cli_comfy, "interactive_available", lambda console: True)
actions = iter(("select", "down", "all", "select"))
monkeypatch.setattr(cli_comfy, "read_picker_action", lambda: next(actions))
requests: list[ShowcaseRunRequest] = []
staged_paths: list[Path] = []
captured_grid_rows: tuple[ShowcaseGridRow, ...] = ()
progress_reporters: list[_CapturedShowcaseProgress] = []
def fake_run_showcase(
request: ShowcaseRunRequest,
*,
progress: Callable[[ShowcasePromptResult], None] | None = None,
) -> ShowcaseRunResult:
requests.append(request)
assert request.lora_name is not None
staged_path = models_dir / "models" / "loras" / request.lora_name
assert staged_path.is_file()
staged_paths.append(staged_path)
prompts, skipped_prompt_ids = select_showcase_prompts(
request.prompt_catalog,
request.prompt_field,
)
results = tuple(
ShowcasePromptResult(
prompt=prompt,
prompt_id=f"queued-{prompt.id}",
filename_prefix=prompt.id,
files=(),
)
for prompt in prompts
)
if progress is not None:
for prompt_result in results:
progress(prompt_result)
return ShowcaseRunResult(
results=results,
skipped_prompt_ids=skipped_prompt_ids,
)
def fake_write_showcase_grid(
rows: tuple[ShowcaseGridRow, ...] | list[ShowcaseGridRow],
*,
output_subfolder: str,
filename: str,
**kwargs: object,
) -> ComfyUploadedImage:
nonlocal captured_grid_rows
captured_grid_rows = tuple(rows)
assert all(path.is_file() for path in staged_paths)
return ComfyUploadedImage(
name=filename,
subfolder=output_subfolder,
type="output",
)
monkeypatch.setattr(showcase_module, "run_showcase", fake_run_showcase)
monkeypatch.setattr(
cli_comfy,
"CliProgress",
_capturing_showcase_progress_factory(progress_reporters),
)
monkeypatch.setattr(
showcase_grid_module,
"write_showcase_grid",
fake_write_showcase_grid,
)
result = invoke_cli(
CliRunner(),
["comfy", "showcase", "-t", "100", "200", "--workflow", "anima"],
)
assert result.exit_code == 0, result.output
assert len(requests) == 2
assert requests[0].generated_at == requests[1].generated_at
assert all(request.showcase_model == "anima" for request in requests)
assert [row.label for row in captured_grid_rows] == [
"ANIMA_1/_simpletuner-output/checkpoint-100/"
"pytorch_lora_weights.comfyui.safetensors",
"ANIMA_1/_simpletuner-output/checkpoint-200/"
"pytorch_lora_weights.comfyui.safetensors",
]
assert all(row.showcase_model == "anima" for row in captured_grid_rows)
assert all(not path.exists() for path in staged_paths)
assert not tuple(
isolated_cli_project.joinpath("TRAINING").glob("*showcase-grid*.jpg")
)
assert len(progress_reporters) == 1
assert progress_reporters[0].title == "Showcase"
assert progress_reporters[0].total == sum(
len(row.result.results) for row in captured_grid_rows
)
assert progress_reporters[0].advances
first_progress_text = progress_reporters[0].advances[0]
final_progress_text = progress_reporters[0].advances[-1]
assert first_progress_text is not None
assert final_progress_text is not None
assert first_progress_text.startswith("LoRA 1/2 · ")
assert final_progress_text.startswith("LoRA 2/2 · ")
assert "Selected TRAINING LoRAs:" in result.output
assert "kneiff-showcase-grid.jpg" in result.output
assert "LoRA: " not in result.output
@pytest.mark.parametrize(
("args", "expected"),
[
(["comfy", "showcase", "100"], "STEPS require --training"),
(
["comfy", "showcase", "-t", "--lora", "character.safetensors"],
"Do not combine --training",
),
],
)
def test_comfy_showcase_training_rejects_invalid_option_combinations(
args: list[str],
expected: str,
) -> None:
result = invoke_cli(CliRunner(), args)
assert result.exit_code != 0
assert expected in result.output
def test_comfy_showcase_training_requires_interactive_terminal() -> None:
result = invoke_cli(CliRunner(), ["comfy", "showcase", "-t"])
assert result.exit_code != 0
assert "requires an interactive" in result.output
assert "terminal for LoRA selection" in result.output
@pytest.mark.parametrize(
("step", "expected"),
[
("0", "positive"),
("200", "Available steps: 100"),
],
)
def test_comfy_showcase_training_rejects_invalid_or_missing_steps(
monkeypatch: pytest.MonkeyPatch,
isolated_cli_project: Path,
step: str,
expected: str,
) -> None:
checkpoint_root = (
isolated_cli_project
/ "TRAINING"
/ "ANIMA_1"
/ "_simpletuner-output"
/ "checkpoint-100"
)
checkpoint_root.mkdir(parents=True)
(checkpoint_root / "weights.safetensors").write_bytes(b"lora")
monkeypatch.setattr(cli_comfy, "interactive_available", lambda console: True)
result = invoke_cli(CliRunner(), ["comfy", "showcase", "-t", step])
assert result.exit_code != 0
assert expected in result.output
def test_comfy_showcase_training_picker_opens_runs_before_checkpoints(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
from kneiff.training.lora.output_discovery import TrainingLoraCandidate
first_path = tmp_path / "first.comfyui.safetensors"
second_path = tmp_path / "second.safetensors"
first_path.write_bytes(b"first")
second_path.write_bytes(b"second")
candidates = (
TrainingLoraCandidate(
path=first_path,
relative_path=Path(
"first_1/_simpletuner-output/checkpoint-50/first.comfyui.safetensors"
),
checkpoint_step=50,
comfyui_native=True,
),
TrainingLoraCandidate(
path=second_path,
relative_path=Path(
"second_1/_simpletuner-output/checkpoint-100/second.safetensors"
),
checkpoint_step=100,
comfyui_native=False,
),
)
actions = iter(("down", "select", "down", "select"))
output = io.StringIO()
monkeypatch.setattr(cli_comfy, "read_picker_action", lambda: next(actions))
selected = cli_comfy.select_training_lora_interactively(
candidates,
console=Console(file=output, force_terminal=False),
)
assert selected == (candidates[1],)
assert "Select TRAINING run" in output.getvalue()
assert "first_1/ (1 LoRA(s))" in output.getvalue()
assert candidates[1].relative_path.as_posix() in output.getvalue()
def test_comfy_showcase_training_picker_can_be_cancelled(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
from kneiff.training.lora.output_discovery import TrainingLoraCandidate
lora_path = tmp_path / "weights.safetensors"
lora_path.write_bytes(b"lora")
candidate = TrainingLoraCandidate(
path=lora_path,
relative_path=Path(
"ready_1/_simpletuner-output/checkpoint-100/weights.safetensors"
),
checkpoint_step=100,
comfyui_native=False,
)
monkeypatch.setattr(cli_comfy, "read_picker_action", lambda: "cancel")
selected = cli_comfy.select_training_lora_interactively(
(candidate,),
console=Console(file=io.StringIO(), force_terminal=False),
)
assert selected is None
def test_comfy_showcase_training_picker_selects_multiple_loras(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
from kneiff.training.lora.output_discovery import TrainingLoraCandidate
candidates = tuple(
TrainingLoraCandidate(
path=tmp_path / f"weights-{step}.safetensors",
relative_path=Path(
f"ready_1/_simpletuner-output/checkpoint-{step}/weights.safetensors"
),
checkpoint_step=step,
comfyui_native=False,
)
for step in (100, 200)
)
for candidate in candidates:
candidate.path.write_bytes(b"lora")
actions = iter(("select", "down", "toggle", "down", "toggle", "select"))
output = io.StringIO()
monkeypatch.setattr(cli_comfy, "read_picker_action", lambda: next(actions))
selected = cli_comfy.select_training_lora_interactively(
candidates,
console=Console(file=output, force_terminal=False),
)
assert selected == candidates
assert "Selected TRAINING LoRAs:" in output.getvalue()
assert "[x]" in output.getvalue()
def test_comfy_showcase_training_infers_workflow_from_relative_path(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
isolated_cli_project: Path,
) -> None:
import kneiff.infer.comfy.showcase as showcase_module
from kneiff.infer.comfy.showcase import ShowcaseRunRequest, ShowcaseRunResult
lora_path = (
isolated_cli_project
/ "TRAINING"
/ "ANIMA_1"
/ "_simpletuner-output"
/ "checkpoint-100"
/ "weights.comfyui.safetensors"
)
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(b"lora")
models_dir = tmp_path / "comfyui-models"
(models_dir / "models" / "loras").mkdir(parents=True)
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
monkeypatch.setattr(cli_comfy, "interactive_available", lambda console: True)
actions = iter(("select", "down", "select"))
monkeypatch.setattr(cli_comfy, "read_picker_action", lambda: next(actions))
requests: list[ShowcaseRunRequest] = []
def fake_run_showcase(
request: ShowcaseRunRequest,
**kwargs: object,
) -> ShowcaseRunResult:
requests.append(request)
return ShowcaseRunResult(results=())
monkeypatch.setattr(showcase_module, "run_showcase", fake_run_showcase)
result = invoke_cli(CliRunner(), ["comfy", "showcase", "-t", "100"])
assert result.exit_code == 0, result.output
assert requests[0].workflow_name == "anima"
def test_comfy_showcase_training_falls_back_to_complete_workflow_picker(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
isolated_cli_project: Path,
) -> None:
import kneiff.infer.comfy.showcase as showcase_module
from kneiff.infer.comfy.showcase import ShowcaseRunRequest, ShowcaseRunResult
lora_path = (
isolated_cli_project
/ "TRAINING"
/ "mystery_1"
/ "_simpletuner-output"
/ "checkpoint-100"
/ "weights.safetensors"
)
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(b"lora")
models_dir = tmp_path / "comfyui-models"
(models_dir / "models" / "loras").mkdir(parents=True)
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
monkeypatch.setattr(cli_comfy, "interactive_available", lambda console: True)
actions = iter(("select", "down", "select", "select"))
monkeypatch.setattr(cli_comfy, "read_picker_action", lambda: next(actions))
requests: list[ShowcaseRunRequest] = []
def fake_run_showcase(
request: ShowcaseRunRequest,
**kwargs: object,
) -> ShowcaseRunResult:
requests.append(request)
return ShowcaseRunResult(results=())
monkeypatch.setattr(showcase_module, "run_showcase", fake_run_showcase)
result = invoke_cli(CliRunner(), ["comfy", "showcase", "-t", "100"])
assert result.exit_code == 0, result.output
assert requests[0].workflow_name == "anima"
assert "Selected workflow: anima" in result.output
def test_comfy_showcase_training_explicit_auto_keeps_inference_failure(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
isolated_cli_project: Path,
) -> None:
lora_path = (
isolated_cli_project
/ "TRAINING"
/ "mystery_1"
/ "_simpletuner-output"
/ "checkpoint-100"
/ "weights.safetensors"
)
lora_path.parent.mkdir(parents=True)
lora_path.write_bytes(b"lora")
models_dir = tmp_path / "comfyui-models"
lora_root = models_dir / "models" / "loras"
lora_root.mkdir(parents=True)
monkeypatch.setenv(COMFY_MODELS_DIR_ENV_KEY, str(models_dir))
monkeypatch.setattr(cli_comfy, "interactive_available", lambda console: True)
actions = iter(("select", "down", "select"))
monkeypatch.setattr(cli_comfy, "read_picker_action", lambda: next(actions))
result = invoke_cli(
CliRunner(),
["comfy", "showcase", "-t", "100", "--workflow", "auto"],
)
assert result.exit_code != 0
assert "Could not infer a workflow" in result.output
assert not (lora_root / ".kneiff-training").exists()
def test_train_help_skips_storage_bootstrap(monkeypatch: pytest.MonkeyPatch) -> None:
runner = CliRunner()
monkeypatch.delenv("KNF_STORAGE", raising=False)
help_result = invoke_cli(runner, ["train", "--help"])
train_result = invoke_cli(runner, ["train"])
assert help_result.exit_code == 0, help_result.output
assert train_result.exit_code == 2
assert "Training run lifecycle workflows." in train_result.output
assert "KNF_STORAGE" not in help_result.output
assert "KNF_STORAGE" not in train_result.output
def test_config_doctor_output_uses_only_knf_env_names() -> None:
runner = CliRunner()
forbidden = ("KNF_STORAGE_ROOT", "KNEIFF_APPRC_TOML", "KNEIFF_CONFIG_FILE")
result = invoke_cli(runner, ["config", "doctor"])
assert "KNF_STORAGE" in result.output
assert "KNF_APPRC_TOML" in result.output
assert not any(name in result.output for name in forbidden)
def test_cli_app_import_keeps_runtime_backends_lazy() -> None:
script = (
"import sys\n"
"import kneiff.cli.app\n"
"heavy_modules = {\n"
" 'huggingface_hub', 'numpy', 'openai', 'openpyxl', 'pandas',\n"
" 'requests', 'safetensors', 'spandrel', 'torch', 'torchvision',\n"
" 'transformers',\n"
"}\n"
"loaded = sorted(name for name in heavy_modules if name in sys.modules)\n"
"print('\\n'.join(loaded))\n"
"raise SystemExit(1 if loaded else 0)\n"
)
result = subprocess.run(
[sys.executable, "-c", script],
capture_output=True,
text=True,
check=False,
)
assert result.returncode == 0, result.stdout + result.stderr
def test_lora_command_group_is_removed() -> None:
runner = CliRunner()
result = invoke_cli(runner, ["lora", "--help"])
assert result.exit_code != 0
def test_old_diff_subcommand_is_removed() -> None:
runner = CliRunner()
result = invoke_cli(runner, ["diff", "--help"])
assert result.exit_code != 0
def test_img_tag_help_shows_selected_tag_output_options(
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv("KNF_STORAGE", raising=False)
runner = CliRunner()
result = invoke_cli(runner, ["img", "tag", "--help"])
assert result.exit_code == 0
assert "--txt" in result.output
assert "--comma" in result.output
assert "-c" in result.output
assert "Write .txt sidecars next to images" in result.output
assert "probability CSV output" in result.output
assert "Legacy JTP-3 snapshot threshold" in result.output
def test_img_tag_cli_passes_text_output_options(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv("KNF_STORAGE", raising=False)
runner = CliRunner()
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
captured: dict[str, tag_jtp3.Jtp3RunConfig] = {}
def fake_run_jtp3(
config: tag_jtp3.Jtp3RunConfig,
snapshot_config: tag_jtp3.Jtp3SnapshotConfig | None = None,
) -> subprocess.CompletedProcess[str]:
captured["config"] = config
return subprocess.CompletedProcess([], 0)
monkeypatch.setattr(tag_jtp3, "run_jtp3", fake_run_jtp3)
result = invoke_cli(runner, ["img", "tag", str(image_path), "--txt", "--comma"])
assert result.exit_code == 0
assert captured["config"].write_txt is True
assert captured["config"].comma_separated is True
result = invoke_cli(runner, ["img", "tag", str(image_path), "-c"])
assert result.exit_code == 0
assert captured["config"].write_txt is False
assert captured["config"].comma_separated is True
def test_img_tag_rejects_csv_stdout_with_txt(
tmp_path: Path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
monkeypatch.delenv("KNF_STORAGE", raising=False)
runner = CliRunner()
image_path = tmp_path / "image.png"
image_path.write_bytes(b"image")
result = invoke_cli(
runner, ["img", "tag", str(image_path), "--csv-stdout", "--txt"]
)
assert result.exit_code != 0
assert "--csv-stdout cannot be combined with --txt or --comma" in result.output
def test_package_import_smoke() -> None:
for module_name in (
"kneiff",
"kneiff.clients",
"kneiff.datasets",
"kneiff.datasets.manifest",
"kneiff.datasets.export",
"kneiff.training",
"kneiff.training.lora",
"kneiff.infer",
"kneiff.cli",
"kneiff.cli.app",
"kneiff.main",
"kneiff.app.workbench",
"kneiff.utils",
"kneiff.utils.image.caption",
"kneiff_dev",
):
assert importlib.import_module(module_name)
def test_removed_import_paths_are_not_shimmed() -> None:
for module_name in (
"kneiff.training.captions",
"kneiff.training.dataset",
"kneiff.training.manifest",
"kneiff.training.augmentations",
"kneiff.inference",
"kneiff.cli_dataset",
"kneiff.cli_dataset_report",
"kneiff.cli_image",
"kneiff.cli_lora",
"kneiff.datasets.manifest_to_captions",
"kneiff.datasets.captions",
"kneiff.datasets.augment",
"kneiff.datasets.manifest.core",
):
with pytest.raises(ModuleNotFoundError):
importlib.import_module(module_name)
|