Repository: vinavfx/ComfyUI-for-Nuke
Branch: main
Commit: 88b7aa1d5286
Files: 32
Total size: 129.9 KB
Directory structure:
gitextract_23hxchp3/
├── .gitignore
├── .gitmodules
├── LICENSE
├── README.md
├── __init__.py
├── examples/
│ ├── cmd.nk
│ └── cmd.py
├── nodes/
│ └── ComfyUI/
│ ├── ComfyUIGizmo.nk
│ ├── MultipleOf.nk
│ ├── OverrideSettings.nk
│ ├── Run.nk
│ └── SwitchAny.nk
├── requirements.txt
├── settings.py
├── src/
│ ├── __init__.py
│ ├── cmd.py
│ ├── common.py
│ ├── connection.py
│ ├── execute_runs.py
│ ├── nodes.py
│ ├── queue_manager.py
│ ├── read_media.py
│ ├── run.py
│ ├── scripts/
│ │ ├── __init__.py
│ │ ├── export_workflow.py
│ │ ├── force_output_connection.py
│ │ └── knob2input.py
│ ├── update_menu.py
│ ├── upload_and_download.py
│ └── workflow_importer.py
└── testing/
├── __init__.py
└── testing.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
session.vim
.undodir/
*.py[cod]
**/*.swp
nodes/Gizmos
__pycache__
_*/
*.code-workspace
.vscode
tasks.todo
================================================
FILE: .gitmodules
================================================
[submodule "nuke_util"]
path = nuke_util
url = https://github.com/vinavfx/nuke_util
[submodule "python_util"]
path = python_util
url = https://github.com/vinavfx/python_util
================================================
FILE: LICENSE
================================================
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
================================================
FILE: README.md
================================================
# ComfyUI for Nuke
API to be able to use ComfyUI nodes within nuke, only using the ComfyUI server
<div style="display: flex;">
<img src="images/screenshot.png"/>
</div>
## Requirements
* Nuke 11 or higher (Not tested on previous versions !)
* `websocket-client` Python library
* <a href="https://github.com/comfyanonymous/ComfyUI" target="_blank">ComfyUI</a>
* ComfyUI-VideoHelperSuite (required to load images and sequences)
* ComfyUI-HQ-Image-Save (if you want to work in exr)
## Installation
### 1. Copy to nuke folder
```sh
# Linux:
cd ~/.nuke
git clone --recursive https://github.com/vinavfx/ComfyUI-for-Nuke comfyui2nuke
# Windows
# Download git: https://git-scm.com/download/win
cd "C:\Users\<username>\.nuke"
git clone --recursive https://github.com/vinavfx/ComfyUI-for-Nuke comfyui2nuke
```
Or manually copy the entire git downloaded folder and its submodules to the nuke user folder
### 2. Install `websocket-client` Python Library
`websocket-client` is a third-party library needed for the scripts to work correctly. [Here is a direct link to it's pypi installation](https://pypi.org/project/websocket-client/).
This method installs the `websocket-client` library directly to your Nuke's Python environment.
This example will be done with Nuke version 15.1v3, depending on your version change the number.
Open a terminal (or command prompt on Windows) and run:
```bash
# Linux/Mac:
/usr/local/Nuke15.1v3/python3 -m pip install websocket-client
# Windows (As administrator)
"C:\Program Files\Nuke15.1v3\python.exe" -m pip install websocket-client
```
### 3. Copy these lines into <b>menu.py</b>
You can then add or update your Nuke `menu.py` file to include the location of your site-packages installation,
It is not necessary to add the site-package if websocket was installed with the root or administrator user,
since in that case it would be within the Nuke installation !
```python
# Linux/Mac:
nuke.pluginAddPath('{}/.local/lib/python{}.{}/site-packages'.format(
os.path.expanduser('~'), sys.version_info.major, sys.version_info.minor))
# Windows (Add only in Nuke older than 12.2)
nuke.pluginAddPath('C:/Python27/Lib/site-packages')
```
```python
import comfyui2nuke as comfyui
comfyui.setup()
```
## Setup
1 - Modify environment variables in [settings.py](./settings.py)
```python
COMFYUI_DIR = '<path_to_ComfyUI>' # Put the directory where ComfyUI is installed !
HOST = '127.0.0.1:8188'
```
Alternatively, you can set these environment variables instead of modifying [settings.py](./settings.py)
- `NUKE_COMFYUI_DIR` - Path where ComfyUI directory is mounted/mapped
- `NUKE_COMFYUI_HOST` - IP:PORT address of the remote ComfyUI server
2 - Run ComfyUI Server
## Tips
1 - When connecting any image or roto from Nuke, take into consideration the <b>'FrameRange'</b>
of the output because that will be the batch size.
2 - To make ComfyUI work with pixel values greater than 1 and less than 0, change tonemap knob to <b>'linear'</b> in the <b>'SaveEXR'</b> node
3 - Latent images only work with formats with multiple of 8, add the '<b>MultipleOf</b>' node before passing the image
to latent, and in the same node there is a button to create a restore node, put it on the image after inference to restore.
4 - To load all ComfyUI nodes when Nuke starts, change the '<b>UPDATE_MENU_AT_START</b>' variable in the [settings.py](./settings.py) file
5 - To use Switch in ComfyUI nodes statically, use '<b>SwitchAny</b>' otherwise use the ComfyUI switches
6 - If you want to have the ComfyUI server on another machine, you must share the folder where ComfyUI is installed and put the path in [setting.py](./settings.py)
================================================
FILE: __init__.py
================================================
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
import os
import nuke # type: ignore
from .src import *
from .testing import *
from functools import partial
from .settings import UPDATE_MENU_AT_START, COMFYUI2NUKE
def setup():
icon = '{}/icons/comfyui_icon.png'.format(COMFYUI2NUKE)
comfyui_menu = nuke.menu('Nodes').addMenu('ComfyUI', icon=icon)
icon_gray = '{}/icons/comfyui_icon_gray.png'.format(COMFYUI2NUKE)
nodes_dir = os.path.join(COMFYUI2NUKE, 'nodes')
refresh_icon = '{}/icons/refresh.png'.format(COMFYUI2NUKE)
basic_icon = '{}/icons/basic.png'.format(COMFYUI2NUKE)
workflow_icon = '{}/icons/workflow.png'.format(COMFYUI2NUKE)
gizmos_icon = '{}/icons/gizmos.png'.format(COMFYUI2NUKE)
scripts_icon = '{}/icons/scripts.png'.format(COMFYUI2NUKE)
comfyui_menu.addCommand(
'Update all ComfyUI', update_menu.update, '', refresh_icon)
comfyui_menu.addCommand(
'Import Workflow', workflow_importer.import_workflow, '', workflow_icon)
comfyui_menu.addMenu('Basic Nodes', basic_icon)
comfyui_menu.addMenu('Scripts', scripts_icon)
comfyui_menu.addMenu('Gizmos', gizmos_icon)
def create_node(nk):
node = nuke.nodePaste(os.path.join(nodes_dir, nk))
node.showControlPanel()
for dirname in os.listdir(nodes_dir):
folder = os.path.join(nodes_dir, dirname)
if not os.path.isdir(folder):
continue
for nk in os.listdir(folder):
if not nk.split('.')[-1] == 'nk':
continue
name = '{}/{}'.format('Basic Nodes' if dirname ==
'ComfyUI' else dirname, nk.split('.')[0])
path_nk = os.path.join(folder, nk)
comfyui_menu.addCommand(name, partial(
create_node, path_nk), '', icon_gray)
comfyui_menu.addCommand(
'Scripts/knob2input', scripts.knob2input.knob_to_input, icon=icon_gray)
comfyui_menu.addCommand(
'Scripts/forceOutput', scripts.force_output_connection.force_output, icon=icon_gray)
comfyui_menu.addCommand(
'Scripts/exportWorkflow', scripts.export_workflow.export_workflow, icon=icon_gray)
comfyui_menu.addCommand(
'Scripts/executeRuns', execute_runs.execute_runs, 'Ctrl+R', icon=icon_gray)
if UPDATE_MENU_AT_START:
update_menu.update()
================================================
FILE: examples/cmd.nk
================================================
Root {
inputs 0
name cmd.nk
format "2048 1556 0 0 2048 1556 1 2K_Super_35(full-ap)"
proxy_type scale
proxy_format "1024 778 0 0 1024 778 1 1K_Super_35(full-ap)"
colorManagement Nuke
workingSpaceLUT linear
monitorLut sRGB
int8Lut sRGB
int16Lut sRGB
logLut Cineon
floatLut linear
}
CheckerBoard2 {
inputs 0
format "512 512 0 0 512 512 1 square_512"
name CheckerBoard1
xpos 64
ypos -135
}
Group {
name SaveImage
tile_color 0xbcb50001
xpos 64
ypos -52
addUserKnob {20 Controls}
addUserKnob {1 filename_prefix_ l filename_prefix t "The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes."}
filename_prefix_ ComfyUI
addUserKnob {22 data -STARTLINE +HIDDEN T "\{\n 'inputs': \[\n \{\n 'opt': false, \n 'outputs': \[\n 'image'\n ], \n 'name': 'images'\n \}\n ], \n 'class_type': 'SaveImage', \n 'outputs': \[], \n 'output_node': true, \n 'knobs_order': \[\n 'filename_prefix_'\n ], \n 'knobs_class': \{\n 'filename_prefix_': 'string'\n \}, \n 'output_name': \[]\n\}"}
}
Input {
inputs 0
name images
}
Output {
name Output1
selected true
}
end_group
Group {
name Run
tile_color 0x609e38ff
note_font "Bitstream Vera Sans"
xpos 64
ypos -28
addUserKnob {20 controls l Controls}
addUserKnob {22 run l Run t "Send a request to ComfyUI Server" T comfyui.cmd.run() +STARTLINE}
}
Input {
inputs 0
name Input
xpos 145
ypos 93
}
Output {
name Output
xpos 145
ypos 257
}
end_group
================================================
FILE: examples/cmd.py
================================================
# /usr/local/Nuke12.0v8 -t ./cmd.py
import nuke
nuke.scriptOpen('./cmd.nk')
run = nuke.toNode('Run')
run.knob('run').execute()
read = comfyui.cmd.get_read(run)
file = read.knob('file').value()
print(file)
================================================
FILE: nodes/ComfyUI/ComfyUIGizmo.nk
================================================
set cut_paste_input [stack 0]
version 12.0 v8
push $cut_paste_input
Group {
name ComfyUIGizmo
tile_color 0xa2b275ff
selected true
xpos 28
ypos -48
addUserKnob {20 controls l Controls}
addUserKnob {26 comfyui_gizmo l ComfyUIGizmo +INVISIBLE T "This knob only allows the read and backup to be outside the gizmo !"}
addUserKnob {41 run l Run T Run.run}
addUserKnob {22 inferenceEnd +HIDDEN T "read = comfyui.cmd.get_read()" +STARTLINE}
}
Input {
inputs 0
name Input
xpos -40
ypos -417
}
Group {
name SaveImage
tile_color 0xbcb50001
xpos -40
ypos -393
addUserKnob {20 Controls}
addUserKnob {1 filename_prefix_ l filename_prefix t "The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes."}
filename_prefix_ 20251114184410342/image
addUserKnob {22 data -STARTLINE +HIDDEN T "\{\n 'knobs_order': \[\n 'filename_prefix_'\n ], \n 'inputs': \[\n \{\n 'opt': false, \n 'outputs': \[\n 'image'\n ], \n 'name': 'images'\n \}\n ], \n 'class_type': 'SaveImage', \n 'outputs': \[], \n 'output_node': true\n\}"}
}
Input {
inputs 0
name images
}
Output {
name Output1
selected true
}
end_group
Group {
name Run
tile_color 0x609e38ff
note_font "Bitstream Vera Sans"
xpos -40
ypos -369
addUserKnob {20 controls l Controls}
addUserKnob {22 run l Run t "Send a request to ComfyUI Server" T comfyui.cmd.run() +STARTLINE}
}
Input {
inputs 0
name Input
xpos 145
ypos 93
}
Output {
name Output
xpos 145
ypos 257
}
end_group
Output {
name Output1
xpos -40
ypos -343
}
end_group
================================================
FILE: nodes/ComfyUI/MultipleOf.nk
================================================
set cut_paste_input [stack 0]
version 12.0 v8
push $cut_paste_input
Group {
name MultipleOf
tile_color 0xa57aaaff
selected true
xpos 701
ypos -8
addUserKnob {20 controls l Controls}
addUserKnob {3 multiple_of l "Multiple of"}
multiple_of 8
addUserKnob {22 restore_format l "restore format" T "this = nuke.thisNode()\nthis.parent().begin()\n\n\[n.setSelected(False) for n in nuke.selectedNodes()]\n\nrestore_node = nuke.createNode('Reformat', inpanel=False)\nrestore_node.setName('RestoreFormat')\nrestore_node.knob('resize').setValue('none')\nrestore_node.knob('center').setValue(False)\nrestore_node.knob('type').setValue('to box')\nrestore_node.knob('box_fixed').setValue(True)\nrestore_node.setXYpos(this.xpos() + 120, this.ypos())\n\nrestore_node.knob('box_width').setExpression('\{\}.Input.width'.format(this.fullName()))\nrestore_node.knob('box_height').setExpression('\{\}.Input.height'.format(this.fullName()))" +STARTLINE}
}
Input {
inputs 0
name Input
xpos -40
ypos 39
}
Crop {
box {0 0 {"ceil(input0.width / multiple_of) * multiple_of"} {"ceil(input0.height / multiple_of) * multiple_of"}}
reformat true
crop false
name crop
xpos -40
ypos 63
}
Output {
name Output1
xpos -40
ypos 87
}
end_group
================================================
FILE: nodes/ComfyUI/OverrideSettings.nk
================================================
set cut_paste_input [stack 0]
version 12.0 v8
push $cut_paste_input
Group {
name OverrideSettings
onCreate "this = nuke.thisNode()\n\nif not this.knob('created').value():\n this.knob('url').setValue(comfyui.settings.URL)\n this.knob('comfyui_dir').setValue(comfyui.settings.COMFYUI_DIR)\n this.knob('use_exr_to_load_images').setValue(comfyui.settings.USE_EXR_TO_LOAD_IMAGES)\n this.knob('display_meta_in_read_node').setValue(comfyui.settings.DISPLAY_META_IN_READ_NODE)\n this.knob('remote_comfyui').setValue(not comfyui.settings.COMFYUI_LOCAL)\n this.knob('output_directory').setValue(comfyui.settings.OUTPUT_DIRECTORY)\n\n this.knob('created').setValue(True)"
knobChanged "if nuke.thisKnob().name() == 'remote_comfyui':\n nuke.thisNode().knob('comfyui_dir').setEnabled(not nuke.thisKnob().value())"
tile_color 0x609e38ff
selected true
xpos 38
ypos -50
addUserKnob {20 User}
addUserKnob {26 override_settings +INVISIBLE}
addUserKnob {6 created +INVISIBLE +STARTLINE}
created false
addUserKnob {1 url l URL t "Add a single URL like 192.168.1.1:8188, or a list of URLs in JSON format like \[\"http://localhost:8188\", \"192.168.1.1:8188\"]"}
url http://0.0.0.0:8188
addUserKnob {1 headers l Headers}
addUserKnob {1 comfyui_dir l "ComfyUI DIrectory" t "Path to the repository where ComfyUI is located. If it’s a remote connection, it should point to the ComfyUI path on the server."}
addUserKnob {26 ""}
addUserKnob {6 use_exr_to_load_images l "Use EXR to laod images" t "If enabled, EXR images will be loaded using the ComfyUI-HQ-Image-Save add-on; otherwise, PNGs will be loaded using the sequence loader from the ComfyUI-VideoHelperSuite add-on." +STARTLINE}
addUserKnob {6 display_meta_in_read_node l "Display metadata in Read Node" t "Will display the generation metadata in the Read node — seed, cfg, steps, etc." +STARTLINE}
display_meta_in_read_node true
addUserKnob {6 remote_comfyui l "Remote ComfyUI Server" t "If enabled, a shared folder is not required to access the images — they will be uploaded and downloaded directly through ComfyUI’s HTTP server. However, this will be slower since the files, especially EXR images, will need to be transferred back and forth." +STARTLINE}
addUserKnob {6 background_submit l "Backgroundi Submit" t "Sending to the queue without showing the Nuke progress bar will not create the Read Node nor relocate the output directory; you will have to manually search the ComfyUI output folder." +STARTLINE}
addUserKnob {26 ""}
addUserKnob {1 output_directory l "Output Directory" t "Directory where the inference images will be saved. If the path is relative, it will be relative to the Nuke .nk project."}
}
Input {
inputs 0
name Input
xpos 0
}
Output {
name Output1
xpos 0
ypos 300
}
end_group
================================================
FILE: nodes/ComfyUI/Run.nk
================================================
set cut_paste_input [stack 0]
version 12.0 v8
push $cut_paste_input
Group {
name Run
tile_color 0x609e38ff
note_font "Bitstream Vera Sans"
selected true
xpos -40
ypos -369
addUserKnob {20 controls l Controls}
addUserKnob {22 run l Run t "Send a request to ComfyUI Server" T comfyui.cmd.run() +STARTLINE}
}
Input {
inputs 0
name Input
xpos 145
ypos 93
}
Output {
name Output
xpos 145
ypos 257
}
end_group
================================================
FILE: nodes/ComfyUI/SwitchAny.nk
================================================
set cut_paste_input [stack 0]
version 12.0 v8
push $cut_paste_input
Switch {
name SwitchAny
tile_color 0x7f7f7fff
selected true
xpos 327
ypos 120
addUserKnob {20 User +INVISIBLE}
addUserKnob {26 switch_any}
}
================================================
FILE: requirements.txt
================================================
websocket-client
requests
trimesh
================================================
FILE: settings.py
================================================
import os
# ENVIRONMENT VARIABLES
COMFYUI_DIR = os.getenv('NUKE_COMFYUI_DIR', '')
URL = os.getenv('NUKE_COMFYUI_URL', '0.0.0.0:8188')
COMFYUI2NUKE = os.path.dirname(__file__)
COMFYUI_LOCAL = bool(int(os.getenv('COMFYUI_LOCAL', '1')))
OUTPUT_DIRECTORY = os.getenv('OUTPUT_DIRECTORY', '')
# SETTINGS
UPDATE_MENU_AT_START = False
USE_EXR_TO_LOAD_IMAGES = False
DISPLAY_META_IN_READ_NODE = True
TEMPORAL_DIR = os.path.join(os.path.expanduser("~"), '.nuke', 'comfyui_temp')
================================================
FILE: src/__init__.py
================================================
from . import (
common,
connection,
nodes,
run,
update_menu,
read_media,
upload_and_download,
workflow_importer,
execute_runs,
scripts,
queue_manager,
cmd
)
================================================
FILE: src/cmd.py
================================================
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
import nuke # type: ignore
from .run import submit
def get_read(group=None):
if nuke.GUI:
return nuke.toNode(nuke.thisNode().fullName() + 'Read')
if not group:
group = nuke.thisNode()
for n in group.parent().nodes():
if n.name() == group.name() + 'Read':
return n
def inference_end(_, run_node):
callback = run_node.parent().knob('inferenceEnd')
if callback:
callback.execute()
def run():
submit(nuke.thisNode(), inference_end)
================================================
FILE: src/common.py
================================================
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
import os
import nuke # type: ignore
import json
from datetime import datetime
import hashlib
from ..settings import *
from ..nuke_util.nuke_util import get_connected_nodes
if not getattr(nuke, 'comfyui_running', False):
nuke.comfyui_running = False
image_inputs = ['image', 'frames', 'pixels', 'images', 'src_images']
mask_inputs = ['mask', 'attn_mask', 'mask_optional']
updated_inputs = False
def show_message(msg):
if nuke.GUI:
nuke.message(msg)
else:
print(msg)
def update_images_and_mask_inputs(settings):
global image_inputs, mask_inputs, updated_inputs
if updated_inputs:
return
updated_inputs = True
from .connection import GET
info = GET('object_info', settings)
if not info:
return
for _, data in info.items():
input_data = data['input']
required = input_data.get('required', {})
optional = input_data.get('optional', {})
for name, value in list(required.items()) + list(optional.items()):
class_type = value[0]
if class_type in ['*', 'IMAGE']:
if not name in image_inputs:
image_inputs.append(name)
if class_type in ['*', 'MASK']:
if not name in mask_inputs:
mask_inputs.append(name)
def get_date_code():
now = datetime.now()
ms = str(int(now.microsecond / 1000)).zfill(3)
return now.strftime("%Y%m%d%H%M%S") + ms
def get_name_code(name, length=15):
h = hashlib.md5(name.encode('utf-8')).hexdigest()
num = int(h, 16)
code = str(num % (10**length)).zfill(length)
return code
def get_settings(run_node=None):
settings = {
'COMFYUI_DIR': COMFYUI_DIR,
'URL': URL,
'COMFYUI_LOCAL': COMFYUI_LOCAL,
'OUTPUT_DIRECTORY': OUTPUT_DIRECTORY,
'UPDATE_MENU_AT_START': UPDATE_MENU_AT_START,
'USE_EXR_TO_LOAD_IMAGES': USE_EXR_TO_LOAD_IMAGES,
'DISPLAY_META_IN_READ_NODE': DISPLAY_META_IN_READ_NODE,
'TEMPORAL_DIR': TEMPORAL_DIR,
'HTTP_HEADER': {},
'BACKGROUND_SUBMIT': False
}
override_node = None
for n in get_connected_nodes(run_node, ignore_disabled=True, continue_at_up_level=True):
if n.knob('override_settings'):
override_node = n
break
if override_node and override_node.knob('override_settings'):
def override(key):
knob = override_node.knob(key)
if knob:
settings[key.upper()] = override_node.knob(key).value()
override('comfyui_dir')
override('url')
override('background_submit')
override('output_directory')
override('use_exr_to_load_images')
override('display_meta_in_read_node')
settings['COMFYUI_LOCAL'] = not override_node.knob(
'remote_comfyui').value()
headers_value = override_node.knob(
'headers').value().replace("'", '"').strip()
if headers_value:
try:
headers = json.loads(headers_value)
except Exception as e:
show_message("Error parsing headers: {}".format(e))
headers = {}
settings['HTTP_HEADER'] = headers
return settings
def get_server_comfyui_dir(settings):
from .connection import GET
info = GET('system_stats', settings)
if not info:
return '.'
main_py = info['system']['argv'][0]
return os.path.dirname(main_py)
def get_comfyui_dir(settings):
COMFYUI_DIR = settings['COMFYUI_DIR']
if not settings['COMFYUI_LOCAL']:
return ''
if os.path.isdir(os.path.join(COMFYUI_DIR, 'comfy')):
return COMFYUI_DIR
show_message('Directory "{}" does not exist'.format(COMFYUI_DIR))
return ''
================================================
FILE: src/connection.py
================================================
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
import sys
import json
import traceback
from collections import OrderedDict
if sys.version_info.major == 2:
import urllib2 as urllib2 # type: ignore
else:
import urllib.request as urllib2
import nuke # type: ignore
from .common import show_message
def GET(endpoint, settings, warning=True, timeout=30):
url = settings['URL']
if not '://' in url:
url = 'http://{}'.format(url)
url = '{}/{}'.format(url, endpoint)
request = urllib2.Request(url, headers=settings['HTTP_HEADER'])
try:
response = urllib2.urlopen(request, timeout=timeout)
data = response.read().decode()
return json.loads(data, object_pairs_hook=OrderedDict)
except:
if warning:
nuke.executeInMainThread(show_message, args=(
'Error connecting to server {} !'.format(settings['URL']),))
def POST(endpoint, data, settings):
url = '{}/{}'.format(settings['URL'], endpoint)
headers = {'Content-Type': 'application/json'}
headers.update(settings['HTTP_HEADER'])
bytes_data = json.dumps(data).encode('utf-8')
request = urllib2.Request(url, bytes_data, headers)
try:
urllib2.urlopen(request)
return ''
except urllib2.HTTPError as e:
try:
error_bytes = e.read()
error_str = error_bytes.decode('utf-8', errors='ignore').strip()
try:
error = json.loads(error_str)
except json.JSONDecodeError:
show_message('Error parsing JSON from server')
return 'ERROR: JSON parsing'
errors = 'ERROR: {}\n\n'.format(error['error']['message'].upper())
node_errors = error['node_errors'] if error['node_errors'] else {}
for name, value in node_errors.items():
nuke.toNode(name).setSelected(True)
errors += '{}:\n'.format(name)
for err in value['errors']:
errors += ' - {}: {}\n'.format(
err['details'], err['message'])
errors += '\n'
return errors
except:
show_message(traceback.format_exc())
except Exception as e:
return 'Error: {}'.format(e)
def convert_to_utf8(data):
if isinstance(data, dict):
return {convert_to_utf8(key): convert_to_utf8(value) for key, value in data.items()}
elif isinstance(data, list):
return [convert_to_utf8(element) for element in data]
elif isinstance(data, str):
return data.encode('utf-8') if sys.version_info[0] < 3 else data
elif sys.version_info[0] < 3 and isinstance(data, unicode):
return data.encode('utf-8')
else:
return data
================================================
FILE: src/execute_runs.py
================================================
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
import nuke # type: ignore
from ..nuke_util.nuke_util import get_output_nodes
from .run import submit
from .queue_manager import resolve_submission_target
from .common import get_settings
def multi_runs(runs, success_callback=None, force_queue=None):
if not runs:
return
run = runs.pop(0)
aux = run
if run.knob('comfyui_gizmo'):
run = nuke.toNode(run.fullName() + '.Run')
def on_success(read):
if read:
for i, n in get_output_nodes(aux):
n.setInput(i, read)
if not runs and success_callback:
success_callback()
multi_runs(runs, success_callback, force_queue)
if not force_queue:
settings = get_settings(run)
settings = resolve_submission_target(settings)
if not settings:
return
force_queue = 'localhost' if 'localhost' in settings['URL'] else 'server'
submit(run, success_callback=on_success, force_queue=force_queue)
def multi_versions(run, versions, success_callback=None):
for n in run.nodes():
if versions > 1 and n.knob('randomize'):
n.knob('randomize').setValue(True)
runs = [run] * versions
multi_runs(runs, success_callback)
def execute_runs():
runs = []
for n in nuke.selectedNodes():
if n.Class() == 'Read':
run_name = n.name().replace('Read', '')
run = nuke.toNode(run_name)
if run and not run in runs:
runs.append(run)
continue
if not n.knob('run'):
continue
if not n in runs:
runs.append(n)
multi_runs(runs)
================================================
FILE: src/nodes.py
================================================
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
import json
import os
import shutil
import random
import traceback
from collections import Counter
import nuke # type: ignore
from ..testing.testing import status_diff
from .upload_and_download import upload_images
from ..nuke_util.nuke_util import get_connected_nodes, get_project_name
from .common import (image_inputs, mask_inputs, get_server_comfyui_dir,
get_comfyui_dir, get_name_code, show_message)
states = {}
def extract_data(run_node, settings):
output_node = get_input(run_node, 0)
if not output_node:
show_message('Run is not connected!')
return {}, None
output_node_data = get_node_data(output_node)
if not output_node_data.get('output_node', False):
show_message('Connect only to output nodes like SaveImage or SaveEXR !')
return {}, None
nodes = get_connected_comfyui_nodes(run_node)
nuke.root().knob('proxy').setValue(False)
from .read_media import get_tonemap
tonemap = get_tonemap(run_node)
comfyui_nodes = [n.name() for n, _ in nodes]
data = {}
input_node_changed = False
for n, node_data in nodes:
if not check_node(n):
return {}, None
if n.knob('randomize'):
if n.knob('randomize').value():
random_value = random.randrange(1, 9999)
seed_knob = next((n.knob(k) for k in (
'seed_', 'noise_seed_', 'value_') if n.knob(k)), None)
if seed_knob:
seed_knob.setValue(random_value)
node_data['inputs'][seed_knob.name()[:-1]] = random_value
for key in image_inputs + mask_inputs:
input_key = node_data['inputs'].get(key)
if not input_key or not type(input_key) == list:
continue
input_fullname = '{}.{}'.format(
n.parent().fullName(), input_key[0])
if not input_fullname.startswith('root.'):
input_fullname = 'root.' + input_fullname
input_node = nuke.toNode(input_fullname) if input_key else None
if not input_node:
continue
if is_switch_any(input_node):
continue
if not input_node.name() in comfyui_nodes:
load_image_data, changed_node, execution_canceled = create_load_images_and_save(
input_node, tonemap, settings)
if execution_canceled:
return {}, None
input_node_changed = True if changed_node else input_node_changed
data[input_node.name()] = load_image_data
data[n.name()] = node_data
return data, input_node_changed
def create_load_images_and_save(node, tonemap, settings):
global states
connected_nodes = get_connected_nodes(node, continue_at_up_level=True)
connected_nodes.append(node)
state = ''
for n in connected_nodes:
n.setSelected(False)
node_state = ''
# knobs that may vary
knobs_ignore = ['old_message', 'old_expression_markers']
for k in n.knobs().values():
if not k.visible() or not k.enabled():
continue
if k.name() in knobs_ignore:
continue
if k.hasExpression() or k.isAnimated():
try:
value = k.valueAt(0)
except:
value = k.toScript()
else:
value = k.toScript()
node_state += '{} '.format(value)
node_state = node_state.replace(
str(n.xpos()), '').replace(str(n.ypos()), '')
state += node_state
current_state = {'connected_nodes': state.strip(), 'state_id': 0}
prev_state = states.get(node.fullName(), {})
frame_range = [node.firstFrame(), node.lastFrame()]
USE_EXR_TO_LOAD_IMAGES = settings['USE_EXR_TO_LOAD_IMAGES']
if USE_EXR_TO_LOAD_IMAGES:
filepath_key = 'filepath'
load_image_data = {
'frame_range': frame_range,
'inputs': {
'filepath': '',
'tonemap': tonemap,
'image_load_cap': 0,
'select_every_nth': 1,
'skip_first_images': 0
},
'class_type': 'LoadEXR'
}
else:
filepath_key = 'directory'
load_image_data = {
'frame_range': frame_range,
'inputs': {
'directory': '',
'skip_first_images': 0,
'select_every_nth': 1,
'image_load_cap': 0
},
'class_type': 'VHS_LoadImagesPath'
}
if current_state.get('connected_nodes') == prev_state.get('connected_nodes'):
sequence_dir = prev_state.get('sequence_dir', 'none')
filepath = prev_state.get('filepath', 'none')
same_exr_setting = prev_state.get(
'USE_EXR_TO_LOAD_IMAGES') == USE_EXR_TO_LOAD_IMAGES
if os.path.isdir(sequence_dir) and os.listdir(sequence_dir) and same_exr_setting:
load_image_data['inputs'][filepath_key] = filepath
load_image_data['inputs']['id'] = prev_state.get('state_id', 0)
return load_image_data, False, False
# For debugging
# status_diff(prev_state.get('connected_nodes'),
# current_state.get('connected_nodes'))
dirname = get_name_code('{}{}{}{}'.format(
get_project_name(), node.fullName(), frame_range[0], frame_range[1]))
relative_input = os.path.join('input', dirname)
filepath = os.path.join(get_server_comfyui_dir(settings), relative_input)
comfyui_input_dir = os.path.join(
get_comfyui_dir(settings), relative_input).replace('\\', '/')
tmp_input_dir = os.path.join(settings['TEMPORAL_DIR'], relative_input)
sequence_dir = comfyui_input_dir if settings['COMFYUI_LOCAL'] else tmp_input_dir
if os.path.isdir(sequence_dir):
shutil.rmtree(sequence_dir)
os.makedirs(sequence_dir)
ext = 'exr' if USE_EXR_TO_LOAD_IMAGES else 'png'
filename = '{}/{}_#####.{}'.format(sequence_dir, dirname, ext)
[n.setSelected(False) for n in nuke.selectedNodes()]
onode = node
invert = None
if not USE_EXR_TO_LOAD_IMAGES:
# VHS_LoadImages inverts the alpha
invert = nuke.createNode('Invert', inpanel=False)
invert.knob('channels').setValue('alpha')
invert.setInput(0, node)
invert.setXYpos(node.xpos(), node.ypos())
onode = invert
write = nuke.createNode('Write', inpanel=False)
write.knob('hide_input').setValue(True)
write.setName(node.name() + '_write')
write.setXYpos(node.xpos(), node.ypos())
write.setSelected(False)
write.setInput(0, onode)
write.knob('file').setValue(filename)
write.knob('raw').setValue(USE_EXR_TO_LOAD_IMAGES)
write.knob('file_type').setValue(ext)
write.knob('channels').setValue('rgba')
try:
nuke.execute(write, node.firstFrame(), node.lastFrame())
if not settings['COMFYUI_LOCAL']:
upload_images(sequence_dir, settings)
except:
nuke.delete(write)
nuke.delete(invert)
show_message(traceback.format_exc())
return {}, False, True
nuke.delete(write)
nuke.delete(invert)
state_id = random.randrange(1, 9999)
current_state['sequence_dir'] = sequence_dir
current_state['filepath'] = filepath
current_state['USE_EXR_TO_LOAD_IMAGES'] = USE_EXR_TO_LOAD_IMAGES
current_state['state_id'] = state_id
states[node.fullName()] = current_state
load_image_data['inputs'][filepath_key] = filepath
load_image_data['inputs']['id'] = state_id
return load_image_data, True, False
def get_connected_comfyui_nodes(root_node, visited=None, ignore_nodes=[]):
if visited is None:
visited = set()
def is_disabled(n):
disable_knob = n.knob('disable')
if not disable_knob:
return
if disable_knob.value():
return True
sd_nodes = []
for i in range(root_node.maxInputs()):
inode = root_node.input(i)
if not inode:
continue
if not i == 0 and is_disabled(root_node):
continue
if is_switch_any(root_node):
if not root_node.knob('which').value() == i:
continue
if inode in visited:
continue
node_data = extract_node_data(inode)
if node_data:
if node_data['class_type'] in ignore_nodes:
continue
visited.add(inode)
if not is_disabled(inode) and node_data:
sd_nodes.append((inode, node_data))
sd_nodes.extend(get_connected_comfyui_nodes(
inode, visited, ignore_nodes))
return sd_nodes
def get_node_data(node):
data_knob = node.knob('data')
if not data_knob:
return {}
value = data_knob.value()
if not 'class_type' in value:
return {}
data = value.split('#')[0].replace("'", '"').replace(
'True', 'true').replace('False', 'false')
return json.loads(data)
def save_node_data(node, data):
node.knob('data').setValue(json.dumps(data, indent=4))
def extract_node_data(node):
data = get_node_data(node)
if not data:
return {}
inputs = {}
for knob in node.knobs().values():
if not knob.name()[-1:] == '_':
continue
if hasattr(knob, 'valueAt'):
value = knob.valueAt(1) if knob.isAnimated() and not knob.hasExpression() else knob.value()
else:
value = knob.value()
if type(knob) == nuke.Enumeration_Knob:
try:
value = float(value)
except:
pass
if type(value) in [float, int]:
value = int(value) if int(value) == value else value
name = knob.name()[:-1]
inputs[name] = value
for i in range(node.maxInputs()):
inode = get_input(node, i)
if not inode:
continue
ignore = data['inputs'][i].get('ignore', False)
if ignore:
continue
input_name = data['inputs'][i]['name']
output_index = 0
if not get_node_data(inode):
if input_name in image_inputs:
output_index = 0
elif input_name in mask_inputs:
output_index = 1
else:
output_index = get_output_index(node, data, i)
if output_index == -2:
continue
if input_name in inputs:
continue
inputs[input_name] = [inode.name(), output_index]
return {'inputs': inputs, 'class_type': data['class_type']}
def get_output_index(node, node_data, input_index):
inode_data = get_node_data(get_input(node, input_index))
if not inode_data:
return -2
inode_outputs = inode_data['outputs']
allowed_outputs = node_data['inputs'][input_index]['outputs']
force_output = node_data['inputs'][input_index].get('force_output')
if not force_output == None:
return force_output
for allowed_output in allowed_outputs:
for i, o in enumerate(inode_outputs):
if allowed_output in [o, '*'] or '*' == o:
return i
return -1
def check_node(node):
node_data = get_node_data(node)
for i in range(node.maxInputs()):
inode = get_input(node, i)
index_data = node_data['inputs'][i]
input_name = index_data['name']
optional_input = index_data.get('opt', False)
if optional_input and not inode:
continue
if not inode:
show_message(
node.name() + ' : "{}" input disconnected !'.format(input_name))
return
inode_data = get_node_data(inode)
if not inode_data:
if input_name in image_inputs + mask_inputs:
if inode.bbox().w() < 10 or inode.bbox().h() < 10:
show_message(
'{}: input "{}" not connected or bbox without information in some frame !'.format(node.name(), input_name))
return
continue
else:
show_message('{}: "{}" does not support "{}" !'.format(
node.name(), input_name, inode.name()))
return
inode_outputs = inode_data['outputs']
_input = node_data['inputs'][i]
allowed_outputs = _input['outputs']
if '*' not in allowed_outputs and '*' not in inode_outputs:
if not any(o in allowed_outputs for o in inode_outputs):
show_message(
node.name() + ' : "{}" connection not supported !'.format(input_name))
return
if requires_force_output(inode_outputs, allowed_outputs[0]):
if _input.get('force_output') == None:
if nuke.ask('{}:\nConnected to node with duplicate outputs, Connect now?'.format(node.name())):
from .scripts.force_output_connection import force_output
force_output(node)
return
return True
def requires_force_output(outputs, input_class):
contador = Counter(outputs)
repeated = [item for item, count in contador.items() if count > 1]
if input_class == '*' and len(outputs) > 1:
pass
else:
if not repeated:
return False
if not '*' in repeated:
if not input_class in repeated:
return False
return True
def update_input_nodes(node):
for n in nuke.allNodes():
if n.Class() == 'Input':
nuke.delete(n)
data = get_node_data(node)
for idx, i in enumerate(data['inputs']):
inode = nuke.createNode('Input', inpanel=False)
inode.setName(i['name'])
if idx == 0:
nuke.toNode('Output1').setInput(0, inode)
def is_switch_any(node):
if not node.Class() == 'Switch':
return
if not node.knob('switch_any'):
return
return True
def get_input(node, i, ignore_disabled=True):
if not node:
return
inode = node.input(i)
for _ in range(100):
if not inode:
return
disable_knob = inode.knob('disable')
disabled_node = False
if disable_knob and ignore_disabled:
disabled_node = inode.knob('disable').value()
if inode.Class() == 'Dot' or disabled_node or inode.knob('override_settings'):
if inode.input(0):
inode = inode.input(0)
continue
else:
return
if is_switch_any(inode):
which = int(inode.knob('which').value())
if inode.input(which):
inode = inode.input(which)
continue
else:
return
return inode
================================================
FILE: src/queue_manager.py
================================================
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
import json
import re
import nuke # type: ignore
from .connection import GET, POST
from .common import show_message
def resolve_submission_target(settings, force_queue=None):
url = settings['URL']
urls = []
pattern = r'^(https?://)?([a-zA-Z0-9.-]+|\d{1,3}(\.\d{1,3}){3})(:\d{1,5})?$'
if re.match(pattern, url):
urls = [url]
else:
try:
urls = json.loads(url)
except:
show_message(
'{}\nIt has to be an URL address or a list of URL addresses as JSON !'.format(url))
return
urls = [
url if '://' in url else 'http://{}'.format(url)
for url in urls
]
available_url = ''
lowest_load_url = None
lowest_pending = 99999
localhost_submit = False
running_client = []
pending_client = []
for url in urls:
settings['URL'] = url
queue = GET('queue', settings, warning=False, timeout=3)
if not queue:
continue
running = queue['queue_running']
pending = queue['queue_pending']
if len(pending) < lowest_pending:
lowest_pending = len(pending)
lowest_load_url = url
if not available_url and not running:
available_url = url
running_client += [r[3]['client_id'] for r in running]
pending_client += [p[3]['client_id'] for p in pending]
if not available_url and not lowest_load_url:
show_message(
"{}\nNo ComfyUI servers found running !".format(', '.join(urls)))
return
elif available_url:
settings['URL'] = available_url
else:
def ellipsis(s, n): return s if len(s) <= n else s[:n-3] + "..."
msg = '<b>Running</b>:\n'
for i, client in enumerate(running_client):
user, nk, send_id = (client.split(':') + [client, '', 1])[:3]
msg += ' {} - <font color=orange>{}</font> : {} : <font color=#6cb56b>{}</font>\n'.format(
i+1, user, ellipsis(nk, 50), send_id)
if pending_client:
msg += '\n<b>Pending</b>:\n'
for i, client in enumerate(pending_client):
user, nk, send_id = (client.split(':') + [client, '', ''])[:3]
msg += ' {} - <font color=orange>{}</font> : {} : <font color=#6cb56b>{}</font>\n'.format(
i+1, user, ellipsis(nk, 50), send_id)
try:
if force_queue:
if force_queue == 'localhost':
settings['URL'] = 'http://localhost:8188'
localhost_submit = True
else:
settings['URL'] = lowest_load_url
elif nuke.askWithCancel("{}\n\nJobs running. Queue or run locally?\n<font color=#6cb56b>Yes = Queue / No = localhost".format(msg)):
settings['URL'] = lowest_load_url
else:
settings['URL'] = 'http://localhost:8188'
localhost_submit = True
except:
return
if settings['COMFYUI_LOCAL']:
comfyui_dir = settings['COMFYUI_DIR']
comfyui_dirs = []
pattern = r'^[^\*\[\]]+$'
if re.match(pattern, comfyui_dir):
comfyui_dirs = [comfyui_dir]
else:
try:
comfyui_dirs = json.loads(comfyui_dir)
except:
show_message(
'{}\nIt must be a ComfyUI directory or a list of ComfyUI directories in JSON format!'.format(comfyui_dir))
return
if not len(urls) == len(comfyui_dirs):
comfyui_dirs = [comfyui_dirs[0]] * len(urls)
settings['COMFYUI_DIR'] = dict(
zip(urls, comfyui_dirs)).get(settings['URL'], '')
if localhost_submit:
settings['COMFYUI_DIR'] = comfyui_dirs[0]
elif not settings['COMFYUI_DIR']:
show_message(
'URL "{}" without assigned ComfyUI directory !'.format(settings['URL']))
return
if not GET('system_stats', settings):
return
return settings
def interrupt(settings, client_id):
queue = GET('queue', settings)
if not queue:
return
def find_prompt_id(queue_list):
return next((r[1] for r in queue_list if r[3].get('client_id') == client_id), '')
prompt_id = find_prompt_id(queue['queue_running'])
endpoint = 'interrupt' if prompt_id else 'queue'
if not prompt_id:
prompt_id = find_prompt_id(queue['queue_pending'])
if prompt_id:
error = POST(endpoint, {'delete': [prompt_id]}, settings)
if error:
show_message(error)
================================================
FILE: src/read_media.py
================================================
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
import os
import shutil
import nuke # type: ignore
from ..nuke_util.media_util import get_padding, get_name_no_padding
from ..nuke_util.nuke_util import get_output_nodes
from .nodes import get_connected_comfyui_nodes, get_input
from .common import get_date_code
from .upload_and_download import download_images
from .update_menu import normalize_nodename
def exr_filepath_fixed(run_node):
nodes = get_connected_comfyui_nodes(run_node)
for n, _ in nodes:
filepath_knob = n.knob('filepath_')
if not filepath_knob:
continue
filepath = filepath_knob.value()
padding = get_padding(filepath)
if not padding:
continue
filepath = filepath.replace(padding, '%04d')
filepath_knob.setText(filepath)
def get_tonemap(run_node):
save_node = get_input(run_node, 0)
if not save_node:
return 'sRGB'
tonemap_knob = save_node.knob('tonemap_')
if not tonemap_knob:
return 'sRGB'
return tonemap_knob.value()
def update_filename_prefix(run_node, update=True, data={}):
output_node = get_input(run_node, 0)
if not output_node:
return
filename_prefix_knob = output_node.knob('filename_prefix_')
if not filename_prefix_knob:
return
if not update:
return filename_prefix_knob.value()
prefix = filename_prefix_knob.value()
old_rand = prefix.split('/')[0]
if old_rand.isdigit():
prefix = prefix.replace(old_rand + '/', '')
new_prefix = '{}/{}'.format(get_date_code(), prefix)
filename_prefix_knob.setValue(new_prefix)
data[output_node.name()]['inputs']['filename_prefix'] = new_prefix
return new_prefix
def set_correct_colorspace(read):
filename = read.knob('file').value()
ext = filename.split('.')[-1]
if ext == 'exr':
read.knob('raw').setValue(True)
else:
read.knob('raw').setValue(False)
def get_gizmo_group(run_node):
gizmo = run_node
while gizmo:
gizmo = gizmo.parent()
if not hasattr(gizmo, 'knob'):
return
if gizmo.knob('comfyui_gizmo'):
return gizmo
def extract_meta(data):
noise_seed = seed = steps = denoise = guidance = causvid = strength = -1
scheduler = sampler_name = lora = lora2 = lora3 = cnet = ''
for name, node in data.items():
class_type = node['class_type']
inputs = node['inputs']
if noise_seed == -1:
noise_seed = inputs.get('noise_seed', -1)
if seed == -1:
seed = inputs.get('seed', -1)
if not sampler_name:
sampler_name = inputs.get('sampler_name', '')
if steps == -1:
steps = inputs.get('steps', -1)
if denoise == -1:
denoise = inputs.get('denoise', -1)
if not scheduler:
scheduler = inputs.get('scheduler', '')
if guidance == -1:
guidance = inputs.get('guidance', -1)
if causvid == -1:
lora_name = inputs.get('lora_name', '')
if 'CausVid' in lora_name:
causvid = inputs.get('strength_model', 0)
if class_type == 'WanVaceToVideo':
strength = inputs.get('strength')
if name in ('extra_lora1', 'extra_lora2', 'extra_lora3'):
lora_name = inputs.get('lora_name', '').split(
'/')[-1].rsplit('.', 1)[0]
lora_strength = inputs.get('strength_model', 0)
formatted = '{}:{}'.format(lora_name, lora_strength)
if name == 'extra_lora1':
lora = formatted
elif name == 'extra_lora2':
lora2 = formatted
elif name == 'extra_lora3':
lora3 = formatted
if class_type == 'ControlNetApplyAdvanced':
cnet_strength = inputs.get('strength', 0)
cnet_end = inputs.get('end_percent', 0)
cnet = '{} : {}'.format(cnet_strength, cnet_end)
meta = []
if not seed == -1:
meta.append(('seed', seed))
if not noise_seed == -1:
meta.append(('noise_seed', noise_seed))
if not steps == -1:
meta.append(('steps', steps))
if sampler_name:
meta.append(('sampler_name', sampler_name))
if scheduler:
meta.append(('scheduler', scheduler))
if not denoise == -1:
meta.append(('denoise', denoise))
if not guidance == -1:
meta.append(('guidance', guidance))
if not strength == -1:
meta.append(('strength', strength))
if not causvid == -1:
meta.append(('causvid', causvid))
if cnet:
meta.append(('CNet', cnet))
if lora:
meta.append(('lora', lora))
if lora2:
meta.append(('lora2', lora2))
if lora3:
meta.append(('lora3', lora3))
return meta
def glb2obj(filename):
import trimesh # type: ignore
mesh = trimesh.load(filename)
obj = filename[:-3] + 'obj'
mesh.export(obj)
read = nuke.createNode('ReadGeo', inpanel=False)
read.knob('file').setValue(obj)
read.setInput(0, None)
return read
def get_frame_range(data):
# Of all the read nodes, it gets the longest range.
ranges = [n.get('frame_range')
for n in data.values() if n.get('frame_range')]
if not ranges:
return [1, 1]
return max(ranges, key=lambda r: r[1] - r[0])
def get_output_path(settings, default_output=False):
default_output_dir = os.path.join(settings['COMFYUI_DIR'], 'output')
if default_output:
return default_output_dir
output_dir = settings['OUTPUT_DIRECTORY'].strip()
untitled = settings['project_name'] == 'Root'
if os.path.isabs(output_dir) and os.path.isdir(output_dir):
return output_dir
elif output_dir and not untitled:
return os.path.join(os.path.dirname(settings['project_name']), output_dir)
elif settings['COMFYUI_LOCAL'] and not untitled:
return default_output_dir
return os.path.join(settings['TEMPORAL_DIR'], 'output')
def relocate_filename(filename, settings):
if not settings['OUTPUT_DIRECTORY'].strip():
return filename
if not filename:
return
task = nuke.ProgressTask('Relocate from ComfyUI')
task.setMessage('Relocating: ...')
task.setProgress(0)
output_dir = get_output_path(settings)
if not os.path.isdir(output_dir):
os.makedirs(output_dir)
src_dir = os.path.dirname(filename)
dst_dir = os.path.join(output_dir, os.path.basename(src_dir))
if os.path.exists(dst_dir):
shutil.rmtree(dst_dir)
os.mkdir(dst_dir)
files = os.listdir(src_dir)
for i, f in enumerate(files):
src_file = os.path.join(src_dir, f)
if os.path.isfile(src_file):
shutil.move(src_file, dst_dir)
task.setMessage('Relocating: ' + f)
task.setProgress(int((i / float(len(files))) * 100))
task.setProgress(100)
return os.path.join(dst_dir, os.path.basename(filename))
def get_separate_filename(settings, default_output=False):
filename_prefix = settings.get('filename_prefix')
if filename_prefix:
basename = os.path.basename(filename_prefix)
dirname = os.path.dirname(filename_prefix)
sequence_output = os.path.join(get_output_path(
settings, default_output), dirname)
return filename_prefix, basename, sequence_output
else:
return None, None, None
def get_local_filename(settings, default_output=False):
_, basename, sequence_output = get_separate_filename(settings, default_output)
if not sequence_output:
return
filenames = nuke.getFileNameList(sequence_output)
if not filenames:
return
filename = next((fn for fn in filenames if basename in fn), None)
if not filename:
return
return os.path.join(sequence_output, filename)
def resolve_filename(run_node, data, settings, already_generated=False):
if settings['COMFYUI_LOCAL']:
if already_generated:
filename = get_local_filename(settings)
else:
filename = get_local_filename(settings, default_output=True)
filename = relocate_filename(filename, settings)
else:
output_dir = get_output_path(settings)
if not os.path.isdir(output_dir):
os.makedirs(output_dir)
filename = download_images(
get_separate_filename(settings), output_dir,
get_frame_range(data), settings, run_node)
return filename
def create_read(run_node, data, settings, filename, already_exists=False):
if not filename:
return
if not already_exists:
backup_previous_generation(run_node)
meta = []
if data:
meta = extract_meta(data)
main_node = get_gizmo_group(run_node)
if not main_node:
main_node = run_node
main_node.parent().begin()
fullname = '{}Read'.format(main_node.fullName())
name = '{}Read'.format(main_node.name())
ext = filename.split('.')[-1].split(' ')[0].lower()
if ext in ['jpg', 'exr', 'tiff', 'png']:
read = nuke.toNode(fullname)
if not read:
read = nuke.createNode('Read', inpanel=False)
read.knob('file').fromUserText(filename)
read.knob('frame_mode').setValue('start at')
read.knob('frame').setValue(str(get_frame_range(data)[0]))
set_correct_colorspace(read)
elif ext in ['glb']:
read = glb2obj(filename)
else:
return
read.setName(name)
read.setXYpos(main_node.xpos(), main_node.ypos() + 35)
read.knob('tile_color').setValue(
main_node.knob('tile_color').value())
label = ''
if meta and settings['DISPLAY_META_IN_READ_NODE']:
label = '<center>'
for key, value in meta:
label += '<font color="green" size=1>{}:</font><font color="white" size=1> {}</>\n'.format(
key, value)
read.knob('label').setValue(label)
comfyui_gizmo = run_node.parent() if run_node.parent().knob(
'comfyui_gizmo') else run_node
for i, onode in get_output_nodes(comfyui_gizmo):
onode.setInput(i, read)
return read
def backup_previous_generation(run_node=None):
if not run_node:
run_node = nuke.thisNode()
main_node = get_gizmo_group(run_node)
if not main_node:
main_node = run_node
main_node.parent().begin()
read = nuke.toNode(main_node.name() + 'Read')
if not read:
return
filename = '{} {}-{}'.format(read.knob('file').value(),
read.knob('first').value(), read.knob('last').value())
basename = get_name_no_padding(filename).replace(' ', '_')
rand = os.path.basename(os.path.dirname(filename)).strip()
name = '{}Backup_{}_{}'.format(main_node.name(), rand, basename)
name = normalize_nodename(name)
if not nuke.toNode(name):
new_read = nuke.createNode('Read', inpanel=False)
new_read.setName(name)
new_read.knob('file').fromUserText(filename)
new_read.knob('label').setValue(read.knob('label').value())
new_read.knob('frame_mode').setValue(read.knob('frame_mode').value())
new_read.knob('frame').setValue(read.knob('frame').value())
set_correct_colorspace(new_read)
reads = sorted(
[n for n in nuke.allNodes('Read') if n.name().split('Backup')[0] == main_node.name()],
key=lambda n: n.name(),
reverse=True
)
xpos = read.xpos() + 150
ypos = read.ypos()
offset_x = 100
offset_y = 20 + max(reads, key=lambda n: n.screenHeight()).screenHeight()
per_row = 10
for i, n in enumerate(reads):
col = i % per_row
row = i // per_row
n.setXYpos(xpos + col * offset_x, ypos + row * offset_y)
================================================
FILE: src/run.py
================================================
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
import textwrap
import sys
import nuke # type: ignore
import os
import traceback
from time import sleep, time
import websocket
import json
import threading
import copy
from ..nuke_util.nuke_util import set_tile_color, get_connected_nodes, get_user_path, get_project_name
from .common import get_comfyui_dir, update_images_and_mask_inputs, get_settings, show_message
from .connection import POST
from .queue_manager import resolve_submission_target, interrupt
from .nodes import extract_data
from .read_media import create_read, update_filename_prefix, exr_filepath_fixed, resolve_filename
states = {}
prompt_counter = 0
def error_node_style(node_name, enable, message=''):
node = nuke.toNode(node_name)
if not node:
return
if enable:
set_tile_color(node, [0, 1, 1])
message = ' '.join(message.split()[:30])
formatted_message = '\n'.join(textwrap.wrap(message, width=30))
node.knob('label').setValue('ERROR:\n' + formatted_message)
else:
node['tile_color'].setValue(0)
node.knob('label').setValue('')
def remove_all_error_style(root_node):
for n in get_connected_nodes(root_node):
label_knob = n.knob('label')
if 'ERROR' in label_knob.value():
error_node_style(n.fullName(), False)
def update_node(node_name, data, run_node, settings):
if 'ShowText' in node_name:
show_text_uptate(node_name, data, run_node)
elif 'PreviewImage' in node_name:
preview_image_update(node_name, data, settings)
def show_text_uptate(node_name, data, run_node):
output = data.get('output', {})
texts = output.get('text', [])
text = texts[0] if texts else ''
run_node.parent().begin()
show_text_node = nuke.toNode(node_name)
if not show_text_node:
return
if not text:
return
text = text.replace('\n', '')
text = text.encode('utf-8') if sys.version_info[0] < 3 else text
formatted_text = '\n'.join(textwrap.wrap(text, width=50))
text_knob = show_text_node.knob('text')
if text_knob:
text_knob.setValue(text)
output_text_node = nuke.toNode(node_name + 'Output')
if not output_text_node:
return
label = '( [value {}.name] )\n{}\n\n'.format(node_name, formatted_text)
output_text_node.knob('label').setValue(label)
xpos = show_text_node.xpos() - output_text_node.screenWidth() - 50
ypos = show_text_node.ypos() - (output_text_node.screenHeight() / 2) + \
(show_text_node.screenHeight() / 2)
output_text_node.knob('label')
output_text_node.setXYpos(xpos, ypos)
def preview_image_update(node_name, data, settings):
output = data.get('output', {})
images = output.get('images', [])
if not images:
return
filename = images[0].get('filename')
if not filename:
return
preview_node = nuke.toNode(node_name)
if not preview_node:
return
preview_node.begin()
filename = '{}/temp/{}'.format(settings['COMFYUI_DIR'], filename)
read = nuke.toNode('read')
if not read:
read = nuke.createNode('Read', inpanel=False)
read.setName('read')
read.knob('file').setValue(filename)
nuke.toNode('Output1').setInput(0, read)
preview_node.knob('postage_stamp').setValue(True)
preview_node.end()
def execute_in_main_thread(func, args=(), kwargs=None):
if kwargs is None:
kwargs = {}
if nuke.GUI:
return nuke.executeInMainThread(func, args=args, kwargs=kwargs)
return func(*args, **kwargs)
def submit(run_node=None, success_callback=None, force_queue=None):
def success_callback_wrapper(read, run_node):
if not success_callback:
return
if success_callback.__code__.co_argcount >= 2:
success_callback(read, run_node)
else:
success_callback(read)
total_time = time()
run_node = run_node or nuke.thisNode()
run_node.begin()
settings = get_settings(run_node)
if not resolve_submission_target(settings, force_queue):
return
update_images_and_mask_inputs(settings)
if settings['COMFYUI_LOCAL'] and not get_comfyui_dir(settings):
return
exr_filepath_fixed(run_node)
settings['project_name'] = nuke.root().name()
data, input_node_changed = extract_data(run_node, settings)
if not data:
return
global states
if data == states.get(run_node.fullName(), {}) and not input_node_changed:
settings['filename_prefix'] = update_filename_prefix(run_node, False)
filename = resolve_filename(run_node, data, settings, True)
read = create_read(run_node, data, settings, filename, already_exists=True)
success_callback_wrapper(read, run_node)
return
settings['filename_prefix'] = update_filename_prefix(run_node, data=data)
state_data = copy.deepcopy(data)
global prompt_counter; prompt_counter += 1
client_id = '{}:{}:{}'.format(os.path.basename(
get_user_path()), get_project_name(), prompt_counter).replace(' ', '-')
body = {
'client_id': client_id,
'prompt': data,
'extra_data': {}
}
url = "{}/ws?clientId={}".format(settings['URL'].replace('http', 'ws'), client_id)
task_status = {'title': 'Inferencing',
'progress': 0, 'message': 'Waiting in Queue ...'}
task = [nuke.ProgressTask(task_status['title'])]
task[0].setMessage(task_status['message'])
execution_error = [False]
def set_task_progress(progress, message = ''):
if not nuke.GUI:
print('{} : {}%'.format(message or task_status['message'], progress))
if not task:
return
task[0].setProgress(progress)
task_status['progress'] = progress
if message:
task[0].setMessage(message)
task_status['message'] = message
def on_message(_, message):
try:
message = json.loads(message)
except:
return
data = message.get('data', None)
type_data = message.get('type', None)
if not data:
return
elif type_data == 'executed':
node = data.get('node')
execute_in_main_thread(
update_node, args=(node, data, run_node, settings))
elif type_data == 'progress':
progress = int(data['value'] * 100 / float(data['max'] or 0.01))
set_task_progress(progress)
elif type_data == 'executing':
node = data.get('node')
if task:
if node:
set_task_progress(0, node)
else:
del task[0]
elif type_data == 'execution_error':
execution_message = data.get('exception_message')
error = 'Error: {}\n\n'.format(data.get('node_type'))
error += execution_message + '\n\n'
for tb in data.get('traceback'):
error += tb + '\n'
execution_error[0] = True
if task:
del task[0]
execute_in_main_thread(
error_node_style, args=(data.get('node_id'), True, execution_message))
execute_in_main_thread(show_message, args=(error))
def on_error(ws, error):
ws.close()
if task:
del task[0]
if 'connected' in str(error):
return
execution_error[0] = True
execute_in_main_thread(show_message, args=('error: ' + str(error)))
def progress_task_loop():
cancelled = False
while task:
if task[0].isCancelled():
if nuke.executeInMainThreadWithResult(lambda: nuke.ask(
'Are you sure? This will stop the ComfyUI inference')):
cancelled = True
break
elif task:
task[0] = nuke.ProgressTask(task_status['title'])
task[0].setProgress(task_status['progress'])
task[0].setMessage(task_status['message'])
sleep(.1)
interrupt(settings, client_id)
if task:
del task[0]
ws.close()
if cancelled:
return
filename = resolve_filename(run_node, data, settings)
execute_in_main_thread(
progress_finished, args=(run_node, filename))
def progress_finished(n, filename):
try:
read = create_read(n, data, settings, filename)
success_callback_wrapper(read, run_node)
if not execution_error[0]:
remove_all_error_style(run_node)
states[run_node.fullName()] = state_data
except:
if not nuke.GUI:
print(traceback.format_exc())
execute_in_main_thread(
show_message, args=(traceback.format_exc()))
headers = ["{}: {}".format(k, v) for k, v in settings['HTTP_HEADER'].items()]
ws = websocket.WebSocketApp(url, header=headers, on_message=on_message, on_error=on_error)
task_loop = None
if not settings['BACKGROUND_SUBMIT']:
threading.Thread(target=ws.run_forever).start()
task_loop = threading.Thread(target=progress_task_loop)
task_loop.start()
error = POST('prompt', body, settings)
if settings['BACKGROUND_SUBMIT'] and not error:
show_message('Workflow sent to the ComfyUI Queue\n{}/output/{}'.format(
settings['COMFYUI_DIR'], os.path.dirname(settings['filename_prefix'] or '')))
if error:
execution_error[0] = True
if task:
del task[0]
show_message(error)
if not nuke.GUI:
task_loop.join() if task_loop else None
print('\nPrompt executed in {} seconds'.format(round(time() - total_time, 1)))
================================================
FILE: src/scripts/__init__.py
================================================
from . import (
knob2input,
force_output_connection,
export_workflow
)
================================================
FILE: src/scripts/export_workflow.py
================================================
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
import nuke # type: ignore
import os
from ..nodes import extract_data
from ...nuke_util.nuke_util import selected_node
from ...python_util.util import jwrite
from ..common import update_images_and_mask_inputs, get_settings
def export_workflow():
node = selected_node()
if not node:
return
if node.knob('comfyui_gizmo'):
node.begin()
node = nuke.toNode('Run')
elif not node.knob('run'):
nuke.message("Select the 'Run' node")
return
settings = get_settings()
update_images_and_mask_inputs(settings)
data, _ = extract_data(node, settings)
if not data:
return
workflow = nuke.getFilename(
'Export Workflow',
"*.json",
os.path.join(os.path.expanduser('~'), 'Desktop/workflow.json'),
type='save'
)
if not workflow:
return
workflow = workflow if 'json' in workflow else workflow + '.json'
jwrite(workflow, data)
nuke.message('Workflow Saved: ' + workflow)
================================================
FILE: src/scripts/force_output_connection.py
================================================
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
import nuke # type: ignore
from ...nuke_util.nuke_util import get_input, selected_node
from ..nodes import get_node_data, requires_force_output, save_node_data
def force_output(node=None):
if not node:
node = selected_node()
if not node:
return
data = get_node_data(node)
p = nuke.Panel('Force Output ({})'.format(node.name()))
items = []
for i in range(node.inputs()):
inode = get_input(node, i, active_switch=True)
if not inode:
continue
inputs_data = data['inputs'][i]
input_class = inputs_data['outputs'][0]
force_output = inputs_data.get('force_output')
inputs = list(reversed(nuke.allNodes(filter='Input', group=node)))
input_node = inputs[i]
label = input_node.name() + ' : ' + inode.name()
dst_node_data = get_node_data(inode)
if not dst_node_data:
continue
outputs = dst_node_data['outputs']
if not requires_force_output(outputs, input_class):
data['inputs'][i].pop('force_output', None)
continue
if not 'output_name' in dst_node_data:
nuke.message('{} obsolete node, generate node again'.format(dst_node_data['class_type']))
return
output_name = dst_node_data['output_name']
outputs_items = ' '.join([n.replace(' ', '\\ ') for n in output_name])
outputs_items = '- ' + outputs_items
if not force_output == None:
outputs_items = output_name[force_output] + ' ' + outputs_items
p.addEnumerationPulldown(label, outputs_items)
items.append((label, output_name, i))
save_node_data(node, data)
if not items:
nuke.message('All outputs are different, there is no need to force it')
node.knob('label').setValue('')
return
if not p.show():
return
force_outputs = ''
for label, output_name, input_index in items:
value = p.value(label)
if value == '-':
data['inputs'][input_index].pop('force_output', None)
continue
output_index = output_name.index(value)
input_name = data['inputs'][input_index]['name']
data['inputs'][input_index]['force_output'] = output_index
force_outputs += '{} -> {}\n'.format(input_name, value)
if force_outputs:
node.knob('label').setValue(
'<font color="green" size=1>{}</font>'.format(force_outputs[:-1]))
else:
node.knob('label').setValue('')
save_node_data(node, data)
================================================
FILE: src/scripts/knob2input.py
================================================
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
import nuke # type: ignore
from ...nuke_util.nuke_util import selected_node
from ..nodes import get_node_data, save_node_data
def knob_to_input():
node = selected_node()
if not node:
return
data = get_node_data(node)
if not data:
nuke.message('Must be a ComfyUI node !')
return
panel = nuke.Panel('Knob to Input ({})'.format(node.name()))
knobs = []
for knob in data['knobs_order']:
if not knob in data['knobs_class']:
continue
_class = data['knobs_class'][knob]
knobs.append((knob, knob[:-1], _class))
for knob, knob_name, _ in knobs:
if any(v.get('name') == knob_name for v in data['inputs']):
panel.addBooleanCheckBox(knob_name, True)
else:
panel.addBooleanCheckBox(knob_name, False)
if not panel.show():
return
knobs = [[panel.value(knob_name), knob, knob_name, _class]
for knob, knob_name, _class in knobs]
convert_knobs(node, data, knobs)
def convert_knobs(node, data, knobs):
for value, knob, knob_name, _class in knobs:
knob_data = {
'opt': False,
'outputs': [_class],
'name': knob_name
}
exists_konb = any(i.get('name') == knob_name for i in data['inputs'])
if value:
if not exists_konb:
data['inputs'].append(knob_data)
_knob = node.knob(knob)
_knob.setName(knob_name + '_hide')
_knob.setVisible(False)
node.begin()
input_node = nuke.createNode('Input', inpanel=False)
input_node.setSelected(False)
input_node.setName(knob_name)
node.end()
elif exists_konb:
node.begin()
nuke.delete(nuke.toNode(knob_name))
node.end()
data['inputs'] = [i for i in data['inputs']
if i.get('name') != knob_name]
_knob = node.knob(knob_name + '_hide')
_knob.setName(knob)
_knob.setVisible(True)
node.knob('label').setValue('')
save_node_data(node, data)
================================================
FILE: src/update_menu.py
================================================
# -*- coding: utf-8 -*-
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
from functools import partial
import re
import json
import nuke # type: ignore
from ..nuke_util.nuke_util import set_tile_color, get_output_nodes
from .connection import GET, convert_to_utf8
from ..settings import COMFYUI2NUKE
from .common import get_settings, show_message
comfyui_nodes = {}
menu_updated = False
def normalize_nodename(name):
if not name.strip():
return 'unnamed'
name = re.sub(r'[^a-zA-Z0-9_]', '', name)
if name and name[0].isdigit():
name = '_' + name
return name
def get_nodes():
if not comfyui_nodes:
update()
return comfyui_nodes
def create_comfyui_node(node_type, inpanel=True):
node_data = comfyui_nodes.get(node_type)
if not node_data:
return
return create_node(node_data, inpanel)
def refresh_models(node, knob_name, class_type):
update()
nodes = get_nodes()
knob = node.knob(knob_name)
_knob = nodes[class_type]['input']['required'][knob_name[:-1]]
models = _knob[0]
if models == 'COMBO':
models = _knob[1].get('options', [])
knob.setValues(models)
def create_node(data, inpanel=True):
try:
selected_node = nuke.selectedNode()
except:
selected_node = None
n = nuke.createNode('Group', inpanel=inpanel)
name = normalize_nodename(data['name'])
display_name = normalize_nodename(data['display_name'])
if display_name[0].isdigit():
display_name = '_' + display_name
n.setName(display_name)
category = data['category'].split('/')[-1]
if category == 'loaders':
set_tile_color(n, [.57, .58, .48])
elif category == 'mask':
set_tile_color(n, [.33, .42, .77])
elif 'VAE' in name:
set_tile_color(n, [.08, .8, .97])
elif 'Save' in name:
set_tile_color(n, [.16, 1, .74])
elif 'Merge' in name or 'Combine' in name:
set_tile_color(n, [.64, .62, .77])
inputs = []
input_data = data['input']
required = input_data.get('required', {})
optional = input_data.get('optional', {})
input_order = data.get('input_order', {})
required_order = input_order.get('required', [])
optional_order = input_order.get('optional', [])
knobs_order = []
knobs_class = {}
for key in required_order + optional_order:
_input = required.get(key, [])
is_optional = not _input
if is_optional:
_input = optional.get(key)
_class = _input[0]
info = _input[1] if len(_input) == 2 else {}
if not type(info) == dict:
continue
tooltip = info.get('tooltip', '')
placeholder = info.get('placeholder', '')
force_input = info.get('forceInput', False)
default_value = info.get('default', 0)
knob_name = key + '_'
if force_input:
inputs.append([key, _class, is_optional])
continue
elif _class == 'INT':
knob = nuke.Int_Knob(knob_name, key)
default_value = default_value if default_value < 1e9 else 1e9
knob.setValue(int(default_value))
knob.setTooltip(tooltip)
elif _class == 'FLOAT':
min_value = info.get('min', 0)
max_value = info.get('max', 1)
knob = nuke.Double_Knob(knob_name, key)
knob.setRange(min_value, max_value)
knob.setValue(default_value)
knob.setTooltip(tooltip)
elif _class == 'STRING' and key in ['filepath', 'file', 'directory']:
knob = nuke.File_Knob(knob_name, key)
knob.setTooltip(tooltip)
elif _class == 'STRING':
multiline = info.get('multiline', False)
if multiline:
knob = nuke.Multiline_Eval_String_Knob(knob_name, key)
else:
knob = nuke.String_Knob(knob_name, key)
default_string = info.get('default', '')
knob.setText(str(default_string))
knob.setTooltip(tooltip + placeholder)
elif _class in ['BOOLEAN', [True, False], [[True, False]]]:
knob = nuke.Boolean_Knob(knob_name, key)
knob.setFlag(nuke.STARTLINE)
knob.setValue(default_value)
knob.setTooltip(tooltip)
elif type(_class) == list or _class == 'COMBO':
if _class == 'COMBO':
options = info.get('options', [])
else:
options = _class
knob = nuke.Enumeration_Knob(
knob_name, key, [str(i) for i in options])
knob.setTooltip(tooltip)
default_item = str(info.get('default', None))
if not default_item == 'None':
knob.setValue(default_item)
else:
inputs.append([key, _class, is_optional])
continue
n.addKnob(knob)
knobs_order.append(knob.name())
if _class in ['INT', 'STRING', 'BOOLEAN', 'FLOAT']:
knobs_class[knob.name()] = str(_class).lower()
if name in ['LoadAudio', 'LoadImage']:
upload_knob = nuke.PyScript_Knob('upload', '+')
upload_knob.setValue('comfyui.upload_and_download.upload_media()')
n.addKnob(upload_knob)
if category == 'loaders' and 'name' in knob_name:
refresh_models_knob = nuke.PyScript_Knob('refresh_models', '🔄')
refresh_models_knob.setValue(
'comfyui.update_menu.refresh_models(nuke.thisNode(), "{}", "{}")'. format(knob_name, data['name']))
n.addKnob(refresh_models_knob)
if 'seed' in key:
randomize_knob = nuke.Boolean_Knob('randomize')
randomize_knob.setTooltip(
'Allows the linked Run to automatically change the seed by randomizing the number.')
randomize_knob.setValue(False)
n.addKnob(randomize_knob)
# Nuke no genera automaticamente una nueva entrada, asi que genera una entrada 2 cuando solo hay 1 !
if inputs:
inputs.append(['input_2'] + inputs[0][1:]
) if inputs[0][0] == 'input_1' else None
_inputs = []
n.begin()
for key, _class, is_optional in inputs:
if not _class:
continue
inode = nuke.createNode('Input', inpanel=False)
inode.setName(normalize_nodename(key))
_inputs.append({
'name': key,
'outputs': [_class.lower()],
'opt': is_optional
})
nuke.createNode('Output', inpanel=False)
n.end()
data_knob = nuke.PyScript_Knob('data')
data_knob.setVisible(False)
outputs = []
for output, output_name in zip(data['output'], data['output_name']):
if type(output) == list:
outputs.append(output_name)
else:
outputs.append(output.lower())
data_knob.setValue(json.dumps({
'knobs_order': knobs_order,
'knobs_class': knobs_class,
'class_type': data['name'],
'output_name': data.get('output_name', False),
'output_node': data.get('output_node', False),
'inputs': _inputs,
'outputs': outputs,
}, indent=4).replace('"', "'"))
n.addKnob(data_knob)
if n.knob('User'):
n.knob('User').setName('Controls')
if selected_node:
n.setXYpos(selected_node.xpos(), selected_node.ypos() + 24)
n.setInput(0, selected_node)
for i, onode in get_output_nodes(selected_node):
onode.setInput(i, n)
if 'ShowText' in name:
show_knob = nuke.Multiline_Eval_String_Knob('text', '')
n.addKnob(show_knob)
n.knob('text').setFlag(nuke.READ_ONLY)
n.knob('onCreate').setValue(
'nuke.thisNode().knob("text").setFlag(nuke.READ_ONLY)')
output_text_node = nuke.createNode('StickyNote', inpanel=False)
output_text_node.setName(display_name + 'Output')
output_text_node.setXYpos(n.xpos() - 100, n.ypos())
output_text_node.knob('label').setText(
'[value {}.name]'.format(n.name()))
n.setSelected(True)
return n
def update_menu():
if menu_updated:
return True
return update()
def update():
global menu_updated
progress = nuke.ProgressTask('Updating ComfyUI')
progress.setMessage('Loading data from server...')
progress.setProgress(0)
info = GET('object_info', get_settings())
if not info:
return
menu_updated = True
comfyui_menu = nuke.menu('Nodes').addMenu('ComfyUI')
for item in comfyui_menu.items():
if item.name() in ['Update all ComfyUI', 'Basic Nodes', 'Gizmos', 'Scripts']:
continue
if not hasattr(item, 'clearMenu'):
continue
item.clearMenu()
load_exr_exist = False
nodes = {}
def normalize_string(string):
if not string:
return ''
string = ''.join(char if ord(
char) < 128 else '' for char in string)
return string.replace(' /', '/').replace('/ ', '/').strip()
for _, value in info.items():
name = value['name'].replace('+', '')
if name == 'LoadEXR':
load_exr_exist = True
value['display_name'] = value.get('display_name') or value.get('name')
display_name = normalize_string(value['display_name'])
category = normalize_string(value['category'])
if not category:
category = 'Uncategorized'
value['category'] = category
item_name = '{}/{}'.format(category, display_name)
nodes[item_name] = value
if not load_exr_exist:
show_message('ComfyUI-HQ-Image-Save module is required !')
icon_gray = '{}/icons/comfyui_icon_gray.png'.format(COMFYUI2NUKE)
progress.setMessage('Refreshing menu items...')
for i, (fullname, value) in enumerate(sorted(nodes.items())):
progress.setProgress(int(i * 100 / len(nodes)))
input_data = value.get('input', {})
input_order = value.get('input_order', {})
if not input_order:
value['input_order'] = {
'required': list(input_data.get('required', {})),
'optional': list(input_data.get('optional', {}))
}
value = json.loads(json.dumps(value)) # OrderedDict to Dict
value_utf8 = convert_to_utf8(value)
comfyui_nodes[value['name']] = value_utf8
comfyui_menu.addCommand(fullname, partial(
create_node, value_utf8), '', icon_gray)
del progress
return True
================================================
FILE: src/upload_and_download.py
================================================
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
import os
import nuke # type: ignore
import shutil
import requests
from .common import get_comfyui_dir, get_settings
def upload_images(folder, settings):
task = nuke.ProgressTask('Uploading to ComfyUI')
url = '{}/upload/image'.format(settings['URL'])
results = []
files = os.listdir(folder)
total = len(files)
for i, file in enumerate(files):
image_path = os.path.join(folder, file)
with open(image_path, 'rb') as f:
files = {'image': f}
data = {
'subfolder': os.path.basename(folder),
'overwrite': 'true'
}
resp = requests.post(
url, headers=settings['HTTP_HEADER'], files=files, data=data)
results.append((resp.status_code, resp.text))
task.setMessage('Uploading: ' + file)
task.setProgress(int((i / float(total)) * 100))
task.setProgress(100)
return results
def download_images(separated_filename, dst_folder, frange, settings, run_node):
from .nodes import get_node_data
_, basename, sequence_output = separated_filename
from .nodes import get_input
save_node = get_input(run_node, 0)
class_type = ''
if save_node:
save_node_data = get_node_data(save_node)
class_type = save_node_data['class_type']
ext_map = {
'SaveEXR': 'exr',
'SaveGLB': 'glb',
'SaveImage': 'png'
}
ext = ext_map.get(class_type, None)
if not ext:
return ''
subfolder = os.path.basename(sequence_output)
output = os.path.join(dst_folder, subfolder)
if not os.path.exists(output):
os.makedirs(output)
last_frame = 0
task = nuke.ProgressTask('Downloading from ComfyUI')
task.setMessage('Downloading: ...')
task.setProgress(0)
total = frange[1] - frange[0] + 1
downloaded = 0
for i in range(1, 10000):
image = '{}_{}_.{}'.format(basename, str(i).zfill(5), ext)
url = '{}/api/view?filename={}&subfolder={}'.format(
settings['URL'], image, subfolder)
r = requests.get(url, headers=settings['HTTP_HEADER'], stream=True)
if r.status_code != 200:
last_frame = i - 1
break
if task.isCancelled():
return
dst_path = os.path.join(output, image)
with open(dst_path, 'wb') as f:
for chunk in r.iter_content(8192):
f.write(chunk)
downloaded += 1
task.setMessage('Downloading: ' + image)
task.setProgress(int((i / float(total)) * 100))
task.setProgress(100)
if not downloaded:
return
return '{}/{}_#####_.{} 1-{}'.format(output, basename, ext, last_frame)
def upload_media():
settings = get_settings()
input_dir = os.path.join(get_comfyui_dir(settings), 'input')
filepath = nuke.getFilename(
'Upload Media', "*.jpg *.exr *.png *.mp3 *.wav")
if not filepath:
return
this = nuke.thisNode()
list_knob = this.knob('audio_')
if not list_knob:
list_knob = this.knob('image_')
if not list_knob:
return
shutil.copy(filepath, input_dir)
filename = os.path.basename(filepath)
updated_options = list_knob.values()
if not filename in updated_options:
updated_options.append(filename)
list_knob.setValues(updated_options)
list_knob.setValue(filename)
================================================
FILE: src/workflow_importer.py
================================================
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
import textwrap
import os
import nuke # type: ignore
from ..nuke_util.nuke_util import set_hex_color
from ..python_util.util import jread
from .update_menu import create_comfyui_node, normalize_nodename, update_menu
from .run import error_node_style
from .nodes import get_node_data
from .connection import convert_to_utf8
from .common import show_message
from ..settings import COMFYUI2NUKE
from .scripts.knob2input import convert_knobs
def center_nodes(nodes):
min_x = min(node['xpos'].value() for node in nodes)
min_y = min(node['ypos'].value() for node in nodes)
for node in nodes:
new_x = node['xpos'].value() - min_x
new_y = node['ypos'].value() - min_y
node.setXYpos(int(new_x), int(new_y))
def import_workflow():
workflow_path = nuke.getFilename('Workflow', '*.json')
if not workflow_path:
return
if not os.path.isfile(workflow_path):
show_message("Please select a JSON file, not a folder")
return
data = jread(workflow_path)
[n.setSelected(False) for n in nuke.selectedNodes()]
if not 'nodes' in data:
show_message(
"Incompatible workflow, perhaps exported from 'Export(API)'")
return
if not update_menu():
return
created_nodes = {}
not_installed = []
nodes = []
ignore_nodes = []
for attrs in data['nodes']:
if attrs['type'] in ignore_nodes:
continue
node = create_comfyui_node(attrs['type'], inpanel=False)
knobs_to_inputs = []
knobs_to_inputs_names = []
for input_item in attrs.get('inputs', []):
if 'widget' in input_item and 'name' in input_item['widget']:
name = input_item['widget']['name']
knobs_to_inputs_names.append(name)
knobs_to_inputs.append(
[True, name + '_', name, input_item['type'].lower()])
if node and knobs_to_inputs:
convert_knobs(node, get_node_data(node), knobs_to_inputs)
if attrs['type'] in ['Note', 'MarkdownNote']:
node = nuke.createNode('StickyNote', inpanel=False)
text = str(convert_to_utf8(attrs['widgets_values'][0]))
formatted_note = '\n'.join(textwrap.wrap(text, width=40))
node.knob('label').setValue(formatted_note + '\n\n')
elif attrs['type'] == 'Reroute':
node = nuke.createNode('Dot', inpanel=False)
elif attrs['type'] in ('easy getNode', 'easy setNode'):
node = nuke.createNode('Dot', inpanel=False)
prefix = 'Get' if attrs['type'] == 'easy getNode' else 'Set'
name = prefix + normalize_nodename(attrs['title'])
node.setName(name)
node.knob('label').setValue(normalize_nodename(attrs['title']))
elif not node:
node = nuke.createNode('NoOp', inpanel=False)
node.setName(normalize_nodename(attrs['type']))
error_node_style(node.fullName(), True, 'Node not installed !')
not_installed.append(attrs['type'])
if not node.knob('tile_color').value():
set_hex_color(node, attrs.get('bgcolor'))
created_nodes[attrs['id']] = (node, attrs, knobs_to_inputs_names)
nodes.append(node)
node.setSelected(False)
pos = attrs['pos']
if type(pos) == list:
xpos, ypos = attrs['pos']
else:
xpos = attrs['pos']['0']
ypos = attrs['pos']['1']
node.setXYpos(int(xpos/2), int(ypos/2))
for attrs in data['groups']:
bd = nuke.createNode('BackdropNode', inpanel=False)
bd.setName('GROUP')
text = convert_to_utf8(attrs['title'])
bd.knob('label').setValue(attrs['title'])
bd.knob('bdwidth').setValue(attrs['bounding'][2]/2)
bd.knob('bdheight').setValue(attrs['bounding'][3]/2)
bd.setXYpos(int(attrs['bounding'][0]/2), int(attrs['bounding'][1]/2))
bd.knob('z_order').setValue(0)
bd.knob('note_font_size').setValue(30)
set_hex_color(bd, attrs.get('color'))
nodes.append(bd)
bd.setSelected(False)
if not nodes:
return
center_nodes(nodes)
def find_node_link(link):
if not link:
return
for node, attrs, _ in created_nodes.values():
for odata in attrs.get('outputs', {}):
links = odata['links']
if not links:
continue
if link in links:
return node
for node, attrs, knobs_to_inputs_names in created_nodes.values():
if attrs['type'] in ('Reroute', 'easy setNode'):
knobs_order = []
elif attrs['type'] == 'easy getNode':
knobs_order = []
node_name = node.name().replace('Get', 'Set')
node.setInput(0, nuke.toNode(node_name))
node.knob('hide_input').setValue(True)
else:
node_data = get_node_data(node)
if not node_data:
continue
knobs_order = node_data['knobs_order']
widgets_values = attrs.get('widgets_values')
values = []
if type(widgets_values) == list:
for value in widgets_values:
if value in ['fixed', 'increment', 'decrement', 'randomize']:
if any('seed' in s for s in knobs_order):
randomize_knob = node.knob('randomize')
if randomize_knob:
randomize_knob.setValue(not value == 'fixed')
continue
values.append(value)
else:
for key in knobs_order:
values.append(widgets_values[key[:-1]])
if not len(values) == len(knobs_order):
values = [v for v in values if v is not None]
for i, value in enumerate(values):
if i >= len(knobs_order):
continue
value = convert_to_utf8(value)
knob = node.knob(knobs_order[i])
if not knob:
continue
if type(value) == int:
value = value if value < 1e9 else 1e9
knob.setValue(int(value))
else:
try:
knob.setValue(value)
except:
show_message('Could not set the knob "{}" value for this node "{}" !'.format(
knob.name(), node.name()))
for i, idata in enumerate(attrs.get('inputs', {})):
link = idata['link']
if idata['name'] + '_' in knobs_order and not idata['name'] in knobs_to_inputs_names:
continue
onode = find_node_link(link)
node.setInput(i, onode)
if 'Save' in attrs['type']:
run_nk = os.path.join(COMFYUI2NUKE, 'nodes/ComfyUI/Run.nk')
run_node = nuke.nodePaste(run_nk)
run_node.setInput(0, node)
run_node.setSelected(False)
run_node.setXYpos(node.xpos(), node.ypos() + 25)
nodes.append(run_node)
[n.setSelected(True) for n in nodes]
if not_installed:
nodes_list = '\n'.join(not_installed)
show_message(
'You need to install these nodes in ComfyUI:\n\n' + nodes_list)
================================================
FILE: testing/__init__.py
================================================
from . import (
testing
)
================================================
FILE: testing/testing.py
================================================
# -----------------------------------------------------------
# AUTHOR --------> Francisco Contreras
# OFFICE --------> Senior VFX Compositor, Software Developer
# WEBSITE -------> https://vinavfx.com
# -----------------------------------------------------------
import nuke # type: ignore
import re
from ..python_util.util import fwrite
import os
def create_all_comfyui_nodes():
def get_menu_items(menu, items=None):
if items is None:
items = []
for item in menu.items():
if isinstance(item, nuke.Menu):
get_menu_items(item, items)
else:
items.append(item)
return items
menu = nuke.menu('Nodes').menu('ComfyUI')
all_items = get_menu_items(menu)
for item in all_items:
if 'Update all' in item.name():
continue
item.invoke()
def status_diff(a, b):
if not a or not b:
return
tokens_a = re.findall(r'\S+', a)
tokens_b = re.findall(r'\S+', b)
diffs = [(x, y) for x, y in zip(tokens_a, tokens_b) if x != y]
diff = ''
for x, y in diffs:
diff += '{} -> {}\n'.format(x, y)
info = 'diff:\n{}\n\nPREVIOUS:\n{}\n\nCURRENT:\n{}'.format(diff, a, b)
file = '/tmp/comfyu2nuke_diff.txt'
fwrite(file, info)
if nuke.ask('diff -> {}, open?'.format(file)):
os.system('pluma {}'.format(file))
gitextract_23hxchp3/
├── .gitignore
├── .gitmodules
├── LICENSE
├── README.md
├── __init__.py
├── examples/
│ ├── cmd.nk
│ └── cmd.py
├── nodes/
│ └── ComfyUI/
│ ├── ComfyUIGizmo.nk
│ ├── MultipleOf.nk
│ ├── OverrideSettings.nk
│ ├── Run.nk
│ └── SwitchAny.nk
├── requirements.txt
├── settings.py
├── src/
│ ├── __init__.py
│ ├── cmd.py
│ ├── common.py
│ ├── connection.py
│ ├── execute_runs.py
│ ├── nodes.py
│ ├── queue_manager.py
│ ├── read_media.py
│ ├── run.py
│ ├── scripts/
│ │ ├── __init__.py
│ │ ├── export_workflow.py
│ │ ├── force_output_connection.py
│ │ └── knob2input.py
│ ├── update_menu.py
│ ├── upload_and_download.py
│ └── workflow_importer.py
└── testing/
├── __init__.py
└── testing.py
SYMBOL INDEX (71 symbols across 16 files)
FILE: __init__.py
function setup (line 14) | def setup():
FILE: src/cmd.py
function get_read (line 11) | def get_read(group=None):
function inference_end (line 23) | def inference_end(_, run_node):
function run (line 29) | def run():
FILE: src/common.py
function show_message (line 22) | def show_message(msg):
function update_images_and_mask_inputs (line 29) | def update_images_and_mask_inputs(settings):
function get_date_code (line 59) | def get_date_code():
function get_name_code (line 65) | def get_name_code(name, length=15):
function get_settings (line 72) | def get_settings(run_node=None):
function get_server_comfyui_dir (line 120) | def get_server_comfyui_dir(settings):
function get_comfyui_dir (line 130) | def get_comfyui_dir(settings):
FILE: src/connection.py
function GET (line 21) | def GET(endpoint, settings, warning=True, timeout=30):
function POST (line 39) | def POST(endpoint, data, settings):
function convert_to_utf8 (line 83) | def convert_to_utf8(data):
FILE: src/execute_runs.py
function multi_runs (line 13) | def multi_runs(runs, success_callback=None, force_queue=None):
function multi_versions (line 44) | def multi_versions(run, versions, success_callback=None):
function execute_runs (line 53) | def execute_runs():
FILE: src/nodes.py
function extract_data (line 23) | def extract_data(run_node, settings):
function create_load_images_and_save (line 94) | def create_load_images_and_save(node, tonemap, settings):
function get_connected_comfyui_nodes (line 245) | def get_connected_comfyui_nodes(root_node, visited=None, ignore_nodes=[]):
function get_node_data (line 291) | def get_node_data(node):
function save_node_data (line 306) | def save_node_data(node, data):
function extract_node_data (line 310) | def extract_node_data(node):
function get_output_index (line 369) | def get_output_index(node, node_data, input_index):
function check_node (line 389) | def check_node(node):
function requires_force_output (line 442) | def requires_force_output(outputs, input_class):
function update_input_nodes (line 459) | def update_input_nodes(node):
function is_switch_any (line 474) | def is_switch_any(node):
function get_input (line 484) | def get_input(node, i, ignore_disabled=True):
FILE: src/queue_manager.py
function resolve_submission_target (line 13) | def resolve_submission_target(settings, force_queue=None):
function interrupt (line 134) | def interrupt(settings, client_id):
FILE: src/read_media.py
function exr_filepath_fixed (line 18) | def exr_filepath_fixed(run_node):
function get_tonemap (line 34) | def get_tonemap(run_node):
function update_filename_prefix (line 47) | def update_filename_prefix(run_node, update=True, data={}):
function set_correct_colorspace (line 71) | def set_correct_colorspace(read):
function get_gizmo_group (line 81) | def get_gizmo_group(run_node):
function extract_meta (line 93) | def extract_meta(data):
function glb2obj (line 192) | def glb2obj(filename):
function get_frame_range (line 206) | def get_frame_range(data):
function get_output_path (line 215) | def get_output_path(settings, default_output=False):
function relocate_filename (line 236) | def relocate_filename(filename, settings):
function get_separate_filename (line 273) | def get_separate_filename(settings, default_output=False):
function get_local_filename (line 289) | def get_local_filename(settings, default_output=False):
function resolve_filename (line 307) | def resolve_filename(run_node, data, settings, already_generated=False):
function create_read (line 327) | def create_read(run_node, data, settings, filename, already_exists=False):
function backup_previous_generation (line 388) | def backup_previous_generation(run_node=None):
FILE: src/run.py
function error_node_style (line 29) | def error_node_style(node_name, enable, message=''):
function remove_all_error_style (line 44) | def remove_all_error_style(root_node):
function update_node (line 51) | def update_node(node_name, data, run_node, settings):
function show_text_uptate (line 59) | def show_text_uptate(node_name, data, run_node):
function preview_image_update (line 94) | def preview_image_update(node_name, data, settings):
function execute_in_main_thread (line 125) | def execute_in_main_thread(func, args=(), kwargs=None):
function submit (line 135) | def submit(run_node=None, success_callback=None, force_queue=None):
FILE: src/scripts/export_workflow.py
function export_workflow (line 14) | def export_workflow():
FILE: src/scripts/force_output_connection.py
function force_output (line 12) | def force_output(node=None):
FILE: src/scripts/knob2input.py
function knob_to_input (line 11) | def knob_to_input():
function convert_knobs (line 45) | def convert_knobs(node, data, knobs):
FILE: src/update_menu.py
function normalize_nodename (line 21) | def normalize_nodename(name):
function get_nodes (line 32) | def get_nodes():
function create_comfyui_node (line 39) | def create_comfyui_node(node_type, inpanel=True):
function refresh_models (line 47) | def refresh_models(node, knob_name, class_type):
function create_node (line 61) | def create_node(data, inpanel=True):
function update_menu (line 277) | def update_menu():
function update (line 284) | def update():
FILE: src/upload_and_download.py
function upload_images (line 14) | def upload_images(folder, settings):
function download_images (line 44) | def download_images(separated_filename, dst_folder, frange, settings, ru...
function upload_media (line 111) | def upload_media():
FILE: src/workflow_importer.py
function center_nodes (line 20) | def center_nodes(nodes):
function import_workflow (line 30) | def import_workflow():
FILE: testing/testing.py
function create_all_comfyui_nodes (line 12) | def create_all_comfyui_nodes():
function status_diff (line 35) | def status_diff(a, b):
Condensed preview — 32 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (139K chars).
[
{
"path": ".gitignore",
"chars": 106,
"preview": "session.vim\n.undodir/\n*.py[cod]\n**/*.swp\nnodes/Gizmos\n__pycache__\n_*/\n*.code-workspace\n.vscode\ntasks.todo\n"
},
{
"path": ".gitmodules",
"chars": 178,
"preview": "[submodule \"nuke_util\"]\n\tpath = nuke_util\n\turl = https://github.com/vinavfx/nuke_util\n[submodule \"python_util\"]\n\tpath = "
},
{
"path": "LICENSE",
"chars": 35149,
"preview": " GNU GENERAL PUBLIC LICENSE\n Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
},
{
"path": "README.md",
"chars": 3713,
"preview": "# ComfyUI for Nuke\nAPI to be able to use ComfyUI nodes within nuke, only using the ComfyUI server\n\n<div style=\"display: "
},
{
"path": "__init__.py",
"chars": 2567,
"preview": "# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contreras\n# OFFICE --------> "
},
{
"path": "examples/cmd.nk",
"chars": 1643,
"preview": "Root {\n inputs 0\n name cmd.nk\n format \"2048 1556 0 0 2048 1556 1 2K_Super_35(full-ap)\"\n proxy_type scale\n proxy_format \""
},
{
"path": "examples/cmd.py",
"chars": 207,
"preview": "# /usr/local/Nuke12.0v8 -t ./cmd.py\nimport nuke\n\nnuke.scriptOpen('./cmd.nk')\nrun = nuke.toNode('Run')\nrun.knob('run').ex"
},
{
"path": "nodes/ComfyUI/ComfyUIGizmo.nk",
"chars": 1767,
"preview": "set cut_paste_input [stack 0]\nversion 12.0 v8\npush $cut_paste_input\nGroup {\n name ComfyUIGizmo\n tile_color 0xa2b275ff\n s"
},
{
"path": "nodes/ComfyUI/MultipleOf.nk",
"chars": 1247,
"preview": "set cut_paste_input [stack 0]\nversion 12.0 v8\npush $cut_paste_input\nGroup {\n name MultipleOf\n tile_color 0xa57aaaff\n sel"
},
{
"path": "nodes/ComfyUI/OverrideSettings.nk",
"chars": 2797,
"preview": "set cut_paste_input [stack 0]\nversion 12.0 v8\npush $cut_paste_input\nGroup {\n name OverrideSettings\n onCreate \"this = nuk"
},
{
"path": "nodes/ComfyUI/Run.nk",
"chars": 430,
"preview": "set cut_paste_input [stack 0]\nversion 12.0 v8\npush $cut_paste_input\nGroup {\n name Run\n tile_color 0x609e38ff\n note_font "
},
{
"path": "nodes/ComfyUI/SwitchAny.nk",
"chars": 217,
"preview": "set cut_paste_input [stack 0]\nversion 12.0 v8\npush $cut_paste_input\nSwitch {\n name SwitchAny\n tile_color 0x7f7f7fff\n sel"
},
{
"path": "requirements.txt",
"chars": 34,
"preview": "websocket-client\nrequests\ntrimesh\n"
},
{
"path": "settings.py",
"chars": 581,
"preview": "import os\n\n# ENVIRONMENT VARIABLES\nCOMFYUI_DIR = os.getenv('NUKE_COMFYUI_DIR', '')\nURL = "
},
{
"path": "src/__init__.py",
"chars": 205,
"preview": "from . import (\n common,\n connection,\n nodes,\n run,\n update_menu,\n read_media,\n upload_and_download"
},
{
"path": "src/cmd.py",
"chars": 769,
"preview": "# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contreras\n# OFFICE --------> "
},
{
"path": "src/common.py",
"chars": 4063,
"preview": "# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contreras\n# OFFICE --------> "
},
{
"path": "src/connection.py",
"chars": 2983,
"preview": "# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contreras\n# OFFICE --------> "
},
{
"path": "src/execute_runs.py",
"chars": 1918,
"preview": "# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contreras\n# OFFICE --------> "
},
{
"path": "src/nodes.py",
"chars": 15214,
"preview": "# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contreras\n# OFFICE --------> "
},
{
"path": "src/queue_manager.py",
"chars": 4902,
"preview": "# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contreras\n# OFFICE --------> "
},
{
"path": "src/read_media.py",
"chars": 12075,
"preview": "# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contreras\n# OFFICE --------> "
},
{
"path": "src/run.py",
"chars": 10111,
"preview": "# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contreras\n# OFFICE --------> "
},
{
"path": "src/scripts/__init__.py",
"chars": 83,
"preview": "from . import (\n knob2input,\n force_output_connection,\n export_workflow\n)\n"
},
{
"path": "src/scripts/export_workflow.py",
"chars": 1267,
"preview": "# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contreras\n# OFFICE --------> "
},
{
"path": "src/scripts/force_output_connection.py",
"chars": 2827,
"preview": "# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contreras\n# OFFICE --------> "
},
{
"path": "src/scripts/knob2input.py",
"chars": 2456,
"preview": "# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contreras\n# OFFICE --------> "
},
{
"path": "src/update_menu.py",
"chars": 10787,
"preview": "# -*- coding: utf-8 -*-\n# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contr"
},
{
"path": "src/upload_and_download.py",
"chars": 3677,
"preview": "# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contreras\n# OFFICE --------> "
},
{
"path": "src/workflow_importer.py",
"chars": 7600,
"preview": "# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contreras\n# OFFICE --------> "
},
{
"path": "testing/__init__.py",
"chars": 30,
"preview": "from . import (\n testing\n)\n"
},
{
"path": "testing/testing.py",
"chars": 1386,
"preview": "# -----------------------------------------------------------\n# AUTHOR --------> Francisco Contreras\n# OFFICE --------> "
}
]
About this extraction
This page contains the full source code of the vinavfx/ComfyUI-for-Nuke GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 32 files (129.9 KB), approximately 31.6k tokens, and a symbol index with 71 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.