HEL-892: add source-bound VOSR2 image reference documentation
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -0,0 +1 @@
|
||||
{"ref":"refs/tags/v0.35.1","node_id":"REF_kwDOIygeJrFyZWZzL3RhZ3MvdjAuMzUuMQ","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/refs/tags/v0.35.1","object":{"sha":"856a922befab9d94cb66f36a3dce17234d7a6e31","type":"commit","url":"https://api.github.com/repos/Comfy-Org/ComfyUI/git/commits/856a922befab9d94cb66f36a3dce17234d7a6e31"}}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,589 @@
|
||||
import os
|
||||
import time
|
||||
import mimetypes
|
||||
import logging
|
||||
from typing import Literal, List
|
||||
from collections.abc import Collection
|
||||
|
||||
from comfy.cli_args import args
|
||||
|
||||
supported_pt_extensions: set[str] = {'.ckpt', '.pt', '.pt2', '.bin', '.pth', '.safetensors', '.pkl', '.sft'}
|
||||
|
||||
folder_names_and_paths: dict[str, tuple[list[str], set[str]]] = {}
|
||||
|
||||
# --base-directory - Resets all default paths configured in folder_paths with a new base path
|
||||
if args.base_directory:
|
||||
base_path = os.path.abspath(args.base_directory)
|
||||
else:
|
||||
base_path = os.path.dirname(os.path.realpath(__file__))
|
||||
|
||||
if args.models_directory:
|
||||
models_dir = os.path.abspath(args.models_directory)
|
||||
else:
|
||||
models_dir = os.path.join(base_path, "models")
|
||||
|
||||
folder_names_and_paths["checkpoints"] = ([os.path.join(models_dir, "checkpoints")], supported_pt_extensions)
|
||||
folder_names_and_paths["configs"] = ([os.path.join(models_dir, "configs")], [".yaml"])
|
||||
|
||||
folder_names_and_paths["loras"] = ([os.path.join(models_dir, "loras")], supported_pt_extensions)
|
||||
folder_names_and_paths["vae"] = ([os.path.join(models_dir, "vae")], supported_pt_extensions)
|
||||
folder_names_and_paths["text_encoders"] = ([os.path.join(models_dir, "text_encoders"), os.path.join(models_dir, "clip")], supported_pt_extensions)
|
||||
folder_names_and_paths["diffusion_models"] = ([os.path.join(models_dir, "unet"), os.path.join(models_dir, "diffusion_models")], supported_pt_extensions)
|
||||
folder_names_and_paths["clip_vision"] = ([os.path.join(models_dir, "clip_vision")], supported_pt_extensions)
|
||||
folder_names_and_paths["style_models"] = ([os.path.join(models_dir, "style_models")], supported_pt_extensions)
|
||||
folder_names_and_paths["embeddings"] = ([os.path.join(models_dir, "embeddings")], supported_pt_extensions)
|
||||
folder_names_and_paths["diffusers"] = ([os.path.join(models_dir, "diffusers")], ["folder"])
|
||||
folder_names_and_paths["vae_approx"] = ([os.path.join(models_dir, "vae_approx")], supported_pt_extensions)
|
||||
|
||||
folder_names_and_paths["controlnet"] = ([os.path.join(models_dir, "controlnet"), os.path.join(models_dir, "t2i_adapter")], supported_pt_extensions)
|
||||
folder_names_and_paths["gligen"] = ([os.path.join(models_dir, "gligen")], supported_pt_extensions)
|
||||
|
||||
folder_names_and_paths["upscale_models"] = ([os.path.join(models_dir, "upscale_models")], supported_pt_extensions)
|
||||
|
||||
folder_names_and_paths["latent_upscale_models"] = ([os.path.join(models_dir, "latent_upscale_models")], supported_pt_extensions)
|
||||
|
||||
folder_names_and_paths["custom_nodes"] = ([os.path.join(base_path, "custom_nodes")], set())
|
||||
|
||||
folder_names_and_paths["datasets"] = ([os.path.join(base_path, "datasets")], set())
|
||||
|
||||
folder_names_and_paths["hypernetworks"] = ([os.path.join(models_dir, "hypernetworks")], supported_pt_extensions)
|
||||
|
||||
folder_names_and_paths["photomaker"] = ([os.path.join(models_dir, "photomaker")], supported_pt_extensions)
|
||||
|
||||
folder_names_and_paths["classifiers"] = ([os.path.join(models_dir, "classifiers")], {""})
|
||||
|
||||
folder_names_and_paths["model_patches"] = ([os.path.join(models_dir, "model_patches")], supported_pt_extensions)
|
||||
|
||||
folder_names_and_paths["audio_encoders"] = ([os.path.join(models_dir, "audio_encoders")], supported_pt_extensions)
|
||||
|
||||
folder_names_and_paths["background_removal"] = ([os.path.join(models_dir, "background_removal")], supported_pt_extensions)
|
||||
|
||||
folder_names_and_paths["frame_interpolation"] = ([os.path.join(models_dir, "frame_interpolation")], supported_pt_extensions)
|
||||
|
||||
folder_names_and_paths["geometry_estimation"] = ([os.path.join(models_dir, "geometry_estimation")], supported_pt_extensions)
|
||||
|
||||
folder_names_and_paths["optical_flow"] = ([os.path.join(models_dir, "optical_flow")], supported_pt_extensions)
|
||||
|
||||
folder_names_and_paths["detection"] = ([os.path.join(models_dir, "detection")], supported_pt_extensions)
|
||||
|
||||
output_directory = os.path.join(base_path, "output")
|
||||
temp_directory = os.path.join(base_path, "temp")
|
||||
input_directory = os.path.join(base_path, "input")
|
||||
user_directory = os.path.join(base_path, "user")
|
||||
|
||||
filename_list_cache: dict[str, tuple[list[str], dict[str, float], float]] = {}
|
||||
|
||||
class CacheHelper:
|
||||
"""
|
||||
Helper class for managing file list cache data.
|
||||
"""
|
||||
def __init__(self):
|
||||
self.cache: dict[str, tuple[list[str], dict[str, float], float]] = {}
|
||||
self.active = False
|
||||
|
||||
def get(self, key: str, default=None) -> tuple[list[str], dict[str, float], float]:
|
||||
if not self.active:
|
||||
return default
|
||||
return self.cache.get(key, default)
|
||||
|
||||
def set(self, key: str, value: tuple[list[str], dict[str, float], float]) -> None:
|
||||
if self.active:
|
||||
self.cache[key] = value
|
||||
|
||||
def clear(self):
|
||||
self.cache.clear()
|
||||
|
||||
def __enter__(self):
|
||||
self.active = True
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_value, traceback):
|
||||
self.active = False
|
||||
self.clear()
|
||||
|
||||
cache_helper = CacheHelper()
|
||||
|
||||
extension_mimetypes_cache = {
|
||||
"webp" : "image",
|
||||
"fbx" : "model",
|
||||
}
|
||||
|
||||
def map_legacy(folder_name: str) -> str:
|
||||
legacy = {"unet": "diffusion_models",
|
||||
"clip": "text_encoders"}
|
||||
return legacy.get(folder_name, folder_name)
|
||||
|
||||
if not os.path.exists(input_directory):
|
||||
try:
|
||||
os.makedirs(input_directory)
|
||||
except:
|
||||
logging.error("Failed to create input directory")
|
||||
|
||||
def set_output_directory(output_dir: str) -> None:
|
||||
global output_directory
|
||||
output_directory = output_dir
|
||||
|
||||
def set_temp_directory(temp_dir: str) -> None:
|
||||
global temp_directory
|
||||
temp_directory = temp_dir
|
||||
|
||||
def set_input_directory(input_dir: str) -> None:
|
||||
global input_directory
|
||||
input_directory = input_dir
|
||||
|
||||
def get_output_directory() -> str:
|
||||
global output_directory
|
||||
return output_directory
|
||||
|
||||
def get_temp_directory() -> str:
|
||||
global temp_directory
|
||||
return temp_directory
|
||||
|
||||
def get_input_directory() -> str:
|
||||
global input_directory
|
||||
return input_directory
|
||||
|
||||
def get_user_directory() -> str:
|
||||
return user_directory
|
||||
|
||||
def set_user_directory(user_dir: str) -> None:
|
||||
global user_directory
|
||||
user_directory = user_dir
|
||||
|
||||
|
||||
# System User Protection - Protects system directories from HTTP endpoint access
|
||||
# System Users are internal-only users that cannot be accessed via HTTP endpoints.
|
||||
# They use the '__' prefix convention (similar to Python's private member convention).
|
||||
SYSTEM_USER_PREFIX = "__"
|
||||
|
||||
|
||||
def get_system_user_directory(name: str = "system") -> str:
|
||||
"""
|
||||
Get the path to a System User directory.
|
||||
|
||||
System User directories (prefixed with '__') are only accessible via internal API,
|
||||
not through HTTP endpoints. Use this for storing system-internal data that
|
||||
should not be exposed to users.
|
||||
|
||||
Args:
|
||||
name: System user name (e.g., "system", "cache"). Must be alphanumeric
|
||||
with underscores allowed, but cannot start with underscore.
|
||||
|
||||
Returns:
|
||||
Absolute path to the system user directory.
|
||||
|
||||
Raises:
|
||||
ValueError: If name is empty, invalid, or starts with underscore.
|
||||
|
||||
Example:
|
||||
>>> get_system_user_directory("cache")
|
||||
'/path/to/user/__cache'
|
||||
"""
|
||||
if not name or not isinstance(name, str):
|
||||
raise ValueError("System user name cannot be empty")
|
||||
if not name.replace("_", "").isalnum():
|
||||
raise ValueError(f"Invalid system user name: '{name}'")
|
||||
if name.startswith("_"):
|
||||
raise ValueError("System user name should not start with underscore")
|
||||
return os.path.join(get_user_directory(), f"{SYSTEM_USER_PREFIX}{name}")
|
||||
|
||||
|
||||
def get_public_user_directory(user_id: str) -> str | None:
|
||||
"""
|
||||
Get the path to a Public User directory for HTTP endpoint access.
|
||||
|
||||
This function provides structural security by returning None for any
|
||||
System User (prefixed with '__'). All HTTP endpoints should use this
|
||||
function instead of directly constructing user paths.
|
||||
|
||||
Args:
|
||||
user_id: User identifier from HTTP request.
|
||||
|
||||
Returns:
|
||||
Absolute path to the user directory, or None if user_id is invalid
|
||||
or refers to a System User.
|
||||
|
||||
Example:
|
||||
>>> get_public_user_directory("default")
|
||||
'/path/to/user/default'
|
||||
>>> get_public_user_directory("__system")
|
||||
None
|
||||
"""
|
||||
if not user_id or not isinstance(user_id, str):
|
||||
return None
|
||||
if user_id.startswith(SYSTEM_USER_PREFIX):
|
||||
return None
|
||||
return os.path.join(get_user_directory(), user_id)
|
||||
|
||||
|
||||
#NOTE: used in http server so don't put folders that should not be accessed remotely
|
||||
def get_directory_by_type(type_name: str) -> str | None:
|
||||
if type_name == "output":
|
||||
return get_output_directory()
|
||||
if type_name == "temp":
|
||||
return get_temp_directory()
|
||||
if type_name == "input":
|
||||
return get_input_directory()
|
||||
return None
|
||||
|
||||
def filter_files_content_types(files: list[str], content_types: List[Literal["image", "video", "audio", "model"]]) -> list[str]:
|
||||
"""
|
||||
Example:
|
||||
files = os.listdir(folder_paths.get_input_directory())
|
||||
videos = filter_files_content_types(files, ["video"])
|
||||
|
||||
Note:
|
||||
- 'model' in MIME context refers to 3D models, not files containing trained weights and parameters
|
||||
"""
|
||||
global extension_mimetypes_cache
|
||||
result = []
|
||||
for file in files:
|
||||
extension = file.split('.')[-1]
|
||||
if extension not in extension_mimetypes_cache:
|
||||
mime_type, _ = mimetypes.guess_type(file, strict=False)
|
||||
if not mime_type:
|
||||
continue
|
||||
content_type = mime_type.split('/')[0]
|
||||
extension_mimetypes_cache[extension] = content_type
|
||||
else:
|
||||
content_type = extension_mimetypes_cache[extension]
|
||||
|
||||
if content_type in content_types:
|
||||
result.append(file)
|
||||
return result
|
||||
|
||||
# determine base_dir rely on annotation if name is 'filename.ext [annotation]' format
|
||||
# otherwise use default_path as base_dir
|
||||
def annotated_filepath(name: str) -> tuple[str, str | None]:
|
||||
if name.endswith("[output]"):
|
||||
base_dir = get_output_directory()
|
||||
name = name[:-9]
|
||||
elif name.endswith("[input]"):
|
||||
base_dir = get_input_directory()
|
||||
name = name[:-8]
|
||||
elif name.endswith("[temp]"):
|
||||
base_dir = get_temp_directory()
|
||||
name = name[:-7]
|
||||
else:
|
||||
return name, None
|
||||
|
||||
return name, base_dir
|
||||
|
||||
|
||||
# Content types a browser may execute or render inline. File endpoints that
|
||||
# serve user-controlled content must force these to download (and ideally set
|
||||
# Content-Disposition: attachment) to avoid stored XSS. Centralised here so the
|
||||
# /view and /userdata handlers can't drift apart. mimetypes.guess_type may
|
||||
# return either the text/* or application/* spelling depending on platform, so
|
||||
# both are listed.
|
||||
DANGEROUS_CONTENT_TYPES = {
|
||||
'text/html', 'text/html-sandboxed', 'application/xhtml+xml',
|
||||
'text/javascript', 'application/javascript', 'application/x-javascript',
|
||||
'application/ecmascript', 'text/css',
|
||||
'image/svg+xml', 'application/xml', 'text/xml',
|
||||
# message/rfc822 (.mht/.mhtml) can carry script in some browsers.
|
||||
'message/rfc822',
|
||||
}
|
||||
|
||||
|
||||
def is_dangerous_content_type(content_type: str | None) -> bool:
|
||||
"""Return True if a browser may execute or render `content_type` inline.
|
||||
|
||||
Normalises before matching so the check can't be slipped past with a
|
||||
charset/boundary parameter (``text/html; charset=utf-8``) or casing
|
||||
(``TEXT/HTML``). Any XML dialect (``*+xml`` or ``*/xml``) is treated as
|
||||
dangerous because XML can carry inline script via stylesheet/entity tricks,
|
||||
which also covers the ``application/{xslt,rss,atom,rdf}+xml`` family without
|
||||
enumerating each one. Endpoints serving user-controlled content should route
|
||||
a dangerous type to ``application/octet-stream`` + ``Content-Disposition:
|
||||
attachment`` + ``X-Content-Type-Options: nosniff``.
|
||||
"""
|
||||
if not content_type:
|
||||
return False
|
||||
normalized = content_type.split(';', 1)[0].strip().lower()
|
||||
if normalized in DANGEROUS_CONTENT_TYPES:
|
||||
return True
|
||||
return normalized.endswith('+xml') or normalized.endswith('/xml')
|
||||
|
||||
|
||||
def renders_safely_as_image(content_type: str | None, sec_fetch_dest: str | None) -> bool:
|
||||
"""Return True if a dangerous `content_type` is safe to serve inline anyway.
|
||||
|
||||
An SVG referenced by an ``<img>`` is loaded in secure static mode: scripts
|
||||
and external references are disabled, so the stored XSS that
|
||||
``is_dangerous_content_type`` guards against cannot fire. The attack needs
|
||||
the SVG to become a document, which is a separate ``Sec-Fetch-Dest``.
|
||||
Browsers set that header themselves and script cannot override it (the
|
||||
``Sec-`` prefix makes it a forbidden header name), so it is trustworthy for
|
||||
this decision. Anything else, including a missing header from a non-browser
|
||||
client or a proxy that strips it, fails closed.
|
||||
"""
|
||||
if sec_fetch_dest != 'image':
|
||||
return False
|
||||
return (content_type or '').split(';', 1)[0].strip().lower() == 'image/svg+xml'
|
||||
|
||||
|
||||
def is_within_directory(directory: str, target: str) -> bool:
|
||||
"""Return True if `target` resolves to a path inside `directory`.
|
||||
|
||||
Uses realpath on both operands so that a symlink placed inside `directory`
|
||||
that points elsewhere cannot escape the containment check at open time.
|
||||
"""
|
||||
try:
|
||||
directory = os.path.realpath(directory)
|
||||
target = os.path.realpath(target)
|
||||
return os.path.commonpath((directory, target)) == directory
|
||||
except ValueError:
|
||||
# ValueError is raised by realpath() on a path with an embedded null
|
||||
# byte, and by commonpath() on Windows when the paths are on different
|
||||
# drives. In either case the target is not safely within the directory.
|
||||
return False
|
||||
|
||||
|
||||
def get_annotated_filepath(name: str, default_dir: str | None=None) -> str:
|
||||
name, base_dir = annotated_filepath(name)
|
||||
|
||||
if base_dir is None:
|
||||
if default_dir is not None:
|
||||
base_dir = default_dir
|
||||
else:
|
||||
base_dir = get_input_directory() # fallback path
|
||||
|
||||
filepath = os.path.abspath(os.path.join(base_dir, name))
|
||||
# Prevent path traversal: the resolved path must stay within base_dir.
|
||||
# repr() the name in the message so a crafted value can't inject log lines.
|
||||
if not is_within_directory(base_dir, filepath):
|
||||
raise ValueError("Invalid file path: {!r}".format(name))
|
||||
return filepath
|
||||
|
||||
|
||||
def exists_annotated_filepath(name) -> bool:
|
||||
name, base_dir = annotated_filepath(name)
|
||||
|
||||
if base_dir is None:
|
||||
base_dir = get_input_directory() # fallback path
|
||||
|
||||
filepath = os.path.abspath(os.path.join(base_dir, name))
|
||||
# Treat traversal attempts as non-existent rather than probing the filesystem.
|
||||
if not is_within_directory(base_dir, filepath):
|
||||
return False
|
||||
return os.path.exists(filepath)
|
||||
|
||||
|
||||
def add_model_folder_path(folder_name: str, full_folder_path: str, is_default: bool = False) -> None:
|
||||
global folder_names_and_paths
|
||||
folder_name = map_legacy(folder_name)
|
||||
if folder_name in folder_names_and_paths:
|
||||
paths, _exts = folder_names_and_paths[folder_name]
|
||||
if full_folder_path in paths:
|
||||
if is_default and paths[0] != full_folder_path:
|
||||
# If the path to the folder is not the first in the list, move it to the beginning.
|
||||
paths.remove(full_folder_path)
|
||||
paths.insert(0, full_folder_path)
|
||||
else:
|
||||
if is_default:
|
||||
paths.insert(0, full_folder_path)
|
||||
else:
|
||||
paths.append(full_folder_path)
|
||||
else:
|
||||
folder_names_and_paths[folder_name] = ([full_folder_path], set())
|
||||
|
||||
def get_folder_paths(folder_name: str) -> list[str]:
|
||||
folder_name = map_legacy(folder_name)
|
||||
return folder_names_and_paths[folder_name][0][:]
|
||||
|
||||
def recursive_search(directory: str, excluded_dir_names: list[str] | None=None) -> tuple[list[str], dict[str, float]]:
|
||||
if not os.path.isdir(directory):
|
||||
return [], {}
|
||||
|
||||
if excluded_dir_names is None:
|
||||
excluded_dir_names = []
|
||||
|
||||
result = []
|
||||
dirs = {}
|
||||
|
||||
# Attempt to add the initial directory to dirs with error handling
|
||||
try:
|
||||
dirs[directory] = os.path.getmtime(directory)
|
||||
except FileNotFoundError:
|
||||
logging.warning(f"Warning: Unable to access {directory}. Skipping this path.")
|
||||
|
||||
logging.debug("recursive file list on directory {}".format(directory))
|
||||
dirpath: str
|
||||
subdirs: list[str]
|
||||
filenames: list[str]
|
||||
|
||||
for dirpath, subdirs, filenames in os.walk(directory, followlinks=True, topdown=True):
|
||||
subdirs[:] = [d for d in subdirs if d not in excluded_dir_names]
|
||||
for file_name in filenames:
|
||||
try:
|
||||
relative_path = os.path.relpath(os.path.join(dirpath, file_name), directory)
|
||||
result.append(relative_path)
|
||||
except:
|
||||
logging.warning(f"Warning: Unable to access {file_name}. Skipping this file.")
|
||||
continue
|
||||
|
||||
for d in subdirs:
|
||||
path: str = os.path.join(dirpath, d)
|
||||
try:
|
||||
dirs[path] = os.path.getmtime(path)
|
||||
except FileNotFoundError:
|
||||
logging.warning(f"Warning: Unable to access {path}. Skipping this path.")
|
||||
continue
|
||||
logging.debug("found {} files".format(len(result)))
|
||||
return result, dirs
|
||||
|
||||
def filter_files_extensions(files: Collection[str], extensions: Collection[str]) -> list[str]:
|
||||
return sorted(list(filter(lambda a: os.path.splitext(a)[-1].lower() in extensions or len(extensions) == 0, files)))
|
||||
|
||||
|
||||
|
||||
def get_full_path(folder_name: str, filename: str) -> str | None:
|
||||
"""
|
||||
Get the full path of a file in a folder, has to be a file
|
||||
"""
|
||||
global folder_names_and_paths
|
||||
folder_name = map_legacy(folder_name)
|
||||
if folder_name not in folder_names_and_paths:
|
||||
return None
|
||||
folders = folder_names_and_paths[folder_name]
|
||||
filename = os.path.relpath(os.path.join("/", filename), "/")
|
||||
for x in folders[0]:
|
||||
full_path = os.path.join(x, filename)
|
||||
if os.path.isfile(full_path):
|
||||
return full_path
|
||||
elif os.path.islink(full_path):
|
||||
logging.warning("WARNING path {} exists but doesn't link anywhere, skipping.".format(full_path))
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def get_full_path_or_raise(folder_name: str, filename: str) -> str:
|
||||
"""
|
||||
Get the full path of a file in a folder, has to be a file
|
||||
"""
|
||||
full_path = get_full_path(folder_name, filename)
|
||||
if full_path is None:
|
||||
raise FileNotFoundError(f"Model in folder '{folder_name}' with filename '{filename}' not found.")
|
||||
return full_path
|
||||
|
||||
|
||||
def get_filename_list_(folder_name: str) -> tuple[list[str], dict[str, float], float]:
|
||||
folder_name = map_legacy(folder_name)
|
||||
global folder_names_and_paths
|
||||
output_list = set()
|
||||
folders = folder_names_and_paths[folder_name]
|
||||
output_folders = {}
|
||||
for x in folders[0]:
|
||||
files, folders_all = recursive_search(x, excluded_dir_names=[".git"])
|
||||
output_list.update(filter_files_extensions(files, folders[1]))
|
||||
output_folders = {**output_folders, **folders_all}
|
||||
|
||||
return sorted(list(output_list)), output_folders, time.perf_counter()
|
||||
|
||||
def cached_filename_list_(folder_name: str) -> tuple[list[str], dict[str, float], float] | None:
|
||||
strong_cache = cache_helper.get(folder_name)
|
||||
if strong_cache is not None:
|
||||
return strong_cache
|
||||
|
||||
global filename_list_cache
|
||||
global folder_names_and_paths
|
||||
folder_name = map_legacy(folder_name)
|
||||
if folder_name not in filename_list_cache:
|
||||
return None
|
||||
out = filename_list_cache[folder_name]
|
||||
|
||||
for x in out[1]:
|
||||
time_modified = out[1][x]
|
||||
folder = x
|
||||
if os.path.getmtime(folder) != time_modified:
|
||||
return None
|
||||
|
||||
folders = folder_names_and_paths[folder_name]
|
||||
for x in folders[0]:
|
||||
if os.path.isdir(x):
|
||||
if x not in out[1]:
|
||||
return None
|
||||
|
||||
return out
|
||||
|
||||
def get_filename_list(folder_name: str) -> list[str]:
|
||||
folder_name = map_legacy(folder_name)
|
||||
out = cached_filename_list_(folder_name)
|
||||
if out is None:
|
||||
out = get_filename_list_(folder_name)
|
||||
global filename_list_cache
|
||||
filename_list_cache[folder_name] = out
|
||||
cache_helper.set(folder_name, out)
|
||||
return list(out[0])
|
||||
|
||||
def get_save_image_path(filename_prefix: str, output_dir: str, image_width=0, image_height=0) -> tuple[str, str, int, str, str]:
|
||||
def map_filename(filename: str) -> tuple[int, str]:
|
||||
prefix_len = len(os.path.basename(filename_prefix))
|
||||
prefix = filename[:prefix_len + 1]
|
||||
try:
|
||||
remainder = filename[prefix_len + 1:]
|
||||
base_remainder = remainder.split('.')[0]
|
||||
digits = int(base_remainder.split('_')[0])
|
||||
except:
|
||||
digits = 0
|
||||
return digits, prefix
|
||||
|
||||
def compute_vars(input: str, image_width: int, image_height: int) -> str:
|
||||
input = input.replace("%width%", str(image_width))
|
||||
input = input.replace("%height%", str(image_height))
|
||||
now = time.localtime()
|
||||
input = input.replace("%year%", str(now.tm_year))
|
||||
input = input.replace("%month%", str(now.tm_mon).zfill(2))
|
||||
input = input.replace("%day%", str(now.tm_mday).zfill(2))
|
||||
input = input.replace("%hour%", str(now.tm_hour).zfill(2))
|
||||
input = input.replace("%minute%", str(now.tm_min).zfill(2))
|
||||
input = input.replace("%second%", str(now.tm_sec).zfill(2))
|
||||
return input
|
||||
|
||||
if "%" in filename_prefix:
|
||||
filename_prefix = compute_vars(filename_prefix, image_width, image_height)
|
||||
|
||||
subfolder = os.path.dirname(os.path.normpath(filename_prefix))
|
||||
filename = os.path.basename(os.path.normpath(filename_prefix))
|
||||
|
||||
full_output_folder = os.path.join(output_dir, subfolder)
|
||||
|
||||
if not is_within_directory(output_dir, full_output_folder):
|
||||
err = "**** ERROR: Saving image outside the output folder is not allowed." + \
|
||||
"\n full_output_folder: " + os.path.abspath(full_output_folder) + \
|
||||
"\n output_dir: " + output_dir
|
||||
logging.error(err)
|
||||
raise Exception(err)
|
||||
|
||||
try:
|
||||
counter = max(filter(lambda a: os.path.normcase(a[1][:-1]) == os.path.normcase(filename) and a[1][-1] == "_", map(map_filename, os.listdir(full_output_folder))))[0] + 1
|
||||
except ValueError:
|
||||
counter = 1
|
||||
except FileNotFoundError:
|
||||
os.makedirs(full_output_folder, exist_ok=True)
|
||||
counter = 1
|
||||
return full_output_folder, filename, counter, subfolder, filename_prefix
|
||||
|
||||
def get_input_subfolders() -> list[str]:
|
||||
"""Returns a list of all subfolder paths in the input directory, recursively.
|
||||
|
||||
Returns:
|
||||
List of folder paths relative to the input directory, excluding the root directory
|
||||
"""
|
||||
input_dir = get_input_directory()
|
||||
folders = []
|
||||
|
||||
try:
|
||||
if not os.path.exists(input_dir):
|
||||
return []
|
||||
|
||||
for root, dirs, _ in os.walk(input_dir):
|
||||
rel_path = os.path.relpath(root, input_dir)
|
||||
if rel_path != ".": # Only include non-root directories
|
||||
# Normalize path separators to forward slashes
|
||||
folders.append(rel_path.replace(os.sep, '/'))
|
||||
|
||||
return sorted(folders)
|
||||
except FileNotFoundError:
|
||||
return []
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
{"ref":"refs/tags/v1.51.9","node_id":"REF_kwDOMIrOxrFyZWZzL3RhZ3MvdjEuNTEuOQ","url":"https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/refs/tags/v1.51.9","object":{"sha":"71d2f2f2b5c6da9dee281836b5b72f3af368966f","type":"commit","url":"https://api.github.com/repos/Comfy-Org/ComfyUI_frontend/git/commits/71d2f2f2b5c6da9dee281836b5b72f3af368966f"}}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { LGraphNode } from '@/lib/litegraph/src/LGraphNode'
|
||||
import {
|
||||
type ComfyNodeDef,
|
||||
type InputSpec,
|
||||
isMediaUploadComboInput
|
||||
} from '@/schemas/nodeDefSchema'
|
||||
|
||||
import { app } from '../../scripts/app'
|
||||
|
||||
// Adds an upload button to the nodes
|
||||
|
||||
const createUploadInput = (
|
||||
imageInputName: string,
|
||||
imageInputOptions: InputSpec
|
||||
): InputSpec => [
|
||||
'IMAGEUPLOAD',
|
||||
{
|
||||
...imageInputOptions[1],
|
||||
imageInputName
|
||||
}
|
||||
]
|
||||
|
||||
app.registerExtension({
|
||||
name: 'Comfy.UploadImage',
|
||||
beforeRegisterNodeDef(_nodeType: typeof LGraphNode, nodeData: ComfyNodeDef) {
|
||||
const { input } = nodeData ?? {}
|
||||
const { required } = input ?? {}
|
||||
if (!required) return
|
||||
|
||||
const found = Object.entries(required).find(([_, input]) =>
|
||||
isMediaUploadComboInput(input)
|
||||
)
|
||||
|
||||
// If media combo input found, attach upload input
|
||||
if (found) {
|
||||
const [inputName, inputSpec] = found
|
||||
required.upload = createUploadInput(inputName, inputSpec)
|
||||
}
|
||||
}
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,160 @@
|
||||
import { isComboWidget } from '@/lib/litegraph/src/litegraph'
|
||||
import type { IBaseWidget } from '@/lib/litegraph/src/types/widgets'
|
||||
|
||||
import { IS_CONTROL_WIDGET } from './controlWidgetMarker'
|
||||
|
||||
type ValueControlMode =
|
||||
| 'fixed'
|
||||
| 'increment'
|
||||
| 'increment-wrap'
|
||||
| 'decrement'
|
||||
| 'randomize'
|
||||
|
||||
export function nextValueForLinkedTarget(params: {
|
||||
target: IBaseWidget
|
||||
linkedWidgets: IBaseWidget[] | undefined
|
||||
nodeId: unknown
|
||||
isPartialExecution: boolean | undefined
|
||||
}): IBaseWidget['value'] | undefined {
|
||||
if (params.isPartialExecution) return undefined
|
||||
const linked = params.linkedWidgets
|
||||
if (!linked) return undefined
|
||||
|
||||
const controlWidget = linked.find(isValueControlWidget)
|
||||
if (!controlWidget) return undefined
|
||||
|
||||
const comboFilter = linked.find(
|
||||
(w) => w !== controlWidget && w.type === 'string'
|
||||
)
|
||||
const filterValue =
|
||||
typeof comboFilter?.value === 'string' ? comboFilter.value : undefined
|
||||
|
||||
const mode = controlWidget.value as ValueControlMode
|
||||
return computeNextControlledValue(params.target, mode, {
|
||||
comboFilter: filterValue,
|
||||
nodeId: params.nodeId
|
||||
})
|
||||
}
|
||||
|
||||
const SAFE_INTEGER_MAX = 1125899906842624
|
||||
const SAFE_INTEGER_MIN = -1125899906842624
|
||||
|
||||
export function isValueControlWidget(widget: IBaseWidget): boolean {
|
||||
return (
|
||||
(widget as Record<symbol, unknown>)[IS_CONTROL_WIDGET] === true &&
|
||||
typeof widget.beforeQueued === 'function' &&
|
||||
typeof widget.afterQueued === 'function'
|
||||
)
|
||||
}
|
||||
|
||||
function buildComboFilter(
|
||||
filter: string | undefined,
|
||||
nodeId?: unknown
|
||||
): ((item: string) => boolean) | undefined {
|
||||
if (!filter) return undefined
|
||||
|
||||
if (filter.startsWith('/') && filter.endsWith('/')) {
|
||||
try {
|
||||
const regex = new RegExp(filter.substring(1, filter.length - 1))
|
||||
return (item: string) => regex.test(item)
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'Error constructing RegExp filter for node ' + String(nodeId),
|
||||
filter,
|
||||
error
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const lower = filter.toLocaleLowerCase()
|
||||
return (item: string) => item.toLocaleLowerCase().includes(lower)
|
||||
}
|
||||
|
||||
export function computeNextControlledValue(
|
||||
target: IBaseWidget,
|
||||
mode: ValueControlMode,
|
||||
options: { comboFilter?: string; nodeId?: unknown } = {}
|
||||
): IBaseWidget['value'] | undefined {
|
||||
if (mode === 'fixed') return undefined
|
||||
|
||||
if (isComboWidget(target)) {
|
||||
return computeNextComboValue(target, mode, options)
|
||||
}
|
||||
|
||||
return computeNextNumberValue(target, mode)
|
||||
}
|
||||
|
||||
function computeNextComboValue(
|
||||
target: IBaseWidget,
|
||||
mode: ValueControlMode,
|
||||
{ comboFilter, nodeId }: { comboFilter?: string; nodeId?: unknown }
|
||||
): IBaseWidget['value'] | undefined {
|
||||
const rawValues = target.options.values
|
||||
if (!Array.isArray(rawValues)) return undefined
|
||||
|
||||
const allValues = rawValues.filter(
|
||||
(value): value is string => typeof value === 'string'
|
||||
)
|
||||
const check = buildComboFilter(comboFilter, nodeId)
|
||||
const values = check ? allValues.filter(check) : allValues
|
||||
|
||||
if (!values.length) {
|
||||
if (allValues.length) {
|
||||
console.warn(
|
||||
'Filter for node ' + String(nodeId) + ' has filtered out all items',
|
||||
comboFilter
|
||||
)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
let currentIndex = values.indexOf(target.value as string)
|
||||
const length = values.length
|
||||
|
||||
switch (mode) {
|
||||
case 'increment':
|
||||
currentIndex += 1
|
||||
break
|
||||
case 'increment-wrap':
|
||||
currentIndex += 1
|
||||
if (currentIndex >= length) currentIndex = 0
|
||||
break
|
||||
case 'decrement':
|
||||
currentIndex -= 1
|
||||
break
|
||||
case 'randomize':
|
||||
currentIndex = Math.floor(Math.random() * length)
|
||||
break
|
||||
}
|
||||
|
||||
currentIndex = Math.max(0, Math.min(length - 1, currentIndex))
|
||||
return values[currentIndex]
|
||||
}
|
||||
|
||||
function computeNextNumberValue(
|
||||
target: IBaseWidget,
|
||||
mode: ValueControlMode
|
||||
): number | undefined {
|
||||
if (typeof target.value !== 'number') return undefined
|
||||
|
||||
const { min: rawMin = 0, max: rawMax = 1, step2 = 1 } = target.options
|
||||
const max = Math.min(SAFE_INTEGER_MAX, rawMax)
|
||||
const min = Math.max(SAFE_INTEGER_MIN, rawMin)
|
||||
const range = (max - min) / step2
|
||||
|
||||
let next = target.value
|
||||
switch (mode) {
|
||||
case 'increment':
|
||||
case 'increment-wrap':
|
||||
next += step2
|
||||
break
|
||||
case 'decrement':
|
||||
next -= step2
|
||||
break
|
||||
case 'randomize':
|
||||
next = Math.floor(Math.random() * range) * step2 + min
|
||||
break
|
||||
}
|
||||
|
||||
return Math.min(Math.max(next, min), max)
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import { t } from '@/i18n'
|
||||
import { type LGraphNode, isComboWidget } from '@/lib/litegraph/src/litegraph'
|
||||
import type {
|
||||
IBaseWidget,
|
||||
IComboWidget,
|
||||
IStringWidget
|
||||
} from '@/lib/litegraph/src/types/widgets'
|
||||
import { nextValueForLinkedTarget } from './valueControl'
|
||||
import { useSettingStore } from '@/platform/settings/settingStore'
|
||||
import { dynamicWidgets } from '@/core/graph/widgets/dynamicWidgets'
|
||||
import { useBooleanWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useBooleanWidget'
|
||||
import { useBoundingBoxWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useBoundingBoxWidget'
|
||||
import { useCurveWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useCurveWidget'
|
||||
import { useChartWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useChartWidget'
|
||||
import { useColorWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useColorWidget'
|
||||
import { useComboWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useComboWidget'
|
||||
import { useCompositorWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useCompositorWidget'
|
||||
import { useFloatWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useFloatWidget'
|
||||
import { useGalleriaWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useGalleriaWidget'
|
||||
import { useBoundingBoxesWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useBoundingBoxesWidget'
|
||||
import { useColorsWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useColorsWidget'
|
||||
import { useImageCompareWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useImageCompareWidget'
|
||||
import { useImageUploadWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useImageUploadWidget'
|
||||
import { useIntWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useIntWidget'
|
||||
import { useMarkdownWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useMarkdownWidget'
|
||||
import { usePainterWidget } from '@/renderer/extensions/vueNodes/widgets/composables/usePainterWidget'
|
||||
import { useRangeWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useRangeWidget'
|
||||
import { useStringWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useStringWidget'
|
||||
import { useTextareaWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useTextareaWidget'
|
||||
import { useVideoEditWidget } from '@/renderer/extensions/vueNodes/widgets/composables/useVideoEditWidget'
|
||||
import { transformInputSpecV1ToV2 } from '@/schemas/nodeDef/migration'
|
||||
import type { InputSpec as InputSpecV2 } from '@/schemas/nodeDef/nodeDefSchemaV2'
|
||||
import type { InputSpec } from '@/schemas/nodeDefSchema'
|
||||
|
||||
import type { ComfyApp } from './app'
|
||||
import { IS_CONTROL_WIDGET } from './controlWidgetMarker'
|
||||
import './domWidget'
|
||||
import './errorNodeWidgets'
|
||||
|
||||
export { IS_CONTROL_WIDGET }
|
||||
|
||||
export type ComfyWidgetConstructorV2 = (
|
||||
node: LGraphNode,
|
||||
inputSpec: InputSpecV2
|
||||
) => IBaseWidget
|
||||
|
||||
export type ComfyWidgetConstructor = (
|
||||
node: LGraphNode,
|
||||
inputName: string,
|
||||
inputData: InputSpec,
|
||||
app: ComfyApp,
|
||||
widgetName?: string
|
||||
) => { widget: IBaseWidget; minWidth?: number; minHeight?: number }
|
||||
|
||||
/**
|
||||
* Transforms a V2 widget constructor to a V1 widget constructor.
|
||||
* @param widgetConstructorV2 The V2 widget constructor to transform.
|
||||
* @returns The transformed V1 widget constructor.
|
||||
*/
|
||||
const transformWidgetConstructorV2ToV1 = (
|
||||
widgetConstructorV2: ComfyWidgetConstructorV2
|
||||
): ComfyWidgetConstructor => {
|
||||
return (node, inputName, inputData) => {
|
||||
const inputSpec = transformInputSpecV1ToV2(inputData, {
|
||||
name: inputName
|
||||
})
|
||||
const widget = widgetConstructorV2(node, inputSpec)
|
||||
return {
|
||||
widget,
|
||||
minWidth: widget.options.minNodeSize?.[0],
|
||||
minHeight: widget.options.minNodeSize?.[1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function controlValueRunBefore() {
|
||||
return useSettingStore().get('Comfy.WidgetControlMode') === 'before'
|
||||
}
|
||||
|
||||
export function updateControlWidgetLabel(widget: IBaseWidget) {
|
||||
if (controlValueRunBefore()) {
|
||||
widget.label = t('g.control_before_generate')
|
||||
} else {
|
||||
widget.label = t('g.control_after_generate')
|
||||
}
|
||||
}
|
||||
|
||||
const HAS_EXECUTED = Symbol()
|
||||
|
||||
export function addValueControlWidget(
|
||||
node: LGraphNode,
|
||||
targetWidget: IBaseWidget,
|
||||
defaultValue?: string,
|
||||
_values?: unknown,
|
||||
widgetName?: string,
|
||||
inputData?: InputSpec
|
||||
): IComboWidget {
|
||||
let name = inputData?.[1]?.control_after_generate
|
||||
if (typeof name !== 'string') {
|
||||
name = widgetName
|
||||
}
|
||||
const widgets = addValueControlWidgets(
|
||||
node,
|
||||
targetWidget,
|
||||
defaultValue ?? 'randomize',
|
||||
{
|
||||
addFilterList: false,
|
||||
controlAfterGenerateName: name
|
||||
},
|
||||
inputData
|
||||
)
|
||||
return widgets[0]
|
||||
}
|
||||
|
||||
export function addValueControlWidgets(
|
||||
node: LGraphNode,
|
||||
targetWidget: IBaseWidget,
|
||||
defaultValue?: string,
|
||||
options?: Record<string, any>,
|
||||
inputData?: InputSpec
|
||||
): [IComboWidget, ...IStringWidget[]] {
|
||||
if (!defaultValue) defaultValue = 'randomize'
|
||||
if (!options) options = {}
|
||||
|
||||
const getName = (defaultName: string, optionName: string) => {
|
||||
let name = defaultName
|
||||
if (options[optionName]) {
|
||||
name = options[optionName]
|
||||
} else if (typeof inputData?.[1]?.[defaultName] === 'string') {
|
||||
name = inputData?.[1]?.[defaultName]
|
||||
} else if (inputData?.[1]?.control_prefix) {
|
||||
name = inputData?.[1]?.control_prefix + ' ' + name
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
const valueControl = node.addWidget(
|
||||
'combo',
|
||||
getName('control_after_generate', 'controlAfterGenerateName'),
|
||||
defaultValue,
|
||||
function () {},
|
||||
{
|
||||
values: ['fixed', 'increment', 'decrement', 'randomize'],
|
||||
serialize: false, // Don't include this in prompt.
|
||||
canvasOnly: true
|
||||
}
|
||||
) as IComboWidget
|
||||
|
||||
valueControl.tooltip =
|
||||
'Allows the linked widget to be changed automatically, for example randomizing the noise seed.'
|
||||
valueControl[IS_CONTROL_WIDGET] = true
|
||||
updateControlWidgetLabel(valueControl)
|
||||
Object.defineProperty(valueControl, 'disabled', {
|
||||
get: () => targetWidget.computedDisabled
|
||||
})
|
||||
const widgets: [IComboWidget, ...IStringWidget[]] = [valueControl]
|
||||
|
||||
const isCombo = isComboWidget(targetWidget)
|
||||
let comboFilter: IStringWidget
|
||||
if (isCombo && valueControl.options.values) {
|
||||
// @ts-expect-error Combo widget values may be a dictionary or legacy function type
|
||||
valueControl.options.values.push('increment-wrap')
|
||||
}
|
||||
if (isCombo && options.addFilterList !== false) {
|
||||
comboFilter = node.addWidget(
|
||||
'string',
|
||||
getName('control_filter_list', 'controlFilterListName'),
|
||||
'',
|
||||
function () {},
|
||||
{
|
||||
serialize: false // Don't include this in prompt.
|
||||
}
|
||||
) as IStringWidget
|
||||
updateControlWidgetLabel(comboFilter)
|
||||
comboFilter.tooltip =
|
||||
"Allows for filtering the list of values when changing the value via the control generate mode. Allows for RegEx matches in the format /abc/ to only filter to values containing 'abc'."
|
||||
Object.defineProperty(comboFilter, 'disabled', {
|
||||
get: () => targetWidget.computedDisabled
|
||||
})
|
||||
|
||||
widgets.push(comboFilter)
|
||||
}
|
||||
|
||||
function applyWidgetControl(isPartialExecution: boolean | undefined) {
|
||||
if (
|
||||
node.inputs?.some(
|
||||
(input) =>
|
||||
input.widget?.name === targetWidget.name && input.link != null
|
||||
)
|
||||
)
|
||||
return
|
||||
|
||||
const next = nextValueForLinkedTarget({
|
||||
target: targetWidget,
|
||||
linkedWidgets: targetWidget.linkedWidgets,
|
||||
nodeId: node.id,
|
||||
isPartialExecution
|
||||
})
|
||||
if (next === undefined) return
|
||||
|
||||
targetWidget.value = next
|
||||
targetWidget.callback?.(next)
|
||||
}
|
||||
|
||||
valueControl.beforeQueued = ({ isPartialExecution } = {}) => {
|
||||
if (controlValueRunBefore()) {
|
||||
// Don't run on first execution
|
||||
if (valueControl[HAS_EXECUTED]) {
|
||||
applyWidgetControl(isPartialExecution)
|
||||
}
|
||||
}
|
||||
valueControl[HAS_EXECUTED] = true
|
||||
}
|
||||
|
||||
valueControl.afterQueued = ({ isPartialExecution } = {}) => {
|
||||
if (!controlValueRunBefore()) {
|
||||
applyWidgetControl(isPartialExecution)
|
||||
}
|
||||
}
|
||||
|
||||
return widgets
|
||||
}
|
||||
|
||||
export const ComfyWidgets = {
|
||||
INT: transformWidgetConstructorV2ToV1(useIntWidget()),
|
||||
FLOAT: transformWidgetConstructorV2ToV1(useFloatWidget()),
|
||||
BOOLEAN: transformWidgetConstructorV2ToV1(useBooleanWidget()),
|
||||
STRING: transformWidgetConstructorV2ToV1(useStringWidget()),
|
||||
MARKDOWN: transformWidgetConstructorV2ToV1(useMarkdownWidget()),
|
||||
COMBO: transformWidgetConstructorV2ToV1(useComboWidget()),
|
||||
IMAGEUPLOAD: useImageUploadWidget(),
|
||||
COLOR: transformWidgetConstructorV2ToV1(useColorWidget()),
|
||||
IMAGECOMPARE: transformWidgetConstructorV2ToV1(useImageCompareWidget()),
|
||||
BOUNDING_BOX: transformWidgetConstructorV2ToV1(useBoundingBoxWidget()),
|
||||
CHART: transformWidgetConstructorV2ToV1(useChartWidget()),
|
||||
GALLERIA: transformWidgetConstructorV2ToV1(useGalleriaWidget()),
|
||||
PAINTER: transformWidgetConstructorV2ToV1(usePainterWidget()),
|
||||
COMPOSITOR: transformWidgetConstructorV2ToV1(useCompositorWidget()),
|
||||
TEXTAREA: transformWidgetConstructorV2ToV1(useTextareaWidget()),
|
||||
CURVE: transformWidgetConstructorV2ToV1(useCurveWidget()),
|
||||
RANGE: transformWidgetConstructorV2ToV1(useRangeWidget()),
|
||||
VIDEO_EDIT: transformWidgetConstructorV2ToV1(useVideoEditWidget()),
|
||||
BOUNDING_BOXES: transformWidgetConstructorV2ToV1(useBoundingBoxesWidget()),
|
||||
COLORS: transformWidgetConstructorV2ToV1(useColorsWidget()),
|
||||
...dynamicWidgets
|
||||
} as const
|
||||
|
||||
export function isValidWidgetType(
|
||||
key: unknown
|
||||
): key is keyof typeof ComfyWidgets {
|
||||
return ComfyWidgets[key as keyof typeof ComfyWidgets] !== undefined
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,231 @@
|
||||
# Goohaitools-ComfyUI 孤海工具箱
|
||||
|
||||
[](https://github.com/goohai/Goohaitools-comfyui)
|
||||
[](https://space.bilibili.com/1194488958)
|
||||
|
||||
## 🎬 视频教程
|
||||
|
||||
### 👉 [点击前往 B 站主页观看全部教程](https://space.bilibili.com/1194488958)
|
||||
|
||||
[](https://space.bilibili.com/1194488958)
|
||||
|
||||
---
|
||||
## 🧩 RunningHub 工作流
|
||||
|
||||
### 👉 [点击访问我的 RunningHub 个人主页](https://www.runninghub.cn/user-center/1959241033525714946/webapp?inviteCode=rh-v1557)
|
||||
|
||||
<a href="https://vibex.runninghub.cn/p/app-5b97e951de8d47aab61ce3e9731f50a9/?inviteCode=rh-v1557" target="_blank">
|
||||
<img src="https://www.runninghub.cn/assets/images/logo.png" alt="RunningHub" height="28" align="middle" />
|
||||
<span style="display:inline-block;margin-left:8px;font-size:15px;font-weight:600;color:#1E90FF;vertical-align:middle;">RH Vibex主页 · 在线运行AI应用</span>
|
||||
</a>
|
||||
|
||||
---
|
||||
|
||||
孤海(Goohai)ComfyUI 实用工具集,合集包含 **70+** 个实用节点,覆盖:文件夹批处理快速读图、指定 DPI 自动保存、多功能遮罩分析与运算、人脸自动矫正/对齐、证件照 & 身份证自动扶正拼版、图像自动排版、实用前端JS、取色器、数字混合运算、证件照可视化服装发型选择等。适合证件照/写真/批处理生产等场景。
|
||||
|
||||
---
|
||||
|
||||
## 📦 节点总览
|
||||
|
||||
所有节点默认位于 `🔵孤海/`(即 `孤海工具箱`)分类下,少量节点按功能归入子分类:`孤海/结婚登记照`、`孤海定制`、`image` 等。
|
||||
|
||||
### 📂 加载 & 文件夹 & 批处理
|
||||
|
||||
| 节点名称 | 说明 |
|
||||
|---------|------|
|
||||
| **加载图像** | 增强版单图加载 |
|
||||
| **加载批次图像** | 从文件夹批量加载图像,支持批处理工作流 |
|
||||
| **📁文件夹图片统计** | 统计文件夹内图片数量 |
|
||||
| **文件夹数量统计** | 统计子文件夹数量 |
|
||||
| **文件夹索引** | 按序号读取文件夹内指定图片 |
|
||||
| **根据文件名识别尺寸** | 从文件名自动解析图像宽高 |
|
||||
| **批处理开关** | 批处理流中用于切换/汇总参数 |
|
||||
| **批处理进度条 🐋** | 批处理任务实时进度可视化 |
|
||||
| **自动新建文件夹** | 自动按规则创建输出目录 |
|
||||
| **自动切换正反斜杠** | Windows / Mac / Linux 路径斜杠自动兼容 |
|
||||
| **忽略多组** | 工作流中忽略多余分支输出 |
|
||||
| **字符串按类型分隔** | 按类型拆分混合字符串 |
|
||||
|
||||
### 💾 保存 & 输出
|
||||
|
||||
| 节点名称 | 说明 |
|
||||
|---------|------|
|
||||
| **保存图像JPG** | 轻量化JPG 格式保存,减少等待时间 |
|
||||
| **图像保存** | 高级图像保存(高级参数)为批处理而生 |
|
||||
|
||||
### 📐 尺寸 & 缩放 & 裁剪
|
||||
|
||||
| 节点名称 | 说明 |
|
||||
|---------|------|
|
||||
| **预设尺寸** | 常用尺寸快捷选项(证件照/社媒/打印等) |
|
||||
| **图像缩放V2** | 图像缩放 V2 增强版 |
|
||||
| **图像缩放按像素** | 按目标像素总数缩放 |
|
||||
| **图像缩放(范围)** | 在指定宽高范围内自适应缩放 |
|
||||
| **图像裁剪按比例** | 按宽高比裁剪 |
|
||||
| **图像裁剪(主体保护)** | 基于遮罩保护主体的智能裁剪 |
|
||||
| **图像旋转** | 图像旋转(常用角度选择) |
|
||||
| **外补画板(按目标宽高)** | 三合一外补画板 —— 按目标宽高 |
|
||||
| **外补画板(按比例)** | 三合一外补画板 —— 按比例 |
|
||||
| **外补画板(按方向)** | 三合一外补画板 —— 按方向 |
|
||||
|
||||
### 🎨 排版 & 拼版
|
||||
|
||||
| 节点名称 | 说明 |
|
||||
|---------|------|
|
||||
| **单尺寸排版** | 单尺寸网格/证件照排版 |
|
||||
| **多尺寸混合排版** | 不同尺寸图片混合排版 |
|
||||
| **批量自动排版** | 批量自动排版到指定纸型/DPI |
|
||||
| **身份证自动扶正拼版** | 身份证自动旋转扶正并拼版 |
|
||||
| **图像嵌入** | 将图像嵌入PNG模板指定位置(水印/相框场景) |
|
||||
|
||||
### 🎭 遮罩(Mask)处理
|
||||
|
||||
| 节点名称 | 说明 |
|
||||
|---------|------|
|
||||
| **遮罩检测** | 自动检测图像生成遮罩 |
|
||||
| **遮罩分析** | 输出遮罩包围盒、面积、中心等信息 |
|
||||
| **遮罩比例计算** | 计算遮罩占图像比例 |
|
||||
| **遮罩对齐v2** | 遮罩与目标位置对齐 V2 |
|
||||
| **遮罩中心对齐** | 按遮罩中心对齐 |
|
||||
| **遮罩裁剪** | 根据遮罩裁剪图像 |
|
||||
| **遮罩裁剪V2** | 通过遮罩裁剪再贴回,解决采样像素偏移问题 |
|
||||
| **裁剪恢复** | 将裁剪后的图像恢复到原坐标 |
|
||||
| **遮罩模糊生长按比例** | 遮罩按比例模糊扩张/收缩 |
|
||||
| **遮罩混合运算** | 遮罩加减乘/交并补等运算 |
|
||||
| **头顶遮罩** | 自动生成头顶扩展遮罩(证件照换装/发型场景) |
|
||||
| **遮罩圆角消除** | 消除遮罩圆角带来的黑边 |
|
||||
| **Seg次序过滤** | Seg 分割次序过滤 |
|
||||
| **图像与遮罩预览** | 图像 + 遮罩实时预览 |
|
||||
| **图像与遮罩描边** | 沿遮罩边缘绘制描边 |
|
||||
|
||||
### 🖼️ 图像处理
|
||||
|
||||
| 节点名称 | 说明 |
|
||||
|---------|------|
|
||||
| **图像对比 视频对比 GH** | 图像/视频滑动对比、自动双拼、左右双拼、上下双拼,支持批次选择 |
|
||||
| **保留遮罩区域移除图像背景** | 保留遮罩内区域,外部背景移除 |
|
||||
| **移除纯色背景 v2** | 自动识别并移除纯色背景 |
|
||||
| **图像合并(遮罩)** | 基于遮罩合成两张图像 |
|
||||
| **图像差异到遮罩** | 两张图像差异生成遮罩 |
|
||||
| **图像添加水印** | 批量添加文字/图片水印 |
|
||||
| **图像组合批次** | 多批次图像合并 |
|
||||
| **自动分割图像** | 根据主体/空白自动切图 |
|
||||
| **图像亮度比较** | 比较图像亮度,输出更亮/更暗分支 |
|
||||
| **肤色差值** | 计算图像肤色差异,可用于肤色一致性判断 |
|
||||
| **主色提取(多版本兼容)** | 提取图像主色调 |
|
||||
| **颜色转换** | HSV/RGB/LAB 等颜色空间互转 |
|
||||
| **常用颜色🔵孤海** | 常用颜色快捷选取 |
|
||||
| **🎨 取色器 / 孤海 取色器(双)** | 图像拾色器(单色/双色) |
|
||||
| **自定义颜色** | 自定义颜色输出 |
|
||||
|
||||
### 👤 人脸 & 证件照
|
||||
|
||||
| 节点名称 | 说明 |
|
||||
|---------|------|
|
||||
| **👤 人脸自动矫正** | 基于关键点自动矫正人脸角度 |
|
||||
| **面部对齐** | 双眼水平对齐,标准脸对齐 |
|
||||
| **证件照裁剪** | 按证件照规范(头肩比/位置)自动裁剪 |
|
||||
| **证件照服装发型** | 证件照服装/发型切换(内置男女士西装、马甲、衬衫、减龄上衣等几十套模板) |
|
||||
| **结婚登记照服装** | 结婚登记照服装切换模板 |
|
||||
| **证件照简易提示词** | 一键生成证件照常用提示词 |
|
||||
| **ID信息** | 身份证文字信息节点 |
|
||||
| **ID证生成器** | 身份证图片生成/排版节点 |
|
||||
|
||||
|
||||
### 🧰 通用小工具
|
||||
|
||||
| 节点名称 | 说明 |
|
||||
|---------|------|
|
||||
| **孤海万能滑条** | 通用整数/浮点滑条,动态范围 |
|
||||
| **孤海-浮点滑条 / 孤海-浮点滑条 0-2** | 浮点滑条(0–1 / 0–2) |
|
||||
| **布尔 孤海** | 布尔开关 |
|
||||
| **孤海-效果切换** | 多效果分支切换(N 选 1) |
|
||||
| **数学运算 孤海** | 加减乘除/混合数学运算/支持三元表达式 |
|
||||
|
||||
---
|
||||
|
||||
## ✨ 特色能力速览
|
||||
|
||||
### 📁 文件夹批处理
|
||||
- 快速加载整个文件夹图片、自动索引、自动统计
|
||||
- 配合 **批处理进度条 🐋** 直观显示当前处理进度
|
||||
- 自动新建输出目录,跨平台路径斜杠自动修正
|
||||
|
||||
### 💾 智能保存
|
||||
- 支持 **JPG 指定 DPI**(打印/证件照常用 300dpi)
|
||||
- 高级保存支持自定义压缩、元数据、命名规则
|
||||
|
||||
### 🎨 自动排版
|
||||
- **单尺寸 / 多尺寸混合 / 批量自动** 三种排版模式
|
||||
- 适配 A4/A5/6 寸等纸型,自动拼版到打印规格
|
||||
- 身份证自动扶正并排版到标准身份证模板
|
||||
|
||||
### 👤 人脸 & 证件照生产流
|
||||
- 人脸检测 → 面部对齐 → 证件照裁剪 → 服装/发型替换 → 自动排版一条龙
|
||||
- 内置女士西装/马甲/衬衫/减龄上衣、结婚登记照等 **几十套服装模板**(见 `image/ID_Photo/` 目录)
|
||||
- 人脸自动矫正 + 肤色差值 + 头顶遮罩扩展,保证换装/换发型自然
|
||||
|
||||
### 🎭 遮罩全家桶
|
||||
- 检测 → 分析 → 生长 → 模糊 → 对齐 → 裁剪 → 恢复 → 混合运算,覆盖绝大部分遮罩场景
|
||||
- 主体保护裁剪、保留遮罩区域抠背景、图像差异生成遮罩等进阶能力
|
||||
|
||||
### 🌈 颜色 & 取色
|
||||
- 取色器、常用色板、颜色空间转换、主色提取,配色/色偏校正场景常用
|
||||
|
||||
### 🖼️ 图像/视频对比
|
||||
- 支持滑动对比、自动双拼、左右双拼、上下双拼
|
||||
- 支持图像和视频预览、视频播放/暂停及进度控制
|
||||
- 双拼模式支持 Alt+滚轮缩放、Alt+左键框内平移,视频支持全屏对比
|
||||
- 批次输入可选择前 10 张图像分别对比
|
||||
- 自动调用输入文件进行预览,无需在 temp 目录新增文件
|
||||
|
||||
---
|
||||
|
||||
## ⚙️ 安装
|
||||
|
||||
### 方法一:Git 克隆(推荐,便于后续更新)
|
||||
|
||||
```bash
|
||||
cd ComfyUI/custom_nodes/
|
||||
git clone https://github.com/goohai/Goohaitools-comfyui.git
|
||||
cd Goohaitools-comfyui
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
重启 ComfyUI 即可。
|
||||
|
||||
|
||||
### 方法二:手动下载
|
||||
|
||||
下载 Goohaitools-comfyui ZIP 包
|
||||
解压到 ComfyUI/custom_nodes/ 目录,确保目录名为 Goohaitools-comfyui
|
||||
进入该目录执行 pip install -r requirements.txt
|
||||
重启 ComfyUI
|
||||
|
||||
requirements.txt 主要依赖:
|
||||
|
||||
opencv-python / scipy / scikit-image / matplotlib:图像处理核心
|
||||
mediapipe>=0.10.20:人脸/关键点检测
|
||||
dlib-bin>=19.24.6:人脸 5 点关键点模型(仓库已内置 shape_predictor_5_face_landmarks.dat)
|
||||
若使用国内网络 pip 安装慢,requirements 已默认配置清华镜像源(-i https://pypi.tuna.tsinghua.edu.cn/simple)。
|
||||
|
||||
## 🔧 前端扩展组件
|
||||
|
||||
本插件在 web/js/ 下提供多个前端 Widget 增强:
|
||||
|
||||
BOOLEAN.js 布尔开关组件
|
||||
GoohaiNote.js 节点备注/便签
|
||||
colorWidget.js 颜色取色器 Widget
|
||||
goohai_universal_slider.js 万能滑条前端交互
|
||||
gh_image_video_comparer.js 图像/视频对比预览
|
||||
id_photo_clothing.js / marry.js 证件照、结婚登记照服装选择前端组件
|
||||
启用后部分节点(取色器、万能滑条、服装切换等)会有更友好的交互 UI。
|
||||
|
||||
|
||||
## 📝 许可证
|
||||
|
||||
本项目采用开源协议发布,欢迎 Star、Fork、PR。
|
||||
|
||||
💬 反馈 & 交流
|
||||
📺 B 站(视频教程 / 工作流演示):孤海B
|
||||
🐛 GitHub Issues:提 Bug & 需求
|
||||
💡 如有问题、想要新增的功能或节点建议,欢迎在 GitHub 提 Issue 或 B 站私信;觉得好用的话,欢迎给仓库点个 Star ⭐。
|
||||
@@ -0,0 +1,49 @@
|
||||
import os
|
||||
import importlib.util
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# 获取当前包目录的路径
|
||||
current_dir = Path(__file__).parent
|
||||
nodes_dir = current_dir / "nodes"
|
||||
|
||||
# 设置WEB目录路径 - 这是关键配置
|
||||
WEB_DIRECTORY = "./web"
|
||||
|
||||
# 初始化全局映射字典
|
||||
NODE_CLASS_MAPPINGS = {}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {}
|
||||
|
||||
# 遍历nodes目录中的所有Python文件
|
||||
for file_path in nodes_dir.glob("*.py"):
|
||||
# 跳过__init__.py文件
|
||||
if file_path.name == "__init__.py":
|
||||
continue
|
||||
|
||||
# 提取模块名(不含.py后缀)
|
||||
module_name = file_path.stem
|
||||
|
||||
# 使用importlib动态加载模块
|
||||
spec = importlib.util.spec_from_file_location(f"goohaitools.nodes.{module_name}", file_path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
|
||||
try:
|
||||
# 执行模块代码
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
# 检查并合并NODE_CLASS_MAPPINGS
|
||||
if hasattr(module, 'NODE_CLASS_MAPPINGS'):
|
||||
NODE_CLASS_MAPPINGS.update(module.NODE_CLASS_MAPPINGS)
|
||||
|
||||
# 检查并合并NODE_DISPLAY_NAME_MAPPINGS
|
||||
if hasattr(module, 'NODE_DISPLAY_NAME_MAPPINGS'):
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(module.NODE_DISPLAY_NAME_MAPPINGS)
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error loading node module {module_name}: {str(e)}")
|
||||
continue
|
||||
|
||||
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', 'WEB_DIRECTORY']
|
||||
|
||||
# 打印加载信息
|
||||
print(f'\033[92m[GoohaiTools]\033[0m \033[93m{len(NODE_CLASS_MAPPINGS)} nodes\033[0m loaded | \033[94mColorWidget enabled\033[0m')
|
||||
@@ -0,0 +1,23 @@
|
||||
class IgnoreGroupsGuHai:
|
||||
"""忽略多组 孤海 — 通过开关控制工作流中各编组的忽略/旁路状态"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {}}
|
||||
|
||||
RETURN_TYPES = ()
|
||||
FUNCTION = "execute"
|
||||
CATEGORY = "孤海工具箱"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
def execute(self):
|
||||
return ()
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"忽略多组孤海": IgnoreGroupsGuHai,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"忽略多组孤海": "忽略多组 孤海",
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,32 @@
|
||||
[
|
||||
{
|
||||
"id": "vosr",
|
||||
"repo": "ylchen333/ComfyUI-VOSR2",
|
||||
"commit": "c9450b611e6b0e854212b81fecde2da5d088c1bc"
|
||||
},
|
||||
{
|
||||
"id": "core",
|
||||
"repo": "Comfy-Org/ComfyUI",
|
||||
"commit": "856a922befab9d94cb66f36a3dce17234d7a6e31"
|
||||
},
|
||||
{
|
||||
"id": "frontend",
|
||||
"repo": "Comfy-Org/ComfyUI_frontend",
|
||||
"commit": "71d2f2f2b5c6da9dee281836b5b72f3af368966f"
|
||||
},
|
||||
{
|
||||
"id": "rgthree",
|
||||
"repo": "rgthree/rgthree-comfy",
|
||||
"commit": "2c5342a8cb0eaecaabf61435a5f37dd594c510ba"
|
||||
},
|
||||
{
|
||||
"id": "vhs",
|
||||
"repo": "Kosinkadink/ComfyUI-VideoHelperSuite",
|
||||
"commit": "4d907bee61e92c2e65af3bd6383a4e4d356126d1"
|
||||
},
|
||||
{
|
||||
"id": "guhai",
|
||||
"repo": "goohai/Goohaitools-comfyui",
|
||||
"commit": "4e11bd3b8471102eef1cadd809c79c94dc8001ee"
|
||||
}
|
||||
]
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Regis Gaughan, III (rgthree)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,115 @@
|
||||
"""
|
||||
@author: rgthree
|
||||
@title: Comfy Nodes
|
||||
@nickname: rgthree
|
||||
@description: A bunch of nodes I created that I also find useful.
|
||||
"""
|
||||
|
||||
from glob import glob
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import re
|
||||
import random
|
||||
|
||||
import execution
|
||||
|
||||
from .py.log import log, log_known_message
|
||||
from .py.config import get_config_value
|
||||
from .py.server.rgthree_server import *
|
||||
|
||||
from .py.context import RgthreeContext
|
||||
from .py.context_switch import RgthreeContextSwitch
|
||||
from .py.context_switch_big import RgthreeContextSwitchBig
|
||||
from .py.display_any import RgthreeDisplayAny, RgthreeDisplayInt
|
||||
from .py.lora_stack import RgthreeLoraLoaderStack
|
||||
from .py.seed import RgthreeSeed
|
||||
from .py.sdxl_empty_latent_image import RgthreeSDXLEmptyLatentImage
|
||||
from .py.power_prompt import RgthreePowerPrompt
|
||||
from .py.power_prompt_simple import RgthreePowerPromptSimple
|
||||
from .py.image_inset_crop import RgthreeImageInsetCrop
|
||||
from .py.context_big import RgthreeBigContext
|
||||
from .py.dynamic_context import RgthreeDynamicContext
|
||||
from .py.dynamic_context_switch import RgthreeDynamicContextSwitch
|
||||
from .py.ksampler_config import RgthreeKSamplerConfig
|
||||
from .py.sdxl_power_prompt_postive import RgthreeSDXLPowerPromptPositive
|
||||
from .py.sdxl_power_prompt_simple import RgthreeSDXLPowerPromptSimple
|
||||
from .py.any_switch import RgthreeAnySwitch
|
||||
from .py.context_merge import RgthreeContextMerge
|
||||
from .py.context_merge_big import RgthreeContextMergeBig
|
||||
from .py.image_comparer import RgthreeImageComparer
|
||||
from .py.power_lora_loader import RgthreePowerLoraLoader
|
||||
from .py.power_primitive import RgthreePowerPrimitive
|
||||
from .py.image_or_latent_size import RgthreeImageOrLatentSize
|
||||
from .py.image_resize import RgthreeImageResize
|
||||
from .py.power_puter import RgthreePowerPuter
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
RgthreeBigContext.NAME: RgthreeBigContext,
|
||||
RgthreeContext.NAME: RgthreeContext,
|
||||
RgthreeContextSwitch.NAME: RgthreeContextSwitch,
|
||||
RgthreeContextSwitchBig.NAME: RgthreeContextSwitchBig,
|
||||
RgthreeContextMerge.NAME: RgthreeContextMerge,
|
||||
RgthreeContextMergeBig.NAME: RgthreeContextMergeBig,
|
||||
RgthreeDisplayInt.NAME: RgthreeDisplayInt,
|
||||
RgthreeDisplayAny.NAME: RgthreeDisplayAny,
|
||||
RgthreeLoraLoaderStack.NAME: RgthreeLoraLoaderStack,
|
||||
RgthreeSeed.NAME: RgthreeSeed,
|
||||
RgthreeImageInsetCrop.NAME: RgthreeImageInsetCrop,
|
||||
RgthreePowerPrompt.NAME: RgthreePowerPrompt,
|
||||
RgthreePowerPromptSimple.NAME: RgthreePowerPromptSimple,
|
||||
RgthreeKSamplerConfig.NAME: RgthreeKSamplerConfig,
|
||||
RgthreeSDXLEmptyLatentImage.NAME: RgthreeSDXLEmptyLatentImage,
|
||||
RgthreeSDXLPowerPromptPositive.NAME: RgthreeSDXLPowerPromptPositive,
|
||||
RgthreeSDXLPowerPromptSimple.NAME: RgthreeSDXLPowerPromptSimple,
|
||||
RgthreeAnySwitch.NAME: RgthreeAnySwitch,
|
||||
RgthreeImageComparer.NAME: RgthreeImageComparer,
|
||||
RgthreePowerLoraLoader.NAME: RgthreePowerLoraLoader,
|
||||
RgthreePowerPrimitive.NAME: RgthreePowerPrimitive,
|
||||
RgthreeImageOrLatentSize.NAME: RgthreeImageOrLatentSize,
|
||||
RgthreeImageResize.NAME: RgthreeImageResize,
|
||||
RgthreePowerPuter.NAME: RgthreePowerPuter,
|
||||
}
|
||||
|
||||
if get_config_value('unreleased.dynamic_context.enabled') is True:
|
||||
NODE_CLASS_MAPPINGS[RgthreeDynamicContext.NAME] = RgthreeDynamicContext
|
||||
NODE_CLASS_MAPPINGS[RgthreeDynamicContextSwitch.NAME] = RgthreeDynamicContextSwitch
|
||||
|
||||
# WEB_DIRECTORY is the comfyui nodes directory that ComfyUI will link and auto-load.
|
||||
WEB_DIRECTORY = "./web/comfyui"
|
||||
|
||||
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
DIR_WEB = os.path.abspath(os.path.join(THIS_DIR, WEB_DIRECTORY))
|
||||
DIR_PY = os.path.abspath(os.path.join(THIS_DIR, 'py'))
|
||||
|
||||
# remove old directories
|
||||
OLD_DIRS = [
|
||||
os.path.abspath(os.path.join(THIS_DIR, '..', '..', 'web', 'extensions', 'rgthree')),
|
||||
os.path.abspath(os.path.join(THIS_DIR, '..', '..', 'web', 'extensions', 'rgthree-comfy')),
|
||||
]
|
||||
for old_dir in OLD_DIRS:
|
||||
if os.path.exists(old_dir):
|
||||
shutil.rmtree(old_dir)
|
||||
|
||||
__all__ = ['NODE_CLASS_MAPPINGS', 'WEB_DIRECTORY']
|
||||
|
||||
NOT_NODES = ['constants', 'log', 'utils', 'rgthree', 'rgthree_server', 'image_clipbaord', 'config']
|
||||
|
||||
nodes = []
|
||||
for file in glob(os.path.join(DIR_PY, '*.py')) + glob(os.path.join(DIR_WEB, '*.js')):
|
||||
name = os.path.splitext(os.path.basename(file))[0]
|
||||
if name in NOT_NODES or name in nodes:
|
||||
continue
|
||||
if name.startswith('_') or name.startswith('base') or 'utils' in name:
|
||||
continue
|
||||
nodes.append(name)
|
||||
if name == 'display_any':
|
||||
nodes.append('display_int')
|
||||
|
||||
print()
|
||||
adjs = ['exciting', 'extraordinary', 'epic', 'fantastic', 'magnificent']
|
||||
log(f'Loaded {len(nodes)} {random.choice(adjs)} nodes. 🎉', color='BRIGHT_GREEN')
|
||||
print()
|
||||
|
||||
if get_config_value('announcements.comfy-nodes-20.incompatible', True):
|
||||
log_known_message('NODES2.0')
|
||||
@@ -0,0 +1,11 @@
|
||||
|
||||
NAMESPACE='rgthree'
|
||||
|
||||
def get_name(name):
|
||||
return '{} ({})'.format(name, NAMESPACE)
|
||||
|
||||
def get_category(sub_dirs = None):
|
||||
if sub_dirs is None:
|
||||
return NAMESPACE
|
||||
else:
|
||||
return "{}/utils".format(NAMESPACE)
|
||||
@@ -0,0 +1,42 @@
|
||||
from nodes import PreviewImage
|
||||
|
||||
from .constants import get_category, get_name
|
||||
|
||||
|
||||
class RgthreeImageComparer(PreviewImage):
|
||||
"""A node that compares two images in the UI."""
|
||||
|
||||
NAME = get_name('Image Comparer')
|
||||
CATEGORY = get_category()
|
||||
FUNCTION = "compare_images"
|
||||
DESCRIPTION = "Compares two images with a hover slider, or click from properties."
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls): # pylint: disable = invalid-name, missing-function-docstring
|
||||
return {
|
||||
"required": {},
|
||||
"optional": {
|
||||
"image_a": ("IMAGE",),
|
||||
"image_b": ("IMAGE",),
|
||||
},
|
||||
"hidden": {
|
||||
"prompt": "PROMPT",
|
||||
"extra_pnginfo": "EXTRA_PNGINFO"
|
||||
},
|
||||
}
|
||||
|
||||
def compare_images(self,
|
||||
image_a=None,
|
||||
image_b=None,
|
||||
filename_prefix="rgthree.compare.",
|
||||
prompt=None,
|
||||
extra_pnginfo=None):
|
||||
|
||||
result = { "ui": { "a_images":[], "b_images": [] } }
|
||||
if image_a is not None and len(image_a) > 0:
|
||||
result['ui']['a_images'] = self.save_images(image_a, filename_prefix, prompt, extra_pnginfo)['ui']['images']
|
||||
|
||||
if image_b is not None and len(image_b) > 0:
|
||||
result['ui']['b_images'] = self.save_images(image_b, filename_prefix, prompt, extra_pnginfo)['ui']['images']
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,365 @@
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
import { RgthreeBaseServerNode } from "./base_node.js";
|
||||
import { NodeTypesString } from "./constants.js";
|
||||
import { addConnectionLayoutSupport } from "./utils.js";
|
||||
import { RgthreeBaseWidget } from "./utils_widgets.js";
|
||||
import { measureText } from "./utils_canvas.js";
|
||||
function imageDataToUrl(data) {
|
||||
return api.apiURL(`/view?filename=${encodeURIComponent(data.filename)}&type=${data.type}&subfolder=${data.subfolder}${app.getPreviewFormatParam()}${app.getRandParam()}`);
|
||||
}
|
||||
export class RgthreeImageComparer extends RgthreeBaseServerNode {
|
||||
constructor(title = RgthreeImageComparer.title) {
|
||||
super(title);
|
||||
this.imageIndex = 0;
|
||||
this.imgs = [];
|
||||
this.serialize_widgets = true;
|
||||
this.isPointerDown = false;
|
||||
this.isPointerOver = false;
|
||||
this.pointerOverPos = [0, 0];
|
||||
this.canvasWidget = null;
|
||||
this.properties["comparer_mode"] = "Slide";
|
||||
}
|
||||
onExecuted(output) {
|
||||
var _a;
|
||||
(_a = super.onExecuted) === null || _a === void 0 ? void 0 : _a.call(this, output);
|
||||
if ("images" in output) {
|
||||
this.canvasWidget.value = {
|
||||
images: (output.images || []).map((d, i) => {
|
||||
return {
|
||||
name: i === 0 ? "A" : "B",
|
||||
selected: true,
|
||||
url: imageDataToUrl(d),
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
else {
|
||||
output.a_images = output.a_images || [];
|
||||
output.b_images = output.b_images || [];
|
||||
const imagesToChoose = [];
|
||||
const multiple = output.a_images.length + output.b_images.length > 2;
|
||||
for (const [i, d] of output.a_images.entries()) {
|
||||
imagesToChoose.push({
|
||||
name: output.a_images.length > 1 || multiple ? `A${i + 1}` : "A",
|
||||
selected: i === 0,
|
||||
url: imageDataToUrl(d),
|
||||
});
|
||||
}
|
||||
for (const [i, d] of output.b_images.entries()) {
|
||||
imagesToChoose.push({
|
||||
name: output.b_images.length > 1 || multiple ? `B${i + 1}` : "B",
|
||||
selected: i === 0,
|
||||
url: imageDataToUrl(d),
|
||||
});
|
||||
}
|
||||
this.canvasWidget.value = { images: imagesToChoose };
|
||||
}
|
||||
}
|
||||
onSerialize(serialised) {
|
||||
var _a;
|
||||
super.onSerialize && super.onSerialize(serialised);
|
||||
for (let [index, widget_value] of (serialised.widgets_values || []).entries()) {
|
||||
if (((_a = this.widgets[index]) === null || _a === void 0 ? void 0 : _a.name) === "rgthree_comparer") {
|
||||
serialised.widgets_values[index] = this.widgets[index].value.images.map((d) => {
|
||||
d = { ...d };
|
||||
delete d.img;
|
||||
return d;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
onNodeCreated() {
|
||||
this.canvasWidget = this.addCustomWidget(new RgthreeImageComparerWidget("rgthree_comparer", this));
|
||||
this.setSize(this.computeSize());
|
||||
this.setDirtyCanvas(true, true);
|
||||
}
|
||||
setIsPointerDown(down = this.isPointerDown) {
|
||||
const newIsDown = down && !!app.canvas.pointer_is_down;
|
||||
if (this.isPointerDown !== newIsDown) {
|
||||
this.isPointerDown = newIsDown;
|
||||
this.setDirtyCanvas(true, false);
|
||||
}
|
||||
this.imageIndex = this.isPointerDown ? 1 : 0;
|
||||
if (this.isPointerDown) {
|
||||
requestAnimationFrame(() => {
|
||||
this.setIsPointerDown();
|
||||
});
|
||||
}
|
||||
}
|
||||
onMouseDown(event, pos, canvas) {
|
||||
var _a;
|
||||
(_a = super.onMouseDown) === null || _a === void 0 ? void 0 : _a.call(this, event, pos, canvas);
|
||||
this.setIsPointerDown(true);
|
||||
return false;
|
||||
}
|
||||
onMouseEnter(event) {
|
||||
var _a;
|
||||
(_a = super.onMouseEnter) === null || _a === void 0 ? void 0 : _a.call(this, event);
|
||||
this.setIsPointerDown(!!app.canvas.pointer_is_down);
|
||||
this.isPointerOver = true;
|
||||
}
|
||||
onMouseLeave(event) {
|
||||
var _a;
|
||||
(_a = super.onMouseLeave) === null || _a === void 0 ? void 0 : _a.call(this, event);
|
||||
this.setIsPointerDown(false);
|
||||
this.isPointerOver = false;
|
||||
}
|
||||
onMouseMove(event, pos, canvas) {
|
||||
var _a;
|
||||
(_a = super.onMouseMove) === null || _a === void 0 ? void 0 : _a.call(this, event, pos, canvas);
|
||||
this.pointerOverPos = [...pos];
|
||||
this.imageIndex = this.pointerOverPos[0] > this.size[0] / 2 ? 1 : 0;
|
||||
}
|
||||
getHelp() {
|
||||
return `
|
||||
<p>
|
||||
The ${this.type.replace("(rgthree)", "")} node compares two images on top of each other.
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<p>
|
||||
<strong>Notes</strong>
|
||||
</p>
|
||||
<ul>
|
||||
<li><p>
|
||||
The right-click menu may show image options (Open Image, Save Image, etc.) which will
|
||||
correspond to the first image (image_a) if clicked on the left-half of the node, or
|
||||
the second image if on the right half of the node.
|
||||
</p></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<p>
|
||||
<strong>Inputs</strong>
|
||||
</p>
|
||||
<ul>
|
||||
<li><p>
|
||||
<code>image_a</code> <i>Optional.</i> The first image to use to compare.
|
||||
image_a.
|
||||
</p></li>
|
||||
<li><p>
|
||||
<code>image_b</code> <i>Optional.</i> The second image to use to compare.
|
||||
</p></li>
|
||||
<li><p>
|
||||
<b>Note</b> <code>image_a</code> and <code>image_b</code> work best when a single
|
||||
image is provided. However, if each/either are a batch, you can choose which item
|
||||
from each batch are chosen to be compared. If either <code>image_a</code> or
|
||||
<code>image_b</code> are not provided, the node will choose the first two from the
|
||||
provided input if it's a batch, otherwise only show the single image (just as
|
||||
Preview Image would).
|
||||
</p></li>
|
||||
</ul>
|
||||
</li>
|
||||
<li>
|
||||
<p>
|
||||
<strong>Properties.</strong> You can change the following properties (by right-clicking
|
||||
on the node, and select "Properties" or "Properties Panel" from the menu):
|
||||
</p>
|
||||
<ul>
|
||||
<li><p>
|
||||
<code>comparer_mode</code> - Choose between "Slide" and "Click". Defaults to "Slide".
|
||||
</p></li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>`;
|
||||
}
|
||||
static setUp(comfyClass, nodeData) {
|
||||
RgthreeBaseServerNode.registerForOverride(comfyClass, nodeData, RgthreeImageComparer);
|
||||
}
|
||||
static onRegisteredForOverride(comfyClass) {
|
||||
addConnectionLayoutSupport(RgthreeImageComparer, app, [
|
||||
["Left", "Right"],
|
||||
["Right", "Left"],
|
||||
]);
|
||||
setTimeout(() => {
|
||||
RgthreeImageComparer.category = comfyClass.category;
|
||||
});
|
||||
}
|
||||
}
|
||||
RgthreeImageComparer.title = NodeTypesString.IMAGE_COMPARER;
|
||||
RgthreeImageComparer.type = NodeTypesString.IMAGE_COMPARER;
|
||||
RgthreeImageComparer.comfyClass = NodeTypesString.IMAGE_COMPARER;
|
||||
RgthreeImageComparer["@comparer_mode"] = {
|
||||
type: "combo",
|
||||
values: ["Slide", "Click"],
|
||||
};
|
||||
class RgthreeImageComparerWidget extends RgthreeBaseWidget {
|
||||
constructor(name, node) {
|
||||
super(name);
|
||||
this.type = "custom";
|
||||
this.hitAreas = {};
|
||||
this.selected = [];
|
||||
this._value = { images: [] };
|
||||
this.node = node;
|
||||
}
|
||||
set value(v) {
|
||||
let cleanedVal;
|
||||
if (Array.isArray(v)) {
|
||||
cleanedVal = v.map((d, i) => {
|
||||
if (!d || typeof d === "string") {
|
||||
d = { url: d, name: i == 0 ? "A" : "B", selected: true };
|
||||
}
|
||||
return d;
|
||||
});
|
||||
}
|
||||
else {
|
||||
cleanedVal = v.images || [];
|
||||
}
|
||||
if (cleanedVal.length > 2) {
|
||||
const hasAAndB = cleanedVal.some((i) => i.name.startsWith("A")) &&
|
||||
cleanedVal.some((i) => i.name.startsWith("B"));
|
||||
if (!hasAAndB) {
|
||||
cleanedVal = [cleanedVal[0], cleanedVal[1]];
|
||||
}
|
||||
}
|
||||
let selected = cleanedVal.filter((d) => d.selected);
|
||||
if (!selected.length && cleanedVal.length) {
|
||||
cleanedVal[0].selected = true;
|
||||
}
|
||||
selected = cleanedVal.filter((d) => d.selected);
|
||||
if (selected.length === 1 && cleanedVal.length > 1) {
|
||||
cleanedVal.find((d) => !d.selected).selected = true;
|
||||
}
|
||||
this._value.images = cleanedVal;
|
||||
selected = cleanedVal.filter((d) => d.selected);
|
||||
this.setSelected(selected);
|
||||
}
|
||||
get value() {
|
||||
return this._value;
|
||||
}
|
||||
setSelected(selected) {
|
||||
this._value.images.forEach((d) => (d.selected = false));
|
||||
this.node.imgs.length = 0;
|
||||
for (const sel of selected) {
|
||||
if (!sel.img) {
|
||||
sel.img = new Image();
|
||||
sel.img.src = sel.url;
|
||||
this.node.imgs.push(sel.img);
|
||||
}
|
||||
sel.selected = true;
|
||||
}
|
||||
this.selected = selected;
|
||||
}
|
||||
draw(ctx, node, width, y) {
|
||||
var _a;
|
||||
this.hitAreas = {};
|
||||
if (this.value.images.length > 2) {
|
||||
ctx.textAlign = "left";
|
||||
ctx.textBaseline = "top";
|
||||
ctx.font = `14px Arial`;
|
||||
const drawData = [];
|
||||
const spacing = 5;
|
||||
let x = 0;
|
||||
for (const img of this.value.images) {
|
||||
const width = measureText(ctx, img.name);
|
||||
drawData.push({
|
||||
img,
|
||||
text: img.name,
|
||||
x,
|
||||
width: measureText(ctx, img.name),
|
||||
});
|
||||
x += width + spacing;
|
||||
}
|
||||
x = (node.size[0] - (x - spacing)) / 2;
|
||||
for (const d of drawData) {
|
||||
ctx.fillStyle = d.img.selected ? "rgba(180, 180, 180, 1)" : "rgba(180, 180, 180, 0.5)";
|
||||
ctx.fillText(d.text, x, y);
|
||||
this.hitAreas[d.text] = {
|
||||
bounds: [x, y, d.width, 14],
|
||||
data: d.img,
|
||||
onDown: this.onSelectionDown,
|
||||
};
|
||||
x += d.width + spacing;
|
||||
}
|
||||
y += 20;
|
||||
}
|
||||
if (((_a = node.properties) === null || _a === void 0 ? void 0 : _a["comparer_mode"]) === "Click") {
|
||||
this.drawImage(ctx, this.selected[this.node.isPointerDown ? 1 : 0], y);
|
||||
}
|
||||
else {
|
||||
this.drawImage(ctx, this.selected[0], y);
|
||||
if (node.isPointerOver) {
|
||||
this.drawImage(ctx, this.selected[1], y, this.node.pointerOverPos[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
onSelectionDown(event, pos, node, bounds) {
|
||||
const selected = [...this.selected];
|
||||
if (bounds === null || bounds === void 0 ? void 0 : bounds.data.name.startsWith("A")) {
|
||||
selected[0] = bounds.data;
|
||||
}
|
||||
else if (bounds === null || bounds === void 0 ? void 0 : bounds.data.name.startsWith("B")) {
|
||||
selected[1] = bounds.data;
|
||||
}
|
||||
this.setSelected(selected);
|
||||
}
|
||||
drawImage(ctx, image, y, cropX) {
|
||||
var _a, _b;
|
||||
if (!((_a = image === null || image === void 0 ? void 0 : image.img) === null || _a === void 0 ? void 0 : _a.naturalWidth) || !((_b = image === null || image === void 0 ? void 0 : image.img) === null || _b === void 0 ? void 0 : _b.naturalHeight)) {
|
||||
return;
|
||||
}
|
||||
let [nodeWidth, nodeHeight] = this.node.size;
|
||||
const imageAspect = (image === null || image === void 0 ? void 0 : image.img.naturalWidth) / (image === null || image === void 0 ? void 0 : image.img.naturalHeight);
|
||||
let height = nodeHeight - y;
|
||||
const widgetAspect = nodeWidth / height;
|
||||
let targetWidth, targetHeight;
|
||||
let offsetX = 0;
|
||||
if (imageAspect > widgetAspect) {
|
||||
targetWidth = nodeWidth;
|
||||
targetHeight = nodeWidth / imageAspect;
|
||||
}
|
||||
else {
|
||||
targetHeight = height;
|
||||
targetWidth = height * imageAspect;
|
||||
offsetX = (nodeWidth - targetWidth) / 2;
|
||||
}
|
||||
const widthMultiplier = (image === null || image === void 0 ? void 0 : image.img.naturalWidth) / targetWidth;
|
||||
const sourceX = 0;
|
||||
const sourceY = 0;
|
||||
const sourceWidth = cropX != null ? (cropX - offsetX) * widthMultiplier : image === null || image === void 0 ? void 0 : image.img.naturalWidth;
|
||||
const sourceHeight = image === null || image === void 0 ? void 0 : image.img.naturalHeight;
|
||||
const destX = (nodeWidth - targetWidth) / 2;
|
||||
const destY = y + (height - targetHeight) / 2;
|
||||
const destWidth = cropX != null ? cropX - offsetX : targetWidth;
|
||||
const destHeight = targetHeight;
|
||||
ctx.save();
|
||||
ctx.beginPath();
|
||||
let globalCompositeOperation = ctx.globalCompositeOperation;
|
||||
if (cropX) {
|
||||
ctx.rect(destX, destY, destWidth, destHeight);
|
||||
ctx.clip();
|
||||
}
|
||||
ctx.drawImage(image === null || image === void 0 ? void 0 : image.img, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
|
||||
if (cropX != null && cropX >= (nodeWidth - targetWidth) / 2 && cropX <= targetWidth + offsetX) {
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(cropX, destY);
|
||||
ctx.lineTo(cropX, destY + destHeight);
|
||||
ctx.globalCompositeOperation = "difference";
|
||||
ctx.strokeStyle = "rgba(255,255,255, 1)";
|
||||
ctx.stroke();
|
||||
}
|
||||
ctx.globalCompositeOperation = globalCompositeOperation;
|
||||
ctx.restore();
|
||||
}
|
||||
computeSize(width) {
|
||||
return [width, 20];
|
||||
}
|
||||
serializeValue(node, index) {
|
||||
const v = [];
|
||||
for (const data of this._value.images) {
|
||||
const d = { ...data };
|
||||
delete d.img;
|
||||
v.push(d);
|
||||
}
|
||||
return { images: v };
|
||||
}
|
||||
}
|
||||
app.registerExtension({
|
||||
name: "rgthree.ImageComparer",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name === RgthreeImageComparer.type) {
|
||||
RgthreeImageComparer.setUp(nodeType, nodeData);
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,301 @@
|
||||
{
|
||||
"sources": [
|
||||
{
|
||||
"id": "vosr",
|
||||
"file": "__init__.py",
|
||||
"local_file": "vosr____init__.py",
|
||||
"url": "https://raw.githubusercontent.com/ylchen333/ComfyUI-VOSR2/c9450b611e6b0e854212b81fecde2da5d088c1bc/__init__.py",
|
||||
"commit": "c9450b611e6b0e854212b81fecde2da5d088c1bc",
|
||||
"sha256": "4da7ceb543f7ad94b9207df61733ab083471071f4e0ebcbdd600b71bd43a65f3",
|
||||
"git_blob_sha1": "5e1fd16823138a5e78531927ff563a545c0cbc91"
|
||||
},
|
||||
{
|
||||
"id": "vosr",
|
||||
"file": "nodes_vosr.py",
|
||||
"local_file": "vosr__nodes_vosr.py",
|
||||
"url": "https://raw.githubusercontent.com/ylchen333/ComfyUI-VOSR2/c9450b611e6b0e854212b81fecde2da5d088c1bc/nodes_vosr.py",
|
||||
"commit": "c9450b611e6b0e854212b81fecde2da5d088c1bc",
|
||||
"sha256": "ee4712cd8ea94d5c70e2f13913c2e775673021dce3f42a954ffea2d6b11a4645",
|
||||
"git_blob_sha1": "c559e834e45646ee6f6aaa6f3ccd59a9536cdf1b"
|
||||
},
|
||||
{
|
||||
"id": "vosr",
|
||||
"file": "loader.py",
|
||||
"local_file": "vosr__loader.py",
|
||||
"url": "https://raw.githubusercontent.com/ylchen333/ComfyUI-VOSR2/c9450b611e6b0e854212b81fecde2da5d088c1bc/loader.py",
|
||||
"commit": "c9450b611e6b0e854212b81fecde2da5d088c1bc",
|
||||
"sha256": "629cc249598001d44bb7516f5f0f9d8d7fc2685aebf3a254e9c2c81811dac196",
|
||||
"git_blob_sha1": "9dd229cc8203a02e628b900af4253dbce2bc997d"
|
||||
},
|
||||
{
|
||||
"id": "vosr",
|
||||
"file": "inference.py",
|
||||
"local_file": "vosr__inference.py",
|
||||
"url": "https://raw.githubusercontent.com/ylchen333/ComfyUI-VOSR2/c9450b611e6b0e854212b81fecde2da5d088c1bc/inference.py",
|
||||
"commit": "c9450b611e6b0e854212b81fecde2da5d088c1bc",
|
||||
"sha256": "4b050e154dc9dfde775b2537b6b35b102d8f0a84a0b27d488050305391212a73",
|
||||
"git_blob_sha1": "ccbcfd4afab0ba4dac4ff003f9c2250ebeb8bf27"
|
||||
},
|
||||
{
|
||||
"id": "vosr",
|
||||
"file": "color.py",
|
||||
"local_file": "vosr__color.py",
|
||||
"url": "https://raw.githubusercontent.com/ylchen333/ComfyUI-VOSR2/c9450b611e6b0e854212b81fecde2da5d088c1bc/color.py",
|
||||
"commit": "c9450b611e6b0e854212b81fecde2da5d088c1bc",
|
||||
"sha256": "9154368749c0d77bcdecb649c9534958a9a2c3a81c1d5045330e2e6062f69aa2",
|
||||
"git_blob_sha1": "a6e60a408d49873b5408fb305dee919ac1a4fc5a"
|
||||
},
|
||||
{
|
||||
"id": "vosr",
|
||||
"file": "tiled_vae.py",
|
||||
"local_file": "vosr__tiled_vae.py",
|
||||
"url": "https://raw.githubusercontent.com/ylchen333/ComfyUI-VOSR2/c9450b611e6b0e854212b81fecde2da5d088c1bc/tiled_vae.py",
|
||||
"commit": "c9450b611e6b0e854212b81fecde2da5d088c1bc",
|
||||
"sha256": "3540cae5ac7680df23f07ac49078a4aad1d107bd193adb56aac278bfa6a0c0ad",
|
||||
"git_blob_sha1": "380fb39798c2900dd3f7e2b6ce84026f4c09556e"
|
||||
},
|
||||
{
|
||||
"id": "vosr",
|
||||
"file": "LICENSE",
|
||||
"local_file": "vosr__LICENSE",
|
||||
"url": "https://raw.githubusercontent.com/ylchen333/ComfyUI-VOSR2/c9450b611e6b0e854212b81fecde2da5d088c1bc/LICENSE",
|
||||
"commit": "c9450b611e6b0e854212b81fecde2da5d088c1bc",
|
||||
"sha256": "de4d0a8b95787defcc0ccaaa783e77750c243f3f0d29f75a7e5e9bf3a5f84863",
|
||||
"git_blob_sha1": "ada5dc2bfdbe0232c59a18747190a14d3c5189ab"
|
||||
},
|
||||
{
|
||||
"id": "core",
|
||||
"file": "nodes.py",
|
||||
"local_file": "core__nodes.py",
|
||||
"url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/856a922befab9d94cb66f36a3dce17234d7a6e31/nodes.py",
|
||||
"commit": "856a922befab9d94cb66f36a3dce17234d7a6e31",
|
||||
"sha256": "f7b6a909bf9a47296b974b730e5db0ec2137a3c6a64dda045970951d7382d4c7",
|
||||
"git_blob_sha1": "038b88350daef6b0f3dbcda8d112a6e1655f4887"
|
||||
},
|
||||
{
|
||||
"id": "core",
|
||||
"file": "comfy_extras/nodes_images.py",
|
||||
"local_file": "core__comfy_extras__nodes_images.py",
|
||||
"url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/856a922befab9d94cb66f36a3dce17234d7a6e31/comfy_extras/nodes_images.py",
|
||||
"commit": "856a922befab9d94cb66f36a3dce17234d7a6e31",
|
||||
"sha256": "c1503a3949530d5708948329e050aa89aedaf739678cdb4084e40d95bea46a60",
|
||||
"git_blob_sha1": "91a3f990c1e1e34e9782f5f2c072ae2c81b1d459"
|
||||
},
|
||||
{
|
||||
"id": "core",
|
||||
"file": "comfy_api/latest/_io.py",
|
||||
"local_file": "core__comfy_api__latest___io.py",
|
||||
"url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/856a922befab9d94cb66f36a3dce17234d7a6e31/comfy_api/latest/_io.py",
|
||||
"commit": "856a922befab9d94cb66f36a3dce17234d7a6e31",
|
||||
"sha256": "55391c45bee9cfd821c7c86a23ab0f9e12ce9b5b40d77d48308c1d3698ed4080",
|
||||
"git_blob_sha1": "4c062d8aabcfdf056425737d35f153b6a67522f8"
|
||||
},
|
||||
{
|
||||
"id": "core",
|
||||
"file": "folder_paths.py",
|
||||
"local_file": "core__folder_paths.py",
|
||||
"url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/856a922befab9d94cb66f36a3dce17234d7a6e31/folder_paths.py",
|
||||
"commit": "856a922befab9d94cb66f36a3dce17234d7a6e31",
|
||||
"sha256": "b748be5d1e068ad673f6c4de069fb6b7b723405c40ae3c3c44465d416f7df2db",
|
||||
"git_blob_sha1": "6723e52c867c57003e9ba4ed53ae58f8d79a7752"
|
||||
},
|
||||
{
|
||||
"id": "core",
|
||||
"file": "LICENSE",
|
||||
"local_file": "core__LICENSE",
|
||||
"url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI/856a922befab9d94cb66f36a3dce17234d7a6e31/LICENSE",
|
||||
"commit": "856a922befab9d94cb66f36a3dce17234d7a6e31",
|
||||
"sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986",
|
||||
"git_blob_sha1": "f288702d2fa16d3cdf0035b15a9fcbc552cd88e7"
|
||||
},
|
||||
{
|
||||
"id": "frontend",
|
||||
"file": "src/scripts/widgets.ts",
|
||||
"local_file": "frontend__src__scripts__widgets.ts",
|
||||
"url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/71d2f2f2b5c6da9dee281836b5b72f3af368966f/src/scripts/widgets.ts",
|
||||
"commit": "71d2f2f2b5c6da9dee281836b5b72f3af368966f",
|
||||
"sha256": "5f3d26cd1626c72ec4d3f7cc806345d0c771afb86daf7127935ff26a7a1f3d54",
|
||||
"git_blob_sha1": "20bcdf0e541f7f38803be6ad5e9cc8fe411a9432"
|
||||
},
|
||||
{
|
||||
"id": "frontend",
|
||||
"file": "src/scripts/valueControl.ts",
|
||||
"local_file": "frontend__src__scripts__valueControl.ts",
|
||||
"url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/71d2f2f2b5c6da9dee281836b5b72f3af368966f/src/scripts/valueControl.ts",
|
||||
"commit": "71d2f2f2b5c6da9dee281836b5b72f3af368966f",
|
||||
"sha256": "57f607f240896f28663c40f02ab16bb01d3914470be486f6c58041e4032d87b1",
|
||||
"git_blob_sha1": "b3e29fc07bf4241c41df92de92d4413082679fbb"
|
||||
},
|
||||
{
|
||||
"id": "frontend",
|
||||
"file": "src/extensions/core/uploadImage.ts",
|
||||
"local_file": "frontend__src__extensions__core__uploadImage.ts",
|
||||
"url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/71d2f2f2b5c6da9dee281836b5b72f3af368966f/src/extensions/core/uploadImage.ts",
|
||||
"commit": "71d2f2f2b5c6da9dee281836b5b72f3af368966f",
|
||||
"sha256": "48d062c2ee95bd77c537c539e6c8f8bc03bd71dcec94c5b82487c014ea3e9c06",
|
||||
"git_blob_sha1": "58e43bb218171534c4713bdced29171ecb96d903"
|
||||
},
|
||||
{
|
||||
"id": "frontend",
|
||||
"file": "src/lib/litegraph/src/LGraphNode.ts",
|
||||
"local_file": "frontend__src__lib__litegraph__src__LGraphNode.ts",
|
||||
"url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/71d2f2f2b5c6da9dee281836b5b72f3af368966f/src/lib/litegraph/src/LGraphNode.ts",
|
||||
"commit": "71d2f2f2b5c6da9dee281836b5b72f3af368966f",
|
||||
"sha256": "d6263d56f28a5e6c5a95a3a263fe0d6ffe4083a981c01a14ec4ebfca43487e50",
|
||||
"git_blob_sha1": "38723cce556962cb80456239df383d49469134d9"
|
||||
},
|
||||
{
|
||||
"id": "frontend",
|
||||
"file": "LICENSE",
|
||||
"local_file": "frontend__LICENSE",
|
||||
"url": "https://raw.githubusercontent.com/Comfy-Org/ComfyUI_frontend/71d2f2f2b5c6da9dee281836b5b72f3af368966f/LICENSE",
|
||||
"commit": "71d2f2f2b5c6da9dee281836b5b72f3af368966f",
|
||||
"sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986",
|
||||
"git_blob_sha1": "f288702d2fa16d3cdf0035b15a9fcbc552cd88e7"
|
||||
},
|
||||
{
|
||||
"id": "rgthree",
|
||||
"file": "__init__.py",
|
||||
"local_file": "rgthree____init__.py",
|
||||
"url": "https://raw.githubusercontent.com/rgthree/rgthree-comfy/2c5342a8cb0eaecaabf61435a5f37dd594c510ba/__init__.py",
|
||||
"commit": "2c5342a8cb0eaecaabf61435a5f37dd594c510ba",
|
||||
"sha256": "c51fdbaf7ed4c397be33413b7464dc3653714711d8a77d4c3e9a410a9d3de152",
|
||||
"git_blob_sha1": "3211d8926c52792d6d99096b4e747315ba9e615c"
|
||||
},
|
||||
{
|
||||
"id": "rgthree",
|
||||
"file": "py/image_comparer.py",
|
||||
"local_file": "rgthree__py__image_comparer.py",
|
||||
"url": "https://raw.githubusercontent.com/rgthree/rgthree-comfy/2c5342a8cb0eaecaabf61435a5f37dd594c510ba/py/image_comparer.py",
|
||||
"commit": "2c5342a8cb0eaecaabf61435a5f37dd594c510ba",
|
||||
"sha256": "43ccce9b6f9413d5196ce4a7a3ef544969ae1ce2b52c44345f6cc8fb28c596fc",
|
||||
"git_blob_sha1": "079ebdbf6051fa86cf89f75f55f8502904d0c93f"
|
||||
},
|
||||
{
|
||||
"id": "rgthree",
|
||||
"file": "py/constants.py",
|
||||
"local_file": "rgthree__py__constants.py",
|
||||
"url": "https://raw.githubusercontent.com/rgthree/rgthree-comfy/2c5342a8cb0eaecaabf61435a5f37dd594c510ba/py/constants.py",
|
||||
"commit": "2c5342a8cb0eaecaabf61435a5f37dd594c510ba",
|
||||
"sha256": "50dee946013b1d88d01fe9d63c2a7ab4d4c59be218cf80171f3542b43f0d8558",
|
||||
"git_blob_sha1": "73b7d687ad24999c3b441f2c2ef39e4e8b3f3d54"
|
||||
},
|
||||
{
|
||||
"id": "rgthree",
|
||||
"file": "web/comfyui/image_comparer.js",
|
||||
"local_file": "rgthree__web__comfyui__image_comparer.js",
|
||||
"url": "https://raw.githubusercontent.com/rgthree/rgthree-comfy/2c5342a8cb0eaecaabf61435a5f37dd594c510ba/web/comfyui/image_comparer.js",
|
||||
"commit": "2c5342a8cb0eaecaabf61435a5f37dd594c510ba",
|
||||
"sha256": "b6dd39b71a2722774ecad101e12823220c6905f9f2a3d1cefca077e1aaa08a49",
|
||||
"git_blob_sha1": "4c5d6b8d8f33f53387d8e385ba6d9ffe4ed4caba"
|
||||
},
|
||||
{
|
||||
"id": "rgthree",
|
||||
"file": "LICENSE",
|
||||
"local_file": "rgthree__LICENSE",
|
||||
"url": "https://raw.githubusercontent.com/rgthree/rgthree-comfy/2c5342a8cb0eaecaabf61435a5f37dd594c510ba/LICENSE",
|
||||
"commit": "2c5342a8cb0eaecaabf61435a5f37dd594c510ba",
|
||||
"sha256": "b34faf7c3e2975fe08d0169958e2b39f076d4d4289cbe2560dd7dd5b1a613ed1",
|
||||
"git_blob_sha1": "5a4eb87c0791b74af3db40c2a4d362469a8b6b43"
|
||||
},
|
||||
{
|
||||
"id": "vhs",
|
||||
"file": "__init__.py",
|
||||
"local_file": "vhs____init__.py",
|
||||
"url": "https://raw.githubusercontent.com/Kosinkadink/ComfyUI-VideoHelperSuite/4d907bee61e92c2e65af3bd6383a4e4d356126d1/__init__.py",
|
||||
"commit": "4d907bee61e92c2e65af3bd6383a4e4d356126d1",
|
||||
"sha256": "d3e74626bfdd628d0e96b190b2c07e25fa1e5ee9f1f402c7c650446f86b0838f",
|
||||
"git_blob_sha1": "9fa995f0ac7e296a62bcba9df68b5250a0f7d041"
|
||||
},
|
||||
{
|
||||
"id": "vhs",
|
||||
"file": "videohelpersuite/nodes.py",
|
||||
"local_file": "vhs__videohelpersuite__nodes.py",
|
||||
"url": "https://raw.githubusercontent.com/Kosinkadink/ComfyUI-VideoHelperSuite/4d907bee61e92c2e65af3bd6383a4e4d356126d1/videohelpersuite/nodes.py",
|
||||
"commit": "4d907bee61e92c2e65af3bd6383a4e4d356126d1",
|
||||
"sha256": "1c306fbc759ea4e09534422efd2603f50877c4674ff101e876e1d33426d46218",
|
||||
"git_blob_sha1": "496bf94e41ea11b8a9315ab92d9ea386636e6115"
|
||||
},
|
||||
{
|
||||
"id": "vhs",
|
||||
"file": "videohelpersuite/load_video_nodes.py",
|
||||
"local_file": "vhs__videohelpersuite__load_video_nodes.py",
|
||||
"url": "https://raw.githubusercontent.com/Kosinkadink/ComfyUI-VideoHelperSuite/4d907bee61e92c2e65af3bd6383a4e4d356126d1/videohelpersuite/load_video_nodes.py",
|
||||
"commit": "4d907bee61e92c2e65af3bd6383a4e4d356126d1",
|
||||
"sha256": "dd0e40047e60eaae7687e1fea812fd94b094187a9808819b74b1130b1819243a",
|
||||
"git_blob_sha1": "5c6bd0b40ac75a8d596a4b3c86253420e8d56bb4"
|
||||
},
|
||||
{
|
||||
"id": "vhs",
|
||||
"file": "videohelpersuite/utils.py",
|
||||
"local_file": "vhs__videohelpersuite__utils.py",
|
||||
"url": "https://raw.githubusercontent.com/Kosinkadink/ComfyUI-VideoHelperSuite/4d907bee61e92c2e65af3bd6383a4e4d356126d1/videohelpersuite/utils.py",
|
||||
"commit": "4d907bee61e92c2e65af3bd6383a4e4d356126d1",
|
||||
"sha256": "ea3d02e0f41dc6b59685fcf6de9217d4b7729766e05e44200433c74e75466a6a",
|
||||
"git_blob_sha1": "5b35ad47fa3d1412773ab561598031ba6a3b38bc"
|
||||
},
|
||||
{
|
||||
"id": "vhs",
|
||||
"file": "video_formats/h264-mp4.json",
|
||||
"local_file": "vhs__video_formats__h264-mp4.json",
|
||||
"url": "https://raw.githubusercontent.com/Kosinkadink/ComfyUI-VideoHelperSuite/4d907bee61e92c2e65af3bd6383a4e4d356126d1/video_formats/h264-mp4.json",
|
||||
"commit": "4d907bee61e92c2e65af3bd6383a4e4d356126d1",
|
||||
"sha256": "4c15a42816ccbb06cb8a2fb02f8d1831d622c8531b26e432959ec80e50f7b8bc",
|
||||
"git_blob_sha1": "4aa0bd57c6a4cc65334d82e5cdaa7aadb8372321"
|
||||
},
|
||||
{
|
||||
"id": "vhs",
|
||||
"file": "web/js/VHS.core.js",
|
||||
"local_file": "vhs__web__js__VHS.core.js",
|
||||
"url": "https://raw.githubusercontent.com/Kosinkadink/ComfyUI-VideoHelperSuite/4d907bee61e92c2e65af3bd6383a4e4d356126d1/web/js/VHS.core.js",
|
||||
"commit": "4d907bee61e92c2e65af3bd6383a4e4d356126d1",
|
||||
"sha256": "fd0f5e78c3fb40dad605105d6d07fd629d166f6ccb4a9d04a20b5cd1b82b13a1",
|
||||
"git_blob_sha1": "8d7f2c877ad215cb61d4fdd823f18b9d26ccab2e"
|
||||
},
|
||||
{
|
||||
"id": "vhs",
|
||||
"file": "LICENSE",
|
||||
"local_file": "vhs__LICENSE",
|
||||
"url": "https://raw.githubusercontent.com/Kosinkadink/ComfyUI-VideoHelperSuite/4d907bee61e92c2e65af3bd6383a4e4d356126d1/LICENSE",
|
||||
"commit": "4d907bee61e92c2e65af3bd6383a4e4d356126d1",
|
||||
"sha256": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986",
|
||||
"git_blob_sha1": "f288702d2fa16d3cdf0035b15a9fcbc552cd88e7"
|
||||
},
|
||||
{
|
||||
"id": "guhai",
|
||||
"file": "__init__.py",
|
||||
"local_file": "guhai____init__.py",
|
||||
"url": "https://raw.githubusercontent.com/goohai/Goohaitools-comfyui/4e11bd3b8471102eef1cadd809c79c94dc8001ee/__init__.py",
|
||||
"commit": "4e11bd3b8471102eef1cadd809c79c94dc8001ee",
|
||||
"sha256": "d1cdc5dce665f9f52aaab69a1742cacabaf2d9617a380b517f8387b4b662d164",
|
||||
"git_blob_sha1": "e5d5dffc4201bff73162a350edad9d00fd0d5e51"
|
||||
},
|
||||
{
|
||||
"id": "guhai",
|
||||
"file": "nodes/\u5ffd\u7565\u591a\u7ec4.py",
|
||||
"local_file": "guhai__nodes__\u5ffd\u7565\u591a\u7ec4.py",
|
||||
"url": "https://raw.githubusercontent.com/goohai/Goohaitools-comfyui/4e11bd3b8471102eef1cadd809c79c94dc8001ee/nodes/\u5ffd\u7565\u591a\u7ec4.py",
|
||||
"commit": "4e11bd3b8471102eef1cadd809c79c94dc8001ee",
|
||||
"sha256": "4350ab38acf4b1e555dbeaf27afe5427223d91b5e9ac4c7a2d4ce25c2931f450",
|
||||
"git_blob_sha1": "fc1992c878179f88b3a0d776f0293cd79108eee5"
|
||||
},
|
||||
{
|
||||
"id": "guhai",
|
||||
"file": "web/js/nodes pass.js",
|
||||
"local_file": "guhai__web__js__nodes pass.js",
|
||||
"url": "https://raw.githubusercontent.com/goohai/Goohaitools-comfyui/4e11bd3b8471102eef1cadd809c79c94dc8001ee/web/js/nodes pass.js",
|
||||
"commit": "4e11bd3b8471102eef1cadd809c79c94dc8001ee",
|
||||
"sha256": "2466edb72013fc93e1685e430042c79bf089b38237bbfab65199d4903e7a3f5f",
|
||||
"git_blob_sha1": "4e3f4e6d2f3e1a8031d63930af7d5caf3f62b8b0"
|
||||
},
|
||||
{
|
||||
"id": "guhai",
|
||||
"file": "README.md",
|
||||
"local_file": "guhai__README.md",
|
||||
"url": "https://raw.githubusercontent.com/goohai/Goohaitools-comfyui/4e11bd3b8471102eef1cadd809c79c94dc8001ee/README.md",
|
||||
"commit": "4e11bd3b8471102eef1cadd809c79c94dc8001ee",
|
||||
"sha256": "7930cd372eda184ec5fc035f4ab202f83021ddaa85a5f868f8923d591f6c8b45",
|
||||
"git_blob_sha1": "5de30a6c14d4dfc93671b04c7d94547b93d79131"
|
||||
}
|
||||
]
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
@@ -0,0 +1,9 @@
|
||||
from .videohelpersuite.nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
|
||||
import folder_paths
|
||||
from .videohelpersuite.server import server
|
||||
from .videohelpersuite import documentation
|
||||
from .videohelpersuite import latent_preview
|
||||
|
||||
WEB_DIRECTORY = "./web"
|
||||
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
|
||||
documentation.format_descriptions(NODE_CLASS_MAPPINGS)
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"main_pass":
|
||||
[
|
||||
"-n", "-c:v", "libx264",
|
||||
"-pix_fmt", ["pix_fmt", ["yuv420p", "yuv420p10le"]],
|
||||
"-crf", ["crf","INT", {"default": 19, "min": 0, "max": 100, "step": 1}],
|
||||
"-vf", "scale=out_color_matrix=bt709",
|
||||
"-color_range", "tv", "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709"
|
||||
],
|
||||
"fake_trc": "bt709",
|
||||
"audio_pass": ["-c:a", "aac", "-movflags", "use_metadata_tags"],
|
||||
"save_metadata": ["save_metadata", "BOOLEAN", {"default": true}],
|
||||
"trim_to_audio": ["trim_to_audio", "BOOLEAN", {"default": false}],
|
||||
"extension": "mp4"
|
||||
}
|
||||
@@ -0,0 +1,672 @@
|
||||
import os
|
||||
import itertools
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image, ImageOps
|
||||
import cv2
|
||||
import psutil
|
||||
import subprocess
|
||||
import re
|
||||
import time
|
||||
|
||||
import folder_paths
|
||||
from comfy.utils import common_upscale, ProgressBar
|
||||
import nodes
|
||||
from comfy.k_diffusion.utils import FolderOfImages
|
||||
from .logger import logger
|
||||
from .utils import BIGMAX, DIMMAX, calculate_file_hash, get_sorted_dir_files_from_directory,\
|
||||
lazy_get_audio, hash_path, validate_path, strip_path, try_download_video, \
|
||||
is_url, imageOrLatent, ffmpeg_path, ENCODE_ARGS, floatOrInt
|
||||
|
||||
|
||||
video_extensions = ['webm', 'mp4', 'mkv', 'gif', 'mov']
|
||||
|
||||
VHSLoadFormats = {
|
||||
'None': {},
|
||||
'AnimateDiff': {'target_rate': 8, 'dim': (8,0,512,512)},
|
||||
'Mochi': {'target_rate': 24, 'dim': (16,0,848,480), 'frames':(6,1)},
|
||||
'LTXV': {'target_rate': 24, 'dim': (32,0,768,512), 'frames':(8,1)},
|
||||
'Hunyuan': {'target_rate': 24, 'dim': (16,0,848,480), 'frames':(4,1)},
|
||||
'Cosmos': {'target_rate': 24, 'dim': (16,0,1280,704), 'frames':(8,1)},
|
||||
'Wan': {'target_rate': 16, 'dim': (8,0,832,480), 'frames':(4,1)},
|
||||
'H3': {'target_rate': 24, 'dim': (32,0,1344,768), 'frames':(17,5)},
|
||||
}
|
||||
"""
|
||||
External plugins may add additional formats to nodes.VHSLoadFormats
|
||||
In addition to shorthand options, direct widget names will map a given dict to options.
|
||||
Adding a third arguement to a frames tuple can enable strict checks on number
|
||||
of loaded frames, i.e (8,1,True)
|
||||
"""
|
||||
if not hasattr(nodes, 'VHSLoadFormats'):
|
||||
nodes.VHSLoadFormats = {}
|
||||
|
||||
def get_load_formats():
|
||||
#TODO: check if {**extra_config.VHSLoafFormats, **VHSLoadFormats} has minimum version
|
||||
formats = {}
|
||||
formats.update(nodes.VHSLoadFormats)
|
||||
formats.update(VHSLoadFormats)
|
||||
return (list(formats.keys()),
|
||||
{'default': 'AnimateDiff', 'formats': formats})
|
||||
def get_format(format):
|
||||
if format in VHSLoadFormats:
|
||||
return VHSLoadFormats[format]
|
||||
return nodes.VHSLoadFormats.get(format, {})
|
||||
|
||||
def is_gif(filename) -> bool:
|
||||
file_parts = filename.split('.')
|
||||
return len(file_parts) > 1 and file_parts[-1] == "gif"
|
||||
|
||||
|
||||
def target_size(width, height, custom_width, custom_height, downscale_ratio=8) -> tuple[int, int]:
|
||||
if downscale_ratio is None:
|
||||
downscale_ratio = 8
|
||||
if custom_width == 0 and custom_height == 0:
|
||||
pass
|
||||
elif custom_height == 0:
|
||||
height *= custom_width/width
|
||||
width = custom_width
|
||||
elif custom_width == 0:
|
||||
width *= custom_height/height
|
||||
height = custom_height
|
||||
else:
|
||||
width = custom_width
|
||||
height = custom_height
|
||||
width = int(width/downscale_ratio + 0.5) * downscale_ratio
|
||||
height = int(height/downscale_ratio + 0.5) * downscale_ratio
|
||||
return (width, height)
|
||||
|
||||
def cv_frame_generator(video, force_rate, frame_load_cap, skip_first_frames,
|
||||
select_every_nth, meta_batch=None, unique_id=None):
|
||||
video_cap = cv2.VideoCapture(video)
|
||||
if not video_cap.isOpened() or not video_cap.grab():
|
||||
raise ValueError(f"{video} could not be loaded with cv.")
|
||||
|
||||
# extract video metadata
|
||||
fps = video_cap.get(cv2.CAP_PROP_FPS)
|
||||
width = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
||||
height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||||
total_frames = int(video_cap.get(cv2.CAP_PROP_FRAME_COUNT))
|
||||
duration = total_frames / fps
|
||||
|
||||
width = 0
|
||||
|
||||
if width <=0 or height <=0:
|
||||
_, frame = video_cap.retrieve()
|
||||
height, width, _ = frame.shape
|
||||
|
||||
# set video_cap to look at start_index frame
|
||||
total_frame_count = 0
|
||||
total_frames_evaluated = -1
|
||||
frames_added = 0
|
||||
base_frame_time = 1 / fps
|
||||
prev_frame = None
|
||||
|
||||
if force_rate == 0:
|
||||
target_frame_time = base_frame_time
|
||||
else:
|
||||
target_frame_time = 1/force_rate
|
||||
|
||||
if total_frames > 0:
|
||||
if force_rate != 0:
|
||||
yieldable_frames = int(total_frames / fps * force_rate)
|
||||
else:
|
||||
yieldable_frames = total_frames
|
||||
if select_every_nth:
|
||||
yieldable_frames //= select_every_nth
|
||||
if frame_load_cap != 0:
|
||||
yieldable_frames = min(frame_load_cap, yieldable_frames)
|
||||
else:
|
||||
yieldable_frames = 0
|
||||
yield (width, height, fps, duration, total_frames, target_frame_time, yieldable_frames)
|
||||
pbar = ProgressBar(yieldable_frames)
|
||||
time_offset=target_frame_time
|
||||
while video_cap.isOpened():
|
||||
if time_offset < target_frame_time:
|
||||
is_returned = video_cap.grab()
|
||||
# if didn't return frame, video has ended
|
||||
if not is_returned:
|
||||
break
|
||||
time_offset += base_frame_time
|
||||
if time_offset < target_frame_time:
|
||||
continue
|
||||
time_offset -= target_frame_time
|
||||
# if not at start_index, skip doing anything with frame
|
||||
total_frame_count += 1
|
||||
if total_frame_count <= skip_first_frames:
|
||||
continue
|
||||
else:
|
||||
total_frames_evaluated += 1
|
||||
|
||||
# if should not be selected, skip doing anything with frame
|
||||
if total_frames_evaluated%select_every_nth != 0:
|
||||
continue
|
||||
|
||||
# opencv loads images in BGR format (yuck), so need to convert to RGB for ComfyUI use
|
||||
# follow up: can videos ever have an alpha channel?
|
||||
# To my testing: No. opencv has no support for alpha
|
||||
unused, frame = video_cap.retrieve()
|
||||
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||
# convert frame to comfyui's expected format
|
||||
# TODO: frame contains no exif information. Check if opencv2 has already applied
|
||||
frame = np.array(frame, dtype=np.float32)
|
||||
torch.from_numpy(frame).div_(255)
|
||||
if prev_frame is not None:
|
||||
inp = yield prev_frame
|
||||
if inp is not None:
|
||||
#ensure the finally block is called
|
||||
return
|
||||
prev_frame = frame
|
||||
frames_added += 1
|
||||
if pbar is not None:
|
||||
pbar.update_absolute(frames_added, yieldable_frames)
|
||||
# if cap exists and we've reached it, stop processing frames
|
||||
if frame_load_cap > 0 and frames_added >= frame_load_cap:
|
||||
break
|
||||
if meta_batch is not None:
|
||||
meta_batch.inputs.pop(unique_id)
|
||||
meta_batch.has_closed_inputs = True
|
||||
if prev_frame is not None:
|
||||
yield prev_frame
|
||||
|
||||
def ffmpeg_frame_generator(video, force_rate, frame_load_cap, start_time,
|
||||
custom_width, custom_height, downscale_ratio=8,
|
||||
meta_batch=None, unique_id=None):
|
||||
args_input = ["-i", video]
|
||||
args_dummy = [ffmpeg_path] + args_input +['-c', 'copy', '-frames:v', '1', "-f", "null", "-"]
|
||||
size_base = None
|
||||
fps_base = None
|
||||
try:
|
||||
dummy_res = subprocess.run(args_dummy, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE, check=True)
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise Exception("An error occurred in the ffmpeg subprocess:\n" \
|
||||
+ e.stderr.decode(*ENCODE_ARGS))
|
||||
lines = dummy_res.stderr.decode(*ENCODE_ARGS)
|
||||
if "Video: vp9 " in lines:
|
||||
args_input = ["-c:v", "libvpx-vp9"] + args_input
|
||||
args_dummy = [ffmpeg_path] + args_input +['-c', 'copy', '-frames:v', '1', "-f", "null", "-"]
|
||||
try:
|
||||
dummy_res = subprocess.run(args_dummy, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE, check=True)
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise Exception("An error occurred in the ffmpeg subprocess:\n" \
|
||||
+ e.stderr.decode(*ENCODE_ARGS))
|
||||
lines = dummy_res.stderr.decode(*ENCODE_ARGS)
|
||||
|
||||
for line in lines.split('\n'):
|
||||
match = re.search("^ *Stream .* Video.*, ([1-9]|\\d{2,})x(\\d+)", line)
|
||||
if match is not None:
|
||||
size_base = [int(match.group(1)), int(match.group(2))]
|
||||
fps_match = re.search(", ([\\d\\.]+) fps", line)
|
||||
if fps_match:
|
||||
fps_base = float(fps_match.group(1))
|
||||
else:
|
||||
fps_base = 1
|
||||
alpha = re.search("(yuva|rgba|bgra|gbra)", line) is not None
|
||||
break
|
||||
else:
|
||||
raise Exception("Failed to parse video/image information. FFMPEG output:\n" + lines)
|
||||
|
||||
durs_match = re.search("Duration: (\\d+:\\d+:\\d+\\.\\d+),", lines)
|
||||
if durs_match:
|
||||
durs = durs_match.group(1).split(':')
|
||||
duration = int(durs[0])*3600 + int(durs[1])*60 + float(durs[2])
|
||||
else:
|
||||
duration = 0
|
||||
|
||||
if start_time > 0:
|
||||
if start_time > 4:
|
||||
post_seek = ['-ss', '4']
|
||||
args_input = ['-ss', str(start_time - 4)] + args_input
|
||||
else:
|
||||
post_seek = ['-ss', str(start_time)]
|
||||
else:
|
||||
post_seek = []
|
||||
args_all_frames = [ffmpeg_path, "-v", "error", "-an"] + \
|
||||
args_input + ["-pix_fmt", "rgba64le"] + post_seek
|
||||
|
||||
vfilters = []
|
||||
if force_rate != 0:
|
||||
vfilters.append("fps=fps="+str(force_rate))
|
||||
if custom_width != 0 or custom_height != 0:
|
||||
size = target_size(size_base[0], size_base[1], custom_width,
|
||||
custom_height, downscale_ratio=downscale_ratio)
|
||||
ar = float(size[0])/float(size[1])
|
||||
if abs(size_base[0]*ar-size_base[1]) >= 1:
|
||||
#Aspect ratio is changed. Crop to new aspect ratio before scale
|
||||
vfilters.append(f"crop=if(gt({ar}\\,a)\\,iw\\,ih*{ar}):if(gt({ar}\\,a)\\,iw/{ar}\\,ih)")
|
||||
size_arg = ':'.join(map(str,size))
|
||||
vfilters.append(f"scale={size_arg}")
|
||||
else:
|
||||
size = size_base
|
||||
if len(vfilters) > 0:
|
||||
args_all_frames += ["-vf", ",".join(vfilters)]
|
||||
yieldable_frames = (force_rate or fps_base)*duration
|
||||
if frame_load_cap > 0:
|
||||
args_all_frames += ["-frames:v", str(frame_load_cap)]
|
||||
yieldable_frames = min(yieldable_frames, frame_load_cap)
|
||||
yield (size_base[0], size_base[1], fps_base, duration, fps_base * duration,
|
||||
1/(force_rate or fps_base), yieldable_frames, size[0], size[1], alpha)
|
||||
|
||||
args_all_frames += ["-f", "rawvideo", "-"]
|
||||
pbar = ProgressBar(yieldable_frames)
|
||||
try:
|
||||
with subprocess.Popen(args_all_frames, stdout=subprocess.PIPE) as proc:
|
||||
#Manually buffer enough bytes for an image
|
||||
bpi = size[0] * size[1] * 8
|
||||
current_bytes = bytearray(bpi)
|
||||
current_offset=0
|
||||
prev_frame = None
|
||||
while True:
|
||||
bytes_read = proc.stdout.read(bpi - current_offset)
|
||||
if bytes_read is None:#sleep to wait for more data
|
||||
time.sleep(.1)
|
||||
continue
|
||||
if len(bytes_read) == 0:#EOF
|
||||
break
|
||||
current_bytes[current_offset:len(bytes_read)] = bytes_read
|
||||
current_offset+=len(bytes_read)
|
||||
if current_offset == bpi:
|
||||
if prev_frame is not None:
|
||||
yield prev_frame
|
||||
pbar.update(1)
|
||||
prev_frame = np.frombuffer(current_bytes, dtype=np.dtype(np.uint16).newbyteorder("<")).reshape(size[1], size[0], 4) / (2**16-1)
|
||||
if not alpha:
|
||||
prev_frame = prev_frame[:, :, :-1]
|
||||
current_offset = 0
|
||||
except BrokenPipeError as e:
|
||||
raise Exception("An error occured in the ffmpeg subprocess:\n" \
|
||||
+ proc.stderr.read().decode(*ENCODE_ARGS))
|
||||
if meta_batch is not None:
|
||||
meta_batch.inputs.pop(unique_id)
|
||||
meta_batch.has_closed_inputs = True
|
||||
if prev_frame is not None:
|
||||
yield prev_frame
|
||||
|
||||
#Python 3.12 adds an itertools.batched, but it's easily replicated for legacy support
|
||||
def batched(it, n):
|
||||
while batch := tuple(itertools.islice(it, n)):
|
||||
yield batch
|
||||
def batched_vae_encode(images, vae, frames_per_batch):
|
||||
for batch in batched(images, frames_per_batch):
|
||||
image_batch = torch.from_numpy(np.array(batch))
|
||||
yield from vae.encode(image_batch).numpy()
|
||||
def resized_cv_frame_gen(custom_width, custom_height, downscale_ratio, **kwargs):
|
||||
gen = cv_frame_generator(**kwargs)
|
||||
info = next(gen)
|
||||
width, height = info[0], info[1]
|
||||
frames_per_batch = (1920 * 1080 * 16) // (width * height) or 1
|
||||
if kwargs.get('meta_batch', None) is not None:
|
||||
frames_per_batch = min(frames_per_batch, kwargs['meta_batch'].frames_per_batch)
|
||||
if custom_width != 0 or custom_height != 0 or downscale_ratio is not None:
|
||||
new_size = target_size(width, height, custom_width, custom_height, downscale_ratio)
|
||||
yield (*info, new_size[0], new_size[1], False)
|
||||
if new_size[0] != width or new_size[1] != height:
|
||||
def rescale(frame):
|
||||
s = torch.from_numpy(np.fromiter(frame, np.dtype((np.float32, (height, width, 3)))))
|
||||
s = s.movedim(-1,1)
|
||||
s = common_upscale(s, new_size[0], new_size[1], "lanczos", "center")
|
||||
return s.movedim(1,-1).numpy()
|
||||
yield from itertools.chain.from_iterable(map(rescale, batched(gen, frames_per_batch)))
|
||||
return
|
||||
else:
|
||||
yield (*info, info[0], info[1], False)
|
||||
yield from gen
|
||||
|
||||
def load_video(meta_batch=None, unique_id=None, memory_limit_mb=None, vae=None,
|
||||
generator=resized_cv_frame_gen, format='None', **kwargs):
|
||||
if 'force_size' in kwargs:
|
||||
kwargs.pop('force_size')
|
||||
logger.warn("force_size has been removed. Did you reload the webpage after updating?")
|
||||
format = get_format(format)
|
||||
kwargs['video'] = strip_path(kwargs['video'])
|
||||
if vae is not None:
|
||||
downscale_ratio = getattr(vae, "downscale_ratio", 8)
|
||||
else:
|
||||
downscale_ratio = format.get('dim', (1,))[0]
|
||||
if meta_batch is None or unique_id not in meta_batch.inputs:
|
||||
gen = generator(meta_batch=meta_batch, unique_id=unique_id, downscale_ratio=downscale_ratio, **kwargs)
|
||||
(width, height, fps, duration, total_frames, target_frame_time, yieldable_frames, new_width, new_height, alpha) = next(gen)
|
||||
|
||||
if meta_batch is not None:
|
||||
meta_batch.inputs[unique_id] = (gen, width, height, fps, duration, total_frames, target_frame_time, yieldable_frames, new_width, new_height, alpha)
|
||||
if yieldable_frames:
|
||||
meta_batch.total_frames = min(meta_batch.total_frames, yieldable_frames)
|
||||
|
||||
else:
|
||||
(gen, width, height, fps, duration, total_frames, target_frame_time, yieldable_frames, new_width, new_height, alpha) = meta_batch.inputs[unique_id]
|
||||
|
||||
memory_limit = None
|
||||
if memory_limit_mb is not None:
|
||||
memory_limit *= 2 ** 20
|
||||
else:
|
||||
#TODO: verify if garbage collection should be performed here.
|
||||
#leaves ~128 MB unreserved for safety
|
||||
try:
|
||||
memory_limit = (psutil.virtual_memory().available + psutil.swap_memory().free) - 2 ** 27
|
||||
except:
|
||||
logger.warn("Failed to calculate available memory. Memory load limit has been disabled")
|
||||
memory_limit = BIGMAX
|
||||
if vae is not None:
|
||||
#space required to load as f32, exist as latent with wiggle room, decode to f32
|
||||
max_loadable_frames = int(memory_limit//(width*height*3*(4+4+1/10)))
|
||||
else:
|
||||
#TODO: use better estimate for when vae is not None
|
||||
#Consider completely ignoring for load_latent case?
|
||||
max_loadable_frames = int(memory_limit//(width*height*3*(.1)))
|
||||
if meta_batch is not None:
|
||||
if 'frames' in format:
|
||||
if meta_batch.frames_per_batch % format['frames'][0] != format['frames'][1]:
|
||||
error = (meta_batch.frames_per_batch - format['frames'][1]) % format['frames'][0]
|
||||
suggested = meta_batch.frames_per_batch - error
|
||||
if error > format['frames'][0] / 2:
|
||||
suggested += format['frames'][0]
|
||||
raise RuntimeError(f"The chosen frames per batch is incompatible with the selected format. Try {suggested}")
|
||||
if meta_batch.frames_per_batch > max_loadable_frames:
|
||||
raise RuntimeError(f"Meta Batch set to {meta_batch.frames_per_batch} frames but only {max_loadable_frames} can fit in memory")
|
||||
gen = itertools.islice(gen, meta_batch.frames_per_batch)
|
||||
else:
|
||||
original_gen = gen
|
||||
gen = itertools.islice(gen, max_loadable_frames)
|
||||
frames_per_batch = (1920 * 1080 * 16) // (width * height) or 1
|
||||
if vae is not None:
|
||||
gen = batched_vae_encode(gen, vae, frames_per_batch)
|
||||
vw,vh = new_width//downscale_ratio, new_height//downscale_ratio
|
||||
channels = getattr(vae, 'latent_channels', 4)
|
||||
images = torch.from_numpy(np.fromiter(gen, np.dtype((np.float32, (channels,vh,vw)))))
|
||||
else:
|
||||
#Some minor wizardry to eliminate a copy and reduce max memory by a factor of ~2
|
||||
images = torch.from_numpy(np.fromiter(gen, np.dtype((np.float32, (new_height, new_width, 4 if alpha else 3)))))
|
||||
if meta_batch is None and memory_limit is not None:
|
||||
try:
|
||||
next(original_gen)
|
||||
raise RuntimeError(f"Memory limit hit after loading {len(images)} frames. Stopping execution.")
|
||||
except StopIteration:
|
||||
pass
|
||||
if len(images) == 0:
|
||||
raise RuntimeError("No frames generated")
|
||||
if 'frames' in format and len(images) % format['frames'][0] != format['frames'][1]:
|
||||
err_msg = f"The number of frames loaded {len(images)}, does not match the requirements of the currently selected format."
|
||||
if len(format['frames']) > 2 and format['frames'][2]:
|
||||
raise RuntimeError(err_msg)
|
||||
div, mod = format['frames'][:2]
|
||||
frames = (len(images) - mod) // div * div + mod
|
||||
images = images[:frames]
|
||||
#Commenting out log message since it's displayed in UI. consider further
|
||||
#logger.warn(err_msg + f" Output has been truncated to {len(images)} frames.")
|
||||
if 'start_time' in kwargs:
|
||||
start_time = kwargs['start_time']
|
||||
else:
|
||||
start_time = kwargs['skip_first_frames'] * target_frame_time
|
||||
target_frame_time *= kwargs.get('select_every_nth', 1)
|
||||
#Setup lambda for lazy audio capture
|
||||
audio = lazy_get_audio(kwargs['video'], start_time, kwargs['frame_load_cap']*target_frame_time)
|
||||
#Adjust target_frame_time for select_every_nth
|
||||
video_info = {
|
||||
"source_fps": fps,
|
||||
"source_frame_count": total_frames,
|
||||
"source_duration": duration,
|
||||
"source_width": width,
|
||||
"source_height": height,
|
||||
"loaded_fps": 1/target_frame_time,
|
||||
"loaded_frame_count": len(images),
|
||||
"loaded_duration": len(images) * target_frame_time,
|
||||
"loaded_width": new_width,
|
||||
"loaded_height": new_height,
|
||||
}
|
||||
if vae is None:
|
||||
return (images, len(images), audio, video_info)
|
||||
else:
|
||||
return ({"samples": images}, len(images), audio, video_info)
|
||||
|
||||
|
||||
|
||||
class LoadVideoUpload:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
input_dir = folder_paths.get_input_directory()
|
||||
files = []
|
||||
for f in os.listdir(input_dir):
|
||||
if os.path.isfile(os.path.join(input_dir, f)):
|
||||
file_parts = f.split('.')
|
||||
if len(file_parts) > 1 and (file_parts[-1].lower() in video_extensions):
|
||||
files.append(f)
|
||||
return {"required": {
|
||||
"video": (sorted(files),),
|
||||
"force_rate": (floatOrInt, {"default": 0, "min": 0, "max": 60, "step": 1, "disable": 0}),
|
||||
"custom_width": ("INT", {"default": 0, "min": 0, "max": DIMMAX, 'disable': 0}),
|
||||
"custom_height": ("INT", {"default": 0, "min": 0, "max": DIMMAX, 'disable': 0}),
|
||||
"frame_load_cap": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1, "disable": 0}),
|
||||
"skip_first_frames": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1}),
|
||||
"select_every_nth": ("INT", {"default": 1, "min": 1, "max": BIGMAX, "step": 1}),
|
||||
},
|
||||
"optional": {
|
||||
"meta_batch": ("VHS_BatchManager",),
|
||||
"vae": ("VAE",),
|
||||
"format": get_load_formats(),
|
||||
},
|
||||
"hidden": {
|
||||
"force_size": "STRING",
|
||||
"unique_id": "UNIQUE_ID"
|
||||
},
|
||||
}
|
||||
|
||||
CATEGORY = "Video Helper Suite 🎥🅥🅗🅢"
|
||||
|
||||
RETURN_TYPES = (imageOrLatent, "INT", "AUDIO", "VHS_VIDEOINFO")
|
||||
RETURN_NAMES = ("IMAGE", "frame_count", "audio", "video_info")
|
||||
|
||||
FUNCTION = "load_video"
|
||||
|
||||
def load_video(self, **kwargs):
|
||||
kwargs['video'] = folder_paths.get_annotated_filepath(strip_path(kwargs['video']))
|
||||
return load_video(**kwargs)
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(s, video, **kwargs):
|
||||
image_path = folder_paths.get_annotated_filepath(video)
|
||||
return calculate_file_hash(image_path)
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(s, video):
|
||||
if not folder_paths.exists_annotated_filepath(video):
|
||||
return "Invalid video file: {}".format(video)
|
||||
return True
|
||||
|
||||
|
||||
class LoadVideoPath:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"video": ("STRING", {"placeholder": "X://insert/path/here.mp4", "vhs_path_extensions": video_extensions}),
|
||||
"force_rate": (floatOrInt, {"default": 0, "min": 0, "max": 60, "step": 1, "disable": 0}),
|
||||
"custom_width": ("INT", {"default": 0, "min": 0, "max": DIMMAX, 'disable': 0}),
|
||||
"custom_height": ("INT", {"default": 0, "min": 0, "max": DIMMAX, 'disable': 0}),
|
||||
"frame_load_cap": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1, "disable": 0}),
|
||||
"skip_first_frames": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1}),
|
||||
"select_every_nth": ("INT", {"default": 1, "min": 1, "max": BIGMAX, "step": 1}),
|
||||
},
|
||||
"optional": {
|
||||
"meta_batch": ("VHS_BatchManager",),
|
||||
"vae": ("VAE",),
|
||||
"format": get_load_formats(),
|
||||
},
|
||||
"hidden": {
|
||||
"force_size": "STRING",
|
||||
"unique_id": "UNIQUE_ID"
|
||||
},
|
||||
}
|
||||
|
||||
CATEGORY = "Video Helper Suite 🎥🅥🅗🅢"
|
||||
|
||||
RETURN_TYPES = (imageOrLatent, "INT", "AUDIO", "VHS_VIDEOINFO")
|
||||
RETURN_NAMES = ("IMAGE", "frame_count", "audio", "video_info")
|
||||
|
||||
FUNCTION = "load_video"
|
||||
|
||||
def load_video(self, **kwargs):
|
||||
if kwargs['video'] is None or validate_path(kwargs['video']) != True:
|
||||
raise Exception("video is not a valid path: " + kwargs['video'])
|
||||
if is_url(kwargs['video']):
|
||||
kwargs['video'] = try_download_video(kwargs['video']) or kwargs['video']
|
||||
return load_video(**kwargs)
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(s, video, **kwargs):
|
||||
return hash_path(video)
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(s, video):
|
||||
return validate_path(video, allow_none=True)
|
||||
|
||||
class LoadVideoFFmpegUpload:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
input_dir = folder_paths.get_input_directory()
|
||||
files = []
|
||||
for f in os.listdir(input_dir):
|
||||
if os.path.isfile(os.path.join(input_dir, f)):
|
||||
file_parts = f.split('.')
|
||||
if len(file_parts) > 1 and (file_parts[-1].lower() in video_extensions):
|
||||
files.append(f)
|
||||
return {"required": {
|
||||
"video": (sorted(files),),
|
||||
"force_rate": (floatOrInt, {"default": 0, "min": 0, "max": 60, "step": 1, "disable": 0}),
|
||||
"custom_width": ("INT", {"default": 0, "min": 0, "max": DIMMAX, 'disable': 0}),
|
||||
"custom_height": ("INT", {"default": 0, "min": 0, "max": DIMMAX, 'disable': 0}),
|
||||
"frame_load_cap": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1, "disable": 0}),
|
||||
"start_time": ("FLOAT", {"default": 0, "min": 0, "max": BIGMAX, "step": .001, "widgetType": "VHSTIMESTAMP"}),
|
||||
},
|
||||
"optional": {
|
||||
"meta_batch": ("VHS_BatchManager",),
|
||||
"vae": ("VAE",),
|
||||
"format": get_load_formats(),
|
||||
},
|
||||
"hidden": {
|
||||
"force_size": "STRING",
|
||||
"unique_id": "UNIQUE_ID"
|
||||
|
||||
},
|
||||
}
|
||||
|
||||
CATEGORY = "Video Helper Suite 🎥🅥🅗🅢"
|
||||
|
||||
RETURN_TYPES = (imageOrLatent, "MASK", "AUDIO", "VHS_VIDEOINFO")
|
||||
RETURN_NAMES = ("IMAGE", "mask", "audio", "video_info")
|
||||
|
||||
FUNCTION = "load_video"
|
||||
|
||||
def load_video(self, **kwargs):
|
||||
kwargs['video'] = folder_paths.get_annotated_filepath(strip_path(kwargs['video']))
|
||||
image, _, audio, video_info = load_video(**kwargs, generator=ffmpeg_frame_generator)
|
||||
if image.size(3) == 4:
|
||||
return (image[:,:,:,:3], 1-image[:,:,:,3], audio, video_info)
|
||||
return (image, torch.zeros(image.size(0), 64, 64, device="cpu"), audio, video_info)
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(s, video, **kwargs):
|
||||
image_path = folder_paths.get_annotated_filepath(video)
|
||||
return calculate_file_hash(image_path)
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(s, video):
|
||||
if not folder_paths.exists_annotated_filepath(video):
|
||||
return "Invalid video file: {}".format(video)
|
||||
return True
|
||||
|
||||
|
||||
class LoadVideoFFmpegPath:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"video": ("STRING", {"placeholder": "X://insert/path/here.mp4", "vhs_path_extensions": video_extensions}),
|
||||
"force_rate": (floatOrInt, {"default": 0, "min": 0, "max": 60, "step": 1, "disable": 0}),
|
||||
"custom_width": ("INT", {"default": 0, "min": 0, "max": DIMMAX, 'disable': 0}),
|
||||
"custom_height": ("INT", {"default": 0, "min": 0, "max": DIMMAX, 'disable': 0}),
|
||||
"frame_load_cap": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1, "disable": 0}),
|
||||
"start_time": ("FLOAT", {"default": 0, "min": 0, "max": BIGMAX, "step": .001, "widgetType": "VHSTIMESTAMP"}),
|
||||
},
|
||||
"optional": {
|
||||
"meta_batch": ("VHS_BatchManager",),
|
||||
"vae": ("VAE",),
|
||||
"format": get_load_formats(),
|
||||
},
|
||||
"hidden": {
|
||||
"force_size": "STRING",
|
||||
"unique_id": "UNIQUE_ID"
|
||||
},
|
||||
}
|
||||
|
||||
CATEGORY = "Video Helper Suite 🎥🅥🅗🅢"
|
||||
|
||||
RETURN_TYPES = (imageOrLatent, "MASK", "AUDIO", "VHS_VIDEOINFO")
|
||||
RETURN_NAMES = ("IMAGE", "mask", "audio", "video_info")
|
||||
|
||||
FUNCTION = "load_video"
|
||||
|
||||
def load_video(self, **kwargs):
|
||||
if kwargs['video'] is None or validate_path(kwargs['video']) != True:
|
||||
raise Exception("video is not a valid path: " + kwargs['video'])
|
||||
if is_url(kwargs['video']):
|
||||
kwargs['video'] = try_download_video(kwargs['video']) or kwargs['video']
|
||||
image, _, audio, video_info = load_video(**kwargs, generator=ffmpeg_frame_generator)
|
||||
if isinstance(image, dict):
|
||||
return (image, None, audio, video_info)
|
||||
if image.size(3) == 4:
|
||||
return (image[:,:,:,:3], 1-image[:,:,:,3], audio, video_info)
|
||||
return (image, torch.zeros(image.size(0), 64, 64, device="cpu"), audio, video_info)
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(s, video, **kwargs):
|
||||
return hash_path(video)
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(s, video):
|
||||
return validate_path(video, allow_none=True)
|
||||
|
||||
class LoadImagePath:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"image": ("STRING", {"placeholder": "X://insert/path/here.png", "vhs_path_extensions": list(FolderOfImages.IMG_EXTENSIONS)}),
|
||||
"custom_width": ("INT", {"default": 0, "min": 0, "max": DIMMAX, "step": 8, 'disable': 0}),
|
||||
"custom_height": ("INT", {"default": 0, "min": 0, "max": DIMMAX, "step": 8, 'disable': 0}),
|
||||
},
|
||||
"optional": {
|
||||
"vae": ("VAE",),
|
||||
},
|
||||
"hidden": {
|
||||
"force_size": "STRING",
|
||||
},
|
||||
}
|
||||
|
||||
CATEGORY = "Video Helper Suite 🎥🅥🅗🅢"
|
||||
|
||||
RETURN_TYPES = (imageOrLatent, "MASK")
|
||||
RETURN_NAMES = ("IMAGE", "mask")
|
||||
|
||||
FUNCTION = "load_image"
|
||||
|
||||
def load_image(self, **kwargs):
|
||||
if kwargs['image'] is None or validate_path(kwargs['image']) != True:
|
||||
raise Exception("image is not a valid path: " + kwargs['image'])
|
||||
kwargs.update({'video': kwargs['image'], 'force_rate': 0, 'frame_load_cap': 0,
|
||||
'start_time': 0})
|
||||
kwargs.pop('image')
|
||||
image, _, _, _ = load_video(**kwargs, generator=ffmpeg_frame_generator)
|
||||
if isinstance(image, dict):
|
||||
return (image, None)
|
||||
if image.size(3) == 4:
|
||||
return (image[:,:,:,:3], 1-image[:,:,:,3])
|
||||
return (image, torch.zeros(image.size(0), 64, 64, device="cpu"))
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(s, image, **kwargs):
|
||||
return hash_path(image)
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(s, image):
|
||||
return validate_path(image, allow_none=True)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,443 @@
|
||||
import hashlib
|
||||
import os
|
||||
from typing import Iterable
|
||||
import shutil
|
||||
import subprocess
|
||||
import re
|
||||
import time
|
||||
from collections.abc import Mapping
|
||||
from typing import Union
|
||||
import functools
|
||||
import torch
|
||||
from torch import Tensor
|
||||
|
||||
import server
|
||||
from .logger import logger
|
||||
import folder_paths
|
||||
|
||||
BIGMIN = -(2**53-1)
|
||||
BIGMAX = (2**53-1)
|
||||
|
||||
DIMMAX = 8192
|
||||
|
||||
ENCODE_ARGS = ("utf-8", 'backslashreplace')
|
||||
|
||||
def ffmpeg_suitability(path):
|
||||
try:
|
||||
version = subprocess.run([path, "-version"], check=True,
|
||||
capture_output=True).stdout.decode(*ENCODE_ARGS)
|
||||
except:
|
||||
return 0
|
||||
score = 0
|
||||
#rough layout of the importance of various features
|
||||
simple_criterion = [("libvpx", 20),("264",10), ("265",3),
|
||||
("svtav1",5),("libopus", 1)]
|
||||
for criterion in simple_criterion:
|
||||
if version.find(criterion[0]) >= 0:
|
||||
score += criterion[1]
|
||||
#obtain rough compile year from copyright information
|
||||
copyright_index = version.find('2000-2')
|
||||
if copyright_index >= 0:
|
||||
copyright_year = version[copyright_index+6:copyright_index+9]
|
||||
if copyright_year.isnumeric():
|
||||
score += int(copyright_year)
|
||||
return score
|
||||
|
||||
class MultiInput(str):
|
||||
def __new__(cls, string, allowed_types="*"):
|
||||
res = super().__new__(cls, string)
|
||||
res.allowed_types=allowed_types
|
||||
return res
|
||||
def __ne__(self, other):
|
||||
if self.allowed_types == "*" or other == "*":
|
||||
return False
|
||||
return other not in self.allowed_types
|
||||
imageOrLatent = MultiInput("IMAGE", ["IMAGE", "LATENT"])
|
||||
floatOrInt = MultiInput("FLOAT", ["FLOAT", "INT"])
|
||||
|
||||
class ContainsAll(dict):
|
||||
def __contains__(self, other):
|
||||
return True
|
||||
def __getitem__(self, key):
|
||||
return super().get(key, (None, {}))
|
||||
|
||||
if "VHS_FORCE_FFMPEG_PATH" in os.environ:
|
||||
ffmpeg_path = os.environ.get("VHS_FORCE_FFMPEG_PATH")
|
||||
else:
|
||||
ffmpeg_paths = []
|
||||
try:
|
||||
from imageio_ffmpeg import get_ffmpeg_exe
|
||||
imageio_ffmpeg_path = get_ffmpeg_exe()
|
||||
ffmpeg_paths.append(imageio_ffmpeg_path)
|
||||
except:
|
||||
if "VHS_USE_IMAGEIO_FFMPEG" in os.environ:
|
||||
raise
|
||||
logger.warn("Failed to import imageio_ffmpeg")
|
||||
if "VHS_USE_IMAGEIO_FFMPEG" in os.environ:
|
||||
ffmpeg_path = imageio_ffmpeg_path
|
||||
else:
|
||||
system_ffmpeg = shutil.which("ffmpeg")
|
||||
if system_ffmpeg is not None:
|
||||
ffmpeg_paths.append(system_ffmpeg)
|
||||
if os.path.isfile("ffmpeg"):
|
||||
ffmpeg_paths.append(os.path.abspath("ffmpeg"))
|
||||
if os.path.isfile("ffmpeg.exe"):
|
||||
ffmpeg_paths.append(os.path.abspath("ffmpeg.exe"))
|
||||
if len(ffmpeg_paths) == 0:
|
||||
logger.error("No valid ffmpeg found.")
|
||||
ffmpeg_path = None
|
||||
elif len(ffmpeg_paths) == 1:
|
||||
#Evaluation of suitability isn't required, can take sole option
|
||||
#to reduce startup time
|
||||
ffmpeg_path = ffmpeg_paths[0]
|
||||
else:
|
||||
ffmpeg_path = max(ffmpeg_paths, key=ffmpeg_suitability)
|
||||
gifski_path = os.environ.get("VHS_GIFSKI", None)
|
||||
if gifski_path is None:
|
||||
gifski_path = os.environ.get("JOV_GIFSKI", None)
|
||||
if gifski_path is None:
|
||||
gifski_path = shutil.which("gifski")
|
||||
ytdl_path = os.environ.get("VHS_YTDL", None) or shutil.which('yt-dlp') \
|
||||
or shutil.which('youtube-dl')
|
||||
download_history = {}
|
||||
def try_download_video(url):
|
||||
if ytdl_path is None:
|
||||
return None
|
||||
if url in download_history:
|
||||
return download_history[url]
|
||||
os.makedirs(folder_paths.get_temp_directory(), exist_ok=True)
|
||||
#Format information could be added to only download audio for Load Audio,
|
||||
#but this gets hairy if same url is also used for video.
|
||||
#Best to just always keep defaults
|
||||
#dl_format = ['-f', 'ba'] if is_audio else []
|
||||
try:
|
||||
res = subprocess.run([ytdl_path, "--print", "after_move:filepath",
|
||||
"-P", folder_paths.get_temp_directory(), url],
|
||||
capture_output=True, check=True)
|
||||
#strip newline
|
||||
file = res.stdout.decode(*ENCODE_ARGS)[:-1]
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise Exception("An error occurred in the yt-dl process:\n" \
|
||||
+ e.stderr.decode(*ENCODE_ARGS))
|
||||
file = None
|
||||
download_history[url] = file
|
||||
return file
|
||||
|
||||
def is_safe_path(path, strict=False):
|
||||
if "VHS_STRICT_PATHS" not in os.environ and not strict:
|
||||
return True
|
||||
basedir = os.path.abspath('.')
|
||||
try:
|
||||
common_path = os.path.commonpath([basedir, path])
|
||||
except:
|
||||
#Different drive on windows
|
||||
return False
|
||||
return common_path == basedir
|
||||
|
||||
def get_sorted_dir_files_from_directory(directory: str, skip_first_images: int=0, select_every_nth: int=1, extensions: Iterable=None):
|
||||
directory = strip_path(directory)
|
||||
dir_files = os.listdir(directory)
|
||||
dir_files = sorted(dir_files)
|
||||
dir_files = [os.path.join(directory, x) for x in dir_files]
|
||||
dir_files = list(filter(lambda filepath: os.path.isfile(filepath), dir_files))
|
||||
# filter by extension, if needed
|
||||
if extensions is not None:
|
||||
extensions = list(extensions)
|
||||
new_dir_files = []
|
||||
for filepath in dir_files:
|
||||
ext = "." + filepath.split(".")[-1]
|
||||
if ext.lower() in extensions:
|
||||
new_dir_files.append(filepath)
|
||||
dir_files = new_dir_files
|
||||
# start at skip_first_images
|
||||
dir_files = dir_files[skip_first_images:]
|
||||
dir_files = dir_files[0::select_every_nth]
|
||||
return dir_files
|
||||
|
||||
|
||||
# modified from https://stackoverflow.com/questions/22058048/hashing-a-file-in-python
|
||||
def calculate_file_hash(filename: str, hash_every_n: int = 1):
|
||||
#Larger video files were taking >.5 seconds to hash even when cached,
|
||||
#so instead the modified time from the filesystem is used as a hash
|
||||
h = hashlib.sha256()
|
||||
h.update(filename.encode())
|
||||
h.update(str(os.path.getmtime(filename)).encode())
|
||||
return h.hexdigest()
|
||||
|
||||
prompt_queue = server.PromptServer.instance.prompt_queue
|
||||
def requeue_workflow_unchecked():
|
||||
"""Requeues the current workflow without checking for multiple requeues"""
|
||||
currently_running = prompt_queue.currently_running
|
||||
value = next(iter(currently_running.values()))
|
||||
|
||||
# Handle both old (5 values) and new (6 values) ComfyUI versions
|
||||
if len(value) == 6:
|
||||
(_, prompt_id, prompt, extra_data, outputs_to_execute, _) = value
|
||||
else:
|
||||
(_, prompt_id, prompt, extra_data, outputs_to_execute) = value
|
||||
|
||||
#Ensure batch_managers are marked stale
|
||||
prompt = prompt.copy()
|
||||
for uid in prompt:
|
||||
if prompt[uid]['class_type'] == 'VHS_BatchManager':
|
||||
prompt[uid]['inputs']['requeue'] = prompt[uid]['inputs'].get('requeue',0)+1
|
||||
|
||||
#execution.py has guards for concurrency, but server doesn't.
|
||||
#TODO: Check that this won't be an issue
|
||||
number = -server.PromptServer.instance.number
|
||||
server.PromptServer.instance.number += 1
|
||||
prompt_id = str(server.uuid.uuid4())
|
||||
# Put back with 6 elements to match what ComfyUI expects
|
||||
sensitive = value[5] if len(value) > 5 else {}
|
||||
prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute, sensitive))
|
||||
|
||||
requeue_guard = [None, 0, 0, {}]
|
||||
|
||||
def requeue_workflow(requeue_required=(-1,True)):
|
||||
assert(len(prompt_queue.currently_running) == 1)
|
||||
global requeue_guard
|
||||
|
||||
value = next(iter(prompt_queue.currently_running.values()))
|
||||
|
||||
# Handle both old (5 values) and new (6 values) ComfyUI versions
|
||||
if len(value) == 6:
|
||||
(run_number, _, prompt, extra_data, outputs_to_execute, _) = value
|
||||
else:
|
||||
(run_number, _, prompt, extra_data, outputs_to_execute) = value
|
||||
|
||||
if requeue_guard[0] != run_number:
|
||||
#Calculate a count of how many outputs are managed by a batch manager
|
||||
managed_outputs=0
|
||||
for bm_uid in prompt:
|
||||
if prompt[bm_uid]['class_type'] == 'VHS_BatchManager':
|
||||
for output_uid in prompt:
|
||||
if prompt[output_uid]['class_type'] in ["VHS_VideoCombine"]:
|
||||
for inp in prompt[output_uid]['inputs'].values():
|
||||
if inp == [bm_uid, 0]:
|
||||
managed_outputs+=1
|
||||
requeue_guard = [run_number, 0, managed_outputs, {}]
|
||||
requeue_guard[1] = requeue_guard[1]+1
|
||||
requeue_guard[3][requeue_required[0]] = requeue_required[1]
|
||||
if requeue_guard[1] == requeue_guard[2] and max(requeue_guard[3].values()):
|
||||
requeue_workflow_unchecked()
|
||||
|
||||
def get_audio(file, start_time=0, duration=0):
|
||||
args = [ffmpeg_path, "-i", file]
|
||||
if start_time > 0:
|
||||
args += ["-ss", str(start_time)]
|
||||
if duration > 0:
|
||||
args += ["-t", str(duration)]
|
||||
try:
|
||||
#TODO: scan for sample rate and maintain
|
||||
res = subprocess.run(args + ["-f", "f32le", "-"],
|
||||
capture_output=True, check=True)
|
||||
audio = torch.frombuffer(bytearray(res.stdout), dtype=torch.float32)
|
||||
match = re.search(', (\\d+) Hz, (\\w+), ',res.stderr.decode(*ENCODE_ARGS))
|
||||
except subprocess.CalledProcessError as e:
|
||||
raise Exception(f"VHS failed to extract audio from {file}:\n" \
|
||||
+ e.stderr.decode(*ENCODE_ARGS))
|
||||
if match:
|
||||
ar = int(match.group(1))
|
||||
#NOTE: Just throwing an error for other channel types right now
|
||||
#Will deal with issues if they come
|
||||
ac = {"mono": 1, "stereo": 2}[match.group(2)]
|
||||
else:
|
||||
ar = 44100
|
||||
ac = 2
|
||||
audio = audio.reshape((-1,ac)).transpose(0,1).unsqueeze(0)
|
||||
return {'waveform': audio, 'sample_rate': ar}
|
||||
|
||||
class LazyAudioMap(Mapping):
|
||||
def __init__(self, file, start_time, duration):
|
||||
self.file = file
|
||||
self.start_time=start_time
|
||||
self.duration=duration
|
||||
self._dict=None
|
||||
def __getitem__(self, key):
|
||||
if self._dict is None:
|
||||
self._dict = get_audio(self.file, self.start_time, self.duration)
|
||||
return self._dict[key]
|
||||
def __iter__(self):
|
||||
if self._dict is None:
|
||||
self._dict = get_audio(self.file, self.start_time, self.duration)
|
||||
return iter(self._dict)
|
||||
def __len__(self):
|
||||
if self._dict is None:
|
||||
self._dict = get_audio(self.file, self.start_time, self.duration)
|
||||
return len(self._dict)
|
||||
def lazy_get_audio(file, start_time=0, duration=0, **kwargs):
|
||||
return LazyAudioMap(file, start_time, duration)
|
||||
|
||||
def is_url(url):
|
||||
return url.split("://")[0] in ["http", "https"]
|
||||
|
||||
def validate_sequence(path):
|
||||
#Check if path is a valid ffmpeg sequence that points to at least one file
|
||||
(path, file) = os.path.split(path)
|
||||
if not os.path.isdir(path):
|
||||
return False
|
||||
match = re.search('%0?\\d+d', file)
|
||||
if not match:
|
||||
return False
|
||||
seq = match.group()
|
||||
if seq == '%d':
|
||||
seq = '\\\\d+'
|
||||
else:
|
||||
seq = '\\\\d{%s}' % seq[1:-1]
|
||||
file_matcher = re.compile(re.sub('%0?\\d+d', seq, file))
|
||||
for file in os.listdir(path):
|
||||
if file_matcher.fullmatch(file):
|
||||
return True
|
||||
return False
|
||||
|
||||
def strip_path(path):
|
||||
#This leaves whitespace inside quotes and only a single "
|
||||
#thus ' ""test"' -> '"test'
|
||||
#consider path.strip(string.whitespace+"\"")
|
||||
#or weightier re.fullmatch("[\\s\"]*(.+?)[\\s\"]*", path).group(1)
|
||||
path = path.strip()
|
||||
if path.startswith("\""):
|
||||
path = path[1:]
|
||||
if path.endswith("\""):
|
||||
path = path[:-1]
|
||||
return path
|
||||
def hash_path(path):
|
||||
if path is None:
|
||||
return "input"
|
||||
if is_url(path):
|
||||
return "url"
|
||||
if not os.path.isfile(path):
|
||||
return "DNE"
|
||||
return calculate_file_hash(strip_path(path))
|
||||
|
||||
|
||||
def validate_path(path, allow_none=False, allow_url=True):
|
||||
if path is None:
|
||||
return allow_none
|
||||
if is_url(path):
|
||||
#Probably not feasible to check if url resolves here
|
||||
if not allow_url:
|
||||
return "URLs are unsupported for this path"
|
||||
return is_safe_path(path)
|
||||
if not os.path.isfile(strip_path(path)):
|
||||
return "Invalid file path: {}".format(path)
|
||||
return is_safe_path(path)
|
||||
|
||||
|
||||
def validate_index(index: int, length: int=0, is_range: bool=False, allow_negative=False, allow_missing=False) -> int:
|
||||
# if part of range, do nothing
|
||||
if is_range:
|
||||
return index
|
||||
# otherwise, validate index
|
||||
# validate not out of range - only when latent_count is passed in
|
||||
if length > 0 and index > length-1 and not allow_missing:
|
||||
raise IndexError(f"Index '{index}' out of range for {length} item(s).")
|
||||
# if negative, validate not out of range
|
||||
if index < 0:
|
||||
if not allow_negative:
|
||||
raise IndexError(f"Negative indeces not allowed, but was '{index}'.")
|
||||
conv_index = length+index
|
||||
if conv_index < 0 and not allow_missing:
|
||||
raise IndexError(f"Index '{index}', converted to '{conv_index}' out of range for {length} item(s).")
|
||||
index = conv_index
|
||||
return index
|
||||
|
||||
|
||||
def convert_to_index_int(raw_index: str, length: int=0, is_range: bool=False, allow_negative=False, allow_missing=False) -> int:
|
||||
try:
|
||||
return validate_index(int(raw_index), length=length, is_range=is_range, allow_negative=allow_negative, allow_missing=allow_missing)
|
||||
except ValueError as e:
|
||||
raise ValueError(f"Index '{raw_index}' must be an integer.", e)
|
||||
|
||||
|
||||
def convert_str_to_indexes(indexes_str: str, length: int=0, allow_missing=False) -> list[int]:
|
||||
if not indexes_str:
|
||||
return []
|
||||
int_indexes = list(range(0, length))
|
||||
allow_negative = length > 0
|
||||
chosen_indexes = []
|
||||
# parse string - allow positive ints, negative ints, and ranges separated by ':'
|
||||
groups = indexes_str.split(",")
|
||||
groups = [g.strip() for g in groups]
|
||||
for g in groups:
|
||||
# parse range of indeces (e.g. 2:16)
|
||||
if ':' in g:
|
||||
index_range = g.split(":", 2)
|
||||
index_range = [r.strip() for r in index_range]
|
||||
|
||||
start_index = index_range[0]
|
||||
if len(start_index) > 0:
|
||||
start_index = convert_to_index_int(start_index, length=length, is_range=True, allow_negative=allow_negative, allow_missing=allow_missing)
|
||||
else:
|
||||
start_index = 0
|
||||
end_index = index_range[1]
|
||||
if len(end_index) > 0:
|
||||
end_index = convert_to_index_int(end_index, length=length, is_range=True, allow_negative=allow_negative, allow_missing=allow_missing)
|
||||
else:
|
||||
end_index = length
|
||||
# support step as well, to allow things like reversing, every-other, etc.
|
||||
step = 1
|
||||
if len(index_range) > 2:
|
||||
step = index_range[2]
|
||||
if len(step) > 0:
|
||||
step = convert_to_index_int(step, length=length, is_range=True, allow_negative=True, allow_missing=True)
|
||||
else:
|
||||
step = 1
|
||||
# if latents were passed in, base indeces on known latent count
|
||||
if len(int_indexes) > 0:
|
||||
chosen_indexes.extend(int_indexes[start_index:end_index][::step])
|
||||
# otherwise, assume indeces are valid
|
||||
else:
|
||||
chosen_indexes.extend(list(range(start_index, end_index, step)))
|
||||
# parse individual indeces
|
||||
else:
|
||||
chosen_indexes.append(convert_to_index_int(g, length=length, allow_negative=allow_negative, allow_missing=allow_missing))
|
||||
return chosen_indexes
|
||||
|
||||
|
||||
def select_indexes(input_obj: Union[Tensor, list], idxs: list):
|
||||
if type(input_obj) == Tensor:
|
||||
return input_obj[idxs]
|
||||
else:
|
||||
return [input_obj[i] for i in idxs]
|
||||
|
||||
def merge_filter_args(args, ftype="-vf"):
|
||||
#TODO This doesn't account for filter_complex
|
||||
#Will likely need to convert all filters to filter complex in the future
|
||||
#But that requires source/output deduplication
|
||||
try:
|
||||
start_index = args.index(ftype)+1
|
||||
index = start_index
|
||||
while True:
|
||||
index = args.index(ftype, index)
|
||||
args[start_index] += ',' + args[index+1]
|
||||
args.pop(index)
|
||||
args.pop(index)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
def select_indexes_from_str(input_obj: Union[Tensor, list], indexes: str, err_if_missing=True, err_if_empty=True):
|
||||
real_idxs = convert_str_to_indexes(indexes, len(input_obj), allow_missing=not err_if_missing)
|
||||
if err_if_empty and len(real_idxs) == 0:
|
||||
raise Exception(f"Nothing was selected based on indexes found in '{indexes}'.")
|
||||
return select_indexes(input_obj, real_idxs)
|
||||
|
||||
def hook(obj, attr):
|
||||
def dec(f):
|
||||
f = functools.update_wrapper(f, getattr(obj,attr))
|
||||
setattr(obj,attr,f)
|
||||
return f
|
||||
return dec
|
||||
|
||||
def cached(duration):
|
||||
def dec(f):
|
||||
cached_ret = None
|
||||
cache_time = 0
|
||||
def cached_func():
|
||||
nonlocal cache_time, cached_ret
|
||||
if time.time() > cache_time + duration or cached_ret is None:
|
||||
cache_time = time.time()
|
||||
cached_ret = f()
|
||||
return cached_ret
|
||||
return cached_func
|
||||
return dec
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or Derivative
|
||||
Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2026 ComfyUI-VOSR2 contributors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Package entrypoint.
|
||||
|
||||
Runs an explicit dependency/version check *before* importing anything that
|
||||
touches torch, einops, or safetensors at module scope (``nodes_vosr`` ->
|
||||
``loader``/``inference`` -> ``models/*``). Without this, an incompatible
|
||||
environment (old torch missing ``torch.compiler``, a stripped-down install
|
||||
missing ``einops``) fails deep inside a vendored architecture file with an
|
||||
opaque ``AttributeError``/``ImportError``, and ComfyUI just logs "module
|
||||
failed to load" with that traceback -- the node pack silently vanishes from
|
||||
the UI with no actionable message. Failing loudly and clearly here, at the
|
||||
top of the package, keeps that diagnosis one log line instead of a stack
|
||||
trace hunt.
|
||||
"""
|
||||
import logging
|
||||
|
||||
_MIN_TORCH = (2, 1) # torch.compiler.disable (models/pos_embed.py) needs >=2.1;
|
||||
# F.scaled_dot_product_attention needs >=2.0.
|
||||
|
||||
|
||||
def _check_dependencies() -> None:
|
||||
try:
|
||||
import torch
|
||||
except ImportError as exc:
|
||||
msg = (
|
||||
"ComfyUI-VOSR2 requires PyTorch, but it could not be imported. "
|
||||
"This normally ships with ComfyUI itself -- check your ComfyUI "
|
||||
"install."
|
||||
)
|
||||
logging.error("[VOSR2] %s", msg)
|
||||
raise ImportError(msg) from exc
|
||||
|
||||
version = tuple(int(p) for p in torch.__version__.split("+")[0].split(".")[:2])
|
||||
if version < _MIN_TORCH:
|
||||
msg = (
|
||||
f"ComfyUI-VOSR2 requires PyTorch >= {'.'.join(map(str, _MIN_TORCH))} "
|
||||
f"(uses torch.compiler and scaled_dot_product_attention), found "
|
||||
f"{torch.__version__}. Upgrade PyTorch, or update ComfyUI to a build "
|
||||
f"that ships a newer torch."
|
||||
)
|
||||
logging.error("[VOSR2] %s", msg)
|
||||
raise ImportError(msg)
|
||||
|
||||
for pkg in ("einops", "safetensors"):
|
||||
try:
|
||||
__import__(pkg)
|
||||
except ImportError as exc:
|
||||
msg = (
|
||||
f"ComfyUI-VOSR2 requires the '{pkg}' package, which normally "
|
||||
f"ships with ComfyUI core but was not found in this environment. "
|
||||
f"Install it with `pip install {pkg}` in ComfyUI's Python "
|
||||
f"environment."
|
||||
)
|
||||
logging.error("[VOSR2] %s", msg)
|
||||
raise ImportError(msg) from exc
|
||||
|
||||
|
||||
_check_dependencies()
|
||||
|
||||
from .nodes_vosr import comfy_entrypoint
|
||||
|
||||
# Serves web/docs/<node_id>.md as each node's in-UI help page. See
|
||||
# https://docs.comfy.org/custom-nodes/backend/help_page
|
||||
WEB_DIRECTORY = "web"
|
||||
|
||||
__all__ = ["comfy_entrypoint", "WEB_DIRECTORY"]
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Torch-native color alignment, ported from VOSR's inference_vosr_onestep.py.
|
||||
|
||||
Upstream implements `adain_color_fix`/`wavelet_color_fix` via PIL round-trips and
|
||||
OpenCV's GaussianBlur on uint8 arrays. VOSR2's contract requires float precision
|
||||
throughout with no PIL/uint8 quantization and no OpenCV dependency, so both are
|
||||
reimplemented here directly on BCHW float tensors in [0, 1], with a small separable
|
||||
Gaussian blur standing in for `cv2.GaussianBlur`.
|
||||
"""
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
ADAIN_EPS = 1e-5
|
||||
WAVELET_SIGMA = 5.0
|
||||
|
||||
|
||||
def _gaussian_kernel1d(sigma: float, radius: int, device, dtype) -> torch.Tensor:
|
||||
x = torch.arange(-radius, radius + 1, device=device, dtype=torch.float32)
|
||||
kernel = torch.exp(-(x**2) / (2.0 * sigma * sigma))
|
||||
kernel = kernel / kernel.sum()
|
||||
return kernel.to(dtype)
|
||||
|
||||
|
||||
def gaussian_blur(x: torch.Tensor, sigma: float) -> torch.Tensor:
|
||||
"""Separable Gaussian blur, reflect-padded, applied per-channel. x: (B, C, H, W).
|
||||
|
||||
Reflect padding requires the pad width to be smaller than the dimension it
|
||||
pads, so each axis' kernel radius is capped to fit -- this only narrows the
|
||||
(already Gaussian-tapered) kernel tail on tiles/images smaller than ~8*sigma
|
||||
pixels, it never errors.
|
||||
"""
|
||||
c, h, w = x.shape[1], x.shape[2], x.shape[3]
|
||||
desired_radius = max(int(math.ceil(sigma * 4.0)), 1)
|
||||
radius_h = max(min(desired_radius, h - 1), 0)
|
||||
radius_w = max(min(desired_radius, w - 1), 0)
|
||||
|
||||
if radius_w > 0:
|
||||
kernel_h = _gaussian_kernel1d(sigma, radius_w, x.device, x.dtype).view(1, 1, 1, -1).expand(c, 1, 1, -1)
|
||||
x = F.pad(x, (radius_w, radius_w, 0, 0), mode="reflect")
|
||||
x = F.conv2d(x, kernel_h, groups=c)
|
||||
if radius_h > 0:
|
||||
kernel_v = _gaussian_kernel1d(sigma, radius_h, x.device, x.dtype).view(1, 1, -1, 1).expand(c, 1, -1, 1)
|
||||
x = F.pad(x, (0, 0, radius_h, radius_h), mode="reflect")
|
||||
x = F.conv2d(x, kernel_v, groups=c)
|
||||
return x
|
||||
|
||||
|
||||
def adain_color_fix(target: torch.Tensor, source: torch.Tensor) -> torch.Tensor:
|
||||
"""Match target's per-channel spatial mean/std to source. Both (B, C, H, W) in [0, 1]."""
|
||||
target_mean = target.mean(dim=[2, 3], keepdim=True)
|
||||
target_std = target.std(dim=[2, 3], keepdim=True) + ADAIN_EPS
|
||||
source_mean = source.mean(dim=[2, 3], keepdim=True)
|
||||
source_std = source.std(dim=[2, 3], keepdim=True) + ADAIN_EPS
|
||||
result = (target - target_mean) / target_std * source_std + source_mean
|
||||
return torch.clamp(result, 0.0, 1.0)
|
||||
|
||||
|
||||
def wavelet_color_fix(target: torch.Tensor, source: torch.Tensor) -> torch.Tensor:
|
||||
"""Combine source's low frequencies with target's high frequencies. Both (B, C, H, W) in [0, 1]."""
|
||||
source_low = gaussian_blur(source, WAVELET_SIGMA)
|
||||
target_low = gaussian_blur(target, WAVELET_SIGMA)
|
||||
target_high = target - target_low
|
||||
result = source_low + target_high
|
||||
return torch.clamp(result, 0.0, 1.0)
|
||||
|
||||
|
||||
def apply_color_alignment(decoded: torch.Tensor, reference: torch.Tensor, mode: str) -> torch.Tensor:
|
||||
"""decoded/reference: (B, C, H, W) float in [0, 1], same spatial size."""
|
||||
if mode == "none":
|
||||
return torch.clamp(decoded, 0.0, 1.0)
|
||||
if mode == "adain":
|
||||
return adain_color_fix(decoded, reference)
|
||||
if mode == "wavelet":
|
||||
return wavelet_color_fix(decoded, reference)
|
||||
raise ValueError(f"Unknown color_alignment mode: {mode!r}")
|
||||
@@ -0,0 +1,218 @@
|
||||
"""VOSR2 inference contract: bicubic pre-scale, pad, encode, one-step denoise,
|
||||
decode, color-align, crop -- with optional DiT/VAE tiling. See VOSR2.md
|
||||
"Inference contract" and "Tiling".
|
||||
|
||||
`forward_flexible` (models/lightningdit.py) asserts a square input -- true of
|
||||
every upstream tiled call (tiles are always cropped `lt_size x lt_size`), but
|
||||
not of a whole non-square image's latent. To support arbitrary aspect ratios
|
||||
without tiling, the untiled path additionally pads to a square before the DiT
|
||||
call and crops back afterward; this is invisible in the output (still cropped
|
||||
to the exact requested size) and only engages when tile_size == 0.
|
||||
"""
|
||||
import logging
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
import comfy.utils
|
||||
|
||||
from .color import apply_color_alignment
|
||||
from .tiled_vae import _gaussian_weights, _make_tile_grid
|
||||
|
||||
AE_FACTOR = 8
|
||||
DIT_PATCH_SIZE = 2
|
||||
PAD_MULTIPLE = AE_FACTOR * DIT_PATCH_SIZE # 16
|
||||
|
||||
|
||||
def _pad_to_multiple(x: torch.Tensor, multiple: int):
|
||||
_, _, h, w = x.shape
|
||||
pad_h = (multiple - h % multiple) % multiple
|
||||
pad_w = (multiple - w % multiple) % multiple
|
||||
if pad_h == 0 and pad_w == 0:
|
||||
return x
|
||||
return F.pad(x, (0, pad_w, 0, pad_h), mode="reflect")
|
||||
|
||||
|
||||
def _pad_to_square(x: torch.Tensor):
|
||||
_, _, h, w = x.shape
|
||||
side = max(h, w)
|
||||
pad_h, pad_w = side - h, side - w
|
||||
if pad_h == 0 and pad_w == 0:
|
||||
return x
|
||||
return F.pad(x, (0, pad_w, 0, pad_h), mode="reflect")
|
||||
|
||||
|
||||
def _generate_noise(shape, seed: int, device, dtype) -> torch.Tensor:
|
||||
"""One item's worth of noise per call; a local CPU Generator keeps global RNG state untouched."""
|
||||
generator = torch.Generator(device="cpu").manual_seed(seed)
|
||||
noise = torch.randn(shape, generator=generator, dtype=torch.float32)
|
||||
return noise.to(device=device, dtype=dtype)
|
||||
|
||||
|
||||
def _generate_noise_batch(shape_per_item, seed: int, batch_size: int, device, dtype) -> torch.Tensor:
|
||||
return torch.stack([_generate_noise(shape_per_item, seed + i, device, dtype) for i in range(batch_size)], dim=0)
|
||||
|
||||
|
||||
def _tile_params(tile_size: int, tile_overlap: int, lh: int, lw: int):
|
||||
"""Pixel tile size/overlap -> latent-space, aligned to the DiT patch size."""
|
||||
lt_size = max((tile_size // AE_FACTOR // DIT_PATCH_SIZE) * DIT_PATCH_SIZE, DIT_PATCH_SIZE)
|
||||
lt_overlap = max(tile_overlap // AE_FACTOR, lt_size // 8)
|
||||
lt_size = min(lt_size, min(lh, lw))
|
||||
lt_overlap = min(lt_overlap, lt_size - 1)
|
||||
return lt_size, lt_overlap
|
||||
|
||||
|
||||
def _resize_to_target(images_bhwc01: torch.Tensor, upscale: int, device) -> torch.Tensor:
|
||||
x = images_bhwc01.movedim(-1, 1).to(device) # BCHW [0, 1]
|
||||
_, _, h, w = x.shape
|
||||
target_h, target_w = h * upscale, w * upscale
|
||||
return F.interpolate(x, size=(target_h, target_w), mode="bicubic").clamp(0.0, 1.0)
|
||||
|
||||
|
||||
def _run_untiled_batch(model, resized01: torch.Tensor, seed: int, vae_tile_size: int, vae_tile_overlap: int) -> torch.Tensor:
|
||||
b, _, h, w = resized01.shape
|
||||
padded01 = _pad_to_multiple(resized01, PAD_MULTIPLE)
|
||||
padded01 = _pad_to_square(padded01)
|
||||
padded_pm1 = padded01 * 2.0 - 1.0
|
||||
|
||||
lq_latent, latents_mean, latents_std = model.encode_tiled(padded_pm1, vae_tile_size, vae_tile_overlap)
|
||||
venc_fea = model.vision_features(padded01)
|
||||
|
||||
noise = _generate_noise_batch(lq_latent.shape[1:], seed, b, lq_latent.device, lq_latent.dtype)
|
||||
sr_latent = model.denoise_one_step(lq_latent, noise, venc_fea)
|
||||
decoded_pm1 = model.decode_tiled(sr_latent, latents_mean, latents_std, vae_tile_size, vae_tile_overlap)
|
||||
|
||||
return decoded_pm1[:, :, :h, :w]
|
||||
|
||||
|
||||
def _count_dit_tiles(h: int, w: int, tile_size: int, tile_overlap: int) -> int:
|
||||
"""Tiles a `run_vosr2` will submit to the DiT for one already-upscaled HxW image, for progress reporting."""
|
||||
padded_h = h + (-h) % PAD_MULTIPLE
|
||||
padded_w = w + (-w) % PAD_MULTIPLE
|
||||
lh, lw = padded_h // AE_FACTOR, padded_w // AE_FACTOR
|
||||
lt_size, lt_overlap = _tile_params(tile_size, tile_overlap, lh, lw)
|
||||
if lh <= lt_size and lw <= lt_size:
|
||||
return 1
|
||||
return len(_make_tile_grid(lh, lt_size, lt_overlap)) * len(_make_tile_grid(lw, lt_size, lt_overlap))
|
||||
|
||||
|
||||
def _run_tiled_single(model, resized01: torch.Tensor, seed: int, tile_size: int, tile_overlap: int,
|
||||
vae_tile_size: int, vae_tile_overlap: int, pbar: comfy.utils.ProgressBar = None) -> torch.Tensor:
|
||||
"""Latent-space tiled DiT inference for one image (B=1). Ported from VOSR's tiled_latent_inference."""
|
||||
_, _, h, w = resized01.shape
|
||||
padded01 = _pad_to_multiple(resized01, PAD_MULTIPLE)
|
||||
padded_pm1 = padded01 * 2.0 - 1.0
|
||||
|
||||
lq_latent, latents_mean, latents_std = model.encode_tiled(padded_pm1, vae_tile_size, vae_tile_overlap)
|
||||
_, lc, lh, lw = lq_latent.shape
|
||||
lt_size, lt_overlap = _tile_params(tile_size, tile_overlap, lh, lw)
|
||||
|
||||
if lh <= lt_size and lw <= lt_size:
|
||||
lq_sq = _pad_to_square(lq_latent)
|
||||
venc_fea = model.vision_features(padded01)
|
||||
noise = _generate_noise(lq_sq.shape[1:], seed, lq_sq.device, lq_sq.dtype).unsqueeze(0)
|
||||
sr_latent = model.denoise_one_step(lq_sq, noise, venc_fea)[:, :, :lh, :lw]
|
||||
if pbar is not None:
|
||||
pbar.update_absolute(pbar.current + 1)
|
||||
else:
|
||||
h_pos = _make_tile_grid(lh, lt_size, lt_overlap)
|
||||
w_pos = _make_tile_grid(lw, lt_size, lt_overlap)
|
||||
g_weight = _gaussian_weights(lt_size, lt_size, lc, lq_latent.device)
|
||||
|
||||
tile_venc = {}
|
||||
for hi in h_pos:
|
||||
for wi in w_pos:
|
||||
ph_s, pw_s = hi * AE_FACTOR, wi * AE_FACTOR
|
||||
ph_e = min((hi + lt_size) * AE_FACTOR, padded01.shape[2])
|
||||
pw_e = min((wi + lt_size) * AE_FACTOR, padded01.shape[3])
|
||||
tile_venc[(hi, wi)] = model.vision_features(padded01[:, :, ph_s:ph_e, pw_s:pw_e])
|
||||
|
||||
noise = _generate_noise(lq_latent.shape[1:], seed, lq_latent.device, lq_latent.dtype).unsqueeze(0)
|
||||
z = noise
|
||||
|
||||
u_acc = torch.zeros_like(lq_latent)
|
||||
w_acc = torch.zeros_like(lq_latent)
|
||||
for hi in h_pos:
|
||||
for wi in w_pos:
|
||||
he, we = hi + lt_size, wi + lt_size
|
||||
inp = torch.cat([lq_latent[:, :, hi:he, wi:we], z[:, :, hi:he, wi:we]], dim=1)
|
||||
u_tile = model.dit_velocity(inp, 1.0, 0.0, tile_venc[(hi, wi)])
|
||||
u_acc[:, :, hi:he, wi:we] += u_tile * g_weight
|
||||
w_acc[:, :, hi:he, wi:we] += g_weight
|
||||
if pbar is not None:
|
||||
pbar.update_absolute(pbar.current + 1)
|
||||
|
||||
sr_latent = z - u_acc / w_acc
|
||||
|
||||
decoded_pm1 = model.decode_tiled(sr_latent, latents_mean, latents_std, vae_tile_size, vae_tile_overlap)
|
||||
return decoded_pm1[:, :, :h, :w]
|
||||
|
||||
|
||||
def run_vosr2(
|
||||
model,
|
||||
images_bhwc01: torch.Tensor,
|
||||
upscale: int,
|
||||
seed: int,
|
||||
color_alignment: str,
|
||||
tile_size: int,
|
||||
tile_overlap: int,
|
||||
vae_tile_size: int,
|
||||
vae_tile_overlap: int,
|
||||
) -> torch.Tensor:
|
||||
if images_bhwc01.shape[-1] != 3:
|
||||
raise ValueError(f"VOSR2Upscale expects a 3-channel RGB IMAGE, got {images_bhwc01.shape[-1]} channels.")
|
||||
if tile_size > 0 and tile_overlap >= tile_size:
|
||||
raise ValueError(f"VOSR2Upscale: tile_overlap ({tile_overlap}) must be smaller than tile_size ({tile_size}).")
|
||||
if vae_tile_size > 0 and vae_tile_overlap >= vae_tile_size:
|
||||
raise ValueError(f"VOSR2Upscale: vae_tile_overlap ({vae_tile_overlap}) must be smaller than vae_tile_size ({vae_tile_size}).")
|
||||
|
||||
device = model.dit_patcher.load_device
|
||||
resized01 = _resize_to_target(images_bhwc01, upscale, device)
|
||||
b, _, h, w = resized01.shape
|
||||
|
||||
if tile_size == 0 and (h > 512 or w > 512):
|
||||
logging.warning(
|
||||
f"VOSR2Upscale: target size {w}x{h} (after {upscale}x upscale) exceeds VOSR 2.0's "
|
||||
f"native 512px training resolution with tile_size=0 (DiT tiling disabled). VOSR2.md "
|
||||
f"states tiling is not optional above 512px -- set tile_size > 0 (e.g. 512) or "
|
||||
f"quality will likely degrade."
|
||||
)
|
||||
if vae_tile_size == 0 and (h > 1024 or w > 1024):
|
||||
logging.warning(
|
||||
f"VOSR2Upscale: target size {w}x{h} (after {upscale}x upscale) with vae_tile_size=0 "
|
||||
f"(VAE tiling disabled) decodes the full image in one pass regardless of tile_size -- "
|
||||
f"this is a common source of CUDA out-of-memory errors at this resolution. Set "
|
||||
f"vae_tile_size > 0 (e.g. 1024) to bound peak VRAM."
|
||||
)
|
||||
|
||||
if tile_size > 0:
|
||||
_, _, h, w = resized01.shape
|
||||
total_tiles = b * _count_dit_tiles(h, w, tile_size, tile_overlap)
|
||||
pbar = comfy.utils.ProgressBar(total_tiles)
|
||||
# Tiling bounds peak VRAM per item, but a batch's items were still
|
||||
# accumulating on GPU here until the final cat -- peak VRAM grew with
|
||||
# batch_size x output resolution regardless of tile_size, defeating
|
||||
# the point for large multi-item batches. Move each item off the GPU
|
||||
# as soon as it's decoded so only one item's output is ever GPU-
|
||||
# resident at a time.
|
||||
#
|
||||
# Color alignment also has to happen per item here, not on the
|
||||
# concatenated batch afterward: wavelet/adain run a Gaussian blur
|
||||
# over the whole tensor at once (color.py), so doing it post-concat
|
||||
# means one CPU allocation sized to the *entire* batch's decoded
|
||||
# output -- for large images/batches that's tens of GB of system
|
||||
# RAM even though nothing is GPU-resident anymore. Aligning each
|
||||
# item right after it's decoded caps that allocation at one item's
|
||||
# size, matching the per-item VRAM bound above.
|
||||
aligned_items = []
|
||||
for i in range(b):
|
||||
item_pm1 = _run_tiled_single(model, resized01[i:i + 1], seed + i, tile_size, tile_overlap, vae_tile_size, vae_tile_overlap, pbar=pbar).cpu()
|
||||
item01 = (item_pm1.clamp(-1.0, 1.0) + 1.0) / 2.0
|
||||
aligned_items.append(apply_color_alignment(item01, resized01[i:i + 1].cpu(), color_alignment))
|
||||
aligned01 = torch.cat(aligned_items, dim=0)
|
||||
else:
|
||||
outputs_pm1 = _run_untiled_batch(model, resized01, seed, vae_tile_size, vae_tile_overlap)
|
||||
decoded01 = (outputs_pm1.clamp(-1.0, 1.0) + 1.0) / 2.0
|
||||
aligned01 = apply_color_alignment(decoded01, resized01, color_alignment)
|
||||
|
||||
return aligned01.movedim(1, -1)
|
||||
@@ -0,0 +1,415 @@
|
||||
"""Discovery and strict loading of a VOSR 2.0 bundle.
|
||||
|
||||
A bundle is a self-contained folder under ``ComfyUI/models/vosr2/`` -- VOSR 2.0
|
||||
is a fixed DiT/VAE/DINOv2 triple (see the layout comment below), so the three
|
||||
pieces are not independently selectable and live together:
|
||||
|
||||
ComfyUI/models/vosr2/<bundle>/
|
||||
args.json
|
||||
checkpoints/ema_model.safetensors (or clean_weights/, or bundle root)
|
||||
Qwen-Image-vae-2d/{config.json, diffusion_pytorch_model.safetensors}
|
||||
dinov2_vitl14.safetensors
|
||||
|
||||
The confirmed bundle is fetched from the pinned Hugging Face repo ``CSWRY/VOSR``
|
||||
on first use, but only for parts that are missing -- once the files are in place
|
||||
nothing here touches the network. See ``ensure_vosr2_files``.
|
||||
|
||||
The ``model`` combo value is re-joined against ``_VOSR2_ROOT`` via
|
||||
``_safe_child_dir``, never taken as -- or resolved through -- an arbitrary path.
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from safetensors.torch import load_file, save_file
|
||||
|
||||
import comfy.model_management
|
||||
import comfy.model_patcher
|
||||
import comfy.utils
|
||||
import folder_paths
|
||||
|
||||
from .models.dinov2 import build_dinov2_vitl14
|
||||
from .models.lightningdit import LightningDiT
|
||||
from .models.qwenimage_vae2d import AutoencoderKLQwenImage2D
|
||||
|
||||
VOSR2_FOLDER_KEY = "vosr2"
|
||||
|
||||
_VOSR2_ROOT = Path(folder_paths.models_dir) / "vosr2"
|
||||
_VOSR2_ROOT.mkdir(parents=True, exist_ok=True)
|
||||
folder_paths.add_model_folder_path(VOSR2_FOLDER_KEY, str(_VOSR2_ROOT))
|
||||
|
||||
# VOSR 2.0 is one indivisible artifact: the DiT runs entirely in *this* Qwen 2D
|
||||
# VAE's latent space (its channel count, scale factor, and per-channel
|
||||
# latents_mean/std), and is conditioned on *this* DINOv2-L feature extractor.
|
||||
# None of the three can be swapped independently, so they live together inside a
|
||||
# single bundle folder rather than in ComfyUI's shared vae/ and clip_vision/
|
||||
# trees. A bundle is a subdirectory of models/vosr2/ laid out as:
|
||||
# <bundle>/args.json
|
||||
# <bundle>/checkpoints/ema_model.safetensors (or clean_weights/, or bundle root)
|
||||
# <bundle>/Qwen-Image-vae-2d/{config.json,diffusion_pytorch_model.safetensors}
|
||||
# <bundle>/dinov2_vitl14.safetensors
|
||||
HF_REPO_ID = "CSWRY/VOSR"
|
||||
KNOWN_MODEL = "VOSR2" # the one confirmed bundle; also the combo default
|
||||
_VAE_SUBDIR = "Qwen-Image-vae-2d" # diffusers VAE dir inside the bundle
|
||||
_VAE_FILES = ("config.json", "diffusion_pytorch_model.safetensors")
|
||||
_VISION_FILENAME = "dinov2_vitl14.safetensors" # converted DINOv2-L, inside the bundle
|
||||
|
||||
# Paths of each piece inside the pinned HF repo. The DiT files carry a "VOSR2/"
|
||||
# prefix that becomes the bundle dir; the VAE files are fetched into the bundle.
|
||||
_DIT_HF_FILES = ("VOSR2/args.json", "VOSR2/checkpoints/ema_model.safetensors")
|
||||
_VAE_HF_FILES = tuple(f"{_VAE_SUBDIR}/{name}" for name in _VAE_FILES)
|
||||
# DINOv2-L ships upstream as a raw torch pickle; the loader converts it to
|
||||
# safetensors on download (this package only ever ``load_file``s .safetensors).
|
||||
_DINOV2_HF_FILE = "torch_cache/checkpoints/dinov2_vitl14_pretrain.pth"
|
||||
|
||||
# Required args.json values for a VOSR 2.0 (one-step 1.4B) checkpoint. See
|
||||
# VOSR2.md "Author confirmation" -- these fields are confirmed to have no
|
||||
# effect, or to be architecturally fixed, for this specific release.
|
||||
REQUIRED_ARGS = {
|
||||
"ae_type": "qwen",
|
||||
"dim": 1536,
|
||||
"depth": 36,
|
||||
"num_heads": 24,
|
||||
"patch_size": 2,
|
||||
"enc_type": "dinov2l",
|
||||
"enc_dim": 1024,
|
||||
"layer_dinov2b_list": [17],
|
||||
"auxiliary_time_cond": False,
|
||||
"distill_type": "onestep",
|
||||
}
|
||||
|
||||
# DiT construction params that must be present in args.json but whose value is
|
||||
# taken from the checkpoint rather than pinned by REQUIRED_ARGS.
|
||||
DIT_ARG_KEYS = ("mlp_ratio", "use_qknorm", "use_swiglu", "use_rope", "use_rmsnorm", "encdim_ratio", "resolution")
|
||||
|
||||
# Known training-only key patterns that may be present in an EMA/distillation
|
||||
# checkpoint but have no corresponding module in the inference-only LightningDiT
|
||||
# above (e.g. an EMA wrapper's step counter). Extend this list, don't relax
|
||||
# strict loading, if a real checkpoint surfaces another such key.
|
||||
_TRAINING_ONLY_KEY_PATTERNS = (
|
||||
re.compile(r"^n_averaged$"),
|
||||
re.compile(r"^step_count$"),
|
||||
re.compile(r"^decay$"),
|
||||
)
|
||||
_STRIPPABLE_PREFIXES = ("module.", "_orig_mod.", "ema_model.")
|
||||
|
||||
|
||||
class VOSR2LoadError(RuntimeError):
|
||||
"""Raised for any missing file, incompatible config, or malformed state dict."""
|
||||
|
||||
|
||||
def _safe_child_dir(root: Path, name: str) -> Path:
|
||||
if not name or "/" in name or "\\" in name or name in (".", ".."):
|
||||
raise VOSR2LoadError(f"Invalid VOSR2 selection: {name!r}")
|
||||
candidate = (root / name).resolve()
|
||||
root_resolved = root.resolve()
|
||||
if root_resolved not in candidate.parents and candidate != root_resolved:
|
||||
raise VOSR2LoadError(f"Invalid VOSR2 selection: {name!r}")
|
||||
return candidate
|
||||
|
||||
|
||||
def list_model_bundles() -> list:
|
||||
if not _VOSR2_ROOT.is_dir():
|
||||
return []
|
||||
return sorted(
|
||||
p.name for p in _VOSR2_ROOT.iterdir()
|
||||
if p.is_dir() and (p / "args.json").is_file()
|
||||
)
|
||||
|
||||
|
||||
def model_options() -> list:
|
||||
"""Bundle combo options: whatever is on disk, but always offering ``KNOWN_MODEL``.
|
||||
|
||||
ComfyUI snapshots combo ``options`` when the schema is built, so on a fresh
|
||||
install ``list_model_bundles()`` returns ``[]`` and the dropdown would be
|
||||
empty and unselectable. Seeding it with the confirmed name lets the user pick
|
||||
it and run; the loader then downloads that bundle on first execute.
|
||||
"""
|
||||
found = list_model_bundles()
|
||||
return found if KNOWN_MODEL in found else [KNOWN_MODEL, *found]
|
||||
|
||||
|
||||
def _convert_dinov2_pth_to_safetensors(src_pth: Path, dest: Path) -> None:
|
||||
# comfy.utils.load_torch_file wraps torch.load with ComfyUI's own
|
||||
# conventions (weights_only=True, mmap where supported, state_dict/
|
||||
# single-key unwrapping) instead of calling torch.load directly.
|
||||
state = comfy.utils.load_torch_file(str(src_pth), safe_load=True)
|
||||
if not isinstance(state, dict):
|
||||
raise VOSR2LoadError(
|
||||
f"Unexpected DINOv2 checkpoint format at {src_pth}: expected a flat state dict."
|
||||
)
|
||||
tensors = {k: v.contiguous() for k, v in state.items() if isinstance(v, torch.Tensor)}
|
||||
if not tensors:
|
||||
raise VOSR2LoadError(f"DINOv2 checkpoint at {src_pth} contained no tensors.")
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = dest.with_name(dest.name + ".tmp")
|
||||
save_file(tensors, str(tmp))
|
||||
tmp.replace(dest)
|
||||
|
||||
|
||||
def ensure_vosr2_files(model_name: str) -> None:
|
||||
"""Fetch the confirmed VOSR 2.0 bundle from ``CSWRY/VOSR`` for missing parts only.
|
||||
|
||||
A no-op once the files are present -- it never contacts the network then.
|
||||
Only ``KNOWN_MODEL`` can be auto-fetched; a custom bundle name that is absent
|
||||
is left for the normal "not found" error in ``load_vosr2``, since this code
|
||||
cannot know where such a bundle would come from.
|
||||
"""
|
||||
if model_name != KNOWN_MODEL:
|
||||
return
|
||||
|
||||
bundle = _VOSR2_ROOT / KNOWN_MODEL
|
||||
vae_dir = bundle / _VAE_SUBDIR
|
||||
|
||||
dit_missing = _find_dit_weight(bundle) is None or not (bundle / "args.json").is_file()
|
||||
vae_missing = not all((vae_dir / name).is_file() for name in _VAE_FILES)
|
||||
vision_missing = not (bundle / _VISION_FILENAME).is_file()
|
||||
|
||||
if not (dit_missing or vae_missing or vision_missing):
|
||||
return
|
||||
|
||||
try:
|
||||
from huggingface_hub import hf_hub_download
|
||||
except ImportError as exc:
|
||||
raise VOSR2LoadError(
|
||||
"VOSR 2.0 model files are missing and huggingface_hub is not available "
|
||||
"to download them. Install huggingface_hub (it normally ships with "
|
||||
"ComfyUI), or place the files manually -- see the README 'Model files' "
|
||||
"section."
|
||||
) from exc
|
||||
|
||||
if dit_missing:
|
||||
logging.info("[VOSR2] downloading DiT bundle from %s ...", HF_REPO_ID)
|
||||
for f in _DIT_HF_FILES:
|
||||
hf_hub_download(HF_REPO_ID, f, local_dir=str(_VOSR2_ROOT))
|
||||
if vae_missing:
|
||||
logging.info("[VOSR2] downloading Qwen-Image 2D VAE from %s ...", HF_REPO_ID)
|
||||
vae_dir.mkdir(parents=True, exist_ok=True)
|
||||
for f in _VAE_HF_FILES:
|
||||
hf_hub_download(HF_REPO_ID, f, local_dir=str(bundle))
|
||||
if vision_missing:
|
||||
logging.info("[VOSR2] downloading + converting DINOv2-L encoder from %s ...", HF_REPO_ID)
|
||||
src = hf_hub_download(HF_REPO_ID, _DINOV2_HF_FILE)
|
||||
_convert_dinov2_pth_to_safetensors(Path(src), bundle / _VISION_FILENAME)
|
||||
|
||||
|
||||
def _load_args_json(bundle_dir: Path) -> dict:
|
||||
args_path = bundle_dir / "args.json"
|
||||
if not args_path.is_file():
|
||||
raise VOSR2LoadError(f"VOSR2 model bundle at {bundle_dir} is missing args.json.")
|
||||
with open(args_path, "r") as f:
|
||||
args = json.load(f)
|
||||
|
||||
for key, expected in REQUIRED_ARGS.items():
|
||||
actual = args.get(key)
|
||||
if actual != expected:
|
||||
raise VOSR2LoadError(
|
||||
f"VOSR2 model bundle at {bundle_dir} has an incompatible config: "
|
||||
f"expected {key}={expected!r}, got {actual!r}. VOSR2 v1 supports only "
|
||||
f"the VOSR 2.0 one-step 1.4B checkpoint."
|
||||
)
|
||||
missing = [k for k in DIT_ARG_KEYS if k not in args]
|
||||
if missing:
|
||||
raise VOSR2LoadError(
|
||||
f"VOSR2 model bundle at {bundle_dir}'s args.json is missing required field(s): {missing}."
|
||||
)
|
||||
return args
|
||||
|
||||
|
||||
def _find_dit_weight(bundle_dir: Path):
|
||||
for candidate in (
|
||||
bundle_dir / "clean_weights" / "ema_model.safetensors",
|
||||
bundle_dir / "checkpoints" / "ema_model.safetensors",
|
||||
bundle_dir / "ema_model.safetensors",
|
||||
):
|
||||
if candidate.is_file():
|
||||
return candidate
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_dit_weight_path(bundle_dir: Path) -> Path:
|
||||
weight = _find_dit_weight(bundle_dir)
|
||||
if weight is None:
|
||||
raise VOSR2LoadError(
|
||||
f"No ema_model.safetensors found under {bundle_dir} "
|
||||
f"(looked in clean_weights/, checkpoints/, and the bundle root)."
|
||||
)
|
||||
return weight
|
||||
|
||||
|
||||
def _clean_state_dict_keys(state_dict: dict) -> dict:
|
||||
cleaned = {}
|
||||
for key, value in state_dict.items():
|
||||
stripped = key
|
||||
for prefix in _STRIPPABLE_PREFIXES:
|
||||
if stripped.startswith(prefix):
|
||||
stripped = stripped[len(prefix):]
|
||||
break
|
||||
if any(pattern.match(stripped) for pattern in _TRAINING_ONLY_KEY_PATTERNS):
|
||||
continue
|
||||
cleaned[stripped] = value
|
||||
return cleaned
|
||||
|
||||
|
||||
def _strict_load(module: torch.nn.Module, state_dict: dict, source: Path):
|
||||
state_dict = _clean_state_dict_keys(state_dict)
|
||||
missing, unexpected = module.load_state_dict(state_dict, strict=False)
|
||||
if missing or unexpected:
|
||||
raise VOSR2LoadError(
|
||||
f"VOSR2 checkpoint at {source} does not match the expected {type(module).__name__} "
|
||||
f"architecture (missing={missing}, unexpected={unexpected})."
|
||||
)
|
||||
|
||||
|
||||
def _resolve_dtype(dtype: str, device) -> torch.dtype:
|
||||
if dtype == "fp16":
|
||||
return torch.float16
|
||||
if dtype == "bf16":
|
||||
return torch.bfloat16
|
||||
if dtype == "default":
|
||||
return comfy.model_management.unet_dtype(device=device)
|
||||
raise VOSR2LoadError(f"Unknown dtype option: {dtype!r}")
|
||||
|
||||
|
||||
class VOSR2Model:
|
||||
"""Runtime bundle: independently offloadable DiT/VAE/vision-encoder plus config.
|
||||
|
||||
Exposes narrow operations (`vision_features`, `encode`, `denoise_one_step`,
|
||||
`decode`) rather than the raw modules, so callers never need to probe for
|
||||
capabilities on the wrapped components.
|
||||
"""
|
||||
|
||||
def __init__(self, dit_patcher, vae_patcher, vision_patcher, args: dict):
|
||||
self.dit_patcher = dit_patcher
|
||||
self.vae_patcher = vae_patcher
|
||||
self.vision_patcher = vision_patcher
|
||||
self.args = args
|
||||
self.vision_layer_index = args["layer_dinov2b_list"][0]
|
||||
self.dinov2_size = args.get("dinov2_size", 448)
|
||||
|
||||
def _load(self, patcher):
|
||||
comfy.model_management.load_models_gpu([patcher], force_full_load=True)
|
||||
return patcher.model, patcher.load_device
|
||||
|
||||
def vision_features(self, lq_bchw_01: torch.Tensor) -> list:
|
||||
"""lq_bchw_01: (B, 3, H, W) in [0, 1]. Returns a one-item list (fixed-index layer)."""
|
||||
model, device = self._load(self.vision_patcher)
|
||||
x = torch.nn.functional.interpolate(lq_bchw_01, size=(self.dinov2_size, self.dinov2_size), mode="bicubic").clamp(0.0, 1.0)
|
||||
mean = torch.tensor((0.485, 0.456, 0.406), device=device, dtype=x.dtype).view(1, 3, 1, 1)
|
||||
std = torch.tensor((0.229, 0.224, 0.225), device=device, dtype=x.dtype).view(1, 3, 1, 1)
|
||||
x = (x.to(device) - mean) / std
|
||||
feats = model.forward_intermediate_layer(x.to(model.pos_embed.dtype), self.vision_layer_index)
|
||||
return [feats]
|
||||
|
||||
def encode(self, x_bchw_neg1_1: torch.Tensor):
|
||||
from . import tiled_vae
|
||||
model, device = self._load(self.vae_patcher)
|
||||
return tiled_vae.encode_latent(model, x_bchw_neg1_1.to(device))
|
||||
|
||||
def encode_tiled(self, x_bchw_neg1_1: torch.Tensor, tile_size: int, tile_overlap: int):
|
||||
from . import tiled_vae
|
||||
model, device = self._load(self.vae_patcher)
|
||||
return tiled_vae.encode_dispatch(model, x_bchw_neg1_1.to(device), tile_size, tile_overlap)
|
||||
|
||||
def decode(self, latent: torch.Tensor, latents_mean, latents_std) -> torch.Tensor:
|
||||
from . import tiled_vae
|
||||
model, device = self._load(self.vae_patcher)
|
||||
return tiled_vae.decode_latent(model, latent.to(device), latents_mean, latents_std)
|
||||
|
||||
def decode_tiled(self, latent: torch.Tensor, latents_mean, latents_std, tile_size: int, tile_overlap: int) -> torch.Tensor:
|
||||
from . import tiled_vae
|
||||
model, device = self._load(self.vae_patcher)
|
||||
return tiled_vae.decode_dispatch(model, latent.to(device), latents_mean, latents_std, tile_size, tile_overlap)
|
||||
|
||||
def dit_velocity(self, inp: torch.Tensor, t_cur: float, t_next: float, venc_fea: list) -> torch.Tensor:
|
||||
"""Single DiT forward: predicted flow velocity for `inp = cat([lq_latent, z], dim=1)`."""
|
||||
model, device = self._load(self.dit_patcher)
|
||||
compute_dtype = model.t_embedder.mlp[0].weight.dtype
|
||||
inp = inp.to(device=device, dtype=compute_dtype)
|
||||
venc_fea = [f.to(device=device, dtype=compute_dtype) for f in venc_fea]
|
||||
b = inp.shape[0]
|
||||
t_cur_t = torch.full((b,), t_cur, device=device, dtype=compute_dtype)
|
||||
t_next_t = torch.full((b,), t_next, device=device, dtype=compute_dtype)
|
||||
return model.forward_flexible(inp, t_cur_t, t_next_t, venc_fea)
|
||||
|
||||
def denoise_one_step(self, lq_latent: torch.Tensor, noise: torch.Tensor, venc_fea: list) -> torch.Tensor:
|
||||
"""One Euler flow-matching update from t=1 to t=0 (VOSR2 is a one-step model)."""
|
||||
device = self.dit_patcher.load_device
|
||||
z = noise.to(device)
|
||||
u = self.dit_velocity(torch.cat([lq_latent.to(device), z], dim=1), 1.0, 0.0, venc_fea)
|
||||
return z - u
|
||||
|
||||
|
||||
def load_vosr2(model_name: str, dtype: str) -> VOSR2Model:
|
||||
ensure_vosr2_files(model_name)
|
||||
|
||||
bundle_dir = _safe_child_dir(_VOSR2_ROOT, model_name)
|
||||
if not bundle_dir.is_dir():
|
||||
raise VOSR2LoadError(f"VOSR2 model bundle not found: {model_name!r}")
|
||||
args = _load_args_json(bundle_dir)
|
||||
dit_weight_path = _resolve_dit_weight_path(bundle_dir)
|
||||
|
||||
# The VAE and vision encoder are part of the bundle -- VOSR 2.0 is a fixed
|
||||
# DiT/VAE/DINOv2 triple, not independently selectable components.
|
||||
vae_dir = bundle_dir / _VAE_SUBDIR
|
||||
if not (vae_dir / "config.json").is_file():
|
||||
raise VOSR2LoadError(
|
||||
f"VOSR2 bundle {bundle_dir} is missing its Qwen-Image 2D VAE "
|
||||
f"({vae_dir}/config.json). The VAE's latent space is tied to this DiT "
|
||||
f"and cannot be substituted."
|
||||
)
|
||||
|
||||
vision_path = bundle_dir / _VISION_FILENAME
|
||||
if not vision_path.is_file():
|
||||
raise VOSR2LoadError(
|
||||
f"VOSR2 bundle {bundle_dir} is missing its DINOv2-L encoder ({vision_path})."
|
||||
)
|
||||
|
||||
load_device = comfy.model_management.get_torch_device()
|
||||
offload_device = comfy.model_management.unet_offload_device()
|
||||
compute_dtype = _resolve_dtype(dtype, load_device)
|
||||
|
||||
base_channels = 16 # Qwen 2D VAE latent channels
|
||||
dit = LightningDiT(
|
||||
input_size=args["resolution"] // 8,
|
||||
patch_size=args["patch_size"],
|
||||
in_channels=2 * base_channels,
|
||||
out_channels=base_channels,
|
||||
hidden_size=args["dim"],
|
||||
depth=args["depth"],
|
||||
num_heads=args["num_heads"],
|
||||
mlp_ratio=args["mlp_ratio"],
|
||||
z_dims=args["enc_dim"],
|
||||
encdim_ratio=args["encdim_ratio"],
|
||||
auxiliary_time_cond=args["auxiliary_time_cond"],
|
||||
use_qknorm=args["use_qknorm"],
|
||||
use_swiglu=args["use_swiglu"],
|
||||
use_rope=args["use_rope"],
|
||||
use_rmsnorm=args["use_rmsnorm"],
|
||||
num_fused_layers=len(args["layer_dinov2b_list"]),
|
||||
)
|
||||
dit_state_dict = load_file(str(dit_weight_path))
|
||||
_strict_load(dit, dit_state_dict, dit_weight_path)
|
||||
dit = dit.eval().to(compute_dtype)
|
||||
for p in dit.parameters():
|
||||
p.requires_grad_(False)
|
||||
|
||||
vae = AutoencoderKLQwenImage2D.from_pretrained(str(vae_dir))
|
||||
vae = vae.eval().float() # Qwen VAE runs in fp32; see VOSR2.md "Device, dtype, and memory".
|
||||
for p in vae.parameters():
|
||||
p.requires_grad_(False)
|
||||
|
||||
vision_encoder = build_dinov2_vitl14()
|
||||
vision_state_dict = load_file(str(vision_path))
|
||||
_strict_load(vision_encoder, vision_state_dict, vision_path)
|
||||
vision_encoder = vision_encoder.eval().to(compute_dtype)
|
||||
for p in vision_encoder.parameters():
|
||||
p.requires_grad_(False)
|
||||
|
||||
dit_patcher = comfy.model_patcher.ModelPatcher(dit, load_device=load_device, offload_device=offload_device)
|
||||
vae_patcher = comfy.model_patcher.ModelPatcher(vae, load_device=load_device, offload_device=offload_device)
|
||||
vision_patcher = comfy.model_patcher.ModelPatcher(vision_encoder, load_device=load_device, offload_device=offload_device)
|
||||
|
||||
return VOSR2Model(dit_patcher, vae_patcher, vision_patcher, args)
|
||||
@@ -0,0 +1,86 @@
|
||||
import sys
|
||||
|
||||
from typing_extensions import override
|
||||
|
||||
from comfy_api.latest import ComfyExtension, io
|
||||
|
||||
from . import loader
|
||||
from .inference import run_vosr2
|
||||
from .loader import VOSR2Model
|
||||
|
||||
|
||||
class VOSR2ModelLoader(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls) -> io.Schema:
|
||||
return io.Schema(
|
||||
node_id="VOSR2ModelLoader",
|
||||
display_name="VOSR 2.0 Model Loader",
|
||||
category="image/upscaling/VOSR2",
|
||||
description="Load a VOSR 2.0 (one-step 1.4B) bundle: matched LightningDiT + Qwen-Image 2D VAE + DINOv2-L. The whole bundle is downloaded from the CSWRY/VOSR Hugging Face repo on first run if absent.",
|
||||
inputs=[
|
||||
io.Combo.Input("model", options=loader.model_options(), default=loader.KNOWN_MODEL, tooltip="VOSR 2.0 bundle folder under models/vosr2/ (DiT + its matched VAE + vision encoder). Downloaded from CSWRY/VOSR on first run if absent."),
|
||||
io.Combo.Input("dtype", options=["default", "fp16", "bf16"], default="default", tooltip="Compute dtype for the DiT and vision encoder. The VAE always runs in fp32."),
|
||||
],
|
||||
outputs=[
|
||||
io.Custom("VOSR2_MODEL").Output(display_name="model"),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, model, dtype) -> io.NodeOutput:
|
||||
bundle = loader.load_vosr2(model, dtype)
|
||||
return io.NodeOutput(bundle)
|
||||
|
||||
|
||||
class VOSR2Upscale(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls) -> io.Schema:
|
||||
return io.Schema(
|
||||
node_id="VOSR2Upscale",
|
||||
display_name="VOSR 2.0 Upscale",
|
||||
category="image/upscaling/VOSR2",
|
||||
description="One-step VOSR 2.0 image super-resolution.",
|
||||
inputs=[
|
||||
io.Custom("VOSR2_MODEL").Input("model", tooltip="Loaded VOSR 2.0 bundle."),
|
||||
io.Image.Input("image"),
|
||||
io.Int.Input("upscale", default=4, min=1, max=sys.maxsize, tooltip="Exact output multiplier. VOSR 2.0 was trained on degradations up to 16x, so higher factors are supported, but there's no general quality guarantee above ~4x -- results depend on the specific image and starting/target resolution, not just the factor. Uncapped so you can experiment; use tiling for large outputs."),
|
||||
io.Int.Input("seed", default=42, min=0, max=sys.maxsize, control_after_generate=io.ControlAfterGenerate.fixed, tooltip="Initial latent-noise seed."),
|
||||
io.Combo.Input("color_alignment", options=["wavelet", "adain", "none"], default="wavelet"),
|
||||
io.Int.Input("tile_size", default=0, min=0, max=4096, step=64, tooltip="DiT pixel tile size; 0 disables tiling. VOSR 2.0 was trained natively at up to 512px, so tiling is required (e.g. 512) whenever the upscaled output exceeds 512x512 -- otherwise quality degrades."),
|
||||
io.Int.Input("tile_overlap", default=32, min=0, max=512, step=8),
|
||||
io.Int.Input("vae_tile_size", default=0, min=0, max=8192, step=64, tooltip="VAE pixel tile size; 0 disables VAE tiling and decodes the full image in one pass regardless of tile_size -- a common source of CUDA OOM once the upscaled output goes much past 1024px. Set a nonzero value (e.g. 1024) for large outputs."),
|
||||
io.Int.Input("vae_tile_overlap", default=32, min=0, max=512, step=8),
|
||||
],
|
||||
outputs=[
|
||||
io.Image.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def validate_inputs(cls, model, image, upscale, seed, color_alignment, tile_size, tile_overlap, vae_tile_size, vae_tile_overlap):
|
||||
if tile_size > 0 and tile_overlap >= tile_size:
|
||||
return f"tile_overlap ({tile_overlap}) must be smaller than tile_size ({tile_size})."
|
||||
if vae_tile_size > 0 and vae_tile_overlap >= vae_tile_size:
|
||||
return f"vae_tile_overlap ({vae_tile_overlap}) must be smaller than vae_tile_size ({vae_tile_size})."
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def execute(cls, model: VOSR2Model, image, upscale, seed, color_alignment, tile_size, tile_overlap, vae_tile_size, vae_tile_overlap) -> io.NodeOutput:
|
||||
result = run_vosr2(
|
||||
model, image, upscale, seed, color_alignment,
|
||||
tile_size, tile_overlap, vae_tile_size, vae_tile_overlap,
|
||||
)
|
||||
return io.NodeOutput(result)
|
||||
|
||||
|
||||
class VOSR2Extension(ComfyExtension):
|
||||
@override
|
||||
async def get_node_list(self) -> list[type[io.ComfyNode]]:
|
||||
return [
|
||||
VOSR2ModelLoader,
|
||||
VOSR2Upscale,
|
||||
]
|
||||
|
||||
|
||||
async def comfy_entrypoint() -> VOSR2Extension:
|
||||
return VOSR2Extension()
|
||||
@@ -0,0 +1,145 @@
|
||||
"""Gaussian-blended tiled VAE encode/decode for the Qwen-Image 2D VAE.
|
||||
|
||||
Ported from VOSR's tiled_vae.py. Full-image VAE encode/decode of large inputs can
|
||||
OOM (the Qwen VAE runs in fp32 internally); this bounds peak memory to one tile's
|
||||
activations. Encoding uses `latent_dist.mode()` (deterministic) rather than
|
||||
`.sample()`, since sampling draws uncorrelated noise per tile and would create
|
||||
seams at tile boundaries.
|
||||
|
||||
Why plain Gaussian blending is sufficient here (unlike SD/LDM's pad+crop `VAEHook`
|
||||
machinery): the Qwen VAE uses RMSNorm2D, a purely per-pixel/per-channel norm with
|
||||
no cross-tile statistics to reconcile (no GroupNorm), so each tile's forward pass
|
||||
is independent and a weighted blend of overlapping outputs is well-founded.
|
||||
"""
|
||||
import math
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
AE_FACTOR = 8 # Qwen VAE spatial compression ratio
|
||||
|
||||
|
||||
def _gaussian_weights(tile_h: int, tile_w: int, channels: int, device) -> torch.Tensor:
|
||||
"""2-D Gaussian blend mask (1, C, tile_h, tile_w) peaked at the centre."""
|
||||
var = 0.01
|
||||
mid_h, mid_w = (tile_h - 1) / 2, (tile_w - 1) / 2
|
||||
y = torch.arange(tile_h, dtype=torch.float32)
|
||||
x = torch.arange(tile_w, dtype=torch.float32)
|
||||
wy = torch.exp(-((y - mid_h) / tile_h) ** 2 / (2 * var))
|
||||
wx = torch.exp(-((x - mid_w) / tile_w) ** 2 / (2 * var))
|
||||
w = wy[:, None] * wx[None, :]
|
||||
return w.to(device).unsqueeze(0).unsqueeze(0).expand(1, channels, -1, -1)
|
||||
|
||||
|
||||
def _make_tile_grid(length: int, tile: int, overlap: int) -> list:
|
||||
"""Sorted, deduplicated starting positions that cover `length`."""
|
||||
stride = max(tile - overlap, 1)
|
||||
if length <= tile:
|
||||
return [0]
|
||||
positions = list(range(0, length - tile + 1, stride))
|
||||
if positions[-1] + tile < length:
|
||||
positions.append(length - tile)
|
||||
return sorted(set(positions))
|
||||
|
||||
|
||||
def _pad_to_multiple(x: torch.Tensor, multiple: int = 8):
|
||||
_, _, h, w = x.shape
|
||||
pad_h = (multiple - h % multiple) % multiple
|
||||
pad_w = (multiple - w % multiple) % multiple
|
||||
if pad_h == 0 and pad_w == 0:
|
||||
return x, h, w
|
||||
return F.pad(x, (0, pad_w, 0, pad_h), mode="reflect"), h, w
|
||||
|
||||
|
||||
def encode_latent(vae, x: torch.Tensor):
|
||||
"""Single-shot deterministic VAE encode -> normalized latent. Returns (latent, mean, std)."""
|
||||
device = x.device
|
||||
latents_mean = torch.tensor(vae.latents_mean, device=device).view(1, -1, 1, 1)
|
||||
latents_std = 1.0 / torch.tensor(vae.latents_std, device=device).view(1, -1, 1, 1)
|
||||
z = vae.encode(x).latent_dist.mode()
|
||||
return (z - latents_mean) * latents_std, latents_mean, latents_std
|
||||
|
||||
|
||||
def decode_latent(vae, sr_latent: torch.Tensor, latents_mean: torch.Tensor, latents_std: torch.Tensor) -> torch.Tensor:
|
||||
"""Single-shot VAE decode -> pixels in [-1, 1]."""
|
||||
sr_latent = sr_latent / latents_std + latents_mean
|
||||
return vae.decode(sr_latent).sample.clamp(-1, 1)
|
||||
|
||||
|
||||
def _tile_params(tile_size: int, tile_overlap: int, lh: int, lw: int):
|
||||
lt_size = max(tile_size // AE_FACTOR, 1)
|
||||
lt_overlap = max(tile_overlap // AE_FACTOR, lt_size // 8)
|
||||
lt_size = min(lt_size, min(lh, lw))
|
||||
lt_overlap = min(lt_overlap, lt_size - 1)
|
||||
return lt_size, lt_overlap
|
||||
|
||||
|
||||
def tiled_encode_latent(vae, x: torch.Tensor, tile_size: int, tile_overlap: int):
|
||||
"""Output latent shape equals the untiled path: ceil(h/8) x ceil(w/8)."""
|
||||
pad, orig_h, orig_w = _pad_to_multiple(x, 8)
|
||||
lh, lw = pad.shape[2] // 8, pad.shape[3] // 8
|
||||
lt_size, lt_overlap = _tile_params(tile_size, tile_overlap, lh, lw)
|
||||
|
||||
if lh <= lt_size and lw <= lt_size:
|
||||
return encode_latent(vae, pad)
|
||||
|
||||
h_pos = _make_tile_grid(lh, lt_size, lt_overlap)
|
||||
w_pos = _make_tile_grid(lw, lt_size, lt_overlap)
|
||||
|
||||
b = pad.shape[0]
|
||||
acc = wacc = g = None
|
||||
mean = std = None
|
||||
for hi in h_pos:
|
||||
for wi in w_pos:
|
||||
crop = pad[:, :, hi * 8:(hi + lt_size) * 8, wi * 8:(wi + lt_size) * 8]
|
||||
z_tile, mean, std = encode_latent(vae, crop)
|
||||
if acc is None:
|
||||
lc = z_tile.shape[1]
|
||||
g = _gaussian_weights(lt_size, lt_size, lc, x.device)
|
||||
acc = torch.zeros(b, lc, lh, lw, device=x.device, dtype=z_tile.dtype)
|
||||
wacc = torch.zeros_like(acc)
|
||||
acc[:, :, hi:hi + lt_size, wi:wi + lt_size] += z_tile * g
|
||||
wacc[:, :, hi:hi + lt_size, wi:wi + lt_size] += g
|
||||
|
||||
blended = acc / wacc
|
||||
out_lh, out_lw = math.ceil(orig_h / 8), math.ceil(orig_w / 8)
|
||||
return blended[:, :, :out_lh, :out_lw], mean, std
|
||||
|
||||
|
||||
def tiled_decode_latent(vae, sr_latent: torch.Tensor, latents_mean, latents_std, tile_size: int, tile_overlap: int) -> torch.Tensor:
|
||||
"""Decodes in pixel space (3ch): each latent tile maps to an exactly-8x pixel tile."""
|
||||
b, _, lh, lw = sr_latent.shape
|
||||
lt_size, lt_overlap = _tile_params(tile_size, tile_overlap, lh, lw)
|
||||
|
||||
if lh <= lt_size and lw <= lt_size:
|
||||
return decode_latent(vae, sr_latent, latents_mean, latents_std)
|
||||
|
||||
h_pos = _make_tile_grid(lh, lt_size, lt_overlap)
|
||||
w_pos = _make_tile_grid(lw, lt_size, lt_overlap)
|
||||
|
||||
out_h, out_w = lh * 8, lw * 8
|
||||
g = _gaussian_weights(lt_size * 8, lt_size * 8, 3, sr_latent.device)
|
||||
acc = torch.zeros(b, 3, out_h, out_w, device=sr_latent.device, dtype=sr_latent.dtype)
|
||||
wacc = torch.zeros_like(acc)
|
||||
for hi in h_pos:
|
||||
for wi in w_pos:
|
||||
he, we = hi + lt_size, wi + lt_size
|
||||
pix = decode_latent(vae, sr_latent[:, :, hi:he, wi:we], latents_mean, latents_std)
|
||||
acc[:, :, hi * 8:he * 8, wi * 8:we * 8] += pix * g
|
||||
wacc[:, :, hi * 8:he * 8, wi * 8:we * 8] += g
|
||||
|
||||
return (acc / wacc).clamp(-1, 1)
|
||||
|
||||
|
||||
def encode_dispatch(vae, x: torch.Tensor, vae_tile_size: int, vae_tile_overlap: int):
|
||||
"""encode_latent, tiled when vae_tile_size > 0."""
|
||||
if vae_tile_size and vae_tile_size > 0:
|
||||
return tiled_encode_latent(vae, x, vae_tile_size, vae_tile_overlap)
|
||||
return encode_latent(vae, x)
|
||||
|
||||
|
||||
def decode_dispatch(vae, sr_latent: torch.Tensor, latents_mean, latents_std, vae_tile_size: int, vae_tile_overlap: int) -> torch.Tensor:
|
||||
"""decode_latent, tiled when vae_tile_size > 0."""
|
||||
if vae_tile_size and vae_tile_size > 0:
|
||||
return tiled_decode_latent(vae, sr_latent, latents_mean, latents_std, vae_tile_size, vae_tile_overlap)
|
||||
return decode_latent(vae, sr_latent, latents_mean, latents_std)
|
||||
Reference in New Issue
Block a user