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

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:
2026-02-09 00:55:26 +00:00
parent 2b70ab9ad0
commit f09734b0ee
2274 changed files with 748556 additions and 3 deletions

View File

@@ -0,0 +1,159 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintainted in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
# Other
*.ipynb
*.code-workspace
/test/test_images
/.vscode
config.json

View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@@ -0,0 +1,44 @@
# ComfyUI_UltimateSDUpscale
[ComfyUI](https://github.com/comfyanonymous/ComfyUI) nodes for performing the image-to-image diffusion process on large images in tiles. This approach improves the details that is commonly found on upscaled images while reducing hardware requirements and maintaining an image size that the diffusion model is trained on.
## Installation
### Using Git
1. Git must be installed on your system. Verify by running `git -v` in a terminal.
2. Enter the following command from the terminal starting in ComfyUI/custom_nodes/
```
git clone https://github.com/ssitu/ComfyUI_UltimateSDUpscale
```
### ComfyUI Manager
1. [ComfyUI Manager](https://github.com/Comfy-Org/ComfyUI-Manager) must be installed.
2. After launching ComfyUI, open ComfyUI Manager and select the "Custom Nodes Manager" option.
3. Search for "UltimateSDUpscale" and install the node. Select latest for the most up-to-date version.
4. Follow any prompts to restart ComfyUI.
### comfy-cli
1. [comfy-cli](https://github.com/Comfy-Org/comfy-cli) must be installed.
2. Run this command from the terminal: `comfy node install comfyui_ultimatesdupscale`
### Manual Download
1. Download the zip file from https://registry.comfy.org/nodes/comfyui_ultimatesdupscale to select the version you want, or obtain the current nightly version by clicking the green "Code" button on the GitHub repository page and selecting "Download ZIP".
2. Create a new folder in the `ComfyUI/custom_nodes/` directory to hold the extracted files (e.g. `ComfyUI/custom_nodes/ComfyUI_UltimateSDUpscale`).
3. Extract the contents of the zip file into the `ComfyUI/custom_nodes/ComfyUI_UltimateSDUpscale` folder.
## Usage
Nodes can be found in the node menu under `image/upscaling`.
Documentation for the nodes can be found in the [`js/docs/`](js/docs/) folder, or viewed within the application by right-clicking the relevant node and selecting the info icon.
Details about most of the parameters can be found [here](https://github.com/Coyote-A/ultimate-upscale-for-automatic1111/wiki/FAQ#parameters-descriptions).
Example workflows can be found in the [`example_workflows/`](example_workflows/) folder. You can also find them in the ComfyUI application under the Templates menu, scroll down the left sidebar to find the Extensions section, then selecting this repository.
## References
* Ultimate Stable Diffusion Upscale script for the Automatic1111 Web UI: https://github.com/Coyote-A/ultimate-upscale-for-automatic1111
* ComfyUI: https://github.com/comfyanonymous/ComfyUI

View File

@@ -0,0 +1,77 @@
import sys
import os
# Check for original USDU script
current_dir = os.path.dirname(os.path.realpath(__file__))
repos_dir = os.path.join(current_dir, "repositories")
usdu_dir = os.path.join(repos_dir, "ultimate_sd_upscale")
if not len(os.listdir(usdu_dir)):
print("[USDU] Original USDU script not found, downloading it from https://github.com/Coyote-A/ultimate-upscale-for-automatic1111")
import urllib.request
import zipfile
import shutil
url = "https://github.com/Coyote-A/ultimate-upscale-for-automatic1111/archive/master.zip"
zip_path = os.path.join(current_dir, "usdu_temp.zip")
urllib.request.urlretrieve(url, zip_path)
with zipfile.ZipFile(zip_path, "r") as zip_ref:
top_folder = zip_ref.namelist()[0].split('/')[0] + '/'
for member in zip_ref.namelist():
if member.startswith(top_folder) and not member.endswith('/'):
target_path = os.path.join(usdu_dir, member[len(top_folder):])
os.makedirs(os.path.dirname(target := os.path.join(usdu_dir, member[len(top_folder):])), exist_ok=True)
with zip_ref.open(member) as source, open(target, 'wb') as target_file:
shutil.copyfileobj(fsrc=zip_ref.open(member), fdst=target_file)
os.remove(zip_path)
print("[USDU] Original USDU script downloaded successfully")
# Remove other custom_node paths from sys.path to avoid conflicts
custom_node_paths = [path for path in sys.path if "custom_node" in path]
original_sys_path = sys.path.copy()
for path in custom_node_paths:
sys.path.remove(path)
# Add this repository's path to sys.path for third-party imports
repo_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, repo_dir)
original_modules = sys.modules.copy()
# Place aside potentially conflicting modules
modules_used = [
"modules",
"modules.devices",
"modules.images",
"modules.processing",
"modules.scripts",
"modules.shared",
"modules.upscaler",
"utils",
]
original_imported_modules = {}
for module in modules_used:
if module in sys.modules:
original_imported_modules[module] = sys.modules.pop(module)
# Proceed with node setup
from .usdu_nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
WEB_DIRECTORY = "./js"
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS"]
# Clean up imports
# Remove any new modules
modules_to_remove = []
for module in sys.modules:
if module not in original_modules:
modules_to_remove.append(module)
for module in modules_to_remove:
del sys.modules[module]
# Restore original modules
sys.modules.update(original_imported_modules)
# Restore original sys.path
sys.path = original_sys_path

View File

@@ -0,0 +1,3 @@
{
"per_tile_progress": true
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 247 KiB

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
# Empty gradio module for the ultimate-upscale.py import because gradio is not needed

View File

@@ -0,0 +1,71 @@
`Ultimate SD Upscale` combines image upscaling with tiled image-to-image processing to create high-quality, detail-enhanced upscaled images.
This is the main node that interfaces with the original code for the Ultimate SD Upscale script. An image is supplied for upscaling, determined by the `upscale_by` parameter. The upscale is performed using the upscale model input.
After the upscaling, the image goes through the redraw step if the tiling order is not set to "None". A tile is selected from the image, defined by the tiling order and tile parameters from the node widgets. The tile is used as input for an image-to-image process, using the sampling-related parameters given by the node widgets. The tile is then pasted back onto the upscaled image at the appropriate position. This continues until all tiles have been processed.
After the redraw step, the seam fix step is applied if enabled. There are various strategies for fixing seams, defined by the `seam_fix_mode` parameter from the node widgets. The seam fix step uses the same image-to-image process as the redraw step, but applied to areas between tiles from the redraw step.
## Inputs
| Parameter | Data Type | Input Method | Default | Range | Description |
|-----------|-----------|--------------|---------|--------|-------------|
| `image` | IMAGE | Image Input | None | - | The image to upscale. |
| `model` | MODEL | Model Selection | None | - | The model to use for image-to-image processing on each tile. |
| `positive` | CONDITIONING | Conditioning Input | None | - | The positive conditioning for each tile during the redraw step. |
| `negative` | CONDITIONING | Conditioning Input | None | - | The negative conditioning for each tile during the redraw step. |
| `vae` | VAE | Model Selection | None | - | The VAE model to use for encoding and decoding tiles. |
| `upscale_by` | FLOAT | Slider | 2.0 | 0.05-4.0 (step 0.05) | The factor to multiply the height and width of the input image(s) by. |
| `seed` | INT | Number Input | 0 | 0-18446744073709551615 | The seed to use for image-to-image processing, ensuring reproducible results. |
| `steps` | INT | Number Input | 20 | 1-10000 | The number of sampling steps to use for each tile during the redraw step and seam fix step. |
| `cfg` | FLOAT | Slider | 8.0 | 0.0-100.0 | The CFG (Classifier Free Guidance) scale to use for each tile. Higher values make the output follow the prompt more closely. The recommended values depend on the model. |
| `sampler_name` | COMBO | Dropdown | - | Available samplers | The sampler to use for each tile during the image-to-image process. |
| `scheduler` | COMBO | Dropdown | - | Available schedulers | The scheduler to use for each tile during the sampling process. |
| `denoise` | FLOAT | Slider | 0.2 | 0.0-1.0 (step 0.01) | The denoising strength to use for each tile. Higher values allow more creative changes, but more chance of seams. |
| `upscale_model` | UPSCALE_MODEL | Model Selection | None | - | The upscaler model for upscaling the image before the tiled redraw step. |
| `mode_type` | COMBO | Dropdown | - | Linear, Chess, None | The tiling order to use for the redraw step. Linear processes tiles row by row, Chess uses a checkerboard pattern, and None skips the redraw step. |
| `tile_width` | INT | Number Input | 512 | 64-8192 (step 8) | The base width of each tile during the redraw step. |
| `tile_height` | INT | Number Input | 512 | 64-8192 (step 8) | The base height of each tile during the redraw step. |
| `mask_blur` | INT | Number Input | 8 | 0-64 | The blur radius for the mask applied to tiles, helping blend tiles seamlessly. A higher value means more of the original image is retained near the seams when pasting the refined tiles back on the upscaled image. |
| `tile_padding` | INT | Number Input | 32 | 0-8192 (step 8) | The padding to apply to tiles, providing more context for better blending. Adds to tile size (e.g. (`tile_width` + `tile_padding`)x(`tile_height` + `tile_padding`)). |
| `seam_fix_mode` | COMBO | Dropdown | - | None, Band Pass, Half Tile, Half Tile + Intersections | The seam fix mode to use. Different modes apply different strategies to fix visible seams between tiles. |
| `seam_fix_denoise` | FLOAT | Slider | 1.0 | 0.0-1.0 (step 0.01) | The denoising strength to use for the seam fix step. |
| `seam_fix_width` | INT | Number Input | 64 | 0-8192 (step 8) | The width of the bands used for the Band Pass seam fix mode. |
| `seam_fix_mask_blur` | INT | Number Input | 8 | 0-64 | The blur radius for the seam fix mask, ensuring smooth blending. |
| `seam_fix_padding` | INT | Number Input | 16 | 0-8192 (step 8) | The padding to apply for the seam fix step. Adds to tile size. |
| `force_uniform_tiles` | BOOLEAN | Toggle | True | True/False | If enabled, tiles that would be cut off by the edges of the image will expand using context around the tile to keep the same tile size determined by `tile_width`, `tile_height`, and `tile_padding`. This is what happens in the A1111 Web UI. If disabled, the minimal size for tiles will be used, which may make the sampling faster but may cause artifacts due to irregular tile sizes. |
| `tiled_decode` | BOOLEAN | Toggle | False | True/False | Whether to use tiled decoding when decoding tiles. Useful when you know the ComfyUI engine will attempt a normal decode and run into an Out Of Memory error, and resorts to tiled decoding anyway. |
## Outputs
| Output Name | Data Type | Description |
|-------------|-----------|-------------|
| `IMAGE` | IMAGE | The final upscaled image. |
## Usage Tips
1. **Basic Usage**
- Typical tile sizes are based on the model resolutions that it is trained on, such as 512x512 for SD1.5 models. If you can generate a coherent image at that resolution, then it is a good choice for the tile size.
- If the workflow involves generating a base image, then using USDU to upscale and refine, it is common to take the base image size as the tile size for the USDU node. For example, generating a 512x512 image, then using USDU with 2x upscale and 512x512 tiles to get a final 1024x1024 image.
- If you want to specify an exact output size, use the "No Upscale" variant of the node and perform the upscaling separately (e.g., ImageUpscaleWithModel -> ImageScale -> UltimateSDUpscaleNoUpscale).
2. **Tiling Modes**
- **Linear**: Processes tiles sequentially row by row.
- **Chess**: Uses a checkerboard pattern, processing every other tile first. Can help reduce visible seams.
- **None**: Skips the redraw step entirely, only performs the initial upscale. Useful if you have an image upscaled by USDU and see seams, and only want to use the seam fix step.
3. **Denoise Settings**
- Use a lower denoise (0.05-0.2) to refine the upscaled image to be less blurry, while avoiding seams and hallucinations.
- Higher denoise values are only usable when using something like a ControlNet tile model to avoid tiles and seams.
4. **Seam Fix Modes**
- **None**: No seam fixing applied
- **Band Pass**: Applies processing to band-like areas between tiles
- **Half Tile**: Processes half-tile overlapping regions
- **Half Tile + Intersections**: Most thorough, processes half-tiles and their intersections
5. **Performance Optimization**
- Enable `tiled_decode` if you're running out of VRAM during decoding, and want to skip the default behavior of attempting normal decoding.
- Use the largest tile size that the model and VRAM can handle to reduce the number of tiles needed.
- Disable `force_uniform_tiles` to only denoise what will be visible after pasting back the tile. This can save processing time, but the model used may not be trained for the resulting tile sizes, and the model will be missing the context around the tile that may otherwise be available with this option enabled.6. **Important Notes**
- The seam fix step significantly increases processing time. If seams are a problem, it may be better to reduce the denoise or increase tile size instead to avoid the increase in processing time.

View File

@@ -0,0 +1,106 @@
`Ultimate SD Upscale (Custom Sample)` combines image upscaling with tiled image-to-image processing using custom samplers and sigmas for advanced control over the sampling process.
This variant of the Ultimate SD Upscale node is designed for advanced users who want to use custom samplers and sigma schedules instead of the built-in ComfyUI samplers. This allows for more experimental and fine-tuned control over the sampling process during the tiled redraw and seam fix steps. The upscale model is optional; if not provided, the Lanczos algorithm will be used instead.
An image is supplied for upscaling, determined by the `upscale_by` parameter. The upscale is performed using the upscale model input if provided, otherwise a Lanczos scaling is applied.
After the upscaling, the image goes through the redraw step if the tiling order is not set to "None". A tile is selected from the image, defined by the tiling order and tile parameters from the node widgets. The tile is used as input for an image-to-image process, using the sampling-related parameters given by the node widgets, including custom sampler and sigmas if provided. The tile is then pasted back onto the upscaled image at the appropriate position. This continues until all tiles have been processed.
After the redraw step, the seam fix step is applied if enabled. There are various strategies for fixing seams, defined by the `seam_fix_mode` parameter from the node widgets. The seam fix step uses the same image-to-image process as the redraw step, but applied to areas between tiles from the redraw step.
## Inputs
### Required Inputs
| Parameter | Data Type | Input Method | Default | Range | Description |
|-----------|-----------|--------------|---------|--------|-------------|
| `image` | IMAGE | Image Input | None | - | The image to upscale. |
| `model` | MODEL | Model Selection | None | - | The model to use for image-to-image processing on each tile. |
| `positive` | CONDITIONING | Conditioning Input | None | - | The positive conditioning for each tile during the redraw step. |
| `negative` | CONDITIONING | Conditioning Input | None | - | The negative conditioning for each tile during the redraw step. |
| `vae` | VAE | Model Selection | None | - | The VAE model to use for encoding and decoding tiles. |
| `upscale_by` | FLOAT | Slider | 2.0 | 0.05-4.0 (step 0.05) | The factor to multiply the height and width of the input image(s) by. |
| `seed` | INT | Number Input | 0 | 0-18446744073709551615 | The seed to use for image-to-image processing, ensuring reproducible results. |
| `steps` | INT | Number Input | 20 | 1-10000 | The number of sampling steps to use for each tile during the redraw step and seam fix step. |
| `cfg` | FLOAT | Slider | 8.0 | 0.0-100.0 | The CFG (Classifier Free Guidance) scale to use for each tile. Higher values make the output follow the prompt more closely. The recommended values depend on the model. |
| `sampler_name` | COMBO | Dropdown | - | Available samplers | The sampler to use for each tile during the image-to-image process. |
| `scheduler` | COMBO | Dropdown | - | Available schedulers | The scheduler to use for each tile during the sampling process. |
| `denoise` | FLOAT | Slider | 0.2 | 0.0-1.0 (step 0.01) | The denoising strength to use for each tile. Higher values allow more creative changes, but more chance of seams. |
| `mode_type` | COMBO | Dropdown | - | Linear, Chess, None | The tiling order to use for the redraw step. Linear processes tiles row by row, Chess uses a checkerboard pattern, and None skips the redraw step. |
| `tile_width` | INT | Number Input | 512 | 64-8192 (step 8) | The base width of each tile during the redraw step. |
| `tile_height` | INT | Number Input | 512 | 64-8192 (step 8) | The base height of each tile during the redraw step. |
| `mask_blur` | INT | Number Input | 8 | 0-64 | The blur radius for the mask applied to tiles, helping blend tiles seamlessly. A higher value means more of the original image is retained near the seams when pasting the refined tiles back on the upscaled image. |
| `tile_padding` | INT | Number Input | 32 | 0-8192 (step 8) | The padding to apply to tiles, providing more context for better blending. Adds to tile size (e.g. (`tile_width` + `tile_padding`)x(`tile_height` + `tile_padding`)). |
| `seam_fix_mode` | COMBO | Dropdown | - | None, Band Pass, Half Tile, Half Tile + Intersections | The seam fix mode to use. Different modes apply different strategies to fix visible seams between tiles. |
| `seam_fix_denoise` | FLOAT | Slider | 1.0 | 0.0-1.0 (step 0.01) | The denoising strength to use for the seam fix step. |
| `seam_fix_width` | INT | Number Input | 64 | 0-8192 (step 8) | The width of the bands used for the Band Pass seam fix mode. |
| `seam_fix_mask_blur` | INT | Number Input | 8 | 0-64 | The blur radius for the seam fix mask, ensuring smooth blending. |
| `seam_fix_padding` | INT | Number Input | 16 | 0-8192 (step 8) | The padding to apply for the seam fix step. Adds to tile size. |
| `force_uniform_tiles` | BOOLEAN | Toggle | True | True/False | If enabled, tiles that would be cut off by the edges of the image will expand using context around the tile to keep the same tile size determined by `tile_width`, `tile_height`, and `tile_padding`. This is what happens in the A1111 Web UI. If disabled, the minimal size for tiles will be used, which may make the sampling faster but may cause artifacts due to irregular tile sizes. |
| `tiled_decode` | BOOLEAN | Toggle | False | True/False | Whether to use tiled decoding when decoding tiles. Useful when you know the ComfyUI engine will attempt a normal decode and run into an Out Of Memory error, and resorts to tiled decoding anyway. |
### Optional Inputs
| Parameter | Data Type | Input Method | Default | Description |
|-----------|-----------|--------------|---------|-------------|
| `upscale_model` | UPSCALE_MODEL | Model Selection | None | The upscaler model for upscaling the image before the tiled redraw step. If not provided, the Lanczos algorithm will be used instead. |
| `custom_sampler` | SAMPLER | Sampler Input | None | A custom sampler to use instead of the built-in ComfyUI sampler specified by `sampler_name`. Only used if both `custom_sampler` and `custom_sigmas` are provided. |
| `custom_sigmas` | SIGMAS | Sigmas Input | None | A custom noise schedule to use during sampling. Only used if both `custom_sampler` and `custom_sigmas` are provided. |
## Outputs
| Output Name | Data Type | Description |
|-------------|-----------|-------------|
| `IMAGE` | IMAGE | The final upscaled image. |
## Usage Tips
1. **When to Use This Node**
- You want to experiment with custom samplers not available in the standard node.
- You need precise control over sigma schedules.
- You're working with advanced sampling techniques or research implementations.
- You want the flexibility to skip the upscale model and use Lanczos instead.
- You're combining USDU with custom sampling workflows.
2. **Basic Usage**
- Typical tile sizes are based on the model resolutions that it is trained on, such as 512x512 for SD1.5 models. If you can generate a coherent image at that resolution, then it is probably a good choice for the tile size.
- If the workflow involves generating a base image, then using USDU to upscale and refine, it is common to take the base image size as the tile size for the USDU node. For example, generating a 512x512 image, then using USDU with 2x upscale and 512x512 tiles to get a final 1024x1024 image.
3. **Custom Sampler Usage**
- When both `custom_sampler` and `custom_sigmas` are provided, `custom_sampler` will be used instead of the `sampler_name` parameter
- Custom samplers can implement experimental or specialized sampling algorithms
- Ensure your custom sampler is compatible with the model and VAE being used
- Custom samplers typically require `custom_sigmas` to be provided as well
4. **Custom Sigmas Usage**
- When both `custom_sampler` and `custom_sigmas` are provided, `custom_sigmas` will be used instead of the default noise schedule.
- Sigma schedules control the noise levels during the denoising process
- Custom sigmas allow you to fine-tune the denoising trajectory
- Different sigma schedules can produce different aesthetic results
- When using `custom_sigmas`, ensure they're appropriate for your `steps` parameter
5. **Tiling Modes**
- **Linear**: Processes tiles sequentially row by row.
- **Chess**: Uses a checkerboard pattern, processing every other tile first. Can help reduce visible seams.
- **None**: Skips the redraw step entirely, only performs the initial upscale. Useful if you have an image upscaled by USDU and see seams, and only want to use the seam fix step.
6. **Denoise Settings**
- Use a lower denoise (0.05-0.2) to refine the upscaled image to be less blurry, while avoiding seams and hallucinations.
- Higher denoise values are only usable when using something like a ControlNet tile model to avoid tiles and seams.
7. **Seam Fix Modes**
- **None**: No seam fixing applied
- **Band Pass**: Applies processing to band-like areas between tiles
- **Half Tile**: Processes half-tile overlapping regions
- **Half Tile + Intersections**: Most thorough, processes half-tiles and their intersections
8. **Performance Optimization**
- Enable `tiled_decode` if you're running out of VRAM during decoding, and want to skip the default behavior of attempting normal decoding.
- Use the largest tile size that the model and VRAM can handle to reduce the number of tiles needed.
- Disable `force_uniform_tiles` to only denoise what will be visible after pasting back the tile. This can save processing time, but the model used may not be trained for the resulting tile sizes, and the model will be missing the context around the tile that may otherwise be available with this option enabled.
9. **Important Notes**
- When no `upscale_model` is provided, Lanczos is used to scale by the `upscale_by` factor instead.
- Custom sampler and sigmas should be compatible with each other, and also the model being used.
- `custom_sampler` and `custom_sigmas` are both optional, but must be provided together to take effect.
- The seam fix step significantly increases processing time. If seams are a problem, it may be better to reduce the denoise or increase tile size instead to avoid the increase in processing time.

View File

@@ -0,0 +1,80 @@
`Ultimate SD Upscale (No Upscale)` applies tiled image-to-image proc5. **Performance Optimization**
- Enable `tiled_decode` if you're running out of VRAM during decoding, and want to skip the default behavior of attempting normal decoding.
- Use the largest tile size that the model and VRAM can handle to reduce the number of tiles needed.
- Disable `force_uniform_tiles` to only denoise what will be visible after pasting back the tile. This can save processing time, but the model used may not be trained for the resulting tile sizes, and the model will be missing the context around the tile that may otherwise be available with this option enabled.ng to an already upscaled image to enhance details and fix seams, without performing the initial upscaling step with an upscale model.
This variant of the Ultimate SD Upscale node is designed for situations where you already have an upscaled image and only want to apply the tiled redraw and seam fix steps. This is useful when you've upscaled an image using a different method or upscaler and want to use USDU's tiled refinement capabilities to add details and remove artifacts.
The image goes through the redraw step if the tiling order is not set to "None". A tile is selected from the image, defined by the tiling order and tile parameters from the node widgets. The tile is used as input for an image-to-image process, using the sampling-related parameters given by the node widgets. The tile is then pasted back onto the image at the appropriate position. This continues until all tiles have been processed.
After the redraw step, the seam fix step is applied if enabled. There are various strategies for fixing seams, defined by the `seam_fix_mode` parameter from the node widgets. The seam fix step uses the same image-to-image process as the redraw step, but applied to areas between tiles from the redraw step.
## Inputs
| Parameter | Data Type | Input Method | Default | Range | Description |
|-----------|-----------|--------------|---------|--------|-------------|
| `upscaled_image` | IMAGE | Image Input | None | - | The already upscaled image to refine with tiled processing. |
| `model` | MODEL | Model Selection | None | - | The model to use for image-to-image processing on each tile. |
| `positive` | CONDITIONING | Conditioning Input | None | - | The positive conditioning for each tile during the redraw step. |
| `negative` | CONDITIONING | Conditioning Input | None | - | The negative conditioning for each tile during the redraw step. |
| `vae` | VAE | Model Selection | None | - | The VAE model to use for encoding and decoding tiles. |
| `seed` | INT | Number Input | 0 | 0-18446744073709551615 | The seed to use for image-to-image processing, ensuring reproducible results. |
| `steps` | INT | Number Input | 20 | 1-10000 | The number of sampling steps to use for each tile during the redraw step and seam fix step. |
| `cfg` | FLOAT | Slider | 8.0 | 0.0-100.0 | The CFG (Classifier Free Guidance) scale to use for each tile. Higher values make the output follow the prompt more closely. The recommended values depend on the model. |
| `sampler_name` | COMBO | Dropdown | - | Available samplers | The sampler to use for each tile during the image-to-image process. |
| `scheduler` | COMBO | Dropdown | - | Available schedulers | The scheduler to use for each tile during the sampling process. |
| `denoise` | FLOAT | Slider | 0.2 | 0.0-1.0 (step 0.01) | The denoising strength to use for each tile. Higher values allow more creative changes, but more chance of seams. |
| `mode_type` | COMBO | Dropdown | - | Linear, Chess, None | The tiling order to use for the redraw step. Linear processes tiles row by row, Chess uses a checkerboard pattern, and None skips the redraw step. |
| `tile_width` | INT | Number Input | 512 | 64-8192 (step 8) | The base width of each tile during the redraw step. |
| `tile_height` | INT | Number Input | 512 | 64-8192 (step 8) | The base height of each tile during the redraw step. |
| `mask_blur` | INT | Number Input | 8 | 0-64 | The blur radius for the mask applied to tiles, helping blend tiles seamlessly. A higher value means more of the original image is retained near the seams when pasting the refined tiles back on the upscaled image. |
| `tile_padding` | INT | Number Input | 32 | 0-8192 (step 8) | The padding to apply to tiles, providing more context for better blending. Adds to tile size (e.g. (`tile_width` + `tile_padding`)x(`tile_height` + `tile_padding`)). |
| `seam_fix_mode` | COMBO | Dropdown | - | None, Band Pass, Half Tile, Half Tile + Intersections | The seam fix mode to use. Different modes apply different strategies to fix visible seams between tiles. |
| `seam_fix_denoise` | FLOAT | Slider | 1.0 | 0.0-1.0 (step 0.01) | The denoising strength to use for the seam fix step. |
| `seam_fix_width` | INT | Number Input | 64 | 0-8192 (step 8) | The width of the bands used for the Band Pass seam fix mode. |
| `seam_fix_mask_blur` | INT | Number Input | 8 | 0-64 | The blur radius for the seam fix mask, ensuring smooth blending. |
| `seam_fix_padding` | INT | Number Input | 16 | 0-8192 (step 8) | The padding to apply for the seam fix step. Adds to tile size. |
| `force_uniform_tiles` | BOOLEAN | Toggle | True | True/False | If enabled, tiles that would be cut off by the edges of the image will expand using context around the tile to keep the same tile size determined by `tile_width`, `tile_height`, and `tile_padding`. This is what happens in the A1111 Web UI. If disabled, the minimal size for tiles will be used, which may make the sampling faster but may cause artifacts due to irregular tile sizes. |
| `tiled_decode` | BOOLEAN | Toggle | False | True/False | Whether to use tiled decoding when decoding tiles. Useful when you know the ComfyUI engine will attempt a normal decode and run into an Out Of Memory error, and resorts to tiled decoding anyway. |
## Outputs
| Output Name | Data Type | Description |
|-------------|-----------|-------------|
| `IMAGE` | IMAGE | The final refined image. |
## Usage Tips
1. **When to Use This Node**
- You've already upscaled an image with a different upscaler and want to add details.
- You want to fix seams or artifacts in an existing high-resolution image.
- You want more control by separating the upscaling and refinement steps.
- You want to skip the use of an upscale model, and do a simple upscale with an algorithm like Lanczos or Nearest Neighbor beforehand.
2. **Basic Usage**
- Typical tile sizes are based on the model resolutions that it is trained on, such as 512x512 for SD1.5 models. If you can generate a coherent image at that resolution, then it is probably a good choice for the tile size.
3. **Tiling Modes**
- **Linear**: Processes tiles sequentially row by row.
- **Chess**: Uses a checkerboard pattern, processing every other tile first. Can help reduce visible seams.
- **None**: Skips the redraw step entirely. Useful if you only want to use the seam fix step to fix visible seams without adding new details.
4. **Denoise Settings**
- Use a lower denoise (0.05-0.2) to refine the upscaled image to be less blurry, while avoiding seams and hallucinations.
- Higher denoise values are only usable when using something like a ControlNet tile model to avoid tiles and seams.
5. **Seam Fix Modes**
- **None**: No seam fixing applied
- **Band Pass**: Applies processing to band-like areas between tiles
- **Half Tile**: Processes half-tile overlapping regions
- **Half Tile + Intersections**: Most thorough, processes half-tiles and their intersections
6. **Performance Optimization**
- Enable `tiled_decode` if you're running out of VRAM during decoding, and want to skip the default behavior of attempting normal decoding.
- Use the largest tile size that the model and VRAM can handle to reduce the number of tiles needed.
- Disable force_uniform_tiles to only denoise what will be visible after pasting back the tile. This can save processing time, but the model used may not be trained for the resulting tile sizes, and the model will be missing the context around the tile that may otherwise be available with this option enabled.
7. **Important Notes**
- This node does not perform any upscaling; it expects an already upscaled image as input
- The input image size determines the output size (no scaling is applied)
- The seam fix step significantly increases processing time. If seams are a problem, it may be better to reduce the denoise or increase tile size instead to avoid the increase in processing time.

View File

@@ -0,0 +1,2 @@
def torch_gc():
pass

View File

@@ -0,0 +1,8 @@
from PIL import Image
def flatten(img, bgcolor):
# Replace transparency with bgcolor
if img.mode in ("RGB"):
return img
return Image.alpha_composite(Image.new("RGBA", img.size, bgcolor), img).convert("RGB")

View File

@@ -0,0 +1,277 @@
from PIL import Image, ImageFilter
import torch
import math
from nodes import common_ksampler, VAEEncode, VAEDecode, VAEDecodeTiled
from comfy_extras.nodes_custom_sampler import SamplerCustom
from usdu_utils import pil_to_tensor, tensor_to_pil, get_crop_region, expand_crop, crop_cond
from modules import shared
from tqdm import tqdm
import comfy
from enum import Enum
import json
import os
if (not hasattr(Image, 'Resampling')): # For older versions of Pillow
Image.Resampling = Image
# Taken from the USDU script
class USDUMode(Enum):
LINEAR = 0
CHESS = 1
NONE = 2
class USDUSFMode(Enum):
NONE = 0
BAND_PASS = 1
HALF_TILE = 2
HALF_TILE_PLUS_INTERSECTIONS = 3
class StableDiffusionProcessing:
def __init__(
self,
init_img,
model,
positive,
negative,
vae,
seed,
steps,
cfg,
sampler_name,
scheduler,
denoise,
upscale_by,
uniform_tile_mode,
tiled_decode,
tile_width,
tile_height,
redraw_mode,
seam_fix_mode,
custom_sampler=None,
custom_sigmas=None,
):
# Variables used by the USDU script
self.init_images = [init_img]
self.image_mask = None
self.mask_blur = 0
self.inpaint_full_res_padding = 0
self.width = init_img.width * upscale_by
self.height = init_img.height * upscale_by
self.rows = round(self.height / tile_height)
self.cols = round(self.width / tile_width)
# ComfyUI Sampler inputs
self.model = model
self.positive = positive
self.negative = negative
self.vae = vae
self.seed = seed
self.steps = steps
self.cfg = cfg
self.sampler_name = sampler_name
self.scheduler = scheduler
self.denoise = denoise
# Optional custom sampler and sigmas
self.custom_sampler = custom_sampler
self.custom_sigmas = custom_sigmas
if (custom_sampler is not None) ^ (custom_sigmas is not None):
print("[USDU] Both custom sampler and custom sigmas must be provided, defaulting to widget sampler and sigmas")
# Variables used only by this script
self.init_size = init_img.width, init_img.height
self.upscale_by = upscale_by
self.uniform_tile_mode = uniform_tile_mode
self.tiled_decode = tiled_decode
self.vae_decoder = VAEDecode()
self.vae_encoder = VAEEncode()
self.vae_decoder_tiled = VAEDecodeTiled()
if self.tiled_decode:
print("[USDU] Using tiled decode")
# Other required A1111 variables for the USDU script that is currently unused in this script
self.extra_generation_params = {}
# Load config file for USDU
config_path = os.path.join(os.path.dirname(__file__), os.pardir, 'config.json')
config = {}
if os.path.exists(config_path):
with open(config_path, 'r') as f:
config = json.load(f)
# Progress bar for the entire process instead of per tile
self.progress_bar_enabled = False
if comfy.utils.PROGRESS_BAR_ENABLED:
self.progress_bar_enabled = True
comfy.utils.PROGRESS_BAR_ENABLED = config.get('per_tile_progress', True)
self.tiles = 0
if redraw_mode.value != USDUMode.NONE.value:
self.tiles += self.rows * self.cols
if seam_fix_mode.value == USDUSFMode.BAND_PASS.value:
self.tiles += (self.rows - 1) + (self.cols - 1)
elif seam_fix_mode.value == USDUSFMode.HALF_TILE.value:
self.tiles += (self.rows - 1) * self.cols + (self.cols - 1) * self.rows
elif seam_fix_mode.value == USDUSFMode.HALF_TILE_PLUS_INTERSECTIONS.value:
self.tiles += (self.rows - 1) * self.cols + (self.cols - 1) * self.rows + (self.rows - 1) * (self.cols - 1)
self.pbar = None
# self.pbar = tqdm(total=self.tiles, desc='USDU') # Creating the pbar here will cause an empty progress bar to be displayed
def __del__(self):
# Undo changes to progress bar flag when node is done or cancelled
if self.progress_bar_enabled:
comfy.utils.PROGRESS_BAR_ENABLED = True
class Processed:
def __init__(self, p: StableDiffusionProcessing, images: list, seed: int, info: str):
self.images = images
self.seed = seed
self.info = info
def infotext(self, p: StableDiffusionProcessing, index):
return None
def fix_seed(p: StableDiffusionProcessing):
pass
def sample(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent, denoise, custom_sampler, custom_sigmas):
# Choose way to sample based on given inputs
# Custom sampler and sigmas
if custom_sampler is not None and custom_sigmas is not None:
kwargs = dict(
model=model,
add_noise=True,
noise_seed=seed,
cfg=cfg,
positive=positive,
negative=negative,
sampler=custom_sampler,
sigmas=custom_sigmas,
latent_image=latent
)
if "execute" in dir(SamplerCustom):
(samples, _) = SamplerCustom.execute(**kwargs)
else:
custom_sample = SamplerCustom()
(samples, _) = getattr(custom_sample, custom_sample.FUNCTION)(**kwargs)
return samples
# Default
(samples,) = common_ksampler(model, seed, steps, cfg, sampler_name,
scheduler, positive, negative, latent, denoise=denoise)
return samples
def process_images(p: StableDiffusionProcessing) -> Processed:
# Where the main image generation happens in A1111
# Show the progress bar
if p.progress_bar_enabled and p.pbar is None:
p.pbar = tqdm(total=p.tiles, desc='USDU', unit='tile')
# Setup
image_mask = p.image_mask.convert('L')
init_image = p.init_images[0]
# Locate the white region of the mask outlining the tile and add padding
crop_region = get_crop_region(image_mask, p.inpaint_full_res_padding)
if p.uniform_tile_mode:
# Expand the crop region to match the processing size ratio and then resize it to the processing size
x1, y1, x2, y2 = crop_region
crop_width = x2 - x1
crop_height = y2 - y1
crop_ratio = crop_width / crop_height
p_ratio = p.width / p.height
if crop_ratio > p_ratio:
target_width = crop_width
target_height = round(crop_width / p_ratio)
else:
target_width = round(crop_height * p_ratio)
target_height = crop_height
crop_region, _ = expand_crop(crop_region, image_mask.width, image_mask.height, target_width, target_height)
tile_size = p.width, p.height
else:
# Uses the minimal size that can fit the mask, minimizes tile size but may lead to image sizes that the model is not trained on
x1, y1, x2, y2 = crop_region
crop_width = x2 - x1
crop_height = y2 - y1
target_width = math.ceil(crop_width / 8) * 8
target_height = math.ceil(crop_height / 8) * 8
crop_region, tile_size = expand_crop(crop_region, image_mask.width,
image_mask.height, target_width, target_height)
# Blur the mask
if p.mask_blur > 0:
image_mask = image_mask.filter(ImageFilter.GaussianBlur(p.mask_blur))
# Crop the images to get the tiles that will be used for generation
tiles = [img.crop(crop_region) for img in shared.batch]
# Assume the same size for all images in the batch
initial_tile_size = tiles[0].size
# Resize if necessary
for i, tile in enumerate(tiles):
if tile.size != tile_size:
tiles[i] = tile.resize(tile_size, Image.Resampling.LANCZOS)
# Crop conditioning
positive_cropped = crop_cond(p.positive, crop_region, p.init_size, init_image.size, tile_size)
negative_cropped = crop_cond(p.negative, crop_region, p.init_size, init_image.size, tile_size)
# Encode the image
batched_tiles = torch.cat([pil_to_tensor(tile) for tile in tiles], dim=0)
(latent,) = p.vae_encoder.encode(p.vae, batched_tiles)
# Generate samples
samples = sample(p.model, p.seed, p.steps, p.cfg, p.sampler_name, p.scheduler, positive_cropped,
negative_cropped, latent, p.denoise, p.custom_sampler, p.custom_sigmas)
# Update the progress bar
if p.progress_bar_enabled:
p.pbar.update(1)
# Decode the sample
if not p.tiled_decode:
(decoded,) = p.vae_decoder.decode(p.vae, samples)
else:
(decoded,) = p.vae_decoder_tiled.decode(p.vae, samples, 512) # Default tile size is 512
# Convert the sample to a PIL image
tiles_sampled = [tensor_to_pil(decoded, i) for i in range(len(decoded))]
for i, tile_sampled in enumerate(tiles_sampled):
init_image = shared.batch[i]
# Resize back to the original size
if tile_sampled.size != initial_tile_size:
tile_sampled = tile_sampled.resize(initial_tile_size, Image.Resampling.LANCZOS)
# Put the tile into position
image_tile_only = Image.new('RGBA', init_image.size)
image_tile_only.paste(tile_sampled, crop_region[:2])
# Add the mask as an alpha channel
# Must make a copy due to the possibility of an edge becoming black
temp = image_tile_only.copy()
temp.putalpha(image_mask)
image_tile_only.paste(temp, image_tile_only)
# Add back the tile to the initial image according to the mask in the alpha channel
result = init_image.convert('RGBA')
result.alpha_composite(image_tile_only)
# Convert back to RGB
result = result.convert('RGB')
shared.batch[i] = result
processed = Processed(p, [shared.batch[0]], p.seed, None)
return processed

View File

@@ -0,0 +1,2 @@
class Script:
pass

View File

@@ -0,0 +1,25 @@
class Options:
img2img_background_color = "#ffffff" # Set to white for now
class State:
interrupted = False
def begin(self):
pass
def end(self):
pass
opts = Options()
state = State()
# Will only ever hold 1 upscaler
sd_upscalers = [None]
# The upscaler usable by ComfyUI nodes
actual_upscaler = None
# Batch of images to upscale
batch = None
batch_as_tensor = None

View File

@@ -0,0 +1,31 @@
from PIL import Image
from usdu_utils import tensor_to_pil, pil_to_tensor
from comfy_extras.nodes_upscale_model import ImageUpscaleWithModel
from modules import shared
if (not hasattr(Image, 'Resampling')): # For older versions of Pillow
Image.Resampling = Image
class Upscaler:
def upscale(self, img: Image, scale, selected_model: str = None):
if scale == 1.0:
return img
if (shared.actual_upscaler is None):
return img.resize((img.width * scale, img.height * scale), Image.Resampling.LANCZOS)
if "execute" in dir(ImageUpscaleWithModel):
# V3 schema: https://github.com/comfyanonymous/ComfyUI/pull/10149
(upscaled,) = ImageUpscaleWithModel.execute(shared.actual_upscaler, shared.batch_as_tensor)
else:
(upscaled,) = ImageUpscaleWithModel().upscale(shared.actual_upscaler, shared.batch_as_tensor)
shared.batch = [tensor_to_pil(upscaled, i) for i in range(len(upscaled))]
return shared.batch[0]
class UpscalerData:
name = ""
data_path = ""
def __init__(self):
self.scaler = Upscaler()

View File

@@ -0,0 +1,25 @@
[project]
name = "comfyui_ultimatesdupscale"
description = "ComfyUI nodes for the Ultimate Stable Diffusion Upscale script by Coyote-A."
version = "1.6.5"
license = { file = "LICENSE" }
[project.optional-dependencies]
test = [
"pytest>=9.0.0",
"pytest-cov>=7.0.0",
]
[project.urls]
Repository = "https://github.com/ssitu/ComfyUI_UltimateSDUpscale"
# Used by Comfy Registry https://comfyregistry.org
[tool.comfy]
PublisherId = "ssit"
DisplayName = "ComfyUI_UltimateSDUpscale"
Icon = ""
includes = ["/repositories/ultimate_sd_upscale/"]
[tool.setuptools.packages.find]
where = ["."]
include = ["ComfyUI_UltimateSDUpscale"]

View File

@@ -0,0 +1,14 @@
import os
import sys
import importlib.util
repositories_path = os.path.dirname(os.path.realpath(__file__))
# Import the script
script_name = os.path.join("scripts", "ultimate-upscale")
repo_name = "ultimate_sd_upscale"
script_path = os.path.join(repositories_path, repo_name, f"{script_name}.py")
spec = importlib.util.spec_from_file_location(script_name, script_path)
ultimate_upscale = importlib.util.module_from_spec(spec)
sys.modules[script_name] = ultimate_upscale
spec.loader.exec_module(ultimate_upscale)

View File

@@ -0,0 +1 @@
.vscode

View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
ultimate-upscale-for-automatic1111
Copyright (C) 2023 Mirzam
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) 2023 Mirzam
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@@ -0,0 +1,119 @@
# Ultimate SD Upscale extension for [AUTOMATIC1111 Stable Diffusion web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui)
Now you have the opportunity to use a large denoise (0.3-0.5) and not spawn many artifacts. Works on any video card, since you can use a 512x512 tile size and the image will converge.
News channel: https://t.me/usdunews
# Instructions
All instructions can be found on the project's [wiki](https://github.com/Coyote-A/ultimate-upscale-for-automatic1111/wiki).
# Refs
https://github.com/ssitu/ComfyUI_UltimateSDUpscale - Implementation for ComfyUI
# Examples
More on [wiki page](https://github.com/Coyote-A/ultimate-upscale-for-automatic1111/wiki/Examples)
<details>
<summary>E1</summary>
Original image
![Original](https://i.imgur.com/J8mRYOD.png)
2k upscaled. **Tile size**: 512, **Padding**: 32, **Mask blur**: 16, **Denoise**: 0.4
![2k upscale](https://i.imgur.com/0aKua4r.png)
</details>
<details>
<summary>E2</summary>
Original image
![Original](https://i.imgur.com/aALNI2w.png)
2k upscaled. **Tile size**: 768, **Padding**: 55, **Mask blur**: 20, **Denoise**: 0.35
![2k upscale](https://i.imgur.com/B5PHz0J.png)
4k upscaled. **Tile size**: 768, **Padding**: 55, **Mask blur**: 20, **Denoise**: 0.35
![4k upscale](https://i.imgur.com/tIUQ7TJ.jpg)
</details>
<details>
<summary>E3</summary>
Original image
![Original](https://i.imgur.com/AGtszA8.png)
4k upscaled. **Tile size**: 768, **Padding**: 55, **Mask blur**: 20, **Denoise**: 0.4
![4k upscale](https://i.imgur.com/LCYLfCs.jpg)
</details>
# API Usage
```javascript
{
"script_name" : "ultimate sd upscale",
"script_args" : [
null, // _ (not used)
512, // tile_width
512, // tile_height
8, // mask_blur
32, // padding
64, // seams_fix_width
0.35, // seams_fix_denoise
32, // seams_fix_padding
0, // upscaler_index
true, // save_upscaled_image a.k.a Upscaled
0, // redraw_mode
false, // save_seams_fix_image a.k.a Seams fix
8, // seams_fix_mask_blur
0, // seams_fix_type
0, // target_size_type
2048, // custom_width
2048, // custom_height
2 // custom_scale
]
}
```
upscaler_index
| Value | |
|:-------------:| -----:|
| 0 | None |
| 1 | Lanczos |
| 2 | Nearest |
| 3 | ESRGAN_4x |
| 4 | LDSR |
| 5 | R-ESRGAN_4x+ |
| 6 | R-ESRGAN 4x+ Anime6B |
| 7 | ScuNET GAN |
| 8 | ScuNET PSNR |
| 9 | SwinIR 4x |
redraw_mode
| Value | |
|:-------------:| -----:|
| 0 | Linear |
| 1 | Chess |
| 2 | None |
seams_fix_mask_blur
| Value | |
|:-------------:| -----:|
| 0 | None |
| 1 | BAND_PASS |
| 2 | HALF_TILE |
| 3 | HALF_TILE_PLUS_INTERSECTIONS |
seams_fix_type
| Value | |
|:-------------:| -----:|
| 0 | None |
| 1 | Band pass |
| 2 | Half tile offset pass |
| 3 | Half tile offset pass + intersections |
seams_fix_type
| Value | |
|:-------------:| -----:|
| 0 | From img2img2 settings |
| 1 | Custom size |
| 2 | Scale from image size |

View File

@@ -0,0 +1,569 @@
import math
import gradio as gr
from PIL import Image, ImageDraw, ImageOps
from modules import processing, shared, images, devices, scripts
from modules.processing import StableDiffusionProcessing
from modules.processing import Processed
from modules.shared import opts, state
from enum import Enum
elem_id_prefix = "ultimateupscale"
class USDUMode(Enum):
LINEAR = 0
CHESS = 1
NONE = 2
class USDUSFMode(Enum):
NONE = 0
BAND_PASS = 1
HALF_TILE = 2
HALF_TILE_PLUS_INTERSECTIONS = 3
class USDUpscaler():
def __init__(self, p, image, upscaler_index:int, save_redraw, save_seams_fix, tile_width, tile_height) -> None:
self.p:StableDiffusionProcessing = p
self.image:Image = image
self.scale_factor = math.ceil(max(p.width, p.height) / max(image.width, image.height))
self.upscaler = shared.sd_upscalers[upscaler_index]
self.redraw = USDURedraw()
self.redraw.save = save_redraw
self.redraw.tile_width = tile_width if tile_width > 0 else tile_height
self.redraw.tile_height = tile_height if tile_height > 0 else tile_width
self.seams_fix = USDUSeamsFix()
self.seams_fix.save = save_seams_fix
self.seams_fix.tile_width = tile_width if tile_width > 0 else tile_height
self.seams_fix.tile_height = tile_height if tile_height > 0 else tile_width
self.initial_info = None
self.rows = math.ceil(self.p.height / self.redraw.tile_height)
self.cols = math.ceil(self.p.width / self.redraw.tile_width)
def get_factor(self, num):
# Its just return, don't need elif
if num == 1:
return 2
if num % 4 == 0:
return 4
if num % 3 == 0:
return 3
if num % 2 == 0:
return 2
return 0
def get_factors(self):
scales = []
current_scale = 1
current_scale_factor = self.get_factor(self.scale_factor)
while current_scale_factor == 0:
self.scale_factor += 1
current_scale_factor = self.get_factor(self.scale_factor)
while current_scale < self.scale_factor:
current_scale_factor = self.get_factor(self.scale_factor // current_scale)
scales.append(current_scale_factor)
current_scale = current_scale * current_scale_factor
if current_scale_factor == 0:
break
self.scales = enumerate(scales)
def upscale(self):
# Log info
print(f"Canva size: {self.p.width}x{self.p.height}")
print(f"Image size: {self.image.width}x{self.image.height}")
print(f"Scale factor: {self.scale_factor}")
# Check upscaler is not empty
if self.upscaler.name == "None":
self.image = self.image.resize((self.p.width, self.p.height), resample=Image.LANCZOS)
return
# Get list with scale factors
self.get_factors()
# Upscaling image over all factors
for index, value in self.scales:
print(f"Upscaling iteration {index+1} with scale factor {value}")
self.image = self.upscaler.scaler.upscale(self.image, value, self.upscaler.data_path)
# Resize image to set values
self.image = self.image.resize((self.p.width, self.p.height), resample=Image.LANCZOS)
def setup_redraw(self, redraw_mode, padding, mask_blur):
self.redraw.mode = USDUMode(redraw_mode)
self.redraw.enabled = self.redraw.mode != USDUMode.NONE
self.redraw.padding = padding
self.p.mask_blur = mask_blur
def setup_seams_fix(self, padding, denoise, mask_blur, width, mode):
self.seams_fix.padding = padding
self.seams_fix.denoise = denoise
self.seams_fix.mask_blur = mask_blur
self.seams_fix.width = width
self.seams_fix.mode = USDUSFMode(mode)
self.seams_fix.enabled = self.seams_fix.mode != USDUSFMode.NONE
def save_image(self):
if type(self.p.prompt) != list:
images.save_image(self.image, self.p.outpath_samples, "", self.p.seed, self.p.prompt, opts.samples_format, info=self.initial_info, p=self.p)
else:
images.save_image(self.image, self.p.outpath_samples, "", self.p.seed, self.p.prompt[0], opts.samples_format, info=self.initial_info, p=self.p)
def calc_jobs_count(self):
redraw_job_count = (self.rows * self.cols) if self.redraw.enabled else 0
seams_job_count = 0
if self.seams_fix.mode == USDUSFMode.BAND_PASS:
seams_job_count = self.rows + self.cols - 2
elif self.seams_fix.mode == USDUSFMode.HALF_TILE:
seams_job_count = self.rows * (self.cols - 1) + (self.rows - 1) * self.cols
elif self.seams_fix.mode == USDUSFMode.HALF_TILE_PLUS_INTERSECTIONS:
seams_job_count = self.rows * (self.cols - 1) + (self.rows - 1) * self.cols + (self.rows - 1) * (self.cols - 1)
state.job_count = redraw_job_count + seams_job_count
def print_info(self):
print(f"Tile size: {self.redraw.tile_width}x{self.redraw.tile_height}")
print(f"Tiles amount: {self.rows * self.cols}")
print(f"Grid: {self.rows}x{self.cols}")
print(f"Redraw enabled: {self.redraw.enabled}")
print(f"Seams fix mode: {self.seams_fix.mode.name}")
def add_extra_info(self):
self.p.extra_generation_params["Ultimate SD upscale upscaler"] = self.upscaler.name
self.p.extra_generation_params["Ultimate SD upscale tile_width"] = self.redraw.tile_width
self.p.extra_generation_params["Ultimate SD upscale tile_height"] = self.redraw.tile_height
self.p.extra_generation_params["Ultimate SD upscale mask_blur"] = self.p.mask_blur
self.p.extra_generation_params["Ultimate SD upscale padding"] = self.redraw.padding
def process(self):
state.begin()
self.calc_jobs_count()
self.result_images = []
if self.redraw.enabled:
self.image = self.redraw.start(self.p, self.image, self.rows, self.cols)
self.initial_info = self.redraw.initial_info
self.result_images.append(self.image)
if self.redraw.save:
self.save_image()
if self.seams_fix.enabled:
self.image = self.seams_fix.start(self.p, self.image, self.rows, self.cols)
self.initial_info = self.seams_fix.initial_info
self.result_images.append(self.image)
if self.seams_fix.save:
self.save_image()
state.end()
class USDURedraw():
def init_draw(self, p, width, height):
p.inpaint_full_res = True
p.inpaint_full_res_padding = self.padding
p.width = math.ceil((self.tile_width+self.padding) / 64) * 64
p.height = math.ceil((self.tile_height+self.padding) / 64) * 64
mask = Image.new("L", (width, height), "black")
draw = ImageDraw.Draw(mask)
return mask, draw
def calc_rectangle(self, xi, yi):
x1 = xi * self.tile_width
y1 = yi * self.tile_height
x2 = xi * self.tile_width + self.tile_width
y2 = yi * self.tile_height + self.tile_height
return x1, y1, x2, y2
def linear_process(self, p, image, rows, cols):
mask, draw = self.init_draw(p, image.width, image.height)
for yi in range(rows):
for xi in range(cols):
if state.interrupted:
break
draw.rectangle(self.calc_rectangle(xi, yi), fill="white")
p.init_images = [image]
p.image_mask = mask
processed = processing.process_images(p)
draw.rectangle(self.calc_rectangle(xi, yi), fill="black")
if (len(processed.images) > 0):
image = processed.images[0]
p.width = image.width
p.height = image.height
self.initial_info = processed.infotext(p, 0)
return image
def chess_process(self, p, image, rows, cols):
mask, draw = self.init_draw(p, image.width, image.height)
tiles = []
# calc tiles colors
for yi in range(rows):
for xi in range(cols):
if state.interrupted:
break
if xi == 0:
tiles.append([])
color = xi % 2 == 0
if yi > 0 and yi % 2 != 0:
color = not color
tiles[yi].append(color)
for yi in range(len(tiles)):
for xi in range(len(tiles[yi])):
if state.interrupted:
break
if not tiles[yi][xi]:
tiles[yi][xi] = not tiles[yi][xi]
continue
tiles[yi][xi] = not tiles[yi][xi]
draw.rectangle(self.calc_rectangle(xi, yi), fill="white")
p.init_images = [image]
p.image_mask = mask
processed = processing.process_images(p)
draw.rectangle(self.calc_rectangle(xi, yi), fill="black")
if (len(processed.images) > 0):
image = processed.images[0]
for yi in range(len(tiles)):
for xi in range(len(tiles[yi])):
if state.interrupted:
break
if not tiles[yi][xi]:
continue
draw.rectangle(self.calc_rectangle(xi, yi), fill="white")
p.init_images = [image]
p.image_mask = mask
processed = processing.process_images(p)
draw.rectangle(self.calc_rectangle(xi, yi), fill="black")
if (len(processed.images) > 0):
image = processed.images[0]
p.width = image.width
p.height = image.height
self.initial_info = processed.infotext(p, 0)
return image
def start(self, p, image, rows, cols):
self.initial_info = None
if self.mode == USDUMode.LINEAR:
return self.linear_process(p, image, rows, cols)
if self.mode == USDUMode.CHESS:
return self.chess_process(p, image, rows, cols)
class USDUSeamsFix():
def init_draw(self, p):
self.initial_info = None
p.width = math.ceil((self.tile_width+self.padding) / 64) * 64
p.height = math.ceil((self.tile_height+self.padding) / 64) * 64
def half_tile_process(self, p, image, rows, cols):
self.init_draw(p)
processed = None
gradient = Image.linear_gradient("L")
row_gradient = Image.new("L", (self.tile_width, self.tile_height), "black")
row_gradient.paste(gradient.resize(
(self.tile_width, self.tile_height//2), resample=Image.BICUBIC), (0, 0))
row_gradient.paste(gradient.rotate(180).resize(
(self.tile_width, self.tile_height//2), resample=Image.BICUBIC),
(0, self.tile_height//2))
col_gradient = Image.new("L", (self.tile_width, self.tile_height), "black")
col_gradient.paste(gradient.rotate(90).resize(
(self.tile_width//2, self.tile_height), resample=Image.BICUBIC), (0, 0))
col_gradient.paste(gradient.rotate(270).resize(
(self.tile_width//2, self.tile_height), resample=Image.BICUBIC), (self.tile_width//2, 0))
p.denoising_strength = self.denoise
p.mask_blur = self.mask_blur
for yi in range(rows-1):
for xi in range(cols):
if state.interrupted:
break
p.width = self.tile_width
p.height = self.tile_height
p.inpaint_full_res = True
p.inpaint_full_res_padding = self.padding
mask = Image.new("L", (image.width, image.height), "black")
mask.paste(row_gradient, (xi*self.tile_width, yi*self.tile_height + self.tile_height//2))
p.init_images = [image]
p.image_mask = mask
processed = processing.process_images(p)
if (len(processed.images) > 0):
image = processed.images[0]
for yi in range(rows):
for xi in range(cols-1):
if state.interrupted:
break
p.width = self.tile_width
p.height = self.tile_height
p.inpaint_full_res = True
p.inpaint_full_res_padding = self.padding
mask = Image.new("L", (image.width, image.height), "black")
mask.paste(col_gradient, (xi*self.tile_width+self.tile_width//2, yi*self.tile_height))
p.init_images = [image]
p.image_mask = mask
processed = processing.process_images(p)
if (len(processed.images) > 0):
image = processed.images[0]
p.width = image.width
p.height = image.height
if processed is not None:
self.initial_info = processed.infotext(p, 0)
return image
def half_tile_process_corners(self, p, image, rows, cols):
fixed_image = self.half_tile_process(p, image, rows, cols)
processed = None
self.init_draw(p)
gradient = Image.radial_gradient("L").resize(
(self.tile_width, self.tile_height), resample=Image.BICUBIC)
gradient = ImageOps.invert(gradient)
p.denoising_strength = self.denoise
#p.mask_blur = 0
p.mask_blur = self.mask_blur
for yi in range(rows-1):
for xi in range(cols-1):
if state.interrupted:
break
p.width = self.tile_width
p.height = self.tile_height
p.inpaint_full_res = True
p.inpaint_full_res_padding = 0
mask = Image.new("L", (fixed_image.width, fixed_image.height), "black")
mask.paste(gradient, (xi*self.tile_width + self.tile_width//2,
yi*self.tile_height + self.tile_height//2))
p.init_images = [fixed_image]
p.image_mask = mask
processed = processing.process_images(p)
if (len(processed.images) > 0):
fixed_image = processed.images[0]
p.width = fixed_image.width
p.height = fixed_image.height
if processed is not None:
self.initial_info = processed.infotext(p, 0)
return fixed_image
def band_pass_process(self, p, image, cols, rows):
self.init_draw(p)
processed = None
p.denoising_strength = self.denoise
p.mask_blur = 0
gradient = Image.linear_gradient("L")
mirror_gradient = Image.new("L", (256, 256), "black")
mirror_gradient.paste(gradient.resize((256, 128), resample=Image.BICUBIC), (0, 0))
mirror_gradient.paste(gradient.rotate(180).resize((256, 128), resample=Image.BICUBIC), (0, 128))
row_gradient = mirror_gradient.resize((image.width, self.width), resample=Image.BICUBIC)
col_gradient = mirror_gradient.rotate(90).resize((self.width, image.height), resample=Image.BICUBIC)
for xi in range(1, rows):
if state.interrupted:
break
p.width = self.width + self.padding * 2
p.height = image.height
p.inpaint_full_res = True
p.inpaint_full_res_padding = self.padding
mask = Image.new("L", (image.width, image.height), "black")
mask.paste(col_gradient, (xi * self.tile_width - self.width // 2, 0))
p.init_images = [image]
p.image_mask = mask
processed = processing.process_images(p)
if (len(processed.images) > 0):
image = processed.images[0]
for yi in range(1, cols):
if state.interrupted:
break
p.width = image.width
p.height = self.width + self.padding * 2
p.inpaint_full_res = True
p.inpaint_full_res_padding = self.padding
mask = Image.new("L", (image.width, image.height), "black")
mask.paste(row_gradient, (0, yi * self.tile_height - self.width // 2))
p.init_images = [image]
p.image_mask = mask
processed = processing.process_images(p)
if (len(processed.images) > 0):
image = processed.images[0]
p.width = image.width
p.height = image.height
if processed is not None:
self.initial_info = processed.infotext(p, 0)
return image
def start(self, p, image, rows, cols):
if USDUSFMode(self.mode) == USDUSFMode.BAND_PASS:
return self.band_pass_process(p, image, rows, cols)
elif USDUSFMode(self.mode) == USDUSFMode.HALF_TILE:
return self.half_tile_process(p, image, rows, cols)
elif USDUSFMode(self.mode) == USDUSFMode.HALF_TILE_PLUS_INTERSECTIONS:
return self.half_tile_process_corners(p, image, rows, cols)
else:
return image
class Script(scripts.Script):
def title(self):
return "Ultimate SD upscale"
def show(self, is_img2img):
return is_img2img
def ui(self, is_img2img):
target_size_types = [
"From img2img2 settings",
"Custom size",
"Scale from image size"
]
seams_fix_types = [
"None",
"Band pass",
"Half tile offset pass",
"Half tile offset pass + intersections"
]
redrow_modes = [
"Linear",
"Chess",
"None"
]
info = gr.HTML(
"<p style=\"margin-bottom:0.75em\">Will upscale the image depending on the selected target size type</p>")
with gr.Row():
target_size_type = gr.Dropdown(label="Target size type", elem_id=f"{elem_id_prefix}_target_size_type", choices=[k for k in target_size_types], type="index",
value=next(iter(target_size_types)))
custom_width = gr.Slider(label='Custom width', elem_id=f"{elem_id_prefix}_custom_width", minimum=64, maximum=8192, step=64, value=2048, visible=False, interactive=True)
custom_height = gr.Slider(label='Custom height', elem_id=f"{elem_id_prefix}_custom_height", minimum=64, maximum=8192, step=64, value=2048, visible=False, interactive=True)
custom_scale = gr.Slider(label='Scale', elem_id=f"{elem_id_prefix}_custom_scale", minimum=1, maximum=16, step=0.01, value=2, visible=False, interactive=True)
gr.HTML("<p style=\"margin-bottom:0.75em\">Redraw options:</p>")
with gr.Row():
upscaler_index = gr.Radio(label='Upscaler', elem_id=f"{elem_id_prefix}_upscaler_index", choices=[x.name for x in shared.sd_upscalers],
value=shared.sd_upscalers[0].name, type="index")
with gr.Row():
redraw_mode = gr.Dropdown(label="Type", elem_id=f"{elem_id_prefix}_redraw_mode", choices=[k for k in redrow_modes], type="index", value=next(iter(redrow_modes)))
tile_width = gr.Slider(elem_id=f"{elem_id_prefix}_tile_width", minimum=0, maximum=2048, step=64, label='Tile width', value=512)
tile_height = gr.Slider(elem_id=f"{elem_id_prefix}_tile_height", minimum=0, maximum=2048, step=64, label='Tile height', value=0)
mask_blur = gr.Slider(elem_id=f"{elem_id_prefix}_mask_blur", label='Mask blur', minimum=0, maximum=64, step=1, value=8)
padding = gr.Slider(elem_id=f"{elem_id_prefix}_padding", label='Padding', minimum=0, maximum=512, step=1, value=32)
gr.HTML("<p style=\"margin-bottom:0.75em\">Seams fix:</p>")
with gr.Row():
seams_fix_type = gr.Dropdown(label="Type", elem_id=f"{elem_id_prefix}_seams_fix_type", choices=[k for k in seams_fix_types], type="index", value=next(iter(seams_fix_types)))
seams_fix_denoise = gr.Slider(label='Denoise', elem_id=f"{elem_id_prefix}_seams_fix_denoise", minimum=0, maximum=1, step=0.01, value=0.35, visible=False, interactive=True)
seams_fix_width = gr.Slider(label='Width', elem_id=f"{elem_id_prefix}_seams_fix_width", minimum=0, maximum=128, step=1, value=64, visible=False, interactive=True)
seams_fix_mask_blur = gr.Slider(label='Mask blur', elem_id=f"{elem_id_prefix}_seams_fix_mask_blur", minimum=0, maximum=64, step=1, value=4, visible=False, interactive=True)
seams_fix_padding = gr.Slider(label='Padding', elem_id=f"{elem_id_prefix}_seams_fix_padding", minimum=0, maximum=128, step=1, value=16, visible=False, interactive=True)
gr.HTML("<p style=\"margin-bottom:0.75em\">Save options:</p>")
with gr.Row():
save_upscaled_image = gr.Checkbox(label="Upscaled", elem_id=f"{elem_id_prefix}_save_upscaled_image", value=True)
save_seams_fix_image = gr.Checkbox(label="Seams fix", elem_id=f"{elem_id_prefix}_save_seams_fix_image", value=False)
def select_fix_type(fix_index):
all_visible = fix_index != 0
mask_blur_visible = fix_index == 2 or fix_index == 3
width_visible = fix_index == 1
return [gr.update(visible=all_visible),
gr.update(visible=width_visible),
gr.update(visible=mask_blur_visible),
gr.update(visible=all_visible)]
seams_fix_type.change(
fn=select_fix_type,
inputs=seams_fix_type,
outputs=[seams_fix_denoise, seams_fix_width, seams_fix_mask_blur, seams_fix_padding]
)
def select_scale_type(scale_index):
is_custom_size = scale_index == 1
is_custom_scale = scale_index == 2
return [gr.update(visible=is_custom_size),
gr.update(visible=is_custom_size),
gr.update(visible=is_custom_scale),
]
target_size_type.change(
fn=select_scale_type,
inputs=target_size_type,
outputs=[custom_width, custom_height, custom_scale]
)
def init_field(scale_name):
try:
scale_index = target_size_types.index(scale_name)
custom_width.visible = custom_height.visible = scale_index == 1
custom_scale.visible = scale_index == 2
except:
pass
target_size_type.init_field = init_field
return [info, tile_width, tile_height, mask_blur, padding, seams_fix_width, seams_fix_denoise, seams_fix_padding,
upscaler_index, save_upscaled_image, redraw_mode, save_seams_fix_image, seams_fix_mask_blur,
seams_fix_type, target_size_type, custom_width, custom_height, custom_scale]
def run(self, p, _, tile_width, tile_height, mask_blur, padding, seams_fix_width, seams_fix_denoise, seams_fix_padding,
upscaler_index, save_upscaled_image, redraw_mode, save_seams_fix_image, seams_fix_mask_blur,
seams_fix_type, target_size_type, custom_width, custom_height, custom_scale):
# Init
processing.fix_seed(p)
devices.torch_gc()
p.do_not_save_grid = True
p.do_not_save_samples = True
p.inpaint_full_res = False
p.inpainting_fill = 1
p.n_iter = 1
p.batch_size = 1
seed = p.seed
# Init image
init_img = p.init_images[0]
if init_img == None:
return Processed(p, [], seed, "Empty image")
init_img = images.flatten(init_img, opts.img2img_background_color)
#override size
if target_size_type == 1:
p.width = custom_width
p.height = custom_height
if target_size_type == 2:
p.width = math.ceil((init_img.width * custom_scale) / 64) * 64
p.height = math.ceil((init_img.height * custom_scale) / 64) * 64
# Upscaling
upscaler = USDUpscaler(p, init_img, upscaler_index, save_upscaled_image, save_seams_fix_image, tile_width, tile_height)
upscaler.upscale()
# Drawing
upscaler.setup_redraw(redraw_mode, padding, mask_blur)
upscaler.setup_seams_fix(seams_fix_padding, seams_fix_denoise, seams_fix_mask_blur, seams_fix_width, seams_fix_type)
upscaler.print_info()
upscaler.add_extra_info()
upscaler.process()
result_images = upscaler.result_images
return Processed(p, result_images, seed, upscaler.initial_info if upscaler.initial_info is not None else "")

View File

@@ -0,0 +1 @@
sample_images/

View File

@@ -0,0 +1,49 @@
# Running Tests
This directory contains tests for ComfyUI_UltimateSDUpscale.
## Prerequisites
- These tests assume that ComfyUI is installed using a virtual environment
- Activate the ComfyUI virtual environment before running tests
- The checkpoint `v1-5-pruned-emaonly-fp16.safetensors` is available
- The upscale model `4x-UltraSharp.pth` is available
## Running Tests
### Using the convenience scripts (works from repo root or test directory):
**Linux/Mac (Bash):**
```bash
./test/run_tests.sh # From repo root
./run_tests.sh # From test directory
```
run_tests.sh will forward all arguments into pytest.
### Using pytest directly (must be in test directory):
```bash
cd test
pytest # Run all tests
pytest -v # Verbose
```
### Common pytest options:
- `-v` - Verbose output
- `-s` - Show print statements
- `--log-cli-level=INFO` - Show info-level logs
- `-k PATTERN` - Run tests matching pattern
- `--lf` - Run last failed tests
## Test Structure
- `conftest.py` - Pytest configuration, fixtures, and path setup
- `sample_images/` - Generated test images for visual inspection
- `test_images/` - Reference images used as inputs or expected outputs
## Troubleshooting
If you encounter import errors:
1. Make sure you're running from the `test/` directory
2. Verify the virtual environment is activated

View File

@@ -0,0 +1,9 @@
import pathlib
class DirectoryConfig:
"""Helper class for test directories."""
def __init__(self, test_images: pathlib.Path, sample_images: pathlib.Path):
self.test_images = test_images
self.sample_images = sample_images

View File

@@ -0,0 +1,174 @@
"""
Setup for the ComfyUI engine and shared test fixtures.
"""
import os
import sys
from pathlib import Path
import pytest
import asyncio
import logging
from setup_utils import SilenceLogs, execute
from hf_downloader import download_test_images
from configs import DirectoryConfig
# Because of manipulations to sys.path, non-packaged imports should be delayed to avoid import issues
#
# # Configuration
#
TEST_CHECKPOINT = "v1-5-pruned-emaonly-fp16.safetensors"
TEST_UPSCALE_MODEL = "4x-UltraSharp.pth"
SAMPLE_IMAGE_SUBDIR = "sample_images"
TEST_IMAGE_SUBDIR = "test_images"
# conftest.py is in repo_root/test/ directory
REPO_ROOT = Path(__file__).parent.parent.resolve()
COMFYUI_ROOT = REPO_ROOT.parent.parent.resolve()
# Make sure the repo root is in sys.path for imports
# Ensure submodule root is in path for test imports
if str(REPO_ROOT) not in sys.path:
sys.path.insert(0, str(REPO_ROOT))
# Ensure ComfyUI path is set up
if str(COMFYUI_ROOT) not in sys.path:
sys.path.insert(0, str(COMFYUI_ROOT))
# Session scoped fixtures
from fixtures_images import base_image
def pytest_configure(config):
"""Called before test collection begins."""
# Download test images
download_test_images(
repo_id="ssitu/ultimatesdupscale_test",
save_dir=(REPO_ROOT / "test" / "test_images").resolve(),
repo_folder="test_images",
)
from comfy.cli_args import args
# args.cpu = True # Force CPU mode for tests
# args.force_fp16 = True # Force float16 mode for tests
args.disable_all_custom_nodes = True
# Assumes the name of the custom node folder is ComfyUI_UltimateSDUpscale
args.whitelist_custom_nodes = ["ComfyUI_UltimateSDUpscale"]
#
# # Path Setup
#
def _setup_comfyui_paths():
"""Configure ComfyUI folder paths for testing."""
# Ensure modules containing a utils.py are NOT in sys.path
# The comfy directory must be removed to prevent comfy/utils.py from shadowing
# ComfyUI's utils/ package directory when we import utils.extra_config
to_remove = [
str(COMFYUI_ROOT / "comfy"),
]
for path_to_remove in to_remove:
while path_to_remove in sys.path:
sys.path.remove(path_to_remove)
# Ensure ComfyUI is in path
if str(COMFYUI_ROOT) not in sys.path:
sys.path.insert(0, str(COMFYUI_ROOT))
# Apply custom paths
# main.py will trigger a warning that torch was already imported, probably by pytest. Shouldn't be a problem as far as I know.
from main import apply_custom_paths
apply_custom_paths()
#
# # Fixtures
#
@pytest.fixture(scope="session")
def comfyui_initialized():
"""Initialize ComfyUI nodes once per test session."""
from nodes import init_extra_nodes
_setup_comfyui_paths()
async def _init():
with SilenceLogs():
await init_extra_nodes(init_api_nodes=False)
asyncio.run(_init())
yield True
@pytest.fixture(scope="session")
def node_classes(comfyui_initialized):
"""Get ComfyUI node class mappings."""
from nodes import NODE_CLASS_MAPPINGS
return NODE_CLASS_MAPPINGS
@pytest.fixture(scope="session")
def test_checkpoint():
"""Find and return a valid test checkpoint."""
import folder_paths
checkpoints = folder_paths.get_filename_list("checkpoints")
# TODO: Should probably use a hash instead of matching the filename
if TEST_CHECKPOINT not in checkpoints:
pytest.skip(f"No test checkpoint found. Please add {TEST_CHECKPOINT}")
return TEST_CHECKPOINT
@pytest.fixture(scope="session")
def loaded_checkpoint(comfyui_initialized, test_checkpoint, node_classes):
"""Load checkpoint and return (model, clip, vae) tuple."""
import torch
with torch.inference_mode():
CheckpointLoaderSimple = node_classes["CheckpointLoaderSimple"]
model, clip, vae = execute(CheckpointLoaderSimple, test_checkpoint)
return model, clip, vae
@pytest.fixture(scope="session")
def upscale_model(comfyui_initialized, node_classes):
"""Load the first available upscale model."""
import torch
import folder_paths
UpscaleModelLoader = node_classes["UpscaleModelLoader"]
upscale_models = folder_paths.get_filename_list("upscale_models")
# TODO: Should probably use a hash instead of matching the filename
if TEST_UPSCALE_MODEL not in upscale_models:
pytest.skip("No upscale models found")
model_name = upscale_models[0]
with torch.inference_mode():
(model,) = execute(UpscaleModelLoader, model_name)
return model
@pytest.fixture(scope="session")
def test_dirs():
"""Return paths to test and sample image directories."""
test_dir = REPO_ROOT / "test"
test_image_dir = test_dir / TEST_IMAGE_SUBDIR
sample_image_dir = test_dir / SAMPLE_IMAGE_SUBDIR
sample_image_dir.mkdir(exist_ok=True)
return DirectoryConfig(
test_images=test_image_dir,
sample_images=sample_image_dir,
)
@pytest.fixture(scope="session")
def seed():
"""Default seed for reproducible tests."""
return 1

View File

@@ -0,0 +1,70 @@
"""
Fixtures for base images.
"""
import pathlib
import pytest
import torch
from setup_utils import execute
from io_utils import save_image, load_image
from configs import DirectoryConfig
# Image file names
EXT = ".jpg"
CATEGORY = pathlib.Path("base_images")
BASE_IMAGE_1_NAME = "main1_sd15" + EXT
BASE_IMAGE_2_NAME = "main2_sd15" + EXT
# Prepend category path
BASE_IMAGE_1 = CATEGORY / BASE_IMAGE_1_NAME
BASE_IMAGE_2 = CATEGORY / BASE_IMAGE_2_NAME
@pytest.fixture(scope="session")
def base_image(loaded_checkpoint, seed, test_dirs: DirectoryConfig, node_classes):
"""Generate a base image for upscaling tests."""
EmptyLatentImage = node_classes["EmptyLatentImage"]
CLIPTextEncode = node_classes["CLIPTextEncode"]
KSampler = node_classes["KSampler"]
VAEDecode = node_classes["VAEDecode"]
model, clip, vae = loaded_checkpoint
with torch.inference_mode():
(empty_latent,) = execute(EmptyLatentImage, width=512, height=512, batch_size=2)
(positive,) = execute(
CLIPTextEncode,
text="beautiful scenery nature glass bottle landscape, , purple galaxy bottle,",
clip=clip,
)
(negative,) = execute(CLIPTextEncode, text="text, watermark", clip=clip)
(samples,) = execute(
KSampler,
model=model,
positive=positive,
negative=negative,
latent_image=empty_latent,
seed=seed,
steps=10,
cfg=8,
sampler_name="dpmpp_2m",
scheduler="karras",
denoise=1.0,
)
(image,) = execute(VAEDecode, samples=samples, vae=vae)
# Save base images
sample_dir = test_dirs.sample_images
base_img1_path = sample_dir / BASE_IMAGE_1
base_img2_path = sample_dir / BASE_IMAGE_2
save_image(image[0:1], base_img1_path)
save_image(image[1:2], base_img2_path)
# Load images back as tensors to account for compression
image = torch.cat([load_image(base_img1_path), load_image(base_img2_path)])
return image, positive, negative

View File

@@ -0,0 +1,85 @@
import logging
import re
import urllib.parse
import urllib.request
from pathlib import Path
logging.basicConfig(level=logging.INFO)
def _fetch_hf_html(repo_id: str, folder_path: str) -> str:
"""Fetch HTML from HuggingFace tree page."""
url = f"https://huggingface.co/datasets/{repo_id}/tree/main/{folder_path}"
with urllib.request.urlopen(url) as response:
return response.read().decode("utf-8")
def list_hf_subfolders(repo_id: str, folder_path: str) -> list[str]:
"""List subfolders in a HuggingFace dataset folder."""
try:
html = _fetch_hf_html(repo_id, folder_path)
pattern = rf'/datasets/{repo_id}/tree/main/({folder_path}/[^"/?]+)'
return sorted(set(re.findall(pattern, html)))
except Exception as e:
logging.error(f"Failed to list subfolders in {folder_path}: {e}")
return []
def list_hf_files(
repo_id: str,
folder_path: str,
extensions: tuple = (".jpg", ".jpeg", ".png", ".webp"),
) -> list[str]:
"""List image files in a HuggingFace dataset folder."""
try:
html = _fetch_hf_html(repo_id, folder_path)
pattern = rf'/datasets/{repo_id}/blob/main/({folder_path}/[^"]+?({"|".join(e for e in extensions)}))'
return [urllib.parse.unquote(match[0]) for match in re.findall(pattern, html)]
except Exception as e:
logging.error(f"Failed to list files in {folder_path}: {e}")
return []
def download_test_images(save_dir: Path, repo_folder: str, repo_id: str) -> Path:
"""Download the test_images/ folder from the HF test dataset repo"""
# Discover all subfolders and collect files
subfolders = list_hf_subfolders(repo_id, repo_folder)
if not subfolders:
logging.warning(f"No subfolders found in {repo_folder}")
return save_dir
all_files = [f for folder in subfolders for f in list_hf_files(repo_id, folder)]
if not all_files:
logging.warning(f"No image files found in {repo_folder}")
return save_dir
logging.info(f"Found {len(all_files)} files from {len(subfolders)} folders")
# Download files, preserving folder structure
save_dir_path = Path(save_dir)
downloaded = 0
skipped = 0
for file_path in all_files:
relative_path = Path(file_path).relative_to(repo_folder)
save_path = save_dir_path / relative_path
if save_path.exists():
logging.info(f"Skipping {relative_path} (already exists)")
skipped += 1
continue
save_path.parent.mkdir(parents=True, exist_ok=True)
url = f"https://huggingface.co/datasets/{repo_id}/resolve/main/{file_path}"
logging.info(f"Downloading {relative_path}...")
urllib.request.urlretrieve(url, save_path)
downloaded += 1
logging.info(f"Downloaded {downloaded} files, skipped {skipped} existing files")
return save_dir_path
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
download_test_images(
repo_id="ssitu/ultimatesdupscale_test",
save_dir=Path("./test/test_images/"),
repo_folder="test_images",
)

View File

@@ -0,0 +1,20 @@
import pathlib
from PIL import Image
import usdu_utils
def save_image(tensor, path: pathlib.Path):
"""The goto function to save a tensor image to the sampled images directory."""
assert tensor.ndim == 3 or (tensor.ndim == 4 and tensor.shape[0] == 1), (
f"Expected a 3D tensor (H, W, C) or (1, H, W, C), got {tensor.ndim=}"
)
if tensor.ndim == 3:
tensor = tensor.unsqueeze(0)
image = usdu_utils.tensor_to_pil(tensor.cpu())
path.parent.mkdir(parents=True, exist_ok=True)
image.save(path, quality=75, optimize=True)
def load_image(path: pathlib.Path, device=None):
"""Load an image from disk and convert it to a tensor."""
return usdu_utils.pil_to_tensor(Image.open(path)).to(device=device)

View File

@@ -0,0 +1,9 @@
[pytest]
# Filter out warnings that are unavoidable or from external libraries
filterwarnings =
# Ignore CUDA compatibility warnings (hardware limitation)
ignore::UserWarning:torch.cuda
# Ignore Swig type warnings from importlib by pytest
ignore:builtin type.*has no __module__ attribute:DeprecationWarning:importlib._bootstrap:488
ignore:builtin type.*has no __module__ attribute:DeprecationWarning:sys:0

View File

@@ -0,0 +1,18 @@
#!/bin/bash
# Can be run from either the repo root or the test directory
# Example usage: sh ./run_tests.sh [additional pytest arguments]
# Get the script directory
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
# Determine the test directory
if [[ "$(basename "$SCRIPT_DIR")" == "test" ]]; then
# Script is in test directory
TEST_DIR="$SCRIPT_DIR"
else
# Script is in repo root
TEST_DIR="$SCRIPT_DIR/test"
fi
cd "$TEST_DIR"
python -m pytest "$@"

View File

@@ -0,0 +1,20 @@
import logging
class SilenceLogs:
"""Context manager to temporarily silence logging."""
def __enter__(self):
logging.disable(logging.CRITICAL)
return self
def __exit__(self, exc_type, exc_value, traceback):
logging.disable(logging.NOTSET)
def execute(node, *args, **kwargs):
"""Execute a ComfyUI node, handling both V3 and legacy schemas."""
if hasattr(node, "execute"):
return node.execute(*args, **kwargs)
else:
return getattr(node(), node.FUNCTION)(*args, **kwargs)

View File

@@ -0,0 +1,27 @@
import torchvision.transforms.functional as TF
def img_tensor_mae(tensor1, tensor2):
"""Calculate the mean absolute difference between two image tensors."""
# Remove batch dimensions if present
tensor1 = tensor1.squeeze(0).cpu()
tensor2 = tensor2.squeeze(0).cpu()
if tensor1.shape != tensor2.shape:
raise ValueError(
f"Tensors must have the same shape for comparison. Got {tensor1.shape=} and {tensor2.shape=}."
)
return (tensor1 - tensor2).abs().mean().item()
def blur(tensor, kernel_size=9, sigma=None):
"""Apply Gaussian blur to an image tensor."""
# [1, H, W, C] -> [1, C, H, W]
if tensor.ndim == 4:
tensor = tensor.permute(0, 3, 1, 2)
elif tensor.ndim == 3:
tensor = tensor.permute(2, 0, 1).unsqueeze(0)
else:
raise ValueError(f"Expected a 3D or 4D tensor, got {tensor.ndim=}")
return TF.gaussian_blur(tensor, kernel_size=kernel_size, sigma=sigma).permute( # type: ignore
0, 2, 3, 1
)

View File

@@ -0,0 +1,31 @@
"""
Tests for base image generation.
"""
import logging
from configs import DirectoryConfig
from tensor_utils import img_tensor_mae, blur
from io_utils import load_image
from fixtures_images import BASE_IMAGE_1, BASE_IMAGE_2
def test_base_image_matches_reference(base_image, test_dirs: DirectoryConfig):
"""
Verify generated base images match reference images.
This is just to check if the checkpoint and generation pipeline are as expected for the tests dependent on their behavior.
"""
logger = logging.getLogger("test_base_image_matches_reference")
image, _, _ = base_image
test_image_dir = test_dirs.test_images
im1 = image[0:1]
im2 = image[1:2]
test_im1 = load_image(test_image_dir / BASE_IMAGE_1)
test_im2 = load_image(test_image_dir / BASE_IMAGE_2)
# Reduce high-frequency noise differences with gaussian blur. Using perceptual metrics are probably overkill.
diff1 = img_tensor_mae(blur(im1), blur(test_im1))
diff2 = img_tensor_mae(blur(im2), blur(test_im2))
logger.info(f"Base Image Diff1: {diff1}, Diff2: {diff2}")
assert diff1 < 0.05, "Image 1 does not match its test image."
assert diff2 < 0.05, "Image 2 does not match its test image."

View File

@@ -0,0 +1,96 @@
"""
Test using controlnet in the upscaling workflow.
"""
import logging
import pathlib
import pytest
import torch
from setup_utils import execute
from tensor_utils import img_tensor_mae, blur
from io_utils import save_image, load_image
from configs import DirectoryConfig
from fixtures_images import EXT
CATEGORY = pathlib.Path(pathlib.Path(__file__).stem.removeprefix("test_"))
CONTROLNET_TILE_OUTPUT_IMAGE = "controlnet_tile" + EXT
TEST_CONTROLNET_TILE_MODEL = "control_v11f1e_sd15_tile.pth"
class TestControlNet:
"""Integration tests for the upscaling workflow with ControlNet."""
@pytest.fixture(scope="class")
def controlnet_upscaled_image(
self,
base_image,
loaded_checkpoint,
upscale_model,
node_classes,
seed,
test_dirs,
):
"""Generate upscaled images using ControlNet."""
image, positive, negative = base_image
model, clip, vae = loaded_checkpoint
image = image[0:1]
(controlnet_tile_model,) = execute(
node_classes["ControlNetLoader"], TEST_CONTROLNET_TILE_MODEL
)
(positive,) = execute(
node_classes["ControlNetApply"], positive, controlnet_tile_model, image, 1.0
)
with torch.inference_mode():
# Run upscale with ControlNet
usdu = node_classes["UltimateSDUpscale"]
(upscaled,) = usdu().upscale(
image=image,
model=model,
positive=positive,
negative=negative,
vae=vae,
upscale_by=2.0,
seed=seed,
steps=5,
cfg=8,
sampler_name="euler",
scheduler="normal",
denoise=1.0,
upscale_model=None,
mode_type="Chess",
tile_width=512,
tile_height=512,
mask_blur=8,
tile_padding=32,
seam_fix_mode="None",
seam_fix_denoise=1.0,
seam_fix_width=64,
seam_fix_mask_blur=8,
seam_fix_padding=16,
force_uniform_tiles=True,
tiled_decode=False,
)
# Save and reload sample image
sample_dir = test_dirs.sample_images
filename = CATEGORY / CONTROLNET_TILE_OUTPUT_IMAGE
save_image(upscaled[0], sample_dir / filename)
upscaled = load_image(sample_dir / filename)
return upscaled
def test_controlnet_upscaled_image_matches_reference(
self, controlnet_upscaled_image, test_dirs: DirectoryConfig
):
"""
Verify ControlNet upscaled images match reference images.
"""
logger = logging.getLogger("test_controlnet_upscaled_image_matches_reference")
test_img_dir = test_dirs.test_images
test_img = load_image(test_img_dir / CATEGORY / CONTROLNET_TILE_OUTPUT_IMAGE)
# Reduce high-frequency noise differences with gaussian blur
diff = img_tensor_mae(blur(controlnet_upscaled_image), blur(test_img))
logger.info(f"ControlNet Upscaled Image Diff: {diff}")
assert diff < 0.05, "ControlNet upscaled image does not match its test image."

View File

@@ -0,0 +1,246 @@
"""
Tests a common workflow for UltimateSDUpscale.
"""
import logging
import pathlib
import torch
from setup_utils import execute
from tensor_utils import img_tensor_mae, blur
from io_utils import save_image, load_image
from configs import DirectoryConfig
from fixtures_images import EXT
# Image file names
CATEGORY = pathlib.Path(pathlib.Path(__file__).stem.removeprefix("test_"))
IMAGE_1 = CATEGORY / ("main1_sd15_upscaled" + EXT)
IMAGE_2 = CATEGORY / ("main2_sd15_upscaled" + EXT)
NO_UPSCALE_IMAGE_1 = CATEGORY / ("main1_sd15_upscaled_no_upscale" + EXT)
NO_UPSCALE_IMAGE_2 = CATEGORY / ("main2_sd15_upscaled_no_upscale" + EXT)
CUSTOM_SAMPLER_IMAGE_1 = CATEGORY / ("main1_sd15_upscaled_custom_sampler" + EXT)
CUSTOM_SAMPLER_IMAGE_2 = CATEGORY / ("main2_sd15_upscaled_custom_sampler" + EXT)
class TestMainWorkflow:
"""Integration tests for the main upscaling workflow."""
def test_upscale(
self,
base_image,
loaded_checkpoint,
upscale_model,
node_classes,
seed,
test_dirs: DirectoryConfig,
):
"""Generate upscaled images using standard workflow."""
image, positive, negative = base_image
model, clip, vae = loaded_checkpoint
with torch.inference_mode():
usdu = node_classes["UltimateSDUpscale"]
(upscaled,) = usdu().upscale(
image=image,
model=model,
positive=positive,
negative=negative,
vae=vae,
upscale_by=2.00000004, # Test small float difference doesn't add extra tiles
seed=seed,
steps=10,
cfg=8,
sampler_name="euler",
scheduler="normal",
denoise=0.2,
upscale_model=upscale_model,
mode_type="Chess",
tile_width=512,
tile_height=512,
mask_blur=8,
tile_padding=32,
seam_fix_mode="None",
seam_fix_denoise=1.0,
seam_fix_width=64,
seam_fix_mask_blur=8,
seam_fix_padding=16,
force_uniform_tiles=True,
tiled_decode=False,
)
# Save images
sample_dir = test_dirs.sample_images
upscaled_img1_path = sample_dir / IMAGE_1
upscaled_img2_path = sample_dir / IMAGE_2
save_image(upscaled[0], upscaled_img1_path)
save_image(upscaled[1], upscaled_img2_path)
# Load to account for compression
upscaled = torch.cat(
[load_image(upscaled_img1_path), load_image(upscaled_img2_path)]
)
# Verify results
logger = logging.getLogger("test_upscale")
test_image_dir = test_dirs.test_images
im1_upscaled = upscaled[0]
im2_upscaled = upscaled[1]
test_im1_upscaled = load_image(test_image_dir / IMAGE_1)
test_im2_upscaled = load_image(test_image_dir / IMAGE_2)
diff1 = img_tensor_mae(blur(im1_upscaled), blur(test_im1_upscaled))
diff2 = img_tensor_mae(blur(im2_upscaled), blur(test_im2_upscaled))
# This tolerance is enough to handle both cpu and gpu as the device, as well as jpg compression differences.
logger.info(f"Diff1: {diff1}, Diff2: {diff2}")
assert diff1 < 0.05, "Upscaled Image 1 doesn't match its test image."
assert diff2 < 0.05, "Upscaled Image 2 doesn't match its test image."
def test_upscale_no_upscale(
self,
base_image,
loaded_checkpoint,
node_classes,
seed,
test_dirs: DirectoryConfig,
):
"""Generate upscaled images using standard workflow using the no upscale node."""
image, positive, negative = base_image
model, clip, vae = loaded_checkpoint
(image,) = execute(
node_classes["ImageScaleBy"],
image=image,
upscale_method="lanczos",
scale_by=2.0,
)
with torch.inference_mode():
usdu = node_classes["UltimateSDUpscaleNoUpscale"]
(upscaled,) = usdu().upscale(
upscaled_image=image,
model=model,
positive=positive,
negative=negative,
vae=vae,
seed=seed,
steps=10,
cfg=8,
sampler_name="euler",
scheduler="normal",
denoise=0.2,
mode_type="Chess",
tile_width=512,
tile_height=512,
mask_blur=8,
tile_padding=32,
seam_fix_mode="None",
seam_fix_denoise=1.0,
seam_fix_width=64,
seam_fix_mask_blur=8,
seam_fix_padding=16,
force_uniform_tiles=True,
tiled_decode=False,
)
# Save images
sample_dir = test_dirs.sample_images
upscaled_img1_path = sample_dir / NO_UPSCALE_IMAGE_1
upscaled_img2_path = sample_dir / NO_UPSCALE_IMAGE_2
save_image(upscaled[0], upscaled_img1_path)
save_image(upscaled[1], upscaled_img2_path)
# Load to account for compression
upscaled = torch.cat(
[load_image(upscaled_img1_path), load_image(upscaled_img2_path)]
)
# Verify results
logger = logging.getLogger("test_upscale_no_upscale")
test_image_dir = test_dirs.test_images
im1_upscaled = upscaled[0]
im2_upscaled = upscaled[1]
test_im1_upscaled = load_image(test_image_dir / NO_UPSCALE_IMAGE_1)
test_im2_upscaled = load_image(test_image_dir / NO_UPSCALE_IMAGE_2)
diff1 = img_tensor_mae(blur(im1_upscaled), blur(test_im1_upscaled))
diff2 = img_tensor_mae(blur(im2_upscaled), blur(test_im2_upscaled))
# This tolerance is enough to handle both cpu and gpu as the device, as well as jpg compression differences.
logger.info(f"Diff1: {diff1}, Diff2: {diff2}")
assert diff1 < 0.05, "No Upscale Image 1 doesn't match its test image."
assert diff2 < 0.05, "No Upscale Image 2 doesn't match its test image."
def test_upscale_with_custom_sampler(
self,
base_image,
loaded_checkpoint,
upscale_model,
node_classes,
seed,
test_dirs: DirectoryConfig,
):
"""Generate upscaled images using standard workflow using the custom sampler node."""
image, positive, negative = base_image
model, clip, vae = loaded_checkpoint
with torch.inference_mode():
# Setup custom scheduler and sampler
custom_scheduler = node_classes["KarrasScheduler"]
(sigmas,) = execute(custom_scheduler, 20, 14.614642, 0.0291675, 7.0)
(_, sigmas) = execute(node_classes["SplitSigmasDenoise"], sigmas, 0.15)
custom_sampler = node_classes["KSamplerSelect"]
(sampler,) = execute(custom_sampler, "dpmpp_2m")
# Run upscale
usdu = node_classes["UltimateSDUpscaleCustomSample"]
(upscaled,) = usdu().upscale(
image=image,
model=model,
positive=positive,
negative=negative,
vae=vae,
upscale_by=2.0,
seed=seed,
steps=10,
cfg=8,
sampler_name="euler",
scheduler="normal",
denoise=0.2,
upscale_model=upscale_model,
mode_type="Chess",
tile_width=512,
tile_height=512,
mask_blur=8,
tile_padding=32,
seam_fix_mode="None",
seam_fix_denoise=1.0,
seam_fix_width=64,
seam_fix_mask_blur=8,
seam_fix_padding=16,
force_uniform_tiles=True,
tiled_decode=False,
custom_sampler=sampler,
custom_sigmas=sigmas,
)
# Save images
sample_dir = test_dirs.sample_images
upscaled_img1_path = sample_dir / CUSTOM_SAMPLER_IMAGE_1
upscaled_img2_path = sample_dir / CUSTOM_SAMPLER_IMAGE_2
save_image(upscaled[0], upscaled_img1_path)
save_image(upscaled[1], upscaled_img2_path)
# Load to account for compression
upscaled = torch.cat(
[load_image(upscaled_img1_path), load_image(upscaled_img2_path)]
)
# Verify results
logger = logging.getLogger("test_upscale_with_custom_sampler")
test_image_dir = test_dirs.test_images
im1_upscaled = upscaled[0]
im2_upscaled = upscaled[1]
test_im1_upscaled = load_image(test_image_dir / CUSTOM_SAMPLER_IMAGE_1)
test_im2_upscaled = load_image(test_image_dir / CUSTOM_SAMPLER_IMAGE_2)
diff1 = img_tensor_mae(blur(im1_upscaled), blur(test_im1_upscaled))
diff2 = img_tensor_mae(blur(im2_upscaled), blur(test_im2_upscaled))
# This tolerance is enough to handle both cpu and gpu as the device, as well as jpg compression differences.
logger.info(f"Diff1: {diff1}, Diff2: {diff2}")
assert diff1 < 0.05, "Upscaled Image 1 doesn't match its test image."
assert diff2 < 0.05, "Upscaled Image 2 doesn't match its test image."

View File

@@ -0,0 +1,69 @@
"""
Test for other settings included in the upscaling nodes.
"""
import logging
import pathlib
import pytest
import torch
from tensor_utils import img_tensor_mae, blur
from io_utils import save_image, load_image
from configs import DirectoryConfig
from fixtures_images import EXT
# Image file names
CATEGORY = pathlib.Path(pathlib.Path(__file__).stem.removeprefix("test_"))
def test_minimal_tile_sizes(
base_image, loaded_checkpoint, node_classes, seed, test_dirs: DirectoryConfig
):
"""Test upscaling with minimal tile sizes."""
filename = "non_uniform_tiles"
image, positive, negative = base_image
model, clip, vae = loaded_checkpoint
with torch.inference_mode():
usdu = node_classes["UltimateSDUpscale"]
(upscaled,) = usdu().upscale(
image=image[0:1],
model=model,
positive=positive,
negative=negative,
vae=vae,
upscale_by=1.5,
seed=seed,
steps=5,
cfg=8,
sampler_name="euler",
scheduler="normal",
denoise=0.15,
upscale_model=None,
mode_type="Chess",
tile_width=512,
tile_height=512,
mask_blur=8,
tile_padding=8,
seam_fix_mode="None",
seam_fix_denoise=1.0,
seam_fix_width=16,
seam_fix_mask_blur=8,
seam_fix_padding=4,
force_uniform_tiles=False,
tiled_decode=False,
)
# Save and reload sample image
sample_dir = test_dirs.sample_images
filename_path = CATEGORY / (filename + EXT)
save_image(upscaled[0], sample_dir / filename_path)
upscaled = load_image(sample_dir / filename_path)
# Compare with reference
test_image_dir = test_dirs.test_images
test_image = load_image(test_image_dir / filename_path)
diff = img_tensor_mae(blur(upscaled), blur(test_image))
logger = logging.getLogger(__name__)
logger.info(f"{filename} MAE: {diff}")
assert diff < 0.05, f"{filename} output doesn't match reference"

View File

@@ -0,0 +1,134 @@
"""
Tests for different upscaling modes and seam fix modes.
"""
import logging
import pathlib
import pytest
import torch
from tensor_utils import img_tensor_mae, blur
from io_utils import save_image, load_image
from configs import DirectoryConfig
from fixtures_images import EXT
# Image file names
CATEGORY = pathlib.Path(pathlib.Path(__file__).stem.removeprefix("test_"))
def image_name_format(prefix: str, mode: str) -> str:
"""Helper for the image name format for the tests below."""
return f"{prefix}_{mode.lower().replace(' ', '_')}{EXT}"
class TestTilingModes:
def _test_upscale_variant(
self,
base_image,
loaded_checkpoint,
node_classes,
seed,
test_dirs: DirectoryConfig,
mode_type,
seam_fix_mode,
seam_fix_denoise,
filename_prefix,
):
"""Helper method to test upscale variants with different parameters."""
logger = logging.getLogger(f"test_{filename_prefix}")
image, positive, negative = base_image
model, clip, vae = loaded_checkpoint
with torch.inference_mode():
usdu = node_classes["UltimateSDUpscale"]
(upscaled,) = usdu().upscale(
image=image[0:1],
model=model,
positive=positive,
negative=negative,
vae=vae,
upscale_by=2.0,
seed=seed,
steps=3,
cfg=8,
sampler_name="euler",
scheduler="normal",
denoise=0.2,
upscale_model=None,
mode_type=mode_type,
tile_width=512,
tile_height=512,
mask_blur=8,
tile_padding=32,
seam_fix_mode=seam_fix_mode,
seam_fix_denoise=seam_fix_denoise,
seam_fix_width=64,
seam_fix_mask_blur=8,
seam_fix_padding=16,
force_uniform_tiles=True,
tiled_decode=False,
)
# Save and reload sample image
sample_dir = test_dirs.sample_images
filename = CATEGORY / filename_prefix
save_image(upscaled[0], sample_dir / filename)
upscaled = load_image(sample_dir / filename)
# Compare with reference
test_image_dir = test_dirs.test_images
test_image = load_image(test_image_dir / filename)
diff = img_tensor_mae(blur(upscaled), blur(test_image))
logger.info(f"{filename_prefix} MAE: {diff}")
assert diff < 0.05, f"{filename_prefix} output doesn't match reference"
# "Chess" is tested in the main workflow test
@pytest.mark.parametrize("mode_type", ["Linear", "None"])
def test_mode_types(
self,
base_image,
loaded_checkpoint,
node_classes,
seed,
mode_type,
test_dirs: DirectoryConfig,
):
"""Test different tiling mode types."""
filename = image_name_format("mode", mode_type)
self._test_upscale_variant(
base_image,
loaded_checkpoint,
node_classes,
seed,
test_dirs,
mode_type=mode_type,
seam_fix_mode="None",
seam_fix_denoise=1.0,
filename_prefix=filename,
)
@pytest.mark.parametrize(
"seam_fix_mode", ["None", "Band Pass", "Half Tile", "Half Tile + Intersections"]
)
def test_seam_fix_modes(
self,
base_image,
loaded_checkpoint,
node_classes,
seed,
seam_fix_mode,
test_dirs: DirectoryConfig,
):
"""Test different seam fix modes."""
filename = image_name_format("seamfix", seam_fix_mode)
self._test_upscale_variant(
base_image,
loaded_checkpoint,
node_classes,
seed,
test_dirs,
mode_type="None",
seam_fix_mode=seam_fix_mode,
seam_fix_denoise=0.5,
filename_prefix=filename,
)

View File

@@ -0,0 +1,243 @@
# ComfyUI Node for Ultimate SD Upscale by Coyote-A: https://github.com/Coyote-A/ultimate-upscale-for-automatic1111
import logging
import torch
import comfy
from usdu_patch import usdu
from usdu_utils import tensor_to_pil, pil_to_tensor
from modules.processing import StableDiffusionProcessing
import modules.shared as shared
from modules.upscaler import UpscalerData
MAX_RESOLUTION = 8192
# The modes available for Ultimate SD Upscale
MODES = {
"Linear": usdu.USDUMode.LINEAR,
"Chess": usdu.USDUMode.CHESS,
"None": usdu.USDUMode.NONE,
}
# The seam fix modes
SEAM_FIX_MODES = {
"None": usdu.USDUSFMode.NONE,
"Band Pass": usdu.USDUSFMode.BAND_PASS,
"Half Tile": usdu.USDUSFMode.HALF_TILE,
"Half Tile + Intersections": usdu.USDUSFMode.HALF_TILE_PLUS_INTERSECTIONS,
}
def USDU_base_inputs():
required = [
("image", ("IMAGE", {"tooltip": "The image to upscale."})),
# Sampling Params
("model", ("MODEL", {"tooltip": "The model to use for image-to-image."})),
("positive", ("CONDITIONING", {"tooltip": "The positive conditioning for each tile."})),
("negative", ("CONDITIONING", {"tooltip": "The negative conditioning for each tile."})),
("vae", ("VAE", {"tooltip": "The VAE model to use for tiles."})),
("upscale_by", ("FLOAT", {"default": 2, "min": 0.05, "max": 4, "step": 0.05, "tooltip": "The factor to upscale the image by."})),
("seed", ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "tooltip": "The seed to use for image-to-image."})),
("steps", ("INT", {"default": 20, "min": 1, "max": 10000, "step": 1, "tooltip": "The number of steps to use for each tile."})),
("cfg", ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "tooltip": "The CFG scale to use for each tile."})),
("sampler_name", (comfy.samplers.KSampler.SAMPLERS, {"tooltip": "The sampler to use for each tile."})),
("scheduler", (comfy.samplers.KSampler.SCHEDULERS, {"tooltip": "The scheduler to use for each tile."})),
("denoise", ("FLOAT", {"default": 0.2, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "The denoising strength to use for each tile."})),
# Upscale Params
("upscale_model", ("UPSCALE_MODEL", {"tooltip": "The upscaler model for upscaling the image."})),
("mode_type", (list(MODES.keys()), {"tooltip": "The tiling order to use for the redraw step."})),
("tile_width", ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8, "tooltip": "The width of each tile."})),
("tile_height", ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8, "tooltip": "The height of each tile."})),
("mask_blur", ("INT", {"default": 8, "min": 0, "max": 64, "step": 1, "tooltip": "The blur radius for the mask."})),
("tile_padding", ("INT", {"default": 32, "min": 0, "max": MAX_RESOLUTION, "step": 8, "tooltip": "The padding to apply between tiles."})),
# Seam fix params
("seam_fix_mode", (list(SEAM_FIX_MODES.keys()), {"tooltip": "The seam fix mode to use."})),
("seam_fix_denoise", ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "The denoising strength to use for the seam fix."})),
("seam_fix_width", ("INT", {"default": 64, "min": 0, "max": MAX_RESOLUTION, "step": 8, "tooltip": "The width of the bands used for the Band Pass seam fix mode."})),
("seam_fix_mask_blur", ("INT", {"default": 8, "min": 0, "max": 64, "step": 1, "tooltip": "The blur radius for the seam fix mask."})),
("seam_fix_padding", ("INT", {"default": 16, "min": 0, "max": MAX_RESOLUTION, "step": 8, "tooltip": "The padding to apply for the seam fix tiles."})),
# Misc
("force_uniform_tiles", ("BOOLEAN", {"default": True, "tooltip": "Force all tiles to be the same as the set tile size, even when tiles could be smaller. This can help prevent the model from working with irregular tile sizes."})),
("tiled_decode", ("BOOLEAN", {"default": False, "tooltip": "Whether to use tiled decoding when decoding tiles."})),
]
optional = []
return required, optional
def prepare_inputs(required: list, optional: list = None):
inputs = {}
if required:
inputs["required"] = {}
for name, type in required:
inputs["required"][name] = type
if optional:
inputs["optional"] = {}
for name, type in optional:
inputs["optional"][name] = type
return inputs
def remove_input(inputs: list, input_name: str):
for i, (n, _) in enumerate(inputs):
if n == input_name:
del inputs[i]
break
def rename_input(inputs: list, old_name: str, new_name: str):
for i, (n, t) in enumerate(inputs):
if n == old_name:
inputs[i] = (new_name, t)
break
class UltimateSDUpscale:
@classmethod
def INPUT_TYPES(s):
required, optional = USDU_base_inputs()
return prepare_inputs(required, optional)
RETURN_TYPES = ("IMAGE",)
FUNCTION = "upscale"
CATEGORY = "image/upscaling"
OUTPUT_TOOLTIPS = ("The final upscaled image.",)
DESCRIPTION = "Upscales an image and runs image-to-image on tiles from the input image."
def upscale(self, image, model, positive, negative, vae, upscale_by, seed,
steps, cfg, sampler_name, scheduler, denoise, upscale_model,
mode_type, tile_width, tile_height, mask_blur, tile_padding,
seam_fix_mode, seam_fix_denoise, seam_fix_mask_blur,
seam_fix_width, seam_fix_padding, force_uniform_tiles, tiled_decode,
custom_sampler=None, custom_sigmas=None):
# Store params
self.tile_width = tile_width
self.tile_height = tile_height
self.mask_blur = mask_blur
self.tile_padding = tile_padding
self.seam_fix_width = seam_fix_width
self.seam_fix_denoise = seam_fix_denoise
self.seam_fix_padding = seam_fix_padding
self.seam_fix_mode = seam_fix_mode
self.mode_type = mode_type
self.upscale_by = upscale_by
self.seam_fix_mask_blur = seam_fix_mask_blur
#
# Set up A1111 patches
#
# Upscaler
# An object that the script works with
shared.sd_upscalers[0] = UpscalerData()
# Where the actual upscaler is stored, will be used when the script upscales using the Upscaler in UpscalerData
shared.actual_upscaler = upscale_model
# Set the batch of images
shared.batch = [tensor_to_pil(image, i) for i in range(len(image))]
shared.batch_as_tensor = image
# Processing
sdprocessing = StableDiffusionProcessing(
shared.batch[0], model, positive, negative, vae,
seed, steps, cfg, sampler_name, scheduler, denoise, upscale_by, force_uniform_tiles, tiled_decode,
tile_width, tile_height, MODES[self.mode_type], SEAM_FIX_MODES[self.seam_fix_mode],
custom_sampler, custom_sigmas,
)
# Disable logging
logger = logging.getLogger()
old_level = logger.getEffectiveLevel()
logger.setLevel(logging.CRITICAL + 1)
try:
#
# Running the script
#
script = usdu.Script()
processed = script.run(p=sdprocessing, _=None, tile_width=self.tile_width, tile_height=self.tile_height,
mask_blur=self.mask_blur, padding=self.tile_padding, seams_fix_width=self.seam_fix_width,
seams_fix_denoise=self.seam_fix_denoise, seams_fix_padding=self.seam_fix_padding,
upscaler_index=0, save_upscaled_image=False, redraw_mode=MODES[self.mode_type],
save_seams_fix_image=False, seams_fix_mask_blur=self.seam_fix_mask_blur,
seams_fix_type=SEAM_FIX_MODES[self.seam_fix_mode], target_size_type=2,
custom_width=None, custom_height=None, custom_scale=self.upscale_by)
# Return the resulting images
images = [pil_to_tensor(img) for img in shared.batch]
tensor = torch.cat(images, dim=0)
return (tensor,)
finally:
# Restore the original logging level
logger.setLevel(old_level)
class UltimateSDUpscaleNoUpscale(UltimateSDUpscale):
@classmethod
def INPUT_TYPES(s):
required, optional = USDU_base_inputs()
remove_input(required, "upscale_model")
remove_input(required, "upscale_by")
rename_input(required, "image", "upscaled_image")
return prepare_inputs(required, optional)
RETURN_TYPES = ("IMAGE",)
FUNCTION = "upscale"
CATEGORY = "image/upscaling"
OUTPUT_TOOLTIPS = ("The final refined image.",)
DESCRIPTION = "Runs image-to-image on tiles from the input image."
def upscale(self, upscaled_image, model, positive, negative, vae, seed,
steps, cfg, sampler_name, scheduler, denoise,
mode_type, tile_width, tile_height, mask_blur, tile_padding,
seam_fix_mode, seam_fix_denoise, seam_fix_mask_blur,
seam_fix_width, seam_fix_padding, force_uniform_tiles, tiled_decode):
upscale_by = 1.0
return super().upscale(upscaled_image, model, positive, negative, vae, upscale_by, seed,
steps, cfg, sampler_name, scheduler, denoise, None,
mode_type, tile_width, tile_height, mask_blur, tile_padding,
seam_fix_mode, seam_fix_denoise, seam_fix_mask_blur,
seam_fix_width, seam_fix_padding, force_uniform_tiles, tiled_decode)
class UltimateSDUpscaleCustomSample(UltimateSDUpscale):
@classmethod
def INPUT_TYPES(s):
required, optional = USDU_base_inputs()
remove_input(required, "upscale_model")
optional.append(("upscale_model", ("UPSCALE_MODEL", {"tooltip": "The model to use for upscaling the image. If not provided, a simple Lanczos scaling will be used instead."})))
optional.append(("custom_sampler", ("SAMPLER", {"tooltip": "A custom sampler to use instead of the built-in ComfyUI sampler specified by sampler_name. Only used if both custom_sampler and custom_sigmas are provided."})))
optional.append(("custom_sigmas", ("SIGMAS", {"tooltip": "A custom noise schedule to use during sampling. Only used if both custom_sampler and custom_sigmas are provided."})))
return prepare_inputs(required, optional)
RETURN_TYPES = ("IMAGE",)
FUNCTION = "upscale"
CATEGORY = "image/upscaling"
OUTPUT_TOOLTIPS = ("The final upscaled image.",)
DESCRIPTION = "Runs image-to-image on tiles from the input image."
def upscale(self, image, model, positive, negative, vae, upscale_by, seed,
steps, cfg, sampler_name, scheduler, denoise,
mode_type, tile_width, tile_height, mask_blur, tile_padding,
seam_fix_mode, seam_fix_denoise, seam_fix_mask_blur,
seam_fix_width, seam_fix_padding, force_uniform_tiles, tiled_decode,
upscale_model=None,
custom_sampler=None, custom_sigmas=None):
return super().upscale(image, model, positive, negative, vae, upscale_by, seed,
steps, cfg, sampler_name, scheduler, denoise, upscale_model,
mode_type, tile_width, tile_height, mask_blur, tile_padding,
seam_fix_mode, seam_fix_denoise, seam_fix_mask_blur,
seam_fix_width, seam_fix_padding, force_uniform_tiles, tiled_decode,
custom_sampler, custom_sigmas)
# A dictionary that contains all nodes you want to export with their names
# NOTE: names should be globally unique
NODE_CLASS_MAPPINGS = {
"UltimateSDUpscale": UltimateSDUpscale,
"UltimateSDUpscaleNoUpscale": UltimateSDUpscaleNoUpscale,
"UltimateSDUpscaleCustomSample": UltimateSDUpscaleCustomSample
}
# A dictionary that contains the friendly/humanly readable titles for the nodes
NODE_DISPLAY_NAME_MAPPINGS = {
"UltimateSDUpscale": "Ultimate SD Upscale",
"UltimateSDUpscaleNoUpscale": "Ultimate SD Upscale (No Upscale)",
"UltimateSDUpscaleCustomSample": "Ultimate SD Upscale (Custom Sample)"
}

View File

@@ -0,0 +1,71 @@
# Make some patches to the script
from repositories import ultimate_upscale as usdu
import modules.shared as shared
import math
from PIL import Image
if (not hasattr(Image, 'Resampling')): # For older versions of Pillow
Image.Resampling = Image
#
# Instead of using multiples of 64, use multiples of 8
#
def round_length(length, multiple=8):
return round(length / multiple) * multiple
# Upscaler
old_init = usdu.USDUpscaler.__init__
def new_init(self, p, image, upscaler_index, save_redraw, save_seams_fix, tile_width, tile_height):
p.width = round_length(image.width * p.upscale_by)
p.height = round_length(image.height * p.upscale_by)
old_init(self, p, image, upscaler_index, save_redraw, save_seams_fix, tile_width, tile_height)
usdu.USDUpscaler.__init__ = new_init
# Redraw
old_setup_redraw = usdu.USDURedraw.init_draw
def new_setup_redraw(self, p, width, height):
mask, draw = old_setup_redraw(self, p, width, height)
p.width = round_length(self.tile_width + self.padding)
p.height = round_length(self.tile_height + self.padding)
return mask, draw
usdu.USDURedraw.init_draw = new_setup_redraw
# Seams fix
old_setup_seams_fix = usdu.USDUSeamsFix.init_draw
def new_setup_seams_fix(self, p):
old_setup_seams_fix(self, p)
p.width = round_length(self.tile_width + self.padding)
p.height = round_length(self.tile_height + self.padding)
usdu.USDUSeamsFix.init_draw = new_setup_seams_fix
#
# Make the script upscale on a batch of images instead of one image
#
old_upscale = usdu.USDUpscaler.upscale
def new_upscale(self):
old_upscale(self)
shared.batch = [self.image] + \
[img.resize((self.p.width, self.p.height), resample=Image.LANCZOS) for img in shared.batch[1:]]
usdu.USDUpscaler.upscale = new_upscale

View File

@@ -0,0 +1,517 @@
import numpy as np
from PIL import Image, ImageFilter
import torch
import torch.nn.functional as F
from torchvision.transforms import GaussianBlur
import math
if (not hasattr(Image, 'Resampling')): # For older versions of Pillow
Image.Resampling = Image
BLUR_KERNEL_SIZE = 15
def tensor_to_pil(img_tensor, batch_index=0):
# Takes a batch of images in the form of a tensor of shape [batch_size, height, width, channels]
# and returns an RGB PIL Image. Assumes channels=3
safe_tensor = torch.nan_to_num(img_tensor[batch_index])
return Image.fromarray((255 * safe_tensor.cpu().numpy()).astype(np.uint8))
def pil_to_tensor(image):
# Takes a PIL image and returns a tensor of shape [1, height, width, channels]
image = np.array(image).astype(np.float32) / 255.0
image = torch.from_numpy(image).unsqueeze(0)
if len(image.shape) == 3: # If the image is grayscale, add a channel dimension
image = image.unsqueeze(-1)
return image
def controlnet_hint_to_pil(tensor, batch_index=0):
return tensor_to_pil(tensor.movedim(1, -1), batch_index)
def pil_to_controlnet_hint(img):
return pil_to_tensor(img).movedim(-1, 1)
def crop_tensor(tensor, region):
# Takes a tensor of shape [batch_size, height, width, channels] and crops it to the given region
x1, y1, x2, y2 = region
return tensor[:, y1:y2, x1:x2, :]
def resize_tensor(tensor, size, mode="nearest-exact"):
# Takes a tensor of shape [B, C, H, W] and resizes
# it to a shape of [B, C, size[0], size[1]] using the given mode
return torch.nn.functional.interpolate(tensor, size=size, mode=mode)
def get_crop_region(mask, pad=0):
# Takes a black and white PIL image in 'L' mode and returns the coordinates of the white rectangular mask region
# Should be equivalent to the get_crop_region function from https://github.com/AUTOMATIC1111/stable-diffusion-webui/blob/master/modules/masking.py
coordinates = mask.getbbox()
if coordinates is not None:
x1, y1, x2, y2 = coordinates
else:
x1, y1, x2, y2 = mask.width, mask.height, 0, 0
# Apply padding
x1 = max(x1 - pad, 0)
y1 = max(y1 - pad, 0)
x2 = min(x2 + pad, mask.width)
y2 = min(y2 + pad, mask.height)
return fix_crop_region((x1, y1, x2, y2), (mask.width, mask.height))
def fix_crop_region(region, image_size):
# Remove the extra pixel added by the get_crop_region function
image_width, image_height = image_size
x1, y1, x2, y2 = region
if x2 < image_width:
x2 -= 1
if y2 < image_height:
y2 -= 1
return x1, y1, x2, y2
def expand_crop(region, width, height, target_width, target_height):
'''
Expands a crop region to a specified target size.
:param region: A tuple of the form (x1, y1, x2, y2) denoting the upper left and the lower right points
of the rectangular region. Expected to have x2 > x1 and y2 > y1.
:param width: The width of the image the crop region is from.
:param height: The height of the image the crop region is from.
:param target_width: The desired width of the crop region.
:param target_height: The desired height of the crop region.
'''
x1, y1, x2, y2 = region
actual_width = x2 - x1
actual_height = y2 - y1
# target_width = math.ceil(actual_width / 8) * 8
# target_height = math.ceil(actual_height / 8) * 8
# Try to expand region to the right of half the difference
width_diff = target_width - actual_width
x2 = min(x2 + width_diff // 2, width)
# Expand region to the left of the difference including the pixels that could not be expanded to the right
width_diff = target_width - (x2 - x1)
x1 = max(x1 - width_diff, 0)
# Try the right again
width_diff = target_width - (x2 - x1)
x2 = min(x2 + width_diff, width)
# Try to expand region to the bottom of half the difference
height_diff = target_height - actual_height
y2 = min(y2 + height_diff // 2, height)
# Expand region to the top of the difference including the pixels that could not be expanded to the bottom
height_diff = target_height - (y2 - y1)
y1 = max(y1 - height_diff, 0)
# Try the bottom again
height_diff = target_height - (y2 - y1)
y2 = min(y2 + height_diff, height)
return (x1, y1, x2, y2), (target_width, target_height)
def resize_region(region, init_size, resize_size):
# Resize a crop so that it fits an image that was resized to the given width and height
x1, y1, x2, y2 = region
init_width, init_height = init_size
resize_width, resize_height = resize_size
x1 = math.floor(x1 * resize_width / init_width)
x2 = math.ceil(x2 * resize_width / init_width)
y1 = math.floor(y1 * resize_height / init_height)
y2 = math.ceil(y2 * resize_height / init_height)
return (x1, y1, x2, y2)
def pad_image(image, left_pad, right_pad, top_pad, bottom_pad, fill=False, blur=False):
'''
Pads an image with the given number of pixels on each side and fills the padding with data from the edges.
:param image: A PIL image
:param left_pad: The number of pixels to pad on the left side
:param right_pad: The number of pixels to pad on the right side
:param top_pad: The number of pixels to pad on the top side
:param bottom_pad: The number of pixels to pad on the bottom side
:param blur: Whether to blur the padded edges
:return: A PIL image with size (image.width + left_pad + right_pad, image.height + top_pad + bottom_pad)
'''
left_edge = image.crop((0, 1, 1, image.height - 1))
right_edge = image.crop((image.width - 1, 1, image.width, image.height - 1))
top_edge = image.crop((1, 0, image.width - 1, 1))
bottom_edge = image.crop((1, image.height - 1, image.width - 1, image.height))
new_width = image.width + left_pad + right_pad
new_height = image.height + top_pad + bottom_pad
padded_image = Image.new(image.mode, (new_width, new_height))
padded_image.paste(image, (left_pad, top_pad))
if fill:
for i in range(left_pad):
edge = left_edge.resize(
(1, new_height - i * (top_pad + bottom_pad) // left_pad), resample=Image.Resampling.NEAREST)
padded_image.paste(edge, (i, i * top_pad // left_pad))
for i in range(right_pad):
edge = right_edge.resize(
(1, new_height - i * (top_pad + bottom_pad) // right_pad), resample=Image.Resampling.NEAREST)
padded_image.paste(edge, (new_width - 1 - i, i * top_pad // right_pad))
for i in range(top_pad):
edge = top_edge.resize(
(new_width - i * (left_pad + right_pad) // top_pad, 1), resample=Image.Resampling.NEAREST)
padded_image.paste(edge, (i * left_pad // top_pad, i))
for i in range(bottom_pad):
edge = bottom_edge.resize(
(new_width - i * (left_pad + right_pad) // bottom_pad, 1), resample=Image.Resampling.NEAREST)
padded_image.paste(edge, (i * left_pad // bottom_pad, new_height - 1 - i))
if blur and not (left_pad == right_pad == top_pad == bottom_pad == 0):
padded_image = padded_image.filter(ImageFilter.GaussianBlur(BLUR_KERNEL_SIZE))
padded_image.paste(image, (left_pad, top_pad))
return padded_image
def pad_image2(image, left_pad, right_pad, top_pad, bottom_pad, fill=False, blur=False):
'''
Pads an image with the given number of pixels on each side and fills the padding with data from the edges.
Faster than pad_image, but only pads with edge data in straight lines.
:param image: A PIL image
:param left_pad: The number of pixels to pad on the left side
:param right_pad: The number of pixels to pad on the right side
:param top_pad: The number of pixels to pad on the top side
:param bottom_pad: The number of pixels to pad on the bottom side
:param blur: Whether to blur the padded edges
:return: A PIL image with size (image.width + left_pad + right_pad, image.height + top_pad + bottom_pad)
'''
left_edge = image.crop((0, 1, 1, image.height - 1))
right_edge = image.crop((image.width - 1, 1, image.width, image.height - 1))
top_edge = image.crop((1, 0, image.width - 1, 1))
bottom_edge = image.crop((1, image.height - 1, image.width - 1, image.height))
new_width = image.width + left_pad + right_pad
new_height = image.height + top_pad + bottom_pad
padded_image = Image.new(image.mode, (new_width, new_height))
padded_image.paste(image, (left_pad, top_pad))
if fill:
if left_pad > 0:
padded_image.paste(left_edge.resize((left_pad, new_height), resample=Image.Resampling.NEAREST), (0, 0))
if right_pad > 0:
padded_image.paste(right_edge.resize((right_pad, new_height),
resample=Image.Resampling.NEAREST), (new_width - right_pad, 0))
if top_pad > 0:
padded_image.paste(top_edge.resize((new_width, top_pad), resample=Image.Resampling.NEAREST), (0, 0))
if bottom_pad > 0:
padded_image.paste(bottom_edge.resize((new_width, bottom_pad),
resample=Image.Resampling.NEAREST), (0, new_height - bottom_pad))
if blur and not (left_pad == right_pad == top_pad == bottom_pad == 0):
padded_image = padded_image.filter(ImageFilter.GaussianBlur(BLUR_KERNEL_SIZE))
padded_image.paste(image, (left_pad, top_pad))
return padded_image
def pad_tensor(tensor, left_pad, right_pad, top_pad, bottom_pad, fill=False, blur=False):
'''
Pads an image tensor with the given number of pixels on each side and fills the padding with data from the edges.
:param tensor: A tensor of shape [B, H, W, C]
:param left_pad: The number of pixels to pad on the left side
:param right_pad: The number of pixels to pad on the right side
:param top_pad: The number of pixels to pad on the top side
:param bottom_pad: The number of pixels to pad on the bottom side
:param blur: Whether to blur the padded edges
:return: A tensor of shape [B, H + top_pad + bottom_pad, W + left_pad + right_pad, C]
'''
batch_size, channels, height, width = tensor.shape
h_pad = left_pad + right_pad
v_pad = top_pad + bottom_pad
new_width = width + h_pad
new_height = height + v_pad
# Create empty image
padded = torch.zeros((batch_size, channels, new_height, new_width), dtype=tensor.dtype)
# Copy the original image into the centor of the padded tensor
padded[:, :, top_pad:top_pad + height, left_pad:left_pad + width] = tensor
# Duplicate the edges of the original image into the padding
if top_pad > 0:
padded[:, :, :top_pad, :] = padded[:, :, top_pad:top_pad + 1, :] # Top edge
if bottom_pad > 0:
padded[:, :, -bottom_pad:, :] = padded[:, :, -bottom_pad - 1:-bottom_pad, :] # Bottom edge
if left_pad > 0:
padded[:, :, :, :left_pad] = padded[:, :, :, left_pad:left_pad + 1] # Left edge
if right_pad > 0:
padded[:, :, :, -right_pad:] = padded[:, :, :, -right_pad - 1:-right_pad] # Right edge
return padded
def resize_and_pad_image(image, width, height, fill=False, blur=False):
'''
Resizes an image to the given width and height and pads it to the given width and height.
:param image: A PIL image
:param width: The width of the resized image
:param height: The height of the resized image
:param fill: Whether to fill the padding with data from the edges
:param blur: Whether to blur the padded edges
:return: A PIL image of size (width, height)
'''
width_ratio = width / image.width
height_ratio = height / image.height
if height_ratio > width_ratio:
resize_ratio = width_ratio
else:
resize_ratio = height_ratio
resize_width = round(image.width * resize_ratio)
resize_height = round(image.height * resize_ratio)
resized = image.resize((resize_width, resize_height), resample=Image.Resampling.LANCZOS)
# Pad the sides of the image to get the image to the desired size that wasn't covered by the resize
horizontal_pad = (width - resize_width) // 2
vertical_pad = (height - resize_height) // 2
result = pad_image2(resized, horizontal_pad, horizontal_pad, vertical_pad, vertical_pad, fill, blur)
result = result.resize((width, height), resample=Image.Resampling.LANCZOS)
return result, (horizontal_pad, vertical_pad)
def resize_and_pad_tensor(tensor, width, height, fill=False, blur=False):
'''
Resizes an image tensor to the given width and height and pads it to the given width and height.
:param tensor: A tensor of shape [B, H, W, C]
:param width: The width of the resized image
:param height: The height of the resized image
:param fill: Whether to fill the padding with data from the edges
:param blur: Whether to blur the padded edges
:return: A tensor of shape [B, height, width, C]
'''
# Resize the image to the closest size that maintains the aspect ratio
width_ratio = width / tensor.shape[3]
height_ratio = height / tensor.shape[2]
if height_ratio > width_ratio:
resize_ratio = width_ratio
else:
resize_ratio = height_ratio
resize_width = round(tensor.shape[3] * resize_ratio)
resize_height = round(tensor.shape[2] * resize_ratio)
resized = F.interpolate(tensor, size=(resize_height, resize_width), mode='nearest-exact')
# Pad the sides of the image to get the image to the desired size that wasn't covered by the resize
horizontal_pad = (width - resize_width) // 2
vertical_pad = (height - resize_height) // 2
result = pad_tensor(resized, horizontal_pad, horizontal_pad, vertical_pad, vertical_pad, fill, blur)
result = F.interpolate(result, size=(height, width), mode='nearest-exact')
return result
def crop_controlnet(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad):
if "control" not in cond_dict:
return
c = cond_dict["control"]
controlnet = c.copy()
cond_dict["control"] = controlnet
while c is not None:
# hint is shape (B, C, H, W)
hint = controlnet.cond_hint_original
resized_crop = resize_region(region, canvas_size, hint.shape[:-3:-1])
hint = crop_tensor(hint.movedim(1, -1), resized_crop).movedim(-1, 1)
hint = resize_tensor(hint, tile_size[::-1])
controlnet.cond_hint_original = hint
c = c.previous_controlnet
controlnet.set_previous_controlnet(c.copy() if c is not None else None)
controlnet = controlnet.previous_controlnet
def region_intersection(region1, region2):
"""
Returns the coordinates of the intersection of two rectangular regions.
:param region1: A tuple of the form (x1, y1, x2, y2) denoting the upper left and the lower right points
of the first rectangular region. Expected to have x2 > x1 and y2 > y1.
:param region2: The second rectangular region with the same format as the first.
:return: A tuple of the form (x1, y1, x2, y2) denoting the rectangular intersection.
None if there is no intersection.
"""
x1, y1, x2, y2 = region1
x1_, y1_, x2_, y2_ = region2
x1 = max(x1, x1_)
y1 = max(y1, y1_)
x2 = min(x2, x2_)
y2 = min(y2, y2_)
if x1 >= x2 or y1 >= y2:
return None
return (x1, y1, x2, y2)
def crop_gligen(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad):
if "gligen" not in cond_dict:
return
type, model, cond = cond_dict["gligen"]
if type != "position":
from warnings import warn
warn(f"Unknown gligen type {type}")
return
cropped = []
for c in cond:
emb, h, w, y, x = c
# Get the coordinates of the box in the upscaled image
x1 = x * 8
y1 = y * 8
x2 = x1 + w * 8
y2 = y1 + h * 8
gligen_upscaled_box = resize_region((x1, y1, x2, y2), init_size, canvas_size)
# Calculate the intersection of the gligen box and the region
intersection = region_intersection(gligen_upscaled_box, region)
if intersection is None:
continue
x1, y1, x2, y2 = intersection
# Offset the gligen box so that the origin is at the top left of the tile region
x1 -= region[0]
y1 -= region[1]
x2 -= region[0]
y2 -= region[1]
# Add the padding
x1 += w_pad
y1 += h_pad
x2 += w_pad
y2 += h_pad
# Set the new position params
h = (y2 - y1) // 8
w = (x2 - x1) // 8
x = x1 // 8
y = y1 // 8
cropped.append((emb, h, w, y, x))
cond_dict["gligen"] = (type, model, cropped)
def crop_area(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad):
if "area" not in cond_dict:
return
# Resize the area conditioning to the canvas size and confine it to the tile region
h, w, y, x = cond_dict["area"]
w, h, x, y = 8 * w, 8 * h, 8 * x, 8 * y
x1, y1, x2, y2 = resize_region((x, y, x + w, y + h), init_size, canvas_size)
intersection = region_intersection((x1, y1, x2, y2), region)
if intersection is None:
del cond_dict["area"]
del cond_dict["strength"]
return
x1, y1, x2, y2 = intersection
# Offset origin to the top left of the tile
x1 -= region[0]
y1 -= region[1]
x2 -= region[0]
y2 -= region[1]
# Add the padding
x1 += w_pad
y1 += h_pad
x2 += w_pad
y2 += h_pad
# Set the params for tile
w, h = (x2 - x1) // 8, (y2 - y1) // 8
x, y = x1 // 8, y1 // 8
cond_dict["area"] = (h, w, y, x)
def crop_mask(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad):
if "mask" not in cond_dict:
return
mask_tensor = cond_dict["mask"] # (B, H, W)
masks = []
for i in range(mask_tensor.shape[0]):
# Convert to PIL image
mask = tensor_to_pil(mask_tensor, i) # W x H
# Resize the mask to the canvas size
mask = mask.resize(canvas_size, Image.Resampling.BICUBIC)
# Crop the mask to the region
mask = mask.crop(region)
# Add padding
mask, _ = resize_and_pad_image(mask, tile_size[0], tile_size[1], fill=True)
# Resize the mask to the tile size
if tile_size != mask.size:
mask = mask.resize(tile_size, Image.Resampling.BICUBIC)
# Convert back to tensor
mask = pil_to_tensor(mask) # (1, H, W, 1)
mask = mask.squeeze(-1) # (1, H, W)
masks.append(mask)
cond_dict["mask"] = torch.cat(masks, dim=0) # (B, H, W)
# Added Flux-Kontext Support crop_reference_latents by TBG ETUR
def crop_reference_latents(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad):
"""
1. Resize each latent to `canvas_size` in latent units.
2. Crop the rectangle `region` (pixel coordinates).
3. Down-sample the crop to latent-space `tile_size`.
Expects a list of BCHW tensors under "reference_latents".
"""
latents = cond_dict.get("reference_latents")
if not isinstance(latents, list):
return # nothing to do
k = 8 # down-sample factor from pixel space → latent space (SD-type models)
W_can_px, H_can_px = canvas_size
# canvas size expressed in latent units
W_can_lat, H_can_lat = W_can_px // k, H_can_px // k
W_tile_px, H_tile_px = tile_size
W_tile_lat, H_tile_lat = max(1, W_tile_px // k), max(1, H_tile_px // k)
x1_px, y1_px, x2_px, y2_px = region
new_latents = []
for t in latents: # (B,C,H_lat_in,W_lat_in)
has_5d = False
if t.ndim == 5: # (B,C,1,H_lat_in,W_lat_in)
has_5d = True
t = t.squeeze(2)
if t.ndim != 4:
raise ValueError(f"expected BCHW, got {t.shape}")
# 1. Resize to canvas resolution in latent units only if needed
if t.shape[-2:] != (H_can_lat, W_can_lat):
t = F.interpolate(t,
size=(H_can_lat, W_can_lat),
mode="bilinear",
align_corners=False)
# 2. Convert pixel crop → latent slice
w0_lat = int(round(x1_px / k))
w1_lat = int(round(x2_px / k))
h0_lat = int(round(y1_px / k))
h1_lat = int(round(y2_px / k))
cropped = t[:, :, h0_lat:h1_lat, w0_lat:w1_lat] # view
# 3. Down-sample to latent-tile size
cropped = F.interpolate(cropped,
size=(H_tile_lat, W_tile_lat),
mode="bilinear",
align_corners=False)
if has_5d:
cropped = cropped.unsqueeze(2)
new_latents.append(cropped)
cond_dict["reference_latents"] = new_latents
def crop_cond(cond, region, init_size, canvas_size, tile_size, w_pad=0, h_pad=0):
cropped = []
for emb, x in cond:
cond_dict = x.copy()
n = [emb, cond_dict]
crop_controlnet(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad)
crop_gligen(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad)
crop_area(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad)
crop_mask(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad)
crop_reference_latents(cond_dict, region, init_size, canvas_size, tile_size, w_pad, h_pad)
cropped.append(n)
return cropped