spideyrim commited on
Commit
4580c31
1 Parent(s): 436faa6

Upload 14 files

Browse files
Files changed (14) hide show
  1. CODEOWNERS +1 -0
  2. LICENSE +674 -0
  3. README.md +212 -0
  4. comfyui_screenshot.png +0 -0
  5. cuda_malloc.py +84 -0
  6. execution.py +764 -0
  7. extra_model_paths.yaml.example +26 -0
  8. folder_paths.py +235 -0
  9. latent_preview.py +77 -0
  10. main.py +195 -0
  11. nodes.py +1786 -0
  12. pytest.ini +5 -0
  13. requirements.txt +12 -0
  14. server.py +630 -0
CODEOWNERS ADDED
@@ -0,0 +1 @@
 
 
1
+ * @comfyanonymous
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.html>.
README.md ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ComfyUI
2
+ =======
3
+ A 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 and SDXL
15
+ - Asynchronous Queue system
16
+ - Many optimizations: Only re-executes the parts of the workflow that changes between executions.
17
+ - Command line option: ```--lowvram``` to make it work on GPUs with less than 3GB vram (enabled automatically on GPUs with low 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 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
+ - Latent previews with [TAESD](#how-to-show-high-quality-previews)
34
+ - Starts up very fast.
35
+ - Works fully offline: will never download anything.
36
+ - [Config file](extra_model_paths.yaml.example) to set the search paths for models.
37
+
38
+ Workflow examples can be found on the [Examples page](https://comfyanonymous.github.io/ComfyUI_examples/)
39
+
40
+ ## Shortcuts
41
+
42
+ | Keybind | Explanation |
43
+ |---------------------------|--------------------------------------------------------------------------------------------------------------------|
44
+ | Ctrl + Enter | Queue up current graph for generation |
45
+ | Ctrl + Shift + Enter | Queue up current graph as first for generation |
46
+ | Ctrl + S | Save workflow |
47
+ | Ctrl + O | Load workflow |
48
+ | Ctrl + A | Select all nodes |
49
+ | Ctrl + M | Mute/unmute selected nodes |
50
+ | Ctrl + B | Bypass selected nodes (acts like the node was removed from the graph and the wires reconnected through) |
51
+ | Delete/Backspace | Delete selected nodes |
52
+ | Ctrl + Delete/Backspace | Delete the current graph |
53
+ | Space | Move the canvas around when held and moving the cursor |
54
+ | Ctrl/Shift + Click | Add clicked node to selection |
55
+ | Ctrl + C/Ctrl + V | Copy and paste selected nodes (without maintaining connections to outputs of unselected nodes) |
56
+ | Ctrl + C/Ctrl + Shift + V | Copy and paste selected nodes (maintaining connections from outputs of unselected nodes to inputs of pasted nodes) |
57
+ | Shift + Drag | Move multiple selected nodes at the same time |
58
+ | Ctrl + D | Load default graph |
59
+ | Q | Toggle visibility of the queue |
60
+ | H | Toggle visibility of history |
61
+ | R | Refresh graph |
62
+ | Double-Click LMB | Open node quick search palette |
63
+
64
+ Ctrl can also be replaced with Cmd instead for macOS users
65
+
66
+ # Installing
67
+
68
+ ## Windows
69
+
70
+ 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).
71
+
72
+ ### [Direct link to download](https://github.com/comfyanonymous/ComfyUI/releases/download/latest/ComfyUI_windows_portable_nvidia_cu118_or_cpu.7z)
73
+
74
+ 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
75
+
76
+ #### How do I share models between another UI and ComfyUI?
77
+
78
+ 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.
79
+
80
+ ## Jupyter Notebook
81
+
82
+ To run it on services like paperspace, kaggle or colab you can use my [Jupyter Notebook](notebooks/comfyui_colab.ipynb)
83
+
84
+ ## Manual Install (Windows, Linux)
85
+
86
+ Git clone this repo.
87
+
88
+ Put your SD checkpoints (the huge ckpt/safetensors files) in: models/checkpoints
89
+
90
+ Put your VAE in: models/vae
91
+
92
+ ### AMD GPUs (Linux only)
93
+ 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:
94
+
95
+ ```pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/rocm5.4.2```
96
+
97
+ This is the command to install the nightly with ROCm 5.6 that supports the 7000 series and might have some performance improvements:
98
+ ```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm5.6```
99
+
100
+ ### NVIDIA
101
+
102
+ Nvidia users should install torch and xformers using this command:
103
+
104
+ ```pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu118 xformers```
105
+
106
+ #### Troubleshooting
107
+
108
+ If you get the "Torch not compiled with CUDA enabled" error, uninstall torch with:
109
+
110
+ ```pip uninstall torch```
111
+
112
+ And install it again with the command above.
113
+
114
+ ### Dependencies
115
+
116
+ Install the dependencies by opening your terminal inside the ComfyUI folder and:
117
+
118
+ ```pip install -r requirements.txt```
119
+
120
+ After this you should have everything installed and can proceed to running ComfyUI.
121
+
122
+ ### Others:
123
+
124
+ #### [Intel Arc](https://github.com/comfyanonymous/ComfyUI/discussions/476)
125
+
126
+ #### Apple Mac silicon
127
+
128
+ You can install ComfyUI in Apple Mac silicon (M1 or M2) with any recent macOS version.
129
+
130
+ 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).
131
+ 1. Follow the [ComfyUI manual installation](#manual-install-windows-linux) instructions for Windows and Linux.
132
+ 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).
133
+ 1. Launch ComfyUI by running `python main.py --force-fp16`. Note that --force-fp16 will only work if you installed the latest pytorch nightly.
134
+
135
+ > **Note**: Remember to add your models, VAE, LoRAs etc. to the corresponding Comfy folders, as discussed in [ComfyUI manual installation](#manual-install-windows-linux).
136
+
137
+ #### DirectML (AMD Cards on Windows)
138
+
139
+ ```pip install torch-directml``` Then you can launch ComfyUI with: ```python main.py --directml```
140
+
141
+ ### I already have another UI for Stable Diffusion installed do I really have to install all of these dependencies?
142
+
143
+ 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:
144
+
145
+ ```source path_to_other_sd_gui/venv/bin/activate```
146
+
147
+ or on Windows:
148
+
149
+ With Powershell: ```"path_to_other_sd_gui\venv\Scripts\Activate.ps1"```
150
+
151
+ With cmd.exe: ```"path_to_other_sd_gui\venv\Scripts\activate.bat"```
152
+
153
+ 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.
154
+
155
+ # Running
156
+
157
+ ```python main.py```
158
+
159
+ ### For AMD cards not officially supported by ROCm
160
+
161
+ Try running it with this command if you have issues:
162
+
163
+ For 6700, 6600 and maybe other RDNA2 or older: ```HSA_OVERRIDE_GFX_VERSION=10.3.0 python main.py```
164
+
165
+ For AMD 7600 and maybe other RDNA3 cards: ```HSA_OVERRIDE_GFX_VERSION=11.0.0 python main.py```
166
+
167
+ # Notes
168
+
169
+ Only parts of the graph that have an output with all the correct inputs will be executed.
170
+
171
+ 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.
172
+
173
+ Dragging a generated png on the webpage or loading one will give you the full workflow including seeds that were used to create it.
174
+
175
+ 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 \\).
176
+
177
+ 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 \\}.
178
+
179
+ Dynamic prompts also support C-style comments, like `// comment` or `/* comment */`.
180
+
181
+ 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):
182
+
183
+ ```embedding:embedding_filename.pt```
184
+
185
+
186
+ ## How to increase generation speed?
187
+
188
+ Make sure you use the regular loaders/Load Checkpoint node to load checkpoints. It will auto pick the right settings depending on your GPU.
189
+
190
+ You can set this command line setting to disable the upcasting to fp32 in some cross attention operations which will increase your speed. Note that this will very likely give you black images on SD2.x models. If you use xformers this option does not do anything.
191
+
192
+ ```--dont-upcast-attention```
193
+
194
+ ## How to show high-quality previews?
195
+
196
+ Use ```--preview-method auto``` to enable previews.
197
+
198
+ 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.
199
+
200
+ ## Support and dev channel
201
+
202
+ [Matrix space: #comfyui_space:matrix.org](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) (it's like discord but open source).
203
+
204
+ # QA
205
+
206
+ ### Why did you make this?
207
+
208
+ I wanted to learn how Stable Diffusion worked in detail. I also wanted something clean and powerful that would let me experiment with SD without restrictions.
209
+
210
+ ### Who is this for?
211
+
212
+ This is for anyone that wants to make complex workflows with SD or that wants to learn more how SD works. The interface follows closely how SD works and the code should be much more simple to understand than other SD UIs.
comfyui_screenshot.png ADDED
cuda_malloc.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import importlib.util
3
+ from comfy.cli_args import args
4
+
5
+ #Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import.
6
+ def get_gpu_names():
7
+ if os.name == 'nt':
8
+ import ctypes
9
+
10
+ # Define necessary C structures and types
11
+ class DISPLAY_DEVICEA(ctypes.Structure):
12
+ _fields_ = [
13
+ ('cb', ctypes.c_ulong),
14
+ ('DeviceName', ctypes.c_char * 32),
15
+ ('DeviceString', ctypes.c_char * 128),
16
+ ('StateFlags', ctypes.c_ulong),
17
+ ('DeviceID', ctypes.c_char * 128),
18
+ ('DeviceKey', ctypes.c_char * 128)
19
+ ]
20
+
21
+ # Load user32.dll
22
+ user32 = ctypes.windll.user32
23
+
24
+ # Call EnumDisplayDevicesA
25
+ def enum_display_devices():
26
+ device_info = DISPLAY_DEVICEA()
27
+ device_info.cb = ctypes.sizeof(device_info)
28
+ device_index = 0
29
+ gpu_names = set()
30
+
31
+ while user32.EnumDisplayDevicesA(None, device_index, ctypes.byref(device_info), 0):
32
+ device_index += 1
33
+ gpu_names.add(device_info.DeviceString.decode('utf-8'))
34
+ return gpu_names
35
+ return enum_display_devices()
36
+ else:
37
+ return set()
38
+
39
+ blacklist = {"GeForce GTX TITAN X", "GeForce GTX 980", "GeForce GTX 970", "GeForce GTX 960", "GeForce GTX 950", "GeForce 945M",
40
+ "GeForce 940M", "GeForce 930M", "GeForce 920M", "GeForce 910M", "GeForce GTX 750", "GeForce GTX 745", "Quadro K620",
41
+ "Quadro K1200", "Quadro K2200", "Quadro M500", "Quadro M520", "Quadro M600", "Quadro M620", "Quadro M1000",
42
+ "Quadro M1200", "Quadro M2000", "Quadro M2200", "Quadro M3000", "Quadro M4000", "Quadro M5000", "Quadro M5500", "Quadro M6000",
43
+ "GeForce MX110", "GeForce MX130", "GeForce 830M", "GeForce 840M", "GeForce GTX 850M", "GeForce GTX 860M",
44
+ "GeForce GTX 1650", "GeForce GTX 1630"
45
+ }
46
+
47
+ def cuda_malloc_supported():
48
+ try:
49
+ names = get_gpu_names()
50
+ except:
51
+ names = set()
52
+ for x in names:
53
+ if "NVIDIA" in x:
54
+ for b in blacklist:
55
+ if b in x:
56
+ return False
57
+ return True
58
+
59
+
60
+ if not args.cuda_malloc:
61
+ try:
62
+ version = ""
63
+ torch_spec = importlib.util.find_spec("torch")
64
+ for folder in torch_spec.submodule_search_locations:
65
+ ver_file = os.path.join(folder, "version.py")
66
+ if os.path.isfile(ver_file):
67
+ spec = importlib.util.spec_from_file_location("torch_version_import", ver_file)
68
+ module = importlib.util.module_from_spec(spec)
69
+ spec.loader.exec_module(module)
70
+ version = module.__version__
71
+ if int(version[0]) >= 2: #enable by default for torch version 2.0 and up
72
+ args.cuda_malloc = cuda_malloc_supported()
73
+ except:
74
+ pass
75
+
76
+
77
+ if args.cuda_malloc and not args.disable_cuda_malloc:
78
+ env_var = os.environ.get('PYTORCH_CUDA_ALLOC_CONF', None)
79
+ if env_var is None:
80
+ env_var = "backend:cudaMallocAsync"
81
+ else:
82
+ env_var += ",backend:cudaMallocAsync"
83
+
84
+ os.environ['PYTORCH_CUDA_ALLOC_CONF'] = env_var
execution.py ADDED
@@ -0,0 +1,764 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import copy
4
+ import json
5
+ import threading
6
+ import heapq
7
+ import traceback
8
+ import gc
9
+
10
+ import torch
11
+ import nodes
12
+
13
+ import comfy.model_management
14
+
15
+ def get_input_data(inputs, class_def, unique_id, outputs={}, prompt={}, extra_data={}):
16
+ valid_inputs = class_def.INPUT_TYPES()
17
+ input_data_all = {}
18
+ for x in inputs:
19
+ input_data = inputs[x]
20
+ if isinstance(input_data, list):
21
+ input_unique_id = input_data[0]
22
+ output_index = input_data[1]
23
+ if input_unique_id not in outputs:
24
+ input_data_all[x] = (None,)
25
+ continue
26
+ obj = outputs[input_unique_id][output_index]
27
+ input_data_all[x] = obj
28
+ else:
29
+ if ("required" in valid_inputs and x in valid_inputs["required"]) or ("optional" in valid_inputs and x in valid_inputs["optional"]):
30
+ input_data_all[x] = [input_data]
31
+
32
+ if "hidden" in valid_inputs:
33
+ h = valid_inputs["hidden"]
34
+ for x in h:
35
+ if h[x] == "PROMPT":
36
+ input_data_all[x] = [prompt]
37
+ if h[x] == "EXTRA_PNGINFO":
38
+ if "extra_pnginfo" in extra_data:
39
+ input_data_all[x] = [extra_data['extra_pnginfo']]
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
+ print("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
+ print("!!! Exception during processing !!!")
181
+ print(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):
198
+ unique_id = current_item
199
+ inputs = prompt[unique_id]['inputs']
200
+ will_execute = []
201
+ if unique_id in outputs:
202
+ return []
203
+
204
+ for x in inputs:
205
+ input_data = inputs[x]
206
+ if isinstance(input_data, list):
207
+ input_unique_id = input_data[0]
208
+ output_index = input_data[1]
209
+ if input_unique_id not in outputs:
210
+ will_execute += recursive_will_execute(prompt, outputs, input_unique_id)
211
+
212
+ return will_execute + [unique_id]
213
+
214
+ def recursive_output_delete_if_changed(prompt, old_prompt, outputs, current_item):
215
+ unique_id = current_item
216
+ inputs = prompt[unique_id]['inputs']
217
+ class_type = prompt[unique_id]['class_type']
218
+ class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
219
+
220
+ is_changed_old = ''
221
+ is_changed = ''
222
+ to_delete = False
223
+ if hasattr(class_def, 'IS_CHANGED'):
224
+ if unique_id in old_prompt and 'is_changed' in old_prompt[unique_id]:
225
+ is_changed_old = old_prompt[unique_id]['is_changed']
226
+ if 'is_changed' not in prompt[unique_id]:
227
+ input_data_all = get_input_data(inputs, class_def, unique_id, outputs)
228
+ if input_data_all is not None:
229
+ try:
230
+ #is_changed = class_def.IS_CHANGED(**input_data_all)
231
+ is_changed = map_node_over_list(class_def, input_data_all, "IS_CHANGED")
232
+ prompt[unique_id]['is_changed'] = is_changed
233
+ except:
234
+ to_delete = True
235
+ else:
236
+ is_changed = prompt[unique_id]['is_changed']
237
+
238
+ if unique_id not in outputs:
239
+ return True
240
+
241
+ if not to_delete:
242
+ if is_changed != is_changed_old:
243
+ to_delete = True
244
+ elif unique_id not in old_prompt:
245
+ to_delete = True
246
+ elif inputs == old_prompt[unique_id]['inputs']:
247
+ for x in inputs:
248
+ input_data = inputs[x]
249
+
250
+ if isinstance(input_data, list):
251
+ input_unique_id = input_data[0]
252
+ output_index = input_data[1]
253
+ if input_unique_id in outputs:
254
+ to_delete = recursive_output_delete_if_changed(prompt, old_prompt, outputs, input_unique_id)
255
+ else:
256
+ to_delete = True
257
+ if to_delete:
258
+ break
259
+ else:
260
+ to_delete = True
261
+
262
+ if to_delete:
263
+ d = outputs.pop(unique_id)
264
+ del d
265
+ return to_delete
266
+
267
+ class PromptExecutor:
268
+ def __init__(self, server):
269
+ self.outputs = {}
270
+ self.object_storage = {}
271
+ self.outputs_ui = {}
272
+ self.old_prompt = {}
273
+ self.server = server
274
+
275
+ def handle_execution_error(self, prompt_id, prompt, current_outputs, executed, error, ex):
276
+ node_id = error["node_id"]
277
+ class_type = prompt[node_id]["class_type"]
278
+
279
+ # First, send back the status to the frontend depending
280
+ # on the exception type
281
+ if isinstance(ex, comfy.model_management.InterruptProcessingException):
282
+ mes = {
283
+ "prompt_id": prompt_id,
284
+ "node_id": node_id,
285
+ "node_type": class_type,
286
+ "executed": list(executed),
287
+ }
288
+ self.server.send_sync("execution_interrupted", mes, self.server.client_id)
289
+ else:
290
+ if self.server.client_id is not None:
291
+ mes = {
292
+ "prompt_id": prompt_id,
293
+ "node_id": node_id,
294
+ "node_type": class_type,
295
+ "executed": list(executed),
296
+
297
+ "exception_message": error["exception_message"],
298
+ "exception_type": error["exception_type"],
299
+ "traceback": error["traceback"],
300
+ "current_inputs": error["current_inputs"],
301
+ "current_outputs": error["current_outputs"],
302
+ }
303
+ self.server.send_sync("execution_error", mes, self.server.client_id)
304
+
305
+ # Next, remove the subsequent outputs since they will not be executed
306
+ to_delete = []
307
+ for o in self.outputs:
308
+ if (o not in current_outputs) and (o not in executed):
309
+ to_delete += [o]
310
+ if o in self.old_prompt:
311
+ d = self.old_prompt.pop(o)
312
+ del d
313
+ for o in to_delete:
314
+ d = self.outputs.pop(o)
315
+ del d
316
+
317
+ def execute(self, prompt, prompt_id, extra_data={}, execute_outputs=[]):
318
+ nodes.interrupt_processing(False)
319
+
320
+ if "client_id" in extra_data:
321
+ self.server.client_id = extra_data["client_id"]
322
+ else:
323
+ self.server.client_id = None
324
+
325
+ if self.server.client_id is not None:
326
+ self.server.send_sync("execution_start", { "prompt_id": prompt_id}, self.server.client_id)
327
+
328
+ with torch.inference_mode():
329
+ #delete cached outputs if nodes don't exist for them
330
+ to_delete = []
331
+ for o in self.outputs:
332
+ if o not in prompt:
333
+ to_delete += [o]
334
+ for o in to_delete:
335
+ d = self.outputs.pop(o)
336
+ del d
337
+ to_delete = []
338
+ for o in self.object_storage:
339
+ if o[0] not in prompt:
340
+ to_delete += [o]
341
+ else:
342
+ p = prompt[o[0]]
343
+ if o[1] != p['class_type']:
344
+ to_delete += [o]
345
+ for o in to_delete:
346
+ d = self.object_storage.pop(o)
347
+ del d
348
+
349
+ for x in prompt:
350
+ recursive_output_delete_if_changed(prompt, self.old_prompt, self.outputs, x)
351
+
352
+ current_outputs = set(self.outputs.keys())
353
+ for x in list(self.outputs_ui.keys()):
354
+ if x not in current_outputs:
355
+ d = self.outputs_ui.pop(x)
356
+ del d
357
+
358
+ comfy.model_management.cleanup_models()
359
+ if self.server.client_id is not None:
360
+ self.server.send_sync("execution_cached", { "nodes": list(current_outputs) , "prompt_id": prompt_id}, self.server.client_id)
361
+ executed = set()
362
+ output_node_id = None
363
+ to_execute = []
364
+
365
+ for node_id in list(execute_outputs):
366
+ to_execute += [(0, node_id)]
367
+
368
+ while len(to_execute) > 0:
369
+ #always execute the output that depends on the least amount of unexecuted nodes first
370
+ to_execute = sorted(list(map(lambda a: (len(recursive_will_execute(prompt, self.outputs, a[-1])), a[-1]), to_execute)))
371
+ output_node_id = to_execute.pop(0)[-1]
372
+
373
+ # This call shouldn't raise anything if there's an error deep in
374
+ # the actual SD code, instead it will report the node where the
375
+ # error was raised
376
+ success, error, ex = recursive_execute(self.server, prompt, self.outputs, output_node_id, extra_data, executed, prompt_id, self.outputs_ui, self.object_storage)
377
+ if success is not True:
378
+ self.handle_execution_error(prompt_id, prompt, current_outputs, executed, error, ex)
379
+ break
380
+
381
+ for x in executed:
382
+ self.old_prompt[x] = copy.deepcopy(prompt[x])
383
+ self.server.last_node_id = None
384
+
385
+
386
+
387
+ def validate_inputs(prompt, item, validated):
388
+ unique_id = item
389
+ if unique_id in validated:
390
+ return validated[unique_id]
391
+
392
+ inputs = prompt[unique_id]['inputs']
393
+ class_type = prompt[unique_id]['class_type']
394
+ obj_class = nodes.NODE_CLASS_MAPPINGS[class_type]
395
+
396
+ class_inputs = obj_class.INPUT_TYPES()
397
+ required_inputs = class_inputs['required']
398
+
399
+ errors = []
400
+ valid = True
401
+
402
+ for x in required_inputs:
403
+ if x not in inputs:
404
+ error = {
405
+ "type": "required_input_missing",
406
+ "message": "Required input is missing",
407
+ "details": f"{x}",
408
+ "extra_info": {
409
+ "input_name": x
410
+ }
411
+ }
412
+ errors.append(error)
413
+ continue
414
+
415
+ val = inputs[x]
416
+ info = required_inputs[x]
417
+ type_input = info[0]
418
+ if isinstance(val, list):
419
+ if len(val) != 2:
420
+ error = {
421
+ "type": "bad_linked_input",
422
+ "message": "Bad linked input, must be a length-2 list of [node_id, slot_index]",
423
+ "details": f"{x}",
424
+ "extra_info": {
425
+ "input_name": x,
426
+ "input_config": info,
427
+ "received_value": val
428
+ }
429
+ }
430
+ errors.append(error)
431
+ continue
432
+
433
+ o_id = val[0]
434
+ o_class_type = prompt[o_id]['class_type']
435
+ r = nodes.NODE_CLASS_MAPPINGS[o_class_type].RETURN_TYPES
436
+ if r[val[1]] != type_input:
437
+ received_type = r[val[1]]
438
+ details = f"{x}, {received_type} != {type_input}"
439
+ error = {
440
+ "type": "return_type_mismatch",
441
+ "message": "Return type mismatch between linked nodes",
442
+ "details": details,
443
+ "extra_info": {
444
+ "input_name": x,
445
+ "input_config": info,
446
+ "received_type": received_type,
447
+ "linked_node": val
448
+ }
449
+ }
450
+ errors.append(error)
451
+ continue
452
+ try:
453
+ r = validate_inputs(prompt, o_id, validated)
454
+ if r[0] is False:
455
+ # `r` will be set in `validated[o_id]` already
456
+ valid = False
457
+ continue
458
+ except Exception as ex:
459
+ typ, _, tb = sys.exc_info()
460
+ valid = False
461
+ exception_type = full_type_name(typ)
462
+ reasons = [{
463
+ "type": "exception_during_inner_validation",
464
+ "message": "Exception when validating inner node",
465
+ "details": str(ex),
466
+ "extra_info": {
467
+ "input_name": x,
468
+ "input_config": info,
469
+ "exception_message": str(ex),
470
+ "exception_type": exception_type,
471
+ "traceback": traceback.format_tb(tb),
472
+ "linked_node": val
473
+ }
474
+ }]
475
+ validated[o_id] = (False, reasons, o_id)
476
+ continue
477
+ else:
478
+ try:
479
+ if type_input == "INT":
480
+ val = int(val)
481
+ inputs[x] = val
482
+ if type_input == "FLOAT":
483
+ val = float(val)
484
+ inputs[x] = val
485
+ if type_input == "STRING":
486
+ val = str(val)
487
+ inputs[x] = val
488
+ except Exception as ex:
489
+ error = {
490
+ "type": "invalid_input_type",
491
+ "message": f"Failed to convert an input value to a {type_input} value",
492
+ "details": f"{x}, {val}, {ex}",
493
+ "extra_info": {
494
+ "input_name": x,
495
+ "input_config": info,
496
+ "received_value": val,
497
+ "exception_message": str(ex)
498
+ }
499
+ }
500
+ errors.append(error)
501
+ continue
502
+
503
+ if len(info) > 1:
504
+ if "min" in info[1] and val < info[1]["min"]:
505
+ error = {
506
+ "type": "value_smaller_than_min",
507
+ "message": "Value {} smaller than min of {}".format(val, info[1]["min"]),
508
+ "details": f"{x}",
509
+ "extra_info": {
510
+ "input_name": x,
511
+ "input_config": info,
512
+ "received_value": val,
513
+ }
514
+ }
515
+ errors.append(error)
516
+ continue
517
+ if "max" in info[1] and val > info[1]["max"]:
518
+ error = {
519
+ "type": "value_bigger_than_max",
520
+ "message": "Value {} bigger than max of {}".format(val, info[1]["max"]),
521
+ "details": f"{x}",
522
+ "extra_info": {
523
+ "input_name": x,
524
+ "input_config": info,
525
+ "received_value": val,
526
+ }
527
+ }
528
+ errors.append(error)
529
+ continue
530
+
531
+ if hasattr(obj_class, "VALIDATE_INPUTS"):
532
+ input_data_all = get_input_data(inputs, obj_class, unique_id)
533
+ #ret = obj_class.VALIDATE_INPUTS(**input_data_all)
534
+ ret = map_node_over_list(obj_class, input_data_all, "VALIDATE_INPUTS")
535
+ for i, r in enumerate(ret):
536
+ if r is not True:
537
+ details = f"{x}"
538
+ if r is not False:
539
+ details += f" - {str(r)}"
540
+
541
+ error = {
542
+ "type": "custom_validation_failed",
543
+ "message": "Custom validation failed for node",
544
+ "details": details,
545
+ "extra_info": {
546
+ "input_name": x,
547
+ "input_config": info,
548
+ "received_value": val,
549
+ }
550
+ }
551
+ errors.append(error)
552
+ continue
553
+ else:
554
+ if isinstance(type_input, list):
555
+ if val not in type_input:
556
+ input_config = info
557
+ list_info = ""
558
+
559
+ # Don't send back gigantic lists like if they're lots of
560
+ # scanned model filepaths
561
+ if len(type_input) > 20:
562
+ list_info = f"(list of length {len(type_input)})"
563
+ input_config = None
564
+ else:
565
+ list_info = str(type_input)
566
+
567
+ error = {
568
+ "type": "value_not_in_list",
569
+ "message": "Value not in list",
570
+ "details": f"{x}: '{val}' not in {list_info}",
571
+ "extra_info": {
572
+ "input_name": x,
573
+ "input_config": input_config,
574
+ "received_value": val,
575
+ }
576
+ }
577
+ errors.append(error)
578
+ continue
579
+
580
+ if len(errors) > 0 or valid is not True:
581
+ ret = (False, errors, unique_id)
582
+ else:
583
+ ret = (True, [], unique_id)
584
+
585
+ validated[unique_id] = ret
586
+ return ret
587
+
588
+ def full_type_name(klass):
589
+ module = klass.__module__
590
+ if module == 'builtins':
591
+ return klass.__qualname__
592
+ return module + '.' + klass.__qualname__
593
+
594
+ def validate_prompt(prompt):
595
+ outputs = set()
596
+ for x in prompt:
597
+ class_ = nodes.NODE_CLASS_MAPPINGS[prompt[x]['class_type']]
598
+ if hasattr(class_, 'OUTPUT_NODE') and class_.OUTPUT_NODE == True:
599
+ outputs.add(x)
600
+
601
+ if len(outputs) == 0:
602
+ error = {
603
+ "type": "prompt_no_outputs",
604
+ "message": "Prompt has no outputs",
605
+ "details": "",
606
+ "extra_info": {}
607
+ }
608
+ return (False, error, [], [])
609
+
610
+ good_outputs = set()
611
+ errors = []
612
+ node_errors = {}
613
+ validated = {}
614
+ for o in outputs:
615
+ valid = False
616
+ reasons = []
617
+ try:
618
+ m = validate_inputs(prompt, o, validated)
619
+ valid = m[0]
620
+ reasons = m[1]
621
+ except Exception as ex:
622
+ typ, _, tb = sys.exc_info()
623
+ valid = False
624
+ exception_type = full_type_name(typ)
625
+ reasons = [{
626
+ "type": "exception_during_validation",
627
+ "message": "Exception when validating node",
628
+ "details": str(ex),
629
+ "extra_info": {
630
+ "exception_type": exception_type,
631
+ "traceback": traceback.format_tb(tb)
632
+ }
633
+ }]
634
+ validated[o] = (False, reasons, o)
635
+
636
+ if valid is True:
637
+ good_outputs.add(o)
638
+ else:
639
+ print(f"Failed to validate prompt for output {o}:")
640
+ if len(reasons) > 0:
641
+ print("* (prompt):")
642
+ for reason in reasons:
643
+ print(f" - {reason['message']}: {reason['details']}")
644
+ errors += [(o, reasons)]
645
+ for node_id, result in validated.items():
646
+ valid = result[0]
647
+ reasons = result[1]
648
+ # If a node upstream has errors, the nodes downstream will also
649
+ # be reported as invalid, but there will be no errors attached.
650
+ # So don't return those nodes as having errors in the response.
651
+ if valid is not True and len(reasons) > 0:
652
+ if node_id not in node_errors:
653
+ class_type = prompt[node_id]['class_type']
654
+ node_errors[node_id] = {
655
+ "errors": reasons,
656
+ "dependent_outputs": [],
657
+ "class_type": class_type
658
+ }
659
+ print(f"* {class_type} {node_id}:")
660
+ for reason in reasons:
661
+ print(f" - {reason['message']}: {reason['details']}")
662
+ node_errors[node_id]["dependent_outputs"].append(o)
663
+ print("Output will be ignored")
664
+
665
+ if len(good_outputs) == 0:
666
+ errors_list = []
667
+ for o, errors in errors:
668
+ for error in errors:
669
+ errors_list.append(f"{error['message']}: {error['details']}")
670
+ errors_list = "\n".join(errors_list)
671
+
672
+ error = {
673
+ "type": "prompt_outputs_failed_validation",
674
+ "message": "Prompt outputs failed validation",
675
+ "details": errors_list,
676
+ "extra_info": {}
677
+ }
678
+
679
+ return (False, error, list(good_outputs), node_errors)
680
+
681
+ return (True, None, list(good_outputs), node_errors)
682
+
683
+
684
+ class PromptQueue:
685
+ def __init__(self, server):
686
+ self.server = server
687
+ self.mutex = threading.RLock()
688
+ self.not_empty = threading.Condition(self.mutex)
689
+ self.task_counter = 0
690
+ self.queue = []
691
+ self.currently_running = {}
692
+ self.history = {}
693
+ server.prompt_queue = self
694
+
695
+ def put(self, item):
696
+ with self.mutex:
697
+ heapq.heappush(self.queue, item)
698
+ self.server.queue_updated()
699
+ self.not_empty.notify()
700
+
701
+ def get(self):
702
+ with self.not_empty:
703
+ while len(self.queue) == 0:
704
+ self.not_empty.wait()
705
+ item = heapq.heappop(self.queue)
706
+ i = self.task_counter
707
+ self.currently_running[i] = copy.deepcopy(item)
708
+ self.task_counter += 1
709
+ self.server.queue_updated()
710
+ return (item, i)
711
+
712
+ def task_done(self, item_id, outputs):
713
+ with self.mutex:
714
+ prompt = self.currently_running.pop(item_id)
715
+ self.history[prompt[1]] = { "prompt": prompt, "outputs": {} }
716
+ for o in outputs:
717
+ self.history[prompt[1]]["outputs"][o] = outputs[o]
718
+ self.server.queue_updated()
719
+
720
+ def get_current_queue(self):
721
+ with self.mutex:
722
+ out = []
723
+ for x in self.currently_running.values():
724
+ out += [x]
725
+ return (out, copy.deepcopy(self.queue))
726
+
727
+ def get_tasks_remaining(self):
728
+ with self.mutex:
729
+ return len(self.queue) + len(self.currently_running)
730
+
731
+ def wipe_queue(self):
732
+ with self.mutex:
733
+ self.queue = []
734
+ self.server.queue_updated()
735
+
736
+ def delete_queue_item(self, function):
737
+ with self.mutex:
738
+ for x in range(len(self.queue)):
739
+ if function(self.queue[x]):
740
+ if len(self.queue) == 1:
741
+ self.wipe_queue()
742
+ else:
743
+ self.queue.pop(x)
744
+ heapq.heapify(self.queue)
745
+ self.server.queue_updated()
746
+ return True
747
+ return False
748
+
749
+ def get_history(self, prompt_id=None):
750
+ with self.mutex:
751
+ if prompt_id is None:
752
+ return copy.deepcopy(self.history)
753
+ elif prompt_id in self.history:
754
+ return {prompt_id: copy.deepcopy(self.history[prompt_id])}
755
+ else:
756
+ return {}
757
+
758
+ def wipe_history(self):
759
+ with self.mutex:
760
+ self.history = {}
761
+
762
+ def delete_history_item(self, id_to_delete):
763
+ with self.mutex:
764
+ self.history.pop(id_to_delete, None)
extra_model_paths.yaml.example ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #Rename this to extra_model_paths.yaml and ComfyUI will load it
2
+
3
+ #config for a1111 ui
4
+ #all you have to do is change the base_path to where yours is installed
5
+ a111:
6
+ base_path: path/to/stable-diffusion-webui/
7
+
8
+ checkpoints: models/Stable-diffusion
9
+ configs: models/Stable-diffusion
10
+ vae: models/VAE
11
+ loras: |
12
+ models/Lora
13
+ models/LyCORIS
14
+ upscale_models: |
15
+ models/ESRGAN
16
+ models/RealESRGAN
17
+ models/SwinIR
18
+ embeddings: embeddings
19
+ hypernetworks: models/hypernetworks
20
+ controlnet: models/ControlNet
21
+
22
+ #other_ui:
23
+ # base_path: path/to/ui
24
+ # checkpoints: models/checkpoints
25
+ # gligen: models/gligen
26
+ # custom_nodes: path/custom_nodes
folder_paths.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import time
3
+
4
+ supported_pt_extensions = set(['.ckpt', '.pt', '.bin', '.pth', '.safetensors'])
5
+
6
+ folder_names_and_paths = {}
7
+
8
+ base_path = os.path.dirname(os.path.realpath(__file__))
9
+ models_dir = os.path.join(base_path, "models")
10
+ folder_names_and_paths["checkpoints"] = ([os.path.join(models_dir, "checkpoints")], supported_pt_extensions)
11
+ folder_names_and_paths["configs"] = ([os.path.join(models_dir, "configs")], [".yaml"])
12
+
13
+ folder_names_and_paths["loras"] = ([os.path.join(models_dir, "loras")], supported_pt_extensions)
14
+ folder_names_and_paths["vae"] = ([os.path.join(models_dir, "vae")], supported_pt_extensions)
15
+ folder_names_and_paths["clip"] = ([os.path.join(models_dir, "clip")], supported_pt_extensions)
16
+ folder_names_and_paths["unet"] = ([os.path.join(models_dir, "unet")], supported_pt_extensions)
17
+ folder_names_and_paths["clip_vision"] = ([os.path.join(models_dir, "clip_vision")], supported_pt_extensions)
18
+ folder_names_and_paths["style_models"] = ([os.path.join(models_dir, "style_models")], supported_pt_extensions)
19
+ folder_names_and_paths["embeddings"] = ([os.path.join(models_dir, "embeddings")], supported_pt_extensions)
20
+ folder_names_and_paths["diffusers"] = ([os.path.join(models_dir, "diffusers")], ["folder"])
21
+ folder_names_and_paths["vae_approx"] = ([os.path.join(models_dir, "vae_approx")], supported_pt_extensions)
22
+
23
+ folder_names_and_paths["controlnet"] = ([os.path.join(models_dir, "controlnet"), os.path.join(models_dir, "t2i_adapter")], supported_pt_extensions)
24
+ folder_names_and_paths["gligen"] = ([os.path.join(models_dir, "gligen")], supported_pt_extensions)
25
+
26
+ folder_names_and_paths["upscale_models"] = ([os.path.join(models_dir, "upscale_models")], supported_pt_extensions)
27
+
28
+ folder_names_and_paths["custom_nodes"] = ([os.path.join(base_path, "custom_nodes")], [])
29
+
30
+ folder_names_and_paths["hypernetworks"] = ([os.path.join(models_dir, "hypernetworks")], supported_pt_extensions)
31
+
32
+ output_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output")
33
+ temp_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "temp")
34
+ input_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "input")
35
+
36
+ filename_list_cache = {}
37
+
38
+ if not os.path.exists(input_directory):
39
+ os.makedirs(input_directory)
40
+
41
+ def set_output_directory(output_dir):
42
+ global output_directory
43
+ output_directory = output_dir
44
+
45
+ def set_temp_directory(temp_dir):
46
+ global temp_directory
47
+ temp_directory = temp_dir
48
+
49
+ def get_output_directory():
50
+ global output_directory
51
+ return output_directory
52
+
53
+ def get_temp_directory():
54
+ global temp_directory
55
+ return temp_directory
56
+
57
+ def get_input_directory():
58
+ global input_directory
59
+ return input_directory
60
+
61
+
62
+ #NOTE: used in http server so don't put folders that should not be accessed remotely
63
+ def get_directory_by_type(type_name):
64
+ if type_name == "output":
65
+ return get_output_directory()
66
+ if type_name == "temp":
67
+ return get_temp_directory()
68
+ if type_name == "input":
69
+ return get_input_directory()
70
+ return None
71
+
72
+
73
+ # determine base_dir rely on annotation if name is 'filename.ext [annotation]' format
74
+ # otherwise use default_path as base_dir
75
+ def annotated_filepath(name):
76
+ if name.endswith("[output]"):
77
+ base_dir = get_output_directory()
78
+ name = name[:-9]
79
+ elif name.endswith("[input]"):
80
+ base_dir = get_input_directory()
81
+ name = name[:-8]
82
+ elif name.endswith("[temp]"):
83
+ base_dir = get_temp_directory()
84
+ name = name[:-7]
85
+ else:
86
+ return name, None
87
+
88
+ return name, base_dir
89
+
90
+
91
+ def get_annotated_filepath(name, default_dir=None):
92
+ name, base_dir = annotated_filepath(name)
93
+
94
+ if base_dir is None:
95
+ if default_dir is not None:
96
+ base_dir = default_dir
97
+ else:
98
+ base_dir = get_input_directory() # fallback path
99
+
100
+ return os.path.join(base_dir, name)
101
+
102
+
103
+ def exists_annotated_filepath(name):
104
+ name, base_dir = annotated_filepath(name)
105
+
106
+ if base_dir is None:
107
+ base_dir = get_input_directory() # fallback path
108
+
109
+ filepath = os.path.join(base_dir, name)
110
+ return os.path.exists(filepath)
111
+
112
+
113
+ def add_model_folder_path(folder_name, full_folder_path):
114
+ global folder_names_and_paths
115
+ if folder_name in folder_names_and_paths:
116
+ folder_names_and_paths[folder_name][0].append(full_folder_path)
117
+ else:
118
+ folder_names_and_paths[folder_name] = ([full_folder_path], set())
119
+
120
+ def get_folder_paths(folder_name):
121
+ return folder_names_and_paths[folder_name][0][:]
122
+
123
+ def recursive_search(directory, excluded_dir_names=None):
124
+ if not os.path.isdir(directory):
125
+ return [], {}
126
+
127
+ if excluded_dir_names is None:
128
+ excluded_dir_names = []
129
+
130
+ result = []
131
+ dirs = {directory: os.path.getmtime(directory)}
132
+ for dirpath, subdirs, filenames in os.walk(directory, followlinks=True, topdown=True):
133
+ subdirs[:] = [d for d in subdirs if d not in excluded_dir_names]
134
+ for file_name in filenames:
135
+ relative_path = os.path.relpath(os.path.join(dirpath, file_name), directory)
136
+ result.append(relative_path)
137
+ for d in subdirs:
138
+ path = os.path.join(dirpath, d)
139
+ dirs[path] = os.path.getmtime(path)
140
+ return result, dirs
141
+
142
+ def filter_files_extensions(files, extensions):
143
+ return sorted(list(filter(lambda a: os.path.splitext(a)[-1].lower() in extensions, files)))
144
+
145
+
146
+
147
+ def get_full_path(folder_name, filename):
148
+ global folder_names_and_paths
149
+ if folder_name not in folder_names_and_paths:
150
+ return None
151
+ folders = folder_names_and_paths[folder_name]
152
+ filename = os.path.relpath(os.path.join("/", filename), "/")
153
+ for x in folders[0]:
154
+ full_path = os.path.join(x, filename)
155
+ if os.path.isfile(full_path):
156
+ return full_path
157
+
158
+ return None
159
+
160
+ def get_filename_list_(folder_name):
161
+ global folder_names_and_paths
162
+ output_list = set()
163
+ folders = folder_names_and_paths[folder_name]
164
+ output_folders = {}
165
+ for x in folders[0]:
166
+ files, folders_all = recursive_search(x, excluded_dir_names=[".git"])
167
+ output_list.update(filter_files_extensions(files, folders[1]))
168
+ output_folders = {**output_folders, **folders_all}
169
+
170
+ return (sorted(list(output_list)), output_folders, time.perf_counter())
171
+
172
+ def cached_filename_list_(folder_name):
173
+ global filename_list_cache
174
+ global folder_names_and_paths
175
+ if folder_name not in filename_list_cache:
176
+ return None
177
+ out = filename_list_cache[folder_name]
178
+ if time.perf_counter() < (out[2] + 0.5):
179
+ return out
180
+ for x in out[1]:
181
+ time_modified = out[1][x]
182
+ folder = x
183
+ if os.path.getmtime(folder) != time_modified:
184
+ return None
185
+
186
+ folders = folder_names_and_paths[folder_name]
187
+ for x in folders[0]:
188
+ if os.path.isdir(x):
189
+ if x not in out[1]:
190
+ return None
191
+
192
+ return out
193
+
194
+ def get_filename_list(folder_name):
195
+ out = cached_filename_list_(folder_name)
196
+ if out is None:
197
+ out = get_filename_list_(folder_name)
198
+ global filename_list_cache
199
+ filename_list_cache[folder_name] = out
200
+ return list(out[0])
201
+
202
+ def get_save_image_path(filename_prefix, output_dir, image_width=0, image_height=0):
203
+ def map_filename(filename):
204
+ prefix_len = len(os.path.basename(filename_prefix))
205
+ prefix = filename[:prefix_len + 1]
206
+ try:
207
+ digits = int(filename[prefix_len + 1:].split('_')[0])
208
+ except:
209
+ digits = 0
210
+ return (digits, prefix)
211
+
212
+ def compute_vars(input, image_width, image_height):
213
+ input = input.replace("%width%", str(image_width))
214
+ input = input.replace("%height%", str(image_height))
215
+ return input
216
+
217
+ filename_prefix = compute_vars(filename_prefix, image_width, image_height)
218
+
219
+ subfolder = os.path.dirname(os.path.normpath(filename_prefix))
220
+ filename = os.path.basename(os.path.normpath(filename_prefix))
221
+
222
+ full_output_folder = os.path.join(output_dir, subfolder)
223
+
224
+ if os.path.commonpath((output_dir, os.path.abspath(full_output_folder))) != output_dir:
225
+ print("Saving image outside the output folder is not allowed.")
226
+ return {}
227
+
228
+ try:
229
+ counter = max(filter(lambda a: a[1][:-1] == filename and a[1][-1] == "_", map(map_filename, os.listdir(full_output_folder))))[0] + 1
230
+ except ValueError:
231
+ counter = 1
232
+ except FileNotFoundError:
233
+ os.makedirs(full_output_folder, exist_ok=True)
234
+ counter = 1
235
+ return full_output_folder, filename, counter, subfolder, filename_prefix
latent_preview.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 folder_paths
8
+
9
+ MAX_PREVIEW_RESOLUTION = 512
10
+
11
+ class LatentPreviewer:
12
+ def decode_latent_to_preview(self, x0):
13
+ pass
14
+
15
+ def decode_latent_to_preview_image(self, preview_format, x0):
16
+ preview_image = self.decode_latent_to_preview(x0)
17
+ return ("JPEG", preview_image, MAX_PREVIEW_RESOLUTION)
18
+
19
+ class TAESDPreviewerImpl(LatentPreviewer):
20
+ def __init__(self, taesd):
21
+ self.taesd = taesd
22
+
23
+ def decode_latent_to_preview(self, x0):
24
+ x_sample = self.taesd.decoder(x0)[0].detach()
25
+ # x_sample = self.taesd.unscale_latents(x_sample).div(4).add(0.5) # returns value in [-2, 2]
26
+ x_sample = x_sample.sub(0.5).mul(2)
27
+
28
+ x_sample = torch.clamp((x_sample + 1.0) / 2.0, min=0.0, max=1.0)
29
+ x_sample = 255. * np.moveaxis(x_sample.cpu().numpy(), 0, 2)
30
+ x_sample = x_sample.astype(np.uint8)
31
+
32
+ preview_image = Image.fromarray(x_sample)
33
+ return preview_image
34
+
35
+
36
+ class Latent2RGBPreviewer(LatentPreviewer):
37
+ def __init__(self, latent_rgb_factors):
38
+ self.latent_rgb_factors = torch.tensor(latent_rgb_factors, device="cpu")
39
+
40
+ def decode_latent_to_preview(self, x0):
41
+ latent_image = x0[0].permute(1, 2, 0).cpu() @ self.latent_rgb_factors
42
+
43
+ latents_ubyte = (((latent_image + 1) / 2)
44
+ .clamp(0, 1) # change scale from -1..1 to 0..1
45
+ .mul(0xFF) # to 0..255
46
+ .byte()).cpu()
47
+
48
+ return Image.fromarray(latents_ubyte.numpy())
49
+
50
+
51
+ def get_previewer(device, latent_format):
52
+ previewer = None
53
+ method = args.preview_method
54
+ if method != LatentPreviewMethod.NoPreviews:
55
+ # TODO previewer methods
56
+ taesd_decoder_path = None
57
+ if latent_format.taesd_decoder_name is not None:
58
+ taesd_decoder_path = folder_paths.get_full_path("vae_approx", latent_format.taesd_decoder_name)
59
+
60
+ if method == LatentPreviewMethod.Auto:
61
+ method = LatentPreviewMethod.Latent2RGB
62
+ if taesd_decoder_path:
63
+ method = LatentPreviewMethod.TAESD
64
+
65
+ if method == LatentPreviewMethod.TAESD:
66
+ if taesd_decoder_path:
67
+ taesd = TAESD(None, taesd_decoder_path).to(device)
68
+ previewer = TAESDPreviewerImpl(taesd)
69
+ else:
70
+ print("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
+
main.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
9
+ def execute_prestartup_script():
10
+ def execute_script(script_path):
11
+ module_name = os.path.splitext(script_path)[0]
12
+ try:
13
+ spec = importlib.util.spec_from_file_location(module_name, script_path)
14
+ module = importlib.util.module_from_spec(spec)
15
+ spec.loader.exec_module(module)
16
+ return True
17
+ except Exception as e:
18
+ print(f"Failed to execute startup-script: {script_path} / {e}")
19
+ return False
20
+
21
+ node_paths = folder_paths.get_folder_paths("custom_nodes")
22
+ for custom_node_path in node_paths:
23
+ possible_modules = os.listdir(custom_node_path)
24
+ node_prestartup_times = []
25
+
26
+ for possible_module in possible_modules:
27
+ module_path = os.path.join(custom_node_path, possible_module)
28
+ if os.path.isfile(module_path) or module_path.endswith(".disabled") or module_path == "__pycache__":
29
+ continue
30
+
31
+ script_path = os.path.join(module_path, "prestartup_script.py")
32
+ if os.path.exists(script_path):
33
+ time_before = time.perf_counter()
34
+ success = execute_script(script_path)
35
+ node_prestartup_times.append((time.perf_counter() - time_before, module_path, success))
36
+ if len(node_prestartup_times) > 0:
37
+ print("\nPrestartup times for custom nodes:")
38
+ for n in sorted(node_prestartup_times):
39
+ if n[2]:
40
+ import_message = ""
41
+ else:
42
+ import_message = " (PRESTARTUP FAILED)"
43
+ print("{:6.1f} seconds{}:".format(n[0], import_message), n[1])
44
+ print()
45
+
46
+ execute_prestartup_script()
47
+
48
+
49
+ # Main code
50
+ import asyncio
51
+ import itertools
52
+ import shutil
53
+ import threading
54
+ import gc
55
+
56
+ from comfy.cli_args import args
57
+
58
+ if os.name == "nt":
59
+ import logging
60
+ logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
61
+
62
+ if __name__ == "__main__":
63
+ if args.cuda_device is not None:
64
+ os.environ['CUDA_VISIBLE_DEVICES'] = str(args.cuda_device)
65
+ print("Set cuda device to:", args.cuda_device)
66
+
67
+ import cuda_malloc
68
+
69
+ import comfy.utils
70
+ import yaml
71
+
72
+ import execution
73
+ import server
74
+ from server import BinaryEventTypes
75
+ from nodes import init_custom_nodes
76
+ import comfy.model_management
77
+
78
+ def cuda_malloc_warning():
79
+ device = comfy.model_management.get_torch_device()
80
+ device_name = comfy.model_management.get_torch_device_name(device)
81
+ cuda_malloc_warning = False
82
+ if "cudaMallocAsync" in device_name:
83
+ for b in cuda_malloc.blacklist:
84
+ if b in device_name:
85
+ cuda_malloc_warning = True
86
+ if cuda_malloc_warning:
87
+ print("\nWARNING: this card most likely does not support cuda-malloc, if you get \"CUDA error\" please run ComfyUI with: --disable-cuda-malloc\n")
88
+
89
+ def prompt_worker(q, server):
90
+ e = execution.PromptExecutor(server)
91
+ while True:
92
+ item, item_id = q.get()
93
+ execution_start_time = time.perf_counter()
94
+ prompt_id = item[1]
95
+ e.execute(item[2], prompt_id, item[3], item[4])
96
+ q.task_done(item_id, e.outputs_ui)
97
+ if server.client_id is not None:
98
+ server.send_sync("executing", { "node": None, "prompt_id": prompt_id }, server.client_id)
99
+
100
+ print("Prompt executed in {:.2f} seconds".format(time.perf_counter() - execution_start_time))
101
+ gc.collect()
102
+ comfy.model_management.soft_empty_cache()
103
+
104
+ async def run(server, address='', port=8188, verbose=True, call_on_start=None):
105
+ await asyncio.gather(server.start(address, port, verbose, call_on_start), server.publish_loop())
106
+
107
+
108
+ def hijack_progress(server):
109
+ def hook(value, total, preview_image):
110
+ comfy.model_management.throw_exception_if_processing_interrupted()
111
+ server.send_sync("progress", {"value": value, "max": total}, server.client_id)
112
+ if preview_image is not None:
113
+ server.send_sync(BinaryEventTypes.UNENCODED_PREVIEW_IMAGE, preview_image, server.client_id)
114
+ comfy.utils.set_progress_bar_global_hook(hook)
115
+
116
+
117
+ def cleanup_temp():
118
+ temp_dir = folder_paths.get_temp_directory()
119
+ if os.path.exists(temp_dir):
120
+ shutil.rmtree(temp_dir, ignore_errors=True)
121
+
122
+
123
+ def load_extra_path_config(yaml_path):
124
+ with open(yaml_path, 'r') as stream:
125
+ config = yaml.safe_load(stream)
126
+ for c in config:
127
+ conf = config[c]
128
+ if conf is None:
129
+ continue
130
+ base_path = None
131
+ if "base_path" in conf:
132
+ base_path = conf.pop("base_path")
133
+ for x in conf:
134
+ for y in conf[x].split("\n"):
135
+ if len(y) == 0:
136
+ continue
137
+ full_path = y
138
+ if base_path is not None:
139
+ full_path = os.path.join(base_path, full_path)
140
+ print("Adding extra search path", x, full_path)
141
+ folder_paths.add_model_folder_path(x, full_path)
142
+
143
+
144
+ if __name__ == "__main__":
145
+ if args.temp_directory:
146
+ temp_dir = os.path.join(os.path.abspath(args.temp_directory), "temp")
147
+ print(f"Setting temp directory to: {temp_dir}")
148
+ folder_paths.set_temp_directory(temp_dir)
149
+ cleanup_temp()
150
+
151
+ loop = asyncio.new_event_loop()
152
+ asyncio.set_event_loop(loop)
153
+ server = server.PromptServer(loop)
154
+ q = execution.PromptQueue(server)
155
+
156
+ extra_model_paths_config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "extra_model_paths.yaml")
157
+ if os.path.isfile(extra_model_paths_config_path):
158
+ load_extra_path_config(extra_model_paths_config_path)
159
+
160
+ if args.extra_model_paths_config:
161
+ for config_path in itertools.chain(*args.extra_model_paths_config):
162
+ load_extra_path_config(config_path)
163
+
164
+ init_custom_nodes()
165
+
166
+ cuda_malloc_warning()
167
+
168
+ server.add_routes()
169
+ hijack_progress(server)
170
+
171
+ threading.Thread(target=prompt_worker, daemon=True, args=(q, server,)).start()
172
+
173
+ if args.output_directory:
174
+ output_dir = os.path.abspath(args.output_directory)
175
+ print(f"Setting output directory to: {output_dir}")
176
+ folder_paths.set_output_directory(output_dir)
177
+
178
+ if args.quick_test_for_ci:
179
+ exit(0)
180
+
181
+ call_on_start = None
182
+ if args.auto_launch:
183
+ def startup_server(address, port):
184
+ import webbrowser
185
+ if os.name == 'nt' and address == '0.0.0.0':
186
+ address = '127.0.0.1'
187
+ webbrowser.open(f"http://{address}:{port}")
188
+ call_on_start = startup_server
189
+
190
+ try:
191
+ loop.run_until_complete(run(server, address=args.listen, port=args.port, verbose=not args.dont_print_server, call_on_start=call_on_start))
192
+ except KeyboardInterrupt:
193
+ print("\nStopped server")
194
+
195
+ cleanup_temp()
nodes.py ADDED
@@ -0,0 +1,1786 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
12
+ from PIL import Image, ImageOps
13
+ from PIL.PngImagePlugin import PngInfo
14
+ import numpy as np
15
+ import safetensors.torch
16
+
17
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy"))
18
+
19
+
20
+ import comfy.diffusers_load
21
+ import comfy.samplers
22
+ import comfy.sample
23
+ import comfy.sd
24
+ import comfy.utils
25
+ import comfy.controlnet
26
+
27
+ import comfy.clip_vision
28
+
29
+ import comfy.model_management
30
+ from comfy.cli_args import args
31
+
32
+ import importlib
33
+
34
+ import folder_paths
35
+ import latent_preview
36
+
37
+ def before_node_execution():
38
+ comfy.model_management.throw_exception_if_processing_interrupted()
39
+
40
+ def interrupt_processing(value=True):
41
+ comfy.model_management.interrupt_current_processing(value)
42
+
43
+ MAX_RESOLUTION=8192
44
+
45
+ class CLIPTextEncode:
46
+ @classmethod
47
+ def INPUT_TYPES(s):
48
+ return {"required": {"text": ("STRING", {"multiline": True}), "clip": ("CLIP", )}}
49
+ RETURN_TYPES = ("CONDITIONING",)
50
+ FUNCTION = "encode"
51
+
52
+ CATEGORY = "conditioning"
53
+
54
+ def encode(self, clip, text):
55
+ tokens = clip.tokenize(text)
56
+ cond, pooled = clip.encode_from_tokens(tokens, return_pooled=True)
57
+ return ([[cond, {"pooled_output": pooled}]], )
58
+
59
+ class ConditioningCombine:
60
+ @classmethod
61
+ def INPUT_TYPES(s):
62
+ return {"required": {"conditioning_1": ("CONDITIONING", ), "conditioning_2": ("CONDITIONING", )}}
63
+ RETURN_TYPES = ("CONDITIONING",)
64
+ FUNCTION = "combine"
65
+
66
+ CATEGORY = "conditioning"
67
+
68
+ def combine(self, conditioning_1, conditioning_2):
69
+ return (conditioning_1 + conditioning_2, )
70
+
71
+ class ConditioningAverage :
72
+ @classmethod
73
+ def INPUT_TYPES(s):
74
+ return {"required": {"conditioning_to": ("CONDITIONING", ), "conditioning_from": ("CONDITIONING", ),
75
+ "conditioning_to_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01})
76
+ }}
77
+ RETURN_TYPES = ("CONDITIONING",)
78
+ FUNCTION = "addWeighted"
79
+
80
+ CATEGORY = "conditioning"
81
+
82
+ def addWeighted(self, conditioning_to, conditioning_from, conditioning_to_strength):
83
+ out = []
84
+
85
+ if len(conditioning_from) > 1:
86
+ print("Warning: ConditioningAverage conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.")
87
+
88
+ cond_from = conditioning_from[0][0]
89
+ pooled_output_from = conditioning_from[0][1].get("pooled_output", None)
90
+
91
+ for i in range(len(conditioning_to)):
92
+ t1 = conditioning_to[i][0]
93
+ pooled_output_to = conditioning_to[i][1].get("pooled_output", pooled_output_from)
94
+ t0 = cond_from[:,:t1.shape[1]]
95
+ if t0.shape[1] < t1.shape[1]:
96
+ t0 = torch.cat([t0] + [torch.zeros((1, (t1.shape[1] - t0.shape[1]), t1.shape[2]))], dim=1)
97
+
98
+ tw = torch.mul(t1, conditioning_to_strength) + torch.mul(t0, (1.0 - conditioning_to_strength))
99
+ t_to = conditioning_to[i][1].copy()
100
+ if pooled_output_from is not None and pooled_output_to is not None:
101
+ t_to["pooled_output"] = torch.mul(pooled_output_to, conditioning_to_strength) + torch.mul(pooled_output_from, (1.0 - conditioning_to_strength))
102
+ elif pooled_output_from is not None:
103
+ t_to["pooled_output"] = pooled_output_from
104
+
105
+ n = [tw, t_to]
106
+ out.append(n)
107
+ return (out, )
108
+
109
+ class ConditioningConcat:
110
+ @classmethod
111
+ def INPUT_TYPES(s):
112
+ return {"required": {
113
+ "conditioning_to": ("CONDITIONING",),
114
+ "conditioning_from": ("CONDITIONING",),
115
+ }}
116
+ RETURN_TYPES = ("CONDITIONING",)
117
+ FUNCTION = "concat"
118
+
119
+ CATEGORY = "conditioning"
120
+
121
+ def concat(self, conditioning_to, conditioning_from):
122
+ out = []
123
+
124
+ if len(conditioning_from) > 1:
125
+ print("Warning: ConditioningConcat conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.")
126
+
127
+ cond_from = conditioning_from[0][0]
128
+
129
+ for i in range(len(conditioning_to)):
130
+ t1 = conditioning_to[i][0]
131
+ tw = torch.cat((t1, cond_from),1)
132
+ n = [tw, conditioning_to[i][1].copy()]
133
+ out.append(n)
134
+
135
+ return (out, )
136
+
137
+ class ConditioningSetArea:
138
+ @classmethod
139
+ def INPUT_TYPES(s):
140
+ return {"required": {"conditioning": ("CONDITIONING", ),
141
+ "width": ("INT", {"default": 64, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
142
+ "height": ("INT", {"default": 64, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
143
+ "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
144
+ "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
145
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
146
+ }}
147
+ RETURN_TYPES = ("CONDITIONING",)
148
+ FUNCTION = "append"
149
+
150
+ CATEGORY = "conditioning"
151
+
152
+ def append(self, conditioning, width, height, x, y, strength):
153
+ c = []
154
+ for t in conditioning:
155
+ n = [t[0], t[1].copy()]
156
+ n[1]['area'] = (height // 8, width // 8, y // 8, x // 8)
157
+ n[1]['strength'] = strength
158
+ n[1]['set_area_to_bounds'] = False
159
+ c.append(n)
160
+ return (c, )
161
+
162
+ class ConditioningSetAreaPercentage:
163
+ @classmethod
164
+ def INPUT_TYPES(s):
165
+ return {"required": {"conditioning": ("CONDITIONING", ),
166
+ "width": ("FLOAT", {"default": 1.0, "min": 0, "max": 1.0, "step": 0.01}),
167
+ "height": ("FLOAT", {"default": 1.0, "min": 0, "max": 1.0, "step": 0.01}),
168
+ "x": ("FLOAT", {"default": 0, "min": 0, "max": 1.0, "step": 0.01}),
169
+ "y": ("FLOAT", {"default": 0, "min": 0, "max": 1.0, "step": 0.01}),
170
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
171
+ }}
172
+ RETURN_TYPES = ("CONDITIONING",)
173
+ FUNCTION = "append"
174
+
175
+ CATEGORY = "conditioning"
176
+
177
+ def append(self, conditioning, width, height, x, y, strength):
178
+ c = []
179
+ for t in conditioning:
180
+ n = [t[0], t[1].copy()]
181
+ n[1]['area'] = ("percentage", height, width, y, x)
182
+ n[1]['strength'] = strength
183
+ n[1]['set_area_to_bounds'] = False
184
+ c.append(n)
185
+ return (c, )
186
+
187
+ class ConditioningSetMask:
188
+ @classmethod
189
+ def INPUT_TYPES(s):
190
+ return {"required": {"conditioning": ("CONDITIONING", ),
191
+ "mask": ("MASK", ),
192
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
193
+ "set_cond_area": (["default", "mask bounds"],),
194
+ }}
195
+ RETURN_TYPES = ("CONDITIONING",)
196
+ FUNCTION = "append"
197
+
198
+ CATEGORY = "conditioning"
199
+
200
+ def append(self, conditioning, mask, set_cond_area, strength):
201
+ c = []
202
+ set_area_to_bounds = False
203
+ if set_cond_area != "default":
204
+ set_area_to_bounds = True
205
+ if len(mask.shape) < 3:
206
+ mask = mask.unsqueeze(0)
207
+ for t in conditioning:
208
+ n = [t[0], t[1].copy()]
209
+ _, h, w = mask.shape
210
+ n[1]['mask'] = mask
211
+ n[1]['set_area_to_bounds'] = set_area_to_bounds
212
+ n[1]['mask_strength'] = strength
213
+ c.append(n)
214
+ return (c, )
215
+
216
+ class ConditioningZeroOut:
217
+ @classmethod
218
+ def INPUT_TYPES(s):
219
+ return {"required": {"conditioning": ("CONDITIONING", )}}
220
+ RETURN_TYPES = ("CONDITIONING",)
221
+ FUNCTION = "zero_out"
222
+
223
+ CATEGORY = "advanced/conditioning"
224
+
225
+ def zero_out(self, conditioning):
226
+ c = []
227
+ for t in conditioning:
228
+ d = t[1].copy()
229
+ if "pooled_output" in d:
230
+ d["pooled_output"] = torch.zeros_like(d["pooled_output"])
231
+ n = [torch.zeros_like(t[0]), d]
232
+ c.append(n)
233
+ return (c, )
234
+
235
+ class ConditioningSetTimestepRange:
236
+ @classmethod
237
+ def INPUT_TYPES(s):
238
+ return {"required": {"conditioning": ("CONDITIONING", ),
239
+ "start": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
240
+ "end": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
241
+ }}
242
+ RETURN_TYPES = ("CONDITIONING",)
243
+ FUNCTION = "set_range"
244
+
245
+ CATEGORY = "advanced/conditioning"
246
+
247
+ def set_range(self, conditioning, start, end):
248
+ c = []
249
+ for t in conditioning:
250
+ d = t[1].copy()
251
+ d['start_percent'] = 1.0 - start
252
+ d['end_percent'] = 1.0 - end
253
+ n = [t[0], d]
254
+ c.append(n)
255
+ return (c, )
256
+
257
+ class VAEDecode:
258
+ @classmethod
259
+ def INPUT_TYPES(s):
260
+ return {"required": { "samples": ("LATENT", ), "vae": ("VAE", )}}
261
+ RETURN_TYPES = ("IMAGE",)
262
+ FUNCTION = "decode"
263
+
264
+ CATEGORY = "latent"
265
+
266
+ def decode(self, vae, samples):
267
+ return (vae.decode(samples["samples"]), )
268
+
269
+ class VAEDecodeTiled:
270
+ @classmethod
271
+ def INPUT_TYPES(s):
272
+ return {"required": {"samples": ("LATENT", ), "vae": ("VAE", ),
273
+ "tile_size": ("INT", {"default": 512, "min": 320, "max": 4096, "step": 64})
274
+ }}
275
+ RETURN_TYPES = ("IMAGE",)
276
+ FUNCTION = "decode"
277
+
278
+ CATEGORY = "_for_testing"
279
+
280
+ def decode(self, vae, samples, tile_size):
281
+ return (vae.decode_tiled(samples["samples"], tile_x=tile_size // 8, tile_y=tile_size // 8, ), )
282
+
283
+ class VAEEncode:
284
+ @classmethod
285
+ def INPUT_TYPES(s):
286
+ return {"required": { "pixels": ("IMAGE", ), "vae": ("VAE", )}}
287
+ RETURN_TYPES = ("LATENT",)
288
+ FUNCTION = "encode"
289
+
290
+ CATEGORY = "latent"
291
+
292
+ @staticmethod
293
+ def vae_encode_crop_pixels(pixels):
294
+ x = (pixels.shape[1] // 8) * 8
295
+ y = (pixels.shape[2] // 8) * 8
296
+ if pixels.shape[1] != x or pixels.shape[2] != y:
297
+ x_offset = (pixels.shape[1] % 8) // 2
298
+ y_offset = (pixels.shape[2] % 8) // 2
299
+ pixels = pixels[:, x_offset:x + x_offset, y_offset:y + y_offset, :]
300
+ return pixels
301
+
302
+ def encode(self, vae, pixels):
303
+ pixels = self.vae_encode_crop_pixels(pixels)
304
+ t = vae.encode(pixels[:,:,:,:3])
305
+ return ({"samples":t}, )
306
+
307
+ class VAEEncodeTiled:
308
+ @classmethod
309
+ def INPUT_TYPES(s):
310
+ return {"required": {"pixels": ("IMAGE", ), "vae": ("VAE", ),
311
+ "tile_size": ("INT", {"default": 512, "min": 320, "max": 4096, "step": 64})
312
+ }}
313
+ RETURN_TYPES = ("LATENT",)
314
+ FUNCTION = "encode"
315
+
316
+ CATEGORY = "_for_testing"
317
+
318
+ def encode(self, vae, pixels, tile_size):
319
+ pixels = VAEEncode.vae_encode_crop_pixels(pixels)
320
+ t = vae.encode_tiled(pixels[:,:,:,:3], tile_x=tile_size, tile_y=tile_size, )
321
+ return ({"samples":t}, )
322
+
323
+ class VAEEncodeForInpaint:
324
+ @classmethod
325
+ def INPUT_TYPES(s):
326
+ return {"required": { "pixels": ("IMAGE", ), "vae": ("VAE", ), "mask": ("MASK", ), "grow_mask_by": ("INT", {"default": 6, "min": 0, "max": 64, "step": 1}),}}
327
+ RETURN_TYPES = ("LATENT",)
328
+ FUNCTION = "encode"
329
+
330
+ CATEGORY = "latent/inpaint"
331
+
332
+ def encode(self, vae, pixels, mask, grow_mask_by=6):
333
+ x = (pixels.shape[1] // 8) * 8
334
+ y = (pixels.shape[2] // 8) * 8
335
+ mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(pixels.shape[1], pixels.shape[2]), mode="bilinear")
336
+
337
+ pixels = pixels.clone()
338
+ if pixels.shape[1] != x or pixels.shape[2] != y:
339
+ x_offset = (pixels.shape[1] % 8) // 2
340
+ y_offset = (pixels.shape[2] % 8) // 2
341
+ pixels = pixels[:,x_offset:x + x_offset, y_offset:y + y_offset,:]
342
+ mask = mask[:,:,x_offset:x + x_offset, y_offset:y + y_offset]
343
+
344
+ #grow mask by a few pixels to keep things seamless in latent space
345
+ if grow_mask_by == 0:
346
+ mask_erosion = mask
347
+ else:
348
+ kernel_tensor = torch.ones((1, 1, grow_mask_by, grow_mask_by))
349
+ padding = math.ceil((grow_mask_by - 1) / 2)
350
+
351
+ mask_erosion = torch.clamp(torch.nn.functional.conv2d(mask.round(), kernel_tensor, padding=padding), 0, 1)
352
+
353
+ m = (1.0 - mask.round()).squeeze(1)
354
+ for i in range(3):
355
+ pixels[:,:,:,i] -= 0.5
356
+ pixels[:,:,:,i] *= m
357
+ pixels[:,:,:,i] += 0.5
358
+ t = vae.encode(pixels)
359
+
360
+ return ({"samples":t, "noise_mask": (mask_erosion[:,:,:x,:y].round())}, )
361
+
362
+ class SaveLatent:
363
+ def __init__(self):
364
+ self.output_dir = folder_paths.get_output_directory()
365
+
366
+ @classmethod
367
+ def INPUT_TYPES(s):
368
+ return {"required": { "samples": ("LATENT", ),
369
+ "filename_prefix": ("STRING", {"default": "latents/ComfyUI"})},
370
+ "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
371
+ }
372
+ RETURN_TYPES = ()
373
+ FUNCTION = "save"
374
+
375
+ OUTPUT_NODE = True
376
+
377
+ CATEGORY = "_for_testing"
378
+
379
+ def save(self, samples, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None):
380
+ full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir)
381
+
382
+ # support save metadata for latent sharing
383
+ prompt_info = ""
384
+ if prompt is not None:
385
+ prompt_info = json.dumps(prompt)
386
+
387
+ metadata = None
388
+ if not args.disable_metadata:
389
+ metadata = {"prompt": prompt_info}
390
+ if extra_pnginfo is not None:
391
+ for x in extra_pnginfo:
392
+ metadata[x] = json.dumps(extra_pnginfo[x])
393
+
394
+ file = f"{filename}_{counter:05}_.latent"
395
+
396
+ results = list()
397
+ results.append({
398
+ "filename": file,
399
+ "subfolder": subfolder,
400
+ "type": "output"
401
+ })
402
+
403
+ file = os.path.join(full_output_folder, file)
404
+
405
+ output = {}
406
+ output["latent_tensor"] = samples["samples"]
407
+ output["latent_format_version_0"] = torch.tensor([])
408
+
409
+ comfy.utils.save_torch_file(output, file, metadata=metadata)
410
+ return { "ui": { "latents": results } }
411
+
412
+
413
+ class LoadLatent:
414
+ @classmethod
415
+ def INPUT_TYPES(s):
416
+ input_dir = folder_paths.get_input_directory()
417
+ files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f)) and f.endswith(".latent")]
418
+ return {"required": {"latent": [sorted(files), ]}, }
419
+
420
+ CATEGORY = "_for_testing"
421
+
422
+ RETURN_TYPES = ("LATENT", )
423
+ FUNCTION = "load"
424
+
425
+ def load(self, latent):
426
+ latent_path = folder_paths.get_annotated_filepath(latent)
427
+ latent = safetensors.torch.load_file(latent_path, device="cpu")
428
+ multiplier = 1.0
429
+ if "latent_format_version_0" not in latent:
430
+ multiplier = 1.0 / 0.18215
431
+ samples = {"samples": latent["latent_tensor"].float() * multiplier}
432
+ return (samples, )
433
+
434
+ @classmethod
435
+ def IS_CHANGED(s, latent):
436
+ image_path = folder_paths.get_annotated_filepath(latent)
437
+ m = hashlib.sha256()
438
+ with open(image_path, 'rb') as f:
439
+ m.update(f.read())
440
+ return m.digest().hex()
441
+
442
+ @classmethod
443
+ def VALIDATE_INPUTS(s, latent):
444
+ if not folder_paths.exists_annotated_filepath(latent):
445
+ return "Invalid latent file: {}".format(latent)
446
+ return True
447
+
448
+
449
+ class CheckpointLoader:
450
+ @classmethod
451
+ def INPUT_TYPES(s):
452
+ return {"required": { "config_name": (folder_paths.get_filename_list("configs"), ),
453
+ "ckpt_name": (folder_paths.get_filename_list("checkpoints"), )}}
454
+ RETURN_TYPES = ("MODEL", "CLIP", "VAE")
455
+ FUNCTION = "load_checkpoint"
456
+
457
+ CATEGORY = "advanced/loaders"
458
+
459
+ def load_checkpoint(self, config_name, ckpt_name, output_vae=True, output_clip=True):
460
+ config_path = folder_paths.get_full_path("configs", config_name)
461
+ ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
462
+ return comfy.sd.load_checkpoint(config_path, ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
463
+
464
+ class CheckpointLoaderSimple:
465
+ @classmethod
466
+ def INPUT_TYPES(s):
467
+ return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ),
468
+ }}
469
+ RETURN_TYPES = ("MODEL", "CLIP", "VAE")
470
+ FUNCTION = "load_checkpoint"
471
+
472
+ CATEGORY = "loaders"
473
+
474
+ def load_checkpoint(self, ckpt_name, output_vae=True, output_clip=True):
475
+ ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
476
+ out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
477
+ return out[:3]
478
+
479
+ class DiffusersLoader:
480
+ @classmethod
481
+ def INPUT_TYPES(cls):
482
+ paths = []
483
+ for search_path in folder_paths.get_folder_paths("diffusers"):
484
+ if os.path.exists(search_path):
485
+ for root, subdir, files in os.walk(search_path, followlinks=True):
486
+ if "model_index.json" in files:
487
+ paths.append(os.path.relpath(root, start=search_path))
488
+
489
+ return {"required": {"model_path": (paths,), }}
490
+ RETURN_TYPES = ("MODEL", "CLIP", "VAE")
491
+ FUNCTION = "load_checkpoint"
492
+
493
+ CATEGORY = "advanced/loaders/deprecated"
494
+
495
+ def load_checkpoint(self, model_path, output_vae=True, output_clip=True):
496
+ for search_path in folder_paths.get_folder_paths("diffusers"):
497
+ if os.path.exists(search_path):
498
+ path = os.path.join(search_path, model_path)
499
+ if os.path.exists(path):
500
+ model_path = path
501
+ break
502
+
503
+ return comfy.diffusers_load.load_diffusers(model_path, output_vae=output_vae, output_clip=output_clip, embedding_directory=folder_paths.get_folder_paths("embeddings"))
504
+
505
+
506
+ class unCLIPCheckpointLoader:
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", "CLIP_VISION")
512
+ FUNCTION = "load_checkpoint"
513
+
514
+ CATEGORY = "loaders"
515
+
516
+ def load_checkpoint(self, ckpt_name, output_vae=True, output_clip=True):
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, output_clipvision=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
519
+ return out
520
+
521
+ class CLIPSetLastLayer:
522
+ @classmethod
523
+ def INPUT_TYPES(s):
524
+ return {"required": { "clip": ("CLIP", ),
525
+ "stop_at_clip_layer": ("INT", {"default": -1, "min": -24, "max": -1, "step": 1}),
526
+ }}
527
+ RETURN_TYPES = ("CLIP",)
528
+ FUNCTION = "set_last_layer"
529
+
530
+ CATEGORY = "conditioning"
531
+
532
+ def set_last_layer(self, clip, stop_at_clip_layer):
533
+ clip = clip.clone()
534
+ clip.clip_layer(stop_at_clip_layer)
535
+ return (clip,)
536
+
537
+ class LoraLoader:
538
+ def __init__(self):
539
+ self.loaded_lora = None
540
+
541
+ @classmethod
542
+ def INPUT_TYPES(s):
543
+ return {"required": { "model": ("MODEL",),
544
+ "clip": ("CLIP", ),
545
+ "lora_name": (folder_paths.get_filename_list("loras"), ),
546
+ "strength_model": ("FLOAT", {"default": 1.0, "min": -20.0, "max": 20.0, "step": 0.01}),
547
+ "strength_clip": ("FLOAT", {"default": 1.0, "min": -20.0, "max": 20.0, "step": 0.01}),
548
+ }}
549
+ RETURN_TYPES = ("MODEL", "CLIP")
550
+ FUNCTION = "load_lora"
551
+
552
+ CATEGORY = "loaders"
553
+
554
+ def load_lora(self, model, clip, lora_name, strength_model, strength_clip):
555
+ if strength_model == 0 and strength_clip == 0:
556
+ return (model, clip)
557
+
558
+ lora_path = folder_paths.get_full_path("loras", lora_name)
559
+ lora = None
560
+ if self.loaded_lora is not None:
561
+ if self.loaded_lora[0] == lora_path:
562
+ lora = self.loaded_lora[1]
563
+ else:
564
+ temp = self.loaded_lora
565
+ self.loaded_lora = None
566
+ del temp
567
+
568
+ if lora is None:
569
+ lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
570
+ self.loaded_lora = (lora_path, lora)
571
+
572
+ model_lora, clip_lora = comfy.sd.load_lora_for_models(model, clip, lora, strength_model, strength_clip)
573
+ return (model_lora, clip_lora)
574
+
575
+ class VAELoader:
576
+ @classmethod
577
+ def INPUT_TYPES(s):
578
+ return {"required": { "vae_name": (folder_paths.get_filename_list("vae"), )}}
579
+ RETURN_TYPES = ("VAE",)
580
+ FUNCTION = "load_vae"
581
+
582
+ CATEGORY = "loaders"
583
+
584
+ #TODO: scale factor?
585
+ def load_vae(self, vae_name):
586
+ vae_path = folder_paths.get_full_path("vae", vae_name)
587
+ vae = comfy.sd.VAE(ckpt_path=vae_path)
588
+ return (vae,)
589
+
590
+ class ControlNetLoader:
591
+ @classmethod
592
+ def INPUT_TYPES(s):
593
+ return {"required": { "control_net_name": (folder_paths.get_filename_list("controlnet"), )}}
594
+
595
+ RETURN_TYPES = ("CONTROL_NET",)
596
+ FUNCTION = "load_controlnet"
597
+
598
+ CATEGORY = "loaders"
599
+
600
+ def load_controlnet(self, control_net_name):
601
+ controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
602
+ controlnet = comfy.controlnet.load_controlnet(controlnet_path)
603
+ return (controlnet,)
604
+
605
+ class DiffControlNetLoader:
606
+ @classmethod
607
+ def INPUT_TYPES(s):
608
+ return {"required": { "model": ("MODEL",),
609
+ "control_net_name": (folder_paths.get_filename_list("controlnet"), )}}
610
+
611
+ RETURN_TYPES = ("CONTROL_NET",)
612
+ FUNCTION = "load_controlnet"
613
+
614
+ CATEGORY = "loaders"
615
+
616
+ def load_controlnet(self, model, control_net_name):
617
+ controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
618
+ controlnet = comfy.controlnet.load_controlnet(controlnet_path, model)
619
+ return (controlnet,)
620
+
621
+
622
+ class ControlNetApply:
623
+ @classmethod
624
+ def INPUT_TYPES(s):
625
+ return {"required": {"conditioning": ("CONDITIONING", ),
626
+ "control_net": ("CONTROL_NET", ),
627
+ "image": ("IMAGE", ),
628
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01})
629
+ }}
630
+ RETURN_TYPES = ("CONDITIONING",)
631
+ FUNCTION = "apply_controlnet"
632
+
633
+ CATEGORY = "conditioning"
634
+
635
+ def apply_controlnet(self, conditioning, control_net, image, strength):
636
+ if strength == 0:
637
+ return (conditioning, )
638
+
639
+ c = []
640
+ control_hint = image.movedim(-1,1)
641
+ for t in conditioning:
642
+ n = [t[0], t[1].copy()]
643
+ c_net = control_net.copy().set_cond_hint(control_hint, strength)
644
+ if 'control' in t[1]:
645
+ c_net.set_previous_controlnet(t[1]['control'])
646
+ n[1]['control'] = c_net
647
+ n[1]['control_apply_to_uncond'] = True
648
+ c.append(n)
649
+ return (c, )
650
+
651
+
652
+ class ControlNetApplyAdvanced:
653
+ @classmethod
654
+ def INPUT_TYPES(s):
655
+ return {"required": {"positive": ("CONDITIONING", ),
656
+ "negative": ("CONDITIONING", ),
657
+ "control_net": ("CONTROL_NET", ),
658
+ "image": ("IMAGE", ),
659
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
660
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
661
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
662
+ }}
663
+
664
+ RETURN_TYPES = ("CONDITIONING","CONDITIONING")
665
+ RETURN_NAMES = ("positive", "negative")
666
+ FUNCTION = "apply_controlnet"
667
+
668
+ CATEGORY = "conditioning"
669
+
670
+ def apply_controlnet(self, positive, negative, control_net, image, strength, start_percent, end_percent):
671
+ if strength == 0:
672
+ return (positive, negative)
673
+
674
+ control_hint = image.movedim(-1,1)
675
+ cnets = {}
676
+
677
+ out = []
678
+ for conditioning in [positive, negative]:
679
+ c = []
680
+ for t in conditioning:
681
+ d = t[1].copy()
682
+
683
+ prev_cnet = d.get('control', None)
684
+ if prev_cnet in cnets:
685
+ c_net = cnets[prev_cnet]
686
+ else:
687
+ c_net = control_net.copy().set_cond_hint(control_hint, strength, (1.0 - start_percent, 1.0 - end_percent))
688
+ c_net.set_previous_controlnet(prev_cnet)
689
+ cnets[prev_cnet] = c_net
690
+
691
+ d['control'] = c_net
692
+ d['control_apply_to_uncond'] = False
693
+ n = [t[0], d]
694
+ c.append(n)
695
+ out.append(c)
696
+ return (out[0], out[1])
697
+
698
+
699
+ class UNETLoader:
700
+ @classmethod
701
+ def INPUT_TYPES(s):
702
+ return {"required": { "unet_name": (folder_paths.get_filename_list("unet"), ),
703
+ }}
704
+ RETURN_TYPES = ("MODEL",)
705
+ FUNCTION = "load_unet"
706
+
707
+ CATEGORY = "advanced/loaders"
708
+
709
+ def load_unet(self, unet_name):
710
+ unet_path = folder_paths.get_full_path("unet", unet_name)
711
+ model = comfy.sd.load_unet(unet_path)
712
+ return (model,)
713
+
714
+ class CLIPLoader:
715
+ @classmethod
716
+ def INPUT_TYPES(s):
717
+ return {"required": { "clip_name": (folder_paths.get_filename_list("clip"), ),
718
+ }}
719
+ RETURN_TYPES = ("CLIP",)
720
+ FUNCTION = "load_clip"
721
+
722
+ CATEGORY = "advanced/loaders"
723
+
724
+ def load_clip(self, clip_name):
725
+ clip_path = folder_paths.get_full_path("clip", clip_name)
726
+ clip = comfy.sd.load_clip(ckpt_paths=[clip_path], embedding_directory=folder_paths.get_folder_paths("embeddings"))
727
+ return (clip,)
728
+
729
+ class DualCLIPLoader:
730
+ @classmethod
731
+ def INPUT_TYPES(s):
732
+ return {"required": { "clip_name1": (folder_paths.get_filename_list("clip"), ), "clip_name2": (folder_paths.get_filename_list("clip"), ),
733
+ }}
734
+ RETURN_TYPES = ("CLIP",)
735
+ FUNCTION = "load_clip"
736
+
737
+ CATEGORY = "advanced/loaders"
738
+
739
+ def load_clip(self, clip_name1, clip_name2):
740
+ clip_path1 = folder_paths.get_full_path("clip", clip_name1)
741
+ clip_path2 = folder_paths.get_full_path("clip", clip_name2)
742
+ clip = comfy.sd.load_clip(ckpt_paths=[clip_path1, clip_path2], embedding_directory=folder_paths.get_folder_paths("embeddings"))
743
+ return (clip,)
744
+
745
+ class CLIPVisionLoader:
746
+ @classmethod
747
+ def INPUT_TYPES(s):
748
+ return {"required": { "clip_name": (folder_paths.get_filename_list("clip_vision"), ),
749
+ }}
750
+ RETURN_TYPES = ("CLIP_VISION",)
751
+ FUNCTION = "load_clip"
752
+
753
+ CATEGORY = "loaders"
754
+
755
+ def load_clip(self, clip_name):
756
+ clip_path = folder_paths.get_full_path("clip_vision", clip_name)
757
+ clip_vision = comfy.clip_vision.load(clip_path)
758
+ return (clip_vision,)
759
+
760
+ class CLIPVisionEncode:
761
+ @classmethod
762
+ def INPUT_TYPES(s):
763
+ return {"required": { "clip_vision": ("CLIP_VISION",),
764
+ "image": ("IMAGE",)
765
+ }}
766
+ RETURN_TYPES = ("CLIP_VISION_OUTPUT",)
767
+ FUNCTION = "encode"
768
+
769
+ CATEGORY = "conditioning"
770
+
771
+ def encode(self, clip_vision, image):
772
+ output = clip_vision.encode_image(image)
773
+ return (output,)
774
+
775
+ class StyleModelLoader:
776
+ @classmethod
777
+ def INPUT_TYPES(s):
778
+ return {"required": { "style_model_name": (folder_paths.get_filename_list("style_models"), )}}
779
+
780
+ RETURN_TYPES = ("STYLE_MODEL",)
781
+ FUNCTION = "load_style_model"
782
+
783
+ CATEGORY = "loaders"
784
+
785
+ def load_style_model(self, style_model_name):
786
+ style_model_path = folder_paths.get_full_path("style_models", style_model_name)
787
+ style_model = comfy.sd.load_style_model(style_model_path)
788
+ return (style_model,)
789
+
790
+
791
+ class StyleModelApply:
792
+ @classmethod
793
+ def INPUT_TYPES(s):
794
+ return {"required": {"conditioning": ("CONDITIONING", ),
795
+ "style_model": ("STYLE_MODEL", ),
796
+ "clip_vision_output": ("CLIP_VISION_OUTPUT", ),
797
+ }}
798
+ RETURN_TYPES = ("CONDITIONING",)
799
+ FUNCTION = "apply_stylemodel"
800
+
801
+ CATEGORY = "conditioning/style_model"
802
+
803
+ def apply_stylemodel(self, clip_vision_output, style_model, conditioning):
804
+ cond = style_model.get_cond(clip_vision_output).flatten(start_dim=0, end_dim=1).unsqueeze(dim=0)
805
+ c = []
806
+ for t in conditioning:
807
+ n = [torch.cat((t[0], cond), dim=1), t[1].copy()]
808
+ c.append(n)
809
+ return (c, )
810
+
811
+ class unCLIPConditioning:
812
+ @classmethod
813
+ def INPUT_TYPES(s):
814
+ return {"required": {"conditioning": ("CONDITIONING", ),
815
+ "clip_vision_output": ("CLIP_VISION_OUTPUT", ),
816
+ "strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
817
+ "noise_augmentation": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
818
+ }}
819
+ RETURN_TYPES = ("CONDITIONING",)
820
+ FUNCTION = "apply_adm"
821
+
822
+ CATEGORY = "conditioning"
823
+
824
+ def apply_adm(self, conditioning, clip_vision_output, strength, noise_augmentation):
825
+ if strength == 0:
826
+ return (conditioning, )
827
+
828
+ c = []
829
+ for t in conditioning:
830
+ o = t[1].copy()
831
+ x = {"clip_vision_output": clip_vision_output, "strength": strength, "noise_augmentation": noise_augmentation}
832
+ if "unclip_conditioning" in o:
833
+ o["unclip_conditioning"] = o["unclip_conditioning"][:] + [x]
834
+ else:
835
+ o["unclip_conditioning"] = [x]
836
+ n = [t[0], o]
837
+ c.append(n)
838
+ return (c, )
839
+
840
+ class GLIGENLoader:
841
+ @classmethod
842
+ def INPUT_TYPES(s):
843
+ return {"required": { "gligen_name": (folder_paths.get_filename_list("gligen"), )}}
844
+
845
+ RETURN_TYPES = ("GLIGEN",)
846
+ FUNCTION = "load_gligen"
847
+
848
+ CATEGORY = "loaders"
849
+
850
+ def load_gligen(self, gligen_name):
851
+ gligen_path = folder_paths.get_full_path("gligen", gligen_name)
852
+ gligen = comfy.sd.load_gligen(gligen_path)
853
+ return (gligen,)
854
+
855
+ class GLIGENTextBoxApply:
856
+ @classmethod
857
+ def INPUT_TYPES(s):
858
+ return {"required": {"conditioning_to": ("CONDITIONING", ),
859
+ "clip": ("CLIP", ),
860
+ "gligen_textbox_model": ("GLIGEN", ),
861
+ "text": ("STRING", {"multiline": True}),
862
+ "width": ("INT", {"default": 64, "min": 8, "max": MAX_RESOLUTION, "step": 8}),
863
+ "height": ("INT", {"default": 64, "min": 8, "max": MAX_RESOLUTION, "step": 8}),
864
+ "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
865
+ "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
866
+ }}
867
+ RETURN_TYPES = ("CONDITIONING",)
868
+ FUNCTION = "append"
869
+
870
+ CATEGORY = "conditioning/gligen"
871
+
872
+ def append(self, conditioning_to, clip, gligen_textbox_model, text, width, height, x, y):
873
+ c = []
874
+ cond, cond_pooled = clip.encode_from_tokens(clip.tokenize(text), return_pooled=True)
875
+ for t in conditioning_to:
876
+ n = [t[0], t[1].copy()]
877
+ position_params = [(cond_pooled, height // 8, width // 8, y // 8, x // 8)]
878
+ prev = []
879
+ if "gligen" in n[1]:
880
+ prev = n[1]['gligen'][2]
881
+
882
+ n[1]['gligen'] = ("position", gligen_textbox_model, prev + position_params)
883
+ c.append(n)
884
+ return (c, )
885
+
886
+ class EmptyLatentImage:
887
+ def __init__(self, device="cpu"):
888
+ self.device = device
889
+
890
+ @classmethod
891
+ def INPUT_TYPES(s):
892
+ return {"required": { "width": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8}),
893
+ "height": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8}),
894
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 64})}}
895
+ RETURN_TYPES = ("LATENT",)
896
+ FUNCTION = "generate"
897
+
898
+ CATEGORY = "latent"
899
+
900
+ def generate(self, width, height, batch_size=1):
901
+ latent = torch.zeros([batch_size, 4, height // 8, width // 8])
902
+ return ({"samples":latent}, )
903
+
904
+
905
+ class LatentFromBatch:
906
+ @classmethod
907
+ def INPUT_TYPES(s):
908
+ return {"required": { "samples": ("LATENT",),
909
+ "batch_index": ("INT", {"default": 0, "min": 0, "max": 63}),
910
+ "length": ("INT", {"default": 1, "min": 1, "max": 64}),
911
+ }}
912
+ RETURN_TYPES = ("LATENT",)
913
+ FUNCTION = "frombatch"
914
+
915
+ CATEGORY = "latent/batch"
916
+
917
+ def frombatch(self, samples, batch_index, length):
918
+ s = samples.copy()
919
+ s_in = samples["samples"]
920
+ batch_index = min(s_in.shape[0] - 1, batch_index)
921
+ length = min(s_in.shape[0] - batch_index, length)
922
+ s["samples"] = s_in[batch_index:batch_index + length].clone()
923
+ if "noise_mask" in samples:
924
+ masks = samples["noise_mask"]
925
+ if masks.shape[0] == 1:
926
+ s["noise_mask"] = masks.clone()
927
+ else:
928
+ if masks.shape[0] < s_in.shape[0]:
929
+ masks = masks.repeat(math.ceil(s_in.shape[0] / masks.shape[0]), 1, 1, 1)[:s_in.shape[0]]
930
+ s["noise_mask"] = masks[batch_index:batch_index + length].clone()
931
+ if "batch_index" not in s:
932
+ s["batch_index"] = [x for x in range(batch_index, batch_index+length)]
933
+ else:
934
+ s["batch_index"] = samples["batch_index"][batch_index:batch_index + length]
935
+ return (s,)
936
+
937
+ class RepeatLatentBatch:
938
+ @classmethod
939
+ def INPUT_TYPES(s):
940
+ return {"required": { "samples": ("LATENT",),
941
+ "amount": ("INT", {"default": 1, "min": 1, "max": 64}),
942
+ }}
943
+ RETURN_TYPES = ("LATENT",)
944
+ FUNCTION = "repeat"
945
+
946
+ CATEGORY = "latent/batch"
947
+
948
+ def repeat(self, samples, amount):
949
+ s = samples.copy()
950
+ s_in = samples["samples"]
951
+
952
+ s["samples"] = s_in.repeat((amount, 1,1,1))
953
+ if "noise_mask" in samples and samples["noise_mask"].shape[0] > 1:
954
+ masks = samples["noise_mask"]
955
+ if masks.shape[0] < s_in.shape[0]:
956
+ masks = masks.repeat(math.ceil(s_in.shape[0] / masks.shape[0]), 1, 1, 1)[:s_in.shape[0]]
957
+ s["noise_mask"] = samples["noise_mask"].repeat((amount, 1,1,1))
958
+ if "batch_index" in s:
959
+ offset = max(s["batch_index"]) - min(s["batch_index"]) + 1
960
+ s["batch_index"] = s["batch_index"] + [x + (i * offset) for i in range(1, amount) for x in s["batch_index"]]
961
+ return (s,)
962
+
963
+ class LatentUpscale:
964
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "bislerp"]
965
+ crop_methods = ["disabled", "center"]
966
+
967
+ @classmethod
968
+ def INPUT_TYPES(s):
969
+ return {"required": { "samples": ("LATENT",), "upscale_method": (s.upscale_methods,),
970
+ "width": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
971
+ "height": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
972
+ "crop": (s.crop_methods,)}}
973
+ RETURN_TYPES = ("LATENT",)
974
+ FUNCTION = "upscale"
975
+
976
+ CATEGORY = "latent"
977
+
978
+ def upscale(self, samples, upscale_method, width, height, crop):
979
+ s = samples.copy()
980
+ s["samples"] = comfy.utils.common_upscale(samples["samples"], width // 8, height // 8, upscale_method, crop)
981
+ return (s,)
982
+
983
+ class LatentUpscaleBy:
984
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "bislerp"]
985
+
986
+ @classmethod
987
+ def INPUT_TYPES(s):
988
+ return {"required": { "samples": ("LATENT",), "upscale_method": (s.upscale_methods,),
989
+ "scale_by": ("FLOAT", {"default": 1.5, "min": 0.01, "max": 8.0, "step": 0.01}),}}
990
+ RETURN_TYPES = ("LATENT",)
991
+ FUNCTION = "upscale"
992
+
993
+ CATEGORY = "latent"
994
+
995
+ def upscale(self, samples, upscale_method, scale_by):
996
+ s = samples.copy()
997
+ width = round(samples["samples"].shape[3] * scale_by)
998
+ height = round(samples["samples"].shape[2] * scale_by)
999
+ s["samples"] = comfy.utils.common_upscale(samples["samples"], width, height, upscale_method, "disabled")
1000
+ return (s,)
1001
+
1002
+ class LatentRotate:
1003
+ @classmethod
1004
+ def INPUT_TYPES(s):
1005
+ return {"required": { "samples": ("LATENT",),
1006
+ "rotation": (["none", "90 degrees", "180 degrees", "270 degrees"],),
1007
+ }}
1008
+ RETURN_TYPES = ("LATENT",)
1009
+ FUNCTION = "rotate"
1010
+
1011
+ CATEGORY = "latent/transform"
1012
+
1013
+ def rotate(self, samples, rotation):
1014
+ s = samples.copy()
1015
+ rotate_by = 0
1016
+ if rotation.startswith("90"):
1017
+ rotate_by = 1
1018
+ elif rotation.startswith("180"):
1019
+ rotate_by = 2
1020
+ elif rotation.startswith("270"):
1021
+ rotate_by = 3
1022
+
1023
+ s["samples"] = torch.rot90(samples["samples"], k=rotate_by, dims=[3, 2])
1024
+ return (s,)
1025
+
1026
+ class LatentFlip:
1027
+ @classmethod
1028
+ def INPUT_TYPES(s):
1029
+ return {"required": { "samples": ("LATENT",),
1030
+ "flip_method": (["x-axis: vertically", "y-axis: horizontally"],),
1031
+ }}
1032
+ RETURN_TYPES = ("LATENT",)
1033
+ FUNCTION = "flip"
1034
+
1035
+ CATEGORY = "latent/transform"
1036
+
1037
+ def flip(self, samples, flip_method):
1038
+ s = samples.copy()
1039
+ if flip_method.startswith("x"):
1040
+ s["samples"] = torch.flip(samples["samples"], dims=[2])
1041
+ elif flip_method.startswith("y"):
1042
+ s["samples"] = torch.flip(samples["samples"], dims=[3])
1043
+
1044
+ return (s,)
1045
+
1046
+ class LatentComposite:
1047
+ @classmethod
1048
+ def INPUT_TYPES(s):
1049
+ return {"required": { "samples_to": ("LATENT",),
1050
+ "samples_from": ("LATENT",),
1051
+ "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1052
+ "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1053
+ "feather": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1054
+ }}
1055
+ RETURN_TYPES = ("LATENT",)
1056
+ FUNCTION = "composite"
1057
+
1058
+ CATEGORY = "latent"
1059
+
1060
+ def composite(self, samples_to, samples_from, x, y, composite_method="normal", feather=0):
1061
+ x = x // 8
1062
+ y = y // 8
1063
+ feather = feather // 8
1064
+ samples_out = samples_to.copy()
1065
+ s = samples_to["samples"].clone()
1066
+ samples_to = samples_to["samples"]
1067
+ samples_from = samples_from["samples"]
1068
+ if feather == 0:
1069
+ 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]
1070
+ else:
1071
+ samples_from = samples_from[:,:,:samples_to.shape[2] - y, :samples_to.shape[3] - x]
1072
+ mask = torch.ones_like(samples_from)
1073
+ for t in range(feather):
1074
+ if y != 0:
1075
+ mask[:,:,t:1+t,:] *= ((1.0/feather) * (t + 1))
1076
+
1077
+ if y + samples_from.shape[2] < samples_to.shape[2]:
1078
+ mask[:,:,mask.shape[2] -1 -t: mask.shape[2]-t,:] *= ((1.0/feather) * (t + 1))
1079
+ if x != 0:
1080
+ mask[:,:,:,t:1+t] *= ((1.0/feather) * (t + 1))
1081
+ if x + samples_from.shape[3] < samples_to.shape[3]:
1082
+ mask[:,:,:,mask.shape[3]- 1 - t: mask.shape[3]- t] *= ((1.0/feather) * (t + 1))
1083
+ rev_mask = torch.ones_like(mask) - mask
1084
+ 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
1085
+ samples_out["samples"] = s
1086
+ return (samples_out,)
1087
+
1088
+ class LatentBlend:
1089
+ @classmethod
1090
+ def INPUT_TYPES(s):
1091
+ return {"required": {
1092
+ "samples1": ("LATENT",),
1093
+ "samples2": ("LATENT",),
1094
+ "blend_factor": ("FLOAT", {
1095
+ "default": 0.5,
1096
+ "min": 0,
1097
+ "max": 1,
1098
+ "step": 0.01
1099
+ }),
1100
+ }}
1101
+
1102
+ RETURN_TYPES = ("LATENT",)
1103
+ FUNCTION = "blend"
1104
+
1105
+ CATEGORY = "_for_testing"
1106
+
1107
+ def blend(self, samples1, samples2, blend_factor:float, blend_mode: str="normal"):
1108
+
1109
+ samples_out = samples1.copy()
1110
+ samples1 = samples1["samples"]
1111
+ samples2 = samples2["samples"]
1112
+
1113
+ if samples1.shape != samples2.shape:
1114
+ samples2.permute(0, 3, 1, 2)
1115
+ samples2 = comfy.utils.common_upscale(samples2, samples1.shape[3], samples1.shape[2], 'bicubic', crop='center')
1116
+ samples2.permute(0, 2, 3, 1)
1117
+
1118
+ samples_blended = self.blend_mode(samples1, samples2, blend_mode)
1119
+ samples_blended = samples1 * blend_factor + samples_blended * (1 - blend_factor)
1120
+ samples_out["samples"] = samples_blended
1121
+ return (samples_out,)
1122
+
1123
+ def blend_mode(self, img1, img2, mode):
1124
+ if mode == "normal":
1125
+ return img2
1126
+ else:
1127
+ raise ValueError(f"Unsupported blend mode: {mode}")
1128
+
1129
+ class LatentCrop:
1130
+ @classmethod
1131
+ def INPUT_TYPES(s):
1132
+ return {"required": { "samples": ("LATENT",),
1133
+ "width": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
1134
+ "height": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
1135
+ "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1136
+ "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1137
+ }}
1138
+ RETURN_TYPES = ("LATENT",)
1139
+ FUNCTION = "crop"
1140
+
1141
+ CATEGORY = "latent/transform"
1142
+
1143
+ def crop(self, samples, width, height, x, y):
1144
+ s = samples.copy()
1145
+ samples = samples['samples']
1146
+ x = x // 8
1147
+ y = y // 8
1148
+
1149
+ #enfonce minimum size of 64
1150
+ if x > (samples.shape[3] - 8):
1151
+ x = samples.shape[3] - 8
1152
+ if y > (samples.shape[2] - 8):
1153
+ y = samples.shape[2] - 8
1154
+
1155
+ new_height = height // 8
1156
+ new_width = width // 8
1157
+ to_x = new_width + x
1158
+ to_y = new_height + y
1159
+ s['samples'] = samples[:,:,y:to_y, x:to_x]
1160
+ return (s,)
1161
+
1162
+ class SetLatentNoiseMask:
1163
+ @classmethod
1164
+ def INPUT_TYPES(s):
1165
+ return {"required": { "samples": ("LATENT",),
1166
+ "mask": ("MASK",),
1167
+ }}
1168
+ RETURN_TYPES = ("LATENT",)
1169
+ FUNCTION = "set_mask"
1170
+
1171
+ CATEGORY = "latent/inpaint"
1172
+
1173
+ def set_mask(self, samples, mask):
1174
+ s = samples.copy()
1175
+ s["noise_mask"] = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1]))
1176
+ return (s,)
1177
+
1178
+
1179
+ 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):
1180
+ device = comfy.model_management.get_torch_device()
1181
+ latent_image = latent["samples"]
1182
+
1183
+ if disable_noise:
1184
+ noise = torch.zeros(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, device="cpu")
1185
+ else:
1186
+ batch_inds = latent["batch_index"] if "batch_index" in latent else None
1187
+ noise = comfy.sample.prepare_noise(latent_image, seed, batch_inds)
1188
+
1189
+ noise_mask = None
1190
+ if "noise_mask" in latent:
1191
+ noise_mask = latent["noise_mask"]
1192
+
1193
+ preview_format = "JPEG"
1194
+ if preview_format not in ["JPEG", "PNG"]:
1195
+ preview_format = "JPEG"
1196
+
1197
+ previewer = latent_preview.get_previewer(device, model.model.latent_format)
1198
+
1199
+ pbar = comfy.utils.ProgressBar(steps)
1200
+ def callback(step, x0, x, total_steps):
1201
+ preview_bytes = None
1202
+ if previewer:
1203
+ preview_bytes = previewer.decode_latent_to_preview_image(preview_format, x0)
1204
+ pbar.update_absolute(step + 1, total_steps, preview_bytes)
1205
+
1206
+ samples = comfy.sample.sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative, latent_image,
1207
+ denoise=denoise, disable_noise=disable_noise, start_step=start_step, last_step=last_step,
1208
+ force_full_denoise=force_full_denoise, noise_mask=noise_mask, callback=callback, seed=seed)
1209
+ out = latent.copy()
1210
+ out["samples"] = samples
1211
+ return (out, )
1212
+
1213
+ class KSampler:
1214
+ @classmethod
1215
+ def INPUT_TYPES(s):
1216
+ return {"required":
1217
+ {"model": ("MODEL",),
1218
+ "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
1219
+ "steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
1220
+ "cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.5, "round": 0.01}),
1221
+ "sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
1222
+ "scheduler": (comfy.samplers.KSampler.SCHEDULERS, ),
1223
+ "positive": ("CONDITIONING", ),
1224
+ "negative": ("CONDITIONING", ),
1225
+ "latent_image": ("LATENT", ),
1226
+ "denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
1227
+ }
1228
+ }
1229
+
1230
+ RETURN_TYPES = ("LATENT",)
1231
+ FUNCTION = "sample"
1232
+
1233
+ CATEGORY = "sampling"
1234
+
1235
+ def sample(self, model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=1.0):
1236
+ return common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise)
1237
+
1238
+ class KSamplerAdvanced:
1239
+ @classmethod
1240
+ def INPUT_TYPES(s):
1241
+ return {"required":
1242
+ {"model": ("MODEL",),
1243
+ "add_noise": (["enable", "disable"], ),
1244
+ "noise_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
1245
+ "steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
1246
+ "cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.5, "round": 0.01}),
1247
+ "sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
1248
+ "scheduler": (comfy.samplers.KSampler.SCHEDULERS, ),
1249
+ "positive": ("CONDITIONING", ),
1250
+ "negative": ("CONDITIONING", ),
1251
+ "latent_image": ("LATENT", ),
1252
+ "start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000}),
1253
+ "end_at_step": ("INT", {"default": 10000, "min": 0, "max": 10000}),
1254
+ "return_with_leftover_noise": (["disable", "enable"], ),
1255
+ }
1256
+ }
1257
+
1258
+ RETURN_TYPES = ("LATENT",)
1259
+ FUNCTION = "sample"
1260
+
1261
+ CATEGORY = "sampling"
1262
+
1263
+ 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):
1264
+ force_full_denoise = True
1265
+ if return_with_leftover_noise == "enable":
1266
+ force_full_denoise = False
1267
+ disable_noise = False
1268
+ if add_noise == "disable":
1269
+ disable_noise = True
1270
+ 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)
1271
+
1272
+ class SaveImage:
1273
+ def __init__(self):
1274
+ self.output_dir = folder_paths.get_output_directory()
1275
+ self.type = "output"
1276
+ self.prefix_append = ""
1277
+
1278
+ @classmethod
1279
+ def INPUT_TYPES(s):
1280
+ return {"required":
1281
+ {"images": ("IMAGE", ),
1282
+ "filename_prefix": ("STRING", {"default": "ComfyUI"})},
1283
+ "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
1284
+ }
1285
+
1286
+ RETURN_TYPES = ()
1287
+ FUNCTION = "save_images"
1288
+
1289
+ OUTPUT_NODE = True
1290
+
1291
+ CATEGORY = "image"
1292
+
1293
+ def save_images(self, images, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None):
1294
+ filename_prefix += self.prefix_append
1295
+ 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])
1296
+ results = list()
1297
+ for image in images:
1298
+ i = 255. * image.cpu().numpy()
1299
+ img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
1300
+ metadata = None
1301
+ if not args.disable_metadata:
1302
+ metadata = PngInfo()
1303
+ if prompt is not None:
1304
+ metadata.add_text("prompt", json.dumps(prompt))
1305
+ if extra_pnginfo is not None:
1306
+ for x in extra_pnginfo:
1307
+ metadata.add_text(x, json.dumps(extra_pnginfo[x]))
1308
+
1309
+ file = f"{filename}_{counter:05}_.png"
1310
+ img.save(os.path.join(full_output_folder, file), pnginfo=metadata, compress_level=4)
1311
+ results.append({
1312
+ "filename": file,
1313
+ "subfolder": subfolder,
1314
+ "type": self.type
1315
+ })
1316
+ counter += 1
1317
+
1318
+ return { "ui": { "images": results } }
1319
+
1320
+ class PreviewImage(SaveImage):
1321
+ def __init__(self):
1322
+ self.output_dir = folder_paths.get_temp_directory()
1323
+ self.type = "temp"
1324
+ self.prefix_append = "_temp_" + ''.join(random.choice("abcdefghijklmnopqrstupvxyz") for x in range(5))
1325
+
1326
+ @classmethod
1327
+ def INPUT_TYPES(s):
1328
+ return {"required":
1329
+ {"images": ("IMAGE", ), },
1330
+ "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
1331
+ }
1332
+
1333
+ class LoadImage:
1334
+ @classmethod
1335
+ def INPUT_TYPES(s):
1336
+ input_dir = folder_paths.get_input_directory()
1337
+ files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
1338
+ return {"required":
1339
+ {"image": (sorted(files), {"image_upload": True})},
1340
+ }
1341
+
1342
+ CATEGORY = "image"
1343
+
1344
+ RETURN_TYPES = ("IMAGE", "MASK")
1345
+ FUNCTION = "load_image"
1346
+ def load_image(self, image):
1347
+ image_path = folder_paths.get_annotated_filepath(image)
1348
+ i = Image.open(image_path)
1349
+ i = ImageOps.exif_transpose(i)
1350
+ image = i.convert("RGB")
1351
+ image = np.array(image).astype(np.float32) / 255.0
1352
+ image = torch.from_numpy(image)[None,]
1353
+ if 'A' in i.getbands():
1354
+ mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
1355
+ mask = 1. - torch.from_numpy(mask)
1356
+ else:
1357
+ mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
1358
+ return (image, mask)
1359
+
1360
+ @classmethod
1361
+ def IS_CHANGED(s, image):
1362
+ image_path = folder_paths.get_annotated_filepath(image)
1363
+ m = hashlib.sha256()
1364
+ with open(image_path, 'rb') as f:
1365
+ m.update(f.read())
1366
+ return m.digest().hex()
1367
+
1368
+ @classmethod
1369
+ def VALIDATE_INPUTS(s, image):
1370
+ if not folder_paths.exists_annotated_filepath(image):
1371
+ return "Invalid image file: {}".format(image)
1372
+
1373
+ return True
1374
+
1375
+ class LoadImageMask:
1376
+ _color_channels = ["alpha", "red", "green", "blue"]
1377
+ @classmethod
1378
+ def INPUT_TYPES(s):
1379
+ input_dir = folder_paths.get_input_directory()
1380
+ files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
1381
+ return {"required":
1382
+ {"image": (sorted(files), {"image_upload": True}),
1383
+ "channel": (s._color_channels, ), }
1384
+ }
1385
+
1386
+ CATEGORY = "mask"
1387
+
1388
+ RETURN_TYPES = ("MASK",)
1389
+ FUNCTION = "load_image"
1390
+ def load_image(self, image, channel):
1391
+ image_path = folder_paths.get_annotated_filepath(image)
1392
+ i = Image.open(image_path)
1393
+ i = ImageOps.exif_transpose(i)
1394
+ if i.getbands() != ("R", "G", "B", "A"):
1395
+ i = i.convert("RGBA")
1396
+ mask = None
1397
+ c = channel[0].upper()
1398
+ if c in i.getbands():
1399
+ mask = np.array(i.getchannel(c)).astype(np.float32) / 255.0
1400
+ mask = torch.from_numpy(mask)
1401
+ if c == 'A':
1402
+ mask = 1. - mask
1403
+ else:
1404
+ mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
1405
+ return (mask,)
1406
+
1407
+ @classmethod
1408
+ def IS_CHANGED(s, image, channel):
1409
+ image_path = folder_paths.get_annotated_filepath(image)
1410
+ m = hashlib.sha256()
1411
+ with open(image_path, 'rb') as f:
1412
+ m.update(f.read())
1413
+ return m.digest().hex()
1414
+
1415
+ @classmethod
1416
+ def VALIDATE_INPUTS(s, image, channel):
1417
+ if not folder_paths.exists_annotated_filepath(image):
1418
+ return "Invalid image file: {}".format(image)
1419
+
1420
+ if channel not in s._color_channels:
1421
+ return "Invalid color channel: {}".format(channel)
1422
+
1423
+ return True
1424
+
1425
+ class ImageScale:
1426
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
1427
+ crop_methods = ["disabled", "center"]
1428
+
1429
+ @classmethod
1430
+ def INPUT_TYPES(s):
1431
+ return {"required": { "image": ("IMAGE",), "upscale_method": (s.upscale_methods,),
1432
+ "width": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
1433
+ "height": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
1434
+ "crop": (s.crop_methods,)}}
1435
+ RETURN_TYPES = ("IMAGE",)
1436
+ FUNCTION = "upscale"
1437
+
1438
+ CATEGORY = "image/upscaling"
1439
+
1440
+ def upscale(self, image, upscale_method, width, height, crop):
1441
+ samples = image.movedim(-1,1)
1442
+ s = comfy.utils.common_upscale(samples, width, height, upscale_method, crop)
1443
+ s = s.movedim(1,-1)
1444
+ return (s,)
1445
+
1446
+ class ImageScaleBy:
1447
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
1448
+
1449
+ @classmethod
1450
+ def INPUT_TYPES(s):
1451
+ return {"required": { "image": ("IMAGE",), "upscale_method": (s.upscale_methods,),
1452
+ "scale_by": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 8.0, "step": 0.01}),}}
1453
+ RETURN_TYPES = ("IMAGE",)
1454
+ FUNCTION = "upscale"
1455
+
1456
+ CATEGORY = "image/upscaling"
1457
+
1458
+ def upscale(self, image, upscale_method, scale_by):
1459
+ samples = image.movedim(-1,1)
1460
+ width = round(samples.shape[3] * scale_by)
1461
+ height = round(samples.shape[2] * scale_by)
1462
+ s = comfy.utils.common_upscale(samples, width, height, upscale_method, "disabled")
1463
+ s = s.movedim(1,-1)
1464
+ return (s,)
1465
+
1466
+ class ImageInvert:
1467
+
1468
+ @classmethod
1469
+ def INPUT_TYPES(s):
1470
+ return {"required": { "image": ("IMAGE",)}}
1471
+
1472
+ RETURN_TYPES = ("IMAGE",)
1473
+ FUNCTION = "invert"
1474
+
1475
+ CATEGORY = "image"
1476
+
1477
+ def invert(self, image):
1478
+ s = 1.0 - image
1479
+ return (s,)
1480
+
1481
+ class ImageBatch:
1482
+
1483
+ @classmethod
1484
+ def INPUT_TYPES(s):
1485
+ return {"required": { "image1": ("IMAGE",), "image2": ("IMAGE",)}}
1486
+
1487
+ RETURN_TYPES = ("IMAGE",)
1488
+ FUNCTION = "batch"
1489
+
1490
+ CATEGORY = "image"
1491
+
1492
+ def batch(self, image1, image2):
1493
+ if image1.shape[1:] != image2.shape[1:]:
1494
+ image2 = comfy.utils.common_upscale(image2.movedim(-1,1), image1.shape[2], image1.shape[1], "bilinear", "center").movedim(1,-1)
1495
+ s = torch.cat((image1, image2), dim=0)
1496
+ return (s,)
1497
+
1498
+ class EmptyImage:
1499
+ def __init__(self, device="cpu"):
1500
+ self.device = device
1501
+
1502
+ @classmethod
1503
+ def INPUT_TYPES(s):
1504
+ return {"required": { "width": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
1505
+ "height": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
1506
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 64}),
1507
+ "color": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFF, "step": 1, "display": "color"}),
1508
+ }}
1509
+ RETURN_TYPES = ("IMAGE",)
1510
+ FUNCTION = "generate"
1511
+
1512
+ CATEGORY = "image"
1513
+
1514
+ def generate(self, width, height, batch_size=1, color=0):
1515
+ r = torch.full([batch_size, height, width, 1], ((color >> 16) & 0xFF) / 0xFF)
1516
+ g = torch.full([batch_size, height, width, 1], ((color >> 8) & 0xFF) / 0xFF)
1517
+ b = torch.full([batch_size, height, width, 1], ((color) & 0xFF) / 0xFF)
1518
+ return (torch.cat((r, g, b), dim=-1), )
1519
+
1520
+ class ImagePadForOutpaint:
1521
+
1522
+ @classmethod
1523
+ def INPUT_TYPES(s):
1524
+ return {
1525
+ "required": {
1526
+ "image": ("IMAGE",),
1527
+ "left": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1528
+ "top": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1529
+ "right": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1530
+ "bottom": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1531
+ "feathering": ("INT", {"default": 40, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
1532
+ }
1533
+ }
1534
+
1535
+ RETURN_TYPES = ("IMAGE", "MASK")
1536
+ FUNCTION = "expand_image"
1537
+
1538
+ CATEGORY = "image"
1539
+
1540
+ def expand_image(self, image, left, top, right, bottom, feathering):
1541
+ d1, d2, d3, d4 = image.size()
1542
+
1543
+ new_image = torch.zeros(
1544
+ (d1, d2 + top + bottom, d3 + left + right, d4),
1545
+ dtype=torch.float32,
1546
+ )
1547
+ new_image[:, top:top + d2, left:left + d3, :] = image
1548
+
1549
+ mask = torch.ones(
1550
+ (d2 + top + bottom, d3 + left + right),
1551
+ dtype=torch.float32,
1552
+ )
1553
+
1554
+ t = torch.zeros(
1555
+ (d2, d3),
1556
+ dtype=torch.float32
1557
+ )
1558
+
1559
+ if feathering > 0 and feathering * 2 < d2 and feathering * 2 < d3:
1560
+
1561
+ for i in range(d2):
1562
+ for j in range(d3):
1563
+ dt = i if top != 0 else d2
1564
+ db = d2 - i if bottom != 0 else d2
1565
+
1566
+ dl = j if left != 0 else d3
1567
+ dr = d3 - j if right != 0 else d3
1568
+
1569
+ d = min(dt, db, dl, dr)
1570
+
1571
+ if d >= feathering:
1572
+ continue
1573
+
1574
+ v = (feathering - d) / feathering
1575
+
1576
+ t[i, j] = v * v
1577
+
1578
+ mask[top:top + d2, left:left + d3] = t
1579
+
1580
+ return (new_image, mask)
1581
+
1582
+
1583
+ NODE_CLASS_MAPPINGS = {
1584
+ "KSampler": KSampler,
1585
+ "CheckpointLoaderSimple": CheckpointLoaderSimple,
1586
+ "CLIPTextEncode": CLIPTextEncode,
1587
+ "CLIPSetLastLayer": CLIPSetLastLayer,
1588
+ "VAEDecode": VAEDecode,
1589
+ "VAEEncode": VAEEncode,
1590
+ "VAEEncodeForInpaint": VAEEncodeForInpaint,
1591
+ "VAELoader": VAELoader,
1592
+ "EmptyLatentImage": EmptyLatentImage,
1593
+ "LatentUpscale": LatentUpscale,
1594
+ "LatentUpscaleBy": LatentUpscaleBy,
1595
+ "LatentFromBatch": LatentFromBatch,
1596
+ "RepeatLatentBatch": RepeatLatentBatch,
1597
+ "SaveImage": SaveImage,
1598
+ "PreviewImage": PreviewImage,
1599
+ "LoadImage": LoadImage,
1600
+ "LoadImageMask": LoadImageMask,
1601
+ "ImageScale": ImageScale,
1602
+ "ImageScaleBy": ImageScaleBy,
1603
+ "ImageInvert": ImageInvert,
1604
+ "ImageBatch": ImageBatch,
1605
+ "ImagePadForOutpaint": ImagePadForOutpaint,
1606
+ "EmptyImage": EmptyImage,
1607
+ "ConditioningAverage ": ConditioningAverage ,
1608
+ "ConditioningCombine": ConditioningCombine,
1609
+ "ConditioningConcat": ConditioningConcat,
1610
+ "ConditioningSetArea": ConditioningSetArea,
1611
+ "ConditioningSetAreaPercentage": ConditioningSetAreaPercentage,
1612
+ "ConditioningSetMask": ConditioningSetMask,
1613
+ "KSamplerAdvanced": KSamplerAdvanced,
1614
+ "SetLatentNoiseMask": SetLatentNoiseMask,
1615
+ "LatentComposite": LatentComposite,
1616
+ "LatentBlend": LatentBlend,
1617
+ "LatentRotate": LatentRotate,
1618
+ "LatentFlip": LatentFlip,
1619
+ "LatentCrop": LatentCrop,
1620
+ "LoraLoader": LoraLoader,
1621
+ "CLIPLoader": CLIPLoader,
1622
+ "UNETLoader": UNETLoader,
1623
+ "DualCLIPLoader": DualCLIPLoader,
1624
+ "CLIPVisionEncode": CLIPVisionEncode,
1625
+ "StyleModelApply": StyleModelApply,
1626
+ "unCLIPConditioning": unCLIPConditioning,
1627
+ "ControlNetApply": ControlNetApply,
1628
+ "ControlNetApplyAdvanced": ControlNetApplyAdvanced,
1629
+ "ControlNetLoader": ControlNetLoader,
1630
+ "DiffControlNetLoader": DiffControlNetLoader,
1631
+ "StyleModelLoader": StyleModelLoader,
1632
+ "CLIPVisionLoader": CLIPVisionLoader,
1633
+ "VAEDecodeTiled": VAEDecodeTiled,
1634
+ "VAEEncodeTiled": VAEEncodeTiled,
1635
+ "unCLIPCheckpointLoader": unCLIPCheckpointLoader,
1636
+ "GLIGENLoader": GLIGENLoader,
1637
+ "GLIGENTextBoxApply": GLIGENTextBoxApply,
1638
+
1639
+ "CheckpointLoader": CheckpointLoader,
1640
+ "DiffusersLoader": DiffusersLoader,
1641
+
1642
+ "LoadLatent": LoadLatent,
1643
+ "SaveLatent": SaveLatent,
1644
+
1645
+ "ConditioningZeroOut": ConditioningZeroOut,
1646
+ "ConditioningSetTimestepRange": ConditioningSetTimestepRange,
1647
+ }
1648
+
1649
+ NODE_DISPLAY_NAME_MAPPINGS = {
1650
+ # Sampling
1651
+ "KSampler": "KSampler",
1652
+ "KSamplerAdvanced": "KSampler (Advanced)",
1653
+ # Loaders
1654
+ "CheckpointLoader": "Load Checkpoint (With Config)",
1655
+ "CheckpointLoaderSimple": "Load Checkpoint",
1656
+ "VAELoader": "Load VAE",
1657
+ "LoraLoader": "Load LoRA",
1658
+ "CLIPLoader": "Load CLIP",
1659
+ "ControlNetLoader": "Load ControlNet Model",
1660
+ "DiffControlNetLoader": "Load ControlNet Model (diff)",
1661
+ "StyleModelLoader": "Load Style Model",
1662
+ "CLIPVisionLoader": "Load CLIP Vision",
1663
+ "UpscaleModelLoader": "Load Upscale Model",
1664
+ # Conditioning
1665
+ "CLIPVisionEncode": "CLIP Vision Encode",
1666
+ "StyleModelApply": "Apply Style Model",
1667
+ "CLIPTextEncode": "CLIP Text Encode (Prompt)",
1668
+ "CLIPSetLastLayer": "CLIP Set Last Layer",
1669
+ "ConditioningCombine": "Conditioning (Combine)",
1670
+ "ConditioningAverage ": "Conditioning (Average)",
1671
+ "ConditioningConcat": "Conditioning (Concat)",
1672
+ "ConditioningSetArea": "Conditioning (Set Area)",
1673
+ "ConditioningSetAreaPercentage": "Conditioning (Set Area with Percentage)",
1674
+ "ConditioningSetMask": "Conditioning (Set Mask)",
1675
+ "ControlNetApply": "Apply ControlNet",
1676
+ "ControlNetApplyAdvanced": "Apply ControlNet (Advanced)",
1677
+ # Latent
1678
+ "VAEEncodeForInpaint": "VAE Encode (for Inpainting)",
1679
+ "SetLatentNoiseMask": "Set Latent Noise Mask",
1680
+ "VAEDecode": "VAE Decode",
1681
+ "VAEEncode": "VAE Encode",
1682
+ "LatentRotate": "Rotate Latent",
1683
+ "LatentFlip": "Flip Latent",
1684
+ "LatentCrop": "Crop Latent",
1685
+ "EmptyLatentImage": "Empty Latent Image",
1686
+ "LatentUpscale": "Upscale Latent",
1687
+ "LatentUpscaleBy": "Upscale Latent By",
1688
+ "LatentComposite": "Latent Composite",
1689
+ "LatentBlend": "Latent Blend",
1690
+ "LatentFromBatch" : "Latent From Batch",
1691
+ "RepeatLatentBatch": "Repeat Latent Batch",
1692
+ # Image
1693
+ "SaveImage": "Save Image",
1694
+ "PreviewImage": "Preview Image",
1695
+ "LoadImage": "Load Image",
1696
+ "LoadImageMask": "Load Image (as Mask)",
1697
+ "ImageScale": "Upscale Image",
1698
+ "ImageScaleBy": "Upscale Image By",
1699
+ "ImageUpscaleWithModel": "Upscale Image (using Model)",
1700
+ "ImageInvert": "Invert Image",
1701
+ "ImagePadForOutpaint": "Pad Image for Outpainting",
1702
+ "ImageBatch": "Batch Images",
1703
+ # _for_testing
1704
+ "VAEDecodeTiled": "VAE Decode (Tiled)",
1705
+ "VAEEncodeTiled": "VAE Encode (Tiled)",
1706
+ }
1707
+
1708
+ EXTENSION_WEB_DIRS = {}
1709
+
1710
+ def load_custom_node(module_path, ignore=set()):
1711
+ module_name = os.path.basename(module_path)
1712
+ if os.path.isfile(module_path):
1713
+ sp = os.path.splitext(module_path)
1714
+ module_name = sp[0]
1715
+ try:
1716
+ if os.path.isfile(module_path):
1717
+ module_spec = importlib.util.spec_from_file_location(module_name, module_path)
1718
+ module_dir = os.path.split(module_path)[0]
1719
+ else:
1720
+ module_spec = importlib.util.spec_from_file_location(module_name, os.path.join(module_path, "__init__.py"))
1721
+ module_dir = module_path
1722
+
1723
+ module = importlib.util.module_from_spec(module_spec)
1724
+ sys.modules[module_name] = module
1725
+ module_spec.loader.exec_module(module)
1726
+
1727
+ if hasattr(module, "WEB_DIRECTORY") and getattr(module, "WEB_DIRECTORY") is not None:
1728
+ web_dir = os.path.abspath(os.path.join(module_dir, getattr(module, "WEB_DIRECTORY")))
1729
+ if os.path.isdir(web_dir):
1730
+ EXTENSION_WEB_DIRS[module_name] = web_dir
1731
+
1732
+ if hasattr(module, "NODE_CLASS_MAPPINGS") and getattr(module, "NODE_CLASS_MAPPINGS") is not None:
1733
+ for name in module.NODE_CLASS_MAPPINGS:
1734
+ if name not in ignore:
1735
+ NODE_CLASS_MAPPINGS[name] = module.NODE_CLASS_MAPPINGS[name]
1736
+ if hasattr(module, "NODE_DISPLAY_NAME_MAPPINGS") and getattr(module, "NODE_DISPLAY_NAME_MAPPINGS") is not None:
1737
+ NODE_DISPLAY_NAME_MAPPINGS.update(module.NODE_DISPLAY_NAME_MAPPINGS)
1738
+ return True
1739
+ else:
1740
+ print(f"Skip {module_path} module for custom nodes due to the lack of NODE_CLASS_MAPPINGS.")
1741
+ return False
1742
+ except Exception as e:
1743
+ print(traceback.format_exc())
1744
+ print(f"Cannot import {module_path} module for custom nodes:", e)
1745
+ return False
1746
+
1747
+ def load_custom_nodes():
1748
+ base_node_names = set(NODE_CLASS_MAPPINGS.keys())
1749
+ node_paths = folder_paths.get_folder_paths("custom_nodes")
1750
+ node_import_times = []
1751
+ for custom_node_path in node_paths:
1752
+ possible_modules = os.listdir(custom_node_path)
1753
+ if "__pycache__" in possible_modules:
1754
+ possible_modules.remove("__pycache__")
1755
+
1756
+ for possible_module in possible_modules:
1757
+ module_path = os.path.join(custom_node_path, possible_module)
1758
+ if os.path.isfile(module_path) and os.path.splitext(module_path)[1] != ".py": continue
1759
+ if module_path.endswith(".disabled"): continue
1760
+ time_before = time.perf_counter()
1761
+ success = load_custom_node(module_path, base_node_names)
1762
+ node_import_times.append((time.perf_counter() - time_before, module_path, success))
1763
+
1764
+ if len(node_import_times) > 0:
1765
+ print("\nImport times for custom nodes:")
1766
+ for n in sorted(node_import_times):
1767
+ if n[2]:
1768
+ import_message = ""
1769
+ else:
1770
+ import_message = " (IMPORT FAILED)"
1771
+ print("{:6.1f} seconds{}:".format(n[0], import_message), n[1])
1772
+ print()
1773
+
1774
+ def init_custom_nodes():
1775
+ load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_latent.py"))
1776
+ load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_hypernetwork.py"))
1777
+ load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_upscale_model.py"))
1778
+ load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_post_processing.py"))
1779
+ load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_mask.py"))
1780
+ load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_rebatch.py"))
1781
+ load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_model_merging.py"))
1782
+ load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_tomesd.py"))
1783
+ load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_clip_sdxl.py"))
1784
+ load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_canny.py"))
1785
+ load_custom_node(os.path.join(os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras"), "nodes_freelunch.py"))
1786
+ load_custom_nodes()
pytest.ini ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ [pytest]
2
+ markers =
3
+ inference: mark as inference test (deselect with '-m "not inference"')
4
+ testpaths = tests
5
+ addopts = -s
requirements.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ torchsde
3
+ einops
4
+ transformers>=4.25.1
5
+ safetensors>=0.3.0
6
+ aiohttp
7
+ accelerate
8
+ pyyaml
9
+ Pillow
10
+ scipy
11
+ tqdm
12
+ psutil
server.py ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from PIL import Image, ImageOps
15
+ from PIL.PngImagePlugin import PngInfo
16
+ from io import BytesIO
17
+
18
+ try:
19
+ import aiohttp
20
+ from aiohttp import web
21
+ except ImportError:
22
+ print("Module 'aiohttp' not installed. Please install it via:")
23
+ print("pip install aiohttp")
24
+ print("or")
25
+ print("pip install -r requirements.txt")
26
+ sys.exit()
27
+
28
+ import mimetypes
29
+ from comfy.cli_args import args
30
+ import comfy.utils
31
+ import comfy.model_management
32
+
33
+
34
+ class BinaryEventTypes:
35
+ PREVIEW_IMAGE = 1
36
+ UNENCODED_PREVIEW_IMAGE = 2
37
+
38
+ async def send_socket_catch_exception(function, message):
39
+ try:
40
+ await function(message)
41
+ except (aiohttp.ClientError, aiohttp.ClientPayloadError, ConnectionResetError) as err:
42
+ print("send error:", err)
43
+
44
+ @web.middleware
45
+ async def cache_control(request: web.Request, handler):
46
+ response: web.Response = await handler(request)
47
+ if request.path.endswith('.js') or request.path.endswith('.css'):
48
+ response.headers.setdefault('Cache-Control', 'no-cache')
49
+ return response
50
+
51
+ def create_cors_middleware(allowed_origin: str):
52
+ @web.middleware
53
+ async def cors_middleware(request: web.Request, handler):
54
+ if request.method == "OPTIONS":
55
+ # Pre-flight request. Reply successfully:
56
+ response = web.Response()
57
+ else:
58
+ response = await handler(request)
59
+
60
+ response.headers['Access-Control-Allow-Origin'] = allowed_origin
61
+ response.headers['Access-Control-Allow-Methods'] = 'POST, GET, DELETE, PUT, OPTIONS'
62
+ response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
63
+ response.headers['Access-Control-Allow-Credentials'] = 'true'
64
+ return response
65
+
66
+ return cors_middleware
67
+
68
+ class PromptServer():
69
+ def __init__(self, loop):
70
+ PromptServer.instance = self
71
+
72
+ mimetypes.init()
73
+ mimetypes.types_map['.js'] = 'application/javascript; charset=utf-8'
74
+
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
+ self.app = web.Application(client_max_size=104857600, middlewares=middlewares)
86
+ self.sockets = dict()
87
+ self.web_root = os.path.join(os.path.dirname(
88
+ os.path.realpath(__file__)), "web")
89
+ routes = web.RouteTableDef()
90
+ self.routes = routes
91
+ self.last_node_id = None
92
+ self.client_id = None
93
+
94
+ self.on_prompt_handlers = []
95
+
96
+ @routes.get('/ws')
97
+ async def websocket_handler(request):
98
+ ws = web.WebSocketResponse()
99
+ await ws.prepare(request)
100
+ sid = request.rel_url.query.get('clientId', '')
101
+ if sid:
102
+ # Reusing existing session, remove old
103
+ self.sockets.pop(sid, None)
104
+ else:
105
+ sid = uuid.uuid4().hex
106
+
107
+ self.sockets[sid] = ws
108
+
109
+ try:
110
+ # Send initial state to the new client
111
+ await self.send("status", { "status": self.get_queue_info(), 'sid': sid }, sid)
112
+ # On reconnect if we are the currently executing client send the current node
113
+ if self.client_id == sid and self.last_node_id is not None:
114
+ await self.send("executing", { "node": self.last_node_id }, sid)
115
+
116
+ async for msg in ws:
117
+ if msg.type == aiohttp.WSMsgType.ERROR:
118
+ print('ws connection closed with exception %s' % ws.exception())
119
+ finally:
120
+ self.sockets.pop(sid, None)
121
+ return ws
122
+
123
+ @routes.get("/")
124
+ async def get_root(request):
125
+ return web.FileResponse(os.path.join(self.web_root, "index.html"))
126
+
127
+ @routes.get("/embeddings")
128
+ def get_embeddings(self):
129
+ embeddings = folder_paths.get_filename_list("embeddings")
130
+ return web.json_response(list(map(lambda a: os.path.splitext(a)[0], embeddings)))
131
+
132
+ @routes.get("/extensions")
133
+ async def get_extensions(request):
134
+ files = glob.glob(os.path.join(
135
+ glob.escape(self.web_root), 'extensions/**/*.js'), recursive=True)
136
+
137
+ extensions = list(map(lambda f: "/" + os.path.relpath(f, self.web_root).replace("\\", "/"), files))
138
+
139
+ for name, dir in nodes.EXTENSION_WEB_DIRS.items():
140
+ files = glob.glob(os.path.join(glob.escape(dir), '**/*.js'), recursive=True)
141
+ extensions.extend(list(map(lambda f: "/extensions/" + urllib.parse.quote(
142
+ name) + "/" + os.path.relpath(f, dir).replace("\\", "/"), files)))
143
+
144
+ return web.json_response(extensions)
145
+
146
+ def get_dir_by_type(dir_type):
147
+ if dir_type is None:
148
+ dir_type = "input"
149
+
150
+ if dir_type == "input":
151
+ type_dir = folder_paths.get_input_directory()
152
+ elif dir_type == "temp":
153
+ type_dir = folder_paths.get_temp_directory()
154
+ elif dir_type == "output":
155
+ type_dir = folder_paths.get_output_directory()
156
+
157
+ return type_dir, dir_type
158
+
159
+ def image_upload(post, image_save_function=None):
160
+ image = post.get("image")
161
+ overwrite = post.get("overwrite")
162
+
163
+ image_upload_type = post.get("type")
164
+ upload_dir, image_upload_type = get_dir_by_type(image_upload_type)
165
+
166
+ if image and image.file:
167
+ filename = image.filename
168
+ if not filename:
169
+ return web.Response(status=400)
170
+
171
+ subfolder = post.get("subfolder", "")
172
+ full_output_folder = os.path.join(upload_dir, os.path.normpath(subfolder))
173
+ filepath = os.path.abspath(os.path.join(full_output_folder, filename))
174
+
175
+ if os.path.commonpath((upload_dir, filepath)) != upload_dir:
176
+ return web.Response(status=400)
177
+
178
+ if not os.path.exists(full_output_folder):
179
+ os.makedirs(full_output_folder)
180
+
181
+ split = os.path.splitext(filename)
182
+
183
+ if overwrite is not None and (overwrite == "true" or overwrite == "1"):
184
+ pass
185
+ else:
186
+ i = 1
187
+ while os.path.exists(filepath):
188
+ filename = f"{split[0]} ({i}){split[1]}"
189
+ filepath = os.path.join(full_output_folder, filename)
190
+ i += 1
191
+
192
+ if image_save_function is not None:
193
+ image_save_function(image, post, filepath)
194
+ else:
195
+ with open(filepath, "wb") as f:
196
+ f.write(image.file.read())
197
+
198
+ return web.json_response({"name" : filename, "subfolder": subfolder, "type": image_upload_type})
199
+ else:
200
+ return web.Response(status=400)
201
+
202
+ @routes.post("/upload/image")
203
+ async def upload_image(request):
204
+ post = await request.post()
205
+ return image_upload(post)
206
+
207
+
208
+ @routes.post("/upload/mask")
209
+ async def upload_mask(request):
210
+ post = await request.post()
211
+
212
+ def image_save_function(image, post, filepath):
213
+ original_ref = json.loads(post.get("original_ref"))
214
+ filename, output_dir = folder_paths.annotated_filepath(original_ref['filename'])
215
+
216
+ # validation for security: prevent accessing arbitrary path
217
+ if filename[0] == '/' or '..' in filename:
218
+ return web.Response(status=400)
219
+
220
+ if output_dir is None:
221
+ type = original_ref.get("type", "output")
222
+ output_dir = folder_paths.get_directory_by_type(type)
223
+
224
+ if output_dir is None:
225
+ return web.Response(status=400)
226
+
227
+ if original_ref.get("subfolder", "") != "":
228
+ full_output_dir = os.path.join(output_dir, original_ref["subfolder"])
229
+ if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir:
230
+ return web.Response(status=403)
231
+ output_dir = full_output_dir
232
+
233
+ file = os.path.join(output_dir, filename)
234
+
235
+ if os.path.isfile(file):
236
+ with Image.open(file) as original_pil:
237
+ metadata = PngInfo()
238
+ if hasattr(original_pil,'text'):
239
+ for key in original_pil.text:
240
+ metadata.add_text(key, original_pil.text[key])
241
+ original_pil = original_pil.convert('RGBA')
242
+ mask_pil = Image.open(image.file).convert('RGBA')
243
+
244
+ # alpha copy
245
+ new_alpha = mask_pil.getchannel('A')
246
+ original_pil.putalpha(new_alpha)
247
+ original_pil.save(filepath, compress_level=4, pnginfo=metadata)
248
+
249
+ return image_upload(post, image_save_function)
250
+
251
+ @routes.get("/view")
252
+ async def view_image(request):
253
+ if "filename" in request.rel_url.query:
254
+ filename = request.rel_url.query["filename"]
255
+ filename,output_dir = folder_paths.annotated_filepath(filename)
256
+
257
+ # validation for security: prevent accessing arbitrary path
258
+ if filename[0] == '/' or '..' in filename:
259
+ return web.Response(status=400)
260
+
261
+ if output_dir is None:
262
+ type = request.rel_url.query.get("type", "output")
263
+ output_dir = folder_paths.get_directory_by_type(type)
264
+
265
+ if output_dir is None:
266
+ return web.Response(status=400)
267
+
268
+ if "subfolder" in request.rel_url.query:
269
+ full_output_dir = os.path.join(output_dir, request.rel_url.query["subfolder"])
270
+ if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir:
271
+ return web.Response(status=403)
272
+ output_dir = full_output_dir
273
+
274
+ filename = os.path.basename(filename)
275
+ file = os.path.join(output_dir, filename)
276
+
277
+ if os.path.isfile(file):
278
+ if 'preview' in request.rel_url.query:
279
+ with Image.open(file) as img:
280
+ preview_info = request.rel_url.query['preview'].split(';')
281
+ image_format = preview_info[0]
282
+ if image_format not in ['webp', 'jpeg'] or 'a' in request.rel_url.query.get('channel', ''):
283
+ image_format = 'webp'
284
+
285
+ quality = 90
286
+ if preview_info[-1].isdigit():
287
+ quality = int(preview_info[-1])
288
+
289
+ buffer = BytesIO()
290
+ if image_format in ['jpeg'] or request.rel_url.query.get('channel', '') == 'rgb':
291
+ img = img.convert("RGB")
292
+ img.save(buffer, format=image_format, quality=quality)
293
+ buffer.seek(0)
294
+
295
+ return web.Response(body=buffer.read(), content_type=f'image/{image_format}',
296
+ headers={"Content-Disposition": f"filename=\"{filename}\""})
297
+
298
+ if 'channel' not in request.rel_url.query:
299
+ channel = 'rgba'
300
+ else:
301
+ channel = request.rel_url.query["channel"]
302
+
303
+ if channel == 'rgb':
304
+ with Image.open(file) as img:
305
+ if img.mode == "RGBA":
306
+ r, g, b, a = img.split()
307
+ new_img = Image.merge('RGB', (r, g, b))
308
+ else:
309
+ new_img = img.convert("RGB")
310
+
311
+ buffer = BytesIO()
312
+ new_img.save(buffer, format='PNG')
313
+ buffer.seek(0)
314
+
315
+ return web.Response(body=buffer.read(), content_type='image/png',
316
+ headers={"Content-Disposition": f"filename=\"{filename}\""})
317
+
318
+ elif channel == 'a':
319
+ with Image.open(file) as img:
320
+ if img.mode == "RGBA":
321
+ _, _, _, a = img.split()
322
+ else:
323
+ a = Image.new('L', img.size, 255)
324
+
325
+ # alpha img
326
+ alpha_img = Image.new('RGBA', img.size)
327
+ alpha_img.putalpha(a)
328
+ alpha_buffer = BytesIO()
329
+ alpha_img.save(alpha_buffer, format='PNG')
330
+ alpha_buffer.seek(0)
331
+
332
+ return web.Response(body=alpha_buffer.read(), content_type='image/png',
333
+ headers={"Content-Disposition": f"filename=\"{filename}\""})
334
+ else:
335
+ return web.FileResponse(file, headers={"Content-Disposition": f"filename=\"{filename}\""})
336
+
337
+ return web.Response(status=404)
338
+
339
+ @routes.get("/view_metadata/{folder_name}")
340
+ async def view_metadata(request):
341
+ folder_name = request.match_info.get("folder_name", None)
342
+ if folder_name is None:
343
+ return web.Response(status=404)
344
+ if not "filename" in request.rel_url.query:
345
+ return web.Response(status=404)
346
+
347
+ filename = request.rel_url.query["filename"]
348
+ if not filename.endswith(".safetensors"):
349
+ return web.Response(status=404)
350
+
351
+ safetensors_path = folder_paths.get_full_path(folder_name, filename)
352
+ if safetensors_path is None:
353
+ return web.Response(status=404)
354
+ out = comfy.utils.safetensors_header(safetensors_path, max_size=1024*1024)
355
+ if out is None:
356
+ return web.Response(status=404)
357
+ dt = json.loads(out)
358
+ if not "__metadata__" in dt:
359
+ return web.Response(status=404)
360
+ return web.json_response(dt["__metadata__"])
361
+
362
+ @routes.get("/system_stats")
363
+ async def get_queue(request):
364
+ device = comfy.model_management.get_torch_device()
365
+ device_name = comfy.model_management.get_torch_device_name(device)
366
+ vram_total, torch_vram_total = comfy.model_management.get_total_memory(device, torch_total_too=True)
367
+ vram_free, torch_vram_free = comfy.model_management.get_free_memory(device, torch_free_too=True)
368
+ system_stats = {
369
+ "system": {
370
+ "os": os.name,
371
+ "python_version": sys.version,
372
+ "embedded_python": os.path.split(os.path.split(sys.executable)[0])[1] == "python_embeded"
373
+ },
374
+ "devices": [
375
+ {
376
+ "name": device_name,
377
+ "type": device.type,
378
+ "index": device.index,
379
+ "vram_total": vram_total,
380
+ "vram_free": vram_free,
381
+ "torch_vram_total": torch_vram_total,
382
+ "torch_vram_free": torch_vram_free,
383
+ }
384
+ ]
385
+ }
386
+ return web.json_response(system_stats)
387
+
388
+ @routes.get("/prompt")
389
+ async def get_prompt(request):
390
+ return web.json_response(self.get_queue_info())
391
+
392
+ def node_info(node_class):
393
+ obj_class = nodes.NODE_CLASS_MAPPINGS[node_class]
394
+ info = {}
395
+ info['input'] = obj_class.INPUT_TYPES()
396
+ info['output'] = obj_class.RETURN_TYPES
397
+ info['output_is_list'] = obj_class.OUTPUT_IS_LIST if hasattr(obj_class, 'OUTPUT_IS_LIST') else [False] * len(obj_class.RETURN_TYPES)
398
+ info['output_name'] = obj_class.RETURN_NAMES if hasattr(obj_class, 'RETURN_NAMES') else info['output']
399
+ info['name'] = node_class
400
+ info['display_name'] = nodes.NODE_DISPLAY_NAME_MAPPINGS[node_class] if node_class in nodes.NODE_DISPLAY_NAME_MAPPINGS.keys() else node_class
401
+ info['description'] = obj_class.DESCRIPTION if hasattr(obj_class,'DESCRIPTION') else ''
402
+ info['category'] = 'sd'
403
+ if hasattr(obj_class, 'OUTPUT_NODE') and obj_class.OUTPUT_NODE == True:
404
+ info['output_node'] = True
405
+ else:
406
+ info['output_node'] = False
407
+
408
+ if hasattr(obj_class, 'CATEGORY'):
409
+ info['category'] = obj_class.CATEGORY
410
+ return info
411
+
412
+ @routes.get("/object_info")
413
+ async def get_object_info(request):
414
+ out = {}
415
+ for x in nodes.NODE_CLASS_MAPPINGS:
416
+ out[x] = node_info(x)
417
+ return web.json_response(out)
418
+
419
+ @routes.get("/object_info/{node_class}")
420
+ async def get_object_info_node(request):
421
+ node_class = request.match_info.get("node_class", None)
422
+ out = {}
423
+ if (node_class is not None) and (node_class in nodes.NODE_CLASS_MAPPINGS):
424
+ out[node_class] = node_info(node_class)
425
+ return web.json_response(out)
426
+
427
+ @routes.get("/history")
428
+ async def get_history(request):
429
+ return web.json_response(self.prompt_queue.get_history())
430
+
431
+ @routes.get("/history/{prompt_id}")
432
+ async def get_history(request):
433
+ prompt_id = request.match_info.get("prompt_id", None)
434
+ return web.json_response(self.prompt_queue.get_history(prompt_id=prompt_id))
435
+
436
+ @routes.get("/queue")
437
+ async def get_queue(request):
438
+ queue_info = {}
439
+ current_queue = self.prompt_queue.get_current_queue()
440
+ queue_info['queue_running'] = current_queue[0]
441
+ queue_info['queue_pending'] = current_queue[1]
442
+ return web.json_response(queue_info)
443
+
444
+ @routes.post("/prompt")
445
+ async def post_prompt(request):
446
+ print("got prompt")
447
+ resp_code = 200
448
+ out_string = ""
449
+ json_data = await request.json()
450
+ json_data = self.trigger_on_prompt(json_data)
451
+
452
+ if "number" in json_data:
453
+ number = float(json_data['number'])
454
+ else:
455
+ number = self.number
456
+ if "front" in json_data:
457
+ if json_data['front']:
458
+ number = -number
459
+
460
+ self.number += 1
461
+
462
+ if "prompt" in json_data:
463
+ prompt = json_data["prompt"]
464
+ valid = execution.validate_prompt(prompt)
465
+ extra_data = {}
466
+ if "extra_data" in json_data:
467
+ extra_data = json_data["extra_data"]
468
+
469
+ if "client_id" in json_data:
470
+ extra_data["client_id"] = json_data["client_id"]
471
+ if valid[0]:
472
+ prompt_id = str(uuid.uuid4())
473
+ outputs_to_execute = valid[2]
474
+ self.prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute))
475
+ response = {"prompt_id": prompt_id, "number": number, "node_errors": valid[3]}
476
+ return web.json_response(response)
477
+ else:
478
+ print("invalid prompt:", valid[1])
479
+ return web.json_response({"error": valid[1], "node_errors": valid[3]}, status=400)
480
+ else:
481
+ return web.json_response({"error": "no prompt", "node_errors": []}, status=400)
482
+
483
+ @routes.post("/queue")
484
+ async def post_queue(request):
485
+ json_data = await request.json()
486
+ if "clear" in json_data:
487
+ if json_data["clear"]:
488
+ self.prompt_queue.wipe_queue()
489
+ if "delete" in json_data:
490
+ to_delete = json_data['delete']
491
+ for id_to_delete in to_delete:
492
+ delete_func = lambda a: a[1] == id_to_delete
493
+ self.prompt_queue.delete_queue_item(delete_func)
494
+
495
+ return web.Response(status=200)
496
+
497
+ @routes.post("/interrupt")
498
+ async def post_interrupt(request):
499
+ nodes.interrupt_processing()
500
+ return web.Response(status=200)
501
+
502
+ @routes.post("/history")
503
+ async def post_history(request):
504
+ json_data = await request.json()
505
+ if "clear" in json_data:
506
+ if json_data["clear"]:
507
+ self.prompt_queue.wipe_history()
508
+ if "delete" in json_data:
509
+ to_delete = json_data['delete']
510
+ for id_to_delete in to_delete:
511
+ self.prompt_queue.delete_history_item(id_to_delete)
512
+
513
+ return web.Response(status=200)
514
+
515
+ def add_routes(self):
516
+ self.app.add_routes(self.routes)
517
+
518
+ for name, dir in nodes.EXTENSION_WEB_DIRS.items():
519
+ self.app.add_routes([
520
+ web.static('/extensions/' + urllib.parse.quote(name), dir, follow_symlinks=True),
521
+ ])
522
+
523
+ self.app.add_routes([
524
+ web.static('/', self.web_root, follow_symlinks=True),
525
+ ])
526
+
527
+ def get_queue_info(self):
528
+ prompt_info = {}
529
+ exec_info = {}
530
+ exec_info['queue_remaining'] = self.prompt_queue.get_tasks_remaining()
531
+ prompt_info['exec_info'] = exec_info
532
+ return prompt_info
533
+
534
+ async def send(self, event, data, sid=None):
535
+ if event == BinaryEventTypes.UNENCODED_PREVIEW_IMAGE:
536
+ await self.send_image(data, sid=sid)
537
+ elif isinstance(data, (bytes, bytearray)):
538
+ await self.send_bytes(event, data, sid)
539
+ else:
540
+ await self.send_json(event, data, sid)
541
+
542
+ def encode_bytes(self, event, data):
543
+ if not isinstance(event, int):
544
+ raise RuntimeError(f"Binary event types must be integers, got {event}")
545
+
546
+ packed = struct.pack(">I", event)
547
+ message = bytearray(packed)
548
+ message.extend(data)
549
+ return message
550
+
551
+ async def send_image(self, image_data, sid=None):
552
+ image_type = image_data[0]
553
+ image = image_data[1]
554
+ max_size = image_data[2]
555
+ if max_size is not None:
556
+ if hasattr(Image, 'Resampling'):
557
+ resampling = Image.Resampling.BILINEAR
558
+ else:
559
+ resampling = Image.ANTIALIAS
560
+
561
+ image = ImageOps.contain(image, (max_size, max_size), resampling)
562
+ type_num = 1
563
+ if image_type == "JPEG":
564
+ type_num = 1
565
+ elif image_type == "PNG":
566
+ type_num = 2
567
+
568
+ bytesIO = BytesIO()
569
+ header = struct.pack(">I", type_num)
570
+ bytesIO.write(header)
571
+ image.save(bytesIO, format=image_type, quality=95, compress_level=4)
572
+ preview_bytes = bytesIO.getvalue()
573
+ await self.send_bytes(BinaryEventTypes.PREVIEW_IMAGE, preview_bytes, sid=sid)
574
+
575
+ async def send_bytes(self, event, data, sid=None):
576
+ message = self.encode_bytes(event, data)
577
+
578
+ if sid is None:
579
+ for ws in self.sockets.values():
580
+ await send_socket_catch_exception(ws.send_bytes, message)
581
+ elif sid in self.sockets:
582
+ await send_socket_catch_exception(self.sockets[sid].send_bytes, message)
583
+
584
+ async def send_json(self, event, data, sid=None):
585
+ message = {"type": event, "data": data}
586
+
587
+ if sid is None:
588
+ for ws in self.sockets.values():
589
+ await send_socket_catch_exception(ws.send_json, message)
590
+ elif sid in self.sockets:
591
+ await send_socket_catch_exception(self.sockets[sid].send_json, message)
592
+
593
+ def send_sync(self, event, data, sid=None):
594
+ self.loop.call_soon_threadsafe(
595
+ self.messages.put_nowait, (event, data, sid))
596
+
597
+ def queue_updated(self):
598
+ self.send_sync("status", { "status": self.get_queue_info() })
599
+
600
+ async def publish_loop(self):
601
+ while True:
602
+ msg = await self.messages.get()
603
+ await self.send(*msg)
604
+
605
+ async def start(self, address, port, verbose=True, call_on_start=None):
606
+ runner = web.AppRunner(self.app, access_log=None)
607
+ await runner.setup()
608
+ site = web.TCPSite(runner, address, port)
609
+ await site.start()
610
+
611
+ if address == '':
612
+ address = '0.0.0.0'
613
+ if verbose:
614
+ print("Starting server\n")
615
+ print("To see the GUI go to: http://{}:{}".format(address, port))
616
+ if call_on_start is not None:
617
+ call_on_start(address, port)
618
+
619
+ def add_on_prompt_handler(self, handler):
620
+ self.on_prompt_handlers.append(handler)
621
+
622
+ def trigger_on_prompt(self, json_data):
623
+ for handler in self.on_prompt_handlers:
624
+ try:
625
+ json_data = handler(json_data)
626
+ except Exception as e:
627
+ print(f"[ERROR] An error occurred during the on_prompt_handler processing")
628
+ traceback.print_exc()
629
+
630
+ return json_data