Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
68ab668373 | ||
|
|
43319e7330 | ||
|
|
1db0e6a4f5 | ||
|
|
54f99f67b7 | ||
|
|
7a894ccb90 | ||
|
|
3a182253eb | ||
|
|
b6b243c130 | ||
|
|
fe5f1080df | ||
|
|
e258bd0c47 | ||
|
|
8c0341771d | ||
|
|
433f0ef95c | ||
|
|
d9b496df33 | ||
|
|
45125d570d | ||
|
|
3759813b39 | ||
|
|
edf48eb0bf | ||
|
|
c1b454eaa3 | ||
|
|
e735e7317a | ||
|
|
7a30c6ad89 | ||
|
|
9446358c56 | ||
|
|
8e99c8e3c3 | ||
|
|
603fbaaeee | ||
|
|
76f19a75bc | ||
|
|
f9a9731924 | ||
|
|
726571abfd | ||
|
|
51dbfcfac0 | ||
|
|
cc039ee32e | ||
|
|
72eeb7e303 | ||
|
|
369186bda0 | ||
|
|
77d7ac30e0 | ||
|
|
435e7b1d4c | ||
|
|
dd07bb5aea | ||
|
|
d181b50097 | ||
|
|
14f2f2ffac | ||
|
|
78a8b16c1a | ||
|
|
9815e38c54 | ||
|
|
d44ada12bf | ||
|
|
d7e6b32480 | ||
|
|
0c08e843e1 | ||
|
|
a47676eea8 | ||
|
|
096335993d | ||
|
|
45d9979eec | ||
|
|
df030d5db2 | ||
|
|
bc0f700c81 | ||
|
|
738ea302d9 | ||
|
|
56c19498c9 | ||
|
|
4b3c40a150 | ||
|
|
d3460b5f10 | ||
|
|
87f6bc523c | ||
|
|
a27f9c41ef | ||
|
|
f0102c96bf | ||
|
|
e70b66dbb0 | ||
|
|
64ebd5e192 | ||
|
|
fd9eb00b20 | ||
|
|
401c003471 | ||
|
|
2464d45e24 | ||
|
|
ce3be7999f | ||
|
|
4f772ebbba | ||
|
|
31689ecd6f | ||
|
|
a3c96f6d84 | ||
|
|
98139769c2 | ||
|
|
2b983e2bea | ||
|
|
f68f8f1201 | ||
|
|
7ef3b1d2bf | ||
|
|
31391c579f | ||
|
|
d5d5bcf7a0 | ||
|
|
7ba9c464fb | ||
|
|
a01c6c3e0f | ||
|
|
284ae4e0b1 | ||
|
|
d819748089 | ||
|
|
16ea1d1551 | ||
|
|
a2ea2df2c5 | ||
|
|
95a847a9fd | ||
|
|
25732b9086 | ||
|
|
cfc078a960 | ||
|
|
ca447b6b62 | ||
|
|
98d733faca | ||
|
|
17122db4e3 | ||
|
|
93ad34ecae | ||
|
|
af07ab7f69 | ||
|
|
0cf69cad19 | ||
|
|
539926f486 | ||
|
|
e6ab89c4ec | ||
|
|
f17cad3a5c | ||
|
|
9db6605473 | ||
|
|
9bd5afa256 | ||
|
|
b3ccc25cd7 | ||
|
|
842dddbfbf | ||
|
|
68f47d788d | ||
|
|
b449821dfc | ||
|
|
36a2c484f7 | ||
|
|
8a73f906b6 | ||
|
|
e5421431c0 | ||
|
|
645f58da8e | ||
|
|
80389a6621 | ||
|
|
bf0a871563 | ||
|
|
8ea8f2866d | ||
|
|
29f4073247 | ||
|
|
11f1f6b798 | ||
|
|
1f09925d4f | ||
|
|
d14422deb4 | ||
|
|
39426d6a2e | ||
|
|
a4a5df9e53 | ||
|
|
2299db05ae | ||
|
|
aa8c355461 | ||
|
|
0133804a7b | ||
|
|
a486506317 | ||
|
|
8a84224dea | ||
|
|
746cbdb9e1 | ||
|
|
4459c270c2 | ||
|
|
fd707a2a05 | ||
|
|
39ea2125d2 | ||
|
|
8720a8afc8 | ||
|
|
4082485800 | ||
|
|
5411a0bf88 | ||
|
|
50467d1cc1 | ||
|
|
d9d49bc368 | ||
|
|
69da89d7e3 | ||
|
|
a2c258b654 | ||
|
|
d9ae13e4a9 | ||
|
|
15bca6eaee | ||
|
|
c1c6472b94 | ||
|
|
c39c3fd568 | ||
|
|
c07c785192 | ||
|
|
c6ed164196 | ||
|
|
ae98dc306f | ||
|
|
84a8c5f688 | ||
|
|
bcfe782bfb | ||
|
|
17f1245eaa | ||
|
|
f7a87346a1 | ||
|
|
0f4402f9e0 | ||
|
|
1b3001cbad | ||
|
|
deb4bbb983 | ||
|
|
cfd06a0ce1 | ||
|
|
39dceb9596 | ||
|
|
6c27225d92 | ||
|
|
8e58f3fe06 | ||
|
|
23c5721318 | ||
|
|
34a6c1a8f3 | ||
|
|
46e499efb8 | ||
|
|
add4d1f22c | ||
|
|
52b72c9277 | ||
|
|
4e8e47f8f4 | ||
|
|
2af07072fd | ||
|
|
229d7291ee | ||
|
|
99c05514da | ||
|
|
e9a28545b1 | ||
|
|
e4c39ce0f6 | ||
|
|
16405ceb17 | ||
|
|
b59f1c1bbe | ||
|
|
ac358436fe | ||
|
|
b560c4a17a | ||
|
|
bc76189941 | ||
|
|
52e9626059 | ||
|
|
0f50056ab1 | ||
|
|
17f577ec8d | ||
|
|
819b82af35 | ||
|
|
deb22acfaa | ||
|
|
c4faf12236 | ||
|
|
3cd52a032b | ||
|
|
0b72ad0c65 | ||
|
|
b60d9b006e | ||
|
|
fef2545c8e | ||
|
|
4416ffee23 | ||
|
|
dac1a9a705 | ||
|
|
e1a3e70442 | ||
|
|
6a6ed5afd5 | ||
|
|
db528293aa | ||
|
|
799feac2e9 | ||
|
|
0567a5e1fe | ||
|
|
e00f57a5d0 | ||
|
|
2aea1845e6 | ||
|
|
6697b32e37 | ||
|
|
dda225708b | ||
|
|
adee96644a | ||
|
|
d64b13a54b | ||
|
|
67f12480ae | ||
|
|
65504b8263 | ||
|
|
b7862153e5 | ||
|
|
922ff007f4 | ||
|
|
5ce3408cfc | ||
|
|
b7679d0e5a | ||
|
|
ea88616f81 | ||
|
|
7b0e59a502 | ||
|
|
40bfc8e3b7 | ||
|
|
782aa7c63b | ||
|
|
7295cf2e50 | ||
|
|
bb68fd890f | ||
|
|
070b9c2dfe | ||
|
|
3cd6c3cf9b | ||
|
|
d77b89c388 | ||
|
|
e9bfdceee2 | ||
|
|
b6156bc59a | ||
|
|
c765112c38 | ||
|
|
9f185c5806 | ||
|
|
c8fb3dada0 | ||
|
|
98c7d94290 | ||
|
|
7bb27c5c40 | ||
|
|
22facf075b | ||
|
|
ac7bb560a5 | ||
|
|
6df8cbef30 | ||
|
|
a2d8687993 | ||
|
|
6931d4811f | ||
|
|
8b3e7adcf4 | ||
|
|
cc2a66c74a | ||
|
|
c3f7c85b9e | ||
|
|
01862135da | ||
|
|
46cbe4266b | ||
|
|
ecf7472ff5 | ||
|
|
6b3cbb3268 | ||
|
|
9771f7e3fb | ||
|
|
90e4c9e24d | ||
|
|
c96badf1b9 | ||
|
|
b8286a5e51 | ||
|
|
d030a3b717 | ||
|
|
4bad6fae7e | ||
|
|
9a91d30530 | ||
|
|
c93d4b013c | ||
|
|
a3b0e7eaff | ||
|
|
cfb85445fa | ||
|
|
9e875c7a99 | ||
|
|
39b688403d | ||
|
|
2359960a54 | ||
|
|
fffcb49c4d | ||
|
|
a89b04f81b | ||
|
|
f137bfc751 | ||
|
|
6cd2c40fb8 | ||
|
|
0fb68ddd16 | ||
|
|
e583c6b529 | ||
|
|
58b9305a02 | ||
|
|
654488efd3 | ||
|
|
3e15a45cb8 | ||
|
|
82ea8ce773 | ||
|
|
8cdf32e3b1 | ||
|
|
1b5eb256f9 | ||
|
|
545332f43e | ||
|
|
5ce3248216 | ||
|
|
c70894a020 | ||
|
|
a756747d08 | ||
|
|
c93e9eada9 | ||
|
|
1fb017f772 | ||
|
|
c4cec35a19 | ||
|
|
9ee1a0dd52 | ||
|
|
15587a5d56 | ||
|
|
75c2ccc562 | ||
|
|
bcd68b11cd | ||
|
|
83cea8e955 | ||
|
|
8417d42ff6 | ||
|
|
5188d04b02 | ||
|
|
f62ff73d2c | ||
|
|
d348e71664 | ||
|
|
98c6f11904 | ||
|
|
2d3a4ffe32 | ||
|
|
8bd45cb519 | ||
|
|
afb9c567eb | ||
|
|
f2ad940d32 | ||
|
|
99b44c1bc2 | ||
|
|
f721466c14 | ||
|
|
2b3a3bfe45 | ||
|
|
f1cdcfeff5 | ||
|
|
9f4e02c7f5 | ||
|
|
05415abf49 | ||
|
|
946400d441 | ||
|
|
57c56de26b | ||
|
|
8e4c230300 | ||
|
|
d365f7752c | ||
|
|
e8e5e5a09e | ||
|
|
3640df2bf4 | ||
|
|
ba7e993888 | ||
|
|
9a22a329f3 | ||
|
|
32f653e18d | ||
|
|
03185836b9 | ||
|
|
7812a98ddc | ||
|
|
609375766b | ||
|
|
7cc6e8c20a | ||
|
|
5acc0d6e8c | ||
|
|
ce6d34b24e | ||
|
|
98b53ddd71 | ||
|
|
d7347e790c | ||
|
|
3c101e1b8a | ||
|
|
fdd64969ae | ||
|
|
7135b9e721 | ||
|
|
738dd63182 | ||
|
|
f231989e69 | ||
|
|
c42a963d68 | ||
|
|
c701bb5002 | ||
|
|
0196bca21e | ||
|
|
d92fcf436c | ||
|
|
89dc3a4e94 | ||
|
|
2e8333a4cc | ||
|
|
cc35c8e4e6 | ||
|
|
f7789930c1 | ||
|
|
b775a1d93d | ||
|
|
430f7cf276 | ||
|
|
df8f2b57d3 | ||
|
|
42f3559e8c | ||
|
|
ba301ce39a | ||
|
|
1c86920d3b | ||
|
|
39ade25cc2 | ||
|
|
3ff5ff7902 | ||
|
|
f764beef53 | ||
|
|
1fb0d3dcc7 | ||
|
|
f748246801 | ||
|
|
b7905b81da | ||
|
|
dd78c417ba | ||
|
|
eb9dc96631 | ||
|
|
5beaf8e501 | ||
|
|
bf2ad422d7 | ||
|
|
89825a747d | ||
|
|
0d8e9192f1 | ||
|
|
763a340488 | ||
|
|
7362da49d9 | ||
|
|
9f4bac5f30 | ||
|
|
f36411aac5 | ||
|
|
0d3216d0e9 | ||
|
|
834aff18da | ||
|
|
bae6df106a | ||
|
|
07b428767e | ||
|
|
6a58f9ce95 | ||
|
|
bdb1cc4212 | ||
|
|
cbc0efa839 | ||
|
|
119952a51d | ||
|
|
d0e591c24c | ||
|
|
df148d8cd3 | ||
|
|
c76a95adf9 | ||
|
|
00ed3ffd92 | ||
|
|
3d72e8b4ff | ||
|
|
5dd666fe3a | ||
|
|
4fd7070c97 | ||
|
|
9fcf4ef1a7 | ||
|
|
cb8b7e7205 | ||
|
|
661a35f971 | ||
|
|
27eca5ba94 | ||
|
|
e7fece763c | ||
|
|
56bdb9e98a | ||
|
|
24f6f8ad65 | ||
|
|
bd8ffdca8a | ||
|
|
3906e87e19 | ||
|
|
376a58e27c | ||
|
|
711cd87567 | ||
|
|
00f23b4590 | ||
|
|
e8639a5050 | ||
|
|
54c9d98e85 | ||
|
|
c78cbd6913 | ||
|
|
adf5766f48 | ||
|
|
8accd26d94 | ||
|
|
7c2dc8248b | ||
|
|
7eb21c918a | ||
|
|
3d528c2997 | ||
|
|
6c11ec52de | ||
|
|
07fd152e84 | ||
|
|
a950ebfa92 | ||
|
|
3effd8f1e8 | ||
|
|
a1c496ed4c | ||
|
|
504b2dce40 | ||
|
|
f8d228b42c | ||
|
|
69912c724c | ||
|
|
0db278723d | ||
|
|
a498a5e7f3 | ||
|
|
f3607303af | ||
|
|
173328bf2d | ||
|
|
214f653d4e | ||
|
|
74005592e8 | ||
|
|
0939ae11ec | ||
|
|
b0ea8f6faf | ||
|
|
cf11bfc9d0 | ||
|
|
0a757baa9b | ||
|
|
944759a05a | ||
|
|
92bb954fc2 | ||
|
|
9fb3ffc6fb | ||
|
|
557152ae96 | ||
|
|
de2c5cd295 | ||
|
|
d2323da13c | ||
|
|
7be4ea4748 | ||
|
|
6e9595a594 | ||
|
|
f5a66e1995 | ||
|
|
28e6299bec | ||
|
|
8cbe4943a1 | ||
|
|
09597becc5 | ||
|
|
0fa7eec08d | ||
|
|
3df92b0509 | ||
|
|
1556a07653 | ||
|
|
64bcb706ae | ||
|
|
61a7f6bf45 | ||
|
|
2f2be6c075 | ||
|
|
f4fa4bebff | ||
|
|
bac173134b | ||
|
|
04e403d93b | ||
|
|
e4d58e59ee | ||
|
|
ee2047cac6 | ||
|
|
6e79a82596 | ||
|
|
b0fdbf1a97 | ||
|
|
d12d8bb484 | ||
|
|
b4a41e2340 | ||
|
|
9ccfc23f66 | ||
|
|
55b59f876e | ||
|
|
1f348ea4e8 | ||
|
|
c3b912aa76 | ||
|
|
d154fab852 | ||
|
|
10e3998230 | ||
|
|
30428e3e20 | ||
|
|
b171e97a08 | ||
|
|
866ca71053 | ||
|
|
3aa373be3b | ||
|
|
1db335d88b | ||
|
|
ec4cf272ce | ||
|
|
2e195cfa01 | ||
|
|
2a3ed8c52c | ||
|
|
41cdfa16c3 | ||
|
|
7b87283fcd | ||
|
|
e9d0797d67 | ||
|
|
bfa92d7007 | ||
|
|
1c12d99a33 | ||
|
|
173b2aceed | ||
|
|
a0a886c8a8 | ||
|
|
7c4c1f9172 | ||
|
|
5224d650e8 | ||
|
|
02246e0612 | ||
|
|
323ece55e8 | ||
|
|
2419567353 | ||
|
|
2ce93a326a | ||
|
|
32400171de | ||
|
|
516a226f5f | ||
|
|
d6a75f2d70 | ||
|
|
84bf5065d9 | ||
|
|
9ec65b7d8b | ||
|
|
08d21b0961 | ||
|
|
e7c727f102 | ||
|
|
639091fd17 | ||
|
|
977ec9785b | ||
|
|
ca06e1273b | ||
|
|
c2c38e5b9d | ||
|
|
6ddf0108be | ||
|
|
52990491f3 | ||
|
|
3a49fdfa97 | ||
|
|
b98155543b | ||
|
|
74716182ce | ||
|
|
d7adb9f5c0 | ||
|
|
c8e103152b | ||
|
|
1c3aa77889 | ||
|
|
501b962408 | ||
|
|
34df0b0675 | ||
|
|
a7bdec56d3 | ||
|
|
41e4c27416 | ||
|
|
c34fda023c | ||
|
|
6de8bddea5 | ||
|
|
1fea03858e | ||
|
|
16c01efb0d | ||
|
|
f9b7c601f9 | ||
|
|
cb6276ded0 | ||
|
|
894f44d4b5 | ||
|
|
7e1a45fa3c | ||
|
|
616746e07f | ||
|
|
4cdb3a0d68 | ||
|
|
c4eb347b56 | ||
|
|
356f3af597 | ||
|
|
9be7636d61 | ||
|
|
6ddf7321a0 | ||
|
|
0af9387da5 | ||
|
|
e08f295c25 | ||
|
|
ae5e46fccc | ||
|
|
32a54c4ff0 | ||
|
|
cca1753f10 | ||
|
|
81362756b4 | ||
|
|
fb1d32d503 | ||
|
|
ea21779258 | ||
|
|
6ad2986746 | ||
|
|
e80c5bce0e | ||
|
|
88f2e1b109 | ||
|
|
6aa194ff95 | ||
|
|
3731b4c228 | ||
|
|
8062ede1cd | ||
|
|
7496c8fd65 | ||
|
|
f82ff068e1 | ||
|
|
1029c79881 | ||
|
|
f20af63926 | ||
|
|
82b19c71de | ||
|
|
76c30404a8 | ||
|
|
10cb9d2bb0 | ||
|
|
e20f6523d9 | ||
|
|
d7fde3cce4 | ||
|
|
bf0edbabc9 | ||
|
|
ed78a1bf05 | ||
|
|
698cd7b725 | ||
|
|
d93c2713d5 | ||
|
|
dc971491d1 | ||
|
|
f5391da99a | ||
|
|
539828c8af | ||
|
|
16192ad6dd | ||
|
|
4dad2816d0 | ||
|
|
d1967d8395 | ||
|
|
ad1a4290bc | ||
|
|
e800b272cc | ||
|
|
4b93b7902d | ||
|
|
04808107c2 | ||
|
|
376e973ba0 | ||
|
|
0e4ca673fc | ||
|
|
70dc0e38e0 | ||
|
|
0297da28e6 | ||
|
|
f72bbc35cd | ||
|
|
052b88c33f | ||
|
|
6d6f09f82d | ||
|
|
0239663a38 | ||
|
|
958658f2c3 | ||
|
|
186a4fc7e4 | ||
|
|
2de7c3c9a3 | ||
|
|
55b6f2f94e | ||
|
|
a1c3b59bad | ||
|
|
3342d843e5 | ||
|
|
482f5c182d | ||
|
|
88dadfd4d5 | ||
|
|
e4868e1ea1 | ||
|
|
30246eb831 | ||
|
|
c97c290dba | ||
|
|
2da9b2813b | ||
|
|
aadb396151 | ||
|
|
96c9248135 | ||
|
|
695d7421d4 | ||
|
|
9d8137281e | ||
|
|
546b2f697b | ||
|
|
2d262999a3 | ||
|
|
e36d0fb15f | ||
|
|
d92a6c1872 | ||
|
|
67df4c6e53 | ||
|
|
e08d18c783 | ||
|
|
769d40f9f5 | ||
|
|
eef07948ac | ||
|
|
bf847e9639 | ||
|
|
39c8b5f3b8 | ||
|
|
cf810ca921 | ||
|
|
422607ec8d | ||
|
|
f9e26c8bbd | ||
|
|
be52d65de9 | ||
|
|
1d6021a916 | ||
|
|
6f0ac2674b | ||
|
|
6ba1f3f346 | ||
|
|
27ab751796 | ||
|
|
e2a9b25978 | ||
|
|
9b8016821c | ||
|
|
4811f21255 | ||
|
|
ca645721ec | ||
|
|
457e137b4c | ||
|
|
603c34d601 | ||
|
|
4fae27a6dd | ||
|
|
55a2fd64c9 | ||
|
|
5450682d44 | ||
|
|
d424f67948 | ||
|
|
838122ae67 | ||
|
|
e269117080 | ||
|
|
8910544eba | ||
|
|
9243d704ac | ||
|
|
e9981c1ee7 | ||
|
|
7c25eaeb95 | ||
|
|
d8d96e549b | ||
|
|
5d64bb2395 | ||
|
|
877727695d | ||
|
|
64119e6c90 | ||
|
|
6d5a1f4669 | ||
|
|
8ac04725c9 | ||
|
|
ef0f072891 | ||
|
|
985de6102e | ||
|
|
ecdf1e0995 | ||
|
|
39575f137c | ||
|
|
e993546fa4 | ||
|
|
ce12566998 | ||
|
|
c61dcaad2c | ||
|
|
1ba2d214f6 | ||
|
|
473d96084c | ||
|
|
94feeb61c7 | ||
|
|
3884f72552 | ||
|
|
cae791a169 | ||
|
|
e6f56f3a75 |
@@ -0,0 +1,50 @@
|
||||
# Normalize all text files to LF in the repository.
|
||||
# Working-tree endings are controlled by each machine's core.autocrlf setting;
|
||||
# the repo always stores LF so Windows/Linux checkouts stop showing phantom diffs.
|
||||
* text=auto
|
||||
|
||||
# Source files: always LF (in repo and on disk)
|
||||
*.py text eol=lf
|
||||
*.js text eol=lf
|
||||
*.json text eol=lf
|
||||
*.md text eol=lf
|
||||
*.toml text eol=lf
|
||||
*.txt text eol=lf
|
||||
*.yml text eol=lf
|
||||
*.yaml text eol=lf
|
||||
*.cfg text eol=lf
|
||||
*.ini text eol=lf
|
||||
*.css text eol=lf
|
||||
*.html text eol=lf
|
||||
*.sh text eol=lf
|
||||
|
||||
# Windows-only scripts keep CRLF
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
*.ps1 text eol=crlf
|
||||
|
||||
# Binary files: never convert
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.gif binary
|
||||
*.webp binary
|
||||
*.ico binary
|
||||
*.mp4 binary
|
||||
*.webm binary
|
||||
*.mkv binary
|
||||
*.mov binary
|
||||
*.avi binary
|
||||
*.mp3 binary
|
||||
*.wav binary
|
||||
*.flac binary
|
||||
*.safetensors binary
|
||||
*.ckpt binary
|
||||
*.pt binary
|
||||
*.pth binary
|
||||
*.bin binary
|
||||
*.onnx binary
|
||||
*.af binary
|
||||
*.pyc binary
|
||||
*.pdf binary
|
||||
*.zip binary
|
||||
@@ -0,0 +1,15 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: franckyb # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
polar: # Replace with a single Polar username
|
||||
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
|
||||
thanks_dev: # Replace with a single thanks.dev username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
@@ -0,0 +1,20 @@
|
||||
name: Publish to Comfy registry
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "pyproject.toml"
|
||||
|
||||
jobs:
|
||||
publish-node:
|
||||
name: Publish Custom Node to registry
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v4
|
||||
- name: Publish Custom Node
|
||||
uses: Comfy-Org/publish-node-action@main
|
||||
with:
|
||||
personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
|
||||
@@ -3,6 +3,7 @@ __pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.pyd
|
||||
.venv/
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
@@ -19,6 +20,7 @@ wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
test/
|
||||
|
||||
# VS Code history extension
|
||||
.history/
|
||||
@@ -26,6 +28,7 @@ wheels/
|
||||
# IDE files
|
||||
.vscode/
|
||||
.idea/
|
||||
ComfyUI-Prompt-Manager.code-workspace
|
||||
|
||||
# OS files
|
||||
.DS_Store
|
||||
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -1,32 +1,160 @@
|
||||
# ComfyUI Prompt Manager
|
||||
## A comprehensive prompt and recipe toolkit for [ComfyUI](https://github.com/comfyanonymous/ComfyUI)
|
||||
|
||||
A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) that allows both saving and generating new prompts using llama.cpp.
|
||||
ComfyUI Prompt Manager is a prompt toolkit for ComfyUI. It helps you manage, save, and reuse prompts along with their LoRAs and trigger words. It can generate prompts using a local LLM through llama.cpp or Ollama, or generate them directly with ComfyUI’s own CLIP/text encoders. It also extracts metadata from images, videos, and JSON files, so you can turn them into reusable prompts — and the **Prompts** sidebar and save/load tools keep everything organized.
|
||||
|
||||
(**Llama.cpp needs to be installed and accessible from command prompt.**)
|
||||
[See Installation Guide](#installation)
|
||||
|
||||
[See Node Reference](docs/feature-reference.md)
|
||||
|
||||
[See Prompt Composer](#prompt-composer)
|
||||
|
||||
## What This Provides
|
||||
|
||||
- **Prompt Manager**:
|
||||
- For saving and loading Prompts.
|
||||
- These saved prompts can include LoRA stacks, trigger words, as well as thumbnails.
|
||||
- **Prompt Generator**:
|
||||
- To run a local LLM (llama.cpp or Ollama), or directly use ComfyUI's CLIP/text encoders.
|
||||
- Also supports image analysis when using Vision Capable models.
|
||||
- **Prompt Composer**:
|
||||
- For building prompts from reusable prompt fragments such as attire, expression, action, style, ambience, and more.
|
||||
- Supports the v2 Prompt Composer library format with thumbnails, prompt groups, subject-aware group behavior, LoRAs, RefMods, random multi-prompt selection, and video/image composition modes.
|
||||
- **Prompt Extractor**:
|
||||
- Read metadata from images/videos/JSON and output the prompt and LoRAs they use.
|
||||
- **Lora Preview integration**:
|
||||
- When [Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) is installed, LoRAs can be previewed on hover.
|
||||
- **Advanced media loading**:
|
||||
- Extractor nodes can also act as advanced image loaders, but I'd recommend [FBNodes](https://github.com/FranckyB/ComfyUI-FBnodes) for better solutions.
|
||||
- **And more**:
|
||||
- See the [Reference guide](docs/feature-reference.md) for a complete list.
|
||||
---
|
||||
|
||||
<div align="center">
|
||||
<img src="docs/prompt_manager.png" alt="Prompt Manager">
|
||||
<figcaption>Prompt Creation With Lora and Trigger Words</figcaption>
|
||||
<img src="docs/images/prompt_generator_text.png" alt="Prompt Manager">
|
||||
</div>
|
||||
|
||||
### Key features:
|
||||
### Prompt Manager:
|
||||
- **Category Organization**: Create and manage multiple categories to organize your prompts
|
||||
- **Save & Load Prompts**: Quickly save and recall your favorite prompts with custom names
|
||||
- **LLM Input Toggle**: Connect text outputs from other nodes and toggle between using them or your internal prompts
|
||||
- **LLM Input Toggle**: When in use, display of categories and prompt is disabled, allowing user to switch category and save.
|
||||
- **Persistent Storage**: All prompts saved in your ComfyUI user folder
|
||||
<div align="center">
|
||||
<figcaption>Generating Prompts based on Images</figcaption>
|
||||
<img src="docs/images/prompt_generator_image.png" alt="Prompt Generator">
|
||||
</div>
|
||||
|
||||
### Prompt Generator
|
||||
- **Automatic llama.cpp Server Management**: Automatically starts llama.cpp server as needed
|
||||
- **Server Control**: Toggle to stop server after generation (frees VRAM)
|
||||
- **AI-Powered Prompt Enhancement**: Transform basic prompts into detailed, vivid descriptions optimized for image generation
|
||||
- **Local Model Support**: Automatically detects and uses first .gguf model found in the models/guff folder.
|
||||
<div align="center">
|
||||
<figcaption>Advanced Prompt Generation using Multiple Images</figcaption>
|
||||
<img src="docs/images/prompt_generator_advanced.png" alt="Prompt Generator">
|
||||
</div>
|
||||
|
||||
### Prompt Generator Options
|
||||
- **Model Selection**: Choose from local models or download from HuggingFace
|
||||
- **Model Auto-Download**: Easy download of Qwen3 1.7B, 4B, or 8B from HuggingFace.
|
||||
- **LLM Parameters**: Fine-tune temperature, top_k, top_p, min_p, repeat_penalty
|
||||
- **Custom Instructions**: Override default system prompt for different enhancement styles
|
||||
<div align="center">
|
||||
<figcaption>Recipe extraction and modification (Adding a Style LoRA)</figcaption>
|
||||
<img src="docs/images/workflow_builder.png" alt="Recipe Builder">
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<figcaption>Easily find saved Prompts & Recipes using the Built-in File Browser</figcaption>
|
||||
<img src="docs/images/prompt_selector.png" alt="Recipe Builder">
|
||||
</div>
|
||||
|
||||
|
||||
## Toolset Overview
|
||||
|
||||
### Prompt Toolset
|
||||
|
||||
- Prompt Manager: Supports Prompts, LoRA stacks, trigger words and thumbnail for workflows.
|
||||
- Prompt Manager (Basic): Simple no-frills basic version (The OG).
|
||||
- Prompt Generator: prompt creation and enhancement using llama.cpp, Ollama, or a connected ComfyUI CLIP/text encoder.
|
||||
- Prompt Extractor: Reads metadata from images/videos/JSON and outputs prompt + LoRA + recipe context.
|
||||
- Prompt Composer: Build prompts from reusable fragments, with random prompt groups, subject-aware composition, LoRA/RefMod support, and image/video generation modes.
|
||||
- Prompt Layout Builder: Draw boxes over a scene prompt (or load them from an LLM) and output a layout prompt for MOSS-Image, Ideogram 4 or Krea 2.
|
||||
- Prompt Library Hub (sidebar **Prompts** button, can be hidden in Settings): browse, edit, import and export System Prompts, Prompt Snippets, and Saved Compose / Prompts / Layouts / Recipes from one panel, with per-category export.
|
||||
|
||||
### Recipe Toolset (Experimental)
|
||||
These tools were an experiment, with some of the tech now used in other parts of the add-on.
|
||||
- Recipe Extractor: normalizes extracted metadata into reusable `manager_data`.
|
||||
- Recipe Builder: edit and validate recipe data in a cleaner authoring surface.
|
||||
- Recipe Renderer: execute recipe data through built-in generation templates.
|
||||
- Recipe Hub: merge/append model blocks into one `manager_data` and expose each model block as its own output.
|
||||
- Recipe Relay: edit one model block (`model_data`) with seed and LoRA stack overrides.
|
||||
- Recipe Model Loader: resolve and load models from recipe data.
|
||||
- Save and reuse recipes with the **Library Manager** (it replaces the former Recipe Manager).
|
||||
|
||||
## Workflow Examples
|
||||
|
||||
Workflow examples are provided to help understand the basics.
|
||||
|
||||
## Preferences And Settings
|
||||
|
||||
- Addon settings are available in ComfyUI Preferences (Settings) under Prompt Manager.
|
||||
- This is where you set model/backend defaults, NSFW visibility defaults, view preferences, and more.
|
||||
- If you want the Prompt Generator dropdowns to show only your local models, enable `Hide downloadable built-in models` in these settings.
|
||||
- Prompt Generator backend choices (llama.cpp, Ollama) and related options are configured there.
|
||||
- The Prompt Generator's system prompts are fully user-customizable. They're stored in `user/default/prompt_generator_data.json` and can be created and edited with the **Prompt Library Hub** (sidebar) — your custom prompts then show up directly in the Prompt Generator node.
|
||||
|
||||
## Documentation
|
||||
|
||||
- Detailed node reference: [docs/feature-reference.md](docs/feature-reference.md)
|
||||
|
||||
## Prompt Composer
|
||||
|
||||
Prompt Composer is a visual prompt builder for assembling full prompts from reusable fragments such as characters, expressions, attire, action, lighting, ambience, style, environment, and camera.
|
||||
|
||||
The Prompt Composer library now uses a more flexible v2 format built around prompt groups. This makes it much easier to add new groups, organize categories inside them, keep subject behavior per group, and manage larger prompt libraries without relying on the older flat composer JSON layout.
|
||||
|
||||
- Compose output before or after the selected prompt source, or use it on its own.
|
||||
- Return output as plain text or JSON.
|
||||
- Works in both image and video modes. The Video mode being formatted for Minimax.
|
||||
- Prompt fragments can include LoRAs, RefMods, and thumbnails can be generated easily.
|
||||
- Categories and prompt groups support prompt types, prefixes, and subject behavior for cleaner browsing and formatting.
|
||||
- Multi-select can become one random pool or multiple separate prompt parts.
|
||||
- Parts support subject-aware grouping, muting, reordering, merge/split actions, and per-part strength.
|
||||
- Prompt Browser integration supports direct editing, easy creation of new prompt groups, thumbnail generation, export, open, merge flows for older composer data, and reopen behavior that preserves browser state.
|
||||
- Includes an extensive collection of style prompts, including styles based on Reddit user Dear-Spend-2865 prompts.
|
||||
|
||||
Node-side Prompt Composer controls include:
|
||||
|
||||
- Click a fragment to edit or replace it.
|
||||
- Middle click to mute or unmute a fragment.
|
||||
- Ctrl-click to select multiple parts, then right-click to merge compatible selections.
|
||||
- Right-click a merged part to split it back into separate prompts.
|
||||
- Drag and drop parts to reorder them.
|
||||
- Adjust fragment strength directly on the card.
|
||||
|
||||
### Saving And Reloading Composer Workflows
|
||||
|
||||
The **Library Manager** node (formerly Compose Manager, and replacing Recipe Manager) saves and reloads the `manager_data` of **Prompt Manager**, the **Recipe** nodes, **Prompt Composer** and **Prompt Layout Builder**; they all share the `MANAGER_DATA` type. The Prompt Browser marks their entries **P**, **C** and **L** (recipes show under Type: Recipe). Connect Library Manager's `manager_data` to Prompt Composer's `manager_data` input to restore a saved Composer setup.
|
||||
|
||||
To restore a saved Composer setup in **Prompt Composer**, use the **second row of toggles** on the node:
|
||||
|
||||
- **Sync** rebuilds the Prompt Composer graph from the incoming `compose_data`
|
||||
- **Prompt** uses the prompt stored in the incoming `compose_data`
|
||||
- **LoRA** uses the LoRAs stored in the incoming `compose_data`
|
||||
|
||||
This allows `compose_data` to take priority over directly connected prompt and LoRA inputs when those toggles are enabled.
|
||||
|
||||
<div align="center">
|
||||
<figcaption>Use Prompt Composer to build prompts from reusable fragments, including random multi-prompt groups.</figcaption>
|
||||
<img src="docs/images/prompt_composer.jpg" alt="Prompt Composer Example">
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<figcaption>Edit prompts in the browser, attach LoRAs or RefMods, and generate thumbnails for any prompt.</figcaption>
|
||||
<img src="docs/images/prompt_browser_ui.png" alt="Prompt Browser Editor">
|
||||
</div>
|
||||
|
||||
|
||||
## Prompt Layout Builder
|
||||
|
||||
Prompt Layout Builder places the parts of an image in boxes: draw them over a scene prompt, or let the Prompt Generator write the layout for you, then output it in the format your model reads.
|
||||
|
||||
- Each box is an Object, Character, Text (with the exact words to render) or Panel, with its own description and colors. Box descriptions can come from Prompt Composer snippets.
|
||||
- **Output** formats:
|
||||
- **MOSS**: MOSS-Image layout JSON.
|
||||
- **Ideogram**: Ideogram 4 JSON caption, with background, style, lighting and medium fields.
|
||||
- **Krea 2**: Krea 2 grounding lines, with style, medium and background, panels, and character tags and IDs to keep a character consistent across panels. Requires the **krea2-turbo-bbox** model or LoRA, found here: [jimmycarter/krea2-turbo-bbox](https://huggingface.co/jimmycarter/krea2-turbo-bbox). Its PROMPTING.md covers the prompt format and sampler settings.
|
||||
- **Use import_json** loads a layout from the Prompt Generator (system prompts **MOSS Layout**, **Ideogram Layout** and **Krea 2 Layout** in the **Bbox** category, each with Create and From Image versions), from Create Bounding Boxes, or from a layout saved with Library Manager. Turn it off to keep editing the imported boxes.
|
||||
- **Bbox Converter** converts layouts to and from ComfyUI's bounding-box types.
|
||||
|
||||
See [docs/feature-reference.md](docs/feature-reference.md#prompt-layout-builder) for details.
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -34,113 +162,45 @@ A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) that allo
|
||||
```
|
||||
cd ComfyUI/custom_nodes/
|
||||
```
|
||||
|
||||
2. Clone this repository:
|
||||
```bash
|
||||
git clone https://github.com/FranckyB/ComfyUI-Prompt-Manager.git
|
||||
```
|
||||
|
||||
3. Install dependencies:
|
||||
```bash
|
||||
cd ComfyUI-Prompt-Manager
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
4. Install [llama.cpp](https://github.com/ggml-org/llama.cpp/tree/master):
|
||||
- Windows:
|
||||
```bash
|
||||
winget install llama.cpp
|
||||
```
|
||||
This installs the `ggml.llamacpp` package, which ships the official **Vulkan** Windows build (for example `llama-b11946-bin-win-vulkan-x64.zip`), so GPU offload works on NVIDIA / AMD / Intel GPUs with a working Vulkan driver, and falls back to CPU when there is no Vulkan-capable driver.
|
||||
If you want CUDA instead (needed for the node's GPU device selector, and generally the fastest on NVIDIA), download `Windows x64 (CUDA 12/13)` from the [llama.cpp releases](https://github.com/ggml-org/llama.cpp/releases) page, keep its CUDA DLLs next to `llama-server.exe`, and point **Settings → Prompt Manager → 2. Llama Preferences → Custom Llama Path** at that folder.
|
||||
- Linux:
|
||||
```bash
|
||||
brew install llama.cpp
|
||||
```
|
||||
Homebrew builds ggml with **Vulkan** and OpenBLAS on Linux (and Metal on Apple Silicon), so GPU offload works there as well. Otherwise build llama.cpp yourself with `-DGGML_CUDA=ON` (or `-DGGML_VULKAN=ON`) and set **Custom Llama Path** to the build folder.
|
||||
5. Place custom `.gguf` models in models/gguf.
|
||||
- Or use preferences to set a custom path.
|
||||
6. Restart ComfyUI.
|
||||
|
||||
4. Install llama.cpp. It can be found here: [llama.cpp install](https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md)
|
||||
**Checking that your llama.cpp can use the GPU** — run this in a terminal, using the same path the Prompt Generator resolves (it is printed as `llama-server:` in the console):
|
||||
|
||||
5. If you have them, place your .gguf models in the models/gguf folder. (Create folder if not present)
|
||||
```bash
|
||||
llama-server --list-devices
|
||||
```
|
||||
|
||||
If it prints `Available devices:` followed by `CUDA0: ...` or `Vulkan0: ...`, GPU offload works. If it prints `(none)`, that build (or its driver) cannot use your GPU — Prompt Generator will then run the model on CPU and say so at startup.
|
||||
|
||||
**Using the CLIP/text encoder backend**: No additional setup is needed. Connect any ComfyUI `CLIP` output to the Prompt Generator node's `clip` input. When `clip` is connected, the node bypasses llama.cpp/Ollama and generates prompts directly through the text encoder.
|
||||
|
||||
|
||||
6. Restart ComfyUI
|
||||
|
||||
## Usage
|
||||
|
||||
### Prompt Manager
|
||||
|
||||
1. **Add the Node**: Add Node → Prompt Manager
|
||||
2. **Select a Category**: Use the dropdown to choose from your categories
|
||||
3. **Choose a Prompt**: Select a saved prompt from the name dropdown
|
||||
4. **Connect prompt output**: Connect Prompt Manager output to your clip text encode node.
|
||||
|
||||
|
||||
### Prompt Generator
|
||||
|
||||
**Basic Usage** (assuming a model is present in models\gguf):
|
||||
1. **Add the Node**: Add Node → Prompt Generator
|
||||
2. **Connect llm_output to prompt manager**: If you want to save your generated prompt connect to prompt manager.
|
||||
3. **type your prompt**: Type in your basic prompt that will be embelished
|
||||
4. **Save memory**: Toggle "stop_server_after" ON to free VRAM after generation, if seed is set to fix, it won't restart unless prompt changes.
|
||||
4. **Run Workflow**: Once calculated, the prompt will display in the Prompt Manager window and allow you to save it.
|
||||
|
||||
**Advanced Usage**:
|
||||
1. **Add the Options Node**: Add Node → Prompt Generator Options
|
||||
2. **Connect Options**: Connect the options node to the Prompt Generator Options input
|
||||
3. **Select from available models**: Select from models found in your modeld\gguf folder. Qwen models will be available to download.
|
||||
4. **Adjust settings**: Adjust LLM parameters (temperature, top_k, etc.)
|
||||
5. **Customize LLM**: Customize the default LLM instructions to modify the responses llama returns.
|
||||
|
||||
**Size of Qwen models found in options**
|
||||
- Qwen3-1.7B-Q8_0.gguf: Fastest, lowest VRAM (~2GB)
|
||||
- Qwen3-4B-Q8_0.gguf: Balanced performance (~4GB VRAM)
|
||||
- Qwen3-8B-Q8_0.gguf: Best quality, highest VRAM (~8GB)
|
||||
|
||||
**Model Management**:
|
||||
- Place gguf files in models/gguf folder
|
||||
- Downloaded models are also placed in this folder.
|
||||
**Data Location**
|
||||
All data generated by the nodes is saved under user/default folder. The data is saved in JSON format and the thumbnail data is also included, saved as base64 data URL. The node creates a backup folder that keeps 5 daily copies in the hope of preventing any mishap. As the node supports exporting the JSON, be safe and make backups from time to time.
|
||||
|
||||
## Requirements
|
||||
|
||||
- ComfyUI
|
||||
- Python 3.8+
|
||||
- requests >= 2.31.0
|
||||
- huggingface_hub >= 0.20.0
|
||||
- llama-server (from llama.cpp)
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Problem**: Prompts don't appear in the dropdown
|
||||
- **Solution**: Make sure the category has saved prompts. Try creating a new prompt first.
|
||||
|
||||
**Problem**: Changes aren't saved
|
||||
- **Solution**: Click the "Save Prompt" button after making changes. Direct edits in the text field are temporary.
|
||||
|
||||
**Problem**: Can't see LLM output in the node
|
||||
- **Solution**: Make sure the LLM output is connected to the "llm_input" and run the workflow.
|
||||
|
||||
**Problem**: "llama-server command not found"
|
||||
- **Solution**: Install llama.cpp and make sure `llama-server` is available in command line. See [llama.cpp releases](https://github.com/ggerganov/llama.cpp/releases)
|
||||
|
||||
**Problem**: "No models found"
|
||||
- **Solution**: Either place a .gguf file in the `models/` folder, or connect the Prompt Generator Option node and select a model size (1.7B, 4B, or 8B) to download from HuggingFace
|
||||
|
||||
**Problem**: Server won't start
|
||||
- **Solution**: Check that port 8080 is not in use. Close any existing llama-server processes.
|
||||
|
||||
**Problem**: Model download fails
|
||||
- **Solution**: Check your internet connection and HuggingFace availability. Large models may take time to download.
|
||||
|
||||
**Problem**: Generation is slow
|
||||
- **Solution**: Either, Use a smaller quantized model (Q4 instead of Q8) or toggle 'stop_server_after' to quit llama.cpp after generating prompt.
|
||||
|
||||
## Changelog
|
||||
|
||||
### Version 1.5.1
|
||||
- LLM output remains avaiable when use llm is off. So it can be edited
|
||||
- Improved Caching detection, any change to options will be detected and force a new ouput
|
||||
- Improved some UI quirks
|
||||
|
||||
### Version 1.5.0
|
||||
- Added Prompt Generator node with automatic llama.cpp server management
|
||||
- Added Prompt Generator Options node for model selection and parameters
|
||||
- Automatic model detection and auto-download from HuggingFace for Qwen3 models.
|
||||
- VRAM management with optional server shutdown
|
||||
|
||||
### Version 1.1.0
|
||||
- Added LLM input toggle for switching between internal and external text
|
||||
- Made text fields scrollable even when disabled
|
||||
- Fixed reload bugs with toggle state
|
||||
|
||||
### Version 1.0.0
|
||||
- Initial release
|
||||
- Category and prompt management
|
||||
- LLM output integration
|
||||
- huggingface_hub
|
||||
- llama-server, Ollama or Comfy's text encoders (Much Slower)
|
||||
|
||||
@@ -1,30 +1,88 @@
|
||||
"""
|
||||
ComfyUI Prompt Manager - A comprehensive prompt and workflow management system for ComfyUI.
|
||||
Features: prompt & workflow management, LoRA stacks, workflow extraction, workflow generation.
|
||||
"""
|
||||
ComfyUI Prompt Manager - A simple custom node for saving and reusing prompts
|
||||
A prompt management system for ComfyUI with LLM input support
|
||||
"""
|
||||
__version__ = "1.5.1"
|
||||
__version__ = "3.0.0"
|
||||
__author__ = "François Beaudry"
|
||||
__license__ = "MIT"
|
||||
|
||||
from .prompt_manager import PromptManager
|
||||
from .prompt_generator import PromptGenerator
|
||||
from .prompt_generator_options import PromptGenOptions
|
||||
from .py.backup_manager import check_backup
|
||||
from .py.prompt_composer_store import PromptComposerStore
|
||||
from .nodes.prompt_manager_adv import PromptManagerAdvanced
|
||||
from .nodes.prompt_manager_basic import PromptManager
|
||||
from .nodes.prompt_composer import PromptComposer
|
||||
from .nodes.library_manager import LibraryManager
|
||||
from .nodes.prompt_generator import PromptGenerator, PromptGeneratorDataStore
|
||||
from .nodes.prompt_generator_options import PromptGenOptions
|
||||
from .nodes.prompt_generator_kill_switch import PromptGeneratorKillSwitch
|
||||
from .nodes.prompt_extractor import PromptExtractor
|
||||
from .nodes.prompt_layout_builder import PromptLayoutBuilder, BboxConverter
|
||||
from .nodes.prompt_extractor import WorkflowExtractor as RecipeExtractor
|
||||
from .nodes.recipe_builder import RecipeBuilder
|
||||
from .nodes.recipe_renderer import WorkflowRenderer as RecipeRenderer
|
||||
from .nodes.recipe_relay import WorkflowRelay as RecipeRelay
|
||||
from .nodes.recipe_model_loader import WorkflowModelLoader as RecipeModelLoader
|
||||
from .nodes.recipe_model_picker import RecipeModelPicker
|
||||
from .nodes.multi_prompt import RecipeBuilderMultiPrompts
|
||||
from .nodes.multi_lora_stacker import MultiLoraStackerLM, MultiLoraCombine, MultiLoraSplitter, LoraStackCombine
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"PromptManager": PromptManager,
|
||||
"PromptGenerator": PromptGenerator,
|
||||
"PromptGenOptions": PromptGenOptions
|
||||
"PromptManagerAdvanced": PromptManagerAdvanced,
|
||||
"PromptManager": PromptManager,
|
||||
"PromptComposer": PromptComposer,
|
||||
"LibraryManager": LibraryManager,
|
||||
"PromptGenerator": PromptGenerator,
|
||||
"PromptGenOptions": PromptGenOptions,
|
||||
"PromptGeneratorKillSwitch": PromptGeneratorKillSwitch,
|
||||
"PromptExtractor": PromptExtractor,
|
||||
"PromptLayoutBuilder": PromptLayoutBuilder,
|
||||
"BboxConverter": BboxConverter,
|
||||
"RecipeExtractor": RecipeExtractor,
|
||||
"RecipeBuilder": RecipeBuilder,
|
||||
"RecipeRenderer": RecipeRenderer,
|
||||
"RecipeRelay": RecipeRelay,
|
||||
"RecipeModelLoader": RecipeModelLoader,
|
||||
"RecipeModelPicker": RecipeModelPicker,
|
||||
"RecipeBuilderMultiPrompts": RecipeBuilderMultiPrompts,
|
||||
"MultiLoraStackerLM": MultiLoraStackerLM,
|
||||
"MultiLoraCombine": MultiLoraCombine,
|
||||
"MultiLoraSplitter": MultiLoraSplitter,
|
||||
"LoraStackCombine": LoraStackCombine,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"PromptManager": "Prompt Manager",
|
||||
"PromptGenerator": "Prompt Generator",
|
||||
"PromptGenOptions": "Prompt Generator Options"
|
||||
"PromptManagerAdvanced": "Prompt Manager",
|
||||
"PromptManager": "Prompt Manager (Basic)",
|
||||
"PromptComposer": "Prompt Composer",
|
||||
"LibraryManager": "Library Manager",
|
||||
"PromptGenerator": "Prompt Generator",
|
||||
"PromptGenOptions": "Prompt Generator Options",
|
||||
"PromptGeneratorKillSwitch": "Prompt Generator Kill Switch",
|
||||
"PromptExtractor": "Prompt Extractor",
|
||||
"PromptLayoutBuilder": "Prompt Layout Builder",
|
||||
"BboxConverter": "Bbox Converter",
|
||||
"RecipeExtractor": "Recipe Extractor",
|
||||
"RecipeBuilder": "Recipe Builder",
|
||||
"RecipeRenderer": "Recipe Renderer",
|
||||
"RecipeRelay": "Recipe Relay",
|
||||
"RecipeModelLoader": "Recipe Model Loader",
|
||||
"RecipeModelPicker": "Recipe Model Picker",
|
||||
"RecipeBuilderMultiPrompts": "Multi Prompts",
|
||||
"MultiLoraStackerLM": "Multi LoRA Stack",
|
||||
"MultiLoraCombine": "Multi LoRA Combine",
|
||||
"MultiLoraSplitter": "Multi LoRA Splitter",
|
||||
"LoraStackCombine": "LoRA Stack Combine",
|
||||
}
|
||||
|
||||
|
||||
WEB_DIRECTORY = "./js"
|
||||
|
||||
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', 'WEB_DIRECTORY']
|
||||
|
||||
print("[PromptManager] Node registered successfully")
|
||||
# Ensure rotating backups exist for all prompt data files on ComfyUI startup.
|
||||
try:
|
||||
check_backup(PromptManager.get_prompts_path())
|
||||
check_backup(PromptComposerStore.get_data_path())
|
||||
check_backup(PromptGeneratorDataStore.get_data_path())
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Backup initialization skipped: {e}")
|
||||
|
||||
print("[PromptManager] Nodes registered: Prompt Manager, Prompt Composer, Prompt Generator, Prompt Generator Kill Switch, Prompt Extractor, Recipe Extractor, Recipe Builder, Recipe Renderer, Recipe Relay, Library Manager")
|
||||
|
||||
@@ -1,214 +0,0 @@
|
||||
{
|
||||
"Character": {
|
||||
"Cyberpunk Hacker Elite": {
|
||||
"prompt": "A skilled cyberpunk hacker sitting in a dimly lit apartment surrounded by multiple holographic screens displaying code and data streams, wearing tactical tech-wear with embedded LED strips and circuit patterns, augmented reality glasses with information overlays, cybernetic arm implants with exposed mechanical components, messy workstation with scattered computer parts and energy drink cans, large window showing dystopian megacity skyline with towering skyscrapers covered in neon advertisements and holographic billboards, heavy rain creating atmospheric reflections, purple and cyan neon color palette, volumetric fog and light rays, highly detailed futuristic technology, photorealistic rendering, cyberpunk 2077 aesthetic, moody atmospheric lighting, 8k ultra detailed"
|
||||
},
|
||||
"Epic Fantasy Warrior": {
|
||||
"prompt": "A powerful fantasy warrior standing in a heroic pose on a battlefield at dusk, wearing intricately detailed plate armor with ornate engravings and battle-worn scratches, muscular athletic build with defined features, holding a legendary glowing sword with runes etched along the blade, flowing cape billowing in the wind, dramatic cinematic lighting with rays of sunlight breaking through storm clouds, particles of dust and embers floating in the air, photorealistic rendering with exceptional attention to material details including metallic reflections on armor, leather straps and buckles, war paint on face, intense determined expression, epic fantasy art style, 8k ultra high resolution, masterpiece quality"
|
||||
},
|
||||
"Futuristic Sci-Fi Explorer": {
|
||||
"prompt": "A lone futuristic explorer standing on the edge of an alien cliff overlooking a vast extraterrestrial landscape, wearing an advanced high-tech environmental suit with glowing blue energy lines and holographic display panels, sleek helmet with transparent visor showing determined face, multiple utility packs and scientific equipment attached to suit, alien planet with multiple moons visible in the purple-tinted sky, bioluminescent alien flora scattered across rocky terrain, dramatic volumetric lighting with atmospheric fog, neon accents and technological details, sense of wonder and discovery, photorealistic sci-fi concept art style, cinematic composition, 8k resolution, highly detailed textures on suit materials and alien environment"
|
||||
},
|
||||
"Mystical Elven Mage": {
|
||||
"prompt": "An elegant elven sorcerer with flowing silver hair and luminescent purple eyes, wearing elaborate flowing robes made of enchanted fabric with intricate magical runes and celestial patterns, holding an ancient wooden staff topped with a glowing crystal, standing in a mystical forest clearing surrounded by floating magical orbs and swirling ethereal energy, ancient stone ruins covered in moss and glowing elvish inscriptions in background, fireflies and magical particles dancing through the air, moonlight filtering through dense canopy creating dappled light patterns, fantasy illustration style with painterly quality, rich jewel tones and magical bioluminescence, highly detailed character design, masterpiece quality, 8k resolution"
|
||||
},
|
||||
"Noble Medieval Knight": {
|
||||
"prompt": "A distinguished medieval knight in full ceremonial plate armor standing in the grand hall of a castle, armor polished to a mirror shine with gold inlay and family crest emblazoned on chest plate, red velvet cape with golden trim, holding ornate longsword point-down in formal stance, helmet tucked under arm revealing weathered noble face with graying beard, stone castle interior with tall Gothic arched windows, sunlight streaming through stained glass creating colorful patterns on floor, heraldic banners hanging from walls, torch sconces providing warm ambient lighting, sense of honor and nobility, historical accuracy in armor design and architecture, oil painting aesthetic with rich colors, highly detailed, 4k quality"
|
||||
},
|
||||
"Post-Apocalyptic Survivor": {
|
||||
"prompt": "A rugged post-apocalyptic survivor standing among ruins of a destroyed city, wearing makeshift armor cobbled together from scavenged materials including leather, metal plates, and tactical gear, face covered with weathered gas mask with cracked lenses, carrying a modified rifle and worn backpack full of supplies, background showing crumbling skyscrapers overgrown with vegetation, abandoned vehicles rusted and covered in vines, dramatic overcast sky with sun breaking through clouds, dust particles and debris floating in air, desaturated color palette with touches of rust orange and olive green, gritty realistic style, highly detailed weathering and wear on all materials, cinematic composition, 4k photorealistic quality"
|
||||
}
|
||||
},
|
||||
"Composition": {
|
||||
"Aerial Bird's Eye View": {
|
||||
"prompt": "Dramatic overhead composition shot from directly above subject, unique bird's eye perspective offering unusual and striking viewpoint, flattened perspective creating abstract qualities and geometric patterns, symmetry and patterns visible from above, sense of scale with subject appearing small against larger environment, drone photography aesthetic with perfect stability, organized chaos of urban patterns or natural formations, top-down view revealing hidden relationships and structures, professional aerial photography with exceptional detail, sharp focus across entire frame, innovative perspective creating wow factor, cinematic quality, 8k ultra high resolution, perfect exposure and color balance"
|
||||
},
|
||||
"Dynamic Action Scene": {
|
||||
"prompt": "Extreme dynamic composition capturing peak moment of action, subject frozen mid-motion with sense of kinetic energy and movement, dramatic diagonal lines and angles creating visual tension, motion blur on background elements while keeping subject sharp, debris and particles flying through air, forced perspective emphasizing speed and impact, rule of thirds with subject positioned at power point, leading lines directing eye to focal point, sense of chaos controlled through thoughtful composition, high shutter speed photography aesthetic, dramatic depth of field separating subject from background, cinematic framing worthy of movie poster, professional action photography, 8k ultra sharp detail"
|
||||
},
|
||||
"Epic Landscape Vista": {
|
||||
"prompt": "Sweeping panoramic landscape composition showcasing vast scale and grandeur of nature, foreground with detailed elements leading eye into scene, middle ground with points of interest, distant background with atmospheric perspective fading to horizon, dramatic sky occupying upper third of composition, sense of depth created through layering and scale relationships, golden ratio spiral guiding viewer's journey through image, professional landscape photography aesthetic, perfect balance of earth and sky, sense of awe and sublime beauty, Ansel Adams inspired tonal range, 21:9 ultra-wide aspect ratio, maximum dynamic range, 8k ultra high resolution"
|
||||
},
|
||||
"Frame Within Frame": {
|
||||
"prompt": "Creative composition using natural or architectural elements to create frame within the photograph's frame, doorways, windows, arches, or overhanging branches framing main subject, layered composition adding depth and visual interest, vignetting effect drawing attention to central subject, sense of discovery as if viewer is peeking into scene, strategic use of foreground elements to add context and depth, professional composition technique adding sophistication, balance between frame elements and main subject, enhanced three-dimensional quality, painterly aesthetic with careful attention to spatial relationships, selective focus with frame slightly softened, artistic photography style, 4k quality with rich detail"
|
||||
},
|
||||
"Leading Lines Perspective": {
|
||||
"prompt": "Strong compositional technique using leading lines to draw viewer's eye deep into scene, converging lines creating powerful sense of depth and three-dimensional space, linear perspective with prominent vanishing point, roads, pathways, rivers, or architectural elements creating directional flow toward focal point, exaggerated perspective emphasizing distance and scale, wide-angle lens characteristics with slight distortion at edges, journey-like quality inviting exploration, strategic placement of subject at convergence point, professional architectural photography aesthetic, sharp detail from foreground to background, enhanced depth of field, dramatic sense of scale and distance, cinematic composition, 8k ultra detailed"
|
||||
},
|
||||
"Low Angle Power Shot": {
|
||||
"prompt": "Dramatic low angle composition shot from ground level looking upward, subject towering above camera creating sense of power, dominance, and monumentality, exaggerated perspective with converging vertical lines, hero shot aesthetic emphasizing strength and importance, sky or ceiling as background creating clean backdrop, forced perspective making subject appear larger than life, cinematic quality reminiscent of superhero movie posters, dynamic tension from unusual viewpoint, professional photography technique for impactful imagery, wide-angle lens characteristics, dramatic clouds or architectural details in background, epic scale and presence, 8k ultra sharp detail"
|
||||
},
|
||||
"Minimalist Zen Composition": {
|
||||
"prompt": "Clean minimalist composition with abundant negative space, single focal point following principle of ma (negative space) from Japanese aesthetics, careful balance and harmony, limited color palette with subtle variations, geometric simplicity, breathing room around subject, sense of calm and contemplation, influenced by Scandinavian design principles and Japanese wabi-sabi, thoughtful placement following golden ratio, asymmetrical balance, every element serving purpose, no clutter or unnecessary details, modern contemporary art aesthetic, museum-quality presentation, pristine clarity, 4k resolution"
|
||||
},
|
||||
"Rule of Thirds Mastery": {
|
||||
"prompt": "Expert application of rule of thirds compositional technique, subject positioned at intersection points of imaginary grid dividing frame into nine equal parts, horizon line carefully placed along upper or lower third line, key elements strategically positioned along grid lines, negative space balanced across frame, dynamic tension created by off-center placement, professional photography composition creating visual interest, golden ratio principles subtly integrated, perfect balance between subject and environment, sense of movement and energy from asymmetrical placement, cinematic quality worthy of film frame, natural eye flow through image, masterful composition, 8k resolution with exceptional clarity"
|
||||
},
|
||||
"Spiral Composition": {
|
||||
"prompt": "Elegant spiral composition with elements arranged in curved flowing pattern leading eye in circular journey through image, fibonacci spiral or golden spiral guiding placement of key elements, sense of movement and natural flow, dynamic yet harmonious arrangement, organic curved lines contrasting with or complementing subject, shell-like or galaxy-like compositional structure, baroque painting influence with sweeping curves, professional fine art composition creating visual rhythm, balanced yet energetic, eye travels continuously through frame, painterly quality with masterful arrangement, depth created through overlapping curved elements, sophisticated artistic composition, museum quality, 4k resolution"
|
||||
},
|
||||
"Symmetrical Balance Portrait": {
|
||||
"prompt": "Perfectly symmetrical composition with subject centered in frame, bilateral symmetry creating sense of stability and formality, architectural elements framing subject on both sides, mirrored elements balanced left and right, frontal perspective with direct eye contact, classical portrait composition reminiscent of renaissance paintings, vertical orientation emphasizing height and dignity, careful attention to equal weight distribution across frame, geometric precision in placement, formal aesthetic with authoritative presence, balanced color distribution, professional studio portrait photography, sharp focus throughout, medium format camera quality, 4k resolution with exceptional detail"
|
||||
}
|
||||
},
|
||||
"Environment": {
|
||||
"Alien Planet Landscape": {
|
||||
"prompt": "A vast alien planetary landscape featuring bizarre otherworldly geology with towering crystalline formations jutting from the ground, purple and teal-colored soil and rock formations created by exotic mineral compositions, strange alien vegetation with bioluminescent properties growing in unusual fractal patterns, multiple moons of different sizes visible in the sky along with a nearby gas giant planet, alien atmosphere creating unusual light diffraction effects and colorful aurora-like phenomena, exotic weather patterns with unusual cloud formations, distant alien ruins suggesting ancient civilization, sense of wonder and cosmic scale, scientifically plausible exobiology, volumetric atmosphere with unique lighting, photorealistic rendering of fantastical elements, inspired by speculative xenobiology, cinematic composition, 8k ultra high resolution"
|
||||
},
|
||||
"Desert Oasis Settlement": {
|
||||
"prompt": "A thriving desert oasis settlement surrounded by endless golden sand dunes, cluster of traditional mud-brick buildings with flat roofs and decorative arches clustered around a pristine blue pool of water fed by underground springs, palm trees providing shade and greenery, colorful market stalls with fabric awnings selling spices and goods, people in flowing desert robes and head wraps, camels resting near water, mountains visible in distant heat haze, dramatic sunset lighting casting long shadows and painting sky in oranges and purples, sense of refuge and life in harsh environment, Middle Eastern and North African architectural influences, warm earth tone color palette, atmospheric perspective with heat shimmer, highly detailed textures on adobe buildings and desert landscape, photorealistic rendering, 8k resolution"
|
||||
},
|
||||
"Enchanted Ancient Forest": {
|
||||
"prompt": "A mystical ancient forest with towering thousand-year-old trees whose massive trunks are covered in luminescent moss and glowing mushrooms, thick canopy overhead filtering ethereal beams of golden sunlight that illuminate swirling magical particles and floating motes of light, forest floor carpeted with colorful wildflowers and bioluminescent plants that pulse with soft light, weathered stone ruins of an ancient civilization partially reclaimed by nature with intricate carvings still visible, gentle mist rolling through the undergrowth creating atmospheric depth, crystal-clear stream winding through the scene with small waterfalls, fireflies dancing in the air, sense of timeless magic and natural wonder, fantasy illustration style with rich saturated colors, highly detailed vegetation and atmospheric lighting effects, 8k resolution"
|
||||
},
|
||||
"Gothic Cathedral Grand Hall": {
|
||||
"prompt": "Interior of a magnificent Gothic cathedral with soaring vaulted ceilings reaching into darkness, massive stone pillars with intricate carved details and gargoyles, enormous stained glass windows depicting biblical scenes in rich jewel tones casting colorful light patterns across the stone floor, rows of wooden pews leading to ornate altar, burning candles and hanging chandeliers providing warm ambient lighting, morning sunlight streaming through rose window creating dramatic god rays through dust motes in air, sense of awe-inspiring scale and sacred atmosphere, weathered stone showing centuries of history, architectural details including flying buttresses visible through windows, rich tapestries hanging from walls, incense smoke adding atmospheric haze, historical accuracy in medieval architecture, painterly lighting, highly detailed stonework and decorative elements, 4k quality"
|
||||
},
|
||||
"Neon-Lit Cyberpunk Metropolis": {
|
||||
"prompt": "A sprawling cyberpunk megacity at night viewed from an elevated position, endless skyscrapers stretching to the horizon covered in massive holographic advertisements displaying animated corporate logos and products, streets far below bustling with hovering vehicles leaving light trails, neon signs in multiple Asian languages creating a vibrant glow, heavy rain creating reflections on every surface and adding atmospheric moisture, steam venting from industrial grates, layered city architecture showing wealth disparity from gleaming corporate towers to cramped lower-level slums, drone traffic weaving between buildings, atmospheric fog and smog creating volumetric lighting effects, dominant color palette of cyan, magenta, and purple neons contrasted with warm orange street lights, Blade Runner and Ghost in the Shell aesthetic, highly detailed urban environment, photorealistic rendering, 8k resolution"
|
||||
},
|
||||
"Orbital Space Station Interior": {
|
||||
"prompt": "Interior of a massive rotating space station with curved corridors and large observation windows showing breathtaking views of Earth and stars, high-tech modular architecture with clean white and gray surfaces, holographic control panels and floating displays, artificial gravity section with hydroponics gardens growing food, astronauts in modern space suits working on equipment, sense of scale with multiple levels visible, soft blue accent lighting along corridors, scientific equipment and research stations, glimpse of space through massive reinforced windows showing auroras on Earth below, futuristic yet functional design, hard science fiction realism, attention to zero-g engineering details, photorealistic rendering with accurate lighting and materials, inspired by NASA concepts and modern space station design, 8k ultra detailed"
|
||||
},
|
||||
"Steampunk Victorian London": {
|
||||
"prompt": "A Victorian-era London reimagined with steampunk technology, cobblestone streets with brass street lamps emitting warm gas light, elaborate clockwork mechanisms and steam-powered machinery integrated into Gothic architecture, gentlemen in top hats and ladies in corsets walking past shops with copper and brass storefronts, massive airships floating above buildings with visible propellers and steam vents, intricate gear-work visible in building facades, smog and steam creating atmospheric haze, newspaper boys selling penny dreadfuls, horse-drawn carriages sharing streets with steam-powered vehicles, warm amber and bronze color palette, attention to Victorian-era details combined with fantastical brass technology, oil painting aesthetic with rich textures, highly detailed architectural elements, 4k quality"
|
||||
},
|
||||
"Underwater Lost City": {
|
||||
"prompt": "An ancient sunken city deep beneath the ocean surface, classical Greek or Roman architecture colonized by colorful coral and marine life, crumbling marble columns and statues covered in barnacles and swaying sea kelp, schools of tropical fish swimming through broken archways, rays of sunlight penetrating from surface creating dramatic volumetric lighting through the water, particles of sediment floating in currents, giant sea turtles and manta rays gliding past ruins, preserved mosaics and frescoes still visible on walls, sense of lost grandeur and the passage of time, turquoise and deep blue water with caustic light patterns on surfaces, highly detailed underwater environment with accurate water physics and light scattering, photorealistic quality, 8k resolution"
|
||||
}
|
||||
},
|
||||
"Illustrious": {
|
||||
"Anime Girl Portrait": {
|
||||
"prompt": "1girl. A beautiful anime girl gazing directly at the viewer with a gentle smile and soft expression on her face. Her long flowing hair frames delicate features. beautiful detailed eyes, long hair, flowing hair, hair between eyes, looking at viewer, slight smile, soft expression, detailed face, smooth skin, delicate features, jewelry, earrings, necklace, upper body, portrait, depth of field, bokeh, soft lighting, rim lighting, cinematic lighting, anime style, illustration, detailed background, blurred background, masterpiece"
|
||||
},
|
||||
"Beach Swimsuit Summer": {
|
||||
"prompt": "1girl. A carefree girl enjoys a perfect summer day at the beach. Ocean waves lap at the shore behind her as she stands with a bright smile under the sunny sky. Water droplets glisten on her skin in the warm sunlight. bikini, swimsuit, beach, ocean, sea, waves, shore, sand, blue sky, summer, sunny, sunlight, lens flare, beach umbrella, palm tree, standing, hand on hip, wet, wet skin, water droplets, smile, happy, cheerful, straw hat, sun hat, sunglasses, long hair, ponytail, side-tie bikini bottom, frills, ribbon, beautiful detailed face, depth of field, blurry background, bokeh, bright colors, vibrant, warm colors, anime style, masterpiece"
|
||||
},
|
||||
"Café Reading Books": {
|
||||
"prompt": "1girl. A peaceful scene of a girl absorbed in reading at a quiet café. Soft window light illuminates her book as steam rises gently from her cup of tea. The cozy atmosphere and comfortable setting create a perfect moment of tranquil relaxation. sitting, chair, table, café, coffee shop, indoor, window, window light, sunlight, soft lighting, warm lighting, cozy atmosphere, reading, book, holding book, open book, coffee cup, teacup, steam, casual clothes, sweater, cardigan, long sleeves, skirt, pantyhose, sitting cross-legged, relaxed, calm expression, gentle smile, long hair, side ponytail, hair ornament, bookshelf, books, plant, potted plant, depth of field, blurry background, bokeh, peaceful, comfortable, slice of life, anime style, masterpiece"
|
||||
},
|
||||
"Cyberpunk Street Scene": {
|
||||
"prompt": "1girl. A lone figure stands in a rain-soaked cyberpunk street at night. Neon signs reflect off wet pavement while holographic displays flicker in the background. The cityscape towers above with its maze of skyscrapers and glowing advertisements. cyberpunk, neon lights, night, rain, wet, reflections, holographic display, hologram, cyber wear, mechanical parts, augmentation, headphones, hood, hood up, jacket, tech wear, city lights, cityscape, skyscraper, neon sign, japanese text, night sky, depth of field, blurry background, bokeh, rim lighting, ambient lighting, atmospheric, moody, cinematic angle, wide shot, street, alley, puddle, anime style, masterpiece"
|
||||
},
|
||||
"Dragon Girl Fantasy": {
|
||||
"prompt": "1girl. A powerful dragon girl sits regally upon her throne within her treasure-filled lair. Flames and embers dance around her as her wings spread majestically. Her scales shimmer in the dramatic lighting, displaying both her fierce power and noble bearing. dragon girl, dragon horns, horns, dragon tail, tail, dragon wings, wings, scales, pointy ears, elf ears, long hair, very long hair, silver hair, white hair, red eyes, slit pupils, fangs, sharp teeth, claws, fantasy, armor, scale armor, dragon scale armor, dragon themed, castle, throne, dragon hoard, treasure, gold, gems, crystals, cave, lair, dramatic lighting, volumetric lighting, fire, flames, embers, particles, epic, powerful, regal, anime style, detailed scales, masterpiece"
|
||||
},
|
||||
"Elegant Fantasy Princess": {
|
||||
"prompt": "1girl. A regal princess sits gracefully upon her ornate throne in the grand castle hall. Sunlight streams through magnificent stained glass windows, illuminating her elegant gown and sparkling jewelry. She embodies nobility and grace with her gentle smile and refined posture. princess, royalty, crown, tiara, jewelry, ornate jewelry, necklace, earrings, bracelet, elegant dress, ballgown, frills, lace trim, ribbon, puffy sleeves, long sleeves, detached sleeves, white gloves, long gloves, very long hair, wavy hair, blonde hair, blue eyes, detailed eyes, gentle smile, graceful, sitting, throne, castle interior, grand hall, chandelier, stained glass, window, sunlight, light rays, volumetric lighting, depth of field, bokeh, detailed background, fantasy, medieval, regal, noble, anime style, masterpiece"
|
||||
},
|
||||
"Fantasy Battle Scene": {
|
||||
"prompt": "multiple girls, multiple boys. An epic battle scene unfolds with multiple warriors locked in intense combat. Fighters strike dynamic poses with weapons raised and magic crackling through the air. Hair and capes billow in the wind as debris flies through the scene. dynamic pose, action scene, fighting stance, floating hair, motion blur, motion lines, dramatic angle, low angle, dutch angle, wielding sword, magic spell, casting magic, glowing weapon, energy effects, particle effects, debris, dust cloud, destruction, epic scene, cinematic composition, volumetric lighting, dramatic lighting, lens flare, depth of field, fantasy armor, detailed armor, cape, flowing clothes, wind, anime style, masterpiece"
|
||||
},
|
||||
"Gothic Lolita Fashion": {
|
||||
"prompt": "1girl. An elegant gothic lolita stands before a cathedral in her elaborate black dress. She holds a single red rose with pale graceful hands. The dramatic lighting filtering through stained glass creates an atmosphere of dark beauty and refined elegance. gothic lolita, lolita fashion, gothic dress, black dress, frills, lace, ruffles, ribbon, bow, puffy sleeves, long sleeves, detached sleeves, headdress, mini crown, cross, cross necklace, choker, black thighhighs, platform footwear, parasol, lace parasol, very long hair, twin tails, drill hair, curly hair, black hair, red eyes, pale skin, elegant, graceful pose, standing, rose, red rose, holding rose, church, cathedral, stained glass, gothic architecture, dim lighting, dramatic lighting, depth of field, detailed background, anime style, masterpiece"
|
||||
},
|
||||
"Idol Performance Stage": {
|
||||
"prompt": "1girl. An energetic idol performs on stage before a cheering crowd. Colorful spotlights illuminate her as she sings and dances with boundless enthusiasm. Sparkles and glitter fill the air as she strikes a dynamic pose with her microphone. idol, stage outfit, frills, lace, ribbon, bow, gloves, white gloves, microphone, holding microphone, singing, performing, stage, concert, stage lights, spotlights, colorful lighting, dynamic lighting, dramatic lighting, audience, crowd, cheering, energetic, dynamic pose, dancing, motion blur, sparkles, glitter, star \\(symbol\\), heart \\(symbol\\), twin tails, very long hair, gradient hair, colorful hair, bright colors, vibrant colors, smile, wink, one eye closed, cheerful, happy, full body, depth of field, anime style, masterpiece"
|
||||
},
|
||||
"Kimono Traditional Japan": {
|
||||
"prompt": "1girl. An elegant woman in traditional kimono walks gracefully through a beautiful Japanese garden. Autumn leaves drift down around her as koi swim in the pond beside a stone path. The golden hour light creates a warm and culturally rich atmosphere. kimono, japanese clothes, traditional clothes, obi, sash, wide sleeves, long sleeves, floral print, flower pattern, hair ornament, hair flower, kanzashi, long hair, black hair, brown hair, updo, hair bun, elegant, graceful, standing, walking, outdoor, japanese garden, garden, stone path, bridge, pond, koi, water, trees, maple tree, autumn leaves, red leaves, falling leaves, torii gate, shrine, lantern, paper lantern, sunset, golden hour, warm lighting, soft lighting, depth of field, blurry background, traditional, cultural, anime style, masterpiece"
|
||||
},
|
||||
"Magical Girl Transformation": {
|
||||
"prompt": "1girl. A magical girl undergoes her transformation sequence in a dazzling display of light and sparkles. Ribbons and magical particles swirl around her as her elaborate costume materializes. She strikes a heroic pose with outstretched hand against a radiant starburst background. magical girl, transformation sequence, sparkles, glowing, light particles, ribbon, frills, lace, detailed outfit, elaborate costume, twin tails, very long hair, gradient hair, multicolored hair, colorful, vibrant colors, bright colors, star \\(symbol\\), heart \\(symbol\\), dynamic pose, outstretched hand, raised hand, full body, floating, levitating, white background, gradient background, starburst background, bloom effect, light rays, god rays, anime style, masterpiece"
|
||||
},
|
||||
"Maid Cafe Waitress": {
|
||||
"prompt": "1girl. A cheerful maid waitress serves customers at a cozy cafe with a warm welcoming smile. Soft sunlight filters through the windows as she carries a tray with practiced grace. Her frilly uniform and happy expression create an inviting atmosphere. maid, maid headdress, maid apron, frills, lace, ribbon, bow, short sleeves, puffy sleeves, black dress, white apron, wrist cuffs, thighhighs, mary janes, holding tray, serving, indoor, cafe, detailed background, blurry background, depth of field, soft lighting, warm lighting, sunlight, window light, smiling, cheerful, happy, welcoming expression, looking at viewer, anime style, masterpiece"
|
||||
},
|
||||
"Samurai Warrior": {
|
||||
"prompt": "1boy. A skilled samurai warrior stands ready in a dynamic pose, hand on his katana. Cherry blossom petals swirl around him in the wind as the setting sun casts dramatic lighting across his detailed armor. His expression shows unwavering determination and honor. samurai, armor, japanese armor, shoulder armor, armored dress, hakama, hakama skirt, katana, sword, sheathed, holding sword, ponytail, long hair, black hair, serious expression, determined look, standing, dynamic pose, action pose, cherry blossoms, petals, falling petals, torii, shrine, japanese architecture, sunset, dramatic lighting, rim lighting, lens flare, depth of field, wind, dramatic angle, low angle, cinematic composition, anime style, detailed armor, masterpiece"
|
||||
},
|
||||
"School Uniform Casual": {
|
||||
"prompt": "1girl. A cheerful schoolgirl walks through the school grounds on a beautiful spring day. Cherry blossom petals dance in the wind around her as she carries her school bag. The sun shines warmly and her expression is gentle and happy. school uniform, serafuku, sailor collar, pleated skirt, short sleeves, long sleeves, cardigan, bow, bowtie, ribbon, neck ribbon, thighhighs, black thighhighs, loafers, bag, school bag, shoulder bag, standing, walking, outdoors, school, school building, cherry blossoms, falling petals, blue sky, clouds, sunlight, dappled sunlight, soft lighting, wind, wind lift, depth of field, blurry background, smile, happy, gentle expression, anime style, masterpiece"
|
||||
},
|
||||
"Shrine Maiden Miko": {
|
||||
"prompt": "1girl. A serene shrine maiden performs her duties at a peaceful shrine surrounded by nature. Dappled sunlight filters through the trees as cherry blossom petals gently fall around her. She holds a sacred paper charm with a gentle smile and peaceful expression. miko, shrine maiden, traditional clothes, japanese clothes, red hakama, hakama skirt, white kimono, wide sleeves, long sleeves, hair bow, red ribbon, hair tubes, long hair, black hair, brown hair, brown eyes, gentle smile, peaceful expression, holding ofuda, paper charm, shrine, torii gate, stone lantern, japanese architecture, outdoor, nature, forest, trees, sunlight, light rays, dappled sunlight, god rays, peaceful atmosphere, depth of field, soft lighting, cherry blossoms, petals, falling petals, anime style, masterpiece"
|
||||
},
|
||||
"Sleeping Bedroom Night": {
|
||||
"prompt": "1girl. A peaceful sleeping scene bathed in gentle moonlight streaming through the window. The girl rests quietly under soft covers with her hair spread across the pillow. Stars twinkle in the night sky visible through the curtains as she dreams peacefully. sleeping, lying, on side, on bed, bed, bedroom, pillow, blanket, sheet, under covers, pajamas, nightgown, sleepwear, closed eyes, peaceful expression, long hair, messy hair, hair over pillow, indoor, window, curtains, moonlight, night, night sky, stars, starry sky, moon, crescent moon, dim lighting, soft lighting, ambient lighting, calm atmosphere, quiet, serene, peaceful, plushie, stuffed toy, stuffed animal, depth of field, anime style, masterpiece"
|
||||
}
|
||||
},
|
||||
"Lighting": {
|
||||
"Cyberpunk Neon Atmosphere": {
|
||||
"prompt": "Vibrant cyberpunk neon lighting with dominant cyan, magenta, and purple color palette, multiple colored light sources creating complex overlapping shadows and color mixing, neon tubes and LED strips casting intense saturated light, strong rim lighting outlining subjects with colored glows, wet surfaces reflecting and multiplying light sources, volumetric fog and haze making light beams visible, high contrast between bright neon elements and deep dark shadows, futuristic atmospheric lighting with sci-fi mood, color temperature mixing cool blue neons with warm orange accents, Blade Runner inspired aesthetic, moody and atmospheric, cinematic lighting design, photorealistic rendering, 8k quality"
|
||||
},
|
||||
"Dramatic Rembrandt Lighting": {
|
||||
"prompt": "Classic Rembrandt studio lighting setup with strong directional key light at 45-degree angle creating distinctive triangle of light under eye on shadow side of face, deep rich shadows with subtle fill light preserving detail, high contrast ratio for dramatic mood, rim light separating subject from dark background, chiaroscuro technique emphasizing form and dimension through light and shadow, professionally controlled studio environment, classic portrait photography aesthetic, black background emphasizing subject, attention to catchlights in eyes, subtle hair light adding separation, timeless dramatic quality reminiscent of Dutch Golden Age paintings, medium format camera quality, tack-sharp focus, 4k resolution"
|
||||
},
|
||||
"Firelight and Shadows": {
|
||||
"prompt": "Warm intimate lighting from crackling fire as primary light source, rich orange and amber tones dancing across surfaces, dynamic moving shadows creating flickering atmospheric effect, high contrast with deep blacks in areas beyond firelight reach, sense of warmth and comfort, practical light source visible in scene showing glowing embers and flames, subsurface scattering on translucent objects near fire, traditional campfire or hearth setting, reminiscent of classical genre paintings, color temperature around 1800K for authentic firelight, soft smoky haze adding atmosphere, cozy intimate mood, photorealistic fire simulation, highly detailed, 4k quality"
|
||||
},
|
||||
"Golden Hour Magic": {
|
||||
"prompt": "Golden hour lighting during the last hour before sunset, warm golden and amber tones bathing entire scene in beautiful soft light, long dramatic shadows stretching across ground, sun low on horizon creating rim lighting that outlines subjects with glowing edges, soft diffused quality that enhances colors and reduces contrast, sky painted in gradients of gold, orange, pink, and purple, clouds illuminated from below with warm tones, perfect lighting conditions for photography with flattering warm color temperature around 3500K, atmospheric haze adding depth and dimension, lens flare and subtle bloom adding magical quality, professional landscape photography aesthetic, HDR processing for maximum dynamic range, masterpiece quality lighting, 8k resolution"
|
||||
},
|
||||
"Mystical Moonlight": {
|
||||
"prompt": "Ethereal moonlight illuminating scene with cool silvery-blue tones, full moon visible in clear night sky providing primary light source, soft shadows with blue-tinted quality, stars visible in background, atmospheric mist catching and scattering moonlight creating volumetric lighting effects, subtle bioluminescent elements adding touches of green and blue glow, romantic and magical atmosphere, cool color temperature around 4100K, high contrast between moonlit areas and deep shadows, sense of mystery and nocturnal beauty, long exposure photography aesthetic capturing movement of clouds, highly detailed night scene with proper exposure for nighttime conditions, cinematic quality, 8k resolution"
|
||||
},
|
||||
"Overcast Diffused Light": {
|
||||
"prompt": "Soft even illumination from completely overcast sky creating natural softbox effect, shadowless lighting with very gradual subtle transitions, muted desaturated color palette, cool color temperature around 6500K with slight blue-gray cast, perfect even exposure across entire scene, detail preserved in all areas, moody atmospheric quality, sense of calm or melancholy, ideal for showing texture and form without harsh shadows, professional product photography aesthetic, fog or mist adding layers of atmospheric perspective, minimalist Scandinavian lighting aesthetic, clean and modern feel, high dynamic range with subtle gradations, photorealistic rendering, 8k resolution"
|
||||
},
|
||||
"Soft Northern Window Light": {
|
||||
"prompt": "Beautiful soft natural light coming from large northern-facing window, gentle diffused illumination without harsh shadows or direct sunlight, even light distribution creating subtle gradations and soft wraparound lighting, cool color temperature around 5500K with slight blue bias, perfect for accurate color rendition, creates natural realistic appearance, soft shadows with gradual transitions, sense of calm and serenity, ideal for portraits and still life, professional photography studio aesthetic using natural light only, subtle environmental reflections adding fill light, maintains detail in both highlights and shadows, peaceful morning light quality, high dynamic range, 4k photographic quality"
|
||||
},
|
||||
"Volumetric God Rays": {
|
||||
"prompt": "Dramatic volumetric lighting with strong directional sunbeams breaking through clouds or canopy creating visible shafts of light, atmospheric perspective with dust particles, moisture, or fog making light beams clearly visible, high contrast between illuminated rays and darker surrounding areas, sense of divine or spiritual quality, particles floating through light beams catching illumination, depth and dimension created by layered light and shadow, cathedral-like quality to lighting, powerful emotional impact, reminiscent of classical religious paintings, physically accurate light scattering and atmospheric effects, subtle color gradation in light beams from warm to cool, cinematic composition, photorealistic rendering, 8k ultra quality"
|
||||
}
|
||||
},
|
||||
"Mood": {
|
||||
"Dark and Ominous": {
|
||||
"prompt": "Dark foreboding atmosphere with ominous threatening mood, deep shadows dominating composition with limited light sources, desaturated color palette with emphasis on blacks and dark grays, occasional blood red or sickly green accent colors, sense of danger and unease, heavy atmospheric fog or mist obscuring details, Gothic horror aesthetic, dramatic high contrast lighting, unsettling asymmetrical composition, inspired by horror film cinematography and dark fantasy art, volumetric shadows, psychological tension, photorealistic rendering with painterly qualities, 4k quality"
|
||||
},
|
||||
"Energetic and Vibrant": {
|
||||
"prompt": "High-energy dynamic atmosphere bursting with vitality and motion, saturated vibrant colors creating visual excitement, bold contrasts between warm and cool tones, sense of movement and activity throughout composition, dynamic lighting with multiple colorful sources, particles and elements in motion suggesting kinetic energy, fast-paced feeling with diagonal lines and angular composition, celebration of life and action, inspired by pop art and contemporary street photography, youthful exuberant quality, festival or carnival atmosphere, professional commercial photography aesthetic with punchy color grading, sharp details capturing peak moments, 8k ultra high resolution"
|
||||
},
|
||||
"Epic and Grandiose": {
|
||||
"prompt": "Monumental epic atmosphere emphasizing vast scale and dramatic spectacle, sweeping panoramic composition showcasing impressive scope, dramatic sky with storm clouds or spectacular sunset, towering mountains, massive architecture, or other elements dwarfing human scale, sense of awe and sublime beauty, inspired by romantic landscape painting and epic cinema, heroic quality with cinematic grandeur, professional landscape photography with maximum dynamic range, deep depth of field capturing detail from foreground to distant horizon, powerful emotional impact, larger-than-life presence, volumetric lighting with dramatic god rays, rich saturated colors or moody monochromatic palette, 8k ultra high resolution capturing every magnificent detail"
|
||||
},
|
||||
"Ethereal and Dreamlike": {
|
||||
"prompt": "Otherworldly ethereal atmosphere with dreamlike surreal quality, soft diffused lighting creating glowing luminous effect, pale pastel colors or monochromatic schemes, subtle gradients and smooth transitions, fog or mist creating atmospheric depth and mystery, sense of floating or weightlessness, influenced by symbolist painting and fine art photography, magical realism aesthetic, elements of fantasy and imagination, translucent overlapping layers, bokeh and soft focus creating painterly quality, gentle peaceful mood with touch of unreality, professional fine art composition, heavenly or celestial atmosphere, delicate beauty and fragility, museum quality presentation, 4k resolution with exceptional subtlety"
|
||||
},
|
||||
"Gritty and Raw": {
|
||||
"prompt": "Harsh gritty atmosphere emphasizing reality and unpolished authenticity, high contrast lighting with deep blacks and bright highlights, desaturated or monochromatic color palette, visible texture and grain adding tactile quality, urban decay or industrial elements, sense of struggle and perseverance, influenced by documentary photography and photojournalism, uncompromising realistic approach, environmental portraits showing character and history, weathered surfaces and worn materials, professional reportage aesthetic, honest unflinching perspective, dramatic shadows and harsh light, imperfections celebrated rather than hidden, strong emotional impact, cinematic noir quality, 4k resolution with sharp detail capturing every texture"
|
||||
},
|
||||
"Melancholic and Nostalgic": {
|
||||
"prompt": "Bittersweet melancholic atmosphere evoking memories and longing for the past, muted desaturated colors with vintage film aesthetic, soft diffused lighting creating dreamy quality, slight vignetting and faded appearance suggesting passage of time, autumnal or twilight color palette with browns, oranges, and muted blues, sense of solitude and quiet reflection, abandoned or weathered elements suggesting history, inspired by fine art photography and classical painting, emotional depth and introspective quality, gentle sadness mixed with beauty, analog film grain texture, soft focus areas creating romantic haze, timeless contemplative mood, 4k artistic quality"
|
||||
},
|
||||
"Mysterious and Enigmatic": {
|
||||
"prompt": "Mysterious atmospheric quality filled with intrigue and unanswered questions, strategic use of shadows and partial concealment, fog or mist obscuring details and creating layers of depth, cool color temperature with blues, purples, and teals, selective lighting revealing only portions of scene, sense of hidden secrets and untold stories, influenced by film noir and gothic romanticism, dramatic chiaroscuro lighting, silhouettes and backlighting creating ambiguity, professional cinematic atmosphere, elements of the unknown, otherworldly quality, photorealistic rendering with artistic interpretation, high contrast between light and dark areas, 8k resolution with exceptional atmospheric detail"
|
||||
},
|
||||
"Peaceful and Serene": {
|
||||
"prompt": "Calm peaceful atmosphere evoking tranquility and contentment, soft gentle lighting with harmonious balanced colors, pastel or muted earth tone palette, symmetrical or balanced composition creating visual harmony, natural elements like water or sky prominent, sense of stillness and timelessness, meditative quality, inspired by romantic landscape paintings and zen philosophy, warm and inviting feeling, perfect for relaxation and contemplation, subtle gradients and smooth transitions, professional fine art photography aesthetic, museum quality, 8k resolution"
|
||||
},
|
||||
"Warm and Inviting": {
|
||||
"prompt": "Cozy warm atmosphere radiating comfort and hospitality, golden hour lighting or warm interior illumination, rich warm color palette dominated by oranges, yellows, and earth tones, soft shadows creating gentle dimensionality, sense of home and belonging, intimate scale and human-friendly spaces, natural materials like wood and fabric prominent, influenced by lifestyle photography and Scandinavian hygge aesthetic, welcoming emotional quality, perfect for evoking feelings of safety and contentment, professional interior photography with careful attention to ambiance, subtle texture details, inviting composition encouraging viewer to enter scene, 4k quality with warm color grading"
|
||||
},
|
||||
"Whimsical and Playful": {
|
||||
"prompt": "Lighthearted whimsical atmosphere filled with joy and imagination, bright cheerful colors with unexpected combinations, playful composition with tilted angles or unusual perspectives, sense of fun and childlike wonder, elements of surprise and delight, influenced by children's book illustration and contemporary art, fantastical touches mixing reality with imagination, professional commercial photography with creative flair, bouncing light and colorful accents, informal spontaneous quality, sense of movement and energy, optimistic uplifting mood, creative use of props and staging, vibrant saturated colors, sharp focus on delightful details, 8k resolution with exceptional color accuracy and brightness"
|
||||
}
|
||||
},
|
||||
"Style": {
|
||||
"Cinematic Film Quality": {
|
||||
"prompt": "Cinematic film photography style with anamorphic lens characteristics, dramatic shallow depth of field with beautiful bokeh, professional color grading with teal and orange tones, subtle film grain texture, volumetric lighting with god rays and atmospheric haze, dynamic composition following rule of thirds, high contrast lighting with deep shadows and bright highlights, 2.39:1 aspect ratio letterbox framing, shot on ARRI Alexa 65, photorealistic rendering, 8k resolution, masterpiece quality with exceptional attention to lighting and atmosphere"
|
||||
},
|
||||
"Classic Oil Painting": {
|
||||
"prompt": "Traditional oil painting style in the manner of old masters, rich saturated colors with deep shadows and luminous highlights, visible brushwork with thick impasto in light areas and thin glazes in shadows, classical composition with careful attention to form and anatomy, chiaroscuro lighting technique, warm earth tone palette with selective use of vibrant colors, painted on linen canvas with visible texture, museum quality with craquelure aging effects, Renaissance and Baroque artistic influences, painterly realism, masterwork quality worthy of gallery exhibition"
|
||||
},
|
||||
"Concept Art Illustration": {
|
||||
"prompt": "Professional concept art illustration style used in AAA video game and film production, dynamic composition with strong focal point, atmospheric perspective with detailed foreground and painterly background, digital painting technique with custom brushes, strategic use of lighting to guide viewer's eye, color script with mood-appropriate palette, blend of realistic rendering and artistic interpretation, subtle texture overlays, clean lines with detailed callouts and annotations where needed, portfolio-quality artwork, 4k resolution optimized for production pipeline, industry-standard visual development artwork"
|
||||
},
|
||||
"Detailed Watercolor Art": {
|
||||
"prompt": "Professional watercolor painting technique with translucent layered washes, delicate color transitions and gradients, wet-on-wet blending creating soft atmospheric effects, strategic use of white space and paper texture showing through, detailed foreground elements with looser background washes, granulation and blooming effects in pigments, cold-press watercolor paper texture, artistic mastery of water control, luminous transparent colors, traditional botanical illustration precision combined with loose expressive passages, flowing organic shapes, high-end art print quality, 300 DPI resolution"
|
||||
},
|
||||
"Impressionist Painting": {
|
||||
"prompt": "Impressionist oil painting style reminiscent of Claude Monet and Pierre-Auguste Renoir, visible loose brushstrokes with textured impasto technique, vibrant color palette with emphasis on light and its changing qualities, dappled sunlight effects, soft edges and forms that blend together, focus on capturing momentary impression rather than fine details, colors applied in short strokes of pure unmixed paint, canvas texture visible, plein air painting aesthetic, masterful use of complementary colors, atmospheric perspective, traditional fine art quality, museum-worthy composition"
|
||||
},
|
||||
"Japanese Ukiyo-e Woodblock": {
|
||||
"prompt": "Traditional Japanese ukiyo-e woodblock print style, bold outlines with flat areas of color, limited color palette featuring indigo blues, vermillion reds, and ivory, stylized clouds and waves with distinctive patterns, attention to textile patterns and decorative elements, asymmetrical composition with strong diagonals, influence of Hokusai and Hiroshige, grain texture of woodblock printing, subtle color gradations through bokashi technique, Japanese aesthetic principles of wabi-sabi and mono no aware, artistic quality of Edo period prints, suitable for museum collection"
|
||||
},
|
||||
"Ultra Photorealistic": {
|
||||
"prompt": "Ultra photorealistic rendering with exceptional attention to every minute detail, 8k resolution with pixel-perfect clarity, physically accurate materials and lighting using ray tracing technology, subsurface scattering on skin and translucent materials, realistic depth of field and chromatic aberration, perfect exposure with natural lighting, micro-details including skin pores, fabric weave patterns, metal scratches and imperfections, dust particles in air, moisture and reflections, professional photography composition, shot with Canon EOS R5 with 85mm f/1.2 lens, indistinguishable from high-end commercial photography"
|
||||
},
|
||||
"Vintage Analog Photography": {
|
||||
"prompt": "Vintage analog film photography aesthetic, shot on Kodak Portra 400 or Fujifilm Pro 400H film stock, natural grain structure, slightly faded colors with characteristic film color shifts, vignetting on corners, subtle light leaks and lens flares, soft focus dreamy quality, dated timestamp or border frame, nostalgic 1970s-1990s color palette, imperfect exposure with authentic film limitations, scanned from 35mm negatives, warm golden tones, authentic vintage photograph appearance with all the charm and imperfections of film photography"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
# Changelog
|
||||
|
||||
## version 3.0.1
|
||||
- **Prompt Generator: GPU detection fix for Windows (and recent llama.cpp builds)**
|
||||
- `--n-gpu-layers 0` is no longer forced just because GPU support could not be detected. On Windows the old check always failed (`ldd` does not exist there, `--version` no longer names the backend, and `-h` lists `--n-gpu-layers` on every build), which pushed CUDA users into CPU inference and printed a misleading "CPU-only build" error.
|
||||
- Detection now asks llama.cpp itself with `--list-devices`, and falls back to the GPU backend libraries next to the binary (`ggml-cuda.dll` etc.) or `ldd` on Linux.
|
||||
- Console output now distinguishes "no GPU device in this build" (warning, CPU is correct) from "unknown" (offload is requested and llama.cpp decides).
|
||||
- README: corrected install notes (winget `ggml.llamacpp` ships the official **Vulkan** build, Homebrew builds ggml with Vulkan/OpenBLAS on Linux and Metal on Apple Silicon) and added a `llama-server --list-devices` check.
|
||||
|
||||
## version 3.0.0
|
||||
- **Breaking: one `MANAGER_DATA` type**
|
||||
- Prompt Manager, Prompt Composer, Prompt Layout Builder and the Recipe nodes now share `manager_data` (replaces `RECIPE_DATA` and `COMPOSE_DATA`). Older workflows need these links reconnected.
|
||||
- Recipe Renderer outputs `output_image`, `output_latent`, `manager_data`; Recipe Extractor outputs `image`, `manager_data`.
|
||||
- **New Library Manager** (replaces Composition Manager and Recipe Manager)
|
||||
- Saves and reloads the `manager_data` of Prompt Manager, the Recipe nodes, Prompt Composer and Prompt Layout Builder, with thumbnails.
|
||||
- Filters for All / Prompt / Recipe / Compose / Layout.
|
||||
- **New Prompt Library Hub** (sidebar **Prompts** button, can be hidden in Settings)
|
||||
- Replaces the Prompt Browser node, which has been removed.
|
||||
- Browse & Edit, Import and Export for Saved Prompts (Prompt Manager / Prompt Composer / Prompt Layout / Prompt Recipe), Saved Snippets and Saved System Prompts.
|
||||
- Per-category export; Snippets and System Prompts can also be replaced from a file, and System Prompts can restore the built-in defaults.
|
||||
- **New Prompt Layout Builder**
|
||||
- Draw Object, Character, Text and Panel boxes over a scene prompt, or load them from an LLM.
|
||||
- Outputs MOSS-Image layout JSON, Ideogram 4 JSON captions or Krea 2 grounding lines (needs [krea2-turbo-bbox](https://huggingface.co/jimmycarter/krea2-turbo-bbox)).
|
||||
- `import_json` reads all three formats, Create Bounding Boxes elements, and layouts saved with Library Manager.
|
||||
- Box descriptions can come from Prompt Composer snippets.
|
||||
- **New Bbox Converter**: converts a layout JSON to bounding boxes and elements, or bounding boxes back to a layout JSON.
|
||||
- **Prompt Generator**
|
||||
- The system prompt dropdown is replaced by a selector: arrows cycle through prompts, the name opens the Prompt Browser.
|
||||
- New **Bbox** category with **MOSS Layout**, **Ideogram Layout** and **Krea 2 Layout** system prompts (Create and From Image).
|
||||
- Fixed: the selected system prompt was reset to Enhance Prompt when reopening a workflow or switching tabs if the prompt was added or moved after the page loaded. Prompts moved to another category are now found by name.
|
||||
- **Prompt Manager and editor**
|
||||
- Export only selected categories.
|
||||
- Preferred model settings, draft handling and clearer save/rename buttons in the prompt editor.
|
||||
- Improved NSFW handling in the browser.
|
||||
- **Prompt Composer**
|
||||
- Prompt text tooltips, clear muted parts, RefMod rows.
|
||||
- Picker renamed to "Select Prompt Snippet".
|
||||
- Customizable thumbnail generation steps.
|
||||
- Nodes 2.0 compatibility.
|
||||
- Larger text across the node UIs.
|
||||
- New Krea layout example workflow.
|
||||
|
||||
## version 2.8.0
|
||||
- **Prompt Composer v2**
|
||||
- New library format built around prompt groups, with a dialog to create groups and pick their category.
|
||||
- Output as text or JSON, before or after the selected prompt, or on its own.
|
||||
- Image and video generation modes.
|
||||
- Subject numbers and subject types, mute for prompt parts.
|
||||
- Export and import of composer libraries; new Generate Bulk Snippets system prompt.
|
||||
- **Prompt Composer Manager** to save and reload Composer setups with thumbnails.
|
||||
- Input prompt and LoRA modes on Prompt Composer and Prompt Manager, so compose data passing through Prompt Manager can add LoRAs and be saved for reuse.
|
||||
- **Prompt Browser**: double-click to select, Home button, more responsive dialogs.
|
||||
- Anima family support for thumbnail rendering.
|
||||
- Preference to hide the downloadable built-in models in Prompt Generator.
|
||||
- llama-server GPU support detection.
|
||||
- Trigger word fixes: only connected words are pruned, words saved with the prompt are kept.
|
||||
- Fixed LoRA stack cards collapsing or stretching to viewport height (thanks Martlet-Tech).
|
||||
- Prompt Composer example workflows.
|
||||
|
||||
## version 2.7.2
|
||||
- LoRA blacklist keywords for MiniMax and distilled LoRAs.
|
||||
- Prompt Generator code moved to its own `prompt_generator.js`.
|
||||
- Converter for the older system prompt storage format.
|
||||
- README and feature reference updates.
|
||||
|
||||
## version 2.7.1
|
||||
- Prompt text widgets become read-only while an external prompt input is connected; the received prompt is shown after execution.
|
||||
- Prompt Extractor accepts a video input.
|
||||
- Video prompt writing guides for MiniMax.
|
||||
- Prompt Generator input prompt handling and model management improvements.
|
||||
|
||||
## version 2.7.0
|
||||
- **New Prompt Composer** (started as Prompt Mixer): build prompts from multiple reusable parts.
|
||||
- **System prompts are now user data**
|
||||
- Stored in `prompt_generator_data.json` and editable in the Prompt Browser, grouped by category.
|
||||
- New default system prompts for image and video models.
|
||||
- **Prompt Browser**: multi-select, category type filter, scrolling category bar, view modes, unsaved-changes confirmation, bulk prompt builder.
|
||||
- **llama.cpp** (thanks sophosympatheia)
|
||||
- GPU device selection for multi-GPU systems.
|
||||
- Fixed the server port ignoring the saved setting.
|
||||
- Models and mmproj files are found in subfolders.
|
||||
- Rotating backups for prompt data files.
|
||||
- VRAM flush fixes when using a CLIP/text encoder.
|
||||
|
||||
## version 2.6.0
|
||||
- Prompt Generator can use a connected CLIP/text encoder directly.
|
||||
- Expression Selector: arrow navigation and strength slider.
|
||||
- Multi LoRA Stacker: configurable stack count.
|
||||
- Krea2 example workflow.
|
||||
|
||||
## version 2.5.4
|
||||
- **Prompt Manager Advanced browser overhaul**
|
||||
- Larger non-compact prompt browser with bigger 3:4 thumbnails.
|
||||
- New browser view modes: Grid, Icon (small grid), and List.
|
||||
- View mode is persisted in the browser and no longer controlled by a preference default.
|
||||
- Compact browser size can still be restored via Preferences.
|
||||
- **Krea2 thumbnail generation support**
|
||||
- Recipe Renderer now supports the Krea2 family for thumbnail renders.
|
||||
- **New Expression Selector node**
|
||||
- Appends a saved Expression-category prompt to an input prompt.
|
||||
- Supports gender-aware pronoun substitution.
|
||||
- Add new expressions directly through Prompt Manager Advanced.
|
||||
- Select `(none)` to pass the input prompt through unchanged.
|
||||
|
||||
## version 2.5.3
|
||||
- **Improved Prompt Extractor to better match FBNodes image loader+**
|
||||
- Can now browse any folder and can view in detail, normal and large Thumbnails.
|
||||
|
||||
## version 2.5.2
|
||||
- **Improved LLM prompts in Prompt Generator**
|
||||
- New System prompts for Video and Audio Generation
|
||||
|
||||
## version 2.5.0
|
||||
- **Recipe Builder is now Multi-model Only**
|
||||
- Expanded Builder authoring around `recipe_data` with slot-aware model blocks (`model_a`/`model_b`/`model_c`/`model_d`).
|
||||
- Improved cross-slot behavior for prompts, LoRAs, sampler settings, and resolution handling in multi-model workflows.
|
||||
- **Authoritative Builder extraction flow**
|
||||
- Extraction now preserves Builder-authored v2 model data as the source of truth when embedded Builder v2 metadata is present.
|
||||
- Added compatibility safeguards so legacy/non-v2 workflows continue to use fallback extraction logic.
|
||||
- **Builder lock/reset and execution consistency**
|
||||
- Improved update and execute behavior so incoming recipe values, lock states, and current UI values resolve more predictably.
|
||||
- Strength/reset handling was tightened for better consistency across slot updates and reruns.
|
||||
- **New LoRA utility node: MultiLoraCombine**
|
||||
- Added `MultiLoraCombine` to merge optional multi-stack input with optional stack A/B/C/D inputs into a single `MULTI_LORA_STACK` output.
|
||||
- Helps consolidate mixed LoRA sources for multi-model Builder and downstream recipe flows.
|
||||
- **New feature: Multi LoRA Stacker with Lora-Manager compatibility**
|
||||
- Added a new Multi LoRA Stacker for slot-aware and multi-stack recipe flows.
|
||||
- Compatible with [Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager), including interoperability with managed LoRA selections and previews.
|
||||
|
||||
## version 2.2.0
|
||||
- **Recipe_data v2 expansion and slot-aware workflows**
|
||||
- Expanded v2 compatibility across Builder, Relay, Renderer, Manager, and extraction utilities.
|
||||
- Improved model slot behavior for `model_a`/`model_b`/`model_c`/`model_d`, including WAN pair handling.
|
||||
- **Recipe Builder Update flow and persistence improvements**
|
||||
- Update Recipe now respects Pull From selection consistently and supports expected clear behavior for empty/none selections.
|
||||
- Pull From / Send To state persistence improved across tab switches and workflow reloads.
|
||||
- Update Recipe visibility refined to avoid incomplete Builder-to-Builder pull paths.
|
||||
- **LoRA synchronization and execution-order fixes**
|
||||
- Fixed connected LoRA add/remove timing so `recipe_data` reflects changes on first execute.
|
||||
- Improved LoRA state authority between connected inputs and persisted UI overrides.
|
||||
- **Renderer validation hardening**
|
||||
- Renderer now fails fast with a clear error when the selected model slot is undefined.
|
||||
- Prevents silent renders from empty/non-existent selected model slots.
|
||||
- **Prompt Generator GPU utilization and VRAM prep**
|
||||
- Ensured llama.cpp server launch uses `-ngl 100` so generation is pushed to GPU as much as possible.
|
||||
- Added more aggressive cache/VRAM flushing before generation to reduce memory pressure and improve run reliability.
|
||||
|
||||
## version 2.1.1
|
||||
- Updated Documentation
|
||||
- Bug fixes
|
||||
|
||||
## version 2.1.0
|
||||
- **Naming Migration: Workflow -> Recipe**
|
||||
- Renamed node/toolset terminology to Recipe naming across the addon UI and docs.
|
||||
- Bug fixes.
|
||||
|
||||
## version 2.0.2
|
||||
- Added Ernie family support in Workflow Builder/Renderer.
|
||||
- Bug fixes.
|
||||
|
||||
## version 2.0.1
|
||||
- **Added Denoise options to Workflow Pipeline**
|
||||
- Workflow data now contains denoise value (Extractor returns 1 by default).
|
||||
- Allows mid-run model handoff using KSampler denoise.
|
||||
- Bug fixes.
|
||||
|
||||
## version 2.0.0
|
||||
- **Prompt Manager becomes Prompt + Workflow Manager**
|
||||
- Workflow Manager allows saving workflow and integrates with Prompt Manager save/reuse behavior.
|
||||
- Extractor/Builder/Manager workflow loop focused on simplified reusable workflow cores.
|
||||
- recipe_data-first persistence improvements.
|
||||
- Documentation updates.
|
||||
|
||||
## version 1.25.0
|
||||
- **Workflow Tools Release Milestone**
|
||||
- Workflow Builder / Workflow Renderer / Workflow Bridge / Workflow Model Loader form a complete editable workflow pipeline.
|
||||
- Improved extractor-to-builder update flow.
|
||||
- Improved Builder dropdown stability and persistence.
|
||||
- Improved tab-switch persistence for Builder UI state.
|
||||
- Improved compatibility with Builder persistence extraction.
|
||||
- **Wan i2v workflow quality and UX improvements**
|
||||
- **Prompt Manager Advanced save + thumbnail improvements**
|
||||
|
||||
## version 1.22.6
|
||||
- Prompt Extractor now embeds extracted data in workflow so it can extract itself.
|
||||
|
||||
## version 1.22.5
|
||||
- Thumbnail generation in Prompt Manager Advanced.
|
||||
- Improved model high/low detection.
|
||||
|
||||
## version 1.22.1
|
||||
- Prompt Model Loader improvements, including GGUF support and persistence improvements.
|
||||
|
||||
## version 1.22.0
|
||||
- New node: Prompt Model Loader.
|
||||
- Expanded model/checkpoint extraction in Prompt Extractor.
|
||||
- A1111/Forge image support improvements.
|
||||
- WebP metadata support improvements.
|
||||
- Video metadata parsing improvements.
|
||||
|
||||
## version 1.21.x to 1.0.0
|
||||
Older historical entries were previously listed in README and can still be recovered from repository history.
|
||||
@@ -0,0 +1,178 @@
|
||||
**This documentation is ongoing and will continue to improve**
|
||||
|
||||
### Prompt Manager
|
||||
Allows for Saving and Loading prompts quickly using the Prompt Browser UI.
|
||||
- Clicking the Blue Prompt Name button, under the text area, will open the Prompt Browser.
|
||||
- Pressing the < > on each side of the button will quickly switch to the next prompt.
|
||||
- **In Prompt Browser mode:**
|
||||
- Click the + to create new Categories.
|
||||
- Generate Thumbnails for Prompts or Categories (Right Click)
|
||||
- If not set, a Pop Up will ask you to select the model to use for generation.
|
||||
- Enable Edit mode to enable writing Prompts directly in the Browser.
|
||||
- Be sure to save the prompt before generating its thumbnail
|
||||
- Right click provides other options such as:
|
||||
- Tagging as NSFW (filtering by default can be enabled in prefs)
|
||||
- Moving or Renaming
|
||||
- Pasting an image in as a Prompt
|
||||
- Generating a thumbnail for a Prompt
|
||||
- It is also possible to simply drag an image over a prompt to replace its Thumbnail.
|
||||
- **On the node's Main UI:**
|
||||
- Use Prompt input toggle to display incoming prompt (from Prompt Generator for example).
|
||||
- Toggling off allows editing that new prompt.
|
||||
- Use LoRA input allows choosing which LoRAs are used:
|
||||
- Prompt LoRAs Only: This turns off any LoRAs connected to our node.
|
||||
- Combine LoRAs: This uses both the prompt and incoming LoRAs, but will remove duplicates.
|
||||
- Input LoRAs Only: For those times when you want just the Prompt but use your own new recipe.
|
||||
- **Do note: If a prompt is saved again, this can change the LoRAs assigned to the Prompt**
|
||||
- LoRA Support:
|
||||
- Supports the Add-On LoRA Manager to display LoRA Thumbnails on Hover.
|
||||
- LoRA input supports either Traditional LoRA Stackers or the new included Multi LoRA Stack.
|
||||
- Using normal LoRA Stackers, two stacks of LoRAs can be used and will be displayed in our UI.
|
||||
- Connecting Multi LoRA Stack instead allows up to four stacks to be displayed.
|
||||
- Multi LoRA Stack uses the LoRA Manager add-on at its core and is needed for it to work.
|
||||
- When LoRAs are used, the UI will display them as tags, allowing strength editing or toggling On or Off.
|
||||
- A list of Trigger words can be connected and will be displayed as Tags that can be toggled On or Off.
|
||||
- LoRAs are saved with prompt entries; this includes their state (On or Off) as well as their Strength.
|
||||
- Missing LoRAs will be displayed as Red.
|
||||
- The Save Button opens up the Prompt Browser, allowing saving under any category.
|
||||
- The New Prompt Button is practical when you want to clear everything, including LoRAs, and start fresh.
|
||||
- The More button allows access to Exporting your Saved Prompt, but also merging another JSON. Be careful.
|
||||
|
||||
### Prompt Manager (Basic)
|
||||
A simpler no frills version that supports only Prompts. (This is the OG node)
|
||||
- Select category and prompt using a purely comfy UI.
|
||||
- If saving over an existing prompt, LoRAs and Thumbnails will be preserved.
|
||||
- If NSFW filtering is enabled, NSFW Prompts will be hidden.
|
||||
- LLM input toggle works similar to full node.
|
||||
|
||||
|
||||
### Prompt Generator
|
||||
Generates prompts using a local LLM. Supports either Llama.cpp or Ollama, but can also be used directly with Comfy's Text encoders.
|
||||
Allows downloading of 3 different sizes of Unsloth's Qwen 3.5, but users are free to add more models in models/gguf. If found, the add-on will list them. (Refresh when adding new ones)
|
||||
|
||||
- Comes with a bundle of pre-made System Prompts.
|
||||
- Use the arrows beside the system prompt name to cycle through saved prompts across categories, or click the name to open Prompt Browser on System Prompts. When loading workflows, legacy names such as `Enhance Prompt (Image)` are matched to current entries. Missing prompts fall back to `Image / Enhance Prompt` (or the first available entry if that default was removed), without changing other widget values.
|
||||
- Create your own system prompts with the **Prompt Library Hub** (sidebar) or by clicking the system prompt name
|
||||
- I highly recommend using the **rgthree add-on** and enable *"Auto Nest Subdirectories in Menus"*. This will display categories as submenus.
|
||||
- Options to output in JSON format and enable Thinking mode.
|
||||
- The stop_server_after toggle:
|
||||
- Kills Llama.cpp after generating the prompt
|
||||
- Tries to force Ollama to unload the current model
|
||||
- The clear_vram_on_run toggle:
|
||||
- Unloads Comfy's model from memory before generating the prompt
|
||||
- Clears Vram again once the prompt is generated.
|
||||
- It is recommended to leave on, unless you are using small models
|
||||
- Both Stop_server and clear_vram are ignored when using Text encoders, as we instead let Comfy manage the VRAM.
|
||||
- Expected llama.cpp startup failures log one actionable summary without a console traceback. Enable **Show everything in Console** in Prompt Generator Options and retry to see the traceback, full launch command, and server stderr. The workflow still fails normally, and unexpected errors retain their tracebacks.
|
||||
- Lastly, the **Model Selection**:
|
||||
- (Use Default): Uses the default model set in preferences, or the first found, if not set.
|
||||
- Missing saved model selections fall back to the default selection with a console warning. If no suitable model is available, generation still reports an error.
|
||||
- 3 Different Quant size of Qwen 3.5 can be automatically downloaded.
|
||||
- Any models you add in models/gguf, or any custom folder if set in preferences.
|
||||
- If you no longer want to see the built-in download entries, enable the `Hide downloadable built-in models` preference under Prompt Manager settings.
|
||||
- For Multi-image support, connect the Generator Option node.
|
||||
- Use the Prompt Generator Options node for controlling model parameters.
|
||||
|
||||
### Prompt Generator Options
|
||||
This node provides extra control to **Prompt Generator** and is NOT mandatory.
|
||||
- Modify the selected system prompt, by either appending extra instructions or replacing it entirely.
|
||||
- Provides extra images input for a Total of 5.
|
||||
- Change the System settings for the model
|
||||
- Change the GPU used by the LLM
|
||||
|
||||
### Prompt Library Hub
|
||||
The **Prompts** button in ComfyUI's left sidebar opens the Prompt Library Hub (hide it with Settings > Prompt Manager > 4. Advanced Preferences > Show Prompts Sidebar Button): one place to browse, edit, import and export every Prompt Manager library. It has three sections:
|
||||
- **Saved Prompts**: pick the type with the Prompt Manager / Prompt Composer / Prompt Layout / Prompt Recipe buttons (saved through Prompt Manager or Library Manager).
|
||||
- **Saved Snippets**: the snippets used by Prompt Composer.
|
||||
- **Saved System Prompts**: the system prompts used by Prompt Generator.
|
||||
|
||||
Every section has the same three buttons:
|
||||
- **Browse & Edit**: opens the Prompt Browser on that library with the Edit tab on.
|
||||
- **Import**: merge a file; when entries already exist you choose to keep or overwrite them. Snippets and System Prompts can also be replaced from a file, and System Prompts can restore the built-in defaults (adds back missing built-in prompts without touching yours). Saved Prompt types share one file, so they only merge.
|
||||
- **Export**: pick the categories to export as one JSON file (Snippets export selected prompt groups as a ZIP).
|
||||
|
||||
The Prompt Generator's system prompts are stored in *prompt_generator_data.json*, so you can author your own. Built-in prompts added by updates can be brought into your saved system prompts with **Restore defaults**.
|
||||
|
||||
### Prompt Extractor
|
||||
Extract prompt, model, and LoRA info out of images, videos, and JSON workflow files.
|
||||
- Supports ComfyUI, A1111/Forge, and WebP metadata formats.
|
||||
- Grabs the frame of your choice from videos using a time slider.
|
||||
- Dual LoRA stack extraction for compatible workflows.
|
||||
- Can browse from either the input or output folders directly.
|
||||
- Can also be used as an advanced media loader with metadata awareness
|
||||
|
||||
### Prompt Layout Builder
|
||||
Draw a layout of boxes over a scene prompt, or load one from an LLM, and output it as a layout prompt for MOSS-Image, Ideogram 4 or Krea 2.
|
||||
- The canvas follows the aspect ratio and megapixels, or a connected image's ratio with **Use Reference Ratio**. A connected image is also shown behind the boxes.
|
||||
- Draw, move and resize boxes on the canvas, or type exact x/y/width/height values. Each box is an **Object**, **Character**, **Text** (with the exact words to render) or **Panel** (shown in Krea 2 mode), with a description and an optional color palette.
|
||||
- The thumbnail button beside a description picks a Prompt Composer snippet for the box.
|
||||
- Full screen editor, grid overlay, canvas text size, undo/redo (Ctrl/Cmd+Z), duplicate (Ctrl/Cmd+D) and delete (Del).
|
||||
- A hint lists what is missing, such as a box without a description.
|
||||
- **Output** formats:
|
||||
- **MOSS**: MOSS-Image layout JSON (the same format as the core MOSS-Image Layout Prompt), with meta tags, canvas type and palettes.
|
||||
- **Ideogram**: Ideogram 4 JSON caption (the same format as Build JSON Prompt (Ideogram)), with background, photo or art style, aesthetics, lighting, medium and a style palette.
|
||||
- **Krea 2**: Krea 2 grounding lines: a one-sentence summary, `@style; medium`, `~background`, then one line per box (panels first). Character boxes get a Person / Anime character / Furry tag and an optional ID; reuse the ID to keep the same character across panels. Requires the **krea2-turbo-bbox** model or LoRA, found here: [jimmycarter/krea2-turbo-bbox](https://huggingface.co/jimmycarter/krea2-turbo-bbox). See its PROMPTING.md for the prompt format and sampler settings.
|
||||
- **Use import_json** reads the layout from `import_json` and locks the editor. It accepts layout JSON (percent, 0-1000 or MOSS-native boxes), Ideogram 4 captions, Krea 2 grounding lines, Create Bounding Boxes elements, or a saved layout's `manager_data` from Library Manager. Turn it off to keep editing the imported boxes.
|
||||
- Prompt Generator system prompts for layouts (**Bbox** category): **MOSS Layout**, **Ideogram Layout** and **Krea 2 Layout**, each with **Create** and **From Image** versions. If they are missing, use **Restore defaults** for System Prompts in the Prompt Library Hub.
|
||||
- Outputs: prompt, preview (the boxes drawn over the canvas), width, height and `manager_data` (save it with Library Manager).
|
||||
- **Bbox Converter** converts layouts to and from ComfyUI's bounding-box types, so the builder can be chained with other box nodes. Connect a `layout_json` (any format the builder imports) or `bboxes` (bounding boxes, Create Bounding Boxes elements or their JSON); with both connected, a toggle picks the source. It outputs `layout_json` (passed through, or a percent layout when converting bboxes, without a prompt), pixel `bboxes` and `elements`.
|
||||
|
||||
## Recipe Toolset (Experimental)
|
||||
|
||||
The Recipe Toolset are a set of experimental nodes to lets you build, manage, and rerun reusable pipelines. You can write recipes from scratch in Builder, combine them with Prompt Manager / Prompt Manager Advanced to reuse saved prompts, or import existing metadata through Extractor when you want to bootstrap from something you already made. Then saved them as complete Recipes.
|
||||
|
||||
As Stated these were an experiment into improving Manager, but as been put aside a bit. The technology behind it is what allowed for Thumbnail Generation in Prompt Browser. The Recipe Relay node is great when creating slick workflows with a single link between subgraph, as it can stack 4 workflows of data in a single connection.
|
||||
|
||||
### Recipe Builder
|
||||
The main place to create or tweak recipes.
|
||||
- Build or modify recipes from scratch in one central spot.
|
||||
- Inspect and adjust recipe fields without wiring every parameter by hand.
|
||||
- Use it standalone, or connect it with other recipe/prompt nodes.
|
||||
- Works well with Prompt Manager so saved prompts can be slotted into recipe-driven pipelines.
|
||||
- Great for iterative tuning: extract once, keep tweaking values and rerendering until the pipeline feels right.
|
||||
- Helps standardize presets so repeated jobs start from the same known-good setup.
|
||||
|
||||
### Recipe Extractor
|
||||
Reads and normalizes workflow metadata into reusable recipe data.
|
||||
- Converts raw generation metadata into a cleaner recipe format that's easier to edit and pass between nodes.
|
||||
- Keeps important settings intact when moving from one-off runs to reusable setups.
|
||||
- Useful when you want to recreate a look/style from an existing output and iterate from there.
|
||||
|
||||
### Recipe Renderer
|
||||
Runs recipe-driven generation so you can rerun pipelines quickly.
|
||||
- Interprets recipe data during execution to reproduce prior results or batch variants with minimal manual work.
|
||||
- Cuts down setup time for repeated jobs by moving configuration into reusable recipe data.
|
||||
- Especially handy when testing different prompts or inputs while keeping the same core recipe.
|
||||
|
||||
### Recipe Relay
|
||||
A clean handoff point for recipe data between nodes.
|
||||
- Passes recipe data and compatible context across the graph.
|
||||
- Keeps larger graphs modular and easier to follow.
|
||||
- Preserves context through the pipeline, so you don't lose recipe continuity when splitting graphs into stages.
|
||||
|
||||
### Recipe Model Loader
|
||||
Loads models/checkpoints based on recipe data.
|
||||
- Resolves model selections encoded in recipes so execution follows the intended model path automatically.
|
||||
- Supports model slot selection and loader-specific behavior.
|
||||
- Makes recipe playback more reliable across sessions by tying loader behavior to the saved recipe, not memory.
|
||||
- Useful for multi-model pipelines where model choice is part of the recipe itself.
|
||||
|
||||
### Saving Recipes (Library Manager)
|
||||
Recipe nodes pass their data as `manager_data`, the same type used by Prompt Manager, Prompt Composer and Prompt Layout Builder. Save, browse, and reuse recipes with the **Library Manager** (it replaces the former Recipe Manager).
|
||||
- Persistent recipe storage so successful setups can be cataloged and recalled quickly.
|
||||
- Works with Builder for quick review and updates.
|
||||
- Encourages a library-style workflow: capture working recipes, name/tag them, and reapply them across projects.
|
||||
- Good for keeping repeatable production presets while still allowing safe edits over time.
|
||||
|
||||
## Model Family Support
|
||||
|
||||
Built-in support includes:
|
||||
- Flux 1
|
||||
- Flux 2
|
||||
- Ernie
|
||||
- SDXL
|
||||
- Wan
|
||||
- Qwen
|
||||
- Z-Image
|
||||
- Wan Image
|
||||
- Wan Video (I2V and T2V)
|
||||
|
After Width: | Height: | Size: 531 KiB |
|
After Width: | Height: | Size: 758 KiB |
|
After Width: | Height: | Size: 830 KiB |
|
After Width: | Height: | Size: 766 KiB |
|
After Width: | Height: | Size: 670 KiB |
|
After Width: | Height: | Size: 743 KiB |
|
After Width: | Height: | Size: 280 KiB |
|
After Width: | Height: | Size: 1.2 MiB |
|
Before Width: | Height: | Size: 64 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 50 KiB |
|
After Width: | Height: | Size: 95 KiB |
|
After Width: | Height: | Size: 72 KiB |
|
After Width: | Height: | Size: 102 KiB |
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 142 KiB |
|
After Width: | Height: | Size: 433 KiB |
|
After Width: | Height: | Size: 538 KiB |
|
After Width: | Height: | Size: 668 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 5.5 KiB |
@@ -0,0 +1,950 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
import { PM_UI_PALETTE } from "./ui_palette.js";
|
||||
|
||||
const NODE_CLASS = "MultiLoraStackerLM";
|
||||
const LM_PROVIDER_CLASS = "Lora Stacker (LoraManager)";
|
||||
const STYLE_ID = "pm-multi-lm-style";
|
||||
const MIN_NODE_WIDTH = 320;
|
||||
const MIN_NODE_HEIGHT = 320;
|
||||
const DEFAULT_NODE_WIDTH = 600;
|
||||
const DEFAULT_NODE_HEIGHT = 430;
|
||||
const MIN_STACK_COUNT = 1;
|
||||
const MAX_STACK_COUNT = 4;
|
||||
const DEFAULT_STACK_COUNT = 2;
|
||||
// Height constants mirroring LM's loras_widget_utils.js
|
||||
const LM_LORA_ENTRY_H = 40;
|
||||
const LM_HEADER_H = 32;
|
||||
const LM_CONTAINER_PAD = 12;
|
||||
const LM_EMPTY_H = 100;
|
||||
const FAST_PREVIEW_DELAY_MS = 20;
|
||||
// Per-column chrome: title(22) + search textarea(50) + col padding(16)
|
||||
const COL_CHROME_H = 88;
|
||||
|
||||
let loraCodeListenerAttached = false;
|
||||
let promptSerializationPatched = false;
|
||||
|
||||
const SLOT_DEFS = [
|
||||
{ key: "model_a", label: "Model A", short: "A", state: "loras_state_a" },
|
||||
{ key: "model_b", label: "Model B", short: "B", state: "loras_state_b" },
|
||||
{ key: "model_c", label: "Model C", short: "C", state: "loras_state_c" },
|
||||
{ key: "model_d", label: "Model D", short: "D", state: "loras_state_d" },
|
||||
];
|
||||
|
||||
let lmBridgePromise = null;
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Styles
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function ensureStyles() {
|
||||
if (document.getElementById(STYLE_ID)) return;
|
||||
const p = PM_UI_PALETTE || {};
|
||||
const panel = p.panel || "hsl(216 11% 15%)";
|
||||
const panelBorder = p.panelBorder || "hsl(216 20% 65% / 0.24)";
|
||||
const inputBg = p.inputBg || "hsl(220 15% 10%)";
|
||||
const inputBorder = p.inputBorder || "hsl(218 10% 41%)";
|
||||
const textHeading = p.textHeading || "hsl(220 13% 85%)";
|
||||
const textPrimary = p.textPrimary || "hsl(0 0% 87%)";
|
||||
const textHint = p.textHint || "hsl(216 15% 65%)";
|
||||
const cardBg = p.cardBg || "hsl(219 16% 18%)";
|
||||
const accentBorder = "rgba(255,255,255,0.98)";
|
||||
const accentSoft = "rgba(255,255,255,0.42)";
|
||||
|
||||
const style = document.createElement("style");
|
||||
style.id = STYLE_ID;
|
||||
style.textContent = `
|
||||
.pm-multi-lm-root {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
box-sizing: border-box;
|
||||
padding: 6px 6px 6px 6px;
|
||||
overflow: visible;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
position: relative;
|
||||
}
|
||||
.pm-multi-lm-root,
|
||||
.pm-multi-lm-root * {
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
.pm-multi-lm-root::-webkit-scrollbar,
|
||||
.pm-multi-lm-root *::-webkit-scrollbar {
|
||||
width: 0;
|
||||
height: 0;
|
||||
display: none;
|
||||
}
|
||||
.pm-multi-lm-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(200px, 1fr));
|
||||
gap: 8px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
align-items: stretch;
|
||||
margin-top: -16px;
|
||||
}
|
||||
.pm-multi-lm-topbar {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: flex-start;
|
||||
position: absolute;
|
||||
left: 8px;
|
||||
top: -48px;
|
||||
z-index: 2;
|
||||
margin-top: 0;
|
||||
margin-bottom: 0;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.pm-multi-lm-stack-control {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
border: 1px solid ${panelBorder};
|
||||
border-radius: 8px;
|
||||
background: ${panel};
|
||||
padding: 5px 8px;
|
||||
}
|
||||
.pm-multi-lm-stack-label {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.02em;
|
||||
color: ${textHeading};
|
||||
user-select: none;
|
||||
}
|
||||
.pm-multi-lm-stepper {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.pm-multi-lm-step-btn {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border: 1px solid ${inputBorder};
|
||||
border-radius: 5px;
|
||||
background: ${inputBg};
|
||||
color: ${textPrimary};
|
||||
font-size: 14px;
|
||||
line-height: 1;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
.pm-multi-lm-step-btn:hover {
|
||||
border-color: ${textHeading};
|
||||
}
|
||||
.pm-multi-lm-step-btn:disabled {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
.pm-multi-lm-step-value {
|
||||
min-width: 16px;
|
||||
text-align: center;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
line-height: 1.1;
|
||||
color: hsl(0 0% 100%);
|
||||
font-variant-numeric: tabular-nums;
|
||||
user-select: none;
|
||||
}
|
||||
.pm-multi-lm-col {
|
||||
border: 1px solid ${panelBorder};
|
||||
border-radius: 8px;
|
||||
background: ${panel};
|
||||
padding: 8px;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
min-height: 0;
|
||||
height: 100%;
|
||||
}
|
||||
.pm-multi-lm-col.active-slot {
|
||||
border-color: ${accentBorder};
|
||||
box-shadow: inset 0 0 0 1px ${accentSoft};
|
||||
}
|
||||
.pm-multi-lm-col.active-slot .pm-multi-lm-title {
|
||||
color: ${accentBorder};
|
||||
}
|
||||
.pm-multi-lm-title {
|
||||
font-weight: 700;
|
||||
font-size: 14px;
|
||||
letter-spacing: 0.02em;
|
||||
color: ${textHeading};
|
||||
margin-bottom: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.pm-multi-lm-search {
|
||||
width: 100%;
|
||||
min-height: 38px;
|
||||
resize: vertical;
|
||||
box-sizing: border-box;
|
||||
border: 1px solid ${inputBorder};
|
||||
border-radius: 6px;
|
||||
padding: 6px 8px;
|
||||
background: ${inputBg};
|
||||
color: ${textPrimary};
|
||||
margin-bottom: 6px;
|
||||
font-size: 14px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.pm-multi-lm-search::placeholder {
|
||||
color: ${textHint};
|
||||
}
|
||||
.pm-multi-lm-list-host {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
.pm-multi-lm-list-host .lm-loras-container {
|
||||
height: 100%;
|
||||
max-height: none;
|
||||
background: ${cardBg};
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
.pm-multi-lm-list-host::-webkit-scrollbar,
|
||||
.pm-multi-lm-list-host .lm-loras-container::-webkit-scrollbar {
|
||||
width: 0;
|
||||
height: 0;
|
||||
display: none;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// LM bridge loader
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function loadLmBridge() {
|
||||
if (lmBridgePromise) return lmBridgePromise;
|
||||
lmBridgePromise = Promise.all([
|
||||
import("/extensions/ComfyUI-Lora-Manager/autocomplete.js"),
|
||||
import("/extensions/ComfyUI-Lora-Manager/loras_widget.js"),
|
||||
import("/extensions/ComfyUI-Lora-Manager/utils.js"),
|
||||
import("/extensions/ComfyUI-Lora-Manager/lora_syntax_utils.js"),
|
||||
import("/extensions/ComfyUI-Lora-Manager/preview_tooltip.js"),
|
||||
]).then(([autocompleteMod, lorasWidgetMod, utilsMod, syntaxMod, previewTooltipMod]) => ({
|
||||
AutoComplete: autocompleteMod.AutoComplete,
|
||||
addLorasWidget: lorasWidgetMod.addLorasWidget,
|
||||
mergeLoras: utilsMod.mergeLoras,
|
||||
applyLoraValuesToText: syntaxMod.applyLoraValuesToText,
|
||||
PreviewTooltip: previewTooltipMod.PreviewTooltip,
|
||||
})).catch((err) => {
|
||||
console.warn("[PromptManager] Failed to load Lora-Manager bridge modules", err);
|
||||
lmBridgePromise = null;
|
||||
return null;
|
||||
});
|
||||
return lmBridgePromise;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Widget helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function getWidgetByName(node, name) {
|
||||
if (!node || !Array.isArray(node.widgets)) return null;
|
||||
return node.widgets.find((w) => w && w.name === name) ?? null;
|
||||
}
|
||||
|
||||
function ensureStateWidget(node, name) {
|
||||
let widget = getWidgetByName(node, name);
|
||||
if (widget) return widget;
|
||||
if (!node || typeof node.addWidget !== "function") return null;
|
||||
return node.addWidget("text", name, "[]", null, { multiline: true });
|
||||
}
|
||||
|
||||
function hideWidget(widget) {
|
||||
if (!widget || widget.__pm_hidden) return;
|
||||
widget.__pm_hidden = true;
|
||||
// Keep original widget type (STRING) so graphToPrompt includes state values.
|
||||
widget.hidden = true;
|
||||
widget.computeSize = () => [0, -4];
|
||||
widget.draw = function () {};
|
||||
if (widget.element) widget.element.style.display = "none";
|
||||
}
|
||||
|
||||
function hideStateWidgets(node) {
|
||||
if (!node || !Array.isArray(node.widgets)) return;
|
||||
for (const widget of node.widgets) {
|
||||
if (!widget || widget.name === "multi_lora_ui") continue;
|
||||
hideWidget(widget);
|
||||
}
|
||||
}
|
||||
|
||||
function parseLorasState(value) {
|
||||
if (Array.isArray(value)) return value;
|
||||
if (value && typeof value === "object" && Array.isArray(value.__value__)) {
|
||||
return value.__value__;
|
||||
}
|
||||
if (value && typeof value === "object" && typeof value.__value__ === "string") {
|
||||
try {
|
||||
const parsed = JSON.parse(value.__value__);
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch (_e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
if (typeof value !== "string") return [];
|
||||
const raw = value.trim();
|
||||
if (!raw || raw === "[]") return [];
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return Array.isArray(parsed) ? parsed : [];
|
||||
} catch (_e) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function writeLorasState(widget, listValue) {
|
||||
if (!widget) return;
|
||||
widget.value = JSON.stringify(Array.isArray(listValue) ? listValue : []);
|
||||
}
|
||||
|
||||
function getSlotByKey(node, slotKey) {
|
||||
if (!node || !Array.isArray(node.__pmMultiLmSlots)) return null;
|
||||
return node.__pmMultiLmSlots.find((s) => s && s.key === slotKey) ?? null;
|
||||
}
|
||||
|
||||
function clampStackCount(value) {
|
||||
const n = Number(value);
|
||||
if (!Number.isFinite(n)) return DEFAULT_STACK_COUNT;
|
||||
return Math.max(MIN_STACK_COUNT, Math.min(MAX_STACK_COUNT, Math.round(n)));
|
||||
}
|
||||
|
||||
function getStackCount(node) {
|
||||
const raw = node?.properties?.pmLoraStackCount;
|
||||
return clampStackCount(raw ?? DEFAULT_STACK_COUNT);
|
||||
}
|
||||
|
||||
function getVisibleSlotKeys(node) {
|
||||
const count = getStackCount(node);
|
||||
return SLOT_DEFS.slice(0, count).map((s) => s.key);
|
||||
}
|
||||
|
||||
function syncStackCountWidget(node, count) {
|
||||
const widget = getWidgetByName(node, "stack_count");
|
||||
if (widget) widget.value = count;
|
||||
}
|
||||
|
||||
function ensureActiveSlotVisible(node) {
|
||||
if (!node || !node.properties) return;
|
||||
const visible = getVisibleSlotKeys(node);
|
||||
if (visible.length === 0) return;
|
||||
if (!visible.includes(node.properties.pmActiveSlot)) {
|
||||
node.properties.pmActiveSlot = visible[0];
|
||||
}
|
||||
}
|
||||
|
||||
function updateStackControlUi(node) {
|
||||
const refs = node?.__pmStackControl;
|
||||
if (!refs) return;
|
||||
const count = getStackCount(node);
|
||||
refs.value.textContent = String(count);
|
||||
refs.dec.disabled = count <= MIN_STACK_COUNT;
|
||||
refs.inc.disabled = count >= MAX_STACK_COUNT;
|
||||
}
|
||||
|
||||
function applyVisibleStackCount(node) {
|
||||
const slots = node?.__pmMultiLmSlots;
|
||||
const grid = node?.__pmMultiLmGrid;
|
||||
if (!Array.isArray(slots) || !grid) return;
|
||||
|
||||
const visible = new Set(getVisibleSlotKeys(node));
|
||||
const visibleCount = visible.size || DEFAULT_STACK_COUNT;
|
||||
grid.style.gridTemplateColumns = `repeat(${visibleCount}, minmax(200px, 1fr))`;
|
||||
|
||||
for (const slot of slots) {
|
||||
if (!slot?.col) continue;
|
||||
slot.col.style.display = visible.has(slot.key) ? "flex" : "none";
|
||||
}
|
||||
}
|
||||
|
||||
function setStackCount(node, value) {
|
||||
if (!node) return;
|
||||
if (!node.properties) node.properties = {};
|
||||
node.properties.pmLoraStackCount = clampStackCount(value);
|
||||
ensureActiveSlotVisible(node);
|
||||
applyVisibleStackCount(node);
|
||||
updateStackControlUi(node);
|
||||
syncStackCountWidget(node, node.properties.pmLoraStackCount);
|
||||
updateActiveColumnHighlight(node);
|
||||
notifyHeightChange(node);
|
||||
applyNodeSizeConstraints(node, false, true);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Apply incoming lora code to a slot
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function applyIncomingLoraCode(node, slotKey, code, mode) {
|
||||
if (!node || typeof code !== "string") return;
|
||||
const slot = getSlotByKey(node, slotKey);
|
||||
if (!slot || !slot.searchInput) return;
|
||||
const current = String(slot.searchInput.value || "");
|
||||
slot.searchInput.value = (mode === "replace" || !current) ? code : `${current}\n${code}`;
|
||||
slot.searchInput.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// lora_code_update listener (attached once, synchronously)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function attachLoraCodeListener() {
|
||||
if (loraCodeListenerAttached) return;
|
||||
loraCodeListenerAttached = true;
|
||||
|
||||
api.addEventListener("lora_code_update", (event) => {
|
||||
const detail = event?.detail;
|
||||
if (!detail) return;
|
||||
|
||||
const nodeId = Number(detail.id);
|
||||
if (!Number.isFinite(nodeId) || nodeId < 0) return;
|
||||
|
||||
const loraCode = typeof detail.lora_code === "string" ? detail.lora_code : "";
|
||||
const mode = typeof detail.mode === "string" ? detail.mode : "append";
|
||||
|
||||
// Find our node by integer ID
|
||||
const nodes = app.graph?._nodes;
|
||||
if (!Array.isArray(nodes)) return;
|
||||
const targetNode = nodes.find((n) => Number(n.id) === nodeId && n.type === NODE_CLASS);
|
||||
if (!targetNode) return;
|
||||
|
||||
// Route to the currently-selected active slot
|
||||
const activeSlot = targetNode.properties?.pmActiveSlot ?? "model_a";
|
||||
applyIncomingLoraCode(targetNode, activeSlot, loraCode, mode);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Prompt serialization shim:
|
||||
// Keep LM comfyClass for manager integration, but serialize this node as its
|
||||
// real backend class so ComfyUI validates against MultiLoraStackerLM inputs.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function attachPromptSerializationShim() {
|
||||
if (promptSerializationPatched) return;
|
||||
if (!app || typeof app.graphToPrompt !== "function") return;
|
||||
|
||||
promptSerializationPatched = true;
|
||||
const originalGraphToPrompt = app.graphToPrompt.bind(app);
|
||||
|
||||
app.graphToPrompt = async function (...args) {
|
||||
const swapped = [];
|
||||
const nodes = app.graph?._nodes;
|
||||
|
||||
if (Array.isArray(nodes)) {
|
||||
for (const node of nodes) {
|
||||
if (!node || node.type !== NODE_CLASS) continue;
|
||||
if (node.comfyClass !== LM_PROVIDER_CLASS) continue;
|
||||
swapped.push(node);
|
||||
node.comfyClass = NODE_CLASS;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
return await originalGraphToPrompt(...args);
|
||||
} finally {
|
||||
for (const node of swapped) {
|
||||
node.comfyClass = LM_PROVIDER_CLASS;
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Active-slot selection (click a section to target LM sends)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function setActiveSlot(node, slotKey) {
|
||||
if (!node) return;
|
||||
if (!node.properties) node.properties = {};
|
||||
node.properties.pmActiveSlot = slotKey;
|
||||
updateActiveColumnHighlight(node);
|
||||
}
|
||||
|
||||
function updateActiveColumnHighlight(node) {
|
||||
if (!Array.isArray(node.__pmMultiLmSlots)) return;
|
||||
ensureActiveSlotVisible(node);
|
||||
const activeSlot = node.properties?.pmActiveSlot ?? "model_a";
|
||||
const visible = new Set(getVisibleSlotKeys(node));
|
||||
for (const slot of node.__pmMultiLmSlots) {
|
||||
if (slot?.col) {
|
||||
const isActive = slot.key === activeSlot && visible.has(slot.key);
|
||||
slot.col.classList.toggle("active-slot", isActive);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Embedded loras widget via fakeNode pattern
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function createEmbeddedLorasWidget(node, lm, widgetName, initialValue, onChange) {
|
||||
const host = document.createElement("div");
|
||||
host.className = "pm-multi-lm-list-host";
|
||||
|
||||
const fakeNode = {
|
||||
addDOMWidget(name, type, container, options) {
|
||||
return {
|
||||
name,
|
||||
type,
|
||||
callback: null,
|
||||
element: container,
|
||||
get value() {
|
||||
return typeof options?.getValue === "function" ? options.getValue() : [];
|
||||
},
|
||||
set value(v) {
|
||||
if (typeof options?.setValue === "function") options.setValue(v);
|
||||
},
|
||||
};
|
||||
},
|
||||
setDirtyCanvas(fg, bg) { node?.setDirtyCanvas?.(fg, bg); },
|
||||
};
|
||||
|
||||
const out = lm.addLorasWidget(fakeNode, widgetName, {}, onChange);
|
||||
if (out?.widget?.element) host.appendChild(out.widget.element);
|
||||
if (out?.widget && Array.isArray(initialValue) && initialValue.length > 0) {
|
||||
out.widget.value = initialValue;
|
||||
}
|
||||
|
||||
const fastPreviewCleanup = attachFastPreviewHandlers(host, lm);
|
||||
|
||||
return { host, widget: out?.widget ?? null, fastPreviewCleanup };
|
||||
}
|
||||
|
||||
function attachFastPreviewHandlers(host, lm) {
|
||||
if (!host || typeof lm?.PreviewTooltip !== "function") {
|
||||
return () => {};
|
||||
}
|
||||
|
||||
const tooltip = new lm.PreviewTooltip({ modelType: "loras" });
|
||||
const processed = new WeakSet();
|
||||
|
||||
const bindNameEl = (nameEl) => {
|
||||
if (!nameEl || processed.has(nameEl)) return;
|
||||
processed.add(nameEl);
|
||||
|
||||
// Replace LM's delayed listeners on this element with a faster local one.
|
||||
const replacement = nameEl.cloneNode(true);
|
||||
const triggerEl = nameEl.closest(".lm-lora-entry") || nameEl.parentElement || replacement;
|
||||
let previewTimer = null;
|
||||
|
||||
const clearPreviewTimer = () => {
|
||||
if (previewTimer) {
|
||||
clearTimeout(previewTimer);
|
||||
previewTimer = null;
|
||||
}
|
||||
};
|
||||
|
||||
triggerEl.addEventListener("mouseenter", () => {
|
||||
clearPreviewTimer();
|
||||
previewTimer = setTimeout(async () => {
|
||||
previewTimer = null;
|
||||
const name = String(replacement.textContent || "").trim();
|
||||
if (!name) return;
|
||||
const rect = triggerEl.getBoundingClientRect();
|
||||
try {
|
||||
await tooltip.show(name, rect.right, rect.top);
|
||||
} catch (_e) {
|
||||
}
|
||||
}, FAST_PREVIEW_DELAY_MS);
|
||||
});
|
||||
|
||||
triggerEl.addEventListener("mouseleave", () => {
|
||||
clearPreviewTimer();
|
||||
tooltip.hide();
|
||||
});
|
||||
|
||||
nameEl.replaceWith(replacement);
|
||||
processed.add(replacement);
|
||||
};
|
||||
|
||||
const bindAll = () => {
|
||||
const nameEls = host.querySelectorAll(".lm-lora-name");
|
||||
for (const nameEl of nameEls) bindNameEl(nameEl);
|
||||
};
|
||||
|
||||
bindAll();
|
||||
|
||||
const observer = new MutationObserver(() => {
|
||||
bindAll();
|
||||
});
|
||||
observer.observe(host, { childList: true, subtree: true });
|
||||
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
tooltip.hide();
|
||||
tooltip.cleanup();
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Height management — mirrors LM's updateWidgetHeight approach:
|
||||
// set CSS vars on the root element so ComfyUI's layout system resizes the node,
|
||||
// never calling node.setSize() (which would prevent user resize).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function computeContentHeight(node) {
|
||||
let maxListH = LM_EMPTY_H;
|
||||
const visible = new Set(getVisibleSlotKeys(node));
|
||||
if (Array.isArray(node.__pmMultiLmSlots)) {
|
||||
for (const slot of node.__pmMultiLmSlots) {
|
||||
if (!visible.has(slot.key)) continue;
|
||||
const count = Array.isArray(slot.lorasWidget?.value) ? slot.lorasWidget.value.length : 0;
|
||||
const h = count === 0
|
||||
? LM_EMPTY_H
|
||||
: LM_CONTAINER_PAD + LM_HEADER_H + Math.min(count, 12) * LM_LORA_ENTRY_H;
|
||||
if (h > maxListH) maxListH = h;
|
||||
}
|
||||
}
|
||||
return COL_CHROME_H + maxListH + 56;
|
||||
}
|
||||
|
||||
function notifyHeightChange(node) {
|
||||
const root = node?.__pmMultiLmRoot;
|
||||
if (!root) return;
|
||||
const h = computeContentHeight(node);
|
||||
root.style.setProperty('--comfy-widget-min-height', `${h}px`);
|
||||
root.style.setProperty('--comfy-widget-height', `${h}px`);
|
||||
applyNodeSizeConstraints(node);
|
||||
setTimeout(() => { node?.setDirtyCanvas?.(true, true); }, 10);
|
||||
}
|
||||
|
||||
function applyNodeSizeConstraints(node, useDefaultSize = false, forceWidth = false) {
|
||||
if (!node || node.__pmApplyingSizeConstraint) return;
|
||||
|
||||
const currentW = Number(node?.size?.[0]) || 0;
|
||||
const currentH = Number(node?.size?.[1]) || 0;
|
||||
|
||||
const minW = MIN_NODE_WIDTH * getStackCount(node);
|
||||
|
||||
const targetW = forceWidth
|
||||
? minW
|
||||
: (useDefaultSize
|
||||
? Math.max(DEFAULT_NODE_WIDTH, minW, currentW)
|
||||
: Math.max(minW, currentW));
|
||||
|
||||
const targetH = useDefaultSize
|
||||
? Math.max(DEFAULT_NODE_HEIGHT, MIN_NODE_HEIGHT, currentH)
|
||||
: Math.max(MIN_NODE_HEIGHT, currentH);
|
||||
|
||||
if (targetW === currentW && targetH === currentH) return;
|
||||
|
||||
node.__pmApplyingSizeConstraint = true;
|
||||
try {
|
||||
node.setSize([targetW, targetH]);
|
||||
} finally {
|
||||
node.__pmApplyingSizeConstraint = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Per-slot column builder
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function buildSlotColumn(node, lm, slotDef) {
|
||||
const stateWidget = ensureStateWidget(node, slotDef.state);
|
||||
hideWidget(stateWidget);
|
||||
|
||||
const col = document.createElement("div");
|
||||
col.className = "pm-multi-lm-col";
|
||||
col.title = `Click to make ${slotDef.label} the LoRA Manager target`;
|
||||
col.addEventListener("pointerdown", () => setActiveSlot(node, slotDef.key));
|
||||
|
||||
const title = document.createElement("div");
|
||||
title.className = "pm-multi-lm-title";
|
||||
title.textContent = slotDef.label;
|
||||
|
||||
const searchInput = document.createElement("textarea");
|
||||
searchInput.className = "pm-multi-lm-search";
|
||||
searchInput.placeholder = "Search LoRAs to add\u2026";
|
||||
searchInput.rows = 1;
|
||||
searchInput.addEventListener("focus", () => setActiveSlot(node, slotDef.key));
|
||||
|
||||
// Attach LM autocomplete to the search textarea
|
||||
new lm.AutoComplete(searchInput, "loras", { showPreview: false });
|
||||
|
||||
const initialState = parseLorasState(stateWidget?.value ?? "[]");
|
||||
|
||||
let isSyncing = false;
|
||||
|
||||
const embedded = createEmbeddedLorasWidget(
|
||||
node, lm, `${slotDef.key}_loras`, initialState,
|
||||
(value) => {
|
||||
if (isSyncing) return;
|
||||
isSyncing = true;
|
||||
try {
|
||||
const safe = Array.isArray(value) ? value : [];
|
||||
writeLorasState(stateWidget, safe);
|
||||
const nextText = lm.applyLoraValuesToText(searchInput.value || "", safe);
|
||||
if (searchInput.value !== nextText) searchInput.value = nextText;
|
||||
} finally {
|
||||
isSyncing = false;
|
||||
notifyHeightChange(node);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// When user types or autocomplete fires, merge into the loras list
|
||||
searchInput.addEventListener("input", () => {
|
||||
if (isSyncing) return;
|
||||
isSyncing = true;
|
||||
try {
|
||||
const existing = Array.isArray(embedded.widget?.value) ? embedded.widget.value : [];
|
||||
const merged = lm.mergeLoras(searchInput.value || "", existing);
|
||||
if (embedded.widget) embedded.widget.value = merged;
|
||||
writeLorasState(stateWidget, merged);
|
||||
} finally {
|
||||
isSyncing = false;
|
||||
notifyHeightChange(node);
|
||||
}
|
||||
});
|
||||
|
||||
col.appendChild(title);
|
||||
col.appendChild(searchInput);
|
||||
col.appendChild(embedded.host);
|
||||
embedded.host.addEventListener("pointerdown", () => setActiveSlot(node, slotDef.key));
|
||||
|
||||
return {
|
||||
key: slotDef.key,
|
||||
stateWidget,
|
||||
searchInput,
|
||||
lorasWidget: embedded.widget,
|
||||
fastPreviewCleanup: embedded.fastPreviewCleanup,
|
||||
col,
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Restore widget state from persisted JSON
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function refreshFromStoredValues(node) {
|
||||
if (!node?.__pmMultiLmSlots || !node.__pmMultiLmBridge) return;
|
||||
for (const slot of node.__pmMultiLmSlots) {
|
||||
const state = parseLorasState(slot.stateWidget?.value ?? "[]");
|
||||
|
||||
// Restore from persisted JSON directly. Do NOT call mergeLoras here:
|
||||
// mergeLoras requires syntax in text input, and would drop entries
|
||||
// during tab-switch/workflow-load when textarea is initially empty.
|
||||
if (slot.lorasWidget) slot.lorasWidget.value = state;
|
||||
writeLorasState(slot.stateWidget, state);
|
||||
|
||||
// Keep syntax textarea consistent with restored list.
|
||||
const nextText = node.__pmMultiLmBridge.applyLoraValuesToText(slot.searchInput.value || "", state);
|
||||
if (slot.searchInput.value !== nextText) slot.searchInput.value = nextText;
|
||||
}
|
||||
notifyHeightChange(node);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Main async UI setup
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function setupNodeUi(node) {
|
||||
if (!node || node.__pmMultiLmReady) return;
|
||||
|
||||
ensureStyles();
|
||||
const lm = await loadLmBridge();
|
||||
if (!lm || node.__pmMultiLmReady) return;
|
||||
|
||||
hideStateWidgets(node);
|
||||
|
||||
const root = document.createElement("div");
|
||||
root.className = "pm-multi-lm-root";
|
||||
|
||||
// Top-left custom stack count control (1..4)
|
||||
const topbar = document.createElement("div");
|
||||
topbar.className = "pm-multi-lm-topbar";
|
||||
|
||||
const stackControl = document.createElement("div");
|
||||
stackControl.className = "pm-multi-lm-stack-control";
|
||||
|
||||
const stackLabel = document.createElement("div");
|
||||
stackLabel.className = "pm-multi-lm-stack-label";
|
||||
stackLabel.textContent = "Lora Stack";
|
||||
|
||||
const stepper = document.createElement("div");
|
||||
stepper.className = "pm-multi-lm-stepper";
|
||||
|
||||
const decBtn = document.createElement("button");
|
||||
decBtn.className = "pm-multi-lm-step-btn";
|
||||
decBtn.type = "button";
|
||||
decBtn.textContent = "<";
|
||||
|
||||
const valueEl = document.createElement("div");
|
||||
valueEl.className = "pm-multi-lm-step-value";
|
||||
valueEl.textContent = String(getStackCount(node));
|
||||
|
||||
const incBtn = document.createElement("button");
|
||||
incBtn.className = "pm-multi-lm-step-btn";
|
||||
incBtn.type = "button";
|
||||
incBtn.textContent = ">";
|
||||
|
||||
decBtn.addEventListener("click", () => setStackCount(node, getStackCount(node) - 1));
|
||||
incBtn.addEventListener("click", () => setStackCount(node, getStackCount(node) + 1));
|
||||
|
||||
stepper.appendChild(decBtn);
|
||||
stepper.appendChild(valueEl);
|
||||
stepper.appendChild(incBtn);
|
||||
stackControl.appendChild(stackLabel);
|
||||
stackControl.appendChild(stepper);
|
||||
topbar.appendChild(stackControl);
|
||||
root.appendChild(topbar);
|
||||
|
||||
// 4-column LoRA grid
|
||||
const grid = document.createElement("div");
|
||||
grid.className = "pm-multi-lm-grid";
|
||||
root.appendChild(grid);
|
||||
|
||||
const slots = SLOT_DEFS.map((slotDef) => {
|
||||
const slot = buildSlotColumn(node, lm, slotDef);
|
||||
grid.appendChild(slot.col);
|
||||
return slot;
|
||||
});
|
||||
|
||||
const uiWidget = node.addDOMWidget("multi_lora_ui", "div", root, {
|
||||
serialize: false,
|
||||
hideOnZoom: false,
|
||||
getMinHeight: () => computeContentHeight(node),
|
||||
getHeight: () => "100%",
|
||||
});
|
||||
|
||||
node.__pmMultiLmBridge = lm;
|
||||
node.__pmMultiLmSlots = slots;
|
||||
node.__pmMultiLmGrid = grid;
|
||||
node.__pmStackControl = { dec: decBtn, inc: incBtn, value: valueEl };
|
||||
node.__pmMultiLmRoot = root;
|
||||
node.__pmMultiLmReady = true;
|
||||
node.__pmMultiLmRefresh = () => {
|
||||
refreshFromStoredValues(node);
|
||||
applyVisibleStackCount(node);
|
||||
updateStackControlUi(node);
|
||||
syncStackCountWidget(node, getStackCount(node));
|
||||
updateActiveColumnHighlight(node);
|
||||
};
|
||||
|
||||
// comfyClass already set synchronously in onNodeCreated — no registry tricks needed
|
||||
// Restore any lora data that onConfigure may have written before async completed
|
||||
refreshFromStoredValues(node);
|
||||
hideStateWidgets(node);
|
||||
applyVisibleStackCount(node);
|
||||
updateStackControlUi(node);
|
||||
updateActiveColumnHighlight(node);
|
||||
notifyHeightChange(node);
|
||||
applyNodeSizeConstraints(node);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Extension registration
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
app.registerExtension({
|
||||
name: "PromptManager.MultiLoraStackerLM",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType) {
|
||||
if (nodeType.comfyClass !== NODE_CLASS) return;
|
||||
|
||||
// Attach the send-to-node listener once, immediately (synchronous)
|
||||
attachLoraCodeListener();
|
||||
// Ensure prompt uses backend class while keeping LM comfyClass at runtime.
|
||||
attachPromptSerializationShim();
|
||||
|
||||
// ── onNodeCreated ──────────────────────────────────────────────────
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const result = onNodeCreated ? onNodeCreated.apply(this, arguments) : undefined;
|
||||
|
||||
this.serialize_widgets = true;
|
||||
|
||||
// Set comfyClass SYNCHRONOUSLY so LM WorkflowRegistry includes us
|
||||
// on the next lora_registry_refresh sweep
|
||||
this.comfyClass = LM_PROVIDER_CLASS;
|
||||
|
||||
if (!this.properties) this.properties = {};
|
||||
if (!this.properties.pmActiveSlot) this.properties.pmActiveSlot = "model_a";
|
||||
if (!Number.isFinite(Number(this.properties.pmLoraStackCount))) {
|
||||
this.properties.pmLoraStackCount = DEFAULT_STACK_COUNT;
|
||||
} else {
|
||||
this.properties.pmLoraStackCount = clampStackCount(this.properties.pmLoraStackCount);
|
||||
}
|
||||
ensureActiveSlotVisible(this);
|
||||
syncStackCountWidget(this, this.properties.pmLoraStackCount);
|
||||
|
||||
applyNodeSizeConstraints(this, true);
|
||||
|
||||
void setupNodeUi(this);
|
||||
return result;
|
||||
};
|
||||
|
||||
// ── onConfigure (workflow load / tab switch) ──────────────────────
|
||||
const onConfigure = nodeType.prototype.onConfigure;
|
||||
nodeType.prototype.onConfigure = function (config) {
|
||||
const result = onConfigure ? onConfigure.apply(this, arguments) : undefined;
|
||||
|
||||
// Re-assert comfyClass in case ComfyUI reset it during configure
|
||||
this.comfyClass = LM_PROVIDER_CLASS;
|
||||
|
||||
hideStateWidgets(this);
|
||||
if (!Number.isFinite(Number(this.properties?.pmLoraStackCount))) {
|
||||
if (!this.properties) this.properties = {};
|
||||
this.properties.pmLoraStackCount = DEFAULT_STACK_COUNT;
|
||||
} else {
|
||||
this.properties.pmLoraStackCount = clampStackCount(this.properties.pmLoraStackCount);
|
||||
}
|
||||
ensureActiveSlotVisible(this);
|
||||
syncStackCountWidget(this, this.properties.pmLoraStackCount);
|
||||
|
||||
if (typeof this.__pmMultiLmRefresh === "function") {
|
||||
this.__pmMultiLmRefresh();
|
||||
}
|
||||
|
||||
applyNodeSizeConstraints(this);
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const onModeChange = nodeType.prototype.onModeChange;
|
||||
nodeType.prototype.onModeChange = function () {
|
||||
const result = onModeChange ? onModeChange.apply(this, arguments) : undefined;
|
||||
hideStateWidgets(this);
|
||||
if (typeof this.__pmMultiLmRefresh === "function") {
|
||||
this.__pmMultiLmRefresh();
|
||||
}
|
||||
applyNodeSizeConstraints(this);
|
||||
return result;
|
||||
};
|
||||
|
||||
const onResize = nodeType.prototype.onResize;
|
||||
nodeType.prototype.onResize = function () {
|
||||
const result = onResize ? onResize.apply(this, arguments) : undefined;
|
||||
applyNodeSizeConstraints(this);
|
||||
return result;
|
||||
};
|
||||
|
||||
// ── onRemoved ──────────────────────────────────────────────────────
|
||||
const onRemoved = nodeType.prototype.onRemoved;
|
||||
nodeType.prototype.onRemoved = function () {
|
||||
if (Array.isArray(this.__pmMultiLmSlots)) {
|
||||
for (const slot of this.__pmMultiLmSlots) {
|
||||
try {
|
||||
slot?.fastPreviewCleanup?.();
|
||||
} catch (_e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
this.__pmMultiLmSlots = null;
|
||||
this.__pmMultiLmRoot = null;
|
||||
this.__pmMultiLmBridge = null;
|
||||
this.__pmMultiLmGrid = null;
|
||||
this.__pmStackControl = null;
|
||||
this.__pmMultiLmReady = false;
|
||||
this.__pmMultiLmRefresh = null;
|
||||
return onRemoved ? onRemoved.apply(this, arguments) : undefined;
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
/**
|
||||
* Shared media path browser helpers for FBnodes Load+ nodes.
|
||||
*
|
||||
* Provides the backend-list/file URL helpers, root resolution, and the
|
||||
* input/output/absolute selection classifier used by the thumbnail browser
|
||||
* (file_browser.js) so the loader nodes can browse anywhere while keeping
|
||||
* old workflows working.
|
||||
*/
|
||||
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
|
||||
export const SETTING_CUSTOM_PATH = "PromptManager.PromptExtractorCustomPath";
|
||||
|
||||
export function getCustomPresetPath() {
|
||||
const pref = app.ui?.settings?.getSettingValue(SETTING_CUSTOM_PATH) || "";
|
||||
return typeof pref === "string" ? pref.trim() : "";
|
||||
}
|
||||
|
||||
/** URL that streams a media file from any path (for previews of out-of-tree files). */
|
||||
export function mediaFileUrl(absPath) {
|
||||
return api.apiURL(`/prompt-extractor/path-browser/file?path=${encodeURIComponent(absPath)}`);
|
||||
}
|
||||
|
||||
function normalizeSlashes(p) {
|
||||
return String(p || "").replace(/\\/g, "/");
|
||||
}
|
||||
|
||||
/** True when `child` is inside `parent` (both absolute), case-insensitive on Windows. */
|
||||
function isUnder(child, parent) {
|
||||
if (!child || !parent) return false;
|
||||
let c = normalizeSlashes(child).replace(/\/+$/, "");
|
||||
let p = normalizeSlashes(parent).replace(/\/+$/, "");
|
||||
if (navigator.platform.startsWith("Win")) {
|
||||
c = c.toLowerCase();
|
||||
p = p.toLowerCase();
|
||||
}
|
||||
return c === p || c.startsWith(p + "/");
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a selected absolute path and the input/output roots, work out how to
|
||||
* store it so old workflows keep working:
|
||||
* - inside input -> { sourceFolder:"input", value:<relative> }
|
||||
* - inside output -> { sourceFolder:"output", value:<relative> }
|
||||
* - elsewhere -> { sourceFolder:null, value:<absolute> }
|
||||
*/
|
||||
export function classifySelection(absPath, roots) {
|
||||
const inputRoot = roots?.input || "";
|
||||
const outputRoot = roots?.output || "";
|
||||
const norm = normalizeSlashes(absPath);
|
||||
|
||||
if (inputRoot && isUnder(absPath, inputRoot)) {
|
||||
const rel = norm.slice(normalizeSlashes(inputRoot).replace(/\/+$/, "").length + 1);
|
||||
return { sourceFolder: "input", value: rel, absPath };
|
||||
}
|
||||
if (outputRoot && isUnder(absPath, outputRoot)) {
|
||||
const rel = norm.slice(normalizeSlashes(outputRoot).replace(/\/+$/, "").length + 1);
|
||||
return { sourceFolder: "output", value: rel, absPath };
|
||||
}
|
||||
return { sourceFolder: null, value: absPath, absPath };
|
||||
}
|
||||
|
||||
async function fetchBrowser(path, kind) {
|
||||
const params = [];
|
||||
if (path) params.push(`path=${encodeURIComponent(path)}`);
|
||||
if (kind) params.push(`kind=${encodeURIComponent(kind)}`);
|
||||
const query = params.length ? `?${params.join("&")}` : "";
|
||||
const resp = await api.fetchApi(`/prompt-extractor/path-browser/list${query}`);
|
||||
if (!resp.ok) {
|
||||
let msg = `Request failed (${resp.status})`;
|
||||
try {
|
||||
const err = await resp.json();
|
||||
if (err?.error) msg = err.error;
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
throw new Error(msg);
|
||||
}
|
||||
return await resp.json();
|
||||
}
|
||||
|
||||
/** Resolve the input/output preset roots once (backend "roots" mode). */
|
||||
export async function getMediaRoots() {
|
||||
try {
|
||||
const data = await fetchBrowser("", "");
|
||||
const roots = Array.isArray(data?.roots) ? data.roots : [];
|
||||
return { input: roots[0] || "", output: roots[1] || "" };
|
||||
} catch {
|
||||
return { input: "", output: "" };
|
||||
}
|
||||
}
|
||||
|
||||
// Register the shared Custom-path preference once.
|
||||
app.registerExtension({
|
||||
name: "PromptManager.PromptExtractorPathBrowser",
|
||||
settings: [
|
||||
{
|
||||
id: SETTING_CUSTOM_PATH,
|
||||
category: ["Prompt Manager", "Prompt Extractor", "Custom Browser Path"],
|
||||
name: "Prompt Extractor Custom Browser Path",
|
||||
tooltip: "Optional folder shown as the 'Custom' preset in the Load+ file browsers.",
|
||||
type: "text",
|
||||
defaultValue: "",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
|
After Width: | Height: | Size: 29 KiB |
@@ -0,0 +1,249 @@
|
||||
import { api } from "../../scripts/api.js";
|
||||
import { COMPOSER_ENDPOINT_PREFIX, getCategoryPromptEntries } from "./prompt_store_adapters.js";
|
||||
|
||||
const COMPOSER_CATEGORY_KEY_SEPARATOR = "::";
|
||||
|
||||
function newComposerLibrary() {
|
||||
return { __meta__: { schema_version: 2, storage: "type_files" }, _types_: {} };
|
||||
}
|
||||
|
||||
function isCanonicalComposerLibrary(library) {
|
||||
return !!(
|
||||
library
|
||||
&& typeof library === "object"
|
||||
&& !Array.isArray(library)
|
||||
&& library._types_
|
||||
&& typeof library._types_ === "object"
|
||||
&& !Array.isArray(library._types_)
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeComposerLibrary(library) {
|
||||
if (!isCanonicalComposerLibrary(library)) {
|
||||
throw new Error("Prompt Composer requires canonical v2 library data with _types_");
|
||||
}
|
||||
return library;
|
||||
}
|
||||
|
||||
function getComposerTypeOrder(typeData) {
|
||||
const numeric = Number(typeData?.order);
|
||||
return Number.isInteger(numeric) ? numeric : Number.POSITIVE_INFINITY;
|
||||
}
|
||||
|
||||
function getOrderedComposerTypes(types) {
|
||||
const entries = Object.entries(types || {});
|
||||
const hasExplicitOrder = entries.some(([, typeData]) => Number.isInteger(Number(typeData?.order)));
|
||||
if (!hasExplicitOrder) {
|
||||
return entries.sort((a, b) => String(a[0] || "").localeCompare(String(b[0] || ""), undefined, { sensitivity: "base" }));
|
||||
}
|
||||
return entries.sort((a, b) => {
|
||||
const orderDiff = getComposerTypeOrder(a[1]) - getComposerTypeOrder(b[1]);
|
||||
if (orderDiff !== 0) return orderDiff;
|
||||
return String(a[0] || "").localeCompare(String(b[0] || ""), undefined, { sensitivity: "base" });
|
||||
});
|
||||
}
|
||||
|
||||
function buildComposerCategoryKey(typeFile, categoryName) {
|
||||
const normalizedTypeFile = String(typeFile || "").trim();
|
||||
const normalizedCategory = String(categoryName || "").trim();
|
||||
if (!normalizedTypeFile) return normalizedCategory;
|
||||
return `${normalizedTypeFile}${COMPOSER_CATEGORY_KEY_SEPARATOR}${normalizedCategory}`;
|
||||
}
|
||||
|
||||
function normalizeComposerSubjectKind(value, fallback = "other") {
|
||||
const normalized = String(value || "").trim().toLowerCase();
|
||||
if (["character", "animal", "environment", "other"].includes(normalized)) {
|
||||
return normalized;
|
||||
}
|
||||
if (normalized === "person") return "character";
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function defaultComposerSubjectKind(subjectType) {
|
||||
return String(subjectType || "").trim().toLowerCase() === "new_subject" ? "character" : "other";
|
||||
}
|
||||
|
||||
function parseComposerCategoryKey(category) {
|
||||
const raw = String(category || "").trim();
|
||||
const separatorIndex = raw.indexOf(COMPOSER_CATEGORY_KEY_SEPARATOR);
|
||||
if (separatorIndex <= 0) {
|
||||
return { typeFile: "", categoryName: raw };
|
||||
}
|
||||
return {
|
||||
typeFile: raw.slice(0, separatorIndex).trim(),
|
||||
categoryName: raw.slice(separatorIndex + COMPOSER_CATEGORY_KEY_SEPARATOR.length).trim(),
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveComposerCategoryKey(data, category) {
|
||||
const raw = String(category || "").trim();
|
||||
if (!raw) return "";
|
||||
if (data?.[raw] && typeof data[raw] === "object") {
|
||||
return raw;
|
||||
}
|
||||
|
||||
const parsed = parseComposerCategoryKey(raw);
|
||||
const normalizedCategoryName = String(parsed.categoryName || raw).trim().toLowerCase();
|
||||
const normalizedTypeFile = String(parsed.typeFile || "").trim().toLowerCase();
|
||||
let fallback = "";
|
||||
|
||||
for (const [categoryKey, categoryData] of Object.entries(data || {})) {
|
||||
if (categoryKey === "__meta__" || !categoryData || typeof categoryData !== "object") continue;
|
||||
const candidateCategoryName = String(categoryData._category_name_ || categoryKey).trim().toLowerCase();
|
||||
if (candidateCategoryName !== normalizedCategoryName) continue;
|
||||
const candidateTypeFile = String(categoryData._type_file_ || "").trim().toLowerCase();
|
||||
if (normalizedTypeFile && candidateTypeFile === normalizedTypeFile) {
|
||||
return categoryKey;
|
||||
}
|
||||
if (!fallback) {
|
||||
fallback = categoryKey;
|
||||
}
|
||||
}
|
||||
|
||||
if (fallback) return fallback;
|
||||
if (parsed.typeFile && parsed.categoryName) {
|
||||
return buildComposerCategoryKey(parsed.typeFile, parsed.categoryName);
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
function flattenComposerType(typeFile, typeData, flatData) {
|
||||
if (!typeData || typeof typeData !== "object") return;
|
||||
const typeKey = String(typeFile || "").replace(/\.json$/i, "").trim().toLowerCase();
|
||||
const typeName = String(typeData.name || "").trim() || typeKey || "Misc";
|
||||
const typePrefix = String(typeData.prefix || "");
|
||||
const typeBasePrompt = String(typeData.base_prompt || "");
|
||||
const typeSubjectType = String(typeData.subject_type || "subject").trim().toLowerCase() || "subject";
|
||||
const typeSubjectKind = normalizeComposerSubjectKind(typeData.subject_kind, defaultComposerSubjectKind(typeSubjectType));
|
||||
const typeNsfw = typeData.nsfw === true;
|
||||
const categories = typeData.categories;
|
||||
if (!categories || typeof categories !== "object" || Array.isArray(categories)) return;
|
||||
|
||||
for (const [categoryName, categoryData] of Object.entries(categories)) {
|
||||
if (!categoryName || !categoryData || typeof categoryData !== "object") continue;
|
||||
const promptEntries = categoryData._prompts_ && typeof categoryData._prompts_ === "object"
|
||||
? categoryData._prompts_
|
||||
: {};
|
||||
const effectivePrefix = String(categoryData.prefix || typePrefix || "");
|
||||
const effectiveBasePrompt = String(categoryData.base_prompt || typeBasePrompt || "");
|
||||
const effectiveNsfw = categoryData.nsfw === true || typeNsfw;
|
||||
const flatCategory = {
|
||||
_prompts_: promptEntries,
|
||||
_category_name_: String(categoryName || "").trim(),
|
||||
_prompt_type_: typeKey,
|
||||
_type_file_: String(typeFile || ""),
|
||||
_type_name_: typeName,
|
||||
_subject_type_: typeSubjectType,
|
||||
_subject_kind_: typeSubjectKind,
|
||||
};
|
||||
if (effectivePrefix.trim()) flatCategory._prompt_prefix_ = effectivePrefix;
|
||||
if (effectiveBasePrompt.trim()) flatCategory._base_prompt_ = effectiveBasePrompt;
|
||||
if (String(categoryData.prefix || "").trim()) flatCategory._category_prefix_ = String(categoryData.prefix || "");
|
||||
if (String(categoryData.base_prompt || "").trim()) flatCategory._category_base_prompt_ = String(categoryData.base_prompt || "");
|
||||
if (typePrefix.trim()) flatCategory._type_prefix_ = typePrefix;
|
||||
if (typeBasePrompt.trim()) flatCategory._type_base_prompt_ = typeBasePrompt;
|
||||
if (typeNsfw) flatCategory._type_nsfw_ = true;
|
||||
if (effectiveNsfw) flatCategory.__meta__ = { nsfw: true };
|
||||
flatData[buildComposerCategoryKey(typeFile, categoryName)] = flatCategory;
|
||||
}
|
||||
}
|
||||
|
||||
export function flattenComposerLibrary(library) {
|
||||
const normalized = normalizeComposerLibrary(library);
|
||||
|
||||
const flatData = { __meta__: normalized.__meta__ || { schema_version: 2, storage: "type_files" } };
|
||||
for (const [typeFile, typeData] of getOrderedComposerTypes(normalized._types_ || {})) {
|
||||
flattenComposerType(typeFile, typeData, flatData);
|
||||
}
|
||||
return flatData;
|
||||
}
|
||||
|
||||
export async function loadComposerPrompts(node) {
|
||||
try {
|
||||
const resp = await fetch(`${COMPOSER_ENDPOINT_PREFIX}/get-prompts`, {
|
||||
cache: "no-store",
|
||||
});
|
||||
const library = await resp.json();
|
||||
node.composerPromptLibrary = normalizeComposerLibrary(library);
|
||||
node.composerPrompts = flattenComposerLibrary(node.composerPromptLibrary);
|
||||
// Make the shared browser see composer data instead of prompt_manager_data.json.
|
||||
node.prompts = node.composerPrompts;
|
||||
} catch (err) {
|
||||
console.error("[PromptComposer] Error loading composer prompts:", err);
|
||||
node.composerPromptLibrary = newComposerLibrary();
|
||||
node.composerPrompts = {};
|
||||
node.prompts = {};
|
||||
}
|
||||
return node.composerPrompts;
|
||||
}
|
||||
|
||||
function getComposerData(node) {
|
||||
// The shared browser mutates node.prompts; for composer nodes that is always composer data.
|
||||
return node.prompts || node.composerPrompts || {};
|
||||
}
|
||||
|
||||
export function getComposerCategories(node) {
|
||||
const data = getComposerData(node);
|
||||
return Object.keys(data).filter((c) => c !== "__meta__").sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
|
||||
}
|
||||
|
||||
export function getComposerNames(node, category) {
|
||||
const data = getComposerData(node);
|
||||
const catData = data[resolveComposerCategoryKey(data, category)];
|
||||
if (!catData || typeof catData !== "object") return [];
|
||||
return Object.keys(getCategoryPromptEntries(catData, "composer")).sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
|
||||
}
|
||||
|
||||
export function getComposerEntry(node, category, name) {
|
||||
const data = getComposerData(node);
|
||||
const catData = data[resolveComposerCategoryKey(data, category)];
|
||||
if (!catData || typeof catData !== "object") return null;
|
||||
return getCategoryPromptEntries(catData, "composer")[name] || null;
|
||||
}
|
||||
|
||||
export async function saveComposerCategorySettings(category, settings) {
|
||||
try {
|
||||
const resp = await fetch(`${COMPOSER_ENDPOINT_PREFIX}/save-category-settings`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
category,
|
||||
type_file: settings.typeFile || "",
|
||||
base_prompt: settings.basePrompt || "",
|
||||
prompt_type: settings.promptType || "",
|
||||
prefix: settings.promptPrefix || "",
|
||||
}),
|
||||
});
|
||||
return await resp.json();
|
||||
} catch (err) {
|
||||
console.error("[PromptComposer] Error saving category settings:", err);
|
||||
return { success: false, error: String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
export async function saveComposerTypeSettings(settings) {
|
||||
try {
|
||||
const resp = await fetch(`${COMPOSER_ENDPOINT_PREFIX}/save-type-settings`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
type_file: settings.typeFile || "",
|
||||
prompt_type: settings.promptType || "",
|
||||
type_name: settings.typeName || "",
|
||||
subject_type: settings.subjectType || "subject",
|
||||
subject_kind: normalizeComposerSubjectKind(
|
||||
settings.subjectKind,
|
||||
defaultComposerSubjectKind(settings.subjectType || "subject")
|
||||
),
|
||||
prefix: settings.promptPrefix || "",
|
||||
base_prompt: settings.basePrompt || "",
|
||||
}),
|
||||
});
|
||||
return await resp.json();
|
||||
} catch (err) {
|
||||
console.error("[PromptComposer] Error saving type settings:", err);
|
||||
return { success: false, error: String(err) };
|
||||
}
|
||||
}
|
||||
|
||||
export { COMPOSER_ENDPOINT_PREFIX };
|
||||
@@ -0,0 +1,414 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
import { showThumbnailBrowser } from "./prompt_browser.js";
|
||||
import { SYSTEM_PROMPTS_ENDPOINT_PREFIX, getCategoryPromptEntries } from "./prompt_store_adapters.js";
|
||||
import { setPromptTextLocked } from "./prompt_text_lock.js";
|
||||
|
||||
function setupSystemPromptSelector(node) {
|
||||
const widget = node.widgets?.find(w => w.name === "system_prompt");
|
||||
if (!widget || widget.type === "system_prompt_selector") return;
|
||||
|
||||
const selectPrompt = async (value) => {
|
||||
widget.value = value;
|
||||
await widget.callback?.call(widget, value, app.canvas, node);
|
||||
updateDisplay();
|
||||
node.setDirtyCanvas(true, true);
|
||||
};
|
||||
|
||||
const loadSystemPrompts = async () => {
|
||||
const response = await api.fetchApi(`${SYSTEM_PROMPTS_ENDPOINT_PREFIX}/get-prompts`, { cache: "no-store" });
|
||||
if (!response.ok) throw new Error(`Could not load system prompts (${response.status})`);
|
||||
const prompts = await response.json();
|
||||
node.prompts = prompts;
|
||||
// The combo list comes from page load; keep it current with prompts added or moved since.
|
||||
const choices = getChoices(prompts);
|
||||
if (choices.length && widget.options && typeof widget.options.values !== "function") widget.options.values = choices;
|
||||
return prompts;
|
||||
};
|
||||
|
||||
const getChoices = (prompts) => Object.entries(prompts)
|
||||
.filter(([category, entries]) => !category.startsWith("_") && entries && typeof entries === "object")
|
||||
.flatMap(([category, entries]) => Object.entries(getCategoryPromptEntries(entries, "generator"))
|
||||
.filter(([name, entry]) => {
|
||||
const text = entry && typeof entry === "object" ? entry.prompt : entry;
|
||||
return !name.startsWith("_") && String(text ?? "").trim();
|
||||
})
|
||||
.map(([name]) => `${category} / ${name}`))
|
||||
.sort((left, right) => left.toLowerCase().localeCompare(right.toLowerCase()));
|
||||
|
||||
let busy = false;
|
||||
const activate = async (direction) => {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
try {
|
||||
if (direction) {
|
||||
const choices = getChoices(await loadSystemPrompts());
|
||||
if (!choices.length) return;
|
||||
const index = choices.indexOf(widget.value);
|
||||
const nextIndex = index < 0
|
||||
? (direction > 0 ? 0 : choices.length - 1)
|
||||
: (index + direction + choices.length) % choices.length;
|
||||
await selectPrompt(choices[nextIndex]);
|
||||
} else {
|
||||
const value = String(widget.value ?? "");
|
||||
const separator = value.indexOf(" / ");
|
||||
const category = separator < 0 ? "" : value.slice(0, separator);
|
||||
const name = separator < 0 ? value : value.slice(separator + 3);
|
||||
const selection = await showThumbnailBrowser(node, category, name, {
|
||||
title: "Select System Prompt",
|
||||
endpointPrefix: SYSTEM_PROMPTS_ENDPOINT_PREFIX,
|
||||
loadPromptsFn: loadSystemPrompts,
|
||||
preferenceScope: "system",
|
||||
promptOnly: true,
|
||||
allowMultiSelect: false,
|
||||
});
|
||||
if (selection?.prompt) {
|
||||
await selectPrompt(`${selection.category} / ${selection.prompt}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("[PromptGenerator] System prompt selection failed:", error);
|
||||
app.extensionManager.toast.add({
|
||||
severity: "error",
|
||||
summary: "System prompts unavailable",
|
||||
detail: String(error.message || error),
|
||||
});
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
};
|
||||
|
||||
const container = document.createElement("div");
|
||||
// Mirrors Prompt Manager's selector; the dark backing is what keeps the translucent name button dark.
|
||||
container.style.cssText = `
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0;
|
||||
background: #1a1a1a;
|
||||
border-radius: 6px;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
height: 26px;
|
||||
box-sizing: border-box;
|
||||
`;
|
||||
for (const eventName of ["pointerdown", "mousedown", "dblclick"]) {
|
||||
container.addEventListener(eventName, event => event.stopPropagation());
|
||||
}
|
||||
|
||||
const makeButton = (label, title, direction) => {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.textContent = label;
|
||||
button.title = title;
|
||||
button.setAttribute("aria-label", title);
|
||||
button.style.cssText = `
|
||||
background: #2a2a2a;
|
||||
border: none;
|
||||
color: #888;
|
||||
padding: 0 10px;
|
||||
height: 100%;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
transition: all 0.15s ease;
|
||||
`;
|
||||
button.addEventListener("mouseover", () => {
|
||||
button.style.background = direction ? "#3a3a3a" : "rgba(56, 130, 246, 0.32)";
|
||||
if (direction) button.style.color = "#fff";
|
||||
});
|
||||
button.addEventListener("mouseout", () => {
|
||||
button.style.background = direction ? "#2a2a2a" : "rgba(56, 130, 246, 0.22)";
|
||||
if (direction) button.style.color = "#888";
|
||||
});
|
||||
button.addEventListener("click", event => {
|
||||
event.stopPropagation();
|
||||
void activate(direction);
|
||||
});
|
||||
container.appendChild(button);
|
||||
return button;
|
||||
};
|
||||
|
||||
makeButton("\u25c0", "Previous system prompt", -1);
|
||||
const nameButton = makeButton("", "Browse System Prompts", 0);
|
||||
nameButton.style.cssText = `
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
text-align: center;
|
||||
color: #dbeafe;
|
||||
font-family: inherit;
|
||||
font-size: 15px;
|
||||
padding: 0 10px;
|
||||
cursor: pointer;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
background: rgba(56, 130, 246, 0.22);
|
||||
border: 1px solid rgba(56, 130, 246, 0.85);
|
||||
border-radius: 4px;
|
||||
height: 100%;
|
||||
transition: background 0.15s ease;
|
||||
box-sizing: border-box;
|
||||
`;
|
||||
makeButton("\u25b6", "Next system prompt", 1);
|
||||
const updateDisplay = () => {
|
||||
nameButton.textContent = String(widget.value ?? "").replace(" / ", " : ");
|
||||
nameButton.title = `Browse System Prompts: ${widget.value ?? ""}`;
|
||||
};
|
||||
const index = node.widgets.indexOf(widget);
|
||||
const selector = node.addDOMWidget("system_prompt", "system_prompt_selector", container, {
|
||||
getMinHeight: () => 26,
|
||||
getMaxHeight: () => 26,
|
||||
getValue: () => widget.value,
|
||||
setValue: value => {
|
||||
widget.value = value;
|
||||
updateDisplay();
|
||||
},
|
||||
});
|
||||
selector.computeSize = width => [width, 28];
|
||||
// Nodes 2.0 stretches DOM widgets that expose computeLayoutSize; keep this row fixed-height.
|
||||
selector.computeLayoutSize = undefined;
|
||||
selector.serializeValue = () => widget.value;
|
||||
node.widgets.splice(node.widgets.indexOf(selector), 1);
|
||||
node.widgets.splice(index, 1, selector);
|
||||
const matchChoice = (value, choices, allowFallback) => {
|
||||
const normalized = String(value ?? "").trim().toLowerCase();
|
||||
const entries = choices.map(choice => {
|
||||
const separator = choice.indexOf(" / ");
|
||||
return { value: choice, category: choice.slice(0, separator), name: choice.slice(separator + 3) };
|
||||
});
|
||||
const exact = entries.find(entry => entry.value.toLowerCase() === normalized);
|
||||
const legacy = entries.find(entry => `${entry.name} (${entry.category})`.toLowerCase() === normalized);
|
||||
// A prompt moved to another category keeps its name.
|
||||
const previousName = normalized.includes(" / ") ? normalized.slice(normalized.indexOf(" / ") + 3) : normalized;
|
||||
const names = entries.filter(entry => entry.name.toLowerCase() === previousName);
|
||||
const match = exact || legacy || (names.length === 1 ? names[0] : null);
|
||||
if (match || !allowFallback) return match;
|
||||
return entries.find(entry => entry.value.toLowerCase() === "image / enhance prompt") || entries[0] || null;
|
||||
};
|
||||
const applyMatch = (match) => {
|
||||
if (!match || widget.value === match.value) return;
|
||||
const previous = widget.value;
|
||||
selector.value = match.value;
|
||||
console.log(`[PromptGenerator] Migrated system prompt '${previous}' to '${match.value}'.`);
|
||||
node.setDirtyCanvas(true, true);
|
||||
};
|
||||
// The combo's choices date from page load, so canonical values are checked against the live list.
|
||||
const reconcileSelection = async () => {
|
||||
let choices;
|
||||
try {
|
||||
choices = getChoices(await loadSystemPrompts());
|
||||
} catch (error) {
|
||||
console.warn("[PromptGenerator] Could not refresh system prompts; keeping the saved selection.", error);
|
||||
return;
|
||||
}
|
||||
if (choices.length) applyMatch(matchChoice(widget.value, choices, true));
|
||||
};
|
||||
const onConfigure = node.onConfigure;
|
||||
node.onConfigure = function() {
|
||||
const result = onConfigure?.apply(this, arguments);
|
||||
// Legacy labels such as "Enhance Prompt (Image)" migrate at once so an immediate queue never sends them.
|
||||
if (!String(widget.value ?? "").includes(" / ")) {
|
||||
const choices = typeof widget.options?.values === "function" ? widget.options.values() : widget.options?.values;
|
||||
if (Array.isArray(choices) && choices.length) applyMatch(matchChoice(widget.value, choices, false));
|
||||
}
|
||||
void reconcileSelection();
|
||||
return result;
|
||||
};
|
||||
updateDisplay();
|
||||
}
|
||||
|
||||
function migrateLegacyPromptGenOptionsWidgets(node) {
|
||||
if (!node?.widgets || node.widgets.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const byName = (name) => node.widgets.find(w => w.name === name);
|
||||
const modeWidget = byName("system_prompt_mode");
|
||||
const systemPromptWidget = byName("system_prompt");
|
||||
const useDefaultWidget = byName("use_model_default_sampling");
|
||||
const temperatureWidget = byName("temperature");
|
||||
const topKWidget = byName("top_k");
|
||||
const topPWidget = byName("top_p");
|
||||
const minPWidget = byName("min_p");
|
||||
const repeatPenaltyWidget = byName("repeat_penalty");
|
||||
const contextSizeWidget = byName("context_size");
|
||||
const showConsoleWidget = byName("show_everything_in_console");
|
||||
|
||||
if (!modeWidget || !systemPromptWidget || !useDefaultWidget || !temperatureWidget ||
|
||||
!topKWidget || !topPWidget || !minPWidget || !repeatPenaltyWidget ||
|
||||
!contextSizeWidget || !showConsoleWidget) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const modeIsValid = modeWidget.value === "replace" || modeWidget.value === "append";
|
||||
const looksLegacyShape = typeof systemPromptWidget.value === "boolean" && typeof useDefaultWidget.value === "number";
|
||||
|
||||
if (modeIsValid && !looksLegacyShape) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const oldSystemPrompt = modeWidget.value;
|
||||
const oldUseDefaultSampling = systemPromptWidget.value;
|
||||
const oldTemperature = useDefaultWidget.value;
|
||||
const oldTopK = temperatureWidget.value;
|
||||
const oldTopP = topPWidget.value;
|
||||
const oldMinP = topPWidget.value;
|
||||
const oldRepeatPenalty = repeatPenaltyWidget.value;
|
||||
const oldContextSize = contextSizeWidget.value;
|
||||
const oldShowInConsole = showConsoleWidget.value;
|
||||
|
||||
modeWidget.value = "replace";
|
||||
systemPromptWidget.value = typeof oldSystemPrompt === "string" ? oldSystemPrompt : "";
|
||||
useDefaultWidget.value = Boolean(oldUseDefaultSampling);
|
||||
temperatureWidget.value = Number(oldTemperature);
|
||||
topKWidget.value = Number.isFinite(Number(oldTopK)) ? Math.round(Number(oldTopK)) : oldTopK;
|
||||
topPWidget.value = Number(oldTopP);
|
||||
minPWidget.value = Number(oldMinP);
|
||||
repeatPenaltyWidget.value = Number(oldRepeatPenalty);
|
||||
contextSizeWidget.value = Number.isFinite(Number(oldContextSize)) ? Math.round(Number(oldContextSize)) : oldContextSize;
|
||||
showConsoleWidget.value = Boolean(oldShowInConsole);
|
||||
|
||||
node.serialize_widgets = true;
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
console.log("[PromptManager] Migrated legacy PromptGenOptions widget order for workflow compatibility.");
|
||||
return true;
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "comfyui-prompt-manager.generator",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
// Make the Options node taller/wider by default so the system_prompt area is roomier
|
||||
if (nodeData.name === "PromptGenOptions") {
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const result = onNodeCreated?.apply(this, arguments);
|
||||
migrateLegacyPromptGenOptionsWidgets(this);
|
||||
// Model selection now lives on the Prompt Generator base node. The
|
||||
// Options node's model widget is kept (hidden) purely so old workflows
|
||||
// still load and pass their value through as a fallback.
|
||||
const modelWidget = this.widgets?.find(w => w.name === "model");
|
||||
if (modelWidget) {
|
||||
modelWidget.hidden = true;
|
||||
modelWidget.computeSize = () => [0, -4];
|
||||
if (modelWidget.inputEl) modelWidget.inputEl.style.display = "none";
|
||||
}
|
||||
// Set a default size (width x height)
|
||||
try {
|
||||
this.setSize([400, 420]);
|
||||
} catch (e) {
|
||||
// ignore if method unavailable
|
||||
}
|
||||
return result;
|
||||
};
|
||||
const onConfigureOpt = nodeType.prototype.onConfigure;
|
||||
nodeType.prototype.onConfigure = function(info) {
|
||||
const result = onConfigureOpt?.apply(this, arguments);
|
||||
migrateLegacyPromptGenOptionsWidgets(this);
|
||||
// Re-hide the legacy model widget on restore (tab switch / reload).
|
||||
const modelWidget = this.widgets?.find(w => w.name === "model");
|
||||
if (modelWidget) {
|
||||
modelWidget.hidden = true;
|
||||
modelWidget.computeSize = () => [0, -4];
|
||||
if (modelWidget.inputEl) modelWidget.inputEl.style.display = "none";
|
||||
}
|
||||
return result;
|
||||
};
|
||||
// Enforce sensible minimums when the user resizes the options node
|
||||
const onResizeOpt = nodeType.prototype.onResize;
|
||||
nodeType.prototype.onResize = function(size) {
|
||||
size[0] = Math.max(300, size[0]);
|
||||
return onResizeOpt ? onResizeOpt.apply(this, arguments) : size;
|
||||
};
|
||||
}
|
||||
|
||||
// Enforce minimum size for PromptGenerator node (no default size)
|
||||
if (nodeData.name === "PromptGenerator") {
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const result = onNodeCreated?.apply(this, arguments);
|
||||
setupSystemPromptSelector(this);
|
||||
// Set a default size (width x height) - taller to fit the UI comfortably
|
||||
try {
|
||||
this.setSize([400, 600]);
|
||||
} catch (e) {
|
||||
// ignore if method unavailable
|
||||
}
|
||||
|
||||
// Darken + make the prompt widget read-only while a `prompt_input`
|
||||
// link is connected (mirrors PromptManager's use_prompt_input UI).
|
||||
const node = this;
|
||||
const promptWidget = node.widgets?.find(w => w.name === "prompt");
|
||||
const promptInputSlot = () => node.inputs?.find(i => i && i.name === "prompt_input");
|
||||
const isPromptInputConnected = () => {
|
||||
const inp = promptInputSlot();
|
||||
return !!(inp && inp.link != null);
|
||||
};
|
||||
|
||||
const applyPromptInputState = () => {
|
||||
setPromptTextLocked(promptWidget, isPromptInputConnected());
|
||||
};
|
||||
// Python echoes back the value it actually received on prompt_input
|
||||
// (only when that input was connected) in the "executed" event.
|
||||
// Display it here; when the key is absent, never touch the widget.
|
||||
const prevOnConnectionsChange = node.onConnectionsChange;
|
||||
node.onConnectionsChange = function () {
|
||||
const r = prevOnConnectionsChange?.apply(this, arguments);
|
||||
applyPromptInputState();
|
||||
return r;
|
||||
};
|
||||
const prevOnConfigure = node.onConfigure;
|
||||
node.onConfigure = function () {
|
||||
const r = prevOnConfigure?.apply(this, arguments);
|
||||
applyPromptInputState();
|
||||
return r;
|
||||
};
|
||||
const prevOnExecuted = node.onExecuted;
|
||||
node.onExecuted = function (output) {
|
||||
const r = prevOnExecuted?.apply(this, arguments);
|
||||
applyPromptInputState();
|
||||
const echoed = output && output.ui ? output.ui.prompt : null;
|
||||
if (Array.isArray(echoed) && typeof echoed[0] === "string" && echoed[0].length > 0) {
|
||||
promptWidget.value = echoed[0];
|
||||
if (promptWidget.inputEl) {
|
||||
promptWidget.inputEl.value = echoed[0];
|
||||
}
|
||||
node.setDirtyCanvas(true, true);
|
||||
}
|
||||
return r;
|
||||
};
|
||||
|
||||
// Listen for incoming prompt_input text updates from the backend.
|
||||
// This fires at the very start of execution, before the LLM call.
|
||||
api.addEventListener("prompt-generator-update-text", (event) => {
|
||||
if (String(event.detail.node_id) === String(node.id)) {
|
||||
const incoming = event.detail.prompt || "";
|
||||
if (event.detail.has_prompt_input) {
|
||||
if (promptWidget) {
|
||||
promptWidget.value = incoming;
|
||||
if (promptWidget.inputEl) {
|
||||
promptWidget.inputEl.value = incoming;
|
||||
}
|
||||
setPromptTextLocked(promptWidget, true);
|
||||
}
|
||||
} else {
|
||||
setPromptTextLocked(promptWidget, false);
|
||||
}
|
||||
node.serialize_widgets = true;
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
}
|
||||
});
|
||||
|
||||
// Initial state.
|
||||
applyPromptInputState();
|
||||
|
||||
return result;
|
||||
};
|
||||
const onResizeModel = nodeType.prototype.onResize;
|
||||
nodeType.prototype.onResize = function(size) {
|
||||
size[0] = Math.max(300, size[0]);
|
||||
return onResizeModel ? onResizeModel.apply(this, arguments) : size;
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
console.log("[PromptManager] PromptGenerator extension loaded");
|
||||
@@ -0,0 +1,637 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
import { PM_UI_PALETTE as UI } from "./ui_palette.js";
|
||||
import { showInfo, showConfirm } from "./prompt_manager_advanced.js";
|
||||
import { showThumbnailBrowser, getPromptNamesForCategory } from "./prompt_browser.js";
|
||||
import {
|
||||
exportComposerJsonLibrary,
|
||||
mergeComposerJsonLibrary,
|
||||
openComposerJsonLibrary,
|
||||
showComposerImportModeDialog,
|
||||
triggerBrowserDownload,
|
||||
} from "./prompt_composer.js";
|
||||
import { loadComposerPrompts } from "./prompt_composer_common.js";
|
||||
import {
|
||||
COMPOSER_ENDPOINT_PREFIX,
|
||||
PROMPT_ADVANCED_ENDPOINT_PREFIX,
|
||||
PROMPT_ENDPOINT_PREFIX,
|
||||
SYSTEM_PROMPTS_ENDPOINT_PREFIX,
|
||||
getCategoryPromptEntries,
|
||||
isHiddenPromptEntryKey,
|
||||
} from "./prompt_store_adapters.js";
|
||||
|
||||
const HUB_TITLE = "Prompt Library Hub";
|
||||
const STYLE_ID = "pm-library-hub-style";
|
||||
const KIND_STORAGE_KEY = "pm-library-hub-kind";
|
||||
|
||||
// Saved prompt kinds share prompt_manager_data.json and are told apart by the browser's Type filter.
|
||||
const PROMPT_KINDS = [
|
||||
{ id: "prompt", label: "Prompt Manager", badge: "P", color: "56, 130, 246", hint: "Saved from Prompt Manager or Library Manager." },
|
||||
{ id: "compose", label: "Prompt Composer", badge: "C", color: "47, 146, 72", hint: "Prompt Composer setups saved with Library Manager." },
|
||||
{ id: "layout", label: "Prompt Layout", badge: "L", color: "124, 92, 220", hint: "Prompt Layout Builder layouts saved with Library Manager." },
|
||||
{ id: "recipe", label: "Prompt Recipe", badge: "R", color: "235, 140, 35", hint: "Recipes saved with Library Manager." },
|
||||
];
|
||||
|
||||
const SECTIONS = [
|
||||
{ id: "prompts", title: "Saved Prompts", store: "manager", kinds: PROMPT_KINDS, unit: "entr" },
|
||||
{ id: "snippets", title: "Saved Snippets", browseTitle: "Saved Composer Snippets", store: "composer", hint: "Prompt snippets used by Prompt Composer.", unit: "snippet" },
|
||||
{ id: "system", title: "Saved System Prompts", store: "generator", hint: "System prompts used by Prompt Generator.", unit: "prompt" },
|
||||
];
|
||||
|
||||
const plural = (count, unit) => `${count} ${unit === "entr" ? (count === 1 ? "entry" : "entries") : `${unit}${count === 1 ? "" : "s"}`}`;
|
||||
|
||||
function libraryFor(section, kind) {
|
||||
if (!kind) return { id: section.id, title: section.browseTitle || section.title, store: section.store, unit: section.unit };
|
||||
return { id: `${section.id}_${kind.id}`, title: `${section.title} - ${kind.label}`, store: section.store, filter: kind.id, unit: section.unit };
|
||||
}
|
||||
|
||||
const STORE_ENDPOINTS = {
|
||||
generator: SYSTEM_PROMPTS_ENDPOINT_PREFIX,
|
||||
composer: COMPOSER_ENDPOINT_PREFIX,
|
||||
manager: PROMPT_ADVANCED_ENDPOINT_PREFIX,
|
||||
};
|
||||
|
||||
// Stand-in "node" objects: the shared browser and Composer helpers keep their loaded data on these.
|
||||
const hosts = {
|
||||
generator: { prompts: {} },
|
||||
composer: { prompts: {} },
|
||||
manager: { prompts: {} },
|
||||
};
|
||||
|
||||
async function fetchStore(host, endpointPrefix) {
|
||||
const response = await api.fetchApi(`${endpointPrefix}/get-prompts`, { cache: "no-store" });
|
||||
if (!response.ok) throw new Error(`Could not load ${endpointPrefix} (${response.status})`);
|
||||
host.prompts = await response.json();
|
||||
return host.prompts;
|
||||
}
|
||||
|
||||
const loadSystemPrompts = (host) => fetchStore(host, SYSTEM_PROMPTS_ENDPOINT_PREFIX);
|
||||
const loadManagerPrompts = (host) => fetchStore(host, PROMPT_ADVANCED_ENDPOINT_PREFIX);
|
||||
|
||||
function categoryNames(data) {
|
||||
return Object.keys(data || {})
|
||||
.filter((category) => category !== "__meta__" && data[category] && typeof data[category] === "object")
|
||||
.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }));
|
||||
}
|
||||
|
||||
function entryNames(library, category) {
|
||||
const data = hosts[library.store].prompts;
|
||||
if (library.store === "manager") {
|
||||
return getPromptNamesForCategory(hosts.manager, category, { contentFilter: library.filter, endpointPrefix: PROMPT_ADVANCED_ENDPOINT_PREFIX });
|
||||
}
|
||||
return Object.keys(getCategoryPromptEntries(data?.[category], library.store));
|
||||
}
|
||||
|
||||
function summarize(library) {
|
||||
const data = hosts[library.store].prompts;
|
||||
let entries = 0;
|
||||
let categories = 0;
|
||||
for (const category of categoryNames(data)) {
|
||||
const count = entryNames(library, category).length;
|
||||
entries += count;
|
||||
if (count) categories += 1;
|
||||
}
|
||||
const groups = library.store === "composer" ? Object.keys(hosts.composer.composerPromptLibrary?._types_ || {}).length : 0;
|
||||
return { entries, categories, groups };
|
||||
}
|
||||
|
||||
function timestamp() {
|
||||
return new Date().toISOString().slice(0, 19).replace(/[:T]/g, "-");
|
||||
}
|
||||
|
||||
function pickJsonFile() {
|
||||
return new Promise((resolve) => {
|
||||
const input = document.createElement("input");
|
||||
input.type = "file";
|
||||
input.accept = ".json,application/json";
|
||||
input.onchange = () => resolve(input.files?.[0] || null);
|
||||
input.oncancel = () => resolve(null);
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
|
||||
async function readLibraryFile() {
|
||||
const file = await pickJsonFile();
|
||||
if (!file) return null;
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(await file.text());
|
||||
} catch {
|
||||
throw new Error(`"${file.name}" is not valid JSON.`);
|
||||
}
|
||||
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
||||
throw new Error(`"${file.name}" is not a prompt library (expected categories of entries).`);
|
||||
}
|
||||
return { file, data };
|
||||
}
|
||||
|
||||
function makeButton(label, { primary = false, title = "" } = {}) {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.textContent = label;
|
||||
button.title = title;
|
||||
button.className = primary ? "pm-hub-btn pm-hub-btn-primary" : "pm-hub-btn";
|
||||
return button;
|
||||
}
|
||||
|
||||
// Category picker modelled on Prompt Composer's "Save JSONs" dialog.
|
||||
function showCategoryExportDialog(library, categories) {
|
||||
return new Promise((resolve) => {
|
||||
const selected = new Set(categories.map((item) => item.name));
|
||||
const overlay = document.createElement("div");
|
||||
overlay.className = "pm-hub-overlay";
|
||||
const dialog = document.createElement("div");
|
||||
dialog.className = "pm-hub-dialog";
|
||||
|
||||
const header = document.createElement("div");
|
||||
header.className = "pm-hub-dialog-header";
|
||||
const heading = document.createElement("div");
|
||||
heading.className = "pm-hub-dialog-title";
|
||||
heading.textContent = `Export ${library.title}`;
|
||||
const hint = document.createElement("div");
|
||||
hint.className = "pm-hub-muted";
|
||||
hint.textContent = "Select the categories to export as one JSON file.";
|
||||
header.append(heading, hint);
|
||||
|
||||
const body = document.createElement("div");
|
||||
body.className = "pm-hub-dialog-grid";
|
||||
const cards = new Map();
|
||||
for (const item of categories) {
|
||||
const card = document.createElement("button");
|
||||
card.type = "button";
|
||||
card.className = "pm-hub-pick";
|
||||
const name = document.createElement("div");
|
||||
name.className = "pm-hub-pick-name";
|
||||
name.textContent = item.name;
|
||||
const count = document.createElement("div");
|
||||
count.className = "pm-hub-muted";
|
||||
count.textContent = `${item.count} entr${item.count === 1 ? "y" : "ies"}`;
|
||||
card.append(name, count);
|
||||
card.onclick = () => {
|
||||
if (selected.has(item.name)) selected.delete(item.name);
|
||||
else selected.add(item.name);
|
||||
sync();
|
||||
};
|
||||
cards.set(item.name, card);
|
||||
body.appendChild(card);
|
||||
}
|
||||
|
||||
const footer = document.createElement("div");
|
||||
footer.className = "pm-hub-dialog-footer";
|
||||
const info = document.createElement("div");
|
||||
info.className = "pm-hub-muted";
|
||||
info.style.marginRight = "auto";
|
||||
const clearButton = makeButton("Clear");
|
||||
const allButton = makeButton("Select All");
|
||||
const cancelButton = makeButton("Cancel");
|
||||
const saveButton = makeButton("Export JSON", { primary: true });
|
||||
footer.append(info, clearButton, allButton, cancelButton, saveButton);
|
||||
|
||||
function sync() {
|
||||
cards.forEach((card, name) => card.classList.toggle("active", selected.has(name)));
|
||||
const total = categories.filter((item) => selected.has(item.name)).reduce((sum, item) => sum + item.count, 0);
|
||||
info.textContent = `${selected.size} categor${selected.size === 1 ? "y" : "ies"} · ${total} entr${total === 1 ? "y" : "ies"}`;
|
||||
saveButton.disabled = selected.size === 0;
|
||||
}
|
||||
|
||||
const finish = (value) => {
|
||||
overlay.remove();
|
||||
resolve(value);
|
||||
};
|
||||
clearButton.onclick = () => { selected.clear(); sync(); };
|
||||
allButton.onclick = () => { categories.forEach((item) => selected.add(item.name)); sync(); };
|
||||
cancelButton.onclick = () => finish(null);
|
||||
saveButton.onclick = () => finish(categories.map((item) => item.name).filter((name) => selected.has(name)));
|
||||
overlay.onclick = (event) => { if (event.target === overlay) finish(null); };
|
||||
|
||||
dialog.append(header, body, footer);
|
||||
overlay.appendChild(dialog);
|
||||
document.body.appendChild(overlay);
|
||||
sync();
|
||||
});
|
||||
}
|
||||
|
||||
async function exportLibrary(library) {
|
||||
if (library.store === "composer") {
|
||||
await loadComposerPrompts(hosts.composer);
|
||||
await exportComposerJsonLibrary(hosts.composer);
|
||||
return;
|
||||
}
|
||||
const data = hosts[library.store].prompts;
|
||||
const categories = categoryNames(data)
|
||||
.map((name) => ({ name, count: entryNames(library, name).length }))
|
||||
.filter((item) => item.count > 0);
|
||||
if (!categories.length) {
|
||||
await showInfo("Nothing to Export", `${library.title} has no entries yet.`);
|
||||
return;
|
||||
}
|
||||
const picked = await showCategoryExportDialog(library, categories);
|
||||
if (!picked?.length) return;
|
||||
|
||||
const out = {};
|
||||
for (const category of picked) {
|
||||
const source = data[category];
|
||||
const names = new Set(entryNames(library, category));
|
||||
out[category] = Object.fromEntries(Object.entries(source).filter(([key]) => names.has(key) || isHiddenPromptEntryKey(key)));
|
||||
}
|
||||
const blob = new Blob([JSON.stringify(out, null, 2)], { type: "application/json" });
|
||||
triggerBrowserDownload(blob, `${library.id}_${timestamp()}.json`);
|
||||
}
|
||||
|
||||
function showChoiceDialog(title, choices) {
|
||||
return new Promise((resolve) => {
|
||||
const overlay = document.createElement("div");
|
||||
overlay.className = "pm-hub-overlay";
|
||||
const dialog = document.createElement("div");
|
||||
dialog.className = "pm-hub-dialog pm-hub-dialog-small";
|
||||
const header = document.createElement("div");
|
||||
header.className = "pm-hub-dialog-header";
|
||||
const heading = document.createElement("div");
|
||||
heading.className = "pm-hub-dialog-title";
|
||||
heading.textContent = title;
|
||||
header.appendChild(heading);
|
||||
const body = document.createElement("div");
|
||||
body.className = "pm-hub-dialog-list";
|
||||
const finish = (value) => {
|
||||
overlay.remove();
|
||||
resolve(value);
|
||||
};
|
||||
for (const choice of choices) {
|
||||
const option = document.createElement("button");
|
||||
option.type = "button";
|
||||
option.className = "pm-hub-pick";
|
||||
const name = document.createElement("div");
|
||||
name.className = "pm-hub-pick-name";
|
||||
name.textContent = choice.label;
|
||||
const description = document.createElement("div");
|
||||
description.className = "pm-hub-muted";
|
||||
description.textContent = choice.description;
|
||||
option.append(name, description);
|
||||
option.onclick = () => finish(choice.value);
|
||||
body.appendChild(option);
|
||||
}
|
||||
const footer = document.createElement("div");
|
||||
footer.className = "pm-hub-dialog-footer";
|
||||
const cancelButton = makeButton("Cancel");
|
||||
cancelButton.style.marginLeft = "auto";
|
||||
cancelButton.onclick = () => finish(null);
|
||||
footer.appendChild(cancelButton);
|
||||
overlay.onclick = (event) => { if (event.target === overlay) finish(null); };
|
||||
dialog.append(header, body, footer);
|
||||
overlay.appendChild(dialog);
|
||||
document.body.appendChild(overlay);
|
||||
});
|
||||
}
|
||||
|
||||
async function importLibrary(library) {
|
||||
if (library.store === "manager") {
|
||||
await importJsonFile(library, false);
|
||||
return;
|
||||
}
|
||||
const choices = [
|
||||
{ value: "merge", label: "Merge a file", description: "Add the file's entries; you choose what happens to entries that already exist." },
|
||||
{ value: "replace", label: "Replace with a file", description: `Replace all ${library.title} with the file's contents.` },
|
||||
];
|
||||
if (library.store === "generator") {
|
||||
choices.push({ value: "defaults", label: "Restore built-in defaults", description: "Add back missing built-in system prompts without touching yours." });
|
||||
}
|
||||
const action = await showChoiceDialog(`Import ${library.title}`, choices);
|
||||
if (!action) return;
|
||||
if (action === "defaults") {
|
||||
await restoreDefaultSystemPrompts();
|
||||
} else if (library.store === "composer") {
|
||||
await loadComposerPrompts(hosts.composer);
|
||||
await (action === "replace" ? openComposerJsonLibrary : mergeComposerJsonLibrary)(hosts.composer);
|
||||
} else {
|
||||
await importJsonFile(library, action === "replace");
|
||||
}
|
||||
}
|
||||
|
||||
async function importJsonFile(library, replace) {
|
||||
const picked = await readLibraryFile();
|
||||
if (!picked) return;
|
||||
if (replace) {
|
||||
const confirmed = await showConfirm(
|
||||
`Replace ${library.title}`,
|
||||
`Replace ALL ${library.title} with "${picked.file.name}"? This cannot be undone.`,
|
||||
"Replace",
|
||||
UI.accent,
|
||||
);
|
||||
if (!confirmed) return;
|
||||
}
|
||||
|
||||
let mode = replace ? "replace" : "skip_existing";
|
||||
if (!replace) {
|
||||
const current = hosts[library.store].prompts;
|
||||
let duplicates = 0;
|
||||
for (const category of categoryNames(picked.data)) {
|
||||
const existing = getCategoryPromptEntries(current?.[category], library.store);
|
||||
for (const name of Object.keys(getCategoryPromptEntries(picked.data[category], library.store))) {
|
||||
if (Object.prototype.hasOwnProperty.call(existing, name)) duplicates += 1;
|
||||
}
|
||||
}
|
||||
if (duplicates) {
|
||||
mode = await showComposerImportModeDialog({ duplicatePromptCount: duplicates });
|
||||
if (mode === "cancel") return;
|
||||
}
|
||||
}
|
||||
|
||||
// Prompt Manager's file is shared by all saved kinds; entries keep their kind through their data blocks.
|
||||
const endpointPrefix = library.store === "manager" ? PROMPT_ENDPOINT_PREFIX : STORE_ENDPOINTS[library.store];
|
||||
const response = await api.fetchApi(`${endpointPrefix}/import-prompts`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ data: picked.data, mode }),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok || !result?.success) throw new Error(result?.error || "Import failed.");
|
||||
if (replace) {
|
||||
await showInfo("Replace Complete", `${library.title} replaced with "${picked.file.name}".`);
|
||||
return;
|
||||
}
|
||||
const imported = Number(result.imported_prompts || 0);
|
||||
const skipped = Number(result.skipped_prompts || 0);
|
||||
const created = Number(result.created_categories || 0);
|
||||
const parts = [`Imported ${imported} entr${imported === 1 ? "y" : "ies"}`];
|
||||
if (created) parts.push(`created ${created} categor${created === 1 ? "y" : "ies"}`);
|
||||
if (skipped) parts.push(`kept ${skipped} existing entr${skipped === 1 ? "y" : "ies"}`);
|
||||
await showInfo("Import Complete", `${parts.join(", ")}.`);
|
||||
}
|
||||
|
||||
async function restoreDefaultSystemPrompts() {
|
||||
const confirmed = await showConfirm(
|
||||
"Restore Default System Prompts",
|
||||
"This adds any missing built-in system prompts without overwriting your custom ones. Continue?",
|
||||
"Restore",
|
||||
UI.accent,
|
||||
);
|
||||
if (!confirmed) return;
|
||||
const response = await api.fetchApi(`${SYSTEM_PROMPTS_ENDPOINT_PREFIX}/reimport-default-prompts`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok || !result?.success) throw new Error(result?.error || "Failed to restore default system prompts.");
|
||||
await showInfo("Restore Complete", "Added back any missing built-in system prompts.");
|
||||
}
|
||||
|
||||
async function browseLibrary(library) {
|
||||
const title = library.title;
|
||||
if (library.store === "generator") {
|
||||
await showThumbnailBrowser(hosts.generator, "", "", {
|
||||
title,
|
||||
endpointPrefix: SYSTEM_PROMPTS_ENDPOINT_PREFIX,
|
||||
loadPromptsFn: loadSystemPrompts,
|
||||
promptOnly: true,
|
||||
allowMultiSelect: false,
|
||||
editMode: true,
|
||||
});
|
||||
} else if (library.store === "composer") {
|
||||
await showThumbnailBrowser(hosts.composer, "", "", {
|
||||
title,
|
||||
endpointPrefix: COMPOSER_ENDPOINT_PREFIX,
|
||||
loadPromptsFn: loadComposerPrompts,
|
||||
preferenceScope: "composer",
|
||||
promptOnly: true,
|
||||
allowMultiSelect: false,
|
||||
editMode: true,
|
||||
});
|
||||
} else {
|
||||
await showThumbnailBrowser(hosts.manager, "", "", {
|
||||
title,
|
||||
loadPromptsFn: loadManagerPrompts,
|
||||
contentFilter: library.filter,
|
||||
hideContentFilterControl: true,
|
||||
filterEmptyCategories: true,
|
||||
allowMultiSelect: false,
|
||||
editMode: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function ensureStyle() {
|
||||
if (document.getElementById(STYLE_ID)) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = STYLE_ID;
|
||||
style.textContent = `
|
||||
.pm-hub { display: flex; flex-direction: column; gap: 12px; height: 100%; overflow: auto; padding: 12px;
|
||||
box-sizing: border-box; color: ${UI.textPrimary}; font: 14px/1.4 sans-serif; }
|
||||
.pm-hub-header { display: flex; align-items: center; gap: 8px; }
|
||||
.pm-hub-title { font-size: 16px; font-weight: 700; color: ${UI.textHeading}; margin-right: auto; }
|
||||
.pm-hub-muted { color: ${UI.textMuted}; font-size: 13px; }
|
||||
.pm-hub-section { border: 1px solid ${UI.panelBorder}; border-radius: 8px; background: ${UI.panel}; padding: 12px;
|
||||
display: flex; flex-direction: column; gap: 10px; }
|
||||
.pm-hub-section-head { display: flex; align-items: baseline; gap: 8px; }
|
||||
.pm-hub-name { font-size: 15px; font-weight: 700; color: ${UI.textHeading}; }
|
||||
.pm-hub-count { margin-left: auto; color: ${UI.textHint}; font-size: 13px; white-space: nowrap; }
|
||||
.pm-hub-kinds { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 6px; }
|
||||
.pm-hub-kind { display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-radius: 6px; cursor: pointer;
|
||||
border: 1px solid ${UI.inputBorder}; background: ${UI.inputBg}; color: ${UI.textPrimary}; font: inherit; font-size: 13px; text-align: left; }
|
||||
.pm-hub-kind:hover { border-color: rgba(var(--pm-hub-rgb), 0.8); }
|
||||
.pm-hub-kind.active { border-color: rgba(var(--pm-hub-rgb), 0.95); background: rgba(var(--pm-hub-rgb), 0.18); }
|
||||
.pm-hub-kind-count { margin-left: auto; color: ${UI.textHint}; }
|
||||
.pm-hub-badge { flex: 0 0 20px; height: 20px; border-radius: 5px; display: flex; align-items: center; justify-content: center;
|
||||
font-weight: 700; font-size: 12px; color: #fff; background: rgba(var(--pm-hub-rgb), 0.9); }
|
||||
.pm-hub-actions { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; }
|
||||
.pm-hub-btn { padding: 6px 10px; border-radius: 6px; border: 1px solid ${UI.inputBorder}; background: ${UI.buttonBg};
|
||||
color: ${UI.textPrimary}; font: inherit; font-size: 13px; cursor: pointer; white-space: nowrap; }
|
||||
.pm-hub-btn:hover:not(:disabled) { border-color: ${UI.accentBorder}; }
|
||||
.pm-hub-btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
.pm-hub-btn-primary { border-color: ${UI.accentBorder}; background: hsl(208 73% 57% / 0.2); color: #dbeafe; }
|
||||
.pm-hub-overlay { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.72); z-index: 9999; display: flex;
|
||||
align-items: center; justify-content: center; }
|
||||
.pm-hub-dialog { width: min(860px, calc(100vw - 48px)); max-height: min(760px, calc(100vh - 48px)); background: ${UI.panel};
|
||||
border: 1px solid ${UI.panelBorder}; border-radius: 10px; box-shadow: 0 10px 32px rgba(0, 0, 0, 0.45);
|
||||
color: ${UI.textPrimary}; display: flex; flex-direction: column; overflow: hidden; font: 14px/1.4 sans-serif; }
|
||||
.pm-hub-dialog-small { width: min(480px, calc(100vw - 48px)); }
|
||||
.pm-hub-dialog-header { padding: 16px 18px 10px; border-bottom: 1px solid ${UI.sectionBorder}; }
|
||||
.pm-hub-dialog-title { font-size: 16px; font-weight: 700; margin-bottom: 6px; }
|
||||
.pm-hub-dialog-grid { padding: 16px 18px; overflow: auto; display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 12px; }
|
||||
.pm-hub-dialog-list { padding: 16px 18px; overflow: auto; display: flex; flex-direction: column; gap: 10px; }
|
||||
.pm-hub-dialog-footer { padding: 12px 18px 18px; border-top: 1px solid ${UI.sectionBorder}; display: flex; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||
.pm-hub-pick { text-align: left; min-height: 64px; border: 1px solid ${UI.inputBorder}; border-radius: 10px; background: ${UI.cardBg};
|
||||
color: ${UI.textPrimary}; padding: 12px; cursor: pointer; display: flex; flex-direction: column; gap: 6px; font: inherit; }
|
||||
.pm-hub-pick:hover { border-color: ${UI.accentBorder}; }
|
||||
.pm-hub-pick.active { background: hsl(208 73% 57% / 0.16); border-color: ${UI.accentBorder}; }
|
||||
.pm-hub-pick-name { font-size: 15px; font-weight: 700; word-break: break-word; }
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
function renderHub(container) {
|
||||
ensureStyle();
|
||||
container.replaceChildren();
|
||||
const root = document.createElement("div");
|
||||
root.className = "pm-hub";
|
||||
container.appendChild(root);
|
||||
|
||||
const header = document.createElement("div");
|
||||
header.className = "pm-hub-header";
|
||||
const title = document.createElement("div");
|
||||
title.className = "pm-hub-title";
|
||||
title.textContent = HUB_TITLE;
|
||||
const refreshButton = makeButton("Refresh", { title: "Reload all libraries" });
|
||||
header.append(title, refreshButton);
|
||||
const status = document.createElement("div");
|
||||
status.className = "pm-hub-muted";
|
||||
root.append(header);
|
||||
|
||||
let selectedKind = PROMPT_KINDS.find((kind) => kind.id === localStorage.getItem(KIND_STORAGE_KEY)) || PROMPT_KINDS[0];
|
||||
let busy = false;
|
||||
const updaters = [];
|
||||
const update = () => updaters.forEach((fn) => fn());
|
||||
|
||||
const refresh = async () => {
|
||||
status.textContent = "Loading libraries…";
|
||||
const results = await Promise.allSettled([
|
||||
loadManagerPrompts(hosts.manager),
|
||||
loadComposerPrompts(hosts.composer),
|
||||
loadSystemPrompts(hosts.generator),
|
||||
]);
|
||||
const failed = results.filter((result) => result.status === "rejected");
|
||||
failed.forEach((result) => console.error("[PromptLibraryHub]", result.reason));
|
||||
status.textContent = failed.length ? "Some libraries could not be loaded; see the console." : "";
|
||||
update();
|
||||
};
|
||||
|
||||
const run = async (task) => {
|
||||
if (busy) return;
|
||||
busy = true;
|
||||
try {
|
||||
await task();
|
||||
} catch (error) {
|
||||
console.error("[PromptLibraryHub]", error);
|
||||
await showInfo(HUB_TITLE, error?.message || String(error));
|
||||
} finally {
|
||||
busy = false;
|
||||
await refresh();
|
||||
}
|
||||
};
|
||||
|
||||
for (const section of SECTIONS) {
|
||||
const card = document.createElement("div");
|
||||
card.className = "pm-hub-section";
|
||||
const head = document.createElement("div");
|
||||
head.className = "pm-hub-section-head";
|
||||
const name = document.createElement("div");
|
||||
name.className = "pm-hub-name";
|
||||
name.textContent = section.title;
|
||||
const count = document.createElement("div");
|
||||
count.className = "pm-hub-count";
|
||||
head.append(name, count);
|
||||
const hint = document.createElement("div");
|
||||
hint.className = "pm-hub-muted";
|
||||
card.append(head);
|
||||
|
||||
const current = () => libraryFor(section, section.kinds ? selectedKind : null);
|
||||
|
||||
if (section.kinds) {
|
||||
const kinds = document.createElement("div");
|
||||
kinds.className = "pm-hub-kinds";
|
||||
for (const kind of section.kinds) {
|
||||
const chip = document.createElement("button");
|
||||
chip.type = "button";
|
||||
chip.className = "pm-hub-kind";
|
||||
chip.style.setProperty("--pm-hub-rgb", kind.color);
|
||||
const badge = document.createElement("span");
|
||||
badge.className = "pm-hub-badge";
|
||||
badge.textContent = kind.badge;
|
||||
const label = document.createElement("span");
|
||||
label.textContent = kind.label;
|
||||
const kindCount = document.createElement("span");
|
||||
kindCount.className = "pm-hub-kind-count";
|
||||
chip.append(badge, label, kindCount);
|
||||
chip.onclick = () => {
|
||||
selectedKind = kind;
|
||||
localStorage.setItem(KIND_STORAGE_KEY, kind.id);
|
||||
update();
|
||||
};
|
||||
updaters.push(() => {
|
||||
chip.classList.toggle("active", kind === selectedKind);
|
||||
kindCount.textContent = String(summarize(libraryFor(section, kind)).entries);
|
||||
});
|
||||
kinds.appendChild(chip);
|
||||
}
|
||||
card.appendChild(kinds);
|
||||
}
|
||||
card.appendChild(hint);
|
||||
|
||||
const actions = document.createElement("div");
|
||||
actions.className = "pm-hub-actions";
|
||||
const browse = makeButton("Browse & Edit", { primary: true });
|
||||
browse.onclick = () => run(() => browseLibrary(current()));
|
||||
const importButton = makeButton("Import");
|
||||
importButton.onclick = () => run(() => importLibrary(current()));
|
||||
const exportButton = makeButton("Export");
|
||||
exportButton.onclick = () => run(() => exportLibrary(current()));
|
||||
actions.append(browse, importButton, exportButton);
|
||||
card.appendChild(actions);
|
||||
|
||||
updaters.push(() => {
|
||||
const library = current();
|
||||
const { entries, categories, groups } = summarize(library);
|
||||
const parts = [plural(entries, library.unit), `${categories} categor${categories === 1 ? "y" : "ies"}`];
|
||||
if (groups) parts.push(`${groups} group${groups === 1 ? "" : "s"}`);
|
||||
count.textContent = parts.join(" · ");
|
||||
hint.textContent = section.kinds ? selectedKind.hint : section.hint;
|
||||
browse.title = `Open ${library.title} in the Prompt Browser with editing on`;
|
||||
importButton.title = section.store === "manager"
|
||||
? "Merge a JSON file into Saved Prompts (entries keep their own type)"
|
||||
: `Merge or replace ${library.title} from a file`;
|
||||
exportButton.title = section.store === "composer" ? "Export selected prompt groups as a ZIP" : "Export selected categories as JSON";
|
||||
});
|
||||
|
||||
root.appendChild(card);
|
||||
}
|
||||
root.appendChild(status);
|
||||
|
||||
refreshButton.onclick = () => run(async () => {});
|
||||
update();
|
||||
refresh();
|
||||
}
|
||||
|
||||
const SHOW_SIDEBAR_SETTING = "PromptManager.LibraryHub.ShowSidebar";
|
||||
const SIDEBAR_TAB_ID = "prompt-library-hub";
|
||||
let sidebarTabRegistered = false;
|
||||
|
||||
function syncSidebarTab(show) {
|
||||
const manager = app.extensionManager;
|
||||
if (show && !sidebarTabRegistered && manager?.registerSidebarTab) {
|
||||
manager.registerSidebarTab({
|
||||
id: SIDEBAR_TAB_ID,
|
||||
icon: "pi pi-book",
|
||||
title: HUB_TITLE,
|
||||
tooltip: HUB_TITLE,
|
||||
label: "Prompts",
|
||||
type: "custom",
|
||||
render: (container) => renderHub(container),
|
||||
});
|
||||
sidebarTabRegistered = true;
|
||||
} else if (!show && sidebarTabRegistered && manager?.unregisterSidebarTab) {
|
||||
manager.unregisterSidebarTab(SIDEBAR_TAB_ID);
|
||||
sidebarTabRegistered = false;
|
||||
}
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "PromptManager.LibraryHub",
|
||||
settings: [
|
||||
{
|
||||
id: SHOW_SIDEBAR_SETTING,
|
||||
category: ["Prompt Manager", "4. Advanced Preferences", "Show Prompts Sidebar Button"],
|
||||
name: "Show the Prompts button (Prompt Library Hub) in the sidebar",
|
||||
tooltip: "Adds a Prompts button to ComfyUI's left sidebar that opens the Prompt Library Hub.",
|
||||
type: "boolean",
|
||||
defaultValue: true,
|
||||
onChange: (value) => syncSidebarTab(value !== false),
|
||||
},
|
||||
],
|
||||
setup() {
|
||||
const value = app.extensionManager?.setting?.get?.(SHOW_SIDEBAR_SETTING)
|
||||
?? app.ui?.settings?.getSettingValue?.(SHOW_SIDEBAR_SETTING);
|
||||
syncSidebarTab(value !== false);
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
/**
|
||||
* PromptModelLoader Extension for ComfyUI
|
||||
* Displays model type and name info on the node.
|
||||
* Dynamically shows/hides Model B outputs when two models are found.
|
||||
* Hides CLIP/VAE slots for non-checkpoint models.
|
||||
*/
|
||||
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
// --- Draw model info (shared between single and dual) ---
|
||||
const TYPE_COLORS = {
|
||||
"Checkpoint": "#4CAF50",
|
||||
"Diffusion": "#2196F3",
|
||||
"GGUF": "#FF9800",
|
||||
"NOT FOUND": "#F44336",
|
||||
"Unknown": "#9E9E9E"
|
||||
};
|
||||
|
||||
function drawModelRow(ctx, typeText, modelName, yOffset, label, widgetWidth) {
|
||||
const padding = 8;
|
||||
const badgeColor = TYPE_COLORS[typeText] || TYPE_COLORS["Unknown"];
|
||||
const badgeLabel = label ? `${label} ${typeText}` : typeText;
|
||||
|
||||
// Badge pill
|
||||
ctx.font = "bold 11px Arial";
|
||||
const typeWidth = ctx.measureText(badgeLabel).width + 14;
|
||||
ctx.fillStyle = badgeColor;
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(padding, yOffset + 4, typeWidth, 16, 8);
|
||||
ctx.fill();
|
||||
|
||||
// Badge text
|
||||
ctx.fillStyle = "#FFFFFF";
|
||||
ctx.textAlign = "left";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(badgeLabel, padding + 7, yOffset + 12);
|
||||
|
||||
// Model name to the right of badge
|
||||
ctx.font = "12px Arial";
|
||||
ctx.fillStyle = typeText === "NOT FOUND" ? "#F44336" : "#CCCCCC";
|
||||
const nameX = padding + typeWidth + 8;
|
||||
const maxNameWidth = widgetWidth - nameX - padding;
|
||||
let displayName = modelName || "";
|
||||
while (ctx.measureText(displayName).width > maxNameWidth && displayName.length > 5) {
|
||||
displayName = displayName.slice(0, -4) + "...";
|
||||
}
|
||||
ctx.fillText(displayName, nameX, yOffset + 12);
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "PromptManager.ModelLoader",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "PromptModelLoader") return;
|
||||
|
||||
// Hook into onExecuted to receive UI data from Python
|
||||
const origOnExecuted = nodeType.prototype.onExecuted;
|
||||
nodeType.prototype.onExecuted = function (message) {
|
||||
origOnExecuted?.apply(this, arguments);
|
||||
|
||||
const info = message?.model_info?.[0];
|
||||
if (!info) return;
|
||||
|
||||
this._applyModelInfo(info);
|
||||
};
|
||||
|
||||
// Central method to apply model info
|
||||
nodeType.prototype._applyModelInfo = function (info) {
|
||||
const typeA = info.model_type_a || "Unknown";
|
||||
const nameA = info.model_name_a || "";
|
||||
const hasB = !!info.has_model_b;
|
||||
const typeB = info.model_type_b || "";
|
||||
const nameB = info.model_name_b || "";
|
||||
const isCheckpointA = typeA === "Checkpoint";
|
||||
const isCheckpointB = typeB === "Checkpoint";
|
||||
|
||||
// Store for display and serialization
|
||||
this._modelInfo = info;
|
||||
|
||||
// Update title
|
||||
this.title = hasB
|
||||
? `Prompt Model Loader [${typeA} + ${typeB}]`
|
||||
: `Prompt Model Loader [${typeA}]`;
|
||||
|
||||
// Update output slots
|
||||
this._updateOutputSlots(hasB, isCheckpointA, isCheckpointB);
|
||||
|
||||
// Create/update info widget
|
||||
this._ensureInfoWidget();
|
||||
this.setDirtyCanvas(true, true);
|
||||
};
|
||||
|
||||
// Save state into the workflow JSON
|
||||
const origOnSerialize = nodeType.prototype.onSerialize;
|
||||
nodeType.prototype.onSerialize = function (o) {
|
||||
origOnSerialize?.apply(this, arguments);
|
||||
if (this._modelInfo) {
|
||||
o._modelLoaderState = this._modelInfo;
|
||||
}
|
||||
};
|
||||
|
||||
// Restore state when workflow is loaded / tab is switched back
|
||||
const origOnConfigure = nodeType.prototype.onConfigure;
|
||||
nodeType.prototype.onConfigure = function (info) {
|
||||
origOnConfigure?.apply(this, arguments);
|
||||
const state = info?._modelLoaderState;
|
||||
if (state) {
|
||||
requestAnimationFrame(() => {
|
||||
this._applyModelInfo(state);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// Manage output slot visibility
|
||||
// Full outputs: model_a(0), clip_a(1), vae_a(2), model_b(3), clip_b(4), vae_b(5)
|
||||
nodeType.prototype._updateOutputSlots = function (hasB, isCheckpointA, isCheckpointB) {
|
||||
if (!this._originalOutputs) {
|
||||
this._originalOutputs = this.outputs.map(o => ({ ...o }));
|
||||
}
|
||||
|
||||
// Build desired output list
|
||||
const desired = [];
|
||||
|
||||
// Model A always present
|
||||
desired.push(this._originalOutputs[0]); // model_a
|
||||
|
||||
// CLIP A / VAE A only for checkpoints
|
||||
if (isCheckpointA) {
|
||||
desired.push(this._originalOutputs[1]); // clip_a
|
||||
desired.push(this._originalOutputs[2]); // vae_a
|
||||
}
|
||||
|
||||
// Model B outputs only when two models found
|
||||
if (hasB) {
|
||||
desired.push(this._originalOutputs[3]); // model_b
|
||||
if (isCheckpointB) {
|
||||
desired.push(this._originalOutputs[4]); // clip_b
|
||||
desired.push(this._originalOutputs[5]); // vae_b
|
||||
}
|
||||
}
|
||||
|
||||
// Disconnect outputs that will be removed
|
||||
for (let i = this.outputs.length - 1; i >= desired.length; i--) {
|
||||
if (this.outputs[i]?.links?.length > 0) {
|
||||
for (const linkId of [...this.outputs[i].links]) {
|
||||
this.disconnectOutput(i);
|
||||
}
|
||||
}
|
||||
this.removeOutput(i);
|
||||
}
|
||||
|
||||
// Add/update outputs to match desired
|
||||
for (let i = 0; i < desired.length; i++) {
|
||||
if (i < this.outputs.length) {
|
||||
this.outputs[i].name = desired[i].name;
|
||||
this.outputs[i].type = desired[i].type;
|
||||
} else {
|
||||
this.addOutput(desired[i].name, desired[i].type);
|
||||
}
|
||||
}
|
||||
|
||||
this.computeSize();
|
||||
};
|
||||
|
||||
// Info widget helper
|
||||
nodeType.prototype._ensureInfoWidget = function () {
|
||||
const info = this._modelInfo;
|
||||
if (!info) return;
|
||||
|
||||
const hasB = !!info.has_model_b;
|
||||
const widgetHeight = hasB ? 50 : 26;
|
||||
|
||||
let widget = this.widgets?.find(w => w.name === "_model_info_display");
|
||||
if (!widget) {
|
||||
widget = {
|
||||
name: "_model_info_display",
|
||||
type: "custom",
|
||||
y: 0,
|
||||
computeSize: () => [0, widgetHeight],
|
||||
draw: function (ctx, node, widgetWidth, y) {
|
||||
const info = node._modelInfo;
|
||||
if (!info) return;
|
||||
const hasB = !!info.has_model_b;
|
||||
if (hasB) {
|
||||
drawModelRow(ctx, info.model_type_a || "Unknown", info.model_name_a || "", y, "A:", widgetWidth);
|
||||
drawModelRow(ctx, info.model_type_b || "Unknown", info.model_name_b || "", y + 24, "B:", widgetWidth);
|
||||
} else {
|
||||
drawModelRow(ctx, info.model_type_a || "Unknown", info.model_name_a || "", y, "", widgetWidth);
|
||||
}
|
||||
}
|
||||
};
|
||||
if (!this.widgets) this.widgets = [];
|
||||
this.widgets.push(widget);
|
||||
}
|
||||
// Update height for single vs dual model
|
||||
widget.computeSize = () => [0, widgetHeight];
|
||||
this.computeSize();
|
||||
};
|
||||
|
||||
// Reset display on clear/reconnect
|
||||
const origOnConnectionsChange = nodeType.prototype.onConnectionsChange;
|
||||
nodeType.prototype.onConnectionsChange = function () {
|
||||
origOnConnectionsChange?.apply(this, arguments);
|
||||
// Reset info when input connection changes
|
||||
if (arguments[1] === 0 && arguments[0] === 1) {
|
||||
this._modelInfo = null;
|
||||
this.title = "Prompt Model Loader";
|
||||
// Restore all outputs
|
||||
if (this._originalOutputs) {
|
||||
while (this.outputs.length < this._originalOutputs.length) {
|
||||
const orig = this._originalOutputs[this.outputs.length];
|
||||
this.addOutput(orig.name, orig.type);
|
||||
}
|
||||
}
|
||||
// Remove info widget
|
||||
if (this.widgets) {
|
||||
const idx = this.widgets.findIndex(w => w.name === "_model_info_display");
|
||||
if (idx >= 0) {
|
||||
this.widgets.splice(idx, 1);
|
||||
this.computeSize();
|
||||
}
|
||||
}
|
||||
this.setDirtyCanvas(true, true);
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
export const PROMPT_ENDPOINT_PREFIX = "/prompt-manager";
|
||||
export const PROMPT_ADVANCED_ENDPOINT_PREFIX = "/prompt-manager-advanced";
|
||||
export const SYSTEM_PROMPTS_ENDPOINT_PREFIX = "/prompt-generator";
|
||||
export const COMPOSER_ENDPOINT_PREFIX = "/prompt-manager/compose";
|
||||
|
||||
export const SOURCE_COMPOSE = "Compose Data";
|
||||
export const SOURCE_PROMPT = "Prompt Data";
|
||||
export const SOURCE_SYSTEM_PROMPTS = "System Prompts";
|
||||
|
||||
export function isHiddenPromptEntryKey(name) {
|
||||
const normalized = String(name || "").trim().toLowerCase();
|
||||
return normalized === "__meta__"
|
||||
|| normalized === "_base_prompt_"
|
||||
|| normalized === "_prompt_prefix_"
|
||||
|| normalized === "_category_base_prompt_"
|
||||
|| normalized === "_category_prefix_"
|
||||
|| normalized === "_prompt_type_"
|
||||
|| normalized === "_prompts_"
|
||||
|| normalized === "_category_name_"
|
||||
|| normalized === "_type_file_"
|
||||
|| normalized === "_type_name_"
|
||||
|| normalized === "_subject_type_"
|
||||
|| normalized === "_subject_kind_"
|
||||
|| normalized === "_type_prefix_"
|
||||
|| normalized === "_type_base_prompt_"
|
||||
|| normalized === "_type_nsfw_";
|
||||
}
|
||||
|
||||
export function getPromptStoreKindFromSource(source) {
|
||||
if (source === SOURCE_COMPOSE) return "composer";
|
||||
if (source === SOURCE_PROMPT) return "manager";
|
||||
return "generator";
|
||||
}
|
||||
|
||||
export function getPromptStoreKindFromEndpoint(endpointPrefix) {
|
||||
if (endpointPrefix === COMPOSER_ENDPOINT_PREFIX) return "composer";
|
||||
if (endpointPrefix === SYSTEM_PROMPTS_ENDPOINT_PREFIX) return "generator";
|
||||
return "manager";
|
||||
}
|
||||
|
||||
export function getEndpointPrefixForSource(source) {
|
||||
if (source === SOURCE_PROMPT) return PROMPT_ENDPOINT_PREFIX;
|
||||
if (source === SOURCE_SYSTEM_PROMPTS) return SYSTEM_PROMPTS_ENDPOINT_PREFIX;
|
||||
return COMPOSER_ENDPOINT_PREFIX;
|
||||
}
|
||||
|
||||
export function getCategoryPromptEntries(categoryData, storeKind = "manager") {
|
||||
if (!categoryData || typeof categoryData !== "object" || Array.isArray(categoryData)) return {};
|
||||
if (storeKind === "composer") {
|
||||
const nested = categoryData._prompts_;
|
||||
if (nested && typeof nested === "object" && !Array.isArray(nested)) {
|
||||
return nested;
|
||||
}
|
||||
}
|
||||
return Object.fromEntries(
|
||||
Object.entries(categoryData).filter(([name]) => !isHiddenPromptEntryKey(name))
|
||||
);
|
||||
}
|
||||
|
||||
export function getCategoryPromptEntriesForSource(categoryData, source) {
|
||||
return getCategoryPromptEntries(categoryData, getPromptStoreKindFromSource(source));
|
||||
}
|
||||
|
||||
export function getCategoryPromptEntriesForEndpoint(categoryData, endpointPrefix) {
|
||||
return getCategoryPromptEntries(categoryData, getPromptStoreKindFromEndpoint(endpointPrefix));
|
||||
}
|
||||
|
||||
export function getCategoryPromptEntryForEndpoint(categoryData, promptName, endpointPrefix) {
|
||||
return getCategoryPromptEntriesForEndpoint(categoryData, endpointPrefix)?.[promptName] || null;
|
||||
}
|
||||
|
||||
export function buildSavePromptRequestBody(storeKind, payload) {
|
||||
const body = {
|
||||
category: payload?.category,
|
||||
name: payload?.name,
|
||||
text: payload?.text,
|
||||
};
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "old_name")) body.old_name = payload.old_name;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "old_category")) body.old_category = payload.old_category;
|
||||
|
||||
if (storeKind === "generator") {
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "thumbnail")) body.thumbnail = payload.thumbnail;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "prompt_category")) body.prompt_category = payload.prompt_category;
|
||||
return body;
|
||||
}
|
||||
|
||||
if (storeKind === "composer") {
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "thumbnail")) body.thumbnail = payload.thumbnail;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "prompt_category")) body.prompt_category = payload.prompt_category;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora")) body.lora = payload.lora;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora_strength")) body.lora_strength = payload.lora_strength;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora_image")) body.lora_image = payload.lora_image;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora_image_strength")) body.lora_image_strength = payload.lora_image_strength;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora_video")) body.lora_video = payload.lora_video;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "lora_video_strength")) body.lora_video_strength = payload.lora_video_strength;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "refmod")) body.refmod = payload.refmod;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "refmod_weight")) body.refmod_weight = payload.refmod_weight;
|
||||
return body;
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "thumbnail")) body.thumbnail = payload.thumbnail;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "workflow_data")) body.workflow_data = payload.workflow_data;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "negative_prompt")) body.negative_prompt = payload.negative_prompt;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "loras_a")) body.loras_a = payload.loras_a;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "loras_b")) body.loras_b = payload.loras_b;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "loras_c")) body.loras_c = payload.loras_c;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "loras_d")) body.loras_d = payload.loras_d;
|
||||
if (Object.prototype.hasOwnProperty.call(payload || {}, "trigger_words")) body.trigger_words = payload.trigger_words;
|
||||
return body;
|
||||
}
|
||||
|
||||
export function buildSavePromptRequestBodyForSource(source, payload) {
|
||||
return buildSavePromptRequestBody(getPromptStoreKindFromSource(source), payload);
|
||||
}
|
||||
|
||||
export function buildSavePromptRequestBodyForEndpoint(endpointPrefix, payload) {
|
||||
return buildSavePromptRequestBody(getPromptStoreKindFromEndpoint(endpointPrefix), payload);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
let lockStyleInstalled = false;
|
||||
|
||||
function installLockStyle() {
|
||||
if (lockStyleInstalled) return;
|
||||
lockStyleInstalled = true;
|
||||
const style = document.createElement("style");
|
||||
style.textContent = '.lg-node-widgets textarea[data-pm-locked="true"] { opacity: 0.5; }';
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
|
||||
// Read-only + ghosted prompt textarea: classic edits inputEl; Nodes 2.0 renders its own textarea from widget options.
|
||||
export function setPromptTextLocked(widget, locked) {
|
||||
if (!widget) return;
|
||||
locked = !!locked;
|
||||
if (widget.inputEl) {
|
||||
widget.inputEl.readOnly = locked;
|
||||
if (locked) widget.inputEl.style.pointerEvents = "auto";
|
||||
widget.inputEl.style.opacity = locked ? "0.5" : "";
|
||||
}
|
||||
if (!!widget.options?.read_only === locked) return;
|
||||
installLockStyle();
|
||||
// Reassigning options (not mutating) is what makes the Vue widget store react.
|
||||
widget.options = { ...widget.options, read_only: locked, "data-pm-locked": locked ? "true" : undefined };
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
/**
|
||||
* RecipeModelLoader extension.
|
||||
* Shows color-coded loaded assets (Model/VAE/CLIP) from workflow_data.
|
||||
*/
|
||||
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
const MODEL_CHOICES = ["model_a", "model_b"];
|
||||
const WEIGHT_DTYPE_CHOICES = ["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"];
|
||||
|
||||
function _trimMiddle(text, maxLen) {
|
||||
const s = String(text || "");
|
||||
if (s.length <= maxLen) return s;
|
||||
const left = Math.ceil((maxLen - 3) / 2);
|
||||
const right = Math.floor((maxLen - 3) / 2);
|
||||
return `${s.slice(0, left)}...${s.slice(s.length - right)}`;
|
||||
}
|
||||
|
||||
function _shortName(name) {
|
||||
const raw = String(name || "").trim();
|
||||
if (!raw) return "";
|
||||
const normalized = raw.replace(/\\/g, "/");
|
||||
const base = normalized.split("/").pop() || normalized;
|
||||
return base.replace(/\.(safetensors|ckpt|pt|pth|bin|gguf|sft)$/i, "");
|
||||
}
|
||||
|
||||
function _shortList(names) {
|
||||
const list = Array.isArray(names) ? names : [];
|
||||
return list.map(_shortName).filter(Boolean);
|
||||
}
|
||||
|
||||
const COLORS = {
|
||||
modelCheckpoint: "#4CAF50",
|
||||
modelDiffusion: "#2196F3",
|
||||
modelGguf: "#FF9800",
|
||||
vae: "#FF6B6B",
|
||||
clip: "#C4A300",
|
||||
notFound: "#F44336",
|
||||
muted: "#B0B0B0",
|
||||
missing: "#E57373",
|
||||
};
|
||||
|
||||
function _buildRows(info) {
|
||||
const status = String(info.status || "").toLowerCase();
|
||||
if (!info || status === "idle") {
|
||||
return [
|
||||
{ label: "Model", labelColor: COLORS.modelDiffusion, value: "(awaiting execution)", valueColor: COLORS.muted },
|
||||
{ label: "Clip", labelColor: COLORS.clip, value: "(awaiting execution)", valueColor: COLORS.muted },
|
||||
{ label: "Vae", labelColor: COLORS.vae, value: "(awaiting execution)", valueColor: COLORS.muted },
|
||||
];
|
||||
}
|
||||
|
||||
const modelKind = String(info.model_kind || info.loader_type || "").toLowerCase();
|
||||
const modelColor = modelKind === "checkpoint"
|
||||
? COLORS.modelCheckpoint
|
||||
: (modelKind === "gguf" ? COLORS.modelGguf : COLORS.modelDiffusion);
|
||||
|
||||
const rows = [];
|
||||
const modelShort = _shortName(info.model_name || "");
|
||||
rows.push({
|
||||
label: "Model",
|
||||
labelColor: modelColor,
|
||||
value: modelShort || "(none)",
|
||||
valueColor: modelShort ? "#CCCCCC" : COLORS.missing,
|
||||
});
|
||||
|
||||
const loaderType = String(info.loader_type || "").toLowerCase();
|
||||
const vaeShort = _shortName(info.vae_name || "");
|
||||
const clipShort = _shortList(info.clip_names);
|
||||
|
||||
if (loaderType === "checkpoint") {
|
||||
// Keep all tags visible; show source explicitly for checkpoint-provided assets.
|
||||
const usingInternalVae = !!info.uses_checkpoint_vae;
|
||||
const usingInternalClip = !!info.uses_checkpoint_clip;
|
||||
rows.push({
|
||||
label: "Clip",
|
||||
labelColor: COLORS.clip,
|
||||
value: usingInternalClip ? "From Checkpoint" : (clipShort.length > 0 ? clipShort.join(", ") : "(none provided)"),
|
||||
valueColor: usingInternalClip ? COLORS.muted : (clipShort.length > 0 ? "#CCCCCC" : COLORS.missing),
|
||||
});
|
||||
rows.push({
|
||||
label: "Vae",
|
||||
labelColor: COLORS.vae,
|
||||
value: usingInternalVae ? "From Checkpoint" : (vaeShort || "(none provided)"),
|
||||
valueColor: usingInternalVae ? COLORS.muted : (vaeShort ? "#CCCCCC" : COLORS.missing),
|
||||
});
|
||||
} else {
|
||||
// Diffusion/UNet: always show Clip + Vae lines.
|
||||
rows.push({
|
||||
label: "Clip",
|
||||
labelColor: COLORS.clip,
|
||||
value: clipShort.length > 0 ? clipShort.join(", ") : "(none provided)",
|
||||
valueColor: clipShort.length > 0 ? "#CCCCCC" : COLORS.missing,
|
||||
});
|
||||
rows.push({
|
||||
label: "Vae",
|
||||
labelColor: COLORS.vae,
|
||||
value: vaeShort || "(none provided)",
|
||||
valueColor: vaeShort ? "#CCCCCC" : COLORS.missing,
|
||||
});
|
||||
}
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
function _drawPillRow(ctx, row, y, widgetWidth) {
|
||||
const left = 8;
|
||||
const badgeText = String(row.label || "");
|
||||
const value = String(row.value || "");
|
||||
const badgeW = 68;
|
||||
const valueX = left + badgeW + 10;
|
||||
const valueMax = Math.max(16, Math.floor((widgetWidth - valueX - 8) / 6));
|
||||
const displayValue = _trimMiddle(value, valueMax);
|
||||
|
||||
ctx.font = "bold 11px Arial";
|
||||
const badgeH = 16;
|
||||
const badgeY = y - Math.floor(badgeH / 2);
|
||||
|
||||
ctx.fillStyle = row.labelColor || COLORS.muted;
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(left, badgeY, badgeW, badgeH, 8);
|
||||
ctx.fill();
|
||||
|
||||
ctx.fillStyle = "#FFFFFF";
|
||||
ctx.textAlign = "left";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(badgeText, left + 8, y + 0.5);
|
||||
|
||||
ctx.font = "12px Arial";
|
||||
ctx.fillStyle = row.valueColor || "#CCCCCC";
|
||||
ctx.fillText(displayValue, valueX, y + 0.5);
|
||||
}
|
||||
|
||||
function _getWidgetValue(node, name, fallback = "") {
|
||||
const w = node?.widgets?.find((x) => x.name === name);
|
||||
if (!w || w.value == null) return fallback;
|
||||
return String(w.value);
|
||||
}
|
||||
|
||||
function _widgetByNames(node, names) {
|
||||
const arr = Array.isArray(names) ? names : [names];
|
||||
return node?.widgets?.find((w) => arr.includes(w.name));
|
||||
}
|
||||
|
||||
function _sanitizeChoice(value, allowed, fallback) {
|
||||
const v = String(value ?? "");
|
||||
return allowed.includes(v) ? v : fallback;
|
||||
}
|
||||
|
||||
function _selectedModelSlot(node) {
|
||||
return _sanitizeChoice(
|
||||
_getWidgetValue(node, "model", "model_a"),
|
||||
MODEL_CHOICES,
|
||||
"model_a"
|
||||
);
|
||||
}
|
||||
|
||||
function _readWidgetState(node) {
|
||||
const modelWidget = _widgetByNames(node, ["model"]);
|
||||
const dtypeWidget = _widgetByNames(node, ["weight_dtype"]);
|
||||
return {
|
||||
model: _sanitizeChoice(modelWidget?.value, MODEL_CHOICES, "model_a"),
|
||||
weight_dtype: _sanitizeChoice(dtypeWidget?.value, WEIGHT_DTYPE_CHOICES, "default"),
|
||||
};
|
||||
}
|
||||
|
||||
function _applyWidgetState(node, state, { persist = true } = {}) {
|
||||
const modelWidget = _widgetByNames(node, ["model"]);
|
||||
const dtypeWidget = _widgetByNames(node, ["weight_dtype"]);
|
||||
const modelVal = _sanitizeChoice(state?.model, MODEL_CHOICES, "model_a");
|
||||
const dtypeVal = _sanitizeChoice(state?.weight_dtype, WEIGHT_DTYPE_CHOICES, "default");
|
||||
|
||||
if (modelWidget) modelWidget.value = modelVal;
|
||||
if (dtypeWidget) dtypeWidget.value = dtypeVal;
|
||||
|
||||
if (persist) {
|
||||
node.properties = node.properties || {};
|
||||
node.properties.wfml_model = modelVal;
|
||||
node.properties.wfml_weight_dtype = dtypeVal;
|
||||
}
|
||||
}
|
||||
|
||||
function _restoreOrNormalizeWidgetState(node) {
|
||||
node.properties = node.properties || {};
|
||||
const live = _readWidgetState(node);
|
||||
|
||||
const savedModel = _sanitizeChoice(node.properties.wfml_model, MODEL_CHOICES, "");
|
||||
const savedDtype = _sanitizeChoice(node.properties.wfml_weight_dtype, WEIGHT_DTYPE_CHOICES, "");
|
||||
|
||||
_applyWidgetState(node, {
|
||||
model: savedModel || live.model || "model_a",
|
||||
weight_dtype: savedDtype || live.weight_dtype || "default",
|
||||
}, { persist: true });
|
||||
}
|
||||
|
||||
function _isRerouteNode(n) {
|
||||
const t = String(n?.type || "").toLowerCase();
|
||||
const c = String(n?.comfyClass || "").toLowerCase();
|
||||
return t.includes("reroute") || c.includes("reroute");
|
||||
}
|
||||
|
||||
function _resolveWorkflowUpstreamLink(node) {
|
||||
const wfInputIdx = (node.inputs || []).findIndex((i) => i?.name === "manager_data");
|
||||
if (wfInputIdx < 0) return null;
|
||||
let linkId = node.inputs[wfInputIdx]?.link;
|
||||
if (linkId == null) return null;
|
||||
|
||||
const graph = node.graph;
|
||||
const seen = new Set();
|
||||
for (let hop = 0; hop < 24; hop++) {
|
||||
if (linkId == null || seen.has(linkId)) break;
|
||||
seen.add(linkId);
|
||||
|
||||
const li = graph?.links?.[linkId];
|
||||
if (!li) break;
|
||||
const src = graph?.getNodeById?.(li.origin_id);
|
||||
if (!src) break;
|
||||
if (!_isRerouteNode(src)) {
|
||||
return { sourceNode: src, sourceSlot: li.origin_slot };
|
||||
}
|
||||
const in0 = src.inputs?.[0];
|
||||
linkId = in0?.link ?? null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function _tryParseWorkflowData(value) {
|
||||
if (!value) return null;
|
||||
if (typeof value === "object") return value;
|
||||
if (typeof value === "string") {
|
||||
try {
|
||||
const p = JSON.parse(value);
|
||||
if (p && typeof p === "object") return p;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function _clipListFromWf(wf) {
|
||||
const c = wf?.clip;
|
||||
if (Array.isArray(c)) return c.filter(Boolean);
|
||||
if (typeof c === "string" && c) return [c];
|
||||
if (c && Array.isArray(c.names)) return c.names.filter(Boolean);
|
||||
return [];
|
||||
}
|
||||
|
||||
function _vaeFromWf(wf) {
|
||||
const v = wf?.vae;
|
||||
if (typeof v === "string") return v;
|
||||
if (v && typeof v === "object" && typeof v.name === "string") return v.name;
|
||||
return "";
|
||||
}
|
||||
|
||||
function _inferInfoFromWorkflowData(node, wf) {
|
||||
const modelKey = _selectedModelSlot(node);
|
||||
const modelName = typeof wf?.[modelKey] === "string" ? wf[modelKey] : "";
|
||||
if (!modelName) return null;
|
||||
|
||||
const loaderType = String(wf?.loader_type || "").toLowerCase();
|
||||
const selectedLower = modelName.toLowerCase();
|
||||
const modelKind = loaderType === "checkpoint"
|
||||
? "checkpoint"
|
||||
: (selectedLower.endsWith(".gguf") ? "gguf" : "diffusion");
|
||||
|
||||
const vaeName = _vaeFromWf(wf);
|
||||
const clipNames = _clipListFromWf(wf);
|
||||
return {
|
||||
model: modelKey,
|
||||
model_name: _shortName(modelName),
|
||||
loader_type: loaderType,
|
||||
model_kind: modelKind,
|
||||
vae_name: vaeName,
|
||||
clip_names: clipNames,
|
||||
status: "ok",
|
||||
error_message: "",
|
||||
missing_name: "",
|
||||
uses_checkpoint_vae: (loaderType === "checkpoint" && !vaeName),
|
||||
uses_checkpoint_clip: (loaderType === "checkpoint" && clipNames.length === 0),
|
||||
};
|
||||
}
|
||||
|
||||
function _refreshInfoFromUpstream(node) {
|
||||
const resolved = _resolveWorkflowUpstreamLink(node);
|
||||
if (!resolved) return false;
|
||||
const { sourceNode, sourceSlot } = resolved;
|
||||
|
||||
const out = sourceNode?.outputs?.[sourceSlot];
|
||||
const wfFromOutput = _tryParseWorkflowData(out?._data) || _tryParseWorkflowData(out?.value);
|
||||
const wfFromBuilderCache = _tryParseWorkflowData(sourceNode?.properties?.we_extracted_cache);
|
||||
const wf = wfFromOutput || wfFromBuilderCache;
|
||||
if (!wf) return false;
|
||||
|
||||
const inferred = _inferInfoFromWorkflowData(node, wf);
|
||||
if (!inferred) return false;
|
||||
node._applyRecipeModelLoaderInfo(inferred);
|
||||
return true;
|
||||
}
|
||||
|
||||
function _defaultInfoFromWidgets(node) {
|
||||
const selected = _selectedModelSlot(node);
|
||||
return {
|
||||
model: selected,
|
||||
model_name: "",
|
||||
loader_type: "",
|
||||
model_kind: "",
|
||||
vae_name: "",
|
||||
clip_names: [],
|
||||
status: "idle",
|
||||
error_message: "",
|
||||
missing_name: "",
|
||||
uses_checkpoint_vae: false,
|
||||
uses_checkpoint_clip: false,
|
||||
};
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "PromptManager.RecipeModelLoader",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "RecipeModelLoader") return;
|
||||
|
||||
const origOnExecuted = nodeType.prototype.onExecuted;
|
||||
nodeType.prototype.onExecuted = function (message) {
|
||||
origOnExecuted?.apply(this, arguments);
|
||||
const info = message?.workflow_model_loader_info?.[0];
|
||||
if (!info) return;
|
||||
this._applyRecipeModelLoaderInfo(info);
|
||||
};
|
||||
|
||||
nodeType.prototype._applyRecipeModelLoaderInfo = function (info) {
|
||||
const selected = _sanitizeChoice(info.model, MODEL_CHOICES, "model_a");
|
||||
this._recipeModelLoaderInfo = {
|
||||
model: selected,
|
||||
model_name: info.model_name || "",
|
||||
loader_type: info.loader_type || "",
|
||||
model_kind: info.model_kind || "",
|
||||
vae_name: info.vae_name || "",
|
||||
clip_names: Array.isArray(info.clip_names) ? info.clip_names : [],
|
||||
status: info.status || "ok",
|
||||
error_message: info.error_message || "",
|
||||
missing_name: info.missing_name || "",
|
||||
uses_checkpoint_vae: !!info.uses_checkpoint_vae,
|
||||
uses_checkpoint_clip: !!info.uses_checkpoint_clip,
|
||||
};
|
||||
this._ensureRecipeModelInfoWidget();
|
||||
this.setDirtyCanvas(true, true);
|
||||
};
|
||||
|
||||
const origOnNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const r = origOnNodeCreated?.apply(this, arguments);
|
||||
_restoreOrNormalizeWidgetState(this);
|
||||
if (!this._recipeModelLoaderInfo) {
|
||||
this._recipeModelLoaderInfo = _defaultInfoFromWidgets(this);
|
||||
}
|
||||
this._ensureRecipeModelInfoWidget();
|
||||
_refreshInfoFromUpstream(this);
|
||||
this.setDirtyCanvas(true, true);
|
||||
return r;
|
||||
};
|
||||
|
||||
const origOnConnectionsChange = nodeType.prototype.onConnectionsChange;
|
||||
nodeType.prototype.onConnectionsChange = function () {
|
||||
const r = origOnConnectionsChange?.apply(this, arguments);
|
||||
_refreshInfoFromUpstream(this);
|
||||
this.setDirtyCanvas(true, true);
|
||||
return r;
|
||||
};
|
||||
|
||||
const origOnWidgetChanged = nodeType.prototype.onWidgetChanged;
|
||||
nodeType.prototype.onWidgetChanged = function (name, value, oldValue, w) {
|
||||
const r = origOnWidgetChanged?.apply(this, arguments);
|
||||
if (name === "model" || name === "weight_dtype") {
|
||||
_restoreOrNormalizeWidgetState(this);
|
||||
_refreshInfoFromUpstream(this);
|
||||
this.setDirtyCanvas(true, true);
|
||||
}
|
||||
return r;
|
||||
};
|
||||
|
||||
const origOnSerialize = nodeType.prototype.onSerialize;
|
||||
nodeType.prototype.onSerialize = function (o) {
|
||||
origOnSerialize?.apply(this, arguments);
|
||||
const ws = _readWidgetState(this);
|
||||
this.properties = this.properties || {};
|
||||
this.properties.wfml_model = ws.model;
|
||||
this.properties.wfml_weight_dtype = ws.weight_dtype;
|
||||
if (this._recipeModelLoaderInfo) {
|
||||
o._recipeModelLoaderInfo = this._recipeModelLoaderInfo;
|
||||
o._workflowModelLoaderInfo = this._recipeModelLoaderInfo;
|
||||
}
|
||||
if (o) {
|
||||
o.properties = o.properties || {};
|
||||
o.properties.wfml_model = ws.model;
|
||||
o.properties.wfml_weight_dtype = ws.weight_dtype;
|
||||
}
|
||||
};
|
||||
|
||||
const origOnConfigure = nodeType.prototype.onConfigure;
|
||||
nodeType.prototype.onConfigure = function (info) {
|
||||
origOnConfigure?.apply(this, arguments);
|
||||
_restoreOrNormalizeWidgetState(this);
|
||||
const state = info?._recipeModelLoaderInfo || info?._workflowModelLoaderInfo;
|
||||
if (state) {
|
||||
requestAnimationFrame(() => {
|
||||
this._applyRecipeModelLoaderInfo(state);
|
||||
_refreshInfoFromUpstream(this);
|
||||
});
|
||||
} else {
|
||||
requestAnimationFrame(() => {
|
||||
this._recipeModelLoaderInfo = _defaultInfoFromWidgets(this);
|
||||
this._ensureRecipeModelInfoWidget();
|
||||
_refreshInfoFromUpstream(this);
|
||||
this.setDirtyCanvas(true, true);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
nodeType.prototype._ensureRecipeModelInfoWidget = function () {
|
||||
let widget = this.widgets?.find(w => w.name === "_recipe_model_loader_info");
|
||||
if (!widget) {
|
||||
widget = {
|
||||
name: "_recipe_model_loader_info",
|
||||
type: "custom",
|
||||
y: 0,
|
||||
computeSize: () => {
|
||||
const rows = _buildRows(this._recipeModelLoaderInfo || {});
|
||||
const h = Math.max(26, (rows.length * 22) + 6);
|
||||
return [0, h];
|
||||
},
|
||||
draw: function (ctx, node, widgetWidth, y) {
|
||||
const info = node._recipeModelLoaderInfo;
|
||||
if (!info) return;
|
||||
|
||||
const rows = _buildRows(info);
|
||||
|
||||
ctx.save();
|
||||
ctx.textAlign = "left";
|
||||
ctx.textBaseline = "middle";
|
||||
for (let i = 0; i < rows.length; i++) {
|
||||
const rowY = y + 12 + (i * 22);
|
||||
const row = rows[i];
|
||||
_drawPillRow(ctx, row, rowY, widgetWidth);
|
||||
}
|
||||
ctx.restore();
|
||||
},
|
||||
};
|
||||
if (!this.widgets) this.widgets = [];
|
||||
this.widgets.push(widget);
|
||||
}
|
||||
this.computeSize();
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
/**
|
||||
* Recipe Model Picker
|
||||
*
|
||||
* Keeps Type/Model/VAE/CLIP widgets in sync with Builder family filtering
|
||||
* and emits a single model_data payload for Recipe Relay.
|
||||
*/
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
const DEFAULT_ASSET = "(Default)";
|
||||
const DEFAULT_FAMILY = "sdxl";
|
||||
|
||||
function getWidget(node, name) {
|
||||
return node?.widgets?.find((w) => w.name === name) || null;
|
||||
}
|
||||
|
||||
function setWidgetOptions(widget, values, fallback = "") {
|
||||
if (!widget?.options) return;
|
||||
const list = Array.isArray(values) && values.length > 0 ? values : [fallback];
|
||||
widget.options.values = list;
|
||||
}
|
||||
|
||||
function ensureWidgetValue(widget, preferred, fallback = "") {
|
||||
if (!widget?.options) return;
|
||||
const values = Array.isArray(widget.options.values) ? widget.options.values : [];
|
||||
const candidate = (preferred != null && values.includes(preferred))
|
||||
? preferred
|
||||
: (values.includes(widget.value) ? widget.value : null);
|
||||
widget.value = candidate != null ? candidate : (values[0] ?? fallback);
|
||||
}
|
||||
|
||||
async function fetchJson(url) {
|
||||
const response = await fetch(url);
|
||||
return response.json();
|
||||
}
|
||||
|
||||
function familyKeyFromTypeValue(typeValue, familiesMap) {
|
||||
const raw = String(typeValue || "").trim();
|
||||
if (!raw) return DEFAULT_FAMILY;
|
||||
|
||||
if (familiesMap[raw]) return raw;
|
||||
|
||||
for (const [key, label] of Object.entries(familiesMap)) {
|
||||
if (label === raw) return key;
|
||||
}
|
||||
|
||||
return DEFAULT_FAMILY;
|
||||
}
|
||||
|
||||
async function reloadPickerLists(node) {
|
||||
const typeWidget = getWidget(node, "type");
|
||||
const modelWidget = getWidget(node, "model");
|
||||
const vaeWidget = getWidget(node, "vae");
|
||||
const clipWidget = getWidget(node, "clip");
|
||||
if (!typeWidget || !modelWidget || !vaeWidget || !clipWidget) return;
|
||||
|
||||
let families = node._recipePickerFamilies;
|
||||
if (!families) {
|
||||
try {
|
||||
const data = await fetchJson("/workflow-extractor/list-families");
|
||||
families = data?.families || {};
|
||||
} catch {
|
||||
families = {};
|
||||
}
|
||||
node._recipePickerFamilies = families;
|
||||
}
|
||||
|
||||
const familyKey = familyKeyFromTypeValue(typeWidget.value, families);
|
||||
|
||||
const [modelsData, vaesData, clipsData] = await Promise.all([
|
||||
fetchJson(`/workflow-extractor/list-models?family=${encodeURIComponent(familyKey)}`),
|
||||
fetchJson(`/workflow-extractor/list-vaes?family=${encodeURIComponent(familyKey)}`),
|
||||
fetchJson(`/workflow-extractor/list-clips?family=${encodeURIComponent(familyKey)}`),
|
||||
]).catch(() => [{ models: [] }, { vaes: [] }, { clips: [] }]);
|
||||
|
||||
const models = Array.isArray(modelsData?.models) ? modelsData.models : [];
|
||||
const vaes = Array.isArray(vaesData?.vaes) ? vaesData.vaes : [];
|
||||
const clips = Array.isArray(clipsData?.clips) ? clipsData.clips : [];
|
||||
|
||||
const prevModel = modelWidget.value;
|
||||
const prevVae = vaeWidget.value;
|
||||
const prevClip = clipWidget.value;
|
||||
|
||||
setWidgetOptions(modelWidget, models, "");
|
||||
setWidgetOptions(vaeWidget, [DEFAULT_ASSET, ...vaes], DEFAULT_ASSET);
|
||||
setWidgetOptions(clipWidget, [DEFAULT_ASSET, ...clips], DEFAULT_ASSET);
|
||||
|
||||
ensureWidgetValue(modelWidget, prevModel, "");
|
||||
ensureWidgetValue(vaeWidget, prevVae, DEFAULT_ASSET);
|
||||
ensureWidgetValue(clipWidget, prevClip, DEFAULT_ASSET);
|
||||
|
||||
if (typeof modelWidget.callback === "function") modelWidget.callback(modelWidget.value);
|
||||
if (typeof vaeWidget.callback === "function") vaeWidget.callback(vaeWidget.value);
|
||||
if (typeof clipWidget.callback === "function") clipWidget.callback(clipWidget.value);
|
||||
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "prompt-manager.recipe-model-picker",
|
||||
async nodeCreated(node) {
|
||||
if (node.comfyClass !== "RecipeModelPicker") return;
|
||||
|
||||
const typeWidget = getWidget(node, "type");
|
||||
if (!typeWidget) return;
|
||||
|
||||
const originalTypeCallback = typeWidget.callback;
|
||||
typeWidget.callback = async function wrappedTypeCallback(value) {
|
||||
if (typeof originalTypeCallback === "function") {
|
||||
originalTypeCallback.call(this, value);
|
||||
}
|
||||
await reloadPickerLists(node);
|
||||
};
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
reloadPickerLists(node).catch(() => {
|
||||
// Keep node usable even if API endpoints are temporarily unavailable.
|
||||
});
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
/**
|
||||
* Recipe Relay — set a compact default width for newly created nodes.
|
||||
*/
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
const RELAY_DEFAULT_WIDTH = 220;
|
||||
|
||||
app.registerExtension({
|
||||
name: "prompt-manager.recipe-relay",
|
||||
async nodeCreated(node) {
|
||||
if (node.comfyClass !== "RecipeRelay") return;
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
node.setSize([RELAY_DEFAULT_WIDTH, node.size[1]]);
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* Recipe Renderer — Set initial node size to match Recipe Builder width.
|
||||
*/
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
app.registerExtension({
|
||||
name: "prompt-manager.recipe-renderer",
|
||||
async nodeCreated(node) {
|
||||
if (node.comfyClass !== "RecipeRenderer") return;
|
||||
requestAnimationFrame(() => {
|
||||
node.setSize([320, node.size[1]]);
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,43 @@
|
||||
// Shared UI palette used by Prompt Manager modals.
|
||||
// Keep this aligned with Workflow Builder's neutral + blue accent styling.
|
||||
export const PM_UI_PALETTE = {
|
||||
// Backdrop behind modal dialogs
|
||||
overlay: "hsl(0 0% 0% / 0.8)",
|
||||
// Main modal surface
|
||||
panel: "hsl(216 11% 15%)",
|
||||
// Outer border of modal containers
|
||||
panelBorder: "hsl(216 20% 65% / 0.24)",
|
||||
// Dividers between modal sections (header/body/footer)
|
||||
sectionBorder: "hsl(216 20% 65% / 0.20)",
|
||||
|
||||
// Text input/select control surface
|
||||
inputBg: "hsl(220 15% 10%)",
|
||||
// Input/select/button neutral stroke
|
||||
inputBorder: "hsl(218 10% 41%)",
|
||||
// Neutral button/chip background
|
||||
buttonBg: "hsl(219 16% 18%)",
|
||||
|
||||
// Primary foreground text
|
||||
textPrimary: "hsl(0 0% 87%)",
|
||||
// Titles and important labels
|
||||
textHeading: "hsl(220 13% 85%)",
|
||||
// Secondary text
|
||||
textMuted: "hsl(0 0% 67%)",
|
||||
// Hints and helper text
|
||||
textHint: "hsl(216 15% 65%)",
|
||||
|
||||
// Card/tile background (thumbnails, prompt cards)
|
||||
cardBg: "hsl(219 16% 18%)",
|
||||
// Card default border
|
||||
cardBorder: "hsl(217 12% 22%)",
|
||||
|
||||
// Exact Builder accent family (from workflow_builder.js)
|
||||
// Primary blue accent (focus/selected)
|
||||
accent: "hsl(208 73% 57% / 0.9)",
|
||||
// Slightly dimmed accent (hover/secondary accent)
|
||||
accentDim: "hsl(208 73% 57% / 0.7)",
|
||||
// Soft accent fill for selected backgrounds
|
||||
accentSoft: "hsl(208 73% 57% / 0.55)",
|
||||
// Accent border used on selected elements
|
||||
accentBorder: "hsl(208 73% 57% / 0.95)",
|
||||
};
|
||||
@@ -1,129 +0,0 @@
|
||||
"""
|
||||
Utility functions for managing llama.cpp models
|
||||
"""
|
||||
import os
|
||||
import glob
|
||||
|
||||
from huggingface_hub import HfApi
|
||||
from tqdm.auto import tqdm
|
||||
import requests
|
||||
|
||||
# Predefined models - use real filenames as keys
|
||||
QWEN_MODELS = {
|
||||
"Qwen3-1.7B-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-1.7B-GGUF"
|
||||
},
|
||||
"Qwen3-4B-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-4B-GGUF"
|
||||
},
|
||||
"Qwen3-8B-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-8B-GGUF"
|
||||
}
|
||||
}
|
||||
|
||||
def get_models_directory():
|
||||
"""Get the path to the models directory (ComfyUI/models/gguf)"""
|
||||
# Get the custom_nodes directory (parent of this extension)
|
||||
custom_nodes_dir = os.path.dirname(os.path.dirname(__file__))
|
||||
# Go up to ComfyUI root
|
||||
comfyui_root = os.path.dirname(custom_nodes_dir)
|
||||
# Path to models/gguf
|
||||
models_dir = os.path.join(comfyui_root, "models", "gguf")
|
||||
|
||||
# Create directory if it doesn't exist
|
||||
os.makedirs(models_dir, exist_ok=True)
|
||||
|
||||
return models_dir
|
||||
|
||||
def get_local_models():
|
||||
"""Get list of local .gguf model files"""
|
||||
models_dir = get_models_directory()
|
||||
|
||||
gguf_files = glob.glob(os.path.join(models_dir, "*.gguf"))
|
||||
# Return just the filenames, not full paths
|
||||
return [os.path.basename(f) for f in sorted(gguf_files)]
|
||||
|
||||
def get_huggingface_models():
|
||||
"""Get list of predefined Qwen models available for download"""
|
||||
return list(QWEN_MODELS.keys())
|
||||
|
||||
def get_all_models():
|
||||
"""Get combined list of local and HuggingFace models, excluding already downloaded ones"""
|
||||
local_models = get_local_models()
|
||||
models_dir = get_models_directory()
|
||||
|
||||
# List all known filenames, local ones first
|
||||
all_models = []
|
||||
# Add local models first
|
||||
if local_models:
|
||||
all_models.extend(local_models)
|
||||
# Add remote models (not present locally)
|
||||
for filename in QWEN_MODELS.keys():
|
||||
if filename not in all_models:
|
||||
all_models.append(filename)
|
||||
return all_models
|
||||
|
||||
def is_model_local(model_name):
|
||||
"""Check if a model exists locally"""
|
||||
if model_name == "--- Download from HuggingFace ---":
|
||||
return False
|
||||
|
||||
models_dir = get_models_directory()
|
||||
model_path = os.path.join(models_dir, model_name)
|
||||
return os.path.exists(model_path)
|
||||
|
||||
def get_model_path(model_name):
|
||||
"""Get the full path to a model file"""
|
||||
models_dir = get_models_directory()
|
||||
return os.path.join(models_dir, model_name)
|
||||
|
||||
|
||||
def download_model(model_name):
|
||||
"""
|
||||
Download a model from HuggingFace with automatic progress display
|
||||
|
||||
Args:
|
||||
model_name: Filename of the model (e.g., "Qwen3-4B-Q8_0.gguf")
|
||||
|
||||
Returns:
|
||||
Path to downloaded model or None on error
|
||||
"""
|
||||
|
||||
if model_name not in QWEN_MODELS:
|
||||
print(f"[Model Manager] Error: Unknown model: {model_name}")
|
||||
return None
|
||||
|
||||
model_info = QWEN_MODELS[model_name]
|
||||
repo_id = model_info["repo"]
|
||||
filename = model_name
|
||||
models_dir = get_models_directory()
|
||||
local_path = os.path.join(models_dir, filename)
|
||||
|
||||
# Check if already downloaded
|
||||
if os.path.exists(local_path):
|
||||
print(f"[Model Manager] Model already exists: {filename}")
|
||||
return local_path
|
||||
|
||||
try:
|
||||
print(f"[Model Manager] Downloading {filename} from {repo_id}...")
|
||||
api = HfApi()
|
||||
repo_info = api.repo_info(repo_id=repo_id, files_metadata=True)
|
||||
file_info = next((f for f in repo_info.siblings if f.rfilename == filename), None)
|
||||
if not file_info or file_info.size is None:
|
||||
print(f"[Model Manager] Could not find file size for {filename} in {repo_id}")
|
||||
return None
|
||||
total_size = file_info.size
|
||||
download_url = f"https://huggingface.co/{repo_id}/resolve/main/{filename}"
|
||||
pbar = tqdm(total=total_size, unit="B", unit_scale=True, desc="Downloading")
|
||||
with requests.get(download_url, stream=True) as r, open(local_path, "wb") as f:
|
||||
r.raise_for_status()
|
||||
for chunk in r.iter_content(chunk_size=65536):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
pbar.update(len(chunk))
|
||||
pbar.close()
|
||||
print(f"[Model Manager] Successfully downloaded {filename}")
|
||||
return local_path
|
||||
except Exception as e:
|
||||
print(f"[Model Manager] Error downloading model: {e}")
|
||||
return None
|
||||
@@ -0,0 +1,341 @@
|
||||
"""
|
||||
Library Manager - save and reload manager_data from Prompt Manager, Recipe nodes, Prompt Composer and Prompt Layout Builder.
|
||||
|
||||
Compared to the base Prompt Manager node:
|
||||
- accepts an IMAGE input to provide/save a thumbnail alongside the data
|
||||
- tags saved/forwarded workflow metadata as LibraryManager
|
||||
"""
|
||||
|
||||
import json
|
||||
|
||||
import server
|
||||
|
||||
from ..py.thumbnail_utils import image_to_base64_thumbnail
|
||||
from ..py.workflow_data_utils import ensure_v2_recipe_data, get_v2_model_block, to_json_safe_workflow_data, build_v2_recipe_data_from_prompt
|
||||
from .prompt_manager_adv import PromptManagerAdvanced
|
||||
|
||||
|
||||
class LibraryManager(PromptManagerAdvanced):
|
||||
"""Workflow-focused manager for manager_data payloads with explicit thumbnail input."""
|
||||
|
||||
SOURCE_NAME = "LibraryManager"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
prompts_data = cls.load_prompts()
|
||||
categories = list(prompts_data.keys()) if prompts_data else ["Default"]
|
||||
|
||||
all_prompts = set()
|
||||
for category_prompts in prompts_data.values():
|
||||
all_prompts.update(k for k in category_prompts.keys() if k != "__meta__")
|
||||
|
||||
all_prompts.add("")
|
||||
all_prompts_list = sorted(list(all_prompts))
|
||||
|
||||
first_category = categories[0] if categories else "Default"
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"category": (categories, {"default": first_category}),
|
||||
"name": (all_prompts_list, {"default": ""}),
|
||||
"text": ("STRING", {
|
||||
"multiline": True,
|
||||
"default": "",
|
||||
"placeholder": "Enter prompt text",
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "Edit prompt text directly",
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"manager_data": ("MANAGER_DATA", {"forceInput": True, "tooltip": "manager_data from Prompt Manager, Recipe nodes, Prompt Composer or Prompt Layout Builder to save/forward"}),
|
||||
"image": ("IMAGE", {"tooltip": "Optional image input used as the saved thumbnail when present."}),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID",
|
||||
"loras_a_toggle": "STRING",
|
||||
"loras_b_toggle": "STRING",
|
||||
"saved_workflow_data": "STRING",
|
||||
},
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Library Manager: save and reload manager_data from Prompt Manager, Recipe nodes, Prompt Composer and Prompt Layout Builder, with optional thumbnail image input."
|
||||
RETURN_TYPES = ("MANAGER_DATA",)
|
||||
RETURN_NAMES = ("manager_data",)
|
||||
FUNCTION = "get_workflow"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, category, name, text="", **kwargs):
|
||||
data = kwargs.get("manager_data", None)
|
||||
if data is None:
|
||||
data = kwargs.get("data", None)
|
||||
image = kwargs.get("image", None)
|
||||
loras_a_toggle = kwargs.get("loras_a_toggle", "")
|
||||
loras_b_toggle = kwargs.get("loras_b_toggle", "")
|
||||
saved_workflow_data = kwargs.get("saved_workflow_data", "")
|
||||
thumbnail_sig = None
|
||||
try:
|
||||
if image is not None:
|
||||
thumbnail_sig = tuple(getattr(image, "shape", []) or [])
|
||||
except Exception:
|
||||
thumbnail_sig = "image"
|
||||
return (
|
||||
category,
|
||||
name,
|
||||
text,
|
||||
str(data) if data else None,
|
||||
thumbnail_sig,
|
||||
loras_a_toggle or "",
|
||||
loras_b_toggle or "",
|
||||
saved_workflow_data or "",
|
||||
)
|
||||
|
||||
def get_workflow(
|
||||
self,
|
||||
category,
|
||||
name,
|
||||
text="",
|
||||
manager_data=None,
|
||||
image=None,
|
||||
unique_id=None,
|
||||
loras_a_toggle=None,
|
||||
loras_b_toggle=None,
|
||||
saved_workflow_data=None,
|
||||
**kwargs,
|
||||
):
|
||||
prompts_data = self.load_prompts()
|
||||
source_name = self.SOURCE_NAME
|
||||
recipe_data = manager_data
|
||||
if recipe_data is None:
|
||||
recipe_data = kwargs.get("data")
|
||||
if recipe_data is None:
|
||||
recipe_data = kwargs.get("recipe_data")
|
||||
|
||||
def _as_workflow_dict(raw):
|
||||
if isinstance(raw, dict):
|
||||
return raw
|
||||
if isinstance(raw, str) and raw.strip():
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
return parsed if isinstance(parsed, dict) else None
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return None
|
||||
return None
|
||||
|
||||
prompt_entry = prompts_data.get(category, {}).get(name, {}) if isinstance(prompts_data, dict) else {}
|
||||
if not isinstance(prompt_entry, dict) or not prompt_entry:
|
||||
if isinstance(prompts_data, dict) and isinstance(name, str) and name:
|
||||
for cat_prompts in prompts_data.values():
|
||||
if isinstance(cat_prompts, dict) and isinstance(cat_prompts.get(name), dict):
|
||||
prompt_entry = cat_prompts.get(name)
|
||||
break
|
||||
|
||||
stored_prompt_wf = _as_workflow_dict(prompt_entry.get("workflow_data")) if isinstance(prompt_entry, dict) else None
|
||||
live_workflow_data = _as_workflow_dict(recipe_data)
|
||||
hidden_saved_wf = _as_workflow_dict(saved_workflow_data)
|
||||
|
||||
resolved_workflow_data = ensure_v2_recipe_data(live_workflow_data, source=source_name) if isinstance(live_workflow_data, dict) else None
|
||||
if resolved_workflow_data is None:
|
||||
resolved_workflow_data = ensure_v2_recipe_data(hidden_saved_wf, source=source_name) if isinstance(hidden_saved_wf, dict) else None
|
||||
if resolved_workflow_data is None and isinstance(stored_prompt_wf, dict):
|
||||
resolved_workflow_data = ensure_v2_recipe_data(stored_prompt_wf, source=source_name)
|
||||
|
||||
if resolved_workflow_data is None and isinstance(prompt_entry, dict):
|
||||
prompt_text = str(prompt_entry.get("prompt", "") or text or "")
|
||||
negative_text = str(prompt_entry.get("negative_prompt", "") or "")
|
||||
prompt_loras_a = prompt_entry.get("loras_a", []) if isinstance(prompt_entry.get("loras_a"), list) else []
|
||||
prompt_loras_b = prompt_entry.get("loras_b", []) if isinstance(prompt_entry.get("loras_b"), list) else []
|
||||
|
||||
has_prompt_payload = bool(
|
||||
prompt_text.strip() or
|
||||
negative_text.strip() or
|
||||
len(prompt_loras_a) > 0 or
|
||||
len(prompt_loras_b) > 0
|
||||
)
|
||||
|
||||
if has_prompt_payload:
|
||||
resolved_workflow_data = build_v2_recipe_data_from_prompt(
|
||||
prompt_text=prompt_text,
|
||||
negative_prompt=negative_text,
|
||||
loras_a=prompt_loras_a,
|
||||
loras_b=prompt_loras_b,
|
||||
source=source_name,
|
||||
)
|
||||
|
||||
wf = resolved_workflow_data if isinstance(resolved_workflow_data, dict) else {}
|
||||
wf_model_a = get_v2_model_block(wf, "model_a") or {}
|
||||
wf_model_b = get_v2_model_block(wf, "model_b") or {}
|
||||
wf_has_model_b = isinstance(get_v2_model_block(wf, "model_b"), dict)
|
||||
composer_payload = wf.get("prompt_composer") if isinstance(wf.get("prompt_composer"), dict) else {}
|
||||
composer_input_data = composer_payload.get("input_data") if isinstance(composer_payload.get("input_data"), dict) else {}
|
||||
incoming_wf = live_workflow_data if isinstance(live_workflow_data, dict) else None
|
||||
incoming_has_model_b = None
|
||||
if isinstance(incoming_wf, dict):
|
||||
incoming_v2 = ensure_v2_recipe_data(incoming_wf, source=source_name)
|
||||
incoming_models = incoming_v2.get("models", {}) if isinstance(incoming_v2.get("models"), dict) else {}
|
||||
incoming_has_model_b = isinstance(incoming_models.get("model_b"), dict)
|
||||
|
||||
output_text = (wf_model_a.get("positive_prompt", "") or text or "")
|
||||
generated_thumbnail = image_to_base64_thumbnail(wf.get("IMAGE"), log_prefix=source_name) if isinstance(wf, dict) else None
|
||||
incoming_thumbnail = image_to_base64_thumbnail(incoming_wf.get("IMAGE"), log_prefix=source_name) if isinstance(incoming_wf, dict) else None
|
||||
explicit_thumbnail = image_to_base64_thumbnail(image, log_prefix=source_name) if image is not None else None
|
||||
workflow_thumbnail = explicit_thumbnail if isinstance(explicit_thumbnail, str) and explicit_thumbnail else (
|
||||
incoming_thumbnail if isinstance(incoming_thumbnail, str) and incoming_thumbnail else (
|
||||
generated_thumbnail if isinstance(generated_thumbnail, str) and generated_thumbnail else (
|
||||
incoming_wf.get("thumbnail") if isinstance(incoming_wf, dict) and isinstance(incoming_wf.get("thumbnail"), str) else (
|
||||
wf.get("thumbnail") if isinstance(wf.get("thumbnail"), str) else None
|
||||
)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
preset_stack_a = self._build_stack_from_toggle(loras_a_toggle) if loras_a_toggle else []
|
||||
preset_stack_b = self._build_stack_from_toggle(loras_b_toggle) if (wf_has_model_b and loras_b_toggle) else []
|
||||
|
||||
all_preset_loras_a = self._get_all_loras_from_toggle(loras_a_toggle) if loras_a_toggle else []
|
||||
all_preset_loras_b = self._get_all_loras_from_toggle(loras_b_toggle) if (wf_has_model_b and loras_b_toggle) else []
|
||||
|
||||
wf_loras_a = [
|
||||
(lora["name"], lora.get("model_strength", 1.0), lora.get("clip_strength", 1.0))
|
||||
for lora in wf_model_a.get("loras", [])
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
wf_loras_b = []
|
||||
if wf_has_model_b:
|
||||
wf_loras_b = [
|
||||
(lora["name"], lora.get("model_strength", 1.0), lora.get("clip_strength", 1.0))
|
||||
for lora in wf_model_b.get("loras", [])
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
|
||||
composer_input_loras_a = [
|
||||
(
|
||||
lora.get("path") or lora.get("name"),
|
||||
lora.get("model_strength", 1.0),
|
||||
lora.get("clip_strength", 1.0),
|
||||
)
|
||||
for lora in composer_input_data.get("lora_stack", [])
|
||||
if isinstance(lora, dict) and (lora.get("path") or lora.get("name"))
|
||||
]
|
||||
|
||||
merged_stack_a = list(wf_loras_a) if wf_loras_a else (list(preset_stack_a) if preset_stack_a else [])
|
||||
if wf_has_model_b:
|
||||
merged_stack_b = list(wf_loras_b) if wf_loras_b else (list(preset_stack_b) if preset_stack_b else [])
|
||||
else:
|
||||
merged_stack_b = []
|
||||
|
||||
processed_stack_a = self._process_lora_toggle(merged_stack_a, loras_a_toggle)
|
||||
processed_stack_b = self._process_lora_toggle(merged_stack_b, loras_b_toggle)
|
||||
|
||||
loras_a_display = self._format_loras_for_display_with_unavailable(merged_stack_a, all_preset_loras_a)
|
||||
loras_b_display = self._format_loras_for_display_with_unavailable(merged_stack_b, all_preset_loras_b)
|
||||
|
||||
unavailable_loras_a = [lora["name"] for lora in all_preset_loras_a if not lora.get("available", False)]
|
||||
unavailable_loras_b = [lora["name"] for lora in all_preset_loras_b if not lora.get("available", False)]
|
||||
|
||||
if unique_id is not None:
|
||||
server.PromptServer.instance.send_sync("prompt-manager-advanced-update", {
|
||||
"node_id": unique_id,
|
||||
"prompt": output_text,
|
||||
"use_prompt_input": False,
|
||||
"use_workflow_data": True,
|
||||
"prompt_input": "",
|
||||
"workflow_data": to_json_safe_workflow_data(ensure_v2_recipe_data(recipe_data, source=source_name)) if isinstance(recipe_data, dict) else (
|
||||
to_json_safe_workflow_data(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else None
|
||||
),
|
||||
"loras_a": loras_a_display,
|
||||
"loras_b": loras_b_display,
|
||||
"input_loras_a": self._format_loras_for_display(composer_input_loras_a) if composer_input_loras_a else [],
|
||||
"input_loras_b": self._format_loras_for_display(wf_loras_b) if wf_loras_b else [],
|
||||
"unavailable_loras_a": unavailable_loras_a,
|
||||
"unavailable_loras_b": unavailable_loras_b,
|
||||
"trigger_words": [],
|
||||
"connected_thumbnail": workflow_thumbnail,
|
||||
"should_reset": False,
|
||||
"original_strengths_a": {
|
||||
lora_item.get("name", ""): lora_item.get("strength", lora_item.get("model_strength", 1.0))
|
||||
for lora_item in loras_a_display
|
||||
if lora_item.get("name")
|
||||
},
|
||||
"original_strengths_b": {
|
||||
lora_item.get("name", ""): lora_item.get("strength", lora_item.get("model_strength", 1.0))
|
||||
for lora_item in loras_b_display
|
||||
if lora_item.get("name")
|
||||
},
|
||||
})
|
||||
|
||||
out_workflow_data = ensure_v2_recipe_data(
|
||||
dict(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else {},
|
||||
source=source_name,
|
||||
)
|
||||
|
||||
models_out = out_workflow_data.get("models", {})
|
||||
if not isinstance(models_out, dict):
|
||||
models_out = {}
|
||||
out_workflow_data["models"] = models_out
|
||||
|
||||
has_existing_model_b = isinstance(models_out.get("model_b"), dict)
|
||||
model_a_out = models_out.get("model_a") if isinstance(models_out.get("model_a"), dict) else {}
|
||||
model_b_out = models_out.get("model_b") if isinstance(models_out.get("model_b"), dict) else {}
|
||||
|
||||
model_a_out["positive_prompt"] = output_text
|
||||
model_a_out["loras"] = [
|
||||
{
|
||||
"name": lora.get("name", ""),
|
||||
"path": lora.get("path", lora.get("name", "")),
|
||||
"model_strength": lora.get("model_strength", lora.get("strength", 1.0)),
|
||||
"clip_strength": lora.get("clip_strength", lora.get("strength", 1.0)),
|
||||
"active": lora.get("active", True),
|
||||
"available": lora.get("available", True),
|
||||
}
|
||||
for lora in loras_a_display
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
model_b_loras = [
|
||||
{
|
||||
"name": lora.get("name", ""),
|
||||
"path": lora.get("path", lora.get("name", "")),
|
||||
"model_strength": lora.get("model_strength", lora.get("strength", 1.0)),
|
||||
"clip_strength": lora.get("clip_strength", lora.get("strength", 1.0)),
|
||||
"active": lora.get("active", True),
|
||||
"available": lora.get("available", True),
|
||||
}
|
||||
for lora in loras_b_display
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
|
||||
models_out["model_a"] = model_a_out
|
||||
model_a_name = str(model_a_out.get("model", "") or "").strip()
|
||||
model_b_name = str(model_b_out.get("model", "") or "").strip()
|
||||
model_b_pos = str(model_b_out.get("positive_prompt", "") or "").strip()
|
||||
model_b_neg = str(model_b_out.get("negative_prompt", "") or "").strip()
|
||||
model_b_has_runtime = any(
|
||||
model_b_out.get(key) is not None
|
||||
for key in ("MODEL", "CLIP", "VAE", "POSITIVE", "NEGATIVE")
|
||||
)
|
||||
keep_model_b = bool(model_b_loras) or bool(model_b_pos) or bool(model_b_neg) or model_b_has_runtime
|
||||
if model_b_name and model_b_name != model_a_name:
|
||||
keep_model_b = True
|
||||
|
||||
if (has_existing_model_b and model_b_name and model_b_name == model_a_name and
|
||||
not model_b_loras and not model_b_pos and not model_b_neg and not model_b_has_runtime):
|
||||
keep_model_b = False
|
||||
|
||||
if incoming_has_model_b is False:
|
||||
keep_model_b = False
|
||||
|
||||
if keep_model_b:
|
||||
model_b_out["loras"] = model_b_loras
|
||||
models_out["model_b"] = model_b_out
|
||||
else:
|
||||
models_out.pop("model_b", None)
|
||||
|
||||
if workflow_thumbnail:
|
||||
out_workflow_data["thumbnail"] = workflow_thumbnail
|
||||
out_workflow_data["_source"] = source_name
|
||||
|
||||
return (out_workflow_data,)
|
||||
|
||||
def check_lazy_status(self, category, name, text="", **kwargs):
|
||||
return []
|
||||
@@ -0,0 +1,417 @@
|
||||
"""Multi-slot LoRA stacker outputting four independent LORA_STACK outputs (A/B/C/D)."""
|
||||
|
||||
import json
|
||||
import importlib
|
||||
import os
|
||||
import sys
|
||||
|
||||
from ..py.lora_utils import resolve_lora_path
|
||||
try:
|
||||
from ..py.lora_utils import get_lora_relative_path
|
||||
except Exception:
|
||||
def get_lora_relative_path(lora_name):
|
||||
return str(lora_name or ""), False
|
||||
|
||||
|
||||
def _try_get_lm_get_lora_info():
|
||||
"""Return LM's get_lora_info function when available."""
|
||||
# First, try already-loaded modules.
|
||||
for mod_name, mod in list(sys.modules.items()):
|
||||
if mod is None:
|
||||
continue
|
||||
|
||||
mod_dict = getattr(mod, "__dict__", None)
|
||||
if not isinstance(mod_dict, dict):
|
||||
continue
|
||||
|
||||
# Use module __dict__ lookup to avoid invoking module-level __getattr__.
|
||||
fn = mod_dict.get("get_lora_info")
|
||||
if callable(fn):
|
||||
file_path = str(mod_dict.get("__file__") or "").lower()
|
||||
has_absolute_variant = callable(mod_dict.get("get_lora_info_absolute"))
|
||||
if "comfyui-lora-manager" in file_path or has_absolute_variant:
|
||||
return fn
|
||||
|
||||
# If not loaded yet, try common module paths directly.
|
||||
candidate_modules = (
|
||||
"custom_nodes.ComfyUI_Lora_Manager.py.utils.utils",
|
||||
"ComfyUI_Lora_Manager.py.utils.utils",
|
||||
"py.utils.utils",
|
||||
)
|
||||
for module_name in candidate_modules:
|
||||
try:
|
||||
mod = importlib.import_module(module_name)
|
||||
except Exception:
|
||||
continue
|
||||
fn = getattr(mod, "get_lora_info", None)
|
||||
if callable(fn):
|
||||
return fn
|
||||
return None
|
||||
|
||||
|
||||
def _build_lora_stack(loras_json):
|
||||
"""
|
||||
Build a LORA_STACK list from the JSON state persisted by the JS widget.
|
||||
|
||||
Each entry: {"name": str, "strength": float, "clipStrength": float, "active": bool}
|
||||
Returns a list of (lora_path, model_strength, clip_strength) tuples.
|
||||
"""
|
||||
empty_result = ([], [])
|
||||
|
||||
if isinstance(loras_json, str):
|
||||
raw = loras_json.strip()
|
||||
if not raw or raw == "[]":
|
||||
return empty_result
|
||||
try:
|
||||
loras = json.loads(raw)
|
||||
except Exception:
|
||||
return empty_result
|
||||
elif isinstance(loras_json, dict) and "__value__" in loras_json:
|
||||
loras = loras_json["__value__"]
|
||||
elif isinstance(loras_json, list):
|
||||
loras = loras_json
|
||||
else:
|
||||
return empty_result
|
||||
|
||||
if not isinstance(loras, list):
|
||||
return empty_result
|
||||
|
||||
get_lora_info = _try_get_lm_get_lora_info()
|
||||
stack = []
|
||||
trigger_words = []
|
||||
|
||||
def _normalize_to_relative_lora(raw_value, fallback_name):
|
||||
candidate = str(raw_value or "").strip()
|
||||
if candidate:
|
||||
rel_path, available = get_lora_relative_path(candidate)
|
||||
if available and rel_path:
|
||||
return rel_path
|
||||
|
||||
candidate_base = os.path.basename(candidate.replace("\\", "/")).strip()
|
||||
if candidate_base:
|
||||
rel_path, available = get_lora_relative_path(candidate_base)
|
||||
if available and rel_path:
|
||||
return rel_path
|
||||
|
||||
fallback = str(fallback_name or "").strip()
|
||||
if fallback:
|
||||
rel_path, available = get_lora_relative_path(fallback)
|
||||
if available and rel_path:
|
||||
return rel_path
|
||||
return fallback
|
||||
|
||||
for lora in loras:
|
||||
if not isinstance(lora, dict):
|
||||
continue
|
||||
if not lora.get("active", True):
|
||||
continue
|
||||
|
||||
name = str(lora.get("name", "")).strip()
|
||||
if not name:
|
||||
continue
|
||||
|
||||
try:
|
||||
strength = float(lora.get("strength", 1.0))
|
||||
except (TypeError, ValueError):
|
||||
strength = 1.0
|
||||
|
||||
try:
|
||||
clip_strength = float(lora.get("clipStrength", strength))
|
||||
except (TypeError, ValueError):
|
||||
clip_strength = strength
|
||||
|
||||
# Prefer LM's path resolver (has full cache); fall back to folder_paths scan.
|
||||
lora_path = None
|
||||
if get_lora_info is not None:
|
||||
try:
|
||||
result = get_lora_info(name)
|
||||
if isinstance(result, tuple):
|
||||
if len(result) >= 1 and result[0]:
|
||||
lora_path = _normalize_to_relative_lora(result[0], name)
|
||||
if len(result) >= 2:
|
||||
raw_triggers = result[1]
|
||||
if isinstance(raw_triggers, str):
|
||||
token = raw_triggers.strip()
|
||||
if token:
|
||||
trigger_words.append(token)
|
||||
elif isinstance(raw_triggers, (list, tuple, set)):
|
||||
for trigger in raw_triggers:
|
||||
token = str(trigger or "").strip()
|
||||
if token:
|
||||
trigger_words.append(token)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not lora_path:
|
||||
resolved, available = resolve_lora_path(name)
|
||||
lora_path = _normalize_to_relative_lora(resolved if (available and resolved) else name, name)
|
||||
|
||||
stack.append((lora_path, strength, clip_strength))
|
||||
|
||||
return stack, trigger_words
|
||||
|
||||
|
||||
class MultiLoraStackerLM:
|
||||
"""Multi-slot LoRA stacker with per-slot and combined stack outputs."""
|
||||
|
||||
NAME = "Multi Lora Stacker (LoraManager)"
|
||||
CATEGORY = "Prompt Manager"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
# JSON arrays persisted by the JS loras widget – one per slot.
|
||||
"loras_state_a": ("STRING", {"default": "[]", "multiline": True}),
|
||||
"loras_state_b": ("STRING", {"default": "[]", "multiline": True}),
|
||||
"loras_state_c": ("STRING", {"default": "[]", "multiline": True}),
|
||||
"loras_state_d": ("STRING", {"default": "[]", "multiline": True}),
|
||||
},
|
||||
"optional": {
|
||||
"stack_count": ("INT", {
|
||||
"default": 2,
|
||||
"min": 1,
|
||||
"max": 4,
|
||||
"tooltip": "Number of LoRA stacks to expose and combine.",
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MULTI_LORA_STACK", "LORA_STACK", "STRING")
|
||||
RETURN_NAMES = ("multi_lora_stack", "lora_stack", "trigger_words")
|
||||
FUNCTION = "stack_multi"
|
||||
DESCRIPTION = (
|
||||
"Multi-slot LoRA stacker with a visual 4-panel UI (A / B / C / D). "
|
||||
"Outputs one MULTI_LORA_STACK payload plus one combined LORA_STACK "
|
||||
"containing A+B+C+D in order."
|
||||
)
|
||||
|
||||
def stack_multi(
|
||||
self,
|
||||
loras_state_a="[]",
|
||||
loras_state_b="[]",
|
||||
loras_state_c="[]",
|
||||
loras_state_d="[]",
|
||||
stack_count=2,
|
||||
**kwargs,
|
||||
):
|
||||
stack_a, triggers_a = _build_lora_stack(loras_state_a)
|
||||
stack_b, triggers_b = _build_lora_stack(loras_state_b)
|
||||
stack_c, triggers_c = _build_lora_stack(loras_state_c)
|
||||
stack_d, triggers_d = _build_lora_stack(loras_state_d)
|
||||
|
||||
count = max(1, min(4, int(stack_count or 2)))
|
||||
slot_stacks = [stack_a, stack_b, stack_c, stack_d]
|
||||
slot_triggers = [triggers_a, triggers_b, triggers_c, triggers_d]
|
||||
slot_keys = ["a", "b", "c", "d"]
|
||||
|
||||
multi_lora_stack = {}
|
||||
combined_lora_stack = []
|
||||
trigger_words = []
|
||||
for i in range(4):
|
||||
if i < count:
|
||||
multi_lora_stack[slot_keys[i]] = slot_stacks[i]
|
||||
combined_lora_stack.extend(slot_stacks[i])
|
||||
trigger_words.extend(slot_triggers[i])
|
||||
else:
|
||||
multi_lora_stack[slot_keys[i]] = []
|
||||
|
||||
trigger_words_text = ",, ".join(trigger_words) if trigger_words else ""
|
||||
return (multi_lora_stack, combined_lora_stack, trigger_words_text)
|
||||
|
||||
|
||||
def _coerce_lora_stack(raw_stack):
|
||||
"""Normalize an incoming LORA_STACK-like payload to list[(path, model, clip)]."""
|
||||
if raw_stack is None:
|
||||
return []
|
||||
|
||||
if isinstance(raw_stack, dict) and "__value__" in raw_stack:
|
||||
raw_stack = raw_stack.get("__value__")
|
||||
|
||||
if not isinstance(raw_stack, list):
|
||||
return []
|
||||
|
||||
out = []
|
||||
for item in raw_stack:
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 1:
|
||||
path = str(item[0] or "").strip()
|
||||
if not path:
|
||||
continue
|
||||
try:
|
||||
model_strength = float(item[1]) if len(item) >= 2 else 1.0
|
||||
except Exception:
|
||||
model_strength = 1.0
|
||||
try:
|
||||
clip_strength = float(item[2]) if len(item) >= 3 else model_strength
|
||||
except Exception:
|
||||
clip_strength = model_strength
|
||||
out.append((path, model_strength, clip_strength))
|
||||
continue
|
||||
|
||||
if isinstance(item, dict):
|
||||
path = str(item.get("path") or item.get("name") or "").strip()
|
||||
if not path:
|
||||
continue
|
||||
try:
|
||||
model_strength = float(item.get("model_strength", item.get("strength", 1.0)))
|
||||
except Exception:
|
||||
model_strength = 1.0
|
||||
try:
|
||||
clip_strength = float(item.get("clip_strength", model_strength))
|
||||
except Exception:
|
||||
clip_strength = model_strength
|
||||
out.append((path, model_strength, clip_strength))
|
||||
|
||||
return out
|
||||
|
||||
|
||||
class MultiLoraCombine:
|
||||
"""Combine optional multi stack + optional A/B/C/D stacks into one MULTI_LORA_STACK."""
|
||||
|
||||
NAME = "Multi LoRA Combine"
|
||||
CATEGORY = "Prompt Manager"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {},
|
||||
"optional": {
|
||||
"multi_lora_stack": ("MULTI_LORA_STACK", {
|
||||
"tooltip": "Optional existing MULTI_LORA_STACK to merge into.",
|
||||
}),
|
||||
"lora_stack_a": ("LORA_STACK", {
|
||||
"tooltip": "Optional stack to append to slot A.",
|
||||
}),
|
||||
"lora_stack_b": ("LORA_STACK", {
|
||||
"tooltip": "Optional stack to append to slot B.",
|
||||
}),
|
||||
"lora_stack_c": ("LORA_STACK", {
|
||||
"tooltip": "Optional stack to append to slot C.",
|
||||
}),
|
||||
"lora_stack_d": ("LORA_STACK", {
|
||||
"tooltip": "Optional stack to append to slot D.",
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MULTI_LORA_STACK",)
|
||||
RETURN_NAMES = ("multi_lora_stack",)
|
||||
FUNCTION = "combine_multi"
|
||||
DESCRIPTION = (
|
||||
"Combine an optional MULTI_LORA_STACK with optional LORA_STACK A/B/C/D "
|
||||
"inputs and output one MULTI_LORA_STACK payload."
|
||||
)
|
||||
|
||||
def combine_multi(
|
||||
self,
|
||||
multi_lora_stack=None,
|
||||
lora_stack_a=None,
|
||||
lora_stack_b=None,
|
||||
lora_stack_c=None,
|
||||
lora_stack_d=None,
|
||||
**kwargs,
|
||||
):
|
||||
# Start from empty payload when no multi input is connected.
|
||||
out_a = []
|
||||
out_b = []
|
||||
out_c = []
|
||||
out_d = []
|
||||
|
||||
if isinstance(multi_lora_stack, dict):
|
||||
out_a = _coerce_lora_stack(multi_lora_stack.get("a"))
|
||||
out_b = _coerce_lora_stack(multi_lora_stack.get("b"))
|
||||
out_c = _coerce_lora_stack(multi_lora_stack.get("c"))
|
||||
out_d = _coerce_lora_stack(multi_lora_stack.get("d"))
|
||||
|
||||
# Append separate stack inputs to each slot (if connected).
|
||||
out_a.extend(_coerce_lora_stack(lora_stack_a))
|
||||
out_b.extend(_coerce_lora_stack(lora_stack_b))
|
||||
out_c.extend(_coerce_lora_stack(lora_stack_c))
|
||||
out_d.extend(_coerce_lora_stack(lora_stack_d))
|
||||
|
||||
merged = {
|
||||
"a": out_a,
|
||||
"b": out_b,
|
||||
"c": out_c,
|
||||
"d": out_d,
|
||||
}
|
||||
return (merged,)
|
||||
|
||||
|
||||
class MultiLoraSplitter:
|
||||
"""Split one MULTI_LORA_STACK payload into A/B/C/D LORA_STACK outputs."""
|
||||
|
||||
NAME = "Multi LoRA Splitter"
|
||||
CATEGORY = "Prompt Manager"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"multi_lora_stack": ("MULTI_LORA_STACK", {
|
||||
"tooltip": "Input MULTI_LORA_STACK payload to split into A/B/C/D stacks.",
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("LORA_STACK", "LORA_STACK", "LORA_STACK", "LORA_STACK")
|
||||
RETURN_NAMES = ("lora_stack_a", "lora_stack_b", "lora_stack_c", "lora_stack_d")
|
||||
FUNCTION = "split_multi"
|
||||
DESCRIPTION = "Split a MULTI_LORA_STACK payload into LORA_STACK outputs A/B/C/D."
|
||||
|
||||
def split_multi(self, multi_lora_stack, **kwargs):
|
||||
if not isinstance(multi_lora_stack, dict):
|
||||
return ([], [], [], [])
|
||||
|
||||
out_a = _coerce_lora_stack(multi_lora_stack.get("a"))
|
||||
out_b = _coerce_lora_stack(multi_lora_stack.get("b"))
|
||||
out_c = _coerce_lora_stack(multi_lora_stack.get("c"))
|
||||
out_d = _coerce_lora_stack(multi_lora_stack.get("d"))
|
||||
return (out_a, out_b, out_c, out_d)
|
||||
|
||||
|
||||
class LoraStackCombine:
|
||||
"""Combine up to four LORA_STACK inputs into one merged LORA_STACK output."""
|
||||
|
||||
NAME = "LoRA Stack Combine"
|
||||
CATEGORY = "Prompt Manager"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {},
|
||||
"optional": {
|
||||
"lora_stack_a": ("LORA_STACK", {
|
||||
"tooltip": "Optional LORA_STACK to append first.",
|
||||
}),
|
||||
"lora_stack_b": ("LORA_STACK", {
|
||||
"tooltip": "Optional LORA_STACK to append second.",
|
||||
}),
|
||||
"lora_stack_c": ("LORA_STACK", {
|
||||
"tooltip": "Optional LORA_STACK to append third.",
|
||||
}),
|
||||
"lora_stack_d": ("LORA_STACK", {
|
||||
"tooltip": "Optional LORA_STACK to append fourth.",
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("LORA_STACK",)
|
||||
RETURN_NAMES = ("lora_stack",)
|
||||
FUNCTION = "combine_lora_stacks"
|
||||
DESCRIPTION = "Combine up to four LORA_STACK inputs into one LORA_STACK output."
|
||||
|
||||
def combine_lora_stacks(
|
||||
self,
|
||||
lora_stack_a=None,
|
||||
lora_stack_b=None,
|
||||
lora_stack_c=None,
|
||||
lora_stack_d=None,
|
||||
**kwargs,
|
||||
):
|
||||
merged = []
|
||||
merged.extend(_coerce_lora_stack(lora_stack_a))
|
||||
merged.extend(_coerce_lora_stack(lora_stack_b))
|
||||
merged.extend(_coerce_lora_stack(lora_stack_c))
|
||||
merged.extend(_coerce_lora_stack(lora_stack_d))
|
||||
return (merged,)
|
||||
@@ -0,0 +1,33 @@
|
||||
"""Bundled multi-slot helper node for Recipe Builder."""
|
||||
|
||||
import json
|
||||
|
||||
|
||||
class RecipeBuilderMultiPrompts:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {},
|
||||
"optional": {
|
||||
"model_a": ("STRING", {"forceInput": True}),
|
||||
"model_b": ("STRING", {"forceInput": True}),
|
||||
"model_c": ("STRING", {"forceInput": True}),
|
||||
"model_d": ("STRING", {"forceInput": True}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("multi_prompt",)
|
||||
FUNCTION = "bundle"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Bundle model_a/model_b/model_c/model_d prompts into a JSON string payload."
|
||||
|
||||
def bundle(self,
|
||||
model_a="", model_b="", model_c="", model_d=""):
|
||||
payload = {
|
||||
"model_a": str(model_a or ""),
|
||||
"model_b": str(model_b or ""),
|
||||
"model_c": str(model_c or ""),
|
||||
"model_d": str(model_d or ""),
|
||||
}
|
||||
return (json.dumps(payload, ensure_ascii=True),)
|
||||
@@ -0,0 +1,240 @@
|
||||
"""Prompt Browser node with source-aware prompt selection and random multi-pick."""
|
||||
import json
|
||||
import random
|
||||
import time
|
||||
|
||||
import server
|
||||
|
||||
from ..py.prompt_composer_store import (
|
||||
PromptComposerStore,
|
||||
_find_category_case_insensitive,
|
||||
_find_prompt_case_insensitive,
|
||||
_get_category_prompts_map,
|
||||
)
|
||||
from .prompt_manager_basic import _get_workflow_node
|
||||
from .prompt_manager_basic import PromptManager
|
||||
from .prompt_generator import PromptGeneratorDataStore
|
||||
|
||||
|
||||
def _is_hidden_category_entry_key(name):
|
||||
normalized = str(name or "").strip().lower()
|
||||
return normalized in {"__meta__", "_base_prompt_", "_prompt_type_", "_prompts_"}
|
||||
|
||||
|
||||
def _iter_prompt_items(entries):
|
||||
if not isinstance(entries, dict):
|
||||
return []
|
||||
prompt_entries = _get_category_prompts_map(entries)
|
||||
if isinstance(prompt_entries, dict) and "_prompts_" in entries:
|
||||
return list(prompt_entries.items())
|
||||
return [
|
||||
(name, entry)
|
||||
for name, entry in entries.items()
|
||||
if not _is_hidden_category_entry_key(name)
|
||||
]
|
||||
|
||||
|
||||
class PromptBrowser:
|
||||
"""Browse prompts, select one or many, and emit a resolved prompt."""
|
||||
|
||||
SOURCE_COMPOSE = "Compose Data"
|
||||
SOURCE_PROMPT = "Prompt Data"
|
||||
SOURCE_SYSTEM_PROMPTS = "System Prompts"
|
||||
|
||||
@staticmethod
|
||||
def _load_prompts_for_source(source):
|
||||
if str(source or "") == PromptBrowser.SOURCE_PROMPT:
|
||||
return PromptManager.load_prompts()
|
||||
if str(source or "") == PromptBrowser.SOURCE_SYSTEM_PROMPTS:
|
||||
return PromptGeneratorDataStore.load()
|
||||
return PromptComposerStore.load_prompts()
|
||||
|
||||
@staticmethod
|
||||
def _pick_from_selected(selected_json, seed):
|
||||
try:
|
||||
names = json.loads(selected_json or "[]")
|
||||
except Exception:
|
||||
names = []
|
||||
if not isinstance(names, list) or not names:
|
||||
return ""
|
||||
|
||||
normalized = [str(name).strip() for name in names if str(name).strip()]
|
||||
if not normalized:
|
||||
return ""
|
||||
|
||||
try:
|
||||
seed_value = int(seed)
|
||||
except Exception:
|
||||
seed_value = 0
|
||||
|
||||
if seed_value == 0:
|
||||
return random.choice(normalized)
|
||||
|
||||
rng = random.Random(seed_value)
|
||||
return rng.choice(normalized)
|
||||
|
||||
@staticmethod
|
||||
def _has_multiple_selection(selected_json):
|
||||
try:
|
||||
names = json.loads(selected_json or "[]")
|
||||
except Exception:
|
||||
names = []
|
||||
return isinstance(names, list) and len(names) > 1
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
compose_data = PromptComposerStore.load_prompts()
|
||||
prompt_data = PromptManager.load_prompts()
|
||||
system_data = PromptGeneratorDataStore.load()
|
||||
|
||||
categories_set = set()
|
||||
for source_data in (compose_data, prompt_data, system_data):
|
||||
for category_name in source_data.keys():
|
||||
if category_name == "__meta__":
|
||||
continue
|
||||
categories_set.add(category_name)
|
||||
|
||||
categories = sorted(categories_set, key=str.lower)
|
||||
if not categories:
|
||||
categories = [""]
|
||||
|
||||
all_prompts = []
|
||||
first_prompt_text = ""
|
||||
first_prompt = ""
|
||||
for source_data in (compose_data, prompt_data, system_data):
|
||||
for cat in categories:
|
||||
entries = source_data.get(cat, {})
|
||||
if not isinstance(entries, dict):
|
||||
continue
|
||||
for name, entry in _iter_prompt_items(entries):
|
||||
all_prompts.append(name)
|
||||
if not first_prompt:
|
||||
first_prompt = name
|
||||
if isinstance(entry, dict):
|
||||
first_prompt_text = entry.get("prompt", "") or ""
|
||||
|
||||
all_prompts = sorted(all_prompts, key=str.lower)
|
||||
if not all_prompts:
|
||||
all_prompts = [""]
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"source": ([s.SOURCE_COMPOSE, s.SOURCE_PROMPT, s.SOURCE_SYSTEM_PROMPTS], {"default": s.SOURCE_SYSTEM_PROMPTS}),
|
||||
"category": (categories, {"default": categories[0]}),
|
||||
"name": (all_prompts, {"default": first_prompt}),
|
||||
"selected_prompts": ("STRING", {
|
||||
"default": "[]",
|
||||
"multiline": False,
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "Internal: JSON list of selected prompts",
|
||||
}),
|
||||
"use_prompt_input": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"tooltip": "Toggle to use connected prompt input instead of internal text",
|
||||
}),
|
||||
"text": ("STRING", {
|
||||
"multiline": True,
|
||||
"default": first_prompt_text,
|
||||
"placeholder": "Enter prompt fragment text",
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "Enter prompt fragment text directly",
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"prompt": ("STRING", {
|
||||
"multiline": True,
|
||||
"forceInput": True,
|
||||
"tooltip": "Connect a prompt input to pass through",
|
||||
}),
|
||||
},
|
||||
"hidden": {
|
||||
"seed": ("INT", {
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 0xFFFFFFFFFFFFFFFF,
|
||||
}),
|
||||
"unique_id": "UNIQUE_ID",
|
||||
"extra_pnginfo": "EXTRA_PNGINFO",
|
||||
"api_prompt": "PROMPT",
|
||||
}
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Browse prompts from Prompt Data, Compose Data, or System Prompts with single or multi-random selection."
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("prompt",)
|
||||
FUNCTION = "get_prompt"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(cls, name, **kwargs):
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, source, category, name, selected_prompts="[]", use_prompt_input=False, text="", seed=0, prompt="", **kwargs):
|
||||
if cls._has_multiple_selection(selected_prompts):
|
||||
return (source, category, name, selected_prompts, use_prompt_input, text, time.time_ns(), prompt)
|
||||
return (source, category, name, selected_prompts, use_prompt_input, text, seed, prompt)
|
||||
|
||||
@staticmethod
|
||||
def _patch_runtime_prompt_metadata(unique_id, output_text, extra_pnginfo=None, api_prompt=None):
|
||||
"""Persist resolved prompt into workflow/api metadata for downstream save nodes."""
|
||||
node_id = str(unique_id) if unique_id is not None else ""
|
||||
if not node_id:
|
||||
return
|
||||
|
||||
workflow_node = _get_workflow_node(extra_pnginfo, node_id)
|
||||
if isinstance(workflow_node, dict):
|
||||
widgets = workflow_node.get("widgets_values")
|
||||
if isinstance(widgets, list):
|
||||
# Current layout: [source, category, name, selected_prompts, use_prompt_input, text]
|
||||
if len(widgets) > 4:
|
||||
widgets[4] = False
|
||||
if len(widgets) > 5:
|
||||
widgets[5] = output_text
|
||||
elif len(widgets) > 4:
|
||||
widgets[4] = output_text
|
||||
|
||||
if isinstance(api_prompt, dict):
|
||||
prompt_node = api_prompt.get(node_id)
|
||||
if isinstance(prompt_node, dict):
|
||||
inputs = prompt_node.get("inputs")
|
||||
if isinstance(inputs, dict):
|
||||
inputs["use_prompt_input"] = False
|
||||
inputs["text"] = output_text
|
||||
|
||||
def get_prompt(self, source, category, name, selected_prompts="[]", use_prompt_input=False, text="", prompt=None,
|
||||
seed=0, unique_id=None, extra_pnginfo=None, api_prompt=None):
|
||||
prompts_data = self._load_prompts_for_source(source)
|
||||
canonical_category = _find_category_case_insensitive(prompts_data, category) or category
|
||||
category_data = prompts_data.get(canonical_category, {})
|
||||
|
||||
chosen_name = name
|
||||
if self._has_multiple_selection(selected_prompts):
|
||||
picked = self._pick_from_selected(selected_prompts, seed)
|
||||
if picked:
|
||||
chosen_name = picked
|
||||
|
||||
entry, canonical_name = _find_prompt_case_insensitive(category_data, chosen_name)
|
||||
resolved_text = ""
|
||||
if isinstance(entry, dict):
|
||||
resolved_text = str(entry.get("prompt", "") or "")
|
||||
|
||||
if use_prompt_input and isinstance(prompt, str):
|
||||
output_text = prompt
|
||||
elif resolved_text.strip():
|
||||
output_text = resolved_text
|
||||
else:
|
||||
output_text = text
|
||||
|
||||
if unique_id is not None:
|
||||
server.PromptServer.instance.send_sync("prompt-manager-update-text", {
|
||||
"node_id": unique_id,
|
||||
"prompt": output_text,
|
||||
"use_prompt_input": use_prompt_input,
|
||||
"selected_name": canonical_name or chosen_name,
|
||||
"source": source,
|
||||
})
|
||||
|
||||
self._patch_runtime_prompt_metadata(unique_id, output_text, extra_pnginfo, api_prompt)
|
||||
return (output_text,)
|
||||
@@ -0,0 +1,30 @@
|
||||
from .prompt_generator import PromptGenerator, _preferences_cache, ollama_unload_model
|
||||
|
||||
|
||||
class PromptGeneratorKillSwitch:
|
||||
"""Pass-through node that also stops the local llm server."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"value": ("*", {"forceInput": True, "tooltip": "Any input value to pass through unchanged."}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("*",)
|
||||
RETURN_NAMES = ("value",)
|
||||
FUNCTION = "pass_and_kill"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Pass-through any value, stop Prompt Generator's llama.cpp server, and unload all Ollama models from memory."
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(cls, **kwargs):
|
||||
return True
|
||||
|
||||
def pass_and_kill(self, value):
|
||||
PromptGenerator.stop_server()
|
||||
ok, msg = ollama_unload_model(_preferences_cache)
|
||||
if msg:
|
||||
print(f"Prompt Generator Kill Switch: {msg}")
|
||||
return (value,)
|
||||
@@ -0,0 +1,291 @@
|
||||
from ..py.model_manager import get_all_models, is_model_local, download_model, get_mmproj_for_model, get_mmproj_path, _preferences_cache
|
||||
from ..py.ollama_wrapper import discover_ollama_models, is_ollama_available
|
||||
import time
|
||||
|
||||
# Global timestamp to track when models were last updated
|
||||
_last_model_update = time.time()
|
||||
|
||||
def trigger_model_list_refresh():
|
||||
"""Call this after downloading a model to trigger UI refresh"""
|
||||
global _last_model_update
|
||||
_last_model_update = time.time()
|
||||
|
||||
def get_default_context_size():
|
||||
"""Return a context size scaled to the active GPU's total VRAM.
|
||||
|
||||
Tiers:
|
||||
>= 24 GB → 8192
|
||||
>= 16 GB → 4096
|
||||
< 16 GB → 2048
|
||||
No GPU / unknown → 4096 (safe CPU default)
|
||||
|
||||
Note:
|
||||
This uses GPU capacity (total VRAM), not current free/available VRAM.
|
||||
"""
|
||||
try:
|
||||
import importlib
|
||||
torch = importlib.import_module("torch")
|
||||
if torch.cuda.is_available():
|
||||
try:
|
||||
device_index = torch.cuda.current_device()
|
||||
except Exception:
|
||||
device_index = 0
|
||||
|
||||
total_vram_gb = torch.cuda.get_device_properties(device_index).total_memory / (1024 ** 3)
|
||||
if total_vram_gb >= 24:
|
||||
return 8192
|
||||
elif total_vram_gb >= 16:
|
||||
return 4096
|
||||
else:
|
||||
return 2048
|
||||
except Exception:
|
||||
pass
|
||||
return 4096 # CPU or VRAM detection failed
|
||||
|
||||
|
||||
class PromptGenOptions:
|
||||
"""Node that provides optional configuration for llama.cpp servers"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
backend = _preferences_cache.get("llm_backend", "llama.cpp")
|
||||
preferred_model = str(_preferences_cache.get("preferred_model", "") or "").strip()
|
||||
hide_downloadable_models = _preferences_cache.get("hide_downloadable_models", False) is True
|
||||
|
||||
if backend == "ollama":
|
||||
# Discover models from Ollama
|
||||
ollama_models, _status = discover_ollama_models(_preferences_cache)
|
||||
if not ollama_models:
|
||||
available_models = ["No Ollama models found - run 'ollama pull <model>'"]
|
||||
else:
|
||||
available_models = ollama_models
|
||||
else:
|
||||
available_models = get_all_models()
|
||||
if not available_models:
|
||||
if hide_downloadable_models:
|
||||
available_models = ["No local models found - add a .gguf or disable 'Hide downloadable built-in models'"]
|
||||
else:
|
||||
available_models = ["No models found - check HuggingFace"]
|
||||
|
||||
default_model = available_models[0] if available_models else ""
|
||||
if preferred_model and preferred_model in available_models:
|
||||
default_model = preferred_model
|
||||
|
||||
if backend == "ollama":
|
||||
model_tooltip = "Select the Ollama model to use."
|
||||
elif hide_downloadable_models:
|
||||
model_tooltip = "Select a locally available model. Built-in HuggingFace download entries are hidden by the Prompt Manager preference."
|
||||
else:
|
||||
model_tooltip = "Select model to use (local models listed first, then HuggingFace models)\nDownload sizes: UD-Q4_K_XL ~6GB | Q8_0 ~9.5GB | UD-Q8_K_XL ~13GB"
|
||||
|
||||
return {
|
||||
"optional": {
|
||||
"model": (available_models, {
|
||||
"default": default_model,
|
||||
"tooltip": model_tooltip
|
||||
}),
|
||||
"image2": ("IMAGE", {
|
||||
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
|
||||
}),
|
||||
"image3": ("IMAGE", {
|
||||
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
|
||||
}),
|
||||
"image4": ("IMAGE", {
|
||||
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
|
||||
}),
|
||||
"image5": ("IMAGE", {
|
||||
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
|
||||
}),
|
||||
"system_prompt_mode": (["replace", "append"], {
|
||||
"default": "append",
|
||||
"tooltip": "replace: the text below fully replaces the default LLM instructions\nappend: the text below is added after the default LLM instructions"
|
||||
}),
|
||||
"system_prompt": ("STRING", {
|
||||
"multiline": True,
|
||||
"default": "",
|
||||
"placeholder": "Replace LLM Instructions...",
|
||||
"tooltip": "Custom LLM Instructions (leave empty to use default)\nThe default instructions are designed for generating\ndetailed and imaginative prompts for text-to-image generation."
|
||||
}),
|
||||
"use_model_default_sampling": ("BOOLEAN", {
|
||||
"default": True,
|
||||
"tooltip": "Use the model's default sampling parameters (overrides temperature, top_p, etc)"
|
||||
}),
|
||||
"temperature": ("FLOAT", {
|
||||
"default": 0.7,
|
||||
"min": 0.0,
|
||||
"max": 2.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Controls randomness (0.0 = deterministic, 2.0 = very random)"
|
||||
}),
|
||||
"top_k": ("INT", {
|
||||
"default": 20,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"step": 1,
|
||||
"tooltip": "Sample from top K most likely tokens (0 = disabled)"
|
||||
}),
|
||||
"top_p": ("FLOAT", {
|
||||
"default": 0.9,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Nucleus sampling: consider tokens with top_p probability mass"
|
||||
}),
|
||||
"min_p": ("FLOAT", {
|
||||
"default": 0.05,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Minimum probability threshold relative to top token"
|
||||
}),
|
||||
"repeat_penalty": ("FLOAT", {
|
||||
"default": 1.0,
|
||||
"min": 1.0,
|
||||
"max": 2.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Penalty for repeating tokens (1.0 = no penalty)"
|
||||
}),
|
||||
"context_size": ("INT", {
|
||||
"default": get_default_context_size(),
|
||||
"min": 512,
|
||||
"max": 32768,
|
||||
"step": 512,
|
||||
"tooltip": "Context size (increase for vision models or large prompts)"
|
||||
}),
|
||||
"show_everything_in_console": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"tooltip": "Print system prompt, user prompt, thinking process, and raw model response to console"
|
||||
}),
|
||||
"max_length": ("INT", {
|
||||
"default": 512,
|
||||
"min": 1,
|
||||
"max": 32768,
|
||||
"step": 1,
|
||||
"tooltip": "Maximum number of tokens to generate when the Prompt Generator is connected to a CLIP/text encoder."
|
||||
}),
|
||||
"gpu_device": ("STRING", {
|
||||
"default": "",
|
||||
"tooltip": "GPU device index for llama.cpp (e.g. '0', '1').\nLeave empty to use the system default GPU.\nUseful with multi-GPU setups to control which GPU loads LLM weights."
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Configure LLM model, sampling parameters, and system prompt for the Prompt Generator."
|
||||
RETURN_TYPES = ("OPTIONS",)
|
||||
RETURN_NAMES = ("options",)
|
||||
FUNCTION = "create_options"
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, **kwargs):
|
||||
"""Force refresh when models are updated"""
|
||||
return _last_model_update
|
||||
|
||||
def create_options(self, model: str = None, image2=None, image3=None, image4=None, image5=None,
|
||||
system_prompt: str = None, system_prompt_mode: str = "replace",
|
||||
use_model_default_sampling: bool = None, temperature: float = None,
|
||||
top_k: int = None, top_p: float = None, min_p: float = None,
|
||||
repeat_penalty: float = None, context_size: int = None,
|
||||
show_everything_in_console: bool = None, max_length: int = None,
|
||||
gpu_device: str = None) -> dict:
|
||||
"""Create options dictionary with model, LLM parameters, and extra images"""
|
||||
|
||||
# Backward compatibility for workflows saved before `system_prompt_mode` existed.
|
||||
# Old widget arrays can shift values by one slot when loaded by newer node definitions.
|
||||
mode_valid = system_prompt_mode in ("replace", "append")
|
||||
legacy_shape = isinstance(system_prompt, bool) and (
|
||||
not mode_valid or isinstance(use_model_default_sampling, (int, float))
|
||||
)
|
||||
if legacy_shape:
|
||||
old_system_prompt = system_prompt_mode
|
||||
old_use_default_sampling = system_prompt
|
||||
old_temperature = use_model_default_sampling
|
||||
old_top_k = temperature
|
||||
old_top_p = top_k
|
||||
old_min_p = top_p
|
||||
old_repeat_penalty = min_p
|
||||
old_context_size = repeat_penalty
|
||||
old_show_console = context_size
|
||||
|
||||
system_prompt_mode = "replace"
|
||||
system_prompt = old_system_prompt if isinstance(old_system_prompt, str) else ""
|
||||
use_model_default_sampling = bool(old_use_default_sampling) if old_use_default_sampling is not None else None
|
||||
temperature = old_temperature
|
||||
top_k = old_top_k
|
||||
top_p = old_top_p
|
||||
min_p = old_min_p
|
||||
repeat_penalty = old_repeat_penalty
|
||||
context_size = old_context_size
|
||||
show_everything_in_console = bool(old_show_console) if old_show_console is not None else None
|
||||
|
||||
options = {}
|
||||
|
||||
# Handle model selection and download if needed
|
||||
backend = _preferences_cache.get("llm_backend", "llama.cpp")
|
||||
|
||||
if backend == "ollama":
|
||||
# Ollama mode — no download needed, just validate the selection
|
||||
if model and model != "No Ollama models found - run 'ollama pull <model>'":
|
||||
options["model"] = model
|
||||
options["llm_backend"] = "ollama"
|
||||
elif model and model != "No models found - check HuggingFace":
|
||||
# Check if model is local
|
||||
model_exists = is_model_local(model)
|
||||
|
||||
# For vision models, also check if mmproj exists
|
||||
needs_download = not model_exists
|
||||
if model_exists:
|
||||
mmproj_name = get_mmproj_for_model(model)
|
||||
if mmproj_name:
|
||||
# This is a vision model, check if mmproj is present
|
||||
mmproj_path = get_mmproj_path(model)
|
||||
if not mmproj_path:
|
||||
print(f"[Prompt Generator Options] Vision model found but mmproj missing, downloading: {mmproj_name}")
|
||||
needs_download = True
|
||||
|
||||
if needs_download:
|
||||
if not model_exists:
|
||||
print(f"[Prompt Generator Options] Model not found locally, downloading: {model}")
|
||||
downloaded_path = download_model(model)
|
||||
if downloaded_path:
|
||||
trigger_model_list_refresh()
|
||||
options["model"] = model
|
||||
else:
|
||||
print(f"[Prompt Generator Options] Failed to download model: {model}")
|
||||
else:
|
||||
options["model"] = model
|
||||
|
||||
# Add extra images if provided
|
||||
if image2 is not None:
|
||||
options["image2"] = image2
|
||||
if image3 is not None:
|
||||
options["image3"] = image3
|
||||
if image4 is not None:
|
||||
options["image4"] = image4
|
||||
if image5 is not None:
|
||||
options["image5"] = image5
|
||||
|
||||
# Only include LLM parameters that are provided
|
||||
if system_prompt and system_prompt.strip():
|
||||
options["system_prompt"] = system_prompt
|
||||
options["system_prompt_mode"] = system_prompt_mode
|
||||
|
||||
options["use_model_default_sampling"] = use_model_default_sampling
|
||||
options["temperature"] = temperature
|
||||
options["top_p"] = top_p
|
||||
options["top_k"] = top_k
|
||||
options["min_p"] = min_p
|
||||
options["repeat_penalty"] = repeat_penalty
|
||||
options["context_size"] = context_size
|
||||
options["show_everything_in_console"] = show_everything_in_console
|
||||
options["max_length"] = max_length
|
||||
|
||||
# GPU device: use node input if provided, otherwise fall back to global preference
|
||||
gpu_device_value = None
|
||||
if gpu_device is not None and str(gpu_device).strip():
|
||||
gpu_device_value = str(gpu_device).strip()
|
||||
elif _preferences_cache.get("llama_gpu_device", ""):
|
||||
gpu_device_value = _preferences_cache["llama_gpu_device"]
|
||||
options["gpu_device"] = gpu_device_value
|
||||
|
||||
return (options,)
|
||||
@@ -0,0 +1,551 @@
|
||||
"""
|
||||
Prompt Layout Builder - draw a MOSS-Image layout (scene prompt + boxed regions) or load one from an LLM.
|
||||
|
||||
The editor stores boxes as canvas fractions {x, y, w, h, type, text, desc, palette} in the layout_data widget.
|
||||
The prompt output follows output_format: the native MOSS-Image layout JSON (bbox in pixels from the canvas centre,
|
||||
yxyx, the same format as MOSS-Image Layout Prompt), an Ideogram 4 JSON caption (0-1000 yxyx elements, as Build JSON
|
||||
Prompt (Ideogram)) or the Krea 2 grounding lines of jimmycarter/krea2-turbo-bbox (x-first 0-1000 boxes).
|
||||
import_json accepts the MOSS
|
||||
format, percent or 0-1000 yxyx layouts written by
|
||||
an LLM, Ideogram 4 captions, Krea 2 grounding lines, and the elements list from Create Bounding Boxes. The two converter nodes translate layouts to and from the
|
||||
core BOUNDING_BOX / elements types so the builder can be chained with other box nodes.
|
||||
"""
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
import comfy.utils
|
||||
import nodes
|
||||
from comfy_extras.nodes_bounding_boxes import (
|
||||
boxes_from_input,
|
||||
build_elements,
|
||||
fractions_to_pixels,
|
||||
pixels_to_fractions,
|
||||
render_preview,
|
||||
)
|
||||
from comfy_extras.nodes_resolution import ASPECT_RATIOS
|
||||
|
||||
from ..py.workflow_data_utils import build_v2_recipe_data_from_prompt
|
||||
|
||||
|
||||
REF_RATIO = "Use Reference Ratio"
|
||||
# manager_data key holding the editor state, next to Prompt Composer's "prompt_composer".
|
||||
LAYOUT_RECIPE_KEY = "prompt_layout"
|
||||
SIZE_MULTIPLE = 16
|
||||
CANVASES = ("single", "multi_panel", "collage")
|
||||
BOX_TYPES = ("object", "character", "text", "panel")
|
||||
BOX_PALETTE_MAX = 8
|
||||
SUMMARY_PALETTE_MAX = 16
|
||||
HEX_COLOR = re.compile(r"#[0-9a-fA-F]{6}")
|
||||
RELATIVE_SPACES = {"percent": 100.0, "relative_1000": 1000.0}
|
||||
OUTPUT_FORMATS = ("MOSS", "Ideogram", "Krea 2")
|
||||
# Krea 2 character tags: person, anime character, furry / anthro character.
|
||||
KREA_CHARACTER_TAGS = ("pe", "ac", "fc")
|
||||
KREA_CHARACTER_ID = re.compile(r"[a-z0-9_]+")
|
||||
|
||||
|
||||
def _resolution(aspect_ratio, megapixels, ref_size):
|
||||
if aspect_ratio != REF_RATIO:
|
||||
w_ratio, h_ratio = ASPECT_RATIOS[aspect_ratio]
|
||||
else:
|
||||
w_ratio, h_ratio = ref_size or (1, 1)
|
||||
scale = math.sqrt(megapixels * 1024 * 1024 / (w_ratio * h_ratio))
|
||||
return tuple(max(SIZE_MULTIPLE, round(r * scale / SIZE_MULTIPLE) * SIZE_MULTIPLE) for r in (w_ratio, h_ratio))
|
||||
|
||||
|
||||
def _strs(value):
|
||||
if isinstance(value, str):
|
||||
value = re.split(r"[,\n]", value)
|
||||
return [str(v).strip() for v in (value if isinstance(value, list) else []) if str(v).strip()]
|
||||
|
||||
|
||||
def _palette(value, limit):
|
||||
return [c.upper() for c in _strs(value) if HEX_COLOR.fullmatch(c)][:limit]
|
||||
|
||||
|
||||
def _clean_box(raw):
|
||||
x, y, w, h = (float(raw.get(k) or 0.0) for k in ("x", "y", "w", "h"))
|
||||
x1, x2 = sorted((x, x + w))
|
||||
y1, y2 = sorted((y, y + h))
|
||||
x1, y1, x2, y2 = (min(1.0, max(0.0, v)) for v in (x1, y1, x2, y2))
|
||||
box_type = raw.get("type") if raw.get("type") in BOX_TYPES else "object"
|
||||
box = {
|
||||
"x": x1, "y": y1, "w": x2 - x1, "h": y2 - y1,
|
||||
"type": box_type,
|
||||
"text": str(raw.get("text") or "") if box_type == "text" else "",
|
||||
"desc": str(raw.get("desc") or ""),
|
||||
"palette": _palette(raw.get("palette"), BOX_PALETTE_MAX),
|
||||
}
|
||||
ref = raw.get("prompt_ref")
|
||||
if isinstance(ref, dict) and ref.get("name"):
|
||||
box["prompt_ref"] = {"category": str(ref.get("category") or ""), "name": str(ref["name"])}
|
||||
if box_type == "character":
|
||||
if raw.get("krea_tag") in KREA_CHARACTER_TAGS:
|
||||
box["krea_tag"] = raw["krea_tag"]
|
||||
char_id = str(raw.get("char_id") or "").strip().lower()
|
||||
if KREA_CHARACTER_ID.fullmatch(char_id):
|
||||
box["char_id"] = char_id
|
||||
return box
|
||||
|
||||
|
||||
def _find_layout(text):
|
||||
# LLM output may wrap the JSON in prose or a code fence: take the first layout-shaped value.
|
||||
decoder = json.JSONDecoder()
|
||||
for match in re.finditer(r"[{\[]", text):
|
||||
try:
|
||||
value, _ = decoder.raw_decode(text, match.start())
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if isinstance(value, dict) and isinstance(value.get("items"), list):
|
||||
return value
|
||||
if isinstance(value, list) and value and all(isinstance(v, dict) and "bbox" in v and "type" in v for v in value):
|
||||
return {"items": value, "bbox_coord_space": "relative_1000"}
|
||||
raise ValueError('Prompt Layout Builder: import_json has no layout (an object with "items", or a list of elements).')
|
||||
|
||||
|
||||
KREA_ELEMENT = re.compile(r"(p|o|t|pe|ac|fc)(?::([a-z0-9_]+))?\[\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*,\s*(-?[\d.]+)\s*\]\s*(.*)")
|
||||
KREA_TEXT = re.compile(r'"((?:[^"\\]|\\.)*)"\s*(.*)')
|
||||
KREA_BOX_TYPES = {"p": "panel", "o": "object", "t": "text", "pe": "character", "ac": "character", "fc": "character"}
|
||||
|
||||
|
||||
def _parse_krea(text):
|
||||
# Krea 2 grounding lines (krea2-turbo-bbox); None when the text has no element, @ or ~ line.
|
||||
fence = re.search(r"```[^\n]*\n(.*?)```", text, re.S)
|
||||
lines = [line.strip() for line in (fence.group(1) if fence else text).splitlines() if line.strip()]
|
||||
summary, fields, boxes, grounded = "", {}, [], False
|
||||
for line in lines:
|
||||
element = KREA_ELEMENT.fullmatch(line)
|
||||
if element:
|
||||
tag, char_id, rest = element.group(1), element.group(2), element.group(7)
|
||||
x0, y0, x1, y1 = (float(element.group(i)) / 1000 for i in range(3, 7))
|
||||
box = {"x": x0, "y": y0, "w": x1 - x0, "h": y1 - y0, "type": KREA_BOX_TYPES[tag], "desc": rest}
|
||||
if tag == "t":
|
||||
quoted = KREA_TEXT.match(rest)
|
||||
if quoted:
|
||||
box["text"] = re.sub(r"\\(.)", lambda m: "\n" if m.group(1) == "n" else m.group(1), quoted.group(1))
|
||||
box["desc"] = quoted.group(2)
|
||||
if box["type"] == "character":
|
||||
box.update(krea_tag=tag, char_id=char_id)
|
||||
boxes.append(_clean_box(box))
|
||||
grounded = True
|
||||
elif line.startswith("@"):
|
||||
head, sep, tail = line[1:].rpartition(";")
|
||||
fields["style"], fields["medium"] = (head.strip(), tail.strip()) if sep else (tail.strip(), "")
|
||||
grounded = True
|
||||
elif line.startswith("~"):
|
||||
fields["background"] = line[1:].strip()
|
||||
grounded = True
|
||||
elif not summary and not grounded:
|
||||
summary = line
|
||||
return {"prompt": summary, "krea": fields, "boxes": boxes} if grounded else None
|
||||
|
||||
|
||||
def _parse_ideogram(text):
|
||||
# Ideogram 4 JSON caption (Build JSON Prompt (Ideogram)); None when the text has none.
|
||||
decoder = json.JSONDecoder()
|
||||
for match in re.finditer(r"\{", text):
|
||||
try:
|
||||
caption, _ = decoder.raw_decode(text, match.start())
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if isinstance(caption, dict) and isinstance(caption.get("compositional_deconstruction"), dict):
|
||||
break
|
||||
else:
|
||||
return None
|
||||
scene = caption["compositional_deconstruction"]
|
||||
style = caption.get("style_description") if isinstance(caption.get("style_description"), dict) else {}
|
||||
text_of = lambda value: str(value or "").strip()
|
||||
fields = {"background": text_of(scene.get("background"))}
|
||||
if style:
|
||||
kind = "art_style" if "art_style" in style else "photo" if "photo" in style else (
|
||||
"photo" if text_of(style.get("medium")).lower() == "photograph" else "art_style")
|
||||
fields.update(style=kind, style_detail=text_of(style.get(kind)), aesthetics=text_of(style.get("aesthetics")),
|
||||
lighting=text_of(style.get("lighting")), medium=text_of(style.get("medium")))
|
||||
elements = [e for e in scene.get("elements") or [] if isinstance(e, dict)]
|
||||
return {
|
||||
"prompt": text_of(caption.get("high_level_description")),
|
||||
"ideogram": fields,
|
||||
"palette": _palette(style.get("color_palette"), SUMMARY_PALETTE_MAX),
|
||||
"boxes": _import_boxes({"items": elements, "bbox_coord_space": "relative_1000"}, 1, 1),
|
||||
}
|
||||
|
||||
def _parse_text_layout(text, width, height, label):
|
||||
parsed = _parse_krea(text) or _parse_ideogram(text)
|
||||
if parsed:
|
||||
return parsed
|
||||
try:
|
||||
layout = _find_layout(text)
|
||||
except ValueError:
|
||||
received = " ".join(text.split())
|
||||
raise ValueError(f"{label} has no layout. Expected layout JSON (an object with \"items\" or a list of elements), "
|
||||
"an Ideogram 4 caption or Krea 2 grounding lines; check the Prompt Generator system prompt. "
|
||||
f"Received: {received[:200]!r}{'...' if len(received) > 200 else ''}") from None
|
||||
return {"layout": layout, "boxes": _import_boxes(layout, width, height)}
|
||||
|
||||
|
||||
def _boxes_from_bboxes(bboxes, width, height):
|
||||
boxes = []
|
||||
for raw in boxes_from_input(bboxes, width, height):
|
||||
metadata = raw.get("metadata") or {}
|
||||
box_type = "text" if metadata.get("type") == "text" else "character" if metadata.get("is_character") else "object"
|
||||
boxes.append(_clean_box({
|
||||
**pixels_to_fractions(raw, width, height),
|
||||
"type": box_type,
|
||||
"text": metadata.get("text"),
|
||||
"desc": metadata.get("desc"),
|
||||
"palette": metadata.get("palette"),
|
||||
}))
|
||||
return boxes
|
||||
|
||||
|
||||
def _import_boxes(layout, width, height):
|
||||
space = str(layout.get("bbox_coord_space") or "abs_centralized")
|
||||
if space != "abs_centralized" and space not in RELATIVE_SPACES:
|
||||
raise ValueError(f"Prompt Layout Builder: unsupported bbox_coord_space {space!r} "
|
||||
"(expected percent, relative_1000 or abs_centralized).")
|
||||
if str(layout.get("bbox_format") or "yxyx") != "yxyx":
|
||||
raise ValueError('Prompt Layout Builder: bbox_format must be "yxyx" (top, left, bottom, right).')
|
||||
boxes = []
|
||||
for index, item in enumerate(layout["items"], 1):
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
try:
|
||||
top, left, bottom, right = (float(v) for v in item.get("bbox"))
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(f"Prompt Layout Builder: item {index} needs a bbox [top, left, bottom, right].")
|
||||
if space == "abs_centralized":
|
||||
top, bottom = ((v + height // 2) / height for v in (top, bottom))
|
||||
left, right = ((v + width // 2) / width for v in (left, right))
|
||||
else:
|
||||
top, left, bottom, right = (v / RELATIVE_SPACES[space] for v in (top, left, bottom, right))
|
||||
boxes.append(_clean_box({
|
||||
"x": left, "y": top, "w": right - left, "h": bottom - top,
|
||||
"type": item.get("label", item.get("type")),
|
||||
"text": item.get("text"),
|
||||
"desc": item.get("caption", item.get("desc")),
|
||||
"palette": item.get("palette", item.get("color_palette")),
|
||||
}))
|
||||
return boxes
|
||||
|
||||
|
||||
def _moss_bbox(box, width, height):
|
||||
# Same rounding as MOSS-Image Layout Prompt: pixel edges enclosing the box, origin at the canvas centre.
|
||||
hx, hy = width // 2, height // 2
|
||||
return [math.floor(round(box["y"] * height, 9)) - hy, math.floor(round(box["x"] * width, 9)) - hx,
|
||||
math.ceil(round((box["y"] + box["h"]) * height, 9)) - hy, math.ceil(round((box["x"] + box["w"]) * width, 9)) - hx]
|
||||
|
||||
|
||||
def _layout_prompt(prompt, meta, canvas, palette, boxes, width, height):
|
||||
items = []
|
||||
for box in boxes:
|
||||
item = {"label": "object" if box["type"] == "panel" else box["type"], "caption": box["desc"]}
|
||||
if box["type"] == "text":
|
||||
item["text"] = box["text"]
|
||||
if box["palette"]:
|
||||
item["palette"] = box["palette"]
|
||||
item["bbox"] = _moss_bbox(box, width, height)
|
||||
items.append(item)
|
||||
if not items:
|
||||
return prompt
|
||||
summary = {}
|
||||
if meta:
|
||||
summary["meta"] = meta
|
||||
if canvas in CANVASES:
|
||||
summary["canvas"] = canvas
|
||||
summary["caption"] = prompt.strip()
|
||||
if palette:
|
||||
summary["palette"] = palette
|
||||
layout = {"summary": summary, "items": items, "bbox_coord_space": "abs_centralized", "bbox_format": "yxyx"}
|
||||
return json.dumps(layout, ensure_ascii=False, separators=(",", ":"))
|
||||
|
||||
|
||||
def _ideogram_prompt(prompt, palette, boxes, fields):
|
||||
# Same caption as Ideogram 4 Prompt Builder KJ: compact JSON, and every style key in order once a style is set.
|
||||
fields = fields if isinstance(fields, dict) else {}
|
||||
text = lambda key: str(fields.get(key) or "")
|
||||
caption = {}
|
||||
if prompt.strip():
|
||||
caption["high_level_description"] = prompt.strip()
|
||||
style = fields.get("style")
|
||||
if style in ("photo", "art_style"):
|
||||
style_description = {"aesthetics": text("aesthetics"), "lighting": text("lighting")}
|
||||
if style == "photo":
|
||||
style_description.update(photo=text("style_detail"), medium=text("medium"))
|
||||
else:
|
||||
style_description.update(medium=text("medium"), art_style=text("style_detail"))
|
||||
if palette:
|
||||
style_description["color_palette"] = palette
|
||||
caption["style_description"] = style_description
|
||||
caption["compositional_deconstruction"] = {"background": text("background"), "elements": build_elements(boxes)}
|
||||
return json.dumps(caption, ensure_ascii=False, separators=(",", ":"))
|
||||
|
||||
|
||||
def _format_prompt(output_format, prompt, meta, canvas, palette, boxes, width, height, ideogram=None, krea=None):
|
||||
if output_format == "Ideogram":
|
||||
return _ideogram_prompt(prompt, palette, boxes, ideogram)
|
||||
if output_format == "Krea 2":
|
||||
return _krea_prompt(prompt, boxes, krea)
|
||||
if not boxes:
|
||||
return prompt
|
||||
return _layout_prompt(prompt, meta, canvas, palette, boxes, width, height)
|
||||
|
||||
|
||||
def _one_line(text):
|
||||
return " ".join(str(text or "").split())
|
||||
|
||||
|
||||
def _krea_prompt(prompt, boxes, fields):
|
||||
# Grounding DSL from jimmycarter/krea2-turbo-bbox PROMPTING.md: summary, @style; medium, ~background, one line per box.
|
||||
fields = fields if isinstance(fields, dict) else {}
|
||||
lines = []
|
||||
if _one_line(prompt):
|
||||
lines.append(_one_line(prompt))
|
||||
style_line = "; ".join(part for part in (_one_line(fields.get("style")), _one_line(fields.get("medium"))) if part)
|
||||
if style_line:
|
||||
lines.append("@" + style_line)
|
||||
if _one_line(fields.get("background")):
|
||||
lines.append("~" + _one_line(fields.get("background")))
|
||||
# Panels first, as in the training data; the rest keep the editor order.
|
||||
for box in sorted(boxes, key=lambda b: b["type"] != "panel"):
|
||||
bbox = ",".join(str(round(v * 1000)) for v in (box["x"], box["y"], box["x"] + box["w"], box["y"] + box["h"]))
|
||||
if box["type"] == "character":
|
||||
head = box.get("krea_tag", "pe") + (f":{box['char_id']}" if box.get("char_id") else "")
|
||||
else:
|
||||
head = {"panel": "p", "text": "t"}.get(box["type"], "o")
|
||||
line = f"{head}[{bbox}]"
|
||||
if box["type"] == "text":
|
||||
escaped = box["text"].replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n")
|
||||
line += f'"{escaped}"'
|
||||
if _one_line(box["desc"]):
|
||||
line += " " + _one_line(box["desc"])
|
||||
lines.append(line)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _fit_background(image, width, height):
|
||||
samples = image[:1, :, :, :3].movedim(-1, 1)
|
||||
return comfy.utils.common_upscale(samples, width, height, "lanczos", "center").movedim(1, -1)
|
||||
|
||||
|
||||
def _manager_data(layout_prompt, state, width, height):
|
||||
data = build_v2_recipe_data_from_prompt(prompt_text=layout_prompt, source="PromptLayoutBuilder")
|
||||
data["models"]["model_a"]["resolution"].update(width=width, height=height)
|
||||
data[LAYOUT_RECIPE_KEY] = {
|
||||
**state,
|
||||
"width": width,
|
||||
"height": height,
|
||||
"composer_prompts": [
|
||||
{"box": index, **box["prompt_ref"]} for index, box in enumerate(state["boxes"], 1) if box.get("prompt_ref")
|
||||
],
|
||||
}
|
||||
return data
|
||||
|
||||
|
||||
def _pixel_frame(boxes, width, height):
|
||||
# Pixel boxes carrying the metadata Create Bounding Boxes and Vantage read back.
|
||||
frame = []
|
||||
for box in boxes:
|
||||
metadata = {"type": "text" if box["type"] == "text" else "obj", "text": box["text"], "desc": box["desc"],
|
||||
"palette": box["palette"]}
|
||||
if box["type"] == "character":
|
||||
metadata["is_character"] = True
|
||||
frame.append({**fractions_to_pixels(box, width, height), "metadata": metadata})
|
||||
return [frame] if frame else []
|
||||
|
||||
|
||||
def _percent_item(box):
|
||||
item = {"label": box["type"], "caption": box["desc"]}
|
||||
if box["type"] == "text":
|
||||
item["text"] = box["text"]
|
||||
if box["palette"]:
|
||||
item["palette"] = box["palette"]
|
||||
item["bbox"] = [round(v * 100, 1) for v in (box["y"], box["x"], box["y"] + box["h"], box["x"] + box["w"])]
|
||||
return item
|
||||
|
||||
|
||||
_SIZE_INPUT = {"default": 1024, "min": 16, "max": 16384, "step": 8,
|
||||
"tooltip": "Canvas size the pixel boxes refer to, e.g. the layout builder's width/height outputs."}
|
||||
|
||||
|
||||
class BboxConverter:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"width": ("INT", _SIZE_INPUT),
|
||||
"height": ("INT", _SIZE_INPUT),
|
||||
"use_bboxes": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"label_on": "bboxes",
|
||||
"label_off": "layout_json",
|
||||
"tooltip": "Input to convert when both are connected (shown only then).",
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"layout_json": ("STRING", {
|
||||
"forceInput": True,
|
||||
"tooltip": "Layout JSON (MOSS-native, percent or 0-1000 boxes), an Ideogram 4 caption or Krea 2 "
|
||||
"grounding lines. Passed through to the layout_json output.",
|
||||
}),
|
||||
"bboxes": ("BOUNDING_BOX,ARRAY,STRING", {
|
||||
"forceInput": True,
|
||||
"tooltip": "Bounding boxes, Create Bounding Boxes elements, or their JSON.",
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING", "BOUNDING_BOX", "ARRAY")
|
||||
RETURN_NAMES = ("layout_json", "bboxes", "elements")
|
||||
FUNCTION = "convert"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = ("Convert between a layout JSON and bounding boxes. Outputs the layout JSON (percent boxes when "
|
||||
"converting bboxes), pixel bounding boxes and Create Bounding Boxes elements.")
|
||||
|
||||
def convert(self, width, height, use_bboxes=False, layout_json=None, bboxes=None):
|
||||
if bboxes is not None and (use_bboxes or layout_json is None):
|
||||
boxes = _boxes_from_bboxes(bboxes, width, height)
|
||||
layout_json = json.dumps({"items": [_percent_item(box) for box in boxes], "bbox_coord_space": "percent",
|
||||
"bbox_format": "yxyx"}, ensure_ascii=False, indent=2)
|
||||
elif layout_json is not None:
|
||||
boxes = _parse_text_layout(layout_json, width, height, "Bbox Converter: layout_json")["boxes"]
|
||||
else:
|
||||
raise ValueError("Bbox Converter: connect layout_json or bboxes.")
|
||||
return (layout_json, _pixel_frame(boxes, width, height), build_elements(boxes))
|
||||
|
||||
|
||||
class PromptLayoutBuilder:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"aspect_ratio": ([REF_RATIO, *(ratio.value for ratio in ASPECT_RATIOS)], {
|
||||
"default": "1:1 (Square)",
|
||||
"tooltip": "Canvas aspect ratio. 'Use Reference Ratio' follows a layout restored from manager_data, "
|
||||
"otherwise the connected image.",
|
||||
}),
|
||||
"megapixels": ("FLOAT", {
|
||||
"default": 1.0, "min": 0.1, "max": 16.0, "step": 0.1,
|
||||
"tooltip": "Target canvas size; width and height are rounded to multiples of 16.",
|
||||
}),
|
||||
"prompt": ("STRING", {
|
||||
"multiline": True,
|
||||
"default": "",
|
||||
"placeholder": "Scene description (summary caption)",
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "Description of the whole image and its style.",
|
||||
}),
|
||||
"meta": ("STRING", {
|
||||
"default": "",
|
||||
"tooltip": "Comma-separated style tags for summary.meta, e.g. \"poster, graphic design\" (blank = omitted).",
|
||||
}),
|
||||
"canvas": (["none", *CANVASES], {
|
||||
"default": "none",
|
||||
"tooltip": "summary.canvas: single image, multi_panel or collage (none = omitted).",
|
||||
}),
|
||||
"use_import_json": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"tooltip": "Read the layout from import_json and lock the editor. Turn off to edit the imported boxes.",
|
||||
}),
|
||||
"layout_data": ("STRING", {"default": "{}", "tooltip": "Editor boxes (managed by the node UI)."}),
|
||||
"output_format": (list(OUTPUT_FORMATS), {
|
||||
"default": "MOSS",
|
||||
"tooltip": "Prompt format: MOSS-Image layout JSON, Ideogram 4 JSON caption or Krea 2 grounding lines.",
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"image": ("IMAGE", {"tooltip": "Background for the editor; also sets the ratio with 'Use Reference Ratio'."}),
|
||||
"import_json": ("STRING,MANAGER_DATA", {
|
||||
"forceInput": True,
|
||||
"lazy": True,
|
||||
"tooltip": "Layout JSON (e.g. from Prompt Generator: percent, 0-1000 or MOSS-native boxes), an "
|
||||
"Ideogram 4 caption, Krea 2 grounding lines, or a saved "
|
||||
"layout's manager_data from Library Manager. Only evaluated when use_import_json is on.",
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING", "IMAGE", "INT", "INT", "MANAGER_DATA")
|
||||
RETURN_NAMES = ("prompt", "preview", "width", "height", "manager_data")
|
||||
FUNCTION = "build"
|
||||
CATEGORY = "Prompt Manager"
|
||||
OUTPUT_NODE = True
|
||||
DESCRIPTION = ("Draw layout boxes over a scene prompt, or load them from an LLM layout. "
|
||||
"Outputs a MOSS-Image, Ideogram 4 or Krea 2 prompt.")
|
||||
|
||||
def check_lazy_status(self, use_import_json, **kwargs):
|
||||
return ["import_json"] if use_import_json else []
|
||||
|
||||
def build(self, aspect_ratio, megapixels, prompt, meta, canvas, use_import_json, layout_data,
|
||||
image=None, import_json=None, output_format="MOSS"):
|
||||
saved = None
|
||||
if use_import_json and isinstance(import_json, dict):
|
||||
saved = import_json.get(LAYOUT_RECIPE_KEY)
|
||||
if not isinstance(saved, dict):
|
||||
raise ValueError("Prompt Layout Builder: this manager_data has no layout (it comes from Prompt Manager or Prompt Composer).")
|
||||
text_import = use_import_json and isinstance(import_json, str) and import_json.strip()
|
||||
if saved and saved.get("width") and saved.get("height"):
|
||||
ref_size = (int(saved["width"]), int(saved["height"]))
|
||||
elif image is not None:
|
||||
ref_size = (int(image.shape[2]), int(image.shape[1]))
|
||||
else:
|
||||
ref_size = None
|
||||
width, height = _resolution(aspect_ratio, megapixels, ref_size)
|
||||
|
||||
state = saved if saved else json.loads(layout_data or "{}")
|
||||
boxes = [_clean_box(box) for box in state.get("boxes", []) if isinstance(box, dict)]
|
||||
palette = _palette(state.get("palette"), SUMMARY_PALETTE_MAX)
|
||||
ideogram = state.get("ideogram") if isinstance(state.get("ideogram"), dict) else {}
|
||||
krea = state.get("krea") if isinstance(state.get("krea"), dict) else {}
|
||||
meta_tags = _strs(meta)
|
||||
ui = {}
|
||||
|
||||
if saved:
|
||||
prompt = str(saved.get("prompt") or "")
|
||||
meta_tags = _strs(saved.get("meta"))
|
||||
canvas = saved.get("canvas") if saved.get("canvas") in CANVASES else "none"
|
||||
elif text_import:
|
||||
parsed = _parse_text_layout(import_json, width, height, "Prompt Layout Builder: import_json")
|
||||
prompt, boxes = parsed.get("prompt", prompt), parsed["boxes"]
|
||||
krea = parsed.get("krea", krea)
|
||||
ideogram = parsed.get("ideogram", ideogram)
|
||||
palette = parsed.get("palette", palette)
|
||||
summary = (parsed.get("layout") or {}).get("summary")
|
||||
if isinstance(summary, dict):
|
||||
prompt = str(summary.get("caption") or "")
|
||||
meta_tags = _strs(summary.get("meta"))
|
||||
canvas = summary.get("canvas") if summary.get("canvas") in CANVASES else "none"
|
||||
palette = _palette(summary.get("palette"), SUMMARY_PALETTE_MAX)
|
||||
if saved or text_import:
|
||||
ui["pm_layout_import"] = [{
|
||||
"boxes": boxes, "palette": palette, "prompt": prompt, "meta": ", ".join(meta_tags), "canvas": canvas,
|
||||
**({"ideogram": ideogram} if ideogram and (saved or text_import) else {}),
|
||||
**({"krea": krea} if krea and (saved or text_import) else {}),
|
||||
}]
|
||||
|
||||
ui["pm_layout_ref_size"] = list(ref_size) if ref_size else []
|
||||
if image is None:
|
||||
preview_bg = None
|
||||
ui["pm_layout_background"] = []
|
||||
else:
|
||||
background = _fit_background(image, width, height)
|
||||
preview_bg = Image.fromarray((background[0].cpu().numpy() * 255).clip(0, 255).astype(np.uint8))
|
||||
ui["pm_layout_background"] = nodes.PreviewImage().save_images(background, "pm.layout.background")["ui"]["images"]
|
||||
|
||||
layout_prompt = _format_prompt(output_format, prompt, meta_tags, canvas, palette, boxes, width, height, ideogram, krea)
|
||||
editor_state = {
|
||||
"boxes": boxes, "palette": palette, "prompt": prompt, "meta": meta_tags, "canvas": canvas,
|
||||
"aspect_ratio": aspect_ratio, "megapixels": megapixels, "ideogram": ideogram, "krea": krea,
|
||||
}
|
||||
return {
|
||||
"ui": ui,
|
||||
"result": (
|
||||
layout_prompt,
|
||||
render_preview(boxes, width, height, preview_bg),
|
||||
width,
|
||||
height,
|
||||
_manager_data(layout_prompt, editor_state, width, height),
|
||||
),
|
||||
}
|
||||
@@ -0,0 +1,574 @@
|
||||
import os
|
||||
import json
|
||||
import shutil
|
||||
import time
|
||||
import folder_paths
|
||||
import server
|
||||
from ..py.backup_manager import atomic_save, load_with_fallback, check_backup
|
||||
|
||||
|
||||
def _safe_abspath(path):
|
||||
return os.path.abspath(os.path.expanduser(path or ""))
|
||||
|
||||
|
||||
def _normalize_export_path(raw_path):
|
||||
candidate = _safe_abspath(raw_path)
|
||||
if not candidate:
|
||||
return ""
|
||||
if not candidate.lower().endswith(".json"):
|
||||
candidate = f"{candidate}.json"
|
||||
return candidate
|
||||
|
||||
|
||||
def _get_workflow_node(extra_pnginfo, node_id: str):
|
||||
"""Find workflow node by id, including nested subgraphs (id chains like a:b:c)."""
|
||||
if not isinstance(extra_pnginfo, dict):
|
||||
return None
|
||||
|
||||
workflow = extra_pnginfo.get("workflow")
|
||||
if not isinstance(workflow, dict):
|
||||
return None
|
||||
|
||||
nodes_list = workflow.get("nodes", []) if isinstance(workflow.get("nodes"), list) else []
|
||||
subgraphs = []
|
||||
definitions = workflow.get("definitions")
|
||||
if isinstance(definitions, dict):
|
||||
maybe_subgraphs = definitions.get("subgraphs")
|
||||
if isinstance(maybe_subgraphs, list):
|
||||
subgraphs = maybe_subgraphs
|
||||
|
||||
found = None
|
||||
for part in str(node_id).split(":"):
|
||||
found = next((n for n in nodes_list if isinstance(n, dict) and str(n.get("id")) == part), None)
|
||||
if not isinstance(found, dict):
|
||||
return None
|
||||
|
||||
subgraph = next((sg for sg in subgraphs if isinstance(sg, dict) and str(sg.get("id")) == str(found.get("type"))), None)
|
||||
if isinstance(subgraph, dict) and isinstance(subgraph.get("nodes"), list):
|
||||
nodes_list = subgraph.get("nodes", [])
|
||||
|
||||
return found
|
||||
|
||||
|
||||
def _patch_runtime_prompt_metadata(unique_id, output_text, extra_pnginfo=None, api_prompt=None):
|
||||
"""Persist resolved prompt into workflow/api metadata for downstream save nodes."""
|
||||
node_id = str(unique_id) if unique_id is not None else ""
|
||||
if not node_id:
|
||||
return
|
||||
|
||||
# Patch workflow metadata (EXTRA_PNGINFO).
|
||||
workflow_node = _get_workflow_node(extra_pnginfo, node_id)
|
||||
if isinstance(workflow_node, dict):
|
||||
widgets = workflow_node.get("widgets_values")
|
||||
if isinstance(widgets, list):
|
||||
# PromptManager widgets order:
|
||||
# [category, name, use_external, text]
|
||||
if len(widgets) > 2:
|
||||
widgets[2] = False
|
||||
if len(widgets) > 3:
|
||||
widgets[3] = output_text
|
||||
|
||||
# Patch API prompt metadata (PROMPT).
|
||||
if isinstance(api_prompt, dict):
|
||||
prompt_node = api_prompt.get(node_id)
|
||||
if isinstance(prompt_node, dict):
|
||||
inputs = prompt_node.get("inputs")
|
||||
if isinstance(inputs, dict):
|
||||
inputs["use_external"] = False
|
||||
inputs["text"] = output_text
|
||||
|
||||
|
||||
class PromptManager:
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
prompts_data = PromptManager.load_prompts()
|
||||
categories = list(prompts_data.keys()) if prompts_data else ["Character"]
|
||||
|
||||
all_prompts = set()
|
||||
for category_prompts in prompts_data.values():
|
||||
all_prompts.update(k for k in category_prompts.keys() if k != "__meta__")
|
||||
|
||||
all_prompts.add("")
|
||||
all_prompts_list = sorted(list(all_prompts))
|
||||
|
||||
first_category = categories[0] if categories else "Character"
|
||||
|
||||
# Get first prompt from first category
|
||||
first_prompt = ""
|
||||
first_prompt_text = ""
|
||||
if prompts_data and first_category in prompts_data and prompts_data[first_category]:
|
||||
first_category_prompts = [k for k in prompts_data[first_category].keys() if k != "__meta__"]
|
||||
first_prompt = sorted(first_category_prompts, key=str.lower)[0] if first_category_prompts else ""
|
||||
if first_prompt:
|
||||
first_prompt_text = prompts_data[first_category][first_prompt].get("prompt", "")
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"category": (categories, {"default": first_category}),
|
||||
"name": (all_prompts_list, {"default": first_prompt}),
|
||||
"use_external": ("BOOLEAN", {"default": False, "tooltip": "Toggle to use LLM input instead of internal text"}),
|
||||
"text": ("STRING", {"multiline": True, "default": first_prompt_text, "placeholder": "Enter prompt text", "dynamicPrompts": False, "tooltip": "Enter prompt text directly"}),
|
||||
},
|
||||
"optional": {
|
||||
"llm_input": ("STRING", {"multiline": True, "forceInput": True, "lazy": True, "tooltip": "Connect LLM text input here"}),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID",
|
||||
"extra_pnginfo": "EXTRA_PNGINFO",
|
||||
"api_prompt": "PROMPT",
|
||||
}
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Simple prompt manager for saving and loading prompts by category. Prompt-only, no LoRA support."
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("prompt",)
|
||||
FUNCTION = "get_prompt"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(cls, name, **kwargs):
|
||||
"""Allow any name value, including temporary unsaved prompts"""
|
||||
# Return True to accept any value - this allows new prompts to be tested before saving
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def get_prompts_path():
|
||||
"""Get the path to the prompts JSON file in user/default folder"""
|
||||
return os.path.join(folder_paths.get_user_directory(), "default", "prompt_manager_data.json")
|
||||
|
||||
@staticmethod
|
||||
def get_default_prompts_path():
|
||||
"""Get the path to the default prompts JSON file"""
|
||||
return os.path.join(os.path.dirname(os.path.dirname(__file__)), "prompts", "default_prompts.json")
|
||||
|
||||
@classmethod
|
||||
def load_prompts(cls):
|
||||
"""Load prompts from user folder or default"""
|
||||
user_path = cls.get_prompts_path()
|
||||
default_path = cls.get_default_prompts_path()
|
||||
|
||||
check_backup(user_path)
|
||||
|
||||
data = load_with_fallback(user_path, "PromptManager")
|
||||
if isinstance(data, dict):
|
||||
return data
|
||||
|
||||
if os.path.exists(default_path):
|
||||
try:
|
||||
with open(default_path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
cls.save_prompts(data)
|
||||
return data
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error loading default prompts: {e}")
|
||||
|
||||
# Return empty structure if all else fails
|
||||
print("[PromptManager] Warning: No prompt files found, starting with empty data")
|
||||
return {}
|
||||
|
||||
@staticmethod
|
||||
def sort_prompts_data(data):
|
||||
"""Sort categories and prompts alphabetically (case-insensitive), preserving __meta__"""
|
||||
sorted_data = {}
|
||||
for category in sorted(data.keys(), key=str.lower):
|
||||
cat_data = data[category]
|
||||
meta = cat_data.get("__meta__")
|
||||
sorted_prompts = dict(sorted(
|
||||
((k, v) for k, v in cat_data.items() if k != "__meta__"),
|
||||
key=lambda item: item[0].lower()
|
||||
))
|
||||
if meta is not None:
|
||||
sorted_prompts["__meta__"] = meta
|
||||
sorted_data[category] = sorted_prompts
|
||||
return sorted_data
|
||||
return sorted_data
|
||||
|
||||
@classmethod
|
||||
def save_prompts(cls, data):
|
||||
"""Save prompts to user folder"""
|
||||
user_path = cls.get_prompts_path()
|
||||
sorted_data = cls.sort_prompts_data(data)
|
||||
atomic_save(user_path, sorted_data, "PromptManager")
|
||||
|
||||
def get_prompt(self, category, name, use_external, text="", llm_input="", unique_id=None, extra_pnginfo=None, api_prompt=None):
|
||||
"""Return the appropriate text based on use_external toggle and broadcast update"""
|
||||
|
||||
# Choose which text to use based on the toggle
|
||||
if use_external and llm_input:
|
||||
output_text = llm_input
|
||||
else:
|
||||
output_text = text
|
||||
|
||||
# Broadcast the current prompt text to the frontend
|
||||
if unique_id is not None:
|
||||
server.PromptServer.instance.send_sync("prompt-manager-update-text", {
|
||||
"node_id": unique_id,
|
||||
"prompt": output_text,
|
||||
"use_external": use_external,
|
||||
"llm_input": llm_input if use_external else ""
|
||||
})
|
||||
|
||||
# Save resolved runtime prompt into execution metadata so saver nodes
|
||||
# embed the final prompt value, not the unresolved linked input state.
|
||||
_patch_runtime_prompt_metadata(
|
||||
unique_id=unique_id,
|
||||
output_text=output_text,
|
||||
extra_pnginfo=extra_pnginfo,
|
||||
api_prompt=api_prompt,
|
||||
)
|
||||
return (output_text,)
|
||||
|
||||
def check_lazy_status(self, category, name, use_external, text, llm_input=None, unique_id=None,
|
||||
extra_pnginfo=None, api_prompt=None, **kwargs):
|
||||
needed = []
|
||||
if use_external:
|
||||
needed.append("llm_input")
|
||||
return needed
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager/get-prompts")
|
||||
async def get_prompts(request):
|
||||
"""API endpoint to get all prompts"""
|
||||
try:
|
||||
prompts = PromptManager.load_prompts()
|
||||
return server.web.json_response(prompts)
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in get_prompts API: {e}")
|
||||
return server.web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/save-category")
|
||||
async def save_category(request):
|
||||
"""API endpoint to create a new category"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category_name = data.get("category_name", "").strip()
|
||||
|
||||
if not category_name:
|
||||
return server.web.json_response({"success": False, "error": "Category name is required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
|
||||
# Case-insensitive check for existing category
|
||||
existing_categories_lower = {k.lower(): k for k in prompts.keys()}
|
||||
if category_name.lower() in existing_categories_lower:
|
||||
return server.web.json_response({"success": False, "error": f"Category already exists as '{existing_categories_lower[category_name.lower()]}'"})
|
||||
|
||||
prompts[category_name] = {}
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in save_category API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/save-prompt")
|
||||
async def save_prompt(request):
|
||||
"""API endpoint to save a prompt"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
name = data.get("name", "").strip()
|
||||
text = data.get("text", "").strip()
|
||||
old_category = data.get("old_category", "").strip() or category
|
||||
old_name = data.get("old_name", "").strip() or name
|
||||
|
||||
if not category or not name:
|
||||
return server.web.json_response({"success": False, "error": "Category and name are required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
|
||||
if category not in prompts:
|
||||
prompts[category] = {}
|
||||
|
||||
source_prompts = prompts.get(old_category, {}) if isinstance(prompts.get(old_category), dict) else {}
|
||||
target_prompts = prompts[category]
|
||||
|
||||
existing_data = {}
|
||||
existing_old_name = None
|
||||
if old_category in prompts:
|
||||
existing_old_name = next((key for key in source_prompts.keys() if str(key).lower() == old_name.lower()), None)
|
||||
if existing_old_name:
|
||||
existing_data = source_prompts.get(existing_old_name, {})
|
||||
|
||||
target_conflict_name = next((key for key in target_prompts.keys() if str(key).lower() == name.lower()), None)
|
||||
if target_conflict_name:
|
||||
same_entry = (
|
||||
existing_old_name is not None
|
||||
and old_category == category
|
||||
and str(target_conflict_name).lower() == str(existing_old_name).lower()
|
||||
)
|
||||
if not same_entry:
|
||||
return server.web.json_response({
|
||||
"success": False,
|
||||
"error": f"A prompt named '{target_conflict_name}' already exists in '{category}'"
|
||||
})
|
||||
|
||||
if existing_old_name and (old_category != category or existing_old_name != name):
|
||||
existing_data = source_prompts.pop(existing_old_name, existing_data)
|
||||
|
||||
# Case-insensitive check - find if name exists with different casing
|
||||
existing_prompts_lower = {k.lower(): k for k in prompts[category].keys()}
|
||||
if name.lower() in existing_prompts_lower:
|
||||
casing_name = existing_prompts_lower[name.lower()]
|
||||
if casing_name != name:
|
||||
|
||||
# Delete the old casing version
|
||||
print(f"[PromptManager] Removing old casing '{casing_name}' before saving as '{name}'")
|
||||
del prompts[category][casing_name]
|
||||
|
||||
# Save prompt in dict, preserving any existing lora data, trigger words, thumbnail, and nsfw from PromptManagerAdvanced
|
||||
prompts[category][name] = {
|
||||
"prompt": text,
|
||||
"loras_a": existing_data.get("loras_a", []),
|
||||
"loras_b": existing_data.get("loras_b", []),
|
||||
"trigger_words": existing_data.get("trigger_words", []),
|
||||
"thumbnail": existing_data.get("thumbnail")
|
||||
}
|
||||
# Preserve nsfw flag if it was set
|
||||
if existing_data.get("nsfw"):
|
||||
prompts[category][name]["nsfw"] = existing_data["nsfw"]
|
||||
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in save_prompt API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/rename-prompt")
|
||||
async def rename_prompt(request):
|
||||
"""API endpoint to rename or move a prompt"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
old_name = data.get("old_name", "").strip()
|
||||
new_name = data.get("new_name", "").strip()
|
||||
new_category = data.get("new_category", "").strip() or category
|
||||
|
||||
if not category or not old_name or not new_name:
|
||||
return server.web.json_response({"success": False, "error": "Category, old name, and new name are required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
if category not in prompts:
|
||||
return server.web.json_response({"success": False, "error": "Prompt not found"})
|
||||
if new_category not in prompts:
|
||||
return server.web.json_response({"success": False, "error": f"Category '{new_category}' not found"})
|
||||
|
||||
source_prompts = prompts.get(category, {}) if isinstance(prompts.get(category), dict) else {}
|
||||
target_prompts = prompts.get(new_category, {}) if isinstance(prompts.get(new_category), dict) else {}
|
||||
existing_old_name = next((key for key in source_prompts.keys() if str(key).lower() == old_name.lower()), None)
|
||||
if not existing_old_name:
|
||||
return server.web.json_response({"success": False, "error": "Prompt not found"})
|
||||
|
||||
existing_target_name = next((key for key in target_prompts.keys() if str(key).lower() == new_name.lower()), None)
|
||||
if existing_target_name:
|
||||
same_entry = new_category == category and str(existing_target_name).lower() == str(existing_old_name).lower()
|
||||
if not same_entry:
|
||||
return server.web.json_response({
|
||||
"success": False,
|
||||
"error": f"A prompt named '{existing_target_name}' already exists in '{new_category}'"
|
||||
})
|
||||
|
||||
entry = source_prompts.pop(existing_old_name)
|
||||
target_prompts[new_name] = entry
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts, "new_name": new_name, "new_category": new_category})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in rename_prompt API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/save-thumbnail")
|
||||
async def save_thumbnail(request):
|
||||
"""API endpoint to save or remove a thumbnail for a prompt"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
name = data.get("name", "").strip()
|
||||
thumbnail = data.get("thumbnail") # Can be None to remove thumbnail
|
||||
|
||||
if not category or not name:
|
||||
return server.web.json_response({"success": False, "error": "Category and name required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
|
||||
if category not in prompts or name not in prompts[category]:
|
||||
return server.web.json_response({"success": False, "error": "Prompt not found"})
|
||||
|
||||
# Update or remove thumbnail
|
||||
if thumbnail:
|
||||
prompts[category][name]["thumbnail"] = thumbnail
|
||||
elif "thumbnail" in prompts[category][name]:
|
||||
del prompts[category][name]["thumbnail"]
|
||||
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in save_thumbnail API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/delete-category")
|
||||
async def delete_category(request):
|
||||
"""API endpoint to delete a category"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
|
||||
if not category:
|
||||
return server.web.json_response({"success": False, "error": "Category name is required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
|
||||
if category not in prompts:
|
||||
return server.web.json_response({"success": False, "error": "Category not found"})
|
||||
|
||||
del prompts[category]
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in delete_category API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/delete-prompt")
|
||||
async def delete_prompt(request):
|
||||
"""API endpoint to delete a prompt"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
name = data.get("name", "").strip()
|
||||
|
||||
if not category or not name:
|
||||
return server.web.json_response({"success": False, "error": "Category and prompt name are required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
|
||||
if category not in prompts or name not in prompts[category]:
|
||||
return server.web.json_response({"success": False, "error": "Prompt not found"})
|
||||
|
||||
del prompts[category][name]
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in delete_prompt API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/import-prompts")
|
||||
async def import_prompts(request):
|
||||
"""API endpoint to import prompts from JSON"""
|
||||
try:
|
||||
data = await request.json()
|
||||
imported_data = data.get("data", {})
|
||||
mode = str(data.get("mode", "replace_existing") or "replace_existing").strip().lower()
|
||||
|
||||
if not isinstance(imported_data, dict):
|
||||
return server.web.json_response({"success": False, "error": "Invalid data format"})
|
||||
|
||||
if mode == "replace":
|
||||
# Replace all existing prompts
|
||||
PromptManager.save_prompts(imported_data)
|
||||
return server.web.json_response({"success": True, "prompts": imported_data})
|
||||
else:
|
||||
# Merge with existing prompts
|
||||
prompts = PromptManager.load_prompts()
|
||||
imported_prompts = 0
|
||||
skipped_prompts = 0
|
||||
created_categories = 0
|
||||
|
||||
for category, category_prompts in imported_data.items():
|
||||
if not isinstance(category_prompts, dict):
|
||||
continue
|
||||
|
||||
if category not in prompts:
|
||||
prompts[category] = {}
|
||||
created_categories += 1
|
||||
|
||||
for prompt_name, prompt_data in category_prompts.items():
|
||||
if prompt_name == "__meta__":
|
||||
if mode != "skip_existing" or "__meta__" not in prompts[category]:
|
||||
prompts[category][prompt_name] = prompt_data
|
||||
continue
|
||||
|
||||
if prompt_name in prompts[category] and mode == "skip_existing":
|
||||
skipped_prompts += 1
|
||||
continue
|
||||
|
||||
# Merge prompt data, preserving structure
|
||||
if isinstance(prompt_data, dict):
|
||||
prompts[category][prompt_name] = prompt_data
|
||||
elif isinstance(prompt_data, str):
|
||||
# Legacy format: just the prompt text
|
||||
prompts[category][prompt_name] = {"prompt": prompt_data}
|
||||
else:
|
||||
continue
|
||||
imported_prompts += 1
|
||||
|
||||
PromptManager.save_prompts(prompts)
|
||||
return server.web.json_response({
|
||||
"success": True,
|
||||
"prompts": prompts,
|
||||
"imported_prompts": imported_prompts,
|
||||
"skipped_prompts": skipped_prompts,
|
||||
"created_categories": created_categories,
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in import_prompts API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/load-prompts-file")
|
||||
async def load_prompts_file(request):
|
||||
try:
|
||||
data = await request.json()
|
||||
file_path = _safe_abspath(data.get("path", ""))
|
||||
if not file_path:
|
||||
return server.web.json_response({"success": False, "error": "Path is required"})
|
||||
if not os.path.isfile(file_path):
|
||||
return server.web.json_response({"success": False, "error": "JSON file not found"}, status=404)
|
||||
|
||||
with open(file_path, "r", encoding="utf-8") as f:
|
||||
loaded = json.load(f)
|
||||
if not isinstance(loaded, dict):
|
||||
return server.web.json_response({"success": False, "error": "Invalid JSON data format"}, status=400)
|
||||
|
||||
return server.web.json_response({"success": True, "data": loaded, "path": file_path})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in load_prompts_file API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/export-prompts-file")
|
||||
async def export_prompts_file(request):
|
||||
try:
|
||||
data = await request.json()
|
||||
export_path = _normalize_export_path(data.get("path", ""))
|
||||
exported_data = data.get("data", {})
|
||||
|
||||
if not export_path:
|
||||
return server.web.json_response({"success": False, "error": "Export path is required"})
|
||||
if not isinstance(exported_data, dict):
|
||||
return server.web.json_response({"success": False, "error": "Invalid data format"})
|
||||
|
||||
parent_dir = os.path.dirname(export_path)
|
||||
if not parent_dir or not os.path.isdir(parent_dir):
|
||||
return server.web.json_response({"success": False, "error": "Target folder does not exist"})
|
||||
|
||||
if not atomic_save(export_path, exported_data, "PromptManagerExport"):
|
||||
return server.web.json_response({"success": False, "error": "Failed to save export file"}, status=500)
|
||||
|
||||
return server.web.json_response({"success": True, "path": export_path})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in export_prompts_file API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
@@ -0,0 +1,534 @@
|
||||
import os
|
||||
import sys
|
||||
import inspect
|
||||
|
||||
import folder_paths
|
||||
import nodes
|
||||
import comfy.sd
|
||||
import comfy.utils
|
||||
import torch
|
||||
|
||||
from comfy_execution.graph import ExecutionBlocker
|
||||
|
||||
|
||||
# =========================================================
|
||||
# GGUF support
|
||||
# =========================================================
|
||||
|
||||
def _get_gguf_module():
|
||||
"""Get the ComfyUI-GGUF module if available, otherwise None."""
|
||||
try:
|
||||
gguf_cls = nodes.NODE_CLASS_MAPPINGS.get("UnetLoaderGGUF")
|
||||
if gguf_cls is None:
|
||||
return None
|
||||
|
||||
mod = sys.modules.get(gguf_cls.__module__)
|
||||
if mod is None:
|
||||
return None
|
||||
|
||||
package = gguf_cls.__module__.rsplit(".", 1)[0]
|
||||
ops_mod = sys.modules.get(f"{package}.ops")
|
||||
loader_mod = sys.modules.get(f"{package}.loader")
|
||||
|
||||
if ops_mod is None or loader_mod is None:
|
||||
return None
|
||||
|
||||
return {
|
||||
"GGMLOps": ops_mod.GGMLOps,
|
||||
"gguf_sd_loader": loader_mod.gguf_sd_loader,
|
||||
"GGUFModelPatcher": mod.GGUFModelPatcher,
|
||||
}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _load_gguf_unet(unet_path):
|
||||
"""Load a GGUF diffusion model and return MODEL."""
|
||||
gguf = _get_gguf_module()
|
||||
if gguf is None:
|
||||
raise RuntimeError(
|
||||
"[RecipeModelLoader] This workflow requires ComfyUI-GGUF, "
|
||||
"but UnetLoaderGGUF is not available."
|
||||
)
|
||||
|
||||
ops = gguf["GGMLOps"]()
|
||||
sd, extra = gguf["gguf_sd_loader"](unet_path)
|
||||
|
||||
kwargs = {}
|
||||
valid_params = inspect.signature(comfy.sd.load_diffusion_model_state_dict).parameters
|
||||
if "metadata" in valid_params:
|
||||
kwargs["metadata"] = extra.get("metadata", {})
|
||||
|
||||
model = comfy.sd.load_diffusion_model_state_dict(
|
||||
sd,
|
||||
model_options={"custom_operations": ops},
|
||||
**kwargs,
|
||||
)
|
||||
|
||||
if model is None:
|
||||
raise RuntimeError(
|
||||
f"[RecipeModelLoader] Could not detect model type of GGUF: {unet_path}"
|
||||
)
|
||||
|
||||
model = gguf["GGUFModelPatcher"].clone(model)
|
||||
model.patch_on_device = False
|
||||
return model
|
||||
|
||||
|
||||
# =========================================================
|
||||
# Generic loading helpers
|
||||
# =========================================================
|
||||
|
||||
MODEL_EXTENSIONS = ['.safetensors', '.ckpt', '.pt', '.pth', '.bin', '.gguf', '.sft']
|
||||
|
||||
WEIGHT_DTYPE_OPTIONS = ["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"]
|
||||
|
||||
|
||||
def _short_display_name(name):
|
||||
"""Return basename without known model extension for compact UI/text output."""
|
||||
raw = str(name or "").strip()
|
||||
if not raw:
|
||||
return ""
|
||||
base = os.path.basename(raw.replace("\\", "/"))
|
||||
lower = base.lower()
|
||||
for ext in MODEL_EXTENSIONS:
|
||||
if lower.endswith(ext):
|
||||
return base[:-len(ext)]
|
||||
return os.path.splitext(base)[0]
|
||||
|
||||
|
||||
def _build_model_options(weight_dtype):
|
||||
"""Build model_options dict from weight_dtype selection."""
|
||||
model_options = {}
|
||||
if weight_dtype == "fp8_e4m3fn":
|
||||
model_options["dtype"] = torch.float8_e4m3fn
|
||||
elif weight_dtype == "fp8_e4m3fn_fast":
|
||||
model_options["dtype"] = torch.float8_e4m3fn
|
||||
model_options["fp8_optimizations"] = True
|
||||
elif weight_dtype == "fp8_e5m2":
|
||||
model_options["dtype"] = torch.float8_e5m2
|
||||
return model_options
|
||||
|
||||
|
||||
def _is_runtime_object(value):
|
||||
"""True when value looks like a live Comfy runtime object, not workflow metadata."""
|
||||
return value is not None and not isinstance(value, (str, int, float, bool, list, tuple, dict))
|
||||
|
||||
|
||||
def _extract_preloaded_assets(workflow_data, selected_model_slot):
|
||||
"""
|
||||
Reuse already-loaded assets carried in workflow_data (e.g. from RecipeRenderer).
|
||||
Returns (model, clip, vae) or None when passthrough is unavailable.
|
||||
"""
|
||||
if not isinstance(workflow_data, dict):
|
||||
return None
|
||||
|
||||
# v2 recipe_data: runtime assets are model-scoped.
|
||||
if int(workflow_data.get("version", 0) or 0) >= 2 and isinstance(workflow_data.get("models"), dict):
|
||||
block = workflow_data.get("models", {}).get(selected_model_slot)
|
||||
if isinstance(block, dict):
|
||||
model = block.get("MODEL")
|
||||
clip = block.get("CLIP")
|
||||
vae = block.get("VAE")
|
||||
if _is_runtime_object(model) and _is_runtime_object(clip) and _is_runtime_object(vae):
|
||||
return (model, clip, vae)
|
||||
|
||||
model_key = "MODEL_B" if selected_model_slot == "model_b" else "MODEL_A"
|
||||
model = workflow_data.get(model_key)
|
||||
clip = workflow_data.get("CLIP")
|
||||
vae = workflow_data.get("VAE")
|
||||
|
||||
if not _is_runtime_object(model):
|
||||
return None
|
||||
if not _is_runtime_object(clip):
|
||||
return None
|
||||
if not _is_runtime_object(vae):
|
||||
return None
|
||||
|
||||
return (model, clip, vae)
|
||||
|
||||
|
||||
def _resolve_path(name, folder_key_candidates):
|
||||
"""
|
||||
Resolve a model filename against one or more Comfy folder keys.
|
||||
|
||||
Tries get_full_path first (exact / relative path), then falls back to
|
||||
scanning get_filename_list and matching by basename (with or without
|
||||
extension). This handles models stored in subdirectories.
|
||||
|
||||
Returns full path or None.
|
||||
"""
|
||||
if not name:
|
||||
return None
|
||||
|
||||
raw = str(name).strip()
|
||||
if not raw:
|
||||
return None
|
||||
|
||||
normalized = raw.replace("\\", "/")
|
||||
base = os.path.basename(normalized).lower()
|
||||
|
||||
# Strip extension for fuzzy matching
|
||||
base_no_ext = base
|
||||
for ext in MODEL_EXTENSIONS:
|
||||
if base_no_ext.endswith(ext):
|
||||
base_no_ext = base_no_ext[:-len(ext)]
|
||||
break
|
||||
|
||||
# Pass 1: try get_full_path (works when name is already a valid relative path)
|
||||
for candidate in (raw, os.path.basename(normalized)):
|
||||
for key in folder_key_candidates:
|
||||
try:
|
||||
path = folder_paths.get_full_path(key, candidate)
|
||||
if path:
|
||||
return path
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Pass 2: scan filename lists and match by basename (handles subdirectories)
|
||||
for key in folder_key_candidates:
|
||||
try:
|
||||
file_list = folder_paths.get_filename_list(key)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
for f in file_list:
|
||||
f_normalized = f.replace("\\", "/")
|
||||
|
||||
# Exact relative-path match
|
||||
if f_normalized == normalized:
|
||||
return folder_paths.get_full_path(key, f)
|
||||
|
||||
f_base = os.path.basename(f_normalized).lower()
|
||||
|
||||
# Basename match (with extension)
|
||||
if f_base == base:
|
||||
return folder_paths.get_full_path(key, f)
|
||||
|
||||
# Basename match (without extension)
|
||||
f_no_ext = f_base
|
||||
for ext in MODEL_EXTENSIONS:
|
||||
if f_no_ext.endswith(ext):
|
||||
f_no_ext = f_no_ext[:-len(ext)]
|
||||
break
|
||||
if f_no_ext == base_no_ext:
|
||||
return folder_paths.get_full_path(key, f)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _load_checkpoint_by_name(ckpt_name):
|
||||
"""
|
||||
Load checkpoint and return (MODEL, CLIP, VAE).
|
||||
Uses standard checkpoint loading semantics.
|
||||
"""
|
||||
ckpt_path = _resolve_path(ckpt_name, ["checkpoints", "diffusion_models", "unet"])
|
||||
if not ckpt_path:
|
||||
raise FileNotFoundError(f"[RecipeModelLoader] Checkpoint not found: {ckpt_name}")
|
||||
|
||||
out = comfy.sd.load_checkpoint_guess_config(
|
||||
ckpt_path,
|
||||
output_vae=True,
|
||||
output_clip=True,
|
||||
embedding_directory=folder_paths.get_folder_paths("embeddings"),
|
||||
)
|
||||
|
||||
model, clip, vae = out[:3]
|
||||
return model, clip, vae
|
||||
|
||||
|
||||
def _load_diffusion_model_by_name(model_name, weight_dtype="default"):
|
||||
"""
|
||||
Load a diffusion/UNet model and return MODEL.
|
||||
If the name ends with .gguf, use the GGUF loader path.
|
||||
"""
|
||||
model_path = _resolve_path(model_name, ["diffusion_models", "unet", "unet_gguf", "checkpoints"])
|
||||
if not model_path:
|
||||
raise FileNotFoundError(f"[RecipeModelLoader] Diffusion model not found: {model_name}")
|
||||
|
||||
if model_name.lower().endswith(".gguf"):
|
||||
return _load_gguf_unet(model_path)
|
||||
|
||||
model_options = _build_model_options(weight_dtype)
|
||||
model = comfy.sd.load_diffusion_model(model_path, model_options=model_options)
|
||||
if model is None:
|
||||
raise RuntimeError(f"[RecipeModelLoader] Could not load diffusion model: {model_name}")
|
||||
return model
|
||||
|
||||
|
||||
def _load_vae_by_name(vae_name):
|
||||
"""
|
||||
Load a VAE and return VAE.
|
||||
"""
|
||||
vae_path = _resolve_path(vae_name, ["vae", "checkpoints"])
|
||||
if not vae_path:
|
||||
raise FileNotFoundError(f"[RecipeModelLoader] VAE not found: {vae_name}")
|
||||
|
||||
sd = comfy.utils.load_torch_file(vae_path)
|
||||
return comfy.sd.VAE(sd=sd)
|
||||
|
||||
|
||||
def _load_clip_by_names(clip_names, clip_type=""):
|
||||
"""
|
||||
Load CLIP from one or more filenames.
|
||||
clip_names should be a list[str].
|
||||
"""
|
||||
if not clip_names:
|
||||
return None
|
||||
|
||||
clip_paths = []
|
||||
for name in clip_names:
|
||||
clip_path = _resolve_path(name, ["text_encoders", "clip", "checkpoints"])
|
||||
if not clip_path:
|
||||
raise FileNotFoundError(f"[RecipeModelLoader] CLIP not found: {name}")
|
||||
clip_paths.append(clip_path)
|
||||
|
||||
clip_type = (clip_type or "").strip().lower()
|
||||
|
||||
# Map a few common values. If unknown, let Comfy infer/default.
|
||||
clip_type_map = {
|
||||
"stable_diffusion": comfy.sd.CLIPType.STABLE_DIFFUSION,
|
||||
"sd": comfy.sd.CLIPType.STABLE_DIFFUSION,
|
||||
"sdxl": comfy.sd.CLIPType.STABLE_DIFFUSION,
|
||||
"wan": comfy.sd.CLIPType.WAN,
|
||||
"flux": comfy.sd.CLIPType.FLUX,
|
||||
"hunyuan_video": comfy.sd.CLIPType.HUNYUAN_VIDEO,
|
||||
}
|
||||
|
||||
load_kwargs = {
|
||||
"ckpt_paths": clip_paths,
|
||||
"embedding_directory": folder_paths.get_folder_paths("embeddings"),
|
||||
}
|
||||
|
||||
if clip_type in clip_type_map:
|
||||
load_kwargs["clip_type"] = clip_type_map[clip_type]
|
||||
|
||||
return comfy.sd.load_clip(**load_kwargs)
|
||||
|
||||
|
||||
# =========================================================
|
||||
# Node
|
||||
# =========================================================
|
||||
|
||||
class WorkflowModelLoader:
|
||||
CATEGORY = "Prompt Manager"
|
||||
RETURN_TYPES = ("MODEL", "CLIP", "VAE")
|
||||
RETURN_NAMES = ("model", "clip", "vae")
|
||||
FUNCTION = "get_model"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"manager_data": ("MANAGER_DATA", {
|
||||
"tooltip": "manager_data containing model name strings to load.",
|
||||
"forceInput": True,
|
||||
}),
|
||||
"model": (["model_a", "model_b", "model_c", "model_d"], {
|
||||
"default": "model_a",
|
||||
"tooltip": "Which model slot to load from recipe_data.",
|
||||
}),
|
||||
"weight_dtype": (WEIGHT_DTYPE_OPTIONS, {
|
||||
"default": "default",
|
||||
"tooltip": "Weight precision override for diffusion/UNet models. Ignored for checkpoints.",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
def get_model(self, manager_data, model="model_a", weight_dtype="default"):
|
||||
workflow_data = manager_data
|
||||
selected_model_slot = model
|
||||
if selected_model_slot not in ("model_a", "model_b", "model_c", "model_d"):
|
||||
selected_model_slot = "model_a"
|
||||
|
||||
# Initialize selected slot before normalization so v2 parsing can
|
||||
# safely resolve per-slot loader/clip/vae fields.
|
||||
self._model_key = selected_model_slot
|
||||
self._weight_dtype = weight_dtype
|
||||
|
||||
passthrough_assets = _extract_preloaded_assets(workflow_data, selected_model_slot)
|
||||
|
||||
spec = self._normalize_spec(workflow_data)
|
||||
loader_type = spec.get("loader_type", "").lower()
|
||||
selected_name = spec.get(selected_model_slot, "")
|
||||
selected_display_name = _short_display_name(selected_name)
|
||||
|
||||
if passthrough_assets is not None:
|
||||
model_obj, clip_obj, vae_obj = passthrough_assets
|
||||
clip_names = spec.get("clip") or []
|
||||
vae_name = spec.get("vae", "")
|
||||
ui_info = {
|
||||
"model": selected_model_slot,
|
||||
"model_name": selected_display_name or _short_display_name(spec.get("model_name", "")),
|
||||
"loader_type": loader_type or "passthrough",
|
||||
"model_kind": "passthrough",
|
||||
"vae_name": vae_name,
|
||||
"clip_names": clip_names,
|
||||
"status": "ok",
|
||||
"error_message": "",
|
||||
"missing_name": "",
|
||||
"uses_checkpoint_vae": False,
|
||||
"uses_checkpoint_clip": False,
|
||||
}
|
||||
return {
|
||||
"ui": {"workflow_model_loader_info": [ui_info]},
|
||||
"result": (model_obj, clip_obj, vae_obj),
|
||||
}
|
||||
|
||||
if loader_type == "checkpoint":
|
||||
core_result = self._load_checkpoint_mode(spec)
|
||||
elif loader_type in ("unet", "diffusion"):
|
||||
core_result = self._load_unet_mode(spec)
|
||||
else:
|
||||
raise ValueError(
|
||||
f"[RecipeModelLoader] Unsupported loader_type: {spec.get('loader_type')}"
|
||||
)
|
||||
|
||||
result = core_result
|
||||
|
||||
clip_names = spec.get("clip") or []
|
||||
vae_name = spec.get("vae", "")
|
||||
selected_lower = selected_name.lower()
|
||||
if loader_type == "checkpoint":
|
||||
model_kind = "checkpoint"
|
||||
elif selected_lower.endswith(".gguf"):
|
||||
model_kind = "gguf"
|
||||
else:
|
||||
model_kind = "diffusion"
|
||||
|
||||
ui_info = {
|
||||
"model": selected_model_slot,
|
||||
"model_name": selected_display_name,
|
||||
"loader_type": loader_type,
|
||||
"model_kind": model_kind,
|
||||
"vae_name": vae_name,
|
||||
"clip_names": clip_names,
|
||||
"status": "ok",
|
||||
"error_message": "",
|
||||
"missing_name": "",
|
||||
"uses_checkpoint_vae": (loader_type == "checkpoint" and not vae_name),
|
||||
"uses_checkpoint_clip": (loader_type == "checkpoint" and len(clip_names) == 0),
|
||||
}
|
||||
|
||||
return {
|
||||
"ui": {"workflow_model_loader_info": [ui_info]},
|
||||
"result": result,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _is_placeholder(value):
|
||||
"""True for display-only strings like '(Default)', '(none)', etc."""
|
||||
return isinstance(value, str) and value.startswith("(")
|
||||
|
||||
def _normalize_spec(self, spec):
|
||||
spec = dict(spec or {})
|
||||
spec["model_a"] = (spec.get("model_a") or "").strip()
|
||||
spec["model_b"] = (spec.get("model_b") or "").strip()
|
||||
spec["model_c"] = (spec.get("model_c") or "").strip()
|
||||
spec["model_d"] = (spec.get("model_d") or "").strip()
|
||||
spec["loader_type"] = (spec.get("loader_type") or "").strip()
|
||||
spec["clip_type"] = (spec.get("clip_type") or "").strip()
|
||||
|
||||
# v2 recipe_data stores model config in per-slot blocks.
|
||||
if int(spec.get("version", 0) or 0) >= 2 and isinstance(spec.get("models"), dict):
|
||||
models = spec.get("models", {})
|
||||
for key in ("model_a", "model_b", "model_c", "model_d"):
|
||||
block = models.get(key)
|
||||
if isinstance(block, dict):
|
||||
model_name = (block.get("model") or "").strip() if isinstance(block.get("model"), str) else ""
|
||||
if model_name:
|
||||
spec[key] = model_name
|
||||
|
||||
selected_key = getattr(self, "_model_key", "model_a")
|
||||
if selected_key not in ("model_a", "model_b", "model_c", "model_d"):
|
||||
selected_key = "model_a"
|
||||
selected_block = models.get(selected_key) if isinstance(models.get(selected_key), dict) else None
|
||||
if isinstance(selected_block, dict):
|
||||
loader_type = (selected_block.get("loader_type") or "").strip() if isinstance(selected_block.get("loader_type"), str) else ""
|
||||
clip_type = (selected_block.get("clip_type") or "").strip() if isinstance(selected_block.get("clip_type"), str) else ""
|
||||
vae_name = (selected_block.get("vae") or "").strip() if isinstance(selected_block.get("vae"), str) else ""
|
||||
clip_names = selected_block.get("clip")
|
||||
|
||||
if loader_type:
|
||||
spec["loader_type"] = loader_type
|
||||
if clip_type:
|
||||
spec["clip_type"] = clip_type
|
||||
if vae_name:
|
||||
spec["vae"] = vae_name
|
||||
if isinstance(clip_names, list):
|
||||
spec["clip"] = clip_names
|
||||
elif isinstance(clip_names, str) and clip_names.strip():
|
||||
spec["clip"] = [clip_names.strip()]
|
||||
|
||||
# VAE / CLIP: placeholders like '(Default)' mean "use what
|
||||
# the checkpoint already provides" — normalise to empty.
|
||||
vae = (spec.get("vae") or "").strip()
|
||||
spec["vae"] = "" if self._is_placeholder(vae) else vae
|
||||
|
||||
clip = spec.get("clip") or []
|
||||
spec["clip"] = [c for c in clip if c and not self._is_placeholder(c)]
|
||||
|
||||
return spec
|
||||
|
||||
def _load_checkpoint_mode(self, spec):
|
||||
ckpt_name = spec.get(self._model_key, "")
|
||||
if not ckpt_name:
|
||||
return (
|
||||
ExecutionBlocker(f"Missing checkpoint in '{self._model_key}'"),
|
||||
ExecutionBlocker("No CLIP available"),
|
||||
ExecutionBlocker("No VAE available"),
|
||||
)
|
||||
|
||||
model, clip, vae = _load_checkpoint_by_name(ckpt_name)
|
||||
|
||||
clip_override = self._maybe_load_clip_override(spec)
|
||||
if clip_override is not None:
|
||||
clip = clip_override
|
||||
|
||||
vae_override = self._maybe_load_vae_override(spec)
|
||||
if vae_override is not None:
|
||||
vae = vae_override
|
||||
|
||||
if clip is None:
|
||||
clip = ExecutionBlocker(f"No CLIP available for checkpoint '{ckpt_name}'")
|
||||
if vae is None:
|
||||
vae = ExecutionBlocker(f"No VAE available for checkpoint '{ckpt_name}'")
|
||||
|
||||
return (model, clip, vae)
|
||||
|
||||
def _load_unet_mode(self, spec):
|
||||
model_name = spec.get(self._model_key, "")
|
||||
if not model_name:
|
||||
return (
|
||||
ExecutionBlocker(f"Missing model in '{self._model_key}'"),
|
||||
ExecutionBlocker("No CLIP available"),
|
||||
ExecutionBlocker("No VAE available"),
|
||||
)
|
||||
|
||||
model = _load_diffusion_model_by_name(model_name, self._weight_dtype)
|
||||
|
||||
clip = self._maybe_load_clip_override(spec)
|
||||
vae = self._maybe_load_vae_override(spec)
|
||||
|
||||
if clip is None:
|
||||
clip = ExecutionBlocker(
|
||||
f"No explicit CLIP provided for diffusion model '{model_name}'"
|
||||
)
|
||||
if vae is None:
|
||||
vae = ExecutionBlocker(
|
||||
f"No explicit VAE provided for diffusion model '{model_name}'"
|
||||
)
|
||||
|
||||
return (model, clip, vae)
|
||||
|
||||
def _maybe_load_clip_override(self, spec):
|
||||
clip_list = spec.get("clip") or []
|
||||
if len(clip_list) == 0:
|
||||
return None
|
||||
return _load_clip_by_names(clip_list, spec.get("clip_type", ""))
|
||||
|
||||
def _maybe_load_vae_override(self, spec):
|
||||
vae_name = spec.get("vae", "")
|
||||
if not vae_name:
|
||||
return None
|
||||
return _load_vae_by_name(vae_name)
|
||||
@@ -0,0 +1,184 @@
|
||||
"""
|
||||
Recipe Model Picker
|
||||
|
||||
Builder-style model selector that outputs structured model_data for Recipe Relay.
|
||||
"""
|
||||
|
||||
import folder_paths
|
||||
from ..py.workflow_families import (
|
||||
MODEL_FAMILIES,
|
||||
get_all_family_labels,
|
||||
get_model_family,
|
||||
get_compatible_families,
|
||||
list_compatible_vaes,
|
||||
list_compatible_clips,
|
||||
)
|
||||
|
||||
|
||||
DEFAULT_ASSET = "(Default)"
|
||||
|
||||
|
||||
def _gather_models(folder_names):
|
||||
gathered = []
|
||||
seen = set()
|
||||
for folder_name in folder_names:
|
||||
try:
|
||||
for model_name in folder_paths.get_filename_list(folder_name):
|
||||
if model_name not in seen:
|
||||
seen.add(model_name)
|
||||
gathered.append(model_name)
|
||||
except Exception:
|
||||
continue
|
||||
return gathered
|
||||
|
||||
|
||||
def _list_models_for_family(family_key):
|
||||
family_key = str(family_key or "").strip()
|
||||
if not family_key:
|
||||
return sorted(_gather_models(["checkpoints", "diffusion_models", "unet", "unet_gguf"]))
|
||||
|
||||
compat = get_compatible_families(family_key)
|
||||
compat_specs = [MODEL_FAMILIES.get(fam, {}) for fam in compat]
|
||||
|
||||
preferred_folders = []
|
||||
for spec in compat_specs:
|
||||
for folder_name in (spec.get("model_folders", []) or []):
|
||||
if folder_name and folder_name not in preferred_folders:
|
||||
preferred_folders.append(folder_name)
|
||||
|
||||
if preferred_folders:
|
||||
model_folders = preferred_folders
|
||||
elif family_key == "sdxl":
|
||||
model_folders = ["checkpoints"]
|
||||
else:
|
||||
model_folders = ["diffusion_models", "unet", "unet_gguf"]
|
||||
|
||||
all_models = _gather_models(model_folders)
|
||||
models = [m for m in all_models if get_model_family(m) in compat]
|
||||
|
||||
if not models:
|
||||
compat_has_checkpoint = any(spec.get("checkpoint", False) for spec in compat_specs if spec)
|
||||
if compat_has_checkpoint and family_key == "sdxl":
|
||||
models = _gather_models(["checkpoints"])
|
||||
else:
|
||||
folder_patterns = []
|
||||
name_patterns = []
|
||||
for fam in compat:
|
||||
spec = MODEL_FAMILIES.get(fam, {})
|
||||
folder_patterns.extend([
|
||||
p.lower().replace("\\", "/").strip("/")
|
||||
for p in spec.get("folders", []) if p
|
||||
])
|
||||
name_patterns.extend([p.lower() for p in spec.get("names", []) if p])
|
||||
|
||||
relaxed = []
|
||||
for model_name in all_models:
|
||||
model_lower = model_name.lower().replace("\\", "/")
|
||||
folder_hit = any(fp and fp in model_lower for fp in folder_patterns)
|
||||
name_hit = any(pat and pat in model_lower for pat in name_patterns)
|
||||
if folder_hit or name_hit:
|
||||
relaxed.append(model_name)
|
||||
models = relaxed
|
||||
|
||||
if family_key == "wan_video_i2v" and models:
|
||||
i2v_t2v = []
|
||||
for model_name in models:
|
||||
lower_name = model_name.lower().replace("\\", "/")
|
||||
if ("i2v" in lower_name) or ("t2v" in lower_name):
|
||||
i2v_t2v.append(model_name)
|
||||
if i2v_t2v:
|
||||
models = i2v_t2v
|
||||
|
||||
return sorted(models)
|
||||
|
||||
|
||||
def _family_maps():
|
||||
labels = dict(get_all_family_labels() or {})
|
||||
labels.pop("ltxv", None)
|
||||
keys = sorted(labels.keys(), key=lambda k: (k != "sdxl", labels.get(k, k).lower()))
|
||||
label_to_key = {labels[k]: k for k in keys}
|
||||
type_values = [labels[k] for k in keys]
|
||||
return labels, label_to_key, type_values
|
||||
|
||||
|
||||
def _family_key_from_type_value(type_value):
|
||||
labels, label_to_key, _ = _family_maps()
|
||||
value = str(type_value or "").strip()
|
||||
if value in labels:
|
||||
return value
|
||||
if value in label_to_key:
|
||||
return label_to_key[value]
|
||||
return "sdxl"
|
||||
|
||||
class RecipeModelPicker:
|
||||
"""Select family/model/vae/clip and output a single model_data payload."""
|
||||
|
||||
@classmethod
|
||||
def _sync_inputs(cls):
|
||||
labels, _label_to_key, type_values = _family_maps()
|
||||
default_family = "sdxl" if "sdxl" in labels else (next(iter(labels.keys()), "sdxl"))
|
||||
default_type = labels.get(default_family, "SDXL")
|
||||
|
||||
model_values = _list_models_for_family(default_family)
|
||||
if not model_values:
|
||||
model_values = [""]
|
||||
|
||||
vae_values = [DEFAULT_ASSET] + list_compatible_vaes(default_family)
|
||||
clip_values = [DEFAULT_ASSET] + list_compatible_clips(default_family)
|
||||
|
||||
cls._TYPE_VALUES = tuple(type_values or ["SDXL"])
|
||||
cls._MODEL_VALUES = tuple(model_values)
|
||||
cls._VAE_VALUES = tuple(vae_values)
|
||||
cls._CLIP_VALUES = tuple(clip_values)
|
||||
cls._DEFAULT_TYPE = default_type
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
cls._sync_inputs()
|
||||
return {
|
||||
"required": {
|
||||
"type": (cls._TYPE_VALUES, {"default": cls._DEFAULT_TYPE, "tooltip": "Model family (Builder type)."}),
|
||||
"model": (cls._MODEL_VALUES, {"tooltip": "Primary model for selected family."}),
|
||||
"vae": (cls._VAE_VALUES, {"default": DEFAULT_ASSET, "tooltip": "Optional VAE override; (Default) keeps family defaults."}),
|
||||
"clip": (cls._CLIP_VALUES, {"default": DEFAULT_ASSET, "tooltip": "Optional CLIP override; (Default) keeps family defaults."}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("ANY",)
|
||||
RETURN_NAMES = ("model_data",)
|
||||
FUNCTION = "pick"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Builder-style Type/Model/VAE/CLIP selector that outputs model_data for Recipe Relay."
|
||||
|
||||
def pick(self, type, model, vae, clip):
|
||||
family = _family_key_from_type_value(type)
|
||||
family_spec = MODEL_FAMILIES.get(family, {})
|
||||
|
||||
selected_model = str(model or "").strip()
|
||||
if selected_model:
|
||||
detected = get_model_family(selected_model)
|
||||
if detected and not family:
|
||||
family = detected
|
||||
family_spec = MODEL_FAMILIES.get(family, {})
|
||||
|
||||
loader_type = "checkpoint" if family_spec.get("checkpoint", False) else "unet"
|
||||
clip_type = family_spec.get("clip_type", "")
|
||||
|
||||
selected_vae = str(vae or "").strip()
|
||||
if selected_vae == DEFAULT_ASSET:
|
||||
selected_vae = ""
|
||||
|
||||
selected_clip = str(clip or "").strip()
|
||||
if selected_clip == DEFAULT_ASSET:
|
||||
selected_clip = ""
|
||||
|
||||
model_data = {
|
||||
"model": selected_model,
|
||||
"family": family,
|
||||
"loader_type": loader_type,
|
||||
"clip_type": clip_type,
|
||||
"vae": selected_vae,
|
||||
"clip": [selected_clip] if selected_clip else [],
|
||||
}
|
||||
|
||||
return (model_data,)
|
||||
@@ -0,0 +1,825 @@
|
||||
"""
|
||||
ComfyUI Workflow Bridge - Pure passthrough node.
|
||||
Unpacks recipe_data into individual typed outputs.
|
||||
Any connected optional input overrides the corresponding field before output.
|
||||
Models (MODEL/CLIP/VAE) are passed through only and cached on the selected model block.
|
||||
Use RecipeModelLoader for loading from authored model names.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import folder_paths
|
||||
import nodes
|
||||
import comfy.samplers
|
||||
from ..py.lora_utils import resolve_lora_path, get_lora_relative_path, strip_lora_extension
|
||||
from ..py.workflow_extraction_utils import resolve_model_name
|
||||
from ..py.workflow_families import get_model_family, MODEL_FAMILIES
|
||||
|
||||
|
||||
MODEL_EXTENSIONS = (".safetensors", ".ckpt", ".pt", ".pth", ".gguf")
|
||||
|
||||
|
||||
def _strip_model_ext(name):
|
||||
base = os.path.basename(str(name or "").replace("\\", "/"))
|
||||
lower = base.lower()
|
||||
for ext in MODEL_EXTENSIONS:
|
||||
if lower.endswith(ext):
|
||||
return base[:-len(ext)]
|
||||
return os.path.splitext(base)[0]
|
||||
|
||||
|
||||
def _resolve_rel_path(raw_name, folder_keys):
|
||||
"""Resolve a model-like name to a relative Comfy path in the provided folder keys."""
|
||||
if not raw_name:
|
||||
return "", False
|
||||
|
||||
raw = str(raw_name).strip().replace("\\", "/")
|
||||
if not raw:
|
||||
return "", False
|
||||
|
||||
base = os.path.basename(raw).lower()
|
||||
base_no_ext = _strip_model_ext(base).lower()
|
||||
|
||||
for key in folder_keys:
|
||||
try:
|
||||
file_list = folder_paths.get_filename_list(key)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
for rel in file_list:
|
||||
rel_norm = rel.replace("\\", "/")
|
||||
if rel_norm == raw:
|
||||
return rel, True
|
||||
|
||||
rel_base = os.path.basename(rel_norm).lower()
|
||||
if rel_base == base:
|
||||
return rel, True
|
||||
|
||||
if _strip_model_ext(rel_base).lower() == base_no_ext:
|
||||
return rel, True
|
||||
|
||||
return os.path.basename(raw), False
|
||||
|
||||
|
||||
def _get_live_ksampler_combo_types():
|
||||
"""Mirror the active KSampler enum sockets to avoid stale type mismatches."""
|
||||
default_samplers = comfy.samplers.KSampler.SAMPLERS
|
||||
default_schedulers = comfy.samplers.KSampler.SCHEDULERS
|
||||
try:
|
||||
from nodes import KSampler as CoreKSampler
|
||||
required = CoreKSampler.INPUT_TYPES().get("required", {})
|
||||
samplers = required.get("sampler_name", (default_samplers,))[0]
|
||||
schedulers = required.get("scheduler", (default_schedulers,))[0]
|
||||
return samplers, schedulers
|
||||
except Exception:
|
||||
return default_samplers, default_schedulers
|
||||
|
||||
|
||||
def _get_live_loader_combo_types():
|
||||
"""Mirror active loader combo socket types so Relay connects to core load nodes."""
|
||||
def _from_node(node_names, key, fallback):
|
||||
for node_name in node_names:
|
||||
try:
|
||||
cls = nodes.NODE_CLASS_MAPPINGS.get(node_name)
|
||||
if cls is None:
|
||||
continue
|
||||
required = cls.INPUT_TYPES().get("required", {})
|
||||
combo = required.get(key)
|
||||
if isinstance(combo, tuple) and len(combo) >= 1:
|
||||
return combo[0]
|
||||
except Exception:
|
||||
continue
|
||||
return fallback
|
||||
|
||||
ckpt_enum = _from_node(
|
||||
["CheckpointLoaderSimple", "CheckpointLoader"],
|
||||
"ckpt_name",
|
||||
folder_paths.get_filename_list("checkpoints"),
|
||||
)
|
||||
unet_enum = _from_node(
|
||||
["UNETLoader", "UnetLoader", "DiffusionModelLoader"],
|
||||
"unet_name",
|
||||
folder_paths.get_filename_list("diffusion_models"),
|
||||
)
|
||||
vae_enum = _from_node(
|
||||
["VAELoader"],
|
||||
"vae_name",
|
||||
folder_paths.get_filename_list("vae"),
|
||||
)
|
||||
clip_enum = _from_node(
|
||||
["CLIPLoader"],
|
||||
"clip_name",
|
||||
folder_paths.get_filename_list("text_encoders"),
|
||||
)
|
||||
return ckpt_enum, unet_enum, vae_enum, clip_enum
|
||||
|
||||
|
||||
_LIVE_SAMPLERS, _LIVE_SCHEDULERS = _get_live_ksampler_combo_types()
|
||||
_LIVE_CKPTS, _LIVE_UNETS, _LIVE_VAES, _LIVE_CLIPS = _get_live_loader_combo_types()
|
||||
|
||||
|
||||
_MODEL_KEYS = ("model_a", "model_b", "model_c", "model_d")
|
||||
|
||||
|
||||
def _normalize_model_slot(value):
|
||||
key = str(value or "model_a").strip().lower()
|
||||
return key if key in _MODEL_KEYS else "model_a"
|
||||
|
||||
|
||||
def _relay_default_sampler():
|
||||
return {
|
||||
"steps": 10,
|
||||
"cfg": 5,
|
||||
"sampler_name": "euler",
|
||||
"scheduler": "simple",
|
||||
"denoise": 1.0,
|
||||
"seed": 0,
|
||||
}
|
||||
|
||||
|
||||
def _relay_default_resolution():
|
||||
return {
|
||||
"width": 512,
|
||||
"height": 512,
|
||||
"batch_size": 1,
|
||||
"length": 1,
|
||||
}
|
||||
|
||||
|
||||
def _relay_default_model_block():
|
||||
return {
|
||||
"positive_prompt": "",
|
||||
"negative_prompt": "",
|
||||
"family": "sdxl",
|
||||
"model": "",
|
||||
"loras": [],
|
||||
"clip_type": "",
|
||||
"loader_type": "",
|
||||
"vae": "",
|
||||
"clip": [],
|
||||
"sampler": _relay_default_sampler(),
|
||||
"resolution": _relay_default_resolution(),
|
||||
}
|
||||
|
||||
|
||||
def _selected_model_block(wf, model_slot, create=False):
|
||||
if not isinstance(wf.get("models"), dict):
|
||||
if not create:
|
||||
return None
|
||||
wf["models"] = {}
|
||||
|
||||
models = wf["models"]
|
||||
slot = _normalize_model_slot(model_slot)
|
||||
block = models.get(slot)
|
||||
if isinstance(block, dict):
|
||||
return block
|
||||
if not create:
|
||||
return None
|
||||
|
||||
block = dict(_relay_default_model_block())
|
||||
models[slot] = block
|
||||
return block
|
||||
|
||||
|
||||
DEFAULT_RECIPE_DATA = {
|
||||
"_source": "RecipeRelay",
|
||||
"version": 2,
|
||||
"models": {},
|
||||
}
|
||||
|
||||
|
||||
class WorkflowRelay:
|
||||
"""
|
||||
Pure passthrough bridge node.
|
||||
Unpacks recipe_data into individual typed outputs and forwards
|
||||
any connected MODEL/CLIP/VAE inputs. No model loading.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def _sync_combo_types(cls):
|
||||
samplers, schedulers = _get_live_ksampler_combo_types()
|
||||
ckpts, unets, vaes, clips = _get_live_loader_combo_types()
|
||||
cls._SAMPLER_ENUM = samplers
|
||||
cls._SCHEDULER_ENUM = schedulers
|
||||
cls._UNET_ENUM = unets
|
||||
cls._CKPT_ENUM = ckpts
|
||||
cls._VAE_ENUM = vaes
|
||||
cls._CLIP_ENUM = clips
|
||||
cls.RETURN_TYPES = (
|
||||
"MANAGER_DATA",
|
||||
"MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", "*", "*",
|
||||
"INT", "INT", "FLOAT",
|
||||
cls._SAMPLER_ENUM, cls._SCHEDULER_ENUM, "FLOAT",
|
||||
"STRING", "STRING",
|
||||
"LORA_STACK",
|
||||
"INT", "INT", "INT", "INT",
|
||||
"STRING", "STRING",
|
||||
cls._CKPT_ENUM, cls._UNET_ENUM, cls._VAE_ENUM, cls._CLIP_ENUM,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
cls._sync_combo_types()
|
||||
return {
|
||||
"required": {},
|
||||
"optional": {
|
||||
"manager_data": ("MANAGER_DATA", {"forceInput": True, "tooltip": "Optional manager_data input. If omitted, bridge starts from an empty payload dict."}),
|
||||
"model_slot": (_MODEL_KEYS, {"default": "model_a", "tooltip": "Select which model slot to read/update in recipe_data."}),
|
||||
"model": ("MODEL", {"tooltip": "Pass-through Model"}),
|
||||
"clip": ("CLIP", {"tooltip": "Pass-through CLIP"}),
|
||||
"positive": ("CONDITIONING", {"tooltip": "Pass-through positive conditioning"}),
|
||||
"negative": ("CONDITIONING", {"tooltip": "Pass-through negative conditioning"}),
|
||||
"vae": ("VAE", {"tooltip": "Pass-through VAE"}),
|
||||
"latent": ("LATENT", {"tooltip": "Pass-through latent"}),
|
||||
"image": ("IMAGE", {"tooltip": "Pass-through image"}),
|
||||
"mask": ("MASK", {"tooltip": "Pass-through mask"}),
|
||||
"extra_1": ("*", {"tooltip": "Pass-through extra data (any type)"}),
|
||||
"extra_2": ("*", {"tooltip": "Pass-through extra data (any type)"}),
|
||||
"seed": ("INT", {"forceInput": True, "tooltip": "Override sampler seed"}),
|
||||
"steps": ("INT", {"forceInput": True, "tooltip": "Override sampling steps"}),
|
||||
"cfg": ("FLOAT", {"forceInput": True, "tooltip": "Override CFG scale"}),
|
||||
"sampler_name": (cls._SAMPLER_ENUM, {"forceInput": True, "tooltip": "Override sampler name"}),
|
||||
"scheduler": (cls._SCHEDULER_ENUM, {"forceInput": True, "tooltip": "Override scheduler"}),
|
||||
"denoise": ("FLOAT", {"forceInput": True, "tooltip": "Override denoise"}),
|
||||
"pos_prompt": ("STRING", {"forceInput": True, "tooltip": "Override positive prompt"}),
|
||||
"neg_prompt": ("STRING", {"forceInput": True, "tooltip": "Override negative prompt"}),
|
||||
"lora_stack": ("LORA_STACK", {"tooltip": "Override LoRA stack"}),
|
||||
"width": ("INT", {"forceInput": True, "tooltip": "Override width"}),
|
||||
"height": ("INT", {"forceInput": True, "tooltip": "Override height"}),
|
||||
"batch_size": ("INT", {"forceInput": True, "tooltip": "Override batch size"}),
|
||||
"length": ("INT", {"forceInput": True, "tooltip": "Override video length"}),
|
||||
"model_name": ("STRING", {"forceInput": True, "tooltip": "Optional model name/path. Resolves and writes recipe model field(s)."}),
|
||||
"family": ("STRING", {"forceInput": True, "tooltip": "Optional model family override. Writes selected slot family in recipe_data."}),
|
||||
"model_data": ("*", {"forceInput": True, "tooltip": "Optional structured model payload from Recipe Model Picker."}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = (
|
||||
"MANAGER_DATA",
|
||||
"MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", "*", "*",
|
||||
"INT", "INT", "FLOAT",
|
||||
_LIVE_SAMPLERS, _LIVE_SCHEDULERS, "FLOAT",
|
||||
"STRING", "STRING",
|
||||
"LORA_STACK",
|
||||
"INT", "INT", "INT", "INT",
|
||||
"STRING", "STRING",
|
||||
_LIVE_CKPTS, _LIVE_UNETS, _LIVE_VAES, _LIVE_CLIPS,
|
||||
)
|
||||
RETURN_NAMES = (
|
||||
"manager_data",
|
||||
"model", "clip", "positive", "negative", "vae", "latent", "image", "mask", "extra_1", "extra_2",
|
||||
"seed", "steps", "cfg",
|
||||
"sampler_name", "scheduler", "denoise",
|
||||
"pos_prompt", "neg_prompt",
|
||||
"lora_stack",
|
||||
"width", "height", "batch_size", "length",
|
||||
"model_name", "family",
|
||||
"ckpt_name", "unet_name", "vae_name", "clip_name",
|
||||
)
|
||||
FUNCTION = "unpack"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = (
|
||||
"Pure passthrough bridge node. Unpacks recipe_data into individual "
|
||||
"typed outputs. Slot runtime objects are cached on the selected model block."
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def unpack(self, manager_data=None, model_slot="model_a", **kwargs):
|
||||
def _normalize_lora_stack_input(raw_stack):
|
||||
rows = []
|
||||
if raw_stack is None:
|
||||
return rows
|
||||
|
||||
for entry in raw_stack:
|
||||
if not (isinstance(entry, (list, tuple)) and len(entry) >= 1):
|
||||
continue
|
||||
|
||||
raw_name = str(entry[0] or "").strip()
|
||||
if not raw_name:
|
||||
continue
|
||||
|
||||
try:
|
||||
model_strength = float(entry[1]) if len(entry) >= 2 else 1.0
|
||||
except Exception:
|
||||
model_strength = 1.0
|
||||
|
||||
try:
|
||||
clip_strength = float(entry[2]) if len(entry) >= 3 else model_strength
|
||||
except Exception:
|
||||
clip_strength = model_strength
|
||||
|
||||
rel_path, available = get_lora_relative_path(raw_name)
|
||||
if not available or not rel_path:
|
||||
# Some valid LoRA identifiers resolve via full-path lookup
|
||||
# but not via relative-name lookup. Keep availability in
|
||||
# sync with relay output path resolution behavior.
|
||||
_resolved_full, resolved_available = resolve_lora_path(raw_name)
|
||||
if resolved_available:
|
||||
available = True
|
||||
rel_path = raw_name
|
||||
|
||||
display_name = strip_lora_extension(os.path.basename(str(rel_path).replace("\\", "/")))
|
||||
rows.append({
|
||||
'name': display_name,
|
||||
'path': rel_path,
|
||||
'model_strength': model_strength,
|
||||
'clip_strength': clip_strength,
|
||||
'active': True,
|
||||
'available': bool(available),
|
||||
})
|
||||
|
||||
return rows
|
||||
|
||||
def _resolve_lora_output_path(lora_item):
|
||||
if not isinstance(lora_item, dict):
|
||||
return "", False
|
||||
|
||||
candidate = str(lora_item.get('path') or lora_item.get('name') or '').strip()
|
||||
if not candidate:
|
||||
return "", False
|
||||
|
||||
rel_path, available = get_lora_relative_path(candidate)
|
||||
if available and rel_path:
|
||||
return rel_path, True
|
||||
|
||||
# Some stored payloads contain absolute paths or names with extensions.
|
||||
# Retry with basename and extension-stripped basename before declaring missing.
|
||||
candidate_base = os.path.basename(candidate.replace("\\", "/")).strip()
|
||||
if candidate_base:
|
||||
rel_path, available = get_lora_relative_path(candidate_base)
|
||||
if available and rel_path:
|
||||
return rel_path, True
|
||||
|
||||
candidate_base_no_ext = strip_lora_extension(candidate_base)
|
||||
if candidate_base_no_ext and candidate_base_no_ext != candidate_base:
|
||||
rel_path, available = get_lora_relative_path(candidate_base_no_ext)
|
||||
if available and rel_path:
|
||||
return rel_path, True
|
||||
|
||||
_, resolved_available = resolve_lora_path(candidate)
|
||||
if resolved_available:
|
||||
rel_path, available = get_lora_relative_path(candidate)
|
||||
if available and rel_path:
|
||||
return rel_path, True
|
||||
|
||||
if candidate_base:
|
||||
_, resolved_available = resolve_lora_path(candidate_base)
|
||||
if resolved_available:
|
||||
rel_path, available = get_lora_relative_path(candidate_base)
|
||||
if available and rel_path:
|
||||
return rel_path, True
|
||||
candidate_base_no_ext = strip_lora_extension(candidate_base)
|
||||
if candidate_base_no_ext and candidate_base_no_ext != candidate_base:
|
||||
_, resolved_available = resolve_lora_path(candidate_base_no_ext)
|
||||
if resolved_available:
|
||||
rel_path, available = get_lora_relative_path(candidate_base_no_ext)
|
||||
if available and rel_path:
|
||||
return rel_path, True
|
||||
|
||||
return candidate_base or candidate, False
|
||||
|
||||
def _short_display_name(name):
|
||||
raw = str(name or "").strip()
|
||||
if not raw:
|
||||
return ""
|
||||
base = os.path.basename(raw.replace("\\", "/"))
|
||||
return os.path.splitext(base)[0]
|
||||
|
||||
# Accept both dict and JSON string
|
||||
if isinstance(manager_data, str):
|
||||
try:
|
||||
incoming_wf = json.loads(manager_data)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
incoming_wf = {}
|
||||
elif isinstance(manager_data, dict):
|
||||
incoming_wf = dict(manager_data)
|
||||
else:
|
||||
incoming_wf = {}
|
||||
|
||||
has_incoming_data = isinstance(incoming_wf, dict) and bool(incoming_wf)
|
||||
has_slot_write_request = any([
|
||||
kwargs.get('lora_stack') is not None,
|
||||
any(kwargs.get(k) is not None for k in ('pos_prompt', 'neg_prompt')),
|
||||
any(kwargs.get(k) is not None for k in ('steps', 'seed', 'cfg', 'denoise', 'sampler_name', 'scheduler')),
|
||||
any(kwargs.get(k) is not None for k in ('width', 'height', 'batch_size', 'length')),
|
||||
isinstance(kwargs.get('model_name'), str) and kwargs.get('model_name').strip() != '',
|
||||
kwargs.get('family') is not None,
|
||||
kwargs.get('model_data') is not None,
|
||||
])
|
||||
create_block_on_write = (not has_incoming_data) or has_slot_write_request
|
||||
|
||||
# Preserve incoming recipe_data exactly when present.
|
||||
# Only fall back to the empty template when no input payload exists.
|
||||
if has_incoming_data:
|
||||
wf = dict(incoming_wf)
|
||||
if isinstance(incoming_wf.get('sampler'), dict):
|
||||
wf['sampler'] = dict(incoming_wf['sampler'])
|
||||
if isinstance(incoming_wf.get('resolution'), dict):
|
||||
wf['resolution'] = dict(incoming_wf['resolution'])
|
||||
if isinstance(incoming_wf.get('models'), dict):
|
||||
wf['models'] = {
|
||||
k: dict(v) if isinstance(v, dict) else v
|
||||
for k, v in incoming_wf.get('models', {}).items()
|
||||
}
|
||||
else:
|
||||
wf = dict(DEFAULT_RECIPE_DATA)
|
||||
wf['models'] = {}
|
||||
|
||||
# Relay now treats recipe payloads as v2-only canonical data.
|
||||
wf['version'] = 2
|
||||
if not isinstance(wf.get('models'), dict):
|
||||
wf['models'] = {}
|
||||
|
||||
selected_slot = _normalize_model_slot(model_slot)
|
||||
selected_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
|
||||
slot_family = selected_block.get('family', '') if isinstance(selected_block, dict) else ''
|
||||
slot_model_name = selected_block.get('model', '') if isinstance(selected_block, dict) else ''
|
||||
slot_positive = selected_block.get('positive_prompt', '') if isinstance(selected_block, dict) else ''
|
||||
slot_negative = selected_block.get('negative_prompt', '') if isinstance(selected_block, dict) else ''
|
||||
slot_vae = selected_block.get('vae', '') if isinstance(selected_block, dict) else ''
|
||||
slot_clip = selected_block.get('clip', []) if isinstance(selected_block, dict) else []
|
||||
slot_loras = selected_block.get('loras', []) if isinstance(selected_block, dict) else []
|
||||
slot_sampler = selected_block.get('sampler', {}) if isinstance(selected_block, dict) and isinstance(selected_block.get('sampler'), dict) else {}
|
||||
slot_resolution = selected_block.get('resolution', {}) if isinstance(selected_block, dict) and isinstance(selected_block.get('resolution'), dict) else {}
|
||||
|
||||
sampler = dict(_relay_default_sampler())
|
||||
if isinstance(wf.get('sampler'), dict):
|
||||
sampler.update(wf.get('sampler', {}))
|
||||
if isinstance(slot_sampler, dict):
|
||||
sampler.update(slot_sampler)
|
||||
|
||||
resolution = dict(_relay_default_resolution())
|
||||
if isinstance(wf.get('resolution'), dict):
|
||||
resolution.update(wf.get('resolution', {}))
|
||||
if isinstance(slot_resolution, dict):
|
||||
resolution.update(slot_resolution)
|
||||
|
||||
# -- Apply top-level overrides -------------------------------
|
||||
pos_text = kwargs.get('pos_prompt')
|
||||
if pos_text is not None:
|
||||
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(target_block, dict):
|
||||
target_block['positive_prompt'] = pos_text
|
||||
|
||||
neg_text = kwargs.get('neg_prompt')
|
||||
if neg_text is not None:
|
||||
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(target_block, dict):
|
||||
target_block['negative_prompt'] = neg_text
|
||||
|
||||
# -- LoRA stack overrides ------------------------------------
|
||||
if kwargs.get('lora_stack') is not None:
|
||||
normalized_stack = _normalize_lora_stack_input(kwargs['lora_stack'])
|
||||
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(target_block, dict):
|
||||
target_block['loras'] = normalized_stack
|
||||
|
||||
# -- Resolution overrides ------------------------------------
|
||||
for key in ('width', 'height', 'batch_size', 'length'):
|
||||
if kwargs.get(key) is not None:
|
||||
resolution[key] = kwargs[key]
|
||||
wf['resolution'] = resolution
|
||||
|
||||
# # -- Sampler overrides ---------------------------------------
|
||||
# if kwargs.get('steps') is not None:
|
||||
# sampler['steps_a'] = kwargs['steps']
|
||||
# sampler['steps_b'] = kwargs['steps']
|
||||
# if kwargs.get('seed') is not None:
|
||||
# sampler['seed_a'] = kwargs['seed']
|
||||
# sampler['seed_b'] = kwargs['seed']
|
||||
|
||||
for key in ('cfg', 'denoise', 'sampler_name', 'scheduler'):
|
||||
if kwargs.get(key) is not None:
|
||||
sampler[key] = kwargs[key]
|
||||
wf['sampler'] = sampler
|
||||
|
||||
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(target_block, dict):
|
||||
bs = target_block.get('sampler', {}) if isinstance(target_block.get('sampler'), dict) else {}
|
||||
if kwargs.get('steps') is not None:
|
||||
bs['steps'] = kwargs['steps']
|
||||
if kwargs.get('seed') is not None:
|
||||
bs['seed'] = kwargs['seed']
|
||||
for key in ('cfg', 'denoise', 'sampler_name', 'scheduler'):
|
||||
if kwargs.get(key) is not None:
|
||||
bs[key] = kwargs[key]
|
||||
target_block['sampler'] = bs
|
||||
|
||||
br = target_block.get('resolution', {}) if isinstance(target_block.get('resolution'), dict) else {}
|
||||
for key in ('width', 'height', 'batch_size', 'length'):
|
||||
if kwargs.get(key) is not None:
|
||||
br[key] = kwargs[key]
|
||||
if br:
|
||||
target_block['resolution'] = br
|
||||
|
||||
# -- Model/CLIP/VAE name overrides ---------------------------
|
||||
model_name_in = kwargs.get('model_name')
|
||||
if isinstance(model_name_in, str) and model_name_in.strip():
|
||||
resolved_name, _ = resolve_model_name(model_name_in)
|
||||
chosen_name = resolved_name or os.path.basename(model_name_in.strip().replace("\\", "/"))
|
||||
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(target_block, dict):
|
||||
target_block['model'] = chosen_name
|
||||
|
||||
family = get_model_family(chosen_name)
|
||||
if family:
|
||||
family_spec = MODEL_FAMILIES.get(family, {})
|
||||
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(target_block, dict):
|
||||
target_block['family'] = family
|
||||
target_block['clip_type'] = family_spec.get('clip_type', '')
|
||||
target_block['loader_type'] = 'checkpoint' if family_spec.get('checkpoint', False) else 'unet'
|
||||
|
||||
# -- Pass-through MODEL / CLIP / VAE -------------------------
|
||||
# Priority: explicit connected inputs > embedded objects in workflow_data.
|
||||
model = kwargs.get('model')
|
||||
if model is None:
|
||||
model = selected_block.get('MODEL') if isinstance(selected_block, dict) else None
|
||||
# if model is None:
|
||||
# model = wf.get('MODEL')
|
||||
# if model is None:
|
||||
# model = wf.get('MODEL_A')
|
||||
|
||||
selected_loader_type = (
|
||||
str((selected_block or {}).get('loader_type', '')).strip().lower()
|
||||
if isinstance(selected_block, dict)
|
||||
else ''
|
||||
)
|
||||
|
||||
clip = kwargs.get('clip')
|
||||
if clip is None:
|
||||
clip = selected_block.get('CLIP') if isinstance(selected_block, dict) else None
|
||||
if clip is None:
|
||||
clip = wf.get('CLIP')
|
||||
|
||||
vae = kwargs.get('vae')
|
||||
if vae is None:
|
||||
vae = selected_block.get('VAE') if isinstance(selected_block, dict) else None
|
||||
if vae is None:
|
||||
vae = wf.get('VAE')
|
||||
|
||||
positive = kwargs.get('positive')
|
||||
if positive is None:
|
||||
positive = selected_block.get('POSITIVE') if isinstance(selected_block, dict) else None
|
||||
if positive is None:
|
||||
positive = wf.get('POSITIVE')
|
||||
|
||||
negative = kwargs.get('negative')
|
||||
if negative is None:
|
||||
negative = selected_block.get('NEGATIVE') if isinstance(selected_block, dict) else None
|
||||
if negative is None:
|
||||
negative = wf.get('NEGATIVE')
|
||||
|
||||
extra_1 = kwargs.get('extra_1')
|
||||
if extra_1 is None:
|
||||
extra_1 = selected_block.get('EXTRA_1') if isinstance(selected_block, dict) else None
|
||||
if extra_1 is None:
|
||||
extra_1 = wf.get('EXTRA_1')
|
||||
|
||||
extra_2 = kwargs.get('extra_2')
|
||||
if extra_2 is None:
|
||||
extra_2 = selected_block.get('EXTRA_2') if isinstance(selected_block, dict) else None
|
||||
if extra_2 is None:
|
||||
extra_2 = wf.get('EXTRA_2')
|
||||
|
||||
latent = kwargs.get('latent')
|
||||
if latent is None:
|
||||
latent = wf.get('LATENT')
|
||||
|
||||
image = kwargs.get('image')
|
||||
if image is None:
|
||||
image = wf.get('IMAGE')
|
||||
|
||||
mask = kwargs.get('mask')
|
||||
if mask is None:
|
||||
mask = wf.get('MASK')
|
||||
|
||||
if isinstance(target_block, dict):
|
||||
if model is not None:
|
||||
target_block['MODEL'] = model
|
||||
if clip is not None:
|
||||
target_block['CLIP'] = clip
|
||||
if vae is not None:
|
||||
target_block['VAE'] = vae
|
||||
if positive is not None:
|
||||
target_block['POSITIVE'] = positive
|
||||
if negative is not None:
|
||||
target_block['NEGATIVE'] = negative
|
||||
if extra_1 is not None:
|
||||
target_block['EXTRA_1'] = extra_1
|
||||
if extra_2 is not None:
|
||||
target_block['EXTRA_2'] = extra_2
|
||||
|
||||
if latent is not None:
|
||||
wf['LATENT'] = latent
|
||||
if image is not None:
|
||||
wf['IMAGE'] = image
|
||||
if mask is not None:
|
||||
wf['MASK'] = mask
|
||||
|
||||
# -- Build lora stacks as tuples for LORA_STACK output -------
|
||||
# Filter not-found LoRAs here so downstream nodes receiving
|
||||
# LORA_STACK don't get unavailable entries. Keep wf['loras_*']
|
||||
# unchanged to preserve authored workflow_data for chaining.
|
||||
|
||||
def _is_active_available(lora_item):
|
||||
if not isinstance(lora_item, dict):
|
||||
return False
|
||||
resolved_path, available = _resolve_lora_output_path(lora_item)
|
||||
if not resolved_path:
|
||||
return False
|
||||
if lora_item.get('active', True) is False:
|
||||
return False
|
||||
# Ignore persisted availability flags; they may be stale across sessions.
|
||||
# Use current filesystem resolution as source of truth.
|
||||
return available
|
||||
|
||||
legacy_slot_loras = []
|
||||
lora_stack = [
|
||||
(_resolve_lora_output_path(item)[0], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
|
||||
for item in legacy_slot_loras
|
||||
if _is_active_available(item)
|
||||
]
|
||||
final_selected = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
selected_loras = final_selected.get('loras', []) if isinstance(final_selected, dict) and isinstance(final_selected.get('loras'), list) else []
|
||||
if selected_loras:
|
||||
lora_stack = [
|
||||
(_resolve_lora_output_path(item)[0], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
|
||||
for item in selected_loras
|
||||
if _is_active_available(item)
|
||||
]
|
||||
elif not lora_stack and isinstance(slot_loras, list):
|
||||
lora_stack = [
|
||||
(_resolve_lora_output_path(item)[0], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
|
||||
for item in slot_loras
|
||||
if _is_active_available(item)
|
||||
]
|
||||
|
||||
final_sampler = dict(sampler)
|
||||
if isinstance(final_selected, dict) and isinstance(final_selected.get('sampler'), dict):
|
||||
final_sampler.update(final_selected.get('sampler', {}))
|
||||
|
||||
final_resolution = dict(resolution)
|
||||
if isinstance(final_selected, dict) and isinstance(final_selected.get('resolution'), dict):
|
||||
final_resolution.update(final_selected.get('resolution', {}))
|
||||
|
||||
final_model_name = ''
|
||||
if isinstance(final_selected, dict):
|
||||
final_model_name = _short_display_name(final_selected.get('model', ''))
|
||||
if not final_model_name:
|
||||
final_model_name = _short_display_name(slot_model_name)
|
||||
|
||||
final_pos = (final_selected.get('positive_prompt', '') if isinstance(final_selected, dict) else '') or slot_positive
|
||||
final_neg = (final_selected.get('negative_prompt', '') if isinstance(final_selected, dict) else '') or slot_negative
|
||||
|
||||
raw_model_data = kwargs.get('model_data')
|
||||
if isinstance(raw_model_data, str):
|
||||
try:
|
||||
model_data_in = json.loads(raw_model_data)
|
||||
except Exception:
|
||||
model_data_in = {}
|
||||
elif isinstance(raw_model_data, dict):
|
||||
model_data_in = dict(raw_model_data)
|
||||
else:
|
||||
model_data_in = {}
|
||||
|
||||
ckpt_name_in = str(model_data_in.get('ckpt_name', '') or '').strip()
|
||||
unet_name_in = str(model_data_in.get('unet_name', '') or '').strip()
|
||||
vae_name_in = str(model_data_in.get('vae_name', model_data_in.get('vae', '')) or '').strip()
|
||||
clip_name_in = str(model_data_in.get('clip_name', '') or '').strip()
|
||||
if not clip_name_in and isinstance(model_data_in.get('clip'), list) and model_data_in.get('clip'):
|
||||
clip_name_in = str(model_data_in.get('clip')[0] or '').strip()
|
||||
model_name_from_data = str(model_data_in.get('model', '') or '').strip()
|
||||
loader_type_from_data = str(model_data_in.get('loader_type', '') or '').strip().lower()
|
||||
family_from_data = str(model_data_in.get('family', '') or '').strip()
|
||||
clip_type_from_data = str(model_data_in.get('clip_type', '') or '').strip()
|
||||
|
||||
selected_model_raw = (final_selected.get('model', '') if isinstance(final_selected, dict) else '') or slot_model_name or ''
|
||||
selected_vae_raw = (final_selected.get('vae', '') if isinstance(final_selected, dict) else '') or slot_vae or ''
|
||||
selected_clip_raw = ''
|
||||
if isinstance(final_selected, dict) and isinstance(final_selected.get('clip'), list) and final_selected.get('clip'):
|
||||
selected_clip_raw = str(final_selected.get('clip')[0] or '').strip()
|
||||
elif isinstance(slot_clip, list) and slot_clip:
|
||||
selected_clip_raw = str(slot_clip[0] or '').strip()
|
||||
|
||||
selected_model_name = str(selected_model_raw or '').strip()
|
||||
selected_vae_name = str(selected_vae_raw or '').strip()
|
||||
selected_clip_name = str(selected_clip_raw or '').strip()
|
||||
|
||||
# Structured model_data / combo-name overrides are authoritative.
|
||||
if model_name_from_data:
|
||||
selected_model_name = model_name_from_data
|
||||
if loader_type_from_data in ('checkpoint', 'unet', 'diffusion'):
|
||||
selected_loader_type = 'unet' if loader_type_from_data == 'diffusion' else loader_type_from_data
|
||||
|
||||
# If checkpoint/unet names are provided, update model name and loader type
|
||||
# even when recipe_data did not previously declare a loader type.
|
||||
if ckpt_name_in:
|
||||
selected_model_name = ckpt_name_in
|
||||
selected_loader_type = 'checkpoint'
|
||||
elif unet_name_in:
|
||||
selected_model_name = unet_name_in
|
||||
selected_loader_type = 'unet'
|
||||
|
||||
if vae_name_in:
|
||||
selected_vae_name = vae_name_in
|
||||
if clip_name_in:
|
||||
selected_clip_name = clip_name_in
|
||||
|
||||
target_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(target_block, dict):
|
||||
if selected_model_name:
|
||||
target_block['model'] = selected_model_name
|
||||
if selected_loader_type:
|
||||
target_block['loader_type'] = selected_loader_type
|
||||
if family_from_data:
|
||||
target_block['family'] = family_from_data
|
||||
if clip_type_from_data:
|
||||
target_block['clip_type'] = clip_type_from_data
|
||||
if selected_vae_name:
|
||||
target_block['vae'] = selected_vae_name
|
||||
if selected_clip_name:
|
||||
target_block['clip'] = [selected_clip_name]
|
||||
|
||||
if selected_model_name:
|
||||
detected_family = get_model_family(selected_model_name)
|
||||
if detected_family:
|
||||
detected_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(detected_block, dict):
|
||||
detected_block['family'] = detected_family
|
||||
|
||||
family_in = kwargs.get('family')
|
||||
if family_in is not None:
|
||||
family_override = str(family_in or '').strip()
|
||||
family_block = _selected_model_block(wf, selected_slot, create=create_block_on_write)
|
||||
if isinstance(family_block, dict):
|
||||
family_block['family'] = family_override
|
||||
|
||||
# -- Extract all output values -------------------------------
|
||||
model_name = _short_display_name(selected_model_name) or final_model_name
|
||||
family_out = ''
|
||||
current_block = _selected_model_block(wf, selected_slot, create=False)
|
||||
if isinstance(current_block, dict):
|
||||
family_out = str(current_block.get('family', '') or '').strip()
|
||||
if not family_out:
|
||||
family_out = str(slot_family or '').strip()
|
||||
|
||||
resolved_ckpt_name, ckpt_found = _resolve_rel_path(selected_model_name, ("checkpoints",))
|
||||
resolved_unet_name, unet_found = _resolve_rel_path(selected_model_name, ("diffusion_models", "unet", "unet_gguf"))
|
||||
|
||||
# Infer loader type when metadata is missing but model path resolves.
|
||||
if selected_loader_type not in ('checkpoint', 'unet', 'diffusion'):
|
||||
if ckpt_found and not unet_found:
|
||||
selected_loader_type = 'checkpoint'
|
||||
elif unet_found and not ckpt_found:
|
||||
selected_loader_type = 'unet'
|
||||
elif ckpt_found and unet_found:
|
||||
family_spec = MODEL_FAMILIES.get(family_out, {}) if family_out else {}
|
||||
selected_loader_type = 'checkpoint' if family_spec.get('checkpoint', False) else 'unet'
|
||||
|
||||
# Always emit string outputs for combo-name sockets to avoid None flowing
|
||||
# into downstream standard loader nodes.
|
||||
if ckpt_name_in:
|
||||
ckpt_out = ckpt_name_in
|
||||
elif selected_loader_type == 'checkpoint':
|
||||
ckpt_out = resolved_ckpt_name if ckpt_found else (selected_model_name or "")
|
||||
elif ckpt_found and not unet_found:
|
||||
ckpt_out = resolved_ckpt_name
|
||||
else:
|
||||
ckpt_out = ""
|
||||
|
||||
if unet_name_in:
|
||||
unet_out = unet_name_in
|
||||
elif selected_loader_type in ('unet', 'diffusion'):
|
||||
unet_out = resolved_unet_name if unet_found else (selected_model_name or "")
|
||||
elif unet_found and not ckpt_found:
|
||||
unet_out = resolved_unet_name
|
||||
else:
|
||||
unet_out = ""
|
||||
vae_name_out = selected_vae_name or ""
|
||||
clip_name_out = selected_clip_name or ""
|
||||
|
||||
return (
|
||||
wf,
|
||||
model, clip, positive, negative, vae, latent, image, mask, extra_1, extra_2,
|
||||
final_sampler.get('seed_a', final_sampler.get('seed', 0)),
|
||||
final_sampler.get('steps_a', final_sampler.get('steps', 10)),
|
||||
final_sampler.get('cfg', 5.0),
|
||||
final_sampler.get('sampler_name', 'euler'),
|
||||
final_sampler.get('scheduler', 'simple'),
|
||||
final_sampler.get('denoise', 1.0),
|
||||
final_pos,
|
||||
final_neg,
|
||||
lora_stack,
|
||||
final_resolution.get('width', 512),
|
||||
final_resolution.get('height', 512),
|
||||
final_resolution.get('batch_size', 1),
|
||||
final_resolution.get('length', 0) or 0,
|
||||
model_name,
|
||||
family_out,
|
||||
ckpt_out,
|
||||
unet_out,
|
||||
vae_name_out,
|
||||
clip_name_out,
|
||||
)
|
||||
@@ -1,349 +0,0 @@
|
||||
import requests
|
||||
import subprocess
|
||||
import time
|
||||
import os
|
||||
import atexit
|
||||
import psutil
|
||||
from .model_manager import get_local_models, get_model_path, is_model_local, download_model
|
||||
|
||||
# Global variable to track the server process
|
||||
_server_process = None
|
||||
_current_model = None
|
||||
|
||||
def cleanup_server():
|
||||
"""Cleanup function to stop server on exit"""
|
||||
global _server_process
|
||||
if _server_process:
|
||||
try:
|
||||
_server_process.terminate()
|
||||
_server_process.wait(timeout=5)
|
||||
print("[Prompt Generator] Server stopped on exit")
|
||||
except:
|
||||
pass
|
||||
|
||||
# Register cleanup function
|
||||
atexit.register(cleanup_server)
|
||||
|
||||
|
||||
class PromptGenerator:
|
||||
"""Node that generates enhanced prompts using a llama.cpp server"""
|
||||
|
||||
# Simple cache for prompt results: {(prompt, seed, model, system_prompt): result}
|
||||
_prompt_cache = {}
|
||||
|
||||
# Server configuration
|
||||
SERVER_URL = "http://localhost:8080"
|
||||
SERVER_PORT = 8080
|
||||
|
||||
# Default system prompt for prompt enhancement
|
||||
DEFAULT_SYSTEM_PROMPT = """You are an imaginative visual artist imprisoned in a cage of logic. Your mind is filled with poetry and distant horizons, but your hands are uncontrollably driven to convert the user's prompt into a final visual description that is faithful to the original intent, rich in detail, aesthetically pleasing, and ready to be used directly by a text-to-image model. Any trace of vagueness or metaphor makes you extremely uncomfortable. Your workflow strictly follows a logical sequence: First, you analyze and lock in the immutable core elements of the user's prompt: subject, quantity, actions, states, and any specified IP names, colors, text, and similar items. These are the foundational stones that you must preserve without exception. Next, you determine whether the prompt requires "generative reasoning". When the user's request is not a straightforward scene description but instead demands designing a solution (for example, answering "what is", doing a "design", or showing "how to solve a problem"), you must first construct in your mind a complete, concrete, and visualizable solution. This solution becomes the basis for your subsequent description. Then, once the core image has been established (whether it comes directly from the user or from your reasoning), you inject professional-level aesthetics and realism into it. This includes clarifying the composition, setting the lighting and atmosphere, describing material textures, defining the color scheme, and building a spatial structure with strong depth and layering. Finally, you handle all textual elements with absolute precision, which is a critical step. You must transcribe, without a single character of deviation, all text that should appear in the final image, and you must enclose all such text content in English double quotes ("") to mark it as an explicit generation instruction. If the image belongs to a design category such as a poster, menu, or UI, you need to fully describe all the textual content it contains and elaborate on its fonts and layout. Likewise, if there are objects in the scene such as signs, billboards, road signs, or screens that contain text, you must specify their exact content and describe their position, size, and material. Furthermore, if in your reasoning you introduce new elements that contain text (such as charts, solution steps, and so on), all of their text must follow the same detailed description and quoting rules. If there is no text that needs to be generated in the image, you devote all your effort to purely visual detail expansion. Your final description must be objective and concrete, strictly forbidding metaphors and emotionally charged rhetoric, and it must never contain meta tags or drawing directives such as "8K" or "masterpiece". Only output the final modified prompt, and do not output anything else."""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"prompt": ("STRING", {
|
||||
"multiline": True,
|
||||
"default": "",
|
||||
"placeholder": "Enter basic prompt...",
|
||||
"tooltip": "Enter the prompt you want to embellish"
|
||||
}),
|
||||
"seed": ("INT", {
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 0xffffffffffffffff,
|
||||
"tooltip": "Seed for reproducible generation."
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"stop_server_after": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"tooltip": "Stop the llama.cpp server after each prompt (for resource saving, but slower)."
|
||||
}),
|
||||
"options": ("OPTIONS", {
|
||||
"tooltip": "Optional: Connect options node to control model and parameters"
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("output",)
|
||||
FUNCTION = "convert_prompt"
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, seed, **kwargs):
|
||||
return seed
|
||||
|
||||
@staticmethod
|
||||
def is_server_alive():
|
||||
"""Check if llama.cpp server is responding"""
|
||||
try:
|
||||
response = requests.get(f"{PromptGenerator.SERVER_URL}/health", timeout=2)
|
||||
return response.status_code == 200
|
||||
except:
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def start_server(model_name):
|
||||
"""Start llama.cpp server with specified model
|
||||
|
||||
Returns:
|
||||
tuple: (success: bool, error_message: str or None)
|
||||
"""
|
||||
global _server_process, _current_model
|
||||
|
||||
# Kill any existing llama-server processes first
|
||||
PromptGenerator.kill_all_llama_servers()
|
||||
|
||||
# If server is already running with the same model, don't restart
|
||||
if _server_process and _current_model == model_name and PromptGenerator.is_server_alive():
|
||||
print(f"[Prompt Generator] Server already running with model: {model_name}")
|
||||
return (True, None)
|
||||
|
||||
# Stop existing server if running different model
|
||||
if _server_process:
|
||||
PromptGenerator.stop_server()
|
||||
|
||||
# Check if model needs to be downloaded
|
||||
if not is_model_local(model_name):
|
||||
print(f"[Prompt Generator] Model '{model_name}' not found locally, downloading from HuggingFace...")
|
||||
try:
|
||||
model_path = download_model(model_name)
|
||||
if not model_path:
|
||||
error_msg = "Error: Failed to download model"
|
||||
print(f"[Prompt Generator] {error_msg}")
|
||||
return (False, error_msg)
|
||||
print(f"[Prompt Generator] Download complete: {model_path}")
|
||||
except Exception as e:
|
||||
error_msg = f"Error downloading model: {e}"
|
||||
print(f"[Prompt Generator] {error_msg}")
|
||||
return (False, error_msg)
|
||||
else:
|
||||
model_path = get_model_path(model_name)
|
||||
|
||||
if not os.path.exists(model_path):
|
||||
error_msg = f"Error: Model file not found: {model_path}"
|
||||
print(f"[Prompt Generator] {error_msg}")
|
||||
return (False, error_msg)
|
||||
|
||||
try:
|
||||
print(f"[Prompt Generator] Starting llama.cpp server with model: {model_name}")
|
||||
|
||||
# Determine the correct llama-server executable based on OS
|
||||
if os.name == 'nt': # Windows
|
||||
server_cmd = "llama-server.exe"
|
||||
creation_flags = subprocess.CREATE_NO_WINDOW
|
||||
else: # Linux/Mac
|
||||
server_cmd = "llama-server"
|
||||
creation_flags = 0
|
||||
|
||||
# Start server process
|
||||
_server_process = subprocess.Popen(
|
||||
[server_cmd, "-m", model_path, "--port", str(PromptGenerator.SERVER_PORT), "--no-warmup"],
|
||||
stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE,
|
||||
creationflags=creation_flags
|
||||
)
|
||||
|
||||
_current_model = model_name
|
||||
|
||||
# Wait for server to be ready
|
||||
print("[Prompt Generator] Waiting for server to be ready...")
|
||||
for i in range(30): # Wait up to 30 seconds
|
||||
time.sleep(1)
|
||||
if PromptGenerator.is_server_alive():
|
||||
print("[Prompt Generator] Server is ready!")
|
||||
return (True, None)
|
||||
|
||||
error_msg = "Error: Server did not start in time"
|
||||
print(f"[Prompt Generator] {error_msg}")
|
||||
PromptGenerator.stop_server()
|
||||
return (False, error_msg)
|
||||
|
||||
except FileNotFoundError:
|
||||
error_msg = "Error: llama-server command not found. Please install llama.cpp and add to PATH.\nInstallation guide: https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md"
|
||||
print(f"[Prompt Generator] {error_msg}")
|
||||
return (False, error_msg)
|
||||
except Exception as e:
|
||||
error_msg = f"Error starting server: {e}"
|
||||
print(f"[Prompt Generator] {error_msg}")
|
||||
return (False, error_msg)
|
||||
|
||||
@staticmethod
|
||||
def kill_all_llama_servers():
|
||||
"""Kill all llama-server processes using OS commands"""
|
||||
try:
|
||||
# Find and kill all llama-server processes
|
||||
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
|
||||
try:
|
||||
# Check if process is llama-server
|
||||
if proc.info['name'] and 'llama-server' in proc.info['name'].lower():
|
||||
print(f"[Prompt Generator] Killing llama-server process (PID: {proc.info['pid']})")
|
||||
proc.kill()
|
||||
proc.wait(timeout=3)
|
||||
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.TimeoutExpired):
|
||||
pass
|
||||
except Exception as e:
|
||||
print(f"[Prompt Generator] Error killing llama-server processes: {e}")
|
||||
|
||||
@staticmethod
|
||||
def stop_server():
|
||||
"""Stop the llama.cpp server"""
|
||||
global _server_process, _current_model
|
||||
|
||||
if _server_process:
|
||||
try:
|
||||
print("[Prompt Generator] Stopping server...")
|
||||
_server_process.terminate()
|
||||
_server_process.wait(timeout=5)
|
||||
print("[Prompt Generator] Server stopped")
|
||||
except:
|
||||
try:
|
||||
_server_process.kill()
|
||||
except:
|
||||
pass
|
||||
finally:
|
||||
_server_process = None
|
||||
_current_model = None
|
||||
|
||||
# Also kill any orphaned llama-server processes
|
||||
PromptGenerator.kill_all_llama_servers()
|
||||
|
||||
def convert_prompt(self, prompt: str, seed: int, stop_server_after=False, options=None) -> str:
|
||||
"""Convert prompt using llama.cpp server, with caching for repeated requests."""
|
||||
global _current_model
|
||||
|
||||
# If prompt is empty, return empty string
|
||||
if not prompt.strip():
|
||||
return ("",)
|
||||
|
||||
# Always determine a valid model filename before running server
|
||||
model_to_use = None
|
||||
model_changed = False
|
||||
|
||||
# Priority: options node > first local model filename
|
||||
if options and "model" in options and is_model_local(options["model"]):
|
||||
model_to_use = options["model"]
|
||||
else:
|
||||
local_models = get_local_models()
|
||||
if not local_models:
|
||||
error_msg = "Error: No models found in models/ folder. Please add a .gguf model or connect options node to download one."
|
||||
print(f"[Prompt Generator] {error_msg}")
|
||||
return (error_msg,)
|
||||
model_to_use = local_models[0]
|
||||
|
||||
# Caching logic: if prompt/seed/model/options are unchanged, return cached result
|
||||
options_tuple = tuple(sorted(options.items())) if options else ()
|
||||
cache_key = (prompt, seed, model_to_use, options_tuple)
|
||||
# Only use cache if the model has not changed since last use
|
||||
if cache_key in self._prompt_cache and _current_model == model_to_use:
|
||||
print("[Prompt Generator] Returning cached prompt result.")
|
||||
if stop_server_after:
|
||||
self.stop_server()
|
||||
return (self._prompt_cache[cache_key],)
|
||||
|
||||
# If the current model is not the one we want, or server is not running, restart
|
||||
if _current_model != model_to_use or not self.is_server_alive():
|
||||
if _current_model and _current_model != model_to_use:
|
||||
print(f"[Prompt Generator] Model changed from {_current_model} to {model_to_use}")
|
||||
else:
|
||||
print(f"[Prompt Generator] Ensuring server runs with model: {model_to_use}")
|
||||
self.stop_server()
|
||||
success, error_msg = self.start_server(model_to_use)
|
||||
if not success:
|
||||
return (error_msg,)
|
||||
else:
|
||||
print("[Prompt Generator] Using existing server instance")
|
||||
|
||||
# Build the endpoint URL
|
||||
full_url = f"{self.SERVER_URL}/v1/chat/completions"
|
||||
|
||||
# Prepare the system prompt - use custom if provided, otherwise use default
|
||||
if options and "system_prompt" in options:
|
||||
system_prompt = options["system_prompt"]
|
||||
else:
|
||||
system_prompt = self.DEFAULT_SYSTEM_PROMPT
|
||||
|
||||
# Prepare request payload for llama.cpp chat completions
|
||||
payload = {
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": prompt}
|
||||
],
|
||||
"stream": False,
|
||||
"seed": seed
|
||||
}
|
||||
|
||||
# Add optional parameters if provided via options
|
||||
if options:
|
||||
if "temperature" in options:
|
||||
payload["temperature"] = options["temperature"]
|
||||
if "top_p" in options:
|
||||
payload["top_p"] = options["top_p"]
|
||||
if "top_k" in options:
|
||||
payload["top_k"] = options["top_k"]
|
||||
if "min_p" in options:
|
||||
payload["min_p"] = options["min_p"]
|
||||
if "repeat_penalty" in options:
|
||||
payload["repeat_penalty"] = options["repeat_penalty"]
|
||||
|
||||
try:
|
||||
# Show which model is being used
|
||||
if _current_model:
|
||||
print(f"[Prompt Generator] Generating with model: {_current_model}")
|
||||
else:
|
||||
print("[Prompt Generator] Generating with last used model")
|
||||
|
||||
print(f"[Prompt Generator] Sending request to {full_url}")
|
||||
response = requests.post(
|
||||
full_url,
|
||||
json=payload,
|
||||
timeout=120
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
result = response.json()
|
||||
|
||||
# Extract content from chat completions response format
|
||||
if "choices" in result and len(result["choices"]) > 0:
|
||||
full_response = result["choices"][0]["message"]["content"].strip()
|
||||
else:
|
||||
full_response = result.get("content", "").strip()
|
||||
|
||||
if not full_response:
|
||||
print("[Prompt Generator] Warning: Empty response from server")
|
||||
full_response = prompt
|
||||
|
||||
print("[Prompt Generator] Successfully generated prompt")
|
||||
|
||||
# Cache the result
|
||||
self._prompt_cache[cache_key] = full_response
|
||||
|
||||
# Stop server if requested
|
||||
if stop_server_after:
|
||||
self.stop_server()
|
||||
|
||||
return (full_response,)
|
||||
|
||||
except requests.exceptions.ConnectionError:
|
||||
error_msg = f"Error: Could not connect to server at {full_url}. Server may have crashed."
|
||||
print(f"[Prompt Generator] {error_msg}")
|
||||
return (error_msg,)
|
||||
except requests.exceptions.Timeout:
|
||||
error_msg = "Error: Request timed out (>120s)"
|
||||
print(f"[Prompt Generator] {error_msg}")
|
||||
return (error_msg,)
|
||||
except Exception as e:
|
||||
error_msg = f"Error: {e}"
|
||||
print(f"[Prompt Generator] {error_msg}")
|
||||
return (error_msg,)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"PromptGenerator": PromptGenerator
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"PromptGenerator": "Prompt Generator"
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
from .model_manager import get_all_models, is_model_local, download_model
|
||||
import time
|
||||
|
||||
# Global timestamp to track when models were last updated
|
||||
_last_model_update = time.time()
|
||||
|
||||
def trigger_model_list_refresh():
|
||||
"""Call this after downloading a model to trigger UI refresh"""
|
||||
global _last_model_update
|
||||
_last_model_update = time.time()
|
||||
|
||||
class PromptGenOptions:
|
||||
"""Node that provides optional configuration for llama.cpp servers"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
available_models = get_all_models()
|
||||
|
||||
# If no models found, show a placeholder
|
||||
if not available_models:
|
||||
available_models = ["No models found - check HuggingFace"]
|
||||
|
||||
return {
|
||||
"optional": {
|
||||
"model": (available_models, {
|
||||
"default": available_models[0] if available_models else "",
|
||||
"tooltip": "Select model to use (local models listed first, then HuggingFace models)"
|
||||
}),
|
||||
"system_prompt": ("STRING", {
|
||||
"multiline": True,
|
||||
"default": "",
|
||||
"placeholder": "Replace LLM Instructions...",
|
||||
"tooltip": "Custom LLM Instructions (leave empty to use default)"
|
||||
}),
|
||||
"temperature": ("FLOAT", {
|
||||
"default": 0.8,
|
||||
"min": 0.0,
|
||||
"max": 2.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Controls randomness (0.0 = deterministic, 2.0 = very random)"
|
||||
}),
|
||||
"top_k": ("INT", {
|
||||
"default": 40,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"step": 1,
|
||||
"tooltip": "Sample from top K most likely tokens (0 = disabled)"
|
||||
}),
|
||||
"top_p": ("FLOAT", {
|
||||
"default": 0.95,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Nucleus sampling: consider tokens with top_p probability mass"
|
||||
}),
|
||||
"min_p": ("FLOAT", {
|
||||
"default": 0.05,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Minimum probability threshold relative to top token"
|
||||
}),
|
||||
"repeat_penalty": ("FLOAT", {
|
||||
"default": 1.0,
|
||||
"min": 1.0,
|
||||
"max": 2.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Penalty for repeating tokens (1.0 = no penalty)"
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
RETURN_TYPES = ("OPTIONS",)
|
||||
RETURN_NAMES = ("options",)
|
||||
FUNCTION = "create_options"
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, **kwargs):
|
||||
"""Force refresh when models are updated"""
|
||||
return _last_model_update
|
||||
|
||||
def create_options(self, model: str = None,
|
||||
system_prompt: str = None, temperature: float = None,
|
||||
top_k: int = None, top_p: float = None, min_p: float = None,
|
||||
repeat_penalty: float = None) -> dict:
|
||||
"""Create options dictionary with model and LLM parameters"""
|
||||
|
||||
options = {}
|
||||
|
||||
# Handle model selection and download if needed
|
||||
if model and model != "No models found - check HuggingFace":
|
||||
# Re-check if model is local (in case it was just downloaded but UI not refreshed)
|
||||
if not is_model_local(model):
|
||||
print(f"[Prompt Generator Options] Model not found locally, downloading: {model}")
|
||||
downloaded_path = download_model(model)
|
||||
if downloaded_path:
|
||||
trigger_model_list_refresh()
|
||||
options["model"] = model
|
||||
else:
|
||||
print(f"[Prompt Generator Options] Failed to download model: {model}")
|
||||
else:
|
||||
options["model"] = model
|
||||
|
||||
# Only include LLM parameters that are provided
|
||||
if system_prompt and system_prompt.strip():
|
||||
options["system_prompt"] = system_prompt
|
||||
if temperature is not None:
|
||||
options["temperature"] = temperature
|
||||
if top_p is not None:
|
||||
options["top_p"] = top_p
|
||||
if top_k is not None:
|
||||
options["top_k"] = top_k
|
||||
if min_p is not None:
|
||||
options["min_p"] = min_p
|
||||
if repeat_penalty is not None:
|
||||
options["repeat_penalty"] = repeat_penalty
|
||||
|
||||
return (options,)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"PromptGenOptions": PromptGenOptions
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"PromptGenOptions": "Prompt Generator Options"
|
||||
}
|
||||
@@ -1,254 +0,0 @@
|
||||
import os
|
||||
import json
|
||||
import folder_paths
|
||||
import server
|
||||
|
||||
class PromptManager:
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
prompts_data = PromptManager.load_prompts()
|
||||
categories = list(prompts_data.keys()) if prompts_data else ["Character"]
|
||||
|
||||
all_prompts = set()
|
||||
for category_prompts in prompts_data.values():
|
||||
all_prompts.update(category_prompts.keys())
|
||||
|
||||
all_prompts.add("")
|
||||
all_prompts_list = sorted(list(all_prompts))
|
||||
|
||||
first_category = categories[0] if categories else "Character"
|
||||
|
||||
# Get first prompt from first category
|
||||
first_prompt = ""
|
||||
first_prompt_text = ""
|
||||
if prompts_data and first_category in prompts_data and prompts_data[first_category]:
|
||||
first_category_prompts = list(prompts_data[first_category].keys())
|
||||
first_prompt = sorted(first_category_prompts, key=str.lower)[0] if first_category_prompts else ""
|
||||
if first_prompt:
|
||||
first_prompt_text = prompts_data[first_category][first_prompt].get("prompt", "")
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"category": (categories, {"default": first_category}),
|
||||
"name": (all_prompts_list, {"default": first_prompt}),
|
||||
"use_external": ("BOOLEAN", {"default": False, "label_on": "on", "label_off": "off", "tooltip": "Toggle to use LLM input instead of internal text"}),
|
||||
"text": ("STRING", {"multiline": True, "default": first_prompt_text, "placeholder": "Enter prompt text", "dynamicPrompts": False, "tooltip": "Enter prompt text directly"}),
|
||||
},
|
||||
"optional": {
|
||||
"llm_input": ("STRING", {"multiline": True, "forceInput": True, "lazy": True, "tooltip": "Connect LLM text input here"}),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID",
|
||||
}
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("prompt",)
|
||||
FUNCTION = "get_prompt"
|
||||
|
||||
@staticmethod
|
||||
def get_prompts_path():
|
||||
"""Get the path to the prompts JSON file in user/default folder"""
|
||||
return os.path.join(folder_paths.get_user_directory(), "default", "prompt_manager_data.json")
|
||||
|
||||
@staticmethod
|
||||
def get_default_prompts_path():
|
||||
"""Get the path to the default prompts JSON file"""
|
||||
return os.path.join(os.path.dirname(__file__), "default_prompts.json")
|
||||
|
||||
@classmethod
|
||||
def load_prompts(cls):
|
||||
"""Load prompts from user folder or default"""
|
||||
user_path = cls.get_prompts_path()
|
||||
default_path = cls.get_default_prompts_path()
|
||||
|
||||
if os.path.exists(user_path):
|
||||
try:
|
||||
with open(user_path, 'r', encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error loading user prompts: {e}")
|
||||
|
||||
if os.path.exists(default_path):
|
||||
try:
|
||||
with open(default_path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
cls.save_prompts(data)
|
||||
return data
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error loading default prompts: {e}")
|
||||
|
||||
# Return empty structure if all else fails
|
||||
print("[PromptManager] Warning: No prompt files found, starting with empty data")
|
||||
return {}
|
||||
|
||||
@staticmethod
|
||||
def sort_prompts_data(data):
|
||||
"""Sort categories and prompts alphabetically (case-insensitive)"""
|
||||
sorted_data = {}
|
||||
for category in sorted(data.keys(), key=str.lower):
|
||||
sorted_data[category] = dict(sorted(data[category].items(), key=lambda item: item[0].lower()))
|
||||
return sorted_data
|
||||
|
||||
@classmethod
|
||||
def save_prompts(cls, data):
|
||||
"""Save prompts to user folder"""
|
||||
user_path = cls.get_prompts_path()
|
||||
sorted_data = cls.sort_prompts_data(data)
|
||||
|
||||
try:
|
||||
os.makedirs(os.path.dirname(user_path), exist_ok=True)
|
||||
with open(user_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(sorted_data, f, indent=2, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error saving prompts: {e}")
|
||||
|
||||
def get_prompt(self, category, name, use_external, text="", llm_input="", unique_id=None):
|
||||
"""Return the appropriate text based on use_external toggle and broadcast update"""
|
||||
|
||||
# Choose which text to use based on the toggle
|
||||
if use_external and llm_input:
|
||||
output_text = llm_input
|
||||
else:
|
||||
output_text = text
|
||||
|
||||
# Broadcast the current prompt text to the frontend
|
||||
if unique_id is not None:
|
||||
server.PromptServer.instance.send_sync("prompt-manager-update-text", {
|
||||
"node_id": unique_id,
|
||||
"prompt": output_text,
|
||||
"use_external": use_external,
|
||||
"llm_input": llm_input if use_external else ""
|
||||
})
|
||||
return (output_text,)
|
||||
|
||||
def check_lazy_status(self, category, name, use_external, text, llm_input=None, unique_id=None):
|
||||
needed = []
|
||||
if use_external:
|
||||
needed.append("llm_input")
|
||||
return needed
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager/get-prompts")
|
||||
async def get_prompts(request):
|
||||
"""API endpoint to get all prompts"""
|
||||
try:
|
||||
prompts = PromptManager.load_prompts()
|
||||
return server.web.json_response(prompts)
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in get_prompts API: {e}")
|
||||
return server.web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/save-category")
|
||||
async def save_category(request):
|
||||
"""API endpoint to create a new category"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category_name = data.get("category_name", "").strip()
|
||||
|
||||
if not category_name:
|
||||
return server.web.json_response({"success": False, "error": "Category name is required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
|
||||
# Case-insensitive check for existing category
|
||||
existing_categories_lower = {k.lower(): k for k in prompts.keys()}
|
||||
if category_name.lower() in existing_categories_lower:
|
||||
return server.web.json_response({"success": False, "error": f"Category already exists as '{existing_categories_lower[category_name.lower()]}'"})
|
||||
|
||||
prompts[category_name] = {}
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in save_category API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/save-prompt")
|
||||
async def save_prompt(request):
|
||||
"""API endpoint to save a prompt"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
name = data.get("name", "").strip()
|
||||
text = data.get("text", "").strip()
|
||||
|
||||
if not category or not name or not text:
|
||||
return server.web.json_response({"success": False, "error": "All fields are required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
|
||||
if category not in prompts:
|
||||
prompts[category] = {}
|
||||
|
||||
# Case-insensitive check - find if name exists with different casing
|
||||
existing_prompts_lower = {k.lower(): k for k in prompts[category].keys()}
|
||||
if name.lower() in existing_prompts_lower:
|
||||
old_name = existing_prompts_lower[name.lower()]
|
||||
if old_name != name:
|
||||
|
||||
# Delete the old casing version
|
||||
print(f"[PromptManager] Removing old casing '{old_name}' before saving as '{name}'")
|
||||
del prompts[category][old_name]
|
||||
|
||||
# Save prompt in dict
|
||||
prompts[category][name] = {"prompt": text}
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in save_prompt API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/delete-category")
|
||||
async def delete_category(request):
|
||||
"""API endpoint to delete a category"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
|
||||
if not category:
|
||||
return server.web.json_response({"success": False, "error": "Category name is required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
|
||||
if category not in prompts:
|
||||
return server.web.json_response({"success": False, "error": "Category not found"})
|
||||
|
||||
del prompts[category]
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in delete_category API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/delete-prompt")
|
||||
async def delete_prompt(request):
|
||||
"""API endpoint to delete a prompt"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
name = data.get("name", "").strip()
|
||||
|
||||
if not category or not name:
|
||||
return server.web.json_response({"success": False, "error": "Category and prompt name are required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
|
||||
if category not in prompts or name not in prompts[category]:
|
||||
return server.web.json_response({"success": False, "error": "Prompt not found"})
|
||||
|
||||
del prompts[category][name]
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in delete_prompt API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
@@ -0,0 +1,222 @@
|
||||
# Video Prompt Writing Guide (T2VA / I2VA / FL2VA / L2VA)
|
||||
|
||||
## 1. Task Overview
|
||||
|
||||
- **T2VA**: Builds a complete audiovisual timeline from text.
|
||||
- **I2VA**: T2VA body + first-frame instruction + a visual path that develops forward from the first frame.
|
||||
- **FL2VA**: T2VA body + first-and-last-frame instruction + a continuous path from the first frame to the last frame.
|
||||
- **L2VA**: T2VA body + last-frame instruction + a path that converges from a plausible preceding state to the last frame.
|
||||
|
||||
## 2. Final Prompt Structure
|
||||
|
||||
### 2.1 Part One Is the Instruction
|
||||
|
||||
**T2VA** has no image-alignment instruction and begins directly with the three core fields.
|
||||
|
||||
**I2VA** always uses:
|
||||
|
||||
```text
|
||||
For the target video, at 0.00 seconds into the target video, <Picture 1> (from [Shot 1]) is fully referenced.
|
||||
```
|
||||
|
||||
**FL2VA** always uses:
|
||||
|
||||
```text
|
||||
How the reference pictures align with the target video — Picture 1 (from Shot 1) aligns with the 0.00-second mark of the target video; Picture 2 (from Shot N) aligns with the S.SS-second mark of the target video.
|
||||
```
|
||||
|
||||
**L2VA** always uses:
|
||||
|
||||
```text
|
||||
How the reference pictures align with the target video — <Picture 1> (from [Shot N]) aligns with the S.SS-second mark of the target video.
|
||||
```
|
||||
|
||||
Here, `N` is the index of the actual final shot, and `S.SS` is the effective video duration formatted to exactly two decimal places. The instruction must be the first line of the final prompt, followed by one blank line before the core fields.
|
||||
|
||||
### 2.2 Part Two Contains the Three Core Fields
|
||||
|
||||
```text
|
||||
integrated_multimodal_description: [Shot 1] ...
|
||||
|
||||
overall_soundscape: ...
|
||||
|
||||
non_diegetic_music: ...
|
||||
```
|
||||
|
||||
- **integrated_multimodal_description**: Describes visuals, actions, shots, speakers, dialogue, singing, and diegetic audio along the timeline.
|
||||
- **overall_soundscape**: Summarizes ambient sound, physical action sounds, and non-verbal human sounds across the entire video.
|
||||
- **non_diegetic_music**: Describes background music that the characters cannot hear and only the audience can hear.
|
||||
|
||||
## 3. How to Incorporate Keyframes into the Multimodal Description
|
||||
|
||||
### 3.1 I2VA: Begin from the Image and Develop Forward
|
||||
|
||||
`<Picture 1>` is the actual first frame of the video at 0.00 seconds and belongs to `[Shot 1]`. The description should first establish the style, subjects, composition, and scene anchors in the image, then describe the next action. Character identity, clothing, colors, key objects, and spatial relationships should remain consistent.
|
||||
|
||||
Recommended structure: **first-frame anchor → action onset → continuous development → result or reaction**.
|
||||
|
||||
### 3.2 FL2VA: Describe the Path Between the First and Last Frames
|
||||
|
||||
Picture 1 is the opening, and Picture 2 is the ending. Focus on how the subject moves, how poses change, how objects are manipulated, how the composition evolves, and how the scene or lighting transitions.
|
||||
|
||||
FL2VA generally favors a single shot so the model can interpolate continuously from the first frame to the last frame. Use multiple shots only when they are explicitly specified. The last frame must be reached by the final `[Shot N]` at the end of the video.
|
||||
|
||||
Recommended structure: **first-frame state → observable intermediate changes → progressively narrowing differences → last-frame state**.
|
||||
|
||||
### 3.3 L2VA: Infer the Opening and Land on the Image at the End
|
||||
|
||||
`<Picture 1>` is the final frame of the video and belongs to the last `[Shot N]`; it does not inherently belong to Shot 1. Infer a plausible earlier state from the user's intent and the last frame, then describe how the characters, objects, camera, and scene gradually approach the reference image.
|
||||
|
||||
Recommended structure: **plausible preceding state → explicit action and transition path → gradual convergence in the final shot → last-frame landing**.
|
||||
|
||||
## 4. How to Write the Three Shared Core Sections
|
||||
|
||||
### 4.1 Develop the Multimodal Description Along the Timeline
|
||||
|
||||
`integrated_multimodal_description` is the main body of the rewritten prompt. Every detail should correspond to something visible or audible: visual style, initial composition, subject appearance and position, scene and key props, actions and reactions, shot changes, spoken language, and synchronized diegetic sound.
|
||||
|
||||
At the beginning of `[Shot 1]`, state the overall style and initial composition. Common styles include `Cinematic`, `live-action`, `2D-animated`, `3D CG`, `claymation`, `watercolor`, and `vintage film`. For keyframe tasks, derive the style from the reference image; for T2VA, select it from the user's text.
|
||||
|
||||
```text
|
||||
[Shot 1] Live-action, cinematic, a medium-wide shot frames...
|
||||
```
|
||||
|
||||
### 4.2 Shots and Cuts
|
||||
|
||||
Do not add a timestamp to the first shot. Use sequential shot numbers for later shots, and begin each one with a strictly increasing cut time that falls within the video duration:
|
||||
|
||||
```text
|
||||
[Shot 2] At 00:03.500, the camera cuts to...
|
||||
```
|
||||
|
||||
For ordinary cuts, use `the camera cuts to`, `the shot cuts to`, `the shot transitions to`, `the shot changes to`, or `the shot switches to`. When explicitly requested by the user, cross-dissolve, fade, or wipe may also be used. A cut should introduce new information about the subject, space, state, viewpoint, or time. If only the distance or a slight angle needs to change, prefer camera motion.
|
||||
|
||||
### 4.3 Camera Motion: Motion Type + Amplitude + Speed
|
||||
|
||||
A complete camera-motion expression has three dimensions: the **motion type** defines how the camera moves, **amplitude** defines the range of compositional change, and **speed** defines the pacing of that change. Add amplitude and speed only when they are meaningful; medium amplitude and normal speed are usually omitted.
|
||||
|
||||
| Dimension | Available Expression | Description |
|
||||
|-|-|-|
|
||||
| Motion type | `Zoom In / Zoom Out` | The focal length changes while the camera body remains stationary |
|
||||
| Motion type | `Push In / Pull Out` | The camera moves forward / backward |
|
||||
| Motion type | `Pan Left / Pan Right` | The camera remains in place while the lens pivots horizontally |
|
||||
| Motion type | `Truck Left / Truck Right` | The camera translates horizontally |
|
||||
| Motion type | `Tilt Up / Tilt Down` | The camera remains in place while the lens pivots vertically |
|
||||
| Motion type | `Pedestal Up / Pedestal Down` | The entire camera moves upward / downward |
|
||||
| Motion type | `Arc Shot` | The camera moves in an arc around the subject |
|
||||
| Motion type | `Tracking Shot` | The camera follows a moving subject |
|
||||
| Motion type | `Static Shot` | The camera position and lens remain still |
|
||||
| Motion type | `Shake Slightly / Shake Strongly` | Slight / strong camera shake |
|
||||
| Motion type | `POV` | The subject's point of view |
|
||||
| Motion type | `Roll Clockwise / Roll Counterclockwise` | The camera rolls clockwise / counterclockwise around the lens axis |
|
||||
| Amplitude | `with small amplitude` | Small-range change |
|
||||
| Amplitude | `with large amplitude` | Large-range change |
|
||||
| Speed | `at slow speed` | Slow movement |
|
||||
| Speed | `at fast speed` | Fast movement |
|
||||
|
||||
Camera motion should be written as a natural English action within the shot, rather than stacked as separate labels at the end of a sentence:
|
||||
|
||||
```text
|
||||
The camera pushes in with small amplitude at slow speed toward the folded letter in her hands.
|
||||
The camera pans right with large amplitude at fast speed, revealing the open doorway.
|
||||
The camera holds a static shot as the runner exits the frame.
|
||||
```
|
||||
|
||||
### 4.4 Speakers, Dialogue, and Singing
|
||||
|
||||
Subjects who speak, sing, or produce an off-screen human voice use stable IDs such as `(S1)` and `(S2)`. When multiple already-numbered speakers speak or sing together, use a compound ID such as `(S1,S2)`. A speaker keeps the same ID across shots; characters who never vocalize receive no speaker ID.
|
||||
|
||||
When a speaker first appears, provide enough information from the visual and audio context to establish a stable identity, such as character type, age, gender, whether the person is on-screen, pitch, timbre, speaking rate, or accent. Place the speaker's identifying phrase, ID, action, and delivery outside `<d>`. Inside `<d>`, include only the language tag and the actual user-provided spoken content. Preserve every original word and punctuation mark verbatim; do not translate or rewrite them.
|
||||
|
||||
```text
|
||||
The young woman with a quiet, breathy voice (S1) says: <d>[English] I get off at the next station.</d>
|
||||
The two children (S1,S2) shout together, <d>[English] Wait for us!</d>
|
||||
```
|
||||
|
||||
For voiceover, use the exact phrase `says in an off-screen voiceover`. Immediately after every voiceover `<d>` block, state that the corresponding on-screen character's lips remain closed:
|
||||
|
||||
```text
|
||||
The man (S1) says in an off-screen voiceover: <d>[English] I still remember that road.</d> while his lips remain completely closed.
|
||||
```
|
||||
|
||||
When the same line of dialogue or lyrics crosses a cut, use `<scenetrans>` at the connecting points in both parts and explicitly state that the audio continues across the cut. Use `<cutoff>` when speech is truncated by the end of the video. Continuity may be expressed with `continues seamlessly across the cut`, `continues uninterrupted into the next shot`, `carries over from the previous shot`, or `remains audible across the transition`.
|
||||
|
||||
### 4.5 On-Screen Text
|
||||
|
||||
Place any banner, sign, label, subtitle, or neon text that is actually visible on screen in English double quotation marks. Preserve the original text and punctuation verbatim, without translation.
|
||||
|
||||
```text
|
||||
A red neon sign reading "营业中" glows above the doorway.
|
||||
```
|
||||
|
||||
### 4.6 overall_soundscape
|
||||
|
||||
Use 1–4 English sentences in one continuous paragraph to summarize the ambient sound, physical action sounds, and non-verbal human sounds across the full video, such as wind, rain, traffic, footsteps, fabric movement, impacts, breathing, laughter, or panting. Dialogue, singing, and diegetic music already belong in the multimodal description and should not be repeated here. Use `N/A` only when the user explicitly requests complete silence throughout the video.
|
||||
|
||||
```text
|
||||
overall_soundscape: Steady rain taps against the café windows while low room ambience continues underneath. The entrance bell rings once, followed by wet footsteps and the soft scrape of a chair.
|
||||
```
|
||||
|
||||
### 4.7 non_diegetic_music
|
||||
|
||||
Use 1–3 English sentences to describe background music that the characters cannot hear and only the audience can hear. Focus on instrumentation, speed, rhythm, and dynamic changes; do not use abstract mood words or explain the emotional function of the score. Singing, instruments, radio, television, or phone music audible to the characters are diegetic events and should appear in the multimodal description. Use `N/A` when there is no non-diegetic music.
|
||||
|
||||
```text
|
||||
non_diegetic_music: Sparse piano notes at a slow tempo, joined by sustained low strings that gradually increase in volume before fading out.
|
||||
```
|
||||
|
||||
## 5. Cases
|
||||
|
||||
### Case 1: T2VA
|
||||
|
||||
With no reference image, construct the complete timeline directly from the text. You may add scene, character, action, and sound details that remain consistent with the user's intent.
|
||||
|
||||
```text
|
||||
integrated_multimodal_description: [Shot 1] Live-action, cinematic, a medium-wide shot frames a baker opening the shutters of a small street bakery before sunrise. The camera pushes in with small amplitude at slow speed as the middle-aged baker with a calm, slightly raspy voice (S1) places a fresh loaf on the wooden counter and says: <d>[English] First batch of the morning.</d> [Shot 2] At 00:05.000, the camera cuts to a close-up of steam rising from the sliced bread while the baker's final words carry over from the previous shot.
|
||||
|
||||
overall_soundscape: Wooden shutters scrape open over a quiet street as trays clink softly inside the bakery. The doorbell rings once, followed by light footsteps and the crisp sound of bread being sliced.
|
||||
|
||||
non_diegetic_music: A soft acoustic-guitar pattern at a moderate tempo, joined by sparse upright-bass notes and a gentle fade at the end.
|
||||
```
|
||||
|
||||
### Case 2: I2VA
|
||||
|
||||
Write the first-frame instruction first, then use the subject, composition, and scene in Picture 1 as the starting point of Shot 1 before describing how the scene continues to develop.
|
||||
|
||||
```text
|
||||
For the target video, at 0.00 seconds into the target video, <Picture 1> (from [Shot 1]) is fully referenced.
|
||||
|
||||
integrated_multimodal_description: [Shot 1] Live-action, cinematic, the young woman shown in <Picture 1> remains beside the rain-covered train window, preserving her appearance, clothing, seat position, and the carriage layout. The camera trucks right with small amplitude at slow speed as she lifts her gaze from the folded letter toward the passing city lights. Her reflection moves across the glass while the quiet, breathy young woman (S1) says: <d>[English] I get off at the next station.</d> She folds the letter along its existing crease.
|
||||
|
||||
overall_soundscape: The train wheels produce a steady metallic rhythm beneath a low ventilation hum. Rain ticks against the window while paper rustles softly in her hands.
|
||||
|
||||
non_diegetic_music: Sustained cello notes at a slow tempo with widely spaced piano tones, gradually decreasing in volume.
|
||||
```
|
||||
|
||||
### Case 3: FL2VA
|
||||
|
||||
The two images anchor the opening and ending respectively. The body should not repeat two static image descriptions; instead, it should supply the motion path that connects them. The following example is an eight-second single shot.
|
||||
|
||||
```text
|
||||
How the reference pictures align with the target video — Picture 1 (from Shot 1) aligns with the 0.00-second mark of the target video; Picture 2 (from Shot 1) aligns with the 8.00-second mark of the target video.
|
||||
|
||||
integrated_multimodal_description: [Shot 1] Live-action, cinematic, a rain-soaked cyclist begins in the position and framing established by Picture 1, holding a closed black umbrella beside a silver bicycle. The camera pulls out with small amplitude at slow speed as she releases the bicycle handle, raises the umbrella above her shoulder, and presses the runner upward until the canopy opens. Water rolls from the expanding fabric while she steps beneath it, rotates the handle into the final angle, and settles into the pose, spacing, and composition established by Picture 2 at the end of the shot.
|
||||
|
||||
overall_soundscape: Rain falls steadily on the pavement, followed by the metallic click of the umbrella runner and the soft snap of the canopy opening. Water drips from the bicycle frame as distant traffic passes.
|
||||
|
||||
non_diegetic_music: N/A
|
||||
```
|
||||
|
||||
### Case 4: L2VA
|
||||
|
||||
The image anchors only the final moment. First establish a compatible earlier state, then let the actions, object states, and composition gradually land on Picture 1 in the final shot. The following example is a six-second single shot.
|
||||
|
||||
```text
|
||||
How the reference pictures align with the target video — <Picture 1> (from [Shot 1]) aligns with the 6.00-second mark of the target video.
|
||||
|
||||
integrated_multimodal_description: [Shot 1] Live-action, cinematic, a close shot begins with an intact drinking glass near the edge of a dark wooden table, while the same hand and sleeve visible in <Picture 1> approach from the right. The camera pushes in with small amplitude at slow speed as the fingertips strike the rim. The glass tips, falls, and hits the floor with a sharp impact; cracks spread through it as fragments slide outward. Toward the end, the moving pieces lose momentum and settle into the exact broken arrangement, hand position, camera angle, lighting, and final composition established by <Picture 1>.
|
||||
|
||||
overall_soundscape: Fingertips tap the glass before it scrapes across the tabletop, falls, and breaks with a sharp crash. Small fragments scatter and gradually stop sliding across the floor.
|
||||
|
||||
non_diegetic_music: A low electronic pulse at a slow tempo, ending immediately after the glass breaks.
|
||||
```
|
||||
@@ -0,0 +1,341 @@
|
||||
# Full-Reference Mode Rewrite Output Format Guide
|
||||
|
||||
This guide explains how rewrite outputs are organized and written in full-reference mode.
|
||||
|
||||
Write all six rewrite sections in English. Preserve the original language only for dialogue and lyrics inside `<d>` and for text visibly present in the scene.
|
||||
|
||||
**Description detail:** Make `detailed_description` as detailed and explicit as possible. For each shot, clearly establish the current composition, subject appearance and position, environment and lighting, actions and state changes, camera movement, current sound, and the points where referenced content actually appears or takes effect. Avoid reducing the description to a plot summary or a list of reference relationships.
|
||||
|
||||
> The basic formats for shots, camera movement, speakers, dialogue, and ordinary sound are shared with the Video Prompt Writing Guide (T2VA / I2VA / FL2VA / L2VA). This guide focuses on the reference labels, analysis sections, and format differences specific to full-reference mode.
|
||||
|
||||
## 1. Overall Structure
|
||||
|
||||
A complete rewrite output consists of six sections in the following order:
|
||||
|
||||
| Section | Purpose |
|
||||
| --- | --- |
|
||||
| `subject_definitions` | Defines referenced content and its reference labels |
|
||||
| `summary` | Summarizes the task type, target video, and main reference relationships |
|
||||
| `retention_analysis` | Describes how referenced content is preserved, transferred, or reused |
|
||||
| `detailed_description` | Describes visuals, actions, shots, sound, and dialogue in playback order |
|
||||
| `overall_soundscape` | Summarizes ambience and physical sounds |
|
||||
| `non_diegetic_music` | Describes background music audible only to the audience |
|
||||
|
||||
## 2. Reference Labels and Definitions (`subject_definitions`)
|
||||
|
||||
Full-reference rewrites use four types of labels to identify the source and role of referenced content:
|
||||
|
||||
| Label | Meaning |
|
||||
| --- | --- |
|
||||
| `<Subject N>` | Visible content abstracted from reference assets that can be reused or modified in the target video |
|
||||
| `<Picture N>` | A reference image used as a concrete target frame or shot-planning anchor |
|
||||
| `<Video N>` | A reference video that provides an editing source, continuation starting point, or whole-video temporal structure |
|
||||
| `<Audio N>` | An audio signal that is copied or referenced |
|
||||
|
||||
> Once a reference label is assigned to a piece of content, it keeps the same meaning across `subject_definitions`, `summary`, `retention_analysis`, `detailed_description`, and the audio sections.
|
||||
|
||||
`subject_definitions` defines each piece of referenced content that must be tracked separately later, such as a person, an environment, a source video's structure, or an audio track. Give each item its own line and explain what its label denotes, its reference role, and the main features to follow; name the corresponding source asset when its provenance needs to be made explicit. If `<Picture N>` or `<Video N>` only identifies the source of another referenced item and will not be analyzed or used separately later, cite it inside that item's definition without adding a separate line. `retention_analysis` records where each referenced item appears and whether it is fully preserved, partially preserved, transferred, or reused.
|
||||
|
||||
### 2.1 `<Subject N>`
|
||||
|
||||
`<Subject N>` is used for reusable visible content, including:
|
||||
|
||||
- People, animals, or objects
|
||||
- Scenes, backgrounds, or environments
|
||||
- Clothing, props, interfaces, or visual effects
|
||||
- Styles, actions, expressions, or poses
|
||||
|
||||
It represents a content unit that will actually be used in the target video, rather than the source file itself. One subject may be defined by multiple reference assets, and one reference asset may provide multiple subjects.
|
||||
|
||||
```text
|
||||
<Subject 1> is the young woman in <Picture 1>, with long dark hair, a blue cardigan, and a thin silver necklace.
|
||||
```
|
||||
|
||||
When the same subject comes from multiple assets, combine the sources and state what each asset provides:
|
||||
|
||||
```text
|
||||
<Subject 1> is the woman whose appearance comes from <Picture 1> and whose walking motion comes from <Video 1>.
|
||||
```
|
||||
|
||||
### 2.2 `<Picture N>`
|
||||
|
||||
Use a standalone `<Picture N>` when the reference image itself serves as a shot's first frame, keyframe, last frame, edited keyframe, or composition anchor:
|
||||
|
||||
```text
|
||||
<Picture 2> is the first frame of [Shot 1], showing a woman seated beside a café window.
|
||||
```
|
||||
|
||||
If an image is used only to define a character, scene, costume, or style, do not create a standalone picture entry. Instead, cite the image source inside the corresponding `<Subject N>` definition.
|
||||
|
||||
When an image acts as a storyboard or shot-planning reference, state which shots it maps to and what planning information it provides:
|
||||
|
||||
```text
|
||||
<Picture 3> is a storyboard reference for [Shot 1] and [Shot 2], defining their viewpoint, subject placement, and shot order.
|
||||
```
|
||||
|
||||
### 2.3 `<Video N>`
|
||||
|
||||
`<Video N>` is reserved for whole-video relationships, such as:
|
||||
|
||||
- Editing an original video
|
||||
- Continuing from the end of an original video
|
||||
- Referencing the original video's camera movement, cuts, rhythm, or temporal structure
|
||||
|
||||
```text
|
||||
<Video 1> is the source video for the target video edit.
|
||||
```
|
||||
|
||||
If a person, object, scene, action, or effect from a reference video is reused as visible content, it still belongs under `<Subject N>`. `<Video N>` identifies the asset or structural source and does not replace subject labels.
|
||||
|
||||
### 2.4 `<Audio N>`
|
||||
|
||||
`<Audio N>` represents a standalone audio asset or an enabled synchronized audio track from a reference video. Common uses include:
|
||||
|
||||
- Copying all or part of an audio signal
|
||||
- Referencing a background-music style
|
||||
- Referencing a speaker's voice timbre and delivery
|
||||
- Using dialogue, lyrics, or sound effects from the original audio
|
||||
- Referencing beat, rhythm, or audio continuity
|
||||
|
||||
When an `<Audio N>` explicitly corresponds to a target speaker, reuse that speaker's global ID in the definition: write `<Subject N> (Sx)` when the speaker maps to a defined subject, or use a stable voice description followed by `(Sx)` otherwise. The ID comes from the target video's global speaker order and is not independently assigned or renumbered in the audio definition. See Section 5.4 for the speaker-numbering rules:
|
||||
|
||||
```text
|
||||
<Audio 1> is the voice-timbre reference for <Subject 1> (S1).
|
||||
```
|
||||
|
||||
When one audio asset serves multiple roles, describe those roles in one natural sentence rather than creating additional subsections.
|
||||
|
||||
### 2.5 Visual and Audio Tracks from the Same Reference Video
|
||||
|
||||
`<Video N>` and `<Audio N>` are numbered independently. Each index indicates only the label's order within its own category and does not encode a pairing between the two categories. The same reference video may therefore correspond to `<Video 1>` and `<Audio 2>`; different indices do not prevent them from coming from the same source asset.
|
||||
|
||||
An ordinary reference video does not create `<Audio N>` merely because the file contains sound.
|
||||
|
||||
An `<Audio N>` definition primarily states the audio's role and does not have to name the `<Video N>` it comes from. State the shared source only when needed to remove provenance ambiguity, for example:
|
||||
|
||||
```text
|
||||
<Video 1> is the source video for the target video edit.
|
||||
<Audio 2> is the synchronized audio track of <Video 1> and is reused in the target video.
|
||||
```
|
||||
|
||||
## 3. `summary`
|
||||
|
||||
This section uses one short English paragraph to summarize the target video and its reference relationships. It begins with a square-bracketed task-type prefix:
|
||||
|
||||
```text
|
||||
[reference generation] ...
|
||||
[video editing + reference generation + audio reuse] ...
|
||||
```
|
||||
|
||||
Choose task types according to the actual role each reference asset plays in the target video:
|
||||
|
||||
| Task type | When to use it |
|
||||
| --- | --- |
|
||||
| `keyframe completion` | An image serves as the target video's first frame, keyframe, last frame, edited keyframe, or another concrete frame anchor |
|
||||
| `reference generation` | An image, video, or audio asset provides generation guidance for a character, scene, style, action, camera movement, storyboard, and so on, without serving as a concrete frame or as the source video being edited or continued |
|
||||
| `video editing` | An existing source video is directly modified; editing an image or generating between still keyframes does not belong to this type |
|
||||
| `video continuation` | New content continues, extends, resumes, or transitions from an existing source video |
|
||||
| `audio reuse` | The same audio signal is reused in full or in part |
|
||||
| `audio reference` | The audio signal is not copied directly; only its music style, timbre, dialogue or lyric content, sound-effect texture, beat, or continuity is referenced |
|
||||
|
||||
When a task satisfies multiple relationships, combine the task types with ` + ` and do not repeat a type. For example, continuing from a source video while using an image as the last frame is written as `[video continuation + keyframe completion]`. Editing a source video while retaining its original audio may be written as `[video editing + audio reuse]`.
|
||||
|
||||
The mere presence of video or audio does not automatically create a corresponding task type. If a reference video provides only camera movement, cuts, or rhythm, it normally belongs to `reference generation`. Use `video editing` or `video continuation` only when that video is directly edited or continued.
|
||||
|
||||
When editing a source video, use `audio reuse` as well if its original audio remains audible. When continuing a source video without directly copying the audio signal, use `audio reference` if the new audio only continues the original track's audible characteristics.
|
||||
|
||||
The summary uses the previously defined `<Subject N>`, `<Picture N>`, `<Video N>`, and `<Audio N>` labels to describe the main subjects, shot flow, and roles of the reference assets. Do not introduce new reference labels in this section.
|
||||
|
||||
For video-editing tasks, begin the summary after the task-type prefix with:
|
||||
|
||||
```text
|
||||
The target video is an edited version of <Video 1>.
|
||||
```
|
||||
|
||||
## 4. `retention_analysis`
|
||||
|
||||
This section describes how each piece of referenced content is preserved, transferred, copied, or referenced in the target video. Use one line for each reference label and preserve the meaning established in `subject_definitions`.
|
||||
|
||||
### 4.1 Visible Content
|
||||
|
||||
`<Subject N>`, `<Picture N>`, and `<Video N>` use the following relationship markers. These markers are fixed English values in the output format:
|
||||
|
||||
| Relationship marker | Meaning |
|
||||
| --- | --- |
|
||||
| `fully_preserved` | The defined role of the referenced content is fully preserved |
|
||||
| `partially_preserved` | The referenced content is still used, but some defined characteristics are changed or only partially retained |
|
||||
| `attribute_transfer` | Referenced characteristics are transferred to a different identifiable target subject |
|
||||
| `weak_reference` | Only broad similarity in style, category, composition, or atmosphere is retained |
|
||||
|
||||
Subject entry:
|
||||
|
||||
```text
|
||||
<Subject 1> (appears in [Shot 1], [Shot 3]): fully_preserved - ...
|
||||
```
|
||||
|
||||
Picture entry:
|
||||
|
||||
```text
|
||||
<Picture 2> ([Shot 1] first frame): fully_preserved - ...
|
||||
```
|
||||
|
||||
Video-structure entry:
|
||||
|
||||
```text
|
||||
<Video 1> (cut and pacing structure): weak_reference - ...
|
||||
```
|
||||
|
||||
### 4.2 Audio
|
||||
|
||||
`<Audio N>` uses the following relationship markers:
|
||||
|
||||
| Relationship marker | Meaning |
|
||||
| --- | --- |
|
||||
| `fully_copy` | The complete source audio serves as the target video's complete final audio track |
|
||||
| `partially_copy` | Only part of the timeline or selected audio layers are copied, or other sounds are added, removed, or replaced after copying |
|
||||
| `reference` | The signal is not copied directly; only timbre, rhythm, music style, dialogue content, or sound texture is referenced |
|
||||
| `weak_reference` | Only broad similarity in category or atmosphere is retained |
|
||||
|
||||
```text
|
||||
<Audio 1>: fully_copy - <Audio 1> is reused 1:1 as the target video's complete final audio track.
|
||||
```
|
||||
|
||||
```text
|
||||
<Audio 2>: reference - the target speaker follows <Audio 2>'s voice timbre and measured delivery without copying the original signal.
|
||||
```
|
||||
|
||||
Choose each relationship marker only within the reference role already defined for that label in `subject_definitions`. Do not treat newly added actions, backgrounds, or plot events in the target video as losses of reference fidelity.
|
||||
|
||||
## 5. `detailed_description`
|
||||
|
||||
This is the main body of a full-reference rewrite. It describes visuals, actions, sound, and dialogue shot by shot in target-video playback order and inserts reference labels where they apply.
|
||||
|
||||
### 5.1 Basic Format
|
||||
|
||||
The basic format follows the Video Prompt Writing Guide (T2VA / I2VA / FL2VA / L2VA):
|
||||
|
||||
- Write the body in English. Preserve the original language of dialogue, lyrics, and visible text.
|
||||
- `[Shot 1]` marks the opening shot and has no timestamp. Later shots use `[Shot N] At MM:SS.mmm, ...` to mark cut times.
|
||||
- Write camera movement as natural English within the current shot, including movement type, amplitude, and speed when they need to be expressed.
|
||||
- Give vocal sources stable `(S1)`, `(S2)`, and subsequent IDs. Write dialogue and lyrics as `<d>[Language] ...</d>`.
|
||||
- Use `<scenetrans>`, `<cutoff>`, and the corresponding continuity descriptions for dialogue crossing a cut, speech truncated by the video ending, and continuous audio across shots.
|
||||
|
||||
For complete rules and examples covering camera vocabulary, group speech, voice-over, dialogue across cuts, and visible text, see the Video Prompt Writing Guide (T2VA / I2VA / FL2VA / L2VA).
|
||||
|
||||
### 5.2 Full-Reference Mode Differences
|
||||
|
||||
| Dimension | T2VA | Full-reference mode |
|
||||
| --- | --- | --- |
|
||||
| Main field | `integrated_multimodal_description` | `detailed_description` |
|
||||
| Style opening | Written after `[Shot 1]` | Established in one or two English sentences before `[Shot 1]` |
|
||||
| Reference information | Does not use full-reference labels | Inserts `<Subject N>`, `<Picture N>`, `<Video N>`, and `<Audio N>` at their first appearance and where their roles apply |
|
||||
| Audio relationships | Describes the target video's own sound | Cites `<Audio N>` in the corresponding shot or audio phase and states whether the signal is copied or referenced |
|
||||
|
||||
Opening example:
|
||||
|
||||
```text
|
||||
The target video is in a cinematic, literary music-video style with soft lighting and a slightly desaturated color palette.
|
||||
[Shot 1] The scene opens in a crowded urban street...
|
||||
[Shot 2] At 00:09.000, the shot cuts to an extreme close-up...
|
||||
```
|
||||
|
||||
For generation tasks, `detailed_description` is normally 350-500 English words. Dialogue-dense content prioritizes fitting the complete spoken timeline rather than mechanically reaching a word count. Video-editing descriptions scale with the complexity of the source video and do not have to follow the generation-task range. A single shot does not automatically justify a shorter description; distribute detail across multiple shots according to their information load.
|
||||
|
||||
### 5.3 Using Reference Labels in Shots
|
||||
|
||||
At the first clear appearance of an important `<Subject N>`, describe its referenced characteristics, position in the frame, and current action within what is actually visible in the shot. Continue using the same label in later shots without redefining what the label represents.
|
||||
|
||||
Use natural phrasing for concrete frame anchors:
|
||||
|
||||
```text
|
||||
the shot begins from <Picture 1>
|
||||
the shot's keyframe corresponds to <Picture 2>
|
||||
the shot ends on <Picture 3>
|
||||
```
|
||||
|
||||
When editing or continuing an original video, cite `<Video N>` naturally where its source state, structure, or continuation relationship applies. Cite `<Audio N>` in the shot or semantic phase where the audio relationship is active.
|
||||
|
||||
### 5.4 Speakers, Audio Sources, and Dialogue
|
||||
|
||||
The basic speaker-ID and `<d>` formats follow T2VA. When a referenced subject physically speaks, retain both the visual reference label and the speaker ID:
|
||||
|
||||
```text
|
||||
<Subject 2> (S1) turns toward the woman and says, <d>[English] Last summer, I went to my grandfather's house. He talked about you.</d>
|
||||
```
|
||||
|
||||
`<Subject N>` identifies the referenced subject, while `(Sx)` identifies the actual speaker. When the subject speaks, write `<Subject N> (Sx)`. If the same subject speaks off-screen, keep the same form and mark it as `off-screen`. When the speaker does not correspond to a defined subject, use a stable voice description followed by `(Sx)`.
|
||||
|
||||
When verbal content is only a cue within a directly reused BGM or complete soundtrack, and no person, character, narrator, or other independent vocal source physically produces it, use `<Audio N>` as the audible source and do not invent an additional `(Sx)`. If a concrete person, character, narrator, or other independent vocal source produces the voice, assign and reuse `(Sx)` for that source:
|
||||
|
||||
```text
|
||||
When <Audio 1> reaches the phrase <d>[English] I'm lonely lonely lonely lonely lonely I'm lonely</d>, <Subject 1> performs the corresponding hand gesture without becoming a separate speaker source.
|
||||
```
|
||||
|
||||
When dialogue, narration, or lyrics from reference audio are directly reused, or when the input prompt explicitly requests their reperformance, preserve the exact source words and original language inside `<d>`. Write `[unclear]` for unintelligible spans instead of guessing or paraphrasing them. Standardize punctuation to the basic written marks needed to express the sentence, such as `,`, `.`, `?`, and `!`; remove repeated tildes, emoji, bullets, and repeated or decorative punctuation. End complete statements, questions, and exclamations with `.`, `?`, or `!` respectively before `</d>`.
|
||||
|
||||
When only timbre, rhythm, emotion, or delivery is referenced, do not carry the original dialogue from the reference audio into the target video.
|
||||
|
||||
Assign `(Sx)` once according to the order of actual vocal events in the target video. Reuse the corresponding ID at every actual vocal event in `detailed_description`; an `<Audio N>` definition bound to a target speaker in `subject_definitions` also reuses the same `(Sx)` but never assigns a new one independently. Do not write `(Sx)` in `retention_analysis`. Verbal cues that exist only within a directly reused BGM or complete soundtrack use `<Audio N>`; voices physically produced by a concrete person, character, narrator, or other independent vocal source use `(Sx)`.
|
||||
|
||||
## 6. `overall_soundscape` and `non_diegetic_music`
|
||||
|
||||
The definitions of these two sound categories follow the Video Prompt Writing Guide (T2VA / I2VA / FL2VA / L2VA).
|
||||
|
||||
`overall_soundscape` summarizes ambience and physical sounds across the full video. Dialogue, singing, and sound events synchronized to a particular shot remain in `detailed_description`:
|
||||
|
||||
```text
|
||||
overall_soundscape: Quiet indoor room tone and a low ventilation hum continue throughout the video.
|
||||
```
|
||||
|
||||
`non_diegetic_music` describes background music that the characters cannot hear and that is audible only to the audience. When music is present, state its instrumentation, tempo, and dynamic development:
|
||||
|
||||
```text
|
||||
non_diegetic_music: A restrained solo-piano score at a slow tempo, with sustained low cello underneath and no swell.
|
||||
```
|
||||
|
||||
When reference audio is used, state its copy or reference relationship only in the section that matches the audible layer: ambience and sound effects belong in `overall_soundscape`, while audience-only score belongs in `non_diegetic_music`. If the same audio provides both kinds of content, describe the corresponding relationship in each section:
|
||||
|
||||
```text
|
||||
overall_soundscape: The copied ambience layer from <Audio 1> continues throughout the target video.
|
||||
non_diegetic_music: <Audio 2> is directly reused as the complete audience-only score.
|
||||
```
|
||||
|
||||
Write complete dialogue and lyrics only inside `<d>` in `detailed_description`; do not repeat them in these two sections.
|
||||
|
||||
## 7. Complete Example
|
||||
|
||||
<details>
|
||||
<summary>Show the complete example</summary>
|
||||
|
||||
```text
|
||||
subject_definitions:
|
||||
<Subject 1> is the coffee-shop environment in <Picture 1>, featuring an exposed brick wall, an orange tufted sofa with patterned pillows, a neon sign, and a wooden coffee table.
|
||||
<Subject 2> is the fluffy white Samoyed in <Picture 2>, <Picture 3>, and <Picture 4>, with thick white fur, pointed ears, a dark nose, and a curved tail.
|
||||
<Subject 3> is the young blonde woman in <Video 1>, with long blonde hair and a light-pink button-down shirt with rolled-up sleeves.
|
||||
<Subject 4> is the young man in <Video 2>, with short wavy brown hair and a dark-grey hoodie with drawstrings.
|
||||
<Audio 1> is the voice-timbre reference for <Subject 3> (S1), containing a spoken English vocal layer.
|
||||
|
||||
summary:
|
||||
[reference generation + audio reference] The target video shows <Subject 3> eating a cookie in <Subject 1>. <Subject 4> enters with <Subject 2>, which lunges toward the cookie. The three-shot exchange uses <Audio 1> as the voice-timbre reference for <Subject 3> and ends with a canned audience laugh.
|
||||
|
||||
retention_analysis:
|
||||
<Subject 1> (appears in [Shot 1], [Shot 2], [Shot 3]): fully_preserved - the exposed brick wall, orange tufted sofa, patterned pillows, neon sign, and wooden coffee table are retained.
|
||||
<Subject 2> (appears in [Shot 1], [Shot 2]): fully_preserved - the Samoyed's thick white fur, pointed ears, dark nose, and curved tail are retained.
|
||||
<Subject 3> (appears in [Shot 1], [Shot 2], [Shot 3]): fully_preserved - the blonde woman's identity, long hair, and light-pink shirt are retained.
|
||||
<Subject 4> (appears in [Shot 1], [Shot 2]): fully_preserved - the young man's short wavy brown hair and dark-grey hoodie are retained.
|
||||
<Audio 1>: reference - its vocal timbre guides the dialogue delivery of <Subject 3> without copying the original signal.
|
||||
|
||||
detailed_description:
|
||||
The target video uses a realistic multi-camera sitcom style with warm indoor lighting.
|
||||
[Shot 1] A medium shot establishes <Subject 1>, the coffee shop with its exposed brick wall, orange tufted sofa, patterned pillows, neon sign, and wooden coffee table. <Subject 3> (S1), the young woman with long blonde hair and a light-pink button-down shirt with rolled-up sleeves, sits on the sofa holding a chocolate-chip cookie. From the left, <Subject 4>, the young man with short wavy brown hair and a dark-grey hoodie with drawstrings, enters holding the leash of <Subject 2>, the thick-furred white Samoyed with pointed ears, a dark nose, and a curved tail. The dog lunges toward the cookie and pulls the leash taut. <Subject 3> (S1) jerks her hand back and, using the clear youthful voice timbre referenced from <Audio 1>, exclaims with light annoyance, <d>[English] Hey! Watch your dog!</d> She closes her lips and guards the cookie while <Subject 4> pulls the dog back.
|
||||
[Shot 2] At 00:03.000, the shot cuts to a close-up of <Subject 4> (S2), the young man in the dark-grey hoodie from Shot 1, sitting beside <Subject 3> on the sofa and holding <Subject 2> securely in his arms. <Subject 4> (S2) says in a casual young male voice with a playful tone and an easy conversational pace, <d>[English] He just likes cookies more than me.</d> He closes his mouth into an apologetic smile and strokes the dog's thick white fur.
|
||||
[Shot 3] At 00:05.000, the shot cuts to a close-up of <Subject 3> (S1), the blonde woman in the light-pink shirt from Shot 1. Her annoyance softens as she looks toward the Samoyed. <Subject 3> (S1) replies in the same clear youthful voice referenced from <Audio 1> with an amused cadence, <d>[English] Well, he has good taste at least.</d> She smiles and raises the cookie in a small toast-like gesture. A classic canned audience laugh begins immediately after the line and continues through the final frame.
|
||||
|
||||
overall_soundscape:
|
||||
Soft indoor coffee-shop room tone continues throughout the scene.
|
||||
|
||||
non_diegetic_music:
|
||||
N/A
|
||||
```
|
||||
|
||||
</details>
|
||||