remove old comfyUI
@@ -1,13 +0,0 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: [jags111]
|
||||
patreon: # jags111
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # B0B7IHIO1
|
||||
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
|
||||
otechie: # Replace with a single Otechie username
|
||||
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
|
||||
custom: ['https://www.buymeacoffee.com/jagsai','https://www. paypal.me/revsmart", orchidsasia.com' ]
|
||||
@@ -1,674 +0,0 @@
|
||||
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,251 +0,0 @@
|
||||
✨🍬Planning to help this branch stay alive and any issues will try to solve or fix .. But will be slow as I run many github repos . before raising any issues, please update comfyUI to the latest and esnure all the required packages are updated ass well. Share your workflow in issues to retest same at our end and update the patch.🍬
|
||||
|
||||
|
||||
<b> Efficiency Nodes for ComfyUI Version 2.0+
|
||||
=======
|
||||
### A collection of <a href="https://github.com/comfyanonymous/ComfyUI" >ComfyUI</a> custom nodes to help streamline workflows and reduce total node count.
|
||||
## Releases
|
||||
|
||||
Please check out our WIKI for any use cases and new developments including workflow and settings.<br>
|
||||
[Efficiency Nodes Wiki](https://github.com/jags111/efficiency-nodes-comfyui/wiki)<br>
|
||||
|
||||
### Nodes:
|
||||
<!-------------------------------------------------------------------------------------------------------------------------------------------------------->
|
||||
<details>
|
||||
<summary><b>Efficient Loader</b> & <b>Eff. Loader SDXL</b></summary>
|
||||
<ul>
|
||||
<li>Nodes that can load & cache Checkpoint, VAE, & LoRA type models. <i>(cache settings found in config file 'node_settings.json')</i></li>
|
||||
<li>Able to apply LoRA & Control Net stacks via their <code>lora_stack</code> and <code>cnet_stack</code> inputs.</li>
|
||||
<li>Come with positive and negative prompt text boxes. You can also set the way you want the prompt to be <a href="https://github.com/BlenderNeko/ComfyUI_ADV_CLIP_emb">encoded</a> via the <code>token_normalization</code> and <code>weight_interpretation</code> widgets.</li>
|
||||
<li>These node's also feature a variety of custom menu options as shown below.
|
||||
<p></p><img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes//NodeMenu%20-%20Efficient%20Loaders.png" width="240" style="display: inline-block;"></p>
|
||||
<p><i>note: "🔍 View model info..." requires <a href="https://github.com/pythongosssss/ComfyUI-Custom-Scripts">ComfyUI-Custom-Scripts</a> to be installed to function.</i></p></li>
|
||||
<li>These loaders are used by the <b>XY Plot</b> node for many of its plot type dependencies.</li>
|
||||
</ul>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes/NODE%20-%20Efficient%20Loader.png" width="240" style="display: inline-block;">
|
||||
<img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes/NODE%20-%20Eff.%20Loader%20SDXL.png" width="240" style="display: inline-block;">
|
||||
</p>
|
||||
</details>
|
||||
<!-------------------------------------------------------------------------------------------------------------------------------------------------------->
|
||||
<details>
|
||||
<summary><b>KSampler (Efficient)</b>, <b>KSampler Adv. (Efficient)</b>, <b>KSampler SDXL (Eff.)</b></summary>
|
||||
|
||||
- Modded KSamplers with the ability to live preview generations and/or vae decode images.
|
||||
- Feature a special seed box that allows for a clearer management of seeds. <i>(-1 seed to apply the selected seed behavior)</i>
|
||||
- Can execute a variety of scripts, such as the <b>XY Plot</b> script. To activate the <code>script</code>, simply connect the input connection.
|
||||
|
||||
<p align="center">
|
||||
<img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes/NODE%20-%20KSampler%20(Efficient).png" width="240">
|
||||
|
||||
<img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes/NODE%20-%20KSampler%20Adv.%20(Efficient).png" width="240">
|
||||
|
||||
<img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes/NODE%20-%20KSampler%20SDXL%20(Eff.).png" width="240">
|
||||
</p>
|
||||
|
||||
</details>
|
||||
<!-------------------------------------------------------------------------------------------------------------------------------------------------------->
|
||||
<details>
|
||||
<summary><b>Script Nodes</b></summary>
|
||||
|
||||
- A group of node's that are used in conjuction with the Efficient KSamplers to execute a variety of 'pre-wired' set of actions.
|
||||
- Script nodes can be chained if their input/outputs allow it. Multiple instances of the same Script Node in a chain does nothing.
|
||||
<p align="center">
|
||||
<img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes/ScriptChain.png" width="1080">
|
||||
</p>
|
||||
<!-------------------------------------------------------------------------------------------------------------------------------------------------------->
|
||||
<details>
|
||||
<summary><b>XY Plot</b></summary>
|
||||
<ul>
|
||||
<li>Node that allows users to specify parameters for the Efficiency KSamplers to plot on a grid.</li>
|
||||
</ul>
|
||||
<p align="center">
|
||||
<img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes/XY%20Plot%20-%20Node%20Example.png" width="1080">
|
||||
</p>
|
||||
|
||||
</details>
|
||||
<!-------------------------------------------------------------------------------------------------------------------------------------------------------->
|
||||
<details>
|
||||
<summary><b>HighRes-Fix</b></summary>
|
||||
<ul>
|
||||
<li>Node that the gives user the ability to upscale KSampler results through variety of different methods.</li>
|
||||
<li>Comes out of the box with popular Neural Network Latent Upscalers such as Ttl's <a href="https://github.com/Ttl/ComfyUi_NNLatentUpscale">ComfyUi_NNLatentUpscale</a> and City96's <a href="https://github.com/city96/SD-Latent-Upscaler">SD-Latent-Upscaler</a>.</li>
|
||||
<li>Supports ControlNet guided latent upscaling. <i> (You must have Fannovel's <a href="https://github.com/Fannovel16/comfyui_controlnet_aux">comfyui_controlnet_aux</a> installed to unlock this feature)</i></li>
|
||||
<li> Local models---The node pulls the required files from huggingface hub by default. You can create a models folder and place the modules there if you have a flaky connection or prefer to use it completely offline, it will load them locally instead. The path should be: ComfyUI/custom_nodes/efficiency-nodes-comfyui/models; Alternatively, just clone the entire HF repo to it: (git clone https://huggingface.co/city96/SD-Latent-Upscaler) to ComfyUI/custom_nodes/efficiency-nodes-comfyui/models</li>
|
||||
</ul>
|
||||
<p align="center">
|
||||
<img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes/HighResFix%20-%20Node%20Example.gif" width="1080">
|
||||
</p>
|
||||
|
||||
</details>
|
||||
<!-------------------------------------------------------------------------------------------------------------------------------------------------------->
|
||||
<details>
|
||||
<summary><b>Noise Control</b></summary>
|
||||
<ul>
|
||||
<li>This node gives the user the ability to manipulate noise sources in a variety of ways, such as the sampling's RNG source.</li>
|
||||
<li>The <a href="https://github.com/shiimizu/ComfyUI_smZNodes">CFG Denoiser</a> noise hijack was developed by smZ, it allows you to get closer recreating Automatic1111 results.</li>
|
||||
<p></p><i>Note: The CFG Denoiser does not work with a variety of conditioning types such as ControlNet & GLIGEN</i></p>
|
||||
<li>This node also allows you to add noise <a href="https://github.com/chrisgoringe/cg-noise">Seed Variations</a> to your generations.</li>
|
||||
<li>For trying to replicate Automatic1111 images, this node will help you achieve it. Encode your prompt using "length+mean" <code>token_normalization</code> with "A1111" <code>weight_interpretation</code>, set the Noise Control Script node's <code>rng_source</code> to "gpu", and turn the <code>cfg_denoiser</code> to true.</li>
|
||||
</ul>
|
||||
<p align="center">
|
||||
<img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes/NODE%20-%20Noise%20Control%20Script.png" width="320">
|
||||
</p>
|
||||
|
||||
</details>
|
||||
<!-------------------------------------------------------------------------------------------------------------------------------------------------------->
|
||||
<details>
|
||||
<summary><b>Tiled Upscaler</b></summary>
|
||||
<ul>
|
||||
<li>The Tiled Upscaler script attempts to encompas BlenderNeko's <a href="https://github.com/BlenderNeko/ComfyUI_TiledKSampler">ComfyUI_TiledKSampler</a> workflow into 1 node.</li>
|
||||
<li>Script supports Tiled ControlNet help via the options.</li>
|
||||
<li>Strongly recommend the <code>preview_method</code> be "vae_decoded_only" when running the script.</li>
|
||||
</ul>
|
||||
<p align="center">
|
||||
<img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes/Tiled%20Upscaler%20-%20Node%20Example.gif" width="1080">
|
||||
</p>
|
||||
|
||||
</details>
|
||||
<!-------------------------------------------------------------------------------------------------------------------------------------------------------->
|
||||
<details>
|
||||
<summary><b>AnimateDiff</b></summary>
|
||||
<ul>
|
||||
<li>To unlock the AnimateDiff script it is required you have installed Kosinkadink's <a href="https://github.com/Kosinkadink/ComfyUI-AnimateDiff-Evolved">ComfyUI-AnimateDiff-Evolved</a>.</li>
|
||||
<li>The latent <code>batch_size</code> when running this script becomes your frame count.</li>
|
||||
</ul>
|
||||
<p align="center">
|
||||
<img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes/AnimateDiff%20-%20Node%20Example.gif" width="1080">
|
||||
</p>
|
||||
|
||||
</details>
|
||||
</details>
|
||||
|
||||
<!-------------------------------------------------------------------------------------------------------------------------------------------------------->
|
||||
<details>
|
||||
<summary><b>Image Overlay</b></summary>
|
||||
<ul>
|
||||
<li>Node that allows for flexible image overlaying. Works also with image batches.</li>
|
||||
</ul>
|
||||
<p align="center">
|
||||
<img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes/Image%20Overlay%20-%20Node%20Example.png" width="1080">
|
||||
</p>
|
||||
|
||||
</details>
|
||||
<!-------------------------------------------------------------------------------------------------------------------------------------------------------->
|
||||
<details>
|
||||
<summary><b>SimpleEval Nodes</b></summary>
|
||||
<ul>
|
||||
<li>A collection of nodes that allows users to write simple Python expressions for a variety of data types using the <i><a href="https://github.com/danthedeckie/simpleeval" >simpleeval</a></i> library.</li>
|
||||
<li>To activate you must have installed the simpleeval library in your Python workspace.</li>
|
||||
<pre>pip install simpleeval</pre>
|
||||
</ul>
|
||||
<p align="center">
|
||||
<img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes/NODE%20-%20Evaluate%20Integers.png" width="320">
|
||||
|
||||
<img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes/NODE%20-%20Evaluate%20Floats.png" width="320">
|
||||
|
||||
<img src="https://github.com/LucianoCirino/efficiency-nodes-media/blob/main/images/nodes/NODE%20-%20Evaluate%20Strings.png" width="320">
|
||||
</p>
|
||||
|
||||
</details>
|
||||
|
||||
<!-------------------------------------------------------------------------------------------------------------------------------------------------------->
|
||||
<details>
|
||||
<summary><b>Latent Upscale nodes</b></summary>
|
||||
<ul>
|
||||
<li>Forked from NN latent this node provides some remarkable neural enhancement to the latents making scaling a cool task</li>
|
||||
<li>Both NN latent upscale and Latent upscaler does the Latent improvemnet in remarkable ways. If you face any issue regarding same please install the nodes from this link([SD-Latent-Upscaler](https://github.com/city96/SD-Latent-Upscaler) and the NN latent upscale from [ComfyUI_NNlatentUpscale](https://github.com/Ttl/ComfyUi_NNLatentUpscale) </li>
|
||||
|
||||
</ul>
|
||||
<p align="center">
|
||||
<img src="images/2023-12-08_19-53-37.png" width="320">
|
||||
|
||||
<img src="images/2023-12-08_19-54-11.png" width="320">
|
||||
|
||||
|
||||
</p>
|
||||
|
||||
</details>
|
||||
|
||||
## Workflow Examples:
|
||||
|
||||
Kindly load all PNG files in same name in the (workflow driectory) to comfyUI to get all this workflows. The PNG files have the json embedded into them and are easy to drag and drop !<br>
|
||||
|
||||
1. HiRes-Fixing<br>
|
||||
[<img src="https://github.com/jags111/efficiency-nodes-comfyui/blob/main/workflows/HiResfix_workflow.png" width="800">](https://github.com/jags111/efficiency-nodes-comfyui/blob/main/workflows/HiResfix_workflow.png)<br>
|
||||
|
||||
2. SDXL Refining & **Noise Control Script**<br>
|
||||
[<img src="https://github.com/jags111/efficiency-nodes-comfyui/blob/main/workflows/SDXL_base_refine_noise_workflow.png" width="800">](https://github.com/jags111/efficiency-nodes-comfyui/blob/main/workflows/SDXL_base_refine_noise_workflow.png)<br>
|
||||
|
||||
3. **XY Plot**: LoRA <code>model_strength</code> vs <code>clip_strength</code><br>
|
||||
[<img src="https://github.com/jags111/efficiency-nodes-comfyui/blob/main/workflows/Eff_XYPlot%20-%20LoRA%20Model%20vs%20Clip%20Strengths01.png" width="800">](https://github.com/jags111/efficiency-nodes-comfyui/blob/main/workflows/Eff_XYPlot%20-%20LoRA%20Model%20vs%20Clip%20Strengths01.png)<br>
|
||||
|
||||
4. Stacking Scripts: **XY Plot** + **Noise Control** + **HiRes-Fix**<br>
|
||||
[<img src="https://github.com/LucianoCirino/efficiency-nodes-comfyui/blob/v2.0/workflows/XYPlot%20-%20Seeds%20vs%20Checkpoints%20%26%20Stacked%20Scripts.png" width="800">](https://github.com/LucianoCirino/efficiency-nodes-comfyui/blob/v2.0/workflows/XYPlot%20-%20Seeds%20vs%20Checkpoints%20%26%20Stacked%20Scripts.png)<br>
|
||||
|
||||
5. Stacking Scripts: **HiRes-Fix** (with ControlNet)<br>
|
||||
[<img src="https://github.com/jags111/efficiency-nodes-comfyui/blob/main/workflows/eff_animatescriptWF001.gif" width="800">](https://github.com/jags111/efficiency-nodes-comfyui/blob/main/workflows/eff_animatescriptWF001.gif)<br>
|
||||
|
||||
6. SVD workflow: **Stable Video Diffusion** + *Kohya Hires** (with latent control)<br>
|
||||
<br>
|
||||
|
||||
|
||||
### Dependencies
|
||||
The python library <i><a href="https://github.com/danthedeckie/simpleeval" >simpleeval</a></i> is required to be installed if you wish to use the **Simpleeval Nodes**.
|
||||
<pre>pip install simpleeval</pre>
|
||||
Also can be installed with a simple pip command <br>
|
||||
'pip install simpleeval'
|
||||
|
||||
A single file library for easily adding evaluatable expressions into python projects. Say you want to allow a user to set an alarm volume, which could depend on the time of day, alarm level, how many previous alarms had gone off, and if there is music playing at the time.
|
||||
|
||||
check Notes for more information.
|
||||
|
||||
## **Install:**
|
||||
To install, drop the "_**efficiency-nodes-comfyui**_" folder into the "_**...\ComfyUI\ComfyUI\custom_nodes**_" directory and restart UI.
|
||||
|
||||
## Todo
|
||||
|
||||
[ ] Add guidance to notebook
|
||||
|
||||
|
||||
# Comfy Resources
|
||||
|
||||
**Efficiency Linked Repos**
|
||||
- [BlenderNeko ComfyUI_ADV_CLIP_emb](https://github.com/BlenderNeko/ComfyUI_ADV_CLIP_emb) by@BlenderNeko
|
||||
- [Chrisgoringe cg-noise](https://github.com/chrisgoringe/cg-noise) by@Chrisgoringe
|
||||
- [pythongosssss ComfyUI-Custom-Scripts](https://github.com/pythongosssss/ComfyUI-Custom-Scripts) by@pythongosssss
|
||||
- [shiimizu ComfyUI_smZNodes](https://github.com/shiimizu/ComfyUI_smZNodes) by@shiimizu
|
||||
- [LEv145_images-grid-comfyUI-plugin](https://github.com/LEv145/images-grid-comfy-plugin)) by@LEv145
|
||||
- [ltdrdata-ComfyUI-Inspire-Pack](https://github.com/ltdrdata/ComfyUI-Inspire-Pack) by@ltdrdata
|
||||
- [pythongosssss-ComfyUI-custom-Scripts](https://github.com/pythongosssss/ComfyUI-Custom-Scripts) by@pythongosssss
|
||||
- [RockOfFire-ComfyUI_Comfyroll_CustomNodes](https://github.com/RockOfFire/ComfyUI_Comfyroll_CustomNodes) by@RockOfFire
|
||||
|
||||
**Guides**:
|
||||
- [Official Examples (eng)](https://comfyanonymous.github.io/ComfyUI_examples/)-
|
||||
- [ComfyUI Community Manual (eng)](https://blenderneko.github.io/ComfyUI-docs/) by @BlenderNeko
|
||||
|
||||
- **Extensions and Custom Nodes**:
|
||||
- [Plugins for Comfy List (eng)](https://github.com/WASasquatch/comfyui-plugins) by @WASasquatch
|
||||
- [ComfyUI tag on CivitAI (eng)](https://civitai.com/tag/comfyui)-
|
||||
- [Tomoaki's personal Wiki (jap)](https://comfyui.creamlab.net/guides/) by @tjhayasaka
|
||||
|
||||
## Support
|
||||
If you create a cool image with our nodes, please show your result and message us on twitter at @jags111 or @NeuralismAI .
|
||||
|
||||
You can join the <a href="https://discord.gg/vNVqT82W" alt="Neuralism Discord"> NEURALISM AI DISCORD </a> or <a href="https://discord.gg/UmSd4qyh" alt =Jags AI Discord > JAGS AI DISCORD </a>
|
||||
Share your work created with this model. Exchange experiences and parameters. And see more interesting custom workflows.
|
||||
|
||||
Support us in Patreon for more future models and new versions of AI notebooks.
|
||||
- tip me on <a href="https://www.patreon.com/jags111"> [patreon]</a>
|
||||
|
||||
My buymeacoffee.com pages and links are here and if you feel you are happy with my work just buy me a coffee !
|
||||
|
||||
<a href="https://www.buymeacoffee.com/jagsAI"> coffee for JAGS AI</a>
|
||||
|
||||
Thank you for being awesome!
|
||||
|
||||
<img src = "images/ComfyUI_temp_vpose_00005_.png" width = "50%">
|
||||
|
||||
<!-- end support-pitch -->
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
import os
|
||||
import subprocess
|
||||
import importlib.util
|
||||
import folder_paths
|
||||
import shutil
|
||||
import sys
|
||||
import traceback
|
||||
|
||||
from .efficiency_nodes import NODE_CLASS_MAPPINGS
|
||||
#from .py.ttl_nn_latent_upscaler import NODE_CLASS_MAPPINGS
|
||||
#from .py.city96_latent_upscaler import NODE_CLASS_MAPPINGS
|
||||
|
||||
|
||||
WEB_DIRECTORY = "js"
|
||||
|
||||
CC_VERSION = 2.0
|
||||
|
||||
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', 'CC_VERSION']
|
||||
@@ -1,3 +0,0 @@
|
||||
github: ["https://www.buymeacoffee.com/jagsai", jags111]
|
||||
patreon: jags111
|
||||
custom: ["https://www.paypal.me/revsmart", orchidsasia.com]
|
||||
|
Before Width: | Height: | Size: 1.2 MiB |
|
Before Width: | Height: | Size: 586 KiB |
|
Before Width: | Height: | Size: 613 KiB |
|
Before Width: | Height: | Size: 1.6 MiB |
|
Before Width: | Height: | Size: 279 KiB |
|
Before Width: | Height: | Size: 1.9 MiB |
|
Before Width: | Height: | Size: 1.3 MiB |
|
Before Width: | Height: | Size: 994 KiB |
|
Before Width: | Height: | Size: 672 KiB |
|
Before Width: | Height: | Size: 230 KiB |
|
Before Width: | Height: | Size: 1.1 MiB |
|
Before Width: | Height: | Size: 58 KiB |
|
Before Width: | Height: | Size: 474 KiB |
|
Before Width: | Height: | Size: 314 KiB |
|
Before Width: | Height: | Size: 624 KiB |
|
Before Width: | Height: | Size: 503 KiB |
|
Before Width: | Height: | Size: 10 MiB |
@@ -1,42 +0,0 @@
|
||||
Images in this group<br>
|
||||
<table><tr>
|
||||
<tr>
|
||||
<td valign="bottom">
|
||||
<img width="200" alt="2023-10-31_22-43-17" src="https://github.com/jags111/efficiency-nodes-comfyui/assets/5968619/f8f217fd-b36f-4b51-9c11-676020c07da8">
|
||||
</td><br>
|
||||
<td valign="bottom">
|
||||
<img width="200" alt="2023-11-04_22-32-57" src="https://github.com/jags111/efficiency-nodes-comfyui/assets/5968619/f7dae80f-f499-4b07-a3aa-8dcbd9013f86">
|
||||
</td><br>
|
||||
<td valign="bottom">
|
||||
<img width="200" alt="2023-11-01_19-54-59" src="https://github.com/jags111/efficiency-nodes-comfyui/assets/5968619/781e5c00-4b62-43f9-a7a3-fd9172c612db">
|
||||
</td><br>
|
||||
<td valign="bottom">
|
||||
<img width="200" alt="2023-11-01_14-25-01" src="https://github.com/jags111/efficiency-nodes-comfyui/assets/5968619/65a390f8-19aa-4838-b3bb-8dfff35782ed">
|
||||
</td><br>
|
||||
</tr>
|
||||
<tr>
|
||||
<td valign="bottom">
|
||||
<img width="200" alt="2023-11-05_00-02-34" src="https://github.com/jags111/efficiency-nodes-comfyui/assets/5968619/664c0280-e091-4200-a47f-987d66cfaecf">
|
||||
</td><br>
|
||||
<td valign="bottom">
|
||||
<img width="200" alt="2023-11-05_00-02-07" src="https://github.com/jags111/efficiency-nodes-comfyui/assets/5968619/52df496f-5440-4f3e-bc22-23b7185e6c0e">
|
||||
</td><br>
|
||||
<td valign="bottom">
|
||||
<img width="200" alt="2023-11-04_23-10-03" src="https://github.com/jags111/efficiency-nodes-comfyui/assets/5968619/64e865cf-52c2-4714-9e8b-41ef68ee77dd">
|
||||
</td><br>
|
||||
<td valign="bottom">
|
||||
<img width="200" alt="2023-11-04_22-57-28" src="https://github.com/jags111/efficiency-nodes-comfyui/assets/5968619/21be4183-43b6-4ebf-ac07-b9ba3012bb57">
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td valign="bottom">
|
||||
<img width="200" alt="2023-11-04_22-47-09" src="https://github.com/jags111/efficiency-nodes-comfyui/assets/5968619/35a007a9-6ee1-4f2f-9d53-5f52074482b5">
|
||||
</td>
|
||||
<td valign="bottom">
|
||||
<img width="200" alt="2023-11-04_22-46-20" src="https://github.com/jags111/efficiency-nodes-comfyui/assets/5968619/5881ced2-fd87-4a24-8341-225748558afd">
|
||||
</td>
|
||||
<td valign="bottom">
|
||||
<img width="200" alt="2023-11-04_22-33-57" src="https://github.com/jags111/efficiency-nodes-comfyui/assets/5968619/44154b1f-67c0-45f8-b09b-517258ec3332">
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
Before Width: | Height: | Size: 6.3 MiB |
|
Before Width: | Height: | Size: 4.1 MiB |
|
Before Width: | Height: | Size: 16 MiB |
|
Before Width: | Height: | Size: 1.3 MiB |
|
Before Width: | Height: | Size: 31 KiB |
|
Before Width: | Height: | Size: 45 KiB |
|
Before Width: | Height: | Size: 51 KiB |
|
Before Width: | Height: | Size: 20 KiB |
|
Before Width: | Height: | Size: 14 KiB |
|
Before Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 36 KiB |
|
Before Width: | Height: | Size: 23 KiB |
|
Before Width: | Height: | Size: 47 KiB |
|
Before Width: | Height: | Size: 58 KiB |
|
Before Width: | Height: | Size: 45 KiB |
|
Before Width: | Height: | Size: 17 KiB |
|
Before Width: | Height: | Size: 32 KiB |
|
Before Width: | Height: | Size: 24 KiB |
|
Before Width: | Height: | Size: 16 KiB |
|
Before Width: | Height: | Size: 5.5 KiB |
|
Before Width: | Height: | Size: 323 KiB |
|
Before Width: | Height: | Size: 14 MiB |
|
Before Width: | Height: | Size: 1.0 MiB |
@@ -1 +0,0 @@
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
const COLOR_THEMES = {
|
||||
red: { nodeColor: "#332222", nodeBgColor: "#553333" },
|
||||
green: { nodeColor: "#223322", nodeBgColor: "#335533" },
|
||||
blue: { nodeColor: "#222233", nodeBgColor: "#333355" },
|
||||
pale_blue: { nodeColor: "#2a363b", nodeBgColor: "#3f5159" },
|
||||
cyan: { nodeColor: "#223333", nodeBgColor: "#335555" },
|
||||
purple: { nodeColor: "#332233", nodeBgColor: "#553355" },
|
||||
yellow: { nodeColor: "#443322", nodeBgColor: "#665533" },
|
||||
none: { nodeColor: null, nodeBgColor: null } // no color
|
||||
};
|
||||
|
||||
const NODE_COLORS = {
|
||||
"KSampler (Efficient)": "random",
|
||||
"KSampler Adv. (Efficient)": "random",
|
||||
"KSampler SDXL (Eff.)": "random",
|
||||
"Efficient Loader": "random",
|
||||
"Eff. Loader SDXL": "random",
|
||||
"LoRA Stacker": "blue",
|
||||
"Control Net Stacker": "green",
|
||||
"Apply ControlNet Stack": "none",
|
||||
"XY Plot": "purple",
|
||||
"Unpack SDXL Tuple": "none",
|
||||
"Pack SDXL Tuple": "none",
|
||||
"XY Input: Seeds++ Batch": "cyan",
|
||||
"XY Input: Add/Return Noise": "cyan",
|
||||
"XY Input: Steps": "cyan",
|
||||
"XY Input: CFG Scale": "cyan",
|
||||
"XY Input: Sampler/Scheduler": "cyan",
|
||||
"XY Input: Denoise": "cyan",
|
||||
"XY Input: VAE": "cyan",
|
||||
"XY Input: Prompt S/R": "cyan",
|
||||
"XY Input: Aesthetic Score": "cyan",
|
||||
"XY Input: Refiner On/Off": "cyan",
|
||||
"XY Input: Checkpoint": "cyan",
|
||||
"XY Input: Clip Skip": "cyan",
|
||||
"XY Input: LoRA": "cyan",
|
||||
"XY Input: LoRA Plot": "cyan",
|
||||
"XY Input: LoRA Stacks": "cyan",
|
||||
"XY Input: Control Net": "cyan",
|
||||
"XY Input: Control Net Plot": "cyan",
|
||||
"XY Input: Manual XY Entry": "cyan",
|
||||
"Manual XY Entry Info": "cyan",
|
||||
"Join XY Inputs of Same Type": "cyan",
|
||||
"Image Overlay": "random",
|
||||
"Noise Control Script": "none",
|
||||
"HighRes-Fix Script": "yellow",
|
||||
"Tiled Upscaler Script": "red",
|
||||
"AnimateDiff Script": "random",
|
||||
"Evaluate Integers": "pale_blue",
|
||||
"Evaluate Floats": "pale_blue",
|
||||
"Evaluate Strings": "pale_blue",
|
||||
"Simple Eval Examples": "pale_blue",
|
||||
};
|
||||
|
||||
function shuffleArray(array) {
|
||||
for (let i = array.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[array[i], array[j]] = [array[j], array[i]]; // Swap elements
|
||||
}
|
||||
}
|
||||
|
||||
let colorKeys = Object.keys(COLOR_THEMES).filter(key => key !== "none");
|
||||
shuffleArray(colorKeys); // Shuffle the color themes initially
|
||||
|
||||
function setNodeColors(node, theme) {
|
||||
if (!theme) {return;}
|
||||
node.shape = "box";
|
||||
if(theme.nodeColor && theme.nodeBgColor) {
|
||||
node.color = theme.nodeColor;
|
||||
node.bgcolor = theme.nodeBgColor;
|
||||
}
|
||||
}
|
||||
|
||||
const ext = {
|
||||
name: "efficiency.appearance",
|
||||
|
||||
nodeCreated(node) {
|
||||
const nclass = node.comfyClass;
|
||||
if (NODE_COLORS.hasOwnProperty(nclass)) {
|
||||
let colorKey = NODE_COLORS[nclass];
|
||||
|
||||
if (colorKey === "random") {
|
||||
// Check for a valid color key before popping
|
||||
if (colorKeys.length === 0 || !COLOR_THEMES[colorKeys[colorKeys.length - 1]]) {
|
||||
colorKeys = Object.keys(COLOR_THEMES).filter(key => key !== "none");
|
||||
shuffleArray(colorKeys);
|
||||
}
|
||||
colorKey = colorKeys.pop();
|
||||
}
|
||||
|
||||
const theme = COLOR_THEMES[colorKey];
|
||||
setNodeColors(node, theme);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
app.registerExtension(ext);
|
||||
@@ -1,144 +0,0 @@
|
||||
import { app } from '../../scripts/app.js'
|
||||
import { api } from '../../scripts/api.js'
|
||||
|
||||
function offsetDOMWidget(
|
||||
widget,
|
||||
ctx,
|
||||
node,
|
||||
widgetWidth,
|
||||
widgetY,
|
||||
height
|
||||
) {
|
||||
const margin = 10
|
||||
const elRect = ctx.canvas.getBoundingClientRect()
|
||||
const transform = new DOMMatrix()
|
||||
.scaleSelf(
|
||||
elRect.width / ctx.canvas.width,
|
||||
elRect.height / ctx.canvas.height
|
||||
)
|
||||
.multiplySelf(ctx.getTransform())
|
||||
.translateSelf(0, widgetY + margin)
|
||||
|
||||
const scale = new DOMMatrix().scaleSelf(transform.a, transform.d)
|
||||
Object.assign(widget.inputEl.style, {
|
||||
transformOrigin: '0 0',
|
||||
transform: scale,
|
||||
left: `${transform.e}px`,
|
||||
top: `${transform.d + transform.f}px`,
|
||||
width: `${widgetWidth}px`,
|
||||
height: `${(height || widget.parent?.inputHeight || 32) - margin}px`,
|
||||
position: 'absolute',
|
||||
background: !node.color ? '' : node.color,
|
||||
color: !node.color ? '' : 'white',
|
||||
zIndex: 5, //app.graph._nodes.indexOf(node),
|
||||
})
|
||||
}
|
||||
|
||||
export const hasWidgets = (node) => {
|
||||
if (!node.widgets || !node.widgets?.[Symbol.iterator]) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
export const cleanupNode = (node) => {
|
||||
if (!hasWidgets(node)) {
|
||||
return
|
||||
}
|
||||
|
||||
for (const w of node.widgets) {
|
||||
if (w.canvas) {
|
||||
w.canvas.remove()
|
||||
}
|
||||
if (w.inputEl) {
|
||||
w.inputEl.remove()
|
||||
}
|
||||
// calls the widget remove callback
|
||||
w.onRemoved?.()
|
||||
}
|
||||
}
|
||||
|
||||
const CreatePreviewElement = (name, val, format) => {
|
||||
const [type] = format.split('/')
|
||||
const w = {
|
||||
name,
|
||||
type,
|
||||
value: val,
|
||||
draw: function (ctx, node, widgetWidth, widgetY, height) {
|
||||
const [cw, ch] = this.computeSize(widgetWidth)
|
||||
offsetDOMWidget(this, ctx, node, widgetWidth, widgetY, ch)
|
||||
},
|
||||
computeSize: function (_) {
|
||||
const ratio = this.inputRatio || 1
|
||||
const width = Math.max(220, this.parent.size[0])
|
||||
return [width, (width / ratio + 10)]
|
||||
},
|
||||
onRemoved: function () {
|
||||
if (this.inputEl) {
|
||||
this.inputEl.remove()
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
w.inputEl = document.createElement(type === 'video' ? 'video' : 'img')
|
||||
w.inputEl.src = w.value
|
||||
if (type === 'video') {
|
||||
w.inputEl.setAttribute('type', 'video/webm');
|
||||
w.inputEl.autoplay = true
|
||||
w.inputEl.loop = true
|
||||
w.inputEl.controls = false;
|
||||
}
|
||||
w.inputEl.onload = function () {
|
||||
w.inputRatio = w.inputEl.naturalWidth / w.inputEl.naturalHeight
|
||||
}
|
||||
document.body.appendChild(w.inputEl)
|
||||
return w
|
||||
}
|
||||
|
||||
const gif_preview = {
|
||||
name: 'efficiency.gif_preview',
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
switch (nodeData.name) {
|
||||
case 'KSampler (Efficient)':{
|
||||
const onExecuted = nodeType.prototype.onExecuted
|
||||
nodeType.prototype.onExecuted = function (message) {
|
||||
const prefix = 'ad_gif_preview_'
|
||||
const r = onExecuted ? onExecuted.apply(this, message) : undefined
|
||||
|
||||
if (this.widgets) {
|
||||
const pos = this.widgets.findIndex((w) => w.name === `${prefix}_0`)
|
||||
if (pos !== -1) {
|
||||
for (let i = pos; i < this.widgets.length; i++) {
|
||||
this.widgets[i].onRemoved?.()
|
||||
}
|
||||
this.widgets.length = pos
|
||||
}
|
||||
if (message?.gifs) {
|
||||
message.gifs.forEach((params, i) => {
|
||||
const previewUrl = api.apiURL(
|
||||
'/view?' + new URLSearchParams(params).toString()
|
||||
)
|
||||
const w = this.addCustomWidget(
|
||||
CreatePreviewElement(`${prefix}_${i}`, previewUrl, params.format || 'image/gif')
|
||||
)
|
||||
w.parent = this
|
||||
})
|
||||
}
|
||||
const onRemoved = this.onRemoved
|
||||
this.onRemoved = () => {
|
||||
cleanupNode(this)
|
||||
return onRemoved?.()
|
||||
}
|
||||
}
|
||||
if (message?.gifs && message.gifs.length > 0) {
|
||||
this.setSize([this.size[0], this.computeSize([this.size[0], this.size[1]])[1]]);
|
||||
}
|
||||
return r
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
app.registerExtension(gif_preview)
|
||||
@@ -1,180 +0,0 @@
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { addMenuHandler } from "./common/utils.js";
|
||||
import { addNode } from "./common/utils.js";
|
||||
|
||||
function createKSamplerEntry(node, samplerType, subNodeType = null, isSDXL = false) {
|
||||
const samplerLabelMap = {
|
||||
"Eff": "KSampler (Efficient)",
|
||||
"Adv": "KSampler Adv. (Efficient)",
|
||||
"SDXL": "KSampler SDXL (Eff.)"
|
||||
};
|
||||
|
||||
const subNodeLabelMap = {
|
||||
"XYPlot": "XY Plot",
|
||||
"NoiseControl": "Noise Control Script",
|
||||
"HiResFix": "HighRes-Fix Script",
|
||||
"TiledUpscale": "Tiled Upscaler Script",
|
||||
"AnimateDiff": "AnimateDiff Script"
|
||||
};
|
||||
|
||||
const nicknameMap = {
|
||||
"KSampler (Efficient)": "KSampler",
|
||||
"KSampler Adv. (Efficient)": "KSampler(Adv)",
|
||||
"KSampler SDXL (Eff.)": "KSampler",
|
||||
"XY Plot": "XY Plot",
|
||||
"Noise Control Script": "NoiseControl",
|
||||
"HighRes-Fix Script": "HiResFix",
|
||||
"Tiled Upscaler Script": "TiledUpscale",
|
||||
"AnimateDiff Script": "AnimateDiff"
|
||||
};
|
||||
|
||||
const kSamplerLabel = samplerLabelMap[samplerType];
|
||||
const subNodeLabel = subNodeLabelMap[subNodeType];
|
||||
|
||||
const kSamplerNickname = nicknameMap[kSamplerLabel];
|
||||
const subNodeNickname = nicknameMap[subNodeLabel];
|
||||
|
||||
const contentLabel = subNodeNickname ? `${kSamplerNickname} + ${subNodeNickname}` : kSamplerNickname;
|
||||
|
||||
return {
|
||||
content: contentLabel,
|
||||
callback: function() {
|
||||
const kSamplerNode = addNode(kSamplerLabel, node, { shiftX: node.size[0] + 50 });
|
||||
|
||||
// Standard connections for all samplers
|
||||
node.connect(0, kSamplerNode, 0); // MODEL
|
||||
node.connect(1, kSamplerNode, 1); // CONDITIONING+
|
||||
node.connect(2, kSamplerNode, 2); // CONDITIONING-
|
||||
|
||||
// Additional connections for non-SDXL
|
||||
if (!isSDXL) {
|
||||
node.connect(3, kSamplerNode, 3); // LATENT
|
||||
node.connect(4, kSamplerNode, 4); // VAE
|
||||
}
|
||||
|
||||
if (subNodeLabel) {
|
||||
const subNode = addNode(subNodeLabel, node, { shiftX: 50, shiftY: node.size[1] + 50 });
|
||||
const dependencyIndex = isSDXL ? 3 : 5;
|
||||
node.connect(dependencyIndex, subNode, 0);
|
||||
subNode.connect(0, kSamplerNode, dependencyIndex);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createStackerNode(node, type) {
|
||||
const stackerLabelMap = {
|
||||
"LoRA": "LoRA Stacker",
|
||||
"ControlNet": "Control Net Stacker"
|
||||
};
|
||||
|
||||
const contentLabel = stackerLabelMap[type];
|
||||
|
||||
return {
|
||||
content: contentLabel,
|
||||
callback: function() {
|
||||
const stackerNode = addNode(contentLabel, node);
|
||||
|
||||
// Calculate the left shift based on the width of the new node
|
||||
const shiftX = -(stackerNode.size[0] + 25);
|
||||
|
||||
stackerNode.pos[0] += shiftX; // Adjust the x position of the new node
|
||||
|
||||
// Introduce a Y offset of 200 for ControlNet Stacker node
|
||||
if (type === "ControlNet") {
|
||||
stackerNode.pos[1] += 300;
|
||||
}
|
||||
|
||||
// Connect outputs to the Efficient Loader based on type
|
||||
if (type === "LoRA") {
|
||||
stackerNode.connect(0, node, 0);
|
||||
} else if (type === "ControlNet") {
|
||||
stackerNode.connect(0, node, 1);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function createXYPlotNode(node, type) {
|
||||
const contentLabel = "XY Plot";
|
||||
|
||||
return {
|
||||
content: contentLabel,
|
||||
callback: function() {
|
||||
const xyPlotNode = addNode(contentLabel, node);
|
||||
|
||||
// Center the X coordinate of the XY Plot node
|
||||
const centerXShift = (node.size[0] - xyPlotNode.size[0]) / 2;
|
||||
xyPlotNode.pos[0] += centerXShift;
|
||||
|
||||
// Adjust the Y position to place it below the loader node
|
||||
xyPlotNode.pos[1] += node.size[1] + 60;
|
||||
|
||||
// Depending on the node type, connect the appropriate output to the XY Plot node
|
||||
if (type === "Efficient") {
|
||||
node.connect(6, xyPlotNode, 0);
|
||||
} else if (type === "SDXL") {
|
||||
node.connect(3, xyPlotNode, 0);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function getMenuValues(type, node) {
|
||||
const subNodeTypes = [null, "XYPlot", "NoiseControl", "HiResFix", "TiledUpscale", "AnimateDiff"];
|
||||
const excludedSubNodeTypes = ["NoiseControl", "HiResFix", "TiledUpscale", "AnimateDiff"]; // Nodes to exclude from the menu
|
||||
|
||||
const menuValues = [];
|
||||
|
||||
// Add the new node types to the menu first for the correct order
|
||||
menuValues.push(createStackerNode(node, "LoRA"));
|
||||
menuValues.push(createStackerNode(node, "ControlNet"));
|
||||
|
||||
for (const subNodeType of subNodeTypes) {
|
||||
// Skip adding submenu items that are in the excludedSubNodeTypes array
|
||||
if (!excludedSubNodeTypes.includes(subNodeType)) {
|
||||
const menuEntry = createKSamplerEntry(node, type === "Efficient" ? "Eff" : "SDXL", subNodeType, type === "SDXL");
|
||||
menuValues.push(menuEntry);
|
||||
}
|
||||
}
|
||||
|
||||
// Insert the standalone XY Plot option after the KSampler without any subNodeTypes and before any other KSamplers with subNodeTypes
|
||||
menuValues.splice(3, 0, createXYPlotNode(node, type));
|
||||
|
||||
return menuValues;
|
||||
}
|
||||
|
||||
function showAddLinkMenuCommon(value, options, e, menu, node, type) {
|
||||
const values = getMenuValues(type, node);
|
||||
new LiteGraph.ContextMenu(values, {
|
||||
event: e,
|
||||
callback: null,
|
||||
parentMenu: menu,
|
||||
node: node
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
// Extension Definition
|
||||
app.registerExtension({
|
||||
name: "efficiency.addLinks",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
const linkTypes = {
|
||||
"Efficient Loader": "Efficient",
|
||||
"Eff. Loader SDXL": "SDXL"
|
||||
};
|
||||
|
||||
const linkType = linkTypes[nodeData.name];
|
||||
|
||||
if (linkType) {
|
||||
addMenuHandler(nodeType, function(insertOption) {
|
||||
insertOption({
|
||||
content: "⛓ Add link...",
|
||||
has_submenu: true,
|
||||
callback: (value, options, e, menu, node) => showAddLinkMenuCommon(value, options, e, menu, node, linkType)
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { addMenuHandler } from "./common/utils.js";
|
||||
import { addNode } from "./common/utils.js";
|
||||
|
||||
const connectionMap = {
|
||||
"KSampler (Efficient)": ["input", 5],
|
||||
"KSampler Adv. (Efficient)": ["input", 5],
|
||||
"KSampler SDXL (Eff.)": ["input", 3],
|
||||
"XY Plot": ["output", 0],
|
||||
"Noise Control Script": ["input & output", 0],
|
||||
"HighRes-Fix Script": ["input & output", 0],
|
||||
"Tiled Upscaler Script": ["input & output", 0],
|
||||
"AnimateDiff Script": ["output", 0]
|
||||
};
|
||||
|
||||
/**
|
||||
* connect this node output to the input of another node
|
||||
* @method connect
|
||||
* @param {number_or_string} slot (could be the number of the slot or the string with the name of the slot)
|
||||
* @param {LGraphNode} node the target node
|
||||
* @param {number_or_string} target_slot the input slot of the target node (could be the number of the slot or the string with the name of the slot, or -1 to connect a trigger)
|
||||
* @return {Object} the link_info is created, otherwise null
|
||||
LGraphNode.prototype.connect = function(output_slot, target_node, input_slot)
|
||||
**/
|
||||
|
||||
function addAndConnectScriptNode(scriptType, selectedNode) {
|
||||
const selectedNodeType = connectionMap[selectedNode.type];
|
||||
const newNodeType = connectionMap[scriptType];
|
||||
|
||||
// 1. Create the new node without position adjustments
|
||||
const newNode = addNode(scriptType, selectedNode, { shiftX: 0, shiftY: 0 });
|
||||
|
||||
// 2. Adjust position of the new node based on conditions
|
||||
if (newNodeType[0].includes("input") && selectedNodeType[0].includes("output")) {
|
||||
newNode.pos[0] += selectedNode.size[0] + 50;
|
||||
} else if (newNodeType[0].includes("output") && selectedNodeType[0].includes("input")) {
|
||||
newNode.pos[0] -= (newNode.size[0] + 50);
|
||||
}
|
||||
|
||||
// 3. Logic for connecting the nodes
|
||||
switch (selectedNodeType[0]) {
|
||||
case "output":
|
||||
if (newNodeType[0] === "input & output") {
|
||||
// For every node that was previously connected to the selectedNode's output
|
||||
const connectedNodes = selectedNode.getOutputNodes(selectedNodeType[1]);
|
||||
if (connectedNodes && connectedNodes.length) {
|
||||
for (let connectedNode of connectedNodes) {
|
||||
// Disconnect the node from selectedNode's output
|
||||
selectedNode.disconnectOutput(selectedNodeType[1]);
|
||||
// Connect the newNode's output to the previously connected node,
|
||||
// using the appropriate slot based on the type of the connectedNode
|
||||
const targetSlot = (connectedNode.type in connectionMap) ? connectionMap[connectedNode.type][1] : 0;
|
||||
newNode.connect(0, connectedNode, targetSlot);
|
||||
}
|
||||
}
|
||||
// Connect selectedNode's output to newNode's input
|
||||
selectedNode.connect(selectedNodeType[1], newNode, newNodeType[1]);
|
||||
}
|
||||
break;
|
||||
|
||||
case "input":
|
||||
if (newNodeType[0] === "output") {
|
||||
newNode.connect(0, selectedNode, selectedNodeType[1]);
|
||||
} else if (newNodeType[0] === "input & output") {
|
||||
const ogInputNode = selectedNode.getInputNode(selectedNodeType[1]);
|
||||
if (ogInputNode) {
|
||||
ogInputNode.connect(0, newNode, 0);
|
||||
}
|
||||
newNode.connect(0, selectedNode, selectedNodeType[1]);
|
||||
}
|
||||
break;
|
||||
case "input & output":
|
||||
if (newNodeType[0] === "output") {
|
||||
newNode.connect(0, selectedNode, 0);
|
||||
} else if (newNodeType[0] === "input & output") {
|
||||
|
||||
const connectedNodes = selectedNode.getOutputNodes(0);
|
||||
if (connectedNodes && connectedNodes.length) {
|
||||
for (let connectedNode of connectedNodes) {
|
||||
selectedNode.disconnectOutput(0);
|
||||
newNode.connect(0, connectedNode, connectedNode.type in connectionMap ? connectionMap[connectedNode.type][1] : 0);
|
||||
}
|
||||
}
|
||||
// Connect selectedNode's output to newNode's input
|
||||
selectedNode.connect(selectedNodeType[1], newNode, newNodeType[1]);
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return newNode;
|
||||
}
|
||||
|
||||
function createScriptEntry(node, scriptType) {
|
||||
return {
|
||||
content: scriptType,
|
||||
callback: function() {
|
||||
addAndConnectScriptNode(scriptType, node);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function getScriptOptions(nodeType, node) {
|
||||
const allScriptTypes = [
|
||||
"XY Plot",
|
||||
"Noise Control Script",
|
||||
"HighRes-Fix Script",
|
||||
"Tiled Upscaler Script",
|
||||
"AnimateDiff Script"
|
||||
];
|
||||
|
||||
// Filter script types based on node type
|
||||
const scriptTypes = allScriptTypes.filter(scriptType => {
|
||||
const scriptBehavior = connectionMap[scriptType][0];
|
||||
|
||||
if (connectionMap[nodeType][0] === "output") {
|
||||
return scriptBehavior.includes("input"); // Includes nodes that are "input" or "input & output"
|
||||
} else {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
return scriptTypes.map(script => createScriptEntry(node, script));
|
||||
}
|
||||
|
||||
|
||||
function showAddScriptMenu(_, options, e, menu, node) {
|
||||
const scriptOptions = getScriptOptions(node.type, node);
|
||||
new LiteGraph.ContextMenu(scriptOptions, {
|
||||
event: e,
|
||||
callback: null,
|
||||
parentMenu: menu,
|
||||
node: node
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
// Extension Definition
|
||||
app.registerExtension({
|
||||
name: "efficiency.addScripts",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
if (connectionMap[nodeData.name]) {
|
||||
addMenuHandler(nodeType, function(insertOption) {
|
||||
insertOption({
|
||||
content: "📜 Add script...",
|
||||
has_submenu: true,
|
||||
callback: showAddScriptMenu
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { addMenuHandler, addNode } from "./common/utils.js";
|
||||
|
||||
const nodePxOffsets = 80;
|
||||
|
||||
function getXYInputNodes() {
|
||||
return [
|
||||
"XY Input: Seeds++ Batch",
|
||||
"XY Input: Add/Return Noise",
|
||||
"XY Input: Steps",
|
||||
"XY Input: CFG Scale",
|
||||
"XY Input: Sampler/Scheduler",
|
||||
"XY Input: Denoise",
|
||||
"XY Input: VAE",
|
||||
"XY Input: Prompt S/R",
|
||||
"XY Input: Aesthetic Score",
|
||||
"XY Input: Refiner On/Off",
|
||||
"XY Input: Checkpoint",
|
||||
"XY Input: Clip Skip",
|
||||
"XY Input: LoRA",
|
||||
"XY Input: LoRA Plot",
|
||||
"XY Input: LoRA Stacks",
|
||||
"XY Input: Control Net",
|
||||
"XY Input: Control Net Plot",
|
||||
"XY Input: Manual XY Entry"
|
||||
];
|
||||
}
|
||||
|
||||
function showAddXYInputMenu(type, e, menu, node) {
|
||||
const specialNodes = [
|
||||
"XY Input: LoRA Plot",
|
||||
"XY Input: Control Net Plot",
|
||||
"XY Input: Manual XY Entry"
|
||||
];
|
||||
|
||||
const values = getXYInputNodes().map(nodeType => {
|
||||
return {
|
||||
content: nodeType,
|
||||
callback: function() {
|
||||
const newNode = addNode(nodeType, node);
|
||||
|
||||
// Calculate the left shift based on the width of the new node
|
||||
const shiftX = -(newNode.size[0] + 35);
|
||||
newNode.pos[0] += shiftX;
|
||||
|
||||
if (specialNodes.includes(nodeType)) {
|
||||
newNode.pos[1] += 20;
|
||||
// Connect both outputs to the XY Plot's 2nd and 3rd input.
|
||||
newNode.connect(0, node, 1);
|
||||
newNode.connect(1, node, 2);
|
||||
} else if (type === 'X') {
|
||||
newNode.pos[1] += 20;
|
||||
newNode.connect(0, node, 1); // Connect to 2nd input
|
||||
} else {
|
||||
newNode.pos[1] += node.size[1] + 45;
|
||||
newNode.connect(0, node, 2); // Connect to 3rd input
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
new LiteGraph.ContextMenu(values, {
|
||||
event: e,
|
||||
callback: null,
|
||||
parentMenu: menu,
|
||||
node: node
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "efficiency.addXYinputs",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
if (nodeData.name === "XY Plot") {
|
||||
addMenuHandler(nodeType, function(insertOption) {
|
||||
insertOption({
|
||||
content: "✏️ Add 𝚇 input...",
|
||||
has_submenu: true,
|
||||
callback: (value, options, e, menu, node) => showAddXYInputMenu('X', e, menu, node)
|
||||
});
|
||||
insertOption({
|
||||
content: "✏️ Add 𝚈 input...",
|
||||
has_submenu: true,
|
||||
callback: (value, options, e, menu, node) => showAddXYInputMenu('Y', e, menu, node)
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -1,104 +0,0 @@
|
||||
.pysssss-model-info {
|
||||
color: white;
|
||||
font-family: sans-serif;
|
||||
max-width: 90vw;
|
||||
}
|
||||
.pysssss-model-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
.pysssss-model-info h2 {
|
||||
text-align: center;
|
||||
margin: 0 0 10px 0;
|
||||
}
|
||||
.pysssss-model-info p {
|
||||
margin: 5px 0;
|
||||
}
|
||||
.pysssss-model-info a {
|
||||
color: dodgerblue;
|
||||
}
|
||||
.pysssss-model-info a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.pysssss-model-tags-list {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
list-style: none;
|
||||
gap: 10px;
|
||||
max-height: 200px;
|
||||
overflow: auto;
|
||||
margin: 10px 0;
|
||||
padding: 0;
|
||||
}
|
||||
.pysssss-model-tag {
|
||||
background-color: rgb(128, 213, 247);
|
||||
color: #000;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
border-radius: 5px;
|
||||
padding: 2px 5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.pysssss-model-tag--selected span::before {
|
||||
content: "✅";
|
||||
position: absolute;
|
||||
background-color: dodgerblue;
|
||||
left: 0;
|
||||
top: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
text-align: center;
|
||||
}
|
||||
.pysssss-model-tag:hover {
|
||||
outline: 2px solid dodgerblue;
|
||||
}
|
||||
.pysssss-model-tag p {
|
||||
margin: 0;
|
||||
}
|
||||
.pysssss-model-tag span {
|
||||
text-align: center;
|
||||
border-radius: 5px;
|
||||
background-color: dodgerblue;
|
||||
color: #fff;
|
||||
padding: 2px;
|
||||
position: relative;
|
||||
min-width: 20px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.pysssss-model-metadata .comfy-modal-content {
|
||||
max-width: 100%;
|
||||
}
|
||||
.pysssss-model-metadata label {
|
||||
margin-right: 1ch;
|
||||
color: #ccc;
|
||||
}
|
||||
|
||||
.pysssss-model-metadata span {
|
||||
color: dodgerblue;
|
||||
}
|
||||
|
||||
.pysssss-preview {
|
||||
max-width: 50%;
|
||||
margin-left: 10px;
|
||||
position: relative;
|
||||
}
|
||||
.pysssss-preview img {
|
||||
max-height: 300px;
|
||||
}
|
||||
.pysssss-preview button {
|
||||
position: absolute;
|
||||
font-size: 12px;
|
||||
bottom: 10px;
|
||||
right: 10px;
|
||||
}
|
||||
.pysssss-model-notes {
|
||||
background-color: rgba(0, 0, 0, 0.25);
|
||||
padding: 5px;
|
||||
margin-top: 5px;
|
||||
}
|
||||
.pysssss-model-notes:empty {
|
||||
display: none;
|
||||
}
|
||||
@@ -1,303 +0,0 @@
|
||||
import { $el, ComfyDialog } from "../../../../scripts/ui.js";
|
||||
import { api } from "../../../../scripts/api.js";
|
||||
import { addStylesheet } from "./utils.js";
|
||||
|
||||
addStylesheet(import.meta.url);
|
||||
|
||||
class MetadataDialog extends ComfyDialog {
|
||||
constructor() {
|
||||
super();
|
||||
|
||||
this.element.classList.add("pysssss-model-metadata");
|
||||
}
|
||||
show(metadata) {
|
||||
super.show(
|
||||
$el(
|
||||
"div",
|
||||
Object.keys(metadata).map((k) =>
|
||||
$el("div", [$el("label", { textContent: k }), $el("span", { textContent: metadata[k] })])
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class ModelInfoDialog extends ComfyDialog {
|
||||
constructor(name) {
|
||||
super();
|
||||
this.name = name;
|
||||
this.element.classList.add("pysssss-model-info");
|
||||
}
|
||||
|
||||
get customNotes() {
|
||||
return this.metadata["pysssss.notes"];
|
||||
}
|
||||
|
||||
set customNotes(v) {
|
||||
this.metadata["pysssss.notes"] = v;
|
||||
}
|
||||
|
||||
get hash() {
|
||||
return this.metadata["pysssss.sha256"];
|
||||
}
|
||||
|
||||
async show(type, value) {
|
||||
this.type = type;
|
||||
|
||||
const req = api.fetchApi("/pysssss/metadata/" + encodeURIComponent(`${type}/${value}`));
|
||||
this.info = $el("div", { style: { flex: "auto" } });
|
||||
this.img = $el("img", { style: { display: "none" } });
|
||||
this.imgWrapper = $el("div.pysssss-preview", [this.img]);
|
||||
this.main = $el("main", { style: { display: "flex" } }, [this.info, this.imgWrapper]);
|
||||
this.content = $el("div.pysssss-model-content", [$el("h2", { textContent: this.name }), this.main]);
|
||||
|
||||
const loading = $el("div", { textContent: "ℹ️ Loading...", parent: this.content });
|
||||
|
||||
super.show(this.content);
|
||||
|
||||
this.metadata = await (await req).json();
|
||||
this.viewMetadata.style.cursor = this.viewMetadata.style.opacity = "";
|
||||
this.viewMetadata.removeAttribute("disabled");
|
||||
|
||||
loading.remove();
|
||||
this.addInfo();
|
||||
}
|
||||
|
||||
createButtons() {
|
||||
const btns = super.createButtons();
|
||||
this.viewMetadata = $el("button", {
|
||||
type: "button",
|
||||
textContent: "View raw metadata",
|
||||
disabled: "disabled",
|
||||
style: {
|
||||
opacity: 0.5,
|
||||
cursor: "not-allowed",
|
||||
},
|
||||
onclick: (e) => {
|
||||
if (this.metadata) {
|
||||
new MetadataDialog().show(this.metadata);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
btns.unshift(this.viewMetadata);
|
||||
return btns;
|
||||
}
|
||||
|
||||
getNoteInfo() {
|
||||
function parseNote() {
|
||||
if (!this.customNotes) return [];
|
||||
|
||||
let notes = [];
|
||||
// Extract links from notes
|
||||
const r = new RegExp("(\\bhttps?:\\/\\/[^\\s]+)", "g");
|
||||
let end = 0;
|
||||
let m;
|
||||
do {
|
||||
m = r.exec(this.customNotes);
|
||||
let pos;
|
||||
let fin = 0;
|
||||
if (m) {
|
||||
pos = m.index;
|
||||
fin = m.index + m[0].length;
|
||||
} else {
|
||||
pos = this.customNotes.length;
|
||||
}
|
||||
|
||||
let pre = this.customNotes.substring(end, pos);
|
||||
if (pre) {
|
||||
pre = pre.replaceAll("\n", "<br>");
|
||||
notes.push(
|
||||
$el("span", {
|
||||
innerHTML: pre,
|
||||
})
|
||||
);
|
||||
}
|
||||
if (m) {
|
||||
notes.push(
|
||||
$el("a", {
|
||||
href: m[0],
|
||||
textContent: m[0],
|
||||
target: "_blank",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
end = fin;
|
||||
} while (m);
|
||||
return notes;
|
||||
}
|
||||
|
||||
let textarea;
|
||||
let notesContainer;
|
||||
const editText = "✏️ Edit";
|
||||
const edit = $el("a", {
|
||||
textContent: editText,
|
||||
href: "#",
|
||||
style: {
|
||||
float: "right",
|
||||
color: "greenyellow",
|
||||
textDecoration: "none",
|
||||
},
|
||||
onclick: async (e) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (textarea) {
|
||||
this.customNotes = textarea.value;
|
||||
|
||||
const resp = await api.fetchApi(
|
||||
"/pysssss/metadata/notes/" + encodeURIComponent(`${this.type}/${this.name}`),
|
||||
{
|
||||
method: "POST",
|
||||
body: this.customNotes,
|
||||
}
|
||||
);
|
||||
|
||||
if (resp.status !== 200) {
|
||||
console.error(resp);
|
||||
alert(`Error saving notes (${req.status}) ${req.statusText}`);
|
||||
return;
|
||||
}
|
||||
|
||||
e.target.textContent = editText;
|
||||
textarea.remove();
|
||||
textarea = null;
|
||||
|
||||
notesContainer.replaceChildren(...parseNote.call(this));
|
||||
} else {
|
||||
e.target.textContent = "💾 Save";
|
||||
textarea = $el("textarea", {
|
||||
style: {
|
||||
width: "100%",
|
||||
minWidth: "200px",
|
||||
minHeight: "50px",
|
||||
},
|
||||
textContent: this.customNotes,
|
||||
});
|
||||
e.target.after(textarea);
|
||||
notesContainer.replaceChildren();
|
||||
textarea.style.height = Math.min(textarea.scrollHeight, 300) + "px";
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
notesContainer = $el("div.pysssss-model-notes", parseNote.call(this));
|
||||
return $el(
|
||||
"div",
|
||||
{
|
||||
style: { display: "contents" },
|
||||
},
|
||||
[edit, notesContainer]
|
||||
);
|
||||
}
|
||||
|
||||
addInfo() {
|
||||
this.addInfoEntry("Notes", this.getNoteInfo());
|
||||
}
|
||||
|
||||
addInfoEntry(name, value) {
|
||||
return $el(
|
||||
"p",
|
||||
{
|
||||
parent: this.info,
|
||||
},
|
||||
[
|
||||
typeof name === "string" ? $el("label", { textContent: name + ": " }) : name,
|
||||
typeof value === "string" ? $el("span", { textContent: value }) : value,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
async getCivitaiDetails() {
|
||||
const req = await fetch("https://civitai.com/api/v1/model-versions/by-hash/" + this.hash);
|
||||
if (req.status === 200) {
|
||||
return await req.json();
|
||||
} else if (req.status === 404) {
|
||||
throw new Error("Model not found");
|
||||
} else {
|
||||
throw new Error(`Error loading info (${req.status}) ${req.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
addCivitaiInfo() {
|
||||
const promise = this.getCivitaiDetails();
|
||||
const content = $el("span", { textContent: "ℹ️ Loading..." });
|
||||
|
||||
this.addInfoEntry(
|
||||
$el("label", [
|
||||
$el("img", {
|
||||
style: {
|
||||
width: "18px",
|
||||
position: "relative",
|
||||
top: "3px",
|
||||
margin: "0 5px 0 0",
|
||||
},
|
||||
src: "https://civitai.com/favicon.ico",
|
||||
}),
|
||||
$el("span", { textContent: "Civitai: " }),
|
||||
]),
|
||||
content
|
||||
);
|
||||
|
||||
return promise
|
||||
.then((info) => {
|
||||
content.replaceChildren(
|
||||
$el("a", {
|
||||
href: "https://civitai.com/models/" + info.modelId,
|
||||
textContent: "View " + info.model.name,
|
||||
target: "_blank",
|
||||
})
|
||||
);
|
||||
|
||||
if (info.images?.length) {
|
||||
this.img.src = info.images[0].url;
|
||||
this.img.style.display = "";
|
||||
|
||||
this.imgSave = $el("button", {
|
||||
textContent: "Use as preview",
|
||||
parent: this.imgWrapper,
|
||||
onclick: async () => {
|
||||
// Convert the preview to a blob
|
||||
const blob = await (await fetch(this.img.src)).blob();
|
||||
|
||||
// Store it in temp
|
||||
const name = "temp_preview." + new URL(this.img.src).pathname.split(".")[1];
|
||||
const body = new FormData();
|
||||
body.append("image", new File([blob], name));
|
||||
body.append("overwrite", "true");
|
||||
body.append("type", "temp");
|
||||
|
||||
const resp = await api.fetchApi("/upload/image", {
|
||||
method: "POST",
|
||||
body,
|
||||
});
|
||||
|
||||
if (resp.status !== 200) {
|
||||
console.error(resp);
|
||||
alert(`Error saving preview (${req.status}) ${req.statusText}`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Use as preview
|
||||
await api.fetchApi("/pysssss/save/" + encodeURIComponent(`${this.type}/${this.name}`), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
filename: name,
|
||||
type: "temp",
|
||||
}),
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
},
|
||||
});
|
||||
app.refreshComboInNodes();
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return info;
|
||||
})
|
||||
.catch((err) => {
|
||||
content.textContent = "⚠️ " + err.message;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
import { app } from '../../../../scripts/app.js'
|
||||
import { $el } from "../../../../scripts/ui.js";
|
||||
|
||||
export function addStylesheet(url) {
|
||||
if (url.endsWith(".js")) {
|
||||
url = url.substr(0, url.length - 2) + "css";
|
||||
}
|
||||
$el("link", {
|
||||
parent: document.head,
|
||||
rel: "stylesheet",
|
||||
type: "text/css",
|
||||
href: url.startsWith("http") ? url : getUrl(url),
|
||||
});
|
||||
}
|
||||
|
||||
export function getUrl(path, baseUrl) {
|
||||
if (baseUrl) {
|
||||
return new URL(path, baseUrl).toString();
|
||||
} else {
|
||||
return new URL("../" + path, import.meta.url).toString();
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadImage(url) {
|
||||
return new Promise((res, rej) => {
|
||||
const img = new Image();
|
||||
img.onload = res;
|
||||
img.onerror = rej;
|
||||
img.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
export function addMenuHandler(nodeType, cb) {
|
||||
|
||||
const GROUPED_MENU_ORDER = {
|
||||
"🔄 Swap with...": 0,
|
||||
"⛓ Add link...": 1,
|
||||
"📜 Add script...": 2,
|
||||
"🔍 View model info...": 3,
|
||||
"🌱 Seed behavior...": 4,
|
||||
"📐 Set Resolution...": 5,
|
||||
"✏️ Add 𝚇 input...": 6,
|
||||
"✏️ Add 𝚈 input...": 7
|
||||
};
|
||||
|
||||
const originalGetOpts = nodeType.prototype.getExtraMenuOptions;
|
||||
|
||||
nodeType.prototype.getExtraMenuOptions = function () {
|
||||
let r = originalGetOpts ? originalGetOpts.apply(this, arguments) || [] : [];
|
||||
|
||||
const insertOption = (option) => {
|
||||
if (GROUPED_MENU_ORDER.hasOwnProperty(option.content)) {
|
||||
// Find the right position for the option
|
||||
let targetPos = r.length; // default to the end
|
||||
|
||||
for (let i = 0; i < r.length; i++) {
|
||||
if (GROUPED_MENU_ORDER.hasOwnProperty(r[i].content) &&
|
||||
GROUPED_MENU_ORDER[option.content] < GROUPED_MENU_ORDER[r[i].content]) {
|
||||
targetPos = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Insert the option at the determined position
|
||||
r.splice(targetPos, 0, option);
|
||||
} else {
|
||||
// If the option is not in the GROUPED_MENU_ORDER, simply add it to the end
|
||||
r.push(option);
|
||||
}
|
||||
};
|
||||
|
||||
cb.call(this, insertOption);
|
||||
|
||||
return r;
|
||||
};
|
||||
}
|
||||
|
||||
export function findWidgetByName(node, widgetName) {
|
||||
return node.widgets.find(widget => widget.name === widgetName);
|
||||
}
|
||||
|
||||
// Utility functions
|
||||
export function addNode(name, nextTo, options) {
|
||||
options = { select: true, shiftX: 0, shiftY: 0, before: false, ...(options || {}) };
|
||||
const node = LiteGraph.createNode(name);
|
||||
app.graph.add(node);
|
||||
node.pos = [
|
||||
nextTo.pos[0] + options.shiftX,
|
||||
nextTo.pos[1] + options.shiftY,
|
||||
];
|
||||
if (options.select) {
|
||||
app.canvas.selectNode(node, false);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
@@ -1,336 +0,0 @@
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { $el } from "../../../scripts/ui.js";
|
||||
import { ModelInfoDialog } from "./common/modelInfoDialog.js";
|
||||
import { addMenuHandler } from "./common/utils.js";
|
||||
|
||||
const MAX_TAGS = 500;
|
||||
|
||||
class LoraInfoDialog extends ModelInfoDialog {
|
||||
getTagFrequency() {
|
||||
if (!this.metadata.ss_tag_frequency) return [];
|
||||
|
||||
const datasets = JSON.parse(this.metadata.ss_tag_frequency);
|
||||
const tags = {};
|
||||
for (const setName in datasets) {
|
||||
const set = datasets[setName];
|
||||
for (const t in set) {
|
||||
if (t in tags) {
|
||||
tags[t] += set[t];
|
||||
} else {
|
||||
tags[t] = set[t];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Object.entries(tags).sort((a, b) => b[1] - a[1]);
|
||||
}
|
||||
|
||||
getResolutions() {
|
||||
let res = [];
|
||||
if (this.metadata.ss_bucket_info) {
|
||||
const parsed = JSON.parse(this.metadata.ss_bucket_info);
|
||||
if (parsed?.buckets) {
|
||||
for (const { resolution, count } of Object.values(parsed.buckets)) {
|
||||
res.push([count, `${resolution.join("x")} * ${count}`]);
|
||||
}
|
||||
}
|
||||
}
|
||||
res = res.sort((a, b) => b[0] - a[0]).map((a) => a[1]);
|
||||
let r = this.metadata.ss_resolution;
|
||||
if (r) {
|
||||
const s = r.split(",");
|
||||
const w = s[0].replace("(", "");
|
||||
const h = s[1].replace(")", "");
|
||||
res.push(`${w.trim()}x${h.trim()} (Base res)`);
|
||||
} else if ((r = this.metadata["modelspec.resolution"])) {
|
||||
res.push(r + " (Base res");
|
||||
}
|
||||
if (!res.length) {
|
||||
res.push("⚠️ Unknown");
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
getTagList(tags) {
|
||||
return tags.map((t) =>
|
||||
$el(
|
||||
"li.pysssss-model-tag",
|
||||
{
|
||||
dataset: {
|
||||
tag: t[0],
|
||||
},
|
||||
$: (el) => {
|
||||
el.onclick = () => {
|
||||
el.classList.toggle("pysssss-model-tag--selected");
|
||||
};
|
||||
},
|
||||
},
|
||||
[
|
||||
$el("p", {
|
||||
textContent: t[0],
|
||||
}),
|
||||
$el("span", {
|
||||
textContent: t[1],
|
||||
}),
|
||||
]
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
addTags() {
|
||||
let tags = this.getTagFrequency();
|
||||
let hasMore;
|
||||
if (tags?.length) {
|
||||
const c = tags.length;
|
||||
let list;
|
||||
if (c > MAX_TAGS) {
|
||||
tags = tags.slice(0, MAX_TAGS);
|
||||
hasMore = $el("p", [
|
||||
$el("span", { textContent: `⚠️ Only showing first ${MAX_TAGS} tags ` }),
|
||||
$el("a", {
|
||||
href: "#",
|
||||
textContent: `Show all ${c}`,
|
||||
onclick: () => {
|
||||
list.replaceChildren(...this.getTagList(this.getTagFrequency()));
|
||||
hasMore.remove();
|
||||
},
|
||||
}),
|
||||
]);
|
||||
}
|
||||
list = $el("ol.pysssss-model-tags-list", this.getTagList(tags));
|
||||
this.tags = $el("div", [list]);
|
||||
} else {
|
||||
this.tags = $el("p", { textContent: "⚠️ No tag frequency metadata found" });
|
||||
}
|
||||
|
||||
this.content.append(this.tags);
|
||||
|
||||
if (hasMore) {
|
||||
this.content.append(hasMore);
|
||||
}
|
||||
}
|
||||
|
||||
async addInfo() {
|
||||
this.addInfoEntry("Name", this.metadata.ss_output_name || "⚠️ Unknown");
|
||||
this.addInfoEntry("Base Model", this.metadata.ss_sd_model_name || "⚠️ Unknown");
|
||||
this.addInfoEntry("Clip Skip", this.metadata.ss_clip_skip || "⚠️ Unknown");
|
||||
|
||||
this.addInfoEntry(
|
||||
"Resolution",
|
||||
$el(
|
||||
"select",
|
||||
this.getResolutions().map((r) => $el("option", { textContent: r }))
|
||||
)
|
||||
);
|
||||
|
||||
super.addInfo();
|
||||
const p = this.addCivitaiInfo();
|
||||
this.addTags();
|
||||
|
||||
const info = await p;
|
||||
if (info) {
|
||||
$el(
|
||||
"p",
|
||||
{
|
||||
parent: this.content,
|
||||
textContent: "Trained Words: ",
|
||||
},
|
||||
[
|
||||
$el("pre", {
|
||||
textContent: info.trainedWords.join(", "),
|
||||
style: {
|
||||
whiteSpace: "pre-wrap",
|
||||
margin: "10px 0",
|
||||
background: "#222",
|
||||
padding: "5px",
|
||||
borderRadius: "5px",
|
||||
maxHeight: "250px",
|
||||
overflow: "auto",
|
||||
},
|
||||
}),
|
||||
]
|
||||
);
|
||||
$el("div", {
|
||||
parent: this.content,
|
||||
innerHTML: info.description,
|
||||
style: {
|
||||
maxHeight: "250px",
|
||||
overflow: "auto",
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
createButtons() {
|
||||
const btns = super.createButtons();
|
||||
|
||||
function copyTags(e, tags) {
|
||||
const textarea = $el("textarea", {
|
||||
parent: document.body,
|
||||
style: {
|
||||
position: "fixed",
|
||||
},
|
||||
textContent: tags.map((el) => el.dataset.tag).join(", "),
|
||||
});
|
||||
textarea.select();
|
||||
try {
|
||||
document.execCommand("copy");
|
||||
if (!e.target.dataset.text) {
|
||||
e.target.dataset.text = e.target.textContent;
|
||||
}
|
||||
e.target.textContent = "Copied " + tags.length + " tags";
|
||||
setTimeout(() => {
|
||||
e.target.textContent = e.target.dataset.text;
|
||||
}, 1000);
|
||||
} catch (ex) {
|
||||
prompt("Copy to clipboard: Ctrl+C, Enter", text);
|
||||
} finally {
|
||||
document.body.removeChild(textarea);
|
||||
}
|
||||
}
|
||||
|
||||
btns.unshift(
|
||||
$el("button", {
|
||||
type: "button",
|
||||
textContent: "Copy Selected",
|
||||
onclick: (e) => {
|
||||
copyTags(e, [...this.tags.querySelectorAll(".pysssss-model-tag--selected")]);
|
||||
},
|
||||
}),
|
||||
$el("button", {
|
||||
type: "button",
|
||||
textContent: "Copy All",
|
||||
onclick: (e) => {
|
||||
copyTags(e, [...this.tags.querySelectorAll(".pysssss-model-tag")]);
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
return btns;
|
||||
}
|
||||
}
|
||||
|
||||
class CheckpointInfoDialog extends ModelInfoDialog {
|
||||
async addInfo() {
|
||||
super.addInfo();
|
||||
const info = await this.addCivitaiInfo();
|
||||
if (info) {
|
||||
this.addInfoEntry("Base Model", info.baseModel || "⚠️ Unknown");
|
||||
|
||||
$el("div", {
|
||||
parent: this.content,
|
||||
innerHTML: info.description,
|
||||
style: {
|
||||
maxHeight: "250px",
|
||||
overflow: "auto",
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const generateNames = (prefix, start, end) => {
|
||||
const result = [];
|
||||
if (start < end) {
|
||||
for (let i = start; i <= end; i++) {
|
||||
result.push(`${prefix}${i}`);
|
||||
}
|
||||
} else {
|
||||
for (let i = start; i >= end; i--) {
|
||||
result.push(`${prefix}${i}`);
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// NOTE: Orders reversed so they appear in ascending order
|
||||
const infoHandler = {
|
||||
"Efficient Loader": {
|
||||
"loras": ["lora_name"],
|
||||
"checkpoints": ["ckpt_name"]
|
||||
},
|
||||
"Eff. Loader SDXL": {
|
||||
"checkpoints": ["refiner_ckpt_name", "base_ckpt_name"]
|
||||
},
|
||||
"LoRA Stacker": {
|
||||
"loras": generateNames("lora_name_", 50, 1)
|
||||
},
|
||||
"XY Input: LoRA": {
|
||||
"loras": generateNames("lora_name_", 50, 1)
|
||||
},
|
||||
"HighRes-Fix Script": {
|
||||
"checkpoints": ["hires_ckpt_name"]
|
||||
}
|
||||
};
|
||||
|
||||
// Utility functions and other parts of your code remain unchanged
|
||||
|
||||
app.registerExtension({
|
||||
name: "efficiency.ModelInfo",
|
||||
beforeRegisterNodeDef(nodeType) {
|
||||
const types = infoHandler[nodeType.comfyClass];
|
||||
|
||||
if (types) {
|
||||
addMenuHandler(nodeType, function (insertOption) { // Here, we are calling addMenuHandler
|
||||
let submenuItems = []; // to store submenu items
|
||||
|
||||
const addSubMenuOption = (type, widgetNames) => {
|
||||
widgetNames.forEach(widgetName => {
|
||||
const widgetValue = this.widgets.find(w => w.name === widgetName)?.value;
|
||||
|
||||
// Check if widgetValue is "None"
|
||||
if (!widgetValue || widgetValue === "None") {
|
||||
return;
|
||||
}
|
||||
|
||||
let value = widgetValue;
|
||||
if (value.content) {
|
||||
value = value.content;
|
||||
}
|
||||
const cls = type === "loras" ? LoraInfoDialog : CheckpointInfoDialog;
|
||||
|
||||
const label = widgetName;
|
||||
|
||||
// Push to submenuItems
|
||||
submenuItems.push({
|
||||
content: label,
|
||||
callback: async () => {
|
||||
new cls(value).show(type, value);
|
||||
},
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
if (typeof types === 'object') {
|
||||
Object.keys(types).forEach(type => {
|
||||
addSubMenuOption(type, types[type]);
|
||||
});
|
||||
}
|
||||
|
||||
// If we have submenu items, use insertOption
|
||||
if (submenuItems.length) {
|
||||
insertOption({ // Using insertOption here
|
||||
content: "🔍 View model info...",
|
||||
has_submenu: true,
|
||||
callback: (value, options, e, menu, node) => {
|
||||
new LiteGraph.ContextMenu(submenuItems, {
|
||||
event: e,
|
||||
callback: null,
|
||||
parentMenu: menu,
|
||||
node: node
|
||||
});
|
||||
|
||||
return false; // This ensures the original context menu doesn't proceed
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
// Additional functions and imports
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { addMenuHandler, findWidgetByName } from "./common/utils.js";
|
||||
|
||||
// A mapping for resolutions based on the type of the loader
|
||||
const RESOLUTIONS = {
|
||||
"Efficient Loader": [
|
||||
{width: 512, height: 512},
|
||||
{width: 512, height: 768},
|
||||
{width: 512, height: 640},
|
||||
{width: 640, height: 512},
|
||||
{width: 640, height: 768},
|
||||
{width: 640, height: 640},
|
||||
{width: 768, height: 512},
|
||||
{width: 768, height: 768},
|
||||
{width: 768, height: 640},
|
||||
],
|
||||
"Eff. Loader SDXL": [
|
||||
{width: 1024, height: 1024},
|
||||
{width: 1152, height: 896},
|
||||
{width: 896, height: 1152},
|
||||
{width: 1216, height: 832},
|
||||
{width: 832, height: 1216},
|
||||
{width: 1344, height: 768},
|
||||
{width: 768, height: 1344},
|
||||
{width: 1536, height: 640},
|
||||
{width: 640, height: 1536}
|
||||
]
|
||||
};
|
||||
|
||||
// Function to set the resolution of a node
|
||||
function setNodeResolution(node, width, height) {
|
||||
let widthWidget = findWidgetByName(node, "empty_latent_width");
|
||||
let heightWidget = findWidgetByName(node, "empty_latent_height");
|
||||
|
||||
if (widthWidget) {
|
||||
widthWidget.value = width;
|
||||
}
|
||||
|
||||
if (heightWidget) {
|
||||
heightWidget.value = height;
|
||||
}
|
||||
}
|
||||
|
||||
// The callback for the resolution submenu
|
||||
function resolutionMenuCallback(node, width, height) {
|
||||
return function() {
|
||||
setNodeResolution(node, width, height);
|
||||
};
|
||||
}
|
||||
|
||||
// Show the set resolution submenu
|
||||
function showResolutionMenu(value, options, e, menu, node) {
|
||||
const resolutions = RESOLUTIONS[node.type];
|
||||
if (!resolutions) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const resolutionOptions = resolutions.map(res => ({
|
||||
content: `${res.width} x ${res.height}`,
|
||||
callback: resolutionMenuCallback(node, res.width, res.height)
|
||||
}));
|
||||
|
||||
new LiteGraph.ContextMenu(resolutionOptions, {
|
||||
event: e,
|
||||
callback: null,
|
||||
parentMenu: menu,
|
||||
node: node
|
||||
});
|
||||
|
||||
return false; // This ensures the original context menu doesn't proceed
|
||||
}
|
||||
|
||||
// Extension Definition
|
||||
app.registerExtension({
|
||||
name: "efficiency.SetResolution",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
if (["Efficient Loader", "Eff. Loader SDXL"].includes(nodeData.name)) {
|
||||
addMenuHandler(nodeType, function (insertOption) {
|
||||
insertOption({
|
||||
content: "📐 Set Resolution...",
|
||||
has_submenu: true,
|
||||
callback: showResolutionMenu
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -1,135 +0,0 @@
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { addMenuHandler } from "./common/utils.js";
|
||||
import { findWidgetByName } from "./common/utils.js";
|
||||
|
||||
function replaceNode(oldNode, newNodeName) {
|
||||
const newNode = LiteGraph.createNode(newNodeName);
|
||||
if (!newNode) {
|
||||
return;
|
||||
}
|
||||
app.graph.add(newNode);
|
||||
|
||||
newNode.pos = oldNode.pos.slice();
|
||||
newNode.size = oldNode.size.slice();
|
||||
|
||||
// Transfer widget values
|
||||
const widgetMapping = {
|
||||
"ckpt_name": "base_ckpt_name",
|
||||
"vae_name": "vae_name",
|
||||
"clip_skip": "base_clip_skip",
|
||||
"positive": "positive",
|
||||
"negative": "negative",
|
||||
"prompt_style": "prompt_style",
|
||||
"empty_latent_width": "empty_latent_width",
|
||||
"empty_latent_height": "empty_latent_height",
|
||||
"batch_size": "batch_size"
|
||||
};
|
||||
|
||||
let effectiveWidgetMapping = widgetMapping;
|
||||
|
||||
// Invert the mapping when going from "Eff. Loader SDXL" to "Efficient Loader"
|
||||
if (oldNode.type === "Eff. Loader SDXL" && newNodeName === "Efficient Loader") {
|
||||
effectiveWidgetMapping = {};
|
||||
for (const [key, value] of Object.entries(widgetMapping)) {
|
||||
effectiveWidgetMapping[value] = key;
|
||||
}
|
||||
}
|
||||
|
||||
oldNode.widgets.forEach(widget => {
|
||||
const newName = effectiveWidgetMapping[widget.name];
|
||||
if (newName) {
|
||||
const newWidget = findWidgetByName(newNode, newName);
|
||||
if (newWidget) {
|
||||
newWidget.value = widget.value;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Hardcoded transfer for specific outputs based on the output names from the nodes in the image
|
||||
const outputMapping = {
|
||||
"MODEL": null, // Not present in "Eff. Loader SDXL"
|
||||
"CONDITIONING+": null, // Not present in "Eff. Loader SDXL"
|
||||
"CONDITIONING-": null, // Not present in "Eff. Loader SDXL"
|
||||
"LATENT": "LATENT",
|
||||
"VAE": "VAE",
|
||||
"CLIP": null, // Not present in "Eff. Loader SDXL"
|
||||
"DEPENDENCIES": "DEPENDENCIES"
|
||||
};
|
||||
|
||||
// Transfer connections from old node outputs to new node outputs based on the outputMapping
|
||||
oldNode.outputs.forEach((output, index) => {
|
||||
if (output && output.links && outputMapping[output.name]) {
|
||||
const newOutputName = outputMapping[output.name];
|
||||
|
||||
// If the new node does not have this output, skip
|
||||
if (newOutputName === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
const newOutputIndex = newNode.findOutputSlot(newOutputName);
|
||||
if (newOutputIndex !== -1) {
|
||||
output.links.forEach(link => {
|
||||
const targetLinkInfo = oldNode.graph.links[link];
|
||||
if (targetLinkInfo) {
|
||||
const targetNode = oldNode.graph.getNodeById(targetLinkInfo.target_id);
|
||||
if (targetNode) {
|
||||
newNode.connect(newOutputIndex, targetNode, targetLinkInfo.target_slot);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Remove old node
|
||||
app.graph.remove(oldNode);
|
||||
}
|
||||
|
||||
function replaceNodeMenuCallback(currentNode, targetNodeName) {
|
||||
return function() {
|
||||
replaceNode(currentNode, targetNodeName);
|
||||
};
|
||||
}
|
||||
|
||||
function showSwapMenu(value, options, e, menu, node) {
|
||||
const swapOptions = [];
|
||||
|
||||
if (node.type !== "Efficient Loader") {
|
||||
swapOptions.push({
|
||||
content: "Efficient Loader",
|
||||
callback: replaceNodeMenuCallback(node, "Efficient Loader")
|
||||
});
|
||||
}
|
||||
|
||||
if (node.type !== "Eff. Loader SDXL") {
|
||||
swapOptions.push({
|
||||
content: "Eff. Loader SDXL",
|
||||
callback: replaceNodeMenuCallback(node, "Eff. Loader SDXL")
|
||||
});
|
||||
}
|
||||
|
||||
new LiteGraph.ContextMenu(swapOptions, {
|
||||
event: e,
|
||||
callback: null,
|
||||
parentMenu: menu,
|
||||
node: node
|
||||
});
|
||||
|
||||
return false; // This ensures the original context menu doesn't proceed
|
||||
}
|
||||
|
||||
// Extension Definition
|
||||
app.registerExtension({
|
||||
name: "efficiency.SwapLoaders",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
if (["Efficient Loader", "Eff. Loader SDXL"].includes(nodeData.name)) {
|
||||
addMenuHandler(nodeType, function (insertOption) {
|
||||
insertOption({
|
||||
content: "🔄 Swap with...",
|
||||
has_submenu: true,
|
||||
callback: showSwapMenu
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -1,191 +0,0 @@
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { addMenuHandler } from "./common/utils.js";
|
||||
import { findWidgetByName } from "./common/utils.js";
|
||||
|
||||
function replaceNode(oldNode, newNodeName) {
|
||||
// Create new node
|
||||
const newNode = LiteGraph.createNode(newNodeName);
|
||||
if (!newNode) {
|
||||
return;
|
||||
}
|
||||
app.graph.add(newNode);
|
||||
|
||||
// Position new node at the same position as the old node
|
||||
newNode.pos = oldNode.pos.slice();
|
||||
|
||||
// Define widget mappings
|
||||
const mappings = {
|
||||
"KSampler (Efficient) <-> KSampler Adv. (Efficient)": {
|
||||
seed: "noise_seed",
|
||||
cfg: "cfg",
|
||||
sampler_name: "sampler_name",
|
||||
scheduler: "scheduler",
|
||||
preview_method: "preview_method",
|
||||
vae_decode: "vae_decode"
|
||||
},
|
||||
"KSampler (Efficient) <-> KSampler SDXL (Eff.)": {
|
||||
seed: "noise_seed",
|
||||
cfg: "cfg",
|
||||
sampler_name: "sampler_name",
|
||||
scheduler: "scheduler",
|
||||
preview_method: "preview_method",
|
||||
vae_decode: "vae_decode"
|
||||
},
|
||||
"KSampler Adv. (Efficient) <-> KSampler SDXL (Eff.)": {
|
||||
noise_seed: "noise_seed",
|
||||
steps: "steps",
|
||||
cfg: "cfg",
|
||||
sampler_name: "sampler_name",
|
||||
scheduler: "scheduler",
|
||||
start_at_step: "start_at_step",
|
||||
preview_method: "preview_method",
|
||||
vae_decode: "vae_decode"}
|
||||
};
|
||||
|
||||
const swapKey = `${oldNode.type} <-> ${newNodeName}`;
|
||||
|
||||
let widgetMapping = {};
|
||||
|
||||
// Check if a reverse mapping is needed
|
||||
if (!mappings[swapKey]) {
|
||||
const reverseKey = `${newNodeName} <-> ${oldNode.type}`;
|
||||
const reverseMapping = mappings[reverseKey];
|
||||
if (reverseMapping) {
|
||||
widgetMapping = Object.entries(reverseMapping).reduce((acc, [key, value]) => {
|
||||
acc[value] = key;
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
} else {
|
||||
widgetMapping = mappings[swapKey];
|
||||
}
|
||||
|
||||
if (oldNode.type === "KSampler (Efficient)" && (newNodeName === "KSampler Adv. (Efficient)" || newNodeName === "KSampler SDXL (Eff.)")) {
|
||||
const denoise = Math.min(Math.max(findWidgetByName(oldNode, "denoise").value, 0), 1); // Ensure denoise is between 0 and 1
|
||||
const steps = Math.min(Math.max(findWidgetByName(oldNode, "steps").value, 0), 10000); // Ensure steps is between 0 and 10000
|
||||
|
||||
const total_steps = Math.floor(steps / denoise);
|
||||
const start_at_step = total_steps - steps;
|
||||
|
||||
findWidgetByName(newNode, "steps").value = Math.min(Math.max(total_steps, 0), 10000); // Ensure total_steps is between 0 and 10000
|
||||
findWidgetByName(newNode, "start_at_step").value = Math.min(Math.max(start_at_step, 0), 10000); // Ensure start_at_step is between 0 and 10000
|
||||
}
|
||||
else if ((oldNode.type === "KSampler Adv. (Efficient)" || oldNode.type === "KSampler SDXL (Eff.)") && newNodeName === "KSampler (Efficient)") {
|
||||
const stepsAdv = Math.min(Math.max(findWidgetByName(oldNode, "steps").value, 0), 10000); // Ensure stepsAdv is between 0 and 10000
|
||||
const start_at_step = Math.min(Math.max(findWidgetByName(oldNode, "start_at_step").value, 0), 10000); // Ensure start_at_step is between 0 and 10000
|
||||
|
||||
const denoise = Math.min(Math.max((stepsAdv - start_at_step) / stepsAdv, 0), 1); // Ensure denoise is between 0 and 1
|
||||
const stepsTotal = stepsAdv - start_at_step;
|
||||
|
||||
findWidgetByName(newNode, "denoise").value = denoise;
|
||||
findWidgetByName(newNode, "steps").value = Math.min(Math.max(stepsTotal, 0), 10000); // Ensure stepsTotal is between 0 and 10000
|
||||
}
|
||||
|
||||
// Transfer widget values from old node to new node
|
||||
oldNode.widgets.forEach(widget => {
|
||||
const newName = widgetMapping[widget.name];
|
||||
if (newName) {
|
||||
const newWidget = findWidgetByName(newNode, newName);
|
||||
if (newWidget) {
|
||||
newWidget.value = widget.value;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Determine the starting indices based on the node types
|
||||
let oldNodeInputStartIndex = 0;
|
||||
let newNodeInputStartIndex = 0;
|
||||
let oldNodeOutputStartIndex = 0;
|
||||
let newNodeOutputStartIndex = 0;
|
||||
|
||||
if (oldNode.type === "KSampler SDXL (Eff.)" || newNodeName === "KSampler SDXL (Eff.)") {
|
||||
oldNodeInputStartIndex = (oldNode.type === "KSampler SDXL (Eff.)") ? 1 : 3;
|
||||
newNodeInputStartIndex = (newNodeName === "KSampler SDXL (Eff.)") ? 1 : 3;
|
||||
oldNodeOutputStartIndex = (oldNode.type === "KSampler SDXL (Eff.)") ? 1 : 3;
|
||||
newNodeOutputStartIndex = (newNodeName === "KSampler SDXL (Eff.)") ? 1 : 3;
|
||||
}
|
||||
|
||||
// Transfer connections from old node to new node
|
||||
oldNode.inputs.slice(oldNodeInputStartIndex).forEach((input, index) => {
|
||||
if (input && input.link !== null) {
|
||||
const originLinkInfo = oldNode.graph.links[input.link];
|
||||
if (originLinkInfo) {
|
||||
const originNode = oldNode.graph.getNodeById(originLinkInfo.origin_id);
|
||||
if (originNode) {
|
||||
originNode.connect(originLinkInfo.origin_slot, newNode, index + newNodeInputStartIndex);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
oldNode.outputs.slice(oldNodeOutputStartIndex).forEach((output, index) => {
|
||||
if (output && output.links) {
|
||||
output.links.forEach(link => {
|
||||
const targetLinkInfo = oldNode.graph.links[link];
|
||||
if (targetLinkInfo) {
|
||||
const targetNode = oldNode.graph.getNodeById(targetLinkInfo.target_id);
|
||||
if (targetNode) {
|
||||
newNode.connect(index + newNodeOutputStartIndex, targetNode, targetLinkInfo.target_slot);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Remove old node
|
||||
app.graph.remove(oldNode);
|
||||
}
|
||||
|
||||
function replaceNodeMenuCallback(currentNode, targetNodeName) {
|
||||
return function() {
|
||||
replaceNode(currentNode, targetNodeName);
|
||||
};
|
||||
}
|
||||
|
||||
function showSwapMenu(value, options, e, menu, node) {
|
||||
const swapOptions = [];
|
||||
|
||||
if (node.type !== "KSampler (Efficient)") {
|
||||
swapOptions.push({
|
||||
content: "KSampler (Efficient)",
|
||||
callback: replaceNodeMenuCallback(node, "KSampler (Efficient)")
|
||||
});
|
||||
}
|
||||
if (node.type !== "KSampler Adv. (Efficient)") {
|
||||
swapOptions.push({
|
||||
content: "KSampler Adv. (Efficient)",
|
||||
callback: replaceNodeMenuCallback(node, "KSampler Adv. (Efficient)")
|
||||
});
|
||||
}
|
||||
if (node.type !== "KSampler SDXL (Eff.)") {
|
||||
swapOptions.push({
|
||||
content: "KSampler SDXL (Eff.)",
|
||||
callback: replaceNodeMenuCallback(node, "KSampler SDXL (Eff.)")
|
||||
});
|
||||
}
|
||||
|
||||
new LiteGraph.ContextMenu(swapOptions, {
|
||||
event: e,
|
||||
callback: null,
|
||||
parentMenu: menu,
|
||||
node: node
|
||||
});
|
||||
|
||||
return false; // This ensures the original context menu doesn't proceed
|
||||
}
|
||||
|
||||
// Extension Definition
|
||||
app.registerExtension({
|
||||
name: "efficiency.SwapSamplers",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
if (["KSampler (Efficient)", "KSampler Adv. (Efficient)", "KSampler SDXL (Eff.)"].includes(nodeData.name)) {
|
||||
addMenuHandler(nodeType, function (insertOption) {
|
||||
insertOption({
|
||||
content: "🔄 Swap with...",
|
||||
has_submenu: true,
|
||||
callback: showSwapMenu
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -1,100 +0,0 @@
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { addMenuHandler } from "./common/utils.js";
|
||||
|
||||
function replaceNode(oldNode, newNodeName) {
|
||||
const newNode = LiteGraph.createNode(newNodeName);
|
||||
if (!newNode) {
|
||||
return;
|
||||
}
|
||||
app.graph.add(newNode);
|
||||
|
||||
newNode.pos = oldNode.pos.slice();
|
||||
|
||||
// Transfer connections from old node to new node
|
||||
// XY Plot and AnimateDiff have only one output
|
||||
if(["XY Plot", "AnimateDiff Script"].includes(oldNode.type)) {
|
||||
if (oldNode.outputs[0] && oldNode.outputs[0].links) {
|
||||
oldNode.outputs[0].links.forEach(link => {
|
||||
const targetLinkInfo = oldNode.graph.links[link];
|
||||
if (targetLinkInfo) {
|
||||
const targetNode = oldNode.graph.getNodeById(targetLinkInfo.target_id);
|
||||
if (targetNode) {
|
||||
newNode.connect(0, targetNode, targetLinkInfo.target_slot);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Noise Control Script, HighRes-Fix Script, and Tiled Upscaler Script have 1 input and 1 output at index 0
|
||||
if (oldNode.inputs[0] && oldNode.inputs[0].link !== null) {
|
||||
const originLinkInfo = oldNode.graph.links[oldNode.inputs[0].link];
|
||||
if (originLinkInfo) {
|
||||
const originNode = oldNode.graph.getNodeById(originLinkInfo.origin_id);
|
||||
if (originNode) {
|
||||
originNode.connect(originLinkInfo.origin_slot, newNode, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (oldNode.outputs[0] && oldNode.outputs[0].links) {
|
||||
oldNode.outputs[0].links.forEach(link => {
|
||||
const targetLinkInfo = oldNode.graph.links[link];
|
||||
if (targetLinkInfo) {
|
||||
const targetNode = oldNode.graph.getNodeById(targetLinkInfo.target_id);
|
||||
if (targetNode) {
|
||||
newNode.connect(0, targetNode, targetLinkInfo.target_slot);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Remove old node
|
||||
app.graph.remove(oldNode);
|
||||
}
|
||||
|
||||
function replaceNodeMenuCallback(currentNode, targetNodeName) {
|
||||
return function() {
|
||||
replaceNode(currentNode, targetNodeName);
|
||||
};
|
||||
}
|
||||
|
||||
function showSwapMenu(value, options, e, menu, node) {
|
||||
const scriptNodes = [
|
||||
"XY Plot",
|
||||
"Noise Control Script",
|
||||
"HighRes-Fix Script",
|
||||
"Tiled Upscaler Script",
|
||||
"AnimateDiff Script"
|
||||
];
|
||||
|
||||
const swapOptions = scriptNodes.filter(n => n !== node.type).map(n => ({
|
||||
content: n,
|
||||
callback: replaceNodeMenuCallback(node, n)
|
||||
}));
|
||||
|
||||
new LiteGraph.ContextMenu(swapOptions, {
|
||||
event: e,
|
||||
callback: null,
|
||||
parentMenu: menu,
|
||||
node: node
|
||||
});
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// Extension Definition
|
||||
app.registerExtension({
|
||||
name: "efficiency.SwapScripts",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
if (["XY Plot", "Noise Control Script", "HighRes-Fix Script", "Tiled Upscaler Script", "AnimateDiff Script"].includes(nodeData.name)) {
|
||||
addMenuHandler(nodeType, function (insertOption) {
|
||||
insertOption({
|
||||
content: "🔄 Swap with...",
|
||||
has_submenu: true,
|
||||
callback: showSwapMenu
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -1,98 +0,0 @@
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { addMenuHandler } from "./common/utils.js";
|
||||
|
||||
function replaceNode(oldNode, newNodeName) {
|
||||
const newNode = LiteGraph.createNode(newNodeName);
|
||||
if (!newNode) {
|
||||
return;
|
||||
}
|
||||
app.graph.add(newNode);
|
||||
|
||||
newNode.pos = oldNode.pos.slice();
|
||||
|
||||
// Handle the special nodes with two outputs
|
||||
const nodesWithTwoOutputs = ["XY Input: LoRA Plot", "XY Input: Control Net Plot", "XY Input: Manual XY Entry"];
|
||||
let outputCount = nodesWithTwoOutputs.includes(oldNode.type) ? 2 : 1;
|
||||
|
||||
// Transfer output connections from old node to new node
|
||||
oldNode.outputs.slice(0, outputCount).forEach((output, index) => {
|
||||
if (output && output.links) {
|
||||
output.links.forEach(link => {
|
||||
const targetLinkInfo = oldNode.graph.links[link];
|
||||
if (targetLinkInfo) {
|
||||
const targetNode = oldNode.graph.getNodeById(targetLinkInfo.target_id);
|
||||
if (targetNode) {
|
||||
newNode.connect(index, targetNode, targetLinkInfo.target_slot);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Remove old node
|
||||
app.graph.remove(oldNode);
|
||||
}
|
||||
|
||||
function replaceNodeMenuCallback(currentNode, targetNodeName) {
|
||||
return function() {
|
||||
replaceNode(currentNode, targetNodeName);
|
||||
};
|
||||
}
|
||||
|
||||
function showSwapMenu(value, options, e, menu, node) {
|
||||
const swapOptions = [];
|
||||
const xyInputNodes = [
|
||||
"XY Input: Seeds++ Batch",
|
||||
"XY Input: Add/Return Noise",
|
||||
"XY Input: Steps",
|
||||
"XY Input: CFG Scale",
|
||||
"XY Input: Sampler/Scheduler",
|
||||
"XY Input: Denoise",
|
||||
"XY Input: VAE",
|
||||
"XY Input: Prompt S/R",
|
||||
"XY Input: Aesthetic Score",
|
||||
"XY Input: Refiner On/Off",
|
||||
"XY Input: Checkpoint",
|
||||
"XY Input: Clip Skip",
|
||||
"XY Input: LoRA",
|
||||
"XY Input: LoRA Plot",
|
||||
"XY Input: LoRA Stacks",
|
||||
"XY Input: Control Net",
|
||||
"XY Input: Control Net Plot",
|
||||
"XY Input: Manual XY Entry"
|
||||
];
|
||||
|
||||
for (const nodeType of xyInputNodes) {
|
||||
if (node.type !== nodeType) {
|
||||
swapOptions.push({
|
||||
content: nodeType,
|
||||
callback: replaceNodeMenuCallback(node, nodeType)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
new LiteGraph.ContextMenu(swapOptions, {
|
||||
event: e,
|
||||
callback: null,
|
||||
parentMenu: menu,
|
||||
node: node
|
||||
});
|
||||
|
||||
return false; // This ensures the original context menu doesn't proceed
|
||||
}
|
||||
|
||||
// Extension Definition
|
||||
app.registerExtension({
|
||||
name: "efficiency.swapXYinputs",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
if (nodeData.name.startsWith("XY Input:")) {
|
||||
addMenuHandler(nodeType, function (insertOption) {
|
||||
insertOption({
|
||||
content: "🔄 Swap with...",
|
||||
has_submenu: true,
|
||||
callback: showSwapMenu
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -1,67 +0,0 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
|
||||
app.registerExtension({
|
||||
name: "efficiency.previewfix",
|
||||
lastExecutedNodeId: null,
|
||||
blobsToRevoke: [], // Array to accumulate blob URLs for revocation
|
||||
debug: false,
|
||||
|
||||
log(...args) {
|
||||
if (this.debug) console.log(...args);
|
||||
},
|
||||
|
||||
error(...args) {
|
||||
if (this.debug) console.error(...args);
|
||||
},
|
||||
|
||||
shouldRevokeBlobForNode(nodeId) {
|
||||
const node = app.graph.getNodeById(nodeId);
|
||||
|
||||
const validTitles = [
|
||||
"KSampler (Efficient)",
|
||||
"KSampler Adv. (Efficient)",
|
||||
"KSampler SDXL (Eff.)"
|
||||
];
|
||||
|
||||
if (!node || !validTitles.includes(node.title)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const getValue = name => ((node.widgets || []).find(w => w.name === name) || {}).value;
|
||||
return getValue("preview_method") !== "none" && getValue("vae_decode").includes("true");
|
||||
},
|
||||
|
||||
setup() {
|
||||
// Intercepting blob creation to store and immediately revoke the last blob URL
|
||||
const originalCreateObjectURL = URL.createObjectURL;
|
||||
URL.createObjectURL = (object) => {
|
||||
const blobURL = originalCreateObjectURL(object);
|
||||
if (blobURL.startsWith('blob:')) {
|
||||
this.log("[BlobURLLogger] Blob URL created:", blobURL);
|
||||
|
||||
// If the current node meets the criteria, add the blob URL to the revocation list
|
||||
if (this.shouldRevokeBlobForNode(this.lastExecutedNodeId)) {
|
||||
this.blobsToRevoke.push(blobURL);
|
||||
}
|
||||
}
|
||||
return blobURL;
|
||||
};
|
||||
|
||||
// Listen to the start of the node execution to revoke all accumulated blob URLs
|
||||
api.addEventListener("executing", ({ detail }) => {
|
||||
if (this.lastExecutedNodeId !== detail || detail === null) {
|
||||
this.blobsToRevoke.forEach(blob => {
|
||||
this.log("[BlobURLLogger] Revoking Blob URL:", blob);
|
||||
URL.revokeObjectURL(blob);
|
||||
});
|
||||
this.blobsToRevoke = []; // Clear the list after revoking all blobs
|
||||
}
|
||||
|
||||
// Update the last executed node ID
|
||||
this.lastExecutedNodeId = detail;
|
||||
});
|
||||
|
||||
this.log("[BlobURLLogger] Hook attached.");
|
||||
},
|
||||
});
|
||||
@@ -1,251 +0,0 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { addMenuHandler } from "./node_options/common/utils.js";
|
||||
|
||||
const LAST_SEED_BUTTON_LABEL = '🎲 Randomize / ♻️ Last Queued Seed';
|
||||
const SEED_BEHAVIOR_RANDOMIZE = 'Randomize';
|
||||
const SEED_BEHAVIOR_INCREMENT = 'Increment';
|
||||
const SEED_BEHAVIOR_DECREMENT = 'Decrement';
|
||||
|
||||
const NODE_WIDGET_MAP = {
|
||||
"KSampler (Efficient)": "seed",
|
||||
"KSampler Adv. (Efficient)": "noise_seed",
|
||||
"KSampler SDXL (Eff.)": "noise_seed",
|
||||
"Noise Control Script": "seed",
|
||||
"HighRes-Fix Script": "seed",
|
||||
"Tiled Upscaler Script": "seed"
|
||||
};
|
||||
|
||||
const SPECIFIC_WIDTH = 325; // Set to desired width
|
||||
|
||||
function setNodeWidthForMappedTitles(node) {
|
||||
if (NODE_WIDGET_MAP[node.comfyClass]) {
|
||||
node.setSize([SPECIFIC_WIDTH, node.size[1]]);
|
||||
}
|
||||
}
|
||||
|
||||
class SeedControl {
|
||||
constructor(node, seedName) {
|
||||
this.lastSeed = -1;
|
||||
this.serializedCtx = {};
|
||||
this.node = node;
|
||||
this.seedBehavior = 'randomize'; // Default behavior
|
||||
|
||||
let controlAfterGenerateIndex;
|
||||
|
||||
for (const [i, w] of this.node.widgets.entries()) {
|
||||
if (w.name === seedName) {
|
||||
this.seedWidget = w;
|
||||
} else if (w.name === 'control_after_generate') {
|
||||
controlAfterGenerateIndex = i;
|
||||
this.node.widgets.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.seedWidget) {
|
||||
throw new Error('Something\'s wrong; expected seed widget');
|
||||
}
|
||||
|
||||
this.lastSeedButton = this.node.addWidget("button", LAST_SEED_BUTTON_LABEL, null, () => {
|
||||
const isValidValue = Number.isInteger(this.seedWidget.value) && this.seedWidget.value >= min && this.seedWidget.value <= max;
|
||||
|
||||
// Special case: if the current label is the default and seed value is -1
|
||||
if (this.lastSeedButton.name === LAST_SEED_BUTTON_LABEL && this.seedWidget.value == -1) {
|
||||
return; // Do nothing and return early
|
||||
}
|
||||
|
||||
if (isValidValue && this.seedWidget.value != -1) {
|
||||
this.lastSeed = this.seedWidget.value;
|
||||
this.seedWidget.value = -1;
|
||||
} else if (this.lastSeed !== -1) {
|
||||
this.seedWidget.value = this.lastSeed;
|
||||
} else {
|
||||
this.seedWidget.value = -1; // Set to -1 if the label didn't update due to a seed value issue
|
||||
}
|
||||
|
||||
if (isValidValue) {
|
||||
this.updateButtonLabel(); // Update the button label to reflect the change
|
||||
}
|
||||
}, { width: 50, serialize: false });
|
||||
|
||||
setNodeWidthForMappedTitles(node);
|
||||
if (controlAfterGenerateIndex !== undefined) {
|
||||
const addedWidget = this.node.widgets.pop();
|
||||
this.node.widgets.splice(controlAfterGenerateIndex, 0, addedWidget);
|
||||
setNodeWidthForMappedTitles(node);
|
||||
}
|
||||
|
||||
const max = Math.min(1125899906842624, this.seedWidget.options.max);
|
||||
const min = Math.max(-1125899906842624, this.seedWidget.options.min);
|
||||
const range = (max - min) / (this.seedWidget.options.step / 10);
|
||||
|
||||
this.seedWidget.serializeValue = async (node, index) => {
|
||||
// Check if the button is disabled
|
||||
if (this.lastSeedButton.disabled) {
|
||||
return this.seedWidget.value;
|
||||
}
|
||||
|
||||
const currentSeed = this.seedWidget.value;
|
||||
this.serializedCtx = {
|
||||
wasSpecial: currentSeed == -1,
|
||||
};
|
||||
|
||||
if (this.serializedCtx.wasSpecial) {
|
||||
switch (this.seedBehavior) {
|
||||
case 'increment':
|
||||
this.serializedCtx.seedUsed = this.lastSeed + 1;
|
||||
break;
|
||||
case 'decrement':
|
||||
this.serializedCtx.seedUsed = this.lastSeed - 1;
|
||||
break;
|
||||
default:
|
||||
this.serializedCtx.seedUsed = Math.floor(Math.random() * range) * (this.seedWidget.options.step / 10) + min;
|
||||
break;
|
||||
}
|
||||
|
||||
// Ensure the seed value is an integer and remains within the accepted range
|
||||
this.serializedCtx.seedUsed = Number.isInteger(this.serializedCtx.seedUsed) ? Math.min(Math.max(this.serializedCtx.seedUsed, min), max) : this.seedWidget.value;
|
||||
|
||||
} else {
|
||||
this.serializedCtx.seedUsed = this.seedWidget.value;
|
||||
}
|
||||
|
||||
if (node && node.widgets_values) {
|
||||
node.widgets_values[index] = this.serializedCtx.seedUsed;
|
||||
} else {
|
||||
// Update the last seed value and the button's label to show the current seed value
|
||||
this.lastSeed = this.serializedCtx.seedUsed;
|
||||
this.updateButtonLabel();
|
||||
}
|
||||
|
||||
this.seedWidget.value = this.serializedCtx.seedUsed;
|
||||
|
||||
if (this.serializedCtx.wasSpecial) {
|
||||
this.lastSeed = this.serializedCtx.seedUsed;
|
||||
this.updateButtonLabel();
|
||||
}
|
||||
|
||||
return this.serializedCtx.seedUsed;
|
||||
};
|
||||
|
||||
this.seedWidget.afterQueued = () => {
|
||||
// Check if the button is disabled
|
||||
if (this.lastSeedButton.disabled) {
|
||||
return; // Exit the function immediately
|
||||
}
|
||||
|
||||
if (this.serializedCtx.wasSpecial) {
|
||||
this.seedWidget.value = -1;
|
||||
}
|
||||
|
||||
// Check if seed has changed to a non -1 value, and if so, update lastSeed
|
||||
if (this.seedWidget.value !== -1) {
|
||||
this.lastSeed = this.seedWidget.value;
|
||||
}
|
||||
|
||||
this.updateButtonLabel();
|
||||
this.serializedCtx = {};
|
||||
};
|
||||
}
|
||||
|
||||
setBehavior(behavior) {
|
||||
this.seedBehavior = behavior;
|
||||
|
||||
// Capture the current seed value as lastSeed and then set the seed widget value to -1
|
||||
if (this.seedWidget.value != -1) {
|
||||
this.lastSeed = this.seedWidget.value;
|
||||
this.seedWidget.value = -1;
|
||||
}
|
||||
|
||||
this.updateButtonLabel();
|
||||
}
|
||||
|
||||
updateButtonLabel() {
|
||||
|
||||
switch (this.seedBehavior) {
|
||||
case 'increment':
|
||||
this.lastSeedButton.name = `➕ Increment / ♻️ ${this.lastSeed === -1 ? "Last Queued Seed" : this.lastSeed}`;
|
||||
break;
|
||||
case 'decrement':
|
||||
this.lastSeedButton.name = `➖ Decrement / ♻️ ${this.lastSeed === -1 ? "Last Queued Seed" : this.lastSeed}`;
|
||||
break;
|
||||
default:
|
||||
this.lastSeedButton.name = `🎲 Randomize / ♻️ ${this.lastSeed === -1 ? "Last Queued Seed" : this.lastSeed}`;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
function showSeedBehaviorMenu(value, options, e, menu, node) {
|
||||
const behaviorOptions = [
|
||||
{
|
||||
content: "🎲 Randomize",
|
||||
callback: () => {
|
||||
node.seedControl.setBehavior('randomize');
|
||||
}
|
||||
},
|
||||
{
|
||||
content: "➕ Increment",
|
||||
callback: () => {
|
||||
node.seedControl.setBehavior('increment');
|
||||
}
|
||||
},
|
||||
{
|
||||
content: "➖ Decrement",
|
||||
callback: () => {
|
||||
node.seedControl.setBehavior('decrement');
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
new LiteGraph.ContextMenu(behaviorOptions, {
|
||||
event: e,
|
||||
callback: null,
|
||||
parentMenu: menu,
|
||||
node: node
|
||||
});
|
||||
|
||||
return false; // This ensures the original context menu doesn't proceed
|
||||
}
|
||||
|
||||
// Extension Definition
|
||||
app.registerExtension({
|
||||
name: "efficiency.seedcontrol",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, _app) {
|
||||
if (NODE_WIDGET_MAP[nodeData.name]) {
|
||||
addMenuHandler(nodeType, function (insertOption) {
|
||||
// Check conditions before showing the seed behavior option
|
||||
let showSeedOption = true;
|
||||
|
||||
if (nodeData.name === "Noise Control Script") {
|
||||
// Check for 'add_seed_noise' widget being false
|
||||
const addSeedNoiseWidget = this.widgets.find(w => w.name === 'add_seed_noise');
|
||||
if (addSeedNoiseWidget && !addSeedNoiseWidget.value) {
|
||||
showSeedOption = false;
|
||||
}
|
||||
} else if (nodeData.name === "HighRes-Fix Script") {
|
||||
// Check for 'use_same_seed' widget being true
|
||||
const useSameSeedWidget = this.widgets.find(w => w.name === 'use_same_seed');
|
||||
if (useSameSeedWidget && useSameSeedWidget.value) {
|
||||
showSeedOption = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (showSeedOption) {
|
||||
insertOption({
|
||||
content: "🌱 Seed behavior...",
|
||||
has_submenu: true,
|
||||
callback: showSeedBehaviorMenu
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
onNodeCreated ? onNodeCreated.apply(this, []) : undefined;
|
||||
this.seedControl = new SeedControl(this, NODE_WIDGET_MAP[nodeData.name]);
|
||||
this.seedControl.seedWidget.value = -1;
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -1,596 +0,0 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
let origProps = {};
|
||||
let initialized = false;
|
||||
|
||||
const findWidgetByName = (node, name) => {
|
||||
return node.widgets ? node.widgets.find((w) => w.name === name) : null;
|
||||
};
|
||||
|
||||
const doesInputWithNameExist = (node, name) => {
|
||||
return node.inputs ? node.inputs.some((input) => input.name === name) : false;
|
||||
};
|
||||
|
||||
const HIDDEN_TAG = "tschide";
|
||||
// Toggle Widget + change size
|
||||
function toggleWidget(node, widget, show = false, suffix = "") {
|
||||
if (!widget || doesInputWithNameExist(node, widget.name)) return;
|
||||
|
||||
// Store the original properties of the widget if not already stored
|
||||
if (!origProps[widget.name]) {
|
||||
origProps[widget.name] = { origType: widget.type, origComputeSize: widget.computeSize };
|
||||
}
|
||||
|
||||
const origSize = node.size;
|
||||
|
||||
// Set the widget type and computeSize based on the show flag
|
||||
widget.type = show ? origProps[widget.name].origType : HIDDEN_TAG + suffix;
|
||||
widget.computeSize = show ? origProps[widget.name].origComputeSize : () => [0, -4];
|
||||
|
||||
// Recursively handle linked widgets if they exist
|
||||
widget.linkedWidgets?.forEach(w => toggleWidget(node, w, ":" + widget.name, show));
|
||||
|
||||
// Calculate the new height for the node based on its computeSize method
|
||||
const newHeight = node.computeSize()[1];
|
||||
node.setSize([node.size[0], newHeight]);
|
||||
}
|
||||
|
||||
const WIDGET_HEIGHT = 24;
|
||||
// Use for Multiline Widget Nodes (aka Efficient Loaders)
|
||||
function toggleWidget_2(node, widget, show = false, suffix = "") {
|
||||
if (!widget || doesInputWithNameExist(node, widget.name)) return;
|
||||
|
||||
const isCurrentlyVisible = widget.type !== HIDDEN_TAG + suffix;
|
||||
if (isCurrentlyVisible === show) return; // Early exit if widget is already in the desired state
|
||||
|
||||
if (!origProps[widget.name]) {
|
||||
origProps[widget.name] = { origType: widget.type, origComputeSize: widget.computeSize };
|
||||
}
|
||||
|
||||
widget.type = show ? origProps[widget.name].origType : HIDDEN_TAG + suffix;
|
||||
widget.computeSize = show ? origProps[widget.name].origComputeSize : () => [0, -4];
|
||||
|
||||
if (initialized){
|
||||
const adjustment = show ? WIDGET_HEIGHT : -WIDGET_HEIGHT;
|
||||
node.setSize([node.size[0], node.size[1] + adjustment]);
|
||||
}
|
||||
}
|
||||
|
||||
// New function to handle widget visibility based on input_mode
|
||||
function handleInputModeWidgetsVisibility(node, inputModeValue) {
|
||||
// Utility function to generate widget names up to a certain count
|
||||
function generateWidgetNames(baseName, count) {
|
||||
return Array.from({ length: count }, (_, i) => `${baseName}_${i + 1}`);
|
||||
}
|
||||
|
||||
// Common widget groups
|
||||
const batchWidgets = ["batch_path", "subdirectories", "batch_sort", "batch_max"];
|
||||
const xbatchWidgets = ["X_batch_path", "X_subdirectories", "X_batch_sort", "X_batch_max"];
|
||||
const ckptWidgets = [...generateWidgetNames("ckpt_name", 50)];
|
||||
const clipSkipWidgets = [...generateWidgetNames("clip_skip", 50)];
|
||||
const vaeNameWidgets = [...generateWidgetNames("vae_name", 50)];
|
||||
const loraNameWidgets = [...generateWidgetNames("lora_name", 50)];
|
||||
const loraWtWidgets = [...generateWidgetNames("lora_wt", 50)];
|
||||
const modelStrWidgets = [...generateWidgetNames("model_str", 50)];
|
||||
const clipStrWidgets = [...generateWidgetNames("clip_str", 50)];
|
||||
const xWidgets = ["X_batch_count", "X_first_value", "X_last_value"]
|
||||
const yWidgets = ["Y_batch_count", "Y_first_value", "Y_last_value"]
|
||||
|
||||
const nodeVisibilityMap = {
|
||||
"LoRA Stacker": {
|
||||
"simple": [...modelStrWidgets, ...clipStrWidgets],
|
||||
"advanced": [...loraWtWidgets]
|
||||
},
|
||||
"XY Input: Steps": {
|
||||
"steps": ["first_start_step", "last_start_step", "first_end_step", "last_end_step", "first_refine_step", "last_refine_step"],
|
||||
"start_at_step": ["first_step", "last_step", "first_end_step", "last_end_step", "first_refine_step", "last_refine_step"],
|
||||
"end_at_step": ["first_step", "last_step", "first_start_step", "last_start_step", "first_refine_step", "last_refine_step"],
|
||||
"refine_at_step": ["first_step", "last_step", "first_start_step", "last_start_step", "first_end_step", "last_end_step"]
|
||||
},
|
||||
"XY Input: VAE": {
|
||||
"VAE Names": [...batchWidgets],
|
||||
"VAE Batch": [...vaeNameWidgets, "vae_count"]
|
||||
},
|
||||
"XY Input: Checkpoint": {
|
||||
"Ckpt Names": [...clipSkipWidgets, ...vaeNameWidgets, ...batchWidgets],
|
||||
"Ckpt Names+ClipSkip": [...vaeNameWidgets, ...batchWidgets],
|
||||
"Ckpt Names+ClipSkip+VAE": [...batchWidgets],
|
||||
"Checkpoint Batch": [...ckptWidgets, ...clipSkipWidgets, ...vaeNameWidgets, "ckpt_count"]
|
||||
},
|
||||
"XY Input: LoRA": {
|
||||
"LoRA Names": [...modelStrWidgets, ...clipStrWidgets, ...batchWidgets],
|
||||
"LoRA Names+Weights": [...batchWidgets, "model_strength", "clip_strength"],
|
||||
"LoRA Batch": [...loraNameWidgets, ...modelStrWidgets, ...clipStrWidgets, "lora_count"]
|
||||
},
|
||||
"XY Input: LoRA Plot": {
|
||||
"X: LoRA Batch, Y: LoRA Weight": ["lora_name", "model_strength", "clip_strength", "X_first_value", "X_last_value"],
|
||||
"X: LoRA Batch, Y: Model Strength": ["lora_name", "model_strength", "model_strength", "X_first_value", "X_last_value"],
|
||||
"X: LoRA Batch, Y: Clip Strength": ["lora_name", "clip_strength", "X_first_value", "X_last_value"],
|
||||
"X: Model Strength, Y: Clip Strength": [...xbatchWidgets, "model_strength", "clip_strength"],
|
||||
},
|
||||
"XY Input: Control Net": {
|
||||
"strength": ["first_start_percent", "last_start_percent", "first_end_percent", "last_end_percent", "strength"],
|
||||
"start_percent": ["first_strength", "last_strength", "first_end_percent", "last_end_percent", "start_percent"],
|
||||
"end_percent": ["first_strength", "last_strength", "first_start_percent", "last_start_percent", "end_percent"]
|
||||
},
|
||||
"XY Input: Control Net Plot": {
|
||||
"X: Strength, Y: Start%": ["strength", "start_percent"],
|
||||
"X: Strength, Y: End%": ["strength","end_percent"],
|
||||
"X: Start%, Y: Strength": ["start_percent", "strength"],
|
||||
"X: Start%, Y: End%": ["start_percent", "end_percent"],
|
||||
"X: End%, Y: Strength": ["end_percent", "strength"],
|
||||
"X: End%, Y: Start%": ["end_percent", "start_percent"],
|
||||
}
|
||||
};
|
||||
|
||||
const inputModeVisibilityMap = nodeVisibilityMap[node.comfyClass];
|
||||
|
||||
if (!inputModeVisibilityMap || !inputModeVisibilityMap[inputModeValue]) return;
|
||||
|
||||
// Reset all widgets to visible
|
||||
for (const key in inputModeVisibilityMap) {
|
||||
for (const widgetName of inputModeVisibilityMap[key]) {
|
||||
const widget = findWidgetByName(node, widgetName);
|
||||
toggleWidget(node, widget, true);
|
||||
}
|
||||
}
|
||||
|
||||
// Hide the specific widgets for the current input_mode value
|
||||
for (const widgetName of inputModeVisibilityMap[inputModeValue]) {
|
||||
const widget = findWidgetByName(node, widgetName);
|
||||
toggleWidget(node, widget, false);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle multi-widget visibilities
|
||||
function handleVisibility(node, countValue, node_type) {
|
||||
const inputModeValue = findWidgetByName(node, "input_mode").value;
|
||||
const baseNamesMap = {
|
||||
"LoRA": ["lora_name", "model_str", "clip_str"],
|
||||
"Checkpoint": ["ckpt_name", "clip_skip", "vae_name"],
|
||||
"LoRA Stacker": ["lora_name", "model_str", "clip_str", "lora_wt"]
|
||||
};
|
||||
|
||||
const baseNames = baseNamesMap[node_type];
|
||||
|
||||
const isBatchMode = inputModeValue.includes("Batch");
|
||||
if (isBatchMode) {countValue = 0;}
|
||||
|
||||
for (let i = 1; i <= 50; i++) {
|
||||
const nameWidget = findWidgetByName(node, `${baseNames[0]}_${i}`);
|
||||
const firstWidget = findWidgetByName(node, `${baseNames[1]}_${i}`);
|
||||
const secondWidget = findWidgetByName(node, `${baseNames[2]}_${i}`);
|
||||
const thirdWidget = node_type === "LoRA Stacker" ? findWidgetByName(node, `${baseNames[3]}_${i}`) : null;
|
||||
|
||||
if (i <= countValue) {
|
||||
toggleWidget(node, nameWidget, true);
|
||||
|
||||
if (node_type === "LoRA Stacker") {
|
||||
if (inputModeValue === "simple") {
|
||||
toggleWidget(node, firstWidget, false); // model_str
|
||||
toggleWidget(node, secondWidget, false); // clip_str
|
||||
toggleWidget(node, thirdWidget, true); // lora_wt
|
||||
} else if (inputModeValue === "advanced") {
|
||||
toggleWidget(node, firstWidget, true); // model_str
|
||||
toggleWidget(node, secondWidget, true); // clip_str
|
||||
toggleWidget(node, thirdWidget, false); // lora_wt
|
||||
}
|
||||
} else if (node_type === "Checkpoint") {
|
||||
if (inputModeValue.includes("ClipSkip")){toggleWidget(node, firstWidget, true);}
|
||||
if (inputModeValue.includes("VAE")){toggleWidget(node, secondWidget, true);}
|
||||
} else if (node_type === "LoRA") {
|
||||
if (inputModeValue.includes("Weights")){
|
||||
toggleWidget(node, firstWidget, true);
|
||||
toggleWidget(node, secondWidget, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
toggleWidget(node, nameWidget, false);
|
||||
toggleWidget(node, firstWidget, false);
|
||||
toggleWidget(node, secondWidget, false);
|
||||
if (thirdWidget) {toggleWidget(node, thirdWidget, false);}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sampler & Scheduler XY input visibility logic
|
||||
function handleSamplerSchedulerVisibility(node, countValue, targetParameter) {
|
||||
for (let i = 1; i <= 50; i++) {
|
||||
const samplerWidget = findWidgetByName(node, `sampler_${i}`);
|
||||
const schedulerWidget = findWidgetByName(node, `scheduler_${i}`);
|
||||
|
||||
if (i <= countValue) {
|
||||
if (targetParameter === "sampler") {
|
||||
toggleWidget(node, samplerWidget, true);
|
||||
toggleWidget(node, schedulerWidget, false);
|
||||
} else if (targetParameter === "scheduler") {
|
||||
toggleWidget(node, samplerWidget, false);
|
||||
toggleWidget(node, schedulerWidget, true);
|
||||
} else { // targetParameter is "sampler & scheduler"
|
||||
toggleWidget(node, samplerWidget, true);
|
||||
toggleWidget(node, schedulerWidget, true);
|
||||
}
|
||||
} else {
|
||||
toggleWidget(node, samplerWidget, false);
|
||||
toggleWidget(node, schedulerWidget, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Handle simple widget visibility based on a count
|
||||
function handleWidgetVisibility(node, thresholdValue, widgetNamePrefix, maxCount) {
|
||||
for (let i = 1; i <= maxCount; i++) {
|
||||
const widget = findWidgetByName(node, `${widgetNamePrefix}${i}`);
|
||||
if (widget) {
|
||||
toggleWidget(node, widget, i <= thresholdValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Disable the 'Ckpt Name+ClipSkip+VAE' option if 'target_ckpt' is "Refiner"
|
||||
let last_ckpt_input_mode;
|
||||
let last_target_ckpt;
|
||||
function xyCkptRefinerOptionsRemove(widget, node) {
|
||||
|
||||
let target_ckpt = findWidgetByName(node, "target_ckpt").value
|
||||
let input_mode = widget.value
|
||||
|
||||
if ((input_mode === "Ckpt Names+ClipSkip+VAE") && (target_ckpt === "Refiner")) {
|
||||
if (last_ckpt_input_mode === "Ckpt Names+ClipSkip") {
|
||||
if (last_target_ckpt === "Refiner"){
|
||||
widget.value = "Checkpoint Batch";
|
||||
} else {widget.value = "Ckpt Names+ClipSkip";}
|
||||
} else if (last_ckpt_input_mode === "Checkpoint Batch") {
|
||||
if (last_target_ckpt === "Refiner"){
|
||||
widget.value = "Ckpt Names+ClipSkip";
|
||||
} else {widget.value = "Checkpoint Batch";}
|
||||
} else if (last_ckpt_input_mode !== 'undefined') {
|
||||
widget.value = last_ckpt_input_mode;
|
||||
} else {
|
||||
widget.value = "Ckpt Names";
|
||||
}
|
||||
} else if (input_mode !== "Ckpt Names+ClipSkip+VAE"){
|
||||
last_ckpt_input_mode = input_mode;
|
||||
}
|
||||
last_target_ckpt = target_ckpt
|
||||
}
|
||||
|
||||
// Create a map of node titles to their respective widget handlers
|
||||
const nodeWidgetHandlers = {
|
||||
"Efficient Loader": {
|
||||
'lora_name': handleEfficientLoaderLoraName
|
||||
},
|
||||
"Eff. Loader SDXL": {
|
||||
'refiner_ckpt_name': handleEffLoaderSDXLRefinerCkptName
|
||||
},
|
||||
"LoRA Stacker": {
|
||||
'input_mode': handleLoRAStackerInputMode,
|
||||
'lora_count': handleLoRAStackerLoraCount
|
||||
},
|
||||
"XY Input: Steps": {
|
||||
'target_parameter': handleXYInputStepsTargetParameter
|
||||
},
|
||||
"XY Input: Sampler/Scheduler": {
|
||||
'target_parameter': handleXYInputSamplerSchedulerTargetParameter,
|
||||
'input_count': handleXYInputSamplerSchedulerInputCount
|
||||
},
|
||||
"XY Input: VAE": {
|
||||
'input_mode': handleXYInputVAEInputMode,
|
||||
'vae_count': handleXYInputVAEVaeCount
|
||||
},
|
||||
"XY Input: Prompt S/R": {
|
||||
'replace_count': handleXYInputPromptSRReplaceCount
|
||||
},
|
||||
"XY Input: Checkpoint": {
|
||||
'input_mode': handleXYInputCheckpointInputMode,
|
||||
'ckpt_count': handleXYInputCheckpointCkptCount,
|
||||
'target_ckpt': handleXYInputCheckpointTargetCkpt
|
||||
},
|
||||
"XY Input: LoRA": {
|
||||
'input_mode': handleXYInputLoRAInputMode,
|
||||
'lora_count': handleXYInputLoRALoraCount
|
||||
},
|
||||
"XY Input: LoRA Plot": {
|
||||
'input_mode': handleXYInputLoRAPlotInputMode
|
||||
},
|
||||
"XY Input: LoRA Stacks": {
|
||||
'node_state': handleXYInputLoRAStacksNodeState
|
||||
},
|
||||
"XY Input: Control Net": {
|
||||
'target_parameter': handleXYInputControlNetTargetParameter
|
||||
},
|
||||
"XY Input: Control Net Plot": {
|
||||
'plot_type': handleXYInputControlNetPlotPlotType
|
||||
},
|
||||
"Noise Control Script": {
|
||||
'add_seed_noise': handleNoiseControlScript
|
||||
},
|
||||
"HighRes-Fix Script": {
|
||||
'upscale_type': handleHiResFixScript,
|
||||
'use_same_seed': handleHiResFixScript,
|
||||
'use_controlnet':handleHiResFixScript
|
||||
},
|
||||
"Tiled Upscaler Script": {
|
||||
'use_controlnet':handleTiledUpscalerScript
|
||||
},
|
||||
};
|
||||
|
||||
// In the main function where widgetLogic is called
|
||||
function widgetLogic(node, widget) {
|
||||
// Retrieve the handler for the current node title and widget name
|
||||
const handler = nodeWidgetHandlers[node.comfyClass]?.[widget.name];
|
||||
if (handler) {
|
||||
handler(node, widget);
|
||||
}
|
||||
}
|
||||
|
||||
// Efficient Loader Handlers
|
||||
function handleEfficientLoaderLoraName(node, widget) {
|
||||
if (widget.value === 'None') {
|
||||
toggleWidget_2(node, findWidgetByName(node, 'lora_model_strength'));
|
||||
toggleWidget_2(node, findWidgetByName(node, 'lora_clip_strength'));
|
||||
} else {
|
||||
toggleWidget_2(node, findWidgetByName(node, 'lora_model_strength'), true);
|
||||
toggleWidget_2(node, findWidgetByName(node, 'lora_clip_strength'), true);
|
||||
}
|
||||
}
|
||||
|
||||
// Eff. Loader SDXL Handlers
|
||||
function handleEffLoaderSDXLRefinerCkptName(node, widget) {
|
||||
if (widget.value === 'None') {
|
||||
toggleWidget_2(node, findWidgetByName(node, 'refiner_clip_skip'));
|
||||
toggleWidget_2(node, findWidgetByName(node, 'positive_ascore'));
|
||||
toggleWidget_2(node, findWidgetByName(node, 'negative_ascore'));
|
||||
} else {
|
||||
toggleWidget_2(node, findWidgetByName(node, 'refiner_clip_skip'), true);
|
||||
toggleWidget_2(node, findWidgetByName(node, 'positive_ascore'), true);
|
||||
toggleWidget_2(node, findWidgetByName(node, 'negative_ascore'), true);
|
||||
}
|
||||
}
|
||||
|
||||
// Noise Control Script Seed Handler
|
||||
function handleNoiseControlScript(node, widget) {
|
||||
|
||||
function ensureSeedControlExists(callback) {
|
||||
if (node.seedControl && node.seedControl.lastSeedButton) {
|
||||
callback();
|
||||
} else {
|
||||
setTimeout(() => ensureSeedControlExists(callback), 0);
|
||||
}
|
||||
}
|
||||
|
||||
ensureSeedControlExists(() => {
|
||||
if (widget.value === false) {
|
||||
toggleWidget(node, findWidgetByName(node, 'seed'));
|
||||
toggleWidget(node, findWidgetByName(node, 'weight'));
|
||||
toggleWidget(node, node.seedControl.lastSeedButton);
|
||||
node.seedControl.lastSeedButton.disabled = true; // Disable the button
|
||||
} else {
|
||||
toggleWidget(node, findWidgetByName(node, 'seed'), true);
|
||||
toggleWidget(node, findWidgetByName(node, 'weight'), true);
|
||||
node.seedControl.lastSeedButton.disabled = false; // Enable the button
|
||||
toggleWidget(node, node.seedControl.lastSeedButton, true);
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
/// HighRes-Fix Script Handlers
|
||||
function handleHiResFixScript(node, widget) {
|
||||
|
||||
function ensureSeedControlExists(callback) {
|
||||
if (node.seedControl && node.seedControl.lastSeedButton) {
|
||||
callback();
|
||||
} else {
|
||||
setTimeout(() => ensureSeedControlExists(callback), 0);
|
||||
}
|
||||
}
|
||||
|
||||
if (findWidgetByName(node, 'upscale_type').value === "latent") {
|
||||
toggleWidget(node, findWidgetByName(node, 'pixel_upscaler'));
|
||||
|
||||
toggleWidget(node, findWidgetByName(node, 'hires_ckpt_name'), true);
|
||||
toggleWidget(node, findWidgetByName(node, 'latent_upscaler'), true);
|
||||
toggleWidget(node, findWidgetByName(node, 'use_same_seed'), true);
|
||||
toggleWidget(node, findWidgetByName(node, 'hires_steps'), true);
|
||||
toggleWidget(node, findWidgetByName(node, 'denoise'), true);
|
||||
toggleWidget(node, findWidgetByName(node, 'iterations'), true);
|
||||
|
||||
ensureSeedControlExists(() => {
|
||||
if (findWidgetByName(node, 'use_same_seed').value == true) {
|
||||
toggleWidget(node, findWidgetByName(node, 'seed'));
|
||||
toggleWidget(node, node.seedControl.lastSeedButton);
|
||||
node.seedControl.lastSeedButton.disabled = true; // Disable the button
|
||||
} else {
|
||||
toggleWidget(node, findWidgetByName(node, 'seed'), true);
|
||||
node.seedControl.lastSeedButton.disabled = false; // Enable the button
|
||||
toggleWidget(node, node.seedControl.lastSeedButton, true);
|
||||
}
|
||||
});
|
||||
|
||||
if (findWidgetByName(node, 'use_controlnet').value == '_'){
|
||||
toggleWidget(node, findWidgetByName(node, 'use_controlnet'));
|
||||
toggleWidget(node, findWidgetByName(node, 'control_net_name'));
|
||||
toggleWidget(node, findWidgetByName(node, 'strength'));
|
||||
toggleWidget(node, findWidgetByName(node, 'preprocessor'));
|
||||
toggleWidget(node, findWidgetByName(node, 'preprocessor_imgs'));
|
||||
}
|
||||
else{
|
||||
toggleWidget(node, findWidgetByName(node, 'use_controlnet'), true);
|
||||
|
||||
if (findWidgetByName(node, 'use_controlnet').value == true){
|
||||
toggleWidget(node, findWidgetByName(node, 'control_net_name'), true);
|
||||
toggleWidget(node, findWidgetByName(node, 'strength'), true);
|
||||
toggleWidget(node, findWidgetByName(node, 'preprocessor'), true);
|
||||
toggleWidget(node, findWidgetByName(node, 'preprocessor_imgs'), true);
|
||||
}
|
||||
else{
|
||||
toggleWidget(node, findWidgetByName(node, 'control_net_name'));
|
||||
toggleWidget(node, findWidgetByName(node, 'strength'));
|
||||
toggleWidget(node, findWidgetByName(node, 'preprocessor'));
|
||||
toggleWidget(node, findWidgetByName(node, 'preprocessor_imgs'));
|
||||
}
|
||||
}
|
||||
|
||||
} else if (findWidgetByName(node, 'upscale_type').value === "pixel") {
|
||||
toggleWidget(node, findWidgetByName(node, 'hires_ckpt_name'));
|
||||
toggleWidget(node, findWidgetByName(node, 'latent_upscaler'));
|
||||
toggleWidget(node, findWidgetByName(node, 'use_same_seed'));
|
||||
toggleWidget(node, findWidgetByName(node, 'hires_steps'));
|
||||
toggleWidget(node, findWidgetByName(node, 'denoise'));
|
||||
toggleWidget(node, findWidgetByName(node, 'iterations'));
|
||||
toggleWidget(node, findWidgetByName(node, 'seed'));
|
||||
ensureSeedControlExists(() => {
|
||||
toggleWidget(node, node.seedControl.lastSeedButton);
|
||||
node.seedControl.lastSeedButton.disabled = true; // Disable the button
|
||||
});
|
||||
toggleWidget(node, findWidgetByName(node, 'use_controlnet'));
|
||||
toggleWidget(node, findWidgetByName(node, 'control_net_name'));
|
||||
toggleWidget(node, findWidgetByName(node, 'strength'));
|
||||
toggleWidget(node, findWidgetByName(node, 'preprocessor'));
|
||||
toggleWidget(node, findWidgetByName(node, 'preprocessor_imgs'));
|
||||
|
||||
toggleWidget(node, findWidgetByName(node, 'pixel_upscaler'), true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Tiled Upscaler Script Handler
|
||||
function handleTiledUpscalerScript(node, widget) {
|
||||
if (findWidgetByName(node, 'use_controlnet').value == true){
|
||||
toggleWidget(node, findWidgetByName(node, 'tile_controlnet'), true);
|
||||
toggleWidget(node, findWidgetByName(node, 'strength'), true);
|
||||
}
|
||||
else{
|
||||
toggleWidget(node, findWidgetByName(node, 'tile_controlnet'));
|
||||
toggleWidget(node, findWidgetByName(node, 'strength'));
|
||||
}
|
||||
}
|
||||
|
||||
// LoRA Stacker Handlers
|
||||
function handleLoRAStackerInputMode(node, widget) {
|
||||
handleInputModeWidgetsVisibility(node, widget.value);
|
||||
handleVisibility(node, findWidgetByName(node, "lora_count").value, "LoRA Stacker");
|
||||
}
|
||||
|
||||
function handleLoRAStackerLoraCount(node, widget) {
|
||||
handleVisibility(node, widget.value, "LoRA Stacker");
|
||||
}
|
||||
|
||||
// XY Input: Steps Handlers
|
||||
function handleXYInputStepsTargetParameter(node, widget) {
|
||||
handleInputModeWidgetsVisibility(node, widget.value);
|
||||
}
|
||||
|
||||
// XY Input: Sampler/Scheduler Handlers
|
||||
function handleXYInputSamplerSchedulerTargetParameter(node, widget) {
|
||||
handleSamplerSchedulerVisibility(node, findWidgetByName(node, 'input_count').value, widget.value);
|
||||
}
|
||||
|
||||
function handleXYInputSamplerSchedulerInputCount(node, widget) {
|
||||
handleSamplerSchedulerVisibility(node, widget.value, findWidgetByName(node, 'target_parameter').value);
|
||||
}
|
||||
|
||||
// XY Input: VAE Handlers
|
||||
function handleXYInputVAEInputMode(node, widget) {
|
||||
handleInputModeWidgetsVisibility(node, widget.value);
|
||||
if (widget.value === "VAE Names") {
|
||||
handleWidgetVisibility(node, findWidgetByName(node, "vae_count").value, "vae_name_", 50);
|
||||
} else {
|
||||
handleWidgetVisibility(node, 0, "vae_name_", 50);
|
||||
}
|
||||
}
|
||||
|
||||
function handleXYInputVAEVaeCount(node, widget) {
|
||||
if (findWidgetByName(node, "input_mode").value === "VAE Names") {
|
||||
handleWidgetVisibility(node, widget.value, "vae_name_", 50);
|
||||
}
|
||||
}
|
||||
|
||||
// XY Input: Prompt S/R Handlers
|
||||
function handleXYInputPromptSRReplaceCount(node, widget) {
|
||||
handleWidgetVisibility(node, widget.value, "replace_", 49);
|
||||
}
|
||||
|
||||
// XY Input: Checkpoint Handlers
|
||||
function handleXYInputCheckpointInputMode(node, widget) {
|
||||
xyCkptRefinerOptionsRemove(widget, node);
|
||||
handleInputModeWidgetsVisibility(node, widget.value);
|
||||
handleVisibility(node, findWidgetByName(node, "ckpt_count").value, "Checkpoint");
|
||||
}
|
||||
|
||||
function handleXYInputCheckpointCkptCount(node, widget) {
|
||||
handleVisibility(node, widget.value, "Checkpoint");
|
||||
}
|
||||
|
||||
function handleXYInputCheckpointTargetCkpt(node, widget) {
|
||||
xyCkptRefinerOptionsRemove(findWidgetByName(node, "input_mode"), node);
|
||||
}
|
||||
|
||||
// XY Input: LoRA Handlers
|
||||
function handleXYInputLoRAInputMode(node, widget) {
|
||||
handleInputModeWidgetsVisibility(node, widget.value);
|
||||
handleVisibility(node, findWidgetByName(node, "lora_count").value, "LoRA");
|
||||
}
|
||||
|
||||
function handleXYInputLoRALoraCount(node, widget) {
|
||||
handleVisibility(node, widget.value, "LoRA");
|
||||
}
|
||||
|
||||
// XY Input: LoRA Plot Handlers
|
||||
function handleXYInputLoRAPlotInputMode(node, widget) {
|
||||
handleInputModeWidgetsVisibility(node, widget.value);
|
||||
}
|
||||
|
||||
// XY Input: LoRA Stacks Handlers
|
||||
function handleXYInputLoRAStacksNodeState(node, widget) {
|
||||
toggleWidget(node, findWidgetByName(node, "node_state"), false);
|
||||
}
|
||||
|
||||
// XY Input: Control Net Handlers
|
||||
function handleXYInputControlNetTargetParameter(node, widget) {
|
||||
handleInputModeWidgetsVisibility(node, widget.value);
|
||||
}
|
||||
|
||||
// XY Input: Control Net Plot Handlers
|
||||
function handleXYInputControlNetPlotPlotType(node, widget) {
|
||||
handleInputModeWidgetsVisibility(node, widget.value);
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "efficiency.widgethider",
|
||||
nodeCreated(node) {
|
||||
for (const w of node.widgets || []) {
|
||||
let widgetValue = w.value;
|
||||
|
||||
// Store the original descriptor if it exists
|
||||
let originalDescriptor = Object.getOwnPropertyDescriptor(w, 'value');
|
||||
|
||||
widgetLogic(node, w);
|
||||
|
||||
Object.defineProperty(w, 'value', {
|
||||
get() {
|
||||
// If there's an original getter, use it. Otherwise, return widgetValue.
|
||||
let valueToReturn = originalDescriptor && originalDescriptor.get
|
||||
? originalDescriptor.get.call(w)
|
||||
: widgetValue;
|
||||
|
||||
return valueToReturn;
|
||||
},
|
||||
set(newVal) {
|
||||
|
||||
// If there's an original setter, use it. Otherwise, set widgetValue.
|
||||
if (originalDescriptor && originalDescriptor.set) {
|
||||
originalDescriptor.set.call(w, newVal);
|
||||
} else {
|
||||
widgetValue = newVal;
|
||||
}
|
||||
|
||||
widgetLogic(node, w);
|
||||
}
|
||||
});
|
||||
}
|
||||
setTimeout(() => {initialized = true;}, 500);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
// Detect and update Efficiency Nodes from v1.92 to v2.00 changes (Final update?)
|
||||
import { app } from '../../scripts/app.js'
|
||||
import { addNode } from "./node_options/common/utils.js";
|
||||
|
||||
const ext = {
|
||||
name: "efficiency.WorkflowFix",
|
||||
};
|
||||
|
||||
function reloadHiResFixNode(originalNode) {
|
||||
|
||||
// Safeguard against missing 'pos' property
|
||||
const position = originalNode.pos && originalNode.pos.length === 2 ? { x: originalNode.pos[0], y: originalNode.pos[1] } : { x: 0, y: 0 };
|
||||
|
||||
// Recreate the node
|
||||
const newNode = addNode("HighRes-Fix Script", originalNode, position);
|
||||
|
||||
// Transfer input connections from old node to new node
|
||||
originalNode.inputs.forEach((input, index) => {
|
||||
if (input && input.link !== null) {
|
||||
const originLinkInfo = originalNode.graph.links[input.link];
|
||||
if (originLinkInfo) {
|
||||
const originNode = originalNode.graph.getNodeById(originLinkInfo.origin_id);
|
||||
if (originNode) {
|
||||
originNode.connect(originLinkInfo.origin_slot, newNode, index);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Transfer output connections from old node to new node
|
||||
originalNode.outputs.forEach((output, index) => {
|
||||
if (output && output.links) {
|
||||
output.links.forEach(link => {
|
||||
const targetLinkInfo = originalNode.graph.links[link];
|
||||
if (targetLinkInfo) {
|
||||
const targetNode = originalNode.graph.getNodeById(targetLinkInfo.target_id);
|
||||
if (targetNode) {
|
||||
newNode.connect(index, targetNode, targetLinkInfo.target_slot);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// Remove the original node after all connections are transferred
|
||||
originalNode.graph.remove(originalNode);
|
||||
|
||||
return newNode;
|
||||
}
|
||||
|
||||
ext.loadedGraphNode = function(node, app) {
|
||||
const originalNode = node; // This line ensures that originalNode refers to the provided node
|
||||
const kSamplerTypes = [
|
||||
"KSampler (Efficient)",
|
||||
"KSampler Adv. (Efficient)",
|
||||
"KSampler SDXL (Eff.)"
|
||||
];
|
||||
|
||||
// EFFICIENT LOADER & EFF. LOADER SDXL
|
||||
/* Changes:
|
||||
Added "token_normalization" & "weight_interpretation" widget below prompt text boxes,
|
||||
below code fixes the widget values for empty_latent_width, empty_latent_height, and batch_size
|
||||
by shifting down by 2 widget values starting from the "token_normalization" widget.
|
||||
Logic triggers when "token_normalization" is a number instead of a string.
|
||||
*/
|
||||
if (node.comfyClass === "Efficient Loader" || node.comfyClass === "Eff. Loader SDXL") {
|
||||
const tokenWidget = node.widgets.find(w => w.name === "token_normalization");
|
||||
const weightWidget = node.widgets.find(w => w.name === "weight_interpretation");
|
||||
|
||||
if (typeof tokenWidget.value === 'number') {
|
||||
console.log("[EfficiencyUpdate]", `Fixing '${node.comfyClass}' token and weight widgets:`, node);
|
||||
const index = node.widgets.indexOf(tokenWidget);
|
||||
if (index !== -1) {
|
||||
for (let i = node.widgets.length - 1; i > index + 1; i--) {
|
||||
node.widgets[i].value = node.widgets[i - 2].value;
|
||||
}
|
||||
}
|
||||
tokenWidget.value = "none";
|
||||
weightWidget.value = "comfy";
|
||||
}
|
||||
}
|
||||
|
||||
// KSAMPLER (EFFICIENT), KSAMPLER ADV. (EFFICIENT), & KSAMPLER SDXL (EFF.)
|
||||
/* Changes:
|
||||
Removed the "sampler_state" widget which cause all widget values to shift down by a factor of 1.
|
||||
Fix involves moving all widget values by -1. "vae_decode" value is lost in this process, so in
|
||||
below fix I manually set it to its default value of "true".
|
||||
*/
|
||||
else if (kSamplerTypes.includes(node.comfyClass)) {
|
||||
|
||||
const seedWidgetName = (node.comfyClass === "KSampler (Efficient)") ? "seed" : "noise_seed";
|
||||
const stepsWidgetName = (node.comfyClass === "KSampler (Efficient)") ? "steps" : "start_at_step";
|
||||
|
||||
const seedWidget = node.widgets.find(w => w.name === seedWidgetName);
|
||||
const stepsWidget = node.widgets.find(w => w.name === stepsWidgetName);
|
||||
|
||||
if (isNaN(seedWidget.value) && isNaN(stepsWidget.value)) {
|
||||
console.log("[EfficiencyUpdate]", `Fixing '${node.comfyClass}' node widgets:`, node);
|
||||
for (let i = 0; i < node.widgets.length - 1; i++) {
|
||||
node.widgets[i].value = node.widgets[i + 1].value;
|
||||
}
|
||||
node.widgets[node.widgets.length - 1].value = "true";
|
||||
}
|
||||
}
|
||||
|
||||
// HIGHRES-FIX SCRIPT
|
||||
/* Changes:
|
||||
Many new changes where added, so in order to properly update, aquired the values of the original
|
||||
widgets, reload a new node, transffer the known original values, and transffer connection.
|
||||
This fix is triggered when the upscale_type widget is neither "latent" or "pixel".
|
||||
*/
|
||||
// Check if the current node is "HighRes-Fix Script" and if any of the above fixes were applied
|
||||
else if (node.comfyClass === "HighRes-Fix Script") {
|
||||
const upscaleTypeWidget = node.widgets.find(w => w.name === "upscale_type");
|
||||
|
||||
if (upscaleTypeWidget && upscaleTypeWidget.value !== "latent" && upscaleTypeWidget.value !== "pixel") {
|
||||
console.log("[EfficiencyUpdate]", "Reloading 'HighRes-Fix Script' node:", node);
|
||||
|
||||
// Reload the node and get the new node instance
|
||||
const newNode = reloadHiResFixNode(node);
|
||||
|
||||
// Update the widgets of the new node
|
||||
const targetWidgetNames = ["latent_upscaler", "upscale_by", "hires_steps", "denoise", "iterations"];
|
||||
|
||||
// Extract the first five values of the original node
|
||||
const originalValues = originalNode.widgets.slice(0, 5).map(w => w.value);
|
||||
|
||||
targetWidgetNames.forEach((name, index) => {
|
||||
const widget = newNode.widgets.find(w => w.name === name);
|
||||
if (widget && originalValues[index] !== undefined) {
|
||||
if (name === "latent_upscaler" && typeof originalValues[index] === 'string') {
|
||||
widget.value = originalValues[index].replace("SD-Latent-Upscaler", "city96");
|
||||
} else {
|
||||
widget.value = originalValues[index];
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
app.registerExtension(ext);
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
{
|
||||
"Efficient Loader": {
|
||||
"model_cache": {
|
||||
"vae": 1,
|
||||
"ckpt": 1,
|
||||
"lora": 1,
|
||||
"refn": 1
|
||||
}
|
||||
},
|
||||
"XY Plot": {
|
||||
"model_cache": {
|
||||
"vae": 5,
|
||||
"ckpt": 5,
|
||||
"lora": 5,
|
||||
"refn": 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
#
|
||||
@@ -1,341 +0,0 @@
|
||||
import torch
|
||||
import numpy as np
|
||||
import itertools
|
||||
from math import gcd
|
||||
|
||||
from comfy import model_management
|
||||
from comfy.sdxl_clip import SDXLClipModel, SDXLRefinerClipModel, SDXLClipG
|
||||
|
||||
def _grouper(n, iterable):
|
||||
it = iter(iterable)
|
||||
while True:
|
||||
chunk = list(itertools.islice(it, n))
|
||||
if not chunk:
|
||||
return
|
||||
yield chunk
|
||||
|
||||
def _norm_mag(w, n):
|
||||
d = w - 1
|
||||
return 1 + np.sign(d) * np.sqrt(np.abs(d)**2 / n)
|
||||
#return np.sign(w) * np.sqrt(np.abs(w)**2 / n)
|
||||
|
||||
def divide_length(word_ids, weights):
|
||||
sums = dict(zip(*np.unique(word_ids, return_counts=True)))
|
||||
sums[0] = 1
|
||||
weights = [[_norm_mag(w, sums[id]) if id != 0 else 1.0
|
||||
for w, id in zip(x, y)] for x, y in zip(weights, word_ids)]
|
||||
return weights
|
||||
|
||||
def shift_mean_weight(word_ids, weights):
|
||||
delta = 1 - np.mean([w for x, y in zip(weights, word_ids) for w, id in zip(x,y) if id != 0])
|
||||
weights = [[w if id == 0 else w+delta
|
||||
for w, id in zip(x, y)] for x, y in zip(weights, word_ids)]
|
||||
return weights
|
||||
|
||||
def scale_to_norm(weights, word_ids, w_max):
|
||||
top = np.max(weights)
|
||||
w_max = min(top, w_max)
|
||||
weights = [[w_max if id == 0 else (w/top) * w_max
|
||||
for w, id in zip(x, y)] for x, y in zip(weights, word_ids)]
|
||||
return weights
|
||||
|
||||
def from_zero(weights, base_emb):
|
||||
weight_tensor = torch.tensor(weights, dtype=base_emb.dtype, device=base_emb.device)
|
||||
weight_tensor = weight_tensor.reshape(1,-1,1).expand(base_emb.shape)
|
||||
return base_emb * weight_tensor
|
||||
|
||||
def mask_word_id(tokens, word_ids, target_id, mask_token):
|
||||
new_tokens = [[mask_token if wid == target_id else t
|
||||
for t, wid in zip(x,y)] for x,y in zip(tokens, word_ids)]
|
||||
mask = np.array(word_ids) == target_id
|
||||
return (new_tokens, mask)
|
||||
|
||||
def batched_clip_encode(tokens, length, encode_func, num_chunks):
|
||||
embs = []
|
||||
for e in _grouper(32, tokens):
|
||||
enc, pooled = encode_func(e)
|
||||
enc = enc.reshape((len(e), length, -1))
|
||||
embs.append(enc)
|
||||
embs = torch.cat(embs)
|
||||
embs = embs.reshape((len(tokens) // num_chunks, length * num_chunks, -1))
|
||||
return embs
|
||||
|
||||
def from_masked(tokens, weights, word_ids, base_emb, length, encode_func, m_token=266):
|
||||
pooled_base = base_emb[0,length-1:length,:]
|
||||
wids, inds = np.unique(np.array(word_ids).reshape(-1), return_index=True)
|
||||
weight_dict = dict((id,w)
|
||||
for id,w in zip(wids ,np.array(weights).reshape(-1)[inds])
|
||||
if w != 1.0)
|
||||
|
||||
if len(weight_dict) == 0:
|
||||
return torch.zeros_like(base_emb), base_emb[0,length-1:length,:]
|
||||
|
||||
weight_tensor = torch.tensor(weights, dtype=base_emb.dtype, device=base_emb.device)
|
||||
weight_tensor = weight_tensor.reshape(1,-1,1).expand(base_emb.shape)
|
||||
|
||||
#m_token = (clip.tokenizer.end_token, 1.0) if clip.tokenizer.pad_with_end else (0,1.0)
|
||||
#TODO: find most suitable masking token here
|
||||
m_token = (m_token, 1.0)
|
||||
|
||||
ws = []
|
||||
masked_tokens = []
|
||||
masks = []
|
||||
|
||||
#create prompts
|
||||
for id, w in weight_dict.items():
|
||||
masked, m = mask_word_id(tokens, word_ids, id, m_token)
|
||||
masked_tokens.extend(masked)
|
||||
|
||||
m = torch.tensor(m, dtype=base_emb.dtype, device=base_emb.device)
|
||||
m = m.reshape(1,-1,1).expand(base_emb.shape)
|
||||
masks.append(m)
|
||||
|
||||
ws.append(w)
|
||||
|
||||
#batch process prompts
|
||||
embs = batched_clip_encode(masked_tokens, length, encode_func, len(tokens))
|
||||
masks = torch.cat(masks)
|
||||
|
||||
embs = (base_emb.expand(embs.shape) - embs)
|
||||
pooled = embs[0,length-1:length,:]
|
||||
|
||||
embs *= masks
|
||||
embs = embs.sum(axis=0, keepdim=True)
|
||||
|
||||
pooled_start = pooled_base.expand(len(ws), -1)
|
||||
ws = torch.tensor(ws).reshape(-1,1).expand(pooled_start.shape)
|
||||
pooled = (pooled - pooled_start) * (ws - 1)
|
||||
pooled = pooled.mean(axis=0, keepdim=True)
|
||||
|
||||
return ((weight_tensor - 1) * embs), pooled_base + pooled
|
||||
|
||||
def mask_inds(tokens, inds, mask_token):
|
||||
clip_len = len(tokens[0])
|
||||
inds_set = set(inds)
|
||||
new_tokens = [[mask_token if i*clip_len + j in inds_set else t
|
||||
for j, t in enumerate(x)] for i, x in enumerate(tokens)]
|
||||
return new_tokens
|
||||
|
||||
def down_weight(tokens, weights, word_ids, base_emb, length, encode_func, m_token=266):
|
||||
w, w_inv = np.unique(weights,return_inverse=True)
|
||||
|
||||
if np.sum(w < 1) == 0:
|
||||
return base_emb, tokens, base_emb[0,length-1:length,:]
|
||||
#m_token = (clip.tokenizer.end_token, 1.0) if clip.tokenizer.pad_with_end else (0,1.0)
|
||||
#using the comma token as a masking token seems to work better than aos tokens for SD 1.x
|
||||
m_token = (m_token, 1.0)
|
||||
|
||||
masked_tokens = []
|
||||
|
||||
masked_current = tokens
|
||||
for i in range(len(w)):
|
||||
if w[i] >= 1:
|
||||
continue
|
||||
masked_current = mask_inds(masked_current, np.where(w_inv == i)[0], m_token)
|
||||
masked_tokens.extend(masked_current)
|
||||
|
||||
embs = batched_clip_encode(masked_tokens, length, encode_func, len(tokens))
|
||||
embs = torch.cat([base_emb, embs])
|
||||
w = w[w<=1.0]
|
||||
w_mix = np.diff([0] + w.tolist())
|
||||
w_mix = torch.tensor(w_mix, dtype=embs.dtype, device=embs.device).reshape((-1,1,1))
|
||||
|
||||
weighted_emb = (w_mix * embs).sum(axis=0, keepdim=True)
|
||||
return weighted_emb, masked_current, weighted_emb[0,length-1:length,:]
|
||||
|
||||
def scale_emb_to_mag(base_emb, weighted_emb):
|
||||
norm_base = torch.linalg.norm(base_emb)
|
||||
norm_weighted = torch.linalg.norm(weighted_emb)
|
||||
embeddings_final = (norm_base / norm_weighted) * weighted_emb
|
||||
return embeddings_final
|
||||
|
||||
def recover_dist(base_emb, weighted_emb):
|
||||
fixed_std = (base_emb.std() / weighted_emb.std()) * (weighted_emb - weighted_emb.mean())
|
||||
embeddings_final = fixed_std + (base_emb.mean() - fixed_std.mean())
|
||||
return embeddings_final
|
||||
|
||||
def A1111_renorm(base_emb, weighted_emb):
|
||||
embeddings_final = (base_emb.mean() / weighted_emb.mean()) * weighted_emb
|
||||
return embeddings_final
|
||||
|
||||
def advanced_encode_from_tokens(tokenized, token_normalization, weight_interpretation, encode_func, m_token=266, length=77, w_max=1.0, return_pooled=False, apply_to_pooled=False):
|
||||
tokens = [[t for t,_,_ in x] for x in tokenized]
|
||||
weights = [[w for _,w,_ in x] for x in tokenized]
|
||||
word_ids = [[wid for _,_,wid in x] for x in tokenized]
|
||||
|
||||
#weight normalization
|
||||
#====================
|
||||
|
||||
#distribute down/up weights over word lengths
|
||||
if token_normalization.startswith("length"):
|
||||
weights = divide_length(word_ids, weights)
|
||||
|
||||
#make mean of word tokens 1
|
||||
if token_normalization.endswith("mean"):
|
||||
weights = shift_mean_weight(word_ids, weights)
|
||||
|
||||
#weight interpretation
|
||||
#=====================
|
||||
pooled = None
|
||||
|
||||
if weight_interpretation == "comfy":
|
||||
weighted_tokens = [[(t,w) for t, w in zip(x, y)] for x, y in zip(tokens, weights)]
|
||||
weighted_emb, pooled_base = encode_func(weighted_tokens)
|
||||
pooled = pooled_base
|
||||
else:
|
||||
unweighted_tokens = [[(t,1.0) for t, _,_ in x] for x in tokenized]
|
||||
base_emb, pooled_base = encode_func(unweighted_tokens)
|
||||
|
||||
if weight_interpretation == "A1111":
|
||||
weighted_emb = from_zero(weights, base_emb)
|
||||
weighted_emb = A1111_renorm(base_emb, weighted_emb)
|
||||
pooled = pooled_base
|
||||
|
||||
if weight_interpretation == "compel":
|
||||
pos_tokens = [[(t,w) if w >= 1.0 else (t,1.0) for t, w in zip(x, y)] for x, y in zip(tokens, weights)]
|
||||
weighted_emb, _ = encode_func(pos_tokens)
|
||||
weighted_emb, _, pooled = down_weight(pos_tokens, weights, word_ids, weighted_emb, length, encode_func)
|
||||
|
||||
if weight_interpretation == "comfy++":
|
||||
weighted_emb, tokens_down, _ = down_weight(unweighted_tokens, weights, word_ids, base_emb, length, encode_func)
|
||||
weights = [[w if w > 1.0 else 1.0 for w in x] for x in weights]
|
||||
#unweighted_tokens = [[(t,1.0) for t, _,_ in x] for x in tokens_down]
|
||||
embs, pooled = from_masked(unweighted_tokens, weights, word_ids, base_emb, length, encode_func)
|
||||
weighted_emb += embs
|
||||
|
||||
if weight_interpretation == "down_weight":
|
||||
weights = scale_to_norm(weights, word_ids, w_max)
|
||||
weighted_emb, _, pooled = down_weight(unweighted_tokens, weights, word_ids, base_emb, length, encode_func)
|
||||
|
||||
if return_pooled:
|
||||
if apply_to_pooled:
|
||||
return weighted_emb, pooled
|
||||
else:
|
||||
return weighted_emb, pooled_base
|
||||
return weighted_emb, None
|
||||
|
||||
def encode_token_weights_g(model, token_weight_pairs):
|
||||
return model.clip_g.encode_token_weights(token_weight_pairs)
|
||||
|
||||
def encode_token_weights_l(model, token_weight_pairs):
|
||||
l_out, _ = model.clip_l.encode_token_weights(token_weight_pairs)
|
||||
return l_out, None
|
||||
|
||||
def encode_token_weights(model, token_weight_pairs, encode_func):
|
||||
if model.layer_idx is not None:
|
||||
model.cond_stage_model.clip_layer(model.layer_idx)
|
||||
|
||||
model_management.load_model_gpu(model.patcher)
|
||||
return encode_func(model.cond_stage_model, token_weight_pairs)
|
||||
|
||||
def prepareXL(embs_l, embs_g, pooled, clip_balance):
|
||||
l_w = 1 - max(0, clip_balance - .5) * 2
|
||||
g_w = 1 - max(0, .5 - clip_balance) * 2
|
||||
if embs_l is not None:
|
||||
return torch.cat([embs_l * l_w, embs_g * g_w], dim=-1), pooled
|
||||
else:
|
||||
return embs_g, pooled
|
||||
|
||||
def advanced_encode(clip, text, token_normalization, weight_interpretation, w_max=1.0, clip_balance=.5, apply_to_pooled=True):
|
||||
tokenized = clip.tokenize(text, return_word_ids=True)
|
||||
if isinstance(clip.cond_stage_model, (SDXLClipModel, SDXLRefinerClipModel, SDXLClipG)):
|
||||
embs_l = None
|
||||
embs_g = None
|
||||
pooled = None
|
||||
if 'l' in tokenized and isinstance(clip.cond_stage_model, SDXLClipModel):
|
||||
embs_l, _ = advanced_encode_from_tokens(tokenized['l'],
|
||||
token_normalization,
|
||||
weight_interpretation,
|
||||
lambda x: encode_token_weights(clip, x, encode_token_weights_l),
|
||||
w_max=w_max,
|
||||
return_pooled=False)
|
||||
if 'g' in tokenized:
|
||||
embs_g, pooled = advanced_encode_from_tokens(tokenized['g'],
|
||||
token_normalization,
|
||||
weight_interpretation,
|
||||
lambda x: encode_token_weights(clip, x, encode_token_weights_g),
|
||||
w_max=w_max,
|
||||
return_pooled=True,
|
||||
apply_to_pooled=apply_to_pooled)
|
||||
return prepareXL(embs_l, embs_g, pooled, clip_balance)
|
||||
else:
|
||||
return advanced_encode_from_tokens(tokenized['l'],
|
||||
token_normalization,
|
||||
weight_interpretation,
|
||||
lambda x: (clip.encode_from_tokens({'l': x}), None),
|
||||
w_max=w_max)
|
||||
def advanced_encode_XL(clip, text1, text2, token_normalization, weight_interpretation, w_max=1.0, clip_balance=.5, apply_to_pooled=True):
|
||||
tokenized1 = clip.tokenize(text1, return_word_ids=True)
|
||||
tokenized2 = clip.tokenize(text2, return_word_ids=True)
|
||||
|
||||
embs_l, _ = advanced_encode_from_tokens(tokenized1['l'],
|
||||
token_normalization,
|
||||
weight_interpretation,
|
||||
lambda x: encode_token_weights(clip, x, encode_token_weights_l),
|
||||
w_max=w_max,
|
||||
return_pooled=False)
|
||||
|
||||
embs_g, pooled = advanced_encode_from_tokens(tokenized2['g'],
|
||||
token_normalization,
|
||||
weight_interpretation,
|
||||
lambda x: encode_token_weights(clip, x, encode_token_weights_g),
|
||||
w_max=w_max,
|
||||
return_pooled=True,
|
||||
apply_to_pooled=apply_to_pooled)
|
||||
|
||||
gcd_num = gcd(embs_l.shape[1], embs_g.shape[1])
|
||||
repeat_l = int((embs_g.shape[1] / gcd_num) * embs_l.shape[1])
|
||||
repeat_g = int((embs_l.shape[1] / gcd_num) * embs_g.shape[1])
|
||||
|
||||
return prepareXL(embs_l.expand((-1,repeat_l,-1)), embs_g.expand((-1,repeat_g,-1)), pooled, clip_balance)
|
||||
|
||||
########################################################################################################################
|
||||
from nodes import MAX_RESOLUTION
|
||||
|
||||
class AdvancedCLIPTextEncode:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"text": ("STRING", {"multiline": True}),
|
||||
"clip": ("CLIP",),
|
||||
"token_normalization": (["none", "mean", "length", "length+mean"],),
|
||||
"weight_interpretation": (["comfy", "A1111", "compel", "comfy++", "down_weight"],),
|
||||
# "affect_pooled": (["disable", "enable"],),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("CONDITIONING",)
|
||||
FUNCTION = "encode"
|
||||
|
||||
CATEGORY = "conditioning/advanced"
|
||||
|
||||
def encode(self, clip, text, token_normalization, weight_interpretation, affect_pooled='disable'):
|
||||
embeddings_final, pooled = advanced_encode(clip, text, token_normalization, weight_interpretation, w_max=1.0,
|
||||
apply_to_pooled=affect_pooled == 'enable')
|
||||
return ([[embeddings_final, {"pooled_output": pooled}]],)
|
||||
|
||||
|
||||
class AddCLIPSDXLRParams:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"conditioning": ("CONDITIONING",),
|
||||
"width": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
|
||||
"height": ("INT", {"default": 1024.0, "min": 0, "max": MAX_RESOLUTION}),
|
||||
"ascore": ("FLOAT", {"default": 6.0, "min": 0.0, "max": 1000.0, "step": 0.01}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("CONDITIONING",)
|
||||
FUNCTION = "encode"
|
||||
|
||||
CATEGORY = "conditioning/advanced"
|
||||
|
||||
def encode(self, conditioning, width, height, ascore):
|
||||
c = []
|
||||
for t in conditioning:
|
||||
n = [t[0], t[1].copy()]
|
||||
n[1]['width'] = width
|
||||
n[1]['height'] = height
|
||||
n[1]['aesthetic_score'] = ascore
|
||||
c.append(n)
|
||||
return (c,)
|
||||
|
||||
@@ -1,345 +0,0 @@
|
||||
# https://github.com/BlenderNeko/ComfyUI_TiledKSampler
|
||||
import sys
|
||||
import os
|
||||
import itertools
|
||||
import numpy as np
|
||||
from tqdm.auto import tqdm
|
||||
import torch
|
||||
|
||||
#sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy"))
|
||||
import comfy.sd
|
||||
import comfy.controlnet
|
||||
import comfy.model_management
|
||||
import comfy.sample
|
||||
from . import bnk_tiling as tiling
|
||||
import latent_preview
|
||||
#import torch
|
||||
#import itertools
|
||||
#import numpy as np
|
||||
MAX_RESOLUTION=8192
|
||||
|
||||
#######################
|
||||
|
||||
def recursion_to_list(obj, attr):
|
||||
current = obj
|
||||
yield current
|
||||
while True:
|
||||
current = getattr(current, attr, None)
|
||||
if current is not None:
|
||||
yield current
|
||||
else:
|
||||
return
|
||||
|
||||
def copy_cond(cond):
|
||||
return [[c1,c2.copy()] for c1,c2 in cond]
|
||||
|
||||
def slice_cond(tile_h, tile_h_len, tile_w, tile_w_len, cond, area, device):
|
||||
tile_h_end = tile_h + tile_h_len
|
||||
tile_w_end = tile_w + tile_w_len
|
||||
coords = area[0] #h_len, w_len, h, w,
|
||||
mask = area[1]
|
||||
if coords is not None:
|
||||
h_len, w_len, h, w = coords
|
||||
h_end = h + h_len
|
||||
w_end = w + w_len
|
||||
if h < tile_h_end and h_end > tile_h and w < tile_w_end and w_end > tile_w:
|
||||
new_h = max(0, h - tile_h)
|
||||
new_w = max(0, w - tile_w)
|
||||
new_h_end = min(tile_h_end, h_end - tile_h)
|
||||
new_w_end = min(tile_w_end, w_end - tile_w)
|
||||
cond[1]['area'] = (new_h_end - new_h, new_w_end - new_w, new_h, new_w)
|
||||
else:
|
||||
return (cond, True)
|
||||
if mask is not None:
|
||||
new_mask = tiling.get_slice(mask, tile_h,tile_h_len,tile_w,tile_w_len)
|
||||
if new_mask.sum().to(device) == 0.0 and 'mask' in cond[1]:
|
||||
return (cond, True)
|
||||
else:
|
||||
cond[1]['mask'] = new_mask
|
||||
return (cond, False)
|
||||
|
||||
def slice_gligen(tile_h, tile_h_len, tile_w, tile_w_len, cond, gligen):
|
||||
tile_h_end = tile_h + tile_h_len
|
||||
tile_w_end = tile_w + tile_w_len
|
||||
if gligen is None:
|
||||
return
|
||||
gligen_type = gligen[0]
|
||||
gligen_model = gligen[1]
|
||||
gligen_areas = gligen[2]
|
||||
|
||||
gligen_areas_new = []
|
||||
for emb, h_len, w_len, h, w in gligen_areas:
|
||||
h_end = h + h_len
|
||||
w_end = w + w_len
|
||||
if h < tile_h_end and h_end > tile_h and w < tile_w_end and w_end > tile_w:
|
||||
new_h = max(0, h - tile_h)
|
||||
new_w = max(0, w - tile_w)
|
||||
new_h_end = min(tile_h_end, h_end - tile_h)
|
||||
new_w_end = min(tile_w_end, w_end - tile_w)
|
||||
gligen_areas_new.append((emb, new_h_end - new_h, new_w_end - new_w, new_h, new_w))
|
||||
|
||||
if len(gligen_areas_new) == 0:
|
||||
del cond['gligen']
|
||||
else:
|
||||
cond['gligen'] = (gligen_type, gligen_model, gligen_areas_new)
|
||||
|
||||
def slice_cnet(h, h_len, w, w_len, model:comfy.controlnet.ControlBase, img):
|
||||
if img is None:
|
||||
img = model.cond_hint_original
|
||||
model.cond_hint = tiling.get_slice(img, h*8, h_len*8, w*8, w_len*8).to(model.control_model.dtype).to(model.device)
|
||||
|
||||
def slices_T2I(h, h_len, w, w_len, model:comfy.controlnet.ControlBase, img):
|
||||
model.control_input = None
|
||||
if img is None:
|
||||
img = model.cond_hint_original
|
||||
model.cond_hint = tiling.get_slice(img, h*8, h_len*8, w*8, w_len*8).float().to(model.device)
|
||||
|
||||
# TODO: refactor some of the mess
|
||||
|
||||
from PIL import Image
|
||||
|
||||
def sample_common(model, add_noise, noise_seed, tile_width, tile_height, tiling_strategy, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, start_at_step, end_at_step, return_with_leftover_noise, denoise=1.0, preview=False):
|
||||
end_at_step = min(end_at_step, steps)
|
||||
device = comfy.model_management.get_torch_device()
|
||||
samples = latent_image["samples"]
|
||||
noise_mask = latent_image["noise_mask"] if "noise_mask" in latent_image else None
|
||||
force_full_denoise = return_with_leftover_noise == "enable"
|
||||
if add_noise == "disable":
|
||||
noise = torch.zeros(samples.size(), dtype=samples.dtype, layout=samples.layout, device="cpu")
|
||||
else:
|
||||
skip = latent_image["batch_index"] if "batch_index" in latent_image else None
|
||||
noise = comfy.sample.prepare_noise(samples, noise_seed, skip)
|
||||
|
||||
if noise_mask is not None:
|
||||
noise_mask = comfy.sample.prepare_mask(noise_mask, noise.shape, device='cpu')
|
||||
|
||||
shape = samples.shape
|
||||
samples = samples.clone()
|
||||
|
||||
tile_width = min(shape[-1] * 8, tile_width)
|
||||
tile_height = min(shape[2] * 8, tile_height)
|
||||
|
||||
real_model = None
|
||||
positive_copy = comfy.sample.convert_cond(positive)
|
||||
negative_copy = comfy.sample.convert_cond(negative)
|
||||
modelPatches, inference_memory = comfy.sample.get_additional_models(positive_copy, negative_copy, model.model_dtype())
|
||||
comfy.model_management.load_models_gpu([model] + modelPatches, model.memory_required(noise.shape) + inference_memory)
|
||||
real_model = model.model
|
||||
|
||||
sampler = comfy.samplers.KSampler(real_model, steps=steps, device=device, sampler=sampler_name, scheduler=scheduler, denoise=denoise, model_options=model.model_options)
|
||||
|
||||
if tiling_strategy != 'padded':
|
||||
if noise_mask is not None:
|
||||
samples += sampler.sigmas[start_at_step].cpu() * noise_mask * model.model.process_latent_out(noise)
|
||||
else:
|
||||
samples += sampler.sigmas[start_at_step].cpu() * model.model.process_latent_out(noise)
|
||||
|
||||
#cnets
|
||||
cnets = [c['control'] for (_, c) in positive + negative if 'control' in c and isinstance(c['control'], comfy.controlnet.ControlNet)]
|
||||
cnets = list(set([x for m in cnets for x in recursion_to_list(m, "previous_controlnet")]))
|
||||
cnet_imgs = [
|
||||
torch.nn.functional.interpolate(m.cond_hint_original, (shape[-2] * 8, shape[-1] * 8), mode='nearest-exact').to('cpu')
|
||||
if m.cond_hint_original.shape[-2] != shape[-2] * 8 or m.cond_hint_original.shape[-1] != shape[-1] * 8 else None
|
||||
for m in cnets]
|
||||
|
||||
#T2I
|
||||
T2Is = [c['control'] for (_, c) in positive + negative if 'control' in c and isinstance(c['control'], comfy.controlnet.T2IAdapter)]
|
||||
T2Is = [x for m in T2Is for x in recursion_to_list(m, "previous_controlnet")]
|
||||
T2I_imgs = [
|
||||
torch.nn.functional.interpolate(m.cond_hint_original, (shape[-2] * 8, shape[-1] * 8), mode='nearest-exact').to('cpu')
|
||||
if m.cond_hint_original.shape[-2] != shape[-2] * 8 or m.cond_hint_original.shape[-1] != shape[-1] * 8 or (m.channels_in == 1 and m.cond_hint_original.shape[1] != 1) else None
|
||||
for m in T2Is
|
||||
]
|
||||
T2I_imgs = [
|
||||
torch.mean(img, 1, keepdim=True) if img is not None and m.channels_in == 1 and m.cond_hint_original.shape[1] else img
|
||||
for m, img in zip(T2Is, T2I_imgs)
|
||||
]
|
||||
|
||||
#cond area and mask
|
||||
spatial_conds_pos = [
|
||||
(c[1]['area'] if 'area' in c[1] else None,
|
||||
comfy.sample.prepare_mask(c[1]['mask'], shape, device) if 'mask' in c[1] else None)
|
||||
for c in positive
|
||||
]
|
||||
spatial_conds_neg = [
|
||||
(c[1]['area'] if 'area' in c[1] else None,
|
||||
comfy.sample.prepare_mask(c[1]['mask'], shape, device) if 'mask' in c[1] else None)
|
||||
for c in negative
|
||||
]
|
||||
|
||||
#gligen
|
||||
gligen_pos = [
|
||||
c[1]['gligen'] if 'gligen' in c[1] else None
|
||||
for c in positive
|
||||
]
|
||||
gligen_neg = [
|
||||
c[1]['gligen'] if 'gligen' in c[1] else None
|
||||
for c in negative
|
||||
]
|
||||
|
||||
|
||||
gen = torch.manual_seed(noise_seed)
|
||||
if tiling_strategy == 'random' or tiling_strategy == 'random strict':
|
||||
tiles = tiling.get_tiles_and_masks_rgrid(end_at_step - start_at_step, samples.shape, tile_height, tile_width, gen)
|
||||
elif tiling_strategy == 'padded':
|
||||
tiles = tiling.get_tiles_and_masks_padded(end_at_step - start_at_step, samples.shape, tile_height, tile_width)
|
||||
else:
|
||||
tiles = tiling.get_tiles_and_masks_simple(end_at_step - start_at_step, samples.shape, tile_height, tile_width)
|
||||
|
||||
total_steps = sum([num_steps for img_pass in tiles for steps_list in img_pass for _,_,_,_,num_steps,_ in steps_list])
|
||||
current_step = [0]
|
||||
|
||||
preview_format = "JPEG"
|
||||
if preview_format not in ["JPEG", "PNG"]:
|
||||
preview_format = "JPEG"
|
||||
previewer = None
|
||||
if preview:
|
||||
previewer = latent_preview.get_previewer(device, model.model.latent_format)
|
||||
|
||||
|
||||
with tqdm(total=total_steps) as pbar_tqdm:
|
||||
pbar = comfy.utils.ProgressBar(total_steps)
|
||||
|
||||
def callback(step, x0, x, total_steps):
|
||||
current_step[0] += 1
|
||||
preview_bytes = None
|
||||
if previewer:
|
||||
preview_bytes = previewer.decode_latent_to_preview_image(preview_format, x0)
|
||||
pbar.update_absolute(current_step[0], preview=preview_bytes)
|
||||
pbar_tqdm.update(1)
|
||||
|
||||
if tiling_strategy == "random strict":
|
||||
samples_next = samples.clone()
|
||||
for img_pass in tiles:
|
||||
for i in range(len(img_pass)):
|
||||
for tile_h, tile_h_len, tile_w, tile_w_len, tile_steps, tile_mask in img_pass[i]:
|
||||
tiled_mask = None
|
||||
if noise_mask is not None:
|
||||
tiled_mask = tiling.get_slice(noise_mask, tile_h, tile_h_len, tile_w, tile_w_len).to(device)
|
||||
if tile_mask is not None:
|
||||
if tiled_mask is not None:
|
||||
tiled_mask *= tile_mask.to(device)
|
||||
else:
|
||||
tiled_mask = tile_mask.to(device)
|
||||
|
||||
if tiling_strategy == 'padded' or tiling_strategy == 'random strict':
|
||||
tile_h, tile_h_len, tile_w, tile_w_len, tiled_mask = tiling.mask_at_boundary( tile_h, tile_h_len, tile_w, tile_w_len,
|
||||
tile_height, tile_width, samples.shape[-2], samples.shape[-1],
|
||||
tiled_mask, device)
|
||||
|
||||
|
||||
if tiled_mask is not None and tiled_mask.sum().cpu() == 0.0:
|
||||
continue
|
||||
|
||||
tiled_latent = tiling.get_slice(samples, tile_h, tile_h_len, tile_w, tile_w_len).to(device)
|
||||
|
||||
if tiling_strategy == 'padded':
|
||||
tiled_noise = tiling.get_slice(noise, tile_h, tile_h_len, tile_w, tile_w_len).to(device)
|
||||
else:
|
||||
if tiled_mask is None or noise_mask is None:
|
||||
tiled_noise = torch.zeros_like(tiled_latent)
|
||||
else:
|
||||
tiled_noise = tiling.get_slice(noise, tile_h, tile_h_len, tile_w, tile_w_len).to(device) * (1 - tiled_mask)
|
||||
|
||||
#TODO: all other condition based stuff like area sets and GLIGEN should also happen here
|
||||
|
||||
#cnets
|
||||
for m, img in zip(cnets, cnet_imgs):
|
||||
slice_cnet(tile_h, tile_h_len, tile_w, tile_w_len, m, img)
|
||||
|
||||
#T2I
|
||||
for m, img in zip(T2Is, T2I_imgs):
|
||||
slices_T2I(tile_h, tile_h_len, tile_w, tile_w_len, m, img)
|
||||
|
||||
pos = [c.copy() for c in positive_copy]#copy_cond(positive_copy)
|
||||
neg = [c.copy() for c in negative_copy]#copy_cond(negative_copy)
|
||||
|
||||
#cond areas
|
||||
pos = [slice_cond(tile_h, tile_h_len, tile_w, tile_w_len, c, area, device) for c, area in zip(pos, spatial_conds_pos)]
|
||||
pos = [c for c, ignore in pos if not ignore]
|
||||
neg = [slice_cond(tile_h, tile_h_len, tile_w, tile_w_len, c, area, device) for c, area in zip(neg, spatial_conds_neg)]
|
||||
neg = [c for c, ignore in neg if not ignore]
|
||||
|
||||
#gligen
|
||||
for cond, gligen in zip(pos, gligen_pos):
|
||||
slice_gligen(tile_h, tile_h_len, tile_w, tile_w_len, cond, gligen)
|
||||
for cond, gligen in zip(neg, gligen_neg):
|
||||
slice_gligen(tile_h, tile_h_len, tile_w, tile_w_len, cond, gligen)
|
||||
|
||||
tile_result = sampler.sample(tiled_noise, pos, neg, cfg=cfg, latent_image=tiled_latent, start_step=start_at_step + i * tile_steps, last_step=start_at_step + i*tile_steps + tile_steps, force_full_denoise=force_full_denoise and i+1 == end_at_step - start_at_step, denoise_mask=tiled_mask, callback=callback, disable_pbar=True, seed=noise_seed)
|
||||
tile_result = tile_result.cpu()
|
||||
if tiled_mask is not None:
|
||||
tiled_mask = tiled_mask.cpu()
|
||||
if tiling_strategy == "random strict":
|
||||
tiling.set_slice(samples_next, tile_result, tile_h, tile_h_len, tile_w, tile_w_len, tiled_mask)
|
||||
else:
|
||||
tiling.set_slice(samples, tile_result, tile_h, tile_h_len, tile_w, tile_w_len, tiled_mask)
|
||||
if tiling_strategy == "random strict":
|
||||
samples = samples_next.clone()
|
||||
|
||||
|
||||
comfy.sample.cleanup_additional_models(modelPatches)
|
||||
|
||||
out = latent_image.copy()
|
||||
out["samples"] = samples.cpu()
|
||||
return (out, )
|
||||
|
||||
|
||||
class TiledKSampler:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required":
|
||||
{"model": ("MODEL",),
|
||||
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
"tile_width": ("INT", {"default": 512, "min": 256, "max": MAX_RESOLUTION, "step": 64}),
|
||||
"tile_height": ("INT", {"default": 512, "min": 256, "max": MAX_RESOLUTION, "step": 64}),
|
||||
"tiling_strategy": (["random", "random strict", "padded", 'simple'], ),
|
||||
"steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
|
||||
"cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0}),
|
||||
"sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
|
||||
"scheduler": (comfy.samplers.KSampler.SCHEDULERS, ),
|
||||
"positive": ("CONDITIONING", ),
|
||||
"negative": ("CONDITIONING", ),
|
||||
"latent_image": ("LATENT", ),
|
||||
"denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
FUNCTION = "sample"
|
||||
|
||||
CATEGORY = "sampling"
|
||||
|
||||
def sample(self, model, seed, tile_width, tile_height, tiling_strategy, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise):
|
||||
steps_total = int(steps / denoise)
|
||||
return sample_common(model, 'enable', seed, tile_width, tile_height, tiling_strategy, steps_total, cfg, sampler_name, scheduler, positive, negative, latent_image, steps_total-steps, steps_total, 'disable', denoise=1.0, preview=True)
|
||||
|
||||
class TiledKSamplerAdvanced:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required":
|
||||
{"model": ("MODEL",),
|
||||
"add_noise": (["enable", "disable"], ),
|
||||
"noise_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
"tile_width": ("INT", {"default": 512, "min": 256, "max": MAX_RESOLUTION, "step": 64}),
|
||||
"tile_height": ("INT", {"default": 512, "min": 256, "max": MAX_RESOLUTION, "step": 64}),
|
||||
"tiling_strategy": (["random", "random strict", "padded", 'simple'], ),
|
||||
"steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
|
||||
"cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0}),
|
||||
"sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
|
||||
"scheduler": (comfy.samplers.KSampler.SCHEDULERS, ),
|
||||
"positive": ("CONDITIONING", ),
|
||||
"negative": ("CONDITIONING", ),
|
||||
"latent_image": ("LATENT", ),
|
||||
"start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000}),
|
||||
"end_at_step": ("INT", {"default": 10000, "min": 0, "max": 10000}),
|
||||
"return_with_leftover_noise": (["disable", "enable"], ),
|
||||
"preview": (["disable", "enable"], ),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
FUNCTION = "sample"
|
||||
|
||||
CATEGORY = "sampling"
|
||||
|
||||
def sample(self, model, add_noise, noise_seed, tile_width, tile_height, tiling_strategy, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, start_at_step, end_at_step, return_with_leftover_noise, preview, denoise=1.0):
|
||||
return sample_common(model, add_noise, noise_seed, tile_width, tile_height, tiling_strategy, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, start_at_step, end_at_step, return_with_leftover_noise, denoise=1.0, preview= preview == 'enable')
|
||||
@@ -1,175 +0,0 @@
|
||||
import torch
|
||||
import itertools
|
||||
import numpy as np
|
||||
|
||||
def grouper(n, iterable):
|
||||
it = iter(iterable)
|
||||
while True:
|
||||
chunk = list(itertools.islice(it, n))
|
||||
if not chunk:
|
||||
return
|
||||
yield chunk
|
||||
|
||||
def create_batches(n, iterable):
|
||||
groups = itertools.groupby(iterable, key= lambda x: (x[1], x[3]))
|
||||
for _, x in groups:
|
||||
for y in grouper(n, x):
|
||||
yield y
|
||||
|
||||
|
||||
def get_slice(tensor, h, h_len, w, w_len):
|
||||
t = tensor.narrow(-2, h, h_len)
|
||||
t = t.narrow(-1, w, w_len)
|
||||
return t
|
||||
|
||||
def set_slice(tensor1,tensor2, h, h_len, w, w_len, mask=None):
|
||||
if mask is not None:
|
||||
tensor1[:,:,h:h+h_len,w:w+w_len] = tensor1[:,:,h:h+h_len,w:w+w_len] * (1 - mask) + tensor2 * mask
|
||||
else:
|
||||
tensor1[:,:,h:h+h_len,w:w+w_len] = tensor2
|
||||
|
||||
def get_tiles_and_masks_simple(steps, latent_shape, tile_height, tile_width):
|
||||
latent_size_h = latent_shape[-2]
|
||||
latent_size_w = latent_shape[-1]
|
||||
tile_size_h = int(tile_height // 8)
|
||||
tile_size_w = int(tile_width // 8)
|
||||
|
||||
h = np.arange(0,latent_size_h, tile_size_h)
|
||||
w = np.arange(0,latent_size_w, tile_size_w)
|
||||
|
||||
def create_tile(hs, ws, i, j):
|
||||
h = int(hs[i])
|
||||
w = int(ws[j])
|
||||
h_len = min(tile_size_h, latent_size_h - h)
|
||||
w_len = min(tile_size_w, latent_size_w - w)
|
||||
return (h, h_len, w, w_len, steps, None)
|
||||
|
||||
passes = [
|
||||
[[create_tile(h, w, i, j) for i in range(len(h)) for j in range(len(w))]],
|
||||
]
|
||||
return passes
|
||||
|
||||
def get_tiles_and_masks_padded(steps, latent_shape, tile_height, tile_width):
|
||||
batch_size = latent_shape[0]
|
||||
latent_size_h = latent_shape[-2]
|
||||
latent_size_w = latent_shape[-1]
|
||||
|
||||
tile_size_h = int(tile_height // 8)
|
||||
tile_size_h = int((tile_size_h // 4) * 4)
|
||||
tile_size_w = int(tile_width // 8)
|
||||
tile_size_w = int((tile_size_w // 4) * 4)
|
||||
|
||||
#masks
|
||||
mask_h = [0,tile_size_h // 4, tile_size_h - tile_size_h // 4, tile_size_h]
|
||||
mask_w = [0,tile_size_w // 4, tile_size_w - tile_size_w // 4, tile_size_w]
|
||||
masks = [[] for _ in range(3)]
|
||||
for i in range(3):
|
||||
for j in range(3):
|
||||
mask = torch.zeros((batch_size,1,tile_size_h, tile_size_w), dtype=torch.float32, device='cpu')
|
||||
mask[:,:,mask_h[i]:mask_h[i+1],mask_w[j]:mask_w[j+1]] = 1.0
|
||||
masks[i].append(mask)
|
||||
|
||||
def create_mask(h_ind, w_ind, h_ind_max, w_ind_max, mask_h, mask_w, h_len, w_len):
|
||||
mask = masks[1][1]
|
||||
if not (h_ind == 0 or h_ind == h_ind_max or w_ind == 0 or w_ind == w_ind_max):
|
||||
return get_slice(mask, 0, h_len, 0, w_len)
|
||||
mask = mask.clone()
|
||||
if h_ind == 0 and mask_h:
|
||||
mask += masks[0][1]
|
||||
if h_ind == h_ind_max and mask_h:
|
||||
mask += masks[2][1]
|
||||
if w_ind == 0 and mask_w:
|
||||
mask += masks[1][0]
|
||||
if w_ind == w_ind_max and mask_w:
|
||||
mask += masks[1][2]
|
||||
if h_ind == 0 and w_ind == 0 and mask_h and mask_w:
|
||||
mask += masks[0][0]
|
||||
if h_ind == 0 and w_ind == w_ind_max and mask_h and mask_w:
|
||||
mask += masks[0][2]
|
||||
if h_ind == h_ind_max and w_ind == 0 and mask_h and mask_w:
|
||||
mask += masks[2][0]
|
||||
if h_ind == h_ind_max and w_ind == w_ind_max and mask_h and mask_w:
|
||||
mask += masks[2][2]
|
||||
return get_slice(mask, 0, h_len, 0, w_len)
|
||||
|
||||
h = np.arange(0,latent_size_h, tile_size_h)
|
||||
h_shift = np.arange(tile_size_h // 2, latent_size_h - tile_size_h // 2, tile_size_h)
|
||||
w = np.arange(0,latent_size_w, tile_size_w)
|
||||
w_shift = np.arange(tile_size_w // 2, latent_size_w - tile_size_h // 2, tile_size_w)
|
||||
|
||||
|
||||
def create_tile(hs, ws, mask_h, mask_w, i, j):
|
||||
h = int(hs[i])
|
||||
w = int(ws[j])
|
||||
h_len = min(tile_size_h, latent_size_h - h)
|
||||
w_len = min(tile_size_w, latent_size_w - w)
|
||||
mask = create_mask(i,j,len(hs)-1, len(ws)-1, mask_h, mask_w, h_len, w_len)
|
||||
return (h, h_len, w, w_len, steps, mask)
|
||||
|
||||
passes = [
|
||||
[[create_tile(h, w, True, True, i, j) for i in range(len(h)) for j in range(len(w))]],
|
||||
[[create_tile(h_shift, w, False, True, i, j) for i in range(len(h_shift)) for j in range(len(w))]],
|
||||
[[create_tile(h, w_shift, True, False, i, j) for i in range(len(h)) for j in range(len(w_shift))]],
|
||||
[[create_tile(h_shift, w_shift, False, False, i,j) for i in range(len(h_shift)) for j in range(len(w_shift))]],
|
||||
]
|
||||
|
||||
return passes
|
||||
|
||||
def mask_at_boundary(h, h_len, w, w_len, tile_size_h, tile_size_w, latent_size_h, latent_size_w, mask, device='cpu'):
|
||||
tile_size_h = int(tile_size_h // 8)
|
||||
tile_size_w = int(tile_size_w // 8)
|
||||
|
||||
if (h_len == tile_size_h or h_len == latent_size_h) and (w_len == tile_size_w or w_len == latent_size_w):
|
||||
return h, h_len, w, w_len, mask
|
||||
h_offset = min(0, latent_size_h - (h + tile_size_h))
|
||||
w_offset = min(0, latent_size_w - (w + tile_size_w))
|
||||
new_mask = torch.zeros((1,1,tile_size_h, tile_size_w), dtype=torch.float32, device=device)
|
||||
new_mask[:,:,-h_offset:h_len if h_offset == 0 else tile_size_h, -w_offset:w_len if w_offset == 0 else tile_size_w] = 1.0 if mask is None else mask
|
||||
return h + h_offset, tile_size_h, w + w_offset, tile_size_w, new_mask
|
||||
|
||||
def get_tiles_and_masks_rgrid(steps, latent_shape, tile_height, tile_width, generator):
|
||||
|
||||
def calc_coords(latent_size, tile_size, jitter):
|
||||
tile_coords = int((latent_size + jitter - 1) // tile_size + 1)
|
||||
tile_coords = [np.clip(tile_size * c - jitter, 0, latent_size) for c in range(tile_coords + 1)]
|
||||
tile_coords = [(c1, c2-c1) for c1, c2 in zip(tile_coords, tile_coords[1:])]
|
||||
return tile_coords
|
||||
|
||||
#calc stuff
|
||||
batch_size = latent_shape[0]
|
||||
latent_size_h = latent_shape[-2]
|
||||
latent_size_w = latent_shape[-1]
|
||||
tile_size_h = int(tile_height // 8)
|
||||
tile_size_w = int(tile_width // 8)
|
||||
|
||||
tiles_all = []
|
||||
|
||||
for s in range(steps):
|
||||
rands = torch.rand((2,), dtype=torch.float32, generator=generator, device='cpu').numpy()
|
||||
|
||||
jitter_w1 = int(rands[0] * tile_size_w)
|
||||
jitter_w2 = int(((rands[0] + .5) % 1.0) * tile_size_w)
|
||||
jitter_h1 = int(rands[1] * tile_size_h)
|
||||
jitter_h2 = int(((rands[1] + .5) % 1.0) * tile_size_h)
|
||||
|
||||
#calc number of tiles
|
||||
tiles_h = [
|
||||
calc_coords(latent_size_h, tile_size_h, jitter_h1),
|
||||
calc_coords(latent_size_h, tile_size_h, jitter_h2)
|
||||
]
|
||||
tiles_w = [
|
||||
calc_coords(latent_size_w, tile_size_w, jitter_w1),
|
||||
calc_coords(latent_size_w, tile_size_w, jitter_w2)
|
||||
]
|
||||
|
||||
tiles = []
|
||||
if s % 2 == 0:
|
||||
for i, h in enumerate(tiles_h[0]):
|
||||
for w in tiles_w[i%2]:
|
||||
tiles.append((int(h[0]), int(h[1]), int(w[0]), int(w[1]), 1, None))
|
||||
else:
|
||||
for i, w in enumerate(tiles_w[0]):
|
||||
for h in tiles_h[i%2]:
|
||||
tiles.append((int(h[0]), int(h[1]), int(w[0]), int(w[1]), 1, None))
|
||||
tiles_all.append(tiles)
|
||||
return [tiles_all]
|
||||
@@ -1,16 +0,0 @@
|
||||
# https://github.com/chrisgoringe/cg-noise
|
||||
import torch
|
||||
|
||||
def get_mixed_noise_function(original_noise_function, variation_seed, variation_weight):
|
||||
def prepare_mixed_noise(latent_image:torch.Tensor, seed, batch_inds):
|
||||
single_image_latent = latent_image[0].unsqueeze_(0)
|
||||
different_noise = original_noise_function(single_image_latent, variation_seed, batch_inds)
|
||||
original_noise = original_noise_function(single_image_latent, seed, batch_inds)
|
||||
if latent_image.shape[0]==1:
|
||||
mixed_noise = original_noise * (1.0-variation_weight) + different_noise * (variation_weight)
|
||||
else:
|
||||
mixed_noise = torch.empty_like(latent_image)
|
||||
for i in range(latent_image.shape[0]):
|
||||
mixed_noise[i] = original_noise * (1.0-variation_weight*i) + different_noise * (variation_weight*i)
|
||||
return mixed_noise
|
||||
return prepare_mixed_noise
|
||||
@@ -1,94 +0,0 @@
|
||||
# https://github.com/city96/SD-Latent-Upscaler
|
||||
# check if any issues on weights and updates and local install for same
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from safetensors.torch import load_file
|
||||
from huggingface_hub import hf_hub_download
|
||||
|
||||
class Upscaler(nn.Module):
|
||||
"""
|
||||
Basic NN layout, ported from:
|
||||
https://github.com/city96/SD-Latent-Upscaler/blob/main/upscaler.py
|
||||
"""
|
||||
version = 2.1 # network revision
|
||||
def head(self):
|
||||
return [
|
||||
nn.Conv2d(self.chan, self.size, kernel_size=self.krn, padding=self.pad),
|
||||
nn.ReLU(),
|
||||
nn.Upsample(scale_factor=self.fac, mode="nearest"),
|
||||
nn.ReLU(),
|
||||
]
|
||||
def core(self):
|
||||
layers = []
|
||||
for _ in range(self.depth):
|
||||
layers += [
|
||||
nn.Conv2d(self.size, self.size, kernel_size=self.krn, padding=self.pad),
|
||||
nn.ReLU(),
|
||||
]
|
||||
return layers
|
||||
def tail(self):
|
||||
return [
|
||||
nn.Conv2d(self.size, self.chan, kernel_size=self.krn, padding=self.pad),
|
||||
]
|
||||
|
||||
def __init__(self, fac, depth=16):
|
||||
super().__init__()
|
||||
self.size = 64 # Conv2d size
|
||||
self.chan = 4 # in/out channels
|
||||
self.depth = depth # no. of layers
|
||||
self.fac = fac # scale factor
|
||||
self.krn = 3 # kernel size
|
||||
self.pad = 1 # padding
|
||||
|
||||
self.sequential = nn.Sequential(
|
||||
*self.head(),
|
||||
*self.core(),
|
||||
*self.tail(),
|
||||
)
|
||||
|
||||
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
||||
return self.sequential(x)
|
||||
|
||||
|
||||
class LatentUpscaler:
|
||||
def __init__(self):
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"samples": ("LATENT", ),
|
||||
"latent_ver": (["v1", "xl"],),
|
||||
"scale_factor": (["1.25", "1.5", "2.0"],),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
FUNCTION = "upscale"
|
||||
CATEGORY = "latent"
|
||||
|
||||
def upscale(self, samples, latent_ver, scale_factor):
|
||||
model = Upscaler(scale_factor)
|
||||
weights = str(hf_hub_download(
|
||||
repo_id="city96/SD-Latent-Upscaler",
|
||||
filename=f"latent-upscaler-v{model.version}_SD{latent_ver}-x{scale_factor}.safetensors")
|
||||
)
|
||||
# weights = f"./latent-upscaler-v{model.version}_SD{latent_ver}-x{scale_factor}.safetensors"
|
||||
|
||||
model.load_state_dict(load_file(weights))
|
||||
lt = samples["samples"]
|
||||
lt = model(lt)
|
||||
del model
|
||||
if "noise_mask" in samples.keys():
|
||||
# expand the noise mask to the same shape as the latent
|
||||
mask = torch.nn.functional.interpolate(samples['noise_mask'], scale_factor=float(scale_factor), mode='bicubic')
|
||||
return ({"samples": lt, "noise_mask": mask},)
|
||||
return ({"samples": lt},)
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"LatentUpscaler": LatentUpscaler,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"LatentUpscaler": "EFF_C Latent Upscaler"
|
||||
}
|
||||
@@ -1,321 +0,0 @@
|
||||
# https://github.com/shiimizu/ComfyUI_smZNodes
|
||||
import comfy
|
||||
import torch
|
||||
from typing import List
|
||||
import comfy.sample
|
||||
from comfy import model_base, model_management
|
||||
from comfy.samplers import KSampler, KSamplerX0Inpaint, wrap_model
|
||||
#from comfy.k_diffusion.external import CompVisDenoiser
|
||||
import nodes
|
||||
import inspect
|
||||
import functools
|
||||
import importlib
|
||||
import os
|
||||
import re
|
||||
import itertools
|
||||
|
||||
import torch
|
||||
from comfy import model_management
|
||||
|
||||
def catenate_conds(conds):
|
||||
if not isinstance(conds[0], dict):
|
||||
return torch.cat(conds)
|
||||
|
||||
return {key: torch.cat([x[key] for x in conds]) for key in conds[0].keys()}
|
||||
|
||||
|
||||
def subscript_cond(cond, a, b):
|
||||
if not isinstance(cond, dict):
|
||||
return cond[a:b]
|
||||
|
||||
return {key: vec[a:b] for key, vec in cond.items()}
|
||||
|
||||
|
||||
def pad_cond(tensor, repeats, empty):
|
||||
if not isinstance(tensor, dict):
|
||||
return torch.cat([tensor, empty.repeat((tensor.shape[0], repeats, 1)).to(device=tensor.device)], axis=1)
|
||||
|
||||
tensor['crossattn'] = pad_cond(tensor['crossattn'], repeats, empty)
|
||||
return tensor
|
||||
|
||||
|
||||
class CFGDenoiser(torch.nn.Module):
|
||||
"""
|
||||
Classifier free guidance denoiser. A wrapper for stable diffusion model (specifically for unet)
|
||||
that can take a noisy picture and produce a noise-free picture using two guidances (prompts)
|
||||
instead of one. Originally, the second prompt is just an empty string, but we use non-empty
|
||||
negative prompt.
|
||||
"""
|
||||
|
||||
def __init__(self, model):
|
||||
super().__init__()
|
||||
self.inner_model = model
|
||||
self.model_wrap = None
|
||||
self.mask = None
|
||||
self.nmask = None
|
||||
self.init_latent = None
|
||||
self.steps = None
|
||||
"""number of steps as specified by user in UI"""
|
||||
|
||||
self.total_steps = None
|
||||
"""expected number of calls to denoiser calculated from self.steps and specifics of the selected sampler"""
|
||||
|
||||
self.step = 0
|
||||
self.image_cfg_scale = None
|
||||
self.padded_cond_uncond = False
|
||||
self.sampler = None
|
||||
self.model_wrap = None
|
||||
self.p = None
|
||||
self.mask_before_denoising = False
|
||||
|
||||
|
||||
def combine_denoised(self, x_out, conds_list, uncond, cond_scale):
|
||||
denoised_uncond = x_out[-uncond.shape[0]:]
|
||||
denoised = torch.clone(denoised_uncond)
|
||||
|
||||
for i, conds in enumerate(conds_list):
|
||||
for cond_index, weight in conds:
|
||||
denoised[i] += (x_out[cond_index] - denoised_uncond[i]) * (weight * cond_scale)
|
||||
|
||||
return denoised
|
||||
|
||||
def combine_denoised_for_edit_model(self, x_out, cond_scale):
|
||||
out_cond, out_img_cond, out_uncond = x_out.chunk(3)
|
||||
denoised = out_uncond + cond_scale * (out_cond - out_img_cond) + self.image_cfg_scale * (out_img_cond - out_uncond)
|
||||
|
||||
return denoised
|
||||
|
||||
def get_pred_x0(self, x_in, x_out, sigma):
|
||||
return x_out
|
||||
|
||||
def update_inner_model(self):
|
||||
self.model_wrap = None
|
||||
|
||||
c, uc = self.p.get_conds()
|
||||
self.sampler.sampler_extra_args['cond'] = c
|
||||
self.sampler.sampler_extra_args['uncond'] = uc
|
||||
|
||||
def forward(self, x, sigma, uncond, cond, cond_scale, s_min_uncond, image_cond):
|
||||
model_management.throw_exception_if_processing_interrupted()
|
||||
|
||||
is_edit_model = False
|
||||
|
||||
conds_list, tensor = cond
|
||||
assert not is_edit_model or all(len(conds) == 1 for conds in conds_list), "AND is not supported for InstructPix2Pix checkpoint (unless using Image CFG scale = 1.0)"
|
||||
|
||||
if self.mask_before_denoising and self.mask is not None:
|
||||
x = self.init_latent * self.mask + self.nmask * x
|
||||
|
||||
batch_size = len(conds_list)
|
||||
repeats = [len(conds_list[i]) for i in range(batch_size)]
|
||||
|
||||
if False:
|
||||
image_uncond = torch.zeros_like(image_cond)
|
||||
make_condition_dict = lambda c_crossattn, c_adm: {"c_crossattn": c_crossattn, "c_adm": c_adm, 'transformer_options': {'from_smZ': True}} # pylint: disable=C3001
|
||||
else:
|
||||
image_uncond = image_cond
|
||||
if isinstance(uncond, dict):
|
||||
make_condition_dict = lambda c_crossattn, c_concat: {**c_crossattn, "c_concat": None, "c_adm": x.c_adm, 'transformer_options': {'from_smZ': True}}
|
||||
else:
|
||||
make_condition_dict = lambda c_crossattn, c_concat: {"c_crossattn": c_crossattn, "c_concat": None, "c_adm": x.c_adm, 'transformer_options': {'from_smZ': True}}
|
||||
|
||||
if not is_edit_model:
|
||||
x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x])
|
||||
sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma])
|
||||
image_cond_in = torch.cat([torch.stack([image_cond[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [image_uncond])
|
||||
else:
|
||||
x_in = torch.cat([torch.stack([x[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [x] + [x])
|
||||
sigma_in = torch.cat([torch.stack([sigma[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [sigma] + [sigma])
|
||||
image_cond_in = torch.cat([torch.stack([image_cond[i] for _ in range(n)]) for i, n in enumerate(repeats)] + [image_uncond] + [torch.zeros_like(self.init_latent)])
|
||||
|
||||
skip_uncond = False
|
||||
|
||||
# alternating uncond allows for higher thresholds without the quality loss normally expected from raising it
|
||||
if self.step % 2 and s_min_uncond > 0 and sigma[0] < s_min_uncond and not is_edit_model:
|
||||
skip_uncond = True
|
||||
x_in = x_in[:-batch_size]
|
||||
sigma_in = sigma_in[:-batch_size]
|
||||
|
||||
if tensor.shape[1] == uncond.shape[1] or skip_uncond:
|
||||
if is_edit_model:
|
||||
cond_in = catenate_conds([tensor, uncond, uncond])
|
||||
elif skip_uncond:
|
||||
cond_in = tensor
|
||||
else:
|
||||
cond_in = catenate_conds([tensor, uncond])
|
||||
|
||||
x_out = torch.zeros_like(x_in)
|
||||
for batch_offset in range(0, x_out.shape[0], batch_size):
|
||||
a = batch_offset
|
||||
b = a + batch_size
|
||||
x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], **make_condition_dict(subscript_cond(cond_in, a, b), image_cond_in[a:b]))
|
||||
else:
|
||||
x_out = torch.zeros_like(x_in)
|
||||
for batch_offset in range(0, tensor.shape[0], batch_size):
|
||||
a = batch_offset
|
||||
b = min(a + batch_size, tensor.shape[0])
|
||||
|
||||
if not is_edit_model:
|
||||
c_crossattn = subscript_cond(tensor, a, b)
|
||||
else:
|
||||
c_crossattn = torch.cat([tensor[a:b]], uncond)
|
||||
|
||||
x_out[a:b] = self.inner_model(x_in[a:b], sigma_in[a:b], **make_condition_dict(c_crossattn, image_cond_in[a:b]))
|
||||
|
||||
if not skip_uncond:
|
||||
x_out[-uncond.shape[0]:] = self.inner_model(x_in[-uncond.shape[0]:], sigma_in[-uncond.shape[0]:], **make_condition_dict(uncond, image_cond_in[-uncond.shape[0]:]))
|
||||
|
||||
denoised_image_indexes = [x[0][0] for x in conds_list]
|
||||
if skip_uncond:
|
||||
fake_uncond = torch.cat([x_out[i:i+1] for i in denoised_image_indexes])
|
||||
x_out = torch.cat([x_out, fake_uncond]) # we skipped uncond denoising, so we put cond-denoised image to where the uncond-denoised image should be
|
||||
|
||||
if is_edit_model:
|
||||
denoised = self.combine_denoised_for_edit_model(x_out, cond_scale)
|
||||
elif skip_uncond:
|
||||
denoised = self.combine_denoised(x_out, conds_list, uncond, 1.0)
|
||||
else:
|
||||
denoised = self.combine_denoised(x_out, conds_list, uncond, cond_scale)
|
||||
|
||||
if not self.mask_before_denoising and self.mask is not None:
|
||||
denoised = self.init_latent * self.mask + self.nmask * denoised
|
||||
|
||||
self.step += 1
|
||||
del x_out
|
||||
return denoised
|
||||
|
||||
# ========================================================================
|
||||
|
||||
def expand(tensor1, tensor2):
|
||||
def adjust_tensor_shape(tensor_small, tensor_big):
|
||||
# Calculate replication factor
|
||||
# -(-a // b) is ceiling of division without importing math.ceil
|
||||
replication_factor = -(-tensor_big.size(1) // tensor_small.size(1))
|
||||
|
||||
# Use repeat to extend tensor_small
|
||||
tensor_small_extended = tensor_small.repeat(1, replication_factor, 1)
|
||||
|
||||
# Take the rows of the extended tensor_small to match tensor_big
|
||||
tensor_small_matched = tensor_small_extended[:, :tensor_big.size(1), :]
|
||||
|
||||
return tensor_small_matched
|
||||
|
||||
# Check if their second dimensions are different
|
||||
if tensor1.size(1) != tensor2.size(1):
|
||||
# Check which tensor has the smaller second dimension and adjust its shape
|
||||
if tensor1.size(1) < tensor2.size(1):
|
||||
tensor1 = adjust_tensor_shape(tensor1, tensor2)
|
||||
else:
|
||||
tensor2 = adjust_tensor_shape(tensor2, tensor1)
|
||||
return (tensor1, tensor2)
|
||||
|
||||
def _find_outer_instance(target, target_type):
|
||||
import inspect
|
||||
frame = inspect.currentframe()
|
||||
while frame:
|
||||
if target in frame.f_locals:
|
||||
found = frame.f_locals[target]
|
||||
if isinstance(found, target_type) and found != 1: # steps == 1
|
||||
return found
|
||||
frame = frame.f_back
|
||||
return None
|
||||
|
||||
# ========================================================================
|
||||
def bounded_modulo(number, modulo_value):
|
||||
return number if number < modulo_value else modulo_value
|
||||
|
||||
def calc_cond(c, current_step):
|
||||
"""Group by smZ conds that may do prompt-editing / regular conds / comfy conds."""
|
||||
_cond = []
|
||||
# Group by conds from smZ
|
||||
fn=lambda x : x[1].get("from_smZ", None) is not None
|
||||
an_iterator = itertools.groupby(c, fn )
|
||||
for key, group in an_iterator:
|
||||
ls=list(group)
|
||||
# Group by prompt-editing conds
|
||||
fn2=lambda x : x[1].get("smZid", None)
|
||||
an_iterator2 = itertools.groupby(ls, fn2)
|
||||
for key2, group2 in an_iterator2:
|
||||
ls2=list(group2)
|
||||
if key2 is not None:
|
||||
orig_len = ls2[0][1].get('orig_len', 1)
|
||||
i = bounded_modulo(current_step, orig_len - 1)
|
||||
_cond = _cond + [ls2[i]]
|
||||
else:
|
||||
_cond = _cond + ls2
|
||||
return _cond
|
||||
|
||||
class CFGNoisePredictor(torch.nn.Module):
|
||||
def __init__(self, model):
|
||||
super().__init__()
|
||||
self.ksampler = _find_outer_instance('self', comfy.samplers.KSampler)
|
||||
self.step = 0
|
||||
self.orig = comfy.samplers.CFGNoisePredictor(model) #CFGNoisePredictorOrig(model)
|
||||
self.inner_model = model
|
||||
self.inner_model2 = CFGDenoiser(model.apply_model)
|
||||
self.inner_model2.num_timesteps = model.num_timesteps
|
||||
self.inner_model2.device = self.ksampler.device if hasattr(self.ksampler, "device") else None
|
||||
self.s_min_uncond = 0.0
|
||||
self.alphas_cumprod = model.alphas_cumprod
|
||||
self.c_adm = None
|
||||
self.init_cond = None
|
||||
self.init_uncond = None
|
||||
self.is_prompt_editing_u = False
|
||||
self.is_prompt_editing_c = False
|
||||
|
||||
def apply_model(self, x, timestep, cond, uncond, cond_scale, cond_concat=None, model_options={}, seed=None):
|
||||
|
||||
cc=calc_cond(cond, self.step)
|
||||
uu=calc_cond(uncond, self.step)
|
||||
self.step += 1
|
||||
|
||||
if (any([p[1].get('from_smZ', False) for p in cc]) or
|
||||
any([p[1].get('from_smZ', False) for p in uu])):
|
||||
if model_options.get('transformer_options',None) is None:
|
||||
model_options['transformer_options'] = {}
|
||||
model_options['transformer_options']['from_smZ'] = True
|
||||
|
||||
# Only supports one cond
|
||||
for ix in range(len(cc)):
|
||||
if cc[ix][1].get('from_smZ', False):
|
||||
cc = [cc[ix]]
|
||||
break
|
||||
for ix in range(len(uu)):
|
||||
if uu[ix][1].get('from_smZ', False):
|
||||
uu = [uu[ix]]
|
||||
break
|
||||
c=cc[0][1]
|
||||
u=uu[0][1]
|
||||
_cc = cc[0][0]
|
||||
_uu = uu[0][0]
|
||||
if c.get("adm_encoded", None) is not None:
|
||||
self.c_adm = torch.cat([c['adm_encoded'], u['adm_encoded']])
|
||||
# SDXL. Need to pad with repeats
|
||||
_cc, _uu = expand(_cc, _uu)
|
||||
_uu, _cc = expand(_uu, _cc)
|
||||
x.c_adm = self.c_adm
|
||||
conds_list = c.get('conds_list', [[(0, 1.0)]])
|
||||
image_cond = txt2img_image_conditioning(None, x)
|
||||
out = self.inner_model2(x, timestep, cond=(conds_list, _cc), uncond=_uu, cond_scale=cond_scale, s_min_uncond=self.s_min_uncond, image_cond=image_cond)
|
||||
return out
|
||||
|
||||
def txt2img_image_conditioning(sd_model, x, width=None, height=None):
|
||||
return x.new_zeros(x.shape[0], 5, 1, 1, dtype=x.dtype, device=x.device)
|
||||
|
||||
# =======================================================================================
|
||||
|
||||
def set_model_k(self: KSampler):
|
||||
self.model_denoise = CFGNoisePredictor(self.model) # main change
|
||||
if ((getattr(self.model, "parameterization", "") == "v") or
|
||||
(getattr(self.model, "model_type", -1) == model_base.ModelType.V_PREDICTION)):
|
||||
self.model_wrap = wrap_model(self.model_denoise, quantize=True)
|
||||
self.model_wrap.parameterization = getattr(self.model, "parameterization", "v")
|
||||
else:
|
||||
self.model_wrap = wrap_model(self.model_denoise, quantize=True)
|
||||
self.model_wrap.parameterization = getattr(self.model, "parameterization", "eps")
|
||||
self.model_k = KSamplerX0Inpaint(self.model_wrap)
|
||||
|
||||
class SDKSampler(comfy.samplers.KSampler):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super(SDKSampler, self).__init__(*args, **kwargs)
|
||||
set_model_k(self)
|
||||
@@ -1,140 +0,0 @@
|
||||
# https://github.com/shiimizu/ComfyUI_smZNodes
|
||||
import numpy as np
|
||||
|
||||
philox_m = [0xD2511F53, 0xCD9E8D57]
|
||||
philox_w = [0x9E3779B9, 0xBB67AE85]
|
||||
|
||||
two_pow32_inv = np.array([2.3283064e-10], dtype=np.float32)
|
||||
two_pow32_inv_2pi = np.array([2.3283064e-10 * 6.2831855], dtype=np.float32)
|
||||
|
||||
|
||||
def uint32(x):
|
||||
"""Converts (N,) np.uint64 array into (2, N) np.unit32 array."""
|
||||
return x.view(np.uint32).reshape(-1, 2).transpose(1, 0)
|
||||
|
||||
|
||||
def philox4_round(counter, key):
|
||||
"""A single round of the Philox 4x32 random number generator."""
|
||||
|
||||
v1 = uint32(counter[0].astype(np.uint64) * philox_m[0])
|
||||
v2 = uint32(counter[2].astype(np.uint64) * philox_m[1])
|
||||
|
||||
counter[0] = v2[1] ^ counter[1] ^ key[0]
|
||||
counter[1] = v2[0]
|
||||
counter[2] = v1[1] ^ counter[3] ^ key[1]
|
||||
counter[3] = v1[0]
|
||||
|
||||
|
||||
def philox4_32(counter, key, rounds=10):
|
||||
"""Generates 32-bit random numbers using the Philox 4x32 random number generator.
|
||||
|
||||
Parameters:
|
||||
counter (numpy.ndarray): A 4xN array of 32-bit integers representing the counter values (offset into generation).
|
||||
key (numpy.ndarray): A 2xN array of 32-bit integers representing the key values (seed).
|
||||
rounds (int): The number of rounds to perform.
|
||||
|
||||
Returns:
|
||||
numpy.ndarray: A 4xN array of 32-bit integers containing the generated random numbers.
|
||||
"""
|
||||
|
||||
for _ in range(rounds - 1):
|
||||
philox4_round(counter, key)
|
||||
|
||||
key[0] = key[0] + philox_w[0]
|
||||
key[1] = key[1] + philox_w[1]
|
||||
|
||||
philox4_round(counter, key)
|
||||
return counter
|
||||
|
||||
|
||||
def box_muller(x, y):
|
||||
"""Returns just the first out of two numbers generated by Box–Muller transform algorithm."""
|
||||
u = x * two_pow32_inv + two_pow32_inv / 2
|
||||
v = y * two_pow32_inv_2pi + two_pow32_inv_2pi / 2
|
||||
|
||||
s = np.sqrt(-2.0 * np.log(u))
|
||||
|
||||
r1 = s * np.sin(v)
|
||||
return r1.astype(np.float32)
|
||||
|
||||
|
||||
class Generator:
|
||||
"""RNG that produces same outputs as torch.randn(..., device='cuda') on CPU"""
|
||||
|
||||
def __init__(self, seed):
|
||||
self.seed = seed
|
||||
self.offset = 0
|
||||
|
||||
def randn(self, shape):
|
||||
"""Generate a sequence of n standard normal random variables using the Philox 4x32 random number generator and the Box-Muller transform."""
|
||||
|
||||
n = 1
|
||||
for x in shape:
|
||||
n *= x
|
||||
|
||||
counter = np.zeros((4, n), dtype=np.uint32)
|
||||
counter[0] = self.offset
|
||||
counter[2] = np.arange(n, dtype=np.uint32) # up to 2^32 numbers can be generated - if you want more you'd need to spill into counter[3]
|
||||
self.offset += 1
|
||||
|
||||
key = np.empty(n, dtype=np.uint64)
|
||||
key.fill(self.seed)
|
||||
key = uint32(key)
|
||||
|
||||
g = philox4_32(counter, key)
|
||||
|
||||
return box_muller(g[0], g[1]).reshape(shape) # discard g[2] and g[3]
|
||||
|
||||
#=======================================================================================================================
|
||||
# Monkey Patch "prepare_noise" function
|
||||
# https://github.com/shiimizu/ComfyUI_smZNodes
|
||||
import torch
|
||||
import functools
|
||||
from comfy.sample import np
|
||||
import comfy.model_management
|
||||
|
||||
def rng_rand_source(rand_source='cpu'):
|
||||
device = comfy.model_management.text_encoder_device()
|
||||
|
||||
def prepare_noise(latent_image, seed, noise_inds=None, device='cpu'):
|
||||
"""
|
||||
creates random noise given a latent image and a seed.
|
||||
optional arg skip can be used to skip and discard x number of noise generations for a given seed
|
||||
"""
|
||||
generator = torch.Generator(device).manual_seed(seed)
|
||||
if rand_source == 'nv':
|
||||
rng = Generator(seed)
|
||||
if noise_inds is None:
|
||||
shape = latent_image.size()
|
||||
if rand_source == 'nv':
|
||||
return torch.asarray(rng.randn(shape), device=device)
|
||||
else:
|
||||
return torch.randn(shape, dtype=latent_image.dtype, layout=latent_image.layout, generator=generator,
|
||||
device=device)
|
||||
|
||||
unique_inds, inverse = np.unique(noise_inds, return_inverse=True)
|
||||
noises = []
|
||||
for i in range(unique_inds[-1] + 1):
|
||||
shape = [1] + list(latent_image.size())[1:]
|
||||
if rand_source == 'nv':
|
||||
noise = torch.asarray(rng.randn(shape), device=device)
|
||||
else:
|
||||
noise = torch.randn(shape, dtype=latent_image.dtype, layout=latent_image.layout, generator=generator,
|
||||
device=device)
|
||||
if i in unique_inds:
|
||||
noises.append(noise)
|
||||
noises = [noises[i] for i in inverse]
|
||||
noises = torch.cat(noises, axis=0)
|
||||
return noises
|
||||
|
||||
if rand_source == 'cpu':
|
||||
if hasattr(comfy.sample, 'prepare_noise_orig'):
|
||||
comfy.sample.prepare_noise = comfy.sample.prepare_noise_orig
|
||||
else:
|
||||
if not hasattr(comfy.sample, 'prepare_noise_orig'):
|
||||
comfy.sample.prepare_noise_orig = comfy.sample.prepare_noise
|
||||
_prepare_noise = functools.partial(prepare_noise, device=device)
|
||||
comfy.sample.prepare_noise = _prepare_noise
|
||||
|
||||
|
||||
|
||||
@@ -1,321 +0,0 @@
|
||||
import torch
|
||||
#from .latent_resizer import LatentResizer
|
||||
from comfy import model_management
|
||||
import os
|
||||
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from einops import rearrange
|
||||
|
||||
def normalization(channels):
|
||||
return nn.GroupNorm(32, channels)
|
||||
|
||||
|
||||
def zero_module(module):
|
||||
for p in module.parameters():
|
||||
p.detach().zero_()
|
||||
return module
|
||||
|
||||
|
||||
class AttnBlock(nn.Module):
|
||||
def __init__(self, in_channels):
|
||||
super().__init__()
|
||||
self.in_channels = in_channels
|
||||
|
||||
self.norm = normalization(in_channels)
|
||||
self.q = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
|
||||
self.k = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
|
||||
self.v = nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
|
||||
self.proj_out = nn.Conv2d(
|
||||
in_channels, in_channels, kernel_size=1, stride=1, padding=0
|
||||
)
|
||||
|
||||
def attention(self, h_: torch.Tensor) -> torch.Tensor:
|
||||
h_ = self.norm(h_)
|
||||
q = self.q(h_)
|
||||
k = self.k(h_)
|
||||
v = self.v(h_)
|
||||
|
||||
b, c, h, w = q.shape
|
||||
q, k, v = map(
|
||||
lambda x: rearrange(x, "b c h w -> b 1 (h w) c").contiguous(), (q, k, v)
|
||||
)
|
||||
h_ = nn.functional.scaled_dot_product_attention(
|
||||
q, k, v
|
||||
) # scale is dim ** -0.5 per default
|
||||
|
||||
return rearrange(h_, "b 1 (h w) c -> b c h w", h=h, w=w, c=c, b=b)
|
||||
|
||||
def forward(self, x, **kwargs):
|
||||
h_ = x
|
||||
h_ = self.attention(h_)
|
||||
h_ = self.proj_out(h_)
|
||||
return x + h_
|
||||
|
||||
|
||||
def make_attn(in_channels, attn_kwargs=None):
|
||||
return AttnBlock(in_channels)
|
||||
|
||||
|
||||
class ResBlockEmb(nn.Module):
|
||||
def __init__(
|
||||
self,
|
||||
channels,
|
||||
emb_channels,
|
||||
dropout=0,
|
||||
out_channels=None,
|
||||
use_conv=False,
|
||||
use_scale_shift_norm=False,
|
||||
kernel_size=3,
|
||||
exchange_temb_dims=False,
|
||||
skip_t_emb=False,
|
||||
):
|
||||
super().__init__()
|
||||
self.channels = channels
|
||||
self.emb_channels = emb_channels
|
||||
self.dropout = dropout
|
||||
self.out_channels = out_channels or channels
|
||||
self.use_conv = use_conv
|
||||
self.use_scale_shift_norm = use_scale_shift_norm
|
||||
self.exchange_temb_dims = exchange_temb_dims
|
||||
|
||||
padding = kernel_size // 2
|
||||
|
||||
self.in_layers = nn.Sequential(
|
||||
normalization(channels),
|
||||
nn.SiLU(),
|
||||
nn.Conv2d(channels, self.out_channels, kernel_size, padding=padding),
|
||||
)
|
||||
|
||||
self.skip_t_emb = skip_t_emb
|
||||
self.emb_out_channels = (
|
||||
2 * self.out_channels if use_scale_shift_norm else self.out_channels
|
||||
)
|
||||
if self.skip_t_emb:
|
||||
print(f"Skipping timestep embedding in {self.__class__.__name__}")
|
||||
assert not self.use_scale_shift_norm
|
||||
self.emb_layers = None
|
||||
self.exchange_temb_dims = False
|
||||
else:
|
||||
self.emb_layers = nn.Sequential(
|
||||
nn.SiLU(),
|
||||
nn.Linear(
|
||||
emb_channels,
|
||||
self.emb_out_channels,
|
||||
),
|
||||
)
|
||||
|
||||
self.out_layers = nn.Sequential(
|
||||
normalization(self.out_channels),
|
||||
nn.SiLU(),
|
||||
nn.Dropout(p=dropout),
|
||||
zero_module(
|
||||
nn.Conv2d(
|
||||
self.out_channels,
|
||||
self.out_channels,
|
||||
kernel_size,
|
||||
padding=padding,
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
if self.out_channels == channels:
|
||||
self.skip_connection = nn.Identity()
|
||||
elif use_conv:
|
||||
self.skip_connection = nn.Conv2d(
|
||||
channels, self.out_channels, kernel_size, padding=padding
|
||||
)
|
||||
else:
|
||||
self.skip_connection = nn.Conv2d(channels, self.out_channels, 1)
|
||||
|
||||
def forward(self, x, emb):
|
||||
h = self.in_layers(x)
|
||||
|
||||
if self.skip_t_emb:
|
||||
emb_out = torch.zeros_like(h)
|
||||
else:
|
||||
emb_out = self.emb_layers(emb).type(h.dtype)
|
||||
while len(emb_out.shape) < len(h.shape):
|
||||
emb_out = emb_out[..., None]
|
||||
if self.use_scale_shift_norm:
|
||||
out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
|
||||
scale, shift = torch.chunk(emb_out, 2, dim=1)
|
||||
h = out_norm(h) * (1 + scale) + shift
|
||||
h = out_rest(h)
|
||||
else:
|
||||
if self.exchange_temb_dims:
|
||||
emb_out = rearrange(emb_out, "b t c ... -> b c t ...")
|
||||
h = h + emb_out
|
||||
h = self.out_layers(h)
|
||||
return self.skip_connection(x) + h
|
||||
|
||||
|
||||
class LatentResizer(nn.Module):
|
||||
def __init__(self, in_blocks=10, out_blocks=10, channels=128, dropout=0, attn=True):
|
||||
super().__init__()
|
||||
self.conv_in = nn.Conv2d(4, channels, 3, padding=1)
|
||||
|
||||
self.channels = channels
|
||||
embed_dim = 32
|
||||
self.embed = nn.Sequential(
|
||||
nn.Linear(1, embed_dim),
|
||||
nn.SiLU(),
|
||||
nn.Linear(embed_dim, embed_dim),
|
||||
)
|
||||
|
||||
self.in_blocks = nn.ModuleList([])
|
||||
for b in range(in_blocks):
|
||||
if (b == 1 or b == in_blocks - 1) and attn:
|
||||
self.in_blocks.append(make_attn(channels))
|
||||
self.in_blocks.append(ResBlockEmb(channels, embed_dim, dropout))
|
||||
|
||||
self.out_blocks = nn.ModuleList([])
|
||||
for b in range(out_blocks):
|
||||
if (b == 1 or b == out_blocks - 1) and attn:
|
||||
self.out_blocks.append(make_attn(channels))
|
||||
self.out_blocks.append(ResBlockEmb(channels, embed_dim, dropout))
|
||||
|
||||
self.norm_out = normalization(channels)
|
||||
self.conv_out = nn.Conv2d(channels, 4, 3, padding=1)
|
||||
|
||||
@classmethod
|
||||
def load_model(cls, filename, device="cpu", dtype=torch.float32, dropout=0):
|
||||
if not 'weights_only' in torch.load.__code__.co_varnames:
|
||||
weights = torch.load(filename, map_location=torch.device("cpu"))
|
||||
else:
|
||||
weights = torch.load(filename, map_location=torch.device("cpu"), weights_only=True)
|
||||
in_blocks = 0
|
||||
out_blocks = 0
|
||||
in_tfs = 0
|
||||
out_tfs = 0
|
||||
channels = weights["conv_in.bias"].shape[0]
|
||||
for k in weights.keys():
|
||||
k = k.split(".")
|
||||
if k[0] == "in_blocks":
|
||||
in_blocks = max(in_blocks, int(k[1]))
|
||||
if k[2] == "q" and k[3] == "weight":
|
||||
in_tfs += 1
|
||||
if k[0] == "out_blocks":
|
||||
out_blocks = max(out_blocks, int(k[1]))
|
||||
if k[2] == "q" and k[3] == "weight":
|
||||
out_tfs += 1
|
||||
in_blocks = in_blocks + 1 - in_tfs
|
||||
out_blocks = out_blocks + 1 - out_tfs
|
||||
resizer = cls(
|
||||
in_blocks=in_blocks,
|
||||
out_blocks=out_blocks,
|
||||
channels=channels,
|
||||
dropout=dropout,
|
||||
attn=(out_tfs != 0),
|
||||
)
|
||||
resizer.load_state_dict(weights)
|
||||
resizer.eval()
|
||||
resizer.to(device, dtype=dtype)
|
||||
return resizer
|
||||
|
||||
def forward(self, x, scale=None, size=None):
|
||||
if scale is None and size is None:
|
||||
raise ValueError("Either scale or size needs to be not None")
|
||||
if scale is not None and size is not None:
|
||||
raise ValueError("Both scale or size can't be not None")
|
||||
if scale is not None:
|
||||
size = (x.shape[-2] * scale, x.shape[-1] * scale)
|
||||
size = tuple([int(round(i)) for i in size])
|
||||
else:
|
||||
scale = size[-1] / x.shape[-1]
|
||||
|
||||
# Output is the same size as input
|
||||
if size == x.shape[-2:]:
|
||||
return x
|
||||
|
||||
scale = torch.tensor([scale - 1], dtype=x.dtype).to(x.device).unsqueeze(0)
|
||||
emb = self.embed(scale)
|
||||
|
||||
x = self.conv_in(x)
|
||||
|
||||
for b in self.in_blocks:
|
||||
if isinstance(b, ResBlockEmb):
|
||||
x = b(x, emb)
|
||||
else:
|
||||
x = b(x)
|
||||
x = F.interpolate(x, size=size, mode="bilinear")
|
||||
for b in self.out_blocks:
|
||||
if isinstance(b, ResBlockEmb):
|
||||
x = b(x, emb)
|
||||
else:
|
||||
x = b(x)
|
||||
|
||||
x = self.norm_out(x)
|
||||
x = F.silu(x)
|
||||
x = self.conv_out(x)
|
||||
return x
|
||||
|
||||
########################################################
|
||||
class NNLatentUpscale:
|
||||
"""
|
||||
Upscales SDXL latent using neural network
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self.local_dir = os.path.dirname(os.path.realpath(__file__))
|
||||
self.scale_factor = 0.13025
|
||||
self.dtype = torch.float32
|
||||
if model_management.should_use_fp16():
|
||||
self.dtype = torch.float16
|
||||
self.weight_path = {
|
||||
"SDXL": os.path.join(self.local_dir, "sdxl_resizer.pt"),
|
||||
"SD 1.x": os.path.join(self.local_dir, "sd15_resizer.pt"),
|
||||
}
|
||||
self.version = "none"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"latent": ("LATENT",),
|
||||
"version": (["SDXL", "SD 1.x"],),
|
||||
"upscale": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 1.5,
|
||||
"min": 1.0,
|
||||
"max": 2.0,
|
||||
"step": 0.01,
|
||||
"display": "number",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
|
||||
FUNCTION = "upscale"
|
||||
|
||||
CATEGORY = "latent"
|
||||
|
||||
def upscale(self, latent, version, upscale):
|
||||
device = model_management.get_torch_device()
|
||||
samples = latent["samples"].to(device=device, dtype=self.dtype)
|
||||
|
||||
if version != self.version:
|
||||
self.model = LatentResizer.load_model(self.weight_path[version], device, self.dtype)
|
||||
self.version = version
|
||||
|
||||
self.model.to(device=device)
|
||||
latent_out = (self.model(self.scale_factor * samples, scale=upscale) / self.scale_factor)
|
||||
|
||||
if self.dtype != torch.float32:
|
||||
latent_out = latent_out.to(dtype=torch.float32)
|
||||
|
||||
latent_out = latent_out.to(device="cpu")
|
||||
|
||||
self.model.to(device=model_management.vae_offload_device())
|
||||
return ({"samples": latent_out},)
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"NNLatentUpscale": NNLatentUpscale
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"NNlLatentUpscale": "EFF Latent Upscale"
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
clip-interrogator
|
||||
simpleeval
|
||||
@@ -1,555 +0,0 @@
|
||||
# Efficiency Nodes Utility functions
|
||||
from torch import Tensor
|
||||
import torch
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
import os
|
||||
import sys
|
||||
import io
|
||||
from contextlib import contextmanager
|
||||
import json
|
||||
import folder_paths
|
||||
|
||||
# Get the absolute path of the parent directory of the current script
|
||||
my_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
# Add the My directory path to the sys.path list
|
||||
sys.path.append(my_dir)
|
||||
|
||||
# Construct the absolute path to the ComfyUI directory
|
||||
comfy_dir = os.path.abspath(os.path.join(my_dir, '..', '..'))
|
||||
|
||||
# Add the ComfyUI directory path to the sys.path list
|
||||
sys.path.append(comfy_dir)
|
||||
|
||||
# Import functions from ComfyUI
|
||||
import comfy.sd
|
||||
import comfy.utils
|
||||
import latent_preview
|
||||
from comfy.cli_args import args
|
||||
|
||||
# Cache for Efficiency Node models
|
||||
loaded_objects = {
|
||||
"ckpt": [], # (ckpt_name, ckpt_model, clip, bvae, [id])
|
||||
"refn": [], # (ckpt_name, ckpt_model, clip, bvae, [id])
|
||||
"vae": [], # (vae_name, vae, [id])
|
||||
"lora": [] # ([(lora_name, strength_model, strength_clip)], ckpt_name, lora_model, clip_lora, [id])
|
||||
}
|
||||
|
||||
# Cache for Efficient Ksamplers
|
||||
last_helds = {
|
||||
"latent": [], # (latent, [parameters], id) # Base sampling latent results
|
||||
"image": [], # (image, id) # Base sampling image results
|
||||
"cnet_img": [] # (cnet_img, [parameters], id) # HiRes-Fix control net preprocessor image results
|
||||
}
|
||||
|
||||
def load_ksampler_results(key: str, my_unique_id, parameters_list=None):
|
||||
global last_helds
|
||||
for data in last_helds[key]:
|
||||
id_ = data[-1] # ID is always the last element in the tuple
|
||||
if id_ == my_unique_id:
|
||||
if parameters_list is not None:
|
||||
# Ensure tuple has at least 3 elements and match with parameters_list
|
||||
if len(data) >= 3 and data[1] == parameters_list:
|
||||
return data[0]
|
||||
else:
|
||||
return data[0]
|
||||
return None
|
||||
|
||||
def store_ksampler_results(key: str, my_unique_id, value, parameters_list=None):
|
||||
global last_helds
|
||||
|
||||
for i, data in enumerate(last_helds[key]):
|
||||
id_ = data[-1] # ID will always be the last in the tuple
|
||||
if id_ == my_unique_id:
|
||||
# Check if parameters_list is provided or not
|
||||
updated_data = (value, parameters_list, id_) if parameters_list is not None else (value, id_)
|
||||
last_helds[key][i] = updated_data
|
||||
return True
|
||||
|
||||
# If parameters_list is given
|
||||
if parameters_list is not None:
|
||||
last_helds[key].append((value, parameters_list, my_unique_id))
|
||||
else:
|
||||
last_helds[key].append((value, my_unique_id))
|
||||
return True
|
||||
|
||||
# Tensor to PIL (grabbed from WAS Suite)
|
||||
def tensor2pil(image: torch.Tensor) -> Image.Image:
|
||||
return Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8))
|
||||
|
||||
# Convert PIL to Tensor (grabbed from WAS Suite)
|
||||
def pil2tensor(image: Image.Image) -> torch.Tensor:
|
||||
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
|
||||
|
||||
# Convert tensor to PIL, resize it, and convert back to tensor
|
||||
def quick_resize(source_tensor: torch.Tensor, target_shape: tuple) -> torch.Tensor:
|
||||
resized_images = []
|
||||
for img in source_tensor:
|
||||
resized_pil = tensor2pil(img.squeeze(0)).resize((target_shape[2], target_shape[1]), Image.ANTIALIAS)
|
||||
resized_images.append(pil2tensor(resized_pil).squeeze(0))
|
||||
return torch.stack(resized_images, dim=0)
|
||||
|
||||
# Create a function to compute the hash of a tensor
|
||||
import hashlib
|
||||
def tensor_to_hash(tensor):
|
||||
byte_repr = tensor.cpu().numpy().tobytes() # Convert tensor to bytes
|
||||
return hashlib.sha256(byte_repr).hexdigest() # Compute hash
|
||||
|
||||
# Color coded messages functions
|
||||
MESSAGE_COLOR = "\033[36m" # Cyan
|
||||
XYPLOT_COLOR = "\033[35m" # Purple
|
||||
SUCCESS_COLOR = "\033[92m" # Green
|
||||
WARNING_COLOR = "\033[93m" # Yellow
|
||||
ERROR_COLOR = "\033[91m" # Red
|
||||
INFO_COLOR = "\033[90m" # Gray
|
||||
def format_message(text, color_code):
|
||||
RESET_COLOR = "\033[0m"
|
||||
return f"{color_code}{text}{RESET_COLOR}"
|
||||
def message(text):
|
||||
return format_message(text, MESSAGE_COLOR)
|
||||
def warning(text):
|
||||
return format_message(text, WARNING_COLOR)
|
||||
def error(text):
|
||||
return format_message(text, ERROR_COLOR)
|
||||
def success(text):
|
||||
return format_message(text, SUCCESS_COLOR)
|
||||
def xyplot_message(text):
|
||||
return format_message(text, XYPLOT_COLOR)
|
||||
def info(text):
|
||||
return format_message(text, INFO_COLOR)
|
||||
|
||||
def extract_node_info(prompt, id, indirect_key=None):
|
||||
# Convert ID to string
|
||||
id = str(id)
|
||||
node_id = None
|
||||
|
||||
# If an indirect_key (like 'script') is provided, perform a two-step lookup
|
||||
if indirect_key:
|
||||
# Ensure the id exists in the prompt and has an 'inputs' entry with the indirect_key
|
||||
if id in prompt and 'inputs' in prompt[id] and indirect_key in prompt[id]['inputs']:
|
||||
# Extract the indirect_id
|
||||
indirect_id = prompt[id]['inputs'][indirect_key][0]
|
||||
|
||||
# Ensure the indirect_id exists in the prompt
|
||||
if indirect_id in prompt:
|
||||
node_id = indirect_id
|
||||
return prompt[indirect_id].get('class_type', None), node_id
|
||||
|
||||
# If indirect_key is not found within the prompt
|
||||
return None, None
|
||||
|
||||
# If no indirect_key is provided, perform a direct lookup
|
||||
return prompt.get(id, {}).get('class_type', None), node_id
|
||||
|
||||
def extract_node_value(prompt, id, key):
|
||||
# If ID is in data, return its 'inputs' value for a given key. Otherwise, return None.
|
||||
return prompt.get(str(id), {}).get('inputs', {}).get(key, None)
|
||||
|
||||
def print_loaded_objects_entries(id=None, prompt=None, show_id=False):
|
||||
print("-" * 40) # Print an empty line followed by a separator line
|
||||
if id is not None:
|
||||
id = str(id) # Convert ID to string
|
||||
if prompt is not None and id is not None:
|
||||
node_name, _ = extract_node_info(prompt, id)
|
||||
if show_id:
|
||||
print(f"\033[36m{node_name} Models Cache: (node_id:{int(id)})\033[0m")
|
||||
else:
|
||||
print(f"\033[36m{node_name} Models Cache:\033[0m")
|
||||
elif id is None:
|
||||
print(f"\033[36mGlobal Models Cache:\033[0m")
|
||||
else:
|
||||
print(f"\033[36mModels Cache: \nnode_id:{int(id)}\033[0m")
|
||||
entries_found = False
|
||||
for key in ["ckpt", "refn", "vae", "lora"]:
|
||||
entries_with_id = loaded_objects[key] if id is None else [entry for entry in loaded_objects[key] if id in entry[-1]]
|
||||
if not entries_with_id: # If no entries with the chosen ID, print None and skip this key
|
||||
continue
|
||||
entries_found = True
|
||||
print(f"{key.capitalize()}:")
|
||||
for i, entry in enumerate(entries_with_id, 1): # Start numbering from 1
|
||||
if key == "lora":
|
||||
base_ckpt_name = os.path.splitext(os.path.basename(entry[1]))[0] # Split logic for base_ckpt
|
||||
if id is None:
|
||||
associated_ids = ', '.join(map(str, entry[-1])) # Gather all associated ids
|
||||
print(f" [{i}] base_ckpt: {base_ckpt_name} (ids: {associated_ids})")
|
||||
else:
|
||||
print(f" [{i}] base_ckpt: {base_ckpt_name}")
|
||||
for name, strength_model, strength_clip in entry[0]:
|
||||
lora_model_info = f"{os.path.splitext(os.path.basename(name))[0]}({round(strength_model, 2)},{round(strength_clip, 2)})"
|
||||
print(f" lora(mod,clip): {lora_model_info}")
|
||||
else:
|
||||
name_without_ext = os.path.splitext(os.path.basename(entry[0]))[0]
|
||||
if id is None:
|
||||
associated_ids = ', '.join(map(str, entry[-1])) # Gather all associated ids
|
||||
print(f" [{i}] {name_without_ext} (ids: {associated_ids})")
|
||||
else:
|
||||
print(f" [{i}] {name_without_ext}")
|
||||
if not entries_found:
|
||||
print("-")
|
||||
|
||||
# This function cleans global variables associated with nodes that are no longer detected on UI
|
||||
def globals_cleanup(prompt):
|
||||
global loaded_objects
|
||||
global last_helds
|
||||
|
||||
# Step 1: Clean up last_helds
|
||||
for key in list(last_helds.keys()):
|
||||
original_length = len(last_helds[key])
|
||||
last_helds[key] = [
|
||||
(*values, id_)
|
||||
for *values, id_ in last_helds[key]
|
||||
if str(id_) in prompt.keys()
|
||||
]
|
||||
|
||||
# Step 2: Clean up loaded_objects
|
||||
for key in list(loaded_objects.keys()):
|
||||
for i, tup in enumerate(list(loaded_objects[key])):
|
||||
# Remove ids from id array in each tuple that don't exist in prompt
|
||||
id_array = [id for id in tup[-1] if str(id) in prompt.keys()]
|
||||
if len(id_array) != len(tup[-1]):
|
||||
if id_array:
|
||||
loaded_objects[key][i] = tup[:-1] + (id_array,)
|
||||
###print(f'Updated tuple at index {i} in {key} in loaded_objects: {loaded_objects[key][i]}')
|
||||
else:
|
||||
# If id array becomes empty, delete the corresponding tuple
|
||||
loaded_objects[key].remove(tup)
|
||||
###print(f'Deleted tuple at index {i} in {key} in loaded_objects because its id array became empty.')
|
||||
|
||||
def load_checkpoint(ckpt_name, id, output_vae=True, cache=None, cache_overwrite=True, ckpt_type="ckpt"):
|
||||
global loaded_objects
|
||||
|
||||
# Create copies of the arguments right at the start
|
||||
ckpt_name = ckpt_name.copy() if isinstance(ckpt_name, (list, dict, set)) else ckpt_name
|
||||
|
||||
# Check if the type is valid
|
||||
if ckpt_type not in ["ckpt", "refn"]:
|
||||
raise ValueError(f"Invalid checkpoint type: {ckpt_type}")
|
||||
|
||||
for entry in loaded_objects[ckpt_type]:
|
||||
if entry[0] == ckpt_name:
|
||||
_, model, clip, vae, ids = entry
|
||||
cache_full = cache and len([entry for entry in loaded_objects[ckpt_type] if id in entry[-1]]) >= cache
|
||||
|
||||
if cache_full:
|
||||
clear_cache(id, cache, ckpt_type)
|
||||
elif id not in ids:
|
||||
ids.append(id)
|
||||
|
||||
return model, clip, vae
|
||||
|
||||
if os.path.isabs(ckpt_name):
|
||||
ckpt_path = ckpt_name
|
||||
else:
|
||||
ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
|
||||
with suppress_output():
|
||||
out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
|
||||
|
||||
model = out[0]
|
||||
clip = out[1]
|
||||
vae = out[2] if output_vae else None # Load VAE from the checkpoint path only if output_vae is True
|
||||
|
||||
if cache:
|
||||
cache_list = [entry for entry in loaded_objects[ckpt_type] if id in entry[-1]]
|
||||
if len(cache_list) < cache:
|
||||
loaded_objects[ckpt_type].append((ckpt_name, model, clip, vae, [id]))
|
||||
else:
|
||||
clear_cache(id, cache, ckpt_type)
|
||||
if cache_overwrite:
|
||||
for e in loaded_objects[ckpt_type]:
|
||||
if id in e[-1]:
|
||||
e[-1].remove(id)
|
||||
# If the id list becomes empty, remove the entry from the ckpt_type list
|
||||
if not e[-1]:
|
||||
loaded_objects[ckpt_type].remove(e)
|
||||
break
|
||||
loaded_objects[ckpt_type].append((ckpt_name, model, clip, vae, [id]))
|
||||
|
||||
return model, clip, vae
|
||||
|
||||
def get_bvae_by_ckpt_name(ckpt_name):
|
||||
for ckpt in loaded_objects["ckpt"]:
|
||||
if ckpt[0] == ckpt_name:
|
||||
return ckpt[3] # return 'bvae' variable
|
||||
return None # return None if no match is found
|
||||
|
||||
def load_vae(vae_name, id, cache=None, cache_overwrite=False):
|
||||
global loaded_objects
|
||||
|
||||
# Create copies of the argument right at the start
|
||||
vae_name = vae_name.copy() if isinstance(vae_name, (list, dict, set)) else vae_name
|
||||
|
||||
for i, entry in enumerate(loaded_objects["vae"]):
|
||||
if entry[0] == vae_name:
|
||||
vae, ids = entry[1], entry[2]
|
||||
if id not in ids:
|
||||
if cache and len([entry for entry in loaded_objects["vae"] if id in entry[-1]]) >= cache:
|
||||
return vae
|
||||
ids.append(id)
|
||||
if cache:
|
||||
clear_cache(id, cache, "vae")
|
||||
return vae
|
||||
|
||||
if os.path.isabs(vae_name):
|
||||
vae_path = vae_name
|
||||
else:
|
||||
vae_path = folder_paths.get_full_path("vae", vae_name)
|
||||
|
||||
sd = comfy.utils.load_torch_file(vae_path)
|
||||
vae = comfy.sd.VAE(sd=sd)
|
||||
|
||||
if cache:
|
||||
if len([entry for entry in loaded_objects["vae"] if id in entry[-1]]) < cache:
|
||||
loaded_objects["vae"].append((vae_name, vae, [id]))
|
||||
else:
|
||||
clear_cache(id, cache, "vae")
|
||||
if cache_overwrite:
|
||||
# Find the first entry with the id, remove the id from the entry's id list
|
||||
for e in loaded_objects["vae"]:
|
||||
if id in e[-1]:
|
||||
e[-1].remove(id)
|
||||
# If the id list becomes empty, remove the entry from the "vae" list
|
||||
if not e[-1]:
|
||||
loaded_objects["vae"].remove(e)
|
||||
break
|
||||
loaded_objects["vae"].append((vae_name, vae, [id]))
|
||||
|
||||
return vae
|
||||
|
||||
def load_lora(lora_params, ckpt_name, id, cache=None, ckpt_cache=None, cache_overwrite=False):
|
||||
global loaded_objects
|
||||
|
||||
# Create copies of the arguments right at the start
|
||||
lora_params = lora_params.copy() if isinstance(lora_params, (list, dict, set)) else lora_params
|
||||
ckpt_name = ckpt_name.copy() if isinstance(ckpt_name, (list, dict, set)) else ckpt_name
|
||||
|
||||
for entry in loaded_objects["lora"]:
|
||||
|
||||
# Convert to sets and compare
|
||||
if set(entry[0]) == set(lora_params) and entry[1] == ckpt_name:
|
||||
|
||||
_, _, lora_model, lora_clip, ids = entry
|
||||
cache_full = cache and len([entry for entry in loaded_objects["lora"] if id in entry[-1]]) >= cache
|
||||
|
||||
if cache_full:
|
||||
clear_cache(id, cache, "lora")
|
||||
elif id not in ids:
|
||||
ids.append(id)
|
||||
|
||||
# Additional cache handling for 'ckpt' just like in 'load_checkpoint' function
|
||||
for ckpt_entry in loaded_objects["ckpt"]:
|
||||
if ckpt_entry[0] == ckpt_name:
|
||||
_, _, _, _, ckpt_ids = ckpt_entry
|
||||
ckpt_cache_full = ckpt_cache and len(
|
||||
[ckpt_entry for ckpt_entry in loaded_objects["ckpt"] if id in ckpt_entry[-1]]) >= ckpt_cache
|
||||
|
||||
if ckpt_cache_full:
|
||||
clear_cache(id, ckpt_cache, "ckpt")
|
||||
elif id not in ckpt_ids:
|
||||
ckpt_ids.append(id)
|
||||
|
||||
return lora_model, lora_clip
|
||||
|
||||
def recursive_load_lora(lora_params, ckpt, clip, id, ckpt_cache, cache_overwrite, folder_paths):
|
||||
if len(lora_params) == 0:
|
||||
return ckpt, clip
|
||||
|
||||
lora_name, strength_model, strength_clip = lora_params[0]
|
||||
if os.path.isabs(lora_name):
|
||||
lora_path = lora_name
|
||||
else:
|
||||
lora_path = folder_paths.get_full_path("loras", lora_name)
|
||||
|
||||
lora_model, lora_clip = comfy.sd.load_lora_for_models(ckpt, clip, comfy.utils.load_torch_file(lora_path), strength_model, strength_clip)
|
||||
|
||||
# Call the function again with the new lora_model and lora_clip and the remaining tuples
|
||||
return recursive_load_lora(lora_params[1:], lora_model, lora_clip, id, ckpt_cache, cache_overwrite, folder_paths)
|
||||
|
||||
# Unpack lora parameters from the first element of the list for now
|
||||
lora_name, strength_model, strength_clip = lora_params[0]
|
||||
ckpt, clip, _ = load_checkpoint(ckpt_name, id, cache=ckpt_cache)
|
||||
|
||||
lora_model, lora_clip = recursive_load_lora(lora_params, ckpt, clip, id, ckpt_cache, cache_overwrite, folder_paths)
|
||||
|
||||
if cache:
|
||||
if len([entry for entry in loaded_objects["lora"] if id in entry[-1]]) < cache:
|
||||
loaded_objects["lora"].append((lora_params, ckpt_name, lora_model, lora_clip, [id]))
|
||||
else:
|
||||
clear_cache(id, cache, "lora")
|
||||
if cache_overwrite:
|
||||
# Find the first entry with the id, remove the id from the entry's id list
|
||||
for e in loaded_objects["lora"]:
|
||||
if id in e[-1]:
|
||||
e[-1].remove(id)
|
||||
# If the id list becomes empty, remove the entry from the "lora" list
|
||||
if not e[-1]:
|
||||
loaded_objects["lora"].remove(e)
|
||||
break
|
||||
loaded_objects["lora"].append((lora_params, ckpt_name, lora_model, lora_clip, [id]))
|
||||
|
||||
return lora_model, lora_clip
|
||||
|
||||
def clear_cache(id, cache, dict_name):
|
||||
"""
|
||||
Clear the cache for a specific id in a specific dictionary.
|
||||
If the cache limit is reached for a specific id, deletes the id from the oldest entry.
|
||||
If the id array of the entry becomes empty, deletes the entry.
|
||||
"""
|
||||
# Get all entries associated with the id_element
|
||||
id_associated_entries = [entry for entry in loaded_objects[dict_name] if id in entry[-1]]
|
||||
while len(id_associated_entries) > cache:
|
||||
# Identify an older entry (but not necessarily the oldest) containing id
|
||||
older_entry = id_associated_entries[0]
|
||||
# Remove the id_element from the older entry
|
||||
older_entry[-1].remove(id)
|
||||
# If the id array of the older entry becomes empty after this, delete the entry
|
||||
if not older_entry[-1]:
|
||||
loaded_objects[dict_name].remove(older_entry)
|
||||
# Update the id_associated_entries
|
||||
id_associated_entries = [entry for entry in loaded_objects[dict_name] if id in entry[-1]]
|
||||
|
||||
|
||||
def clear_cache_by_exception(node_id, vae_dict=None, ckpt_dict=None, lora_dict=None, refn_dict=None):
|
||||
global loaded_objects
|
||||
|
||||
dict_mapping = {
|
||||
"vae_dict": "vae",
|
||||
"ckpt_dict": "ckpt",
|
||||
"lora_dict": "lora",
|
||||
"refn_dict": "refn"
|
||||
}
|
||||
|
||||
for arg_name, arg_val in {"vae_dict": vae_dict, "ckpt_dict": ckpt_dict, "lora_dict": lora_dict, "refn_dict": refn_dict}.items():
|
||||
if arg_val is None:
|
||||
continue
|
||||
|
||||
dict_name = dict_mapping[arg_name]
|
||||
|
||||
for tuple_idx, tuple_item in enumerate(loaded_objects[dict_name].copy()):
|
||||
if arg_name == "lora_dict":
|
||||
# Iterate over the tuples (lora_params, ckpt_name) in arg_val
|
||||
for lora_params, ckpt_name in arg_val:
|
||||
# Compare lists of tuples considering order inside tuples, but not order of tuples
|
||||
if set(lora_params) == set(tuple_item[0]) and ckpt_name == tuple_item[1]:
|
||||
break
|
||||
else: # If no match was found in lora_dict, remove the tuple from loaded_objects
|
||||
if node_id in tuple_item[-1]:
|
||||
tuple_item[-1].remove(node_id)
|
||||
if not tuple_item[-1]:
|
||||
loaded_objects[dict_name].remove(tuple_item)
|
||||
continue
|
||||
elif tuple_item[0] not in arg_val: # Only remove the tuple if it's not in arg_val
|
||||
if node_id in tuple_item[-1]:
|
||||
tuple_item[-1].remove(node_id)
|
||||
if not tuple_item[-1]:
|
||||
loaded_objects[dict_name].remove(tuple_item)
|
||||
|
||||
# Retrieve the cache number from 'node_settings' json file
|
||||
def get_cache_numbers(node_name):
|
||||
# Get the directory path of the current file
|
||||
my_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
# Construct the file path for node_settings.json
|
||||
settings_file = os.path.join(my_dir, 'node_settings.json')
|
||||
# Load the settings from the JSON file
|
||||
with open(settings_file, 'r') as file:
|
||||
node_settings = json.load(file)
|
||||
# Retrieve the cache numbers for the given node
|
||||
model_cache_settings = node_settings.get(node_name, {}).get('model_cache', {})
|
||||
vae_cache = int(model_cache_settings.get('vae', 1))
|
||||
ckpt_cache = int(model_cache_settings.get('ckpt', 1))
|
||||
lora_cache = int(model_cache_settings.get('lora', 1))
|
||||
refn_cache = int(model_cache_settings.get('ckpt', 1))
|
||||
return vae_cache, ckpt_cache, lora_cache, refn_cache,
|
||||
|
||||
def print_last_helds(id=None):
|
||||
print("\n" + "-" * 40) # Print an empty line followed by a separator line
|
||||
if id is not None:
|
||||
id = str(id) # Convert ID to string
|
||||
print(f"Node-specific Last Helds (node_id:{int(id)})")
|
||||
else:
|
||||
print(f"Global Last Helds:")
|
||||
for key in ["preview_images", "latent", "output_images", "vae_decode"]:
|
||||
entries_with_id = last_helds[key] if id is None else [entry for entry in last_helds[key] if id == entry[-1]]
|
||||
if not entries_with_id: # If no entries with the chosen ID, print None and skip this key
|
||||
continue
|
||||
print(f"{key.capitalize()}:")
|
||||
for i, entry in enumerate(entries_with_id, 1): # Start numbering from 1
|
||||
if isinstance(entry[0], bool): # Special handling for boolean types
|
||||
output = entry[0]
|
||||
else:
|
||||
output = len(entry[0])
|
||||
if id is None:
|
||||
print(f" [{i}] Output: {output} (id: {entry[-1]})")
|
||||
else:
|
||||
print(f" [{i}] Output: {output}")
|
||||
print("-" * 40) # Print a separator line
|
||||
print("\n") # Print an empty line
|
||||
|
||||
# For suppressing print outputs from functions
|
||||
@contextmanager
|
||||
def suppress_output():
|
||||
original_stdout = sys.stdout
|
||||
original_stderr = sys.stderr
|
||||
|
||||
sys.stdout = io.StringIO()
|
||||
sys.stderr = io.StringIO()
|
||||
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
sys.stdout = original_stdout
|
||||
sys.stderr = original_stderr
|
||||
|
||||
# Set global preview_method
|
||||
def set_preview_method(method):
|
||||
if method == 'auto' or method == 'LatentPreviewMethod.Auto':
|
||||
args.preview_method = latent_preview.LatentPreviewMethod.Auto
|
||||
elif method == 'latent2rgb' or method == 'LatentPreviewMethod.Latent2RGB':
|
||||
args.preview_method = latent_preview.LatentPreviewMethod.Latent2RGB
|
||||
elif method == 'taesd' or method == 'LatentPreviewMethod.TAESD':
|
||||
args.preview_method = latent_preview.LatentPreviewMethod.TAESD
|
||||
else:
|
||||
args.preview_method = latent_preview.LatentPreviewMethod.NoPreviews
|
||||
|
||||
# Extract global preview_method
|
||||
def global_preview_method():
|
||||
return args.preview_method
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------------------------
|
||||
# Delete efficiency nodes web extensions from 'ComfyUI\web\extensions'.
|
||||
# Pull https://github.com/comfyanonymous/ComfyUI/pull/1273 now allows defining web extensions through a dir path in init
|
||||
import shutil
|
||||
|
||||
# Destination directory
|
||||
destination_dir = os.path.join(comfy_dir, 'web', 'extensions', 'efficiency-nodes-comfyui')
|
||||
|
||||
# Check if the directory exists and delete it
|
||||
if os.path.exists(destination_dir):
|
||||
shutil.rmtree(destination_dir)
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------------------------
|
||||
# Other
|
||||
class XY_Capsule:
|
||||
def pre_define_model(self, model, clip, vae):
|
||||
return model, clip, vae
|
||||
|
||||
def set_result(self, image, latent):
|
||||
pass
|
||||
|
||||
def get_result(self, model, clip, vae):
|
||||
return None
|
||||
|
||||
def set_x_capsule(self, capsule):
|
||||
return None
|
||||
|
||||
def getLabel(self):
|
||||
return "Unknown"
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 6.3 MiB |
|
Before Width: | Height: | Size: 529 KiB |
|
Before Width: | Height: | Size: 1.4 MiB |
|
Before Width: | Height: | Size: 306 KiB |
|
Before Width: | Height: | Size: 5.8 MiB |
|
Before Width: | Height: | Size: 1022 KiB |