Add custom nodes, Civitai loras (LFS), and vast.ai setup script
Some checks failed
Python Linting / Run Ruff (push) Has been cancelled
Python Linting / Run Pylint (push) Has been cancelled
Full Comfy CI Workflow Runs / test-stable (12.1, , linux, 3.10, [self-hosted Linux], stable) (push) Has been cancelled
Full Comfy CI Workflow Runs / test-stable (12.1, , linux, 3.11, [self-hosted Linux], stable) (push) Has been cancelled
Full Comfy CI Workflow Runs / test-stable (12.1, , linux, 3.12, [self-hosted Linux], stable) (push) Has been cancelled
Full Comfy CI Workflow Runs / test-unix-nightly (12.1, , linux, 3.11, [self-hosted Linux], nightly) (push) Has been cancelled
Execution Tests / test (macos-latest) (push) Has been cancelled
Execution Tests / test (ubuntu-latest) (push) Has been cancelled
Execution Tests / test (windows-latest) (push) Has been cancelled
Test server launches without errors / test (push) Has been cancelled
Unit Tests / test (macos-latest) (push) Has been cancelled
Unit Tests / test (ubuntu-latest) (push) Has been cancelled
Unit Tests / test (windows-2022) (push) Has been cancelled
Some checks failed
Python Linting / Run Ruff (push) Has been cancelled
Python Linting / Run Pylint (push) Has been cancelled
Full Comfy CI Workflow Runs / test-stable (12.1, , linux, 3.10, [self-hosted Linux], stable) (push) Has been cancelled
Full Comfy CI Workflow Runs / test-stable (12.1, , linux, 3.11, [self-hosted Linux], stable) (push) Has been cancelled
Full Comfy CI Workflow Runs / test-stable (12.1, , linux, 3.12, [self-hosted Linux], stable) (push) Has been cancelled
Full Comfy CI Workflow Runs / test-unix-nightly (12.1, , linux, 3.11, [self-hosted Linux], nightly) (push) Has been cancelled
Execution Tests / test (macos-latest) (push) Has been cancelled
Execution Tests / test (ubuntu-latest) (push) Has been cancelled
Execution Tests / test (windows-latest) (push) Has been cancelled
Test server launches without errors / test (push) Has been cancelled
Unit Tests / test (macos-latest) (push) Has been cancelled
Unit Tests / test (ubuntu-latest) (push) Has been cancelled
Unit Tests / test (windows-2022) (push) Has been cancelled
Includes 30 custom nodes committed directly, 7 Civitai-exclusive loras stored via Git LFS, and a setup script that installs all dependencies and downloads HuggingFace-hosted models on vast.ai. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
36
custom_nodes/whiterabbit/.gitignore
vendored
Normal file
36
custom_nodes/whiterabbit/.gitignore
vendored
Normal file
@@ -0,0 +1,36 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
vendor/ckpts/
|
||||
*.pth
|
||||
|
||||
# Virtual envs
|
||||
.venv/
|
||||
venv/
|
||||
env/
|
||||
ENV/
|
||||
.conda/
|
||||
|
||||
# Tool caches
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
.pyre/
|
||||
.pytype/
|
||||
.tox/
|
||||
.nox/
|
||||
.cache/
|
||||
|
||||
# Logs / temp
|
||||
*.log
|
||||
logs/
|
||||
tmp/
|
||||
temp/
|
||||
*.tmp
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.iml
|
||||
661
custom_nodes/whiterabbit/LICENSE
Normal file
661
custom_nodes/whiterabbit/LICENSE
Normal file
@@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are 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.
|
||||
|
||||
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.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
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 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 work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
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 AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2023 Fannovel16
|
||||
|
||||
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.
|
||||
118
custom_nodes/whiterabbit/README_zh-CN.md
Normal file
118
custom_nodes/whiterabbit/README_zh-CN.md
Normal file
@@ -0,0 +1,118 @@
|
||||
# WhiteRabbit:掌控时间之流 🐇
|
||||
[English](readme.md) | **简体中文**
|
||||
|
||||
这是 **comfyui-WhiteRabbit**,一个专为在 ComfyUI 中处理视频而设计的节点包。
|
||||
|
||||
兔子的拿手好戏是穿梭时间,帮你做出无缝循环视频。但她带来的可不止这些——高质量的任意帧率重采样和超快的图像缩放也都在这份“茶会”礼盒里!
|
||||
|
||||
虽然这些节点中有些当然也能用于单张图片,但它们无一不是以高效的**批处理**为核心设计。这意味着性能收益会层层叠加,让你在硬件允许的范围内尽可能快地处理整段视频。
|
||||
|
||||
|
||||
## 安装
|
||||
|
||||
WhiteRabbit 支持两种布局:
|
||||
|
||||
1) **外部基础包(存在时优先)**:`custom_nodes/comfyui-frame-interpolation/`
|
||||
2) **内置的应急副本(随本项目打包)**:`vendor/`
|
||||
|
||||
**快速安装:**
|
||||
1. 将 **comfyui-WhiteRabbit** 文件夹放入 `ComfyUI/custom_nodes/`。
|
||||
2. 安装本节点所需的依赖:
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
**可选项:** 你可以在 `custom_nodes/` 目录中安装 [ComfyUI-Frame-Interpolation](https://github.com/Fannovel16/ComfyUI-Frame-Interpolation)。WhiteRabbit 会自动检测到它并复用其中的资源。如果你已经在用它,这尤其方便,因为无需同时保存两份 RIFE 模型。
|
||||
|
||||
### Python 依赖
|
||||
|
||||
本节点依赖于 ComfyUI 已提供的核心包(如 `torch`、`torchvision`、`numpy`、`einops`、`pyyaml`)。你的**节点本地** `requirements.txt` 仅需新增:
|
||||
|
||||
```
|
||||
packaging
|
||||
torchlanc
|
||||
```
|
||||
|
||||
## 节点一览
|
||||
|
||||
这个节点包帮你解决视频创作中一些最棘手的问题。
|
||||
|
||||
### 时间扭曲者(Time Benders)
|
||||
|
||||
这些节点通过 **RIFE** 插帧模型在时间上增删帧。为了获得一点点额外速度,它们被优化为协同工作,在多 RIFE 工作流中缓存 RIFE 模型,以获得小幅效率提升。
|
||||
|
||||
- **RIFE VFI Interpolate by Multiple**:帧插值的基础工具。将帧数乘以 2x、4x 等,它会生成让你的视频丝滑流畅的新帧。
|
||||
- **RIFE VFI FPS Resample**:时间旅行大师。把视频转换为指定目标帧率,自动处理补帧与丢帧。内置多种防止常见伪影(如闪烁)的措施,输出更干净。
|
||||
- **RIFE VFI Custom Timing**:需要完全掌控?以“外科级精度”放置每一帧。通过提供自定义时序列表来制作速度坡道,或只在特定时刻进行平滑处理。
|
||||
- **RIFE Seam Timing Analyzer**:自定义时序节点的完美搭档。自动计算无缝循环的精确时序,给出你需要的 CSV 数值,让过渡天衣无缝。
|
||||
|
||||

|
||||
> 示例:**RIFE VFI FPS Resample** 节点是“时间大师”,可将你的视频重采样到新的帧率。自己试试吧——附带工作流!
|
||||
|
||||
### 循环大师(Loop Masters)
|
||||
|
||||
做出一个无缝循环的视频常像解谜。这些节点把开启完美、连续循环的钥匙交给你。
|
||||
|
||||
- **Prepare Loop Frames**:第一步。该节点会处理整段视频以准备循环“接缝”,将最后一帧与第一帧单独打成一个批。这一小对帧就是你的插帧器开始过渡所需的一切。
|
||||
- **Assemble Loop Frames**:最后一块拼图。插帧器施展魔法后,该节点会把新的接缝帧追加到原视频的末尾,组装出完整、连续的循环。
|
||||
- **Autocrop to Loop**:别在帧的森林里迷路!这个聪明的节点会智能分析视频,从末尾找到最佳裁剪点,确保循环尽可能顺畅。
|
||||
- **Trim Batch Ends**:一个用于从片段开头或结尾裁掉固定数量帧的简洁工具,适合去掉不需要的开场/收尾。
|
||||
- **Roll Frames**:循环地改变一批图像的顺序。在循环场景中,这会改变你的循环从第几帧开始。
|
||||
- **Unroll Frames**:撤销上面节点的操作;你可能会为了某个过程(如插帧)先滚动帧,再恢复原顺序。该节点支持设置帧乘数,以与之前的 **RIFE VFI Interpolate by Multiple** 保持同步。
|
||||
|
||||

|
||||
> 示例:用 **Prepare Loop Frames** → **RIFE Seam Timing Analyzer** → **RIFE VFI Custom Timing** → **Assemble Loop Frames** 缝合无缝循环。把这张 png 丢进 ComfyUI 亲自试驾!
|
||||
|
||||

|
||||
> 示例:最好的循环就是你已经拥有的那个。**Autocrop to Loop** 通过分析片段尾部帧之间的视觉差异与时序,帮你找到最佳结束帧。
|
||||
|
||||
### 后期处理(Post-Processing)
|
||||
|
||||
这些节点是得力助手!
|
||||
|
||||
- **Batch Resize w/ Lanczos**:快速、正统、品质不妥协。这个 CUDA 加速的节点使用为 PyTorch 编写的高质量 Lanczos 算法 [TorchLanc](https://github.com/Artificial-Sweetener/TorchLanc) 来批量缩放图像(当然也支持单张)。它相比 CPU 方案(如 Pillow 自带的 Lanczos)速度显著更快,最高可达约 *10×* 提升。
|
||||
- **Upscale w/ Model (Advanced)**:ComfyUI 自带 “Upscale Image (Using Model)” 的进阶版本,直接暴露批大小与切片等参数。如果根据你的机器进行调优,放大速度能显著提升。
|
||||
- **Pixel Hold**:通过抑制由视频扩散或压缩造成的小幅波动,减少视频闪烁并清理画面中的静态区域。也可将输入图像作为基准,具备一定的创作潜力。
|
||||
- **Watermark**:支持单图与批量。非常快速,尤其是与专业编辑工具中做同类操作相比。
|
||||
|
||||

|
||||
> 示例:使用 **Batch Resize w/ Lanczos** 快速缩放图像。已附工作流!
|
||||
|
||||

|
||||
> 示例:将 **Upscale w/ Model (Advanced)** 与 **Batch Resize w/ Lanczos** 配合使用,达到特定目标尺寸。图中已附带工作流。
|
||||
|
||||

|
||||
> 示例:用灵活的配置选项为每一帧快速添加水印。已附工作流。
|
||||
|
||||
## 许可与致谢
|
||||
- **项目许可:** GNU Affero General Public License v3.0(**AGPL-3.0**)。请阅读本仓库内完整的 [LICENSE](LICENSE)!AGPL-3.0 是强 Copyleft 许可。如果你分发本软件,你必须提供其对应的源代码;如果你让用户通过网络与修改过的版本交互,你也必须向他们提供该修改版本的对应源代码。
|
||||
|
||||
- **依赖许可(MIT):** 为了可靠性,本项目**内置(vendor)**了 **[ComfyUI-Frame-Interpolation](https://github.com/Fannovel16/ComfyUI-Frame-Interpolation)** 的极少量组件。这些文件遵循 MIT 许可,由 **[Fannovel16](https://github.com/Fannovel16)** 与其**[贡献者](https://github.com/Fannovel16/ComfyUI-Frame-Interpolation/graphs/contributors)** 授权;参见 `LICENSES/MIT-ComfyUI-Frame-Interpolation.txt`:
|
||||
- `vendor/vfi_utils.py`
|
||||
- `vendor/rife/__init__.py`
|
||||
- `vendor/rife/rife_arch.py`
|
||||
- 另外,本项目也在 [`interpolation.py`](interpolation.py) 中借鉴并改编了 **[ComfyUI-Frame-Interpolation](https://github.com/Fannovel16/ComfyUI-Frame-Interpolation)** 的少量内容。
|
||||
- **Batch Resize w/ Lanczos** 的 UI 设计受到了 [Kijai](https://github.com/kijai/) 优秀项目 [KJNodes](thub.com/kijai/ComfyUI-KJNodes) 中相似节点的启发。
|
||||
|
||||
### 研究引用
|
||||
|
||||
本节点包在视频帧插值上使用 **RIFE(IFNet)**。你可以在[这里](https://ar5iv.labs.arxiv.org/html/2011.06294)阅读论文。
|
||||
|
||||
```bibtex
|
||||
@inproceedings{huang2022rife,
|
||||
title={Real-Time Intermediate Flow Estimation for Video Frame Interpolation},
|
||||
author={Huang, Zhewei and Zhang, Tianyuan and Heng, Wen and Shi, Boxin and Zhou, Shuchang},
|
||||
booktitle={European Conference on Computer Vision (ECCV)},
|
||||
year={2022}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 来自开发者 ❤️
|
||||
|
||||
希望你使用这些节点时的快乐,不亚于我把它们拼到一起时!
|
||||
|
||||
- **请我喝杯咖啡**:你可以在我的 [Ko-fi 页面](https://ko-fi.com/artificial_sweetener) 支持更多类似项目。
|
||||
- **我的网站与社媒**:欢迎在 [artificialsweetener.ai](https://artificialsweetener.ai) 查看我的艺术作品、诗歌与开发动态。
|
||||
- **如果你喜欢这个项目**,在 GitHub 上点一颗 Star 会让我非常开心!! ⭐
|
||||
56
custom_nodes/whiterabbit/__init__.py
Normal file
56
custom_nodes/whiterabbit/__init__.py
Normal file
@@ -0,0 +1,56 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# SPDX-FileCopyrightText: 2025 ArtificialSweetener <artificialsweetenerai@proton.me>
|
||||
|
||||
from .interpolation import (
|
||||
RIFE_FPS_Resample,
|
||||
RIFE_SeamTimingAnalyzer,
|
||||
RIFE_VFI_Advanced,
|
||||
RIFE_VFI_Opt,
|
||||
)
|
||||
from .noise_control import PixelHold
|
||||
from .post_process import BatchWatermarkSingle
|
||||
from .scaling import BatchResizeWithLanczos, UpscaleWithModelAdvanced
|
||||
from .video_loop import (
|
||||
AssembleLoopFrames,
|
||||
AutocropToLoop,
|
||||
PrepareLoopFrames,
|
||||
RollFrames,
|
||||
TrimBatchEnds,
|
||||
UnrollFrames,
|
||||
)
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"PrepareLoopFrames": PrepareLoopFrames,
|
||||
"AssembleLoopFrames": AssembleLoopFrames,
|
||||
"RollFrames": RollFrames,
|
||||
"UnrollFrames": UnrollFrames,
|
||||
"AutocropToLoop": AutocropToLoop,
|
||||
"TrimBatchEnds": TrimBatchEnds,
|
||||
"RIFE_VFI_Opt": RIFE_VFI_Opt,
|
||||
"RIFE_VFI_Advanced": RIFE_VFI_Advanced,
|
||||
"RIFE_SeamTimingAnalyzer": RIFE_SeamTimingAnalyzer,
|
||||
"RIFE_FPS_Resample": RIFE_FPS_Resample,
|
||||
"PixelHold": PixelHold,
|
||||
"UpscaleWithModelAdvanced": UpscaleWithModelAdvanced,
|
||||
"BatchResizeWithLanczos": BatchResizeWithLanczos,
|
||||
"BatchWatermarkSingle": BatchWatermarkSingle,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"PrepareLoopFrames": "🐇 Prepare Loop Frames",
|
||||
"AssembleLoopFrames": "🐇 Assemble Loop Frames",
|
||||
"RollFrames": "🐇 Roll Frames",
|
||||
"UnrollFrames": "🐇 Unroll Frames",
|
||||
"AutocropToLoop": "🐇 Autocrop to Loop",
|
||||
"TrimBatchEnds": "🐇 Trim Batch Ends",
|
||||
"RIFE_VFI_Opt": "🐇 RIFE VFI Interpolate by Multiple",
|
||||
"RIFE_VFI_Advanced": "🐇 RIFE VFI Custom Timing",
|
||||
"RIFE_SeamTimingAnalyzer": "🐇 RIFE Seam Timing Analyzer",
|
||||
"RIFE_FPS_Resample": "🐇 RIFE VFI FPS Resample",
|
||||
"PixelHold": "🐇 Pixel Hold",
|
||||
"UpscaleWithModelAdvanced": "🐇 Upscale w/ Model (Advanced)",
|
||||
"BatchResizeWithLanczos": "🐇 Batch Resize w/ Lanczos",
|
||||
"BatchWatermarkSingle": "🐇 Watermark",
|
||||
}
|
||||
|
||||
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
|
||||
BIN
custom_nodes/whiterabbit/examples/autocrop_to_loop.png
Normal file
BIN
custom_nodes/whiterabbit/examples/autocrop_to_loop.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.9 MiB |
BIN
custom_nodes/whiterabbit/examples/interpolate_loop_seam.png
Normal file
BIN
custom_nodes/whiterabbit/examples/interpolate_loop_seam.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1016 KiB |
BIN
custom_nodes/whiterabbit/examples/resample_framerate.png
Normal file
BIN
custom_nodes/whiterabbit/examples/resample_framerate.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.1 MiB |
BIN
custom_nodes/whiterabbit/examples/resize.png
Normal file
BIN
custom_nodes/whiterabbit/examples/resize.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.4 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.8 MiB |
BIN
custom_nodes/whiterabbit/examples/watermark.png
Normal file
BIN
custom_nodes/whiterabbit/examples/watermark.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.3 MiB |
1168
custom_nodes/whiterabbit/interpolation.py
Normal file
1168
custom_nodes/whiterabbit/interpolation.py
Normal file
File diff suppressed because it is too large
Load Diff
751
custom_nodes/whiterabbit/noise_control.py
Normal file
751
custom_nodes/whiterabbit/noise_control.py
Normal file
@@ -0,0 +1,751 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# SPDX-FileCopyrightText: 2025 ArtificialSweetener <artificialsweetenerai@proton.me>
|
||||
import math
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def _to_lin(x):
|
||||
return torch.where(
|
||||
x <= 0.04045, x / 12.92, ((x + 0.055) / 1.055).clamp(min=0) ** 2.4
|
||||
)
|
||||
|
||||
|
||||
def _to_srgb(x):
|
||||
return torch.where(
|
||||
x <= 0.0031308, 12.92 * x, 1.055 * x.clamp(min=0) ** (1 / 2.4) - 0.055
|
||||
)
|
||||
|
||||
|
||||
def _luma(x):
|
||||
return 0.2126 * x[..., 0:1] + 0.7152 * x[..., 1:2] + 0.0722 * x[..., 2:3]
|
||||
|
||||
|
||||
def _sobel_mag(y): # y: NHWC 1ch
|
||||
kx = (
|
||||
torch.tensor([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=torch.float32)
|
||||
.view(1, 1, 3, 3)
|
||||
.to(y.device)
|
||||
)
|
||||
ky = (
|
||||
torch.tensor([[-1, -2, -1], [0, 0, 0], [1, 2, 1]], dtype=torch.float32)
|
||||
.view(1, 1, 3, 3)
|
||||
.to(y.device)
|
||||
)
|
||||
t = F.pad(y.permute(0, 3, 1, 2), (1, 1, 1, 1), mode="reflect")
|
||||
gx = F.conv2d(t, kx)
|
||||
gy = F.conv2d(t, ky)
|
||||
return torch.sqrt(gx * gx + gy * gy).permute(0, 2, 3, 1).contiguous()
|
||||
|
||||
|
||||
def _gauss1d(sigma, r):
|
||||
if r <= 0:
|
||||
return torch.tensor([1.0], dtype=torch.float32)
|
||||
xs = torch.arange(-r, r + 1, dtype=torch.float32)
|
||||
k = torch.exp(-(xs * xs) / (2 * sigma * sigma))
|
||||
return (k / k.sum()).contiguous()
|
||||
|
||||
|
||||
def _blur_nhwc(x, sigma):
|
||||
if sigma <= 0:
|
||||
return x
|
||||
N, H, W, C = x.shape
|
||||
max_r = max(0, min(H, W) // 2 - 1)
|
||||
r = min(int(math.ceil(3.0 * sigma)), max_r)
|
||||
if r <= 0:
|
||||
return x
|
||||
k = _gauss1d(sigma, r)
|
||||
kH = k.view(1, 1, -1, 1).repeat(C, 1, 1, 1)
|
||||
kW = k.view(1, 1, 1, -1).repeat(C, 1, 1, 1)
|
||||
t = x.permute(0, 3, 1, 2).contiguous()
|
||||
t = F.conv2d(F.pad(t, (0, 0, r, r), mode="reflect"), kH, groups=C)
|
||||
t = F.conv2d(F.pad(t, (r, r, 0, 0), mode="reflect"), kW, groups=C)
|
||||
return t.permute(0, 2, 3, 1).contiguous()
|
||||
|
||||
|
||||
def _avgpool_tiles(x1, tile):
|
||||
t = x1.permute(0, 3, 1, 2)
|
||||
o = F.avg_pool2d(t, kernel_size=tile, stride=tile)
|
||||
return o.permute(0, 2, 3, 1)
|
||||
|
||||
|
||||
def _mad_tiles(x1, tile):
|
||||
t = x1.permute(0, 3, 1, 2)
|
||||
N, C, H, W = t.shape
|
||||
th, tw = H // tile, W // tile
|
||||
t = t[:, :, : th * tile, : tw * tile]
|
||||
patches = F.unfold(t, kernel_size=tile, stride=tile) # (N, C*tile*tile, th*tw)
|
||||
patches = patches.transpose(1, 2).reshape(-1, tile * tile) # (N*th*tw, K)
|
||||
med = patches.median(dim=1, keepdim=True).values
|
||||
mad = (patches - med).abs().median(dim=1).values.view(N, th, tw, 1)
|
||||
return mad
|
||||
|
||||
|
||||
def _upsample_mask(mask_tile, H, W, mode="nearest"):
|
||||
t = mask_tile.permute(0, 3, 1, 2)
|
||||
t = F.interpolate(
|
||||
t,
|
||||
size=(H, W),
|
||||
mode=("bilinear" if mode == "bilinear" else "nearest"),
|
||||
align_corners=False if mode == "bilinear" else None,
|
||||
)
|
||||
return t.permute(0, 2, 3, 1)
|
||||
|
||||
|
||||
def _dilate(mask01, r):
|
||||
if r <= 0:
|
||||
return mask01
|
||||
t = mask01.permute(0, 3, 1, 2)
|
||||
t = F.pad(t, (r, r, r, r), mode="replicate")
|
||||
t = F.max_pool2d(t, kernel_size=2 * r + 1, stride=1)
|
||||
return t.permute(0, 2, 3, 1)
|
||||
|
||||
|
||||
def _resize_lanczos(img01, H, W): # (1,Hr,Wr,C) float CPU -> (1,H,W,C) float CPU
|
||||
arr = (img01[0].cpu().numpy() * 255.0).clip(0, 255).astype(np.uint8)
|
||||
pil = Image.fromarray(arr, mode="RGB").resize((W, H), resample=Image.LANCZOS)
|
||||
out = np.asarray(pil).astype(np.float32) / 255.0
|
||||
return torch.from_numpy(out).unsqueeze(0)
|
||||
|
||||
|
||||
class PixelHold:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"frames": (
|
||||
"IMAGE",
|
||||
{"tooltip": "Your clip (frames×H×W×C, values 0–1)."},
|
||||
),
|
||||
"ref_source": (
|
||||
["external", "batch_index"],
|
||||
{
|
||||
"default": "external",
|
||||
"tooltip": "Pick the reference: an external image or a frame from this clip.",
|
||||
},
|
||||
),
|
||||
"ref_index": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 999999,
|
||||
"tooltip": "If using a frame from this clip, which frame to use as the reference.",
|
||||
},
|
||||
),
|
||||
"reference": (
|
||||
"IMAGE",
|
||||
{
|
||||
"default": None,
|
||||
"tooltip": "Optional external reference (1×H×W×C). If sizes differ, it will be resized to match.",
|
||||
},
|
||||
),
|
||||
"linearize": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"tooltip": "Work in linear color for steadier results on flat areas.",
|
||||
},
|
||||
),
|
||||
"auto_luma": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"tooltip": "Auto sensitivity for brightness changes (adapts per frame).",
|
||||
},
|
||||
),
|
||||
"auto_k": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 2.5,
|
||||
"min": 0.5,
|
||||
"max": 6.0,
|
||||
"step": 0.1,
|
||||
"tooltip": "Auto strength. Higher = lock more to the reference (2–3 is typical).",
|
||||
},
|
||||
),
|
||||
"tau_luma": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 1.5 / 255.0,
|
||||
"min": 0.0,
|
||||
"max": 4.0 / 255.0,
|
||||
"step": 0.0005,
|
||||
"tooltip": "Manual brightness threshold when Auto is OFF. Lower = stricter (more locking).",
|
||||
},
|
||||
),
|
||||
"tau_grad": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.02,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.001,
|
||||
"tooltip": "How much edge change to allow. Lower protects edges more.",
|
||||
},
|
||||
),
|
||||
"mode": (
|
||||
["tile", "pixel"],
|
||||
{
|
||||
"default": "tile",
|
||||
"tooltip": "Tile: fast & robust. Pixel: finer but noisier.",
|
||||
},
|
||||
),
|
||||
"tile_size": (
|
||||
"INT",
|
||||
{
|
||||
"default": 32,
|
||||
"min": 8,
|
||||
"max": 256,
|
||||
"step": 8,
|
||||
"tooltip": "Tile size when using Tile mode.",
|
||||
},
|
||||
),
|
||||
"score_mode": (
|
||||
["l1_tile", "mad_tile"],
|
||||
{
|
||||
"default": "l1_tile",
|
||||
"tooltip": "How tiles measure change: mean abs diff (fast) or median abs dev (robust).",
|
||||
},
|
||||
),
|
||||
"edge_band": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"tooltip": "Protect a belt around strong edges to avoid wobble/stretch.",
|
||||
},
|
||||
),
|
||||
"band_radius": (
|
||||
"INT",
|
||||
{
|
||||
"default": 4,
|
||||
"min": 0,
|
||||
"max": 64,
|
||||
"tooltip": "Width of the protected belt (pixels).",
|
||||
},
|
||||
),
|
||||
"tau_edge_low": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 1.5 / 255.0,
|
||||
"min": 0.0,
|
||||
"max": 0.25,
|
||||
"step": 0.0005,
|
||||
"tooltip": "Treat as low-motion below this level (edge belt).",
|
||||
},
|
||||
),
|
||||
"tau_edge_high": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 6.0 / 255.0,
|
||||
"min": 0.0,
|
||||
"max": 0.5,
|
||||
"step": 0.0005,
|
||||
"tooltip": "Treat as high-motion above this level (edge belt).",
|
||||
},
|
||||
),
|
||||
"apply": (
|
||||
["all", "lowfreq"],
|
||||
{
|
||||
"default": "all",
|
||||
"tooltip": "Hold the whole image (All) or only its smooth part (Low-freq).",
|
||||
},
|
||||
),
|
||||
"dilate": (
|
||||
"INT",
|
||||
{
|
||||
"default": 1,
|
||||
"min": 0,
|
||||
"max": 16,
|
||||
"tooltip": "Expand the mask (pixels).",
|
||||
},
|
||||
),
|
||||
"feather_sigma": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 2.0,
|
||||
"min": 0.0,
|
||||
"max": 16.0,
|
||||
"step": 0.5,
|
||||
"tooltip": "Soften mask edges (pixels).",
|
||||
},
|
||||
),
|
||||
"process_on": (
|
||||
["auto", "cpu", "gpu"],
|
||||
{
|
||||
"default": "auto",
|
||||
"tooltip": "Choose CPU/GPU. Auto switches to GPU on very large frames.",
|
||||
},
|
||||
),
|
||||
"gpu_clear_every": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 1000,
|
||||
"tooltip": "If >0 and using GPU, free memory every N frames.",
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "IMAGE")
|
||||
RETURN_NAMES = ("images", "mask_preview")
|
||||
FUNCTION = "apply_hold"
|
||||
CATEGORY = "video utils"
|
||||
DESCRIPTION = (
|
||||
"Locks parts of each frame to a chosen reference (external image or a frame from the clip) whenever changes are small—"
|
||||
"useful for stabilizing flat areas or backgrounds while leaving motion to pass through."
|
||||
)
|
||||
|
||||
@torch.no_grad()
|
||||
def apply_hold(
|
||||
self,
|
||||
frames,
|
||||
ref_source="external",
|
||||
ref_index=0,
|
||||
reference=None,
|
||||
linearize=True,
|
||||
auto_luma=True,
|
||||
auto_k=2.5,
|
||||
tau_luma=1.5 / 255.0,
|
||||
tau_grad=0.02,
|
||||
mode="tile",
|
||||
tile_size=32,
|
||||
score_mode="l1_tile",
|
||||
edge_band=True,
|
||||
band_radius=4,
|
||||
tau_edge_low=1.5 / 255.0,
|
||||
tau_edge_high=6.0 / 255.0,
|
||||
apply="all",
|
||||
dilate=1,
|
||||
feather_sigma=2.0,
|
||||
process_on="auto",
|
||||
gpu_clear_every=0,
|
||||
):
|
||||
x = frames if isinstance(frames, torch.Tensor) else torch.tensor(frames)
|
||||
B, H, W, C = x.shape
|
||||
|
||||
if str(ref_source) == "external" and reference is not None:
|
||||
ref = (
|
||||
reference
|
||||
if isinstance(reference, torch.Tensor)
|
||||
else torch.tensor(reference)
|
||||
)
|
||||
if ref.shape[1] != H or ref.shape[2] != W:
|
||||
ref = _resize_lanczos(ref[:1].to("cpu"), H, W)
|
||||
ref = ref[:1].repeat(B, 1, 1, 1)
|
||||
else:
|
||||
idx = max(0, min(int(ref_index), B - 1))
|
||||
ref = x[idx : idx + 1].repeat(B, 1, 1, 1)
|
||||
|
||||
x_lin = _to_lin(x) if linearize else x
|
||||
r_lin = _to_lin(ref) if linearize else ref
|
||||
want_gpu = (process_on == "gpu") or (
|
||||
process_on == "auto" and torch.cuda.is_available() and (H * W >= 6_000_000)
|
||||
)
|
||||
dev = torch.device("cuda") if want_gpu else torch.device("cpu")
|
||||
|
||||
r_lin = r_lin.to(dev)
|
||||
y_r = _luma(r_lin)
|
||||
g_r = _sobel_mag(y_r)
|
||||
|
||||
if apply == "lowfreq":
|
||||
LF_r = _blur_nhwc(r_lin.to("cpu"), 13.0)
|
||||
|
||||
out_frames, mask_frames = [], []
|
||||
clear_ctr = 0
|
||||
|
||||
for i in range(B):
|
||||
f = x_lin[i : i + 1].to(dev)
|
||||
y_f = _luma(f)
|
||||
g_f = _sobel_mag(y_f)
|
||||
|
||||
dY = (y_f - y_r[i : i + 1]).abs()
|
||||
dG = (g_f - g_r[i : i + 1]).abs()
|
||||
|
||||
if auto_luma:
|
||||
med = torch.median(dY.view(-1))
|
||||
sigma = 1.4826 * med.item()
|
||||
tau_luma_eff = max(0.0, min(4.0 / 255.0, float(auto_k) * float(sigma)))
|
||||
else:
|
||||
tau_luma_eff = float(tau_luma)
|
||||
|
||||
if mode == "tile":
|
||||
sY = (
|
||||
_mad_tiles(dY, tile_size)
|
||||
if score_mode == "mad_tile"
|
||||
else _avgpool_tiles(dY, tile_size)
|
||||
)
|
||||
sG = (
|
||||
_mad_tiles(dG, tile_size)
|
||||
if score_mode == "mad_tile"
|
||||
else _avgpool_tiles(dG, tile_size)
|
||||
)
|
||||
mask = (sY < tau_luma_eff).to(torch.float32) * (
|
||||
sG < float(tau_grad)
|
||||
).to(torch.float32)
|
||||
mask = _upsample_mask(mask, H, W, mode="nearest")
|
||||
else:
|
||||
mask = (dY < tau_luma_eff).to(torch.float32) * (
|
||||
dG < float(tau_grad)
|
||||
).to(torch.float32)
|
||||
|
||||
mask = _dilate(mask, int(dilate))
|
||||
if feather_sigma > 0:
|
||||
mask = (
|
||||
_blur_nhwc(mask.to("cpu"), float(feather_sigma))
|
||||
.to(dev)
|
||||
.clamp_(0.0, 1.0)
|
||||
)
|
||||
|
||||
if edge_band:
|
||||
D = (y_f - y_r[i : i + 1]).abs()
|
||||
high = (D > float(tau_edge_high)).to(torch.float32)
|
||||
low = (D < float(tau_edge_low)).to(torch.float32)
|
||||
band = _dilate(high, int(band_radius)) * low
|
||||
if feather_sigma > 0:
|
||||
band = (
|
||||
_blur_nhwc(band.to("cpu"), float(feather_sigma))
|
||||
.to(dev)
|
||||
.clamp_(0.0, 1.0)
|
||||
)
|
||||
mask = (mask * (1.0 - band)).clamp_(0.0, 1.0)
|
||||
|
||||
if apply == "all":
|
||||
composed_lin = mask * r_lin[i : i + 1] + (1.0 - mask) * f
|
||||
composed_lin = composed_lin.to("cpu")
|
||||
else:
|
||||
f_cpu = f.to("cpu")
|
||||
LF_f = _blur_nhwc(f_cpu, 13.0)
|
||||
HF_f = f_cpu - LF_f
|
||||
LF_mix = (
|
||||
mask.to("cpu") * LF_r[i : i + 1] + (1.0 - mask.to("cpu")) * LF_f
|
||||
)
|
||||
composed_lin = (HF_f + LF_mix).clamp(0.0, 1.0)
|
||||
|
||||
out = _to_srgb(composed_lin) if linearize else composed_lin
|
||||
mvis = mask.to("cpu").repeat(1, 1, 1, 3).clamp_(0.0, 1.0)
|
||||
|
||||
out_frames.append(out.clamp(0, 1))
|
||||
mask_frames.append(mvis)
|
||||
|
||||
if dev.type == "cuda" and int(gpu_clear_every) > 0:
|
||||
clear_ctr += 1
|
||||
if clear_ctr >= int(gpu_clear_every):
|
||||
torch.cuda.empty_cache()
|
||||
clear_ctr = 0
|
||||
|
||||
y_out = torch.cat(out_frames, dim=0)
|
||||
mask_preview = torch.cat(mask_frames, dim=0)
|
||||
return (y_out, mask_preview)
|
||||
|
||||
|
||||
class BlackSpotCleaner:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"frames": (
|
||||
"IMAGE",
|
||||
{"tooltip": "Your clip (frames×H×W×C, values 0–1)."},
|
||||
),
|
||||
"linearize": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"tooltip": "Work in linear color for cleaner detection.",
|
||||
},
|
||||
),
|
||||
"detector": (
|
||||
["blackhat", "local_floor"],
|
||||
{
|
||||
"default": "blackhat",
|
||||
"tooltip": "blackhat: tiny dark specks • local_floor: larger soft blotches.",
|
||||
},
|
||||
),
|
||||
"radius": (
|
||||
"INT",
|
||||
{
|
||||
"default": 5,
|
||||
"min": 1,
|
||||
"max": 31,
|
||||
"tooltip": "Approximate spot size (pixels). Increase for bigger blotches.",
|
||||
},
|
||||
),
|
||||
"tau_blackhat": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 4.0 / 255.0,
|
||||
"min": 0.0,
|
||||
"max": 0.5,
|
||||
"step": 0.0005,
|
||||
"tooltip": "Base sensitivity (0–1). Lower = fix more, higher = fix less.",
|
||||
},
|
||||
),
|
||||
"auto_blackhat": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"tooltip": "Auto-tune sensitivity from image noise (robust to lighting/texture).",
|
||||
},
|
||||
),
|
||||
"bh_k": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 3.0,
|
||||
"min": 0.5,
|
||||
"max": 8.0,
|
||||
"step": 0.1,
|
||||
"tooltip": "Auto strength multiplier. Higher = more aggressive fixes.",
|
||||
},
|
||||
),
|
||||
"temporal_gate": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"tooltip": "Only fix if darker than neighboring frames (reduces false positives).",
|
||||
},
|
||||
),
|
||||
"temporal_radius": (
|
||||
"INT",
|
||||
{
|
||||
"default": 1,
|
||||
"min": 1,
|
||||
"max": 3,
|
||||
"tooltip": "How many neighbor frames to compare on each side.",
|
||||
},
|
||||
),
|
||||
"grad_guard": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"tooltip": "Skip fixes on strong edges/text to avoid halos.",
|
||||
},
|
||||
),
|
||||
"tau_grad_edge": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.07,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.001,
|
||||
"tooltip": "Edge strength where fixes are skipped (higher = skip more).",
|
||||
},
|
||||
),
|
||||
"dilate": (
|
||||
"INT",
|
||||
{
|
||||
"default": 1,
|
||||
"min": 0,
|
||||
"max": 8,
|
||||
"tooltip": "Expand the fix mask (pixels).",
|
||||
},
|
||||
),
|
||||
"feather_sigma": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 1.5,
|
||||
"min": 0.0,
|
||||
"max": 16.0,
|
||||
"step": 0.5,
|
||||
"tooltip": "Soften mask edges (pixels).",
|
||||
},
|
||||
),
|
||||
"process_on": (
|
||||
["auto", "cpu", "gpu"],
|
||||
{
|
||||
"default": "auto",
|
||||
"tooltip": "Choose CPU/GPU. Auto switches to GPU on very large frames.",
|
||||
},
|
||||
),
|
||||
"gpu_clear_every": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 1000,
|
||||
"tooltip": "If >0 and using GPU, free memory every N frames.",
|
||||
},
|
||||
),
|
||||
},
|
||||
"optional": {
|
||||
"reference": (
|
||||
"IMAGE",
|
||||
{
|
||||
"tooltip": "Optional external reference floor (1×H×W×C). Resized if needed."
|
||||
},
|
||||
),
|
||||
"ref_source": (
|
||||
["none", "external", "batch_index"],
|
||||
{
|
||||
"default": "none",
|
||||
"tooltip": "Choose a floor: none, an external image, or a frame index from this clip.",
|
||||
},
|
||||
),
|
||||
"ref_index": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 999999,
|
||||
"tooltip": "If using a frame index as the floor, which one to use.",
|
||||
},
|
||||
),
|
||||
"tau_down": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 2.0 / 255.0,
|
||||
"min": 0.0,
|
||||
"max": 0.5,
|
||||
"step": 0.0005,
|
||||
"tooltip": "Only lift where the frame is at least this much darker than the floor.",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "IMAGE")
|
||||
RETURN_NAMES = ("images", "mask_preview")
|
||||
FUNCTION = "clean"
|
||||
CATEGORY = "video utils"
|
||||
DESCRIPTION = "Removes tiny dark specks and soft blotches by gently lifting only the dark outliers—keeps edges and details safe with guards."
|
||||
|
||||
@torch.no_grad()
|
||||
def clean(
|
||||
self,
|
||||
frames,
|
||||
linearize=True,
|
||||
detector="blackhat",
|
||||
radius=5,
|
||||
tau_blackhat=4.0 / 255.0,
|
||||
auto_blackhat=True,
|
||||
bh_k=3.0,
|
||||
temporal_gate=True,
|
||||
temporal_radius=1,
|
||||
grad_guard=True,
|
||||
tau_grad_edge=0.07,
|
||||
dilate=1,
|
||||
feather_sigma=1.5,
|
||||
process_on="auto",
|
||||
gpu_clear_every=0,
|
||||
reference=None,
|
||||
ref_source="none",
|
||||
ref_index=0,
|
||||
tau_down=2.0 / 255.0,
|
||||
):
|
||||
x = frames if isinstance(frames, torch.Tensor) else torch.tensor(frames)
|
||||
B, H, W, C = x.shape
|
||||
|
||||
ref = None
|
||||
if str(ref_source) == "external" and reference is not None:
|
||||
ref = (
|
||||
reference
|
||||
if isinstance(reference, torch.Tensor)
|
||||
else torch.tensor(reference)
|
||||
)
|
||||
if ref.shape[1] != H or ref.shape[2] != W:
|
||||
ref = _resize_lanczos(ref[:1].to("cpu"), H, W)
|
||||
ref = ref[:1].repeat(B, 1, 1, 1)
|
||||
elif str(ref_source) == "batch_index":
|
||||
idx = max(0, min(int(ref_index), B - 1))
|
||||
ref = x[idx : idx + 1].repeat(B, 1, 1, 1)
|
||||
|
||||
xx = _to_lin(x) if linearize else x
|
||||
rr = _to_lin(ref) if (ref is not None and linearize) else ref
|
||||
|
||||
want_gpu = (process_on == "gpu") or (
|
||||
process_on == "auto" and torch.cuda.is_available() and (H * W >= 6_000_000)
|
||||
)
|
||||
dev = torch.device("cuda") if want_gpu else torch.device("cpu")
|
||||
|
||||
y = _luma(xx).to(dev)
|
||||
g = _sobel_mag(y)
|
||||
if rr is not None:
|
||||
y_ref = _luma(rr).to(device=y.device, dtype=y.dtype) # match y
|
||||
assert (
|
||||
y_ref.shape[0] == y.shape[0]
|
||||
), f"y_ref B={y_ref.shape[0]} vs y B={y.shape[0]}"
|
||||
assert (
|
||||
y_ref.shape[1:3] == y.shape[1:3]
|
||||
), f"spatial mismatch {y_ref.shape[1:3]} vs {y.shape[1:3]}"
|
||||
floor = (y_ref - y) > float(tau_down)
|
||||
|
||||
r = int(radius)
|
||||
if detector == "blackhat":
|
||||
k = max(1, 2 * r + 1)
|
||||
k = min(k, 2 * min(H, W) - 1)
|
||||
t = y.permute(0, 3, 1, 2)
|
||||
d = F.max_pool2d(
|
||||
F.pad(t, (k // 2, k // 2, k // 2, k // 2), mode="replicate"),
|
||||
kernel_size=k,
|
||||
stride=1,
|
||||
)
|
||||
e = -F.max_pool2d(
|
||||
F.pad(-d, (k // 2, k // 2, k // 2, k // 2), mode="replicate"),
|
||||
kernel_size=k,
|
||||
stride=1,
|
||||
)
|
||||
y_close = e.permute(0, 2, 3, 1)
|
||||
score = (y_close - y).clamp_min(0)
|
||||
else:
|
||||
sigma = max(0.5, r / 2.0)
|
||||
Bsm = _blur_nhwc(y.to("cpu"), sigma).to(y.device)
|
||||
score = (Bsm - y).clamp_min(0)
|
||||
tau = float(tau_blackhat)
|
||||
if bool(auto_blackhat):
|
||||
region = (g < float(tau_grad_edge)).to(torch.float32)
|
||||
if region.sum() < 1:
|
||||
region = torch.ones_like(region)
|
||||
sel = score[region > 0.5].view(-1)
|
||||
if sel.numel() > 0:
|
||||
med = torch.median(sel)
|
||||
sigma_bh = 1.4826 * torch.median((sel - med).abs())
|
||||
tau = max(tau, float(bh_k) * float(sigma_bh))
|
||||
|
||||
mask = (score > tau).to(torch.float32)
|
||||
|
||||
if rr is not None:
|
||||
floor = (y_ref - y) > float(tau_down)
|
||||
mask = torch.maximum(mask, floor.to(torch.float32))
|
||||
|
||||
if temporal_gate and B > 1:
|
||||
idxs = []
|
||||
for dt in range(1, int(temporal_radius) + 1):
|
||||
if dt < B:
|
||||
idxs += [
|
||||
torch.clamp(torch.arange(B) - dt, 0, B - 1),
|
||||
torch.clamp(torch.arange(B) + dt, 0, B - 1),
|
||||
]
|
||||
neigh = torch.stack([y[i] for i in torch.stack(idxs, dim=0)], dim=0)
|
||||
y_med = torch.median(neigh, dim=0).values
|
||||
mask = mask * ((y_med - y) > tau).to(torch.float32)
|
||||
|
||||
if grad_guard:
|
||||
guard = (g < float(tau_grad_edge)).to(torch.float32)
|
||||
mask = mask * guard
|
||||
|
||||
mask = _dilate(mask, int(dilate))
|
||||
if feather_sigma > 0:
|
||||
mask = (
|
||||
_blur_nhwc(mask.to("cpu"), float(feather_sigma))
|
||||
.to(dev)
|
||||
.clamp_(0.0, 1.0)
|
||||
)
|
||||
|
||||
delta = score * mask
|
||||
delta3 = delta.repeat(1, 1, 1, 3)
|
||||
out_lin = (xx.to(dev) + delta3).clamp(0.0, 1.0)
|
||||
if dev.type == "cuda":
|
||||
out_lin = out_lin.to("cpu")
|
||||
|
||||
out = _to_srgb(out_lin) if linearize else out_lin
|
||||
mask_preview = mask.to("cpu").repeat(1, 1, 1, 3).clamp_(0.0, 1.0)
|
||||
|
||||
if dev.type == "cuda" and int(gpu_clear_every) > 0:
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
return (out.clamp(0, 1), mask_preview)
|
||||
544
custom_nodes/whiterabbit/post_process.py
Normal file
544
custom_nodes/whiterabbit/post_process.py
Normal file
@@ -0,0 +1,544 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# SPDX-FileCopyrightText: 2025 ArtificialSweetener
|
||||
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
from collections import OrderedDict
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
import comfy.utils as comfy_utils
|
||||
import folder_paths
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from PIL import Image
|
||||
from torchlanc import lanczos_resize
|
||||
|
||||
|
||||
def _chunk_spans(n: int, cap: int) -> List[Tuple[int, int]]:
|
||||
if cap <= 0 or cap >= n:
|
||||
return [(0, n)]
|
||||
out = []
|
||||
i = 0
|
||||
while i < n:
|
||||
j = min(n, i + cap)
|
||||
out.append((i, j))
|
||||
i = j
|
||||
return out
|
||||
|
||||
|
||||
def _bhwc_to_nchw(x: torch.Tensor) -> torch.Tensor:
|
||||
return x.movedim(-1, -3)
|
||||
|
||||
|
||||
def _nchw_to_bhwc(x: torch.Tensor) -> torch.Tensor:
|
||||
return x.movedim(-3, -1)
|
||||
|
||||
|
||||
def _ensure_rgba_nchw(wm: torch.Tensor) -> torch.Tensor:
|
||||
"""
|
||||
wm: (1,H,W,C) in [0,1] → return (4,H,W) float
|
||||
C may be 1,3,4; synthesize alpha=1 if missing.
|
||||
"""
|
||||
if wm.dim() != 4 or wm.shape[0] != 1:
|
||||
raise ValueError(
|
||||
"watermark must be a single IMAGE tensor of shape (1,H,W,C) in [0,1]."
|
||||
)
|
||||
_, h, w, c = wm.shape
|
||||
x = _bhwc_to_nchw(wm[0]).float().clamp_(0, 1) # (C,H,W)
|
||||
if c == 4:
|
||||
return x
|
||||
if c == 3:
|
||||
a = torch.ones(1, h, w, device=x.device, dtype=x.dtype)
|
||||
return torch.cat([x, a], dim=0)
|
||||
if c == 1:
|
||||
rgb = x.repeat(3, 1, 1)
|
||||
a = torch.ones(1, h, w, device=x.device, dtype=x.dtype)
|
||||
return torch.cat([rgb, a], dim=0)
|
||||
raise ValueError(f"Unsupported watermark channel count C={c}. Expected 1, 3 or 4.")
|
||||
|
||||
|
||||
def _load_rgba_from_path(path: str, device: torch.device) -> torch.Tensor:
|
||||
"""
|
||||
Load an image from disk as RGBA in [0,1] and return (4,H,W) on the target device.
|
||||
No rotation or other processing happens here.
|
||||
"""
|
||||
try:
|
||||
with Image.open(path) as im:
|
||||
im = im.convert("RGBA")
|
||||
arr = np.asarray(im, dtype=np.float32) / 255.0 # (H,W,4) in [0,1]
|
||||
except Exception as e:
|
||||
raise ValueError(f"Failed to load watermark image from '{path}': {e}")
|
||||
t = torch.from_numpy(arr).to(device=device, dtype=torch.float32) # (H,W,4)
|
||||
return t.permute(2, 0, 1).contiguous() # (4,H,W)
|
||||
|
||||
|
||||
def _rotate_bicubic_expand(x: torch.Tensor, degrees: float) -> torch.Tensor:
|
||||
"""
|
||||
x: (N,C,H,W). Rotate around center with bicubic sampling and EXPAND canvas
|
||||
(PIL-like `expand=True`). Parts outside input are zero/transparent.
|
||||
"""
|
||||
deg = float(degrees) % 360.0
|
||||
if deg == 0.0:
|
||||
return x
|
||||
|
||||
N, C, H, W = x.shape
|
||||
rad = deg * 3.141592653589793 / 180.0
|
||||
cosr = float(torch.cos(torch.tensor(rad)))
|
||||
sinr = float(torch.sin(torch.tensor(rad)))
|
||||
|
||||
# Expanded output size (axis-aligned bounding box of the rotated rectangle)
|
||||
new_w = int((abs(W * cosr) + abs(H * sinr)) + 0.9999)
|
||||
new_h = int((abs(H * cosr) + abs(W * sinr)) + 0.9999)
|
||||
new_w = max(1, new_w)
|
||||
new_h = max(1, new_h)
|
||||
|
||||
# Centers in pixel coords
|
||||
cx_in = (W - 1) * 0.5
|
||||
cy_in = (H - 1) * 0.5
|
||||
cx_out = (new_w - 1) * 0.5
|
||||
cy_out = (new_h - 1) * 0.5
|
||||
|
||||
# Output grid in pixel coords
|
||||
ys = torch.linspace(0, new_h - 1, new_h, device=x.device, dtype=x.dtype)
|
||||
xs = torch.linspace(0, new_w - 1, new_w, device=x.device, dtype=x.dtype)
|
||||
gy, gx = torch.meshgrid(ys, xs, indexing="ij")
|
||||
|
||||
# Inverse rotation: output → input (rotate about centers)
|
||||
rx = gx - cx_out
|
||||
ry = gy - cy_out
|
||||
x_in = cosr * rx + sinr * ry + cx_in
|
||||
y_in = -sinr * rx + cosr * ry + cy_in
|
||||
|
||||
# Normalize to [-1,1] for align_corners=False
|
||||
x_norm = (x_in + 0.5) / W * 2.0 - 1.0
|
||||
y_norm = (y_in + 0.5) / H * 2.0 - 1.0
|
||||
grid = torch.stack((x_norm, y_norm), dim=-1).unsqueeze(0).repeat(N, 1, 1, 1)
|
||||
|
||||
# Sample
|
||||
try:
|
||||
return F.grid_sample(
|
||||
x, grid, mode="bicubic", padding_mode="zeros", align_corners=False
|
||||
)
|
||||
except Exception:
|
||||
return F.grid_sample(
|
||||
x, grid, mode="bilinear", padding_mode="zeros", align_corners=False
|
||||
)
|
||||
|
||||
|
||||
def _position_xy(
|
||||
position: str,
|
||||
base_w: int,
|
||||
base_h: int,
|
||||
wm_w: int,
|
||||
wm_h: int,
|
||||
pad_x: int,
|
||||
pad_y: int,
|
||||
) -> Tuple[int, int]:
|
||||
pos = (position or "bottom-right").strip().lower()
|
||||
if pos == "center":
|
||||
return (base_w - wm_w) // 2, (base_h - wm_h) // 2
|
||||
|
||||
x = (
|
||||
0
|
||||
if "left" in pos
|
||||
else (base_w - wm_w if "right" in pos else (base_w - wm_w) // 2)
|
||||
)
|
||||
y = (
|
||||
0
|
||||
if "top" in pos
|
||||
else (base_h - wm_h if "bottom" in pos else (base_h - wm_h) // 2)
|
||||
)
|
||||
|
||||
if "left" in pos:
|
||||
x += int(pad_x)
|
||||
if "right" in pos:
|
||||
x -= int(pad_x)
|
||||
if "top" in pos:
|
||||
y += int(pad_y)
|
||||
if "bottom" in pos:
|
||||
y -= int(pad_y)
|
||||
return x, y
|
||||
|
||||
|
||||
class _SmallLRU:
|
||||
def __init__(self, capacity: int = 6):
|
||||
self.capacity = int(max(1, capacity))
|
||||
self._m: "OrderedDict[Tuple, Tuple[torch.Tensor, torch.Tensor]]" = OrderedDict()
|
||||
|
||||
def get(self, key: Tuple):
|
||||
v = self._m.get(key)
|
||||
if v is not None:
|
||||
self._m.move_to_end(key)
|
||||
return v
|
||||
|
||||
def put(self, key: Tuple, value):
|
||||
if key in self._m:
|
||||
self._m.move_to_end(key)
|
||||
self._m[key] = value
|
||||
if len(self._m) > self.capacity:
|
||||
self._m.popitem(last=False)
|
||||
|
||||
|
||||
class BatchWatermarkSingle:
|
||||
"""
|
||||
Single-position watermark for image batches.
|
||||
|
||||
- Scale uses base image WIDTH × (scale/100)
|
||||
- Rotation always applies, with clipping (no expand)
|
||||
- Padding in pixels (ignored for center)
|
||||
- TorchLanc for watermark resize
|
||||
- Chunked batches + small LRU cache + optional torch.compile
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
# Mirror LoadImage: list files from the input directory, allow upload
|
||||
input_dir = folder_paths.get_input_directory()
|
||||
files = [
|
||||
f
|
||||
for f in os.listdir(input_dir)
|
||||
if os.path.isfile(os.path.join(input_dir, f))
|
||||
]
|
||||
files = folder_paths.filter_files_content_types(files, ["image"])
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"image": (
|
||||
"IMAGE",
|
||||
{
|
||||
"tooltip": "Images to watermark. Accepts (H,W,C) or (B,H,W,C) with values in [0–1]. Processed on GPU."
|
||||
},
|
||||
),
|
||||
"watermark": (
|
||||
sorted(files),
|
||||
{
|
||||
"image_upload": True,
|
||||
"tooltip": "Select or upload the watermark image (PNG recommended). The file’s transparency is preserved.",
|
||||
},
|
||||
),
|
||||
"position": (
|
||||
["bottom-right", "bottom-left", "top-right", "top-left", "center"],
|
||||
{
|
||||
"default": "bottom-right",
|
||||
"tooltip": "Where to place the watermark. Padding is ignored when 'center' is selected. Rotation clips; no canvas expand.",
|
||||
},
|
||||
),
|
||||
"scale": (
|
||||
"INT",
|
||||
{
|
||||
"default": 70,
|
||||
"min": 1,
|
||||
"max": 100,
|
||||
"step": 1,
|
||||
"tooltip": "Width-based scaling. Target watermark width = image width × (scale/100). Aspect ratio preserved.",
|
||||
},
|
||||
),
|
||||
"transparency": (
|
||||
"INT",
|
||||
{
|
||||
"default": 100,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"step": 1,
|
||||
"tooltip": "Alpha multiplier for the watermark: 100 = unchanged, 0 = fully transparent.",
|
||||
},
|
||||
),
|
||||
"rotation": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 359,
|
||||
"step": 1,
|
||||
"tooltip": "Rotate the watermark (degrees) with bicubic resampling. Canvas expands so nothing is clipped (PIL-style).",
|
||||
},
|
||||
),
|
||||
"padding_x": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 16384,
|
||||
"step": 1,
|
||||
"tooltip": "Extra horizontal padding in pixels from the chosen edge (ignored when position='center').",
|
||||
},
|
||||
),
|
||||
"padding_y": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 16384,
|
||||
"step": 1,
|
||||
"tooltip": "Extra vertical padding in pixels from the chosen edge (ignored when position='center').",
|
||||
},
|
||||
),
|
||||
"optical_padding": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": False,
|
||||
"tooltip": "Adjust placement by the watermark’s visual center so equal padding looks right (optical alignment). Affects corner positions; ignored when position='center'.",
|
||||
},
|
||||
),
|
||||
"optical_strength": (
|
||||
"INT",
|
||||
{
|
||||
"default": 40,
|
||||
"min": 0,
|
||||
"max": 100,
|
||||
"step": 5,
|
||||
"tooltip": "How strongly to nudge toward visual centering (0–100). 0 = off. Higher values shift more for wide/rotated marks.",
|
||||
},
|
||||
),
|
||||
"max_batch_size": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 4096,
|
||||
"step": 1,
|
||||
"tooltip": "Process images in chunks to control VRAM. 0 = process the whole batch at once.",
|
||||
},
|
||||
),
|
||||
"sinc_window": (
|
||||
"INT",
|
||||
{
|
||||
"default": 3,
|
||||
"min": 1,
|
||||
"max": 8,
|
||||
"step": 1,
|
||||
"tooltip": "Lanczos window size (a) used when resizing the watermark. Higher = sharper (but more ringing).",
|
||||
},
|
||||
),
|
||||
"precision": (
|
||||
["fp32", "fp16", "bf16"],
|
||||
{
|
||||
"default": "fp32",
|
||||
"tooltip": "Resampling compute dtype. fp32 = safest quality; fp16/bf16 can be faster on many GPUs.",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "apply"
|
||||
CATEGORY = "image/post"
|
||||
DESCRIPTION = "GPU accelerated watermark overlay. TorchLanc resize for quality and speed. Works for single images, but efficient for batches, too!"
|
||||
|
||||
def apply(
|
||||
self,
|
||||
image: torch.Tensor,
|
||||
watermark: str,
|
||||
position: str,
|
||||
scale: int,
|
||||
transparency: int,
|
||||
rotation: int,
|
||||
padding_x: int,
|
||||
padding_y: int,
|
||||
optical_padding: bool,
|
||||
optical_strength: int,
|
||||
max_batch_size: int,
|
||||
sinc_window: int,
|
||||
precision: str,
|
||||
):
|
||||
|
||||
if image is None or not isinstance(image, torch.Tensor):
|
||||
raise ValueError(
|
||||
"image must be a torch.Tensor with shape (H,W,C) or (B,H,W,C) in [0,1]."
|
||||
)
|
||||
if not isinstance(watermark, str) or not watermark:
|
||||
raise ValueError("Select a watermark image from the list (or upload one).")
|
||||
|
||||
if not folder_paths.exists_annotated_filepath(watermark):
|
||||
raise ValueError(f"Invalid watermark file: {watermark}")
|
||||
watermark_path = folder_paths.get_annotated_filepath(watermark)
|
||||
|
||||
# Refuse sequences (we must get a tensor just like Lanczos)
|
||||
if isinstance(image, (list, tuple)):
|
||||
raise TypeError(
|
||||
"Expected IMAGE tensor (H,W,C) or (B,H,W,C); got a sequence. Use 'Image Batch' to re-batch."
|
||||
)
|
||||
|
||||
# Accept both single images (H,W,C) and batches (B,H,W,C); normalize to batch
|
||||
if image.dim() == 3:
|
||||
image = image.unsqueeze(0) # -> (1,H,W,C)
|
||||
elif image.dim() != 4:
|
||||
raise ValueError(
|
||||
f"Unexpected IMAGE tensor rank {image.dim()}; expected 3 or 4 dims."
|
||||
)
|
||||
|
||||
B, H, W, C = image.shape
|
||||
if C not in (1, 3, 4):
|
||||
raise ValueError(f"Unsupported channel count C={C}. Expected 1, 3 or 4.")
|
||||
|
||||
# Common
|
||||
device = torch.device("cuda")
|
||||
scale = int(scale)
|
||||
transparency = max(0, min(100, int(transparency)))
|
||||
rotation = int(rotation) % 360
|
||||
pad_x = int(padding_x)
|
||||
pad_y = int(padding_y)
|
||||
optical_padding = bool(optical_padding)
|
||||
optical_strength = max(0, min(100, int(optical_strength)))
|
||||
|
||||
# Prepare watermark once (load RGBA from disk to preserve original transparency)
|
||||
wm_rgba = _load_rgba_from_path(watermark_path, device) # (4,hw,ww)
|
||||
wm_h0, wm_w0 = int(wm_rgba.shape[1]), int(wm_rgba.shape[2])
|
||||
|
||||
# Progress
|
||||
pbar = comfy_utils.ProgressBar(B)
|
||||
|
||||
out_chunks: List[torch.Tensor] = []
|
||||
|
||||
# Compute final watermark once (all images in a Comfy batch share H×W)
|
||||
target_w = max(1, int(round(W * (scale / 100.0))))
|
||||
target_h = max(1, int(round(wm_h0 * target_w / max(1, wm_w0))))
|
||||
|
||||
# Premultiply BEFORE resampling to avoid dark fringes
|
||||
pm0 = wm_rgba[:3, :, :] * wm_rgba[3:4, :, :]
|
||||
a0 = wm_rgba[3:4, :, :]
|
||||
wm_pm = torch.cat([pm0, a0], dim=0).unsqueeze(0) # (1,4,hw,ww)
|
||||
|
||||
wm_resized_pm = lanczos_resize(
|
||||
wm_pm,
|
||||
height=target_h,
|
||||
width=target_w,
|
||||
a=int(sinc_window),
|
||||
precision=str(precision),
|
||||
clamp=True,
|
||||
chunk_size=0,
|
||||
)[
|
||||
0
|
||||
] # (4,h,w)
|
||||
|
||||
# Apply transparency uniformly to premultiplied color AND alpha
|
||||
if transparency != 100:
|
||||
t = float(transparency) / 100.0
|
||||
wm_resized_pm[:3, :, :].mul_(t)
|
||||
wm_resized_pm[3:4, :, :].mul_(t)
|
||||
|
||||
# Rotate in premultiplied space (expand canvas)
|
||||
wm_final = _rotate_bicubic_expand(wm_resized_pm.unsqueeze(0), rotation)[
|
||||
0
|
||||
] # (4,h,w)
|
||||
pm_final, a_final = wm_final[:3, :, :], wm_final[3:4, :, :] # (3,h,w), (1,h,w)
|
||||
|
||||
# Position
|
||||
wm_h, wm_w = int(pm_final.shape[1]), int(pm_final.shape[2])
|
||||
x, y = _position_xy(position, W, H, wm_w, wm_h, pad_x, pad_y)
|
||||
|
||||
# Optional optical padding (corner positions only)
|
||||
if optical_padding and position != "center":
|
||||
a = a_final[0] # (h,w)
|
||||
denom = a.sum()
|
||||
if float(denom.item() if hasattr(denom, "item") else denom) > 1e-8:
|
||||
ys = torch.linspace(0, wm_h - 1, wm_h, device=a.device, dtype=a.dtype)
|
||||
xs = torch.linspace(0, wm_w - 1, wm_w, device=a.device, dtype=a.dtype)
|
||||
cy = (a.sum(dim=1) * ys).sum() / denom
|
||||
cx = (a.sum(dim=0) * xs).sum() / denom
|
||||
gx = (wm_w - 1) * 0.5
|
||||
gy = (wm_h - 1) * 0.5
|
||||
s = float(optical_strength) / 100.0
|
||||
dx = (gx - cx) * s # positive when centroid is left of center
|
||||
dy = (gy - cy) * s # positive when centroid is above center
|
||||
|
||||
if "right" in position:
|
||||
x += int(round(dx.item()))
|
||||
if "left" in position:
|
||||
x -= int(round(dx.item()))
|
||||
if "bottom" in position:
|
||||
y += int(round(dy.item()))
|
||||
if "top" in position:
|
||||
y -= int(round(dy.item()))
|
||||
|
||||
# Intersection with base image (clip)
|
||||
x0 = max(0, x)
|
||||
y0 = max(0, y)
|
||||
x1 = min(W, x + wm_w)
|
||||
y1 = min(H, y + wm_h)
|
||||
|
||||
if x1 <= x0 or y1 <= y0:
|
||||
out = image.to("cpu", non_blocking=False).float().clamp_(0, 1).contiguous()
|
||||
if not torch.is_tensor(out) or out.dim() != 4:
|
||||
raise TypeError(
|
||||
f"Pass-through produced non-tensor or wrong rank: {type(out)} / {getattr(out,'shape',None)}"
|
||||
)
|
||||
return (out,)
|
||||
|
||||
wx0 = x0 - x
|
||||
wy0 = y0 - y
|
||||
w_w = x1 - x0
|
||||
w_h = y1 - y0
|
||||
|
||||
pm_crop = pm_final[:, wy0 : wy0 + w_h, wx0 : wx0 + w_w].contiguous()
|
||||
a_crop = a_final[:, wy0 : wy0 + w_h, wx0 : wx0 + w_w].contiguous()
|
||||
|
||||
# Process in chunks
|
||||
for s, e in _chunk_spans(B, int(max_batch_size)):
|
||||
sub = (
|
||||
_bhwc_to_nchw(image[s:e])
|
||||
.to(device, non_blocking=True)
|
||||
.float()
|
||||
.clamp_(0, 1)
|
||||
)
|
||||
|
||||
ov_pm = pm_crop.unsqueeze(0).expand(sub.shape[0], -1, -1, -1)
|
||||
ov_a = a_crop.unsqueeze(0).expand(sub.shape[0], -1, -1, -1)
|
||||
|
||||
if C == 1:
|
||||
rgb = sub.repeat(1, 3, 1, 1)
|
||||
roi = rgb[:, :, y0:y1, x0:x1]
|
||||
roi_out = roi * (1.0 - ov_a) + ov_pm
|
||||
rgb[:, :, y0:y1, x0:x1] = roi_out
|
||||
# Convert back to 1ch (luma)
|
||||
y_luma = (
|
||||
0.2126 * rgb[:, 0:1] + 0.7152 * rgb[:, 1:2] + 0.0722 * rgb[:, 2:3]
|
||||
).clamp_(0, 1)
|
||||
sub = y_luma
|
||||
elif C == 3:
|
||||
roi = sub[:, :3, y0:y1, x0:x1]
|
||||
roi_out = roi * (1.0 - ov_a) + ov_pm
|
||||
sub[:, :3, y0:y1, x0:x1] = roi_out
|
||||
else: # C == 4
|
||||
roi = sub[:, :3, y0:y1, x0:x1]
|
||||
roi_out = roi * (1.0 - ov_a) + ov_pm
|
||||
sub[:, :3, y0:y1, x0:x1] = roi_out
|
||||
|
||||
out_chunks.append(
|
||||
_nchw_to_bhwc(sub).to("cpu", non_blocking=False).clamp_(0, 1)
|
||||
)
|
||||
pbar.update(e - s)
|
||||
|
||||
out = torch.cat(out_chunks, dim=0) # CPU BHWC chunks → CPU BHWC batch
|
||||
|
||||
if out.dim() > 4:
|
||||
b_flat = 1
|
||||
for s in out.shape[:-3]:
|
||||
b_flat *= int(s)
|
||||
out = out.reshape(b_flat, *out.shape[-3:])
|
||||
if out.dim() == 3:
|
||||
out = out.unsqueeze(0)
|
||||
if (
|
||||
out.dim() == 4
|
||||
and out.shape[1] in (1, 3, 4)
|
||||
and out.shape[-1] not in (1, 3, 4)
|
||||
):
|
||||
out = out.permute(0, 2, 3, 1).contiguous()
|
||||
if out.dim() != 4:
|
||||
raise ValueError(
|
||||
f"Unexpected IMAGE tensor shape {tuple(out.shape)}; expected (B,H,W,C)."
|
||||
)
|
||||
|
||||
out = (
|
||||
out.to("cpu", non_blocking=False)
|
||||
.to(dtype=torch.float32)
|
||||
.clamp_(0, 1)
|
||||
.contiguous()
|
||||
)
|
||||
|
||||
if not torch.is_tensor(out):
|
||||
raise TypeError(f"IMAGE output must be torch.Tensor, got: {type(out)}")
|
||||
|
||||
return (out,)
|
||||
22
custom_nodes/whiterabbit/pyproject.toml
Normal file
22
custom_nodes/whiterabbit/pyproject.toml
Normal file
@@ -0,0 +1,22 @@
|
||||
[project]
|
||||
name = "whiterabbit"
|
||||
description = "Powerful video frame manipulation nodes for ComfyUI such as: efficient high quality batch scaling, arbitrary framerate resampling, seamless video loop tools, batch watermark composite, and more."
|
||||
version = "1.1.1"
|
||||
license = {file = "LICENSE"}
|
||||
classifiers = [
|
||||
"Operating System :: OS Independent",
|
||||
"Environment :: GPU :: NVIDIA CUDA",
|
||||
]
|
||||
|
||||
dependencies = ["torchlanc", "packaging"]
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/Artificial-Sweetener/comfyui-WhiteRabbit"
|
||||
Documentation = "https://github.com/Artificial-Sweetener/comfyui-WhiteRabbit/wiki"
|
||||
"Bug Tracker" = "https://github.com/Artificial-Sweetener/comfyui-WhiteRabbit/issues"
|
||||
|
||||
[tool.comfy]
|
||||
PublisherId = "artificialsweetener"
|
||||
DisplayName = "WhiteRabbit"
|
||||
Icon = ""
|
||||
includes = []
|
||||
116
custom_nodes/whiterabbit/readme.md
Normal file
116
custom_nodes/whiterabbit/readme.md
Normal file
@@ -0,0 +1,116 @@
|
||||
# WhiteRabbit: Master the Flow of Time 🐇
|
||||
**English** | [简体中文](README_zh-CN.md)
|
||||
|
||||
This is **comfyui-WhiteRabbit**, a nodepack designed to help you work with video from within ComfyUI.
|
||||
|
||||
The Rabbit's specialty is looping through time to help you create seamless looping video, but that's not all she brings to the tea party. Quality, arbitrary framerate resampling and super fast image resizing are also part of the kit!
|
||||
|
||||
While some of these nodes certainly can be used for single-image tasks, every one of them is designed with efficient **batch handling** in mind and that means the performance gains compound, letting you process whole video clips as fast as possible within your hardware constraints.
|
||||
|
||||
|
||||
## Installation
|
||||
|
||||
WhiteRabbit supports two layouts:
|
||||
|
||||
1) **External base pack (preferred when present)**: `custom_nodes/comfyui-frame-interpolation/`
|
||||
2) **Vendored fallback (bundled here)**: `vendor/`
|
||||
|
||||
**Quick install:**
|
||||
1. Drop the **comfyui-WhiteRabbit** folder into `ComfyUI/custom_nodes/`.
|
||||
2. Install this node’s requirements:
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
|
||||
**Optionally**, you can install [ComfyUI-Frame-Interpolation](https://github.com/Fannovel16/ComfyUI-Frame-Interpolation) inside of your custom_nodes/ folder. WhiteRabbit will detect it and use resources from there. Especially handy if you already use it, since it avoids keeping two versions of the RIFE models.
|
||||
|
||||
### Python requirements
|
||||
|
||||
This node relies on ComfyUI’s core packages (e.g., `torch`, `torchvision`, `numpy`, `einops`, `pyyaml`) that are already provided by ComfyUI. Your **node-local** `requirements.txt` only adds:
|
||||
|
||||
```
|
||||
packaging
|
||||
torchlanc
|
||||
```
|
||||
|
||||
## The Nodes
|
||||
|
||||
This pack of nodes helps you solve some of the trickiest problems in video creation.
|
||||
|
||||
### Time Benders
|
||||
|
||||
These nodes bend time itself to add or remove frames, all powered by the **RIFE** interpolation model. For a slight speed boost, they’re optimized to work together, caching the RIFE model for small efficiency gains in multi‑RIFE workflows.
|
||||
|
||||
- **RIFE VFI Interpolate by Multiple**: The basic tool for frame interpolation. Multiply your frames by 2×, 4×, etc., and it’ll generate the new frames needed to make your video silky smooth.
|
||||
- **RIFE VFI FPS Resample**: A master of time travel. Convert your video to a specific target frame rate, automatically handling both adding and dropping frames as needed. Includes features to prevent common artifacts like flicker for a clean result.
|
||||
- **RIFE VFI Custom Timing**: Ready for total control? Place every new frame with surgical precision. Create custom speed ramps or smooth out specific moments by providing a custom timing list.
|
||||
- **RIFE Seam Timing Analyzer**: The perfect companion to the custom timing node. Automatically calculates the exact timing for a seamless loop, giving you the CSV values you need to make your transition feel flawless.
|
||||
|
||||

|
||||
> *Example:* The **RIFE VFI FPS Resample** node is a master of time, resampling your video to a new frame rate. Try for yourself; the workflow is attached!
|
||||
|
||||
### Loop Masters
|
||||
|
||||
Making a seamless video loop can feel like a riddle. These nodes give you the keys to the perfect, continuous loop.
|
||||
|
||||
- **Prepare Loop Frames**: The first step. This node takes your entire video and prepares the loop "seam" by isolating the last and first frames into a separate batch. This little pair is all your interpolator needs to get started on the transition.
|
||||
- **Assemble Loop Frames**: The final piece. After your interpolator works its magic, this node takes your original video and appends the new seam frames to the end, assembling your complete, continuous loop.
|
||||
- **Autocrop to Loop**: Don't get lost in the forest of frames! This clever node intelligently analyzes your video to find the best possible place to crop from the end, ensuring your loop flows as smoothly as can be.
|
||||
- **Trim Batch Ends**: A simple tool for trimming a fixed number of frames from the beginning or end of your clip, perfect for removing unwanted intros or outros.
|
||||
- **Roll Frames**: Change the order of the images in a batch cyclicly. In the context of a loop, this will change on what frame your loop starts.
|
||||
- **Unroll Frames**: Undo the work done by the above node; you may want to roll frames for a specific process (like interpolation) before returning them to their original order. This node comes with the ability to add a frame multiplier to put it in sync with a **RIFE VFI Interpolate by Multiple** that comes before.
|
||||
|
||||

|
||||
> *Example:* Stitch a seamless loop with **Prepare Loop Frames** ➜ **RIFE Seam Timing Analyzer** ➜ **RIFE VFI Custom Timing ➜ **Assemble Loop Frames**. You can drop this png into ComfyUI and take it for a test drive!
|
||||
|
||||

|
||||
> *Example:* The best loop is the one you already have. **Autocrop to Loop** can help you find the best end frame by analyzing the visual difference and timing between trailing frames in your clip.
|
||||
|
||||
### Post-Processing
|
||||
|
||||
These nodes play support!
|
||||
|
||||
- **Batch Resize w/ Lanczos**: Fast, principled, and uncompromising in quality. This CUDA‑accelerated node resizes a batch of images (or your single images, of course) using the high‑quality Lanczos algorithm written for PyTorch; [TorchLanc](https://github.com/Artificial-Sweetener/TorchLanc). It’s dramatically faster than CPU alternatives like Pillow's own Lanczos, with potential for up to a *10× speed increase*.
|
||||
- **Upscale w/ Model (Advanced)**: A version of ComfyUI's own "Upscale Image (Using Model)" but with direct controls exposed for batch size and tiling which can help speed up scaling dramatically if you tune the numbers to your system.
|
||||
- **Pixel Hold**: Can be used to reduce video flicker and clean up static parts of a video by reducing small fluctuations caused by video diffusion or compression. There is the potential to use this creatively because it can also take an input image as its baseline.
|
||||
- **Watermark**: For single images or batches. Very quick, especially when compared to doing the same task in pro editing tools.
|
||||
|
||||

|
||||
> *Example:* Resize images quickly with **Batch Resize w/ Lanczos**. Workflow attached!!
|
||||
|
||||

|
||||
> *Example:* Use **Upscale w/ Model (Advanced)** in concert with **Batch Resize w/ Lanczos** to reach a specific target size like so. The image is holding onto the workflow for you.
|
||||
|
||||

|
||||
> *Example:* Apply a watermark to each frame rapidly with smart configuration options. Workflow included.
|
||||
|
||||
## License & Acknowledgements
|
||||
- **Project License:** GNU Affero General Public License v3.0 (**AGPL‑3.0**). Please read the full [LICENSE](LICENSE) included with this repo! The AGPL-3.0 is a strong copyleft license. If you convey the software, you must provide its corresponding source; and if you let users interact with a modified version over a network, you must offer them that modified version’s corresponding source.
|
||||
|
||||
- **Dependency License (MIT):** This project **vendors** minimal components from **[ComfyUI-Frame-Interpolation](https://github.com/Fannovel16/ComfyUI-Frame-Interpolation)** for reliability. These files are licensed under MIT by **[Fannovel16](https://github.com/Fannovel16)** and **[contributors](https://github.com/Fannovel16/ComfyUI-Frame-Interpolation/graphs/contributors)**; see the included license at `LICENSES/MIT-ComfyUI-Frame-Interpolation.txt`:
|
||||
- `vendor/vfi_utils.py`
|
||||
- `vendor/rife/__init__.py`
|
||||
- `vendor/rife/rife_arch.py`
|
||||
- From **[ComfyUI-Frame-Interpolation](https://github.com/Fannovel16/ComfyUI-Frame-Interpolation)**, it also adapt small portions within [`interpolation.py`](interpolation.py).
|
||||
- UI for **Batch Resize w/ Lanczos** was inspired by the similar node from [Kijai](https://github.com/kijai/)'s excellent [KJNodes](thub.com/kijai/ComfyUI-KJNodes).
|
||||
|
||||
### Research citations
|
||||
|
||||
This node pack uses **RIFE (IFNet)** for video frame interpolation. You can read the white paper [here](https://ar5iv.labs.arxiv.org/html/2011.06294).
|
||||
|
||||
```bibtex
|
||||
@inproceedings{huang2022rife,
|
||||
title={Real-Time Intermediate Flow Estimation for Video Frame Interpolation},
|
||||
author={Huang, Zhewei and Zhang, Tianyuan and Heng, Wen and Shi, Boxin and Zhou, Shuchang},
|
||||
booktitle={European Conference on Computer Vision (ECCV)},
|
||||
year={2022}
|
||||
}
|
||||
```
|
||||
---
|
||||
|
||||
## From the Developer ❤️
|
||||
|
||||
I hope you love using these nodes as much as I loved putting them together!
|
||||
|
||||
- **Buy Me a Coffee**: You can help fuel more projects like this at my [Ko-fi page](https://ko-fi.com/artificial_sweetener).
|
||||
- **My Website & Socials**: See my art, poetry, and other dev updates at [artificialsweetener.ai](https://artificialsweetener.ai).
|
||||
- **If you like this project**, it would mean a lot to me if you gave me a star here on Github!! ⭐
|
||||
2
custom_nodes/whiterabbit/requirements.txt
Normal file
2
custom_nodes/whiterabbit/requirements.txt
Normal file
@@ -0,0 +1,2 @@
|
||||
packaging
|
||||
torchlanc
|
||||
696
custom_nodes/whiterabbit/scaling.py
Normal file
696
custom_nodes/whiterabbit/scaling.py
Normal file
@@ -0,0 +1,696 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# SPDX-FileCopyrightText: 2025 ArtificialSweetener <artificialsweetenerai@proton.me>
|
||||
import math
|
||||
from typing import List, Optional, Tuple
|
||||
|
||||
import comfy.utils as comfy_utils
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from comfy import model_management
|
||||
from torchlanc import lanczos_resize
|
||||
|
||||
|
||||
class UpscaleWithModelAdvanced:
|
||||
DESCRIPTION = """Based on Comfy's native "Upscale Image (using Model)", with controls exposed to tune for large batches, avoid slow
|
||||
OOM fallbacks, and create opportunities to optimize for speed.
|
||||
|
||||
Defaults
|
||||
- Behaves about the same as the original node.
|
||||
|
||||
Controls
|
||||
- max_batch_size > 0: process images in chunks to keep VRAM steady and reduce fallback slowdowns.
|
||||
- tile_size: choose a starting tile; original node defaults to 512. 0 = auto (falls back 512 → 256 → 128 on OOM).
|
||||
- channels_last: try ON for a speedup on some systems.
|
||||
- precision: lower (fp16/bf16) can be faster; may impact quality depending on the model.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"upscale_model": (
|
||||
"UPSCALE_MODEL",
|
||||
{"tooltip": "Pick your ESRGAN model (e.g. 2× / 4×)."},
|
||||
),
|
||||
"image": (
|
||||
"IMAGE",
|
||||
{
|
||||
"tooltip": "Images to upscale. Accepts a batch: frames×H×W×C with values in [0–1]."
|
||||
},
|
||||
),
|
||||
},
|
||||
"optional": {
|
||||
"max_batch_size": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 4096,
|
||||
"step": 1,
|
||||
"tooltip": "How many images to process at once. 0 = all at once. Set >0 if you hit OOM.",
|
||||
},
|
||||
),
|
||||
"tile_size": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 2048,
|
||||
"step": 32,
|
||||
"tooltip": "How big each tile is. 0 = auto (starts at 512 and halves on OOM). Bigger is faster; smaller is safer.",
|
||||
},
|
||||
),
|
||||
"channels_last": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": False,
|
||||
"tooltip": "Try this ON for a small speed boost on some GPUs. If you see no gain, leave it OFF.",
|
||||
},
|
||||
),
|
||||
"precision": (
|
||||
["fp32", "fp16", "bf16"],
|
||||
{
|
||||
"default": "fp32",
|
||||
"tooltip": "Math mode. fp32 = safest. fp16/bf16 can be faster on many GPUs, may impact image quality.",
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "upscale"
|
||||
CATEGORY = "image/upscaling"
|
||||
|
||||
def upscale(
|
||||
self,
|
||||
upscale_model,
|
||||
image,
|
||||
max_batch_size=0,
|
||||
tile_size=0,
|
||||
channels_last=False,
|
||||
precision="fp32",
|
||||
):
|
||||
def spans(n, cap):
|
||||
if cap <= 0 or cap >= n:
|
||||
return [(0, n)]
|
||||
out = []
|
||||
i = 0
|
||||
while i < n:
|
||||
j = min(n, i + cap)
|
||||
out.append((i, j))
|
||||
i = j
|
||||
return out
|
||||
|
||||
device = model_management.get_torch_device()
|
||||
|
||||
upscale_model.to(device)
|
||||
for p in upscale_model.model.parameters():
|
||||
if p.device != device:
|
||||
p.data = p.data.to(device)
|
||||
if p._grad is not None:
|
||||
p._grad.data = p._grad.data.to(device)
|
||||
|
||||
upscale_model.model.eval()
|
||||
|
||||
scale = float(getattr(upscale_model, "scale", 4.0))
|
||||
memory_required = model_management.module_size(upscale_model.model)
|
||||
memory_required += (
|
||||
(512 * 512 * 3) * image.element_size() * max(scale, 1.0) * 384.0
|
||||
)
|
||||
memory_required += image.nelement() * image.element_size()
|
||||
model_management.free_memory(memory_required, device)
|
||||
|
||||
B, H, W, C = image.shape
|
||||
out_chunks = []
|
||||
|
||||
for s, e in spans(B, int(max_batch_size)):
|
||||
sub = image[s:e].movedim(-1, -3).to(device, non_blocking=True)
|
||||
|
||||
if channels_last and device.type == "cuda":
|
||||
sub = sub.to(memory_format=torch.channels_last)
|
||||
|
||||
tile = 512 if tile_size in (0, None) else int(tile_size)
|
||||
overlap = 32
|
||||
|
||||
oom = True
|
||||
while oom:
|
||||
try:
|
||||
steps = sub.shape[0] * comfy_utils.get_tiled_scale_steps(
|
||||
sub.shape[3],
|
||||
sub.shape[2],
|
||||
tile_x=tile,
|
||||
tile_y=tile,
|
||||
overlap=overlap,
|
||||
)
|
||||
pbar = comfy_utils.ProgressBar(steps)
|
||||
|
||||
if device.type == "cuda" and precision in ("fp16", "bf16"):
|
||||
amp_dtype = (
|
||||
torch.float16 if precision == "fp16" else torch.bfloat16
|
||||
)
|
||||
with torch.autocast(
|
||||
device_type="cuda", dtype=amp_dtype
|
||||
), torch.inference_mode():
|
||||
sr = comfy_utils.tiled_scale(
|
||||
sub,
|
||||
lambda a: upscale_model(a),
|
||||
tile_x=tile,
|
||||
tile_y=tile,
|
||||
overlap=overlap,
|
||||
upscale_amount=scale,
|
||||
pbar=pbar,
|
||||
)
|
||||
|
||||
else:
|
||||
with torch.inference_mode():
|
||||
sr = comfy_utils.tiled_scale(
|
||||
sub,
|
||||
lambda a: upscale_model(a),
|
||||
tile_x=tile,
|
||||
tile_y=tile,
|
||||
overlap=overlap,
|
||||
upscale_amount=scale,
|
||||
pbar=pbar,
|
||||
)
|
||||
|
||||
oom = False
|
||||
except model_management.OOM_EXCEPTION as e:
|
||||
tile //= 2
|
||||
if tile < 128:
|
||||
raise e
|
||||
|
||||
out_chunks.append(
|
||||
torch.clamp(sr.movedim(-3, -1), 0.0, 1.0).to("cpu", non_blocking=True)
|
||||
)
|
||||
|
||||
upscale_model.to("cpu")
|
||||
return (torch.cat(out_chunks, dim=0),)
|
||||
|
||||
|
||||
def _chunk_spans(n: int, max_bs: int) -> List[Tuple[int, int]]:
|
||||
if max_bs <= 0 or max_bs >= n:
|
||||
return [(0, n)]
|
||||
s, spans = 0, []
|
||||
while s < n:
|
||||
e = min(n, s + max_bs)
|
||||
spans.append((s, e))
|
||||
s = e
|
||||
return spans
|
||||
|
||||
|
||||
def _floor_mul(x: int, k: int) -> int:
|
||||
if k <= 1:
|
||||
return max(1, x)
|
||||
return x - (x % k)
|
||||
|
||||
|
||||
def _ceil_mul(x: int, k: int) -> int:
|
||||
if k <= 1:
|
||||
return max(1, x)
|
||||
r = x % k
|
||||
return x if r == 0 else x + (k - r)
|
||||
|
||||
|
||||
def _fit_keep_aspect(sw: int, sh: int, tw: int, th: int) -> Tuple[int, int]:
|
||||
if tw <= 0 and th <= 0:
|
||||
return sw, sh
|
||||
if tw <= 0:
|
||||
r = th / sh
|
||||
elif th <= 0:
|
||||
r = tw / sw
|
||||
else:
|
||||
r = min(tw / sw, th / sh)
|
||||
return max(1, int(round(sw * r))), max(1, int(round(sh * r)))
|
||||
|
||||
|
||||
def _fit_keep_ar_divisible(
|
||||
sw: int, sh: int, tw: int, th: int, d: int
|
||||
) -> Tuple[int, int]:
|
||||
if d <= 1:
|
||||
return _fit_keep_aspect(sw, sh, tw, th)
|
||||
fw, fh = _fit_keep_aspect(sw, sh, tw, th)
|
||||
g = math.gcd(sw, sh)
|
||||
base_w = d * (sw // g)
|
||||
base_h = d * (sh // g)
|
||||
k = min(fw // base_w, fh // base_h)
|
||||
if k >= 1:
|
||||
return base_w * k, base_h * k
|
||||
return max(d, _floor_mul(fw, d)), max(d, _floor_mul(fh, d))
|
||||
|
||||
|
||||
def _scale_then_crop_divisible(
|
||||
sw: int, sh: int, req_w: int, req_h: int, d: int
|
||||
) -> Tuple[int, int, int, int]:
|
||||
"""
|
||||
AR Scale + Divisible Crop:
|
||||
1) Scale once (keep AR), locking the SOURCE long side to floor(requested_long/d)*d (>0).
|
||||
2) Crop ONLY the short side to the largest multiple of d that is ≤ scaled short side and ≤ requested short side (>0).
|
||||
"""
|
||||
d = max(1, int(d))
|
||||
req_w = max(1, int(req_w))
|
||||
req_h = max(1, int(req_h))
|
||||
req_w_div = _floor_mul(req_w, d)
|
||||
req_h_div = _floor_mul(req_h, d)
|
||||
|
||||
src_long_is_h = sh >= sw
|
||||
|
||||
if src_long_is_h:
|
||||
if req_h_div == 0:
|
||||
raise ValueError(
|
||||
f"AR Scale + Divisible Crop: requested height {req_h}px < divisible_by {d}."
|
||||
)
|
||||
scale = req_h_div / sh
|
||||
rh = req_h_div
|
||||
rw = max(1, int(round(sw * scale)))
|
||||
if rw < d:
|
||||
raise ValueError(
|
||||
f"AR Scale + Divisible Crop: scaled width {rw}px < divisible_by {d}."
|
||||
)
|
||||
if req_w_div == 0:
|
||||
raise ValueError(
|
||||
f"AR Scale + Divisible Crop: requested width {req_w}px < divisible_by {d}."
|
||||
)
|
||||
out_w = min(req_w_div, _floor_mul(rw, d))
|
||||
out_h = rh
|
||||
else:
|
||||
if req_w_div == 0:
|
||||
raise ValueError(
|
||||
f"AR Scale + Divisible Crop: requested width {req_w}px < divisible_by {d}."
|
||||
)
|
||||
scale = req_w_div / sw
|
||||
rw = req_w_div
|
||||
rh = max(1, int(round(sh * scale)))
|
||||
if rh < d:
|
||||
raise ValueError(
|
||||
f"AR Scale + Divisible Crop: scaled height {rh}px < divisible_by {d}."
|
||||
)
|
||||
if req_h_div == 0:
|
||||
raise ValueError(
|
||||
f"AR Scale + Divisible Crop: requested height {req_h}px < divisible_by {d}."
|
||||
)
|
||||
out_h = min(req_h_div, _floor_mul(rh, d))
|
||||
out_w = rw
|
||||
|
||||
if (rw % d == 0) and (rh % d == 0):
|
||||
return rw, rh, rw, rh
|
||||
|
||||
return rw, rh, out_w, out_h
|
||||
|
||||
|
||||
def _cover_keep_aspect(sw: int, sh: int, tw: int, th: int) -> Tuple[int, int]:
|
||||
r = max(tw / sw, th / sh)
|
||||
return max(1, int((sw * r) + 0.999999)), max(1, int((sh * r) + 0.999999))
|
||||
|
||||
|
||||
def _pad_sides(pos: str, pad_w: int, pad_h: int) -> Tuple[int, int, int, int]:
|
||||
lw = pad_w // 2
|
||||
rw = pad_w - lw
|
||||
th = pad_h // 2
|
||||
bh = pad_h - th
|
||||
if pos in ("top-left", "top", "top-right"):
|
||||
th, bh = 0, pad_h
|
||||
if pos in ("bottom-left", "bottom", "bottom-right"):
|
||||
th, bh = pad_h, 0
|
||||
if pos in ("top-left", "left", "bottom-left"):
|
||||
lw, rw = 0, pad_w
|
||||
if pos in ("top-right", "right", "bottom-right"):
|
||||
lw, rw = pad_w, 0
|
||||
return lw, rw, th, bh
|
||||
|
||||
|
||||
def _crop_offsets(
|
||||
pos: str, in_w: int, in_h: int, out_w: int, out_h: int
|
||||
) -> Tuple[int, int]:
|
||||
dx = max(0, in_w - out_w)
|
||||
dy = max(0, in_h - out_h)
|
||||
mapx = {
|
||||
"top-left": "left",
|
||||
"left": "left",
|
||||
"bottom-left": "left",
|
||||
"top": "center",
|
||||
"center": "center",
|
||||
"bottom": "center",
|
||||
"top-right": "right",
|
||||
"right": "right",
|
||||
"bottom-right": "right",
|
||||
}
|
||||
mapy = {
|
||||
"top-left": "top",
|
||||
"top": "top",
|
||||
"top-right": "top",
|
||||
"left": "center",
|
||||
"center": "center",
|
||||
"right": "center",
|
||||
"bottom-left": "bottom",
|
||||
"bottom": "bottom",
|
||||
"bottom-right": "bottom",
|
||||
}
|
||||
lx = {"left": 0, "center": dx // 2, "right": dx}.get(
|
||||
mapx.get(pos, "center"), dx // 2
|
||||
)
|
||||
ly = {"top": 0, "center": dy // 2, "bottom": dy}.get(
|
||||
mapy.get(pos, "center"), dy // 2
|
||||
)
|
||||
return lx, ly
|
||||
|
||||
|
||||
def _parse_pad_color(
|
||||
s: str, c: int, device: torch.device, dtype: torch.dtype
|
||||
) -> torch.Tensor:
|
||||
s = (s or "").strip()
|
||||
if not s:
|
||||
return torch.zeros(c, device=device, dtype=dtype)
|
||||
try:
|
||||
parts = [int(p.strip()) for p in s.split(",")]
|
||||
except Exception:
|
||||
parts = [0, 0, 0]
|
||||
rgb = [int(max(0, min(255, v))) for v in (parts + [0, 0, 0])[:3]]
|
||||
v = torch.tensor(
|
||||
[rgb[0] / 255.0, rgb[1] / 255.0, rgb[2] / 255.0], device=device, dtype=dtype
|
||||
)
|
||||
if c == 1:
|
||||
return v[:1]
|
||||
if c == 4:
|
||||
return torch.cat([v, torch.ones(1, device=device, dtype=dtype)])
|
||||
return v
|
||||
|
||||
|
||||
def _nearest_interp(x: torch.Tensor, size: Tuple[int, int]) -> torch.Tensor:
|
||||
try:
|
||||
return F.interpolate(x, size=size, mode="nearest-exact")
|
||||
except Exception:
|
||||
return F.interpolate(x, size=size, mode="nearest")
|
||||
|
||||
|
||||
def _divisible_box(w: int, h: int, d: int) -> Tuple[int, int]:
|
||||
if d <= 1:
|
||||
return int(w), int(h)
|
||||
return _floor_mul(int(w), d), _floor_mul(int(h), d)
|
||||
|
||||
|
||||
def _normalize_mode(mode: str) -> str:
|
||||
key = (mode or "").strip().lower()
|
||||
table = {
|
||||
"keep ar": "keep_ar",
|
||||
"stretch": "stretch",
|
||||
"crop (cover + crop)": "crop",
|
||||
"pad (fit + pad)": "pad",
|
||||
"ar scale + divisible crop": "ar_scale_crop_divisible",
|
||||
}
|
||||
if key not in table:
|
||||
raise ValueError(
|
||||
"Unknown resize_mode. Use one of: "
|
||||
"'Keep AR', 'Stretch', 'Crop (Cover + Crop)', 'Pad (Fit + Pad)', 'AR Scale + Divisible Crop'."
|
||||
)
|
||||
return table[key]
|
||||
|
||||
|
||||
class BatchResizeWithLanczos:
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"image": (
|
||||
"IMAGE",
|
||||
{
|
||||
"tooltip": "Input batch (B,H,W,C) in [0,1] float.\nProcessed on GPU."
|
||||
},
|
||||
),
|
||||
"width": (
|
||||
"INT",
|
||||
{
|
||||
"default": 1024,
|
||||
"min": 1,
|
||||
"max": 16384,
|
||||
"step": 1,
|
||||
"tooltip": "Target width (pixels).\n\n"
|
||||
"Notes:\n"
|
||||
"• Keep AR / Pad: maximum width for the fit\n"
|
||||
"• Crop: final output width\n"
|
||||
"• AR Scale + Divisible Crop: requested width before divisibility",
|
||||
},
|
||||
),
|
||||
"height": (
|
||||
"INT",
|
||||
{
|
||||
"default": 576,
|
||||
"min": 1,
|
||||
"max": 16384,
|
||||
"step": 1,
|
||||
"tooltip": "Target height (pixels).\n\n"
|
||||
"Notes:\n"
|
||||
"• Keep AR / Pad: maximum height for the fit\n"
|
||||
"• Crop: final output height\n"
|
||||
"• AR Scale + Divisible Crop: requested height before divisibility",
|
||||
},
|
||||
),
|
||||
"resize_mode": (
|
||||
[
|
||||
"Keep AR",
|
||||
"Stretch",
|
||||
"Crop (Cover + Crop)",
|
||||
"Pad (Fit + Pad)",
|
||||
"AR Scale + Divisible Crop",
|
||||
],
|
||||
{
|
||||
"default": "Keep AR",
|
||||
"tooltip": "Modes:\n"
|
||||
"- Keep AR: Fit inside width×height (preserve aspect)\n"
|
||||
"- Stretch: Force to width×height (may distort)\n"
|
||||
"- Crop (Cover + Crop): Scale to cover, then crop to width×height\n"
|
||||
"- Pad (Fit + Pad): Fit inside, then pad to width×height\n"
|
||||
"- AR Scale + Divisible Crop: Scale by SOURCE long side to ≤ requested divisible; crop ONLY the short side to its divisible",
|
||||
},
|
||||
),
|
||||
"divisible_by": (
|
||||
"INT",
|
||||
{
|
||||
"default": 1,
|
||||
"min": 1,
|
||||
"max": 4096,
|
||||
"step": 1,
|
||||
"tooltip": "Force output dimensions to multiples of N.\n\n"
|
||||
"Details:\n"
|
||||
"• Keep AR: Fit → then step down to the largest size ≤ requested that keeps AR AND makes both sides divisible\n"
|
||||
"• AR Scale + Divisible Crop: Lock the scaled LONG side to its divisible target; crop ONLY the short side to its divisible\n"
|
||||
"Set to 1 (or 0 in UI) to disable",
|
||||
},
|
||||
),
|
||||
"max_batch_size": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 4096,
|
||||
"step": 1,
|
||||
"tooltip": "0 = process whole batch\n>0 = chunk the batch to this size",
|
||||
},
|
||||
),
|
||||
"sinc_window": (
|
||||
"INT",
|
||||
{
|
||||
"default": 3,
|
||||
"min": 1,
|
||||
"max": 8,
|
||||
"step": 1,
|
||||
"tooltip": "Lanczos window size (a). Higher = sharper (more ringing).",
|
||||
},
|
||||
),
|
||||
"pad_color": (
|
||||
"STRING",
|
||||
{
|
||||
"default": "0, 0, 0",
|
||||
"tooltip": "Pad mode only. RGB as 'r, g, b' (0-255).",
|
||||
},
|
||||
),
|
||||
"crop_position": (
|
||||
[
|
||||
"center",
|
||||
"top-left",
|
||||
"top",
|
||||
"top-right",
|
||||
"left",
|
||||
"right",
|
||||
"bottom-left",
|
||||
"bottom",
|
||||
"bottom-right",
|
||||
],
|
||||
{
|
||||
"default": "center",
|
||||
"tooltip": "Where to crop/pad from.\nChoose which edges are preserved for cropping, or where padding is added.",
|
||||
},
|
||||
),
|
||||
"precision": (
|
||||
["fp32", "fp16", "bf16"],
|
||||
{"default": "fp32", "tooltip": "Resampling compute dtype."},
|
||||
),
|
||||
},
|
||||
"optional": {
|
||||
"mask": (
|
||||
"MASK",
|
||||
{
|
||||
"tooltip": "Optional mask (B,H,W) in [0,1].\nResized with nearest.\nFollows the same crop/pad as the image."
|
||||
},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "INT", "INT", "MASK")
|
||||
RETURN_NAMES = ("IMAGE", "width", "height", "mask")
|
||||
FUNCTION = "process"
|
||||
CATEGORY = "image/resize"
|
||||
DESCRIPTION = (
|
||||
"CUDA-accelerated, gamma-correct Lanczos resizer (TorchLanc).\n\n"
|
||||
"Modes:\n"
|
||||
"• Keep AR\n"
|
||||
"• Stretch\n"
|
||||
"• Crop (Cover + Crop)\n"
|
||||
"• Pad (Fit + Pad)\n"
|
||||
"• AR Scale + Divisible Crop\n\n"
|
||||
"Node functionality based on Resize nodes by Kijai\n\n"
|
||||
"More from me!: https://artificialsweetener.ai"
|
||||
)
|
||||
|
||||
def process(
|
||||
self,
|
||||
image: torch.Tensor,
|
||||
width: int,
|
||||
height: int,
|
||||
resize_mode: str,
|
||||
divisible_by: int,
|
||||
max_batch_size: int,
|
||||
sinc_window: int,
|
||||
pad_color: str,
|
||||
crop_position: str,
|
||||
precision: str,
|
||||
mask: Optional[torch.Tensor] = None,
|
||||
):
|
||||
if image is None or not isinstance(image, torch.Tensor):
|
||||
raise ValueError(
|
||||
"image must be a torch.Tensor of shape (B,H,W,C) in [0,1]."
|
||||
)
|
||||
|
||||
B, H, W, C = image.shape
|
||||
if C not in (1, 3, 4):
|
||||
raise ValueError(f"Unsupported channel count C={C}. Expected 1, 3 or 4.")
|
||||
|
||||
d = int(divisible_by) if int(divisible_by) > 1 else 1
|
||||
mode = _normalize_mode(resize_mode)
|
||||
|
||||
device = torch.device("cuda")
|
||||
image = image.float().clamp_(0, 1)
|
||||
|
||||
if mode == "stretch":
|
||||
tw, th = _divisible_box(width, height, d)
|
||||
rw, rh = tw, th
|
||||
out_w, out_h = tw, th
|
||||
|
||||
elif mode == "keep_ar":
|
||||
rw, rh = _fit_keep_ar_divisible(W, H, int(width), int(height), d)
|
||||
out_w, out_h = rw, rh
|
||||
|
||||
elif mode == "ar_scale_crop_divisible":
|
||||
if width <= 0 or height <= 0:
|
||||
raise ValueError(
|
||||
"AR Scale + Divisible Crop requires non-zero width and height."
|
||||
)
|
||||
rw, rh, out_w, out_h = _scale_then_crop_divisible(
|
||||
W, H, int(width), int(height), d
|
||||
)
|
||||
|
||||
elif mode == "crop":
|
||||
if width <= 0 or height <= 0:
|
||||
raise ValueError("Crop requires non-zero width and height.")
|
||||
tw, th = _divisible_box(width, height, d)
|
||||
rw, rh = _cover_keep_aspect(W, H, tw, th)
|
||||
out_w, out_h = tw, th
|
||||
|
||||
elif mode == "pad":
|
||||
if width <= 0 or height <= 0:
|
||||
raise ValueError("Pad requires non-zero width and height.")
|
||||
tw, th = _divisible_box(width, height, d)
|
||||
rw, rh = _fit_keep_aspect(W, H, tw, th)
|
||||
out_w, out_h = tw, th
|
||||
|
||||
else:
|
||||
raise ValueError(f"Unknown resize_mode: {resize_mode}")
|
||||
|
||||
out_imgs: List[torch.Tensor] = []
|
||||
out_masks: List[torch.Tensor] = []
|
||||
|
||||
crop_like = mode in ("crop", "ar_scale_crop_divisible")
|
||||
pad_like = mode == "pad"
|
||||
resize_to = (rh, rw) if (crop_like or pad_like) else (out_h, out_w)
|
||||
|
||||
pbar = comfy_utils.ProgressBar(B)
|
||||
|
||||
for s, e in _chunk_spans(B, int(max_batch_size)):
|
||||
x = image[s:e].movedim(-1, 1).to(device, non_blocking=True)
|
||||
|
||||
y = lanczos_resize(
|
||||
x,
|
||||
height=resize_to[0],
|
||||
width=resize_to[1],
|
||||
a=int(sinc_window),
|
||||
precision=str(precision),
|
||||
clamp=True,
|
||||
chunk_size=0,
|
||||
)
|
||||
|
||||
ox = oy = 0
|
||||
left = right = top = bottom = 0
|
||||
|
||||
if crop_like:
|
||||
ox, oy = _crop_offsets(crop_position, rw, rh, out_w, out_h)
|
||||
y = y[:, :, oy : oy + out_h, ox : ox + out_w]
|
||||
elif pad_like:
|
||||
pad_w = max(0, out_w - rw)
|
||||
pad_h = max(0, out_h - rh)
|
||||
left, right, top, bottom = _pad_sides(crop_position, pad_w, pad_h)
|
||||
|
||||
if d > 1:
|
||||
base_w = rw + left + right
|
||||
base_h = rh + top + bottom
|
||||
right += _ceil_mul(base_w, d) - base_w
|
||||
bottom += _ceil_mul(base_h, d) - base_h
|
||||
out_w = rw + left + right
|
||||
out_h = rh + top + bottom
|
||||
|
||||
color = _parse_pad_color(pad_color, C, y.device, y.dtype).view(
|
||||
1, C, 1, 1
|
||||
)
|
||||
canvas = color.expand(y.shape[0], -1, out_h, out_w).clone()
|
||||
canvas[:, :, top : top + rh, left : left + rw] = y
|
||||
y = canvas
|
||||
|
||||
out_imgs.append(y.to("cpu", non_blocking=False).movedim(1, -1))
|
||||
|
||||
if isinstance(mask, torch.Tensor):
|
||||
m = mask[s:e].unsqueeze(1).to(device, non_blocking=True)
|
||||
m_res = _nearest_interp(m, size=resize_to)
|
||||
if crop_like:
|
||||
m_res = m_res[:, :, oy : oy + out_h, ox : ox + out_w]
|
||||
elif pad_like:
|
||||
base = torch.zeros(
|
||||
(m_res.shape[0], 1, out_h, out_w),
|
||||
device=m_res.device,
|
||||
dtype=m_res.dtype,
|
||||
)
|
||||
base[:, :, top : top + rh, left : left + rw] = m_res
|
||||
m_res = base
|
||||
out_masks.append(m_res.squeeze(1).to("cpu", non_blocking=False))
|
||||
|
||||
pbar.update(e - s)
|
||||
|
||||
images_out = torch.cat(out_imgs, dim=0)
|
||||
mask_out = (
|
||||
torch.cat(out_masks, dim=0)
|
||||
if out_masks
|
||||
else torch.zeros((B, out_h, out_w), dtype=torch.float32)
|
||||
)
|
||||
|
||||
return images_out, out_w, out_h, mask_out
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {"BatchResizeWithLanczos": BatchResizeWithLanczos}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {"BatchResizeWithLanczos": "Batch Resize with Lanczos"}
|
||||
5
custom_nodes/whiterabbit/vendor/config.yaml
vendored
Normal file
5
custom_nodes/whiterabbit/vendor/config.yaml
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
# Copyright (c) 2023–2025 Fannovel16 and contributors
|
||||
# See LICENSES/MIT-ComfyUI-Frame-Interpolation.txt for the full text.
|
||||
#Plz don't delete this file, just edit it when neccessary.
|
||||
ckpts_path: "./ckpts"
|
||||
ops_backend: "cupy" #Either "taichi" or "cupy"
|
||||
140
custom_nodes/whiterabbit/vendor/rife/__init__.py
vendored
Normal file
140
custom_nodes/whiterabbit/vendor/rife/__init__.py
vendored
Normal file
@@ -0,0 +1,140 @@
|
||||
# Copyright (c) 2023–2025 Fannovel16 and contributors
|
||||
# See LICENSES/MIT-ComfyUI-Frame-Interpolation.txt for the full text.
|
||||
import torch
|
||||
from torch.utils.data import DataLoader
|
||||
import pathlib
|
||||
from vfi_utils import (
|
||||
load_file_from_github_release,
|
||||
preprocess_frames,
|
||||
postprocess_frames,
|
||||
generic_frame_loop,
|
||||
InterpolationStateList,
|
||||
)
|
||||
import typing
|
||||
from comfy.model_management import get_torch_device
|
||||
import re
|
||||
from functools import cmp_to_key
|
||||
from packaging import version
|
||||
|
||||
MODEL_TYPE = pathlib.Path(__file__).parent.name
|
||||
CKPT_NAME_VER_DICT = {
|
||||
"rife40.pth": "4.0",
|
||||
"rife41.pth": "4.0",
|
||||
"rife42.pth": "4.2",
|
||||
"rife43.pth": "4.3",
|
||||
"rife44.pth": "4.3",
|
||||
"rife45.pth": "4.5",
|
||||
"rife46.pth": "4.6",
|
||||
"rife47.pth": "4.7",
|
||||
"rife48.pth": "4.7",
|
||||
"rife49.pth": "4.7",
|
||||
"sudo_rife4_269.662_testV1_scale1.pth": "4.0",
|
||||
# Arch 4.10 doesn't work due to state dict mismatch
|
||||
# TODO: Investigating and fix it
|
||||
# "rife410.pth": "4.10",
|
||||
# "rife411.pth": "4.10",
|
||||
# "rife412.pth": "4.10"
|
||||
}
|
||||
|
||||
|
||||
class RIFE_VFI:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"ckpt_name": (
|
||||
sorted(
|
||||
list(CKPT_NAME_VER_DICT.keys()),
|
||||
key=lambda ckpt_name: version.parse(
|
||||
CKPT_NAME_VER_DICT[ckpt_name]
|
||||
),
|
||||
),
|
||||
{"default": "rife47.pth"},
|
||||
),
|
||||
"frames": ("IMAGE",),
|
||||
"clear_cache_after_n_frames": (
|
||||
"INT",
|
||||
{"default": 10, "min": 1, "max": 1000},
|
||||
),
|
||||
"multiplier": ("INT", {"default": 2, "min": 1}),
|
||||
"fast_mode": ("BOOLEAN", {"default": True}),
|
||||
"ensemble": ("BOOLEAN", {"default": True}),
|
||||
"scale_factor": ([0.25, 0.5, 1.0, 2.0, 4.0], {"default": 1.0}),
|
||||
},
|
||||
"optional": {"optional_interpolation_states": ("INTERPOLATION_STATES",)},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
FUNCTION = "vfi"
|
||||
CATEGORY = "ComfyUI-Frame-Interpolation/VFI"
|
||||
|
||||
def vfi(
|
||||
self,
|
||||
ckpt_name: typing.AnyStr,
|
||||
frames: torch.Tensor,
|
||||
clear_cache_after_n_frames=10,
|
||||
multiplier: typing.SupportsInt = 2,
|
||||
fast_mode=False,
|
||||
ensemble=False,
|
||||
scale_factor=1.0,
|
||||
optional_interpolation_states: InterpolationStateList = None,
|
||||
**kwargs
|
||||
):
|
||||
"""
|
||||
Perform video frame interpolation using a given checkpoint model.
|
||||
|
||||
Args:
|
||||
ckpt_name (str): The name of the checkpoint model to use.
|
||||
frames (torch.Tensor): A tensor containing input video frames.
|
||||
clear_cache_after_n_frames (int, optional): The number of frames to process before clearing CUDA cache
|
||||
to prevent memory overflow. Defaults to 10. Lower numbers are safer but mean more processing time.
|
||||
How high you should set it depends on how many input frames there are, input resolution (after upscaling),
|
||||
how many times you want to multiply them, and how long you're willing to wait for the process to complete.
|
||||
multiplier (int, optional): The multiplier for each input frame. 60 input frames * 2 = 120 output frames. Defaults to 2.
|
||||
|
||||
Returns:
|
||||
tuple: A tuple containing the output interpolated frames.
|
||||
|
||||
Note:
|
||||
This method interpolates frames in a video sequence using a specified checkpoint model.
|
||||
It processes each frame sequentially, generating interpolated frames between them.
|
||||
|
||||
To prevent memory overflow, it clears the CUDA cache after processing a specified number of frames.
|
||||
"""
|
||||
from .rife_arch import IFNet
|
||||
|
||||
model_path = load_file_from_github_release(MODEL_TYPE, ckpt_name)
|
||||
arch_ver = CKPT_NAME_VER_DICT[ckpt_name]
|
||||
interpolation_model = IFNet(arch_ver=arch_ver)
|
||||
interpolation_model.load_state_dict(torch.load(model_path))
|
||||
interpolation_model.eval().to(get_torch_device())
|
||||
frames = preprocess_frames(frames)
|
||||
|
||||
def return_middle_frame(
|
||||
frame_0, frame_1, timestep, model, scale_list, in_fast_mode, in_ensemble
|
||||
):
|
||||
return model(
|
||||
frame_0, frame_1, timestep, scale_list, in_fast_mode, in_ensemble
|
||||
)
|
||||
|
||||
scale_list = [
|
||||
8 / scale_factor,
|
||||
4 / scale_factor,
|
||||
2 / scale_factor,
|
||||
1 / scale_factor,
|
||||
]
|
||||
|
||||
args = [interpolation_model, scale_list, fast_mode, ensemble]
|
||||
out = postprocess_frames(
|
||||
generic_frame_loop(
|
||||
type(self).__name__,
|
||||
frames,
|
||||
clear_cache_after_n_frames,
|
||||
multiplier,
|
||||
return_middle_frame,
|
||||
*args,
|
||||
interpolation_states=optional_interpolation_states,
|
||||
dtype=torch.float32
|
||||
)
|
||||
)
|
||||
return (out,)
|
||||
588
custom_nodes/whiterabbit/vendor/rife/rife_arch.py
vendored
Normal file
588
custom_nodes/whiterabbit/vendor/rife/rife_arch.py
vendored
Normal file
@@ -0,0 +1,588 @@
|
||||
# Copyright (c) 2023–2025 Fannovel16 and contributors
|
||||
# See LICENSES/MIT-ComfyUI-Frame-Interpolation.txt for the full text.
|
||||
"""
|
||||
26-Dez-21
|
||||
https://github.com/hzwer/Practical-RIFE
|
||||
https://github.com/hzwer/Practical-RIFE/blob/main/model/warplayer.py
|
||||
https://github.com/HolyWu/vs-rife/blob/master/vsrife/__init__.py
|
||||
"""
|
||||
from torch.nn.parallel import DistributedDataParallel as DDP
|
||||
from torch.optim import AdamW
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import torch.nn as nn
|
||||
import torch.optim as optim
|
||||
import warnings
|
||||
from comfy.model_management import get_torch_device
|
||||
|
||||
device = get_torch_device()
|
||||
backwarp_tenGrid = {}
|
||||
|
||||
|
||||
class ResConv(nn.Module):
|
||||
def __init__(self, c, dilation=1):
|
||||
super(ResConv, self).__init__()
|
||||
self.conv = nn.Conv2d(c, c, 3, 1, dilation, dilation=dilation, groups=1)
|
||||
self.beta = nn.Parameter(torch.ones((1, c, 1, 1)), requires_grad=True)
|
||||
self.relu = nn.LeakyReLU(0.2, True)
|
||||
|
||||
def forward(self, x):
|
||||
return self.relu(self.conv(x) * self.beta + x)
|
||||
|
||||
|
||||
def warp(tenInput, tenFlow):
|
||||
k = (str(tenFlow.device), str(tenFlow.size()))
|
||||
if k not in backwarp_tenGrid:
|
||||
tenHorizontal = (
|
||||
torch.linspace(-1.0, 1.0, tenFlow.shape[3], device=device)
|
||||
.view(1, 1, 1, tenFlow.shape[3])
|
||||
.expand(tenFlow.shape[0], -1, tenFlow.shape[2], -1)
|
||||
)
|
||||
tenVertical = (
|
||||
torch.linspace(-1.0, 1.0, tenFlow.shape[2], device=device)
|
||||
.view(1, 1, tenFlow.shape[2], 1)
|
||||
.expand(tenFlow.shape[0], -1, -1, tenFlow.shape[3])
|
||||
)
|
||||
backwarp_tenGrid[k] = torch.cat([tenHorizontal, tenVertical], 1).to(device)
|
||||
|
||||
tenFlow = torch.cat(
|
||||
[
|
||||
tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0),
|
||||
tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0),
|
||||
],
|
||||
1,
|
||||
)
|
||||
|
||||
g = (backwarp_tenGrid[k] + tenFlow).permute(0, 2, 3, 1)
|
||||
|
||||
if tenInput.type() == "torch.cuda.HalfTensor":
|
||||
g = g.half()
|
||||
|
||||
padding_mode = "border"
|
||||
if device.type == "mps":
|
||||
# https://github.com/pytorch/pytorch/issues/125098
|
||||
padding_mode = "zeros"
|
||||
g = g.clamp(-1, 1)
|
||||
return torch.nn.functional.grid_sample(
|
||||
input=tenInput,
|
||||
grid=g,
|
||||
mode="bilinear",
|
||||
padding_mode=padding_mode,
|
||||
align_corners=True,
|
||||
)
|
||||
|
||||
|
||||
def conv(
|
||||
in_planes,
|
||||
out_planes,
|
||||
kernel_size=3,
|
||||
stride=1,
|
||||
padding=1,
|
||||
dilation=1,
|
||||
arch_ver="4.0",
|
||||
):
|
||||
if arch_ver == "4.0":
|
||||
return nn.Sequential(
|
||||
nn.Conv2d(
|
||||
in_planes,
|
||||
out_planes,
|
||||
kernel_size=kernel_size,
|
||||
stride=stride,
|
||||
padding=padding,
|
||||
dilation=dilation,
|
||||
bias=True,
|
||||
),
|
||||
nn.PReLU(out_planes),
|
||||
)
|
||||
if arch_ver in ["4.2", "4.3", "4.5", "4.6", "4.7", "4.10"]:
|
||||
return nn.Sequential(
|
||||
nn.Conv2d(
|
||||
in_planes,
|
||||
out_planes,
|
||||
kernel_size=kernel_size,
|
||||
stride=stride,
|
||||
padding=padding,
|
||||
dilation=dilation,
|
||||
bias=True,
|
||||
),
|
||||
nn.LeakyReLU(0.2, True),
|
||||
)
|
||||
|
||||
|
||||
def conv_woact(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
|
||||
return nn.Sequential(
|
||||
nn.Conv2d(
|
||||
in_planes,
|
||||
out_planes,
|
||||
kernel_size=kernel_size,
|
||||
stride=stride,
|
||||
padding=padding,
|
||||
dilation=dilation,
|
||||
bias=True,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def conv_woact(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
|
||||
return nn.Sequential(
|
||||
nn.Conv2d(
|
||||
in_planes,
|
||||
out_planes,
|
||||
kernel_size=kernel_size,
|
||||
stride=stride,
|
||||
padding=padding,
|
||||
dilation=dilation,
|
||||
bias=True,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def deconv(in_planes, out_planes, kernel_size=4, stride=2, padding=1, arch_ver="4.0"):
|
||||
if arch_ver == "4.0":
|
||||
return nn.Sequential(
|
||||
torch.nn.ConvTranspose2d(
|
||||
in_channels=in_planes,
|
||||
out_channels=out_planes,
|
||||
kernel_size=4,
|
||||
stride=2,
|
||||
padding=1,
|
||||
bias=True,
|
||||
),
|
||||
nn.PReLU(out_planes),
|
||||
)
|
||||
if arch_ver in ["4.2", "4.3", "4.5", "4.6", "4.7", "4.10"]:
|
||||
return nn.Sequential(
|
||||
torch.nn.ConvTranspose2d(
|
||||
in_channels=in_planes,
|
||||
out_channels=out_planes,
|
||||
kernel_size=4,
|
||||
stride=2,
|
||||
padding=1,
|
||||
bias=True,
|
||||
),
|
||||
nn.LeakyReLU(0.2, True),
|
||||
)
|
||||
|
||||
|
||||
class Conv2(nn.Module):
|
||||
def __init__(self, in_planes, out_planes, stride=2, arch_ver="4.0"):
|
||||
super(Conv2, self).__init__()
|
||||
self.conv1 = conv(in_planes, out_planes, 3, stride, 1, arch_ver=arch_ver)
|
||||
self.conv2 = conv(out_planes, out_planes, 3, 1, 1, arch_ver=arch_ver)
|
||||
|
||||
def forward(self, x):
|
||||
x = self.conv1(x)
|
||||
x = self.conv2(x)
|
||||
return x
|
||||
|
||||
|
||||
class IFBlock(nn.Module):
|
||||
def __init__(self, in_planes, c=64, arch_ver="4.0"):
|
||||
super(IFBlock, self).__init__()
|
||||
self.arch_ver = arch_ver
|
||||
self.conv0 = nn.Sequential(
|
||||
conv(in_planes, c // 2, 3, 2, 1, arch_ver=arch_ver),
|
||||
conv(c // 2, c, 3, 2, 1, arch_ver=arch_ver),
|
||||
)
|
||||
self.arch_ver = arch_ver
|
||||
|
||||
if arch_ver in ["4.0", "4.2", "4.3"]:
|
||||
self.convblock = nn.Sequential(
|
||||
conv(c, c, arch_ver=arch_ver),
|
||||
conv(c, c, arch_ver=arch_ver),
|
||||
conv(c, c, arch_ver=arch_ver),
|
||||
conv(c, c, arch_ver=arch_ver),
|
||||
conv(c, c, arch_ver=arch_ver),
|
||||
conv(c, c, arch_ver=arch_ver),
|
||||
conv(c, c, arch_ver=arch_ver),
|
||||
conv(c, c, arch_ver=arch_ver),
|
||||
)
|
||||
self.lastconv = nn.ConvTranspose2d(c, 5, 4, 2, 1)
|
||||
|
||||
if arch_ver in ["4.5", "4.6", "4.7", "4.10"]:
|
||||
self.convblock = nn.Sequential(
|
||||
ResConv(c),
|
||||
ResConv(c),
|
||||
ResConv(c),
|
||||
ResConv(c),
|
||||
ResConv(c),
|
||||
ResConv(c),
|
||||
ResConv(c),
|
||||
ResConv(c),
|
||||
)
|
||||
if arch_ver == "4.5":
|
||||
self.lastconv = nn.Sequential(
|
||||
nn.ConvTranspose2d(c, 4 * 5, 4, 2, 1), nn.PixelShuffle(2)
|
||||
)
|
||||
if arch_ver in ["4.6", "4.7", "4.10"]:
|
||||
self.lastconv = nn.Sequential(
|
||||
nn.ConvTranspose2d(c, 4 * 6, 4, 2, 1), nn.PixelShuffle(2)
|
||||
)
|
||||
|
||||
def forward(self, x, flow=None, scale=1):
|
||||
x = F.interpolate(
|
||||
x, scale_factor=1.0 / scale, mode="bilinear", align_corners=False
|
||||
)
|
||||
if flow is not None:
|
||||
flow = (
|
||||
F.interpolate(
|
||||
flow, scale_factor=1.0 / scale, mode="bilinear", align_corners=False
|
||||
)
|
||||
* 1.0
|
||||
/ scale
|
||||
)
|
||||
x = torch.cat((x, flow), 1)
|
||||
feat = self.conv0(x)
|
||||
if self.arch_ver == "4.0":
|
||||
feat = self.convblock(feat) + feat
|
||||
if self.arch_ver in ["4.2", "4.3", "4.5", "4.6", "4.7", "4.10"]:
|
||||
feat = self.convblock(feat)
|
||||
|
||||
tmp = self.lastconv(feat)
|
||||
if self.arch_ver in ["4.0", "4.2", "4.3"]:
|
||||
tmp = F.interpolate(
|
||||
tmp, scale_factor=scale * 2, mode="bilinear", align_corners=False
|
||||
)
|
||||
flow = tmp[:, :4] * scale * 2
|
||||
if self.arch_ver in ["4.5", "4.6", "4.7", "4.10"]:
|
||||
tmp = F.interpolate(
|
||||
tmp, scale_factor=scale, mode="bilinear", align_corners=False
|
||||
)
|
||||
flow = tmp[:, :4] * scale
|
||||
mask = tmp[:, 4:5]
|
||||
return flow, mask
|
||||
|
||||
|
||||
class Contextnet(nn.Module):
|
||||
def __init__(self, arch_ver="4.0"):
|
||||
super(Contextnet, self).__init__()
|
||||
c = 16
|
||||
self.conv1 = Conv2(3, c, arch_ver=arch_ver)
|
||||
self.conv2 = Conv2(c, 2 * c, arch_ver=arch_ver)
|
||||
self.conv3 = Conv2(2 * c, 4 * c, arch_ver=arch_ver)
|
||||
self.conv4 = Conv2(4 * c, 8 * c, arch_ver=arch_ver)
|
||||
|
||||
def forward(self, x, flow):
|
||||
x = self.conv1(x)
|
||||
flow = (
|
||||
F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False)
|
||||
* 0.5
|
||||
)
|
||||
f1 = warp(x, flow)
|
||||
x = self.conv2(x)
|
||||
flow = (
|
||||
F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False)
|
||||
* 0.5
|
||||
)
|
||||
f2 = warp(x, flow)
|
||||
x = self.conv3(x)
|
||||
flow = (
|
||||
F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False)
|
||||
* 0.5
|
||||
)
|
||||
f3 = warp(x, flow)
|
||||
x = self.conv4(x)
|
||||
flow = (
|
||||
F.interpolate(flow, scale_factor=0.5, mode="bilinear", align_corners=False)
|
||||
* 0.5
|
||||
)
|
||||
f4 = warp(x, flow)
|
||||
return [f1, f2, f3, f4]
|
||||
|
||||
|
||||
class Unet(nn.Module):
|
||||
def __init__(self, arch_ver="4.0"):
|
||||
super(Unet, self).__init__()
|
||||
c = 16
|
||||
self.down0 = Conv2(17, 2 * c, arch_ver=arch_ver)
|
||||
self.down1 = Conv2(4 * c, 4 * c, arch_ver=arch_ver)
|
||||
self.down2 = Conv2(8 * c, 8 * c, arch_ver=arch_ver)
|
||||
self.down3 = Conv2(16 * c, 16 * c, arch_ver=arch_ver)
|
||||
self.up0 = deconv(32 * c, 8 * c, arch_ver=arch_ver)
|
||||
self.up1 = deconv(16 * c, 4 * c, arch_ver=arch_ver)
|
||||
self.up2 = deconv(8 * c, 2 * c, arch_ver=arch_ver)
|
||||
self.up3 = deconv(4 * c, c, arch_ver=arch_ver)
|
||||
self.conv = nn.Conv2d(c, 3, 3, 1, 1)
|
||||
|
||||
def forward(self, img0, img1, warped_img0, warped_img1, mask, flow, c0, c1):
|
||||
s0 = self.down0(
|
||||
torch.cat((img0, img1, warped_img0, warped_img1, mask, flow), 1)
|
||||
)
|
||||
s1 = self.down1(torch.cat((s0, c0[0], c1[0]), 1))
|
||||
s2 = self.down2(torch.cat((s1, c0[1], c1[1]), 1))
|
||||
s3 = self.down3(torch.cat((s2, c0[2], c1[2]), 1))
|
||||
x = self.up0(torch.cat((s3, c0[3], c1[3]), 1))
|
||||
x = self.up1(torch.cat((x, s2), 1))
|
||||
x = self.up2(torch.cat((x, s1), 1))
|
||||
x = self.up3(torch.cat((x, s0), 1))
|
||||
x = self.conv(x)
|
||||
return torch.sigmoid(x)
|
||||
|
||||
|
||||
"""
|
||||
currently supports 4.0-4.12
|
||||
|
||||
4.0: 4.0, 4.1
|
||||
4.2: 4.2
|
||||
4.3: 4.3, 4.4
|
||||
4.5: 4.5
|
||||
4.6: 4.6
|
||||
4.7: 4.7, 4.8, 4.9
|
||||
4.10: 4.10 4.11 4.12
|
||||
"""
|
||||
|
||||
|
||||
class IFNet(nn.Module):
|
||||
def __init__(self, arch_ver="4.0"):
|
||||
super(IFNet, self).__init__()
|
||||
self.arch_ver = arch_ver
|
||||
if arch_ver in ["4.0", "4.2", "4.3", "4.5", "4.6"]:
|
||||
self.block0 = IFBlock(7, c=192, arch_ver=arch_ver)
|
||||
self.block1 = IFBlock(8 + 4, c=128, arch_ver=arch_ver)
|
||||
self.block2 = IFBlock(8 + 4, c=96, arch_ver=arch_ver)
|
||||
self.block3 = IFBlock(8 + 4, c=64, arch_ver=arch_ver)
|
||||
if arch_ver in ["4.7"]:
|
||||
self.block0 = IFBlock(7 + 8, c=192, arch_ver=arch_ver)
|
||||
self.block1 = IFBlock(8 + 4 + 8, c=128, arch_ver=arch_ver)
|
||||
self.block2 = IFBlock(8 + 4 + 8, c=96, arch_ver=arch_ver)
|
||||
self.block3 = IFBlock(8 + 4 + 8, c=64, arch_ver=arch_ver)
|
||||
self.encode = nn.Sequential(
|
||||
nn.Conv2d(3, 16, 3, 2, 1), nn.ConvTranspose2d(16, 4, 4, 2, 1)
|
||||
)
|
||||
if arch_ver in ["4.10"]:
|
||||
self.block0 = IFBlock(7 + 16, c=192)
|
||||
self.block1 = IFBlock(8 + 4 + 16, c=128)
|
||||
self.block2 = IFBlock(8 + 4 + 16, c=96)
|
||||
self.block3 = IFBlock(8 + 4 + 16, c=64)
|
||||
self.encode = nn.Sequential(
|
||||
nn.Conv2d(3, 32, 3, 2, 1),
|
||||
nn.LeakyReLU(0.2, True),
|
||||
nn.Conv2d(32, 32, 3, 1, 1),
|
||||
nn.LeakyReLU(0.2, True),
|
||||
nn.Conv2d(32, 32, 3, 1, 1),
|
||||
nn.LeakyReLU(0.2, True),
|
||||
nn.ConvTranspose2d(32, 8, 4, 2, 1),
|
||||
)
|
||||
|
||||
if arch_ver in ["4.0", "4.2", "4.3"]:
|
||||
self.contextnet = Contextnet(arch_ver=arch_ver)
|
||||
self.unet = Unet(arch_ver=arch_ver)
|
||||
self.arch_ver = arch_ver
|
||||
|
||||
def forward(
|
||||
self,
|
||||
img0,
|
||||
img1,
|
||||
timestep=0.5,
|
||||
scale_list=[8, 4, 2, 1],
|
||||
training=True,
|
||||
fastmode=True,
|
||||
ensemble=False,
|
||||
return_flow=False,
|
||||
):
|
||||
img0 = torch.clamp(img0, 0, 1)
|
||||
img1 = torch.clamp(img1, 0, 1)
|
||||
|
||||
n, c, h, w = img0.shape
|
||||
ph = ((h - 1) // 64 + 1) * 64
|
||||
pw = ((w - 1) // 64 + 1) * 64
|
||||
padding = (0, pw - w, 0, ph - h)
|
||||
img0 = F.pad(img0, padding)
|
||||
img1 = F.pad(img1, padding)
|
||||
x = torch.cat((img0, img1), 1)
|
||||
|
||||
if training == False:
|
||||
channel = x.shape[1] // 2
|
||||
img0 = x[:, :channel]
|
||||
img1 = x[:, channel:]
|
||||
if not torch.is_tensor(timestep):
|
||||
timestep = (x[:, :1].clone() * 0 + 1) * timestep
|
||||
else:
|
||||
timestep = timestep.repeat(1, 1, img0.shape[2], img0.shape[3])
|
||||
|
||||
flow_list = []
|
||||
merged = []
|
||||
mask_list = []
|
||||
|
||||
if self.arch_ver in ["4.7", "4.10"]:
|
||||
f0 = self.encode(img0[:, :3])
|
||||
f1 = self.encode(img1[:, :3])
|
||||
|
||||
warped_img0 = img0
|
||||
warped_img1 = img1
|
||||
flow = None
|
||||
mask = None
|
||||
block = [self.block0, self.block1, self.block2, self.block3]
|
||||
|
||||
for i in range(4):
|
||||
if flow is None:
|
||||
# 4.0-4.6
|
||||
if self.arch_ver in ["4.0", "4.2", "4.3", "4.5", "4.6"]:
|
||||
flow, mask = block[i](
|
||||
torch.cat((img0[:, :3], img1[:, :3], timestep), 1),
|
||||
None,
|
||||
scale=scale_list[i],
|
||||
)
|
||||
if ensemble:
|
||||
f1, m1 = block[i](
|
||||
torch.cat((img1[:, :3], img0[:, :3], 1 - timestep), 1),
|
||||
None,
|
||||
scale=scale_list[i],
|
||||
)
|
||||
flow = (flow + torch.cat((f1[:, 2:4], f1[:, :2]), 1)) / 2
|
||||
mask = (mask + (-m1)) / 2
|
||||
|
||||
# 4.7+
|
||||
if self.arch_ver in ["4.7", "4.10"]:
|
||||
flow, mask = block[i](
|
||||
torch.cat((img0[:, :3], img1[:, :3], f0, f1, timestep), 1),
|
||||
None,
|
||||
scale=scale_list[i],
|
||||
)
|
||||
|
||||
if ensemble:
|
||||
f_, m_ = block[i](
|
||||
torch.cat(
|
||||
(img1[:, :3], img0[:, :3], f1, f0, 1 - timestep), 1
|
||||
),
|
||||
None,
|
||||
scale=scale_list[i],
|
||||
)
|
||||
flow = (flow + torch.cat((f_[:, 2:4], f_[:, :2]), 1)) / 2
|
||||
mask = (mask + (-m_)) / 2
|
||||
|
||||
else:
|
||||
# 4.0-4.6
|
||||
if self.arch_ver in ["4.0", "4.2", "4.3", "4.5", "4.6"]:
|
||||
f0, m0 = block[i](
|
||||
torch.cat(
|
||||
(warped_img0[:, :3], warped_img1[:, :3], timestep, mask), 1
|
||||
),
|
||||
flow,
|
||||
scale=scale_list[i],
|
||||
)
|
||||
|
||||
if self.arch_ver in ["4.0"]:
|
||||
if (
|
||||
i == 1
|
||||
and f0[:, :2].abs().max() > 32
|
||||
and f0[:, 2:4].abs().max() > 32
|
||||
and not training
|
||||
):
|
||||
for k in range(4):
|
||||
scale_list[k] *= 2
|
||||
flow, mask = block[0](
|
||||
torch.cat((img0[:, :3], img1[:, :3], timestep), 1),
|
||||
None,
|
||||
scale=scale_list[0],
|
||||
)
|
||||
warped_img0 = warp(img0, flow[:, :2])
|
||||
warped_img1 = warp(img1, flow[:, 2:4])
|
||||
f0, m0 = block[i](
|
||||
torch.cat(
|
||||
(
|
||||
warped_img0[:, :3],
|
||||
warped_img1[:, :3],
|
||||
timestep,
|
||||
mask,
|
||||
),
|
||||
1,
|
||||
),
|
||||
flow,
|
||||
scale=scale_list[i],
|
||||
)
|
||||
|
||||
# 4.7+
|
||||
if self.arch_ver in ["4.7", "4.10"]:
|
||||
fd, m0 = block[i](
|
||||
torch.cat(
|
||||
(
|
||||
warped_img0[:, :3],
|
||||
warped_img1[:, :3],
|
||||
warp(f0, flow[:, :2]),
|
||||
warp(f1, flow[:, 2:4]),
|
||||
timestep,
|
||||
mask,
|
||||
),
|
||||
1,
|
||||
),
|
||||
flow,
|
||||
scale=scale_list[i],
|
||||
)
|
||||
flow = flow + fd
|
||||
|
||||
# 4.0-4.6 ensemble
|
||||
if ensemble and self.arch_ver in [
|
||||
"4.0",
|
||||
"4.2",
|
||||
"4.3",
|
||||
"4.5",
|
||||
"4.6",
|
||||
]:
|
||||
f1, m1 = block[i](
|
||||
torch.cat(
|
||||
(
|
||||
warped_img1[:, :3],
|
||||
warped_img0[:, :3],
|
||||
1 - timestep,
|
||||
-mask,
|
||||
),
|
||||
1,
|
||||
),
|
||||
torch.cat((flow[:, 2:4], flow[:, :2]), 1),
|
||||
scale=scale_list[i],
|
||||
)
|
||||
f0 = (f0 + torch.cat((f1[:, 2:4], f1[:, :2]), 1)) / 2
|
||||
m0 = (m0 + (-m1)) / 2
|
||||
|
||||
# 4.7+ ensemble
|
||||
if ensemble and self.arch_ver in ["4.7", "4.10"]:
|
||||
wf0 = warp(f0, flow[:, :2])
|
||||
wf1 = warp(f1, flow[:, 2:4])
|
||||
|
||||
f_, m_ = block[i](
|
||||
torch.cat(
|
||||
(
|
||||
warped_img1[:, :3],
|
||||
warped_img0[:, :3],
|
||||
wf1,
|
||||
wf0,
|
||||
1 - timestep,
|
||||
-mask,
|
||||
),
|
||||
1,
|
||||
),
|
||||
torch.cat((flow[:, 2:4], flow[:, :2]), 1),
|
||||
scale=scale_list[i],
|
||||
)
|
||||
fd = (fd + torch.cat((f_[:, 2:4], f_[:, :2]), 1)) / 2
|
||||
mask = (m0 + (-m_)) / 2
|
||||
|
||||
if self.arch_ver in ["4.0", "4.2", "4.3", "4.5", "4.6"]:
|
||||
flow = flow + f0
|
||||
mask = mask + m0
|
||||
|
||||
if not ensemble and self.arch_ver in ["4.7", "4.10"]:
|
||||
mask = m0
|
||||
|
||||
mask_list.append(mask)
|
||||
flow_list.append(flow)
|
||||
warped_img0 = warp(img0, flow[:, :2])
|
||||
warped_img1 = warp(img1, flow[:, 2:4])
|
||||
merged.append((warped_img0, warped_img1))
|
||||
|
||||
if self.arch_ver in ["4.0", "4.1", "4.2", "4.3", "4.4", "4.5", "4.6"]:
|
||||
mask_list[3] = torch.sigmoid(mask_list[3])
|
||||
merged[3] = merged[3][0] * mask_list[3] + merged[3][1] * (1 - mask_list[3])
|
||||
|
||||
if self.arch_ver in ["4.7", "4.10"]:
|
||||
mask = torch.sigmoid(mask)
|
||||
merged[3] = warped_img0 * mask + warped_img1 * (1 - mask)
|
||||
|
||||
if not fastmode and self.arch_ver in ["4.0", "4.2", "4.3"]:
|
||||
c0 = self.contextnet(img0, flow[:, :2])
|
||||
c1 = self.contextnet(img1, flow[:, 2:4])
|
||||
tmp = self.unet(img0, img1, warped_img0, warped_img1, mask, flow, c0, c1)
|
||||
res = tmp[:, :3] * 2 - 1
|
||||
merged[3] = torch.clamp(merged[3] + res, 0, 1)
|
||||
return merged[3][:, :, :h, :w]
|
||||
358
custom_nodes/whiterabbit/vendor/vfi_utils.py
vendored
Normal file
358
custom_nodes/whiterabbit/vendor/vfi_utils.py
vendored
Normal file
@@ -0,0 +1,358 @@
|
||||
# Copyright (c) 2023–2025 Fannovel16 and contributors
|
||||
# See LICENSES/MIT-ComfyUI-Frame-Interpolation.txt for the full text.
|
||||
|
||||
import yaml
|
||||
import os
|
||||
from torch.hub import download_url_to_file, get_dir
|
||||
from urllib.parse import urlparse
|
||||
import torch
|
||||
import typing
|
||||
import traceback
|
||||
import einops
|
||||
import gc
|
||||
import torchvision.transforms.functional as transform
|
||||
from comfy.model_management import soft_empty_cache, get_torch_device
|
||||
import numpy as np
|
||||
|
||||
BASE_MODEL_DOWNLOAD_URLS = [
|
||||
"https://github.com/styler00dollar/VSGAN-tensorrt-docker/releases/download/models/",
|
||||
"https://github.com/Fannovel16/ComfyUI-Frame-Interpolation/releases/download/models/",
|
||||
"https://github.com/dajes/frame-interpolation-pytorch/releases/download/v1.0.0/",
|
||||
]
|
||||
|
||||
config_path = os.path.join(os.path.dirname(__file__), "./config.yaml")
|
||||
if os.path.exists(config_path):
|
||||
config = yaml.load(open(config_path, "r", encoding="utf-8"), Loader=yaml.FullLoader)
|
||||
else:
|
||||
raise Exception(
|
||||
"config.yaml file is neccessary, plz recreate the config file by downloading it from https://github.com/Fannovel16/ComfyUI-Frame-Interpolation"
|
||||
)
|
||||
DEVICE = get_torch_device()
|
||||
|
||||
|
||||
class InterpolationStateList:
|
||||
|
||||
def __init__(self, frame_indices: typing.List[int], is_skip_list: bool):
|
||||
self.frame_indices = frame_indices
|
||||
self.is_skip_list = is_skip_list
|
||||
|
||||
def is_frame_skipped(self, frame_index):
|
||||
is_frame_in_list = frame_index in self.frame_indices
|
||||
return (
|
||||
self.is_skip_list
|
||||
and is_frame_in_list
|
||||
or not self.is_skip_list
|
||||
and not is_frame_in_list
|
||||
)
|
||||
|
||||
|
||||
class MakeInterpolationStateList:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"frame_indices": ("STRING", {"multiline": True, "default": "1,2,3"}),
|
||||
"is_skip_list": (
|
||||
"BOOLEAN",
|
||||
{"default": True},
|
||||
),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("INTERPOLATION_STATES",)
|
||||
FUNCTION = "create_options"
|
||||
CATEGORY = "ComfyUI-Frame-Interpolation/VFI"
|
||||
|
||||
def create_options(self, frame_indices: str, is_skip_list: bool):
|
||||
frame_indices_list = [int(item) for item in frame_indices.split(",")]
|
||||
|
||||
interpolation_state_list = InterpolationStateList(
|
||||
frame_indices=frame_indices_list,
|
||||
is_skip_list=is_skip_list,
|
||||
)
|
||||
return (interpolation_state_list,)
|
||||
|
||||
|
||||
def get_ckpt_container_path(model_type):
|
||||
return os.path.abspath(
|
||||
os.path.join(os.path.dirname(__file__), config["ckpts_path"], model_type)
|
||||
)
|
||||
|
||||
|
||||
def load_file_from_url(url, model_dir=None, progress=True, file_name=None):
|
||||
"""Load file form http url, will download models if necessary.
|
||||
|
||||
Ref:https://github.com/1adrianb/face-alignment/blob/master/face_alignment/utils.py
|
||||
|
||||
Args:
|
||||
url (str): URL to be downloaded.
|
||||
model_dir (str): The path to save the downloaded model. Should be a full path. If None, use pytorch hub_dir.
|
||||
Default: None.
|
||||
progress (bool): Whether to show the download progress. Default: True.
|
||||
file_name (str): The downloaded file name. If None, use the file name in the url. Default: None.
|
||||
|
||||
Returns:
|
||||
str: The path to the downloaded file.
|
||||
"""
|
||||
if model_dir is None: # use the pytorch hub_dir
|
||||
hub_dir = get_dir()
|
||||
model_dir = os.path.join(hub_dir, "checkpoints")
|
||||
|
||||
os.makedirs(model_dir, exist_ok=True)
|
||||
|
||||
parts = urlparse(url)
|
||||
file_name = os.path.basename(parts.path)
|
||||
if file_name is not None:
|
||||
file_name = file_name
|
||||
cached_file = os.path.abspath(os.path.join(model_dir, file_name))
|
||||
if not os.path.exists(cached_file):
|
||||
print(f'Downloading: "{url}" to {cached_file}\n')
|
||||
download_url_to_file(url, cached_file, hash_prefix=None, progress=progress)
|
||||
return cached_file
|
||||
|
||||
|
||||
def load_file_from_github_release(model_type, ckpt_name):
|
||||
error_strs = []
|
||||
for i, base_model_download_url in enumerate(BASE_MODEL_DOWNLOAD_URLS):
|
||||
try:
|
||||
return load_file_from_url(
|
||||
base_model_download_url + ckpt_name, get_ckpt_container_path(model_type)
|
||||
)
|
||||
except Exception:
|
||||
traceback_str = traceback.format_exc()
|
||||
if i < len(BASE_MODEL_DOWNLOAD_URLS) - 1:
|
||||
print("Failed! Trying another endpoint.")
|
||||
error_strs.append(
|
||||
f"Error when downloading from: {base_model_download_url + ckpt_name}\n\n{traceback_str}"
|
||||
)
|
||||
|
||||
error_str = "\n\n".join(error_strs)
|
||||
raise Exception(
|
||||
f"Tried all GitHub base urls to download {ckpt_name} but no suceess. Below is the error log:\n\n{error_str}"
|
||||
)
|
||||
|
||||
|
||||
def load_file_from_direct_url(model_type, url):
|
||||
return load_file_from_url(url, get_ckpt_container_path(model_type))
|
||||
|
||||
|
||||
def preprocess_frames(frames):
|
||||
return einops.rearrange(frames[..., :3], "n h w c -> n c h w")
|
||||
|
||||
|
||||
def postprocess_frames(frames):
|
||||
return einops.rearrange(frames, "n c h w -> n h w c")[..., :3].cpu()
|
||||
|
||||
|
||||
def assert_batch_size(frames, batch_size=2, vfi_name=None):
|
||||
subject_verb = (
|
||||
"Most VFI models require"
|
||||
if vfi_name is None
|
||||
else f"VFI model {vfi_name} requires"
|
||||
)
|
||||
assert (
|
||||
len(frames) >= batch_size
|
||||
), f"{subject_verb} at least {batch_size} frames to work with, only found {frames.shape[0]}. Please check the frame input using PreviewImage."
|
||||
|
||||
|
||||
def _generic_frame_loop(
|
||||
frames,
|
||||
clear_cache_after_n_frames,
|
||||
multiplier: typing.Union[typing.SupportsInt, typing.List],
|
||||
return_middle_frame_function,
|
||||
*return_middle_frame_function_args,
|
||||
interpolation_states: InterpolationStateList = None,
|
||||
use_timestep=True,
|
||||
dtype=torch.float16,
|
||||
final_logging=True,
|
||||
):
|
||||
|
||||
# https://github.com/hzwer/Practical-RIFE/blob/main/inference_video.py#L169
|
||||
def non_timestep_inference(frame0, frame1, n):
|
||||
middle = return_middle_frame_function(
|
||||
frame0, frame1, None, *return_middle_frame_function_args
|
||||
)
|
||||
if n == 1:
|
||||
return [middle]
|
||||
first_half = non_timestep_inference(frame0, middle, n=n // 2)
|
||||
second_half = non_timestep_inference(middle, frame1, n=n // 2)
|
||||
if n % 2:
|
||||
return [*first_half, middle, *second_half]
|
||||
else:
|
||||
return [*first_half, *second_half]
|
||||
|
||||
output_frames = torch.zeros(
|
||||
multiplier * frames.shape[0], *frames.shape[1:], dtype=dtype, device="cpu"
|
||||
)
|
||||
out_len = 0
|
||||
|
||||
number_of_frames_processed_since_last_cleared_cuda_cache = 0
|
||||
|
||||
for frame_itr in range(
|
||||
len(frames) - 1
|
||||
): # Skip the final frame since there are no frames after it
|
||||
frame0 = frames[frame_itr : frame_itr + 1]
|
||||
output_frames[out_len] = frame0 # Start with first frame
|
||||
out_len += 1
|
||||
# Ensure that input frames are in fp32 - the same dtype as model
|
||||
frame0 = frame0.to(dtype=torch.float32)
|
||||
frame1 = frames[frame_itr + 1 : frame_itr + 2].to(dtype=torch.float32)
|
||||
|
||||
if interpolation_states is not None and interpolation_states.is_frame_skipped(
|
||||
frame_itr
|
||||
):
|
||||
continue
|
||||
|
||||
# Generate and append a batch of middle frames
|
||||
middle_frame_batches = []
|
||||
|
||||
if use_timestep:
|
||||
for middle_i in range(1, multiplier):
|
||||
timestep = middle_i / multiplier
|
||||
|
||||
middle_frame = (
|
||||
return_middle_frame_function(
|
||||
frame0.to(DEVICE),
|
||||
frame1.to(DEVICE),
|
||||
timestep,
|
||||
*return_middle_frame_function_args,
|
||||
)
|
||||
.detach()
|
||||
.cpu()
|
||||
)
|
||||
middle_frame_batches.append(middle_frame.to(dtype=dtype))
|
||||
else:
|
||||
middle_frames = non_timestep_inference(
|
||||
frame0.to(DEVICE), frame1.to(DEVICE), multiplier - 1
|
||||
)
|
||||
middle_frame_batches.extend(
|
||||
torch.cat(middle_frames, dim=0).detach().cpu().to(dtype=dtype)
|
||||
)
|
||||
|
||||
# Copy middle frames to output
|
||||
for middle_frame in middle_frame_batches:
|
||||
output_frames[out_len] = middle_frame
|
||||
out_len += 1
|
||||
|
||||
number_of_frames_processed_since_last_cleared_cuda_cache += 1
|
||||
# Try to avoid a memory overflow by clearing cuda cache regularly
|
||||
if (
|
||||
number_of_frames_processed_since_last_cleared_cuda_cache
|
||||
>= clear_cache_after_n_frames
|
||||
):
|
||||
print("Comfy-VFI: Clearing cache...", end=" ")
|
||||
soft_empty_cache()
|
||||
number_of_frames_processed_since_last_cleared_cuda_cache = 0
|
||||
print("Done cache clearing")
|
||||
|
||||
gc.collect()
|
||||
|
||||
if final_logging:
|
||||
print(
|
||||
f"Comfy-VFI done! {len(output_frames)} frames generated at resolution: {output_frames[0].shape}"
|
||||
)
|
||||
# Append final frame
|
||||
output_frames[out_len] = frames[-1:]
|
||||
out_len += 1
|
||||
# clear cache for courtesy
|
||||
if final_logging:
|
||||
print("Comfy-VFI: Final clearing cache...", end=" ")
|
||||
soft_empty_cache()
|
||||
if final_logging:
|
||||
print("Done cache clearing")
|
||||
return output_frames[:out_len]
|
||||
|
||||
|
||||
def generic_frame_loop(
|
||||
model_name,
|
||||
frames,
|
||||
clear_cache_after_n_frames,
|
||||
multiplier: typing.Union[typing.SupportsInt, typing.List],
|
||||
return_middle_frame_function,
|
||||
*return_middle_frame_function_args,
|
||||
interpolation_states: InterpolationStateList = None,
|
||||
use_timestep=True,
|
||||
dtype=torch.float32,
|
||||
):
|
||||
|
||||
assert_batch_size(frames, vfi_name=model_name.replace("_", " ").replace("VFI", ""))
|
||||
if type(multiplier) == int:
|
||||
return _generic_frame_loop(
|
||||
frames,
|
||||
clear_cache_after_n_frames,
|
||||
multiplier,
|
||||
return_middle_frame_function,
|
||||
*return_middle_frame_function_args,
|
||||
interpolation_states=interpolation_states,
|
||||
use_timestep=use_timestep,
|
||||
dtype=dtype,
|
||||
)
|
||||
if type(multiplier) == list:
|
||||
multipliers = list(map(int, multiplier))
|
||||
multipliers += [2] * (len(frames) - len(multipliers) - 1)
|
||||
frame_batches = []
|
||||
for frame_itr in range(len(frames) - 1):
|
||||
multiplier = multipliers[frame_itr]
|
||||
if multiplier == 0:
|
||||
continue
|
||||
frame_batch = _generic_frame_loop(
|
||||
frames[frame_itr : frame_itr + 2],
|
||||
clear_cache_after_n_frames,
|
||||
multiplier,
|
||||
return_middle_frame_function,
|
||||
*return_middle_frame_function_args,
|
||||
interpolation_states=interpolation_states,
|
||||
use_timestep=use_timestep,
|
||||
dtype=dtype,
|
||||
final_logging=False,
|
||||
)
|
||||
if (
|
||||
frame_itr != len(frames) - 2
|
||||
): # Not append last frame unless this batch is the last one
|
||||
frame_batch = frame_batch[:-1]
|
||||
frame_batches.append(frame_batch)
|
||||
output_frames = torch.cat(frame_batches)
|
||||
print(
|
||||
f"Comfy-VFI done! {len(output_frames)} frames generated at resolution: {output_frames[0].shape}"
|
||||
)
|
||||
return output_frames
|
||||
raise NotImplementedError(f"multipiler of {type(multiplier)}")
|
||||
|
||||
|
||||
class FloatToInt:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {"float": ("FLOAT", {"default": 0, "min": 0, "step": 0.01})}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("INT",)
|
||||
FUNCTION = "convert"
|
||||
CATEGORY = "ComfyUI-Frame-Interpolation"
|
||||
|
||||
def convert(self, float):
|
||||
if hasattr(float, "__iter__"):
|
||||
return (list(map(int, float)),)
|
||||
return (int(float),)
|
||||
|
||||
|
||||
""" def generic_4frame_loop(
|
||||
frames,
|
||||
clear_cache_after_n_frames,
|
||||
multiplier: typing.SupportsInt,
|
||||
return_middle_frame_function,
|
||||
*return_middle_frame_function_args,
|
||||
interpolation_states: InterpolationStateList = None,
|
||||
use_timestep=False):
|
||||
|
||||
if use_timestep: raise NotImplementedError("Timestep 4 frame VFI model")
|
||||
def non_timestep_inference(frame_0, frame_1, frame_2, frame_3, n):
|
||||
middle = return_middle_frame_function(frame_0, frame_1, None, *return_middle_frame_function_args)
|
||||
if n == 1:
|
||||
return [middle]
|
||||
first_half = non_timestep_inference(frame_0, middle, n=n//2)
|
||||
second_half = non_timestep_inference(middle, frame_1, n=n//2)
|
||||
if n%2:
|
||||
return [*first_half, middle, *second_half]
|
||||
else:
|
||||
return [*first_half, *second_half] """
|
||||
852
custom_nodes/whiterabbit/video_loop.py
Normal file
852
custom_nodes/whiterabbit/video_loop.py
Normal file
@@ -0,0 +1,852 @@
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# SPDX-FileCopyrightText: 2025 ArtificialSweetener <artificialsweetenerai@proton.me>
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
class PrepareLoopFrames:
|
||||
DESCRIPTION = "Prepares the wrap seam: builds a tiny 2-frame batch [last, first] for your interpolator and also passes the original clip through unchanged."
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"images": (
|
||||
"IMAGE",
|
||||
{
|
||||
"tooltip": "Your clip as an IMAGE batch (frames×H×W×C, values 0–1). Outputs: [last, first] for the seam, plus the original clip."
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "IMAGE")
|
||||
RETURN_NAMES = ("interp_batch", "original_images")
|
||||
FUNCTION = "prepare"
|
||||
CATEGORY = "video utils"
|
||||
|
||||
def prepare(self, images):
|
||||
last_frame = images[-1:]
|
||||
first_frame = images[0:1]
|
||||
interp_batch = torch.cat((last_frame, first_frame), dim=0)
|
||||
return (interp_batch, images)
|
||||
|
||||
|
||||
class AssembleLoopFrames:
|
||||
DESCRIPTION = "Builds the final loop: appends only the new in-between seam frames to your original clip—no duplicate of frame 1."
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"original_images": (
|
||||
"IMAGE",
|
||||
{"tooltip": "Your original clip (frames×H×W×C)."},
|
||||
),
|
||||
"interpolated_frames": (
|
||||
"IMAGE",
|
||||
{
|
||||
"tooltip": "Frames that bridge last→first. The first and last of this batch are the originals; only the middle ones get added."
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
RETURN_NAMES = ("images",)
|
||||
FUNCTION = "assemble"
|
||||
CATEGORY = "video utils"
|
||||
|
||||
def assemble(self, original_images, interpolated_frames):
|
||||
original_images = original_images.to(interpolated_frames.device)
|
||||
in_between = interpolated_frames[1:-1]
|
||||
out = torch.cat((original_images, in_between), dim=0)
|
||||
return (out,)
|
||||
|
||||
|
||||
class RollFrames:
|
||||
DESCRIPTION = "Rolls the clip in a loop by an integer amount (cyclic shift). Also returns the same offset so you can undo it later."
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"images": ("IMAGE", {"tooltip": "Your clip (frames×H×W×C)."}),
|
||||
"offset": (
|
||||
"INT",
|
||||
{
|
||||
"default": 1,
|
||||
"min": -9999,
|
||||
"max": 9999,
|
||||
"step": 1,
|
||||
"tooltip": "How far to rotate the clip. Positive = forward in time; negative = backward.",
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "INT")
|
||||
RETURN_NAMES = ("images", "offset_out")
|
||||
FUNCTION = "roll"
|
||||
CATEGORY = "video utils"
|
||||
|
||||
def roll(self, images, offset):
|
||||
B = images.shape[0]
|
||||
if B == 0:
|
||||
return (images, int(offset))
|
||||
k = int(offset) % B
|
||||
if k == 0:
|
||||
return (images, int(offset))
|
||||
rolled = torch.roll(images, shifts=-k, dims=0) # +1 → [2,3,...,1]
|
||||
return (rolled, int(offset))
|
||||
|
||||
|
||||
class UnrollFrames:
|
||||
DESCRIPTION = "Undo a previous roll after interpolation by accounting for the inserted frames (rotate by base_offset × (m+1))."
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"images": (
|
||||
"IMAGE",
|
||||
{"tooltip": "Clip after interpolation (frames′×H×W×C)."},
|
||||
),
|
||||
"base_offset": (
|
||||
"INT",
|
||||
{
|
||||
"default": 1,
|
||||
"min": -9999,
|
||||
"max": 9999,
|
||||
"step": 1,
|
||||
"tooltip": "Use the exact offset_out that came from RollFrames.",
|
||||
},
|
||||
),
|
||||
"m": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 9999,
|
||||
"step": 1,
|
||||
"tooltip": "How many in-betweens per gap were added (the interpolation multiple).",
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
RETURN_NAMES = ("images",)
|
||||
FUNCTION = "unroll"
|
||||
CATEGORY = "video utils"
|
||||
|
||||
def unroll(self, images, base_offset, m):
|
||||
Bp = images.shape[0]
|
||||
if Bp == 0:
|
||||
return (images,)
|
||||
eff = (int(base_offset) * (int(m) + 1)) % Bp
|
||||
return (torch.roll(images, shifts=+eff, dims=0),)
|
||||
|
||||
|
||||
class AutocropToLoop:
|
||||
"""
|
||||
Finds a natural loop by cropping frames from the END of the batch.
|
||||
Returns the cropped clip that makes the seam (last_kept -> first)
|
||||
feel like a normal step between real neighbors.
|
||||
|
||||
Score = weighted mix of:
|
||||
- step-size match (L1/MSE distance)
|
||||
- similarity match (SSIM)
|
||||
- exposure continuity (luma)
|
||||
- motion consistency (optical flow; optional)
|
||||
|
||||
Speed: can run metrics on GPU and use mixed precision for SSIM/conv math.
|
||||
Progress bar: one tick per candidate crop (0..max_end_crop_frames).
|
||||
"""
|
||||
|
||||
DESCRIPTION = "Auto-crops the clip to create a smoother loop: tests crops from the end and scores the seam so it feels like a normal step."
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"clip_frames": (
|
||||
"IMAGE",
|
||||
{
|
||||
"tooltip": "Your full clip (NHWC, 0–1). Tries every crop from 0..max_end_crop_frames and returns the best loop."
|
||||
},
|
||||
),
|
||||
"max_end_crop_frames": (
|
||||
"INT",
|
||||
{
|
||||
"default": 12,
|
||||
"min": 0,
|
||||
"max": 10000,
|
||||
"tooltip": "Largest crop to test at the END. Higher = more candidates (slower), but potentially better.",
|
||||
},
|
||||
),
|
||||
"include_first_step": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"tooltip": "Use the first neighbor pair (frame 0→1) as a target step size/similarity.",
|
||||
},
|
||||
),
|
||||
"include_last_step": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"tooltip": "Use the last neighbor pair inside the KEPT region as a target.",
|
||||
},
|
||||
),
|
||||
"include_global_median_step": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": False,
|
||||
"tooltip": "Also use the median step across the KEPT region (needs ≥3 frames). Helps ignore outliers.",
|
||||
},
|
||||
),
|
||||
"seam_window_frames": (
|
||||
"INT",
|
||||
{
|
||||
"default": 2,
|
||||
"min": 1,
|
||||
"max": 6,
|
||||
"tooltip": "Average over multiple aligned pairs across the seam. Larger = more robust.",
|
||||
},
|
||||
),
|
||||
"distance_metric": (
|
||||
["L1", "MSE"],
|
||||
{
|
||||
"default": "L1",
|
||||
"tooltip": "How to measure step size for matching. L1 is usually more forgiving; MSE penalizes big errors more.",
|
||||
},
|
||||
),
|
||||
"score_in_8bit": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": False,
|
||||
"tooltip": "Score with an 8-bit view (simulate export). Output video still stays float.",
|
||||
},
|
||||
),
|
||||
"use_ssim_similarity": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"tooltip": "Include SSIM so the seam ‘looks’ like a normal neighbor—avoid freeze or jump.",
|
||||
},
|
||||
),
|
||||
"use_exposure_guard": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"tooltip": "Promote smooth brightness across the seam (reduces flicker pops).",
|
||||
},
|
||||
),
|
||||
"use_flow_guard": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": False,
|
||||
"tooltip": "Encourage consistent motion across the seam (needs OpenCV; slower).",
|
||||
},
|
||||
),
|
||||
"weight_step_size": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.55,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Importance of matching step size. Higher = less freeze/jump risk.",
|
||||
},
|
||||
),
|
||||
"weight_similarity": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.30,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Importance of visual similarity (SSIM). Helps avoid a frozen-looking seam.",
|
||||
},
|
||||
),
|
||||
"weight_exposure": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.10,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Importance of even brightness across the seam.",
|
||||
},
|
||||
),
|
||||
"weight_flow": (
|
||||
"FLOAT",
|
||||
{
|
||||
"default": 0.05,
|
||||
"min": 0.0,
|
||||
"max": 1.0,
|
||||
"step": 0.01,
|
||||
"tooltip": "Importance of motion continuity across the seam.",
|
||||
},
|
||||
),
|
||||
"ssim_downsample_scales": (
|
||||
"STRING",
|
||||
{
|
||||
"default": "1,2",
|
||||
"tooltip": "SSIM scales to average, as a comma list. Example: 1,2 = full-res and half-res.",
|
||||
},
|
||||
),
|
||||
"accelerate_with_gpu": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"tooltip": "If ON and CUDA is available, run scoring on GPU for a big speedup (same results).",
|
||||
},
|
||||
),
|
||||
"use_mixed_precision": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": True,
|
||||
"tooltip": "If ON (with GPU), use mixed precision for SSIM/conv math (faster on larger clips).",
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "INT", "INT", "FLOAT", "STRING")
|
||||
RETURN_NAMES = (
|
||||
"cropped_clip",
|
||||
"end_crop_frames",
|
||||
"cropped_length",
|
||||
"score",
|
||||
"diagnostics_csv",
|
||||
)
|
||||
FUNCTION = "find_and_crop"
|
||||
CATEGORY = "video utils"
|
||||
|
||||
_gw_cache = {} # gaussian window cache
|
||||
|
||||
def _to_nchw(self, x):
|
||||
import torch
|
||||
|
||||
if x.ndim == 4 and x.shape[-1] in (1, 3, 4):
|
||||
return x.permute(0, 3, 1, 2).contiguous()
|
||||
return x
|
||||
|
||||
def _parse_scales(self, csv):
|
||||
scales = []
|
||||
for s in str(csv).split(","):
|
||||
s = s.strip()
|
||||
if not s:
|
||||
continue
|
||||
try:
|
||||
v = int(s)
|
||||
if v >= 1 and v not in scales:
|
||||
scales.append(v)
|
||||
except Exception:
|
||||
pass
|
||||
return scales or [1]
|
||||
|
||||
def _downsample(self, x, s):
|
||||
import torch.nn.functional as F
|
||||
|
||||
if s == 1:
|
||||
return x
|
||||
H, W = x.shape[-2:]
|
||||
newH = max(1, H // s)
|
||||
newW = max(1, W // s)
|
||||
return F.interpolate(x, size=(newH, newW), mode="area", align_corners=None)
|
||||
|
||||
def _dist(self, A, B, kind="L1"):
|
||||
if kind == "MSE":
|
||||
return ((A - B) ** 2).mean(dim=(1, 2, 3))
|
||||
return (A - B).abs().mean(dim=(1, 2, 3))
|
||||
|
||||
def _luma(self, x_nchw):
|
||||
if x_nchw.shape[1] == 1:
|
||||
return x_nchw[:, 0:1]
|
||||
R = x_nchw[:, 0:1]
|
||||
G = x_nchw[:, 1:2]
|
||||
B = x_nchw[:, 2:3]
|
||||
return 0.2126 * R + 0.7152 * G + 0.0722 * B
|
||||
|
||||
def _gaussian_window(self, C, k=7, sigma=1.5, device="cpu", dtype=None):
|
||||
import torch
|
||||
|
||||
key = (int(C), int(k), float(sigma), str(device), str(dtype))
|
||||
w = self._gw_cache.get(key)
|
||||
if w is not None:
|
||||
return w
|
||||
ax = torch.arange(k, dtype=dtype, device=device) - (k - 1) / 2.0
|
||||
gauss = torch.exp(-0.5 * (ax / sigma) ** 2)
|
||||
kernel1d = (gauss / gauss.sum()).unsqueeze(1)
|
||||
kernel2d = kernel1d @ kernel1d.t()
|
||||
w = kernel2d.expand(C, 1, k, k).contiguous()
|
||||
self._gw_cache[key] = w
|
||||
return w
|
||||
|
||||
def _ssim_pair_batched(self, x, y, k=7, sigma=1.5, C1=0.01**2, C2=0.03**2):
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
C = x.shape[1]
|
||||
w = self._gaussian_window(C, k=k, sigma=sigma, device=x.device, dtype=x.dtype)
|
||||
mu_x = F.conv2d(x, w, padding=k // 2, groups=C)
|
||||
mu_y = F.conv2d(y, w, padding=k // 2, groups=C)
|
||||
mu_x2, mu_y2, mu_xy = mu_x * mu_x, mu_y * mu_y, mu_x * mu_y
|
||||
sigma_x2 = F.conv2d(x * x, w, padding=k // 2, groups=C) - mu_x2
|
||||
sigma_y2 = F.conv2d(y * y, w, padding=k // 2, groups=C) - mu_y2
|
||||
sigma_xy = F.conv2d(x * y, w, padding=k // 2, groups=C) - mu_xy
|
||||
ssim_map = ((2.0 * mu_xy + C1) * (2.0 * sigma_xy + C2)) / (
|
||||
(mu_x2 + mu_y2 + C1) * (sigma_x2 + sigma_y2 + C2) + 1e-12
|
||||
)
|
||||
return ssim_map.mean(dim=(1, 2, 3)) # (N,)
|
||||
|
||||
def _ssim_multiscale_batched(self, x, y, scales):
|
||||
vecs = []
|
||||
for s in scales:
|
||||
xs = self._downsample(x, s)
|
||||
ys = self._downsample(y, s)
|
||||
vecs.append(self._ssim_pair_batched(xs, ys))
|
||||
return sum(vecs) / float(len(vecs)) # (N,)
|
||||
|
||||
def _precompute_adjacent_metrics(
|
||||
self, clip_nhwc_dev, kind, use_ssim, ds_scales, use_exp, use_flow
|
||||
):
|
||||
"""
|
||||
Returns dict with vectors of length (B-1):
|
||||
D_adj (torch), S_adj (torch), E_adj (torch), F_adj (np, CPU)
|
||||
All torch tensors are on the same device as clip_nhwc_dev.
|
||||
"""
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
B = int(clip_nhwc_dev.shape[0])
|
||||
N = max(0, B - 1)
|
||||
result = {}
|
||||
if N == 0:
|
||||
result["D_adj"] = torch.empty(0, device=clip_nhwc_dev.device)
|
||||
result["S_adj"] = torch.empty(0, device=clip_nhwc_dev.device)
|
||||
result["E_adj"] = torch.empty(0, device=clip_nhwc_dev.device)
|
||||
result["F_adj"] = np.zeros((0,), dtype="float64")
|
||||
return result, self._to_nchw(clip_nhwc_dev)
|
||||
|
||||
x_nchw = self._to_nchw(clip_nhwc_dev) # B,C,H,W (device)
|
||||
X = x_nchw[:-1]
|
||||
Y = x_nchw[1:] # N,C,H,W
|
||||
|
||||
result["D_adj"] = self._dist(X, Y, kind=kind) # (N,)
|
||||
|
||||
if use_ssim:
|
||||
result["S_adj"] = self._ssim_multiscale_batched(X, Y, ds_scales) # (N,)
|
||||
else:
|
||||
result["S_adj"] = torch.empty(0, device=x_nchw.device)
|
||||
|
||||
if use_exp:
|
||||
Y_luma = self._luma(x_nchw).mean(dim=(1, 2, 3)) # (B,)
|
||||
result["E_adj"] = (Y_luma[:-1] - Y_luma[1:]).abs() # (N,)
|
||||
else:
|
||||
result["E_adj"] = torch.empty(0, device=x_nchw.device)
|
||||
|
||||
if use_flow:
|
||||
F_adj = []
|
||||
for i in range(N):
|
||||
a = clip_nhwc_dev[i : i + 1].detach().cpu()
|
||||
b = clip_nhwc_dev[i + 1 : i + 2].detach().cpu()
|
||||
F_adj.append(self._flow_mag_mean(a, b))
|
||||
import numpy as np
|
||||
|
||||
result["F_adj"] = np.array(F_adj, dtype="float64")
|
||||
else:
|
||||
import numpy as np
|
||||
|
||||
result["F_adj"] = np.zeros((N,), dtype="float64")
|
||||
|
||||
return result, x_nchw
|
||||
|
||||
def _precompute_seam_tables(self, x_nchw_dev, W, kind, use_ssim, ds_scales):
|
||||
"""
|
||||
For k = 0..W-1, precompute per-frame metrics vs first+k:
|
||||
D_to_firstk[k] : (B,) distances to frame k
|
||||
S_to_firstk[k] : (B,) SSIM to frame k (if use_ssim)
|
||||
E_to_firstk[k] : (B,) |luma(i)-luma(k)|
|
||||
Tensors live on x_nchw_dev.device.
|
||||
"""
|
||||
import torch
|
||||
|
||||
B = int(x_nchw_dev.shape[0])
|
||||
W = max(1, min(int(W), B - 1))
|
||||
D_to_firstk, S_to_firstk, E_to_firstk = [], [], []
|
||||
|
||||
Y = self._luma(x_nchw_dev).mean(dim=(1, 2, 3))
|
||||
|
||||
for k in range(W):
|
||||
Bk = x_nchw_dev[k : k + 1].expand_as(x_nchw_dev)
|
||||
Dk = self._dist(x_nchw_dev, Bk, kind=kind)
|
||||
D_to_firstk.append(Dk)
|
||||
if use_ssim:
|
||||
Sk = self._ssim_multiscale_batched(x_nchw_dev, Bk, ds_scales)
|
||||
S_to_firstk.append(Sk)
|
||||
else:
|
||||
S_to_firstk.append(torch.empty(0, device=x_nchw_dev.device))
|
||||
Ek = (Y - Y[k]).abs()
|
||||
E_to_firstk.append(Ek)
|
||||
|
||||
return D_to_firstk, S_to_firstk, E_to_firstk
|
||||
|
||||
def _flow_mag_mean(self, a_nhwc, b_nhwc, max_side=256):
|
||||
"""
|
||||
Mean optical-flow magnitude. Accepts NHWC with/without batch,
|
||||
RGB/RGBA/Gray. Soft-fails to 0.0 if OpenCV unavailable.
|
||||
"""
|
||||
try:
|
||||
import cv2
|
||||
import numpy as np
|
||||
except Exception:
|
||||
return 0.0
|
||||
|
||||
a = (a_nhwc.detach().cpu().numpy() * 255.0).clip(0, 255).astype("uint8")
|
||||
b = (b_nhwc.detach().cpu().numpy() * 255.0).clip(0, 255).astype("uint8")
|
||||
if a.ndim == 4 and a.shape[0] == 1:
|
||||
a = a[0]
|
||||
if b.ndim == 4 and b.shape[0] == 1:
|
||||
b = b[0]
|
||||
|
||||
def to_gray(x: np.ndarray) -> np.ndarray:
|
||||
if x.ndim == 2:
|
||||
return x
|
||||
if x.ndim == 3:
|
||||
c = x.shape[-1]
|
||||
if c == 1:
|
||||
return x[..., 0]
|
||||
if c == 3:
|
||||
return cv2.cvtColor(x, cv2.COLOR_RGB2GRAY)
|
||||
if c == 4:
|
||||
return cv2.cvtColor(x, cv2.COLOR_RGBA2GRAY)
|
||||
return x.mean(axis=-1).astype(x.dtype)
|
||||
x2 = np.squeeze(x)
|
||||
if x2.ndim == 2:
|
||||
return x2
|
||||
if x2.ndim == 3:
|
||||
return x2.mean(axis=-1).astype(x2.dtype)
|
||||
return None
|
||||
|
||||
a_g, b_g = to_gray(a), to_gray(b)
|
||||
if a_g is None or b_g is None or a_g.ndim != 2 or b_g.ndim != 2:
|
||||
return 0.0
|
||||
|
||||
H, W = a_g.shape
|
||||
scale = max(1.0, max(H, W) / float(max_side))
|
||||
if scale > 1.0:
|
||||
newW = int(round(W / scale))
|
||||
newH = int(round(H / scale))
|
||||
a_g = cv2.resize(a_g, (newW, newH), interpolation=cv2.INTER_AREA)
|
||||
b_g = cv2.resize(b_g, (newW, newH), interpolation=cv2.INTER_AREA)
|
||||
|
||||
try:
|
||||
flow = cv2.calcOpticalFlowFarneback(
|
||||
a_g, b_g, None, 0.5, 3, 21, 3, 5, 1.1, 0
|
||||
)
|
||||
mag = (flow[..., 0] ** 2 + flow[..., 1] ** 2) ** 0.5
|
||||
return float(mag.mean())
|
||||
except Exception:
|
||||
return 0.0
|
||||
|
||||
def find_and_crop(
|
||||
self,
|
||||
clip_frames,
|
||||
max_end_crop_frames,
|
||||
include_first_step,
|
||||
include_last_step,
|
||||
include_global_median_step,
|
||||
seam_window_frames,
|
||||
distance_metric,
|
||||
score_in_8bit,
|
||||
use_ssim_similarity,
|
||||
use_exposure_guard,
|
||||
use_flow_guard,
|
||||
weight_step_size,
|
||||
weight_similarity,
|
||||
weight_exposure,
|
||||
weight_flow,
|
||||
ssim_downsample_scales,
|
||||
accelerate_with_gpu,
|
||||
use_mixed_precision,
|
||||
):
|
||||
import contextlib
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from comfy.utils import ProgressBar
|
||||
|
||||
clip_out = clip_frames
|
||||
clip_eval = (
|
||||
(clip_frames * 255.0).round().clamp(0, 255) / 255.0
|
||||
if score_in_8bit
|
||||
else clip_frames
|
||||
)
|
||||
|
||||
B = int(clip_eval.shape[0])
|
||||
if B < 2:
|
||||
header = "end_crop,score,D_seam,D_target,S_seam,S_target,E_seam,E_target,F_seam,F_target"
|
||||
return (clip_out, 0, B, 0.0, header)
|
||||
|
||||
dev = "cuda" if accelerate_with_gpu and torch.cuda.is_available() else "cpu"
|
||||
amp_ctx = (
|
||||
torch.cuda.amp.autocast
|
||||
if (dev == "cuda" and use_mixed_precision)
|
||||
else contextlib.nullcontext
|
||||
)
|
||||
|
||||
ds_scales = self._parse_scales(ssim_downsample_scales)
|
||||
kind = distance_metric
|
||||
W = int(seam_window_frames)
|
||||
total_candidates = int(max(0, max_end_crop_frames)) + 1
|
||||
|
||||
with torch.no_grad():
|
||||
with amp_ctx():
|
||||
|
||||
clip_eval_dev = clip_eval.to(dev, non_blocking=True)
|
||||
|
||||
pre, x_nchw_dev = self._precompute_adjacent_metrics(
|
||||
clip_nhwc_dev=clip_eval_dev,
|
||||
kind=kind,
|
||||
use_ssim=use_ssim_similarity,
|
||||
ds_scales=ds_scales,
|
||||
use_exp=use_exposure_guard,
|
||||
use_flow=use_flow_guard,
|
||||
)
|
||||
D_adj, S_adj, E_adj, F_adj = (
|
||||
pre["D_adj"],
|
||||
pre["S_adj"],
|
||||
pre["E_adj"],
|
||||
pre["F_adj"],
|
||||
)
|
||||
|
||||
D_seam_tab, S_seam_tab, E_seam_tab = self._precompute_seam_tables(
|
||||
x_nchw_dev=x_nchw_dev,
|
||||
W=W,
|
||||
kind=kind,
|
||||
use_ssim=use_ssim_similarity,
|
||||
ds_scales=ds_scales,
|
||||
)
|
||||
|
||||
Y = self._luma(x_nchw_dev).mean(dim=(1, 2, 3))
|
||||
|
||||
best_extra = 0
|
||||
best_score = float("inf")
|
||||
rows = []
|
||||
pbar = ProgressBar(total_candidates)
|
||||
|
||||
for extra in range(0, total_candidates):
|
||||
keep = B - extra
|
||||
if keep < 2:
|
||||
pbar.update(1)
|
||||
continue
|
||||
|
||||
last_idx = keep - 1
|
||||
W_eff = max(1, min(W, last_idx + 1, B - 1))
|
||||
|
||||
chosen_D = []
|
||||
if include_first_step and keep >= 2:
|
||||
chosen_D.append(D_adj[0])
|
||||
if include_last_step and keep >= 2:
|
||||
chosen_D.append(D_adj[last_idx - 1])
|
||||
if include_global_median_step and keep >= 3:
|
||||
chosen_D.append(D_adj[: keep - 1].median())
|
||||
if not chosen_D and keep >= 2:
|
||||
chosen_D = [D_adj[0]]
|
||||
D_target = float(
|
||||
(
|
||||
chosen_D[0]
|
||||
if len(chosen_D) == 1
|
||||
else torch.stack(chosen_D).median()
|
||||
).item()
|
||||
)
|
||||
|
||||
if use_ssim_similarity and S_adj.numel() > 0 and keep >= 2:
|
||||
chosen_S = []
|
||||
if include_first_step:
|
||||
chosen_S.append(S_adj[0])
|
||||
if include_last_step:
|
||||
chosen_S.append(S_adj[last_idx - 1])
|
||||
if include_global_median_step and keep >= 3:
|
||||
chosen_S.append(S_adj[: keep - 1].median())
|
||||
S_target = float(
|
||||
(
|
||||
chosen_S[0]
|
||||
if (chosen_S and len(chosen_S) == 1)
|
||||
else (
|
||||
torch.stack(chosen_S).median()
|
||||
if chosen_S
|
||||
else torch.tensor(0.0, device=S_adj.device)
|
||||
)
|
||||
).item()
|
||||
)
|
||||
else:
|
||||
S_target = 0.0
|
||||
|
||||
if use_exposure_guard and keep >= 2:
|
||||
e_first = (Y[0] - Y[1]).abs()
|
||||
e_last = (Y[last_idx] - Y[last_idx - 1]).abs()
|
||||
if include_global_median_step and keep >= 3:
|
||||
e_med = (Y[: keep - 1] - Y[1:keep]).abs().median()
|
||||
E_target = float(
|
||||
torch.stack([e_first, e_last, e_med]).median().item()
|
||||
)
|
||||
else:
|
||||
E_target = float(torch.stack([e_first, e_last]).median().item())
|
||||
else:
|
||||
E_target = 0.0
|
||||
|
||||
if use_flow_guard and keep >= 3 and F_adj.size > 0:
|
||||
import numpy as np
|
||||
|
||||
F_target = float(np.median(F_adj[: keep - 1]))
|
||||
else:
|
||||
F_target = 0.0
|
||||
|
||||
idxs = [last_idx - (W_eff - 1 - r) for r in range(W_eff)]
|
||||
idxs_t = torch.tensor(idxs, device=x_nchw_dev.device, dtype=torch.long)
|
||||
|
||||
D_vals = torch.stack(
|
||||
[
|
||||
D_seam_tab[r].index_select(0, idxs_t[r : r + 1]).squeeze(0)
|
||||
for r in range(W_eff)
|
||||
]
|
||||
)
|
||||
D_seam = float(D_vals.mean().item())
|
||||
|
||||
if use_ssim_similarity and S_seam_tab[0].numel() > 0:
|
||||
S_vals = torch.stack(
|
||||
[
|
||||
S_seam_tab[r].index_select(0, idxs_t[r : r + 1]).squeeze(0)
|
||||
for r in range(W_eff)
|
||||
]
|
||||
)
|
||||
S_seam = float(S_vals.mean().item())
|
||||
else:
|
||||
S_seam = 0.0
|
||||
|
||||
if use_exposure_guard:
|
||||
E_vals = torch.stack(
|
||||
[
|
||||
E_seam_tab[r].index_select(0, idxs_t[r : r + 1]).squeeze(0)
|
||||
for r in range(W_eff)
|
||||
]
|
||||
)
|
||||
E_seam = float(E_vals.mean().item())
|
||||
else:
|
||||
E_seam = 0.0
|
||||
|
||||
F_seam = 0.0
|
||||
|
||||
eps = 1e-12
|
||||
cost_step = abs(D_seam - D_target) / (D_target + eps)
|
||||
cost_sim = (
|
||||
abs(S_seam - S_target) / (abs(S_target) + eps)
|
||||
if use_ssim_similarity
|
||||
else 0.0
|
||||
)
|
||||
cost_exp = (
|
||||
abs(E_seam - E_target) / (E_target + eps)
|
||||
if (use_exposure_guard and E_target > 0.0)
|
||||
else 0.0
|
||||
)
|
||||
cost_flow = (
|
||||
abs(F_seam - F_target) / (F_target + eps)
|
||||
if (use_flow_guard and F_target > 0.0)
|
||||
else 0.0
|
||||
)
|
||||
|
||||
score = (
|
||||
weight_step_size * cost_step
|
||||
+ weight_similarity * cost_sim
|
||||
+ weight_exposure * cost_exp
|
||||
+ weight_flow * cost_flow
|
||||
)
|
||||
|
||||
rows.append(
|
||||
f"{extra},{score:.6f},{D_seam:.6f},{D_target:.6f},{S_seam:.6f},{S_target:.6f},{E_seam:.6f},{E_target:.6f},{F_seam:.6f},{F_target:.6f}"
|
||||
)
|
||||
|
||||
if score < best_score:
|
||||
best_score = score
|
||||
best_extra = extra
|
||||
|
||||
pbar.update(1)
|
||||
|
||||
final_keep = max(2, B - best_extra)
|
||||
cropped = clip_out[0:final_keep]
|
||||
header = "end_crop,score,D_seam,D_target,S_seam,S_target,E_seam,E_target,F_seam,F_target"
|
||||
diagnostics_csv = header + "\n" + "\n".join(rows) if rows else header
|
||||
return (
|
||||
cropped,
|
||||
int(best_extra),
|
||||
int(final_keep),
|
||||
float(best_score),
|
||||
diagnostics_csv,
|
||||
)
|
||||
|
||||
|
||||
class TrimBatchEnds:
|
||||
"""
|
||||
Trim frames from the START and/or END of an IMAGE batch (NHWC, [0..1]).
|
||||
Both trims are applied in one pass. Always leaves at least one frame.
|
||||
"""
|
||||
|
||||
DESCRIPTION = "Quickly remove frames from the start and/or end of a clip. Always keeps at least one frame."
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"clip_frames": ("IMAGE", {"tooltip": "Your clip (frames×H×W×C, 0–1)."}),
|
||||
"trim_start_frames": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 100000,
|
||||
"tooltip": "Frames to remove from the START.",
|
||||
},
|
||||
),
|
||||
"trim_end_frames": (
|
||||
"INT",
|
||||
{
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 100000,
|
||||
"tooltip": "Frames to remove from the END.",
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
RETURN_NAMES = ("images",)
|
||||
FUNCTION = "crop"
|
||||
CATEGORY = "video utils"
|
||||
|
||||
def crop(self, clip_frames, trim_start_frames, trim_end_frames):
|
||||
import torch
|
||||
|
||||
if not isinstance(clip_frames, torch.Tensor) or clip_frames.ndim != 4:
|
||||
return (clip_frames,)
|
||||
|
||||
B = int(clip_frames.shape[0])
|
||||
if B <= 1:
|
||||
return (clip_frames,)
|
||||
|
||||
s = max(0, int(trim_start_frames))
|
||||
e = max(0, int(trim_end_frames))
|
||||
|
||||
if s + e >= B:
|
||||
s = min(s, B - 1)
|
||||
e = max(0, B - s - 1)
|
||||
|
||||
out = clip_frames[s : B - e] if e > 0 else clip_frames[s:]
|
||||
if out.shape[0] == 0:
|
||||
out = clip_frames[B - 1 : B]
|
||||
return (out,)
|
||||
Reference in New Issue
Block a user