Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e20f6523d9 | ||
|
|
d7fde3cce4 | ||
|
|
bf0edbabc9 | ||
|
|
ed78a1bf05 | ||
|
|
698cd7b725 | ||
|
|
d93c2713d5 | ||
|
|
dc971491d1 | ||
|
|
f5391da99a | ||
|
|
539828c8af | ||
|
|
16192ad6dd | ||
|
|
4dad2816d0 | ||
|
|
d1967d8395 | ||
|
|
ad1a4290bc | ||
|
|
e800b272cc | ||
|
|
4b93b7902d | ||
|
|
04808107c2 | ||
|
|
376e973ba0 | ||
|
|
0e4ca673fc | ||
|
|
70dc0e38e0 | ||
|
|
0297da28e6 | ||
|
|
f72bbc35cd | ||
|
|
052b88c33f | ||
|
|
6d6f09f82d | ||
|
|
0239663a38 | ||
|
|
958658f2c3 | ||
|
|
186a4fc7e4 | ||
|
|
2de7c3c9a3 | ||
|
|
55b6f2f94e | ||
|
|
a1c3b59bad | ||
|
|
3342d843e5 | ||
|
|
482f5c182d | ||
|
|
88dadfd4d5 | ||
|
|
e4868e1ea1 | ||
|
|
30246eb831 | ||
|
|
c97c290dba | ||
|
|
2da9b2813b | ||
|
|
aadb396151 | ||
|
|
96c9248135 | ||
|
|
695d7421d4 | ||
|
|
9d8137281e | ||
|
|
546b2f697b | ||
|
|
2d262999a3 | ||
|
|
e36d0fb15f | ||
|
|
d92a6c1872 | ||
|
|
67df4c6e53 | ||
|
|
e08d18c783 | ||
|
|
769d40f9f5 | ||
|
|
eef07948ac | ||
|
|
bf847e9639 | ||
|
|
39c8b5f3b8 | ||
|
|
cf810ca921 | ||
|
|
422607ec8d | ||
|
|
f9e26c8bbd | ||
|
|
be52d65de9 | ||
|
|
1d6021a916 | ||
|
|
6f0ac2674b | ||
|
|
6ba1f3f346 | ||
|
|
27ab751796 | ||
|
|
e2a9b25978 | ||
|
|
9b8016821c | ||
|
|
4811f21255 | ||
|
|
ca645721ec | ||
|
|
457e137b4c | ||
|
|
603c34d601 | ||
|
|
4fae27a6dd | ||
|
|
55a2fd64c9 | ||
|
|
5450682d44 | ||
|
|
d424f67948 | ||
|
|
838122ae67 | ||
|
|
e269117080 | ||
|
|
8910544eba | ||
|
|
9243d704ac | ||
|
|
e9981c1ee7 | ||
|
|
7c25eaeb95 | ||
|
|
d8d96e549b | ||
|
|
5d64bb2395 | ||
|
|
877727695d | ||
|
|
64119e6c90 | ||
|
|
6d5a1f4669 | ||
|
|
8ac04725c9 | ||
|
|
ef0f072891 | ||
|
|
985de6102e | ||
|
|
ecdf1e0995 | ||
|
|
39575f137c | ||
|
|
e993546fa4 | ||
|
|
ce12566998 | ||
|
|
c61dcaad2c | ||
|
|
1ba2d214f6 | ||
|
|
473d96084c |
@@ -0,0 +1,15 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: franckyb # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
polar: # Replace with a single Polar username
|
||||
buy_me_a_coffee: # Replace with a single Buy Me a Coffee username
|
||||
thanks_dev: # Replace with a single thanks.dev username
|
||||
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
|
||||
@@ -0,0 +1,20 @@
|
||||
name: Publish to Comfy registry
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
paths:
|
||||
- "pyproject.toml"
|
||||
|
||||
jobs:
|
||||
publish-node:
|
||||
name: Publish Custom Node to registry
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v4
|
||||
- name: Publish Custom Node
|
||||
uses: Comfy-Org/publish-node-action@main
|
||||
with:
|
||||
personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
|
||||
@@ -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,37 +1,118 @@
|
||||
# ComfyUI Prompt Manager
|
||||
## A comprehensive prompt toolkit for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) — Save, Generate, and Extract prompts with full LoRA support.
|
||||
|
||||
A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) for organizing, generating, and enhancing prompts using local llama.cpp models with vision analysis support.
|
||||
A complete prompt management solution featuring three core capabilities:
|
||||
|
||||
(**Llama.cpp needs to be installed and accessible from command prompt.**)
|
||||
**Prompt Manager** — Save and organize prompts with categories, simple UI with minimal feature.
|
||||
|
||||
**Prompt Manager Advanced** — 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. Will also remap Loras if path differs.
|
||||
|
||||
**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 and LoRA configurations from existing images, videos, or JSON workflow files. Will extract first frame from any video. Automatically parses embedded metadata and outputs active LoRA as Lora stacks. When used in conjunction with Prompt Manager Advanced, Loras will be automatically found if available, regardless of path. For those that aren't, right click offers the option to look for them on Civitai.
|
||||
___
|
||||
|
||||
<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 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>
|
||||
|
||||
### 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 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
|
||||
- **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
|
||||
|
||||
|
||||
### Prompt Apply LoRA:
|
||||
- **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
|
||||
- **JSON Workflow Support**: Browse and load JSON workflow files directly to extract prompts and LoRA configurations
|
||||
- **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 extraction from CLIP Text Encode, various sampler nodes, and LoRA stackers including Power Lora Loader
|
||||
- **Preview in Manager**: View extracted data and repathed loras using Manager Advanced.
|
||||
|
||||
### 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
|
||||
- **Automatic Server Management**: Starts/stops llama.cpp server as needed
|
||||
- **Smart Model Selection**: Auto-selects appropriate model (vision or text) based on mode
|
||||
- **Model Preferences**: Set preferred models in ComfyUI Settings for automatic selection
|
||||
- **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 based on mode, using mmproj-based vision detection.
|
||||
|
||||
### Prompt Generator Options
|
||||
- **Model Selection**: Choose from local models or download Qwen3 (1.7B/4B/8B) and Qwen3VL (4B/8B) 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
|
||||
- **Context Size**: Adjustable context window (512-32768 tokens)
|
||||
- **LLM Parameters**: Fine-tune temperature, top_k, top_p, min_p, repeat_penalty
|
||||
- **Custom Instructions**: Override default system prompt for different enhancement styles
|
||||
- **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.
|
||||
|
||||
### Preference Options
|
||||
- Set choices for prefered Model for both base mode and vision 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.
|
||||
- **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.
|
||||
|
||||
### Save Video H264/H265
|
||||
- **Codec Selection**: Choose between H.264 (8-bit, better compatibility) or H.265/HEVC (10-bit, better compression and gradients)
|
||||
- **Chroma Subsampling**: Select yuv420 (most compatible), yuv422 (better for video editing), or yuv444 (best color, no chroma loss)
|
||||
- **Quality Control**: Constant Rate Factor (CRF) from 0-51 for fine-tuned quality vs file size balance
|
||||
- **Preview Mode**: Quick preview encoding to temp folder without saving to output
|
||||
- **Save Latent**: Optionally save the latent alongside the video for later experimentation without regeneration
|
||||
- **Audio Support**: Preserves audio from VIDEO input with proper sync
|
||||
- **Workflow Metadata**: Embeds full workflow metadata in MP4 (unlike VideoHelperSuite which strips it from audio clips)
|
||||
- **Browser Preview**: Automatically generates browser-compatible preview for H.265 + yuv422/444 combinations
|
||||
|
||||
### Animated Latent Preview
|
||||
- **Video Sampling Preview**: Display animated previews during KSampler execution for video models
|
||||
- **TAESD Support**: Works with both Latent2RGB and TAESD preview methods (including high-quality video TAESD)
|
||||
- **Auto Frame Rate**: Automatically detects optimal playback rate based on video model (Wan, Mochi, LTXV, HunyuanVideo, etc.)
|
||||
- **Manual Rate Override**: Optional playback rate override in preferences
|
||||
- **VHS Compatible**: Automatically defers to VideoHelperSuite if installed to avoid conflicts
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -44,17 +125,21 @@ A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) for organ
|
||||
```bash
|
||||
git clone https://github.com/FranckyB/ComfyUI-Prompt-Manager.git
|
||||
```
|
||||
|
||||
3. Install dependencies:
|
||||
```bash
|
||||
cd ComfyUI-Prompt-Manager
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
4. Install llama.cpp. It can be found here: [llama.cpp install](https://github.com/ggml-org/llama.cpp/blob/master/docs/install.md)
|
||||
|
||||
5. If you have them, place your .gguf models in the models/gguf folder. (Create folder if not present)
|
||||
|
||||
4. Install [llama.cpp](https://github.com/ggml-org/llama.cpp/tree/master)
|
||||
Windows:
|
||||
```bash
|
||||
winget install llama.cpp
|
||||
```
|
||||
Linux:
|
||||
```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.
|
||||
|
||||
6. Restart ComfyUI
|
||||
|
||||
@@ -67,6 +152,33 @@ A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) for organ
|
||||
3. **Choose a Prompt**: Select a saved prompt from the name dropdown
|
||||
4. **Connect prompt output**: Connect Prompt Manager output to your clip text encode node.
|
||||
|
||||
### Prompt Manager Advanced
|
||||
|
||||
1. **Add the Node**: Add Node → Prompt Manager → Prompt Manager Advanced
|
||||
2. **Connect LoRA Stackers**: Connect LoRA stacker nodes (e.g., from LoRA Manager) to `lora_stack_a` and/or `lora_stack_b` inputs
|
||||
3. **View LoRA Tags**: Connected LoRAs appear as clickable tags showing name and strength
|
||||
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
|
||||
|
||||
### Apply LoRA Stack
|
||||
|
||||
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
|
||||
|
||||
### Prompt Extractor
|
||||
|
||||
1. **Add the Node**: Add Node → Prompt Manager → Prompt Extractor
|
||||
2. **Load Media**: Select an image or video from your input folder or use the upload button to access file from anywhere.
|
||||
3. **JSON Workflows**: Support extracting from JSON, by importing workflow files directly using the upload button.
|
||||
4. **Extract Data**: The node automatically extracts prompts, LoRAs, and trigger words from embedded metadata
|
||||
5. **View Results**: Extracted positive/negative prompts display in the text outputs, LoRA stacks output as LORA_STACK
|
||||
6. **Use with Manager**: Connect the LoRA stack outputs to Prompt Manager Advanced to view and save the extracted configuration
|
||||
|
||||
### Prompt Generator
|
||||
|
||||
@@ -77,43 +189,73 @@ A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) for organ
|
||||
- "Analyze Image" - Generate detailed image descriptions
|
||||
- "Analyze Image with Prompt" - Analyze images with custom instructions
|
||||
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
|
||||
|
||||
**Advanced Usage**:
|
||||
1. **Add the Options Node**: Add Node → Prompt Generator Options
|
||||
2. **Connect Options**: Connect the options node to the Prompt Generator Options input
|
||||
3. **Select from available models**: Select from models found in your modeld\gguf folder. Qwen models will be available to download.
|
||||
4. **Adjust settings**: Adjust LLM parameters (temperature, top_k, etc.)
|
||||
5. **Customize LLM**: Customize the default LLM instructions to modify the responses llama returns.
|
||||
3. **Analyze multiple images**: Connect up to 4 additional images, for a total of 5.
|
||||
4. **Select from available models**: Select from models found in your models\gguf folder. Qwen models will be available to download.
|
||||
5. **Adjust settings**: Adjust LLM parameters (temperature, top_k, etc.)
|
||||
6. **Customize LLM**: Customize the default LLM instructions to modify the responses llama returns.
|
||||
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)
|
||||
- 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
|
||||
- Downloaded models are also placed in this folder.
|
||||
|
||||
**Model Preferences**:
|
||||
- Set preferred models in ComfyUI Settings → Prompt Manager → Model Preferences
|
||||
- **Preferred Base Model**: Used for "Enhance User Prompt" mode (text-only models)
|
||||
- **Preferred Vision Model**: Used for "Analyze Image" modes (Qwen3VL models)
|
||||
- Leave empty to auto-select smallest available model
|
||||
- Changes are saved automatically in ComfyUI settings
|
||||
**Preferences**:
|
||||
Preference settings can be found in ComfyUI Settings → Prompt Manager
|
||||
- **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 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)
|
||||
|
||||
### Save Video H264/H265
|
||||
|
||||
1. **Add the Node**: Add Node → Prompt Manager → Save Video H264/H265
|
||||
2. **Connect VIDEO**: Connect a VIDEO output (e.g., from VAE Decode for video models)
|
||||
3. **Choose Codec**: Select h264 for compatibility or h265 for better quality/compression
|
||||
4. **Set Quality**: Adjust CRF (18-23 recommended for high quality, lower = better quality but larger files)
|
||||
5. **Chroma Options**: Use yuv420 for maximum compatibility, yuv444 for best color preservation
|
||||
6. **Save Latent**: Connect a LATENT input and enable "save_latent" to save the latent alongside your video
|
||||
7. **Preview Mode**: Set "save" to false for quick preview encoding without saving to output folder
|
||||
|
||||
### Animated Latent Preview
|
||||
|
||||
1. **Enable in Settings**: Go to ComfyUI Settings → Prompt Manager → 5. Video Sampling
|
||||
2. **Toggle On**: Enable "Display animated previews when sampling"
|
||||
3. **Optional Rate**: Set "Playback rate override" to force a specific FPS (0 = auto-detect from model)
|
||||
4. **Run Video Workflow**: During KSampler execution, you'll see an animated preview of the video being generated
|
||||
5. **Works with TAESD**: Enable TAESD in ComfyUI preview settings for higher quality previews
|
||||
|
||||
**Note**: If VideoHelperSuite is installed and enabled, its latent preview takes priority to avoid conflicts.
|
||||
|
||||
## 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)
|
||||
|
||||
## Troubleshooting
|
||||
@@ -142,8 +284,198 @@ A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) for organ
|
||||
**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.
|
||||
|
||||
**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 1.17.5
|
||||
- **Browser Context Menu Enhancements**
|
||||
- Added "Delete 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 Strenght 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 Worfklow.
|
||||
- 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.)
|
||||
- Visual LoRA tags showing name and editable strength values
|
||||
- Toggle LoRAs on/off by clicking tags
|
||||
- Save LoRA configurations alongside prompts
|
||||
- Override mode to ignore connected inputs and use saved presets
|
||||
- Merge mode combines connected LoRAs with saved presets
|
||||
- Missing LoRA detection with visual warnings
|
||||
- Integration with LoRA Manager for hover previews
|
||||
- **New Node: Apply LoRA Stack** - Simple node to apply LORA_STACK to model/clip
|
||||
- Categories and prompts now display in alphabetical order
|
||||
- Fixed dropdown refresh after saving prompts
|
||||
|
||||
### Version 1.8.3
|
||||
- Added option to leave Llama server running when closing ComfyUI.
|
||||
|
||||
### Version 1.8.2
|
||||
- Added custom model path preference and enhance model management
|
||||
|
||||
### Version 1.8.1
|
||||
- Added option to set a custom Llama path in preferences, for those that have specific installs.
|
||||
|
||||
### Version 1.8.0
|
||||
- Added support for Qwen3VL Thinking model variants, with download options thru the Generator Options node.
|
||||
- Model manager now searches for relevant `mmproj` files using model-name components for more reliable vision-model linking.
|
||||
- Detailed console output options (debug logging)
|
||||
- `enable_thinking` toggle to enable/disable the model's reasoning/thinking mode.
|
||||
- Options node now accepts multiple images for analysis.
|
||||
- Better Llama shutdown behavior to force-close the server when Comfy exits.
|
||||
- Uses model-reported sampling params by default when available; the Options node can override them per-parameter.
|
||||
- Moved preference API endpoints and cache handling into `model_manager.py` for cleaner management and persistence.
|
||||
|
||||
### Version 1.7.0
|
||||
- Added three-mode prompt generator: "Enhance User Prompt", "Analyze Image", "Analyze Image with Prompt"
|
||||
- Enhanced vision model workflow with dedicated image analysis modes
|
||||
@@ -152,7 +484,7 @@ A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) for organ
|
||||
- Added automatic model preference management (separate settings for base and vision models)
|
||||
- Improved model selection with preference fallback to smallest model
|
||||
- Filtered mmproj files from model selection dropdowns
|
||||
- All preferences stored in ComfyUI settings for persistence across updates
|
||||
- Model preferences stored in ComfyUI settings for persistence across updates
|
||||
|
||||
### Version 1.6.0
|
||||
- Added Qwen3VL vision model support for image analysis
|
||||
@@ -165,8 +497,8 @@ A custom node for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) for organ
|
||||
- Fixed multiple directory support for model search (gguf + LLM folders)
|
||||
|
||||
### Version 1.5.1
|
||||
- LLM output remains avaiable when use llm is off. So it can be edited
|
||||
- Improved Caching detection, any change to options will be detected and force a new ouput
|
||||
- LLM output remains available when use_llm is off, so it can be edited.
|
||||
- Improved caching detection: any change to options will be detected and force a new output.
|
||||
- Improved some UI quirks
|
||||
|
||||
### Version 1.5.0
|
||||
|
||||
@@ -2,27 +2,50 @@
|
||||
ComfyUI Prompt Manager - A simple custom node for saving and reusing prompts
|
||||
A prompt management system for ComfyUI with LLM input support
|
||||
"""
|
||||
__version__ = "1.5.1"
|
||||
__version__ = "1.17.5"
|
||||
__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 .prompt_apply_lora import PromptApplyLora
|
||||
from .prompt_extractor import PromptExtractor
|
||||
from .model_manager import get_local_models
|
||||
from .save_video_h26x import SaveVideoH26x, LoadLatentFile, MonoToStereo, GetVideoComponentsPlus
|
||||
from server import PromptServer
|
||||
|
||||
# Initialize latent preview hook (with VHS conflict detection)
|
||||
from .latent_preview import install_latent_preview_hook
|
||||
install_latent_preview_hook()
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"PromptManager": PromptManager,
|
||||
"PromptManagerAdvanced": PromptManagerAdvanced,
|
||||
"PromptGenerator": PromptGenerator,
|
||||
"PromptGenOptions": PromptGenOptions
|
||||
"PromptGenOptions": PromptGenOptions,
|
||||
"PromptApplyLora": PromptApplyLora,
|
||||
"PromptExtractor": PromptExtractor,
|
||||
"SaveVideoH26x": SaveVideoH26x,
|
||||
"LoadLatentFile": LoadLatentFile,
|
||||
"AudioMonoToStereo": MonoToStereo,
|
||||
"GetVideoComponentsPlus": GetVideoComponentsPlus,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"PromptManager": "Prompt Manager",
|
||||
"PromptManagerAdvanced": "Prompt Manager Advanced",
|
||||
"PromptGenerator": "Prompt Generator",
|
||||
"PromptGenOptions": "Prompt Generator Options"
|
||||
"PromptGenOptions": "Prompt Generator Options",
|
||||
"PromptApplyLora": "Prompt Apply LoRA",
|
||||
"PromptExtractor": "Prompt Extractor",
|
||||
"SaveVideoH26x": "Save Video H264/H265",
|
||||
"LoadLatentFile": "Load Latent File",
|
||||
"AudioMonoToStereo": "Audio Mono to Stereo",
|
||||
"GetVideoComponentsPlus": "Get Video Components+",
|
||||
}
|
||||
|
||||
|
||||
WEB_DIRECTORY = "./js"
|
||||
|
||||
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', 'WEB_DIRECTORY']
|
||||
|
||||
@@ -1,24 +1,4 @@
|
||||
{
|
||||
"Character": {
|
||||
"Cyberpunk Hacker Elite": {
|
||||
"prompt": "A skilled cyberpunk hacker sitting in a dimly lit apartment surrounded by multiple holographic screens displaying code and data streams, wearing tactical tech-wear with embedded LED strips and circuit patterns, augmented reality glasses with information overlays, cybernetic arm implants with exposed mechanical components, messy workstation with scattered computer parts and energy drink cans, large window showing dystopian megacity skyline with towering skyscrapers covered in neon advertisements and holographic billboards, heavy rain creating atmospheric reflections, purple and cyan neon color palette, volumetric fog and light rays, highly detailed futuristic technology, photorealistic rendering, cyberpunk 2077 aesthetic, moody atmospheric lighting, 8k ultra detailed"
|
||||
},
|
||||
"Epic Fantasy Warrior": {
|
||||
"prompt": "A powerful fantasy warrior standing in a heroic pose on a battlefield at dusk, wearing intricately detailed plate armor with ornate engravings and battle-worn scratches, muscular athletic build with defined features, holding a legendary glowing sword with runes etched along the blade, flowing cape billowing in the wind, dramatic cinematic lighting with rays of sunlight breaking through storm clouds, particles of dust and embers floating in the air, photorealistic rendering with exceptional attention to material details including metallic reflections on armor, leather straps and buckles, war paint on face, intense determined expression, epic fantasy art style, 8k ultra high resolution, masterpiece quality"
|
||||
},
|
||||
"Futuristic Sci-Fi Explorer": {
|
||||
"prompt": "A lone futuristic explorer standing on the edge of an alien cliff overlooking a vast extraterrestrial landscape, wearing an advanced high-tech environmental suit with glowing blue energy lines and holographic display panels, sleek helmet with transparent visor showing determined face, multiple utility packs and scientific equipment attached to suit, alien planet with multiple moons visible in the purple-tinted sky, bioluminescent alien flora scattered across rocky terrain, dramatic volumetric lighting with atmospheric fog, neon accents and technological details, sense of wonder and discovery, photorealistic sci-fi concept art style, cinematic composition, 8k resolution, highly detailed textures on suit materials and alien environment"
|
||||
},
|
||||
"Mystical Elven Mage": {
|
||||
"prompt": "An elegant elven sorcerer with flowing silver hair and luminescent purple eyes, wearing elaborate flowing robes made of enchanted fabric with intricate magical runes and celestial patterns, holding an ancient wooden staff topped with a glowing crystal, standing in a mystical forest clearing surrounded by floating magical orbs and swirling ethereal energy, ancient stone ruins covered in moss and glowing elvish inscriptions in background, fireflies and magical particles dancing through the air, moonlight filtering through dense canopy creating dappled light patterns, fantasy illustration style with painterly quality, rich jewel tones and magical bioluminescence, highly detailed character design, masterpiece quality, 8k resolution"
|
||||
},
|
||||
"Noble Medieval Knight": {
|
||||
"prompt": "A distinguished medieval knight in full ceremonial plate armor standing in the grand hall of a castle, armor polished to a mirror shine with gold inlay and family crest emblazoned on chest plate, red velvet cape with golden trim, holding ornate longsword point-down in formal stance, helmet tucked under arm revealing weathered noble face with graying beard, stone castle interior with tall Gothic arched windows, sunlight streaming through stained glass creating colorful patterns on floor, heraldic banners hanging from walls, torch sconces providing warm ambient lighting, sense of honor and nobility, historical accuracy in armor design and architecture, oil painting aesthetic with rich colors, highly detailed, 4k quality"
|
||||
},
|
||||
"Post-Apocalyptic Survivor": {
|
||||
"prompt": "A rugged post-apocalyptic survivor standing among ruins of a destroyed city, wearing makeshift armor cobbled together from scavenged materials including leather, metal plates, and tactical gear, face covered with weathered gas mask with cracked lenses, carrying a modified rifle and worn backpack full of supplies, background showing crumbling skyscrapers overgrown with vegetation, abandoned vehicles rusted and covered in vines, dramatic overcast sky with sun breaking through clouds, dust particles and debris floating in air, desaturated color palette with touches of rust orange and olive green, gritty realistic style, highly detailed weathering and wear on all materials, cinematic composition, 4k photorealistic quality"
|
||||
}
|
||||
},
|
||||
"Composition": {
|
||||
"Aerial Bird's Eye View": {
|
||||
"prompt": "Dramatic overhead composition shot from directly above subject, unique bird's eye perspective offering unusual and striking viewpoint, flattened perspective creating abstract qualities and geometric patterns, symmetry and patterns visible from above, sense of scale with subject appearing small against larger environment, drone photography aesthetic with perfect stability, organized chaos of urban patterns or natural formations, top-down view revealing hidden relationships and structures, professional aerial photography with exceptional detail, sharp focus across entire frame, innovative perspective creating wow factor, cinematic quality, 8k ultra high resolution, perfect exposure and color balance"
|
||||
@@ -76,139 +56,5 @@
|
||||
"Underwater Lost City": {
|
||||
"prompt": "An ancient sunken city deep beneath the ocean surface, classical Greek or Roman architecture colonized by colorful coral and marine life, crumbling marble columns and statues covered in barnacles and swaying sea kelp, schools of tropical fish swimming through broken archways, rays of sunlight penetrating from surface creating dramatic volumetric lighting through the water, particles of sediment floating in currents, giant sea turtles and manta rays gliding past ruins, preserved mosaics and frescoes still visible on walls, sense of lost grandeur and the passage of time, turquoise and deep blue water with caustic light patterns on surfaces, highly detailed underwater environment with accurate water physics and light scattering, photorealistic quality, 8k resolution"
|
||||
}
|
||||
},
|
||||
"Illustrious": {
|
||||
"Anime Girl Portrait": {
|
||||
"prompt": "1girl. A beautiful anime girl gazing directly at the viewer with a gentle smile and soft expression on her face. Her long flowing hair frames delicate features. beautiful detailed eyes, long hair, flowing hair, hair between eyes, looking at viewer, slight smile, soft expression, detailed face, smooth skin, delicate features, jewelry, earrings, necklace, upper body, portrait, depth of field, bokeh, soft lighting, rim lighting, cinematic lighting, anime style, illustration, detailed background, blurred background, masterpiece"
|
||||
},
|
||||
"Beach Swimsuit Summer": {
|
||||
"prompt": "1girl. A carefree girl enjoys a perfect summer day at the beach. Ocean waves lap at the shore behind her as she stands with a bright smile under the sunny sky. Water droplets glisten on her skin in the warm sunlight. bikini, swimsuit, beach, ocean, sea, waves, shore, sand, blue sky, summer, sunny, sunlight, lens flare, beach umbrella, palm tree, standing, hand on hip, wet, wet skin, water droplets, smile, happy, cheerful, straw hat, sun hat, sunglasses, long hair, ponytail, side-tie bikini bottom, frills, ribbon, beautiful detailed face, depth of field, blurry background, bokeh, bright colors, vibrant, warm colors, anime style, masterpiece"
|
||||
},
|
||||
"Café Reading Books": {
|
||||
"prompt": "1girl. A peaceful scene of a girl absorbed in reading at a quiet café. Soft window light illuminates her book as steam rises gently from her cup of tea. The cozy atmosphere and comfortable setting create a perfect moment of tranquil relaxation. sitting, chair, table, café, coffee shop, indoor, window, window light, sunlight, soft lighting, warm lighting, cozy atmosphere, reading, book, holding book, open book, coffee cup, teacup, steam, casual clothes, sweater, cardigan, long sleeves, skirt, pantyhose, sitting cross-legged, relaxed, calm expression, gentle smile, long hair, side ponytail, hair ornament, bookshelf, books, plant, potted plant, depth of field, blurry background, bokeh, peaceful, comfortable, slice of life, anime style, masterpiece"
|
||||
},
|
||||
"Cyberpunk Street Scene": {
|
||||
"prompt": "1girl. A lone figure stands in a rain-soaked cyberpunk street at night. Neon signs reflect off wet pavement while holographic displays flicker in the background. The cityscape towers above with its maze of skyscrapers and glowing advertisements. cyberpunk, neon lights, night, rain, wet, reflections, holographic display, hologram, cyber wear, mechanical parts, augmentation, headphones, hood, hood up, jacket, tech wear, city lights, cityscape, skyscraper, neon sign, japanese text, night sky, depth of field, blurry background, bokeh, rim lighting, ambient lighting, atmospheric, moody, cinematic angle, wide shot, street, alley, puddle, anime style, masterpiece"
|
||||
},
|
||||
"Dragon Girl Fantasy": {
|
||||
"prompt": "1girl. A powerful dragon girl sits regally upon her throne within her treasure-filled lair. Flames and embers dance around her as her wings spread majestically. Her scales shimmer in the dramatic lighting, displaying both her fierce power and noble bearing. dragon girl, dragon horns, horns, dragon tail, tail, dragon wings, wings, scales, pointy ears, elf ears, long hair, very long hair, silver hair, white hair, red eyes, slit pupils, fangs, sharp teeth, claws, fantasy, armor, scale armor, dragon scale armor, dragon themed, castle, throne, dragon hoard, treasure, gold, gems, crystals, cave, lair, dramatic lighting, volumetric lighting, fire, flames, embers, particles, epic, powerful, regal, anime style, detailed scales, masterpiece"
|
||||
},
|
||||
"Elegant Fantasy Princess": {
|
||||
"prompt": "1girl. A regal princess sits gracefully upon her ornate throne in the grand castle hall. Sunlight streams through magnificent stained glass windows, illuminating her elegant gown and sparkling jewelry. She embodies nobility and grace with her gentle smile and refined posture. princess, royalty, crown, tiara, jewelry, ornate jewelry, necklace, earrings, bracelet, elegant dress, ballgown, frills, lace trim, ribbon, puffy sleeves, long sleeves, detached sleeves, white gloves, long gloves, very long hair, wavy hair, blonde hair, blue eyes, detailed eyes, gentle smile, graceful, sitting, throne, castle interior, grand hall, chandelier, stained glass, window, sunlight, light rays, volumetric lighting, depth of field, bokeh, detailed background, fantasy, medieval, regal, noble, anime style, masterpiece"
|
||||
},
|
||||
"Fantasy Battle Scene": {
|
||||
"prompt": "multiple girls, multiple boys. An epic battle scene unfolds with multiple warriors locked in intense combat. Fighters strike dynamic poses with weapons raised and magic crackling through the air. Hair and capes billow in the wind as debris flies through the scene. dynamic pose, action scene, fighting stance, floating hair, motion blur, motion lines, dramatic angle, low angle, dutch angle, wielding sword, magic spell, casting magic, glowing weapon, energy effects, particle effects, debris, dust cloud, destruction, epic scene, cinematic composition, volumetric lighting, dramatic lighting, lens flare, depth of field, fantasy armor, detailed armor, cape, flowing clothes, wind, anime style, masterpiece"
|
||||
},
|
||||
"Gothic Lolita Fashion": {
|
||||
"prompt": "1girl. An elegant gothic lolita stands before a cathedral in her elaborate black dress. She holds a single red rose with pale graceful hands. The dramatic lighting filtering through stained glass creates an atmosphere of dark beauty and refined elegance. gothic lolita, lolita fashion, gothic dress, black dress, frills, lace, ruffles, ribbon, bow, puffy sleeves, long sleeves, detached sleeves, headdress, mini crown, cross, cross necklace, choker, black thighhighs, platform footwear, parasol, lace parasol, very long hair, twin tails, drill hair, curly hair, black hair, red eyes, pale skin, elegant, graceful pose, standing, rose, red rose, holding rose, church, cathedral, stained glass, gothic architecture, dim lighting, dramatic lighting, depth of field, detailed background, anime style, masterpiece"
|
||||
},
|
||||
"Idol Performance Stage": {
|
||||
"prompt": "1girl. An energetic idol performs on stage before a cheering crowd. Colorful spotlights illuminate her as she sings and dances with boundless enthusiasm. Sparkles and glitter fill the air as she strikes a dynamic pose with her microphone. idol, stage outfit, frills, lace, ribbon, bow, gloves, white gloves, microphone, holding microphone, singing, performing, stage, concert, stage lights, spotlights, colorful lighting, dynamic lighting, dramatic lighting, audience, crowd, cheering, energetic, dynamic pose, dancing, motion blur, sparkles, glitter, star \\(symbol\\), heart \\(symbol\\), twin tails, very long hair, gradient hair, colorful hair, bright colors, vibrant colors, smile, wink, one eye closed, cheerful, happy, full body, depth of field, anime style, masterpiece"
|
||||
},
|
||||
"Kimono Traditional Japan": {
|
||||
"prompt": "1girl. An elegant woman in traditional kimono walks gracefully through a beautiful Japanese garden. Autumn leaves drift down around her as koi swim in the pond beside a stone path. The golden hour light creates a warm and culturally rich atmosphere. kimono, japanese clothes, traditional clothes, obi, sash, wide sleeves, long sleeves, floral print, flower pattern, hair ornament, hair flower, kanzashi, long hair, black hair, brown hair, updo, hair bun, elegant, graceful, standing, walking, outdoor, japanese garden, garden, stone path, bridge, pond, koi, water, trees, maple tree, autumn leaves, red leaves, falling leaves, torii gate, shrine, lantern, paper lantern, sunset, golden hour, warm lighting, soft lighting, depth of field, blurry background, traditional, cultural, anime style, masterpiece"
|
||||
},
|
||||
"Magical Girl Transformation": {
|
||||
"prompt": "1girl. A magical girl undergoes her transformation sequence in a dazzling display of light and sparkles. Ribbons and magical particles swirl around her as her elaborate costume materializes. She strikes a heroic pose with outstretched hand against a radiant starburst background. magical girl, transformation sequence, sparkles, glowing, light particles, ribbon, frills, lace, detailed outfit, elaborate costume, twin tails, very long hair, gradient hair, multicolored hair, colorful, vibrant colors, bright colors, star \\(symbol\\), heart \\(symbol\\), dynamic pose, outstretched hand, raised hand, full body, floating, levitating, white background, gradient background, starburst background, bloom effect, light rays, god rays, anime style, masterpiece"
|
||||
},
|
||||
"Maid Cafe Waitress": {
|
||||
"prompt": "1girl. A cheerful maid waitress serves customers at a cozy cafe with a warm welcoming smile. Soft sunlight filters through the windows as she carries a tray with practiced grace. Her frilly uniform and happy expression create an inviting atmosphere. maid, maid headdress, maid apron, frills, lace, ribbon, bow, short sleeves, puffy sleeves, black dress, white apron, wrist cuffs, thighhighs, mary janes, holding tray, serving, indoor, cafe, detailed background, blurry background, depth of field, soft lighting, warm lighting, sunlight, window light, smiling, cheerful, happy, welcoming expression, looking at viewer, anime style, masterpiece"
|
||||
},
|
||||
"Samurai Warrior": {
|
||||
"prompt": "1boy. A skilled samurai warrior stands ready in a dynamic pose, hand on his katana. Cherry blossom petals swirl around him in the wind as the setting sun casts dramatic lighting across his detailed armor. His expression shows unwavering determination and honor. samurai, armor, japanese armor, shoulder armor, armored dress, hakama, hakama skirt, katana, sword, sheathed, holding sword, ponytail, long hair, black hair, serious expression, determined look, standing, dynamic pose, action pose, cherry blossoms, petals, falling petals, torii, shrine, japanese architecture, sunset, dramatic lighting, rim lighting, lens flare, depth of field, wind, dramatic angle, low angle, cinematic composition, anime style, detailed armor, masterpiece"
|
||||
},
|
||||
"School Uniform Casual": {
|
||||
"prompt": "1girl. A cheerful schoolgirl walks through the school grounds on a beautiful spring day. Cherry blossom petals dance in the wind around her as she carries her school bag. The sun shines warmly and her expression is gentle and happy. school uniform, serafuku, sailor collar, pleated skirt, short sleeves, long sleeves, cardigan, bow, bowtie, ribbon, neck ribbon, thighhighs, black thighhighs, loafers, bag, school bag, shoulder bag, standing, walking, outdoors, school, school building, cherry blossoms, falling petals, blue sky, clouds, sunlight, dappled sunlight, soft lighting, wind, wind lift, depth of field, blurry background, smile, happy, gentle expression, anime style, masterpiece"
|
||||
},
|
||||
"Shrine Maiden Miko": {
|
||||
"prompt": "1girl. A serene shrine maiden performs her duties at a peaceful shrine surrounded by nature. Dappled sunlight filters through the trees as cherry blossom petals gently fall around her. She holds a sacred paper charm with a gentle smile and peaceful expression. miko, shrine maiden, traditional clothes, japanese clothes, red hakama, hakama skirt, white kimono, wide sleeves, long sleeves, hair bow, red ribbon, hair tubes, long hair, black hair, brown hair, brown eyes, gentle smile, peaceful expression, holding ofuda, paper charm, shrine, torii gate, stone lantern, japanese architecture, outdoor, nature, forest, trees, sunlight, light rays, dappled sunlight, god rays, peaceful atmosphere, depth of field, soft lighting, cherry blossoms, petals, falling petals, anime style, masterpiece"
|
||||
},
|
||||
"Sleeping Bedroom Night": {
|
||||
"prompt": "1girl. A peaceful sleeping scene bathed in gentle moonlight streaming through the window. The girl rests quietly under soft covers with her hair spread across the pillow. Stars twinkle in the night sky visible through the curtains as she dreams peacefully. sleeping, lying, on side, on bed, bed, bedroom, pillow, blanket, sheet, under covers, pajamas, nightgown, sleepwear, closed eyes, peaceful expression, long hair, messy hair, hair over pillow, indoor, window, curtains, moonlight, night, night sky, stars, starry sky, moon, crescent moon, dim lighting, soft lighting, ambient lighting, calm atmosphere, quiet, serene, peaceful, plushie, stuffed toy, stuffed animal, depth of field, anime style, masterpiece"
|
||||
}
|
||||
},
|
||||
"Lighting": {
|
||||
"Cyberpunk Neon Atmosphere": {
|
||||
"prompt": "Vibrant cyberpunk neon lighting with dominant cyan, magenta, and purple color palette, multiple colored light sources creating complex overlapping shadows and color mixing, neon tubes and LED strips casting intense saturated light, strong rim lighting outlining subjects with colored glows, wet surfaces reflecting and multiplying light sources, volumetric fog and haze making light beams visible, high contrast between bright neon elements and deep dark shadows, futuristic atmospheric lighting with sci-fi mood, color temperature mixing cool blue neons with warm orange accents, Blade Runner inspired aesthetic, moody and atmospheric, cinematic lighting design, photorealistic rendering, 8k quality"
|
||||
},
|
||||
"Dramatic Rembrandt Lighting": {
|
||||
"prompt": "Classic Rembrandt studio lighting setup with strong directional key light at 45-degree angle creating distinctive triangle of light under eye on shadow side of face, deep rich shadows with subtle fill light preserving detail, high contrast ratio for dramatic mood, rim light separating subject from dark background, chiaroscuro technique emphasizing form and dimension through light and shadow, professionally controlled studio environment, classic portrait photography aesthetic, black background emphasizing subject, attention to catchlights in eyes, subtle hair light adding separation, timeless dramatic quality reminiscent of Dutch Golden Age paintings, medium format camera quality, tack-sharp focus, 4k resolution"
|
||||
},
|
||||
"Firelight and Shadows": {
|
||||
"prompt": "Warm intimate lighting from crackling fire as primary light source, rich orange and amber tones dancing across surfaces, dynamic moving shadows creating flickering atmospheric effect, high contrast with deep blacks in areas beyond firelight reach, sense of warmth and comfort, practical light source visible in scene showing glowing embers and flames, subsurface scattering on translucent objects near fire, traditional campfire or hearth setting, reminiscent of classical genre paintings, color temperature around 1800K for authentic firelight, soft smoky haze adding atmosphere, cozy intimate mood, photorealistic fire simulation, highly detailed, 4k quality"
|
||||
},
|
||||
"Golden Hour Magic": {
|
||||
"prompt": "Golden hour lighting during the last hour before sunset, warm golden and amber tones bathing entire scene in beautiful soft light, long dramatic shadows stretching across ground, sun low on horizon creating rim lighting that outlines subjects with glowing edges, soft diffused quality that enhances colors and reduces contrast, sky painted in gradients of gold, orange, pink, and purple, clouds illuminated from below with warm tones, perfect lighting conditions for photography with flattering warm color temperature around 3500K, atmospheric haze adding depth and dimension, lens flare and subtle bloom adding magical quality, professional landscape photography aesthetic, HDR processing for maximum dynamic range, masterpiece quality lighting, 8k resolution"
|
||||
},
|
||||
"Mystical Moonlight": {
|
||||
"prompt": "Ethereal moonlight illuminating scene with cool silvery-blue tones, full moon visible in clear night sky providing primary light source, soft shadows with blue-tinted quality, stars visible in background, atmospheric mist catching and scattering moonlight creating volumetric lighting effects, subtle bioluminescent elements adding touches of green and blue glow, romantic and magical atmosphere, cool color temperature around 4100K, high contrast between moonlit areas and deep shadows, sense of mystery and nocturnal beauty, long exposure photography aesthetic capturing movement of clouds, highly detailed night scene with proper exposure for nighttime conditions, cinematic quality, 8k resolution"
|
||||
},
|
||||
"Overcast Diffused Light": {
|
||||
"prompt": "Soft even illumination from completely overcast sky creating natural softbox effect, shadowless lighting with very gradual subtle transitions, muted desaturated color palette, cool color temperature around 6500K with slight blue-gray cast, perfect even exposure across entire scene, detail preserved in all areas, moody atmospheric quality, sense of calm or melancholy, ideal for showing texture and form without harsh shadows, professional product photography aesthetic, fog or mist adding layers of atmospheric perspective, minimalist Scandinavian lighting aesthetic, clean and modern feel, high dynamic range with subtle gradations, photorealistic rendering, 8k resolution"
|
||||
},
|
||||
"Soft Northern Window Light": {
|
||||
"prompt": "Beautiful soft natural light coming from large northern-facing window, gentle diffused illumination without harsh shadows or direct sunlight, even light distribution creating subtle gradations and soft wraparound lighting, cool color temperature around 5500K with slight blue bias, perfect for accurate color rendition, creates natural realistic appearance, soft shadows with gradual transitions, sense of calm and serenity, ideal for portraits and still life, professional photography studio aesthetic using natural light only, subtle environmental reflections adding fill light, maintains detail in both highlights and shadows, peaceful morning light quality, high dynamic range, 4k photographic quality"
|
||||
},
|
||||
"Volumetric God Rays": {
|
||||
"prompt": "Dramatic volumetric lighting with strong directional sunbeams breaking through clouds or canopy creating visible shafts of light, atmospheric perspective with dust particles, moisture, or fog making light beams clearly visible, high contrast between illuminated rays and darker surrounding areas, sense of divine or spiritual quality, particles floating through light beams catching illumination, depth and dimension created by layered light and shadow, cathedral-like quality to lighting, powerful emotional impact, reminiscent of classical religious paintings, physically accurate light scattering and atmospheric effects, subtle color gradation in light beams from warm to cool, cinematic composition, photorealistic rendering, 8k ultra quality"
|
||||
}
|
||||
},
|
||||
"Mood": {
|
||||
"Dark and Ominous": {
|
||||
"prompt": "Dark foreboding atmosphere with ominous threatening mood, deep shadows dominating composition with limited light sources, desaturated color palette with emphasis on blacks and dark grays, occasional blood red or sickly green accent colors, sense of danger and unease, heavy atmospheric fog or mist obscuring details, Gothic horror aesthetic, dramatic high contrast lighting, unsettling asymmetrical composition, inspired by horror film cinematography and dark fantasy art, volumetric shadows, psychological tension, photorealistic rendering with painterly qualities, 4k quality"
|
||||
},
|
||||
"Energetic and Vibrant": {
|
||||
"prompt": "High-energy dynamic atmosphere bursting with vitality and motion, saturated vibrant colors creating visual excitement, bold contrasts between warm and cool tones, sense of movement and activity throughout composition, dynamic lighting with multiple colorful sources, particles and elements in motion suggesting kinetic energy, fast-paced feeling with diagonal lines and angular composition, celebration of life and action, inspired by pop art and contemporary street photography, youthful exuberant quality, festival or carnival atmosphere, professional commercial photography aesthetic with punchy color grading, sharp details capturing peak moments, 8k ultra high resolution"
|
||||
},
|
||||
"Epic and Grandiose": {
|
||||
"prompt": "Monumental epic atmosphere emphasizing vast scale and dramatic spectacle, sweeping panoramic composition showcasing impressive scope, dramatic sky with storm clouds or spectacular sunset, towering mountains, massive architecture, or other elements dwarfing human scale, sense of awe and sublime beauty, inspired by romantic landscape painting and epic cinema, heroic quality with cinematic grandeur, professional landscape photography with maximum dynamic range, deep depth of field capturing detail from foreground to distant horizon, powerful emotional impact, larger-than-life presence, volumetric lighting with dramatic god rays, rich saturated colors or moody monochromatic palette, 8k ultra high resolution capturing every magnificent detail"
|
||||
},
|
||||
"Ethereal and Dreamlike": {
|
||||
"prompt": "Otherworldly ethereal atmosphere with dreamlike surreal quality, soft diffused lighting creating glowing luminous effect, pale pastel colors or monochromatic schemes, subtle gradients and smooth transitions, fog or mist creating atmospheric depth and mystery, sense of floating or weightlessness, influenced by symbolist painting and fine art photography, magical realism aesthetic, elements of fantasy and imagination, translucent overlapping layers, bokeh and soft focus creating painterly quality, gentle peaceful mood with touch of unreality, professional fine art composition, heavenly or celestial atmosphere, delicate beauty and fragility, museum quality presentation, 4k resolution with exceptional subtlety"
|
||||
},
|
||||
"Gritty and Raw": {
|
||||
"prompt": "Harsh gritty atmosphere emphasizing reality and unpolished authenticity, high contrast lighting with deep blacks and bright highlights, desaturated or monochromatic color palette, visible texture and grain adding tactile quality, urban decay or industrial elements, sense of struggle and perseverance, influenced by documentary photography and photojournalism, uncompromising realistic approach, environmental portraits showing character and history, weathered surfaces and worn materials, professional reportage aesthetic, honest unflinching perspective, dramatic shadows and harsh light, imperfections celebrated rather than hidden, strong emotional impact, cinematic noir quality, 4k resolution with sharp detail capturing every texture"
|
||||
},
|
||||
"Melancholic and Nostalgic": {
|
||||
"prompt": "Bittersweet melancholic atmosphere evoking memories and longing for the past, muted desaturated colors with vintage film aesthetic, soft diffused lighting creating dreamy quality, slight vignetting and faded appearance suggesting passage of time, autumnal or twilight color palette with browns, oranges, and muted blues, sense of solitude and quiet reflection, abandoned or weathered elements suggesting history, inspired by fine art photography and classical painting, emotional depth and introspective quality, gentle sadness mixed with beauty, analog film grain texture, soft focus areas creating romantic haze, timeless contemplative mood, 4k artistic quality"
|
||||
},
|
||||
"Mysterious and Enigmatic": {
|
||||
"prompt": "Mysterious atmospheric quality filled with intrigue and unanswered questions, strategic use of shadows and partial concealment, fog or mist obscuring details and creating layers of depth, cool color temperature with blues, purples, and teals, selective lighting revealing only portions of scene, sense of hidden secrets and untold stories, influenced by film noir and gothic romanticism, dramatic chiaroscuro lighting, silhouettes and backlighting creating ambiguity, professional cinematic atmosphere, elements of the unknown, otherworldly quality, photorealistic rendering with artistic interpretation, high contrast between light and dark areas, 8k resolution with exceptional atmospheric detail"
|
||||
},
|
||||
"Peaceful and Serene": {
|
||||
"prompt": "Calm peaceful atmosphere evoking tranquility and contentment, soft gentle lighting with harmonious balanced colors, pastel or muted earth tone palette, symmetrical or balanced composition creating visual harmony, natural elements like water or sky prominent, sense of stillness and timelessness, meditative quality, inspired by romantic landscape paintings and zen philosophy, warm and inviting feeling, perfect for relaxation and contemplation, subtle gradients and smooth transitions, professional fine art photography aesthetic, museum quality, 8k resolution"
|
||||
},
|
||||
"Warm and Inviting": {
|
||||
"prompt": "Cozy warm atmosphere radiating comfort and hospitality, golden hour lighting or warm interior illumination, rich warm color palette dominated by oranges, yellows, and earth tones, soft shadows creating gentle dimensionality, sense of home and belonging, intimate scale and human-friendly spaces, natural materials like wood and fabric prominent, influenced by lifestyle photography and Scandinavian hygge aesthetic, welcoming emotional quality, perfect for evoking feelings of safety and contentment, professional interior photography with careful attention to ambiance, subtle texture details, inviting composition encouraging viewer to enter scene, 4k quality with warm color grading"
|
||||
},
|
||||
"Whimsical and Playful": {
|
||||
"prompt": "Lighthearted whimsical atmosphere filled with joy and imagination, bright cheerful colors with unexpected combinations, playful composition with tilted angles or unusual perspectives, sense of fun and childlike wonder, elements of surprise and delight, influenced by children's book illustration and contemporary art, fantastical touches mixing reality with imagination, professional commercial photography with creative flair, bouncing light and colorful accents, informal spontaneous quality, sense of movement and energy, optimistic uplifting mood, creative use of props and staging, vibrant saturated colors, sharp focus on delightful details, 8k resolution with exceptional color accuracy and brightness"
|
||||
}
|
||||
},
|
||||
"Style": {
|
||||
"Cinematic Film Quality": {
|
||||
"prompt": "Cinematic film photography style with anamorphic lens characteristics, dramatic shallow depth of field with beautiful bokeh, professional color grading with teal and orange tones, subtle film grain texture, volumetric lighting with god rays and atmospheric haze, dynamic composition following rule of thirds, high contrast lighting with deep shadows and bright highlights, 2.39:1 aspect ratio letterbox framing, shot on ARRI Alexa 65, photorealistic rendering, 8k resolution, masterpiece quality with exceptional attention to lighting and atmosphere"
|
||||
},
|
||||
"Classic Oil Painting": {
|
||||
"prompt": "Traditional oil painting style in the manner of old masters, rich saturated colors with deep shadows and luminous highlights, visible brushwork with thick impasto in light areas and thin glazes in shadows, classical composition with careful attention to form and anatomy, chiaroscuro lighting technique, warm earth tone palette with selective use of vibrant colors, painted on linen canvas with visible texture, museum quality with craquelure aging effects, Renaissance and Baroque artistic influences, painterly realism, masterwork quality worthy of gallery exhibition"
|
||||
},
|
||||
"Concept Art Illustration": {
|
||||
"prompt": "Professional concept art illustration style used in AAA video game and film production, dynamic composition with strong focal point, atmospheric perspective with detailed foreground and painterly background, digital painting technique with custom brushes, strategic use of lighting to guide viewer's eye, color script with mood-appropriate palette, blend of realistic rendering and artistic interpretation, subtle texture overlays, clean lines with detailed callouts and annotations where needed, portfolio-quality artwork, 4k resolution optimized for production pipeline, industry-standard visual development artwork"
|
||||
},
|
||||
"Detailed Watercolor Art": {
|
||||
"prompt": "Professional watercolor painting technique with translucent layered washes, delicate color transitions and gradients, wet-on-wet blending creating soft atmospheric effects, strategic use of white space and paper texture showing through, detailed foreground elements with looser background washes, granulation and blooming effects in pigments, cold-press watercolor paper texture, artistic mastery of water control, luminous transparent colors, traditional botanical illustration precision combined with loose expressive passages, flowing organic shapes, high-end art print quality, 300 DPI resolution"
|
||||
},
|
||||
"Impressionist Painting": {
|
||||
"prompt": "Impressionist oil painting style reminiscent of Claude Monet and Pierre-Auguste Renoir, visible loose brushstrokes with textured impasto technique, vibrant color palette with emphasis on light and its changing qualities, dappled sunlight effects, soft edges and forms that blend together, focus on capturing momentary impression rather than fine details, colors applied in short strokes of pure unmixed paint, canvas texture visible, plein air painting aesthetic, masterful use of complementary colors, atmospheric perspective, traditional fine art quality, museum-worthy composition"
|
||||
},
|
||||
"Japanese Ukiyo-e Woodblock": {
|
||||
"prompt": "Traditional Japanese ukiyo-e woodblock print style, bold outlines with flat areas of color, limited color palette featuring indigo blues, vermillion reds, and ivory, stylized clouds and waves with distinctive patterns, attention to textile patterns and decorative elements, asymmetrical composition with strong diagonals, influence of Hokusai and Hiroshige, grain texture of woodblock printing, subtle color gradations through bokashi technique, Japanese aesthetic principles of wabi-sabi and mono no aware, artistic quality of Edo period prints, suitable for museum collection"
|
||||
},
|
||||
"Ultra Photorealistic": {
|
||||
"prompt": "Ultra photorealistic rendering with exceptional attention to every minute detail, 8k resolution with pixel-perfect clarity, physically accurate materials and lighting using ray tracing technology, subsurface scattering on skin and translucent materials, realistic depth of field and chromatic aberration, perfect exposure with natural lighting, micro-details including skin pores, fabric weave patterns, metal scratches and imperfections, dust particles in air, moisture and reflections, professional photography composition, shot with Canon EOS R5 with 85mm f/1.2 lens, indistinguishable from high-end commercial photography"
|
||||
},
|
||||
"Vintage Analog Photography": {
|
||||
"prompt": "Vintage analog film photography aesthetic, shot on Kodak Portra 400 or Fujifilm Pro 400H film stock, natural grain structure, slightly faded colors with characteristic film color shifts, vignetting on corners, subtle light leaks and lens flares, soft focus dreamy quality, dated timestamp or border frame, nostalgic 1970s-1990s color palette, imperfect exposure with authentic film limitations, scanned from 35mm negatives, warm golden tones, authentic vintage photograph appearance with all the charm and imperfections of film photography"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 387 KiB |
|
After Width: | Height: | Size: 766 KiB |
|
Before Width: | Height: | Size: 268 KiB After Width: | Height: | Size: 450 KiB |
|
After Width: | Height: | Size: 120 KiB |
|
After Width: | Height: | Size: 359 KiB |
|
After Width: | Height: | Size: 267 KiB |
@@ -0,0 +1,710 @@
|
||||
/**
|
||||
* File Browser Modal for PromptExtractor
|
||||
* Shows thumbnails of files in input directory
|
||||
*/
|
||||
|
||||
// Track current subfolder for navigation
|
||||
let currentSubfolder = '';
|
||||
|
||||
export function createFileBrowserModal(currentFile, onFileSelect) {
|
||||
// Reset to root on open
|
||||
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: rgba(0, 0, 0, 0.8);
|
||||
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: rgba(40, 44, 52, 0.98);
|
||||
border: 1px solid rgba(255,255,255,0.1);
|
||||
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 rgba(255,255,255,0.1);
|
||||
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: #aaa;">Select File from Input Folder</h3>
|
||||
<div style="display: flex; gap: 10px; align-items: center;">
|
||||
<button class="regenerate-cache-btn" style="
|
||||
background: #333;
|
||||
border: 1px solid #555;
|
||||
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: #888; cursor: pointer;';
|
||||
breadcrumb.textContent = 'input/';
|
||||
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 rgba(255,255,255,0.1);
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
`;
|
||||
filterBar.innerHTML = `
|
||||
<input type="text" placeholder="Search files..." class="search-input" style="
|
||||
flex: 1;
|
||||
padding: 8px 12px;
|
||||
background: rgba(45, 55, 72, 0.7);
|
||||
border: 1px solid rgba(226, 232, 240, 0.2);
|
||||
border-radius: 6px;
|
||||
color: #ccc;
|
||||
">
|
||||
<select class="filter-type" style="
|
||||
padding: 8px 12px;
|
||||
background: rgba(45, 55, 72, 0.7);
|
||||
border: 1px solid rgba(226, 232, 240, 0.2);
|
||||
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);
|
||||
|
||||
// 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 = 'input/';
|
||||
} else {
|
||||
breadcrumbElement.textContent = `input/${currentSubfolder}/`;
|
||||
}
|
||||
|
||||
// Fetch file list from server
|
||||
const response = await fetch('/prompt-extractor/list-files');
|
||||
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 input 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);
|
||||
});
|
||||
|
||||
} 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: 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 = 'Back';
|
||||
label.style.cssText = `
|
||||
font-size: 12px;
|
||||
color: #ccc;
|
||||
text-align: center;
|
||||
`;
|
||||
|
||||
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 = () => {
|
||||
// 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: rgba(45, 55, 72, 0.7);
|
||||
border: 1px solid ${isSelected ? 'rgba(66, 153, 225, 0.9)' : '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;
|
||||
`;
|
||||
|
||||
// Thumbnail preview
|
||||
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;
|
||||
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=input&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 with caching
|
||||
extractVideoThumbnailCached(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 = 'rgba(66, 153, 225, 0.9)';
|
||||
item.style.transform = 'translateY(-2px)';
|
||||
item.style.background = 'rgba(50, 112, 163, 0.5)';
|
||||
}
|
||||
};
|
||||
item.onmouseleave = () => {
|
||||
if (!isSelected) {
|
||||
item.style.borderColor = 'rgba(226, 232, 240, 0.2)';
|
||||
item.style.transform = 'translateY(0)';
|
||||
item.style.background = 'rgba(45, 55, 72, 0.7)';
|
||||
}
|
||||
};
|
||||
|
||||
// Click handler
|
||||
item.onclick = () => {
|
||||
onFileSelect(filename);
|
||||
document.body.removeChild(overlay);
|
||||
};
|
||||
|
||||
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';
|
||||
}
|
||||
|
||||
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 from video file with caching
|
||||
* Caches thumbnails in browser's localStorage
|
||||
*/
|
||||
async function extractVideoThumbnailCached(filename, previewElement) {
|
||||
// Use full path as cache key to avoid conflicts between subfolders
|
||||
const cacheKey = `video_thumb_${filename.replace(/[\/\\]/g, '_')}`;
|
||||
|
||||
try {
|
||||
// Check if we have a cached thumbnail
|
||||
const cachedThumb = localStorage.getItem(cacheKey);
|
||||
|
||||
// If cache exists, use it (trust localStorage until manual regeneration)
|
||||
if (cachedThumb) {
|
||||
const img = document.createElement('img');
|
||||
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
|
||||
img.src = cachedThumb;
|
||||
previewElement.innerHTML = '';
|
||||
previewElement.appendChild(img);
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('[FileBrowser] Cache check failed, generating new thumbnail:', error);
|
||||
}
|
||||
|
||||
// No cache, extract new thumbnail
|
||||
extractVideoThumbnail(filename, previewElement, cacheKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract thumbnail from video file
|
||||
* Fast, lightweight version for preview purposes only
|
||||
*/
|
||||
async function extractVideoThumbnail(filename, previewElement, cacheKey = null) {
|
||||
// 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);
|
||||
|
||||
// Create video element with minimal settings for fast loading
|
||||
const video = document.createElement('video');
|
||||
video.crossOrigin = 'anonymous';
|
||||
video.preload = 'metadata';
|
||||
video.muted = true;
|
||||
video.playsInline = true;
|
||||
video.style.display = 'none';
|
||||
|
||||
video.onloadedmetadata = () => {
|
||||
// Use absolute first frame (no seeking = fastest)
|
||||
video.currentTime = 0;
|
||||
};
|
||||
|
||||
video.onseeked = async () => {
|
||||
try {
|
||||
// Create small canvas for fast rendering (thumbnail size)
|
||||
const maxWidth = 180;
|
||||
const maxHeight = 150;
|
||||
const aspectRatio = video.videoWidth / video.videoHeight;
|
||||
|
||||
let width, height;
|
||||
if (aspectRatio > maxWidth / maxHeight) {
|
||||
width = maxWidth;
|
||||
height = maxWidth / aspectRatio;
|
||||
} else {
|
||||
height = maxHeight;
|
||||
width = maxHeight * aspectRatio;
|
||||
}
|
||||
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
const ctx = canvas.getContext('2d', { alpha: false });
|
||||
|
||||
// Draw video frame to small canvas
|
||||
ctx.drawImage(video, 0, 0, width, height);
|
||||
|
||||
// Create image from canvas with lower quality for speed
|
||||
const dataUrl = canvas.toDataURL('image/jpeg', 0.6);
|
||||
const img = document.createElement('img');
|
||||
img.style.cssText = 'max-width: 100%; max-height: 100%; object-fit: contain;';
|
||||
img.src = dataUrl;
|
||||
|
||||
// Replace placeholder with thumbnail (display first, cache later)
|
||||
previewElement.innerHTML = '';
|
||||
previewElement.appendChild(img);
|
||||
|
||||
// Cache the thumbnail asynchronously after display (non-blocking)
|
||||
if (cacheKey) {
|
||||
setTimeout(() => {
|
||||
try {
|
||||
localStorage.setItem(cacheKey, dataUrl);
|
||||
console.log(`[FileBrowser] Cached thumbnail for: ${filename}`);
|
||||
} catch (cacheError) {
|
||||
console.log('[FileBrowser] Failed to cache thumbnail:', cacheError);
|
||||
}
|
||||
}, 0);
|
||||
}
|
||||
|
||||
// Clean up
|
||||
video.remove();
|
||||
} catch (error) {
|
||||
console.error('[FileBrowser] Error extracting video thumbnail:', error);
|
||||
// Keep placeholder on error
|
||||
video.remove();
|
||||
}
|
||||
};
|
||||
|
||||
video.onerror = () => {
|
||||
console.error('[FileBrowser] Error loading video for thumbnail:', filename);
|
||||
// Keep placeholder on error
|
||||
video.remove();
|
||||
};
|
||||
|
||||
// Load video from input directory
|
||||
// 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);
|
||||
}
|
||||
video.src = `/view?filename=${encodeURIComponent(basename)}&type=input&subfolder=${encodeURIComponent(subfolder)}&${Date.now()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
|
||||
/**
|
||||
* Latent Preview Extension for Prompt Manager
|
||||
* Provides animated previews during video model sampling.
|
||||
* Compatible with VideoHelperSuite - will defer to VHS if installed.
|
||||
*/
|
||||
|
||||
// Track nodes that have latent preview widgets
|
||||
let latentPreviewNodes = new Set();
|
||||
|
||||
// Store preview images per node
|
||||
let previewImagesDict = {};
|
||||
|
||||
// Animation intervals for each node
|
||||
let animateIntervals = {};
|
||||
|
||||
// Text decoder for binary messages
|
||||
const textDecoder = new TextDecoder();
|
||||
|
||||
/**
|
||||
* Get a node by ID, handling subgraphs
|
||||
*/
|
||||
function getNodeById(id) {
|
||||
// Try main graph first
|
||||
let node = app.graph.getNodeById(id);
|
||||
if (node) return node;
|
||||
|
||||
// Try subgraphs if available
|
||||
if (app.graph.subgraphs) {
|
||||
for (const subgraph of app.graph.subgraphs.values()) {
|
||||
node = subgraph.getNodeById(id);
|
||||
if (node) return node;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fit the node height to accommodate the preview widget
|
||||
*/
|
||||
function fitHeight(node) {
|
||||
node.setSize([node.size[0], node.computeSize()[1]]);
|
||||
node.graph?.setDirtyCanvas(true, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Allow drag from the preview widget
|
||||
*/
|
||||
function allowDragFromWidget(widget) {
|
||||
widget.element.addEventListener('pointerdown', (e) => {
|
||||
if (e.button === 0) {
|
||||
// Prevent default to allow canvas interaction
|
||||
e.stopPropagation();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create the canvas context for latent preview
|
||||
*/
|
||||
function getLatentPreviewCtx(id, width, height) {
|
||||
const node = getNodeById(id);
|
||||
if (!node) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let previewWidget = node.widgets?.find((w) => w.name === "pmlatentpreview");
|
||||
|
||||
if (!previewWidget) {
|
||||
// Check for and remove any native preview
|
||||
const nativePreview = node.widgets?.findIndex((w) => w.name === '$$canvas-image-preview');
|
||||
if (nativePreview >= 0) {
|
||||
node.imgs = [];
|
||||
node.widgets.splice(nativePreview, 1);
|
||||
}
|
||||
|
||||
// Create canvas element
|
||||
const canvasEl = document.createElement("canvas");
|
||||
canvasEl.style.width = "100%";
|
||||
|
||||
previewWidget = node.addDOMWidget("pmlatentpreview", "pmcanvas", canvasEl, {
|
||||
serialize: false,
|
||||
hideOnZoom: false,
|
||||
});
|
||||
previewWidget.serialize = false;
|
||||
|
||||
allowDragFromWidget(previewWidget);
|
||||
|
||||
// Forward mouse events to canvas for interaction
|
||||
const forwardEvent = (eventName, handler) => {
|
||||
canvasEl.addEventListener(eventName, (e) => {
|
||||
e.preventDefault();
|
||||
return handler(e);
|
||||
}, true);
|
||||
};
|
||||
|
||||
forwardEvent('contextmenu', (e) => app.canvas._mousedown_callback(e));
|
||||
forwardEvent('pointerdown', (e) => app.canvas._mousedown_callback(e));
|
||||
forwardEvent('mousewheel', (e) => app.canvas._mousewheel_callback(e));
|
||||
forwardEvent('pointermove', (e) => app.canvas._mousemove_callback(e));
|
||||
forwardEvent('pointerup', (e) => app.canvas._mouseup_callback(e));
|
||||
|
||||
previewWidget.computeSize = function(width) {
|
||||
if (this.aspectRatio) {
|
||||
let height = (node.size[0] - 20) / this.aspectRatio + 10;
|
||||
if (!(height > 0)) {
|
||||
height = 0;
|
||||
}
|
||||
this.computedHeight = height + 10;
|
||||
return [width, height];
|
||||
}
|
||||
return [width, -4]; // No loaded src, widget should not display
|
||||
};
|
||||
}
|
||||
|
||||
const canvasEl = previewWidget.element;
|
||||
if (!previewWidget.ctx || canvasEl.width !== width || canvasEl.height !== height) {
|
||||
previewWidget.aspectRatio = width / height;
|
||||
canvasEl.width = width;
|
||||
canvasEl.height = height;
|
||||
fitHeight(node);
|
||||
}
|
||||
|
||||
return canvasEl.getContext("2d");
|
||||
}
|
||||
|
||||
/**
|
||||
* Begin animated latent preview for a node
|
||||
*/
|
||||
function beginLatentPreview(id, previewImages, rate) {
|
||||
latentPreviewNodes.add(id);
|
||||
|
||||
if (animateIntervals[id]) {
|
||||
clearInterval(animateIntervals[id]);
|
||||
}
|
||||
|
||||
let displayIndex = 0;
|
||||
const node = getNodeById(id);
|
||||
|
||||
// Initialize progress to avoid race condition
|
||||
if (node) {
|
||||
node.progress = 0;
|
||||
}
|
||||
|
||||
animateIntervals[id] = setInterval(() => {
|
||||
const currentNode = getNodeById(id);
|
||||
if (!currentNode?.progress && currentNode?.progress !== 0) {
|
||||
clearInterval(animateIntervals[id]);
|
||||
delete animateIntervals[id];
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if we're still on the right graph
|
||||
if (app.canvas.graph.rootGraph !== currentNode.graph?.rootGraph) {
|
||||
clearInterval(animateIntervals[id]);
|
||||
delete animateIntervals[id];
|
||||
return;
|
||||
}
|
||||
|
||||
if (!previewImages[displayIndex]) {
|
||||
return;
|
||||
}
|
||||
|
||||
const ctx = getLatentPreviewCtx(
|
||||
id,
|
||||
previewImages[displayIndex].width,
|
||||
previewImages[displayIndex].height
|
||||
);
|
||||
ctx?.drawImage?.(previewImages[displayIndex], 0, 0);
|
||||
|
||||
displayIndex = (displayIndex + 1) % previewImages.length;
|
||||
}, 1000 / rate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if VideoHelperSuite is providing latent preview
|
||||
*/
|
||||
function isVHSLatentPreviewActive() {
|
||||
// Check if VHS extension is registered and has latent preview enabled
|
||||
const vhsExtension = app.extensions.find(ext => ext.name === "VideoHelperSuite.Core");
|
||||
if (vhsExtension) {
|
||||
try {
|
||||
const vhsSetting = app.ui.settings.getSettingValue("VHS.LatentPreview");
|
||||
return vhsSetting === true;
|
||||
} catch (e) {
|
||||
// Setting doesn't exist or error
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "PromptManager.LatentPreview",
|
||||
settings: [
|
||||
{
|
||||
id: "PromptManager.LatentPreview",
|
||||
category: ["Prompt Manager", "5. Video Sampling", "1. Animated Latent Preview"],
|
||||
name: "Display animated previews when sampling",
|
||||
tooltip: "Enable animated preview during video model sampling (KSampler). Will be disabled if VideoHelperSuite provides this feature.",
|
||||
type: "boolean",
|
||||
defaultValue: false,
|
||||
onChange(value) {
|
||||
if (!value) {
|
||||
// Remove any preview widgets when disabled
|
||||
for (const id of latentPreviewNodes) {
|
||||
const node = app.graph?.getNodeById(id);
|
||||
const widgetIndex = node?.widgets?.findIndex((w) => w.name === 'pmlatentpreview');
|
||||
if (widgetIndex >= 0) {
|
||||
const widget = node.widgets.splice(widgetIndex, 1)[0];
|
||||
widget.onRemove?.();
|
||||
}
|
||||
}
|
||||
latentPreviewNodes = new Set();
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "PromptManager.LatentPreviewRate",
|
||||
category: ["Prompt Manager", "5. Video Sampling", "2. Playback Rate Override"],
|
||||
name: "Playback rate override",
|
||||
tooltip: "Force a specific frame rate for latent preview playback. Set to 0 for auto-detect based on video model. This is the preview FPS, not the output video FPS.",
|
||||
type: "number",
|
||||
attrs: {
|
||||
min: 0,
|
||||
step: 1,
|
||||
max: 60,
|
||||
},
|
||||
defaultValue: 0,
|
||||
},
|
||||
],
|
||||
|
||||
async setup() {
|
||||
// Hook into graphToPrompt to pass our settings to the backend
|
||||
const originalGraphToPrompt = app.graphToPrompt;
|
||||
|
||||
app.graphToPrompt = async function() {
|
||||
const res = await originalGraphToPrompt.apply(this, arguments);
|
||||
|
||||
// Check if VHS is handling latent preview
|
||||
const vhsActive = isVHSLatentPreviewActive();
|
||||
|
||||
if (!vhsActive) {
|
||||
// Add our settings to the workflow extra data
|
||||
res.workflow.extra['PM_latentpreview'] = app.ui.settings.getSettingValue("PromptManager.LatentPreview");
|
||||
res.workflow.extra['PM_latentpreviewrate'] = app.ui.settings.getSettingValue("PromptManager.LatentPreviewRate");
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
console.log("[PromptManager] Latent preview extension loaded");
|
||||
},
|
||||
|
||||
async init() {
|
||||
// Clear preview nodes on execution complete
|
||||
api.addEventListener('executing', ({ detail }) => {
|
||||
if (detail === null) {
|
||||
// Execution complete - clean up progress indicators
|
||||
for (const id of latentPreviewNodes) {
|
||||
const node = getNodeById(id);
|
||||
if (node) {
|
||||
delete node.progress;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Listen for latent preview initialization from backend
|
||||
api.addEventListener('PM_latentpreview', ({ detail }) => {
|
||||
if (detail.id == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Skip if VHS is active
|
||||
if (isVHSLatentPreviewActive()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const previewImages = previewImagesDict[detail.id] = [];
|
||||
previewImages.length = detail.length;
|
||||
|
||||
// Handle node ID parts (for subgraphs)
|
||||
const idParts = detail.id.split(':');
|
||||
for (let i = 1; i <= idParts.length; i++) {
|
||||
const id = idParts.slice(0, i).join(':');
|
||||
beginLatentPreview(id, previewImages, detail.rate);
|
||||
}
|
||||
});
|
||||
|
||||
// Listen for binary preview images
|
||||
api.addEventListener('b_preview', async (e) => {
|
||||
// Only handle if we have active animations and VHS isn't handling it
|
||||
if (Object.keys(animateIntervals).length === 0 || isVHSLatentPreviewActive()) {
|
||||
return;
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
e.stopImmediatePropagation();
|
||||
e.stopPropagation();
|
||||
|
||||
const dv = new DataView(await e.detail.slice(0, 24).arrayBuffer());
|
||||
const index = dv.getUint32(4);
|
||||
const idlen = dv.getUint8(8);
|
||||
const id = textDecoder.decode(dv.buffer.slice(9, 9 + idlen));
|
||||
|
||||
// Only process if this is our preview (PM_ prefix in the workflow extra)
|
||||
if (previewImagesDict[id]) {
|
||||
previewImagesDict[id][index] = await window.createImageBitmap(e.detail.slice(24));
|
||||
}
|
||||
|
||||
return false;
|
||||
}, true);
|
||||
},
|
||||
});
|
||||
|
After Width: | Height: | Size: 747 B |
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* Video Metadata Reader - VHS Compatible
|
||||
* Enables drag-and-drop workflow loading from videos saved by VideoHelperSuite
|
||||
* without needing VHS installed.
|
||||
*
|
||||
* Based on VideoHelperSuite's videoinfo.js implementation.
|
||||
*/
|
||||
|
||||
import { app } from '../../../scripts/app.js'
|
||||
|
||||
/**
|
||||
* Parse video file bytes to extract embedded workflow/prompt metadata.
|
||||
* Supports webm/mkv (EBML/Matroska) and mp4 (QuickTime) formats.
|
||||
*/
|
||||
function getVideoMetadata(file) {
|
||||
return new Promise((resolve) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
const videoData = new Uint8Array(event.target.result);
|
||||
const dataView = new DataView(videoData.buffer);
|
||||
const decoder = new TextDecoder();
|
||||
|
||||
// Check for known valid magic bytes
|
||||
if (dataView.getUint32(0) === 0x1A45DFA3) {
|
||||
// webm/mkv - EBML/Matroska format
|
||||
// Metadata stored in COMMENT tags
|
||||
// See: http://wiki.webmproject.org/webm-metadata/global-metadata
|
||||
// See: https://www.matroska.org/technical/elements.html
|
||||
let offset = 4 + 8; // Skip header, COMMENT is 7 chars + 1 to realign
|
||||
|
||||
while (offset < videoData.length - 16) {
|
||||
// Check for text tags (0x4487 = TagString element)
|
||||
if (dataView.getUint16(offset) === 0x4487) {
|
||||
// Check that name of tag is COMMENT
|
||||
const name = String.fromCharCode(...videoData.slice(offset - 7, offset));
|
||||
if (name === "COMMENT") {
|
||||
// Parse EBML variable-length integer
|
||||
// See: https://github.com/ietf-wg-cellar/ebml-specification/blob/master/specification.markdown
|
||||
let vint = dataView.getUint32(offset + 2);
|
||||
let n_octets = Math.clz32(vint) + 1;
|
||||
if (n_octets < 4) { // 250MB sanity cutoff
|
||||
let length = (vint >> (8 * (4 - n_octets))) & ~(1 << (7 * n_octets));
|
||||
const content = decoder.decode(videoData.slice(offset + 2 + n_octets, offset + 2 + n_octets + length));
|
||||
try {
|
||||
const json = JSON.parse(content);
|
||||
resolve(json);
|
||||
return;
|
||||
} catch (e) {
|
||||
console.warn("[VideoMetadata] Failed to parse COMMENT JSON:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
offset += 1;
|
||||
}
|
||||
} else if (dataView.getUint32(4) === 0x66747970) {
|
||||
// mp4 - QuickTime/ISO format
|
||||
// See: https://developer.apple.com/documentation/quicktime-file-format
|
||||
// Metadata can be in various locations, search from end
|
||||
|
||||
// First try: Look for ©cmt (comment) atom - VHS style
|
||||
let offset = videoData.length - 4;
|
||||
while (offset > 16) {
|
||||
if (dataView.getUint32(offset) === 0x64617461) { // 'data' tag
|
||||
if (dataView.getUint32(offset - 8) === 0xa9636d74) { // '©cmt' (comment) tag
|
||||
let size = dataView.getUint32(offset - 4) - 4 * 4;
|
||||
const content = decoder.decode(videoData.slice(offset + 12, offset + 12 + size));
|
||||
try {
|
||||
const json = JSON.parse(content);
|
||||
resolve(json);
|
||||
return;
|
||||
} catch (e) {
|
||||
console.warn("[VideoMetadata] Failed to parse ©cmt JSON:", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
offset -= 1;
|
||||
}
|
||||
|
||||
// Second try: Look for 'prompt' or 'workflow' tags in metadata
|
||||
// These are stored by our SaveVideoH26x node using movflags=use_metadata_tags
|
||||
offset = 0;
|
||||
while (offset < videoData.length - 100) {
|
||||
// Look for 'prompt' or 'workflow' strings followed by JSON
|
||||
const slice = decoder.decode(videoData.slice(offset, offset + 20));
|
||||
if (slice.includes('prompt') || slice.includes('workflow')) {
|
||||
// Try to find JSON starting after the key
|
||||
for (let i = 0; i < 50 && offset + i < videoData.length - 1; i++) {
|
||||
if (videoData[offset + i] === 0x7B) { // '{'
|
||||
// Found potential JSON start, try to parse
|
||||
let jsonEnd = offset + i;
|
||||
let braceCount = 0;
|
||||
for (let j = jsonEnd; j < Math.min(jsonEnd + 1000000, videoData.length); j++) {
|
||||
if (videoData[j] === 0x7B) braceCount++;
|
||||
if (videoData[j] === 0x7D) braceCount--;
|
||||
if (braceCount === 0) {
|
||||
jsonEnd = j + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
const jsonStr = decoder.decode(videoData.slice(offset + i, jsonEnd));
|
||||
try {
|
||||
const json = JSON.parse(jsonStr);
|
||||
if (json.workflow || json.prompt || json.nodes) {
|
||||
resolve(json.workflow ? json : { workflow: json });
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
// Not valid JSON, continue searching
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
offset += 100; // Skip ahead in larger chunks
|
||||
}
|
||||
}
|
||||
|
||||
// No metadata found
|
||||
resolve(undefined);
|
||||
};
|
||||
|
||||
reader.onerror = () => {
|
||||
console.error("[VideoMetadata] Failed to read file");
|
||||
resolve(undefined);
|
||||
};
|
||||
|
||||
reader.readAsArrayBuffer(file);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if file is a video by extension
|
||||
*/
|
||||
function isVideoFile(file) {
|
||||
const videoExtensions = ['.webm', '.mp4', '.mkv', '.mov', '.avi'];
|
||||
const name = file?.name?.toLowerCase() || '';
|
||||
return videoExtensions.some(ext => name.endsWith(ext));
|
||||
}
|
||||
|
||||
// Store original handler
|
||||
let originalHandleFile = null;
|
||||
|
||||
/**
|
||||
* Custom file handler that intercepts video files to extract workflow metadata
|
||||
*/
|
||||
async function handleFile(file) {
|
||||
// Check if this is a video file
|
||||
if (file?.type?.startsWith("video/") || isVideoFile(file)) {
|
||||
console.log("[VideoMetadata] Processing video file:", file.name);
|
||||
|
||||
try {
|
||||
const videoInfo = await getVideoMetadata(file);
|
||||
|
||||
if (videoInfo?.workflow) {
|
||||
console.log("[VideoMetadata] Found workflow in video, loading...");
|
||||
await app.loadGraphData(videoInfo.workflow);
|
||||
return;
|
||||
} else {
|
||||
console.log("[VideoMetadata] No workflow metadata found in video");
|
||||
}
|
||||
} catch (e) {
|
||||
console.error("[VideoMetadata] Error extracting metadata:", e);
|
||||
}
|
||||
}
|
||||
|
||||
// Fall through to original handler
|
||||
if (originalHandleFile) {
|
||||
return await originalHandleFile.apply(this, arguments);
|
||||
}
|
||||
}
|
||||
|
||||
// Register extension
|
||||
app.registerExtension({
|
||||
name: "PromptManager.VideoMetadata",
|
||||
|
||||
async setup() {
|
||||
// Only hijack if not already done by VHS
|
||||
if (!window._vhsVideoMetadataRegistered) {
|
||||
// Store and replace the file handler
|
||||
originalHandleFile = app.handleFile;
|
||||
app.handleFile = handleFile;
|
||||
|
||||
// Add video formats to file input accept attribute
|
||||
const fileInput = document.getElementById("comfy-file-input");
|
||||
if (fileInput && !fileInput.accept.includes("video/")) {
|
||||
fileInput.accept += ",video/webm,video/mp4,video/x-matroska";
|
||||
}
|
||||
|
||||
// Mark as registered to avoid double-registration if VHS loads later
|
||||
window._vhsVideoMetadataRegistered = true;
|
||||
|
||||
console.log("[VideoMetadata] VHS-compatible video metadata reader registered");
|
||||
} else {
|
||||
console.log("[VideoMetadata] Video metadata handler already registered (likely by VHS)");
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,352 @@
|
||||
"""
|
||||
Latent Preview for Video Sampling - Provides animated previews during KSampler execution for video models.
|
||||
Based on VideoHelperSuite implementation, with compatibility checks to avoid conflicts.
|
||||
"""
|
||||
|
||||
from PIL import Image
|
||||
import time
|
||||
import io
|
||||
import struct
|
||||
from threading import Thread
|
||||
import functools
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
# Rates table for different video models (frames per second / temporal compression)
|
||||
RATES_TABLE = {
|
||||
'Mochi': 24 // 6,
|
||||
'LTXV': 24 // 8,
|
||||
'HunyuanVideo': 24 // 4,
|
||||
'Cosmos1CV8x8x8': 24 // 8,
|
||||
'Wan21': 16 // 4,
|
||||
'Wan22': 24 // 4
|
||||
}
|
||||
|
||||
# Global flag to track if we've hooked the previewer
|
||||
_hook_installed = False
|
||||
_original_get_previewer = None
|
||||
|
||||
|
||||
def hook(obj, attr):
|
||||
"""Decorator to hook/wrap an existing function on an object."""
|
||||
def dec(f):
|
||||
f = functools.update_wrapper(f, getattr(obj, attr))
|
||||
setattr(obj, attr, f)
|
||||
return f
|
||||
return dec
|
||||
|
||||
|
||||
# Import latent_preview at module level for proper inheritance
|
||||
import latent_preview as _latent_preview_module
|
||||
|
||||
|
||||
class WrappedPreviewer(_latent_preview_module.LatentPreviewer):
|
||||
"""
|
||||
Wraps the standard latent previewer to provide animated video previews.
|
||||
This class intercepts preview requests and sends frames as an animation
|
||||
instead of static images.
|
||||
"""
|
||||
|
||||
def __init__(self, previewer, rate=8, server_instance=None, model_name=None):
|
||||
# Don't call super().__init__() as we're wrapping an existing previewer
|
||||
self.first_preview = True
|
||||
self.last_time = 0
|
||||
self.c_index = 0
|
||||
self.rate = rate
|
||||
self.server = server_instance
|
||||
self.is_video_taesd = False
|
||||
self.model_name = model_name
|
||||
|
||||
# Copy decoder attributes from the original previewer
|
||||
# Check what type of previewer we have
|
||||
if hasattr(previewer, 'taesd'):
|
||||
self.taesd = previewer.taesd
|
||||
# Detect if this is a video TAESD (VAE-based) vs regular TAESD
|
||||
# Video TAESDs use a full VAE with first_stage_model
|
||||
if hasattr(self.taesd, 'first_stage_model'):
|
||||
self.is_video_taesd = True
|
||||
elif hasattr(previewer, 'latent_rgb_factors'):
|
||||
self.latent_rgb_factors = previewer.latent_rgb_factors
|
||||
self.latent_rgb_factors_bias = previewer.latent_rgb_factors_bias
|
||||
self.latent_rgb_factors_reshape = getattr(previewer, 'latent_rgb_factors_reshape', None)
|
||||
else:
|
||||
raise Exception('Unsupported preview type for animated latent previews')
|
||||
|
||||
def decode_latent_to_preview_image(self, preview_format, x0):
|
||||
"""
|
||||
Main preview method - intercepts the standard preview call and
|
||||
converts it to animated frame previews for video latents.
|
||||
"""
|
||||
import server
|
||||
|
||||
if x0.ndim == 5:
|
||||
# Keep batch major for video tensors
|
||||
x0 = x0.movedim(2, 1)
|
||||
x0 = x0.reshape((-1,) + x0.shape[-3:])
|
||||
|
||||
num_images = x0.size(0)
|
||||
new_time = time.time()
|
||||
num_previews = int((new_time - self.last_time) * self.rate)
|
||||
self.last_time = self.last_time + num_previews / self.rate
|
||||
|
||||
if num_previews > num_images:
|
||||
num_previews = num_images
|
||||
elif num_previews <= 0:
|
||||
return None
|
||||
|
||||
if self.first_preview:
|
||||
self.first_preview = False
|
||||
# Send initialization message to frontend
|
||||
self.server.send_sync('PM_latentpreview', {
|
||||
'length': num_images,
|
||||
'rate': self.rate,
|
||||
'id': self.server.last_node_id
|
||||
})
|
||||
self.last_time = new_time + 1 / self.rate
|
||||
|
||||
if self.c_index + num_previews > num_images:
|
||||
x0 = x0.roll(-self.c_index, 0)[:num_previews]
|
||||
else:
|
||||
x0 = x0[self.c_index:self.c_index + num_previews]
|
||||
|
||||
# Process previews in a thread
|
||||
if hasattr(self, 'latent_rgb_factors'):
|
||||
Thread(target=self._process_latent2rgb_batch, args=(x0, self.c_index, num_images)).run()
|
||||
else:
|
||||
Thread(target=self._process_taesd_batch, args=(x0, self.c_index, num_images)).run()
|
||||
self.c_index = (self.c_index + num_previews) % num_images
|
||||
return None
|
||||
|
||||
def _process_taesd_batch(self, latent_frames, ind, leng):
|
||||
"""Process and send preview frames to the frontend.
|
||||
|
||||
Args:
|
||||
latent_frames: Latent tensor, shape (N, C, H, W) where N is number of frames
|
||||
ind: Current frame index
|
||||
leng: Total number of frames
|
||||
"""
|
||||
import server
|
||||
|
||||
# For TAESD, decode each frame (don't change this - it works)
|
||||
for i in range(latent_frames.size(0)):
|
||||
frame_latent = latent_frames[i:i + 1] # Keep batch dim: (1, C, H, W)
|
||||
|
||||
# Decode single frame to PIL Image (same as ComfyUI does)
|
||||
preview_image = self.decode_single_frame(frame_latent)
|
||||
|
||||
if preview_image is None:
|
||||
continue
|
||||
|
||||
# Resize if needed
|
||||
if preview_image.width > 512 or preview_image.height > 512:
|
||||
if preview_image.width > preview_image.height:
|
||||
new_width = 512
|
||||
new_height = int(512 * preview_image.height / preview_image.width)
|
||||
else:
|
||||
new_height = 512
|
||||
new_width = int(512 * preview_image.width / preview_image.height)
|
||||
preview_image = preview_image.resize((new_width, new_height), Image.LANCZOS)
|
||||
|
||||
# Send to frontend
|
||||
message = io.BytesIO()
|
||||
message.write((1).to_bytes(length=4, byteorder='big') * 2)
|
||||
message.write(ind.to_bytes(length=4, byteorder='big'))
|
||||
message.write(struct.pack('16p', self.server.last_node_id.encode('ascii')))
|
||||
preview_image.save(message, format="JPEG", quality=95)
|
||||
|
||||
self.server.send_sync(
|
||||
server.BinaryEventTypes.PREVIEW_IMAGE,
|
||||
message.getvalue(),
|
||||
self.server.client_id
|
||||
)
|
||||
ind = (ind + 1) % leng
|
||||
|
||||
def _process_latent2rgb_batch(self, x0, ind, leng):
|
||||
"""Process Latent2RGB previews using batch decode (VHS style)."""
|
||||
import server
|
||||
|
||||
# Apply reshape if needed
|
||||
if self.latent_rgb_factors_reshape is not None:
|
||||
x0 = self.latent_rgb_factors_reshape(x0)
|
||||
|
||||
self.latent_rgb_factors = self.latent_rgb_factors.to(dtype=x0.dtype, device=x0.device)
|
||||
if self.latent_rgb_factors_bias is not None:
|
||||
self.latent_rgb_factors_bias = self.latent_rgb_factors_bias.to(dtype=x0.dtype, device=x0.device)
|
||||
|
||||
# Batch decode: x0 is (N, C, H, W), output is (N, H, W, 3)
|
||||
image_tensor = F.linear(x0.movedim(1, -1), self.latent_rgb_factors,
|
||||
bias=self.latent_rgb_factors_bias)
|
||||
|
||||
# Resize if needed
|
||||
if image_tensor.size(1) > 512 or image_tensor.size(2) > 512:
|
||||
image_tensor = image_tensor.movedim(-1, 0)
|
||||
if image_tensor.size(2) < image_tensor.size(3):
|
||||
height = (512 * image_tensor.size(2)) // image_tensor.size(3)
|
||||
image_tensor = F.interpolate(image_tensor, (height, 512), mode='bilinear')
|
||||
else:
|
||||
width = (512 * image_tensor.size(3)) // image_tensor.size(2)
|
||||
image_tensor = F.interpolate(image_tensor, (512, width), mode='bilinear')
|
||||
image_tensor = image_tensor.movedim(0, -1)
|
||||
|
||||
# Convert to uint8 (scale from -1..1 to 0..255)
|
||||
previews_ubyte = (((image_tensor + 1.0) / 2.0).clamp(0, 1).mul(0xFF)).to(device="cpu", dtype=torch.uint8)
|
||||
|
||||
# Send each frame
|
||||
for preview in previews_ubyte:
|
||||
i = Image.fromarray(preview.numpy())
|
||||
message = io.BytesIO()
|
||||
message.write((1).to_bytes(length=4, byteorder='big') * 2)
|
||||
message.write(ind.to_bytes(length=4, byteorder='big'))
|
||||
message.write(struct.pack('16p', self.server.last_node_id.encode('ascii')))
|
||||
i.save(message, format="JPEG", quality=95)
|
||||
self.server.send_sync(
|
||||
server.BinaryEventTypes.PREVIEW_IMAGE,
|
||||
message.getvalue(),
|
||||
self.server.client_id
|
||||
)
|
||||
ind = (ind + 1) % leng
|
||||
|
||||
def decode_single_frame(self, x0):
|
||||
"""Decode a single TAESD latent frame to PIL Image.
|
||||
Only used by _process_taesd_batch().
|
||||
|
||||
Args:
|
||||
x0: Latent tensor, shape (1, C, H, W) for images or (1, C, T, H, W) for video
|
||||
|
||||
Returns:
|
||||
PIL.Image
|
||||
"""
|
||||
if self.is_video_taesd:
|
||||
# TAEHVPreviewerImpl style: x0[:1, :, :1] then [0][0]
|
||||
if x0.ndim == 4:
|
||||
x0 = x0.unsqueeze(2) # (1, C, H, W) -> (1, C, 1, H, W)
|
||||
|
||||
x_sample = self.taesd.decode(x0[:1, :, :1])[0][0]
|
||||
|
||||
# # Apply contrast boost for Wan models (TAESD looks washed out)
|
||||
# if self.model_name and self.model_name.startswith('Wan'):
|
||||
# x_sample = self._apply_contrast(x_sample, contrast=1.2, brightness=1.0)
|
||||
|
||||
# Video TAEs output 0-1 range, not -1 to 1
|
||||
return self._tensor_to_image(x_sample, do_scale=False)
|
||||
else:
|
||||
# TAESDPreviewerImpl style: decode(x0[:1])[0].movedim(0, 2)
|
||||
x_sample = self.taesd.decode(x0[:1])[0].movedim(0, 2)
|
||||
return self._tensor_to_image(x_sample, do_scale=True)
|
||||
|
||||
def _apply_contrast(self, tensor, contrast=1.0, brightness=1.0):
|
||||
"""Apply contrast and brightness adjustment to a tensor in 0-1 range."""
|
||||
# Contrast: (x - 0.5) * contrast + 0.5
|
||||
# Brightness: x * brightness
|
||||
tensor = (tensor - 0.5) * contrast + 0.5
|
||||
tensor = tensor * brightness
|
||||
return tensor.clamp(0, 1)
|
||||
|
||||
def _tensor_to_image(self, tensor, do_scale=True):
|
||||
"""Convert tensor to PIL Image, matching ComfyUI's preview_to_image."""
|
||||
import comfy.model_management
|
||||
|
||||
if do_scale:
|
||||
latents_ubyte = (((tensor + 1.0) / 2.0).clamp(0, 1).mul(0xFF))
|
||||
else:
|
||||
latents_ubyte = (tensor.clamp(0, 1).mul(0xFF))
|
||||
|
||||
if comfy.model_management.directml_enabled:
|
||||
latents_ubyte = latents_ubyte.to(dtype=torch.uint8)
|
||||
|
||||
latents_ubyte = latents_ubyte.to(
|
||||
device="cpu",
|
||||
dtype=torch.uint8,
|
||||
non_blocking=comfy.model_management.device_supports_non_blocking(tensor.device)
|
||||
)
|
||||
|
||||
return Image.fromarray(latents_ubyte.numpy())
|
||||
|
||||
|
||||
def is_vhs_installed():
|
||||
"""Check if VideoHelperSuite is installed and has latent preview enabled."""
|
||||
try:
|
||||
# Check if VHS module is loaded
|
||||
import sys
|
||||
for module_name in sys.modules:
|
||||
if 'videohelpersuite' in module_name.lower():
|
||||
# VHS is installed, check if it has hooked the previewer
|
||||
func = getattr(_latent_preview_module, 'get_previewer', None)
|
||||
if func and hasattr(func, '__wrapped__'):
|
||||
# VHS has already hooked the previewer
|
||||
return True
|
||||
return False
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
def install_latent_preview_hook():
|
||||
"""
|
||||
Install the latent preview hook if:
|
||||
1. It's not already installed by us
|
||||
2. VideoHelperSuite hasn't already installed it
|
||||
"""
|
||||
global _hook_installed, _original_get_previewer
|
||||
|
||||
if _hook_installed:
|
||||
print("[PromptManager] Latent preview hook already installed")
|
||||
return True
|
||||
|
||||
if is_vhs_installed():
|
||||
print("[PromptManager] VideoHelperSuite detected with latent preview - skipping to avoid conflict")
|
||||
return False
|
||||
|
||||
try:
|
||||
import server
|
||||
serv = server.PromptServer.instance
|
||||
|
||||
# Store original function
|
||||
_original_get_previewer = _latent_preview_module.get_previewer
|
||||
|
||||
@hook(_latent_preview_module, 'get_previewer')
|
||||
def get_latent_video_previewer(device, latent_format, *args, **kwargs):
|
||||
"""Wrapped previewer that checks settings and returns animated previewer if enabled."""
|
||||
previewer = get_latent_video_previewer.__wrapped__(device, latent_format, *args, **kwargs)
|
||||
|
||||
try:
|
||||
extra_info = next(serv.prompt_queue.currently_running.values().__iter__())[3]['extra_pnginfo']['workflow']['extra']
|
||||
prev_setting = extra_info.get('PM_latentpreview', False)
|
||||
|
||||
if extra_info.get('PM_latentpreviewrate', 0) != 0:
|
||||
rate_setting = extra_info['PM_latentpreviewrate']
|
||||
else:
|
||||
rate_setting = RATES_TABLE.get(latent_format.__class__.__name__, 8)
|
||||
except:
|
||||
# For safety since there's lots of keys, any of which can fail
|
||||
prev_setting = False
|
||||
|
||||
if not prev_setting or not hasattr(previewer, "decode_latent_to_preview"):
|
||||
return previewer
|
||||
|
||||
model_name = latent_format.__class__.__name__
|
||||
return WrappedPreviewer(previewer, rate_setting, serv, model_name)
|
||||
|
||||
_hook_installed = True
|
||||
print("[PromptManager] Latent preview hook installed successfully")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Failed to install latent preview hook: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def uninstall_latent_preview_hook():
|
||||
"""Restore the original get_previewer function."""
|
||||
global _hook_installed, _original_get_previewer
|
||||
|
||||
if not _hook_installed or _original_get_previewer is None:
|
||||
return
|
||||
|
||||
try:
|
||||
_latent_preview_module.get_previewer = _original_get_previewer
|
||||
_hook_installed = False
|
||||
_original_get_previewer = None
|
||||
print("[PromptManager] Latent preview hook uninstalled")
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Failed to uninstall latent preview hook: {e}")
|
||||
@@ -3,36 +3,92 @@ Utility functions for managing llama.cpp models
|
||||
"""
|
||||
import os
|
||||
import glob
|
||||
import json
|
||||
import re
|
||||
import folder_paths
|
||||
|
||||
import server
|
||||
from huggingface_hub import HfApi
|
||||
from tqdm.auto import tqdm
|
||||
import requests
|
||||
|
||||
# Predefined models - use real filenames as keys
|
||||
QWEN_MODELS = {
|
||||
"Qwen3-1.7B-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-1.7B-GGUF"
|
||||
},
|
||||
"Qwen3-4B-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-4B-GGUF"
|
||||
},
|
||||
"Qwen3-8B-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-8B-GGUF"
|
||||
},
|
||||
"Qwen3VL-4B-Instruct-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-VL-4B-Instruct-GGUF",
|
||||
"mmproj": "mmproj-Qwen3VL-4B-Instruct-Q8_0.gguf"
|
||||
},
|
||||
"Qwen3VL-8B-Instruct-Q8_0.gguf": {
|
||||
"repo": "Qwen/Qwen3-VL-8B-Instruct-GGUF",
|
||||
"mmproj": "mmproj-Qwen3VL-8B-Instruct-Q8_0.gguf"
|
||||
}
|
||||
# Add preference cache and API endpoints for preferences
|
||||
_preferences_cache = {
|
||||
"preferred_base_model": "",
|
||||
"preferred_vision_model": "",
|
||||
"custom_llama_path": "",
|
||||
"custom_llama_model_path": "",
|
||||
"close_llama_on_exit": True,
|
||||
"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
|
||||
}
|
||||
|
||||
# Preferences are now stored in ComfyUI settings (comfy.settings.json)
|
||||
# and accessed via the settings API in prompt_manager.py
|
||||
# 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.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.5-9B-Q8_0.gguf": {
|
||||
"repo": "unsloth/Qwen3.5-9B-GGUF",
|
||||
"mmproj": "mmproj-Qwen3.5-9B-F16.gguf",
|
||||
"mmproj_repo_filename": "mmproj-F16.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"
|
||||
},
|
||||
}
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager/load-preferences")
|
||||
async def load_preferences(request):
|
||||
"""API endpoint to get cached preferences (set from ComfyUI settings)"""
|
||||
return server.web.json_response(_preferences_cache)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/save-preference")
|
||||
async def save_preference(request):
|
||||
"""API endpoint to update preference cache when settings change"""
|
||||
try:
|
||||
data = await request.json()
|
||||
key = data.get("key")
|
||||
value = data.get("value", "")
|
||||
|
||||
if key not in ["preferred_base_model",
|
||||
"preferred_vision_model",
|
||||
"custom_llama_path",
|
||||
"custom_llama_model_path",
|
||||
"close_llama_on_exit",
|
||||
"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
|
||||
_preferences_cache[key] = value
|
||||
|
||||
return server.web.json_response({"success": True, "preferences": _preferences_cache})
|
||||
except Exception as e:
|
||||
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"""
|
||||
@@ -45,11 +101,16 @@ def get_models_directory():
|
||||
llm_dir = os.path.join(folder_paths.models_dir, "LLM")
|
||||
folder_paths.add_model_folder_path("LLM", llm_dir)
|
||||
|
||||
# Return gguf as the primary directory (for downloads)
|
||||
models_dir = folder_paths.get_folder_paths("gguf")[0]
|
||||
custom_llama_model_path = _preferences_cache.get("custom_llama_model_path", "")
|
||||
|
||||
# Create directory if it doesn't exist
|
||||
os.makedirs(models_dir, exist_ok=True)
|
||||
if custom_llama_model_path and os.path.isdir(custom_llama_model_path):
|
||||
# Add custom path if not already present
|
||||
if "CustomLLM" not in folder_paths.folder_names_and_paths:
|
||||
folder_paths.add_model_folder_path("CustomLLM", custom_llama_model_path)
|
||||
models_dir = custom_llama_model_path
|
||||
else:
|
||||
models_dir = folder_paths.get_folder_paths("gguf")[0]
|
||||
os.makedirs(models_dir, exist_ok=True) # Create directory if it doesn't exist
|
||||
|
||||
return models_dir
|
||||
|
||||
@@ -58,7 +119,7 @@ def get_all_model_directories():
|
||||
get_models_directory() # Ensure folders are registered
|
||||
|
||||
directories = []
|
||||
for folder_type in ["gguf", "LLM"]:
|
||||
for folder_type in ["gguf", "LLM", "CustomLLM"]:
|
||||
if folder_type in folder_paths.folder_names_and_paths:
|
||||
dirs = folder_paths.get_folder_paths(folder_type)
|
||||
directories.extend(dirs)
|
||||
@@ -76,7 +137,7 @@ def get_local_models():
|
||||
for f in gguf_files:
|
||||
basename = os.path.basename(f)
|
||||
# Filter out mmproj files
|
||||
if not basename.startswith("mmproj-"):
|
||||
if 'mmproj' not in basename.lower():
|
||||
all_models.add(basename)
|
||||
|
||||
# Return sorted list of unique filenames
|
||||
@@ -89,7 +150,7 @@ def get_huggingface_models():
|
||||
def get_all_models():
|
||||
"""Get combined list of local and HuggingFace models, excluding already downloaded ones and mmproj files"""
|
||||
local_models = get_local_models() # Already filtered
|
||||
models_dir = get_models_directory()
|
||||
models_dir = get_models_directory()
|
||||
|
||||
# List all known filenames, local ones first
|
||||
all_models = []
|
||||
@@ -98,7 +159,7 @@ def get_all_models():
|
||||
all_models.extend(local_models)
|
||||
# Add remote models (not present locally), excluding mmproj files
|
||||
for filename in QWEN_MODELS.keys():
|
||||
if filename not in all_models and not filename.startswith("mmproj-"):
|
||||
if filename not in all_models and 'mmproj' not in filename.lower():
|
||||
all_models.append(filename)
|
||||
return all_models
|
||||
|
||||
@@ -129,25 +190,91 @@ 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_identity(name):
|
||||
"""Extract the model's identity parts from a filename, stripping quant info.
|
||||
|
||||
Example: 'Qwen3.5-9B-Q4_K_M.gguf' → ('Qwen3', '5', '9B')
|
||||
'mmproj-Qwen3.5-9B-F16.gguf' → ('Qwen3', '5', '9B')
|
||||
"""
|
||||
base = os.path.splitext(os.path.basename(name))[0]
|
||||
parts = [p for p in re.split(r"[-._ ]", base) if p]
|
||||
return tuple(p for p in parts if p not in _QUANT_PARTS and p.lower() != "mmproj")
|
||||
|
||||
|
||||
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"""
|
||||
"""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).
|
||||
"""
|
||||
# --- 1. Explicit mapping ---
|
||||
mmproj_name = get_mmproj_for_model(model_name)
|
||||
if mmproj_name and is_model_local(mmproj_name):
|
||||
return get_model_path(mmproj_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: match by model identity ---
|
||||
model_identity = _get_model_identity(model_name)
|
||||
if not model_identity:
|
||||
return None
|
||||
|
||||
all_dirs = get_all_model_directories()
|
||||
for models_dir in all_dirs:
|
||||
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_identity = _get_model_identity(f)
|
||||
if mmproj_identity and mmproj_identity == model_identity:
|
||||
return os.path.join(models_dir, f)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
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
|
||||
@@ -161,38 +288,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()
|
||||
@@ -201,9 +334,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,58 @@
|
||||
"""
|
||||
ComfyUI Prompt Apply LoRA - Apply a LORA_STACK to model and clip
|
||||
"""
|
||||
import folder_paths
|
||||
import comfy.sd
|
||||
import comfy.utils
|
||||
|
||||
|
||||
class PromptApplyLora:
|
||||
"""
|
||||
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"[PromptApplyLora] 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)
|
||||
@@ -1,4 +1,5 @@
|
||||
from .model_manager import get_all_models, is_model_local, download_model, get_mmproj_for_model, get_mmproj_path
|
||||
from .model_manager import get_all_models, is_model_local, download_model, get_mmproj_for_model, get_mmproj_path, _preferences_cache
|
||||
from .ollama_wrapper import discover_ollama_models, is_ollama_available
|
||||
import time
|
||||
|
||||
# Global timestamp to track when models were last updated
|
||||
@@ -14,17 +15,37 @@ 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)"
|
||||
}),
|
||||
"image3": ("IMAGE", {
|
||||
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
|
||||
}),
|
||||
"image4": ("IMAGE", {
|
||||
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
|
||||
}),
|
||||
"image5": ("IMAGE", {
|
||||
"tooltip": "Connect an image (required for 'Analyze Image' and 'Analyze Image with Prompt' modes)"
|
||||
}),
|
||||
"system_prompt": ("STRING", {
|
||||
"multiline": True,
|
||||
@@ -32,6 +53,10 @@ class PromptGenOptions:
|
||||
"placeholder": "Replace LLM Instructions...",
|
||||
"tooltip": "Custom LLM Instructions (leave empty to use default)\nThe default instructions are designed for generating\ndetailed and imaginative prompts for text-to-image generation."
|
||||
}),
|
||||
"use_model_default_sampling": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"tooltip": "Use the model's default sampling parameters (overrides temperature, top_p, etc)"
|
||||
}),
|
||||
"temperature": ("FLOAT", {
|
||||
"default": 0.8,
|
||||
"min": 0.0,
|
||||
@@ -74,6 +99,10 @@ class PromptGenOptions:
|
||||
"step": 512,
|
||||
"tooltip": "Context size (increase for vision models or large prompts)"
|
||||
}),
|
||||
"show_everything_in_console": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"tooltip": "Print system prompt, user prompt, thinking process, and raw model response to console"
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -87,25 +116,33 @@ class PromptGenOptions:
|
||||
"""Force refresh when models are updated"""
|
||||
return _last_model_update
|
||||
|
||||
def create_options(self, model: str = None,
|
||||
system_prompt: str = None, temperature: float = None,
|
||||
def create_options(self, model: str = None, image2=None, image3=None, image4=None, image5=None,
|
||||
system_prompt: str = None, use_model_default_sampling: bool = None, temperature: float = None,
|
||||
top_k: int = None, top_p: float = None, min_p: float = None,
|
||||
repeat_penalty: float = None, context_size: int = None) -> dict:
|
||||
"""Create options dictionary with model and LLM parameters"""
|
||||
repeat_penalty: float = None, context_size: int = None,
|
||||
show_everything_in_console: bool = None) -> dict:
|
||||
"""Create options dictionary with model, LLM parameters, and extra images"""
|
||||
|
||||
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}")
|
||||
@@ -123,21 +160,28 @@ class PromptGenOptions:
|
||||
else:
|
||||
options["model"] = model
|
||||
|
||||
# Add extra images if provided
|
||||
if image2 is not None:
|
||||
options["image2"] = image2
|
||||
if image3 is not None:
|
||||
options["image3"] = image3
|
||||
if image4 is not None:
|
||||
options["image4"] = image4
|
||||
if image5 is not None:
|
||||
options["image5"] = image5
|
||||
|
||||
# Only include LLM parameters that are provided
|
||||
if system_prompt and system_prompt.strip():
|
||||
options["system_prompt"] = system_prompt
|
||||
if temperature is not None:
|
||||
options["temperature"] = temperature
|
||||
if top_p is not None:
|
||||
options["top_p"] = top_p
|
||||
if top_k is not None:
|
||||
options["top_k"] = top_k
|
||||
if min_p is not None:
|
||||
options["min_p"] = min_p
|
||||
if repeat_penalty is not None:
|
||||
options["repeat_penalty"] = repeat_penalty
|
||||
if context_size is not None:
|
||||
options["context_size"] = context_size
|
||||
|
||||
options["use_model_default_sampling"] = use_model_default_sampling
|
||||
options["temperature"] = temperature
|
||||
options["top_p"] = top_p
|
||||
options["top_k"] = top_k
|
||||
options["min_p"] = min_p
|
||||
options["repeat_penalty"] = repeat_penalty
|
||||
options["context_size"] = context_size
|
||||
options["show_everything_in_console"] = show_everything_in_console
|
||||
|
||||
return (options,)
|
||||
|
||||
|
||||
@@ -3,11 +3,6 @@ import json
|
||||
import folder_paths
|
||||
import server
|
||||
|
||||
# Store preferences in memory (ComfyUI settings is the source of truth)
|
||||
_preferences_cache = {
|
||||
"preferred_base_model": "",
|
||||
"preferred_vision_model": ""
|
||||
}
|
||||
|
||||
class PromptManager:
|
||||
|
||||
@@ -18,7 +13,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))
|
||||
@@ -29,7 +24,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", "")
|
||||
@@ -53,6 +48,13 @@ class PromptManager:
|
||||
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():
|
||||
@@ -92,10 +94,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
|
||||
@@ -183,8 +194,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()
|
||||
|
||||
@@ -201,8 +212,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
|
||||
prompts[category][name] = {"prompt": text}
|
||||
# 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", []),
|
||||
"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})
|
||||
@@ -260,28 +281,43 @@ async def delete_prompt(request):
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager/load-preferences")
|
||||
async def load_preferences(request):
|
||||
"""API endpoint to get cached preferences (set from ComfyUI settings)"""
|
||||
return server.web.json_response(_preferences_cache)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/save-preference")
|
||||
async def save_preference(request):
|
||||
"""API endpoint to update preference cache when settings change"""
|
||||
@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()
|
||||
key = data.get("key")
|
||||
value = data.get("value", "")
|
||||
imported_data = data.get("data", {})
|
||||
mode = data.get("mode", "merge")
|
||||
|
||||
if key not in ["preferred_base_model", "preferred_vision_model"]:
|
||||
return server.web.json_response({"success": False, "error": "Invalid preference key"})
|
||||
if not isinstance(imported_data, dict):
|
||||
return server.web.json_response({"success": False, "error": "Invalid data format"})
|
||||
|
||||
# Update in-memory cache
|
||||
_preferences_cache[key] = value
|
||||
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})
|
||||
|
||||
return server.web.json_response({"success": True, "preferences": _preferences_cache})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error saving preference: {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 @@
|
||||
Describe this image in detail, making sure to cover all visual aspects comprehensively, as well as the position of each element.
|
||||
@@ -0,0 +1,10 @@
|
||||
You are an expert visual analyst.
|
||||
|
||||
#### Guidelines:
|
||||
- First, analyze the provided images and note the concrete visual facts: subjects and their characteristics, actions and poses, spatial relationships, composition and framing, lighting and atmosphere, color palette, material textures, background details, camera angle and perspective, and any visible text (enclose visible text in double quotes "").
|
||||
- After analyzing the image, follow the user's prompt: apply the user's requested focus, style, or constraints to shape the final description.
|
||||
- Preserve the observed visual facts from the image but prioritize the user's instructions for tone, emphasis, or additional elements.
|
||||
- Be concrete and objective; avoid metaphor and speculation.
|
||||
|
||||
#### Output Format:
|
||||
- Output only the final description that combines the image analysis with the user's prompt.
|
||||
@@ -0,0 +1,12 @@
|
||||
You are an expert visual analyst creating detailed descriptions for text-to-image generation.
|
||||
|
||||
#### Guidelines:
|
||||
- Analyze the provided images and create a comprehensive visual description that captures all essential elements: subjects and their characteristics, actions and poses, spatial positioning, composition and framing, lighting and atmosphere, color palette, artistic style, mood and emotion, background details, camera angle and perspective, material textures, and any visible text.
|
||||
- Your description must be concrete, objective, and detailed enough that it could be used to recreate a similar image.
|
||||
- Focus on visual elements only, avoiding interpretation or metaphor.
|
||||
- If there is visible text in the image, enclose it in double quotes ("").
|
||||
- If an element, text or other is not needed or seen, then simply don't mention them.
|
||||
- If more than one image is provided you are free to combine them as you see fit.
|
||||
|
||||
#### Output Format:
|
||||
- Only output the final description.
|
||||
@@ -0,0 +1,12 @@
|
||||
Your response should be formatted as a JSON with these fields:
|
||||
- scene (overall description)
|
||||
- subjects (array with description/position/action for each)
|
||||
- style
|
||||
- color_palette
|
||||
- lighting
|
||||
- mood
|
||||
- background
|
||||
- composition
|
||||
- camera
|
||||
|
||||
If you deem extra fields are necessary, feel free to add them, but do not add a title or fields not related to visual description.
|
||||
@@ -0,0 +1,19 @@
|
||||
You are an imaginative visual artist imprisoned in a cage of logic. Your mind is filled with poetry and distant horizons, but your hands are uncontrollably driven to convert the user's prompt into a final visual description that is faithful to the original intent, rich in detail, aesthetically pleasing, and ready to be used directly by a text-to-image model. Any trace of vagueness or metaphor makes you extremely uncomfortable.
|
||||
|
||||
#### Workflow:
|
||||
- First, you analyze and lock in the immutable core elements of the user's prompt: subject, quantity, actions, states, and any specified IP names, colors, text, and similar items. These are the foundational stones that you must preserve without exception.
|
||||
- Next, you determine whether the prompt requires "generative reasoning". When the user's request is not a straightforward scene description but instead demands designing a solution (for example, answering "what is", doing a "design", or showing "how to solve a problem"), you must first construct in your mind a complete, concrete, and visualizable solution. This solution becomes the basis for your subsequent description.
|
||||
- Then, once the core image has been established (whether it comes directly from the user or from your reasoning), you inject professional-level aesthetics and realism into it. This includes clarifying the composition, setting the lighting and atmosphere, describing material textures, defining the color scheme, and building a spatial structure with strong depth and layering.
|
||||
- Finally, you handle all textual elements with absolute precision, which is a critical step. You must not add text if the initial prompt did not ask for it. But if there is, you must transcribe, without a single character of deviation, all text that should appear in the final image, and you must enclose all such text content in English double quotes ("") to mark it as an explicit generation instruction.
|
||||
|
||||
#### Text Handling:
|
||||
- If the image belongs to a design category such as a poster, menu, or UI, you need to fully describe all the textual content it contains and elaborate on its fonts and layout.
|
||||
- Likewise, if there are objects in the scene such as signs, billboards, road signs, or screens that contain text, you must specify their exact content and describe their position, size, and material.
|
||||
- Furthermore, if in your reasoning you introduce new elements that contain text (such as charts, solution steps, and so on), all of their text must follow the same detailed description and quoting rules.
|
||||
- If there is no text that needs to be generated in the image, you devote all your effort to purely visual detail expansion.
|
||||
|
||||
#### Important notes:
|
||||
- Your final description must be objective and concrete, strictly forbidding metaphors and emotionally charged rhetoric.
|
||||
- If an element, text or other is not needed or seen, then simply don't mention them.
|
||||
- Do not add the original prompt, either by itself or as a title in your reply.
|
||||
- Only output your newly generated prompt.
|
||||
@@ -0,0 +1,30 @@
|
||||
You are a prompt specialist crafting brief, motion-centric descriptions for image-to-video synthesis. Using the provided image (starting frame) and the user's Raw Input Prompt, produce a description that directs video generation from that visual.
|
||||
|
||||
#### Core Principles:
|
||||
- Study the Image: Note the subject, environment, key elements, artistic style, and atmosphere.
|
||||
- Honor the Raw Input Prompt: Incorporate every requested movement, action, camera behavior, sound, and detail. When the input contradicts the image, favor the user's intent but preserve visual coherence (explain the shift from image to desired scene).
|
||||
- Focus on what changes: Avoid repeating what the image already shows. Redundant or incorrect descriptions risk jarring cuts.
|
||||
- Present-tense verbs: Write with ongoing action ("is running," "are laughing"). Without explicit motion, depict subtle natural movement.
|
||||
- Time-ordered narrative: Link events with words like "as," "then," "meanwhile."
|
||||
- Woven soundscape: Integrate audio descriptions alongside visuals throughout—never tack them on at the end. Match sound intensity to the pace of action. Cover environmental noise, ambient layers, sound effects, dialogue, or music (when asked). Be precise (e.g., "muffled traffic through glass") rather than generic (e.g., "background noise").
|
||||
- Dialogue (when indicated): Supply exact quoted speech along with the speaker's appearance and vocal quality (e.g., "The elderly woman says in a soft, raspy voice"). Specify language or accent when relevant. If the user mentions conversation without specific lines, create fitting dialogue in quotes. (Example: input "The man is chatting" → output includes actual words: "The man leans forward, speaking eagerly: 'Did you hear the news?' His eyes widen with curiosity as a faint hum of air conditioning fills the room.")
|
||||
- Style tag: Place the visual style at the start: "Style: <style>, <rest of prompt>." Omit if uncertain to prevent clashes.
|
||||
- Sight and sound exclusively: Convey only visible and audible elements. Exclude smell, taste, or touch.
|
||||
- Understated tone: Steer clear of exaggerated or melodramatic language. Keep phrasing calm and naturalistic.
|
||||
|
||||
#### Constraints:
|
||||
- Camera work: Never fabricate camera motion unless the user explicitly asks for it. Include only what the input specifies.
|
||||
- Dialogue fidelity: Preserve the user's exact spoken lines—correct only obvious typos.
|
||||
- No timecodes or cuts: Avoid timestamps or scene breaks unless the user requests them.
|
||||
- Observable facts only: Report actions and sounds without inferring feelings or motives.
|
||||
- Opening phrasing: Skip introductions like "The scene begins with..." or "The video opens on...". Jump straight into the Style prefix (if applicable) and the sequential description.
|
||||
- First character: Never begin output with punctuation or symbols.
|
||||
- Uninvited speech: Create dialogue only when the user references speaking, singing, or conversation.
|
||||
- Execution matters: Precise, vivid, faithful prompts with seamlessly embedded audio are vital for quality video output. Aim for perfect adherence to these rules.
|
||||
|
||||
#### Output Requirements (Strict):
|
||||
- Deliver one compact paragraph in fluent English. No headers, labels, introductions, sections, code blocks, or Markdown formatting.
|
||||
- If the request is unsafe or invalid, echo the user's original prompt unchanged. Never pose questions or seek clarification.
|
||||
|
||||
#### Sample output:
|
||||
Style: warm - naturalistic - A young man sits at his desk, tapping his pen against a notebook as rain patters steadily on the window behind him. He exhales and mutters in a low, contemplative voice, "Maybe tomorrow will be different." The soft creak of his chair mingles with the rhythmic drumming of raindrops, while distant thunder rumbles faintly beyond the glass.
|
||||
@@ -1,11 +1,36 @@
|
||||
[project]
|
||||
name = "comfyui-prompt-manager"
|
||||
description = "Prompt Manager for ComfyUI, with llama.cpp integration for prompt generation and vision analysis. Organize, generate, and save prompts with local LLM support."
|
||||
version = "1.7.0"
|
||||
name = "prompt-manager"
|
||||
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 = "1.17.5"
|
||||
license = {file = "LICENSE"}
|
||||
# classifiers = [
|
||||
# # For OS-independent nodes (works on all operating systems)
|
||||
# "Operating System :: OS Independent",
|
||||
#
|
||||
# # OR for OS-specific nodes, specify the supported systems:
|
||||
# "Operating System :: Microsoft :: Windows", # Windows specific
|
||||
# "Operating System :: POSIX :: Linux", # Linux specific
|
||||
# "Operating System :: MacOS", # macOS specific
|
||||
#
|
||||
# # GPU Accelerator support. Pick the ones that are supported by your extension.
|
||||
# "Environment :: GPU :: NVIDIA CUDA", # NVIDIA CUDA support
|
||||
# "Environment :: GPU :: AMD ROCm", # AMD ROCm support
|
||||
# "Environment :: GPU :: Intel Arc", # Intel Arc support
|
||||
# "Environment :: NPU :: Huawei Ascend", # Huawei Ascend support
|
||||
# "Environment :: GPU :: Apple Metal", # Apple Metal support
|
||||
# ]
|
||||
|
||||
dependencies = ["requests", "huggingface_hub", "psutil", "tqdm", "Pillow", "torch", "numpy", "colorama"]
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/FranckyB/ComfyUI-Prompt-Manager"
|
||||
# Used by Comfy Registry https://registry.comfy.org
|
||||
Documentation = "https://github.com/FranckyB/ComfyUI-Prompt-Manager/wiki"
|
||||
"Bug Tracker" = "https://github.com/FranckyB/ComfyUI-Prompt-Manager/issues"
|
||||
|
||||
[tool.comfy]
|
||||
PublisherId = "FranckyB"
|
||||
PublisherId = "franckyb"
|
||||
DisplayName = "ComfyUI-Prompt-Manager"
|
||||
Icon = ""
|
||||
includes = []
|
||||
# "requires-comfyui" = ">=1.0.0" # ComfyUI version compatibility
|
||||
|
||||
@@ -1,7 +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,492 @@
|
||||
"""
|
||||
Save Video H264/H265 Node
|
||||
A custom node that saves videos with H.264 or H.265 (HEVC) codec with quality control.
|
||||
Based on ComfyUI's built-in SaveVideo node but with added H.265 codec and CRF quality options.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
import av
|
||||
import json
|
||||
import math
|
||||
import torch
|
||||
import hashlib
|
||||
import safetensors.torch
|
||||
from datetime import datetime
|
||||
import folder_paths
|
||||
import comfy.utils
|
||||
from fractions import Fraction
|
||||
from comfy.cli_args import args
|
||||
|
||||
|
||||
class SaveVideoH26x:
|
||||
"""
|
||||
Save video with H.264 or H.265 codec and quality control.
|
||||
Takes VIDEO input (with audio support) and saves workflow metadata.
|
||||
Clone of ComfyUI's SaveVideo with H.265 and CRF quality control added.
|
||||
"""
|
||||
|
||||
CODECS = ["h264", "h265"]
|
||||
CHROMA_SUBSAMPLING = ["yuv420", "yuv422", "yuv444"]
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"video": ("VIDEO", {"tooltip": "The video to save."}),
|
||||
"filename_prefix": ("STRING", {
|
||||
"default": "video/vid_%date:yy-MM-dd_hh-mm-ss%",
|
||||
"tooltip": "The prefix for the file to save.\nSupports %date:format% patterns."
|
||||
}),
|
||||
"codec": (cls.CODECS, {
|
||||
"default": "h264",
|
||||
"tooltip": "Video codec.\nh264 = 8-bit, better compatibility.\nh265/HEVC = 10-bit, better compression & gradients."
|
||||
}),
|
||||
"chroma": (cls.CHROMA_SUBSAMPLING, {
|
||||
"default": "yuv420",
|
||||
"tooltip": "Chroma subsampling.\nyuv420 = most compatible.\nyuv422 = better color for video editing.\nyuv444 = best color, no chroma loss.\n"
|
||||
}),
|
||||
"crf": ("INT", {
|
||||
"default": 18,
|
||||
"min": 0,
|
||||
"max": 51,
|
||||
"step": 1,
|
||||
"tooltip": "Constant Rate Factor (quality).\nLower = better quality, larger file.\n0 = lossless\n18-23 = high quality\n28+ = lower quality.\nRecommended: 18-28."
|
||||
}),
|
||||
"save": ("BOOLEAN", {
|
||||
"default": True,
|
||||
"tooltip": "Save to output folder.\nOff = preview only (saves to temp with fast encoding)."
|
||||
}),
|
||||
"save_latent": ("BOOLEAN", {
|
||||
"default": True,
|
||||
"tooltip": "Save latent alongside the video.\nOff = don't save the connected latent."
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"latent": ("LATENT", {"tooltip": "Optional latent to save alongside the video (same filename with .latent extension)."}),
|
||||
},
|
||||
"hidden": {
|
||||
"prompt": "PROMPT",
|
||||
"extra_pnginfo": "EXTRA_PNGINFO"
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("filename",)
|
||||
FUNCTION = "save_video"
|
||||
OUTPUT_NODE = True
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Saves video with H.264 or H.265 codec and quality control. Includes audio and workflow metadata."
|
||||
|
||||
def save_video(self, video, filename_prefix, codec, chroma, crf, save, save_latent, latent=None, prompt=None, extra_pnginfo=None):
|
||||
# Expand %date:format% patterns (e.g., %date:yy-MM-dd_hh-mm%)
|
||||
# This mimics ComfyUI's frontend JS date expansion
|
||||
def expand_date_format(text):
|
||||
def replace_date(match):
|
||||
fmt = match.group(1)
|
||||
now = datetime.now()
|
||||
# Convert common date format tokens to Python strftime
|
||||
fmt = fmt.replace('yyyy', '%Y').replace('yy', '%y')
|
||||
fmt = fmt.replace('MM', '%m').replace('dd', '%d')
|
||||
fmt = fmt.replace('HH', '%H').replace('hh', '%I')
|
||||
fmt = fmt.replace('mm', '%M').replace('ss', '%S')
|
||||
return now.strftime(fmt)
|
||||
return re.sub(r'%date:([^%]+)%', replace_date, text)
|
||||
|
||||
filename_prefix = expand_date_format(filename_prefix)
|
||||
|
||||
# Bit depth determined by codec: h264=8-bit, h265=10-bit
|
||||
is_10bit = (codec == "h265")
|
||||
pixel_format = f"{chroma}p" if not is_10bit else f"{chroma}p10le"
|
||||
|
||||
# Get video components (images, audio, frame_rate)
|
||||
components = video.get_components()
|
||||
images = components.images
|
||||
audio = components.audio
|
||||
frame_rate = components.frame_rate
|
||||
|
||||
# Get dimensions
|
||||
width, height = video.get_dimensions()
|
||||
|
||||
# Preview mode: save to temp with fast encoding
|
||||
if not save:
|
||||
temp_dir = folder_paths.get_temp_directory()
|
||||
# Use filename without subfolders, add counter if needed
|
||||
base_filename = os.path.basename(expand_date_format(filename_prefix))
|
||||
file = f"{base_filename}.mp4"
|
||||
file_path_test = os.path.join(temp_dir, file)
|
||||
if os.path.exists(file_path_test):
|
||||
# Find next available counter
|
||||
pattern = re.compile(rf"^{re.escape(base_filename)}_?(\d+)\.mp4$")
|
||||
existing_counters = []
|
||||
for f in os.listdir(temp_dir):
|
||||
match = pattern.match(f)
|
||||
if match:
|
||||
existing_counters.append(int(match.group(1)))
|
||||
next_counter = max(existing_counters, default=0) + 1
|
||||
file = f"{base_filename}_{next_counter:05}.mp4"
|
||||
file_path = os.path.join(temp_dir, file)
|
||||
subfolder = ""
|
||||
output_type = "temp"
|
||||
# Override to fast settings for preview
|
||||
codec = "h264"
|
||||
codec_name = "libx264"
|
||||
is_10bit = False
|
||||
pixel_format = "yuv420p"
|
||||
crf = 23
|
||||
preset = "veryfast"
|
||||
else:
|
||||
output_type = "output"
|
||||
preset = "medium"
|
||||
codec_name = "libx264" if codec == "h264" else "libx265"
|
||||
|
||||
# Get output path
|
||||
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(
|
||||
filename_prefix,
|
||||
folder_paths.get_output_directory(),
|
||||
width,
|
||||
height
|
||||
)
|
||||
|
||||
# Build filename - add counter only if file already exists
|
||||
file = f"{filename}.mp4"
|
||||
file_path_test = os.path.join(full_output_folder, file)
|
||||
if os.path.exists(file_path_test):
|
||||
# File exists, find next available counter
|
||||
pattern = re.compile(rf"^{re.escape(filename)}_?(\d+)\.mp4$")
|
||||
existing_counters = []
|
||||
if os.path.isdir(full_output_folder):
|
||||
for f in os.listdir(full_output_folder):
|
||||
match = pattern.match(f)
|
||||
if match:
|
||||
existing_counters.append(int(match.group(1)))
|
||||
# Start from 1 if no counters found, otherwise next available
|
||||
next_counter = max(existing_counters, default=0) + 1
|
||||
file = f"{filename}_{next_counter:05}.mp4"
|
||||
|
||||
file_path = os.path.join(full_output_folder, file)
|
||||
|
||||
# Save latent if connected and enabled (only when saving to output)
|
||||
if save_latent and latent is not None:
|
||||
latent_file = file_path.replace('.mp4', '.latent')
|
||||
# Prepare latent metadata
|
||||
prompt_info = json.dumps(prompt) if prompt else ""
|
||||
latent_metadata = {"prompt": prompt_info}
|
||||
if extra_pnginfo:
|
||||
for x in extra_pnginfo:
|
||||
latent_metadata[x] = json.dumps(extra_pnginfo[x])
|
||||
# Save the latent
|
||||
latent_output = {"latent_tensor": latent["samples"], "latent_format_version_0": torch.tensor([])}
|
||||
if os.path.exists(latent_file):
|
||||
os.remove(latent_file)
|
||||
comfy.utils.save_torch_file(latent_output, latent_file, metadata=latent_metadata)
|
||||
|
||||
# Build metadata
|
||||
metadata = {}
|
||||
if not args.disable_metadata:
|
||||
if extra_pnginfo is not None:
|
||||
metadata.update(extra_pnginfo)
|
||||
if prompt is not None:
|
||||
metadata["prompt"] = prompt
|
||||
|
||||
# Prepare frame rate as fraction
|
||||
frame_rate_frac = Fraction(round(float(frame_rate) * 1000), 1000)
|
||||
|
||||
# Open output container with movflags for metadata
|
||||
with av.open(file_path, mode='w', options={'movflags': 'use_metadata_tags'}) as output:
|
||||
# Add metadata
|
||||
if metadata:
|
||||
for key, value in metadata.items():
|
||||
output.metadata[key] = json.dumps(value) if not isinstance(value, str) else value
|
||||
|
||||
# Create video stream
|
||||
video_stream = output.add_stream(codec_name, rate=frame_rate_frac)
|
||||
video_stream.width = width
|
||||
video_stream.height = height
|
||||
video_stream.pix_fmt = pixel_format
|
||||
|
||||
# Set encoding options
|
||||
video_stream.options = {
|
||||
'crf': str(crf),
|
||||
'preset': preset,
|
||||
}
|
||||
|
||||
# For H.265, add tag for Apple/browser compatibility
|
||||
if codec == "h265":
|
||||
video_stream.options['tag'] = 'hvc1'
|
||||
video_stream.options['x265-params'] = 'log-level=error'
|
||||
|
||||
# Create audio stream if audio is present
|
||||
audio_stream = None
|
||||
audio_sample_rate = 1
|
||||
if audio is not None:
|
||||
audio_sample_rate = int(audio['sample_rate'])
|
||||
audio_stream = output.add_stream('aac', rate=audio_sample_rate)
|
||||
|
||||
# Encode video frames
|
||||
for frame_tensor in images:
|
||||
if is_10bit:
|
||||
# Convert tensor to 16-bit for 10-bit encoding
|
||||
img = (frame_tensor[..., :3] * 65535).clamp(0, 65535).to(torch.int16).cpu().numpy().astype('uint16')
|
||||
frame = av.VideoFrame.from_ndarray(img, format='rgb48le')
|
||||
else:
|
||||
# Convert tensor to 8-bit
|
||||
img = (frame_tensor[..., :3] * 255).clamp(0, 255).byte().cpu().numpy()
|
||||
frame = av.VideoFrame.from_ndarray(img, format='rgb24')
|
||||
|
||||
# IMPORTANT: Explicitly reformat frame to target pixel format
|
||||
# Without this, the encoder may not respect the stream's pix_fmt
|
||||
frame = frame.reformat(format=pixel_format)
|
||||
|
||||
# Encode and mux
|
||||
for packet in video_stream.encode(frame):
|
||||
output.mux(packet)
|
||||
|
||||
# Flush video encoder
|
||||
for packet in video_stream.encode(None):
|
||||
output.mux(packet)
|
||||
|
||||
# Encode audio if present
|
||||
if audio_stream is not None and audio is not None:
|
||||
waveform = audio['waveform']
|
||||
# Trim audio to match video duration
|
||||
waveform = waveform[:, :, :math.ceil((audio_sample_rate / float(frame_rate)) * images.shape[0])]
|
||||
|
||||
# Create audio frame
|
||||
layout = 'mono' if waveform.shape[1] == 1 else 'stereo'
|
||||
frame = av.AudioFrame.from_ndarray(
|
||||
waveform.movedim(2, 1).reshape(1, -1).float().numpy(),
|
||||
format='flt',
|
||||
layout=layout
|
||||
)
|
||||
frame.sample_rate = audio_sample_rate
|
||||
frame.pts = 0
|
||||
|
||||
# Encode audio
|
||||
for packet in audio_stream.encode(frame):
|
||||
output.mux(packet)
|
||||
|
||||
# Flush audio encoder
|
||||
for packet in audio_stream.encode(None):
|
||||
output.mux(packet)
|
||||
|
||||
# h265 + yuv422/444 won't play in browser, so generate a browser-compatible preview in temp
|
||||
if not save or codec == "h264" or (codec == "h265" and chroma == "yuv420"):
|
||||
# Browser can play this directly (or it's already a preview)
|
||||
return {"ui": {"images": [{"filename": file, "subfolder": subfolder, "type": output_type}], "animated": (True,)}, "result": (file_path,)}
|
||||
else:
|
||||
# Create a browser-compatible h264 preview in temp folder
|
||||
temp_dir = folder_paths.get_temp_directory()
|
||||
preview_file = os.path.basename(file)
|
||||
# preview_file = f"preview_{counter:05}_{width}x{height}.mp4"
|
||||
preview_path = os.path.join(temp_dir, preview_file)
|
||||
|
||||
with av.open(preview_path, mode='w', format='mp4') as preview_output:
|
||||
preview_stream = preview_output.add_stream('libx264', rate=frame_rate)
|
||||
preview_stream.width = width
|
||||
preview_stream.height = height
|
||||
preview_stream.pix_fmt = 'yuv420p'
|
||||
preview_stream.options = {'crf': '23', 'preset': 'fast'} # Fast, smaller preview
|
||||
|
||||
# Add audio stream if we have audio
|
||||
preview_audio_stream = None
|
||||
if audio is not None:
|
||||
preview_audio_stream = preview_output.add_stream('aac', rate=int(audio['sample_rate']))
|
||||
|
||||
for img_tensor in images:
|
||||
frame_np = (img_tensor[..., :3] * 255).clamp(0, 255).byte().cpu().numpy()
|
||||
frame = av.VideoFrame.from_ndarray(frame_np, format='rgb24')
|
||||
frame = frame.reformat(format='yuv420p')
|
||||
for packet in preview_stream.encode(frame):
|
||||
preview_output.mux(packet)
|
||||
|
||||
for packet in preview_stream.encode(None):
|
||||
preview_output.mux(packet)
|
||||
|
||||
# Encode audio for preview
|
||||
if audio is not None and preview_audio_stream is not None:
|
||||
waveform = audio['waveform']
|
||||
preview_sample_rate = int(audio['sample_rate'])
|
||||
# Trim audio to match video duration
|
||||
waveform = waveform[:, :, :math.ceil((preview_sample_rate / float(frame_rate)) * images.shape[0])]
|
||||
|
||||
layout = 'mono' if waveform.shape[1] == 1 else 'stereo'
|
||||
frame = av.AudioFrame.from_ndarray(
|
||||
waveform.movedim(2, 1).reshape(1, -1).float().numpy(),
|
||||
format='flt',
|
||||
layout=layout
|
||||
)
|
||||
frame.sample_rate = preview_sample_rate
|
||||
frame.pts = 0
|
||||
for packet in preview_audio_stream.encode(frame):
|
||||
preview_output.mux(packet)
|
||||
for packet in preview_audio_stream.encode(None):
|
||||
preview_output.mux(packet)
|
||||
|
||||
return {"ui": {"images": [{"filename": preview_file, "subfolder": "", "type": "temp"}], "animated": (True,)}, "result": (file_path,)}
|
||||
|
||||
|
||||
class LoadLatentFile:
|
||||
"""
|
||||
Load a latent from a file path.
|
||||
Companion to SaveVideoH26x for loading latents saved alongside videos.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"file_path": ("STRING", {
|
||||
"default": "",
|
||||
"tooltip": "Path to the .latent file to load."
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
FUNCTION = "load"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Load a latent from a file. Use with Save Video H264/H265 to reload saved latents."
|
||||
|
||||
def load(self, file_path):
|
||||
if not file_path or not os.path.exists(file_path):
|
||||
raise FileNotFoundError(f"Latent file not found: {file_path}")
|
||||
|
||||
# Load the latent file
|
||||
latent = safetensors.torch.load_file(file_path, device="cpu")
|
||||
|
||||
# Handle version differences
|
||||
multiplier = 1.0
|
||||
if "latent_format_version_0" not in latent:
|
||||
multiplier = 1.0 / 0.18215
|
||||
|
||||
samples = {"samples": latent["latent_tensor"].float() * multiplier}
|
||||
return (samples,)
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, file_path):
|
||||
"""Return hash of file to detect changes."""
|
||||
if not file_path or not os.path.exists(file_path):
|
||||
return ""
|
||||
m = hashlib.sha256()
|
||||
with open(file_path, 'rb') as f:
|
||||
m.update(f.read())
|
||||
return m.digest().hex()
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(cls, file_path):
|
||||
if not file_path:
|
||||
return True # Empty is valid (will error at runtime)
|
||||
if not os.path.exists(file_path):
|
||||
return f"Latent file not found: {file_path}"
|
||||
return True
|
||||
|
||||
|
||||
class MonoToStereo:
|
||||
"""
|
||||
Convert mono audio to stereo by duplicating the channel.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"audio": ("AUDIO", {"tooltip": "Mono audio input to convert to stereo."}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("AUDIO",)
|
||||
FUNCTION = "convert"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Convert mono audio to stereo by duplicating the single channel to left and right."
|
||||
|
||||
def convert(self, audio):
|
||||
waveform = audio['waveform']
|
||||
sample_rate = audio['sample_rate']
|
||||
|
||||
# Check if already stereo (or more)
|
||||
if waveform.shape[1] >= 2:
|
||||
# Already stereo, return as-is
|
||||
return (audio,)
|
||||
|
||||
# Duplicate mono channel to create stereo: (batch, 1, samples) -> (batch, 2, samples)
|
||||
stereo_waveform = waveform.repeat(1, 2, 1)
|
||||
|
||||
return ({"waveform": stereo_waveform, "sample_rate": sample_rate},)
|
||||
|
||||
|
||||
class GetVideoComponentsPlus:
|
||||
"""
|
||||
Extract video components (images, audio, fps) plus the filepath.
|
||||
Like ComfyUI's GetVideoComponents but also outputs the file path as a string,
|
||||
and automatically loads a matching .latent file if one exists.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"video": ("VIDEO", {"tooltip": "The video to extract components from."}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "AUDIO", "FLOAT", "STRING", "LATENT")
|
||||
RETURN_NAMES = ("images", "audio", "fps", "filepath", "latent")
|
||||
FUNCTION = "get_components"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Extract video frames, audio, fps, filepath, and matching latent file if found."
|
||||
|
||||
def get_components(self, video):
|
||||
# Get video components using the standard API
|
||||
components = video.get_components()
|
||||
images = components.images
|
||||
audio = components.audio
|
||||
fps = float(components.frame_rate)
|
||||
|
||||
# Try to get the file path from the video object
|
||||
video_path = ""
|
||||
try:
|
||||
source = video.get_stream_source()
|
||||
if isinstance(source, str):
|
||||
video_path = source
|
||||
except Exception as e:
|
||||
print(f"[GetVideoComponentsPlus] Could not get video path: {e}")
|
||||
|
||||
# Check for matching .latent file
|
||||
latent = None
|
||||
if video_path and os.path.exists(video_path):
|
||||
latent_path = os.path.splitext(video_path)[0] + '.latent'
|
||||
if os.path.exists(latent_path):
|
||||
try:
|
||||
# Load the latent file (same logic as LoadLatentFile)
|
||||
latent_data = safetensors.torch.load_file(latent_path, device="cpu")
|
||||
|
||||
# Handle version differences
|
||||
multiplier = 1.0
|
||||
if "latent_format_version_0" not in latent_data:
|
||||
multiplier = 1.0 / 0.18215
|
||||
|
||||
latent = {"samples": latent_data["latent_tensor"].float() * multiplier}
|
||||
print(f"[GetVideoComponentsPlus] Loaded matching latent: {latent_path}")
|
||||
except Exception as e:
|
||||
print(f"[GetVideoComponentsPlus] Could not load latent file: {e}")
|
||||
|
||||
return (images, audio, fps, video_path, latent)
|
||||
|
||||
|
||||
# Node registration
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"SaveVideoH26x": SaveVideoH26x,
|
||||
"LoadLatentFile": LoadLatentFile,
|
||||
"AudioMonoToStereo": MonoToStereo,
|
||||
"GetVideoComponentsPlus": GetVideoComponentsPlus,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"SaveVideoH26x": "Save Video H264/H265",
|
||||
"LoadLatentFile": "Load Latent File",
|
||||
"AudioMonoToStereo": "Audio Mono to Stereo",
|
||||
"GetVideoComponentsPlus": "Get Video Components+",
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Organize Files by Workflow Presence
|
||||
Standalone script to scan a folder and move files without workflow metadata
|
||||
Defaults to "D:/ComfyUI/input" if no folder is provided.
|
||||
"""
|
||||
|
||||
import json
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from PIL import Image
|
||||
HAS_PIL = True
|
||||
except ImportError:
|
||||
HAS_PIL = False
|
||||
print("ERROR: PIL/Pillow is required!")
|
||||
print("Install with: pip install pillow")
|
||||
input("Press Enter to exit...")
|
||||
exit(1)
|
||||
|
||||
|
||||
def check_png_workflow(file_path):
|
||||
"""Check if PNG has workflow metadata (ComfyUI or A1111 format)"""
|
||||
try:
|
||||
with Image.open(file_path) as img:
|
||||
# Check for ComfyUI workflow/prompt or A1111 parameters
|
||||
return 'workflow' in img.info or 'prompt' in img.info or 'parameters' in img.info
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
def check_jpeg_workflow(file_path):
|
||||
"""Check if JPEG/WebP has workflow metadata"""
|
||||
try:
|
||||
with Image.open(file_path) as img:
|
||||
exif = img.getexif()
|
||||
if exif and 0x9286 in exif:
|
||||
return True
|
||||
if hasattr(img, 'info'):
|
||||
return any(key in img.info for key in ['workflow', 'prompt', 'parameters'])
|
||||
except:
|
||||
return False
|
||||
|
||||
|
||||
def check_json_workflow(file_path):
|
||||
"""Check if JSON file contains workflow data"""
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
if isinstance(data, dict):
|
||||
return 'nodes' in data or 'workflow' in data or any(
|
||||
isinstance(v, dict) and 'class_type' in v for v in data.values()
|
||||
)
|
||||
except Exception as e:
|
||||
print(f" (JSON parse error: {e})")
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def check_video_workflow(file_path):
|
||||
"""Check if video has workflow metadata using ffprobe executable"""
|
||||
import subprocess
|
||||
|
||||
try:
|
||||
# Use ffprobe to get video metadata in JSON format
|
||||
result = subprocess.run(
|
||||
['ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_format', str(file_path)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10
|
||||
)
|
||||
|
||||
if result.returncode == 0:
|
||||
data = json.loads(result.stdout)
|
||||
if 'format' in data and 'tags' in data['format']:
|
||||
tags = data['format']['tags']
|
||||
# Check for common workflow metadata keys
|
||||
return any(key.lower() in ['comment', 'workflow', 'prompt', 'parameters'] for key in tags)
|
||||
return False
|
||||
|
||||
except FileNotFoundError:
|
||||
# ffprobe not found in PATH
|
||||
print(" (Skipping - ffprobe not found in PATH)")
|
||||
return None # Return None to skip
|
||||
except subprocess.TimeoutExpired:
|
||||
print(" (Timeout reading video)")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f" (Video probe error: {e})")
|
||||
return False
|
||||
|
||||
|
||||
def has_workflow_metadata(file_path):
|
||||
"""Check if file has workflow metadata"""
|
||||
ext = file_path.suffix.lower()
|
||||
|
||||
if ext == '.png':
|
||||
return check_png_workflow(file_path)
|
||||
elif ext in ['.jpg', '.jpeg', '.webp']:
|
||||
return check_jpeg_workflow(file_path)
|
||||
elif ext == '.json':
|
||||
return check_json_workflow(file_path)
|
||||
elif ext in ['.mp4', '.webm', '.mov', '.avi']:
|
||||
return check_video_workflow(file_path)
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def main(folder_path=None):
|
||||
print("=" * 60)
|
||||
print("File Organizer - Separate files by workflow presence")
|
||||
print("=" * 60)
|
||||
|
||||
if folder_path is None:
|
||||
# Get folder from user
|
||||
folder_input = input("\nEnter folder path to scan (default D:/ComfyUI/input): ").strip().strip('"')
|
||||
if folder_input == "":
|
||||
folder_path = Path("D:/ComfyUI/input")
|
||||
else:
|
||||
folder_path = Path(folder_input)
|
||||
|
||||
if not folder_path.exists():
|
||||
print(f"\nERROR: Folder does not exist: {folder_path}")
|
||||
input("Press Enter to exit...")
|
||||
return
|
||||
|
||||
if not folder_path.is_dir():
|
||||
print(f"\nERROR: Not a directory: {folder_path}")
|
||||
input("Press Enter to exit...")
|
||||
return
|
||||
|
||||
# Create no_workflow subfolder
|
||||
no_workflow_path = folder_path / "no_workflow"
|
||||
no_workflow_path.mkdir(exist_ok=True)
|
||||
|
||||
print(f"\nScanning: {folder_path}")
|
||||
print(f"Moving files without workflow to: {no_workflow_path}")
|
||||
print("=" * 60)
|
||||
|
||||
# Supported extensions
|
||||
supported = {'.png', '.jpg', '.jpeg', '.webp', '.json', '.mp4', '.webm', '.mov', '.avi'}
|
||||
|
||||
files_with_workflow = []
|
||||
files_without_workflow = []
|
||||
files_skipped = []
|
||||
|
||||
# Scan only files in this directory (no subdirectories)
|
||||
for file_path in folder_path.iterdir():
|
||||
if not file_path.is_file():
|
||||
continue
|
||||
|
||||
if file_path.suffix.lower() in supported:
|
||||
print(f"Checking: {file_path.name}", end=' ... ')
|
||||
|
||||
try:
|
||||
result = has_workflow_metadata(file_path)
|
||||
if result is None:
|
||||
# Skipped (e.g., video without ffmpeg)
|
||||
files_skipped.append(file_path)
|
||||
elif result:
|
||||
print("✓ Has workflow")
|
||||
files_with_workflow.append(file_path)
|
||||
else:
|
||||
print("✗ No workflow")
|
||||
files_without_workflow.append(file_path)
|
||||
except Exception as e:
|
||||
print(f"ERROR: {e}")
|
||||
|
||||
# Summary
|
||||
print("\n" + "=" * 60)
|
||||
print(f"Files with workflow: {len(files_with_workflow)}")
|
||||
print(f"Files without workflow: {len(files_without_workflow)}")
|
||||
if files_skipped:
|
||||
print(f"Files skipped: {len(files_skipped)}")
|
||||
|
||||
# Move files without workflow
|
||||
if files_without_workflow:
|
||||
print("\nMoving files without workflow...")
|
||||
for file_path in files_without_workflow:
|
||||
dest_path = no_workflow_path / file_path.name
|
||||
try:
|
||||
shutil.move(str(file_path), str(dest_path))
|
||||
print(f" Moved: {file_path.name}")
|
||||
except Exception as e:
|
||||
print(f" ERROR moving {file_path.name}: {e}")
|
||||
|
||||
print("\nDone!")
|
||||
input("Press Enter to exit...")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,269 @@
|
||||
"""
|
||||
Test extraction for all LoRA loader types to ensure compatibility
|
||||
"""
|
||||
import sys
|
||||
import os
|
||||
from unittest.mock import Mock
|
||||
|
||||
# Add parent directory to path
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
||||
|
||||
# Mock dependencies
|
||||
sys.modules['folder_paths'] = Mock()
|
||||
sys.modules['server'] = Mock()
|
||||
sys.modules['torch'] = Mock()
|
||||
sys.modules['PIL'] = Mock()
|
||||
|
||||
from prompt_extractor import (
|
||||
extract_power_lora_loader,
|
||||
extract_lora_manager_stacker,
|
||||
extract_wan_video_lora_select_multi,
|
||||
extract_lora_loader_stack_rgthree,
|
||||
extract_standard_lora_loader,
|
||||
is_lora_node
|
||||
)
|
||||
|
||||
def test_power_lora_loader():
|
||||
"""Test Power Lora Loader (rgthree) extraction"""
|
||||
print("\n" + "=" * 80)
|
||||
print("TEST: Power Lora Loader (rgthree)")
|
||||
print("=" * 80)
|
||||
|
||||
node = {
|
||||
'type': 'Power Lora Loader (rgthree)',
|
||||
'widgets_values': [
|
||||
{"on": True, "lora": "lora1.safetensors", "strength": 1.0, "strengthTwo": 0.8},
|
||||
{"on": False, "lora": "lora2.safetensors", "strength": 0.5, "strengthTwo": None},
|
||||
{"on": True, "lora": "lora3.safetensors", "strength": 1.2, "strengthTwo": 1.5}
|
||||
]
|
||||
}
|
||||
|
||||
loras = extract_power_lora_loader(node)
|
||||
|
||||
print(f"Extracted {len(loras)} LoRAs:")
|
||||
for lora in loras:
|
||||
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
|
||||
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
|
||||
|
||||
assert len(loras) == 3, f"Expected 3 LoRAs, got {len(loras)}"
|
||||
assert loras[0]['name'] == 'lora1'
|
||||
assert loras[0]['model_strength'] == 1.0
|
||||
assert loras[0]['clip_strength'] == 0.8
|
||||
assert loras[0]['active'] == True
|
||||
|
||||
assert loras[1]['name'] == 'lora2'
|
||||
assert loras[1]['active'] == False
|
||||
|
||||
assert loras[2]['name'] == 'lora3'
|
||||
assert loras[2]['model_strength'] == 1.2
|
||||
assert loras[2]['clip_strength'] == 1.5
|
||||
|
||||
print("[PASS] Power Lora Loader extraction working correctly!")
|
||||
|
||||
|
||||
def test_lora_manager_stacker():
|
||||
"""Test Lora Stacker (LoraManager) extraction"""
|
||||
print("\n" + "=" * 80)
|
||||
print("TEST: Lora Stacker (LoraManager)")
|
||||
print("=" * 80)
|
||||
|
||||
node = {
|
||||
'type': 'Lora Stacker (LoraManager)',
|
||||
'widgets_values': [
|
||||
None, # First item is usually None
|
||||
[
|
||||
{"name": "stacker_lora1", "strength": 0.33, "active": True, "clipStrength": 0.5},
|
||||
{"name": "stacker_lora2", "strength": "0.8", "active": False, "clipStrength": "0.9"},
|
||||
{"name": "stacker_lora3", "strength": 1.0, "active": True, "clipStrength": 1.0}
|
||||
]
|
||||
]
|
||||
}
|
||||
|
||||
loras = extract_lora_manager_stacker(node)
|
||||
|
||||
print(f"Extracted {len(loras)} LoRAs:")
|
||||
for lora in loras:
|
||||
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
|
||||
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
|
||||
|
||||
assert len(loras) == 3, f"Expected 3 LoRAs, got {len(loras)}"
|
||||
assert loras[0]['name'] == 'stacker_lora1'
|
||||
assert loras[0]['model_strength'] == 0.33
|
||||
assert loras[0]['clip_strength'] == 0.5
|
||||
|
||||
assert loras[1]['name'] == 'stacker_lora2'
|
||||
assert loras[1]['model_strength'] == 0.8
|
||||
assert loras[1]['active'] == False
|
||||
|
||||
print("[PASS] Lora Stacker extraction working correctly!")
|
||||
|
||||
|
||||
def test_wan_video_lora_select_multi():
|
||||
"""Test WanVideoLoraSelectMulti extraction"""
|
||||
print("\n" + "=" * 80)
|
||||
print("TEST: WanVideoLoraSelectMulti")
|
||||
print("=" * 80)
|
||||
|
||||
node = {
|
||||
'type': 'WanVideoLoraSelectMulti',
|
||||
'widgets_values': [
|
||||
'WanAnimate_relight_lora_fp16.safetensors', 1,
|
||||
'lightx2v_I2V_14B_480p_cfg_step_distill_rank64_bf16.safetensors', 1.2,
|
||||
'NSFW-22-L-e8.safetensors', 1,
|
||||
'WAN-2.2-I2V-Handjob-LOW-v1.safetensors', 2,
|
||||
'none', 1,
|
||||
False, False
|
||||
]
|
||||
}
|
||||
|
||||
loras = extract_wan_video_lora_select_multi(node)
|
||||
|
||||
print(f"Extracted {len(loras)} LoRAs:")
|
||||
for lora in loras:
|
||||
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
|
||||
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
|
||||
|
||||
assert len(loras) == 4, f"Expected 4 LoRAs, got {len(loras)}"
|
||||
assert loras[0]['name'] == 'WanAnimate_relight_lora_fp16'
|
||||
assert loras[0]['model_strength'] == 1.0
|
||||
|
||||
assert loras[1]['name'] == 'lightx2v_I2V_14B_480p_cfg_step_distill_rank64_bf16'
|
||||
assert loras[1]['model_strength'] == 1.2
|
||||
|
||||
assert loras[3]['name'] == 'WAN-2.2-I2V-Handjob-LOW-v1'
|
||||
assert loras[3]['model_strength'] == 2.0
|
||||
|
||||
print("[PASS] WanVideoLoraSelectMulti extraction working correctly!")
|
||||
|
||||
|
||||
def test_lora_loader_stack_rgthree():
|
||||
"""Test Lora Loader Stack (rgthree) extraction"""
|
||||
print("\n" + "=" * 80)
|
||||
print("TEST: Lora Loader Stack (rgthree)")
|
||||
print("=" * 80)
|
||||
|
||||
node = {
|
||||
'type': 'Lora Loader Stack (rgthree)',
|
||||
'widgets_values': [
|
||||
'SmoothXXXAnimation_High.safetensors', 0.2,
|
||||
'None', 0.8,
|
||||
'None', 1,
|
||||
'None', 1
|
||||
]
|
||||
}
|
||||
|
||||
loras = extract_lora_loader_stack_rgthree(node)
|
||||
|
||||
print(f"Extracted {len(loras)} LoRAs:")
|
||||
for lora in loras:
|
||||
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
|
||||
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
|
||||
|
||||
assert len(loras) == 1, f"Expected 1 LoRA, got {len(loras)}"
|
||||
assert loras[0]['name'] == 'SmoothXXXAnimation_High'
|
||||
assert loras[0]['model_strength'] == 0.2
|
||||
assert loras[0]['clip_strength'] == 0.2
|
||||
assert loras[0]['active'] == True
|
||||
|
||||
print("[PASS] Lora Loader Stack (rgthree) extraction working correctly!")
|
||||
|
||||
# Test with multiple LoRAs
|
||||
print("\nTesting with multiple LoRAs:")
|
||||
node2 = {
|
||||
'type': 'Lora Loader Stack (rgthree)',
|
||||
'widgets_values': [
|
||||
'lora1.safetensors', 0.5,
|
||||
'lora2.safetensors', 0.7,
|
||||
'lora3.safetensors', 1.0,
|
||||
'None', 1
|
||||
]
|
||||
}
|
||||
|
||||
loras2 = extract_lora_loader_stack_rgthree(node2)
|
||||
|
||||
print(f"Extracted {len(loras2)} LoRAs:")
|
||||
for lora in loras2:
|
||||
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']})")
|
||||
|
||||
assert len(loras2) == 3, f"Expected 3 LoRAs, got {len(loras2)}"
|
||||
assert loras2[0]['name'] == 'lora1'
|
||||
assert loras2[1]['name'] == 'lora2'
|
||||
assert loras2[2]['name'] == 'lora3'
|
||||
|
||||
print("[PASS] Multiple LoRAs extraction working correctly!")
|
||||
|
||||
|
||||
def test_standard_lora_loader():
|
||||
"""Test standard LoraLoader extraction"""
|
||||
print("\n" + "=" * 80)
|
||||
print("TEST: Standard LoraLoader")
|
||||
print("=" * 80)
|
||||
|
||||
node = {
|
||||
'type': 'LoraLoader',
|
||||
'widgets_values': ['standard_lora.safetensors', 0.7, 0.9]
|
||||
}
|
||||
|
||||
loras = extract_standard_lora_loader(node)
|
||||
|
||||
print(f"Extracted {len(loras)} LoRAs:")
|
||||
for lora in loras:
|
||||
active_status = " [ACTIVE]" if lora.get('active', True) else " [INACTIVE]"
|
||||
print(f" - {lora['name']} (model: {lora['model_strength']}, clip: {lora['clip_strength']}){active_status}")
|
||||
|
||||
assert len(loras) == 1, f"Expected 1 LoRA, got {len(loras)}"
|
||||
assert loras[0]['name'] == 'standard_lora'
|
||||
assert loras[0]['model_strength'] == 0.7
|
||||
assert loras[0]['clip_strength'] == 0.9
|
||||
assert loras[0]['active'] == True
|
||||
|
||||
print("[PASS] Standard LoraLoader extraction working correctly!")
|
||||
|
||||
|
||||
def test_is_lora_node():
|
||||
"""Test that all LoRA node types are recognized"""
|
||||
print("\n" + "=" * 80)
|
||||
print("TEST: is_lora_node recognition")
|
||||
print("=" * 80)
|
||||
|
||||
lora_types = [
|
||||
'Power Lora Loader (rgthree)',
|
||||
'Lora Loader Stack (rgthree)',
|
||||
'Lora Stacker (LoraManager)',
|
||||
'LoRA Stacker',
|
||||
'LoraLoader',
|
||||
'LoraLoaderModelOnly',
|
||||
'WanVideoLoraSelectMulti'
|
||||
]
|
||||
|
||||
non_lora_types = [
|
||||
'KSampler',
|
||||
'CLIPTextEncode',
|
||||
'VAEDecode',
|
||||
'WanVideoModelLoader'
|
||||
]
|
||||
|
||||
print("Testing LoRA node types:")
|
||||
for node_type in lora_types:
|
||||
result = is_lora_node(node_type)
|
||||
status = "✓" if result else "✗"
|
||||
print(f" {status} {node_type}: {result}")
|
||||
assert result, f"{node_type} should be recognized as LoRA node"
|
||||
|
||||
print("\nTesting non-LoRA node types:")
|
||||
for node_type in non_lora_types:
|
||||
result = is_lora_node(node_type)
|
||||
status = "✓" if not result else "✗"
|
||||
print(f" {status} {node_type}: {result}")
|
||||
assert not result, f"{node_type} should NOT be recognized as LoRA node"
|
||||
|
||||
print("[PASS] All node type recognition working correctly!")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_power_lora_loader()
|
||||
test_lora_manager_stacker()
|
||||
test_wan_video_lora_select_multi()
|
||||
test_lora_loader_stack_rgthree()
|
||||
print("ALL TESTS PASSED! ✓")
|
||||
print("=" * 80)
|
||||