Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
@@ -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']
|
||||
@@ -26,6 +26,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,82 +1,146 @@
|
||||
# ComfyUI Prompt Manager
|
||||
## A custom [ComfyUI](https://github.com/comfyanonymous/ComfyUI) node for Organizing, Generating or Enhancing prompts.
|
||||
## A comprehensive prompt and workflow toolkit for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) — Save, Generate, Extract, Build, and Reuse workflows with full LoRA support.
|
||||
|
||||
This addon started off as a simple prompt Manager, to help save and retrieve prompts.
|
||||
But has since evolved to allow generating prompts for Images, video and Image analysis.
|
||||
The new advanced version of the manager, now allows the user to save the entire recipe,
|
||||
as it allows saving the Lora Stacks that goes with a prompt. Supporting Dual Stack for Wan.
|
||||
A complete prompt and workflow management suite featuring:
|
||||
|
||||
## v2.0 Introduces: Workflow Extractor + Workflow Builder + Workflow Renderer + Workflow Manager
|
||||
|
||||
The goal of this v2.0 workflow layer is to strip workflows down to their core elements so they are easier to understand, edit, and reuse.
|
||||
|
||||
- Extract metadata from source images and videos (ComfyUI or A1111/Forge)
|
||||
- Reduce complex graphs into a clean, editable workflow core
|
||||
- Rebuild and run from that simplified core with Workflow Builder to Workflow Renderer
|
||||
- Save and reuse clean workflow entries through Workflow Manager
|
||||
- Combine with Prompt tools (Prompt Manager, and Prompt Generator) for easier prompt creation and generation.
|
||||
|
||||
Think of it as workflow de-spaghetti: keep the important parts, remove unnecessary complexity.
|
||||
|
||||
This release marks version 2.0.0. More polish and quality-of-life improvements are planned.
|
||||
|
||||
**Prompt Manager** — Save and organize prompts with categories, complete with matching LoRA stacks, trigger words, and thumbnail previews. Supports dual LoRA stacks for complex workflows like Wan videos. Toggle LoRAs on/off or adjust strengths directly from saved presets. Supports workflow_data input from Workflow Builder or Prompt Extractor to pull workflow prompts and LoRA stacks directly into PMA. Will also remap LoRAs if paths differ.
|
||||
|
||||
**Prompt Generator** — Generate and enhance prompts using local LLMs via [llama.cpp](https://github.com/ggerganov/llama.cpp) or [Ollama](https://ollama.com). Supports text enhancement, image analysis with vision models (Qwen3.5), and thinking mode for deeper reasoning. Analyze up to 5 images at once.
|
||||
|
||||
**Prompt Extractor** — Extract prompts, LoRA configurations, and checkpoint/model paths from existing images, videos, or JSON workflow files. Extracts the first frame from any video. Automatically parses embedded metadata and outputs active LoRAs as LoRA stacks, plus resolved model paths (High/Low for dual-model workflows like Wan). Supports ComfyUI, A1111/Forge, and WebP metadata formats. When used with Prompt Manager Advanced, LoRAs are automatically found if available, regardless of path. For those that are not, right-click offers the option to look for them on Civitai. Browse files from both your input and output folders.
|
||||
|
||||
**Prompt Model Loader** — Load checkpoints, diffusion, or GGUF models from a string path output by Prompt Extractor. Auto-detects whether the model is a checkpoint (outputs MODEL + CLIP + VAE) or a diffusion/UNET/GGUF model (outputs MODEL only). Displays model type badge and name directly on the node. Works around ComfyUI's combo type limitation, allowing extracted model paths to connect directly to a loader. Supports [ComfyUI-GGUF](https://github.com/city96/ComfyUI-GGUF) models when the extension is installed.
|
||||
|
||||
**Workflow Suite of Tools** — Build and re-render extracted workflows with dedicated nodes:
|
||||
|
||||
- **Workflow Extractor**: Reads workflow metadata and normalizes it into reusable workflow_data.
|
||||
- **Workflow Builder**: Lets you edit and assemble a clean core workflow from extracted metadata.
|
||||
- **Workflow Renderer**: Runs built-in workflow templates for near one-click generation after Builder setup.
|
||||
- **Workflow Bridge**: Passes workflow context and routing data between nodes cleanly.
|
||||
- **Workflow Model Loader**: Resolves and loads the right model/checkpoint from workflow data.
|
||||
- **Workflow Manager**: Saves and reuses cleaned workflow entries for fast reruns.
|
||||
|
||||
Builder + Renderer + Workflow Manager provides a streamlined generation path: configure Builder once, connect Renderer and Save Image/Save Video, and save both the output and the resulting workflow.
|
||||
|
||||
Built-in workflow support includes Flux 1, Flux 2, SDXL, Wan, Qwen, Z-Image, Wan Image, and Wan Video (I2V and T2V).
|
||||
|
||||
**Workflow Builder + Workflow Manager Reuse Loop** — Build workflow_data from extracted image/video metadata or from Workflow Builder directly, then save and reuse those workflow entries through Workflow Manager.
|
||||
___
|
||||
For Prompt Generation, it uses an existing install of [llama.cpp](https://github.com/ggerganov/llama.cpp), preventing install conflicts with ComfyUI.
|
||||
Provides options to automatically download Qwen3 and Qwen3VL models.
|
||||
Supports prompt enhancing, image analysis, or custom image processing, with up to 5 images at once.
|
||||
Custom GGUF models can be used if supported by llama.cpp; simply drop them in the models/gguf folder.
|
||||
Users can now set a custom Llama-server path as well as a custom Model Path in ComfyUI's preferences.
|
||||
If a Custom Model Path is added, it will become the default download folder.
|
||||
|
||||
<div align="center">
|
||||
<figcaption>Simple Prompt Generator Usage</figcaption>
|
||||
<img src="docs/prompt_manager.png" alt="Prompt Manager">
|
||||
</div>
|
||||
|
||||
|
||||
<div align="center">
|
||||
<figcaption>Advanced Prompt Generator Usage</figcaption>
|
||||
<img src="docs/prompt_generator_advanced.png" alt="Prompt Manager">
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<figcaption>Prompt Manager Advanced, with Lora support</figcaption>
|
||||
<figcaption>Prompt Manager Advanced, with Lora and trigger word support</figcaption>
|
||||
<img src="docs/prompt_manager_advanced.png" alt="Prompt Manager">
|
||||
</div>
|
||||
|
||||
<div align="center">
|
||||
<figcaption>Prompt Extractor connected to Manager Advanced, so workflow can be saved with Loras</figcaption>
|
||||
<img src="docs/prompt_extractor.png" alt="Prompt Manager">
|
||||
</div>
|
||||
<div align="center">
|
||||
<figcaption>Advanced Prompt Generator</figcaption>
|
||||
<img src="docs/prompt_generator_advanced.png" alt="Prompt Manager">
|
||||
</div>
|
||||
<div align="center">
|
||||
<figcaption>Simple Prompt Generator</figcaption>
|
||||
<img src="docs/prompt_manager.png" alt="Prompt Manager">
|
||||
</div>
|
||||
<div align="center">
|
||||
<figcaption>Workflow Builder</figcaption>
|
||||
<img src="docs/workflow_builder.jpg" 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
|
||||
- **NSFW Tagging**: Mark categories and individual prompts as NSFW with visual badge indicator on the node title bar
|
||||
- **NSFW Filtering**: Hide/show NSFW content via a global preference — NSFW categories and prompts are filtered from dropdowns when hidden
|
||||
- **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
|
||||
|
||||
### Prompt Manager Advanced:
|
||||
- **All Prompt Manager Features**: Everything from the basic Prompt Manager, plus LoRA integration
|
||||
- **All Prompt Manager Features**: Everything from the basic Prompt Manager, plus LoRA and trigger-word integration
|
||||
- **NSFW Tagging**: Mark categories and individual prompts as NSFW — red "NSFW" badge appears on the prompt selector and in the thumbnail browser
|
||||
- **NSFW Filtering**: Session-persistent NSFW toggle button in the thumbnail browser to show/hide NSFW content; navigation arrows skip NSFW entries when hidden
|
||||
- **List View Mode**: Switch between thumbnail grid and compact list view in the prompt browser, with session-persistent preference
|
||||
- **Prompt Thumbnails**: Save thumbnail images with your prompts for visual identification in the dropdown
|
||||
- **Dual LoRA Stack Support**: Two separate LoRA stack inputs/outputs for complex workflows (e.g., Wan video with different LoRAs for image and video)
|
||||
- **Visual LoRA Tags**: See connected LoRAs as clickable tags with strength values
|
||||
- **Toggle LoRAs On/Off**: Click any LoRA tag to enable/disable it without disconnecting
|
||||
- **Editable Strengths**: Click the strength value on any tag to adjust it inline
|
||||
- **Trigger Words Support**: Save and display trigger words alongside prompts and LoRAs; can use [ComfyUI-Lora-Manager](https://github.com/infantesimone/ComfyUI-Lora-Manager) trigger words.
|
||||
- **Right-Click to Delete**: Right-click any LoRA or trigger word tag to remove it
|
||||
- **Save LoRAs with Prompts**: When you save a prompt, the current LoRA configuration is saved with it
|
||||
- **Override Mode**: Toggle "Override Lora" to ignore connected inputs and use only saved preset LoRAs
|
||||
- **Merge Mode**: When override is off, connected LoRAs are merged with saved presets
|
||||
- **Workflow Data Input**: Optional workflow_data input from Workflow Builder or Prompt Extractor, with use_workflow_data toggle support to use extracted prompt and LoRA stacks directly in PMA
|
||||
- **LoRA Manager Integration**: If [ComfyUI-Lora-Manager](https://github.com/infantesimone/ComfyUI-Lora-Manager) is installed, hovering over LoRA tags shows preview images
|
||||
- **Missing LoRA Detection**: LoRAs that aren't found on your system are highlighted in red
|
||||
- **Thumbnail Generation**: Right-click any prompt to generate a thumbnail using a selectable checkpoint model. Model choice persists in ComfyUI preferences.
|
||||
|
||||
### Apply LoRA Stack:
|
||||
- **Simple LoRA Application**: Takes a LORA_STACK and applies it to your model/clip
|
||||
- **Works with Any Stacker**: Compatible with LoRA Manager's stacker or any node outputting LORA_STACK
|
||||
- **Optional CLIP**: CLIP input is optional for workflows that don't need it
|
||||
### Prompt Extractor:
|
||||
- **Extract from Images/Videos**: Load images or videos and extract embedded prompts, LoRAs, and workflow metadata
|
||||
- **Model/Checkpoint Extraction**: Extracts checkpoint and UNET model paths from workflows, with High/Low (A/B) assignment for dual-model setups like Wan video
|
||||
- **A1111/Forge Support**: Parses A1111 parameters format to extract prompts, LoRAs, and model names from Forge/A1111 generated images
|
||||
- **WebP Metadata Support**: Reads EXIF metadata from WebP images (RIFF format parser)
|
||||
- **JSON Workflow Support**: Browse and load JSON workflow files directly to extract prompts and LoRA configurations
|
||||
- **Input/Output Folder Switching**: Toggle between browsing your input or output folder directly from the node
|
||||
- **Dual LoRA Stack Output**: Outputs two separate LoRA stacks for workflows using dual stacking (e.g., Wan video)
|
||||
- **Active LoRA Filtering**: Only extracts LoRAs that are marked as active in the source workflow
|
||||
- **Wide Node Compatibility**: Supports 11+ model loader types including CheckpointLoader, UNETLoader, UnetLoaderGGUF, DiffusionModelLoader, WanVideoModelLoader, CyberdyneModelHub, and more
|
||||
- **Preview in Manager**: View extracted data and repathed LoRAs using Manager Advanced.
|
||||
|
||||
### Prompt Model Loader:
|
||||
- **String-to-Model Loading**: Takes a model path string (from Prompt Extractor) and loads the model directly
|
||||
- **Auto-Detection**: Automatically detects whether the path is a checkpoint (returns MODEL + CLIP + VAE) or diffusion/UNET/GGUF model (returns MODEL only)
|
||||
- **GGUF Support**: Loads GGUF models when [ComfyUI-GGUF](https://github.com/city96/ComfyUI-GGUF) is installed, with automatic runtime detection
|
||||
- **Visual Model Info**: Displays model type badge (Checkpoint/Diffusion/GGUF) and model name directly on the node
|
||||
- **State Persistence**: Model info display and output slot visibility persist across tab switches and workflow reloads
|
||||
- **Graceful Error Handling**: Displays a red "NOT FOUND" badge instead of crashing when a model path cannot be resolved
|
||||
- **Model Path Resolution**: Works with both full paths and relative paths, searching checkpoints, diffusion_models, and unet folders
|
||||
- **Weight Dtype Support**: Optional weight dtype selection for memory optimization
|
||||
- **Family Filtering Tip**: Family filtering works best when model families are separated into clear folder structures (for example folders that include family cues like i2v/t2v/high/low).
|
||||
|
||||
### Prompt Generator
|
||||
- **Three Generation Modes**: Enhance text prompts, analyze images, or analyze images with custom instructions
|
||||
- **Dual Backend Support**: Use llama.cpp (local server, default) or Ollama as the LLM backend
|
||||
- **Prompt Enhancement**: Transform basic prompts into detailed descriptions using local LLMs
|
||||
- **Vision Analysis**: Analyze images with Qwen3VL models to generate detailed descriptions
|
||||
- **Vision Analysis**: Analyze images with vision-capable models to generate detailed descriptions
|
||||
- **Custom Image Analysis**: Provide your own instructions for image analysis
|
||||
- **JSON Output**: Optional structured JSON output with scene breakdown
|
||||
- **Thinking Support**: Support Thinking models to perform deeper generative reasoning.
|
||||
- **Automatic Server Management**: Starts/stops llama.cpp server as needed, with automatic shut off at exit.
|
||||
- **Smart Model Selection**: Auto-selects appropriate model (vision or text) based on mode or Thinking mode.
|
||||
- **Smart Model Selection**: Auto-selects appropriate model based on mode, using mmproj-based vision detection.
|
||||
|
||||
### Prompt Generator Options
|
||||
- **Model Selection**: Choose from local models or download Qwen3, Qwen3VL and Qwen3VL Thinking models from HuggingFace
|
||||
- **Model Selection**: Choose from local models or download Qwen3.5 models from HuggingFace
|
||||
- **Auto-Download**: Automatically downloads both model and required mmproj files for vision models
|
||||
- **LLM Parameters**: Fine-tune temperature, top_k, top_p, min_p, repeat_penalty and context size.
|
||||
- **Custom Instructions**: Override default system prompt for different enhancement styles.
|
||||
- **Extra Image Inputs**: Combine up to 5 images to generate your prompt.
|
||||
- **Console Debugging**: Enable outputing the entire process to the console for debugging purposes.
|
||||
- **Console Debugging**: Enable outputting the entire process to the console for debugging purposes.
|
||||
|
||||
### Preference Options
|
||||
- Set choices for prefered Model for both base mode and VL model.
|
||||
- Set new default model location, previous folder (gguf and llm) will still be scanned, but model will save in new default.
|
||||
- Set custom Location for Llama.cpp. If Llama.cpp was not added to the system Path, this option let's you specify it's location.
|
||||
- Set choices for preferred models for both base mode and vision mode.
|
||||
- Set a new default model location. Previous folders (gguf and llm) are still scanned, but new downloads are saved to the new default.
|
||||
- Set a custom location for Llama.cpp. If Llama.cpp was not added to your system PATH, this option lets you specify its location.
|
||||
- **LLM Backend**: Choose between llama.cpp (default) or Ollama as the generation backend.
|
||||
- **Ollama Settings**: Configure Ollama URL and keep-alive duration for model memory management.
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -103,7 +167,7 @@ If a Custom Model Path is added, it will become the default download folder.
|
||||
```bash
|
||||
brew install llama.cpp
|
||||
```
|
||||
5. If you have them, place your .gguf models in the models/gguf folder or set in prererences your preferred folder path.
|
||||
5. If you have them, place your .gguf models in the models/gguf folder, or set your preferred folder path in preferences.
|
||||
|
||||
6. Restart ComfyUI
|
||||
|
||||
@@ -124,16 +188,19 @@ If a Custom Model Path is added, it will become the default download folder.
|
||||
4. **Toggle LoRAs**: Click a tag to enable/disable that LoRA (disabled tags turn gray)
|
||||
5. **Adjust Strength**: Click the strength number on a tag to edit it inline
|
||||
6. **Save with LoRAs**: Click "Save Prompt" to save both the prompt text and current LoRA configuration
|
||||
7. **Override Mode**: Enable "Override Lora" checkbox to ignore connected inputs and use only the saved preset LoRAs
|
||||
8. **Connect Outputs**: Use `lora_stack_a` and `lora_stack_b` outputs with the Apply LoRA Stack node
|
||||
7. **Workflow Input (Optional)**: Connect workflow_data from Workflow Builder or Prompt Extractor and enable use_workflow_data to use extracted prompt and LoRA stacks in PMA
|
||||
8. **Override Mode**: Enable "Override Lora" checkbox to ignore connected inputs and use only the saved preset LoRAs
|
||||
9. **Connect Outputs**: Use `lora_stack_a` and `lora_stack_b` outputs with the Apply LoRA Stack node
|
||||
|
||||
### Apply LoRA Stack
|
||||
### Prompt Extractor
|
||||
|
||||
1. **Add the Node**: Add Node → Prompt Manager → Apply LoRA Stack
|
||||
2. **Connect Model**: Connect your model (e.g., from Load Checkpoint) to the `model` input
|
||||
3. **Connect LoRA Stack**: Connect a `LORA_STACK` output (from Prompt Manager Advanced or LoRA Manager's stacker)
|
||||
4. **Optional CLIP**: Connect CLIP if your workflow needs it (some video workflows don't)
|
||||
5. **Use Outputs**: Connect the modified model/clip to your sampler or other nodes
|
||||
1. **Add the Node**: Add Node → Prompt Manager → Prompt Extractor
|
||||
2. **Choose Source Folder**: Use the `source_folder` dropdown to browse files from either your **input** or **output** folder
|
||||
3. **Load Media**: Select an image or video from the file browser, or drag-and-drop files onto the node
|
||||
4. **JSON Workflows**: Supports extracting from JSON workflow files directly
|
||||
5. **Extract Data**: The node automatically extracts prompts, LoRAs, and trigger words from embedded metadata
|
||||
6. **View Results**: Extracted positive/negative prompts display in the text outputs, LoRA stacks output as LORA_STACK
|
||||
7. **Use with Manager**: Connect the LoRA stack outputs to Prompt Manager Advanced to view and save the extracted configuration
|
||||
|
||||
|
||||
### Prompt Generator
|
||||
@@ -147,8 +214,8 @@ If a Custom Model Path is added, it will become the default download folder.
|
||||
3. **Connect inputs**: Connect image for vision modes, or just use text for enhancement mode
|
||||
4. **Output as Json**: Use Format_as_Json to experiment with Json prompts.
|
||||
5. **Push the LLM**: Use enable_thinking to enable the model to perform deeper generative reasoning before producing the final prompt.
|
||||
4. **Save memory**: Toggle "stop_server_after" ON to free VRAM after generation
|
||||
5. **Run Workflow**: Generated prompt displays and can be saved to Prompt Manager
|
||||
6. **Save memory**: Toggle "stop_server_after" ON to free VRAM after generation
|
||||
7. **Run Workflow**: Generated prompt displays and can be saved to Prompt Manager
|
||||
|
||||
**Advanced Usage**:
|
||||
1. **Add the Options Node**: Add Node → Prompt Generator Options
|
||||
@@ -160,13 +227,11 @@ If a Custom Model Path is added, it will become the default download folder.
|
||||
7. **Enable Debugging**: Enable complete printout of process to console using show_everything_in_console
|
||||
|
||||
**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)
|
||||
- Qwen3VL-4B-Instruct-Q8_0.gguf: Vision model, balanced performance (~5GB VRAM)
|
||||
- Qwen3VL-8B-Instruct-Q8_0.gguf: Vision model, best quality (~9GB VRAM)
|
||||
- Qwen3VL-4B-Thinking-Q8_0.gguf: Vision model, Thinking variant, balanced performance (~5GB VRAM)
|
||||
- Qwen3VL-8B-Thinking-Q8_0.gguf: Vision model, Thinking variant, best quality (~9GB VRAM)
|
||||
- Qwen3.5-9B-UD-Q4_K_XL.gguf: Unsloth Dynamic 4-bit, good balance (~6GB VRAM)
|
||||
- Qwen3.5-9B-Q8_0.gguf: Standard 8-bit, high quality (~9.5GB VRAM)
|
||||
- Qwen3.5-9B-UD-Q8_K_XL.gguf: Unsloth Dynamic 8-bit, best quality (~13GB VRAM)
|
||||
|
||||
All Qwen3.5 models are unified vision+text — every model supports both text enhancement and image analysis via its mmproj file. Thinking mode is controlled at runtime via a toggle, no separate model variant needed.
|
||||
|
||||
**Model Management**:
|
||||
- Place gguf files in models/gguf folder
|
||||
@@ -174,20 +239,25 @@ If a Custom Model Path is added, it will become the default download folder.
|
||||
|
||||
**Preferences**:
|
||||
Preference settings can be found in ComfyUI Settings → Prompt Manager
|
||||
- **Preferred Base Model**: Name of model used for "Enhance User Prompt" mode (text-only models)
|
||||
- **Preferred Vision Model**: Name of model Used for "Analyze Image" modes (Qwen3VL models)
|
||||
- **Preferred Base Model**: Name of model used for "Enhance User Prompt" mode
|
||||
- **Preferred Vision Model**: Name of model used for "Analyze Image" modes
|
||||
- **Set Default Port** You can set the port used by Llama.cpp
|
||||
- **Close Llama on Exit** By default Llama.cpp with be close on exit.
|
||||
- **Close Llama on Exit** By default Llama.cpp will be closed on exit.
|
||||
- **Hide NSFW by Default**: When enabled, NSFW categories and prompts are hidden from all dropdowns, navigation, and the thumbnail browser
|
||||
- **Default View Mode**: Choose between thumbnail grid or list view for the Advanced prompt browser
|
||||
- **LLM Backend**: Choose between llama.cpp (default) or Ollama
|
||||
- **Ollama URL**: Set the Ollama server address (default: http://127.0.0.1:11434)
|
||||
- **Keep Alive Duration**: How long Ollama keeps the model loaded after a request (e.g. 5m, 30m, 0 for immediate unload)
|
||||
|
||||
## Requirements
|
||||
|
||||
- ComfyUI
|
||||
- Python 3.8+
|
||||
- requests >= 2.31.0
|
||||
- huggingface_hub >= 0.20.0
|
||||
- psutil >= 5.9.0
|
||||
- tqdm >= 4.66.0
|
||||
- Pillow >= 10.0.0
|
||||
- requests
|
||||
- huggingface_hub
|
||||
- psutil
|
||||
- tqdm
|
||||
- Pillow
|
||||
- colorama
|
||||
- llama-server (from llama.cpp)
|
||||
|
||||
@@ -206,7 +276,7 @@ Preference settings can be found in ComfyUI Settings → Prompt Manager
|
||||
- **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
|
||||
- **Solution**: Either place a .gguf file in the `models/` folder, or connect the Prompt Generator Options 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.
|
||||
@@ -215,14 +285,306 @@ Preference settings can be found in ComfyUI Settings → Prompt Manager
|
||||
- **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.
|
||||
- **Solution**: Use a smaller quantized model (Q4 instead of Q8), or toggle 'stop_server_after' to quit llama.cpp after generating a prompt.
|
||||
|
||||
**Problem**: Default Model used is not what I want
|
||||
**Problem**: Default model used is not what I want
|
||||
- **Solution**: You can set your preferred model in the ComfyUI settings. Simply add its full name, with .gguf extension, for both the VL and base models. Enabling Thinking in the Generator might change what is used for VL models.
|
||||
|
||||
|
||||
## Changelog
|
||||
|
||||
### version 2.0.0
|
||||
- **Prompt Manager becomes Prompt + Workflow Manager**
|
||||
- Workflow Manager now allows saving Workflow and is integrated with Prompt Manager save/reuse behavior
|
||||
- Extractor, Builder, and Manager workflow loop now focuses on simplified, reusable workflow cores
|
||||
- Workflow save/reuse behavior aligned with workflow_data-first persistence for consistent prompt and LoRA retention
|
||||
- Documentation updated to reflect full prompt and workflow scope
|
||||
- More polish improvements coming soon
|
||||
|
||||
### version 1.25.0
|
||||
- **Workflow Tools Release Milestone**
|
||||
- Workflow Builder / Workflow Renderer / Workflow Bridge / Workflow Model Loader now form a complete editable workflow pipeline
|
||||
- Improved extractor-to-builder update flow for image/video metadata refresh
|
||||
- Improved Builder dropdown stability and selection persistence on first open
|
||||
- Improved tab-switch persistence for Builder UI state, including LoRA stacks and LoRA state
|
||||
- Improved compatibility when extracting from workflows generated by Builder persistence data
|
||||
|
||||
- **Wan i2v Workflow Quality and UX Improvements**
|
||||
- Better high/low model handling and dual-pass sampler defaults in workflow path
|
||||
- Improved model-family filtering and unsupported-family handling in Builder/Renderer
|
||||
- Improved workflow update diagnostics to simplify troubleshooting of resolution and model propagation
|
||||
|
||||
- **Prompt Manager Advanced Save + Thumbnail Improvements**
|
||||
- Save flow now reuses the full Advanced browser UI (same search, category tools, NSFW/filter handling, and existing prompt selection behavior)
|
||||
- Save action terminology updated to **Save Workflow** for workflow-oriented entries
|
||||
- Save now enforces category selection before submission to avoid uncategorized/invalid saves
|
||||
- Workflow Saver save action now uses failure-only notifications (no success toast spam)
|
||||
- Thumbnail generation now tries Workflow Renderer first when workflow_data is present, with automatic fallback to the basic checkpoint/LoRA thumbnail path
|
||||
- Renderer thumbnail path now forces thumbnail-safe resolution and single-frame batch settings before queueing (consistent size, batch=1)
|
||||
|
||||
### version 1.22.6
|
||||
- **Prompt Extractor now extract Prompt Extractor**
|
||||
- Prompt Extractor now embeds extracted data in the workflow, so it can extract itself.
|
||||
|
||||
### version 1.22.5
|
||||
- **Thumbnail Generation in Prompt Manager Advanced**
|
||||
- Right-click any prompt to generate a thumbnail using a basic KSampler workflow
|
||||
- Checkpoint model selector with filterable list of all available checkpoints
|
||||
- Includes saved LoRAs (both stacks, active only) for more accurate thumbnails
|
||||
- LoRA paths resolved via existing fuzzy matching — renamed LoRAs are found automatically
|
||||
- Random seed on each generation — re-generate to get a different result
|
||||
- Selected checkpoint persists in ComfyUI preferences across sessions
|
||||
- Change model anytime via right-click menu or ComfyUI Settings → Prompt Manager
|
||||
- Spinner overlay during generation with 120s timeout
|
||||
|
||||
- **Improved Model High/Low Detection**
|
||||
- Better detection of embedded high/low indicators in model names (e.g., `tastysinHighV81`, `tastysinLowV81`)
|
||||
|
||||
### version 1.22.1
|
||||
- **Prompt Model Loader Improvements**
|
||||
- Added GGUF model support via runtime detection of [ComfyUI-GGUF](https://github.com/city96/ComfyUI-GGUF) extension
|
||||
- Visual model type badge (Checkpoint/Diffusion/GGUF/NOT FOUND) and model name displayed on the node
|
||||
- CLIP and VAE output slots automatically hidden for non-checkpoint models
|
||||
- State persistence: model info and output slot visibility survive tab switches and workflow reloads
|
||||
- Graceful error handling: shows red "NOT FOUND" badge instead of crashing on missing models
|
||||
- Searches `unet_gguf` folder paths registered by ComfyUI-GGUF
|
||||
|
||||
### version 1.22.0
|
||||
- **New Node: Prompt Model Loader**
|
||||
- Loads checkpoints or diffusion/UNET models from a string path (output by Prompt Extractor)
|
||||
- Auto-detects model type: checkpoints return MODEL + CLIP + VAE, diffusion models return MODEL only
|
||||
- Searches ComfyUI checkpoints, diffusion_models, and unet folders automatically
|
||||
- Optional weight dtype selection for memory optimization
|
||||
|
||||
- **Model/Checkpoint Extraction in Prompt Extractor**
|
||||
- Extracts checkpoint and UNET model paths from workflow metadata
|
||||
- High/Low (A/B) model assignment for dual-model workflows (e.g., Wan video with different models per noise level)
|
||||
- Resolves extracted model names to local file paths using ComfyUI's folder system
|
||||
- Supports 11+ model loader types: CheckpointLoaderSimple, UNETLoader, UnetLoaderGGUF, DiffusionModelLoader, WanVideoModelLoader, CyberdyneModelHub (dual high/low), and more
|
||||
- New `model_a` and `model_b` STRING outputs on the Prompt Extractor node
|
||||
|
||||
- **A1111/Forge Image Support**
|
||||
- Parses `Model:` field from A1111/Forge parameters format (both JS and Python paths)
|
||||
- Extracts model names from images generated by Automatic1111, Forge, and compatible UIs
|
||||
|
||||
- **WebP Metadata Support**
|
||||
- Added RIFF/EXIF parser for reading ComfyUI metadata from WebP images
|
||||
- Fixed EXIF tag reading to use correct tags (0x010e ImageDescription, 0x010f Make) for ComfyUI metadata
|
||||
|
||||
- **Video Metadata Improvements**
|
||||
- Added `comment` tag parsing in ffprobe fallback for videos that store metadata as JSON wrapper
|
||||
|
||||
### version 1.21.2
|
||||
- **Improved Thumbnail Extraction**
|
||||
- prompt extractor: enhance video thumbnail extraction and error handling for unsupported formats
|
||||
|
||||
- **Improve llama-server**
|
||||
- Increase server startup timeout from 30s to 120s for large models
|
||||
- Detect early server crashes and show stderr output to user
|
||||
- Fix _get_model_keywords docstring to reflect version preservation (qwen3.5)
|
||||
|
||||
### version 1.21.1
|
||||
- **Bug Fix** - Fixed issues caused by restructure
|
||||
|
||||
### version 1.21.0
|
||||
- **Removed miscellaneous tools** — Switch Any, Save Video H26x, Apply LoRA Stack, Better Image Loader, and Animated Latent Preview have been moved to a dedicated repository: [ComfyUI-FBnodes](https://github.com/FranckyB/ComfyUI-FBnodes)
|
||||
- **Project restructure** — Organized node files into `nodes/` and utility modules into `py/` for cleaner codebase
|
||||
|
||||
### version 1.20.0
|
||||
- **New Node: Better Image Loader**
|
||||
- Streamlined image and video loader with the same file browser as Prompt Extractor
|
||||
- Browse input or output folders, preview images and videos, scrub through video frames
|
||||
- Drag-and-drop support, single IMAGE output — no metadata extraction or LoRA processing
|
||||
- **Prompt Extractor: Input/Output Folder Switching**
|
||||
- New `source_folder` toggle to browse files from either your input or output directory
|
||||
- File browser, thumbnails, and previews all respect the selected source folder
|
||||
- **Switch Any Bug Fix**
|
||||
- Fixed SwitchAnyBool not triggering upstream node execution
|
||||
- Fixed SwitchAny input names reverting to defaults after execution
|
||||
|
||||
### version 1.19.0
|
||||
- **True Switch Any Node**
|
||||
- Added a 10 input 'True' Switch any node, that takes any inputs, doesn't lock in the type.
|
||||
- Allows rename of inputs using a simple string with all names split using , or ;
|
||||
- True lazy support, any Non selected input is disconnected internally.
|
||||
- **Metadata Json**
|
||||
- Added metadata output, so workflow found can be visualized
|
||||
- **Bug Fix**
|
||||
- Fixed bug where page reload and switching workflow would needlessly refetch the prompt.
|
||||
|
||||
### version 1.18.0
|
||||
- **Thumbnail Hover Preview**
|
||||
- Intelligent delay system: 1000ms initial, then 50ms for fast browsing (resets after 2s inactivity)
|
||||
- Preference toggle in ComfyUI Settings and browser UI (🔍 Preview / 🔍 Off)
|
||||
- Auto-scroll to selected prompt when browser opens
|
||||
- **Improved Thumbnail Quality**
|
||||
- Increased resolution to 200x200 (up from 128x128) with aspect ratio preservation
|
||||
- Optimized JSON storage format
|
||||
|
||||
### version 1.17.6
|
||||
- **Swap LoRA Stack Outputs**
|
||||
- Added `swap_lora_outputs` toggle to swap LoRA Stack A and B outputs
|
||||
- Useful for quickly testing different LoRA configurations in dual-stack workflows
|
||||
- **LoRA Input Handling Fixes**
|
||||
- Fixed issue when no LoRA input was connected: toggling LoRAs off would cause the list to refresh and revert the toggle state
|
||||
- Fixed inability to set LoRA strength to 0 (zero values were incorrectly replaced with 1.0)
|
||||
- Fixed saving prompts to use current displayed state instead of re-querying connected inputs
|
||||
- Added automatic cleanup of input-derived LoRAs when they're no longer present in the connected input
|
||||
- Improving `use_lora_input` toggle behavior to properly remove input-derived LoRAs when switching OFF while preserving preset LoRA toggle states
|
||||
|
||||
### version 1.17.5
|
||||
- **Browser Context Menu Enhancements**
|
||||
- Added "Delete Prompt", "Rename and Move Prompt" option to prompt right-click menu in the thumbnail browser
|
||||
- Added "Delete Category", "Rename Category" options to category right-click menu
|
||||
- Added "+" button at the end of the category list to create new categories directly from the browser
|
||||
- All browser operations preserve unsaved prompt state (text, loras, trigger words are not reset)
|
||||
- **Streamlined More Dropdown**
|
||||
- Removed Rename Category, New Category, Delete Category, and Delete Prompt from the "More" dropdown (now accessible via browser context menus)
|
||||
|
||||
### version 1.17.0
|
||||
- **NSFW Tagging & Filtering**
|
||||
- Mark entire categories or individual prompts as NSFW
|
||||
- Visual red "NSFW" badge on the Prompt Manager node title bar and on the Advanced prompt selector
|
||||
- NSFW badge appears on all prompts within an NSFW-tagged category in the thumbnail browser
|
||||
- Category buttons show red border for NSFW categories in the thumbnail browser
|
||||
- Global preference to hide/show NSFW content — filters dropdowns, navigation arrows, and browser
|
||||
- Session-persistent NSFW toggle button in the Advanced thumbnail browser
|
||||
- Toggle NSFW on categories and prompts via context menu or the save/new category dialogs
|
||||
- **List View Mode**
|
||||
- New compact list view alternative to the thumbnail grid in the Advanced prompt browser
|
||||
- Toggle between grid and list view with a button in the browser controls bar
|
||||
- View mode preference is session-persistent
|
||||
- Default view mode configurable in ComfyUI settings
|
||||
- **UI Improvements**
|
||||
- Search input moved into the controls bar with a clear (×) button
|
||||
- Separator line between category buttons and prompt content
|
||||
|
||||
### version 1.16.0
|
||||
- **Ollama Support**
|
||||
- Added Ollama as an alternative LLM backend alongside llama.cpp
|
||||
- Auto-discovers available Ollama models when no model is explicitly configured
|
||||
- Keep-alive duration setting controls how long Ollama keeps the model loaded in memory
|
||||
- "Stop server after" toggle unloads the model from Ollama memory to free VRAM
|
||||
- **Upgraded to Qwen3.5 Models**
|
||||
- Replaced Qwen3/Qwen3VL models with unified Qwen3.5-9B (vision+text in one model)
|
||||
- Three download options: UD-Q4_K_XL (~6GB), Q8_0 (~9.5GB), UD-Q8_K_XL (~13GB)
|
||||
- Thinking mode is now a runtime toggle — no separate model variant needed
|
||||
- **mmproj-Based Vision Detection**
|
||||
- Vision model detection no longer relies on "VL" in the filename
|
||||
- Models are identified as vision-capable based on the presence of an mmproj file
|
||||
- Heuristic matching supports user-provided models outside the predefined registry
|
||||
- Backward compatible with existing Qwen3VL models and their mmproj files
|
||||
- **Bug Fixes**
|
||||
- Fixed seed control_after_generate not working (increment/decrement/randomize)
|
||||
- Improved Prompt Extractor detection logic
|
||||
|
||||
### version 1.15.9
|
||||
- **Bug Fixes**
|
||||
- Improved Prompt Extractor, enhanced detection logic
|
||||
|
||||
### version 1.15.7
|
||||
- **Added Rename Category Option**
|
||||
- **Bug Fixes**
|
||||
|
||||
### version 1.15.6
|
||||
- **Video Metadata Reader - VHS Compatible**
|
||||
- Added capability to read metadata from VideoHelperSuite generated videos.
|
||||
|
||||
### version 1.15.5
|
||||
- **Added get video components+ node**
|
||||
- Since our save video node can saves latents, this also returns the matching latent (if found) and filepath.
|
||||
- **Video Preview in Prompt Extractor**
|
||||
- Added the option to preview in fullscreen with dark overlay for both images and video on the Prompt Extractor node.
|
||||
|
||||
### version 1.15.0
|
||||
- **Added Animated Latent Preview**
|
||||
- Added Similar option to VideoHelperSuite, to display animated Latent preview. With the addition that it works in TAESD mode.
|
||||
- Check for VideoHelperSuite node, so not to conflict with it. (Will do nothing if installed)
|
||||
|
||||
### version 1.14.5
|
||||
- **Added Save Latent support to Save Video node**
|
||||
- allows to save the full data of a generation to then experiment without the need to regenerate.
|
||||
- added some very quick workflow examples.
|
||||
-A simplified version of my Wan workflow
|
||||
-A basic Z-Image base workflow with Prompt Generator.
|
||||
- Small bug fixes
|
||||
|
||||
### version 1.14.0
|
||||
- **Addition of a "Save Video H264/H265" node, that replicates ComfyUI's Video Node**
|
||||
- Adds choice between H264/H265
|
||||
- Choice of Chroma Subsampling between yuv420, yuv422, yuv444
|
||||
- Can set Constant Rate Factor (compression level)
|
||||
- Generates a quick proxy video if chosen format could not play in browser (H265 + yuv422 or H265 + yuv444)
|
||||
- Unlike VideoHelperSuite, clip with Audio also include Metadata. Which can then be used with Prompt Extractor.
|
||||
|
||||
### version 1.13.5
|
||||
- Added browse window with thumbnails in Extractor, with cache system for speedup.
|
||||
- Bug fix for issue caused by new additions.
|
||||
|
||||
### version 1.12.7
|
||||
- Quality of life improvements and added option to change the strength of any LoRA in Manager, so we can tweak extracted workflows live.
|
||||
|
||||
### version 1.12.6
|
||||
- Tweak to caching behavior for prompt extractor and prompt manager advanced
|
||||
|
||||
### version 1.12.5
|
||||
- Some dependencies to FFMpeg were still present, remove them and added a frame_position value, so we can specify what frame to get from video.
|
||||
|
||||
### version 1.12.0
|
||||
- Prompt Extractor: Added Lora inputs, so it can be used as a passthrough, with a None Choice at top, to easily deactivate it.
|
||||
- Prompt Extractor: Improved logic for determining positive prompts in workflow.
|
||||
- Prompt Extractor: Improved logic for finding High and Low Lora Stacks
|
||||
- Prompt Manager Advanced: Added Fuzzy Logic to find Loras that might have been renamed
|
||||
- Prompt Manager Advanced: Fixed issue of Lora buttons getting cleared when changing tab.
|
||||
|
||||
### Version 1.11.5
|
||||
- Slight adjustement to extractor node, gets metadata in a method more consistent with ComfyUI, removing need for ffmpeg for videos.
|
||||
|
||||
### Version 1.11.2
|
||||
- Slight adjustement to extractor node to behave exactly like the Load image node, while also supporting Videos. (With extract first frame support)
|
||||
|
||||
### Version 1.11.0
|
||||
- **New Node: Prompt Extractor** - Extract prompts and LoRA configurations from images, videos, and JSON workflows
|
||||
- Loads embedded metadata from PNG, JPEG, WebP images and MP4 videos
|
||||
- Browse and load JSON workflow files directly
|
||||
- Dual LoRA stack output for workflows using two stacks (e.g., Wan video)
|
||||
- Filters inactive LoRAs - only extracts LoRAs marked as active
|
||||
- Supports extraction from CLIP Text Encode, samplers, and LoRA stackers
|
||||
- Compatible with Power Lora Loader, WanMoeKSamplerAdvanced, and other common nodes
|
||||
- **Prompt Thumbnails** - Save thumbnail images with prompts in Prompt Manager Advanced
|
||||
- Visual identification of prompts in the dropdown selector
|
||||
- Thumbnails stored alongside prompt data for easy management
|
||||
- **Simplified "New Prompt" button**
|
||||
- Now clears fields immediately without asking for a name
|
||||
- Enter the name when saving instead of when creating
|
||||
- Keeps you in the current category for faster workflow
|
||||
- **Bug fixes and improvements**
|
||||
- Fixed JSON workflow file path resolution
|
||||
- Improved LoRA extraction for complex workflows
|
||||
|
||||
### Version 1.10.0
|
||||
- **Unified UI for Prompt Manager and Prompt Manager Advanced**
|
||||
- Three-button layout: Save Prompt, New Prompt, and More (dropdown menu)
|
||||
- New Prompt button creates a temporary prompt that isn't saved until you click Save Prompt
|
||||
- Save Prompt opens a modal with category selection (create new or select existing)
|
||||
- More dropdown includes: Import JSON, Export JSON, Delete Prompt, Delete Category
|
||||
- **Import/Export JSON functionality**
|
||||
- Export all prompts to a JSON file
|
||||
- Import prompts with Merge (add to existing) or Replace (overwrite all) options
|
||||
- Proper cancel handling without false success messages
|
||||
- **Multi-tab synchronization**
|
||||
- Changing category or prompt reloads data from server
|
||||
- Prevents conflicts when editing prompts in multiple browser tabs
|
||||
- **Prompt Manager now preserves LoRA data**
|
||||
- LoRA stacks, trigger words, and active states are preserved when saving from basic Prompt Manager
|
||||
- Seamless compatibility between Prompt Manager and Prompt Manager Advanced
|
||||
- **Trigger Words support in Prompt Manager Advanced**
|
||||
- Save and restore trigger words alongside prompts and LoRAs
|
||||
- Trigger words display as editable text when loading saved prompts
|
||||
- **Improved unsaved changes detection**
|
||||
- Warning when switching away from newly created (unsaved) prompts
|
||||
- Cancel button properly reverts dropdown to previous selection
|
||||
|
||||
### Version 1.9.0
|
||||
- **New Node: Prompt Manager Advanced** - Extended prompt manager with LoRA stack support
|
||||
- Dual LoRA stack inputs/outputs for complex workflows (Wan video, etc.)
|
||||
|
||||
@@ -1,37 +1,56 @@
|
||||
"""
|
||||
ComfyUI Prompt Manager - A simple custom node for saving and reusing prompts
|
||||
A prompt management system for ComfyUI with LLM input support
|
||||
ComfyUI Prompt Manager - A comprehensive prompt and workflow management system for ComfyUI.
|
||||
Features: prompt & workflow management, LoRA stacks, workflow extraction, workflow generation.
|
||||
"""
|
||||
__version__ = "1.9.1"
|
||||
__version__ = "2.0.0"
|
||||
__author__ = "François Beaudry"
|
||||
__license__ = "MIT"
|
||||
|
||||
from .prompt_manager import PromptManager
|
||||
from .prompt_manager_advanced import PromptManagerAdvanced
|
||||
from .prompt_generator import PromptGenerator
|
||||
from .prompt_generator_options import PromptGenOptions
|
||||
from .apply_lora_stack import ApplyLoRAStack
|
||||
from .model_manager import get_local_models
|
||||
from server import PromptServer
|
||||
from .nodes.apply_lora import ApplyLoraPlusPlus
|
||||
from .nodes.prompt_manager_adv import PromptManagerAdvanced
|
||||
from .nodes.prompt_manager_basic import PromptManager
|
||||
from .nodes.prompt_generator import PromptGenerator
|
||||
from .nodes.prompt_generator_options import PromptGenOptions
|
||||
from .nodes.prompt_extractor import PromptExtractor
|
||||
from .nodes.prompt_extractor import WorkflowExtractor
|
||||
from .nodes.workflow_builder import WorkflowBuilder
|
||||
from .nodes.workflow_renderer import WorkflowRenderer
|
||||
from .nodes.workflow_bridge import WorkflowBridge
|
||||
from .nodes.workflow_model_loader import WorkflowModelLoader
|
||||
from .nodes.workflow_manager import WorkflowManager
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"PromptManager": PromptManager,
|
||||
"PromptApplyLora": ApplyLoraPlusPlus,
|
||||
"PromptManagerAdvanced": PromptManagerAdvanced,
|
||||
"PromptGenerator": PromptGenerator,
|
||||
"PromptGenOptions": PromptGenOptions,
|
||||
"ApplyLoRAStack": ApplyLoRAStack
|
||||
"PromptManager": PromptManager,
|
||||
"PromptGenerator": PromptGenerator,
|
||||
"PromptGenOptions": PromptGenOptions,
|
||||
"PromptExtractor": PromptExtractor,
|
||||
"WorkflowExtractor": WorkflowExtractor,
|
||||
"WorkflowBuilder": WorkflowBuilder,
|
||||
"WorkflowRenderer": WorkflowRenderer,
|
||||
"WorkflowBridge": WorkflowBridge,
|
||||
"WorkflowModelLoader": WorkflowModelLoader,
|
||||
"WorkflowManager": WorkflowManager,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"PromptManager": "Prompt Manager",
|
||||
"PromptManagerAdvanced": "Prompt Manager Advanced",
|
||||
"PromptGenerator": "Prompt Generator",
|
||||
"PromptGenOptions": "Prompt Generator Options",
|
||||
"ApplyLoRAStack": "Apply LoRA Stack"
|
||||
"PromptApplyLora": "Apply LoRA++",
|
||||
"PromptManagerAdvanced": "Prompt Manager",
|
||||
"PromptManager": "Prompt Manager (Basic)",
|
||||
"PromptGenerator": "Prompt Generator",
|
||||
"PromptGenOptions": "Prompt Generator Options",
|
||||
"PromptExtractor": "Prompt Extractor",
|
||||
"WorkflowExtractor": "Workflow Extractor",
|
||||
"WorkflowBuilder": "Workflow Builder",
|
||||
"WorkflowRenderer": "Workflow Renderer",
|
||||
"WorkflowBridge": "Workflow Bridge",
|
||||
"WorkflowModelLoader": "Workflow Model Loader",
|
||||
"WorkflowManager": "Workflow Manager",
|
||||
}
|
||||
|
||||
WEB_DIRECTORY = "./js"
|
||||
|
||||
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', 'WEB_DIRECTORY']
|
||||
|
||||
print("[PromptManager] Node registered successfully")
|
||||
print("[PromptManager] Nodes registered: Apply LoRA++, Prompt Manager (Basic), Prompt Manager, Prompt Generator, Prompt Generator Options, Prompt Extractor, Workflow Extractor, Workflow Builder, Workflow Renderer, Workflow Bridge, Workflow Model Loader, Workflow Manager")
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
"""
|
||||
ComfyUI Apply LoRA Stack - Apply a LORA_STACK to model and clip
|
||||
"""
|
||||
import folder_paths
|
||||
import comfy.sd
|
||||
import comfy.utils
|
||||
|
||||
|
||||
class ApplyLoRAStack:
|
||||
"""
|
||||
Apply a LoRA stack to a model and optionally a CLIP.
|
||||
Takes a LORA_STACK (list of tuples) and applies each LoRA sequentially.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"model": ("MODEL",),
|
||||
"lora_stack": ("LORA_STACK",),
|
||||
},
|
||||
"optional": {
|
||||
"clip": ("CLIP",),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL", "CLIP")
|
||||
RETURN_NAMES = ("model", "clip")
|
||||
FUNCTION = "apply_stack"
|
||||
CATEGORY = "Prompt Manager"
|
||||
|
||||
def apply_stack(self, model, lora_stack, clip=None):
|
||||
if not lora_stack:
|
||||
return (model, clip)
|
||||
|
||||
model_out = model
|
||||
clip_out = clip
|
||||
|
||||
for lora_name, model_strength, clip_strength in lora_stack:
|
||||
# Skip if no strength
|
||||
if model_strength == 0 and clip_strength == 0:
|
||||
continue
|
||||
|
||||
# Get the LoRA path
|
||||
lora_path = folder_paths.get_full_path("loras", lora_name)
|
||||
if lora_path is None:
|
||||
print(f"[ApplyLoRAStack] Warning: LoRA not found: {lora_name}")
|
||||
continue
|
||||
|
||||
# Load the LoRA
|
||||
lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
|
||||
|
||||
# Apply to model and clip
|
||||
model_out, clip_out = comfy.sd.load_lora_for_models(
|
||||
model_out, clip_out, lora, model_strength, clip_strength
|
||||
)
|
||||
|
||||
return (model_out, clip_out)
|
||||
@@ -0,0 +1,38 @@
|
||||
import sys, json, subprocess, io
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
|
||||
# Check videos with missing loader types
|
||||
test_files = {
|
||||
'DiffusionModelLoaderKJ': r'D:\ComfyUI-Dev\input\Workflow\Vids\2026_01_08_60FPS_00002.mp4',
|
||||
'WanVideoModelLoader': r'D:\ComfyUI-Dev\input\Workflow\Vids\vid_00061.mp4',
|
||||
'SeaArtUnetLoader': r'D:\ComfyUI-Dev\input\Workflow\Vids\25439d30-d0d7-4dd4-b64c-b46345c76351.mp4',
|
||||
'CyberdyneModelHub': r'D:\ComfyUI-Dev\input\Workflow\Vids\d39dbdc3-f08c-44e1-bd4c-410ecb08d3c9.mp4',
|
||||
'CheckpointInNum': r'D:\ComfyUI-Dev\input\Workflow\Vids\num__00168.mp4',
|
||||
}
|
||||
|
||||
for label, f in test_files.items():
|
||||
print(f"\n=== {label} ===")
|
||||
r = subprocess.run(['ffprobe','-v','quiet','-print_format','json','-show_format',f], capture_output=True, text=True, timeout=10)
|
||||
data = json.loads(r.stdout)
|
||||
tags = data['format']['tags']
|
||||
|
||||
# Try direct tags first, then comment
|
||||
prompt = tags.get('prompt')
|
||||
if not prompt:
|
||||
comment = tags.get('comment', '{}')
|
||||
comment_data = json.loads(comment)
|
||||
prompt = comment_data.get('prompt', '{}')
|
||||
|
||||
if isinstance(prompt, str):
|
||||
prompt = json.loads(prompt)
|
||||
|
||||
targets = ['Diffusion', 'Wan', 'SeaArt', 'Cyberdyne', 'Checkpoint', 'UNET', 'Unet', 'Model']
|
||||
for nid, ndata in prompt.items():
|
||||
ct = ndata.get('class_type', '')
|
||||
if 'Cyberdyne' in ct or ct == 'Wan_Cyberdyne_Genisys':
|
||||
inputs = ndata.get('inputs', {})
|
||||
inp_str = json.dumps(inputs)
|
||||
if len(inp_str) > 800:
|
||||
inp_str = inp_str[:800] + '...'
|
||||
print(f" Node {nid}: {ct}")
|
||||
print(f" inputs: {inp_str}")
|
||||
@@ -0,0 +1,189 @@
|
||||
# ComfyUI Tab Switch & State Persistence
|
||||
|
||||
## How ComfyUI handles tab switches
|
||||
|
||||
When a user switches browser tabs (or ComfyUI workflow tabs) and returns, ComfyUI **destroys and recreates all nodes**. The sequence is:
|
||||
|
||||
1. `onNodeCreated` fires (synchronous — rebuilds all DOM, widgets, state variables from scratch)
|
||||
2. `onConfigure` fires immediately after (synchronous — receives serialized `info` with `properties` and `widgets_values`)
|
||||
|
||||
This means **any JS variable stored on the node object is lost**. Only data serialized into the workflow JSON survives.
|
||||
|
||||
## What gets serialized in workflow JSON
|
||||
|
||||
Each node in the workflow JSON has:
|
||||
- `properties` — an object directly on the node, serialized as-is
|
||||
- `widgets_values` — an array of widget values (index-based, fragile if widget order changes)
|
||||
- `pos`, `size`, `flags` — layout info
|
||||
|
||||
## The correct pattern (node.properties)
|
||||
|
||||
### Store durable state in `node.properties`
|
||||
|
||||
```js
|
||||
// In syncHidden (called on every user interaction):
|
||||
node.properties ||= {};
|
||||
node.properties.my_state_key = JSON.stringify(stateObject);
|
||||
```
|
||||
|
||||
`node.properties` is **directly serialized** in the workflow JSON `"properties"` field. It survives:
|
||||
- Tab switches
|
||||
- Page refreshes
|
||||
- Workflow save/load
|
||||
- Copy/paste
|
||||
|
||||
### Restore in onConfigure (synchronously)
|
||||
|
||||
```js
|
||||
nodeType.prototype.onConfigure = function (info) {
|
||||
origConfigure?.apply(this, arguments);
|
||||
const node = this;
|
||||
|
||||
// Set flag SYNCHRONOUSLY — blocks onNodeCreated's async callbacks
|
||||
node._configuredFromWorkflow = true;
|
||||
|
||||
// Read from node.properties (already restored by LiteGraph)
|
||||
const props = node.properties || {};
|
||||
const savedState = props.my_state_key;
|
||||
|
||||
// Restore UI synchronously — no setTimeout, no API calls
|
||||
if (savedState) {
|
||||
const state = JSON.parse(savedState);
|
||||
restoreUI(node, state);
|
||||
}
|
||||
|
||||
// Recalculate heights AFTER restoring UI
|
||||
if (node._weRecalc) node._weRecalc();
|
||||
node.setDirtyCanvas(true, true);
|
||||
};
|
||||
```
|
||||
|
||||
### Guard onNodeCreated's async work
|
||||
|
||||
```js
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
// ... build DOM, create widgets ...
|
||||
|
||||
// Async init — only for FRESH node creation
|
||||
const initImg = getWidgetValue("image");
|
||||
if (initImg) {
|
||||
setTimeout(() => {
|
||||
// _configuredFromWorkflow was set synchronously by onConfigure
|
||||
// before this setTimeout fires
|
||||
if (!node._configuredFromWorkflow) doInitialLoad(initImg);
|
||||
}, 300);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
## Critical rules
|
||||
|
||||
1. **NEVER use setTimeout in onConfigure** — it creates race conditions with onNodeCreated's async work
|
||||
2. **NEVER make API/network calls in onConfigure** — restore purely from serialized data
|
||||
3. **NEVER reload images/thumbnails in onConfigure** — causes DOM flash and height reset
|
||||
4. **ALWAYS call recalcHeight after restore** — otherwise the node stays at its empty initial size
|
||||
5. **ALWAYS persist state on every user interaction** — syncHidden must write to node.properties immediately
|
||||
6. **ALWAYS persist state after doExtract** — so even before user changes anything, the extracted data is saved
|
||||
7. **Use a permanent flag** (`_configuredFromWorkflow`) — set it in onConfigure, never clear it. It only needs to block the initial async load in onNodeCreated.
|
||||
|
||||
## Why widgets_values is unreliable
|
||||
|
||||
- Index-based: if you splice widgets (e.g., adding a Browse button), indices shift
|
||||
- DOM widgets with `serialize: false` still take a slot
|
||||
- Widget order depends on Python INPUT_TYPES + JS modifications
|
||||
- `node.properties` is a named key-value store — no index alignment issues
|
||||
|
||||
## What we store in properties
|
||||
|
||||
For the Workflow Extractor node:
|
||||
- `we_override_data` — JSON of all user overrides (model, sampler, prompts, section states, family)
|
||||
- `we_lora_state` — JSON of LoRA toggle states
|
||||
- `we_extracted_cache` — JSON of the full extracted data (avoids API call on restore)
|
||||
|
||||
We also write to the hidden widgets (`override_data`, `lora_state`, `extracted_cache`) for Python execution, but `node.properties` is the source of truth for tab persistence.
|
||||
|
||||
## Reference: PM Advanced pattern
|
||||
|
||||
The Prompt Manager Advanced node uses this exact pattern:
|
||||
- `_configuredFromWorkflow = true` set synchronously in onConfigure
|
||||
- State restored from `info.widgets_values` (works for PM Advanced because it doesn't splice widgets)
|
||||
- DOM widgets reattached synchronously
|
||||
- Only async work is data loading (not state restoration)
|
||||
- The flag permanently blocks onNodeCreated's async `loadPromptData` callback
|
||||
|
||||
## Do NOT use visibilitychange
|
||||
|
||||
The `visibilitychange` event is NOT needed. PM Advanced doesn't use it. ComfyUI's own lifecycle (onNodeCreated → onConfigure) handles everything. Adding `visibilitychange` listeners causes extra work that fights against the restore flow.
|
||||
|
||||
## DOM Widget Sizing — Critical Rules
|
||||
|
||||
When a node uses `addDOMWidget` with a container holding sections/content, sizing is the #1 source of bugs. Follow these rules:
|
||||
|
||||
### The Problem: Flex Shrinking
|
||||
|
||||
LiteGraph constrains widget containers to the node's current height. If your root container uses `display: flex; flex-direction: column`, child elements will **shrink to fit** inside the constrained container. Then `scrollHeight` / `offsetHeight` report the *compressed* height, `computeSize` returns that small value to LiteGraph, and the node collapses to nothing in a feedback loop.
|
||||
|
||||
### The Fix: `flexShrink: "0"` on all children
|
||||
|
||||
Every direct child of the root flex container (sections, cards, etc.) must have `flexShrink: "0"`. This prevents compression, forces overflow, and makes `scrollHeight` report the **true** content height.
|
||||
|
||||
```js
|
||||
// In makeSection():
|
||||
const wrap = makeEl("div", {
|
||||
borderRadius: "6px", overflow: "hidden", marginTop: "2px",
|
||||
backgroundColor: C.bgCard, flexShrink: "0", // ← CRITICAL
|
||||
});
|
||||
```
|
||||
|
||||
### computeSize must use scrollHeight, not offsetHeight
|
||||
|
||||
- `offsetHeight` — reports the *clipped* height (what the parent container allows)
|
||||
- `scrollHeight` — reports the full *intrinsic* content height (what the content actually needs)
|
||||
|
||||
```js
|
||||
domW.computeSize = function (nodeWidth) {
|
||||
const h = root.scrollHeight || 800;
|
||||
return [nodeWidth, h];
|
||||
};
|
||||
```
|
||||
|
||||
### Use requestAnimationFrame, not setTimeout
|
||||
|
||||
After DOM mutations (adding LoRA tags, showing/hiding rows), call `_resizeNode` via `requestAnimationFrame` — not `setTimeout`. RAF guarantees the browser has reflowed the DOM, so `scrollHeight` is accurate.
|
||||
|
||||
```js
|
||||
if (node._weRecalc) requestAnimationFrame(() => node._weRecalc());
|
||||
```
|
||||
|
||||
### Reference: PMA's approach
|
||||
|
||||
PMA avoids this problem entirely by using **multiple separate DOM widgets** (one per section), each with their own `computeSize`. LiteGraph sums them naturally. WG uses a single DOM widget with a flex container, so the `flexShrink: "0"` + `scrollHeight` approach is required instead.
|
||||
|
||||
### _resizeNode pattern
|
||||
|
||||
```js
|
||||
function _resizeNode() {
|
||||
const domH = root.scrollHeight || 800;
|
||||
const needed = domH + NATIVE_H;
|
||||
if (node.size) {
|
||||
const w = Math.max(MIN_W, node.size[0]);
|
||||
const h = Math.max(needed, MIN_H);
|
||||
if (node.size[0] !== w || node.size[1] !== h) {
|
||||
node.setSize([w, h]);
|
||||
}
|
||||
}
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
}
|
||||
```
|
||||
|
||||
### onResize for enforcing minimums
|
||||
|
||||
```js
|
||||
const origOnResize = node.onResize;
|
||||
node.onResize = function (size) {
|
||||
const domH = root.scrollHeight || 800;
|
||||
size[0] = Math.max(MIN_W, size[0]);
|
||||
size[1] = Math.max(domH + NATIVE_H, MIN_H, size[1]);
|
||||
if (origOnResize) return origOnResize.apply(this, arguments);
|
||||
};
|
||||
```
|
||||
|
After Width: | Height: | Size: 387 KiB |
|
Before Width: | Height: | Size: 58 KiB After Width: | Height: | Size: 120 KiB |
|
After Width: | Height: | Size: 229 KiB |
|
After Width: | Height: | Size: 359 KiB |
|
After Width: | Height: | Size: 267 KiB |
|
After Width: | Height: | Size: 254 KiB |
|
After Width: | Height: | Size: 229 KiB |
@@ -0,0 +1,767 @@
|
||||
/**
|
||||
* File Browser Modal for PromptExtractor
|
||||
* Shows thumbnails of files in input directory
|
||||
*/
|
||||
import { PM_UI_PALETTE as UI } from './ui_palette.js';
|
||||
|
||||
// Track current subfolder for navigation
|
||||
let currentSubfolder = '';
|
||||
// Track current source folder (input or output)
|
||||
let currentSourceFolder = 'input';
|
||||
|
||||
export function createFileBrowserModal(currentFile, onFileSelect, sourceFolder) {
|
||||
// Store source folder
|
||||
currentSourceFolder = sourceFolder || 'input';
|
||||
// If a file is currently selected and lives in a subfolder, open in that folder
|
||||
if (currentFile && currentFile.includes('/')) {
|
||||
currentSubfolder = currentFile.substring(0, currentFile.lastIndexOf('/'));
|
||||
} else {
|
||||
currentSubfolder = '';
|
||||
}
|
||||
|
||||
// Create modal overlay
|
||||
const overlay = document.createElement('div');
|
||||
overlay.className = 'prompt-extractor-browser-overlay';
|
||||
overlay.style.cssText = `
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: ${UI.overlay};
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 10000;
|
||||
`;
|
||||
|
||||
// Create modal container (match PromptManagerAdvanced styling)
|
||||
const modal = document.createElement('div');
|
||||
modal.className = 'prompt-extractor-browser-modal';
|
||||
modal.style.cssText = `
|
||||
background: ${UI.panel};
|
||||
border: 1px solid ${UI.panelBorder};
|
||||
border-radius: 6px;
|
||||
width: 90%;
|
||||
max-width: 1200px;
|
||||
height: 80%;
|
||||
max-height: 800px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
`;
|
||||
|
||||
// Create header
|
||||
const header = document.createElement('div');
|
||||
header.style.cssText = `
|
||||
padding: 15px 20px;
|
||||
border-bottom: 1px solid ${UI.sectionBorder};
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
`;
|
||||
|
||||
const topRow = document.createElement('div');
|
||||
topRow.style.cssText = 'display: flex; justify-content: space-between; align-items: center;';
|
||||
topRow.innerHTML = `
|
||||
<h3 style="margin: 0; color: #d3d7de;">Select File from ${currentSourceFolder === 'output' ? 'Output' : 'Input'} Folder</h3>
|
||||
<div style="display: flex; gap: 10px; align-items: center;">
|
||||
<button class="regenerate-cache-btn" style="
|
||||
background: ${UI.buttonBg};
|
||||
border: 1px solid ${UI.inputBorder};
|
||||
border-radius: 6px;
|
||||
color: #ccc;
|
||||
padding: 5px 12px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
">Regenerate Cache</button>
|
||||
<button class="close-btn" style="
|
||||
background: none;
|
||||
border: none;
|
||||
color: #aaa;
|
||||
font-size: 24px;
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
">×</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const breadcrumb = document.createElement('div');
|
||||
breadcrumb.className = 'folder-breadcrumb';
|
||||
breadcrumb.style.cssText = `font-size: 12px; color: ${UI.textHint}; cursor: pointer;`;
|
||||
breadcrumb.textContent = `${currentSourceFolder}/`;
|
||||
breadcrumb.onclick = () => {
|
||||
if (currentSubfolder) {
|
||||
currentSubfolder = '';
|
||||
loadFileThumbnails(gridContainer, currentFile, onFileSelect, overlay, breadcrumb);
|
||||
}
|
||||
};
|
||||
|
||||
header.appendChild(topRow);
|
||||
header.appendChild(breadcrumb);
|
||||
|
||||
// Create search/filter bar
|
||||
const filterBar = document.createElement('div');
|
||||
filterBar.style.cssText = `
|
||||
padding: 10px 20px;
|
||||
border-bottom: 1px solid ${UI.sectionBorder};
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
`;
|
||||
filterBar.innerHTML = `
|
||||
<input type="text" placeholder="Search files..." class="search-input" style="
|
||||
flex: 1;
|
||||
padding: 8px 12px;
|
||||
background: ${UI.inputBg};
|
||||
border: 1px solid ${UI.inputBorder};
|
||||
border-radius: 6px;
|
||||
color: #ccc;
|
||||
">
|
||||
<select class="filter-type" style="
|
||||
padding: 8px 12px;
|
||||
background: ${UI.inputBg};
|
||||
border: 1px solid ${UI.inputBorder};
|
||||
border-radius: 6px;
|
||||
color: #ccc;
|
||||
">
|
||||
<option value="all">All Files</option>
|
||||
<option value="image">Images</option>
|
||||
<option value="video">Videos</option>
|
||||
<option value="json">JSON</option>
|
||||
</select>
|
||||
`;
|
||||
|
||||
// Create thumbnail grid container
|
||||
const gridContainer = document.createElement('div');
|
||||
gridContainer.className = 'thumbnail-grid';
|
||||
gridContainer.style.cssText = `
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 20px;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
|
||||
gap: 15px;
|
||||
align-content: start;
|
||||
`;
|
||||
|
||||
// Create loading indicator
|
||||
const loading = document.createElement('div');
|
||||
loading.style.cssText = `
|
||||
text-align: center;
|
||||
padding: 40px;
|
||||
color: #aaa;
|
||||
`;
|
||||
loading.textContent = 'Loading files...';
|
||||
gridContainer.appendChild(loading);
|
||||
|
||||
// Assemble modal
|
||||
modal.appendChild(header);
|
||||
modal.appendChild(filterBar);
|
||||
modal.appendChild(gridContainer);
|
||||
overlay.appendChild(modal);
|
||||
|
||||
// Prevent right-click context menu everywhere in the browser
|
||||
// (video thumbnails have their own handler that will show the refresh menu)
|
||||
overlay.oncontextmenu = (e) => {
|
||||
e.preventDefault();
|
||||
return false;
|
||||
};
|
||||
|
||||
// Close button handler
|
||||
const closeBtn = topRow.querySelector('.close-btn');
|
||||
closeBtn.onclick = () => document.body.removeChild(overlay);
|
||||
overlay.onclick = (e) => {
|
||||
if (e.target === overlay) document.body.removeChild(overlay);
|
||||
};
|
||||
|
||||
// Regenerate cache button handler
|
||||
const regenerateCacheBtn = topRow.querySelector('.regenerate-cache-btn');
|
||||
regenerateCacheBtn.onclick = () => {
|
||||
clearThumbnailCache();
|
||||
// Reload thumbnails to regenerate them
|
||||
loadFileThumbnails(gridContainer, currentFile, onFileSelect, overlay, breadcrumb);
|
||||
};
|
||||
|
||||
// Add to DOM
|
||||
document.body.appendChild(overlay);
|
||||
|
||||
// Load files
|
||||
loadFileThumbnails(gridContainer, currentFile, onFileSelect, overlay, breadcrumb);
|
||||
|
||||
// Setup search/filter
|
||||
const searchInput = filterBar.querySelector('.search-input');
|
||||
const filterType = filterBar.querySelector('.filter-type');
|
||||
|
||||
searchInput.oninput = () => filterThumbnails(gridContainer, searchInput.value, filterType.value);
|
||||
filterType.onchange = () => filterThumbnails(gridContainer, searchInput.value, filterType.value);
|
||||
}
|
||||
|
||||
async function loadFileThumbnails(container, currentFile, onFileSelect, overlay, breadcrumbElement) {
|
||||
try {
|
||||
// Update breadcrumb
|
||||
if (!currentSubfolder) {
|
||||
breadcrumbElement.textContent = `${currentSourceFolder}/`;
|
||||
} else {
|
||||
breadcrumbElement.textContent = `${currentSourceFolder}/${currentSubfolder}/`;
|
||||
}
|
||||
|
||||
// Fetch file list from server
|
||||
const response = await fetch(`/prompt-extractor/list-files?source=${encodeURIComponent(currentSourceFolder)}`);
|
||||
const data = await response.json();
|
||||
|
||||
container.innerHTML = '';
|
||||
|
||||
if (!data.files || data.files.length === 0) {
|
||||
container.innerHTML = '<div style="text-align: center; padding: 40px; color: #aaa;">No files found in ' + currentSourceFolder + ' directory</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
// Get all files with their full paths
|
||||
const allFiles = data.files.filter(f => f !== '(none)');
|
||||
|
||||
// Filter files/folders for current directory
|
||||
const currentFiles = [];
|
||||
const subfolders = new Set();
|
||||
|
||||
const prefix = currentSubfolder ? currentSubfolder + '/' : '';
|
||||
|
||||
allFiles.forEach(filepath => {
|
||||
if (filepath.startsWith(prefix)) {
|
||||
const remainder = filepath.substring(prefix.length);
|
||||
const slashIndex = remainder.indexOf('/');
|
||||
|
||||
if (slashIndex === -1) {
|
||||
// It's a file in current directory
|
||||
currentFiles.push(filepath);
|
||||
} else {
|
||||
// It's in a subdirectory - extract folder name
|
||||
const folderName = remainder.substring(0, slashIndex);
|
||||
subfolders.add(folderName);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Add "back" button if in subfolder
|
||||
if (currentSubfolder) {
|
||||
const backItem = createBackItem(container, currentFile, onFileSelect, overlay, breadcrumbElement);
|
||||
container.appendChild(backItem);
|
||||
}
|
||||
|
||||
// Add folder items
|
||||
Array.from(subfolders).sort().forEach(folderName => {
|
||||
const folderItem = createFolderItem(folderName, container, currentFile, onFileSelect, overlay, breadcrumbElement);
|
||||
container.appendChild(folderItem);
|
||||
});
|
||||
|
||||
// Create thumbnail for each file
|
||||
currentFiles.forEach(filename => {
|
||||
const item = createThumbnailItem(filename, currentFile, onFileSelect, overlay);
|
||||
container.appendChild(item);
|
||||
});
|
||||
|
||||
// Scroll to the currently selected file
|
||||
if (currentFile) {
|
||||
const selectedItem = container.querySelector(`.thumbnail-item[data-filename="${CSS.escape(currentFile)}"]`);
|
||||
if (selectedItem) {
|
||||
// Use requestAnimationFrame to ensure layout is complete before scrolling
|
||||
requestAnimationFrame(() => {
|
||||
selectedItem.scrollIntoView({ block: 'center', behavior: 'instant' });
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.error('[FileBrowser] Error loading files:', error);
|
||||
container.innerHTML = '<div style="text-align: center; padding: 40px; color: rgba(220, 53, 69, 0.9);">Error loading files</div>';
|
||||
}
|
||||
}
|
||||
|
||||
function createBackItem(container, currentFile, onFileSelect, overlay, breadcrumbElement) {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'folder-item';
|
||||
item.style.cssText = `
|
||||
background: ${UI.cardBg};
|
||||
border: 1px solid ${UI.panelBorder};
|
||||
border-radius: 6px;
|
||||
padding: 8px;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
`;
|
||||
|
||||
const preview = document.createElement('div');
|
||||
preview.style.cssText = `
|
||||
width: 100%;
|
||||
height: 150px;
|
||||
background: rgba(16, 18, 22, 0.6);
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 64px;
|
||||
`;
|
||||
preview.textContent = '←';
|
||||
|
||||
const label = document.createElement('div');
|
||||
label.textContent = 'Back';
|
||||
label.style.cssText = `
|
||||
font-size: 12px;
|
||||
color: #ccc;
|
||||
text-align: center;
|
||||
`;
|
||||
|
||||
item.appendChild(preview);
|
||||
item.appendChild(label);
|
||||
|
||||
item.onmouseenter = () => {
|
||||
item.style.borderColor = UI.accentBorder;
|
||||
item.style.transform = 'translateY(-2px)';
|
||||
item.style.background = UI.accentSoft;
|
||||
};
|
||||
item.onmouseleave = () => {
|
||||
item.style.borderColor = UI.panelBorder;
|
||||
item.style.transform = 'translateY(0)';
|
||||
item.style.background = UI.cardBg;
|
||||
};
|
||||
|
||||
item.onclick = () => {
|
||||
// Go up one level
|
||||
const parts = currentSubfolder.split('/');
|
||||
parts.pop();
|
||||
currentSubfolder = parts.join('/');
|
||||
loadFileThumbnails(container, currentFile, onFileSelect, overlay, breadcrumbElement);
|
||||
};
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
function createFolderItem(folderName, container, currentFile, onFileSelect, overlay, breadcrumbElement) {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'folder-item';
|
||||
item.style.cssText = `
|
||||
background: rgba(45, 55, 72, 0.7);
|
||||
border: 1px solid rgba(226, 232, 240, 0.2);
|
||||
border-radius: 6px;
|
||||
padding: 8px;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
`;
|
||||
|
||||
const preview = document.createElement('div');
|
||||
preview.style.cssText = `
|
||||
width: 100%;
|
||||
height: 150px;
|
||||
background: rgba(0, 0, 0, 0.5);
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 64px;
|
||||
`;
|
||||
preview.textContent = '📁';
|
||||
|
||||
const label = document.createElement('div');
|
||||
label.textContent = folderName;
|
||||
label.style.cssText = `
|
||||
font-size: 12px;
|
||||
color: #ccc;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
text-align: center;
|
||||
`;
|
||||
label.title = folderName;
|
||||
|
||||
item.appendChild(preview);
|
||||
item.appendChild(label);
|
||||
|
||||
item.onmouseenter = () => {
|
||||
item.style.borderColor = 'rgba(66, 153, 225, 0.9)';
|
||||
item.style.transform = 'translateY(-2px)';
|
||||
item.style.background = 'rgba(50, 112, 163, 0.5)';
|
||||
};
|
||||
item.onmouseleave = () => {
|
||||
item.style.borderColor = 'rgba(226, 232, 240, 0.2)';
|
||||
item.style.transform = 'translateY(0)';
|
||||
item.style.background = 'rgba(45, 55, 72, 0.7)';
|
||||
};
|
||||
|
||||
item.onclick = () => {
|
||||
// Navigate into folder
|
||||
currentSubfolder = currentSubfolder ? `${currentSubfolder}/${folderName}` : folderName;
|
||||
loadFileThumbnails(container, currentFile, onFileSelect, overlay, breadcrumbElement);
|
||||
};
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
function createThumbnailItem(filename, currentFile, onFileSelect, overlay) {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'thumbnail-item';
|
||||
item.dataset.filename = filename;
|
||||
item.dataset.type = getFileType(filename);
|
||||
|
||||
const isSelected = filename === currentFile;
|
||||
|
||||
item.style.cssText = `
|
||||
background: ${UI.cardBg};
|
||||
border: 1px solid ${isSelected ? UI.accent : UI.panelBorder};
|
||||
border-radius: 6px;
|
||||
padding: 8px;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s ease;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
`;
|
||||
|
||||
// Thumbnail preview
|
||||
const preview = document.createElement('div');
|
||||
preview.style.cssText = `
|
||||
width: 100%;
|
||||
height: 150px;
|
||||
background: rgba(16, 18, 22, 0.6);
|
||||
border-radius: 4px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
`;
|
||||
|
||||
const ext = filename.split('.').pop().toLowerCase();
|
||||
const imageExts = ['png', 'jpg', 'jpeg', 'webp'];
|
||||
const videoExts = ['mp4', 'webm', 'mov', 'avi'];
|
||||
|
||||
if (imageExts.includes(ext)) {
|
||||
const img = document.createElement('img');
|
||||
// Handle subfolder paths: split filename into folder and basename
|
||||
let subfolder = '';
|
||||
let basename = filename;
|
||||
if (filename.includes('/')) {
|
||||
const lastSlash = filename.lastIndexOf('/');
|
||||
subfolder = filename.substring(0, lastSlash);
|
||||
basename = filename.substring(lastSlash + 1);
|
||||
}
|
||||
img.src = `/view?filename=${encodeURIComponent(basename)}&type=${currentSourceFolder}&subfolder=${encodeURIComponent(subfolder)}`;
|
||||
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
|
||||
img.onerror = () => {
|
||||
// Use placeholder image
|
||||
img.src = new URL("./placeholder.png", import.meta.url).href;
|
||||
};
|
||||
preview.appendChild(img);
|
||||
} else if (videoExts.includes(ext)) {
|
||||
// Extract video thumbnail via server-side PyAV
|
||||
extractVideoThumbnailServer(filename, preview);
|
||||
} else if (ext === 'json') {
|
||||
// Use placeholder for JSON
|
||||
const img = document.createElement('img');
|
||||
img.src = new URL("./placeholder.png", import.meta.url).href;
|
||||
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
|
||||
preview.appendChild(img);
|
||||
} else {
|
||||
// Use placeholder for unknown types
|
||||
const img = document.createElement('img');
|
||||
img.src = new URL("./placeholder.png", import.meta.url).href;
|
||||
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
|
||||
preview.appendChild(img);
|
||||
}
|
||||
|
||||
// Filename label (show only basename, not full path)
|
||||
const label = document.createElement('div');
|
||||
const basename = filename.includes('/') ? filename.split('/').pop() : filename;
|
||||
label.textContent = basename;
|
||||
label.style.cssText = `
|
||||
font-size: 12px;
|
||||
color: ${isSelected ? '#fff' : '#ccc'};
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
text-align: center;
|
||||
`;
|
||||
label.title = filename; // Full path in tooltip
|
||||
|
||||
item.appendChild(preview);
|
||||
item.appendChild(label);
|
||||
|
||||
// Hover effect
|
||||
item.onmouseenter = () => {
|
||||
if (!isSelected) {
|
||||
item.style.borderColor = UI.accentBorder;
|
||||
item.style.transform = 'translateY(-2px)';
|
||||
item.style.background = UI.accentSoft;
|
||||
}
|
||||
};
|
||||
item.onmouseleave = () => {
|
||||
if (!isSelected) {
|
||||
item.style.borderColor = UI.panelBorder;
|
||||
item.style.transform = 'translateY(0)';
|
||||
item.style.background = UI.cardBg;
|
||||
}
|
||||
};
|
||||
|
||||
// Click handler
|
||||
item.onclick = (e) => {
|
||||
// Don't select if clicking to close context menu
|
||||
if (document.querySelector('.thumbnail-context-menu')) {
|
||||
return;
|
||||
}
|
||||
onFileSelect(filename);
|
||||
document.body.removeChild(overlay);
|
||||
};
|
||||
|
||||
// Right-click context menu - only for video thumbnails
|
||||
if (videoExts.includes(ext)) {
|
||||
item.oncontextmenu = (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
showThumbnailContextMenu(e, filename, preview);
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
function getFileType(filename) {
|
||||
const ext = filename.split('.').pop().toLowerCase();
|
||||
const imageExts = ['png', 'jpg', 'jpeg', 'webp'];
|
||||
const videoExts = ['mp4', 'webm', 'mov', 'avi'];
|
||||
|
||||
if (imageExts.includes(ext)) return 'image';
|
||||
if (videoExts.includes(ext)) return 'video';
|
||||
if (ext === 'json') return 'json';
|
||||
return 'other';
|
||||
}
|
||||
|
||||
/**
|
||||
* Show context menu for thumbnail with refresh option
|
||||
*/
|
||||
function showThumbnailContextMenu(event, filename, previewElement) {
|
||||
// Remove any existing context menu
|
||||
const existingMenu = document.querySelector('.thumbnail-context-menu');
|
||||
if (existingMenu) {
|
||||
existingMenu.remove();
|
||||
}
|
||||
|
||||
// Create context menu
|
||||
const menu = document.createElement('div');
|
||||
menu.className = 'thumbnail-context-menu';
|
||||
menu.style.cssText = `
|
||||
position: fixed;
|
||||
left: ${event.pageX}px;
|
||||
top: ${event.pageY}px;
|
||||
background: ${UI.panel};
|
||||
border: 1px solid ${UI.panelBorder};
|
||||
border-radius: 6px;
|
||||
padding: 4px;
|
||||
z-index: 10001;
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
|
||||
min-width: 160px;
|
||||
`;
|
||||
|
||||
// Refresh option
|
||||
const refreshBtn = document.createElement('div');
|
||||
refreshBtn.textContent = '🔄 Refresh Thumbnail';
|
||||
refreshBtn.style.cssText = `
|
||||
padding: 8px 12px;
|
||||
color: #ccc;
|
||||
cursor: pointer;
|
||||
border-radius: 4px;
|
||||
font-size: 13px;
|
||||
transition: background 0.15s ease;
|
||||
`;
|
||||
refreshBtn.onmouseenter = () => {
|
||||
refreshBtn.style.background = UI.accentSoft;
|
||||
};
|
||||
refreshBtn.onmouseleave = () => {
|
||||
refreshBtn.style.background = 'transparent';
|
||||
};
|
||||
refreshBtn.onclick = () => {
|
||||
refreshIndividualThumbnail(filename, previewElement);
|
||||
menu.remove();
|
||||
};
|
||||
|
||||
menu.appendChild(refreshBtn);
|
||||
document.body.appendChild(menu);
|
||||
|
||||
// Close menu when clicking outside
|
||||
const closeMenu = (e) => {
|
||||
if (!menu.contains(e.target)) {
|
||||
e.stopPropagation(); // Prevent click from going through to elements below
|
||||
menu.remove();
|
||||
document.removeEventListener('click', closeMenu, true); // Remove from capture phase
|
||||
}
|
||||
};
|
||||
// Use capture phase to catch the click before it reaches other elements
|
||||
setTimeout(() => {
|
||||
document.addEventListener('click', closeMenu, true);
|
||||
}, 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh thumbnail for a single file
|
||||
*/
|
||||
function refreshIndividualThumbnail(filename, previewElement) {
|
||||
console.log(`[FileBrowser] Refreshing thumbnail for: ${filename}`);
|
||||
|
||||
// Clear cache for this specific file
|
||||
const cacheKey = `video_thumb_pyav_${filename.replace(/[\/\\]/g, '_')}`;
|
||||
|
||||
try {
|
||||
localStorage.removeItem(cacheKey);
|
||||
console.log(`[FileBrowser] Cleared cache for: ${filename}`);
|
||||
} catch (error) {
|
||||
console.error('[FileBrowser] Error clearing cache:', error);
|
||||
}
|
||||
|
||||
// Re-extract thumbnail via server-side PyAV
|
||||
extractVideoThumbnailServer(filename, previewElement);
|
||||
}
|
||||
|
||||
function filterThumbnails(container, searchText, fileType) {
|
||||
const items = container.querySelectorAll('.thumbnail-item');
|
||||
const search = searchText.toLowerCase();
|
||||
|
||||
items.forEach(item => {
|
||||
const filename = item.dataset.filename.toLowerCase();
|
||||
const type = item.dataset.type;
|
||||
|
||||
const matchesSearch = !searchText || filename.includes(search);
|
||||
const matchesType = fileType === 'all' || type === fileType;
|
||||
|
||||
item.style.display = (matchesSearch && matchesType) ? 'flex' : 'none';
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract thumbnail using server-side PyAV for all videos.
|
||||
* Fetches a JPEG frame from /prompt-extractor/video-frame and caches to localStorage.
|
||||
*/
|
||||
function extractVideoThumbnailServer(filename, previewElement) {
|
||||
const cacheKey = `video_thumb_pyav_${filename.replace(/[\/\\]/g, '_')}`;
|
||||
try {
|
||||
const cached = localStorage.getItem(cacheKey);
|
||||
if (cached) {
|
||||
const img = document.createElement('img');
|
||||
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
|
||||
img.src = cached;
|
||||
previewElement.innerHTML = '';
|
||||
previewElement.appendChild(img);
|
||||
return;
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
// Show placeholder while loading
|
||||
const placeholderImg = document.createElement('img');
|
||||
placeholderImg.src = new URL("./placeholder.png", import.meta.url).href;
|
||||
placeholderImg.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
|
||||
previewElement.innerHTML = '';
|
||||
previewElement.appendChild(placeholderImg);
|
||||
|
||||
const frameUrl = `/prompt-extractor/video-frame?filename=${encodeURIComponent(filename)}&source=${currentSourceFolder}&position=0`;
|
||||
const img = document.createElement('img');
|
||||
img.onload = () => {
|
||||
// Scale down to thumbnail size
|
||||
const maxW = 180, maxH = 150;
|
||||
const ar = img.naturalWidth / img.naturalHeight;
|
||||
let w, h;
|
||||
if (ar > maxW / maxH) { w = maxW; h = maxW / ar; }
|
||||
else { h = maxH; w = maxH * ar; }
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext('2d', { alpha: false });
|
||||
ctx.drawImage(img, 0, 0, w, h);
|
||||
const dataUrl = canvas.toDataURL('image/jpeg', 0.6);
|
||||
const result = document.createElement('img');
|
||||
result.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
|
||||
result.src = dataUrl;
|
||||
previewElement.innerHTML = '';
|
||||
previewElement.appendChild(result);
|
||||
try { localStorage.setItem(cacheKey, dataUrl); } catch (e) { /* ignore */ }
|
||||
};
|
||||
img.onerror = () => {
|
||||
previewElement.innerHTML = `
|
||||
<div style="text-align: center; color: #888; font-size: 11px; padding: 10px;">
|
||||
<div style="font-size: 24px; margin-bottom: 6px;">🎬</div>
|
||||
<div>Preview unavailable</div>
|
||||
</div>`;
|
||||
};
|
||||
img.src = frameUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear all video thumbnail cache
|
||||
*/
|
||||
function clearThumbnailCache() {
|
||||
try {
|
||||
const cachePrefix = 'video_thumb_';
|
||||
const keysToRemove = [];
|
||||
|
||||
// Find all cache keys in localStorage
|
||||
for (let i = 0; i < localStorage.length; i++) {
|
||||
const key = localStorage.key(i);
|
||||
if (key && key.startsWith(cachePrefix)) {
|
||||
keysToRemove.push(key);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove all cache entries
|
||||
keysToRemove.forEach(key => {
|
||||
localStorage.removeItem(key);
|
||||
});
|
||||
|
||||
console.log(`[FileBrowser] Cleared ${keysToRemove.length} cache entries`);
|
||||
} catch (error) {
|
||||
console.error('[FileBrowser] Error clearing cache:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up orphaned thumbnail cache entries
|
||||
* Removes cache for files that no longer exist in the input directory
|
||||
*/
|
||||
function cleanupOrphanedThumbnailCache(currentFiles) {
|
||||
try {
|
||||
const cachePrefix = 'video_thumb_';
|
||||
const timePrefix = 'video_thumb_time_';
|
||||
const keysToRemove = [];
|
||||
|
||||
// Find all cache keys in localStorage
|
||||
for (let i = 0; i < localStorage.length; i++) {
|
||||
const key = localStorage.key(i);
|
||||
|
||||
// Check if it's a video thumbnail cache key
|
||||
if (key && key.startsWith(cachePrefix)) {
|
||||
// Extract filename from cache key
|
||||
const filename = key.substring(cachePrefix.length);
|
||||
|
||||
// If this filename is not in current files list, mark for removal
|
||||
if (!currentFiles.includes(filename)) {
|
||||
keysToRemove.push(key);
|
||||
keysToRemove.push(timePrefix + filename);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove orphaned cache entries
|
||||
keysToRemove.forEach(key => {
|
||||
localStorage.removeItem(key);
|
||||
});
|
||||
|
||||
if (keysToRemove.length > 0) {
|
||||
console.log(`[FileBrowser] Cleaned up ${keysToRemove.length / 2} orphaned thumbnail cache entries`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[FileBrowser] Error cleaning up cache:', error);
|
||||
}
|
||||
}
|
||||
|
||||
|
After Width: | Height: | Size: 747 B |
@@ -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,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.16)",
|
||||
// Accent border used on selected elements
|
||||
accentBorder: "hsl(208 73% 57% / 0.65)",
|
||||
};
|
||||
@@ -0,0 +1,455 @@
|
||||
/**
|
||||
* WorkflowModelLoader 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 === "workflow_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._applyWorkflowModelLoaderInfo(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.WorkflowModelLoader",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "WorkflowModelLoader") 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._applyWorkflowModelLoaderInfo(info);
|
||||
};
|
||||
|
||||
nodeType.prototype._applyWorkflowModelLoaderInfo = function (info) {
|
||||
const selected = _sanitizeChoice(info.model, MODEL_CHOICES, "model_a");
|
||||
this._workflowModelLoaderInfo = {
|
||||
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._ensureWorkflowModelInfoWidget();
|
||||
this.setDirtyCanvas(true, true);
|
||||
};
|
||||
|
||||
const origOnNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
const r = origOnNodeCreated?.apply(this, arguments);
|
||||
_restoreOrNormalizeWidgetState(this);
|
||||
if (!this._workflowModelLoaderInfo) {
|
||||
this._workflowModelLoaderInfo = _defaultInfoFromWidgets(this);
|
||||
}
|
||||
this._ensureWorkflowModelInfoWidget();
|
||||
_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._workflowModelLoaderInfo) {
|
||||
o._workflowModelLoaderInfo = this._workflowModelLoaderInfo;
|
||||
}
|
||||
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?._workflowModelLoaderInfo;
|
||||
if (state) {
|
||||
requestAnimationFrame(() => {
|
||||
this._applyWorkflowModelLoaderInfo(state);
|
||||
_refreshInfoFromUpstream(this);
|
||||
});
|
||||
} else {
|
||||
requestAnimationFrame(() => {
|
||||
this._workflowModelLoaderInfo = _defaultInfoFromWidgets(this);
|
||||
this._ensureWorkflowModelInfoWidget();
|
||||
_refreshInfoFromUpstream(this);
|
||||
this.setDirtyCanvas(true, true);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
nodeType.prototype._ensureWorkflowModelInfoWidget = function () {
|
||||
let widget = this.widgets?.find(w => w.name === "_workflow_model_loader_info");
|
||||
if (!widget) {
|
||||
widget = {
|
||||
name: "_workflow_model_loader_info",
|
||||
type: "custom",
|
||||
y: 0,
|
||||
computeSize: () => {
|
||||
const rows = _buildRows(this._workflowModelLoaderInfo || {});
|
||||
const h = Math.max(26, (rows.length * 22) + 6);
|
||||
return [0, h];
|
||||
},
|
||||
draw: function (ctx, node, widgetWidth, y) {
|
||||
const info = node._workflowModelLoaderInfo;
|
||||
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,15 @@
|
||||
/**
|
||||
* Workflow Renderer — Set initial node size to match Workflow Builder width.
|
||||
*/
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
app.registerExtension({
|
||||
name: "prompt-manager.workflow-renderer",
|
||||
async nodeCreated(node) {
|
||||
if (node.comfyClass !== "WorkflowRenderer") return;
|
||||
requestAnimationFrame(() => {
|
||||
node.setSize([320, node.size[1]]);
|
||||
app.graph.setDirtyCanvas(true, true);
|
||||
});
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
"""
|
||||
ComfyUI Prompt Apply LoRA - Apply a LORA_STACK to model
|
||||
"""
|
||||
import ast
|
||||
import json
|
||||
import os
|
||||
|
||||
import comfy.sd
|
||||
import comfy.utils
|
||||
|
||||
from ..py.lora_utils import resolve_lora_path
|
||||
|
||||
|
||||
def parse_lora_stack_text(text):
|
||||
"""Parse a lora stack from a text string.
|
||||
|
||||
Accepts formats:
|
||||
JSON: [["lora_name", 1.0, 1.0], ...]
|
||||
Python: [("lora_name", 1.0, 1.0), ...]
|
||||
Plain: One path/name per line (strength defaults to 1.0)
|
||||
Returns a list of (name, model_strength, clip_strength) tuples.
|
||||
"""
|
||||
text = text.strip()
|
||||
if not text:
|
||||
return []
|
||||
|
||||
# Try JSON first
|
||||
try:
|
||||
data = json.loads(text)
|
||||
return [(str(item[0]), float(item[1]), float(item[2])) for item in data]
|
||||
except (json.JSONDecodeError, ValueError, IndexError, TypeError):
|
||||
pass
|
||||
|
||||
# Fall back to Python literal (handles tuples)
|
||||
try:
|
||||
data = ast.literal_eval(text)
|
||||
return [(str(item[0]), float(item[1]), float(item[2])) for item in data]
|
||||
except (ValueError, SyntaxError, IndexError, TypeError):
|
||||
pass
|
||||
|
||||
# Fall back to newline-separated paths/names (strength defaults to 1.0)
|
||||
lines = [line.strip() for line in text.splitlines() if line.strip()]
|
||||
if lines:
|
||||
return [(line, 1.0, 1.0) for line in lines]
|
||||
|
||||
return []
|
||||
|
||||
|
||||
class ApplyLoraPlusPlus:
|
||||
"""
|
||||
Apply a LoRA stack to a model.
|
||||
Takes a LORA_STACK (list of tuples) and applies each LoRA sequentially.
|
||||
Uses fuzzy matching to find LoRAs on disk — LoRAs not found are skipped.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"model": ("MODEL",),
|
||||
},
|
||||
"optional": {
|
||||
"clip_optional": ("CLIP",),
|
||||
"lora_stack": ("LORA_STACK",),
|
||||
"lora_stack_text": ("STRING", {"default": "", "multiline": True}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL", "CLIP")
|
||||
RETURN_NAMES = ("model", "clip")
|
||||
FUNCTION = "apply_stack"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Apply a LoRA stack to a model. You can connect LORA_STACK or input LoRA path as text\none LoRA per line (Full paths can reference any location on disk.)"
|
||||
|
||||
def apply_stack(self, model, clip_optional=None, lora_stack=None, lora_stack_text=""):
|
||||
clip = clip_optional
|
||||
|
||||
# If no stack input and no text, return early
|
||||
if not lora_stack and (not lora_stack_text or not lora_stack_text.strip()):
|
||||
return (model, clip)
|
||||
|
||||
# Merge both sources
|
||||
stack = list(lora_stack) if lora_stack else []
|
||||
if lora_stack_text:
|
||||
stack.extend(parse_lora_stack_text(lora_stack_text))
|
||||
|
||||
if not stack:
|
||||
return (model, clip)
|
||||
|
||||
model_out = model
|
||||
clip_out = clip
|
||||
|
||||
for lora_name, model_strength, clip_strength in stack:
|
||||
# Skip if no strength
|
||||
if model_strength == 0 and clip_strength == 0:
|
||||
continue
|
||||
|
||||
# If it looks like a full path and exists on disk, use it directly
|
||||
if os.path.isabs(lora_name) and os.path.isfile(lora_name):
|
||||
lora_path = lora_name
|
||||
else:
|
||||
# Resolve LoRA using fuzzy matching (handles renamed LoRAs, WAN tokens, etc.)
|
||||
lora_path, found = resolve_lora_path(lora_name)
|
||||
if not found:
|
||||
print(f"[PromptApplyLora] Warning: LoRA not found, skipping: {lora_name}")
|
||||
continue
|
||||
|
||||
# Load the LoRA
|
||||
lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
|
||||
|
||||
# Apply to model + clip
|
||||
model_out, clip_out = comfy.sd.load_lora_for_models(
|
||||
model_out, clip_out, lora, model_strength, clip_strength
|
||||
)
|
||||
|
||||
return (model_out, clip_out)
|
||||
@@ -13,14 +13,17 @@ import numpy as np
|
||||
from colorama import Fore, Style
|
||||
from PIL import Image
|
||||
from io import BytesIO
|
||||
from .model_manager import get_local_models, get_model_path, is_model_local, download_model, get_mmproj_path
|
||||
from ..py.model_manager import get_local_models, get_model_path, is_model_local, download_model, get_mmproj_path, has_vision_support
|
||||
|
||||
# Ollama integration
|
||||
from ..py.ollama_wrapper import generate_chat as ollama_generate_chat, unload_model as ollama_unload_model
|
||||
|
||||
# ComfyUI interrupt helper
|
||||
import comfy.model_management
|
||||
|
||||
# Try to import preferences cache, fallback to empty dict if not available
|
||||
try:
|
||||
from .model_manager import _preferences_cache
|
||||
from ..py.model_manager import _preferences_cache
|
||||
except ImportError:
|
||||
_preferences_cache = {}
|
||||
|
||||
@@ -174,7 +177,7 @@ signal.signal(signal.SIGINT, _signal_handler)
|
||||
signal.signal(signal.SIGTERM, _signal_handler)
|
||||
|
||||
# --- Prompt Loading Helpers ---
|
||||
_PROMPTS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "prompts")
|
||||
_PROMPTS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "prompts")
|
||||
_prompts_cache = {}
|
||||
|
||||
def load_prompt(filename):
|
||||
@@ -229,7 +232,7 @@ class PromptGenerator:
|
||||
|
||||
@staticmethod
|
||||
def get_image_system_prompt():
|
||||
"""Load the system prompt for image description (used with Qwen3VL)."""
|
||||
"""Load the system prompt for image description (used with vision models)."""
|
||||
return load_prompt("image_default_system_prompt.txt")
|
||||
|
||||
@staticmethod
|
||||
@@ -248,63 +251,54 @@ class PromptGenerator:
|
||||
return load_prompt("json_system_prompt.txt")
|
||||
|
||||
@staticmethod
|
||||
def find_qwen3vl_model(available_models, thinking):
|
||||
"""Find the preferred or smallest available Qwen3VL model
|
||||
def find_vision_model(available_models):
|
||||
"""Find the preferred or first available vision-capable model.
|
||||
|
||||
First checks user preferences, then falls back to smallest model (4B preferred over 8B)
|
||||
A model is considered vision-capable if it has an mmproj file
|
||||
(either in the registry or on disk).
|
||||
"""
|
||||
|
||||
qwen3vl_models = [m for m in available_models if 'qwen3vl' in m.lower()]
|
||||
if not qwen3vl_models:
|
||||
vision_models = [m for m in available_models if has_vision_support(m)]
|
||||
if not vision_models:
|
||||
return None
|
||||
|
||||
# Check user preference first
|
||||
preferred = _preferences_cache.get("preferred_vision_model", "")
|
||||
if preferred and preferred in qwen3vl_models and is_model_local(preferred):
|
||||
if thinking:
|
||||
if 'thinking' in preferred.lower():
|
||||
return preferred
|
||||
else:
|
||||
if 'thinking' not in preferred.lower():
|
||||
return preferred
|
||||
if preferred and preferred in vision_models and is_model_local(preferred):
|
||||
return preferred
|
||||
|
||||
# Let's filter models based on thinking mode
|
||||
if thinking:
|
||||
filtered_models = [model for model in qwen3vl_models if 'thinking' in model.lower()]
|
||||
else:
|
||||
filtered_models = [model for model in qwen3vl_models if 'thinking' not in model.lower()]
|
||||
if filtered_models:
|
||||
qwen3vl_models = filtered_models
|
||||
|
||||
# Fall back to smaller model (prefer 4B over 8B)
|
||||
for model in qwen3vl_models:
|
||||
if '4b' in model.lower():
|
||||
# Fall back to smallest model
|
||||
for model in vision_models:
|
||||
if '4b' in model.lower() or '3b' in model.lower():
|
||||
return model
|
||||
|
||||
return qwen3vl_models[0]
|
||||
return vision_models[0]
|
||||
|
||||
@staticmethod
|
||||
def find_non_vl_model(available_models):
|
||||
"""Find the preferred or smallest available non-vision model by file size
|
||||
def find_text_model(available_models):
|
||||
"""Find the preferred or smallest available model for text enhancement.
|
||||
|
||||
First checks user preferences, then falls back to smallest model by file size
|
||||
Any model can be used for text (vision models work too),
|
||||
but we prefer non-vision models when available to save resources.
|
||||
Falls back to vision-capable models if that's all there is.
|
||||
"""
|
||||
# Prefer models without mmproj (lighter weight)
|
||||
text_only = [m for m in available_models if not has_vision_support(m)]
|
||||
|
||||
non_vl_models = [m for m in available_models if 'qwen3vl' not in m.lower()]
|
||||
if not non_vl_models:
|
||||
candidates = text_only if text_only else available_models
|
||||
if not candidates:
|
||||
return None
|
||||
|
||||
# Check user preference first
|
||||
preferred = _preferences_cache.get("preferred_base_model", "")
|
||||
if preferred and preferred in non_vl_models and is_model_local(preferred):
|
||||
if preferred and preferred in candidates and is_model_local(preferred):
|
||||
return preferred
|
||||
|
||||
# Fall back to smaller model (prefer 4B over 8B)
|
||||
for model in non_vl_models:
|
||||
if '4b' in model.lower():
|
||||
# Fall back to smallest model
|
||||
for model in candidates:
|
||||
if '4b' in model.lower() or '3b' in model.lower():
|
||||
return model
|
||||
|
||||
return non_vl_models[0]
|
||||
return candidates[0]
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
@@ -314,7 +308,8 @@ class PromptGenerator:
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 0xffffffffffffffff,
|
||||
"tooltip": "Seed for reproducible generation."
|
||||
"tooltip": "Seed for reproducible generation.",
|
||||
"control_after_generate": True
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
@@ -350,6 +345,7 @@ class PromptGenerator:
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Generate or enhance prompts using a local LLM via llama.cpp or Ollama."
|
||||
RETURN_TYPES = ("STRING", "STRING")
|
||||
RETURN_NAMES = ("output", "thoughts")
|
||||
FUNCTION = "convert_prompt"
|
||||
@@ -443,15 +439,14 @@ class PromptGenerator:
|
||||
# Build command arguments
|
||||
cmd_args = [server_cmd, "-m", model_path, "--port", str(PromptGenerator.SERVER_PORT), "--no-warmup", "-c", str(context_size)]
|
||||
|
||||
# Add vision flags for VL models
|
||||
# Add vision flags for models with mmproj
|
||||
if use_vision_model:
|
||||
mmproj_path = get_mmproj_path(model_name)
|
||||
if mmproj_path:
|
||||
# Only print if mmproj is used
|
||||
print_pg(f"Vision model: using mmproj: {os.path.basename(mmproj_path)}")
|
||||
cmd_args.extend(["--mmproj", mmproj_path])
|
||||
else:
|
||||
error_msg = f"Error: Vision model requires mmproj file for '{model_name}' but it was not found. \nPlease ensure it exists, or use the Generator Options node to download the Qwen3VL model and its mmproj file."
|
||||
error_msg = f"Error: Vision mode requires an mmproj file for '{model_name}' but none was found.\nPlease ensure an mmproj file exists, or use the Generator Options node to download a vision-capable model."
|
||||
print_pg(error_msg, RED)
|
||||
return (False, error_msg)
|
||||
|
||||
@@ -502,17 +497,33 @@ class PromptGenerator:
|
||||
_current_context_size = context_size
|
||||
|
||||
# Wait for server to be ready
|
||||
for i in range(30): # Wait up to 30 seconds
|
||||
for i in range(60): # Wait up to 60 seconds
|
||||
time.sleep(1)
|
||||
try:
|
||||
comfy.model_management.throw_exception_if_processing_interrupted()
|
||||
except Exception:
|
||||
# Propagate interrupt up to caller
|
||||
raise
|
||||
# Check if process has crashed
|
||||
if _server_process.poll() is not None:
|
||||
stderr_output = ""
|
||||
try:
|
||||
stderr_output = _server_process.stderr.read().decode("utf-8", errors="replace").strip()
|
||||
except Exception:
|
||||
pass
|
||||
error_msg = f"Error: llama-server exited with code {_server_process.returncode}"
|
||||
if stderr_output:
|
||||
# Show last 5 lines of stderr for context
|
||||
last_lines = "\n".join(stderr_output.splitlines()[-5:])
|
||||
error_msg += f"\n{last_lines}"
|
||||
print_pg(error_msg, RED)
|
||||
_server_process = None
|
||||
_current_model = None
|
||||
return (False, error_msg)
|
||||
if PromptGenerator.is_server_alive():
|
||||
return (True, None)
|
||||
|
||||
error_msg = "Error: Server did not start in time"
|
||||
error_msg = "Error: Server did not start in time (60s)"
|
||||
print_pg(error_msg, RED)
|
||||
PromptGenerator.stop_server()
|
||||
return (False, error_msg)
|
||||
@@ -650,11 +661,17 @@ class PromptGenerator:
|
||||
return PromptGenerator.fetch_model_defaults()
|
||||
|
||||
def convert_prompt(self, seed: int, mode="Enhance Prompt (Image)", prompt="", image=None, format_as_json=False, enable_thinking=True, stop_server_after=False, options=None, **kwargs) -> str:
|
||||
"""Convert prompt using llama.cpp server, with caching for repeated requests."""
|
||||
"""Convert prompt using llama.cpp server or Ollama, with caching for repeated requests."""
|
||||
global _current_model
|
||||
|
||||
print_pg_header() # Print header for this execution
|
||||
|
||||
# Determine LLM backend: "ollama" or "llama.cpp"
|
||||
use_ollama = (
|
||||
(options and options.get("llm_backend") == "ollama")
|
||||
or _preferences_cache.get("llm_backend", "llama.cpp") == "ollama"
|
||||
)
|
||||
|
||||
# Extract console option from connected options node
|
||||
show_everything_in_console = False # Default to False when options not connected
|
||||
use_model_default_sampling = True # Default to using model defaults
|
||||
@@ -674,61 +691,73 @@ class PromptGenerator:
|
||||
if (mode == "Enhance Prompt (Image)" or mode == "Enhance Prompt (Video)") and not prompt.strip():
|
||||
error_msg = "Did you perhaps forget to enter a User Prompt?"
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
# Always determine a valid model filename before running server
|
||||
model_to_use = None
|
||||
available_models = get_local_models()
|
||||
|
||||
if use_vision_model:
|
||||
# Check if options specifies a Qwen3VL model
|
||||
if options and "model" in options and "vl" in options["model"].lower() and is_model_local(options["model"]):
|
||||
if use_ollama:
|
||||
# ── Ollama model selection ──
|
||||
# Priority: Options node > auto-discover from Ollama
|
||||
if options and "model" in options:
|
||||
model_to_use = options["model"]
|
||||
elif options and "model" in options and is_model_local(options["model"]):
|
||||
# Non-VL model selected but in vision mode
|
||||
print_pg(f"Warning: Non-vision model '{options['model']}' selected but '{mode}' mode is active.\nIgnoring model selection and using a Vision Model instead.")
|
||||
model_to_use = self.find_qwen3vl_model(available_models, enable_thinking)
|
||||
if model_to_use is None:
|
||||
error_msg = f"Error: '{mode}' mode requires a Qwen3VL model. Please connect the Options node and select a Qwen3VL model (Qwen3VL-4B or Qwen3VL-8B) to use vision capabilities."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
else:
|
||||
# Try to find a Qwen3VL model automatically
|
||||
model_to_use = self.find_qwen3vl_model(available_models, enable_thinking)
|
||||
if model_to_use is None:
|
||||
error_msg = f"Error: '{mode}' mode requires a Qwen3VL model. Please connect the Options node and select a Qwen3VL model (Qwen3VL-4B or Qwen3VL-8B) to use vision capabilities."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
else:
|
||||
# Enhance Prompt mode - use regular model selection logic (exclude Qwen3VL models)
|
||||
if options and "model" in options and is_model_local(options["model"]):
|
||||
# If user explicitly selected a Qwen3VL model but in Enhance mode, use first non-VL model instead
|
||||
if "qwen3vl" in options["model"].lower():
|
||||
model_to_use = self.find_non_vl_model(available_models)
|
||||
if model_to_use:
|
||||
print_pg(f"Warning: Qwen3VL model '{options['model']}' selected but 'Enhance Prompt' mode is active. Ignoring model selection and using {model_to_use} instead.")
|
||||
else:
|
||||
error_msg = "Error: Only Qwen3VL models available but 'Enhance Prompt' mode is active. Please add a .gguf model or use Generator Options to add a non-vision model."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
# Auto-discover available models from Ollama
|
||||
from ..py.ollama_wrapper import discover_ollama_models
|
||||
discovered, status = discover_ollama_models(_preferences_cache)
|
||||
if discovered:
|
||||
model_to_use = discovered[0]
|
||||
print_pg(f"Auto-selected Ollama model: {model_to_use}")
|
||||
else:
|
||||
model_to_use = options["model"]
|
||||
else:
|
||||
if not available_models:
|
||||
error_msg = "Error: No models found in models/ folder. Please add a .gguf model or use Generator Options node to download one."
|
||||
error_msg = (f"Error: No Ollama model available. {status}\n"
|
||||
"Pull a model first (e.g. `ollama pull llama3.1`).")
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
# Find smallest non-VL model
|
||||
model_to_use = self.find_non_vl_model(available_models)
|
||||
if not model_to_use:
|
||||
error_msg = "Error: Only Qwen3VL models available but 'Enhance Prompt' mode is active. Please add a non-vision model or switch to 'Describe Image' mode."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
# let's make sure thinking is disabled for non-thinking versions of Qwen3VL
|
||||
if enable_thinking and "qwen3vl" in model_to_use.lower() and "thinking" not in model_to_use.lower():
|
||||
print_pg("Warning: Thinking disabled - model does not support it.")
|
||||
enable_thinking = False
|
||||
print_pg("Backend : Ollama")
|
||||
|
||||
else:
|
||||
# ── llama.cpp model selection ──
|
||||
print_pg("Backend : llama.cpp")
|
||||
available_models = get_local_models()
|
||||
|
||||
if use_vision_model:
|
||||
# Check if the selected model supports vision (has mmproj)
|
||||
if options and "model" in options and has_vision_support(options["model"]) and is_model_local(options["model"]):
|
||||
model_to_use = options["model"]
|
||||
elif options and "model" in options and is_model_local(options["model"]):
|
||||
# Selected model doesn't support vision
|
||||
print_pg(f"Warning: Model '{options['model']}' has no mmproj (no vision support) but '{mode}' mode is active.\nIgnoring model selection and searching for a vision-capable model.")
|
||||
model_to_use = self.find_vision_model(available_models)
|
||||
if model_to_use is None:
|
||||
error_msg = f"Error: '{mode}' mode requires a vision model (one with an mmproj file). Please download a vision-capable model via the Options node."
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
else:
|
||||
# Try to find a vision model automatically
|
||||
model_to_use = self.find_vision_model(available_models)
|
||||
if model_to_use is None:
|
||||
error_msg = f"Error: '{mode}' mode requires a vision model (one with an mmproj file). Please download a vision-capable model via the Options node."
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
else:
|
||||
# Enhance Prompt mode - any model works, prefer text-only for efficiency
|
||||
if options and "model" in options and is_model_local(options["model"]):
|
||||
model_to_use = options["model"]
|
||||
else:
|
||||
if not available_models:
|
||||
error_msg = "Error: No models found in models/ folder. Please add a .gguf model or use Generator Options node to download one."
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
model_to_use = self.find_text_model(available_models)
|
||||
if not model_to_use:
|
||||
error_msg = "Error: No suitable model found. Please add a .gguf model or use the Generator Options node to download one."
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
# Thinking mode is only meaningful if the model explicitly supports it
|
||||
# (no longer tied to Qwen3VL naming — generic check)
|
||||
# Users can always enable thinking; the model will simply ignore it if unsupported.
|
||||
|
||||
print_pg(f"Vision mode : {'ON' if use_vision_model else 'OFF'}")
|
||||
print_pg(f"Thinking mode : {'ON' if enable_thinking else 'OFF'}")
|
||||
@@ -750,18 +779,19 @@ class PromptGenerator:
|
||||
|
||||
if not images:
|
||||
error_msg = f"Error: '{mode}' mode requires at least one image to be connected. Please connect an image or switch to 'Enhance Prompt' mode."
|
||||
print_pg(error_msg)
|
||||
return (error_msg,)
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
# If the current model is not the one we want, or server is not running, restart
|
||||
# Also restart if context_size has changed
|
||||
# Also restart if context_size has changed (llama.cpp only)
|
||||
context_size = options.get("context_size", 4096) if options else 4096
|
||||
if _current_model != model_to_use or _current_context_size != context_size or not self.is_server_alive():
|
||||
self.stop_server()
|
||||
# Get context_size from options or use default
|
||||
success, error_msg = self.start_server(model_to_use, context_size, use_vision_model)
|
||||
if not success:
|
||||
return (error_msg,)
|
||||
if not use_ollama:
|
||||
if _current_model != model_to_use or _current_context_size != context_size or not self.is_server_alive():
|
||||
self.stop_server()
|
||||
# Get context_size from options or use default
|
||||
success, error_msg = self.start_server(model_to_use, context_size, use_vision_model)
|
||||
if not success:
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
# Build the endpoint URL
|
||||
full_url = f"http://localhost:{self.SERVER_PORT}/v1/chat/completions"
|
||||
@@ -795,9 +825,9 @@ class PromptGenerator:
|
||||
else:
|
||||
user_content = prompt
|
||||
|
||||
# === TOKENIZATION (only for non-cached requests) ===
|
||||
# === TOKENIZATION (only for non-cached requests, llama.cpp only) ===
|
||||
cached_token_counts = None
|
||||
if show_everything_in_console:
|
||||
if show_everything_in_console and not use_ollama:
|
||||
cached_token_counts = self._get_token_counts_parallel(system_prompt, user_content)
|
||||
|
||||
# If in vision mode, encode images for the request
|
||||
@@ -830,7 +860,7 @@ class PromptGenerator:
|
||||
img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8')
|
||||
image_contents.append({"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_base64}"}})
|
||||
|
||||
# Qwen3VL format for vision messages: all images, then text
|
||||
# Vision format: all images first, then text
|
||||
user_message = {
|
||||
"role": "user",
|
||||
"content": image_contents + [{"type": "text", "text": user_content}]
|
||||
@@ -838,6 +868,29 @@ class PromptGenerator:
|
||||
else:
|
||||
user_message = {"role": "user", "content": user_content}
|
||||
|
||||
# ================================================================
|
||||
# Ollama generation path
|
||||
# ================================================================
|
||||
if use_ollama:
|
||||
return self._generate_via_ollama(
|
||||
model_to_use=model_to_use,
|
||||
system_prompt=system_prompt,
|
||||
user_message=user_message,
|
||||
user_content=user_content,
|
||||
seed=seed,
|
||||
enable_thinking=enable_thinking,
|
||||
use_model_default_sampling=use_model_default_sampling,
|
||||
show_everything_in_console=show_everything_in_console,
|
||||
stop_server_after=stop_server_after,
|
||||
options=options,
|
||||
images=images,
|
||||
context_size=context_size,
|
||||
prompt=prompt,
|
||||
)
|
||||
|
||||
# ================================================================
|
||||
# llama.cpp generation path (existing)
|
||||
# ================================================================
|
||||
payload = {
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
@@ -897,7 +950,7 @@ class PromptGenerator:
|
||||
stream=True
|
||||
)
|
||||
else:
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
response.raise_for_status()
|
||||
|
||||
@@ -1008,18 +1061,186 @@ class PromptGenerator:
|
||||
except requests.exceptions.ConnectionError:
|
||||
error_msg = f"Error: Could not connect to server at {full_url}. Server may have crashed."
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
except requests.exceptions.Timeout:
|
||||
error_msg = "Error: Request timed out (>120s)"
|
||||
print_pg(error_msg, RED)
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
except Exception as e:
|
||||
error_msg = f"Error: {e}"
|
||||
print_pg(error_msg, RED)
|
||||
if response.status_code == 400:
|
||||
print_pg("Perhaps your query requires a larger context size.\nConsider increasing it using the Generator Options node.", RED)
|
||||
error_msg += "\nConsider increasing context size using Generator Options node."
|
||||
return (error_msg,)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
# ================================================================
|
||||
# Ollama generation helper
|
||||
# ================================================================
|
||||
def _generate_via_ollama(self, model_to_use, system_prompt, user_message,
|
||||
user_content, seed, enable_thinking,
|
||||
use_model_default_sampling, show_everything_in_console,
|
||||
stop_server_after, options, images, context_size, prompt):
|
||||
"""Generate text using Ollama's OpenAI-compatible endpoint with streaming."""
|
||||
|
||||
messages = [
|
||||
{"role": "system", "content": system_prompt},
|
||||
user_message,
|
||||
]
|
||||
|
||||
# Sampling parameters
|
||||
temperature = 0.8
|
||||
top_k = 40
|
||||
top_p = 0.95
|
||||
min_p = 0.05
|
||||
repeat_penalty = 1.0
|
||||
if options and not use_model_default_sampling:
|
||||
temperature = options.get("temperature", temperature)
|
||||
top_k = options.get("top_k", top_k)
|
||||
top_p = options.get("top_p", top_p)
|
||||
min_p = options.get("min_p", min_p)
|
||||
repeat_penalty = options.get("repeat_penalty", repeat_penalty)
|
||||
|
||||
if show_everything_in_console:
|
||||
print_pg(f"{'=' * 60}", GREEN)
|
||||
print_pg(" DETAILED INFORMATION ENABLED (Ollama)", GREEN)
|
||||
print_pg(f"{'=' * 60}", GREEN)
|
||||
if not use_model_default_sampling:
|
||||
print_pg("------ GENERATION PARAMETERS ------", GREEN)
|
||||
for name, val in [("seed", seed), ("temperature", temperature),
|
||||
("top_k", top_k), ("top_p", top_p),
|
||||
("min_p", min_p), ("repeat_penalty", repeat_penalty)]:
|
||||
print_pg(f"{name} = {val}", GREEN)
|
||||
else:
|
||||
print_pg("Using model default sampling parameters", GREEN)
|
||||
print_pg("\n--------- SYSTEM PROMPT ---------", GREEN)
|
||||
print_pg(f"{system_prompt}", GREEN)
|
||||
print_pg("\n--------- USER PROMPT ---------", GREEN)
|
||||
print_pg(f"{user_content}", GREEN)
|
||||
|
||||
# Call Ollama (streaming)
|
||||
result = ollama_generate_chat(
|
||||
user_config=_preferences_cache,
|
||||
model_name=model_to_use,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
top_k=top_k,
|
||||
top_p=top_p,
|
||||
min_p=min_p,
|
||||
repeat_penalty=repeat_penalty,
|
||||
seed=seed,
|
||||
stream=True,
|
||||
timeout=120,
|
||||
use_model_defaults=use_model_default_sampling,
|
||||
enable_thinking=enable_thinking,
|
||||
)
|
||||
|
||||
# result is (response_obj, error_msg) for streaming
|
||||
if result[1] is not None:
|
||||
print_pg(f"Ollama error: {result[1]}", RED)
|
||||
return (result[1],)
|
||||
|
||||
response = result[0]
|
||||
|
||||
try:
|
||||
full_response = ""
|
||||
thinking_content = ""
|
||||
usage_stats = None
|
||||
first_thinking = True
|
||||
first_content = True
|
||||
|
||||
for line in response.iter_lines():
|
||||
# Check for user interrupt
|
||||
try:
|
||||
comfy.model_management.throw_exception_if_processing_interrupted()
|
||||
except Exception:
|
||||
try:
|
||||
response.close()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
|
||||
if line:
|
||||
line = line.decode('utf-8')
|
||||
if line.startswith('data: '):
|
||||
data = line[6:]
|
||||
if data == '[DONE]':
|
||||
break
|
||||
try:
|
||||
chunk = json.loads(data)
|
||||
|
||||
if "usage" in chunk:
|
||||
usage_stats = chunk["usage"]
|
||||
|
||||
if 'choices' in chunk and len(chunk['choices']) > 0:
|
||||
delta = chunk['choices'][0].get('delta', {})
|
||||
if 'reasoning_content' in delta:
|
||||
reasoning_delta = delta['reasoning_content']
|
||||
if reasoning_delta is not None:
|
||||
thinking_content += str(reasoning_delta)
|
||||
if show_everything_in_console:
|
||||
if first_thinking:
|
||||
print_pg("\n--------- THINKING ---------", GREEN)
|
||||
first_thinking = False
|
||||
print(f"{GREEN}{str(reasoning_delta)}{RESET}", end='', flush=True)
|
||||
if 'content' in delta:
|
||||
content_delta = delta['content']
|
||||
if content_delta is not None:
|
||||
full_response += str(content_delta)
|
||||
if show_everything_in_console:
|
||||
if first_content:
|
||||
print_pg("\n\n--------- FINAL ANSWER ---------", CYAN)
|
||||
first_content = False
|
||||
print(f"{CYAN}{str(content_delta)}{RESET}", end='', flush=True)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
if show_everything_in_console:
|
||||
print('') # Final newline
|
||||
|
||||
if not show_everything_in_console:
|
||||
print_pg("Prompt generation complete (Ollama).")
|
||||
|
||||
if show_everything_in_console and usage_stats:
|
||||
self.print_token_stats(usage_stats, None, thinking_content, full_response, images)
|
||||
else:
|
||||
print_pg_footer()
|
||||
|
||||
if not full_response:
|
||||
print_pg("Warning: Empty response from Ollama")
|
||||
full_response = prompt
|
||||
|
||||
# "stop_server_after" → unload model from Ollama memory immediately
|
||||
# (This overrides the keep_alive duration for this request)
|
||||
if stop_server_after:
|
||||
print_pg("Unloading model from Ollama memory...")
|
||||
ok, msg = ollama_unload_model(_preferences_cache, model_to_use)
|
||||
print_pg(msg, GREEN if ok else RED)
|
||||
else:
|
||||
keep_alive = _preferences_cache.get("ollama_keep_alive", "5m")
|
||||
if keep_alive and str(keep_alive) != "0":
|
||||
print_pg(f"Model will stay loaded for: {keep_alive}")
|
||||
|
||||
return (full_response, thinking_content)
|
||||
|
||||
except comfy.model_management.InterruptProcessingException:
|
||||
try:
|
||||
response.close()
|
||||
except Exception:
|
||||
pass
|
||||
raise
|
||||
except requests.exceptions.ConnectionError:
|
||||
error_msg = "Error: Lost connection to Ollama during generation."
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
except requests.exceptions.Timeout:
|
||||
error_msg = "Error: Ollama request timed out (>120s)"
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
except Exception as e:
|
||||
error_msg = f"Error (Ollama): {e}"
|
||||
print_pg(error_msg, RED)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
def print_token_stats(self, usage_stats, cached_token_counts, thinking_content, full_response, images):
|
||||
"""Print token statistics using pre-cached counts"""
|
||||
@@ -1,4 +1,5 @@
|
||||
from .model_manager import get_all_models, is_model_local, download_model, get_mmproj_for_model, get_mmproj_path
|
||||
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
|
||||
@@ -14,17 +15,25 @@ class PromptGenOptions:
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
available_models = get_all_models()
|
||||
backend = _preferences_cache.get("llm_backend", "llama.cpp")
|
||||
|
||||
# If no models found, show a placeholder
|
||||
if not available_models:
|
||||
available_models = ["No models found - check HuggingFace"]
|
||||
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:
|
||||
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)"
|
||||
"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"
|
||||
}),
|
||||
"image2": ("IMAGE", {
|
||||
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
|
||||
@@ -98,6 +107,7 @@ class PromptGenOptions:
|
||||
}
|
||||
|
||||
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"
|
||||
@@ -117,16 +127,23 @@ class PromptGenOptions:
|
||||
options = {}
|
||||
|
||||
# Handle model selection and download if needed
|
||||
if model and model != "No models found - check HuggingFace":
|
||||
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 VL models, also check if mmproj exists
|
||||
# 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 VL model, check if mmproj is present
|
||||
# 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}")
|
||||
@@ -1,11 +1,35 @@
|
||||
import os
|
||||
import json
|
||||
import shutil
|
||||
import time
|
||||
import folder_paths
|
||||
import server
|
||||
|
||||
|
||||
class PromptManager:
|
||||
|
||||
@staticmethod
|
||||
def get_weekly_backup_path():
|
||||
"""Get the path to the weekly rotating backup file."""
|
||||
return PromptManager.get_prompts_path() + "_bak"
|
||||
|
||||
@staticmethod
|
||||
def _refresh_weekly_backup_if_due(source_path, backup_path, interval_days=7):
|
||||
"""Refresh backup only when missing or older than interval_days."""
|
||||
if not os.path.exists(source_path):
|
||||
return
|
||||
|
||||
should_refresh = not os.path.exists(backup_path)
|
||||
if not should_refresh:
|
||||
try:
|
||||
age_seconds = time.time() - os.path.getmtime(backup_path)
|
||||
should_refresh = age_seconds >= (interval_days * 24 * 60 * 60)
|
||||
except Exception:
|
||||
should_refresh = True
|
||||
|
||||
if should_refresh:
|
||||
shutil.copy2(source_path, backup_path)
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
prompts_data = PromptManager.load_prompts()
|
||||
@@ -13,7 +37,7 @@ class PromptManager:
|
||||
|
||||
all_prompts = set()
|
||||
for category_prompts in prompts_data.values():
|
||||
all_prompts.update(category_prompts.keys())
|
||||
all_prompts.update(k for k in category_prompts.keys() if k != "__meta__")
|
||||
|
||||
all_prompts.add("")
|
||||
all_prompts_list = sorted(list(all_prompts))
|
||||
@@ -24,7 +48,7 @@ class PromptManager:
|
||||
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_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", "")
|
||||
@@ -45,11 +69,18 @@ class PromptManager:
|
||||
}
|
||||
|
||||
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"""
|
||||
@@ -58,7 +89,7 @@ class PromptManager:
|
||||
@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")
|
||||
return os.path.join(os.path.dirname(os.path.dirname(__file__)), "default_prompts.json")
|
||||
|
||||
@classmethod
|
||||
def load_prompts(cls):
|
||||
@@ -72,6 +103,26 @@ class PromptManager:
|
||||
return json.load(f)
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error loading user prompts: {e}")
|
||||
# Try backup variants before falling back to defaults.
|
||||
# Never overwrite a user file just because parsing failed.
|
||||
backup_candidates = [
|
||||
cls.get_weekly_backup_path(),
|
||||
user_path + ".bak",
|
||||
user_path + ".backup",
|
||||
user_path + ".tmp",
|
||||
]
|
||||
for backup_path in backup_candidates:
|
||||
if not os.path.exists(backup_path):
|
||||
continue
|
||||
try:
|
||||
with open(backup_path, 'r', encoding='utf-8') as f:
|
||||
backup_data = json.load(f)
|
||||
print(f"[PromptManager] Recovered prompts from backup: {backup_path}")
|
||||
return backup_data
|
||||
except Exception as be:
|
||||
print(f"[PromptManager] Backup load failed ({backup_path}): {be}")
|
||||
print("[PromptManager] User prompt file exists but could not be parsed; not overwriting with defaults.")
|
||||
return {}
|
||||
|
||||
if os.path.exists(default_path):
|
||||
try:
|
||||
@@ -88,10 +139,19 @@ class PromptManager:
|
||||
|
||||
@staticmethod
|
||||
def sort_prompts_data(data):
|
||||
"""Sort categories and prompts alphabetically (case-insensitive)"""
|
||||
"""Sort categories and prompts alphabetically (case-insensitive), preserving __meta__"""
|
||||
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()))
|
||||
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
|
||||
@@ -99,13 +159,25 @@ class PromptManager:
|
||||
"""Save prompts to user folder"""
|
||||
user_path = cls.get_prompts_path()
|
||||
sorted_data = cls.sort_prompts_data(data)
|
||||
tmp_path = user_path + ".tmp"
|
||||
bak_path = cls.get_weekly_backup_path()
|
||||
|
||||
try:
|
||||
os.makedirs(os.path.dirname(user_path), exist_ok=True)
|
||||
with open(user_path, 'w', encoding='utf-8') as f:
|
||||
# Weekly rotating backup: refresh at most once every 7 days.
|
||||
cls._refresh_weekly_backup_if_due(user_path, bak_path)
|
||||
|
||||
# Atomic write: write temp then replace to avoid truncated/corrupt files.
|
||||
with open(tmp_path, 'w', encoding='utf-8') as f:
|
||||
json.dump(sorted_data, f, indent=2, ensure_ascii=False)
|
||||
os.replace(tmp_path, user_path)
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error saving prompts: {e}")
|
||||
try:
|
||||
if os.path.exists(tmp_path):
|
||||
os.remove(tmp_path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
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"""
|
||||
@@ -179,8 +251,8 @@ async def save_prompt(request):
|
||||
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"})
|
||||
if not category or not name:
|
||||
return server.web.json_response({"success": False, "error": "Category and name are required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
|
||||
@@ -197,13 +269,18 @@ async def save_prompt(request):
|
||||
print(f"[PromptManager] Removing old casing '{old_name}' before saving as '{name}'")
|
||||
del prompts[category][old_name]
|
||||
|
||||
# Save prompt in dict, preserving any existing lora data from PromptManagerAdvanced
|
||||
# Save prompt in dict, preserving any existing lora data, trigger words, thumbnail, and nsfw from PromptManagerAdvanced
|
||||
existing_data = prompts[category].get(name, {})
|
||||
prompts[category][name] = {
|
||||
"prompt": text,
|
||||
"loras_a": existing_data.get("loras_a", []),
|
||||
"loras_b": existing_data.get("loras_b", [])
|
||||
"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})
|
||||
@@ -259,3 +336,45 @@ async def delete_prompt(request):
|
||||
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 = data.get("mode", "merge")
|
||||
|
||||
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()
|
||||
|
||||
for category, category_prompts in imported_data.items():
|
||||
if not isinstance(category_prompts, dict):
|
||||
continue
|
||||
|
||||
if category not in prompts:
|
||||
prompts[category] = {}
|
||||
|
||||
for prompt_name, prompt_data in category_prompts.items():
|
||||
# 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}
|
||||
|
||||
PromptManager.save_prompts(prompts)
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,443 @@
|
||||
"""
|
||||
ComfyUI Workflow Bridge - Pure passthrough node.
|
||||
Unpacks workflow_data into individual typed outputs.
|
||||
Any connected optional input overrides the corresponding field before output.
|
||||
Models (MODEL/CLIP/VAE) are passed through only - use WorkflowModelLoader for loading.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import folder_paths
|
||||
import comfy.samplers
|
||||
from ..py.lora_utils import resolve_lora_path
|
||||
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")
|
||||
|
||||
|
||||
class _AnyType(str):
|
||||
"""Comfy wildcard type that can connect to any socket type."""
|
||||
|
||||
def __ne__(self, _other):
|
||||
return False
|
||||
|
||||
|
||||
ANY_TYPE = _AnyType("ANY")
|
||||
|
||||
|
||||
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
|
||||
|
||||
|
||||
_LIVE_SAMPLERS, _LIVE_SCHEDULERS = _get_live_ksampler_combo_types()
|
||||
|
||||
|
||||
DEFAULT_WORKFLOW_DATA = {
|
||||
"_source": "WorkflowBridge",
|
||||
"family": "",
|
||||
"model_a": "",
|
||||
"model_b": "",
|
||||
"positive_prompt": "",
|
||||
"negative_prompt": "",
|
||||
"loras_a": [],
|
||||
"loras_b": [],
|
||||
"vae": "",
|
||||
"clip": [],
|
||||
"clip_type": "",
|
||||
"loader_type": "",
|
||||
"sampler": {
|
||||
"steps_a": 10,
|
||||
"steps_b": 10,
|
||||
"cfg": 5,
|
||||
"seed_a": 0,
|
||||
"seed_b": 0,
|
||||
"sampler_name": "euler",
|
||||
"scheduler": "simple",
|
||||
},
|
||||
"resolution": {
|
||||
"width": 512,
|
||||
"height": 512,
|
||||
"batch_size": 1,
|
||||
"length": 1,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class WorkflowBridge:
|
||||
"""
|
||||
Pure passthrough bridge node.
|
||||
Unpacks workflow_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()
|
||||
cls._SAMPLER_ENUM = samplers
|
||||
cls._SCHEDULER_ENUM = schedulers
|
||||
cls.RETURN_TYPES = (
|
||||
"WORKFLOW_DATA",
|
||||
"MODEL", "MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", ANY_TYPE,
|
||||
"INT", "INT", "INT", "INT", "FLOAT",
|
||||
cls._SAMPLER_ENUM, cls._SCHEDULER_ENUM,
|
||||
"STRING", "STRING",
|
||||
"LORA_STACK", "LORA_STACK",
|
||||
"INT", "INT", "INT", "INT",
|
||||
"STRING", "STRING", "STRING", "STRING",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
cls._sync_combo_types()
|
||||
return {
|
||||
"required": {},
|
||||
"optional": {
|
||||
"workflow_data": ("WORKFLOW_DATA", {"forceInput": True, "tooltip": "Optional workflow data input. If omitted, bridge starts from an empty workflow_data dict."}),
|
||||
"model_a": ("MODEL", {"tooltip": "Pass-through Model A"}),
|
||||
"model_b": ("MODEL", {"tooltip": "Pass-through Model B"}),
|
||||
"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": (ANY_TYPE, {"tooltip": "Pass-through extra data (any type)"}),
|
||||
"seed_a": ("INT", {"forceInput": True, "tooltip": "Override seed A"}),
|
||||
"seed_b": ("INT", {"forceInput": True, "tooltip": "Override seed B (dual-sampler)"}),
|
||||
"steps_a": ("INT", {"forceInput": True, "tooltip": "Override sampling steps A"}),
|
||||
"steps_b": ("INT", {"forceInput": True, "tooltip": "Override sampling steps B (dual-sampler)"}),
|
||||
"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"}),
|
||||
"pos_prompt": ("STRING", {"forceInput": True, "tooltip": "Override positive prompt"}),
|
||||
"neg_prompt": ("STRING", {"forceInput": True, "tooltip": "Override negative prompt"}),
|
||||
"lora_stack_a": ("LORA_STACK", {"tooltip": "Override LoRA stack A"}),
|
||||
"lora_stack_b": ("LORA_STACK", {"tooltip": "Override LoRA stack B"}),
|
||||
"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_a_name": ("STRING", {"forceInput": True, "tooltip": "Optional Model A name/path. Resolves and writes workflow_data['model_a']."}),
|
||||
"model_b_name": ("STRING", {"forceInput": True, "tooltip": "Optional Model B name/path. Resolves and writes workflow_data['model_b']."}),
|
||||
"clip_name": ("STRING", {"forceInput": True, "tooltip": "Optional CLIP name/path. Resolves and writes workflow_data['clip']."}),
|
||||
"vae_name": ("STRING", {"forceInput": True, "tooltip": "Optional VAE name/path. Resolves and writes workflow_data['vae']."}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = (
|
||||
"WORKFLOW_DATA",
|
||||
"MODEL", "MODEL", "CLIP", "CONDITIONING", "CONDITIONING", "VAE", "LATENT", "IMAGE", "MASK", ANY_TYPE,
|
||||
"INT", "INT", "INT", "INT", "FLOAT",
|
||||
_LIVE_SAMPLERS, _LIVE_SCHEDULERS,
|
||||
"STRING", "STRING",
|
||||
"LORA_STACK", "LORA_STACK",
|
||||
"INT", "INT", "INT", "INT",
|
||||
"STRING", "STRING", "STRING", "STRING",
|
||||
)
|
||||
RETURN_NAMES = (
|
||||
"workflow_data",
|
||||
"model_a", "model_b", "clip", "positive", "negative", "vae", "latent", "image", "mask", "extra",
|
||||
"seed_a", "seed_b", "steps_a", "steps_b", "cfg",
|
||||
"sampler_name", "scheduler",
|
||||
"pos_prompt", "neg_prompt",
|
||||
"lora_stack_a", "lora_stack_b",
|
||||
"width", "height", "batch_size", "length",
|
||||
"model_a_name", "model_b_name", "clip_name", "vae_name",
|
||||
)
|
||||
FUNCTION = "unpack"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = (
|
||||
"Pure passthrough bridge node. Unpacks workflow_data into individual "
|
||||
"typed outputs. Models are forwarded from connected inputs only."
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def unpack(self, workflow_data=None, **kwargs):
|
||||
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(workflow_data, str):
|
||||
try:
|
||||
incoming_wf = json.loads(workflow_data)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
incoming_wf = {}
|
||||
elif isinstance(workflow_data, dict):
|
||||
incoming_wf = dict(workflow_data)
|
||||
else:
|
||||
incoming_wf = {}
|
||||
|
||||
# Start from a full empty-workflow template, then layer incoming values.
|
||||
wf = dict(DEFAULT_WORKFLOW_DATA)
|
||||
if isinstance(incoming_wf, dict):
|
||||
wf.update(incoming_wf)
|
||||
|
||||
incoming_sampler = incoming_wf.get('sampler')
|
||||
if isinstance(incoming_sampler, dict):
|
||||
wf['sampler'] = dict(DEFAULT_WORKFLOW_DATA['sampler'])
|
||||
wf['sampler'].update(incoming_sampler)
|
||||
|
||||
incoming_resolution = incoming_wf.get('resolution')
|
||||
if isinstance(incoming_resolution, dict):
|
||||
wf['resolution'] = dict(DEFAULT_WORKFLOW_DATA['resolution'])
|
||||
wf['resolution'].update(incoming_resolution)
|
||||
|
||||
sampler = dict(wf.get('sampler', DEFAULT_WORKFLOW_DATA['sampler']))
|
||||
resolution = dict(wf.get('resolution', DEFAULT_WORKFLOW_DATA['resolution']))
|
||||
|
||||
# -- Apply top-level overrides -------------------------------
|
||||
pos_text = kwargs.get('pos_prompt')
|
||||
if pos_text is not None:
|
||||
wf['positive_prompt'] = pos_text
|
||||
|
||||
neg_text = kwargs.get('neg_prompt')
|
||||
if neg_text is not None:
|
||||
wf['negative_prompt'] = neg_text
|
||||
|
||||
# -- LoRA stack overrides ------------------------------------
|
||||
if kwargs.get('lora_stack_a') is not None:
|
||||
wf['loras_a'] = [
|
||||
{'name': n, 'model_strength': ms, 'clip_strength': cs}
|
||||
for n, ms, cs in kwargs['lora_stack_a']
|
||||
]
|
||||
if kwargs.get('lora_stack_b') is not None:
|
||||
wf['loras_b'] = [
|
||||
{'name': n, 'model_strength': ms, 'clip_strength': cs}
|
||||
for n, ms, cs in kwargs['lora_stack_b']
|
||||
]
|
||||
|
||||
# -- 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 ---------------------------------------
|
||||
for key in ('steps_a', 'steps_b', 'cfg', 'seed_a', 'seed_b', 'sampler_name', 'scheduler'):
|
||||
if kwargs.get(key) is not None:
|
||||
sampler[key] = kwargs[key]
|
||||
wf['sampler'] = sampler
|
||||
|
||||
# -- Model/CLIP/VAE name overrides ---------------------------
|
||||
model_a_name_in = kwargs.get('model_a_name')
|
||||
model_b_name_in = kwargs.get('model_b_name')
|
||||
clip_name_in = kwargs.get('clip_name')
|
||||
vae_name_in = kwargs.get('vae_name')
|
||||
|
||||
if isinstance(model_a_name_in, str) and model_a_name_in.strip():
|
||||
resolved_a, _ = resolve_model_name(model_a_name_in)
|
||||
wf['model_a'] = resolved_a or os.path.basename(model_a_name_in.strip().replace("\\", "/"))
|
||||
|
||||
family = get_model_family(wf['model_a'])
|
||||
if family:
|
||||
wf['family'] = family
|
||||
family_spec = MODEL_FAMILIES.get(family, {})
|
||||
wf['clip_type'] = family_spec.get('clip_type', '')
|
||||
wf['loader_type'] = 'checkpoint' if family_spec.get('checkpoint', False) else 'unet'
|
||||
|
||||
if isinstance(model_b_name_in, str) and model_b_name_in.strip():
|
||||
resolved_b, _ = resolve_model_name(model_b_name_in)
|
||||
wf['model_b'] = resolved_b or os.path.basename(model_b_name_in.strip().replace("\\", "/"))
|
||||
|
||||
if isinstance(clip_name_in, str) and clip_name_in.strip():
|
||||
resolved_clip, _ = _resolve_rel_path(clip_name_in, ["text_encoders", "clip", "checkpoints"])
|
||||
wf['clip'] = [resolved_clip] if resolved_clip else []
|
||||
|
||||
if isinstance(vae_name_in, str) and vae_name_in.strip():
|
||||
resolved_vae, _ = _resolve_rel_path(vae_name_in, ["vae", "checkpoints"])
|
||||
wf['vae'] = resolved_vae
|
||||
|
||||
# -- Pass-through MODEL / CLIP / VAE -------------------------
|
||||
# Priority: explicit connected inputs > embedded objects in workflow_data.
|
||||
model_a = kwargs.get('model_a')
|
||||
if model_a is None:
|
||||
model_a = wf.get('MODEL_A')
|
||||
|
||||
model_b = kwargs.get('model_b')
|
||||
if model_b is None:
|
||||
model_b = wf.get('MODEL_B')
|
||||
|
||||
clip = kwargs.get('clip')
|
||||
if clip is None:
|
||||
clip = wf.get('CLIP')
|
||||
|
||||
vae = kwargs.get('vae')
|
||||
if vae is None:
|
||||
vae = wf.get('VAE')
|
||||
|
||||
positive = kwargs.get('positive')
|
||||
if positive is None:
|
||||
positive = wf.get('POSITIVE')
|
||||
|
||||
negative = kwargs.get('negative')
|
||||
if negative is None:
|
||||
negative = wf.get('NEGATIVE')
|
||||
|
||||
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')
|
||||
|
||||
extra = kwargs.get('extra')
|
||||
if extra is None:
|
||||
extra = wf.get('EXTRA')
|
||||
|
||||
if model_a is not None:
|
||||
wf['MODEL_A'] = model_a
|
||||
if model_b is not None:
|
||||
wf['MODEL_B'] = model_b
|
||||
if clip is not None:
|
||||
wf['CLIP'] = clip
|
||||
if vae is not None:
|
||||
wf['VAE'] = vae
|
||||
if positive is not None:
|
||||
wf['POSITIVE'] = positive
|
||||
if negative is not None:
|
||||
wf['NEGATIVE'] = negative
|
||||
if latent is not None:
|
||||
wf['LATENT'] = latent
|
||||
if image is not None:
|
||||
wf['IMAGE'] = image
|
||||
if mask is not None:
|
||||
wf['MASK'] = mask
|
||||
if extra is not None:
|
||||
wf['EXTRA'] = extra
|
||||
|
||||
# -- 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.
|
||||
_lora_found_cache = {}
|
||||
|
||||
def _lora_is_found(name):
|
||||
if not name:
|
||||
return False
|
||||
if name in _lora_found_cache:
|
||||
return _lora_found_cache[name]
|
||||
_, found = resolve_lora_path(name)
|
||||
_lora_found_cache[name] = bool(found)
|
||||
return _lora_found_cache[name]
|
||||
|
||||
def _is_active_available_found(lora_item):
|
||||
if not isinstance(lora_item, dict):
|
||||
return False
|
||||
lora_name = lora_item.get('name')
|
||||
if not lora_name:
|
||||
return False
|
||||
if lora_item.get('active', True) is False:
|
||||
return False
|
||||
if lora_item.get('available', True) is False:
|
||||
return False
|
||||
return _lora_is_found(lora_name)
|
||||
|
||||
lora_stack_a = [
|
||||
(item['name'], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
|
||||
for item in wf.get('loras_a', [])
|
||||
if _is_active_available_found(item)
|
||||
]
|
||||
lora_stack_b = [
|
||||
(item['name'], item.get('model_strength', 1.0), item.get('clip_strength', 1.0))
|
||||
for item in wf.get('loras_b', [])
|
||||
if _is_active_available_found(item)
|
||||
]
|
||||
|
||||
# -- Extract all output values -------------------------------
|
||||
model_a_name = _short_display_name(wf.get('model_a', ''))
|
||||
model_b_name = _short_display_name(wf.get('model_b', ''))
|
||||
clip_name = ''
|
||||
clip_field = wf.get('clip', [])
|
||||
if isinstance(clip_field, list) and clip_field:
|
||||
clip_name = _short_display_name(clip_field[0])
|
||||
elif isinstance(clip_field, str):
|
||||
clip_name = _short_display_name(clip_field)
|
||||
vae_name = _short_display_name(wf.get('vae', ''))
|
||||
|
||||
return (
|
||||
wf,
|
||||
model_a, model_b, clip, positive, negative, vae, latent, image, mask, extra,
|
||||
sampler.get('seed_a', sampler.get('seed', 0)),
|
||||
sampler.get('seed_b', 0) or 0,
|
||||
sampler.get('steps_a', sampler.get('steps', 10)),
|
||||
sampler.get('steps_b', sampler.get('steps_a', sampler.get('steps', 10))),
|
||||
sampler.get('cfg', 5.0),
|
||||
sampler.get('sampler_name', 'euler'),
|
||||
sampler.get('scheduler', 'simple'),
|
||||
wf.get('positive_prompt', ''),
|
||||
wf.get('negative_prompt', ''),
|
||||
lora_stack_a,
|
||||
lora_stack_b,
|
||||
resolution.get('width', 512),
|
||||
resolution.get('height', 512),
|
||||
resolution.get('batch_size', 1),
|
||||
resolution.get('length', 0) or 0,
|
||||
model_a_name,
|
||||
model_b_name,
|
||||
clip_name,
|
||||
vae_name,
|
||||
)
|
||||
@@ -0,0 +1,273 @@
|
||||
"""
|
||||
Workflow Manager - stripped-down workflow_data editor based on PromptManagerAdvanced.
|
||||
|
||||
Differences from PromptManagerAdvanced:
|
||||
- workflow_data input/output only (no prompt/lora stack outputs)
|
||||
- no use_* switches
|
||||
- no trigger words pipeline
|
||||
"""
|
||||
|
||||
import json
|
||||
import base64
|
||||
from io import BytesIO
|
||||
|
||||
import server
|
||||
|
||||
from ..py.workflow_data_utils import to_json_safe_workflow_data
|
||||
from .prompt_manager_adv import PromptManagerAdvanced
|
||||
|
||||
try:
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
IMAGE_SUPPORT = True
|
||||
except ImportError:
|
||||
IMAGE_SUPPORT = False
|
||||
|
||||
|
||||
def _image_to_base64_thumbnail(image_tensor, max_size=200):
|
||||
if not IMAGE_SUPPORT or image_tensor is None:
|
||||
return None
|
||||
|
||||
try:
|
||||
img_array = image_tensor[0] if len(image_tensor.shape) == 4 else image_tensor
|
||||
if hasattr(img_array, "cpu"):
|
||||
img_array = img_array.cpu().numpy()
|
||||
img_array = (img_array * 255).astype(np.uint8)
|
||||
img = Image.fromarray(img_array)
|
||||
|
||||
width, height = img.size
|
||||
min_dim = min(width, height)
|
||||
if min_dim > max_size:
|
||||
scale = max_size / min_dim
|
||||
img = img.resize((int(width * scale), int(height * scale)), Image.LANCZOS)
|
||||
|
||||
buffer = BytesIO()
|
||||
img.save(buffer, format="JPEG", quality=85)
|
||||
base64_str = base64.b64encode(buffer.getvalue()).decode("utf-8")
|
||||
return f"data:image/jpeg;base64,{base64_str}"
|
||||
except Exception as e:
|
||||
print(f"[WorkflowManager] Thumbnail generation failed: {e}")
|
||||
return None
|
||||
|
||||
|
||||
class WorkflowManager(PromptManagerAdvanced):
|
||||
"""Workflow-focused manager that edits and forwards WORKFLOW_DATA."""
|
||||
|
||||
@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"
|
||||
|
||||
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}),
|
||||
"text": ("STRING", {
|
||||
"multiline": True,
|
||||
"default": first_prompt_text,
|
||||
"placeholder": "Enter prompt text",
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "Edit workflow_data prompt text directly",
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"workflow_data": ("WORKFLOW_DATA", {"forceInput": True, "tooltip": "Connected workflow_data to edit/forward"}),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID",
|
||||
"loras_a_toggle": "STRING",
|
||||
"loras_b_toggle": "STRING",
|
||||
"saved_workflow_data": "STRING",
|
||||
},
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Workflow-data focused manager (no use switches, no trigger words)."
|
||||
RETURN_TYPES = ("WORKFLOW_DATA",)
|
||||
RETURN_NAMES = ("workflow_data",)
|
||||
FUNCTION = "get_workflow"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, category, name, text="", **kwargs):
|
||||
workflow_data = kwargs.get("workflow_data", 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", "")
|
||||
return (
|
||||
category,
|
||||
name,
|
||||
text,
|
||||
str(workflow_data) if workflow_data else None,
|
||||
loras_a_toggle or "",
|
||||
loras_b_toggle or "",
|
||||
saved_workflow_data or "",
|
||||
)
|
||||
|
||||
def get_workflow(
|
||||
self,
|
||||
category,
|
||||
name,
|
||||
text="",
|
||||
workflow_data=None,
|
||||
unique_id=None,
|
||||
loras_a_toggle=None,
|
||||
loras_b_toggle=None,
|
||||
saved_workflow_data=None,
|
||||
):
|
||||
prompts_data = self.load_prompts()
|
||||
prompt_entry = prompts_data.get(category, {}).get(name, {}) if isinstance(prompts_data, dict) else {}
|
||||
stored_prompt_wf = prompt_entry.get("workflow_data") if isinstance(prompt_entry, dict) else None
|
||||
|
||||
live_workflow_data = None
|
||||
if isinstance(workflow_data, dict):
|
||||
live_workflow_data = workflow_data
|
||||
elif isinstance(workflow_data, str) and workflow_data.strip():
|
||||
try:
|
||||
parsed = json.loads(workflow_data)
|
||||
if isinstance(parsed, dict):
|
||||
live_workflow_data = parsed
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
live_workflow_data = None
|
||||
|
||||
hidden_saved_wf = None
|
||||
if isinstance(saved_workflow_data, str) and saved_workflow_data.strip():
|
||||
try:
|
||||
parsed_saved = json.loads(saved_workflow_data)
|
||||
if isinstance(parsed_saved, dict):
|
||||
hidden_saved_wf = parsed_saved
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
hidden_saved_wf = None
|
||||
|
||||
# WorkflowManager should prefer live connected workflow_data when present,
|
||||
# then fall back to local serialized state.
|
||||
resolved_workflow_data = live_workflow_data if isinstance(live_workflow_data, dict) else None
|
||||
if resolved_workflow_data is None:
|
||||
resolved_workflow_data = hidden_saved_wf
|
||||
if resolved_workflow_data is None and isinstance(stored_prompt_wf, dict):
|
||||
resolved_workflow_data = stored_prompt_wf
|
||||
|
||||
wf = resolved_workflow_data if isinstance(resolved_workflow_data, dict) else {}
|
||||
incoming_wf = live_workflow_data if isinstance(live_workflow_data, dict) else None
|
||||
output_text = (wf.get("positive_prompt", "") or text or "")
|
||||
generated_thumbnail = _image_to_base64_thumbnail(wf.get("IMAGE")) if isinstance(wf, dict) else None
|
||||
incoming_thumbnail = _image_to_base64_thumbnail(incoming_wf.get("IMAGE")) if isinstance(incoming_wf, dict) else None
|
||||
workflow_thumbnail = 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
|
||||
)
|
||||
)
|
||||
)
|
||||
|
||||
# Build preset stacks from saved toggle state.
|
||||
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 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 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.get("loras_a", [])
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
wf_loras_b = [
|
||||
(lora["name"], lora.get("model_strength", 1.0), lora.get("clip_strength", 1.0))
|
||||
for lora in wf.get("loras_b", [])
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
|
||||
# WorkflowManager is workflow-data centric: workflow LoRAs are base, preset toggles merge in.
|
||||
merged_stack_a = self._merge_lora_stacks(wf_loras_a, preset_stack_a) if (wf_loras_a or preset_stack_a) else []
|
||||
merged_stack_b = self._merge_lora_stacks(wf_loras_b, preset_stack_b) if (wf_loras_b or preset_stack_b) else []
|
||||
|
||||
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(incoming_wf) if isinstance(incoming_wf, 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(wf_loras_a) if wf_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 = dict(resolved_workflow_data) if isinstance(resolved_workflow_data, dict) else {}
|
||||
out_workflow_data["positive_prompt"] = output_text
|
||||
out_workflow_data["loras_a"] = [
|
||||
{
|
||||
"name": 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),
|
||||
"found": lora.get("found", lora.get("available", True)),
|
||||
}
|
||||
for lora in loras_a_display
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
out_workflow_data["loras_b"] = [
|
||||
{
|
||||
"name": 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),
|
||||
"found": lora.get("found", lora.get("available", True)),
|
||||
}
|
||||
for lora in loras_b_display
|
||||
if isinstance(lora, dict) and lora.get("name")
|
||||
]
|
||||
out_workflow_data["_source"] = "WorkflowManager"
|
||||
|
||||
return (out_workflow_data,)
|
||||
|
||||
def check_lazy_status(self, category, name, text="", **kwargs):
|
||||
return []
|
||||
@@ -0,0 +1,434 @@
|
||||
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(
|
||||
"[WorkflowModelLoader] 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"[WorkflowModelLoader] 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 _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"[WorkflowModelLoader] 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"[WorkflowModelLoader] 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"[WorkflowModelLoader] 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"[WorkflowModelLoader] 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"[WorkflowModelLoader] 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", "STRING")
|
||||
RETURN_NAMES = ("model", "clip", "vae", "model_name")
|
||||
FUNCTION = "get_model"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"workflow_data": ("WORKFLOW_DATA", {
|
||||
"tooltip": "Workflow data containing model name strings to load.",
|
||||
"forceInput": True,
|
||||
}),
|
||||
"model": (["model_a", "model_b"], {
|
||||
"default": "model_a",
|
||||
"tooltip": "Which model slot to load from workflow_data.",
|
||||
}),
|
||||
"weight_dtype": (WEIGHT_DTYPE_OPTIONS, {
|
||||
"default": "default",
|
||||
"tooltip": "Weight precision override for diffusion/UNet models. Ignored for checkpoints.",
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
def get_model(self, workflow_data, model="model_a", weight_dtype="default"):
|
||||
spec = self._normalize_spec(workflow_data)
|
||||
selected_model_slot = model
|
||||
if selected_model_slot not in ("model_a", "model_b"):
|
||||
selected_model_slot = "model_a"
|
||||
|
||||
self._model_key = selected_model_slot
|
||||
self._weight_dtype = weight_dtype
|
||||
loader_type = spec.get("loader_type", "").lower()
|
||||
selected_name = spec.get(selected_model_slot, "")
|
||||
selected_display_name = _short_display_name(selected_name)
|
||||
|
||||
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"[WorkflowModelLoader] Unsupported loader_type: {spec.get('loader_type')}"
|
||||
)
|
||||
|
||||
result = (*core_result, selected_display_name)
|
||||
|
||||
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 '(from checkpoint)', '(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["loader_type"] = (spec.get("loader_type") or "").strip()
|
||||
spec["clip_type"] = (spec.get("clip_type") or "").strip()
|
||||
|
||||
# VAE / CLIP: placeholders like '(from checkpoint)' 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)
|
||||
@@ -1,621 +0,0 @@
|
||||
"""
|
||||
ComfyUI Prompt Manager Advanced - Extended prompt management with LoRA stack support
|
||||
Saves prompts along with associated LoRA configurations
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import folder_paths
|
||||
import server
|
||||
|
||||
|
||||
def get_available_loras():
|
||||
"""Get all available LoRAs from ComfyUI's folder system"""
|
||||
lora_files = folder_paths.get_filename_list("loras")
|
||||
return lora_files
|
||||
|
||||
|
||||
def resolve_lora_path(lora_name):
|
||||
"""
|
||||
Resolve a LoRA name to its full path using ComfyUI's folder system.
|
||||
Returns (full_path, found) tuple.
|
||||
"""
|
||||
lora_files = get_available_loras()
|
||||
|
||||
# Try exact match first (with extension)
|
||||
for lora_file in lora_files:
|
||||
if lora_file == lora_name:
|
||||
return folder_paths.get_full_path("loras", lora_file), True
|
||||
|
||||
# Try matching by name without extension
|
||||
lora_name_lower = lora_name.lower()
|
||||
for lora_file in lora_files:
|
||||
file_name_no_ext = os.path.splitext(os.path.basename(lora_file))[0]
|
||||
if file_name_no_ext.lower() == lora_name_lower:
|
||||
return folder_paths.get_full_path("loras", lora_file), True
|
||||
|
||||
# Try partial match (lora_name might be just the filename, lora_file might have subdirs)
|
||||
for lora_file in lora_files:
|
||||
file_name = os.path.basename(lora_file)
|
||||
file_name_no_ext = os.path.splitext(file_name)[0]
|
||||
if file_name_no_ext.lower() == lora_name_lower or file_name.lower() == lora_name_lower:
|
||||
return folder_paths.get_full_path("loras", lora_file), True
|
||||
|
||||
# Not found
|
||||
return None, False
|
||||
|
||||
|
||||
def get_lora_relative_path(lora_name):
|
||||
"""
|
||||
Get the relative path for a LoRA that ComfyUI expects for loading.
|
||||
Returns (relative_path, found) tuple.
|
||||
"""
|
||||
lora_files = get_available_loras()
|
||||
|
||||
lora_name_lower = lora_name.lower()
|
||||
for lora_file in lora_files:
|
||||
file_name_no_ext = os.path.splitext(os.path.basename(lora_file))[0]
|
||||
if file_name_no_ext.lower() == lora_name_lower:
|
||||
return lora_file, True
|
||||
|
||||
# Not found
|
||||
return lora_name, False
|
||||
|
||||
|
||||
class PromptManagerAdvanced:
|
||||
"""
|
||||
Advanced Prompt Manager with LoRA stack integration.
|
||||
Supports saving/loading prompts with associated LoRA configurations.
|
||||
Features two LoRA stack inputs/outputs for dual LoRA workflows (e.g., Wan video).
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
prompts_data = PromptManagerAdvanced.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(category_prompts.keys())
|
||||
|
||||
all_prompts.add("")
|
||||
all_prompts_list = sorted(list(all_prompts))
|
||||
|
||||
first_category = categories[0] if categories else "Default"
|
||||
|
||||
# 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"}),
|
||||
"override_lora": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"tooltip": "When enabled, ignore connected LoRA stacks and use only the saved preset values"
|
||||
}),
|
||||
"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"}),
|
||||
"lora_stack_a": ("LORA_STACK", {"tooltip": "First LoRA stack input (e.g., for base model)"}),
|
||||
"lora_stack_b": ("LORA_STACK", {"tooltip": "Second LoRA stack input (e.g., for video model)"}),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID",
|
||||
"loras_a_toggle": "STRING",
|
||||
"loras_b_toggle": "STRING",
|
||||
}
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
RETURN_TYPES = ("STRING", "LORA_STACK", "LORA_STACK")
|
||||
RETURN_NAMES = ("prompt", "lora_stack_a", "lora_stack_b")
|
||||
FUNCTION = "get_prompt"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@staticmethod
|
||||
def get_prompts_path():
|
||||
"""Get the path to the prompts JSON file in user/default folder (shared with standard PromptManager)"""
|
||||
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 (shared with standard PromptManager)"""
|
||||
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"[PromptManagerAdvanced] 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"[PromptManagerAdvanced] Error loading default prompts: {e}")
|
||||
|
||||
# Return empty structure if all else fails
|
||||
print("[PromptManagerAdvanced] 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"[PromptManagerAdvanced] Error saving prompts: {e}")
|
||||
|
||||
def _merge_lora_stacks(self, preset_stack, connected_stack):
|
||||
"""
|
||||
Merge preset loras with connected loras, avoiding duplicates.
|
||||
Preset loras come first, then connected loras that aren't already in preset.
|
||||
|
||||
Args:
|
||||
preset_stack: List of tuples from saved preset
|
||||
connected_stack: List of tuples from connected input
|
||||
|
||||
Returns:
|
||||
Combined lora stack with no duplicates (by lora name)
|
||||
"""
|
||||
if not connected_stack:
|
||||
return preset_stack if preset_stack else []
|
||||
if not preset_stack:
|
||||
return list(connected_stack)
|
||||
|
||||
# Build set of lora names from preset
|
||||
preset_names = set()
|
||||
for lora_path, _, _ in preset_stack:
|
||||
lora_name = os.path.splitext(os.path.basename(lora_path))[0]
|
||||
preset_names.add(lora_name)
|
||||
|
||||
# Start with preset, add non-duplicate connected loras
|
||||
merged = list(preset_stack)
|
||||
for lora_path, model_strength, clip_strength in connected_stack:
|
||||
lora_name = os.path.splitext(os.path.basename(lora_path))[0]
|
||||
if lora_name not in preset_names:
|
||||
merged.append((lora_path, model_strength, clip_strength))
|
||||
|
||||
return merged
|
||||
|
||||
def _process_lora_toggle(self, lora_stack, toggle_data):
|
||||
"""
|
||||
Process lora stack with toggle data to filter active loras and apply strength adjustments.
|
||||
|
||||
Args:
|
||||
lora_stack: List of tuples (lora_path, model_strength, clip_strength)
|
||||
toggle_data: JSON string or list of toggle states [{name, active, strength}, ...]
|
||||
|
||||
Returns:
|
||||
Filtered lora stack with adjusted strengths
|
||||
"""
|
||||
if not lora_stack:
|
||||
return []
|
||||
|
||||
if not toggle_data:
|
||||
return list(lora_stack)
|
||||
|
||||
# Parse toggle data if it's a string
|
||||
try:
|
||||
if isinstance(toggle_data, str):
|
||||
toggle_data = json.loads(toggle_data)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return list(lora_stack)
|
||||
|
||||
if not isinstance(toggle_data, list):
|
||||
return list(lora_stack)
|
||||
|
||||
# Create a map of toggle states by lora name
|
||||
toggle_map = {}
|
||||
for item in toggle_data:
|
||||
if isinstance(item, dict):
|
||||
name = item.get('name', '')
|
||||
toggle_map[name] = {
|
||||
'active': item.get('active', True),
|
||||
'strength': item.get('strength')
|
||||
}
|
||||
|
||||
# Filter and adjust lora stack
|
||||
filtered_stack = []
|
||||
for lora_path, model_strength, clip_strength in lora_stack:
|
||||
# Extract lora name from path
|
||||
lora_name = os.path.splitext(os.path.basename(lora_path))[0]
|
||||
|
||||
# Check toggle state
|
||||
toggle_state = toggle_map.get(lora_name, {'active': True, 'strength': None})
|
||||
|
||||
if not toggle_state['active']:
|
||||
continue # Skip inactive loras
|
||||
|
||||
# Apply strength adjustment if provided
|
||||
if toggle_state['strength'] is not None:
|
||||
adjusted_strength = float(toggle_state['strength'])
|
||||
# Scale both model and clip strength proportionally
|
||||
ratio = adjusted_strength / model_strength if model_strength != 0 else 1.0
|
||||
model_strength = adjusted_strength
|
||||
clip_strength = clip_strength * ratio
|
||||
|
||||
filtered_stack.append((lora_path, model_strength, clip_strength))
|
||||
|
||||
return filtered_stack
|
||||
|
||||
def get_prompt(self, category, name, use_external, text="", override_lora=False, llm_input="",
|
||||
lora_stack_a=None, lora_stack_b=None,
|
||||
unique_id=None, loras_a_toggle=None, loras_b_toggle=None):
|
||||
"""Return the prompt text and filtered lora stacks based on toggle states"""
|
||||
|
||||
# Choose which text to use based on the toggle
|
||||
if use_external and llm_input:
|
||||
output_text = llm_input
|
||||
else:
|
||||
output_text = text
|
||||
|
||||
# Build preset stacks from saved toggle data (these are what we display/manage)
|
||||
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 loras_b_toggle else []
|
||||
|
||||
# When override_lora is enabled, ignore connected stacks and use only saved loras
|
||||
if override_lora:
|
||||
lora_stack_a = preset_stack_a
|
||||
lora_stack_b = preset_stack_b
|
||||
else:
|
||||
# Merge: preset loras + connected loras (avoiding duplicates by lora name)
|
||||
lora_stack_a = self._merge_lora_stacks(preset_stack_a, lora_stack_a)
|
||||
lora_stack_b = self._merge_lora_stacks(preset_stack_b, lora_stack_b)
|
||||
|
||||
# Process lora stacks with toggle data (filter inactive, apply strength)
|
||||
processed_stack_a = self._process_lora_toggle(lora_stack_a, loras_a_toggle)
|
||||
processed_stack_b = self._process_lora_toggle(lora_stack_b, loras_b_toggle)
|
||||
|
||||
# Display logic depends on override mode:
|
||||
# - Override ON: Show only preset loras (what will actually be used)
|
||||
# - Override OFF: Show merged loras (preset + connected) so user sees full picture
|
||||
if override_lora:
|
||||
loras_a_display = self._format_loras_for_display(preset_stack_a) if preset_stack_a else []
|
||||
loras_b_display = self._format_loras_for_display(preset_stack_b) if preset_stack_b else []
|
||||
else:
|
||||
loras_a_display = self._format_loras_for_display(lora_stack_a) if lora_stack_a else []
|
||||
loras_b_display = self._format_loras_for_display(lora_stack_b) if lora_stack_b else []
|
||||
|
||||
# Broadcast update to frontend
|
||||
if unique_id is not None:
|
||||
server.PromptServer.instance.send_sync("prompt-manager-advanced-update", {
|
||||
"node_id": unique_id,
|
||||
"prompt": output_text,
|
||||
"use_external": use_external,
|
||||
"llm_input": llm_input,
|
||||
"loras_a": loras_a_display,
|
||||
"loras_b": loras_b_display
|
||||
})
|
||||
|
||||
return (output_text, processed_stack_a if processed_stack_a else [], processed_stack_b if processed_stack_b else [])
|
||||
|
||||
def check_lazy_status(self, category, name, use_external, text, override_lora=False, llm_input=None,
|
||||
lora_stack_a=None, lora_stack_b=None,
|
||||
unique_id=None, loras_a_toggle=None, loras_b_toggle=None):
|
||||
"""Tell ComfyUI which lazy inputs are needed based on current settings"""
|
||||
needed = []
|
||||
if use_external:
|
||||
needed.append("llm_input")
|
||||
return needed
|
||||
|
||||
def _build_stack_from_toggle(self, toggle_data):
|
||||
"""
|
||||
Build a lora stack from toggle data by resolving paths at runtime.
|
||||
This is used when no input stack is connected but we have saved lora data.
|
||||
"""
|
||||
if not toggle_data:
|
||||
return []
|
||||
|
||||
# Parse toggle data if it's a string
|
||||
try:
|
||||
if isinstance(toggle_data, str):
|
||||
toggle_data = json.loads(toggle_data)
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return []
|
||||
|
||||
if not isinstance(toggle_data, list):
|
||||
return []
|
||||
|
||||
stack = []
|
||||
missing_loras = []
|
||||
|
||||
for item in toggle_data:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
|
||||
lora_name = item.get('name', '')
|
||||
if not lora_name:
|
||||
continue
|
||||
|
||||
# Resolve the path at runtime
|
||||
relative_path, found = get_lora_relative_path(lora_name)
|
||||
|
||||
if not found:
|
||||
missing_loras.append(lora_name)
|
||||
continue # Skip missing loras
|
||||
|
||||
strength = float(item.get('strength', 1.0))
|
||||
clip_strength = float(item.get('clip_strength', strength))
|
||||
|
||||
stack.append((relative_path, strength, clip_strength))
|
||||
|
||||
# Log warning for missing loras
|
||||
if missing_loras:
|
||||
print(f"[PromptManagerAdvanced] Warning: Could not find LoRAs: {', '.join(missing_loras)}")
|
||||
|
||||
return stack
|
||||
|
||||
def _format_loras_for_display(self, lora_stack):
|
||||
"""Format lora stack for frontend display"""
|
||||
if not lora_stack:
|
||||
return []
|
||||
|
||||
display_list = []
|
||||
for lora_path, model_strength, clip_strength in lora_stack:
|
||||
lora_name = os.path.splitext(os.path.basename(lora_path))[0]
|
||||
display_list.append({
|
||||
"name": lora_name,
|
||||
"path": lora_path,
|
||||
"model_strength": model_strength,
|
||||
"clip_strength": clip_strength,
|
||||
"active": True,
|
||||
"strength": model_strength
|
||||
})
|
||||
return display_list
|
||||
|
||||
|
||||
# API Routes for Advanced Prompt Manager
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager-advanced/get-prompts")
|
||||
async def get_prompts_advanced(request):
|
||||
"""API endpoint to get all advanced prompts"""
|
||||
try:
|
||||
prompts = PromptManagerAdvanced.load_prompts()
|
||||
return server.web.json_response(prompts)
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in get_prompts API: {e}")
|
||||
return server.web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager-advanced/save-category")
|
||||
async def save_category_advanced(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 = PromptManagerAdvanced.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] = {}
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] 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-advanced/save-prompt")
|
||||
async def save_prompt_advanced(request):
|
||||
"""API endpoint to save a prompt with lora configurations"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
name = data.get("name", "").strip()
|
||||
text = data.get("text", "").strip()
|
||||
loras_a = data.get("loras_a", [])
|
||||
loras_b = data.get("loras_b", [])
|
||||
|
||||
if not category or not name:
|
||||
return server.web.json_response({"success": False, "error": "Category and name are required"})
|
||||
|
||||
prompts = PromptManagerAdvanced.load_prompts()
|
||||
|
||||
if category not in prompts:
|
||||
prompts[category] = {}
|
||||
|
||||
# Case-insensitive check for existing prompt
|
||||
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"[PromptManagerAdvanced] Removing old casing '{old_name}' before saving as '{name}'")
|
||||
del prompts[category][old_name]
|
||||
|
||||
# Normalize lora data - only save name and strengths
|
||||
# Inactive loras are not saved (filtered out by frontend)
|
||||
# Paths are resolved at runtime for portability
|
||||
def normalize_lora_data(loras):
|
||||
normalized = []
|
||||
for lora in loras:
|
||||
if isinstance(lora, dict) and lora.get('name'):
|
||||
normalized.append({
|
||||
"name": lora.get('name'),
|
||||
"strength": lora.get('strength', lora.get('model_strength', 1.0)),
|
||||
"clip_strength": lora.get('clip_strength', lora.get('strength', 1.0))
|
||||
})
|
||||
return normalized
|
||||
|
||||
# Save prompt with normalized lora data (no paths - they're resolved at runtime)
|
||||
prompts[category][name] = {
|
||||
"prompt": text,
|
||||
"loras_a": normalize_lora_data(loras_a),
|
||||
"loras_b": normalize_lora_data(loras_b)
|
||||
}
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] 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-advanced/delete-category")
|
||||
async def delete_category_advanced(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 = PromptManagerAdvanced.load_prompts()
|
||||
|
||||
if category not in prompts:
|
||||
return server.web.json_response({"success": False, "error": "Category not found"})
|
||||
|
||||
del prompts[category]
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] 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-advanced/delete-prompt")
|
||||
async def delete_prompt_advanced(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 = PromptManagerAdvanced.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]
|
||||
PromptManagerAdvanced.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] 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-advanced/check-loras")
|
||||
async def check_loras_advanced(request):
|
||||
"""API endpoint to check which LoRAs are available in the system"""
|
||||
try:
|
||||
data = await request.json()
|
||||
lora_names = data.get("lora_names", [])
|
||||
|
||||
results = {}
|
||||
for lora_name in lora_names:
|
||||
_, found = get_lora_relative_path(lora_name)
|
||||
results[lora_name] = found
|
||||
|
||||
return server.web.json_response({"success": True, "results": results})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in check_loras API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager-advanced/available-loras")
|
||||
async def get_available_loras_api(request):
|
||||
"""API endpoint to get list of all available LoRA names"""
|
||||
try:
|
||||
lora_files = get_available_loras()
|
||||
# Return just the names without extensions for easier matching
|
||||
lora_names = [os.path.splitext(os.path.basename(f))[0] for f in lora_files]
|
||||
return server.web.json_response({"success": True, "loras": sorted(set(lora_names))})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in available_loras API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager-advanced/get-prompt-data")
|
||||
async def get_prompt_data_advanced(request):
|
||||
"""API endpoint to get specific prompt data including loras with availability check"""
|
||||
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 name are required"})
|
||||
|
||||
prompts = PromptManagerAdvanced.load_prompts()
|
||||
|
||||
if category not in prompts or name not in prompts[category]:
|
||||
return server.web.json_response({"success": False, "error": "Prompt not found"})
|
||||
|
||||
prompt_data = prompts[category][name]
|
||||
|
||||
# Add availability info to loras
|
||||
def add_availability(loras):
|
||||
result = []
|
||||
for lora in loras:
|
||||
lora_copy = dict(lora)
|
||||
_, found = get_lora_relative_path(lora.get('name', ''))
|
||||
lora_copy['available'] = found
|
||||
result.append(lora_copy)
|
||||
return result
|
||||
|
||||
return server.web.json_response({
|
||||
"success": True,
|
||||
"data": {
|
||||
"prompt": prompt_data.get("prompt", ""),
|
||||
"loras_a": add_availability(prompt_data.get("loras_a", [])),
|
||||
"loras_b": add_availability(prompt_data.get("loras_b", []))
|
||||
}
|
||||
})
|
||||
except Exception as e:
|
||||
print(f"[PromptManagerAdvanced] Error in get_prompt_data API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
@@ -0,0 +1,422 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
convert_to_api.py — Convert ComfyUI UI-format workflow JSON to API format + _map.json
|
||||
|
||||
Usage:
|
||||
python tools/convert_to_api.py
|
||||
# Reads from workflows/*.json, writes to workflows/api/*_api.json + *_map.json
|
||||
|
||||
API format: dict keyed by node ID (string), each value = {"class_type": ..., "inputs": {...}}
|
||||
Map format: dict of semantic field -> [node_id_str, input_field_name]
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
|
||||
# ── Path setup ──────────────────────────────────────────────────────────────
|
||||
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
REPO_ROOT = os.path.dirname(SCRIPT_DIR)
|
||||
SRC_DIR = os.path.join(REPO_ROOT, "workflows")
|
||||
DST_DIR = os.path.join(REPO_ROOT, "workflows", "api")
|
||||
os.makedirs(DST_DIR, exist_ok=True)
|
||||
|
||||
|
||||
# ── UI → API conversion ──────────────────────────────────────────────────────
|
||||
|
||||
def ui_to_api(ui_data):
|
||||
"""
|
||||
Convert a UI-format workflow dict to API-format.
|
||||
|
||||
UI format: { nodes: [...], links: [...], ... }
|
||||
- nodes have id, type, inputs (with link IDs), outputs (with link IDs), widgets_values
|
||||
API format: { "NODE_ID": { class_type, inputs: {field: value_or_[src_id, slot]} } }
|
||||
|
||||
Widget values are embedded directly; linked inputs reference the source node+slot.
|
||||
"""
|
||||
nodes = ui_data.get("nodes", [])
|
||||
links = ui_data.get("links", [])
|
||||
|
||||
# Build link map: link_id -> (src_node_id, src_slot_index)
|
||||
# Links: [link_id, src_node_id, src_slot, dst_node_id, dst_slot, type]
|
||||
link_map = {}
|
||||
for lk in links:
|
||||
if len(lk) >= 4:
|
||||
link_map[lk[0]] = (str(lk[1]), lk[2])
|
||||
|
||||
api = {}
|
||||
for node in nodes:
|
||||
node_id = str(node["id"])
|
||||
class_type = node["type"]
|
||||
inputs_def = node.get("inputs", []) # [{name, type, link, widget?}]
|
||||
widgets_val = node.get("widgets_values", [])
|
||||
|
||||
# We need to figure out which inputs are widget-backed vs link-backed.
|
||||
# ComfyUI heuristic:
|
||||
# - If input has a "widget" key, it is widget-backed (value from widgets_values)
|
||||
# - If input has a "link" key (non-null), it is link-backed
|
||||
# - Some inputs can be either (widget overridable by link)
|
||||
|
||||
api_inputs = {}
|
||||
widget_idx = 0 # index into widgets_values
|
||||
|
||||
for inp in inputs_def:
|
||||
name = inp["name"]
|
||||
link = inp.get("link")
|
||||
has_widget = "widget" in inp
|
||||
|
||||
if link is not None:
|
||||
# Link wins
|
||||
src = link_map.get(link)
|
||||
if src:
|
||||
api_inputs[name] = [src[0], src[1]]
|
||||
else:
|
||||
# Dangling link — fall back to widget value if available
|
||||
if has_widget and widget_idx < len(widgets_val):
|
||||
api_inputs[name] = widgets_val[widget_idx]
|
||||
widget_idx += 1
|
||||
elif has_widget:
|
||||
if widget_idx < len(widgets_val):
|
||||
api_inputs[name] = widgets_val[widget_idx]
|
||||
widget_idx += 1
|
||||
# else: pure output-only input — skip
|
||||
|
||||
# Any remaining widgets_values beyond named widget inputs are for
|
||||
# implicit widget-only nodes (e.g. seed control extra slot "control_after_generate")
|
||||
# We inject them by matching known extra widget names per class_type
|
||||
_inject_extra_widgets(class_type, api_inputs, widgets_val, widget_idx)
|
||||
|
||||
api[node_id] = {
|
||||
"class_type": class_type,
|
||||
"inputs": api_inputs,
|
||||
}
|
||||
|
||||
return api
|
||||
|
||||
|
||||
def _inject_extra_widgets(class_type, api_inputs, widgets_val, start_idx):
|
||||
"""
|
||||
Some nodes have implicit extra widget slots not reflected in the inputs list.
|
||||
The most common: KSampler seed has a hidden 'control_after_generate' slot
|
||||
inserted after noise_seed in widgets_values, but it is NOT in the inputs
|
||||
definition — so our widget_idx counter goes off by 1 after consuming seed.
|
||||
|
||||
We fully re-map widgets_values for known node types that have hidden slots,
|
||||
overwriting anything the loop may have set incorrectly.
|
||||
"""
|
||||
# KSampler: [seed, control_after_generate, steps, cfg, sampler_name, scheduler, denoise]
|
||||
# inputs list has: seed, steps, cfg, sampler_name, scheduler, denoise (no control_after_generate)
|
||||
if class_type == "KSampler" and len(widgets_val) >= 7:
|
||||
api_inputs["seed"] = widgets_val[0]
|
||||
# widgets_val[1] = control_after_generate -- skip
|
||||
api_inputs["steps"] = widgets_val[2]
|
||||
api_inputs["cfg"] = widgets_val[3]
|
||||
api_inputs["sampler_name"] = widgets_val[4]
|
||||
api_inputs["scheduler"] = widgets_val[5]
|
||||
api_inputs["denoise"] = widgets_val[6]
|
||||
|
||||
# KSamplerAdvanced: [add_noise, noise_seed, control_after_generate, steps, cfg,
|
||||
# sampler_name, scheduler, start_at_step, end_at_step, return_with_leftover_noise]
|
||||
elif class_type == "KSamplerAdvanced" and len(widgets_val) >= 10:
|
||||
api_inputs["add_noise"] = widgets_val[0]
|
||||
api_inputs["noise_seed"] = widgets_val[1]
|
||||
# widgets_val[2] = control_after_generate -- skip
|
||||
api_inputs["steps"] = widgets_val[3]
|
||||
api_inputs["cfg"] = widgets_val[4]
|
||||
api_inputs["sampler_name"] = widgets_val[5]
|
||||
api_inputs["scheduler"] = widgets_val[6]
|
||||
api_inputs["start_at_step"] = widgets_val[7]
|
||||
api_inputs["end_at_step"] = widgets_val[8]
|
||||
api_inputs["return_with_leftover_noise"] = widgets_val[9]
|
||||
|
||||
# RandomNoise: [noise_seed, control_after_generate]
|
||||
elif class_type == "RandomNoise" and len(widgets_val) >= 1:
|
||||
api_inputs["noise_seed"] = widgets_val[0]
|
||||
# widgets_val[1] = control_after_generate -- skip
|
||||
|
||||
|
||||
# ── Map generation ───────────────────────────────────────────────────────────
|
||||
|
||||
def build_map(api, family_hint):
|
||||
"""
|
||||
Build a semantic field map for the given API workflow.
|
||||
Returns a dict: { field_name: [node_id_str, input_key] | null }
|
||||
|
||||
The map is used by WorkflowRenderer to patch values before execution.
|
||||
"""
|
||||
m = {}
|
||||
|
||||
for nid, node in api.items():
|
||||
ct = node["class_type"]
|
||||
inp = node["inputs"]
|
||||
|
||||
# ── Positive / Negative prompts ──────────────────────────────────
|
||||
if ct == "CLIPTextEncode":
|
||||
# Determine pos vs neg by looking at what this feeds into
|
||||
# We'll do a two-pass approach after the loop
|
||||
pass
|
||||
|
||||
# ── Checkpoint loader ─────────────────────────────────────────────
|
||||
if ct in ("CheckpointLoaderSimple", "CheckpointLoader"):
|
||||
m["checkpoint"] = [nid, "ckpt_name"]
|
||||
|
||||
# ── UNET loaders ─────────────────────────────────────────────────
|
||||
if ct in ("UNETLoader", "UNETLoaderGGUF"):
|
||||
if "model_a" not in m:
|
||||
m["model_a"] = [nid, "unet_name"]
|
||||
else:
|
||||
m["model_b"] = [nid, "unet_name"]
|
||||
|
||||
# ── VAE ───────────────────────────────────────────────────────────
|
||||
if ct == "VAELoader":
|
||||
m["vae"] = [nid, "vae_name"]
|
||||
|
||||
# ── CLIP / text encoder ───────────────────────────────────────────
|
||||
if ct in ("CLIPLoader", "DualCLIPLoader"):
|
||||
if ct == "DualCLIPLoader":
|
||||
m["clip_1"] = [nid, "clip_name1"]
|
||||
m["clip_2"] = [nid, "clip_name2"]
|
||||
else:
|
||||
m["clip"] = [nid, "clip_name"]
|
||||
|
||||
# ── Latent size ───────────────────────────────────────────────────
|
||||
if ct in ("EmptyLatentImage", "EmptySD3LatentImage", "EmptyHunyuanLatentVideo"):
|
||||
m["latent_width"] = [nid, "width"]
|
||||
m["latent_height"] = [nid, "height"]
|
||||
if ct == "EmptyHunyuanLatentVideo":
|
||||
m["latent_length"] = [nid, "length"]
|
||||
|
||||
# ── WanImageToVideo latent (i2v) — size comes from Resize node ───
|
||||
if ct == "WanImageToVideo":
|
||||
m["wan_i2v_latent"] = [nid, "start_image"] # image input
|
||||
# width/height fed from resize node — mapped separately
|
||||
|
||||
# ── Resize node (used in i2v for size control) ────────────────────
|
||||
if ct in ("ImageResizeKJv2", "ImageScale", "ImageResize"):
|
||||
if "resize_width" not in m:
|
||||
m["resize_width"] = [nid, "width"]
|
||||
m["resize_height"] = [nid, "height"]
|
||||
|
||||
# ── KSampler (standard) ───────────────────────────────────────────
|
||||
if ct == "KSampler":
|
||||
m["ksampler_seed"] = [nid, "seed"]
|
||||
m["ksampler_steps"] = [nid, "steps"]
|
||||
m["ksampler_cfg"] = [nid, "cfg"]
|
||||
m["ksampler_sampler"] = [nid, "sampler_name"]
|
||||
m["ksampler_scheduler"] = [nid, "scheduler"]
|
||||
m["ksampler_denoise"] = [nid, "denoise"]
|
||||
|
||||
# ── KSamplerAdvanced (WAN dual) ───────────────────────────────────
|
||||
if ct == "KSamplerAdvanced":
|
||||
if "ksampler_high_seed" not in m:
|
||||
m["ksampler_high_seed"] = [nid, "noise_seed"]
|
||||
m["ksampler_high_steps"] = [nid, "steps"]
|
||||
m["ksampler_high_start"] = [nid, "start_at_step"]
|
||||
m["ksampler_high_end"] = [nid, "end_at_step"]
|
||||
m["ksampler_high_cfg"] = [nid, "cfg"]
|
||||
m["ksampler_high_sampler"] = [nid, "sampler_name"]
|
||||
m["ksampler_high_scheduler"] = [nid, "scheduler"]
|
||||
else:
|
||||
m["ksampler_low_seed"] = [nid, "noise_seed"]
|
||||
m["ksampler_low_steps"] = [nid, "steps"]
|
||||
m["ksampler_low_start"] = [nid, "start_at_step"]
|
||||
m["ksampler_low_end"] = [nid, "end_at_step"]
|
||||
m["ksampler_low_cfg"] = [nid, "cfg"]
|
||||
m["ksampler_low_sampler"] = [nid, "sampler_name"]
|
||||
m["ksampler_low_scheduler"] = [nid, "scheduler"]
|
||||
|
||||
# ── Flux / custom samplers ────────────────────────────────────────
|
||||
if ct == "KSamplerSelect":
|
||||
m["flux_sampler"] = [nid, "sampler_name"]
|
||||
if ct in ("BasicScheduler",):
|
||||
m["flux_scheduler"] = [nid, "scheduler"]
|
||||
m["flux_steps"] = [nid, "steps"]
|
||||
m["flux_denoise"] = [nid, "denoise"]
|
||||
if ct == "Flux2Scheduler":
|
||||
m["flux2_steps"] = [nid, "steps"]
|
||||
m["flux2_width"] = [nid, "width"]
|
||||
m["flux2_height"] = [nid, "height"]
|
||||
if ct == "CFGGuider":
|
||||
m["flux2_cfg"] = [nid, "cfg"]
|
||||
if ct == "FluxGuidance":
|
||||
m["flux_guidance"] = [nid, "guidance"]
|
||||
if ct == "RandomNoise":
|
||||
m["flux_seed"] = [nid, "noise_seed"]
|
||||
|
||||
# ── PromptApplyLora ───────────────────────────────────────────────
|
||||
if ct == "PromptApplyLora":
|
||||
if "lora_stack_a" not in m:
|
||||
m["lora_stack_a"] = [nid, "lora_stack_text"]
|
||||
else:
|
||||
m["lora_stack_b"] = [nid, "lora_stack_text"]
|
||||
|
||||
# ── VAEDecode (output image) ───────────────────────────────────────
|
||||
if ct == "VAEDecode":
|
||||
m["vae_decode"] = [nid, None] # source of output IMAGE tensor
|
||||
|
||||
# ── SaveImage → mark for removal ─────────────────────────────────
|
||||
if ct == "SaveImage":
|
||||
m.setdefault("_save_nodes", []).append(nid)
|
||||
|
||||
# ── ModelSamplingSD3 (WAN shift) ──────────────────────────────────
|
||||
if ct == "ModelSamplingSD3":
|
||||
if "wan_shift_a" not in m:
|
||||
m["wan_shift_a"] = [nid, "shift"]
|
||||
else:
|
||||
m["wan_shift_b"] = [nid, "shift"]
|
||||
|
||||
# ── Two-pass: resolve CLIPTextEncode pos/neg by tracing links ────────
|
||||
_resolve_clip_text_encode(api, m)
|
||||
|
||||
return m
|
||||
|
||||
|
||||
def _resolve_clip_text_encode(api, m):
|
||||
"""
|
||||
For CLIPTextEncode nodes, determine which is positive and which is negative
|
||||
by checking what node/slot they feed into.
|
||||
"""
|
||||
# Build reverse link map: (dst_node_id, dst_slot) -> src_node_id
|
||||
# We look at each node's inputs and find CLIPTextEncode sources
|
||||
text_encode_nodes = [nid for nid, n in api.items() if n["class_type"] == "CLIPTextEncode"]
|
||||
if not text_encode_nodes:
|
||||
return
|
||||
|
||||
# For each CLIPTextEncode, check what uses its output
|
||||
# In API format, inputs reference sources as [src_node_id, src_slot]
|
||||
pos_node = None
|
||||
neg_node = None
|
||||
|
||||
for nid, node in api.items():
|
||||
for field, val in node["inputs"].items():
|
||||
if isinstance(val, list) and len(val) == 2:
|
||||
src_nid = str(val[0])
|
||||
if src_nid in text_encode_nodes:
|
||||
if field == "positive" and pos_node is None:
|
||||
pos_node = src_nid
|
||||
elif field == "negative" and neg_node is None:
|
||||
neg_node = src_nid
|
||||
# WanImageToVideo also has positive/negative
|
||||
elif field == "positive":
|
||||
pass
|
||||
elif field == "negative":
|
||||
pass
|
||||
|
||||
# Also handle FluxGuidance — positive goes into conditioning input
|
||||
if pos_node is None:
|
||||
for nid, node in api.items():
|
||||
if node["class_type"] == "FluxGuidance":
|
||||
for field, val in node["inputs"].items():
|
||||
if field == "conditioning" and isinstance(val, list):
|
||||
src = str(val[0])
|
||||
if src in text_encode_nodes:
|
||||
pos_node = src
|
||||
break
|
||||
|
||||
# For ConditioningZeroOut — that's the negative for Flux
|
||||
for nid, node in api.items():
|
||||
if node["class_type"] == "ConditioningZeroOut":
|
||||
neg_node = nid # The output of ConditioningZeroOut is the negative
|
||||
|
||||
if pos_node:
|
||||
m["positive_prompt"] = [pos_node, "text"]
|
||||
if neg_node and api.get(neg_node, {}).get("class_type") == "CLIPTextEncode":
|
||||
m["negative_prompt"] = [neg_node, "text"]
|
||||
elif neg_node and api.get(neg_node, {}).get("class_type") == "ConditioningZeroOut":
|
||||
# For Flux, negative is zero — we patch the CLIPTextEncode feeding into it
|
||||
for nid, node in api.items():
|
||||
if node["class_type"] == "ConditioningZeroOut":
|
||||
for field, val in node["inputs"].items():
|
||||
if isinstance(val, list):
|
||||
src = str(val[0])
|
||||
if api.get(src, {}).get("class_type") == "CLIPTextEncode":
|
||||
m["negative_prompt"] = [src, "text"]
|
||||
break
|
||||
|
||||
# Fallback: if only one CLIPTextEncode, it's positive
|
||||
if pos_node is None and len(text_encode_nodes) >= 1:
|
||||
m["positive_prompt"] = [text_encode_nodes[0], "text"]
|
||||
if neg_node is None and len(text_encode_nodes) >= 2:
|
||||
m["negative_prompt"] = [text_encode_nodes[1], "text"]
|
||||
|
||||
|
||||
# ── Strip SaveImage nodes from API ───────────────────────────────────────────
|
||||
|
||||
def strip_save_nodes(api, map_data):
|
||||
"""Remove SaveImage nodes from the API dict (not needed for in-process execution)."""
|
||||
save_ids = set(map_data.pop("_save_nodes", []))
|
||||
for nid in save_ids:
|
||||
api.pop(nid, None)
|
||||
# Also remove any references to these nodes from other nodes' inputs
|
||||
for node in api.values():
|
||||
node["inputs"] = {
|
||||
k: v for k, v in node["inputs"].items()
|
||||
if not (isinstance(v, list) and len(v) == 2 and str(v[0]) in save_ids)
|
||||
}
|
||||
|
||||
|
||||
# ── Main ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
FAMILY_HINTS = {
|
||||
"sdxl": "sdxl",
|
||||
"flux_1": "flux1",
|
||||
"flux_2": "flux2",
|
||||
"z_image": "zimage",
|
||||
"wan_image": "wan_image",
|
||||
"wan_video_t2v": "wan_video_t2v",
|
||||
"wan_video_i2v": "wan_video_i2v",
|
||||
"qwen_image": "qwen_image",
|
||||
}
|
||||
|
||||
def convert_file(src_path, dst_api_path, dst_map_path, family_hint):
|
||||
with open(src_path, "r", encoding="utf-8") as f:
|
||||
ui_data = json.load(f)
|
||||
|
||||
api = ui_to_api(ui_data)
|
||||
map_data = build_map(api, family_hint)
|
||||
strip_save_nodes(api, map_data)
|
||||
|
||||
with open(dst_api_path, "w", encoding="utf-8") as f:
|
||||
json.dump(api, f, indent=2)
|
||||
|
||||
with open(dst_map_path, "w", encoding="utf-8") as f:
|
||||
json.dump(map_data, f, indent=2)
|
||||
|
||||
print(f" {os.path.basename(src_path)} -> {os.path.basename(dst_api_path)} (map: {os.path.basename(dst_map_path)})")
|
||||
return api, map_data
|
||||
|
||||
|
||||
def main():
|
||||
print(f"Source: {SRC_DIR}")
|
||||
print(f"Destination: {DST_DIR}")
|
||||
print()
|
||||
|
||||
for fname in sorted(os.listdir(SRC_DIR)):
|
||||
if not fname.endswith(".json"):
|
||||
continue
|
||||
stem = fname[:-5] # strip .json
|
||||
if stem in FAMILY_HINTS:
|
||||
hint = FAMILY_HINTS[stem]
|
||||
else:
|
||||
hint = stem
|
||||
|
||||
src_path = os.path.join(SRC_DIR, fname)
|
||||
dst_api_path = os.path.join(DST_DIR, f"{stem}_api.json")
|
||||
dst_map_path = os.path.join(DST_DIR, f"{stem}_map.json")
|
||||
|
||||
try:
|
||||
api, map_data = convert_file(src_path, dst_api_path, dst_map_path, hint)
|
||||
# Print key mappings for review
|
||||
for k, v in sorted(map_data.items()):
|
||||
print(f" {k}: {v}")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f" ERROR converting {fname}: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
print("Done.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,171 @@
|
||||
"""
|
||||
Shared LoRA resolution utilities for ComfyUI-Prompt-Manager.
|
||||
|
||||
Provides fuzzy matching logic for finding LoRA files on disk, handling
|
||||
renamed LoRAs, WAN-related tokens, and partial name matches.
|
||||
|
||||
Used by: PromptManagerAdvanced, PromptExtractor, WorkflowBuilder, WorkflowRenderer.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import folder_paths
|
||||
|
||||
|
||||
# Known LoRA file extensions
|
||||
LORA_EXTENSIONS = ['.safetensors', '.ckpt', '.pt', '.bin', '.pth']
|
||||
|
||||
# Tokens to remove for fuzzy matching (case-insensitive)
|
||||
# Order matters: remove longer tokens first to avoid partial matches
|
||||
WAN_TOKENS = ['wan_2_2', 'wan22', 'wan2.2', '20epoc', 'a14b', '14b', 'i2v', 't2v']
|
||||
|
||||
|
||||
def get_available_loras():
|
||||
"""Get all available LoRAs from ComfyUI's folder system."""
|
||||
return folder_paths.get_filename_list("loras")
|
||||
|
||||
|
||||
def normalize_path_separators(path):
|
||||
"""Normalize path separators based on OS - for basename extraction only."""
|
||||
if os.name == 'nt': # Windows
|
||||
return path.replace('/', '\\')
|
||||
else: # Linux/Mac
|
||||
return path.replace('\\', '/')
|
||||
|
||||
|
||||
def strip_lora_extension(name):
|
||||
"""Remove only known LoRA file extensions, not arbitrary dots in names."""
|
||||
name_lower = name.lower()
|
||||
for ext in LORA_EXTENSIONS:
|
||||
if name_lower.endswith(ext):
|
||||
return name[:-len(ext)]
|
||||
return name
|
||||
|
||||
|
||||
def _normalize_name_for_fuzzy(name):
|
||||
"""
|
||||
Remove WAN tokens from name, treating underscores and hyphens as separators.
|
||||
Also removes content in parentheses (e.g., "MyLora (1)" becomes "MyLora").
|
||||
Returns list of remaining non-empty parts in lowercase.
|
||||
"""
|
||||
name_lower = name.lower()
|
||||
|
||||
# Remove anything in parentheses (e.g., " (1)", "(copy)", etc.)
|
||||
name_lower = re.sub(r'\s*\([^)]*\)', '', name_lower)
|
||||
|
||||
# Replace each token with a placeholder to preserve boundaries
|
||||
for token in WAN_TOKENS:
|
||||
# Use word boundary-aware replacement with _ or - as delimiter
|
||||
pattern = rf'(?:^|[_-]){re.escape(token)}(?:[_-]|$)'
|
||||
name_lower = re.sub(pattern, '_', name_lower)
|
||||
|
||||
# Split by underscore or hyphen and filter out empty strings
|
||||
parts = [p for p in re.split(r'[_-]', name_lower) if p]
|
||||
return parts
|
||||
|
||||
|
||||
def fuzzy_match_lora(lora_name, lora_files):
|
||||
"""
|
||||
Attempt to find a matching LoRA using fuzzy matching.
|
||||
Handles renamed LoRAs by removing common WAN-related tokens.
|
||||
|
||||
Example: "DR34LAY_HIGH_V2" can match "DR34LAY_I2V_14B_HIGH_V2"
|
||||
|
||||
Returns (matched_file, True) if found, (None, False) otherwise.
|
||||
"""
|
||||
# Normalize the search name
|
||||
search_parts = _normalize_name_for_fuzzy(strip_lora_extension(lora_name))
|
||||
search_set = set(search_parts)
|
||||
|
||||
# If search_set is empty after normalization, we can't do fuzzy matching
|
||||
if not search_set:
|
||||
return None, False
|
||||
|
||||
candidates = []
|
||||
for lora_file in lora_files:
|
||||
file_name_no_ext = strip_lora_extension(os.path.basename(lora_file))
|
||||
file_parts = _normalize_name_for_fuzzy(file_name_no_ext)
|
||||
file_set = set(file_parts)
|
||||
|
||||
# Check if all search parts are present in the file parts
|
||||
if search_set.issubset(file_set):
|
||||
# Calculate how well this matches (prefer closer matches)
|
||||
extra_parts = len(file_set - search_set)
|
||||
candidates.append((lora_file, file_name_no_ext, extra_parts))
|
||||
|
||||
if not candidates:
|
||||
return None, False
|
||||
|
||||
# If only one match, return it
|
||||
if len(candidates) == 1:
|
||||
return candidates[0][0], True
|
||||
|
||||
# Multiple matches - prefer ones that match i2v/t2v from original if present
|
||||
lora_name_lower = lora_name.lower()
|
||||
has_i2v = 'i2v' in lora_name_lower
|
||||
has_t2v = 't2v' in lora_name_lower
|
||||
|
||||
if has_i2v:
|
||||
i2v_matches = [c for c in candidates if 'i2v' in c[1].lower()]
|
||||
if i2v_matches:
|
||||
candidates = i2v_matches
|
||||
elif has_t2v:
|
||||
t2v_matches = [c for c in candidates if 't2v' in c[1].lower()]
|
||||
if t2v_matches:
|
||||
candidates = t2v_matches
|
||||
|
||||
# Return the match with fewest extra parts (closest match)
|
||||
candidates.sort(key=lambda x: x[2])
|
||||
return candidates[0][0], True
|
||||
|
||||
|
||||
def get_lora_relative_path(lora_name):
|
||||
"""
|
||||
Get the relative path for a LoRA that ComfyUI expects for loading.
|
||||
Returns (relative_path, found) tuple.
|
||||
Supports fuzzy matching for renamed LoRAs.
|
||||
"""
|
||||
lora_files = get_available_loras()
|
||||
|
||||
lora_name_lower = lora_name.lower()
|
||||
|
||||
# Try exact match first
|
||||
for lora_file in lora_files:
|
||||
file_name_no_ext = strip_lora_extension(os.path.basename(lora_file))
|
||||
if file_name_no_ext.lower() == lora_name_lower:
|
||||
return lora_file, True
|
||||
|
||||
# Try fuzzy match for renamed LoRAs
|
||||
fuzzy_match, found = fuzzy_match_lora(lora_name, lora_files)
|
||||
if found:
|
||||
return fuzzy_match, True
|
||||
|
||||
# Not found
|
||||
return lora_name, False
|
||||
|
||||
|
||||
def resolve_lora_path(lora_name):
|
||||
"""
|
||||
Resolve a LoRA name to its full path using ComfyUI's folder system.
|
||||
Uses exact matching first, then fuzzy matching with WAN token handling.
|
||||
Returns (full_path_or_name, found) tuple.
|
||||
"""
|
||||
lora_files = get_available_loras()
|
||||
|
||||
# Try exact match first (with extension, as-is from workflow)
|
||||
for lora_file in lora_files:
|
||||
if lora_file == lora_name:
|
||||
return folder_paths.get_full_path("loras", lora_file), True
|
||||
|
||||
# Try matching by name without extension
|
||||
lora_name_lower = lora_name.lower()
|
||||
for lora_file in lora_files:
|
||||
file_name_no_ext = strip_lora_extension(os.path.basename(lora_file))
|
||||
if file_name_no_ext.lower() == lora_name_lower:
|
||||
return folder_paths.get_full_path("loras", lora_file), True
|
||||
|
||||
# Fuzzy match for renamed LoRAs
|
||||
fuzzy_match, found = fuzzy_match_lora(lora_name, lora_files)
|
||||
if found:
|
||||
return folder_paths.get_full_path("loras", fuzzy_match), True
|
||||
|
||||
return None, False
|
||||
@@ -17,33 +17,32 @@ _preferences_cache = {
|
||||
"custom_llama_path": "",
|
||||
"custom_llama_model_path": "",
|
||||
"close_llama_on_exit": True,
|
||||
"custom_llama_port": 8080
|
||||
"custom_llama_port": 8080,
|
||||
"llm_backend": "llama.cpp", # "llama.cpp" or "ollama"
|
||||
"ollama_url": "http://127.0.0.1:11434",
|
||||
"ollama_keep_alive": "5m", # How long Ollama keeps model loaded after request
|
||||
}
|
||||
|
||||
# Predefined models - use real filenames as keys
|
||||
# Qwen3.5 models are unified vision+text — every model supports vision via its mmproj.
|
||||
# "mmproj" is the LOCAL filename we store on disk.
|
||||
# "mmproj_repo_filename" is the filename in the HuggingFace repo (may differ).
|
||||
QWEN_MODELS = {
|
||||
"Qwen3-4B-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-4B-GGUF"
|
||||
"Qwen3.5-9B-UD-Q4_K_XL.gguf": {
|
||||
"repo": "unsloth/Qwen3.5-9B-GGUF",
|
||||
"mmproj": "mmproj-Qwen3.5-9B-F16.gguf",
|
||||
"mmproj_repo_filename": "mmproj-F16.gguf"
|
||||
},
|
||||
"Qwen3-8B-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-8B-GGUF"
|
||||
"Qwen3.5-9B-Q8_0.gguf": {
|
||||
"repo": "unsloth/Qwen3.5-9B-GGUF",
|
||||
"mmproj": "mmproj-Qwen3.5-9B-F16.gguf",
|
||||
"mmproj_repo_filename": "mmproj-F16.gguf"
|
||||
},
|
||||
"Qwen3VL-4B-Instruct-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-VL-4B-Instruct-GGUF",
|
||||
"mmproj": "mmproj-Qwen3VL-4B-Instruct-Q8_0.gguf"
|
||||
"Qwen3.5-9B-UD-Q8_K_XL.gguf": {
|
||||
"repo": "unsloth/Qwen3.5-9B-GGUF",
|
||||
"mmproj": "mmproj-Qwen3.5-9B-F16.gguf",
|
||||
"mmproj_repo_filename": "mmproj-F16.gguf"
|
||||
},
|
||||
"Qwen3VL-8B-Instruct-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-VL-8B-Instruct-GGUF",
|
||||
"mmproj": "mmproj-Qwen3VL-8B-Instruct-Q8_0.gguf"
|
||||
},
|
||||
"Qwen3VL-4B-Thinking-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-VL-4B-Thinking-GGUF",
|
||||
"mmproj": "mmproj-Qwen3VL-4B-Thinking-Q8_0.gguf"
|
||||
},
|
||||
"Qwen3VL-8B-Thinking-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-VL-8B-Thinking-GGUF",
|
||||
"mmproj": "mmproj-Qwen3VL-8B-Thinking-Q8_0.gguf"
|
||||
}
|
||||
}
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager/load-preferences")
|
||||
@@ -65,7 +64,10 @@ async def save_preference(request):
|
||||
"custom_llama_path",
|
||||
"custom_llama_model_path",
|
||||
"close_llama_on_exit",
|
||||
"custom_llama_port"]:
|
||||
"custom_llama_port",
|
||||
"llm_backend",
|
||||
"ollama_url",
|
||||
"ollama_keep_alive"]:
|
||||
return server.web.json_response({"success": False, "error": "Invalid preference key"})
|
||||
|
||||
# Update in-memory cache
|
||||
@@ -76,6 +78,18 @@ async def save_preference(request):
|
||||
print(f"[Model Manager] Error saving preference: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager/ollama-models")
|
||||
async def list_ollama_models(request):
|
||||
"""API endpoint to discover available Ollama models."""
|
||||
try:
|
||||
from .ollama_wrapper import discover_ollama_models
|
||||
models, status = discover_ollama_models(_preferences_cache)
|
||||
return server.web.json_response({"models": models, "status": status})
|
||||
except Exception as e:
|
||||
return server.web.json_response({"models": [], "status": f"Error: {e}"}, status=500)
|
||||
|
||||
|
||||
def get_models_directory():
|
||||
"""Get the path to the primary models directory (ComfyUI/models/gguf) for downloads"""
|
||||
# Register both gguf and LLM folders
|
||||
@@ -176,41 +190,117 @@ def get_model_path(model_name):
|
||||
models_dir = get_models_directory()
|
||||
return os.path.join(models_dir, model_name)
|
||||
|
||||
# Quantization-related filename parts — stripped when matching models to mmproj files
|
||||
_QUANT_PARTS = frozenset({
|
||||
"Q2", "Q3", "Q4", "Q5", "Q6", "Q8",
|
||||
"K", "M", "S", "L", "XS", "XL", "XXS", "XXL",
|
||||
"IQ1", "IQ2", "IQ3", "IQ4", "NL",
|
||||
"BF16", "F16", "F32",
|
||||
"0", "1", "UD",
|
||||
})
|
||||
|
||||
|
||||
def _get_model_keywords(name):
|
||||
"""Extract normalised keyword set from a model filename for fuzzy matching.
|
||||
|
||||
Splits on hyphens, underscores, dots, and spaces, lowercases everything,
|
||||
and strips quantisation tags + the literal 'mmproj' token.
|
||||
|
||||
Example: 'qwen3.5-9b-nsfw-captioning-v3.Q8_0.gguf'
|
||||
→ {'qwen3.5', '9b', 'nsfw', 'captioning', 'v3'}
|
||||
'qwen3.5-9b-nsfw-captioning-v3.mmproj-Q8_0.gguf'
|
||||
→ {'qwen3.5', '9b', 'nsfw', 'captioning', 'v3'}
|
||||
"""
|
||||
base = os.path.splitext(os.path.basename(name))[0]
|
||||
# First split on hyphens, underscores, spaces (not dots)
|
||||
raw_parts = [p for p in re.split(r"[-_ ]", base) if p]
|
||||
# Then split tokens on dots, UNLESS the token is a version string like 'qwen3.5'
|
||||
parts = []
|
||||
for token in raw_parts:
|
||||
if re.match(r'^[a-zA-Z]+\d+\.\d+$', token):
|
||||
# Version string (e.g. 'qwen3.5') — keep intact
|
||||
parts.append(token)
|
||||
elif '.' in token:
|
||||
# Split other dotted tokens (e.g. 'v3.Q8' → 'v3', 'Q8')
|
||||
parts.extend(p for p in token.split('.') if p)
|
||||
else:
|
||||
parts.append(token)
|
||||
lc_quant = {q.lower() for q in _QUANT_PARTS}
|
||||
return {p.lower() for p in parts if p.lower() not in lc_quant and p.lower() != "mmproj" and p.lower() != "gguf"}
|
||||
|
||||
|
||||
def get_mmproj_for_model(model_name):
|
||||
"""Get the mmproj filename for a given vision model"""
|
||||
"""Get the mmproj filename for a given model from the predefined registry."""
|
||||
if model_name in QWEN_MODELS and "mmproj" in QWEN_MODELS[model_name]:
|
||||
return QWEN_MODELS[model_name]["mmproj"]
|
||||
return None
|
||||
|
||||
|
||||
def get_mmproj_path(model_name):
|
||||
"""Get the path to the mmproj file for a vision model, if it exists
|
||||
Searches for mmproj files that contain all parts of the model name
|
||||
"""Get the path to the mmproj file for a model, if it exists.
|
||||
|
||||
1. Check the explicit QWEN_MODELS mapping first.
|
||||
2. Fall back to heuristic matching by model identity (strips quant parts).
|
||||
"""
|
||||
# Get all parts of the model name (excluding .gguf)
|
||||
model_parts = [part for part in re.split(r"[-.]", os.path.splitext(os.path.basename(model_name))[0]) if part]
|
||||
# --- 1. Explicit mapping ---
|
||||
mmproj_name = get_mmproj_for_model(model_name)
|
||||
if mmproj_name:
|
||||
all_dirs = get_all_model_directories()
|
||||
for d in all_dirs:
|
||||
p = os.path.join(d, mmproj_name)
|
||||
if os.path.exists(p):
|
||||
return p
|
||||
# Mapped but file not found on disk
|
||||
return None
|
||||
|
||||
# --- 2. Heuristic: keyword-based matching ---
|
||||
# Split the model name into normalised keywords (no quant tags, no 'mmproj')
|
||||
# and find the mmproj file that shares the most keywords (minimum 4).
|
||||
model_keywords = _get_model_keywords(model_name)
|
||||
if len(model_keywords) < 2:
|
||||
return None
|
||||
|
||||
MIN_KEYWORD_MATCH = min(4, len(model_keywords)) # at least 4, or all if fewer
|
||||
|
||||
# Get all local mmproj files
|
||||
all_dirs = get_all_model_directories()
|
||||
mmproj_files = []
|
||||
best_match = None
|
||||
best_match_count = 0
|
||||
for models_dir in all_dirs:
|
||||
if os.path.exists(models_dir):
|
||||
for f in os.listdir(models_dir):
|
||||
if 'mmproj' in f.lower() and f.endswith('.gguf'):
|
||||
mmproj_files.append(f)
|
||||
if not os.path.exists(models_dir):
|
||||
continue
|
||||
for f in os.listdir(models_dir):
|
||||
if 'mmproj' not in f.lower() or not f.endswith('.gguf'):
|
||||
continue
|
||||
mmproj_keywords = _get_model_keywords(f)
|
||||
common = model_keywords & mmproj_keywords
|
||||
if len(common) >= MIN_KEYWORD_MATCH and len(common) > best_match_count:
|
||||
best_match = os.path.join(models_dir, f)
|
||||
best_match_count = len(common)
|
||||
|
||||
# Find mmproj that contains all model parts
|
||||
for mmproj_file in mmproj_files:
|
||||
# Let's split the mmproj filename to check for matching bits, we remove extension and mmproj
|
||||
mmproj_parts = [part for part in re.split(r"[-.]", os.path.splitext(os.path.basename(mmproj_file))[0].replace('mmproj', '')) if part]
|
||||
if all(part in mmproj_parts for part in model_parts):
|
||||
return get_model_path(mmproj_file)
|
||||
return best_match
|
||||
|
||||
|
||||
def has_vision_support(model_name):
|
||||
"""Check whether a model has vision capabilities.
|
||||
|
||||
Returns True if an mmproj file is available (on disk or in the registry).
|
||||
"""
|
||||
# Check explicit registry first (even if not yet downloaded)
|
||||
if get_mmproj_for_model(model_name):
|
||||
return True
|
||||
# Check if a matching mmproj file already exists on disk
|
||||
return get_mmproj_path(model_name) is not None
|
||||
|
||||
def download_model(model_name):
|
||||
"""Download a model from HuggingFace with automatic progress display
|
||||
For VL models, also downloads the matching mmproj file if needed
|
||||
"""Download a model from HuggingFace with automatic progress display.
|
||||
Also downloads the matching mmproj file if one is defined.
|
||||
|
||||
The mmproj file in the repo may have a generic name (e.g. 'mmproj-F16.gguf').
|
||||
We rename it on download to a model-specific name to avoid conflicts when
|
||||
multiple model sizes are installed side-by-side.
|
||||
|
||||
Args:
|
||||
model_name: Filename of the model (e.g., "Qwen3-4B-Q8_0.gguf")
|
||||
model_name: Filename of the model (e.g., 'Qwen3.5-9B-Q8_0.gguf')
|
||||
|
||||
Returns:
|
||||
Path to downloaded model or None on error
|
||||
@@ -224,38 +314,44 @@ def download_model(model_name):
|
||||
models_dir = get_models_directory()
|
||||
|
||||
# Build list of files to download
|
||||
# Each entry: repo_filename (name in the HF repo), local_filename (name on disk), desc
|
||||
files_to_download = [
|
||||
{"filename": model_name, "desc": "Downloading model"}
|
||||
{"repo_filename": model_name, "local_filename": model_name, "desc": "Downloading model"}
|
||||
]
|
||||
|
||||
# Add mmproj file if this is a VL model
|
||||
mmproj_name = get_mmproj_for_model(model_name)
|
||||
if mmproj_name:
|
||||
# Add mmproj file if this model has one
|
||||
mmproj_local = get_mmproj_for_model(model_name)
|
||||
if mmproj_local:
|
||||
mmproj_repo = model_info.get("mmproj_repo_filename", mmproj_local)
|
||||
files_to_download.append({
|
||||
"filename": mmproj_name,
|
||||
"repo_filename": mmproj_repo,
|
||||
"local_filename": mmproj_local,
|
||||
"desc": "Downloading mmproj"
|
||||
})
|
||||
|
||||
# Download each file if it doesn't exist
|
||||
for file_info in files_to_download:
|
||||
filename = file_info["filename"]
|
||||
local_path = os.path.join(models_dir, filename)
|
||||
repo_filename = file_info["repo_filename"]
|
||||
local_filename = file_info["local_filename"]
|
||||
local_path = os.path.join(models_dir, local_filename)
|
||||
|
||||
if os.path.exists(local_path):
|
||||
print(f"[Model Manager] File already exists: {filename}")
|
||||
print(f"[Model Manager] File already exists: {local_filename}")
|
||||
continue
|
||||
|
||||
# Download the file
|
||||
try:
|
||||
print(f"[Model Manager] Downloading {filename} from {repo_id}...")
|
||||
print(f"[Model Manager] Downloading {repo_filename} from {repo_id}...")
|
||||
api = HfApi()
|
||||
repo_info = api.repo_info(repo_id=repo_id, files_metadata=True)
|
||||
file_metadata = next((f for f in repo_info.siblings if f.rfilename == filename), None)
|
||||
repo_info_obj = api.repo_info(repo_id=repo_id, files_metadata=True)
|
||||
file_metadata = next((f for f in repo_info_obj.siblings if f.rfilename == repo_filename), None)
|
||||
if not file_metadata or file_metadata.size is None:
|
||||
print(f"[Model Manager] Could not find file size for {filename} in {repo_id}")
|
||||
print(f"[Model Manager] Could not find file size for {repo_filename} in {repo_id}")
|
||||
return None
|
||||
total_size = file_metadata.size
|
||||
download_url = f"https://huggingface.co/{repo_id}/resolve/main/{filename}"
|
||||
download_url = f"https://huggingface.co/{repo_id}/resolve/main/{repo_filename}"
|
||||
if local_filename != repo_filename:
|
||||
print(f"[Model Manager] Will save as: {local_filename}")
|
||||
pbar = tqdm(total=total_size, unit="B", unit_scale=True, desc=file_info["desc"])
|
||||
with requests.get(download_url, stream=True) as r, open(local_path, "wb") as f:
|
||||
r.raise_for_status()
|
||||
@@ -264,9 +360,9 @@ def download_model(model_name):
|
||||
f.write(chunk)
|
||||
pbar.update(len(chunk))
|
||||
pbar.close()
|
||||
print(f"[Model Manager] Successfully downloaded {filename}")
|
||||
print(f"[Model Manager] Successfully downloaded {local_filename}")
|
||||
except Exception as e:
|
||||
print(f"[Model Manager] Error downloading {filename}: {e}")
|
||||
print(f"[Model Manager] Error downloading {repo_filename}: {e}")
|
||||
return None
|
||||
|
||||
return os.path.join(models_dir, model_name)
|
||||
@@ -0,0 +1,198 @@
|
||||
"""
|
||||
Ollama integration for ComfyUI Prompt Manager.
|
||||
|
||||
Provides model discovery, generation, and memory management
|
||||
via Ollama's native API and OpenAI-compatible endpoint.
|
||||
"""
|
||||
import requests
|
||||
import json
|
||||
|
||||
# ============================================================================
|
||||
# Default endpoints
|
||||
# ============================================================================
|
||||
|
||||
DEFAULT_OLLAMA_URL = "http://127.0.0.1:11434"
|
||||
|
||||
|
||||
def _get_ollama_base(user_config):
|
||||
"""Resolve Ollama base URL (without /v1 or /api) from config."""
|
||||
url = str(user_config.get("ollama_url", DEFAULT_OLLAMA_URL)).strip().rstrip("/")
|
||||
if not url:
|
||||
url = DEFAULT_OLLAMA_URL
|
||||
# Strip trailing /v1 or /api paths so we always have the root
|
||||
for suffix in ("/v1", "/api", "/api/tags", "/api/chat"):
|
||||
if url.endswith(suffix):
|
||||
url = url[: -len(suffix)]
|
||||
break
|
||||
return url
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Model discovery
|
||||
# ============================================================================
|
||||
|
||||
def discover_ollama_models(user_config):
|
||||
"""Query Ollama for available models.
|
||||
|
||||
Returns:
|
||||
(list_of_model_names, status_message)
|
||||
"""
|
||||
base = _get_ollama_base(user_config)
|
||||
tags_url = f"{base}/api/tags"
|
||||
timeout = 12
|
||||
|
||||
try:
|
||||
response = requests.get(tags_url, timeout=timeout)
|
||||
if response.status_code == 200:
|
||||
payload = response.json()
|
||||
names = []
|
||||
if isinstance(payload, dict):
|
||||
for item in payload.get("models", []):
|
||||
if isinstance(item, dict):
|
||||
name = item.get("model") or item.get("name")
|
||||
if isinstance(name, str) and name.strip():
|
||||
names.append(name.strip())
|
||||
if names:
|
||||
unique = sorted(set(names), key=lambda x: x.lower())
|
||||
return unique, f"Found {len(unique)} Ollama model(s)."
|
||||
return [], "Ollama responded but no models were found. Pull one first, e.g. `ollama pull llama3.1`."
|
||||
return [], f"Ollama returned HTTP {response.status_code}."
|
||||
except requests.exceptions.ConnectionError:
|
||||
return [], f"Could not connect to Ollama at {base}. Start `ollama serve` and retry."
|
||||
except requests.exceptions.Timeout:
|
||||
return [], f"Timed out querying Ollama at {base}."
|
||||
except Exception as e:
|
||||
return [], f"Failed to query Ollama models: {e}"
|
||||
|
||||
|
||||
def is_ollama_available(user_config):
|
||||
"""Check if Ollama is reachable."""
|
||||
base = _get_ollama_base(user_config)
|
||||
try:
|
||||
resp = requests.get(f"{base}/api/tags", timeout=5)
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Generation (OpenAI-compatible chat/completions via Ollama)
|
||||
# ============================================================================
|
||||
|
||||
def generate_chat(user_config, model_name, messages, temperature=0.8,
|
||||
top_k=40, top_p=0.95, min_p=0.05, repeat_penalty=1.0,
|
||||
seed=None, stream=True, timeout=120,
|
||||
use_model_defaults=True, enable_thinking=False):
|
||||
"""Send a chat completion request to Ollama's OpenAI-compatible endpoint.
|
||||
|
||||
Args:
|
||||
user_config: preferences dict with ollama_url, ollama_keep_alive, etc.
|
||||
model_name: Ollama model tag (e.g. "llama3.1:latest")
|
||||
messages: list of {role, content} dicts (OpenAI format)
|
||||
stream: if True, returns a streaming response iterator
|
||||
timeout: request timeout in seconds
|
||||
|
||||
Returns:
|
||||
If stream=False: (response_text, thinking_text, usage_stats, error_msg)
|
||||
If stream=True: (response_object, error_msg) — caller handles streaming
|
||||
"""
|
||||
base = _get_ollama_base(user_config)
|
||||
url = f"{base}/v1/chat/completions"
|
||||
|
||||
payload = {
|
||||
"model": model_name,
|
||||
"messages": messages,
|
||||
"stream": stream,
|
||||
}
|
||||
|
||||
# Set keep_alive to control how long the model stays loaded after this request
|
||||
keep_alive = user_config.get("ollama_keep_alive", "5m")
|
||||
if keep_alive:
|
||||
payload["keep_alive"] = keep_alive
|
||||
|
||||
if stream:
|
||||
payload["stream_options"] = {"include_usage": True}
|
||||
|
||||
if seed is not None:
|
||||
payload["seed"] = seed
|
||||
|
||||
if enable_thinking:
|
||||
payload["chat_template_kwargs"] = {"enable_thinking": True}
|
||||
|
||||
if not use_model_defaults:
|
||||
payload["temperature"] = temperature
|
||||
payload["top_k"] = top_k
|
||||
payload["top_p"] = top_p
|
||||
payload["min_p"] = min_p
|
||||
payload["repeat_penalty"] = repeat_penalty
|
||||
|
||||
try:
|
||||
response = requests.post(url, json=payload, timeout=timeout, stream=stream)
|
||||
if response.status_code != 200:
|
||||
detail = _extract_error(response)
|
||||
return (None, f"Ollama request failed ({response.status_code}): {detail}")
|
||||
if stream:
|
||||
return (response, None)
|
||||
else:
|
||||
result = response.json()
|
||||
text = result["choices"][0]["message"]["content"]
|
||||
usage = result.get("usage")
|
||||
return (text.strip(), "", usage, None)
|
||||
except requests.exceptions.ConnectionError:
|
||||
return (None, "Could not connect to Ollama. Start 'ollama serve' and retry.")
|
||||
except requests.exceptions.Timeout:
|
||||
return (None, f"Ollama request timed out ({timeout}s). Try a shorter prompt or smaller model.")
|
||||
except (KeyError, IndexError):
|
||||
return (None, "Unexpected response format from Ollama.")
|
||||
except Exception as e:
|
||||
return (None, f"Ollama generation failed: {e}")
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Memory management — unload model from Ollama VRAM
|
||||
# ============================================================================
|
||||
|
||||
def unload_model(user_config, model_name):
|
||||
"""Tell Ollama to unload a model from memory (free VRAM).
|
||||
|
||||
Uses the /api/generate endpoint with keep_alive=0 to immediately
|
||||
evict the model from GPU memory.
|
||||
"""
|
||||
base = _get_ollama_base(user_config)
|
||||
url = f"{base}/api/generate"
|
||||
|
||||
try:
|
||||
response = requests.post(url, json={
|
||||
"model": model_name,
|
||||
"keep_alive": 0,
|
||||
}, timeout=15)
|
||||
if response.status_code == 200:
|
||||
return True, f"Model '{model_name}' unloaded from Ollama memory."
|
||||
return False, f"Ollama returned HTTP {response.status_code} while unloading model."
|
||||
except requests.exceptions.ConnectionError:
|
||||
return False, "Could not connect to Ollama to unload model."
|
||||
except Exception as e:
|
||||
return False, f"Failed to unload model from Ollama: {e}"
|
||||
|
||||
|
||||
# ============================================================================
|
||||
# Helpers
|
||||
# ============================================================================
|
||||
|
||||
def _extract_error(response):
|
||||
"""Extract error message from an Ollama error response."""
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
text = (response.text or "").strip()
|
||||
return text[:300] if text else f"HTTP {response.status_code}"
|
||||
|
||||
if isinstance(payload, dict):
|
||||
err = payload.get("error")
|
||||
if isinstance(err, str) and err.strip():
|
||||
return err.strip()
|
||||
msg = payload.get("message")
|
||||
if isinstance(msg, str) and msg.strip():
|
||||
return msg.strip()
|
||||
|
||||
return f"HTTP {response.status_code}"
|
||||
@@ -0,0 +1,96 @@
|
||||
"""
|
||||
Utility functions for WORKFLOW_DATA dicts.
|
||||
Runtime object keys (MODEL_A, MODEL_B, CLIP, VAE, POSITIVE, NEGATIVE, etc.)
|
||||
store non-serializable ComfyUI objects and must be stripped before JSON
|
||||
serialization.
|
||||
"""
|
||||
|
||||
import json
|
||||
import math
|
||||
|
||||
# Keys that hold runtime (non-JSON-serializable) objects/conditioning payloads.
|
||||
# These should never be persisted in saved prompt/workflow metadata.
|
||||
RUNTIME_OBJECT_KEYS = frozenset({
|
||||
"MODEL_A",
|
||||
"MODEL_B",
|
||||
"CLIP",
|
||||
"VAE",
|
||||
"LATENT",
|
||||
"IMAGE",
|
||||
"MASK",
|
||||
"EXTRA",
|
||||
"POSITIVE",
|
||||
"NEGATIVE",
|
||||
})
|
||||
|
||||
|
||||
def _strip_runtime_keys_deep(value):
|
||||
"""Recursively strip runtime-only keys from dict/list containers."""
|
||||
if isinstance(value, dict):
|
||||
return {
|
||||
k: _strip_runtime_keys_deep(v)
|
||||
for k, v in value.items()
|
||||
if k not in RUNTIME_OBJECT_KEYS
|
||||
}
|
||||
if isinstance(value, list):
|
||||
return [_strip_runtime_keys_deep(v) for v in value]
|
||||
if isinstance(value, tuple):
|
||||
return [_strip_runtime_keys_deep(v) for v in value]
|
||||
if isinstance(value, set):
|
||||
return [_strip_runtime_keys_deep(v) for v in value]
|
||||
return value
|
||||
|
||||
|
||||
def strip_runtime_objects(wf):
|
||||
"""Return a deep copy of wf with all runtime object keys removed.
|
||||
|
||||
Use before JSON serialization (saving prompts, send_sync to JS, etc.).
|
||||
"""
|
||||
if not isinstance(wf, dict):
|
||||
return wf
|
||||
return _strip_runtime_keys_deep(wf)
|
||||
|
||||
|
||||
def _json_default(value):
|
||||
"""Best-effort fallback for objects that JSON cannot encode directly."""
|
||||
if isinstance(value, (set, tuple)):
|
||||
return list(value)
|
||||
if isinstance(value, bytes):
|
||||
return value.decode("utf-8", errors="replace")
|
||||
return str(value)
|
||||
|
||||
|
||||
def to_json_safe_workflow_data(wf):
|
||||
"""Return a deep JSON-safe copy of workflow data with runtime keys removed.
|
||||
|
||||
This is stricter than strip_runtime_objects(): it also sanitizes nested
|
||||
containers and unknown object types so metadata embedding cannot fail
|
||||
during Save Image serialization.
|
||||
"""
|
||||
if not isinstance(wf, dict):
|
||||
return {}
|
||||
|
||||
stripped = strip_runtime_objects(wf)
|
||||
|
||||
# Normalize NaN/Inf because Python's json allows them by default but strict
|
||||
# JSON consumers may reject them.
|
||||
def _normalize_numbers(value):
|
||||
if isinstance(value, float) and (math.isnan(value) or math.isinf(value)):
|
||||
return None
|
||||
if isinstance(value, dict):
|
||||
return {k: _normalize_numbers(v) for k, v in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_normalize_numbers(v) for v in value]
|
||||
if isinstance(value, tuple):
|
||||
return [_normalize_numbers(v) for v in value]
|
||||
if isinstance(value, set):
|
||||
return [_normalize_numbers(v) for v in value]
|
||||
return value
|
||||
|
||||
normalized = _normalize_numbers(stripped)
|
||||
|
||||
try:
|
||||
return json.loads(json.dumps(normalized, default=_json_default, allow_nan=False))
|
||||
except Exception:
|
||||
# Last-resort safety: stringify opaque values while preserving structure.
|
||||
return json.loads(json.dumps(str(normalized)))
|
||||
@@ -0,0 +1,973 @@
|
||||
"""
|
||||
Shared extraction helpers for ComfyUI Prompt Manager.
|
||||
|
||||
Used by both WorkflowExtractor and WorkflowBuilder / WorkflowRenderer nodes.
|
||||
Handles: sampler params, VAE info, CLIP info, resolution, model resolution,
|
||||
and the full extract_all_from_file() entry point.
|
||||
"""
|
||||
import os
|
||||
import json
|
||||
import folder_paths
|
||||
|
||||
from .workflow_families import get_model_family, get_family_label
|
||||
|
||||
# ─── Constants ────────────────────────────────────────────────────────────────
|
||||
|
||||
MODEL_EXTENSIONS = ['.safetensors', '.ckpt', '.pt', '.pth', '.bin', '.gguf', '.sft']
|
||||
|
||||
# Node types that contain sampler parameters
|
||||
KSAMPLER_TYPES = [
|
||||
'KSampler', 'KSamplerAdvanced', 'KSamplerSelect',
|
||||
'SamplerCustomAdvanced', 'SamplerCustom',
|
||||
'WanMoeKSamplerAdvanced',
|
||||
]
|
||||
|
||||
SCHEDULER_TYPES = ['BasicScheduler', 'Flux2Scheduler', 'SDTurboScheduler', 'KarrasScheduler']
|
||||
GUIDER_TYPES = ['BasicGuider', 'CFGGuider', 'DualCFGGuider']
|
||||
NOISE_TYPES = ['RandomNoise', 'DisableNoise']
|
||||
VAE_LOADER_TYPES = ['VAELoader', 'VAELoaderConsistencyDecoder']
|
||||
CLIP_LOADER_TYPES = ['CLIPLoader', 'DualCLIPLoader', 'TripleCLIPLoader']
|
||||
LATENT_TYPES = ['EmptyLatentImage', 'EmptyFlux2LatentImage', 'EmptySD3LatentImage']
|
||||
VIDEO_LATENT_TYPES = ['WanVideoLatentImage', 'WanImageToVideo', 'EmptyHunyuanLatentVideo']
|
||||
|
||||
CHECKPOINT_TYPES = ('CheckpointLoaderSimple', 'CheckpointLoader', 'CheckpointLoaderNF4')
|
||||
|
||||
# Node types that carry embedded extracted_data.
|
||||
# Keep 'WorkflowGenerator' for backward compat with images generated before rename.
|
||||
# WorkflowBuilder stores authoritative extracted_data for Builder+Renderer graphs.
|
||||
_EMBEDDED_NODE_TYPES = (
|
||||
'WorkflowRenderer',
|
||||
'WorkflowGenerator',
|
||||
'WorkflowBuilder',
|
||||
'PromptExtractor',
|
||||
)
|
||||
|
||||
|
||||
def _get_embedded_extracted_data(workflow_data):
|
||||
"""Return the best ``extracted_data`` dict from a WR/WG or PE node, or *None*.
|
||||
|
||||
Prioritises WorkflowRenderer/WorkflowGenerator over WorkflowBuilder over
|
||||
PromptExtractor, and only returns data that actually contains ``sampler``
|
||||
or ``resolution`` keys.
|
||||
"""
|
||||
if not workflow_data or not isinstance(workflow_data, dict):
|
||||
return None
|
||||
|
||||
best = None
|
||||
best_rank = -1
|
||||
|
||||
for wf_node in workflow_data.get('nodes', []):
|
||||
ntype = wf_node.get('type', '')
|
||||
if ntype not in _EMBEDDED_NODE_TYPES:
|
||||
continue
|
||||
ed = wf_node.get('extracted_data')
|
||||
if not ed or not isinstance(ed, dict):
|
||||
continue
|
||||
has_useful = bool(ed.get('sampler') or ed.get('resolution'))
|
||||
if not has_useful:
|
||||
continue
|
||||
if ntype in ('WorkflowRenderer', 'WorkflowGenerator'):
|
||||
rank = 3
|
||||
elif ntype == 'WorkflowBuilder':
|
||||
rank = 2
|
||||
else:
|
||||
rank = 1
|
||||
|
||||
# Prefer higher-priority source; among same type, first wins.
|
||||
if best is None or rank > best_rank:
|
||||
best = ed
|
||||
best_rank = rank
|
||||
if best_rank == 3:
|
||||
break # WR/WG is highest priority — stop early
|
||||
|
||||
return best
|
||||
|
||||
|
||||
# ─── Sampler extraction ───────────────────────────────────────────────────────
|
||||
|
||||
def extract_sampler_params(prompt_data, workflow_data):
|
||||
"""
|
||||
Extract sampler parameters from KSampler nodes in API or workflow format.
|
||||
Returns a dict with steps_a, steps_b, cfg, seed_a, seed_b, sampler_name, scheduler.
|
||||
"""
|
||||
params = {
|
||||
'steps_a': 20,
|
||||
'steps_b': None, # WAN Video low-pass steps (None = same as steps_a)
|
||||
'cfg': 7.0,
|
||||
'seed_a': 0,
|
||||
'seed_b': None, # WAN Video second-sampler seed (None = use same as seed_a)
|
||||
'sampler_name': 'euler',
|
||||
'scheduler': 'normal',
|
||||
}
|
||||
|
||||
# ── API format ────────────────────────────────────────────────────────────
|
||||
if prompt_data and isinstance(prompt_data, dict):
|
||||
# WAN Video uses two KSamplerAdvanced nodes (high + low pass).
|
||||
# Collect all of them so we can expose both seeds.
|
||||
ksampler_advanced_nodes = []
|
||||
for node_id, node_data in prompt_data.items():
|
||||
if not isinstance(node_data, dict):
|
||||
continue
|
||||
ct = node_data.get('class_type', '')
|
||||
inp = node_data.get('inputs', {})
|
||||
|
||||
if ct == 'KSampler':
|
||||
params['steps_a'] = inp.get('steps', params['steps_a'])
|
||||
params['cfg'] = inp.get('cfg', params['cfg'])
|
||||
seed_val = inp.get('seed', inp.get('noise_seed', params['seed_a']))
|
||||
params['seed_a'] = seed_val if not isinstance(seed_val, list) else params['seed_a']
|
||||
params['sampler_name'] = inp.get('sampler_name', params['sampler_name'])
|
||||
params['scheduler'] = inp.get('scheduler', params['scheduler'])
|
||||
return params # standard KSampler found — done
|
||||
|
||||
if ct == 'KSamplerAdvanced':
|
||||
ksampler_advanced_nodes.append(inp)
|
||||
|
||||
if ct == 'WanMoeKSamplerAdvanced':
|
||||
params['steps_a'] = inp.get('steps', params['steps_a'])
|
||||
params['cfg'] = inp.get('cfg', params['cfg'])
|
||||
seed_val = inp.get('seed', inp.get('noise_seed', params['seed_a']))
|
||||
params['seed_a'] = seed_val if not isinstance(seed_val, list) else params['seed_a']
|
||||
params['sampler_name'] = inp.get('sampler_name', params['sampler_name'])
|
||||
params['scheduler'] = inp.get('scheduler', params['scheduler'])
|
||||
return params
|
||||
|
||||
# Handle KSamplerAdvanced — including WAN Video dual-sampler pattern
|
||||
if ksampler_advanced_nodes:
|
||||
first = ksampler_advanced_nodes[0]
|
||||
params['steps_a'] = first.get('steps', params['steps_a'])
|
||||
params['cfg'] = first.get('cfg', params['cfg'])
|
||||
seed_val = first.get('seed', first.get('noise_seed', params['seed_a']))
|
||||
params['seed_a'] = seed_val if not isinstance(seed_val, list) else params['seed_a']
|
||||
params['sampler_name'] = first.get('sampler_name', params['sampler_name'])
|
||||
params['scheduler'] = first.get('scheduler', params['scheduler'])
|
||||
if len(ksampler_advanced_nodes) >= 2:
|
||||
# Second node = low-pass sampler — expose its seed as seed_b
|
||||
second = ksampler_advanced_nodes[1]
|
||||
seed_b = second.get('seed', second.get('noise_seed', params['seed_a']))
|
||||
params['seed_b'] = seed_b if not isinstance(seed_b, list) else params['seed_a']
|
||||
# Extract steps_b if the second sampler has different steps
|
||||
steps_b_val = second.get('steps')
|
||||
if steps_b_val is not None and not isinstance(steps_b_val, list):
|
||||
params['steps_b'] = int(steps_b_val)
|
||||
return params
|
||||
|
||||
# Second pass for split-node pattern (SamplerCustomAdvanced)
|
||||
for node_id, node_data in prompt_data.items():
|
||||
if not isinstance(node_data, dict):
|
||||
continue
|
||||
ct = node_data.get('class_type', '')
|
||||
inp = node_data.get('inputs', {})
|
||||
|
||||
if ct == 'KSamplerSelect':
|
||||
params['sampler_name'] = inp.get('sampler_name', params['sampler_name'])
|
||||
elif ct in ('BasicScheduler', 'Flux2Scheduler'):
|
||||
params['steps_a'] = inp.get('steps', params['steps_a'])
|
||||
params['scheduler'] = inp.get('scheduler', params['scheduler'])
|
||||
elif ct == 'CFGGuider':
|
||||
params['cfg'] = inp.get('cfg', params['cfg'])
|
||||
elif ct == 'RandomNoise':
|
||||
params['seed_a'] = inp.get('noise_seed', params['seed_a'])
|
||||
|
||||
# ── Workflow (node graph) format fallback ─────────────────────────────────
|
||||
if workflow_data and isinstance(workflow_data, dict):
|
||||
from .workflow_node_utils import build_node_map
|
||||
node_map = build_node_map(workflow_data)
|
||||
for node_id, node in node_map.items():
|
||||
ntype = node.get('type', '')
|
||||
widgets = node.get('widgets_values', [])
|
||||
|
||||
if ntype == 'KSampler' and len(widgets) >= 6:
|
||||
try:
|
||||
params['seed_a'] = int(widgets[0]) if widgets[0] is not None else 0
|
||||
params['steps_a'] = int(widgets[2]) if widgets[2] is not None else 20
|
||||
params['cfg'] = float(widgets[3]) if widgets[3] is not None else 7.0
|
||||
params['sampler_name'] = str(widgets[4]) if widgets[4] else 'euler'
|
||||
params['scheduler'] = str(widgets[5]) if widgets[5] else 'normal'
|
||||
return params
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
|
||||
elif ntype == 'KSamplerSelect' and widgets:
|
||||
params['sampler_name'] = str(widgets[0]) if widgets[0] else params['sampler_name']
|
||||
elif ntype in ('BasicScheduler', 'Flux2Scheduler') and len(widgets) >= 2:
|
||||
try:
|
||||
params['scheduler'] = str(widgets[0]) if widgets[0] else params['scheduler']
|
||||
params['steps_a'] = int(widgets[1]) if widgets[1] is not None else params['steps_a']
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
elif ntype == 'CFGGuider' and widgets:
|
||||
try:
|
||||
params['cfg'] = float(widgets[0]) if widgets[0] is not None else params['cfg']
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
elif ntype == 'RandomNoise' and widgets:
|
||||
try:
|
||||
params['seed_a'] = int(widgets[0]) if widgets[0] is not None else 0
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
|
||||
# ── Fallback: embedded extracted_data from WG / PE nodes ──────────────
|
||||
ed = _get_embedded_extracted_data(workflow_data)
|
||||
if ed:
|
||||
s = ed.get('sampler')
|
||||
if s and isinstance(s, dict) and s.get('sampler_name'):
|
||||
params['steps_a'] = s.get('steps_a', s.get('steps', params['steps_a']))
|
||||
params['steps_b'] = s.get('steps_b', params['steps_b'])
|
||||
params['cfg'] = s.get('cfg', params['cfg'])
|
||||
params['seed_a'] = s.get('seed_a', s.get('seed', params['seed_a']))
|
||||
params['sampler_name'] = s.get('sampler_name', params['sampler_name'])
|
||||
params['scheduler'] = s.get('scheduler', params['scheduler'])
|
||||
|
||||
return params
|
||||
|
||||
|
||||
# ─── VAE extraction ───────────────────────────────────────────────────────────
|
||||
|
||||
def extract_vae_info(prompt_data, workflow_data):
|
||||
"""Extract VAE loader information from the workflow. Returns {'name', 'source'}."""
|
||||
vae_info = {'name': '', 'source': 'unknown'}
|
||||
|
||||
if prompt_data and isinstance(prompt_data, dict):
|
||||
for node_id, node_data in prompt_data.items():
|
||||
if not isinstance(node_data, dict):
|
||||
continue
|
||||
ct = node_data.get('class_type', '')
|
||||
inp = node_data.get('inputs', {})
|
||||
|
||||
if ct in VAE_LOADER_TYPES:
|
||||
vae_info['name'] = inp.get('vae_name', '')
|
||||
vae_info['source'] = 'separate'
|
||||
return vae_info
|
||||
|
||||
if ct in CHECKPOINT_TYPES and inp.get('ckpt_name'):
|
||||
if not vae_info['name']:
|
||||
vae_info['name'] = '(from checkpoint)'
|
||||
vae_info['source'] = 'checkpoint'
|
||||
# Don't return — a separate VAE loader later overrides this
|
||||
|
||||
if not vae_info['name'] and workflow_data and isinstance(workflow_data, dict):
|
||||
from .workflow_node_utils import build_node_map
|
||||
node_map = build_node_map(workflow_data)
|
||||
for node_id, node in node_map.items():
|
||||
ntype = node.get('type', '')
|
||||
widgets = node.get('widgets_values', [])
|
||||
|
||||
if ntype in VAE_LOADER_TYPES and widgets:
|
||||
vae_info['name'] = str(widgets[0]) if widgets[0] else ''
|
||||
vae_info['source'] = 'separate'
|
||||
return vae_info
|
||||
|
||||
if ntype in CHECKPOINT_TYPES and widgets and not vae_info['name']:
|
||||
vae_info['name'] = '(from checkpoint)'
|
||||
vae_info['source'] = 'checkpoint'
|
||||
|
||||
# ── Fallback: embedded extracted_data from WG / PE nodes ──────────────
|
||||
if not vae_info['name']:
|
||||
ed = _get_embedded_extracted_data(workflow_data)
|
||||
if ed:
|
||||
vae = ed.get('vae', '')
|
||||
if vae and isinstance(vae, str) and vae not in ('', '\u2014'):
|
||||
vae_info['name'] = vae
|
||||
vae_info['source'] = 'embedded'
|
||||
|
||||
return vae_info
|
||||
|
||||
|
||||
# ─── CLIP extraction ──────────────────────────────────────────────────────────
|
||||
|
||||
def extract_clip_info(prompt_data, workflow_data):
|
||||
"""Extract CLIP loader information. Returns {'names', 'type', 'source'}."""
|
||||
clip_info = {'names': [], 'type': '', 'source': 'unknown'}
|
||||
|
||||
if prompt_data and isinstance(prompt_data, dict):
|
||||
for node_id, node_data in prompt_data.items():
|
||||
if not isinstance(node_data, dict):
|
||||
continue
|
||||
ct = node_data.get('class_type', '')
|
||||
inp = node_data.get('inputs', {})
|
||||
|
||||
if ct == 'CLIPLoader':
|
||||
clip_info['names'] = [inp.get('clip_name', '')]
|
||||
clip_info['type'] = inp.get('type', '')
|
||||
clip_info['source'] = 'separate'
|
||||
return clip_info
|
||||
|
||||
if ct == 'DualCLIPLoader':
|
||||
clip_info['names'] = [inp.get('clip_name1', ''), inp.get('clip_name2', '')]
|
||||
clip_info['type'] = inp.get('type', '')
|
||||
clip_info['source'] = 'separate'
|
||||
return clip_info
|
||||
|
||||
if ct == 'TripleCLIPLoader':
|
||||
clip_info['names'] = [
|
||||
inp.get('clip_name1', ''),
|
||||
inp.get('clip_name2', ''),
|
||||
inp.get('clip_name3', ''),
|
||||
]
|
||||
clip_info['source'] = 'separate'
|
||||
return clip_info
|
||||
|
||||
if ct in CHECKPOINT_TYPES and inp.get('ckpt_name') and not clip_info['names']:
|
||||
clip_info['names'] = ['(from checkpoint)']
|
||||
clip_info['source'] = 'checkpoint'
|
||||
|
||||
if not clip_info['names'] and workflow_data and isinstance(workflow_data, dict):
|
||||
from .workflow_node_utils import build_node_map
|
||||
node_map = build_node_map(workflow_data)
|
||||
for node_id, node in node_map.items():
|
||||
ntype = node.get('type', '')
|
||||
widgets = node.get('widgets_values', [])
|
||||
|
||||
if ntype == 'CLIPLoader' and widgets:
|
||||
clip_info['names'] = [str(widgets[0]) if widgets[0] else '']
|
||||
clip_info['type'] = str(widgets[1]) if len(widgets) > 1 and widgets[1] else ''
|
||||
clip_info['source'] = 'separate'
|
||||
return clip_info
|
||||
|
||||
if ntype == 'DualCLIPLoader' and len(widgets) >= 2:
|
||||
clip_info['names'] = [
|
||||
str(widgets[0]) if widgets[0] else '',
|
||||
str(widgets[1]) if widgets[1] else '',
|
||||
]
|
||||
clip_info['type'] = str(widgets[2]) if len(widgets) > 2 and widgets[2] else ''
|
||||
clip_info['source'] = 'separate'
|
||||
return clip_info
|
||||
|
||||
if ntype in CHECKPOINT_TYPES and widgets and not clip_info['names']:
|
||||
clip_info['names'] = ['(from checkpoint)']
|
||||
clip_info['source'] = 'checkpoint'
|
||||
|
||||
# ── Fallback: embedded extracted_data from WG / PE nodes ──────────────
|
||||
if not clip_info['names']:
|
||||
ed = _get_embedded_extracted_data(workflow_data)
|
||||
if ed:
|
||||
clip = ed.get('clip', [])
|
||||
names = clip if isinstance(clip, list) else ([clip] if clip else [])
|
||||
if any(n for n in names):
|
||||
clip_info['names'] = names
|
||||
clip_info['source'] = 'embedded'
|
||||
|
||||
return clip_info
|
||||
|
||||
|
||||
# ─── Resolution extraction ────────────────────────────────────────────────────
|
||||
|
||||
def extract_resolution(prompt_data, workflow_data, return_source=False):
|
||||
"""Extract image/video resolution from latent nodes.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
return_source : bool
|
||||
If True, returns ``(resolution_dict, source)`` where source is one of:
|
||||
``prompt_graph``, ``workflow_graph``, ``embedded``, ``default``.
|
||||
"""
|
||||
def _ret(res, source):
|
||||
return (res, source) if return_source else res
|
||||
|
||||
resolution = {'width': 512, 'height': 512, 'batch_size': 1, 'length': None}
|
||||
|
||||
if prompt_data and isinstance(prompt_data, dict):
|
||||
for node_id, node_data in prompt_data.items():
|
||||
if not isinstance(node_data, dict):
|
||||
continue
|
||||
ct = node_data.get('class_type', '')
|
||||
inp = node_data.get('inputs', {})
|
||||
|
||||
if ct in LATENT_TYPES + VIDEO_LATENT_TYPES:
|
||||
def _scalar(val, fallback, field_name=None):
|
||||
"""Resolve node-ref lists to scalar by looking up the
|
||||
referenced node in prompt_data, or return fallback."""
|
||||
if isinstance(val, list):
|
||||
# Node reference: [node_id, output_index]
|
||||
ref_id = str(val[0])
|
||||
ref_node = prompt_data.get(ref_id, {})
|
||||
ref_inp = ref_node.get('inputs', {})
|
||||
# PrimitiveInt / ImageResizeKJv2 / similar
|
||||
if 'value' in ref_inp:
|
||||
return int(ref_inp['value'])
|
||||
# ImageResizeKJv2: width is output slot 1, height slot 2
|
||||
if field_name == 'width' and 'width' in ref_inp:
|
||||
v = ref_inp['width']
|
||||
return int(v) if not isinstance(v, list) else fallback
|
||||
if field_name == 'height' and 'height' in ref_inp:
|
||||
v = ref_inp['height']
|
||||
return int(v) if not isinstance(v, list) else fallback
|
||||
return fallback
|
||||
try:
|
||||
return int(val)
|
||||
except (TypeError, ValueError):
|
||||
return fallback
|
||||
|
||||
w = inp.get('width', resolution['width'])
|
||||
h = inp.get('height', resolution['height'])
|
||||
b = inp.get('batch_size', resolution['batch_size'])
|
||||
resolution['width'] = _scalar(w, resolution['width'], 'width')
|
||||
resolution['height'] = _scalar(h, resolution['height'], 'height')
|
||||
if ct in VIDEO_LATENT_TYPES:
|
||||
# For video latent nodes (WanImageToVideo, etc.), batch_size
|
||||
# is the frame count — store it as length, keep batch_size=1.
|
||||
b_val = _scalar(b, resolution['batch_size'])
|
||||
resolution['batch_size'] = 1
|
||||
if 'length' in inp:
|
||||
l = inp.get('length')
|
||||
resolution['length'] = _scalar(l, None) if l is not None else None
|
||||
elif b_val > 1:
|
||||
# batch_size field holds frame count
|
||||
resolution['length'] = b_val
|
||||
else:
|
||||
b_val = _scalar(b, resolution['batch_size'])
|
||||
resolution['batch_size'] = b_val
|
||||
if 'length' in inp:
|
||||
l = inp.get('length')
|
||||
resolution['length'] = _scalar(l, None) if l is not None else None
|
||||
return _ret(resolution, 'prompt_graph')
|
||||
|
||||
if workflow_data and isinstance(workflow_data, dict):
|
||||
from .workflow_node_utils import build_node_map
|
||||
node_map = build_node_map(workflow_data)
|
||||
for node_id, node in node_map.items():
|
||||
ntype = node.get('type', '')
|
||||
widgets = node.get('widgets_values', [])
|
||||
|
||||
if ntype in LATENT_TYPES and len(widgets) >= 3:
|
||||
try:
|
||||
resolution['width'] = int(widgets[0]) if widgets[0] else 512
|
||||
resolution['height'] = int(widgets[1]) if widgets[1] else 512
|
||||
resolution['batch_size'] = int(widgets[2]) if widgets[2] else 1
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
return _ret(resolution, 'workflow_graph')
|
||||
|
||||
if ntype in VIDEO_LATENT_TYPES and len(widgets) >= 3:
|
||||
try:
|
||||
resolution['width'] = int(widgets[0]) if widgets[0] else 512
|
||||
resolution['height'] = int(widgets[1]) if widgets[1] else 512
|
||||
if len(widgets) > 2:
|
||||
resolution['length'] = int(widgets[2]) if widgets[2] else 81
|
||||
resolution['batch_size'] = int(widgets[3]) if len(widgets) > 3 and widgets[3] else 1
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
return _ret(resolution, 'workflow_graph')
|
||||
|
||||
# ── Fallback: embedded extracted_data from WG / PE nodes ──────────────
|
||||
ed = _get_embedded_extracted_data(workflow_data)
|
||||
if ed:
|
||||
r = ed.get('resolution')
|
||||
if r and isinstance(r, dict) and r.get('width'):
|
||||
resolution['width'] = r.get('width', resolution['width'])
|
||||
resolution['height'] = r.get('height', resolution['height'])
|
||||
resolution['batch_size'] = r.get('batch_size', resolution['batch_size'])
|
||||
if r.get('length') is not None:
|
||||
resolution['length'] = r['length']
|
||||
return _ret(resolution, 'embedded')
|
||||
|
||||
return _ret(resolution, 'default')
|
||||
|
||||
|
||||
# ─── Model resolution ─────────────────────────────────────────────────────────
|
||||
|
||||
def resolve_model_name(model_name):
|
||||
"""Resolve model name to (relative_path, folder_name) or (None, None)."""
|
||||
if not model_name:
|
||||
return None, None
|
||||
|
||||
model_name_clean = model_name.strip().replace('\\', '/')
|
||||
name_base = os.path.basename(model_name_clean).lower()
|
||||
name_no_ext = name_base
|
||||
for ext in MODEL_EXTENSIONS:
|
||||
if name_no_ext.endswith(ext):
|
||||
name_no_ext = name_no_ext[:-len(ext)]
|
||||
break
|
||||
|
||||
for folder_name in ['checkpoints', 'diffusion_models', 'unet', 'unet_gguf']:
|
||||
try:
|
||||
file_list = folder_paths.get_filename_list(folder_name)
|
||||
except Exception:
|
||||
continue
|
||||
for f in file_list:
|
||||
f_normalized = f.replace('\\', '/')
|
||||
if f_normalized == model_name_clean:
|
||||
return f, folder_name
|
||||
f_base = os.path.basename(f_normalized).lower()
|
||||
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_base == name_base or f_no_ext == name_no_ext:
|
||||
return f, folder_name
|
||||
|
||||
return None, None
|
||||
|
||||
|
||||
def resolve_vae_name(vae_name):
|
||||
"""Resolve VAE name to full path, or None if not found / from checkpoint."""
|
||||
if not vae_name or vae_name.startswith('('):
|
||||
return None
|
||||
try:
|
||||
vae_list = folder_paths.get_filename_list("vae")
|
||||
name_lower = os.path.basename(vae_name).lower()
|
||||
for v in vae_list:
|
||||
if v == vae_name or os.path.basename(v).lower() == name_lower:
|
||||
return folder_paths.get_full_path("vae", v)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def resolve_clip_names(clip_names, clip_type=''):
|
||||
"""
|
||||
Resolve a list of CLIP names to full paths.
|
||||
Returns list of paths (None for any not found).
|
||||
"""
|
||||
paths = []
|
||||
for name in clip_names:
|
||||
if not name or name.startswith('('):
|
||||
paths.append(None)
|
||||
continue
|
||||
found = None
|
||||
name_lower = os.path.basename(name).lower()
|
||||
for folder in ['text_encoders', 'clip']:
|
||||
try:
|
||||
for f in folder_paths.get_filename_list(folder):
|
||||
if f == name or os.path.basename(f).lower() == name_lower:
|
||||
found = folder_paths.get_full_path(folder, f)
|
||||
break
|
||||
if found:
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
paths.append(found)
|
||||
return paths
|
||||
|
||||
|
||||
# ─── Embedded generation data (WG / PE) ──────────────────────────────────────
|
||||
|
||||
def _find_embedded_generation_data(workflow_data, prompt_data):
|
||||
"""
|
||||
Look for sampler / resolution / model data embedded by WorkflowRenderer
|
||||
(or legacy WorkflowGenerator) or PromptExtractor. Checks (in priority order):
|
||||
|
||||
1. WR/WG/WB node ``extracted_data`` (full dict with sampler + resolution)
|
||||
2. WR/WG/WB node ``widgets_values`` containing the ``override_data`` JSON
|
||||
3. WR/WG/WB ``override_data`` in the prompt API inputs
|
||||
4. PE node ``extracted_data``
|
||||
|
||||
Returns a dict with ``sampler``, ``resolution``, ``vae``, ``clip``,
|
||||
``model_a``, ``model_b`` keys — or *None* if nothing was found.
|
||||
"""
|
||||
out = {}
|
||||
|
||||
# --- Helper: merge extracted_data dict into *out* ---
|
||||
def _apply_extracted(ed, source_label):
|
||||
s = ed.get('sampler')
|
||||
if s and isinstance(s, dict) and s.get('sampler_name'):
|
||||
out['sampler'] = {
|
||||
'steps_a': s.get('steps_a', s.get('steps', 20)),
|
||||
'steps_b': s.get('steps_b'),
|
||||
'cfg': s.get('cfg', 7.0),
|
||||
'seed_a': s.get('seed_a', s.get('seed', 0)),
|
||||
'seed_b': s.get('seed_b'),
|
||||
'sampler_name': s.get('sampler_name', 'euler'),
|
||||
'scheduler': s.get('scheduler', 'normal'),
|
||||
}
|
||||
r = ed.get('resolution')
|
||||
if r and isinstance(r, dict) and r.get('width'):
|
||||
out['resolution'] = {
|
||||
'width': r.get('width', 512),
|
||||
'height': r.get('height', 512),
|
||||
'batch_size': r.get('batch_size', 1),
|
||||
'length': r.get('length'),
|
||||
}
|
||||
vae = ed.get('vae', '')
|
||||
if vae and isinstance(vae, str) and vae not in ('', '\u2014'):
|
||||
out['vae'] = {'name': vae, 'source': source_label}
|
||||
clip = ed.get('clip', [])
|
||||
if clip:
|
||||
names = clip if isinstance(clip, list) else [clip]
|
||||
if any(n for n in names):
|
||||
out['clip'] = {'names': names, 'type': '', 'source': source_label}
|
||||
if ed.get('model_a'):
|
||||
out.setdefault('model_a', ed['model_a'])
|
||||
if ed.get('model_b'):
|
||||
out.setdefault('model_b', ed['model_b'])
|
||||
|
||||
# --- Helper: parse override_data JSON (flat keys) ---
|
||||
def _apply_override_json(ov_str, source_label):
|
||||
try:
|
||||
ov = json.loads(ov_str) if ov_str else {}
|
||||
except (json.JSONDecodeError, TypeError):
|
||||
return
|
||||
if not isinstance(ov, dict):
|
||||
return
|
||||
if ov.get('width') or ov.get('steps_a') or ov.get('steps'):
|
||||
if 'sampler' not in out and ov.get('sampler_name'):
|
||||
out['sampler'] = {
|
||||
'steps_a': ov.get('steps_a', ov.get('steps', 20)),
|
||||
'steps_b': ov.get('steps_b'),
|
||||
'cfg': ov.get('cfg', 7.0),
|
||||
'seed_a': ov.get('seed_a', ov.get('seed', 0)),
|
||||
'seed_b': ov.get('seed_b'),
|
||||
'sampler_name': ov.get('sampler_name', 'euler'),
|
||||
'scheduler': ov.get('scheduler', 'normal'),
|
||||
}
|
||||
if 'resolution' not in out and ov.get('width'):
|
||||
out['resolution'] = {
|
||||
'width': ov.get('width', 512),
|
||||
'height': ov.get('height', 512),
|
||||
'batch_size': ov.get('batch_size', 1),
|
||||
'length': ov.get('length'),
|
||||
}
|
||||
if ov.get('model_a'):
|
||||
out.setdefault('model_a', ov['model_a'])
|
||||
|
||||
# --- 1. Workflow nodes (extracted_data + widgets_values) ---
|
||||
if workflow_data and isinstance(workflow_data, dict):
|
||||
for wf_node in workflow_data.get('nodes', []):
|
||||
ntype = wf_node.get('type', '')
|
||||
if ntype in ('WorkflowRenderer', 'WorkflowGenerator', 'WorkflowBuilder'):
|
||||
# Priority 1: extracted_data
|
||||
ed = wf_node.get('extracted_data')
|
||||
if ed and isinstance(ed, dict):
|
||||
_apply_extracted(ed, ntype)
|
||||
# Priority 2: override_data in widgets_values
|
||||
if 'sampler' not in out or 'resolution' not in out:
|
||||
for v in (wf_node.get('widgets_values') or []):
|
||||
if isinstance(v, str) and len(v) > 5 and v.strip().startswith('{'):
|
||||
_apply_override_json(v, ntype)
|
||||
if 'sampler' in out and 'resolution' in out:
|
||||
break
|
||||
if 'sampler' in out or 'resolution' in out:
|
||||
break # WR/WG/WB found — done
|
||||
|
||||
# Priority 4: PromptExtractor extracted_data (only if WG wasn't found)
|
||||
if 'sampler' not in out and 'resolution' not in out:
|
||||
for wf_node in workflow_data.get('nodes', []):
|
||||
if wf_node.get('type') == 'PromptExtractor':
|
||||
ed = wf_node.get('extracted_data')
|
||||
if ed and isinstance(ed, dict):
|
||||
_apply_extracted(ed, 'PromptExtractor')
|
||||
if 'sampler' in out or 'resolution' in out:
|
||||
break
|
||||
|
||||
# --- 3. Prompt API (WR/WG override_data in inputs) ---
|
||||
if ('sampler' not in out or 'resolution' not in out) and prompt_data and isinstance(prompt_data, dict):
|
||||
for node_id, node_data in prompt_data.items():
|
||||
if not isinstance(node_data, dict):
|
||||
continue
|
||||
if node_data.get('class_type') in ('WorkflowRenderer', 'WorkflowGenerator', 'WorkflowBuilder'):
|
||||
inp = node_data.get('inputs', {})
|
||||
_apply_override_json(inp.get('override_data', ''), node_data['class_type'])
|
||||
break
|
||||
|
||||
return out if out else None
|
||||
|
||||
|
||||
# ─── Full extraction ──────────────────────────────────────────────────────────
|
||||
|
||||
def extract_all_from_file(file_path, source_folder='input'):
|
||||
"""
|
||||
Extract ALL generation parameters from a file.
|
||||
|
||||
Returns a dict with:
|
||||
positive_prompt, negative_prompt,
|
||||
loras_a, loras_b,
|
||||
model_a, model_b,
|
||||
vae {'name', 'source'},
|
||||
clip {'names', 'type', 'source'},
|
||||
sampler {'steps_a', 'steps_b', 'cfg', 'seed_a', 'seed_b', 'sampler_name', 'scheduler'},
|
||||
resolution {'width', 'height', 'batch_size', 'length'},
|
||||
is_video (bool)
|
||||
"""
|
||||
# Import extraction functions from prompt_extractor (lives in nodes/).
|
||||
# Late import to avoid circular deps at module load time.
|
||||
# Relative import works because py/ and nodes/ are siblings in the same package.
|
||||
from ..nodes.prompt_extractor import (
|
||||
parse_workflow_for_prompts,
|
||||
extract_metadata_from_png,
|
||||
extract_metadata_from_jpeg,
|
||||
extract_metadata_from_json,
|
||||
extract_metadata_from_video,
|
||||
)
|
||||
from .lora_utils import resolve_lora_path
|
||||
|
||||
result = {
|
||||
'positive_prompt': '',
|
||||
'negative_prompt': '',
|
||||
'loras_a': [],
|
||||
'loras_b': [],
|
||||
'model_a': '',
|
||||
'model_b': '',
|
||||
'vae': {'name': '', 'source': 'unknown'},
|
||||
'clip': {'names': [], 'type': '', 'source': 'unknown'},
|
||||
'sampler': {
|
||||
'steps_a': 20, 'steps_b': None, 'cfg': 7.0, 'seed_a': 0, 'seed_b': None,
|
||||
'sampler_name': 'euler', 'scheduler': 'normal',
|
||||
},
|
||||
'resolution': {'width': 512, 'height': 512, 'batch_size': 1, 'length': None},
|
||||
'is_video': False,
|
||||
}
|
||||
|
||||
ext = os.path.splitext(file_path)[1].lower()
|
||||
prompt_data = None
|
||||
workflow_data = None
|
||||
|
||||
if ext == '.png':
|
||||
prompt_data, workflow_data = extract_metadata_from_png(file_path)
|
||||
elif ext in ('.jpg', '.jpeg', '.webp'):
|
||||
prompt_data, workflow_data = extract_metadata_from_jpeg(file_path)
|
||||
elif ext == '.json':
|
||||
prompt_data, workflow_data = extract_metadata_from_json(file_path)
|
||||
elif ext in ('.mp4', '.webm', '.mov', '.avi'):
|
||||
prompt_data, workflow_data = extract_metadata_from_video(file_path)
|
||||
result['is_video'] = True
|
||||
|
||||
if not prompt_data and not workflow_data:
|
||||
return result
|
||||
|
||||
extracted = parse_workflow_for_prompts(prompt_data, workflow_data)
|
||||
result['positive_prompt'] = extracted.get('positive_prompt', '')
|
||||
result['negative_prompt'] = extracted.get('negative_prompt', '')
|
||||
result['loras_a'] = extracted.get('loras_a', [])
|
||||
result['loras_b'] = extracted.get('loras_b', [])
|
||||
|
||||
models_a = extracted.get('models_a', [])
|
||||
models_b = extracted.get('models_b', [])
|
||||
result['model_a'] = os.path.basename(models_a[0].replace('\\', '/')) if models_a else ''
|
||||
result['model_b'] = os.path.basename(models_b[0].replace('\\', '/')) if models_b else ''
|
||||
|
||||
result['sampler'] = extract_sampler_params(prompt_data, workflow_data)
|
||||
result['vae'] = extract_vae_info(prompt_data, workflow_data)
|
||||
result['clip'] = extract_clip_info(prompt_data, workflow_data)
|
||||
result['resolution'] = extract_resolution(prompt_data, workflow_data)
|
||||
|
||||
# ── A1111 / Forge override ────────────────────────────────────────────
|
||||
# When prompt_data is a parsed A1111 dict (has 'prompt' + 'loras' keys)
|
||||
# the ComfyUI extraction functions won't find anything. Apply the
|
||||
# values that parse_a1111_parameters() already extracted.
|
||||
if isinstance(prompt_data, dict) and 'prompt' in prompt_data and 'loras' in prompt_data:
|
||||
_s = result['sampler']
|
||||
if prompt_data.get('sampler_name'):
|
||||
_s['sampler_name'] = prompt_data['sampler_name']
|
||||
if prompt_data.get('scheduler'):
|
||||
_s['scheduler'] = prompt_data['scheduler']
|
||||
if prompt_data.get('steps'):
|
||||
_s['steps_a'] = prompt_data['steps']
|
||||
if prompt_data.get('cfg'):
|
||||
_s['cfg'] = prompt_data['cfg']
|
||||
if prompt_data.get('seed'):
|
||||
_s['seed_a'] = prompt_data['seed']
|
||||
_r = result['resolution']
|
||||
if prompt_data.get('width') and prompt_data.get('height'):
|
||||
_r['width'] = prompt_data['width']
|
||||
_r['height'] = prompt_data['height']
|
||||
|
||||
# ── Embedded data override (WorkflowRenderer / PromptExtractor) ──────
|
||||
# When a WorkflowRenderer generated the image there are no standalone
|
||||
# KSampler / EmptyLatentImage nodes. Look for authoritative values in:
|
||||
# 1. extracted_data on the WG or PE node
|
||||
# 2. widgets_values override_data JSON on the WG node
|
||||
# Also check prompt API for WG override_data.
|
||||
_embedded = _find_embedded_generation_data(workflow_data, prompt_data)
|
||||
if _embedded:
|
||||
for key in ('sampler', 'resolution'):
|
||||
if key in _embedded and isinstance(_embedded[key], dict):
|
||||
result[key] = _embedded[key]
|
||||
if _embedded.get('vae'):
|
||||
result['vae'] = _embedded['vae']
|
||||
if _embedded.get('clip'):
|
||||
result['clip'] = _embedded['clip']
|
||||
if not result['model_a'] and _embedded.get('model_a'):
|
||||
result['model_a'] = _embedded['model_a']
|
||||
if not result['model_b'] and _embedded.get('model_b'):
|
||||
result['model_b'] = _embedded['model_b']
|
||||
|
||||
if result['resolution']['length'] is not None:
|
||||
result['is_video'] = True
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def enrich_with_availability(result):
|
||||
"""
|
||||
Add availability flags (lora_availability, model_a_found, etc.)
|
||||
to an extract_all_from_file() result dict in-place.
|
||||
Returns the same dict.
|
||||
"""
|
||||
from .lora_utils import resolve_lora_path
|
||||
|
||||
# LoRA availability
|
||||
lora_availability = {}
|
||||
for loras in [result['loras_a'], result['loras_b']]:
|
||||
for lora in loras:
|
||||
name = lora.get('name', '')
|
||||
if name and name not in lora_availability:
|
||||
_, found = resolve_lora_path(name)
|
||||
lora_availability[name] = found
|
||||
result['lora_availability'] = lora_availability
|
||||
|
||||
# Model A / B availability
|
||||
for key in ['model_a', 'model_b']:
|
||||
model_name = result[key]
|
||||
if model_name:
|
||||
resolved, folder = resolve_model_name(model_name)
|
||||
result[f'{key}_found'] = resolved is not None
|
||||
result[f'{key}_resolved'] = resolved
|
||||
else:
|
||||
result[f'{key}_found'] = True
|
||||
result[f'{key}_resolved'] = None
|
||||
|
||||
# Model family detection (use resolved path — has folder prefix)
|
||||
ref_path = result.get('model_a_resolved') or result.get('model_a', '')
|
||||
family = get_model_family(ref_path)
|
||||
result['model_family'] = family
|
||||
result['model_family_label'] = get_family_label(family)
|
||||
|
||||
# VAE availability
|
||||
vae_name = result['vae'].get('name', '')
|
||||
if vae_name and not vae_name.startswith('('):
|
||||
result['vae_found'] = resolve_vae_name(vae_name) is not None
|
||||
else:
|
||||
result['vae_found'] = True
|
||||
|
||||
# CLIP availability
|
||||
clip_found = []
|
||||
for name in result['clip'].get('names', []):
|
||||
if name and not name.startswith('('):
|
||||
paths = resolve_clip_names([name])
|
||||
clip_found.append(paths[0] is not None)
|
||||
else:
|
||||
clip_found.append(True)
|
||||
result['clip_found'] = clip_found
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def _build_sampler_dict(sampler, family):
|
||||
"""Return sampler dict with steps_a/steps_b for all families."""
|
||||
import math as _math
|
||||
d = {**sampler}
|
||||
# Normalize: if only a plain 'seed' key exists, map it to seed_a
|
||||
if 'seed' in d:
|
||||
d.setdefault('seed_a', d.pop('seed'))
|
||||
d.setdefault('seed_a', 0)
|
||||
d.setdefault('seed_b', sampler.get('seed_b'))
|
||||
# Normalize legacy 'steps' key → steps_a
|
||||
if 'steps' in d and 'steps_a' not in d:
|
||||
d['steps_a'] = d.pop('steps')
|
||||
elif 'steps' in d:
|
||||
d.pop('steps')
|
||||
d.setdefault('steps_a', 20)
|
||||
if family in ('wan_video_i2v', 'wan_video_t2v'):
|
||||
# For WAN dual-sampler: if steps_b not set, split steps_a evenly
|
||||
if d.get('steps_b') is None:
|
||||
total = d['steps_a']
|
||||
d['steps_a'] = _math.ceil(total / 2)
|
||||
d['steps_b'] = total - d['steps_a']
|
||||
# Remove legacy keys
|
||||
d.pop('steps_high', None)
|
||||
d.pop('steps_low', None)
|
||||
return d
|
||||
|
||||
|
||||
def build_simplified_workflow_data(extracted, overrides=None, sampler_params=None):
|
||||
"""
|
||||
Build the shared workflow_data dict that both WorkflowBuilder and PromptExtractor output.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
extracted : dict — result of extract_all_from_file() or an equivalent dict with the same keys
|
||||
overrides : dict — optional JS-side override values (model_a, positive_prompt, …)
|
||||
sampler_params : dict — optional sampler values (already-merged steps/cfg/seed/…)
|
||||
|
||||
Returns a serialisable dict (same schema for both nodes).
|
||||
"""
|
||||
if overrides is None:
|
||||
overrides = {}
|
||||
sampler = sampler_params if sampler_params is not None else extracted.get('sampler', {
|
||||
'steps_a': 20, 'steps_b': None, 'cfg': 7.0, 'seed_a': 0, 'seed_b': None,
|
||||
'sampler_name': 'euler', 'scheduler': 'normal',
|
||||
})
|
||||
|
||||
family = extracted.get('model_family', '')
|
||||
|
||||
# If family is unknown, infer from clip type — each family requires a
|
||||
# specific CLIPLoader type, so this is a reliable signal.
|
||||
clip_info = extracted.get('clip', {})
|
||||
if not family:
|
||||
_clip_type = clip_info.get('type', '').lower()
|
||||
_clip_src = clip_info.get('source', '')
|
||||
if _clip_src == 'checkpoint':
|
||||
family = 'sdxl'
|
||||
elif 'flux2' in _clip_type:
|
||||
family = 'flux2'
|
||||
elif 'flux' in _clip_type:
|
||||
family = 'flux1'
|
||||
elif 'sd3' in _clip_type:
|
||||
family = 'sd3'
|
||||
elif 'wan' in _clip_type:
|
||||
family = 'wan_video_t2v'
|
||||
elif 'qwen_image' in _clip_type:
|
||||
family = 'qwen_image'
|
||||
elif 'lumina2' in _clip_type:
|
||||
family = 'zimage'
|
||||
|
||||
# Determine loader_type: family spec is authoritative when available.
|
||||
# The clip source heuristic ('checkpoint' vs 'separate') is unreliable
|
||||
# when data passes through multiple nodes (e.g. PE → WB → Renderer)
|
||||
# because intermediate steps may set source to 'workflow_data'.
|
||||
from .workflow_families import MODEL_FAMILIES
|
||||
family_spec = MODEL_FAMILIES.get(family, {})
|
||||
if family_spec:
|
||||
is_ckpt = family_spec.get('checkpoint', False)
|
||||
loader_type = 'checkpoint' if is_ckpt else 'unet'
|
||||
else:
|
||||
# No family spec — fall back to clip source heuristic
|
||||
clip_source = clip_info.get('source', '')
|
||||
if clip_source == 'checkpoint':
|
||||
loader_type = 'checkpoint'
|
||||
elif clip_source in ('separate', 'workflow_data'):
|
||||
loader_type = 'unet'
|
||||
else:
|
||||
loader_type = ''
|
||||
|
||||
vae_override_explicit = 'vae' in overrides
|
||||
clip_override_explicit = 'clip_names' in overrides
|
||||
|
||||
vae_val = overrides.get('vae', extracted.get('vae', {}).get('name', ''))
|
||||
clip_val = overrides.get('clip_names', extracted.get('clip', {}).get('names', []))
|
||||
|
||||
# For checkpoint models: if the user didn't explicitly choose a separate
|
||||
# VAE / CLIP file, the checkpoint's own VAE / CLIP should be used.
|
||||
# The extracted values may contain real filenames from the source workflow
|
||||
# (e.g. clip_g.safetensors) but those came from a DualCLIPLoader in the
|
||||
# original graph — they shouldn't override the checkpoint's built-in ones.
|
||||
if loader_type == 'checkpoint':
|
||||
if not vae_override_explicit or not vae_val or vae_val.startswith('('):
|
||||
vae_val = '(from checkpoint)'
|
||||
if not clip_override_explicit or not clip_val or clip_val == [] or \
|
||||
(len(clip_val) == 1 and (not clip_val[0] or clip_val[0].startswith('('))):
|
||||
clip_val = ['(from checkpoint)']
|
||||
|
||||
return {
|
||||
"_source": overrides.get('_source', 'PromptExtractor'),
|
||||
"family": family,
|
||||
"model_a": overrides.get('model_a', extracted.get('model_a', '')),
|
||||
"model_b": overrides.get('model_b', extracted.get('model_b', '')),
|
||||
"positive_prompt": overrides.get('positive_prompt', extracted.get('positive_prompt', '')),
|
||||
"negative_prompt": overrides.get('negative_prompt', extracted.get('negative_prompt', '')),
|
||||
"loras_a": extracted.get('loras_a', []),
|
||||
"loras_b": extracted.get('loras_b', []),
|
||||
"vae": vae_val,
|
||||
"clip": clip_val,
|
||||
"clip_type": clip_info.get('type', '') or family_spec.get('clip_type', ''),
|
||||
"loader_type": loader_type,
|
||||
"sampler": _build_sampler_dict(sampler, family),
|
||||
"resolution": {
|
||||
"width": overrides.get('width', extracted.get('resolution', {}).get('width', 512)),
|
||||
"height": overrides.get('height', extracted.get('resolution', {}).get('height', 512)),
|
||||
"batch_size": overrides.get('batch_size', extracted.get('resolution', {}).get('batch_size', 1)),
|
||||
"length": overrides.get('length', extracted.get('resolution', {}).get('length', None)),
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
"""
|
||||
Model family definitions and compatibility helpers for ComfyUI Prompt Manager.
|
||||
|
||||
Shared by workflow_builder, workflow_renderer, and workflow_extraction_utils.
|
||||
|
||||
Each family dict specifies:
|
||||
"label" — human-readable name shown in UI dropdowns
|
||||
"folders" — lowercase path prefixes (matched against relative model path)
|
||||
"names" — lowercase substrings matched against filename only
|
||||
"vae" — VAE filename substrings compatible with this family
|
||||
"vae_exact" — VAE exact basenames (full filename match, e.g. "ae.safetensors")
|
||||
"clip" — CLIP/text-encoder filename substrings compatible with this family
|
||||
"clip_exact" — CLIP exact basenames (full filename match)
|
||||
"clip_exclude" — substrings that DISQUALIFY a CLIP match (applied after include patterns)
|
||||
"clip_type" — CLIPType key passed to comfy.sd.load_clip (e.g. "flux", "wan")
|
||||
"clip_slots" — number of distinct CLIP files needed (default 1; flux1/sdxl need 2)
|
||||
"sampler" — internal sampling strategy key (see SAMPLER_STRATEGIES below)
|
||||
|
||||
Matching rules:
|
||||
VAE: vae_exact checked first (full basename), then vae substring patterns.
|
||||
CLIP: clip_exclude applied first — any match disqualifies the file.
|
||||
Then clip_exact checked (full basename), then clip substring patterns.
|
||||
Folder prefixes checked before name patterns. First match wins for family detection.
|
||||
To add a new family: add a dict entry and handle its "sampler" key in workflow_builder.
|
||||
"""
|
||||
import os
|
||||
import folder_paths
|
||||
|
||||
# ─── Family definitions ──────────────────────────────────────────────────────
|
||||
|
||||
MODEL_FAMILIES = {
|
||||
# ── Flux 2 / Klein ───────────────────────────────────────────────────────
|
||||
"flux2": {
|
||||
"label": "Flux 2",
|
||||
"folders": ["klein/", "flux2/"],
|
||||
"names": ["flux2", "flux-2", "flux_2", "klein", "flux.2"],
|
||||
# Flux2/Klein uses its own VAE — NOT ae.safetensors
|
||||
"vae": ["flux2-vae", "flux2_vae"],
|
||||
# Klein uses Qwen text encoders (NOT T5/CLIP-L):
|
||||
# 4B model → qwen_3_4b.safetensors
|
||||
# 9B model → qwen_3_8b_fp8mixed.safetensors
|
||||
# CLIPLoader type must be "flux2" so CLIPType.FLUX2 is used.
|
||||
"clip": ["qwen_3_8b"],
|
||||
"clip_exclude": ["qwen_2.5", "qwen_2_5", "qwen_3_4b", "t5xxl", "umt5", "clip_l", "clip_g", "gemma"],
|
||||
"clip_type": "flux2",
|
||||
"sampler": "flux2",
|
||||
},
|
||||
# ── Flux 1 (Dev + Schnell merged) ────────────────────────────────────────
|
||||
"flux1": {
|
||||
"label": "Flux 1",
|
||||
"folders": ["flux/", "flux1/"],
|
||||
"names": ["flux-dev", "flux_dev", "fluxdev", "flux1-dev", "flux1_dev",
|
||||
"flux-schnell", "flux_schnell", "fluxschnell", "flux1-schnell",
|
||||
"flux1_schnell", "flux1-", "flux1_", "flux.1"],
|
||||
# ae.safetensors is the canonical Flux1 VAE — exact match required to
|
||||
# avoid catching "mae.safetensors" or other short-named files.
|
||||
"vae": [],
|
||||
"vae_exact": ["ae.safetensors"],
|
||||
# Flux1 uses T5-XXL + CLIP-L dual encoders.
|
||||
# umt5_xxl also contains "t5xxl" as substring — exclude it explicitly.
|
||||
"clip": ["t5xxl"],
|
||||
"clip_exclude": ["umt5", "clip_l", "clip_g", "qwen", "gemma", "awq-int"],
|
||||
"clip_type": "flux",
|
||||
"clip_slots": 2,
|
||||
"sampler": "flux",
|
||||
},
|
||||
# ── Z-Image (Base + Turbo merged) ────────────────────────────────────────
|
||||
"zimage": {
|
||||
"label": "Z-Image",
|
||||
"folders": ["zib/", "zit/", "zimage/"],
|
||||
"names": ["z_image", "z-image", "zimage", "blitz"],
|
||||
# Z-Image shares ae.safetensors with Flux1 for its base VAE.
|
||||
"vae": ["zimageturbo_vae"],
|
||||
"vae_exact": ["ae.safetensors"],
|
||||
# Z-Image uses Qwen 3 4B as its text encoder (not the larger 8B,
|
||||
# not T5, not CLIP-L). The 4B file is typically named
|
||||
# "qwen-4b-zimage.safetensors" or "qwen_3_4b.safetensors".
|
||||
"clip": ["qwen-4b-zimage", "qwen_3_4b"],
|
||||
"clip_exclude": ["qwen_3_8b", "qwen_2.5", "qwen_2_5", "t5xxl", "umt5",
|
||||
"clip_l", "clip_g", "gemma"],
|
||||
"clip_type": "lumina2",
|
||||
"sampler": "zimage",
|
||||
},
|
||||
# ── WAN 2.x Video — Image-to-Video (dual KSampler + i2v latent) ──────────
|
||||
"wan_video_i2v": {
|
||||
"label": "WAN Video (i2v)",
|
||||
"folders": ["wan2_2/i2v/", "wan2_1/i2v/"],
|
||||
"names": ["wan2.2_i2v", "wan2.1_i2v", "wan_i2v", "i2v"],
|
||||
"vae": ["wan_2.1_vae", "wan2.1_vae", "wan2.1-vae", "wan_2.1-vae"],
|
||||
"clip": ["umt5_xxl", "umt5-xxl"],
|
||||
"clip_exclude": ["t5xxl", "clip_l", "clip_g", "qwen", "gemma"],
|
||||
"clip_type": "wan",
|
||||
"sampler": "wan_video",
|
||||
},
|
||||
# ── WAN 2.x Video — Text-to-Video (dual KSampler) ────────────────────────
|
||||
# DETECTION PRIORITY: must appear before wan_image — they share the same
|
||||
# folders/names, so first-match wins. Auto-detected T2V models land here;
|
||||
# user selects wan_image explicitly from the family dropdown.
|
||||
"wan_video_t2v": {
|
||||
"label": "WAN Video (t2v)",
|
||||
"folders": ["wan2_2/", "wan2_1/", "wan/"],
|
||||
"names": ["wan2.2", "wan2.1", "wan2_2", "wan2_1", "wanvideo", "wan_t2v",
|
||||
"wan2.2_t2v", "wan2.1_t2v"],
|
||||
"vae": ["wan_2.1_vae", "wan2.1_vae", "wan2.1-vae", "wan_2.1-vae"],
|
||||
"clip": ["umt5_xxl", "umt5-xxl"],
|
||||
"clip_exclude": ["t5xxl", "clip_l", "clip_g", "qwen", "gemma"],
|
||||
"clip_type": "wan",
|
||||
"sampler": "wan_video",
|
||||
},
|
||||
# ── WAN 2.x Image (single KSampler, text-to-image) ──────────────────────
|
||||
# Same model files as WAN Video T2V — identical folders/names/vae/clip.
|
||||
# Must appear AFTER wan_video_t2v so auto-detection resolves T2V models
|
||||
# to wan_video_t2v. User picks this family explicitly for still images.
|
||||
# Sampler stays wan_image (single KSampler, no dual Steps rows).
|
||||
"wan_image": {
|
||||
"label": "WAN Image",
|
||||
"folders": ["wan2_2/", "wan2_1/", "wan/"],
|
||||
"names": ["wan2.2", "wan2.1", "wan2_2", "wan2_1", "wanvideo", "wan_t2v",
|
||||
"wan2.2_t2v", "wan2.1_t2v"],
|
||||
"vae": ["wan_2.1_vae", "wan2.1_vae", "wan2.1-vae", "wan_2.1-vae"],
|
||||
# WAN uses UMT5-XXL exclusively — NOT t5xxl, NOT clip_l/g.
|
||||
"clip": ["umt5_xxl", "umt5-xxl"],
|
||||
"clip_exclude": ["t5xxl", "clip_l", "clip_g", "qwen", "gemma"],
|
||||
"clip_type": "wan",
|
||||
"sampler": "wan_image",
|
||||
},
|
||||
# ── LTX-Video ────────────────────────────────────────────────────────────
|
||||
"ltxv": {
|
||||
"label": "LTX-Video",
|
||||
"folders": ["ltx/"],
|
||||
"names": ["ltxv", "ltx-video", "ltx-2", "ltx2"],
|
||||
# LTX has its own VAE — NOT ae.safetensors, NOT SDXL/SD VAE.
|
||||
# taeltx* are TAE-based approximation VAEs for LTX.
|
||||
"vae": ["ltx23_video_vae", "ltxv_vae", "ltx_vae", "taeltx"],
|
||||
# LTX-Video uses T5-XXL only (same encoder family as Flux1 but
|
||||
# NOT the dual CLIP-L+T5 combo — single T5 only).
|
||||
# umt5_xxl contains "t5xxl" → must exclude it.
|
||||
"clip": ["t5xxl"],
|
||||
"clip_exclude": ["umt5", "clip_l", "clip_g", "qwen", "gemma"],
|
||||
"clip_type": "sd3",
|
||||
"sampler": "flux",
|
||||
},
|
||||
# ── SDXL (+ Pony, Illustrious, Turbo merged) ────────────────────────────
|
||||
"sdxl": {
|
||||
"label": "SDXL",
|
||||
"folders": ["illustrious/", "pony/", "sdxl/"],
|
||||
"names": ["sdxl", "illustrious", "noob", "pony"],
|
||||
# SDXL uses its own finely-tuned VAE (sdxl_vae / sdxl-vae) or the
|
||||
# widely-used vae-ft-mse-840000 (originally SD1.5 but SDXL-compatible).
|
||||
"vae": ["sdxl_vae", "sdxl-vae", "vae-ft-mse"],
|
||||
# SDXL uses dual text encoders: CLIP-L + CLIP-G.
|
||||
"clip": ["clip_l", "clip_g"],
|
||||
"clip_exclude": ["t5xxl", "umt5", "qwen", "gemma"],
|
||||
"sampler": "standard",
|
||||
"checkpoint": True,
|
||||
},
|
||||
# ── SD 1.5 ───────────────────────────────────────────────────────────────
|
||||
"sd15": {
|
||||
"label": "SD 1.5",
|
||||
"folders": [],
|
||||
"names": ["sd-1", "sd_1", "sd1", "v1-5", "v1_5", "v1.5", "dreamshaper", "realistic"],
|
||||
# SD1.5 canonical VAE: vae-ft-mse-840000 or vae-ft-ema-560000.
|
||||
"vae": ["vae-ft-mse-840000", "vae-ft-ema-560000", "orangemix", "blessed2"],
|
||||
# SD1.5 uses a single CLIP-L encoder only (NOT CLIP-G like SDXL).
|
||||
"clip": ["clip_l"],
|
||||
"clip_exclude": ["clip_g", "t5xxl", "umt5", "qwen", "gemma"],
|
||||
"sampler": "standard",
|
||||
"checkpoint": True,
|
||||
},
|
||||
# ── Qwen Image ───────────────────────────────────────────────────────────
|
||||
"qwen_image": {
|
||||
"label": "Qwen Image",
|
||||
"folders": ["qwen/"],
|
||||
"names": ["qwen_image"],
|
||||
"vae": ["qwen_image_vae"],
|
||||
"clip": ["qwen_2.5_vl", "qwen_2_5_vl"],
|
||||
"clip_exclude": ["qwen_3", "t5xxl", "umt5", "clip_l", "clip_g", "gemma"],
|
||||
"clip_type": "qwen_image",
|
||||
"sampler": "standard",
|
||||
},
|
||||
}
|
||||
|
||||
# Compatibility groups — checkpoint families that can share each other's models.
|
||||
# VAE/CLIP are NOT grouped (they differ per family) — model weights only.
|
||||
MODEL_COMPAT_GROUPS = [
|
||||
{"sdxl"}, # SDXL-arch — all merged into one now
|
||||
{"flux1"}, # Flux1 variants — all merged into one now
|
||||
{"zimage"}, # Z-Image — all merged
|
||||
{"flux2"}, # Flux2 — all merged
|
||||
{"wan_image", "wan_video_t2v"}, # WAN Image shares T2V model files
|
||||
]
|
||||
|
||||
# Sampling strategy keys (referenced by workflow_builder.py / workflow_renderer.py)
|
||||
# Each key maps to a specific sampling code path.
|
||||
SAMPLER_STRATEGIES = {
|
||||
"standard": "standard", # KSampler — SD1.5, SDXL, Qwen
|
||||
"flux": "flux", # SamplerCustomAdvanced + BasicGuider (Flux1, LTX-Video)
|
||||
"flux2": "flux2", # SamplerCustomAdvanced + CFGGuider (Klein/Flux2)
|
||||
"zimage": "zimage", # ModelSamplingAuraFlow + standard KSampler (Z-Image)
|
||||
"wan_image": "wan_image", # Single KSampler — WAN Image
|
||||
"wan_video": "wan_video", # Dual KSamplerAdvanced high/low (WAN Video i2v + t2v)
|
||||
}
|
||||
|
||||
# Workflow template filenames (in workflows/api/) keyed by family.
|
||||
# Maps each family key to its _api.json and _map.json stem.
|
||||
FAMILY_WORKFLOW_STEMS = {
|
||||
"sdxl": "sdxl",
|
||||
"sd15": None, # No template yet — falls back to hardcoded
|
||||
"flux1": "flux_1",
|
||||
"flux2": "flux_2",
|
||||
"zimage": "z_image",
|
||||
"wan_image": "wan_image",
|
||||
"wan_video_i2v": "wan_video_i2v",
|
||||
"wan_video_t2v": "wan_video_t2v",
|
||||
"ltxv": None, # No template yet
|
||||
"qwen_image": "qwen_image",
|
||||
}
|
||||
|
||||
|
||||
# ─── Family lookup ───────────────────────────────────────────────────────────
|
||||
|
||||
def get_model_family(model_path):
|
||||
"""
|
||||
Return the family key for a model, or None if unknown.
|
||||
Accepts a relative path like 'Illustrious/Anime/illustrij_v20.safetensors'.
|
||||
"""
|
||||
if not model_path:
|
||||
return None
|
||||
path_lower = model_path.lower().replace("\\", "/")
|
||||
name_lower = os.path.basename(path_lower)
|
||||
|
||||
for family, spec in MODEL_FAMILIES.items():
|
||||
for prefix in spec.get("folders", []):
|
||||
if path_lower.startswith(prefix.lower().replace("\\", "/")):
|
||||
return family
|
||||
for pat in spec.get("names", []):
|
||||
if pat in name_lower:
|
||||
return family
|
||||
return None
|
||||
|
||||
|
||||
def get_family_label(family):
|
||||
"""Return the human-readable label for a family, or the key itself."""
|
||||
if not family:
|
||||
return "Unknown"
|
||||
return MODEL_FAMILIES.get(family, {}).get("label", family)
|
||||
|
||||
|
||||
def get_family_sampler_strategy(family):
|
||||
"""Return the sampler strategy key for a family (default: 'standard')."""
|
||||
if not family:
|
||||
return "standard"
|
||||
return MODEL_FAMILIES.get(family, {}).get("sampler", "standard")
|
||||
|
||||
|
||||
def get_compatible_families(family):
|
||||
"""Return the set of all checkpoint-families compatible with the given one."""
|
||||
if not family:
|
||||
return set()
|
||||
result = {family}
|
||||
for group in MODEL_COMPAT_GROUPS:
|
||||
if family in group:
|
||||
result |= group
|
||||
return result
|
||||
|
||||
|
||||
def get_all_family_labels():
|
||||
"""Return a dict of {family_key: label} for all known families."""
|
||||
hidden = {"ltxv"}
|
||||
return {k: v.get("label", k) for k, v in MODEL_FAMILIES.items() if k not in hidden}
|
||||
|
||||
|
||||
# ─── Model listing ───────────────────────────────────────────────────────────
|
||||
|
||||
def _model_keywords(model_name):
|
||||
"""Extract meaningful keywords from a model filename for fuzzy matching.
|
||||
Strips extension, path, and GGUF quantization tokens (Q8_0, Q4_K_M, etc.)."""
|
||||
import re
|
||||
base = os.path.splitext(os.path.basename(model_name))[0].lower()
|
||||
# Remove GGUF quant suffixes: Q8_0, Q4_K_M, Q5_K_S, Q6_K, etc.
|
||||
base = re.sub(r'[-_]?q\d[_\w]*$', '', base, flags=re.IGNORECASE)
|
||||
# Also strip common precision suffixes: fp8, fp16, bf16, fp32
|
||||
base = re.sub(r'[-_]?(?:fp8|fp16|bf16|fp32)(?:mixed)?$', '', base, flags=re.IGNORECASE)
|
||||
# Split on _ and - to get keywords, filter empties
|
||||
return set(tok for tok in re.split(r'[-_]', base) if tok)
|
||||
|
||||
|
||||
def list_compatible_models(reference_model, family_override=None):
|
||||
"""
|
||||
Given a reference model name/path, return a list of compatible
|
||||
models found on disk, sorted by keyword similarity to the reference.
|
||||
|
||||
The best keyword match is first, so callers can use [0] as a fallback.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
reference_model : str — model path/name to derive family from
|
||||
family_override : str | None — explicit family key (takes priority)
|
||||
"""
|
||||
family = family_override or get_model_family(reference_model)
|
||||
compat = get_compatible_families(family)
|
||||
|
||||
all_models = []
|
||||
for folder_name in ['checkpoints', 'diffusion_models', 'unet', 'unet_gguf']:
|
||||
try:
|
||||
all_models.extend(folder_paths.get_filename_list(folder_name))
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# Deduplicate preserving order
|
||||
seen = set()
|
||||
unique = []
|
||||
for m in all_models:
|
||||
if m not in seen:
|
||||
seen.add(m)
|
||||
unique.append(m)
|
||||
|
||||
if not compat:
|
||||
return []
|
||||
|
||||
compatible = []
|
||||
for m in unique:
|
||||
m_family = get_model_family(m)
|
||||
if m_family and m_family in compat:
|
||||
compatible.append(m)
|
||||
|
||||
if not compatible:
|
||||
return []
|
||||
|
||||
# Sort by keyword similarity to reference model (best match first)
|
||||
ref_keywords = _model_keywords(reference_model)
|
||||
if ref_keywords:
|
||||
def _match_score(m):
|
||||
m_keywords = _model_keywords(m)
|
||||
shared = len(ref_keywords & m_keywords)
|
||||
# Tie-break: prefer fewer extra keywords (closer match)
|
||||
extra = len(m_keywords - ref_keywords)
|
||||
return (-shared, extra, m.lower())
|
||||
compatible.sort(key=_match_score)
|
||||
else:
|
||||
compatible.sort()
|
||||
|
||||
return compatible
|
||||
|
||||
|
||||
def list_all_models():
|
||||
"""Return all models from all known model folder types (deduplicated, sorted)."""
|
||||
all_models = []
|
||||
seen = set()
|
||||
for folder_name in ['checkpoints', 'diffusion_models', 'unet', 'unet_gguf']:
|
||||
try:
|
||||
for m in folder_paths.get_filename_list(folder_name):
|
||||
if m not in seen:
|
||||
seen.add(m)
|
||||
all_models.append(m)
|
||||
except Exception:
|
||||
continue
|
||||
return sorted(all_models)
|
||||
|
||||
|
||||
def list_compatible_vaes(family, return_recommended=False):
|
||||
"""Return sorted list of VAE files compatible with the given family.
|
||||
If return_recommended=True, returns (list, recommended_str_or_None).
|
||||
|
||||
Matching order:
|
||||
1. vae_exact — full basename match (e.g. "ae.safetensors"), case-insensitive
|
||||
2. vae — substring match against basename or full relative path
|
||||
Falls back to all VAEs when no patterns are defined or nothing matched.
|
||||
"""
|
||||
def _ret(lst, rec):
|
||||
return (sorted(lst), rec) if return_recommended else sorted(lst)
|
||||
|
||||
if not family:
|
||||
try:
|
||||
return _ret(folder_paths.get_filename_list("vae"), None)
|
||||
except Exception:
|
||||
return _ret([], None)
|
||||
|
||||
spec = MODEL_FAMILIES.get(family, {})
|
||||
exact_names = [e.lower() for e in spec.get("vae_exact", [])]
|
||||
patterns = [p.lower() for p in spec.get("vae", [])]
|
||||
|
||||
if not exact_names and not patterns:
|
||||
try:
|
||||
return _ret(folder_paths.get_filename_list("vae"), None)
|
||||
except Exception:
|
||||
return _ret([], None)
|
||||
|
||||
try:
|
||||
all_vaes = folder_paths.get_filename_list("vae")
|
||||
except Exception:
|
||||
return _ret([], None)
|
||||
|
||||
matched = []
|
||||
recommended = None
|
||||
is_checkpoint = spec.get("checkpoint", False)
|
||||
|
||||
for v in all_vaes:
|
||||
v_lower = v.lower().replace("\\", "/")
|
||||
v_name = os.path.basename(v_lower)
|
||||
|
||||
# 1. Exact basename match (e.g. "ae.safetensors")
|
||||
if v_name in exact_names:
|
||||
matched.append(v)
|
||||
if recommended is None and not is_checkpoint:
|
||||
recommended = v
|
||||
continue
|
||||
|
||||
# 2. Substring patterns
|
||||
for pat in patterns:
|
||||
if pat in v_name or pat in v_lower:
|
||||
matched.append(v)
|
||||
if recommended is None and not is_checkpoint:
|
||||
recommended = v
|
||||
break
|
||||
|
||||
if matched:
|
||||
return _ret(matched, recommended)
|
||||
return _ret(all_vaes, None)
|
||||
|
||||
|
||||
def list_compatible_clips(family, return_recommended=False):
|
||||
"""Return sorted list of CLIP/text-encoder files compatible with the given family.
|
||||
If return_recommended=True, returns (list, recommended_str_or_None).
|
||||
|
||||
Matching order:
|
||||
1. clip_exclude — if ANY exclude pattern is found in the basename/path, skip the file
|
||||
2. clip_exact — full basename match, case-insensitive
|
||||
3. clip — substring match against basename or full relative path
|
||||
Falls back to all CLIPs when no patterns are defined or nothing matched.
|
||||
"""
|
||||
def _ret(lst, rec):
|
||||
return (sorted(lst), rec) if return_recommended else sorted(lst)
|
||||
|
||||
if not family:
|
||||
clips = _gather_all_clips()
|
||||
return _ret(clips, None)
|
||||
|
||||
spec = MODEL_FAMILIES.get(family, {})
|
||||
exclude_pats = [e.lower() for e in spec.get("clip_exclude", [])]
|
||||
exact_names = [e.lower() for e in spec.get("clip_exact", [])]
|
||||
patterns = [p.lower() for p in spec.get("clip", [])]
|
||||
|
||||
if not exact_names and not patterns:
|
||||
clips = _gather_all_clips()
|
||||
return _ret(clips, None)
|
||||
|
||||
all_clips = _gather_all_clips()
|
||||
|
||||
matched = []
|
||||
recommended = None
|
||||
is_checkpoint = spec.get("checkpoint", False)
|
||||
|
||||
for c in all_clips:
|
||||
c_lower = c.lower().replace("\\", "/")
|
||||
c_name = os.path.basename(c_lower)
|
||||
|
||||
# 1. Exclusion check — disqualify if any exclude pattern is present
|
||||
if any(ex in c_name or ex in c_lower for ex in exclude_pats):
|
||||
continue
|
||||
|
||||
# 2. Exact basename match
|
||||
if c_name in exact_names:
|
||||
matched.append(c)
|
||||
if recommended is None and not is_checkpoint:
|
||||
recommended = c
|
||||
continue
|
||||
|
||||
# 3. Substring include patterns
|
||||
for pat in patterns:
|
||||
if pat in c_name or pat in c_lower:
|
||||
matched.append(c)
|
||||
if recommended is None and not is_checkpoint:
|
||||
recommended = c
|
||||
break
|
||||
|
||||
if matched:
|
||||
return _ret(matched, recommended)
|
||||
return _ret(all_clips, None)
|
||||
|
||||
|
||||
def _gather_all_clips():
|
||||
"""Gather CLIP files from text_encoders and clip folders."""
|
||||
clips = []
|
||||
seen = set()
|
||||
for folder in ['text_encoders', 'clip']:
|
||||
try:
|
||||
for c in folder_paths.get_filename_list(folder):
|
||||
if c not in seen:
|
||||
seen.add(c)
|
||||
clips.append(c)
|
||||
except Exception:
|
||||
pass
|
||||
return clips
|
||||
@@ -0,0 +1,8 @@
|
||||
"""
|
||||
Thin re-exports of node-graph helpers from prompt_extractor.
|
||||
Placed in py/ so workflow_extraction_utils can import without a circular dep.
|
||||
Uses relative import since both py/ and nodes/ are siblings under the package root.
|
||||
"""
|
||||
from ..nodes.prompt_extractor import build_node_map, build_link_map
|
||||
|
||||
__all__ = ['build_node_map', 'build_link_map']
|
||||
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "prompt-manager"
|
||||
description = "Prompt Manager extension for ComfyUI, allowing user to both save and generate prompts, as well as save matching loras for each prompt."
|
||||
version = "1.9.1"
|
||||
description = "A comprehensive prompt management system for ComfyUI that saves complete workflow recipes including prompts, LoRAs, and their settings. Features AI-powered prompt generation, prompt extraction from ComfyUI/A1111 images and videos, and Dual LoRA Stack support for Wan workflows."
|
||||
version = "2.0.0"
|
||||
license = {file = "LICENSE"}
|
||||
# classifiers = [
|
||||
# # For OS-independent nodes (works on all operating systems)
|
||||
@@ -20,7 +20,7 @@ license = {file = "LICENSE"}
|
||||
# "Environment :: GPU :: Apple Metal", # Apple Metal support
|
||||
# ]
|
||||
|
||||
dependencies = ["requests>=2.31.0", "huggingface_hub>=0.20.0", "psutil>=5.9.0", "tqdm>=4.66.0", "Pillow>=10.0.0", "torch>=2.0.0", "numpy>=1.24.0", "colorama"]
|
||||
dependencies = ["requests", "huggingface_hub", "psutil", "tqdm", "Pillow", "torch", "numpy", "colorama"]
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/FranckyB/ComfyUI-Prompt-Manager"
|
||||
@@ -34,4 +34,3 @@ DisplayName = "ComfyUI-Prompt-Manager"
|
||||
Icon = ""
|
||||
includes = []
|
||||
# "requires-comfyui" = ">=1.0.0" # ComfyUI version compatibility
|
||||
|
||||
|
||||
@@ -1,8 +1,2 @@
|
||||
requests>=2.31.0
|
||||
huggingface_hub>=0.20.0
|
||||
psutil>=5.9.0
|
||||
tqdm>=4.66.0
|
||||
Pillow>=10.0.0
|
||||
torch>=2.0.0
|
||||
numpy>=1.24.0
|
||||
huggingface_hub
|
||||
colorama
|
||||
@@ -0,0 +1,38 @@
|
||||
import sys, io, json
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
from PIL import Image
|
||||
|
||||
img = Image.open(r'D:\ComfyUI-Dev\output\ComfyUI_00006_.png')
|
||||
print('=== Keys in info ===')
|
||||
for k in img.info:
|
||||
print(f' {k}: {len(str(img.info[k]))} chars')
|
||||
|
||||
# Check workflow for extracted_data
|
||||
wf = json.loads(img.info.get('workflow', '{}'))
|
||||
for node in wf.get('nodes', []):
|
||||
ntype = node.get('type', '')
|
||||
nid = node.get('id', '?')
|
||||
if ntype == 'PromptExtractor':
|
||||
print(f'\n=== PromptExtractor node {nid} ===')
|
||||
ext = node.get('extracted_data')
|
||||
if ext:
|
||||
print('extracted_data FOUND:')
|
||||
print(json.dumps(ext, indent=2, ensure_ascii=False)[:2000])
|
||||
else:
|
||||
print('extracted_data: MISSING')
|
||||
print('Node keys:', list(node.keys()))
|
||||
# Show widgets_values
|
||||
wv = node.get('widgets_values', [])
|
||||
print(f'widgets_values ({len(wv)} items): {str(wv)[:500]}')
|
||||
|
||||
# Also check prompt (API format) for PromptExtractor
|
||||
prompt = json.loads(img.info.get('prompt', '{}'))
|
||||
for nid, ndata in prompt.items():
|
||||
if isinstance(ndata, dict) and ndata.get('class_type') == 'PromptExtractor':
|
||||
print(f'\n=== API PromptExtractor node {nid} ===')
|
||||
inputs = ndata.get('inputs', {})
|
||||
print('Input keys:', list(inputs.keys()))
|
||||
for k in ['loras_a_toggle', 'loras_b_toggle', 'lora_stack_a', 'lora_stack_b']:
|
||||
if k in inputs:
|
||||
val = inputs[k]
|
||||
print(f' {k}: {str(val)[:300]}')
|
||||
@@ -0,0 +1,97 @@
|
||||
import sys, json, types, os, glob, io
|
||||
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
|
||||
sys.path.insert(0, r'D:\ComfyUI-Dev')
|
||||
mock_server = types.ModuleType('server')
|
||||
mock_server.web = types.SimpleNamespace(json_response=lambda *a, **k: None)
|
||||
class FakePromptServer:
|
||||
class instance:
|
||||
class routes:
|
||||
@staticmethod
|
||||
def post(path): return lambda f: f
|
||||
@staticmethod
|
||||
def get(path): return lambda f: f
|
||||
mock_server.PromptServer = FakePromptServer
|
||||
sys.modules['server'] = mock_server
|
||||
|
||||
sys.path.insert(0, r'D:\ComfyUI\custom_nodes\ComfyUI-Prompt-Manager')
|
||||
from nodes.prompt_extractor import parse_workflow_for_prompts, MODEL_LOADER_TYPES, parse_a1111_parameters
|
||||
from PIL import Image
|
||||
|
||||
pics_dir = r'D:\ComfyUI-Dev\input\Workflow\Pics'
|
||||
no_model_count = 0
|
||||
ok_count = 0
|
||||
|
||||
for f in sorted(glob.glob(os.path.join(pics_dir, '*.png'))):
|
||||
try:
|
||||
img = Image.open(f)
|
||||
prompt_str = img.info.get('prompt', '')
|
||||
workflow_str = img.info.get('workflow', '')
|
||||
parameters_str = img.info.get('parameters', '')
|
||||
if not prompt_str and not workflow_str and not parameters_str:
|
||||
continue
|
||||
|
||||
# Handle A1111 parameters format
|
||||
if not prompt_str and not workflow_str and parameters_str:
|
||||
parsed_a1111 = parse_a1111_parameters(parameters_str)
|
||||
prompt_data = parsed_a1111 if parsed_a1111 else {}
|
||||
workflow_data = {}
|
||||
else:
|
||||
prompt_data = json.loads(prompt_str) if prompt_str else {}
|
||||
workflow_data = json.loads(workflow_str) if workflow_str else {}
|
||||
|
||||
# Check what model loaders exist
|
||||
api_loaders = []
|
||||
if prompt_data:
|
||||
for nid, ndata in prompt_data.items():
|
||||
if isinstance(ndata, dict):
|
||||
ct = ndata.get('class_type', '')
|
||||
if ct in MODEL_LOADER_TYPES:
|
||||
api_loaders.append((nid, ct))
|
||||
|
||||
wf_loaders = []
|
||||
wf_loader_types = set()
|
||||
if workflow_data and 'nodes' in workflow_data:
|
||||
for node in workflow_data['nodes']:
|
||||
if isinstance(node, dict):
|
||||
ntype = node.get('type', '')
|
||||
if ntype in MODEL_LOADER_TYPES:
|
||||
wid = node.get('widgets_values', [])
|
||||
wf_loaders.append((node.get('id'), ntype, wid[:2] if wid else []))
|
||||
# Also check for checkpoint-like types not in our list
|
||||
nt_lower = ntype.lower()
|
||||
if any(k in nt_lower for k in ['checkpoint', 'unet', 'diffusion', 'model_loader']):
|
||||
wf_loader_types.add(ntype)
|
||||
|
||||
parsed = parse_workflow_for_prompts(prompt_data, workflow_data)
|
||||
models_a = parsed.get('models_a', [])
|
||||
models_b = parsed.get('models_b', [])
|
||||
|
||||
basename = os.path.basename(f)
|
||||
if not models_a and not models_b:
|
||||
no_model_count += 1
|
||||
print(f"\nNO MODELS: {basename}")
|
||||
if api_loaders:
|
||||
print(f" API loaders found: {api_loaders}")
|
||||
if wf_loaders:
|
||||
print(f" WF loaders found: {wf_loaders}")
|
||||
if wf_loader_types:
|
||||
print(f" Checkpoint-like types in WF: {wf_loader_types}")
|
||||
if not api_loaders and not wf_loaders and not wf_loader_types:
|
||||
all_types = set()
|
||||
if prompt_data:
|
||||
for ndata in prompt_data.values():
|
||||
if isinstance(ndata, dict):
|
||||
all_types.add(ndata.get('class_type', ''))
|
||||
if workflow_data and 'nodes' in workflow_data:
|
||||
for node in workflow_data['nodes']:
|
||||
if isinstance(node, dict):
|
||||
all_types.add(node.get('type', ''))
|
||||
print(f" ALL types: {sorted(all_types)}")
|
||||
else:
|
||||
ok_count += 1
|
||||
except Exception as e:
|
||||
print(f"ERROR: {os.path.basename(f)}: {e}")
|
||||
|
||||
print(f"\n=== SUMMARY: {ok_count} OK, {no_model_count} no models ===")
|
||||
@@ -0,0 +1,82 @@
|
||||
import sys, json, types, os, glob, io
|
||||
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
|
||||
|
||||
sys.path.insert(0, r'D:\ComfyUI-Dev')
|
||||
mock_server = types.ModuleType('server')
|
||||
mock_server.web = types.SimpleNamespace(json_response=lambda *a, **k: None)
|
||||
class FakePromptServer:
|
||||
class instance:
|
||||
class routes:
|
||||
@staticmethod
|
||||
def post(path): return lambda f: f
|
||||
@staticmethod
|
||||
def get(path): return lambda f: f
|
||||
mock_server.PromptServer = FakePromptServer
|
||||
sys.modules['server'] = mock_server
|
||||
|
||||
sys.path.insert(0, r'D:\ComfyUI\custom_nodes\ComfyUI-Prompt-Manager')
|
||||
from nodes.prompt_extractor import parse_workflow_for_prompts, extract_metadata_from_video, MODEL_LOADER_TYPES, resolve_model_path
|
||||
|
||||
vids_dir = r'D:\ComfyUI-Dev\input\Workflow\Vids'
|
||||
ok_count = 0
|
||||
no_model_count = 0
|
||||
no_metadata_count = 0
|
||||
error_count = 0
|
||||
|
||||
for f in sorted(glob.glob(os.path.join(vids_dir, '*.mp4'))):
|
||||
basename = os.path.basename(f)
|
||||
try:
|
||||
result = extract_metadata_from_video(f)
|
||||
if not result or (not result[0] and not result[1]):
|
||||
no_metadata_count += 1
|
||||
continue
|
||||
|
||||
prompt_str, workflow_str = result
|
||||
prompt_data = json.loads(prompt_str) if isinstance(prompt_str, str) else (prompt_str or {})
|
||||
workflow_data = json.loads(workflow_str) if isinstance(workflow_str, str) else (workflow_str or {})
|
||||
|
||||
if not prompt_data and not workflow_data:
|
||||
no_metadata_count += 1
|
||||
continue
|
||||
|
||||
parsed = parse_workflow_for_prompts(prompt_data, workflow_data)
|
||||
models_a = parsed.get('models_a', [])
|
||||
models_b = parsed.get('models_b', [])
|
||||
|
||||
if models_a or models_b:
|
||||
ok_count += 1
|
||||
a_resolved = resolve_model_path(models_a[0])[0] if models_a else ""
|
||||
b_resolved = resolve_model_path(models_b[0])[0] if models_b else ""
|
||||
print(f"OK: {basename} -> A={a_resolved}, B={b_resolved}")
|
||||
else:
|
||||
no_model_count += 1
|
||||
# Check what loader types exist
|
||||
all_types = set()
|
||||
loader_types = set()
|
||||
if prompt_data:
|
||||
for ndata in prompt_data.values():
|
||||
if isinstance(ndata, dict):
|
||||
ct = ndata.get('class_type', '')
|
||||
all_types.add(ct)
|
||||
ct_lower = ct.lower()
|
||||
if any(k in ct_lower for k in ['checkpoint', 'unet', 'diffusion', 'model', 'loader']):
|
||||
loader_types.add(ct)
|
||||
if workflow_data and 'nodes' in workflow_data:
|
||||
for node in workflow_data['nodes']:
|
||||
if isinstance(node, dict):
|
||||
nt = node.get('type', '')
|
||||
all_types.add(nt)
|
||||
nt_lower = nt.lower()
|
||||
if any(k in nt_lower for k in ['checkpoint', 'unet', 'diffusion', 'model', 'loader']):
|
||||
loader_types.add(nt)
|
||||
print(f"NO MODELS: {basename}")
|
||||
if loader_types:
|
||||
print(f" Loader-like types: {sorted(loader_types)}")
|
||||
else:
|
||||
print(f" ALL types: {sorted(all_types)}")
|
||||
except Exception as e:
|
||||
error_count += 1
|
||||
print(f"ERROR: {basename}: {type(e).__name__}: {e}")
|
||||
|
||||
print(f"\n=== SUMMARY: {ok_count} OK, {no_model_count} no models, {no_metadata_count} no metadata, {error_count} errors ===")
|
||||