hxrron commited on
Commit
85fbb27
·
verified ·
1 Parent(s): f17396d

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. .gitignore +39 -0
  2. ComfyUI/.gitattributes +2 -0
  3. ComfyUI/.gitignore +26 -0
  4. ComfyUI/CODEOWNERS +24 -0
  5. ComfyUI/CONTRIBUTING.md +41 -0
  6. ComfyUI/LICENSE +674 -0
  7. ComfyUI/README.md +400 -0
  8. ComfyUI/alembic.ini +84 -0
  9. ComfyUI/comfyui_version.py +3 -0
  10. ComfyUI/cuda_malloc.py +90 -0
  11. ComfyUI/execution.py +1044 -0
  12. ComfyUI/extra_model_paths.yaml.example +47 -0
  13. ComfyUI/folder_paths.py +425 -0
  14. ComfyUI/hook_breaker_ac10a0.py +17 -0
  15. ComfyUI/latent_preview.py +108 -0
  16. ComfyUI/main.py +323 -0
  17. ComfyUI/new_updater.py +35 -0
  18. ComfyUI/node_helpers.py +60 -0
  19. ComfyUI/nodes.py +0 -0
  20. ComfyUI/pyproject.toml +24 -0
  21. ComfyUI/pytest.ini +9 -0
  22. ComfyUI/requirements.txt +30 -0
  23. ComfyUI/server.py +899 -0
  24. README_VERY_IMPORTANT.txt +31 -0
  25. Read Me 2.txt +0 -0
  26. Workflow's/catvton_example.json +323 -0
  27. python_embeded/LICENSE.txt +702 -0
  28. python_embeded/_asyncio.pyd +0 -0
  29. python_embeded/_bz2.pyd +0 -0
  30. python_embeded/_hashlib.pyd +0 -0
  31. python_embeded/_msi.pyd +0 -0
  32. python_embeded/_multiprocessing.pyd +0 -0
  33. python_embeded/_overlapped.pyd +0 -0
  34. python_embeded/_queue.pyd +0 -0
  35. python_embeded/_socket.pyd +0 -0
  36. python_embeded/_uuid.pyd +0 -0
  37. python_embeded/_wmi.pyd +0 -0
  38. python_embeded/get-pip.py +0 -0
  39. python_embeded/libffi-8.dll +0 -0
  40. python_embeded/python3.dll +0 -0
  41. python_embeded/python312._pth +7 -0
  42. python_embeded/select.pyd +0 -0
  43. python_embeded/vcruntime140_1.dll +0 -0
  44. python_embeded/winsound.pyd +0 -0
  45. run_cpu.bat +2 -0
  46. run_nvidia_gpu.bat +2 -0
  47. run_nvidia_gpu_fast_fp16_accumulation.bat +2 -0
  48. update/update.py +151 -0
  49. update/update_comfyui.bat +8 -0
  50. upload_to_hf.py +53 -0
