Spaces:
Runtime error
Runtime error
Upload 19 files
Browse files- ComfyUI/.pylintrc +3 -0
- ComfyUI/CODEOWNERS +1 -0
- ComfyUI/CONTRIBUTING.md +41 -0
- ComfyUI/LICENSE +674 -0
- ComfyUI/README.md +237 -0
- ComfyUI/comfyui_screenshot.png +0 -0
- ComfyUI/cuda_malloc.py +90 -0
- ComfyUI/execution.py +864 -0
- ComfyUI/extra_model_paths.yaml.example +42 -0
- ComfyUI/fix_torch.py +24 -0
- ComfyUI/folder_paths.py +270 -0
- ComfyUI/latent_preview.py +94 -0
- ComfyUI/main.py +268 -0
- ComfyUI/new_updater.py +35 -0
- ComfyUI/node_helpers.py +37 -0
- ComfyUI/nodes.py +2068 -0
- ComfyUI/pytest.ini +8 -0
- ComfyUI/requirements.txt +20 -0
- ComfyUI/server.py +696 -0
ComfyUI/.pylintrc
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
[MESSAGES CONTROL]
|
2 |
+
disable=all
|
3 |
+
enable=eval-used
|
ComfyUI/CODEOWNERS
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
* @comfyanonymous
|
ComfyUI/CONTRIBUTING.md
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Contributing to ComfyUI
|
2 |
+
|
3 |
+
Welcome, and thank you for your interest in contributing to ComfyUI!
|
4 |
+
|
5 |
+
There are several ways in which you can contribute, beyond writing code. The goal of this document is to provide a high-level overview of how you can get involved.
|
6 |
+
|
7 |
+
## Asking Questions
|
8 |
+
|
9 |
+
Have a question? Instead of opening an issue, please ask on [Discord](https://comfy.org/discord) or [Matrix](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) channels. Our team and the community will help you.
|
10 |
+
|
11 |
+
## Providing Feedback
|
12 |
+
|
13 |
+
Your comments and feedback are welcome, and the development team is available via a handful of different channels.
|
14 |
+
|
15 |
+
See the `#bug-report`, `#feature-request` and `#feedback` channels on Discord.
|
16 |
+
|
17 |
+
## Reporting Issues
|
18 |
+
|
19 |
+
Have you identified a reproducible problem in ComfyUI? Do you have a feature request? We want to hear about it! Here's how you can report your issue as effectively as possible.
|
20 |
+
|
21 |
+
|
22 |
+
### Look For an Existing Issue
|
23 |
+
|
24 |
+
Before you create a new issue, please do a search in [open issues](https://github.com/comfyanonymous/ComfyUI/issues) to see if the issue or feature request has already been filed.
|
25 |
+
|
26 |
+
If you find your issue already exists, make relevant comments and add your [reaction](https://github.com/blog/2119-add-reactions-to-pull-requests-issues-and-comments). Use a reaction in place of a "+1" comment:
|
27 |
+
|
28 |
+
* 👍 - upvote
|
29 |
+
* 👎 - downvote
|
30 |
+
|
31 |
+
If you cannot find an existing issue that describes your bug or feature, create a new issue. We have an issue template in place to organize new issues.
|
32 |
+
|
33 |
+
|
34 |
+
### Creating Pull Requests
|
35 |
+
|
36 |
+
* Please refer to the article on [creating pull requests](https://github.com/comfyanonymous/ComfyUI/wiki/How-to-Contribute-Code) and contributing to this project.
|
37 |
+
|
38 |
+
|
39 |
+
## Thank You
|
40 |
+
|
41 |
+
Your contributions to open source, large or small, make great projects like this possible. Thank you for taking the time to contribute.
|
ComfyUI/LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<https://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.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The most powerful and modular stable diffusion GUI and backend.
|
4 |
+
-----------
|
5 |
+
![ComfyUI Screenshot](comfyui_screenshot.png)
|
6 |
+
|
7 |
+
This ui will let you design and execute advanced stable diffusion pipelines using a graph/nodes/flowchart based interface. For some workflow examples and see what ComfyUI can do you can check out:
|
8 |
+
### [ComfyUI Examples](https://comfyanonymous.github.io/ComfyUI_examples/)
|
9 |
+
|
10 |
+
### [Installing ComfyUI](#installing)
|
11 |
+
|
12 |
+
## Features
|
13 |
+
- Nodes/graph/flowchart interface to experiment and create complex Stable Diffusion workflows without needing to code anything.
|
14 |
+
- Fully supports SD1.x, SD2.x, [SDXL](https://comfyanonymous.github.io/ComfyUI_examples/sdxl/), [Stable Video Diffusion](https://comfyanonymous.github.io/ComfyUI_examples/video/), [Stable Cascade](https://comfyanonymous.github.io/ComfyUI_examples/stable_cascade/), [SD3](https://comfyanonymous.github.io/ComfyUI_examples/sd3/) and [Stable Audio](https://comfyanonymous.github.io/ComfyUI_examples/audio/)
|
15 |
+
- Asynchronous Queue system
|
16 |
+
- Many optimizations: Only re-executes the parts of the workflow that changes between executions.
|
17 |
+
- Smart memory management: can automatically run models on GPUs with as low as 1GB vram.
|
18 |
+
- Works even if you don't have a GPU with: ```--cpu``` (slow)
|
19 |
+
- Can load ckpt, safetensors and diffusers models/checkpoints. Standalone VAEs and CLIP models.
|
20 |
+
- Embeddings/Textual inversion
|
21 |
+
- [Loras (regular, locon and loha)](https://comfyanonymous.github.io/ComfyUI_examples/lora/)
|
22 |
+
- [Hypernetworks](https://comfyanonymous.github.io/ComfyUI_examples/hypernetworks/)
|
23 |
+
- Loading full workflows (with seeds) from generated PNG, WebP and FLAC files.
|
24 |
+
- Saving/Loading workflows as Json files.
|
25 |
+
- Nodes interface can be used to create complex workflows like one for [Hires fix](https://comfyanonymous.github.io/ComfyUI_examples/2_pass_txt2img/) or much more advanced ones.
|
26 |
+
- [Area Composition](https://comfyanonymous.github.io/ComfyUI_examples/area_composition/)
|
27 |
+
- [Inpainting](https://comfyanonymous.github.io/ComfyUI_examples/inpaint/) with both regular and inpainting models.
|
28 |
+
- [ControlNet and T2I-Adapter](https://comfyanonymous.github.io/ComfyUI_examples/controlnet/)
|
29 |
+
- [Upscale Models (ESRGAN, ESRGAN variants, SwinIR, Swin2SR, etc...)](https://comfyanonymous.github.io/ComfyUI_examples/upscale_models/)
|
30 |
+
- [unCLIP Models](https://comfyanonymous.github.io/ComfyUI_examples/unclip/)
|
31 |
+
- [GLIGEN](https://comfyanonymous.github.io/ComfyUI_examples/gligen/)
|
32 |
+
- [Model Merging](https://comfyanonymous.github.io/ComfyUI_examples/model_merging/)
|
33 |
+
- [LCM models and Loras](https://comfyanonymous.github.io/ComfyUI_examples/lcm/)
|
34 |
+
- [SDXL Turbo](https://comfyanonymous.github.io/ComfyUI_examples/sdturbo/)
|
35 |
+
- [AuraFlow](https://comfyanonymous.github.io/ComfyUI_examples/aura_flow/)
|
36 |
+
- [HunyuanDiT](https://comfyanonymous.github.io/ComfyUI_examples/hunyuan_dit/)
|
37 |
+
- Latent previews with [TAESD](#how-to-show-high-quality-previews)
|
38 |
+
- Starts up very fast.
|
39 |
+
- Works fully offline: will never download anything.
|
40 |
+
- [Config file](extra_model_paths.yaml.example) to set the search paths for models.
|
41 |
+
|
42 |
+
Workflow examples can be found on the [Examples page](https://comfyanonymous.github.io/ComfyUI_examples/)
|
43 |
+
|
44 |
+
## Shortcuts
|
45 |
+
|
46 |
+
| Keybind | Explanation |
|
47 |
+
|------------------------------------|--------------------------------------------------------------------------------------------------------------------|
|
48 |
+
| Ctrl + Enter | Queue up current graph for generation |
|
49 |
+
| Ctrl + Shift + Enter | Queue up current graph as first for generation |
|
50 |
+
| Ctrl + Z/Ctrl + Y | Undo/Redo |
|
51 |
+
| Ctrl + S | Save workflow |
|
52 |
+
| Ctrl + O | Load workflow |
|
53 |
+
| Ctrl + A | Select all nodes |
|
54 |
+
| Alt + C | Collapse/uncollapse selected nodes |
|
55 |
+
| Ctrl + M | Mute/unmute selected nodes |
|
56 |
+
| Ctrl + B | Bypass selected nodes (acts like the node was removed from the graph and the wires reconnected through) |
|
57 |
+
| Delete/Backspace | Delete selected nodes |
|
58 |
+
| Ctrl + Backspace | Delete the current graph |
|
59 |
+
| Space | Move the canvas around when held and moving the cursor |
|
60 |
+
| Ctrl/Shift + Click | Add clicked node to selection |
|
61 |
+
| Ctrl + C/Ctrl + V | Copy and paste selected nodes (without maintaining connections to outputs of unselected nodes) |
|
62 |
+
| Ctrl + C/Ctrl + Shift + V | Copy and paste selected nodes (maintaining connections from outputs of unselected nodes to inputs of pasted nodes) |
|
63 |
+
| Shift + Drag | Move multiple selected nodes at the same time |
|
64 |
+
| Ctrl + D | Load default graph |
|
65 |
+
| Alt + `+` | Canvas Zoom in |
|
66 |
+
| Alt + `-` | Canvas Zoom out |
|
67 |
+
| Ctrl + Shift + LMB + Vertical drag | Canvas Zoom in/out |
|
68 |
+
| Q | Toggle visibility of the queue |
|
69 |
+
| H | Toggle visibility of history |
|
70 |
+
| R | Refresh graph |
|
71 |
+
| Double-Click LMB | Open node quick search palette |
|
72 |
+
|
73 |
+
Ctrl can also be replaced with Cmd instead for macOS users
|
74 |
+
|
75 |
+
# Installing
|
76 |
+
|
77 |
+
## Windows
|
78 |
+
|
79 |
+
There is a portable standalone build for Windows that should work for running on Nvidia GPUs or for running on your CPU only on the [releases page](https://github.com/comfyanonymous/ComfyUI/releases).
|
80 |
+
|
81 |
+
### [Direct link to download](https://github.com/comfyanonymous/ComfyUI/releases/latest/download/ComfyUI_windows_portable_nvidia.7z)
|
82 |
+
|
83 |
+
Simply download, extract with [7-Zip](https://7-zip.org) and run. Make sure you put your Stable Diffusion checkpoints/models (the huge ckpt/safetensors files) in: ComfyUI\models\checkpoints
|
84 |
+
|
85 |
+
If you have trouble extracting it, right click the file -> properties -> unblock
|
86 |
+
|
87 |
+
#### How do I share models between another UI and ComfyUI?
|
88 |
+
|
89 |
+
See the [Config file](extra_model_paths.yaml.example) to set the search paths for models. In the standalone windows build you can find this file in the ComfyUI directory. Rename this file to extra_model_paths.yaml and edit it with your favorite text editor.
|
90 |
+
|
91 |
+
## Jupyter Notebook
|
92 |
+
|
93 |
+
To run it on services like paperspace, kaggle or colab you can use my [Jupyter Notebook](notebooks/comfyui_colab.ipynb)
|
94 |
+
|
95 |
+
## Manual Install (Windows, Linux)
|
96 |
+
|
97 |
+
Git clone this repo.
|
98 |
+
|
99 |
+
Put your SD checkpoints (the huge ckpt/safetensors files) in: models/checkpoints
|
100 |
+
|
101 |
+
Put your VAE in: models/vae
|
102 |
+
|
103 |
+
|
104 |
+
### AMD GPUs (Linux only)
|
105 |
+
AMD users can install rocm and pytorch with pip if you don't have it already installed, this is the command to install the stable version:
|
106 |
+
|
107 |
+
```pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm6.0```
|
108 |
+
|
109 |
+
This is the command to install the nightly with ROCm 6.0 which might have some performance improvements:
|
110 |
+
|
111 |
+
```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.1```
|
112 |
+
|
113 |
+
### NVIDIA
|
114 |
+
|
115 |
+
Nvidia users should install stable pytorch using this command:
|
116 |
+
|
117 |
+
```pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu121```
|
118 |
+
|
119 |
+
This is the command to install pytorch nightly instead which might have performance improvements:
|
120 |
+
|
121 |
+
```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cu124```
|
122 |
+
|
123 |
+
#### Troubleshooting
|
124 |
+
|
125 |
+
If you get the "Torch not compiled with CUDA enabled" error, uninstall torch with:
|
126 |
+
|
127 |
+
```pip uninstall torch```
|
128 |
+
|
129 |
+
And install it again with the command above.
|
130 |
+
|
131 |
+
### Dependencies
|
132 |
+
|
133 |
+
Install the dependencies by opening your terminal inside the ComfyUI folder and:
|
134 |
+
|
135 |
+
```pip install -r requirements.txt```
|
136 |
+
|
137 |
+
After this you should have everything installed and can proceed to running ComfyUI.
|
138 |
+
|
139 |
+
### Others:
|
140 |
+
|
141 |
+
#### Intel GPUs
|
142 |
+
|
143 |
+
Intel GPU support is available for all Intel GPUs supported by Intel's Extension for Pytorch (IPEX) with the support requirements listed in the [Installation](https://intel.github.io/intel-extension-for-pytorch/index.html#installation?platform=gpu) page. Choose your platform and method of install and follow the instructions. The steps are as follows:
|
144 |
+
|
145 |
+
1. Start by installing the drivers or kernel listed or newer in the Installation page of IPEX linked above for Windows and Linux if needed.
|
146 |
+
1. Follow the instructions to install [Intel's oneAPI Basekit](https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit-download.html) for your platform.
|
147 |
+
1. Install the packages for IPEX using the instructions provided in the Installation page for your platform.
|
148 |
+
1. Follow the [ComfyUI manual installation](#manual-install-windows-linux) instructions for Windows and Linux and run ComfyUI normally as described above after everything is installed.
|
149 |
+
|
150 |
+
Additional discussion and help can be found [here](https://github.com/comfyanonymous/ComfyUI/discussions/476).
|
151 |
+
|
152 |
+
#### Apple Mac silicon
|
153 |
+
|
154 |
+
You can install ComfyUI in Apple Mac silicon (M1 or M2) with any recent macOS version.
|
155 |
+
|
156 |
+
1. Install pytorch nightly. For instructions, read the [Accelerated PyTorch training on Mac](https://developer.apple.com/metal/pytorch/) Apple Developer guide (make sure to install the latest pytorch nightly).
|
157 |
+
1. Follow the [ComfyUI manual installation](#manual-install-windows-linux) instructions for Windows and Linux.
|
158 |
+
1. Install the ComfyUI [dependencies](#dependencies). If you have another Stable Diffusion UI [you might be able to reuse the dependencies](#i-already-have-another-ui-for-stable-diffusion-installed-do-i-really-have-to-install-all-of-these-dependencies).
|
159 |
+
1. Launch ComfyUI by running `python main.py`
|
160 |
+
|
161 |
+
> **Note**: Remember to add your models, VAE, LoRAs etc. to the corresponding Comfy folders, as discussed in [ComfyUI manual installation](#manual-install-windows-linux).
|
162 |
+
|
163 |
+
#### DirectML (AMD Cards on Windows)
|
164 |
+
|
165 |
+
```pip install torch-directml``` Then you can launch ComfyUI with: ```python main.py --directml```
|
166 |
+
|
167 |
+
### I already have another UI for Stable Diffusion installed do I really have to install all of these dependencies?
|
168 |
+
|
169 |
+
You don't. If you have another UI installed and working with its own python venv you can use that venv to run ComfyUI. You can open up your favorite terminal and activate it:
|
170 |
+
|
171 |
+
```source path_to_other_sd_gui/venv/bin/activate```
|
172 |
+
|
173 |
+
or on Windows:
|
174 |
+
|
175 |
+
With Powershell: ```"path_to_other_sd_gui\venv\Scripts\Activate.ps1"```
|
176 |
+
|
177 |
+
With cmd.exe: ```"path_to_other_sd_gui\venv\Scripts\activate.bat"```
|
178 |
+
|
179 |
+
And then you can use that terminal to run ComfyUI without installing any dependencies. Note that the venv folder might be called something else depending on the SD UI.
|
180 |
+
|
181 |
+
# Running
|
182 |
+
|
183 |
+
```python main.py```
|
184 |
+
|
185 |
+
### For AMD cards not officially supported by ROCm
|
186 |
+
|
187 |
+
Try running it with this command if you have issues:
|
188 |
+
|
189 |
+
For 6700, 6600 and maybe other RDNA2 or older: ```HSA_OVERRIDE_GFX_VERSION=10.3.0 python main.py```
|
190 |
+
|
191 |
+
For AMD 7600 and maybe other RDNA3 cards: ```HSA_OVERRIDE_GFX_VERSION=11.0.0 python main.py```
|
192 |
+
|
193 |
+
# Notes
|
194 |
+
|
195 |
+
Only parts of the graph that have an output with all the correct inputs will be executed.
|
196 |
+
|
197 |
+
Only parts of the graph that change from each execution to the next will be executed, if you submit the same graph twice only the first will be executed. If you change the last part of the graph only the part you changed and the part that depends on it will be executed.
|
198 |
+
|
199 |
+
Dragging a generated png on the webpage or loading one will give you the full workflow including seeds that were used to create it.
|
200 |
+
|
201 |
+
You can use () to change emphasis of a word or phrase like: (good code:1.2) or (bad code:0.8). The default emphasis for () is 1.1. To use () characters in your actual prompt escape them like \\( or \\).
|
202 |
+
|
203 |
+
You can use {day|night}, for wildcard/dynamic prompts. With this syntax "{wild|card|test}" will be randomly replaced by either "wild", "card" or "test" by the frontend every time you queue the prompt. To use {} characters in your actual prompt escape them like: \\{ or \\}.
|
204 |
+
|
205 |
+
Dynamic prompts also support C-style comments, like `// comment` or `/* comment */`.
|
206 |
+
|
207 |
+
To use a textual inversion concepts/embeddings in a text prompt put them in the models/embeddings directory and use them in the CLIPTextEncode node like this (you can omit the .pt extension):
|
208 |
+
|
209 |
+
```embedding:embedding_filename.pt```
|
210 |
+
|
211 |
+
|
212 |
+
## How to show high-quality previews?
|
213 |
+
|
214 |
+
Use ```--preview-method auto``` to enable previews.
|
215 |
+
|
216 |
+
The default installation includes a fast latent preview method that's low-resolution. To enable higher-quality previews with [TAESD](https://github.com/madebyollin/taesd), download the [taesd_decoder.pth](https://github.com/madebyollin/taesd/raw/main/taesd_decoder.pth) (for SD1.x and SD2.x) and [taesdxl_decoder.pth](https://github.com/madebyollin/taesd/raw/main/taesdxl_decoder.pth) (for SDXL) models and place them in the `models/vae_approx` folder. Once they're installed, restart ComfyUI to enable high-quality previews.
|
217 |
+
|
218 |
+
## How to use TLS/SSL?
|
219 |
+
Generate a self-signed certificate (not appropriate for shared/production use) and key by running the command: `openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -sha256 -days 3650 -nodes -subj "/C=XX/ST=StateName/L=CityName/O=CompanyName/OU=CompanySectionName/CN=CommonNameOrHostname"`
|
220 |
+
|
221 |
+
Use `--tls-keyfile key.pem --tls-certfile cert.pem` to enable TLS/SSL, the app will now be accessible with `https://...` instead of `http://...`.
|
222 |
+
|
223 |
+
> Note: Windows users can use [alexisrolland/docker-openssl](https://github.com/alexisrolland/docker-openssl) or one of the [3rd party binary distributions](https://wiki.openssl.org/index.php/Binaries) to run the command example above.
|
224 |
+
<br/><br/>If you use a container, note that the volume mount `-v` can be a relative path so `... -v ".\:/openssl-certs" ...` would create the key & cert files in the current directory of your command prompt or powershell terminal.
|
225 |
+
|
226 |
+
## Support and dev channel
|
227 |
+
|
228 |
+
[Matrix space: #comfyui_space:matrix.org](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) (it's like discord but open source).
|
229 |
+
|
230 |
+
See also: [https://www.comfy.org/](https://www.comfy.org/)
|
231 |
+
|
232 |
+
# QA
|
233 |
+
|
234 |
+
### Which GPU should I buy for this?
|
235 |
+
|
236 |
+
[See this page for some recommendations](https://github.com/comfyanonymous/ComfyUI/wiki/Which-GPU-should-I-buy-for-ComfyUI)
|
237 |
+
|
ComfyUI/comfyui_screenshot.png
ADDED
ComfyUI/cuda_malloc.py
ADDED
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import importlib.util
|
3 |
+
from comfy.cli_args import args
|
4 |
+
import subprocess
|
5 |
+
|
6 |
+
#Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import.
|
7 |
+
def get_gpu_names():
|
8 |
+
if os.name == 'nt':
|
9 |
+
import ctypes
|
10 |
+
|
11 |
+
# Define necessary C structures and types
|
12 |
+
class DISPLAY_DEVICEA(ctypes.Structure):
|
13 |
+
_fields_ = [
|
14 |
+
('cb', ctypes.c_ulong),
|
15 |
+
('DeviceName', ctypes.c_char * 32),
|
16 |
+
('DeviceString', ctypes.c_char * 128),
|
17 |
+
('StateFlags', ctypes.c_ulong),
|
18 |
+
('DeviceID', ctypes.c_char * 128),
|
19 |
+
('DeviceKey', ctypes.c_char * 128)
|
20 |
+
]
|
21 |
+
|
22 |
+
# Load user32.dll
|
23 |
+
user32 = ctypes.windll.user32
|
24 |
+
|
25 |
+
# Call EnumDisplayDevicesA
|
26 |
+
def enum_display_devices():
|
27 |
+
device_info = DISPLAY_DEVICEA()
|
28 |
+
device_info.cb = ctypes.sizeof(device_info)
|
29 |
+
device_index = 0
|
30 |
+
gpu_names = set()
|
31 |
+
|
32 |
+
while user32.EnumDisplayDevicesA(None, device_index, ctypes.byref(device_info), 0):
|
33 |
+
device_index += 1
|
34 |
+
gpu_names.add(device_info.DeviceString.decode('utf-8'))
|
35 |
+
return gpu_names
|
36 |
+
return enum_display_devices()
|
37 |
+
else:
|
38 |
+
gpu_names = set()
|
39 |
+
out = subprocess.check_output(['nvidia-smi', '-L'])
|
40 |
+
for l in out.split(b'\n'):
|
41 |
+
if len(l) > 0:
|
42 |
+
gpu_names.add(l.decode('utf-8').split(' (UUID')[0])
|
43 |
+
return gpu_names
|
44 |
+
|
45 |
+
blacklist = {"GeForce GTX TITAN X", "GeForce GTX 980", "GeForce GTX 970", "GeForce GTX 960", "GeForce GTX 950", "GeForce 945M",
|
46 |
+
"GeForce 940M", "GeForce 930M", "GeForce 920M", "GeForce 910M", "GeForce GTX 750", "GeForce GTX 745", "Quadro K620",
|
47 |
+
"Quadro K1200", "Quadro K2200", "Quadro M500", "Quadro M520", "Quadro M600", "Quadro M620", "Quadro M1000",
|
48 |
+
"Quadro M1200", "Quadro M2000", "Quadro M2200", "Quadro M3000", "Quadro M4000", "Quadro M5000", "Quadro M5500", "Quadro M6000",
|
49 |
+
"GeForce MX110", "GeForce MX130", "GeForce 830M", "GeForce 840M", "GeForce GTX 850M", "GeForce GTX 860M",
|
50 |
+
"GeForce GTX 1650", "GeForce GTX 1630", "Tesla M4", "Tesla M6", "Tesla M10", "Tesla M40", "Tesla M60"
|
51 |
+
}
|
52 |
+
|
53 |
+
def cuda_malloc_supported():
|
54 |
+
try:
|
55 |
+
names = get_gpu_names()
|
56 |
+
except:
|
57 |
+
names = set()
|
58 |
+
for x in names:
|
59 |
+
if "NVIDIA" in x:
|
60 |
+
for b in blacklist:
|
61 |
+
if b in x:
|
62 |
+
return False
|
63 |
+
return True
|
64 |
+
|
65 |
+
|
66 |
+
if not args.cuda_malloc:
|
67 |
+
try:
|
68 |
+
version = ""
|
69 |
+
torch_spec = importlib.util.find_spec("torch")
|
70 |
+
for folder in torch_spec.submodule_search_locations:
|
71 |
+
ver_file = os.path.join(folder, "version.py")
|
72 |
+
if os.path.isfile(ver_file):
|
73 |
+
spec = importlib.util.spec_from_file_location("torch_version_import", ver_file)
|
74 |
+
module = importlib.util.module_from_spec(spec)
|
75 |
+
spec.loader.exec_module(module)
|
76 |
+
version = module.__version__
|
77 |
+
if int(version[0]) >= 2: #enable by default for torch version 2.0 and up
|
78 |
+
args.cuda_malloc = cuda_malloc_supported()
|
79 |
+
except:
|
80 |
+
pass
|
81 |
+
|
82 |
+
|
83 |
+
if args.cuda_malloc and not args.disable_cuda_malloc:
|
84 |
+
env_var = os.environ.get('PYTORCH_CUDA_ALLOC_CONF', None)
|
85 |
+
if env_var is None:
|
86 |
+
env_var = "backend:cudaMallocAsync"
|
87 |
+
else:
|
88 |
+
env_var += ",backend:cudaMallocAsync"
|
89 |
+
|
90 |
+
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = env_var
|
ComfyUI/execution.py
ADDED
@@ -0,0 +1,864 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import sys
|
2 |
+
import copy
|
3 |
+
import logging
|
4 |
+
import threading
|
5 |
+
import heapq
|
6 |
+
import time
|
7 |
+
import traceback
|
8 |
+
import inspect
|
9 |
+
from typing import List, Literal, NamedTuple, Optional
|
10 |
+
|
11 |
+
import torch
|
12 |
+
import nodes
|
13 |
+
|
14 |
+
import comfy.model_management
|
15 |
+
|
16 |
+
def get_input_data(inputs, class_def, unique_id, outputs={}, prompt={}, extra_data={}):
|
17 |
+
valid_inputs = class_def.INPUT_TYPES()
|
18 |
+
input_data_all = {}
|
19 |
+
for x in inputs:
|
20 |
+
input_data = inputs[x]
|
21 |
+
if isinstance(input_data, list):
|
22 |
+
input_unique_id = input_data[0]
|
23 |
+
output_index = input_data[1]
|
24 |
+
if input_unique_id not in outputs:
|
25 |
+
input_data_all[x] = (None,)
|
26 |
+
continue
|
27 |
+
obj = outputs[input_unique_id][output_index]
|
28 |
+
input_data_all[x] = obj
|
29 |
+
else:
|
30 |
+
if ("required" in valid_inputs and x in valid_inputs["required"]) or ("optional" in valid_inputs and x in valid_inputs["optional"]):
|
31 |
+
input_data_all[x] = [input_data]
|
32 |
+
|
33 |
+
if "hidden" in valid_inputs:
|
34 |
+
h = valid_inputs["hidden"]
|
35 |
+
for x in h:
|
36 |
+
if h[x] == "PROMPT":
|
37 |
+
input_data_all[x] = [prompt]
|
38 |
+
if h[x] == "EXTRA_PNGINFO":
|
39 |
+
input_data_all[x] = [extra_data.get('extra_pnginfo', None)]
|
40 |
+
if h[x] == "UNIQUE_ID":
|
41 |
+
input_data_all[x] = [unique_id]
|
42 |
+
return input_data_all
|
43 |
+
|
44 |
+
def map_node_over_list(obj, input_data_all, func, allow_interrupt=False):
|
45 |
+
# check if node wants the lists
|
46 |
+
input_is_list = False
|
47 |
+
if hasattr(obj, "INPUT_IS_LIST"):
|
48 |
+
input_is_list = obj.INPUT_IS_LIST
|
49 |
+
|
50 |
+
if len(input_data_all) == 0:
|
51 |
+
max_len_input = 0
|
52 |
+
else:
|
53 |
+
max_len_input = max([len(x) for x in input_data_all.values()])
|
54 |
+
|
55 |
+
# get a slice of inputs, repeat last input when list isn't long enough
|
56 |
+
def slice_dict(d, i):
|
57 |
+
d_new = dict()
|
58 |
+
for k,v in d.items():
|
59 |
+
d_new[k] = v[i if len(v) > i else -1]
|
60 |
+
return d_new
|
61 |
+
|
62 |
+
results = []
|
63 |
+
if input_is_list:
|
64 |
+
if allow_interrupt:
|
65 |
+
nodes.before_node_execution()
|
66 |
+
results.append(getattr(obj, func)(**input_data_all))
|
67 |
+
elif max_len_input == 0:
|
68 |
+
if allow_interrupt:
|
69 |
+
nodes.before_node_execution()
|
70 |
+
results.append(getattr(obj, func)())
|
71 |
+
else:
|
72 |
+
for i in range(max_len_input):
|
73 |
+
if allow_interrupt:
|
74 |
+
nodes.before_node_execution()
|
75 |
+
results.append(getattr(obj, func)(**slice_dict(input_data_all, i)))
|
76 |
+
return results
|
77 |
+
|
78 |
+
def get_output_data(obj, input_data_all):
|
79 |
+
|
80 |
+
results = []
|
81 |
+
uis = []
|
82 |
+
return_values = map_node_over_list(obj, input_data_all, obj.FUNCTION, allow_interrupt=True)
|
83 |
+
|
84 |
+
for r in return_values:
|
85 |
+
if isinstance(r, dict):
|
86 |
+
if 'ui' in r:
|
87 |
+
uis.append(r['ui'])
|
88 |
+
if 'result' in r:
|
89 |
+
results.append(r['result'])
|
90 |
+
else:
|
91 |
+
results.append(r)
|
92 |
+
|
93 |
+
output = []
|
94 |
+
if len(results) > 0:
|
95 |
+
# check which outputs need concatenating
|
96 |
+
output_is_list = [False] * len(results[0])
|
97 |
+
if hasattr(obj, "OUTPUT_IS_LIST"):
|
98 |
+
output_is_list = obj.OUTPUT_IS_LIST
|
99 |
+
|
100 |
+
# merge node execution results
|
101 |
+
for i, is_list in zip(range(len(results[0])), output_is_list):
|
102 |
+
if is_list:
|
103 |
+
output.append([x for o in results for x in o[i]])
|
104 |
+
else:
|
105 |
+
output.append([o[i] for o in results])
|
106 |
+
|
107 |
+
ui = dict()
|
108 |
+
if len(uis) > 0:
|
109 |
+
ui = {k: [y for x in uis for y in x[k]] for k in uis[0].keys()}
|
110 |
+
return output, ui
|
111 |
+
|
112 |
+
def format_value(x):
|
113 |
+
if x is None:
|
114 |
+
return None
|
115 |
+
elif isinstance(x, (int, float, bool, str)):
|
116 |
+
return x
|
117 |
+
else:
|
118 |
+
return str(x)
|
119 |
+
|
120 |
+
def recursive_execute(server, prompt, outputs, current_item, extra_data, executed, prompt_id, outputs_ui, object_storage):
|
121 |
+
unique_id = current_item
|
122 |
+
inputs = prompt[unique_id]['inputs']
|
123 |
+
class_type = prompt[unique_id]['class_type']
|
124 |
+
class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
|
125 |
+
if unique_id in outputs:
|
126 |
+
return (True, None, None)
|
127 |
+
|
128 |
+
for x in inputs:
|
129 |
+
input_data = inputs[x]
|
130 |
+
|
131 |
+
if isinstance(input_data, list):
|
132 |
+
input_unique_id = input_data[0]
|
133 |
+
output_index = input_data[1]
|
134 |
+
if input_unique_id not in outputs:
|
135 |
+
result = recursive_execute(server, prompt, outputs, input_unique_id, extra_data, executed, prompt_id, outputs_ui, object_storage)
|
136 |
+
if result[0] is not True:
|
137 |
+
# Another node failed further upstream
|
138 |
+
return result
|
139 |
+
|
140 |
+
input_data_all = None
|
141 |
+
try:
|
142 |
+
input_data_all = get_input_data(inputs, class_def, unique_id, outputs, prompt, extra_data)
|
143 |
+
if server.client_id is not None:
|
144 |
+
server.last_node_id = unique_id
|
145 |
+
server.send_sync("executing", { "node": unique_id, "prompt_id": prompt_id }, server.client_id)
|
146 |
+
|
147 |
+
obj = object_storage.get((unique_id, class_type), None)
|
148 |
+
if obj is None:
|
149 |
+
obj = class_def()
|
150 |
+
object_storage[(unique_id, class_type)] = obj
|
151 |
+
|
152 |
+
output_data, output_ui = get_output_data(obj, input_data_all)
|
153 |
+
outputs[unique_id] = output_data
|
154 |
+
if len(output_ui) > 0:
|
155 |
+
outputs_ui[unique_id] = output_ui
|
156 |
+
if server.client_id is not None:
|
157 |
+
server.send_sync("executed", { "node": unique_id, "output": output_ui, "prompt_id": prompt_id }, server.client_id)
|
158 |
+
except comfy.model_management.InterruptProcessingException as iex:
|
159 |
+
logging.info("Processing interrupted")
|
160 |
+
|
161 |
+
# skip formatting inputs/outputs
|
162 |
+
error_details = {
|
163 |
+
"node_id": unique_id,
|
164 |
+
}
|
165 |
+
|
166 |
+
return (False, error_details, iex)
|
167 |
+
except Exception as ex:
|
168 |
+
typ, _, tb = sys.exc_info()
|
169 |
+
exception_type = full_type_name(typ)
|
170 |
+
input_data_formatted = {}
|
171 |
+
if input_data_all is not None:
|
172 |
+
input_data_formatted = {}
|
173 |
+
for name, inputs in input_data_all.items():
|
174 |
+
input_data_formatted[name] = [format_value(x) for x in inputs]
|
175 |
+
|
176 |
+
output_data_formatted = {}
|
177 |
+
for node_id, node_outputs in outputs.items():
|
178 |
+
output_data_formatted[node_id] = [[format_value(x) for x in l] for l in node_outputs]
|
179 |
+
|
180 |
+
logging.error(f"!!! Exception during processing!!! {ex}")
|
181 |
+
logging.error(traceback.format_exc())
|
182 |
+
|
183 |
+
error_details = {
|
184 |
+
"node_id": unique_id,
|
185 |
+
"exception_message": str(ex),
|
186 |
+
"exception_type": exception_type,
|
187 |
+
"traceback": traceback.format_tb(tb),
|
188 |
+
"current_inputs": input_data_formatted,
|
189 |
+
"current_outputs": output_data_formatted
|
190 |
+
}
|
191 |
+
return (False, error_details, ex)
|
192 |
+
|
193 |
+
executed.add(unique_id)
|
194 |
+
|
195 |
+
return (True, None, None)
|
196 |
+
|
197 |
+
def recursive_will_execute(prompt, outputs, current_item, memo={}):
|
198 |
+
unique_id = current_item
|
199 |
+
|
200 |
+
if unique_id in memo:
|
201 |
+
return memo[unique_id]
|
202 |
+
|
203 |
+
inputs = prompt[unique_id]['inputs']
|
204 |
+
will_execute = []
|
205 |
+
if unique_id in outputs:
|
206 |
+
return []
|
207 |
+
|
208 |
+
for x in inputs:
|
209 |
+
input_data = inputs[x]
|
210 |
+
if isinstance(input_data, list):
|
211 |
+
input_unique_id = input_data[0]
|
212 |
+
output_index = input_data[1]
|
213 |
+
if input_unique_id not in outputs:
|
214 |
+
will_execute += recursive_will_execute(prompt, outputs, input_unique_id, memo)
|
215 |
+
|
216 |
+
memo[unique_id] = will_execute + [unique_id]
|
217 |
+
return memo[unique_id]
|
218 |
+
|
219 |
+
def recursive_output_delete_if_changed(prompt, old_prompt, outputs, current_item):
|
220 |
+
unique_id = current_item
|
221 |
+
inputs = prompt[unique_id]['inputs']
|
222 |
+
class_type = prompt[unique_id]['class_type']
|
223 |
+
class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
|
224 |
+
|
225 |
+
is_changed_old = ''
|
226 |
+
is_changed = ''
|
227 |
+
to_delete = False
|
228 |
+
if hasattr(class_def, 'IS_CHANGED'):
|
229 |
+
if unique_id in old_prompt and 'is_changed' in old_prompt[unique_id]:
|
230 |
+
is_changed_old = old_prompt[unique_id]['is_changed']
|
231 |
+
if 'is_changed' not in prompt[unique_id]:
|
232 |
+
input_data_all = get_input_data(inputs, class_def, unique_id, outputs)
|
233 |
+
if input_data_all is not None:
|
234 |
+
try:
|
235 |
+
#is_changed = class_def.IS_CHANGED(**input_data_all)
|
236 |
+
is_changed = map_node_over_list(class_def, input_data_all, "IS_CHANGED")
|
237 |
+
prompt[unique_id]['is_changed'] = is_changed
|
238 |
+
except:
|
239 |
+
to_delete = True
|
240 |
+
else:
|
241 |
+
is_changed = prompt[unique_id]['is_changed']
|
242 |
+
|
243 |
+
if unique_id not in outputs:
|
244 |
+
return True
|
245 |
+
|
246 |
+
if not to_delete:
|
247 |
+
if is_changed != is_changed_old:
|
248 |
+
to_delete = True
|
249 |
+
elif unique_id not in old_prompt:
|
250 |
+
to_delete = True
|
251 |
+
elif class_type != old_prompt[unique_id]['class_type']:
|
252 |
+
to_delete = True
|
253 |
+
elif inputs == old_prompt[unique_id]['inputs']:
|
254 |
+
for x in inputs:
|
255 |
+
input_data = inputs[x]
|
256 |
+
|
257 |
+
if isinstance(input_data, list):
|
258 |
+
input_unique_id = input_data[0]
|
259 |
+
output_index = input_data[1]
|
260 |
+
if input_unique_id in outputs:
|
261 |
+
to_delete = recursive_output_delete_if_changed(prompt, old_prompt, outputs, input_unique_id)
|
262 |
+
else:
|
263 |
+
to_delete = True
|
264 |
+
if to_delete:
|
265 |
+
break
|
266 |
+
else:
|
267 |
+
to_delete = True
|
268 |
+
|
269 |
+
if to_delete:
|
270 |
+
d = outputs.pop(unique_id)
|
271 |
+
del d
|
272 |
+
return to_delete
|
273 |
+
|
274 |
+
class PromptExecutor:
|
275 |
+
def __init__(self, server):
|
276 |
+
self.server = server
|
277 |
+
self.reset()
|
278 |
+
|
279 |
+
def reset(self):
|
280 |
+
self.outputs = {}
|
281 |
+
self.object_storage = {}
|
282 |
+
self.outputs_ui = {}
|
283 |
+
self.status_messages = []
|
284 |
+
self.success = True
|
285 |
+
self.old_prompt = {}
|
286 |
+
|
287 |
+
def add_message(self, event, data: dict, broadcast: bool):
|
288 |
+
data = {
|
289 |
+
**data,
|
290 |
+
"timestamp": int(time.time() * 1000),
|
291 |
+
}
|
292 |
+
self.status_messages.append((event, data))
|
293 |
+
if self.server.client_id is not None or broadcast:
|
294 |
+
self.server.send_sync(event, data, self.server.client_id)
|
295 |
+
|
296 |
+
def handle_execution_error(self, prompt_id, prompt, current_outputs, executed, error, ex):
|
297 |
+
node_id = error["node_id"]
|
298 |
+
class_type = prompt[node_id]["class_type"]
|
299 |
+
|
300 |
+
# First, send back the status to the frontend depending
|
301 |
+
# on the exception type
|
302 |
+
if isinstance(ex, comfy.model_management.InterruptProcessingException):
|
303 |
+
mes = {
|
304 |
+
"prompt_id": prompt_id,
|
305 |
+
"node_id": node_id,
|
306 |
+
"node_type": class_type,
|
307 |
+
"executed": list(executed),
|
308 |
+
}
|
309 |
+
self.add_message("execution_interrupted", mes, broadcast=True)
|
310 |
+
else:
|
311 |
+
mes = {
|
312 |
+
"prompt_id": prompt_id,
|
313 |
+
"node_id": node_id,
|
314 |
+
"node_type": class_type,
|
315 |
+
"executed": list(executed),
|
316 |
+
|
317 |
+
"exception_message": error["exception_message"],
|
318 |
+
"exception_type": error["exception_type"],
|
319 |
+
"traceback": error["traceback"],
|
320 |
+
"current_inputs": error["current_inputs"],
|
321 |
+
"current_outputs": error["current_outputs"],
|
322 |
+
}
|
323 |
+
self.add_message("execution_error", mes, broadcast=False)
|
324 |
+
|
325 |
+
# Next, remove the subsequent outputs since they will not be executed
|
326 |
+
to_delete = []
|
327 |
+
for o in self.outputs:
|
328 |
+
if (o not in current_outputs) and (o not in executed):
|
329 |
+
to_delete += [o]
|
330 |
+
if o in self.old_prompt:
|
331 |
+
d = self.old_prompt.pop(o)
|
332 |
+
del d
|
333 |
+
for o in to_delete:
|
334 |
+
d = self.outputs.pop(o)
|
335 |
+
del d
|
336 |
+
|
337 |
+
def execute(self, prompt, prompt_id, extra_data={}, execute_outputs=[]):
|
338 |
+
nodes.interrupt_processing(False)
|
339 |
+
|
340 |
+
if "client_id" in extra_data:
|
341 |
+
self.server.client_id = extra_data["client_id"]
|
342 |
+
else:
|
343 |
+
self.server.client_id = None
|
344 |
+
|
345 |
+
self.status_messages = []
|
346 |
+
self.add_message("execution_start", { "prompt_id": prompt_id}, broadcast=False)
|
347 |
+
|
348 |
+
with torch.inference_mode():
|
349 |
+
#delete cached outputs if nodes don't exist for them
|
350 |
+
to_delete = []
|
351 |
+
for o in self.outputs:
|
352 |
+
if o not in prompt:
|
353 |
+
to_delete += [o]
|
354 |
+
for o in to_delete:
|
355 |
+
d = self.outputs.pop(o)
|
356 |
+
del d
|
357 |
+
to_delete = []
|
358 |
+
for o in self.object_storage:
|
359 |
+
if o[0] not in prompt:
|
360 |
+
to_delete += [o]
|
361 |
+
else:
|
362 |
+
p = prompt[o[0]]
|
363 |
+
if o[1] != p['class_type']:
|
364 |
+
to_delete += [o]
|
365 |
+
for o in to_delete:
|
366 |
+
d = self.object_storage.pop(o)
|
367 |
+
del d
|
368 |
+
|
369 |
+
for x in prompt:
|
370 |
+
recursive_output_delete_if_changed(prompt, self.old_prompt, self.outputs, x)
|
371 |
+
|
372 |
+
current_outputs = set(self.outputs.keys())
|
373 |
+
for x in list(self.outputs_ui.keys()):
|
374 |
+
if x not in current_outputs:
|
375 |
+
d = self.outputs_ui.pop(x)
|
376 |
+
del d
|
377 |
+
|
378 |
+
comfy.model_management.cleanup_models(keep_clone_weights_loaded=True)
|
379 |
+
self.add_message("execution_cached",
|
380 |
+
{ "nodes": list(current_outputs) , "prompt_id": prompt_id},
|
381 |
+
broadcast=False)
|
382 |
+
executed = set()
|
383 |
+
output_node_id = None
|
384 |
+
to_execute = []
|
385 |
+
|
386 |
+
for node_id in list(execute_outputs):
|
387 |
+
to_execute += [(0, node_id)]
|
388 |
+
|
389 |
+
while len(to_execute) > 0:
|
390 |
+
#always execute the output that depends on the least amount of unexecuted nodes first
|
391 |
+
memo = {}
|
392 |
+
to_execute = sorted(list(map(lambda a: (len(recursive_will_execute(prompt, self.outputs, a[-1], memo)), a[-1]), to_execute)))
|
393 |
+
output_node_id = to_execute.pop(0)[-1]
|
394 |
+
|
395 |
+
# This call shouldn't raise anything if there's an error deep in
|
396 |
+
# the actual SD code, instead it will report the node where the
|
397 |
+
# error was raised
|
398 |
+
self.success, error, ex = recursive_execute(self.server, prompt, self.outputs, output_node_id, extra_data, executed, prompt_id, self.outputs_ui, self.object_storage)
|
399 |
+
if self.success is not True:
|
400 |
+
self.handle_execution_error(prompt_id, prompt, current_outputs, executed, error, ex)
|
401 |
+
break
|
402 |
+
else:
|
403 |
+
# Only execute when the while-loop ends without break
|
404 |
+
self.add_message("execution_success", { "prompt_id": prompt_id }, broadcast=False)
|
405 |
+
|
406 |
+
for x in executed:
|
407 |
+
self.old_prompt[x] = copy.deepcopy(prompt[x])
|
408 |
+
self.server.last_node_id = None
|
409 |
+
if comfy.model_management.DISABLE_SMART_MEMORY:
|
410 |
+
comfy.model_management.unload_all_models()
|
411 |
+
|
412 |
+
|
413 |
+
|
414 |
+
def validate_inputs(prompt, item, validated):
|
415 |
+
unique_id = item
|
416 |
+
if unique_id in validated:
|
417 |
+
return validated[unique_id]
|
418 |
+
|
419 |
+
inputs = prompt[unique_id]['inputs']
|
420 |
+
class_type = prompt[unique_id]['class_type']
|
421 |
+
obj_class = nodes.NODE_CLASS_MAPPINGS[class_type]
|
422 |
+
|
423 |
+
class_inputs = obj_class.INPUT_TYPES()
|
424 |
+
required_inputs = class_inputs['required']
|
425 |
+
|
426 |
+
errors = []
|
427 |
+
valid = True
|
428 |
+
|
429 |
+
validate_function_inputs = []
|
430 |
+
if hasattr(obj_class, "VALIDATE_INPUTS"):
|
431 |
+
validate_function_inputs = inspect.getfullargspec(obj_class.VALIDATE_INPUTS).args
|
432 |
+
|
433 |
+
for x in required_inputs:
|
434 |
+
if x not in inputs:
|
435 |
+
error = {
|
436 |
+
"type": "required_input_missing",
|
437 |
+
"message": "Required input is missing",
|
438 |
+
"details": f"{x}",
|
439 |
+
"extra_info": {
|
440 |
+
"input_name": x
|
441 |
+
}
|
442 |
+
}
|
443 |
+
errors.append(error)
|
444 |
+
continue
|
445 |
+
|
446 |
+
val = inputs[x]
|
447 |
+
info = required_inputs[x]
|
448 |
+
type_input = info[0]
|
449 |
+
if isinstance(val, list):
|
450 |
+
if len(val) != 2:
|
451 |
+
error = {
|
452 |
+
"type": "bad_linked_input",
|
453 |
+
"message": "Bad linked input, must be a length-2 list of [node_id, slot_index]",
|
454 |
+
"details": f"{x}",
|
455 |
+
"extra_info": {
|
456 |
+
"input_name": x,
|
457 |
+
"input_config": info,
|
458 |
+
"received_value": val
|
459 |
+
}
|
460 |
+
}
|
461 |
+
errors.append(error)
|
462 |
+
continue
|
463 |
+
|
464 |
+
o_id = val[0]
|
465 |
+
o_class_type = prompt[o_id]['class_type']
|
466 |
+
r = nodes.NODE_CLASS_MAPPINGS[o_class_type].RETURN_TYPES
|
467 |
+
if r[val[1]] != type_input:
|
468 |
+
received_type = r[val[1]]
|
469 |
+
details = f"{x}, {received_type} != {type_input}"
|
470 |
+
error = {
|
471 |
+
"type": "return_type_mismatch",
|
472 |
+
"message": "Return type mismatch between linked nodes",
|
473 |
+
"details": details,
|
474 |
+
"extra_info": {
|
475 |
+
"input_name": x,
|
476 |
+
"input_config": info,
|
477 |
+
"received_type": received_type,
|
478 |
+
"linked_node": val
|
479 |
+
}
|
480 |
+
}
|
481 |
+
errors.append(error)
|
482 |
+
continue
|
483 |
+
try:
|
484 |
+
r = validate_inputs(prompt, o_id, validated)
|
485 |
+
if r[0] is False:
|
486 |
+
# `r` will be set in `validated[o_id]` already
|
487 |
+
valid = False
|
488 |
+
continue
|
489 |
+
except Exception as ex:
|
490 |
+
typ, _, tb = sys.exc_info()
|
491 |
+
valid = False
|
492 |
+
exception_type = full_type_name(typ)
|
493 |
+
reasons = [{
|
494 |
+
"type": "exception_during_inner_validation",
|
495 |
+
"message": "Exception when validating inner node",
|
496 |
+
"details": str(ex),
|
497 |
+
"extra_info": {
|
498 |
+
"input_name": x,
|
499 |
+
"input_config": info,
|
500 |
+
"exception_message": str(ex),
|
501 |
+
"exception_type": exception_type,
|
502 |
+
"traceback": traceback.format_tb(tb),
|
503 |
+
"linked_node": val
|
504 |
+
}
|
505 |
+
}]
|
506 |
+
validated[o_id] = (False, reasons, o_id)
|
507 |
+
continue
|
508 |
+
else:
|
509 |
+
try:
|
510 |
+
if type_input == "INT":
|
511 |
+
val = int(val)
|
512 |
+
inputs[x] = val
|
513 |
+
if type_input == "FLOAT":
|
514 |
+
val = float(val)
|
515 |
+
inputs[x] = val
|
516 |
+
if type_input == "STRING":
|
517 |
+
val = str(val)
|
518 |
+
inputs[x] = val
|
519 |
+
except Exception as ex:
|
520 |
+
error = {
|
521 |
+
"type": "invalid_input_type",
|
522 |
+
"message": f"Failed to convert an input value to a {type_input} value",
|
523 |
+
"details": f"{x}, {val}, {ex}",
|
524 |
+
"extra_info": {
|
525 |
+
"input_name": x,
|
526 |
+
"input_config": info,
|
527 |
+
"received_value": val,
|
528 |
+
"exception_message": str(ex)
|
529 |
+
}
|
530 |
+
}
|
531 |
+
errors.append(error)
|
532 |
+
continue
|
533 |
+
|
534 |
+
if len(info) > 1:
|
535 |
+
if "min" in info[1] and val < info[1]["min"]:
|
536 |
+
error = {
|
537 |
+
"type": "value_smaller_than_min",
|
538 |
+
"message": "Value {} smaller than min of {}".format(val, info[1]["min"]),
|
539 |
+
"details": f"{x}",
|
540 |
+
"extra_info": {
|
541 |
+
"input_name": x,
|
542 |
+
"input_config": info,
|
543 |
+
"received_value": val,
|
544 |
+
}
|
545 |
+
}
|
546 |
+
errors.append(error)
|
547 |
+
continue
|
548 |
+
if "max" in info[1] and val > info[1]["max"]:
|
549 |
+
error = {
|
550 |
+
"type": "value_bigger_than_max",
|
551 |
+
"message": "Value {} bigger than max of {}".format(val, info[1]["max"]),
|
552 |
+
"details": f"{x}",
|
553 |
+
"extra_info": {
|
554 |
+
"input_name": x,
|
555 |
+
"input_config": info,
|
556 |
+
"received_value": val,
|
557 |
+
}
|
558 |
+
}
|
559 |
+
errors.append(error)
|
560 |
+
continue
|
561 |
+
|
562 |
+
if x not in validate_function_inputs:
|
563 |
+
if isinstance(type_input, list):
|
564 |
+
if val not in type_input:
|
565 |
+
input_config = info
|
566 |
+
list_info = ""
|
567 |
+
|
568 |
+
# Don't send back gigantic lists like if they're lots of
|
569 |
+
# scanned model filepaths
|
570 |
+
if len(type_input) > 20:
|
571 |
+
list_info = f"(list of length {len(type_input)})"
|
572 |
+
input_config = None
|
573 |
+
else:
|
574 |
+
list_info = str(type_input)
|
575 |
+
|
576 |
+
error = {
|
577 |
+
"type": "value_not_in_list",
|
578 |
+
"message": "Value not in list",
|
579 |
+
"details": f"{x}: '{val}' not in {list_info}",
|
580 |
+
"extra_info": {
|
581 |
+
"input_name": x,
|
582 |
+
"input_config": input_config,
|
583 |
+
"received_value": val,
|
584 |
+
}
|
585 |
+
}
|
586 |
+
errors.append(error)
|
587 |
+
continue
|
588 |
+
|
589 |
+
if len(validate_function_inputs) > 0:
|
590 |
+
input_data_all = get_input_data(inputs, obj_class, unique_id)
|
591 |
+
input_filtered = {}
|
592 |
+
for x in input_data_all:
|
593 |
+
if x in validate_function_inputs:
|
594 |
+
input_filtered[x] = input_data_all[x]
|
595 |
+
|
596 |
+
#ret = obj_class.VALIDATE_INPUTS(**input_filtered)
|
597 |
+
ret = map_node_over_list(obj_class, input_filtered, "VALIDATE_INPUTS")
|
598 |
+
for x in input_filtered:
|
599 |
+
for i, r in enumerate(ret):
|
600 |
+
if r is not True:
|
601 |
+
details = f"{x}"
|
602 |
+
if r is not False:
|
603 |
+
details += f" - {str(r)}"
|
604 |
+
|
605 |
+
error = {
|
606 |
+
"type": "custom_validation_failed",
|
607 |
+
"message": "Custom validation failed for node",
|
608 |
+
"details": details,
|
609 |
+
"extra_info": {
|
610 |
+
"input_name": x,
|
611 |
+
"input_config": info,
|
612 |
+
"received_value": val,
|
613 |
+
}
|
614 |
+
}
|
615 |
+
errors.append(error)
|
616 |
+
continue
|
617 |
+
|
618 |
+
if len(errors) > 0 or valid is not True:
|
619 |
+
ret = (False, errors, unique_id)
|
620 |
+
else:
|
621 |
+
ret = (True, [], unique_id)
|
622 |
+
|
623 |
+
validated[unique_id] = ret
|
624 |
+
return ret
|
625 |
+
|
626 |
+
def full_type_name(klass):
|
627 |
+
module = klass.__module__
|
628 |
+
if module == 'builtins':
|
629 |
+
return klass.__qualname__
|
630 |
+
return module + '.' + klass.__qualname__
|
631 |
+
|
632 |
+
def validate_prompt(prompt):
|
633 |
+
outputs = set()
|
634 |
+
for x in prompt:
|
635 |
+
if 'class_type' not in prompt[x]:
|
636 |
+
error = {
|
637 |
+
"type": "invalid_prompt",
|
638 |
+
"message": f"Cannot execute because a node is missing the class_type property.",
|
639 |
+
"details": f"Node ID '#{x}'",
|
640 |
+
"extra_info": {}
|
641 |
+
}
|
642 |
+
return (False, error, [], [])
|
643 |
+
|
644 |
+
class_type = prompt[x]['class_type']
|
645 |
+
class_ = nodes.NODE_CLASS_MAPPINGS.get(class_type, None)
|
646 |
+
if class_ is None:
|
647 |
+
error = {
|
648 |
+
"type": "invalid_prompt",
|
649 |
+
"message": f"Cannot execute because node {class_type} does not exist.",
|
650 |
+
"details": f"Node ID '#{x}'",
|
651 |
+
"extra_info": {}
|
652 |
+
}
|
653 |
+
return (False, error, [], [])
|
654 |
+
|
655 |
+
if hasattr(class_, 'OUTPUT_NODE') and class_.OUTPUT_NODE is True:
|
656 |
+
outputs.add(x)
|
657 |
+
|
658 |
+
if len(outputs) == 0:
|
659 |
+
error = {
|
660 |
+
"type": "prompt_no_outputs",
|
661 |
+
"message": "Prompt has no outputs",
|
662 |
+
"details": "",
|
663 |
+
"extra_info": {}
|
664 |
+
}
|
665 |
+
return (False, error, [], [])
|
666 |
+
|
667 |
+
good_outputs = set()
|
668 |
+
errors = []
|
669 |
+
node_errors = {}
|
670 |
+
validated = {}
|
671 |
+
for o in outputs:
|
672 |
+
valid = False
|
673 |
+
reasons = []
|
674 |
+
try:
|
675 |
+
m = validate_inputs(prompt, o, validated)
|
676 |
+
valid = m[0]
|
677 |
+
reasons = m[1]
|
678 |
+
except Exception as ex:
|
679 |
+
typ, _, tb = sys.exc_info()
|
680 |
+
valid = False
|
681 |
+
exception_type = full_type_name(typ)
|
682 |
+
reasons = [{
|
683 |
+
"type": "exception_during_validation",
|
684 |
+
"message": "Exception when validating node",
|
685 |
+
"details": str(ex),
|
686 |
+
"extra_info": {
|
687 |
+
"exception_type": exception_type,
|
688 |
+
"traceback": traceback.format_tb(tb)
|
689 |
+
}
|
690 |
+
}]
|
691 |
+
validated[o] = (False, reasons, o)
|
692 |
+
|
693 |
+
if valid is True:
|
694 |
+
good_outputs.add(o)
|
695 |
+
else:
|
696 |
+
logging.error(f"Failed to validate prompt for output {o}:")
|
697 |
+
if len(reasons) > 0:
|
698 |
+
logging.error("* (prompt):")
|
699 |
+
for reason in reasons:
|
700 |
+
logging.error(f" - {reason['message']}: {reason['details']}")
|
701 |
+
errors += [(o, reasons)]
|
702 |
+
for node_id, result in validated.items():
|
703 |
+
valid = result[0]
|
704 |
+
reasons = result[1]
|
705 |
+
# If a node upstream has errors, the nodes downstream will also
|
706 |
+
# be reported as invalid, but there will be no errors attached.
|
707 |
+
# So don't return those nodes as having errors in the response.
|
708 |
+
if valid is not True and len(reasons) > 0:
|
709 |
+
if node_id not in node_errors:
|
710 |
+
class_type = prompt[node_id]['class_type']
|
711 |
+
node_errors[node_id] = {
|
712 |
+
"errors": reasons,
|
713 |
+
"dependent_outputs": [],
|
714 |
+
"class_type": class_type
|
715 |
+
}
|
716 |
+
logging.error(f"* {class_type} {node_id}:")
|
717 |
+
for reason in reasons:
|
718 |
+
logging.error(f" - {reason['message']}: {reason['details']}")
|
719 |
+
node_errors[node_id]["dependent_outputs"].append(o)
|
720 |
+
logging.error("Output will be ignored")
|
721 |
+
|
722 |
+
if len(good_outputs) == 0:
|
723 |
+
errors_list = []
|
724 |
+
for o, errors in errors:
|
725 |
+
for error in errors:
|
726 |
+
errors_list.append(f"{error['message']}: {error['details']}")
|
727 |
+
errors_list = "\n".join(errors_list)
|
728 |
+
|
729 |
+
error = {
|
730 |
+
"type": "prompt_outputs_failed_validation",
|
731 |
+
"message": "Prompt outputs failed validation",
|
732 |
+
"details": errors_list,
|
733 |
+
"extra_info": {}
|
734 |
+
}
|
735 |
+
|
736 |
+
return (False, error, list(good_outputs), node_errors)
|
737 |
+
|
738 |
+
return (True, None, list(good_outputs), node_errors)
|
739 |
+
|
740 |
+
MAXIMUM_HISTORY_SIZE = 10000
|
741 |
+
|
742 |
+
class PromptQueue:
|
743 |
+
def __init__(self, server):
|
744 |
+
self.server = server
|
745 |
+
self.mutex = threading.RLock()
|
746 |
+
self.not_empty = threading.Condition(self.mutex)
|
747 |
+
self.task_counter = 0
|
748 |
+
self.queue = []
|
749 |
+
self.currently_running = {}
|
750 |
+
self.history = {}
|
751 |
+
self.flags = {}
|
752 |
+
server.prompt_queue = self
|
753 |
+
|
754 |
+
def put(self, item):
|
755 |
+
with self.mutex:
|
756 |
+
heapq.heappush(self.queue, item)
|
757 |
+
self.server.queue_updated()
|
758 |
+
self.not_empty.notify()
|
759 |
+
|
760 |
+
def get(self, timeout=None):
|
761 |
+
with self.not_empty:
|
762 |
+
while len(self.queue) == 0:
|
763 |
+
self.not_empty.wait(timeout=timeout)
|
764 |
+
if timeout is not None and len(self.queue) == 0:
|
765 |
+
return None
|
766 |
+
item = heapq.heappop(self.queue)
|
767 |
+
i = self.task_counter
|
768 |
+
self.currently_running[i] = copy.deepcopy(item)
|
769 |
+
self.task_counter += 1
|
770 |
+
self.server.queue_updated()
|
771 |
+
return (item, i)
|
772 |
+
|
773 |
+
class ExecutionStatus(NamedTuple):
|
774 |
+
status_str: Literal['success', 'error']
|
775 |
+
completed: bool
|
776 |
+
messages: List[str]
|
777 |
+
|
778 |
+
def task_done(self, item_id, outputs,
|
779 |
+
status: Optional['PromptQueue.ExecutionStatus']):
|
780 |
+
with self.mutex:
|
781 |
+
prompt = self.currently_running.pop(item_id)
|
782 |
+
if len(self.history) > MAXIMUM_HISTORY_SIZE:
|
783 |
+
self.history.pop(next(iter(self.history)))
|
784 |
+
|
785 |
+
status_dict: Optional[dict] = None
|
786 |
+
if status is not None:
|
787 |
+
status_dict = copy.deepcopy(status._asdict())
|
788 |
+
|
789 |
+
self.history[prompt[1]] = {
|
790 |
+
"prompt": prompt,
|
791 |
+
"outputs": copy.deepcopy(outputs),
|
792 |
+
'status': status_dict,
|
793 |
+
}
|
794 |
+
self.server.queue_updated()
|
795 |
+
|
796 |
+
def get_current_queue(self):
|
797 |
+
with self.mutex:
|
798 |
+
out = []
|
799 |
+
for x in self.currently_running.values():
|
800 |
+
out += [x]
|
801 |
+
return (out, copy.deepcopy(self.queue))
|
802 |
+
|
803 |
+
def get_tasks_remaining(self):
|
804 |
+
with self.mutex:
|
805 |
+
return len(self.queue) + len(self.currently_running)
|
806 |
+
|
807 |
+
def wipe_queue(self):
|
808 |
+
with self.mutex:
|
809 |
+
self.queue = []
|
810 |
+
self.server.queue_updated()
|
811 |
+
|
812 |
+
def delete_queue_item(self, function):
|
813 |
+
with self.mutex:
|
814 |
+
for x in range(len(self.queue)):
|
815 |
+
if function(self.queue[x]):
|
816 |
+
if len(self.queue) == 1:
|
817 |
+
self.wipe_queue()
|
818 |
+
else:
|
819 |
+
self.queue.pop(x)
|
820 |
+
heapq.heapify(self.queue)
|
821 |
+
self.server.queue_updated()
|
822 |
+
return True
|
823 |
+
return False
|
824 |
+
|
825 |
+
def get_history(self, prompt_id=None, max_items=None, offset=-1):
|
826 |
+
with self.mutex:
|
827 |
+
if prompt_id is None:
|
828 |
+
out = {}
|
829 |
+
i = 0
|
830 |
+
if offset < 0 and max_items is not None:
|
831 |
+
offset = len(self.history) - max_items
|
832 |
+
for k in self.history:
|
833 |
+
if i >= offset:
|
834 |
+
out[k] = self.history[k]
|
835 |
+
if max_items is not None and len(out) >= max_items:
|
836 |
+
break
|
837 |
+
i += 1
|
838 |
+
return out
|
839 |
+
elif prompt_id in self.history:
|
840 |
+
return {prompt_id: copy.deepcopy(self.history[prompt_id])}
|
841 |
+
else:
|
842 |
+
return {}
|
843 |
+
|
844 |
+
def wipe_history(self):
|
845 |
+
with self.mutex:
|
846 |
+
self.history = {}
|
847 |
+
|
848 |
+
def delete_history_item(self, id_to_delete):
|
849 |
+
with self.mutex:
|
850 |
+
self.history.pop(id_to_delete, None)
|
851 |
+
|
852 |
+
def set_flag(self, name, data):
|
853 |
+
with self.mutex:
|
854 |
+
self.flags[name] = data
|
855 |
+
self.not_empty.notify()
|
856 |
+
|
857 |
+
def get_flags(self, reset=True):
|
858 |
+
with self.mutex:
|
859 |
+
if reset:
|
860 |
+
ret = self.flags
|
861 |
+
self.flags = {}
|
862 |
+
return ret
|
863 |
+
else:
|
864 |
+
return self.flags.copy()
|
ComfyUI/extra_model_paths.yaml.example
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#Rename this to extra_model_paths.yaml and ComfyUI will load it
|
2 |
+
|
3 |
+
|
4 |
+
#config for a1111 ui
|
5 |
+
#all you have to do is change the base_path to where yours is installed
|
6 |
+
a111:
|
7 |
+
base_path: path/to/stable-diffusion-webui/
|
8 |
+
|
9 |
+
checkpoints: models/Stable-diffusion
|
10 |
+
configs: models/Stable-diffusion
|
11 |
+
vae: models/VAE
|
12 |
+
loras: |
|
13 |
+
models/Lora
|
14 |
+
models/LyCORIS
|
15 |
+
upscale_models: |
|
16 |
+
models/ESRGAN
|
17 |
+
models/RealESRGAN
|
18 |
+
models/SwinIR
|
19 |
+
embeddings: embeddings
|
20 |
+
hypernetworks: models/hypernetworks
|
21 |
+
controlnet: models/ControlNet
|
22 |
+
|
23 |
+
#config for comfyui
|
24 |
+
#your base path should be either an existing comfy install or a central folder where you store all of your models, loras, etc.
|
25 |
+
|
26 |
+
#comfyui:
|
27 |
+
# base_path: path/to/comfyui/
|
28 |
+
# checkpoints: models/checkpoints/
|
29 |
+
# clip: models/clip/
|
30 |
+
# clip_vision: models/clip_vision/
|
31 |
+
# configs: models/configs/
|
32 |
+
# controlnet: models/controlnet/
|
33 |
+
# embeddings: models/embeddings/
|
34 |
+
# loras: models/loras/
|
35 |
+
# upscale_models: models/upscale_models/
|
36 |
+
# vae: models/vae/
|
37 |
+
|
38 |
+
#other_ui:
|
39 |
+
# base_path: path/to/ui
|
40 |
+
# checkpoints: models/checkpoints
|
41 |
+
# gligen: models/gligen
|
42 |
+
# custom_nodes: path/custom_nodes
|
ComfyUI/fix_torch.py
ADDED
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import importlib.util
|
2 |
+
import shutil
|
3 |
+
import os
|
4 |
+
import ctypes
|
5 |
+
import logging
|
6 |
+
|
7 |
+
|
8 |
+
torch_spec = importlib.util.find_spec("torch")
|
9 |
+
for folder in torch_spec.submodule_search_locations:
|
10 |
+
lib_folder = os.path.join(folder, "lib")
|
11 |
+
test_file = os.path.join(lib_folder, "fbgemm.dll")
|
12 |
+
dest = os.path.join(lib_folder, "libomp140.x86_64.dll")
|
13 |
+
if os.path.exists(dest):
|
14 |
+
break
|
15 |
+
|
16 |
+
with open(test_file, 'rb') as f:
|
17 |
+
contents = f.read()
|
18 |
+
if b"libomp140.x86_64.dll" not in contents:
|
19 |
+
break
|
20 |
+
try:
|
21 |
+
mydll = ctypes.cdll.LoadLibrary(test_file)
|
22 |
+
except FileNotFoundError as e:
|
23 |
+
logging.warning("Detected pytorch version with libomp issue, patching.")
|
24 |
+
shutil.copyfile(os.path.join(lib_folder, "libiomp5md.dll"), dest)
|
ComfyUI/folder_paths.py
ADDED
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import time
|
3 |
+
import logging
|
4 |
+
from typing import Set, List, Dict, Tuple
|
5 |
+
|
6 |
+
supported_pt_extensions: Set[str] = set(['.ckpt', '.pt', '.bin', '.pth', '.safetensors', '.pkl'])
|
7 |
+
|
8 |
+
SupportedFileExtensionsType = Set[str]
|
9 |
+
ScanPathType = List[str]
|
10 |
+
folder_names_and_paths: Dict[str, Tuple[ScanPathType, SupportedFileExtensionsType]] = {}
|
11 |
+
|
12 |
+
base_path = os.path.dirname(os.path.realpath(__file__))
|
13 |
+
models_dir = os.path.join(base_path, "models")
|
14 |
+
folder_names_and_paths["checkpoints"] = ([os.path.join(models_dir, "checkpoints")], supported_pt_extensions)
|
15 |
+
folder_names_and_paths["configs"] = ([os.path.join(models_dir, "configs")], [".yaml"])
|
16 |
+
|
17 |
+
folder_names_and_paths["loras"] = ([os.path.join(models_dir, "loras")], supported_pt_extensions)
|
18 |
+
folder_names_and_paths["vae"] = ([os.path.join(models_dir, "vae")], supported_pt_extensions)
|
19 |
+
folder_names_and_paths["clip"] = ([os.path.join(models_dir, "clip")], supported_pt_extensions)
|
20 |
+
folder_names_and_paths["unet"] = ([os.path.join(models_dir, "unet")], supported_pt_extensions)
|
21 |
+
folder_names_and_paths["clip_vision"] = ([os.path.join(models_dir, "clip_vision")], supported_pt_extensions)
|
22 |
+
folder_names_and_paths["style_models"] = ([os.path.join(models_dir, "style_models")], supported_pt_extensions)
|
23 |
+
folder_names_and_paths["embeddings"] = ([os.path.join(models_dir, "embeddings")], supported_pt_extensions)
|
24 |
+
folder_names_and_paths["diffusers"] = ([os.path.join(models_dir, "diffusers")], ["folder"])
|
25 |
+
folder_names_and_paths["vae_approx"] = ([os.path.join(models_dir, "vae_approx")], supported_pt_extensions)
|
26 |
+
|
27 |
+
folder_names_and_paths["controlnet"] = ([os.path.join(models_dir, "controlnet"), os.path.join(models_dir, "t2i_adapter")], supported_pt_extensions)
|
28 |
+
folder_names_and_paths["gligen"] = ([os.path.join(models_dir, "gligen")], supported_pt_extensions)
|
29 |
+
|
30 |
+
folder_names_and_paths["upscale_models"] = ([os.path.join(models_dir, "upscale_models")], supported_pt_extensions)
|
31 |
+
|
32 |
+
folder_names_and_paths["custom_nodes"] = ([os.path.join(base_path, "custom_nodes")], set())
|
33 |
+
|
34 |
+
folder_names_and_paths["hypernetworks"] = ([os.path.join(models_dir, "hypernetworks")], supported_pt_extensions)
|
35 |
+
|
36 |
+
folder_names_and_paths["photomaker"] = ([os.path.join(models_dir, "photomaker")], supported_pt_extensions)
|
37 |
+
|
38 |
+
folder_names_and_paths["classifiers"] = ([os.path.join(models_dir, "classifiers")], {""})
|
39 |
+
|
40 |
+
output_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output")
|
41 |
+
temp_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "temp")
|
42 |
+
input_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "input")
|
43 |
+
user_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "user")
|
44 |
+
|
45 |
+
filename_list_cache = {}
|
46 |
+
|
47 |
+
if not os.path.exists(input_directory):
|
48 |
+
try:
|
49 |
+
os.makedirs(input_directory)
|
50 |
+
except:
|
51 |
+
logging.error("Failed to create input directory")
|
52 |
+
|
53 |
+
def set_output_directory(output_dir):
|
54 |
+
global output_directory
|
55 |
+
output_directory = output_dir
|
56 |
+
|
57 |
+
def set_temp_directory(temp_dir):
|
58 |
+
global temp_directory
|
59 |
+
temp_directory = temp_dir
|
60 |
+
|
61 |
+
def set_input_directory(input_dir):
|
62 |
+
global input_directory
|
63 |
+
input_directory = input_dir
|
64 |
+
|
65 |
+
def get_output_directory():
|
66 |
+
global output_directory
|
67 |
+
return output_directory
|
68 |
+
|
69 |
+
def get_temp_directory():
|
70 |
+
global temp_directory
|
71 |
+
return temp_directory
|
72 |
+
|
73 |
+
def get_input_directory():
|
74 |
+
global input_directory
|
75 |
+
return input_directory
|
76 |
+
|
77 |
+
|
78 |
+
#NOTE: used in http server so don't put folders that should not be accessed remotely
|
79 |
+
def get_directory_by_type(type_name):
|
80 |
+
if type_name == "output":
|
81 |
+
return get_output_directory()
|
82 |
+
if type_name == "temp":
|
83 |
+
return get_temp_directory()
|
84 |
+
if type_name == "input":
|
85 |
+
return get_input_directory()
|
86 |
+
return None
|
87 |
+
|
88 |
+
|
89 |
+
# determine base_dir rely on annotation if name is 'filename.ext [annotation]' format
|
90 |
+
# otherwise use default_path as base_dir
|
91 |
+
def annotated_filepath(name):
|
92 |
+
if name.endswith("[output]"):
|
93 |
+
base_dir = get_output_directory()
|
94 |
+
name = name[:-9]
|
95 |
+
elif name.endswith("[input]"):
|
96 |
+
base_dir = get_input_directory()
|
97 |
+
name = name[:-8]
|
98 |
+
elif name.endswith("[temp]"):
|
99 |
+
base_dir = get_temp_directory()
|
100 |
+
name = name[:-7]
|
101 |
+
else:
|
102 |
+
return name, None
|
103 |
+
|
104 |
+
return name, base_dir
|
105 |
+
|
106 |
+
|
107 |
+
def get_annotated_filepath(name, default_dir=None):
|
108 |
+
name, base_dir = annotated_filepath(name)
|
109 |
+
|
110 |
+
if base_dir is None:
|
111 |
+
if default_dir is not None:
|
112 |
+
base_dir = default_dir
|
113 |
+
else:
|
114 |
+
base_dir = get_input_directory() # fallback path
|
115 |
+
|
116 |
+
return os.path.join(base_dir, name)
|
117 |
+
|
118 |
+
|
119 |
+
def exists_annotated_filepath(name):
|
120 |
+
name, base_dir = annotated_filepath(name)
|
121 |
+
|
122 |
+
if base_dir is None:
|
123 |
+
base_dir = get_input_directory() # fallback path
|
124 |
+
|
125 |
+
filepath = os.path.join(base_dir, name)
|
126 |
+
return os.path.exists(filepath)
|
127 |
+
|
128 |
+
|
129 |
+
def add_model_folder_path(folder_name, full_folder_path):
|
130 |
+
global folder_names_and_paths
|
131 |
+
if folder_name in folder_names_and_paths:
|
132 |
+
folder_names_and_paths[folder_name][0].append(full_folder_path)
|
133 |
+
else:
|
134 |
+
folder_names_and_paths[folder_name] = ([full_folder_path], set())
|
135 |
+
|
136 |
+
def get_folder_paths(folder_name):
|
137 |
+
return folder_names_and_paths[folder_name][0][:]
|
138 |
+
|
139 |
+
def recursive_search(directory, excluded_dir_names=None):
|
140 |
+
if not os.path.isdir(directory):
|
141 |
+
return [], {}
|
142 |
+
|
143 |
+
if excluded_dir_names is None:
|
144 |
+
excluded_dir_names = []
|
145 |
+
|
146 |
+
result = []
|
147 |
+
dirs = {}
|
148 |
+
|
149 |
+
# Attempt to add the initial directory to dirs with error handling
|
150 |
+
try:
|
151 |
+
dirs[directory] = os.path.getmtime(directory)
|
152 |
+
except FileNotFoundError:
|
153 |
+
logging.warning(f"Warning: Unable to access {directory}. Skipping this path.")
|
154 |
+
|
155 |
+
logging.debug("recursive file list on directory {}".format(directory))
|
156 |
+
for dirpath, subdirs, filenames in os.walk(directory, followlinks=True, topdown=True):
|
157 |
+
subdirs[:] = [d for d in subdirs if d not in excluded_dir_names]
|
158 |
+
for file_name in filenames:
|
159 |
+
relative_path = os.path.relpath(os.path.join(dirpath, file_name), directory)
|
160 |
+
result.append(relative_path)
|
161 |
+
|
162 |
+
for d in subdirs:
|
163 |
+
path = os.path.join(dirpath, d)
|
164 |
+
try:
|
165 |
+
dirs[path] = os.path.getmtime(path)
|
166 |
+
except FileNotFoundError:
|
167 |
+
logging.warning(f"Warning: Unable to access {path}. Skipping this path.")
|
168 |
+
continue
|
169 |
+
logging.debug("found {} files".format(len(result)))
|
170 |
+
return result, dirs
|
171 |
+
|
172 |
+
def filter_files_extensions(files, extensions):
|
173 |
+
return sorted(list(filter(lambda a: os.path.splitext(a)[-1].lower() in extensions or len(extensions) == 0, files)))
|
174 |
+
|
175 |
+
|
176 |
+
|
177 |
+
def get_full_path(folder_name, filename):
|
178 |
+
global folder_names_and_paths
|
179 |
+
if folder_name not in folder_names_and_paths:
|
180 |
+
return None
|
181 |
+
folders = folder_names_and_paths[folder_name]
|
182 |
+
filename = os.path.relpath(os.path.join("/", filename), "/")
|
183 |
+
for x in folders[0]:
|
184 |
+
full_path = os.path.join(x, filename)
|
185 |
+
if os.path.isfile(full_path):
|
186 |
+
return full_path
|
187 |
+
elif os.path.islink(full_path):
|
188 |
+
logging.warning("WARNING path {} exists but doesn't link anywhere, skipping.".format(full_path))
|
189 |
+
|
190 |
+
return None
|
191 |
+
|
192 |
+
def get_filename_list_(folder_name):
|
193 |
+
global folder_names_and_paths
|
194 |
+
output_list = set()
|
195 |
+
folders = folder_names_and_paths[folder_name]
|
196 |
+
output_folders = {}
|
197 |
+
for x in folders[0]:
|
198 |
+
files, folders_all = recursive_search(x, excluded_dir_names=[".git"])
|
199 |
+
output_list.update(filter_files_extensions(files, folders[1]))
|
200 |
+
output_folders = {**output_folders, **folders_all}
|
201 |
+
|
202 |
+
return (sorted(list(output_list)), output_folders, time.perf_counter())
|
203 |
+
|
204 |
+
def cached_filename_list_(folder_name):
|
205 |
+
global filename_list_cache
|
206 |
+
global folder_names_and_paths
|
207 |
+
if folder_name not in filename_list_cache:
|
208 |
+
return None
|
209 |
+
out = filename_list_cache[folder_name]
|
210 |
+
|
211 |
+
for x in out[1]:
|
212 |
+
time_modified = out[1][x]
|
213 |
+
folder = x
|
214 |
+
if os.path.getmtime(folder) != time_modified:
|
215 |
+
return None
|
216 |
+
|
217 |
+
folders = folder_names_and_paths[folder_name]
|
218 |
+
for x in folders[0]:
|
219 |
+
if os.path.isdir(x):
|
220 |
+
if x not in out[1]:
|
221 |
+
return None
|
222 |
+
|
223 |
+
return out
|
224 |
+
|
225 |
+
def get_filename_list(folder_name):
|
226 |
+
out = cached_filename_list_(folder_name)
|
227 |
+
if out is None:
|
228 |
+
out = get_filename_list_(folder_name)
|
229 |
+
global filename_list_cache
|
230 |
+
filename_list_cache[folder_name] = out
|
231 |
+
return list(out[0])
|
232 |
+
|
233 |
+
def get_save_image_path(filename_prefix, output_dir, image_width=0, image_height=0):
|
234 |
+
def map_filename(filename):
|
235 |
+
prefix_len = len(os.path.basename(filename_prefix))
|
236 |
+
prefix = filename[:prefix_len + 1]
|
237 |
+
try:
|
238 |
+
digits = int(filename[prefix_len + 1:].split('_')[0])
|
239 |
+
except:
|
240 |
+
digits = 0
|
241 |
+
return (digits, prefix)
|
242 |
+
|
243 |
+
def compute_vars(input, image_width, image_height):
|
244 |
+
input = input.replace("%width%", str(image_width))
|
245 |
+
input = input.replace("%height%", str(image_height))
|
246 |
+
return input
|
247 |
+
|
248 |
+
filename_prefix = compute_vars(filename_prefix, image_width, image_height)
|
249 |
+
|
250 |
+
subfolder = os.path.dirname(os.path.normpath(filename_prefix))
|
251 |
+
filename = os.path.basename(os.path.normpath(filename_prefix))
|
252 |
+
|
253 |
+
full_output_folder = os.path.join(output_dir, subfolder)
|
254 |
+
|
255 |
+
if os.path.commonpath((output_dir, os.path.abspath(full_output_folder))) != output_dir:
|
256 |
+
err = "**** ERROR: Saving image outside the output folder is not allowed." + \
|
257 |
+
"\n full_output_folder: " + os.path.abspath(full_output_folder) + \
|
258 |
+
"\n output_dir: " + output_dir + \
|
259 |
+
"\n commonpath: " + os.path.commonpath((output_dir, os.path.abspath(full_output_folder)))
|
260 |
+
logging.error(err)
|
261 |
+
raise Exception(err)
|
262 |
+
|
263 |
+
try:
|
264 |
+
counter = max(filter(lambda a: os.path.normcase(a[1][:-1]) == os.path.normcase(filename) and a[1][-1] == "_", map(map_filename, os.listdir(full_output_folder))))[0] + 1
|
265 |
+
except ValueError:
|
266 |
+
counter = 1
|
267 |
+
except FileNotFoundError:
|
268 |
+
os.makedirs(full_output_folder, exist_ok=True)
|
269 |
+
counter = 1
|
270 |
+
return full_output_folder, filename, counter, subfolder, filename_prefix
|
ComfyUI/latent_preview.py
ADDED
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from PIL import Image
|
3 |
+
import struct
|
4 |
+
import numpy as np
|
5 |
+
from comfy.cli_args import args, LatentPreviewMethod
|
6 |
+
from comfy.taesd.taesd import TAESD
|
7 |
+
import comfy.model_management
|
8 |
+
import folder_paths
|
9 |
+
import comfy.utils
|
10 |
+
import logging
|
11 |
+
|
12 |
+
MAX_PREVIEW_RESOLUTION = 512
|
13 |
+
|
14 |
+
def preview_to_image(latent_image):
|
15 |
+
latents_ubyte = (((latent_image + 1.0) / 2.0).clamp(0, 1) # change scale from -1..1 to 0..1
|
16 |
+
.mul(0xFF) # to 0..255
|
17 |
+
).to(device="cpu", dtype=torch.uint8, non_blocking=comfy.model_management.device_supports_non_blocking(latent_image.device))
|
18 |
+
|
19 |
+
return Image.fromarray(latents_ubyte.numpy())
|
20 |
+
|
21 |
+
class LatentPreviewer:
|
22 |
+
def decode_latent_to_preview(self, x0):
|
23 |
+
pass
|
24 |
+
|
25 |
+
def decode_latent_to_preview_image(self, preview_format, x0):
|
26 |
+
preview_image = self.decode_latent_to_preview(x0)
|
27 |
+
return ("JPEG", preview_image, MAX_PREVIEW_RESOLUTION)
|
28 |
+
|
29 |
+
class TAESDPreviewerImpl(LatentPreviewer):
|
30 |
+
def __init__(self, taesd):
|
31 |
+
self.taesd = taesd
|
32 |
+
|
33 |
+
def decode_latent_to_preview(self, x0):
|
34 |
+
x_sample = self.taesd.decode(x0[:1])[0].movedim(0, 2)
|
35 |
+
return preview_to_image(x_sample)
|
36 |
+
|
37 |
+
|
38 |
+
class Latent2RGBPreviewer(LatentPreviewer):
|
39 |
+
def __init__(self, latent_rgb_factors):
|
40 |
+
self.latent_rgb_factors = torch.tensor(latent_rgb_factors, device="cpu")
|
41 |
+
|
42 |
+
def decode_latent_to_preview(self, x0):
|
43 |
+
self.latent_rgb_factors = self.latent_rgb_factors.to(dtype=x0.dtype, device=x0.device)
|
44 |
+
latent_image = x0[0].permute(1, 2, 0) @ self.latent_rgb_factors
|
45 |
+
return preview_to_image(latent_image)
|
46 |
+
|
47 |
+
|
48 |
+
def get_previewer(device, latent_format):
|
49 |
+
previewer = None
|
50 |
+
method = args.preview_method
|
51 |
+
if method != LatentPreviewMethod.NoPreviews:
|
52 |
+
# TODO previewer methods
|
53 |
+
taesd_decoder_path = None
|
54 |
+
if latent_format.taesd_decoder_name is not None:
|
55 |
+
taesd_decoder_path = next(
|
56 |
+
(fn for fn in folder_paths.get_filename_list("vae_approx")
|
57 |
+
if fn.startswith(latent_format.taesd_decoder_name)),
|
58 |
+
""
|
59 |
+
)
|
60 |
+
taesd_decoder_path = folder_paths.get_full_path("vae_approx", taesd_decoder_path)
|
61 |
+
|
62 |
+
if method == LatentPreviewMethod.Auto:
|
63 |
+
method = LatentPreviewMethod.Latent2RGB
|
64 |
+
|
65 |
+
if method == LatentPreviewMethod.TAESD:
|
66 |
+
if taesd_decoder_path:
|
67 |
+
taesd = TAESD(None, taesd_decoder_path, latent_channels=latent_format.latent_channels).to(device)
|
68 |
+
previewer = TAESDPreviewerImpl(taesd)
|
69 |
+
else:
|
70 |
+
logging.warning("Warning: TAESD previews enabled, but could not find models/vae_approx/{}".format(latent_format.taesd_decoder_name))
|
71 |
+
|
72 |
+
if previewer is None:
|
73 |
+
if latent_format.latent_rgb_factors is not None:
|
74 |
+
previewer = Latent2RGBPreviewer(latent_format.latent_rgb_factors)
|
75 |
+
return previewer
|
76 |
+
|
77 |
+
def prepare_callback(model, steps, x0_output_dict=None):
|
78 |
+
preview_format = "JPEG"
|
79 |
+
if preview_format not in ["JPEG", "PNG"]:
|
80 |
+
preview_format = "JPEG"
|
81 |
+
|
82 |
+
previewer = get_previewer(model.load_device, model.model.latent_format)
|
83 |
+
|
84 |
+
pbar = comfy.utils.ProgressBar(steps)
|
85 |
+
def callback(step, x0, x, total_steps):
|
86 |
+
if x0_output_dict is not None:
|
87 |
+
x0_output_dict["x0"] = x0
|
88 |
+
|
89 |
+
preview_bytes = None
|
90 |
+
if previewer:
|
91 |
+
preview_bytes = previewer.decode_latent_to_preview_image(preview_format, x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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import comfy.options
|
2 |
+
comfy.options.enable_args_parsing()
|
3 |
+
|
4 |
+
import os
|
5 |
+
import importlib.util
|
6 |
+
import folder_paths
|
7 |
+
import time
|
8 |
+
from comfy.cli_args import args
|
9 |
+
|
10 |
+
|
11 |
+
def execute_prestartup_script():
|
12 |
+
def execute_script(script_path):
|
13 |
+
module_name = os.path.splitext(script_path)[0]
|
14 |
+
try:
|
15 |
+
spec = importlib.util.spec_from_file_location(module_name, script_path)
|
16 |
+
module = importlib.util.module_from_spec(spec)
|
17 |
+
spec.loader.exec_module(module)
|
18 |
+
return True
|
19 |
+
except Exception as e:
|
20 |
+
print(f"Failed to execute startup-script: {script_path} / {e}")
|
21 |
+
return False
|
22 |
+
|
23 |
+
if args.disable_all_custom_nodes:
|
24 |
+
return
|
25 |
+
|
26 |
+
node_paths = folder_paths.get_folder_paths("custom_nodes")
|
27 |
+
for custom_node_path in node_paths:
|
28 |
+
possible_modules = os.listdir(custom_node_path)
|
29 |
+
node_prestartup_times = []
|
30 |
+
|
31 |
+
for possible_module in possible_modules:
|
32 |
+
module_path = os.path.join(custom_node_path, possible_module)
|
33 |
+
if os.path.isfile(module_path) or module_path.endswith(".disabled") or module_path == "__pycache__":
|
34 |
+
continue
|
35 |
+
|
36 |
+
script_path = os.path.join(module_path, "prestartup_script.py")
|
37 |
+
if os.path.exists(script_path):
|
38 |
+
time_before = time.perf_counter()
|
39 |
+
success = execute_script(script_path)
|
40 |
+
node_prestartup_times.append((time.perf_counter() - time_before, module_path, success))
|
41 |
+
if len(node_prestartup_times) > 0:
|
42 |
+
print("\nPrestartup times for custom nodes:")
|
43 |
+
for n in sorted(node_prestartup_times):
|
44 |
+
if n[2]:
|
45 |
+
import_message = ""
|
46 |
+
else:
|
47 |
+
import_message = " (PRESTARTUP FAILED)"
|
48 |
+
print("{:6.1f} seconds{}:".format(n[0], import_message), n[1])
|
49 |
+
print()
|
50 |
+
|
51 |
+
execute_prestartup_script()
|
52 |
+
|
53 |
+
|
54 |
+
# Main code
|
55 |
+
import asyncio
|
56 |
+
import itertools
|
57 |
+
import shutil
|
58 |
+
import threading
|
59 |
+
import gc
|
60 |
+
|
61 |
+
import logging
|
62 |
+
|
63 |
+
if os.name == "nt":
|
64 |
+
logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
|
65 |
+
|
66 |
+
if __name__ == "__main__":
|
67 |
+
if args.cuda_device is not None:
|
68 |
+
os.environ['CUDA_VISIBLE_DEVICES'] = str(args.cuda_device)
|
69 |
+
logging.info("Set cuda device to: {}".format(args.cuda_device))
|
70 |
+
|
71 |
+
if args.deterministic:
|
72 |
+
if 'CUBLAS_WORKSPACE_CONFIG' not in os.environ:
|
73 |
+
os.environ['CUBLAS_WORKSPACE_CONFIG'] = ":4096:8"
|
74 |
+
|
75 |
+
import cuda_malloc
|
76 |
+
|
77 |
+
if args.windows_standalone_build:
|
78 |
+
try:
|
79 |
+
import fix_torch
|
80 |
+
except:
|
81 |
+
pass
|
82 |
+
|
83 |
+
import comfy.utils
|
84 |
+
import yaml
|
85 |
+
|
86 |
+
import execution
|
87 |
+
import server
|
88 |
+
from server import BinaryEventTypes
|
89 |
+
import nodes
|
90 |
+
import comfy.model_management
|
91 |
+
|
92 |
+
def cuda_malloc_warning():
|
93 |
+
device = comfy.model_management.get_torch_device()
|
94 |
+
device_name = comfy.model_management.get_torch_device_name(device)
|
95 |
+
cuda_malloc_warning = False
|
96 |
+
if "cudaMallocAsync" in device_name:
|
97 |
+
for b in cuda_malloc.blacklist:
|
98 |
+
if b in device_name:
|
99 |
+
cuda_malloc_warning = True
|
100 |
+
if cuda_malloc_warning:
|
101 |
+
logging.warning("\nWARNING: this card most likely does not support cuda-malloc, if you get \"CUDA error\" please run ComfyUI with: --disable-cuda-malloc\n")
|
102 |
+
|
103 |
+
def prompt_worker(q, server):
|
104 |
+
e = execution.PromptExecutor(server)
|
105 |
+
last_gc_collect = 0
|
106 |
+
need_gc = False
|
107 |
+
gc_collect_interval = 10.0
|
108 |
+
|
109 |
+
while True:
|
110 |
+
timeout = 1000.0
|
111 |
+
if need_gc:
|
112 |
+
timeout = max(gc_collect_interval - (current_time - last_gc_collect), 0.0)
|
113 |
+
|
114 |
+
queue_item = q.get(timeout=timeout)
|
115 |
+
if queue_item is not None:
|
116 |
+
item, item_id = queue_item
|
117 |
+
execution_start_time = time.perf_counter()
|
118 |
+
prompt_id = item[1]
|
119 |
+
server.last_prompt_id = prompt_id
|
120 |
+
|
121 |
+
e.execute(item[2], prompt_id, item[3], item[4])
|
122 |
+
need_gc = True
|
123 |
+
q.task_done(item_id,
|
124 |
+
e.outputs_ui,
|
125 |
+
status=execution.PromptQueue.ExecutionStatus(
|
126 |
+
status_str='success' if e.success else 'error',
|
127 |
+
completed=e.success,
|
128 |
+
messages=e.status_messages))
|
129 |
+
if server.client_id is not None:
|
130 |
+
server.send_sync("executing", { "node": None, "prompt_id": prompt_id }, server.client_id)
|
131 |
+
|
132 |
+
current_time = time.perf_counter()
|
133 |
+
execution_time = current_time - execution_start_time
|
134 |
+
logging.info("Prompt executed in {:.2f} seconds".format(execution_time))
|
135 |
+
|
136 |
+
flags = q.get_flags()
|
137 |
+
free_memory = flags.get("free_memory", False)
|
138 |
+
|
139 |
+
if flags.get("unload_models", free_memory):
|
140 |
+
comfy.model_management.unload_all_models()
|
141 |
+
need_gc = True
|
142 |
+
last_gc_collect = 0
|
143 |
+
|
144 |
+
if free_memory:
|
145 |
+
e.reset()
|
146 |
+
need_gc = True
|
147 |
+
last_gc_collect = 0
|
148 |
+
|
149 |
+
if need_gc:
|
150 |
+
current_time = time.perf_counter()
|
151 |
+
if (current_time - last_gc_collect) > gc_collect_interval:
|
152 |
+
comfy.model_management.cleanup_models()
|
153 |
+
gc.collect()
|
154 |
+
comfy.model_management.soft_empty_cache()
|
155 |
+
last_gc_collect = current_time
|
156 |
+
need_gc = False
|
157 |
+
|
158 |
+
async def run(server, address='', port=8188, verbose=True, call_on_start=None):
|
159 |
+
await asyncio.gather(server.start(address, port, verbose, call_on_start), server.publish_loop())
|
160 |
+
|
161 |
+
|
162 |
+
def hijack_progress(server):
|
163 |
+
def hook(value, total, preview_image):
|
164 |
+
comfy.model_management.throw_exception_if_processing_interrupted()
|
165 |
+
progress = {"value": value, "max": total, "prompt_id": server.last_prompt_id, "node": server.last_node_id}
|
166 |
+
|
167 |
+
server.send_sync("progress", progress, server.client_id)
|
168 |
+
if preview_image is not None:
|
169 |
+
server.send_sync(BinaryEventTypes.UNENCODED_PREVIEW_IMAGE, preview_image, server.client_id)
|
170 |
+
comfy.utils.set_progress_bar_global_hook(hook)
|
171 |
+
|
172 |
+
|
173 |
+
def cleanup_temp():
|
174 |
+
temp_dir = folder_paths.get_temp_directory()
|
175 |
+
if os.path.exists(temp_dir):
|
176 |
+
shutil.rmtree(temp_dir, ignore_errors=True)
|
177 |
+
|
178 |
+
|
179 |
+
def load_extra_path_config(yaml_path):
|
180 |
+
with open(yaml_path, 'r') as stream:
|
181 |
+
config = yaml.safe_load(stream)
|
182 |
+
for c in config:
|
183 |
+
conf = config[c]
|
184 |
+
if conf is None:
|
185 |
+
continue
|
186 |
+
base_path = None
|
187 |
+
if "base_path" in conf:
|
188 |
+
base_path = conf.pop("base_path")
|
189 |
+
for x in conf:
|
190 |
+
for y in conf[x].split("\n"):
|
191 |
+
if len(y) == 0:
|
192 |
+
continue
|
193 |
+
full_path = y
|
194 |
+
if base_path is not None:
|
195 |
+
full_path = os.path.join(base_path, full_path)
|
196 |
+
logging.info("Adding extra search path {} {}".format(x, full_path))
|
197 |
+
folder_paths.add_model_folder_path(x, full_path)
|
198 |
+
|
199 |
+
|
200 |
+
if __name__ == "__main__":
|
201 |
+
if args.temp_directory:
|
202 |
+
temp_dir = os.path.join(os.path.abspath(args.temp_directory), "temp")
|
203 |
+
logging.info(f"Setting temp directory to: {temp_dir}")
|
204 |
+
folder_paths.set_temp_directory(temp_dir)
|
205 |
+
cleanup_temp()
|
206 |
+
|
207 |
+
if args.windows_standalone_build:
|
208 |
+
try:
|
209 |
+
import new_updater
|
210 |
+
new_updater.update_windows_updater()
|
211 |
+
except:
|
212 |
+
pass
|
213 |
+
|
214 |
+
loop = asyncio.new_event_loop()
|
215 |
+
asyncio.set_event_loop(loop)
|
216 |
+
server = server.PromptServer(loop)
|
217 |
+
q = execution.PromptQueue(server)
|
218 |
+
|
219 |
+
extra_model_paths_config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "extra_model_paths.yaml")
|
220 |
+
if os.path.isfile(extra_model_paths_config_path):
|
221 |
+
load_extra_path_config(extra_model_paths_config_path)
|
222 |
+
|
223 |
+
if args.extra_model_paths_config:
|
224 |
+
for config_path in itertools.chain(*args.extra_model_paths_config):
|
225 |
+
load_extra_path_config(config_path)
|
226 |
+
|
227 |
+
nodes.init_extra_nodes(init_custom_nodes=not args.disable_all_custom_nodes)
|
228 |
+
|
229 |
+
cuda_malloc_warning()
|
230 |
+
|
231 |
+
server.add_routes()
|
232 |
+
hijack_progress(server)
|
233 |
+
|
234 |
+
threading.Thread(target=prompt_worker, daemon=True, args=(q, server,)).start()
|
235 |
+
|
236 |
+
if args.output_directory:
|
237 |
+
output_dir = os.path.abspath(args.output_directory)
|
238 |
+
logging.info(f"Setting output directory to: {output_dir}")
|
239 |
+
folder_paths.set_output_directory(output_dir)
|
240 |
+
|
241 |
+
#These are the default folders that checkpoints, clip and vae models will be saved to when using CheckpointSave, etc.. nodes
|
242 |
+
folder_paths.add_model_folder_path("checkpoints", os.path.join(folder_paths.get_output_directory(), "checkpoints"))
|
243 |
+
folder_paths.add_model_folder_path("clip", os.path.join(folder_paths.get_output_directory(), "clip"))
|
244 |
+
folder_paths.add_model_folder_path("vae", os.path.join(folder_paths.get_output_directory(), "vae"))
|
245 |
+
|
246 |
+
if args.input_directory:
|
247 |
+
input_dir = os.path.abspath(args.input_directory)
|
248 |
+
logging.info(f"Setting input directory to: {input_dir}")
|
249 |
+
folder_paths.set_input_directory(input_dir)
|
250 |
+
|
251 |
+
if args.quick_test_for_ci:
|
252 |
+
exit(0)
|
253 |
+
|
254 |
+
call_on_start = None
|
255 |
+
if args.auto_launch:
|
256 |
+
def startup_server(scheme, address, port):
|
257 |
+
import webbrowser
|
258 |
+
if os.name == 'nt' and address == '0.0.0.0':
|
259 |
+
address = '127.0.0.1'
|
260 |
+
webbrowser.open(f"{scheme}://{address}:{port}")
|
261 |
+
call_on_start = startup_server
|
262 |
+
|
263 |
+
try:
|
264 |
+
loop.run_until_complete(run(server, address=args.listen, port=args.port, verbose=not args.dont_print_server, call_on_start=call_on_start))
|
265 |
+
except KeyboardInterrupt:
|
266 |
+
logging.info("\nStopped server")
|
267 |
+
|
268 |
+
cleanup_temp()
|
ComfyUI/new_updater.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import shutil
|
3 |
+
|
4 |
+
base_path = os.path.dirname(os.path.realpath(__file__))
|
5 |
+
|
6 |
+
|
7 |
+
def update_windows_updater():
|
8 |
+
top_path = os.path.dirname(base_path)
|
9 |
+
updater_path = os.path.join(base_path, ".ci/update_windows/update.py")
|
10 |
+
bat_path = os.path.join(base_path, ".ci/update_windows/update_comfyui.bat")
|
11 |
+
|
12 |
+
dest_updater_path = os.path.join(top_path, "update/update.py")
|
13 |
+
dest_bat_path = os.path.join(top_path, "update/update_comfyui.bat")
|
14 |
+
dest_bat_deps_path = os.path.join(top_path, "update/update_comfyui_and_python_dependencies.bat")
|
15 |
+
|
16 |
+
try:
|
17 |
+
with open(dest_bat_path, 'rb') as f:
|
18 |
+
contents = f.read()
|
19 |
+
except:
|
20 |
+
return
|
21 |
+
|
22 |
+
if not contents.startswith(b"..\\python_embeded\\python.exe .\\update.py"):
|
23 |
+
return
|
24 |
+
|
25 |
+
shutil.copy(updater_path, dest_updater_path)
|
26 |
+
try:
|
27 |
+
with open(dest_bat_deps_path, 'rb') as f:
|
28 |
+
contents = f.read()
|
29 |
+
contents = contents.replace(b'..\\python_embeded\\python.exe .\\update.py ..\\ComfyUI\\', b'call update_comfyui.bat nopause')
|
30 |
+
with open(dest_bat_deps_path, 'wb') as f:
|
31 |
+
f.write(contents)
|
32 |
+
except:
|
33 |
+
pass
|
34 |
+
shutil.copy(bat_path, dest_bat_path)
|
35 |
+
print("Updated the windows standalone package updater.")
|
ComfyUI/node_helpers.py
ADDED
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import hashlib
|
2 |
+
|
3 |
+
from comfy.cli_args import args
|
4 |
+
|
5 |
+
from PIL import ImageFile, UnidentifiedImageError
|
6 |
+
|
7 |
+
def conditioning_set_values(conditioning, values={}):
|
8 |
+
c = []
|
9 |
+
for t in conditioning:
|
10 |
+
n = [t[0], t[1].copy()]
|
11 |
+
for k in values:
|
12 |
+
n[1][k] = values[k]
|
13 |
+
c.append(n)
|
14 |
+
|
15 |
+
return c
|
16 |
+
|
17 |
+
def pillow(fn, arg):
|
18 |
+
prev_value = None
|
19 |
+
try:
|
20 |
+
x = fn(arg)
|
21 |
+
except (OSError, UnidentifiedImageError, ValueError): #PIL issues #4472 and #2445, also fixes ComfyUI issue #3416
|
22 |
+
prev_value = ImageFile.LOAD_TRUNCATED_IMAGES
|
23 |
+
ImageFile.LOAD_TRUNCATED_IMAGES = True
|
24 |
+
x = fn(arg)
|
25 |
+
finally:
|
26 |
+
if prev_value is not None:
|
27 |
+
ImageFile.LOAD_TRUNCATED_IMAGES = prev_value
|
28 |
+
return x
|
29 |
+
|
30 |
+
def hasher():
|
31 |
+
hashfuncs = {
|
32 |
+
"md5": hashlib.md5,
|
33 |
+
"sha1": hashlib.sha1,
|
34 |
+
"sha256": hashlib.sha256,
|
35 |
+
"sha512": hashlib.sha512
|
36 |
+
}
|
37 |
+
return hashfuncs[args.default_hashing_function]
|
ComfyUI/nodes.py
ADDED
@@ -0,0 +1,2068 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
|
3 |
+
import os
|
4 |
+
import sys
|
5 |
+
import json
|
6 |
+
import hashlib
|
7 |
+
import traceback
|
8 |
+
import math
|
9 |
+
import time
|
10 |
+
import random
|
11 |
+
import logging
|
12 |
+
|
13 |
+
from PIL import Image, ImageOps, ImageSequence, ImageFile
|
14 |
+
from PIL.PngImagePlugin import PngInfo
|
15 |
+
|
16 |
+
import numpy as np
|
17 |
+
import safetensors.torch
|
18 |
+
|
19 |
+
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy"))
|
20 |
+
|
21 |
+
import comfy.diffusers_load
|
22 |
+
import comfy.samplers
|
23 |
+
import comfy.sample
|
24 |
+
import comfy.sd
|
25 |
+
import comfy.utils
|
26 |
+
import comfy.controlnet
|
27 |
+
|
28 |
+
import comfy.clip_vision
|
29 |
+
|
30 |
+
import comfy.model_management
|
31 |
+
from comfy.cli_args import args
|
32 |
+
|
33 |
+
import importlib
|
34 |
+
|
35 |
+
import folder_paths
|
36 |
+
import latent_preview
|
37 |
+
import node_helpers
|
38 |
+
|
39 |
+
def before_node_execution():
|
40 |
+
comfy.model_management.throw_exception_if_processing_interrupted()
|
41 |
+
|
42 |
+
def interrupt_processing(value=True):
|
43 |
+
comfy.model_management.interrupt_current_processing(value)
|
44 |
+
|
45 |
+
MAX_RESOLUTION=16384
|
46 |
+
|
47 |
+
class CLIPTextEncode:
|
48 |
+
@classmethod
|
49 |
+
def INPUT_TYPES(s):
|
50 |
+
return {"required": {"text": ("STRING", {"multiline": True, "dynamicPrompts": True}), "clip": ("CLIP", )}}
|
51 |
+
RETURN_TYPES = ("CONDITIONING",)
|
52 |
+
FUNCTION = "encode"
|
53 |
+
|
54 |
+
CATEGORY = "conditioning"
|
55 |
+
|
56 |
+
def encode(self, clip, text):
|
57 |
+
tokens = clip.tokenize(text)
|
58 |
+
output = clip.encode_from_tokens(tokens, return_pooled=True, return_dict=True)
|
59 |
+
cond = output.pop("cond")
|
60 |
+
return ([[cond, output]], )
|
61 |
+
|
62 |
+
class ConditioningCombine:
|
63 |
+
@classmethod
|
64 |
+
def INPUT_TYPES(s):
|
65 |
+
return {"required": {"conditioning_1": ("CONDITIONING", ), "conditioning_2": ("CONDITIONING", )}}
|
66 |
+
RETURN_TYPES = ("CONDITIONING",)
|
67 |
+
FUNCTION = "combine"
|
68 |
+
|
69 |
+
CATEGORY = "conditioning"
|
70 |
+
|
71 |
+
def combine(self, conditioning_1, conditioning_2):
|
72 |
+
return (conditioning_1 + conditioning_2, )
|
73 |
+
|
74 |
+
class ConditioningAverage :
|
75 |
+
@classmethod
|
76 |
+
def INPUT_TYPES(s):
|
77 |
+
return {"required": {"conditioning_to": ("CONDITIONING", ), "conditioning_from": ("CONDITIONING", ),
|
78 |
+
"conditioning_to_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01})
|
79 |
+
}}
|
80 |
+
RETURN_TYPES = ("CONDITIONING",)
|
81 |
+
FUNCTION = "addWeighted"
|
82 |
+
|
83 |
+
CATEGORY = "conditioning"
|
84 |
+
|
85 |
+
def addWeighted(self, conditioning_to, conditioning_from, conditioning_to_strength):
|
86 |
+
out = []
|
87 |
+
|
88 |
+
if len(conditioning_from) > 1:
|
89 |
+
logging.warning("Warning: ConditioningAverage conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.")
|
90 |
+
|
91 |
+
cond_from = conditioning_from[0][0]
|
92 |
+
pooled_output_from = conditioning_from[0][1].get("pooled_output", None)
|
93 |
+
|
94 |
+
for i in range(len(conditioning_to)):
|
95 |
+
t1 = conditioning_to[i][0]
|
96 |
+
pooled_output_to = conditioning_to[i][1].get("pooled_output", pooled_output_from)
|
97 |
+
t0 = cond_from[:,:t1.shape[1]]
|
98 |
+
if t0.shape[1] < t1.shape[1]:
|
99 |
+
t0 = torch.cat([t0] + [torch.zeros((1, (t1.shape[1] - t0.shape[1]), t1.shape[2]))], dim=1)
|
100 |
+
|
101 |
+
tw = torch.mul(t1, conditioning_to_strength) + torch.mul(t0, (1.0 - conditioning_to_strength))
|
102 |
+
t_to = conditioning_to[i][1].copy()
|
103 |
+
if pooled_output_from is not None and pooled_output_to is not None:
|
104 |
+
t_to["pooled_output"] = torch.mul(pooled_output_to, conditioning_to_strength) + torch.mul(pooled_output_from, (1.0 - conditioning_to_strength))
|
105 |
+
elif pooled_output_from is not None:
|
106 |
+
t_to["pooled_output"] = pooled_output_from
|
107 |
+
|
108 |
+
n = [tw, t_to]
|
109 |
+
out.append(n)
|
110 |
+
return (out, )
|
111 |
+
|
112 |
+
class ConditioningConcat:
|
113 |
+
@classmethod
|
114 |
+
def INPUT_TYPES(s):
|
115 |
+
return {"required": {
|
116 |
+
"conditioning_to": ("CONDITIONING",),
|
117 |
+
"conditioning_from": ("CONDITIONING",),
|
118 |
+
}}
|
119 |
+
RETURN_TYPES = ("CONDITIONING",)
|
120 |
+
FUNCTION = "concat"
|
121 |
+
|
122 |
+
CATEGORY = "conditioning"
|
123 |
+
|
124 |
+
def concat(self, conditioning_to, conditioning_from):
|
125 |
+
out = []
|
126 |
+
|
127 |
+
if len(conditioning_from) > 1:
|
128 |
+
logging.warning("Warning: ConditioningConcat conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.")
|
129 |
+
|
130 |
+
cond_from = conditioning_from[0][0]
|
131 |
+
|
132 |
+
for i in range(len(conditioning_to)):
|
133 |
+
t1 = conditioning_to[i][0]
|
134 |
+
tw = torch.cat((t1, cond_from),1)
|
135 |
+
n = [tw, conditioning_to[i][1].copy()]
|
136 |
+
out.append(n)
|
137 |
+
|
138 |
+
return (out, )
|
139 |
+
|
140 |
+
class ConditioningSetArea:
|
141 |
+
@classmethod
|
142 |
+
def INPUT_TYPES(s):
|
143 |
+
return {"required": {"conditioning": ("CONDITIONING", ),
|
144 |
+
"width": ("INT", {"default": 64, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
|
145 |
+
"height": ("INT", {"default": 64, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
|
146 |
+
"x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
147 |
+
"y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
148 |
+
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
|
149 |
+
}}
|
150 |
+
RETURN_TYPES = ("CONDITIONING",)
|
151 |
+
FUNCTION = "append"
|
152 |
+
|
153 |
+
CATEGORY = "conditioning"
|
154 |
+
|
155 |
+
def append(self, conditioning, width, height, x, y, strength):
|
156 |
+
c = node_helpers.conditioning_set_values(conditioning, {"area": (height // 8, width // 8, y // 8, x // 8),
|
157 |
+
"strength": strength,
|
158 |
+
"set_area_to_bounds": False})
|
159 |
+
return (c, )
|
160 |
+
|
161 |
+
class ConditioningSetAreaPercentage:
|
162 |
+
@classmethod
|
163 |
+
def INPUT_TYPES(s):
|
164 |
+
return {"required": {"conditioning": ("CONDITIONING", ),
|
165 |
+
"width": ("FLOAT", {"default": 1.0, "min": 0, "max": 1.0, "step": 0.01}),
|
166 |
+
"height": ("FLOAT", {"default": 1.0, "min": 0, "max": 1.0, "step": 0.01}),
|
167 |
+
"x": ("FLOAT", {"default": 0, "min": 0, "max": 1.0, "step": 0.01}),
|
168 |
+
"y": ("FLOAT", {"default": 0, "min": 0, "max": 1.0, "step": 0.01}),
|
169 |
+
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
|
170 |
+
}}
|
171 |
+
RETURN_TYPES = ("CONDITIONING",)
|
172 |
+
FUNCTION = "append"
|
173 |
+
|
174 |
+
CATEGORY = "conditioning"
|
175 |
+
|
176 |
+
def append(self, conditioning, width, height, x, y, strength):
|
177 |
+
c = node_helpers.conditioning_set_values(conditioning, {"area": ("percentage", height, width, y, x),
|
178 |
+
"strength": strength,
|
179 |
+
"set_area_to_bounds": False})
|
180 |
+
return (c, )
|
181 |
+
|
182 |
+
class ConditioningSetAreaStrength:
|
183 |
+
@classmethod
|
184 |
+
def INPUT_TYPES(s):
|
185 |
+
return {"required": {"conditioning": ("CONDITIONING", ),
|
186 |
+
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
|
187 |
+
}}
|
188 |
+
RETURN_TYPES = ("CONDITIONING",)
|
189 |
+
FUNCTION = "append"
|
190 |
+
|
191 |
+
CATEGORY = "conditioning"
|
192 |
+
|
193 |
+
def append(self, conditioning, strength):
|
194 |
+
c = node_helpers.conditioning_set_values(conditioning, {"strength": strength})
|
195 |
+
return (c, )
|
196 |
+
|
197 |
+
|
198 |
+
class ConditioningSetMask:
|
199 |
+
@classmethod
|
200 |
+
def INPUT_TYPES(s):
|
201 |
+
return {"required": {"conditioning": ("CONDITIONING", ),
|
202 |
+
"mask": ("MASK", ),
|
203 |
+
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
|
204 |
+
"set_cond_area": (["default", "mask bounds"],),
|
205 |
+
}}
|
206 |
+
RETURN_TYPES = ("CONDITIONING",)
|
207 |
+
FUNCTION = "append"
|
208 |
+
|
209 |
+
CATEGORY = "conditioning"
|
210 |
+
|
211 |
+
def append(self, conditioning, mask, set_cond_area, strength):
|
212 |
+
set_area_to_bounds = False
|
213 |
+
if set_cond_area != "default":
|
214 |
+
set_area_to_bounds = True
|
215 |
+
if len(mask.shape) < 3:
|
216 |
+
mask = mask.unsqueeze(0)
|
217 |
+
|
218 |
+
c = node_helpers.conditioning_set_values(conditioning, {"mask": mask,
|
219 |
+
"set_area_to_bounds": set_area_to_bounds,
|
220 |
+
"mask_strength": strength})
|
221 |
+
return (c, )
|
222 |
+
|
223 |
+
class ConditioningZeroOut:
|
224 |
+
@classmethod
|
225 |
+
def INPUT_TYPES(s):
|
226 |
+
return {"required": {"conditioning": ("CONDITIONING", )}}
|
227 |
+
RETURN_TYPES = ("CONDITIONING",)
|
228 |
+
FUNCTION = "zero_out"
|
229 |
+
|
230 |
+
CATEGORY = "advanced/conditioning"
|
231 |
+
|
232 |
+
def zero_out(self, conditioning):
|
233 |
+
c = []
|
234 |
+
for t in conditioning:
|
235 |
+
d = t[1].copy()
|
236 |
+
pooled_output = d.get("pooled_output", None)
|
237 |
+
if pooled_output is not None:
|
238 |
+
d["pooled_output"] = torch.zeros_like(pooled_output)
|
239 |
+
n = [torch.zeros_like(t[0]), d]
|
240 |
+
c.append(n)
|
241 |
+
return (c, )
|
242 |
+
|
243 |
+
class ConditioningSetTimestepRange:
|
244 |
+
@classmethod
|
245 |
+
def INPUT_TYPES(s):
|
246 |
+
return {"required": {"conditioning": ("CONDITIONING", ),
|
247 |
+
"start": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
|
248 |
+
"end": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
|
249 |
+
}}
|
250 |
+
RETURN_TYPES = ("CONDITIONING",)
|
251 |
+
FUNCTION = "set_range"
|
252 |
+
|
253 |
+
CATEGORY = "advanced/conditioning"
|
254 |
+
|
255 |
+
def set_range(self, conditioning, start, end):
|
256 |
+
c = node_helpers.conditioning_set_values(conditioning, {"start_percent": start,
|
257 |
+
"end_percent": end})
|
258 |
+
return (c, )
|
259 |
+
|
260 |
+
class VAEDecode:
|
261 |
+
@classmethod
|
262 |
+
def INPUT_TYPES(s):
|
263 |
+
return {"required": { "samples": ("LATENT", ), "vae": ("VAE", )}}
|
264 |
+
RETURN_TYPES = ("IMAGE",)
|
265 |
+
FUNCTION = "decode"
|
266 |
+
|
267 |
+
CATEGORY = "latent"
|
268 |
+
|
269 |
+
def decode(self, vae, samples):
|
270 |
+
return (vae.decode(samples["samples"]), )
|
271 |
+
|
272 |
+
class VAEDecodeTiled:
|
273 |
+
@classmethod
|
274 |
+
def INPUT_TYPES(s):
|
275 |
+
return {"required": {"samples": ("LATENT", ), "vae": ("VAE", ),
|
276 |
+
"tile_size": ("INT", {"default": 512, "min": 320, "max": 4096, "step": 64})
|
277 |
+
}}
|
278 |
+
RETURN_TYPES = ("IMAGE",)
|
279 |
+
FUNCTION = "decode"
|
280 |
+
|
281 |
+
CATEGORY = "_for_testing"
|
282 |
+
|
283 |
+
def decode(self, vae, samples, tile_size):
|
284 |
+
return (vae.decode_tiled(samples["samples"], tile_x=tile_size // 8, tile_y=tile_size // 8, ), )
|
285 |
+
|
286 |
+
class VAEEncode:
|
287 |
+
@classmethod
|
288 |
+
def INPUT_TYPES(s):
|
289 |
+
return {"required": { "pixels": ("IMAGE", ), "vae": ("VAE", )}}
|
290 |
+
RETURN_TYPES = ("LATENT",)
|
291 |
+
FUNCTION = "encode"
|
292 |
+
|
293 |
+
CATEGORY = "latent"
|
294 |
+
|
295 |
+
def encode(self, vae, pixels):
|
296 |
+
t = vae.encode(pixels[:,:,:,:3])
|
297 |
+
return ({"samples":t}, )
|
298 |
+
|
299 |
+
class VAEEncodeTiled:
|
300 |
+
@classmethod
|
301 |
+
def INPUT_TYPES(s):
|
302 |
+
return {"required": {"pixels": ("IMAGE", ), "vae": ("VAE", ),
|
303 |
+
"tile_size": ("INT", {"default": 512, "min": 320, "max": 4096, "step": 64})
|
304 |
+
}}
|
305 |
+
RETURN_TYPES = ("LATENT",)
|
306 |
+
FUNCTION = "encode"
|
307 |
+
|
308 |
+
CATEGORY = "_for_testing"
|
309 |
+
|
310 |
+
def encode(self, vae, pixels, tile_size):
|
311 |
+
t = vae.encode_tiled(pixels[:,:,:,:3], tile_x=tile_size, tile_y=tile_size, )
|
312 |
+
return ({"samples":t}, )
|
313 |
+
|
314 |
+
class VAEEncodeForInpaint:
|
315 |
+
@classmethod
|
316 |
+
def INPUT_TYPES(s):
|
317 |
+
return {"required": { "pixels": ("IMAGE", ), "vae": ("VAE", ), "mask": ("MASK", ), "grow_mask_by": ("INT", {"default": 6, "min": 0, "max": 64, "step": 1}),}}
|
318 |
+
RETURN_TYPES = ("LATENT",)
|
319 |
+
FUNCTION = "encode"
|
320 |
+
|
321 |
+
CATEGORY = "latent/inpaint"
|
322 |
+
|
323 |
+
def encode(self, vae, pixels, mask, grow_mask_by=6):
|
324 |
+
x = (pixels.shape[1] // vae.downscale_ratio) * vae.downscale_ratio
|
325 |
+
y = (pixels.shape[2] // vae.downscale_ratio) * vae.downscale_ratio
|
326 |
+
mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(pixels.shape[1], pixels.shape[2]), mode="bilinear")
|
327 |
+
|
328 |
+
pixels = pixels.clone()
|
329 |
+
if pixels.shape[1] != x or pixels.shape[2] != y:
|
330 |
+
x_offset = (pixels.shape[1] % vae.downscale_ratio) // 2
|
331 |
+
y_offset = (pixels.shape[2] % vae.downscale_ratio) // 2
|
332 |
+
pixels = pixels[:,x_offset:x + x_offset, y_offset:y + y_offset,:]
|
333 |
+
mask = mask[:,:,x_offset:x + x_offset, y_offset:y + y_offset]
|
334 |
+
|
335 |
+
#grow mask by a few pixels to keep things seamless in latent space
|
336 |
+
if grow_mask_by == 0:
|
337 |
+
mask_erosion = mask
|
338 |
+
else:
|
339 |
+
kernel_tensor = torch.ones((1, 1, grow_mask_by, grow_mask_by))
|
340 |
+
padding = math.ceil((grow_mask_by - 1) / 2)
|
341 |
+
|
342 |
+
mask_erosion = torch.clamp(torch.nn.functional.conv2d(mask.round(), kernel_tensor, padding=padding), 0, 1)
|
343 |
+
|
344 |
+
m = (1.0 - mask.round()).squeeze(1)
|
345 |
+
for i in range(3):
|
346 |
+
pixels[:,:,:,i] -= 0.5
|
347 |
+
pixels[:,:,:,i] *= m
|
348 |
+
pixels[:,:,:,i] += 0.5
|
349 |
+
t = vae.encode(pixels)
|
350 |
+
|
351 |
+
return ({"samples":t, "noise_mask": (mask_erosion[:,:,:x,:y].round())}, )
|
352 |
+
|
353 |
+
|
354 |
+
class InpaintModelConditioning:
|
355 |
+
@classmethod
|
356 |
+
def INPUT_TYPES(s):
|
357 |
+
return {"required": {"positive": ("CONDITIONING", ),
|
358 |
+
"negative": ("CONDITIONING", ),
|
359 |
+
"vae": ("VAE", ),
|
360 |
+
"pixels": ("IMAGE", ),
|
361 |
+
"mask": ("MASK", ),
|
362 |
+
}}
|
363 |
+
|
364 |
+
RETURN_TYPES = ("CONDITIONING","CONDITIONING","LATENT")
|
365 |
+
RETURN_NAMES = ("positive", "negative", "latent")
|
366 |
+
FUNCTION = "encode"
|
367 |
+
|
368 |
+
CATEGORY = "conditioning/inpaint"
|
369 |
+
|
370 |
+
def encode(self, positive, negative, pixels, vae, mask):
|
371 |
+
x = (pixels.shape[1] // 8) * 8
|
372 |
+
y = (pixels.shape[2] // 8) * 8
|
373 |
+
mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(pixels.shape[1], pixels.shape[2]), mode="bilinear")
|
374 |
+
|
375 |
+
orig_pixels = pixels
|
376 |
+
pixels = orig_pixels.clone()
|
377 |
+
if pixels.shape[1] != x or pixels.shape[2] != y:
|
378 |
+
x_offset = (pixels.shape[1] % 8) // 2
|
379 |
+
y_offset = (pixels.shape[2] % 8) // 2
|
380 |
+
pixels = pixels[:,x_offset:x + x_offset, y_offset:y + y_offset,:]
|
381 |
+
mask = mask[:,:,x_offset:x + x_offset, y_offset:y + y_offset]
|
382 |
+
|
383 |
+
m = (1.0 - mask.round()).squeeze(1)
|
384 |
+
for i in range(3):
|
385 |
+
pixels[:,:,:,i] -= 0.5
|
386 |
+
pixels[:,:,:,i] *= m
|
387 |
+
pixels[:,:,:,i] += 0.5
|
388 |
+
concat_latent = vae.encode(pixels)
|
389 |
+
orig_latent = vae.encode(orig_pixels)
|
390 |
+
|
391 |
+
out_latent = {}
|
392 |
+
|
393 |
+
out_latent["samples"] = orig_latent
|
394 |
+
out_latent["noise_mask"] = mask
|
395 |
+
|
396 |
+
out = []
|
397 |
+
for conditioning in [positive, negative]:
|
398 |
+
c = node_helpers.conditioning_set_values(conditioning, {"concat_latent_image": concat_latent,
|
399 |
+
"concat_mask": mask})
|
400 |
+
out.append(c)
|
401 |
+
return (out[0], out[1], out_latent)
|
402 |
+
|
403 |
+
|
404 |
+
class SaveLatent:
|
405 |
+
def __init__(self):
|
406 |
+
self.output_dir = folder_paths.get_output_directory()
|
407 |
+
|
408 |
+
@classmethod
|
409 |
+
def INPUT_TYPES(s):
|
410 |
+
return {"required": { "samples": ("LATENT", ),
|
411 |
+
"filename_prefix": ("STRING", {"default": "latents/ComfyUI"})},
|
412 |
+
"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
|
413 |
+
}
|
414 |
+
RETURN_TYPES = ()
|
415 |
+
FUNCTION = "save"
|
416 |
+
|
417 |
+
OUTPUT_NODE = True
|
418 |
+
|
419 |
+
CATEGORY = "_for_testing"
|
420 |
+
|
421 |
+
def save(self, samples, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None):
|
422 |
+
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir)
|
423 |
+
|
424 |
+
# support save metadata for latent sharing
|
425 |
+
prompt_info = ""
|
426 |
+
if prompt is not None:
|
427 |
+
prompt_info = json.dumps(prompt)
|
428 |
+
|
429 |
+
metadata = None
|
430 |
+
if not args.disable_metadata:
|
431 |
+
metadata = {"prompt": prompt_info}
|
432 |
+
if extra_pnginfo is not None:
|
433 |
+
for x in extra_pnginfo:
|
434 |
+
metadata[x] = json.dumps(extra_pnginfo[x])
|
435 |
+
|
436 |
+
file = f"{filename}_{counter:05}_.latent"
|
437 |
+
|
438 |
+
results = list()
|
439 |
+
results.append({
|
440 |
+
"filename": file,
|
441 |
+
"subfolder": subfolder,
|
442 |
+
"type": "output"
|
443 |
+
})
|
444 |
+
|
445 |
+
file = os.path.join(full_output_folder, file)
|
446 |
+
|
447 |
+
output = {}
|
448 |
+
output["latent_tensor"] = samples["samples"]
|
449 |
+
output["latent_format_version_0"] = torch.tensor([])
|
450 |
+
|
451 |
+
comfy.utils.save_torch_file(output, file, metadata=metadata)
|
452 |
+
return { "ui": { "latents": results } }
|
453 |
+
|
454 |
+
|
455 |
+
class LoadLatent:
|
456 |
+
@classmethod
|
457 |
+
def INPUT_TYPES(s):
|
458 |
+
input_dir = folder_paths.get_input_directory()
|
459 |
+
files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f)) and f.endswith(".latent")]
|
460 |
+
return {"required": {"latent": [sorted(files), ]}, }
|
461 |
+
|
462 |
+
CATEGORY = "_for_testing"
|
463 |
+
|
464 |
+
RETURN_TYPES = ("LATENT", )
|
465 |
+
FUNCTION = "load"
|
466 |
+
|
467 |
+
def load(self, latent):
|
468 |
+
latent_path = folder_paths.get_annotated_filepath(latent)
|
469 |
+
latent = safetensors.torch.load_file(latent_path, device="cpu")
|
470 |
+
multiplier = 1.0
|
471 |
+
if "latent_format_version_0" not in latent:
|
472 |
+
multiplier = 1.0 / 0.18215
|
473 |
+
samples = {"samples": latent["latent_tensor"].float() * multiplier}
|
474 |
+
return (samples, )
|
475 |
+
|
476 |
+
@classmethod
|
477 |
+
def IS_CHANGED(s, latent):
|
478 |
+
image_path = folder_paths.get_annotated_filepath(latent)
|
479 |
+
m = hashlib.sha256()
|
480 |
+
with open(image_path, 'rb') as f:
|
481 |
+
m.update(f.read())
|
482 |
+
return m.digest().hex()
|
483 |
+
|
484 |
+
@classmethod
|
485 |
+
def VALIDATE_INPUTS(s, latent):
|
486 |
+
if not folder_paths.exists_annotated_filepath(latent):
|
487 |
+
return "Invalid latent file: {}".format(latent)
|
488 |
+
return True
|
489 |
+
|
490 |
+
|
491 |
+
class CheckpointLoader:
|
492 |
+
@classmethod
|
493 |
+
def INPUT_TYPES(s):
|
494 |
+
return {"required": { "config_name": (folder_paths.get_filename_list("configs"), ),
|
495 |
+
"ckpt_name": (folder_paths.get_filename_list("checkpoints"), )}}
|
496 |
+
RETURN_TYPES = ("MODEL", "CLIP", "VAE")
|
497 |
+
FUNCTION = "load_checkpoint"
|
498 |
+
|
499 |
+
CATEGORY = "advanced/loaders"
|
500 |
+
|
501 |
+
def load_checkpoint(self, config_name, ckpt_name):
|
502 |
+
config_path = folder_paths.get_full_path("configs", config_name)
|
503 |
+
ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
|
504 |
+
return comfy.sd.load_checkpoint(config_path, ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
|
505 |
+
|
506 |
+
class CheckpointLoaderSimple:
|
507 |
+
@classmethod
|
508 |
+
def INPUT_TYPES(s):
|
509 |
+
return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ),
|
510 |
+
}}
|
511 |
+
RETURN_TYPES = ("MODEL", "CLIP", "VAE")
|
512 |
+
FUNCTION = "load_checkpoint"
|
513 |
+
|
514 |
+
CATEGORY = "loaders"
|
515 |
+
|
516 |
+
def load_checkpoint(self, ckpt_name):
|
517 |
+
ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
|
518 |
+
out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
|
519 |
+
return out[:3]
|
520 |
+
|
521 |
+
class DiffusersLoader:
|
522 |
+
@classmethod
|
523 |
+
def INPUT_TYPES(cls):
|
524 |
+
paths = []
|
525 |
+
for search_path in folder_paths.get_folder_paths("diffusers"):
|
526 |
+
if os.path.exists(search_path):
|
527 |
+
for root, subdir, files in os.walk(search_path, followlinks=True):
|
528 |
+
if "model_index.json" in files:
|
529 |
+
paths.append(os.path.relpath(root, start=search_path))
|
530 |
+
|
531 |
+
return {"required": {"model_path": (paths,), }}
|
532 |
+
RETURN_TYPES = ("MODEL", "CLIP", "VAE")
|
533 |
+
FUNCTION = "load_checkpoint"
|
534 |
+
|
535 |
+
CATEGORY = "advanced/loaders/deprecated"
|
536 |
+
|
537 |
+
def load_checkpoint(self, model_path, output_vae=True, output_clip=True):
|
538 |
+
for search_path in folder_paths.get_folder_paths("diffusers"):
|
539 |
+
if os.path.exists(search_path):
|
540 |
+
path = os.path.join(search_path, model_path)
|
541 |
+
if os.path.exists(path):
|
542 |
+
model_path = path
|
543 |
+
break
|
544 |
+
|
545 |
+
return comfy.diffusers_load.load_diffusers(model_path, output_vae=output_vae, output_clip=output_clip, embedding_directory=folder_paths.get_folder_paths("embeddings"))
|
546 |
+
|
547 |
+
|
548 |
+
class unCLIPCheckpointLoader:
|
549 |
+
@classmethod
|
550 |
+
def INPUT_TYPES(s):
|
551 |
+
return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ),
|
552 |
+
}}
|
553 |
+
RETURN_TYPES = ("MODEL", "CLIP", "VAE", "CLIP_VISION")
|
554 |
+
FUNCTION = "load_checkpoint"
|
555 |
+
|
556 |
+
CATEGORY = "loaders"
|
557 |
+
|
558 |
+
def load_checkpoint(self, ckpt_name, output_vae=True, output_clip=True):
|
559 |
+
ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
|
560 |
+
out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, output_clipvision=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
|
561 |
+
return out
|
562 |
+
|
563 |
+
class CLIPSetLastLayer:
|
564 |
+
@classmethod
|
565 |
+
def INPUT_TYPES(s):
|
566 |
+
return {"required": { "clip": ("CLIP", ),
|
567 |
+
"stop_at_clip_layer": ("INT", {"default": -1, "min": -24, "max": -1, "step": 1}),
|
568 |
+
}}
|
569 |
+
RETURN_TYPES = ("CLIP",)
|
570 |
+
FUNCTION = "set_last_layer"
|
571 |
+
|
572 |
+
CATEGORY = "conditioning"
|
573 |
+
|
574 |
+
def set_last_layer(self, clip, stop_at_clip_layer):
|
575 |
+
clip = clip.clone()
|
576 |
+
clip.clip_layer(stop_at_clip_layer)
|
577 |
+
return (clip,)
|
578 |
+
|
579 |
+
class LoraLoader:
|
580 |
+
def __init__(self):
|
581 |
+
self.loaded_lora = None
|
582 |
+
|
583 |
+
@classmethod
|
584 |
+
def INPUT_TYPES(s):
|
585 |
+
return {"required": { "model": ("MODEL",),
|
586 |
+
"clip": ("CLIP", ),
|
587 |
+
"lora_name": (folder_paths.get_filename_list("loras"), ),
|
588 |
+
"strength_model": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01}),
|
589 |
+
"strength_clip": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01}),
|
590 |
+
}}
|
591 |
+
RETURN_TYPES = ("MODEL", "CLIP")
|
592 |
+
FUNCTION = "load_lora"
|
593 |
+
|
594 |
+
CATEGORY = "loaders"
|
595 |
+
|
596 |
+
def load_lora(self, model, clip, lora_name, strength_model, strength_clip):
|
597 |
+
if strength_model == 0 and strength_clip == 0:
|
598 |
+
return (model, clip)
|
599 |
+
|
600 |
+
lora_path = folder_paths.get_full_path("loras", lora_name)
|
601 |
+
lora = None
|
602 |
+
if self.loaded_lora is not None:
|
603 |
+
if self.loaded_lora[0] == lora_path:
|
604 |
+
lora = self.loaded_lora[1]
|
605 |
+
else:
|
606 |
+
temp = self.loaded_lora
|
607 |
+
self.loaded_lora = None
|
608 |
+
del temp
|
609 |
+
|
610 |
+
if lora is None:
|
611 |
+
lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
|
612 |
+
self.loaded_lora = (lora_path, lora)
|
613 |
+
|
614 |
+
model_lora, clip_lora = comfy.sd.load_lora_for_models(model, clip, lora, strength_model, strength_clip)
|
615 |
+
return (model_lora, clip_lora)
|
616 |
+
|
617 |
+
class LoraLoaderModelOnly(LoraLoader):
|
618 |
+
@classmethod
|
619 |
+
def INPUT_TYPES(s):
|
620 |
+
return {"required": { "model": ("MODEL",),
|
621 |
+
"lora_name": (folder_paths.get_filename_list("loras"), ),
|
622 |
+
"strength_model": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01}),
|
623 |
+
}}
|
624 |
+
RETURN_TYPES = ("MODEL",)
|
625 |
+
FUNCTION = "load_lora_model_only"
|
626 |
+
|
627 |
+
def load_lora_model_only(self, model, lora_name, strength_model):
|
628 |
+
return (self.load_lora(model, None, lora_name, strength_model, 0)[0],)
|
629 |
+
|
630 |
+
class VAELoader:
|
631 |
+
@staticmethod
|
632 |
+
def vae_list():
|
633 |
+
vaes = folder_paths.get_filename_list("vae")
|
634 |
+
approx_vaes = folder_paths.get_filename_list("vae_approx")
|
635 |
+
sdxl_taesd_enc = False
|
636 |
+
sdxl_taesd_dec = False
|
637 |
+
sd1_taesd_enc = False
|
638 |
+
sd1_taesd_dec = False
|
639 |
+
sd3_taesd_enc = False
|
640 |
+
sd3_taesd_dec = False
|
641 |
+
|
642 |
+
for v in approx_vaes:
|
643 |
+
if v.startswith("taesd_decoder."):
|
644 |
+
sd1_taesd_dec = True
|
645 |
+
elif v.startswith("taesd_encoder."):
|
646 |
+
sd1_taesd_enc = True
|
647 |
+
elif v.startswith("taesdxl_decoder."):
|
648 |
+
sdxl_taesd_dec = True
|
649 |
+
elif v.startswith("taesdxl_encoder."):
|
650 |
+
sdxl_taesd_enc = True
|
651 |
+
elif v.startswith("taesd3_decoder."):
|
652 |
+
sd3_taesd_dec = True
|
653 |
+
elif v.startswith("taesd3_encoder."):
|
654 |
+
sd3_taesd_enc = True
|
655 |
+
if sd1_taesd_dec and sd1_taesd_enc:
|
656 |
+
vaes.append("taesd")
|
657 |
+
if sdxl_taesd_dec and sdxl_taesd_enc:
|
658 |
+
vaes.append("taesdxl")
|
659 |
+
if sd3_taesd_dec and sd3_taesd_enc:
|
660 |
+
vaes.append("taesd3")
|
661 |
+
return vaes
|
662 |
+
|
663 |
+
@staticmethod
|
664 |
+
def load_taesd(name):
|
665 |
+
sd = {}
|
666 |
+
approx_vaes = folder_paths.get_filename_list("vae_approx")
|
667 |
+
|
668 |
+
encoder = next(filter(lambda a: a.startswith("{}_encoder.".format(name)), approx_vaes))
|
669 |
+
decoder = next(filter(lambda a: a.startswith("{}_decoder.".format(name)), approx_vaes))
|
670 |
+
|
671 |
+
enc = comfy.utils.load_torch_file(folder_paths.get_full_path("vae_approx", encoder))
|
672 |
+
for k in enc:
|
673 |
+
sd["taesd_encoder.{}".format(k)] = enc[k]
|
674 |
+
|
675 |
+
dec = comfy.utils.load_torch_file(folder_paths.get_full_path("vae_approx", decoder))
|
676 |
+
for k in dec:
|
677 |
+
sd["taesd_decoder.{}".format(k)] = dec[k]
|
678 |
+
|
679 |
+
if name == "taesd":
|
680 |
+
sd["vae_scale"] = torch.tensor(0.18215)
|
681 |
+
sd["vae_shift"] = torch.tensor(0.0)
|
682 |
+
elif name == "taesdxl":
|
683 |
+
sd["vae_scale"] = torch.tensor(0.13025)
|
684 |
+
sd["vae_shift"] = torch.tensor(0.0)
|
685 |
+
elif name == "taesd3":
|
686 |
+
sd["vae_scale"] = torch.tensor(1.5305)
|
687 |
+
sd["vae_shift"] = torch.tensor(0.0609)
|
688 |
+
return sd
|
689 |
+
|
690 |
+
@classmethod
|
691 |
+
def INPUT_TYPES(s):
|
692 |
+
return {"required": { "vae_name": (s.vae_list(), )}}
|
693 |
+
RETURN_TYPES = ("VAE",)
|
694 |
+
FUNCTION = "load_vae"
|
695 |
+
|
696 |
+
CATEGORY = "loaders"
|
697 |
+
|
698 |
+
#TODO: scale factor?
|
699 |
+
def load_vae(self, vae_name):
|
700 |
+
if vae_name in ["taesd", "taesdxl", "taesd3"]:
|
701 |
+
sd = self.load_taesd(vae_name)
|
702 |
+
else:
|
703 |
+
vae_path = folder_paths.get_full_path("vae", vae_name)
|
704 |
+
sd = comfy.utils.load_torch_file(vae_path)
|
705 |
+
vae = comfy.sd.VAE(sd=sd)
|
706 |
+
return (vae,)
|
707 |
+
|
708 |
+
class ControlNetLoader:
|
709 |
+
@classmethod
|
710 |
+
def INPUT_TYPES(s):
|
711 |
+
return {"required": { "control_net_name": (folder_paths.get_filename_list("controlnet"), )}}
|
712 |
+
|
713 |
+
RETURN_TYPES = ("CONTROL_NET",)
|
714 |
+
FUNCTION = "load_controlnet"
|
715 |
+
|
716 |
+
CATEGORY = "loaders"
|
717 |
+
|
718 |
+
def load_controlnet(self, control_net_name):
|
719 |
+
controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
|
720 |
+
controlnet = comfy.controlnet.load_controlnet(controlnet_path)
|
721 |
+
return (controlnet,)
|
722 |
+
|
723 |
+
class DiffControlNetLoader:
|
724 |
+
@classmethod
|
725 |
+
def INPUT_TYPES(s):
|
726 |
+
return {"required": { "model": ("MODEL",),
|
727 |
+
"control_net_name": (folder_paths.get_filename_list("controlnet"), )}}
|
728 |
+
|
729 |
+
RETURN_TYPES = ("CONTROL_NET",)
|
730 |
+
FUNCTION = "load_controlnet"
|
731 |
+
|
732 |
+
CATEGORY = "loaders"
|
733 |
+
|
734 |
+
def load_controlnet(self, model, control_net_name):
|
735 |
+
controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
|
736 |
+
controlnet = comfy.controlnet.load_controlnet(controlnet_path, model)
|
737 |
+
return (controlnet,)
|
738 |
+
|
739 |
+
|
740 |
+
class ControlNetApply:
|
741 |
+
@classmethod
|
742 |
+
def INPUT_TYPES(s):
|
743 |
+
return {"required": {"conditioning": ("CONDITIONING", ),
|
744 |
+
"control_net": ("CONTROL_NET", ),
|
745 |
+
"image": ("IMAGE", ),
|
746 |
+
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01})
|
747 |
+
}}
|
748 |
+
RETURN_TYPES = ("CONDITIONING",)
|
749 |
+
FUNCTION = "apply_controlnet"
|
750 |
+
|
751 |
+
CATEGORY = "conditioning/controlnet"
|
752 |
+
|
753 |
+
def apply_controlnet(self, conditioning, control_net, image, strength):
|
754 |
+
if strength == 0:
|
755 |
+
return (conditioning, )
|
756 |
+
|
757 |
+
c = []
|
758 |
+
control_hint = image.movedim(-1,1)
|
759 |
+
for t in conditioning:
|
760 |
+
n = [t[0], t[1].copy()]
|
761 |
+
c_net = control_net.copy().set_cond_hint(control_hint, strength)
|
762 |
+
if 'control' in t[1]:
|
763 |
+
c_net.set_previous_controlnet(t[1]['control'])
|
764 |
+
n[1]['control'] = c_net
|
765 |
+
n[1]['control_apply_to_uncond'] = True
|
766 |
+
c.append(n)
|
767 |
+
return (c, )
|
768 |
+
|
769 |
+
|
770 |
+
class ControlNetApplyAdvanced:
|
771 |
+
@classmethod
|
772 |
+
def INPUT_TYPES(s):
|
773 |
+
return {"required": {"positive": ("CONDITIONING", ),
|
774 |
+
"negative": ("CONDITIONING", ),
|
775 |
+
"control_net": ("CONTROL_NET", ),
|
776 |
+
"image": ("IMAGE", ),
|
777 |
+
"strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
|
778 |
+
"start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
|
779 |
+
"end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
|
780 |
+
}}
|
781 |
+
|
782 |
+
RETURN_TYPES = ("CONDITIONING","CONDITIONING")
|
783 |
+
RETURN_NAMES = ("positive", "negative")
|
784 |
+
FUNCTION = "apply_controlnet"
|
785 |
+
|
786 |
+
CATEGORY = "conditioning/controlnet"
|
787 |
+
|
788 |
+
def apply_controlnet(self, positive, negative, control_net, image, strength, start_percent, end_percent, vae=None):
|
789 |
+
if strength == 0:
|
790 |
+
return (positive, negative)
|
791 |
+
|
792 |
+
control_hint = image.movedim(-1,1)
|
793 |
+
cnets = {}
|
794 |
+
|
795 |
+
out = []
|
796 |
+
for conditioning in [positive, negative]:
|
797 |
+
c = []
|
798 |
+
for t in conditioning:
|
799 |
+
d = t[1].copy()
|
800 |
+
|
801 |
+
prev_cnet = d.get('control', None)
|
802 |
+
if prev_cnet in cnets:
|
803 |
+
c_net = cnets[prev_cnet]
|
804 |
+
else:
|
805 |
+
c_net = control_net.copy().set_cond_hint(control_hint, strength, (start_percent, end_percent), vae)
|
806 |
+
c_net.set_previous_controlnet(prev_cnet)
|
807 |
+
cnets[prev_cnet] = c_net
|
808 |
+
|
809 |
+
d['control'] = c_net
|
810 |
+
d['control_apply_to_uncond'] = False
|
811 |
+
n = [t[0], d]
|
812 |
+
c.append(n)
|
813 |
+
out.append(c)
|
814 |
+
return (out[0], out[1])
|
815 |
+
|
816 |
+
|
817 |
+
class UNETLoader:
|
818 |
+
@classmethod
|
819 |
+
def INPUT_TYPES(s):
|
820 |
+
return {"required": { "unet_name": (folder_paths.get_filename_list("unet"), ),
|
821 |
+
}}
|
822 |
+
RETURN_TYPES = ("MODEL",)
|
823 |
+
FUNCTION = "load_unet"
|
824 |
+
|
825 |
+
CATEGORY = "advanced/loaders"
|
826 |
+
|
827 |
+
def load_unet(self, unet_name):
|
828 |
+
unet_path = folder_paths.get_full_path("unet", unet_name)
|
829 |
+
model = comfy.sd.load_unet(unet_path)
|
830 |
+
return (model,)
|
831 |
+
|
832 |
+
class CLIPLoader:
|
833 |
+
@classmethod
|
834 |
+
def INPUT_TYPES(s):
|
835 |
+
return {"required": { "clip_name": (folder_paths.get_filename_list("clip"), ),
|
836 |
+
"type": (["stable_diffusion", "stable_cascade", "sd3", "stable_audio"], ),
|
837 |
+
}}
|
838 |
+
RETURN_TYPES = ("CLIP",)
|
839 |
+
FUNCTION = "load_clip"
|
840 |
+
|
841 |
+
CATEGORY = "advanced/loaders"
|
842 |
+
|
843 |
+
def load_clip(self, clip_name, type="stable_diffusion"):
|
844 |
+
if type == "stable_cascade":
|
845 |
+
clip_type = comfy.sd.CLIPType.STABLE_CASCADE
|
846 |
+
elif type == "sd3":
|
847 |
+
clip_type = comfy.sd.CLIPType.SD3
|
848 |
+
elif type == "stable_audio":
|
849 |
+
clip_type = comfy.sd.CLIPType.STABLE_AUDIO
|
850 |
+
else:
|
851 |
+
clip_type = comfy.sd.CLIPType.STABLE_DIFFUSION
|
852 |
+
|
853 |
+
clip_path = folder_paths.get_full_path("clip", clip_name)
|
854 |
+
clip = comfy.sd.load_clip(ckpt_paths=[clip_path], embedding_directory=folder_paths.get_folder_paths("embeddings"), clip_type=clip_type)
|
855 |
+
return (clip,)
|
856 |
+
|
857 |
+
class DualCLIPLoader:
|
858 |
+
@classmethod
|
859 |
+
def INPUT_TYPES(s):
|
860 |
+
return {"required": { "clip_name1": (folder_paths.get_filename_list("clip"), ),
|
861 |
+
"clip_name2": (folder_paths.get_filename_list("clip"), ),
|
862 |
+
"type": (["sdxl", "sd3"], ),
|
863 |
+
}}
|
864 |
+
RETURN_TYPES = ("CLIP",)
|
865 |
+
FUNCTION = "load_clip"
|
866 |
+
|
867 |
+
CATEGORY = "advanced/loaders"
|
868 |
+
|
869 |
+
def load_clip(self, clip_name1, clip_name2, type):
|
870 |
+
clip_path1 = folder_paths.get_full_path("clip", clip_name1)
|
871 |
+
clip_path2 = folder_paths.get_full_path("clip", clip_name2)
|
872 |
+
if type == "sdxl":
|
873 |
+
clip_type = comfy.sd.CLIPType.STABLE_DIFFUSION
|
874 |
+
elif type == "sd3":
|
875 |
+
clip_type = comfy.sd.CLIPType.SD3
|
876 |
+
|
877 |
+
clip = comfy.sd.load_clip(ckpt_paths=[clip_path1, clip_path2], embedding_directory=folder_paths.get_folder_paths("embeddings"), clip_type=clip_type)
|
878 |
+
return (clip,)
|
879 |
+
|
880 |
+
class CLIPVisionLoader:
|
881 |
+
@classmethod
|
882 |
+
def INPUT_TYPES(s):
|
883 |
+
return {"required": { "clip_name": (folder_paths.get_filename_list("clip_vision"), ),
|
884 |
+
}}
|
885 |
+
RETURN_TYPES = ("CLIP_VISION",)
|
886 |
+
FUNCTION = "load_clip"
|
887 |
+
|
888 |
+
CATEGORY = "loaders"
|
889 |
+
|
890 |
+
def load_clip(self, clip_name):
|
891 |
+
clip_path = folder_paths.get_full_path("clip_vision", clip_name)
|
892 |
+
clip_vision = comfy.clip_vision.load(clip_path)
|
893 |
+
return (clip_vision,)
|
894 |
+
|
895 |
+
class CLIPVisionEncode:
|
896 |
+
@classmethod
|
897 |
+
def INPUT_TYPES(s):
|
898 |
+
return {"required": { "clip_vision": ("CLIP_VISION",),
|
899 |
+
"image": ("IMAGE",)
|
900 |
+
}}
|
901 |
+
RETURN_TYPES = ("CLIP_VISION_OUTPUT",)
|
902 |
+
FUNCTION = "encode"
|
903 |
+
|
904 |
+
CATEGORY = "conditioning"
|
905 |
+
|
906 |
+
def encode(self, clip_vision, image):
|
907 |
+
output = clip_vision.encode_image(image)
|
908 |
+
return (output,)
|
909 |
+
|
910 |
+
class StyleModelLoader:
|
911 |
+
@classmethod
|
912 |
+
def INPUT_TYPES(s):
|
913 |
+
return {"required": { "style_model_name": (folder_paths.get_filename_list("style_models"), )}}
|
914 |
+
|
915 |
+
RETURN_TYPES = ("STYLE_MODEL",)
|
916 |
+
FUNCTION = "load_style_model"
|
917 |
+
|
918 |
+
CATEGORY = "loaders"
|
919 |
+
|
920 |
+
def load_style_model(self, style_model_name):
|
921 |
+
style_model_path = folder_paths.get_full_path("style_models", style_model_name)
|
922 |
+
style_model = comfy.sd.load_style_model(style_model_path)
|
923 |
+
return (style_model,)
|
924 |
+
|
925 |
+
|
926 |
+
class StyleModelApply:
|
927 |
+
@classmethod
|
928 |
+
def INPUT_TYPES(s):
|
929 |
+
return {"required": {"conditioning": ("CONDITIONING", ),
|
930 |
+
"style_model": ("STYLE_MODEL", ),
|
931 |
+
"clip_vision_output": ("CLIP_VISION_OUTPUT", ),
|
932 |
+
}}
|
933 |
+
RETURN_TYPES = ("CONDITIONING",)
|
934 |
+
FUNCTION = "apply_stylemodel"
|
935 |
+
|
936 |
+
CATEGORY = "conditioning/style_model"
|
937 |
+
|
938 |
+
def apply_stylemodel(self, clip_vision_output, style_model, conditioning):
|
939 |
+
cond = style_model.get_cond(clip_vision_output).flatten(start_dim=0, end_dim=1).unsqueeze(dim=0)
|
940 |
+
c = []
|
941 |
+
for t in conditioning:
|
942 |
+
n = [torch.cat((t[0], cond), dim=1), t[1].copy()]
|
943 |
+
c.append(n)
|
944 |
+
return (c, )
|
945 |
+
|
946 |
+
class unCLIPConditioning:
|
947 |
+
@classmethod
|
948 |
+
def INPUT_TYPES(s):
|
949 |
+
return {"required": {"conditioning": ("CONDITIONING", ),
|
950 |
+
"clip_vision_output": ("CLIP_VISION_OUTPUT", ),
|
951 |
+
"strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
|
952 |
+
"noise_augmentation": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
953 |
+
}}
|
954 |
+
RETURN_TYPES = ("CONDITIONING",)
|
955 |
+
FUNCTION = "apply_adm"
|
956 |
+
|
957 |
+
CATEGORY = "conditioning"
|
958 |
+
|
959 |
+
def apply_adm(self, conditioning, clip_vision_output, strength, noise_augmentation):
|
960 |
+
if strength == 0:
|
961 |
+
return (conditioning, )
|
962 |
+
|
963 |
+
c = []
|
964 |
+
for t in conditioning:
|
965 |
+
o = t[1].copy()
|
966 |
+
x = {"clip_vision_output": clip_vision_output, "strength": strength, "noise_augmentation": noise_augmentation}
|
967 |
+
if "unclip_conditioning" in o:
|
968 |
+
o["unclip_conditioning"] = o["unclip_conditioning"][:] + [x]
|
969 |
+
else:
|
970 |
+
o["unclip_conditioning"] = [x]
|
971 |
+
n = [t[0], o]
|
972 |
+
c.append(n)
|
973 |
+
return (c, )
|
974 |
+
|
975 |
+
class GLIGENLoader:
|
976 |
+
@classmethod
|
977 |
+
def INPUT_TYPES(s):
|
978 |
+
return {"required": { "gligen_name": (folder_paths.get_filename_list("gligen"), )}}
|
979 |
+
|
980 |
+
RETURN_TYPES = ("GLIGEN",)
|
981 |
+
FUNCTION = "load_gligen"
|
982 |
+
|
983 |
+
CATEGORY = "loaders"
|
984 |
+
|
985 |
+
def load_gligen(self, gligen_name):
|
986 |
+
gligen_path = folder_paths.get_full_path("gligen", gligen_name)
|
987 |
+
gligen = comfy.sd.load_gligen(gligen_path)
|
988 |
+
return (gligen,)
|
989 |
+
|
990 |
+
class GLIGENTextBoxApply:
|
991 |
+
@classmethod
|
992 |
+
def INPUT_TYPES(s):
|
993 |
+
return {"required": {"conditioning_to": ("CONDITIONING", ),
|
994 |
+
"clip": ("CLIP", ),
|
995 |
+
"gligen_textbox_model": ("GLIGEN", ),
|
996 |
+
"text": ("STRING", {"multiline": True, "dynamicPrompts": True}),
|
997 |
+
"width": ("INT", {"default": 64, "min": 8, "max": MAX_RESOLUTION, "step": 8}),
|
998 |
+
"height": ("INT", {"default": 64, "min": 8, "max": MAX_RESOLUTION, "step": 8}),
|
999 |
+
"x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
1000 |
+
"y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
1001 |
+
}}
|
1002 |
+
RETURN_TYPES = ("CONDITIONING",)
|
1003 |
+
FUNCTION = "append"
|
1004 |
+
|
1005 |
+
CATEGORY = "conditioning/gligen"
|
1006 |
+
|
1007 |
+
def append(self, conditioning_to, clip, gligen_textbox_model, text, width, height, x, y):
|
1008 |
+
c = []
|
1009 |
+
cond, cond_pooled = clip.encode_from_tokens(clip.tokenize(text), return_pooled="unprojected")
|
1010 |
+
for t in conditioning_to:
|
1011 |
+
n = [t[0], t[1].copy()]
|
1012 |
+
position_params = [(cond_pooled, height // 8, width // 8, y // 8, x // 8)]
|
1013 |
+
prev = []
|
1014 |
+
if "gligen" in n[1]:
|
1015 |
+
prev = n[1]['gligen'][2]
|
1016 |
+
|
1017 |
+
n[1]['gligen'] = ("position", gligen_textbox_model, prev + position_params)
|
1018 |
+
c.append(n)
|
1019 |
+
return (c, )
|
1020 |
+
|
1021 |
+
class EmptyLatentImage:
|
1022 |
+
def __init__(self):
|
1023 |
+
self.device = comfy.model_management.intermediate_device()
|
1024 |
+
|
1025 |
+
@classmethod
|
1026 |
+
def INPUT_TYPES(s):
|
1027 |
+
return {"required": { "width": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8}),
|
1028 |
+
"height": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8}),
|
1029 |
+
"batch_size": ("INT", {"default": 1, "min": 1, "max": 4096})}}
|
1030 |
+
RETURN_TYPES = ("LATENT",)
|
1031 |
+
FUNCTION = "generate"
|
1032 |
+
|
1033 |
+
CATEGORY = "latent"
|
1034 |
+
|
1035 |
+
def generate(self, width, height, batch_size=1):
|
1036 |
+
latent = torch.zeros([batch_size, 4, height // 8, width // 8], device=self.device)
|
1037 |
+
return ({"samples":latent}, )
|
1038 |
+
|
1039 |
+
|
1040 |
+
class LatentFromBatch:
|
1041 |
+
@classmethod
|
1042 |
+
def INPUT_TYPES(s):
|
1043 |
+
return {"required": { "samples": ("LATENT",),
|
1044 |
+
"batch_index": ("INT", {"default": 0, "min": 0, "max": 63}),
|
1045 |
+
"length": ("INT", {"default": 1, "min": 1, "max": 64}),
|
1046 |
+
}}
|
1047 |
+
RETURN_TYPES = ("LATENT",)
|
1048 |
+
FUNCTION = "frombatch"
|
1049 |
+
|
1050 |
+
CATEGORY = "latent/batch"
|
1051 |
+
|
1052 |
+
def frombatch(self, samples, batch_index, length):
|
1053 |
+
s = samples.copy()
|
1054 |
+
s_in = samples["samples"]
|
1055 |
+
batch_index = min(s_in.shape[0] - 1, batch_index)
|
1056 |
+
length = min(s_in.shape[0] - batch_index, length)
|
1057 |
+
s["samples"] = s_in[batch_index:batch_index + length].clone()
|
1058 |
+
if "noise_mask" in samples:
|
1059 |
+
masks = samples["noise_mask"]
|
1060 |
+
if masks.shape[0] == 1:
|
1061 |
+
s["noise_mask"] = masks.clone()
|
1062 |
+
else:
|
1063 |
+
if masks.shape[0] < s_in.shape[0]:
|
1064 |
+
masks = masks.repeat(math.ceil(s_in.shape[0] / masks.shape[0]), 1, 1, 1)[:s_in.shape[0]]
|
1065 |
+
s["noise_mask"] = masks[batch_index:batch_index + length].clone()
|
1066 |
+
if "batch_index" not in s:
|
1067 |
+
s["batch_index"] = [x for x in range(batch_index, batch_index+length)]
|
1068 |
+
else:
|
1069 |
+
s["batch_index"] = samples["batch_index"][batch_index:batch_index + length]
|
1070 |
+
return (s,)
|
1071 |
+
|
1072 |
+
class RepeatLatentBatch:
|
1073 |
+
@classmethod
|
1074 |
+
def INPUT_TYPES(s):
|
1075 |
+
return {"required": { "samples": ("LATENT",),
|
1076 |
+
"amount": ("INT", {"default": 1, "min": 1, "max": 64}),
|
1077 |
+
}}
|
1078 |
+
RETURN_TYPES = ("LATENT",)
|
1079 |
+
FUNCTION = "repeat"
|
1080 |
+
|
1081 |
+
CATEGORY = "latent/batch"
|
1082 |
+
|
1083 |
+
def repeat(self, samples, amount):
|
1084 |
+
s = samples.copy()
|
1085 |
+
s_in = samples["samples"]
|
1086 |
+
|
1087 |
+
s["samples"] = s_in.repeat((amount, 1,1,1))
|
1088 |
+
if "noise_mask" in samples and samples["noise_mask"].shape[0] > 1:
|
1089 |
+
masks = samples["noise_mask"]
|
1090 |
+
if masks.shape[0] < s_in.shape[0]:
|
1091 |
+
masks = masks.repeat(math.ceil(s_in.shape[0] / masks.shape[0]), 1, 1, 1)[:s_in.shape[0]]
|
1092 |
+
s["noise_mask"] = samples["noise_mask"].repeat((amount, 1,1,1))
|
1093 |
+
if "batch_index" in s:
|
1094 |
+
offset = max(s["batch_index"]) - min(s["batch_index"]) + 1
|
1095 |
+
s["batch_index"] = s["batch_index"] + [x + (i * offset) for i in range(1, amount) for x in s["batch_index"]]
|
1096 |
+
return (s,)
|
1097 |
+
|
1098 |
+
class LatentUpscale:
|
1099 |
+
upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "bislerp"]
|
1100 |
+
crop_methods = ["disabled", "center"]
|
1101 |
+
|
1102 |
+
@classmethod
|
1103 |
+
def INPUT_TYPES(s):
|
1104 |
+
return {"required": { "samples": ("LATENT",), "upscale_method": (s.upscale_methods,),
|
1105 |
+
"width": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
1106 |
+
"height": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
1107 |
+
"crop": (s.crop_methods,)}}
|
1108 |
+
RETURN_TYPES = ("LATENT",)
|
1109 |
+
FUNCTION = "upscale"
|
1110 |
+
|
1111 |
+
CATEGORY = "latent"
|
1112 |
+
|
1113 |
+
def upscale(self, samples, upscale_method, width, height, crop):
|
1114 |
+
if width == 0 and height == 0:
|
1115 |
+
s = samples
|
1116 |
+
else:
|
1117 |
+
s = samples.copy()
|
1118 |
+
|
1119 |
+
if width == 0:
|
1120 |
+
height = max(64, height)
|
1121 |
+
width = max(64, round(samples["samples"].shape[3] * height / samples["samples"].shape[2]))
|
1122 |
+
elif height == 0:
|
1123 |
+
width = max(64, width)
|
1124 |
+
height = max(64, round(samples["samples"].shape[2] * width / samples["samples"].shape[3]))
|
1125 |
+
else:
|
1126 |
+
width = max(64, width)
|
1127 |
+
height = max(64, height)
|
1128 |
+
|
1129 |
+
s["samples"] = comfy.utils.common_upscale(samples["samples"], width // 8, height // 8, upscale_method, crop)
|
1130 |
+
return (s,)
|
1131 |
+
|
1132 |
+
class LatentUpscaleBy:
|
1133 |
+
upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "bislerp"]
|
1134 |
+
|
1135 |
+
@classmethod
|
1136 |
+
def INPUT_TYPES(s):
|
1137 |
+
return {"required": { "samples": ("LATENT",), "upscale_method": (s.upscale_methods,),
|
1138 |
+
"scale_by": ("FLOAT", {"default": 1.5, "min": 0.01, "max": 8.0, "step": 0.01}),}}
|
1139 |
+
RETURN_TYPES = ("LATENT",)
|
1140 |
+
FUNCTION = "upscale"
|
1141 |
+
|
1142 |
+
CATEGORY = "latent"
|
1143 |
+
|
1144 |
+
def upscale(self, samples, upscale_method, scale_by):
|
1145 |
+
s = samples.copy()
|
1146 |
+
width = round(samples["samples"].shape[3] * scale_by)
|
1147 |
+
height = round(samples["samples"].shape[2] * scale_by)
|
1148 |
+
s["samples"] = comfy.utils.common_upscale(samples["samples"], width, height, upscale_method, "disabled")
|
1149 |
+
return (s,)
|
1150 |
+
|
1151 |
+
class LatentRotate:
|
1152 |
+
@classmethod
|
1153 |
+
def INPUT_TYPES(s):
|
1154 |
+
return {"required": { "samples": ("LATENT",),
|
1155 |
+
"rotation": (["none", "90 degrees", "180 degrees", "270 degrees"],),
|
1156 |
+
}}
|
1157 |
+
RETURN_TYPES = ("LATENT",)
|
1158 |
+
FUNCTION = "rotate"
|
1159 |
+
|
1160 |
+
CATEGORY = "latent/transform"
|
1161 |
+
|
1162 |
+
def rotate(self, samples, rotation):
|
1163 |
+
s = samples.copy()
|
1164 |
+
rotate_by = 0
|
1165 |
+
if rotation.startswith("90"):
|
1166 |
+
rotate_by = 1
|
1167 |
+
elif rotation.startswith("180"):
|
1168 |
+
rotate_by = 2
|
1169 |
+
elif rotation.startswith("270"):
|
1170 |
+
rotate_by = 3
|
1171 |
+
|
1172 |
+
s["samples"] = torch.rot90(samples["samples"], k=rotate_by, dims=[3, 2])
|
1173 |
+
return (s,)
|
1174 |
+
|
1175 |
+
class LatentFlip:
|
1176 |
+
@classmethod
|
1177 |
+
def INPUT_TYPES(s):
|
1178 |
+
return {"required": { "samples": ("LATENT",),
|
1179 |
+
"flip_method": (["x-axis: vertically", "y-axis: horizontally"],),
|
1180 |
+
}}
|
1181 |
+
RETURN_TYPES = ("LATENT",)
|
1182 |
+
FUNCTION = "flip"
|
1183 |
+
|
1184 |
+
CATEGORY = "latent/transform"
|
1185 |
+
|
1186 |
+
def flip(self, samples, flip_method):
|
1187 |
+
s = samples.copy()
|
1188 |
+
if flip_method.startswith("x"):
|
1189 |
+
s["samples"] = torch.flip(samples["samples"], dims=[2])
|
1190 |
+
elif flip_method.startswith("y"):
|
1191 |
+
s["samples"] = torch.flip(samples["samples"], dims=[3])
|
1192 |
+
|
1193 |
+
return (s,)
|
1194 |
+
|
1195 |
+
class LatentComposite:
|
1196 |
+
@classmethod
|
1197 |
+
def INPUT_TYPES(s):
|
1198 |
+
return {"required": { "samples_to": ("LATENT",),
|
1199 |
+
"samples_from": ("LATENT",),
|
1200 |
+
"x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
1201 |
+
"y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
1202 |
+
"feather": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
1203 |
+
}}
|
1204 |
+
RETURN_TYPES = ("LATENT",)
|
1205 |
+
FUNCTION = "composite"
|
1206 |
+
|
1207 |
+
CATEGORY = "latent"
|
1208 |
+
|
1209 |
+
def composite(self, samples_to, samples_from, x, y, composite_method="normal", feather=0):
|
1210 |
+
x = x // 8
|
1211 |
+
y = y // 8
|
1212 |
+
feather = feather // 8
|
1213 |
+
samples_out = samples_to.copy()
|
1214 |
+
s = samples_to["samples"].clone()
|
1215 |
+
samples_to = samples_to["samples"]
|
1216 |
+
samples_from = samples_from["samples"]
|
1217 |
+
if feather == 0:
|
1218 |
+
s[:,:,y:y+samples_from.shape[2],x:x+samples_from.shape[3]] = samples_from[:,:,:samples_to.shape[2] - y, :samples_to.shape[3] - x]
|
1219 |
+
else:
|
1220 |
+
samples_from = samples_from[:,:,:samples_to.shape[2] - y, :samples_to.shape[3] - x]
|
1221 |
+
mask = torch.ones_like(samples_from)
|
1222 |
+
for t in range(feather):
|
1223 |
+
if y != 0:
|
1224 |
+
mask[:,:,t:1+t,:] *= ((1.0/feather) * (t + 1))
|
1225 |
+
|
1226 |
+
if y + samples_from.shape[2] < samples_to.shape[2]:
|
1227 |
+
mask[:,:,mask.shape[2] -1 -t: mask.shape[2]-t,:] *= ((1.0/feather) * (t + 1))
|
1228 |
+
if x != 0:
|
1229 |
+
mask[:,:,:,t:1+t] *= ((1.0/feather) * (t + 1))
|
1230 |
+
if x + samples_from.shape[3] < samples_to.shape[3]:
|
1231 |
+
mask[:,:,:,mask.shape[3]- 1 - t: mask.shape[3]- t] *= ((1.0/feather) * (t + 1))
|
1232 |
+
rev_mask = torch.ones_like(mask) - mask
|
1233 |
+
s[:,:,y:y+samples_from.shape[2],x:x+samples_from.shape[3]] = samples_from[:,:,:samples_to.shape[2] - y, :samples_to.shape[3] - x] * mask + s[:,:,y:y+samples_from.shape[2],x:x+samples_from.shape[3]] * rev_mask
|
1234 |
+
samples_out["samples"] = s
|
1235 |
+
return (samples_out,)
|
1236 |
+
|
1237 |
+
class LatentBlend:
|
1238 |
+
@classmethod
|
1239 |
+
def INPUT_TYPES(s):
|
1240 |
+
return {"required": {
|
1241 |
+
"samples1": ("LATENT",),
|
1242 |
+
"samples2": ("LATENT",),
|
1243 |
+
"blend_factor": ("FLOAT", {
|
1244 |
+
"default": 0.5,
|
1245 |
+
"min": 0,
|
1246 |
+
"max": 1,
|
1247 |
+
"step": 0.01
|
1248 |
+
}),
|
1249 |
+
}}
|
1250 |
+
|
1251 |
+
RETURN_TYPES = ("LATENT",)
|
1252 |
+
FUNCTION = "blend"
|
1253 |
+
|
1254 |
+
CATEGORY = "_for_testing"
|
1255 |
+
|
1256 |
+
def blend(self, samples1, samples2, blend_factor:float, blend_mode: str="normal"):
|
1257 |
+
|
1258 |
+
samples_out = samples1.copy()
|
1259 |
+
samples1 = samples1["samples"]
|
1260 |
+
samples2 = samples2["samples"]
|
1261 |
+
|
1262 |
+
if samples1.shape != samples2.shape:
|
1263 |
+
samples2.permute(0, 3, 1, 2)
|
1264 |
+
samples2 = comfy.utils.common_upscale(samples2, samples1.shape[3], samples1.shape[2], 'bicubic', crop='center')
|
1265 |
+
samples2.permute(0, 2, 3, 1)
|
1266 |
+
|
1267 |
+
samples_blended = self.blend_mode(samples1, samples2, blend_mode)
|
1268 |
+
samples_blended = samples1 * blend_factor + samples_blended * (1 - blend_factor)
|
1269 |
+
samples_out["samples"] = samples_blended
|
1270 |
+
return (samples_out,)
|
1271 |
+
|
1272 |
+
def blend_mode(self, img1, img2, mode):
|
1273 |
+
if mode == "normal":
|
1274 |
+
return img2
|
1275 |
+
else:
|
1276 |
+
raise ValueError(f"Unsupported blend mode: {mode}")
|
1277 |
+
|
1278 |
+
class LatentCrop:
|
1279 |
+
@classmethod
|
1280 |
+
def INPUT_TYPES(s):
|
1281 |
+
return {"required": { "samples": ("LATENT",),
|
1282 |
+
"width": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
|
1283 |
+
"height": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
|
1284 |
+
"x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
1285 |
+
"y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
1286 |
+
}}
|
1287 |
+
RETURN_TYPES = ("LATENT",)
|
1288 |
+
FUNCTION = "crop"
|
1289 |
+
|
1290 |
+
CATEGORY = "latent/transform"
|
1291 |
+
|
1292 |
+
def crop(self, samples, width, height, x, y):
|
1293 |
+
s = samples.copy()
|
1294 |
+
samples = samples['samples']
|
1295 |
+
x = x // 8
|
1296 |
+
y = y // 8
|
1297 |
+
|
1298 |
+
#enfonce minimum size of 64
|
1299 |
+
if x > (samples.shape[3] - 8):
|
1300 |
+
x = samples.shape[3] - 8
|
1301 |
+
if y > (samples.shape[2] - 8):
|
1302 |
+
y = samples.shape[2] - 8
|
1303 |
+
|
1304 |
+
new_height = height // 8
|
1305 |
+
new_width = width // 8
|
1306 |
+
to_x = new_width + x
|
1307 |
+
to_y = new_height + y
|
1308 |
+
s['samples'] = samples[:,:,y:to_y, x:to_x]
|
1309 |
+
return (s,)
|
1310 |
+
|
1311 |
+
class SetLatentNoiseMask:
|
1312 |
+
@classmethod
|
1313 |
+
def INPUT_TYPES(s):
|
1314 |
+
return {"required": { "samples": ("LATENT",),
|
1315 |
+
"mask": ("MASK",),
|
1316 |
+
}}
|
1317 |
+
RETURN_TYPES = ("LATENT",)
|
1318 |
+
FUNCTION = "set_mask"
|
1319 |
+
|
1320 |
+
CATEGORY = "latent/inpaint"
|
1321 |
+
|
1322 |
+
def set_mask(self, samples, mask):
|
1323 |
+
s = samples.copy()
|
1324 |
+
s["noise_mask"] = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1]))
|
1325 |
+
return (s,)
|
1326 |
+
|
1327 |
+
def common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent, denoise=1.0, disable_noise=False, start_step=None, last_step=None, force_full_denoise=False):
|
1328 |
+
latent_image = latent["samples"]
|
1329 |
+
latent_image = comfy.sample.fix_empty_latent_channels(model, latent_image)
|
1330 |
+
|
1331 |
+
if disable_noise:
|
1332 |
+
noise = torch.zeros(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, device="cpu")
|
1333 |
+
else:
|
1334 |
+
batch_inds = latent["batch_index"] if "batch_index" in latent else None
|
1335 |
+
noise = comfy.sample.prepare_noise(latent_image, seed, batch_inds)
|
1336 |
+
|
1337 |
+
noise_mask = None
|
1338 |
+
if "noise_mask" in latent:
|
1339 |
+
noise_mask = latent["noise_mask"]
|
1340 |
+
|
1341 |
+
callback = latent_preview.prepare_callback(model, steps)
|
1342 |
+
disable_pbar = not comfy.utils.PROGRESS_BAR_ENABLED
|
1343 |
+
samples = comfy.sample.sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative, latent_image,
|
1344 |
+
denoise=denoise, disable_noise=disable_noise, start_step=start_step, last_step=last_step,
|
1345 |
+
force_full_denoise=force_full_denoise, noise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed)
|
1346 |
+
out = latent.copy()
|
1347 |
+
out["samples"] = samples
|
1348 |
+
return (out, )
|
1349 |
+
|
1350 |
+
class KSampler:
|
1351 |
+
@classmethod
|
1352 |
+
def INPUT_TYPES(s):
|
1353 |
+
return {"required":
|
1354 |
+
{"model": ("MODEL",),
|
1355 |
+
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
1356 |
+
"steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
|
1357 |
+
"cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.1, "round": 0.01}),
|
1358 |
+
"sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
|
1359 |
+
"scheduler": (comfy.samplers.KSampler.SCHEDULERS, ),
|
1360 |
+
"positive": ("CONDITIONING", ),
|
1361 |
+
"negative": ("CONDITIONING", ),
|
1362 |
+
"latent_image": ("LATENT", ),
|
1363 |
+
"denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
|
1364 |
+
}
|
1365 |
+
}
|
1366 |
+
|
1367 |
+
RETURN_TYPES = ("LATENT",)
|
1368 |
+
FUNCTION = "sample"
|
1369 |
+
|
1370 |
+
CATEGORY = "sampling"
|
1371 |
+
|
1372 |
+
def sample(self, model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=1.0):
|
1373 |
+
return common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise)
|
1374 |
+
|
1375 |
+
class KSamplerAdvanced:
|
1376 |
+
@classmethod
|
1377 |
+
def INPUT_TYPES(s):
|
1378 |
+
return {"required":
|
1379 |
+
{"model": ("MODEL",),
|
1380 |
+
"add_noise": (["enable", "disable"], ),
|
1381 |
+
"noise_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
1382 |
+
"steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
|
1383 |
+
"cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.1, "round": 0.01}),
|
1384 |
+
"sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
|
1385 |
+
"scheduler": (comfy.samplers.KSampler.SCHEDULERS, ),
|
1386 |
+
"positive": ("CONDITIONING", ),
|
1387 |
+
"negative": ("CONDITIONING", ),
|
1388 |
+
"latent_image": ("LATENT", ),
|
1389 |
+
"start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000}),
|
1390 |
+
"end_at_step": ("INT", {"default": 10000, "min": 0, "max": 10000}),
|
1391 |
+
"return_with_leftover_noise": (["disable", "enable"], ),
|
1392 |
+
}
|
1393 |
+
}
|
1394 |
+
|
1395 |
+
RETURN_TYPES = ("LATENT",)
|
1396 |
+
FUNCTION = "sample"
|
1397 |
+
|
1398 |
+
CATEGORY = "sampling"
|
1399 |
+
|
1400 |
+
def sample(self, model, add_noise, noise_seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, start_at_step, end_at_step, return_with_leftover_noise, denoise=1.0):
|
1401 |
+
force_full_denoise = True
|
1402 |
+
if return_with_leftover_noise == "enable":
|
1403 |
+
force_full_denoise = False
|
1404 |
+
disable_noise = False
|
1405 |
+
if add_noise == "disable":
|
1406 |
+
disable_noise = True
|
1407 |
+
return common_ksampler(model, noise_seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise, disable_noise=disable_noise, start_step=start_at_step, last_step=end_at_step, force_full_denoise=force_full_denoise)
|
1408 |
+
|
1409 |
+
class SaveImage:
|
1410 |
+
def __init__(self):
|
1411 |
+
self.output_dir = folder_paths.get_output_directory()
|
1412 |
+
self.type = "output"
|
1413 |
+
self.prefix_append = ""
|
1414 |
+
self.compress_level = 4
|
1415 |
+
|
1416 |
+
@classmethod
|
1417 |
+
def INPUT_TYPES(s):
|
1418 |
+
return {"required":
|
1419 |
+
{"images": ("IMAGE", ),
|
1420 |
+
"filename_prefix": ("STRING", {"default": "ComfyUI"})},
|
1421 |
+
"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
|
1422 |
+
}
|
1423 |
+
|
1424 |
+
RETURN_TYPES = ()
|
1425 |
+
FUNCTION = "save_images"
|
1426 |
+
|
1427 |
+
OUTPUT_NODE = True
|
1428 |
+
|
1429 |
+
CATEGORY = "image"
|
1430 |
+
|
1431 |
+
def save_images(self, images, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None):
|
1432 |
+
filename_prefix += self.prefix_append
|
1433 |
+
full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0])
|
1434 |
+
results = list()
|
1435 |
+
for (batch_number, image) in enumerate(images):
|
1436 |
+
i = 255. * image.cpu().numpy()
|
1437 |
+
img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
|
1438 |
+
metadata = None
|
1439 |
+
if not args.disable_metadata:
|
1440 |
+
metadata = PngInfo()
|
1441 |
+
if prompt is not None:
|
1442 |
+
metadata.add_text("prompt", json.dumps(prompt))
|
1443 |
+
if extra_pnginfo is not None:
|
1444 |
+
for x in extra_pnginfo:
|
1445 |
+
metadata.add_text(x, json.dumps(extra_pnginfo[x]))
|
1446 |
+
|
1447 |
+
filename_with_batch_num = filename.replace("%batch_num%", str(batch_number))
|
1448 |
+
file = f"{filename_with_batch_num}_{counter:05}_.png"
|
1449 |
+
img.save(os.path.join(full_output_folder, file), pnginfo=metadata, compress_level=self.compress_level)
|
1450 |
+
results.append({
|
1451 |
+
"filename": file,
|
1452 |
+
"subfolder": subfolder,
|
1453 |
+
"type": self.type
|
1454 |
+
})
|
1455 |
+
counter += 1
|
1456 |
+
|
1457 |
+
return { "ui": { "images": results } }
|
1458 |
+
|
1459 |
+
class PreviewImage(SaveImage):
|
1460 |
+
def __init__(self):
|
1461 |
+
self.output_dir = folder_paths.get_temp_directory()
|
1462 |
+
self.type = "temp"
|
1463 |
+
self.prefix_append = "_temp_" + ''.join(random.choice("abcdefghijklmnopqrstupvxyz") for x in range(5))
|
1464 |
+
self.compress_level = 1
|
1465 |
+
|
1466 |
+
@classmethod
|
1467 |
+
def INPUT_TYPES(s):
|
1468 |
+
return {"required":
|
1469 |
+
{"images": ("IMAGE", ), },
|
1470 |
+
"hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
|
1471 |
+
}
|
1472 |
+
|
1473 |
+
class LoadImage:
|
1474 |
+
@classmethod
|
1475 |
+
def INPUT_TYPES(s):
|
1476 |
+
input_dir = folder_paths.get_input_directory()
|
1477 |
+
files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
|
1478 |
+
return {"required":
|
1479 |
+
{"image": (sorted(files), {"image_upload": True})},
|
1480 |
+
}
|
1481 |
+
|
1482 |
+
CATEGORY = "image"
|
1483 |
+
|
1484 |
+
RETURN_TYPES = ("IMAGE", "MASK")
|
1485 |
+
FUNCTION = "load_image"
|
1486 |
+
def load_image(self, image):
|
1487 |
+
image_path = folder_paths.get_annotated_filepath(image)
|
1488 |
+
|
1489 |
+
img = node_helpers.pillow(Image.open, image_path)
|
1490 |
+
|
1491 |
+
output_images = []
|
1492 |
+
output_masks = []
|
1493 |
+
w, h = None, None
|
1494 |
+
|
1495 |
+
excluded_formats = ['MPO']
|
1496 |
+
|
1497 |
+
for i in ImageSequence.Iterator(img):
|
1498 |
+
i = node_helpers.pillow(ImageOps.exif_transpose, i)
|
1499 |
+
|
1500 |
+
if i.mode == 'I':
|
1501 |
+
i = i.point(lambda i: i * (1 / 255))
|
1502 |
+
image = i.convert("RGB")
|
1503 |
+
|
1504 |
+
if len(output_images) == 0:
|
1505 |
+
w = image.size[0]
|
1506 |
+
h = image.size[1]
|
1507 |
+
|
1508 |
+
if image.size[0] != w or image.size[1] != h:
|
1509 |
+
continue
|
1510 |
+
|
1511 |
+
image = np.array(image).astype(np.float32) / 255.0
|
1512 |
+
image = torch.from_numpy(image)[None,]
|
1513 |
+
if 'A' in i.getbands():
|
1514 |
+
mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
|
1515 |
+
mask = 1. - torch.from_numpy(mask)
|
1516 |
+
else:
|
1517 |
+
mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
|
1518 |
+
output_images.append(image)
|
1519 |
+
output_masks.append(mask.unsqueeze(0))
|
1520 |
+
|
1521 |
+
if len(output_images) > 1 and img.format not in excluded_formats:
|
1522 |
+
output_image = torch.cat(output_images, dim=0)
|
1523 |
+
output_mask = torch.cat(output_masks, dim=0)
|
1524 |
+
else:
|
1525 |
+
output_image = output_images[0]
|
1526 |
+
output_mask = output_masks[0]
|
1527 |
+
|
1528 |
+
return (output_image, output_mask)
|
1529 |
+
|
1530 |
+
@classmethod
|
1531 |
+
def IS_CHANGED(s, image):
|
1532 |
+
image_path = folder_paths.get_annotated_filepath(image)
|
1533 |
+
m = hashlib.sha256()
|
1534 |
+
with open(image_path, 'rb') as f:
|
1535 |
+
m.update(f.read())
|
1536 |
+
return m.digest().hex()
|
1537 |
+
|
1538 |
+
@classmethod
|
1539 |
+
def VALIDATE_INPUTS(s, image):
|
1540 |
+
if not folder_paths.exists_annotated_filepath(image):
|
1541 |
+
return "Invalid image file: {}".format(image)
|
1542 |
+
|
1543 |
+
return True
|
1544 |
+
|
1545 |
+
class LoadImageMask:
|
1546 |
+
_color_channels = ["alpha", "red", "green", "blue"]
|
1547 |
+
@classmethod
|
1548 |
+
def INPUT_TYPES(s):
|
1549 |
+
input_dir = folder_paths.get_input_directory()
|
1550 |
+
files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
|
1551 |
+
return {"required":
|
1552 |
+
{"image": (sorted(files), {"image_upload": True}),
|
1553 |
+
"channel": (s._color_channels, ), }
|
1554 |
+
}
|
1555 |
+
|
1556 |
+
CATEGORY = "mask"
|
1557 |
+
|
1558 |
+
RETURN_TYPES = ("MASK",)
|
1559 |
+
FUNCTION = "load_image"
|
1560 |
+
def load_image(self, image, channel):
|
1561 |
+
image_path = folder_paths.get_annotated_filepath(image)
|
1562 |
+
i = node_helpers.pillow(Image.open, image_path)
|
1563 |
+
i = node_helpers.pillow(ImageOps.exif_transpose, i)
|
1564 |
+
if i.getbands() != ("R", "G", "B", "A"):
|
1565 |
+
if i.mode == 'I':
|
1566 |
+
i = i.point(lambda i: i * (1 / 255))
|
1567 |
+
i = i.convert("RGBA")
|
1568 |
+
mask = None
|
1569 |
+
c = channel[0].upper()
|
1570 |
+
if c in i.getbands():
|
1571 |
+
mask = np.array(i.getchannel(c)).astype(np.float32) / 255.0
|
1572 |
+
mask = torch.from_numpy(mask)
|
1573 |
+
if c == 'A':
|
1574 |
+
mask = 1. - mask
|
1575 |
+
else:
|
1576 |
+
mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
|
1577 |
+
return (mask.unsqueeze(0),)
|
1578 |
+
|
1579 |
+
@classmethod
|
1580 |
+
def IS_CHANGED(s, image, channel):
|
1581 |
+
image_path = folder_paths.get_annotated_filepath(image)
|
1582 |
+
m = hashlib.sha256()
|
1583 |
+
with open(image_path, 'rb') as f:
|
1584 |
+
m.update(f.read())
|
1585 |
+
return m.digest().hex()
|
1586 |
+
|
1587 |
+
@classmethod
|
1588 |
+
def VALIDATE_INPUTS(s, image):
|
1589 |
+
if not folder_paths.exists_annotated_filepath(image):
|
1590 |
+
return "Invalid image file: {}".format(image)
|
1591 |
+
|
1592 |
+
return True
|
1593 |
+
|
1594 |
+
class ImageScale:
|
1595 |
+
upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
|
1596 |
+
crop_methods = ["disabled", "center"]
|
1597 |
+
|
1598 |
+
@classmethod
|
1599 |
+
def INPUT_TYPES(s):
|
1600 |
+
return {"required": { "image": ("IMAGE",), "upscale_method": (s.upscale_methods,),
|
1601 |
+
"width": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
|
1602 |
+
"height": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
|
1603 |
+
"crop": (s.crop_methods,)}}
|
1604 |
+
RETURN_TYPES = ("IMAGE",)
|
1605 |
+
FUNCTION = "upscale"
|
1606 |
+
|
1607 |
+
CATEGORY = "image/upscaling"
|
1608 |
+
|
1609 |
+
def upscale(self, image, upscale_method, width, height, crop):
|
1610 |
+
if width == 0 and height == 0:
|
1611 |
+
s = image
|
1612 |
+
else:
|
1613 |
+
samples = image.movedim(-1,1)
|
1614 |
+
|
1615 |
+
if width == 0:
|
1616 |
+
width = max(1, round(samples.shape[3] * height / samples.shape[2]))
|
1617 |
+
elif height == 0:
|
1618 |
+
height = max(1, round(samples.shape[2] * width / samples.shape[3]))
|
1619 |
+
|
1620 |
+
s = comfy.utils.common_upscale(samples, width, height, upscale_method, crop)
|
1621 |
+
s = s.movedim(1,-1)
|
1622 |
+
return (s,)
|
1623 |
+
|
1624 |
+
class ImageScaleBy:
|
1625 |
+
upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
|
1626 |
+
|
1627 |
+
@classmethod
|
1628 |
+
def INPUT_TYPES(s):
|
1629 |
+
return {"required": { "image": ("IMAGE",), "upscale_method": (s.upscale_methods,),
|
1630 |
+
"scale_by": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 8.0, "step": 0.01}),}}
|
1631 |
+
RETURN_TYPES = ("IMAGE",)
|
1632 |
+
FUNCTION = "upscale"
|
1633 |
+
|
1634 |
+
CATEGORY = "image/upscaling"
|
1635 |
+
|
1636 |
+
def upscale(self, image, upscale_method, scale_by):
|
1637 |
+
samples = image.movedim(-1,1)
|
1638 |
+
width = round(samples.shape[3] * scale_by)
|
1639 |
+
height = round(samples.shape[2] * scale_by)
|
1640 |
+
s = comfy.utils.common_upscale(samples, width, height, upscale_method, "disabled")
|
1641 |
+
s = s.movedim(1,-1)
|
1642 |
+
return (s,)
|
1643 |
+
|
1644 |
+
class ImageInvert:
|
1645 |
+
|
1646 |
+
@classmethod
|
1647 |
+
def INPUT_TYPES(s):
|
1648 |
+
return {"required": { "image": ("IMAGE",)}}
|
1649 |
+
|
1650 |
+
RETURN_TYPES = ("IMAGE",)
|
1651 |
+
FUNCTION = "invert"
|
1652 |
+
|
1653 |
+
CATEGORY = "image"
|
1654 |
+
|
1655 |
+
def invert(self, image):
|
1656 |
+
s = 1.0 - image
|
1657 |
+
return (s,)
|
1658 |
+
|
1659 |
+
class ImageBatch:
|
1660 |
+
|
1661 |
+
@classmethod
|
1662 |
+
def INPUT_TYPES(s):
|
1663 |
+
return {"required": { "image1": ("IMAGE",), "image2": ("IMAGE",)}}
|
1664 |
+
|
1665 |
+
RETURN_TYPES = ("IMAGE",)
|
1666 |
+
FUNCTION = "batch"
|
1667 |
+
|
1668 |
+
CATEGORY = "image"
|
1669 |
+
|
1670 |
+
def batch(self, image1, image2):
|
1671 |
+
if image1.shape[1:] != image2.shape[1:]:
|
1672 |
+
image2 = comfy.utils.common_upscale(image2.movedim(-1,1), image1.shape[2], image1.shape[1], "bilinear", "center").movedim(1,-1)
|
1673 |
+
s = torch.cat((image1, image2), dim=0)
|
1674 |
+
return (s,)
|
1675 |
+
|
1676 |
+
class EmptyImage:
|
1677 |
+
def __init__(self, device="cpu"):
|
1678 |
+
self.device = device
|
1679 |
+
|
1680 |
+
@classmethod
|
1681 |
+
def INPUT_TYPES(s):
|
1682 |
+
return {"required": { "width": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
|
1683 |
+
"height": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
|
1684 |
+
"batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}),
|
1685 |
+
"color": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFF, "step": 1, "display": "color"}),
|
1686 |
+
}}
|
1687 |
+
RETURN_TYPES = ("IMAGE",)
|
1688 |
+
FUNCTION = "generate"
|
1689 |
+
|
1690 |
+
CATEGORY = "image"
|
1691 |
+
|
1692 |
+
def generate(self, width, height, batch_size=1, color=0):
|
1693 |
+
r = torch.full([batch_size, height, width, 1], ((color >> 16) & 0xFF) / 0xFF)
|
1694 |
+
g = torch.full([batch_size, height, width, 1], ((color >> 8) & 0xFF) / 0xFF)
|
1695 |
+
b = torch.full([batch_size, height, width, 1], ((color) & 0xFF) / 0xFF)
|
1696 |
+
return (torch.cat((r, g, b), dim=-1), )
|
1697 |
+
|
1698 |
+
class ImagePadForOutpaint:
|
1699 |
+
|
1700 |
+
@classmethod
|
1701 |
+
def INPUT_TYPES(s):
|
1702 |
+
return {
|
1703 |
+
"required": {
|
1704 |
+
"image": ("IMAGE",),
|
1705 |
+
"left": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
1706 |
+
"top": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
1707 |
+
"right": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
1708 |
+
"bottom": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
|
1709 |
+
"feathering": ("INT", {"default": 40, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
|
1710 |
+
}
|
1711 |
+
}
|
1712 |
+
|
1713 |
+
RETURN_TYPES = ("IMAGE", "MASK")
|
1714 |
+
FUNCTION = "expand_image"
|
1715 |
+
|
1716 |
+
CATEGORY = "image"
|
1717 |
+
|
1718 |
+
def expand_image(self, image, left, top, right, bottom, feathering):
|
1719 |
+
d1, d2, d3, d4 = image.size()
|
1720 |
+
|
1721 |
+
new_image = torch.ones(
|
1722 |
+
(d1, d2 + top + bottom, d3 + left + right, d4),
|
1723 |
+
dtype=torch.float32,
|
1724 |
+
) * 0.5
|
1725 |
+
|
1726 |
+
new_image[:, top:top + d2, left:left + d3, :] = image
|
1727 |
+
|
1728 |
+
mask = torch.ones(
|
1729 |
+
(d2 + top + bottom, d3 + left + right),
|
1730 |
+
dtype=torch.float32,
|
1731 |
+
)
|
1732 |
+
|
1733 |
+
t = torch.zeros(
|
1734 |
+
(d2, d3),
|
1735 |
+
dtype=torch.float32
|
1736 |
+
)
|
1737 |
+
|
1738 |
+
if feathering > 0 and feathering * 2 < d2 and feathering * 2 < d3:
|
1739 |
+
|
1740 |
+
for i in range(d2):
|
1741 |
+
for j in range(d3):
|
1742 |
+
dt = i if top != 0 else d2
|
1743 |
+
db = d2 - i if bottom != 0 else d2
|
1744 |
+
|
1745 |
+
dl = j if left != 0 else d3
|
1746 |
+
dr = d3 - j if right != 0 else d3
|
1747 |
+
|
1748 |
+
d = min(dt, db, dl, dr)
|
1749 |
+
|
1750 |
+
if d >= feathering:
|
1751 |
+
continue
|
1752 |
+
|
1753 |
+
v = (feathering - d) / feathering
|
1754 |
+
|
1755 |
+
t[i, j] = v * v
|
1756 |
+
|
1757 |
+
mask[top:top + d2, left:left + d3] = t
|
1758 |
+
|
1759 |
+
return (new_image, mask)
|
1760 |
+
|
1761 |
+
|
1762 |
+
NODE_CLASS_MAPPINGS = {
|
1763 |
+
"KSampler": KSampler,
|
1764 |
+
"CheckpointLoaderSimple": CheckpointLoaderSimple,
|
1765 |
+
"CLIPTextEncode": CLIPTextEncode,
|
1766 |
+
"CLIPSetLastLayer": CLIPSetLastLayer,
|
1767 |
+
"VAEDecode": VAEDecode,
|
1768 |
+
"VAEEncode": VAEEncode,
|
1769 |
+
"VAEEncodeForInpaint": VAEEncodeForInpaint,
|
1770 |
+
"VAELoader": VAELoader,
|
1771 |
+
"EmptyLatentImage": EmptyLatentImage,
|
1772 |
+
"LatentUpscale": LatentUpscale,
|
1773 |
+
"LatentUpscaleBy": LatentUpscaleBy,
|
1774 |
+
"LatentFromBatch": LatentFromBatch,
|
1775 |
+
"RepeatLatentBatch": RepeatLatentBatch,
|
1776 |
+
"SaveImage": SaveImage,
|
1777 |
+
"PreviewImage": PreviewImage,
|
1778 |
+
"LoadImage": LoadImage,
|
1779 |
+
"LoadImageMask": LoadImageMask,
|
1780 |
+
"ImageScale": ImageScale,
|
1781 |
+
"ImageScaleBy": ImageScaleBy,
|
1782 |
+
"ImageInvert": ImageInvert,
|
1783 |
+
"ImageBatch": ImageBatch,
|
1784 |
+
"ImagePadForOutpaint": ImagePadForOutpaint,
|
1785 |
+
"EmptyImage": EmptyImage,
|
1786 |
+
"ConditioningAverage": ConditioningAverage ,
|
1787 |
+
"ConditioningCombine": ConditioningCombine,
|
1788 |
+
"ConditioningConcat": ConditioningConcat,
|
1789 |
+
"ConditioningSetArea": ConditioningSetArea,
|
1790 |
+
"ConditioningSetAreaPercentage": ConditioningSetAreaPercentage,
|
1791 |
+
"ConditioningSetAreaStrength": ConditioningSetAreaStrength,
|
1792 |
+
"ConditioningSetMask": ConditioningSetMask,
|
1793 |
+
"KSamplerAdvanced": KSamplerAdvanced,
|
1794 |
+
"SetLatentNoiseMask": SetLatentNoiseMask,
|
1795 |
+
"LatentComposite": LatentComposite,
|
1796 |
+
"LatentBlend": LatentBlend,
|
1797 |
+
"LatentRotate": LatentRotate,
|
1798 |
+
"LatentFlip": LatentFlip,
|
1799 |
+
"LatentCrop": LatentCrop,
|
1800 |
+
"LoraLoader": LoraLoader,
|
1801 |
+
"CLIPLoader": CLIPLoader,
|
1802 |
+
"UNETLoader": UNETLoader,
|
1803 |
+
"DualCLIPLoader": DualCLIPLoader,
|
1804 |
+
"CLIPVisionEncode": CLIPVisionEncode,
|
1805 |
+
"StyleModelApply": StyleModelApply,
|
1806 |
+
"unCLIPConditioning": unCLIPConditioning,
|
1807 |
+
"ControlNetApply": ControlNetApply,
|
1808 |
+
"ControlNetApplyAdvanced": ControlNetApplyAdvanced,
|
1809 |
+
"ControlNetLoader": ControlNetLoader,
|
1810 |
+
"DiffControlNetLoader": DiffControlNetLoader,
|
1811 |
+
"StyleModelLoader": StyleModelLoader,
|
1812 |
+
"CLIPVisionLoader": CLIPVisionLoader,
|
1813 |
+
"VAEDecodeTiled": VAEDecodeTiled,
|
1814 |
+
"VAEEncodeTiled": VAEEncodeTiled,
|
1815 |
+
"unCLIPCheckpointLoader": unCLIPCheckpointLoader,
|
1816 |
+
"GLIGENLoader": GLIGENLoader,
|
1817 |
+
"GLIGENTextBoxApply": GLIGENTextBoxApply,
|
1818 |
+
"InpaintModelConditioning": InpaintModelConditioning,
|
1819 |
+
|
1820 |
+
"CheckpointLoader": CheckpointLoader,
|
1821 |
+
"DiffusersLoader": DiffusersLoader,
|
1822 |
+
|
1823 |
+
"LoadLatent": LoadLatent,
|
1824 |
+
"SaveLatent": SaveLatent,
|
1825 |
+
|
1826 |
+
"ConditioningZeroOut": ConditioningZeroOut,
|
1827 |
+
"ConditioningSetTimestepRange": ConditioningSetTimestepRange,
|
1828 |
+
"LoraLoaderModelOnly": LoraLoaderModelOnly,
|
1829 |
+
}
|
1830 |
+
|
1831 |
+
NODE_DISPLAY_NAME_MAPPINGS = {
|
1832 |
+
# Sampling
|
1833 |
+
"KSampler": "KSampler",
|
1834 |
+
"KSamplerAdvanced": "KSampler (Advanced)",
|
1835 |
+
# Loaders
|
1836 |
+
"CheckpointLoader": "Load Checkpoint With Config (DEPRECATED)",
|
1837 |
+
"CheckpointLoaderSimple": "Load Checkpoint",
|
1838 |
+
"VAELoader": "Load VAE",
|
1839 |
+
"LoraLoader": "Load LoRA",
|
1840 |
+
"CLIPLoader": "Load CLIP",
|
1841 |
+
"ControlNetLoader": "Load ControlNet Model",
|
1842 |
+
"DiffControlNetLoader": "Load ControlNet Model (diff)",
|
1843 |
+
"StyleModelLoader": "Load Style Model",
|
1844 |
+
"CLIPVisionLoader": "Load CLIP Vision",
|
1845 |
+
"UpscaleModelLoader": "Load Upscale Model",
|
1846 |
+
# Conditioning
|
1847 |
+
"CLIPVisionEncode": "CLIP Vision Encode",
|
1848 |
+
"StyleModelApply": "Apply Style Model",
|
1849 |
+
"CLIPTextEncode": "CLIP Text Encode (Prompt)",
|
1850 |
+
"CLIPSetLastLayer": "CLIP Set Last Layer",
|
1851 |
+
"ConditioningCombine": "Conditioning (Combine)",
|
1852 |
+
"ConditioningAverage ": "Conditioning (Average)",
|
1853 |
+
"ConditioningConcat": "Conditioning (Concat)",
|
1854 |
+
"ConditioningSetArea": "Conditioning (Set Area)",
|
1855 |
+
"ConditioningSetAreaPercentage": "Conditioning (Set Area with Percentage)",
|
1856 |
+
"ConditioningSetMask": "Conditioning (Set Mask)",
|
1857 |
+
"ControlNetApply": "Apply ControlNet",
|
1858 |
+
"ControlNetApplyAdvanced": "Apply ControlNet (Advanced)",
|
1859 |
+
# Latent
|
1860 |
+
"VAEEncodeForInpaint": "VAE Encode (for Inpainting)",
|
1861 |
+
"SetLatentNoiseMask": "Set Latent Noise Mask",
|
1862 |
+
"VAEDecode": "VAE Decode",
|
1863 |
+
"VAEEncode": "VAE Encode",
|
1864 |
+
"LatentRotate": "Rotate Latent",
|
1865 |
+
"LatentFlip": "Flip Latent",
|
1866 |
+
"LatentCrop": "Crop Latent",
|
1867 |
+
"EmptyLatentImage": "Empty Latent Image",
|
1868 |
+
"LatentUpscale": "Upscale Latent",
|
1869 |
+
"LatentUpscaleBy": "Upscale Latent By",
|
1870 |
+
"LatentComposite": "Latent Composite",
|
1871 |
+
"LatentBlend": "Latent Blend",
|
1872 |
+
"LatentFromBatch" : "Latent From Batch",
|
1873 |
+
"RepeatLatentBatch": "Repeat Latent Batch",
|
1874 |
+
# Image
|
1875 |
+
"SaveImage": "Save Image",
|
1876 |
+
"PreviewImage": "Preview Image",
|
1877 |
+
"LoadImage": "Load Image",
|
1878 |
+
"LoadImageMask": "Load Image (as Mask)",
|
1879 |
+
"ImageScale": "Upscale Image",
|
1880 |
+
"ImageScaleBy": "Upscale Image By",
|
1881 |
+
"ImageUpscaleWithModel": "Upscale Image (using Model)",
|
1882 |
+
"ImageInvert": "Invert Image",
|
1883 |
+
"ImagePadForOutpaint": "Pad Image for Outpainting",
|
1884 |
+
"ImageBatch": "Batch Images",
|
1885 |
+
# _for_testing
|
1886 |
+
"VAEDecodeTiled": "VAE Decode (Tiled)",
|
1887 |
+
"VAEEncodeTiled": "VAE Encode (Tiled)",
|
1888 |
+
}
|
1889 |
+
|
1890 |
+
EXTENSION_WEB_DIRS = {}
|
1891 |
+
|
1892 |
+
|
1893 |
+
def get_module_name(module_path: str) -> str:
|
1894 |
+
"""
|
1895 |
+
Returns the module name based on the given module path.
|
1896 |
+
Examples:
|
1897 |
+
get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node.py") -> "my_custom_node"
|
1898 |
+
get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node") -> "my_custom_node"
|
1899 |
+
get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/") -> "my_custom_node"
|
1900 |
+
get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/__init__.py") -> "my_custom_node"
|
1901 |
+
get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/__init__") -> "my_custom_node"
|
1902 |
+
get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/__init__/") -> "my_custom_node"
|
1903 |
+
get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node.disabled") -> "custom_nodes
|
1904 |
+
Args:
|
1905 |
+
module_path (str): The path of the module.
|
1906 |
+
Returns:
|
1907 |
+
str: The module name.
|
1908 |
+
"""
|
1909 |
+
base_path = os.path.basename(module_path)
|
1910 |
+
if os.path.isfile(module_path):
|
1911 |
+
base_path = os.path.splitext(base_path)[0]
|
1912 |
+
return base_path
|
1913 |
+
|
1914 |
+
|
1915 |
+
def load_custom_node(module_path: str, ignore=set(), module_parent="custom_nodes") -> bool:
|
1916 |
+
module_name = os.path.basename(module_path)
|
1917 |
+
if os.path.isfile(module_path):
|
1918 |
+
sp = os.path.splitext(module_path)
|
1919 |
+
module_name = sp[0]
|
1920 |
+
try:
|
1921 |
+
logging.debug("Trying to load custom node {}".format(module_path))
|
1922 |
+
if os.path.isfile(module_path):
|
1923 |
+
module_spec = importlib.util.spec_from_file_location(module_name, module_path)
|
1924 |
+
module_dir = os.path.split(module_path)[0]
|
1925 |
+
else:
|
1926 |
+
module_spec = importlib.util.spec_from_file_location(module_name, os.path.join(module_path, "__init__.py"))
|
1927 |
+
module_dir = module_path
|
1928 |
+
|
1929 |
+
module = importlib.util.module_from_spec(module_spec)
|
1930 |
+
sys.modules[module_name] = module
|
1931 |
+
module_spec.loader.exec_module(module)
|
1932 |
+
|
1933 |
+
if hasattr(module, "WEB_DIRECTORY") and getattr(module, "WEB_DIRECTORY") is not None:
|
1934 |
+
web_dir = os.path.abspath(os.path.join(module_dir, getattr(module, "WEB_DIRECTORY")))
|
1935 |
+
if os.path.isdir(web_dir):
|
1936 |
+
EXTENSION_WEB_DIRS[module_name] = web_dir
|
1937 |
+
|
1938 |
+
if hasattr(module, "NODE_CLASS_MAPPINGS") and getattr(module, "NODE_CLASS_MAPPINGS") is not None:
|
1939 |
+
for name, node_cls in module.NODE_CLASS_MAPPINGS.items():
|
1940 |
+
if name not in ignore:
|
1941 |
+
NODE_CLASS_MAPPINGS[name] = node_cls
|
1942 |
+
node_cls.RELATIVE_PYTHON_MODULE = "{}.{}".format(module_parent, get_module_name(module_path))
|
1943 |
+
if hasattr(module, "NODE_DISPLAY_NAME_MAPPINGS") and getattr(module, "NODE_DISPLAY_NAME_MAPPINGS") is not None:
|
1944 |
+
NODE_DISPLAY_NAME_MAPPINGS.update(module.NODE_DISPLAY_NAME_MAPPINGS)
|
1945 |
+
return True
|
1946 |
+
else:
|
1947 |
+
logging.warning(f"Skip {module_path} module for custom nodes due to the lack of NODE_CLASS_MAPPINGS.")
|
1948 |
+
return False
|
1949 |
+
except Exception as e:
|
1950 |
+
logging.warning(traceback.format_exc())
|
1951 |
+
logging.warning(f"Cannot import {module_path} module for custom nodes: {e}")
|
1952 |
+
return False
|
1953 |
+
|
1954 |
+
def init_external_custom_nodes():
|
1955 |
+
"""
|
1956 |
+
Initializes the external custom nodes.
|
1957 |
+
|
1958 |
+
This function loads custom nodes from the specified folder paths and imports them into the application.
|
1959 |
+
It measures the import times for each custom node and logs the results.
|
1960 |
+
|
1961 |
+
Returns:
|
1962 |
+
None
|
1963 |
+
"""
|
1964 |
+
base_node_names = set(NODE_CLASS_MAPPINGS.keys())
|
1965 |
+
node_paths = folder_paths.get_folder_paths("custom_nodes")
|
1966 |
+
node_import_times = []
|
1967 |
+
for custom_node_path in node_paths:
|
1968 |
+
possible_modules = os.listdir(os.path.realpath(custom_node_path))
|
1969 |
+
if "__pycache__" in possible_modules:
|
1970 |
+
possible_modules.remove("__pycache__")
|
1971 |
+
|
1972 |
+
for possible_module in possible_modules:
|
1973 |
+
module_path = os.path.join(custom_node_path, possible_module)
|
1974 |
+
if os.path.isfile(module_path) and os.path.splitext(module_path)[1] != ".py": continue
|
1975 |
+
if module_path.endswith(".disabled"): continue
|
1976 |
+
time_before = time.perf_counter()
|
1977 |
+
success = load_custom_node(module_path, base_node_names, module_parent="custom_nodes")
|
1978 |
+
node_import_times.append((time.perf_counter() - time_before, module_path, success))
|
1979 |
+
|
1980 |
+
if len(node_import_times) > 0:
|
1981 |
+
logging.info("\nImport times for custom nodes:")
|
1982 |
+
for n in sorted(node_import_times):
|
1983 |
+
if n[2]:
|
1984 |
+
import_message = ""
|
1985 |
+
else:
|
1986 |
+
import_message = " (IMPORT FAILED)"
|
1987 |
+
logging.info("{:6.1f} seconds{}: {}".format(n[0], import_message, n[1]))
|
1988 |
+
logging.info("")
|
1989 |
+
|
1990 |
+
def init_builtin_extra_nodes():
|
1991 |
+
"""
|
1992 |
+
Initializes the built-in extra nodes in ComfyUI.
|
1993 |
+
|
1994 |
+
This function loads the extra node files located in the "comfy_extras" directory and imports them into ComfyUI.
|
1995 |
+
If any of the extra node files fail to import, a warning message is logged.
|
1996 |
+
|
1997 |
+
Returns:
|
1998 |
+
None
|
1999 |
+
"""
|
2000 |
+
extras_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras")
|
2001 |
+
extras_files = [
|
2002 |
+
"nodes_latent.py",
|
2003 |
+
"nodes_hypernetwork.py",
|
2004 |
+
"nodes_upscale_model.py",
|
2005 |
+
"nodes_post_processing.py",
|
2006 |
+
"nodes_mask.py",
|
2007 |
+
"nodes_compositing.py",
|
2008 |
+
"nodes_rebatch.py",
|
2009 |
+
"nodes_model_merging.py",
|
2010 |
+
"nodes_tomesd.py",
|
2011 |
+
"nodes_clip_sdxl.py",
|
2012 |
+
"nodes_canny.py",
|
2013 |
+
"nodes_freelunch.py",
|
2014 |
+
"nodes_custom_sampler.py",
|
2015 |
+
"nodes_hypertile.py",
|
2016 |
+
"nodes_model_advanced.py",
|
2017 |
+
"nodes_model_downscale.py",
|
2018 |
+
"nodes_images.py",
|
2019 |
+
"nodes_video_model.py",
|
2020 |
+
"nodes_sag.py",
|
2021 |
+
"nodes_perpneg.py",
|
2022 |
+
"nodes_stable3d.py",
|
2023 |
+
"nodes_sdupscale.py",
|
2024 |
+
"nodes_photomaker.py",
|
2025 |
+
"nodes_cond.py",
|
2026 |
+
"nodes_morphology.py",
|
2027 |
+
"nodes_stable_cascade.py",
|
2028 |
+
"nodes_differential_diffusion.py",
|
2029 |
+
"nodes_ip2p.py",
|
2030 |
+
"nodes_model_merging_model_specific.py",
|
2031 |
+
"nodes_pag.py",
|
2032 |
+
"nodes_align_your_steps.py",
|
2033 |
+
"nodes_attention_multiply.py",
|
2034 |
+
"nodes_advanced_samplers.py",
|
2035 |
+
"nodes_webcam.py",
|
2036 |
+
"nodes_audio.py",
|
2037 |
+
"nodes_sd3.py",
|
2038 |
+
"nodes_gits.py",
|
2039 |
+
"nodes_controlnet.py",
|
2040 |
+
"nodes_hunyuan.py",
|
2041 |
+
]
|
2042 |
+
|
2043 |
+
import_failed = []
|
2044 |
+
for node_file in extras_files:
|
2045 |
+
if not load_custom_node(os.path.join(extras_dir, node_file), module_parent="comfy_extras"):
|
2046 |
+
import_failed.append(node_file)
|
2047 |
+
|
2048 |
+
return import_failed
|
2049 |
+
|
2050 |
+
|
2051 |
+
def init_extra_nodes(init_custom_nodes=True):
|
2052 |
+
import_failed = init_builtin_extra_nodes()
|
2053 |
+
|
2054 |
+
if init_custom_nodes:
|
2055 |
+
init_external_custom_nodes()
|
2056 |
+
else:
|
2057 |
+
logging.info("Skipping loading of custom nodes")
|
2058 |
+
|
2059 |
+
if len(import_failed) > 0:
|
2060 |
+
logging.warning("WARNING: some comfy_extras/ nodes did not import correctly. This may be because they are missing some dependencies.\n")
|
2061 |
+
for node in import_failed:
|
2062 |
+
logging.warning("IMPORT FAILED: {}".format(node))
|
2063 |
+
logging.warning("\nThis issue might be caused by new missing dependencies added the last time you updated ComfyUI.")
|
2064 |
+
if args.windows_standalone_build:
|
2065 |
+
logging.warning("Please run the update script: update/update_comfyui.bat")
|
2066 |
+
else:
|
2067 |
+
logging.warning("Please do a: pip install -r requirements.txt")
|
2068 |
+
logging.warning("")
|
ComfyUI/pytest.ini
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
[pytest]
|
2 |
+
markers =
|
3 |
+
inference: mark as inference test (deselect with '-m "not inference"')
|
4 |
+
testpaths =
|
5 |
+
tests
|
6 |
+
tests-unit
|
7 |
+
addopts = -s
|
8 |
+
pythonpath = .
|
ComfyUI/requirements.txt
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch
|
2 |
+
torchsde
|
3 |
+
torchvision
|
4 |
+
torchaudio
|
5 |
+
einops
|
6 |
+
transformers>=4.28.1
|
7 |
+
tokenizers>=0.13.3
|
8 |
+
sentencepiece
|
9 |
+
safetensors>=0.4.2
|
10 |
+
aiohttp
|
11 |
+
pyyaml
|
12 |
+
Pillow
|
13 |
+
scipy
|
14 |
+
tqdm
|
15 |
+
psutil
|
16 |
+
|
17 |
+
#non essential dependencies:
|
18 |
+
kornia>=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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
import asyncio
|
4 |
+
import traceback
|
5 |
+
|
6 |
+
import nodes
|
7 |
+
import folder_paths
|
8 |
+
import execution
|
9 |
+
import uuid
|
10 |
+
import urllib
|
11 |
+
import json
|
12 |
+
import glob
|
13 |
+
import struct
|
14 |
+
import ssl
|
15 |
+
import hashlib
|
16 |
+
from PIL import Image, ImageOps
|
17 |
+
from PIL.PngImagePlugin import PngInfo
|
18 |
+
from io import BytesIO
|
19 |
+
|
20 |
+
import aiohttp
|
21 |
+
from aiohttp import web
|
22 |
+
import logging
|
23 |
+
|
24 |
+
import mimetypes
|
25 |
+
from comfy.cli_args import args
|
26 |
+
import comfy.utils
|
27 |
+
import comfy.model_management
|
28 |
+
import node_helpers
|
29 |
+
from app.frontend_management import FrontendManager
|
30 |
+
from app.user_manager import UserManager
|
31 |
+
|
32 |
+
|
33 |
+
class BinaryEventTypes:
|
34 |
+
PREVIEW_IMAGE = 1
|
35 |
+
UNENCODED_PREVIEW_IMAGE = 2
|
36 |
+
|
37 |
+
async def send_socket_catch_exception(function, message):
|
38 |
+
try:
|
39 |
+
await function(message)
|
40 |
+
except (aiohttp.ClientError, aiohttp.ClientPayloadError, ConnectionResetError) as err:
|
41 |
+
logging.warning("send error: {}".format(err))
|
42 |
+
|
43 |
+
@web.middleware
|
44 |
+
async def cache_control(request: web.Request, handler):
|
45 |
+
response: web.Response = await handler(request)
|
46 |
+
if request.path.endswith('.js') or request.path.endswith('.css'):
|
47 |
+
response.headers.setdefault('Cache-Control', 'no-cache')
|
48 |
+
return response
|
49 |
+
|
50 |
+
def create_cors_middleware(allowed_origin: str):
|
51 |
+
@web.middleware
|
52 |
+
async def cors_middleware(request: web.Request, handler):
|
53 |
+
if request.method == "OPTIONS":
|
54 |
+
# Pre-flight request. Reply successfully:
|
55 |
+
response = web.Response()
|
56 |
+
else:
|
57 |
+
response = await handler(request)
|
58 |
+
|
59 |
+
response.headers['Access-Control-Allow-Origin'] = allowed_origin
|
60 |
+
response.headers['Access-Control-Allow-Methods'] = 'POST, GET, DELETE, PUT, OPTIONS'
|
61 |
+
response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
|
62 |
+
response.headers['Access-Control-Allow-Credentials'] = 'true'
|
63 |
+
return response
|
64 |
+
|
65 |
+
return cors_middleware
|
66 |
+
|
67 |
+
class PromptServer():
|
68 |
+
def __init__(self, loop):
|
69 |
+
PromptServer.instance = self
|
70 |
+
|
71 |
+
mimetypes.init()
|
72 |
+
mimetypes.types_map['.js'] = 'application/javascript; charset=utf-8'
|
73 |
+
|
74 |
+
self.user_manager = UserManager()
|
75 |
+
self.supports = ["custom_nodes_from_web"]
|
76 |
+
self.prompt_queue = None
|
77 |
+
self.loop = loop
|
78 |
+
self.messages = asyncio.Queue()
|
79 |
+
self.number = 0
|
80 |
+
|
81 |
+
middlewares = [cache_control]
|
82 |
+
if args.enable_cors_header:
|
83 |
+
middlewares.append(create_cors_middleware(args.enable_cors_header))
|
84 |
+
|
85 |
+
max_upload_size = round(args.max_upload_size * 1024 * 1024)
|
86 |
+
self.app = web.Application(client_max_size=max_upload_size, middlewares=middlewares)
|
87 |
+
self.sockets = dict()
|
88 |
+
self.web_root = (
|
89 |
+
FrontendManager.init_frontend(args.front_end_version)
|
90 |
+
if args.front_end_root is None
|
91 |
+
else args.front_end_root
|
92 |
+
)
|
93 |
+
logging.info(f"[Prompt Server] web root: {self.web_root}")
|
94 |
+
routes = web.RouteTableDef()
|
95 |
+
self.routes = routes
|
96 |
+
self.last_node_id = None
|
97 |
+
self.client_id = None
|
98 |
+
|
99 |
+
self.on_prompt_handlers = []
|
100 |
+
|
101 |
+
@routes.get('/ws')
|
102 |
+
async def websocket_handler(request):
|
103 |
+
ws = web.WebSocketResponse()
|
104 |
+
await ws.prepare(request)
|
105 |
+
sid = request.rel_url.query.get('clientId', '')
|
106 |
+
if sid:
|
107 |
+
# Reusing existing session, remove old
|
108 |
+
self.sockets.pop(sid, None)
|
109 |
+
else:
|
110 |
+
sid = uuid.uuid4().hex
|
111 |
+
|
112 |
+
self.sockets[sid] = ws
|
113 |
+
|
114 |
+
try:
|
115 |
+
# Send initial state to the new client
|
116 |
+
await self.send("status", { "status": self.get_queue_info(), 'sid': sid }, sid)
|
117 |
+
# On reconnect if we are the currently executing client send the current node
|
118 |
+
if self.client_id == sid and self.last_node_id is not None:
|
119 |
+
await self.send("executing", { "node": self.last_node_id }, sid)
|
120 |
+
|
121 |
+
async for msg in ws:
|
122 |
+
if msg.type == aiohttp.WSMsgType.ERROR:
|
123 |
+
logging.warning('ws connection closed with exception %s' % ws.exception())
|
124 |
+
finally:
|
125 |
+
self.sockets.pop(sid, None)
|
126 |
+
return ws
|
127 |
+
|
128 |
+
@routes.get("/")
|
129 |
+
async def get_root(request):
|
130 |
+
return web.FileResponse(os.path.join(self.web_root, "index.html"))
|
131 |
+
|
132 |
+
@routes.get("/embeddings")
|
133 |
+
def get_embeddings(self):
|
134 |
+
embeddings = folder_paths.get_filename_list("embeddings")
|
135 |
+
return web.json_response(list(map(lambda a: os.path.splitext(a)[0], embeddings)))
|
136 |
+
|
137 |
+
@routes.get("/extensions")
|
138 |
+
async def get_extensions(request):
|
139 |
+
files = glob.glob(os.path.join(
|
140 |
+
glob.escape(self.web_root), 'extensions/**/*.js'), recursive=True)
|
141 |
+
|
142 |
+
extensions = list(map(lambda f: "/" + os.path.relpath(f, self.web_root).replace("\\", "/"), files))
|
143 |
+
|
144 |
+
for name, dir in nodes.EXTENSION_WEB_DIRS.items():
|
145 |
+
files = glob.glob(os.path.join(glob.escape(dir), '**/*.js'), recursive=True)
|
146 |
+
extensions.extend(list(map(lambda f: "/extensions/" + urllib.parse.quote(
|
147 |
+
name) + "/" + os.path.relpath(f, dir).replace("\\", "/"), files)))
|
148 |
+
|
149 |
+
return web.json_response(extensions)
|
150 |
+
|
151 |
+
def get_dir_by_type(dir_type):
|
152 |
+
if dir_type is None:
|
153 |
+
dir_type = "input"
|
154 |
+
|
155 |
+
if dir_type == "input":
|
156 |
+
type_dir = folder_paths.get_input_directory()
|
157 |
+
elif dir_type == "temp":
|
158 |
+
type_dir = folder_paths.get_temp_directory()
|
159 |
+
elif dir_type == "output":
|
160 |
+
type_dir = folder_paths.get_output_directory()
|
161 |
+
|
162 |
+
return type_dir, dir_type
|
163 |
+
|
164 |
+
def compare_image_hash(filepath, image):
|
165 |
+
hasher = node_helpers.hasher()
|
166 |
+
|
167 |
+
# function to compare hashes of two images to see if it already exists, fix to #3465
|
168 |
+
if os.path.exists(filepath):
|
169 |
+
a = hasher()
|
170 |
+
b = hasher()
|
171 |
+
with open(filepath, "rb") as f:
|
172 |
+
a.update(f.read())
|
173 |
+
b.update(image.file.read())
|
174 |
+
image.file.seek(0)
|
175 |
+
f.close()
|
176 |
+
return a.hexdigest() == b.hexdigest()
|
177 |
+
return False
|
178 |
+
|
179 |
+
def image_upload(post, image_save_function=None):
|
180 |
+
image = post.get("image")
|
181 |
+
overwrite = post.get("overwrite")
|
182 |
+
image_is_duplicate = False
|
183 |
+
|
184 |
+
image_upload_type = post.get("type")
|
185 |
+
upload_dir, image_upload_type = get_dir_by_type(image_upload_type)
|
186 |
+
|
187 |
+
if image and image.file:
|
188 |
+
filename = image.filename
|
189 |
+
if not filename:
|
190 |
+
return web.Response(status=400)
|
191 |
+
|
192 |
+
subfolder = post.get("subfolder", "")
|
193 |
+
full_output_folder = os.path.join(upload_dir, os.path.normpath(subfolder))
|
194 |
+
filepath = os.path.abspath(os.path.join(full_output_folder, filename))
|
195 |
+
|
196 |
+
if os.path.commonpath((upload_dir, filepath)) != upload_dir:
|
197 |
+
return web.Response(status=400)
|
198 |
+
|
199 |
+
if not os.path.exists(full_output_folder):
|
200 |
+
os.makedirs(full_output_folder)
|
201 |
+
|
202 |
+
split = os.path.splitext(filename)
|
203 |
+
|
204 |
+
if overwrite is not None and (overwrite == "true" or overwrite == "1"):
|
205 |
+
pass
|
206 |
+
else:
|
207 |
+
i = 1
|
208 |
+
while os.path.exists(filepath):
|
209 |
+
if compare_image_hash(filepath, image): #compare hash to prevent saving of duplicates with same name, fix for #3465
|
210 |
+
image_is_duplicate = True
|
211 |
+
break
|
212 |
+
filename = f"{split[0]} ({i}){split[1]}"
|
213 |
+
filepath = os.path.join(full_output_folder, filename)
|
214 |
+
i += 1
|
215 |
+
|
216 |
+
if not image_is_duplicate:
|
217 |
+
if image_save_function is not None:
|
218 |
+
image_save_function(image, post, filepath)
|
219 |
+
else:
|
220 |
+
with open(filepath, "wb") as f:
|
221 |
+
f.write(image.file.read())
|
222 |
+
|
223 |
+
return web.json_response({"name" : filename, "subfolder": subfolder, "type": image_upload_type})
|
224 |
+
else:
|
225 |
+
return web.Response(status=400)
|
226 |
+
|
227 |
+
@routes.post("/upload/image")
|
228 |
+
async def upload_image(request):
|
229 |
+
post = await request.post()
|
230 |
+
return image_upload(post)
|
231 |
+
|
232 |
+
|
233 |
+
@routes.post("/upload/mask")
|
234 |
+
async def upload_mask(request):
|
235 |
+
post = await request.post()
|
236 |
+
|
237 |
+
def image_save_function(image, post, filepath):
|
238 |
+
original_ref = json.loads(post.get("original_ref"))
|
239 |
+
filename, output_dir = folder_paths.annotated_filepath(original_ref['filename'])
|
240 |
+
|
241 |
+
# validation for security: prevent accessing arbitrary path
|
242 |
+
if filename[0] == '/' or '..' in filename:
|
243 |
+
return web.Response(status=400)
|
244 |
+
|
245 |
+
if output_dir is None:
|
246 |
+
type = original_ref.get("type", "output")
|
247 |
+
output_dir = folder_paths.get_directory_by_type(type)
|
248 |
+
|
249 |
+
if output_dir is None:
|
250 |
+
return web.Response(status=400)
|
251 |
+
|
252 |
+
if original_ref.get("subfolder", "") != "":
|
253 |
+
full_output_dir = os.path.join(output_dir, original_ref["subfolder"])
|
254 |
+
if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir:
|
255 |
+
return web.Response(status=403)
|
256 |
+
output_dir = full_output_dir
|
257 |
+
|
258 |
+
file = os.path.join(output_dir, filename)
|
259 |
+
|
260 |
+
if os.path.isfile(file):
|
261 |
+
with Image.open(file) as original_pil:
|
262 |
+
metadata = PngInfo()
|
263 |
+
if hasattr(original_pil,'text'):
|
264 |
+
for key in original_pil.text:
|
265 |
+
metadata.add_text(key, original_pil.text[key])
|
266 |
+
original_pil = original_pil.convert('RGBA')
|
267 |
+
mask_pil = Image.open(image.file).convert('RGBA')
|
268 |
+
|
269 |
+
# alpha copy
|
270 |
+
new_alpha = mask_pil.getchannel('A')
|
271 |
+
original_pil.putalpha(new_alpha)
|
272 |
+
original_pil.save(filepath, compress_level=4, pnginfo=metadata)
|
273 |
+
|
274 |
+
return image_upload(post, image_save_function)
|
275 |
+
|
276 |
+
@routes.get("/view")
|
277 |
+
async def view_image(request):
|
278 |
+
if "filename" in request.rel_url.query:
|
279 |
+
filename = request.rel_url.query["filename"]
|
280 |
+
filename,output_dir = folder_paths.annotated_filepath(filename)
|
281 |
+
|
282 |
+
# validation for security: prevent accessing arbitrary path
|
283 |
+
if filename[0] == '/' or '..' in filename:
|
284 |
+
return web.Response(status=400)
|
285 |
+
|
286 |
+
if output_dir is None:
|
287 |
+
type = request.rel_url.query.get("type", "output")
|
288 |
+
output_dir = folder_paths.get_directory_by_type(type)
|
289 |
+
|
290 |
+
if output_dir is None:
|
291 |
+
return web.Response(status=400)
|
292 |
+
|
293 |
+
if "subfolder" in request.rel_url.query:
|
294 |
+
full_output_dir = os.path.join(output_dir, request.rel_url.query["subfolder"])
|
295 |
+
if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir:
|
296 |
+
return web.Response(status=403)
|
297 |
+
output_dir = full_output_dir
|
298 |
+
|
299 |
+
filename = os.path.basename(filename)
|
300 |
+
file = os.path.join(output_dir, filename)
|
301 |
+
|
302 |
+
if os.path.isfile(file):
|
303 |
+
if 'preview' in request.rel_url.query:
|
304 |
+
with Image.open(file) as img:
|
305 |
+
preview_info = request.rel_url.query['preview'].split(';')
|
306 |
+
image_format = preview_info[0]
|
307 |
+
if image_format not in ['webp', 'jpeg'] or 'a' in request.rel_url.query.get('channel', ''):
|
308 |
+
image_format = 'webp'
|
309 |
+
|
310 |
+
quality = 90
|
311 |
+
if preview_info[-1].isdigit():
|
312 |
+
quality = int(preview_info[-1])
|
313 |
+
|
314 |
+
buffer = BytesIO()
|
315 |
+
if image_format in ['jpeg'] or request.rel_url.query.get('channel', '') == 'rgb':
|
316 |
+
img = img.convert("RGB")
|
317 |
+
img.save(buffer, format=image_format, quality=quality)
|
318 |
+
buffer.seek(0)
|
319 |
+
|
320 |
+
return web.Response(body=buffer.read(), content_type=f'image/{image_format}',
|
321 |
+
headers={"Content-Disposition": f"filename=\"{filename}\""})
|
322 |
+
|
323 |
+
if 'channel' not in request.rel_url.query:
|
324 |
+
channel = 'rgba'
|
325 |
+
else:
|
326 |
+
channel = request.rel_url.query["channel"]
|
327 |
+
|
328 |
+
if channel == 'rgb':
|
329 |
+
with Image.open(file) as img:
|
330 |
+
if img.mode == "RGBA":
|
331 |
+
r, g, b, a = img.split()
|
332 |
+
new_img = Image.merge('RGB', (r, g, b))
|
333 |
+
else:
|
334 |
+
new_img = img.convert("RGB")
|
335 |
+
|
336 |
+
buffer = BytesIO()
|
337 |
+
new_img.save(buffer, format='PNG')
|
338 |
+
buffer.seek(0)
|
339 |
+
|
340 |
+
return web.Response(body=buffer.read(), content_type='image/png',
|
341 |
+
headers={"Content-Disposition": f"filename=\"{filename}\""})
|
342 |
+
|
343 |
+
elif channel == 'a':
|
344 |
+
with Image.open(file) as img:
|
345 |
+
if img.mode == "RGBA":
|
346 |
+
_, _, _, a = img.split()
|
347 |
+
else:
|
348 |
+
a = Image.new('L', img.size, 255)
|
349 |
+
|
350 |
+
# alpha img
|
351 |
+
alpha_img = Image.new('RGBA', img.size)
|
352 |
+
alpha_img.putalpha(a)
|
353 |
+
alpha_buffer = BytesIO()
|
354 |
+
alpha_img.save(alpha_buffer, format='PNG')
|
355 |
+
alpha_buffer.seek(0)
|
356 |
+
|
357 |
+
return web.Response(body=alpha_buffer.read(), content_type='image/png',
|
358 |
+
headers={"Content-Disposition": f"filename=\"{filename}\""})
|
359 |
+
else:
|
360 |
+
return web.FileResponse(file, headers={"Content-Disposition": f"filename=\"{filename}\""})
|
361 |
+
|
362 |
+
return web.Response(status=404)
|
363 |
+
|
364 |
+
@routes.get("/view_metadata/{folder_name}")
|
365 |
+
async def view_metadata(request):
|
366 |
+
folder_name = request.match_info.get("folder_name", None)
|
367 |
+
if folder_name is None:
|
368 |
+
return web.Response(status=404)
|
369 |
+
if not "filename" in request.rel_url.query:
|
370 |
+
return web.Response(status=404)
|
371 |
+
|
372 |
+
filename = request.rel_url.query["filename"]
|
373 |
+
if not filename.endswith(".safetensors"):
|
374 |
+
return web.Response(status=404)
|
375 |
+
|
376 |
+
safetensors_path = folder_paths.get_full_path(folder_name, filename)
|
377 |
+
if safetensors_path is None:
|
378 |
+
return web.Response(status=404)
|
379 |
+
out = comfy.utils.safetensors_header(safetensors_path, max_size=1024*1024)
|
380 |
+
if out is None:
|
381 |
+
return web.Response(status=404)
|
382 |
+
dt = json.loads(out)
|
383 |
+
if not "__metadata__" in dt:
|
384 |
+
return web.Response(status=404)
|
385 |
+
return web.json_response(dt["__metadata__"])
|
386 |
+
|
387 |
+
@routes.get("/system_stats")
|
388 |
+
async def get_queue(request):
|
389 |
+
device = comfy.model_management.get_torch_device()
|
390 |
+
device_name = comfy.model_management.get_torch_device_name(device)
|
391 |
+
vram_total, torch_vram_total = comfy.model_management.get_total_memory(device, torch_total_too=True)
|
392 |
+
vram_free, torch_vram_free = comfy.model_management.get_free_memory(device, torch_free_too=True)
|
393 |
+
system_stats = {
|
394 |
+
"system": {
|
395 |
+
"os": os.name,
|
396 |
+
"python_version": sys.version,
|
397 |
+
"embedded_python": os.path.split(os.path.split(sys.executable)[0])[1] == "python_embeded"
|
398 |
+
},
|
399 |
+
"devices": [
|
400 |
+
{
|
401 |
+
"name": device_name,
|
402 |
+
"type": device.type,
|
403 |
+
"index": device.index,
|
404 |
+
"vram_total": vram_total,
|
405 |
+
"vram_free": vram_free,
|
406 |
+
"torch_vram_total": torch_vram_total,
|
407 |
+
"torch_vram_free": torch_vram_free,
|
408 |
+
}
|
409 |
+
]
|
410 |
+
}
|
411 |
+
return web.json_response(system_stats)
|
412 |
+
|
413 |
+
@routes.get("/prompt")
|
414 |
+
async def get_prompt(request):
|
415 |
+
return web.json_response(self.get_queue_info())
|
416 |
+
|
417 |
+
def node_info(node_class):
|
418 |
+
obj_class = nodes.NODE_CLASS_MAPPINGS[node_class]
|
419 |
+
info = {}
|
420 |
+
info['input'] = obj_class.INPUT_TYPES()
|
421 |
+
info['output'] = obj_class.RETURN_TYPES
|
422 |
+
info['output_is_list'] = obj_class.OUTPUT_IS_LIST if hasattr(obj_class, 'OUTPUT_IS_LIST') else [False] * len(obj_class.RETURN_TYPES)
|
423 |
+
info['output_name'] = obj_class.RETURN_NAMES if hasattr(obj_class, 'RETURN_NAMES') else info['output']
|
424 |
+
info['name'] = node_class
|
425 |
+
info['display_name'] = nodes.NODE_DISPLAY_NAME_MAPPINGS[node_class] if node_class in nodes.NODE_DISPLAY_NAME_MAPPINGS.keys() else node_class
|
426 |
+
info['description'] = obj_class.DESCRIPTION if hasattr(obj_class,'DESCRIPTION') else ''
|
427 |
+
info['python_module'] = getattr(obj_class, "RELATIVE_PYTHON_MODULE", "nodes")
|
428 |
+
info['category'] = 'sd'
|
429 |
+
if hasattr(obj_class, 'OUTPUT_NODE') and obj_class.OUTPUT_NODE == True:
|
430 |
+
info['output_node'] = True
|
431 |
+
else:
|
432 |
+
info['output_node'] = False
|
433 |
+
|
434 |
+
if hasattr(obj_class, 'CATEGORY'):
|
435 |
+
info['category'] = obj_class.CATEGORY
|
436 |
+
return info
|
437 |
+
|
438 |
+
@routes.get("/object_info")
|
439 |
+
async def get_object_info(request):
|
440 |
+
out = {}
|
441 |
+
for x in nodes.NODE_CLASS_MAPPINGS:
|
442 |
+
try:
|
443 |
+
out[x] = node_info(x)
|
444 |
+
except Exception as e:
|
445 |
+
logging.error(f"[ERROR] An error occurred while retrieving information for the '{x}' node.")
|
446 |
+
logging.error(traceback.format_exc())
|
447 |
+
return web.json_response(out)
|
448 |
+
|
449 |
+
@routes.get("/object_info/{node_class}")
|
450 |
+
async def get_object_info_node(request):
|
451 |
+
node_class = request.match_info.get("node_class", None)
|
452 |
+
out = {}
|
453 |
+
if (node_class is not None) and (node_class in nodes.NODE_CLASS_MAPPINGS):
|
454 |
+
out[node_class] = node_info(node_class)
|
455 |
+
return web.json_response(out)
|
456 |
+
|
457 |
+
@routes.get("/history")
|
458 |
+
async def get_history(request):
|
459 |
+
max_items = request.rel_url.query.get("max_items", None)
|
460 |
+
if max_items is not None:
|
461 |
+
max_items = int(max_items)
|
462 |
+
return web.json_response(self.prompt_queue.get_history(max_items=max_items))
|
463 |
+
|
464 |
+
@routes.get("/history/{prompt_id}")
|
465 |
+
async def get_history(request):
|
466 |
+
prompt_id = request.match_info.get("prompt_id", None)
|
467 |
+
return web.json_response(self.prompt_queue.get_history(prompt_id=prompt_id))
|
468 |
+
|
469 |
+
@routes.get("/queue")
|
470 |
+
async def get_queue(request):
|
471 |
+
queue_info = {}
|
472 |
+
current_queue = self.prompt_queue.get_current_queue()
|
473 |
+
queue_info['queue_running'] = current_queue[0]
|
474 |
+
queue_info['queue_pending'] = current_queue[1]
|
475 |
+
return web.json_response(queue_info)
|
476 |
+
|
477 |
+
@routes.post("/prompt")
|
478 |
+
async def post_prompt(request):
|
479 |
+
logging.info("got prompt")
|
480 |
+
resp_code = 200
|
481 |
+
out_string = ""
|
482 |
+
json_data = await request.json()
|
483 |
+
json_data = self.trigger_on_prompt(json_data)
|
484 |
+
|
485 |
+
if "number" in json_data:
|
486 |
+
number = float(json_data['number'])
|
487 |
+
else:
|
488 |
+
number = self.number
|
489 |
+
if "front" in json_data:
|
490 |
+
if json_data['front']:
|
491 |
+
number = -number
|
492 |
+
|
493 |
+
self.number += 1
|
494 |
+
|
495 |
+
if "prompt" in json_data:
|
496 |
+
prompt = json_data["prompt"]
|
497 |
+
valid = execution.validate_prompt(prompt)
|
498 |
+
extra_data = {}
|
499 |
+
if "extra_data" in json_data:
|
500 |
+
extra_data = json_data["extra_data"]
|
501 |
+
|
502 |
+
if "client_id" in json_data:
|
503 |
+
extra_data["client_id"] = json_data["client_id"]
|
504 |
+
if valid[0]:
|
505 |
+
prompt_id = str(uuid.uuid4())
|
506 |
+
outputs_to_execute = valid[2]
|
507 |
+
self.prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute))
|
508 |
+
response = {"prompt_id": prompt_id, "number": number, "node_errors": valid[3]}
|
509 |
+
return web.json_response(response)
|
510 |
+
else:
|
511 |
+
logging.warning("invalid prompt: {}".format(valid[1]))
|
512 |
+
return web.json_response({"error": valid[1], "node_errors": valid[3]}, status=400)
|
513 |
+
else:
|
514 |
+
return web.json_response({"error": "no prompt", "node_errors": []}, status=400)
|
515 |
+
|
516 |
+
@routes.post("/queue")
|
517 |
+
async def post_queue(request):
|
518 |
+
json_data = await request.json()
|
519 |
+
if "clear" in json_data:
|
520 |
+
if json_data["clear"]:
|
521 |
+
self.prompt_queue.wipe_queue()
|
522 |
+
if "delete" in json_data:
|
523 |
+
to_delete = json_data['delete']
|
524 |
+
for id_to_delete in to_delete:
|
525 |
+
delete_func = lambda a: a[1] == id_to_delete
|
526 |
+
self.prompt_queue.delete_queue_item(delete_func)
|
527 |
+
|
528 |
+
return web.Response(status=200)
|
529 |
+
|
530 |
+
@routes.post("/interrupt")
|
531 |
+
async def post_interrupt(request):
|
532 |
+
nodes.interrupt_processing()
|
533 |
+
return web.Response(status=200)
|
534 |
+
|
535 |
+
@routes.post("/free")
|
536 |
+
async def post_free(request):
|
537 |
+
json_data = await request.json()
|
538 |
+
unload_models = json_data.get("unload_models", False)
|
539 |
+
free_memory = json_data.get("free_memory", False)
|
540 |
+
if unload_models:
|
541 |
+
self.prompt_queue.set_flag("unload_models", unload_models)
|
542 |
+
if free_memory:
|
543 |
+
self.prompt_queue.set_flag("free_memory", free_memory)
|
544 |
+
return web.Response(status=200)
|
545 |
+
|
546 |
+
@routes.post("/history")
|
547 |
+
async def post_history(request):
|
548 |
+
json_data = await request.json()
|
549 |
+
if "clear" in json_data:
|
550 |
+
if json_data["clear"]:
|
551 |
+
self.prompt_queue.wipe_history()
|
552 |
+
if "delete" in json_data:
|
553 |
+
to_delete = json_data['delete']
|
554 |
+
for id_to_delete in to_delete:
|
555 |
+
self.prompt_queue.delete_history_item(id_to_delete)
|
556 |
+
|
557 |
+
return web.Response(status=200)
|
558 |
+
|
559 |
+
def add_routes(self):
|
560 |
+
self.user_manager.add_routes(self.routes)
|
561 |
+
|
562 |
+
# Prefix every route with /api for easier matching for delegation.
|
563 |
+
# This is very useful for frontend dev server, which need to forward
|
564 |
+
# everything except serving of static files.
|
565 |
+
# Currently both the old endpoints without prefix and new endpoints with
|
566 |
+
# prefix are supported.
|
567 |
+
api_routes = web.RouteTableDef()
|
568 |
+
for route in self.routes:
|
569 |
+
# Custom nodes might add extra static routes. Only process non-static
|
570 |
+
# routes to add /api prefix.
|
571 |
+
if isinstance(route, web.RouteDef):
|
572 |
+
api_routes.route(route.method, "/api" + route.path)(route.handler, **route.kwargs)
|
573 |
+
self.app.add_routes(api_routes)
|
574 |
+
self.app.add_routes(self.routes)
|
575 |
+
|
576 |
+
for name, dir in nodes.EXTENSION_WEB_DIRS.items():
|
577 |
+
self.app.add_routes([
|
578 |
+
web.static('/extensions/' + urllib.parse.quote(name), dir),
|
579 |
+
])
|
580 |
+
|
581 |
+
self.app.add_routes([
|
582 |
+
web.static('/', self.web_root),
|
583 |
+
])
|
584 |
+
|
585 |
+
def get_queue_info(self):
|
586 |
+
prompt_info = {}
|
587 |
+
exec_info = {}
|
588 |
+
exec_info['queue_remaining'] = self.prompt_queue.get_tasks_remaining()
|
589 |
+
prompt_info['exec_info'] = exec_info
|
590 |
+
return prompt_info
|
591 |
+
|
592 |
+
async def send(self, event, data, sid=None):
|
593 |
+
if event == BinaryEventTypes.UNENCODED_PREVIEW_IMAGE:
|
594 |
+
await self.send_image(data, sid=sid)
|
595 |
+
elif isinstance(data, (bytes, bytearray)):
|
596 |
+
await self.send_bytes(event, data, sid)
|
597 |
+
else:
|
598 |
+
await self.send_json(event, data, sid)
|
599 |
+
|
600 |
+
def encode_bytes(self, event, data):
|
601 |
+
if not isinstance(event, int):
|
602 |
+
raise RuntimeError(f"Binary event types must be integers, got {event}")
|
603 |
+
|
604 |
+
packed = struct.pack(">I", event)
|
605 |
+
message = bytearray(packed)
|
606 |
+
message.extend(data)
|
607 |
+
return message
|
608 |
+
|
609 |
+
async def send_image(self, image_data, sid=None):
|
610 |
+
image_type = image_data[0]
|
611 |
+
image = image_data[1]
|
612 |
+
max_size = image_data[2]
|
613 |
+
if max_size is not None:
|
614 |
+
if hasattr(Image, 'Resampling'):
|
615 |
+
resampling = Image.Resampling.BILINEAR
|
616 |
+
else:
|
617 |
+
resampling = Image.ANTIALIAS
|
618 |
+
|
619 |
+
image = ImageOps.contain(image, (max_size, max_size), resampling)
|
620 |
+
type_num = 1
|
621 |
+
if image_type == "JPEG":
|
622 |
+
type_num = 1
|
623 |
+
elif image_type == "PNG":
|
624 |
+
type_num = 2
|
625 |
+
|
626 |
+
bytesIO = BytesIO()
|
627 |
+
header = struct.pack(">I", type_num)
|
628 |
+
bytesIO.write(header)
|
629 |
+
image.save(bytesIO, format=image_type, quality=95, compress_level=1)
|
630 |
+
preview_bytes = bytesIO.getvalue()
|
631 |
+
await self.send_bytes(BinaryEventTypes.PREVIEW_IMAGE, preview_bytes, sid=sid)
|
632 |
+
|
633 |
+
async def send_bytes(self, event, data, sid=None):
|
634 |
+
message = self.encode_bytes(event, data)
|
635 |
+
|
636 |
+
if sid is None:
|
637 |
+
sockets = list(self.sockets.values())
|
638 |
+
for ws in sockets:
|
639 |
+
await send_socket_catch_exception(ws.send_bytes, message)
|
640 |
+
elif sid in self.sockets:
|
641 |
+
await send_socket_catch_exception(self.sockets[sid].send_bytes, message)
|
642 |
+
|
643 |
+
async def send_json(self, event, data, sid=None):
|
644 |
+
message = {"type": event, "data": data}
|
645 |
+
|
646 |
+
if sid is None:
|
647 |
+
sockets = list(self.sockets.values())
|
648 |
+
for ws in sockets:
|
649 |
+
await send_socket_catch_exception(ws.send_json, message)
|
650 |
+
elif sid in self.sockets:
|
651 |
+
await send_socket_catch_exception(self.sockets[sid].send_json, message)
|
652 |
+
|
653 |
+
def send_sync(self, event, data, sid=None):
|
654 |
+
self.loop.call_soon_threadsafe(
|
655 |
+
self.messages.put_nowait, (event, data, sid))
|
656 |
+
|
657 |
+
def queue_updated(self):
|
658 |
+
self.send_sync("status", { "status": self.get_queue_info() })
|
659 |
+
|
660 |
+
async def publish_loop(self):
|
661 |
+
while True:
|
662 |
+
msg = await self.messages.get()
|
663 |
+
await self.send(*msg)
|
664 |
+
|
665 |
+
async def start(self, address, port, verbose=True, call_on_start=None):
|
666 |
+
runner = web.AppRunner(self.app, access_log=None)
|
667 |
+
await runner.setup()
|
668 |
+
ssl_ctx = None
|
669 |
+
scheme = "http"
|
670 |
+
if args.tls_keyfile and args.tls_certfile:
|
671 |
+
ssl_ctx = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_SERVER, verify_mode=ssl.CERT_NONE)
|
672 |
+
ssl_ctx.load_cert_chain(certfile=args.tls_certfile,
|
673 |
+
keyfile=args.tls_keyfile)
|
674 |
+
scheme = "https"
|
675 |
+
|
676 |
+
site = web.TCPSite(runner, address, port, ssl_context=ssl_ctx)
|
677 |
+
await site.start()
|
678 |
+
|
679 |
+
if verbose:
|
680 |
+
logging.info("Starting server\n")
|
681 |
+
logging.info("To see the GUI go to: {}://{}:{}".format(scheme, address, port))
|
682 |
+
if call_on_start is not None:
|
683 |
+
call_on_start(scheme, address, port)
|
684 |
+
|
685 |
+
def add_on_prompt_handler(self, handler):
|
686 |
+
self.on_prompt_handlers.append(handler)
|
687 |
+
|
688 |
+
def trigger_on_prompt(self, json_data):
|
689 |
+
for handler in self.on_prompt_handlers:
|
690 |
+
try:
|
691 |
+
json_data = handler(json_data)
|
692 |
+
except Exception as e:
|
693 |
+
logging.warning(f"[ERROR] An error occurred during the on_prompt_handler processing")
|
694 |
+
logging.warning(traceback.format_exc())
|
695 |
+
|
696 |
+
return json_data
|