Add custom nodes, Civitai loras (LFS), and vast.ai setup script
Some checks failed
Python Linting / Run Ruff (push) Has been cancelled
Python Linting / Run Pylint (push) Has been cancelled
Full Comfy CI Workflow Runs / test-stable (12.1, , linux, 3.10, [self-hosted Linux], stable) (push) Has been cancelled
Full Comfy CI Workflow Runs / test-stable (12.1, , linux, 3.11, [self-hosted Linux], stable) (push) Has been cancelled
Full Comfy CI Workflow Runs / test-stable (12.1, , linux, 3.12, [self-hosted Linux], stable) (push) Has been cancelled
Full Comfy CI Workflow Runs / test-unix-nightly (12.1, , linux, 3.11, [self-hosted Linux], nightly) (push) Has been cancelled
Execution Tests / test (macos-latest) (push) Has been cancelled
Execution Tests / test (ubuntu-latest) (push) Has been cancelled
Execution Tests / test (windows-latest) (push) Has been cancelled
Test server launches without errors / test (push) Has been cancelled
Unit Tests / test (macos-latest) (push) Has been cancelled
Unit Tests / test (ubuntu-latest) (push) Has been cancelled
Unit Tests / test (windows-2022) (push) Has been cancelled
Some checks failed
Python Linting / Run Ruff (push) Has been cancelled
Python Linting / Run Pylint (push) Has been cancelled
Full Comfy CI Workflow Runs / test-stable (12.1, , linux, 3.10, [self-hosted Linux], stable) (push) Has been cancelled
Full Comfy CI Workflow Runs / test-stable (12.1, , linux, 3.11, [self-hosted Linux], stable) (push) Has been cancelled
Full Comfy CI Workflow Runs / test-stable (12.1, , linux, 3.12, [self-hosted Linux], stable) (push) Has been cancelled
Full Comfy CI Workflow Runs / test-unix-nightly (12.1, , linux, 3.11, [self-hosted Linux], nightly) (push) Has been cancelled
Execution Tests / test (macos-latest) (push) Has been cancelled
Execution Tests / test (ubuntu-latest) (push) Has been cancelled
Execution Tests / test (windows-latest) (push) Has been cancelled
Test server launches without errors / test (push) Has been cancelled
Unit Tests / test (macos-latest) (push) Has been cancelled
Unit Tests / test (ubuntu-latest) (push) Has been cancelled
Unit Tests / test (windows-2022) (push) Has been cancelled
Includes 30 custom nodes committed directly, 7 Civitai-exclusive loras stored via Git LFS, and a setup script that installs all dependencies and downloads HuggingFace-hosted models on vast.ai. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
161
custom_nodes/comfyui-inspire-pack/.gitignore
vendored
Normal file
161
custom_nodes/comfyui-inspire-pack/.gitignore
vendored
Normal file
@@ -0,0 +1,161 @@
|
||||
# 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
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/#use-with-ide
|
||||
.pdm.toml
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__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 maintained 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/
|
||||
resources/prompt-builder.yaml
|
||||
674
custom_nodes/comfyui-inspire-pack/LICENSE
Normal file
674
custom_nodes/comfyui-inspire-pack/LICENSE
Normal 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>.
|
||||
204
custom_nodes/comfyui-inspire-pack/README.md
Normal file
204
custom_nodes/comfyui-inspire-pack/README.md
Normal file
@@ -0,0 +1,204 @@
|
||||
# ComfyUI-Inspire-Pack
|
||||
This repository offers various extension nodes for ComfyUI. Nodes here have different characteristics compared to those in the ComfyUI Impact Pack. The Impact Pack has become too large now...
|
||||
|
||||
## Notice:
|
||||
* V1.18: To use the 'OSS' Scheduler, please update to ComfyUI version 0.3.28 or later (April 13th or newer) and Impact Pack version V8.11 or higher.
|
||||
* V1.9.1 To avoid confusion with the `NOISE` type in core, the type name has been changed to `NOISE_IMAGE`.
|
||||
* V0.73 The Variation Seed feature is added to Regional Prompt nodes, and it is only compatible with versions Impact Pack V5.10 and above.
|
||||
* V0.69 incompatible with the outdated **ComfyUI IPAdapter Plus**. (A version dated March 24th or later is required.)
|
||||
* V0.64 add sigma_factor to RegionalPrompt... nodes required Impact Pack V4.76 or later.
|
||||
* V0.62 support faceid in Regional IPAdapter
|
||||
* V0.48 optimized wildcard node. This update requires Impact Pack V4.39.2 or later.
|
||||
* V0.13.2 isn't compatible with old ControlNet Auxiliary Preprocessor. If you will use `MediaPipeFaceMeshDetectorProvider` update to latest version(Sep. 17th).
|
||||
* WARN: If you use version **0.12 to 0.12.2** without a GlobalSeed node, your workflow's seed may have been erased. Please update immediately.
|
||||
|
||||
## Nodes
|
||||
### Lora Block Weight - This is a node that provides functionality related to Lora block weight.
|
||||
* This provides similar functionality to [sd-webui-lora-block-weight](https://github.com/hako-mikan/sd-webui-lora-block-weight)
|
||||
* `LoRA Loader (Block Weight)`: When loading Lora, the block weight vector is applied.
|
||||
* In the block vector, you can use numbers, R, A, a, B, and b.
|
||||
* R is determined sequentially based on a random seed, while A and B represent the values of the A and B parameters, respectively. a and b are half of the values of A and B, respectively.
|
||||
* `XY Input: LoRA Block Weight`: This is a node in the [Efficiency Nodes](https://github.com/LucianoCirino/efficiency-nodes-comfyui)' XY Plot that allows you to use Lora block weight.
|
||||
* You must ensure that X and Y connections are made, and dependencies should be connected to the XY Plot.
|
||||
* Note: To use this feature, update `Efficient Nodes` to a version released after September 3rd.
|
||||
* Make LoRA Block Weight: Instead of directly applying the LoRA Block Weight to the MODEL, it is generated in a separate LBW_MODEL form
|
||||
* Apply LoRA Block Weight: Apply LBW_MODEL to MODEL and CLIP
|
||||
* Save LoRA Block Weight: Save LBW_MODEL as a .lbw.safetensors file
|
||||
* Load LoRA Block Weight: Load LBW_MODEL from .lbw.safetensors file
|
||||
|
||||
|
||||
### SEGS Supports nodes - This is a node that supports ApplyControlNet (SEGS) from the Impact Pack.
|
||||
* `OpenPose Preprocessor Provider (SEGS)`: OpenPose preprocessor is applied for the purpose of using OpenPose ControlNet in SEGS.
|
||||
* You need to install [ControlNet Auxiliary Preprocessors](https://github.com/Fannovel16/comfyui_controlnet_aux) to use this.
|
||||
* `Canny Preprocessor Provider (SEGS)`: Canny preprocessor is applied for the purpose of using Canny ControlNet in SEGS.
|
||||
* `DW Preprocessor Provider (SEGS)`, `MiDaS Depth Map Preprocessor Provider (SEGS)`, `LeReS Depth Map Preprocessor Provider (SEGS)`,
|
||||
`MediaPipe FaceMesh Preprocessor Provider (SEGS)`, `HED Preprocessor Provider (SEGS)`, `Fake Scribble Preprocessor (SEGS)`,
|
||||
`AnimeLineArt Preprocessor Provider (SEGS)`, `Manga2Anime LineArt Preprocessor Provider (SEGS)`, `LineArt Preprocessor Provider (SEGS)`,
|
||||
`Color Preprocessor Provider (SEGS)`, `Inpaint Preprocessor Provider (SEGS)`, `Tile Preprocessor Provider (SEGS)`, `MeshGraphormer Depth Map Preprocessor Provider (SEGS)`
|
||||
* `MediaPipeFaceMeshDetectorProvider`: This node provides `BBOX_DETECTOR` and `SEGM_DETECTOR` that can be used in Impact Pack's Detector using the `MediaPipe-FaceMesh Preprocessor` of ControlNet Auxiliary Preprocessors.
|
||||
|
||||
|
||||
### A1111 Compatibility support - These nodes assists in replicating the creation of A1111 in ComfyUI exactly.
|
||||
* `KSampler (Inspire)`: ComfyUI uses the CPU for generating random noise, while A1111 uses the GPU. One of the three factors that significantly impact reproducing A1111's results in ComfyUI can be addressed using `KSampler (Inspire)`.
|
||||
* Other point #1 : Please make sure you haven't forgotten to include 'embedding:' in the embedding used in the prompt, like 'embedding:easynegative.'
|
||||
* Other point #2 : ComfyUI and A1111 have different interpretations of weighting. To align them, you need to use [BlenderNeko/Advanced CLIP Text Encode](https://github.com/BlenderNeko/ComfyUI_ADV_CLIP_emb).
|
||||
* `KSamplerAdvanced (Inspire)`: Inspire Pack version of `KSampler (Advanced)`.
|
||||
* `RandomNoise (inspire)`: Inspire Pack version of `RandomNoise`.
|
||||
* Common Parameters
|
||||
* `batch_seed_mode` determines how seeds are applied to batch latents:
|
||||
* `comfy`: This method applies the noise to batch latents all at once. This is advantageous to prevent duplicate images from being generated due to seed duplication when creating images.
|
||||
* `incremental`: Similar to the A1111 case, this method incrementally increases the seed and applies noise sequentially for each batch. This approach is beneficial for straightforward reproduction using only the seed.
|
||||
* `variation_strength`: In each batch, the variation strength starts from the set `variation_strength` and increases by `xxx`.
|
||||
* `variation_seed` and `variation_strength` - Initial noise generated by the seed is transformed to the shape of `variation_seed` by `variation_strength`. If `variation_strength` is 0, it only relies on the influence of the seed, and if `variation_strength` is 1.0, it is solely influenced by `variation_seed`.
|
||||
* These parameters are used when you want to maintain the composition of an image generated by the seed but wish to introduce slight changes.
|
||||
|
||||
|
||||
### Sampler nodes
|
||||
* `KSampler Progress (Inspire)` - In KSampler, the sampling process generates latent batches. By using `Video Combine` node from [ComfyUI-VideoHelperSuite](https://github.com/Kosinkadink/ComfyUI-VideoHelperSuite), you can create a video from the progress.
|
||||
* `Scheduled CFGGuider (Inspire)` - This is a CFGGuider that adjusts the schedule from from_cfg to to_cfg using linear, log, and exp methods.
|
||||
* `Scheduled PerpNeg CFGGuider (Inspire)` - This is a PerpNeg CFGGuider that adjusts the schedule from from_cfg to to_cfg using linear, log, and exp methods.
|
||||
|
||||
|
||||
### Prompt Support - These are nodes for supporting prompt processing.
|
||||
* `Load Prompts From Dir (Inspire)`: It sequentially reads prompts files from the specified directory. The output it returns is ZIPPED_PROMPT.
|
||||
* Specify the directories located under `ComfyUI-Inspire-Pack/prompts/`
|
||||
* One prompts file can have multiple prompts separated by `---`.
|
||||
* e.g. `prompts/example`
|
||||
* **NOTE**: This node provides advanced option via `Show advanced`
|
||||
* load_cap, start_index
|
||||
|
||||
* `Load Prompts From File (Inspire)`: It sequentially reads prompts from the specified file. The output it returns is ZIPPED_PROMPT.
|
||||
* Specify the file located under `ComfyUI-Inspire-Pack/prompts/`
|
||||
* e.g. `prompts/example/prompt2.txt`
|
||||
* **NOTE**: This node provides advanced option via `Show advanced`
|
||||
* load_cap, start_index
|
||||
|
||||
* `Load Single Prompt From File (Inspire)`: Loads a single prompt from a file containing multiple prompts by using an index.
|
||||
* The prompts file directory can be specified as `inspire_prompts` in `extra_model_paths.yaml`
|
||||
* `Unzip Prompt (Inspire)`: Separate ZIPPED_PROMPT into `positive`, `negative`, and name components.
|
||||
* `positive` and `negative` represent text prompts, while `name` represents the name of the prompt. When loaded from a file using `Load Prompts From File (Inspire)`, the name corresponds to the file name.
|
||||
* `Zip Prompt (Inspire)`: Create ZIPPED_PROMPT from positive, negative, and name_opt.
|
||||
* If name_opt is omitted, it will be considered as an empty name.
|
||||
* `Prompt Extractor (Inspire)`: This node reads prompt information from the image's metadata. Since it retrieves all the text, you need to directly specify the prompts to be used for `positive` and `negative` as indicated in the info.
|
||||
* `Global Seed (Inspire)`: This is a node that controls the global seed without a separate connection line. It only controls when the widget's name is 'seed' or 'noise_seed'. Additionally, if 'control_before_generate' is checked, it controls the seed before executing the prompt.
|
||||
* Seeds that have been converted into inputs are excluded from the target. If you want to control the seed separately, convert it into an input and control it separately.
|
||||
* `Global Sampler (Inspire)`: This node is similar to GlobalSeed and can simultaneously set the sampler_name and scheduler for all nodes in the workflow.
|
||||
* It applies only to nodes that have both sampler_name and scheduler, and it won't be effective if `GlobalSampler` is muted.
|
||||
* If some of the `sampler_name` and `scheduler` have been converted to input and connected to Primitive node, it will not apply only to the converted widget. The widget that has not been converted to input will still be affected.
|
||||
* `Bind [ImageList, PromptList] (Inspire)`: Bind Image list and zipped prompt list to export `image`, `positive`, `negative`, and `prompt_label` in a list format. If there are more prompts than images, the excess prompts are ignored, and if there are not enough, the remainder is filled with default input based on the images.
|
||||
* `Wildcard Encode (Inspire)`: The combination node of [ImpactWildcardEncode](https://github.com/ltdrdata/ComfyUI-extension-tutorials/blob/Main/ComfyUI-Impact-Pack/tutorial/ImpactWildcard.md) and BlenderNeko's [CLIP Text Encode (Advanced)](https://github.com/BlenderNeko/ComfyUI_ADV_CLIP_emb).
|
||||
* To use this node, you need both the [Impact Pack](https://github.com/ltdrdata/ComfyUI-Impact-Pack) and the [Advanced CLIP Text Encode]((https://github.com/BlenderNeko/ComfyUI_ADV_CLIP_emb)) extensions.
|
||||
* This node is identical to `ImpactWildcardEncode`, but it encodes using `CLIP Text Encode (Advanced)` instead of the default CLIP Text Encode from ComfyUI for CLIP Text Encode.
|
||||
* Requirement: Impact Pack V4.18.6 or above
|
||||
* `Prompt Builder (Inspire)`: This node is a convenience node that allows you to easily assemble prompts by selecting categories and presets. To modify the presets, edit the `ComfyUI-InspirePack/resources/prompt-builder.yaml` file.
|
||||
* `Seed Explorer (Inspire)`: This node helps explore seeds by allowing you to adjust the variation seed gradually in a prompt-like form.
|
||||
* This feature is designed for utilizing a seed that you like, adding slight variations, and then further modifying from there when exploring.
|
||||
* In the `seed_prompt`, the first seed is considered the initial seed, and the reflection rate is omitted, always defaulting to 1.0.
|
||||
* Each prompt is separated by a comma, and from the second seed onwards, it should follow the format `seed:strength`.
|
||||
* Pressing the "Add to prompt" button will append `additional_seed:additional_strength` to the prompt.
|
||||
* `Composite Noise (Inspire)`: This node overwrites a specific area on top of the destination noise with the source noise.
|
||||
* `Random Generator for List (Inspire)`: When connecting the list output to the signal input, this node generates random values for all items in the list.
|
||||
* `Make Basic Pipe (Inspire)`: This is a node that creates a BASIC_PIPE using Wildcard Encode. The `Add select to` determines whether the selected item from the `Select to...` combo will be input as positive wildcard text or negative wildcard text.
|
||||
* `Remove ControlNet (Inspire)`, `Remove ControlNet [RegionalPrompts] (Inspire)`: Remove ControlNet from CONDITIONING or REGIONAL_PROMPTS.
|
||||
* `Remove ControlNet [RegionalPrompts] (Inspire)` requires Impact Pack V4.73.1 or above.
|
||||
|
||||
### Regional Nodes - These node simplifies the application of prompts by region.
|
||||
* Regional Sampler - These nodes assists in the easy utilization of the regional sampler in the `Impact Pack`.
|
||||
* `Regional Prompt Simple (Inspire)`: This node takes `mask` and `basic_pipe` as inputs and simplifies the creation of `REGIONAL_PROMPTS`.
|
||||
* `Regional Prompt By Color Mask (Inspire)`: Similar to `Regional Prompt Simple (Inspire)`, this function accepts a color mask image as input and defines the region using the color value that will be used as the mask, instead of directly receiving the mask.
|
||||
* The color value can only be in the form of a hex code like #FFFF00 or a decimal number.
|
||||
* Regional Conditioning - These nodes provides assistance for simplifying the use of `Conditioning (Set Mask)`.
|
||||
* `Regional Conditioning Simple (Inspire)`
|
||||
* `Regional Conditioning By Color Mask (Inspire)`
|
||||
* Regional IPAdapter - These nodes facilitates the convenient use of the attn_mask feature in `ComfyUI IPAdapter Plus` custom nodes.
|
||||
* To use this node, you need to install the [ComfyUI IPAdapter Plus](https://github.com/cubiq/ComfyUI_IPAdapter_plus) extension.
|
||||
* `Regional IPAdapter Mask (Inspire)`, `Regional IPAdapter By Color Mask (Inspire)`
|
||||
* `Regional IPAdapter Encoded Mask (Inspire)`, `Regional IPAdapter Encoded By Color Mask (Inspire)`: accept `embeds` instead of `image`
|
||||
* Regional Seed Explorer - These nodes restrict the variation through a seed prompt, applying it only to the masked areas.
|
||||
* `Regional Seed Explorer By Mask (Inspire)`
|
||||
* `Regional Seed Explorer By Color Mask (Inspire)`
|
||||
* `Regional CFG (Inspire)` - By applying a mask as a multiplier to the configured cfg, it allows different areas to have different cfg settings.
|
||||
* `Color Mask To Depth Mask (Inspire)` - Convert the color map from the spec text into a mask with depth values ranging from 0.0 to 1.0.
|
||||
* The range of the mask value is limited to 0.0 to 1.0.
|
||||
* base_value: Sets the value of the base mask.
|
||||
* dilation: Dilation applied to each mask layer before flattening.
|
||||
* flatten_method: The method of flattening the mask layers.
|
||||
* The layers are flattened including the base layer set by base_value.
|
||||
* override: Each pixel is overwritten by the non-zero value of the upper layer.
|
||||
* sum: Each pixel is flattened by summing the values of all layers.
|
||||
* max: Each pixel is flattened by taking the maximum value from all layers.
|
||||
|
||||
### Image Util
|
||||
* `Load Image Batch From Dir (Inspire)`: This is almost same as `LoadImagesFromDirectory` of [ComfyUI-Advanced-Controlnet](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet). This is just a modified version. Just note that this node forcibly normalizes the size of the loaded image to match the size of the first image, even if they are not the same size, to create a batch image.
|
||||
* `Load Image List From Dir (Inspire)`: This is almost same as `Load Image Batch From Dir (Inspire)`. However, note that this node loads data in a list format, not as a batch, so it returns images at their original size without normalizing the size.
|
||||
* `Load Image (Inspire)`: This node is similar to LoadImage, but the loaded image information is stored in the workflow. The image itself is stored in the workflow, making it easier to reproduce image generation on other computers.
|
||||
* `Change Image Batch Size (Inspire)`: Change Image Batch Size
|
||||
* `simple`: if the `batch_size` is larger than the batch size of the input image, the last frame will be duplicated. If it is smaller, it will be simply cropped.
|
||||
* `Change Latent Batch Size (Inspire)`: Change Latent Batch Size
|
||||
* `ImageBatchSplitter //Inspire`, `LatentBatchSplitter //Inspire`: The script divides a batch of images/latents into individual images/latents, each with a quantity equal to the specified `split_count`. An additional output slot is added for each `split_count`. If the number of images/latents exceeds the `split_count`, the remaining ones are returned as the "remained" output.
|
||||
* `Color Map To Masks (Inspire)`: From the color_map, it extracts the top max_count number of colors and creates masks. min_pixels represents the minimum number of pixels for each color.
|
||||
* `Select Nth Mask (Inspire)`: Extracts the nth mask from the mask batch.
|
||||
|
||||
### Backend Cache - Nodes for storing arbitrary data from the backend in a cache and sharing it across multiple workflows.
|
||||
* `Cache Backend Data (Inspire)`: Stores any backend data in the cache using a string key. Tags are for quick reference.
|
||||
* `Retrieve Backend Data (Inspire)`: Retrieves cached backend data using a string key.
|
||||
* `Remove Backend Data (Inspire)`: Removes cached backend data.
|
||||
* Deletion in this node only removes it from the cache managed by Inspire, and if it's still in use elsewhere, it won't be completely removed from memory.
|
||||
* `signal_opt` is used to control the order of execution for this node; it will still run without a `signal_opt` input.
|
||||
* When using '*' as the key, it clears all data.
|
||||
* `Show Cached Info (Inspire)`: Displays information about cached data.
|
||||
* Default tag cache size is 5. You can edit the default size of each tag in `cache_settings.json`.
|
||||
* Runtime tag cache size can be modified on the `Show Cached Info (Inspire)` node. For example: `ckpt: 10`.
|
||||
* `Cache Backend Data [NumberKey] (Inspire)`, `Retrieve Backend Data [NumberKey] (Inspire)`, `Remove Backend Data [NumberKey] (Inspire)`: These nodes are provided for convenience in the automation process, allowing the use of numbers as keys.
|
||||
* `Cache Backend Data List (Inspire)`, `Cache Backend Data List [NumberKey] (Inspire)`: This node allows list input for backend cache. Conversely, nodes like `Cache Backend Data [NumberKey] (Inspire)` that do not accept list input will attempt to cache redundantly and overwrite existing data if provided with a list input. Therefore, it is necessary to use a unique key for each element to prevent this. This node caches the combined list. When retrieving cached backend data through this node, the output is in the form of a list.
|
||||
* `Shared Checkpoint Loader (Inspire)`: When loading a checkpoint through this loader, it is automatically cached in the backend cache. Additionally, if it is already cached, it retrieves it from the cache instead of loading it anew.
|
||||
* When `key_opt` is empty, the `ckpt_name` is set as the cache key. The cache key output can be used for deletion purposes with Remove Back End.
|
||||
* This node resolves the issue of reloading checkpoints during workflow switching.
|
||||
* `Shared Diffusion Model Loader (Inspire)`: Similar to the `Shared Checkpoint Loader (Inspire)` but used for loading Diffusion models instead of Checkpoints.
|
||||
* `Shared Text Encoder Loader (Inspire)`: Similar to the `Shared Checkpoint Loader (Inspire)` but used for loading Text Encoder models instead of Checkpoints.
|
||||
* This node also functions as a unified node for `CLIPLoader`, `DualCLIPLoader`, and `TripleCLIPLoader`.
|
||||
* `Stable Cascade Checkpoint Loader (Inspire)`: This node provides a feature that allows you to load the `stage_b` and `stage_c` checkpoints of Stable Cascade at once, and it also provides a backend caching feature, optionally.
|
||||
* `Is Cached (Inspire)`: Returns whether the cache exists.
|
||||
|
||||
### Conditioning - Nodes for conditionings
|
||||
* `Concat Conditionings with Multiplier (Inspire)`: Concatenating an arbitrary number of Conditionings while applying a multiplier for each Conditioning. The multiplier depends on `comfy_PoP`, so [comfy_PoP](https://github.com/picturesonpictures/comfy_PoP) must be installed.
|
||||
* `Conditioning Upscale (Inspire)`: When upscaling an image, it helps to expand the conditioning area according to the upscale factor. Taken from [ComfyUI_Dave_CustomNode](https://github.com/Davemane42/ComfyUI_Dave_CustomNode)
|
||||
* `Conditioning Stretch (Inspire)`: When upscaling an image, it helps to expand the conditioning area by specifying the original resolution and the new resolution to be applied. Taken from [ComfyUI_Dave_CustomNode](https://github.com/Davemane42/ComfyUI_Dave_CustomNode)
|
||||
|
||||
### Models - Nodes for models
|
||||
* `IPAdapter Model Helper (Inspire)`: This provides presets that allow for easy loading of the IPAdapter related models. However, it is essential for the model's name to be accurate.
|
||||
* You can download the appropriate model through ComfyUI-Manager.
|
||||
|
||||
### List - Nodes for List processing
|
||||
* `Float Range (Inspire)`: Create a float list that increases the value by `step` from `start` to `stop`. A list as large as the maximum limit is created, and when `ensure_end` is enabled, the last value of the list becomes the stop value.
|
||||
* `Worklist To Item List (Inspire)`: The list in ComfyUI allows for repeated execution of a sub-workflow. This groups these repetitions (a.k.a. list) into a single ITEM_LIST output. ITEM_LIST can then be used in ForeachList.
|
||||
* `▶Foreach List (Inspire)`: A starting node for performing iterative tasks by retrieving items one by one from the ITEM_LIST.\nGenerate a new intermediate_output using item and intermediate_output as inputs, then connect it to ForeachListEnd.\nNOTE:If initial_input is omitted, the first item in item_list is used as the initial value, and the processing starts from the second item in item_list.
|
||||
* `Foreach List◀ (Inspire)`: An end node for performing iterative tasks by retrieving items one by one from the ITEM_LIST.\nNOTE:Directly connect the outputs of ForeachListBegin to 'flow_control' and 'remained_list'.
|
||||
* `Drop List (Inspire)`: Removes all items from the ITEM_LIST. If the ITEM_LIST generated through this node is passed to ForeachListEnd, the process is immediately terminated.
|
||||
|
||||
### Util - Utilities
|
||||
* `ToIPAdapterPipe (Inspire)`, `FromIPAdapterPipe (Inspire)`: These nodes assists in conveniently using the bundled ipadapter_model, clip_vision, and model required for applying IPAdapter.
|
||||
* `List Counter (Inspire)`: When each item in the list traverses through this node, it increments a counter by one, generating an integer value.
|
||||
* `RGB Hex To HSV (Inspire)`: Convert an RGB hex string like `#FFD500` to HSV:
|
||||
|
||||
## Credits
|
||||
|
||||
ComfyUI/[ComfyUI](https://github.com/comfyanonymous/ComfyUI) - A powerful and modular stable diffusion GUI.
|
||||
|
||||
ComfyUI/[sd-webui-lora-block-weight](https://github.com/hako-mikan/sd-webui-lora-block-weight) - The original idea for LoraBlockWeight came from here, and it is based on the syntax of this extension.
|
||||
|
||||
jags111/[efficiency-nodes-comfyui](https://github.com/jags111/ComfyUI-Jags-workflows) - The `XY Input` provided by the Inspire Pack supports the `XY Plot` of this node.
|
||||
|
||||
Fannovel16/[comfyui_controlnet_aux](https://github.com/Fannovel16/comfyui_controlnet_aux) - The wrapper for the controlnet preprocessor in the Inspire Pack depends on these nodes.
|
||||
|
||||
Kosinkadink/[ComfyUI-Advanced-Controlnet](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet) - `Load Images From Dir (Inspire)` code is came from here.
|
||||
|
||||
Trung0246/[ComfyUI-0246](https://github.com/Trung0246/ComfyUI-0246) - Nice bypass hack!
|
||||
|
||||
cubiq/[ComfyUI_IPAdapter_plus](https://github.com/cubiq/ComfyUI_IPAdapter_plus) - IPAdapter related nodes depend on this extension.
|
||||
|
||||
Davemane42/[ComfyUI_Dave_CustomNode](https://github.com/Davemane42/ComfyUI_Dave_CustomNode) - Original author of ConditioningStretch, ConditioningUpscale
|
||||
|
||||
BlenderNeko/[ComfyUI_Noise](https://github.com/BlenderNeko/ComfyUI_Noise) - slerp code for noise variation
|
||||
|
||||
BadCafeCode/[execution-inversion-demo-comfyui](https://github.com/BadCafeCode/execution-inversion-demo-comfyui) - reference loop implementation for ComfyUI
|
||||
41
custom_nodes/comfyui-inspire-pack/__init__.py
Normal file
41
custom_nodes/comfyui-inspire-pack/__init__.py
Normal file
@@ -0,0 +1,41 @@
|
||||
"""
|
||||
@author: Dr.Lt.Data
|
||||
@title: Inspire Pack
|
||||
@nickname: Inspire Pack
|
||||
@description: This extension provides various nodes to support Lora Block Weight, Regional Nodes, Backend Cache, Prompt Utils, List Utils and the Impact Pack.
|
||||
"""
|
||||
|
||||
import importlib
|
||||
import logging
|
||||
|
||||
version_code = [1, 23]
|
||||
version_str = f"V{version_code[0]}.{version_code[1]}" + (f'.{version_code[2]}' if len(version_code) > 2 else '')
|
||||
logging.info(f"### Loading: ComfyUI-Inspire-Pack ({version_str})")
|
||||
|
||||
node_list = [
|
||||
"lora_block_weight",
|
||||
"segs_support",
|
||||
"a1111_compat",
|
||||
"prompt_support",
|
||||
"inspire_server",
|
||||
"image_util",
|
||||
"regional_nodes",
|
||||
"sampler_nodes",
|
||||
"backend_support",
|
||||
"list_nodes",
|
||||
"conditioning_nodes",
|
||||
"model_nodes",
|
||||
"util_nodes"
|
||||
]
|
||||
|
||||
NODE_CLASS_MAPPINGS = {}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {}
|
||||
|
||||
for module_name in node_list:
|
||||
imported_module = importlib.import_module(".inspire.{}".format(module_name), __name__)
|
||||
|
||||
NODE_CLASS_MAPPINGS = {**NODE_CLASS_MAPPINGS, **imported_module.NODE_CLASS_MAPPINGS}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {**NODE_DISPLAY_NAME_MAPPINGS, **imported_module.NODE_DISPLAY_NAME_MAPPINGS}
|
||||
|
||||
WEB_DIRECTORY = "./js"
|
||||
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
|
||||
5
custom_nodes/comfyui-inspire-pack/cache_settings.json
Normal file
5
custom_nodes/comfyui-inspire-pack/cache_settings.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"ckpt": 5,
|
||||
"latent": 100,
|
||||
"image": 100
|
||||
}
|
||||
460
custom_nodes/comfyui-inspire-pack/inspire/a1111_compat.py
Normal file
460
custom_nodes/comfyui-inspire-pack/inspire/a1111_compat.py
Normal file
@@ -0,0 +1,460 @@
|
||||
import comfy
|
||||
import torch
|
||||
from .libs import utils
|
||||
from einops import rearrange
|
||||
import random
|
||||
import math
|
||||
from .libs import common
|
||||
import logging
|
||||
|
||||
|
||||
supported_noise_modes = ["GPU(=A1111)", "CPU", "GPU+internal_seed", "CPU+internal_seed"]
|
||||
|
||||
|
||||
class Inspire_RandomNoise:
|
||||
def __init__(self, seed, mode, incremental_seed_mode, variation_seed, variation_strength, variation_method="linear", internal_seed=None):
|
||||
device = comfy.model_management.get_torch_device()
|
||||
# HOTFIX: https://github.com/comfyanonymous/ComfyUI/commit/916d1e14a93ef331adef7c0deff2fdcf443b05cf#commitcomment-151914788
|
||||
# seed value should be different with generated noise
|
||||
|
||||
self.seed = internal_seed
|
||||
self.noise_seed = seed
|
||||
self.noise_device = "cpu" if mode == "CPU" else device
|
||||
self.incremental_seed_mode = incremental_seed_mode
|
||||
self.variation_seed = variation_seed
|
||||
self.variation_strength = variation_strength
|
||||
self.variation_method = variation_method
|
||||
|
||||
def generate_noise(self, input_latent):
|
||||
latent_image = input_latent["samples"]
|
||||
batch_inds = input_latent["batch_index"] if "batch_index" in input_latent else None
|
||||
noise = utils.prepare_noise(latent_image, self.noise_seed, batch_inds, self.noise_device, self.incremental_seed_mode,
|
||||
variation_seed=self.variation_seed, variation_strength=self.variation_strength, variation_method=self.variation_method)
|
||||
return noise.cpu()
|
||||
|
||||
|
||||
class RandomNoise:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"noise_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "tooltip": "This is the seed for the initial noise applied to the latent."}),
|
||||
"noise_mode": (["GPU(=A1111)", "CPU"],),
|
||||
"batch_seed_mode": (["incremental", "comfy", "variation str inc:0.01", "variation str inc:0.05"],),
|
||||
"variation_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
"variation_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
},
|
||||
"optional":
|
||||
{
|
||||
"variation_method": (["linear", "slerp"],),
|
||||
"internal_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "tooltip": "This is the seed used for generating noise in intermediate steps when using ancestral and SDE-based samplers.\nNOTE: If `noise_mode` is in GPU mode and `internal_seed` is the same as `seed`, the generated image may be distorted."}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("NOISE",)
|
||||
FUNCTION = "get_noise"
|
||||
CATEGORY = "InspirePack/a1111_compat"
|
||||
|
||||
def get_noise(self, noise_seed, noise_mode, batch_seed_mode, variation_seed, variation_strength, variation_method="linear", internal_seed=None):
|
||||
if internal_seed is None:
|
||||
internal_seed = noise_seed
|
||||
|
||||
return (Inspire_RandomNoise(noise_seed, noise_mode, batch_seed_mode, variation_seed, variation_strength, variation_method=variation_method, internal_seed=internal_seed),)
|
||||
|
||||
|
||||
def inspire_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent, denoise=1.0,
|
||||
noise_mode="CPU", disable_noise=False, start_step=None, last_step=None, force_full_denoise=False,
|
||||
incremental_seed_mode="comfy", variation_seed=None, variation_strength=None, noise=None, callback=None, variation_method="linear",
|
||||
scheduler_func=None, internal_seed=None):
|
||||
device = comfy.model_management.get_torch_device()
|
||||
noise_device = "cpu" if 'cpu' in noise_mode.lower() else device
|
||||
latent_image = latent["samples"]
|
||||
if hasattr(comfy.sample, 'fix_empty_latent_channels'):
|
||||
latent_image = comfy.sample.fix_empty_latent_channels(model, latent_image)
|
||||
|
||||
latent = latent.copy()
|
||||
|
||||
if noise is not None and latent_image.shape[1] != noise.shape[1]:
|
||||
logging.info("[Inspire Pack] inspire_ksampler: The type of latent input for noise generation does not match the model's latent type. When using the SD3 model, you must use the SD3 Empty Latent.")
|
||||
raise Exception("The type of latent input for noise generation does not match the model's latent type. When using the SD3 model, you must use the SD3 Empty Latent.")
|
||||
|
||||
if noise is None:
|
||||
if disable_noise:
|
||||
torch.manual_seed(seed)
|
||||
noise = torch.zeros(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, device=noise_device)
|
||||
else:
|
||||
batch_inds = latent["batch_index"] if "batch_index" in latent else None
|
||||
noise = utils.prepare_noise(latent_image, seed, batch_inds, noise_device, incremental_seed_mode,
|
||||
variation_seed=variation_seed, variation_strength=variation_strength, variation_method=variation_method)
|
||||
|
||||
if start_step is None:
|
||||
if denoise == 1.0:
|
||||
start_step = 0
|
||||
else:
|
||||
advanced_steps = math.floor(steps / denoise)
|
||||
start_step = advanced_steps - steps
|
||||
steps = advanced_steps
|
||||
|
||||
if internal_seed is None:
|
||||
internal_seed = seed
|
||||
|
||||
if 'internal_seed' in noise_mode:
|
||||
seed = internal_seed
|
||||
|
||||
try:
|
||||
samples = common.impact_sampling(
|
||||
model=model, add_noise=not disable_noise, seed=seed, steps=steps, cfg=cfg, sampler_name=sampler_name, scheduler=scheduler, positive=positive, negative=negative,
|
||||
latent_image=latent, start_at_step=start_step, end_at_step=last_step, return_with_leftover_noise=not force_full_denoise, noise=noise, callback=callback,
|
||||
scheduler_func=scheduler_func)
|
||||
except Exception as e:
|
||||
if "unexpected keyword argument 'scheduler_func'" in str(e):
|
||||
logging.info("[Inspire Pack] Impact Pack is outdated. (Cannot use GITS scheduler.)")
|
||||
|
||||
samples = common.impact_sampling(
|
||||
model=model, add_noise=not disable_noise, seed=seed, steps=steps, cfg=cfg, sampler_name=sampler_name, scheduler=scheduler, positive=positive, negative=negative,
|
||||
latent_image=latent, start_at_step=start_step, end_at_step=last_step, return_with_leftover_noise=not force_full_denoise, noise=noise, callback=callback)
|
||||
else:
|
||||
raise e
|
||||
|
||||
return samples, noise
|
||||
|
||||
|
||||
class KSampler_inspire:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required":
|
||||
{"model": ("MODEL",),
|
||||
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "tooltip": "This is the seed for the initial noise applied to the latent."}),
|
||||
"steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
|
||||
"cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0}),
|
||||
"sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
|
||||
"scheduler": (common.get_schedulers(), ),
|
||||
"positive": ("CONDITIONING", ),
|
||||
"negative": ("CONDITIONING", ),
|
||||
"latent_image": ("LATENT", ),
|
||||
"denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
"noise_mode": (supported_noise_modes,),
|
||||
"batch_seed_mode": (["incremental", "comfy", "variation str inc:0.01", "variation str inc:0.05"],),
|
||||
"variation_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
"variation_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
},
|
||||
"optional":
|
||||
{
|
||||
"variation_method": (["linear", "slerp"],),
|
||||
"scheduler_func_opt": ("SCHEDULER_FUNC",),
|
||||
"internal_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "tooltip": "This is the seed used for generating noise in intermediate steps when using ancestral and SDE-based samplers.\nNOTE: If `noise_mode` is in GPU mode and `internal_seed` is the same as `seed`, the generated image may be distorted."}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/a1111_compat"
|
||||
|
||||
@staticmethod
|
||||
def doit(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise, noise_mode,
|
||||
batch_seed_mode="comfy", variation_seed=None, variation_strength=None, variation_method="linear", scheduler_func_opt=None,
|
||||
internal_seed=None):
|
||||
return (inspire_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise, noise_mode,
|
||||
incremental_seed_mode=batch_seed_mode, variation_seed=variation_seed, variation_strength=variation_strength, variation_method=variation_method,
|
||||
scheduler_func=scheduler_func_opt, internal_seed=internal_seed)[0], )
|
||||
|
||||
|
||||
class KSamplerAdvanced_inspire:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required":
|
||||
{"model": ("MODEL",),
|
||||
"add_noise": ("BOOLEAN", {"default": True, "label_on": "enable", "label_off": "disable"}),
|
||||
"noise_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "tooltip": "This is the seed for the initial noise applied to the latent."}),
|
||||
"steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
|
||||
"cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.5, "round": 0.01}),
|
||||
"sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
|
||||
"scheduler": (common.get_schedulers(), ),
|
||||
"positive": ("CONDITIONING", ),
|
||||
"negative": ("CONDITIONING", ),
|
||||
"latent_image": ("LATENT", ),
|
||||
"start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000}),
|
||||
"end_at_step": ("INT", {"default": 10000, "min": 0, "max": 10000}),
|
||||
"noise_mode": (supported_noise_modes,),
|
||||
"return_with_leftover_noise": ("BOOLEAN", {"default": False, "label_on": "enable", "label_off": "disable"}),
|
||||
"batch_seed_mode": (["incremental", "comfy", "variation str inc:0.01", "variation str inc:0.05"],),
|
||||
"variation_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
"variation_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
},
|
||||
"optional":
|
||||
{
|
||||
"variation_method": (["linear", "slerp"],),
|
||||
"noise_opt": ("NOISE_IMAGE",),
|
||||
"scheduler_func_opt": ("SCHEDULER_FUNC",),
|
||||
"internal_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "tooltip": "This is the seed used for generating noise in intermediate steps when using ancestral and SDE-based samplers.\nNOTE: If `noise_mode` is in GPU mode and `internal_seed` is the same as `seed`, the generated image may be distorted."}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/a1111_compat"
|
||||
|
||||
@staticmethod
|
||||
def sample(model, add_noise, noise_seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, start_at_step, end_at_step, noise_mode, return_with_leftover_noise,
|
||||
denoise=1.0, batch_seed_mode="comfy", variation_seed=None, variation_strength=None, noise_opt=None, callback=None, variation_method="linear", scheduler_func_opt=None, internal_seed=None):
|
||||
force_full_denoise = True
|
||||
|
||||
if return_with_leftover_noise:
|
||||
force_full_denoise = False
|
||||
|
||||
disable_noise = False
|
||||
|
||||
if not add_noise:
|
||||
disable_noise = True
|
||||
|
||||
return inspire_ksampler(model, noise_seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image,
|
||||
denoise=denoise, disable_noise=disable_noise, start_step=start_at_step, last_step=end_at_step,
|
||||
force_full_denoise=force_full_denoise, noise_mode=noise_mode, incremental_seed_mode=batch_seed_mode,
|
||||
variation_seed=variation_seed, variation_strength=variation_strength, noise=noise_opt, callback=callback, variation_method=variation_method,
|
||||
scheduler_func=scheduler_func_opt, internal_seed=internal_seed)
|
||||
|
||||
def doit(self, *args, **kwargs):
|
||||
return (self.sample(*args, **kwargs)[0],)
|
||||
|
||||
|
||||
class KSampler_inspire_pipe:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required":
|
||||
{"basic_pipe": ("BASIC_PIPE",),
|
||||
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "tooltip": "This is the seed for the initial noise applied to the latent."}),
|
||||
"steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
|
||||
"cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0}),
|
||||
"sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
|
||||
"scheduler": (common.get_schedulers(), ),
|
||||
"latent_image": ("LATENT", ),
|
||||
"denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
"noise_mode": (supported_noise_modes,),
|
||||
"batch_seed_mode": (["incremental", "comfy", "variation str inc:0.01", "variation str inc:0.05"],),
|
||||
"variation_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
"variation_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
},
|
||||
"optional":
|
||||
{
|
||||
"scheduler_func_opt": ("SCHEDULER_FUNC",),
|
||||
"internal_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "tooltip": "This is the seed used for generating noise in intermediate steps when using ancestral and SDE-based samplers.\nNOTE: If `noise_mode` is in GPU mode and `internal_seed` is the same as `seed`, the generated image may be distorted."}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("LATENT", "VAE")
|
||||
FUNCTION = "sample"
|
||||
|
||||
CATEGORY = "InspirePack/a1111_compat"
|
||||
|
||||
def sample(self, basic_pipe, seed, steps, cfg, sampler_name, scheduler, latent_image, denoise, noise_mode, batch_seed_mode="comfy",
|
||||
variation_seed=None, variation_strength=None, scheduler_func_opt=None, internal_seed=None):
|
||||
model, clip, vae, positive, negative = basic_pipe
|
||||
latent = inspire_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise, noise_mode, incremental_seed_mode=batch_seed_mode,
|
||||
variation_seed=variation_seed, variation_strength=variation_strength, scheduler_func=scheduler_func_opt, internal_seed=internal_seed)[0]
|
||||
return latent, vae
|
||||
|
||||
|
||||
class KSamplerAdvanced_inspire_pipe:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required":
|
||||
{"basic_pipe": ("BASIC_PIPE",),
|
||||
"add_noise": ("BOOLEAN", {"default": True, "label_on": "enable", "label_off": "disable"}),
|
||||
"noise_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "tooltip": "This is the seed for the initial noise applied to the latent."}),
|
||||
"steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
|
||||
"cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.5, "round": 0.01}),
|
||||
"sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
|
||||
"scheduler": (common.get_schedulers(), ),
|
||||
"latent_image": ("LATENT", ),
|
||||
"start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000}),
|
||||
"end_at_step": ("INT", {"default": 10000, "min": 0, "max": 10000}),
|
||||
"noise_mode": (supported_noise_modes,),
|
||||
"return_with_leftover_noise": ("BOOLEAN", {"default": False, "label_on": "enable", "label_off": "disable"}),
|
||||
"batch_seed_mode": (["incremental", "comfy", "variation str inc:0.01", "variation str inc:0.05"],),
|
||||
"variation_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
"variation_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
},
|
||||
"optional":
|
||||
{
|
||||
"noise_opt": ("NOISE_IMAGE",),
|
||||
"scheduler_func_opt": ("SCHEDULER_FUNC",),
|
||||
"internal_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "tooltip": "This is the seed used for generating noise in intermediate steps when using ancestral and SDE-based samplers.\nNOTE: If `noise_mode` is in GPU mode and `internal_seed` is the same as `seed`, the generated image may be distorted."}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("LATENT", "VAE", )
|
||||
FUNCTION = "sample"
|
||||
|
||||
CATEGORY = "InspirePack/a1111_compat"
|
||||
|
||||
def sample(self, basic_pipe, add_noise, noise_seed, steps, cfg, sampler_name, scheduler, latent_image, start_at_step, end_at_step, noise_mode, return_with_leftover_noise,
|
||||
denoise=1.0, batch_seed_mode="comfy", variation_seed=None, variation_strength=None, noise_opt=None, scheduler_func_opt=None, internal_seed=None):
|
||||
model, clip, vae, positive, negative = basic_pipe
|
||||
latent = KSamplerAdvanced_inspire().sample(model=model, add_noise=add_noise, noise_seed=noise_seed,
|
||||
steps=steps, cfg=cfg, sampler_name=sampler_name, scheduler=scheduler,
|
||||
positive=positive, negative=negative, latent_image=latent_image,
|
||||
start_at_step=start_at_step, end_at_step=end_at_step,
|
||||
noise_mode=noise_mode, return_with_leftover_noise=return_with_leftover_noise,
|
||||
denoise=denoise, batch_seed_mode=batch_seed_mode, variation_seed=variation_seed,
|
||||
variation_strength=variation_strength, noise_opt=noise_opt, scheduler_func_opt=scheduler_func_opt,
|
||||
internal_seed=internal_seed)[0]
|
||||
return latent, vae
|
||||
|
||||
|
||||
# Modified version of ComfyUI main code
|
||||
# https://github.com/comfyanonymous/ComfyUI/blob/master/comfy_extras/nodes_hypertile.py
|
||||
def get_closest_divisors(hw: int, aspect_ratio: float) -> tuple[int, int]:
|
||||
pairs = [(i, hw // i) for i in range(int(math.sqrt(hw)), 1, -1) if hw % i == 0]
|
||||
pair = min(((i, hw // i) for i in range(2, hw + 1) if hw % i == 0),
|
||||
key=lambda x: abs(x[1] / x[0] - aspect_ratio))
|
||||
pairs.append(pair)
|
||||
res = min(pairs, key=lambda x: max(x) / min(x))
|
||||
return res
|
||||
|
||||
|
||||
def calc_optimal_hw(hw: int, aspect_ratio: float) -> tuple[int, int]:
|
||||
hcand = round(math.sqrt(hw * aspect_ratio))
|
||||
wcand = hw // hcand
|
||||
|
||||
if hcand * wcand != hw:
|
||||
wcand = round(math.sqrt(hw / aspect_ratio))
|
||||
hcand = hw // wcand
|
||||
|
||||
if hcand * wcand != hw:
|
||||
return get_closest_divisors(hw, aspect_ratio)
|
||||
|
||||
return hcand, wcand
|
||||
|
||||
|
||||
def random_divisor(value: int, min_value: int, /, max_options: int = 1, rand_obj=random.Random()) -> int:
|
||||
# print(f"value={value}, min_value={min_value}, max_options={max_options}")
|
||||
min_value = min(min_value, value)
|
||||
|
||||
# All big divisors of value (inclusive)
|
||||
divisors = [i for i in range(min_value, value + 1) if value % i == 0]
|
||||
|
||||
ns = [value // i for i in divisors[:max_options]] # has at least 1 element
|
||||
|
||||
if len(ns) - 1 > 0:
|
||||
idx = rand_obj.randint(0, len(ns) - 1)
|
||||
else:
|
||||
idx = 0
|
||||
# print(f"ns={ns}, idx={idx}")
|
||||
|
||||
return ns[idx]
|
||||
|
||||
# def get_divisors(value: int, min_value: int, /, max_options: int = 1) -> list[int]:
|
||||
# """
|
||||
# Returns divisors of value that
|
||||
# x * min_value <= value
|
||||
# in big -> small order, amount of divisors is limited by max_options
|
||||
# """
|
||||
# max_options = max(1, max_options) # at least 1 option should be returned
|
||||
# min_value = min(min_value, value)
|
||||
# divisors = [i for i in range(min_value, value + 1) if value % i == 0] # divisors in small -> big order
|
||||
# ns = [value // i for i in divisors[:max_options]] # has at least 1 element # big -> small order
|
||||
# return ns
|
||||
|
||||
|
||||
# def random_divisor(value: int, min_value: int, /, max_options: int = 1, rand_obj=None) -> int:
|
||||
# """
|
||||
# Returns a random divisor of value that
|
||||
# x * min_value <= value
|
||||
# if max_options is 1, the behavior is deterministic
|
||||
# """
|
||||
# print(f"value={value}, min_value={min_value}, max_options={max_options}")
|
||||
# ns = get_divisors(value, min_value, max_options=max_options) # get cached divisors
|
||||
# idx = rand_obj.randint(0, len(ns) - 1)
|
||||
# print(f"ns={ns}, idx={idx}")
|
||||
#
|
||||
# return ns[idx]
|
||||
|
||||
|
||||
class HyperTileInspire:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {"model": ("MODEL",),
|
||||
"tile_size": ("INT", {"default": 256, "min": 1, "max": 2048}),
|
||||
"swap_size": ("INT", {"default": 2, "min": 1, "max": 128}),
|
||||
"max_depth": ("INT", {"default": 0, "min": 0, "max": 10}),
|
||||
"scale_depth": ("BOOLEAN", {"default": False}),
|
||||
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
}}
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "patch"
|
||||
|
||||
CATEGORY = "InspirePack/__for_testing"
|
||||
|
||||
def patch(self, model, tile_size, swap_size, max_depth, scale_depth, seed):
|
||||
latent_tile_size = max(32, tile_size) // 8
|
||||
temp = None
|
||||
|
||||
rand_obj = random.Random()
|
||||
rand_obj.seed(seed)
|
||||
|
||||
def hypertile_in(q, k, v, extra_options):
|
||||
nonlocal temp
|
||||
model_chans = q.shape[-2]
|
||||
orig_shape = extra_options['original_shape']
|
||||
apply_to = []
|
||||
for i in range(max_depth + 1):
|
||||
apply_to.append((orig_shape[-2] / (2 ** i)) * (orig_shape[-1] / (2 ** i)))
|
||||
|
||||
if model_chans in apply_to:
|
||||
shape = extra_options["original_shape"]
|
||||
aspect_ratio = shape[-1] / shape[-2]
|
||||
|
||||
hw = q.size(1)
|
||||
# h, w = calc_optimal_hw(hw, aspect_ratio)
|
||||
h, w = round(math.sqrt(hw * aspect_ratio)), round(math.sqrt(hw / aspect_ratio))
|
||||
|
||||
factor = (2 ** apply_to.index(model_chans)) if scale_depth else 1
|
||||
nh = random_divisor(h, latent_tile_size * factor, swap_size, rand_obj)
|
||||
nw = random_divisor(w, latent_tile_size * factor, swap_size, rand_obj)
|
||||
|
||||
logging.debug(f"factor: {factor} <--- params.depth: {apply_to.index(model_chans)} / scale_depth: {scale_depth} / latent_tile_size={latent_tile_size}")
|
||||
# print(f"h: {h}, w:{w} --> nh: {nh}, nw: {nw}")
|
||||
|
||||
if nh * nw > 1:
|
||||
q = rearrange(q, "b (nh h nw w) c -> (b nh nw) (h w) c", h=h // nh, w=w // nw, nh=nh, nw=nw)
|
||||
temp = (nh, nw, h, w)
|
||||
# else:
|
||||
# temp = None
|
||||
|
||||
logging.debug(f"q={q} / k={k} / v={v}")
|
||||
return q, k, v
|
||||
|
||||
return q, k, v
|
||||
|
||||
def hypertile_out(out, extra_options):
|
||||
nonlocal temp
|
||||
if temp is not None:
|
||||
nh, nw, h, w = temp
|
||||
temp = None
|
||||
out = rearrange(out, "(b nh nw) hw c -> b nh nw hw c", nh=nh, nw=nw)
|
||||
out = rearrange(out, "b nh nw (h w) c -> b (nh h nw w) c", h=h // nh, w=w // nw)
|
||||
return out
|
||||
|
||||
m = model.clone()
|
||||
m.set_model_attn1_patch(hypertile_in)
|
||||
m.set_model_attn1_output_patch(hypertile_out)
|
||||
return (m, )
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"KSampler //Inspire": KSampler_inspire,
|
||||
"KSamplerAdvanced //Inspire": KSamplerAdvanced_inspire,
|
||||
"KSamplerPipe //Inspire": KSampler_inspire_pipe,
|
||||
"KSamplerAdvancedPipe //Inspire": KSamplerAdvanced_inspire_pipe,
|
||||
"RandomNoise //Inspire": RandomNoise,
|
||||
"HyperTile //Inspire": HyperTileInspire
|
||||
}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"KSampler //Inspire": "KSampler (inspire)",
|
||||
"KSamplerAdvanced //Inspire": "KSamplerAdvanced (inspire)",
|
||||
"KSamplerPipe //Inspire": "KSampler [pipe] (inspire)",
|
||||
"KSamplerAdvancedPipe //Inspire": "KSamplerAdvanced [pipe] (inspire)",
|
||||
"RandomNoise //Inspire": "RandomNoise (inspire)",
|
||||
"HyperTile //Inspire": "HyperTile (Inspire)"
|
||||
}
|
||||
764
custom_nodes/comfyui-inspire-pack/inspire/backend_support.py
Normal file
764
custom_nodes/comfyui-inspire-pack/inspire/backend_support.py
Normal file
@@ -0,0 +1,764 @@
|
||||
import json
|
||||
import os
|
||||
from .libs import common
|
||||
|
||||
import folder_paths
|
||||
import nodes
|
||||
from server import PromptServer
|
||||
|
||||
from .libs.utils import TaggedCache, any_typ
|
||||
|
||||
import logging
|
||||
|
||||
root_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
settings_file = os.path.join(root_dir, 'cache_settings.json')
|
||||
try:
|
||||
with open(settings_file) as f:
|
||||
cache_settings = json.load(f)
|
||||
except Exception as e:
|
||||
logging.error(e)
|
||||
cache_settings = {}
|
||||
cache = TaggedCache(cache_settings)
|
||||
cache_count = {}
|
||||
|
||||
|
||||
def update_cache(k, tag, v):
|
||||
cache[k] = (tag, v)
|
||||
cnt = cache_count.get(k)
|
||||
if cnt is None:
|
||||
cnt = 0
|
||||
cache_count[k] = cnt
|
||||
else:
|
||||
cache_count[k] += 1
|
||||
|
||||
|
||||
def cache_weak_hash(k):
|
||||
cnt = cache_count.get(k)
|
||||
if cnt is None:
|
||||
cnt = 0
|
||||
|
||||
return k, cnt
|
||||
|
||||
|
||||
class CacheBackendData:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"key": ("STRING", {"multiline": False, "placeholder": "Input data key (e.g. 'model a', 'chunli lora', 'girl latent 3', ...)"}),
|
||||
"tag": ("STRING", {"multiline": False, "placeholder": "Tag: short description"}),
|
||||
"data": (any_typ,),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = (any_typ,)
|
||||
RETURN_NAMES = ("data opt",)
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Backend"
|
||||
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@staticmethod
|
||||
def doit(key, tag, data):
|
||||
global cache
|
||||
|
||||
if key == '*':
|
||||
logging.warning("[Inspire Pack] CacheBackendData: '*' is reserved key. Cannot use that key")
|
||||
return (None,)
|
||||
|
||||
update_cache(key, tag, (False, data))
|
||||
return (data,)
|
||||
|
||||
|
||||
class CacheBackendDataNumberKey:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"key": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
"tag": ("STRING", {"multiline": False, "placeholder": "Tag: short description"}),
|
||||
"data": (any_typ,),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = (any_typ,)
|
||||
RETURN_NAMES = ("data opt",)
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Backend"
|
||||
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@staticmethod
|
||||
def doit(key, tag, data):
|
||||
global cache
|
||||
|
||||
update_cache(key, tag, (False, data))
|
||||
return (data,)
|
||||
|
||||
|
||||
class CacheBackendDataList:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"key": ("STRING", {"multiline": False, "placeholder": "Input data key (e.g. 'model a', 'chunli lora', 'girl latent 3', ...)"}),
|
||||
"tag": ("STRING", {"multiline": False, "placeholder": "Tag: short description"}),
|
||||
"data": (any_typ,),
|
||||
}
|
||||
}
|
||||
|
||||
INPUT_IS_LIST = True
|
||||
|
||||
RETURN_TYPES = (any_typ,)
|
||||
RETURN_NAMES = ("data opt",)
|
||||
OUTPUT_IS_LIST = (True,)
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Backend"
|
||||
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@staticmethod
|
||||
def doit(key, tag, data):
|
||||
global cache
|
||||
|
||||
if key == '*':
|
||||
logging.warning("[Inspire Pack] CacheBackendDataList: '*' is reserved key. Cannot use that key")
|
||||
return (None,)
|
||||
|
||||
update_cache(key[0], tag[0], (True, data))
|
||||
return (data,)
|
||||
|
||||
|
||||
class CacheBackendDataNumberKeyList:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"key": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
"tag": ("STRING", {"multiline": False, "placeholder": "Tag: short description"}),
|
||||
"data": (any_typ,),
|
||||
}
|
||||
}
|
||||
|
||||
INPUT_IS_LIST = True
|
||||
|
||||
RETURN_TYPES = (any_typ,)
|
||||
RETURN_NAMES = ("data opt",)
|
||||
OUTPUT_IS_LIST = (True,)
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Backend"
|
||||
|
||||
OUTPUT_NODE = True
|
||||
|
||||
def doit(self, key, tag, data):
|
||||
global cache
|
||||
update_cache(key[0], tag[0], (True, data))
|
||||
return (data,)
|
||||
|
||||
|
||||
class RetrieveBackendData:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"key": ("STRING", {"multiline": False, "placeholder": "Input data key (e.g. 'model a', 'chunli lora', 'girl latent 3', ...)"}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = (any_typ,)
|
||||
RETURN_NAMES = ("data",)
|
||||
OUTPUT_IS_LIST = (True,)
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Backend"
|
||||
|
||||
@staticmethod
|
||||
def doit(key):
|
||||
global cache
|
||||
|
||||
v = cache.get(key)
|
||||
|
||||
if v is None:
|
||||
logging.warning(f"[RetrieveBackendData] '{key}' is unregistered key.")
|
||||
return ([None],)
|
||||
|
||||
is_list, data = v[1]
|
||||
|
||||
if is_list:
|
||||
return (data,)
|
||||
else:
|
||||
return ([data],)
|
||||
|
||||
@staticmethod
|
||||
def IS_CHANGED(key):
|
||||
return cache_weak_hash(key)
|
||||
|
||||
|
||||
class RetrieveBackendDataNumberKey(RetrieveBackendData):
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"key": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class RemoveBackendData:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"key": ("STRING", {"multiline": False, "placeholder": "Input data key ('*' = clear all)"}),
|
||||
},
|
||||
"optional": {
|
||||
"signal_opt": (any_typ,),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = (any_typ,)
|
||||
RETURN_NAMES = ("signal",)
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Backend"
|
||||
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@staticmethod
|
||||
def doit(key, signal_opt=None):
|
||||
global cache
|
||||
|
||||
if key == '*':
|
||||
cache = TaggedCache(cache_settings)
|
||||
elif key in cache:
|
||||
del cache[key]
|
||||
else:
|
||||
logging.warning(f"[Inspire Pack] RemoveBackendData: invalid data key {key}")
|
||||
|
||||
return (signal_opt,)
|
||||
|
||||
|
||||
class RemoveBackendDataNumberKey(RemoveBackendData):
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"key": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
},
|
||||
"optional": {
|
||||
"signal_opt": (any_typ,),
|
||||
}
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def doit(key, signal_opt=None):
|
||||
global cache
|
||||
|
||||
if key in cache:
|
||||
del cache[key]
|
||||
else:
|
||||
logging.warning(f"[Inspire Pack] RemoveBackendDataNumberKey: invalid data key {key}")
|
||||
|
||||
return (signal_opt,)
|
||||
|
||||
|
||||
class ShowCachedInfo:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"cache_info": ("STRING", {"multiline": True, "default": ""}),
|
||||
"key": ("STRING", {"multiline": False, "default": ""}),
|
||||
},
|
||||
"hidden": {"unique_id": "UNIQUE_ID"},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ()
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Backend"
|
||||
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@staticmethod
|
||||
def get_data():
|
||||
global cache
|
||||
|
||||
text1 = "---- [String Key Caches] ----\n"
|
||||
text2 = "---- [Number Key Caches] ----\n"
|
||||
for k, v in cache.items():
|
||||
tag = 'N/A(tag)' if v[0] == '' else v[0]
|
||||
if isinstance(k, str):
|
||||
text1 += f'{k}: {tag}\n'
|
||||
else:
|
||||
text2 += f'{k}: {tag}\n'
|
||||
|
||||
text3 = "---- [TagCache Settings] ----\n"
|
||||
for k, v in cache._tag_settings.items():
|
||||
text3 += f'{k}: {v}\n'
|
||||
|
||||
for k, v in cache._data.items():
|
||||
if k not in cache._tag_settings:
|
||||
text3 += f'{k}: {v.maxsize}\n'
|
||||
|
||||
return f'{text1}\n{text2}\n{text3}'
|
||||
|
||||
@staticmethod
|
||||
def set_cache_settings(data: str):
|
||||
global cache
|
||||
settings = data.split("---- [TagCache Settings] ----\n")[-1].strip().split("\n")
|
||||
|
||||
new_tag_settings = {}
|
||||
for s in settings:
|
||||
k, v = s.split(":")
|
||||
new_tag_settings[k] = int(v.strip())
|
||||
if new_tag_settings == cache._tag_settings:
|
||||
# tag settings is not changed
|
||||
return
|
||||
|
||||
new_cache = TaggedCache(new_tag_settings)
|
||||
for k, v in cache.items():
|
||||
new_cache[k] = v
|
||||
cache = new_cache
|
||||
|
||||
def doit(self, cache_info, key, unique_id):
|
||||
text = ShowCachedInfo.get_data()
|
||||
PromptServer.instance.send_sync("inspire-node-feedback", {"node_id": unique_id, "widget_name": "cache_info", "type": "text", "data": text})
|
||||
|
||||
return {}
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, **kwargs):
|
||||
return float("NaN")
|
||||
|
||||
|
||||
class CheckpointLoaderSimpleShared(nodes.CheckpointLoaderSimple):
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"ckpt_name": (folder_paths.get_filename_list("checkpoints"), ),
|
||||
"key_opt": ("STRING", {"multiline": False, "placeholder": "If empty, use 'ckpt_name' as the key."}),
|
||||
},
|
||||
"optional": {
|
||||
"mode": (['Auto', 'Override Cache', 'Read Only'],),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("MODEL", "CLIP", "VAE", "STRING")
|
||||
RETURN_NAMES = ("model", "clip", "vae", "cache key")
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Backend"
|
||||
|
||||
def doit(self, ckpt_name, key_opt, mode='Auto'):
|
||||
if mode == 'Read Only':
|
||||
if key_opt.strip() == '':
|
||||
raise Exception("[CheckpointLoaderSimpleShared] key_opt cannot be omit if mode is 'Read Only'")
|
||||
key = key_opt.strip()
|
||||
elif key_opt.strip() == '':
|
||||
key = ckpt_name
|
||||
else:
|
||||
key = key_opt.strip()
|
||||
|
||||
if key not in cache or mode == 'Override Cache':
|
||||
res = self.load_checkpoint(ckpt_name)
|
||||
update_cache(key, "ckpt", (False, res))
|
||||
cache_kind = 'ckpt'
|
||||
logging.info(f"[Inspire Pack] CheckpointLoaderSimpleShared: Ckpt '{ckpt_name}' is cached to '{key}'.")
|
||||
else:
|
||||
cache_kind, (_, res) = cache[key]
|
||||
logging.info(f"[Inspire Pack] CheckpointLoaderSimpleShared: Cached ckpt '{key}' is loaded. (Loading skip)")
|
||||
|
||||
if cache_kind == 'ckpt':
|
||||
model, clip, vae = res
|
||||
elif cache_kind == 'unclip_ckpt':
|
||||
model, clip, vae, _ = res
|
||||
else:
|
||||
raise Exception(f"[CheckpointLoaderSimpleShared] Unexpected cache_kind '{cache_kind}'")
|
||||
|
||||
return model, clip, vae, key
|
||||
|
||||
@staticmethod
|
||||
def IS_CHANGED(ckpt_name, key_opt, mode='Auto'):
|
||||
if mode == 'Read Only':
|
||||
if key_opt.strip() == '':
|
||||
raise Exception("[CheckpointLoaderSimpleShared] key_opt cannot be omit if mode is 'Read Only'")
|
||||
key = key_opt.strip()
|
||||
elif key_opt.strip() == '':
|
||||
key = ckpt_name
|
||||
else:
|
||||
key = key_opt.strip()
|
||||
|
||||
if mode == 'Read Only':
|
||||
return (None, cache_weak_hash(key))
|
||||
elif mode == 'Override Cache':
|
||||
return (ckpt_name, key)
|
||||
|
||||
return (None, cache_weak_hash(key))
|
||||
|
||||
|
||||
class LoadDiffusionModelShared(nodes.UNETLoader):
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": { "model_name": (folder_paths.get_filename_list("diffusion_models"), {"tooltip": "Diffusion Model Name"}),
|
||||
"weight_dtype": (["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"],),
|
||||
"key_opt": ("STRING", {"multiline": False, "placeholder": "If empty, use 'model_name' as the key."}),
|
||||
"mode": (['Auto', 'Override Cache', 'Read Only'],),
|
||||
}
|
||||
}
|
||||
RETURN_TYPES = ("MODEL", "STRING")
|
||||
RETURN_NAMES = ("model", "cache key")
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Backend"
|
||||
|
||||
def doit(self, model_name, weight_dtype, key_opt, mode='Auto'):
|
||||
if mode == 'Read Only':
|
||||
if key_opt.strip() == '':
|
||||
raise Exception("[LoadDiffusionModelShared] key_opt cannot be omit if mode is 'Read Only'")
|
||||
key = key_opt.strip()
|
||||
elif key_opt.strip() == '':
|
||||
key = f"{model_name}_{weight_dtype}"
|
||||
else:
|
||||
key = key_opt.strip()
|
||||
|
||||
if key not in cache or mode == 'Override Cache':
|
||||
model = self.load_unet(model_name, weight_dtype)[0]
|
||||
update_cache(key, "diffusion", (False, model))
|
||||
logging.info(f"[Inspire Pack] LoadDiffusionModelShared: diffusion model '{model_name}' is cached to '{key}'.")
|
||||
else:
|
||||
_, (_, model) = cache[key]
|
||||
logging.info(f"[Inspire Pack] LoadDiffusionModelShared: Cached diffusion model '{key}' is loaded. (Loading skip)")
|
||||
|
||||
return model, key
|
||||
|
||||
@staticmethod
|
||||
def IS_CHANGED(model_name, weight_dtype, key_opt, mode='Auto'):
|
||||
if mode == 'Read Only':
|
||||
if key_opt.strip() == '':
|
||||
raise Exception("[LoadDiffusionModelShared] key_opt cannot be omit if mode is 'Read Only'")
|
||||
key = key_opt.strip()
|
||||
elif key_opt.strip() == '':
|
||||
key = f"{model_name}_{weight_dtype}"
|
||||
else:
|
||||
key = key_opt.strip()
|
||||
|
||||
if mode == 'Read Only':
|
||||
return None, cache_weak_hash(key)
|
||||
elif mode == 'Override Cache':
|
||||
return model_name, key
|
||||
|
||||
return None, cache_weak_hash(key)
|
||||
|
||||
|
||||
class LoadTextEncoderShared:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": { "model_name1": (folder_paths.get_filename_list("text_encoders"), ),
|
||||
"model_name2": (["None"] + folder_paths.get_filename_list("text_encoders"), ),
|
||||
"model_name3": (["None"] + folder_paths.get_filename_list("text_encoders"), ),
|
||||
"type": (["stable_diffusion", "stable_cascade", "sd3", "stable_audio", "mochi", "ltxv", "pixart", "cosmos", "sdxl", "flux", "hunyuan_video"], ),
|
||||
"key_opt": ("STRING", {"multiline": False, "placeholder": "If empty, use 'model_name' as the key."}),
|
||||
"mode": (['Auto', 'Override Cache', 'Read Only'],),
|
||||
},
|
||||
"optional": { "device": (["default", "cpu"], {"advanced": True}), }
|
||||
}
|
||||
RETURN_TYPES = ("CLIP", "STRING")
|
||||
RETURN_NAMES = ("clip", "cache key")
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Backend"
|
||||
|
||||
DESCRIPTION = \
|
||||
("[Recipes single]\n"
|
||||
"stable_diffusion: clip-l\n"
|
||||
"stable_cascade: clip-g\n"
|
||||
"sd3: t5 / clip-g / clip-l\n"
|
||||
"stable_audio: t5\n"
|
||||
"mochi: t5\n"
|
||||
"cosmos: old t5 xxl\n\n"
|
||||
"[Recipes dual]\n"
|
||||
"sdxl: clip-l, clip-g\n"
|
||||
"sd3: clip-l, clip-g / clip-l, t5 / clip-g, t5\n"
|
||||
"flux: clip-l, t5\n\n"
|
||||
"[Recipes triple]\n"
|
||||
"sd3: clip-l, clip-g, t5")
|
||||
|
||||
def doit(self, model_name1, model_name2, model_name3, type, key_opt, mode='Auto', device="default"):
|
||||
if mode == 'Read Only':
|
||||
if key_opt.strip() == '':
|
||||
raise Exception("[LoadTextEncoderShared] key_opt cannot be omit if mode is 'Read Only'")
|
||||
key = key_opt.strip()
|
||||
elif key_opt.strip() == '':
|
||||
key = model_name1
|
||||
if model_name2 is not None:
|
||||
key += f"_{model_name2}"
|
||||
if model_name3 is not None:
|
||||
key += f"_{model_name3}"
|
||||
key += f"_{type}_{device}"
|
||||
else:
|
||||
key = key_opt.strip()
|
||||
|
||||
if key not in cache or mode == 'Override Cache':
|
||||
if model_name2 != "None" and model_name3 != "None": # triple text encoder
|
||||
if len({model_name1, model_name2, model_name3}) < 3:
|
||||
logging.error("[LoadTextEncoderShared] The same model has been selected multiple times.")
|
||||
raise ValueError("The same model has been selected multiple times.")
|
||||
|
||||
if type not in ["sd3"]:
|
||||
logging.error("[LoadTextEncoderShared] Currently, the triple text encoder is only supported in `sd3`.")
|
||||
raise ValueError("Currently, the triple text encoder is only supported in `sd3`.")
|
||||
|
||||
tcloader = nodes.NODE_CLASS_MAPPINGS["TripleCLIPLoader"]()
|
||||
if hasattr(tcloader, 'execute'):
|
||||
# node v3
|
||||
res = tcloader.execute(model_name1, model_name2, model_name3)[0]
|
||||
else:
|
||||
# legacy compatibility
|
||||
res = tcloader.load_clip(model_name1, model_name2, model_name3)[0]
|
||||
|
||||
elif model_name2 != "None" or model_name3 != "None": # dual text encoder
|
||||
second_model = model_name2 if model_name2 != "None" else model_name3
|
||||
|
||||
if model_name1 == second_model:
|
||||
logging.error("[LoadTextEncoderShared] You have selected the same model for both.")
|
||||
raise ValueError("[LoadTextEncoderShared] You have selected the same model for both.")
|
||||
|
||||
if type not in ["sdxl", "sd3", "flux", "hunyuan_video"]:
|
||||
logging.error("[LoadTextEncoderShared] Currently, the triple text encoder is only supported in `sdxl, sd3, flux, hunyuan_video`.")
|
||||
raise ValueError("Currently, the triple text encoder is only supported in `sdxl, sd3, flux, hunyuan_video`.")
|
||||
|
||||
res = nodes.NODE_CLASS_MAPPINGS["DualCLIPLoader"]().load_clip(model_name1, second_model, type=type, device=device)[0]
|
||||
|
||||
else: # single text encoder
|
||||
if type not in ["stable_diffusion", "stable_cascade", "sd3", "stable_audio", "mochi", "ltxv", "pixart", "cosmos"]:
|
||||
logging.error("[LoadTextEncoderShared] Currently, the single text encoder is only supported in `stable_diffusion, stable_cascade, sd3, stable_audio, mochi, ltxv, pixart, cosmos`.")
|
||||
raise ValueError("Currently, the single text encoder is only supported in `stable_diffusion, stable_cascade, sd3, stable_audio, mochi, ltxv, pixart, cosmos`.")
|
||||
|
||||
res = nodes.NODE_CLASS_MAPPINGS["CLIPLoader"]().load_clip(model_name1, type=type, device=device)[0]
|
||||
|
||||
update_cache(key, "diffusion", (False, res))
|
||||
logging.info(f"[Inspire Pack] LoadTextEncoderShared: text encoder model set is cached to '{key}'.")
|
||||
else:
|
||||
_, (_, res) = cache[key]
|
||||
logging.info(f"[Inspire Pack] LoadTextEncoderShared: Cached text encoder model set '{key}' is loaded. (Loading skip)")
|
||||
|
||||
return res, key
|
||||
|
||||
@staticmethod
|
||||
def IS_CHANGED(model_name1, model_name2, model_name3, type, key_opt, mode='Auto', device="default"):
|
||||
if mode == 'Read Only':
|
||||
if key_opt.strip() == '':
|
||||
raise Exception("[LoadTextEncoderShared] key_opt cannot be omit if mode is 'Read Only'")
|
||||
key = key_opt.strip()
|
||||
elif key_opt.strip() == '':
|
||||
key = model_name1
|
||||
if model_name2 is not None:
|
||||
key += f"_{model_name2}"
|
||||
if model_name3 is not None:
|
||||
key += f"_{model_name3}"
|
||||
key += f"_{type}_{device}"
|
||||
else:
|
||||
key = key_opt.strip()
|
||||
|
||||
if mode == 'Read Only':
|
||||
return None, cache_weak_hash(key)
|
||||
elif mode == 'Override Cache':
|
||||
return f"{model_name1}_{model_name2}_{model_name3}_{type}_{device}", key
|
||||
|
||||
return None, cache_weak_hash(key)
|
||||
|
||||
|
||||
class StableCascade_CheckpointLoader:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
ckpts = folder_paths.get_filename_list("checkpoints")
|
||||
default_stage_b = ''
|
||||
default_stage_c = ''
|
||||
|
||||
sc_ckpts = [x for x in ckpts if 'cascade' in x.lower()]
|
||||
sc_b_ckpts = [x for x in sc_ckpts if 'stage_b' in x.lower()]
|
||||
sc_c_ckpts = [x for x in sc_ckpts if 'stage_c' in x.lower()]
|
||||
|
||||
if len(sc_b_ckpts) == 0:
|
||||
sc_b_ckpts = [x for x in ckpts if 'stage_b' in x.lower()]
|
||||
if len(sc_c_ckpts) == 0:
|
||||
sc_c_ckpts = [x for x in ckpts if 'stage_c' in x.lower()]
|
||||
|
||||
if len(sc_b_ckpts) == 0:
|
||||
sc_b_ckpts = ckpts
|
||||
if len(sc_c_ckpts) == 0:
|
||||
sc_c_ckpts = ckpts
|
||||
|
||||
if len(sc_b_ckpts) > 0:
|
||||
default_stage_b = sc_b_ckpts[0]
|
||||
if len(sc_c_ckpts) > 0:
|
||||
default_stage_c = sc_c_ckpts[0]
|
||||
|
||||
return {"required": {
|
||||
"stage_b": (ckpts, {'default': default_stage_b}),
|
||||
"key_opt_b": ("STRING", {"multiline": False, "placeholder": "If empty, use 'stage_b' as the key."}),
|
||||
"stage_c": (ckpts, {'default': default_stage_c}),
|
||||
"key_opt_c": ("STRING", {"multiline": False, "placeholder": "If empty, use 'stage_c' as the key."}),
|
||||
"cache_mode": (["none", "stage_b", "stage_c", "all"], {"default": "none"}),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("MODEL", "VAE", "MODEL", "VAE", "CLIP_VISION", "CLIP", "STRING", "STRING")
|
||||
RETURN_NAMES = ("b_model", "b_vae", "c_model", "c_vae", "c_clip_vision", "clip", "key_b", "key_c")
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Backend"
|
||||
|
||||
def doit(self, stage_b, key_opt_b, stage_c, key_opt_c, cache_mode):
|
||||
if key_opt_b.strip() == '':
|
||||
key_b = stage_b
|
||||
else:
|
||||
key_b = key_opt_b.strip()
|
||||
|
||||
if key_opt_c.strip() == '':
|
||||
key_c = stage_c
|
||||
else:
|
||||
key_c = key_opt_c.strip()
|
||||
|
||||
if cache_mode in ['stage_b', "all"]:
|
||||
if key_b not in cache:
|
||||
res_b = nodes.CheckpointLoaderSimple().load_checkpoint(ckpt_name=stage_b)
|
||||
update_cache(key_b, "ckpt", (False, res_b))
|
||||
logging.info(f"[Inspire Pack] StableCascade_CheckpointLoader: Ckpt '{stage_b}' is cached to '{key_b}'.")
|
||||
else:
|
||||
_, (_, res_b) = cache[key_b]
|
||||
logging.info(f"[Inspire Pack] StableCascade_CheckpointLoader: Cached ckpt '{key_b}' is loaded. (Loading skip)")
|
||||
b_model, clip, b_vae = res_b
|
||||
else:
|
||||
b_model, clip, b_vae = nodes.CheckpointLoaderSimple().load_checkpoint(ckpt_name=stage_b)
|
||||
|
||||
if cache_mode in ['stage_c', "all"]:
|
||||
if key_c not in cache:
|
||||
res_c = nodes.unCLIPCheckpointLoader().load_checkpoint(ckpt_name=stage_c)
|
||||
update_cache(key_c, "unclip_ckpt", (False, res_c))
|
||||
logging.info(f"[Inspire Pack] StableCascade_CheckpointLoader: Ckpt '{stage_c}' is cached to '{key_c}'.")
|
||||
else:
|
||||
_, (_, res_c) = cache[key_c]
|
||||
logging.info(f"[Inspire Pack] StableCascade_CheckpointLoader: Cached ckpt '{key_c}' is loaded. (Loading skip)")
|
||||
c_model, _, c_vae, clip_vision = res_c
|
||||
else:
|
||||
c_model, _, c_vae, clip_vision = nodes.unCLIPCheckpointLoader().load_checkpoint(ckpt_name=stage_c)
|
||||
|
||||
return b_model, b_vae, c_model, c_vae, clip_vision, clip, key_b, key_c
|
||||
|
||||
|
||||
class IsCached:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"key": ("STRING", {"multiline": False}),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID"
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("BOOLEAN", )
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Backend"
|
||||
|
||||
@staticmethod
|
||||
def IS_CHANGED(key, unique_id):
|
||||
return common.is_changed(unique_id, key in cache)
|
||||
|
||||
def doit(self, key, unique_id):
|
||||
return (key in cache,)
|
||||
|
||||
|
||||
# WIP: not properly working, yet
|
||||
class CacheBridge:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"value": (any_typ,),
|
||||
"mode": ("BOOLEAN", {"default": True, "label_off": "cached", "label_on": "passthrough"}),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID"
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = (any_typ, )
|
||||
RETURN_NAMES = ("value",)
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Backend"
|
||||
|
||||
@staticmethod
|
||||
def IS_CHANGED(value, mode, unique_id):
|
||||
if not mode and unique_id in common.changed_cache:
|
||||
return common.not_changed_value(unique_id)
|
||||
else:
|
||||
return common.changed_value(unique_id)
|
||||
|
||||
def doit(self, value, mode, unique_id):
|
||||
if not mode:
|
||||
# cache mode
|
||||
if unique_id not in common.changed_cache:
|
||||
common.changed_cache[unique_id] = value
|
||||
common.changed_count_cache[unique_id] = 0
|
||||
|
||||
return (common.changed_cache[unique_id],)
|
||||
else:
|
||||
common.changed_cache[unique_id] = value
|
||||
common.changed_count_cache[unique_id] = 0
|
||||
|
||||
return (common.changed_cache[unique_id],)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"CacheBackendData //Inspire": CacheBackendData,
|
||||
"CacheBackendDataNumberKey //Inspire": CacheBackendDataNumberKey,
|
||||
"CacheBackendDataList //Inspire": CacheBackendDataList,
|
||||
"CacheBackendDataNumberKeyList //Inspire": CacheBackendDataNumberKeyList,
|
||||
"RetrieveBackendData //Inspire": RetrieveBackendData,
|
||||
"RetrieveBackendDataNumberKey //Inspire": RetrieveBackendDataNumberKey,
|
||||
"RemoveBackendData //Inspire": RemoveBackendData,
|
||||
"RemoveBackendDataNumberKey //Inspire": RemoveBackendDataNumberKey,
|
||||
"ShowCachedInfo //Inspire": ShowCachedInfo,
|
||||
"CheckpointLoaderSimpleShared //Inspire": CheckpointLoaderSimpleShared,
|
||||
"LoadDiffusionModelShared //Inspire": LoadDiffusionModelShared,
|
||||
"LoadTextEncoderShared //Inspire": LoadTextEncoderShared,
|
||||
"StableCascade_CheckpointLoader //Inspire": StableCascade_CheckpointLoader,
|
||||
"IsCached //Inspire": IsCached,
|
||||
# "CacheBridge //Inspire": CacheBridge,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"CacheBackendData //Inspire": "Cache Backend Data (Inspire)",
|
||||
"CacheBackendDataNumberKey //Inspire": "Cache Backend Data [NumberKey] (Inspire)",
|
||||
"CacheBackendDataList //Inspire": "Cache Backend Data List (Inspire)",
|
||||
"CacheBackendDataNumberKeyList //Inspire": "Cache Backend Data List [NumberKey] (Inspire)",
|
||||
"RetrieveBackendData //Inspire": "Retrieve Backend Data (Inspire)",
|
||||
"RetrieveBackendDataNumberKey //Inspire": "Retrieve Backend Data [NumberKey] (Inspire)",
|
||||
"RemoveBackendData //Inspire": "Remove Backend Data (Inspire)",
|
||||
"RemoveBackendDataNumberKey //Inspire": "Remove Backend Data [NumberKey] (Inspire)",
|
||||
"ShowCachedInfo //Inspire": "Show Cached Info (Inspire)",
|
||||
"CheckpointLoaderSimpleShared //Inspire": "Shared Checkpoint Loader (Inspire)",
|
||||
"LoadDiffusionModelShared //Inspire": "Shared Diffusion Model Loader (Inspire)",
|
||||
"LoadTextEncoderShared //Inspire": "Shared Text Encoder Loader (Inspire)",
|
||||
"StableCascade_CheckpointLoader //Inspire": "Stable Cascade Checkpoint Loader (Inspire)",
|
||||
"IsCached //Inspire": "Is Cached (Inspire)",
|
||||
# "CacheBridge //Inspire": "Cache Bridge (Inspire)"
|
||||
}
|
||||
165
custom_nodes/comfyui-inspire-pack/inspire/conditioning_nodes.py
Normal file
165
custom_nodes/comfyui-inspire-pack/inspire/conditioning_nodes.py
Normal file
@@ -0,0 +1,165 @@
|
||||
import torch
|
||||
import nodes
|
||||
import inspect
|
||||
from .libs import utils
|
||||
from nodes import MAX_RESOLUTION
|
||||
import logging
|
||||
|
||||
|
||||
class ConcatConditioningsWithMultiplier:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
stack = inspect.stack()
|
||||
if stack[1].function == 'get_input_info':
|
||||
# bypass validation
|
||||
class AllContainer:
|
||||
def __contains__(self, item):
|
||||
return True
|
||||
|
||||
def __getitem__(self, key):
|
||||
return "FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}
|
||||
|
||||
return {
|
||||
"required": {"conditioning1": ("CONDITIONING",), },
|
||||
"optional": AllContainer()
|
||||
}
|
||||
|
||||
return {
|
||||
"required": {"conditioning1": ("CONDITIONING",), },
|
||||
"optional": {"multiplier1": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}), },
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("CONDITIONING",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/__for_testing"
|
||||
|
||||
def doit(self, **kwargs):
|
||||
if "ConditioningMultiplier_PoP" in nodes.NODE_CLASS_MAPPINGS:
|
||||
obj = nodes.NODE_CLASS_MAPPINGS["ConditioningMultiplier_PoP"]()
|
||||
else:
|
||||
utils.try_install_custom_node('https://github.com/picturesonpictures/comfy_PoP',
|
||||
"To use 'ConcatConditioningsWithMultiplier' node, 'comfy_PoP' extension is required.")
|
||||
raise Exception("'comfy_PoP' node isn't installed.")
|
||||
|
||||
conditioning_to = kwargs['conditioning1']
|
||||
conditioning_to = obj.multiply_conditioning_strength(conditioning=conditioning_to, multiplier=float(kwargs['multiplier1']))[0]
|
||||
|
||||
out = None
|
||||
for k, conditioning_from in kwargs.items():
|
||||
if k == 'conditioning1' or not k.startswith('conditioning'):
|
||||
continue
|
||||
|
||||
out = []
|
||||
if len(conditioning_from) > 1:
|
||||
logging.warning(f"[Inspire Pack] ConcatConditioningsWithMultiplier {k} contains more than 1 cond, only the first one will actually be applied to conditioning1.")
|
||||
|
||||
mkey = 'multiplier' + k[12:]
|
||||
multiplier = float(kwargs[mkey])
|
||||
conditioning_from = obj.multiply_conditioning_strength(conditioning=conditioning_from, multiplier=multiplier)[0]
|
||||
cond_from = conditioning_from[0][0]
|
||||
|
||||
for i in range(len(conditioning_to)):
|
||||
t1 = conditioning_to[i][0]
|
||||
tw = torch.cat((t1, cond_from), 1)
|
||||
n = [tw, conditioning_to[i][1].copy()]
|
||||
out.append(n)
|
||||
|
||||
conditioning_to = out
|
||||
|
||||
if out is None:
|
||||
return (kwargs['conditioning1'],)
|
||||
else:
|
||||
return (out,)
|
||||
|
||||
|
||||
# CREDIT for ConditioningStretch, ConditioningUpscale: Davemane42
|
||||
# Imported to support archived custom nodes.
|
||||
# original code: https://github.com/Davemane42/ComfyUI_Dave_CustomNode/blob/main/MultiAreaConditioning.py
|
||||
class ConditioningStretch:
|
||||
def __init__(self) -> None:
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"conditioning": ("CONDITIONING",),
|
||||
"resolutionX": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 64}),
|
||||
"resolutionY": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 64}),
|
||||
"newWidth": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 64}),
|
||||
"newHeight": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 64}),
|
||||
# "scalar": ("INT", {"default": 2, "min": 1, "max": 100, "step": 0.5}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("CONDITIONING",)
|
||||
CATEGORY = "InspirePack/conditioning"
|
||||
|
||||
FUNCTION = 'upscale'
|
||||
|
||||
@staticmethod
|
||||
def upscale(conditioning, resolutionX, resolutionY, newWidth, newHeight, scalar=1):
|
||||
c = []
|
||||
for t in conditioning:
|
||||
|
||||
n = [t[0], t[1].copy()]
|
||||
if 'area' in n[1]:
|
||||
newWidth *= scalar
|
||||
newHeight *= scalar
|
||||
|
||||
x = ((n[1]['area'][3] * 8) * newWidth / resolutionX) // 8
|
||||
y = ((n[1]['area'][2] * 8) * newHeight / resolutionY) // 8
|
||||
w = ((n[1]['area'][1] * 8) * newWidth / resolutionX) // 8
|
||||
h = ((n[1]['area'][0] * 8) * newHeight / resolutionY) // 8
|
||||
|
||||
n[1]['area'] = tuple(map(lambda x: (((int(x) + 7) >> 3) << 3), [h, w, y, x]))
|
||||
|
||||
c.append(n)
|
||||
|
||||
return (c,)
|
||||
|
||||
|
||||
class ConditioningUpscale:
|
||||
def __init__(self) -> None:
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"conditioning": ("CONDITIONING",),
|
||||
"scalar": ("INT", {"default": 2, "min": 1, "max": 100, "step": 0.5}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("CONDITIONING",)
|
||||
CATEGORY = "InspirePack/conditioning"
|
||||
|
||||
FUNCTION = 'upscale'
|
||||
|
||||
@staticmethod
|
||||
def upscale(conditioning, scalar):
|
||||
c = []
|
||||
for t in conditioning:
|
||||
|
||||
n = [t[0], t[1].copy()]
|
||||
if 'area' in n[1]:
|
||||
n[1]['area'] = tuple(map(lambda x: ((x * scalar + 7) >> 3) << 3, n[1]['area']))
|
||||
|
||||
c.append(n)
|
||||
|
||||
return (c,)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"ConcatConditioningsWithMultiplier //Inspire": ConcatConditioningsWithMultiplier,
|
||||
"ConditioningUpscale //Inspire": ConditioningUpscale,
|
||||
"ConditioningStretch //Inspire": ConditioningStretch,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"ConcatConditioningsWithMultiplier //Inspire": "Concat Conditionings with Multiplier (Inspire)",
|
||||
"ConditioningUpscale //Inspire": "Conditioning Upscale (Inspire)",
|
||||
"ConditioningStretch //Inspire": "Conditioning Stretch (Inspire)",
|
||||
}
|
||||
511
custom_nodes/comfyui-inspire-pack/inspire/image_util.py
Normal file
511
custom_nodes/comfyui-inspire-pack/inspire/image_util.py
Normal file
@@ -0,0 +1,511 @@
|
||||
import os
|
||||
|
||||
import torch
|
||||
from PIL import ImageOps
|
||||
try:
|
||||
import pillow_jxl # noqa: F401
|
||||
jxl = True
|
||||
except ImportError:
|
||||
jxl = False
|
||||
import comfy
|
||||
import folder_paths
|
||||
import base64
|
||||
from io import BytesIO
|
||||
from .libs.utils import ByPassTypeTuple, empty_pil_tensor, empty_latent
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
import logging
|
||||
import re
|
||||
|
||||
|
||||
def extract_first_number(s):
|
||||
match = re.search(r'\d+', s)
|
||||
return int(match.group()) if match else float('inf')
|
||||
|
||||
|
||||
sort_methods = [
|
||||
"None",
|
||||
"Alphabetical (ASC)",
|
||||
"Alphabetical (DESC)",
|
||||
"Numerical (ASC)",
|
||||
"Numerical (DESC)",
|
||||
"Datetime (ASC)",
|
||||
"Datetime (DESC)"
|
||||
]
|
||||
|
||||
|
||||
def sort_by(items, base_path='.', method=None):
|
||||
def fullpath(x): return os.path.join(base_path, x)
|
||||
|
||||
def get_timestamp(path):
|
||||
try:
|
||||
return os.path.getmtime(path)
|
||||
except FileNotFoundError:
|
||||
return float('-inf')
|
||||
|
||||
if method == "Alphabetical (ASC)":
|
||||
return sorted(items)
|
||||
elif method == "Alphabetical (DESC)":
|
||||
return sorted(items, reverse=True)
|
||||
elif method == "Numerical (ASC)":
|
||||
return sorted(items, key=lambda x: extract_first_number(os.path.splitext(x)[0]))
|
||||
elif method == "Numerical (DESC)":
|
||||
return sorted(items, key=lambda x: extract_first_number(os.path.splitext(x)[0]), reverse=True)
|
||||
elif method == "Datetime (ASC)":
|
||||
return sorted(items, key=lambda x: get_timestamp(fullpath(x)))
|
||||
elif method == "Datetime (DESC)":
|
||||
return sorted(items, key=lambda x: get_timestamp(fullpath(x)), reverse=True)
|
||||
else:
|
||||
return items
|
||||
|
||||
|
||||
class LoadImagesFromDirBatch:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"directory": ("STRING", {"default": ""}),
|
||||
},
|
||||
"optional": {
|
||||
"image_load_cap": ("INT", {"default": 0, "min": 0, "step": 1}),
|
||||
"start_index": ("INT", {"default": 0, "min": -1, "max": 0xffffffffffffffff, "step": 1}),
|
||||
"load_always": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}),
|
||||
"sort_method": (sort_methods,),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "MASK", "INT")
|
||||
FUNCTION = "load_images"
|
||||
|
||||
CATEGORY = "image"
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, **kwargs):
|
||||
if 'load_always' in kwargs and kwargs['load_always']:
|
||||
return float("NaN")
|
||||
else:
|
||||
return hash(frozenset(kwargs))
|
||||
|
||||
def load_images(self, directory: str, image_load_cap: int = 0, start_index: int = 0, load_always=False, sort_method=None):
|
||||
if not os.path.isdir(directory):
|
||||
raise FileNotFoundError(f"Directory '{directory} cannot be found.'")
|
||||
dir_files = os.listdir(directory)
|
||||
if len(dir_files) == 0:
|
||||
raise FileNotFoundError(f"No files in directory '{directory}'.")
|
||||
|
||||
# Filter files by extension
|
||||
valid_extensions = ['.jpg', '.jpeg', '.png', '.webp']
|
||||
if jxl:
|
||||
valid_extensions.extend('.jxl')
|
||||
dir_files = [f for f in dir_files if any(f.lower().endswith(ext) for ext in valid_extensions)]
|
||||
|
||||
dir_files = sort_by(dir_files, directory, sort_method)
|
||||
dir_files = [os.path.join(directory, x) for x in dir_files]
|
||||
|
||||
# start at start_index
|
||||
dir_files = dir_files[start_index:]
|
||||
|
||||
images = []
|
||||
masks = []
|
||||
|
||||
limit_images = False
|
||||
if image_load_cap > 0:
|
||||
limit_images = True
|
||||
image_count = 0
|
||||
|
||||
has_non_empty_mask = False
|
||||
|
||||
for image_path in dir_files:
|
||||
if os.path.isdir(image_path) and os.path.ex:
|
||||
continue
|
||||
if limit_images and image_count >= image_load_cap:
|
||||
break
|
||||
i = Image.open(image_path)
|
||||
i = ImageOps.exif_transpose(i)
|
||||
image = i.convert("RGB")
|
||||
image = np.array(image).astype(np.float32) / 255.0
|
||||
image = torch.from_numpy(image)[None,]
|
||||
if 'A' in i.getbands():
|
||||
mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
|
||||
mask = 1. - torch.from_numpy(mask)
|
||||
has_non_empty_mask = True
|
||||
else:
|
||||
mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu")
|
||||
images.append(image)
|
||||
masks.append(mask)
|
||||
image_count += 1
|
||||
|
||||
if len(images) == 1:
|
||||
return (images[0], masks[0], 1)
|
||||
|
||||
elif len(images) > 1:
|
||||
image1 = images[0]
|
||||
mask1 = None
|
||||
|
||||
for image2 in images[1:]:
|
||||
if image1.shape[1:] != image2.shape[1:]:
|
||||
image2 = comfy.utils.common_upscale(image2.movedim(-1, 1), image1.shape[2], image1.shape[1], "bilinear", "center").movedim(1, -1)
|
||||
image1 = torch.cat((image1, image2), dim=0)
|
||||
|
||||
for mask2 in masks:
|
||||
if has_non_empty_mask:
|
||||
if image1.shape[1:3] != mask2.shape:
|
||||
mask2 = torch.nn.functional.interpolate(mask2.unsqueeze(0).unsqueeze(0), size=(image1.shape[1], image1.shape[2]), mode='bilinear', align_corners=False)
|
||||
mask2 = mask2.squeeze(0)
|
||||
else:
|
||||
mask2 = mask2.unsqueeze(0)
|
||||
else:
|
||||
mask2 = mask2.unsqueeze(0)
|
||||
|
||||
if mask1 is None:
|
||||
mask1 = mask2
|
||||
else:
|
||||
mask1 = torch.cat((mask1, mask2), dim=0)
|
||||
|
||||
return (image1, mask1, len(images))
|
||||
|
||||
|
||||
class LoadImagesFromDirList:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"directory": ("STRING", {"default": ""}),
|
||||
},
|
||||
"optional": {
|
||||
"image_load_cap": ("INT", {"default": 0, "min": 0, "step": 1}),
|
||||
"start_index": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "step": 1}),
|
||||
"load_always": ("BOOLEAN", {"default": False, "label_on": "enabled", "label_off": "disabled"}),
|
||||
"sort_method": (sort_methods,),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "MASK", "STRING")
|
||||
RETURN_NAMES = ("IMAGE", "MASK", "FILE PATH")
|
||||
OUTPUT_IS_LIST = (True, True, True)
|
||||
|
||||
FUNCTION = "load_images"
|
||||
|
||||
CATEGORY = "image"
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, **kwargs):
|
||||
if 'load_always' in kwargs and kwargs['load_always']:
|
||||
return float("NaN")
|
||||
else:
|
||||
return hash(frozenset(kwargs))
|
||||
|
||||
def load_images(self, directory: str, image_load_cap: int = 0, start_index: int = 0, load_always=False, sort_method=None):
|
||||
if not os.path.isdir(directory):
|
||||
raise FileNotFoundError(f"Directory '{directory}' cannot be found.")
|
||||
dir_files = os.listdir(directory)
|
||||
if len(dir_files) == 0:
|
||||
raise FileNotFoundError(f"No files in directory '{directory}'.")
|
||||
|
||||
# Filter files by extension
|
||||
valid_extensions = ['.jpg', '.jpeg', '.png', '.webp']
|
||||
if jxl:
|
||||
valid_extensions.extend('.jxl')
|
||||
dir_files = [f for f in dir_files if any(f.lower().endswith(ext) for ext in valid_extensions)]
|
||||
|
||||
dir_files = sort_by(dir_files, directory, sort_method)
|
||||
dir_files = [os.path.join(directory, x) for x in dir_files]
|
||||
|
||||
# start at start_index
|
||||
dir_files = dir_files[start_index:]
|
||||
|
||||
images = []
|
||||
masks = []
|
||||
file_paths = []
|
||||
|
||||
limit_images = False
|
||||
if image_load_cap > 0:
|
||||
limit_images = True
|
||||
image_count = 0
|
||||
|
||||
for image_path in dir_files:
|
||||
if os.path.isdir(image_path) and os.path.ex:
|
||||
continue
|
||||
if limit_images and image_count >= image_load_cap:
|
||||
break
|
||||
i = Image.open(image_path)
|
||||
i = ImageOps.exif_transpose(i)
|
||||
image = i.convert("RGB")
|
||||
image = np.array(image).astype(np.float32) / 255.0
|
||||
image = torch.from_numpy(image)[None,]
|
||||
|
||||
if 'A' in i.getbands():
|
||||
mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
|
||||
mask = 1. - torch.from_numpy(mask)
|
||||
else:
|
||||
mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu")
|
||||
|
||||
images.append(image)
|
||||
masks.append(mask)
|
||||
file_paths.append(str(image_path))
|
||||
image_count += 1
|
||||
|
||||
return (images, masks, file_paths)
|
||||
|
||||
|
||||
class LoadImageInspire:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
input_dir = folder_paths.get_input_directory()
|
||||
files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
|
||||
return {"required": {
|
||||
"image": (sorted(files) + ["#DATA"], {"image_upload": True}),
|
||||
"image_data": ("STRING", {"multiline": False}),
|
||||
}
|
||||
}
|
||||
|
||||
CATEGORY = "InspirePack/image"
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "MASK")
|
||||
FUNCTION = "load_image"
|
||||
|
||||
def load_image(self, image, image_data):
|
||||
image_data = base64.b64decode(image_data.split(",")[1])
|
||||
i = Image.open(BytesIO(image_data))
|
||||
i = ImageOps.exif_transpose(i)
|
||||
image = i.convert("RGB")
|
||||
image = np.array(image).astype(np.float32) / 255.0
|
||||
image = torch.from_numpy(image)[None,]
|
||||
if 'A' in i.getbands():
|
||||
mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
|
||||
mask = 1. - torch.from_numpy(mask)
|
||||
else:
|
||||
mask = torch.zeros((64, 64), dtype=torch.float32, device="cpu")
|
||||
return (image, mask.unsqueeze(0))
|
||||
|
||||
|
||||
class ChangeImageBatchSize:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"image": ("IMAGE",),
|
||||
"batch_size": ("INT", {"default": 1, "min": 1, "max": 4096, "step": 1}),
|
||||
"mode": (["simple"],)
|
||||
}
|
||||
}
|
||||
|
||||
CATEGORY = "InspirePack/Util"
|
||||
|
||||
RETURN_TYPES = ("IMAGE", )
|
||||
FUNCTION = "doit"
|
||||
|
||||
@staticmethod
|
||||
def resize_tensor(input_tensor, batch_size, mode):
|
||||
if mode == "simple":
|
||||
if len(input_tensor) < batch_size:
|
||||
last_frame = input_tensor[-1].unsqueeze(0).expand(batch_size - len(input_tensor), -1, -1, -1)
|
||||
output_tensor = torch.concat((input_tensor, last_frame), dim=0)
|
||||
else:
|
||||
output_tensor = input_tensor[:batch_size, :, :, :]
|
||||
return output_tensor
|
||||
else:
|
||||
logging.warning(f"[Inspire Pack] ChangeImage(Latent)BatchSize: Unknown mode `{mode}` - ignored")
|
||||
return input_tensor
|
||||
|
||||
@staticmethod
|
||||
def doit(image, batch_size, mode):
|
||||
res = ChangeImageBatchSize.resize_tensor(image, batch_size, mode)
|
||||
return (res,)
|
||||
|
||||
|
||||
class ChangeLatentBatchSize:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"latent": ("LATENT",),
|
||||
"batch_size": ("INT", {"default": 1, "min": 1, "max": 4096, "step": 1}),
|
||||
"mode": (["simple"],)
|
||||
}
|
||||
}
|
||||
|
||||
CATEGORY = "InspirePack/Util"
|
||||
|
||||
RETURN_TYPES = ("LATENT", )
|
||||
FUNCTION = "doit"
|
||||
|
||||
@staticmethod
|
||||
def doit(latent, batch_size, mode):
|
||||
res_latent = latent.copy()
|
||||
samples = res_latent['samples']
|
||||
samples = ChangeImageBatchSize.resize_tensor(samples, batch_size, mode)
|
||||
res_latent['samples'] = samples
|
||||
return (res_latent,)
|
||||
|
||||
|
||||
class ImageBatchSplitter:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"images": ("IMAGE",),
|
||||
"split_count": ("INT", {"default": 4, "min": 0, "max": 50, "step": 1}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ByPassTypeTuple(("IMAGE", ))
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Util"
|
||||
|
||||
def doit(self, images, split_count):
|
||||
cnt = min(split_count, len(images))
|
||||
res = [image.unsqueeze(0) for image in images[:cnt]]
|
||||
|
||||
if split_count >= len(images):
|
||||
lack_cnt = split_count - cnt + 1 # including remained
|
||||
empty_image = empty_pil_tensor()
|
||||
for x in range(0, lack_cnt):
|
||||
res.append(empty_image)
|
||||
elif cnt < len(images):
|
||||
remained_cnt = len(images) - cnt
|
||||
remained_image = images[-remained_cnt:]
|
||||
res.append(remained_image)
|
||||
|
||||
return tuple(res)
|
||||
|
||||
|
||||
class LatentBatchSplitter:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"latent": ("LATENT",),
|
||||
"split_count": ("INT", {"default": 4, "min": 0, "max": 50, "step": 1}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ByPassTypeTuple(("LATENT", ))
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Util"
|
||||
|
||||
def doit(self, latent, split_count):
|
||||
samples = latent['samples']
|
||||
|
||||
latent_base = latent.copy()
|
||||
del latent_base['samples']
|
||||
|
||||
cnt = min(split_count, len(samples))
|
||||
res = []
|
||||
|
||||
for single_samples in samples[:cnt]:
|
||||
item = latent_base.copy()
|
||||
item['samples'] = single_samples.unsqueeze(0)
|
||||
res.append(item)
|
||||
|
||||
if split_count >= len(samples):
|
||||
lack_cnt = split_count - cnt + 1 # including remained
|
||||
item = latent_base.copy()
|
||||
item['samples'] = empty_latent()
|
||||
|
||||
for x in range(0, lack_cnt):
|
||||
res.append(item)
|
||||
|
||||
elif cnt < len(samples):
|
||||
remained_cnt = len(samples) - cnt
|
||||
remained_latent = latent_base.copy()
|
||||
remained_latent['samples'] = samples[-remained_cnt:]
|
||||
res.append(remained_latent)
|
||||
|
||||
return tuple(res)
|
||||
|
||||
|
||||
def top_k_colors(image_tensor, k, min_pixels):
|
||||
flattened_image = image_tensor.view(-1, image_tensor.size(-1))
|
||||
|
||||
unique_colors, counts = torch.unique(flattened_image, dim=0, return_counts=True)
|
||||
|
||||
sorted_counts, sorted_indices = torch.sort(counts, descending=True)
|
||||
sorted_colors = unique_colors[sorted_indices]
|
||||
|
||||
filtered_colors = sorted_colors[sorted_counts >= min_pixels]
|
||||
|
||||
return filtered_colors[:k]
|
||||
|
||||
|
||||
def create_mask(image_tensor, color):
|
||||
mask_tensor = torch.zeros_like(image_tensor[:, :, :, 0])
|
||||
mask_tensor = torch.where(torch.all(image_tensor == color, dim=-1, keepdim=False), 1, mask_tensor)
|
||||
return mask_tensor
|
||||
|
||||
|
||||
class ColorMapToMasks:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"color_map": ("IMAGE",),
|
||||
"min_pixels": ("INT", {"default": 500, "min": 1, "max": 0xffffffffffffffff, "step": 1}),
|
||||
"max_count": ("INT", {"default": 5, "min": 0, "max": 1000, "step": 1}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MASK",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Util"
|
||||
|
||||
def doit(self, color_map, max_count, min_pixels):
|
||||
if len(color_map) > 0:
|
||||
logging.warning("[Inspire Pack] ColorMapToMasks - Sure, here's the translation: `color_map` can only be a single image. Only the first image will be processed. If you want to utilize the remaining images, convert the Image Batch to an Image List.")
|
||||
|
||||
top_colors = top_k_colors(color_map[0], max_count, min_pixels)
|
||||
|
||||
masks = None
|
||||
|
||||
for color in top_colors:
|
||||
this_mask = create_mask(color_map, color)
|
||||
if masks is None:
|
||||
masks = this_mask
|
||||
else:
|
||||
masks = torch.concat((masks, this_mask), dim=0)
|
||||
|
||||
if masks is None:
|
||||
masks = torch.zeros_like(color_map[0, :, :, 0])
|
||||
masks.unsqueeze(0)
|
||||
|
||||
return (masks,)
|
||||
|
||||
|
||||
class SelectNthMask:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"masks": ("MASK",),
|
||||
"idx": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "step": 1}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MASK",)
|
||||
FUNCTION = "doit"
|
||||
CATEGORY = "InspirePack/Util"
|
||||
|
||||
def doit(self, masks, idx):
|
||||
return (masks[idx].unsqueeze(0),)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"LoadImagesFromDir //Inspire": LoadImagesFromDirBatch,
|
||||
"LoadImageListFromDir //Inspire": LoadImagesFromDirList,
|
||||
"LoadImage //Inspire": LoadImageInspire,
|
||||
"ChangeImageBatchSize //Inspire": ChangeImageBatchSize,
|
||||
"ChangeLatentBatchSize //Inspire": ChangeLatentBatchSize,
|
||||
"ImageBatchSplitter //Inspire": ImageBatchSplitter,
|
||||
"LatentBatchSplitter //Inspire": LatentBatchSplitter,
|
||||
"ColorMapToMasks //Inspire": ColorMapToMasks,
|
||||
"SelectNthMask //Inspire": SelectNthMask
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"LoadImagesFromDir //Inspire": "Load Image Batch From Dir (Inspire)",
|
||||
"LoadImageListFromDir //Inspire": "Load Image List From Dir (Inspire)",
|
||||
"LoadImage //Inspire": "Load Image (Inspire)",
|
||||
"ChangeImageBatchSize //Inspire": "Change Image Batch Size (Inspire)",
|
||||
"ChangeLatentBatchSize //Inspire": "Change Latent Batch Size (Inspire)",
|
||||
"ImageBatchSplitter //Inspire": "Image Batch Splitter (Inspire)",
|
||||
"LatentBatchSplitter //Inspire": "Latent Batch Splitter (Inspire)",
|
||||
"ColorMapToMasks //Inspire": "Color Map To Masks (Inspire)",
|
||||
"SelectNthMask //Inspire": "Select Nth Mask (Inspire)"
|
||||
}
|
||||
412
custom_nodes/comfyui-inspire-pack/inspire/inspire_server.py
Normal file
412
custom_nodes/comfyui-inspire-pack/inspire/inspire_server.py
Normal file
@@ -0,0 +1,412 @@
|
||||
import random
|
||||
|
||||
import nodes
|
||||
import server
|
||||
from enum import Enum
|
||||
from . import prompt_support
|
||||
from aiohttp import web
|
||||
from . import backend_support
|
||||
from .libs import common
|
||||
import logging
|
||||
|
||||
|
||||
max_seed = 2**32 - 1
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get("/inspire/prompt_builder")
|
||||
def prompt_builder(request):
|
||||
result = {"presets": []}
|
||||
|
||||
if "category" in request.rel_url.query:
|
||||
category = request.rel_url.query["category"]
|
||||
if category in prompt_support.prompt_builder_preset:
|
||||
result['presets'] = prompt_support.prompt_builder_preset[category]
|
||||
|
||||
return web.json_response(result)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get("/inspire/cache/remove")
|
||||
def cache_remove(request):
|
||||
if "key" in request.rel_url.query:
|
||||
key = request.rel_url.query["key"]
|
||||
del backend_support.cache[key]
|
||||
|
||||
return web.Response(status=200)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get("/inspire/cache/clear")
|
||||
def cache_clear(request):
|
||||
backend_support.cache.clear()
|
||||
return web.Response(status=200)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get("/inspire/cache/list")
|
||||
def cache_refresh(request):
|
||||
return web.Response(text=backend_support.ShowCachedInfo.get_data(), status=200)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/inspire/cache/settings")
|
||||
async def set_cache_settings(request):
|
||||
data = await request.text()
|
||||
try:
|
||||
backend_support.ShowCachedInfo.set_cache_settings(data)
|
||||
return web.Response(text='OK', status=200)
|
||||
except Exception as e:
|
||||
return web.Response(text=f"{e}", status=500)
|
||||
|
||||
|
||||
class SGmode(Enum):
|
||||
FIX = 1
|
||||
INCR = 2
|
||||
DECR = 3
|
||||
RAND = 4
|
||||
|
||||
|
||||
class SeedGenerator:
|
||||
def __init__(self, base_value, action):
|
||||
self.base_value = base_value
|
||||
|
||||
if action == "fixed" or action == "increment" or action == "decrement" or action == "randomize":
|
||||
self.action = SGmode.FIX
|
||||
elif action == 'increment for each node':
|
||||
self.action = SGmode.INCR
|
||||
elif action == 'decrement for each node':
|
||||
self.action = SGmode.DECR
|
||||
elif action == 'randomize for each node':
|
||||
self.action = SGmode.RAND
|
||||
|
||||
def next(self):
|
||||
seed = self.base_value
|
||||
|
||||
if self.action == SGmode.INCR:
|
||||
self.base_value += 1
|
||||
if self.base_value > max_seed:
|
||||
self.base_value = 0
|
||||
elif self.action == SGmode.DECR:
|
||||
self.base_value -= 1
|
||||
if self.base_value < 0:
|
||||
self.base_value = max_seed
|
||||
elif self.action == SGmode.RAND:
|
||||
self.base_value = random.randint(0, max_seed)
|
||||
|
||||
return seed
|
||||
|
||||
|
||||
def control_seed(v):
|
||||
action = v['inputs']['action']
|
||||
value = v['inputs']['value']
|
||||
|
||||
if action == 'increment' or action == 'increment for each node':
|
||||
value += 1
|
||||
if value > max_seed:
|
||||
value = 0
|
||||
elif action == 'decrement' or action == 'decrement for each node':
|
||||
value -= 1
|
||||
if value < 0:
|
||||
value = max_seed
|
||||
elif action == 'randomize' or action == 'randomize for each node':
|
||||
value = random.randint(0, max_seed)
|
||||
|
||||
v['inputs']['value'] = value
|
||||
|
||||
return value
|
||||
|
||||
|
||||
def prompt_seed_update(json_data):
|
||||
try:
|
||||
widget_idx_map = json_data['extra_data']['extra_pnginfo']['workflow']['widget_idx_map']
|
||||
except Exception:
|
||||
return False, None
|
||||
|
||||
value = None
|
||||
mode = None
|
||||
node = None
|
||||
action = None
|
||||
|
||||
for k, v in json_data['prompt'].items():
|
||||
if 'class_type' not in v:
|
||||
continue
|
||||
|
||||
cls = v['class_type']
|
||||
if cls == 'GlobalSeed //Inspire':
|
||||
mode = v['inputs']['mode']
|
||||
action = v['inputs']['action']
|
||||
value = v['inputs']['value']
|
||||
node = k, v
|
||||
|
||||
# control before generated
|
||||
if mode is not None and mode:
|
||||
value = control_seed(node[1])
|
||||
|
||||
if value is not None:
|
||||
seed_generator = SeedGenerator(value, action)
|
||||
|
||||
for k, v in json_data['prompt'].items():
|
||||
for k2, v2 in v['inputs'].items():
|
||||
if isinstance(v2, str) and '$GlobalSeed.value$' in v2:
|
||||
v['inputs'][k2] = v2.replace('$GlobalSeed.value$', str(value))
|
||||
|
||||
if k not in widget_idx_map or ('seed' not in widget_idx_map[k] and 'noise_seed' not in widget_idx_map[k]):
|
||||
continue
|
||||
|
||||
if 'seed' in v['inputs']:
|
||||
if isinstance(v['inputs']['seed'], int):
|
||||
v['inputs']['seed'] = seed_generator.next()
|
||||
|
||||
if 'noise_seed' in v['inputs']:
|
||||
if isinstance(v['inputs']['noise_seed'], int):
|
||||
v['inputs']['noise_seed'] = seed_generator.next()
|
||||
|
||||
for k2, v2 in v['inputs'].items():
|
||||
if isinstance(v2, str) and '$GlobalSeed.value$' in v2:
|
||||
v['inputs'][k2] = v2.replace('$GlobalSeed.value$', str(value))
|
||||
|
||||
# control after generated
|
||||
if mode is not None and not mode:
|
||||
control_seed(node[1])
|
||||
|
||||
return value is not None, mode
|
||||
|
||||
|
||||
def workflow_seed_update(json_data, mode):
|
||||
nodes = json_data['extra_data']['extra_pnginfo']['workflow']['nodes']
|
||||
widget_idx_map = json_data['extra_data']['extra_pnginfo']['workflow']['widget_idx_map']
|
||||
prompt = json_data['prompt']
|
||||
|
||||
updated_seed_map = {}
|
||||
value = None
|
||||
for node in nodes:
|
||||
node_id = str(node['id'])
|
||||
if node_id in prompt:
|
||||
if node['type'] == 'GlobalSeed //Inspire':
|
||||
if mode is True:
|
||||
node['widgets_values'][3] = node['widgets_values'][0]
|
||||
node['widgets_values'][0] = prompt[node_id]['inputs']['value']
|
||||
node['widgets_values'][2] = 'fixed'
|
||||
|
||||
value = prompt[node_id]['inputs']['value']
|
||||
|
||||
elif node_id in widget_idx_map:
|
||||
widget_idx = None
|
||||
seed = None
|
||||
if 'noise_seed' in prompt[node_id]['inputs']:
|
||||
seed = prompt[node_id]['inputs']['noise_seed']
|
||||
widget_idx = widget_idx_map[node_id].get('noise_seed')
|
||||
elif 'seed' in prompt[node_id]['inputs']:
|
||||
seed = prompt[node_id]['inputs']['seed']
|
||||
widget_idx = widget_idx_map[node_id].get('seed')
|
||||
|
||||
if widget_idx is not None:
|
||||
node['widgets_values'][widget_idx] = seed
|
||||
updated_seed_map[node_id] = seed
|
||||
|
||||
server.PromptServer.instance.send_sync("inspire-global-seed", {"value": value, "seed_map": updated_seed_map})
|
||||
|
||||
|
||||
def prompt_sampler_update(json_data):
|
||||
try:
|
||||
widget_idx_map = json_data['extra_data']['extra_pnginfo']['workflow']['widget_idx_map']
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
nodes = json_data['extra_data']['extra_pnginfo']['workflow']['nodes']
|
||||
prompt = json_data['prompt']
|
||||
|
||||
sampler_name = None
|
||||
scheduler = None
|
||||
|
||||
for v in prompt.values():
|
||||
cls = v.get('class_type')
|
||||
if cls == 'GlobalSampler //Inspire':
|
||||
sampler_name = v['inputs']['sampler_name']
|
||||
scheduler = v['inputs']['scheduler']
|
||||
|
||||
if sampler_name is None:
|
||||
return
|
||||
|
||||
for node in nodes:
|
||||
cls = node.get('type')
|
||||
if cls == 'GlobalSampler //Inspire' or cls is None:
|
||||
continue
|
||||
|
||||
node_id = str(node['id'])
|
||||
|
||||
if node_id in prompt and node_id in widget_idx_map:
|
||||
sampler_widget_idx = widget_idx_map[node_id].get('sampler_name')
|
||||
scheduler_widget_idx = widget_idx_map[node_id].get('scheduler')
|
||||
|
||||
prompt_inputs = prompt[node_id]['inputs']
|
||||
|
||||
if ('sampler_name' in prompt_inputs and 'scheduler' in prompt_inputs and
|
||||
isinstance(prompt_inputs['sampler_name'], str) and 'scheduler' in prompt_inputs):
|
||||
|
||||
if sampler_widget_idx is not None:
|
||||
prompt_inputs['sampler_name'] = sampler_name
|
||||
node['widgets_values'][sampler_widget_idx] = sampler_name
|
||||
server.PromptServer.instance.send_sync("inspire-node-feedback", {"node_id": node_id, "widget_name": 'sampler_name', "type": "text", "data": sampler_name})
|
||||
|
||||
if scheduler_widget_idx is not None:
|
||||
prompt_inputs['scheduler'] = scheduler
|
||||
node['widgets_values'][scheduler_widget_idx] = scheduler
|
||||
server.PromptServer.instance.send_sync("inspire-node-feedback", {"node_id": node_id, "widget_name": 'scheduler', "type": "text", "data": scheduler})
|
||||
|
||||
|
||||
def workflow_loadimage_update(json_data):
|
||||
prompt = json_data['prompt']
|
||||
|
||||
for v in prompt.values():
|
||||
if 'class_type' in v and v['class_type'] == 'LoadImage //Inspire':
|
||||
v['inputs']['image'] = "#DATA"
|
||||
|
||||
|
||||
def populate_wildcards(json_data):
|
||||
prompt = json_data['prompt']
|
||||
|
||||
if 'ImpactWildcardProcessor' in nodes.NODE_CLASS_MAPPINGS:
|
||||
if not hasattr(nodes.NODE_CLASS_MAPPINGS['ImpactWildcardProcessor'], 'process'):
|
||||
logging.warning("[Inspire Pack] Your Impact Pack is outdated. Please update to the latest version.")
|
||||
return
|
||||
|
||||
wildcard_process = nodes.NODE_CLASS_MAPPINGS['ImpactWildcardProcessor'].process
|
||||
updated_widget_values = {}
|
||||
mbp_updated_widget_values = {}
|
||||
for k, v in prompt.items():
|
||||
if 'class_type' in v and v['class_type'] == 'WildcardEncode //Inspire':
|
||||
inputs = v['inputs']
|
||||
|
||||
# legacy adapter
|
||||
if isinstance(inputs['mode'], bool):
|
||||
if inputs['mode']:
|
||||
new_mode = 'populate'
|
||||
else:
|
||||
new_mode = 'fixed'
|
||||
|
||||
inputs['mode'] = new_mode
|
||||
|
||||
if inputs['mode'] == 'populate' and isinstance(inputs['populated_text'], str):
|
||||
if isinstance(inputs['seed'], list):
|
||||
try:
|
||||
input_node = prompt[inputs['seed'][0]]
|
||||
if input_node['class_type'] == 'ImpactInt':
|
||||
input_seed = int(input_node['inputs']['value'])
|
||||
if not isinstance(input_seed, int):
|
||||
continue
|
||||
if input_node['class_type'] == 'Seed (rgthree)':
|
||||
input_seed = int(input_node['inputs']['seed'])
|
||||
if not isinstance(input_seed, int):
|
||||
continue
|
||||
else:
|
||||
logging.warning("[Inspire Pack] Only `ImpactInt`, `Seed (rgthree)` and `Primitive` Node are allowed as the seed for '{v['class_type']}'. It will be ignored. ")
|
||||
continue
|
||||
except:
|
||||
continue
|
||||
else:
|
||||
input_seed = int(inputs['seed'])
|
||||
|
||||
inputs['populated_text'] = wildcard_process(text=inputs['wildcard_text'], seed=input_seed)
|
||||
inputs['mode'] = 'reproduce'
|
||||
|
||||
server.PromptServer.instance.send_sync("inspire-node-feedback", {"node_id": k, "widget_name": "populated_text", "type": "text", "data": inputs['populated_text']})
|
||||
updated_widget_values[k] = inputs['populated_text']
|
||||
|
||||
if inputs['mode'] == 'reproduce':
|
||||
server.PromptServer.instance.send_sync("inspire-node-feedback", {"node_id": k, "widget_name": "mode", "type": "text", "value": 'populate'})
|
||||
|
||||
elif 'class_type' in v and v['class_type'] == 'MakeBasicPipe //Inspire':
|
||||
inputs = v['inputs']
|
||||
if inputs['wildcard_mode'] == 'populate' and (isinstance(inputs['positive_populated_text'], str) or isinstance(inputs['negative_populated_text'], str)):
|
||||
if isinstance(inputs['seed'], list):
|
||||
try:
|
||||
input_node = prompt[inputs['seed'][0]]
|
||||
if input_node['class_type'] == 'ImpactInt':
|
||||
input_seed = int(input_node['inputs']['value'])
|
||||
if not isinstance(input_seed, int):
|
||||
continue
|
||||
if input_node['class_type'] == 'Seed (rgthree)':
|
||||
input_seed = int(input_node['inputs']['seed'])
|
||||
if not isinstance(input_seed, int):
|
||||
continue
|
||||
else:
|
||||
logging.warning("[Inspire Pack] Only `ImpactInt`, `Seed (rgthree)` and `Primitive` Node are allowed as the seed for '{v['class_type']}'. It will be ignored. ")
|
||||
continue
|
||||
except:
|
||||
continue
|
||||
else:
|
||||
input_seed = int(inputs['seed'])
|
||||
|
||||
if isinstance(inputs['positive_populated_text'], str):
|
||||
inputs['positive_populated_text'] = wildcard_process(text=inputs['positive_wildcard_text'], seed=input_seed)
|
||||
server.PromptServer.instance.send_sync("inspire-node-feedback", {"node_id": k, "widget_name": "positive_populated_text", "type": "text", "data": inputs['positive_populated_text']})
|
||||
|
||||
if isinstance(inputs['negative_populated_text'], str):
|
||||
inputs['negative_populated_text'] = wildcard_process(text=inputs['negative_wildcard_text'], seed=input_seed)
|
||||
server.PromptServer.instance.send_sync("inspire-node-feedback", {"node_id": k, "widget_name": "negative_populated_text", "type": "text", "data": inputs['negative_populated_text']})
|
||||
|
||||
inputs['wildcard_mode'] = 'reproduce'
|
||||
mbp_updated_widget_values[k] = inputs['positive_populated_text'], inputs['negative_populated_text']
|
||||
|
||||
if inputs['wildcard_mode'] == 'reproduce':
|
||||
server.PromptServer.instance.send_sync("inspire-node-feedback", {"node_id": k, "widget_name": "wildcard_mode", "type": "text", "value": 'populate'})
|
||||
|
||||
if 'extra_data' in json_data and 'extra_pnginfo' in json_data['extra_data']:
|
||||
extra_pnginfo = json_data['extra_data']['extra_pnginfo']
|
||||
if 'workflow' in extra_pnginfo and extra_pnginfo['workflow'] is not None and 'nodes' in extra_pnginfo['workflow']:
|
||||
for node in extra_pnginfo['workflow']['nodes']:
|
||||
key = str(node['id'])
|
||||
if key in updated_widget_values:
|
||||
node['widgets_values'][3] = updated_widget_values[key]
|
||||
node['widgets_values'][4] = 'reproduce'
|
||||
if key in mbp_updated_widget_values:
|
||||
node['widgets_values'][7] = mbp_updated_widget_values[key][0]
|
||||
node['widgets_values'][8] = mbp_updated_widget_values[key][1]
|
||||
node['widgets_values'][5] = 'reproduce'
|
||||
|
||||
|
||||
def force_reset_useless_params(json_data):
|
||||
prompt = json_data['prompt']
|
||||
|
||||
for k, v in prompt.items():
|
||||
if 'class_type' in v and v['class_type'] == 'PromptBuilder //Inspire':
|
||||
v['inputs']['category'] = '#PLACEHOLDER'
|
||||
|
||||
return json_data
|
||||
|
||||
|
||||
def clear_unused_node_changed_cache(json_data):
|
||||
prompt = json_data['prompt']
|
||||
|
||||
unused = []
|
||||
for x in common.changed_cache.keys():
|
||||
if x not in prompt:
|
||||
unused.append(x)
|
||||
|
||||
for x in unused:
|
||||
del common.changed_cache[x]
|
||||
del common.changed_count_cache[x]
|
||||
|
||||
return json_data
|
||||
|
||||
|
||||
def onprompt(json_data):
|
||||
prompt_support.list_counter_map = {}
|
||||
|
||||
is_changed, mode = prompt_seed_update(json_data)
|
||||
if is_changed:
|
||||
workflow_seed_update(json_data, mode)
|
||||
|
||||
prompt_sampler_update(json_data)
|
||||
|
||||
workflow_loadimage_update(json_data)
|
||||
populate_wildcards(json_data)
|
||||
|
||||
force_reset_useless_params(json_data)
|
||||
clear_unused_node_changed_cache(json_data)
|
||||
|
||||
return json_data
|
||||
|
||||
|
||||
server.PromptServer.instance.add_on_prompt_handler(onprompt)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {}
|
||||
87
custom_nodes/comfyui-inspire-pack/inspire/libs/common.py
Normal file
87
custom_nodes/comfyui-inspire-pack/inspire/libs/common.py
Normal file
@@ -0,0 +1,87 @@
|
||||
import comfy
|
||||
import nodes
|
||||
from . import utils
|
||||
import logging
|
||||
from server import PromptServer
|
||||
|
||||
|
||||
ADDITIONAL_SCHEDULERS = ['AYS SDXL', 'AYS SD1', 'AYS SVD', 'GITS[coeff=1.2]', 'LTXV[default]', 'OSS FLUX', 'OSS Wan', 'OSS Chroma']
|
||||
|
||||
|
||||
def get_schedulers():
|
||||
return list(comfy.samplers.SCHEDULER_HANDLERS) + ADDITIONAL_SCHEDULERS
|
||||
|
||||
|
||||
def impact_sampling(*args, **kwargs):
|
||||
if 'RegionalSampler' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/ltdrdata/ComfyUI-Impact-Pack',
|
||||
"'Impact Pack' extension is required.")
|
||||
raise Exception("[ERROR] You need to install 'ComfyUI-Impact-Pack'")
|
||||
|
||||
return nodes.NODE_CLASS_MAPPINGS['RegionalSampler'].separated_sample(*args, **kwargs)
|
||||
|
||||
|
||||
changed_count_cache = {}
|
||||
changed_cache = {}
|
||||
|
||||
|
||||
def changed_value(uid):
|
||||
v = changed_count_cache.get(uid, 0)
|
||||
changed_count_cache[uid] = v + 1
|
||||
return v + 1
|
||||
|
||||
|
||||
def not_changed_value(uid):
|
||||
return changed_count_cache.get(uid, 0)
|
||||
|
||||
|
||||
def is_changed(uid, value):
|
||||
if uid not in changed_cache or changed_cache[uid] != value:
|
||||
res = changed_value(uid)
|
||||
else:
|
||||
res = not_changed_value(uid)
|
||||
|
||||
changed_cache[uid] = value
|
||||
|
||||
logging.info(f"keys: {changed_cache.keys()}")
|
||||
|
||||
return res
|
||||
|
||||
|
||||
def update_node_status(node, text, progress=None):
|
||||
if PromptServer.instance.client_id is None:
|
||||
return
|
||||
|
||||
PromptServer.instance.send_sync("inspire/update_status", {
|
||||
"node": node,
|
||||
"progress": progress,
|
||||
"text": text
|
||||
}, PromptServer.instance.client_id)
|
||||
|
||||
|
||||
class ListWrapper:
|
||||
def __init__(self, data, aux=None):
|
||||
if isinstance(data, ListWrapper):
|
||||
self._data = data
|
||||
if aux is None:
|
||||
self.aux = data.aux
|
||||
else:
|
||||
self.aux = aux
|
||||
else:
|
||||
self._data = list(data)
|
||||
self.aux = aux
|
||||
|
||||
def __getitem__(self, index):
|
||||
if isinstance(index, slice):
|
||||
return ListWrapper(self._data[index], self.aux)
|
||||
else:
|
||||
return self._data[index]
|
||||
|
||||
def __setitem__(self, index, value):
|
||||
self._data[index] = value
|
||||
|
||||
def __len__(self):
|
||||
return len(self._data)
|
||||
|
||||
def __repr__(self):
|
||||
return f"ListWrapper({self._data}, aux={self.aux})"
|
||||
351
custom_nodes/comfyui-inspire-pack/inspire/libs/utils.py
Normal file
351
custom_nodes/comfyui-inspire-pack/inspire/libs/utils.py
Normal file
@@ -0,0 +1,351 @@
|
||||
import itertools
|
||||
from typing import Optional
|
||||
import numpy as np
|
||||
import torch
|
||||
from PIL import Image, ImageDraw
|
||||
import math
|
||||
import cv2
|
||||
import folder_paths
|
||||
import logging
|
||||
|
||||
|
||||
def apply_variation_noise(latent_image, noise_device, variation_seed, variation_strength, mask=None, variation_method='linear'):
|
||||
latent_size = latent_image.size()
|
||||
latent_size_1batch = [1, latent_size[1], latent_size[2], latent_size[3]]
|
||||
|
||||
if noise_device == "cpu":
|
||||
variation_generator = torch.manual_seed(variation_seed)
|
||||
else:
|
||||
torch.cuda.manual_seed(variation_seed)
|
||||
variation_generator = None
|
||||
|
||||
variation_latent = torch.randn(latent_size_1batch, dtype=latent_image.dtype, layout=latent_image.layout,
|
||||
generator=variation_generator, device=noise_device)
|
||||
|
||||
variation_noise = variation_latent.expand(latent_image.size()[0], -1, -1, -1)
|
||||
|
||||
if variation_strength == 0:
|
||||
return latent_image
|
||||
elif mask is None:
|
||||
result = (1 - variation_strength) * latent_image + variation_strength * variation_noise
|
||||
else:
|
||||
# this seems precision is not enough when variation_strength is 0.0
|
||||
mixed_noise = mix_noise(latent_image, variation_noise, variation_strength, variation_method=variation_method)
|
||||
result = (mask == 1).float() * mixed_noise + (mask == 0).float() * latent_image
|
||||
|
||||
return result
|
||||
|
||||
|
||||
# CREDIT: https://github.com/BlenderNeko/ComfyUI_Noise/blob/afb14757216257b12268c91845eac248727a55e2/nodes.py#L68
|
||||
# https://discuss.pytorch.org/t/help-regarding-slerp-function-for-generative-model-sampling/32475/3
|
||||
def slerp(val, low, high):
|
||||
dims = low.shape
|
||||
|
||||
low = low.reshape(dims[0], -1)
|
||||
high = high.reshape(dims[0], -1)
|
||||
|
||||
low_norm = low/torch.norm(low, dim=1, keepdim=True)
|
||||
high_norm = high/torch.norm(high, dim=1, keepdim=True)
|
||||
|
||||
low_norm[low_norm != low_norm] = 0.0
|
||||
high_norm[high_norm != high_norm] = 0.0
|
||||
|
||||
omega = torch.acos((low_norm*high_norm).sum(1))
|
||||
so = torch.sin(omega)
|
||||
res = (torch.sin((1.0-val)*omega)/so).unsqueeze(1)*low + (torch.sin(val*omega)/so).unsqueeze(1) * high
|
||||
|
||||
return res.reshape(dims)
|
||||
|
||||
|
||||
def mix_noise(from_noise, to_noise, strength, variation_method):
|
||||
to_noise = to_noise.to(from_noise.device)
|
||||
|
||||
if variation_method == 'slerp':
|
||||
mixed_noise = slerp(strength, from_noise, to_noise)
|
||||
else:
|
||||
# linear
|
||||
mixed_noise = (1 - strength) * from_noise + strength * to_noise
|
||||
|
||||
# NOTE: Since the variance of the Gaussian noise in mixed_noise has changed, it must be corrected through scaling.
|
||||
scale_factor = math.sqrt((1 - strength) ** 2 + strength ** 2)
|
||||
mixed_noise /= scale_factor
|
||||
|
||||
return mixed_noise
|
||||
|
||||
|
||||
def prepare_noise(latent_image, seed, noise_inds=None, noise_device="cpu", incremental_seed_mode="comfy", variation_seed=None, variation_strength=None, variation_method="linear"):
|
||||
"""
|
||||
creates random noise given a latent image and a seed.
|
||||
optional arg skip can be used to skip and discard x number of noise generations for a given seed
|
||||
"""
|
||||
|
||||
latent_size = latent_image.size()
|
||||
latent_size_1batch = [1, latent_size[1], latent_size[2], latent_size[3]]
|
||||
|
||||
if variation_strength is not None and variation_strength > 0 or incremental_seed_mode.startswith("variation str inc"):
|
||||
if noise_device == "cpu":
|
||||
variation_generator = torch.manual_seed(variation_seed)
|
||||
else:
|
||||
torch.cuda.manual_seed(variation_seed)
|
||||
variation_generator = None
|
||||
|
||||
variation_latent = torch.randn(latent_size_1batch, dtype=latent_image.dtype, layout=latent_image.layout,
|
||||
generator=variation_generator, device=noise_device)
|
||||
else:
|
||||
variation_latent = None
|
||||
|
||||
def apply_variation(input_latent, strength_up=None):
|
||||
if variation_latent is None:
|
||||
return input_latent
|
||||
else:
|
||||
strength = variation_strength
|
||||
|
||||
if strength_up is not None:
|
||||
strength += strength_up
|
||||
|
||||
variation_noise = variation_latent.expand(input_latent.size()[0], -1, -1, -1)
|
||||
|
||||
mixed_noise = mix_noise(input_latent, variation_noise, strength, variation_method)
|
||||
|
||||
return mixed_noise
|
||||
|
||||
# method: incremental seed batch noise
|
||||
if noise_inds is None and incremental_seed_mode == "incremental":
|
||||
batch_cnt = latent_size[0]
|
||||
|
||||
latents = None
|
||||
for i in range(batch_cnt):
|
||||
if noise_device == "cpu":
|
||||
generator = torch.manual_seed(seed+i)
|
||||
else:
|
||||
torch.cuda.manual_seed(seed+i)
|
||||
generator = None
|
||||
|
||||
latent = torch.randn(latent_size_1batch, dtype=latent_image.dtype, layout=latent_image.layout,
|
||||
generator=generator, device=noise_device)
|
||||
|
||||
latent = apply_variation(latent)
|
||||
|
||||
if latents is None:
|
||||
latents = latent
|
||||
else:
|
||||
latents = torch.cat((latents, latent), dim=0)
|
||||
|
||||
return latents
|
||||
|
||||
# method: incremental variation batch noise
|
||||
elif noise_inds is None and incremental_seed_mode.startswith("variation str inc"):
|
||||
batch_cnt = latent_size[0]
|
||||
|
||||
latents = None
|
||||
for i in range(batch_cnt):
|
||||
if noise_device == "cpu":
|
||||
generator = torch.manual_seed(seed)
|
||||
else:
|
||||
torch.cuda.manual_seed(seed)
|
||||
generator = None
|
||||
|
||||
latent = torch.randn(latent_size_1batch, dtype=latent_image.dtype, layout=latent_image.layout,
|
||||
generator=generator, device=noise_device)
|
||||
|
||||
step = float(incremental_seed_mode[18:])
|
||||
latent = apply_variation(latent, step*i)
|
||||
|
||||
if latents is None:
|
||||
latents = latent
|
||||
else:
|
||||
latents = torch.cat((latents, latent), dim=0)
|
||||
|
||||
return latents
|
||||
|
||||
# method: comfy batch noise
|
||||
if noise_device == "cpu":
|
||||
generator = torch.manual_seed(seed)
|
||||
else:
|
||||
torch.cuda.manual_seed(seed)
|
||||
generator = None
|
||||
|
||||
if noise_inds is None:
|
||||
latents = torch.randn(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout,
|
||||
generator=generator, device=noise_device)
|
||||
latents = apply_variation(latents)
|
||||
return latents
|
||||
|
||||
unique_inds, inverse = np.unique(noise_inds, return_inverse=True)
|
||||
noises = []
|
||||
for i in range(unique_inds[-1] + 1):
|
||||
noise = torch.randn([1] + list(latent_image.size())[1:], dtype=latent_image.dtype, layout=latent_image.layout,
|
||||
generator=generator, device=noise_device)
|
||||
if i in unique_inds:
|
||||
noises.append(noise)
|
||||
noises = [noises[i] for i in inverse]
|
||||
noises = torch.cat(noises, axis=0)
|
||||
return noises
|
||||
|
||||
|
||||
def pil2tensor(image):
|
||||
return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
|
||||
|
||||
|
||||
def empty_pil_tensor(w=64, h=64):
|
||||
image = Image.new("RGB", (w, h))
|
||||
draw = ImageDraw.Draw(image)
|
||||
draw.rectangle((0, 0, w-1, h-1), fill=(0, 0, 0))
|
||||
return pil2tensor(image)
|
||||
|
||||
|
||||
def try_install_custom_node(custom_node_url, msg):
|
||||
try:
|
||||
import cm_global
|
||||
cm_global.try_call(api='cm.try-install-custom-node',
|
||||
sender="Inspire Pack", custom_node_url=custom_node_url, msg=msg)
|
||||
except Exception as e: # noqa: F841
|
||||
logging.error(msg)
|
||||
logging.error("[Inspire Pack] ComfyUI-Manager is outdated. The custom node installation feature is not available.")
|
||||
|
||||
|
||||
def empty_latent():
|
||||
return torch.zeros([1, 4, 8, 8])
|
||||
|
||||
# wildcard trick is taken from pythongossss's
|
||||
class AnyType(str):
|
||||
def __ne__(self, __value: object) -> bool:
|
||||
return False
|
||||
|
||||
any_typ = AnyType("*")
|
||||
|
||||
|
||||
# author: Trung0246 --->
|
||||
class TautologyStr(str):
|
||||
def __ne__(self, other):
|
||||
return False
|
||||
|
||||
|
||||
class ByPassTypeTuple(tuple):
|
||||
def __getitem__(self, index):
|
||||
if index > 0:
|
||||
index = 0
|
||||
item = super().__getitem__(index)
|
||||
if isinstance(item, str):
|
||||
return TautologyStr(item)
|
||||
return item
|
||||
|
||||
|
||||
class TaggedCache:
|
||||
def __init__(self, tag_settings: Optional[dict]=None):
|
||||
self._tag_settings = tag_settings or {} # tag cache size
|
||||
self._data = {}
|
||||
|
||||
def __getitem__(self, key):
|
||||
for tag_data in self._data.values():
|
||||
if key in tag_data:
|
||||
return tag_data[key]
|
||||
raise KeyError(f'Key `{key}` does not exist')
|
||||
|
||||
def __setitem__(self, key, value: tuple):
|
||||
# value: (tag: str, (islist: bool, data: *))
|
||||
|
||||
# if key already exists, pop old value
|
||||
for tag_data in self._data.values():
|
||||
if key in tag_data:
|
||||
tag_data.pop(key, None)
|
||||
break
|
||||
|
||||
tag = value[0]
|
||||
if tag not in self._data:
|
||||
|
||||
try:
|
||||
from cachetools import LRUCache
|
||||
|
||||
default_size = 20
|
||||
if 'ckpt' in tag:
|
||||
default_size = 5
|
||||
elif tag in ['latent', 'image']:
|
||||
default_size = 100
|
||||
|
||||
self._data[tag] = LRUCache(maxsize=self._tag_settings.get(tag, default_size))
|
||||
|
||||
except (ImportError, ModuleNotFoundError):
|
||||
# TODO: implement a simple lru dict
|
||||
self._data[tag] = {}
|
||||
self._data[tag][key] = value
|
||||
|
||||
def __delitem__(self, key):
|
||||
for tag_data in self._data.values():
|
||||
if key in tag_data:
|
||||
del tag_data[key]
|
||||
return
|
||||
raise KeyError(f'Key `{key}` does not exist')
|
||||
|
||||
def __contains__(self, key):
|
||||
return any(key in tag_data for tag_data in self._data.values())
|
||||
|
||||
def items(self):
|
||||
yield from itertools.chain(*map(lambda x :x.items(), self._data.values()))
|
||||
|
||||
def get(self, key, default=None):
|
||||
"""D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None."""
|
||||
for tag_data in self._data.values():
|
||||
if key in tag_data:
|
||||
return tag_data[key]
|
||||
return default
|
||||
|
||||
def clear(self):
|
||||
# clear all cache
|
||||
self._data = {}
|
||||
|
||||
|
||||
def make_3d_mask(mask):
|
||||
if len(mask.shape) == 4:
|
||||
return mask.squeeze(0)
|
||||
|
||||
elif len(mask.shape) == 2:
|
||||
return mask.unsqueeze(0)
|
||||
|
||||
return mask
|
||||
|
||||
|
||||
def dilate_mask(mask: torch.Tensor, dilation_factor: float) -> torch.Tensor:
|
||||
"""Dilate a mask using a square kernel with a given dilation factor."""
|
||||
kernel_size = int(dilation_factor * 2) + 1
|
||||
kernel = np.ones((abs(kernel_size), abs(kernel_size)), np.uint8)
|
||||
|
||||
masks = make_3d_mask(mask).numpy()
|
||||
dilated_masks = []
|
||||
for m in masks:
|
||||
if dilation_factor > 0:
|
||||
m2 = cv2.dilate(m, kernel, iterations=1)
|
||||
else:
|
||||
m2 = cv2.erode(m, kernel, iterations=1)
|
||||
|
||||
dilated_masks.append(torch.from_numpy(m2))
|
||||
|
||||
return torch.stack(dilated_masks)
|
||||
|
||||
|
||||
def flatten_non_zero_override(masks: torch.Tensor):
|
||||
"""
|
||||
flatten multiple layer mask tensor to 1 layer mask tensor.
|
||||
Override the lower layer with the tensor from the upper layer, but only override non-zero values.
|
||||
|
||||
:param masks: 3d mask
|
||||
:return: flatten mask
|
||||
"""
|
||||
final_mask = masks[0]
|
||||
|
||||
for i in range(1, masks.size(0)):
|
||||
non_zero_mask = masks[i] != 0
|
||||
final_mask[non_zero_mask] = masks[i][non_zero_mask]
|
||||
|
||||
return final_mask
|
||||
|
||||
|
||||
def add_folder_path_and_extensions(folder_name, full_folder_paths, extensions):
|
||||
for full_folder_path in full_folder_paths:
|
||||
folder_paths.add_model_folder_path(folder_name, full_folder_path)
|
||||
if folder_name in folder_paths.folder_names_and_paths:
|
||||
current_paths, current_extensions = folder_paths.folder_names_and_paths[folder_name]
|
||||
updated_extensions = current_extensions | extensions
|
||||
folder_paths.folder_names_and_paths[folder_name] = (current_paths, updated_extensions)
|
||||
else:
|
||||
folder_paths.folder_names_and_paths[folder_name] = (full_folder_paths, extensions)
|
||||
266
custom_nodes/comfyui-inspire-pack/inspire/list_nodes.py
Normal file
266
custom_nodes/comfyui-inspire-pack/inspire/list_nodes.py
Normal file
@@ -0,0 +1,266 @@
|
||||
import logging
|
||||
|
||||
from comfy_execution.graph_utils import GraphBuilder, is_link
|
||||
from .libs.utils import any_typ
|
||||
from .libs.common import update_node_status, ListWrapper
|
||||
|
||||
class FloatRange:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"start": ("FLOAT", {"default": 0.0, "min": -100.0, "max": 100.0, 'step': 0.000000001}),
|
||||
"stop": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, 'step': 0.000000001}),
|
||||
"step": ("FLOAT", {"default": 0.01, "min": 0.0, "max": 100.0, 'step': 0.000000001}),
|
||||
"limit": ("INT", {"default": 100, "min": 2, "max": 4096, "step": 1}),
|
||||
"ensure_end": ("BOOLEAN", {"default": True, "label_on": "enable", "label_off": "disable"}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("FLOAT",)
|
||||
OUTPUT_IS_LIST = (True,)
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/List"
|
||||
|
||||
def doit(self, start, stop, step, limit, ensure_end):
|
||||
if start == stop or step == 0:
|
||||
return ([start], )
|
||||
|
||||
reverse = False
|
||||
if start > stop:
|
||||
reverse = True
|
||||
start, stop = stop, start
|
||||
|
||||
res = []
|
||||
x = start
|
||||
last = x
|
||||
while x <= stop and limit > 0:
|
||||
res.append(x)
|
||||
last = x
|
||||
limit -= 1
|
||||
x += step
|
||||
|
||||
if ensure_end and last != stop:
|
||||
if len(res) >= limit:
|
||||
res.pop()
|
||||
|
||||
res.append(stop)
|
||||
|
||||
if reverse:
|
||||
res.reverse()
|
||||
|
||||
return (res, )
|
||||
|
||||
|
||||
class WorklistToItemList:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"item": (any_typ, ),
|
||||
}
|
||||
}
|
||||
|
||||
INPUT_IS_LIST = True
|
||||
|
||||
RETURN_TYPES = ("ITEM_LIST",)
|
||||
RETURN_NAMES = ("item_list",)
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
DESCRIPTION = "The list in ComfyUI allows for repeated execution of a sub-workflow.\nThis groups these repetitions (a.k.a. list) into a single ITEM_LIST output.\nITEM_LIST can then be used in ForeachList."
|
||||
|
||||
CATEGORY = "InspirePack/List"
|
||||
|
||||
def doit(self, item):
|
||||
return (item, )
|
||||
|
||||
|
||||
# Loop nodes are implemented based on BadCafeCode's reference loop implementation
|
||||
# https://github.com/BadCafeCode/execution-inversion-demo-comfyui/blob/main/flow_control.py
|
||||
|
||||
class ForeachListBegin:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"item_list": ("ITEM_LIST", {"tooltip": "ITEM_LIST containing items to be processed iteratively."}),
|
||||
},
|
||||
"optional": {
|
||||
"initial_input": (any_typ, {"tooltip": "If initial_input is omitted, the first item in item_list is used as the initial value, and the processing starts from the second item in item_list."}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("FOREACH_LIST_CONTROL", "ITEM_LIST", any_typ, any_typ)
|
||||
RETURN_NAMES = ("flow_control", "remained_list", "item", "intermediate_output")
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"Pass ForeachListEnd as is to indicate the end of the iteration.",
|
||||
"Output the ITEM_LIST containing the remaining items during the iteration, passing ForeachListEnd as is to indicate the end of the iteration.",
|
||||
"Output the current item during the iteration.",
|
||||
"Output the intermediate results during the iteration.")
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
DESCRIPTION = "A starting node for performing iterative tasks by retrieving items one by one from the ITEM_LIST.\nGenerate a new intermediate_output using item and intermediate_output as inputs, then connect it to ForeachListEnd.\nNOTE:If initial_input is omitted, the first item in item_list is used as the initial value, and the processing starts from the second item in item_list."
|
||||
|
||||
CATEGORY = "InspirePack/List"
|
||||
|
||||
def doit(self, item_list, initial_input=None):
|
||||
if initial_input is None:
|
||||
initial_input = item_list[0]
|
||||
item_list = item_list[1:]
|
||||
|
||||
if len(item_list) > 0:
|
||||
next_list = ListWrapper(item_list[1:])
|
||||
next_item = item_list[0]
|
||||
else:
|
||||
next_list = ListWrapper([])
|
||||
next_item = None
|
||||
|
||||
if next_list.aux is None:
|
||||
next_list.aux = len(item_list), None
|
||||
|
||||
return "stub", next_list, next_item, initial_input
|
||||
|
||||
|
||||
class ForeachListEnd:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"flow_control": ("FOREACH_LIST_CONTROL", {"rawLink": True, "tooltip": "Directly connect the output of ForeachListBegin, the starting node of the iteration."}),
|
||||
"remained_list": ("ITEM_LIST", {"tooltip":"Directly connect the output of ForeachListBegin, the starting node of the iteration."}),
|
||||
"intermediate_output": (any_typ, {"tooltip":"Connect the intermediate outputs processed within the iteration here."}),
|
||||
},
|
||||
"hidden": {
|
||||
"dynprompt": "DYNPROMPT",
|
||||
"unique_id": "UNIQUE_ID",
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = (any_typ,)
|
||||
RETURN_NAMES = ("result",)
|
||||
OUTPUT_TOOLTIPS = ("This is the final output value.",)
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
DESCRIPTION = "A end node for performing iterative tasks by retrieving items one by one from the ITEM_LIST.\nNOTE:Directly connect the outputs of ForeachListBegin to 'flow_control' and 'remained_list'."
|
||||
|
||||
CATEGORY = "InspirePack/List"
|
||||
|
||||
def explore_dependencies(self, node_id, dynprompt, upstream):
|
||||
node_info = dynprompt.get_node(node_id)
|
||||
if "inputs" not in node_info:
|
||||
return
|
||||
for k, v in node_info["inputs"].items():
|
||||
if is_link(v):
|
||||
parent_id = v[0]
|
||||
if parent_id not in upstream:
|
||||
upstream[parent_id] = []
|
||||
self.explore_dependencies(parent_id, dynprompt, upstream)
|
||||
upstream[parent_id].append(node_id)
|
||||
|
||||
def collect_contained(self, node_id, upstream, contained):
|
||||
if node_id not in upstream:
|
||||
return
|
||||
for child_id in upstream[node_id]:
|
||||
if child_id not in contained:
|
||||
contained[child_id] = True
|
||||
self.collect_contained(child_id, upstream, contained)
|
||||
|
||||
def doit(self, flow_control, remained_list, intermediate_output, dynprompt, unique_id):
|
||||
if hasattr(remained_list, "aux"):
|
||||
if remained_list.aux[1] is None:
|
||||
remained_list.aux = (remained_list.aux[0], unique_id)
|
||||
|
||||
update_node_status(remained_list.aux[1], f"{(remained_list.aux[0]-len(remained_list))}/{remained_list.aux[0]} steps", (remained_list.aux[0]-len(remained_list))/remained_list.aux[0])
|
||||
else:
|
||||
logging.warning("[Inspire Pack] ForeachListEnd: `remained_list` did not come from ForeachList.")
|
||||
|
||||
if len(remained_list) == 0:
|
||||
return (intermediate_output,)
|
||||
|
||||
# We want to loop
|
||||
upstream = {}
|
||||
|
||||
# Get the list of all nodes between the open and close nodes
|
||||
self.explore_dependencies(unique_id, dynprompt, upstream)
|
||||
|
||||
contained = {}
|
||||
open_node = flow_control[0]
|
||||
self.collect_contained(open_node, upstream, contained)
|
||||
contained[unique_id] = True
|
||||
contained[open_node] = True
|
||||
|
||||
# We'll use the default prefix, but to avoid having node names grow exponentially in size,
|
||||
# we'll use "Recurse" for the name of the recursively-generated copy of this node.
|
||||
graph = GraphBuilder()
|
||||
for node_id in contained:
|
||||
original_node = dynprompt.get_node(node_id)
|
||||
node = graph.node(original_node["class_type"], "Recurse" if node_id == unique_id else node_id)
|
||||
node.set_override_display_id(node_id)
|
||||
|
||||
for node_id in contained:
|
||||
original_node = dynprompt.get_node(node_id)
|
||||
node = graph.lookup_node("Recurse" if node_id == unique_id else node_id)
|
||||
for k, v in original_node["inputs"].items():
|
||||
if is_link(v) and v[0] in contained:
|
||||
parent = graph.lookup_node(v[0])
|
||||
node.set_input(k, parent.out(v[1]))
|
||||
else:
|
||||
node.set_input(k, v)
|
||||
|
||||
new_open = graph.lookup_node(open_node)
|
||||
|
||||
new_open.set_input("item_list", remained_list)
|
||||
new_open.set_input("initial_input", intermediate_output)
|
||||
|
||||
my_clone = graph.lookup_node("Recurse" )
|
||||
result = (my_clone.out(0),)
|
||||
|
||||
return {
|
||||
"result": result,
|
||||
"expand": graph.finalize(),
|
||||
}
|
||||
|
||||
|
||||
class DropItems:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": { "item_list": ("ITEM_LIST", {"tooltip":"Directly connect the output of ForeachListBegin, the starting node of the iteration."}), },
|
||||
}
|
||||
|
||||
RETURN_TYPES = (any_typ,)
|
||||
RETURN_NAMES = ("ITEM_LIST",)
|
||||
OUTPUT_TOOLTIPS = ("This is the final output value.",)
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
DESCRIPTION = ""
|
||||
|
||||
CATEGORY = "InspirePack/List"
|
||||
|
||||
def doit(self, item_list):
|
||||
l = ListWrapper([])
|
||||
if hasattr(item_list, 'aux'):
|
||||
l.aux = item_list.aux
|
||||
else:
|
||||
logging.warning("[Inspire Pack] DropItems: `item_list` did not come from ForeachList.")
|
||||
|
||||
return (l,)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"FloatRange //Inspire": FloatRange,
|
||||
"WorklistToItemList //Inspire": WorklistToItemList,
|
||||
"ForeachListBegin //Inspire": ForeachListBegin,
|
||||
"ForeachListEnd //Inspire": ForeachListEnd,
|
||||
"DropItems //Inspire": DropItems,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"FloatRange //Inspire": "Float Range (Inspire)",
|
||||
"WorklistToItemList //Inspire": "Worklist To Item List (Inspire)",
|
||||
"ForeachListBegin //Inspire": "▶Foreach List (Inspire)",
|
||||
"ForeachListEnd //Inspire": "Foreach List◀ (Inspire)",
|
||||
"DropItems //Inspire": "Drop Items (Inspire)",
|
||||
}
|
||||
1148
custom_nodes/comfyui-inspire-pack/inspire/lora_block_weight.py
Normal file
1148
custom_nodes/comfyui-inspire-pack/inspire/lora_block_weight.py
Normal file
File diff suppressed because it is too large
Load Diff
191
custom_nodes/comfyui-inspire-pack/inspire/model_nodes.py
Normal file
191
custom_nodes/comfyui-inspire-pack/inspire/model_nodes.py
Normal file
@@ -0,0 +1,191 @@
|
||||
import nodes
|
||||
import folder_paths
|
||||
import os
|
||||
import server
|
||||
from .libs import utils
|
||||
from . import backend_support
|
||||
from comfy import sdxl_clip
|
||||
import logging
|
||||
|
||||
|
||||
model_preset = {
|
||||
# base
|
||||
"SD1.5": ("ip-adapter_sd15", "CLIP-ViT-H-14-laion2B-s32B-b79K", None, False),
|
||||
"SD1.5 Light v11": ("ip-adapter_sd15_light_v11", "CLIP-ViT-H-14-laion2B-s32B-b79K", None, False),
|
||||
"SD1.5 Light": ("ip-adapter_sd15_light", "CLIP-ViT-H-14-laion2B-s32B-b79K", None, False),
|
||||
"SD1.5 Plus": ("ip-adapter-plus_sd15", "CLIP-ViT-H-14-laion2B-s32B-b79K", None, False),
|
||||
"SD1.5 Plus Face": ("ip-adapter-plus-face_sd15", "CLIP-ViT-H-14-laion2B-s32B-b79K", None, False),
|
||||
"SD1.5 Full Face": ("ip-adapter-full-face_sd15", "CLIP-ViT-H-14-laion2B-s32B-b79K", None, False),
|
||||
"SD1.5 ViT-G": ("ip-adapter_sd15_vit-G", "CLIP-ViT-bigG-14-laion2B-39B-b160k", None, False),
|
||||
"SDXL": ("ip-adapter_sdxl", "CLIP-ViT-bigG-14-laion2B-39B-b160k", None, False),
|
||||
"SDXL ViT-H": ("ip-adapter_sdxl_vit-h", "CLIP-ViT-H-14-laion2B-s32B-b79K", None, False),
|
||||
"SDXL Plus ViT-H": ("ip-adapter-plus_sdxl_vit-h", "CLIP-ViT-H-14-laion2B-s32B-b79K", None, False),
|
||||
"SDXL Plus Face ViT-H": ("ip-adapter-plus-face_sdxl_vit-h", "CLIP-ViT-H-14-laion2B-s32B-b79K", None, False),
|
||||
"Kolors Plus": ("Kolors-IP-Adapter-Plus", "clip-vit-large-patch14-336", None, False),
|
||||
|
||||
# faceid
|
||||
"SD1.5 FaceID": ("ip-adapter-faceid_sd15", "CLIP-ViT-H-14-laion2B-s32B-b79K", "ip-adapter-faceid_sd15_lora", True),
|
||||
"SD1.5 FaceID Plus v2": ("ip-adapter-faceid-plusv2_sd15", "CLIP-ViT-H-14-laion2B-s32B-b79K", "ip-adapter-faceid-plusv2_sd15_lora", True),
|
||||
"SD1.5 FaceID Plus": ("ip-adapter-faceid-plus_sd15", "CLIP-ViT-H-14-laion2B-s32B-b79K", "ip-adapter-faceid-plus_sd15_lora", True),
|
||||
"SD1.5 FaceID Portrait v11": ("ip-adapter-faceid-portrait-v11_sd15", "CLIP-ViT-H-14-laion2B-s32B-b79K", None, True),
|
||||
"SD1.5 FaceID Portrait": ("ip-adapter-faceid-portrait_sd15", "CLIP-ViT-H-14-laion2B-s32B-b79K", None, True),
|
||||
"SDXL FaceID": ("ip-adapter-faceid_sdxl", "CLIP-ViT-H-14-laion2B-s32B-b79K", "ip-adapter-faceid_sdxl_lora", True),
|
||||
"SDXL FaceID Plus v2": ("ip-adapter-faceid-plusv2_sdxl", "CLIP-ViT-H-14-laion2B-s32B-b79K", "ip-adapter-faceid-plusv2_sdxl_lora", True),
|
||||
"SDXL FaceID Portrait": ("ip-adapter-faceid-portrait_sdxl", "CLIP-ViT-H-14-laion2B-s32B-b79K", None, True),
|
||||
"SDXL FaceID Portrait unnorm": ("ip-adapter-faceid-portrait_sdxl_unnorm", "CLIP-ViT-H-14-laion2B-s32B-b79K", None, True),
|
||||
"Kolors FaceID Plus": ("Kolors-IP-Adapter-FaceID-Plus", "clip-vit-large-patch14-336", None, True),
|
||||
|
||||
# composition
|
||||
"SD1.5 Plus Composition": ("ip-adapter_sd15", "CLIP-ViT-H-14-laion2B-s32B-b79K", None, False),
|
||||
"SDXL Plus Composition": ("ip-adapter_sdxl", "CLIP-ViT-bigG-14-laion2B-39B-b160k", None, False),
|
||||
}
|
||||
|
||||
|
||||
def lookup_model(model_dir, name):
|
||||
if name is None:
|
||||
return None, "N/A"
|
||||
|
||||
names = [(os.path.splitext(os.path.basename(x))[0], x) for x in folder_paths.get_filename_list(model_dir)]
|
||||
resolved_name = [y for x, y in names if x == name]
|
||||
|
||||
if len(resolved_name) > 0:
|
||||
return resolved_name[0], "OK"
|
||||
else:
|
||||
logging.error(f"[Inspire Pack] IPAdapterModelHelper: The `{name}` model file does not exist in `{model_dir}` model dir.")
|
||||
return None, "FAIL"
|
||||
|
||||
|
||||
class IPAdapterModelHelper:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"model": ("MODEL",),
|
||||
"preset": (list(model_preset.keys()),),
|
||||
"lora_strength_model": ("FLOAT", {"default": 1.0, "min": -20.0, "max": 20.0, "step": 0.01}),
|
||||
"lora_strength_clip": ("FLOAT", {"default": 1.0, "min": -20.0, "max": 20.0, "step": 0.01}),
|
||||
"insightface_provider": (["CPU", "CUDA", "ROCM"], ),
|
||||
"cache_mode": (["insightface only", "clip_vision only", "all", "none"], {"default": "insightface only"}),
|
||||
},
|
||||
"optional": {
|
||||
"clip": ("CLIP",),
|
||||
"insightface_model_name": (['buffalo_l', 'antelopev2'],),
|
||||
},
|
||||
"hidden": {"unique_id": "UNIQUE_ID"}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IPADAPTER_PIPE", "IPADAPTER", "CLIP_VISION", "INSIGHTFACE", "MODEL", "CLIP", "STRING", "STRING")
|
||||
RETURN_NAMES = ("IPADAPTER_PIPE", "IPADAPTER", "CLIP_VISION", "INSIGHTFACE", "MODEL", "CLIP", "insightface_cache_key", "clip_vision_cache_key")
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/models"
|
||||
|
||||
def doit(self, model, preset, lora_strength_model, lora_strength_clip, insightface_provider, clip=None, cache_mode="none", unique_id=None, insightface_model_name='buffalo_l'):
|
||||
if 'IPAdapter' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/cubiq/ComfyUI_IPAdapter_plus',
|
||||
"To use 'IPAdapterModelHelper' node, 'ComfyUI IPAdapter Plus' extension is required.")
|
||||
raise Exception("[ERROR] To use IPAdapterModelHelper, you need to install 'ComfyUI IPAdapter Plus'")
|
||||
|
||||
is_sdxl_preset = 'SDXL' in preset
|
||||
if clip is not None:
|
||||
is_sdxl_model = isinstance(clip.tokenizer, sdxl_clip.SDXLTokenizer)
|
||||
else:
|
||||
is_sdxl_model = False
|
||||
|
||||
if is_sdxl_preset != is_sdxl_model:
|
||||
server.PromptServer.instance.send_sync("inspire-node-output-label", {"node_id": unique_id, "output_idx": 1, "label": "IPADAPTER (fail)"})
|
||||
server.PromptServer.instance.send_sync("inspire-node-output-label", {"node_id": unique_id, "output_idx": 2, "label": "CLIP_VISION (fail)"})
|
||||
server.PromptServer.instance.send_sync("inspire-node-output-label", {"node_id": unique_id, "output_idx": 3, "label": "INSIGHTFACE (fail)"})
|
||||
server.PromptServer.instance.send_sync("inspire-node-output-label", {"node_id": unique_id, "output_idx": 4, "label": "MODEL (fail)"})
|
||||
server.PromptServer.instance.send_sync("inspire-node-output-label", {"node_id": unique_id, "output_idx": 5, "label": "CLIP (fail)"})
|
||||
logging.error("[Inspire Pack] IPAdapterModelHelper: You cannot mix SDXL and SD1.5 in the checkpoint and IPAdapter.")
|
||||
raise Exception("[ERROR] You cannot mix SDXL and SD1.5 in the checkpoint and IPAdapter.")
|
||||
|
||||
ipadapter, clipvision, lora, is_insightface = model_preset[preset]
|
||||
|
||||
ipadapter, ok1 = lookup_model("ipadapter", ipadapter)
|
||||
clipvision, ok2 = lookup_model("clip_vision", clipvision)
|
||||
lora, ok3 = lookup_model("loras", lora)
|
||||
|
||||
if ok1 == "OK":
|
||||
ok1 = "IPADAPTER"
|
||||
else:
|
||||
ok1 = f"IPADAPTER ({ok1})"
|
||||
|
||||
if ok2 == "OK":
|
||||
ok2 = "CLIP_VISION"
|
||||
else:
|
||||
ok2 = f"CLIP_VISION ({ok2})"
|
||||
|
||||
server.PromptServer.instance.send_sync("inspire-node-output-label", {"node_id": unique_id, "output_idx": 1, "label": ok1})
|
||||
server.PromptServer.instance.send_sync("inspire-node-output-label", {"node_id": unique_id, "output_idx": 2, "label": ok2})
|
||||
|
||||
if ok3 == "FAIL":
|
||||
server.PromptServer.instance.send_sync("inspire-node-output-label", {"node_id": unique_id, "output_idx": 4, "label": "MODEL (fail)"})
|
||||
server.PromptServer.instance.send_sync("inspire-node-output-label", {"node_id": unique_id, "output_idx": 5, "label": "CLIP (fail)"})
|
||||
else:
|
||||
server.PromptServer.instance.send_sync("inspire-node-output-label", {"node_id": unique_id, "output_idx": 4, "label": "MODEL"})
|
||||
server.PromptServer.instance.send_sync("inspire-node-output-label", {"node_id": unique_id, "output_idx": 5, "label": "CLIP"})
|
||||
|
||||
if ok1 == "FAIL" or ok2 == "FAIL" or ok3 == "FAIL":
|
||||
raise Exception("ERROR: Failed to load several models in IPAdapterModelHelper.")
|
||||
|
||||
if ipadapter is not None:
|
||||
ipadapter = nodes.NODE_CLASS_MAPPINGS["IPAdapterModelLoader"]().load_ipadapter_model(ipadapter_file=ipadapter)[0]
|
||||
|
||||
ccache_key = ""
|
||||
if clipvision is not None:
|
||||
if cache_mode in ["clip_vision only", "all"]:
|
||||
ccache_key = clipvision
|
||||
if ccache_key not in backend_support.cache:
|
||||
backend_support.update_cache(ccache_key, "clipvision", (False, nodes.CLIPVisionLoader().load_clip(clip_name=clipvision)[0]))
|
||||
_, (_, clipvision) = backend_support.cache[ccache_key]
|
||||
else:
|
||||
clipvision = nodes.CLIPVisionLoader().load_clip(clip_name=clipvision)[0]
|
||||
|
||||
if lora is not None:
|
||||
model, clip = nodes.LoraLoader().load_lora(model=model, clip=clip, lora_name=lora, strength_model=lora_strength_model, strength_clip=lora_strength_clip)
|
||||
|
||||
def f(x):
|
||||
return nodes.LoraLoader().load_lora(model=x, clip=clip, lora_name=lora, strength_model=lora_strength_model, strength_clip=lora_strength_clip)
|
||||
lora_loader = f
|
||||
else:
|
||||
def f(x):
|
||||
return x
|
||||
lora_loader = f
|
||||
|
||||
if 'IPAdapterInsightFaceLoader' in nodes.NODE_CLASS_MAPPINGS:
|
||||
insight_face_loader = nodes.NODE_CLASS_MAPPINGS['IPAdapterInsightFaceLoader']().load_insightface
|
||||
else:
|
||||
logging.warning("'ComfyUI IPAdapter Plus' extension is either too outdated or not installed.")
|
||||
insight_face_loader = None
|
||||
|
||||
icache_key = ""
|
||||
if is_insightface:
|
||||
if insight_face_loader is None:
|
||||
raise Exception("[ERROR] 'ComfyUI IPAdapter Plus' extension is either too outdated or not installed.")
|
||||
|
||||
if cache_mode in ["insightface only", "all"]:
|
||||
icache_key = 'insightface-' + insightface_provider
|
||||
if icache_key not in backend_support.cache:
|
||||
backend_support.update_cache(icache_key, "insightface", (False, insight_face_loader(provider=insightface_provider, model_name=insightface_model_name)[0]))
|
||||
_, (_, insightface) = backend_support.cache[icache_key]
|
||||
else:
|
||||
insightface = insight_face_loader(insightface_provider)[0]
|
||||
|
||||
server.PromptServer.instance.send_sync("inspire-node-output-label", {"node_id": unique_id, "output_idx": 3, "label": "INSIGHTFACE"})
|
||||
else:
|
||||
insightface = None
|
||||
server.PromptServer.instance.send_sync("inspire-node-output-label", {"node_id": unique_id, "output_idx": 3, "label": "INSIGHTFACE (N/A)"})
|
||||
|
||||
pipe = ipadapter, model, clipvision, insightface, lora_loader
|
||||
return pipe, ipadapter, clipvision, insightface, model, clip, icache_key, ccache_key
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"IPAdapterModelHelper //Inspire": IPAdapterModelHelper,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"IPAdapterModelHelper //Inspire": "IPAdapter Model Helper (Inspire)",
|
||||
}
|
||||
1063
custom_nodes/comfyui-inspire-pack/inspire/prompt_support.py
Normal file
1063
custom_nodes/comfyui-inspire-pack/inspire/prompt_support.py
Normal file
File diff suppressed because it is too large
Load Diff
699
custom_nodes/comfyui-inspire-pack/inspire/regional_nodes.py
Normal file
699
custom_nodes/comfyui-inspire-pack/inspire/regional_nodes.py
Normal file
@@ -0,0 +1,699 @@
|
||||
import traceback
|
||||
|
||||
import comfy
|
||||
import nodes
|
||||
import torch
|
||||
import re
|
||||
import webcolors
|
||||
|
||||
from . import prompt_support
|
||||
from .libs import utils, common
|
||||
|
||||
import logging
|
||||
|
||||
class RegionalPromptSimple:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"basic_pipe": ("BASIC_PIPE",),
|
||||
"mask": ("MASK",),
|
||||
"cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0}),
|
||||
"sampler_name": (comfy.samplers.KSampler.SAMPLERS,),
|
||||
"scheduler": (common.get_schedulers(),),
|
||||
"wildcard_prompt": ("STRING", {"multiline": True, "dynamicPrompts": False, "placeholder": "wildcard prompt"}),
|
||||
"controlnet_in_pipe": ("BOOLEAN", {"default": False, "label_on": "Keep", "label_off": "Override"}),
|
||||
"sigma_factor": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
|
||||
},
|
||||
"optional": {
|
||||
"variation_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
"variation_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
"variation_method": (["linear", "slerp"],),
|
||||
"scheduler_func_opt": ("SCHEDULER_FUNC",),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("REGIONAL_PROMPTS", )
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Regional"
|
||||
|
||||
@staticmethod
|
||||
def doit(basic_pipe, mask, cfg, sampler_name, scheduler, wildcard_prompt,
|
||||
controlnet_in_pipe=False, sigma_factor=1.0, variation_seed=0, variation_strength=0.0, variation_method='linear', scheduler_func_opt=None):
|
||||
if 'RegionalPrompt' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/ltdrdata/ComfyUI-Impact-Pack',
|
||||
"To use 'RegionalPromptSimple' node, 'Impact Pack' extension is required.")
|
||||
raise Exception("[ERROR] To use RegionalPromptSimple, you need to install 'ComfyUI-Impact-Pack'")
|
||||
|
||||
model, clip, vae, positive, negative = basic_pipe
|
||||
|
||||
iwe = nodes.NODE_CLASS_MAPPINGS['ImpactWildcardEncode']()
|
||||
kap = nodes.NODE_CLASS_MAPPINGS['KSamplerAdvancedProvider']()
|
||||
rp = nodes.NODE_CLASS_MAPPINGS['RegionalPrompt']()
|
||||
|
||||
if wildcard_prompt != "":
|
||||
model, clip, new_positive, _ = iwe.doit(model=model, clip=clip, populated_text=wildcard_prompt, seed=None)
|
||||
|
||||
if controlnet_in_pipe:
|
||||
prev_cnet = None
|
||||
for t in positive:
|
||||
if 'control' in t[1] and 'control_apply_to_uncond' in t[1]:
|
||||
prev_cnet = t[1]['control'], t[1]['control_apply_to_uncond']
|
||||
break
|
||||
|
||||
if prev_cnet is not None:
|
||||
for t in new_positive:
|
||||
t[1]['control'] = prev_cnet[0]
|
||||
t[1]['control_apply_to_uncond'] = prev_cnet[1]
|
||||
|
||||
else:
|
||||
new_positive = positive
|
||||
|
||||
basic_pipe = model, clip, vae, new_positive, negative
|
||||
|
||||
sampler = kap.doit(cfg, sampler_name, scheduler, basic_pipe, sigma_factor=sigma_factor, scheduler_func_opt=scheduler_func_opt)[0]
|
||||
try:
|
||||
regional_prompts = rp.doit(mask, sampler, variation_seed=variation_seed, variation_strength=variation_strength, variation_method=variation_method)[0]
|
||||
except:
|
||||
raise Exception("[Inspire-Pack] ERROR: Impact Pack is outdated. Update Impact Pack to latest version to use this.")
|
||||
|
||||
return (regional_prompts, )
|
||||
|
||||
|
||||
def color_to_mask(color_mask, mask_color):
|
||||
try:
|
||||
if mask_color.startswith("#") or mask_color.isalpha():
|
||||
hex = mask_color[1:] if mask_color.startswith("#") else webcolors.name_to_hex(mask_color)[1:]
|
||||
selected = int(hex, 16)
|
||||
else:
|
||||
selected = int(mask_color, 10)
|
||||
except Exception:
|
||||
raise Exception("[ERROR] Invalid mask_color value. mask_color should be a color value for RGB")
|
||||
|
||||
temp = (torch.clamp(color_mask, 0, 1.0) * 255.0).round().to(torch.int)
|
||||
temp = torch.bitwise_left_shift(temp[:, :, :, 0], 16) + torch.bitwise_left_shift(temp[:, :, :, 1], 8) + temp[:, :, :, 2]
|
||||
mask = torch.where(temp == selected, 1.0, 0.0)
|
||||
return mask
|
||||
|
||||
|
||||
class RegionalPromptColorMask:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"basic_pipe": ("BASIC_PIPE",),
|
||||
"color_mask": ("IMAGE",),
|
||||
"mask_color": ("STRING", {"multiline": False, "default": "#FFFFFF"}),
|
||||
"cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0}),
|
||||
"sampler_name": (comfy.samplers.KSampler.SAMPLERS,),
|
||||
"scheduler": (common.get_schedulers(),),
|
||||
"wildcard_prompt": ("STRING", {"multiline": True, "dynamicPrompts": False, "placeholder": "wildcard prompt"}),
|
||||
"controlnet_in_pipe": ("BOOLEAN", {"default": False, "label_on": "Keep", "label_off": "Override"}),
|
||||
"sigma_factor": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
|
||||
},
|
||||
"optional": {
|
||||
"variation_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
"variation_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
"variation_method": (["linear", "slerp"],),
|
||||
"scheduler_func_opt": ("SCHEDULER_FUNC",),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("REGIONAL_PROMPTS", "MASK")
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Regional"
|
||||
|
||||
@staticmethod
|
||||
def doit(basic_pipe, color_mask, mask_color, cfg, sampler_name, scheduler, wildcard_prompt,
|
||||
controlnet_in_pipe=False, sigma_factor=1.0, variation_seed=0, variation_strength=0.0, variation_method="linear", scheduler_func_opt=None):
|
||||
mask = color_to_mask(color_mask, mask_color)
|
||||
rp = RegionalPromptSimple().doit(basic_pipe, mask, cfg, sampler_name, scheduler, wildcard_prompt, controlnet_in_pipe,
|
||||
sigma_factor=sigma_factor, variation_seed=variation_seed, variation_strength=variation_strength, variation_method=variation_method, scheduler_func_opt=scheduler_func_opt)[0]
|
||||
return rp, mask
|
||||
|
||||
|
||||
class RegionalConditioningSimple:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"clip": ("CLIP", ),
|
||||
"mask": ("MASK",),
|
||||
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
|
||||
"set_cond_area": (["default", "mask bounds"],),
|
||||
"prompt": ("STRING", {"multiline": True, "placeholder": "prompt"}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("CONDITIONING", )
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Regional"
|
||||
|
||||
@staticmethod
|
||||
def doit(clip, mask, strength, set_cond_area, prompt):
|
||||
conditioning = nodes.CLIPTextEncode().encode(clip, prompt)[0]
|
||||
conditioning = nodes.ConditioningSetMask().append(conditioning, mask, set_cond_area, strength)[0]
|
||||
return (conditioning, )
|
||||
|
||||
|
||||
class RegionalConditioningColorMask:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"clip": ("CLIP", ),
|
||||
"color_mask": ("IMAGE",),
|
||||
"mask_color": ("STRING", {"multiline": False, "default": "#FFFFFF"}),
|
||||
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
|
||||
"set_cond_area": (["default", "mask bounds"],),
|
||||
"prompt": ("STRING", {"multiline": True, "placeholder": "prompt"}),
|
||||
},
|
||||
"optional": {
|
||||
"dilation": ("INT", {"default": 0, "min": -512, "max": 512, "step": 1}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("CONDITIONING", "MASK")
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Regional"
|
||||
|
||||
@staticmethod
|
||||
def doit(clip, color_mask, mask_color, strength, set_cond_area, prompt, dilation=0):
|
||||
mask = color_to_mask(color_mask, mask_color)
|
||||
|
||||
if dilation != 0:
|
||||
mask = utils.dilate_mask(mask, dilation)
|
||||
|
||||
conditioning = nodes.CLIPTextEncode().encode(clip, prompt)[0]
|
||||
conditioning = nodes.ConditioningSetMask().append(conditioning, mask, set_cond_area, strength)[0]
|
||||
return conditioning, mask
|
||||
|
||||
|
||||
class ToIPAdapterPipe:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"ipadapter": ("IPADAPTER", ),
|
||||
"model": ("MODEL",),
|
||||
},
|
||||
"optional": {
|
||||
"clip_vision": ("CLIP_VISION",),
|
||||
"insightface": ("INSIGHTFACE",),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IPADAPTER_PIPE",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Util"
|
||||
|
||||
@staticmethod
|
||||
def doit(ipadapter, model, clip_vision, insightface=None):
|
||||
pipe = ipadapter, model, clip_vision, insightface, lambda x: x
|
||||
|
||||
return (pipe,)
|
||||
|
||||
|
||||
class FromIPAdapterPipe:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"ipadapter_pipe": ("IPADAPTER_PIPE", ),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IPADAPTER", "MODEL", "CLIP_VISION", "INSIGHTFACE")
|
||||
RETURN_NAMES = ("ipadapter", "model", "clip_vision", "insight_face")
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Util"
|
||||
|
||||
def doit(self, ipadapter_pipe):
|
||||
ipadapter, model, clip_vision, insightface, _ = ipadapter_pipe
|
||||
return ipadapter, model, clip_vision, insightface
|
||||
|
||||
|
||||
class IPAdapterConditioning:
|
||||
def __init__(self, mask, weight, weight_type, noise=None, image=None, neg_image=None, embeds=None, start_at=0.0, end_at=1.0, combine_embeds='concat', unfold_batch=False, weight_v2=False, neg_embeds=None):
|
||||
self.mask = mask
|
||||
self.image = image
|
||||
self.neg_image = neg_image
|
||||
self.embeds = embeds
|
||||
self.neg_embeds = neg_embeds
|
||||
self.weight = weight
|
||||
self.noise = noise
|
||||
self.weight_type = weight_type
|
||||
self.start_at = start_at
|
||||
self.end_at = end_at
|
||||
self.unfold_batch = unfold_batch
|
||||
self.weight_v2 = weight_v2
|
||||
self.combine_embeds = combine_embeds
|
||||
|
||||
def doit(self, ipadapter_pipe):
|
||||
ipadapter, model, clip_vision, insightface, _ = ipadapter_pipe
|
||||
|
||||
if 'IPAdapterAdvanced' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/cubiq/ComfyUI_IPAdapter_plus',
|
||||
"To use 'Regional IPAdapter' node, 'ComfyUI IPAdapter Plus' extension is required.")
|
||||
raise Exception("[ERROR] To use IPAdapterModelHelper, you need to install 'ComfyUI IPAdapter Plus'")
|
||||
|
||||
if self.embeds is None:
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['IPAdapterAdvanced']
|
||||
model = obj().apply_ipadapter(model=model, ipadapter=ipadapter, weight=self.weight, weight_type=self.weight_type,
|
||||
start_at=self.start_at, end_at=self.end_at, combine_embeds=self.combine_embeds,
|
||||
clip_vision=clip_vision, image=self.image, image_negative=self.neg_image, attn_mask=self.mask,
|
||||
insightface=insightface, weight_faceidv2=self.weight_v2)[0]
|
||||
else:
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['IPAdapterEmbeds']
|
||||
model = obj().apply_ipadapter(model=model, ipadapter=ipadapter, pos_embed=self.embeds, weight=self.weight, weight_type=self.weight_type,
|
||||
start_at=self.start_at, end_at=self.end_at, neg_embed=self.neg_embeds,
|
||||
attn_mask=self.mask, clip_vision=clip_vision)[0]
|
||||
|
||||
return model
|
||||
|
||||
|
||||
IPADAPTER_WEIGHT_TYPES_CACHE = None
|
||||
|
||||
|
||||
def IPADAPTER_WEIGHT_TYPES():
|
||||
global IPADAPTER_WEIGHT_TYPES_CACHE
|
||||
|
||||
if IPADAPTER_WEIGHT_TYPES_CACHE is None:
|
||||
try:
|
||||
IPADAPTER_WEIGHT_TYPES_CACHE = nodes.NODE_CLASS_MAPPINGS['IPAdapterAdvanced']().INPUT_TYPES()['required']['weight_type'][0]
|
||||
except Exception:
|
||||
logging.error("[Inspire Pack] IPAdapterPlus is not installed.")
|
||||
IPADAPTER_WEIGHT_TYPES_CACHE = ["IPAdapterPlus is not installed"]
|
||||
|
||||
return IPADAPTER_WEIGHT_TYPES_CACHE
|
||||
|
||||
|
||||
class RegionalIPAdapterMask:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"mask": ("MASK",),
|
||||
|
||||
"image": ("IMAGE",),
|
||||
"weight": ("FLOAT", {"default": 0.7, "min": -1, "max": 3, "step": 0.05}),
|
||||
"noise": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
"weight_type": (IPADAPTER_WEIGHT_TYPES(), ),
|
||||
"start_at": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
|
||||
"end_at": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}),
|
||||
"unfold_batch": ("BOOLEAN", {"default": False}),
|
||||
},
|
||||
"optional": {
|
||||
"faceid_v2": ("BOOLEAN", {"default": False}),
|
||||
"weight_v2": ("FLOAT", {"default": 1.0, "min": -1, "max": 3, "step": 0.05}),
|
||||
"combine_embeds": (["concat", "add", "subtract", "average", "norm average"],),
|
||||
"neg_image": ("IMAGE",),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("REGIONAL_IPADAPTER", )
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Regional"
|
||||
|
||||
@staticmethod
|
||||
def doit(mask, image, weight, noise, weight_type, start_at=0.0, end_at=1.0, unfold_batch=False, faceid_v2=False, weight_v2=False, combine_embeds="concat", neg_image=None):
|
||||
cond = IPAdapterConditioning(mask, weight, weight_type, noise=noise, image=image, neg_image=neg_image, start_at=start_at, end_at=end_at, unfold_batch=unfold_batch, weight_v2=weight_v2, combine_embeds=combine_embeds)
|
||||
return (cond, )
|
||||
|
||||
|
||||
class RegionalIPAdapterColorMask:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"color_mask": ("IMAGE",),
|
||||
"mask_color": ("STRING", {"multiline": False, "default": "#FFFFFF"}),
|
||||
"image": ("IMAGE",),
|
||||
"weight": ("FLOAT", {"default": 0.7, "min": -1, "max": 3, "step": 0.05}),
|
||||
"noise": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
"weight_type": (IPADAPTER_WEIGHT_TYPES(), ),
|
||||
"start_at": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
|
||||
"end_at": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}),
|
||||
"unfold_batch": ("BOOLEAN", {"default": False}),
|
||||
},
|
||||
"optional": {
|
||||
"faceid_v2": ("BOOLEAN", {"default": False }),
|
||||
"weight_v2": ("FLOAT", {"default": 1.0, "min": -1, "max": 3, "step": 0.05}),
|
||||
"combine_embeds": (["concat", "add", "subtract", "average", "norm average"],),
|
||||
"neg_image": ("IMAGE",),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("REGIONAL_IPADAPTER", "MASK")
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Regional"
|
||||
|
||||
@staticmethod
|
||||
def doit(color_mask, mask_color, image, weight, noise, weight_type, start_at=0.0, end_at=1.0, unfold_batch=False, faceid_v2=False, weight_v2=False, combine_embeds="concat", neg_image=None):
|
||||
mask = color_to_mask(color_mask, mask_color)
|
||||
cond = IPAdapterConditioning(mask, weight, weight_type, noise=noise, image=image, neg_image=neg_image, start_at=start_at, end_at=end_at, unfold_batch=unfold_batch, weight_v2=weight_v2, combine_embeds=combine_embeds)
|
||||
return (cond, mask)
|
||||
|
||||
|
||||
class RegionalIPAdapterEncodedMask:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"mask": ("MASK",),
|
||||
|
||||
"embeds": ("EMBEDS",),
|
||||
"weight": ("FLOAT", {"default": 0.7, "min": -1, "max": 3, "step": 0.05}),
|
||||
"weight_type": (IPADAPTER_WEIGHT_TYPES(), ),
|
||||
"start_at": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
|
||||
"end_at": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}),
|
||||
"unfold_batch": ("BOOLEAN", {"default": False}),
|
||||
},
|
||||
"optional": {
|
||||
"neg_embeds": ("EMBEDS",),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("REGIONAL_IPADAPTER", )
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Regional"
|
||||
|
||||
@staticmethod
|
||||
def doit(mask, embeds, weight, weight_type, start_at=0.0, end_at=1.0, unfold_batch=False, neg_embeds=None):
|
||||
cond = IPAdapterConditioning(mask, weight, weight_type, embeds=embeds, start_at=start_at, end_at=end_at, unfold_batch=unfold_batch, neg_embeds=neg_embeds)
|
||||
return (cond, )
|
||||
|
||||
|
||||
class RegionalIPAdapterEncodedColorMask:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"color_mask": ("IMAGE",),
|
||||
"mask_color": ("STRING", {"multiline": False, "default": "#FFFFFF"}),
|
||||
|
||||
"embeds": ("EMBEDS",),
|
||||
"weight": ("FLOAT", {"default": 0.7, "min": -1, "max": 3, "step": 0.05}),
|
||||
"weight_type": (IPADAPTER_WEIGHT_TYPES(), ),
|
||||
"start_at": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
|
||||
"end_at": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}),
|
||||
"unfold_batch": ("BOOLEAN", {"default": False}),
|
||||
},
|
||||
"optional": {
|
||||
"neg_embeds": ("EMBEDS",),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("REGIONAL_IPADAPTER", "MASK")
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Regional"
|
||||
|
||||
@staticmethod
|
||||
def doit(color_mask, mask_color, embeds, weight, weight_type, start_at=0.0, end_at=1.0, unfold_batch=False, neg_embeds=None):
|
||||
mask = color_to_mask(color_mask, mask_color)
|
||||
cond = IPAdapterConditioning(mask, weight, weight_type, embeds=embeds, start_at=start_at, end_at=end_at, unfold_batch=unfold_batch, neg_embeds=neg_embeds)
|
||||
return (cond, mask)
|
||||
|
||||
|
||||
class ApplyRegionalIPAdapters:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"ipadapter_pipe": ("IPADAPTER_PIPE",),
|
||||
"regional_ipadapter1": ("REGIONAL_IPADAPTER", ),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL", )
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Regional"
|
||||
|
||||
@staticmethod
|
||||
def doit(**kwargs):
|
||||
ipadapter_pipe = kwargs['ipadapter_pipe']
|
||||
ipadapter, model, clip_vision, insightface, lora_loader = ipadapter_pipe
|
||||
|
||||
del kwargs['ipadapter_pipe']
|
||||
|
||||
for k, v in kwargs.items():
|
||||
ipadapter_pipe = ipadapter, model, clip_vision, insightface, lora_loader
|
||||
model = v.doit(ipadapter_pipe)
|
||||
|
||||
return (model, )
|
||||
|
||||
|
||||
class RegionalSeedExplorerMask:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"mask": ("MASK",),
|
||||
|
||||
"noise": ("NOISE_IMAGE",),
|
||||
"seed_prompt": ("STRING", {"multiline": True, "dynamicPrompts": False, "pysssss.autocomplete": False}),
|
||||
"enable_additional": ("BOOLEAN", {"default": True, "label_on": "true", "label_off": "false"}),
|
||||
"additional_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
"additional_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
"noise_mode": (["GPU(=A1111)", "CPU"],),
|
||||
},
|
||||
"optional":
|
||||
{"variation_method": (["linear", "slerp"],), }
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("NOISE_IMAGE",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Regional"
|
||||
|
||||
@staticmethod
|
||||
def doit(mask, noise, seed_prompt, enable_additional, additional_seed, additional_strength, noise_mode, variation_method='linear'):
|
||||
device = comfy.model_management.get_torch_device()
|
||||
noise_device = "cpu" if noise_mode == "CPU" else device
|
||||
|
||||
noise = noise.to(device)
|
||||
mask = mask.to(device)
|
||||
|
||||
if len(mask.shape) == 2:
|
||||
mask = mask.unsqueeze(0)
|
||||
|
||||
mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(noise.shape[2], noise.shape[3]), mode="bilinear").squeeze(0)
|
||||
|
||||
try:
|
||||
seed_prompt = seed_prompt.replace("\n", "")
|
||||
items = seed_prompt.strip().split(",")
|
||||
|
||||
if items == ['']:
|
||||
items = []
|
||||
|
||||
if enable_additional:
|
||||
items.append((additional_seed, additional_strength))
|
||||
|
||||
noise = prompt_support.SeedExplorer.apply_variation(noise, items, noise_device, mask, variation_method=variation_method)
|
||||
except Exception:
|
||||
logging.error("[Inspire Pack] IGNORED: RegionalSeedExplorerColorMask is failed.")
|
||||
traceback.print_exc()
|
||||
|
||||
noise = noise.cpu()
|
||||
mask.cpu()
|
||||
return (noise,)
|
||||
|
||||
|
||||
class RegionalSeedExplorerColorMask:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"color_mask": ("IMAGE",),
|
||||
"mask_color": ("STRING", {"multiline": False, "default": "#FFFFFF"}),
|
||||
|
||||
"noise": ("NOISE_IMAGE",),
|
||||
"seed_prompt": ("STRING", {"multiline": True, "dynamicPrompts": False, "pysssss.autocomplete": False}),
|
||||
"enable_additional": ("BOOLEAN", {"default": True, "label_on": "true", "label_off": "false"}),
|
||||
"additional_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
"additional_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
"noise_mode": (["GPU(=A1111)", "CPU"],),
|
||||
},
|
||||
"optional":
|
||||
{"variation_method": (["linear", "slerp"],), }
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("NOISE_IMAGE", "MASK")
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Regional"
|
||||
|
||||
@staticmethod
|
||||
def doit(color_mask, mask_color, noise, seed_prompt, enable_additional, additional_seed, additional_strength, noise_mode, variation_method='linear'):
|
||||
device = comfy.model_management.get_torch_device()
|
||||
noise_device = "cpu" if noise_mode == "CPU" else device
|
||||
|
||||
color_mask = color_mask.to(device)
|
||||
noise = noise.to(device)
|
||||
|
||||
mask = color_to_mask(color_mask, mask_color)
|
||||
original_mask = mask
|
||||
mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(noise.shape[2], noise.shape[3]), mode="bilinear").squeeze(0)
|
||||
|
||||
mask = mask.to(device)
|
||||
|
||||
try:
|
||||
seed_prompt = seed_prompt.replace("\n", "")
|
||||
items = seed_prompt.strip().split(",")
|
||||
|
||||
if items == ['']:
|
||||
items = []
|
||||
|
||||
if enable_additional:
|
||||
items.append((additional_seed, additional_strength))
|
||||
|
||||
noise = prompt_support.SeedExplorer.apply_variation(noise, items, noise_device, mask, variation_method=variation_method)
|
||||
except Exception:
|
||||
logging.error("[Inspire Pack] IGNORED: RegionalSeedExplorerColorMask is failed.")
|
||||
traceback.print_exc()
|
||||
|
||||
color_mask.cpu()
|
||||
noise = noise.cpu()
|
||||
original_mask = original_mask.cpu()
|
||||
return (noise, original_mask)
|
||||
|
||||
|
||||
class ColorMaskToDepthMask:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"color_mask": ("IMAGE",),
|
||||
"spec": ("STRING", {"multiline": True, "default": "#FF0000:1.0\n#000000:1.0"}),
|
||||
"base_value": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0}),
|
||||
"dilation": ("INT", {"default": 0, "min": -512, "max": 512, "step": 1}),
|
||||
"flatten_method": (["override", "sum", "max"],),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MASK", )
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Regional"
|
||||
|
||||
def doit(self, color_mask, spec, base_value, dilation, flatten_method):
|
||||
specs = spec.split('\n')
|
||||
pat = re.compile("(?P<color_code>#[A-F0-9]+):(?P<cfg>[0-9]+(.[0-9]*)?)")
|
||||
|
||||
masks = [torch.ones((1, color_mask.shape[1], color_mask.shape[2])) * base_value]
|
||||
for x in specs:
|
||||
match = pat.match(x)
|
||||
if match:
|
||||
mask = color_to_mask(color_mask=color_mask, mask_color=match['color_code']) * float(match['cfg'])
|
||||
mask = utils.dilate_mask(mask, dilation)
|
||||
masks.append(mask)
|
||||
|
||||
if masks:
|
||||
masks = torch.cat(masks, dim=0)
|
||||
if flatten_method == 'override':
|
||||
masks = utils.flatten_non_zero_override(masks)
|
||||
elif flatten_method == 'max':
|
||||
masks = torch.max(masks, dim=0)[0]
|
||||
else: # flatten_method == 'sum':
|
||||
masks = torch.sum(masks, dim=0)
|
||||
|
||||
masks = torch.clamp(masks, min=0.0, max=1.0)
|
||||
masks = masks.unsqueeze(0)
|
||||
else:
|
||||
masks = torch.tensor([])
|
||||
|
||||
return (masks, )
|
||||
|
||||
|
||||
class RegionalCFG:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {"model": ("MODEL",),
|
||||
"mask": ("MASK",),
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Regional"
|
||||
|
||||
@staticmethod
|
||||
def doit(model, mask):
|
||||
if len(mask.shape) == 2:
|
||||
mask = mask.unsqueeze(0).unsqueeze(0)
|
||||
elif len(mask.shape) == 3:
|
||||
mask = mask.unsqueeze(0)
|
||||
|
||||
size = None
|
||||
|
||||
def regional_cfg(args):
|
||||
nonlocal mask
|
||||
nonlocal size
|
||||
|
||||
x = args['input']
|
||||
|
||||
if mask.device != x.device:
|
||||
mask = mask.to(x.device)
|
||||
|
||||
if size != (x.shape[2], x.shape[3]):
|
||||
size = (x.shape[2], x.shape[3])
|
||||
mask = torch.nn.functional.interpolate(mask, size=size, mode='bilinear', align_corners=False)
|
||||
|
||||
cond_pred = args["cond_denoised"]
|
||||
uncond_pred = args["uncond_denoised"]
|
||||
cond_scale = args["cond_scale"]
|
||||
|
||||
cfg_result = uncond_pred + (cond_pred - uncond_pred) * cond_scale * mask
|
||||
|
||||
return x - cfg_result
|
||||
|
||||
m = model.clone()
|
||||
m.set_model_sampler_cfg_function(regional_cfg)
|
||||
return (m,)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"RegionalPromptSimple //Inspire": RegionalPromptSimple,
|
||||
"RegionalPromptColorMask //Inspire": RegionalPromptColorMask,
|
||||
"RegionalConditioningSimple //Inspire": RegionalConditioningSimple,
|
||||
"RegionalConditioningColorMask //Inspire": RegionalConditioningColorMask,
|
||||
"RegionalIPAdapterMask //Inspire": RegionalIPAdapterMask,
|
||||
"RegionalIPAdapterColorMask //Inspire": RegionalIPAdapterColorMask,
|
||||
"RegionalIPAdapterEncodedMask //Inspire": RegionalIPAdapterEncodedMask,
|
||||
"RegionalIPAdapterEncodedColorMask //Inspire": RegionalIPAdapterEncodedColorMask,
|
||||
"RegionalSeedExplorerMask //Inspire": RegionalSeedExplorerMask,
|
||||
"RegionalSeedExplorerColorMask //Inspire": RegionalSeedExplorerColorMask,
|
||||
"ToIPAdapterPipe //Inspire": ToIPAdapterPipe,
|
||||
"FromIPAdapterPipe //Inspire": FromIPAdapterPipe,
|
||||
"ApplyRegionalIPAdapters //Inspire": ApplyRegionalIPAdapters,
|
||||
"RegionalCFG //Inspire": RegionalCFG,
|
||||
"ColorMaskToDepthMask //Inspire": ColorMaskToDepthMask,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"RegionalPromptSimple //Inspire": "Regional Prompt Simple (Inspire)",
|
||||
"RegionalPromptColorMask //Inspire": "Regional Prompt By Color Mask (Inspire)",
|
||||
"RegionalConditioningSimple //Inspire": "Regional Conditioning Simple (Inspire)",
|
||||
"RegionalConditioningColorMask //Inspire": "Regional Conditioning By Color Mask (Inspire)",
|
||||
"RegionalIPAdapterMask //Inspire": "Regional IPAdapter Mask (Inspire)",
|
||||
"RegionalIPAdapterColorMask //Inspire": "Regional IPAdapter By Color Mask (Inspire)",
|
||||
"RegionalIPAdapterEncodedMask //Inspire": "Regional IPAdapter Encoded Mask (Inspire)",
|
||||
"RegionalIPAdapterEncodedColorMask //Inspire": "Regional IPAdapter Encoded By Color Mask (Inspire)",
|
||||
"RegionalSeedExplorerMask //Inspire": "Regional Seed Explorer By Mask (Inspire)",
|
||||
"RegionalSeedExplorerColorMask //Inspire": "Regional Seed Explorer By Color Mask (Inspire)",
|
||||
"ToIPAdapterPipe //Inspire": "ToIPAdapterPipe (Inspire)",
|
||||
"FromIPAdapterPipe //Inspire": "FromIPAdapterPipe (Inspire)",
|
||||
"ApplyRegionalIPAdapters //Inspire": "Apply Regional IPAdapters (Inspire)",
|
||||
"RegionalCFG //Inspire": "Regional CFG (Inspire)",
|
||||
"ColorMaskToDepthMask //Inspire": "Color Mask To Depth Mask (Inspire)",
|
||||
}
|
||||
353
custom_nodes/comfyui-inspire-pack/inspire/sampler_nodes.py
Normal file
353
custom_nodes/comfyui-inspire-pack/inspire/sampler_nodes.py
Normal file
@@ -0,0 +1,353 @@
|
||||
import torch
|
||||
from . import a1111_compat
|
||||
import comfy
|
||||
from .libs import common
|
||||
from comfy.samplers import CFGGuider
|
||||
from comfy_extras.nodes_perpneg import Guider_PerpNeg
|
||||
import math
|
||||
|
||||
|
||||
class KSampler_progress(a1111_compat.KSampler_inspire):
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"model": ("MODEL",),
|
||||
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
"steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
|
||||
"cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0}),
|
||||
"sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
|
||||
"scheduler": (common.get_schedulers(), ),
|
||||
"positive": ("CONDITIONING", ),
|
||||
"negative": ("CONDITIONING", ),
|
||||
"latent_image": ("LATENT", ),
|
||||
"denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
||||
"noise_mode": (a1111_compat.supported_noise_modes,),
|
||||
"interval": ("INT", {"default": 1, "min": 1, "max": 10000}),
|
||||
"omit_start_latent": ("BOOLEAN", {"default": True, "label_on": "True", "label_off": "False"}),
|
||||
"omit_final_latent": ("BOOLEAN", {"default": False, "label_on": "True", "label_off": "False"}),
|
||||
},
|
||||
"optional": {
|
||||
"scheduler_func_opt": ("SCHEDULER_FUNC",),
|
||||
}
|
||||
}
|
||||
|
||||
CATEGORY = "InspirePack/analysis"
|
||||
|
||||
RETURN_TYPES = ("LATENT", "LATENT")
|
||||
RETURN_NAMES = ("latent", "progress_latent")
|
||||
|
||||
@staticmethod
|
||||
def doit(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise, noise_mode,
|
||||
interval, omit_start_latent, omit_final_latent, scheduler_func_opt=None):
|
||||
adv_steps = int(steps / denoise)
|
||||
|
||||
if omit_start_latent:
|
||||
result = []
|
||||
else:
|
||||
result = [comfy.sample.fix_empty_latent_channels(model, latent_image['samples']).cpu()]
|
||||
|
||||
def progress_callback(step, x0, x, total_steps):
|
||||
if (total_steps-1) != step and step % interval != 0:
|
||||
return
|
||||
|
||||
x = model.model.process_latent_out(x)
|
||||
x = x.cpu()
|
||||
result.append(x)
|
||||
|
||||
latent_image, noise = a1111_compat.KSamplerAdvanced_inspire.sample(model, True, seed, adv_steps, cfg, sampler_name, scheduler, positive, negative, latent_image, (adv_steps-steps),
|
||||
adv_steps, noise_mode, False, callback=progress_callback, scheduler_func_opt=scheduler_func_opt)
|
||||
|
||||
if not omit_final_latent:
|
||||
result.append(latent_image['samples'].cpu())
|
||||
|
||||
if len(result) > 0:
|
||||
result = torch.cat(result)
|
||||
result = {'samples': result}
|
||||
else:
|
||||
result = latent_image
|
||||
|
||||
return latent_image, result
|
||||
|
||||
|
||||
class KSamplerAdvanced_progress(a1111_compat.KSamplerAdvanced_inspire):
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"model": ("MODEL",),
|
||||
"add_noise": ("BOOLEAN", {"default": True, "label_on": "enable", "label_off": "disable"}),
|
||||
"noise_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
"steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
|
||||
"cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.5, "round": 0.01}),
|
||||
"sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
|
||||
"scheduler": (common.get_schedulers(), ),
|
||||
"positive": ("CONDITIONING", ),
|
||||
"negative": ("CONDITIONING", ),
|
||||
"latent_image": ("LATENT", ),
|
||||
"start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000}),
|
||||
"end_at_step": ("INT", {"default": 10000, "min": 0, "max": 10000}),
|
||||
"noise_mode": (a1111_compat.supported_noise_modes,),
|
||||
"return_with_leftover_noise": ("BOOLEAN", {"default": False, "label_on": "enable", "label_off": "disable"}),
|
||||
"interval": ("INT", {"default": 1, "min": 1, "max": 10000}),
|
||||
"omit_start_latent": ("BOOLEAN", {"default": False, "label_on": "True", "label_off": "False"}),
|
||||
"omit_final_latent": ("BOOLEAN", {"default": False, "label_on": "True", "label_off": "False"}),
|
||||
},
|
||||
"optional": {
|
||||
"prev_progress_latent_opt": ("LATENT",),
|
||||
"scheduler_func_opt": ("SCHEDULER_FUNC",),
|
||||
}
|
||||
}
|
||||
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/analysis"
|
||||
|
||||
RETURN_TYPES = ("LATENT", "LATENT")
|
||||
RETURN_NAMES = ("latent", "progress_latent")
|
||||
|
||||
def doit(self, model, add_noise, noise_seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image,
|
||||
start_at_step, end_at_step, noise_mode, return_with_leftover_noise, interval, omit_start_latent, omit_final_latent,
|
||||
prev_progress_latent_opt=None, scheduler_func_opt=None):
|
||||
|
||||
if omit_start_latent:
|
||||
result = []
|
||||
else:
|
||||
result = [latent_image['samples']]
|
||||
|
||||
def progress_callback(step, x0, x, total_steps):
|
||||
if (total_steps-1) != step and step % interval != 0:
|
||||
return
|
||||
|
||||
x = model.model.process_latent_out(x)
|
||||
x = x.cpu()
|
||||
result.append(x)
|
||||
|
||||
latent_image, noise = a1111_compat.KSamplerAdvanced_inspire.sample(model, add_noise, noise_seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, start_at_step, end_at_step,
|
||||
noise_mode, return_with_leftover_noise, callback=progress_callback, scheduler_func_opt=scheduler_func_opt)
|
||||
|
||||
if not omit_final_latent:
|
||||
result.append(latent_image['samples'].cpu())
|
||||
|
||||
if len(result) > 0:
|
||||
result = torch.cat(result)
|
||||
result = {'samples': result}
|
||||
else:
|
||||
result = latent_image
|
||||
|
||||
if prev_progress_latent_opt is not None:
|
||||
result['samples'] = torch.cat((prev_progress_latent_opt['samples'], result['samples']), dim=0)
|
||||
|
||||
return latent_image, result
|
||||
|
||||
|
||||
def exponential_interpolation(from_cfg, to_cfg, i, steps):
|
||||
if i == steps-1:
|
||||
return to_cfg
|
||||
|
||||
if from_cfg == to_cfg:
|
||||
return from_cfg
|
||||
|
||||
if from_cfg == 0:
|
||||
return to_cfg * (1 - math.exp(-5 * i / steps)) / (1 - math.exp(-5))
|
||||
elif to_cfg == 0:
|
||||
return from_cfg * (math.exp(-5 * i / steps) - math.exp(-5)) / (1 - math.exp(-5))
|
||||
else:
|
||||
log_from = math.log(from_cfg)
|
||||
log_to = math.log(to_cfg)
|
||||
log_value = log_from + (log_to - log_from) * i / steps
|
||||
return math.exp(log_value)
|
||||
|
||||
|
||||
def logarithmic_interpolation(from_cfg, to_cfg, i, steps):
|
||||
if i == 0:
|
||||
return from_cfg
|
||||
|
||||
if i == steps-1:
|
||||
return to_cfg
|
||||
|
||||
log_i = math.log(i + 1)
|
||||
log_steps = math.log(steps + 1)
|
||||
|
||||
t = log_i / log_steps
|
||||
|
||||
return from_cfg + (to_cfg - from_cfg) * t
|
||||
|
||||
|
||||
def cosine_interpolation(from_cfg, to_cfg, i, steps):
|
||||
if (i == 0) or (i == steps-1):
|
||||
return from_cfg
|
||||
|
||||
t = (1.0 + math.cos(math.pi*2*(i/steps))) / 2
|
||||
|
||||
return from_cfg + (to_cfg - from_cfg) * t
|
||||
|
||||
|
||||
class Guider_scheduled(CFGGuider):
|
||||
def __init__(self, model_patcher, sigmas, from_cfg, to_cfg, schedule):
|
||||
super().__init__(model_patcher)
|
||||
self.default_cfg = self.cfg
|
||||
self.sigmas = sigmas
|
||||
self.cfg_sigmas = None
|
||||
self.cfg_sigmas_i = None
|
||||
self.from_cfg = from_cfg
|
||||
self.to_cfg = to_cfg
|
||||
self.schedule = schedule
|
||||
self.last_i = 0
|
||||
self.renew_cfg_sigmas()
|
||||
|
||||
def set_cfg(self, cfg):
|
||||
self.default_cfg = cfg
|
||||
self.renew_cfg_sigmas()
|
||||
|
||||
def renew_cfg_sigmas(self):
|
||||
self.cfg_sigmas = {}
|
||||
self.cfg_sigmas_i = {}
|
||||
i = 0
|
||||
steps = len(self.sigmas) - 1
|
||||
for x in self.sigmas:
|
||||
k = float(x)
|
||||
delta = self.to_cfg - self.from_cfg
|
||||
if self.schedule == 'exp':
|
||||
self.cfg_sigmas[k] = exponential_interpolation(self.from_cfg, self.to_cfg, i, steps), i
|
||||
elif self.schedule == 'log':
|
||||
self.cfg_sigmas[k] = logarithmic_interpolation(self.from_cfg, self.to_cfg, i, steps), i
|
||||
elif self.schedule == 'cos':
|
||||
self.cfg_sigmas[k] = cosine_interpolation(self.from_cfg, self.to_cfg, i, steps), i
|
||||
else:
|
||||
self.cfg_sigmas[k] = self.from_cfg + delta * i / steps, i
|
||||
|
||||
self.cfg_sigmas_i[i] = self.cfg_sigmas[k]
|
||||
i += 1
|
||||
|
||||
def predict_noise(self, x, timestep, model_options={}, seed=None):
|
||||
k = float(timestep[0])
|
||||
|
||||
v = self.cfg_sigmas.get(k)
|
||||
if v is None:
|
||||
# fallback
|
||||
v = self.cfg_sigmas_i[self.last_i+1]
|
||||
self.cfg_sigmas[k] = v
|
||||
|
||||
self.last_i = v[1]
|
||||
self.cfg = v[0]
|
||||
|
||||
return super().predict_noise(x, timestep, model_options, seed)
|
||||
|
||||
|
||||
class Guider_PerpNeg_scheduled(Guider_PerpNeg):
|
||||
def __init__(self, model_patcher, sigmas, from_cfg, to_cfg, schedule, neg_scale):
|
||||
super().__init__(model_patcher)
|
||||
self.default_cfg = self.cfg
|
||||
self.sigmas = sigmas
|
||||
self.cfg_sigmas = None
|
||||
self.cfg_sigmas_i = None
|
||||
self.from_cfg = from_cfg
|
||||
self.to_cfg = to_cfg
|
||||
self.schedule = schedule
|
||||
self.neg_scale = neg_scale
|
||||
self.last_i = 0
|
||||
self.renew_cfg_sigmas()
|
||||
|
||||
def set_cfg(self, cfg):
|
||||
self.default_cfg = cfg
|
||||
self.renew_cfg_sigmas()
|
||||
|
||||
def renew_cfg_sigmas(self):
|
||||
self.cfg_sigmas = {}
|
||||
self.cfg_sigmas_i = {}
|
||||
i = 0
|
||||
steps = len(self.sigmas) - 1
|
||||
for x in self.sigmas:
|
||||
k = float(x)
|
||||
delta = self.to_cfg - self.from_cfg
|
||||
if self.schedule == 'exp':
|
||||
self.cfg_sigmas[k] = exponential_interpolation(self.from_cfg, self.to_cfg, i, steps), i
|
||||
elif self.schedule == 'log':
|
||||
self.cfg_sigmas[k] = logarithmic_interpolation(self.from_cfg, self.to_cfg, i, steps), i
|
||||
elif self.schedule == 'cos':
|
||||
self.cfg_sigmas[k] = cosine_interpolation(self.from_cfg, self.to_cfg, i, steps), i
|
||||
else:
|
||||
self.cfg_sigmas[k] = self.from_cfg + delta * i / steps, i
|
||||
|
||||
self.cfg_sigmas_i[i] = self.cfg_sigmas[k]
|
||||
i += 1
|
||||
|
||||
def predict_noise(self, x, timestep, model_options={}, seed=None):
|
||||
k = float(timestep[0])
|
||||
|
||||
v = self.cfg_sigmas.get(k)
|
||||
if v is None:
|
||||
# fallback
|
||||
v = self.cfg_sigmas_i[self.last_i+1]
|
||||
self.cfg_sigmas[k] = v
|
||||
|
||||
self.last_i = v[1]
|
||||
self.cfg = v[0]
|
||||
|
||||
return super().predict_noise(x, timestep, model_options, seed)
|
||||
|
||||
|
||||
class ScheduledCFGGuider:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"model": ("MODEL", ),
|
||||
"positive": ("CONDITIONING", ),
|
||||
"negative": ("CONDITIONING", ),
|
||||
"sigmas": ("SIGMAS", ),
|
||||
"from_cfg": ("FLOAT", {"default": 6.5, "min": 0.0, "max": 100.0, "step": 0.1, "round": 0.01}),
|
||||
"to_cfg": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step": 0.1, "round": 0.01}),
|
||||
"schedule": (["linear", "log", "exp", "cos"], {'default': 'log'})
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("GUIDER", "SIGMAS")
|
||||
|
||||
FUNCTION = "get_guider"
|
||||
CATEGORY = "sampling/custom_sampling/guiders"
|
||||
|
||||
def get_guider(self, model, positive, negative, sigmas, from_cfg, to_cfg, schedule):
|
||||
guider = Guider_scheduled(model, sigmas, from_cfg, to_cfg, schedule)
|
||||
guider.set_conds(positive, negative)
|
||||
return guider, sigmas
|
||||
|
||||
|
||||
class ScheduledPerpNegCFGGuider:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"model": ("MODEL", ),
|
||||
"positive": ("CONDITIONING", ),
|
||||
"negative": ("CONDITIONING", ),
|
||||
"empty_conditioning": ("CONDITIONING", ),
|
||||
"neg_scale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step": 0.01}),
|
||||
"sigmas": ("SIGMAS", ),
|
||||
"from_cfg": ("FLOAT", {"default": 6.5, "min": 0.0, "max": 100.0, "step": 0.1, "round": 0.01}),
|
||||
"to_cfg": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 100.0, "step": 0.1, "round": 0.01}),
|
||||
"schedule": (["linear", "log", "exp", "cos"], {'default': 'log'})
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("GUIDER", "SIGMAS")
|
||||
|
||||
FUNCTION = "get_guider"
|
||||
CATEGORY = "sampling/custom_sampling/guiders"
|
||||
|
||||
def get_guider(self, model, positive, negative, empty_conditioning, neg_scale, sigmas, from_cfg, to_cfg, schedule):
|
||||
guider = Guider_PerpNeg_scheduled(model, sigmas, from_cfg, to_cfg, schedule, neg_scale)
|
||||
guider.set_conds(positive, negative, empty_conditioning)
|
||||
return guider, sigmas
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"KSamplerProgress //Inspire": KSampler_progress,
|
||||
"KSamplerAdvancedProgress //Inspire": KSamplerAdvanced_progress,
|
||||
"ScheduledCFGGuider //Inspire": ScheduledCFGGuider,
|
||||
"ScheduledPerpNegCFGGuider //Inspire": ScheduledPerpNegCFGGuider
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"KSamplerProgress //Inspire": "KSampler Progress (Inspire)",
|
||||
"KSamplerAdvancedProgress //Inspire": "KSampler Advanced Progress (Inspire)",
|
||||
"ScheduledCFGGuider //Inspire": "Scheduled CFGGuider (Inspire)",
|
||||
"ScheduledPerpNegCFGGuider //Inspire": "Scheduled PerpNeg CFGGuider (Inspire)"
|
||||
}
|
||||
648
custom_nodes/comfyui-inspire-pack/inspire/segs_support.py
Normal file
648
custom_nodes/comfyui-inspire-pack/inspire/segs_support.py
Normal file
@@ -0,0 +1,648 @@
|
||||
import nodes
|
||||
import numpy as np
|
||||
import torch
|
||||
from .libs import utils
|
||||
import logging
|
||||
|
||||
def normalize_size_base_64(w, h):
|
||||
short_side = min(w, h)
|
||||
remainder = short_side % 64
|
||||
return short_side - remainder + (64 if remainder > 0 else 0)
|
||||
|
||||
|
||||
class MediaPipeFaceMeshDetector:
|
||||
def __init__(self, face, mouth, left_eyebrow, left_eye, left_pupil, right_eyebrow, right_eye, right_pupil, max_faces, is_segm):
|
||||
self.face = face
|
||||
self.mouth = mouth
|
||||
self.left_eyebrow = left_eyebrow
|
||||
self.left_eye = left_eye
|
||||
self.left_pupil = left_pupil
|
||||
self.right_eyebrow = right_eyebrow
|
||||
self.right_eye = right_eye
|
||||
self.right_pupil = right_pupil
|
||||
self.is_segm = is_segm
|
||||
self.max_faces = max_faces
|
||||
self.override_bbox_by_segm = True
|
||||
|
||||
def detect(self, image, threshold, dilation, crop_factor, drop_size=1, crop_min_size=None, detailer_hook=None):
|
||||
if 'MediaPipe-FaceMeshPreprocessor' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/Fannovel16/comfyui_controlnet_aux',
|
||||
"To use 'MediaPipeFaceMeshDetector' node, 'ComfyUI's ControlNet Auxiliary Preprocessors.' extension is required.")
|
||||
raise Exception("[ERROR] To use MediaPipeFaceMeshDetector, you need to install 'ComfyUI's ControlNet Auxiliary Preprocessors.'")
|
||||
|
||||
if 'MediaPipeFaceMeshToSEGS' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/ltdrdata/ComfyUI-Impact-Pack',
|
||||
"To use 'MediaPipeFaceMeshDetector' node, 'Impact Pack' extension is required.")
|
||||
raise Exception("[ERROR] To use MediaPipeFaceMeshDetector, you need to install 'ComfyUI-Impact-Pack'")
|
||||
|
||||
pre_obj = nodes.NODE_CLASS_MAPPINGS['MediaPipe-FaceMeshPreprocessor']
|
||||
seg_obj = nodes.NODE_CLASS_MAPPINGS['MediaPipeFaceMeshToSEGS']
|
||||
|
||||
resolution = normalize_size_base_64(image.shape[2], image.shape[1])
|
||||
facemesh_image = pre_obj().detect(image, self.max_faces, threshold, resolution=resolution)[0]
|
||||
|
||||
facemesh_image = nodes.ImageScale().upscale(facemesh_image, "bilinear", image.shape[2], image.shape[1], "disabled")[0]
|
||||
|
||||
segs = seg_obj().doit(facemesh_image, crop_factor, not self.is_segm, crop_min_size, drop_size, dilation,
|
||||
self.face, self.mouth, self.left_eyebrow, self.left_eye, self.left_pupil,
|
||||
self.right_eyebrow, self.right_eye, self.right_pupil)[0]
|
||||
|
||||
return segs
|
||||
|
||||
def setAux(self, x):
|
||||
pass
|
||||
|
||||
|
||||
class MediaPipe_FaceMesh_Preprocessor_wrapper:
|
||||
def __init__(self, max_faces, min_confidence, upscale_factor=1.0):
|
||||
self.max_faces = max_faces
|
||||
self.min_confidence = min_confidence
|
||||
self.upscale_factor = upscale_factor
|
||||
|
||||
def apply(self, image, mask=None):
|
||||
if 'MediaPipe-FaceMeshPreprocessor' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/Fannovel16/comfyui_controlnet_aux',
|
||||
"To use 'MediaPipe_FaceMesh_Preprocessor_Provider_for_SEGS' node, 'ComfyUI's ControlNet Auxiliary Preprocessors.' extension is required.")
|
||||
raise Exception("[ERROR] To use MediaPipe_FaceMesh_Preprocessor_Provider_for_SEGS, you need to install 'ComfyUI's ControlNet Auxiliary Preprocessors.'")
|
||||
|
||||
if self.upscale_factor != 1.0:
|
||||
image = nodes.ImageScaleBy().upscale(image, 'bilinear', self.upscale_factor)[0]
|
||||
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['MediaPipe-FaceMeshPreprocessor']()
|
||||
resolution = normalize_size_base_64(image.shape[2], image.shape[1])
|
||||
return obj.detect(image, self.max_faces, self.min_confidence, resolution=resolution)[0]
|
||||
|
||||
|
||||
class AnimeLineArt_Preprocessor_wrapper:
|
||||
def apply(self, image, mask=None):
|
||||
if 'AnimeLineArtPreprocessor' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/Fannovel16/comfyui_controlnet_aux',
|
||||
"To use 'AnimeLineArt_Preprocessor_Provider' node, 'ComfyUI's ControlNet Auxiliary Preprocessors.' extension is required.")
|
||||
raise Exception("[ERROR] To use AnimeLineArt_Preprocessor_Provider, you need to install 'ComfyUI's ControlNet Auxiliary Preprocessors.'")
|
||||
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['AnimeLineArtPreprocessor']()
|
||||
resolution = normalize_size_base_64(image.shape[2], image.shape[1])
|
||||
return obj.execute(image, resolution=resolution)[0]
|
||||
|
||||
|
||||
class Manga2Anime_LineArt_Preprocessor_wrapper:
|
||||
def apply(self, image, mask=None):
|
||||
if 'Manga2Anime_LineArt_Preprocessor' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/Fannovel16/comfyui_controlnet_aux',
|
||||
"To use 'Manga2Anime_LineArt_Preprocessor_Provider' node, 'ComfyUI's ControlNet Auxiliary Preprocessors.' extension is required.")
|
||||
raise Exception("[ERROR] To use Manga2Anime_LineArt_Preprocessor_Provider, you need to install 'ComfyUI's ControlNet Auxiliary Preprocessors.'")
|
||||
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['Manga2Anime_LineArt_Preprocessor']()
|
||||
resolution = normalize_size_base_64(image.shape[2], image.shape[1])
|
||||
return obj.execute(image, resolution=resolution)[0]
|
||||
|
||||
|
||||
class Color_Preprocessor_wrapper:
|
||||
def apply(self, image, mask=None):
|
||||
if 'ColorPreprocessor' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/Fannovel16/comfyui_controlnet_aux',
|
||||
"To use 'Color_Preprocessor_Provider' node, 'ComfyUI's ControlNet Auxiliary Preprocessors.' extension is required.")
|
||||
raise Exception("[ERROR] To use Color_Preprocessor_Provider, you need to install 'ComfyUI's ControlNet Auxiliary Preprocessors.'")
|
||||
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['ColorPreprocessor']()
|
||||
resolution = normalize_size_base_64(image.shape[2], image.shape[1])
|
||||
return obj.execute(image, resolution=resolution)[0]
|
||||
|
||||
|
||||
class InpaintPreprocessor_wrapper:
|
||||
def __init__(self, black_pixel_for_xinsir_cn):
|
||||
self.black_pixel_for_xinsir_cn = black_pixel_for_xinsir_cn
|
||||
|
||||
def apply(self, image, mask=None):
|
||||
if 'InpaintPreprocessor' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/Fannovel16/comfyui_controlnet_aux',
|
||||
"To use 'InpaintPreprocessor_Provider' node, 'ComfyUI's ControlNet Auxiliary Preprocessors.' extension is required.")
|
||||
raise Exception("[ERROR] To use InpaintPreprocessor_Provider, you need to install 'ComfyUI's ControlNet Auxiliary Preprocessors.'")
|
||||
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['InpaintPreprocessor']()
|
||||
if mask is None:
|
||||
mask = torch.ones((image.shape[1], image.shape[2]), dtype=torch.float32, device="cpu").unsqueeze(0)
|
||||
|
||||
try:
|
||||
res = obj.preprocess(image, mask, black_pixel_for_xinsir_cn=self.black_pixel_for_xinsir_cn)[0]
|
||||
except Exception as e:
|
||||
if self.black_pixel_for_xinsir_cn:
|
||||
raise e
|
||||
else:
|
||||
res = obj.preprocess(image, mask)[0]
|
||||
logging.warning("[Inspire Pack] Installed 'ComfyUI's ControlNet Auxiliary Preprocessors.' is outdated.")
|
||||
|
||||
return res
|
||||
|
||||
|
||||
class TilePreprocessor_wrapper:
|
||||
def __init__(self, pyrUp_iters):
|
||||
self.pyrUp_iters = pyrUp_iters
|
||||
|
||||
def apply(self, image, mask=None):
|
||||
if 'TilePreprocessor' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/Fannovel16/comfyui_controlnet_aux',
|
||||
"To use 'TilePreprocessor_Provider' node, 'ComfyUI's ControlNet Auxiliary Preprocessors.' extension is required.")
|
||||
raise Exception("[ERROR] To use TilePreprocessor_Provider, you need to install 'ComfyUI's ControlNet Auxiliary Preprocessors.'")
|
||||
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['TilePreprocessor']()
|
||||
resolution = normalize_size_base_64(image.shape[2], image.shape[1])
|
||||
return obj.execute(image, self.pyrUp_iters, resolution=resolution)[0]
|
||||
|
||||
|
||||
class MeshGraphormerDepthMapPreprocessorProvider_wrapper:
|
||||
def apply(self, image, mask=None):
|
||||
if 'MeshGraphormer-DepthMapPreprocessor' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/Fannovel16/comfyui_controlnet_aux',
|
||||
"To use 'MeshGraphormerDepthMapPreprocessorProvider' node, 'ComfyUI's ControlNet Auxiliary Preprocessors.' extension is required.")
|
||||
raise Exception("[ERROR] To use MeshGraphormerDepthMapPreprocessorProvider, you need to install 'ComfyUI's ControlNet Auxiliary Preprocessors.'")
|
||||
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['MeshGraphormer-DepthMapPreprocessor']()
|
||||
resolution = normalize_size_base_64(image.shape[2], image.shape[1])
|
||||
return obj.execute(image, resolution=resolution)[0]
|
||||
|
||||
|
||||
class LineArt_Preprocessor_wrapper:
|
||||
def __init__(self, coarse):
|
||||
self.coarse = coarse
|
||||
|
||||
def apply(self, image, mask=None):
|
||||
if 'LineArtPreprocessor' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/Fannovel16/comfyui_controlnet_aux',
|
||||
"To use 'LineArt_Preprocessor_Provider' node, 'ComfyUI's ControlNet Auxiliary Preprocessors.' extension is required.")
|
||||
raise Exception("[ERROR] To use LineArt_Preprocessor_Provider, you need to install 'ComfyUI's ControlNet Auxiliary Preprocessors.'")
|
||||
|
||||
coarse = 'enable' if self.coarse else 'disable'
|
||||
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['LineArtPreprocessor']()
|
||||
resolution = normalize_size_base_64(image.shape[2], image.shape[1])
|
||||
return obj.execute(image, resolution=resolution, coarse=coarse)[0]
|
||||
|
||||
|
||||
class OpenPose_Preprocessor_wrapper:
|
||||
def __init__(self, detect_hand, detect_body, detect_face, upscale_factor=1.0):
|
||||
self.detect_hand = detect_hand
|
||||
self.detect_body = detect_body
|
||||
self.detect_face = detect_face
|
||||
self.upscale_factor = upscale_factor
|
||||
|
||||
def apply(self, image, mask=None):
|
||||
if 'OpenposePreprocessor' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/Fannovel16/comfyui_controlnet_aux',
|
||||
"To use 'OpenPose_Preprocessor_Provider' node, 'ComfyUI's ControlNet Auxiliary Preprocessors.' extension is required.")
|
||||
raise Exception("[ERROR] To use OpenPose_Preprocessor_Provider, you need to install 'ComfyUI's ControlNet Auxiliary Preprocessors.'")
|
||||
|
||||
detect_hand = 'enable' if self.detect_hand else 'disable'
|
||||
detect_body = 'enable' if self.detect_body else 'disable'
|
||||
detect_face = 'enable' if self.detect_face else 'disable'
|
||||
|
||||
if self.upscale_factor != 1.0:
|
||||
image = nodes.ImageScaleBy().upscale(image, 'bilinear', self.upscale_factor)[0]
|
||||
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['OpenposePreprocessor']()
|
||||
resolution = normalize_size_base_64(image.shape[2], image.shape[1])
|
||||
return obj.estimate_pose(image, detect_hand, detect_body, detect_face, resolution=resolution)['result'][0]
|
||||
|
||||
|
||||
class DWPreprocessor_wrapper:
|
||||
def __init__(self, detect_hand, detect_body, detect_face, upscale_factor=1.0, bbox_detector="yolox_l.onnx", pose_estimator="dw-ll_ucoco_384.onnx"):
|
||||
self.detect_hand = detect_hand
|
||||
self.detect_body = detect_body
|
||||
self.detect_face = detect_face
|
||||
self.upscale_factor = upscale_factor
|
||||
self.bbox_detector = bbox_detector
|
||||
self.pose_estimator = pose_estimator
|
||||
|
||||
def apply(self, image, mask=None):
|
||||
if 'DWPreprocessor' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/Fannovel16/comfyui_controlnet_aux',
|
||||
"To use 'DWPreprocessor_Provider' node, 'ComfyUI's ControlNet Auxiliary Preprocessors.' extension is required.")
|
||||
raise Exception("[ERROR] To use DWPreprocessor_Provider, you need to install 'ComfyUI's ControlNet Auxiliary Preprocessors.'")
|
||||
|
||||
detect_hand = 'enable' if self.detect_hand else 'disable'
|
||||
detect_body = 'enable' if self.detect_body else 'disable'
|
||||
detect_face = 'enable' if self.detect_face else 'disable'
|
||||
|
||||
if self.upscale_factor != 1.0:
|
||||
image = nodes.ImageScaleBy().upscale(image, 'bilinear', self.upscale_factor)[0]
|
||||
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['DWPreprocessor']()
|
||||
resolution = normalize_size_base_64(image.shape[2], image.shape[1])
|
||||
return obj.estimate_pose(image, detect_hand, detect_body, detect_face, resolution=resolution, bbox_detector=self.bbox_detector, pose_estimator=self.pose_estimator)['result'][0]
|
||||
|
||||
|
||||
class LeReS_DepthMap_Preprocessor_wrapper:
|
||||
def __init__(self, rm_nearest, rm_background, boost):
|
||||
self.rm_nearest = rm_nearest
|
||||
self.rm_background = rm_background
|
||||
self.boost = boost
|
||||
|
||||
def apply(self, image, mask=None):
|
||||
if 'LeReS-DepthMapPreprocessor' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/Fannovel16/comfyui_controlnet_aux',
|
||||
"To use 'LeReS_DepthMap_Preprocessor_Provider' node, 'ComfyUI's ControlNet Auxiliary Preprocessors.' extension is required.")
|
||||
raise Exception("[ERROR] To use LeReS_DepthMap_Preprocessor_Provider, you need to install 'ComfyUI's ControlNet Auxiliary Preprocessors.'")
|
||||
|
||||
boost = 'enable' if self.boost else 'disable'
|
||||
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['LeReS-DepthMapPreprocessor']()
|
||||
resolution = normalize_size_base_64(image.shape[2], image.shape[1])
|
||||
return obj.execute(image, self.rm_nearest, self.rm_background, boost=boost, resolution=resolution)[0]
|
||||
|
||||
|
||||
class MiDaS_DepthMap_Preprocessor_wrapper:
|
||||
def __init__(self, a, bg_threshold):
|
||||
self.a = a
|
||||
self.bg_threshold = bg_threshold
|
||||
|
||||
def apply(self, image, mask=None):
|
||||
if 'MiDaS-DepthMapPreprocessor' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/Fannovel16/comfyui_controlnet_aux',
|
||||
"To use 'MiDaS_DepthMap_Preprocessor_Provider' node, 'ComfyUI's ControlNet Auxiliary Preprocessors.' extension is required.")
|
||||
raise Exception("[ERROR] To use MiDaS_DepthMap_Preprocessor_Provider, you need to install 'ComfyUI's ControlNet Auxiliary Preprocessors.'")
|
||||
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['MiDaS-DepthMapPreprocessor']()
|
||||
resolution = normalize_size_base_64(image.shape[2], image.shape[1])
|
||||
return obj.execute(image, self.a, self.bg_threshold, resolution=resolution)[0]
|
||||
|
||||
|
||||
class Zoe_DepthMap_Preprocessor_wrapper:
|
||||
def apply(self, image, mask=None):
|
||||
if 'Zoe-DepthMapPreprocessor' not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/Fannovel16/comfyui_controlnet_aux',
|
||||
"To use 'Zoe_DepthMap_Preprocessor_Provider' node, 'ComfyUI's ControlNet Auxiliary Preprocessors.' extension is required.")
|
||||
raise Exception("[ERROR] To use Zoe_DepthMap_Preprocessor_Provider, you need to install 'ComfyUI's ControlNet Auxiliary Preprocessors.'")
|
||||
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['Zoe-DepthMapPreprocessor']()
|
||||
resolution = normalize_size_base_64(image.shape[2], image.shape[1])
|
||||
return obj.execute(image, resolution=resolution)[0]
|
||||
|
||||
|
||||
class HED_Preprocessor_wrapper:
|
||||
def __init__(self, safe, nodename):
|
||||
self.safe = safe
|
||||
self.nodename = nodename
|
||||
|
||||
def apply(self, image, mask=None):
|
||||
if self.nodename not in nodes.NODE_CLASS_MAPPINGS:
|
||||
utils.try_install_custom_node('https://github.com/Fannovel16/comfyui_controlnet_aux',
|
||||
f"To use '{self.nodename}_Preprocessor_Provider' node, 'ComfyUI's ControlNet Auxiliary Preprocessors.' extension is required.")
|
||||
raise Exception(f"[ERROR] To use {self.nodename}_Provider, you need to install 'ComfyUI's ControlNet Auxiliary Preprocessors.'")
|
||||
|
||||
obj = nodes.NODE_CLASS_MAPPINGS[self.nodename]()
|
||||
resolution = normalize_size_base_64(image.shape[2], image.shape[1])
|
||||
return obj.execute(image, resolution=resolution, safe="enable" if self.safe else "disable")[0]
|
||||
|
||||
|
||||
class Canny_Preprocessor_wrapper:
|
||||
def __init__(self, low_threshold, high_threshold):
|
||||
self.low_threshold = low_threshold
|
||||
self.high_threshold = high_threshold
|
||||
|
||||
def apply(self, image, mask=None):
|
||||
obj = nodes.NODE_CLASS_MAPPINGS['Canny']()
|
||||
if hasattr(obj, 'execute'):
|
||||
# node v3
|
||||
return obj.execute(image, self.low_threshold, self.high_threshold)[0]
|
||||
else:
|
||||
# legacy compatibility
|
||||
return obj.detect_edge(image, self.low_threshold, self.high_threshold)[0]
|
||||
|
||||
|
||||
class OpenPose_Preprocessor_Provider_for_SEGS:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"detect_hand": ("BOOLEAN", {"default": True, "label_on": "enable", "label_off": "disable"}),
|
||||
"detect_body": ("BOOLEAN", {"default": True, "label_on": "enable", "label_off": "disable"}),
|
||||
"detect_face": ("BOOLEAN", {"default": True, "label_on": "enable", "label_off": "disable"}),
|
||||
"resolution_upscale_by": ("FLOAT", {"default": 1.0, "min": 0.5, "max": 100, "step": 0.1}),
|
||||
}
|
||||
}
|
||||
RETURN_TYPES = ("SEGS_PREPROCESSOR",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/SEGS/ControlNet"
|
||||
|
||||
def doit(self, detect_hand, detect_body, detect_face, resolution_upscale_by):
|
||||
obj = OpenPose_Preprocessor_wrapper(detect_hand, detect_body, detect_face, upscale_factor=resolution_upscale_by)
|
||||
return (obj, )
|
||||
|
||||
|
||||
class DWPreprocessor_Provider_for_SEGS:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"detect_hand": ("BOOLEAN", {"default": True, "label_on": "enable", "label_off": "disable"}),
|
||||
"detect_body": ("BOOLEAN", {"default": True, "label_on": "enable", "label_off": "disable"}),
|
||||
"detect_face": ("BOOLEAN", {"default": True, "label_on": "enable", "label_off": "disable"}),
|
||||
"resolution_upscale_by": ("FLOAT", {"default": 1.0, "min": 0.5, "max": 100, "step": 0.1}),
|
||||
"bbox_detector": (
|
||||
["yolox_l.torchscript.pt", "yolox_l.onnx", "yolo_nas_l_fp16.onnx", "yolo_nas_m_fp16.onnx", "yolo_nas_s_fp16.onnx"],
|
||||
{"default": "yolox_l.onnx"}
|
||||
),
|
||||
"pose_estimator": (["dw-ll_ucoco_384_bs5.torchscript.pt", "dw-ll_ucoco_384.onnx", "dw-ll_ucoco.onnx"], {"default": "dw-ll_ucoco_384_bs5.torchscript.pt"})
|
||||
}
|
||||
}
|
||||
RETURN_TYPES = ("SEGS_PREPROCESSOR",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/SEGS/ControlNet"
|
||||
|
||||
def doit(self, detect_hand, detect_body, detect_face, resolution_upscale_by, bbox_detector, pose_estimator):
|
||||
obj = DWPreprocessor_wrapper(detect_hand, detect_body, detect_face, upscale_factor=resolution_upscale_by, bbox_detector=bbox_detector, pose_estimator=pose_estimator)
|
||||
return (obj, )
|
||||
|
||||
|
||||
class LeReS_DepthMap_Preprocessor_Provider_for_SEGS:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"rm_nearest": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100, "step": 0.1}),
|
||||
"rm_background": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100, "step": 0.1})
|
||||
},
|
||||
"optional": {
|
||||
"boost": ("BOOLEAN", {"default": False, "label_on": "enable", "label_off": "disable"}),
|
||||
}
|
||||
}
|
||||
RETURN_TYPES = ("SEGS_PREPROCESSOR",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/SEGS/ControlNet"
|
||||
|
||||
def doit(self, rm_nearest, rm_background, boost=False):
|
||||
obj = LeReS_DepthMap_Preprocessor_wrapper(rm_nearest, rm_background, boost)
|
||||
return (obj, )
|
||||
|
||||
|
||||
class MiDaS_DepthMap_Preprocessor_Provider_for_SEGS:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"a": ("FLOAT", {"default": np.pi * 2.0, "min": 0.0, "max": np.pi * 5.0, "step": 0.05}),
|
||||
"bg_threshold": ("FLOAT", {"default": 0.1, "min": 0, "max": 1, "step": 0.05})
|
||||
}
|
||||
}
|
||||
RETURN_TYPES = ("SEGS_PREPROCESSOR",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/SEGS/ControlNet"
|
||||
|
||||
def doit(self, a, bg_threshold):
|
||||
obj = MiDaS_DepthMap_Preprocessor_wrapper(a, bg_threshold)
|
||||
return (obj, )
|
||||
|
||||
|
||||
class Zoe_DepthMap_Preprocessor_Provider_for_SEGS:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return { "required": {} }
|
||||
RETURN_TYPES = ("SEGS_PREPROCESSOR",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/SEGS/ControlNet"
|
||||
|
||||
def doit(self):
|
||||
obj = Zoe_DepthMap_Preprocessor_wrapper()
|
||||
return (obj, )
|
||||
|
||||
|
||||
class Canny_Preprocessor_Provider_for_SEGS:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"low_threshold": ("FLOAT", {"default": 0.4, "min": 0.01, "max": 0.99, "step": 0.01}),
|
||||
"high_threshold": ("FLOAT", {"default": 0.8, "min": 0.01, "max": 0.99, "step": 0.01})
|
||||
}
|
||||
}
|
||||
RETURN_TYPES = ("SEGS_PREPROCESSOR",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/SEGS/ControlNet"
|
||||
|
||||
def doit(self, low_threshold, high_threshold):
|
||||
obj = Canny_Preprocessor_wrapper(low_threshold, high_threshold)
|
||||
return (obj, )
|
||||
|
||||
|
||||
class HEDPreprocessor_Provider_for_SEGS:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"safe": ("BOOLEAN", {"default": True, "label_on": "enable", "label_off": "disable"})
|
||||
}
|
||||
}
|
||||
RETURN_TYPES = ("SEGS_PREPROCESSOR",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/SEGS/ControlNet"
|
||||
|
||||
def doit(self, safe):
|
||||
obj = HED_Preprocessor_wrapper(safe, "HEDPreprocessor")
|
||||
return (obj, )
|
||||
|
||||
|
||||
class FakeScribblePreprocessor_Provider_for_SEGS(HEDPreprocessor_Provider_for_SEGS):
|
||||
def doit(self, safe):
|
||||
obj = HED_Preprocessor_wrapper(safe, "FakeScribblePreprocessor")
|
||||
return (obj, )
|
||||
|
||||
|
||||
class MediaPipe_FaceMesh_Preprocessor_Provider_for_SEGS:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {
|
||||
"max_faces": ("INT", {"default": 10, "min": 1, "max": 50, "step": 1}),
|
||||
"min_confidence": ("FLOAT", {"default": 0.5, "min": 0.01, "max": 1.0, "step": 0.01}),
|
||||
"resolution_upscale_by": ("FLOAT", {"default": 1.0, "min": 0.5, "max": 100, "step": 0.1}),
|
||||
}
|
||||
}
|
||||
RETURN_TYPES = ("SEGS_PREPROCESSOR",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/SEGS/ControlNet"
|
||||
|
||||
def doit(self, max_faces, min_confidence, resolution_upscale_by):
|
||||
obj = MediaPipe_FaceMesh_Preprocessor_wrapper(max_faces, min_confidence, upscale_factor=resolution_upscale_by)
|
||||
return (obj, )
|
||||
|
||||
|
||||
class MediaPipeFaceMeshDetectorProvider:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
bool_true_widget = ("BOOLEAN", {"default": True, "label_on": "enable", "label_off": "disable"})
|
||||
bool_false_widget = ("BOOLEAN", {"default": False, "label_on": "enable", "label_off": "disable"})
|
||||
return {"required": {
|
||||
"max_faces": ("INT", {"default": 10, "min": 1, "max": 50, "step": 1}),
|
||||
"face": bool_true_widget,
|
||||
"mouth": bool_false_widget,
|
||||
"left_eyebrow": bool_false_widget,
|
||||
"left_eye": bool_false_widget,
|
||||
"left_pupil": bool_false_widget,
|
||||
"right_eyebrow": bool_false_widget,
|
||||
"right_eye": bool_false_widget,
|
||||
"right_pupil": bool_false_widget,
|
||||
}}
|
||||
|
||||
RETURN_TYPES = ("BBOX_DETECTOR", "SEGM_DETECTOR")
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/Detector"
|
||||
|
||||
def doit(self, max_faces, face, mouth, left_eyebrow, left_eye, left_pupil, right_eyebrow, right_eye, right_pupil):
|
||||
bbox_detector = MediaPipeFaceMeshDetector(face, mouth, left_eyebrow, left_eye, left_pupil, right_eyebrow, right_eye, right_pupil, max_faces, is_segm=False)
|
||||
segm_detector = MediaPipeFaceMeshDetector(face, mouth, left_eyebrow, left_eye, left_pupil, right_eyebrow, right_eye, right_pupil, max_faces, is_segm=True)
|
||||
|
||||
return (bbox_detector, segm_detector)
|
||||
|
||||
|
||||
class AnimeLineArt_Preprocessor_Provider_for_SEGS:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {}}
|
||||
RETURN_TYPES = ("SEGS_PREPROCESSOR",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/SEGS/ControlNet"
|
||||
|
||||
def doit(self):
|
||||
obj = AnimeLineArt_Preprocessor_wrapper()
|
||||
return (obj, )
|
||||
|
||||
|
||||
class Manga2Anime_LineArt_Preprocessor_Provider_for_SEGS:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {}}
|
||||
RETURN_TYPES = ("SEGS_PREPROCESSOR",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/SEGS/ControlNet"
|
||||
|
||||
def doit(self):
|
||||
obj = Manga2Anime_LineArt_Preprocessor_wrapper()
|
||||
return (obj, )
|
||||
|
||||
|
||||
class LineArt_Preprocessor_Provider_for_SEGS:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"coarse": ("BOOLEAN", {"default": False, "label_on": "enable", "label_off": "disable"}),
|
||||
}}
|
||||
RETURN_TYPES = ("SEGS_PREPROCESSOR",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/SEGS/ControlNet"
|
||||
|
||||
def doit(self, coarse):
|
||||
obj = LineArt_Preprocessor_wrapper(coarse)
|
||||
return (obj, )
|
||||
|
||||
|
||||
class Color_Preprocessor_Provider_for_SEGS:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {}}
|
||||
RETURN_TYPES = ("SEGS_PREPROCESSOR",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/SEGS/ControlNet"
|
||||
|
||||
def doit(self):
|
||||
obj = Color_Preprocessor_wrapper()
|
||||
return (obj, )
|
||||
|
||||
|
||||
class InpaintPreprocessor_Provider_for_SEGS:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {
|
||||
"required": {},
|
||||
"optional": {
|
||||
"black_pixel_for_xinsir_cn": ("BOOLEAN", {"default": False, "label_on": "enable", "label_off": "disable"}),
|
||||
}
|
||||
}
|
||||
RETURN_TYPES = ("SEGS_PREPROCESSOR",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/SEGS/ControlNet"
|
||||
|
||||
def doit(self, black_pixel_for_xinsir_cn=False):
|
||||
obj = InpaintPreprocessor_wrapper(black_pixel_for_xinsir_cn)
|
||||
return (obj, )
|
||||
|
||||
|
||||
class TilePreprocessor_Provider_for_SEGS:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {'pyrUp_iters': ("INT", {"default": 3, "min": 1, "max": 10, "step": 1})}}
|
||||
RETURN_TYPES = ("SEGS_PREPROCESSOR",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/SEGS/ControlNet"
|
||||
|
||||
def doit(self, pyrUp_iters):
|
||||
obj = TilePreprocessor_wrapper(pyrUp_iters)
|
||||
return (obj, )
|
||||
|
||||
|
||||
class MeshGraphormerDepthMapPreprocessorProvider_for_SEGS:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {}}
|
||||
RETURN_TYPES = ("SEGS_PREPROCESSOR",)
|
||||
FUNCTION = "doit"
|
||||
|
||||
CATEGORY = "InspirePack/SEGS/ControlNet"
|
||||
|
||||
def doit(self):
|
||||
obj = MeshGraphormerDepthMapPreprocessorProvider_wrapper()
|
||||
return (obj, )
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"OpenPose_Preprocessor_Provider_for_SEGS //Inspire": OpenPose_Preprocessor_Provider_for_SEGS,
|
||||
"DWPreprocessor_Provider_for_SEGS //Inspire": DWPreprocessor_Provider_for_SEGS,
|
||||
"MiDaS_DepthMap_Preprocessor_Provider_for_SEGS //Inspire": MiDaS_DepthMap_Preprocessor_Provider_for_SEGS,
|
||||
"LeRes_DepthMap_Preprocessor_Provider_for_SEGS //Inspire": LeReS_DepthMap_Preprocessor_Provider_for_SEGS,
|
||||
# "Zoe_DepthMap_Preprocessor_Provider_for_SEGS //Inspire": Zoe_DepthMap_Preprocessor_Provider_for_SEGS,
|
||||
"Canny_Preprocessor_Provider_for_SEGS //Inspire": Canny_Preprocessor_Provider_for_SEGS,
|
||||
"MediaPipe_FaceMesh_Preprocessor_Provider_for_SEGS //Inspire": MediaPipe_FaceMesh_Preprocessor_Provider_for_SEGS,
|
||||
"HEDPreprocessor_Provider_for_SEGS //Inspire": HEDPreprocessor_Provider_for_SEGS,
|
||||
"FakeScribblePreprocessor_Provider_for_SEGS //Inspire": FakeScribblePreprocessor_Provider_for_SEGS,
|
||||
"AnimeLineArt_Preprocessor_Provider_for_SEGS //Inspire": AnimeLineArt_Preprocessor_Provider_for_SEGS,
|
||||
"Manga2Anime_LineArt_Preprocessor_Provider_for_SEGS //Inspire": Manga2Anime_LineArt_Preprocessor_Provider_for_SEGS,
|
||||
"LineArt_Preprocessor_Provider_for_SEGS //Inspire": LineArt_Preprocessor_Provider_for_SEGS,
|
||||
"Color_Preprocessor_Provider_for_SEGS //Inspire": Color_Preprocessor_Provider_for_SEGS,
|
||||
"InpaintPreprocessor_Provider_for_SEGS //Inspire": InpaintPreprocessor_Provider_for_SEGS,
|
||||
"TilePreprocessor_Provider_for_SEGS //Inspire": TilePreprocessor_Provider_for_SEGS,
|
||||
"MeshGraphormerDepthMapPreprocessorProvider_for_SEGS //Inspire": MeshGraphormerDepthMapPreprocessorProvider_for_SEGS,
|
||||
"MediaPipeFaceMeshDetectorProvider //Inspire": MediaPipeFaceMeshDetectorProvider,
|
||||
}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"OpenPose_Preprocessor_Provider_for_SEGS //Inspire": "OpenPose Preprocessor Provider (SEGS)",
|
||||
"DWPreprocessor_Provider_for_SEGS //Inspire": "DWPreprocessor Provider (SEGS)",
|
||||
"MiDaS_DepthMap_Preprocessor_Provider_for_SEGS //Inspire": "MiDaS Depth Map Preprocessor Provider (SEGS)",
|
||||
"LeRes_DepthMap_Preprocessor_Provider_for_SEGS //Inspire": "LeReS Depth Map Preprocessor Provider (SEGS)",
|
||||
# "Zoe_DepthMap_Preprocessor_Provider_for_SEGS //Inspire": "Zoe Depth Map Preprocessor Provider (SEGS)",
|
||||
"Canny_Preprocessor_Provider_for_SEGS //Inspire": "Canny Preprocessor Provider (SEGS)",
|
||||
"MediaPipe_FaceMesh_Preprocessor_Provider_for_SEGS //Inspire": "MediaPipe FaceMesh Preprocessor Provider (SEGS)",
|
||||
"HEDPreprocessor_Provider_for_SEGS //Inspire": "HED Preprocessor Provider (SEGS)",
|
||||
"FakeScribblePreprocessor_Provider_for_SEGS //Inspire": "Fake Scribble Preprocessor Provider (SEGS)",
|
||||
"AnimeLineArt_Preprocessor_Provider_for_SEGS //Inspire": "AnimeLineArt Preprocessor Provider (SEGS)",
|
||||
"Manga2Anime_LineArt_Preprocessor_Provider_for_SEGS //Inspire": "Manga2Anime LineArt Preprocessor Provider (SEGS)",
|
||||
"LineArt_Preprocessor_Provider_for_SEGS //Inspire": "LineArt Preprocessor Provider (SEGS)",
|
||||
"Color_Preprocessor_Provider_for_SEGS //Inspire": "Color Preprocessor Provider (SEGS)",
|
||||
"InpaintPreprocessor_Provider_for_SEGS //Inspire": "Inpaint Preprocessor Provider (SEGS)",
|
||||
"TilePreprocessor_Provider_for_SEGS //Inspire": "Tile Preprocessor Provider (SEGS)",
|
||||
"MeshGraphormerDepthMapPreprocessorProvider_for_SEGS //Inspire": "MeshGraphormer Depth Map Preprocessor Provider (SEGS)",
|
||||
"MediaPipeFaceMeshDetectorProvider //Inspire": "MediaPipeFaceMesh Detector Provider",
|
||||
}
|
||||
41
custom_nodes/comfyui-inspire-pack/inspire/util_nodes.py
Normal file
41
custom_nodes/comfyui-inspire-pack/inspire/util_nodes.py
Normal file
@@ -0,0 +1,41 @@
|
||||
import colorsys
|
||||
|
||||
|
||||
def hex_to_hsv(hex_color):
|
||||
hex_color = hex_color.lstrip('#')
|
||||
r, g, b = tuple(int(hex_color[i:i+2], 16) / 255.0 for i in (0, 2, 4))
|
||||
|
||||
h, s, v = colorsys.rgb_to_hsv(r, g, b)
|
||||
|
||||
hue = h * 360
|
||||
|
||||
saturation = s
|
||||
value = v
|
||||
|
||||
return hue, saturation, value
|
||||
|
||||
|
||||
class RGB_HexToHSV:
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
return {"required": {
|
||||
"rgb_hex": ("STRING", {"defaultInput": True}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("FLOAT", "FLOAT", "FLOAT")
|
||||
RETURN_NAMES = ("hue", "saturation", "value")
|
||||
FUNCTION = "doit"
|
||||
CATEGORY = "InspirePack/Util"
|
||||
|
||||
def doit(self, rgb_hex):
|
||||
return hex_to_hsv(rgb_hex)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"RGB_HexToHSV //Inspire": RGB_HexToHSV,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"RGB_HexToHSV //Inspire": "RGB Hex To HSV (Inspire)",
|
||||
}
|
||||
27
custom_nodes/comfyui-inspire-pack/js/common.js
Normal file
27
custom_nodes/comfyui-inspire-pack/js/common.js
Normal file
@@ -0,0 +1,27 @@
|
||||
import { api } from "../../scripts/api.js";
|
||||
|
||||
function nodeFeedbackHandler(event) {
|
||||
let nodes = app.graph._nodes_by_id;
|
||||
let node = nodes[event.detail.node_id];
|
||||
if(node) {
|
||||
if(event.detail.type == "text") {
|
||||
const w = node.widgets.find((w) => event.detail.widget_name === w.name);
|
||||
if(w) {
|
||||
w.value = event.detail.data;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
api.addEventListener("inspire-node-feedback", nodeFeedbackHandler);
|
||||
|
||||
|
||||
function nodeOutputLabelHandler(event) {
|
||||
let nodes = app.graph._nodes_by_id;
|
||||
let node = nodes[event.detail.node_id];
|
||||
if(node) {
|
||||
node.outputs[event.detail.output_idx].label = event.detail.label;
|
||||
}
|
||||
}
|
||||
|
||||
api.addEventListener("inspire-node-output-label", nodeOutputLabelHandler);
|
||||
71
custom_nodes/comfyui-inspire-pack/js/image_util.js
Normal file
71
custom_nodes/comfyui-inspire-pack/js/image_util.js
Normal file
@@ -0,0 +1,71 @@
|
||||
import { ComfyApp, app } from "../../scripts/app.js";
|
||||
|
||||
function load_image(str) {
|
||||
let base64String = canvas.toDataURL('image/png');
|
||||
let img = new Image();
|
||||
img.src = base64String;
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "Comfy.Inspire.img",
|
||||
|
||||
nodeCreated(node, app) {
|
||||
if(node.comfyClass == "LoadImage //Inspire") {
|
||||
let w = node.widgets.find(obj => obj.name === 'image_data');
|
||||
|
||||
Object.defineProperty(w, 'value', {
|
||||
set(v) {
|
||||
if(v != '[IMAGE DATA]')
|
||||
w._value = v;
|
||||
},
|
||||
get() {
|
||||
const stackTrace = new Error().stack;
|
||||
if(!stackTrace.includes('draw') && !stackTrace.includes('graphToPrompt') && stackTrace.includes('app.js')) {
|
||||
return "[IMAGE DATA]";
|
||||
}
|
||||
else {
|
||||
return w._value;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let set_img_act = (v) => {
|
||||
node._img = v;
|
||||
var canvas = document.createElement('canvas');
|
||||
canvas.width = v[0].width;
|
||||
canvas.height = v[0].height;
|
||||
|
||||
var context = canvas.getContext('2d');
|
||||
context.drawImage(v[0], 0, 0, v[0].width, v[0].height);
|
||||
|
||||
var base64Image = canvas.toDataURL('image/png');
|
||||
w.value = base64Image;
|
||||
};
|
||||
|
||||
Object.defineProperty(node, 'imgs', {
|
||||
set(v) {
|
||||
if (v && !v[0].complete) {
|
||||
let orig_onload = v[0].onload;
|
||||
v[0].onload = function(v2) {
|
||||
if(orig_onload)
|
||||
orig_onload();
|
||||
set_img_act(v);
|
||||
};
|
||||
}
|
||||
else {
|
||||
set_img_act(v);
|
||||
}
|
||||
},
|
||||
get() {
|
||||
if(this._img == undefined && w.value != '') {
|
||||
this._img = [new Image()];
|
||||
if(w.value && w.value != '[IMAGE DATA]')
|
||||
this._img[0].src = w.value;
|
||||
}
|
||||
|
||||
return this._img;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
})
|
||||
36
custom_nodes/comfyui-inspire-pack/js/inspire-backend.js
Normal file
36
custom_nodes/comfyui-inspire-pack/js/inspire-backend.js
Normal file
@@ -0,0 +1,36 @@
|
||||
import { api } from "../../scripts/api.js";
|
||||
|
||||
async function refresh_data(node) {
|
||||
let response = await api.fetchApi('/inspire/cache/list');
|
||||
node.widgets[0].value = await response.text();
|
||||
}
|
||||
|
||||
async function remove_key(node, key) {
|
||||
await api.fetchApi(`/inspire/cache/remove?key=${key}`);
|
||||
node.widgets[1].value = '';
|
||||
refresh_data(node);
|
||||
}
|
||||
|
||||
async function clear_data(node) {
|
||||
await api.fetchApi('/inspire/cache/clear');
|
||||
refresh_data(node);
|
||||
}
|
||||
|
||||
async function set_cache_settings(node) {
|
||||
await api.fetchApi('/inspire/cache/settings', {
|
||||
method: "POST",
|
||||
headers: {"Content-Type": "application/json",},
|
||||
body: node.widgets[0].value,
|
||||
});
|
||||
refresh_data(node);
|
||||
}
|
||||
|
||||
export function register_cache_info(node, app) {
|
||||
if(node.comfyClass == "ShowCachedInfo //Inspire") {
|
||||
node.addWidget("button", "Remove Key", null, () => { remove_key(node, node.widgets[1].value); });
|
||||
node.addWidget("button", "Save Settings", null, () => { set_cache_settings(node); });
|
||||
node.addWidget("button", "Refresh", null, () => { refresh_data(node); });
|
||||
node.addWidget("button", "Clear", null, () => { clear_data(node); });
|
||||
refresh_data(node);
|
||||
}
|
||||
}
|
||||
301
custom_nodes/comfyui-inspire-pack/js/inspire-flex.js
Normal file
301
custom_nodes/comfyui-inspire-pack/js/inspire-flex.js
Normal file
@@ -0,0 +1,301 @@
|
||||
import { ComfyApp, app } from "../../scripts/app.js";
|
||||
|
||||
export function register_concat_conditionings_with_multiplier_node(nodeType, nodeData, app) {
|
||||
if (nodeData.name === 'ConcatConditioningsWithMultiplier //Inspire') {
|
||||
var input_name = "conditioning";
|
||||
|
||||
const onConnectionsChange = nodeType.prototype.onConnectionsChange;
|
||||
let this_handler = async function (type, index, connected, link_info) {
|
||||
let last_state = this.state_change_handling;
|
||||
try {
|
||||
this.state_change_handling = true;
|
||||
if(!link_info || link_info.type != 'CONDITIONING')
|
||||
return;
|
||||
|
||||
let self = this;
|
||||
|
||||
function get_input_count(prefix, linked_only) {
|
||||
let cnt = 0;
|
||||
for(let i in self.inputs) {
|
||||
if(linked_only && !self.inputs[i].link)
|
||||
continue;
|
||||
|
||||
if(self.inputs[i].name.startsWith(prefix))
|
||||
cnt+=1;
|
||||
}
|
||||
|
||||
return cnt;
|
||||
}
|
||||
|
||||
function get_widget_count(prefix) {
|
||||
let cnt = 0;
|
||||
for(let i in self.widgets) {
|
||||
if(self.widgets[i].name.startsWith(prefix))
|
||||
cnt+=1;
|
||||
}
|
||||
|
||||
return cnt;
|
||||
}
|
||||
|
||||
function get_unconnected() {
|
||||
let unconnected = [];
|
||||
for(let i in self.inputs) {
|
||||
let input = self.inputs[i];
|
||||
if(input.name.startsWith('conditioning')) {
|
||||
if(input.link == undefined)
|
||||
unconnected.push(i);
|
||||
}
|
||||
}
|
||||
|
||||
return unconnected;
|
||||
}
|
||||
|
||||
let unconnected = get_unconnected();
|
||||
|
||||
function renames() {
|
||||
let con_i = 1;
|
||||
|
||||
let rename_map = {};
|
||||
|
||||
for(let i in self.inputs) {
|
||||
let input = self.inputs[i];
|
||||
if(input.name.startsWith('conditioning')) {
|
||||
let orig_i = Number(input.name.substring(12));
|
||||
if(orig_i != con_i) {
|
||||
rename_map[orig_i] = con_i;
|
||||
input.name = 'conditioning'+con_i;
|
||||
}
|
||||
con_i++;
|
||||
}
|
||||
}
|
||||
|
||||
// update multiplier input
|
||||
for(let i in self.inputs) {
|
||||
let input = self.inputs[i];
|
||||
if(input.name.startsWith('multiplier')) {
|
||||
let orig_i = Number(input.name.substring(10));
|
||||
if(rename_map[orig_i]) {
|
||||
input.name = 'multiplier'+rename_map[orig_i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// update multiplier widget
|
||||
for(let i in self.widgets) {
|
||||
let w = self.widgets[i];
|
||||
if(w.name.startsWith('multiplier')) {
|
||||
let orig_i = Number(w.name.substring(10));
|
||||
if(rename_map[orig_i]) {
|
||||
w.name = 'multiplier'+rename_map[orig_i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return con_i;
|
||||
}
|
||||
|
||||
function remove_multiplier_link(i, link_id) {
|
||||
let link = app.graph.links[link_id];
|
||||
const node = app.graph.getNodeById(link.origin_id);
|
||||
let x = node.outputs[link.origin_slot].links.findIndex((w) => w == link_id);
|
||||
node.outputs[link.origin_slot].links.splice(x, 1);
|
||||
self.disconnectInput(i);
|
||||
app.graph.links.splice(link_id, 1);
|
||||
}
|
||||
|
||||
async function remove_target_multiplier(target_name) {
|
||||
// remove strength from slot
|
||||
for(let i in self.inputs) {
|
||||
let input = self.inputs[i];
|
||||
if(input.name.startsWith(target_name)) {
|
||||
if(input.link) {
|
||||
remove_multiplier_link(i, input.link);
|
||||
}
|
||||
await self.removeInput(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const widget_index = self.widgets.findIndex((w) => w.name == target_name);
|
||||
self.widgets.splice(widget_index, 1);
|
||||
}
|
||||
|
||||
async function remove_garbage() {
|
||||
let unconnected = get_unconnected();
|
||||
|
||||
// remove unconnected conditionings
|
||||
while(unconnected.length > 0) {
|
||||
let last_one = unconnected.reverse()[0];
|
||||
self.removeInput(last_one);
|
||||
unconnected = get_unconnected();
|
||||
}
|
||||
|
||||
// remove dangling multipliers
|
||||
let conds = new Set();
|
||||
let muls = new Set();
|
||||
for(let i in self.inputs) {
|
||||
let input = self.inputs[i];
|
||||
if(input.link && input.name.startsWith('conditioning')) {
|
||||
let index = Number(input.name.substring(12));
|
||||
conds.add(index);
|
||||
}
|
||||
else if(input.name.startsWith('multiplier')) {
|
||||
let index = Number(input.name.substring(10));
|
||||
muls.add(index);
|
||||
}
|
||||
}
|
||||
for(let i in self.widgets) {
|
||||
let index = Number(self.widgets[i].name.substring(10));
|
||||
muls.add(index);
|
||||
}
|
||||
|
||||
let dangling_muls = [...muls].filter(x => !conds.has(x));
|
||||
while(dangling_muls.length > 0) {
|
||||
let remove_target = dangling_muls.pop();
|
||||
let target_name = `multiplier${remove_target}`;
|
||||
await remove_target_multiplier(target_name);
|
||||
}
|
||||
}
|
||||
|
||||
async function ensure_multipliers() {
|
||||
if(self.ensuring_multipliers) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
self.ensuring_multipliers = true;
|
||||
|
||||
let ncon = get_input_count('conditioning', true);
|
||||
let nmul = get_input_count('multiplier', false) + get_widget_count('multiplier');
|
||||
|
||||
if(ncon == 0 && nmul == 0)
|
||||
ncon = 1;
|
||||
|
||||
for(let i = nmul+1; i<=ncon; i++) {
|
||||
let config = { min: 0, max: 10, step: 0.1, round: 0.01, precision: 2 };
|
||||
|
||||
// NOTE: addWidget trigger calling ensure_multipliers
|
||||
let widget = await self.addWidget("number", `multiplier${i}`, 1.0, function (v) {
|
||||
if (config.round) {
|
||||
self.value = Math.round(v/config.round)*config.round;
|
||||
} else {
|
||||
self.value = v;
|
||||
}
|
||||
}, config);
|
||||
}
|
||||
}
|
||||
finally{
|
||||
self.ensuring_multipliers = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function recover_multipliers() {
|
||||
if(self.recover_multipliers) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
self.recover_multipliers = true;
|
||||
for(let i = 1; i<self.widgets_values.length; i++) {
|
||||
let config = { min: 0, max: 10, step: 0.1, round: 0.01, precision: 2 };
|
||||
|
||||
// NOTE: addWidget trigger calling recover_multipliers
|
||||
let widget = await self.addWidget("number", `multiplier${i+1}`, 1.0, function (v) {
|
||||
if (config.round) {
|
||||
self.value = Math.round(v/config.round)*config.round;
|
||||
} else {
|
||||
self.value = v;
|
||||
}
|
||||
}, config);
|
||||
}
|
||||
}
|
||||
finally{
|
||||
self.recover_multipliers = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function ensure_inputs() {
|
||||
if(get_unconnected() == 0) {
|
||||
let con_i = renames();
|
||||
self.addInput(`conditioning${con_i}`, self.outputs[0].type);
|
||||
}
|
||||
}
|
||||
|
||||
const stackTrace = new Error().stack;
|
||||
if(!stackTrace.includes('loadGraphData') && !stackTrace.includes('pasteFromClipboard')) {
|
||||
await remove_garbage();
|
||||
await ensure_inputs();
|
||||
}
|
||||
|
||||
if(!stackTrace.includes('loadGraphData')) {
|
||||
await ensure_multipliers();
|
||||
}
|
||||
else {
|
||||
await recover_multipliers();
|
||||
}
|
||||
|
||||
await this.setSize( this.computeSize() );
|
||||
}
|
||||
finally {
|
||||
this.state_change_handling = last_state;
|
||||
}
|
||||
}
|
||||
|
||||
nodeType.prototype.onConnectionsChange = this_handler;
|
||||
}
|
||||
}
|
||||
|
||||
function ensure_splitter_outputs(node, output_name, value, type) {
|
||||
if(node.outputs.length != (value + 1)) {
|
||||
while(node.outputs.length != (value + 1)) {
|
||||
if(node.outputs.length > value + 1) {
|
||||
node.removeOutput(node.outputs.length-1);
|
||||
}
|
||||
else {
|
||||
node.addOutput(`output${node.outputs.length+1}`, type);
|
||||
}
|
||||
}
|
||||
|
||||
for(let i in node.outputs) {
|
||||
let output = node.outputs[i];
|
||||
output.name = `${output_name} ${parseInt(i)+1}`;
|
||||
}
|
||||
|
||||
if(node.outputs[0].label == type || node.outputs[0].label == 'remained')
|
||||
delete node.outputs[0].label;
|
||||
|
||||
|
||||
let last_output = node.outputs[node.outputs.length-1];
|
||||
last_output.name = 'remained';
|
||||
}
|
||||
}
|
||||
|
||||
export function register_splitter(node, app) {
|
||||
if(node.comfyClass === 'ImageBatchSplitter //Inspire' || node.comfyClass === 'LatentBatchSplitter //Inspire') {
|
||||
let split_count = node.widgets[0];
|
||||
|
||||
let output_name = 'output';
|
||||
let output_type = "*";
|
||||
|
||||
if(node.comfyClass === 'ImageBatchSplitter //Inspire') {
|
||||
output_name = 'image';
|
||||
output_type = "IMAGE";
|
||||
}
|
||||
else if(node.comfyClass === 'LatentBatchSplitter //Inspire') {
|
||||
output_name = 'latent';
|
||||
output_type = "LATENT";
|
||||
}
|
||||
|
||||
ensure_splitter_outputs(node, output_name, split_count.value, output_type);
|
||||
|
||||
Object.defineProperty(split_count, "value", {
|
||||
set: async function(value) {
|
||||
if(value < 0 || value > 50)
|
||||
return;
|
||||
|
||||
ensure_splitter_outputs(node, output_name, value, output_type);
|
||||
},
|
||||
get: function() {
|
||||
return node.outputs.length - 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
7
custom_nodes/comfyui-inspire-pack/js/inspire-loop.js
Normal file
7
custom_nodes/comfyui-inspire-pack/js/inspire-loop.js
Normal file
@@ -0,0 +1,7 @@
|
||||
import { inspireProgressBadge } from "./progress-badge.js"
|
||||
|
||||
export function register_loop_node(nodeType, nodeData, app) {
|
||||
if(nodeData.name == 'ForeachListEnd //Inspire') {
|
||||
inspireProgressBadge.addStatusHandler(nodeType);
|
||||
}
|
||||
}
|
||||
17
custom_nodes/comfyui-inspire-pack/js/inspire-pack.js
Normal file
17
custom_nodes/comfyui-inspire-pack/js/inspire-pack.js
Normal file
@@ -0,0 +1,17 @@
|
||||
import { ComfyApp, app } from "../../scripts/app.js";
|
||||
import { register_concat_conditionings_with_multiplier_node, register_splitter } from "./inspire-flex.js";
|
||||
import { register_cache_info } from "./inspire-backend.js";
|
||||
import { register_loop_node } from "./inspire-loop.js";
|
||||
|
||||
app.registerExtension({
|
||||
name: "Comfy.Inspire",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
await register_concat_conditionings_with_multiplier_node(nodeType, nodeData, app);
|
||||
await register_loop_node(nodeType, nodeData, app);
|
||||
},
|
||||
|
||||
nodeCreated(node, app) {
|
||||
register_cache_info(node, app);
|
||||
register_splitter(node, app);
|
||||
}
|
||||
})
|
||||
165
custom_nodes/comfyui-inspire-pack/js/lora_block_weight.js
Normal file
165
custom_nodes/comfyui-inspire-pack/js/lora_block_weight.js
Normal file
@@ -0,0 +1,165 @@
|
||||
import { ComfyApp, app } from "../../scripts/app.js";
|
||||
|
||||
app.registerExtension({
|
||||
name: "Comfy.Inspire.LBW",
|
||||
|
||||
nodeCreated(node, app) {
|
||||
if(node.comfyClass == "LoraLoaderBlockWeight //Inspire" || node.comfyClass == "MakeLBW //Inspire") {
|
||||
// category filter
|
||||
const lora_names_widget = node.widgets[node.widgets.findIndex(obj => obj.name === 'lora_name')];
|
||||
var full_lora_list = lora_names_widget.options.values;
|
||||
const category_filter_widget = node.widgets[node.widgets.findIndex(obj => obj.name === 'category_filter')];
|
||||
|
||||
Object.defineProperty(lora_names_widget.options, "values", {
|
||||
set: (x) => {
|
||||
full_lora_list = x;
|
||||
},
|
||||
get: () => {
|
||||
if(category_filter_widget.value == 'All')
|
||||
return full_lora_list;
|
||||
|
||||
let l = full_lora_list.filter(x => x.startsWith(category_filter_widget.value));
|
||||
return l;
|
||||
}
|
||||
});
|
||||
|
||||
// vector selector
|
||||
let preset_i = 9;
|
||||
let vector_i = 10;
|
||||
|
||||
if(node.comfyClass == "MakeLBW //Inspire") {
|
||||
preset_i = 7;
|
||||
vector_i = 8;
|
||||
}
|
||||
|
||||
node._value = "Preset";
|
||||
|
||||
node.widgets[preset_i].callback = (v, canvas, node, pos, e) => {
|
||||
node.widgets[vector_i].value = node._value.split(':')[1];
|
||||
if(node.widgets_values) {
|
||||
node.widgets_values[vector_i] = node.widgets[preset_i].value;
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(node.widgets[preset_i], "value", {
|
||||
set: (value) => {
|
||||
if(value != "Preset")
|
||||
node._value = value;
|
||||
},
|
||||
get: () => {
|
||||
return node._value;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if(node.comfyClass == "XY Input: Lora Block Weight //Inspire") {
|
||||
// category filter
|
||||
const lora_names_widget = node.widgets[node.widgets.findIndex(obj => obj.name === 'lora_name')];
|
||||
var full_lora_list = lora_names_widget.options.values;
|
||||
const category_filter_widget = node.widgets[node.widgets.findIndex(obj => obj.name === 'category_filter')];
|
||||
|
||||
Object.defineProperty(lora_names_widget.options, "values", {
|
||||
set: (x) => {
|
||||
full_lora_list = x;
|
||||
},
|
||||
get: () => {
|
||||
if(category_filter_widget.value == 'All')
|
||||
return full_lora_list;
|
||||
|
||||
let l = full_lora_list.filter(x => x.startsWith(category_filter_widget.value));
|
||||
return l;
|
||||
}
|
||||
});
|
||||
|
||||
// vector selector
|
||||
let preset_i = 9;
|
||||
let vector_i = 10;
|
||||
node._value = "Preset";
|
||||
|
||||
node.widgets[preset_i].callback = (v, canvas, node, pos, e) => {
|
||||
let value = node._value;
|
||||
if(!value.startsWith('@') && node.widgets[vector_i].value != "")
|
||||
node.widgets[vector_i].value += "\n";
|
||||
if(value.startsWith('@')) {
|
||||
let spec = value.split(':')[1];
|
||||
var n;
|
||||
var sub_n = null;
|
||||
var block = null;
|
||||
|
||||
if(isNaN(spec)) {
|
||||
let sub_spec = spec.split(',');
|
||||
|
||||
if(sub_spec.length != 3) {
|
||||
node.widgets_values[vector_i] = '!! SPEC ERROR !!';
|
||||
node._value = '';
|
||||
return;
|
||||
}
|
||||
|
||||
n = parseInt(sub_spec[0].trim());
|
||||
sub_n = parseInt(sub_spec[1].trim());
|
||||
block = parseInt(sub_spec[2].trim());
|
||||
}
|
||||
else {
|
||||
n = parseInt(spec.trim());
|
||||
}
|
||||
|
||||
node.widgets[vector_i].value = "";
|
||||
if(sub_n == null) {
|
||||
for(let i=1; i<=n; i++) {
|
||||
var temp = "";
|
||||
for(let j=1; j<=n; j++) {
|
||||
if(temp!='')
|
||||
temp += ',';
|
||||
if(j==i)
|
||||
temp += 'A';
|
||||
else
|
||||
temp += '0';
|
||||
}
|
||||
|
||||
node.widgets[vector_i].value += `B${i}:${temp}\n`;
|
||||
}
|
||||
}
|
||||
else {
|
||||
for(let i=1; i<=sub_n; i++) {
|
||||
var temp = "";
|
||||
for(let j=1; j<=n; j++) {
|
||||
if(temp!='')
|
||||
temp += ',';
|
||||
|
||||
if(block!=j)
|
||||
temp += '0';
|
||||
else {
|
||||
temp += ' ';
|
||||
for(let k=1; k<=sub_n; k++) {
|
||||
if(k==i)
|
||||
temp += 'A ';
|
||||
else
|
||||
temp += '0 ';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
node.widgets[vector_i].value += `B${block}.SUB${i}:${temp}\n`;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
node.widgets[vector_i].value += `${value}/${value.split(':')[0]}`;
|
||||
}
|
||||
if(node.widgets_values) {
|
||||
node.widgets_values[vector_i] = node.widgets[preset_i].value;
|
||||
}
|
||||
}
|
||||
|
||||
Object.defineProperty(node.widgets[preset_i], "value", {
|
||||
set: (value) => {
|
||||
if(value != 'Preset')
|
||||
node._value = value;
|
||||
},
|
||||
get: () => {
|
||||
return node._value;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
76
custom_nodes/comfyui-inspire-pack/js/progress-badge.js
Normal file
76
custom_nodes/comfyui-inspire-pack/js/progress-badge.js
Normal file
@@ -0,0 +1,76 @@
|
||||
import { api } from "../../scripts/api.js";
|
||||
|
||||
// copying from https://github.com/pythongosssss/ComfyUI-WD14-Tagger
|
||||
class InspireProgressBadge {
|
||||
constructor() {
|
||||
if (!window.__progress_badge__) {
|
||||
window.__progress_badge__ = Symbol("__inspire_progress_badge__");
|
||||
}
|
||||
this.symbol = window.__progress_badge__;
|
||||
}
|
||||
|
||||
getState(node) {
|
||||
return node[this.symbol] || {};
|
||||
}
|
||||
|
||||
setState(node, state) {
|
||||
node[this.symbol] = state;
|
||||
app.canvas.setDirty(true);
|
||||
}
|
||||
|
||||
addStatusHandler(nodeType) {
|
||||
if (nodeType[this.symbol]?.statusTagHandler) {
|
||||
return;
|
||||
}
|
||||
if (!nodeType[this.symbol]) {
|
||||
nodeType[this.symbol] = {};
|
||||
}
|
||||
nodeType[this.symbol] = {
|
||||
statusTagHandler: true,
|
||||
};
|
||||
|
||||
api.addEventListener("inspire/update_status", ({ detail }) => {
|
||||
let { node, progress, text } = detail;
|
||||
const n = app.graph.getNodeById(+(node || app.runningNodeId));
|
||||
if (!n) return;
|
||||
const state = this.getState(n);
|
||||
state.status = Object.assign(state.status || {}, { progress: text ? progress : null, text: text || null });
|
||||
this.setState(n, state);
|
||||
});
|
||||
|
||||
const self = this;
|
||||
const onDrawForeground = nodeType.prototype.onDrawForeground;
|
||||
nodeType.prototype.onDrawForeground = function (ctx) {
|
||||
const r = onDrawForeground?.apply?.(this, arguments);
|
||||
const state = self.getState(this);
|
||||
if (!state?.status?.text) {
|
||||
return r;
|
||||
}
|
||||
|
||||
const { fgColor, bgColor, text, progress, progressColor } = { ...state.status };
|
||||
|
||||
ctx.save();
|
||||
ctx.font = "12px sans-serif";
|
||||
const sz = ctx.measureText(text);
|
||||
ctx.fillStyle = bgColor || "dodgerblue";
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(0, -LiteGraph.NODE_TITLE_HEIGHT - 20, sz.width + 12, 20, 5);
|
||||
ctx.fill();
|
||||
|
||||
if (progress) {
|
||||
ctx.fillStyle = progressColor || "green";
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(0, -LiteGraph.NODE_TITLE_HEIGHT - 20, (sz.width + 12) * progress, 20, 5);
|
||||
ctx.fill();
|
||||
}
|
||||
|
||||
ctx.fillStyle = fgColor || "#fff";
|
||||
ctx.fillText(text, 6, -LiteGraph.NODE_TITLE_HEIGHT - 6);
|
||||
ctx.restore();
|
||||
return r;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const inspireProgressBadge = new InspireProgressBadge();
|
||||
|
||||
339
custom_nodes/comfyui-inspire-pack/js/prompt.js
Normal file
339
custom_nodes/comfyui-inspire-pack/js/prompt.js
Normal file
@@ -0,0 +1,339 @@
|
||||
import { ComfyApp, app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
|
||||
let get_wildcards_list;
|
||||
let get_wildcard_label;
|
||||
let is_wildcard_label;
|
||||
let load_wildcard_status;
|
||||
|
||||
try {
|
||||
const ImpactPack = await import("../ComfyUI-Impact-Pack/impact-pack.js");
|
||||
console.log("[Inspire Pack] Impact Pack module loaded:", ImpactPack);
|
||||
get_wildcards_list = ImpactPack.get_wildcards_list;
|
||||
get_wildcard_label = ImpactPack.get_wildcard_label;
|
||||
is_wildcard_label = ImpactPack.is_wildcard_label;
|
||||
load_wildcard_status = ImpactPack.load_wildcard_status;
|
||||
console.log("[Inspire Pack] Functions imported:", {
|
||||
get_wildcards_list: !!get_wildcards_list,
|
||||
get_wildcard_label: !!get_wildcard_label,
|
||||
is_wildcard_label: !!is_wildcard_label,
|
||||
load_wildcard_status: !!load_wildcard_status
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
console.error("[Inspire Pack] Failed to import Impact Pack module:", error);
|
||||
}
|
||||
|
||||
// Fallback for get_wildcards_list
|
||||
if(!get_wildcards_list) {
|
||||
console.warn("[Inspire Pack] get_wildcards_list not available. Using fallback.");
|
||||
get_wildcards_list = () => {
|
||||
return ["Impact Pack isn't installed or needs browser cache refresh."];
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback for on-demand features (backward compatibility with older Impact Pack)
|
||||
if(!get_wildcard_label) {
|
||||
get_wildcard_label = () => { return "Select the Wildcard to add to the text"; };
|
||||
}
|
||||
if(!is_wildcard_label) {
|
||||
is_wildcard_label = (value) => { return value === "Select the Wildcard to add to the text"; };
|
||||
}
|
||||
if(!load_wildcard_status) {
|
||||
load_wildcard_status = async () => {}; // No-op for older versions
|
||||
}
|
||||
|
||||
let pb_cache = {};
|
||||
|
||||
async function get_prompt_builder_items(category) {
|
||||
if(pb_cache[category])
|
||||
return pb_cache[category];
|
||||
else {
|
||||
let res = await api.fetchApi(`/inspire/prompt_builder?category=${category}`);
|
||||
let data = await res.json();
|
||||
pb_cache[category] = data.presets;
|
||||
return data.presets;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
app.registerExtension({
|
||||
name: "Comfy.Inspire.Prompts",
|
||||
|
||||
nodeCreated(node, app) {
|
||||
if(node.comfyClass == "WildcardEncode //Inspire") {
|
||||
const wildcard_text_widget_index = node.widgets.findIndex((w) => w.name == 'wildcard_text');
|
||||
const populated_text_widget_index = node.widgets.findIndex((w) => w.name == 'populated_text');
|
||||
const mode_widget_index = node.widgets.findIndex((w) => w.name == 'mode');
|
||||
|
||||
const wildcard_text_widget = node.widgets[wildcard_text_widget_index];
|
||||
const populated_text_widget = node.widgets[populated_text_widget_index];
|
||||
|
||||
// lora selector, wildcard selector
|
||||
let combo_id = 5;
|
||||
|
||||
// lora
|
||||
node.widgets[combo_id].callback = (value, canvas, node, pos, e) => {
|
||||
let lora_name = node._value;
|
||||
if(lora_name.endsWith('.safetensors')) {
|
||||
lora_name = lora_name.slice(0, -12);
|
||||
}
|
||||
|
||||
wildcard_text_widget.value += `<lora:${lora_name}>`;
|
||||
}
|
||||
|
||||
Object.defineProperty(node.widgets[combo_id], "value", {
|
||||
set: (value) => {
|
||||
if (value !== "Select the LoRA to add to the text")
|
||||
node._value = value;
|
||||
},
|
||||
|
||||
get: () => { return "Select the LoRA to add to the text"; }
|
||||
});
|
||||
|
||||
// wildcard
|
||||
node.widgets[combo_id+1].callback = async (value, canvas, node, pos, e) => {
|
||||
if(wildcard_text_widget.value != '')
|
||||
wildcard_text_widget.value += ', '
|
||||
|
||||
wildcard_text_widget.value += node._wildcard_value;
|
||||
|
||||
// Reload wildcard status to update loaded count (Impact Pack staged feature)
|
||||
await load_wildcard_status();
|
||||
app.canvas.setDirty(true);
|
||||
}
|
||||
|
||||
Object.defineProperty(node.widgets[combo_id+1], "value", {
|
||||
set: (value) => {
|
||||
if (!is_wildcard_label(value))
|
||||
node._wildcard_value = value;
|
||||
},
|
||||
get: () => { return get_wildcard_label(); }
|
||||
});
|
||||
|
||||
Object.defineProperty(node.widgets[combo_id+1].options, "values", {
|
||||
set: (x) => {},
|
||||
get: () => {
|
||||
return get_wildcards_list();
|
||||
}
|
||||
});
|
||||
|
||||
// Preventing validation errors from occurring in any situation.
|
||||
node.widgets[combo_id].serializeValue = () => { return "Select the LoRA to add to the text"; }
|
||||
node.widgets[combo_id+1].serializeValue = () => {
|
||||
// Always serialize as the default label (not the dynamic on-demand label)
|
||||
return "Select the Wildcard to add to the text";
|
||||
}
|
||||
|
||||
// wildcard populating
|
||||
populated_text_widget.inputEl.disabled = true;
|
||||
const mode_widget = node.widgets[mode_widget_index];
|
||||
|
||||
// mode combo
|
||||
Object.defineProperty(mode_widget, "value", {
|
||||
set: (value) => {
|
||||
if(value == true)
|
||||
node._mode_value = "populate";
|
||||
else if(value == false)
|
||||
node._mode_value = "fixed";
|
||||
else
|
||||
node._mode_value = value; // combo value
|
||||
|
||||
populated_text_widget.inputEl.disabled = node._mode_value == 'populate';
|
||||
},
|
||||
get: () => {
|
||||
if(node._mode_value != undefined)
|
||||
return node._mode_value;
|
||||
else
|
||||
return 'populate';
|
||||
}
|
||||
});
|
||||
}
|
||||
else if(node.comfyClass == "MakeBasicPipe //Inspire") {
|
||||
const pos_wildcard_text_widget = node.widgets.find((w) => w.name == 'positive_wildcard_text');
|
||||
const pos_populated_text_widget = node.widgets.find((w) => w.name == 'positive_populated_text');
|
||||
const neg_wildcard_text_widget = node.widgets.find((w) => w.name == 'negative_wildcard_text');
|
||||
const neg_populated_text_widget = node.widgets.find((w) => w.name == 'negative_populated_text');
|
||||
|
||||
const mode_widget = node.widgets.find((w) => w.name == 'wildcard_mode');
|
||||
const direction_widget = node.widgets.find((w) => w.name == 'Add selection to');
|
||||
|
||||
// lora selector, wildcard selector
|
||||
let combo_id = 5;
|
||||
|
||||
node.widgets[combo_id].callback = (value, canvas, node, pos, e) => {
|
||||
let lora_name = node._lora_value;
|
||||
if (lora_name.endsWith('.safetensors')) {
|
||||
lora_name = lora_name.slice(0, -12);
|
||||
}
|
||||
|
||||
if(direction_widget.value) {
|
||||
pos_wildcard_text_widget.value += `<lora:${lora_name}>`;
|
||||
}
|
||||
else {
|
||||
neg_wildcard_text_widget.value += `<lora:${lora_name}>`;
|
||||
}
|
||||
}
|
||||
Object.defineProperty(node.widgets[combo_id], "value", {
|
||||
set: (value) => {
|
||||
if (value !== "Select the LoRA to add to the text")
|
||||
node._lora_value = value;
|
||||
},
|
||||
get: () => { return "Select the LoRA to add to the text"; }
|
||||
});
|
||||
|
||||
node.widgets[combo_id+1].callback = async (value, canvas, node, pos, e) => {
|
||||
let w = null;
|
||||
if(direction_widget.value) {
|
||||
w = pos_wildcard_text_widget;
|
||||
}
|
||||
else {
|
||||
w = neg_wildcard_text_widget;
|
||||
}
|
||||
|
||||
if(w.value != '')
|
||||
w.value += ', '
|
||||
|
||||
w.value += node._wildcard_value;
|
||||
|
||||
// Reload wildcard status to update loaded count (Impact Pack staged feature)
|
||||
await load_wildcard_status();
|
||||
app.canvas.setDirty(true);
|
||||
}
|
||||
|
||||
Object.defineProperty(node.widgets[combo_id+1], "value", {
|
||||
set: (value) => {
|
||||
if (!is_wildcard_label(value))
|
||||
node._wildcard_value = value;
|
||||
},
|
||||
get: () => { return get_wildcard_label(); }
|
||||
});
|
||||
|
||||
Object.defineProperty(node.widgets[combo_id+1].options, "values", {
|
||||
set: (x) => {},
|
||||
get: () => {
|
||||
return get_wildcards_list();
|
||||
}
|
||||
});
|
||||
|
||||
// Preventing validation errors from occurring in any situation.
|
||||
node.widgets[combo_id].serializeValue = () => { return "Select the LoRA to add to the text"; }
|
||||
node.widgets[combo_id+1].serializeValue = () => {
|
||||
// Always serialize as the default label (not the dynamic on-demand label)
|
||||
return "Select the Wildcard to add to the text";
|
||||
}
|
||||
|
||||
// wildcard populating
|
||||
pos_populated_text_widget.inputEl.disabled = true;
|
||||
neg_populated_text_widget.inputEl.disabled = true;
|
||||
|
||||
// mode combo
|
||||
Object.defineProperty(mode_widget, "value", {
|
||||
set: (value) => {
|
||||
if(value == true)
|
||||
node._mode_value = "populate";
|
||||
else if(value == false)
|
||||
node._mode_value = "fixed";
|
||||
else
|
||||
node._mode_value = value; // combo value
|
||||
|
||||
pos_populated_text_widget.inputEl.disabled = node._mode_value == 'populate';
|
||||
neg_populated_text_widget.inputEl.disabled = node._mode_value == 'populate';
|
||||
},
|
||||
get: () => {
|
||||
if(node._mode_value != undefined)
|
||||
return node._mode_value;
|
||||
else
|
||||
return 'populate';
|
||||
}
|
||||
});
|
||||
}
|
||||
else if(node.comfyClass == "PromptBuilder //Inspire") {
|
||||
const preset_widget = node.widgets[node.widgets.findIndex(obj => obj.name === 'preset')];
|
||||
const category_widget = node.widgets[node.widgets.findIndex(obj => obj.name === 'category')];
|
||||
|
||||
Object.defineProperty(preset_widget.options, "values", {
|
||||
set: (x) => {},
|
||||
get: () => {
|
||||
get_prompt_builder_items(category_widget.value);
|
||||
if(pb_cache[category_widget.value] == undefined) {
|
||||
return ["#PRESET"];
|
||||
}
|
||||
return pb_cache[category_widget.value];
|
||||
}
|
||||
});
|
||||
|
||||
preset_widget.callback = (value, canvas, node, pos, e) => {
|
||||
if(node.widgets[2].value) {
|
||||
node.widgets[2].value += ', ';
|
||||
}
|
||||
|
||||
const y = node._preset_value.split(':');
|
||||
if(y.length == 2)
|
||||
node.widgets[2].value += y[1].trim();
|
||||
else
|
||||
node.widgets[2].value += node._preset_value.trim();
|
||||
}
|
||||
|
||||
Object.defineProperty(preset_widget, "value", {
|
||||
set: (value) => {
|
||||
if (value !== "#PRESET")
|
||||
node._preset_value = value;
|
||||
},
|
||||
get: () => { return '#PRESET'; }
|
||||
});
|
||||
|
||||
preset_widget.serializeValue = (workflowNode, widgetIndex) => { return "#PRESET"; };
|
||||
}
|
||||
else if(node.comfyClass == "SeedExplorer //Inspire"
|
||||
|| node.comfyClass == "RegionalSeedExplorerMask //Inspire"
|
||||
|| node.comfyClass == "RegionalSeedExplorerColorMask //Inspire") {
|
||||
const prompt_widget = node.widgets[node.widgets.findIndex(obj => obj.name === 'seed_prompt')];
|
||||
const seed_widget = node.widgets[node.widgets.findIndex(obj => obj.name === 'additional_seed')];
|
||||
const strength_widget = node.widgets[node.widgets.findIndex(obj => obj.name === 'additional_strength')];
|
||||
|
||||
let allow_init_seed = node.comfyClass == "SeedExplorer //Inspire";
|
||||
|
||||
node.addWidget("button", "Add to prompt", null, () => {
|
||||
if(!prompt_widget.value?.trim() && allow_init_seed) {
|
||||
prompt_widget.value = ''+seed_widget.value;
|
||||
}
|
||||
else {
|
||||
if(prompt_widget.value?.trim())
|
||||
prompt_widget.value += ', ';
|
||||
|
||||
prompt_widget.value += `${seed_widget.value}:${strength_widget.value.toFixed(2)}`;
|
||||
seed_widget.value += 1;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
const original_queuePrompt = api.queuePrompt;
|
||||
async function queuePrompt_with_widget_idxs(number, { output, workflow }, ...args) {
|
||||
workflow.widget_idx_map = {};
|
||||
|
||||
for(let i in app.graph._nodes_by_id) {
|
||||
let widgets = app.graph._nodes_by_id[i].widgets;
|
||||
if(widgets) {
|
||||
for(let j in widgets) {
|
||||
if(['seed', 'noise_seed', 'sampler_name', 'scheduler'].includes(widgets[j].name)
|
||||
&& widgets[j].type != 'converted-widget') {
|
||||
if(workflow.widget_idx_map[i] == undefined) {
|
||||
workflow.widget_idx_map[i] = {};
|
||||
}
|
||||
|
||||
workflow.widget_idx_map[i][widgets[j].name] = parseInt(j);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return await original_queuePrompt.call(api, number, { output, workflow }, ...args);
|
||||
}
|
||||
|
||||
api.queuePrompt = queuePrompt_with_widget_idxs;
|
||||
64
custom_nodes/comfyui-inspire-pack/js/regional.js
Normal file
64
custom_nodes/comfyui-inspire-pack/js/regional.js
Normal file
@@ -0,0 +1,64 @@
|
||||
import { ComfyApp, app } from "../../scripts/app.js";
|
||||
import { ComfyDialog, $el } from "../../scripts/ui.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
|
||||
app.registerExtension({
|
||||
name: "Comfy.Inspire.Regional",
|
||||
async beforeRegisterNodeDef(nodeType, nodeData, app) {
|
||||
if (nodeData.name === 'ApplyRegionalIPAdapters //Inspire') {
|
||||
var input_name = "input";
|
||||
var base_slot = 0;
|
||||
|
||||
switch(nodeData.name) {
|
||||
case 'ApplyRegionalIPAdapters //Inspire':
|
||||
input_name = "regional_ipadapter";
|
||||
base_slot = 1;
|
||||
break;
|
||||
}
|
||||
|
||||
const onConnectionsChange = nodeType.prototype.onConnectionsChange;
|
||||
nodeType.prototype.onConnectionsChange = function (type, index, connected, link_info) {
|
||||
if(!link_info || type == 2)
|
||||
return;
|
||||
|
||||
if(this.inputs[0].type == '*'){
|
||||
const node = app.graph.getNodeById(link_info.origin_id);
|
||||
let origin_type = node.outputs[link_info.origin_slot].type;
|
||||
|
||||
if(origin_type == '*') {
|
||||
this.disconnectInput(link_info.target_slot);
|
||||
return;
|
||||
}
|
||||
|
||||
for(let i in this.inputs) {
|
||||
let input_i = this.inputs[i];
|
||||
if(input_i.name != 'select' && input_i.name != 'sel_mode')
|
||||
input_i.type = origin_type;
|
||||
}
|
||||
}
|
||||
|
||||
if (!connected && (this.inputs.length > base_slot+1)) {
|
||||
const stackTrace = new Error().stack;
|
||||
|
||||
if(
|
||||
!stackTrace.includes('LGraphNode.prototype.connect') && // for touch device
|
||||
!stackTrace.includes('LGraphNode.connect') && // for mouse device
|
||||
!stackTrace.includes('loadGraphData')) {
|
||||
this.removeInput(index);
|
||||
}
|
||||
}
|
||||
|
||||
let slot_i = 1;
|
||||
for (let i = base_slot; i < this.inputs.length; i++) {
|
||||
let input_i = this.inputs[i];
|
||||
input_i.name = `${input_name}${slot_i}`
|
||||
slot_i++;
|
||||
}
|
||||
|
||||
let last_slot = this.inputs[this.inputs.length - 1];
|
||||
if (last_slot.link != undefined) {
|
||||
this.addInput(`${input_name}${slot_i}`, this.inputs[base_slot].type);
|
||||
}
|
||||
}
|
||||
}
|
||||
}});
|
||||
28
custom_nodes/comfyui-inspire-pack/js/seed.js
Normal file
28
custom_nodes/comfyui-inspire-pack/js/seed.js
Normal file
@@ -0,0 +1,28 @@
|
||||
import { api } from "../../scripts/api.js";
|
||||
|
||||
function globalSeedHandler(event) {
|
||||
let nodes = app.graph._nodes_by_id;
|
||||
|
||||
for(let i in nodes) {
|
||||
let node = nodes[i];
|
||||
|
||||
if(node.type == 'GlobalSeed //Inspire') {
|
||||
if(node.widgets) {
|
||||
const w = node.widgets.find((w) => w.name == 'value');
|
||||
const last_w = node.widgets.find((w) => w.name == 'last_seed');
|
||||
last_w.value = w.value;
|
||||
if(event.detail.value != null)
|
||||
w.value = event.detail.value;
|
||||
}
|
||||
}
|
||||
else
|
||||
if(node.widgets) {
|
||||
const w = node.widgets.find((w) => (w.name == 'seed' || w.name == 'noise_seed') && w.type == 'number');
|
||||
if(w && event.detail.seed_map[node.id] != undefined) {
|
||||
w.value = event.detail.seed_map[node.id];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
api.addEventListener("inspire-global-seed", globalSeedHandler);
|
||||
@@ -0,0 +1,2 @@
|
||||
positive:beautiful scenery nature glass bottle landscape, , purple galaxy bottle,
|
||||
negative:text, watermark
|
||||
@@ -0,0 +1,12 @@
|
||||
positive:1girl is walking through street,
|
||||
raincoat, yellow umbrella
|
||||
|
||||
negative:text, watermark
|
||||
-----------------
|
||||
positive:museum, people are looking paintings, abstract
|
||||
|
||||
negative:text, watermark
|
||||
----
|
||||
positive:battle ground of space ships
|
||||
|
||||
negative:text, watermark
|
||||
15
custom_nodes/comfyui-inspire-pack/pyproject.toml
Normal file
15
custom_nodes/comfyui-inspire-pack/pyproject.toml
Normal file
@@ -0,0 +1,15 @@
|
||||
[project]
|
||||
name = "comfyui-inspire-pack"
|
||||
description = "This extension provides various nodes to support Lora Block Weight, Regional Nodes, Backend Cache, Prompt Utils, List Utils, Noise(Seed) Utils, ... and the Impact Pack."
|
||||
version = "1.23"
|
||||
license = { file = "LICENSE" }
|
||||
dependencies = ["matplotlib", "cachetools"]
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/ltdrdata/ComfyUI-Inspire-Pack"
|
||||
# Used by Comfy Registry https://comfyregistry.org
|
||||
|
||||
[tool.comfy]
|
||||
PublisherId = "drltdata"
|
||||
DisplayName = "ComfyUI Inspire Pack"
|
||||
Icon = ""
|
||||
5
custom_nodes/comfyui-inspire-pack/requirements.txt
Normal file
5
custom_nodes/comfyui-inspire-pack/requirements.txt
Normal file
@@ -0,0 +1,5 @@
|
||||
matplotlib
|
||||
cachetools
|
||||
numpy
|
||||
webcolors
|
||||
opencv-python
|
||||
@@ -0,0 +1,20 @@
|
||||
SD-BODY:1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1
|
||||
SD-BODY0.5:1,1,1,1,1,1,0.2,1,0.2,0,0,0.8,1,1,1,1,1
|
||||
SD-FACE:1,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0
|
||||
SD-FACE0.5:1,0,0,0,0,0,0,0,0.8,1,1,0.2,0,0,0,0,0
|
||||
SD-FACE0.2:1,0,0,0,0,0,0,0,0.2,0.6,0.8,0.2,0,0,0,0,0
|
||||
SD-HAND:1,0,1,1,0.2,0,0,0,0,0,0,0,0,0,0,0,0
|
||||
SD-CLOTHING:1,1,1,1,1,0,0.2,0,0.8,1,1,0.2,0,0,0,0,0
|
||||
SD-POSE:1,0,0,0,0,0,0.2,1,1,1,0,0,0,0,0,0,0
|
||||
SD-PALETTE:1,0,0,0,0,0,0,0,0,0,0,0.8,1,1,1,1,1
|
||||
SD-KEEPCHAR:1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,0,0
|
||||
SD-KEEPBG:1,1,1,1,1,1,0.2,1,0.2,0,0,0.8,1,1,1,0,0
|
||||
SD-REDUCEFIT:1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1
|
||||
SD-LyCOBODY:1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1,1
|
||||
SD-LyCOBODY0.5:1,1,1,1,1,1,1,1,1,0.2,0.2,0.5,1,1,0,0,0,0.2,0,0,0.8,1,1,1,1
|
||||
SD-LyCOFACE:1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,0,0,0,0,0
|
||||
SD-LyCOFACE0.5:1,0,0,0,0,0,0,0,0,0,0,0,0,0,0.2,0.5,0.8,1,1,1,0.2,0,0,0,0,0
|
||||
SD-LyCOCLOTH:1,1,1,1,1,1,1,1,0,0.2,0.2,0.2,0,0,0,0,0.5,0.8,1,1,0.2,0,0,0,0,0
|
||||
SD-LyCOPOSE:1,0,0,0,0,0,0,0,0,0.2,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0
|
||||
SD-LyCOKEEPBG:1,1,1,1,1,1,1,1,1,0.2,0.4,0.8,1,1,0.8,0.4,0.2,0.2,0,0,0.8,1,1,1,0,0
|
||||
SD-LyCOPALETTE:1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.8,1,1,1,1,1
|
||||
122
custom_nodes/comfyui-inspire-pack/resources/lbw-preset.txt
Normal file
122
custom_nodes/comfyui-inspire-pack/resources/lbw-preset.txt
Normal file
@@ -0,0 +1,122 @@
|
||||
SD-NONE:0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
|
||||
SD-ALL:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
|
||||
SD-INS:1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0
|
||||
SD-IND:1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0
|
||||
SD-INALL:1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0
|
||||
SD-MIDD:1,0,0,0,1,1,1,1,1,1,1,1,0,0,0,0,0
|
||||
SD-MIDD0.2:1,0,0,0,0,0,0.2,0.4,0.4,0.2,0,0,0,0,0,0,0
|
||||
SD-MIDD0.8:1,0,0,0,0,0.5,0.8,0.8,0.4,0,0,0,0,0,0,0,0
|
||||
SD-MOUT:1,0,0,0,0,0,1,1,1,1,1,1,1,1,0.5,0,0
|
||||
SD-OUTD:1,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0
|
||||
SD-OUTS:1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1
|
||||
SD-OUTALL:1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1
|
||||
SD-ROUT:1,1,1,1,1,1,1,1,R,R,R,R,R,R,R,R,R
|
||||
SD-AOUT:A,1,1,1,1,1,1,1,1,1,1,1,A,A,A,A,A
|
||||
SD-AB:A,B,B,B,B,B,B,B,B,B,B,B,A,A,A,A,A
|
||||
SD-ALL0.5:0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5
|
||||
SD-LyC-NONE:0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
|
||||
SD-LyC-ALL:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
|
||||
SD-LyC-INALL:1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
|
||||
SD-LyC-MIDALL:1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0
|
||||
SD-LyC-OUTALL:1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1
|
||||
SDXL-NONE:0,0,0,0,0,0,0,0,0,0,0,0
|
||||
SDXL-ALL:1,1,1,1,1,1,1,1,1,1,1,1
|
||||
SDXL-INALL:1,1,1,1,1,0,0,0,0,0,0,0
|
||||
SDXL-MIDALL:1,0,0,0,0,1,0,0,0,0,0,0
|
||||
SDXL-OUTALL:1,0,0,0,0,0,1,1,1,1,1,1
|
||||
SDXL-LyC-NONE:0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
|
||||
SDXL-LyC-ALL:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
|
||||
SDXL-LyC-INALL:1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0
|
||||
SDXL-LyC-MIDALL:1,0,0,0,0,0,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0
|
||||
SDXL-LyC-OUTALL:1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1
|
||||
FLUX-DBL-ALL:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
|
||||
FLUX-DBL-FRONT7:1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0
|
||||
FLUX-DBL-MID6:1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0
|
||||
FLUX-DBL-TAIL6:1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1
|
||||
FLUX-SINGLE-ALL:1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
|
||||
FLUX-SINGLE-1to10:1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
|
||||
FLUX-SINGLE-11to20:1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
|
||||
FLUX-SINGLE-21to30:1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0
|
||||
FLUX-SINGLE-31to37:1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1
|
||||
FLUX-ALL:1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
|
||||
@SD-FULL-TEST:17
|
||||
@SD-BLOCK1-TEST:17,12,1
|
||||
@SD-BLOCK2-TEST:17,12,2
|
||||
@SD-BLOCK3-TEST:17,12,3
|
||||
@SD-BLOCK4-TEST:17,12,4
|
||||
@SD-BLOCK5-TEST:17,12,5
|
||||
@SD-BLOCK6-TEST:17,12,6
|
||||
@SD-BLOCK7-TEST:17,12,7
|
||||
@SD-BLOCK8-TEST:17,12,8
|
||||
@SD-BLOCK9-TEST:17,12,9
|
||||
@SD-BLOCK10-TEST:17,12,10
|
||||
@SD-BLOCK11-TEST:17,12,11
|
||||
@SD-BLOCK12-TEST:17,12,12
|
||||
@SD-BLOCK13-TEST:17,12,13
|
||||
@SD-BLOCK14-TEST:17,12,14
|
||||
@SD-BLOCK15-TEST:17,12,15
|
||||
@SD-BLOCK16-TEST:17,12,16
|
||||
@SD-BLOCK17-TEST:17,12,17
|
||||
@SD-LyC-FULL-TEST:27
|
||||
@SDXL-FULL-TEST:12
|
||||
@SDXL-LyC-FULL-TEST:21
|
||||
@FLUX-DBL-FULL:19
|
||||
@FLUX-DBL-SGL-FULL:58
|
||||
@FLUX-DBL0-TEST:19,14,2
|
||||
@FLUX-DBL1-TEST:19,14,3
|
||||
@FLUX-DBL2-TEST:19,14,4
|
||||
@FLUX-DBL3-TEST:19,14,5
|
||||
@FLUX-DBL4-TEST:19,14,6
|
||||
@FLUX-DBL5-TEST:19,14,7
|
||||
@FLUX-DBL6-TEST:19,14,8
|
||||
@FLUX-DBL7-TEST:19,14,9
|
||||
@FLUX-DBL8-TEST:19,14,10
|
||||
@FLUX-DBL9-TEST:19,14,11
|
||||
@FLUX-DBL10-TEST:19,14,12
|
||||
@FLUX-DBL11-TEST:19,14,13
|
||||
@FLUX-DBL12-TEST:19,14,14
|
||||
@FLUX-DBL13-TEST:19,14,15
|
||||
@FLUX-DBL14-TEST:19,14,16
|
||||
@FLUX-DBL15-TEST:19,14,17
|
||||
@FLUX-DBL16-TEST:19,14,18
|
||||
@FLUX-DBL17-TEST:19,14,19
|
||||
@FLUX-DBL18-TEST:19,14,20
|
||||
@FLUX-SGL0-TEST:58,6,21
|
||||
@FLUX-SGL1-TEST:58,6,22
|
||||
@FLUX-SGL2-TEST:58,6,23
|
||||
@FLUX-SGL3-TEST:58,6,24
|
||||
@FLUX-SGL4-TEST:58,6,25
|
||||
@FLUX-SGL5-TEST:58,6,26
|
||||
@FLUX-SGL6-TEST:58,6,27
|
||||
@FLUX-SGL7-TEST:58,6,28
|
||||
@FLUX-SGL8-TEST:58,6,29
|
||||
@FLUX-SGL9-TEST:58,6,30
|
||||
@FLUX-SGL10-TEST:58,6,31
|
||||
@FLUX-SGL11-TEST:58,6,32
|
||||
@FLUX-SGL12-TEST:58,6,33
|
||||
@FLUX-SGL13-TEST:58,6,34
|
||||
@FLUX-SGL14-TEST:58,6,35
|
||||
@FLUX-SGL15-TEST:58,6,36
|
||||
@FLUX-SGL16-TEST:58,6,37
|
||||
@FLUX-SGL17-TEST:58,6,38
|
||||
@FLUX-SGL18-TEST:58,6,39
|
||||
@FLUX-SGL19-TEST:58,6,40
|
||||
@FLUX-SGL20-TEST:58,6,41
|
||||
@FLUX-SGL21-TEST:58,6,42
|
||||
@FLUX-SGL22-TEST:58,6,43
|
||||
@FLUX-SGL23-TEST:58,6,44
|
||||
@FLUX-SGL24-TEST:58,6,45
|
||||
@FLUX-SGL25-TEST:58,6,46
|
||||
@FLUX-SGL26-TEST:58,6,47
|
||||
@FLUX-SGL27-TEST:58,6,48
|
||||
@FLUX-SGL28-TEST:58,6,49
|
||||
@FLUX-SGL29-TEST:58,6,50
|
||||
@FLUX-SGL30-TEST:58,6,51
|
||||
@FLUX-SGL31-TEST:58,6,52
|
||||
@FLUX-SGL32-TEST:58,6,53
|
||||
@FLUX-SGL33-TEST:58,6,54
|
||||
@FLUX-SGL34-TEST:58,6,55
|
||||
@FLUX-SGL35-TEST:58,6,56
|
||||
@FLUX-SGL36-TEST:58,6,57
|
||||
@FLUX-SGL37-TEST:58,6,58
|
||||
@FLUX-SGL38-TEST:58,6,59
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user