.gitignore ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Cache and temporary files
2
+ .cache/
3
+ __pycache__/
4
+ *.pyc
5
+ *.pyo
6
+ *.pyd
7
+ .Python
8
+ *.so
9
+ *.egg
10
+ *.egg-info/
11
+ dist/
12
+ build/
13
+ *.log
14
+
15
+ # ComfyUI specific
16
+ ComfyUI/custom_nodes/comfyui-manager/.cache/
17
+ ComfyUI/output/
18
+ ComfyUI/temp/
19
+ ComfyUI/input/
20
+
21
+ # Model checkpoints (if you want to exclude large files)
22
+ *.ckpt
23
+ *.safetensors
24
+ *.pth
25
+
26
+ # Virtual environments
27
+ venv/
28
+ env/
29
+ ENV/
30
+
31
+ # IDE files
32
+ .vscode/
33
+ .idea/
34
+ *.swp
35
+ *.swo
36
+
37
+ # OS files
38
+ .DS_Store
39
+ Thumbs.db
ComfyUI/.gitattributes ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ /web/assets/** linguist-generated
2
+ /web/** linguist-vendored
ComfyUI/.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
ComfyUI/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 @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
9
+ /tests/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
10
+ /tests-unit/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
11
+ /notebooks/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
12
+ /script_examples/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
13
+ /.github/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
14
+ /requirements.txt @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
15
+ /pyproject.toml @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @Kosinkadink @christian-byrne
16
+
17
+ # Python web server
18
+ /api_server/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @christian-byrne
19
+ /app/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @christian-byrne
20
+ /utils/ @yoland68 @robinjhuang @webfiltered @pythongosssss @ltdrdata @christian-byrne
21
+
22
+ # Node developers
23
+ /comfy_extras/ @yoland68 @robinjhuang @pythongosssss @ltdrdata @Kosinkadink @webfiltered @christian-byrne
24
+ /comfy/comfy_types/ @yoland68 @robinjhuang @pythongosssss @ltdrdata @Kosinkadink @webfiltered @christian-byrne
ComfyUI/CONTRIBUTING.md ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributing to ComfyUI
2
+
3
+ Welcome, and thank you for your interest in contributing to ComfyUI!
4
+
5
+ There are several ways in which you can contribute, beyond writing code. The goal of this document is to provide a high-level overview of how you can get involved.
6
+
7
+ ## Asking Questions
8
+
9
+ Have a question? Instead of opening an issue, please ask on [Discord](https://comfy.org/discord) or [Matrix](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) channels. Our team and the community will help you.
10
+
11
+ ## Providing Feedback
12
+
13
+ Your comments and feedback are welcome, and the development team is available via a handful of different channels.
14
+
15
+ See the `#bug-report`, `#feature-request` and `#feedback` channels on Discord.
16
+
17
+ ## Reporting Issues
18
+
19
+ Have you identified a reproducible problem in ComfyUI? Do you have a feature request? We want to hear about it! Here's how you can report your issue as effectively as possible.
20
+
21
+
22
+ ### Look For an Existing Issue
23
+
24
+ Before you create a new issue, please do a search in [open issues](https://github.com/comfyanonymous/ComfyUI/issues) to see if the issue or feature request has already been filed.
25
+
26
+ If you find your issue already exists, make relevant comments and add your [reaction](https://github.com/blog/2119-add-reactions-to-pull-requests-issues-and-comments). Use a reaction in place of a "+1" comment:
27
+
28
+ * 👍 - upvote
29
+ * 👎 - downvote
30
+
31
+ If you cannot find an existing issue that describes your bug or feature, create a new issue. We have an issue template in place to organize new issues.
32
+
33
+
34
+ ### Creating Pull Requests
35
+
36
+ * Please refer to the article on [creating pull requests](https://github.com/comfyanonymous/ComfyUI/wiki/How-to-Contribute-Code) and contributing to this project.
37
+
38
+
39
+ ## Thank You
40
+
41
+ Your contributions to open source, large or small, make great projects like this possible. Thank you for taking the time to contribute.
ComfyUI/LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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>.
ComfyUI/README.md ADDED
@@ -0,0 +1,400 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ # ComfyUI
4
+ **The most powerful and modular visual AI engine and application.**
5
+
6
+
7
+ [![Website][website-shield]][website-url]
8
+ [![Dynamic JSON Badge][discord-shield]][discord-url]
9
+ [![Twitter][twitter-shield]][twitter-url]
10
+ [![Matrix][matrix-shield]][matrix-url]
11
+ <br>
12
+ [![][github-release-shield]][github-release-link]
13
+ [![][github-release-date-shield]][github-release-link]
14
+ [![][github-downloads-shield]][github-downloads-link]
15
+ [![][github-downloads-latest-shield]][github-downloads-link]
16
+
17
+ [matrix-shield]: https://img.shields.io/badge/Matrix-000000?style=flat&logo=matrix&logoColor=white
18
+ [matrix-url]: https://app.element.io/#/room/%23comfyui_space%3Amatrix.org
19
+ [website-shield]: https://img.shields.io/badge/ComfyOrg-4285F4?style=flat
20
+ [website-url]: https://www.comfy.org/
21
+ <!-- Workaround to display total user from https://github.com/badges/shields/issues/4500#issuecomment-2060079995 -->
22
+ [discord-shield]: https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fdiscord.com%2Fapi%2Finvites%2Fcomfyorg%3Fwith_counts%3Dtrue&query=%24.approximate_member_count&logo=discord&logoColor=white&label=Discord&color=green&suffix=%20total
23
+ [discord-url]: https://www.comfy.org/discord
24
+ [twitter-shield]: https://img.shields.io/twitter/follow/ComfyUI
25
+ [twitter-url]: https://x.com/ComfyUI
26
+
27
+ [github-release-shield]: https://img.shields.io/github/v/release/comfyanonymous/ComfyUI?style=flat&sort=semver
28
+ [github-release-link]: https://github.com/comfyanonymous/ComfyUI/releases
29
+ [github-release-date-shield]: https://img.shields.io/github/release-date/comfyanonymous/ComfyUI?style=flat
30
+ [github-downloads-shield]: https://img.shields.io/github/downloads/comfyanonymous/ComfyUI/total?style=flat
31
+ [github-downloads-latest-shield]: https://img.shields.io/github/downloads/comfyanonymous/ComfyUI/latest/total?style=flat&label=downloads%40latest
32
+ [github-downloads-link]: https://github.com/comfyanonymous/ComfyUI/releases
33
+
34
+ ![ComfyUI Screenshot](https://github.com/user-attachments/assets/7ccaf2c1-9b72-41ae-9a89-5688c94b7abe)
35
+ </div>
36
+
37
+ ComfyUI lets you design and execute advanced stable diffusion pipelines using a graph/nodes/flowchart based interface. Available on Windows, Linux, and macOS.
38
+
39
+ ## Get Started
40
+
41
+ #### [Desktop Application](https://www.comfy.org/download)
42
+ - The easiest way to get started.
43
+ - Available on Windows & macOS.
44
+
45
+ #### [Windows Portable Package](#installing)
46
+ - Get the latest commits and completely portable.
47
+ - Available on Windows.
48
+
49
+ #### [Manual Install](#manual-install-windows-linux)
50
+ Supports all operating systems and GPU types (NVIDIA, AMD, Intel, Apple Silicon, Ascend).
51
+
52
+ ## [Examples](https://comfyanonymous.github.io/ComfyUI_examples/)
53
+ See what ComfyUI can do with the [example workflows](https://comfyanonymous.github.io/ComfyUI_examples/).
54
+
55
+ ## Features
56
+ - Nodes/graph/flowchart interface to experiment and create complex Stable Diffusion workflows without needing to code anything.
57
+ - Image Models
58
+ - SD1.x, SD2.x,
59
+ - [SDXL](https://comfyanonymous.github.io/ComfyUI_examples/sdxl/), [SDXL Turbo](https://comfyanonymous.github.io/ComfyUI_examples/sdturbo/)
60
+ - [Stable Cascade](https://comfyanonymous.github.io/ComfyUI_examples/stable_cascade/)
61
+ - [SD3 and SD3.5](https://comfyanonymous.github.io/ComfyUI_examples/sd3/)
62
+ - Pixart Alpha and Sigma
63
+ - [AuraFlow](https://comfyanonymous.github.io/ComfyUI_examples/aura_flow/)
64
+ - [HunyuanDiT](https://comfyanonymous.github.io/ComfyUI_examples/hunyuan_dit/)
65
+ - [Flux](https://comfyanonymous.github.io/ComfyUI_examples/flux/)
66
+ - [Lumina Image 2.0](https://comfyanonymous.github.io/ComfyUI_examples/lumina2/)
67
+ - [HiDream](https://comfyanonymous.github.io/ComfyUI_examples/hidream/)
68
+ - Video Models
69
+ - [Stable Video Diffusion](https://comfyanonymous.github.io/ComfyUI_examples/video/)
70
+ - [Mochi](https://comfyanonymous.github.io/ComfyUI_examples/mochi/)
71
+ - [LTX-Video](https://comfyanonymous.github.io/ComfyUI_examples/ltxv/)
72
+ - [Hunyuan Video](https://comfyanonymous.github.io/ComfyUI_examples/hunyuan_video/)
73
+ - [Nvidia Cosmos](https://comfyanonymous.github.io/ComfyUI_examples/cosmos/)
74
+ - [Wan 2.1](https://comfyanonymous.github.io/ComfyUI_examples/wan/)
75
+ - Audio Models
76
+ - [Stable Audio](https://comfyanonymous.github.io/ComfyUI_examples/audio/)
77
+ - [ACE Step](https://comfyanonymous.github.io/ComfyUI_examples/audio/)
78
+ - 3D Models
79
+ - [Hunyuan3D 2.0](https://docs.comfy.org/tutorials/3d/hunyuan3D-2)
80
+ - Asynchronous Queue system
81
+ - Many optimizations: Only re-executes the parts of the workflow that changes between executions.
82
+ - Smart memory management: can automatically run models on GPUs with as low as 1GB vram.
83
+ - Works even if you don't have a GPU with: ```--cpu``` (slow)
84
+ - Can load ckpt, safetensors and diffusers models/checkpoints. Standalone VAEs and CLIP models.
85
+ - Embeddings/Textual inversion
86
+ - [Loras (regular, locon and loha)](https://comfyanonymous.github.io/ComfyUI_examples/lora/)
87
+ - [Hypernetworks](https://comfyanonymous.github.io/ComfyUI_examples/hypernetworks/)
88
+ - Loading full workflows (with seeds) from generated PNG, WebP and FLAC files.
89
+ - Saving/Loading workflows as Json files.
90
+ - Nodes interface can be used to create complex workflows like one for [Hires fix](https://comfyanonymous.github.io/ComfyUI_examples/2_pass_txt2img/) or much more advanced ones.
91
+ - [Area Composition](https://comfyanonymous.github.io/ComfyUI_examples/area_composition/)
92
+ - [Inpainting](https://comfyanonymous.github.io/ComfyUI_examples/inpaint/) with both regular and inpainting models.
93
+ - [ControlNet and T2I-Adapter](https://comfyanonymous.github.io/ComfyUI_examples/controlnet/)
94
+ - [Upscale Models (ESRGAN, ESRGAN variants, SwinIR, Swin2SR, etc...)](https://comfyanonymous.github.io/ComfyUI_examples/upscale_models/)
95
+ - [unCLIP Models](https://comfyanonymous.github.io/ComfyUI_examples/unclip/)
96
+ - [GLIGEN](https://comfyanonymous.github.io/ComfyUI_examples/gligen/)
97
+ - [Model Merging](https://comfyanonymous.github.io/ComfyUI_examples/model_merging/)
98
+ - [LCM models and Loras](https://comfyanonymous.github.io/ComfyUI_examples/lcm/)
99
+ - Latent previews with [TAESD](#how-to-show-high-quality-previews)
100
+ - Starts up very fast.
101
+ - Works fully offline: core will never download anything unless you want to.
102
+ - Optional API nodes to use paid models from external providers through the online [Comfy API](https://docs.comfy.org/tutorials/api-nodes/overview).
103
+ - [Config file](extra_model_paths.yaml.example) to set the search paths for models.
104
+
105
+ Workflow examples can be found on the [Examples page](https://comfyanonymous.github.io/ComfyUI_examples/)
106
+
107
+ ## Release Process
108
+
109
+ ComfyUI follows a weekly release cycle every Friday, with three interconnected repositories:
110
+
111
+ 1. **[ComfyUI Core](https://github.com/comfyanonymous/ComfyUI)**
112
+ - Releases a new stable version (e.g., v0.7.0)
113
+ - Serves as the foundation for the desktop release
114
+
115
+ 2. **[ComfyUI Desktop](https://github.com/Comfy-Org/desktop)**
116
+ - Builds a new release using the latest stable core version
117
+
118
+ 3. **[ComfyUI Frontend](https://github.com/Comfy-Org/ComfyUI_frontend)**
119
+ - Weekly frontend updates are merged into the core repository
120
+ - Features are frozen for the upcoming core release
121
+ - Development continues for the next release cycle
122
+
123
+ ## Shortcuts
124
+
125
+ | Keybind | Explanation |
126
+ |------------------------------------|--------------------------------------------------------------------------------------------------------------------|
127
+ | `Ctrl` + `Enter` | Queue up current graph for generation |
128
+ | `Ctrl` + `Shift` + `Enter` | Queue up current graph as first for generation |
129
+ | `Ctrl` + `Alt` + `Enter` | Cancel current generation |
130
+ | `Ctrl` + `Z`/`Ctrl` + `Y` | Undo/Redo |
131
+ | `Ctrl` + `S` | Save workflow |
132
+ | `Ctrl` + `O` | Load workflow |
133
+ | `Ctrl` + `A` | Select all nodes |
134
+ | `Alt `+ `C` | Collapse/uncollapse selected nodes |
135
+ | `Ctrl` + `M` | Mute/unmute selected nodes |
136
+ | `Ctrl` + `B` | Bypass selected nodes (acts like the node was removed from the graph and the wires reconnected through) |
137
+ | `Delete`/`Backspace` | Delete selected nodes |
138
+ | `Ctrl` + `Backspace` | Delete the current graph |
139
+ | `Space` | Move the canvas around when held and moving the cursor |
140
+ | `Ctrl`/`Shift` + `Click` | Add clicked node to selection |
141
+ | `Ctrl` + `C`/`Ctrl` + `V` | Copy and paste selected nodes (without maintaining connections to outputs of unselected nodes) |
142
+ | `Ctrl` + `C`/`Ctrl` + `Shift` + `V` | Copy and paste selected nodes (maintaining connections from outputs of unselected nodes to inputs of pasted nodes) |
143
+ | `Shift` + `Drag` | Move multiple selected nodes at the same time |
144
+ | `Ctrl` + `D` | Load default graph |
145
+ | `Alt` + `+` | Canvas Zoom in |
146
+ | `Alt` + `-` | Canvas Zoom out |
147
+ | `Ctrl` + `Shift` + LMB + Vertical drag | Canvas Zoom in/out |
148
+ | `P` | Pin/Unpin selected nodes |
149
+ | `Ctrl` + `G` | Group selected nodes |
150
+ | `Q` | Toggle visibility of the queue |
151
+ | `H` | Toggle visibility of history |
152
+ | `R` | Refresh graph |
153
+ | `F` | Show/Hide menu |
154
+ | `.` | Fit view to selection (Whole graph when nothing is selected) |
155
+ | Double-Click LMB | Open node quick search palette |
156
+ | `Shift` + Drag | Move multiple wires at once |
157
+ | `Ctrl` + `Alt` + LMB | Disconnect all wires from clicked slot |
158
+
159
+ `Ctrl` can also be replaced with `Cmd` instead for macOS users
160
+
161
+ # Installing
162
+
163
+ ## Windows Portable
164
+
165
+ There is a portable standalone build for Windows that should work for running on Nvidia GPUs or for running on your CPU only on the [releases page](https://github.com/comfyanonymous/ComfyUI/releases).
166
+
167
+ ### [Direct link to download](https://github.com/comfyanonymous/ComfyUI/releases/latest/download/ComfyUI_windows_portable_nvidia.7z)
168
+
169
+ Simply download, extract with [7-Zip](https://7-zip.org) and run. Make sure you put your Stable Diffusion checkpoints/models (the huge ckpt/safetensors files) in: ComfyUI\models\checkpoints
170
+
171
+ If you have trouble extracting it, right click the file -> properties -> unblock
172
+
173
+ #### How do I share models between another UI and ComfyUI?
174
+
175
+ See the [Config file](extra_model_paths.yaml.example) to set the search paths for models. In the standalone windows build you can find this file in the ComfyUI directory. Rename this file to extra_model_paths.yaml and edit it with your favorite text editor.
176
+
177
+ ## Jupyter Notebook
178
+
179
+ To run it on services like paperspace, kaggle or colab you can use my [Jupyter Notebook](notebooks/comfyui_colab.ipynb)
180
+
181
+
182
+ ## [comfy-cli](https://docs.comfy.org/comfy-cli/getting-started)
183
+
184
+ You can install and start ComfyUI using comfy-cli:
185
+ ```bash
186
+ pip install comfy-cli
187
+ comfy install
188
+ ```
189
+
190
+ ## Manual Install (Windows, Linux)
191
+
192
+ python 3.13 is supported but using 3.12 is recommended because some custom nodes and their dependencies might not support it yet.
193
+
194
+ Git clone this repo.
195
+
196
+ Put your SD checkpoints (the huge ckpt/safetensors files) in: models/checkpoints
197
+
198
+ Put your VAE in: models/vae
199
+
200
+
201
+ ### AMD GPUs (Linux only)
202
+ AMD users can install rocm and pytorch with pip if you don't have it already installed, this is the command to install the stable version:
203
+
204
+ ```pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/rocm6.3```
205
+
206
+ This is the command to install the nightly with ROCm 6.4 which might have some performance improvements:
207
+
208
+ ```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/rocm6.4```
209
+
210
+ ### Intel GPUs (Windows and Linux)
211
+
212
+ (Option 1) Intel Arc GPU users can install native PyTorch with torch.xpu support using pip (currently available in PyTorch nightly builds). More information can be found [here](https://pytorch.org/docs/main/notes/get_start_xpu.html)
213
+
214
+ 1. To install PyTorch nightly, use the following command:
215
+
216
+ ```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/xpu```
217
+
218
+ 2. Launch ComfyUI by running `python main.py`
219
+
220
+
221
+ (Option 2) Alternatively, Intel GPUs supported by Intel Extension for PyTorch (IPEX) can leverage IPEX for improved performance.
222
+
223
+ 1. For Intel® Arc™ A-Series Graphics utilizing IPEX, create a conda environment and use the commands below:
224
+
225
+ ```
226
+ conda install libuv
227
+ pip install torch==2.3.1.post0+cxx11.abi torchvision==0.18.1.post0+cxx11.abi torchaudio==2.3.1.post0+cxx11.abi intel-extension-for-pytorch==2.3.110.post0+xpu --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/us/ --extra-index-url https://pytorch-extension.intel.com/release-whl/stable/xpu/cn/
228
+ ```
229
+
230
+ For other supported Intel GPUs with IPEX, visit [Installation](https://intel.github.io/intel-extension-for-pytorch/index.html#installation?platform=gpu) for more information.
231
+
232
+ Additional discussion and help can be found [here](https://github.com/comfyanonymous/ComfyUI/discussions/476).
233
+
234
+ ### NVIDIA
235
+
236
+ Nvidia users should install stable pytorch using this command:
237
+
238
+ ```pip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu128```
239
+
240
+ This is the command to install pytorch nightly instead which might have performance improvements.
241
+
242
+ ```pip install --pre torch torchvision torchaudio --index-url https://download.pytorch.org/whl/nightly/cu128```
243
+
244
+ #### Troubleshooting
245
+
246
+ If you get the "Torch not compiled with CUDA enabled" error, uninstall torch with:
247
+
248
+ ```pip uninstall torch```
249
+
250
+ And install it again with the command above.
251
+
252
+ ### Dependencies
253
+
254
+ Install the dependencies by opening your terminal inside the ComfyUI folder and:
255
+
256
+ ```pip install -r requirements.txt```
257
+
258
+ After this you should have everything installed and can proceed to running ComfyUI.
259
+
260
+ ### Others:
261
+
262
+ #### Apple Mac silicon
263
+
264
+ You can install ComfyUI in Apple Mac silicon (M1 or M2) with any recent macOS version.
265
+
266
+ 1. Install pytorch nightly. For instructions, read the [Accelerated PyTorch training on Mac](https://developer.apple.com/metal/pytorch/) Apple Developer guide (make sure to install the latest pytorch nightly).
267
+ 1. Follow the [ComfyUI manual installation](#manual-install-windows-linux) instructions for Windows and Linux.
268
+ 1. Install the ComfyUI [dependencies](#dependencies). If you have another Stable Diffusion UI [you might be able to reuse the dependencies](#i-already-have-another-ui-for-stable-diffusion-installed-do-i-really-have-to-install-all-of-these-dependencies).
269
+ 1. Launch ComfyUI by running `python main.py`
270
+
271
+ > **Note**: Remember to add your models, VAE, LoRAs etc. to the corresponding Comfy folders, as discussed in [ComfyUI manual installation](#manual-install-windows-linux).
272
+
273
+ #### DirectML (AMD Cards on Windows)
274
+
275
+ ```pip install torch-directml``` Then you can launch ComfyUI with: ```python main.py --directml```
276
+
277
+ #### Ascend NPUs
278
+
279
+ For models compatible with Ascend Extension for PyTorch (torch_npu). To get started, ensure your environment meets the prerequisites outlined on the [installation](https://ascend.github.io/docs/sources/ascend/quick_install.html) page. Here's a step-by-step guide tailored to your platform and installation method:
280
+
281
+ 1. Begin by installing the recommended or newer kernel version for Linux as specified in the Installation page of torch-npu, if necessary.
282
+ 2. Proceed with the installation of Ascend Basekit, which includes the driver, firmware, and CANN, following the instructions provided for your specific platform.
283
+ 3. Next, install the necessary packages for torch-npu by adhering to the platform-specific instructions on the [Installation](https://ascend.github.io/docs/sources/pytorch/install.html#pytorch) page.
284
+ 4. Finally, adhere to the [ComfyUI manual installation](#manual-install-windows-linux) guide for Linux. Once all components are installed, you can run ComfyUI as described earlier.
285
+
286
+ #### Cambricon MLUs
287
+
288
+ For models compatible with Cambricon Extension for PyTorch (torch_mlu). Here's a step-by-step guide tailored to your platform and installation method:
289
+
290
+ 1. Install the Cambricon CNToolkit by adhering to the platform-specific instructions on the [Installation](https://www.cambricon.com/docs/sdk_1.15.0/cntoolkit_3.7.2/cntoolkit_install_3.7.2/index.html)
291
+ 2. Next, install the PyTorch(torch_mlu) following the instructions on the [Installation](https://www.cambricon.com/docs/sdk_1.15.0/cambricon_pytorch_1.17.0/user_guide_1.9/index.html)
292
+ 3. Launch ComfyUI by running `python main.py`
293
+
294
+ # Running
295
+
296
+ ```python main.py```
297
+
298
+ ### For AMD cards not officially supported by ROCm
299
+
300
+ Try running it with this command if you have issues:
301
+
302
+ For 6700, 6600 and maybe other RDNA2 or older: ```HSA_OVERRIDE_GFX_VERSION=10.3.0 python main.py```
303
+
304
+ For AMD 7600 and maybe other RDNA3 cards: ```HSA_OVERRIDE_GFX_VERSION=11.0.0 python main.py```
305
+
306
+ ### AMD ROCm Tips
307
+
308
+ You can enable experimental memory efficient attention on recent pytorch in ComfyUI on some AMD GPUs using this command, it should already be enabled by default on RDNA3. If this improves speed for you on latest pytorch on your GPU please report it so that I can enable it by default.
309
+
310
+ ```TORCH_ROCM_AOTRITON_ENABLE_EXPERIMENTAL=1 python main.py --use-pytorch-cross-attention```
311
+
312
+ You can also try setting this env variable `PYTORCH_TUNABLEOP_ENABLED=1` which might speed things up at the cost of a very slow initial run.
313
+
314
+ # Notes
315
+
316
+ Only parts of the graph that have an output with all the correct inputs will be executed.
317
+
318
+ Only parts of the graph that change from each execution to the next will be executed, if you submit the same graph twice only the first will be executed. If you change the last part of the graph only the part you changed and the part that depends on it will be executed.
319
+
320
+ Dragging a generated png on the webpage or loading one will give you the full workflow including seeds that were used to create it.
321
+
322
+ You can use () to change emphasis of a word or phrase like: (good code:1.2) or (bad code:0.8). The default emphasis for () is 1.1. To use () characters in your actual prompt escape them like \\( or \\).
323
+
324
+ You can use {day|night}, for wildcard/dynamic prompts. With this syntax "{wild|card|test}" will be randomly replaced by either "wild", "card" or "test" by the frontend every time you queue the prompt. To use {} characters in your actual prompt escape them like: \\{ or \\}.
325
+
326
+ Dynamic prompts also support C-style comments, like `// comment` or `/* comment */`.
327
+
328
+ To use a textual inversion concepts/embeddings in a text prompt put them in the models/embeddings directory and use them in the CLIPTextEncode node like this (you can omit the .pt extension):
329
+
330
+ ```embedding:embedding_filename.pt```
331
+
332
+
333
+ ## How to show high-quality previews?
334
+
335
+ Use ```--preview-method auto``` to enable previews.
336
+
337
+ The default installation includes a fast latent preview method that's low-resolution. To enable higher-quality previews with [TAESD](https://github.com/madebyollin/taesd), download the [taesd_decoder.pth, taesdxl_decoder.pth, taesd3_decoder.pth and taef1_decoder.pth](https://github.com/madebyollin/taesd/) and place them in the `models/vae_approx` folder. Once they're installed, restart ComfyUI and launch it with `--preview-method taesd` to enable high-quality previews.
338
+
339
+ ## How to use TLS/SSL?
340
+ Generate a self-signed certificate (not appropriate for shared/production use) and key by running the command: `openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -sha256 -days 3650 -nodes -subj "/C=XX/ST=StateName/L=CityName/O=CompanyName/OU=CompanySectionName/CN=CommonNameOrHostname"`
341
+
342
+ Use `--tls-keyfile key.pem --tls-certfile cert.pem` to enable TLS/SSL, the app will now be accessible with `https://...` instead of `http://...`.
343
+
344
+ > Note: Windows users can use [alexisrolland/docker-openssl](https://github.com/alexisrolland/docker-openssl) or one of the [3rd party binary distributions](https://wiki.openssl.org/index.php/Binaries) to run the command example above.
345
+ <br/><br/>If you use a container, note that the volume mount `-v` can be a relative path so `... -v ".\:/openssl-certs" ...` would create the key & cert files in the current directory of your command prompt or powershell terminal.
346
+
347
+ ## Support and dev channel
348
+
349
+ [Discord](https://comfy.org/discord): Try the #help or #feedback channels.
350
+
351
+ [Matrix space: #comfyui_space:matrix.org](https://app.element.io/#/room/%23comfyui_space%3Amatrix.org) (it's like discord but open source).
352
+
353
+ See also: [https://www.comfy.org/](https://www.comfy.org/)
354
+
355
+ ## Frontend Development
356
+
357
+ As of August 15, 2024, we have transitioned to a new frontend, which is now hosted in a separate repository: [ComfyUI Frontend](https://github.com/Comfy-Org/ComfyUI_frontend). This repository now hosts the compiled JS (from TS/Vue) under the `web/` directory.
358
+
359
+ ### Reporting Issues and Requesting Features
360
+
361
+ For any bugs, issues, or feature requests related to the frontend, please use the [ComfyUI Frontend repository](https://github.com/Comfy-Org/ComfyUI_frontend). This will help us manage and address frontend-specific concerns more efficiently.
362
+
363
+ ### Using the Latest Frontend
364
+
365
+ The new frontend is now the default for ComfyUI. However, please note:
366
+
367
+ 1. The frontend in the main ComfyUI repository is updated fortnightly.
368
+ 2. Daily releases are available in the separate frontend repository.
369
+
370
+ To use the most up-to-date frontend version:
371
+
372
+ 1. For the latest daily release, launch ComfyUI with this command line argument:
373
+
374
+ ```
375
+ --front-end-version Comfy-Org/ComfyUI_frontend@latest
376
+ ```
377
+
378
+ 2. For a specific version, replace `latest` with the desired version number:
379
+
380
+ ```
381
+ --front-end-version Comfy-Org/ComfyUI_frontend@1.2.2
382
+ ```
383
+
384
+ This approach allows you to easily switch between the stable fortnightly release and the cutting-edge daily updates, or even specific versions for testing purposes.
385
+
386
+ ### Accessing the Legacy Frontend
387
+
388
+ If you need to use the legacy frontend for any reason, you can access it using the following command line argument:
389
+
390
+ ```
391
+ --front-end-version Comfy-Org/ComfyUI_legacy_frontend@latest
392
+ ```
393
+
394
+ This will use a snapshot of the legacy frontend preserved in the [ComfyUI Legacy Frontend repository](https://github.com/Comfy-Org/ComfyUI_legacy_frontend).
395
+
396
+ # QA
397
+
398
+ ### Which GPU should I buy for this?
399
+
400
+ [See this page for some recommendations](https://github.com/comfyanonymous/ComfyUI/wiki/Which-GPU-should-I-buy-for-ComfyUI)
ComfyUI/alembic.ini ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A generic, single database configuration.
2
+
3
+ [alembic]
4
+ # path to migration scripts
5
+ # Use forward slashes (/) also on windows to provide an os agnostic path
6
+ script_location = alembic_db
7
+
8
+ # template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
9
+ # Uncomment the line below if you want the files to be prepended with date and time
10
+ # see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
11
+ # for all available tokens
12
+ # file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
13
+
14
+ # sys.path path, will be prepended to sys.path if present.
15
+ # defaults to the current working directory.
16
+ prepend_sys_path = .
17
+
18
+ # timezone to use when rendering the date within the migration file
19
+ # as well as the filename.
20
+ # If specified, requires the python>=3.9 or backports.zoneinfo library and tzdata library.
21
+ # Any required deps can installed by adding `alembic[tz]` to the pip requirements
22
+ # string value is passed to ZoneInfo()
23
+ # leave blank for localtime
24
+ # timezone =
25
+
26
+ # max length of characters to apply to the "slug" field
27
+ # truncate_slug_length = 40
28
+
29
+ # set to 'true' to run the environment during
30
+ # the 'revision' command, regardless of autogenerate
31
+ # revision_environment = false
32
+
33
+ # set to 'true' to allow .pyc and .pyo files without
34
+ # a source .py file to be detected as revisions in the
35
+ # versions/ directory
36
+ # sourceless = false
37
+
38
+ # version location specification; This defaults
39
+ # to alembic_db/versions. When using multiple version
40
+ # directories, initial revisions must be specified with --version-path.
41
+ # The path separator used here should be the separator specified by "version_path_separator" below.
42
+ # version_locations = %(here)s/bar:%(here)s/bat:alembic_db/versions
43
+
44
+ # version path separator; As mentioned above, this is the character used to split
45
+ # version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
46
+ # If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
47
+ # Valid values for version_path_separator are:
48
+ #
49
+ # version_path_separator = :
50
+ # version_path_separator = ;
51
+ # version_path_separator = space
52
+ # version_path_separator = newline
53
+ #
54
+ # Use os.pathsep. Default configuration used for new projects.
55
+ version_path_separator = os
56
+
57
+ # set to 'true' to search source files recursively
58
+ # in each "version_locations" directory
59
+ # new in Alembic version 1.10
60
+ # recursive_version_locations = false
61
+
62
+ # the output encoding used when revision files
63
+ # are written from script.py.mako
64
+ # output_encoding = utf-8
65
+
66
+ sqlalchemy.url = sqlite:///user/comfyui.db
67
+
68
+
69
+ [post_write_hooks]
70
+ # post_write_hooks defines scripts or Python functions that are run
71
+ # on newly generated revision scripts. See the documentation for further
72
+ # detail and examples
73
+
74
+ # format using "black" - use the console_scripts runner, against the "black" entrypoint
75
+ # hooks = black
76
+ # black.type = console_scripts
77
+ # black.entrypoint = black
78
+ # black.options = -l 79 REVISION_SCRIPT_FILENAME
79
+
80
+ # lint with attempts to fix using "ruff" - use the exec runner, execute a binary
81
+ # hooks = ruff
82
+ # ruff.type = exec
83
+ # ruff.executable = %(here)s/.venv/bin/ruff
84
+ # ruff.options = check --fix REVISION_SCRIPT_FILENAME
ComfyUI/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.41"
ComfyUI/cuda_malloc.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import importlib.util
3
+ from comfy.cli_args import args
4
+ import subprocess
5
+
6
+ #Can't use pytorch to get the GPU names because the cuda malloc has to be set before the first import.
7
+ def get_gpu_names():
8
+ if os.name == 'nt':
9
+ import ctypes
10
+
11
+ # Define necessary C structures and types
12
+ class DISPLAY_DEVICEA(ctypes.Structure):
13
+ _fields_ = [
14
+ ('cb', ctypes.c_ulong),
15
+ ('DeviceName', ctypes.c_char * 32),
16
+ ('DeviceString', ctypes.c_char * 128),
17
+ ('StateFlags', ctypes.c_ulong),
18
+ ('DeviceID', ctypes.c_char * 128),
19
+ ('DeviceKey', ctypes.c_char * 128)
20
+ ]
21
+
22
+ # Load user32.dll
23
+ user32 = ctypes.windll.user32
24
+
25
+ # Call EnumDisplayDevicesA
26
+ def enum_display_devices():
27
+ device_info = DISPLAY_DEVICEA()
28
+ device_info.cb = ctypes.sizeof(device_info)
29
+ device_index = 0
30
+ gpu_names = set()
31
+
32
+ while user32.EnumDisplayDevicesA(None, device_index, ctypes.byref(device_info), 0):
33
+ device_index += 1
34
+ gpu_names.add(device_info.DeviceString.decode('utf-8'))
35
+ return gpu_names
36
+ return enum_display_devices()
37
+ else:
38
+ gpu_names = set()
39
+ out = subprocess.check_output(['nvidia-smi', '-L'])
40
+ for l in out.split(b'\n'):
41
+ if len(l) > 0:
42
+ gpu_names.add(l.decode('utf-8').split(' (UUID')[0])
43
+ return gpu_names
44
+
45
+ blacklist = {"GeForce GTX TITAN X", "GeForce GTX 980", "GeForce GTX 970", "GeForce GTX 960", "GeForce GTX 950", "GeForce 945M",
46
+ "GeForce 940M", "GeForce 930M", "GeForce 920M", "GeForce 910M", "GeForce GTX 750", "GeForce GTX 745", "Quadro K620",
47
+ "Quadro K1200", "Quadro K2200", "Quadro M500", "Quadro M520", "Quadro M600", "Quadro M620", "Quadro M1000",
48
+ "Quadro M1200", "Quadro M2000", "Quadro M2200", "Quadro M3000", "Quadro M4000", "Quadro M5000", "Quadro M5500", "Quadro M6000",
49
+ "GeForce MX110", "GeForce MX130", "GeForce 830M", "GeForce 840M", "GeForce GTX 850M", "GeForce GTX 860M",
50
+ "GeForce GTX 1650", "GeForce GTX 1630", "Tesla M4", "Tesla M6", "Tesla M10", "Tesla M40", "Tesla M60"
51
+ }
52
+
53
+ def cuda_malloc_supported():
54
+ try:
55
+ names = get_gpu_names()
56
+ except:
57
+ names = set()
58
+ for x in names:
59
+ if "NVIDIA" in x:
60
+ for b in blacklist:
61
+ if b in x:
62
+ return False
63
+ return True
64
+
65
+
66
+ if not args.cuda_malloc:
67
+ try:
68
+ version = ""
69
+ torch_spec = importlib.util.find_spec("torch")
70
+ for folder in torch_spec.submodule_search_locations:
71
+ ver_file = os.path.join(folder, "version.py")
72
+ if os.path.isfile(ver_file):
73
+ spec = importlib.util.spec_from_file_location("torch_version_import", ver_file)
74
+ module = importlib.util.module_from_spec(spec)
75
+ spec.loader.exec_module(module)
76
+ version = module.__version__
77
+ if int(version[0]) >= 2: #enable by default for torch version 2.0 and up
78
+ args.cuda_malloc = cuda_malloc_supported()
79
+ except:
80
+ pass
81
+
82
+
83
+ if args.cuda_malloc and not args.disable_cuda_malloc:
84
+ env_var = os.environ.get('PYTORCH_CUDA_ALLOC_CONF', None)
85
+ if env_var is None:
86
+ env_var = "backend:cudaMallocAsync"
87
+ else:
88
+ env_var += ",backend:cudaMallocAsync"
89
+
90
+ os.environ['PYTORCH_CUDA_ALLOC_CONF'] = env_var
ComfyUI/execution.py ADDED
@@ -0,0 +1,1044 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import heapq
3
+ import inspect
4
+ import logging
5
+ import sys
6
+ import threading
7
+ import time
8
+ import traceback
9
+ from enum import Enum
10
+ from typing import List, Literal, NamedTuple, Optional
11
+
12
+ import torch
13
+
14
+ import comfy.model_management
15
+ import nodes
16
+ from comfy_execution.caching import (
17
+ CacheKeySetID,
18
+ CacheKeySetInputSignature,
19
+ DependencyAwareCache,
20
+ HierarchicalCache,
21
+ LRUCache,
22
+ )
23
+ from comfy_execution.graph import (
24
+ DynamicPrompt,
25
+ ExecutionBlocker,
26
+ ExecutionList,
27
+ get_input_info,
28
+ )
29
+ from comfy_execution.graph_utils import GraphBuilder, is_link
30
+ from comfy_execution.validation import validate_node_input
31
+
32
+
33
+ class ExecutionResult(Enum):
34
+ SUCCESS = 0
35
+ FAILURE = 1
36
+ PENDING = 2
37
+
38
+ class DuplicateNodeError(Exception):
39
+ pass
40
+
41
+ class IsChangedCache:
42
+ def __init__(self, dynprompt, outputs_cache):
43
+ self.dynprompt = dynprompt
44
+ self.outputs_cache = outputs_cache
45
+ self.is_changed = {}
46
+
47
+ def get(self, node_id):
48
+ if node_id in self.is_changed:
49
+ return self.is_changed[node_id]
50
+
51
+ node = self.dynprompt.get_node(node_id)
52
+ class_type = node["class_type"]
53
+ class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
54
+ if not hasattr(class_def, "IS_CHANGED"):
55
+ self.is_changed[node_id] = False
56
+ return self.is_changed[node_id]
57
+
58
+ if "is_changed" in node:
59
+ self.is_changed[node_id] = node["is_changed"]
60
+ return self.is_changed[node_id]
61
+
62
+ # Intentionally do not use cached outputs here. We only want constants in IS_CHANGED
63
+ input_data_all, _ = get_input_data(node["inputs"], class_def, node_id, None)
64
+ try:
65
+ is_changed = _map_node_over_list(class_def, input_data_all, "IS_CHANGED")
66
+ node["is_changed"] = [None if isinstance(x, ExecutionBlocker) else x for x in is_changed]
67
+ except Exception as e:
68
+ logging.warning("WARNING: {}".format(e))
69
+ node["is_changed"] = float("NaN")
70
+ finally:
71
+ self.is_changed[node_id] = node["is_changed"]
72
+ return self.is_changed[node_id]
73
+
74
+
75
+ class CacheType(Enum):
76
+ CLASSIC = 0
77
+ LRU = 1
78
+ DEPENDENCY_AWARE = 2
79
+
80
+
81
+ class CacheSet:
82
+ def __init__(self, cache_type=None, cache_size=None):
83
+ if cache_type == CacheType.DEPENDENCY_AWARE:
84
+ self.init_dependency_aware_cache()
85
+ logging.info("Disabling intermediate node cache.")
86
+ elif cache_type == CacheType.LRU:
87
+ if cache_size is None:
88
+ cache_size = 0
89
+ self.init_lru_cache(cache_size)
90
+ logging.info("Using LRU cache")
91
+ else:
92
+ self.init_classic_cache()
93
+
94
+ self.all = [self.outputs, self.ui, self.objects]
95
+
96
+ # Performs like the old cache -- dump data ASAP
97
+ def init_classic_cache(self):
98
+ self.outputs = HierarchicalCache(CacheKeySetInputSignature)
99
+ self.ui = HierarchicalCache(CacheKeySetInputSignature)
100
+ self.objects = HierarchicalCache(CacheKeySetID)
101
+
102
+ def init_lru_cache(self, cache_size):
103
+ self.outputs = LRUCache(CacheKeySetInputSignature, max_size=cache_size)
104
+ self.ui = LRUCache(CacheKeySetInputSignature, max_size=cache_size)
105
+ self.objects = HierarchicalCache(CacheKeySetID)
106
+
107
+ # only hold cached items while the decendents have not executed
108
+ def init_dependency_aware_cache(self):
109
+ self.outputs = DependencyAwareCache(CacheKeySetInputSignature)
110
+ self.ui = DependencyAwareCache(CacheKeySetInputSignature)
111
+ self.objects = DependencyAwareCache(CacheKeySetID)
112
+
113
+ def recursive_debug_dump(self):
114
+ result = {
115
+ "outputs": self.outputs.recursive_debug_dump(),
116
+ "ui": self.ui.recursive_debug_dump(),
117
+ }
118
+ return result
119
+
120
+ def get_input_data(inputs, class_def, unique_id, outputs=None, dynprompt=None, extra_data={}):
121
+ valid_inputs = class_def.INPUT_TYPES()
122
+ input_data_all = {}
123
+ missing_keys = {}
124
+ for x in inputs:
125
+ input_data = inputs[x]
126
+ _, input_category, input_info = get_input_info(class_def, x, valid_inputs)
127
+ def mark_missing():
128
+ missing_keys[x] = True
129
+ input_data_all[x] = (None,)
130
+ if is_link(input_data) and (not input_info or not input_info.get("rawLink", False)):
131
+ input_unique_id = input_data[0]
132
+ output_index = input_data[1]
133
+ if outputs is None:
134
+ mark_missing()
135
+ continue # This might be a lazily-evaluated input
136
+ cached_output = outputs.get(input_unique_id)
137
+ if cached_output is None:
138
+ mark_missing()
139
+ continue
140
+ if output_index >= len(cached_output):
141
+ mark_missing()
142
+ continue
143
+ obj = cached_output[output_index]
144
+ input_data_all[x] = obj
145
+ elif input_category is not None:
146
+ input_data_all[x] = [input_data]
147
+
148
+ if "hidden" in valid_inputs:
149
+ h = valid_inputs["hidden"]
150
+ for x in h:
151
+ if h[x] == "PROMPT":
152
+ input_data_all[x] = [dynprompt.get_original_prompt() if dynprompt is not None else {}]
153
+ if h[x] == "DYNPROMPT":
154
+ input_data_all[x] = [dynprompt]
155
+ if h[x] == "EXTRA_PNGINFO":
156
+ input_data_all[x] = [extra_data.get('extra_pnginfo', None)]
157
+ if h[x] == "UNIQUE_ID":
158
+ input_data_all[x] = [unique_id]
159
+ if h[x] == "AUTH_TOKEN_COMFY_ORG":
160
+ input_data_all[x] = [extra_data.get("auth_token_comfy_org", None)]
161
+ if h[x] == "API_KEY_COMFY_ORG":
162
+ input_data_all[x] = [extra_data.get("api_key_comfy_org", None)]
163
+ return input_data_all, missing_keys
164
+
165
+ map_node_over_list = None #Don't hook this please
166
+
167
+ def _map_node_over_list(obj, input_data_all, func, allow_interrupt=False, execution_block_cb=None, pre_execute_cb=None):
168
+ # check if node wants the lists
169
+ input_is_list = getattr(obj, "INPUT_IS_LIST", False)
170
+
171
+ if len(input_data_all) == 0:
172
+ max_len_input = 0
173
+ else:
174
+ max_len_input = max(len(x) for x in input_data_all.values())
175
+
176
+ # get a slice of inputs, repeat last input when list isn't long enough
177
+ def slice_dict(d, i):
178
+ return {k: v[i if len(v) > i else -1] for k, v in d.items()}
179
+
180
+ results = []
181
+ def process_inputs(inputs, index=None, input_is_list=False):
182
+ if allow_interrupt:
183
+ nodes.before_node_execution()
184
+ execution_block = None
185
+ for k, v in inputs.items():
186
+ if input_is_list:
187
+ for e in v:
188
+ if isinstance(e, ExecutionBlocker):
189
+ v = e
190
+ break
191
+ if isinstance(v, ExecutionBlocker):
192
+ execution_block = execution_block_cb(v) if execution_block_cb else v
193
+ break
194
+ if execution_block is None:
195
+ if pre_execute_cb is not None and index is not None:
196
+ pre_execute_cb(index)
197
+ results.append(getattr(obj, func)(**inputs))
198
+ else:
199
+ results.append(execution_block)
200
+
201
+ if input_is_list:
202
+ process_inputs(input_data_all, 0, input_is_list=input_is_list)
203
+ elif max_len_input == 0:
204
+ process_inputs({})
205
+ else:
206
+ for i in range(max_len_input):
207
+ input_dict = slice_dict(input_data_all, i)
208
+ process_inputs(input_dict, i)
209
+ return results
210
+
211
+ def merge_result_data(results, obj):
212
+ # check which outputs need concatenating
213
+ output = []
214
+ output_is_list = [False] * len(results[0])
215
+ if hasattr(obj, "OUTPUT_IS_LIST"):
216
+ output_is_list = obj.OUTPUT_IS_LIST
217
+
218
+ # merge node execution results
219
+ for i, is_list in zip(range(len(results[0])), output_is_list):
220
+ if is_list:
221
+ value = []
222
+ for o in results:
223
+ if isinstance(o[i], ExecutionBlocker):
224
+ value.append(o[i])
225
+ else:
226
+ value.extend(o[i])
227
+ output.append(value)
228
+ else:
229
+ output.append([o[i] for o in results])
230
+ return output
231
+
232
+ def get_output_data(obj, input_data_all, execution_block_cb=None, pre_execute_cb=None):
233
+ results = []
234
+ uis = []
235
+ subgraph_results = []
236
+ 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)
237
+ has_subgraph = False
238
+ for i in range(len(return_values)):
239
+ r = return_values[i]
240
+ if isinstance(r, dict):
241
+ if 'ui' in r:
242
+ uis.append(r['ui'])
243
+ if 'expand' in r:
244
+ # Perform an expansion, but do not append results
245
+ has_subgraph = True
246
+ new_graph = r['expand']
247
+ result = r.get("result", None)
248
+ if isinstance(result, ExecutionBlocker):
249
+ result = tuple([result] * len(obj.RETURN_TYPES))
250
+ subgraph_results.append((new_graph, result))
251
+ elif 'result' in r:
252
+ result = r.get("result", None)
253
+ if isinstance(result, ExecutionBlocker):
254
+ result = tuple([result] * len(obj.RETURN_TYPES))
255
+ results.append(result)
256
+ subgraph_results.append((None, result))
257
+ else:
258
+ if isinstance(r, ExecutionBlocker):
259
+ r = tuple([r] * len(obj.RETURN_TYPES))
260
+ results.append(r)
261
+ subgraph_results.append((None, r))
262
+
263
+ if has_subgraph:
264
+ output = subgraph_results
265
+ elif len(results) > 0:
266
+ output = merge_result_data(results, obj)
267
+ else:
268
+ output = []
269
+ ui = dict()
270
+ if len(uis) > 0:
271
+ ui = {k: [y for x in uis for y in x[k]] for k in uis[0].keys()}
272
+ return output, ui, has_subgraph
273
+
274
+ def format_value(x):
275
+ if x is None:
276
+ return None
277
+ elif isinstance(x, (int, float, bool, str)):
278
+ return x
279
+ else:
280
+ return str(x)
281
+
282
+ def execute(server, dynprompt, caches, current_item, extra_data, executed, prompt_id, execution_list, pending_subgraph_results):
283
+ unique_id = current_item
284
+ real_node_id = dynprompt.get_real_node_id(unique_id)
285
+ display_node_id = dynprompt.get_display_node_id(unique_id)
286
+ parent_node_id = dynprompt.get_parent_node_id(unique_id)
287
+ inputs = dynprompt.get_node(unique_id)['inputs']
288
+ class_type = dynprompt.get_node(unique_id)['class_type']
289
+ class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
290
+ if caches.outputs.get(unique_id) is not None:
291
+ if server.client_id is not None:
292
+ cached_output = caches.ui.get(unique_id) or {}
293
+ 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)
294
+ return (ExecutionResult.SUCCESS, None, None)
295
+
296
+ input_data_all = None
297
+ try:
298
+ if unique_id in pending_subgraph_results:
299
+ cached_results = pending_subgraph_results[unique_id]
300
+ resolved_outputs = []
301
+ for is_subgraph, result in cached_results:
302
+ if not is_subgraph:
303
+ resolved_outputs.append(result)
304
+ else:
305
+ resolved_output = []
306
+ for r in result:
307
+ if is_link(r):
308
+ source_node, source_output = r[0], r[1]
309
+ node_output = caches.outputs.get(source_node)[source_output]
310
+ for o in node_output:
311
+ resolved_output.append(o)
312
+
313
+ else:
314
+ resolved_output.append(r)
315
+ resolved_outputs.append(tuple(resolved_output))
316
+ output_data = merge_result_data(resolved_outputs, class_def)
317
+ output_ui = []
318
+ has_subgraph = False
319
+ else:
320
+ input_data_all, missing_keys = get_input_data(inputs, class_def, unique_id, caches.outputs, dynprompt, extra_data)
321
+ if server.client_id is not None:
322
+ server.last_node_id = display_node_id
323
+ server.send_sync("executing", { "node": unique_id, "display_node": display_node_id, "prompt_id": prompt_id }, server.client_id)
324
+
325
+ obj = caches.objects.get(unique_id)
326
+ if obj is None:
327
+ obj = class_def()
328
+ caches.objects.set(unique_id, obj)
329
+
330
+ if hasattr(obj, "check_lazy_status"):
331
+ required_inputs = _map_node_over_list(obj, input_data_all, "check_lazy_status", allow_interrupt=True)
332
+ required_inputs = set(sum([r for r in required_inputs if isinstance(r,list)], []))
333
+ required_inputs = [x for x in required_inputs if isinstance(x,str) and (
334
+ x not in input_data_all or x in missing_keys
335
+ )]
336
+ if len(required_inputs) > 0:
337
+ for i in required_inputs:
338
+ execution_list.make_input_strong_link(unique_id, i)
339
+ return (ExecutionResult.PENDING, None, None)
340
+
341
+ def execution_block_cb(block):
342
+ if block.message is not None:
343
+ mes = {
344
+ "prompt_id": prompt_id,
345
+ "node_id": unique_id,
346
+ "node_type": class_type,
347
+ "executed": list(executed),
348
+
349
+ "exception_message": f"Execution Blocked: {block.message}",
350
+ "exception_type": "ExecutionBlocked",
351
+ "traceback": [],
352
+ "current_inputs": [],
353
+ "current_outputs": [],
354
+ }
355
+ server.send_sync("execution_error", mes, server.client_id)
356
+ return ExecutionBlocker(None)
357
+ else:
358
+ return block
359
+ def pre_execute_cb(call_index):
360
+ GraphBuilder.set_default_prefix(unique_id, call_index, 0)
361
+ 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)
362
+ if len(output_ui) > 0:
363
+ caches.ui.set(unique_id, {
364
+ "meta": {
365
+ "node_id": unique_id,
366
+ "display_node": display_node_id,
367
+ "parent_node": parent_node_id,
368
+ "real_node_id": real_node_id,
369
+ },
370
+ "output": output_ui
371
+ })
372
+ if server.client_id is not None:
373
+ server.send_sync("executed", { "node": unique_id, "display_node": display_node_id, "output": output_ui, "prompt_id": prompt_id }, server.client_id)
374
+ if has_subgraph:
375
+ cached_outputs = []
376
+ new_node_ids = []
377
+ new_output_ids = []
378
+ new_output_links = []
379
+ for i in range(len(output_data)):
380
+ new_graph, node_outputs = output_data[i]
381
+ if new_graph is None:
382
+ cached_outputs.append((False, node_outputs))
383
+ else:
384
+ # Check for conflicts
385
+ for node_id in new_graph.keys():
386
+ if dynprompt.has_node(node_id):
387
+ raise DuplicateNodeError(f"Attempt to add duplicate node {node_id}. Ensure node ids are unique and deterministic or use graph_utils.GraphBuilder.")
388
+ for node_id, node_info in new_graph.items():
389
+ new_node_ids.append(node_id)
390
+ display_id = node_info.get("override_display_id", unique_id)
391
+ dynprompt.add_ephemeral_node(node_id, node_info, unique_id, display_id)
392
+ # Figure out if the newly created node is an output node
393
+ class_type = node_info["class_type"]
394
+ class_def = nodes.NODE_CLASS_MAPPINGS[class_type]
395
+ if hasattr(class_def, 'OUTPUT_NODE') and class_def.OUTPUT_NODE == True:
396
+ new_output_ids.append(node_id)
397
+ for i in range(len(node_outputs)):
398
+ if is_link(node_outputs[i]):
399
+ from_node_id, from_socket = node_outputs[i][0], node_outputs[i][1]
400
+ new_output_links.append((from_node_id, from_socket))
401
+ cached_outputs.append((True, node_outputs))
402
+ new_node_ids = set(new_node_ids)
403
+ for cache in caches.all:
404
+ cache.ensure_subcache_for(unique_id, new_node_ids).clean_unused()
405
+ for node_id in new_output_ids:
406
+ execution_list.add_node(node_id)
407
+ for link in new_output_links:
408
+ execution_list.add_strong_link(link[0], link[1], unique_id)
409
+ pending_subgraph_results[unique_id] = cached_outputs
410
+ return (ExecutionResult.PENDING, None, None)
411
+ caches.outputs.set(unique_id, output_data)
412
+ except comfy.model_management.InterruptProcessingException as iex:
413
+ logging.info("Processing interrupted")
414
+
415
+ # skip formatting inputs/outputs
416
+ error_details = {
417
+ "node_id": real_node_id,
418
+ }
419
+
420
+ return (ExecutionResult.FAILURE, error_details, iex)
421
+ except Exception as ex:
422
+ typ, _, tb = sys.exc_info()
423
+ exception_type = full_type_name(typ)
424
+ input_data_formatted = {}
425
+ if input_data_all is not None:
426
+ input_data_formatted = {}
427
+ for name, inputs in input_data_all.items():
428
+ input_data_formatted[name] = [format_value(x) for x in inputs]
429
+
430
+ logging.error(f"!!! Exception during processing !!! {ex}")
431
+ logging.error(traceback.format_exc())
432
+
433
+ error_details = {
434
+ "node_id": real_node_id,
435
+ "exception_message": str(ex),
436
+ "exception_type": exception_type,
437
+ "traceback": traceback.format_tb(tb),
438
+ "current_inputs": input_data_formatted
439
+ }
440
+ if isinstance(ex, comfy.model_management.OOM_EXCEPTION):
441
+ logging.error("Got an OOM, unloading all loaded models.")
442
+ comfy.model_management.unload_all_models()
443
+
444
+ return (ExecutionResult.FAILURE, error_details, ex)
445
+
446
+ executed.add(unique_id)
447
+
448
+ return (ExecutionResult.SUCCESS, None, None)
449
+
450
+ class PromptExecutor:
451
+ def __init__(self, server, cache_type=False, cache_size=None):
452
+ self.cache_size = cache_size
453
+ self.cache_type = cache_type
454
+ self.server = server
455
+ self.reset()
456
+
457
+ def reset(self):
458
+ self.caches = CacheSet(cache_type=self.cache_type, cache_size=self.cache_size)
459
+ self.status_messages = []
460
+ self.success = True
461
+
462
+ def add_message(self, event, data: dict, broadcast: bool):
463
+ data = {
464
+ **data,
465
+ "timestamp": int(time.time() * 1000),
466
+ }
467
+ self.status_messages.append((event, data))
468
+ if self.server.client_id is not None or broadcast:
469
+ self.server.send_sync(event, data, self.server.client_id)
470
+
471
+ def handle_execution_error(self, prompt_id, prompt, current_outputs, executed, error, ex):
472
+ node_id = error["node_id"]
473
+ class_type = prompt[node_id]["class_type"]
474
+
475
+ # First, send back the status to the frontend depending
476
+ # on the exception type
477
+ if isinstance(ex, comfy.model_management.InterruptProcessingException):
478
+ mes = {
479
+ "prompt_id": prompt_id,
480
+ "node_id": node_id,
481
+ "node_type": class_type,
482
+ "executed": list(executed),
483
+ }
484
+ self.add_message("execution_interrupted", mes, broadcast=True)
485
+ else:
486
+ mes = {
487
+ "prompt_id": prompt_id,
488
+ "node_id": node_id,
489
+ "node_type": class_type,
490
+ "executed": list(executed),
491
+ "exception_message": error["exception_message"],
492
+ "exception_type": error["exception_type"],
493
+ "traceback": error["traceback"],
494
+ "current_inputs": error["current_inputs"],
495
+ "current_outputs": list(current_outputs),
496
+ }
497
+ self.add_message("execution_error", mes, broadcast=False)
498
+
499
+ def execute(self, prompt, prompt_id, extra_data={}, execute_outputs=[]):
500
+ nodes.interrupt_processing(False)
501
+
502
+ if "client_id" in extra_data:
503
+ self.server.client_id = extra_data["client_id"]
504
+ else:
505
+ self.server.client_id = None
506
+
507
+ self.status_messages = []
508
+ self.add_message("execution_start", { "prompt_id": prompt_id}, broadcast=False)
509
+
510
+ with torch.inference_mode():
511
+ dynamic_prompt = DynamicPrompt(prompt)
512
+ is_changed_cache = IsChangedCache(dynamic_prompt, self.caches.outputs)
513
+ for cache in self.caches.all:
514
+ cache.set_prompt(dynamic_prompt, prompt.keys(), is_changed_cache)
515
+ cache.clean_unused()
516
+
517
+ cached_nodes = []
518
+ for node_id in prompt:
519
+ if self.caches.outputs.get(node_id) is not None:
520
+ cached_nodes.append(node_id)
521
+
522
+ comfy.model_management.cleanup_models_gc()
523
+ self.add_message("execution_cached",
524
+ { "nodes": cached_nodes, "prompt_id": prompt_id},
525
+ broadcast=False)
526
+ pending_subgraph_results = {}
527
+ executed = set()
528
+ execution_list = ExecutionList(dynamic_prompt, self.caches.outputs)
529
+ current_outputs = self.caches.outputs.all_node_ids()
530
+ for node_id in list(execute_outputs):
531
+ execution_list.add_node(node_id)
532
+
533
+ while not execution_list.is_empty():
534
+ node_id, error, ex = execution_list.stage_node_execution()
535
+ if error is not None:
536
+ self.handle_execution_error(prompt_id, dynamic_prompt.original_prompt, current_outputs, executed, error, ex)
537
+ break
538
+
539
+ result, error, ex = execute(self.server, dynamic_prompt, self.caches, node_id, extra_data, executed, prompt_id, execution_list, pending_subgraph_results)
540
+ self.success = result != ExecutionResult.FAILURE
541
+ if result == ExecutionResult.FAILURE:
542
+ self.handle_execution_error(prompt_id, dynamic_prompt.original_prompt, current_outputs, executed, error, ex)
543
+ break
544
+ elif result == ExecutionResult.PENDING:
545
+ execution_list.unstage_node_execution()
546
+ else: # result == ExecutionResult.SUCCESS:
547
+ execution_list.complete_node_execution()
548
+ else:
549
+ # Only execute when the while-loop ends without break
550
+ self.add_message("execution_success", { "prompt_id": prompt_id }, broadcast=False)
551
+
552
+ ui_outputs = {}
553
+ meta_outputs = {}
554
+ all_node_ids = self.caches.ui.all_node_ids()
555
+ for node_id in all_node_ids:
556
+ ui_info = self.caches.ui.get(node_id)
557
+ if ui_info is not None:
558
+ ui_outputs[node_id] = ui_info["output"]
559
+ meta_outputs[node_id] = ui_info["meta"]
560
+ self.history_result = {
561
+ "outputs": ui_outputs,
562
+ "meta": meta_outputs,
563
+ }
564
+ self.server.last_node_id = None
565
+ if comfy.model_management.DISABLE_SMART_MEMORY:
566
+ comfy.model_management.unload_all_models()
567
+
568
+
569
+ def validate_inputs(prompt, item, validated):
570
+ unique_id = item
571
+ if unique_id in validated:
572
+ return validated[unique_id]
573
+
574
+ inputs = prompt[unique_id]['inputs']
575
+ class_type = prompt[unique_id]['class_type']
576
+ obj_class = nodes.NODE_CLASS_MAPPINGS[class_type]
577
+
578
+ class_inputs = obj_class.INPUT_TYPES()
579
+ valid_inputs = set(class_inputs.get('required',{})).union(set(class_inputs.get('optional',{})))
580
+
581
+ errors = []
582
+ valid = True
583
+
584
+ validate_function_inputs = []
585
+ validate_has_kwargs = False
586
+ if hasattr(obj_class, "VALIDATE_INPUTS"):
587
+ argspec = inspect.getfullargspec(obj_class.VALIDATE_INPUTS)
588
+ validate_function_inputs = argspec.args
589
+ validate_has_kwargs = argspec.varkw is not None
590
+ received_types = {}
591
+
592
+ for x in valid_inputs:
593
+ input_type, input_category, extra_info = get_input_info(obj_class, x, class_inputs)
594
+ assert extra_info is not None
595
+ if x not in inputs:
596
+ if input_category == "required":
597
+ error = {
598
+ "type": "required_input_missing",
599
+ "message": "Required input is missing",
600
+ "details": f"{x}",
601
+ "extra_info": {
602
+ "input_name": x
603
+ }
604
+ }
605
+ errors.append(error)
606
+ continue
607
+
608
+ val = inputs[x]
609
+ info = (input_type, extra_info)
610
+ if isinstance(val, list):
611
+ if len(val) != 2:
612
+ error = {
613
+ "type": "bad_linked_input",
614
+ "message": "Bad linked input, must be a length-2 list of [node_id, slot_index]",
615
+ "details": f"{x}",
616
+ "extra_info": {
617
+ "input_name": x,
618
+ "input_config": info,
619
+ "received_value": val
620
+ }
621
+ }
622
+ errors.append(error)
623
+ continue
624
+
625
+ o_id = val[0]
626
+ o_class_type = prompt[o_id]['class_type']
627
+ r = nodes.NODE_CLASS_MAPPINGS[o_class_type].RETURN_TYPES
628
+ received_type = r[val[1]]
629
+ received_types[x] = received_type
630
+ if 'input_types' not in validate_function_inputs and not validate_node_input(received_type, input_type):
631
+ details = f"{x}, received_type({received_type}) mismatch input_type({input_type})"
632
+ error = {
633
+ "type": "return_type_mismatch",
634
+ "message": "Return type mismatch between linked nodes",
635
+ "details": details,
636
+ "extra_info": {
637
+ "input_name": x,
638
+ "input_config": info,
639
+ "received_type": received_type,
640
+ "linked_node": val
641
+ }
642
+ }
643
+ errors.append(error)
644
+ continue
645
+ try:
646
+ r = validate_inputs(prompt, o_id, validated)
647
+ if r[0] is False:
648
+ # `r` will be set in `validated[o_id]` already
649
+ valid = False
650
+ continue
651
+ except Exception as ex:
652
+ typ, _, tb = sys.exc_info()
653
+ valid = False
654
+ exception_type = full_type_name(typ)
655
+ reasons = [{
656
+ "type": "exception_during_inner_validation",
657
+ "message": "Exception when validating inner node",
658
+ "details": str(ex),
659
+ "extra_info": {
660
+ "input_name": x,
661
+ "input_config": info,
662
+ "exception_message": str(ex),
663
+ "exception_type": exception_type,
664
+ "traceback": traceback.format_tb(tb),
665
+ "linked_node": val
666
+ }
667
+ }]
668
+ validated[o_id] = (False, reasons, o_id)
669
+ continue
670
+ else:
671
+ try:
672
+ # Unwraps values wrapped in __value__ key. This is used to pass
673
+ # list widget value to execution, as by default list value is
674
+ # reserved to represent the connection between nodes.
675
+ if isinstance(val, dict) and "__value__" in val:
676
+ val = val["__value__"]
677
+ inputs[x] = val
678
+
679
+ if input_type == "INT":
680
+ val = int(val)
681
+ inputs[x] = val
682
+ if input_type == "FLOAT":
683
+ val = float(val)
684
+ inputs[x] = val
685
+ if input_type == "STRING":
686
+ val = str(val)
687
+ inputs[x] = val
688
+ if input_type == "BOOLEAN":
689
+ val = bool(val)
690
+ inputs[x] = val
691
+ except Exception as ex:
692
+ error = {
693
+ "type": "invalid_input_type",
694
+ "message": f"Failed to convert an input value to a {input_type} value",
695
+ "details": f"{x}, {val}, {ex}",
696
+ "extra_info": {
697
+ "input_name": x,
698
+ "input_config": info,
699
+ "received_value": val,
700
+ "exception_message": str(ex)
701
+ }
702
+ }
703
+ errors.append(error)
704
+ continue
705
+
706
+ if x not in validate_function_inputs and not validate_has_kwargs:
707
+ if "min" in extra_info and val < extra_info["min"]:
708
+ error = {
709
+ "type": "value_smaller_than_min",
710
+ "message": "Value {} smaller than min of {}".format(val, extra_info["min"]),
711
+ "details": f"{x}",
712
+ "extra_info": {
713
+ "input_name": x,
714
+ "input_config": info,
715
+ "received_value": val,
716
+ }
717
+ }
718
+ errors.append(error)
719
+ continue
720
+ if "max" in extra_info and val > extra_info["max"]:
721
+ error = {
722
+ "type": "value_bigger_than_max",
723
+ "message": "Value {} bigger than max of {}".format(val, extra_info["max"]),
724
+ "details": f"{x}",
725
+ "extra_info": {
726
+ "input_name": x,
727
+ "input_config": info,
728
+ "received_value": val,
729
+ }
730
+ }
731
+ errors.append(error)
732
+ continue
733
+
734
+ if isinstance(input_type, list):
735
+ combo_options = input_type
736
+ if val not in combo_options:
737
+ input_config = info
738
+ list_info = ""
739
+
740
+ # Don't send back gigantic lists like if they're lots of
741
+ # scanned model filepaths
742
+ if len(combo_options) > 20:
743
+ list_info = f"(list of length {len(combo_options)})"
744
+ input_config = None
745
+ else:
746
+ list_info = str(combo_options)
747
+
748
+ error = {
749
+ "type": "value_not_in_list",
750
+ "message": "Value not in list",
751
+ "details": f"{x}: '{val}' not in {list_info}",
752
+ "extra_info": {
753
+ "input_name": x,
754
+ "input_config": input_config,
755
+ "received_value": val,
756
+ }
757
+ }
758
+ errors.append(error)
759
+ continue
760
+
761
+ if len(validate_function_inputs) > 0 or validate_has_kwargs:
762
+ input_data_all, _ = get_input_data(inputs, obj_class, unique_id)
763
+ input_filtered = {}
764
+ for x in input_data_all:
765
+ if x in validate_function_inputs or validate_has_kwargs:
766
+ input_filtered[x] = input_data_all[x]
767
+ if 'input_types' in validate_function_inputs:
768
+ input_filtered['input_types'] = [received_types]
769
+
770
+ #ret = obj_class.VALIDATE_INPUTS(**input_filtered)
771
+ ret = _map_node_over_list(obj_class, input_filtered, "VALIDATE_INPUTS")
772
+ for x in input_filtered:
773
+ for i, r in enumerate(ret):
774
+ if r is not True and not isinstance(r, ExecutionBlocker):
775
+ details = f"{x}"
776
+ if r is not False:
777
+ details += f" - {str(r)}"
778
+
779
+ error = {
780
+ "type": "custom_validation_failed",
781
+ "message": "Custom validation failed for node",
782
+ "details": details,
783
+ "extra_info": {
784
+ "input_name": x,
785
+ }
786
+ }
787
+ errors.append(error)
788
+ continue
789
+
790
+ if len(errors) > 0 or valid is not True:
791
+ ret = (False, errors, unique_id)
792
+ else:
793
+ ret = (True, [], unique_id)
794
+
795
+ validated[unique_id] = ret
796
+ return ret
797
+
798
+ def full_type_name(klass):
799
+ module = klass.__module__
800
+ if module == 'builtins':
801
+ return klass.__qualname__
802
+ return module + '.' + klass.__qualname__
803
+
804
+ def validate_prompt(prompt):
805
+ outputs = set()
806
+ for x in prompt:
807
+ if 'class_type' not in prompt[x]:
808
+ error = {
809
+ "type": "invalid_prompt",
810
+ "message": "Cannot execute because a node is missing the class_type property.",
811
+ "details": f"Node ID '#{x}'",
812
+ "extra_info": {}
813
+ }
814
+ return (False, error, [], {})
815
+
816
+ class_type = prompt[x]['class_type']
817
+ class_ = nodes.NODE_CLASS_MAPPINGS.get(class_type, None)
818
+ if class_ is None:
819
+ error = {
820
+ "type": "invalid_prompt",
821
+ "message": f"Cannot execute because node {class_type} does not exist.",
822
+ "details": f"Node ID '#{x}'",
823
+ "extra_info": {}
824
+ }
825
+ return (False, error, [], {})
826
+
827
+ if hasattr(class_, 'OUTPUT_NODE') and class_.OUTPUT_NODE is True:
828
+ outputs.add(x)
829
+
830
+ if len(outputs) == 0:
831
+ error = {
832
+ "type": "prompt_no_outputs",
833
+ "message": "Prompt has no outputs",
834
+ "details": "",
835
+ "extra_info": {}
836
+ }
837
+ return (False, error, [], {})
838
+
839
+ good_outputs = set()
840
+ errors = []
841
+ node_errors = {}
842
+ validated = {}
843
+ for o in outputs:
844
+ valid = False
845
+ reasons = []
846
+ try:
847
+ m = validate_inputs(prompt, o, validated)
848
+ valid = m[0]
849
+ reasons = m[1]
850
+ except Exception as ex:
851
+ typ, _, tb = sys.exc_info()
852
+ valid = False
853
+ exception_type = full_type_name(typ)
854
+ reasons = [{
855
+ "type": "exception_during_validation",
856
+ "message": "Exception when validating node",
857
+ "details": str(ex),
858
+ "extra_info": {
859
+ "exception_type": exception_type,
860
+ "traceback": traceback.format_tb(tb)
861
+ }
862
+ }]
863
+ validated[o] = (False, reasons, o)
864
+
865
+ if valid is True:
866
+ good_outputs.add(o)
867
+ else:
868
+ logging.error(f"Failed to validate prompt for output {o}:")
869
+ if len(reasons) > 0:
870
+ logging.error("* (prompt):")
871
+ for reason in reasons:
872
+ logging.error(f" - {reason['message']}: {reason['details']}")
873
+ errors += [(o, reasons)]
874
+ for node_id, result in validated.items():
875
+ valid = result[0]
876
+ reasons = result[1]
877
+ # If a node upstream has errors, the nodes downstream will also
878
+ # be reported as invalid, but there will be no errors attached.
879
+ # So don't return those nodes as having errors in the response.
880
+ if valid is not True and len(reasons) > 0:
881
+ if node_id not in node_errors:
882
+ class_type = prompt[node_id]['class_type']
883
+ node_errors[node_id] = {
884
+ "errors": reasons,
885
+ "dependent_outputs": [],
886
+ "class_type": class_type
887
+ }
888
+ logging.error(f"* {class_type} {node_id}:")
889
+ for reason in reasons:
890
+ logging.error(f" - {reason['message']}: {reason['details']}")
891
+ node_errors[node_id]["dependent_outputs"].append(o)
892
+ logging.error("Output will be ignored")
893
+
894
+ if len(good_outputs) == 0:
895
+ errors_list = []
896
+ for o, errors in errors:
897
+ for error in errors:
898
+ errors_list.append(f"{error['message']}: {error['details']}")
899
+ errors_list = "\n".join(errors_list)
900
+
901
+ error = {
902
+ "type": "prompt_outputs_failed_validation",
903
+ "message": "Prompt outputs failed validation",
904
+ "details": errors_list,
905
+ "extra_info": {}
906
+ }
907
+
908
+ return (False, error, list(good_outputs), node_errors)
909
+
910
+ return (True, None, list(good_outputs), node_errors)
911
+
912
+ MAXIMUM_HISTORY_SIZE = 10000
913
+
914
+ class PromptQueue:
915
+ def __init__(self, server):
916
+ self.server = server
917
+ self.mutex = threading.RLock()
918
+ self.not_empty = threading.Condition(self.mutex)
919
+ self.task_counter = 0
920
+ self.queue = []
921
+ self.currently_running = {}
922
+ self.history = {}
923
+ self.flags = {}
924
+
925
+ def put(self, item):
926
+ with self.mutex:
927
+ heapq.heappush(self.queue, item)
928
+ self.server.queue_updated()
929
+ self.not_empty.notify()
930
+
931
+ def get(self, timeout=None):
932
+ with self.not_empty:
933
+ while len(self.queue) == 0:
934
+ self.not_empty.wait(timeout=timeout)
935
+ if timeout is not None and len(self.queue) == 0:
936
+ return None
937
+ item = heapq.heappop(self.queue)
938
+ i = self.task_counter
939
+ self.currently_running[i] = copy.deepcopy(item)
940
+ self.task_counter += 1
941
+ self.server.queue_updated()
942
+ return (item, i)
943
+
944
+ class ExecutionStatus(NamedTuple):
945
+ status_str: Literal['success', 'error']
946
+ completed: bool
947
+ messages: List[str]
948
+
949
+ def task_done(self, item_id, history_result,
950
+ status: Optional['PromptQueue.ExecutionStatus']):
951
+ with self.mutex:
952
+ prompt = self.currently_running.pop(item_id)
953
+ if len(self.history) > MAXIMUM_HISTORY_SIZE:
954
+ self.history.pop(next(iter(self.history)))
955
+
956
+ status_dict: Optional[dict] = None
957
+ if status is not None:
958
+ status_dict = copy.deepcopy(status._asdict())
959
+
960
+ self.history[prompt[1]] = {
961
+ "prompt": prompt,
962
+ "outputs": {},
963
+ 'status': status_dict,
964
+ }
965
+ self.history[prompt[1]].update(history_result)
966
+ self.server.queue_updated()
967
+
968
+ # Note: slow
969
+ def get_current_queue(self):
970
+ with self.mutex:
971
+ out = []
972
+ for x in self.currently_running.values():
973
+ out += [x]
974
+ return (out, copy.deepcopy(self.queue))
975
+
976
+ # read-safe as long as queue items are immutable
977
+ def get_current_queue_volatile(self):
978
+ with self.mutex:
979
+ running = [x for x in self.currently_running.values()]
980
+ queued = copy.copy(self.queue)
981
+ return (running, queued)
982
+
983
+ def get_tasks_remaining(self):
984
+ with self.mutex:
985
+ return len(self.queue) + len(self.currently_running)
986
+
987
+ def wipe_queue(self):
988
+ with self.mutex:
989
+ self.queue = []
990
+ self.server.queue_updated()
991
+
992
+ def delete_queue_item(self, function):
993
+ with self.mutex:
994
+ for x in range(len(self.queue)):
995
+ if function(self.queue[x]):
996
+ if len(self.queue) == 1:
997
+ self.wipe_queue()
998
+ else:
999
+ self.queue.pop(x)
1000
+ heapq.heapify(self.queue)
1001
+ self.server.queue_updated()
1002
+ return True
1003
+ return False
1004
+
1005
+ def get_history(self, prompt_id=None, max_items=None, offset=-1):
1006
+ with self.mutex:
1007
+ if prompt_id is None:
1008
+ out = {}
1009
+ i = 0
1010
+ if offset < 0 and max_items is not None:
1011
+ offset = len(self.history) - max_items
1012
+ for k in self.history:
1013
+ if i >= offset:
1014
+ out[k] = self.history[k]
1015
+ if max_items is not None and len(out) >= max_items:
1016
+ break
1017
+ i += 1
1018
+ return out
1019
+ elif prompt_id in self.history:
1020
+ return {prompt_id: copy.deepcopy(self.history[prompt_id])}
1021
+ else:
1022
+ return {}
1023
+
1024
+ def wipe_history(self):
1025
+ with self.mutex:
1026
+ self.history = {}
1027
+
1028
+ def delete_history_item(self, id_to_delete):
1029
+ with self.mutex:
1030
+ self.history.pop(id_to_delete, None)
1031
+
1032
+ def set_flag(self, name, data):
1033
+ with self.mutex:
1034
+ self.flags[name] = data
1035
+ self.not_empty.notify()
1036
+
1037
+ def get_flags(self, reset=True):
1038
+ with self.mutex:
1039
+ if reset:
1040
+ ret = self.flags
1041
+ self.flags = {}
1042
+ return ret
1043
+ else:
1044
+ return self.flags.copy()
ComfyUI/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
ComfyUI/folder_paths.py ADDED
@@ -0,0 +1,425 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
280
+ Get the full path of a file in a folder, has to be a file
281
+ """
282
+ global folder_names_and_paths
283
+ folder_name = map_legacy(folder_name)
284
+ if folder_name not in folder_names_and_paths:
285
+ return None
286
+ folders = folder_names_and_paths[folder_name]
287
+ filename = os.path.relpath(os.path.join("/", filename), "/")
288
+ for x in folders[0]:
289
+ full_path = os.path.join(x, filename)
290
+ if os.path.isfile(full_path):
291
+ return full_path
292
+ elif os.path.islink(full_path):
293
+ logging.warning("WARNING path {} exists but doesn't link anywhere, skipping.".format(full_path))
294
+
295
+ return None
296
+
297
+
298
+ def get_full_path_or_raise(folder_name: str, filename: str) -> str:
299
+ """
300
+ Get the full path of a file in a folder, has to be a file
301
+ """
302
+ full_path = get_full_path(folder_name, filename)
303
+ if full_path is None:
304
+ raise FileNotFoundError(f"Model in folder '{folder_name}' with filename '{filename}' not found.")
305
+ return full_path
306
+
307
+
308
+ def get_filename_list_(folder_name: str) -> tuple[list[str], dict[str, float], float]:
309
+ folder_name = map_legacy(folder_name)
310
+ global folder_names_and_paths
311
+ output_list = set()
312
+ folders = folder_names_and_paths[folder_name]
313
+ output_folders = {}
314
+ for x in folders[0]:
315
+ files, folders_all = recursive_search(x, excluded_dir_names=[".git"])
316
+ output_list.update(filter_files_extensions(files, folders[1]))
317
+ output_folders = {**output_folders, **folders_all}
318
+
319
+ return sorted(list(output_list)), output_folders, time.perf_counter()
320
+
321
+ def cached_filename_list_(folder_name: str) -> tuple[list[str], dict[str, float], float] | None:
322
+ strong_cache = cache_helper.get(folder_name)
323
+ if strong_cache is not None:
324
+ return strong_cache
325
+
326
+ global filename_list_cache
327
+ global folder_names_and_paths
328
+ folder_name = map_legacy(folder_name)
329
+ if folder_name not in filename_list_cache:
330
+ return None
331
+ out = filename_list_cache[folder_name]
332
+
333
+ for x in out[1]:
334
+ time_modified = out[1][x]
335
+ folder = x
336
+ if os.path.getmtime(folder) != time_modified:
337
+ return None
338
+
339
+ folders = folder_names_and_paths[folder_name]
340
+ for x in folders[0]:
341
+ if os.path.isdir(x):
342
+ if x not in out[1]:
343
+ return None
344
+
345
+ return out
346
+
347
+ def get_filename_list(folder_name: str) -> list[str]:
348
+ folder_name = map_legacy(folder_name)
349
+ out = cached_filename_list_(folder_name)
350
+ if out is None:
351
+ out = get_filename_list_(folder_name)
352
+ global filename_list_cache
353
+ filename_list_cache[folder_name] = out
354
+ cache_helper.set(folder_name, out)
355
+ return list(out[0])
356
+
357
+ def get_save_image_path(filename_prefix: str, output_dir: str, image_width=0, image_height=0) -> tuple[str, str, int, str, str]:
358
+ def map_filename(filename: str) -> tuple[int, str]:
359
+ prefix_len = len(os.path.basename(filename_prefix))
360
+ prefix = filename[:prefix_len + 1]
361
+ try:
362
+ digits = int(filename[prefix_len + 1:].split('_')[0])
363
+ except:
364
+ digits = 0
365
+ return digits, prefix
366
+
367
+ def compute_vars(input: str, image_width: int, image_height: int) -> str:
368
+ input = input.replace("%width%", str(image_width))
369
+ input = input.replace("%height%", str(image_height))
370
+ now = time.localtime()
371
+ input = input.replace("%year%", str(now.tm_year))
372
+ input = input.replace("%month%", str(now.tm_mon).zfill(2))
373
+ input = input.replace("%day%", str(now.tm_mday).zfill(2))
374
+ input = input.replace("%hour%", str(now.tm_hour).zfill(2))
375
+ input = input.replace("%minute%", str(now.tm_min).zfill(2))
376
+ input = input.replace("%second%", str(now.tm_sec).zfill(2))
377
+ return input
378
+
379
+ if "%" in filename_prefix:
380
+ filename_prefix = compute_vars(filename_prefix, image_width, image_height)
381
+
382
+ subfolder = os.path.dirname(os.path.normpath(filename_prefix))
383
+ filename = os.path.basename(os.path.normpath(filename_prefix))
384
+
385
+ full_output_folder = os.path.join(output_dir, subfolder)
386
+
387
+ if os.path.commonpath((output_dir, os.path.abspath(full_output_folder))) != output_dir:
388
+ err = "**** ERROR: Saving image outside the output folder is not allowed." + \
389
+ "\n full_output_folder: " + os.path.abspath(full_output_folder) + \
390
+ "\n output_dir: " + output_dir + \
391
+ "\n commonpath: " + os.path.commonpath((output_dir, os.path.abspath(full_output_folder)))
392
+ logging.error(err)
393
+ raise Exception(err)
394
+
395
+ try:
396
+ 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
397
+ except ValueError:
398
+ counter = 1
399
+ except FileNotFoundError:
400
+ os.makedirs(full_output_folder, exist_ok=True)
401
+ counter = 1
402
+ return full_output_folder, filename, counter, subfolder, filename_prefix
403
+
404
+ def get_input_subfolders() -> list[str]:
405
+ """Returns a list of all subfolder paths in the input directory, recursively.
406
+
407
+ Returns:
408
+ List of folder paths relative to the input directory, excluding the root directory
409
+ """
410
+ input_dir = get_input_directory()
411
+ folders = []
412
+
413
+ try:
414
+ if not os.path.exists(input_dir):
415
+ return []
416
+
417
+ for root, dirs, _ in os.walk(input_dir):
418
+ rel_path = os.path.relpath(root, input_dir)
419
+ if rel_path != ".": # Only include non-root directories
420
+ # Normalize path separators to forward slashes
421
+ folders.append(rel_path.replace(os.sep, '/'))
422
+
423
+ return sorted(folders)
424
+ except FileNotFoundError:
425
+ return []
ComfyUI/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])
ComfyUI/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
+
ComfyUI/main.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ setup_logger(log_level=args.verbose, use_stdout=args.log_stdout)
21
+
22
+ def apply_custom_paths():
23
+ # extra model paths
24
+ extra_model_paths_config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "extra_model_paths.yaml")
25
+ if os.path.isfile(extra_model_paths_config_path):
26
+ utils.extra_config.load_extra_path_config(extra_model_paths_config_path)
27
+
28
+ if args.extra_model_paths_config:
29
+ for config_path in itertools.chain(*args.extra_model_paths_config):
30
+ utils.extra_config.load_extra_path_config(config_path)
31
+
32
+ # --output-directory, --input-directory, --user-directory
33
+ if args.output_directory:
34
+ output_dir = os.path.abspath(args.output_directory)
35
+ logging.info(f"Setting output directory to: {output_dir}")
36
+ folder_paths.set_output_directory(output_dir)
37
+
38
+ # These are the default folders that checkpoints, clip and vae models will be saved to when using CheckpointSave, etc.. nodes
39
+ folder_paths.add_model_folder_path("checkpoints", os.path.join(folder_paths.get_output_directory(), "checkpoints"))
40
+ folder_paths.add_model_folder_path("clip", os.path.join(folder_paths.get_output_directory(), "clip"))
41
+ folder_paths.add_model_folder_path("vae", os.path.join(folder_paths.get_output_directory(), "vae"))
42
+ folder_paths.add_model_folder_path("diffusion_models",
43
+ os.path.join(folder_paths.get_output_directory(), "diffusion_models"))
44
+ folder_paths.add_model_folder_path("loras", os.path.join(folder_paths.get_output_directory(), "loras"))
45
+
46
+ if args.input_directory:
47
+ input_dir = os.path.abspath(args.input_directory)
48
+ logging.info(f"Setting input directory to: {input_dir}")
49
+ folder_paths.set_input_directory(input_dir)
50
+
51
+ if args.user_directory:
52
+ user_dir = os.path.abspath(args.user_directory)
53
+ logging.info(f"Setting user directory to: {user_dir}")
54
+ folder_paths.set_user_directory(user_dir)
55
+
56
+
57
+ def execute_prestartup_script():
58
+ def execute_script(script_path):
59
+ module_name = os.path.splitext(script_path)[0]
60
+ try:
61
+ spec = importlib.util.spec_from_file_location(module_name, script_path)
62
+ module = importlib.util.module_from_spec(spec)
63
+ spec.loader.exec_module(module)
64
+ return True
65
+ except Exception as e:
66
+ logging.error(f"Failed to execute startup-script: {script_path} / {e}")
67
+ return False
68
+
69
+ if args.disable_all_custom_nodes:
70
+ return
71
+
72
+ node_paths = folder_paths.get_folder_paths("custom_nodes")
73
+ for custom_node_path in node_paths:
74
+ possible_modules = os.listdir(custom_node_path)
75
+ node_prestartup_times = []
76
+
77
+ for possible_module in possible_modules:
78
+ module_path = os.path.join(custom_node_path, possible_module)
79
+ if os.path.isfile(module_path) or module_path.endswith(".disabled") or module_path == "__pycache__":
80
+ continue
81
+
82
+ script_path = os.path.join(module_path, "prestartup_script.py")
83
+ if os.path.exists(script_path):
84
+ time_before = time.perf_counter()
85
+ success = execute_script(script_path)
86
+ node_prestartup_times.append((time.perf_counter() - time_before, module_path, success))
87
+ if len(node_prestartup_times) > 0:
88
+ logging.info("\nPrestartup times for custom nodes:")
89
+ for n in sorted(node_prestartup_times):
90
+ if n[2]:
91
+ import_message = ""
92
+ else:
93
+ import_message = " (PRESTARTUP FAILED)"
94
+ logging.info("{:6.1f} seconds{}: {}".format(n[0], import_message, n[1]))
95
+ logging.info("")
96
+
97
+ apply_custom_paths()
98
+ execute_prestartup_script()
99
+
100
+
101
+ # Main code
102
+ import asyncio
103
+ import shutil
104
+ import threading
105
+ import gc
106
+
107
+
108
+ if os.name == "nt":
109
+ logging.getLogger("xformers").addFilter(lambda record: 'A matching Triton is not available' not in record.getMessage())
110
+
111
+ if __name__ == "__main__":
112
+ if args.cuda_device is not None:
113
+ os.environ['CUDA_VISIBLE_DEVICES'] = str(args.cuda_device)
114
+ os.environ['HIP_VISIBLE_DEVICES'] = str(args.cuda_device)
115
+ logging.info("Set cuda device to: {}".format(args.cuda_device))
116
+
117
+ if args.oneapi_device_selector is not None:
118
+ os.environ['ONEAPI_DEVICE_SELECTOR'] = args.oneapi_device_selector
119
+ logging.info("Set oneapi device selector to: {}".format(args.oneapi_device_selector))
120
+
121
+ if args.deterministic:
122
+ if 'CUBLAS_WORKSPACE_CONFIG' not in os.environ:
123
+ os.environ['CUBLAS_WORKSPACE_CONFIG'] = ":4096:8"
124
+
125
+ import cuda_malloc
126
+
127
+ import comfy.utils
128
+
129
+ import execution
130
+ import server
131
+ from server import BinaryEventTypes
132
+ import nodes
133
+ import comfy.model_management
134
+ import comfyui_version
135
+ import app.logger
136
+ import hook_breaker_ac10a0
137
+
138
+ def cuda_malloc_warning():
139
+ device = comfy.model_management.get_torch_device()
140
+ device_name = comfy.model_management.get_torch_device_name(device)
141
+ cuda_malloc_warning = False
142
+ if "cudaMallocAsync" in device_name:
143
+ for b in cuda_malloc.blacklist:
144
+ if b in device_name:
145
+ cuda_malloc_warning = True
146
+ if cuda_malloc_warning:
147
+ 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")
148
+
149
+
150
+ def prompt_worker(q, server_instance):
151
+ current_time: float = 0.0
152
+ cache_type = execution.CacheType.CLASSIC
153
+ if args.cache_lru > 0:
154
+ cache_type = execution.CacheType.LRU
155
+ elif args.cache_none:
156
+ cache_type = execution.CacheType.DEPENDENCY_AWARE
157
+
158
+ e = execution.PromptExecutor(server_instance, cache_type=cache_type, cache_size=args.cache_lru)
159
+ last_gc_collect = 0
160
+ need_gc = False
161
+ gc_collect_interval = 10.0
162
+
163
+ while True:
164
+ timeout = 1000.0
165
+ if need_gc:
166
+ timeout = max(gc_collect_interval - (current_time - last_gc_collect), 0.0)
167
+
168
+ queue_item = q.get(timeout=timeout)
169
+ if queue_item is not None:
170
+ item, item_id = queue_item
171
+ execution_start_time = time.perf_counter()
172
+ prompt_id = item[1]
173
+ server_instance.last_prompt_id = prompt_id
174
+
175
+ e.execute(item[2], prompt_id, item[3], item[4])
176
+ need_gc = True
177
+ q.task_done(item_id,
178
+ e.history_result,
179
+ status=execution.PromptQueue.ExecutionStatus(
180
+ status_str='success' if e.success else 'error',
181
+ completed=e.success,
182
+ messages=e.status_messages))
183
+ if server_instance.client_id is not None:
184
+ server_instance.send_sync("executing", {"node": None, "prompt_id": prompt_id}, server_instance.client_id)
185
+
186
+ current_time = time.perf_counter()
187
+ execution_time = current_time - execution_start_time
188
+ logging.info("Prompt executed in {:.2f} seconds".format(execution_time))
189
+
190
+ flags = q.get_flags()
191
+ free_memory = flags.get("free_memory", False)
192
+
193
+ if flags.get("unload_models", free_memory):
194
+ comfy.model_management.unload_all_models()
195
+ need_gc = True
196
+ last_gc_collect = 0
197
+
198
+ if free_memory:
199
+ e.reset()
200
+ need_gc = True
201
+ last_gc_collect = 0
202
+
203
+ if need_gc:
204
+ current_time = time.perf_counter()
205
+ if (current_time - last_gc_collect) > gc_collect_interval:
206
+ gc.collect()
207
+ comfy.model_management.soft_empty_cache()
208
+ last_gc_collect = current_time
209
+ need_gc = False
210
+ hook_breaker_ac10a0.restore_functions()
211
+
212
+
213
+ async def run(server_instance, address='', port=8188, verbose=True, call_on_start=None):
214
+ addresses = []
215
+ for addr in address.split(","):
216
+ addresses.append((addr, port))
217
+ await asyncio.gather(
218
+ server_instance.start_multi_address(addresses, call_on_start, verbose), server_instance.publish_loop()
219
+ )
220
+
221
+
222
+ def hijack_progress(server_instance):
223
+ def hook(value, total, preview_image):
224
+ comfy.model_management.throw_exception_if_processing_interrupted()
225
+ progress = {"value": value, "max": total, "prompt_id": server_instance.last_prompt_id, "node": server_instance.last_node_id}
226
+
227
+ server_instance.send_sync("progress", progress, server_instance.client_id)
228
+ if preview_image is not None:
229
+ server_instance.send_sync(BinaryEventTypes.UNENCODED_PREVIEW_IMAGE, preview_image, server_instance.client_id)
230
+
231
+ comfy.utils.set_progress_bar_global_hook(hook)
232
+
233
+
234
+ def cleanup_temp():
235
+ temp_dir = folder_paths.get_temp_directory()
236
+ if os.path.exists(temp_dir):
237
+ shutil.rmtree(temp_dir, ignore_errors=True)
238
+
239
+
240
+ def setup_database():
241
+ try:
242
+ from app.database.db import init_db, dependencies_available
243
+ if dependencies_available():
244
+ init_db()
245
+ except Exception as e:
246
+ logging.error(f"Failed to initialize database. Please ensure you have installed the latest requirements. If the error persists, please report this as in future the database will be required: {e}")
247
+
248
+
249
+ def start_comfyui(asyncio_loop=None):
250
+ """
251
+ Starts the ComfyUI server using the provided asyncio event loop or creates a new one.
252
+ Returns the event loop, server instance, and a function to start the server asynchronously.
253
+ """
254
+ if args.temp_directory:
255
+ temp_dir = os.path.join(os.path.abspath(args.temp_directory), "temp")
256
+ logging.info(f"Setting temp directory to: {temp_dir}")
257
+ folder_paths.set_temp_directory(temp_dir)
258
+ cleanup_temp()
259
+
260
+ if args.windows_standalone_build:
261
+ try:
262
+ import new_updater
263
+ new_updater.update_windows_updater()
264
+ except:
265
+ pass
266
+
267
+ if not asyncio_loop:
268
+ asyncio_loop = asyncio.new_event_loop()
269
+ asyncio.set_event_loop(asyncio_loop)
270
+ prompt_server = server.PromptServer(asyncio_loop)
271
+
272
+ hook_breaker_ac10a0.save_functions()
273
+ nodes.init_extra_nodes(init_custom_nodes=not args.disable_all_custom_nodes, init_api_nodes=not args.disable_api_nodes)
274
+ hook_breaker_ac10a0.restore_functions()
275
+
276
+ cuda_malloc_warning()
277
+ setup_database()
278
+
279
+ prompt_server.add_routes()
280
+ hijack_progress(prompt_server)
281
+
282
+ threading.Thread(target=prompt_worker, daemon=True, args=(prompt_server.prompt_queue, prompt_server,)).start()
283
+
284
+ if args.quick_test_for_ci:
285
+ exit(0)
286
+
287
+ os.makedirs(folder_paths.get_temp_directory(), exist_ok=True)
288
+ call_on_start = None
289
+ if args.auto_launch:
290
+ def startup_server(scheme, address, port):
291
+ import webbrowser
292
+ if os.name == 'nt' and address == '0.0.0.0':
293
+ address = '127.0.0.1'
294
+ if ':' in address:
295
+ address = "[{}]".format(address)
296
+ webbrowser.open(f"{scheme}://{address}:{port}")
297
+ call_on_start = startup_server
298
+
299
+ async def start_all():
300
+ await prompt_server.setup()
301
+ await run(prompt_server, address=args.listen, port=args.port, verbose=not args.dont_print_server, call_on_start=call_on_start)
302
+
303
+ # Returning these so that other code can integrate with the ComfyUI loop and server
304
+ return asyncio_loop, prompt_server, start_all
305
+
306
+
307
+ if __name__ == "__main__":
308
+ # Running directly, just start ComfyUI.
309
+ logging.info("Python version: {}".format(sys.version))
310
+ logging.info("ComfyUI version: {}".format(comfyui_version.__version__))
311
+
312
+ if sys.version_info.major == 3 and sys.version_info.minor < 10:
313
+ logging.warning("WARNING: You are using a python version older than 3.10, please upgrade to a newer one. 3.12 and above is recommended.")
314
+
315
+ event_loop, _, start_all_func = start_comfyui()
316
+ try:
317
+ x = start_all_func()
318
+ app.logger.print_startup_warnings()
319
+ event_loop.run_until_complete(x)
320
+ except KeyboardInterrupt:
321
+ logging.info("\nStopped server")
322
+
323
+ cleanup_temp()
ComfyUI/new_updater.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+
4
+ base_path = os.path.dirname(os.path.realpath(__file__))
5
+
6
+
7
+ def update_windows_updater():
8
+ top_path = os.path.dirname(base_path)
9
+ updater_path = os.path.join(base_path, ".ci/update_windows/update.py")
10
+ bat_path = os.path.join(base_path, ".ci/update_windows/update_comfyui.bat")
11
+
12
+ dest_updater_path = os.path.join(top_path, "update/update.py")
13
+ dest_bat_path = os.path.join(top_path, "update/update_comfyui.bat")
14
+ dest_bat_deps_path = os.path.join(top_path, "update/update_comfyui_and_python_dependencies.bat")
15
+
16
+ try:
17
+ with open(dest_bat_path, 'rb') as f:
18
+ contents = f.read()
19
+ except:
20
+ return
21
+
22
+ if not contents.startswith(b"..\\python_embeded\\python.exe .\\update.py"):
23
+ return
24
+
25
+ shutil.copy(updater_path, dest_updater_path)
26
+ try:
27
+ with open(dest_bat_deps_path, 'rb') as f:
28
+ contents = f.read()
29
+ contents = contents.replace(b'..\\python_embeded\\python.exe .\\update.py ..\\ComfyUI\\', b'call update_comfyui.bat nopause')
30
+ with open(dest_bat_deps_path, 'wb') as f:
31
+ f.write(contents)
32
+ except:
33
+ pass
34
+ shutil.copy(bat_path, dest_bat_path)
35
+ print("Updated the windows standalone package updater.") # noqa: T201
ComfyUI/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
ComfyUI/nodes.py ADDED
The diff for this file is too large to render. See raw diff
 
ComfyUI/pyproject.toml ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "ComfyUI"
3
+ version = "0.3.41"
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"]
ComfyUI/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 = .
ComfyUI/requirements.txt ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ comfyui-frontend-package==1.21.7
2
+ comfyui-workflow-templates==0.1.28
3
+ comfyui-embedded-docs==0.2.2
4
+ torch
5
+ torchsde
6
+ torchvision
7
+ torchaudio
8
+ numpy>=1.25.0
9
+ einops
10
+ transformers>=4.28.1
11
+ tokenizers>=0.13.3
12
+ sentencepiece
13
+ safetensors>=0.4.2
14
+ aiohttp>=3.11.8
15
+ yarl>=1.18.0
16
+ pyyaml
17
+ Pillow
18
+ scipy
19
+ tqdm
20
+ psutil
21
+ alembic
22
+ SQLAlchemy
23
+
24
+ #non essential dependencies:
25
+ kornia>=0.7.1
26
+ spandrel
27
+ soundfile
28
+ av>=14.2.0
29
+ pydantic~=2.0
30
+ pydantic-settings~=2.0
ComfyUI/server.py ADDED
@@ -0,0 +1,899 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 mimetypes to download instead of display
480
+ if content_type in {'text/html', 'text/html-sandboxed', 'application/xhtml+xml', 'text/javascript', 'text/css'}:
481
+ content_type = 'application/octet-stream' # Forces download
482
+
483
+ return web.FileResponse(
484
+ file,
485
+ headers={
486
+ "Content-Disposition": f"filename=\"{filename}\"",
487
+ "Content-Type": content_type
488
+ }
489
+ )
490
+
491
+ return web.Response(status=404)
492
+
493
+ @routes.get("/view_metadata/{folder_name}")
494
+ async def view_metadata(request):
495
+ folder_name = request.match_info.get("folder_name", None)
496
+ if folder_name is None:
497
+ return web.Response(status=404)
498
+ if not "filename" in request.rel_url.query:
499
+ return web.Response(status=404)
500
+
501
+ filename = request.rel_url.query["filename"]
502
+ if not filename.endswith(".safetensors"):
503
+ return web.Response(status=404)
504
+
505
+ safetensors_path = folder_paths.get_full_path(folder_name, filename)
506
+ if safetensors_path is None:
507
+ return web.Response(status=404)
508
+ out = comfy.utils.safetensors_header(safetensors_path, max_size=1024*1024)
509
+ if out is None:
510
+ return web.Response(status=404)
511
+ dt = json.loads(out)
512
+ if not "__metadata__" in dt:
513
+ return web.Response(status=404)
514
+ return web.json_response(dt["__metadata__"])
515
+
516
+ @routes.get("/system_stats")
517
+ async def system_stats(request):
518
+ device = comfy.model_management.get_torch_device()
519
+ device_name = comfy.model_management.get_torch_device_name(device)
520
+ cpu_device = comfy.model_management.torch.device("cpu")
521
+ ram_total = comfy.model_management.get_total_memory(cpu_device)
522
+ ram_free = comfy.model_management.get_free_memory(cpu_device)
523
+ vram_total, torch_vram_total = comfy.model_management.get_total_memory(device, torch_total_too=True)
524
+ vram_free, torch_vram_free = comfy.model_management.get_free_memory(device, torch_free_too=True)
525
+
526
+ system_stats = {
527
+ "system": {
528
+ "os": os.name,
529
+ "ram_total": ram_total,
530
+ "ram_free": ram_free,
531
+ "comfyui_version": __version__,
532
+ "python_version": sys.version,
533
+ "pytorch_version": comfy.model_management.torch_version,
534
+ "embedded_python": os.path.split(os.path.split(sys.executable)[0])[1] == "python_embeded",
535
+ "argv": sys.argv
536
+ },
537
+ "devices": [
538
+ {
539
+ "name": device_name,
540
+ "type": device.type,
541
+ "index": device.index,
542
+ "vram_total": vram_total,
543
+ "vram_free": vram_free,
544
+ "torch_vram_total": torch_vram_total,
545
+ "torch_vram_free": torch_vram_free,
546
+ }
547
+ ]
548
+ }
549
+ return web.json_response(system_stats)
550
+
551
+ @routes.get("/prompt")
552
+ async def get_prompt(request):
553
+ return web.json_response(self.get_queue_info())
554
+
555
+ def node_info(node_class):
556
+ obj_class = nodes.NODE_CLASS_MAPPINGS[node_class]
557
+ info = {}
558
+ info['input'] = obj_class.INPUT_TYPES()
559
+ info['input_order'] = {key: list(value.keys()) for (key, value) in obj_class.INPUT_TYPES().items()}
560
+ info['output'] = obj_class.RETURN_TYPES
561
+ info['output_is_list'] = obj_class.OUTPUT_IS_LIST if hasattr(obj_class, 'OUTPUT_IS_LIST') else [False] * len(obj_class.RETURN_TYPES)
562
+ info['output_name'] = obj_class.RETURN_NAMES if hasattr(obj_class, 'RETURN_NAMES') else info['output']
563
+ info['name'] = node_class
564
+ info['display_name'] = nodes.NODE_DISPLAY_NAME_MAPPINGS[node_class] if node_class in nodes.NODE_DISPLAY_NAME_MAPPINGS.keys() else node_class
565
+ info['description'] = obj_class.DESCRIPTION if hasattr(obj_class,'DESCRIPTION') else ''
566
+ info['python_module'] = getattr(obj_class, "RELATIVE_PYTHON_MODULE", "nodes")
567
+ info['category'] = 'sd'
568
+ if hasattr(obj_class, 'OUTPUT_NODE') and obj_class.OUTPUT_NODE == True:
569
+ info['output_node'] = True
570
+ else:
571
+ info['output_node'] = False
572
+
573
+ if hasattr(obj_class, 'CATEGORY'):
574
+ info['category'] = obj_class.CATEGORY
575
+
576
+ if hasattr(obj_class, 'OUTPUT_TOOLTIPS'):
577
+ info['output_tooltips'] = obj_class.OUTPUT_TOOLTIPS
578
+
579
+ if getattr(obj_class, "DEPRECATED", False):
580
+ info['deprecated'] = True
581
+ if getattr(obj_class, "EXPERIMENTAL", False):
582
+ info['experimental'] = True
583
+
584
+ if hasattr(obj_class, 'API_NODE'):
585
+ info['api_node'] = obj_class.API_NODE
586
+ return info
587
+
588
+ @routes.get("/object_info")
589
+ async def get_object_info(request):
590
+ with folder_paths.cache_helper:
591
+ out = {}
592
+ for x in nodes.NODE_CLASS_MAPPINGS:
593
+ try:
594
+ out[x] = node_info(x)
595
+ except Exception:
596
+ logging.error(f"[ERROR] An error occurred while retrieving information for the '{x}' node.")
597
+ logging.error(traceback.format_exc())
598
+ return web.json_response(out)
599
+
600
+ @routes.get("/object_info/{node_class}")
601
+ async def get_object_info_node(request):
602
+ node_class = request.match_info.get("node_class", None)
603
+ out = {}
604
+ if (node_class is not None) and (node_class in nodes.NODE_CLASS_MAPPINGS):
605
+ out[node_class] = node_info(node_class)
606
+ return web.json_response(out)
607
+
608
+ @routes.get("/history")
609
+ async def get_history(request):
610
+ max_items = request.rel_url.query.get("max_items", None)
611
+ if max_items is not None:
612
+ max_items = int(max_items)
613
+ return web.json_response(self.prompt_queue.get_history(max_items=max_items))
614
+
615
+ @routes.get("/history/{prompt_id}")
616
+ async def get_history_prompt_id(request):
617
+ prompt_id = request.match_info.get("prompt_id", None)
618
+ return web.json_response(self.prompt_queue.get_history(prompt_id=prompt_id))
619
+
620
+ @routes.get("/queue")
621
+ async def get_queue(request):
622
+ queue_info = {}
623
+ current_queue = self.prompt_queue.get_current_queue_volatile()
624
+ queue_info['queue_running'] = current_queue[0]
625
+ queue_info['queue_pending'] = current_queue[1]
626
+ return web.json_response(queue_info)
627
+
628
+ @routes.post("/prompt")
629
+ async def post_prompt(request):
630
+ logging.info("got prompt")
631
+ json_data = await request.json()
632
+ json_data = self.trigger_on_prompt(json_data)
633
+
634
+ if "number" in json_data:
635
+ number = float(json_data['number'])
636
+ else:
637
+ number = self.number
638
+ if "front" in json_data:
639
+ if json_data['front']:
640
+ number = -number
641
+
642
+ self.number += 1
643
+
644
+ if "prompt" in json_data:
645
+ prompt = json_data["prompt"]
646
+ valid = execution.validate_prompt(prompt)
647
+ extra_data = {}
648
+ if "extra_data" in json_data:
649
+ extra_data = json_data["extra_data"]
650
+
651
+ if "client_id" in json_data:
652
+ extra_data["client_id"] = json_data["client_id"]
653
+ if valid[0]:
654
+ prompt_id = str(uuid.uuid4())
655
+ outputs_to_execute = valid[2]
656
+ self.prompt_queue.put((number, prompt_id, prompt, extra_data, outputs_to_execute))
657
+ response = {"prompt_id": prompt_id, "number": number, "node_errors": valid[3]}
658
+ return web.json_response(response)
659
+ else:
660
+ logging.warning("invalid prompt: {}".format(valid[1]))
661
+ return web.json_response({"error": valid[1], "node_errors": valid[3]}, status=400)
662
+ else:
663
+ error = {
664
+ "type": "no_prompt",
665
+ "message": "No prompt provided",
666
+ "details": "No prompt provided",
667
+ "extra_info": {}
668
+ }
669
+ return web.json_response({"error": error, "node_errors": {}}, status=400)
670
+
671
+ @routes.post("/queue")
672
+ async def post_queue(request):
673
+ json_data = await request.json()
674
+ if "clear" in json_data:
675
+ if json_data["clear"]:
676
+ self.prompt_queue.wipe_queue()
677
+ if "delete" in json_data:
678
+ to_delete = json_data['delete']
679
+ for id_to_delete in to_delete:
680
+ delete_func = lambda a: a[1] == id_to_delete
681
+ self.prompt_queue.delete_queue_item(delete_func)
682
+
683
+ return web.Response(status=200)
684
+
685
+ @routes.post("/interrupt")
686
+ async def post_interrupt(request):
687
+ nodes.interrupt_processing()
688
+ return web.Response(status=200)
689
+
690
+ @routes.post("/free")
691
+ async def post_free(request):
692
+ json_data = await request.json()
693
+ unload_models = json_data.get("unload_models", False)
694
+ free_memory = json_data.get("free_memory", False)
695
+ if unload_models:
696
+ self.prompt_queue.set_flag("unload_models", unload_models)
697
+ if free_memory:
698
+ self.prompt_queue.set_flag("free_memory", free_memory)
699
+ return web.Response(status=200)
700
+
701
+ @routes.post("/history")
702
+ async def post_history(request):
703
+ json_data = await request.json()
704
+ if "clear" in json_data:
705
+ if json_data["clear"]:
706
+ self.prompt_queue.wipe_history()
707
+ if "delete" in json_data:
708
+ to_delete = json_data['delete']
709
+ for id_to_delete in to_delete:
710
+ self.prompt_queue.delete_history_item(id_to_delete)
711
+
712
+ return web.Response(status=200)
713
+
714
+ async def setup(self):
715
+ timeout = aiohttp.ClientTimeout(total=None) # no timeout
716
+ self.client_session = aiohttp.ClientSession(timeout=timeout)
717
+
718
+ def add_routes(self):
719
+ self.user_manager.add_routes(self.routes)
720
+ self.model_file_manager.add_routes(self.routes)
721
+ self.custom_node_manager.add_routes(self.routes, self.app, nodes.LOADED_MODULE_DIRS.items())
722
+ self.app.add_subapp('/internal', self.internal_routes.get_app())
723
+
724
+ # Prefix every route with /api for easier matching for delegation.
725
+ # This is very useful for frontend dev server, which need to forward
726
+ # everything except serving of static files.
727
+ # Currently both the old endpoints without prefix and new endpoints with
728
+ # prefix are supported.
729
+ api_routes = web.RouteTableDef()
730
+ for route in self.routes:
731
+ # Custom nodes might add extra static routes. Only process non-static
732
+ # routes to add /api prefix.
733
+ if isinstance(route, web.RouteDef):
734
+ api_routes.route(route.method, "/api" + route.path)(route.handler, **route.kwargs)
735
+ self.app.add_routes(api_routes)
736
+ self.app.add_routes(self.routes)
737
+
738
+ # Add routes from web extensions.
739
+ for name, dir in nodes.EXTENSION_WEB_DIRS.items():
740
+ self.app.add_routes([web.static('/extensions/' + name, dir)])
741
+
742
+ workflow_templates_path = FrontendManager.templates_path()
743
+ if workflow_templates_path:
744
+ self.app.add_routes([
745
+ web.static('/templates', workflow_templates_path)
746
+ ])
747
+
748
+ # Serve embedded documentation from the package
749
+ embedded_docs_path = FrontendManager.embedded_docs_path()
750
+ if embedded_docs_path:
751
+ self.app.add_routes([
752
+ web.static('/docs', embedded_docs_path)
753
+ ])
754
+
755
+ self.app.add_routes([
756
+ web.static('/', self.web_root),
757
+ ])
758
+
759
+ def get_queue_info(self):
760
+ prompt_info = {}
761
+ exec_info = {}
762
+ exec_info['queue_remaining'] = self.prompt_queue.get_tasks_remaining()
763
+ prompt_info['exec_info'] = exec_info
764
+ return prompt_info
765
+
766
+ async def send(self, event, data, sid=None):
767
+ if event == BinaryEventTypes.UNENCODED_PREVIEW_IMAGE:
768
+ await self.send_image(data, sid=sid)
769
+ elif isinstance(data, (bytes, bytearray)):
770
+ await self.send_bytes(event, data, sid)
771
+ else:
772
+ await self.send_json(event, data, sid)
773
+
774
+ def encode_bytes(self, event, data):
775
+ if not isinstance(event, int):
776
+ raise RuntimeError(f"Binary event types must be integers, got {event}")
777
+
778
+ packed = struct.pack(">I", event)
779
+ message = bytearray(packed)
780
+ message.extend(data)
781
+ return message
782
+
783
+ async def send_image(self, image_data, sid=None):
784
+ image_type = image_data[0]
785
+ image = image_data[1]
786
+ max_size = image_data[2]
787
+ if max_size is not None:
788
+ if hasattr(Image, 'Resampling'):
789
+ resampling = Image.Resampling.BILINEAR
790
+ else:
791
+ resampling = Image.Resampling.LANCZOS
792
+
793
+ image = ImageOps.contain(image, (max_size, max_size), resampling)
794
+ type_num = 1
795
+ if image_type == "JPEG":
796
+ type_num = 1
797
+ elif image_type == "PNG":
798
+ type_num = 2
799
+
800
+ bytesIO = BytesIO()
801
+ header = struct.pack(">I", type_num)
802
+ bytesIO.write(header)
803
+ image.save(bytesIO, format=image_type, quality=95, compress_level=1)
804
+ preview_bytes = bytesIO.getvalue()
805
+ await self.send_bytes(BinaryEventTypes.PREVIEW_IMAGE, preview_bytes, sid=sid)
806
+
807
+ async def send_bytes(self, event, data, sid=None):
808
+ message = self.encode_bytes(event, data)
809
+
810
+ if sid is None:
811
+ sockets = list(self.sockets.values())
812
+ for ws in sockets:
813
+ await send_socket_catch_exception(ws.send_bytes, message)
814
+ elif sid in self.sockets:
815
+ await send_socket_catch_exception(self.sockets[sid].send_bytes, message)
816
+
817
+ async def send_json(self, event, data, sid=None):
818
+ message = {"type": event, "data": data}
819
+
820
+ if sid is None:
821
+ sockets = list(self.sockets.values())
822
+ for ws in sockets:
823
+ await send_socket_catch_exception(ws.send_json, message)
824
+ elif sid in self.sockets:
825
+ await send_socket_catch_exception(self.sockets[sid].send_json, message)
826
+
827
+ def send_sync(self, event, data, sid=None):
828
+ self.loop.call_soon_threadsafe(
829
+ self.messages.put_nowait, (event, data, sid))
830
+
831
+ def queue_updated(self):
832
+ self.send_sync("status", { "status": self.get_queue_info() })
833
+
834
+ async def publish_loop(self):
835
+ while True:
836
+ msg = await self.messages.get()
837
+ await self.send(*msg)
838
+
839
+ async def start(self, address, port, verbose=True, call_on_start=None):
840
+ await self.start_multi_address([(address, port)], call_on_start=call_on_start)
841
+
842
+ async def start_multi_address(self, addresses, call_on_start=None, verbose=True):
843
+ runner = web.AppRunner(self.app, access_log=None)
844
+ await runner.setup()
845
+ ssl_ctx = None
846
+ scheme = "http"
847
+ if args.tls_keyfile and args.tls_certfile:
848
+ ssl_ctx = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_SERVER, verify_mode=ssl.CERT_NONE)
849
+ ssl_ctx.load_cert_chain(certfile=args.tls_certfile,
850
+ keyfile=args.tls_keyfile)
851
+ scheme = "https"
852
+
853
+ if verbose:
854
+ logging.info("Starting server\n")
855
+ for addr in addresses:
856
+ address = addr[0]
857
+ port = addr[1]
858
+ site = web.TCPSite(runner, address, port, ssl_context=ssl_ctx)
859
+ await site.start()
860
+
861
+ if not hasattr(self, 'address'):
862
+ self.address = address #TODO: remove this
863
+ self.port = port
864
+
865
+ if ':' in address:
866
+ address_print = "[{}]".format(address)
867
+ else:
868
+ address_print = address
869
+
870
+ if verbose:
871
+ logging.info("To see the GUI go to: {}://{}:{}".format(scheme, address_print, port))
872
+
873
+ if call_on_start is not None:
874
+ call_on_start(scheme, self.address, self.port)
875
+
876
+ def add_on_prompt_handler(self, handler):
877
+ self.on_prompt_handlers.append(handler)
878
+
879
+ def trigger_on_prompt(self, json_data):
880
+ for handler in self.on_prompt_handlers:
881
+ try:
882
+ json_data = handler(json_data)
883
+ except Exception:
884
+ logging.warning("[ERROR] An error occurred during the on_prompt_handler processing")
885
+ logging.warning(traceback.format_exc())
886
+
887
+ return json_data
888
+
889
+ def send_progress_text(
890
+ self, text: Union[bytes, bytearray, str], node_id: str, sid=None
891
+ ):
892
+ if isinstance(text, str):
893
+ text = text.encode("utf-8")
894
+ node_id_bytes = str(node_id).encode("utf-8")
895
+
896
+ # Pack the node_id length as a 4-byte unsigned integer, followed by the node_id bytes
897
+ message = struct.pack(">I", len(node_id_bytes)) + node_id_bytes + text
898
+
899
+ self.send_sync(BinaryEventTypes.TEXT, message, sid)
README_VERY_IMPORTANT.txt ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ HOW TO RUN:
2
+
3
+ if you have a NVIDIA gpu:
4
+
5
+ run_nvidia_gpu.bat
6
+
7
+
8
+
9
+ To run it in slow CPU mode:
10
+
11
+ run_cpu.bat
12
+
13
+
14
+
15
+ IF YOU GET A RED ERROR IN THE UI MAKE SURE YOU HAVE A MODEL/CHECKPOINT IN: ComfyUI\models\checkpoints
16
+
17
+ You can download the stable diffusion 1.5 one from: https://huggingface.co/Comfy-Org/stable-diffusion-v1-5-archive/blob/main/v1-5-pruned-emaonly-fp16.safetensors
18
+
19
+
20
+ RECOMMENDED WAY TO UPDATE:
21
+ To update the ComfyUI code: update\update_comfyui.bat
22
+
23
+
24
+
25
+ To update ComfyUI with the python dependencies, note that you should ONLY run this if you have issues with python dependencies.
26
+ update\update_comfyui_and_python_dependencies.bat
27
+
28
+
29
+ TO SHARE MODELS BETWEEN COMFYUI AND ANOTHER UI:
30
+ In the ComfyUI directory you will find a file: extra_model_paths.yaml.example
31
+ Rename this file to: extra_model_paths.yaml and edit it with your favorite text editor.
Read Me 2.txt ADDED
File without changes
Workflow's/catvton_example.json ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "last_node_id": 13,
3
+ "last_link_id": 18,
4
+ "nodes": [
5
+ {
6
+ "id": 2,
7
+ "type": "LoadImage",
8
+ "pos": {
9
+ "0": 283,
10
+ "1": 153
11
+ },
12
+ "size": {
13
+ "0": 315,
14
+ "1": 314
15
+ },
16
+ "flags": {},
17
+ "order": 0,
18
+ "mode": 0,
19
+ "inputs": [],
20
+ "outputs": [
21
+ {
22
+ "name": "IMAGE",
23
+ "type": "IMAGE",
24
+ "links": [
25
+ 1,
26
+ 16
27
+ ],
28
+ "slot_index": 0,
29
+ "shape": 3
30
+ },
31
+ {
32
+ "name": "MASK",
33
+ "type": "MASK",
34
+ "links": null,
35
+ "shape": 3
36
+ }
37
+ ],
38
+ "properties": {
39
+ "Node name for S&R": "LoadImage"
40
+ },
41
+ "widgets_values": [
42
+ "girl.jpg",
43
+ "image"
44
+ ]
45
+ },
46
+ {
47
+ "id": 8,
48
+ "type": "PreviewImage",
49
+ "pos": {
50
+ "0": 1647,
51
+ "1": 159
52
+ },
53
+ "size": {
54
+ "0": 530.576171875,
55
+ "1": 734.8110961914062
56
+ },
57
+ "flags": {},
58
+ "order": 5,
59
+ "mode": 0,
60
+ "inputs": [
61
+ {
62
+ "name": "images",
63
+ "type": "IMAGE",
64
+ "link": 8
65
+ }
66
+ ],
67
+ "outputs": [],
68
+ "properties": {
69
+ "Node name for S&R": "PreviewImage"
70
+ }
71
+ },
72
+ {
73
+ "id": 1,
74
+ "type": "CatVTONWrapper",
75
+ "pos": {
76
+ "0": 1146,
77
+ "1": 161
78
+ },
79
+ "size": {
80
+ "0": 315,
81
+ "1": 218
82
+ },
83
+ "flags": {},
84
+ "order": 4,
85
+ "mode": 0,
86
+ "inputs": [
87
+ {
88
+ "name": "image",
89
+ "type": "IMAGE",
90
+ "link": 1,
91
+ "slot_index": 0
92
+ },
93
+ {
94
+ "name": "mask",
95
+ "type": "MASK",
96
+ "link": 18
97
+ },
98
+ {
99
+ "name": "refer_image",
100
+ "type": "IMAGE",
101
+ "link": 7,
102
+ "slot_index": 2
103
+ }
104
+ ],
105
+ "outputs": [
106
+ {
107
+ "name": "image",
108
+ "type": "IMAGE",
109
+ "links": [
110
+ 8
111
+ ],
112
+ "slot_index": 0,
113
+ "shape": 3
114
+ }
115
+ ],
116
+ "properties": {
117
+ "Node name for S&R": "CatVTONWrapper"
118
+ },
119
+ "widgets_values": [
120
+ 25,
121
+ "fp16",
122
+ 491151633043877,
123
+ "randomize",
124
+ 50,
125
+ 3
126
+ ]
127
+ },
128
+ {
129
+ "id": 11,
130
+ "type": "LayerMask: MaskPreview",
131
+ "pos": {
132
+ "0": 1141,
133
+ "1": 563
134
+ },
135
+ "size": [
136
+ 323.2476717529296,
137
+ 354.9690538940429
138
+ ],
139
+ "flags": {},
140
+ "order": 3,
141
+ "mode": 0,
142
+ "inputs": [
143
+ {
144
+ "name": "mask",
145
+ "type": "MASK",
146
+ "link": 17
147
+ }
148
+ ],
149
+ "outputs": [],
150
+ "properties": {
151
+ "Node name for S&R": "LayerMask: MaskPreview"
152
+ },
153
+ "color": "rgba(27, 80, 119, 0.7)"
154
+ },
155
+ {
156
+ "id": 13,
157
+ "type": "LayerMask: HumanPartsUltra",
158
+ "pos": {
159
+ "0": 682,
160
+ "1": 405
161
+ },
162
+ "size": {
163
+ "0": 352.79998779296875,
164
+ "1": 534
165
+ },
166
+ "flags": {},
167
+ "order": 2,
168
+ "mode": 0,
169
+ "inputs": [
170
+ {
171
+ "name": "image",
172
+ "type": "IMAGE",
173
+ "link": 16
174
+ }
175
+ ],
176
+ "outputs": [
177
+ {
178
+ "name": "image",
179
+ "type": "IMAGE",
180
+ "links": null,
181
+ "shape": 3
182
+ },
183
+ {
184
+ "name": "mask",
185
+ "type": "MASK",
186
+ "links": [
187
+ 17,
188
+ 18
189
+ ],
190
+ "shape": 3,
191
+ "slot_index": 1
192
+ }
193
+ ],
194
+ "properties": {
195
+ "Node name for S&R": "LayerMask: HumanPartsUltra"
196
+ },
197
+ "widgets_values": [
198
+ false,
199
+ false,
200
+ false,
201
+ true,
202
+ false,
203
+ false,
204
+ false,
205
+ false,
206
+ false,
207
+ false,
208
+ false,
209
+ false,
210
+ "VITMatte",
211
+ 8,
212
+ 6,
213
+ 0.01,
214
+ 0.99,
215
+ true,
216
+ "cuda",
217
+ 2
218
+ ],
219
+ "color": "rgba(27, 80, 119, 0.7)"
220
+ },
221
+ {
222
+ "id": 7,
223
+ "type": "LoadImage",
224
+ "pos": {
225
+ "0": 285,
226
+ "1": 611
227
+ },
228
+ "size": {
229
+ "0": 315,
230
+ "1": 314
231
+ },
232
+ "flags": {},
233
+ "order": 1,
234
+ "mode": 0,
235
+ "inputs": [],
236
+ "outputs": [
237
+ {
238
+ "name": "IMAGE",
239
+ "type": "IMAGE",
240
+ "links": [
241
+ 7
242
+ ],
243
+ "shape": 3
244
+ },
245
+ {
246
+ "name": "MASK",
247
+ "type": "MASK",
248
+ "links": null,
249
+ "shape": 3
250
+ }
251
+ ],
252
+ "properties": {
253
+ "Node name for S&R": "LoadImage"
254
+ },
255
+ "widgets_values": [
256
+ "panda_t_shirt.jpg",
257
+ "image"
258
+ ]
259
+ }
260
+ ],
261
+ "links": [
262
+ [
263
+ 1,
264
+ 2,
265
+ 0,
266
+ 1,
267
+ 0,
268
+ "IMAGE"
269
+ ],
270
+ [
271
+ 7,
272
+ 7,
273
+ 0,
274
+ 1,
275
+ 2,
276
+ "IMAGE"
277
+ ],
278
+ [
279
+ 8,
280
+ 1,
281
+ 0,
282
+ 8,
283
+ 0,
284
+ "IMAGE"
285
+ ],
286
+ [
287
+ 16,
288
+ 2,
289
+ 0,
290
+ 13,
291
+ 0,
292
+ "IMAGE"
293
+ ],
294
+ [
295
+ 17,
296
+ 13,
297
+ 1,
298
+ 11,
299
+ 0,
300
+ "MASK"
301
+ ],
302
+ [
303
+ 18,
304
+ 13,
305
+ 1,
306
+ 1,
307
+ 1,
308
+ "MASK"
309
+ ]
310
+ ],
311
+ "groups": [],
312
+ "config": {},
313
+ "extra": {
314
+ "ds": {
315
+ "scale": 0.7513148009015777,
316
+ "offset": [
317
+ 338.6524316406253,
318
+ 290.41768908691427
319
+ ]
320
+ }
321
+ },
322
+ "version": 0.4
323
+ }
python_embeded/LICENSE.txt ADDED
@@ -0,0 +1,702 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ A. HISTORY OF THE SOFTWARE
2
+ ==========================
3
+
4
+ Python was created in the early 1990s by Guido van Rossum at Stichting
5
+ Mathematisch Centrum (CWI, see https://www.cwi.nl) in the Netherlands
6
+ as a successor of a language called ABC. Guido remains Python's
7
+ principal author, although it includes many contributions from others.
8
+
9
+ In 1995, Guido continued his work on Python at the Corporation for
10
+ National Research Initiatives (CNRI, see https://www.cnri.reston.va.us)
11
+ in Reston, Virginia where he released several versions of the
12
+ software.
13
+
14
+ In May 2000, Guido and the Python core development team moved to
15
+ BeOpen.com to form the BeOpen PythonLabs team. In October of the same
16
+ year, the PythonLabs team moved to Digital Creations, which became
17
+ Zope Corporation. In 2001, the Python Software Foundation (PSF, see
18
+ https://www.python.org/psf/) was formed, a non-profit organization
19
+ created specifically to own Python-related Intellectual Property.
20
+ Zope Corporation was a sponsoring member of the PSF.
21
+
22
+ All Python releases are Open Source (see https://opensource.org for
23
+ the Open Source Definition). Historically, most, but not all, Python
24
+ releases have also been GPL-compatible; the table below summarizes
25
+ the various releases.
26
+
27
+ Release Derived Year Owner GPL-
28
+ from compatible? (1)
29
+
30
+ 0.9.0 thru 1.2 1991-1995 CWI yes
31
+ 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes
32
+ 1.6 1.5.2 2000 CNRI no
33
+ 2.0 1.6 2000 BeOpen.com no
34
+ 1.6.1 1.6 2001 CNRI yes (2)
35
+ 2.1 2.0+1.6.1 2001 PSF no
36
+ 2.0.1 2.0+1.6.1 2001 PSF yes
37
+ 2.1.1 2.1+2.0.1 2001 PSF yes
38
+ 2.1.2 2.1.1 2002 PSF yes
39
+ 2.1.3 2.1.2 2002 PSF yes
40
+ 2.2 and above 2.1.1 2001-now PSF yes
41
+
42
+ Footnotes:
43
+
44
+ (1) GPL-compatible doesn't mean that we're distributing Python under
45
+ the GPL. All Python licenses, unlike the GPL, let you distribute
46
+ a modified version without making your changes open source. The
47
+ GPL-compatible licenses make it possible to combine Python with
48
+ other software that is released under the GPL; the others don't.
49
+
50
+ (2) According to Richard Stallman, 1.6.1 is not GPL-compatible,
51
+ because its license has a choice of law clause. According to
52
+ CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1
53
+ is "not incompatible" with the GPL.
54
+
55
+ Thanks to the many outside volunteers who have worked under Guido's
56
+ direction to make these releases possible.
57
+
58
+
59
+ B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON
60
+ ===============================================================
61
+
62
+ Python software and documentation are licensed under the
63
+ Python Software Foundation License Version 2.
64
+
65
+ Starting with Python 3.8.6, examples, recipes, and other code in
66
+ the documentation are dual licensed under the PSF License Version 2
67
+ and the Zero-Clause BSD license.
68
+
69
+ Some software incorporated into Python is under different licenses.
70
+ The licenses are listed with code falling under that license.
71
+
72
+
73
+ PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
74
+ --------------------------------------------
75
+
76
+ 1. This LICENSE AGREEMENT is between the Python Software Foundation
77
+ ("PSF"), and the Individual or Organization ("Licensee") accessing and
78
+ otherwise using this software ("Python") in source or binary form and
79
+ its associated documentation.
80
+
81
+ 2. Subject to the terms and conditions of this License Agreement, PSF hereby
82
+ grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
83
+ analyze, test, perform and/or display publicly, prepare derivative works,
84
+ distribute, and otherwise use Python alone or in any derivative version,
85
+ provided, however, that PSF's License Agreement and PSF's notice of copyright,
86
+ i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,
87
+ 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023 Python Software Foundation;
88
+ All Rights Reserved" are retained in Python alone or in any derivative version
89
+ prepared by Licensee.
90
+
91
+ 3. In the event Licensee prepares a derivative work that is based on
92
+ or incorporates Python or any part thereof, and wants to make
93
+ the derivative work available to others as provided herein, then
94
+ Licensee hereby agrees to include in any such work a brief summary of
95
+ the changes made to Python.
96
+
97
+ 4. PSF is making Python available to Licensee on an "AS IS"
98
+ basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
99
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
100
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
101
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
102
+ INFRINGE ANY THIRD PARTY RIGHTS.
103
+
104
+ 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
105
+ FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
106
+ A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
107
+ OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
108
+
109
+ 6. This License Agreement will automatically terminate upon a material
110
+ breach of its terms and conditions.
111
+
112
+ 7. Nothing in this License Agreement shall be deemed to create any
113
+ relationship of agency, partnership, or joint venture between PSF and
114
+ Licensee. This License Agreement does not grant permission to use PSF
115
+ trademarks or trade name in a trademark sense to endorse or promote
116
+ products or services of Licensee, or any third party.
117
+
118
+ 8. By copying, installing or otherwise using Python, Licensee
119
+ agrees to be bound by the terms and conditions of this License
120
+ Agreement.
121
+
122
+
123
+ BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0
124
+ -------------------------------------------
125
+
126
+ BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1
127
+
128
+ 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an
129
+ office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the
130
+ Individual or Organization ("Licensee") accessing and otherwise using
131
+ this software in source or binary form and its associated
132
+ documentation ("the Software").
133
+
134
+ 2. Subject to the terms and conditions of this BeOpen Python License
135
+ Agreement, BeOpen hereby grants Licensee a non-exclusive,
136
+ royalty-free, world-wide license to reproduce, analyze, test, perform
137
+ and/or display publicly, prepare derivative works, distribute, and
138
+ otherwise use the Software alone or in any derivative version,
139
+ provided, however, that the BeOpen Python License is retained in the
140
+ Software, alone or in any derivative version prepared by Licensee.
141
+
142
+ 3. BeOpen is making the Software available to Licensee on an "AS IS"
143
+ basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
144
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND
145
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
146
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT
147
+ INFRINGE ANY THIRD PARTY RIGHTS.
148
+
149
+ 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE
150
+ SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS
151
+ AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY
152
+ DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
153
+
154
+ 5. This License Agreement will automatically terminate upon a material
155
+ breach of its terms and conditions.
156
+
157
+ 6. This License Agreement shall be governed by and interpreted in all
158
+ respects by the law of the State of California, excluding conflict of
159
+ law provisions. Nothing in this License Agreement shall be deemed to
160
+ create any relationship of agency, partnership, or joint venture
161
+ between BeOpen and Licensee. This License Agreement does not grant
162
+ permission to use BeOpen trademarks or trade names in a trademark
163
+ sense to endorse or promote products or services of Licensee, or any
164
+ third party. As an exception, the "BeOpen Python" logos available at
165
+ http://www.pythonlabs.com/logos.html may be used according to the
166
+ permissions granted on that web page.
167
+
168
+ 7. By copying, installing or otherwise using the software, Licensee
169
+ agrees to be bound by the terms and conditions of this License
170
+ Agreement.
171
+
172
+
173
+ CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1
174
+ ---------------------------------------
175
+
176
+ 1. This LICENSE AGREEMENT is between the Corporation for National
177
+ Research Initiatives, having an office at 1895 Preston White Drive,
178
+ Reston, VA 20191 ("CNRI"), and the Individual or Organization
179
+ ("Licensee") accessing and otherwise using Python 1.6.1 software in
180
+ source or binary form and its associated documentation.
181
+
182
+ 2. Subject to the terms and conditions of this License Agreement, CNRI
183
+ hereby grants Licensee a nonexclusive, royalty-free, world-wide
184
+ license to reproduce, analyze, test, perform and/or display publicly,
185
+ prepare derivative works, distribute, and otherwise use Python 1.6.1
186
+ alone or in any derivative version, provided, however, that CNRI's
187
+ License Agreement and CNRI's notice of copyright, i.e., "Copyright (c)
188
+ 1995-2001 Corporation for National Research Initiatives; All Rights
189
+ Reserved" are retained in Python 1.6.1 alone or in any derivative
190
+ version prepared by Licensee. Alternately, in lieu of CNRI's License
191
+ Agreement, Licensee may substitute the following text (omitting the
192
+ quotes): "Python 1.6.1 is made available subject to the terms and
193
+ conditions in CNRI's License Agreement. This Agreement together with
194
+ Python 1.6.1 may be located on the internet using the following
195
+ unique, persistent identifier (known as a handle): 1895.22/1013. This
196
+ Agreement may also be obtained from a proxy server on the internet
197
+ using the following URL: http://hdl.handle.net/1895.22/1013".
198
+
199
+ 3. In the event Licensee prepares a derivative work that is based on
200
+ or incorporates Python 1.6.1 or any part thereof, and wants to make
201
+ the derivative work available to others as provided herein, then
202
+ Licensee hereby agrees to include in any such work a brief summary of
203
+ the changes made to Python 1.6.1.
204
+
205
+ 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS"
206
+ basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
207
+ IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND
208
+ DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
209
+ FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT
210
+ INFRINGE ANY THIRD PARTY RIGHTS.
211
+
212
+ 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
213
+ 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
214
+ A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,
215
+ OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
216
+
217
+ 6. This License Agreement will automatically terminate upon a material
218
+ breach of its terms and conditions.
219
+
220
+ 7. This License Agreement shall be governed by the federal
221
+ intellectual property law of the United States, including without
222
+ limitation the federal copyright law, and, to the extent such
223
+ U.S. federal law does not apply, by the law of the Commonwealth of
224
+ Virginia, excluding Virginia's conflict of law provisions.
225
+ Notwithstanding the foregoing, with regard to derivative works based
226
+ on Python 1.6.1 that incorporate non-separable material that was
227
+ previously distributed under the GNU General Public License (GPL), the
228
+ law of the Commonwealth of Virginia shall govern this License
229
+ Agreement only as to issues arising under or with respect to
230
+ Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this
231
+ License Agreement shall be deemed to create any relationship of
232
+ agency, partnership, or joint venture between CNRI and Licensee. This
233
+ License Agreement does not grant permission to use CNRI trademarks or
234
+ trade name in a trademark sense to endorse or promote products or
235
+ services of Licensee, or any third party.
236
+
237
+ 8. By clicking on the "ACCEPT" button where indicated, or by copying,
238
+ installing or otherwise using Python 1.6.1, Licensee agrees to be
239
+ bound by the terms and conditions of this License Agreement.
240
+
241
+ ACCEPT
242
+
243
+
244
+ CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2
245
+ --------------------------------------------------
246
+
247
+ Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,
248
+ The Netherlands. All rights reserved.
249
+
250
+ Permission to use, copy, modify, and distribute this software and its
251
+ documentation for any purpose and without fee is hereby granted,
252
+ provided that the above copyright notice appear in all copies and that
253
+ both that copyright notice and this permission notice appear in
254
+ supporting documentation, and that the name of Stichting Mathematisch
255
+ Centrum or CWI not be used in advertising or publicity pertaining to
256
+ distribution of the software without specific, written prior
257
+ permission.
258
+
259
+ STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO
260
+ THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
261
+ FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE
262
+ FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
263
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
264
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
265
+ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
266
+
267
+ ZERO-CLAUSE BSD LICENSE FOR CODE IN THE PYTHON DOCUMENTATION
268
+ ----------------------------------------------------------------------
269
+
270
+ Permission to use, copy, modify, and/or distribute this software for any
271
+ purpose with or without fee is hereby granted.
272
+
273
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
274
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
275
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
276
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
277
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
278
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
279
+ PERFORMANCE OF THIS SOFTWARE.
280
+
281
+
282
+
283
+ Additional Conditions for this Windows binary build
284
+ ---------------------------------------------------
285
+
286
+ This program is linked with and uses Microsoft Distributable Code,
287
+ copyrighted by Microsoft Corporation. The Microsoft Distributable Code
288
+ is embedded in each .exe, .dll and .pyd file as a result of running
289
+ the code through a linker.
290
+
291
+ If you further distribute programs that include the Microsoft
292
+ Distributable Code, you must comply with the restrictions on
293
+ distribution specified by Microsoft. In particular, you must require
294
+ distributors and external end users to agree to terms that protect the
295
+ Microsoft Distributable Code at least as much as Microsoft's own
296
+ requirements for the Distributable Code. See Microsoft's documentation
297
+ (included in its developer tools and on its website at microsoft.com)
298
+ for specific details.
299
+
300
+ Redistribution of the Windows binary build of the Python interpreter
301
+ complies with this agreement, provided that you do not:
302
+
303
+ - alter any copyright, trademark or patent notice in Microsoft's
304
+ Distributable Code;
305
+
306
+ - use Microsoft's trademarks in your programs' names or in a way that
307
+ suggests your programs come from or are endorsed by Microsoft;
308
+
309
+ - distribute Microsoft's Distributable Code to run on a platform other
310
+ than Microsoft operating systems, run-time technologies or application
311
+ platforms; or
312
+
313
+ - include Microsoft Distributable Code in malicious, deceptive or
314
+ unlawful programs.
315
+
316
+ These restrictions apply only to the Microsoft Distributable Code as
317
+ defined above, not to Python itself or any programs running on the
318
+ Python interpreter. The redistribution of the Python interpreter and
319
+ libraries is governed by the Python Software License included with this
320
+ file, or by other licenses as marked.
321
+
322
+
323
+
324
+ --------------------------------------------------------------------------
325
+
326
+ This program, "bzip2", the associated library "libbzip2", and all
327
+ documentation, are copyright (C) 1996-2019 Julian R Seward. All
328
+ rights reserved.
329
+
330
+ Redistribution and use in source and binary forms, with or without
331
+ modification, are permitted provided that the following conditions
332
+ are met:
333
+
334
+ 1. Redistributions of source code must retain the above copyright
335
+ notice, this list of conditions and the following disclaimer.
336
+
337
+ 2. The origin of this software must not be misrepresented; you must
338
+ not claim that you wrote the original software. If you use this
339
+ software in a product, an acknowledgment in the product
340
+ documentation would be appreciated but is not required.
341
+
342
+ 3. Altered source versions must be plainly marked as such, and must
343
+ not be misrepresented as being the original software.
344
+
345
+ 4. The name of the author may not be used to endorse or promote
346
+ products derived from this software without specific prior written
347
+ permission.
348
+
349
+ THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
350
+ OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
351
+ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
352
+ ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
353
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
354
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
355
+ GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
356
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
357
+ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
358
+ NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
359
+ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
360
+
361
+ Julian Seward, jseward@acm.org
362
+ bzip2/libbzip2 version 1.0.8 of 13 July 2019
363
+
364
+ --------------------------------------------------------------------------
365
+
366
+ libffi - Copyright (c) 1996-2022 Anthony Green, Red Hat, Inc and others.
367
+ See source files for details.
368
+
369
+ Permission is hereby granted, free of charge, to any person obtaining
370
+ a copy of this software and associated documentation files (the
371
+ ``Software''), to deal in the Software without restriction, including
372
+ without limitation the rights to use, copy, modify, merge, publish,
373
+ distribute, sublicense, and/or sell copies of the Software, and to
374
+ permit persons to whom the Software is furnished to do so, subject to
375
+ the following conditions:
376
+
377
+ The above copyright notice and this permission notice shall be
378
+ included in all copies or substantial portions of the Software.
379
+
380
+ THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND,
381
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
382
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
383
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
384
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
385
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
386
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
387
+
388
+
389
+ Apache License
390
+ Version 2.0, January 2004
391
+ https://www.apache.org/licenses/
392
+
393
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
394
+
395
+ 1. Definitions.
396
+
397
+ "License" shall mean the terms and conditions for use, reproduction,
398
+ and distribution as defined by Sections 1 through 9 of this document.
399
+
400
+ "Licensor" shall mean the copyright owner or entity authorized by
401
+ the copyright owner that is granting the License.
402
+
403
+ "Legal Entity" shall mean the union of the acting entity and all
404
+ other entities that control, are controlled by, or are under common
405
+ control with that entity. For the purposes of this definition,
406
+ "control" means (i) the power, direct or indirect, to cause the
407
+ direction or management of such entity, whether by contract or
408
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
409
+ outstanding shares, or (iii) beneficial ownership of such entity.
410
+
411
+ "You" (or "Your") shall mean an individual or Legal Entity
412
+ exercising permissions granted by this License.
413
+
414
+ "Source" form shall mean the preferred form for making modifications,
415
+ including but not limited to software source code, documentation
416
+ source, and configuration files.
417
+
418
+ "Object" form shall mean any form resulting from mechanical
419
+ transformation or translation of a Source form, including but
420
+ not limited to compiled object code, generated documentation,
421
+ and conversions to other media types.
422
+
423
+ "Work" shall mean the work of authorship, whether in Source or
424
+ Object form, made available under the License, as indicated by a
425
+ copyright notice that is included in or attached to the work
426
+ (an example is provided in the Appendix below).
427
+
428
+ "Derivative Works" shall mean any work, whether in Source or Object
429
+ form, that is based on (or derived from) the Work and for which the
430
+ editorial revisions, annotations, elaborations, or other modifications
431
+ represent, as a whole, an original work of authorship. For the purposes
432
+ of this License, Derivative Works shall not include works that remain
433
+ separable from, or merely link (or bind by name) to the interfaces of,
434
+ the Work and Derivative Works thereof.
435
+
436
+ "Contribution" shall mean any work of authorship, including
437
+ the original version of the Work and any modifications or additions
438
+ to that Work or Derivative Works thereof, that is intentionally
439
+ submitted to Licensor for inclusion in the Work by the copyright owner
440
+ or by an individual or Legal Entity authorized to submit on behalf of
441
+ the copyright owner. For the purposes of this definition, "submitted"
442
+ means any form of electronic, verbal, or written communication sent
443
+ to the Licensor or its representatives, including but not limited to
444
+ communication on electronic mailing lists, source code control systems,
445
+ and issue tracking systems that are managed by, or on behalf of, the
446
+ Licensor for the purpose of discussing and improving the Work, but
447
+ excluding communication that is conspicuously marked or otherwise
448
+ designated in writing by the copyright owner as "Not a Contribution."
449
+
450
+ "Contributor" shall mean Licensor and any individual or Legal Entity
451
+ on behalf of whom a Contribution has been received by Licensor and
452
+ subsequently incorporated within the Work.
453
+
454
+ 2. Grant of Copyright License. Subject to the terms and conditions of
455
+ this License, each Contributor hereby grants to You a perpetual,
456
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
457
+ copyright license to reproduce, prepare Derivative Works of,
458
+ publicly display, publicly perform, sublicense, and distribute the
459
+ Work and such Derivative Works in Source or Object form.
460
+
461
+ 3. Grant of Patent License. Subject to the terms and conditions of
462
+ this License, each Contributor hereby grants to You a perpetual,
463
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
464
+ (except as stated in this section) patent license to make, have made,
465
+ use, offer to sell, sell, import, and otherwise transfer the Work,
466
+ where such license applies only to those patent claims licensable
467
+ by such Contributor that are necessarily infringed by their
468
+ Contribution(s) alone or by combination of their Contribution(s)
469
+ with the Work to which such Contribution(s) was submitted. If You
470
+ institute patent litigation against any entity (including a
471
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
472
+ or a Contribution incorporated within the Work constitutes direct
473
+ or contributory patent infringement, then any patent licenses
474
+ granted to You under this License for that Work shall terminate
475
+ as of the date such litigation is filed.
476
+
477
+ 4. Redistribution. You may reproduce and distribute copies of the
478
+ Work or Derivative Works thereof in any medium, with or without
479
+ modifications, and in Source or Object form, provided that You
480
+ meet the following conditions:
481
+
482
+ (a) You must give any other recipients of the Work or
483
+ Derivative Works a copy of this License; and
484
+
485
+ (b) You must cause any modified files to carry prominent notices
486
+ stating that You changed the files; and
487
+
488
+ (c) You must retain, in the Source form of any Derivative Works
489
+ that You distribute, all copyright, patent, trademark, and
490
+ attribution notices from the Source form of the Work,
491
+ excluding those notices that do not pertain to any part of
492
+ the Derivative Works; and
493
+
494
+ (d) If the Work includes a "NOTICE" text file as part of its
495
+ distribution, then any Derivative Works that You distribute must
496
+ include a readable copy of the attribution notices contained
497
+ within such NOTICE file, excluding those notices that do not
498
+ pertain to any part of the Derivative Works, in at least one
499
+ of the following places: within a NOTICE text file distributed
500
+ as part of the Derivative Works; within the Source form or
501
+ documentation, if provided along with the Derivative Works; or,
502
+ within a display generated by the Derivative Works, if and
503
+ wherever such third-party notices normally appear. The contents
504
+ of the NOTICE file are for informational purposes only and
505
+ do not modify the License. You may add Your own attribution
506
+ notices within Derivative Works that You distribute, alongside
507
+ or as an addendum to the NOTICE text from the Work, provided
508
+ that such additional attribution notices cannot be construed
509
+ as modifying the License.
510
+
511
+ You may add Your own copyright statement to Your modifications and
512
+ may provide additional or different license terms and conditions
513
+ for use, reproduction, or distribution of Your modifications, or
514
+ for any such Derivative Works as a whole, provided Your use,
515
+ reproduction, and distribution of the Work otherwise complies with
516
+ the conditions stated in this License.
517
+
518
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
519
+ any Contribution intentionally submitted for inclusion in the Work
520
+ by You to the Licensor shall be under the terms and conditions of
521
+ this License, without any additional terms or conditions.
522
+ Notwithstanding the above, nothing herein shall supersede or modify
523
+ the terms of any separate license agreement you may have executed
524
+ with Licensor regarding such Contributions.
525
+
526
+ 6. Trademarks. This License does not grant permission to use the trade
527
+ names, trademarks, service marks, or product names of the Licensor,
528
+ except as required for reasonable and customary use in describing the
529
+ origin of the Work and reproducing the content of the NOTICE file.
530
+
531
+ 7. Disclaimer of Warranty. Unless required by applicable law or
532
+ agreed to in writing, Licensor provides the Work (and each
533
+ Contributor provides its Contributions) on an "AS IS" BASIS,
534
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
535
+ implied, including, without limitation, any warranties or conditions
536
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
537
+ PARTICULAR PURPOSE. You are solely responsible for determining the
538
+ appropriateness of using or redistributing the Work and assume any
539
+ risks associated with Your exercise of permissions under this License.
540
+
541
+ 8. Limitation of Liability. In no event and under no legal theory,
542
+ whether in tort (including negligence), contract, or otherwise,
543
+ unless required by applicable law (such as deliberate and grossly
544
+ negligent acts) or agreed to in writing, shall any Contributor be
545
+ liable to You for damages, including any direct, indirect, special,
546
+ incidental, or consequential damages of any character arising as a
547
+ result of this License or out of the use or inability to use the
548
+ Work (including but not limited to damages for loss of goodwill,
549
+ work stoppage, computer failure or malfunction, or any and all
550
+ other commercial damages or losses), even if such Contributor
551
+ has been advised of the possibility of such damages.
552
+
553
+ 9. Accepting Warranty or Additional Liability. While redistributing
554
+ the Work or Derivative Works thereof, You may choose to offer,
555
+ and charge a fee for, acceptance of support, warranty, indemnity,
556
+ or other liability obligations and/or rights consistent with this
557
+ License. However, in accepting such obligations, You may act only
558
+ on Your own behalf and on Your sole responsibility, not on behalf
559
+ of any other Contributor, and only if You agree to indemnify,
560
+ defend, and hold each Contributor harmless for any liability
561
+ incurred by, or claims asserted against, such Contributor by reason
562
+ of your accepting any such warranty or additional liability.
563
+
564
+ END OF TERMS AND CONDITIONS
565
+
566
+ This software is copyrighted by the Regents of the University of
567
+ California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
568
+ Corporation and other parties. The following terms apply to all files
569
+ associated with the software unless explicitly disclaimed in
570
+ individual files.
571
+
572
+ The authors hereby grant permission to use, copy, modify, distribute,
573
+ and license this software and its documentation for any purpose, provided
574
+ that existing copyright notices are retained in all copies and that this
575
+ notice is included verbatim in any distributions. No written agreement,
576
+ license, or royalty fee is required for any of the authorized uses.
577
+ Modifications to this software may be copyrighted by their authors
578
+ and need not follow the licensing terms described here, provided that
579
+ the new terms are clearly indicated on the first page of each file where
580
+ they apply.
581
+
582
+ IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
583
+ FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
584
+ ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
585
+ DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
586
+ POSSIBILITY OF SUCH DAMAGE.
587
+
588
+ THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
589
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
590
+ FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
591
+ IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
592
+ NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
593
+ MODIFICATIONS.
594
+
595
+ GOVERNMENT USE: If you are acquiring this software on behalf of the
596
+ U.S. government, the Government shall have only "Restricted Rights"
597
+ in the software and related documentation as defined in the Federal
598
+ Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
599
+ are acquiring the software on behalf of the Department of Defense, the
600
+ software shall be classified as "Commercial Computer Software" and the
601
+ Government shall have only "Restricted Rights" as defined in Clause
602
+ 252.227-7014 (b) (3) of DFARs. Notwithstanding the foregoing, the
603
+ authors grant the U.S. Government and others acting in its behalf
604
+ permission to use and distribute the software in accordance with the
605
+ terms specified in this license.
606
+
607
+ This software is copyrighted by the Regents of the University of
608
+ California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
609
+ Corporation, Apple Inc. and other parties. The following terms apply to
610
+ all files associated with the software unless explicitly disclaimed in
611
+ individual files.
612
+
613
+ The authors hereby grant permission to use, copy, modify, distribute,
614
+ and license this software and its documentation for any purpose, provided
615
+ that existing copyright notices are retained in all copies and that this
616
+ notice is included verbatim in any distributions. No written agreement,
617
+ license, or royalty fee is required for any of the authorized uses.
618
+ Modifications to this software may be copyrighted by their authors
619
+ and need not follow the licensing terms described here, provided that
620
+ the new terms are clearly indicated on the first page of each file where
621
+ they apply.
622
+
623
+ IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
624
+ FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
625
+ ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
626
+ DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
627
+ POSSIBILITY OF SUCH DAMAGE.
628
+
629
+ THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
630
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
631
+ FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
632
+ IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
633
+ NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
634
+ MODIFICATIONS.
635
+
636
+ GOVERNMENT USE: If you are acquiring this software on behalf of the
637
+ U.S. government, the Government shall have only "Restricted Rights"
638
+ in the software and related documentation as defined in the Federal
639
+ Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
640
+ are acquiring the software on behalf of the Department of Defense, the
641
+ software shall be classified as "Commercial Computer Software" and the
642
+ Government shall have only "Restricted Rights" as defined in Clause
643
+ 252.227-7013 (b) (3) of DFARs. Notwithstanding the foregoing, the
644
+ authors grant the U.S. Government and others acting in its behalf
645
+ permission to use and distribute the software in accordance with the
646
+ terms specified in this license.
647
+
648
+ Copyright (c) 1993-1999 Ioi Kim Lam.
649
+ Copyright (c) 2000-2001 Tix Project Group.
650
+ Copyright (c) 2004 ActiveState
651
+
652
+ This software is copyrighted by the above entities
653
+ and other parties. The following terms apply to all files associated
654
+ with the software unless explicitly disclaimed in individual files.
655
+
656
+ The authors hereby grant permission to use, copy, modify, distribute,
657
+ and license this software and its documentation for any purpose, provided
658
+ that existing copyright notices are retained in all copies and that this
659
+ notice is included verbatim in any distributions. No written agreement,
660
+ license, or royalty fee is required for any of the authorized uses.
661
+ Modifications to this software may be copyrighted by their authors
662
+ and need not follow the licensing terms described here, provided that
663
+ the new terms are clearly indicated on the first page of each file where
664
+ they apply.
665
+
666
+ IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
667
+ FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
668
+ ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
669
+ DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
670
+ POSSIBILITY OF SUCH DAMAGE.
671
+
672
+ THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
673
+ INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
674
+ FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
675
+ IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
676
+ NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
677
+ MODIFICATIONS.
678
+
679
+ GOVERNMENT USE: If you are acquiring this software on behalf of the
680
+ U.S. government, the Government shall have only "Restricted Rights"
681
+ in the software and related documentation as defined in the Federal
682
+ Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
683
+ are acquiring the software on behalf of the Department of Defense, the
684
+ software shall be classified as "Commercial Computer Software" and the
685
+ Government shall have only "Restricted Rights" as defined in Clause
686
+ 252.227-7013 (c) (1) of DFARs. Notwithstanding the foregoing, the
687
+ authors grant the U.S. Government and others acting in its behalf
688
+ permission to use and distribute the software in accordance with the
689
+ terms specified in this license.
690
+
691
+ ----------------------------------------------------------------------
692
+
693
+ Parts of this software are based on the Tcl/Tk software copyrighted by
694
+ the Regents of the University of California, Sun Microsystems, Inc.,
695
+ and other parties. The original license terms of the Tcl/Tk software
696
+ distribution is included in the file docs/license.tcltk.
697
+
698
+ Parts of this software are based on the HTML Library software
699
+ copyrighted by Sun Microsystems, Inc. The original license terms of
700
+ the HTML Library software distribution is included in the file
701
+ docs/license.html_lib.
702
+
python_embeded/_asyncio.pyd ADDED
Binary file (74.1 kB). View file
 
python_embeded/_bz2.pyd ADDED
Binary file (86.9 kB). View file
 
python_embeded/_hashlib.pyd ADDED
Binary file (69 kB). View file
 
python_embeded/_msi.pyd ADDED
Binary file (46.6 kB). View file
 
python_embeded/_multiprocessing.pyd ADDED
Binary file (37.4 kB). View file
 
python_embeded/_overlapped.pyd ADDED
Binary file (57.3 kB). View file
 
python_embeded/_queue.pyd ADDED
Binary file (33.8 kB). View file
 
python_embeded/_socket.pyd ADDED
Binary file (85.5 kB). View file
 
python_embeded/_uuid.pyd ADDED
Binary file (27.1 kB). View file
 
python_embeded/_wmi.pyd ADDED
Binary file (40.3 kB). View file
 
python_embeded/get-pip.py ADDED
The diff for this file is too large to render. See raw diff
 
python_embeded/libffi-8.dll ADDED
Binary file (39.7 kB). View file
 
python_embeded/python3.dll ADDED
Binary file (70.4 kB). View file
 
python_embeded/python312._pth ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ ../ComfyUI
2
+ python312.zip
3
+ .
4
+
5
+ # Uncomment to run site.main() automatically
6
+ #import site
7
+ import site
python_embeded/select.pyd ADDED
Binary file (33.1 kB). View file
 
python_embeded/vcruntime140_1.dll ADDED
Binary file (49.8 kB). View file
 
python_embeded/winsound.pyd ADDED
Binary file (31.7 kB). View file
 
run_cpu.bat ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ .\python_embeded\python.exe -s ComfyUI\main.py --cpu --windows-standalone-build
2
+ pause
run_nvidia_gpu.bat ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ .\python_embeded\python.exe -s ComfyUI\main.py --windows-standalone-build
2
+ pause
run_nvidia_gpu_fast_fp16_accumulation.bat ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ .\python_embeded\python.exe -s ComfyUI\main.py --windows-standalone-build --fast fp16_accumulation
2
+ pause
update/update.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pygit2
2
+ from datetime import datetime
3
+ import sys
4
+ import os
5
+ import shutil
6
+ import filecmp
7
+
8
+ def pull(repo, remote_name='origin', branch='master'):
9
+ for remote in repo.remotes:
10
+ if remote.name == remote_name:
11
+ remote.fetch()
12
+ remote_master_id = repo.lookup_reference('refs/remotes/origin/%s' % (branch)).target
13
+ merge_result, _ = repo.merge_analysis(remote_master_id)
14
+ # Up to date, do nothing
15
+ if merge_result & pygit2.GIT_MERGE_ANALYSIS_UP_TO_DATE:
16
+ return
17
+ # We can just fastforward
18
+ elif merge_result & pygit2.GIT_MERGE_ANALYSIS_FASTFORWARD:
19
+ repo.checkout_tree(repo.get(remote_master_id))
20
+ try:
21
+ master_ref = repo.lookup_reference('refs/heads/%s' % (branch))
22
+ master_ref.set_target(remote_master_id)
23
+ except KeyError:
24
+ repo.create_branch(branch, repo.get(remote_master_id))
25
+ repo.head.set_target(remote_master_id)
26
+ elif merge_result & pygit2.GIT_MERGE_ANALYSIS_NORMAL:
27
+ repo.merge(remote_master_id)
28
+
29
+ if repo.index.conflicts is not None:
30
+ for conflict in repo.index.conflicts:
31
+ print('Conflicts found in:', conflict[0].path) # noqa: T201
32
+ raise AssertionError('Conflicts, ahhhhh!!')
33
+
34
+ user = repo.default_signature
35
+ tree = repo.index.write_tree()
36
+ repo.create_commit('HEAD',
37
+ user,
38
+ user,
39
+ 'Merge!',
40
+ tree,
41
+ [repo.head.target, remote_master_id])
42
+ # We need to do this or git CLI will think we are still merging.
43
+ repo.state_cleanup()
44
+ else:
45
+ raise AssertionError('Unknown merge analysis result')
46
+
47
+ pygit2.option(pygit2.GIT_OPT_SET_OWNER_VALIDATION, 0)
48
+ repo_path = str(sys.argv[1])
49
+ repo = pygit2.Repository(repo_path)
50
+ ident = pygit2.Signature('comfyui', 'comfy@ui')
51
+ try:
52
+ print("stashing current changes") # noqa: T201
53
+ repo.stash(ident)
54
+ except KeyError:
55
+ print("nothing to stash") # noqa: T201
56
+ backup_branch_name = 'backup_branch_{}'.format(datetime.today().strftime('%Y-%m-%d_%H_%M_%S'))
57
+ print("creating backup branch: {}".format(backup_branch_name)) # noqa: T201
58
+ try:
59
+ repo.branches.local.create(backup_branch_name, repo.head.peel())
60
+ except:
61
+ pass
62
+
63
+ print("checking out master branch") # noqa: T201
64
+ branch = repo.lookup_branch('master')
65
+ if branch is None:
66
+ try:
67
+ ref = repo.lookup_reference('refs/remotes/origin/master')
68
+ except:
69
+ print("pulling.") # noqa: T201
70
+ pull(repo)
71
+ ref = repo.lookup_reference('refs/remotes/origin/master')
72
+ repo.checkout(ref)
73
+ branch = repo.lookup_branch('master')
74
+ if branch is None:
75
+ repo.create_branch('master', repo.get(ref.target))
76
+ else:
77
+ ref = repo.lookup_reference(branch.name)
78
+ repo.checkout(ref)
79
+
80
+ print("pulling latest changes") # noqa: T201
81
+ pull(repo)
82
+
83
+ if "--stable" in sys.argv:
84
+ def latest_tag(repo):
85
+ versions = []
86
+ for k in repo.references:
87
+ try:
88
+ prefix = "refs/tags/v"
89
+ if k.startswith(prefix):
90
+ version = list(map(int, k[len(prefix):].split(".")))
91
+ versions.append((version[0] * 10000000000 + version[1] * 100000 + version[2], k))
92
+ except:
93
+ pass
94
+ versions.sort()
95
+ if len(versions) > 0:
96
+ return versions[-1][1]
97
+ return None
98
+ latest_tag = latest_tag(repo)
99
+ if latest_tag is not None:
100
+ repo.checkout(latest_tag)
101
+
102
+ print("Done!") # noqa: T201
103
+
104
+ self_update = True
105
+ if len(sys.argv) > 2:
106
+ self_update = '--skip_self_update' not in sys.argv
107
+
108
+ update_py_path = os.path.realpath(__file__)
109
+ repo_update_py_path = os.path.join(repo_path, ".ci/update_windows/update.py")
110
+
111
+ cur_path = os.path.dirname(update_py_path)
112
+
113
+
114
+ req_path = os.path.join(cur_path, "current_requirements.txt")
115
+ repo_req_path = os.path.join(repo_path, "requirements.txt")
116
+
117
+
118
+ def files_equal(file1, file2):
119
+ try:
120
+ return filecmp.cmp(file1, file2, shallow=False)
121
+ except:
122
+ return False
123
+
124
+ def file_size(f):
125
+ try:
126
+ return os.path.getsize(f)
127
+ except:
128
+ return 0
129
+
130
+
131
+ if self_update and not files_equal(update_py_path, repo_update_py_path) and file_size(repo_update_py_path) > 10:
132
+ shutil.copy(repo_update_py_path, os.path.join(cur_path, "update_new.py"))
133
+ exit()
134
+
135
+ if not os.path.exists(req_path) or not files_equal(repo_req_path, req_path):
136
+ import subprocess
137
+ try:
138
+ subprocess.check_call([sys.executable, '-s', '-m', 'pip', 'install', '-r', repo_req_path])
139
+ shutil.copy(repo_req_path, req_path)
140
+ except:
141
+ pass
142
+
143
+
144
+ stable_update_script = os.path.join(repo_path, ".ci/update_windows/update_comfyui_stable.bat")
145
+ stable_update_script_to = os.path.join(cur_path, "update_comfyui_stable.bat")
146
+
147
+ try:
148
+ if not file_size(stable_update_script_to) > 10:
149
+ shutil.copy(stable_update_script, stable_update_script_to)
150
+ except:
151
+ pass
update/update_comfyui.bat ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ ..\python_embeded\python.exe .\update.py ..\ComfyUI\
3
+ if exist update_new.py (
4
+ move /y update_new.py update.py
5
+ echo Running updater again since it got updated.
6
+ ..\python_embeded\python.exe .\update.py ..\ComfyUI\ --skip_self_update
7
+ )
8
+ if "%~1"=="" pause
upload_to_hf.py ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from huggingface_hub import HfApi
2
+ import os
3
+
4
+ api = HfApi()
5
+
6
+ # Define patterns to ignore
7
+ ignore_patterns = [
8
+ "**/.cache/**",
9
+ "**/__pycache__/**",
10
+ "**/*.pyc",
11
+ "**/*.pyo",
12
+ "**/*.log",
13
+ "**/output/**",
14
+ "**/temp/**",
15
+ "**/input/**",
16
+ "**/.git/**",
17
+ "**/node_modules/**",
18
+ "**/build/**",
19
+ "**/dist/**",
20
+ "**/*.egg-info/**",
21
+ ]
22
+
23
+ print("Starting upload with ignore patterns...")
24
+ print(f"Uploading from: {os.getcwd()}")
25
+ print(f"Ignoring patterns: {ignore_patterns}")
26
+
27
+ try:
28
+ # Use upload_folder with ignore patterns
29
+ api.upload_folder(
30
+ folder_path=".",
31
+ repo_id="hxrron/VTONmodels",
32
+ repo_type="model",
33
+ ignore_patterns=ignore_patterns,
34
+ commit_message="Initial upload of VTON models"
35
+ )
36
+ print("Upload completed successfully!")
37
+ except Exception as e:
38
+ print(f"Error during upload: {e}")
39
+ print("\nTrying alternative approach...")
40
+
41
+ # If that fails, try upload_large_folder
42
+ try:
43
+ from huggingface_hub import upload_large_folder
44
+
45
+ upload_large_folder(
46
+ folder_path=".",
47
+ repo_id="hxrron/VTONmodels",
48
+ repo_type="model",
49
+ ignore_patterns=ignore_patterns,
50
+ )
51
+ print("Upload completed with large folder method!")
52
+ except Exception as e2:
53
+ print(f"Alternative method also failed: {e2}")