Initial commit

This commit is contained in:
TK3R
2026-02-14 09:46:46 -05:00
commit f7a70d74a0
30 changed files with 2600 additions and 0 deletions
+39
View File
@@ -0,0 +1,39 @@
name: Lint
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
lint:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
steps:
- uses: actions/checkout@v3
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install flake8 black
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Check formatting with black
run: |
black --check .
+147
View File
@@ -0,0 +1,147 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.pyc
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
pip-wheel-metadata/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
*.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/
# 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
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
.python-version
# pipenv
Pipfile.lock
# PEP 582
__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/
# VS Code
.vscode/
*.code-workspace
# macOS
.DS_Store
.AppleDouble
.LSOverride
# Windows
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
*.stackdump
[Dd]esktop.ini
$RECYCLE.BIN/
*.lnk
# ComfyUI specific
web/extensions/
temp/
+67
View File
@@ -0,0 +1,67 @@
# Contributing to ComfyUI TK3R Extensions
Thank you for considering contributing to ComfyUI TK3R Extensions! This document provides guidelines for contributing to the project.
## How to Contribute
### Reporting Bugs
If you find a bug, please open an issue on GitHub with:
- A clear, descriptive title
- Steps to reproduce the issue
- Expected behavior
- Actual behavior
- Your environment (OS, Python version, ComfyUI version)
- Screenshots if applicable
### Suggesting Enhancements
Enhancement suggestions are welcome! Please open an issue with:
- A clear, descriptive title
- Detailed description of the proposed functionality
- Why this enhancement would be useful
- Examples of how it would be used
### Pull Requests
1. Fork the repository
2. Create a new branch (`git checkout -b feature/amazing-feature`)
3. Make your changes
4. Ensure your code follows the existing style
5. Test your changes thoroughly
6. Commit your changes (`git commit -m 'Add amazing feature'`)
7. Push to the branch (`git push origin feature/amazing-feature`)
8. Open a Pull Request
### Code Style
- Follow PEP 8 guidelines
- Use meaningful variable and function names
- Add comments for complex logic
- Include docstrings for functions and classes
- Keep functions focused and concise
### Testing
- Test your changes with different ComfyUI workflows
- Ensure backward compatibility when possible
- Document any breaking changes clearly
### Documentation
- Update the README.md if you add new features
- Add usage examples for new nodes
- Update the changelog
## Code of Conduct
- Be respectful and constructive
- Welcome newcomers and help them learn
- Focus on what is best for the community
- Show empathy towards other community members
## Questions?
Feel free to open an issue for questions or join the discussion in existing issues.
Thank you for contributing! 🎉
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+116
View File
@@ -0,0 +1,116 @@
# ComfyUI TK3R Extensions
Extended versions of various ComfyUI nodes plus some utility nodes.
## Description
This repository contains custom nodes for ComfyUI that provide extended capabilities beyond the standard nodes as well as some utility nodes.
## Installation
### Method 1: ComfyUI Manager (Recommended)
1. Install [ComfyUI Manager](https://github.com/ltdrdata/ComfyUI-Manager)
2. Search for "TK3R Extensions" in the manager
3. Click Install
### Method 2: Manual Installation
1. Navigate to your ComfyUI custom nodes directory:
```bash
cd ComfyUI/custom_nodes
```
2. Clone this repository:
```bash
git clone https://github.com/TK3R/ComfyUI_TK3R_Ext.git
```
3. Restart ComfyUI
## Usage
After installation, the nodes will appear in ComfyUI under the "TK3R Advanced" and "TK3R Utility" categories. Each node provides specific functionality:
### TK3R ControlNet Apply Advanced
Advanced version of the ControlNet Apply node with a strength decay option. Allows gradual decay of the controlnet strength rather than sharp cutoff. Similar principle as the Qwen/ZImage controlnet nodes, see examples below.
### TK3R Qwen Image Diffsynth ControlNet Advanced / TK3R ZImage Fun Controlnet
Advanced version of the QwenImageDiffsynthControlnet / ZImageFunControlnet nodes with start / stop control as well as strength decay option, allowing significantly more control and making controlnets more useful. For example cutting off the controlnet influence earlier frees the model to fill in finer details, or you can cut off very early so that the controlnet only guides the general composition.
![ControlNet Example Base](assets/tk3r_cn_no_cn.webp)
![ControlNet Example No Stop, No Decay](assets/tk3r_cn_no_stop_no_decay.webp)
![ControlNet Example Stop 0.75, Linear Decay](assets/tk3r_cn_075_stop_linear_decay.webp)
![ControlNet Example Stop 0.65, Inverse Exponential Decay](assets/tk3r_cn_065_stop_invexp_decay.webp)
### TK3R Scheduled CFG Guider
Advanced version of the CFGGuider node allowing per-step CFG scheduling.
![Scheduled CFG Guider](assets/tk3r_scheduled_cfg_guider.png)
git push --force -u origin mainnotes: The schedule is comma separated floats interpolated over the set amount of steps, if you want something like an exponential curve just copy the same values several times; *schedule* output is the CFG schedule for info/debugging reasons, *normalized_schedule* is an output that can be used with a graph node to compare against the sigma schedule of models where the sigmas go 1.0 - 0.0
### TK3R TextEncodeQwenImageEditPlus Ext
An enhanced version of the TextEncodeQwenImageEditPlus node; not my code, but I do not remember where I got it from and it was an overwrite of the default node so I separated it into my nodes.
![TextEncodeQwenImageEditPlus Ext](assets/tk3r_teqiepe.webp)
### TK3R CLIP Text Encode With Token Count
A version of the CLIP Text Encode node showing the character and token count after encoding. Useful for staying within the token count limits of the various encoders. It also merges the lumina2 text encode sysprompt code so there's no need to use a separate node.
![Token Counter](assets/tk3r_te_tokens.webp)
### TK3R Image Compare
This is a small utility node that caches the last input image. I use it together with rgthree Image Comparer to compare the current generation with the previous one. Simply wire the vae decode image output to its image input and output 1 will be the current image and output 2 - the previous one.
![Image Compare](assets/tk3r_image_compare.webp)
### TK3R Lora Rank Reader
A simple utility node that reads a lora and outputs its rank.
![Lora Rank Reader](assets/tk3r_lora_rank_reader.webp)
### TK3R Safetensors Precision Reader
A simple utility node that reads a safetensors file and outputs its floating-point precision.
![Safetensors Precision Reader](assets/tk3r_safetensors_precision_reader.webp)
### TK3R Sigmas Interpolate
A simple utility node that allows blending two sigma schedules with the same step count. Just for fun.
![Sigmas Interpolate](assets/tk3r_sigmas_interpolate.webp)
## License
GPLv3 License same as ComfyUI license as several nodes are derivatives of ComfyUI nodes - See LICENSE file for details
## Credits
- Node loader code adapted from [WAS Extras](https://github.com/WASasquatch/WAS_Extras), thank you [WAS](https://github.com/WASasquatch)
- These nodes are mostly vibe-coded with different Github Copilot agents
## Changelog
### v1.0.0
- Initial release
- TK3R ControlNet Apply Advanced
- TK3R Qwen Image Diffsynth ControlNet Advanced / TK3R ZImage Fun Controlnet
- TK3R Scheduled CFG Guider
- TK3R TextEncodeQwenImageEditPlus Ext
- TK3R CLIP Text Encode With Token Count
- TK3R Image Compare
- TK3r Lora Rank Reader
- TK3R Safetensors Precision Reader
- TK3R Sigmas Interpolate
+139
View File
@@ -0,0 +1,139 @@
# code lifted from WAS Extras, thanks WAS
import importlib
import pkgutil
import time
import traceback
import os
try:
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, TimeElapsedColumn, TextColumn
from rich.traceback import install as rich_traceback_install
console = Console(force_terminal=True, no_color=False)
rich_traceback_install(show_locals=False, word_wrap=True)
except Exception:
console = None
PREFIX = "[TK3R Ext] "
NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
WEB_DIRECTORY = os.path.join(os.path.dirname(__file__), "web")
class NodeLoader:
def __init__(self, package_name: str, prefix: str = PREFIX):
self.package_name = package_name
self.prefix = prefix
self.timings: dict[str, tuple[float, bool, Exception | None]] = {}
def module_path(self, module) -> str:
spec = getattr(module, "__spec__", None)
if spec and getattr(spec, "origin", None):
return spec.origin
return getattr(module, "__file__", repr(module))
def record(self, module, elapsed: float, ok: bool, err: Exception | None) -> None:
self.timings[self.module_path(module)] = (elapsed, ok, err)
if ok:
NODE_CLASS_MAPPINGS.update(getattr(module, "NODE_CLASS_MAPPINGS", {}))
NODE_DISPLAY_NAME_MAPPINGS.update(getattr(module, "NODE_DISPLAY_NAME_MAPPINGS", {}))
def import_module(self, fullname: str, package: str | None = None) -> tuple[object | None, bool]:
t0 = time.time()
ok = True
err = None
mod = None
try:
mod = importlib.import_module(fullname, package=package)
except Exception as e:
ok = False
err = e
if console is None:
traceback.print_exc()
else:
console.print_exception()
elapsed = time.time() - t0
if mod is not None:
self.record(mod, elapsed, ok, err)
return mod, ok
def print_intro(self) -> None:
msg = "A few enhanced vanilla nodes as well as some utility nodes. No warranty."
if console:
# Single rule and a single-titled panel
console.rule(style="cyan")
console.print(Panel(msg, title="TK3R Ext", border_style="cyan"))
else:
print(f"{self.prefix}A few enhanced vanilla nodes as well as some utility nodes. No warranty.")
def print_no_nodes_pkg(self) -> None:
msg = "No ./nodes package found or import failed."
if console:
console.print(f"{self.prefix}[bold yellow]{msg}[/bold yellow]")
else:
print(f"{self.prefix}{msg}")
def print_summary(self) -> None:
total = len(self.timings)
ok_count = sum(1 for _, (_, ok, _) in self.timings.items() if ok)
fail_count = total - ok_count
if console:
table = Table(
expand=False,
header_style="cyan",
border_style="cyan",
)
table.add_column("Module/File", overflow="fold")
table.add_column("Time (s)", justify="right")
table.add_column("Status", justify="center")
table.add_column("Error", overflow="fold")
for path, (timing, success, err) in self.timings.items():
status = "[green]OK[/green]" if success else "[red]FAILED[/red]"
err_text = "" if err is None else f"{type(err).__name__}: {err}"
table.add_row(str(path), f"{timing:.2f}", status, err_text)
console.print(table)
console.print(f"Totals: [green]{ok_count} ok[/green], [red]{fail_count} failed[/red], {total} modules.")
else:
print(f"{self.prefix} Import times:")
for path, (timing, success, err) in self.timings.items():
print(f" {timing:.1f} seconds{('' if success else ' (IMPORT FAILED)')}: {path}")
if err:
print("Error:", err)
print(f"{self.prefix}Totals: {total} modules, {ok_count} ok, {fail_count} failed.")
def load_all(self) -> None:
# self.print_intro()
nodes_pkg, ok = self.import_module(".nodes", package=self.package_name)
if not ok or nodes_pkg is None:
self.print_no_nodes_pkg()
self.print_summary()
return
if console:
with Progress(
SpinnerColumn(style="cyan"),
TextColumn("[progress.description]{task.description}", style="bright_black"),
TimeElapsedColumn(),
console=console,
transient=True,
) as progress:
task = progress.add_task("Loading nodes from ./nodes ...", total=None)
for _, name, _ in pkgutil.walk_packages(nodes_pkg.__path__, prefix=nodes_pkg.__name__ + "."):
self.import_module(name)
progress.remove_task(task)
else:
print("Loading nodes from ./nodes ...")
for _, name, _ in pkgutil.walk_packages(nodes_pkg.__path__, prefix=nodes_pkg.__name__ + "."):
self.import_module(name)
self.print_summary()
_loader = NodeLoader(package_name=__name__, prefix=PREFIX)
_loader.load_all()
__all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 307 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 302 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 311 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 305 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+368
View File
@@ -0,0 +1,368 @@
"""
Custom ControlNet nodes with start/stop percent and decay functionality.
This file contains modified versions of QwenImageDiffsynthControlnet and related classes
that support temporal control with decay modes.
Extracted from comfy_extras/nodes_model_patch.py to preserve custom modifications
after ComfyUI updates.
"""
import math
import torch
import comfy.utils
import comfy.latent_formats
import comfy.model_management
import comfy.ldm.lumina.controlnet
# ============================================================================
# Sigma Window and Decay Utilities
# ============================================================================
SIGMA_EPS = 1e-6
def _clamp_percent(value: float) -> float:
return max(0.0, min(1.0, float(value)))
def _sigma_from_percent(model_sampling, percent: float) -> float:
sigma = model_sampling.percent_to_sigma(percent)
if isinstance(sigma, torch.Tensor):
sigma = float(sigma.detach().cpu())
return float(sigma)
def resolve_sigma_window(model_sampling, start_percent: float, end_percent: float):
start = _clamp_percent(start_percent)
end = _clamp_percent(end_percent)
sigma_start = _sigma_from_percent(model_sampling, start)
sigma_end = _sigma_from_percent(model_sampling, end)
sigma_high = max(sigma_start, sigma_end)
sigma_low = min(sigma_start, sigma_end)
if math.isclose(sigma_high, sigma_low, rel_tol=1e-6, abs_tol=SIGMA_EPS):
sigma_high += SIGMA_EPS
return sigma_low, sigma_high
def current_sigma(transformer_options):
if not isinstance(transformer_options, dict):
return None
sigma_tensor = transformer_options.get("sigmas")
if not isinstance(sigma_tensor, torch.Tensor) or sigma_tensor.numel() == 0:
return None
return float(sigma_tensor.reshape(-1)[0].item())
def sigma_within_window(transformer_options, sigma_low: float, sigma_high: float, sigma_val=None) -> bool:
if sigma_val is None:
sigma_val = current_sigma(transformer_options)
if sigma_val is None:
return True
return (sigma_low - SIGMA_EPS) <= sigma_val <= (sigma_high + SIGMA_EPS)
DECAY_MODES = ["none", "linear", "cosine", "exponential", "inverse_exponential"]
def calculate_strength_multiplier(sigma_val, sigma_low, sigma_high, decay_mode="none"):
"""Calculate strength multiplier based on sigma position within window.
Args:
sigma_val: Current sigma value
sigma_low: Low bound of sigma window (corresponds to stop_percent)
sigma_high: High bound of sigma window (corresponds to start_percent)
decay_mode: One of "none", "linear", "cosine", "exponential", "inverse_exponential"
Returns:
Strength multiplier between 0.0 and 1.0
"""
if sigma_val is None:
return 1.0
# Outside window check
if sigma_val < sigma_low - SIGMA_EPS:
return 0.0
if sigma_val > sigma_high + SIGMA_EPS:
return 0.0 if decay_mode != "none" else 1.0
# No decay - instant cutoff at stop_percent
if decay_mode == "none":
return 1.0
if sigma_high <= sigma_low:
return 1.0
# Calculate normalized position: 1.0 at sigma_high (start), 0.0 at sigma_low (stop)
t = (sigma_val - sigma_low) / (sigma_high - sigma_low)
t = max(0.0, min(1.0, t)) # Clamp to [0, 1]
if decay_mode == "linear":
return t
elif decay_mode == "cosine":
# Smooth S-curve using cosine interpolation
return (1.0 - math.cos(t * math.pi)) / 2.0
elif decay_mode == "exponential":
# Fast decay at start, slow at end (strength drops quickly)
return 1.0 - math.exp(-3.0 * t) / (1.0 - math.exp(-3.0)) if t > 0 else 0.0
elif decay_mode == "inverse_exponential":
# Slow decay at start, fast at end (strength holds longer)
return (math.exp(3.0 * t) - 1.0) / (math.exp(3.0) - 1.0)
else:
return 1.0
# ============================================================================
# Patch Classes with Decay Support
# ============================================================================
class DiffSynthCnetPatch:
def __init__(self, model_patch, vae, image, strength, mask=None, sigma_low: float = float("-inf"), sigma_high: float = float("inf"),
start_percent: float = 0.0, stop_percent: float = 1.0, decay_mode: str = "none"):
self.model_patch = model_patch
self.vae = vae
self.image = image
self.strength = strength
self.mask = mask
self.sigma_low = min(sigma_low, sigma_high)
self.sigma_high = max(sigma_low, sigma_high)
self.start_percent = start_percent
self.stop_percent = stop_percent
self.decay_mode = decay_mode
self.encoded_image = model_patch.model.process_input_latent_image(self.encode_latent_cond(image))
self.encoded_image_size = (image.shape[1], image.shape[2])
def encode_latent_cond(self, image):
latent_image = self.vae.encode(image)
if self.model_patch.model.additional_in_dim > 0:
if self.mask is None:
mask_ = torch.ones_like(latent_image)[:, :self.model_patch.model.additional_in_dim // 4]
else:
mask_ = comfy.utils.common_upscale(self.mask.mean(dim=1, keepdim=True), latent_image.shape[-1], latent_image.shape[-2], "bilinear", "none")
return torch.cat([latent_image, mask_], dim=1)
else:
return latent_image
def __call__(self, kwargs):
transformer_options = kwargs.get("transformer_options")
block_index = kwargs.get("block_index")
sigma_val = current_sigma(transformer_options)
# Calculate strength multiplier based on position in sigma window
strength_mult = calculate_strength_multiplier(sigma_val, self.sigma_low, self.sigma_high, self.decay_mode)
effective_strength = self.strength * strength_mult
if strength_mult <= 0:
return kwargs
x = kwargs.get("x")
img = kwargs.get("img")
spacial_compression = self.vae.spacial_compression_encode()
if self.encoded_image is None or self.encoded_image_size != (x.shape[-2] * spacial_compression, x.shape[-1] * spacial_compression):
image_scaled = comfy.utils.common_upscale(self.image.movedim(-1, 1), x.shape[-1] * spacial_compression, x.shape[-2] * spacial_compression, "area", "center")
loaded_models = comfy.model_management.loaded_models(only_currently_used=True)
self.encoded_image = self.model_patch.model.process_input_latent_image(self.encode_latent_cond(image_scaled.movedim(1, -1)))
self.encoded_image_size = (image_scaled.shape[-2], image_scaled.shape[-1])
comfy.model_management.load_models_gpu(loaded_models)
img[:, :self.encoded_image.shape[1]] += (self.model_patch.model.control_block(img[:, :self.encoded_image.shape[1]], self.encoded_image.to(img.dtype), block_index) * effective_strength)
kwargs['img'] = img
return kwargs
def to(self, device_or_dtype):
if isinstance(device_or_dtype, torch.device):
self.encoded_image = self.encoded_image.to(device_or_dtype)
return self
def models(self):
return [self.model_patch]
class ZImageControlPatch:
def __init__(self, model_patch, vae, image, strength, inpaint_image=None, mask=None, sigma_low: float = float("-inf"), sigma_high: float = float("inf"),
start_percent: float = 0.0, stop_percent: float = 1.0, decay_mode: str = "none"):
self.model_patch = model_patch
self.vae = vae
self.image = image
self.inpaint_image = inpaint_image
self.mask = mask
self.strength = strength
self.sigma_low = min(sigma_low, sigma_high)
self.sigma_high = max(sigma_low, sigma_high)
self.start_percent = start_percent
self.stop_percent = stop_percent
self.decay_mode = decay_mode
self.encoded_image = self.encode_latent_cond(image)
self.encoded_image_size = (image.shape[1], image.shape[2])
self.temp_data = None
def encode_latent_cond(self, control_image, inpaint_image=None):
latent_image = comfy.latent_formats.Flux().process_in(self.vae.encode(control_image))
if self.model_patch.model.additional_in_dim > 0:
if self.mask is None:
mask_ = torch.zeros_like(latent_image)[:, :1]
else:
mask_ = comfy.utils.common_upscale(self.mask.mean(dim=1, keepdim=True), latent_image.shape[-1], latent_image.shape[-2], "bilinear", "none")
if inpaint_image is None:
inpaint_image = torch.ones_like(control_image) * 0.5
inpaint_image_latent = comfy.latent_formats.Flux().process_in(self.vae.encode(inpaint_image))
return torch.cat([latent_image, mask_, inpaint_image_latent], dim=1)
else:
return latent_image
def __call__(self, kwargs):
transformer_options = kwargs.get("transformer_options")
block_index = kwargs.get("block_index")
block_type = kwargs.get("block_type", "")
sigma_val = current_sigma(transformer_options)
# Calculate strength multiplier based on position in sigma window
strength_mult = calculate_strength_multiplier(sigma_val, self.sigma_low, self.sigma_high, self.decay_mode)
effective_strength = self.strength * strength_mult
if strength_mult <= 0:
# Still need to pop img and txt as the original code does
kwargs.pop("img", None)
kwargs.pop("txt", None)
return kwargs
x = kwargs.get("x")
img = kwargs.get("img")
img_input = kwargs.get("img_input")
txt = kwargs.get("txt")
pe = kwargs.get("pe")
vec = kwargs.get("vec")
spacial_compression = self.vae.spacial_compression_encode()
if self.encoded_image is None or self.encoded_image_size != (x.shape[-2] * spacial_compression, x.shape[-1] * spacial_compression):
image_scaled = comfy.utils.common_upscale(self.image.movedim(-1, 1), x.shape[-1] * spacial_compression, x.shape[-2] * spacial_compression, "area", "center")
inpaint_scaled = None
if self.inpaint_image is not None:
inpaint_scaled = comfy.utils.common_upscale(self.inpaint_image.movedim(-1, 1), x.shape[-1] * spacial_compression, x.shape[-2] * spacial_compression, "area", "center").movedim(1, -1)
loaded_models = comfy.model_management.loaded_models(only_currently_used=True)
self.encoded_image = self.encode_latent_cond(image_scaled.movedim(1, -1), inpaint_scaled)
self.encoded_image_size = (image_scaled.shape[-2], image_scaled.shape[-1])
comfy.model_management.load_models_gpu(loaded_models)
cnet_blocks = self.model_patch.model.n_control_layers
div = round(30 / cnet_blocks)
cnet_index = (block_index // div)
cnet_index_float = (block_index / div)
kwargs.pop("img") # we do ops in place
kwargs.pop("txt")
if cnet_index_float > (cnet_blocks - 1):
self.temp_data = None
return kwargs
if self.temp_data is None or self.temp_data[0] > cnet_index:
if block_type == "noise_refiner":
self.temp_data = (-3, (None, self.model_patch.model(txt, self.encoded_image.to(img.dtype), pe, vec)))
else:
self.temp_data = (-1, (None, self.model_patch.model(txt, self.encoded_image.to(img.dtype), pe, vec)))
if block_type == "noise_refiner":
next_layer = self.temp_data[0] + 1
self.temp_data = (next_layer, self.model_patch.model.forward_noise_refiner_block(block_index, self.temp_data[1][1], img_input[:, :self.temp_data[1][1].shape[1]], None, pe, vec))
if self.temp_data[1][0] is not None:
img[:, :self.temp_data[1][0].shape[1]] += (self.temp_data[1][0] * effective_strength)
else:
while self.temp_data[0] < cnet_index and (self.temp_data[0] + 1) < cnet_blocks:
next_layer = self.temp_data[0] + 1
self.temp_data = (next_layer, self.model_patch.model.forward_control_block(next_layer, self.temp_data[1][1], img_input[:, :self.temp_data[1][1].shape[1]], None, pe, vec))
if cnet_index_float == self.temp_data[0]:
img[:, :self.temp_data[1][0].shape[1]] += (self.temp_data[1][0] * effective_strength)
if cnet_blocks == self.temp_data[0] + 1:
self.temp_data = None
return kwargs
def to(self, device_or_dtype):
if isinstance(device_or_dtype, torch.device):
self.encoded_image = self.encoded_image.to(device_or_dtype)
self.temp_data = None
return self
def models(self):
return [self.model_patch]
# ============================================================================
# Main Node Class
# ============================================================================
class TK3RQwenImageDiffsynthControlnetAdvanced:
@classmethod
def INPUT_TYPES(s):
return {"required": { "model": ("MODEL",),
"model_patch": ("MODEL_PATCH",),
"vae": ("VAE",),
"image": ("IMAGE",),
"strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
"stop_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
"decay": (DECAY_MODES, {"default": "none", "tooltip": "Strength decay curve: none=instant cutoff, linear=even decay, cosine=smooth S-curve, exponential=fast initial decay, inverse_exponential=slow initial decay"}),
},
"optional": {"mask": ("MASK",)}}
RETURN_TYPES = ("MODEL",)
FUNCTION = "diffsynth_controlnet"
CATEGORY = "TK3R/Advanced"
def diffsynth_controlnet(self, model, model_patch, vae, image, strength, start_percent=0.0, stop_percent=1.0, decay="none", mask=None):
model_patched = model.clone()
image = image[:, :, :, :3]
model_sampling = model.get_model_object("model_sampling")
if model_sampling is None:
sigma_low, sigma_high = float("-inf"), float("inf")
else:
sigma_low, sigma_high = resolve_sigma_window(model_sampling, start_percent, stop_percent)
if mask is not None:
if mask.ndim == 3:
mask = mask.unsqueeze(1)
if mask.ndim == 4:
mask = mask.unsqueeze(2)
mask = 1.0 - mask
if isinstance(model_patch.model, comfy.ldm.lumina.controlnet.ZImage_Control):
patch = ZImageControlPatch(model_patch, vae, image, strength, mask=mask, sigma_low=sigma_low, sigma_high=sigma_high, start_percent=start_percent, stop_percent=stop_percent, decay_mode=decay)
model_patched.set_model_noise_refiner_patch(patch)
model_patched.set_model_double_block_patch(patch)
else:
model_patched.set_model_double_block_patch(DiffSynthCnetPatch(model_patch, vae, image, strength, mask, sigma_low, sigma_high, start_percent, stop_percent, decay))
return (model_patched,)
class TK3RZImageFunControlnet(TK3RQwenImageDiffsynthControlnetAdvanced):
@classmethod
def INPUT_TYPES(s):
return {"required": { "model": ("MODEL",),
"model_patch": ("MODEL_PATCH",),
"vae": ("VAE",),
"strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
"start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
"stop_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
"decay": (DECAY_MODES, {"default": "none", "tooltip": "Strength decay curve: none=instant cutoff, linear=even decay, cosine=smooth S-curve, exponential=fast initial decay, inverse_exponential=slow initial decay"}),
},
"optional": {"image": ("IMAGE",), "inpaint_image": ("IMAGE",), "mask": ("MASK",)}}
CATEGORY = "TK3R/Advanced"
# ============================================================================
# Node Registration
# ============================================================================
NODE_CLASS_MAPPINGS = {
"TK3RQwenImageDiffsynthControlnetAdvanced": TK3RQwenImageDiffsynthControlnetAdvanced,
"TK3RZImageFunControlnet": TK3RZImageFunControlnet,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"TK3RQwenImageDiffsynthControlnetAdvanced": "TK3R Qwen Image DiffSynth ControlNet Advanced (Custom)",
"TK3RZImageFunControlnet": "TK3R ZImage Fun ControlNet (Custom)",
}
+74
View File
@@ -0,0 +1,74 @@
import node_helpers
import comfy.utils
import math
from typing_extensions import override
from comfy_api.latest import ComfyExtension, io
class TK3RTextEncodeQwenImageEditPlus:
"""
This an enhanced version of the TextEncodeQwenImageEditPlus node, it is NOT my code, I originally got it from some repo and it was supposed to just overwrite the original file but this is not a good approach with all the constant Comfy updates, so I have added it as a separate node in my repo.
"""
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"clip": ("CLIP", ),
"prompt": ("STRING", {"multiline": True, "dynamicPrompts": True}),
},
"optional": {
"vae": ("VAE", ),
"image1": ("IMAGE", ),
"image2": ("IMAGE", ),
"image3": ("IMAGE", ),
"image4": ("IMAGE", ),
"target_latent": ("LATENT", ),
}
}
RETURN_TYPES = ("CONDITIONING",)
RETURN_NAMES = ("conditioning",)
FUNCTION = "execute"
CATEGORY = "TK3R/Advanced"
def execute(self, clip, prompt, vae=None, image1=None, image2=None, image3=None, image4=None, target_latent=None):
ref_latents = []
images = [image1, image2, image3, image4]
images_vl = []
llama_template = "<|im_start|>system\nDescribe key details of the input image (including any objects, characters, poses, facial features, clothing, setting, textures and style), then explain how the user's text instruction should alter, modify or recreate the image. Generate a new image that meets the user's requirements, which can vary from a small change to a completely new image using inputs as a guide.<|im_end|>\n<|im_start|>user\n{}<|im_end|>\n<|im_start|>assistant\n"
image_prompt = ""
for i, image in enumerate(images):
if image is not None:
samples = image.movedim(-1, 1)
total = int(384 * 384)
scale_by = math.sqrt(total / (samples.shape[3] * samples.shape[2]))
width = round(samples.shape[3] * scale_by)
height = round(samples.shape[2] * scale_by)
s = comfy.utils.common_upscale(samples, width, height, "lanczos", "center")
images_vl.append(s.movedim(1, -1))
if vae is not None:
if target_latent is not None:
twidth = target_latent["samples"].shape[-1] * 8
theight = target_latent["samples"].shape[-2] * 8
s = comfy.utils.common_upscale(samples, twidth, theight, "lanczos", "center")
else:
s = samples
ref_latents.append(vae.encode(s.movedim(1, -1)[:, :, :, :3]))
image_prompt += "Picture {}: <|vision_start|><|image_pad|><|vision_end|>".format(i + 1)
tokens = clip.tokenize(image_prompt + prompt, images=images_vl, llama_template=llama_template)
conditioning = clip.encode_from_tokens_scheduled(tokens)
if len(ref_latents) > 0:
conditioning = node_helpers.conditioning_set_values(conditioning, {"reference_latents": ref_latents}, append=True)
return (conditioning,)
NODE_CLASS_MAPPINGS = {
"TK3RTextEncodeQwenImageEditPlusExt": TK3RTextEncodeQwenImageEditPlus
}
NODE_DISPLAY_NAME_MAPPINGS = {
"TK3RTextEncodeQwenImageEditPlusExt": "TK3R TextEncodeQwenImageEditPlus Ext"
}
@@ -0,0 +1,158 @@
import torch
class TK3RCLIPTextEncodeWithTokenCount:
"""
CLIPTextEncode with added token count output.
Encodes text and returns both the conditioning and token count.
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"text": ("STRING", {
"multiline": True,
"default": "",
"dynamicPrompts": True,
"tooltip": "The text to be encoded."
}),
"clip": ("CLIP", {"tooltip": "The CLIP model used for encoding the text."}),
"system_prompt": (list(cls.SYSTEM_PROMPT.keys()), {"default": "none", "tooltip": "System prompt for Lumina2 models. Use 'none' for other models."}),
}
}
SYSTEM_PROMPT = {
"none": "",
"lumina2: superior": "You are an assistant designed to generate superior images with the superior "\
"degree of image-text alignment based on textual prompts or user prompts.",
"lumina2: alignment": "You are an assistant designed to generate high-quality images with the "\
"highest degree of image-text alignment based on textual prompts."
}
RETURN_TYPES = ("CONDITIONING", "INT", "STRING")
RETURN_NAMES = ("conditioning", "token_count", "info")
FUNCTION = "encode"
CATEGORY = "TK3R/Utility"
OUTPUT_NODE = True
DESCRIPTION = "Encodes text prompt and outputs the conditioning along with token count information."
def encode(self, clip, text, system_prompt="none"):
if clip is None:
raise RuntimeError("ERROR: clip input is invalid: None\n\nIf the clip is from a checkpoint loader node your checkpoint does not contain a valid clip or text encoder model.")
# Apply system prompt if selected
if system_prompt != "none":
sys_prompt_text = self.SYSTEM_PROMPT[system_prompt]
text = f'{sys_prompt_text} <Prompt Start> {text}'
# Tokenize the text
tokens = clip.tokenize(text)
# Count tokens
token_counts = {}
total_tokens = 0
for key, token_data in tokens.items():
count = 0
if isinstance(token_data, torch.Tensor):
# Direct tensor: count non-padding tokens
# For CLIP tokenizers, structure is: [start_token, ...content..., end_token, pad, pad, ...]
# Common values: start=49406, end=49407, pad=49407
flat_tokens = token_data.flatten()
# Skip the start token (first token)
tokens_to_check = flat_tokens[1:] if len(flat_tokens) > 1 else flat_tokens
for i, token_id in enumerate(tokens_to_check):
tid = token_id.item()
# Check if this is an end/pad token by looking ahead
# If we see the same token repeated to the end, it's padding
if i < len(tokens_to_check) - 1:
# Check if all remaining tokens are the same (padding pattern)
remaining = tokens_to_check[i:]
if len(remaining) > 1 and all(t.item() == tid for t in remaining):
# This is the start of padding, include current token as end token
count += 1
break
count += 1
# Add 1 for the start token
count += 1
elif isinstance(token_data, list):
# Handle nested list structures
if len(token_data) > 0:
inner_data = token_data[0]
if isinstance(inner_data, list):
# Nested list structure (SDXL format: [[token_ids], [weights]])
# Count non-padding tokens by looking for repeating end token pattern
for i, token_id in enumerate(inner_data):
# Check if remaining tokens are all the same (padding pattern)
if i > 0 and i < len(inner_data) - 1:
remaining = inner_data[i:]
if len(remaining) > 1 and all(t == token_id for t in remaining):
# Found padding start, include current token as end token
count = i + 1
break
# If no padding pattern found, use full length
if count == 0:
count = len(inner_data)
elif isinstance(inner_data, torch.Tensor):
# List containing tensor
flat_tokens = inner_data.flatten()
# Skip start token
tokens_to_check = flat_tokens[1:] if len(flat_tokens) > 1 else flat_tokens
for i, token_id in enumerate(tokens_to_check):
tid = token_id.item() if isinstance(token_id, torch.Tensor) else token_id
# Check for padding pattern
if i < len(tokens_to_check) - 1:
remaining = tokens_to_check[i:]
if len(remaining) > 1:
remaining_vals = [t.item() if isinstance(t, torch.Tensor) else t for t in remaining]
if all(v == tid for v in remaining_vals):
count += 1
break
count += 1
# Add 1 for start token
count += 1
else:
# Direct list of tokens
count = len(token_data)
token_counts[key] = count
total_tokens = max(total_tokens, count)
# Build info string
info_lines = [f"Total tokens: {total_tokens}"]
info_lines.append(f"Text length: {len(text)} characters")
if len(token_counts) > 1:
info_lines.append(f"\nTokenizer breakdown:")
for key, count in token_counts.items():
info_lines.append(f" {key}: {count} tokens")
info_string = "\n".join(info_lines)
# Encode from tokens (same as CLIPTextEncode)
conditioning = clip.encode_from_tokens_scheduled(tokens)
return {"ui": {"text": [info_string]}, "result": (conditioning, total_tokens, info_string)}
NODE_CLASS_MAPPINGS = {
"TK3R CLIP Text Encode With Token Count": TK3RCLIPTextEncodeWithTokenCount,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"TK3R CLIP Text Encode With Token Count": "TK3R CLIP Text Encode With Token Count",
}
+213
View File
@@ -0,0 +1,213 @@
import logging
import math
import torch
logger = logging.getLogger(__name__)
DECAY_MODES = ["none", "linear", "cosine", "exponential", "inverse_exponential"]
def _clamp_percent(value: float) -> float:
return max(0.0, min(1.0, float(value)))
def _sigma_from_percent(model_sampling, percent: float) -> float:
sigma = model_sampling.percent_to_sigma(percent)
if isinstance(sigma, torch.Tensor):
sigma = float(sigma.detach().cpu())
return float(sigma)
def resolve_sigma_window(model_sampling, start_percent: float, end_percent: float):
start = _clamp_percent(start_percent)
end = _clamp_percent(end_percent)
sigma_start = _sigma_from_percent(model_sampling, start)
sigma_end = _sigma_from_percent(model_sampling, end)
sigma_high = max(sigma_start, sigma_end)
sigma_low = min(sigma_start, sigma_end)
if math.isclose(sigma_high, sigma_low, rel_tol=1e-6, abs_tol=1e-9):
sigma_high += 1e-9
return sigma_low, sigma_high
def current_sigma(transformer_options):
if not isinstance(transformer_options, dict):
return None
sigma_tensor = transformer_options.get("sigmas")
if not isinstance(sigma_tensor, torch.Tensor) or sigma_tensor.numel() == 0:
return None
return float(sigma_tensor.reshape(-1)[0].item())
def calculate_strength_multiplier(sigma_val, sigma_low, sigma_high, decay_mode="none"):
if sigma_val is None:
return 1.0
if sigma_val < sigma_low - 1e-9:
return 0.0
if sigma_val > sigma_high + 1e-9:
return 0.0 if decay_mode != "none" else 1.0
if decay_mode == "none":
return 1.0
if sigma_high <= sigma_low:
return 1.0
t = (sigma_val - sigma_low) / (sigma_high - sigma_low)
t = max(0.0, min(1.0, t))
if decay_mode == "linear":
return t
if decay_mode == "cosine":
return (1.0 - math.cos(t * math.pi)) / 2.0
if decay_mode == "exponential":
return 1.0 - math.exp(-3.0 * t) / (1.0 - math.exp(-3.0)) if t > 0 else 0.0
if decay_mode == "inverse_exponential":
return (math.exp(3.0 * t) - 1.0) / (math.exp(3.0) - 1.0)
return 1.0
class DecayControlNetWrapper:
"""Scales control outputs per step using sigma-window decay.
Transparently wraps a controlnet and delegates all attributes/methods to it,
except get_control which applies decay-based strength scaling.
"""
def __init__(self, inner, start_percent: float, end_percent: float, decay_mode: str):
object.__setattr__(self, 'inner', inner)
object.__setattr__(self, 'start_percent', start_percent)
object.__setattr__(self, 'end_percent', end_percent)
object.__setattr__(self, 'decay_mode', decay_mode)
object.__setattr__(self, 'sigma_low', float("-inf"))
object.__setattr__(self, 'sigma_high', float("inf"))
def __getattr__(self, name):
"""Delegate attribute access to inner controlnet."""
return getattr(self.inner, name)
def __setattr__(self, name, value):
"""Delegate attribute setting to inner controlnet, except internal state."""
if name in ('inner', 'start_percent', 'end_percent', 'decay_mode', 'sigma_low', 'sigma_high'):
object.__setattr__(self, name, value)
else:
setattr(self.inner, name, value)
def pre_run(self, model, percent_to_timestep_function):
try:
sampling = getattr(model, "model_sampling", None)
if sampling is not None:
self.sigma_low, self.sigma_high = resolve_sigma_window(sampling, self.start_percent, self.end_percent)
except Exception as e:
logger.warning("DecayControlNetWrapper: failed to resolve sigma window (%s)", e)
return self.inner.pre_run(model, percent_to_timestep_function)
def get_control(self, x_noisy, t, cond, batched_number, transformer_options):
ctrl = self.inner.get_control(x_noisy, t, cond, batched_number, transformer_options)
if ctrl is None:
return None
sigma_val = current_sigma(transformer_options)
mult = calculate_strength_multiplier(sigma_val, self.sigma_low, self.sigma_high, self.decay_mode)
if mult == 1.0:
return ctrl
if mult == 0.0:
return None
try:
for key in ctrl:
arr = ctrl[key]
for i, x in enumerate(arr):
if x is not None:
arr[i] = x * mult
except Exception as e:
logger.warning("DecayControlNetWrapper: scaling failed (%s)", e)
return ctrl
def cleanup(self):
return self.inner.cleanup()
def get_models(self):
return self.inner.get_models()
def get_extra_hooks(self):
return self.inner.get_extra_hooks()
def inference_memory_requirements(self, dtype):
return self.inner.inference_memory_requirements(dtype)
def copy(self):
return DecayControlNetWrapper(self.inner.copy(), self.start_percent, self.end_percent, self.decay_mode)
def set_previous_controlnet(self, prev):
self.inner.set_previous_controlnet(prev)
return self
def set_cond_hint(self, *args, **kwargs):
return self.inner.set_cond_hint(*args, **kwargs)
class TK3RControlNetApplyAdvanced:
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"positive": ("CONDITIONING", ),
"negative": ("CONDITIONING", ),
"control_net": ("CONTROL_NET", ),
"image": ("IMAGE", ),
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
"start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
"end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}),
"decay": (DECAY_MODES, {"default": "none", "tooltip": "Strength decay: none, linear, cosine, exponential, inverse_exponential."}),
},
"optional": {
"vae": ("VAE", ),
},
}
RETURN_TYPES = ("CONDITIONING","CONDITIONING")
RETURN_NAMES = ("positive", "negative")
FUNCTION = "apply_controlnet"
CATEGORY = "TK3R/Advanced"
def apply_controlnet(self, positive, negative, control_net, image, strength, start_percent, end_percent, decay="none", vae=None, extra_concat=[]):
if strength == 0:
return (positive, negative)
control_hint = image.movedim(-1,1)
cnets = {}
out = []
for conditioning in [positive, negative]:
c = []
for t in conditioning:
d = t[1].copy()
prev_cnet = d.get('control', None)
if prev_cnet in cnets:
c_net = cnets[prev_cnet]
else:
c_net = control_net.copy().set_cond_hint(control_hint, strength, (start_percent, end_percent), vae=vae, extra_concat=extra_concat)
c_net.set_previous_controlnet(prev_cnet)
if decay != "none":
c_net = DecayControlNetWrapper(c_net, start_percent, end_percent, decay)
cnets[prev_cnet] = c_net
d['control'] = c_net
d['control_apply_to_uncond'] = False
n = [t[0], d]
c.append(n)
out.append(c)
return (out[0], out[1])
NODE_CLASS_MAPPINGS = {
"TK3R ControlNet Apply Advanced": TK3RControlNetApplyAdvanced,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"TK3R ControlNet Apply Advanced": "TK3R ControlNet Apply Advanced",
}
+46
View File
@@ -0,0 +1,46 @@
import torch
class TK3RImageCompare:
"""
Node that outputs both current and previous image inputs.
Useful for comparing consecutive frames or tracking image changes.
"""
# Class-level cache to store the last image
_last_image = {}
@classmethod
def INPUT_TYPES(s):
return {"required": { "image": ("IMAGE",)}}
RETURN_TYPES = ("IMAGE", "IMAGE")
RETURN_NAMES = ("current", "previous")
FUNCTION = "compare"
CATEGORY = "TK3R/Utility"
def compare(self, image):
# Generate a unique key for this node instance
# Using id(self) to track per-instance
instance_id = id(self)
# Get the previous image for this instance, if it exists
if instance_id in TK3RImageCompare._last_image:
previous = TK3RImageCompare._last_image[instance_id]
else:
# First run - return current image for both outputs
previous = image
# Store current image as the new "last" image for next run
TK3RImageCompare._last_image[instance_id] = image.clone()
return (image, previous)
NODE_CLASS_MAPPINGS = {
"TK3R Image Compare": TK3RImageCompare,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"TK3R Image Compare": "TK3R Image Compare",
}
+89
View File
@@ -0,0 +1,89 @@
"""
LoRA Rank Reader Node
A ComfyUI node that reads and displays the rank of a LoRA safetensors file.
"""
from safetensors import safe_open
import os
import folder_paths
class TK3RLoRARankReader:
"""
Reads a LoRA .safetensors file and outputs information about its rank.
The rank (r) is the bottleneck dimension in LoRA matrices, which determines
the model's capacity and file size.
"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"lora_name": (folder_paths.get_filename_list("loras"), {"tooltip": "The name of the LoRA."}),
}
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("info",)
FUNCTION = "read_rank"
CATEGORY = "TK3R/Utility"
DESCRIPTION = "Reads and displays the rank of a LoRA safetensors file."
OUTPUT_NODE = True
def read_rank(self, lora_name):
lora_path = folder_paths.get_full_path_or_raise("loras", lora_name)
try:
with safe_open(lora_path, framework="pt") as f:
# Search for the first 'A' or 'down' matrix to identify the rank
# These matrices have the shape (rank, original_dimension)
keys = f.keys()
target_key = next((k for k in keys if "lora_A" in k or "lora_down" in k), None)
if target_key:
tensor_shape = f.get_slice(target_key).get_shape()
# The rank 'r' is the smaller bottleneck dimension, typically the first index
rank = tensor_shape[0]
info_lines = [
f"=== LoRA Analysis ===",
f"File: {os.path.basename(lora_path)}",
f"Rank (r): {rank}",
f"Sample key: {target_key}",
f"Tensor shape: {tensor_shape}"
]
# Check for Alpha in metadata if it exists
metadata = f.metadata()
if metadata and 'ss_network_alpha' in metadata:
info_lines.append(f"Network Alpha: {metadata['ss_network_alpha']}")
# Count total LoRA layers
lora_layer_count = len([k for k in keys if "lora_A" in k or "lora_down" in k])
info_lines.append(f"Total LoRA layers: {lora_layer_count}")
info_text = "\n".join(info_lines)
print(info_text)
return (info_text,)
else:
error_msg = f"Error: Could not find LoRA weight matrices in {lora_path}"
print(error_msg)
return (error_msg,)
except Exception as e:
error_msg = f"Error opening file: {str(e)}"
print(error_msg)
return (error_msg,)
# Register nodes
NODE_CLASS_MAPPINGS = {
"TK3RLoRARankReader": TK3RLoRARankReader,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"TK3RLoRARankReader": "LoRA Rank Reader",
}
+114
View File
@@ -0,0 +1,114 @@
"""
Safetensors Precision Reader Node
A ComfyUI node that reads and displays the floating-point precision of a safetensors file.
"""
import os
import logging
import traceback
import folder_paths
class TK3RSafetensorsPrecisionReader:
"""
Reads a safetensors file and reports the floating-point precision used (fp8, fp16, bf16, fp32, etc.)
"""
@classmethod
def INPUT_TYPES(s):
return {
"required": {
"file_path": ("STRING", {"default": "", "multiline": False, "tooltip": "Full path to safetensors file"}),
}
}
RETURN_TYPES = ("STRING",)
RETURN_NAMES = ("PRECISION_INFO",)
FUNCTION = "read_precision"
CATEGORY = "TK3R/Utility"
OUTPUT_NODE = True
def read_precision(self, file_path):
import safetensors.torch
try:
# If relative path provided, try to resolve from models folder
if not os.path.isabs(file_path):
models_dir = folder_paths.get_folder_paths("checkpoints")[0]
models_dir = os.path.dirname(models_dir) # Go up to models folder
file_path = os.path.join(models_dir, file_path)
logging.info(f"\n[TK3R Sft Precision Reader] Reading file: {file_path}")
dtype_counts = {}
total_tensors = 0
with safetensors.torch.safe_open(file_path, framework="pt") as f:
keys = list(f.keys())
total_tensors = len(keys)
logging.info(f" Total tensors: {total_tensors}")
for key in keys:
tensor = f.get_tensor(key)
dtype_str = str(tensor.dtype).replace('torch.', '')
if dtype_str not in dtype_counts:
dtype_counts[dtype_str] = 0
dtype_counts[dtype_str] += 1
# Determine primary precision
if not dtype_counts:
return ("ERROR: No tensors found in file",)
# Sort by count to find most common dtype
sorted_dtypes = sorted(dtype_counts.items(), key=lambda x: x[1], reverse=True)
primary_dtype = sorted_dtypes[0][0]
primary_count = sorted_dtypes[0][1]
# Map torch dtypes to common names
precision_map = {
'float32': 'fp32',
'float16': 'fp16',
'bfloat16': 'bf16',
'float8_e4m3fn': 'fp8 (e4m3)',
'float8_e5m2': 'fp8 (e5m2)',
'int8': 'int8',
'uint8': 'uint8',
}
primary_precision = precision_map.get(primary_dtype, primary_dtype)
# Build detailed info
info_lines = [
f"File: {os.path.basename(file_path)}",
f"Primary Precision: {primary_precision}",
f"Total Tensors: {total_tensors}",
"\nPrecision Breakdown:"
]
for dtype, count in sorted_dtypes:
precision_name = precision_map.get(dtype, dtype)
percentage = (count / total_tensors) * 100
info_lines.append(f" {precision_name}: {count} tensors ({percentage:.1f}%)")
result = "\n".join(info_lines)
logging.info(f"\n[TK3R Sft Precision Reader] Result:\n{result}")
return (result,)
except Exception as e:
error_message = f"ERROR: {str(e)}\n{traceback.format_exc()}"
logging.error(f"\n[TK3R Sft Precision Reader] {error_message}")
return (error_message,)
# Register nodes
NODE_CLASS_MAPPINGS = {
"TK3R Safetensors Precision Reader": TK3RSafetensorsPrecisionReader,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"TK3RSafetensorsPrecisionReader": "TK3R Safetensors Precision Reader",
}
+213
View File
@@ -0,0 +1,213 @@
import logging
import math
import torch
import comfy.samplers
logger = logging.getLogger(__name__)
class Guider_CFGSchedule(comfy.samplers.CFGGuider):
def set_cfg_schedule(self, schedule):
if isinstance(schedule, list):
schedule = torch.tensor(schedule, dtype=torch.float32)
self.cfg_schedule = schedule
self.last_sigma_idx = None
# Set cfg to the first value for compatibility
if len(schedule) > 0:
self.cfg = float(schedule[0].item())
def predict_noise(self, x, timestep, model_options={}, seed=None):
sched_len = int(self.cfg_schedule.shape[-1]) if hasattr(self, "cfg_schedule") else 0
if sched_len == 0:
cond_scale = self.cfg
else:
current_sigma = timestep[0].item() if isinstance(timestep, torch.Tensor) else timestep[0]
# Find which step range this sigma falls in
try:
sample_sigmas = model_options["transformer_options"]["sample_sigmas"]
# Sigmas are in descending order. Find where current_sigma fits
sigma_idx = 0
for i in range(len(sample_sigmas) - 1):
if current_sigma >= sample_sigmas[i + 1]:
sigma_idx = i
break
sigma_idx = i + 1
except Exception as e:
logger.warning(f"Could not get sample_sigmas: {e}, using index 0")
sigma_idx = 0
# Only log when sigma_idx changes (new actual step)
if self.last_sigma_idx is None or sigma_idx != self.last_sigma_idx:
self.last_sigma_idx = sigma_idx
step_idx = min(sigma_idx, sched_len - 1)
logger.info(f"[CFG Schedule] Step {sigma_idx}: CFG = {float(self.cfg_schedule[step_idx].item()):.1f} (sigma={current_sigma:.4f})")
step_idx = min(sigma_idx, sched_len - 1)
cond_scale = float(self.cfg_schedule[step_idx].item())
negative_cond = self.conds.get("negative", None)
positive_cond = self.conds.get("positive", None)
return comfy.samplers.sampling_function(self.inner_model, x, timestep, negative_cond, positive_cond, cond_scale, model_options=model_options, seed=seed)
class TK3RCFGScheduleGuider:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"model": ("MODEL",),
"positive": ("CONDITIONING",),
"negative": ("CONDITIONING",),
"cfg_schedule": ("STRING", {"default": "3.0, 2.0, 1.5, 1.0", "multiline": False}),
"interpolate_steps": ("INT", {"default": 0, "min": 0, "max": 1000, "step": 1}),
},
}
RETURN_TYPES = ("GUIDER", "SIGMAS", "SIGMAS")
RETURN_NAMES = ("guider", "schedule", "normalized_schedule")
FUNCTION = "execute"
CATEGORY = "TK3R/Advanced"
def execute(self, model, positive, negative, cfg_schedule, interpolate_steps):
# Parse the string into a list of floats
try:
cfg_values = [float(x.strip()) for x in cfg_schedule.split(',')]
logger.info(f"[CFG Schedule] Parsed CFG schedule: {[f'{x:.1f}' for x in cfg_values]}")
# Interpolate if steps > 0
if interpolate_steps > 0:
cfg_values = self._interpolate_schedule(cfg_values, interpolate_steps)
logger.info(f"[CFG Schedule] Interpolated to {interpolate_steps} steps: {[f'{x:.1f}' for x in cfg_values]}")
cfg_tensor = torch.tensor(cfg_values, dtype=torch.float32)
except (ValueError, AttributeError) as e:
logger.warning(f"Failed to parse cfg_schedule '{cfg_schedule}': {e}. Using default 8.0")
cfg_tensor = torch.tensor([8.0], dtype=torch.float32)
guider = Guider_CFGSchedule(model)
guider.set_conds(positive, negative)
guider.set_cfg_schedule(cfg_tensor)
# Create normalized schedule (0-1 range)
min_cfg = cfg_tensor.min()
max_cfg = cfg_tensor.max()
if max_cfg > min_cfg:
normalized_schedule = (cfg_tensor - min_cfg) / (max_cfg - min_cfg)
else:
# All values are the same, normalize to 1.0
normalized_schedule = torch.ones_like(cfg_tensor)
return (guider, cfg_tensor, normalized_schedule)
def _interpolate_schedule(self, values, steps):
"""Interpolate the schedule values over the specified number of steps."""
if len(values) == 1:
# Single value, repeat it
return values * steps
if steps == len(values):
# Already the right length
return values
# Create interpolated values
input_indices = torch.linspace(0, len(values) - 1, len(values))
output_indices = torch.linspace(0, len(values) - 1, steps)
# Linear interpolation
values_tensor = torch.tensor(values, dtype=torch.float32)
interpolated = torch.zeros(steps, dtype=torch.float32)
for i, out_idx in enumerate(output_indices):
# Find the two surrounding input indices
left_idx = int(torch.floor(out_idx).item())
right_idx = min(left_idx + 1, len(values) - 1)
# Calculate interpolation weight
if left_idx == right_idx:
interpolated[i] = values_tensor[left_idx]
else:
weight = out_idx - left_idx
interpolated[i] = values_tensor[left_idx] * (1 - weight) + values_tensor[right_idx] * weight
return interpolated.tolist()
class Guider_CFGSigmaInterpolate(comfy.samplers.CFGGuider):
def set_sigma_schedule(self, start_cfg, end_cfg, linear_blend):
self.start_cfg = start_cfg
self.end_cfg = end_cfg
self.linear_blend = linear_blend
# Set cfg for compatibility
self.cfg = start_cfg
def predict_noise(self, x, timestep, model_options={}, seed=None):
current_sigma = timestep[0].item() if isinstance(timestep, torch.Tensor) else timestep[0]
# Sigma-based interpolation (follows sigma schedule)
sigma_progress = 1.0 - max(0.0, min(1.0, current_sigma)) # Clamp to [0, 1]
# Linear-based interpolation (based on position in sampling schedule)
linear_progress = sigma_progress # Default to same as sigma
try:
sample_sigmas = model_options["transformer_options"]["sample_sigmas"]
# Find position in the sigma schedule
sigma_idx = 0
for i in range(len(sample_sigmas) - 1):
if current_sigma >= sample_sigmas[i + 1]:
sigma_idx = i
break
sigma_idx = i + 1
linear_progress = sigma_idx / max(1, len(sample_sigmas) - 1)
except Exception as e:
logger.warning(f"Could not get sample_sigmas for linear progress: {e}")
# Blend between linear and sigma schedules
# linear_blend = 0.0 means full linear schedule
# linear_blend = 1.0 means full sigma schedule
blended_progress = (sigma_progress * self.linear_blend) + (linear_progress * (1.0 - self.linear_blend))
cond_scale = self.start_cfg + (self.end_cfg - self.start_cfg) * blended_progress
logger.info(f"[CFG Sigma Interpolate] Sigma={current_sigma:.4f}, SigmaProgress={sigma_progress:.4f}, LinearProgress={linear_progress:.4f}, Blend={self.linear_blend:.2f}, CFG={cond_scale:.4f}")
negative_cond = self.conds.get("negative", None)
positive_cond = self.conds.get("positive", None)
return comfy.samplers.sampling_function(self.inner_model, x, timestep, negative_cond, positive_cond, cond_scale, model_options=model_options, seed=seed)
class TK3RCFGSigmaInterpolate:
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"model": ("MODEL",),
"positive": ("CONDITIONING",),
"negative": ("CONDITIONING",),
"cfg_start": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 30.0, "step": 0.1}),
"cfg_end": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 30.0, "step": 0.1}),
"linear_blend": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.05}),
},
}
RETURN_TYPES = ("GUIDER",)
RETURN_NAMES = ("guider",)
FUNCTION = "execute"
CATEGORY = "TK3R/Advanced"
def execute(self, model, positive, negative, cfg_start, cfg_end, linear_blend):
logger.info(f"[CFG Sigma Interpolate] Creating guider with start_cfg={cfg_start}, end_cfg={cfg_end}, linear_blend={linear_blend}")
guider = Guider_CFGSigmaInterpolate(model)
guider.set_conds(positive, negative)
guider.set_sigma_schedule(cfg_start, cfg_end, linear_blend)
return (guider,)
NODE_CLASS_MAPPINGS = {
"TK3R Scheduled CFG Guider": TK3RCFGScheduleGuider,
"TK3R CFG Sigma Interpolate": TK3RCFGSigmaInterpolate,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"TK3R Scheduled CFG Guider": "TK3R Scheduled CFG Guider",
"TK3R CFG Sigma Interpolate": "TK3R CFG Sigma Interpolate",
}
+50
View File
@@ -0,0 +1,50 @@
"""
Interpolate between two sigma schedules by averaging each pair
"""
import torch
import logging
logger = logging.getLogger(__name__)
class TK3RSigmasInterpolate:
"""Interpolate between two sigma schedules by averaging corresponding values"""
@classmethod
def INPUT_TYPES(cls):
return {
"required": {
"sigmas_1": ("SIGMAS", {"tooltip": "First sigma schedule"}),
"sigmas_2": ("SIGMAS", {"tooltip": "Second sigma schedule"}),
},
}
RETURN_TYPES = ("SIGMAS",)
RETURN_NAMES = ("sigmas",)
FUNCTION = "interpolate_sigmas"
CATEGORY = "TK3R/Utility"
DESCRIPTION = "Interpolate between two sigma schedules by averaging each pair. If lengths don't match, returns first sigma schedule unchanged."
def interpolate_sigmas(self, sigmas_1, sigmas_2):
# Check if lengths match
if len(sigmas_1) != len(sigmas_2):
logger.error(
f"TK3RSigmasInterpolate: Sigma length mismatch! "
f"sigmas_1 has {len(sigmas_1)} values, sigmas_2 has {len(sigmas_2)} values. "
f"Returning sigmas_1 unchanged."
)
return (sigmas_1,)
# Average the two sigma schedules
interpolated_sigmas = (sigmas_1 + sigmas_2) / 2.0
return (interpolated_sigmas,)
NODE_CLASS_MAPPINGS = {
"TK3RSigmasInterpolate": TK3RSigmasInterpolate,
}
NODE_DISPLAY_NAME_MAPPINGS = {
"TK3RSigmasInterpolate": "TK3R Sigmas Interpolate",
}
+44
View File
@@ -0,0 +1,44 @@
[project]
name = "comfyui_tk3r_ext"
version = "1.0.0"
description = "Extended versions of various ComfyUI nodes"
readme = "README.md"
requires-python = ">=3.8"
license = {text = "GPLv3"}
authors = [
{name = "TK3R"}
]
keywords = ["comfyui", "custom-nodes", "stable-diffusion", "controlnet"]
classifiers = [
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: GPLv3 License",
"Operating System :: OS Independent",
"Environment :: GPU :: NVIDIA CUDA",
"Environment :: GPU :: AMD ROCm",
"Environment :: GPU :: Apple Metal",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
]
dependencies = [
"rich>=10.0.0"
]
[project.urls]
Homepage = "https://github.com/TK3R/ComfyUI_TK3R_Ext"
Repository = "https://github.com/TK3R/ComfyUI_TK3R_Ext"
Issues = "https://github.com/TK3R/ComfyUI_TK3R_Ext/issues"
[build-system]
requires = ["setuptools>=45", "wheel"]
build-backend = "setuptools.build_meta"
[tool.comfy]
PublisherId = "TK3R"
DisplayName = "TK3R Ext"
requires-comfyui = ">=1.0.0"
+1
View File
@@ -0,0 +1 @@
rich>=10.0.0
@@ -0,0 +1,48 @@
import { app } from "../../scripts/app.js";
import { ComfyWidgets } from "../../scripts/widgets.js";
app.registerExtension({
name: "TK3R.TextOutput",
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "TK3RCLIPTextEncodeWithTokenCount" || nodeData.name === "TK3R CLIP Text Encode With Token Count") {
const onExecuted = nodeType.prototype.onExecuted;
nodeType.prototype.onExecuted = function (message) {
onExecuted?.apply(this, arguments);
if (this.widgets) {
const pos = this.widgets.findIndex((w) => w.name === "output_text");
if (pos !== -1) {
for (let i = pos; i < this.widgets.length; i++) {
this.widgets[i].onRemove?.();
}
this.widgets.length = pos;
}
}
const text = message.text;
if (!text) { return; }
// Create widget as multiline initially to get a textarea
const w = ComfyWidgets["STRING"](this, "output_text", ["STRING", { multiline: true }], app).widget;
w.inputEl.readOnly = true;
w.inputEl.style.opacity = 0.6;
w.inputEl.rows = 2;
w.inputEl.style.height = "auto";
w.value = text[0];
// Trick ComfyUI/LiteGraph into treating this as a fixed-size widget
// so it doesn't try to expand it to fill remaining vertical space
w.options = w.options || {};
w.options.multiline = false;
// Override computeSize to return fixed small height
w.computeSize = function(width) {
return [width, 40]; // ~40px for 2 lines
}
// Refresh node appearance without resetting dimensions
this.onResize?.(this.size);
};
}
},
});