JasonSmithSO commited on
Commit
1b1c183
·
verified ·
1 Parent(s): f18fd7a

Upload 203 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. LICENSE +674 -0
  3. README.md +290 -245
  4. execution.py +993 -0
  5. extra_model_paths.yaml.example +45 -0
  6. fix_torch.py +25 -0
  7. folder_paths.py +345 -0
  8. index.html +50 -0
  9. latent_preview.py +94 -0
  10. load_file_from_url.py +55 -0
  11. main.py +266 -0
  12. model_filemanager/__init__.py +2 -0
  13. model_filemanager/download_models.py +240 -0
  14. models/checkpoints/put_checkpoints_here +0 -0
  15. models/clip/put_clip_or_text_encoder_models_here +0 -0
  16. models/clip_vision/put_clip_vision_models_here +0 -0
  17. models/configs/anything_v3.yaml +73 -0
  18. models/configs/v1-inference.yaml +70 -0
  19. models/configs/v1-inference_clip_skip_2.yaml +73 -0
  20. models/configs/v1-inference_clip_skip_2_fp16.yaml +74 -0
  21. models/configs/v1-inference_fp16.yaml +71 -0
  22. models/configs/v1-inpainting-inference.yaml +71 -0
  23. models/configs/v2-inference-v.yaml +68 -0
  24. models/configs/v2-inference-v_fp32.yaml +68 -0
  25. models/configs/v2-inference.yaml +67 -0
  26. models/configs/v2-inference_fp32.yaml +67 -0
  27. models/configs/v2-inpainting-inference.yaml +158 -0
  28. models/controlnet/put_controlnets_and_t2i_here +0 -0
  29. models/diffusers/put_diffusers_models_here +0 -0
  30. models/diffusion_models/put_diffusion_model_files_here +0 -0
  31. models/embeddings/put_embeddings_or_textual_inversion_concepts_here +0 -0
  32. models/gligen/put_gligen_models_here +0 -0
  33. models/hypernetworks/put_hypernetworks_here +0 -0
  34. models/loras/put_loras_here +0 -0
  35. models/photomaker/put_photomaker_models_here +0 -0
  36. models/style_models/put_t2i_style_model_here +0 -0
  37. models/unet/put_unet_files_here +0 -0
  38. models/upscale_models/put_esrgan_and_other_upscale_models_here +0 -0
  39. models/vae/put_vae_here +0 -0
  40. models/vae_approx/put_taesd_encoder_pth_and_taesd_decoder_pth_here +0 -0
  41. new_updater.py +35 -0
  42. node_helpers.py +37 -0
  43. nodes.py +2136 -0
  44. notebooks/comfyui_colab.ipynb +329 -0
  45. pytest.ini +9 -0
  46. requirements.txt +17 -21
  47. script_examples/basic_api_example.py +120 -0
  48. script_examples/websockets_api_example.py +163 -0
  49. script_examples/websockets_api_example_ws_images.py +159 -0
  50. server.py +841 -0
.gitattributes CHANGED
@@ -53,3 +53,4 @@ rgthree-comfy/docs/rgthree_context.png filter=lfs diff=lfs merge=lfs -text
53
  x-flux-comfyui/assets/image1.png filter=lfs diff=lfs merge=lfs -text
54
  x-flux-comfyui/guide/manager_menu.png filter=lfs diff=lfs merge=lfs -text
55
  x-flux-comfyui/workflows/example.jpg filter=lfs diff=lfs merge=lfs -text
 
 
53
  x-flux-comfyui/assets/image1.png filter=lfs diff=lfs merge=lfs -text
54
  x-flux-comfyui/guide/manager_menu.png filter=lfs diff=lfs merge=lfs -text
55
  x-flux-comfyui/workflows/example.jpg filter=lfs diff=lfs merge=lfs -text
56
+ web/fonts/materialdesignicons-webfont.woff2 filter=lfs diff=lfs merge=lfs -text
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 CHANGED
@@ -1,252 +1,297 @@
1
- # ComfyUI's ControlNet Auxiliary Preprocessors
2
- Plug-and-play [ComfyUI](https://github.com/comfyanonymous/ComfyUI) node sets for making [ControlNet](https://github.com/lllyasviel/ControlNet/) hint images
3
-
4
- "anime style, a protest in the street, cyberpunk city, a woman with pink hair and golden eyes (looking at the viewer) is holding a sign with the text "ComfyUI ControlNet Aux" in bold, neon pink" on Flux.1 Dev
5
-
6
- ![](./examples/CNAuxBanner.jpg)
7
-
8
- The code is copy-pasted from the respective folders in https://github.com/lllyasviel/ControlNet/tree/main/annotator and connected to [the 🤗 Hub](https://huggingface.co/lllyasviel/Annotators).
9
-
10
- All credit & copyright goes to https://github.com/lllyasviel.
11
-
12
- # Updates
13
- Go to [Update page](./UPDATES.md) to follow updates
14
-
15
- # Installation:
16
- ## Using ComfyUI Manager (recommended):
17
- Install [ComfyUI Manager](https://github.com/ltdrdata/ComfyUI-Manager) and do steps introduced there to install this repo.
18
-
19
- ## Alternative:
20
- If you're running on Linux, or non-admin account on windows you'll want to ensure `/ComfyUI/custom_nodes` and `comfyui_controlnet_aux` has write permissions.
21
-
22
- There is now a **install.bat** you can run to install to portable if detected. Otherwise it will default to system and assume you followed ConfyUI's manual installation steps.
23
-
24
- If you can't run **install.bat** (e.g. you are a Linux user). Open the CMD/Shell and do the following:
25
- - Navigate to your `/ComfyUI/custom_nodes/` folder
26
- - Run `git clone https://github.com/Fannovel16/comfyui_controlnet_aux/`
27
- - Navigate to your `comfyui_controlnet_aux` folder
28
- - Portable/venv:
29
- - Run `path/to/ComfUI/python_embedded/python.exe -s -m pip install -r requirements.txt`
30
- - With system python
31
- - Run `pip install -r requirements.txt`
32
- - Start ComfyUI
33
-
34
- # Nodes
35
- Please note that this repo only supports preprocessors making hint images (e.g. stickman, canny edge, etc).
36
- All preprocessors except Inpaint are intergrated into `AIO Aux Preprocessor` node.
37
- This node allow you to quickly get the preprocessor but a preprocessor's own threshold parameters won't be able to set.
38
- You need to use its node directly to set thresholds.
39
-
40
- # Nodes (sections are categories in Comfy menu)
41
- ## Line Extractors
42
- | Preprocessor Node | sd-webui-controlnet/other | ControlNet/T2I-Adapter |
43
- |-----------------------------|---------------------------|-------------------------------------------|
44
- | Binary Lines | binary | control_scribble |
45
- | Canny Edge | canny | control_v11p_sd15_canny <br> control_canny <br> t2iadapter_canny |
46
- | HED Soft-Edge Lines | hed | control_v11p_sd15_softedge <br> control_hed |
47
- | Standard Lineart | standard_lineart | control_v11p_sd15_lineart |
48
- | Realistic Lineart | lineart (or `lineart_coarse` if `coarse` is enabled) | control_v11p_sd15_lineart |
49
- | Anime Lineart | lineart_anime | control_v11p_sd15s2_lineart_anime |
50
- | Manga Lineart | lineart_anime_denoise | control_v11p_sd15s2_lineart_anime |
51
- | M-LSD Lines | mlsd | control_v11p_sd15_mlsd <br> control_mlsd |
52
- | PiDiNet Soft-Edge Lines | pidinet | control_v11p_sd15_softedge <br> control_scribble |
53
- | Scribble Lines | scribble | control_v11p_sd15_scribble <br> control_scribble |
54
- | Scribble XDoG Lines | scribble_xdog | control_v11p_sd15_scribble <br> control_scribble |
55
- | Fake Scribble Lines | scribble_hed | control_v11p_sd15_scribble <br> control_scribble |
56
- | TEED Soft-Edge Lines | teed | [controlnet-sd-xl-1.0-softedge-dexined](https://huggingface.co/SargeZT/controlnet-sd-xl-1.0-softedge-dexined/blob/main/controlnet-sd-xl-1.0-softedge-dexined.safetensors) <br> control_v11p_sd15_softedge (Theoretically)
57
- | Scribble PiDiNet Lines | scribble_pidinet | control_v11p_sd15_scribble <br> control_scribble |
58
- | AnyLine Lineart | | mistoLine_fp16.safetensors <br> mistoLine_rank256 <br> control_v11p_sd15s2_lineart_anime <br> control_v11p_sd15_lineart |
59
-
60
- ## Normal and Depth Estimators
61
- | Preprocessor Node | sd-webui-controlnet/other | ControlNet/T2I-Adapter |
62
- |-----------------------------|---------------------------|-------------------------------------------|
63
- | MiDaS Depth Map | (normal) depth | control_v11f1p_sd15_depth <br> control_depth <br> t2iadapter_depth |
64
- | LeReS Depth Map | depth_leres | control_v11f1p_sd15_depth <br> control_depth <br> t2iadapter_depth |
65
- | Zoe Depth Map | depth_zoe | control_v11f1p_sd15_depth <br> control_depth <br> t2iadapter_depth |
66
- | MiDaS Normal Map | normal_map | control_normal |
67
- | BAE Normal Map | normal_bae | control_v11p_sd15_normalbae |
68
- | MeshGraphormer Hand Refiner ([HandRefinder](https://github.com/wenquanlu/HandRefiner)) | depth_hand_refiner | [control_sd15_inpaint_depth_hand_fp16](https://huggingface.co/hr16/ControlNet-HandRefiner-pruned/blob/main/control_sd15_inpaint_depth_hand_fp16.safetensors) |
69
- | Depth Anything | depth_anything | [Depth-Anything](https://huggingface.co/spaces/LiheYoung/Depth-Anything/blob/main/checkpoints_controlnet/diffusion_pytorch_model.safetensors) |
70
- | Zoe Depth Anything <br> (Basically Zoe but the encoder is replaced with DepthAnything) | depth_anything | [Depth-Anything](https://huggingface.co/spaces/LiheYoung/Depth-Anything/blob/main/checkpoints_controlnet/diffusion_pytorch_model.safetensors) |
71
- | Normal DSINE | | control_normal/control_v11p_sd15_normalbae |
72
- | Metric3D Depth | | control_v11f1p_sd15_depth <br> control_depth <br> t2iadapter_depth |
73
- | Metric3D Normal | | control_v11p_sd15_normalbae |
74
- | Depth Anything V2 | | [Depth-Anything](https://huggingface.co/spaces/LiheYoung/Depth-Anything/blob/main/checkpoints_controlnet/diffusion_pytorch_model.safetensors) |
75
-
76
- ## Faces and Poses Estimators
77
- | Preprocessor Node | sd-webui-controlnet/other | ControlNet/T2I-Adapter |
78
- |-----------------------------|---------------------------|-------------------------------------------|
79
- | DWPose Estimator | dw_openpose_full | control_v11p_sd15_openpose <br> control_openpose <br> t2iadapter_openpose |
80
- | OpenPose Estimator | openpose (detect_body) <br> openpose_hand (detect_body + detect_hand) <br> openpose_faceonly (detect_face) <br> openpose_full (detect_hand + detect_body + detect_face) | control_v11p_sd15_openpose <br> control_openpose <br> t2iadapter_openpose |
81
- | MediaPipe Face Mesh | mediapipe_face | controlnet_sd21_laion_face_v2 |
82
- | Animal Estimator | animal_openpose | [control_sd15_animal_openpose_fp16](https://huggingface.co/huchenlei/animal_openpose/blob/main/control_sd15_animal_openpose_fp16.pth) |
83
-
84
- ## Optical Flow Estimators
85
- | Preprocessor Node | sd-webui-controlnet/other | ControlNet/T2I-Adapter |
86
- |-----------------------------|---------------------------|-------------------------------------------|
87
- | Unimatch Optical Flow | | [DragNUWA](https://github.com/ProjectNUWA/DragNUWA) |
88
-
89
- ### How to get OpenPose-format JSON?
90
- #### User-side
91
- This workflow will save images to ComfyUI's output folder (the same location as output images). If you haven't found `Save Pose Keypoints` node, update this extension
92
- ![](./examples/example_save_kps.png)
93
-
94
- #### Dev-side
95
- An array of [OpenPose-format JSON](https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/doc/02_output.md#json-output-format) corresponsding to each frame in an IMAGE batch can be gotten from DWPose and OpenPose using `app.nodeOutputs` on the UI or `/history` API endpoint. JSON output from AnimalPose uses a kinda similar format to OpenPose JSON:
96
- ```
97
- [
98
- {
99
- "version": "ap10k",
100
- "animals": [
101
- [[x1, y1, 1], [x2, y2, 1],..., [x17, y17, 1]],
102
- [[x1, y1, 1], [x2, y2, 1],..., [x17, y17, 1]],
103
- ...
104
- ],
105
- "canvas_height": 512,
106
- "canvas_width": 768
107
- },
108
- ...
109
- ]
110
- ```
111
 
112
- For extension developers (e.g. Openpose editor):
113
- ```js
114
- const poseNodes = app.graph._nodes.filter(node => ["OpenposePreprocessor", "DWPreprocessor", "AnimalPosePreprocessor"].includes(node.type))
115
- for (const poseNode of poseNodes) {
116
- const openposeResults = JSON.parse(app.nodeOutputs[poseNode.id].openpose_json[0])
117
- console.log(openposeResults) //An array containing Openpose JSON for each frame
118
- }
119
- ```
120
 
121
- For API users:
122
- Javascript
123
- ```js
124
- import fetch from "node-fetch" //Remember to add "type": "module" to "package.json"
125
- async function main() {
126
- const promptId = '792c1905-ecfe-41f4-8114-83e6a4a09a9f' //Too lazy to POST /queue
127
- let history = await fetch(`http://127.0.0.1:8188/history/${promptId}`).then(re => re.json())
128
- history = history[promptId]
129
- const nodeOutputs = Object.values(history.outputs).filter(output => output.openpose_json)
130
- for (const nodeOutput of nodeOutputs) {
131
- const openposeResults = JSON.parse(nodeOutput.openpose_json[0])
132
- console.log(openposeResults) //An array containing Openpose JSON for each frame
133
- }
134
- }
135
- main()
136
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
137
 
138
- Python
139
- ```py
140
- import json, urllib.request
141
 
142
- server_address = "127.0.0.1:8188"
143
- prompt_id = '' #Too lazy to POST /queue
144
 
145
- def get_history(prompt_id):
146
- with urllib.request.urlopen("http://{}/history/{}".format(server_address, prompt_id)) as response:
147
- return json.loads(response.read())
148
 
149
- history = get_history(prompt_id)[prompt_id]
150
- for o in history['outputs']:
151
- for node_id in history['outputs']:
152
- node_output = history['outputs'][node_id]
153
- if 'openpose_json' in node_output:
154
- print(json.loads(node_output['openpose_json'][0])) #An list containing Openpose JSON for each frame
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  ```
156
- ## Semantic Segmentation
157
- | Preprocessor Node | sd-webui-controlnet/other | ControlNet/T2I-Adapter |
158
- |-----------------------------|---------------------------|-------------------------------------------|
159
- | OneFormer ADE20K Segmentor | oneformer_ade20k | control_v11p_sd15_seg |
160
- | OneFormer COCO Segmentor | oneformer_coco | control_v11p_sd15_seg |
161
- | UniFormer Segmentor | segmentation |control_sd15_seg <br> control_v11p_sd15_seg|
162
-
163
- ## T2IAdapter-only
164
- | Preprocessor Node | sd-webui-controlnet/other | ControlNet/T2I-Adapter |
165
- |-----------------------------|---------------------------|-------------------------------------------|
166
- | Color Pallete | color | t2iadapter_color |
167
- | Content Shuffle | shuffle | t2iadapter_style |
168
-
169
- ## Recolor
170
- | Preprocessor Node | sd-webui-controlnet/other | ControlNet/T2I-Adapter |
171
- |-----------------------------|---------------------------|-------------------------------------------|
172
- | Image Luminance | recolor_luminance | [ioclab_sd15_recolor](https://huggingface.co/lllyasviel/sd_control_collection/resolve/main/ioclab_sd15_recolor.safetensors) <br> [sai_xl_recolor_256lora](https://huggingface.co/lllyasviel/sd_control_collection/resolve/main/sai_xl_recolor_256lora.safetensors) <br> [bdsqlsz_controlllite_xl_recolor_luminance](https://huggingface.co/bdsqlsz/qinglong_controlnet-lllite/resolve/main/bdsqlsz_controlllite_xl_recolor_luminance.safetensors) |
173
- | Image Intensity | recolor_intensity | Idk. Maybe same as above? |
174
-
175
- # Examples
176
- > A picture is worth a thousand words
177
-
178
- ![](./examples/ExecuteAll1.jpg)
179
- ![](./examples/ExecuteAll2.jpg)
180
-
181
- # Testing workflow
182
- https://github.com/Fannovel16/comfyui_controlnet_aux/blob/main/examples/ExecuteAll.png
183
- Input image: https://github.com/Fannovel16/comfyui_controlnet_aux/blob/main/examples/comfyui-controlnet-aux-logo.png
184
-
185
- # Q&A:
186
- ## Why some nodes doesn't appear after I installed this repo?
187
-
188
- This repo has a new mechanism which will skip any custom node can't be imported. If you meet this case, please create a issue on [Issues tab](https://github.com/Fannovel16/comfyui_controlnet_aux/issues) with the log from the command line.
189
-
190
- ## DWPose/AnimalPose only uses CPU so it's so slow. How can I make it use GPU?
191
- There are two ways to speed-up DWPose: using TorchScript checkpoints (.torchscript.pt) checkpoints or ONNXRuntime (.onnx). TorchScript way is little bit slower than ONNXRuntime but doesn't require any additional library and still way way faster than CPU.
192
-
193
- A torchscript bbox detector is compatiable with an onnx pose estimator and vice versa.
194
- ### TorchScript
195
- Set `bbox_detector` and `pose_estimator` according to this picture. You can try other bbox detector endings with `.torchscript.pt` to reduce bbox detection time if input images are ideal.
196
- ![](./examples/example_torchscript.png)
197
- ### ONNXRuntime
198
- If onnxruntime is installed successfully and the checkpoint used endings with `.onnx`, it will replace default cv2 backend to take advantage of GPU. Note that if you are using NVidia card, this method currently can only works on CUDA 11.8 (ComfyUI_windows_portable_nvidia_cu118_or_cpu.7z) unless you compile onnxruntime yourself.
199
-
200
- 1. Know your onnxruntime build:
201
- * * NVidia CUDA 11.x or bellow/AMD GPU: `onnxruntime-gpu`
202
- * * NVidia CUDA 12.x: `onnxruntime-gpu --extra-index-url https://aiinfra.pkgs.visualstudio.com/PublicPackages/_packaging/onnxruntime-cuda-12/pypi/simple/`
203
- * * DirectML: `onnxruntime-directml`
204
- * * OpenVINO: `onnxruntime-openvino`
205
-
206
- Note that if this is your first time using ComfyUI, please test if it can run on your device before doing next steps.
207
-
208
- 2. Add it into `requirements.txt`
209
-
210
- 3. Run `install.bat` or pip command mentioned in Installation
211
-
212
- ![](./examples/example_onnx.png)
213
-
214
- # Assets files of preprocessors
215
- * anime_face_segment: [bdsqlsz/qinglong_controlnet-lllite/Annotators/UNet.pth](https://huggingface.co/bdsqlsz/qinglong_controlnet-lllite/blob/main/Annotators/UNet.pth), [anime-seg/isnetis.ckpt](https://huggingface.co/skytnt/anime-seg/blob/main/isnetis.ckpt)
216
- * densepose: [LayerNorm/DensePose-TorchScript-with-hint-image/densepose_r50_fpn_dl.torchscript](https://huggingface.co/LayerNorm/DensePose-TorchScript-with-hint-image/blob/main/densepose_r50_fpn_dl.torchscript)
217
- * dwpose:
218
- * * bbox_detector: Either [yzd-v/DWPose/yolox_l.onnx](https://huggingface.co/yzd-v/DWPose/blob/main/yolox_l.onnx), [hr16/yolox-onnx/yolox_l.torchscript.pt](https://huggingface.co/hr16/yolox-onnx/blob/main/yolox_l.torchscript.pt), [hr16/yolo-nas-fp16/yolo_nas_l_fp16.onnx](https://huggingface.co/hr16/yolo-nas-fp16/blob/main/yolo_nas_l_fp16.onnx), [hr16/yolo-nas-fp16/yolo_nas_m_fp16.onnx](https://huggingface.co/hr16/yolo-nas-fp16/blob/main/yolo_nas_m_fp16.onnx), [hr16/yolo-nas-fp16/yolo_nas_s_fp16.onnx](https://huggingface.co/hr16/yolo-nas-fp16/blob/main/yolo_nas_s_fp16.onnx)
219
- * * pose_estimator: Either [hr16/DWPose-TorchScript-BatchSize5/dw-ll_ucoco_384_bs5.torchscript.pt](https://huggingface.co/hr16/DWPose-TorchScript-BatchSize5/blob/main/dw-ll_ucoco_384_bs5.torchscript.pt), [yzd-v/DWPose/dw-ll_ucoco_384.onnx](https://huggingface.co/yzd-v/DWPose/blob/main/dw-ll_ucoco_384.onnx)
220
- * animal_pose (ap10k):
221
- * * bbox_detector: Either [yzd-v/DWPose/yolox_l.onnx](https://huggingface.co/yzd-v/DWPose/blob/main/yolox_l.onnx), [hr16/yolox-onnx/yolox_l.torchscript.pt](https://huggingface.co/hr16/yolox-onnx/blob/main/yolox_l.torchscript.pt), [hr16/yolo-nas-fp16/yolo_nas_l_fp16.onnx](https://huggingface.co/hr16/yolo-nas-fp16/blob/main/yolo_nas_l_fp16.onnx), [hr16/yolo-nas-fp16/yolo_nas_m_fp16.onnx](https://huggingface.co/hr16/yolo-nas-fp16/blob/main/yolo_nas_m_fp16.onnx), [hr16/yolo-nas-fp16/yolo_nas_s_fp16.onnx](https://huggingface.co/hr16/yolo-nas-fp16/blob/main/yolo_nas_s_fp16.onnx)
222
- * * pose_estimator: Either [hr16/DWPose-TorchScript-BatchSize5/rtmpose-m_ap10k_256_bs5.torchscript.pt](https://huggingface.co/hr16/DWPose-TorchScript-BatchSize5/blob/main/rtmpose-m_ap10k_256_bs5.torchscript.pt), [hr16/UnJIT-DWPose/rtmpose-m_ap10k_256.onnx](https://huggingface.co/hr16/UnJIT-DWPose/blob/main/rtmpose-m_ap10k_256.onnx)
223
- * hed: [lllyasviel/Annotators/ControlNetHED.pth](https://huggingface.co/lllyasviel/Annotators/blob/main/ControlNetHED.pth)
224
- * leres: [lllyasviel/Annotators/res101.pth](https://huggingface.co/lllyasviel/Annotators/blob/main/res101.pth), [lllyasviel/Annotators/latest_net_G.pth](https://huggingface.co/lllyasviel/Annotators/blob/main/latest_net_G.pth)
225
- * lineart: [lllyasviel/Annotators/sk_model.pth](https://huggingface.co/lllyasviel/Annotators/blob/main/sk_model.pth), [lllyasviel/Annotators/sk_model2.pth](https://huggingface.co/lllyasviel/Annotators/blob/main/sk_model2.pth)
226
- * lineart_anime: [lllyasviel/Annotators/netG.pth](https://huggingface.co/lllyasviel/Annotators/blob/main/netG.pth)
227
- * manga_line: [lllyasviel/Annotators/erika.pth](https://huggingface.co/lllyasviel/Annotators/blob/main/erika.pth)
228
- * mesh_graphormer: [hr16/ControlNet-HandRefiner-pruned/graphormer_hand_state_dict.bin](https://huggingface.co/hr16/ControlNet-HandRefiner-pruned/blob/main/graphormer_hand_state_dict.bin), [hr16/ControlNet-HandRefiner-pruned/hrnetv2_w64_imagenet_pretrained.pth](https://huggingface.co/hr16/ControlNet-HandRefiner-pruned/blob/main/hrnetv2_w64_imagenet_pretrained.pth)
229
- * midas: [lllyasviel/Annotators/dpt_hybrid-midas-501f0c75.pt](https://huggingface.co/lllyasviel/Annotators/blob/main/dpt_hybrid-midas-501f0c75.pt)
230
- * mlsd: [lllyasviel/Annotators/mlsd_large_512_fp32.pth](https://huggingface.co/lllyasviel/Annotators/blob/main/mlsd_large_512_fp32.pth)
231
- * normalbae: [lllyasviel/Annotators/scannet.pt](https://huggingface.co/lllyasviel/Annotators/blob/main/scannet.pt)
232
- * oneformer: [lllyasviel/Annotators/250_16_swin_l_oneformer_ade20k_160k.pth](https://huggingface.co/lllyasviel/Annotators/blob/main/250_16_swin_l_oneformer_ade20k_160k.pth)
233
- * open_pose: [lllyasviel/Annotators/body_pose_model.pth](https://huggingface.co/lllyasviel/Annotators/blob/main/body_pose_model.pth), [lllyasviel/Annotators/hand_pose_model.pth](https://huggingface.co/lllyasviel/Annotators/blob/main/hand_pose_model.pth), [lllyasviel/Annotators/facenet.pth](https://huggingface.co/lllyasviel/Annotators/blob/main/facenet.pth)
234
- * pidi: [lllyasviel/Annotators/table5_pidinet.pth](https://huggingface.co/lllyasviel/Annotators/blob/main/table5_pidinet.pth)
235
- * sam: [dhkim2810/MobileSAM/mobile_sam.pt](https://huggingface.co/dhkim2810/MobileSAM/blob/main/mobile_sam.pt)
236
- * uniformer: [lllyasviel/Annotators/upernet_global_small.pth](https://huggingface.co/lllyasviel/Annotators/blob/main/upernet_global_small.pth)
237
- * zoe: [lllyasviel/Annotators/ZoeD_M12_N.pt](https://huggingface.co/lllyasviel/Annotators/blob/main/ZoeD_M12_N.pt)
238
- * teed: [bdsqlsz/qinglong_controlnet-lllite/7_model.pth](https://huggingface.co/bdsqlsz/qinglong_controlnet-lllite/blob/main/Annotators/7_model.pth)
239
- * depth_anything: Either [LiheYoung/Depth-Anything/checkpoints/depth_anything_vitl14.pth](https://huggingface.co/spaces/LiheYoung/Depth-Anything/blob/main/checkpoints/depth_anything_vitl14.pth), [LiheYoung/Depth-Anything/checkpoints/depth_anything_vitb14.pth](https://huggingface.co/spaces/LiheYoung/Depth-Anything/blob/main/checkpoints/depth_anything_vitb14.pth) or [LiheYoung/Depth-Anything/checkpoints/depth_anything_vits14.pth](https://huggingface.co/spaces/LiheYoung/Depth-Anything/blob/main/checkpoints/depth_anything_vits14.pth)
240
- * diffusion_edge: Either [hr16/Diffusion-Edge/diffusion_edge_indoor.pt](https://huggingface.co/hr16/Diffusion-Edge/blob/main/diffusion_edge_indoor.pt), [hr16/Diffusion-Edge/diffusion_edge_urban.pt](https://huggingface.co/hr16/Diffusion-Edge/blob/main/diffusion_edge_urban.pt) or [hr16/Diffusion-Edge/diffusion_edge_natrual.pt](https://huggingface.co/hr16/Diffusion-Edge/blob/main/diffusion_edge_natrual.pt)
241
- * unimatch: Either [hr16/Unimatch/gmflow-scale2-regrefine6-mixdata.pth](https://huggingface.co/hr16/Unimatch/blob/main/gmflow-scale2-regrefine6-mixdata.pth), [hr16/Unimatch/gmflow-scale2-mixdata.pth](https://huggingface.co/hr16/Unimatch/blob/main/gmflow-scale2-mixdata.pth) or [hr16/Unimatch/gmflow-scale1-mixdata.pth](https://huggingface.co/hr16/Unimatch/blob/main/gmflow-scale1-mixdata.pth)
242
- * zoe_depth_anything: Either [LiheYoung/Depth-Anything/checkpoints_metric_depth/depth_anything_metric_depth_indoor.pt](https://huggingface.co/spaces/LiheYoung/Depth-Anything/blob/main/checkpoints_metric_depth/depth_anything_metric_depth_indoor.pt) or [LiheYoung/Depth-Anything/checkpoints_metric_depth/depth_anything_metric_depth_outdoor.pt](https://huggingface.co/spaces/LiheYoung/Depth-Anything/blob/main/checkpoints_metric_depth/depth_anything_metric_depth_outdoor.pt)
243
- # 1500 Stars 😄
244
- <a href="https://star-history.com/#Fannovel16/comfyui_controlnet_aux&Date">
245
- <picture>
246
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=Fannovel16/comfyui_controlnet_aux&type=Date&theme=dark" />
247
- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=Fannovel16/comfyui_controlnet_aux&type=Date" />
248
- <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=Fannovel16/comfyui_controlnet_aux&type=Date" />
249
- </picture>
250
- </a>
251
-
252
- Thanks for yalls supports. I never thought the graph for stars would be linear lol.
 
1
+ <div align="center">
2
+
3
+ # ComfyUI
4
+ **The most powerful and modular diffusion model GUI and backend.**
5
+
6
+
7
+ [![Website][website-shield]][website-url]
8
+ [![Dynamic JSON Badge][discord-shield]][discord-url]
9
+ [![Matrix][matrix-shield]][matrix-url]
10
+ <br>
11
+ [![][github-release-shield]][github-release-link]
12
+ [![][github-release-date-shield]][github-release-link]
13
+ [![][github-downloads-shield]][github-downloads-link]
14
+ [![][github-downloads-latest-shield]][github-downloads-link]
15
+
16
+ [matrix-shield]: https://img.shields.io/badge/Matrix-000000?style=flat&logo=matrix&logoColor=white
17
+ [matrix-url]: https://app.element.io/#/room/%23comfyui_space%3Amatrix.org
18
+ [website-shield]: https://img.shields.io/badge/ComfyOrg-4285F4?style=flat
19
+ [website-url]: https://www.comfy.org/
20
+ <!-- Workaround to display total user from https://github.com/badges/shields/issues/4500#issuecomment-2060079995 -->
21
+ [discord-shield]: https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fdiscord.com%2Fapi%2Finvites%2Fcomfyorg%3Fwith_counts%3Dtrue&query=%24.approximate_member_count&logo=discord&logoColor=white&label=Discord&color=green&suffix=%20total
22
+ [discord-url]: https://www.comfy.org/discord
23
+
24
+ [github-release-shield]: https://img.shields.io/github/v/release/comfyanonymous/ComfyUI?style=flat&sort=semver
25
+ [github-release-link]: https://github.com/comfyanonymous/ComfyUI/releases
26
+ [github-release-date-shield]: https://img.shields.io/github/release-date/comfyanonymous/ComfyUI?style=flat
27
+ [github-downloads-shield]: https://img.shields.io/github/downloads/comfyanonymous/ComfyUI/total?style=flat
28
+ [github-downloads-latest-shield]: https://img.shields.io/github/downloads/comfyanonymous/ComfyUI/latest/total?style=flat&label=downloads%40latest
29
+ [github-downloads-link]: https://github.com/comfyanonymous/ComfyUI/releases
30
+
31
+ ![ComfyUI Screenshot](comfyui_screenshot.png)
32
+ </div>
33
+
34
+ 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:
35
+ ### [ComfyUI Examples](https://comfyanonymous.github.io/ComfyUI_examples/)
36
+
37
+ ### [Installing ComfyUI](#installing)
38
+
39
+ ## Features
40
+ - Nodes/graph/flowchart interface to experiment and create complex Stable Diffusion workflows without needing to code anything.
41
+ - Fully supports SD1.x, SD2.x, [SDXL](https://comfyanonymous.github.io/ComfyUI_examples/sdxl/), [Stable Video Diffusion](https://comfyanonymous.github.io/ComfyUI_examples/video/), [Stable Cascade](https://comfyanonymous.github.io/ComfyUI_examples/stable_cascade/), [SD3](https://comfyanonymous.github.io/ComfyUI_examples/sd3/) and [Stable Audio](https://comfyanonymous.github.io/ComfyUI_examples/audio/)
42
+ - [Flux](https://comfyanonymous.github.io/ComfyUI_examples/flux/)
43
+ - Asynchronous Queue system
44
+ - Many optimizations: Only re-executes the parts of the workflow that changes between executions.
45
+ - Smart memory management: can automatically run models on GPUs with as low as 1GB vram.
46
+ - Works even if you don't have a GPU with: ```--cpu``` (slow)
47
+ - Can load ckpt, safetensors and diffusers models/checkpoints. Standalone VAEs and CLIP models.
48
+ - Embeddings/Textual inversion
49
+ - [Loras (regular, locon and loha)](https://comfyanonymous.github.io/ComfyUI_examples/lora/)
50
+ - [Hypernetworks](https://comfyanonymous.github.io/ComfyUI_examples/hypernetworks/)
51
+ - Loading full workflows (with seeds) from generated PNG, WebP and FLAC files.
52
+ - Saving/Loading workflows as Json files.
53
+ - 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.
54
+ - [Area Composition](https://comfyanonymous.github.io/ComfyUI_examples/area_composition/)
55
+ - [Inpainting](https://comfyanonymous.github.io/ComfyUI_examples/inpaint/) with both regular and inpainting models.
56
+ - [ControlNet and T2I-Adapter](https://comfyanonymous.github.io/ComfyUI_examples/controlnet/)
57
+ - [Upscale Models (ESRGAN, ESRGAN variants, SwinIR, Swin2SR, etc...)](https://comfyanonymous.github.io/ComfyUI_examples/upscale_models/)
58
+ - [unCLIP Models](https://comfyanonymous.github.io/ComfyUI_examples/unclip/)
59
+ - [GLIGEN](https://comfyanonymous.github.io/ComfyUI_examples/gligen/)
60
+ - [Model Merging](https://comfyanonymous.github.io/ComfyUI_examples/model_merging/)
61
+ - [LCM models and Loras](https://comfyanonymous.github.io/ComfyUI_examples/lcm/)
62
+ - [SDXL Turbo](https://comfyanonymous.github.io/ComfyUI_examples/sdturbo/)
63
+ - [AuraFlow](https://comfyanonymous.github.io/ComfyUI_examples/aura_flow/)
64
+ - [HunyuanDiT](https://comfyanonymous.github.io/ComfyUI_examples/hunyuan_dit/)
65
+ - Latent previews with [TAESD](#how-to-show-high-quality-previews)
66
+ - Starts up very fast.
67
+ - Works fully offline: will never download anything.
68
+ - [Config file](extra_model_paths.yaml.example) to set the search paths for models.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
+ Workflow examples can be found on the [Examples page](https://comfyanonymous.github.io/ComfyUI_examples/)
 
 
 
 
 
 
 
71
 
72
+ ## Shortcuts
73
+
74
+ | Keybind | Explanation |
75
+ |------------------------------------|--------------------------------------------------------------------------------------------------------------------|
76
+ | Ctrl + Enter | Queue up current graph for generation |
77
+ | Ctrl + Shift + Enter | Queue up current graph as first for generation |
78
+ | Ctrl + Alt + Enter | Cancel current generation |
79
+ | Ctrl + Z/Ctrl + Y | Undo/Redo |
80
+ | Ctrl + S | Save workflow |
81
+ | Ctrl + O | Load workflow |
82
+ | Ctrl + A | Select all nodes |
83
+ | Alt + C | Collapse/uncollapse selected nodes |
84
+ | Ctrl + M | Mute/unmute selected nodes |
85
+ | Ctrl + B | Bypass selected nodes (acts like the node was removed from the graph and the wires reconnected through) |
86
+ | Delete/Backspace | Delete selected nodes |
87
+ | Ctrl + Backspace | Delete the current graph |
88
+ | Space | Move the canvas around when held and moving the cursor |
89
+ | Ctrl/Shift + Click | Add clicked node to selection |
90
+ | Ctrl + C/Ctrl + V | Copy and paste selected nodes (without maintaining connections to outputs of unselected nodes) |
91
+ | Ctrl + C/Ctrl + Shift + V | Copy and paste selected nodes (maintaining connections from outputs of unselected nodes to inputs of pasted nodes) |
92
+ | Shift + Drag | Move multiple selected nodes at the same time |
93
+ | Ctrl + D | Load default graph |
94
+ | Alt + `+` | Canvas Zoom in |
95
+ | Alt + `-` | Canvas Zoom out |
96
+ | Ctrl + Shift + LMB + Vertical drag | Canvas Zoom in/out |
97
+ | P | Pin/Unpin selected nodes |
98
+ | Ctrl + G | Group selected nodes |
99
+ | Q | Toggle visibility of the queue |
100
+ | H | Toggle visibility of history |
101
+ | R | Refresh graph |
102
+ | Double-Click LMB | Open node quick search palette |
103
+ | Shift + Drag | Move multiple wires at once |
104
+ | Ctrl + Alt + LMB | Disconnect all wires from clicked slot |
105
+
106
+ Ctrl can also be replaced with Cmd instead for macOS users
107
+
108
+ # Installing
109
+
110
+ ## Windows
111
+
112
+ 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).
113
+
114
+ ### [Direct link to download](https://github.com/comfyanonymous/ComfyUI/releases/latest/download/ComfyUI_windows_portable_nvidia.7z)
115
+
116
+ 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
117
+
118
+ If you have trouble extracting it, right click the file -> properties -> unblock
119
+
120
+ #### How do I share models between another UI and ComfyUI?
121
+
122
+ 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.
123
+
124
+ ## Jupyter Notebook
125
+
126
+ To run it on services like paperspace, kaggle or colab you can use my [Jupyter Notebook](notebooks/comfyui_colab.ipynb)
127
+
128
+ ## Manual Install (Windows, Linux)
129
+
130
+ Git clone this repo.
131
+
132
+ Put your SD checkpoints (the huge ckpt/safetensors files) in: models/checkpoints
133
+
134
+ Put your VAE in: models/vae
135
+
136
+
137
+ ### AMD GPUs (Linux only)
138
+ 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:
139
+
140
+ ```pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm6.1```
141
+
142
+ This is the command to install the nightly with ROCm 6.2 which might have some performance improvements:
143
+
144
+ ```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.2```
145
+
146
+ ### NVIDIA
147
+
148
+ Nvidia users should install stable pytorch using this command:
149
+
150
+ ```pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu124```
151
+
152
+ This is the command to install pytorch nightly instead which might have performance improvements:
153
+
154
+ ```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cu124```
155
+
156
+ #### Troubleshooting
157
+
158
+ If you get the "Torch not compiled with CUDA enabled" error, uninstall torch with:
159
+
160
+ ```pip uninstall torch```
161
+
162
+ And install it again with the command above.
163
+
164
+ ### Dependencies
165
+
166
+ Install the dependencies by opening your terminal inside the ComfyUI folder and:
167
+
168
+ ```pip install -r requirements.txt```
169
+
170
+ After this you should have everything installed and can proceed to running ComfyUI.
171
+
172
+ ### Others:
173
+
174
+ #### Intel GPUs
175
+
176
+ Intel GPU support is available for all Intel GPUs supported by Intel's Extension for Pytorch (IPEX) with the support requirements listed in the [Installation](https://intel.github.io/intel-extension-for-pytorch/index.html#installation?platform=gpu) page. Choose your platform and method of install and follow the instructions. The steps are as follows:
177
+
178
+ 1. Start by installing the drivers or kernel listed or newer in the Installation page of IPEX linked above for Windows and Linux if needed.
179
+ 1. Follow the instructions to install [Intel's oneAPI Basekit](https://www.intel.com/content/www/us/en/developer/tools/oneapi/base-toolkit-download.html) for your platform.
180
+ 1. Install the packages for IPEX using the instructions provided in the Installation page for your platform.
181
+ 1. Follow the [ComfyUI manual installation](#manual-install-windows-linux) instructions for Windows and Linux and run ComfyUI normally as described above after everything is installed.
182
+
183
+ Additional discussion and help can be found [here](https://github.com/comfyanonymous/ComfyUI/discussions/476).
184
+
185
+ #### Apple Mac silicon
186
+
187
+ You can install ComfyUI in Apple Mac silicon (M1 or M2) with any recent macOS version.
188
+
189
+ 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).
190
+ 1. Follow the [ComfyUI manual installation](#manual-install-windows-linux) instructions for Windows and Linux.
191
+ 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).
192
+ 1. Launch ComfyUI by running `python main.py`
193
 
194
+ > **Note**: Remember to add your models, VAE, LoRAs etc. to the corresponding Comfy folders, as discussed in [ComfyUI manual installation](#manual-install-windows-linux).
 
 
195
 
196
+ #### DirectML (AMD Cards on Windows)
 
197
 
198
+ ```pip install torch-directml``` Then you can launch ComfyUI with: ```python main.py --directml```
 
 
199
 
200
+ # Running
201
+
202
+ ```python main.py```
203
+
204
+ ### For AMD cards not officially supported by ROCm
205
+
206
+ Try running it with this command if you have issues:
207
+
208
+ For 6700, 6600 and maybe other RDNA2 or older: ```HSA_OVERRIDE_GFX_VERSION=10.3.0 python main.py```
209
+
210
+ For AMD 7600 and maybe other RDNA3 cards: ```HSA_OVERRIDE_GFX_VERSION=11.0.0 python main.py```
211
+
212
+ # Notes
213
+
214
+ Only parts of the graph that have an output with all the correct inputs will be executed.
215
+
216
+ 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.
217
+
218
+ Dragging a generated png on the webpage or loading one will give you the full workflow including seeds that were used to create it.
219
+
220
+ 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 \\).
221
+
222
+ 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 \\}.
223
+
224
+ Dynamic prompts also support C-style comments, like `// comment` or `/* comment */`.
225
+
226
+ 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):
227
+
228
+ ```embedding:embedding_filename.pt```
229
+
230
+
231
+ ## How to show high-quality previews?
232
+
233
+ Use ```--preview-method auto``` to enable previews.
234
+
235
+ 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, taesdxl_decoder.pth, taesd3_decoder.pth and taef1_decoder.pth](https://github.com/madebyollin/taesd/) and place them in the `models/vae_approx` folder. Once they're installed, restart ComfyUI and launch it with `--preview-method taesd` to enable high-quality previews.
236
+
237
+ ## How to use TLS/SSL?
238
+ Generate a self-signed certificate (not appropriate for shared/production use) and key by running the command: `openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -sha256 -days 3650 -nodes -subj "/C=XX/ST=StateName/L=CityName/O=CompanyName/OU=CompanySectionName/CN=CommonNameOrHostname"`
239
+
240
+ Use `--tls-keyfile key.pem --tls-certfile cert.pem` to enable TLS/SSL, the app will now be accessible with `https://...` instead of `http://...`.
241
+
242
+ > Note: Windows users can use [alexisrolland/docker-openssl](https://github.com/alexisrolland/docker-openssl) or one of the [3rd party binary distributions](https://wiki.openssl.org/index.php/Binaries) to run the command example above.
243
+ <br/><br/>If you use a container, note that the volume mount `-v` can be a relative path so `... -v ".\:/openssl-certs" ...` would create the key & cert files in the current directory of your command prompt or powershell terminal.
244
+
245
+ ## Support and dev channel
246
+
247
+ [Matrix space: #comfyui_space:matrix.org](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) (it's like discord but open source).
248
+
249
+ See also: [https://www.comfy.org/](https://www.comfy.org/)
250
+
251
+ ## Frontend Development
252
+
253
+ As of August 15, 2024, we have transitioned to a new frontend, which is now hosted in a separate repository: [ComfyUI Frontend](https://github.com/Comfy-Org/ComfyUI_frontend). This repository now hosts the compiled JS (from TS/Vue) under the `web/` directory.
254
+
255
+ ### Reporting Issues and Requesting Features
256
+
257
+ For any bugs, issues, or feature requests related to the frontend, please use the [ComfyUI Frontend repository](https://github.com/Comfy-Org/ComfyUI_frontend). This will help us manage and address frontend-specific concerns more efficiently.
258
+
259
+ ### Using the Latest Frontend
260
+
261
+ The new frontend is now the default for ComfyUI. However, please note:
262
+
263
+ 1. The frontend in the main ComfyUI repository is updated weekly.
264
+ 2. Daily releases are available in the separate frontend repository.
265
+
266
+ To use the most up-to-date frontend version:
267
+
268
+ 1. For the latest daily release, launch ComfyUI with this command line argument:
269
+
270
+ ```
271
+ --front-end-version Comfy-Org/ComfyUI_frontend@latest
272
+ ```
273
+
274
+ 2. For a specific version, replace `latest` with the desired version number:
275
+
276
+ ```
277
+ --front-end-version Comfy-Org/[email protected]
278
+ ```
279
+
280
+ This approach allows you to easily switch between the stable weekly release and the cutting-edge daily updates, or even specific versions for testing purposes.
281
+
282
+ ### Accessing the Legacy Frontend
283
+
284
+ If you need to use the legacy frontend for any reason, you can access it using the following command line argument:
285
+
286
+ ```
287
+ --front-end-version Comfy-Org/ComfyUI_legacy_frontend@latest
288
  ```
289
+
290
+ This will use a snapshot of the legacy frontend preserved in the [ComfyUI Legacy Frontend repository](https://github.com/Comfy-Org/ComfyUI_legacy_frontend).
291
+
292
+ # QA
293
+
294
+ ### Which GPU should I buy for this?
295
+
296
+ [See this page for some recommendations](https://github.com/comfyanonymous/ComfyUI/wiki/Which-GPU-should-I-buy-for-ComfyUI)
297
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
execution.py ADDED
@@ -0,0 +1,993 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import copy
3
+ import logging
4
+ import threading
5
+ import heapq
6
+ import time
7
+ import traceback
8
+ from enum import Enum
9
+ import inspect
10
+ from typing import List, Literal, NamedTuple, Optional
11
+
12
+ import torch
13
+ import nodes
14
+
15
+ import comfy.model_management
16
+ from comfy_execution.graph import get_input_info, ExecutionList, DynamicPrompt, ExecutionBlocker
17
+ from comfy_execution.graph_utils import is_link, GraphBuilder
18
+ from comfy_execution.caching import HierarchicalCache, LRUCache, CacheKeySetInputSignature, CacheKeySetID
19
+ from comfy.cli_args import args
20
+
21
+ class ExecutionResult(Enum):
22
+ SUCCESS = 0
23
+ FAILURE = 1
24
+ PENDING = 2
25
+
26
+ class DuplicateNodeError(Exception):
27
+ pass
28
+
29
+ class IsChangedCache:
30
+ def __init__(self, dynprompt, outputs_cache):
31
+ self.dynprompt = dynprompt
32
+ self.outputs_cache = outputs_cache
33
+ self.is_changed = {}
34
+
35
+ def get(self, node_id):
36
+ if node_id in self.is_changed:
37
+ return self.is_changed[node_id]
38
+
39
+ node = self.dynprompt.get_node(node_id)
40
+ class_type = node["class_type"]
41
+ class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
42
+ if not hasattr(class_def, "IS_CHANGED"):
43
+ self.is_changed[node_id] = False
44
+ return self.is_changed[node_id]
45
+
46
+ if "is_changed" in node:
47
+ self.is_changed[node_id] = node["is_changed"]
48
+ return self.is_changed[node_id]
49
+
50
+ # Intentionally do not use cached outputs here. We only want constants in IS_CHANGED
51
+ input_data_all, _ = get_input_data(node["inputs"], class_def, node_id, None)
52
+ try:
53
+ is_changed = _map_node_over_list(class_def, input_data_all, "IS_CHANGED")
54
+ node["is_changed"] = [None if isinstance(x, ExecutionBlocker) else x for x in is_changed]
55
+ except Exception as e:
56
+ logging.warning("WARNING: {}".format(e))
57
+ node["is_changed"] = float("NaN")
58
+ finally:
59
+ self.is_changed[node_id] = node["is_changed"]
60
+ return self.is_changed[node_id]
61
+
62
+ class CacheSet:
63
+ def __init__(self, lru_size=None):
64
+ if lru_size is None or lru_size == 0:
65
+ self.init_classic_cache()
66
+ else:
67
+ self.init_lru_cache(lru_size)
68
+ self.all = [self.outputs, self.ui, self.objects]
69
+
70
+ # Useful for those with ample RAM/VRAM -- allows experimenting without
71
+ # blowing away the cache every time
72
+ def init_lru_cache(self, cache_size):
73
+ self.outputs = LRUCache(CacheKeySetInputSignature, max_size=cache_size)
74
+ self.ui = LRUCache(CacheKeySetInputSignature, max_size=cache_size)
75
+ self.objects = HierarchicalCache(CacheKeySetID)
76
+
77
+ # Performs like the old cache -- dump data ASAP
78
+ def init_classic_cache(self):
79
+ self.outputs = HierarchicalCache(CacheKeySetInputSignature)
80
+ self.ui = HierarchicalCache(CacheKeySetInputSignature)
81
+ self.objects = HierarchicalCache(CacheKeySetID)
82
+
83
+ def recursive_debug_dump(self):
84
+ result = {
85
+ "outputs": self.outputs.recursive_debug_dump(),
86
+ "ui": self.ui.recursive_debug_dump(),
87
+ }
88
+ return result
89
+
90
+ def get_input_data(inputs, class_def, unique_id, outputs=None, dynprompt=None, extra_data={}):
91
+ valid_inputs = class_def.INPUT_TYPES()
92
+ input_data_all = {}
93
+ missing_keys = {}
94
+ for x in inputs:
95
+ input_data = inputs[x]
96
+ input_type, input_category, input_info = get_input_info(class_def, x)
97
+ def mark_missing():
98
+ missing_keys[x] = True
99
+ input_data_all[x] = (None,)
100
+ if is_link(input_data) and (not input_info or not input_info.get("rawLink", False)):
101
+ input_unique_id = input_data[0]
102
+ output_index = input_data[1]
103
+ if outputs is None:
104
+ mark_missing()
105
+ continue # This might be a lazily-evaluated input
106
+ cached_output = outputs.get(input_unique_id)
107
+ if cached_output is None:
108
+ mark_missing()
109
+ continue
110
+ if output_index >= len(cached_output):
111
+ mark_missing()
112
+ continue
113
+ obj = cached_output[output_index]
114
+ input_data_all[x] = obj
115
+ elif input_category is not None:
116
+ input_data_all[x] = [input_data]
117
+
118
+ if "hidden" in valid_inputs:
119
+ h = valid_inputs["hidden"]
120
+ for x in h:
121
+ if h[x] == "PROMPT":
122
+ input_data_all[x] = [dynprompt.get_original_prompt() if dynprompt is not None else {}]
123
+ if h[x] == "DYNPROMPT":
124
+ input_data_all[x] = [dynprompt]
125
+ if h[x] == "EXTRA_PNGINFO":
126
+ input_data_all[x] = [extra_data.get('extra_pnginfo', None)]
127
+ if h[x] == "UNIQUE_ID":
128
+ input_data_all[x] = [unique_id]
129
+ return input_data_all, missing_keys
130
+
131
+ map_node_over_list = None #Don't hook this please
132
+
133
+ def _map_node_over_list(obj, input_data_all, func, allow_interrupt=False, execution_block_cb=None, pre_execute_cb=None):
134
+ # check if node wants the lists
135
+ input_is_list = getattr(obj, "INPUT_IS_LIST", False)
136
+
137
+ if len(input_data_all) == 0:
138
+ max_len_input = 0
139
+ else:
140
+ max_len_input = max(len(x) for x in input_data_all.values())
141
+
142
+ # get a slice of inputs, repeat last input when list isn't long enough
143
+ def slice_dict(d, i):
144
+ return {k: v[i if len(v) > i else -1] for k, v in d.items()}
145
+
146
+ results = []
147
+ def process_inputs(inputs, index=None):
148
+ if allow_interrupt:
149
+ nodes.before_node_execution()
150
+ execution_block = None
151
+ for k, v in inputs.items():
152
+ if isinstance(v, ExecutionBlocker):
153
+ execution_block = execution_block_cb(v) if execution_block_cb else v
154
+ break
155
+ if execution_block is None:
156
+ if pre_execute_cb is not None and index is not None:
157
+ pre_execute_cb(index)
158
+ results.append(getattr(obj, func)(**inputs))
159
+ else:
160
+ results.append(execution_block)
161
+
162
+ if input_is_list:
163
+ process_inputs(input_data_all, 0)
164
+ elif max_len_input == 0:
165
+ process_inputs({})
166
+ else:
167
+ for i in range(max_len_input):
168
+ input_dict = slice_dict(input_data_all, i)
169
+ process_inputs(input_dict, i)
170
+ return results
171
+
172
+ def merge_result_data(results, obj):
173
+ # check which outputs need concatenating
174
+ output = []
175
+ output_is_list = [False] * len(results[0])
176
+ if hasattr(obj, "OUTPUT_IS_LIST"):
177
+ output_is_list = obj.OUTPUT_IS_LIST
178
+
179
+ # merge node execution results
180
+ for i, is_list in zip(range(len(results[0])), output_is_list):
181
+ if is_list:
182
+ value = []
183
+ for o in results:
184
+ if isinstance(o[i], ExecutionBlocker):
185
+ value.append(o[i])
186
+ else:
187
+ value.extend(o[i])
188
+ output.append(value)
189
+ else:
190
+ output.append([o[i] for o in results])
191
+ return output
192
+
193
+ def get_output_data(obj, input_data_all, execution_block_cb=None, pre_execute_cb=None):
194
+
195
+ results = []
196
+ uis = []
197
+ subgraph_results = []
198
+ return_values = _map_node_over_list(obj, input_data_all, obj.FUNCTION, allow_interrupt=True, execution_block_cb=execution_block_cb, pre_execute_cb=pre_execute_cb)
199
+ has_subgraph = False
200
+ for i in range(len(return_values)):
201
+ r = return_values[i]
202
+ if isinstance(r, dict):
203
+ if 'ui' in r:
204
+ uis.append(r['ui'])
205
+ if 'expand' in r:
206
+ # Perform an expansion, but do not append results
207
+ has_subgraph = True
208
+ new_graph = r['expand']
209
+ result = r.get("result", None)
210
+ if isinstance(result, ExecutionBlocker):
211
+ result = tuple([result] * len(obj.RETURN_TYPES))
212
+ subgraph_results.append((new_graph, result))
213
+ elif 'result' in r:
214
+ result = r.get("result", None)
215
+ if isinstance(result, ExecutionBlocker):
216
+ result = tuple([result] * len(obj.RETURN_TYPES))
217
+ results.append(result)
218
+ subgraph_results.append((None, result))
219
+ else:
220
+ if isinstance(r, ExecutionBlocker):
221
+ r = tuple([r] * len(obj.RETURN_TYPES))
222
+ results.append(r)
223
+ subgraph_results.append((None, r))
224
+
225
+ if has_subgraph:
226
+ output = subgraph_results
227
+ elif len(results) > 0:
228
+ output = merge_result_data(results, obj)
229
+ else:
230
+ output = []
231
+ ui = dict()
232
+ if len(uis) > 0:
233
+ ui = {k: [y for x in uis for y in x[k]] for k in uis[0].keys()}
234
+ return output, ui, has_subgraph
235
+
236
+ def format_value(x):
237
+ if x is None:
238
+ return None
239
+ elif isinstance(x, (int, float, bool, str)):
240
+ return x
241
+ else:
242
+ return str(x)
243
+
244
+ def execute(server, dynprompt, caches, current_item, extra_data, executed, prompt_id, execution_list, pending_subgraph_results):
245
+ unique_id = current_item
246
+ real_node_id = dynprompt.get_real_node_id(unique_id)
247
+ display_node_id = dynprompt.get_display_node_id(unique_id)
248
+ parent_node_id = dynprompt.get_parent_node_id(unique_id)
249
+ inputs = dynprompt.get_node(unique_id)['inputs']
250
+ class_type = dynprompt.get_node(unique_id)['class_type']
251
+ class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
252
+ if caches.outputs.get(unique_id) is not None:
253
+ if server.client_id is not None:
254
+ cached_output = caches.ui.get(unique_id) or {}
255
+ server.send_sync("executed", { "node": unique_id, "display_node": display_node_id, "output": cached_output.get("output",None), "prompt_id": prompt_id }, server.client_id)
256
+ return (ExecutionResult.SUCCESS, None, None)
257
+
258
+ input_data_all = None
259
+ try:
260
+ if unique_id in pending_subgraph_results:
261
+ cached_results = pending_subgraph_results[unique_id]
262
+ resolved_outputs = []
263
+ for is_subgraph, result in cached_results:
264
+ if not is_subgraph:
265
+ resolved_outputs.append(result)
266
+ else:
267
+ resolved_output = []
268
+ for r in result:
269
+ if is_link(r):
270
+ source_node, source_output = r[0], r[1]
271
+ node_output = caches.outputs.get(source_node)[source_output]
272
+ for o in node_output:
273
+ resolved_output.append(o)
274
+
275
+ else:
276
+ resolved_output.append(r)
277
+ resolved_outputs.append(tuple(resolved_output))
278
+ output_data = merge_result_data(resolved_outputs, class_def)
279
+ output_ui = []
280
+ has_subgraph = False
281
+ else:
282
+ input_data_all, missing_keys = get_input_data(inputs, class_def, unique_id, caches.outputs, dynprompt, extra_data)
283
+ if server.client_id is not None:
284
+ server.last_node_id = display_node_id
285
+ server.send_sync("executing", { "node": unique_id, "display_node": display_node_id, "prompt_id": prompt_id }, server.client_id)
286
+
287
+ obj = caches.objects.get(unique_id)
288
+ if obj is None:
289
+ obj = class_def()
290
+ caches.objects.set(unique_id, obj)
291
+
292
+ if hasattr(obj, "check_lazy_status"):
293
+ required_inputs = _map_node_over_list(obj, input_data_all, "check_lazy_status", allow_interrupt=True)
294
+ required_inputs = set(sum([r for r in required_inputs if isinstance(r,list)], []))
295
+ required_inputs = [x for x in required_inputs if isinstance(x,str) and (
296
+ x not in input_data_all or x in missing_keys
297
+ )]
298
+ if len(required_inputs) > 0:
299
+ for i in required_inputs:
300
+ execution_list.make_input_strong_link(unique_id, i)
301
+ return (ExecutionResult.PENDING, None, None)
302
+
303
+ def execution_block_cb(block):
304
+ if block.message is not None:
305
+ mes = {
306
+ "prompt_id": prompt_id,
307
+ "node_id": unique_id,
308
+ "node_type": class_type,
309
+ "executed": list(executed),
310
+
311
+ "exception_message": f"Execution Blocked: {block.message}",
312
+ "exception_type": "ExecutionBlocked",
313
+ "traceback": [],
314
+ "current_inputs": [],
315
+ "current_outputs": [],
316
+ }
317
+ server.send_sync("execution_error", mes, server.client_id)
318
+ return ExecutionBlocker(None)
319
+ else:
320
+ return block
321
+ def pre_execute_cb(call_index):
322
+ GraphBuilder.set_default_prefix(unique_id, call_index, 0)
323
+ output_data, output_ui, has_subgraph = get_output_data(obj, input_data_all, execution_block_cb=execution_block_cb, pre_execute_cb=pre_execute_cb)
324
+ if len(output_ui) > 0:
325
+ caches.ui.set(unique_id, {
326
+ "meta": {
327
+ "node_id": unique_id,
328
+ "display_node": display_node_id,
329
+ "parent_node": parent_node_id,
330
+ "real_node_id": real_node_id,
331
+ },
332
+ "output": output_ui
333
+ })
334
+ if server.client_id is not None:
335
+ server.send_sync("executed", { "node": unique_id, "display_node": display_node_id, "output": output_ui, "prompt_id": prompt_id }, server.client_id)
336
+ if has_subgraph:
337
+ cached_outputs = []
338
+ new_node_ids = []
339
+ new_output_ids = []
340
+ new_output_links = []
341
+ for i in range(len(output_data)):
342
+ new_graph, node_outputs = output_data[i]
343
+ if new_graph is None:
344
+ cached_outputs.append((False, node_outputs))
345
+ else:
346
+ # Check for conflicts
347
+ for node_id in new_graph.keys():
348
+ if dynprompt.has_node(node_id):
349
+ raise DuplicateNodeError(f"Attempt to add duplicate node {node_id}. Ensure node ids are unique and deterministic or use graph_utils.GraphBuilder.")
350
+ for node_id, node_info in new_graph.items():
351
+ new_node_ids.append(node_id)
352
+ display_id = node_info.get("override_display_id", unique_id)
353
+ dynprompt.add_ephemeral_node(node_id, node_info, unique_id, display_id)
354
+ # Figure out if the newly created node is an output node
355
+ class_type = node_info["class_type"]
356
+ class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
357
+ if hasattr(class_def, 'OUTPUT_NODE') and class_def.OUTPUT_NODE == True:
358
+ new_output_ids.append(node_id)
359
+ for i in range(len(node_outputs)):
360
+ if is_link(node_outputs[i]):
361
+ from_node_id, from_socket = node_outputs[i][0], node_outputs[i][1]
362
+ new_output_links.append((from_node_id, from_socket))
363
+ cached_outputs.append((True, node_outputs))
364
+ new_node_ids = set(new_node_ids)
365
+ for cache in caches.all:
366
+ cache.ensure_subcache_for(unique_id, new_node_ids).clean_unused()
367
+ for node_id in new_output_ids:
368
+ execution_list.add_node(node_id)
369
+ for link in new_output_links:
370
+ execution_list.add_strong_link(link[0], link[1], unique_id)
371
+ pending_subgraph_results[unique_id] = cached_outputs
372
+ return (ExecutionResult.PENDING, None, None)
373
+ caches.outputs.set(unique_id, output_data)
374
+ except comfy.model_management.InterruptProcessingException as iex:
375
+ logging.info("Processing interrupted")
376
+
377
+ # skip formatting inputs/outputs
378
+ error_details = {
379
+ "node_id": real_node_id,
380
+ }
381
+
382
+ return (ExecutionResult.FAILURE, error_details, iex)
383
+ except Exception as ex:
384
+ typ, _, tb = sys.exc_info()
385
+ exception_type = full_type_name(typ)
386
+ input_data_formatted = {}
387
+ if input_data_all is not None:
388
+ input_data_formatted = {}
389
+ for name, inputs in input_data_all.items():
390
+ input_data_formatted[name] = [format_value(x) for x in inputs]
391
+
392
+ logging.error(f"!!! Exception during processing !!! {ex}")
393
+ logging.error(traceback.format_exc())
394
+
395
+ error_details = {
396
+ "node_id": real_node_id,
397
+ "exception_message": str(ex),
398
+ "exception_type": exception_type,
399
+ "traceback": traceback.format_tb(tb),
400
+ "current_inputs": input_data_formatted
401
+ }
402
+ if isinstance(ex, comfy.model_management.OOM_EXCEPTION):
403
+ logging.error("Got an OOM, unloading all loaded models.")
404
+ comfy.model_management.unload_all_models()
405
+
406
+ return (ExecutionResult.FAILURE, error_details, ex)
407
+
408
+ executed.add(unique_id)
409
+
410
+ return (ExecutionResult.SUCCESS, None, None)
411
+
412
+ class PromptExecutor:
413
+ def __init__(self, server, lru_size=None):
414
+ self.lru_size = lru_size
415
+ self.server = server
416
+ self.reset()
417
+
418
+ def reset(self):
419
+ self.caches = CacheSet(self.lru_size)
420
+ self.status_messages = []
421
+ self.success = True
422
+
423
+ def add_message(self, event, data: dict, broadcast: bool):
424
+ data = {
425
+ **data,
426
+ "timestamp": int(time.time() * 1000),
427
+ }
428
+ self.status_messages.append((event, data))
429
+ if self.server.client_id is not None or broadcast:
430
+ self.server.send_sync(event, data, self.server.client_id)
431
+
432
+ def handle_execution_error(self, prompt_id, prompt, current_outputs, executed, error, ex):
433
+ node_id = error["node_id"]
434
+ class_type = prompt[node_id]["class_type"]
435
+
436
+ # First, send back the status to the frontend depending
437
+ # on the exception type
438
+ if isinstance(ex, comfy.model_management.InterruptProcessingException):
439
+ mes = {
440
+ "prompt_id": prompt_id,
441
+ "node_id": node_id,
442
+ "node_type": class_type,
443
+ "executed": list(executed),
444
+ }
445
+ self.add_message("execution_interrupted", mes, broadcast=True)
446
+ else:
447
+ mes = {
448
+ "prompt_id": prompt_id,
449
+ "node_id": node_id,
450
+ "node_type": class_type,
451
+ "executed": list(executed),
452
+ "exception_message": error["exception_message"],
453
+ "exception_type": error["exception_type"],
454
+ "traceback": error["traceback"],
455
+ "current_inputs": error["current_inputs"],
456
+ "current_outputs": list(current_outputs),
457
+ }
458
+ self.add_message("execution_error", mes, broadcast=False)
459
+
460
+ def execute(self, prompt, prompt_id, extra_data={}, execute_outputs=[]):
461
+ nodes.interrupt_processing(False)
462
+
463
+ if "client_id" in extra_data:
464
+ self.server.client_id = extra_data["client_id"]
465
+ else:
466
+ self.server.client_id = None
467
+
468
+ self.status_messages = []
469
+ self.add_message("execution_start", { "prompt_id": prompt_id}, broadcast=False)
470
+
471
+ comfy.model_management.print_memory_info()
472
+ with torch.inference_mode():
473
+ dynamic_prompt = DynamicPrompt(prompt)
474
+ is_changed_cache = IsChangedCache(dynamic_prompt, self.caches.outputs)
475
+ for cache in self.caches.all:
476
+ cache.set_prompt(dynamic_prompt, prompt.keys(), is_changed_cache)
477
+ cache.clean_unused()
478
+
479
+ cached_nodes = []
480
+ for node_id in prompt:
481
+ if self.caches.outputs.get(node_id) is not None:
482
+ cached_nodes.append(node_id)
483
+
484
+ comfy.model_management.cleanup_models(keep_clone_weights_loaded=True)
485
+ self.add_message("execution_cached",
486
+ { "nodes": cached_nodes, "prompt_id": prompt_id},
487
+ broadcast=False)
488
+ pending_subgraph_results = {}
489
+ executed = set()
490
+ execution_list = ExecutionList(dynamic_prompt, self.caches.outputs)
491
+ current_outputs = self.caches.outputs.all_node_ids()
492
+ for node_id in list(execute_outputs):
493
+ execution_list.add_node(node_id)
494
+
495
+ while not execution_list.is_empty():
496
+ node_id, error, ex = execution_list.stage_node_execution()
497
+ if error is not None:
498
+ self.handle_execution_error(prompt_id, dynamic_prompt.original_prompt, current_outputs, executed, error, ex)
499
+ break
500
+
501
+ result, error, ex = execute(self.server, dynamic_prompt, self.caches, node_id, extra_data, executed, prompt_id, execution_list, pending_subgraph_results)
502
+ self.success = result != ExecutionResult.FAILURE
503
+ if result == ExecutionResult.FAILURE:
504
+ self.handle_execution_error(prompt_id, dynamic_prompt.original_prompt, current_outputs, executed, error, ex)
505
+ break
506
+ elif result == ExecutionResult.PENDING:
507
+ execution_list.unstage_node_execution()
508
+ else: # result == ExecutionResult.SUCCESS:
509
+ execution_list.complete_node_execution()
510
+ else:
511
+ # Only execute when the while-loop ends without break
512
+ self.add_message("execution_success", { "prompt_id": prompt_id }, broadcast=False)
513
+
514
+ ui_outputs = {}
515
+ meta_outputs = {}
516
+ all_node_ids = self.caches.ui.all_node_ids()
517
+ for node_id in all_node_ids:
518
+ ui_info = self.caches.ui.get(node_id)
519
+ if ui_info is not None:
520
+ ui_outputs[node_id] = ui_info["output"]
521
+ meta_outputs[node_id] = ui_info["meta"]
522
+ self.history_result = {
523
+ "outputs": ui_outputs,
524
+ "meta": meta_outputs,
525
+ }
526
+ self.server.last_node_id = None
527
+ if comfy.model_management.DISABLE_SMART_MEMORY:
528
+ comfy.model_management.unload_all_models()
529
+ comfy.model_management.print_memory_info()
530
+
531
+
532
+
533
+ def validate_inputs(prompt, item, validated):
534
+ unique_id = item
535
+ if unique_id in validated:
536
+ return validated[unique_id]
537
+
538
+ inputs = prompt[unique_id]['inputs']
539
+ class_type = prompt[unique_id]['class_type']
540
+ obj_class = nodes.NODE_CLASS_MAPPINGS[class_type]
541
+
542
+ class_inputs = obj_class.INPUT_TYPES()
543
+ valid_inputs = set(class_inputs.get('required',{})).union(set(class_inputs.get('optional',{})))
544
+
545
+ errors = []
546
+ valid = True
547
+
548
+ validate_function_inputs = []
549
+ validate_has_kwargs = False
550
+ if hasattr(obj_class, "VALIDATE_INPUTS"):
551
+ argspec = inspect.getfullargspec(obj_class.VALIDATE_INPUTS)
552
+ validate_function_inputs = argspec.args
553
+ validate_has_kwargs = argspec.varkw is not None
554
+ received_types = {}
555
+
556
+ for x in valid_inputs:
557
+ type_input, input_category, extra_info = get_input_info(obj_class, x)
558
+ assert extra_info is not None
559
+ if x not in inputs:
560
+ if input_category == "required":
561
+ error = {
562
+ "type": "required_input_missing",
563
+ "message": "Required input is missing",
564
+ "details": f"{x}",
565
+ "extra_info": {
566
+ "input_name": x
567
+ }
568
+ }
569
+ errors.append(error)
570
+ continue
571
+
572
+ val = inputs[x]
573
+ info = (type_input, extra_info)
574
+ if isinstance(val, list):
575
+ if len(val) != 2:
576
+ error = {
577
+ "type": "bad_linked_input",
578
+ "message": "Bad linked input, must be a length-2 list of [node_id, slot_index]",
579
+ "details": f"{x}",
580
+ "extra_info": {
581
+ "input_name": x,
582
+ "input_config": info,
583
+ "received_value": val
584
+ }
585
+ }
586
+ errors.append(error)
587
+ continue
588
+
589
+ o_id = val[0]
590
+ o_class_type = prompt[o_id]['class_type']
591
+ r = nodes.NODE_CLASS_MAPPINGS[o_class_type].RETURN_TYPES
592
+ received_type = r[val[1]]
593
+ received_types[x] = received_type
594
+ if 'input_types' not in validate_function_inputs and received_type != type_input:
595
+ details = f"{x}, {received_type} != {type_input}"
596
+ error = {
597
+ "type": "return_type_mismatch",
598
+ "message": "Return type mismatch between linked nodes",
599
+ "details": details,
600
+ "extra_info": {
601
+ "input_name": x,
602
+ "input_config": info,
603
+ "received_type": received_type,
604
+ "linked_node": val
605
+ }
606
+ }
607
+ errors.append(error)
608
+ continue
609
+ try:
610
+ r = validate_inputs(prompt, o_id, validated)
611
+ if r[0] is False:
612
+ # `r` will be set in `validated[o_id]` already
613
+ valid = False
614
+ continue
615
+ except Exception as ex:
616
+ typ, _, tb = sys.exc_info()
617
+ valid = False
618
+ exception_type = full_type_name(typ)
619
+ reasons = [{
620
+ "type": "exception_during_inner_validation",
621
+ "message": "Exception when validating inner node",
622
+ "details": str(ex),
623
+ "extra_info": {
624
+ "input_name": x,
625
+ "input_config": info,
626
+ "exception_message": str(ex),
627
+ "exception_type": exception_type,
628
+ "traceback": traceback.format_tb(tb),
629
+ "linked_node": val
630
+ }
631
+ }]
632
+ validated[o_id] = (False, reasons, o_id)
633
+ continue
634
+ else:
635
+ try:
636
+ if type_input == "INT":
637
+ val = int(val)
638
+ inputs[x] = val
639
+ if type_input == "FLOAT":
640
+ val = float(val)
641
+ inputs[x] = val
642
+ if type_input == "STRING":
643
+ val = str(val)
644
+ inputs[x] = val
645
+ if type_input == "BOOLEAN":
646
+ val = bool(val)
647
+ inputs[x] = val
648
+ except Exception as ex:
649
+ error = {
650
+ "type": "invalid_input_type",
651
+ "message": f"Failed to convert an input value to a {type_input} value",
652
+ "details": f"{x}, {val}, {ex}",
653
+ "extra_info": {
654
+ "input_name": x,
655
+ "input_config": info,
656
+ "received_value": val,
657
+ "exception_message": str(ex)
658
+ }
659
+ }
660
+ errors.append(error)
661
+ continue
662
+
663
+ if x not in validate_function_inputs and not validate_has_kwargs:
664
+ if "min" in extra_info and val < extra_info["min"]:
665
+ error = {
666
+ "type": "value_smaller_than_min",
667
+ "message": "Value {} smaller than min of {}".format(val, extra_info["min"]),
668
+ "details": f"{x}",
669
+ "extra_info": {
670
+ "input_name": x,
671
+ "input_config": info,
672
+ "received_value": val,
673
+ }
674
+ }
675
+ errors.append(error)
676
+ continue
677
+ if "max" in extra_info and val > extra_info["max"]:
678
+ error = {
679
+ "type": "value_bigger_than_max",
680
+ "message": "Value {} bigger than max of {}".format(val, extra_info["max"]),
681
+ "details": f"{x}",
682
+ "extra_info": {
683
+ "input_name": x,
684
+ "input_config": info,
685
+ "received_value": val,
686
+ }
687
+ }
688
+ errors.append(error)
689
+ continue
690
+
691
+ if isinstance(type_input, list):
692
+ if val not in type_input:
693
+ input_config = info
694
+ list_info = ""
695
+
696
+ # Don't send back gigantic lists like if they're lots of
697
+ # scanned model filepaths
698
+ if len(type_input) > 20:
699
+ list_info = f"(list of length {len(type_input)})"
700
+ input_config = None
701
+ else:
702
+ list_info = str(type_input)
703
+
704
+ error = {
705
+ "type": "value_not_in_list",
706
+ "message": "Value not in list",
707
+ "details": f"{x}: '{val}' not in {list_info}",
708
+ "extra_info": {
709
+ "input_name": x,
710
+ "input_config": input_config,
711
+ "received_value": val,
712
+ }
713
+ }
714
+ errors.append(error)
715
+ continue
716
+
717
+ if len(validate_function_inputs) > 0 or validate_has_kwargs:
718
+ input_data_all, _ = get_input_data(inputs, obj_class, unique_id)
719
+ input_filtered = {}
720
+ for x in input_data_all:
721
+ if x in validate_function_inputs or validate_has_kwargs:
722
+ input_filtered[x] = input_data_all[x]
723
+ if 'input_types' in validate_function_inputs:
724
+ input_filtered['input_types'] = [received_types]
725
+
726
+ #ret = obj_class.VALIDATE_INPUTS(**input_filtered)
727
+ ret = _map_node_over_list(obj_class, input_filtered, "VALIDATE_INPUTS")
728
+ for x in input_filtered:
729
+ for i, r in enumerate(ret):
730
+ if r is not True and not isinstance(r, ExecutionBlocker):
731
+ details = f"{x}"
732
+ if r is not False:
733
+ details += f" - {str(r)}"
734
+
735
+ error = {
736
+ "type": "custom_validation_failed",
737
+ "message": "Custom validation failed for node",
738
+ "details": details,
739
+ "extra_info": {
740
+ "input_name": x,
741
+ }
742
+ }
743
+ errors.append(error)
744
+ continue
745
+
746
+ if len(errors) > 0 or valid is not True:
747
+ ret = (False, errors, unique_id)
748
+ else:
749
+ ret = (True, [], unique_id)
750
+
751
+ validated[unique_id] = ret
752
+ return ret
753
+
754
+ def full_type_name(klass):
755
+ module = klass.__module__
756
+ if module == 'builtins':
757
+ return klass.__qualname__
758
+ return module + '.' + klass.__qualname__
759
+
760
+ def validate_prompt(prompt):
761
+ outputs = set()
762
+ for x in prompt:
763
+ if 'class_type' not in prompt[x]:
764
+ error = {
765
+ "type": "invalid_prompt",
766
+ "message": f"Cannot execute because a node is missing the class_type property.",
767
+ "details": f"Node ID '#{x}'",
768
+ "extra_info": {}
769
+ }
770
+ return (False, error, [], [])
771
+
772
+ class_type = prompt[x]['class_type']
773
+ class_ = nodes.NODE_CLASS_MAPPINGS.get(class_type, None)
774
+ if class_ is None:
775
+ error = {
776
+ "type": "invalid_prompt",
777
+ "message": f"Cannot execute because node {class_type} does not exist.",
778
+ "details": f"Node ID '#{x}'",
779
+ "extra_info": {}
780
+ }
781
+ return (False, error, [], [])
782
+
783
+ if hasattr(class_, 'OUTPUT_NODE') and class_.OUTPUT_NODE is True:
784
+ outputs.add(x)
785
+
786
+ if len(outputs) == 0:
787
+ error = {
788
+ "type": "prompt_no_outputs",
789
+ "message": "Prompt has no outputs",
790
+ "details": "",
791
+ "extra_info": {}
792
+ }
793
+ return (False, error, [], [])
794
+
795
+ good_outputs = set()
796
+ errors = []
797
+ node_errors = {}
798
+ validated = {}
799
+ for o in outputs:
800
+ valid = False
801
+ reasons = []
802
+ try:
803
+ m = validate_inputs(prompt, o, validated)
804
+ valid = m[0]
805
+ reasons = m[1]
806
+ except Exception as ex:
807
+ typ, _, tb = sys.exc_info()
808
+ valid = False
809
+ exception_type = full_type_name(typ)
810
+ reasons = [{
811
+ "type": "exception_during_validation",
812
+ "message": "Exception when validating node",
813
+ "details": str(ex),
814
+ "extra_info": {
815
+ "exception_type": exception_type,
816
+ "traceback": traceback.format_tb(tb)
817
+ }
818
+ }]
819
+ validated[o] = (False, reasons, o)
820
+
821
+ if valid is True:
822
+ good_outputs.add(o)
823
+ else:
824
+ logging.error(f"Failed to validate prompt for output {o}:")
825
+ if len(reasons) > 0:
826
+ logging.error("* (prompt):")
827
+ for reason in reasons:
828
+ logging.error(f" - {reason['message']}: {reason['details']}")
829
+ errors += [(o, reasons)]
830
+ for node_id, result in validated.items():
831
+ valid = result[0]
832
+ reasons = result[1]
833
+ # If a node upstream has errors, the nodes downstream will also
834
+ # be reported as invalid, but there will be no errors attached.
835
+ # So don't return those nodes as having errors in the response.
836
+ if valid is not True and len(reasons) > 0:
837
+ if node_id not in node_errors:
838
+ class_type = prompt[node_id]['class_type']
839
+ node_errors[node_id] = {
840
+ "errors": reasons,
841
+ "dependent_outputs": [],
842
+ "class_type": class_type
843
+ }
844
+ logging.error(f"* {class_type} {node_id}:")
845
+ for reason in reasons:
846
+ logging.error(f" - {reason['message']}: {reason['details']}")
847
+ node_errors[node_id]["dependent_outputs"].append(o)
848
+ logging.error("Output will be ignored")
849
+
850
+ if len(good_outputs) == 0:
851
+ errors_list = []
852
+ for o, errors in errors:
853
+ for error in errors:
854
+ errors_list.append(f"{error['message']}: {error['details']}")
855
+ errors_list = "\n".join(errors_list)
856
+
857
+ error = {
858
+ "type": "prompt_outputs_failed_validation",
859
+ "message": "Prompt outputs failed validation",
860
+ "details": errors_list,
861
+ "extra_info": {}
862
+ }
863
+
864
+ return (False, error, list(good_outputs), node_errors)
865
+
866
+ return (True, None, list(good_outputs), node_errors)
867
+
868
+ MAXIMUM_HISTORY_SIZE = 10000
869
+
870
+ class PromptQueue:
871
+ def __init__(self, server):
872
+ self.server = server
873
+ self.mutex = threading.RLock()
874
+ self.not_empty = threading.Condition(self.mutex)
875
+ self.task_counter = 0
876
+ self.queue = []
877
+ self.currently_running = {}
878
+ self.history = {}
879
+ self.flags = {}
880
+ server.prompt_queue = self
881
+
882
+ def put(self, item):
883
+ with self.mutex:
884
+ heapq.heappush(self.queue, item)
885
+ self.server.queue_updated()
886
+ self.not_empty.notify()
887
+
888
+ def get(self, timeout=None):
889
+ with self.not_empty:
890
+ while len(self.queue) == 0:
891
+ self.not_empty.wait(timeout=timeout)
892
+ if timeout is not None and len(self.queue) == 0:
893
+ return None
894
+ item = heapq.heappop(self.queue)
895
+ i = self.task_counter
896
+ self.currently_running[i] = copy.deepcopy(item)
897
+ self.task_counter += 1
898
+ self.server.queue_updated()
899
+ return (item, i)
900
+
901
+ class ExecutionStatus(NamedTuple):
902
+ status_str: Literal['success', 'error']
903
+ completed: bool
904
+ messages: List[str]
905
+
906
+ def task_done(self, item_id, history_result,
907
+ status: Optional['PromptQueue.ExecutionStatus']):
908
+ with self.mutex:
909
+ prompt = self.currently_running.pop(item_id)
910
+ if len(self.history) > MAXIMUM_HISTORY_SIZE:
911
+ self.history.pop(next(iter(self.history)))
912
+
913
+ status_dict: Optional[dict] = None
914
+ if status is not None:
915
+ status_dict = copy.deepcopy(status._asdict())
916
+
917
+ self.history[prompt[1]] = {
918
+ "prompt": prompt,
919
+ "outputs": {},
920
+ 'status': status_dict,
921
+ }
922
+ self.history[prompt[1]].update(history_result)
923
+ self.server.queue_updated()
924
+
925
+ def get_current_queue(self):
926
+ with self.mutex:
927
+ out = []
928
+ for x in self.currently_running.values():
929
+ out += [x]
930
+ return (out, copy.deepcopy(self.queue))
931
+
932
+ def get_tasks_remaining(self):
933
+ with self.mutex:
934
+ return len(self.queue) + len(self.currently_running)
935
+
936
+ def wipe_queue(self):
937
+ with self.mutex:
938
+ self.queue = []
939
+ self.server.queue_updated()
940
+
941
+ def delete_queue_item(self, function):
942
+ with self.mutex:
943
+ for x in range(len(self.queue)):
944
+ if function(self.queue[x]):
945
+ if len(self.queue) == 1:
946
+ self.wipe_queue()
947
+ else:
948
+ self.queue.pop(x)
949
+ heapq.heapify(self.queue)
950
+ self.server.queue_updated()
951
+ return True
952
+ return False
953
+
954
+ def get_history(self, prompt_id=None, max_items=None, offset=-1):
955
+ with self.mutex:
956
+ if prompt_id is None:
957
+ out = {}
958
+ i = 0
959
+ if offset < 0 and max_items is not None:
960
+ offset = len(self.history) - max_items
961
+ for k in self.history:
962
+ if i >= offset:
963
+ out[k] = self.history[k]
964
+ if max_items is not None and len(out) >= max_items:
965
+ break
966
+ i += 1
967
+ return out
968
+ elif prompt_id in self.history:
969
+ return {prompt_id: copy.deepcopy(self.history[prompt_id])}
970
+ else:
971
+ return {}
972
+
973
+ def wipe_history(self):
974
+ with self.mutex:
975
+ self.history = {}
976
+
977
+ def delete_history_item(self, id_to_delete):
978
+ with self.mutex:
979
+ self.history.pop(id_to_delete, None)
980
+
981
+ def set_flag(self, name, data):
982
+ with self.mutex:
983
+ self.flags[name] = data
984
+ self.not_empty.notify()
985
+
986
+ def get_flags(self, reset=True):
987
+ with self.mutex:
988
+ if reset:
989
+ ret = self.flags
990
+ self.flags = {}
991
+ return ret
992
+ else:
993
+ return self.flags.copy()
extra_model_paths.yaml.example ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #Rename this to extra_model_paths.yaml and ComfyUI will load it
2
+
3
+
4
+ #config for a1111 ui
5
+ #all you have to do is change the base_path to where yours is installed
6
+ a111:
7
+ base_path: path/to/stable-diffusion-webui/
8
+
9
+ checkpoints: models/Stable-diffusion
10
+ configs: models/Stable-diffusion
11
+ vae: models/VAE
12
+ loras: |
13
+ models/Lora
14
+ models/LyCORIS
15
+ upscale_models: |
16
+ models/ESRGAN
17
+ models/RealESRGAN
18
+ models/SwinIR
19
+ embeddings: embeddings
20
+ hypernetworks: models/hypernetworks
21
+ controlnet: models/ControlNet
22
+
23
+ #config for comfyui
24
+ #your base path should be either an existing comfy install or a central folder where you store all of your models, loras, etc.
25
+
26
+ #comfyui:
27
+ # base_path: path/to/comfyui/
28
+ # checkpoints: models/checkpoints/
29
+ # clip: models/clip/
30
+ # clip_vision: models/clip_vision/
31
+ # configs: models/configs/
32
+ # controlnet: models/controlnet/
33
+ # diffusion_models: |
34
+ # models/diffusion_models
35
+ # models/unet
36
+ # embeddings: models/embeddings/
37
+ # loras: models/loras/
38
+ # upscale_models: models/upscale_models/
39
+ # vae: models/vae/
40
+
41
+ #other_ui:
42
+ # base_path: path/to/ui
43
+ # checkpoints: models/checkpoints
44
+ # gligen: models/gligen
45
+ # custom_nodes: path/custom_nodes
fix_torch.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.util
2
+ import shutil
3
+ import os
4
+ import ctypes
5
+ import logging
6
+
7
+
8
+ torch_spec = importlib.util.find_spec("torch")
9
+ logging.info("Fix and patch for torch in windows")
10
+ for folder in torch_spec.submodule_search_locations:
11
+ lib_folder = os.path.join(folder, "lib")
12
+ test_file = os.path.join(lib_folder, "fbgemm.dll")
13
+ dest = os.path.join(lib_folder, "libomp140.x86_64.dll")
14
+ if os.path.exists(dest):
15
+ break
16
+
17
+ with open(test_file, 'rb') as f:
18
+ contents = f.read()
19
+ if b"libomp140.x86_64.dll" not in contents:
20
+ break
21
+ try:
22
+ mydll = ctypes.cdll.LoadLibrary(test_file)
23
+ except FileNotFoundError as e:
24
+ logging.warning("Detected pytorch version with libomp issue, patching.")
25
+ shutil.copyfile(os.path.join(lib_folder, "libiomp5md.dll"), dest)
folder_paths.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import time
5
+ import mimetypes
6
+ import logging
7
+ from pathlib import Path # FooocusPlus_Comfymod
8
+ from typing import Set, List, Dict, Tuple, Literal
9
+ from collections.abc import Collection
10
+
11
+ supported_pt_extensions: set[str] = {'.ckpt', '.pt', '.bin', '.pth', '.safetensors', '.pkl', '.sft'}
12
+
13
+ folder_names_and_paths: dict[str, tuple[list[str], set[str]]] = {}
14
+
15
+ base_path = os.path.dirname(os.path.realpath(__file__))
16
+
17
+ # FooocusPlus_Comfymod: set to valid model dirs:
18
+ #models_dir = os.path.join(os.path.dirname(base_path), "models")
19
+ current_dir = Path.cwd()
20
+ user_models_dir = Path(current_dir.resolve().parent/'UserDir/models')
21
+ models_dir = user_models_dir
22
+
23
+
24
+ def reset_folder_names_and_paths(models_root):
25
+ global models_dir, folder_names_and_paths
26
+ models_dir = models_root
27
+ #print(f'folder_names_and_paths:{folder_names_and_paths}')
28
+ folder_names_and_paths = {}
29
+ folder_names_and_paths["checkpoints"] = ([os.path.join(models_dir, "checkpoints")], supported_pt_extensions)
30
+ folder_names_and_paths["configs"] = ([os.path.join(models_dir, "configs")], [".yaml"])
31
+ folder_names_and_paths["loras"] = ([os.path.join(models_dir, "loras")], supported_pt_extensions)
32
+ folder_names_and_paths["vae"] = ([os.path.join(models_dir, "vae")], supported_pt_extensions)
33
+ folder_names_and_paths["clip"] = ([os.path.join(models_dir, "clip")], supported_pt_extensions)
34
+ folder_names_and_paths["diffusion_models"] = ([os.path.join(models_dir, "unet"), os.path.join(models_dir, "diffusion_models")], supported_pt_extensions)
35
+ folder_names_and_paths["clip_vision"] = ([os.path.join(models_dir, "clip_vision")], supported_pt_extensions)
36
+ folder_names_and_paths["style_models"] = ([os.path.join(models_dir, "style_models")], supported_pt_extensions)
37
+ folder_names_and_paths["embeddings"] = ([os.path.join(models_dir, "embeddings")], supported_pt_extensions)
38
+ folder_names_and_paths["diffusers"] = ([os.path.join(models_dir, "diffusers")], ["folder"])
39
+ folder_names_and_paths["vae_approx"] = ([os.path.join(models_dir, "vae_approx")], supported_pt_extensions)
40
+
41
+ folder_names_and_paths["controlnet"] = ([os.path.join(models_dir, "controlnet"), os.path.join(models_dir, "t2i_adapter")], supported_pt_extensions)
42
+ folder_names_and_paths["gligen"] = ([os.path.join(models_dir, "gligen")], supported_pt_extensions)
43
+
44
+ folder_names_and_paths["upscale_models"] = ([os.path.join(models_dir, "upscale_models")], supported_pt_extensions)
45
+
46
+ folder_names_and_paths["custom_nodes"] = ([os.path.join(base_path, "custom_nodes")], set())
47
+
48
+ folder_names_and_paths["hypernetworks"] = ([os.path.join(models_dir, "hypernetworks")], supported_pt_extensions)
49
+
50
+ folder_names_and_paths["photomaker"] = ([os.path.join(models_dir, "photomaker")], supported_pt_extensions)
51
+
52
+ folder_names_and_paths["classifiers"] = ([os.path.join(models_dir, "classifiers")], {""})
53
+ return
54
+
55
+ reset_folder_names_and_paths(models_dir)
56
+
57
+ output_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "output")
58
+ temp_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "temp")
59
+ input_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "input")
60
+ user_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)), "user")
61
+
62
+ filename_list_cache: dict[str, tuple[list[str], dict[str, float], float]] = {}
63
+
64
+ extension_mimetypes_cache = {
65
+ "webp" : "image",
66
+ }
67
+
68
+ def map_legacy(folder_name: str) -> str:
69
+ legacy = {"unet": "diffusion_models",
70
+ "llm": "llms",
71
+ }
72
+ return legacy.get(folder_name, folder_name)
73
+
74
+ if not os.path.exists(input_directory):
75
+ try:
76
+ os.makedirs(input_directory)
77
+ except:
78
+ logging.error("Failed to create input directory")
79
+
80
+ def set_output_directory(output_dir: str) -> None:
81
+ global output_directory
82
+ output_directory = output_dir
83
+
84
+ def set_temp_directory(temp_dir: str) -> None:
85
+ global temp_directory
86
+ temp_directory = temp_dir
87
+
88
+ def set_input_directory(input_dir: str) -> None:
89
+ global input_directory
90
+ input_directory = input_dir
91
+
92
+ def get_output_directory() -> str:
93
+ global output_directory
94
+ return output_directory
95
+
96
+ def get_temp_directory() -> str:
97
+ global temp_directory
98
+ return temp_directory
99
+
100
+ def get_input_directory() -> str:
101
+ global input_directory
102
+ return input_directory
103
+
104
+ def get_user_directory() -> str:
105
+ return user_directory
106
+
107
+ def set_user_directory(user_dir: str) -> None:
108
+ global user_directory
109
+ user_directory = user_dir
110
+
111
+
112
+ #NOTE: used in http server so don't put folders that should not be accessed remotely
113
+ def get_directory_by_type(type_name: str) -> str | None:
114
+ if type_name == "output":
115
+ return get_output_directory()
116
+ if type_name == "temp":
117
+ return get_temp_directory()
118
+ if type_name == "input":
119
+ return get_input_directory()
120
+ return None
121
+
122
+ def filter_files_content_types(files: List[str], content_types: Literal["image", "video", "audio"]) -> List[str]:
123
+ """
124
+ Example:
125
+ files = os.listdir(folder_paths.get_input_directory())
126
+ filter_files_content_types(files, ["image", "audio", "video"])
127
+ """
128
+ global extension_mimetypes_cache
129
+ result = []
130
+ for file in files:
131
+ extension = file.split('.')[-1]
132
+ if extension not in extension_mimetypes_cache:
133
+ mime_type, _ = mimetypes.guess_type(file, strict=False)
134
+ if not mime_type:
135
+ continue
136
+ content_type = mime_type.split('/')[0]
137
+ extension_mimetypes_cache[extension] = content_type
138
+ else:
139
+ content_type = extension_mimetypes_cache[extension]
140
+
141
+ if content_type in content_types:
142
+ result.append(file)
143
+ return result
144
+
145
+ # determine base_dir rely on annotation if name is 'filename.ext [annotation]' format
146
+ # otherwise use default_path as base_dir
147
+ def annotated_filepath(name: str) -> tuple[str, str | None]:
148
+ if name.endswith("[output]"):
149
+ base_dir = get_output_directory()
150
+ name = name[:-9]
151
+ elif name.endswith("[input]"):
152
+ base_dir = get_input_directory()
153
+ name = name[:-8]
154
+ elif name.endswith("[temp]"):
155
+ base_dir = get_temp_directory()
156
+ name = name[:-7]
157
+ else:
158
+ return name, None
159
+
160
+ return name, base_dir
161
+
162
+
163
+ def get_annotated_filepath(name: str, default_dir: str | None=None) -> str:
164
+ name, base_dir = annotated_filepath(name)
165
+
166
+ if base_dir is None:
167
+ if default_dir is not None:
168
+ base_dir = default_dir
169
+ else:
170
+ base_dir = get_input_directory() # fallback path
171
+
172
+ return os.path.join(base_dir, name)
173
+
174
+
175
+ def exists_annotated_filepath(name) -> bool:
176
+ name, base_dir = annotated_filepath(name)
177
+
178
+ if base_dir is None:
179
+ base_dir = get_input_directory() # fallback path
180
+
181
+ filepath = os.path.join(base_dir, name)
182
+ return os.path.exists(filepath)
183
+
184
+
185
+ def add_model_folder_path(folder_name: str, full_folder_path: str) -> None:
186
+ global folder_names_and_paths
187
+ folder_name = map_legacy(folder_name)
188
+ if folder_name in folder_names_and_paths:
189
+ if full_folder_path not in folder_names_and_paths[folder_name][0]:
190
+ folder_names_and_paths[folder_name][0].append(full_folder_path)
191
+ else:
192
+ folder_names_and_paths[folder_name] = ([full_folder_path], set())
193
+
194
+ def get_folder_paths(folder_name: str) -> list[str]:
195
+ folder_name = map_legacy(folder_name)
196
+ return folder_names_and_paths[folder_name][0][:]
197
+
198
+ def recursive_search(directory: str, excluded_dir_names: list[str] | None=None) -> tuple[list[str], dict[str, float]]:
199
+ if not os.path.isdir(directory):
200
+ return [], {}
201
+
202
+ if excluded_dir_names is None:
203
+ excluded_dir_names = []
204
+
205
+ result = []
206
+ dirs = {}
207
+
208
+ # Attempt to add the initial directory to dirs with error handling
209
+ try:
210
+ dirs[directory] = os.path.getmtime(directory)
211
+ except FileNotFoundError:
212
+ logging.warning(f"Warning: Unable to access {directory}. Skipping this path.")
213
+
214
+ logging.debug("recursive file list on directory {}".format(directory))
215
+ dirpath: str
216
+ subdirs: list[str]
217
+ filenames: list[str]
218
+
219
+ for dirpath, subdirs, filenames in os.walk(directory, followlinks=True, topdown=True):
220
+ subdirs[:] = [d for d in subdirs if d not in excluded_dir_names]
221
+ for file_name in filenames:
222
+ relative_path = os.path.relpath(os.path.join(dirpath, file_name), directory)
223
+ result.append(relative_path)
224
+
225
+ for d in subdirs:
226
+ path: str = os.path.join(dirpath, d)
227
+ try:
228
+ dirs[path] = os.path.getmtime(path)
229
+ except FileNotFoundError:
230
+ logging.warning(f"Warning: Unable to access {path}. Skipping this path.")
231
+ continue
232
+ logging.debug("found {} files".format(len(result)))
233
+ return result, dirs
234
+
235
+ def filter_files_extensions(files: Collection[str], extensions: Collection[str]) -> list[str]:
236
+ return sorted(list(filter(lambda a: os.path.splitext(a)[-1].lower() in extensions or len(extensions) == 0, files)))
237
+
238
+
239
+
240
+ def get_full_path(folder_name: str, filename: str) -> str | None:
241
+ global folder_names_and_paths
242
+ folder_name = map_legacy(folder_name)
243
+ if folder_name not in folder_names_and_paths:
244
+ return None
245
+ folders = folder_names_and_paths[folder_name]
246
+ filename = os.path.relpath(os.path.join("/", filename), "/")
247
+ for x in folders[0]:
248
+ full_path = os.path.join(x, filename)
249
+ if os.path.isfile(full_path):
250
+ return full_path
251
+ elif os.path.islink(full_path):
252
+ logging.warning("WARNING path {} exists but doesn't link anywhere, skipping.".format(full_path))
253
+
254
+ return None
255
+
256
+ def get_filename_list_(folder_name: str) -> tuple[list[str], dict[str, float], float]:
257
+ folder_name = map_legacy(folder_name)
258
+ global folder_names_and_paths
259
+ output_list = set()
260
+ folders = folder_names_and_paths[folder_name]
261
+ output_folders = {}
262
+ for x in folders[0]:
263
+ files, folders_all = recursive_search(x, excluded_dir_names=[".git"])
264
+ output_list.update(filter_files_extensions(files, folders[1]))
265
+ output_folders = {**output_folders, **folders_all}
266
+
267
+ return sorted(list(output_list)), output_folders, time.perf_counter()
268
+
269
+ def cached_filename_list_(folder_name: str) -> tuple[list[str], dict[str, float], float] | None:
270
+ global filename_list_cache
271
+ global folder_names_and_paths
272
+ folder_name = map_legacy(folder_name)
273
+ if folder_name not in filename_list_cache:
274
+ return None
275
+ out = filename_list_cache[folder_name]
276
+
277
+ for x in out[1]:
278
+ time_modified = out[1][x]
279
+ folder = x
280
+ if os.path.getmtime(folder) != time_modified:
281
+ return None
282
+
283
+ folders = folder_names_and_paths[folder_name]
284
+ for x in folders[0]:
285
+ if os.path.isdir(x):
286
+ if x not in out[1]:
287
+ return None
288
+
289
+ return out
290
+
291
+ def get_filename_list(folder_name: str) -> list[str]:
292
+ folder_name = map_legacy(folder_name)
293
+ out = cached_filename_list_(folder_name)
294
+ if out is None:
295
+ out = get_filename_list_(folder_name)
296
+ global filename_list_cache
297
+ filename_list_cache[folder_name] = out
298
+ return list(out[0])
299
+
300
+ def get_save_image_path(filename_prefix: str, output_dir: str, image_width=0, image_height=0) -> tuple[str, str, int, str, str]:
301
+ def map_filename(filename: str) -> tuple[int, str]:
302
+ prefix_len = len(os.path.basename(filename_prefix))
303
+ prefix = filename[:prefix_len + 1]
304
+ try:
305
+ digits = int(filename[prefix_len + 1:].split('_')[0])
306
+ except:
307
+ digits = 0
308
+ return digits, prefix
309
+
310
+ def compute_vars(input: str, image_width: int, image_height: int) -> str:
311
+ input = input.replace("%width%", str(image_width))
312
+ input = input.replace("%height%", str(image_height))
313
+ now = time.localtime()
314
+ input = input.replace("%year%", str(now.tm_year))
315
+ input = input.replace("%month%", str(now.tm_mon).zfill(2))
316
+ input = input.replace("%day%", str(now.tm_mday).zfill(2))
317
+ input = input.replace("%hour%", str(now.tm_hour).zfill(2))
318
+ input = input.replace("%minute%", str(now.tm_min).zfill(2))
319
+ input = input.replace("%second%", str(now.tm_sec).zfill(2))
320
+ return input
321
+
322
+ if "%" in filename_prefix:
323
+ filename_prefix = compute_vars(filename_prefix, image_width, image_height)
324
+
325
+ subfolder = os.path.dirname(os.path.normpath(filename_prefix))
326
+ filename = os.path.basename(os.path.normpath(filename_prefix))
327
+
328
+ full_output_folder = os.path.join(output_dir, subfolder)
329
+
330
+ if os.path.commonpath((output_dir, os.path.abspath(full_output_folder))) != output_dir:
331
+ err = "**** ERROR: Saving image outside the output folder is not allowed." + \
332
+ "\n full_output_folder: " + os.path.abspath(full_output_folder) + \
333
+ "\n output_dir: " + output_dir + \
334
+ "\n commonpath: " + os.path.commonpath((output_dir, os.path.abspath(full_output_folder)))
335
+ logging.error(err)
336
+ raise Exception(err)
337
+
338
+ try:
339
+ counter = max(filter(lambda a: os.path.normcase(a[1][:-1]) == os.path.normcase(filename) and a[1][-1] == "_", map(map_filename, os.listdir(full_output_folder))))[0] + 1
340
+ except ValueError:
341
+ counter = 1
342
+ except FileNotFoundError:
343
+ os.makedirs(full_output_folder, exist_ok=True)
344
+ counter = 1
345
+ return full_output_folder, filename, counter, subfolder, filename_prefix
index.html ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <title>ComfyUI</title>
6
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
7
+ <!-- Browser Test Fonts -->
8
+ <!-- <link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:ital,wght@0,100..700;1,100..700&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
9
+ <link href="https://fonts.googleapis.com/css2?family=Noto+Color+Emoji&family=Roboto+Mono:ital,wght@0,100..700;1,100..700&family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
10
+ <style>
11
+ * {
12
+ font-family: 'Roboto Mono', 'Noto Color Emoji';
13
+ }
14
+ </style> -->
15
+ <link rel="stylesheet" type="text/css" href="user.css" />
16
+ <link rel="stylesheet" type="text/css" href="materialdesignicons.min.css" />
17
+ <script type="module" crossorigin src="./assets/index-CaD4RONs.js"></script>
18
+ <link rel="stylesheet" crossorigin href="./assets/index-DAK31IJJ.css">
19
+ </head>
20
+ <body class="litegraph">
21
+ <div id="vue-app"></div>
22
+ <div id="comfy-user-selection" class="comfy-user-selection" style="display: none;">
23
+ <main class="comfy-user-selection-inner">
24
+ <h1>ComfyUI</h1>
25
+ <form>
26
+ <section>
27
+ <label>New user:
28
+ <input placeholder="Enter a username" />
29
+ </label>
30
+ </section>
31
+ <div class="comfy-user-existing">
32
+ <span class="or-separator">OR</span>
33
+ <section>
34
+ <label>
35
+ Existing user:
36
+ <select>
37
+ <option hidden disabled selected value> Select a user </option>
38
+ </select>
39
+ </label>
40
+ </section>
41
+ </div>
42
+ <footer>
43
+ <span class="comfy-user-error">&nbsp;</span>
44
+ <button class="comfy-btn comfy-user-button-next">Next</button>
45
+ </footer>
46
+ </form>
47
+ </main>
48
+ </div>
49
+ </body>
50
+ </html>
latent_preview.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from PIL import Image
3
+ import struct
4
+ import numpy as np
5
+ from comfy.cli_args import args, LatentPreviewMethod
6
+ from comfy.taesd.taesd import TAESD
7
+ import comfy.model_management
8
+ import folder_paths
9
+ import comfy.utils
10
+ import logging
11
+
12
+ MAX_PREVIEW_RESOLUTION = args.preview_size
13
+
14
+ def preview_to_image(latent_image):
15
+ latents_ubyte = (((latent_image + 1.0) / 2.0).clamp(0, 1) # change scale from -1..1 to 0..1
16
+ .mul(0xFF) # to 0..255
17
+ ).to(device="cpu", dtype=torch.uint8, non_blocking=comfy.model_management.device_supports_non_blocking(latent_image.device))
18
+
19
+ return Image.fromarray(latents_ubyte.numpy())
20
+
21
+ class LatentPreviewer:
22
+ def decode_latent_to_preview(self, x0):
23
+ pass
24
+
25
+ def decode_latent_to_preview_image(self, preview_format, x0):
26
+ preview_image = self.decode_latent_to_preview(x0)
27
+ return ("JPEG", preview_image, MAX_PREVIEW_RESOLUTION)
28
+
29
+ class TAESDPreviewerImpl(LatentPreviewer):
30
+ def __init__(self, taesd):
31
+ self.taesd = taesd
32
+
33
+ def decode_latent_to_preview(self, x0):
34
+ x_sample = self.taesd.decode(x0[:1])[0].movedim(0, 2)
35
+ return preview_to_image(x_sample)
36
+
37
+
38
+ class Latent2RGBPreviewer(LatentPreviewer):
39
+ def __init__(self, latent_rgb_factors):
40
+ self.latent_rgb_factors = torch.tensor(latent_rgb_factors, device="cpu")
41
+
42
+ def decode_latent_to_preview(self, x0):
43
+ self.latent_rgb_factors = self.latent_rgb_factors.to(dtype=x0.dtype, device=x0.device)
44
+ latent_image = x0[0].permute(1, 2, 0) @ self.latent_rgb_factors
45
+ return preview_to_image(latent_image)
46
+
47
+
48
+ def get_previewer(device, latent_format):
49
+ previewer = None
50
+ method = args.preview_method
51
+ if method != LatentPreviewMethod.NoPreviews:
52
+ # TODO previewer methods
53
+ taesd_decoder_path = None
54
+ if latent_format.taesd_decoder_name is not None:
55
+ taesd_decoder_path = next(
56
+ (fn for fn in folder_paths.get_filename_list("vae_approx")
57
+ if fn.startswith(latent_format.taesd_decoder_name)),
58
+ ""
59
+ )
60
+ taesd_decoder_path = folder_paths.get_full_path("vae_approx", taesd_decoder_path)
61
+
62
+ if method == LatentPreviewMethod.Auto:
63
+ method = LatentPreviewMethod.Latent2RGB
64
+
65
+ if method == LatentPreviewMethod.TAESD:
66
+ if taesd_decoder_path:
67
+ taesd = TAESD(None, taesd_decoder_path, latent_channels=latent_format.latent_channels).to(device)
68
+ previewer = TAESDPreviewerImpl(taesd)
69
+ else:
70
+ logging.warning("Warning: TAESD previews enabled, but could not find models/vae_approx/{}".format(latent_format.taesd_decoder_name))
71
+
72
+ if previewer is None:
73
+ if latent_format.latent_rgb_factors is not None:
74
+ previewer = Latent2RGBPreviewer(latent_format.latent_rgb_factors)
75
+ return previewer
76
+
77
+ def prepare_callback(model, steps, x0_output_dict=None):
78
+ preview_format = "JPEG"
79
+ if preview_format not in ["JPEG", "PNG"]:
80
+ preview_format = "JPEG"
81
+
82
+ previewer = get_previewer(model.load_device, model.model.latent_format)
83
+
84
+ pbar = comfy.utils.ProgressBar(steps)
85
+ def callback(step, x0, x, total_steps):
86
+ if x0_output_dict is not None:
87
+ x0_output_dict["x0"] = x0
88
+
89
+ preview_bytes = None
90
+ if previewer:
91
+ preview_bytes = previewer.decode_latent_to_preview_image(preview_format, x0)
92
+ pbar.update_absolute(step + 1, total_steps, preview_bytes)
93
+ return callback
94
+
load_file_from_url.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import folder_paths
3
+ import json
4
+ from pathlib import Path # FooocusPlus_Comfymod
5
+ from urllib.parse import urlparse
6
+ from typing import Optional
7
+
8
+
9
+ def load_file_from_url(
10
+ url: str,
11
+ *,
12
+ model_dir: str,
13
+ progress: bool = True,
14
+ file_name: Optional[str] = None,
15
+ ) -> str:
16
+ """Download a file from `url` into `model_dir`, using the file present if possible.
17
+ Returns the path to the downloaded file.
18
+ """
19
+ os.makedirs(model_dir, exist_ok=True)
20
+ if not file_name:
21
+ parts = urlparse(url)
22
+ file_name = os.path.basename(parts.path)
23
+ cached_file = os.path.abspath(os.path.join(model_dir, file_name))
24
+ if not os.path.exists(cached_file):
25
+ if url.find("huggingface.co")>=0:
26
+ url = url.replace('huggingface.co', 'hf-mirror.com')
27
+ print(f'Downloading: "{url}" to {cached_file}\n')
28
+ from torch.hub import download_url_to_file
29
+ download_url_to_file(url, cached_file, progress=progress)
30
+
31
+ return cached_file
32
+
33
+
34
+ def load_model_for_path(models_url, root_name):
35
+ models_root = folder_paths.get_folder_paths(root_name)[0]
36
+ for model_path in models_url:
37
+ model_full_path = os.path.join(models_root, model_path)
38
+ if not os.path.exists(model_full_path):
39
+ model_full_path = load_file_from_url(
40
+ url=models_url[model_path], model_dir=models_root, file_name=model_path
41
+ )
42
+
43
+
44
+ # FooocusPlus_Comfymod: set IC-Light paths:
45
+ default_base_SD15_name = str(Path(folder_paths.user_models_dir/'checkpoints/SD1.5/realisticVisionV60B1_v51VAE.safetensors'))
46
+ default_unet_SD15_name = str(Path(folder_paths.user_models_dir/'unet/iclight_sd15_fc_unet_ldm.safetensors'))
47
+
48
+ # FooocusPlus_Comfymod: # fake out model downloading: its done in modules.config
49
+ def load_model_for_iclight():
50
+ global default_base_SD15_name, default_unet_SD15_name
51
+ models_path = default_unet_SD15_name
52
+ model_full_path = Path(default_unet_SD15_name)
53
+ models_path = default_base_SD15_name
54
+ model_full_path = Path(default_base_SD15_name)
55
+ return
main.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ root = os.path.dirname(os.path.abspath(__file__))
4
+ sys.path.append(root)
5
+ #os.chdir(root)
6
+ import warnings
7
+ warnings.filterwarnings("ignore", category=FutureWarning)
8
+
9
+ import comfy.options
10
+ comfy.options.enable_args_parsing()
11
+
12
+ import importlib.util
13
+ import folder_paths
14
+ import time
15
+ from comfy.cli_args import args
16
+ from app.logger import setup_logger
17
+
18
+
19
+ setup_logger(verbose=args.verbose)
20
+
21
+
22
+ def execute_prestartup_script():
23
+ def execute_script(script_path):
24
+ module_name = os.path.splitext(script_path)[0]
25
+ try:
26
+ spec = importlib.util.spec_from_file_location(module_name, script_path)
27
+ module = importlib.util.module_from_spec(spec)
28
+ spec.loader.exec_module(module)
29
+ return True
30
+ except Exception as e:
31
+ print(f"Failed to execute startup-script: {script_path} / {e}")
32
+ return False
33
+
34
+ if args.disable_all_custom_nodes:
35
+ return
36
+
37
+ node_paths = folder_paths.get_folder_paths("custom_nodes")
38
+ for custom_node_path in node_paths:
39
+ possible_modules = os.listdir(custom_node_path)
40
+ node_prestartup_times = []
41
+
42
+ for possible_module in possible_modules:
43
+ module_path = os.path.join(custom_node_path, possible_module)
44
+ if os.path.isfile(module_path) or module_path.endswith(".disabled") or module_path == "__pycache__":
45
+ continue
46
+
47
+ script_path = os.path.join(module_path, "prestartup_script.py")
48
+ if os.path.exists(script_path):
49
+ time_before = time.perf_counter()
50
+ success = execute_script(script_path)
51
+ node_prestartup_times.append((time.perf_counter() - time_before, module_path, success))
52
+ if len(node_prestartup_times) > 0:
53
+ print("[Comfyd] Prestartup times for custom nodes:")
54
+ for n in sorted(node_prestartup_times):
55
+ if n[2]:
56
+ import_message = ""
57
+ else:
58
+ import_message = " (PRESTARTUP FAILED)"
59
+ print("[Comfyd] {:6.1f} seconds{}:".format(n[0], import_message), n[1])
60
+ #print()
61
+
62
+ #execute_prestartup_script()
63
+
64
+ # Main code
65
+ import asyncio
66
+ import itertools
67
+ import shutil
68
+ import threading
69
+ import gc
70
+
71
+ import logging
72
+ import utils.extra_config
73
+
74
+ if os.name == "nt":
75
+ logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
76
+
77
+ if __name__ == "__main__":
78
+ if args.cuda_device is not None:
79
+ os.environ['CUDA_VISIBLE_DEVICES'] = str(args.cuda_device)
80
+ logging.info("Set cuda device to: {}".format(args.cuda_device))
81
+
82
+ if args.deterministic:
83
+ if 'CUBLAS_WORKSPACE_CONFIG' not in os.environ:
84
+ os.environ['CUBLAS_WORKSPACE_CONFIG'] = ":4096:8"
85
+
86
+ import cuda_malloc
87
+
88
+ if args.windows_standalone_build:
89
+ try:
90
+ import fix_torch
91
+ except:
92
+ pass
93
+
94
+ import comfy.utils
95
+
96
+ import execution
97
+ import server
98
+ from server import BinaryEventTypes
99
+ import nodes
100
+ import comfy.model_management
101
+
102
+ def cuda_malloc_warning():
103
+ device = comfy.model_management.get_torch_device()
104
+ device_name = comfy.model_management.get_torch_device_name(device)
105
+ cuda_malloc_warning = False
106
+ if "cudaMallocAsync" in device_name:
107
+ for b in cuda_malloc.blacklist:
108
+ if b in device_name:
109
+ cuda_malloc_warning = True
110
+ if cuda_malloc_warning:
111
+ logging.warning("\nWARNING: this card most likely does not support cuda-malloc, if you get \"CUDA error\" please run ComfyUI with: --disable-cuda-malloc\n")
112
+
113
+ def prompt_worker(q, server):
114
+ e = execution.PromptExecutor(server, lru_size=args.cache_lru)
115
+ last_gc_collect = 0
116
+ need_gc = False
117
+ gc_collect_interval = 10.0
118
+
119
+ while True:
120
+ timeout = 1000.0
121
+ if need_gc:
122
+ timeout = max(gc_collect_interval - (current_time - last_gc_collect), 0.0)
123
+
124
+ queue_item = q.get(timeout=timeout)
125
+ if queue_item is not None:
126
+ item, item_id = queue_item
127
+ execution_start_time = time.perf_counter()
128
+ prompt_id = item[1]
129
+ server.last_prompt_id = prompt_id
130
+
131
+ e.execute(item[2], prompt_id, item[3], item[4])
132
+ need_gc = True
133
+ q.task_done(item_id,
134
+ e.history_result,
135
+ status=execution.PromptQueue.ExecutionStatus(
136
+ status_str='success' if e.success else 'error',
137
+ completed=e.success,
138
+ messages=e.status_messages))
139
+ if server.client_id is not None:
140
+ server.send_sync("executing", { "node": None, "prompt_id": prompt_id }, server.client_id)
141
+
142
+ current_time = time.perf_counter()
143
+ execution_time = current_time - execution_start_time
144
+ logging.info("Prompt executed in {:.2f} seconds".format(execution_time))
145
+
146
+ flags = q.get_flags()
147
+ free_memory = flags.get("free_memory", False)
148
+
149
+ if flags.get("unload_models", free_memory):
150
+ comfy.model_management.unload_all_models()
151
+ need_gc = True
152
+ last_gc_collect = 0
153
+
154
+ if free_memory:
155
+ e.reset()
156
+ need_gc = True
157
+ last_gc_collect = 0
158
+
159
+ if need_gc:
160
+ current_time = time.perf_counter()
161
+ if (current_time - last_gc_collect) > gc_collect_interval:
162
+ comfy.model_management.cleanup_models()
163
+ gc.collect()
164
+ comfy.model_management.soft_empty_cache()
165
+ last_gc_collect = current_time
166
+ need_gc = False
167
+
168
+ async def run(server, address='', port=8188, verbose=True, call_on_start=None):
169
+ await asyncio.gather(server.start(address, port, verbose, call_on_start), server.publish_loop())
170
+
171
+
172
+ def hijack_progress(server):
173
+ def hook(value, total, preview_image):
174
+ comfy.model_management.throw_exception_if_processing_interrupted()
175
+ progress = {"value": value, "max": total, "prompt_id": server.last_prompt_id, "node": server.last_node_id}
176
+
177
+ server.send_sync("progress", progress, server.client_id)
178
+ if preview_image is not None:
179
+ server.send_sync(BinaryEventTypes.UNENCODED_PREVIEW_IMAGE, preview_image, server.client_id)
180
+ comfy.utils.set_progress_bar_global_hook(hook)
181
+
182
+
183
+ def cleanup_temp():
184
+ temp_dir = folder_paths.get_temp_directory()
185
+ if os.path.exists(temp_dir):
186
+ shutil.rmtree(temp_dir, ignore_errors=True)
187
+
188
+
189
+ if __name__ == "__main__":
190
+ if args.temp_directory:
191
+ temp_dir = os.path.join(os.path.abspath(args.temp_directory), "temp")
192
+ logging.info(f"Setting temp directory to: {temp_dir}")
193
+ folder_paths.set_temp_directory(temp_dir)
194
+ cleanup_temp()
195
+
196
+ if args.windows_standalone_build:
197
+ try:
198
+ import new_updater
199
+ new_updater.update_windows_updater()
200
+ except:
201
+ pass
202
+
203
+ loop = asyncio.new_event_loop()
204
+ asyncio.set_event_loop(loop)
205
+ server = server.PromptServer(loop)
206
+ q = execution.PromptQueue(server)
207
+
208
+ extra_model_paths_config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "extra_model_paths.yaml")
209
+ if os.path.isfile(extra_model_paths_config_path):
210
+ utils.extra_config.load_extra_path_config(extra_model_paths_config_path)
211
+
212
+ if args.extra_model_paths_config:
213
+ for config_path in itertools.chain(*args.extra_model_paths_config):
214
+ utils.extra_config.load_extra_path_config(config_path)
215
+
216
+ execute_prestartup_script()
217
+ nodes.init_extra_nodes(init_custom_nodes=not args.disable_all_custom_nodes)
218
+
219
+ cuda_malloc_warning()
220
+
221
+ server.add_routes()
222
+ hijack_progress(server)
223
+
224
+ threading.Thread(target=prompt_worker, daemon=True, args=(q, server,)).start()
225
+
226
+ if args.output_directory:
227
+ output_dir = os.path.abspath(args.output_directory)
228
+ logging.info(f"Setting output directory to: {output_dir}")
229
+ folder_paths.set_output_directory(output_dir)
230
+
231
+ #These are the default folders that checkpoints, clip and vae models will be saved to when using CheckpointSave, etc.. nodes
232
+ folder_paths.add_model_folder_path("checkpoints", os.path.join(folder_paths.get_output_directory(), "checkpoints"))
233
+ folder_paths.add_model_folder_path("clip", os.path.join(folder_paths.get_output_directory(), "clip"))
234
+ folder_paths.add_model_folder_path("vae", os.path.join(folder_paths.get_output_directory(), "vae"))
235
+ folder_paths.add_model_folder_path("diffusion_models", os.path.join(folder_paths.get_output_directory(), "diffusion_models"))
236
+ folder_paths.add_model_folder_path("loras", os.path.join(folder_paths.get_output_directory(), "loras"))
237
+
238
+ if args.input_directory:
239
+ input_dir = os.path.abspath(args.input_directory)
240
+ logging.info(f"Setting input directory to: {input_dir}")
241
+ folder_paths.set_input_directory(input_dir)
242
+
243
+ if args.user_directory:
244
+ user_dir = os.path.abspath(args.user_directory)
245
+ logging.info(f"Setting user directory to: {user_dir}")
246
+ folder_paths.set_user_directory(user_dir)
247
+
248
+ if args.quick_test_for_ci:
249
+ exit(0)
250
+
251
+ call_on_start = None
252
+ if args.auto_launch:
253
+ def startup_server(scheme, address, port):
254
+ import webbrowser
255
+ if os.name == 'nt' and address == '0.0.0.0':
256
+ address = '127.0.0.1'
257
+ webbrowser.open(f"{scheme}://{address}:{port}")
258
+ call_on_start = startup_server
259
+
260
+ try:
261
+ loop.run_until_complete(server.setup())
262
+ loop.run_until_complete(run(server, address=args.listen, port=args.port, verbose=not args.dont_print_server, call_on_start=call_on_start))
263
+ except KeyboardInterrupt:
264
+ logging.info("\nStopped server")
265
+
266
+ cleanup_temp()
model_filemanager/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # model_manager/__init__.py
2
+ from .download_models import download_model, DownloadModelStatus, DownloadStatusType, create_model_path, check_file_exists, track_download_progress, validate_model_subdirectory, validate_filename
model_filemanager/download_models.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import aiohttp
3
+ import os
4
+ import traceback
5
+ import logging
6
+ from folder_paths import models_dir
7
+ import re
8
+ from typing import Callable, Any, Optional, Awaitable, Dict
9
+ from enum import Enum
10
+ import time
11
+ from dataclasses import dataclass
12
+
13
+
14
+ class DownloadStatusType(Enum):
15
+ PENDING = "pending"
16
+ IN_PROGRESS = "in_progress"
17
+ COMPLETED = "completed"
18
+ ERROR = "error"
19
+
20
+ @dataclass
21
+ class DownloadModelStatus():
22
+ status: str
23
+ progress_percentage: float
24
+ message: str
25
+ already_existed: bool = False
26
+
27
+ def __init__(self, status: DownloadStatusType, progress_percentage: float, message: str, already_existed: bool):
28
+ self.status = status.value # Store the string value of the Enum
29
+ self.progress_percentage = progress_percentage
30
+ self.message = message
31
+ self.already_existed = already_existed
32
+
33
+ def to_dict(self) -> Dict[str, Any]:
34
+ return {
35
+ "status": self.status,
36
+ "progress_percentage": self.progress_percentage,
37
+ "message": self.message,
38
+ "already_existed": self.already_existed
39
+ }
40
+
41
+ async def download_model(model_download_request: Callable[[str], Awaitable[aiohttp.ClientResponse]],
42
+ model_name: str,
43
+ model_url: str,
44
+ model_sub_directory: str,
45
+ progress_callback: Callable[[str, DownloadModelStatus], Awaitable[Any]],
46
+ progress_interval: float = 1.0) -> DownloadModelStatus:
47
+ """
48
+ Download a model file from a given URL into the models directory.
49
+
50
+ Args:
51
+ model_download_request (Callable[[str], Awaitable[aiohttp.ClientResponse]]):
52
+ A function that makes an HTTP request. This makes it easier to mock in unit tests.
53
+ model_name (str):
54
+ The name of the model file to be downloaded. This will be the filename on disk.
55
+ model_url (str):
56
+ The URL from which to download the model.
57
+ model_sub_directory (str):
58
+ The subdirectory within the main models directory where the model
59
+ should be saved (e.g., 'checkpoints', 'loras', etc.).
60
+ progress_callback (Callable[[str, DownloadModelStatus], Awaitable[Any]]):
61
+ An asynchronous function to call with progress updates.
62
+
63
+ Returns:
64
+ DownloadModelStatus: The result of the download operation.
65
+ """
66
+ if not validate_model_subdirectory(model_sub_directory):
67
+ return DownloadModelStatus(
68
+ DownloadStatusType.ERROR,
69
+ 0,
70
+ "Invalid model subdirectory",
71
+ False
72
+ )
73
+
74
+ if not validate_filename(model_name):
75
+ return DownloadModelStatus(
76
+ DownloadStatusType.ERROR,
77
+ 0,
78
+ "Invalid model name",
79
+ False
80
+ )
81
+
82
+ file_path, relative_path = create_model_path(model_name, model_sub_directory, models_dir)
83
+ existing_file = await check_file_exists(file_path, model_name, progress_callback, relative_path)
84
+ if existing_file:
85
+ return existing_file
86
+
87
+ try:
88
+ status = DownloadModelStatus(DownloadStatusType.PENDING, 0, f"Starting download of {model_name}", False)
89
+ await progress_callback(relative_path, status)
90
+
91
+ response = await model_download_request(model_url)
92
+ if response.status != 200:
93
+ error_message = f"Failed to download {model_name}. Status code: {response.status}"
94
+ logging.error(error_message)
95
+ status = DownloadModelStatus(DownloadStatusType.ERROR, 0, error_message, False)
96
+ await progress_callback(relative_path, status)
97
+ return DownloadModelStatus(DownloadStatusType.ERROR, 0, error_message, False)
98
+
99
+ return await track_download_progress(response, file_path, model_name, progress_callback, relative_path, progress_interval)
100
+
101
+ except Exception as e:
102
+ logging.error(f"Error in downloading model: {e}")
103
+ return await handle_download_error(e, model_name, progress_callback, relative_path)
104
+
105
+
106
+ def create_model_path(model_name: str, model_directory: str, models_base_dir: str) -> tuple[str, str]:
107
+ full_model_dir = os.path.join(models_base_dir, model_directory)
108
+ os.makedirs(full_model_dir, exist_ok=True)
109
+ file_path = os.path.join(full_model_dir, model_name)
110
+
111
+ # Ensure the resulting path is still within the base directory
112
+ abs_file_path = os.path.abspath(file_path)
113
+ abs_base_dir = os.path.abspath(str(models_base_dir))
114
+ if os.path.commonprefix([abs_file_path, abs_base_dir]) != abs_base_dir:
115
+ raise Exception(f"Invalid model directory: {model_directory}/{model_name}")
116
+
117
+
118
+ relative_path = '/'.join([model_directory, model_name])
119
+ return file_path, relative_path
120
+
121
+ async def check_file_exists(file_path: str,
122
+ model_name: str,
123
+ progress_callback: Callable[[str, DownloadModelStatus], Awaitable[Any]],
124
+ relative_path: str) -> Optional[DownloadModelStatus]:
125
+ if os.path.exists(file_path):
126
+ status = DownloadModelStatus(DownloadStatusType.COMPLETED, 100, f"{model_name} already exists", True)
127
+ await progress_callback(relative_path, status)
128
+ return status
129
+ return None
130
+
131
+
132
+ async def track_download_progress(response: aiohttp.ClientResponse,
133
+ file_path: str,
134
+ model_name: str,
135
+ progress_callback: Callable[[str, DownloadModelStatus], Awaitable[Any]],
136
+ relative_path: str,
137
+ interval: float = 1.0) -> DownloadModelStatus:
138
+ try:
139
+ total_size = int(response.headers.get('Content-Length', 0))
140
+ downloaded = 0
141
+ last_update_time = time.time()
142
+
143
+ async def update_progress():
144
+ nonlocal last_update_time
145
+ progress = (downloaded / total_size) * 100 if total_size > 0 else 0
146
+ status = DownloadModelStatus(DownloadStatusType.IN_PROGRESS, progress, f"Downloading {model_name}", False)
147
+ await progress_callback(relative_path, status)
148
+ last_update_time = time.time()
149
+
150
+ with open(file_path, 'wb') as f:
151
+ chunk_iterator = response.content.iter_chunked(8192)
152
+ while True:
153
+ try:
154
+ chunk = await chunk_iterator.__anext__()
155
+ except StopAsyncIteration:
156
+ break
157
+ f.write(chunk)
158
+ downloaded += len(chunk)
159
+
160
+ if time.time() - last_update_time >= interval:
161
+ await update_progress()
162
+
163
+ await update_progress()
164
+
165
+ logging.info(f"Successfully downloaded {model_name}. Total downloaded: {downloaded}")
166
+ status = DownloadModelStatus(DownloadStatusType.COMPLETED, 100, f"Successfully downloaded {model_name}", False)
167
+ await progress_callback(relative_path, status)
168
+
169
+ return status
170
+ except Exception as e:
171
+ logging.error(f"Error in track_download_progress: {e}")
172
+ logging.error(traceback.format_exc())
173
+ return await handle_download_error(e, model_name, progress_callback, relative_path)
174
+
175
+ async def handle_download_error(e: Exception,
176
+ model_name: str,
177
+ progress_callback: Callable[[str, DownloadModelStatus], Any],
178
+ relative_path: str) -> DownloadModelStatus:
179
+ error_message = f"Error downloading {model_name}: {str(e)}"
180
+ status = DownloadModelStatus(DownloadStatusType.ERROR, 0, error_message, False)
181
+ await progress_callback(relative_path, status)
182
+ return status
183
+
184
+ def validate_model_subdirectory(model_subdirectory: str) -> bool:
185
+ """
186
+ Validate that the model subdirectory is safe to install into.
187
+ Must not contain relative paths, nested paths or special characters
188
+ other than underscores and hyphens.
189
+
190
+ Args:
191
+ model_subdirectory (str): The subdirectory for the specific model type.
192
+
193
+ Returns:
194
+ bool: True if the subdirectory is safe, False otherwise.
195
+ """
196
+ if len(model_subdirectory) > 50:
197
+ return False
198
+
199
+ if '..' in model_subdirectory or '/' in model_subdirectory:
200
+ return False
201
+
202
+ if not re.match(r'^[a-zA-Z0-9_-]+$', model_subdirectory):
203
+ return False
204
+
205
+ return True
206
+
207
+ def validate_filename(filename: str)-> bool:
208
+ """
209
+ Validate a filename to ensure it's safe and doesn't contain any path traversal attempts.
210
+
211
+ Args:
212
+ filename (str): The filename to validate
213
+
214
+ Returns:
215
+ bool: True if the filename is valid, False otherwise
216
+ """
217
+ if not filename.lower().endswith(('.sft', '.safetensors')):
218
+ return False
219
+
220
+ # Check if the filename is empty, None, or just whitespace
221
+ if not filename or not filename.strip():
222
+ return False
223
+
224
+ # Check for any directory traversal attempts or invalid characters
225
+ if any(char in filename for char in ['..', '/', '\\', '\n', '\r', '\t', '\0']):
226
+ return False
227
+
228
+ # Check if the filename starts with a dot (hidden file)
229
+ if filename.startswith('.'):
230
+ return False
231
+
232
+ # Use a whitelist of allowed characters
233
+ if not re.match(r'^[a-zA-Z0-9_\-. ]+$', filename):
234
+ return False
235
+
236
+ # Ensure the filename isn't too long
237
+ if len(filename) > 255:
238
+ return False
239
+
240
+ return True
models/checkpoints/put_checkpoints_here ADDED
File without changes
models/clip/put_clip_or_text_encoder_models_here ADDED
File without changes
models/clip_vision/put_clip_vision_models_here ADDED
File without changes
models/configs/anything_v3.yaml ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 1.0e-04
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.00085
6
+ linear_end: 0.0120
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: "jpg"
11
+ cond_stage_key: "txt"
12
+ image_size: 64
13
+ channels: 4
14
+ cond_stage_trainable: false # Note: different from the one we trained before
15
+ conditioning_key: crossattn
16
+ monitor: val/loss_simple_ema
17
+ scale_factor: 0.18215
18
+ use_ema: False
19
+
20
+ scheduler_config: # 10000 warmup steps
21
+ target: ldm.lr_scheduler.LambdaLinearScheduler
22
+ params:
23
+ warm_up_steps: [ 10000 ]
24
+ cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
25
+ f_start: [ 1.e-6 ]
26
+ f_max: [ 1. ]
27
+ f_min: [ 1. ]
28
+
29
+ unet_config:
30
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
31
+ params:
32
+ image_size: 32 # unused
33
+ in_channels: 4
34
+ out_channels: 4
35
+ model_channels: 320
36
+ attention_resolutions: [ 4, 2, 1 ]
37
+ num_res_blocks: 2
38
+ channel_mult: [ 1, 2, 4, 4 ]
39
+ num_heads: 8
40
+ use_spatial_transformer: True
41
+ transformer_depth: 1
42
+ context_dim: 768
43
+ use_checkpoint: True
44
+ legacy: False
45
+
46
+ first_stage_config:
47
+ target: ldm.models.autoencoder.AutoencoderKL
48
+ params:
49
+ embed_dim: 4
50
+ monitor: val/rec_loss
51
+ ddconfig:
52
+ double_z: true
53
+ z_channels: 4
54
+ resolution: 256
55
+ in_channels: 3
56
+ out_ch: 3
57
+ ch: 128
58
+ ch_mult:
59
+ - 1
60
+ - 2
61
+ - 4
62
+ - 4
63
+ num_res_blocks: 2
64
+ attn_resolutions: []
65
+ dropout: 0.0
66
+ lossconfig:
67
+ target: torch.nn.Identity
68
+
69
+ cond_stage_config:
70
+ target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
71
+ params:
72
+ layer: "hidden"
73
+ layer_idx: -2
models/configs/v1-inference.yaml ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 1.0e-04
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.00085
6
+ linear_end: 0.0120
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: "jpg"
11
+ cond_stage_key: "txt"
12
+ image_size: 64
13
+ channels: 4
14
+ cond_stage_trainable: false # Note: different from the one we trained before
15
+ conditioning_key: crossattn
16
+ monitor: val/loss_simple_ema
17
+ scale_factor: 0.18215
18
+ use_ema: False
19
+
20
+ scheduler_config: # 10000 warmup steps
21
+ target: ldm.lr_scheduler.LambdaLinearScheduler
22
+ params:
23
+ warm_up_steps: [ 10000 ]
24
+ cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
25
+ f_start: [ 1.e-6 ]
26
+ f_max: [ 1. ]
27
+ f_min: [ 1. ]
28
+
29
+ unet_config:
30
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
31
+ params:
32
+ image_size: 32 # unused
33
+ in_channels: 4
34
+ out_channels: 4
35
+ model_channels: 320
36
+ attention_resolutions: [ 4, 2, 1 ]
37
+ num_res_blocks: 2
38
+ channel_mult: [ 1, 2, 4, 4 ]
39
+ num_heads: 8
40
+ use_spatial_transformer: True
41
+ transformer_depth: 1
42
+ context_dim: 768
43
+ use_checkpoint: True
44
+ legacy: False
45
+
46
+ first_stage_config:
47
+ target: ldm.models.autoencoder.AutoencoderKL
48
+ params:
49
+ embed_dim: 4
50
+ monitor: val/rec_loss
51
+ ddconfig:
52
+ double_z: true
53
+ z_channels: 4
54
+ resolution: 256
55
+ in_channels: 3
56
+ out_ch: 3
57
+ ch: 128
58
+ ch_mult:
59
+ - 1
60
+ - 2
61
+ - 4
62
+ - 4
63
+ num_res_blocks: 2
64
+ attn_resolutions: []
65
+ dropout: 0.0
66
+ lossconfig:
67
+ target: torch.nn.Identity
68
+
69
+ cond_stage_config:
70
+ target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
models/configs/v1-inference_clip_skip_2.yaml ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 1.0e-04
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.00085
6
+ linear_end: 0.0120
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: "jpg"
11
+ cond_stage_key: "txt"
12
+ image_size: 64
13
+ channels: 4
14
+ cond_stage_trainable: false # Note: different from the one we trained before
15
+ conditioning_key: crossattn
16
+ monitor: val/loss_simple_ema
17
+ scale_factor: 0.18215
18
+ use_ema: False
19
+
20
+ scheduler_config: # 10000 warmup steps
21
+ target: ldm.lr_scheduler.LambdaLinearScheduler
22
+ params:
23
+ warm_up_steps: [ 10000 ]
24
+ cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
25
+ f_start: [ 1.e-6 ]
26
+ f_max: [ 1. ]
27
+ f_min: [ 1. ]
28
+
29
+ unet_config:
30
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
31
+ params:
32
+ image_size: 32 # unused
33
+ in_channels: 4
34
+ out_channels: 4
35
+ model_channels: 320
36
+ attention_resolutions: [ 4, 2, 1 ]
37
+ num_res_blocks: 2
38
+ channel_mult: [ 1, 2, 4, 4 ]
39
+ num_heads: 8
40
+ use_spatial_transformer: True
41
+ transformer_depth: 1
42
+ context_dim: 768
43
+ use_checkpoint: True
44
+ legacy: False
45
+
46
+ first_stage_config:
47
+ target: ldm.models.autoencoder.AutoencoderKL
48
+ params:
49
+ embed_dim: 4
50
+ monitor: val/rec_loss
51
+ ddconfig:
52
+ double_z: true
53
+ z_channels: 4
54
+ resolution: 256
55
+ in_channels: 3
56
+ out_ch: 3
57
+ ch: 128
58
+ ch_mult:
59
+ - 1
60
+ - 2
61
+ - 4
62
+ - 4
63
+ num_res_blocks: 2
64
+ attn_resolutions: []
65
+ dropout: 0.0
66
+ lossconfig:
67
+ target: torch.nn.Identity
68
+
69
+ cond_stage_config:
70
+ target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
71
+ params:
72
+ layer: "hidden"
73
+ layer_idx: -2
models/configs/v1-inference_clip_skip_2_fp16.yaml ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 1.0e-04
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.00085
6
+ linear_end: 0.0120
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: "jpg"
11
+ cond_stage_key: "txt"
12
+ image_size: 64
13
+ channels: 4
14
+ cond_stage_trainable: false # Note: different from the one we trained before
15
+ conditioning_key: crossattn
16
+ monitor: val/loss_simple_ema
17
+ scale_factor: 0.18215
18
+ use_ema: False
19
+
20
+ scheduler_config: # 10000 warmup steps
21
+ target: ldm.lr_scheduler.LambdaLinearScheduler
22
+ params:
23
+ warm_up_steps: [ 10000 ]
24
+ cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
25
+ f_start: [ 1.e-6 ]
26
+ f_max: [ 1. ]
27
+ f_min: [ 1. ]
28
+
29
+ unet_config:
30
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
31
+ params:
32
+ use_fp16: True
33
+ image_size: 32 # unused
34
+ in_channels: 4
35
+ out_channels: 4
36
+ model_channels: 320
37
+ attention_resolutions: [ 4, 2, 1 ]
38
+ num_res_blocks: 2
39
+ channel_mult: [ 1, 2, 4, 4 ]
40
+ num_heads: 8
41
+ use_spatial_transformer: True
42
+ transformer_depth: 1
43
+ context_dim: 768
44
+ use_checkpoint: True
45
+ legacy: False
46
+
47
+ first_stage_config:
48
+ target: ldm.models.autoencoder.AutoencoderKL
49
+ params:
50
+ embed_dim: 4
51
+ monitor: val/rec_loss
52
+ ddconfig:
53
+ double_z: true
54
+ z_channels: 4
55
+ resolution: 256
56
+ in_channels: 3
57
+ out_ch: 3
58
+ ch: 128
59
+ ch_mult:
60
+ - 1
61
+ - 2
62
+ - 4
63
+ - 4
64
+ num_res_blocks: 2
65
+ attn_resolutions: []
66
+ dropout: 0.0
67
+ lossconfig:
68
+ target: torch.nn.Identity
69
+
70
+ cond_stage_config:
71
+ target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
72
+ params:
73
+ layer: "hidden"
74
+ layer_idx: -2
models/configs/v1-inference_fp16.yaml ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 1.0e-04
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.00085
6
+ linear_end: 0.0120
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: "jpg"
11
+ cond_stage_key: "txt"
12
+ image_size: 64
13
+ channels: 4
14
+ cond_stage_trainable: false # Note: different from the one we trained before
15
+ conditioning_key: crossattn
16
+ monitor: val/loss_simple_ema
17
+ scale_factor: 0.18215
18
+ use_ema: False
19
+
20
+ scheduler_config: # 10000 warmup steps
21
+ target: ldm.lr_scheduler.LambdaLinearScheduler
22
+ params:
23
+ warm_up_steps: [ 10000 ]
24
+ cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
25
+ f_start: [ 1.e-6 ]
26
+ f_max: [ 1. ]
27
+ f_min: [ 1. ]
28
+
29
+ unet_config:
30
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
31
+ params:
32
+ use_fp16: True
33
+ image_size: 32 # unused
34
+ in_channels: 4
35
+ out_channels: 4
36
+ model_channels: 320
37
+ attention_resolutions: [ 4, 2, 1 ]
38
+ num_res_blocks: 2
39
+ channel_mult: [ 1, 2, 4, 4 ]
40
+ num_heads: 8
41
+ use_spatial_transformer: True
42
+ transformer_depth: 1
43
+ context_dim: 768
44
+ use_checkpoint: True
45
+ legacy: False
46
+
47
+ first_stage_config:
48
+ target: ldm.models.autoencoder.AutoencoderKL
49
+ params:
50
+ embed_dim: 4
51
+ monitor: val/rec_loss
52
+ ddconfig:
53
+ double_z: true
54
+ z_channels: 4
55
+ resolution: 256
56
+ in_channels: 3
57
+ out_ch: 3
58
+ ch: 128
59
+ ch_mult:
60
+ - 1
61
+ - 2
62
+ - 4
63
+ - 4
64
+ num_res_blocks: 2
65
+ attn_resolutions: []
66
+ dropout: 0.0
67
+ lossconfig:
68
+ target: torch.nn.Identity
69
+
70
+ cond_stage_config:
71
+ target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
models/configs/v1-inpainting-inference.yaml ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 7.5e-05
3
+ target: ldm.models.diffusion.ddpm.LatentInpaintDiffusion
4
+ params:
5
+ linear_start: 0.00085
6
+ linear_end: 0.0120
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: "jpg"
11
+ cond_stage_key: "txt"
12
+ image_size: 64
13
+ channels: 4
14
+ cond_stage_trainable: false # Note: different from the one we trained before
15
+ conditioning_key: hybrid # important
16
+ monitor: val/loss_simple_ema
17
+ scale_factor: 0.18215
18
+ finetune_keys: null
19
+
20
+ scheduler_config: # 10000 warmup steps
21
+ target: ldm.lr_scheduler.LambdaLinearScheduler
22
+ params:
23
+ warm_up_steps: [ 2500 ] # NOTE for resuming. use 10000 if starting from scratch
24
+ cycle_lengths: [ 10000000000000 ] # incredibly large number to prevent corner cases
25
+ f_start: [ 1.e-6 ]
26
+ f_max: [ 1. ]
27
+ f_min: [ 1. ]
28
+
29
+ unet_config:
30
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
31
+ params:
32
+ image_size: 32 # unused
33
+ in_channels: 9 # 4 data + 4 downscaled image + 1 mask
34
+ out_channels: 4
35
+ model_channels: 320
36
+ attention_resolutions: [ 4, 2, 1 ]
37
+ num_res_blocks: 2
38
+ channel_mult: [ 1, 2, 4, 4 ]
39
+ num_heads: 8
40
+ use_spatial_transformer: True
41
+ transformer_depth: 1
42
+ context_dim: 768
43
+ use_checkpoint: True
44
+ legacy: False
45
+
46
+ first_stage_config:
47
+ target: ldm.models.autoencoder.AutoencoderKL
48
+ params:
49
+ embed_dim: 4
50
+ monitor: val/rec_loss
51
+ ddconfig:
52
+ double_z: true
53
+ z_channels: 4
54
+ resolution: 256
55
+ in_channels: 3
56
+ out_ch: 3
57
+ ch: 128
58
+ ch_mult:
59
+ - 1
60
+ - 2
61
+ - 4
62
+ - 4
63
+ num_res_blocks: 2
64
+ attn_resolutions: []
65
+ dropout: 0.0
66
+ lossconfig:
67
+ target: torch.nn.Identity
68
+
69
+ cond_stage_config:
70
+ target: ldm.modules.encoders.modules.FrozenCLIPEmbedder
71
+
models/configs/v2-inference-v.yaml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 1.0e-4
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ parameterization: "v"
6
+ linear_start: 0.00085
7
+ linear_end: 0.0120
8
+ num_timesteps_cond: 1
9
+ log_every_t: 200
10
+ timesteps: 1000
11
+ first_stage_key: "jpg"
12
+ cond_stage_key: "txt"
13
+ image_size: 64
14
+ channels: 4
15
+ cond_stage_trainable: false
16
+ conditioning_key: crossattn
17
+ monitor: val/loss_simple_ema
18
+ scale_factor: 0.18215
19
+ use_ema: False # we set this to false because this is an inference only config
20
+
21
+ unet_config:
22
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
23
+ params:
24
+ use_checkpoint: True
25
+ use_fp16: True
26
+ image_size: 32 # unused
27
+ in_channels: 4
28
+ out_channels: 4
29
+ model_channels: 320
30
+ attention_resolutions: [ 4, 2, 1 ]
31
+ num_res_blocks: 2
32
+ channel_mult: [ 1, 2, 4, 4 ]
33
+ num_head_channels: 64 # need to fix for flash-attn
34
+ use_spatial_transformer: True
35
+ use_linear_in_transformer: True
36
+ transformer_depth: 1
37
+ context_dim: 1024
38
+ legacy: False
39
+
40
+ first_stage_config:
41
+ target: ldm.models.autoencoder.AutoencoderKL
42
+ params:
43
+ embed_dim: 4
44
+ monitor: val/rec_loss
45
+ ddconfig:
46
+ #attn_type: "vanilla-xformers"
47
+ double_z: true
48
+ z_channels: 4
49
+ resolution: 256
50
+ in_channels: 3
51
+ out_ch: 3
52
+ ch: 128
53
+ ch_mult:
54
+ - 1
55
+ - 2
56
+ - 4
57
+ - 4
58
+ num_res_blocks: 2
59
+ attn_resolutions: []
60
+ dropout: 0.0
61
+ lossconfig:
62
+ target: torch.nn.Identity
63
+
64
+ cond_stage_config:
65
+ target: ldm.modules.encoders.modules.FrozenOpenCLIPEmbedder
66
+ params:
67
+ freeze: True
68
+ layer: "penultimate"
models/configs/v2-inference-v_fp32.yaml ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 1.0e-4
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ parameterization: "v"
6
+ linear_start: 0.00085
7
+ linear_end: 0.0120
8
+ num_timesteps_cond: 1
9
+ log_every_t: 200
10
+ timesteps: 1000
11
+ first_stage_key: "jpg"
12
+ cond_stage_key: "txt"
13
+ image_size: 64
14
+ channels: 4
15
+ cond_stage_trainable: false
16
+ conditioning_key: crossattn
17
+ monitor: val/loss_simple_ema
18
+ scale_factor: 0.18215
19
+ use_ema: False # we set this to false because this is an inference only config
20
+
21
+ unet_config:
22
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
23
+ params:
24
+ use_checkpoint: True
25
+ use_fp16: False
26
+ image_size: 32 # unused
27
+ in_channels: 4
28
+ out_channels: 4
29
+ model_channels: 320
30
+ attention_resolutions: [ 4, 2, 1 ]
31
+ num_res_blocks: 2
32
+ channel_mult: [ 1, 2, 4, 4 ]
33
+ num_head_channels: 64 # need to fix for flash-attn
34
+ use_spatial_transformer: True
35
+ use_linear_in_transformer: True
36
+ transformer_depth: 1
37
+ context_dim: 1024
38
+ legacy: False
39
+
40
+ first_stage_config:
41
+ target: ldm.models.autoencoder.AutoencoderKL
42
+ params:
43
+ embed_dim: 4
44
+ monitor: val/rec_loss
45
+ ddconfig:
46
+ #attn_type: "vanilla-xformers"
47
+ double_z: true
48
+ z_channels: 4
49
+ resolution: 256
50
+ in_channels: 3
51
+ out_ch: 3
52
+ ch: 128
53
+ ch_mult:
54
+ - 1
55
+ - 2
56
+ - 4
57
+ - 4
58
+ num_res_blocks: 2
59
+ attn_resolutions: []
60
+ dropout: 0.0
61
+ lossconfig:
62
+ target: torch.nn.Identity
63
+
64
+ cond_stage_config:
65
+ target: ldm.modules.encoders.modules.FrozenOpenCLIPEmbedder
66
+ params:
67
+ freeze: True
68
+ layer: "penultimate"
models/configs/v2-inference.yaml ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 1.0e-4
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.00085
6
+ linear_end: 0.0120
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: "jpg"
11
+ cond_stage_key: "txt"
12
+ image_size: 64
13
+ channels: 4
14
+ cond_stage_trainable: false
15
+ conditioning_key: crossattn
16
+ monitor: val/loss_simple_ema
17
+ scale_factor: 0.18215
18
+ use_ema: False # we set this to false because this is an inference only config
19
+
20
+ unet_config:
21
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
22
+ params:
23
+ use_checkpoint: True
24
+ use_fp16: True
25
+ image_size: 32 # unused
26
+ in_channels: 4
27
+ out_channels: 4
28
+ model_channels: 320
29
+ attention_resolutions: [ 4, 2, 1 ]
30
+ num_res_blocks: 2
31
+ channel_mult: [ 1, 2, 4, 4 ]
32
+ num_head_channels: 64 # need to fix for flash-attn
33
+ use_spatial_transformer: True
34
+ use_linear_in_transformer: True
35
+ transformer_depth: 1
36
+ context_dim: 1024
37
+ legacy: False
38
+
39
+ first_stage_config:
40
+ target: ldm.models.autoencoder.AutoencoderKL
41
+ params:
42
+ embed_dim: 4
43
+ monitor: val/rec_loss
44
+ ddconfig:
45
+ #attn_type: "vanilla-xformers"
46
+ double_z: true
47
+ z_channels: 4
48
+ resolution: 256
49
+ in_channels: 3
50
+ out_ch: 3
51
+ ch: 128
52
+ ch_mult:
53
+ - 1
54
+ - 2
55
+ - 4
56
+ - 4
57
+ num_res_blocks: 2
58
+ attn_resolutions: []
59
+ dropout: 0.0
60
+ lossconfig:
61
+ target: torch.nn.Identity
62
+
63
+ cond_stage_config:
64
+ target: ldm.modules.encoders.modules.FrozenOpenCLIPEmbedder
65
+ params:
66
+ freeze: True
67
+ layer: "penultimate"
models/configs/v2-inference_fp32.yaml ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 1.0e-4
3
+ target: ldm.models.diffusion.ddpm.LatentDiffusion
4
+ params:
5
+ linear_start: 0.00085
6
+ linear_end: 0.0120
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: "jpg"
11
+ cond_stage_key: "txt"
12
+ image_size: 64
13
+ channels: 4
14
+ cond_stage_trainable: false
15
+ conditioning_key: crossattn
16
+ monitor: val/loss_simple_ema
17
+ scale_factor: 0.18215
18
+ use_ema: False # we set this to false because this is an inference only config
19
+
20
+ unet_config:
21
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
22
+ params:
23
+ use_checkpoint: True
24
+ use_fp16: False
25
+ image_size: 32 # unused
26
+ in_channels: 4
27
+ out_channels: 4
28
+ model_channels: 320
29
+ attention_resolutions: [ 4, 2, 1 ]
30
+ num_res_blocks: 2
31
+ channel_mult: [ 1, 2, 4, 4 ]
32
+ num_head_channels: 64 # need to fix for flash-attn
33
+ use_spatial_transformer: True
34
+ use_linear_in_transformer: True
35
+ transformer_depth: 1
36
+ context_dim: 1024
37
+ legacy: False
38
+
39
+ first_stage_config:
40
+ target: ldm.models.autoencoder.AutoencoderKL
41
+ params:
42
+ embed_dim: 4
43
+ monitor: val/rec_loss
44
+ ddconfig:
45
+ #attn_type: "vanilla-xformers"
46
+ double_z: true
47
+ z_channels: 4
48
+ resolution: 256
49
+ in_channels: 3
50
+ out_ch: 3
51
+ ch: 128
52
+ ch_mult:
53
+ - 1
54
+ - 2
55
+ - 4
56
+ - 4
57
+ num_res_blocks: 2
58
+ attn_resolutions: []
59
+ dropout: 0.0
60
+ lossconfig:
61
+ target: torch.nn.Identity
62
+
63
+ cond_stage_config:
64
+ target: ldm.modules.encoders.modules.FrozenOpenCLIPEmbedder
65
+ params:
66
+ freeze: True
67
+ layer: "penultimate"
models/configs/v2-inpainting-inference.yaml ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ model:
2
+ base_learning_rate: 5.0e-05
3
+ target: ldm.models.diffusion.ddpm.LatentInpaintDiffusion
4
+ params:
5
+ linear_start: 0.00085
6
+ linear_end: 0.0120
7
+ num_timesteps_cond: 1
8
+ log_every_t: 200
9
+ timesteps: 1000
10
+ first_stage_key: "jpg"
11
+ cond_stage_key: "txt"
12
+ image_size: 64
13
+ channels: 4
14
+ cond_stage_trainable: false
15
+ conditioning_key: hybrid
16
+ scale_factor: 0.18215
17
+ monitor: val/loss_simple_ema
18
+ finetune_keys: null
19
+ use_ema: False
20
+
21
+ unet_config:
22
+ target: ldm.modules.diffusionmodules.openaimodel.UNetModel
23
+ params:
24
+ use_checkpoint: True
25
+ image_size: 32 # unused
26
+ in_channels: 9
27
+ out_channels: 4
28
+ model_channels: 320
29
+ attention_resolutions: [ 4, 2, 1 ]
30
+ num_res_blocks: 2
31
+ channel_mult: [ 1, 2, 4, 4 ]
32
+ num_head_channels: 64 # need to fix for flash-attn
33
+ use_spatial_transformer: True
34
+ use_linear_in_transformer: True
35
+ transformer_depth: 1
36
+ context_dim: 1024
37
+ legacy: False
38
+
39
+ first_stage_config:
40
+ target: ldm.models.autoencoder.AutoencoderKL
41
+ params:
42
+ embed_dim: 4
43
+ monitor: val/rec_loss
44
+ ddconfig:
45
+ #attn_type: "vanilla-xformers"
46
+ double_z: true
47
+ z_channels: 4
48
+ resolution: 256
49
+ in_channels: 3
50
+ out_ch: 3
51
+ ch: 128
52
+ ch_mult:
53
+ - 1
54
+ - 2
55
+ - 4
56
+ - 4
57
+ num_res_blocks: 2
58
+ attn_resolutions: [ ]
59
+ dropout: 0.0
60
+ lossconfig:
61
+ target: torch.nn.Identity
62
+
63
+ cond_stage_config:
64
+ target: ldm.modules.encoders.modules.FrozenOpenCLIPEmbedder
65
+ params:
66
+ freeze: True
67
+ layer: "penultimate"
68
+
69
+
70
+ data:
71
+ target: ldm.data.laion.WebDataModuleFromConfig
72
+ params:
73
+ tar_base: null # for concat as in LAION-A
74
+ p_unsafe_threshold: 0.1
75
+ filter_word_list: "data/filters.yaml"
76
+ max_pwatermark: 0.45
77
+ batch_size: 8
78
+ num_workers: 6
79
+ multinode: True
80
+ min_size: 512
81
+ train:
82
+ shards:
83
+ - "pipe:aws s3 cp s3://stability-aws/laion-a-native/part-0/{00000..18699}.tar -"
84
+ - "pipe:aws s3 cp s3://stability-aws/laion-a-native/part-1/{00000..18699}.tar -"
85
+ - "pipe:aws s3 cp s3://stability-aws/laion-a-native/part-2/{00000..18699}.tar -"
86
+ - "pipe:aws s3 cp s3://stability-aws/laion-a-native/part-3/{00000..18699}.tar -"
87
+ - "pipe:aws s3 cp s3://stability-aws/laion-a-native/part-4/{00000..18699}.tar -" #{00000-94333}.tar"
88
+ shuffle: 10000
89
+ image_key: jpg
90
+ image_transforms:
91
+ - target: torchvision.transforms.Resize
92
+ params:
93
+ size: 512
94
+ interpolation: 3
95
+ - target: torchvision.transforms.RandomCrop
96
+ params:
97
+ size: 512
98
+ postprocess:
99
+ target: ldm.data.laion.AddMask
100
+ params:
101
+ mode: "512train-large"
102
+ p_drop: 0.25
103
+ # NOTE use enough shards to avoid empty validation loops in workers
104
+ validation:
105
+ shards:
106
+ - "pipe:aws s3 cp s3://deep-floyd-s3/datasets/laion_cleaned-part5/{93001..94333}.tar - "
107
+ shuffle: 0
108
+ image_key: jpg
109
+ image_transforms:
110
+ - target: torchvision.transforms.Resize
111
+ params:
112
+ size: 512
113
+ interpolation: 3
114
+ - target: torchvision.transforms.CenterCrop
115
+ params:
116
+ size: 512
117
+ postprocess:
118
+ target: ldm.data.laion.AddMask
119
+ params:
120
+ mode: "512train-large"
121
+ p_drop: 0.25
122
+
123
+ lightning:
124
+ find_unused_parameters: True
125
+ modelcheckpoint:
126
+ params:
127
+ every_n_train_steps: 5000
128
+
129
+ callbacks:
130
+ metrics_over_trainsteps_checkpoint:
131
+ params:
132
+ every_n_train_steps: 10000
133
+
134
+ image_logger:
135
+ target: main.ImageLogger
136
+ params:
137
+ enable_autocast: False
138
+ disabled: False
139
+ batch_frequency: 1000
140
+ max_images: 4
141
+ increase_log_steps: False
142
+ log_first_step: False
143
+ log_images_kwargs:
144
+ use_ema_scope: False
145
+ inpaint: False
146
+ plot_progressive_rows: False
147
+ plot_diffusion_rows: False
148
+ N: 4
149
+ unconditional_guidance_scale: 5.0
150
+ unconditional_guidance_label: [""]
151
+ ddim_steps: 50 # todo check these out for depth2img,
152
+ ddim_eta: 0.0 # todo check these out for depth2img,
153
+
154
+ trainer:
155
+ benchmark: True
156
+ val_check_interval: 5000000
157
+ num_sanity_val_steps: 0
158
+ accumulate_grad_batches: 1
models/controlnet/put_controlnets_and_t2i_here ADDED
File without changes
models/diffusers/put_diffusers_models_here ADDED
File without changes
models/diffusion_models/put_diffusion_model_files_here ADDED
File without changes
models/embeddings/put_embeddings_or_textual_inversion_concepts_here ADDED
File without changes
models/gligen/put_gligen_models_here ADDED
File without changes
models/hypernetworks/put_hypernetworks_here ADDED
File without changes
models/loras/put_loras_here ADDED
File without changes
models/photomaker/put_photomaker_models_here ADDED
File without changes
models/style_models/put_t2i_style_model_here ADDED
File without changes
models/unet/put_unet_files_here ADDED
File without changes
models/upscale_models/put_esrgan_and_other_upscale_models_here ADDED
File without changes
models/vae/put_vae_here ADDED
File without changes
models/vae_approx/put_taesd_encoder_pth_and_taesd_decoder_pth_here ADDED
File without changes
new_updater.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+
4
+ base_path = os.path.dirname(os.path.realpath(__file__))
5
+
6
+
7
+ def update_windows_updater():
8
+ top_path = os.path.dirname(base_path)
9
+ updater_path = os.path.join(base_path, ".ci/update_windows/update.py")
10
+ bat_path = os.path.join(base_path, ".ci/update_windows/update_comfyui.bat")
11
+
12
+ dest_updater_path = os.path.join(top_path, "update/update.py")
13
+ dest_bat_path = os.path.join(top_path, "update/update_comfyui.bat")
14
+ dest_bat_deps_path = os.path.join(top_path, "update/update_comfyui_and_python_dependencies.bat")
15
+
16
+ try:
17
+ with open(dest_bat_path, 'rb') as f:
18
+ contents = f.read()
19
+ except:
20
+ return
21
+
22
+ if not contents.startswith(b"..\\python_embedded\\python.exe .\\update.py"):
23
+ return
24
+
25
+ shutil.copy(updater_path, dest_updater_path)
26
+ try:
27
+ with open(dest_bat_deps_path, 'rb') as f:
28
+ contents = f.read()
29
+ contents = contents.replace(b'..\\python_embedded\\python.exe .\\update.py ..\\ComfyUI\\', b'call update_comfyui.bat nopause')
30
+ with open(dest_bat_deps_path, 'wb') as f:
31
+ f.write(contents)
32
+ except:
33
+ pass
34
+ shutil.copy(bat_path, dest_bat_path)
35
+ print("Updated the windows standalone package updater.")
node_helpers.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+
3
+ from comfy.cli_args import args
4
+
5
+ from PIL import ImageFile, UnidentifiedImageError
6
+
7
+ def conditioning_set_values(conditioning, values={}):
8
+ c = []
9
+ for t in conditioning:
10
+ n = [t[0], t[1].copy()]
11
+ for k in values:
12
+ n[1][k] = values[k]
13
+ c.append(n)
14
+
15
+ return c
16
+
17
+ def pillow(fn, arg):
18
+ prev_value = None
19
+ try:
20
+ x = fn(arg)
21
+ except (OSError, UnidentifiedImageError, ValueError): #PIL issues #4472 and #2445, also fixes ComfyUI issue #3416
22
+ prev_value = ImageFile.LOAD_TRUNCATED_IMAGES
23
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
24
+ x = fn(arg)
25
+ finally:
26
+ if prev_value is not None:
27
+ ImageFile.LOAD_TRUNCATED_IMAGES = prev_value
28
+ return x
29
+
30
+ def hasher():
31
+ hashfuncs = {
32
+ "md5": hashlib.md5,
33
+ "sha1": hashlib.sha1,
34
+ "sha256": hashlib.sha256,
35
+ "sha512": hashlib.sha512
36
+ }
37
+ return hashfuncs[args.default_hashing_function]
nodes.py ADDED
@@ -0,0 +1,2136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ import os
4
+ import sys
5
+ import json
6
+ import hashlib
7
+ import traceback
8
+ import math
9
+ import time
10
+ import random
11
+ import logging
12
+
13
+ from PIL import Image, ImageOps, ImageSequence, ImageFile
14
+ from PIL.PngImagePlugin import PngInfo
15
+
16
+ import numpy as np
17
+ import safetensors.torch
18
+
19
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy"))
20
+
21
+ import comfy.diffusers_load
22
+ import comfy.samplers
23
+ import comfy.sample
24
+ import comfy.sd
25
+ import comfy.utils
26
+ import comfy.controlnet
27
+
28
+ import comfy.clip_vision
29
+
30
+ import comfy.model_management
31
+ from comfy.cli_args import args
32
+
33
+ import importlib
34
+
35
+ import folder_paths
36
+ import latent_preview
37
+ import node_helpers
38
+
39
+ def before_node_execution():
40
+ comfy.model_management.throw_exception_if_processing_interrupted()
41
+
42
+ def interrupt_processing(value=True):
43
+ comfy.model_management.interrupt_current_processing(value)
44
+
45
+ MAX_RESOLUTION=16384
46
+
47
+ class CLIPTextEncode:
48
+ @classmethod
49
+ def INPUT_TYPES(s):
50
+ return {
51
+ "required": {
52
+ "text": ("STRING", {"multiline": True, "dynamicPrompts": True, "tooltip": "The text to be encoded."}),
53
+ "clip": ("CLIP", {"tooltip": "The CLIP model used for encoding the text."})
54
+ }
55
+ }
56
+ RETURN_TYPES = ("CONDITIONING",)
57
+ OUTPUT_TOOLTIPS = ("A conditioning containing the embedded text used to guide the diffusion model.",)
58
+ FUNCTION = "encode"
59
+
60
+ CATEGORY = "conditioning"
61
+ DESCRIPTION = "Encodes a text prompt using a CLIP model into an embedding that can be used to guide the diffusion model towards generating specific images."
62
+
63
+ def encode(self, clip, text):
64
+ tokens = clip.tokenize(text)
65
+ output = clip.encode_from_tokens(tokens, return_pooled=True, return_dict=True)
66
+ cond = output.pop("cond")
67
+ return ([[cond, output]], )
68
+
69
+ class ConditioningCombine:
70
+ @classmethod
71
+ def INPUT_TYPES(s):
72
+ return {"required": {"conditioning_1": ("CONDITIONING", ), "conditioning_2": ("CONDITIONING", )}}
73
+ RETURN_TYPES = ("CONDITIONING",)
74
+ FUNCTION = "combine"
75
+
76
+ CATEGORY = "conditioning"
77
+
78
+ def combine(self, conditioning_1, conditioning_2):
79
+ return (conditioning_1 + conditioning_2, )
80
+
81
+ class ConditioningAverage :
82
+ @classmethod
83
+ def INPUT_TYPES(s):
84
+ return {"required": {"conditioning_to": ("CONDITIONING", ), "conditioning_from": ("CONDITIONING", ),
85
+ "conditioning_to_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01})
86
+ }}
87
+ RETURN_TYPES = ("CONDITIONING",)
88
+ FUNCTION = "addWeighted"
89
+
90
+ CATEGORY = "conditioning"
91
+
92
+ def addWeighted(self, conditioning_to, conditioning_from, conditioning_to_strength):
93
+ out = []
94
+
95
+ if len(conditioning_from) > 1:
96
+ logging.warning("Warning: ConditioningAverage conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.")
97
+
98
+ cond_from = conditioning_from[0][0]
99
+ pooled_output_from = conditioning_from[0][1].get("pooled_output", None)
100
+
101
+ for i in range(len(conditioning_to)):
102
+ t1 = conditioning_to[i][0]
103
+ pooled_output_to = conditioning_to[i][1].get("pooled_output", pooled_output_from)
104
+ t0 = cond_from[:,:t1.shape[1]]
105
+ if t0.shape[1] < t1.shape[1]:
106
+ t0 = torch.cat([t0] + [torch.zeros((1, (t1.shape[1] - t0.shape[1]), t1.shape[2]))], dim=1)
107
+
108
+ tw = torch.mul(t1, conditioning_to_strength) + torch.mul(t0, (1.0 - conditioning_to_strength))
109
+ t_to = conditioning_to[i][1].copy()
110
+ if pooled_output_from is not None and pooled_output_to is not None:
111
+ t_to["pooled_output"] = torch.mul(pooled_output_to, conditioning_to_strength) + torch.mul(pooled_output_from, (1.0 - conditioning_to_strength))
112
+ elif pooled_output_from is not None:
113
+ t_to["pooled_output"] = pooled_output_from
114
+
115
+ n = [tw, t_to]
116
+ out.append(n)
117
+ return (out, )
118
+
119
+ class ConditioningConcat:
120
+ @classmethod
121
+ def INPUT_TYPES(s):
122
+ return {"required": {
123
+ "conditioning_to": ("CONDITIONING",),
124
+ "conditioning_from": ("CONDITIONING",),
125
+ }}
126
+ RETURN_TYPES = ("CONDITIONING",)
127
+ FUNCTION = "concat"
128
+
129
+ CATEGORY = "conditioning"
130
+
131
+ def concat(self, conditioning_to, conditioning_from):
132
+ out = []
133
+
134
+ if len(conditioning_from) > 1:
135
+ logging.warning("Warning: ConditioningConcat conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.")
136
+
137
+ cond_from = conditioning_from[0][0]
138
+
139
+ for i in range(len(conditioning_to)):
140
+ t1 = conditioning_to[i][0]
141
+ tw = torch.cat((t1, cond_from),1)
142
+ n = [tw, conditioning_to[i][1].copy()]
143
+ out.append(n)
144
+
145
+ return (out, )
146
+
147
+ class ConditioningSetArea:
148
+ @classmethod
149
+ def INPUT_TYPES(s):
150
+ return {"required": {"conditioning": ("CONDITIONING", ),
151
+ "width": ("INT", {"default": 64, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
152
+ "height": ("INT", {"default": 64, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
153
+ "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
154
+ "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
155
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
156
+ }}
157
+ RETURN_TYPES = ("CONDITIONING",)
158
+ FUNCTION = "append"
159
+
160
+ CATEGORY = "conditioning"
161
+
162
+ def append(self, conditioning, width, height, x, y, strength):
163
+ c = node_helpers.conditioning_set_values(conditioning, {"area": (height // 8, width // 8, y // 8, x // 8),
164
+ "strength": strength,
165
+ "set_area_to_bounds": False})
166
+ return (c, )
167
+
168
+ class ConditioningSetAreaPercentage:
169
+ @classmethod
170
+ def INPUT_TYPES(s):
171
+ return {"required": {"conditioning": ("CONDITIONING", ),
172
+ "width": ("FLOAT", {"default": 1.0, "min": 0, "max": 1.0, "step": 0.01}),
173
+ "height": ("FLOAT", {"default": 1.0, "min": 0, "max": 1.0, "step": 0.01}),
174
+ "x": ("FLOAT", {"default": 0, "min": 0, "max": 1.0, "step": 0.01}),
175
+ "y": ("FLOAT", {"default": 0, "min": 0, "max": 1.0, "step": 0.01}),
176
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
177
+ }}
178
+ RETURN_TYPES = ("CONDITIONING",)
179
+ FUNCTION = "append"
180
+
181
+ CATEGORY = "conditioning"
182
+
183
+ def append(self, conditioning, width, height, x, y, strength):
184
+ c = node_helpers.conditioning_set_values(conditioning, {"area": ("percentage", height, width, y, x),
185
+ "strength": strength,
186
+ "set_area_to_bounds": False})
187
+ return (c, )
188
+
189
+ class ConditioningSetAreaStrength:
190
+ @classmethod
191
+ def INPUT_TYPES(s):
192
+ return {"required": {"conditioning": ("CONDITIONING", ),
193
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
194
+ }}
195
+ RETURN_TYPES = ("CONDITIONING",)
196
+ FUNCTION = "append"
197
+
198
+ CATEGORY = "conditioning"
199
+
200
+ def append(self, conditioning, strength):
201
+ c = node_helpers.conditioning_set_values(conditioning, {"strength": strength})
202
+ return (c, )
203
+
204
+
205
+ class ConditioningSetMask:
206
+ @classmethod
207
+ def INPUT_TYPES(s):
208
+ return {"required": {"conditioning": ("CONDITIONING", ),
209
+ "mask": ("MASK", ),
210
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
211
+ "set_cond_area": (["default", "mask bounds"],),
212
+ }}
213
+ RETURN_TYPES = ("CONDITIONING",)
214
+ FUNCTION = "append"
215
+
216
+ CATEGORY = "conditioning"
217
+
218
+ def append(self, conditioning, mask, set_cond_area, strength):
219
+ set_area_to_bounds = False
220
+ if set_cond_area != "default":
221
+ set_area_to_bounds = True
222
+ if len(mask.shape) < 3:
223
+ mask = mask.unsqueeze(0)
224
+
225
+ c = node_helpers.conditioning_set_values(conditioning, {"mask": mask,
226
+ "set_area_to_bounds": set_area_to_bounds,
227
+ "mask_strength": strength})
228
+ return (c, )
229
+
230
+ class ConditioningZeroOut:
231
+ @classmethod
232
+ def INPUT_TYPES(s):
233
+ return {"required": {"conditioning": ("CONDITIONING", )}}
234
+ RETURN_TYPES = ("CONDITIONING",)
235
+ FUNCTION = "zero_out"
236
+
237
+ CATEGORY = "advanced/conditioning"
238
+
239
+ def zero_out(self, conditioning):
240
+ c = []
241
+ for t in conditioning:
242
+ d = t[1].copy()
243
+ pooled_output = d.get("pooled_output", None)
244
+ if pooled_output is not None:
245
+ d["pooled_output"] = torch.zeros_like(pooled_output)
246
+ n = [torch.zeros_like(t[0]), d]
247
+ c.append(n)
248
+ return (c, )
249
+
250
+ class ConditioningSetTimestepRange:
251
+ @classmethod
252
+ def INPUT_TYPES(s):
253
+ return {"required": {"conditioning": ("CONDITIONING", ),
254
+ "start": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
255
+ "end": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
256
+ }}
257
+ RETURN_TYPES = ("CONDITIONING",)
258
+ FUNCTION = "set_range"
259
+
260
+ CATEGORY = "advanced/conditioning"
261
+
262
+ def set_range(self, conditioning, start, end):
263
+ c = node_helpers.conditioning_set_values(conditioning, {"start_percent": start,
264
+ "end_percent": end})
265
+ return (c, )
266
+
267
+ class VAEDecode:
268
+ @classmethod
269
+ def INPUT_TYPES(s):
270
+ return {
271
+ "required": {
272
+ "samples": ("LATENT", {"tooltip": "The latent to be decoded."}),
273
+ "vae": ("VAE", {"tooltip": "The VAE model used for decoding the latent."})
274
+ }
275
+ }
276
+ RETURN_TYPES = ("IMAGE",)
277
+ OUTPUT_TOOLTIPS = ("The decoded image.",)
278
+ FUNCTION = "decode"
279
+
280
+ CATEGORY = "latent"
281
+ DESCRIPTION = "Decodes latent images back into pixel space images."
282
+
283
+ def decode(self, vae, samples):
284
+ return (vae.decode(samples["samples"]), )
285
+
286
+ class VAEDecodeTiled:
287
+ @classmethod
288
+ def INPUT_TYPES(s):
289
+ return {"required": {"samples": ("LATENT", ), "vae": ("VAE", ),
290
+ "tile_size": ("INT", {"default": 512, "min": 320, "max": 4096, "step": 64})
291
+ }}
292
+ RETURN_TYPES = ("IMAGE",)
293
+ FUNCTION = "decode"
294
+
295
+ CATEGORY = "_for_testing"
296
+
297
+ def decode(self, vae, samples, tile_size):
298
+ return (vae.decode_tiled(samples["samples"], tile_x=tile_size // 8, tile_y=tile_size // 8, ), )
299
+
300
+ class VAEEncode:
301
+ @classmethod
302
+ def INPUT_TYPES(s):
303
+ return {"required": { "pixels": ("IMAGE", ), "vae": ("VAE", )}}
304
+ RETURN_TYPES = ("LATENT",)
305
+ FUNCTION = "encode"
306
+
307
+ CATEGORY = "latent"
308
+
309
+ def encode(self, vae, pixels):
310
+ t = vae.encode(pixels[:,:,:,:3])
311
+ return ({"samples":t}, )
312
+
313
+ class VAEEncodeTiled:
314
+ @classmethod
315
+ def INPUT_TYPES(s):
316
+ return {"required": {"pixels": ("IMAGE", ), "vae": ("VAE", ),
317
+ "tile_size": ("INT", {"default": 512, "min": 320, "max": 4096, "step": 64})
318
+ }}
319
+ RETURN_TYPES = ("LATENT",)
320
+ FUNCTION = "encode"
321
+
322
+ CATEGORY = "_for_testing"
323
+
324
+ def encode(self, vae, pixels, tile_size):
325
+ t = vae.encode_tiled(pixels[:,:,:,:3], tile_x=tile_size, tile_y=tile_size, )
326
+ return ({"samples":t}, )
327
+
328
+ class VAEEncodeForInpaint:
329
+ @classmethod
330
+ def INPUT_TYPES(s):
331
+ return {"required": { "pixels": ("IMAGE", ), "vae": ("VAE", ), "mask": ("MASK", ), "grow_mask_by": ("INT", {"default": 6, "min": 0, "max": 64, "step": 1}),}}
332
+ RETURN_TYPES = ("LATENT",)
333
+ FUNCTION = "encode"
334
+
335
+ CATEGORY = "latent/inpaint"
336
+
337
+ def encode(self, vae, pixels, mask, grow_mask_by=6):
338
+ x = (pixels.shape[1] // vae.downscale_ratio) * vae.downscale_ratio
339
+ y = (pixels.shape[2] // vae.downscale_ratio) * vae.downscale_ratio
340
+ mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(pixels.shape[1], pixels.shape[2]), mode="bilinear")
341
+
342
+ pixels = pixels.clone()
343
+ if pixels.shape[1] != x or pixels.shape[2] != y:
344
+ x_offset = (pixels.shape[1] % vae.downscale_ratio) // 2
345
+ y_offset = (pixels.shape[2] % vae.downscale_ratio) // 2
346
+ pixels = pixels[:,x_offset:x + x_offset, y_offset:y + y_offset,:]
347
+ mask = mask[:,:,x_offset:x + x_offset, y_offset:y + y_offset]
348
+
349
+ #grow mask by a few pixels to keep things seamless in latent space
350
+ if grow_mask_by == 0:
351
+ mask_erosion = mask
352
+ else:
353
+ kernel_tensor = torch.ones((1, 1, grow_mask_by, grow_mask_by))
354
+ padding = math.ceil((grow_mask_by - 1) / 2)
355
+
356
+ mask_erosion = torch.clamp(torch.nn.functional.conv2d(mask.round(), kernel_tensor, padding=padding), 0, 1)
357
+
358
+ m = (1.0 - mask.round()).squeeze(1)
359
+ for i in range(3):
360
+ pixels[:,:,:,i] -= 0.5
361
+ pixels[:,:,:,i] *= m
362
+ pixels[:,:,:,i] += 0.5
363
+ t = vae.encode(pixels)
364
+
365
+ return ({"samples":t, "noise_mask": (mask_erosion[:,:,:x,:y].round())}, )
366
+
367
+
368
+ class InpaintModelConditioning:
369
+ @classmethod
370
+ def INPUT_TYPES(s):
371
+ return {"required": {"positive": ("CONDITIONING", ),
372
+ "negative": ("CONDITIONING", ),
373
+ "vae": ("VAE", ),
374
+ "pixels": ("IMAGE", ),
375
+ "mask": ("MASK", ),
376
+ }}
377
+
378
+ RETURN_TYPES = ("CONDITIONING","CONDITIONING","LATENT")
379
+ RETURN_NAMES = ("positive", "negative", "latent")
380
+ FUNCTION = "encode"
381
+
382
+ CATEGORY = "conditioning/inpaint"
383
+
384
+ def encode(self, positive, negative, pixels, vae, mask):
385
+ x = (pixels.shape[1] // 8) * 8
386
+ y = (pixels.shape[2] // 8) * 8
387
+ mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(pixels.shape[1], pixels.shape[2]), mode="bilinear")
388
+
389
+ orig_pixels = pixels
390
+ pixels = orig_pixels.clone()
391
+ if pixels.shape[1] != x or pixels.shape[2] != y:
392
+ x_offset = (pixels.shape[1] % 8) // 2
393
+ y_offset = (pixels.shape[2] % 8) // 2
394
+ pixels = pixels[:,x_offset:x + x_offset, y_offset:y + y_offset,:]
395
+ mask = mask[:,:,x_offset:x + x_offset, y_offset:y + y_offset]
396
+
397
+ m = (1.0 - mask.round()).squeeze(1)
398
+ for i in range(3):
399
+ pixels[:,:,:,i] -= 0.5
400
+ pixels[:,:,:,i] *= m
401
+ pixels[:,:,:,i] += 0.5
402
+ concat_latent = vae.encode(pixels)
403
+ orig_latent = vae.encode(orig_pixels)
404
+
405
+ out_latent = {}
406
+
407
+ out_latent["samples"] = orig_latent
408
+ out_latent["noise_mask"] = mask
409
+
410
+ out = []
411
+ for conditioning in [positive, negative]:
412
+ c = node_helpers.conditioning_set_values(conditioning, {"concat_latent_image": concat_latent,
413
+ "concat_mask": mask})
414
+ out.append(c)
415
+ return (out[0], out[1], out_latent)
416
+
417
+
418
+ class SaveLatent:
419
+ def __init__(self):
420
+ self.output_dir = folder_paths.get_output_directory()
421
+
422
+ @classmethod
423
+ def INPUT_TYPES(s):
424
+ return {"required": { "samples": ("LATENT", ),
425
+ "filename_prefix": ("STRING", {"default": "latents/ComfyUI"})},
426
+ "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
427
+ }
428
+ RETURN_TYPES = ()
429
+ FUNCTION = "save"
430
+
431
+ OUTPUT_NODE = True
432
+
433
+ CATEGORY = "_for_testing"
434
+
435
+ def save(self, samples, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None):
436
+ full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir)
437
+
438
+ # support save metadata for latent sharing
439
+ prompt_info = ""
440
+ if prompt is not None:
441
+ prompt_info = json.dumps(prompt)
442
+
443
+ metadata = None
444
+ if not args.disable_metadata:
445
+ metadata = {"prompt": prompt_info}
446
+ if extra_pnginfo is not None:
447
+ for x in extra_pnginfo:
448
+ metadata[x] = json.dumps(extra_pnginfo[x])
449
+
450
+ file = f"{filename}_{counter:05}_.latent"
451
+
452
+ results = list()
453
+ results.append({
454
+ "filename": file,
455
+ "subfolder": subfolder,
456
+ "type": "output"
457
+ })
458
+
459
+ file = os.path.join(full_output_folder, file)
460
+
461
+ output = {}
462
+ output["latent_tensor"] = samples["samples"]
463
+ output["latent_format_version_0"] = torch.tensor([])
464
+
465
+ comfy.utils.save_torch_file(output, file, metadata=metadata)
466
+ return { "ui": { "latents": results } }
467
+
468
+
469
+ class LoadLatent:
470
+ @classmethod
471
+ def INPUT_TYPES(s):
472
+ input_dir = folder_paths.get_input_directory()
473
+ files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f)) and f.endswith(".latent")]
474
+ return {"required": {"latent": [sorted(files), ]}, }
475
+
476
+ CATEGORY = "_for_testing"
477
+
478
+ RETURN_TYPES = ("LATENT", )
479
+ FUNCTION = "load"
480
+
481
+ def load(self, latent):
482
+ latent_path = folder_paths.get_annotated_filepath(latent)
483
+ latent = safetensors.torch.load_file(latent_path, device="cpu")
484
+ multiplier = 1.0
485
+ if "latent_format_version_0" not in latent:
486
+ multiplier = 1.0 / 0.18215
487
+ samples = {"samples": latent["latent_tensor"].float() * multiplier}
488
+ return (samples, )
489
+
490
+ @classmethod
491
+ def IS_CHANGED(s, latent):
492
+ image_path = folder_paths.get_annotated_filepath(latent)
493
+ m = hashlib.sha256()
494
+ with open(image_path, 'rb') as f:
495
+ m.update(f.read())
496
+ return m.digest().hex()
497
+
498
+ @classmethod
499
+ def VALIDATE_INPUTS(s, latent):
500
+ if not folder_paths.exists_annotated_filepath(latent):
501
+ return "Invalid latent file: {}".format(latent)
502
+ return True
503
+
504
+
505
+ class CheckpointLoader:
506
+ @classmethod
507
+ def INPUT_TYPES(s):
508
+ return {"required": { "config_name": (folder_paths.get_filename_list("configs"), ),
509
+ "ckpt_name": (folder_paths.get_filename_list("checkpoints"), )}}
510
+ RETURN_TYPES = ("MODEL", "CLIP", "VAE")
511
+ FUNCTION = "load_checkpoint"
512
+
513
+ CATEGORY = "advanced/loaders"
514
+ DEPRECATED = True
515
+
516
+ def load_checkpoint(self, config_name, ckpt_name):
517
+ config_path = folder_paths.get_full_path("configs", config_name)
518
+ ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
519
+ return comfy.sd.load_checkpoint(config_path, ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
520
+
521
+ class CheckpointLoaderSimple:
522
+ @classmethod
523
+ def INPUT_TYPES(s):
524
+ return {
525
+ "required": {
526
+ "ckpt_name": (folder_paths.get_filename_list("checkpoints"), {"tooltip": "The name of the checkpoint (model) to load."}),
527
+ }
528
+ }
529
+ RETURN_TYPES = ("MODEL", "CLIP", "VAE")
530
+ OUTPUT_TOOLTIPS = ("The model used for denoising latents.",
531
+ "The CLIP model used for encoding text prompts.",
532
+ "The VAE model used for encoding and decoding images to and from latent space.")
533
+ FUNCTION = "load_checkpoint"
534
+
535
+ CATEGORY = "loaders"
536
+ DESCRIPTION = "Loads a diffusion model checkpoint, diffusion models are used to denoise latents."
537
+
538
+ def load_checkpoint(self, ckpt_name):
539
+ ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
540
+ out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
541
+ return out[:3]
542
+
543
+ class DiffusersLoader:
544
+ @classmethod
545
+ def INPUT_TYPES(cls):
546
+ paths = []
547
+ for search_path in folder_paths.get_folder_paths("diffusers"):
548
+ if os.path.exists(search_path):
549
+ for root, subdir, files in os.walk(search_path, followlinks=True):
550
+ if "model_index.json" in files:
551
+ paths.append(os.path.relpath(root, start=search_path))
552
+
553
+ return {"required": {"model_path": (paths,), }}
554
+ RETURN_TYPES = ("MODEL", "CLIP", "VAE")
555
+ FUNCTION = "load_checkpoint"
556
+
557
+ CATEGORY = "advanced/loaders/deprecated"
558
+
559
+ def load_checkpoint(self, model_path, output_vae=True, output_clip=True):
560
+ for search_path in folder_paths.get_folder_paths("diffusers"):
561
+ if os.path.exists(search_path):
562
+ path = os.path.join(search_path, model_path)
563
+ if os.path.exists(path):
564
+ model_path = path
565
+ break
566
+
567
+ return comfy.diffusers_load.load_diffusers(model_path, output_vae=output_vae, output_clip=output_clip, embedding_directory=folder_paths.get_folder_paths("embeddings"))
568
+
569
+
570
+ class unCLIPCheckpointLoader:
571
+ @classmethod
572
+ def INPUT_TYPES(s):
573
+ return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ),
574
+ }}
575
+ RETURN_TYPES = ("MODEL", "CLIP", "VAE", "CLIP_VISION")
576
+ FUNCTION = "load_checkpoint"
577
+
578
+ CATEGORY = "loaders"
579
+
580
+ def load_checkpoint(self, ckpt_name, output_vae=True, output_clip=True):
581
+ ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
582
+ 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"))
583
+ return out
584
+
585
+ class CLIPSetLastLayer:
586
+ @classmethod
587
+ def INPUT_TYPES(s):
588
+ return {"required": { "clip": ("CLIP", ),
589
+ "stop_at_clip_layer": ("INT", {"default": -1, "min": -24, "max": -1, "step": 1}),
590
+ }}
591
+ RETURN_TYPES = ("CLIP",)
592
+ FUNCTION = "set_last_layer"
593
+
594
+ CATEGORY = "conditioning"
595
+
596
+ def set_last_layer(self, clip, stop_at_clip_layer):
597
+ clip = clip.clone()
598
+ clip.clip_layer(stop_at_clip_layer)
599
+ return (clip,)
600
+
601
+ class LoraLoader:
602
+ def __init__(self):
603
+ self.loaded_lora = None
604
+
605
+ @classmethod
606
+ def INPUT_TYPES(s):
607
+ return {
608
+ "required": {
609
+ "model": ("MODEL", {"tooltip": "The diffusion model the LoRA will be applied to."}),
610
+ "clip": ("CLIP", {"tooltip": "The CLIP model the LoRA will be applied to."}),
611
+ "lora_name": (folder_paths.get_filename_list("loras"), {"tooltip": "The name of the LoRA."}),
612
+ "strength_model": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01, "tooltip": "How strongly to modify the diffusion model. This value can be negative."}),
613
+ "strength_clip": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01, "tooltip": "How strongly to modify the CLIP model. This value can be negative."}),
614
+ }
615
+ }
616
+
617
+ RETURN_TYPES = ("MODEL", "CLIP")
618
+ OUTPUT_TOOLTIPS = ("The modified diffusion model.", "The modified CLIP model.")
619
+ FUNCTION = "load_lora"
620
+
621
+ CATEGORY = "loaders"
622
+ DESCRIPTION = "LoRAs are used to modify diffusion and CLIP models, altering the way in which latents are denoised such as applying styles. Multiple LoRA nodes can be linked together."
623
+
624
+ def load_lora(self, model, clip, lora_name, strength_model, strength_clip):
625
+ if strength_model == 0 and strength_clip == 0:
626
+ return (model, clip)
627
+
628
+ lora_path = folder_paths.get_full_path("loras", lora_name)
629
+ lora = None
630
+ if self.loaded_lora is not None:
631
+ if self.loaded_lora[0] == lora_path:
632
+ lora = self.loaded_lora[1]
633
+ else:
634
+ temp = self.loaded_lora
635
+ self.loaded_lora = None
636
+ del temp
637
+
638
+ if lora is None:
639
+ lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
640
+ self.loaded_lora = (lora_path, lora)
641
+
642
+ model_lora, clip_lora = comfy.sd.load_lora_for_models(model, clip, lora, strength_model, strength_clip)
643
+ return (model_lora, clip_lora)
644
+
645
+ class LoraLoaderModelOnly(LoraLoader):
646
+ @classmethod
647
+ def INPUT_TYPES(s):
648
+ return {"required": { "model": ("MODEL",),
649
+ "lora_name": (folder_paths.get_filename_list("loras"), ),
650
+ "strength_model": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01}),
651
+ }}
652
+ RETURN_TYPES = ("MODEL",)
653
+ FUNCTION = "load_lora_model_only"
654
+
655
+ def load_lora_model_only(self, model, lora_name, strength_model):
656
+ return (self.load_lora(model, None, lora_name, strength_model, 0)[0],)
657
+
658
+ class VAELoader:
659
+ @staticmethod
660
+ def vae_list():
661
+ vaes = folder_paths.get_filename_list("vae")
662
+ approx_vaes = folder_paths.get_filename_list("vae_approx")
663
+ sdxl_taesd_enc = False
664
+ sdxl_taesd_dec = False
665
+ sd1_taesd_enc = False
666
+ sd1_taesd_dec = False
667
+ sd3_taesd_enc = False
668
+ sd3_taesd_dec = False
669
+ f1_taesd_enc = False
670
+ f1_taesd_dec = False
671
+
672
+ for v in approx_vaes:
673
+ if v.startswith("taesd_decoder."):
674
+ sd1_taesd_dec = True
675
+ elif v.startswith("taesd_encoder."):
676
+ sd1_taesd_enc = True
677
+ elif v.startswith("taesdxl_decoder."):
678
+ sdxl_taesd_dec = True
679
+ elif v.startswith("taesdxl_encoder."):
680
+ sdxl_taesd_enc = True
681
+ elif v.startswith("taesd3_decoder."):
682
+ sd3_taesd_dec = True
683
+ elif v.startswith("taesd3_encoder."):
684
+ sd3_taesd_enc = True
685
+ elif v.startswith("taef1_encoder."):
686
+ f1_taesd_dec = True
687
+ elif v.startswith("taef1_decoder."):
688
+ f1_taesd_enc = True
689
+ if sd1_taesd_dec and sd1_taesd_enc:
690
+ vaes.append("taesd")
691
+ if sdxl_taesd_dec and sdxl_taesd_enc:
692
+ vaes.append("taesdxl")
693
+ if sd3_taesd_dec and sd3_taesd_enc:
694
+ vaes.append("taesd3")
695
+ if f1_taesd_dec and f1_taesd_enc:
696
+ vaes.append("taef1")
697
+ return vaes
698
+
699
+ @staticmethod
700
+ def load_taesd(name):
701
+ sd = {}
702
+ approx_vaes = folder_paths.get_filename_list("vae_approx")
703
+
704
+ encoder = next(filter(lambda a: a.startswith("{}_encoder.".format(name)), approx_vaes))
705
+ decoder = next(filter(lambda a: a.startswith("{}_decoder.".format(name)), approx_vaes))
706
+
707
+ enc = comfy.utils.load_torch_file(folder_paths.get_full_path("vae_approx", encoder))
708
+ for k in enc:
709
+ sd["taesd_encoder.{}".format(k)] = enc[k]
710
+
711
+ dec = comfy.utils.load_torch_file(folder_paths.get_full_path("vae_approx", decoder))
712
+ for k in dec:
713
+ sd["taesd_decoder.{}".format(k)] = dec[k]
714
+
715
+ if name == "taesd":
716
+ sd["vae_scale"] = torch.tensor(0.18215)
717
+ sd["vae_shift"] = torch.tensor(0.0)
718
+ elif name == "taesdxl":
719
+ sd["vae_scale"] = torch.tensor(0.13025)
720
+ sd["vae_shift"] = torch.tensor(0.0)
721
+ elif name == "taesd3":
722
+ sd["vae_scale"] = torch.tensor(1.5305)
723
+ sd["vae_shift"] = torch.tensor(0.0609)
724
+ elif name == "taef1":
725
+ sd["vae_scale"] = torch.tensor(0.3611)
726
+ sd["vae_shift"] = torch.tensor(0.1159)
727
+ return sd
728
+
729
+ @classmethod
730
+ def INPUT_TYPES(s):
731
+ return {"required": { "vae_name": (s.vae_list(), )}}
732
+ RETURN_TYPES = ("VAE",)
733
+ FUNCTION = "load_vae"
734
+
735
+ CATEGORY = "loaders"
736
+
737
+ #TODO: scale factor?
738
+ def load_vae(self, vae_name):
739
+ if vae_name in ["taesd", "taesdxl", "taesd3", "taef1"]:
740
+ sd = self.load_taesd(vae_name)
741
+ else:
742
+ vae_path = folder_paths.get_full_path("vae", vae_name)
743
+ sd = comfy.utils.load_torch_file(vae_path)
744
+ vae = comfy.sd.VAE(sd=sd)
745
+ return (vae,)
746
+
747
+ class ControlNetLoader:
748
+ @classmethod
749
+ def INPUT_TYPES(s):
750
+ return {"required": { "control_net_name": (folder_paths.get_filename_list("controlnet"), )}}
751
+
752
+ RETURN_TYPES = ("CONTROL_NET",)
753
+ FUNCTION = "load_controlnet"
754
+
755
+ CATEGORY = "loaders"
756
+
757
+ def load_controlnet(self, control_net_name):
758
+ controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
759
+ controlnet = comfy.controlnet.load_controlnet(controlnet_path)
760
+ return (controlnet,)
761
+
762
+ class DiffControlNetLoader:
763
+ @classmethod
764
+ def INPUT_TYPES(s):
765
+ return {"required": { "model": ("MODEL",),
766
+ "control_net_name": (folder_paths.get_filename_list("controlnet"), )}}
767
+
768
+ RETURN_TYPES = ("CONTROL_NET",)
769
+ FUNCTION = "load_controlnet"
770
+
771
+ CATEGORY = "loaders"
772
+
773
+ def load_controlnet(self, model, control_net_name):
774
+ controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
775
+ controlnet = comfy.controlnet.load_controlnet(controlnet_path, model)
776
+ return (controlnet,)
777
+
778
+
779
+ class ControlNetApply:
780
+ @classmethod
781
+ def INPUT_TYPES(s):
782
+ return {"required": {"conditioning": ("CONDITIONING", ),
783
+ "control_net": ("CONTROL_NET", ),
784
+ "image": ("IMAGE", ),
785
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01})
786
+ }}
787
+ RETURN_TYPES = ("CONDITIONING",)
788
+ FUNCTION = "apply_controlnet"
789
+
790
+ CATEGORY = "conditioning/controlnet"
791
+
792
+ def apply_controlnet(self, conditioning, control_net, image, strength):
793
+ if strength == 0:
794
+ return (conditioning, )
795
+
796
+ c = []
797
+ control_hint = image.movedim(-1,1)
798
+ for t in conditioning:
799
+ n = [t[0], t[1].copy()]
800
+ c_net = control_net.copy().set_cond_hint(control_hint, strength)
801
+ if 'control' in t[1]:
802
+ c_net.set_previous_controlnet(t[1]['control'])
803
+ n[1]['control'] = c_net
804
+ n[1]['control_apply_to_uncond'] = True
805
+ c.append(n)
806
+ return (c, )
807
+
808
+
809
+ class ControlNetApplyAdvanced:
810
+ @classmethod
811
+ def INPUT_TYPES(s):
812
+ return {"required": {"positive": ("CONDITIONING", ),
813
+ "negative": ("CONDITIONING", ),
814
+ "control_net": ("CONTROL_NET", ),
815
+ "image": ("IMAGE", ),
816
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
817
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
818
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
819
+ }}
820
+
821
+ RETURN_TYPES = ("CONDITIONING","CONDITIONING")
822
+ RETURN_NAMES = ("positive", "negative")
823
+ FUNCTION = "apply_controlnet"
824
+
825
+ CATEGORY = "conditioning/controlnet"
826
+
827
+ def apply_controlnet(self, positive, negative, control_net, image, strength, start_percent, end_percent, vae=None, extra_concat=[]):
828
+ if strength == 0:
829
+ return (positive, negative)
830
+
831
+ control_hint = image.movedim(-1,1)
832
+ cnets = {}
833
+
834
+ out = []
835
+ for conditioning in [positive, negative]:
836
+ c = []
837
+ for t in conditioning:
838
+ d = t[1].copy()
839
+
840
+ prev_cnet = d.get('control', None)
841
+ if prev_cnet in cnets:
842
+ c_net = cnets[prev_cnet]
843
+ else:
844
+ c_net = control_net.copy().set_cond_hint(control_hint, strength, (start_percent, end_percent), vae=vae, extra_concat=extra_concat)
845
+ c_net.set_previous_controlnet(prev_cnet)
846
+ cnets[prev_cnet] = c_net
847
+
848
+ d['control'] = c_net
849
+ d['control_apply_to_uncond'] = False
850
+ n = [t[0], d]
851
+ c.append(n)
852
+ out.append(c)
853
+ return (out[0], out[1])
854
+
855
+
856
+ class UNETLoader:
857
+ @classmethod
858
+ def INPUT_TYPES(s):
859
+ return {"required": { "unet_name": (folder_paths.get_filename_list("diffusion_models"), ),
860
+ "weight_dtype": (["default", "fp8_e4m3fn", "fp8_e5m2"],)
861
+ }}
862
+ RETURN_TYPES = ("MODEL",)
863
+ FUNCTION = "load_unet"
864
+
865
+ CATEGORY = "advanced/loaders"
866
+
867
+ def load_unet(self, unet_name, weight_dtype):
868
+ model_options = {}
869
+ if weight_dtype == "fp8_e4m3fn":
870
+ model_options["dtype"] = torch.float8_e4m3fn
871
+ elif weight_dtype == "fp8_e5m2":
872
+ model_options["dtype"] = torch.float8_e5m2
873
+
874
+ unet_path = folder_paths.get_full_path("diffusion_models", unet_name)
875
+ model = comfy.sd.load_diffusion_model(unet_path, model_options=model_options)
876
+ return (model,)
877
+
878
+ class CLIPLoader:
879
+ @classmethod
880
+ def INPUT_TYPES(s):
881
+ return {"required": { "clip_name": (folder_paths.get_filename_list("clip"), ),
882
+ "type": (["stable_diffusion", "stable_cascade", "sd3", "stable_audio"], ),
883
+ }}
884
+ RETURN_TYPES = ("CLIP",)
885
+ FUNCTION = "load_clip"
886
+
887
+ CATEGORY = "advanced/loaders"
888
+
889
+ def load_clip(self, clip_name, type="stable_diffusion"):
890
+ if type == "stable_cascade":
891
+ clip_type = comfy.sd.CLIPType.STABLE_CASCADE
892
+ elif type == "sd3":
893
+ clip_type = comfy.sd.CLIPType.SD3
894
+ elif type == "stable_audio":
895
+ clip_type = comfy.sd.CLIPType.STABLE_AUDIO
896
+ else:
897
+ clip_type = comfy.sd.CLIPType.STABLE_DIFFUSION
898
+
899
+ clip_path = folder_paths.get_full_path("clip", clip_name)
900
+ clip = comfy.sd.load_clip(ckpt_paths=[clip_path], embedding_directory=folder_paths.get_folder_paths("embeddings"), clip_type=clip_type)
901
+ return (clip,)
902
+
903
+ class DualCLIPLoader:
904
+ @classmethod
905
+ def INPUT_TYPES(s):
906
+ return {"required": { "clip_name1": (folder_paths.get_filename_list("clip"), ),
907
+ "clip_name2": (folder_paths.get_filename_list("clip"), ),
908
+ "type": (["sdxl", "sd3", "flux"], ),
909
+ }}
910
+ RETURN_TYPES = ("CLIP",)
911
+ FUNCTION = "load_clip"
912
+
913
+ CATEGORY = "advanced/loaders"
914
+
915
+ def load_clip(self, clip_name1, clip_name2, type):
916
+ clip_path1 = folder_paths.get_full_path("clip", clip_name1)
917
+ clip_path2 = folder_paths.get_full_path("clip", clip_name2)
918
+ if type == "sdxl":
919
+ clip_type = comfy.sd.CLIPType.STABLE_DIFFUSION
920
+ elif type == "sd3":
921
+ clip_type = comfy.sd.CLIPType.SD3
922
+ elif type == "flux":
923
+ clip_type = comfy.sd.CLIPType.FLUX
924
+
925
+ clip = comfy.sd.load_clip(ckpt_paths=[clip_path1, clip_path2], embedding_directory=folder_paths.get_folder_paths("embeddings"), clip_type=clip_type)
926
+ return (clip,)
927
+
928
+ class CLIPVisionLoader:
929
+ @classmethod
930
+ def INPUT_TYPES(s):
931
+ return {"required": { "clip_name": (folder_paths.get_filename_list("clip_vision"), ),
932
+ }}
933
+ RETURN_TYPES = ("CLIP_VISION",)
934
+ FUNCTION = "load_clip"
935
+
936
+ CATEGORY = "loaders"
937
+
938
+ def load_clip(self, clip_name):
939
+ clip_path = folder_paths.get_full_path("clip_vision", clip_name)
940
+ clip_vision = comfy.clip_vision.load(clip_path)
941
+ return (clip_vision,)
942
+
943
+ class CLIPVisionEncode:
944
+ @classmethod
945
+ def INPUT_TYPES(s):
946
+ return {"required": { "clip_vision": ("CLIP_VISION",),
947
+ "image": ("IMAGE",)
948
+ }}
949
+ RETURN_TYPES = ("CLIP_VISION_OUTPUT",)
950
+ FUNCTION = "encode"
951
+
952
+ CATEGORY = "conditioning"
953
+
954
+ def encode(self, clip_vision, image):
955
+ output = clip_vision.encode_image(image)
956
+ return (output,)
957
+
958
+ class StyleModelLoader:
959
+ @classmethod
960
+ def INPUT_TYPES(s):
961
+ return {"required": { "style_model_name": (folder_paths.get_filename_list("style_models"), )}}
962
+
963
+ RETURN_TYPES = ("STYLE_MODEL",)
964
+ FUNCTION = "load_style_model"
965
+
966
+ CATEGORY = "loaders"
967
+
968
+ def load_style_model(self, style_model_name):
969
+ style_model_path = folder_paths.get_full_path("style_models", style_model_name)
970
+ style_model = comfy.sd.load_style_model(style_model_path)
971
+ return (style_model,)
972
+
973
+
974
+ class StyleModelApply:
975
+ @classmethod
976
+ def INPUT_TYPES(s):
977
+ return {"required": {"conditioning": ("CONDITIONING", ),
978
+ "style_model": ("STYLE_MODEL", ),
979
+ "clip_vision_output": ("CLIP_VISION_OUTPUT", ),
980
+ }}
981
+ RETURN_TYPES = ("CONDITIONING",)
982
+ FUNCTION = "apply_stylemodel"
983
+
984
+ CATEGORY = "conditioning/style_model"
985
+
986
+ def apply_stylemodel(self, clip_vision_output, style_model, conditioning):
987
+ cond = style_model.get_cond(clip_vision_output).flatten(start_dim=0, end_dim=1).unsqueeze(dim=0)
988
+ c = []
989
+ for t in conditioning:
990
+ n = [torch.cat((t[0], cond), dim=1), t[1].copy()]
991
+ c.append(n)
992
+ return (c, )
993
+
994
+ class unCLIPConditioning:
995
+ @classmethod
996
+ def INPUT_TYPES(s):
997
+ return {"required": {"conditioning": ("CONDITIONING", ),
998
+ "clip_vision_output": ("CLIP_VISION_OUTPUT", ),
999
+ "strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
1000
+ "noise_augmentation": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
1001
+ }}
1002
+ RETURN_TYPES = ("CONDITIONING",)
1003
+ FUNCTION = "apply_adm"
1004
+
1005
+ CATEGORY = "conditioning"
1006
+
1007
+ def apply_adm(self, conditioning, clip_vision_output, strength, noise_augmentation):
1008
+ if strength == 0:
1009
+ return (conditioning, )
1010
+
1011
+ c = []
1012
+ for t in conditioning:
1013
+ o = t[1].copy()
1014
+ x = {"clip_vision_output": clip_vision_output, "strength": strength, "noise_augmentation": noise_augmentation}
1015
+ if "unclip_conditioning" in o:
1016
+ o["unclip_conditioning"] = o["unclip_conditioning"][:] + [x]
1017
+ else:
1018
+ o["unclip_conditioning"] = [x]
1019
+ n = [t[0], o]
1020
+ c.append(n)
1021
+ return (c, )
1022
+
1023
+ class GLIGENLoader:
1024
+ @classmethod
1025
+ def INPUT_TYPES(s):
1026
+ return {"required": { "gligen_name": (folder_paths.get_filename_list("gligen"), )}}
1027
+
1028
+ RETURN_TYPES = ("GLIGEN",)
1029
+ FUNCTION = "load_gligen"
1030
+
1031
+ CATEGORY = "loaders"
1032
+
1033
+ def load_gligen(self, gligen_name):
1034
+ gligen_path = folder_paths.get_full_path("gligen", gligen_name)
1035
+ gligen = comfy.sd.load_gligen(gligen_path)
1036
+ return (gligen,)
1037
+
1038
+ class GLIGENTextBoxApply:
1039
+ @classmethod
1040
+ def INPUT_TYPES(s):
1041
+ return {"required": {"conditioning_to": ("CONDITIONING", ),
1042
+ "clip": ("CLIP", ),
1043
+ "gligen_textbox_model": ("GLIGEN", ),
1044
+ "text": ("STRING", {"multiline": True, "dynamicPrompts": True}),
1045
+ "width": ("INT", {"default": 64, "min": 8, "max": MAX_RESOLUTION, "step": 8}),
1046
+ "height": ("INT", {"default": 64, "min": 8, "max": MAX_RESOLUTION, "step": 8}),
1047
+ "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1048
+ "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1049
+ }}
1050
+ RETURN_TYPES = ("CONDITIONING",)
1051
+ FUNCTION = "append"
1052
+
1053
+ CATEGORY = "conditioning/gligen"
1054
+
1055
+ def append(self, conditioning_to, clip, gligen_textbox_model, text, width, height, x, y):
1056
+ c = []
1057
+ cond, cond_pooled = clip.encode_from_tokens(clip.tokenize(text), return_pooled="unprojected")
1058
+ for t in conditioning_to:
1059
+ n = [t[0], t[1].copy()]
1060
+ position_params = [(cond_pooled, height // 8, width // 8, y // 8, x // 8)]
1061
+ prev = []
1062
+ if "gligen" in n[1]:
1063
+ prev = n[1]['gligen'][2]
1064
+
1065
+ n[1]['gligen'] = ("position", gligen_textbox_model, prev + position_params)
1066
+ c.append(n)
1067
+ return (c, )
1068
+
1069
+ class EmptyLatentImage:
1070
+ def __init__(self):
1071
+ self.device = comfy.model_management.intermediate_device()
1072
+
1073
+ @classmethod
1074
+ def INPUT_TYPES(s):
1075
+ return {
1076
+ "required": {
1077
+ "width": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8, "tooltip": "The width of the latent images in pixels."}),
1078
+ "height": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8, "tooltip": "The height of the latent images in pixels."}),
1079
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096, "tooltip": "The number of latent images in the batch."})
1080
+ }
1081
+ }
1082
+ RETURN_TYPES = ("LATENT",)
1083
+ OUTPUT_TOOLTIPS = ("The empty latent image batch.",)
1084
+ FUNCTION = "generate"
1085
+
1086
+ CATEGORY = "latent"
1087
+ DESCRIPTION = "Create a new batch of empty latent images to be denoised via sampling."
1088
+
1089
+ def generate(self, width, height, batch_size=1):
1090
+ latent = torch.zeros([batch_size, 4, height // 8, width // 8], device=self.device)
1091
+ return ({"samples":latent}, )
1092
+
1093
+
1094
+ class LatentFromBatch:
1095
+ @classmethod
1096
+ def INPUT_TYPES(s):
1097
+ return {"required": { "samples": ("LATENT",),
1098
+ "batch_index": ("INT", {"default": 0, "min": 0, "max": 63}),
1099
+ "length": ("INT", {"default": 1, "min": 1, "max": 64}),
1100
+ }}
1101
+ RETURN_TYPES = ("LATENT",)
1102
+ FUNCTION = "frombatch"
1103
+
1104
+ CATEGORY = "latent/batch"
1105
+
1106
+ def frombatch(self, samples, batch_index, length):
1107
+ s = samples.copy()
1108
+ s_in = samples["samples"]
1109
+ batch_index = min(s_in.shape[0] - 1, batch_index)
1110
+ length = min(s_in.shape[0] - batch_index, length)
1111
+ s["samples"] = s_in[batch_index:batch_index + length].clone()
1112
+ if "noise_mask" in samples:
1113
+ masks = samples["noise_mask"]
1114
+ if masks.shape[0] == 1:
1115
+ s["noise_mask"] = masks.clone()
1116
+ else:
1117
+ if masks.shape[0] < s_in.shape[0]:
1118
+ masks = masks.repeat(math.ceil(s_in.shape[0] / masks.shape[0]), 1, 1, 1)[:s_in.shape[0]]
1119
+ s["noise_mask"] = masks[batch_index:batch_index + length].clone()
1120
+ if "batch_index" not in s:
1121
+ s["batch_index"] = [x for x in range(batch_index, batch_index+length)]
1122
+ else:
1123
+ s["batch_index"] = samples["batch_index"][batch_index:batch_index + length]
1124
+ return (s,)
1125
+
1126
+ class RepeatLatentBatch:
1127
+ @classmethod
1128
+ def INPUT_TYPES(s):
1129
+ return {"required": { "samples": ("LATENT",),
1130
+ "amount": ("INT", {"default": 1, "min": 1, "max": 64}),
1131
+ }}
1132
+ RETURN_TYPES = ("LATENT",)
1133
+ FUNCTION = "repeat"
1134
+
1135
+ CATEGORY = "latent/batch"
1136
+
1137
+ def repeat(self, samples, amount):
1138
+ s = samples.copy()
1139
+ s_in = samples["samples"]
1140
+
1141
+ s["samples"] = s_in.repeat((amount, 1,1,1))
1142
+ if "noise_mask" in samples and samples["noise_mask"].shape[0] > 1:
1143
+ masks = samples["noise_mask"]
1144
+ if masks.shape[0] < s_in.shape[0]:
1145
+ masks = masks.repeat(math.ceil(s_in.shape[0] / masks.shape[0]), 1, 1, 1)[:s_in.shape[0]]
1146
+ s["noise_mask"] = samples["noise_mask"].repeat((amount, 1,1,1))
1147
+ if "batch_index" in s:
1148
+ offset = max(s["batch_index"]) - min(s["batch_index"]) + 1
1149
+ s["batch_index"] = s["batch_index"] + [x + (i * offset) for i in range(1, amount) for x in s["batch_index"]]
1150
+ return (s,)
1151
+
1152
+ class LatentUpscale:
1153
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "bislerp"]
1154
+ crop_methods = ["disabled", "center"]
1155
+
1156
+ @classmethod
1157
+ def INPUT_TYPES(s):
1158
+ return {"required": { "samples": ("LATENT",), "upscale_method": (s.upscale_methods,),
1159
+ "width": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1160
+ "height": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1161
+ "crop": (s.crop_methods,)}}
1162
+ RETURN_TYPES = ("LATENT",)
1163
+ FUNCTION = "upscale"
1164
+
1165
+ CATEGORY = "latent"
1166
+
1167
+ def upscale(self, samples, upscale_method, width, height, crop):
1168
+ if width == 0 and height == 0:
1169
+ s = samples
1170
+ else:
1171
+ s = samples.copy()
1172
+
1173
+ if width == 0:
1174
+ height = max(64, height)
1175
+ width = max(64, round(samples["samples"].shape[3] * height / samples["samples"].shape[2]))
1176
+ elif height == 0:
1177
+ width = max(64, width)
1178
+ height = max(64, round(samples["samples"].shape[2] * width / samples["samples"].shape[3]))
1179
+ else:
1180
+ width = max(64, width)
1181
+ height = max(64, height)
1182
+
1183
+ s["samples"] = comfy.utils.common_upscale(samples["samples"], width // 8, height // 8, upscale_method, crop)
1184
+ return (s,)
1185
+
1186
+ class LatentUpscaleBy:
1187
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "bislerp"]
1188
+
1189
+ @classmethod
1190
+ def INPUT_TYPES(s):
1191
+ return {"required": { "samples": ("LATENT",), "upscale_method": (s.upscale_methods,),
1192
+ "scale_by": ("FLOAT", {"default": 1.5, "min": 0.01, "max": 8.0, "step": 0.01}),}}
1193
+ RETURN_TYPES = ("LATENT",)
1194
+ FUNCTION = "upscale"
1195
+
1196
+ CATEGORY = "latent"
1197
+
1198
+ def upscale(self, samples, upscale_method, scale_by):
1199
+ s = samples.copy()
1200
+ width = round(samples["samples"].shape[3] * scale_by)
1201
+ height = round(samples["samples"].shape[2] * scale_by)
1202
+ s["samples"] = comfy.utils.common_upscale(samples["samples"], width, height, upscale_method, "disabled")
1203
+ return (s,)
1204
+
1205
+ class LatentRotate:
1206
+ @classmethod
1207
+ def INPUT_TYPES(s):
1208
+ return {"required": { "samples": ("LATENT",),
1209
+ "rotation": (["none", "90 degrees", "180 degrees", "270 degrees"],),
1210
+ }}
1211
+ RETURN_TYPES = ("LATENT",)
1212
+ FUNCTION = "rotate"
1213
+
1214
+ CATEGORY = "latent/transform"
1215
+
1216
+ def rotate(self, samples, rotation):
1217
+ s = samples.copy()
1218
+ rotate_by = 0
1219
+ if rotation.startswith("90"):
1220
+ rotate_by = 1
1221
+ elif rotation.startswith("180"):
1222
+ rotate_by = 2
1223
+ elif rotation.startswith("270"):
1224
+ rotate_by = 3
1225
+
1226
+ s["samples"] = torch.rot90(samples["samples"], k=rotate_by, dims=[3, 2])
1227
+ return (s,)
1228
+
1229
+ class LatentFlip:
1230
+ @classmethod
1231
+ def INPUT_TYPES(s):
1232
+ return {"required": { "samples": ("LATENT",),
1233
+ "flip_method": (["x-axis: vertically", "y-axis: horizontally"],),
1234
+ }}
1235
+ RETURN_TYPES = ("LATENT",)
1236
+ FUNCTION = "flip"
1237
+
1238
+ CATEGORY = "latent/transform"
1239
+
1240
+ def flip(self, samples, flip_method):
1241
+ s = samples.copy()
1242
+ if flip_method.startswith("x"):
1243
+ s["samples"] = torch.flip(samples["samples"], dims=[2])
1244
+ elif flip_method.startswith("y"):
1245
+ s["samples"] = torch.flip(samples["samples"], dims=[3])
1246
+
1247
+ return (s,)
1248
+
1249
+ class LatentComposite:
1250
+ @classmethod
1251
+ def INPUT_TYPES(s):
1252
+ return {"required": { "samples_to": ("LATENT",),
1253
+ "samples_from": ("LATENT",),
1254
+ "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1255
+ "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1256
+ "feather": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1257
+ }}
1258
+ RETURN_TYPES = ("LATENT",)
1259
+ FUNCTION = "composite"
1260
+
1261
+ CATEGORY = "latent"
1262
+
1263
+ def composite(self, samples_to, samples_from, x, y, composite_method="normal", feather=0):
1264
+ x = x // 8
1265
+ y = y // 8
1266
+ feather = feather // 8
1267
+ samples_out = samples_to.copy()
1268
+ s = samples_to["samples"].clone()
1269
+ samples_to = samples_to["samples"]
1270
+ samples_from = samples_from["samples"]
1271
+ if feather == 0:
1272
+ 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]
1273
+ else:
1274
+ samples_from = samples_from[:,:,:samples_to.shape[2] - y, :samples_to.shape[3] - x]
1275
+ mask = torch.ones_like(samples_from)
1276
+ for t in range(feather):
1277
+ if y != 0:
1278
+ mask[:,:,t:1+t,:] *= ((1.0/feather) * (t + 1))
1279
+
1280
+ if y + samples_from.shape[2] < samples_to.shape[2]:
1281
+ mask[:,:,mask.shape[2] -1 -t: mask.shape[2]-t,:] *= ((1.0/feather) * (t + 1))
1282
+ if x != 0:
1283
+ mask[:,:,:,t:1+t] *= ((1.0/feather) * (t + 1))
1284
+ if x + samples_from.shape[3] < samples_to.shape[3]:
1285
+ mask[:,:,:,mask.shape[3]- 1 - t: mask.shape[3]- t] *= ((1.0/feather) * (t + 1))
1286
+ rev_mask = torch.ones_like(mask) - mask
1287
+ 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
1288
+ samples_out["samples"] = s
1289
+ return (samples_out,)
1290
+
1291
+ class LatentBlend:
1292
+ @classmethod
1293
+ def INPUT_TYPES(s):
1294
+ return {"required": {
1295
+ "samples1": ("LATENT",),
1296
+ "samples2": ("LATENT",),
1297
+ "blend_factor": ("FLOAT", {
1298
+ "default": 0.5,
1299
+ "min": 0,
1300
+ "max": 1,
1301
+ "step": 0.01
1302
+ }),
1303
+ }}
1304
+
1305
+ RETURN_TYPES = ("LATENT",)
1306
+ FUNCTION = "blend"
1307
+
1308
+ CATEGORY = "_for_testing"
1309
+
1310
+ def blend(self, samples1, samples2, blend_factor:float, blend_mode: str="normal"):
1311
+
1312
+ samples_out = samples1.copy()
1313
+ samples1 = samples1["samples"]
1314
+ samples2 = samples2["samples"]
1315
+
1316
+ if samples1.shape != samples2.shape:
1317
+ samples2.permute(0, 3, 1, 2)
1318
+ samples2 = comfy.utils.common_upscale(samples2, samples1.shape[3], samples1.shape[2], 'bicubic', crop='center')
1319
+ samples2.permute(0, 2, 3, 1)
1320
+
1321
+ samples_blended = self.blend_mode(samples1, samples2, blend_mode)
1322
+ samples_blended = samples1 * blend_factor + samples_blended * (1 - blend_factor)
1323
+ samples_out["samples"] = samples_blended
1324
+ return (samples_out,)
1325
+
1326
+ def blend_mode(self, img1, img2, mode):
1327
+ if mode == "normal":
1328
+ return img2
1329
+ else:
1330
+ raise ValueError(f"Unsupported blend mode: {mode}")
1331
+
1332
+ class LatentCrop:
1333
+ @classmethod
1334
+ def INPUT_TYPES(s):
1335
+ return {"required": { "samples": ("LATENT",),
1336
+ "width": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
1337
+ "height": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
1338
+ "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1339
+ "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1340
+ }}
1341
+ RETURN_TYPES = ("LATENT",)
1342
+ FUNCTION = "crop"
1343
+
1344
+ CATEGORY = "latent/transform"
1345
+
1346
+ def crop(self, samples, width, height, x, y):
1347
+ s = samples.copy()
1348
+ samples = samples['samples']
1349
+ x = x // 8
1350
+ y = y // 8
1351
+
1352
+ #enfonce minimum size of 64
1353
+ if x > (samples.shape[3] - 8):
1354
+ x = samples.shape[3] - 8
1355
+ if y > (samples.shape[2] - 8):
1356
+ y = samples.shape[2] - 8
1357
+
1358
+ new_height = height // 8
1359
+ new_width = width // 8
1360
+ to_x = new_width + x
1361
+ to_y = new_height + y
1362
+ s['samples'] = samples[:,:,y:to_y, x:to_x]
1363
+ return (s,)
1364
+
1365
+ class SetLatentNoiseMask:
1366
+ @classmethod
1367
+ def INPUT_TYPES(s):
1368
+ return {"required": { "samples": ("LATENT",),
1369
+ "mask": ("MASK",),
1370
+ }}
1371
+ RETURN_TYPES = ("LATENT",)
1372
+ FUNCTION = "set_mask"
1373
+
1374
+ CATEGORY = "latent/inpaint"
1375
+
1376
+ def set_mask(self, samples, mask):
1377
+ s = samples.copy()
1378
+ s["noise_mask"] = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1]))
1379
+ return (s,)
1380
+
1381
+ 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):
1382
+ latent_image = latent["samples"]
1383
+ latent_image = comfy.sample.fix_empty_latent_channels(model, latent_image)
1384
+
1385
+ if disable_noise:
1386
+ noise = torch.zeros(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, device="cpu")
1387
+ else:
1388
+ batch_inds = latent["batch_index"] if "batch_index" in latent else None
1389
+ noise = comfy.sample.prepare_noise(latent_image, seed, batch_inds)
1390
+
1391
+ noise_mask = None
1392
+ if "noise_mask" in latent:
1393
+ noise_mask = latent["noise_mask"]
1394
+
1395
+ callback = latent_preview.prepare_callback(model, steps)
1396
+ disable_pbar = not comfy.utils.PROGRESS_BAR_ENABLED
1397
+ samples = comfy.sample.sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative, latent_image,
1398
+ denoise=denoise, disable_noise=disable_noise, start_step=start_step, last_step=last_step,
1399
+ force_full_denoise=force_full_denoise, noise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed)
1400
+ out = latent.copy()
1401
+ out["samples"] = samples
1402
+ return (out, )
1403
+
1404
+ class KSampler:
1405
+ @classmethod
1406
+ def INPUT_TYPES(s):
1407
+ return {
1408
+ "required": {
1409
+ "model": ("MODEL", {"tooltip": "The model used for denoising the input latent."}),
1410
+ "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "tooltip": "The random seed used for creating the noise."}),
1411
+ "steps": ("INT", {"default": 20, "min": 1, "max": 10000, "tooltip": "The number of steps used in the denoising process."}),
1412
+ "cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.1, "round": 0.01, "tooltip": "The Classifier-Free Guidance scale balances creativity and adherence to the prompt. Higher values result in images more closely matching the prompt however too high values will negatively impact quality."}),
1413
+ "sampler_name": (comfy.samplers.KSampler.SAMPLERS, {"tooltip": "The algorithm used when sampling, this can affect the quality, speed, and style of the generated output."}),
1414
+ "scheduler": (comfy.samplers.KSampler.SCHEDULERS, {"tooltip": "The scheduler controls how noise is gradually removed to form the image."}),
1415
+ "positive": ("CONDITIONING", {"tooltip": "The conditioning describing the attributes you want to include in the image."}),
1416
+ "negative": ("CONDITIONING", {"tooltip": "The conditioning describing the attributes you want to exclude from the image."}),
1417
+ "latent_image": ("LATENT", {"tooltip": "The latent image to denoise."}),
1418
+ "denoise": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "The amount of denoising applied, lower values will maintain the structure of the initial image allowing for image to image sampling."}),
1419
+ }
1420
+ }
1421
+
1422
+ RETURN_TYPES = ("LATENT",)
1423
+ OUTPUT_TOOLTIPS = ("The denoised latent.",)
1424
+ FUNCTION = "sample"
1425
+
1426
+ CATEGORY = "sampling"
1427
+ DESCRIPTION = "Uses the provided model, positive and negative conditioning to denoise the latent image."
1428
+
1429
+ def sample(self, model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=1.0):
1430
+ return common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise)
1431
+
1432
+ class KSamplerAdvanced:
1433
+ @classmethod
1434
+ def INPUT_TYPES(s):
1435
+ return {"required":
1436
+ {"model": ("MODEL",),
1437
+ "add_noise": (["enable", "disable"], ),
1438
+ "noise_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
1439
+ "steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
1440
+ "cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.1, "round": 0.01}),
1441
+ "sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
1442
+ "scheduler": (comfy.samplers.KSampler.SCHEDULERS, ),
1443
+ "positive": ("CONDITIONING", ),
1444
+ "negative": ("CONDITIONING", ),
1445
+ "latent_image": ("LATENT", ),
1446
+ "start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000}),
1447
+ "end_at_step": ("INT", {"default": 10000, "min": 0, "max": 10000}),
1448
+ "return_with_leftover_noise": (["disable", "enable"], ),
1449
+ }
1450
+ }
1451
+
1452
+ RETURN_TYPES = ("LATENT",)
1453
+ FUNCTION = "sample"
1454
+
1455
+ CATEGORY = "sampling"
1456
+
1457
+ 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):
1458
+ force_full_denoise = True
1459
+ if return_with_leftover_noise == "enable":
1460
+ force_full_denoise = False
1461
+ disable_noise = False
1462
+ if add_noise == "disable":
1463
+ disable_noise = True
1464
+ 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)
1465
+
1466
+ class SaveImage:
1467
+ def __init__(self):
1468
+ self.output_dir = folder_paths.get_output_directory()
1469
+ self.type = "output"
1470
+ self.prefix_append = ""
1471
+ self.compress_level = 4
1472
+
1473
+ @classmethod
1474
+ def INPUT_TYPES(s):
1475
+ return {
1476
+ "required": {
1477
+ "images": ("IMAGE", {"tooltip": "The images to save."}),
1478
+ "filename_prefix": ("STRING", {"default": "ComfyUI", "tooltip": "The prefix for the file to save. This may include formatting information such as %date:yyyy-MM-dd% or %Empty Latent Image.width% to include values from nodes."})
1479
+ },
1480
+ "hidden": {
1481
+ "prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"
1482
+ },
1483
+ }
1484
+
1485
+ RETURN_TYPES = ()
1486
+ FUNCTION = "save_images"
1487
+
1488
+ OUTPUT_NODE = True
1489
+
1490
+ CATEGORY = "image"
1491
+ DESCRIPTION = "Saves the input images to your ComfyUI output directory."
1492
+
1493
+ def save_images(self, images, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None):
1494
+ filename_prefix += self.prefix_append
1495
+ 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])
1496
+ results = list()
1497
+ for (batch_number, image) in enumerate(images):
1498
+ i = 255. * image.cpu().numpy()
1499
+ img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
1500
+ metadata = None
1501
+ if not args.disable_metadata:
1502
+ metadata = PngInfo()
1503
+ if prompt is not None:
1504
+ metadata.add_text("prompt", json.dumps(prompt))
1505
+ if extra_pnginfo is not None:
1506
+ for x in extra_pnginfo:
1507
+ metadata.add_text(x, json.dumps(extra_pnginfo[x]))
1508
+
1509
+ filename_with_batch_num = filename.replace("%batch_num%", str(batch_number))
1510
+ file = f"{filename_with_batch_num}_{counter:05}_.png"
1511
+ img.save(os.path.join(full_output_folder, file), pnginfo=metadata, compress_level=self.compress_level)
1512
+ results.append({
1513
+ "filename": file,
1514
+ "subfolder": subfolder,
1515
+ "type": self.type
1516
+ })
1517
+ counter += 1
1518
+
1519
+ return { "ui": { "images": results } }
1520
+
1521
+ class PreviewImage(SaveImage):
1522
+ def __init__(self):
1523
+ self.output_dir = folder_paths.get_temp_directory()
1524
+ self.type = "temp"
1525
+ self.prefix_append = "_temp_" + ''.join(random.choice("abcdefghijklmnopqrstupvxyz") for x in range(5))
1526
+ self.compress_level = 1
1527
+
1528
+ @classmethod
1529
+ def INPUT_TYPES(s):
1530
+ return {"required":
1531
+ {"images": ("IMAGE", ), },
1532
+ "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
1533
+ }
1534
+
1535
+ class LoadImage:
1536
+ @classmethod
1537
+ def INPUT_TYPES(s):
1538
+ input_dir = folder_paths.get_input_directory()
1539
+ files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
1540
+ return {"required":
1541
+ {"image": (sorted(files), {"image_upload": True})},
1542
+ }
1543
+
1544
+ CATEGORY = "image"
1545
+
1546
+ RETURN_TYPES = ("IMAGE", "MASK")
1547
+ FUNCTION = "load_image"
1548
+ def load_image(self, image):
1549
+ image_path = folder_paths.get_annotated_filepath(image)
1550
+
1551
+ img = node_helpers.pillow(Image.open, image_path)
1552
+
1553
+ output_images = []
1554
+ output_masks = []
1555
+ w, h = None, None
1556
+
1557
+ excluded_formats = ['MPO']
1558
+
1559
+ for i in ImageSequence.Iterator(img):
1560
+ i = node_helpers.pillow(ImageOps.exif_transpose, i)
1561
+
1562
+ if i.mode == 'I':
1563
+ i = i.point(lambda i: i * (1 / 255))
1564
+ image = i.convert("RGB")
1565
+
1566
+ if len(output_images) == 0:
1567
+ w = image.size[0]
1568
+ h = image.size[1]
1569
+
1570
+ if image.size[0] != w or image.size[1] != h:
1571
+ continue
1572
+
1573
+ image = np.array(image).astype(np.float32) / 255.0
1574
+ image = torch.from_numpy(image)[None,]
1575
+ if 'A' in i.getbands():
1576
+ mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
1577
+ mask = 1. - torch.from_numpy(mask)
1578
+ else:
1579
+ mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
1580
+ output_images.append(image)
1581
+ output_masks.append(mask.unsqueeze(0))
1582
+
1583
+ if len(output_images) > 1 and img.format not in excluded_formats:
1584
+ output_image = torch.cat(output_images, dim=0)
1585
+ output_mask = torch.cat(output_masks, dim=0)
1586
+ else:
1587
+ output_image = output_images[0]
1588
+ output_mask = output_masks[0]
1589
+
1590
+ return (output_image, output_mask)
1591
+
1592
+ @classmethod
1593
+ def IS_CHANGED(s, image):
1594
+ image_path = folder_paths.get_annotated_filepath(image)
1595
+ m = hashlib.sha256()
1596
+ with open(image_path, 'rb') as f:
1597
+ m.update(f.read())
1598
+ return m.digest().hex()
1599
+
1600
+ @classmethod
1601
+ def VALIDATE_INPUTS(s, image):
1602
+ if not folder_paths.exists_annotated_filepath(image):
1603
+ return "Invalid image file: {}".format(image)
1604
+
1605
+ return True
1606
+
1607
+ class LoadImageMask:
1608
+ _color_channels = ["alpha", "red", "green", "blue"]
1609
+ @classmethod
1610
+ def INPUT_TYPES(s):
1611
+ input_dir = folder_paths.get_input_directory()
1612
+ files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
1613
+ return {"required":
1614
+ {"image": (sorted(files), {"image_upload": True}),
1615
+ "channel": (s._color_channels, ), }
1616
+ }
1617
+
1618
+ CATEGORY = "mask"
1619
+
1620
+ RETURN_TYPES = ("MASK",)
1621
+ FUNCTION = "load_image"
1622
+ def load_image(self, image, channel):
1623
+ image_path = folder_paths.get_annotated_filepath(image)
1624
+ i = node_helpers.pillow(Image.open, image_path)
1625
+ i = node_helpers.pillow(ImageOps.exif_transpose, i)
1626
+ if i.getbands() != ("R", "G", "B", "A"):
1627
+ if i.mode == 'I':
1628
+ i = i.point(lambda i: i * (1 / 255))
1629
+ i = i.convert("RGBA")
1630
+ mask = None
1631
+ c = channel[0].upper()
1632
+ if c in i.getbands():
1633
+ mask = np.array(i.getchannel(c)).astype(np.float32) / 255.0
1634
+ mask = torch.from_numpy(mask)
1635
+ if c == 'A':
1636
+ mask = 1. - mask
1637
+ else:
1638
+ mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
1639
+ return (mask.unsqueeze(0),)
1640
+
1641
+ @classmethod
1642
+ def IS_CHANGED(s, image, channel):
1643
+ image_path = folder_paths.get_annotated_filepath(image)
1644
+ m = hashlib.sha256()
1645
+ with open(image_path, 'rb') as f:
1646
+ m.update(f.read())
1647
+ return m.digest().hex()
1648
+
1649
+ @classmethod
1650
+ def VALIDATE_INPUTS(s, image):
1651
+ if not folder_paths.exists_annotated_filepath(image):
1652
+ return "Invalid image file: {}".format(image)
1653
+
1654
+ return True
1655
+
1656
+ class ImageScale:
1657
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
1658
+ crop_methods = ["disabled", "center"]
1659
+
1660
+ @classmethod
1661
+ def INPUT_TYPES(s):
1662
+ return {"required": { "image": ("IMAGE",), "upscale_method": (s.upscale_methods,),
1663
+ "width": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
1664
+ "height": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
1665
+ "crop": (s.crop_methods,)}}
1666
+ RETURN_TYPES = ("IMAGE",)
1667
+ FUNCTION = "upscale"
1668
+
1669
+ CATEGORY = "image/upscaling"
1670
+
1671
+ def upscale(self, image, upscale_method, width, height, crop):
1672
+ if width == 0 and height == 0:
1673
+ s = image
1674
+ else:
1675
+ samples = image.movedim(-1,1)
1676
+
1677
+ if width == 0:
1678
+ width = max(1, round(samples.shape[3] * height / samples.shape[2]))
1679
+ elif height == 0:
1680
+ height = max(1, round(samples.shape[2] * width / samples.shape[3]))
1681
+
1682
+ s = comfy.utils.common_upscale(samples, width, height, upscale_method, crop)
1683
+ s = s.movedim(1,-1)
1684
+ return (s,)
1685
+
1686
+ class ImageScaleBy:
1687
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
1688
+
1689
+ @classmethod
1690
+ def INPUT_TYPES(s):
1691
+ return {"required": { "image": ("IMAGE",), "upscale_method": (s.upscale_methods,),
1692
+ "scale_by": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 8.0, "step": 0.01}),}}
1693
+ RETURN_TYPES = ("IMAGE",)
1694
+ FUNCTION = "upscale"
1695
+
1696
+ CATEGORY = "image/upscaling"
1697
+
1698
+ def upscale(self, image, upscale_method, scale_by):
1699
+ samples = image.movedim(-1,1)
1700
+ width = round(samples.shape[3] * scale_by)
1701
+ height = round(samples.shape[2] * scale_by)
1702
+ s = comfy.utils.common_upscale(samples, width, height, upscale_method, "disabled")
1703
+ s = s.movedim(1,-1)
1704
+ return (s,)
1705
+
1706
+ class ImageInvert:
1707
+
1708
+ @classmethod
1709
+ def INPUT_TYPES(s):
1710
+ return {"required": { "image": ("IMAGE",)}}
1711
+
1712
+ RETURN_TYPES = ("IMAGE",)
1713
+ FUNCTION = "invert"
1714
+
1715
+ CATEGORY = "image"
1716
+
1717
+ def invert(self, image):
1718
+ s = 1.0 - image
1719
+ return (s,)
1720
+
1721
+ class ImageBatch:
1722
+
1723
+ @classmethod
1724
+ def INPUT_TYPES(s):
1725
+ return {"required": { "image1": ("IMAGE",), "image2": ("IMAGE",)}}
1726
+
1727
+ RETURN_TYPES = ("IMAGE",)
1728
+ FUNCTION = "batch"
1729
+
1730
+ CATEGORY = "image"
1731
+
1732
+ def batch(self, image1, image2):
1733
+ if image1.shape[1:] != image2.shape[1:]:
1734
+ image2 = comfy.utils.common_upscale(image2.movedim(-1,1), image1.shape[2], image1.shape[1], "bilinear", "center").movedim(1,-1)
1735
+ s = torch.cat((image1, image2), dim=0)
1736
+ return (s,)
1737
+
1738
+ class EmptyImage:
1739
+ def __init__(self, device="cpu"):
1740
+ self.device = device
1741
+
1742
+ @classmethod
1743
+ def INPUT_TYPES(s):
1744
+ return {"required": { "width": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
1745
+ "height": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
1746
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}),
1747
+ "color": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFF, "step": 1, "display": "color"}),
1748
+ }}
1749
+ RETURN_TYPES = ("IMAGE",)
1750
+ FUNCTION = "generate"
1751
+
1752
+ CATEGORY = "image"
1753
+
1754
+ def generate(self, width, height, batch_size=1, color=0):
1755
+ r = torch.full([batch_size, height, width, 1], ((color >> 16) & 0xFF) / 0xFF)
1756
+ g = torch.full([batch_size, height, width, 1], ((color >> 8) & 0xFF) / 0xFF)
1757
+ b = torch.full([batch_size, height, width, 1], ((color) & 0xFF) / 0xFF)
1758
+ return (torch.cat((r, g, b), dim=-1), )
1759
+
1760
+ class ImagePadForOutpaint:
1761
+
1762
+ @classmethod
1763
+ def INPUT_TYPES(s):
1764
+ return {
1765
+ "required": {
1766
+ "image": ("IMAGE",),
1767
+ "left": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1768
+ "top": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1769
+ "right": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1770
+ "bottom": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1771
+ "feathering": ("INT", {"default": 40, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
1772
+ }
1773
+ }
1774
+
1775
+ RETURN_TYPES = ("IMAGE", "MASK")
1776
+ FUNCTION = "expand_image"
1777
+
1778
+ CATEGORY = "image"
1779
+
1780
+ def expand_image(self, image, left, top, right, bottom, feathering):
1781
+ d1, d2, d3, d4 = image.size()
1782
+
1783
+ new_image = torch.ones(
1784
+ (d1, d2 + top + bottom, d3 + left + right, d4),
1785
+ dtype=torch.float32,
1786
+ ) * 0.5
1787
+
1788
+ new_image[:, top:top + d2, left:left + d3, :] = image
1789
+
1790
+ mask = torch.ones(
1791
+ (d2 + top + bottom, d3 + left + right),
1792
+ dtype=torch.float32,
1793
+ )
1794
+
1795
+ t = torch.zeros(
1796
+ (d2, d3),
1797
+ dtype=torch.float32
1798
+ )
1799
+
1800
+ if feathering > 0 and feathering * 2 < d2 and feathering * 2 < d3:
1801
+
1802
+ for i in range(d2):
1803
+ for j in range(d3):
1804
+ dt = i if top != 0 else d2
1805
+ db = d2 - i if bottom != 0 else d2
1806
+
1807
+ dl = j if left != 0 else d3
1808
+ dr = d3 - j if right != 0 else d3
1809
+
1810
+ d = min(dt, db, dl, dr)
1811
+
1812
+ if d >= feathering:
1813
+ continue
1814
+
1815
+ v = (feathering - d) / feathering
1816
+
1817
+ t[i, j] = v * v
1818
+
1819
+ mask[top:top + d2, left:left + d3] = t
1820
+
1821
+ return (new_image, mask)
1822
+
1823
+
1824
+ NODE_CLASS_MAPPINGS = {
1825
+ "KSampler": KSampler,
1826
+ "CheckpointLoaderSimple": CheckpointLoaderSimple,
1827
+ "CLIPTextEncode": CLIPTextEncode,
1828
+ "CLIPSetLastLayer": CLIPSetLastLayer,
1829
+ "VAEDecode": VAEDecode,
1830
+ "VAEEncode": VAEEncode,
1831
+ "VAEEncodeForInpaint": VAEEncodeForInpaint,
1832
+ "VAELoader": VAELoader,
1833
+ "EmptyLatentImage": EmptyLatentImage,
1834
+ "LatentUpscale": LatentUpscale,
1835
+ "LatentUpscaleBy": LatentUpscaleBy,
1836
+ "LatentFromBatch": LatentFromBatch,
1837
+ "RepeatLatentBatch": RepeatLatentBatch,
1838
+ "SaveImage": SaveImage,
1839
+ "PreviewImage": PreviewImage,
1840
+ "LoadImage": LoadImage,
1841
+ "LoadImageMask": LoadImageMask,
1842
+ "ImageScale": ImageScale,
1843
+ "ImageScaleBy": ImageScaleBy,
1844
+ "ImageInvert": ImageInvert,
1845
+ "ImageBatch": ImageBatch,
1846
+ "ImagePadForOutpaint": ImagePadForOutpaint,
1847
+ "EmptyImage": EmptyImage,
1848
+ "ConditioningAverage": ConditioningAverage ,
1849
+ "ConditioningCombine": ConditioningCombine,
1850
+ "ConditioningConcat": ConditioningConcat,
1851
+ "ConditioningSetArea": ConditioningSetArea,
1852
+ "ConditioningSetAreaPercentage": ConditioningSetAreaPercentage,
1853
+ "ConditioningSetAreaStrength": ConditioningSetAreaStrength,
1854
+ "ConditioningSetMask": ConditioningSetMask,
1855
+ "KSamplerAdvanced": KSamplerAdvanced,
1856
+ "SetLatentNoiseMask": SetLatentNoiseMask,
1857
+ "LatentComposite": LatentComposite,
1858
+ "LatentBlend": LatentBlend,
1859
+ "LatentRotate": LatentRotate,
1860
+ "LatentFlip": LatentFlip,
1861
+ "LatentCrop": LatentCrop,
1862
+ "LoraLoader": LoraLoader,
1863
+ "CLIPLoader": CLIPLoader,
1864
+ "UNETLoader": UNETLoader,
1865
+ "DualCLIPLoader": DualCLIPLoader,
1866
+ "CLIPVisionEncode": CLIPVisionEncode,
1867
+ "StyleModelApply": StyleModelApply,
1868
+ "unCLIPConditioning": unCLIPConditioning,
1869
+ "ControlNetApply": ControlNetApply,
1870
+ "ControlNetApplyAdvanced": ControlNetApplyAdvanced,
1871
+ "ControlNetLoader": ControlNetLoader,
1872
+ "DiffControlNetLoader": DiffControlNetLoader,
1873
+ "StyleModelLoader": StyleModelLoader,
1874
+ "CLIPVisionLoader": CLIPVisionLoader,
1875
+ "VAEDecodeTiled": VAEDecodeTiled,
1876
+ "VAEEncodeTiled": VAEEncodeTiled,
1877
+ "unCLIPCheckpointLoader": unCLIPCheckpointLoader,
1878
+ "GLIGENLoader": GLIGENLoader,
1879
+ "GLIGENTextBoxApply": GLIGENTextBoxApply,
1880
+ "InpaintModelConditioning": InpaintModelConditioning,
1881
+
1882
+ "CheckpointLoader": CheckpointLoader,
1883
+ "DiffusersLoader": DiffusersLoader,
1884
+
1885
+ "LoadLatent": LoadLatent,
1886
+ "SaveLatent": SaveLatent,
1887
+
1888
+ "ConditioningZeroOut": ConditioningZeroOut,
1889
+ "ConditioningSetTimestepRange": ConditioningSetTimestepRange,
1890
+ "LoraLoaderModelOnly": LoraLoaderModelOnly,
1891
+ }
1892
+
1893
+ NODE_DISPLAY_NAME_MAPPINGS = {
1894
+ # Sampling
1895
+ "KSampler": "KSampler",
1896
+ "KSamplerAdvanced": "KSampler (Advanced)",
1897
+ # Loaders
1898
+ "CheckpointLoader": "Load Checkpoint With Config (DEPRECATED)",
1899
+ "CheckpointLoaderSimple": "Load Checkpoint",
1900
+ "VAELoader": "Load VAE",
1901
+ "LoraLoader": "Load LoRA",
1902
+ "CLIPLoader": "Load CLIP",
1903
+ "ControlNetLoader": "Load ControlNet Model",
1904
+ "DiffControlNetLoader": "Load ControlNet Model (diff)",
1905
+ "StyleModelLoader": "Load Style Model",
1906
+ "CLIPVisionLoader": "Load CLIP Vision",
1907
+ "UpscaleModelLoader": "Load Upscale Model",
1908
+ "UNETLoader": "Load Diffusion Model",
1909
+ # Conditioning
1910
+ "CLIPVisionEncode": "CLIP Vision Encode",
1911
+ "StyleModelApply": "Apply Style Model",
1912
+ "CLIPTextEncode": "CLIP Text Encode (Prompt)",
1913
+ "CLIPSetLastLayer": "CLIP Set Last Layer",
1914
+ "ConditioningCombine": "Conditioning (Combine)",
1915
+ "ConditioningAverage ": "Conditioning (Average)",
1916
+ "ConditioningConcat": "Conditioning (Concat)",
1917
+ "ConditioningSetArea": "Conditioning (Set Area)",
1918
+ "ConditioningSetAreaPercentage": "Conditioning (Set Area with Percentage)",
1919
+ "ConditioningSetMask": "Conditioning (Set Mask)",
1920
+ "ControlNetApply": "Apply ControlNet",
1921
+ "ControlNetApplyAdvanced": "Apply ControlNet (Advanced)",
1922
+ # Latent
1923
+ "VAEEncodeForInpaint": "VAE Encode (for Inpainting)",
1924
+ "SetLatentNoiseMask": "Set Latent Noise Mask",
1925
+ "VAEDecode": "VAE Decode",
1926
+ "VAEEncode": "VAE Encode",
1927
+ "LatentRotate": "Rotate Latent",
1928
+ "LatentFlip": "Flip Latent",
1929
+ "LatentCrop": "Crop Latent",
1930
+ "EmptyLatentImage": "Empty Latent Image",
1931
+ "LatentUpscale": "Upscale Latent",
1932
+ "LatentUpscaleBy": "Upscale Latent By",
1933
+ "LatentComposite": "Latent Composite",
1934
+ "LatentBlend": "Latent Blend",
1935
+ "LatentFromBatch" : "Latent From Batch",
1936
+ "RepeatLatentBatch": "Repeat Latent Batch",
1937
+ # Image
1938
+ "SaveImage": "Save Image",
1939
+ "PreviewImage": "Preview Image",
1940
+ "LoadImage": "Load Image",
1941
+ "LoadImageMask": "Load Image (as Mask)",
1942
+ "ImageScale": "Upscale Image",
1943
+ "ImageScaleBy": "Upscale Image By",
1944
+ "ImageUpscaleWithModel": "Upscale Image (using Model)",
1945
+ "ImageInvert": "Invert Image",
1946
+ "ImagePadForOutpaint": "Pad Image for Outpainting",
1947
+ "ImageBatch": "Batch Images",
1948
+ # _for_testing
1949
+ "VAEDecodeTiled": "VAE Decode (Tiled)",
1950
+ "VAEEncodeTiled": "VAE Encode (Tiled)",
1951
+ }
1952
+
1953
+ EXTENSION_WEB_DIRS = {}
1954
+
1955
+
1956
+ def get_module_name(module_path: str) -> str:
1957
+ """
1958
+ Returns the module name based on the given module path.
1959
+ Examples:
1960
+ get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node.py") -> "my_custom_node"
1961
+ get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node") -> "my_custom_node"
1962
+ get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/") -> "my_custom_node"
1963
+ get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/__init__.py") -> "my_custom_node"
1964
+ get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/__init__") -> "my_custom_node"
1965
+ get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/__init__/") -> "my_custom_node"
1966
+ get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node.disabled") -> "custom_nodes
1967
+ Args:
1968
+ module_path (str): The path of the module.
1969
+ Returns:
1970
+ str: The module name.
1971
+ """
1972
+ base_path = os.path.basename(module_path)
1973
+ if os.path.isfile(module_path):
1974
+ base_path = os.path.splitext(base_path)[0]
1975
+ return base_path
1976
+
1977
+
1978
+ def load_custom_node(module_path: str, ignore=set(), module_parent="custom_nodes") -> bool:
1979
+ module_name = os.path.basename(module_path)
1980
+ if os.path.isfile(module_path):
1981
+ sp = os.path.splitext(module_path)
1982
+ module_name = sp[0]
1983
+ try:
1984
+ logging.debug("Trying to load custom node {}".format(module_path))
1985
+ if os.path.isfile(module_path):
1986
+ module_spec = importlib.util.spec_from_file_location(module_name, module_path)
1987
+ module_dir = os.path.split(module_path)[0]
1988
+ else:
1989
+ module_spec = importlib.util.spec_from_file_location(module_name, os.path.join(module_path, "__init__.py"))
1990
+ module_dir = module_path
1991
+
1992
+ module = importlib.util.module_from_spec(module_spec)
1993
+ sys.modules[module_name] = module
1994
+ module_spec.loader.exec_module(module)
1995
+
1996
+ if hasattr(module, "WEB_DIRECTORY") and getattr(module, "WEB_DIRECTORY") is not None:
1997
+ web_dir = os.path.abspath(os.path.join(module_dir, getattr(module, "WEB_DIRECTORY")))
1998
+ if os.path.isdir(web_dir):
1999
+ EXTENSION_WEB_DIRS[module_name] = web_dir
2000
+
2001
+ if hasattr(module, "NODE_CLASS_MAPPINGS") and getattr(module, "NODE_CLASS_MAPPINGS") is not None:
2002
+ for name, node_cls in module.NODE_CLASS_MAPPINGS.items():
2003
+ if name not in ignore:
2004
+ NODE_CLASS_MAPPINGS[name] = node_cls
2005
+ node_cls.RELATIVE_PYTHON_MODULE = "{}.{}".format(module_parent, get_module_name(module_path))
2006
+ if hasattr(module, "NODE_DISPLAY_NAME_MAPPINGS") and getattr(module, "NODE_DISPLAY_NAME_MAPPINGS") is not None:
2007
+ NODE_DISPLAY_NAME_MAPPINGS.update(module.NODE_DISPLAY_NAME_MAPPINGS)
2008
+ return True
2009
+ else:
2010
+ logging.warning(f"Skip {module_path} module for custom nodes due to the lack of NODE_CLASS_MAPPINGS.")
2011
+ return False
2012
+ except Exception as e:
2013
+ logging.warning(traceback.format_exc())
2014
+ logging.warning(f"Cannot import {module_path} module for custom nodes: {e}")
2015
+ return False
2016
+
2017
+ def init_external_custom_nodes():
2018
+ """
2019
+ Initializes the external custom nodes.
2020
+
2021
+ This function loads custom nodes from the specified folder paths and imports them into the application.
2022
+ It measures the import times for each custom node and logs the results.
2023
+
2024
+ Returns:
2025
+ None
2026
+ """
2027
+ base_node_names = set(NODE_CLASS_MAPPINGS.keys())
2028
+ node_paths = folder_paths.get_folder_paths("custom_nodes")
2029
+ node_import_times = []
2030
+ for custom_node_path in node_paths:
2031
+ possible_modules = os.listdir(os.path.realpath(custom_node_path))
2032
+ if "__pycache__" in possible_modules:
2033
+ possible_modules.remove("__pycache__")
2034
+
2035
+ for possible_module in possible_modules:
2036
+ module_path = os.path.join(custom_node_path, possible_module)
2037
+ if os.path.isfile(module_path) and os.path.splitext(module_path)[1] != ".py": continue
2038
+ if module_path.endswith(".disabled"): continue
2039
+ time_before = time.perf_counter()
2040
+ success = load_custom_node(module_path, base_node_names, module_parent="custom_nodes")
2041
+ node_import_times.append((time.perf_counter() - time_before, module_path, success))
2042
+
2043
+ if len(node_import_times) > 0:
2044
+ logging.info("Import times for custom nodes:")
2045
+ for n in sorted(node_import_times):
2046
+ if n[2]:
2047
+ import_message = ""
2048
+ else:
2049
+ import_message = " (IMPORT FAILED)"
2050
+ logging.info("{:6.1f} seconds{}: {}".format(n[0], import_message, n[1]))
2051
+ logging.info("")
2052
+
2053
+ def init_builtin_extra_nodes():
2054
+ """
2055
+ Initializes the built-in extra nodes in ComfyUI.
2056
+
2057
+ This function loads the extra node files located in the "comfy_extras" directory and imports them into ComfyUI.
2058
+ If any of the extra node files fail to import, a warning message is logged.
2059
+
2060
+ Returns:
2061
+ None
2062
+ """
2063
+ extras_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras")
2064
+ extras_files = [
2065
+ "nodes_latent.py",
2066
+ "nodes_hypernetwork.py",
2067
+ "nodes_upscale_model.py",
2068
+ "nodes_post_processing.py",
2069
+ "nodes_mask.py",
2070
+ "nodes_compositing.py",
2071
+ "nodes_rebatch.py",
2072
+ "nodes_model_merging.py",
2073
+ "nodes_tomesd.py",
2074
+ "nodes_clip_sdxl.py",
2075
+ "nodes_canny.py",
2076
+ "nodes_freelunch.py",
2077
+ "nodes_custom_sampler.py",
2078
+ "nodes_hypertile.py",
2079
+ "nodes_model_advanced.py",
2080
+ "nodes_model_downscale.py",
2081
+ "nodes_images.py",
2082
+ "nodes_video_model.py",
2083
+ "nodes_sag.py",
2084
+ "nodes_perpneg.py",
2085
+ "nodes_stable3d.py",
2086
+ "nodes_sdupscale.py",
2087
+ "nodes_photomaker.py",
2088
+ "nodes_cond.py",
2089
+ "nodes_morphology.py",
2090
+ "nodes_stable_cascade.py",
2091
+ "nodes_differential_diffusion.py",
2092
+ "nodes_ip2p.py",
2093
+ "nodes_model_merging_model_specific.py",
2094
+ "nodes_pag.py",
2095
+ "nodes_align_your_steps.py",
2096
+ "nodes_attention_multiply.py",
2097
+ "nodes_advanced_samplers.py",
2098
+ "nodes_webcam.py",
2099
+ "nodes_audio.py",
2100
+ "nodes_sd3.py",
2101
+ "nodes_gits.py",
2102
+ "nodes_controlnet.py",
2103
+ "nodes_hunyuan.py",
2104
+ "nodes_flux.py",
2105
+ "nodes_lora_extract.py",
2106
+ "nodes_torch_compile.py",
2107
+ ]
2108
+
2109
+ import_failed = []
2110
+ for node_file in extras_files:
2111
+ if not load_custom_node(os.path.join(extras_dir, node_file), module_parent="comfy_extras"):
2112
+ import_failed.append(node_file)
2113
+
2114
+ return import_failed
2115
+
2116
+
2117
+ def init_extra_nodes(init_custom_nodes=True):
2118
+ import_failed = init_builtin_extra_nodes()
2119
+
2120
+ if init_custom_nodes:
2121
+ init_external_custom_nodes()
2122
+ else:
2123
+ logging.info("Skipping loading of custom nodes")
2124
+
2125
+ if len(import_failed) > 0:
2126
+ logging.warning("WARNING: some comfy_extras/ nodes did not import correctly. This may be because they are missing some dependencies.\n")
2127
+ for node in import_failed:
2128
+ logging.warning("IMPORT FAILED: {}".format(node))
2129
+ logging.warning("\nThis issue might be caused by new missing dependencies added the last time you updated ComfyUI.")
2130
+ if args.windows_standalone_build:
2131
+ logging.warning("Please run the update script: update/update_comfyui.bat")
2132
+ else:
2133
+ logging.warning("Please do a: pip install -r requirements.txt")
2134
+ logging.warning("")
2135
+
2136
+ return import_failed
notebooks/comfyui_colab.ipynb ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {
6
+ "id": "aaaaaaaaaa"
7
+ },
8
+ "source": [
9
+ "Git clone the repo and install the requirements. (ignore the pip errors about protobuf)"
10
+ ]
11
+ },
12
+ {
13
+ "cell_type": "code",
14
+ "execution_count": null,
15
+ "metadata": {
16
+ "id": "bbbbbbbbbb"
17
+ },
18
+ "outputs": [],
19
+ "source": [
20
+ "#@title Environment Setup\n",
21
+ "\n",
22
+ "from pathlib import Path\n",
23
+ "\n",
24
+ "OPTIONS = {}\n",
25
+ "\n",
26
+ "USE_GOOGLE_DRIVE = False #@param {type:\"boolean\"}\n",
27
+ "UPDATE_COMFY_UI = True #@param {type:\"boolean\"}\n",
28
+ "WORKSPACE = 'ComfyUI'\n",
29
+ "OPTIONS['USE_GOOGLE_DRIVE'] = USE_GOOGLE_DRIVE\n",
30
+ "OPTIONS['UPDATE_COMFY_UI'] = UPDATE_COMFY_UI\n",
31
+ "\n",
32
+ "if OPTIONS['USE_GOOGLE_DRIVE']:\n",
33
+ " !echo \"Mounting Google Drive...\"\n",
34
+ " %cd /\n",
35
+ " \n",
36
+ " from google.colab import drive\n",
37
+ " drive.mount('/content/drive')\n",
38
+ "\n",
39
+ " WORKSPACE = \"/content/drive/MyDrive/ComfyUI\"\n",
40
+ " %cd /content/drive/MyDrive\n",
41
+ "\n",
42
+ "![ ! -d $WORKSPACE ] && echo -= Initial setup ComfyUI =- && git clone https://github.com/comfyanonymous/ComfyUI\n",
43
+ "%cd $WORKSPACE\n",
44
+ "\n",
45
+ "if OPTIONS['UPDATE_COMFY_UI']:\n",
46
+ " !echo -= Updating ComfyUI =-\n",
47
+ " !git pull\n",
48
+ "\n",
49
+ "!echo -= Install dependencies =-\n",
50
+ "!pip install xformers!=0.0.18 -r requirements.txt --extra-index-url https://download.pytorch.org/whl/cu121 --extra-index-url https://download.pytorch.org/whl/cu118 --extra-index-url https://download.pytorch.org/whl/cu117"
51
+ ]
52
+ },
53
+ {
54
+ "cell_type": "markdown",
55
+ "metadata": {
56
+ "id": "cccccccccc"
57
+ },
58
+ "source": [
59
+ "Download some models/checkpoints/vae or custom comfyui nodes (uncomment the commands for the ones you want)"
60
+ ]
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "execution_count": null,
65
+ "metadata": {
66
+ "id": "dddddddddd"
67
+ },
68
+ "outputs": [],
69
+ "source": [
70
+ "# Checkpoints\n",
71
+ "\n",
72
+ "### SDXL\n",
73
+ "### I recommend these workflow examples: https://comfyanonymous.github.io/ComfyUI_examples/sdxl/\n",
74
+ "\n",
75
+ "#!wget -c https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_base_1.0.safetensors -P ./models/checkpoints/\n",
76
+ "#!wget -c https://huggingface.co/stabilityai/stable-diffusion-xl-refiner-1.0/resolve/main/sd_xl_refiner_1.0.safetensors -P ./models/checkpoints/\n",
77
+ "\n",
78
+ "# SDXL ReVision\n",
79
+ "#!wget -c https://huggingface.co/comfyanonymous/clip_vision_g/resolve/main/clip_vision_g.safetensors -P ./models/clip_vision/\n",
80
+ "\n",
81
+ "# SD1.5\n",
82
+ "!wget -c https://huggingface.co/Comfy-Org/stable-diffusion-v1-5-archive/resolve/main/v1-5-pruned-emaonly-fp16.safetensors -P ./models/checkpoints/\n",
83
+ "\n",
84
+ "# SD2\n",
85
+ "#!wget -c https://huggingface.co/stabilityai/stable-diffusion-2-1-base/resolve/main/v2-1_512-ema-pruned.safetensors -P ./models/checkpoints/\n",
86
+ "#!wget -c https://huggingface.co/stabilityai/stable-diffusion-2-1/resolve/main/v2-1_768-ema-pruned.safetensors -P ./models/checkpoints/\n",
87
+ "\n",
88
+ "# Some SD1.5 anime style\n",
89
+ "#!wget -c https://huggingface.co/WarriorMama777/OrangeMixs/resolve/main/Models/AbyssOrangeMix2/AbyssOrangeMix2_hard.safetensors -P ./models/checkpoints/\n",
90
+ "#!wget -c https://huggingface.co/WarriorMama777/OrangeMixs/resolve/main/Models/AbyssOrangeMix3/AOM3A1_orangemixs.safetensors -P ./models/checkpoints/\n",
91
+ "#!wget -c https://huggingface.co/WarriorMama777/OrangeMixs/resolve/main/Models/AbyssOrangeMix3/AOM3A3_orangemixs.safetensors -P ./models/checkpoints/\n",
92
+ "#!wget -c https://huggingface.co/Linaqruf/anything-v3.0/resolve/main/anything-v3-fp16-pruned.safetensors -P ./models/checkpoints/\n",
93
+ "\n",
94
+ "# Waifu Diffusion 1.5 (anime style SD2.x 768-v)\n",
95
+ "#!wget -c https://huggingface.co/waifu-diffusion/wd-1-5-beta3/resolve/main/wd-illusion-fp16.safetensors -P ./models/checkpoints/\n",
96
+ "\n",
97
+ "\n",
98
+ "# unCLIP models\n",
99
+ "#!wget -c https://huggingface.co/comfyanonymous/illuminatiDiffusionV1_v11_unCLIP/resolve/main/illuminatiDiffusionV1_v11-unclip-h-fp16.safetensors -P ./models/checkpoints/\n",
100
+ "#!wget -c https://huggingface.co/comfyanonymous/wd-1.5-beta2_unCLIP/resolve/main/wd-1-5-beta2-aesthetic-unclip-h-fp16.safetensors -P ./models/checkpoints/\n",
101
+ "\n",
102
+ "\n",
103
+ "# VAE\n",
104
+ "!wget -c https://huggingface.co/stabilityai/sd-vae-ft-mse-original/resolve/main/vae-ft-mse-840000-ema-pruned.safetensors -P ./models/vae/\n",
105
+ "#!wget -c https://huggingface.co/WarriorMama777/OrangeMixs/resolve/main/VAEs/orangemix.vae.pt -P ./models/vae/\n",
106
+ "#!wget -c https://huggingface.co/hakurei/waifu-diffusion-v1-4/resolve/main/vae/kl-f8-anime2.ckpt -P ./models/vae/\n",
107
+ "\n",
108
+ "\n",
109
+ "# Loras\n",
110
+ "#!wget -c https://civitai.com/api/download/models/10350 -O ./models/loras/theovercomer8sContrastFix_sd21768.safetensors #theovercomer8sContrastFix SD2.x 768-v\n",
111
+ "#!wget -c https://civitai.com/api/download/models/10638 -O ./models/loras/theovercomer8sContrastFix_sd15.safetensors #theovercomer8sContrastFix SD1.x\n",
112
+ "#!wget -c https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0/resolve/main/sd_xl_offset_example-lora_1.0.safetensors -P ./models/loras/ #SDXL offset noise lora\n",
113
+ "\n",
114
+ "\n",
115
+ "# T2I-Adapter\n",
116
+ "#!wget -c https://huggingface.co/TencentARC/T2I-Adapter/resolve/main/models/t2iadapter_depth_sd14v1.pth -P ./models/controlnet/\n",
117
+ "#!wget -c https://huggingface.co/TencentARC/T2I-Adapter/resolve/main/models/t2iadapter_seg_sd14v1.pth -P ./models/controlnet/\n",
118
+ "#!wget -c https://huggingface.co/TencentARC/T2I-Adapter/resolve/main/models/t2iadapter_sketch_sd14v1.pth -P ./models/controlnet/\n",
119
+ "#!wget -c https://huggingface.co/TencentARC/T2I-Adapter/resolve/main/models/t2iadapter_keypose_sd14v1.pth -P ./models/controlnet/\n",
120
+ "#!wget -c https://huggingface.co/TencentARC/T2I-Adapter/resolve/main/models/t2iadapter_openpose_sd14v1.pth -P ./models/controlnet/\n",
121
+ "#!wget -c https://huggingface.co/TencentARC/T2I-Adapter/resolve/main/models/t2iadapter_color_sd14v1.pth -P ./models/controlnet/\n",
122
+ "#!wget -c https://huggingface.co/TencentARC/T2I-Adapter/resolve/main/models/t2iadapter_canny_sd14v1.pth -P ./models/controlnet/\n",
123
+ "\n",
124
+ "# T2I Styles Model\n",
125
+ "#!wget -c https://huggingface.co/TencentARC/T2I-Adapter/resolve/main/models/t2iadapter_style_sd14v1.pth -P ./models/style_models/\n",
126
+ "\n",
127
+ "# CLIPVision model (needed for styles model)\n",
128
+ "#!wget -c https://huggingface.co/openai/clip-vit-large-patch14/resolve/main/pytorch_model.bin -O ./models/clip_vision/clip_vit14.bin\n",
129
+ "\n",
130
+ "\n",
131
+ "# ControlNet\n",
132
+ "#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11e_sd15_ip2p_fp16.safetensors -P ./models/controlnet/\n",
133
+ "#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11e_sd15_shuffle_fp16.safetensors -P ./models/controlnet/\n",
134
+ "#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_canny_fp16.safetensors -P ./models/controlnet/\n",
135
+ "#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11f1p_sd15_depth_fp16.safetensors -P ./models/controlnet/\n",
136
+ "#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_inpaint_fp16.safetensors -P ./models/controlnet/\n",
137
+ "#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_lineart_fp16.safetensors -P ./models/controlnet/\n",
138
+ "#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_mlsd_fp16.safetensors -P ./models/controlnet/\n",
139
+ "#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_normalbae_fp16.safetensors -P ./models/controlnet/\n",
140
+ "#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_openpose_fp16.safetensors -P ./models/controlnet/\n",
141
+ "#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_scribble_fp16.safetensors -P ./models/controlnet/\n",
142
+ "#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_seg_fp16.safetensors -P ./models/controlnet/\n",
143
+ "#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15_softedge_fp16.safetensors -P ./models/controlnet/\n",
144
+ "#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11p_sd15s2_lineart_anime_fp16.safetensors -P ./models/controlnet/\n",
145
+ "#!wget -c https://huggingface.co/comfyanonymous/ControlNet-v1-1_fp16_safetensors/resolve/main/control_v11u_sd15_tile_fp16.safetensors -P ./models/controlnet/\n",
146
+ "\n",
147
+ "# ControlNet SDXL\n",
148
+ "#!wget -c https://huggingface.co/stabilityai/control-lora/resolve/main/control-LoRAs-rank256/control-lora-canny-rank256.safetensors -P ./models/controlnet/\n",
149
+ "#!wget -c https://huggingface.co/stabilityai/control-lora/resolve/main/control-LoRAs-rank256/control-lora-depth-rank256.safetensors -P ./models/controlnet/\n",
150
+ "#!wget -c https://huggingface.co/stabilityai/control-lora/resolve/main/control-LoRAs-rank256/control-lora-recolor-rank256.safetensors -P ./models/controlnet/\n",
151
+ "#!wget -c https://huggingface.co/stabilityai/control-lora/resolve/main/control-LoRAs-rank256/control-lora-sketch-rank256.safetensors -P ./models/controlnet/\n",
152
+ "\n",
153
+ "# Controlnet Preprocessor nodes by Fannovel16\n",
154
+ "#!cd custom_nodes && git clone https://github.com/Fannovel16/comfy_controlnet_preprocessors; cd comfy_controlnet_preprocessors && python install.py\n",
155
+ "\n",
156
+ "\n",
157
+ "# GLIGEN\n",
158
+ "#!wget -c https://huggingface.co/comfyanonymous/GLIGEN_pruned_safetensors/resolve/main/gligen_sd14_textbox_pruned_fp16.safetensors -P ./models/gligen/\n",
159
+ "\n",
160
+ "\n",
161
+ "# ESRGAN upscale model\n",
162
+ "#!wget -c https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth -P ./models/upscale_models/\n",
163
+ "#!wget -c https://huggingface.co/sberbank-ai/Real-ESRGAN/resolve/main/RealESRGAN_x2.pth -P ./models/upscale_models/\n",
164
+ "#!wget -c https://huggingface.co/sberbank-ai/Real-ESRGAN/resolve/main/RealESRGAN_x4.pth -P ./models/upscale_models/\n",
165
+ "\n",
166
+ "\n"
167
+ ]
168
+ },
169
+ {
170
+ "cell_type": "markdown",
171
+ "metadata": {
172
+ "id": "kkkkkkkkkkkkkkk"
173
+ },
174
+ "source": [
175
+ "### Run ComfyUI with cloudflared (Recommended Way)\n",
176
+ "\n",
177
+ "\n"
178
+ ]
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "execution_count": null,
183
+ "metadata": {
184
+ "id": "jjjjjjjjjjjjjj"
185
+ },
186
+ "outputs": [],
187
+ "source": [
188
+ "!wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb\n",
189
+ "!dpkg -i cloudflared-linux-amd64.deb\n",
190
+ "\n",
191
+ "import subprocess\n",
192
+ "import threading\n",
193
+ "import time\n",
194
+ "import socket\n",
195
+ "import urllib.request\n",
196
+ "\n",
197
+ "def iframe_thread(port):\n",
198
+ " while True:\n",
199
+ " time.sleep(0.5)\n",
200
+ " sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n",
201
+ " result = sock.connect_ex(('127.0.0.1', port))\n",
202
+ " if result == 0:\n",
203
+ " break\n",
204
+ " sock.close()\n",
205
+ " print(\"\\nComfyUI finished loading, trying to launch cloudflared (if it gets stuck here cloudflared is having issues)\\n\")\n",
206
+ "\n",
207
+ " p = subprocess.Popen([\"cloudflared\", \"tunnel\", \"--url\", \"http://127.0.0.1:{}\".format(port)], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n",
208
+ " for line in p.stderr:\n",
209
+ " l = line.decode()\n",
210
+ " if \"trycloudflare.com \" in l:\n",
211
+ " print(\"This is the URL to access ComfyUI:\", l[l.find(\"http\"):], end='')\n",
212
+ " #print(l, end='')\n",
213
+ "\n",
214
+ "\n",
215
+ "threading.Thread(target=iframe_thread, daemon=True, args=(8188,)).start()\n",
216
+ "\n",
217
+ "!python main.py --dont-print-server"
218
+ ]
219
+ },
220
+ {
221
+ "cell_type": "markdown",
222
+ "metadata": {
223
+ "id": "kkkkkkkkkkkkkk"
224
+ },
225
+ "source": [
226
+ "### Run ComfyUI with localtunnel\n",
227
+ "\n",
228
+ "\n"
229
+ ]
230
+ },
231
+ {
232
+ "cell_type": "code",
233
+ "execution_count": null,
234
+ "metadata": {
235
+ "id": "jjjjjjjjjjjjj"
236
+ },
237
+ "outputs": [],
238
+ "source": [
239
+ "!npm install -g localtunnel\n",
240
+ "\n",
241
+ "import subprocess\n",
242
+ "import threading\n",
243
+ "import time\n",
244
+ "import socket\n",
245
+ "import urllib.request\n",
246
+ "\n",
247
+ "def iframe_thread(port):\n",
248
+ " while True:\n",
249
+ " time.sleep(0.5)\n",
250
+ " sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n",
251
+ " result = sock.connect_ex(('127.0.0.1', port))\n",
252
+ " if result == 0:\n",
253
+ " break\n",
254
+ " sock.close()\n",
255
+ " print(\"\\nComfyUI finished loading, trying to launch localtunnel (if it gets stuck here localtunnel is having issues)\\n\")\n",
256
+ "\n",
257
+ " print(\"The password/enpoint ip for localtunnel is:\", urllib.request.urlopen('https://ipv4.icanhazip.com').read().decode('utf8').strip(\"\\n\"))\n",
258
+ " p = subprocess.Popen([\"lt\", \"--port\", \"{}\".format(port)], stdout=subprocess.PIPE)\n",
259
+ " for line in p.stdout:\n",
260
+ " print(line.decode(), end='')\n",
261
+ "\n",
262
+ "\n",
263
+ "threading.Thread(target=iframe_thread, daemon=True, args=(8188,)).start()\n",
264
+ "\n",
265
+ "!python main.py --dont-print-server"
266
+ ]
267
+ },
268
+ {
269
+ "cell_type": "markdown",
270
+ "metadata": {
271
+ "id": "gggggggggg"
272
+ },
273
+ "source": [
274
+ "### Run ComfyUI with colab iframe (use only in case the previous way with localtunnel doesn't work)\n",
275
+ "\n",
276
+ "You should see the ui appear in an iframe. If you get a 403 error, it's your firefox settings or an extension that's messing things up.\n",
277
+ "\n",
278
+ "If you want to open it in another window use the link.\n",
279
+ "\n",
280
+ "Note that some UI features like live image previews won't work because the colab iframe blocks websockets."
281
+ ]
282
+ },
283
+ {
284
+ "cell_type": "code",
285
+ "execution_count": null,
286
+ "metadata": {
287
+ "id": "hhhhhhhhhh"
288
+ },
289
+ "outputs": [],
290
+ "source": [
291
+ "import threading\n",
292
+ "import time\n",
293
+ "import socket\n",
294
+ "def iframe_thread(port):\n",
295
+ " while True:\n",
296
+ " time.sleep(0.5)\n",
297
+ " sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n",
298
+ " result = sock.connect_ex(('127.0.0.1', port))\n",
299
+ " if result == 0:\n",
300
+ " break\n",
301
+ " sock.close()\n",
302
+ " from google.colab import output\n",
303
+ " output.serve_kernel_port_as_iframe(port, height=1024)\n",
304
+ " print(\"to open it in a window you can open this link here:\")\n",
305
+ " output.serve_kernel_port_as_window(port)\n",
306
+ "\n",
307
+ "threading.Thread(target=iframe_thread, daemon=True, args=(8188,)).start()\n",
308
+ "\n",
309
+ "!python main.py --dont-print-server"
310
+ ]
311
+ }
312
+ ],
313
+ "metadata": {
314
+ "accelerator": "GPU",
315
+ "colab": {
316
+ "provenance": []
317
+ },
318
+ "gpuClass": "standard",
319
+ "kernelspec": {
320
+ "display_name": "Python 3",
321
+ "name": "python3"
322
+ },
323
+ "language_info": {
324
+ "name": "python"
325
+ }
326
+ },
327
+ "nbformat": 4,
328
+ "nbformat_minor": 0
329
+ }
pytest.ini ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ [pytest]
2
+ markers =
3
+ inference: mark as inference test (deselect with '-m "not inference"')
4
+ execution: mark as execution test (deselect with '-m "not execution"')
5
+ testpaths =
6
+ tests
7
+ tests-unit
8
+ addopts = -s
9
+ pythonpath = .
requirements.txt CHANGED
@@ -1,24 +1,20 @@
1
  torch
2
- importlib_metadata
3
- huggingface_hub
4
- scipy
5
- opencv-python>=4.7.0.72
6
- filelock
7
- numpy
8
- Pillow
9
- einops
10
  torchvision
 
 
 
 
 
 
 
11
  pyyaml
12
- scikit-image
13
- python-dateutil
14
- mediapipe
15
- svglib
16
- fvcore
17
- yapf
18
- omegaconf
19
- ftfy
20
- addict
21
- yacs
22
- trimesh[easy]
23
- albumentations
24
- scikit-learn
 
1
  torch
2
+ torchsde
 
 
 
 
 
 
 
3
  torchvision
4
+ torchaudio
5
+ einops
6
+ transformers>=4.28.1
7
+ tokenizers>=0.13.3
8
+ sentencepiece
9
+ safetensors>=0.4.2
10
+ aiohttp
11
  pyyaml
12
+ Pillow
13
+ scipy
14
+ tqdm
15
+ psutil
16
+
17
+ #non essential dependencies:
18
+ kornia>=0.7.1
19
+ spandrel
20
+ soundfile
 
 
 
 
script_examples/basic_api_example.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from urllib import request, parse
3
+ import random
4
+
5
+ #This is the ComfyUI api prompt format.
6
+
7
+ #If you want it for a specific workflow you can "enable dev mode options"
8
+ #in the settings of the UI (gear beside the "Queue Size: ") this will enable
9
+ #a button on the UI to save workflows in api format.
10
+
11
+ #keep in mind ComfyUI is pre alpha software so this format will change a bit.
12
+
13
+ #this is the one for the default workflow
14
+ prompt_text = """
15
+ {
16
+ "3": {
17
+ "class_type": "KSampler",
18
+ "inputs": {
19
+ "cfg": 8,
20
+ "denoise": 1,
21
+ "latent_image": [
22
+ "5",
23
+ 0
24
+ ],
25
+ "model": [
26
+ "4",
27
+ 0
28
+ ],
29
+ "negative": [
30
+ "7",
31
+ 0
32
+ ],
33
+ "positive": [
34
+ "6",
35
+ 0
36
+ ],
37
+ "sampler_name": "euler",
38
+ "scheduler": "normal",
39
+ "seed": 8566257,
40
+ "steps": 20
41
+ }
42
+ },
43
+ "4": {
44
+ "class_type": "CheckpointLoaderSimple",
45
+ "inputs": {
46
+ "ckpt_name": "v1-5-pruned-emaonly.safetensors"
47
+ }
48
+ },
49
+ "5": {
50
+ "class_type": "EmptyLatentImage",
51
+ "inputs": {
52
+ "batch_size": 1,
53
+ "height": 512,
54
+ "width": 512
55
+ }
56
+ },
57
+ "6": {
58
+ "class_type": "CLIPTextEncode",
59
+ "inputs": {
60
+ "clip": [
61
+ "4",
62
+ 1
63
+ ],
64
+ "text": "masterpiece best quality girl"
65
+ }
66
+ },
67
+ "7": {
68
+ "class_type": "CLIPTextEncode",
69
+ "inputs": {
70
+ "clip": [
71
+ "4",
72
+ 1
73
+ ],
74
+ "text": "bad hands"
75
+ }
76
+ },
77
+ "8": {
78
+ "class_type": "VAEDecode",
79
+ "inputs": {
80
+ "samples": [
81
+ "3",
82
+ 0
83
+ ],
84
+ "vae": [
85
+ "4",
86
+ 2
87
+ ]
88
+ }
89
+ },
90
+ "9": {
91
+ "class_type": "SaveImage",
92
+ "inputs": {
93
+ "filename_prefix": "ComfyUI",
94
+ "images": [
95
+ "8",
96
+ 0
97
+ ]
98
+ }
99
+ }
100
+ }
101
+ """
102
+
103
+ def queue_prompt(prompt):
104
+ p = {"prompt": prompt}
105
+ data = json.dumps(p).encode('utf-8')
106
+ req = request.Request("http://127.0.0.1:8188/prompt", data=data)
107
+ request.urlopen(req)
108
+
109
+
110
+ prompt = json.loads(prompt_text)
111
+ #set the text prompt for our positive CLIPTextEncode
112
+ prompt["6"]["inputs"]["text"] = "masterpiece best quality man"
113
+
114
+ #set the seed for our KSampler node
115
+ prompt["3"]["inputs"]["seed"] = 5
116
+
117
+
118
+ queue_prompt(prompt)
119
+
120
+
script_examples/websockets_api_example.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #This is an example that uses the websockets api to know when a prompt execution is done
2
+ #Once the prompt execution is done it downloads the images using the /history endpoint
3
+
4
+ import websocket #NOTE: websocket-client (https://github.com/websocket-client/websocket-client)
5
+ import uuid
6
+ import json
7
+ import urllib.request
8
+ import urllib.parse
9
+
10
+ server_address = "127.0.0.1:8188"
11
+ client_id = str(uuid.uuid4())
12
+
13
+ def queue_prompt(prompt):
14
+ p = {"prompt": prompt, "client_id": client_id}
15
+ data = json.dumps(p).encode('utf-8')
16
+ req = urllib.request.Request("http://{}/prompt".format(server_address), data=data)
17
+ return json.loads(urllib.request.urlopen(req).read())
18
+
19
+ def get_image(filename, subfolder, folder_type):
20
+ data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
21
+ url_values = urllib.parse.urlencode(data)
22
+ with urllib.request.urlopen("http://{}/view?{}".format(server_address, url_values)) as response:
23
+ return response.read()
24
+
25
+ def get_history(prompt_id):
26
+ with urllib.request.urlopen("http://{}/history/{}".format(server_address, prompt_id)) as response:
27
+ return json.loads(response.read())
28
+
29
+ def get_images(ws, prompt):
30
+ prompt_id = queue_prompt(prompt)['prompt_id']
31
+ output_images = {}
32
+ while True:
33
+ out = ws.recv()
34
+ if isinstance(out, str):
35
+ message = json.loads(out)
36
+ if message['type'] == 'executing':
37
+ data = message['data']
38
+ if data['node'] is None and data['prompt_id'] == prompt_id:
39
+ break #Execution is done
40
+ else:
41
+ continue #previews are binary data
42
+
43
+ history = get_history(prompt_id)[prompt_id]
44
+ for node_id in history['outputs']:
45
+ node_output = history['outputs'][node_id]
46
+ images_output = []
47
+ if 'images' in node_output:
48
+ for image in node_output['images']:
49
+ image_data = get_image(image['filename'], image['subfolder'], image['type'])
50
+ images_output.append(image_data)
51
+ output_images[node_id] = images_output
52
+
53
+ return output_images
54
+
55
+ prompt_text = """
56
+ {
57
+ "3": {
58
+ "class_type": "KSampler",
59
+ "inputs": {
60
+ "cfg": 8,
61
+ "denoise": 1,
62
+ "latent_image": [
63
+ "5",
64
+ 0
65
+ ],
66
+ "model": [
67
+ "4",
68
+ 0
69
+ ],
70
+ "negative": [
71
+ "7",
72
+ 0
73
+ ],
74
+ "positive": [
75
+ "6",
76
+ 0
77
+ ],
78
+ "sampler_name": "euler",
79
+ "scheduler": "normal",
80
+ "seed": 8566257,
81
+ "steps": 20
82
+ }
83
+ },
84
+ "4": {
85
+ "class_type": "CheckpointLoaderSimple",
86
+ "inputs": {
87
+ "ckpt_name": "v1-5-pruned-emaonly.safetensors"
88
+ }
89
+ },
90
+ "5": {
91
+ "class_type": "EmptyLatentImage",
92
+ "inputs": {
93
+ "batch_size": 1,
94
+ "height": 512,
95
+ "width": 512
96
+ }
97
+ },
98
+ "6": {
99
+ "class_type": "CLIPTextEncode",
100
+ "inputs": {
101
+ "clip": [
102
+ "4",
103
+ 1
104
+ ],
105
+ "text": "masterpiece best quality girl"
106
+ }
107
+ },
108
+ "7": {
109
+ "class_type": "CLIPTextEncode",
110
+ "inputs": {
111
+ "clip": [
112
+ "4",
113
+ 1
114
+ ],
115
+ "text": "bad hands"
116
+ }
117
+ },
118
+ "8": {
119
+ "class_type": "VAEDecode",
120
+ "inputs": {
121
+ "samples": [
122
+ "3",
123
+ 0
124
+ ],
125
+ "vae": [
126
+ "4",
127
+ 2
128
+ ]
129
+ }
130
+ },
131
+ "9": {
132
+ "class_type": "SaveImage",
133
+ "inputs": {
134
+ "filename_prefix": "ComfyUI",
135
+ "images": [
136
+ "8",
137
+ 0
138
+ ]
139
+ }
140
+ }
141
+ }
142
+ """
143
+
144
+ prompt = json.loads(prompt_text)
145
+ #set the text prompt for our positive CLIPTextEncode
146
+ prompt["6"]["inputs"]["text"] = "masterpiece best quality man"
147
+
148
+ #set the seed for our KSampler node
149
+ prompt["3"]["inputs"]["seed"] = 5
150
+
151
+ ws = websocket.WebSocket()
152
+ ws.connect("ws://{}/ws?clientId={}".format(server_address, client_id))
153
+ images = get_images(ws, prompt)
154
+
155
+ #Commented out code to display the output images:
156
+
157
+ # for node_id in images:
158
+ # for image_data in images[node_id]:
159
+ # from PIL import Image
160
+ # import io
161
+ # image = Image.open(io.BytesIO(image_data))
162
+ # image.show()
163
+
script_examples/websockets_api_example_ws_images.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #This is an example that uses the websockets api and the SaveImageWebsocket node to get images directly without
2
+ #them being saved to disk
3
+
4
+ import websocket #NOTE: websocket-client (https://github.com/websocket-client/websocket-client)
5
+ import uuid
6
+ import json
7
+ import urllib.request
8
+ import urllib.parse
9
+
10
+ server_address = "127.0.0.1:8188"
11
+ client_id = str(uuid.uuid4())
12
+
13
+ def queue_prompt(prompt):
14
+ p = {"prompt": prompt, "client_id": client_id}
15
+ data = json.dumps(p).encode('utf-8')
16
+ req = urllib.request.Request("http://{}/prompt".format(server_address), data=data)
17
+ return json.loads(urllib.request.urlopen(req).read())
18
+
19
+ def get_image(filename, subfolder, folder_type):
20
+ data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
21
+ url_values = urllib.parse.urlencode(data)
22
+ with urllib.request.urlopen("http://{}/view?{}".format(server_address, url_values)) as response:
23
+ return response.read()
24
+
25
+ def get_history(prompt_id):
26
+ with urllib.request.urlopen("http://{}/history/{}".format(server_address, prompt_id)) as response:
27
+ return json.loads(response.read())
28
+
29
+ def get_images(ws, prompt):
30
+ prompt_id = queue_prompt(prompt)['prompt_id']
31
+ output_images = {}
32
+ current_node = ""
33
+ while True:
34
+ out = ws.recv()
35
+ if isinstance(out, str):
36
+ message = json.loads(out)
37
+ if message['type'] == 'executing':
38
+ data = message['data']
39
+ if data['prompt_id'] == prompt_id:
40
+ if data['node'] is None:
41
+ break #Execution is done
42
+ else:
43
+ current_node = data['node']
44
+ else:
45
+ if current_node == 'save_image_websocket_node':
46
+ images_output = output_images.get(current_node, [])
47
+ images_output.append(out[8:])
48
+ output_images[current_node] = images_output
49
+
50
+ return output_images
51
+
52
+ prompt_text = """
53
+ {
54
+ "3": {
55
+ "class_type": "KSampler",
56
+ "inputs": {
57
+ "cfg": 8,
58
+ "denoise": 1,
59
+ "latent_image": [
60
+ "5",
61
+ 0
62
+ ],
63
+ "model": [
64
+ "4",
65
+ 0
66
+ ],
67
+ "negative": [
68
+ "7",
69
+ 0
70
+ ],
71
+ "positive": [
72
+ "6",
73
+ 0
74
+ ],
75
+ "sampler_name": "euler",
76
+ "scheduler": "normal",
77
+ "seed": 8566257,
78
+ "steps": 20
79
+ }
80
+ },
81
+ "4": {
82
+ "class_type": "CheckpointLoaderSimple",
83
+ "inputs": {
84
+ "ckpt_name": "v1-5-pruned-emaonly.safetensors"
85
+ }
86
+ },
87
+ "5": {
88
+ "class_type": "EmptyLatentImage",
89
+ "inputs": {
90
+ "batch_size": 1,
91
+ "height": 512,
92
+ "width": 512
93
+ }
94
+ },
95
+ "6": {
96
+ "class_type": "CLIPTextEncode",
97
+ "inputs": {
98
+ "clip": [
99
+ "4",
100
+ 1
101
+ ],
102
+ "text": "masterpiece best quality girl"
103
+ }
104
+ },
105
+ "7": {
106
+ "class_type": "CLIPTextEncode",
107
+ "inputs": {
108
+ "clip": [
109
+ "4",
110
+ 1
111
+ ],
112
+ "text": "bad hands"
113
+ }
114
+ },
115
+ "8": {
116
+ "class_type": "VAEDecode",
117
+ "inputs": {
118
+ "samples": [
119
+ "3",
120
+ 0
121
+ ],
122
+ "vae": [
123
+ "4",
124
+ 2
125
+ ]
126
+ }
127
+ },
128
+ "save_image_websocket_node": {
129
+ "class_type": "SaveImageWebsocket",
130
+ "inputs": {
131
+ "images": [
132
+ "8",
133
+ 0
134
+ ]
135
+ }
136
+ }
137
+ }
138
+ """
139
+
140
+ prompt = json.loads(prompt_text)
141
+ #set the text prompt for our positive CLIPTextEncode
142
+ prompt["6"]["inputs"]["text"] = "masterpiece best quality man"
143
+
144
+ #set the seed for our KSampler node
145
+ prompt["3"]["inputs"]["seed"] = 5
146
+
147
+ ws = websocket.WebSocket()
148
+ ws.connect("ws://{}/ws?clientId={}".format(server_address, client_id))
149
+ images = get_images(ws, prompt)
150
+
151
+ #Commented out code to display the output images:
152
+
153
+ # for node_id in images:
154
+ # for image_data in images[node_id]:
155
+ # from PIL import Image
156
+ # import io
157
+ # image = Image.open(io.BytesIO(image_data))
158
+ # image.show()
159
+
server.py ADDED
@@ -0,0 +1,841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import asyncio
4
+ import traceback
5
+
6
+ import nodes
7
+ import folder_paths
8
+ import execution
9
+ import uuid
10
+ import urllib
11
+ import json
12
+ import glob
13
+ import struct
14
+ import ssl
15
+ import socket
16
+ import ipaddress
17
+ from PIL import Image, ImageOps
18
+ from PIL.PngImagePlugin import PngInfo
19
+ from io import BytesIO
20
+
21
+ import aiohttp
22
+ from aiohttp import web
23
+ import logging
24
+
25
+ import mimetypes
26
+ from comfy.cli_args import args
27
+ import comfy.utils
28
+ import comfy.model_management
29
+ import node_helpers
30
+ from app.frontend_management import FrontendManager
31
+ from app.user_manager import UserManager
32
+ from model_filemanager import download_model, DownloadModelStatus
33
+ from typing import Optional
34
+ from api_server.routes.internal.internal_routes import InternalRoutes
35
+
36
+ class BinaryEventTypes:
37
+ PREVIEW_IMAGE = 1
38
+ UNENCODED_PREVIEW_IMAGE = 2
39
+
40
+ async def send_socket_catch_exception(function, message):
41
+ try:
42
+ await function(message)
43
+ except (aiohttp.ClientError, aiohttp.ClientPayloadError, ConnectionResetError) as err:
44
+ logging.warning("send error: {}".format(err))
45
+
46
+ def get_comfyui_version():
47
+ comfyui_version = "unknown"
48
+ repo_path = os.path.dirname(os.path.realpath(__file__))
49
+ try:
50
+ import pygit2
51
+ repo = pygit2.Repository(repo_path)
52
+ comfyui_version = repo.describe(describe_strategy=pygit2.GIT_DESCRIBE_TAGS)
53
+ except Exception:
54
+ try:
55
+ import subprocess
56
+ comfyui_version = subprocess.check_output(["git", "describe", "--tags"], cwd=repo_path).decode('utf-8')
57
+ except Exception as e:
58
+ logging.warning(f"Failed to get ComfyUI version: {e}")
59
+ return comfyui_version.strip()
60
+
61
+ @web.middleware
62
+ async def cache_control(request: web.Request, handler):
63
+ response: web.Response = await handler(request)
64
+ if request.path.endswith('.js') or request.path.endswith('.css'):
65
+ response.headers.setdefault('Cache-Control', 'no-cache')
66
+ return response
67
+
68
+ def create_cors_middleware(allowed_origin: str):
69
+ @web.middleware
70
+ async def cors_middleware(request: web.Request, handler):
71
+ if request.method == "OPTIONS":
72
+ # Pre-flight request. Reply successfully:
73
+ response = web.Response()
74
+ else:
75
+ response = await handler(request)
76
+
77
+ response.headers['Access-Control-Allow-Origin'] = allowed_origin
78
+ response.headers['Access-Control-Allow-Methods'] = 'POST, GET, DELETE, PUT, OPTIONS'
79
+ response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
80
+ response.headers['Access-Control-Allow-Credentials'] = 'true'
81
+ return response
82
+
83
+ return cors_middleware
84
+
85
+ def is_loopback(host):
86
+ if host is None:
87
+ return False
88
+ try:
89
+ if ipaddress.ip_address(host).is_loopback:
90
+ return True
91
+ else:
92
+ return False
93
+ except:
94
+ pass
95
+
96
+ loopback = False
97
+ for family in (socket.AF_INET, socket.AF_INET6):
98
+ try:
99
+ r = socket.getaddrinfo(host, None, family, socket.SOCK_STREAM)
100
+ for family, _, _, _, sockaddr in r:
101
+ if not ipaddress.ip_address(sockaddr[0]).is_loopback:
102
+ return loopback
103
+ else:
104
+ loopback = True
105
+ except socket.gaierror:
106
+ pass
107
+
108
+ return loopback
109
+
110
+
111
+ def create_origin_only_middleware():
112
+ @web.middleware
113
+ async def origin_only_middleware(request: web.Request, handler):
114
+ #this code is used to prevent the case where a random website can queue comfy workflows by making a POST to 127.0.0.1 which browsers don't prevent for some dumb reason.
115
+ #in that case the Host and Origin hostnames won't match
116
+ #I know the proper fix would be to add a cookie but this should take care of the problem in the meantime
117
+ if 'Host' in request.headers and 'Origin' in request.headers:
118
+ host = request.headers['Host']
119
+ origin = request.headers['Origin']
120
+ host_domain = host.lower()
121
+ parsed = urllib.parse.urlparse(origin)
122
+ origin_domain = parsed.netloc.lower()
123
+ host_domain_parsed = urllib.parse.urlsplit('//' + host_domain)
124
+
125
+ #limit the check to when the host domain is localhost, this makes it slightly less safe but should still prevent the exploit
126
+ loopback = is_loopback(host_domain_parsed.hostname)
127
+
128
+ if parsed.port is None: #if origin doesn't have a port strip it from the host to handle weird browsers, same for host
129
+ host_domain = host_domain_parsed.hostname
130
+ if host_domain_parsed.port is None:
131
+ origin_domain = parsed.hostname
132
+
133
+ if loopback and host_domain is not None and origin_domain is not None and len(host_domain) > 0 and len(origin_domain) > 0:
134
+ if host_domain != origin_domain:
135
+ logging.warning("WARNING: request with non matching host and origin {} != {}, returning 403".format(host_domain, origin_domain))
136
+ return web.Response(status=403)
137
+
138
+ if request.method == "OPTIONS":
139
+ response = web.Response()
140
+ else:
141
+ response = await handler(request)
142
+
143
+ return response
144
+
145
+ return origin_only_middleware
146
+
147
+ class PromptServer():
148
+ def __init__(self, loop):
149
+ PromptServer.instance = self
150
+
151
+ mimetypes.init()
152
+ mimetypes.types_map['.js'] = 'application/javascript; charset=utf-8'
153
+
154
+ self.user_manager = UserManager()
155
+ self.internal_routes = InternalRoutes()
156
+ self.supports = ["custom_nodes_from_web"]
157
+ self.prompt_queue = None
158
+ self.loop = loop
159
+ self.messages = asyncio.Queue()
160
+ self.client_session:Optional[aiohttp.ClientSession] = None
161
+ self.number = 0
162
+
163
+ middlewares = [cache_control]
164
+ if args.enable_cors_header:
165
+ middlewares.append(create_cors_middleware(args.enable_cors_header))
166
+ else:
167
+ middlewares.append(create_origin_only_middleware())
168
+
169
+ max_upload_size = round(args.max_upload_size * 1024 * 1024)
170
+ self.app = web.Application(client_max_size=max_upload_size, middlewares=middlewares)
171
+ self.sockets = dict()
172
+ self.web_root = (
173
+ FrontendManager.init_frontend(args.front_end_version)
174
+ if args.front_end_root is None
175
+ else args.front_end_root
176
+ )
177
+ logging.info(f"[Prompt Server] web root: {self.web_root}")
178
+ routes = web.RouteTableDef()
179
+ self.routes = routes
180
+ self.last_node_id = None
181
+ self.client_id = None
182
+
183
+ self.on_prompt_handlers = []
184
+
185
+ @routes.get('/ws')
186
+ async def websocket_handler(request):
187
+ ws = web.WebSocketResponse()
188
+ await ws.prepare(request)
189
+ sid = request.rel_url.query.get('clientId', '')
190
+ if sid:
191
+ # Reusing existing session, remove old
192
+ self.sockets.pop(sid, None)
193
+ else:
194
+ sid = uuid.uuid4().hex
195
+
196
+ self.sockets[sid] = ws
197
+
198
+ try:
199
+ # Send initial state to the new client
200
+ await self.send("status", { "status": self.get_queue_info(), 'sid': sid }, sid)
201
+ # On reconnect if we are the currently executing client send the current node
202
+ if self.client_id == sid and self.last_node_id is not None:
203
+ await self.send("executing", { "node": self.last_node_id }, sid)
204
+
205
+ async for msg in ws:
206
+ if msg.type == aiohttp.WSMsgType.ERROR:
207
+ logging.warning('ws connection closed with exception %s' % ws.exception())
208
+ finally:
209
+ self.sockets.pop(sid, None)
210
+ return ws
211
+
212
+ @routes.get("/")
213
+ async def get_root(request):
214
+ response = web.FileResponse(os.path.join(os.path.dirname(os.path.realpath(__file__)), "index.html"))
215
+ response.headers['Cache-Control'] = 'no-cache'
216
+ response.headers["Pragma"] = "no-cache"
217
+ response.headers["Expires"] = "0"
218
+ return response
219
+
220
+ @routes.get("/embeddings")
221
+ def get_embeddings(self):
222
+ embeddings = folder_paths.get_filename_list("embeddings")
223
+ return web.json_response(list(map(lambda a: os.path.splitext(a)[0], embeddings)))
224
+
225
+ @routes.get("/models/{folder}")
226
+ async def get_models(request):
227
+ folder = request.match_info.get("folder", None)
228
+ if not folder in folder_paths.folder_names_and_paths:
229
+ return web.Response(status=404)
230
+ files = folder_paths.get_filename_list(folder)
231
+ return web.json_response(files)
232
+
233
+ @routes.get("/extensions")
234
+ async def get_extensions(request):
235
+ files = glob.glob(os.path.join(
236
+ glob.escape(self.web_root), 'extensions/**/*.js'), recursive=True)
237
+
238
+ extensions = list(map(lambda f: "/" + os.path.relpath(f, self.web_root).replace("\\", "/"), files))
239
+
240
+ for name, dir in nodes.EXTENSION_WEB_DIRS.items():
241
+ files = glob.glob(os.path.join(glob.escape(dir), '**/*.js'), recursive=True)
242
+ extensions.extend(list(map(lambda f: "/extensions/" + urllib.parse.quote(
243
+ name) + "/" + os.path.relpath(f, dir).replace("\\", "/"), files)))
244
+
245
+ return web.json_response(extensions)
246
+
247
+ def get_dir_by_type(dir_type):
248
+ if dir_type is None:
249
+ dir_type = "input"
250
+
251
+ if dir_type == "input":
252
+ type_dir = folder_paths.get_input_directory()
253
+ elif dir_type == "temp":
254
+ type_dir = folder_paths.get_temp_directory()
255
+ elif dir_type == "output":
256
+ type_dir = folder_paths.get_output_directory()
257
+
258
+ return type_dir, dir_type
259
+
260
+ def compare_image_hash(filepath, image):
261
+ hasher = node_helpers.hasher()
262
+
263
+ # function to compare hashes of two images to see if it already exists, fix to #3465
264
+ if os.path.exists(filepath):
265
+ a = hasher()
266
+ b = hasher()
267
+ with open(filepath, "rb") as f:
268
+ a.update(f.read())
269
+ b.update(image.file.read())
270
+ image.file.seek(0)
271
+ f.close()
272
+ return a.hexdigest() == b.hexdigest()
273
+ return False
274
+
275
+ def image_upload(post, image_save_function=None):
276
+ image = post.get("image")
277
+ overwrite = post.get("overwrite")
278
+ image_is_duplicate = False
279
+
280
+ image_upload_type = post.get("type")
281
+ upload_dir, image_upload_type = get_dir_by_type(image_upload_type)
282
+
283
+ if image and image.file:
284
+ filename = image.filename
285
+ if not filename:
286
+ return web.Response(status=400)
287
+
288
+ subfolder = post.get("subfolder", "")
289
+ full_output_folder = os.path.join(upload_dir, os.path.normpath(subfolder))
290
+ filepath = os.path.abspath(os.path.join(full_output_folder, filename))
291
+
292
+ if os.path.commonpath((upload_dir, filepath)) != upload_dir:
293
+ return web.Response(status=400)
294
+
295
+ if not os.path.exists(full_output_folder):
296
+ os.makedirs(full_output_folder)
297
+
298
+ split = os.path.splitext(filename)
299
+
300
+ if overwrite is not None and (overwrite == "true" or overwrite == "1"):
301
+ pass
302
+ else:
303
+ i = 1
304
+ while os.path.exists(filepath):
305
+ if compare_image_hash(filepath, image): #compare hash to prevent saving of duplicates with same name, fix for #3465
306
+ image_is_duplicate = True
307
+ break
308
+ filename = f"{split[0]} ({i}){split[1]}"
309
+ filepath = os.path.join(full_output_folder, filename)
310
+ i += 1
311
+
312
+ if not image_is_duplicate:
313
+ if image_save_function is not None:
314
+ image_save_function(image, post, filepath)
315
+ else:
316
+ with open(filepath, "wb") as f:
317
+ f.write(image.file.read())
318
+
319
+ return web.json_response({"name" : filename, "subfolder": subfolder, "type": image_upload_type})
320
+ else:
321
+ return web.Response(status=400)
322
+
323
+ @routes.post("/upload/image")
324
+ async def upload_image(request):
325
+ post = await request.post()
326
+ return image_upload(post)
327
+
328
+
329
+ @routes.post("/upload/mask")
330
+ async def upload_mask(request):
331
+ post = await request.post()
332
+
333
+ def image_save_function(image, post, filepath):
334
+ original_ref = json.loads(post.get("original_ref"))
335
+ filename, output_dir = folder_paths.annotated_filepath(original_ref['filename'])
336
+
337
+ # validation for security: prevent accessing arbitrary path
338
+ if filename[0] == '/' or '..' in filename:
339
+ return web.Response(status=400)
340
+
341
+ if output_dir is None:
342
+ type = original_ref.get("type", "output")
343
+ output_dir = folder_paths.get_directory_by_type(type)
344
+
345
+ if output_dir is None:
346
+ return web.Response(status=400)
347
+
348
+ if original_ref.get("subfolder", "") != "":
349
+ full_output_dir = os.path.join(output_dir, original_ref["subfolder"])
350
+ if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir:
351
+ return web.Response(status=403)
352
+ output_dir = full_output_dir
353
+
354
+ file = os.path.join(output_dir, filename)
355
+
356
+ if os.path.isfile(file):
357
+ with Image.open(file) as original_pil:
358
+ metadata = PngInfo()
359
+ if hasattr(original_pil,'text'):
360
+ for key in original_pil.text:
361
+ metadata.add_text(key, original_pil.text[key])
362
+ original_pil = original_pil.convert('RGBA')
363
+ mask_pil = Image.open(image.file).convert('RGBA')
364
+
365
+ # alpha copy
366
+ new_alpha = mask_pil.getchannel('A')
367
+ original_pil.putalpha(new_alpha)
368
+ original_pil.save(filepath, compress_level=4, pnginfo=metadata)
369
+
370
+ return image_upload(post, image_save_function)
371
+
372
+ @routes.get("/view")
373
+ async def view_image(request):
374
+ if "filename" in request.rel_url.query:
375
+ filename = request.rel_url.query["filename"]
376
+ filename,output_dir = folder_paths.annotated_filepath(filename)
377
+
378
+ # validation for security: prevent accessing arbitrary path
379
+ if filename[0] == '/' or '..' in filename:
380
+ return web.Response(status=400)
381
+
382
+ if output_dir is None:
383
+ type = request.rel_url.query.get("type", "output")
384
+ output_dir = folder_paths.get_directory_by_type(type)
385
+
386
+ if output_dir is None:
387
+ return web.Response(status=400)
388
+
389
+ if "subfolder" in request.rel_url.query:
390
+ full_output_dir = os.path.join(output_dir, request.rel_url.query["subfolder"])
391
+ if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir:
392
+ return web.Response(status=403)
393
+ output_dir = full_output_dir
394
+
395
+ filename = os.path.basename(filename)
396
+ file = os.path.join(output_dir, filename)
397
+
398
+ if os.path.isfile(file):
399
+ if 'preview' in request.rel_url.query:
400
+ with Image.open(file) as img:
401
+ preview_info = request.rel_url.query['preview'].split(';')
402
+ image_format = preview_info[0]
403
+ if image_format not in ['webp', 'jpeg'] or 'a' in request.rel_url.query.get('channel', ''):
404
+ image_format = 'webp'
405
+
406
+ quality = 90
407
+ if preview_info[-1].isdigit():
408
+ quality = int(preview_info[-1])
409
+
410
+ buffer = BytesIO()
411
+ if image_format in ['jpeg'] or request.rel_url.query.get('channel', '') == 'rgb':
412
+ img = img.convert("RGB")
413
+ img.save(buffer, format=image_format, quality=quality)
414
+ buffer.seek(0)
415
+
416
+ return web.Response(body=buffer.read(), content_type=f'image/{image_format}',
417
+ headers={"Content-Disposition": f"filename=\"{filename}\""})
418
+
419
+ if 'channel' not in request.rel_url.query:
420
+ channel = 'rgba'
421
+ else:
422
+ channel = request.rel_url.query["channel"]
423
+
424
+ if channel == 'rgb':
425
+ with Image.open(file) as img:
426
+ if img.mode == "RGBA":
427
+ r, g, b, a = img.split()
428
+ new_img = Image.merge('RGB', (r, g, b))
429
+ else:
430
+ new_img = img.convert("RGB")
431
+
432
+ buffer = BytesIO()
433
+ new_img.save(buffer, format='PNG')
434
+ buffer.seek(0)
435
+
436
+ return web.Response(body=buffer.read(), content_type='image/png',
437
+ headers={"Content-Disposition": f"filename=\"{filename}\""})
438
+
439
+ elif channel == 'a':
440
+ with Image.open(file) as img:
441
+ if img.mode == "RGBA":
442
+ _, _, _, a = img.split()
443
+ else:
444
+ a = Image.new('L', img.size, 255)
445
+
446
+ # alpha img
447
+ alpha_img = Image.new('RGBA', img.size)
448
+ alpha_img.putalpha(a)
449
+ alpha_buffer = BytesIO()
450
+ alpha_img.save(alpha_buffer, format='PNG')
451
+ alpha_buffer.seek(0)
452
+
453
+ return web.Response(body=alpha_buffer.read(), content_type='image/png',
454
+ headers={"Content-Disposition": f"filename=\"{filename}\""})
455
+ else:
456
+ return web.FileResponse(file, headers={"Content-Disposition": f"filename=\"{filename}\""})
457
+
458
+ return web.Response(status=404)
459
+
460
+ @routes.get("/view_metadata/{folder_name}")
461
+ async def view_metadata(request):
462
+ folder_name = request.match_info.get("folder_name", None)
463
+ if folder_name is None:
464
+ return web.Response(status=404)
465
+ if not "filename" in request.rel_url.query:
466
+ return web.Response(status=404)
467
+
468
+ filename = request.rel_url.query["filename"]
469
+ if not filename.endswith(".safetensors"):
470
+ return web.Response(status=404)
471
+
472
+ safetensors_path = folder_paths.get_full_path(folder_name, filename)
473
+ if safetensors_path is None:
474
+ return web.Response(status=404)
475
+ out = comfy.utils.safetensors_header(safetensors_path, max_size=1024*1024)
476
+ if out is None:
477
+ return web.Response(status=404)
478
+ dt = json.loads(out)
479
+ if not "__metadata__" in dt:
480
+ return web.Response(status=404)
481
+ return web.json_response(dt["__metadata__"])
482
+
483
+ @routes.get("/system_stats")
484
+ async def system_stats(request):
485
+ device = comfy.model_management.get_torch_device()
486
+ device_name = comfy.model_management.get_torch_device_name(device)
487
+ vram_total, torch_vram_total = comfy.model_management.get_total_memory(device, torch_total_too=True)
488
+ vram_free, torch_vram_free = comfy.model_management.get_free_memory(device, torch_free_too=True)
489
+
490
+ system_stats = {
491
+ "system": {
492
+ "os": os.name,
493
+ "comfyui_version": get_comfyui_version(),
494
+ "python_version": sys.version,
495
+ "pytorch_version": comfy.model_management.torch_version,
496
+ "embedded_python": os.path.split(os.path.split(sys.executable)[0])[1] == "python_embedded",
497
+ "argv": sys.argv
498
+ },
499
+ "devices": [
500
+ {
501
+ "name": device_name,
502
+ "type": device.type,
503
+ "index": device.index,
504
+ "vram_total": vram_total,
505
+ "vram_free": vram_free,
506
+ "torch_vram_total": torch_vram_total,
507
+ "torch_vram_free": torch_vram_free,
508
+ }
509
+ ]
510
+ }
511
+ return web.json_response(system_stats)
512
+
513
+ @routes.get("/prompt")
514
+ async def get_prompt(request):
515
+ return web.json_response(self.get_queue_info())
516
+
517
+ def node_info(node_class):
518
+ obj_class = nodes.NODE_CLASS_MAPPINGS[node_class]
519
+ info = {}
520
+ info['input'] = obj_class.INPUT_TYPES()
521
+ info['input_order'] = {key: list(value.keys()) for (key, value) in obj_class.INPUT_TYPES().items()}
522
+ info['output'] = obj_class.RETURN_TYPES
523
+ info['output_is_list'] = obj_class.OUTPUT_IS_LIST if hasattr(obj_class, 'OUTPUT_IS_LIST') else [False] * len(obj_class.RETURN_TYPES)
524
+ info['output_name'] = obj_class.RETURN_NAMES if hasattr(obj_class, 'RETURN_NAMES') else info['output']
525
+ info['name'] = node_class
526
+ info['display_name'] = nodes.NODE_DISPLAY_NAME_MAPPINGS[node_class] if node_class in nodes.NODE_DISPLAY_NAME_MAPPINGS.keys() else node_class
527
+ info['description'] = obj_class.DESCRIPTION if hasattr(obj_class,'DESCRIPTION') else ''
528
+ info['python_module'] = getattr(obj_class, "RELATIVE_PYTHON_MODULE", "nodes")
529
+ info['category'] = 'sd'
530
+ if hasattr(obj_class, 'OUTPUT_NODE') and obj_class.OUTPUT_NODE == True:
531
+ info['output_node'] = True
532
+ else:
533
+ info['output_node'] = False
534
+
535
+ if hasattr(obj_class, 'CATEGORY'):
536
+ info['category'] = obj_class.CATEGORY
537
+
538
+ if hasattr(obj_class, 'OUTPUT_TOOLTIPS'):
539
+ info['output_tooltips'] = obj_class.OUTPUT_TOOLTIPS
540
+
541
+ if getattr(obj_class, "DEPRECATED", False):
542
+ info['deprecated'] = True
543
+ if getattr(obj_class, "EXPERIMENTAL", False):
544
+ info['experimental'] = True
545
+ return info
546
+
547
+ @routes.get("/object_info")
548
+ async def get_object_info(request):
549
+ out = {}
550
+ for x in nodes.NODE_CLASS_MAPPINGS:
551
+ try:
552
+ out[x] = node_info(x)
553
+ except Exception as e:
554
+ logging.error(f"[ERROR] An error occurred while retrieving information for the '{x}' node.")
555
+ logging.error(traceback.format_exc())
556
+ return web.json_response(out)
557
+
558
+ @routes.get("/object_info/{node_class}")
559
+ async def get_object_info_node(request):
560
+ node_class = request.match_info.get("node_class", None)
561
+ out = {}
562
+ if (node_class is not None) and (node_class in nodes.NODE_CLASS_MAPPINGS):
563
+ out[node_class] = node_info(node_class)
564
+ return web.json_response(out)
565
+
566
+ @routes.get("/history")
567
+ async def get_history(request):
568
+ max_items = request.rel_url.query.get("max_items", None)
569
+ if max_items is not None:
570
+ max_items = int(max_items)
571
+ return web.json_response(self.prompt_queue.get_history(max_items=max_items))
572
+
573
+ @routes.get("/history/{prompt_id}")
574
+ async def get_history(request):
575
+ prompt_id = request.match_info.get("prompt_id", None)
576
+ return web.json_response(self.prompt_queue.get_history(prompt_id=prompt_id))
577
+
578
+ @routes.get("/queue")
579
+ async def get_queue(request):
580
+ queue_info = {}
581
+ current_queue = self.prompt_queue.get_current_queue()
582
+ queue_info['queue_running'] = current_queue[0]
583
+ queue_info['queue_pending'] = current_queue[1]
584
+ return web.json_response(queue_info)
585
+
586
+ @routes.post("/prompt")
587
+ async def post_prompt(request):
588
+ logging.info("got prompt")
589
+ resp_code = 200
590
+ out_string = ""
591
+ json_data = await request.json()
592
+ json_data = self.trigger_on_prompt(json_data)
593
+
594
+ if "number" in json_data:
595
+ number = float(json_data['number'])
596
+ else:
597
+ number = self.number
598
+ if "front" in json_data:
599
+ if json_data['front']:
600
+ number = -number
601
+
602
+ self.number += 1
603
+
604
+ if "prompt" in json_data:
605
+ prompt = json_data["prompt"]
606
+ valid = execution.validate_prompt(prompt)
607
+ extra_data = {}
608
+ if "extra_data" in json_data:
609
+ extra_data = json_data["extra_data"]
610
+
611
+ if "client_id" in json_data:
612
+ extra_data["client_id"] = json_data["client_id"]
613
+ if valid[0]:
614
+ prompt_id = str(uuid.uuid4())
615
+ outputs_to_execute = valid[2]
616
+ self.prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute))
617
+ response = {"prompt_id": prompt_id, "number": number, "node_errors": valid[3]}
618
+ return web.json_response(response)
619
+ else:
620
+ logging.warning("invalid prompt: {}".format(valid[1]))
621
+ return web.json_response({"error": valid[1], "node_errors": valid[3]}, status=400)
622
+ else:
623
+ return web.json_response({"error": "no prompt", "node_errors": []}, status=400)
624
+
625
+ @routes.post("/queue")
626
+ async def post_queue(request):
627
+ json_data = await request.json()
628
+ if "clear" in json_data:
629
+ if json_data["clear"]:
630
+ self.prompt_queue.wipe_queue()
631
+ if "delete" in json_data:
632
+ to_delete = json_data['delete']
633
+ for id_to_delete in to_delete:
634
+ delete_func = lambda a: a[1] == id_to_delete
635
+ self.prompt_queue.delete_queue_item(delete_func)
636
+
637
+ return web.Response(status=200)
638
+
639
+ @routes.post("/interrupt")
640
+ async def post_interrupt(request):
641
+ nodes.interrupt_processing()
642
+ return web.Response(status=200)
643
+
644
+ @routes.post("/free")
645
+ async def post_free(request):
646
+ json_data = await request.json()
647
+ unload_models = json_data.get("unload_models", False)
648
+ free_memory = json_data.get("free_memory", False)
649
+ if unload_models:
650
+ self.prompt_queue.set_flag("unload_models", unload_models)
651
+ if free_memory:
652
+ self.prompt_queue.set_flag("free_memory", free_memory)
653
+ return web.Response(status=200)
654
+
655
+ @routes.post("/history")
656
+ async def post_history(request):
657
+ json_data = await request.json()
658
+ if "clear" in json_data:
659
+ if json_data["clear"]:
660
+ self.prompt_queue.wipe_history()
661
+ if "delete" in json_data:
662
+ to_delete = json_data['delete']
663
+ for id_to_delete in to_delete:
664
+ self.prompt_queue.delete_history_item(id_to_delete)
665
+
666
+ return web.Response(status=200)
667
+
668
+ # Internal route. Should not be depended upon and is subject to change at any time.
669
+ # TODO(robinhuang): Move to internal route table class once we refactor PromptServer to pass around Websocket.
670
+ @routes.post("/internal/models/download")
671
+ async def download_handler(request):
672
+ async def report_progress(filename: str, status: DownloadModelStatus):
673
+ payload = status.to_dict()
674
+ payload['download_path'] = filename
675
+ await self.send_json("download_progress", payload)
676
+
677
+ data = await request.json()
678
+ url = data.get('url')
679
+ model_directory = data.get('model_directory')
680
+ model_filename = data.get('model_filename')
681
+ progress_interval = data.get('progress_interval', 1.0) # In seconds, how often to report download progress.
682
+
683
+ if not url or not model_directory or not model_filename:
684
+ return web.json_response({"status": "error", "message": "Missing URL or folder path or filename"}, status=400)
685
+
686
+ session = self.client_session
687
+ if session is None:
688
+ logging.error("Client session is not initialized")
689
+ return web.Response(status=500)
690
+
691
+ task = asyncio.create_task(download_model(lambda url: session.get(url), model_filename, url, model_directory, report_progress, progress_interval))
692
+ await task
693
+
694
+ return web.json_response(task.result().to_dict())
695
+
696
+ async def setup(self):
697
+ timeout = aiohttp.ClientTimeout(total=None) # no timeout
698
+ self.client_session = aiohttp.ClientSession(timeout=timeout)
699
+
700
+ def add_routes(self):
701
+ self.user_manager.add_routes(self.routes)
702
+ self.app.add_subapp('/internal', self.internal_routes.get_app())
703
+
704
+ # Prefix every route with /api for easier matching for delegation.
705
+ # This is very useful for frontend dev server, which need to forward
706
+ # everything except serving of static files.
707
+ # Currently both the old endpoints without prefix and new endpoints with
708
+ # prefix are supported.
709
+ api_routes = web.RouteTableDef()
710
+ for route in self.routes:
711
+ # Custom nodes might add extra static routes. Only process non-static
712
+ # routes to add /api prefix.
713
+ if isinstance(route, web.RouteDef):
714
+ api_routes.route(route.method, "/api" + route.path)(route.handler, **route.kwargs)
715
+ self.app.add_routes(api_routes)
716
+ self.app.add_routes(self.routes)
717
+
718
+ for name, dir in nodes.EXTENSION_WEB_DIRS.items():
719
+ self.app.add_routes([
720
+ web.static('/extensions/' + urllib.parse.quote(name), dir),
721
+ ])
722
+
723
+ self.app.add_routes([
724
+ web.static('/', self.web_root),
725
+ ])
726
+
727
+ def get_queue_info(self):
728
+ prompt_info = {}
729
+ exec_info = {}
730
+ exec_info['queue_remaining'] = self.prompt_queue.get_tasks_remaining()
731
+ prompt_info['exec_info'] = exec_info
732
+ return prompt_info
733
+
734
+ async def send(self, event, data, sid=None):
735
+ if event == BinaryEventTypes.UNENCODED_PREVIEW_IMAGE:
736
+ await self.send_image(data, sid=sid)
737
+ elif isinstance(data, (bytes, bytearray)):
738
+ await self.send_bytes(event, data, sid)
739
+ else:
740
+ await self.send_json(event, data, sid)
741
+
742
+ def encode_bytes(self, event, data):
743
+ if not isinstance(event, int):
744
+ raise RuntimeError(f"Binary event types must be integers, got {event}")
745
+
746
+ packed = struct.pack(">I", event)
747
+ message = bytearray(packed)
748
+ message.extend(data)
749
+ return message
750
+
751
+ async def send_image(self, image_data, sid=None):
752
+ image_type = image_data[0]
753
+ image = image_data[1]
754
+ max_size = image_data[2]
755
+ if max_size is not None:
756
+ if hasattr(Image, 'Resampling'):
757
+ resampling = Image.Resampling.BILINEAR
758
+ else:
759
+ resampling = Image.ANTIALIAS
760
+
761
+ image = ImageOps.contain(image, (max_size, max_size), resampling)
762
+ type_num = 1
763
+ if image_type == "JPEG":
764
+ type_num = 1
765
+ elif image_type == "PNG":
766
+ type_num = 2
767
+
768
+ bytesIO = BytesIO()
769
+ header = struct.pack(">I", type_num)
770
+ bytesIO.write(header)
771
+ image.save(bytesIO, format=image_type, quality=95, compress_level=1)
772
+ preview_bytes = bytesIO.getvalue()
773
+ await self.send_bytes(BinaryEventTypes.PREVIEW_IMAGE, preview_bytes, sid=sid)
774
+
775
+ async def send_bytes(self, event, data, sid=None):
776
+ message = self.encode_bytes(event, data)
777
+
778
+ if sid is None:
779
+ sockets = list(self.sockets.values())
780
+ for ws in sockets:
781
+ await send_socket_catch_exception(ws.send_bytes, message)
782
+ elif sid in self.sockets:
783
+ await send_socket_catch_exception(self.sockets[sid].send_bytes, message)
784
+
785
+ async def send_json(self, event, data, sid=None):
786
+ message = {"type": event, "data": data}
787
+
788
+ if sid is None:
789
+ sockets = list(self.sockets.values())
790
+ for ws in sockets:
791
+ await send_socket_catch_exception(ws.send_json, message)
792
+ elif sid in self.sockets:
793
+ await send_socket_catch_exception(self.sockets[sid].send_json, message)
794
+
795
+ def send_sync(self, event, data, sid=None):
796
+ self.loop.call_soon_threadsafe(
797
+ self.messages.put_nowait, (event, data, sid))
798
+
799
+ def queue_updated(self):
800
+ self.send_sync("status", { "status": self.get_queue_info() })
801
+
802
+ async def publish_loop(self):
803
+ while True:
804
+ msg = await self.messages.get()
805
+ await self.send(*msg)
806
+
807
+ async def start(self, address, port, verbose=True, call_on_start=None):
808
+ runner = web.AppRunner(self.app, access_log=None)
809
+ await runner.setup()
810
+ ssl_ctx = None
811
+ scheme = "http"
812
+ if args.tls_keyfile and args.tls_certfile:
813
+ ssl_ctx = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_SERVER, verify_mode=ssl.CERT_NONE)
814
+ ssl_ctx.load_cert_chain(certfile=args.tls_certfile,
815
+ keyfile=args.tls_keyfile)
816
+ scheme = "https"
817
+
818
+ site = web.TCPSite(runner, address, port, ssl_context=ssl_ctx)
819
+ await site.start()
820
+
821
+ self.address = address
822
+ self.port = port
823
+
824
+ if verbose:
825
+ logging.info(f'Starting Comfyd server!\n')
826
+ #logging.info("To see the GUI go to: {}://{}:{}".format(scheme, address, port))
827
+ if call_on_start is not None:
828
+ call_on_start(scheme, address, port)
829
+
830
+ def add_on_prompt_handler(self, handler):
831
+ self.on_prompt_handlers.append(handler)
832
+
833
+ def trigger_on_prompt(self, json_data):
834
+ for handler in self.on_prompt_handlers:
835
+ try:
836
+ json_data = handler(json_data)
837
+ except Exception as e:
838
+ logging.warning(f"[ERROR] An error occurred during the on_prompt_handler processing")
839
+ logging.warning(traceback.format_exc())
840
+
841
+ return json_data