gokaygokay commited on
Commit
19b48f8
·
verified ·
1 Parent(s): 59463a5

Upload 26 files

Browse files
.gitattributes CHANGED
@@ -1,35 +1,2 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ /web/assets/** linguist-generated
2
+ /web/** linguist-vendored
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.gitignore ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ /output/
4
+ /input/
5
+ !/input/example.png
6
+ /models/
7
+ /temp/
8
+ /custom_nodes/
9
+ !custom_nodes/example_node.py.example
10
+ extra_model_paths.yaml
11
+ /.vs
12
+ .vscode/
13
+ .idea/
14
+ venv/
15
+ .venv/
16
+ /web/extensions/*
17
+ !/web/extensions/logging.js.example
18
+ !/web/extensions/core/
19
+ /tests-ui/data/object_info.json
20
+ /user/
21
+ *.log
22
+ web_custom_versions/
23
+ .DS_Store
24
+ openapi.yaml
25
+ filtered-openapi.yaml
26
+ uv.lock
CODEOWNERS ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Admins
2
+ * @comfyanonymous
3
+
4
+ # Note: Github teams syntax cannot be used here as the repo is not owned by Comfy-Org.
5
+ # Inlined the team members for now.
6
+
7
+ # Maintainers
8
+ *.md @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
9
+ /tests/ @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
10
+ /tests-unit/ @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
11
+ /notebooks/ @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
12
+ /script_examples/ @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
13
+ /.github/ @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
14
+ /requirements.txt @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
15
+ /pyproject.toml @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
16
+
17
+ # Python web server
18
+ /api_server/ @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @christian-byrne
19
+ /app/ @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @christian-byrne
20
+ /utils/ @yoland68 @robinjhuang @huchenlei @webfiltered @pythongosssss @ltdrdata @christian-byrne
21
+
22
+ # Node developers
23
+ /comfy_extras/ @yoland68 @robinjhuang @huchenlei @pythongosssss @ltdrdata @Kosinkadink @webfiltered @christian-byrne
24
+ /comfy/comfy_types/ @yoland68 @robinjhuang @huchenlei @pythongosssss @ltdrdata @Kosinkadink @webfiltered @christian-byrne
CONTRIBUTING.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to ComfyUI
2
+
3
+ Welcome, and thank you for your interest in contributing to ComfyUI!
4
+
5
+ There are several ways in which you can contribute, beyond writing code. The goal of this document is to provide a high-level overview of how you can get involved.
6
+
7
+ ## Asking Questions
8
+
9
+ Have a question? Instead of opening an issue, please ask on [Discord](https://comfy.org/discord) or [Matrix](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) channels. Our team and the community will help you.
10
+
11
+ ## Providing Feedback
12
+
13
+ Your comments and feedback are welcome, and the development team is available via a handful of different channels.
14
+
15
+ See the `#bug-report`, `#feature-request` and `#feedback` channels on Discord.
16
+
17
+ ## Reporting Issues
18
+
19
+ Have you identified a reproducible problem in ComfyUI? Do you have a feature request? We want to hear about it! Here's how you can report your issue as effectively as possible.
20
+
21
+
22
+ ### Look For an Existing Issue
23
+
24
+ Before you create a new issue, please do a search in [open issues](https://github.com/comfyanonymous/ComfyUI/issues) to see if the issue or feature request has already been filed.
25
+
26
+ If you find your issue already exists, make relevant comments and add your [reaction](https://github.com/blog/2119-add-reactions-to-pull-requests-issues-and-comments). Use a reaction in place of a "+1" comment:
27
+
28
+ * 👍 - upvote
29
+ * 👎 - downvote
30
+
31
+ If you cannot find an existing issue that describes your bug or feature, create a new issue. We have an issue template in place to organize new issues.
32
+
33
+
34
+ ### Creating Pull Requests
35
+
36
+ * Please refer to the article on [creating pull requests](https://github.com/comfyanonymous/ComfyUI/wiki/How-to-Contribute-Code) and contributing to this project.
37
+
38
+
39
+ ## Thank You
40
+
41
+ Your contributions to open source, large or small, make great projects like this possible. Thank you for taking the time to contribute.
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,14 +1,14 @@
1
- ---
2
- title: Video Prompt Generator
3
- emoji: 🔥
4
- colorFrom: blue
5
- colorTo: pink
6
- sdk: gradio
7
- sdk_version: 5.14.0
8
- app_file: app.py
9
- pinned: true
10
- license: apache-2.0
11
- short_description: Create Prompts for your Videos
12
- ---
13
-
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
+ ---
2
+ title: Video Prompt Generator
3
+ emoji: 🔥
4
+ colorFrom: blue
5
+ colorTo: pink
6
+ sdk: gradio
7
+ sdk_version: 5.14.0
8
+ app_file: app.py
9
+ pinned: true
10
+ license: apache-2.0
11
+ short_description: Create Prompts for your Videos
12
+ ---
13
+
14
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
app.py CHANGED
@@ -1,72 +1,183 @@
1
- import spaces
2
- import torch
3
- import gradio as gr
4
- import os
5
- from diffusers import FluxPipeline
6
- from transformers import T5EncoderModel, CLIPTextModel
7
-
8
- # Initialize model outside the function
9
- device = "cuda" if torch.cuda.is_available() else "cpu"
10
- dtype = torch.bfloat16
11
- file_url = "https://huggingface.co/lodestones/Chroma/blob/main/chroma-unlocked-v31.safetensors"
12
- huggingface_token = os.getenv("HUGGINGFACE_TOKEN")
13
- single_file_base_model = "camenduru/FLUX.1-dev-diffusers"
14
-
15
- # Initialize text encoders
16
- text_encoder = CLIPTextModel.from_pretrained(
17
- single_file_base_model,
18
- subfolder="text_encoder",
19
- torch_dtype=dtype,
20
- token=huggingface_token
21
- )
22
-
23
- text_encoder_2 = T5EncoderModel.from_pretrained(
24
- single_file_base_model,
25
- subfolder="text_encoder_2",
26
- torch_dtype=dtype,
27
- config=single_file_base_model,
28
- token=huggingface_token
29
- )
30
-
31
- # Load the pipeline with proper configuration
32
- flux_pipeline = FluxPipeline.from_single_file(
33
- file_url,
34
- text_encoder=text_encoder,
35
- text_encoder_2=text_encoder_2,
36
- torch_dtype=dtype,
37
- token=huggingface_token
38
- )
39
- flux_pipeline.to(device)
40
-
41
- @spaces.GPU()
42
- def generate_image(prompt, negative_prompt="", num_inference_steps=30, guidance_scale=7.5):
43
- # Generate image
44
- image = flux_pipeline(
45
- prompt=prompt,
46
- negative_prompt=negative_prompt,
47
- num_inference_steps=num_inference_steps,
48
- guidance_scale=guidance_scale
49
- ).images[0]
50
-
51
- return image
52
-
53
- # Create Gradio interface
54
- iface = gr.Interface(
55
- fn=generate_image,
56
- inputs=[
57
- gr.Textbox(label="Prompt", placeholder="Enter your prompt here..."),
58
- gr.Textbox(label="Negative Prompt", placeholder="Enter negative prompt here...", value=""),
59
- gr.Slider(minimum=1, maximum=100, value=30, step=1, label="Number of Inference Steps"),
60
- gr.Slider(minimum=1.0, maximum=20.0, value=7.5, step=0.1, label="Guidance Scale")
61
- ],
62
- outputs=gr.Image(label="Generated Image"),
63
- title="Chroma Image Generator",
64
- description="Generate images using the Chroma model",
65
- examples=[
66
- ["A beautiful sunset over mountains, photorealistic, 8k", "blurry, low quality, distorted", 30, 7.5],
67
- ["A futuristic cityscape at night, neon lights, cyberpunk style", "ugly, deformed, low resolution", 30, 7.5]
68
- ]
69
- )
70
-
71
- if __name__ == "__main__":
72
- iface.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import sys
4
+ from typing import Sequence, Mapping, Any, Union
5
+ import torch
6
+ import gradio as gr
7
+ from huggingface_hub import hf_hub_download
8
+
9
+ # Download required models
10
+ t5_path = hf_hub_download(repo_id="comfyanonymous/flux_text_encoders", filename="t5xxl_fp8_e4m3fn.safetensors", local_dir="models/text_encoders/")
11
+ vae_path = hf_hub_download(repo_id="black-forest-labs/FLUX.1-dev", filename="ae.safetensors", local_dir="models/vae")
12
+ unet_path = hf_hub_download(repo_id="lodestones/Chroma", filename="chroma-unlocked-v31.safetensors", local_dir="models/unet")
13
+
14
+ # Import the workflow functions
15
+ from my_workflow import (
16
+ get_value_at_index,
17
+ add_comfyui_directory_to_sys_path,
18
+ add_extra_model_paths,
19
+ import_custom_nodes,
20
+ NODE_CLASS_MAPPINGS,
21
+ CLIPTextEncode,
22
+ CLIPLoader,
23
+ VAEDecode,
24
+ UNETLoader,
25
+ VAELoader,
26
+ SaveImage,
27
+ )
28
+
29
+ # Initialize ComfyUI
30
+ add_comfyui_directory_to_sys_path()
31
+ add_extra_model_paths()
32
+ import_custom_nodes()
33
+
34
+ def generate_image(prompt, negative_prompt, width, height, steps, cfg, seed):
35
+ with torch.inference_mode():
36
+ # Set random seed if provided
37
+ if seed == -1:
38
+ seed = random.randint(1, 2**64)
39
+ random.seed(seed)
40
+
41
+ randomnoise = NODE_CLASS_MAPPINGS["RandomNoise"]()
42
+ randomnoise_68 = randomnoise.get_noise(noise_seed=seed)
43
+
44
+ emptysd3latentimage = NODE_CLASS_MAPPINGS["EmptySD3LatentImage"]()
45
+ emptysd3latentimage_69 = emptysd3latentimage.generate(
46
+ width=width, height=height, batch_size=1
47
+ )
48
+
49
+ ksamplerselect = NODE_CLASS_MAPPINGS["KSamplerSelect"]()
50
+ ksamplerselect_72 = ksamplerselect.get_sampler(sampler_name="euler")
51
+
52
+ cliploader = CLIPLoader()
53
+ cliploader_78 = cliploader.load_clip(
54
+ clip_name="t5xxl_fp8_e4m3fn.safetensors", type="chroma", device="default"
55
+ )
56
+
57
+ t5tokenizeroptions = NODE_CLASS_MAPPINGS["T5TokenizerOptions"]()
58
+ t5tokenizeroptions_82 = t5tokenizeroptions.set_options(
59
+ min_padding=1, min_length=0, clip=get_value_at_index(cliploader_78, 0)
60
+ )
61
+
62
+ cliptextencode = CLIPTextEncode()
63
+ cliptextencode_74 = cliptextencode.encode(
64
+ text=prompt,
65
+ clip=get_value_at_index(t5tokenizeroptions_82, 0),
66
+ )
67
+
68
+ cliptextencode_75 = cliptextencode.encode(
69
+ text=negative_prompt,
70
+ clip=get_value_at_index(t5tokenizeroptions_82, 0),
71
+ )
72
+
73
+ unetloader = UNETLoader()
74
+ unetloader_76 = unetloader.load_unet(
75
+ unet_name="chroma-unlocked-v31.safetensors", weight_dtype="fp8_e4m3fn"
76
+ )
77
+
78
+ vaeloader = VAELoader()
79
+ vaeloader_80 = vaeloader.load_vae(vae_name="ae.safetensors")
80
+
81
+ cfgguider = NODE_CLASS_MAPPINGS["CFGGuider"]()
82
+ basicscheduler = NODE_CLASS_MAPPINGS["BasicScheduler"]()
83
+ samplercustomadvanced = NODE_CLASS_MAPPINGS["SamplerCustomAdvanced"]()
84
+ vaedecode = VAEDecode()
85
+ saveimage = SaveImage()
86
+
87
+ cfgguider_73 = cfgguider.get_guider(
88
+ cfg=cfg,
89
+ model=get_value_at_index(unetloader_76, 0),
90
+ positive=get_value_at_index(cliptextencode_74, 0),
91
+ negative=get_value_at_index(cliptextencode_75, 0),
92
+ )
93
+
94
+ basicscheduler_84 = basicscheduler.get_sigmas(
95
+ scheduler="beta",
96
+ steps=steps,
97
+ denoise=1,
98
+ model=get_value_at_index(unetloader_76, 0),
99
+ )
100
+
101
+ samplercustomadvanced_67 = samplercustomadvanced.sample(
102
+ noise=get_value_at_index(randomnoise_68, 0),
103
+ guider=get_value_at_index(cfgguider_73, 0),
104
+ sampler=get_value_at_index(ksamplerselect_72, 0),
105
+ sigmas=get_value_at_index(basicscheduler_84, 0),
106
+ latent_image=get_value_at_index(emptysd3latentimage_69, 0),
107
+ )
108
+
109
+ vaedecode_79 = vaedecode.decode(
110
+ samples=get_value_at_index(samplercustomadvanced_67, 0),
111
+ vae=get_value_at_index(vaeloader_80, 0),
112
+ )
113
+
114
+ # Instead of saving to file, return the image directly
115
+ return get_value_at_index(vaedecode_79, 0)
116
+
117
+ # Create Gradio interface
118
+ with gr.Blocks() as app:
119
+ gr.Markdown("# Chroma Image Generator")
120
+
121
+ with gr.Row():
122
+ with gr.Column():
123
+ prompt = gr.Textbox(
124
+ label="Prompt",
125
+ placeholder="Enter your prompt here...",
126
+ lines=3
127
+ )
128
+ negative_prompt = gr.Textbox(
129
+ label="Negative Prompt",
130
+ placeholder="Enter negative prompt here...",
131
+ value="low quality, ugly, unfinished, out of focus, deformed, disfigure, blurry, smudged, restricted palette, flat colors",
132
+ lines=2
133
+ )
134
+
135
+ with gr.Row():
136
+ width = gr.Slider(
137
+ minimum=512,
138
+ maximum=2048,
139
+ value=1024,
140
+ step=64,
141
+ label="Width"
142
+ )
143
+ height = gr.Slider(
144
+ minimum=512,
145
+ maximum=2048,
146
+ value=1024,
147
+ step=64,
148
+ label="Height"
149
+ )
150
+
151
+ with gr.Row():
152
+ steps = gr.Slider(
153
+ minimum=1,
154
+ maximum=50,
155
+ value=26,
156
+ step=1,
157
+ label="Steps"
158
+ )
159
+ cfg = gr.Slider(
160
+ minimum=1,
161
+ maximum=20,
162
+ value=4,
163
+ step=0.5,
164
+ label="CFG Scale"
165
+ )
166
+ seed = gr.Number(
167
+ value=-1,
168
+ label="Seed (-1 for random)"
169
+ )
170
+
171
+ generate_btn = gr.Button("Generate")
172
+
173
+ with gr.Column():
174
+ output_image = gr.Image(label="Generated Image")
175
+
176
+ generate_btn.click(
177
+ fn=generate_image,
178
+ inputs=[prompt, negative_prompt, width, height, steps, cfg, seed],
179
+ outputs=[output_image]
180
+ )
181
+
182
+ if __name__ == "__main__":
183
+ app.launch(share=True)
chroma_api.json ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "67": {
3
+ "inputs": {
4
+ "noise": [
5
+ "68",
6
+ 0
7
+ ],
8
+ "guider": [
9
+ "73",
10
+ 0
11
+ ],
12
+ "sampler": [
13
+ "72",
14
+ 0
15
+ ],
16
+ "sigmas": [
17
+ "84",
18
+ 0
19
+ ],
20
+ "latent_image": [
21
+ "69",
22
+ 0
23
+ ]
24
+ },
25
+ "class_type": "SamplerCustomAdvanced",
26
+ "_meta": {
27
+ "title": "SamplerCustomAdvanced"
28
+ }
29
+ },
30
+ "68": {
31
+ "inputs": {
32
+ "noise_seed": 666
33
+ },
34
+ "class_type": "RandomNoise",
35
+ "_meta": {
36
+ "title": "RandomNoise"
37
+ }
38
+ },
39
+ "69": {
40
+ "inputs": {
41
+ "width": 1024,
42
+ "height": 1024,
43
+ "batch_size": 1
44
+ },
45
+ "class_type": "EmptySD3LatentImage",
46
+ "_meta": {
47
+ "title": "EmptySD3LatentImage"
48
+ }
49
+ },
50
+ "72": {
51
+ "inputs": {
52
+ "sampler_name": "euler"
53
+ },
54
+ "class_type": "KSamplerSelect",
55
+ "_meta": {
56
+ "title": "KSamplerSelect"
57
+ }
58
+ },
59
+ "73": {
60
+ "inputs": {
61
+ "cfg": 4,
62
+ "model": [
63
+ "76",
64
+ 0
65
+ ],
66
+ "positive": [
67
+ "74",
68
+ 0
69
+ ],
70
+ "negative": [
71
+ "75",
72
+ 0
73
+ ]
74
+ },
75
+ "class_type": "CFGGuider",
76
+ "_meta": {
77
+ "title": "CFGGuider"
78
+ }
79
+ },
80
+ "74": {
81
+ "inputs": {
82
+ "text": "Extreme close-up photograph of a single tiger eye, direct frontal view. The iris is very detailed and the pupil resembling a dark void. The word \"Chroma\" is across the lower portion of the image in large white stylized letters, with brush strokes resembling those made with Japanese calligraphy. Each strand of the thick fur is highly detailed and distinguishable. Natural lighting to capture authentic eye shine and depth.",
83
+ "clip": [
84
+ "82",
85
+ 0
86
+ ]
87
+ },
88
+ "class_type": "CLIPTextEncode",
89
+ "_meta": {
90
+ "title": "CLIP Text Encode (Prompt)"
91
+ }
92
+ },
93
+ "75": {
94
+ "inputs": {
95
+ "text": "low quality, ugly, unfinished, out of focus, deformed, disfigure, blurry, smudged, restricted palette, flat colors",
96
+ "clip": [
97
+ "82",
98
+ 0
99
+ ]
100
+ },
101
+ "class_type": "CLIPTextEncode",
102
+ "_meta": {
103
+ "title": "CLIP Text Encode (Prompt)"
104
+ }
105
+ },
106
+ "76": {
107
+ "inputs": {
108
+ "unet_name": "chroma-unlocked-v31.safetensors",
109
+ "weight_dtype": "fp8_e4m3fn"
110
+ },
111
+ "class_type": "UNETLoader",
112
+ "_meta": {
113
+ "title": "Load Diffusion Model"
114
+ }
115
+ },
116
+ "78": {
117
+ "inputs": {
118
+ "clip_name": "t5xxl_fp8_e4m3fn.safetensors",
119
+ "type": "chroma",
120
+ "device": "default"
121
+ },
122
+ "class_type": "CLIPLoader",
123
+ "_meta": {
124
+ "title": "Load CLIP"
125
+ }
126
+ },
127
+ "79": {
128
+ "inputs": {
129
+ "samples": [
130
+ "67",
131
+ 0
132
+ ],
133
+ "vae": [
134
+ "80",
135
+ 0
136
+ ]
137
+ },
138
+ "class_type": "VAEDecode",
139
+ "_meta": {
140
+ "title": "VAE Decode"
141
+ }
142
+ },
143
+ "80": {
144
+ "inputs": {
145
+ "vae_name": "ae.safetensors"
146
+ },
147
+ "class_type": "VAELoader",
148
+ "_meta": {
149
+ "title": "Load VAE"
150
+ }
151
+ },
152
+ "81": {
153
+ "inputs": {
154
+ "filename_prefix": "2025-05-24/ComfyUI",
155
+ "images": [
156
+ "79",
157
+ 0
158
+ ]
159
+ },
160
+ "class_type": "SaveImage",
161
+ "_meta": {
162
+ "title": "Save Image"
163
+ }
164
+ },
165
+ "82": {
166
+ "inputs": {
167
+ "min_padding": 1,
168
+ "min_length": 0,
169
+ "clip": [
170
+ "78",
171
+ 0
172
+ ]
173
+ },
174
+ "class_type": "T5TokenizerOptions",
175
+ "_meta": {
176
+ "title": "T5TokenizerOptions"
177
+ }
178
+ },
179
+ "84": {
180
+ "inputs": {
181
+ "scheduler": "beta",
182
+ "steps": 26,
183
+ "denoise": 1,
184
+ "model": [
185
+ "76",
186
+ 0
187
+ ]
188
+ },
189
+ "class_type": "BasicScheduler",
190
+ "_meta": {
191
+ "title": "BasicScheduler"
192
+ }
193
+ }
194
+ }
comfyui_to_python.py ADDED
@@ -0,0 +1,641 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import glob
3
+ import inspect
4
+ import json
5
+ import os
6
+ import random
7
+ import sys
8
+ import re
9
+ from typing import Dict, List, Any, Callable, Tuple, TextIO
10
+ from argparse import ArgumentParser
11
+
12
+ import black
13
+
14
+
15
+ from comfyui_to_python_utils import (
16
+ import_custom_nodes,
17
+ find_path,
18
+ add_comfyui_directory_to_sys_path,
19
+ add_extra_model_paths,
20
+ get_value_at_index,
21
+ )
22
+
23
+ add_comfyui_directory_to_sys_path()
24
+ from nodes import NODE_CLASS_MAPPINGS
25
+
26
+
27
+ DEFAULT_INPUT_FILE = "workflow_api.json"
28
+ DEFAULT_OUTPUT_FILE = "workflow_api.py"
29
+ DEFAULT_QUEUE_SIZE = 10
30
+
31
+
32
+ class FileHandler:
33
+ """Handles reading and writing files.
34
+
35
+ This class provides methods to read JSON data from an input file and write code to an output file.
36
+ """
37
+
38
+ @staticmethod
39
+ def read_json_file(file_path: str | TextIO, encoding: str = "utf-8") -> dict:
40
+ """
41
+ Reads a JSON file and returns its contents as a dictionary.
42
+
43
+ Args:
44
+ file_path (str): The path to the JSON file.
45
+
46
+ Returns:
47
+ dict: The contents of the JSON file as a dictionary.
48
+
49
+ Raises:
50
+ FileNotFoundError: If the file is not found, it lists all JSON files in the directory of the file path.
51
+ ValueError: If the file is not a valid JSON.
52
+ """
53
+
54
+ if hasattr(file_path, "read"):
55
+ return json.load(file_path)
56
+ with open(file_path, "r", encoding="utf-8") as file:
57
+ data = json.load(file)
58
+ return data
59
+
60
+ @staticmethod
61
+ def write_code_to_file(file_path: str | TextIO, code: str) -> None:
62
+ """Write the specified code to a Python file.
63
+
64
+ Args:
65
+ file_path (str): The path to the Python file.
66
+ code (str): The code to write to the file.
67
+
68
+ Returns:
69
+ None
70
+ """
71
+ if isinstance(file_path, str):
72
+ # Extract directory from the filename
73
+ directory = os.path.dirname(file_path)
74
+
75
+ # If the directory does not exist, create it
76
+ if directory and not os.path.exists(directory):
77
+ os.makedirs(directory)
78
+
79
+ # Save the code to a .py file
80
+ with open(file_path, "w", encoding="utf-8") as file:
81
+ file.write(code)
82
+ else:
83
+ file_path.write(code)
84
+
85
+
86
+ class LoadOrderDeterminer:
87
+ """Determine the load order of each key in the provided dictionary.
88
+
89
+ This class places the nodes without node dependencies first, then ensures that any node whose
90
+ result is used in another node will be added to the list in the order it should be executed.
91
+
92
+ Attributes:
93
+ data (Dict): The dictionary for which to determine the load order.
94
+ node_class_mappings (Dict): Mappings of node classes.
95
+ """
96
+
97
+ def __init__(self, data: Dict, node_class_mappings: Dict):
98
+ """Initialize the LoadOrderDeterminer with the given data and node class mappings.
99
+
100
+ Args:
101
+ data (Dict): The dictionary for which to determine the load order.
102
+ node_class_mappings (Dict): Mappings of node classes.
103
+ """
104
+ self.data = data
105
+ self.node_class_mappings = node_class_mappings
106
+ self.visited = {}
107
+ self.load_order = []
108
+ self.is_special_function = False
109
+
110
+ def determine_load_order(self) -> List[Tuple[str, Dict, bool]]:
111
+ """Determine the load order for the given data.
112
+
113
+ Returns:
114
+ List[Tuple[str, Dict, bool]]: A list of tuples representing the load order.
115
+ """
116
+ self._load_special_functions_first()
117
+ self.is_special_function = False
118
+ for key in self.data:
119
+ if key not in self.visited:
120
+ self._dfs(key)
121
+ return self.load_order
122
+
123
+ def _dfs(self, key: str) -> None:
124
+ """Depth-First Search function to determine the load order.
125
+
126
+ Args:
127
+ key (str): The key from which to start the DFS.
128
+
129
+ Returns:
130
+ None
131
+ """
132
+ # Mark the node as visited.
133
+ self.visited[key] = True
134
+ inputs = self.data[key]["inputs"]
135
+ # Loop over each input key.
136
+ for input_key, val in inputs.items():
137
+ # If the value is a list and the first item in the list has not been visited yet,
138
+ # then recursively apply DFS on the dependency.
139
+ if isinstance(val, list) and val[0] not in self.visited:
140
+ self._dfs(val[0])
141
+ # Add the key and its corresponding data to the load order list.
142
+ self.load_order.append((key, self.data[key], self.is_special_function))
143
+
144
+ def _load_special_functions_first(self) -> None:
145
+ """Load functions without dependencies, loaderes, and encoders first.
146
+
147
+ Returns:
148
+ None
149
+ """
150
+ # Iterate over each key in the data to check for loader keys.
151
+ for key in self.data:
152
+ class_def = self.node_class_mappings[self.data[key]["class_type"]]()
153
+ # Check if the class is a loader class or meets specific conditions.
154
+ if (
155
+ class_def.CATEGORY == "loaders"
156
+ or class_def.FUNCTION in ["encode"]
157
+ or not any(
158
+ isinstance(val, list) for val in self.data[key]["inputs"].values()
159
+ )
160
+ ):
161
+ self.is_special_function = True
162
+ # If the key has not been visited, perform a DFS from that key.
163
+ if key not in self.visited:
164
+ self._dfs(key)
165
+
166
+
167
+ class CodeGenerator:
168
+ """Generates Python code for a workflow based on the load order.
169
+
170
+ Attributes:
171
+ node_class_mappings (Dict): Mappings of node classes.
172
+ base_node_class_mappings (Dict): Base mappings of node classes.
173
+ """
174
+
175
+ def __init__(self, node_class_mappings: Dict, base_node_class_mappings: Dict):
176
+ """Initialize the CodeGenerator with given node class mappings.
177
+
178
+ Args:
179
+ node_class_mappings (Dict): Mappings of node classes.
180
+ base_node_class_mappings (Dict): Base mappings of node classes.
181
+ """
182
+ self.node_class_mappings = node_class_mappings
183
+ self.base_node_class_mappings = base_node_class_mappings
184
+
185
+ def generate_workflow(
186
+ self,
187
+ load_order: List,
188
+ queue_size: int = 10,
189
+ ) -> str:
190
+ """Generate the execution code based on the load order.
191
+
192
+ Args:
193
+ load_order (List): A list of tuples representing the load order.
194
+ queue_size (int): The number of photos that will be created by the script.
195
+
196
+ Returns:
197
+ str: Generated execution code as a string.
198
+ """
199
+ # Create the necessary data structures to hold imports and generated code
200
+ import_statements, executed_variables, special_functions_code, code = (
201
+ set(["NODE_CLASS_MAPPINGS"]),
202
+ {},
203
+ [],
204
+ [],
205
+ )
206
+ # This dictionary will store the names of the objects that we have already initialized
207
+ initialized_objects = {}
208
+
209
+ custom_nodes = False
210
+ # Loop over each dictionary in the load order list
211
+ for idx, data, is_special_function in load_order:
212
+ # Generate class definition and inputs from the data
213
+ inputs, class_type = data["inputs"], data["class_type"]
214
+ input_types = self.node_class_mappings[class_type].INPUT_TYPES()
215
+ class_def = self.node_class_mappings[class_type]()
216
+
217
+ # If required inputs are not present, skip the node as it will break the code if passed through to the script
218
+ missing_required_variable = False
219
+ if "required" in input_types.keys():
220
+ for required in input_types["required"]:
221
+ if required not in inputs.keys():
222
+ missing_required_variable = True
223
+ if missing_required_variable:
224
+ continue
225
+
226
+ # If the class hasn't been initialized yet, initialize it and generate the import statements
227
+ if class_type not in initialized_objects:
228
+ # No need to use preview image nodes since we are executing the script in a terminal
229
+ if class_type == "PreviewImage":
230
+ continue
231
+
232
+ class_type, import_statement, class_code = self.get_class_info(
233
+ class_type
234
+ )
235
+ initialized_objects[class_type] = self.clean_variable_name(class_type)
236
+ if class_type in self.base_node_class_mappings.keys():
237
+ import_statements.add(import_statement)
238
+ if class_type not in self.base_node_class_mappings.keys():
239
+ custom_nodes = True
240
+ special_functions_code.append(class_code)
241
+
242
+ # Get all possible parameters for class_def
243
+ class_def_params = self.get_function_parameters(
244
+ getattr(class_def, class_def.FUNCTION)
245
+ )
246
+ no_params = class_def_params is None
247
+
248
+ # Remove any keyword arguments from **inputs if they are not in class_def_params
249
+ inputs = {
250
+ key: value
251
+ for key, value in inputs.items()
252
+ if no_params or key in class_def_params
253
+ }
254
+ # Deal with hidden variables
255
+ if (
256
+ "hidden" in input_types.keys()
257
+ and "unique_id" in input_types["hidden"].keys()
258
+ ):
259
+ inputs["unique_id"] = random.randint(1, 2**64)
260
+ elif class_def_params is not None:
261
+ if "unique_id" in class_def_params:
262
+ inputs["unique_id"] = random.randint(1, 2**64)
263
+
264
+ # Create executed variable and generate code
265
+ executed_variables[idx] = f"{self.clean_variable_name(class_type)}_{idx}"
266
+ inputs = self.update_inputs(inputs, executed_variables)
267
+
268
+ if is_special_function:
269
+ special_functions_code.append(
270
+ self.create_function_call_code(
271
+ initialized_objects[class_type],
272
+ class_def.FUNCTION,
273
+ executed_variables[idx],
274
+ is_special_function,
275
+ **inputs,
276
+ )
277
+ )
278
+ else:
279
+ code.append(
280
+ self.create_function_call_code(
281
+ initialized_objects[class_type],
282
+ class_def.FUNCTION,
283
+ executed_variables[idx],
284
+ is_special_function,
285
+ **inputs,
286
+ )
287
+ )
288
+
289
+ # Generate final code by combining imports and code, and wrap them in a main function
290
+ final_code = self.assemble_python_code(
291
+ import_statements, special_functions_code, code, queue_size, custom_nodes
292
+ )
293
+
294
+ return final_code
295
+
296
+ def create_function_call_code(
297
+ self,
298
+ obj_name: str,
299
+ func: str,
300
+ variable_name: str,
301
+ is_special_function: bool,
302
+ **kwargs,
303
+ ) -> str:
304
+ """Generate Python code for a function call.
305
+
306
+ Args:
307
+ obj_name (str): The name of the initialized object.
308
+ func (str): The function to be called.
309
+ variable_name (str): The name of the variable that the function result should be assigned to.
310
+ is_special_function (bool): Determines the code indentation.
311
+ **kwargs: The keyword arguments for the function.
312
+
313
+ Returns:
314
+ str: The generated Python code.
315
+ """
316
+ args = ", ".join(self.format_arg(key, value) for key, value in kwargs.items())
317
+
318
+ # Generate the Python code
319
+ code = f"{variable_name} = {obj_name}.{func}({args})\n"
320
+
321
+ # If the code contains dependencies and is not a loader or encoder, indent the code because it will be placed inside
322
+ # of a for loop
323
+ if not is_special_function:
324
+ code = f"\t{code}"
325
+
326
+ return code
327
+
328
+ def format_arg(self, key: str, value: any) -> str:
329
+ """Formats arguments based on key and value.
330
+
331
+ Args:
332
+ key (str): Argument key.
333
+ value (any): Argument value.
334
+
335
+ Returns:
336
+ str: Formatted argument as a string.
337
+ """
338
+ if key == "noise_seed" or key == "seed":
339
+ return f"{key}=random.randint(1, 2**64)"
340
+ elif isinstance(value, str):
341
+ value = value.replace("\n", "\\n").replace('"', "'")
342
+ return f'{key}="{value}"'
343
+ elif isinstance(value, dict) and "variable_name" in value:
344
+ return f'{key}={value["variable_name"]}'
345
+ return f"{key}={value}"
346
+
347
+ def assemble_python_code(
348
+ self,
349
+ import_statements: set,
350
+ speical_functions_code: List[str],
351
+ code: List[str],
352
+ queue_size: int,
353
+ custom_nodes=False,
354
+ ) -> str:
355
+ """Generates the final code string.
356
+
357
+ Args:
358
+ import_statements (set): A set of unique import statements.
359
+ speical_functions_code (List[str]): A list of special functions code strings.
360
+ code (List[str]): A list of code strings.
361
+ queue_size (int): Number of photos that will be generated by the script.
362
+ custom_nodes (bool): Whether to include custom nodes in the code.
363
+
364
+ Returns:
365
+ str: Generated final code as a string.
366
+ """
367
+ # Get the source code of the utils functions as a string
368
+ func_strings = []
369
+ for func in [
370
+ get_value_at_index,
371
+ find_path,
372
+ add_comfyui_directory_to_sys_path,
373
+ add_extra_model_paths,
374
+ ]:
375
+ func_strings.append(f"\n{inspect.getsource(func)}")
376
+ # Define static import statements required for the script
377
+ static_imports = (
378
+ [
379
+ "import os",
380
+ "import random",
381
+ "import sys",
382
+ "from typing import Sequence, Mapping, Any, Union",
383
+ "import torch",
384
+ ]
385
+ + func_strings
386
+ + ["\n\nadd_comfyui_directory_to_sys_path()\nadd_extra_model_paths()\n"]
387
+ )
388
+ # Check if custom nodes should be included
389
+ if custom_nodes:
390
+ static_imports.append(f"\n{inspect.getsource(import_custom_nodes)}\n")
391
+ custom_nodes = "import_custom_nodes()\n\t"
392
+ else:
393
+ custom_nodes = ""
394
+ # Create import statements for node classes
395
+ imports_code = [
396
+ f"from nodes import {', '.join([class_name for class_name in import_statements])}"
397
+ ]
398
+ # Assemble the main function code, including custom nodes if applicable
399
+ main_function_code = (
400
+ "def main():\n\t"
401
+ + f"{custom_nodes}with torch.inference_mode():\n\t\t"
402
+ + "\n\t\t".join(speical_functions_code)
403
+ + f"\n\n\t\tfor q in range({queue_size}):\n\t\t"
404
+ + "\n\t\t".join(code)
405
+ )
406
+ # Concatenate all parts to form the final code
407
+ final_code = "\n".join(
408
+ static_imports
409
+ + imports_code
410
+ + ["", main_function_code, "", 'if __name__ == "__main__":', "\tmain()"]
411
+ )
412
+ # Format the final code according to PEP 8 using the Black library
413
+ final_code = black.format_str(final_code, mode=black.Mode())
414
+
415
+ return final_code
416
+
417
+ def get_class_info(self, class_type: str) -> Tuple[str, str, str]:
418
+ """Generates and returns necessary information about class type.
419
+
420
+ Args:
421
+ class_type (str): Class type.
422
+
423
+ Returns:
424
+ Tuple[str, str, str]: Updated class type, import statement string, class initialization code.
425
+ """
426
+ import_statement = class_type
427
+ variable_name = self.clean_variable_name(class_type)
428
+ if class_type in self.base_node_class_mappings.keys():
429
+ class_code = f"{variable_name} = {class_type.strip()}()"
430
+ else:
431
+ class_code = f'{variable_name} = NODE_CLASS_MAPPINGS["{class_type}"]()'
432
+
433
+ return class_type, import_statement, class_code
434
+
435
+ @staticmethod
436
+ def clean_variable_name(class_type: str) -> str:
437
+ """
438
+ Remove any characters from variable name that could cause errors running the Python script.
439
+
440
+ Args:
441
+ class_type (str): Class type.
442
+
443
+ Returns:
444
+ str: Cleaned variable name with no special characters or spaces
445
+ """
446
+ # Convert to lowercase and replace spaces with underscores
447
+ clean_name = class_type.lower().strip().replace("-", "_").replace(" ", "_")
448
+
449
+ # Remove characters that are not letters, numbers, or underscores
450
+ clean_name = re.sub(r"[^a-z0-9_]", "", clean_name)
451
+
452
+ # Ensure that it doesn't start with a number
453
+ if clean_name[0].isdigit():
454
+ clean_name = "_" + clean_name
455
+
456
+ return clean_name
457
+
458
+ def get_function_parameters(self, func: Callable) -> List:
459
+ """Get the names of a function's parameters.
460
+
461
+ Args:
462
+ func (Callable): The function whose parameters we want to inspect.
463
+
464
+ Returns:
465
+ List: A list containing the names of the function's parameters.
466
+ """
467
+ signature = inspect.signature(func)
468
+ parameters = {
469
+ name: param.default if param.default != param.empty else None
470
+ for name, param in signature.parameters.items()
471
+ }
472
+ catch_all = any(
473
+ param.kind == inspect.Parameter.VAR_KEYWORD
474
+ for param in signature.parameters.values()
475
+ )
476
+ return list(parameters.keys()) if not catch_all else None
477
+
478
+ def update_inputs(self, inputs: Dict, executed_variables: Dict) -> Dict:
479
+ """Update inputs based on the executed variables.
480
+
481
+ Args:
482
+ inputs (Dict): Inputs dictionary to update.
483
+ executed_variables (Dict): Dictionary storing executed variable names.
484
+
485
+ Returns:
486
+ Dict: Updated inputs dictionary.
487
+ """
488
+ for key in inputs.keys():
489
+ if (
490
+ isinstance(inputs[key], list)
491
+ and inputs[key][0] in executed_variables.keys()
492
+ ):
493
+ inputs[key] = {
494
+ "variable_name": f"get_value_at_index({executed_variables[inputs[key][0]]}, {inputs[key][1]})"
495
+ }
496
+ return inputs
497
+
498
+
499
+ class ComfyUItoPython:
500
+ """Main workflow to generate Python code from a workflow_api.json file.
501
+
502
+ Attributes:
503
+ input_file (str): Path to the input JSON file.
504
+ output_file (str): Path to the output Python file.
505
+ queue_size (int): The number of photos that will be created by the script.
506
+ node_class_mappings (Dict): Mappings of node classes.
507
+ base_node_class_mappings (Dict): Base mappings of node classes.
508
+ """
509
+
510
+ def __init__(
511
+ self,
512
+ workflow: str = "",
513
+ input_file: str = "",
514
+ output_file: str | TextIO = "",
515
+ queue_size: int = 1,
516
+ node_class_mappings: Dict = NODE_CLASS_MAPPINGS,
517
+ needs_init_custom_nodes: bool = False,
518
+ ):
519
+ """Initialize the ComfyUItoPython class with the given parameters. Exactly one of workflow or input_file must be specified.
520
+ Args:
521
+ workflow (str): The workflow's JSON.
522
+ input_file (str): Path to the input JSON file.
523
+ output_file (str | TextIO): Path to the output file or a file-like object.
524
+ queue_size (int): The number of times a workflow will be executed by the script. Defaults to 1.
525
+ node_class_mappings (Dict): Mappings of node classes. Defaults to NODE_CLASS_MAPPINGS.
526
+ needs_init_custom_nodes (bool): Whether to initialize custom nodes. Defaults to False.
527
+ """
528
+ if input_file and workflow:
529
+ raise ValueError("Can't provide both input_file and workflow")
530
+ elif not input_file and not workflow:
531
+ raise ValueError("Needs input_file or workflow")
532
+
533
+ if not output_file:
534
+ raise ValueError("Needs output_file")
535
+
536
+ self.workflow = workflow
537
+ self.input_file = input_file
538
+ self.output_file = output_file
539
+ self.queue_size = queue_size
540
+ self.node_class_mappings = node_class_mappings
541
+ self.needs_init_custom_nodes = needs_init_custom_nodes
542
+
543
+ self.base_node_class_mappings = copy.deepcopy(self.node_class_mappings)
544
+ self.execute()
545
+
546
+ def execute(self):
547
+ """Execute the main workflow to generate Python code.
548
+
549
+ Returns:
550
+ None
551
+ """
552
+ # Step 1: Import all custom nodes if we need to
553
+ if self.needs_init_custom_nodes:
554
+ import_custom_nodes()
555
+ else:
556
+ # If they're already imported, we don't know which nodes are custom nodes, so we need to import all of them
557
+ self.base_node_class_mappings = {}
558
+
559
+ # Step 2: Read JSON data from the input file
560
+ if self.input_file:
561
+ data = FileHandler.read_json_file(self.input_file)
562
+ else:
563
+ data = json.loads(self.workflow)
564
+
565
+ # Step 3: Determine the load order
566
+ load_order_determiner = LoadOrderDeterminer(data, self.node_class_mappings)
567
+ load_order = load_order_determiner.determine_load_order()
568
+
569
+ # Step 4: Generate the workflow code
570
+ code_generator = CodeGenerator(
571
+ self.node_class_mappings, self.base_node_class_mappings
572
+ )
573
+ generated_code = code_generator.generate_workflow(
574
+ load_order, queue_size=self.queue_size
575
+ )
576
+
577
+ # Step 5: Write the generated code to a file
578
+ FileHandler.write_code_to_file(self.output_file, generated_code)
579
+
580
+ print(f"Code successfully generated and written to {self.output_file}")
581
+
582
+
583
+ def run(
584
+ input_file: str = DEFAULT_INPUT_FILE,
585
+ output_file: str = DEFAULT_OUTPUT_FILE,
586
+ queue_size: int = DEFAULT_QUEUE_SIZE,
587
+ ) -> None:
588
+ """Generate Python code from a ComfyUI workflow_api.json file.
589
+
590
+ Args:
591
+ input_file (str): Path to the input JSON file. Defaults to "workflow_api.json".
592
+ output_file (str): Path to the output Python file.
593
+ Defaults to "workflow_api.py".
594
+ queue_size (int): The number of times a workflow will be executed by the script.
595
+ Defaults to 1.
596
+
597
+ Returns:
598
+ None
599
+ """
600
+ ComfyUItoPython(
601
+ input_file=input_file,
602
+ output_file=output_file,
603
+ queue_size=queue_size,
604
+ needs_init_custom_nodes=True,
605
+ )
606
+
607
+
608
+ def main() -> None:
609
+ """Main function to generate Python code from a ComfyUI workflow_api.json file."""
610
+ parser = ArgumentParser(
611
+ description="Generate Python code from a ComfyUI workflow_api.json file."
612
+ )
613
+ parser.add_argument(
614
+ "-f",
615
+ "--input_file",
616
+ type=str,
617
+ help="path to the input JSON file",
618
+ default=DEFAULT_INPUT_FILE,
619
+ )
620
+ parser.add_argument(
621
+ "-o",
622
+ "--output_file",
623
+ type=str,
624
+ help="path to the output Python file",
625
+ default=DEFAULT_OUTPUT_FILE,
626
+ )
627
+ parser.add_argument(
628
+ "-q",
629
+ "--queue_size",
630
+ type=int,
631
+ help="number of times the workflow will be executed by default",
632
+ default=DEFAULT_QUEUE_SIZE,
633
+ )
634
+ pargs = parser.parse_args()
635
+ run(**vars(pargs))
636
+ print("Done.")
637
+
638
+
639
+ if __name__ == "__main__":
640
+ """Run the main function."""
641
+ main()
comfyui_to_python_utils.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Sequence, Mapping, Any, Union
3
+ import sys
4
+
5
+
6
+ def import_custom_nodes() -> None:
7
+ """Find all custom nodes in the custom_nodes folder and add those node objects to NODE_CLASS_MAPPINGS
8
+
9
+ This function sets up a new asyncio event loop, initializes the PromptServer,
10
+ creates a PromptQueue, and initializes the custom nodes.
11
+ """
12
+ import asyncio
13
+ import execution
14
+ from nodes import init_extra_nodes
15
+ import server
16
+
17
+ # Creating a new event loop and setting it as the default loop
18
+ loop = asyncio.new_event_loop()
19
+ asyncio.set_event_loop(loop)
20
+
21
+ # Creating an instance of PromptServer with the loop
22
+ server_instance = server.PromptServer(loop)
23
+ execution.PromptQueue(server_instance)
24
+
25
+ # Initializing custom nodes
26
+ init_extra_nodes()
27
+
28
+
29
+ def find_path(name: str, path: str = None) -> str:
30
+ """
31
+ Recursively looks at parent folders starting from the given path until it finds the given name.
32
+ Returns the path as a Path object if found, or None otherwise.
33
+ """
34
+ # If no path is given, use the current working directory
35
+ if path is None:
36
+ path = os.getcwd()
37
+
38
+ # Check if the current directory contains the name
39
+ if name in os.listdir(path):
40
+ path_name = os.path.join(path, name)
41
+ print(f"{name} found: {path_name}")
42
+ return path_name
43
+
44
+ # Get the parent directory
45
+ parent_directory = os.path.dirname(path)
46
+
47
+ # If the parent directory is the same as the current directory, we've reached the root and stop the search
48
+ if parent_directory == path:
49
+ return None
50
+
51
+ # Recursively call the function with the parent directory
52
+ return find_path(name, parent_directory)
53
+
54
+
55
+ def add_comfyui_directory_to_sys_path() -> None:
56
+ """
57
+ Add 'ComfyUI' to the sys.path
58
+ """
59
+ comfyui_path = find_path("ComfyUI")
60
+ if comfyui_path is not None and os.path.isdir(comfyui_path):
61
+ sys.path.append(comfyui_path)
62
+ print(f"'{comfyui_path}' added to sys.path")
63
+
64
+
65
+ def add_extra_model_paths() -> None:
66
+ """
67
+ Parse the optional extra_model_paths.yaml file and add the parsed paths to the sys.path.
68
+ """
69
+ try:
70
+ from main import load_extra_path_config
71
+ except ImportError:
72
+ print(
73
+ "Could not import load_extra_path_config from main.py. Looking in utils.extra_config instead."
74
+ )
75
+ from utils.extra_config import load_extra_path_config
76
+
77
+ extra_model_paths = find_path("extra_model_paths.yaml")
78
+
79
+ if extra_model_paths is not None:
80
+ load_extra_path_config(extra_model_paths)
81
+ else:
82
+ print("Could not find the extra_model_paths config file.")
83
+
84
+
85
+ def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
86
+ """Returns the value at the given index of a sequence or mapping.
87
+
88
+ If the object is a sequence (like list or string), returns the value at the given index.
89
+ If the object is a mapping (like a dictionary), returns the value at the index-th key.
90
+
91
+ Some return a dictionary, in these cases, we look for the "results" key
92
+
93
+ Args:
94
+ obj (Union[Sequence, Mapping]): The object to retrieve the value from.
95
+ index (int): The index of the value to retrieve.
96
+
97
+ Returns:
98
+ Any: The value at the given index.
99
+
100
+ Raises:
101
+ IndexError: If the index is out of bounds for the object and the object is not a mapping.
102
+ """
103
+ try:
104
+ return obj[index]
105
+ except KeyError:
106
+ return obj["result"][index]
comfyui_version.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ # This file is automatically generated by the build process when version is
2
+ # updated in pyproject.toml.
3
+ __version__ = "0.3.35"
cuda_malloc.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import importlib.util
3
+ from comfy.cli_args import args
4
+ import subprocess
5
+
6
+ #Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import.
7
+ def get_gpu_names():
8
+ if os.name == 'nt':
9
+ import ctypes
10
+
11
+ # Define necessary C structures and types
12
+ class DISPLAY_DEVICEA(ctypes.Structure):
13
+ _fields_ = [
14
+ ('cb', ctypes.c_ulong),
15
+ ('DeviceName', ctypes.c_char * 32),
16
+ ('DeviceString', ctypes.c_char * 128),
17
+ ('StateFlags', ctypes.c_ulong),
18
+ ('DeviceID', ctypes.c_char * 128),
19
+ ('DeviceKey', ctypes.c_char * 128)
20
+ ]
21
+
22
+ # Load user32.dll
23
+ user32 = ctypes.windll.user32
24
+
25
+ # Call EnumDisplayDevicesA
26
+ def enum_display_devices():
27
+ device_info = DISPLAY_DEVICEA()
28
+ device_info.cb = ctypes.sizeof(device_info)
29
+ device_index = 0
30
+ gpu_names = set()
31
+
32
+ while user32.EnumDisplayDevicesA(None, device_index, ctypes.byref(device_info), 0):
33
+ device_index += 1
34
+ gpu_names.add(device_info.DeviceString.decode('utf-8'))
35
+ return gpu_names
36
+ return enum_display_devices()
37
+ else:
38
+ gpu_names = set()
39
+ out = subprocess.check_output(['nvidia-smi', '-L'])
40
+ for l in out.split(b'\n'):
41
+ if len(l) > 0:
42
+ gpu_names.add(l.decode('utf-8').split(' (UUID')[0])
43
+ return gpu_names
44
+
45
+ blacklist = {"GeForce GTX TITAN X", "GeForce GTX 980", "GeForce GTX 970", "GeForce GTX 960", "GeForce GTX 950", "GeForce 945M",
46
+ "GeForce 940M", "GeForce 930M", "GeForce 920M", "GeForce 910M", "GeForce GTX 750", "GeForce GTX 745", "Quadro K620",
47
+ "Quadro K1200", "Quadro K2200", "Quadro M500", "Quadro M520", "Quadro M600", "Quadro M620", "Quadro M1000",
48
+ "Quadro M1200", "Quadro M2000", "Quadro M2200", "Quadro M3000", "Quadro M4000", "Quadro M5000", "Quadro M5500", "Quadro M6000",
49
+ "GeForce MX110", "GeForce MX130", "GeForce 830M", "GeForce 840M", "GeForce GTX 850M", "GeForce GTX 860M",
50
+ "GeForce GTX 1650", "GeForce GTX 1630", "Tesla M4", "Tesla M6", "Tesla M10", "Tesla M40", "Tesla M60"
51
+ }
52
+
53
+ def cuda_malloc_supported():
54
+ try:
55
+ names = get_gpu_names()
56
+ except:
57
+ names = set()
58
+ for x in names:
59
+ if "NVIDIA" in x:
60
+ for b in blacklist:
61
+ if b in x:
62
+ return False
63
+ return True
64
+
65
+
66
+ if not args.cuda_malloc:
67
+ try:
68
+ version = ""
69
+ torch_spec = importlib.util.find_spec("torch")
70
+ for folder in torch_spec.submodule_search_locations:
71
+ ver_file = os.path.join(folder, "version.py")
72
+ if os.path.isfile(ver_file):
73
+ spec = importlib.util.spec_from_file_location("torch_version_import", ver_file)
74
+ module = importlib.util.module_from_spec(spec)
75
+ spec.loader.exec_module(module)
76
+ version = module.__version__
77
+ if int(version[0]) >= 2: #enable by default for torch version 2.0 and up
78
+ args.cuda_malloc = cuda_malloc_supported()
79
+ except:
80
+ pass
81
+
82
+
83
+ if args.cuda_malloc and not args.disable_cuda_malloc:
84
+ env_var = os.environ.get('PYTORCH_CUDA_ALLOC_CONF', None)
85
+ if env_var is None:
86
+ env_var = "backend:cudaMallocAsync"
87
+ else:
88
+ env_var += ",backend:cudaMallocAsync"
89
+
90
+ os.environ['PYTORCH_CUDA_ALLOC_CONF'] = env_var
execution.py ADDED
@@ -0,0 +1,1032 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, DependencyAwareCache, CacheKeySetInputSignature, CacheKeySetID
19
+ from comfy_execution.validation import validate_node_input
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
+
63
+ class CacheType(Enum):
64
+ CLASSIC = 0
65
+ LRU = 1
66
+ DEPENDENCY_AWARE = 2
67
+
68
+
69
+ class CacheSet:
70
+ def __init__(self, cache_type=None, cache_size=None):
71
+ if cache_type == CacheType.DEPENDENCY_AWARE:
72
+ self.init_dependency_aware_cache()
73
+ logging.info("Disabling intermediate node cache.")
74
+ elif cache_type == CacheType.LRU:
75
+ if cache_size is None:
76
+ cache_size = 0
77
+ self.init_lru_cache(cache_size)
78
+ logging.info("Using LRU cache")
79
+ else:
80
+ self.init_classic_cache()
81
+
82
+ self.all = [self.outputs, self.ui, self.objects]
83
+
84
+ # Performs like the old cache -- dump data ASAP
85
+ def init_classic_cache(self):
86
+ self.outputs = HierarchicalCache(CacheKeySetInputSignature)
87
+ self.ui = HierarchicalCache(CacheKeySetInputSignature)
88
+ self.objects = HierarchicalCache(CacheKeySetID)
89
+
90
+ def init_lru_cache(self, cache_size):
91
+ self.outputs = LRUCache(CacheKeySetInputSignature, max_size=cache_size)
92
+ self.ui = LRUCache(CacheKeySetInputSignature, max_size=cache_size)
93
+ self.objects = HierarchicalCache(CacheKeySetID)
94
+
95
+ # only hold cached items while the decendents have not executed
96
+ def init_dependency_aware_cache(self):
97
+ self.outputs = DependencyAwareCache(CacheKeySetInputSignature)
98
+ self.ui = DependencyAwareCache(CacheKeySetInputSignature)
99
+ self.objects = DependencyAwareCache(CacheKeySetID)
100
+
101
+ def recursive_debug_dump(self):
102
+ result = {
103
+ "outputs": self.outputs.recursive_debug_dump(),
104
+ "ui": self.ui.recursive_debug_dump(),
105
+ }
106
+ return result
107
+
108
+ def get_input_data(inputs, class_def, unique_id, outputs=None, dynprompt=None, extra_data={}):
109
+ valid_inputs = class_def.INPUT_TYPES()
110
+ input_data_all = {}
111
+ missing_keys = {}
112
+ for x in inputs:
113
+ input_data = inputs[x]
114
+ _, input_category, input_info = get_input_info(class_def, x, valid_inputs)
115
+ def mark_missing():
116
+ missing_keys[x] = True
117
+ input_data_all[x] = (None,)
118
+ if is_link(input_data) and (not input_info or not input_info.get("rawLink", False)):
119
+ input_unique_id = input_data[0]
120
+ output_index = input_data[1]
121
+ if outputs is None:
122
+ mark_missing()
123
+ continue # This might be a lazily-evaluated input
124
+ cached_output = outputs.get(input_unique_id)
125
+ if cached_output is None:
126
+ mark_missing()
127
+ continue
128
+ if output_index >= len(cached_output):
129
+ mark_missing()
130
+ continue
131
+ obj = cached_output[output_index]
132
+ input_data_all[x] = obj
133
+ elif input_category is not None:
134
+ input_data_all[x] = [input_data]
135
+
136
+ if "hidden" in valid_inputs:
137
+ h = valid_inputs["hidden"]
138
+ for x in h:
139
+ if h[x] == "PROMPT":
140
+ input_data_all[x] = [dynprompt.get_original_prompt() if dynprompt is not None else {}]
141
+ if h[x] == "DYNPROMPT":
142
+ input_data_all[x] = [dynprompt]
143
+ if h[x] == "EXTRA_PNGINFO":
144
+ input_data_all[x] = [extra_data.get('extra_pnginfo', None)]
145
+ if h[x] == "UNIQUE_ID":
146
+ input_data_all[x] = [unique_id]
147
+ if h[x] == "AUTH_TOKEN_COMFY_ORG":
148
+ input_data_all[x] = [extra_data.get("auth_token_comfy_org", None)]
149
+ if h[x] == "API_KEY_COMFY_ORG":
150
+ input_data_all[x] = [extra_data.get("api_key_comfy_org", None)]
151
+ return input_data_all, missing_keys
152
+
153
+ map_node_over_list = None #Don't hook this please
154
+
155
+ def _map_node_over_list(obj, input_data_all, func, allow_interrupt=False, execution_block_cb=None, pre_execute_cb=None):
156
+ # check if node wants the lists
157
+ input_is_list = getattr(obj, "INPUT_IS_LIST", False)
158
+
159
+ if len(input_data_all) == 0:
160
+ max_len_input = 0
161
+ else:
162
+ max_len_input = max(len(x) for x in input_data_all.values())
163
+
164
+ # get a slice of inputs, repeat last input when list isn't long enough
165
+ def slice_dict(d, i):
166
+ return {k: v[i if len(v) > i else -1] for k, v in d.items()}
167
+
168
+ results = []
169
+ def process_inputs(inputs, index=None, input_is_list=False):
170
+ if allow_interrupt:
171
+ nodes.before_node_execution()
172
+ execution_block = None
173
+ for k, v in inputs.items():
174
+ if input_is_list:
175
+ for e in v:
176
+ if isinstance(e, ExecutionBlocker):
177
+ v = e
178
+ break
179
+ if isinstance(v, ExecutionBlocker):
180
+ execution_block = execution_block_cb(v) if execution_block_cb else v
181
+ break
182
+ if execution_block is None:
183
+ if pre_execute_cb is not None and index is not None:
184
+ pre_execute_cb(index)
185
+ results.append(getattr(obj, func)(**inputs))
186
+ else:
187
+ results.append(execution_block)
188
+
189
+ if input_is_list:
190
+ process_inputs(input_data_all, 0, input_is_list=input_is_list)
191
+ elif max_len_input == 0:
192
+ process_inputs({})
193
+ else:
194
+ for i in range(max_len_input):
195
+ input_dict = slice_dict(input_data_all, i)
196
+ process_inputs(input_dict, i)
197
+ return results
198
+
199
+ def merge_result_data(results, obj):
200
+ # check which outputs need concatenating
201
+ output = []
202
+ output_is_list = [False] * len(results[0])
203
+ if hasattr(obj, "OUTPUT_IS_LIST"):
204
+ output_is_list = obj.OUTPUT_IS_LIST
205
+
206
+ # merge node execution results
207
+ for i, is_list in zip(range(len(results[0])), output_is_list):
208
+ if is_list:
209
+ value = []
210
+ for o in results:
211
+ if isinstance(o[i], ExecutionBlocker):
212
+ value.append(o[i])
213
+ else:
214
+ value.extend(o[i])
215
+ output.append(value)
216
+ else:
217
+ output.append([o[i] for o in results])
218
+ return output
219
+
220
+ def get_output_data(obj, input_data_all, execution_block_cb=None, pre_execute_cb=None):
221
+ results = []
222
+ uis = []
223
+ subgraph_results = []
224
+ 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)
225
+ has_subgraph = False
226
+ for i in range(len(return_values)):
227
+ r = return_values[i]
228
+ if isinstance(r, dict):
229
+ if 'ui' in r:
230
+ uis.append(r['ui'])
231
+ if 'expand' in r:
232
+ # Perform an expansion, but do not append results
233
+ has_subgraph = True
234
+ new_graph = r['expand']
235
+ result = r.get("result", None)
236
+ if isinstance(result, ExecutionBlocker):
237
+ result = tuple([result] * len(obj.RETURN_TYPES))
238
+ subgraph_results.append((new_graph, result))
239
+ elif 'result' in r:
240
+ result = r.get("result", None)
241
+ if isinstance(result, ExecutionBlocker):
242
+ result = tuple([result] * len(obj.RETURN_TYPES))
243
+ results.append(result)
244
+ subgraph_results.append((None, result))
245
+ else:
246
+ if isinstance(r, ExecutionBlocker):
247
+ r = tuple([r] * len(obj.RETURN_TYPES))
248
+ results.append(r)
249
+ subgraph_results.append((None, r))
250
+
251
+ if has_subgraph:
252
+ output = subgraph_results
253
+ elif len(results) > 0:
254
+ output = merge_result_data(results, obj)
255
+ else:
256
+ output = []
257
+ ui = dict()
258
+ if len(uis) > 0:
259
+ ui = {k: [y for x in uis for y in x[k]] for k in uis[0].keys()}
260
+ return output, ui, has_subgraph
261
+
262
+ def format_value(x):
263
+ if x is None:
264
+ return None
265
+ elif isinstance(x, (int, float, bool, str)):
266
+ return x
267
+ else:
268
+ return str(x)
269
+
270
+ def execute(server, dynprompt, caches, current_item, extra_data, executed, prompt_id, execution_list, pending_subgraph_results):
271
+ unique_id = current_item
272
+ real_node_id = dynprompt.get_real_node_id(unique_id)
273
+ display_node_id = dynprompt.get_display_node_id(unique_id)
274
+ parent_node_id = dynprompt.get_parent_node_id(unique_id)
275
+ inputs = dynprompt.get_node(unique_id)['inputs']
276
+ class_type = dynprompt.get_node(unique_id)['class_type']
277
+ class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
278
+ if caches.outputs.get(unique_id) is not None:
279
+ if server.client_id is not None:
280
+ cached_output = caches.ui.get(unique_id) or {}
281
+ 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)
282
+ return (ExecutionResult.SUCCESS, None, None)
283
+
284
+ input_data_all = None
285
+ try:
286
+ if unique_id in pending_subgraph_results:
287
+ cached_results = pending_subgraph_results[unique_id]
288
+ resolved_outputs = []
289
+ for is_subgraph, result in cached_results:
290
+ if not is_subgraph:
291
+ resolved_outputs.append(result)
292
+ else:
293
+ resolved_output = []
294
+ for r in result:
295
+ if is_link(r):
296
+ source_node, source_output = r[0], r[1]
297
+ node_output = caches.outputs.get(source_node)[source_output]
298
+ for o in node_output:
299
+ resolved_output.append(o)
300
+
301
+ else:
302
+ resolved_output.append(r)
303
+ resolved_outputs.append(tuple(resolved_output))
304
+ output_data = merge_result_data(resolved_outputs, class_def)
305
+ output_ui = []
306
+ has_subgraph = False
307
+ else:
308
+ input_data_all, missing_keys = get_input_data(inputs, class_def, unique_id, caches.outputs, dynprompt, extra_data)
309
+ if server.client_id is not None:
310
+ server.last_node_id = display_node_id
311
+ server.send_sync("executing", { "node": unique_id, "display_node": display_node_id, "prompt_id": prompt_id }, server.client_id)
312
+
313
+ obj = caches.objects.get(unique_id)
314
+ if obj is None:
315
+ obj = class_def()
316
+ caches.objects.set(unique_id, obj)
317
+
318
+ if hasattr(obj, "check_lazy_status"):
319
+ required_inputs = _map_node_over_list(obj, input_data_all, "check_lazy_status", allow_interrupt=True)
320
+ required_inputs = set(sum([r for r in required_inputs if isinstance(r,list)], []))
321
+ required_inputs = [x for x in required_inputs if isinstance(x,str) and (
322
+ x not in input_data_all or x in missing_keys
323
+ )]
324
+ if len(required_inputs) > 0:
325
+ for i in required_inputs:
326
+ execution_list.make_input_strong_link(unique_id, i)
327
+ return (ExecutionResult.PENDING, None, None)
328
+
329
+ def execution_block_cb(block):
330
+ if block.message is not None:
331
+ mes = {
332
+ "prompt_id": prompt_id,
333
+ "node_id": unique_id,
334
+ "node_type": class_type,
335
+ "executed": list(executed),
336
+
337
+ "exception_message": f"Execution Blocked: {block.message}",
338
+ "exception_type": "ExecutionBlocked",
339
+ "traceback": [],
340
+ "current_inputs": [],
341
+ "current_outputs": [],
342
+ }
343
+ server.send_sync("execution_error", mes, server.client_id)
344
+ return ExecutionBlocker(None)
345
+ else:
346
+ return block
347
+ def pre_execute_cb(call_index):
348
+ GraphBuilder.set_default_prefix(unique_id, call_index, 0)
349
+ 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)
350
+ if len(output_ui) > 0:
351
+ caches.ui.set(unique_id, {
352
+ "meta": {
353
+ "node_id": unique_id,
354
+ "display_node": display_node_id,
355
+ "parent_node": parent_node_id,
356
+ "real_node_id": real_node_id,
357
+ },
358
+ "output": output_ui
359
+ })
360
+ if server.client_id is not None:
361
+ server.send_sync("executed", { "node": unique_id, "display_node": display_node_id, "output": output_ui, "prompt_id": prompt_id }, server.client_id)
362
+ if has_subgraph:
363
+ cached_outputs = []
364
+ new_node_ids = []
365
+ new_output_ids = []
366
+ new_output_links = []
367
+ for i in range(len(output_data)):
368
+ new_graph, node_outputs = output_data[i]
369
+ if new_graph is None:
370
+ cached_outputs.append((False, node_outputs))
371
+ else:
372
+ # Check for conflicts
373
+ for node_id in new_graph.keys():
374
+ if dynprompt.has_node(node_id):
375
+ raise DuplicateNodeError(f"Attempt to add duplicate node {node_id}. Ensure node ids are unique and deterministic or use graph_utils.GraphBuilder.")
376
+ for node_id, node_info in new_graph.items():
377
+ new_node_ids.append(node_id)
378
+ display_id = node_info.get("override_display_id", unique_id)
379
+ dynprompt.add_ephemeral_node(node_id, node_info, unique_id, display_id)
380
+ # Figure out if the newly created node is an output node
381
+ class_type = node_info["class_type"]
382
+ class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
383
+ if hasattr(class_def, 'OUTPUT_NODE') and class_def.OUTPUT_NODE == True:
384
+ new_output_ids.append(node_id)
385
+ for i in range(len(node_outputs)):
386
+ if is_link(node_outputs[i]):
387
+ from_node_id, from_socket = node_outputs[i][0], node_outputs[i][1]
388
+ new_output_links.append((from_node_id, from_socket))
389
+ cached_outputs.append((True, node_outputs))
390
+ new_node_ids = set(new_node_ids)
391
+ for cache in caches.all:
392
+ cache.ensure_subcache_for(unique_id, new_node_ids).clean_unused()
393
+ for node_id in new_output_ids:
394
+ execution_list.add_node(node_id)
395
+ for link in new_output_links:
396
+ execution_list.add_strong_link(link[0], link[1], unique_id)
397
+ pending_subgraph_results[unique_id] = cached_outputs
398
+ return (ExecutionResult.PENDING, None, None)
399
+ caches.outputs.set(unique_id, output_data)
400
+ except comfy.model_management.InterruptProcessingException as iex:
401
+ logging.info("Processing interrupted")
402
+
403
+ # skip formatting inputs/outputs
404
+ error_details = {
405
+ "node_id": real_node_id,
406
+ }
407
+
408
+ return (ExecutionResult.FAILURE, error_details, iex)
409
+ except Exception as ex:
410
+ typ, _, tb = sys.exc_info()
411
+ exception_type = full_type_name(typ)
412
+ input_data_formatted = {}
413
+ if input_data_all is not None:
414
+ input_data_formatted = {}
415
+ for name, inputs in input_data_all.items():
416
+ input_data_formatted[name] = [format_value(x) for x in inputs]
417
+
418
+ logging.error(f"!!! Exception during processing !!! {ex}")
419
+ logging.error(traceback.format_exc())
420
+
421
+ error_details = {
422
+ "node_id": real_node_id,
423
+ "exception_message": str(ex),
424
+ "exception_type": exception_type,
425
+ "traceback": traceback.format_tb(tb),
426
+ "current_inputs": input_data_formatted
427
+ }
428
+ if isinstance(ex, comfy.model_management.OOM_EXCEPTION):
429
+ logging.error("Got an OOM, unloading all loaded models.")
430
+ comfy.model_management.unload_all_models()
431
+
432
+ return (ExecutionResult.FAILURE, error_details, ex)
433
+
434
+ executed.add(unique_id)
435
+
436
+ return (ExecutionResult.SUCCESS, None, None)
437
+
438
+ class PromptExecutor:
439
+ def __init__(self, server, cache_type=False, cache_size=None):
440
+ self.cache_size = cache_size
441
+ self.cache_type = cache_type
442
+ self.server = server
443
+ self.reset()
444
+
445
+ def reset(self):
446
+ self.caches = CacheSet(cache_type=self.cache_type, cache_size=self.cache_size)
447
+ self.status_messages = []
448
+ self.success = True
449
+
450
+ def add_message(self, event, data: dict, broadcast: bool):
451
+ data = {
452
+ **data,
453
+ "timestamp": int(time.time() * 1000),
454
+ }
455
+ self.status_messages.append((event, data))
456
+ if self.server.client_id is not None or broadcast:
457
+ self.server.send_sync(event, data, self.server.client_id)
458
+
459
+ def handle_execution_error(self, prompt_id, prompt, current_outputs, executed, error, ex):
460
+ node_id = error["node_id"]
461
+ class_type = prompt[node_id]["class_type"]
462
+
463
+ # First, send back the status to the frontend depending
464
+ # on the exception type
465
+ if isinstance(ex, comfy.model_management.InterruptProcessingException):
466
+ mes = {
467
+ "prompt_id": prompt_id,
468
+ "node_id": node_id,
469
+ "node_type": class_type,
470
+ "executed": list(executed),
471
+ }
472
+ self.add_message("execution_interrupted", mes, broadcast=True)
473
+ else:
474
+ mes = {
475
+ "prompt_id": prompt_id,
476
+ "node_id": node_id,
477
+ "node_type": class_type,
478
+ "executed": list(executed),
479
+ "exception_message": error["exception_message"],
480
+ "exception_type": error["exception_type"],
481
+ "traceback": error["traceback"],
482
+ "current_inputs": error["current_inputs"],
483
+ "current_outputs": list(current_outputs),
484
+ }
485
+ self.add_message("execution_error", mes, broadcast=False)
486
+
487
+ def execute(self, prompt, prompt_id, extra_data={}, execute_outputs=[]):
488
+ nodes.interrupt_processing(False)
489
+
490
+ if "client_id" in extra_data:
491
+ self.server.client_id = extra_data["client_id"]
492
+ else:
493
+ self.server.client_id = None
494
+
495
+ self.status_messages = []
496
+ self.add_message("execution_start", { "prompt_id": prompt_id}, broadcast=False)
497
+
498
+ with torch.inference_mode():
499
+ dynamic_prompt = DynamicPrompt(prompt)
500
+ is_changed_cache = IsChangedCache(dynamic_prompt, self.caches.outputs)
501
+ for cache in self.caches.all:
502
+ cache.set_prompt(dynamic_prompt, prompt.keys(), is_changed_cache)
503
+ cache.clean_unused()
504
+
505
+ cached_nodes = []
506
+ for node_id in prompt:
507
+ if self.caches.outputs.get(node_id) is not None:
508
+ cached_nodes.append(node_id)
509
+
510
+ comfy.model_management.cleanup_models_gc()
511
+ self.add_message("execution_cached",
512
+ { "nodes": cached_nodes, "prompt_id": prompt_id},
513
+ broadcast=False)
514
+ pending_subgraph_results = {}
515
+ executed = set()
516
+ execution_list = ExecutionList(dynamic_prompt, self.caches.outputs)
517
+ current_outputs = self.caches.outputs.all_node_ids()
518
+ for node_id in list(execute_outputs):
519
+ execution_list.add_node(node_id)
520
+
521
+ while not execution_list.is_empty():
522
+ node_id, error, ex = execution_list.stage_node_execution()
523
+ if error is not None:
524
+ self.handle_execution_error(prompt_id, dynamic_prompt.original_prompt, current_outputs, executed, error, ex)
525
+ break
526
+
527
+ result, error, ex = execute(self.server, dynamic_prompt, self.caches, node_id, extra_data, executed, prompt_id, execution_list, pending_subgraph_results)
528
+ self.success = result != ExecutionResult.FAILURE
529
+ if result == ExecutionResult.FAILURE:
530
+ self.handle_execution_error(prompt_id, dynamic_prompt.original_prompt, current_outputs, executed, error, ex)
531
+ break
532
+ elif result == ExecutionResult.PENDING:
533
+ execution_list.unstage_node_execution()
534
+ else: # result == ExecutionResult.SUCCESS:
535
+ execution_list.complete_node_execution()
536
+ else:
537
+ # Only execute when the while-loop ends without break
538
+ self.add_message("execution_success", { "prompt_id": prompt_id }, broadcast=False)
539
+
540
+ ui_outputs = {}
541
+ meta_outputs = {}
542
+ all_node_ids = self.caches.ui.all_node_ids()
543
+ for node_id in all_node_ids:
544
+ ui_info = self.caches.ui.get(node_id)
545
+ if ui_info is not None:
546
+ ui_outputs[node_id] = ui_info["output"]
547
+ meta_outputs[node_id] = ui_info["meta"]
548
+ self.history_result = {
549
+ "outputs": ui_outputs,
550
+ "meta": meta_outputs,
551
+ }
552
+ self.server.last_node_id = None
553
+ if comfy.model_management.DISABLE_SMART_MEMORY:
554
+ comfy.model_management.unload_all_models()
555
+
556
+
557
+ def validate_inputs(prompt, item, validated):
558
+ unique_id = item
559
+ if unique_id in validated:
560
+ return validated[unique_id]
561
+
562
+ inputs = prompt[unique_id]['inputs']
563
+ class_type = prompt[unique_id]['class_type']
564
+ obj_class = nodes.NODE_CLASS_MAPPINGS[class_type]
565
+
566
+ class_inputs = obj_class.INPUT_TYPES()
567
+ valid_inputs = set(class_inputs.get('required',{})).union(set(class_inputs.get('optional',{})))
568
+
569
+ errors = []
570
+ valid = True
571
+
572
+ validate_function_inputs = []
573
+ validate_has_kwargs = False
574
+ if hasattr(obj_class, "VALIDATE_INPUTS"):
575
+ argspec = inspect.getfullargspec(obj_class.VALIDATE_INPUTS)
576
+ validate_function_inputs = argspec.args
577
+ validate_has_kwargs = argspec.varkw is not None
578
+ received_types = {}
579
+
580
+ for x in valid_inputs:
581
+ input_type, input_category, extra_info = get_input_info(obj_class, x, class_inputs)
582
+ assert extra_info is not None
583
+ if x not in inputs:
584
+ if input_category == "required":
585
+ error = {
586
+ "type": "required_input_missing",
587
+ "message": "Required input is missing",
588
+ "details": f"{x}",
589
+ "extra_info": {
590
+ "input_name": x
591
+ }
592
+ }
593
+ errors.append(error)
594
+ continue
595
+
596
+ val = inputs[x]
597
+ info = (input_type, extra_info)
598
+ if isinstance(val, list):
599
+ if len(val) != 2:
600
+ error = {
601
+ "type": "bad_linked_input",
602
+ "message": "Bad linked input, must be a length-2 list of [node_id, slot_index]",
603
+ "details": f"{x}",
604
+ "extra_info": {
605
+ "input_name": x,
606
+ "input_config": info,
607
+ "received_value": val
608
+ }
609
+ }
610
+ errors.append(error)
611
+ continue
612
+
613
+ o_id = val[0]
614
+ o_class_type = prompt[o_id]['class_type']
615
+ r = nodes.NODE_CLASS_MAPPINGS[o_class_type].RETURN_TYPES
616
+ received_type = r[val[1]]
617
+ received_types[x] = received_type
618
+ if 'input_types' not in validate_function_inputs and not validate_node_input(received_type, input_type):
619
+ details = f"{x}, received_type({received_type}) mismatch input_type({input_type})"
620
+ error = {
621
+ "type": "return_type_mismatch",
622
+ "message": "Return type mismatch between linked nodes",
623
+ "details": details,
624
+ "extra_info": {
625
+ "input_name": x,
626
+ "input_config": info,
627
+ "received_type": received_type,
628
+ "linked_node": val
629
+ }
630
+ }
631
+ errors.append(error)
632
+ continue
633
+ try:
634
+ r = validate_inputs(prompt, o_id, validated)
635
+ if r[0] is False:
636
+ # `r` will be set in `validated[o_id]` already
637
+ valid = False
638
+ continue
639
+ except Exception as ex:
640
+ typ, _, tb = sys.exc_info()
641
+ valid = False
642
+ exception_type = full_type_name(typ)
643
+ reasons = [{
644
+ "type": "exception_during_inner_validation",
645
+ "message": "Exception when validating inner node",
646
+ "details": str(ex),
647
+ "extra_info": {
648
+ "input_name": x,
649
+ "input_config": info,
650
+ "exception_message": str(ex),
651
+ "exception_type": exception_type,
652
+ "traceback": traceback.format_tb(tb),
653
+ "linked_node": val
654
+ }
655
+ }]
656
+ validated[o_id] = (False, reasons, o_id)
657
+ continue
658
+ else:
659
+ try:
660
+ # Unwraps values wrapped in __value__ key. This is used to pass
661
+ # list widget value to execution, as by default list value is
662
+ # reserved to represent the connection between nodes.
663
+ if isinstance(val, dict) and "__value__" in val:
664
+ val = val["__value__"]
665
+ inputs[x] = val
666
+
667
+ if input_type == "INT":
668
+ val = int(val)
669
+ inputs[x] = val
670
+ if input_type == "FLOAT":
671
+ val = float(val)
672
+ inputs[x] = val
673
+ if input_type == "STRING":
674
+ val = str(val)
675
+ inputs[x] = val
676
+ if input_type == "BOOLEAN":
677
+ val = bool(val)
678
+ inputs[x] = val
679
+ except Exception as ex:
680
+ error = {
681
+ "type": "invalid_input_type",
682
+ "message": f"Failed to convert an input value to a {input_type} value",
683
+ "details": f"{x}, {val}, {ex}",
684
+ "extra_info": {
685
+ "input_name": x,
686
+ "input_config": info,
687
+ "received_value": val,
688
+ "exception_message": str(ex)
689
+ }
690
+ }
691
+ errors.append(error)
692
+ continue
693
+
694
+ if x not in validate_function_inputs and not validate_has_kwargs:
695
+ if "min" in extra_info and val < extra_info["min"]:
696
+ error = {
697
+ "type": "value_smaller_than_min",
698
+ "message": "Value {} smaller than min of {}".format(val, extra_info["min"]),
699
+ "details": f"{x}",
700
+ "extra_info": {
701
+ "input_name": x,
702
+ "input_config": info,
703
+ "received_value": val,
704
+ }
705
+ }
706
+ errors.append(error)
707
+ continue
708
+ if "max" in extra_info and val > extra_info["max"]:
709
+ error = {
710
+ "type": "value_bigger_than_max",
711
+ "message": "Value {} bigger than max of {}".format(val, extra_info["max"]),
712
+ "details": f"{x}",
713
+ "extra_info": {
714
+ "input_name": x,
715
+ "input_config": info,
716
+ "received_value": val,
717
+ }
718
+ }
719
+ errors.append(error)
720
+ continue
721
+
722
+ if isinstance(input_type, list):
723
+ combo_options = input_type
724
+ if val not in combo_options:
725
+ input_config = info
726
+ list_info = ""
727
+
728
+ # Don't send back gigantic lists like if they're lots of
729
+ # scanned model filepaths
730
+ if len(combo_options) > 20:
731
+ list_info = f"(list of length {len(combo_options)})"
732
+ input_config = None
733
+ else:
734
+ list_info = str(combo_options)
735
+
736
+ error = {
737
+ "type": "value_not_in_list",
738
+ "message": "Value not in list",
739
+ "details": f"{x}: '{val}' not in {list_info}",
740
+ "extra_info": {
741
+ "input_name": x,
742
+ "input_config": input_config,
743
+ "received_value": val,
744
+ }
745
+ }
746
+ errors.append(error)
747
+ continue
748
+
749
+ if len(validate_function_inputs) > 0 or validate_has_kwargs:
750
+ input_data_all, _ = get_input_data(inputs, obj_class, unique_id)
751
+ input_filtered = {}
752
+ for x in input_data_all:
753
+ if x in validate_function_inputs or validate_has_kwargs:
754
+ input_filtered[x] = input_data_all[x]
755
+ if 'input_types' in validate_function_inputs:
756
+ input_filtered['input_types'] = [received_types]
757
+
758
+ #ret = obj_class.VALIDATE_INPUTS(**input_filtered)
759
+ ret = _map_node_over_list(obj_class, input_filtered, "VALIDATE_INPUTS")
760
+ for x in input_filtered:
761
+ for i, r in enumerate(ret):
762
+ if r is not True and not isinstance(r, ExecutionBlocker):
763
+ details = f"{x}"
764
+ if r is not False:
765
+ details += f" - {str(r)}"
766
+
767
+ error = {
768
+ "type": "custom_validation_failed",
769
+ "message": "Custom validation failed for node",
770
+ "details": details,
771
+ "extra_info": {
772
+ "input_name": x,
773
+ }
774
+ }
775
+ errors.append(error)
776
+ continue
777
+
778
+ if len(errors) > 0 or valid is not True:
779
+ ret = (False, errors, unique_id)
780
+ else:
781
+ ret = (True, [], unique_id)
782
+
783
+ validated[unique_id] = ret
784
+ return ret
785
+
786
+ def full_type_name(klass):
787
+ module = klass.__module__
788
+ if module == 'builtins':
789
+ return klass.__qualname__
790
+ return module + '.' + klass.__qualname__
791
+
792
+ def validate_prompt(prompt):
793
+ outputs = set()
794
+ for x in prompt:
795
+ if 'class_type' not in prompt[x]:
796
+ error = {
797
+ "type": "invalid_prompt",
798
+ "message": "Cannot execute because a node is missing the class_type property.",
799
+ "details": f"Node ID '#{x}'",
800
+ "extra_info": {}
801
+ }
802
+ return (False, error, [], {})
803
+
804
+ class_type = prompt[x]['class_type']
805
+ class_ = nodes.NODE_CLASS_MAPPINGS.get(class_type, None)
806
+ if class_ is None:
807
+ error = {
808
+ "type": "invalid_prompt",
809
+ "message": f"Cannot execute because node {class_type} does not exist.",
810
+ "details": f"Node ID '#{x}'",
811
+ "extra_info": {}
812
+ }
813
+ return (False, error, [], {})
814
+
815
+ if hasattr(class_, 'OUTPUT_NODE') and class_.OUTPUT_NODE is True:
816
+ outputs.add(x)
817
+
818
+ if len(outputs) == 0:
819
+ error = {
820
+ "type": "prompt_no_outputs",
821
+ "message": "Prompt has no outputs",
822
+ "details": "",
823
+ "extra_info": {}
824
+ }
825
+ return (False, error, [], {})
826
+
827
+ good_outputs = set()
828
+ errors = []
829
+ node_errors = {}
830
+ validated = {}
831
+ for o in outputs:
832
+ valid = False
833
+ reasons = []
834
+ try:
835
+ m = validate_inputs(prompt, o, validated)
836
+ valid = m[0]
837
+ reasons = m[1]
838
+ except Exception as ex:
839
+ typ, _, tb = sys.exc_info()
840
+ valid = False
841
+ exception_type = full_type_name(typ)
842
+ reasons = [{
843
+ "type": "exception_during_validation",
844
+ "message": "Exception when validating node",
845
+ "details": str(ex),
846
+ "extra_info": {
847
+ "exception_type": exception_type,
848
+ "traceback": traceback.format_tb(tb)
849
+ }
850
+ }]
851
+ validated[o] = (False, reasons, o)
852
+
853
+ if valid is True:
854
+ good_outputs.add(o)
855
+ else:
856
+ logging.error(f"Failed to validate prompt for output {o}:")
857
+ if len(reasons) > 0:
858
+ logging.error("* (prompt):")
859
+ for reason in reasons:
860
+ logging.error(f" - {reason['message']}: {reason['details']}")
861
+ errors += [(o, reasons)]
862
+ for node_id, result in validated.items():
863
+ valid = result[0]
864
+ reasons = result[1]
865
+ # If a node upstream has errors, the nodes downstream will also
866
+ # be reported as invalid, but there will be no errors attached.
867
+ # So don't return those nodes as having errors in the response.
868
+ if valid is not True and len(reasons) > 0:
869
+ if node_id not in node_errors:
870
+ class_type = prompt[node_id]['class_type']
871
+ node_errors[node_id] = {
872
+ "errors": reasons,
873
+ "dependent_outputs": [],
874
+ "class_type": class_type
875
+ }
876
+ logging.error(f"* {class_type} {node_id}:")
877
+ for reason in reasons:
878
+ logging.error(f" - {reason['message']}: {reason['details']}")
879
+ node_errors[node_id]["dependent_outputs"].append(o)
880
+ logging.error("Output will be ignored")
881
+
882
+ if len(good_outputs) == 0:
883
+ errors_list = []
884
+ for o, errors in errors:
885
+ for error in errors:
886
+ errors_list.append(f"{error['message']}: {error['details']}")
887
+ errors_list = "\n".join(errors_list)
888
+
889
+ error = {
890
+ "type": "prompt_outputs_failed_validation",
891
+ "message": "Prompt outputs failed validation",
892
+ "details": errors_list,
893
+ "extra_info": {}
894
+ }
895
+
896
+ return (False, error, list(good_outputs), node_errors)
897
+
898
+ return (True, None, list(good_outputs), node_errors)
899
+
900
+ MAXIMUM_HISTORY_SIZE = 10000
901
+
902
+ class PromptQueue:
903
+ def __init__(self, server):
904
+ self.server = server
905
+ self.mutex = threading.RLock()
906
+ self.not_empty = threading.Condition(self.mutex)
907
+ self.task_counter = 0
908
+ self.queue = []
909
+ self.currently_running = {}
910
+ self.history = {}
911
+ self.flags = {}
912
+
913
+ def put(self, item):
914
+ with self.mutex:
915
+ heapq.heappush(self.queue, item)
916
+ self.server.queue_updated()
917
+ self.not_empty.notify()
918
+
919
+ def get(self, timeout=None):
920
+ with self.not_empty:
921
+ while len(self.queue) == 0:
922
+ self.not_empty.wait(timeout=timeout)
923
+ if timeout is not None and len(self.queue) == 0:
924
+ return None
925
+ item = heapq.heappop(self.queue)
926
+ i = self.task_counter
927
+ self.currently_running[i] = copy.deepcopy(item)
928
+ self.task_counter += 1
929
+ self.server.queue_updated()
930
+ return (item, i)
931
+
932
+ class ExecutionStatus(NamedTuple):
933
+ status_str: Literal['success', 'error']
934
+ completed: bool
935
+ messages: List[str]
936
+
937
+ def task_done(self, item_id, history_result,
938
+ status: Optional['PromptQueue.ExecutionStatus']):
939
+ with self.mutex:
940
+ prompt = self.currently_running.pop(item_id)
941
+ if len(self.history) > MAXIMUM_HISTORY_SIZE:
942
+ self.history.pop(next(iter(self.history)))
943
+
944
+ status_dict: Optional[dict] = None
945
+ if status is not None:
946
+ status_dict = copy.deepcopy(status._asdict())
947
+
948
+ self.history[prompt[1]] = {
949
+ "prompt": prompt,
950
+ "outputs": {},
951
+ 'status': status_dict,
952
+ }
953
+ self.history[prompt[1]].update(history_result)
954
+ self.server.queue_updated()
955
+
956
+ # Note: slow
957
+ def get_current_queue(self):
958
+ with self.mutex:
959
+ out = []
960
+ for x in self.currently_running.values():
961
+ out += [x]
962
+ return (out, copy.deepcopy(self.queue))
963
+
964
+ # read-safe as long as queue items are immutable
965
+ def get_current_queue_volatile(self):
966
+ with self.mutex:
967
+ running = [x for x in self.currently_running.values()]
968
+ queued = copy.copy(self.queue)
969
+ return (running, queued)
970
+
971
+ def get_tasks_remaining(self):
972
+ with self.mutex:
973
+ return len(self.queue) + len(self.currently_running)
974
+
975
+ def wipe_queue(self):
976
+ with self.mutex:
977
+ self.queue = []
978
+ self.server.queue_updated()
979
+
980
+ def delete_queue_item(self, function):
981
+ with self.mutex:
982
+ for x in range(len(self.queue)):
983
+ if function(self.queue[x]):
984
+ if len(self.queue) == 1:
985
+ self.wipe_queue()
986
+ else:
987
+ self.queue.pop(x)
988
+ heapq.heapify(self.queue)
989
+ self.server.queue_updated()
990
+ return True
991
+ return False
992
+
993
+ def get_history(self, prompt_id=None, max_items=None, offset=-1):
994
+ with self.mutex:
995
+ if prompt_id is None:
996
+ out = {}
997
+ i = 0
998
+ if offset < 0 and max_items is not None:
999
+ offset = len(self.history) - max_items
1000
+ for k in self.history:
1001
+ if i >= offset:
1002
+ out[k] = self.history[k]
1003
+ if max_items is not None and len(out) >= max_items:
1004
+ break
1005
+ i += 1
1006
+ return out
1007
+ elif prompt_id in self.history:
1008
+ return {prompt_id: copy.deepcopy(self.history[prompt_id])}
1009
+ else:
1010
+ return {}
1011
+
1012
+ def wipe_history(self):
1013
+ with self.mutex:
1014
+ self.history = {}
1015
+
1016
+ def delete_history_item(self, id_to_delete):
1017
+ with self.mutex:
1018
+ self.history.pop(id_to_delete, None)
1019
+
1020
+ def set_flag(self, name, data):
1021
+ with self.mutex:
1022
+ self.flags[name] = data
1023
+ self.not_empty.notify()
1024
+
1025
+ def get_flags(self, reset=True):
1026
+ with self.mutex:
1027
+ if reset:
1028
+ ret = self.flags
1029
+ self.flags = {}
1030
+ return ret
1031
+ else:
1032
+ return self.flags.copy()
extra_model_paths.yaml.example ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # # You can use is_default to mark that these folders should be listed first, and used as the default dirs for eg downloads
29
+ # #is_default: true
30
+ # checkpoints: models/checkpoints/
31
+ # clip: models/clip/
32
+ # clip_vision: models/clip_vision/
33
+ # configs: models/configs/
34
+ # controlnet: models/controlnet/
35
+ # diffusion_models: |
36
+ # models/diffusion_models
37
+ # models/unet
38
+ # embeddings: models/embeddings/
39
+ # loras: models/loras/
40
+ # upscale_models: models/upscale_models/
41
+ # vae: models/vae/
42
+
43
+ #other_ui:
44
+ # base_path: path/to/ui
45
+ # checkpoints: models/checkpoints
46
+ # gligen: models/gligen
47
+ # custom_nodes: path/custom_nodes
folder_paths.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import time
5
+ import mimetypes
6
+ import logging
7
+ from typing import Literal, List
8
+ from collections.abc import Collection
9
+
10
+ from comfy.cli_args import args
11
+
12
+ supported_pt_extensions: set[str] = {'.ckpt', '.pt', '.pt2', '.bin', '.pth', '.safetensors', '.pkl', '.sft'}
13
+
14
+ folder_names_and_paths: dict[str, tuple[list[str], set[str]]] = {}
15
+
16
+ # --base-directory - Resets all default paths configured in folder_paths with a new base path
17
+ if args.base_directory:
18
+ base_path = os.path.abspath(args.base_directory)
19
+ else:
20
+ base_path = os.path.dirname(os.path.realpath(__file__))
21
+
22
+ models_dir = os.path.join(base_path, "models")
23
+ folder_names_and_paths["checkpoints"] = ([os.path.join(models_dir, "checkpoints")], supported_pt_extensions)
24
+ folder_names_and_paths["configs"] = ([os.path.join(models_dir, "configs")], [".yaml"])
25
+
26
+ folder_names_and_paths["loras"] = ([os.path.join(models_dir, "loras")], supported_pt_extensions)
27
+ folder_names_and_paths["vae"] = ([os.path.join(models_dir, "vae")], supported_pt_extensions)
28
+ folder_names_and_paths["text_encoders"] = ([os.path.join(models_dir, "text_encoders"), os.path.join(models_dir, "clip")], supported_pt_extensions)
29
+ folder_names_and_paths["diffusion_models"] = ([os.path.join(models_dir, "unet"), os.path.join(models_dir, "diffusion_models")], supported_pt_extensions)
30
+ folder_names_and_paths["clip_vision"] = ([os.path.join(models_dir, "clip_vision")], supported_pt_extensions)
31
+ folder_names_and_paths["style_models"] = ([os.path.join(models_dir, "style_models")], supported_pt_extensions)
32
+ folder_names_and_paths["embeddings"] = ([os.path.join(models_dir, "embeddings")], supported_pt_extensions)
33
+ folder_names_and_paths["diffusers"] = ([os.path.join(models_dir, "diffusers")], ["folder"])
34
+ folder_names_and_paths["vae_approx"] = ([os.path.join(models_dir, "vae_approx")], supported_pt_extensions)
35
+
36
+ folder_names_and_paths["controlnet"] = ([os.path.join(models_dir, "controlnet"), os.path.join(models_dir, "t2i_adapter")], supported_pt_extensions)
37
+ folder_names_and_paths["gligen"] = ([os.path.join(models_dir, "gligen")], supported_pt_extensions)
38
+
39
+ folder_names_and_paths["upscale_models"] = ([os.path.join(models_dir, "upscale_models")], supported_pt_extensions)
40
+
41
+ folder_names_and_paths["custom_nodes"] = ([os.path.join(base_path, "custom_nodes")], set())
42
+
43
+ folder_names_and_paths["hypernetworks"] = ([os.path.join(models_dir, "hypernetworks")], supported_pt_extensions)
44
+
45
+ folder_names_and_paths["photomaker"] = ([os.path.join(models_dir, "photomaker")], supported_pt_extensions)
46
+
47
+ folder_names_and_paths["classifiers"] = ([os.path.join(models_dir, "classifiers")], {""})
48
+
49
+ output_directory = os.path.join(base_path, "output")
50
+ temp_directory = os.path.join(base_path, "temp")
51
+ input_directory = os.path.join(base_path, "input")
52
+ user_directory = os.path.join(base_path, "user")
53
+
54
+ filename_list_cache: dict[str, tuple[list[str], dict[str, float], float]] = {}
55
+
56
+ class CacheHelper:
57
+ """
58
+ Helper class for managing file list cache data.
59
+ """
60
+ def __init__(self):
61
+ self.cache: dict[str, tuple[list[str], dict[str, float], float]] = {}
62
+ self.active = False
63
+
64
+ def get(self, key: str, default=None) -> tuple[list[str], dict[str, float], float]:
65
+ if not self.active:
66
+ return default
67
+ return self.cache.get(key, default)
68
+
69
+ def set(self, key: str, value: tuple[list[str], dict[str, float], float]) -> None:
70
+ if self.active:
71
+ self.cache[key] = value
72
+
73
+ def clear(self):
74
+ self.cache.clear()
75
+
76
+ def __enter__(self):
77
+ self.active = True
78
+ return self
79
+
80
+ def __exit__(self, exc_type, exc_value, traceback):
81
+ self.active = False
82
+ self.clear()
83
+
84
+ cache_helper = CacheHelper()
85
+
86
+ extension_mimetypes_cache = {
87
+ "webp" : "image",
88
+ "fbx" : "model",
89
+ }
90
+
91
+ def map_legacy(folder_name: str) -> str:
92
+ legacy = {"unet": "diffusion_models",
93
+ "clip": "text_encoders"}
94
+ return legacy.get(folder_name, folder_name)
95
+
96
+ if not os.path.exists(input_directory):
97
+ try:
98
+ os.makedirs(input_directory)
99
+ except:
100
+ logging.error("Failed to create input directory")
101
+
102
+ def set_output_directory(output_dir: str) -> None:
103
+ global output_directory
104
+ output_directory = output_dir
105
+
106
+ def set_temp_directory(temp_dir: str) -> None:
107
+ global temp_directory
108
+ temp_directory = temp_dir
109
+
110
+ def set_input_directory(input_dir: str) -> None:
111
+ global input_directory
112
+ input_directory = input_dir
113
+
114
+ def get_output_directory() -> str:
115
+ global output_directory
116
+ return output_directory
117
+
118
+ def get_temp_directory() -> str:
119
+ global temp_directory
120
+ return temp_directory
121
+
122
+ def get_input_directory() -> str:
123
+ global input_directory
124
+ return input_directory
125
+
126
+ def get_user_directory() -> str:
127
+ return user_directory
128
+
129
+ def set_user_directory(user_dir: str) -> None:
130
+ global user_directory
131
+ user_directory = user_dir
132
+
133
+
134
+ #NOTE: used in http server so don't put folders that should not be accessed remotely
135
+ def get_directory_by_type(type_name: str) -> str | None:
136
+ if type_name == "output":
137
+ return get_output_directory()
138
+ if type_name == "temp":
139
+ return get_temp_directory()
140
+ if type_name == "input":
141
+ return get_input_directory()
142
+ return None
143
+
144
+ def filter_files_content_types(files: list[str], content_types: List[Literal["image", "video", "audio", "model"]]) -> list[str]:
145
+ """
146
+ Example:
147
+ files = os.listdir(folder_paths.get_input_directory())
148
+ videos = filter_files_content_types(files, ["video"])
149
+
150
+ Note:
151
+ - 'model' in MIME context refers to 3D models, not files containing trained weights and parameters
152
+ """
153
+ global extension_mimetypes_cache
154
+ result = []
155
+ for file in files:
156
+ extension = file.split('.')[-1]
157
+ if extension not in extension_mimetypes_cache:
158
+ mime_type, _ = mimetypes.guess_type(file, strict=False)
159
+ if not mime_type:
160
+ continue
161
+ content_type = mime_type.split('/')[0]
162
+ extension_mimetypes_cache[extension] = content_type
163
+ else:
164
+ content_type = extension_mimetypes_cache[extension]
165
+
166
+ if content_type in content_types:
167
+ result.append(file)
168
+ return result
169
+
170
+ # determine base_dir rely on annotation if name is 'filename.ext [annotation]' format
171
+ # otherwise use default_path as base_dir
172
+ def annotated_filepath(name: str) -> tuple[str, str | None]:
173
+ if name.endswith("[output]"):
174
+ base_dir = get_output_directory()
175
+ name = name[:-9]
176
+ elif name.endswith("[input]"):
177
+ base_dir = get_input_directory()
178
+ name = name[:-8]
179
+ elif name.endswith("[temp]"):
180
+ base_dir = get_temp_directory()
181
+ name = name[:-7]
182
+ else:
183
+ return name, None
184
+
185
+ return name, base_dir
186
+
187
+
188
+ def get_annotated_filepath(name: str, default_dir: str | None=None) -> str:
189
+ name, base_dir = annotated_filepath(name)
190
+
191
+ if base_dir is None:
192
+ if default_dir is not None:
193
+ base_dir = default_dir
194
+ else:
195
+ base_dir = get_input_directory() # fallback path
196
+
197
+ return os.path.join(base_dir, name)
198
+
199
+
200
+ def exists_annotated_filepath(name) -> bool:
201
+ name, base_dir = annotated_filepath(name)
202
+
203
+ if base_dir is None:
204
+ base_dir = get_input_directory() # fallback path
205
+
206
+ filepath = os.path.join(base_dir, name)
207
+ return os.path.exists(filepath)
208
+
209
+
210
+ def add_model_folder_path(folder_name: str, full_folder_path: str, is_default: bool = False) -> None:
211
+ global folder_names_and_paths
212
+ folder_name = map_legacy(folder_name)
213
+ if folder_name in folder_names_and_paths:
214
+ paths, _exts = folder_names_and_paths[folder_name]
215
+ if full_folder_path in paths:
216
+ if is_default and paths[0] != full_folder_path:
217
+ # If the path to the folder is not the first in the list, move it to the beginning.
218
+ paths.remove(full_folder_path)
219
+ paths.insert(0, full_folder_path)
220
+ else:
221
+ if is_default:
222
+ paths.insert(0, full_folder_path)
223
+ else:
224
+ paths.append(full_folder_path)
225
+ else:
226
+ folder_names_and_paths[folder_name] = ([full_folder_path], set())
227
+
228
+ def get_folder_paths(folder_name: str) -> list[str]:
229
+ folder_name = map_legacy(folder_name)
230
+ return folder_names_and_paths[folder_name][0][:]
231
+
232
+ def recursive_search(directory: str, excluded_dir_names: list[str] | None=None) -> tuple[list[str], dict[str, float]]:
233
+ if not os.path.isdir(directory):
234
+ return [], {}
235
+
236
+ if excluded_dir_names is None:
237
+ excluded_dir_names = []
238
+
239
+ result = []
240
+ dirs = {}
241
+
242
+ # Attempt to add the initial directory to dirs with error handling
243
+ try:
244
+ dirs[directory] = os.path.getmtime(directory)
245
+ except FileNotFoundError:
246
+ logging.warning(f"Warning: Unable to access {directory}. Skipping this path.")
247
+
248
+ logging.debug("recursive file list on directory {}".format(directory))
249
+ dirpath: str
250
+ subdirs: list[str]
251
+ filenames: list[str]
252
+
253
+ for dirpath, subdirs, filenames in os.walk(directory, followlinks=True, topdown=True):
254
+ subdirs[:] = [d for d in subdirs if d not in excluded_dir_names]
255
+ for file_name in filenames:
256
+ try:
257
+ relative_path = os.path.relpath(os.path.join(dirpath, file_name), directory)
258
+ result.append(relative_path)
259
+ except:
260
+ logging.warning(f"Warning: Unable to access {file_name}. Skipping this file.")
261
+ continue
262
+
263
+ for d in subdirs:
264
+ path: str = os.path.join(dirpath, d)
265
+ try:
266
+ dirs[path] = os.path.getmtime(path)
267
+ except FileNotFoundError:
268
+ logging.warning(f"Warning: Unable to access {path}. Skipping this path.")
269
+ continue
270
+ logging.debug("found {} files".format(len(result)))
271
+ return result, dirs
272
+
273
+ def filter_files_extensions(files: Collection[str], extensions: Collection[str]) -> list[str]:
274
+ return sorted(list(filter(lambda a: os.path.splitext(a)[-1].lower() in extensions or len(extensions) == 0, files)))
275
+
276
+
277
+
278
+ def get_full_path(folder_name: str, filename: str) -> str | None:
279
+ global folder_names_and_paths
280
+ folder_name = map_legacy(folder_name)
281
+ if folder_name not in folder_names_and_paths:
282
+ return None
283
+ folders = folder_names_and_paths[folder_name]
284
+ filename = os.path.relpath(os.path.join("/", filename), "/")
285
+ for x in folders[0]:
286
+ full_path = os.path.join(x, filename)
287
+ if os.path.isfile(full_path):
288
+ return full_path
289
+ elif os.path.islink(full_path):
290
+ logging.warning("WARNING path {} exists but doesn't link anywhere, skipping.".format(full_path))
291
+
292
+ return None
293
+
294
+
295
+ def get_full_path_or_raise(folder_name: str, filename: str) -> str:
296
+ full_path = get_full_path(folder_name, filename)
297
+ if full_path is None:
298
+ raise FileNotFoundError(f"Model in folder '{folder_name}' with filename '{filename}' not found.")
299
+ return full_path
300
+
301
+
302
+ def get_filename_list_(folder_name: str) -> tuple[list[str], dict[str, float], float]:
303
+ folder_name = map_legacy(folder_name)
304
+ global folder_names_and_paths
305
+ output_list = set()
306
+ folders = folder_names_and_paths[folder_name]
307
+ output_folders = {}
308
+ for x in folders[0]:
309
+ files, folders_all = recursive_search(x, excluded_dir_names=[".git"])
310
+ output_list.update(filter_files_extensions(files, folders[1]))
311
+ output_folders = {**output_folders, **folders_all}
312
+
313
+ return sorted(list(output_list)), output_folders, time.perf_counter()
314
+
315
+ def cached_filename_list_(folder_name: str) -> tuple[list[str], dict[str, float], float] | None:
316
+ strong_cache = cache_helper.get(folder_name)
317
+ if strong_cache is not None:
318
+ return strong_cache
319
+
320
+ global filename_list_cache
321
+ global folder_names_and_paths
322
+ folder_name = map_legacy(folder_name)
323
+ if folder_name not in filename_list_cache:
324
+ return None
325
+ out = filename_list_cache[folder_name]
326
+
327
+ for x in out[1]:
328
+ time_modified = out[1][x]
329
+ folder = x
330
+ if os.path.getmtime(folder) != time_modified:
331
+ return None
332
+
333
+ folders = folder_names_and_paths[folder_name]
334
+ for x in folders[0]:
335
+ if os.path.isdir(x):
336
+ if x not in out[1]:
337
+ return None
338
+
339
+ return out
340
+
341
+ def get_filename_list(folder_name: str) -> list[str]:
342
+ folder_name = map_legacy(folder_name)
343
+ out = cached_filename_list_(folder_name)
344
+ if out is None:
345
+ out = get_filename_list_(folder_name)
346
+ global filename_list_cache
347
+ filename_list_cache[folder_name] = out
348
+ cache_helper.set(folder_name, out)
349
+ return list(out[0])
350
+
351
+ def get_save_image_path(filename_prefix: str, output_dir: str, image_width=0, image_height=0) -> tuple[str, str, int, str, str]:
352
+ def map_filename(filename: str) -> tuple[int, str]:
353
+ prefix_len = len(os.path.basename(filename_prefix))
354
+ prefix = filename[:prefix_len + 1]
355
+ try:
356
+ digits = int(filename[prefix_len + 1:].split('_')[0])
357
+ except:
358
+ digits = 0
359
+ return digits, prefix
360
+
361
+ def compute_vars(input: str, image_width: int, image_height: int) -> str:
362
+ input = input.replace("%width%", str(image_width))
363
+ input = input.replace("%height%", str(image_height))
364
+ now = time.localtime()
365
+ input = input.replace("%year%", str(now.tm_year))
366
+ input = input.replace("%month%", str(now.tm_mon).zfill(2))
367
+ input = input.replace("%day%", str(now.tm_mday).zfill(2))
368
+ input = input.replace("%hour%", str(now.tm_hour).zfill(2))
369
+ input = input.replace("%minute%", str(now.tm_min).zfill(2))
370
+ input = input.replace("%second%", str(now.tm_sec).zfill(2))
371
+ return input
372
+
373
+ if "%" in filename_prefix:
374
+ filename_prefix = compute_vars(filename_prefix, image_width, image_height)
375
+
376
+ subfolder = os.path.dirname(os.path.normpath(filename_prefix))
377
+ filename = os.path.basename(os.path.normpath(filename_prefix))
378
+
379
+ full_output_folder = os.path.join(output_dir, subfolder)
380
+
381
+ if os.path.commonpath((output_dir, os.path.abspath(full_output_folder))) != output_dir:
382
+ err = "**** ERROR: Saving image outside the output folder is not allowed." + \
383
+ "\n full_output_folder: " + os.path.abspath(full_output_folder) + \
384
+ "\n output_dir: " + output_dir + \
385
+ "\n commonpath: " + os.path.commonpath((output_dir, os.path.abspath(full_output_folder)))
386
+ logging.error(err)
387
+ raise Exception(err)
388
+
389
+ try:
390
+ 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
391
+ except ValueError:
392
+ counter = 1
393
+ except FileNotFoundError:
394
+ os.makedirs(full_output_folder, exist_ok=True)
395
+ counter = 1
396
+ return full_output_folder, filename, counter, subfolder, filename_prefix
hook_breaker_ac10a0.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Prevent custom nodes from hooking anything important
2
+ import comfy.model_management
3
+
4
+ HOOK_BREAK = [(comfy.model_management, "cast_to")]
5
+
6
+
7
+ SAVED_FUNCTIONS = []
8
+
9
+
10
+ def save_functions():
11
+ for f in HOOK_BREAK:
12
+ SAVED_FUNCTIONS.append((f[0], f[1], getattr(f[0], f[1])))
13
+
14
+
15
+ def restore_functions():
16
+ for f in SAVED_FUNCTIONS:
17
+ setattr(f[0], f[1], f[2])
latent_preview.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from PIL import Image
3
+ from comfy.cli_args import args, LatentPreviewMethod
4
+ from comfy.taesd.taesd import TAESD
5
+ import comfy.model_management
6
+ import folder_paths
7
+ import comfy.utils
8
+ import logging
9
+
10
+ MAX_PREVIEW_RESOLUTION = args.preview_size
11
+
12
+ def preview_to_image(latent_image):
13
+ latents_ubyte = (((latent_image + 1.0) / 2.0).clamp(0, 1) # change scale from -1..1 to 0..1
14
+ .mul(0xFF) # to 0..255
15
+ )
16
+ if comfy.model_management.directml_enabled:
17
+ latents_ubyte = latents_ubyte.to(dtype=torch.uint8)
18
+ latents_ubyte = latents_ubyte.to(device="cpu", dtype=torch.uint8, non_blocking=comfy.model_management.device_supports_non_blocking(latent_image.device))
19
+
20
+ return Image.fromarray(latents_ubyte.numpy())
21
+
22
+ class LatentPreviewer:
23
+ def decode_latent_to_preview(self, x0):
24
+ pass
25
+
26
+ def decode_latent_to_preview_image(self, preview_format, x0):
27
+ preview_image = self.decode_latent_to_preview(x0)
28
+ return ("JPEG", preview_image, MAX_PREVIEW_RESOLUTION)
29
+
30
+ class TAESDPreviewerImpl(LatentPreviewer):
31
+ def __init__(self, taesd):
32
+ self.taesd = taesd
33
+
34
+ def decode_latent_to_preview(self, x0):
35
+ x_sample = self.taesd.decode(x0[:1])[0].movedim(0, 2)
36
+ return preview_to_image(x_sample)
37
+
38
+
39
+ class Latent2RGBPreviewer(LatentPreviewer):
40
+ def __init__(self, latent_rgb_factors, latent_rgb_factors_bias=None):
41
+ self.latent_rgb_factors = torch.tensor(latent_rgb_factors, device="cpu").transpose(0, 1)
42
+ self.latent_rgb_factors_bias = None
43
+ if latent_rgb_factors_bias is not None:
44
+ self.latent_rgb_factors_bias = torch.tensor(latent_rgb_factors_bias, device="cpu")
45
+
46
+ def decode_latent_to_preview(self, x0):
47
+ self.latent_rgb_factors = self.latent_rgb_factors.to(dtype=x0.dtype, device=x0.device)
48
+ if self.latent_rgb_factors_bias is not None:
49
+ self.latent_rgb_factors_bias = self.latent_rgb_factors_bias.to(dtype=x0.dtype, device=x0.device)
50
+
51
+ if x0.ndim == 5:
52
+ x0 = x0[0, :, 0]
53
+ else:
54
+ x0 = x0[0]
55
+
56
+ latent_image = torch.nn.functional.linear(x0.movedim(0, -1), self.latent_rgb_factors, bias=self.latent_rgb_factors_bias)
57
+ # latent_image = x0[0].permute(1, 2, 0) @ self.latent_rgb_factors
58
+
59
+ return preview_to_image(latent_image)
60
+
61
+
62
+ def get_previewer(device, latent_format):
63
+ previewer = None
64
+ method = args.preview_method
65
+ if method != LatentPreviewMethod.NoPreviews:
66
+ # TODO previewer methods
67
+ taesd_decoder_path = None
68
+ if latent_format.taesd_decoder_name is not None:
69
+ taesd_decoder_path = next(
70
+ (fn for fn in folder_paths.get_filename_list("vae_approx")
71
+ if fn.startswith(latent_format.taesd_decoder_name)),
72
+ ""
73
+ )
74
+ taesd_decoder_path = folder_paths.get_full_path("vae_approx", taesd_decoder_path)
75
+
76
+ if method == LatentPreviewMethod.Auto:
77
+ method = LatentPreviewMethod.Latent2RGB
78
+
79
+ if method == LatentPreviewMethod.TAESD:
80
+ if taesd_decoder_path:
81
+ taesd = TAESD(None, taesd_decoder_path, latent_channels=latent_format.latent_channels).to(device)
82
+ previewer = TAESDPreviewerImpl(taesd)
83
+ else:
84
+ logging.warning("Warning: TAESD previews enabled, but could not find models/vae_approx/{}".format(latent_format.taesd_decoder_name))
85
+
86
+ if previewer is None:
87
+ if latent_format.latent_rgb_factors is not None:
88
+ previewer = Latent2RGBPreviewer(latent_format.latent_rgb_factors, latent_format.latent_rgb_factors_bias)
89
+ return previewer
90
+
91
+ def prepare_callback(model, steps, x0_output_dict=None):
92
+ preview_format = "JPEG"
93
+ if preview_format not in ["JPEG", "PNG"]:
94
+ preview_format = "JPEG"
95
+
96
+ previewer = get_previewer(model.load_device, model.model.latent_format)
97
+
98
+ pbar = comfy.utils.ProgressBar(steps)
99
+ def callback(step, x0, x, total_steps):
100
+ if x0_output_dict is not None:
101
+ x0_output_dict["x0"] = x0
102
+
103
+ preview_bytes = None
104
+ if previewer:
105
+ preview_bytes = previewer.decode_latent_to_preview_image(preview_format, x0)
106
+ pbar.update_absolute(step + 1, total_steps, preview_bytes)
107
+ return callback
108
+
main.py ADDED
@@ -0,0 +1,311 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import comfy.options
2
+ comfy.options.enable_args_parsing()
3
+
4
+ import os
5
+ import importlib.util
6
+ import folder_paths
7
+ import time
8
+ from comfy.cli_args import args
9
+ from app.logger import setup_logger
10
+ import itertools
11
+ import utils.extra_config
12
+ import logging
13
+ import sys
14
+
15
+ if __name__ == "__main__":
16
+ #NOTE: These do not do anything on core ComfyUI, they are for custom nodes.
17
+ os.environ['HF_HUB_DISABLE_TELEMETRY'] = '1'
18
+ os.environ['DO_NOT_TRACK'] = '1'
19
+
20
+
21
+ setup_logger(log_level=args.verbose, use_stdout=args.log_stdout)
22
+
23
+ def apply_custom_paths():
24
+ # extra model paths
25
+ extra_model_paths_config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "extra_model_paths.yaml")
26
+ if os.path.isfile(extra_model_paths_config_path):
27
+ utils.extra_config.load_extra_path_config(extra_model_paths_config_path)
28
+
29
+ if args.extra_model_paths_config:
30
+ for config_path in itertools.chain(*args.extra_model_paths_config):
31
+ utils.extra_config.load_extra_path_config(config_path)
32
+
33
+ # --output-directory, --input-directory, --user-directory
34
+ if args.output_directory:
35
+ output_dir = os.path.abspath(args.output_directory)
36
+ logging.info(f"Setting output directory to: {output_dir}")
37
+ folder_paths.set_output_directory(output_dir)
38
+
39
+ # These are the default folders that checkpoints, clip and vae models will be saved to when using CheckpointSave, etc.. nodes
40
+ folder_paths.add_model_folder_path("checkpoints", os.path.join(folder_paths.get_output_directory(), "checkpoints"))
41
+ folder_paths.add_model_folder_path("clip", os.path.join(folder_paths.get_output_directory(), "clip"))
42
+ folder_paths.add_model_folder_path("vae", os.path.join(folder_paths.get_output_directory(), "vae"))
43
+ folder_paths.add_model_folder_path("diffusion_models",
44
+ os.path.join(folder_paths.get_output_directory(), "diffusion_models"))
45
+ folder_paths.add_model_folder_path("loras", os.path.join(folder_paths.get_output_directory(), "loras"))
46
+
47
+ if args.input_directory:
48
+ input_dir = os.path.abspath(args.input_directory)
49
+ logging.info(f"Setting input directory to: {input_dir}")
50
+ folder_paths.set_input_directory(input_dir)
51
+
52
+ if args.user_directory:
53
+ user_dir = os.path.abspath(args.user_directory)
54
+ logging.info(f"Setting user directory to: {user_dir}")
55
+ folder_paths.set_user_directory(user_dir)
56
+
57
+
58
+ def execute_prestartup_script():
59
+ def execute_script(script_path):
60
+ module_name = os.path.splitext(script_path)[0]
61
+ try:
62
+ spec = importlib.util.spec_from_file_location(module_name, script_path)
63
+ module = importlib.util.module_from_spec(spec)
64
+ spec.loader.exec_module(module)
65
+ return True
66
+ except Exception as e:
67
+ logging.error(f"Failed to execute startup-script: {script_path} / {e}")
68
+ return False
69
+
70
+ if args.disable_all_custom_nodes:
71
+ return
72
+
73
+ node_paths = folder_paths.get_folder_paths("custom_nodes")
74
+ for custom_node_path in node_paths:
75
+ possible_modules = os.listdir(custom_node_path)
76
+ node_prestartup_times = []
77
+
78
+ for possible_module in possible_modules:
79
+ module_path = os.path.join(custom_node_path, possible_module)
80
+ if os.path.isfile(module_path) or module_path.endswith(".disabled") or module_path == "__pycache__":
81
+ continue
82
+
83
+ script_path = os.path.join(module_path, "prestartup_script.py")
84
+ if os.path.exists(script_path):
85
+ time_before = time.perf_counter()
86
+ success = execute_script(script_path)
87
+ node_prestartup_times.append((time.perf_counter() - time_before, module_path, success))
88
+ if len(node_prestartup_times) > 0:
89
+ logging.info("\nPrestartup times for custom nodes:")
90
+ for n in sorted(node_prestartup_times):
91
+ if n[2]:
92
+ import_message = ""
93
+ else:
94
+ import_message = " (PRESTARTUP FAILED)"
95
+ logging.info("{:6.1f} seconds{}: {}".format(n[0], import_message, n[1]))
96
+ logging.info("")
97
+
98
+ apply_custom_paths()
99
+ execute_prestartup_script()
100
+
101
+
102
+ # Main code
103
+ import asyncio
104
+ import shutil
105
+ import threading
106
+ import gc
107
+
108
+
109
+ if os.name == "nt":
110
+ logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
111
+
112
+ if __name__ == "__main__":
113
+ if args.cuda_device is not None:
114
+ os.environ['CUDA_VISIBLE_DEVICES'] = str(args.cuda_device)
115
+ os.environ['HIP_VISIBLE_DEVICES'] = str(args.cuda_device)
116
+ logging.info("Set cuda device to: {}".format(args.cuda_device))
117
+
118
+ if args.oneapi_device_selector is not None:
119
+ os.environ['ONEAPI_DEVICE_SELECTOR'] = args.oneapi_device_selector
120
+ logging.info("Set oneapi device selector to: {}".format(args.oneapi_device_selector))
121
+
122
+ if args.deterministic:
123
+ if 'CUBLAS_WORKSPACE_CONFIG' not in os.environ:
124
+ os.environ['CUBLAS_WORKSPACE_CONFIG'] = ":4096:8"
125
+
126
+ import cuda_malloc
127
+
128
+ import comfy.utils
129
+
130
+ import execution
131
+ import server
132
+ from server import BinaryEventTypes
133
+ import nodes
134
+ import comfy.model_management
135
+ import comfyui_version
136
+ import app.logger
137
+ import hook_breaker_ac10a0
138
+
139
+ def cuda_malloc_warning():
140
+ device = comfy.model_management.get_torch_device()
141
+ device_name = comfy.model_management.get_torch_device_name(device)
142
+ cuda_malloc_warning = False
143
+ if "cudaMallocAsync" in device_name:
144
+ for b in cuda_malloc.blacklist:
145
+ if b in device_name:
146
+ cuda_malloc_warning = True
147
+ if cuda_malloc_warning:
148
+ 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")
149
+
150
+
151
+ def prompt_worker(q, server_instance):
152
+ current_time: float = 0.0
153
+ cache_type = execution.CacheType.CLASSIC
154
+ if args.cache_lru > 0:
155
+ cache_type = execution.CacheType.LRU
156
+ elif args.cache_none:
157
+ cache_type = execution.CacheType.DEPENDENCY_AWARE
158
+
159
+ e = execution.PromptExecutor(server_instance, cache_type=cache_type, cache_size=args.cache_lru)
160
+ last_gc_collect = 0
161
+ need_gc = False
162
+ gc_collect_interval = 10.0
163
+
164
+ while True:
165
+ timeout = 1000.0
166
+ if need_gc:
167
+ timeout = max(gc_collect_interval - (current_time - last_gc_collect), 0.0)
168
+
169
+ queue_item = q.get(timeout=timeout)
170
+ if queue_item is not None:
171
+ item, item_id = queue_item
172
+ execution_start_time = time.perf_counter()
173
+ prompt_id = item[1]
174
+ server_instance.last_prompt_id = prompt_id
175
+
176
+ e.execute(item[2], prompt_id, item[3], item[4])
177
+ need_gc = True
178
+ q.task_done(item_id,
179
+ e.history_result,
180
+ status=execution.PromptQueue.ExecutionStatus(
181
+ status_str='success' if e.success else 'error',
182
+ completed=e.success,
183
+ messages=e.status_messages))
184
+ if server_instance.client_id is not None:
185
+ server_instance.send_sync("executing", {"node": None, "prompt_id": prompt_id}, server_instance.client_id)
186
+
187
+ current_time = time.perf_counter()
188
+ execution_time = current_time - execution_start_time
189
+ logging.info("Prompt executed in {:.2f} seconds".format(execution_time))
190
+
191
+ flags = q.get_flags()
192
+ free_memory = flags.get("free_memory", False)
193
+
194
+ if flags.get("unload_models", free_memory):
195
+ comfy.model_management.unload_all_models()
196
+ need_gc = True
197
+ last_gc_collect = 0
198
+
199
+ if free_memory:
200
+ e.reset()
201
+ need_gc = True
202
+ last_gc_collect = 0
203
+
204
+ if need_gc:
205
+ current_time = time.perf_counter()
206
+ if (current_time - last_gc_collect) > gc_collect_interval:
207
+ gc.collect()
208
+ comfy.model_management.soft_empty_cache()
209
+ last_gc_collect = current_time
210
+ need_gc = False
211
+ hook_breaker_ac10a0.restore_functions()
212
+
213
+
214
+ async def run(server_instance, address='', port=8188, verbose=True, call_on_start=None):
215
+ addresses = []
216
+ for addr in address.split(","):
217
+ addresses.append((addr, port))
218
+ await asyncio.gather(
219
+ server_instance.start_multi_address(addresses, call_on_start, verbose), server_instance.publish_loop()
220
+ )
221
+
222
+
223
+ def hijack_progress(server_instance):
224
+ def hook(value, total, preview_image):
225
+ comfy.model_management.throw_exception_if_processing_interrupted()
226
+ progress = {"value": value, "max": total, "prompt_id": server_instance.last_prompt_id, "node": server_instance.last_node_id}
227
+
228
+ server_instance.send_sync("progress", progress, server_instance.client_id)
229
+ if preview_image is not None:
230
+ server_instance.send_sync(BinaryEventTypes.UNENCODED_PREVIEW_IMAGE, preview_image, server_instance.client_id)
231
+
232
+ comfy.utils.set_progress_bar_global_hook(hook)
233
+
234
+
235
+ def cleanup_temp():
236
+ temp_dir = folder_paths.get_temp_directory()
237
+ if os.path.exists(temp_dir):
238
+ shutil.rmtree(temp_dir, ignore_errors=True)
239
+
240
+
241
+ def start_comfyui(asyncio_loop=None):
242
+ """
243
+ Starts the ComfyUI server using the provided asyncio event loop or creates a new one.
244
+ Returns the event loop, server instance, and a function to start the server asynchronously.
245
+ """
246
+ if args.temp_directory:
247
+ temp_dir = os.path.join(os.path.abspath(args.temp_directory), "temp")
248
+ logging.info(f"Setting temp directory to: {temp_dir}")
249
+ folder_paths.set_temp_directory(temp_dir)
250
+ cleanup_temp()
251
+
252
+ if args.windows_standalone_build:
253
+ try:
254
+ import new_updater
255
+ new_updater.update_windows_updater()
256
+ except:
257
+ pass
258
+
259
+ if not asyncio_loop:
260
+ asyncio_loop = asyncio.new_event_loop()
261
+ asyncio.set_event_loop(asyncio_loop)
262
+ prompt_server = server.PromptServer(asyncio_loop)
263
+
264
+ hook_breaker_ac10a0.save_functions()
265
+ nodes.init_extra_nodes(init_custom_nodes=not args.disable_all_custom_nodes, init_api_nodes=not args.disable_api_nodes)
266
+ hook_breaker_ac10a0.restore_functions()
267
+
268
+ cuda_malloc_warning()
269
+
270
+ prompt_server.add_routes()
271
+ hijack_progress(prompt_server)
272
+
273
+ threading.Thread(target=prompt_worker, daemon=True, args=(prompt_server.prompt_queue, prompt_server,)).start()
274
+
275
+ if args.quick_test_for_ci:
276
+ exit(0)
277
+
278
+ os.makedirs(folder_paths.get_temp_directory(), exist_ok=True)
279
+ call_on_start = None
280
+ if args.auto_launch:
281
+ def startup_server(scheme, address, port):
282
+ import webbrowser
283
+ if os.name == 'nt' and address == '0.0.0.0':
284
+ address = '127.0.0.1'
285
+ if ':' in address:
286
+ address = "[{}]".format(address)
287
+ webbrowser.open(f"{scheme}://{address}:{port}")
288
+ call_on_start = startup_server
289
+
290
+ async def start_all():
291
+ await prompt_server.setup()
292
+ await run(prompt_server, address=args.listen, port=args.port, verbose=not args.dont_print_server, call_on_start=call_on_start)
293
+
294
+ # Returning these so that other code can integrate with the ComfyUI loop and server
295
+ return asyncio_loop, prompt_server, start_all
296
+
297
+
298
+ if __name__ == "__main__":
299
+ # Running directly, just start ComfyUI.
300
+ logging.info("Python version: {}".format(sys.version))
301
+ logging.info("ComfyUI version: {}".format(comfyui_version.__version__))
302
+
303
+ event_loop, _, start_all_func = start_comfyui()
304
+ try:
305
+ x = start_all_func()
306
+ app.logger.print_startup_warnings()
307
+ event_loop.run_until_complete(x)
308
+ except KeyboardInterrupt:
309
+ logging.info("\nStopped server")
310
+
311
+ cleanup_temp()
my_workflow.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import random
3
+ import sys
4
+ from typing import Sequence, Mapping, Any, Union
5
+ import torch
6
+
7
+
8
+ def get_value_at_index(obj: Union[Sequence, Mapping], index: int) -> Any:
9
+ """Returns the value at the given index of a sequence or mapping.
10
+
11
+ If the object is a sequence (like list or string), returns the value at the given index.
12
+ If the object is a mapping (like a dictionary), returns the value at the index-th key.
13
+
14
+ Some return a dictionary, in these cases, we look for the "results" key
15
+
16
+ Args:
17
+ obj (Union[Sequence, Mapping]): The object to retrieve the value from.
18
+ index (int): The index of the value to retrieve.
19
+
20
+ Returns:
21
+ Any: The value at the given index.
22
+
23
+ Raises:
24
+ IndexError: If the index is out of bounds for the object and the object is not a mapping.
25
+ """
26
+ try:
27
+ return obj[index]
28
+ except KeyError:
29
+ return obj["result"][index]
30
+
31
+
32
+ def find_path(name: str, path: str = None) -> str:
33
+ """
34
+ Recursively looks at parent folders starting from the given path until it finds the given name.
35
+ Returns the path as a Path object if found, or None otherwise.
36
+ """
37
+ # If no path is given, use the current working directory
38
+ if path is None:
39
+ path = os.getcwd()
40
+
41
+ # Check if the current directory contains the name
42
+ if name in os.listdir(path):
43
+ path_name = os.path.join(path, name)
44
+ print(f"{name} found: {path_name}")
45
+ return path_name
46
+
47
+ # Get the parent directory
48
+ parent_directory = os.path.dirname(path)
49
+
50
+ # If the parent directory is the same as the current directory, we've reached the root and stop the search
51
+ if parent_directory == path:
52
+ return None
53
+
54
+ # Recursively call the function with the parent directory
55
+ return find_path(name, parent_directory)
56
+
57
+
58
+ def add_comfyui_directory_to_sys_path() -> None:
59
+ """
60
+ Add 'ComfyUI' to the sys.path
61
+ """
62
+ comfyui_path = find_path("ComfyUI")
63
+ if comfyui_path is not None and os.path.isdir(comfyui_path):
64
+ sys.path.append(comfyui_path)
65
+ print(f"'{comfyui_path}' added to sys.path")
66
+
67
+
68
+ def add_extra_model_paths() -> None:
69
+ """
70
+ Parse the optional extra_model_paths.yaml file and add the parsed paths to the sys.path.
71
+ """
72
+ try:
73
+ from main import load_extra_path_config
74
+ except ImportError:
75
+ print(
76
+ "Could not import load_extra_path_config from main.py. Looking in utils.extra_config instead."
77
+ )
78
+ from utils.extra_config import load_extra_path_config
79
+
80
+ extra_model_paths = find_path("extra_model_paths.yaml")
81
+
82
+ if extra_model_paths is not None:
83
+ load_extra_path_config(extra_model_paths)
84
+ else:
85
+ print("Could not find the extra_model_paths config file.")
86
+
87
+
88
+ add_comfyui_directory_to_sys_path()
89
+ add_extra_model_paths()
90
+
91
+
92
+ def import_custom_nodes() -> None:
93
+ """Find all custom nodes in the custom_nodes folder and add those node objects to NODE_CLASS_MAPPINGS
94
+
95
+ This function sets up a new asyncio event loop, initializes the PromptServer,
96
+ creates a PromptQueue, and initializes the custom nodes.
97
+ """
98
+ import asyncio
99
+ import execution
100
+ from nodes import init_extra_nodes
101
+ from main import apply_custom_paths, execute_prestartup_script
102
+
103
+ # Creating a new event loop and setting it as the default loop
104
+ loop = asyncio.new_event_loop()
105
+ asyncio.set_event_loop(loop)
106
+
107
+ # Creating an instance of PromptServer with the loop
108
+ server_instance = server.PromptServer(loop)
109
+ execution.PromptQueue(server_instance)
110
+
111
+ # Initializing custom nodes
112
+ init_extra_nodes()
113
+
114
+ apply_custom_paths()
115
+ execute_prestartup_script()
116
+
117
+
118
+ from nodes import (
119
+ CLIPTextEncode,
120
+ NODE_CLASS_MAPPINGS,
121
+ CLIPLoader,
122
+ VAEDecode,
123
+ UNETLoader,
124
+ VAELoader,
125
+ SaveImage,
126
+ )
127
+
128
+
129
+ def main():
130
+ import_custom_nodes()
131
+ with torch.inference_mode():
132
+ randomnoise = NODE_CLASS_MAPPINGS["RandomNoise"]()
133
+ randomnoise_68 = randomnoise.get_noise(noise_seed=random.randint(1, 2**64))
134
+
135
+ emptysd3latentimage = NODE_CLASS_MAPPINGS["EmptySD3LatentImage"]()
136
+ emptysd3latentimage_69 = emptysd3latentimage.generate(
137
+ width=1024, height=1024, batch_size=1
138
+ )
139
+
140
+ ksamplerselect = NODE_CLASS_MAPPINGS["KSamplerSelect"]()
141
+ ksamplerselect_72 = ksamplerselect.get_sampler(sampler_name="euler")
142
+
143
+ cliploader = CLIPLoader()
144
+ cliploader_78 = cliploader.load_clip(
145
+ clip_name="t5xxl_fp8_e4m3fn.safetensors", type="chroma", device="default"
146
+ )
147
+
148
+ t5tokenizeroptions = NODE_CLASS_MAPPINGS["T5TokenizerOptions"]()
149
+ t5tokenizeroptions_82 = t5tokenizeroptions.set_options(
150
+ min_padding=1, min_length=0, clip=get_value_at_index(cliploader_78, 0)
151
+ )
152
+
153
+ cliptextencode = CLIPTextEncode()
154
+ cliptextencode_74 = cliptextencode.encode(
155
+ text="Extreme close-up photograph of a single tiger eye, direct frontal view. The iris is very detailed and the pupil resembling a dark void. The word 'Chroma' is across the lower portion of the image in large white stylized letters, with brush strokes resembling those made with Japanese calligraphy. Each strand of the thick fur is highly detailed and distinguishable. Natural lighting to capture authentic eye shine and depth.",
156
+ clip=get_value_at_index(t5tokenizeroptions_82, 0),
157
+ )
158
+
159
+ cliptextencode_75 = cliptextencode.encode(
160
+ text="low quality, ugly, unfinished, out of focus, deformed, disfigure, blurry, smudged, restricted palette, flat colors",
161
+ clip=get_value_at_index(t5tokenizeroptions_82, 0),
162
+ )
163
+
164
+ unetloader = UNETLoader()
165
+ unetloader_76 = unetloader.load_unet(
166
+ unet_name="chroma-unlocked-v31.safetensors", weight_dtype="fp8_e4m3fn"
167
+ )
168
+
169
+ vaeloader = VAELoader()
170
+ vaeloader_80 = vaeloader.load_vae(vae_name="ae.safetensors")
171
+
172
+ cfgguider = NODE_CLASS_MAPPINGS["CFGGuider"]()
173
+ basicscheduler = NODE_CLASS_MAPPINGS["BasicScheduler"]()
174
+ samplercustomadvanced = NODE_CLASS_MAPPINGS["SamplerCustomAdvanced"]()
175
+ vaedecode = VAEDecode()
176
+ saveimage = SaveImage()
177
+
178
+ for q in range(1):
179
+ cfgguider_73 = cfgguider.get_guider(
180
+ cfg=4,
181
+ model=get_value_at_index(unetloader_76, 0),
182
+ positive=get_value_at_index(cliptextencode_74, 0),
183
+ negative=get_value_at_index(cliptextencode_75, 0),
184
+ )
185
+
186
+ basicscheduler_84 = basicscheduler.get_sigmas(
187
+ scheduler="beta",
188
+ steps=26,
189
+ denoise=1,
190
+ model=get_value_at_index(unetloader_76, 0),
191
+ )
192
+
193
+ samplercustomadvanced_67 = samplercustomadvanced.sample(
194
+ noise=get_value_at_index(randomnoise_68, 0),
195
+ guider=get_value_at_index(cfgguider_73, 0),
196
+ sampler=get_value_at_index(ksamplerselect_72, 0),
197
+ sigmas=get_value_at_index(basicscheduler_84, 0),
198
+ latent_image=get_value_at_index(emptysd3latentimage_69, 0),
199
+ )
200
+
201
+ vaedecode_79 = vaedecode.decode(
202
+ samples=get_value_at_index(samplercustomadvanced_67, 0),
203
+ vae=get_value_at_index(vaeloader_80, 0),
204
+ )
205
+
206
+ saveimage_81 = saveimage.save_images(
207
+ filename_prefix="2025-05-24/ComfyUI",
208
+ images=get_value_at_index(vaedecode_79, 0),
209
+ )
210
+
211
+
212
+ if __name__ == "__main__":
213
+ main()
new_updater.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+
4
+ base_path = os.path.dirname(os.path.realpath(__file__))
5
+
6
+
7
+ def update_windows_updater():
8
+ top_path = os.path.dirname(base_path)
9
+ updater_path = os.path.join(base_path, ".ci/update_windows/update.py")
10
+ bat_path = os.path.join(base_path, ".ci/update_windows/update_comfyui.bat")
11
+
12
+ dest_updater_path = os.path.join(top_path, "update/update.py")
13
+ dest_bat_path = os.path.join(top_path, "update/update_comfyui.bat")
14
+ dest_bat_deps_path = os.path.join(top_path, "update/update_comfyui_and_python_dependencies.bat")
15
+
16
+ try:
17
+ with open(dest_bat_path, 'rb') as f:
18
+ contents = f.read()
19
+ except:
20
+ return
21
+
22
+ if not contents.startswith(b"..\\python_embeded\\python.exe .\\update.py"):
23
+ return
24
+
25
+ shutil.copy(updater_path, dest_updater_path)
26
+ try:
27
+ with open(dest_bat_deps_path, 'rb') as f:
28
+ contents = f.read()
29
+ contents = contents.replace(b'..\\python_embeded\\python.exe .\\update.py ..\\ComfyUI\\', b'call update_comfyui.bat nopause')
30
+ with open(dest_bat_deps_path, 'wb') as f:
31
+ f.write(contents)
32
+ except:
33
+ pass
34
+ shutil.copy(bat_path, dest_bat_path)
35
+ print("Updated the windows standalone package updater.") # noqa: T201
node_helpers.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import hashlib
2
+ import torch
3
+
4
+ from comfy.cli_args import args
5
+
6
+ from PIL import ImageFile, UnidentifiedImageError
7
+
8
+ def conditioning_set_values(conditioning, values={}, append=False):
9
+ c = []
10
+ for t in conditioning:
11
+ n = [t[0], t[1].copy()]
12
+ for k in values:
13
+ val = values[k]
14
+ if append:
15
+ old_val = n[1].get(k, None)
16
+ if old_val is not None:
17
+ val = old_val + val
18
+
19
+ n[1][k] = val
20
+ c.append(n)
21
+
22
+ return c
23
+
24
+ def pillow(fn, arg):
25
+ prev_value = None
26
+ try:
27
+ x = fn(arg)
28
+ except (OSError, UnidentifiedImageError, ValueError): #PIL issues #4472 and #2445, also fixes ComfyUI issue #3416
29
+ prev_value = ImageFile.LOAD_TRUNCATED_IMAGES
30
+ ImageFile.LOAD_TRUNCATED_IMAGES = True
31
+ x = fn(arg)
32
+ finally:
33
+ if prev_value is not None:
34
+ ImageFile.LOAD_TRUNCATED_IMAGES = prev_value
35
+ return x
36
+
37
+ def hasher():
38
+ hashfuncs = {
39
+ "md5": hashlib.md5,
40
+ "sha1": hashlib.sha1,
41
+ "sha256": hashlib.sha256,
42
+ "sha512": hashlib.sha512
43
+ }
44
+ return hashfuncs[args.default_hashing_function]
45
+
46
+ def string_to_torch_dtype(string):
47
+ if string == "fp32":
48
+ return torch.float32
49
+ if string == "fp16":
50
+ return torch.float16
51
+ if string == "bf16":
52
+ return torch.bfloat16
53
+
54
+ def image_alpha_fix(destination, source):
55
+ if destination.shape[-1] < source.shape[-1]:
56
+ source = source[...,:destination.shape[-1]]
57
+ elif destination.shape[-1] > source.shape[-1]:
58
+ destination = torch.nn.functional.pad(destination, (0, 1))
59
+ destination[..., -1] = 1.0
60
+ return destination, source
nodes.py ADDED
@@ -0,0 +1,2331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import torch
3
+
4
+ import os
5
+ import sys
6
+ import json
7
+ import hashlib
8
+ import traceback
9
+ import math
10
+ import time
11
+ import random
12
+ import logging
13
+
14
+ from PIL import Image, ImageOps, ImageSequence
15
+ from PIL.PngImagePlugin import PngInfo
16
+
17
+ import numpy as np
18
+ import safetensors.torch
19
+
20
+ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy"))
21
+
22
+ import comfy.diffusers_load
23
+ import comfy.samplers
24
+ import comfy.sample
25
+ import comfy.sd
26
+ import comfy.utils
27
+ import comfy.controlnet
28
+ from comfy.comfy_types import IO, ComfyNodeABC, InputTypeDict, FileLocator
29
+
30
+ import comfy.clip_vision
31
+
32
+ import comfy.model_management
33
+ from comfy.cli_args import args
34
+
35
+ import importlib
36
+
37
+ import folder_paths
38
+ import latent_preview
39
+ import node_helpers
40
+
41
+ def before_node_execution():
42
+ comfy.model_management.throw_exception_if_processing_interrupted()
43
+
44
+ def interrupt_processing(value=True):
45
+ comfy.model_management.interrupt_current_processing(value)
46
+
47
+ MAX_RESOLUTION=16384
48
+
49
+ class CLIPTextEncode(ComfyNodeABC):
50
+ @classmethod
51
+ def INPUT_TYPES(s) -> InputTypeDict:
52
+ return {
53
+ "required": {
54
+ "text": (IO.STRING, {"multiline": True, "dynamicPrompts": True, "tooltip": "The text to be encoded."}),
55
+ "clip": (IO.CLIP, {"tooltip": "The CLIP model used for encoding the text."})
56
+ }
57
+ }
58
+ RETURN_TYPES = (IO.CONDITIONING,)
59
+ OUTPUT_TOOLTIPS = ("A conditioning containing the embedded text used to guide the diffusion model.",)
60
+ FUNCTION = "encode"
61
+
62
+ CATEGORY = "conditioning"
63
+ 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."
64
+
65
+ def encode(self, clip, text):
66
+ if clip is None:
67
+ raise RuntimeError("ERROR: clip input is invalid: None\n\nIf the clip is from a checkpoint loader node your checkpoint does not contain a valid clip or text encoder model.")
68
+ tokens = clip.tokenize(text)
69
+ return (clip.encode_from_tokens_scheduled(tokens), )
70
+
71
+
72
+ class ConditioningCombine:
73
+ @classmethod
74
+ def INPUT_TYPES(s):
75
+ return {"required": {"conditioning_1": ("CONDITIONING", ), "conditioning_2": ("CONDITIONING", )}}
76
+ RETURN_TYPES = ("CONDITIONING",)
77
+ FUNCTION = "combine"
78
+
79
+ CATEGORY = "conditioning"
80
+
81
+ def combine(self, conditioning_1, conditioning_2):
82
+ return (conditioning_1 + conditioning_2, )
83
+
84
+ class ConditioningAverage :
85
+ @classmethod
86
+ def INPUT_TYPES(s):
87
+ return {"required": {"conditioning_to": ("CONDITIONING", ), "conditioning_from": ("CONDITIONING", ),
88
+ "conditioning_to_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01})
89
+ }}
90
+ RETURN_TYPES = ("CONDITIONING",)
91
+ FUNCTION = "addWeighted"
92
+
93
+ CATEGORY = "conditioning"
94
+
95
+ def addWeighted(self, conditioning_to, conditioning_from, conditioning_to_strength):
96
+ out = []
97
+
98
+ if len(conditioning_from) > 1:
99
+ logging.warning("Warning: ConditioningAverage conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.")
100
+
101
+ cond_from = conditioning_from[0][0]
102
+ pooled_output_from = conditioning_from[0][1].get("pooled_output", None)
103
+
104
+ for i in range(len(conditioning_to)):
105
+ t1 = conditioning_to[i][0]
106
+ pooled_output_to = conditioning_to[i][1].get("pooled_output", pooled_output_from)
107
+ t0 = cond_from[:,:t1.shape[1]]
108
+ if t0.shape[1] < t1.shape[1]:
109
+ t0 = torch.cat([t0] + [torch.zeros((1, (t1.shape[1] - t0.shape[1]), t1.shape[2]))], dim=1)
110
+
111
+ tw = torch.mul(t1, conditioning_to_strength) + torch.mul(t0, (1.0 - conditioning_to_strength))
112
+ t_to = conditioning_to[i][1].copy()
113
+ if pooled_output_from is not None and pooled_output_to is not None:
114
+ t_to["pooled_output"] = torch.mul(pooled_output_to, conditioning_to_strength) + torch.mul(pooled_output_from, (1.0 - conditioning_to_strength))
115
+ elif pooled_output_from is not None:
116
+ t_to["pooled_output"] = pooled_output_from
117
+
118
+ n = [tw, t_to]
119
+ out.append(n)
120
+ return (out, )
121
+
122
+ class ConditioningConcat:
123
+ @classmethod
124
+ def INPUT_TYPES(s):
125
+ return {"required": {
126
+ "conditioning_to": ("CONDITIONING",),
127
+ "conditioning_from": ("CONDITIONING",),
128
+ }}
129
+ RETURN_TYPES = ("CONDITIONING",)
130
+ FUNCTION = "concat"
131
+
132
+ CATEGORY = "conditioning"
133
+
134
+ def concat(self, conditioning_to, conditioning_from):
135
+ out = []
136
+
137
+ if len(conditioning_from) > 1:
138
+ logging.warning("Warning: ConditioningConcat conditioning_from contains more than 1 cond, only the first one will actually be applied to conditioning_to.")
139
+
140
+ cond_from = conditioning_from[0][0]
141
+
142
+ for i in range(len(conditioning_to)):
143
+ t1 = conditioning_to[i][0]
144
+ tw = torch.cat((t1, cond_from),1)
145
+ n = [tw, conditioning_to[i][1].copy()]
146
+ out.append(n)
147
+
148
+ return (out, )
149
+
150
+ class ConditioningSetArea:
151
+ @classmethod
152
+ def INPUT_TYPES(s):
153
+ return {"required": {"conditioning": ("CONDITIONING", ),
154
+ "width": ("INT", {"default": 64, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
155
+ "height": ("INT", {"default": 64, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
156
+ "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
157
+ "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
158
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
159
+ }}
160
+ RETURN_TYPES = ("CONDITIONING",)
161
+ FUNCTION = "append"
162
+
163
+ CATEGORY = "conditioning"
164
+
165
+ def append(self, conditioning, width, height, x, y, strength):
166
+ c = node_helpers.conditioning_set_values(conditioning, {"area": (height // 8, width // 8, y // 8, x // 8),
167
+ "strength": strength,
168
+ "set_area_to_bounds": False})
169
+ return (c, )
170
+
171
+ class ConditioningSetAreaPercentage:
172
+ @classmethod
173
+ def INPUT_TYPES(s):
174
+ return {"required": {"conditioning": ("CONDITIONING", ),
175
+ "width": ("FLOAT", {"default": 1.0, "min": 0, "max": 1.0, "step": 0.01}),
176
+ "height": ("FLOAT", {"default": 1.0, "min": 0, "max": 1.0, "step": 0.01}),
177
+ "x": ("FLOAT", {"default": 0, "min": 0, "max": 1.0, "step": 0.01}),
178
+ "y": ("FLOAT", {"default": 0, "min": 0, "max": 1.0, "step": 0.01}),
179
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
180
+ }}
181
+ RETURN_TYPES = ("CONDITIONING",)
182
+ FUNCTION = "append"
183
+
184
+ CATEGORY = "conditioning"
185
+
186
+ def append(self, conditioning, width, height, x, y, strength):
187
+ c = node_helpers.conditioning_set_values(conditioning, {"area": ("percentage", height, width, y, x),
188
+ "strength": strength,
189
+ "set_area_to_bounds": False})
190
+ return (c, )
191
+
192
+ class ConditioningSetAreaStrength:
193
+ @classmethod
194
+ def INPUT_TYPES(s):
195
+ return {"required": {"conditioning": ("CONDITIONING", ),
196
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
197
+ }}
198
+ RETURN_TYPES = ("CONDITIONING",)
199
+ FUNCTION = "append"
200
+
201
+ CATEGORY = "conditioning"
202
+
203
+ def append(self, conditioning, strength):
204
+ c = node_helpers.conditioning_set_values(conditioning, {"strength": strength})
205
+ return (c, )
206
+
207
+
208
+ class ConditioningSetMask:
209
+ @classmethod
210
+ def INPUT_TYPES(s):
211
+ return {"required": {"conditioning": ("CONDITIONING", ),
212
+ "mask": ("MASK", ),
213
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
214
+ "set_cond_area": (["default", "mask bounds"],),
215
+ }}
216
+ RETURN_TYPES = ("CONDITIONING",)
217
+ FUNCTION = "append"
218
+
219
+ CATEGORY = "conditioning"
220
+
221
+ def append(self, conditioning, mask, set_cond_area, strength):
222
+ set_area_to_bounds = False
223
+ if set_cond_area != "default":
224
+ set_area_to_bounds = True
225
+ if len(mask.shape) < 3:
226
+ mask = mask.unsqueeze(0)
227
+
228
+ c = node_helpers.conditioning_set_values(conditioning, {"mask": mask,
229
+ "set_area_to_bounds": set_area_to_bounds,
230
+ "mask_strength": strength})
231
+ return (c, )
232
+
233
+ class ConditioningZeroOut:
234
+ @classmethod
235
+ def INPUT_TYPES(s):
236
+ return {"required": {"conditioning": ("CONDITIONING", )}}
237
+ RETURN_TYPES = ("CONDITIONING",)
238
+ FUNCTION = "zero_out"
239
+
240
+ CATEGORY = "advanced/conditioning"
241
+
242
+ def zero_out(self, conditioning):
243
+ c = []
244
+ for t in conditioning:
245
+ d = t[1].copy()
246
+ pooled_output = d.get("pooled_output", None)
247
+ if pooled_output is not None:
248
+ d["pooled_output"] = torch.zeros_like(pooled_output)
249
+ conditioning_lyrics = d.get("conditioning_lyrics", None)
250
+ if conditioning_lyrics is not None:
251
+ d["conditioning_lyrics"] = torch.zeros_like(conditioning_lyrics)
252
+ n = [torch.zeros_like(t[0]), d]
253
+ c.append(n)
254
+ return (c, )
255
+
256
+ class ConditioningSetTimestepRange:
257
+ @classmethod
258
+ def INPUT_TYPES(s):
259
+ return {"required": {"conditioning": ("CONDITIONING", ),
260
+ "start": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
261
+ "end": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
262
+ }}
263
+ RETURN_TYPES = ("CONDITIONING",)
264
+ FUNCTION = "set_range"
265
+
266
+ CATEGORY = "advanced/conditioning"
267
+
268
+ def set_range(self, conditioning, start, end):
269
+ c = node_helpers.conditioning_set_values(conditioning, {"start_percent": start,
270
+ "end_percent": end})
271
+ return (c, )
272
+
273
+ class VAEDecode:
274
+ @classmethod
275
+ def INPUT_TYPES(s):
276
+ return {
277
+ "required": {
278
+ "samples": ("LATENT", {"tooltip": "The latent to be decoded."}),
279
+ "vae": ("VAE", {"tooltip": "The VAE model used for decoding the latent."})
280
+ }
281
+ }
282
+ RETURN_TYPES = ("IMAGE",)
283
+ OUTPUT_TOOLTIPS = ("The decoded image.",)
284
+ FUNCTION = "decode"
285
+
286
+ CATEGORY = "latent"
287
+ DESCRIPTION = "Decodes latent images back into pixel space images."
288
+
289
+ def decode(self, vae, samples):
290
+ images = vae.decode(samples["samples"])
291
+ if len(images.shape) == 5: #Combine batches
292
+ images = images.reshape(-1, images.shape[-3], images.shape[-2], images.shape[-1])
293
+ return (images, )
294
+
295
+ class VAEDecodeTiled:
296
+ @classmethod
297
+ def INPUT_TYPES(s):
298
+ return {"required": {"samples": ("LATENT", ), "vae": ("VAE", ),
299
+ "tile_size": ("INT", {"default": 512, "min": 64, "max": 4096, "step": 32}),
300
+ "overlap": ("INT", {"default": 64, "min": 0, "max": 4096, "step": 32}),
301
+ "temporal_size": ("INT", {"default": 64, "min": 8, "max": 4096, "step": 4, "tooltip": "Only used for video VAEs: Amount of frames to decode at a time."}),
302
+ "temporal_overlap": ("INT", {"default": 8, "min": 4, "max": 4096, "step": 4, "tooltip": "Only used for video VAEs: Amount of frames to overlap."}),
303
+ }}
304
+ RETURN_TYPES = ("IMAGE",)
305
+ FUNCTION = "decode"
306
+
307
+ CATEGORY = "_for_testing"
308
+
309
+ def decode(self, vae, samples, tile_size, overlap=64, temporal_size=64, temporal_overlap=8):
310
+ if tile_size < overlap * 4:
311
+ overlap = tile_size // 4
312
+ if temporal_size < temporal_overlap * 2:
313
+ temporal_overlap = temporal_overlap // 2
314
+ temporal_compression = vae.temporal_compression_decode()
315
+ if temporal_compression is not None:
316
+ temporal_size = max(2, temporal_size // temporal_compression)
317
+ temporal_overlap = max(1, min(temporal_size // 2, temporal_overlap // temporal_compression))
318
+ else:
319
+ temporal_size = None
320
+ temporal_overlap = None
321
+
322
+ compression = vae.spacial_compression_decode()
323
+ images = vae.decode_tiled(samples["samples"], tile_x=tile_size // compression, tile_y=tile_size // compression, overlap=overlap // compression, tile_t=temporal_size, overlap_t=temporal_overlap)
324
+ if len(images.shape) == 5: #Combine batches
325
+ images = images.reshape(-1, images.shape[-3], images.shape[-2], images.shape[-1])
326
+ return (images, )
327
+
328
+ class VAEEncode:
329
+ @classmethod
330
+ def INPUT_TYPES(s):
331
+ return {"required": { "pixels": ("IMAGE", ), "vae": ("VAE", )}}
332
+ RETURN_TYPES = ("LATENT",)
333
+ FUNCTION = "encode"
334
+
335
+ CATEGORY = "latent"
336
+
337
+ def encode(self, vae, pixels):
338
+ t = vae.encode(pixels[:,:,:,:3])
339
+ return ({"samples":t}, )
340
+
341
+ class VAEEncodeTiled:
342
+ @classmethod
343
+ def INPUT_TYPES(s):
344
+ return {"required": {"pixels": ("IMAGE", ), "vae": ("VAE", ),
345
+ "tile_size": ("INT", {"default": 512, "min": 64, "max": 4096, "step": 64}),
346
+ "overlap": ("INT", {"default": 64, "min": 0, "max": 4096, "step": 32}),
347
+ "temporal_size": ("INT", {"default": 64, "min": 8, "max": 4096, "step": 4, "tooltip": "Only used for video VAEs: Amount of frames to encode at a time."}),
348
+ "temporal_overlap": ("INT", {"default": 8, "min": 4, "max": 4096, "step": 4, "tooltip": "Only used for video VAEs: Amount of frames to overlap."}),
349
+ }}
350
+ RETURN_TYPES = ("LATENT",)
351
+ FUNCTION = "encode"
352
+
353
+ CATEGORY = "_for_testing"
354
+
355
+ def encode(self, vae, pixels, tile_size, overlap, temporal_size=64, temporal_overlap=8):
356
+ t = vae.encode_tiled(pixels[:,:,:,:3], tile_x=tile_size, tile_y=tile_size, overlap=overlap, tile_t=temporal_size, overlap_t=temporal_overlap)
357
+ return ({"samples": t}, )
358
+
359
+ class VAEEncodeForInpaint:
360
+ @classmethod
361
+ def INPUT_TYPES(s):
362
+ return {"required": { "pixels": ("IMAGE", ), "vae": ("VAE", ), "mask": ("MASK", ), "grow_mask_by": ("INT", {"default": 6, "min": 0, "max": 64, "step": 1}),}}
363
+ RETURN_TYPES = ("LATENT",)
364
+ FUNCTION = "encode"
365
+
366
+ CATEGORY = "latent/inpaint"
367
+
368
+ def encode(self, vae, pixels, mask, grow_mask_by=6):
369
+ x = (pixels.shape[1] // vae.downscale_ratio) * vae.downscale_ratio
370
+ y = (pixels.shape[2] // vae.downscale_ratio) * vae.downscale_ratio
371
+ mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(pixels.shape[1], pixels.shape[2]), mode="bilinear")
372
+
373
+ pixels = pixels.clone()
374
+ if pixels.shape[1] != x or pixels.shape[2] != y:
375
+ x_offset = (pixels.shape[1] % vae.downscale_ratio) // 2
376
+ y_offset = (pixels.shape[2] % vae.downscale_ratio) // 2
377
+ pixels = pixels[:,x_offset:x + x_offset, y_offset:y + y_offset,:]
378
+ mask = mask[:,:,x_offset:x + x_offset, y_offset:y + y_offset]
379
+
380
+ #grow mask by a few pixels to keep things seamless in latent space
381
+ if grow_mask_by == 0:
382
+ mask_erosion = mask
383
+ else:
384
+ kernel_tensor = torch.ones((1, 1, grow_mask_by, grow_mask_by))
385
+ padding = math.ceil((grow_mask_by - 1) / 2)
386
+
387
+ mask_erosion = torch.clamp(torch.nn.functional.conv2d(mask.round(), kernel_tensor, padding=padding), 0, 1)
388
+
389
+ m = (1.0 - mask.round()).squeeze(1)
390
+ for i in range(3):
391
+ pixels[:,:,:,i] -= 0.5
392
+ pixels[:,:,:,i] *= m
393
+ pixels[:,:,:,i] += 0.5
394
+ t = vae.encode(pixels)
395
+
396
+ return ({"samples":t, "noise_mask": (mask_erosion[:,:,:x,:y].round())}, )
397
+
398
+
399
+ class InpaintModelConditioning:
400
+ @classmethod
401
+ def INPUT_TYPES(s):
402
+ return {"required": {"positive": ("CONDITIONING", ),
403
+ "negative": ("CONDITIONING", ),
404
+ "vae": ("VAE", ),
405
+ "pixels": ("IMAGE", ),
406
+ "mask": ("MASK", ),
407
+ "noise_mask": ("BOOLEAN", {"default": True, "tooltip": "Add a noise mask to the latent so sampling will only happen within the mask. Might improve results or completely break things depending on the model."}),
408
+ }}
409
+
410
+ RETURN_TYPES = ("CONDITIONING","CONDITIONING","LATENT")
411
+ RETURN_NAMES = ("positive", "negative", "latent")
412
+ FUNCTION = "encode"
413
+
414
+ CATEGORY = "conditioning/inpaint"
415
+
416
+ def encode(self, positive, negative, pixels, vae, mask, noise_mask=True):
417
+ x = (pixels.shape[1] // 8) * 8
418
+ y = (pixels.shape[2] // 8) * 8
419
+ mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(pixels.shape[1], pixels.shape[2]), mode="bilinear")
420
+
421
+ orig_pixels = pixels
422
+ pixels = orig_pixels.clone()
423
+ if pixels.shape[1] != x or pixels.shape[2] != y:
424
+ x_offset = (pixels.shape[1] % 8) // 2
425
+ y_offset = (pixels.shape[2] % 8) // 2
426
+ pixels = pixels[:,x_offset:x + x_offset, y_offset:y + y_offset,:]
427
+ mask = mask[:,:,x_offset:x + x_offset, y_offset:y + y_offset]
428
+
429
+ m = (1.0 - mask.round()).squeeze(1)
430
+ for i in range(3):
431
+ pixels[:,:,:,i] -= 0.5
432
+ pixels[:,:,:,i] *= m
433
+ pixels[:,:,:,i] += 0.5
434
+ concat_latent = vae.encode(pixels)
435
+ orig_latent = vae.encode(orig_pixels)
436
+
437
+ out_latent = {}
438
+
439
+ out_latent["samples"] = orig_latent
440
+ if noise_mask:
441
+ out_latent["noise_mask"] = mask
442
+
443
+ out = []
444
+ for conditioning in [positive, negative]:
445
+ c = node_helpers.conditioning_set_values(conditioning, {"concat_latent_image": concat_latent,
446
+ "concat_mask": mask})
447
+ out.append(c)
448
+ return (out[0], out[1], out_latent)
449
+
450
+
451
+ class SaveLatent:
452
+ def __init__(self):
453
+ self.output_dir = folder_paths.get_output_directory()
454
+
455
+ @classmethod
456
+ def INPUT_TYPES(s):
457
+ return {"required": { "samples": ("LATENT", ),
458
+ "filename_prefix": ("STRING", {"default": "latents/ComfyUI"})},
459
+ "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
460
+ }
461
+ RETURN_TYPES = ()
462
+ FUNCTION = "save"
463
+
464
+ OUTPUT_NODE = True
465
+
466
+ CATEGORY = "_for_testing"
467
+
468
+ def save(self, samples, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None):
469
+ full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir)
470
+
471
+ # support save metadata for latent sharing
472
+ prompt_info = ""
473
+ if prompt is not None:
474
+ prompt_info = json.dumps(prompt)
475
+
476
+ metadata = None
477
+ if not args.disable_metadata:
478
+ metadata = {"prompt": prompt_info}
479
+ if extra_pnginfo is not None:
480
+ for x in extra_pnginfo:
481
+ metadata[x] = json.dumps(extra_pnginfo[x])
482
+
483
+ file = f"{filename}_{counter:05}_.latent"
484
+
485
+ results: list[FileLocator] = []
486
+ results.append({
487
+ "filename": file,
488
+ "subfolder": subfolder,
489
+ "type": "output"
490
+ })
491
+
492
+ file = os.path.join(full_output_folder, file)
493
+
494
+ output = {}
495
+ output["latent_tensor"] = samples["samples"].contiguous()
496
+ output["latent_format_version_0"] = torch.tensor([])
497
+
498
+ comfy.utils.save_torch_file(output, file, metadata=metadata)
499
+ return { "ui": { "latents": results } }
500
+
501
+
502
+ class LoadLatent:
503
+ @classmethod
504
+ def INPUT_TYPES(s):
505
+ input_dir = folder_paths.get_input_directory()
506
+ files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f)) and f.endswith(".latent")]
507
+ return {"required": {"latent": [sorted(files), ]}, }
508
+
509
+ CATEGORY = "_for_testing"
510
+
511
+ RETURN_TYPES = ("LATENT", )
512
+ FUNCTION = "load"
513
+
514
+ def load(self, latent):
515
+ latent_path = folder_paths.get_annotated_filepath(latent)
516
+ latent = safetensors.torch.load_file(latent_path, device="cpu")
517
+ multiplier = 1.0
518
+ if "latent_format_version_0" not in latent:
519
+ multiplier = 1.0 / 0.18215
520
+ samples = {"samples": latent["latent_tensor"].float() * multiplier}
521
+ return (samples, )
522
+
523
+ @classmethod
524
+ def IS_CHANGED(s, latent):
525
+ image_path = folder_paths.get_annotated_filepath(latent)
526
+ m = hashlib.sha256()
527
+ with open(image_path, 'rb') as f:
528
+ m.update(f.read())
529
+ return m.digest().hex()
530
+
531
+ @classmethod
532
+ def VALIDATE_INPUTS(s, latent):
533
+ if not folder_paths.exists_annotated_filepath(latent):
534
+ return "Invalid latent file: {}".format(latent)
535
+ return True
536
+
537
+
538
+ class CheckpointLoader:
539
+ @classmethod
540
+ def INPUT_TYPES(s):
541
+ return {"required": { "config_name": (folder_paths.get_filename_list("configs"), ),
542
+ "ckpt_name": (folder_paths.get_filename_list("checkpoints"), )}}
543
+ RETURN_TYPES = ("MODEL", "CLIP", "VAE")
544
+ FUNCTION = "load_checkpoint"
545
+
546
+ CATEGORY = "advanced/loaders"
547
+ DEPRECATED = True
548
+
549
+ def load_checkpoint(self, config_name, ckpt_name):
550
+ config_path = folder_paths.get_full_path("configs", config_name)
551
+ ckpt_path = folder_paths.get_full_path_or_raise("checkpoints", ckpt_name)
552
+ return comfy.sd.load_checkpoint(config_path, ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
553
+
554
+ class CheckpointLoaderSimple:
555
+ @classmethod
556
+ def INPUT_TYPES(s):
557
+ return {
558
+ "required": {
559
+ "ckpt_name": (folder_paths.get_filename_list("checkpoints"), {"tooltip": "The name of the checkpoint (model) to load."}),
560
+ }
561
+ }
562
+ RETURN_TYPES = ("MODEL", "CLIP", "VAE")
563
+ OUTPUT_TOOLTIPS = ("The model used for denoising latents.",
564
+ "The CLIP model used for encoding text prompts.",
565
+ "The VAE model used for encoding and decoding images to and from latent space.")
566
+ FUNCTION = "load_checkpoint"
567
+
568
+ CATEGORY = "loaders"
569
+ DESCRIPTION = "Loads a diffusion model checkpoint, diffusion models are used to denoise latents."
570
+
571
+ def load_checkpoint(self, ckpt_name):
572
+ ckpt_path = folder_paths.get_full_path_or_raise("checkpoints", ckpt_name)
573
+ out = comfy.sd.load_checkpoint_guess_config(ckpt_path, output_vae=True, output_clip=True, embedding_directory=folder_paths.get_folder_paths("embeddings"))
574
+ return out[:3]
575
+
576
+ class DiffusersLoader:
577
+ @classmethod
578
+ def INPUT_TYPES(cls):
579
+ paths = []
580
+ for search_path in folder_paths.get_folder_paths("diffusers"):
581
+ if os.path.exists(search_path):
582
+ for root, subdir, files in os.walk(search_path, followlinks=True):
583
+ if "model_index.json" in files:
584
+ paths.append(os.path.relpath(root, start=search_path))
585
+
586
+ return {"required": {"model_path": (paths,), }}
587
+ RETURN_TYPES = ("MODEL", "CLIP", "VAE")
588
+ FUNCTION = "load_checkpoint"
589
+
590
+ CATEGORY = "advanced/loaders/deprecated"
591
+
592
+ def load_checkpoint(self, model_path, output_vae=True, output_clip=True):
593
+ for search_path in folder_paths.get_folder_paths("diffusers"):
594
+ if os.path.exists(search_path):
595
+ path = os.path.join(search_path, model_path)
596
+ if os.path.exists(path):
597
+ model_path = path
598
+ break
599
+
600
+ return comfy.diffusers_load.load_diffusers(model_path, output_vae=output_vae, output_clip=output_clip, embedding_directory=folder_paths.get_folder_paths("embeddings"))
601
+
602
+
603
+ class unCLIPCheckpointLoader:
604
+ @classmethod
605
+ def INPUT_TYPES(s):
606
+ return {"required": { "ckpt_name": (folder_paths.get_filename_list("checkpoints"), ),
607
+ }}
608
+ RETURN_TYPES = ("MODEL", "CLIP", "VAE", "CLIP_VISION")
609
+ FUNCTION = "load_checkpoint"
610
+
611
+ CATEGORY = "loaders"
612
+
613
+ def load_checkpoint(self, ckpt_name, output_vae=True, output_clip=True):
614
+ ckpt_path = folder_paths.get_full_path_or_raise("checkpoints", ckpt_name)
615
+ 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"))
616
+ return out
617
+
618
+ class CLIPSetLastLayer:
619
+ @classmethod
620
+ def INPUT_TYPES(s):
621
+ return {"required": { "clip": ("CLIP", ),
622
+ "stop_at_clip_layer": ("INT", {"default": -1, "min": -24, "max": -1, "step": 1}),
623
+ }}
624
+ RETURN_TYPES = ("CLIP",)
625
+ FUNCTION = "set_last_layer"
626
+
627
+ CATEGORY = "conditioning"
628
+
629
+ def set_last_layer(self, clip, stop_at_clip_layer):
630
+ clip = clip.clone()
631
+ clip.clip_layer(stop_at_clip_layer)
632
+ return (clip,)
633
+
634
+ class LoraLoader:
635
+ def __init__(self):
636
+ self.loaded_lora = None
637
+
638
+ @classmethod
639
+ def INPUT_TYPES(s):
640
+ return {
641
+ "required": {
642
+ "model": ("MODEL", {"tooltip": "The diffusion model the LoRA will be applied to."}),
643
+ "clip": ("CLIP", {"tooltip": "The CLIP model the LoRA will be applied to."}),
644
+ "lora_name": (folder_paths.get_filename_list("loras"), {"tooltip": "The name of the LoRA."}),
645
+ "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."}),
646
+ "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."}),
647
+ }
648
+ }
649
+
650
+ RETURN_TYPES = ("MODEL", "CLIP")
651
+ OUTPUT_TOOLTIPS = ("The modified diffusion model.", "The modified CLIP model.")
652
+ FUNCTION = "load_lora"
653
+
654
+ CATEGORY = "loaders"
655
+ 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."
656
+
657
+ def load_lora(self, model, clip, lora_name, strength_model, strength_clip):
658
+ if strength_model == 0 and strength_clip == 0:
659
+ return (model, clip)
660
+
661
+ lora_path = folder_paths.get_full_path_or_raise("loras", lora_name)
662
+ lora = None
663
+ if self.loaded_lora is not None:
664
+ if self.loaded_lora[0] == lora_path:
665
+ lora = self.loaded_lora[1]
666
+ else:
667
+ self.loaded_lora = None
668
+
669
+ if lora is None:
670
+ lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
671
+ self.loaded_lora = (lora_path, lora)
672
+
673
+ model_lora, clip_lora = comfy.sd.load_lora_for_models(model, clip, lora, strength_model, strength_clip)
674
+ return (model_lora, clip_lora)
675
+
676
+ class LoraLoaderModelOnly(LoraLoader):
677
+ @classmethod
678
+ def INPUT_TYPES(s):
679
+ return {"required": { "model": ("MODEL",),
680
+ "lora_name": (folder_paths.get_filename_list("loras"), ),
681
+ "strength_model": ("FLOAT", {"default": 1.0, "min": -100.0, "max": 100.0, "step": 0.01}),
682
+ }}
683
+ RETURN_TYPES = ("MODEL",)
684
+ FUNCTION = "load_lora_model_only"
685
+
686
+ def load_lora_model_only(self, model, lora_name, strength_model):
687
+ return (self.load_lora(model, None, lora_name, strength_model, 0)[0],)
688
+
689
+ class VAELoader:
690
+ @staticmethod
691
+ def vae_list():
692
+ vaes = folder_paths.get_filename_list("vae")
693
+ approx_vaes = folder_paths.get_filename_list("vae_approx")
694
+ sdxl_taesd_enc = False
695
+ sdxl_taesd_dec = False
696
+ sd1_taesd_enc = False
697
+ sd1_taesd_dec = False
698
+ sd3_taesd_enc = False
699
+ sd3_taesd_dec = False
700
+ f1_taesd_enc = False
701
+ f1_taesd_dec = False
702
+
703
+ for v in approx_vaes:
704
+ if v.startswith("taesd_decoder."):
705
+ sd1_taesd_dec = True
706
+ elif v.startswith("taesd_encoder."):
707
+ sd1_taesd_enc = True
708
+ elif v.startswith("taesdxl_decoder."):
709
+ sdxl_taesd_dec = True
710
+ elif v.startswith("taesdxl_encoder."):
711
+ sdxl_taesd_enc = True
712
+ elif v.startswith("taesd3_decoder."):
713
+ sd3_taesd_dec = True
714
+ elif v.startswith("taesd3_encoder."):
715
+ sd3_taesd_enc = True
716
+ elif v.startswith("taef1_encoder."):
717
+ f1_taesd_dec = True
718
+ elif v.startswith("taef1_decoder."):
719
+ f1_taesd_enc = True
720
+ if sd1_taesd_dec and sd1_taesd_enc:
721
+ vaes.append("taesd")
722
+ if sdxl_taesd_dec and sdxl_taesd_enc:
723
+ vaes.append("taesdxl")
724
+ if sd3_taesd_dec and sd3_taesd_enc:
725
+ vaes.append("taesd3")
726
+ if f1_taesd_dec and f1_taesd_enc:
727
+ vaes.append("taef1")
728
+ return vaes
729
+
730
+ @staticmethod
731
+ def load_taesd(name):
732
+ sd = {}
733
+ approx_vaes = folder_paths.get_filename_list("vae_approx")
734
+
735
+ encoder = next(filter(lambda a: a.startswith("{}_encoder.".format(name)), approx_vaes))
736
+ decoder = next(filter(lambda a: a.startswith("{}_decoder.".format(name)), approx_vaes))
737
+
738
+ enc = comfy.utils.load_torch_file(folder_paths.get_full_path_or_raise("vae_approx", encoder))
739
+ for k in enc:
740
+ sd["taesd_encoder.{}".format(k)] = enc[k]
741
+
742
+ dec = comfy.utils.load_torch_file(folder_paths.get_full_path_or_raise("vae_approx", decoder))
743
+ for k in dec:
744
+ sd["taesd_decoder.{}".format(k)] = dec[k]
745
+
746
+ if name == "taesd":
747
+ sd["vae_scale"] = torch.tensor(0.18215)
748
+ sd["vae_shift"] = torch.tensor(0.0)
749
+ elif name == "taesdxl":
750
+ sd["vae_scale"] = torch.tensor(0.13025)
751
+ sd["vae_shift"] = torch.tensor(0.0)
752
+ elif name == "taesd3":
753
+ sd["vae_scale"] = torch.tensor(1.5305)
754
+ sd["vae_shift"] = torch.tensor(0.0609)
755
+ elif name == "taef1":
756
+ sd["vae_scale"] = torch.tensor(0.3611)
757
+ sd["vae_shift"] = torch.tensor(0.1159)
758
+ return sd
759
+
760
+ @classmethod
761
+ def INPUT_TYPES(s):
762
+ return {"required": { "vae_name": (s.vae_list(), )}}
763
+ RETURN_TYPES = ("VAE",)
764
+ FUNCTION = "load_vae"
765
+
766
+ CATEGORY = "loaders"
767
+
768
+ #TODO: scale factor?
769
+ def load_vae(self, vae_name):
770
+ if vae_name in ["taesd", "taesdxl", "taesd3", "taef1"]:
771
+ sd = self.load_taesd(vae_name)
772
+ else:
773
+ vae_path = folder_paths.get_full_path_or_raise("vae", vae_name)
774
+ sd = comfy.utils.load_torch_file(vae_path)
775
+ vae = comfy.sd.VAE(sd=sd)
776
+ vae.throw_exception_if_invalid()
777
+ return (vae,)
778
+
779
+ class ControlNetLoader:
780
+ @classmethod
781
+ def INPUT_TYPES(s):
782
+ return {"required": { "control_net_name": (folder_paths.get_filename_list("controlnet"), )}}
783
+
784
+ RETURN_TYPES = ("CONTROL_NET",)
785
+ FUNCTION = "load_controlnet"
786
+
787
+ CATEGORY = "loaders"
788
+
789
+ def load_controlnet(self, control_net_name):
790
+ controlnet_path = folder_paths.get_full_path_or_raise("controlnet", control_net_name)
791
+ controlnet = comfy.controlnet.load_controlnet(controlnet_path)
792
+ if controlnet is None:
793
+ raise RuntimeError("ERROR: controlnet file is invalid and does not contain a valid controlnet model.")
794
+ return (controlnet,)
795
+
796
+ class DiffControlNetLoader:
797
+ @classmethod
798
+ def INPUT_TYPES(s):
799
+ return {"required": { "model": ("MODEL",),
800
+ "control_net_name": (folder_paths.get_filename_list("controlnet"), )}}
801
+
802
+ RETURN_TYPES = ("CONTROL_NET",)
803
+ FUNCTION = "load_controlnet"
804
+
805
+ CATEGORY = "loaders"
806
+
807
+ def load_controlnet(self, model, control_net_name):
808
+ controlnet_path = folder_paths.get_full_path_or_raise("controlnet", control_net_name)
809
+ controlnet = comfy.controlnet.load_controlnet(controlnet_path, model)
810
+ return (controlnet,)
811
+
812
+
813
+ class ControlNetApply:
814
+ @classmethod
815
+ def INPUT_TYPES(s):
816
+ return {"required": {"conditioning": ("CONDITIONING", ),
817
+ "control_net": ("CONTROL_NET", ),
818
+ "image": ("IMAGE", ),
819
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01})
820
+ }}
821
+ RETURN_TYPES = ("CONDITIONING",)
822
+ FUNCTION = "apply_controlnet"
823
+
824
+ DEPRECATED = True
825
+ CATEGORY = "conditioning/controlnet"
826
+
827
+ def apply_controlnet(self, conditioning, control_net, image, strength):
828
+ if strength == 0:
829
+ return (conditioning, )
830
+
831
+ c = []
832
+ control_hint = image.movedim(-1,1)
833
+ for t in conditioning:
834
+ n = [t[0], t[1].copy()]
835
+ c_net = control_net.copy().set_cond_hint(control_hint, strength)
836
+ if 'control' in t[1]:
837
+ c_net.set_previous_controlnet(t[1]['control'])
838
+ n[1]['control'] = c_net
839
+ n[1]['control_apply_to_uncond'] = True
840
+ c.append(n)
841
+ return (c, )
842
+
843
+
844
+ class ControlNetApplyAdvanced:
845
+ @classmethod
846
+ def INPUT_TYPES(s):
847
+ return {"required": {"positive": ("CONDITIONING", ),
848
+ "negative": ("CONDITIONING", ),
849
+ "control_net": ("CONTROL_NET", ),
850
+ "image": ("IMAGE", ),
851
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
852
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
853
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
854
+ },
855
+ "optional": {"vae": ("VAE", ),
856
+ }
857
+ }
858
+
859
+ RETURN_TYPES = ("CONDITIONING","CONDITIONING")
860
+ RETURN_NAMES = ("positive", "negative")
861
+ FUNCTION = "apply_controlnet"
862
+
863
+ CATEGORY = "conditioning/controlnet"
864
+
865
+ def apply_controlnet(self, positive, negative, control_net, image, strength, start_percent, end_percent, vae=None, extra_concat=[]):
866
+ if strength == 0:
867
+ return (positive, negative)
868
+
869
+ control_hint = image.movedim(-1,1)
870
+ cnets = {}
871
+
872
+ out = []
873
+ for conditioning in [positive, negative]:
874
+ c = []
875
+ for t in conditioning:
876
+ d = t[1].copy()
877
+
878
+ prev_cnet = d.get('control', None)
879
+ if prev_cnet in cnets:
880
+ c_net = cnets[prev_cnet]
881
+ else:
882
+ c_net = control_net.copy().set_cond_hint(control_hint, strength, (start_percent, end_percent), vae=vae, extra_concat=extra_concat)
883
+ c_net.set_previous_controlnet(prev_cnet)
884
+ cnets[prev_cnet] = c_net
885
+
886
+ d['control'] = c_net
887
+ d['control_apply_to_uncond'] = False
888
+ n = [t[0], d]
889
+ c.append(n)
890
+ out.append(c)
891
+ return (out[0], out[1])
892
+
893
+
894
+ class UNETLoader:
895
+ @classmethod
896
+ def INPUT_TYPES(s):
897
+ return {"required": { "unet_name": (folder_paths.get_filename_list("diffusion_models"), ),
898
+ "weight_dtype": (["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"],)
899
+ }}
900
+ RETURN_TYPES = ("MODEL",)
901
+ FUNCTION = "load_unet"
902
+
903
+ CATEGORY = "advanced/loaders"
904
+
905
+ def load_unet(self, unet_name, weight_dtype):
906
+ model_options = {}
907
+ if weight_dtype == "fp8_e4m3fn":
908
+ model_options["dtype"] = torch.float8_e4m3fn
909
+ elif weight_dtype == "fp8_e4m3fn_fast":
910
+ model_options["dtype"] = torch.float8_e4m3fn
911
+ model_options["fp8_optimizations"] = True
912
+ elif weight_dtype == "fp8_e5m2":
913
+ model_options["dtype"] = torch.float8_e5m2
914
+
915
+ unet_path = folder_paths.get_full_path_or_raise("diffusion_models", unet_name)
916
+ model = comfy.sd.load_diffusion_model(unet_path, model_options=model_options)
917
+ return (model,)
918
+
919
+ class CLIPLoader:
920
+ @classmethod
921
+ def INPUT_TYPES(s):
922
+ return {"required": { "clip_name": (folder_paths.get_filename_list("text_encoders"), ),
923
+ "type": (["stable_diffusion", "stable_cascade", "sd3", "stable_audio", "mochi", "ltxv", "pixart", "cosmos", "lumina2", "wan", "hidream", "chroma", "ace"], ),
924
+ },
925
+ "optional": {
926
+ "device": (["default", "cpu"], {"advanced": True}),
927
+ }}
928
+ RETURN_TYPES = ("CLIP",)
929
+ FUNCTION = "load_clip"
930
+
931
+ CATEGORY = "advanced/loaders"
932
+
933
+ DESCRIPTION = "[Recipes]\n\nstable_diffusion: clip-l\nstable_cascade: clip-g\nsd3: t5 xxl/ clip-g / clip-l\nstable_audio: t5 base\nmochi: t5 xxl\ncosmos: old t5 xxl\nlumina2: gemma 2 2B\nwan: umt5 xxl\n hidream: llama-3.1 (Recommend) or t5"
934
+
935
+ def load_clip(self, clip_name, type="stable_diffusion", device="default"):
936
+ clip_type = getattr(comfy.sd.CLIPType, type.upper(), comfy.sd.CLIPType.STABLE_DIFFUSION)
937
+
938
+ model_options = {}
939
+ if device == "cpu":
940
+ model_options["load_device"] = model_options["offload_device"] = torch.device("cpu")
941
+
942
+ clip_path = folder_paths.get_full_path_or_raise("text_encoders", clip_name)
943
+ clip = comfy.sd.load_clip(ckpt_paths=[clip_path], embedding_directory=folder_paths.get_folder_paths("embeddings"), clip_type=clip_type, model_options=model_options)
944
+ return (clip,)
945
+
946
+ class DualCLIPLoader:
947
+ @classmethod
948
+ def INPUT_TYPES(s):
949
+ return {"required": { "clip_name1": (folder_paths.get_filename_list("text_encoders"), ),
950
+ "clip_name2": (folder_paths.get_filename_list("text_encoders"), ),
951
+ "type": (["sdxl", "sd3", "flux", "hunyuan_video", "hidream"], ),
952
+ },
953
+ "optional": {
954
+ "device": (["default", "cpu"], {"advanced": True}),
955
+ }}
956
+ RETURN_TYPES = ("CLIP",)
957
+ FUNCTION = "load_clip"
958
+
959
+ CATEGORY = "advanced/loaders"
960
+
961
+ DESCRIPTION = "[Recipes]\n\nsdxl: clip-l, clip-g\nsd3: clip-l, clip-g / clip-l, t5 / clip-g, t5\nflux: clip-l, t5\nhidream: at least one of t5 or llama, recommended t5 and llama"
962
+
963
+ def load_clip(self, clip_name1, clip_name2, type, device="default"):
964
+ clip_type = getattr(comfy.sd.CLIPType, type.upper(), comfy.sd.CLIPType.STABLE_DIFFUSION)
965
+
966
+ clip_path1 = folder_paths.get_full_path_or_raise("text_encoders", clip_name1)
967
+ clip_path2 = folder_paths.get_full_path_or_raise("text_encoders", clip_name2)
968
+
969
+ model_options = {}
970
+ if device == "cpu":
971
+ model_options["load_device"] = model_options["offload_device"] = torch.device("cpu")
972
+
973
+ clip = comfy.sd.load_clip(ckpt_paths=[clip_path1, clip_path2], embedding_directory=folder_paths.get_folder_paths("embeddings"), clip_type=clip_type, model_options=model_options)
974
+ return (clip,)
975
+
976
+ class CLIPVisionLoader:
977
+ @classmethod
978
+ def INPUT_TYPES(s):
979
+ return {"required": { "clip_name": (folder_paths.get_filename_list("clip_vision"), ),
980
+ }}
981
+ RETURN_TYPES = ("CLIP_VISION",)
982
+ FUNCTION = "load_clip"
983
+
984
+ CATEGORY = "loaders"
985
+
986
+ def load_clip(self, clip_name):
987
+ clip_path = folder_paths.get_full_path_or_raise("clip_vision", clip_name)
988
+ clip_vision = comfy.clip_vision.load(clip_path)
989
+ if clip_vision is None:
990
+ raise RuntimeError("ERROR: clip vision file is invalid and does not contain a valid vision model.")
991
+ return (clip_vision,)
992
+
993
+ class CLIPVisionEncode:
994
+ @classmethod
995
+ def INPUT_TYPES(s):
996
+ return {"required": { "clip_vision": ("CLIP_VISION",),
997
+ "image": ("IMAGE",),
998
+ "crop": (["center", "none"],)
999
+ }}
1000
+ RETURN_TYPES = ("CLIP_VISION_OUTPUT",)
1001
+ FUNCTION = "encode"
1002
+
1003
+ CATEGORY = "conditioning"
1004
+
1005
+ def encode(self, clip_vision, image, crop):
1006
+ crop_image = True
1007
+ if crop != "center":
1008
+ crop_image = False
1009
+ output = clip_vision.encode_image(image, crop=crop_image)
1010
+ return (output,)
1011
+
1012
+ class StyleModelLoader:
1013
+ @classmethod
1014
+ def INPUT_TYPES(s):
1015
+ return {"required": { "style_model_name": (folder_paths.get_filename_list("style_models"), )}}
1016
+
1017
+ RETURN_TYPES = ("STYLE_MODEL",)
1018
+ FUNCTION = "load_style_model"
1019
+
1020
+ CATEGORY = "loaders"
1021
+
1022
+ def load_style_model(self, style_model_name):
1023
+ style_model_path = folder_paths.get_full_path_or_raise("style_models", style_model_name)
1024
+ style_model = comfy.sd.load_style_model(style_model_path)
1025
+ return (style_model,)
1026
+
1027
+
1028
+ class StyleModelApply:
1029
+ @classmethod
1030
+ def INPUT_TYPES(s):
1031
+ return {"required": {"conditioning": ("CONDITIONING", ),
1032
+ "style_model": ("STYLE_MODEL", ),
1033
+ "clip_vision_output": ("CLIP_VISION_OUTPUT", ),
1034
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}),
1035
+ "strength_type": (["multiply", "attn_bias"], ),
1036
+ }}
1037
+ RETURN_TYPES = ("CONDITIONING",)
1038
+ FUNCTION = "apply_stylemodel"
1039
+
1040
+ CATEGORY = "conditioning/style_model"
1041
+
1042
+ def apply_stylemodel(self, conditioning, style_model, clip_vision_output, strength, strength_type):
1043
+ cond = style_model.get_cond(clip_vision_output).flatten(start_dim=0, end_dim=1).unsqueeze(dim=0)
1044
+ if strength_type == "multiply":
1045
+ cond *= strength
1046
+
1047
+ n = cond.shape[1]
1048
+ c_out = []
1049
+ for t in conditioning:
1050
+ (txt, keys) = t
1051
+ keys = keys.copy()
1052
+ # even if the strength is 1.0 (i.e, no change), if there's already a mask, we have to add to it
1053
+ if "attention_mask" in keys or (strength_type == "attn_bias" and strength != 1.0):
1054
+ # math.log raises an error if the argument is zero
1055
+ # torch.log returns -inf, which is what we want
1056
+ attn_bias = torch.log(torch.Tensor([strength if strength_type == "attn_bias" else 1.0]))
1057
+ # get the size of the mask image
1058
+ mask_ref_size = keys.get("attention_mask_img_shape", (1, 1))
1059
+ n_ref = mask_ref_size[0] * mask_ref_size[1]
1060
+ n_txt = txt.shape[1]
1061
+ # grab the existing mask
1062
+ mask = keys.get("attention_mask", None)
1063
+ # create a default mask if it doesn't exist
1064
+ if mask is None:
1065
+ mask = torch.zeros((txt.shape[0], n_txt + n_ref, n_txt + n_ref), dtype=torch.float16)
1066
+ # convert the mask dtype, because it might be boolean
1067
+ # we want it to be interpreted as a bias
1068
+ if mask.dtype == torch.bool:
1069
+ # log(True) = log(1) = 0
1070
+ # log(False) = log(0) = -inf
1071
+ mask = torch.log(mask.to(dtype=torch.float16))
1072
+ # now we make the mask bigger to add space for our new tokens
1073
+ new_mask = torch.zeros((txt.shape[0], n_txt + n + n_ref, n_txt + n + n_ref), dtype=torch.float16)
1074
+ # copy over the old mask, in quandrants
1075
+ new_mask[:, :n_txt, :n_txt] = mask[:, :n_txt, :n_txt]
1076
+ new_mask[:, :n_txt, n_txt+n:] = mask[:, :n_txt, n_txt:]
1077
+ new_mask[:, n_txt+n:, :n_txt] = mask[:, n_txt:, :n_txt]
1078
+ new_mask[:, n_txt+n:, n_txt+n:] = mask[:, n_txt:, n_txt:]
1079
+ # now fill in the attention bias to our redux tokens
1080
+ new_mask[:, :n_txt, n_txt:n_txt+n] = attn_bias
1081
+ new_mask[:, n_txt+n:, n_txt:n_txt+n] = attn_bias
1082
+ keys["attention_mask"] = new_mask.to(txt.device)
1083
+ keys["attention_mask_img_shape"] = mask_ref_size
1084
+
1085
+ c_out.append([torch.cat((txt, cond), dim=1), keys])
1086
+
1087
+ return (c_out,)
1088
+
1089
+ class unCLIPConditioning:
1090
+ @classmethod
1091
+ def INPUT_TYPES(s):
1092
+ return {"required": {"conditioning": ("CONDITIONING", ),
1093
+ "clip_vision_output": ("CLIP_VISION_OUTPUT", ),
1094
+ "strength": ("FLOAT", {"default": 1.0, "min": -10.0, "max": 10.0, "step": 0.01}),
1095
+ "noise_augmentation": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.01}),
1096
+ }}
1097
+ RETURN_TYPES = ("CONDITIONING",)
1098
+ FUNCTION = "apply_adm"
1099
+
1100
+ CATEGORY = "conditioning"
1101
+
1102
+ def apply_adm(self, conditioning, clip_vision_output, strength, noise_augmentation):
1103
+ if strength == 0:
1104
+ return (conditioning, )
1105
+
1106
+ c = node_helpers.conditioning_set_values(conditioning, {"unclip_conditioning": [{"clip_vision_output": clip_vision_output, "strength": strength, "noise_augmentation": noise_augmentation}]}, append=True)
1107
+ return (c, )
1108
+
1109
+ class GLIGENLoader:
1110
+ @classmethod
1111
+ def INPUT_TYPES(s):
1112
+ return {"required": { "gligen_name": (folder_paths.get_filename_list("gligen"), )}}
1113
+
1114
+ RETURN_TYPES = ("GLIGEN",)
1115
+ FUNCTION = "load_gligen"
1116
+
1117
+ CATEGORY = "loaders"
1118
+
1119
+ def load_gligen(self, gligen_name):
1120
+ gligen_path = folder_paths.get_full_path_or_raise("gligen", gligen_name)
1121
+ gligen = comfy.sd.load_gligen(gligen_path)
1122
+ return (gligen,)
1123
+
1124
+ class GLIGENTextBoxApply:
1125
+ @classmethod
1126
+ def INPUT_TYPES(s):
1127
+ return {"required": {"conditioning_to": ("CONDITIONING", ),
1128
+ "clip": ("CLIP", ),
1129
+ "gligen_textbox_model": ("GLIGEN", ),
1130
+ "text": ("STRING", {"multiline": True, "dynamicPrompts": True}),
1131
+ "width": ("INT", {"default": 64, "min": 8, "max": MAX_RESOLUTION, "step": 8}),
1132
+ "height": ("INT", {"default": 64, "min": 8, "max": MAX_RESOLUTION, "step": 8}),
1133
+ "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1134
+ "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1135
+ }}
1136
+ RETURN_TYPES = ("CONDITIONING",)
1137
+ FUNCTION = "append"
1138
+
1139
+ CATEGORY = "conditioning/gligen"
1140
+
1141
+ def append(self, conditioning_to, clip, gligen_textbox_model, text, width, height, x, y):
1142
+ c = []
1143
+ cond, cond_pooled = clip.encode_from_tokens(clip.tokenize(text), return_pooled="unprojected")
1144
+ for t in conditioning_to:
1145
+ n = [t[0], t[1].copy()]
1146
+ position_params = [(cond_pooled, height // 8, width // 8, y // 8, x // 8)]
1147
+ prev = []
1148
+ if "gligen" in n[1]:
1149
+ prev = n[1]['gligen'][2]
1150
+
1151
+ n[1]['gligen'] = ("position", gligen_textbox_model, prev + position_params)
1152
+ c.append(n)
1153
+ return (c, )
1154
+
1155
+ class EmptyLatentImage:
1156
+ def __init__(self):
1157
+ self.device = comfy.model_management.intermediate_device()
1158
+
1159
+ @classmethod
1160
+ def INPUT_TYPES(s):
1161
+ return {
1162
+ "required": {
1163
+ "width": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8, "tooltip": "The width of the latent images in pixels."}),
1164
+ "height": ("INT", {"default": 512, "min": 16, "max": MAX_RESOLUTION, "step": 8, "tooltip": "The height of the latent images in pixels."}),
1165
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096, "tooltip": "The number of latent images in the batch."})
1166
+ }
1167
+ }
1168
+ RETURN_TYPES = ("LATENT",)
1169
+ OUTPUT_TOOLTIPS = ("The empty latent image batch.",)
1170
+ FUNCTION = "generate"
1171
+
1172
+ CATEGORY = "latent"
1173
+ DESCRIPTION = "Create a new batch of empty latent images to be denoised via sampling."
1174
+
1175
+ def generate(self, width, height, batch_size=1):
1176
+ latent = torch.zeros([batch_size, 4, height // 8, width // 8], device=self.device)
1177
+ return ({"samples":latent}, )
1178
+
1179
+
1180
+ class LatentFromBatch:
1181
+ @classmethod
1182
+ def INPUT_TYPES(s):
1183
+ return {"required": { "samples": ("LATENT",),
1184
+ "batch_index": ("INT", {"default": 0, "min": 0, "max": 63}),
1185
+ "length": ("INT", {"default": 1, "min": 1, "max": 64}),
1186
+ }}
1187
+ RETURN_TYPES = ("LATENT",)
1188
+ FUNCTION = "frombatch"
1189
+
1190
+ CATEGORY = "latent/batch"
1191
+
1192
+ def frombatch(self, samples, batch_index, length):
1193
+ s = samples.copy()
1194
+ s_in = samples["samples"]
1195
+ batch_index = min(s_in.shape[0] - 1, batch_index)
1196
+ length = min(s_in.shape[0] - batch_index, length)
1197
+ s["samples"] = s_in[batch_index:batch_index + length].clone()
1198
+ if "noise_mask" in samples:
1199
+ masks = samples["noise_mask"]
1200
+ if masks.shape[0] == 1:
1201
+ s["noise_mask"] = masks.clone()
1202
+ else:
1203
+ if masks.shape[0] < s_in.shape[0]:
1204
+ masks = masks.repeat(math.ceil(s_in.shape[0] / masks.shape[0]), 1, 1, 1)[:s_in.shape[0]]
1205
+ s["noise_mask"] = masks[batch_index:batch_index + length].clone()
1206
+ if "batch_index" not in s:
1207
+ s["batch_index"] = [x for x in range(batch_index, batch_index+length)]
1208
+ else:
1209
+ s["batch_index"] = samples["batch_index"][batch_index:batch_index + length]
1210
+ return (s,)
1211
+
1212
+ class RepeatLatentBatch:
1213
+ @classmethod
1214
+ def INPUT_TYPES(s):
1215
+ return {"required": { "samples": ("LATENT",),
1216
+ "amount": ("INT", {"default": 1, "min": 1, "max": 64}),
1217
+ }}
1218
+ RETURN_TYPES = ("LATENT",)
1219
+ FUNCTION = "repeat"
1220
+
1221
+ CATEGORY = "latent/batch"
1222
+
1223
+ def repeat(self, samples, amount):
1224
+ s = samples.copy()
1225
+ s_in = samples["samples"]
1226
+
1227
+ s["samples"] = s_in.repeat((amount, 1,1,1))
1228
+ if "noise_mask" in samples and samples["noise_mask"].shape[0] > 1:
1229
+ masks = samples["noise_mask"]
1230
+ if masks.shape[0] < s_in.shape[0]:
1231
+ masks = masks.repeat(math.ceil(s_in.shape[0] / masks.shape[0]), 1, 1, 1)[:s_in.shape[0]]
1232
+ s["noise_mask"] = samples["noise_mask"].repeat((amount, 1,1,1))
1233
+ if "batch_index" in s:
1234
+ offset = max(s["batch_index"]) - min(s["batch_index"]) + 1
1235
+ s["batch_index"] = s["batch_index"] + [x + (i * offset) for i in range(1, amount) for x in s["batch_index"]]
1236
+ return (s,)
1237
+
1238
+ class LatentUpscale:
1239
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "bislerp"]
1240
+ crop_methods = ["disabled", "center"]
1241
+
1242
+ @classmethod
1243
+ def INPUT_TYPES(s):
1244
+ return {"required": { "samples": ("LATENT",), "upscale_method": (s.upscale_methods,),
1245
+ "width": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1246
+ "height": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1247
+ "crop": (s.crop_methods,)}}
1248
+ RETURN_TYPES = ("LATENT",)
1249
+ FUNCTION = "upscale"
1250
+
1251
+ CATEGORY = "latent"
1252
+
1253
+ def upscale(self, samples, upscale_method, width, height, crop):
1254
+ if width == 0 and height == 0:
1255
+ s = samples
1256
+ else:
1257
+ s = samples.copy()
1258
+
1259
+ if width == 0:
1260
+ height = max(64, height)
1261
+ width = max(64, round(samples["samples"].shape[-1] * height / samples["samples"].shape[-2]))
1262
+ elif height == 0:
1263
+ width = max(64, width)
1264
+ height = max(64, round(samples["samples"].shape[-2] * width / samples["samples"].shape[-1]))
1265
+ else:
1266
+ width = max(64, width)
1267
+ height = max(64, height)
1268
+
1269
+ s["samples"] = comfy.utils.common_upscale(samples["samples"], width // 8, height // 8, upscale_method, crop)
1270
+ return (s,)
1271
+
1272
+ class LatentUpscaleBy:
1273
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "bislerp"]
1274
+
1275
+ @classmethod
1276
+ def INPUT_TYPES(s):
1277
+ return {"required": { "samples": ("LATENT",), "upscale_method": (s.upscale_methods,),
1278
+ "scale_by": ("FLOAT", {"default": 1.5, "min": 0.01, "max": 8.0, "step": 0.01}),}}
1279
+ RETURN_TYPES = ("LATENT",)
1280
+ FUNCTION = "upscale"
1281
+
1282
+ CATEGORY = "latent"
1283
+
1284
+ def upscale(self, samples, upscale_method, scale_by):
1285
+ s = samples.copy()
1286
+ width = round(samples["samples"].shape[-1] * scale_by)
1287
+ height = round(samples["samples"].shape[-2] * scale_by)
1288
+ s["samples"] = comfy.utils.common_upscale(samples["samples"], width, height, upscale_method, "disabled")
1289
+ return (s,)
1290
+
1291
+ class LatentRotate:
1292
+ @classmethod
1293
+ def INPUT_TYPES(s):
1294
+ return {"required": { "samples": ("LATENT",),
1295
+ "rotation": (["none", "90 degrees", "180 degrees", "270 degrees"],),
1296
+ }}
1297
+ RETURN_TYPES = ("LATENT",)
1298
+ FUNCTION = "rotate"
1299
+
1300
+ CATEGORY = "latent/transform"
1301
+
1302
+ def rotate(self, samples, rotation):
1303
+ s = samples.copy()
1304
+ rotate_by = 0
1305
+ if rotation.startswith("90"):
1306
+ rotate_by = 1
1307
+ elif rotation.startswith("180"):
1308
+ rotate_by = 2
1309
+ elif rotation.startswith("270"):
1310
+ rotate_by = 3
1311
+
1312
+ s["samples"] = torch.rot90(samples["samples"], k=rotate_by, dims=[3, 2])
1313
+ return (s,)
1314
+
1315
+ class LatentFlip:
1316
+ @classmethod
1317
+ def INPUT_TYPES(s):
1318
+ return {"required": { "samples": ("LATENT",),
1319
+ "flip_method": (["x-axis: vertically", "y-axis: horizontally"],),
1320
+ }}
1321
+ RETURN_TYPES = ("LATENT",)
1322
+ FUNCTION = "flip"
1323
+
1324
+ CATEGORY = "latent/transform"
1325
+
1326
+ def flip(self, samples, flip_method):
1327
+ s = samples.copy()
1328
+ if flip_method.startswith("x"):
1329
+ s["samples"] = torch.flip(samples["samples"], dims=[2])
1330
+ elif flip_method.startswith("y"):
1331
+ s["samples"] = torch.flip(samples["samples"], dims=[3])
1332
+
1333
+ return (s,)
1334
+
1335
+ class LatentComposite:
1336
+ @classmethod
1337
+ def INPUT_TYPES(s):
1338
+ return {"required": { "samples_to": ("LATENT",),
1339
+ "samples_from": ("LATENT",),
1340
+ "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1341
+ "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1342
+ "feather": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1343
+ }}
1344
+ RETURN_TYPES = ("LATENT",)
1345
+ FUNCTION = "composite"
1346
+
1347
+ CATEGORY = "latent"
1348
+
1349
+ def composite(self, samples_to, samples_from, x, y, composite_method="normal", feather=0):
1350
+ x = x // 8
1351
+ y = y // 8
1352
+ feather = feather // 8
1353
+ samples_out = samples_to.copy()
1354
+ s = samples_to["samples"].clone()
1355
+ samples_to = samples_to["samples"]
1356
+ samples_from = samples_from["samples"]
1357
+ if feather == 0:
1358
+ 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]
1359
+ else:
1360
+ samples_from = samples_from[:,:,:samples_to.shape[2] - y, :samples_to.shape[3] - x]
1361
+ mask = torch.ones_like(samples_from)
1362
+ for t in range(feather):
1363
+ if y != 0:
1364
+ mask[:,:,t:1+t,:] *= ((1.0/feather) * (t + 1))
1365
+
1366
+ if y + samples_from.shape[2] < samples_to.shape[2]:
1367
+ mask[:,:,mask.shape[2] -1 -t: mask.shape[2]-t,:] *= ((1.0/feather) * (t + 1))
1368
+ if x != 0:
1369
+ mask[:,:,:,t:1+t] *= ((1.0/feather) * (t + 1))
1370
+ if x + samples_from.shape[3] < samples_to.shape[3]:
1371
+ mask[:,:,:,mask.shape[3]- 1 - t: mask.shape[3]- t] *= ((1.0/feather) * (t + 1))
1372
+ rev_mask = torch.ones_like(mask) - mask
1373
+ 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
1374
+ samples_out["samples"] = s
1375
+ return (samples_out,)
1376
+
1377
+ class LatentBlend:
1378
+ @classmethod
1379
+ def INPUT_TYPES(s):
1380
+ return {"required": {
1381
+ "samples1": ("LATENT",),
1382
+ "samples2": ("LATENT",),
1383
+ "blend_factor": ("FLOAT", {
1384
+ "default": 0.5,
1385
+ "min": 0,
1386
+ "max": 1,
1387
+ "step": 0.01
1388
+ }),
1389
+ }}
1390
+
1391
+ RETURN_TYPES = ("LATENT",)
1392
+ FUNCTION = "blend"
1393
+
1394
+ CATEGORY = "_for_testing"
1395
+
1396
+ def blend(self, samples1, samples2, blend_factor:float, blend_mode: str="normal"):
1397
+
1398
+ samples_out = samples1.copy()
1399
+ samples1 = samples1["samples"]
1400
+ samples2 = samples2["samples"]
1401
+
1402
+ if samples1.shape != samples2.shape:
1403
+ samples2.permute(0, 3, 1, 2)
1404
+ samples2 = comfy.utils.common_upscale(samples2, samples1.shape[3], samples1.shape[2], 'bicubic', crop='center')
1405
+ samples2.permute(0, 2, 3, 1)
1406
+
1407
+ samples_blended = self.blend_mode(samples1, samples2, blend_mode)
1408
+ samples_blended = samples1 * blend_factor + samples_blended * (1 - blend_factor)
1409
+ samples_out["samples"] = samples_blended
1410
+ return (samples_out,)
1411
+
1412
+ def blend_mode(self, img1, img2, mode):
1413
+ if mode == "normal":
1414
+ return img2
1415
+ else:
1416
+ raise ValueError(f"Unsupported blend mode: {mode}")
1417
+
1418
+ class LatentCrop:
1419
+ @classmethod
1420
+ def INPUT_TYPES(s):
1421
+ return {"required": { "samples": ("LATENT",),
1422
+ "width": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
1423
+ "height": ("INT", {"default": 512, "min": 64, "max": MAX_RESOLUTION, "step": 8}),
1424
+ "x": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1425
+ "y": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1426
+ }}
1427
+ RETURN_TYPES = ("LATENT",)
1428
+ FUNCTION = "crop"
1429
+
1430
+ CATEGORY = "latent/transform"
1431
+
1432
+ def crop(self, samples, width, height, x, y):
1433
+ s = samples.copy()
1434
+ samples = samples['samples']
1435
+ x = x // 8
1436
+ y = y // 8
1437
+
1438
+ #enfonce minimum size of 64
1439
+ if x > (samples.shape[3] - 8):
1440
+ x = samples.shape[3] - 8
1441
+ if y > (samples.shape[2] - 8):
1442
+ y = samples.shape[2] - 8
1443
+
1444
+ new_height = height // 8
1445
+ new_width = width // 8
1446
+ to_x = new_width + x
1447
+ to_y = new_height + y
1448
+ s['samples'] = samples[:,:,y:to_y, x:to_x]
1449
+ return (s,)
1450
+
1451
+ class SetLatentNoiseMask:
1452
+ @classmethod
1453
+ def INPUT_TYPES(s):
1454
+ return {"required": { "samples": ("LATENT",),
1455
+ "mask": ("MASK",),
1456
+ }}
1457
+ RETURN_TYPES = ("LATENT",)
1458
+ FUNCTION = "set_mask"
1459
+
1460
+ CATEGORY = "latent/inpaint"
1461
+
1462
+ def set_mask(self, samples, mask):
1463
+ s = samples.copy()
1464
+ s["noise_mask"] = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1]))
1465
+ return (s,)
1466
+
1467
+ 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):
1468
+ latent_image = latent["samples"]
1469
+ latent_image = comfy.sample.fix_empty_latent_channels(model, latent_image)
1470
+
1471
+ if disable_noise:
1472
+ noise = torch.zeros(latent_image.size(), dtype=latent_image.dtype, layout=latent_image.layout, device="cpu")
1473
+ else:
1474
+ batch_inds = latent["batch_index"] if "batch_index" in latent else None
1475
+ noise = comfy.sample.prepare_noise(latent_image, seed, batch_inds)
1476
+
1477
+ noise_mask = None
1478
+ if "noise_mask" in latent:
1479
+ noise_mask = latent["noise_mask"]
1480
+
1481
+ callback = latent_preview.prepare_callback(model, steps)
1482
+ disable_pbar = not comfy.utils.PROGRESS_BAR_ENABLED
1483
+ samples = comfy.sample.sample(model, noise, steps, cfg, sampler_name, scheduler, positive, negative, latent_image,
1484
+ denoise=denoise, disable_noise=disable_noise, start_step=start_step, last_step=last_step,
1485
+ force_full_denoise=force_full_denoise, noise_mask=noise_mask, callback=callback, disable_pbar=disable_pbar, seed=seed)
1486
+ out = latent.copy()
1487
+ out["samples"] = samples
1488
+ return (out, )
1489
+
1490
+ class KSampler:
1491
+ @classmethod
1492
+ def INPUT_TYPES(s):
1493
+ return {
1494
+ "required": {
1495
+ "model": ("MODEL", {"tooltip": "The model used for denoising the input latent."}),
1496
+ "seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "control_after_generate": True, "tooltip": "The random seed used for creating the noise."}),
1497
+ "steps": ("INT", {"default": 20, "min": 1, "max": 10000, "tooltip": "The number of steps used in the denoising process."}),
1498
+ "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."}),
1499
+ "sampler_name": (comfy.samplers.KSampler.SAMPLERS, {"tooltip": "The algorithm used when sampling, this can affect the quality, speed, and style of the generated output."}),
1500
+ "scheduler": (comfy.samplers.KSampler.SCHEDULERS, {"tooltip": "The scheduler controls how noise is gradually removed to form the image."}),
1501
+ "positive": ("CONDITIONING", {"tooltip": "The conditioning describing the attributes you want to include in the image."}),
1502
+ "negative": ("CONDITIONING", {"tooltip": "The conditioning describing the attributes you want to exclude from the image."}),
1503
+ "latent_image": ("LATENT", {"tooltip": "The latent image to denoise."}),
1504
+ "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."}),
1505
+ }
1506
+ }
1507
+
1508
+ RETURN_TYPES = ("LATENT",)
1509
+ OUTPUT_TOOLTIPS = ("The denoised latent.",)
1510
+ FUNCTION = "sample"
1511
+
1512
+ CATEGORY = "sampling"
1513
+ DESCRIPTION = "Uses the provided model, positive and negative conditioning to denoise the latent image."
1514
+
1515
+ def sample(self, model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=1.0):
1516
+ return common_ksampler(model, seed, steps, cfg, sampler_name, scheduler, positive, negative, latent_image, denoise=denoise)
1517
+
1518
+ class KSamplerAdvanced:
1519
+ @classmethod
1520
+ def INPUT_TYPES(s):
1521
+ return {"required":
1522
+ {"model": ("MODEL",),
1523
+ "add_noise": (["enable", "disable"], ),
1524
+ "noise_seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff, "control_after_generate": True}),
1525
+ "steps": ("INT", {"default": 20, "min": 1, "max": 10000}),
1526
+ "cfg": ("FLOAT", {"default": 8.0, "min": 0.0, "max": 100.0, "step":0.1, "round": 0.01}),
1527
+ "sampler_name": (comfy.samplers.KSampler.SAMPLERS, ),
1528
+ "scheduler": (comfy.samplers.KSampler.SCHEDULERS, ),
1529
+ "positive": ("CONDITIONING", ),
1530
+ "negative": ("CONDITIONING", ),
1531
+ "latent_image": ("LATENT", ),
1532
+ "start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000}),
1533
+ "end_at_step": ("INT", {"default": 10000, "min": 0, "max": 10000}),
1534
+ "return_with_leftover_noise": (["disable", "enable"], ),
1535
+ }
1536
+ }
1537
+
1538
+ RETURN_TYPES = ("LATENT",)
1539
+ FUNCTION = "sample"
1540
+
1541
+ CATEGORY = "sampling"
1542
+
1543
+ 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):
1544
+ force_full_denoise = True
1545
+ if return_with_leftover_noise == "enable":
1546
+ force_full_denoise = False
1547
+ disable_noise = False
1548
+ if add_noise == "disable":
1549
+ disable_noise = True
1550
+ 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)
1551
+
1552
+ class SaveImage:
1553
+ def __init__(self):
1554
+ self.output_dir = folder_paths.get_output_directory()
1555
+ self.type = "output"
1556
+ self.prefix_append = ""
1557
+ self.compress_level = 4
1558
+
1559
+ @classmethod
1560
+ def INPUT_TYPES(s):
1561
+ return {
1562
+ "required": {
1563
+ "images": ("IMAGE", {"tooltip": "The images to save."}),
1564
+ "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."})
1565
+ },
1566
+ "hidden": {
1567
+ "prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"
1568
+ },
1569
+ }
1570
+
1571
+ RETURN_TYPES = ()
1572
+ FUNCTION = "save_images"
1573
+
1574
+ OUTPUT_NODE = True
1575
+
1576
+ CATEGORY = "image"
1577
+ DESCRIPTION = "Saves the input images to your ComfyUI output directory."
1578
+
1579
+ def save_images(self, images, filename_prefix="ComfyUI", prompt=None, extra_pnginfo=None):
1580
+ filename_prefix += self.prefix_append
1581
+ 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])
1582
+ results = list()
1583
+ for (batch_number, image) in enumerate(images):
1584
+ i = 255. * image.cpu().numpy()
1585
+ img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
1586
+ metadata = None
1587
+ if not args.disable_metadata:
1588
+ metadata = PngInfo()
1589
+ if prompt is not None:
1590
+ metadata.add_text("prompt", json.dumps(prompt))
1591
+ if extra_pnginfo is not None:
1592
+ for x in extra_pnginfo:
1593
+ metadata.add_text(x, json.dumps(extra_pnginfo[x]))
1594
+
1595
+ filename_with_batch_num = filename.replace("%batch_num%", str(batch_number))
1596
+ file = f"{filename_with_batch_num}_{counter:05}_.png"
1597
+ img.save(os.path.join(full_output_folder, file), pnginfo=metadata, compress_level=self.compress_level)
1598
+ results.append({
1599
+ "filename": file,
1600
+ "subfolder": subfolder,
1601
+ "type": self.type
1602
+ })
1603
+ counter += 1
1604
+
1605
+ return { "ui": { "images": results } }
1606
+
1607
+ class PreviewImage(SaveImage):
1608
+ def __init__(self):
1609
+ self.output_dir = folder_paths.get_temp_directory()
1610
+ self.type = "temp"
1611
+ self.prefix_append = "_temp_" + ''.join(random.choice("abcdefghijklmnopqrstupvxyz") for x in range(5))
1612
+ self.compress_level = 1
1613
+
1614
+ @classmethod
1615
+ def INPUT_TYPES(s):
1616
+ return {"required":
1617
+ {"images": ("IMAGE", ), },
1618
+ "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
1619
+ }
1620
+
1621
+ class LoadImage:
1622
+ @classmethod
1623
+ def INPUT_TYPES(s):
1624
+ input_dir = folder_paths.get_input_directory()
1625
+ files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
1626
+ files = folder_paths.filter_files_content_types(files, ["image"])
1627
+ return {"required":
1628
+ {"image": (sorted(files), {"image_upload": True})},
1629
+ }
1630
+
1631
+ CATEGORY = "image"
1632
+
1633
+ RETURN_TYPES = ("IMAGE", "MASK")
1634
+ FUNCTION = "load_image"
1635
+ def load_image(self, image):
1636
+ image_path = folder_paths.get_annotated_filepath(image)
1637
+
1638
+ img = node_helpers.pillow(Image.open, image_path)
1639
+
1640
+ output_images = []
1641
+ output_masks = []
1642
+ w, h = None, None
1643
+
1644
+ excluded_formats = ['MPO']
1645
+
1646
+ for i in ImageSequence.Iterator(img):
1647
+ i = node_helpers.pillow(ImageOps.exif_transpose, i)
1648
+
1649
+ if i.mode == 'I':
1650
+ i = i.point(lambda i: i * (1 / 255))
1651
+ image = i.convert("RGB")
1652
+
1653
+ if len(output_images) == 0:
1654
+ w = image.size[0]
1655
+ h = image.size[1]
1656
+
1657
+ if image.size[0] != w or image.size[1] != h:
1658
+ continue
1659
+
1660
+ image = np.array(image).astype(np.float32) / 255.0
1661
+ image = torch.from_numpy(image)[None,]
1662
+ if 'A' in i.getbands():
1663
+ mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
1664
+ mask = 1. - torch.from_numpy(mask)
1665
+ elif i.mode == 'P' and 'transparency' in i.info:
1666
+ mask = np.array(i.convert('RGBA').getchannel('A')).astype(np.float32) / 255.0
1667
+ mask = 1. - torch.from_numpy(mask)
1668
+ else:
1669
+ mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
1670
+ output_images.append(image)
1671
+ output_masks.append(mask.unsqueeze(0))
1672
+
1673
+ if len(output_images) > 1 and img.format not in excluded_formats:
1674
+ output_image = torch.cat(output_images, dim=0)
1675
+ output_mask = torch.cat(output_masks, dim=0)
1676
+ else:
1677
+ output_image = output_images[0]
1678
+ output_mask = output_masks[0]
1679
+
1680
+ return (output_image, output_mask)
1681
+
1682
+ @classmethod
1683
+ def IS_CHANGED(s, image):
1684
+ image_path = folder_paths.get_annotated_filepath(image)
1685
+ m = hashlib.sha256()
1686
+ with open(image_path, 'rb') as f:
1687
+ m.update(f.read())
1688
+ return m.digest().hex()
1689
+
1690
+ @classmethod
1691
+ def VALIDATE_INPUTS(s, image):
1692
+ if not folder_paths.exists_annotated_filepath(image):
1693
+ return "Invalid image file: {}".format(image)
1694
+
1695
+ return True
1696
+
1697
+ class LoadImageMask:
1698
+ _color_channels = ["alpha", "red", "green", "blue"]
1699
+ @classmethod
1700
+ def INPUT_TYPES(s):
1701
+ input_dir = folder_paths.get_input_directory()
1702
+ files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
1703
+ return {"required":
1704
+ {"image": (sorted(files), {"image_upload": True}),
1705
+ "channel": (s._color_channels, ), }
1706
+ }
1707
+
1708
+ CATEGORY = "mask"
1709
+
1710
+ RETURN_TYPES = ("MASK",)
1711
+ FUNCTION = "load_image"
1712
+ def load_image(self, image, channel):
1713
+ image_path = folder_paths.get_annotated_filepath(image)
1714
+ i = node_helpers.pillow(Image.open, image_path)
1715
+ i = node_helpers.pillow(ImageOps.exif_transpose, i)
1716
+ if i.getbands() != ("R", "G", "B", "A"):
1717
+ if i.mode == 'I':
1718
+ i = i.point(lambda i: i * (1 / 255))
1719
+ i = i.convert("RGBA")
1720
+ mask = None
1721
+ c = channel[0].upper()
1722
+ if c in i.getbands():
1723
+ mask = np.array(i.getchannel(c)).astype(np.float32) / 255.0
1724
+ mask = torch.from_numpy(mask)
1725
+ if c == 'A':
1726
+ mask = 1. - mask
1727
+ else:
1728
+ mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
1729
+ return (mask.unsqueeze(0),)
1730
+
1731
+ @classmethod
1732
+ def IS_CHANGED(s, image, channel):
1733
+ image_path = folder_paths.get_annotated_filepath(image)
1734
+ m = hashlib.sha256()
1735
+ with open(image_path, 'rb') as f:
1736
+ m.update(f.read())
1737
+ return m.digest().hex()
1738
+
1739
+ @classmethod
1740
+ def VALIDATE_INPUTS(s, image):
1741
+ if not folder_paths.exists_annotated_filepath(image):
1742
+ return "Invalid image file: {}".format(image)
1743
+
1744
+ return True
1745
+
1746
+
1747
+ class LoadImageOutput(LoadImage):
1748
+ @classmethod
1749
+ def INPUT_TYPES(s):
1750
+ return {
1751
+ "required": {
1752
+ "image": ("COMBO", {
1753
+ "image_upload": True,
1754
+ "image_folder": "output",
1755
+ "remote": {
1756
+ "route": "/internal/files/output",
1757
+ "refresh_button": True,
1758
+ "control_after_refresh": "first",
1759
+ },
1760
+ }),
1761
+ }
1762
+ }
1763
+
1764
+ DESCRIPTION = "Load an image from the output folder. When the refresh button is clicked, the node will update the image list and automatically select the first image, allowing for easy iteration."
1765
+ EXPERIMENTAL = True
1766
+ FUNCTION = "load_image"
1767
+
1768
+
1769
+ class ImageScale:
1770
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
1771
+ crop_methods = ["disabled", "center"]
1772
+
1773
+ @classmethod
1774
+ def INPUT_TYPES(s):
1775
+ return {"required": { "image": ("IMAGE",), "upscale_method": (s.upscale_methods,),
1776
+ "width": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
1777
+ "height": ("INT", {"default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
1778
+ "crop": (s.crop_methods,)}}
1779
+ RETURN_TYPES = ("IMAGE",)
1780
+ FUNCTION = "upscale"
1781
+
1782
+ CATEGORY = "image/upscaling"
1783
+
1784
+ def upscale(self, image, upscale_method, width, height, crop):
1785
+ if width == 0 and height == 0:
1786
+ s = image
1787
+ else:
1788
+ samples = image.movedim(-1,1)
1789
+
1790
+ if width == 0:
1791
+ width = max(1, round(samples.shape[3] * height / samples.shape[2]))
1792
+ elif height == 0:
1793
+ height = max(1, round(samples.shape[2] * width / samples.shape[3]))
1794
+
1795
+ s = comfy.utils.common_upscale(samples, width, height, upscale_method, crop)
1796
+ s = s.movedim(1,-1)
1797
+ return (s,)
1798
+
1799
+ class ImageScaleBy:
1800
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
1801
+
1802
+ @classmethod
1803
+ def INPUT_TYPES(s):
1804
+ return {"required": { "image": ("IMAGE",), "upscale_method": (s.upscale_methods,),
1805
+ "scale_by": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 8.0, "step": 0.01}),}}
1806
+ RETURN_TYPES = ("IMAGE",)
1807
+ FUNCTION = "upscale"
1808
+
1809
+ CATEGORY = "image/upscaling"
1810
+
1811
+ def upscale(self, image, upscale_method, scale_by):
1812
+ samples = image.movedim(-1,1)
1813
+ width = round(samples.shape[3] * scale_by)
1814
+ height = round(samples.shape[2] * scale_by)
1815
+ s = comfy.utils.common_upscale(samples, width, height, upscale_method, "disabled")
1816
+ s = s.movedim(1,-1)
1817
+ return (s,)
1818
+
1819
+ class ImageInvert:
1820
+
1821
+ @classmethod
1822
+ def INPUT_TYPES(s):
1823
+ return {"required": { "image": ("IMAGE",)}}
1824
+
1825
+ RETURN_TYPES = ("IMAGE",)
1826
+ FUNCTION = "invert"
1827
+
1828
+ CATEGORY = "image"
1829
+
1830
+ def invert(self, image):
1831
+ s = 1.0 - image
1832
+ return (s,)
1833
+
1834
+ class ImageBatch:
1835
+
1836
+ @classmethod
1837
+ def INPUT_TYPES(s):
1838
+ return {"required": { "image1": ("IMAGE",), "image2": ("IMAGE",)}}
1839
+
1840
+ RETURN_TYPES = ("IMAGE",)
1841
+ FUNCTION = "batch"
1842
+
1843
+ CATEGORY = "image"
1844
+
1845
+ def batch(self, image1, image2):
1846
+ if image1.shape[1:] != image2.shape[1:]:
1847
+ image2 = comfy.utils.common_upscale(image2.movedim(-1,1), image1.shape[2], image1.shape[1], "bilinear", "center").movedim(1,-1)
1848
+ s = torch.cat((image1, image2), dim=0)
1849
+ return (s,)
1850
+
1851
+ class EmptyImage:
1852
+ def __init__(self, device="cpu"):
1853
+ self.device = device
1854
+
1855
+ @classmethod
1856
+ def INPUT_TYPES(s):
1857
+ return {"required": { "width": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
1858
+ "height": ("INT", {"default": 512, "min": 1, "max": MAX_RESOLUTION, "step": 1}),
1859
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}),
1860
+ "color": ("INT", {"default": 0, "min": 0, "max": 0xFFFFFF, "step": 1, "display": "color"}),
1861
+ }}
1862
+ RETURN_TYPES = ("IMAGE",)
1863
+ FUNCTION = "generate"
1864
+
1865
+ CATEGORY = "image"
1866
+
1867
+ def generate(self, width, height, batch_size=1, color=0):
1868
+ r = torch.full([batch_size, height, width, 1], ((color >> 16) & 0xFF) / 0xFF)
1869
+ g = torch.full([batch_size, height, width, 1], ((color >> 8) & 0xFF) / 0xFF)
1870
+ b = torch.full([batch_size, height, width, 1], ((color) & 0xFF) / 0xFF)
1871
+ return (torch.cat((r, g, b), dim=-1), )
1872
+
1873
+ class ImagePadForOutpaint:
1874
+
1875
+ @classmethod
1876
+ def INPUT_TYPES(s):
1877
+ return {
1878
+ "required": {
1879
+ "image": ("IMAGE",),
1880
+ "left": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1881
+ "top": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1882
+ "right": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1883
+ "bottom": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
1884
+ "feathering": ("INT", {"default": 40, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
1885
+ }
1886
+ }
1887
+
1888
+ RETURN_TYPES = ("IMAGE", "MASK")
1889
+ FUNCTION = "expand_image"
1890
+
1891
+ CATEGORY = "image"
1892
+
1893
+ def expand_image(self, image, left, top, right, bottom, feathering):
1894
+ d1, d2, d3, d4 = image.size()
1895
+
1896
+ new_image = torch.ones(
1897
+ (d1, d2 + top + bottom, d3 + left + right, d4),
1898
+ dtype=torch.float32,
1899
+ ) * 0.5
1900
+
1901
+ new_image[:, top:top + d2, left:left + d3, :] = image
1902
+
1903
+ mask = torch.ones(
1904
+ (d2 + top + bottom, d3 + left + right),
1905
+ dtype=torch.float32,
1906
+ )
1907
+
1908
+ t = torch.zeros(
1909
+ (d2, d3),
1910
+ dtype=torch.float32
1911
+ )
1912
+
1913
+ if feathering > 0 and feathering * 2 < d2 and feathering * 2 < d3:
1914
+
1915
+ for i in range(d2):
1916
+ for j in range(d3):
1917
+ dt = i if top != 0 else d2
1918
+ db = d2 - i if bottom != 0 else d2
1919
+
1920
+ dl = j if left != 0 else d3
1921
+ dr = d3 - j if right != 0 else d3
1922
+
1923
+ d = min(dt, db, dl, dr)
1924
+
1925
+ if d >= feathering:
1926
+ continue
1927
+
1928
+ v = (feathering - d) / feathering
1929
+
1930
+ t[i, j] = v * v
1931
+
1932
+ mask[top:top + d2, left:left + d3] = t
1933
+
1934
+ return (new_image, mask.unsqueeze(0))
1935
+
1936
+
1937
+ NODE_CLASS_MAPPINGS = {
1938
+ "KSampler": KSampler,
1939
+ "CheckpointLoaderSimple": CheckpointLoaderSimple,
1940
+ "CLIPTextEncode": CLIPTextEncode,
1941
+ "CLIPSetLastLayer": CLIPSetLastLayer,
1942
+ "VAEDecode": VAEDecode,
1943
+ "VAEEncode": VAEEncode,
1944
+ "VAEEncodeForInpaint": VAEEncodeForInpaint,
1945
+ "VAELoader": VAELoader,
1946
+ "EmptyLatentImage": EmptyLatentImage,
1947
+ "LatentUpscale": LatentUpscale,
1948
+ "LatentUpscaleBy": LatentUpscaleBy,
1949
+ "LatentFromBatch": LatentFromBatch,
1950
+ "RepeatLatentBatch": RepeatLatentBatch,
1951
+ "SaveImage": SaveImage,
1952
+ "PreviewImage": PreviewImage,
1953
+ "LoadImage": LoadImage,
1954
+ "LoadImageMask": LoadImageMask,
1955
+ "LoadImageOutput": LoadImageOutput,
1956
+ "ImageScale": ImageScale,
1957
+ "ImageScaleBy": ImageScaleBy,
1958
+ "ImageInvert": ImageInvert,
1959
+ "ImageBatch": ImageBatch,
1960
+ "ImagePadForOutpaint": ImagePadForOutpaint,
1961
+ "EmptyImage": EmptyImage,
1962
+ "ConditioningAverage": ConditioningAverage ,
1963
+ "ConditioningCombine": ConditioningCombine,
1964
+ "ConditioningConcat": ConditioningConcat,
1965
+ "ConditioningSetArea": ConditioningSetArea,
1966
+ "ConditioningSetAreaPercentage": ConditioningSetAreaPercentage,
1967
+ "ConditioningSetAreaStrength": ConditioningSetAreaStrength,
1968
+ "ConditioningSetMask": ConditioningSetMask,
1969
+ "KSamplerAdvanced": KSamplerAdvanced,
1970
+ "SetLatentNoiseMask": SetLatentNoiseMask,
1971
+ "LatentComposite": LatentComposite,
1972
+ "LatentBlend": LatentBlend,
1973
+ "LatentRotate": LatentRotate,
1974
+ "LatentFlip": LatentFlip,
1975
+ "LatentCrop": LatentCrop,
1976
+ "LoraLoader": LoraLoader,
1977
+ "CLIPLoader": CLIPLoader,
1978
+ "UNETLoader": UNETLoader,
1979
+ "DualCLIPLoader": DualCLIPLoader,
1980
+ "CLIPVisionEncode": CLIPVisionEncode,
1981
+ "StyleModelApply": StyleModelApply,
1982
+ "unCLIPConditioning": unCLIPConditioning,
1983
+ "ControlNetApply": ControlNetApply,
1984
+ "ControlNetApplyAdvanced": ControlNetApplyAdvanced,
1985
+ "ControlNetLoader": ControlNetLoader,
1986
+ "DiffControlNetLoader": DiffControlNetLoader,
1987
+ "StyleModelLoader": StyleModelLoader,
1988
+ "CLIPVisionLoader": CLIPVisionLoader,
1989
+ "VAEDecodeTiled": VAEDecodeTiled,
1990
+ "VAEEncodeTiled": VAEEncodeTiled,
1991
+ "unCLIPCheckpointLoader": unCLIPCheckpointLoader,
1992
+ "GLIGENLoader": GLIGENLoader,
1993
+ "GLIGENTextBoxApply": GLIGENTextBoxApply,
1994
+ "InpaintModelConditioning": InpaintModelConditioning,
1995
+
1996
+ "CheckpointLoader": CheckpointLoader,
1997
+ "DiffusersLoader": DiffusersLoader,
1998
+
1999
+ "LoadLatent": LoadLatent,
2000
+ "SaveLatent": SaveLatent,
2001
+
2002
+ "ConditioningZeroOut": ConditioningZeroOut,
2003
+ "ConditioningSetTimestepRange": ConditioningSetTimestepRange,
2004
+ "LoraLoaderModelOnly": LoraLoaderModelOnly,
2005
+ }
2006
+
2007
+ NODE_DISPLAY_NAME_MAPPINGS = {
2008
+ # Sampling
2009
+ "KSampler": "KSampler",
2010
+ "KSamplerAdvanced": "KSampler (Advanced)",
2011
+ # Loaders
2012
+ "CheckpointLoader": "Load Checkpoint With Config (DEPRECATED)",
2013
+ "CheckpointLoaderSimple": "Load Checkpoint",
2014
+ "VAELoader": "Load VAE",
2015
+ "LoraLoader": "Load LoRA",
2016
+ "CLIPLoader": "Load CLIP",
2017
+ "ControlNetLoader": "Load ControlNet Model",
2018
+ "DiffControlNetLoader": "Load ControlNet Model (diff)",
2019
+ "StyleModelLoader": "Load Style Model",
2020
+ "CLIPVisionLoader": "Load CLIP Vision",
2021
+ "UpscaleModelLoader": "Load Upscale Model",
2022
+ "UNETLoader": "Load Diffusion Model",
2023
+ # Conditioning
2024
+ "CLIPVisionEncode": "CLIP Vision Encode",
2025
+ "StyleModelApply": "Apply Style Model",
2026
+ "CLIPTextEncode": "CLIP Text Encode (Prompt)",
2027
+ "CLIPSetLastLayer": "CLIP Set Last Layer",
2028
+ "ConditioningCombine": "Conditioning (Combine)",
2029
+ "ConditioningAverage ": "Conditioning (Average)",
2030
+ "ConditioningConcat": "Conditioning (Concat)",
2031
+ "ConditioningSetArea": "Conditioning (Set Area)",
2032
+ "ConditioningSetAreaPercentage": "Conditioning (Set Area with Percentage)",
2033
+ "ConditioningSetMask": "Conditioning (Set Mask)",
2034
+ "ControlNetApply": "Apply ControlNet (OLD)",
2035
+ "ControlNetApplyAdvanced": "Apply ControlNet",
2036
+ # Latent
2037
+ "VAEEncodeForInpaint": "VAE Encode (for Inpainting)",
2038
+ "SetLatentNoiseMask": "Set Latent Noise Mask",
2039
+ "VAEDecode": "VAE Decode",
2040
+ "VAEEncode": "VAE Encode",
2041
+ "LatentRotate": "Rotate Latent",
2042
+ "LatentFlip": "Flip Latent",
2043
+ "LatentCrop": "Crop Latent",
2044
+ "EmptyLatentImage": "Empty Latent Image",
2045
+ "LatentUpscale": "Upscale Latent",
2046
+ "LatentUpscaleBy": "Upscale Latent By",
2047
+ "LatentComposite": "Latent Composite",
2048
+ "LatentBlend": "Latent Blend",
2049
+ "LatentFromBatch" : "Latent From Batch",
2050
+ "RepeatLatentBatch": "Repeat Latent Batch",
2051
+ # Image
2052
+ "SaveImage": "Save Image",
2053
+ "PreviewImage": "Preview Image",
2054
+ "LoadImage": "Load Image",
2055
+ "LoadImageMask": "Load Image (as Mask)",
2056
+ "LoadImageOutput": "Load Image (from Outputs)",
2057
+ "ImageScale": "Upscale Image",
2058
+ "ImageScaleBy": "Upscale Image By",
2059
+ "ImageUpscaleWithModel": "Upscale Image (using Model)",
2060
+ "ImageInvert": "Invert Image",
2061
+ "ImagePadForOutpaint": "Pad Image for Outpainting",
2062
+ "ImageBatch": "Batch Images",
2063
+ "ImageCrop": "Image Crop",
2064
+ "ImageBlend": "Image Blend",
2065
+ "ImageBlur": "Image Blur",
2066
+ "ImageQuantize": "Image Quantize",
2067
+ "ImageSharpen": "Image Sharpen",
2068
+ "ImageScaleToTotalPixels": "Scale Image to Total Pixels",
2069
+ # _for_testing
2070
+ "VAEDecodeTiled": "VAE Decode (Tiled)",
2071
+ "VAEEncodeTiled": "VAE Encode (Tiled)",
2072
+ }
2073
+
2074
+ EXTENSION_WEB_DIRS = {}
2075
+
2076
+ # Dictionary of successfully loaded module names and associated directories.
2077
+ LOADED_MODULE_DIRS = {}
2078
+
2079
+
2080
+ def get_module_name(module_path: str) -> str:
2081
+ """
2082
+ Returns the module name based on the given module path.
2083
+ Examples:
2084
+ get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node.py") -> "my_custom_node"
2085
+ get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node") -> "my_custom_node"
2086
+ get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/") -> "my_custom_node"
2087
+ get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/__init__.py") -> "my_custom_node"
2088
+ get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/__init__") -> "my_custom_node"
2089
+ get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node/__init__/") -> "my_custom_node"
2090
+ get_module_name("C:/Users/username/ComfyUI/custom_nodes/my_custom_node.disabled") -> "custom_nodes
2091
+ Args:
2092
+ module_path (str): The path of the module.
2093
+ Returns:
2094
+ str: The module name.
2095
+ """
2096
+ base_path = os.path.basename(module_path)
2097
+ if os.path.isfile(module_path):
2098
+ base_path = os.path.splitext(base_path)[0]
2099
+ return base_path
2100
+
2101
+
2102
+ def load_custom_node(module_path: str, ignore=set(), module_parent="custom_nodes") -> bool:
2103
+ module_name = get_module_name(module_path)
2104
+ if os.path.isfile(module_path):
2105
+ sp = os.path.splitext(module_path)
2106
+ module_name = sp[0]
2107
+ sys_module_name = module_name
2108
+ elif os.path.isdir(module_path):
2109
+ sys_module_name = module_path.replace(".", "_x_")
2110
+
2111
+ try:
2112
+ logging.debug("Trying to load custom node {}".format(module_path))
2113
+ if os.path.isfile(module_path):
2114
+ module_spec = importlib.util.spec_from_file_location(sys_module_name, module_path)
2115
+ module_dir = os.path.split(module_path)[0]
2116
+ else:
2117
+ module_spec = importlib.util.spec_from_file_location(sys_module_name, os.path.join(module_path, "__init__.py"))
2118
+ module_dir = module_path
2119
+
2120
+ module = importlib.util.module_from_spec(module_spec)
2121
+ sys.modules[sys_module_name] = module
2122
+ module_spec.loader.exec_module(module)
2123
+
2124
+ LOADED_MODULE_DIRS[module_name] = os.path.abspath(module_dir)
2125
+
2126
+ if hasattr(module, "WEB_DIRECTORY") and getattr(module, "WEB_DIRECTORY") is not None:
2127
+ web_dir = os.path.abspath(os.path.join(module_dir, getattr(module, "WEB_DIRECTORY")))
2128
+ if os.path.isdir(web_dir):
2129
+ EXTENSION_WEB_DIRS[module_name] = web_dir
2130
+
2131
+ if hasattr(module, "NODE_CLASS_MAPPINGS") and getattr(module, "NODE_CLASS_MAPPINGS") is not None:
2132
+ for name, node_cls in module.NODE_CLASS_MAPPINGS.items():
2133
+ if name not in ignore:
2134
+ NODE_CLASS_MAPPINGS[name] = node_cls
2135
+ node_cls.RELATIVE_PYTHON_MODULE = "{}.{}".format(module_parent, get_module_name(module_path))
2136
+ if hasattr(module, "NODE_DISPLAY_NAME_MAPPINGS") and getattr(module, "NODE_DISPLAY_NAME_MAPPINGS") is not None:
2137
+ NODE_DISPLAY_NAME_MAPPINGS.update(module.NODE_DISPLAY_NAME_MAPPINGS)
2138
+ return True
2139
+ else:
2140
+ logging.warning(f"Skip {module_path} module for custom nodes due to the lack of NODE_CLASS_MAPPINGS.")
2141
+ return False
2142
+ except Exception as e:
2143
+ logging.warning(traceback.format_exc())
2144
+ logging.warning(f"Cannot import {module_path} module for custom nodes: {e}")
2145
+ return False
2146
+
2147
+ def init_external_custom_nodes():
2148
+ """
2149
+ Initializes the external custom nodes.
2150
+
2151
+ This function loads custom nodes from the specified folder paths and imports them into the application.
2152
+ It measures the import times for each custom node and logs the results.
2153
+
2154
+ Returns:
2155
+ None
2156
+ """
2157
+ base_node_names = set(NODE_CLASS_MAPPINGS.keys())
2158
+ node_paths = folder_paths.get_folder_paths("custom_nodes")
2159
+ node_import_times = []
2160
+ for custom_node_path in node_paths:
2161
+ possible_modules = os.listdir(os.path.realpath(custom_node_path))
2162
+ if "__pycache__" in possible_modules:
2163
+ possible_modules.remove("__pycache__")
2164
+
2165
+ for possible_module in possible_modules:
2166
+ module_path = os.path.join(custom_node_path, possible_module)
2167
+ if os.path.isfile(module_path) and os.path.splitext(module_path)[1] != ".py": continue
2168
+ if module_path.endswith(".disabled"): continue
2169
+ time_before = time.perf_counter()
2170
+ success = load_custom_node(module_path, base_node_names, module_parent="custom_nodes")
2171
+ node_import_times.append((time.perf_counter() - time_before, module_path, success))
2172
+
2173
+ if len(node_import_times) > 0:
2174
+ logging.info("\nImport times for custom nodes:")
2175
+ for n in sorted(node_import_times):
2176
+ if n[2]:
2177
+ import_message = ""
2178
+ else:
2179
+ import_message = " (IMPORT FAILED)"
2180
+ logging.info("{:6.1f} seconds{}: {}".format(n[0], import_message, n[1]))
2181
+ logging.info("")
2182
+
2183
+ def init_builtin_extra_nodes():
2184
+ """
2185
+ Initializes the built-in extra nodes in ComfyUI.
2186
+
2187
+ This function loads the extra node files located in the "comfy_extras" directory and imports them into ComfyUI.
2188
+ If any of the extra node files fail to import, a warning message is logged.
2189
+
2190
+ Returns:
2191
+ None
2192
+ """
2193
+ extras_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_extras")
2194
+ extras_files = [
2195
+ "nodes_latent.py",
2196
+ "nodes_hypernetwork.py",
2197
+ "nodes_upscale_model.py",
2198
+ "nodes_post_processing.py",
2199
+ "nodes_mask.py",
2200
+ "nodes_compositing.py",
2201
+ "nodes_rebatch.py",
2202
+ "nodes_model_merging.py",
2203
+ "nodes_tomesd.py",
2204
+ "nodes_clip_sdxl.py",
2205
+ "nodes_canny.py",
2206
+ "nodes_freelunch.py",
2207
+ "nodes_custom_sampler.py",
2208
+ "nodes_hypertile.py",
2209
+ "nodes_model_advanced.py",
2210
+ "nodes_model_downscale.py",
2211
+ "nodes_images.py",
2212
+ "nodes_video_model.py",
2213
+ "nodes_sag.py",
2214
+ "nodes_perpneg.py",
2215
+ "nodes_stable3d.py",
2216
+ "nodes_sdupscale.py",
2217
+ "nodes_photomaker.py",
2218
+ "nodes_pixart.py",
2219
+ "nodes_cond.py",
2220
+ "nodes_morphology.py",
2221
+ "nodes_stable_cascade.py",
2222
+ "nodes_differential_diffusion.py",
2223
+ "nodes_ip2p.py",
2224
+ "nodes_model_merging_model_specific.py",
2225
+ "nodes_pag.py",
2226
+ "nodes_align_your_steps.py",
2227
+ "nodes_attention_multiply.py",
2228
+ "nodes_advanced_samplers.py",
2229
+ "nodes_webcam.py",
2230
+ "nodes_audio.py",
2231
+ "nodes_sd3.py",
2232
+ "nodes_gits.py",
2233
+ "nodes_controlnet.py",
2234
+ "nodes_hunyuan.py",
2235
+ "nodes_flux.py",
2236
+ "nodes_lora_extract.py",
2237
+ "nodes_torch_compile.py",
2238
+ "nodes_mochi.py",
2239
+ "nodes_slg.py",
2240
+ "nodes_mahiro.py",
2241
+ "nodes_lt.py",
2242
+ "nodes_hooks.py",
2243
+ "nodes_load_3d.py",
2244
+ "nodes_cosmos.py",
2245
+ "nodes_video.py",
2246
+ "nodes_lumina2.py",
2247
+ "nodes_wan.py",
2248
+ "nodes_lotus.py",
2249
+ "nodes_hunyuan3d.py",
2250
+ "nodes_primitive.py",
2251
+ "nodes_cfg.py",
2252
+ "nodes_optimalsteps.py",
2253
+ "nodes_hidream.py",
2254
+ "nodes_fresca.py",
2255
+ "nodes_apg.py",
2256
+ "nodes_preview_any.py",
2257
+ "nodes_ace.py",
2258
+ "nodes_string.py",
2259
+ "nodes_camera_trajectory.py",
2260
+ ]
2261
+
2262
+ import_failed = []
2263
+ for node_file in extras_files:
2264
+ if not load_custom_node(os.path.join(extras_dir, node_file), module_parent="comfy_extras"):
2265
+ import_failed.append(node_file)
2266
+
2267
+ return import_failed
2268
+
2269
+
2270
+ def init_builtin_api_nodes():
2271
+ api_nodes_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "comfy_api_nodes")
2272
+ api_nodes_files = [
2273
+ "nodes_ideogram.py",
2274
+ "nodes_openai.py",
2275
+ "nodes_minimax.py",
2276
+ "nodes_veo2.py",
2277
+ "nodes_kling.py",
2278
+ "nodes_bfl.py",
2279
+ "nodes_luma.py",
2280
+ "nodes_recraft.py",
2281
+ "nodes_pixverse.py",
2282
+ "nodes_stability.py",
2283
+ "nodes_pika.py",
2284
+ ]
2285
+
2286
+ if not load_custom_node(os.path.join(api_nodes_dir, "canary.py"), module_parent="comfy_api_nodes"):
2287
+ return api_nodes_files
2288
+
2289
+ import_failed = []
2290
+ for node_file in api_nodes_files:
2291
+ if not load_custom_node(os.path.join(api_nodes_dir, node_file), module_parent="comfy_api_nodes"):
2292
+ import_failed.append(node_file)
2293
+
2294
+ return import_failed
2295
+
2296
+
2297
+ def init_extra_nodes(init_custom_nodes=True, init_api_nodes=True):
2298
+ import_failed = init_builtin_extra_nodes()
2299
+
2300
+ import_failed_api = []
2301
+ if init_api_nodes:
2302
+ import_failed_api = init_builtin_api_nodes()
2303
+
2304
+ if init_custom_nodes:
2305
+ init_external_custom_nodes()
2306
+ else:
2307
+ logging.info("Skipping loading of custom nodes")
2308
+
2309
+ if len(import_failed_api) > 0:
2310
+ logging.warning("WARNING: some comfy_api_nodes/ nodes did not import correctly. This may be because they are missing some dependencies.\n")
2311
+ for node in import_failed_api:
2312
+ logging.warning("IMPORT FAILED: {}".format(node))
2313
+ logging.warning("\nThis issue might be caused by new missing dependencies added the last time you updated ComfyUI.")
2314
+ if args.windows_standalone_build:
2315
+ logging.warning("Please run the update script: update/update_comfyui.bat")
2316
+ else:
2317
+ logging.warning("Please do a: pip install -r requirements.txt")
2318
+ logging.warning("")
2319
+
2320
+ if len(import_failed) > 0:
2321
+ logging.warning("WARNING: some comfy_extras/ nodes did not import correctly. This may be because they are missing some dependencies.\n")
2322
+ for node in import_failed:
2323
+ logging.warning("IMPORT FAILED: {}".format(node))
2324
+ logging.warning("\nThis issue might be caused by new missing dependencies added the last time you updated ComfyUI.")
2325
+ if args.windows_standalone_build:
2326
+ logging.warning("Please run the update script: update/update_comfyui.bat")
2327
+ else:
2328
+ logging.warning("Please do a: pip install -r requirements.txt")
2329
+ logging.warning("")
2330
+
2331
+ return import_failed
pyproject.toml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "ComfyUI"
3
+ version = "0.3.35"
4
+ readme = "README.md"
5
+ license = { file = "LICENSE" }
6
+ requires-python = ">=3.9"
7
+
8
+ [project.urls]
9
+ homepage = "https://www.comfy.org/"
10
+ repository = "https://github.com/comfyanonymous/ComfyUI"
11
+ documentation = "https://docs.comfy.org/"
12
+
13
+ [tool.ruff]
14
+ lint.select = [
15
+ "N805", # invalid-first-argument-name-for-method
16
+ "S307", # suspicious-eval-usage
17
+ "S102", # exec
18
+ "T", # print-usage
19
+ "W",
20
+ # The "F" series in Ruff stands for "Pyflakes" rules, which catch various Python syntax errors and undefined names.
21
+ # See all rules here: https://docs.astral.sh/ruff/rules/#pyflakes-f
22
+ "F",
23
+ ]
24
+ exclude = ["*.ipynb"]
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,9 +1,9 @@
1
- accelerate
2
- git+https://github.com/huggingface/diffusers.git
3
- torch
4
- gradio
5
- transformers
6
- xformers
7
- sentencepiece
8
- bitsandbytes
9
  peft
 
1
+ accelerate
2
+ git+https://github.com/huggingface/diffusers.git
3
+ torch
4
+ gradio
5
+ transformers
6
+ xformers
7
+ sentencepiece
8
+ bitsandbytes
9
  peft
server.py ADDED
@@ -0,0 +1,893 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 comfyui_version import __version__
31
+ from app.frontend_management import FrontendManager
32
+
33
+ from app.user_manager import UserManager
34
+ from app.model_manager import ModelFileManager
35
+ from app.custom_node_manager import CustomNodeManager
36
+ from typing import Optional, Union
37
+ from api_server.routes.internal.internal_routes import InternalRoutes
38
+
39
+ class BinaryEventTypes:
40
+ PREVIEW_IMAGE = 1
41
+ UNENCODED_PREVIEW_IMAGE = 2
42
+ TEXT = 3
43
+
44
+ async def send_socket_catch_exception(function, message):
45
+ try:
46
+ await function(message)
47
+ except (aiohttp.ClientError, aiohttp.ClientPayloadError, ConnectionResetError, BrokenPipeError, ConnectionError) as err:
48
+ logging.warning("send error: {}".format(err))
49
+
50
+ @web.middleware
51
+ async def cache_control(request: web.Request, handler):
52
+ response: web.Response = await handler(request)
53
+ if request.path.endswith('.js') or request.path.endswith('.css') or request.path.endswith('index.json'):
54
+ response.headers.setdefault('Cache-Control', 'no-cache')
55
+ return response
56
+
57
+
58
+ @web.middleware
59
+ async def compress_body(request: web.Request, handler):
60
+ accept_encoding = request.headers.get("Accept-Encoding", "")
61
+ response: web.Response = await handler(request)
62
+ if not isinstance(response, web.Response):
63
+ return response
64
+ if response.content_type not in ["application/json", "text/plain"]:
65
+ return response
66
+ if response.body and "gzip" in accept_encoding:
67
+ response.enable_compression()
68
+ return response
69
+
70
+
71
+ def create_cors_middleware(allowed_origin: str):
72
+ @web.middleware
73
+ async def cors_middleware(request: web.Request, handler):
74
+ if request.method == "OPTIONS":
75
+ # Pre-flight request. Reply successfully:
76
+ response = web.Response()
77
+ else:
78
+ response = await handler(request)
79
+
80
+ response.headers['Access-Control-Allow-Origin'] = allowed_origin
81
+ response.headers['Access-Control-Allow-Methods'] = 'POST, GET, DELETE, PUT, OPTIONS'
82
+ response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
83
+ response.headers['Access-Control-Allow-Credentials'] = 'true'
84
+ return response
85
+
86
+ return cors_middleware
87
+
88
+ def is_loopback(host):
89
+ if host is None:
90
+ return False
91
+ try:
92
+ if ipaddress.ip_address(host).is_loopback:
93
+ return True
94
+ else:
95
+ return False
96
+ except:
97
+ pass
98
+
99
+ loopback = False
100
+ for family in (socket.AF_INET, socket.AF_INET6):
101
+ try:
102
+ r = socket.getaddrinfo(host, None, family, socket.SOCK_STREAM)
103
+ for family, _, _, _, sockaddr in r:
104
+ if not ipaddress.ip_address(sockaddr[0]).is_loopback:
105
+ return loopback
106
+ else:
107
+ loopback = True
108
+ except socket.gaierror:
109
+ pass
110
+
111
+ return loopback
112
+
113
+
114
+ def create_origin_only_middleware():
115
+ @web.middleware
116
+ async def origin_only_middleware(request: web.Request, handler):
117
+ #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.
118
+ #in that case the Host and Origin hostnames won't match
119
+ #I know the proper fix would be to add a cookie but this should take care of the problem in the meantime
120
+ if 'Host' in request.headers and 'Origin' in request.headers:
121
+ host = request.headers['Host']
122
+ origin = request.headers['Origin']
123
+ host_domain = host.lower()
124
+ parsed = urllib.parse.urlparse(origin)
125
+ origin_domain = parsed.netloc.lower()
126
+ host_domain_parsed = urllib.parse.urlsplit('//' + host_domain)
127
+
128
+ #limit the check to when the host domain is localhost, this makes it slightly less safe but should still prevent the exploit
129
+ loopback = is_loopback(host_domain_parsed.hostname)
130
+
131
+ if parsed.port is None: #if origin doesn't have a port strip it from the host to handle weird browsers, same for host
132
+ host_domain = host_domain_parsed.hostname
133
+ if host_domain_parsed.port is None:
134
+ origin_domain = parsed.hostname
135
+
136
+ if loopback and host_domain is not None and origin_domain is not None and len(host_domain) > 0 and len(origin_domain) > 0:
137
+ if host_domain != origin_domain:
138
+ logging.warning("WARNING: request with non matching host and origin {} != {}, returning 403".format(host_domain, origin_domain))
139
+ return web.Response(status=403)
140
+
141
+ if request.method == "OPTIONS":
142
+ response = web.Response()
143
+ else:
144
+ response = await handler(request)
145
+
146
+ return response
147
+
148
+ return origin_only_middleware
149
+
150
+ class PromptServer():
151
+ def __init__(self, loop):
152
+ PromptServer.instance = self
153
+
154
+ mimetypes.init()
155
+ mimetypes.add_type('application/javascript; charset=utf-8', '.js')
156
+ mimetypes.add_type('image/webp', '.webp')
157
+
158
+ self.user_manager = UserManager()
159
+ self.model_file_manager = ModelFileManager()
160
+ self.custom_node_manager = CustomNodeManager()
161
+ self.internal_routes = InternalRoutes(self)
162
+ self.supports = ["custom_nodes_from_web"]
163
+ self.prompt_queue = execution.PromptQueue(self)
164
+ self.loop = loop
165
+ self.messages = asyncio.Queue()
166
+ self.client_session:Optional[aiohttp.ClientSession] = None
167
+ self.number = 0
168
+
169
+ middlewares = [cache_control]
170
+ if args.enable_compress_response_body:
171
+ middlewares.append(compress_body)
172
+
173
+ if args.enable_cors_header:
174
+ middlewares.append(create_cors_middleware(args.enable_cors_header))
175
+ else:
176
+ middlewares.append(create_origin_only_middleware())
177
+
178
+ max_upload_size = round(args.max_upload_size * 1024 * 1024)
179
+ self.app = web.Application(client_max_size=max_upload_size, middlewares=middlewares)
180
+ self.sockets = dict()
181
+ self.web_root = (
182
+ FrontendManager.init_frontend(args.front_end_version)
183
+ if args.front_end_root is None
184
+ else args.front_end_root
185
+ )
186
+ logging.info(f"[Prompt Server] web root: {self.web_root}")
187
+ routes = web.RouteTableDef()
188
+ self.routes = routes
189
+ self.last_node_id = None
190
+ self.client_id = None
191
+
192
+ self.on_prompt_handlers = []
193
+
194
+ @routes.get('/ws')
195
+ async def websocket_handler(request):
196
+ ws = web.WebSocketResponse()
197
+ await ws.prepare(request)
198
+ sid = request.rel_url.query.get('clientId', '')
199
+ if sid:
200
+ # Reusing existing session, remove old
201
+ self.sockets.pop(sid, None)
202
+ else:
203
+ sid = uuid.uuid4().hex
204
+
205
+ self.sockets[sid] = ws
206
+
207
+ try:
208
+ # Send initial state to the new client
209
+ await self.send("status", { "status": self.get_queue_info(), 'sid': sid }, sid)
210
+ # On reconnect if we are the currently executing client send the current node
211
+ if self.client_id == sid and self.last_node_id is not None:
212
+ await self.send("executing", { "node": self.last_node_id }, sid)
213
+
214
+ async for msg in ws:
215
+ if msg.type == aiohttp.WSMsgType.ERROR:
216
+ logging.warning('ws connection closed with exception %s' % ws.exception())
217
+ finally:
218
+ self.sockets.pop(sid, None)
219
+ return ws
220
+
221
+ @routes.get("/")
222
+ async def get_root(request):
223
+ response = web.FileResponse(os.path.join(self.web_root, "index.html"))
224
+ response.headers['Cache-Control'] = 'no-cache'
225
+ response.headers["Pragma"] = "no-cache"
226
+ response.headers["Expires"] = "0"
227
+ return response
228
+
229
+ @routes.get("/embeddings")
230
+ def get_embeddings(request):
231
+ embeddings = folder_paths.get_filename_list("embeddings")
232
+ return web.json_response(list(map(lambda a: os.path.splitext(a)[0], embeddings)))
233
+
234
+ @routes.get("/models")
235
+ def list_model_types(request):
236
+ model_types = list(folder_paths.folder_names_and_paths.keys())
237
+
238
+ return web.json_response(model_types)
239
+
240
+ @routes.get("/models/{folder}")
241
+ async def get_models(request):
242
+ folder = request.match_info.get("folder", None)
243
+ if not folder in folder_paths.folder_names_and_paths:
244
+ return web.Response(status=404)
245
+ files = folder_paths.get_filename_list(folder)
246
+ return web.json_response(files)
247
+
248
+ @routes.get("/extensions")
249
+ async def get_extensions(request):
250
+ files = glob.glob(os.path.join(
251
+ glob.escape(self.web_root), 'extensions/**/*.js'), recursive=True)
252
+
253
+ extensions = list(map(lambda f: "/" + os.path.relpath(f, self.web_root).replace("\\", "/"), files))
254
+
255
+ for name, dir in nodes.EXTENSION_WEB_DIRS.items():
256
+ files = glob.glob(os.path.join(glob.escape(dir), '**/*.js'), recursive=True)
257
+ extensions.extend(list(map(lambda f: "/extensions/" + urllib.parse.quote(
258
+ name) + "/" + os.path.relpath(f, dir).replace("\\", "/"), files)))
259
+
260
+ return web.json_response(extensions)
261
+
262
+ def get_dir_by_type(dir_type):
263
+ if dir_type is None:
264
+ dir_type = "input"
265
+
266
+ if dir_type == "input":
267
+ type_dir = folder_paths.get_input_directory()
268
+ elif dir_type == "temp":
269
+ type_dir = folder_paths.get_temp_directory()
270
+ elif dir_type == "output":
271
+ type_dir = folder_paths.get_output_directory()
272
+
273
+ return type_dir, dir_type
274
+
275
+ def compare_image_hash(filepath, image):
276
+ hasher = node_helpers.hasher()
277
+
278
+ # function to compare hashes of two images to see if it already exists, fix to #3465
279
+ if os.path.exists(filepath):
280
+ a = hasher()
281
+ b = hasher()
282
+ with open(filepath, "rb") as f:
283
+ a.update(f.read())
284
+ b.update(image.file.read())
285
+ image.file.seek(0)
286
+ return a.hexdigest() == b.hexdigest()
287
+ return False
288
+
289
+ def image_upload(post, image_save_function=None):
290
+ image = post.get("image")
291
+ overwrite = post.get("overwrite")
292
+ image_is_duplicate = False
293
+
294
+ image_upload_type = post.get("type")
295
+ upload_dir, image_upload_type = get_dir_by_type(image_upload_type)
296
+
297
+ if image and image.file:
298
+ filename = image.filename
299
+ if not filename:
300
+ return web.Response(status=400)
301
+
302
+ subfolder = post.get("subfolder", "")
303
+ full_output_folder = os.path.join(upload_dir, os.path.normpath(subfolder))
304
+ filepath = os.path.abspath(os.path.join(full_output_folder, filename))
305
+
306
+ if os.path.commonpath((upload_dir, filepath)) != upload_dir:
307
+ return web.Response(status=400)
308
+
309
+ if not os.path.exists(full_output_folder):
310
+ os.makedirs(full_output_folder)
311
+
312
+ split = os.path.splitext(filename)
313
+
314
+ if overwrite is not None and (overwrite == "true" or overwrite == "1"):
315
+ pass
316
+ else:
317
+ i = 1
318
+ while os.path.exists(filepath):
319
+ if compare_image_hash(filepath, image): #compare hash to prevent saving of duplicates with same name, fix for #3465
320
+ image_is_duplicate = True
321
+ break
322
+ filename = f"{split[0]} ({i}){split[1]}"
323
+ filepath = os.path.join(full_output_folder, filename)
324
+ i += 1
325
+
326
+ if not image_is_duplicate:
327
+ if image_save_function is not None:
328
+ image_save_function(image, post, filepath)
329
+ else:
330
+ with open(filepath, "wb") as f:
331
+ f.write(image.file.read())
332
+
333
+ return web.json_response({"name" : filename, "subfolder": subfolder, "type": image_upload_type})
334
+ else:
335
+ return web.Response(status=400)
336
+
337
+ @routes.post("/upload/image")
338
+ async def upload_image(request):
339
+ post = await request.post()
340
+ return image_upload(post)
341
+
342
+
343
+ @routes.post("/upload/mask")
344
+ async def upload_mask(request):
345
+ post = await request.post()
346
+
347
+ def image_save_function(image, post, filepath):
348
+ original_ref = json.loads(post.get("original_ref"))
349
+ filename, output_dir = folder_paths.annotated_filepath(original_ref['filename'])
350
+
351
+ if not filename:
352
+ return web.Response(status=400)
353
+
354
+ # validation for security: prevent accessing arbitrary path
355
+ if filename[0] == '/' or '..' in filename:
356
+ return web.Response(status=400)
357
+
358
+ if output_dir is None:
359
+ type = original_ref.get("type", "output")
360
+ output_dir = folder_paths.get_directory_by_type(type)
361
+
362
+ if output_dir is None:
363
+ return web.Response(status=400)
364
+
365
+ if original_ref.get("subfolder", "") != "":
366
+ full_output_dir = os.path.join(output_dir, original_ref["subfolder"])
367
+ if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir:
368
+ return web.Response(status=403)
369
+ output_dir = full_output_dir
370
+
371
+ file = os.path.join(output_dir, filename)
372
+
373
+ if os.path.isfile(file):
374
+ with Image.open(file) as original_pil:
375
+ metadata = PngInfo()
376
+ if hasattr(original_pil,'text'):
377
+ for key in original_pil.text:
378
+ metadata.add_text(key, original_pil.text[key])
379
+ original_pil = original_pil.convert('RGBA')
380
+ mask_pil = Image.open(image.file).convert('RGBA')
381
+
382
+ # alpha copy
383
+ new_alpha = mask_pil.getchannel('A')
384
+ original_pil.putalpha(new_alpha)
385
+ original_pil.save(filepath, compress_level=4, pnginfo=metadata)
386
+
387
+ return image_upload(post, image_save_function)
388
+
389
+ @routes.get("/view")
390
+ async def view_image(request):
391
+ if "filename" in request.rel_url.query:
392
+ filename = request.rel_url.query["filename"]
393
+ filename,output_dir = folder_paths.annotated_filepath(filename)
394
+
395
+ if not filename:
396
+ return web.Response(status=400)
397
+
398
+ # validation for security: prevent accessing arbitrary path
399
+ if filename[0] == '/' or '..' in filename:
400
+ return web.Response(status=400)
401
+
402
+ if output_dir is None:
403
+ type = request.rel_url.query.get("type", "output")
404
+ output_dir = folder_paths.get_directory_by_type(type)
405
+
406
+ if output_dir is None:
407
+ return web.Response(status=400)
408
+
409
+ if "subfolder" in request.rel_url.query:
410
+ full_output_dir = os.path.join(output_dir, request.rel_url.query["subfolder"])
411
+ if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir:
412
+ return web.Response(status=403)
413
+ output_dir = full_output_dir
414
+
415
+ filename = os.path.basename(filename)
416
+ file = os.path.join(output_dir, filename)
417
+
418
+ if os.path.isfile(file):
419
+ if 'preview' in request.rel_url.query:
420
+ with Image.open(file) as img:
421
+ preview_info = request.rel_url.query['preview'].split(';')
422
+ image_format = preview_info[0]
423
+ if image_format not in ['webp', 'jpeg'] or 'a' in request.rel_url.query.get('channel', ''):
424
+ image_format = 'webp'
425
+
426
+ quality = 90
427
+ if preview_info[-1].isdigit():
428
+ quality = int(preview_info[-1])
429
+
430
+ buffer = BytesIO()
431
+ if image_format in ['jpeg'] or request.rel_url.query.get('channel', '') == 'rgb':
432
+ img = img.convert("RGB")
433
+ img.save(buffer, format=image_format, quality=quality)
434
+ buffer.seek(0)
435
+
436
+ return web.Response(body=buffer.read(), content_type=f'image/{image_format}',
437
+ headers={"Content-Disposition": f"filename=\"{filename}\""})
438
+
439
+ if 'channel' not in request.rel_url.query:
440
+ channel = 'rgba'
441
+ else:
442
+ channel = request.rel_url.query["channel"]
443
+
444
+ if channel == 'rgb':
445
+ with Image.open(file) as img:
446
+ if img.mode == "RGBA":
447
+ r, g, b, a = img.split()
448
+ new_img = Image.merge('RGB', (r, g, b))
449
+ else:
450
+ new_img = img.convert("RGB")
451
+
452
+ buffer = BytesIO()
453
+ new_img.save(buffer, format='PNG')
454
+ buffer.seek(0)
455
+
456
+ return web.Response(body=buffer.read(), content_type='image/png',
457
+ headers={"Content-Disposition": f"filename=\"{filename}\""})
458
+
459
+ elif channel == 'a':
460
+ with Image.open(file) as img:
461
+ if img.mode == "RGBA":
462
+ _, _, _, a = img.split()
463
+ else:
464
+ a = Image.new('L', img.size, 255)
465
+
466
+ # alpha img
467
+ alpha_img = Image.new('RGBA', img.size)
468
+ alpha_img.putalpha(a)
469
+ alpha_buffer = BytesIO()
470
+ alpha_img.save(alpha_buffer, format='PNG')
471
+ alpha_buffer.seek(0)
472
+
473
+ return web.Response(body=alpha_buffer.read(), content_type='image/png',
474
+ headers={"Content-Disposition": f"filename=\"{filename}\""})
475
+ else:
476
+ # Get content type from mimetype, defaulting to 'application/octet-stream'
477
+ content_type = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
478
+
479
+ # For security, force certain extensions to download instead of display
480
+ file_extension = os.path.splitext(filename)[1].lower()
481
+ if file_extension in {'.html', '.htm', '.js', '.css'}:
482
+ content_type = 'application/octet-stream' # Forces download
483
+
484
+ return web.FileResponse(
485
+ file,
486
+ headers={
487
+ "Content-Disposition": f"filename=\"{filename}\"",
488
+ "Content-Type": content_type
489
+ }
490
+ )
491
+
492
+ return web.Response(status=404)
493
+
494
+ @routes.get("/view_metadata/{folder_name}")
495
+ async def view_metadata(request):
496
+ folder_name = request.match_info.get("folder_name", None)
497
+ if folder_name is None:
498
+ return web.Response(status=404)
499
+ if not "filename" in request.rel_url.query:
500
+ return web.Response(status=404)
501
+
502
+ filename = request.rel_url.query["filename"]
503
+ if not filename.endswith(".safetensors"):
504
+ return web.Response(status=404)
505
+
506
+ safetensors_path = folder_paths.get_full_path(folder_name, filename)
507
+ if safetensors_path is None:
508
+ return web.Response(status=404)
509
+ out = comfy.utils.safetensors_header(safetensors_path, max_size=1024*1024)
510
+ if out is None:
511
+ return web.Response(status=404)
512
+ dt = json.loads(out)
513
+ if not "__metadata__" in dt:
514
+ return web.Response(status=404)
515
+ return web.json_response(dt["__metadata__"])
516
+
517
+ @routes.get("/system_stats")
518
+ async def system_stats(request):
519
+ device = comfy.model_management.get_torch_device()
520
+ device_name = comfy.model_management.get_torch_device_name(device)
521
+ cpu_device = comfy.model_management.torch.device("cpu")
522
+ ram_total = comfy.model_management.get_total_memory(cpu_device)
523
+ ram_free = comfy.model_management.get_free_memory(cpu_device)
524
+ vram_total, torch_vram_total = comfy.model_management.get_total_memory(device, torch_total_too=True)
525
+ vram_free, torch_vram_free = comfy.model_management.get_free_memory(device, torch_free_too=True)
526
+
527
+ system_stats = {
528
+ "system": {
529
+ "os": os.name,
530
+ "ram_total": ram_total,
531
+ "ram_free": ram_free,
532
+ "comfyui_version": __version__,
533
+ "python_version": sys.version,
534
+ "pytorch_version": comfy.model_management.torch_version,
535
+ "embedded_python": os.path.split(os.path.split(sys.executable)[0])[1] == "python_embeded",
536
+ "argv": sys.argv
537
+ },
538
+ "devices": [
539
+ {
540
+ "name": device_name,
541
+ "type": device.type,
542
+ "index": device.index,
543
+ "vram_total": vram_total,
544
+ "vram_free": vram_free,
545
+ "torch_vram_total": torch_vram_total,
546
+ "torch_vram_free": torch_vram_free,
547
+ }
548
+ ]
549
+ }
550
+ return web.json_response(system_stats)
551
+
552
+ @routes.get("/prompt")
553
+ async def get_prompt(request):
554
+ return web.json_response(self.get_queue_info())
555
+
556
+ def node_info(node_class):
557
+ obj_class = nodes.NODE_CLASS_MAPPINGS[node_class]
558
+ info = {}
559
+ info['input'] = obj_class.INPUT_TYPES()
560
+ info['input_order'] = {key: list(value.keys()) for (key, value) in obj_class.INPUT_TYPES().items()}
561
+ info['output'] = obj_class.RETURN_TYPES
562
+ info['output_is_list'] = obj_class.OUTPUT_IS_LIST if hasattr(obj_class, 'OUTPUT_IS_LIST') else [False] * len(obj_class.RETURN_TYPES)
563
+ info['output_name'] = obj_class.RETURN_NAMES if hasattr(obj_class, 'RETURN_NAMES') else info['output']
564
+ info['name'] = node_class
565
+ info['display_name'] = nodes.NODE_DISPLAY_NAME_MAPPINGS[node_class] if node_class in nodes.NODE_DISPLAY_NAME_MAPPINGS.keys() else node_class
566
+ info['description'] = obj_class.DESCRIPTION if hasattr(obj_class,'DESCRIPTION') else ''
567
+ info['python_module'] = getattr(obj_class, "RELATIVE_PYTHON_MODULE", "nodes")
568
+ info['category'] = 'sd'
569
+ if hasattr(obj_class, 'OUTPUT_NODE') and obj_class.OUTPUT_NODE == True:
570
+ info['output_node'] = True
571
+ else:
572
+ info['output_node'] = False
573
+
574
+ if hasattr(obj_class, 'CATEGORY'):
575
+ info['category'] = obj_class.CATEGORY
576
+
577
+ if hasattr(obj_class, 'OUTPUT_TOOLTIPS'):
578
+ info['output_tooltips'] = obj_class.OUTPUT_TOOLTIPS
579
+
580
+ if getattr(obj_class, "DEPRECATED", False):
581
+ info['deprecated'] = True
582
+ if getattr(obj_class, "EXPERIMENTAL", False):
583
+ info['experimental'] = True
584
+
585
+ if hasattr(obj_class, 'API_NODE'):
586
+ info['api_node'] = obj_class.API_NODE
587
+ return info
588
+
589
+ @routes.get("/object_info")
590
+ async def get_object_info(request):
591
+ with folder_paths.cache_helper:
592
+ out = {}
593
+ for x in nodes.NODE_CLASS_MAPPINGS:
594
+ try:
595
+ out[x] = node_info(x)
596
+ except Exception:
597
+ logging.error(f"[ERROR] An error occurred while retrieving information for the '{x}' node.")
598
+ logging.error(traceback.format_exc())
599
+ return web.json_response(out)
600
+
601
+ @routes.get("/object_info/{node_class}")
602
+ async def get_object_info_node(request):
603
+ node_class = request.match_info.get("node_class", None)
604
+ out = {}
605
+ if (node_class is not None) and (node_class in nodes.NODE_CLASS_MAPPINGS):
606
+ out[node_class] = node_info(node_class)
607
+ return web.json_response(out)
608
+
609
+ @routes.get("/history")
610
+ async def get_history(request):
611
+ max_items = request.rel_url.query.get("max_items", None)
612
+ if max_items is not None:
613
+ max_items = int(max_items)
614
+ return web.json_response(self.prompt_queue.get_history(max_items=max_items))
615
+
616
+ @routes.get("/history/{prompt_id}")
617
+ async def get_history_prompt_id(request):
618
+ prompt_id = request.match_info.get("prompt_id", None)
619
+ return web.json_response(self.prompt_queue.get_history(prompt_id=prompt_id))
620
+
621
+ @routes.get("/queue")
622
+ async def get_queue(request):
623
+ queue_info = {}
624
+ current_queue = self.prompt_queue.get_current_queue_volatile()
625
+ queue_info['queue_running'] = current_queue[0]
626
+ queue_info['queue_pending'] = current_queue[1]
627
+ return web.json_response(queue_info)
628
+
629
+ @routes.post("/prompt")
630
+ async def post_prompt(request):
631
+ logging.info("got prompt")
632
+ json_data = await request.json()
633
+ json_data = self.trigger_on_prompt(json_data)
634
+
635
+ if "number" in json_data:
636
+ number = float(json_data['number'])
637
+ else:
638
+ number = self.number
639
+ if "front" in json_data:
640
+ if json_data['front']:
641
+ number = -number
642
+
643
+ self.number += 1
644
+
645
+ if "prompt" in json_data:
646
+ prompt = json_data["prompt"]
647
+ valid = execution.validate_prompt(prompt)
648
+ extra_data = {}
649
+ if "extra_data" in json_data:
650
+ extra_data = json_data["extra_data"]
651
+
652
+ if "client_id" in json_data:
653
+ extra_data["client_id"] = json_data["client_id"]
654
+ if valid[0]:
655
+ prompt_id = str(uuid.uuid4())
656
+ outputs_to_execute = valid[2]
657
+ self.prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute))
658
+ response = {"prompt_id": prompt_id, "number": number, "node_errors": valid[3]}
659
+ return web.json_response(response)
660
+ else:
661
+ logging.warning("invalid prompt: {}".format(valid[1]))
662
+ return web.json_response({"error": valid[1], "node_errors": valid[3]}, status=400)
663
+ else:
664
+ error = {
665
+ "type": "no_prompt",
666
+ "message": "No prompt provided",
667
+ "details": "No prompt provided",
668
+ "extra_info": {}
669
+ }
670
+ return web.json_response({"error": error, "node_errors": {}}, status=400)
671
+
672
+ @routes.post("/queue")
673
+ async def post_queue(request):
674
+ json_data = await request.json()
675
+ if "clear" in json_data:
676
+ if json_data["clear"]:
677
+ self.prompt_queue.wipe_queue()
678
+ if "delete" in json_data:
679
+ to_delete = json_data['delete']
680
+ for id_to_delete in to_delete:
681
+ delete_func = lambda a: a[1] == id_to_delete
682
+ self.prompt_queue.delete_queue_item(delete_func)
683
+
684
+ return web.Response(status=200)
685
+
686
+ @routes.post("/interrupt")
687
+ async def post_interrupt(request):
688
+ nodes.interrupt_processing()
689
+ return web.Response(status=200)
690
+
691
+ @routes.post("/free")
692
+ async def post_free(request):
693
+ json_data = await request.json()
694
+ unload_models = json_data.get("unload_models", False)
695
+ free_memory = json_data.get("free_memory", False)
696
+ if unload_models:
697
+ self.prompt_queue.set_flag("unload_models", unload_models)
698
+ if free_memory:
699
+ self.prompt_queue.set_flag("free_memory", free_memory)
700
+ return web.Response(status=200)
701
+
702
+ @routes.post("/history")
703
+ async def post_history(request):
704
+ json_data = await request.json()
705
+ if "clear" in json_data:
706
+ if json_data["clear"]:
707
+ self.prompt_queue.wipe_history()
708
+ if "delete" in json_data:
709
+ to_delete = json_data['delete']
710
+ for id_to_delete in to_delete:
711
+ self.prompt_queue.delete_history_item(id_to_delete)
712
+
713
+ return web.Response(status=200)
714
+
715
+ async def setup(self):
716
+ timeout = aiohttp.ClientTimeout(total=None) # no timeout
717
+ self.client_session = aiohttp.ClientSession(timeout=timeout)
718
+
719
+ def add_routes(self):
720
+ self.user_manager.add_routes(self.routes)
721
+ self.model_file_manager.add_routes(self.routes)
722
+ self.custom_node_manager.add_routes(self.routes, self.app, nodes.LOADED_MODULE_DIRS.items())
723
+ self.app.add_subapp('/internal', self.internal_routes.get_app())
724
+
725
+ # Prefix every route with /api for easier matching for delegation.
726
+ # This is very useful for frontend dev server, which need to forward
727
+ # everything except serving of static files.
728
+ # Currently both the old endpoints without prefix and new endpoints with
729
+ # prefix are supported.
730
+ api_routes = web.RouteTableDef()
731
+ for route in self.routes:
732
+ # Custom nodes might add extra static routes. Only process non-static
733
+ # routes to add /api prefix.
734
+ if isinstance(route, web.RouteDef):
735
+ api_routes.route(route.method, "/api" + route.path)(route.handler, **route.kwargs)
736
+ self.app.add_routes(api_routes)
737
+ self.app.add_routes(self.routes)
738
+
739
+ # Add routes from web extensions.
740
+ for name, dir in nodes.EXTENSION_WEB_DIRS.items():
741
+ self.app.add_routes([web.static('/extensions/' + name, dir)])
742
+
743
+ workflow_templates_path = FrontendManager.templates_path()
744
+ if workflow_templates_path:
745
+ self.app.add_routes([
746
+ web.static('/templates', workflow_templates_path)
747
+ ])
748
+
749
+ self.app.add_routes([
750
+ web.static('/', self.web_root),
751
+ ])
752
+
753
+ def get_queue_info(self):
754
+ prompt_info = {}
755
+ exec_info = {}
756
+ exec_info['queue_remaining'] = self.prompt_queue.get_tasks_remaining()
757
+ prompt_info['exec_info'] = exec_info
758
+ return prompt_info
759
+
760
+ async def send(self, event, data, sid=None):
761
+ if event == BinaryEventTypes.UNENCODED_PREVIEW_IMAGE:
762
+ await self.send_image(data, sid=sid)
763
+ elif isinstance(data, (bytes, bytearray)):
764
+ await self.send_bytes(event, data, sid)
765
+ else:
766
+ await self.send_json(event, data, sid)
767
+
768
+ def encode_bytes(self, event, data):
769
+ if not isinstance(event, int):
770
+ raise RuntimeError(f"Binary event types must be integers, got {event}")
771
+
772
+ packed = struct.pack(">I", event)
773
+ message = bytearray(packed)
774
+ message.extend(data)
775
+ return message
776
+
777
+ async def send_image(self, image_data, sid=None):
778
+ image_type = image_data[0]
779
+ image = image_data[1]
780
+ max_size = image_data[2]
781
+ if max_size is not None:
782
+ if hasattr(Image, 'Resampling'):
783
+ resampling = Image.Resampling.BILINEAR
784
+ else:
785
+ resampling = Image.ANTIALIAS
786
+
787
+ image = ImageOps.contain(image, (max_size, max_size), resampling)
788
+ type_num = 1
789
+ if image_type == "JPEG":
790
+ type_num = 1
791
+ elif image_type == "PNG":
792
+ type_num = 2
793
+
794
+ bytesIO = BytesIO()
795
+ header = struct.pack(">I", type_num)
796
+ bytesIO.write(header)
797
+ image.save(bytesIO, format=image_type, quality=95, compress_level=1)
798
+ preview_bytes = bytesIO.getvalue()
799
+ await self.send_bytes(BinaryEventTypes.PREVIEW_IMAGE, preview_bytes, sid=sid)
800
+
801
+ async def send_bytes(self, event, data, sid=None):
802
+ message = self.encode_bytes(event, data)
803
+
804
+ if sid is None:
805
+ sockets = list(self.sockets.values())
806
+ for ws in sockets:
807
+ await send_socket_catch_exception(ws.send_bytes, message)
808
+ elif sid in self.sockets:
809
+ await send_socket_catch_exception(self.sockets[sid].send_bytes, message)
810
+
811
+ async def send_json(self, event, data, sid=None):
812
+ message = {"type": event, "data": data}
813
+
814
+ if sid is None:
815
+ sockets = list(self.sockets.values())
816
+ for ws in sockets:
817
+ await send_socket_catch_exception(ws.send_json, message)
818
+ elif sid in self.sockets:
819
+ await send_socket_catch_exception(self.sockets[sid].send_json, message)
820
+
821
+ def send_sync(self, event, data, sid=None):
822
+ self.loop.call_soon_threadsafe(
823
+ self.messages.put_nowait, (event, data, sid))
824
+
825
+ def queue_updated(self):
826
+ self.send_sync("status", { "status": self.get_queue_info() })
827
+
828
+ async def publish_loop(self):
829
+ while True:
830
+ msg = await self.messages.get()
831
+ await self.send(*msg)
832
+
833
+ async def start(self, address, port, verbose=True, call_on_start=None):
834
+ await self.start_multi_address([(address, port)], call_on_start=call_on_start)
835
+
836
+ async def start_multi_address(self, addresses, call_on_start=None, verbose=True):
837
+ runner = web.AppRunner(self.app, access_log=None)
838
+ await runner.setup()
839
+ ssl_ctx = None
840
+ scheme = "http"
841
+ if args.tls_keyfile and args.tls_certfile:
842
+ ssl_ctx = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_SERVER, verify_mode=ssl.CERT_NONE)
843
+ ssl_ctx.load_cert_chain(certfile=args.tls_certfile,
844
+ keyfile=args.tls_keyfile)
845
+ scheme = "https"
846
+
847
+ if verbose:
848
+ logging.info("Starting server\n")
849
+ for addr in addresses:
850
+ address = addr[0]
851
+ port = addr[1]
852
+ site = web.TCPSite(runner, address, port, ssl_context=ssl_ctx)
853
+ await site.start()
854
+
855
+ if not hasattr(self, 'address'):
856
+ self.address = address #TODO: remove this
857
+ self.port = port
858
+
859
+ if ':' in address:
860
+ address_print = "[{}]".format(address)
861
+ else:
862
+ address_print = address
863
+
864
+ if verbose:
865
+ logging.info("To see the GUI go to: {}://{}:{}".format(scheme, address_print, port))
866
+
867
+ if call_on_start is not None:
868
+ call_on_start(scheme, self.address, self.port)
869
+
870
+ def add_on_prompt_handler(self, handler):
871
+ self.on_prompt_handlers.append(handler)
872
+
873
+ def trigger_on_prompt(self, json_data):
874
+ for handler in self.on_prompt_handlers:
875
+ try:
876
+ json_data = handler(json_data)
877
+ except Exception:
878
+ logging.warning("[ERROR] An error occurred during the on_prompt_handler processing")
879
+ logging.warning(traceback.format_exc())
880
+
881
+ return json_data
882
+
883
+ def send_progress_text(
884
+ self, text: Union[bytes, bytearray, str], node_id: str, sid=None
885
+ ):
886
+ if isinstance(text, str):
887
+ text = text.encode("utf-8")
888
+ node_id_bytes = str(node_id).encode("utf-8")
889
+
890
+ # Pack the node_id length as a 4-byte unsigned integer, followed by the node_id bytes
891
+ message = struct.pack(">I", len(node_id_bytes)) + node_id_bytes + text
892
+
893
+ self.send_sync(BinaryEventTypes.TEXT, message, sid)