Freak-ppa commited on
Commit
8c0b0b5
·
verified ·
1 Parent(s): 8d4cfef

Upload 171 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. ComfyUI/custom_nodes/ComfyUI-KJNodes/.github/workflows/publish.yml +21 -0
  2. ComfyUI/custom_nodes/ComfyUI-KJNodes/.gitignore +10 -0
  3. ComfyUI/custom_nodes/ComfyUI-KJNodes/LICENSE +674 -0
  4. ComfyUI/custom_nodes/ComfyUI-KJNodes/README.md +65 -0
  5. ComfyUI/custom_nodes/ComfyUI-KJNodes/__init__.py +167 -0
  6. ComfyUI/custom_nodes/ComfyUI-KJNodes/__pycache__/__init__.cpython-310.pyc +0 -0
  7. ComfyUI/custom_nodes/ComfyUI-KJNodes/config.json +3 -0
  8. ComfyUI/custom_nodes/ComfyUI-KJNodes/docs/images/2024-04-03_20_49_29-ComfyUI.png +0 -0
  9. ComfyUI/custom_nodes/ComfyUI-KJNodes/docs/images/319121566-05f66385-7568-4b1f-8bbc-11053660b02f.png +0 -0
  10. ComfyUI/custom_nodes/ComfyUI-KJNodes/docs/images/319121636-706b5081-9120-4a29-bd76-901691ada688.png +0 -0
  11. ComfyUI/custom_nodes/ComfyUI-KJNodes/fonts/FreeMono.ttf +0 -0
  12. ComfyUI/custom_nodes/ComfyUI-KJNodes/fonts/FreeMonoBoldOblique.otf +0 -0
  13. ComfyUI/custom_nodes/ComfyUI-KJNodes/fonts/TTNorms-Black.otf +0 -0
  14. ComfyUI/custom_nodes/ComfyUI-KJNodes/intrinsic_loras/intrinsic_lora_sd15_albedo.safetensors +3 -0
  15. ComfyUI/custom_nodes/ComfyUI-KJNodes/intrinsic_loras/intrinsic_lora_sd15_depth.safetensors +3 -0
  16. ComfyUI/custom_nodes/ComfyUI-KJNodes/intrinsic_loras/intrinsic_lora_sd15_normal.safetensors +3 -0
  17. ComfyUI/custom_nodes/ComfyUI-KJNodes/intrinsic_loras/intrinsic_lora_sd15_shading.safetensors +3 -0
  18. ComfyUI/custom_nodes/ComfyUI-KJNodes/intrinsic_loras/intrinsic_loras.txt +4 -0
  19. ComfyUI/custom_nodes/ComfyUI-KJNodes/kjweb_async/marked.min.js +6 -0
  20. ComfyUI/custom_nodes/ComfyUI-KJNodes/kjweb_async/protovis.min.js +0 -0
  21. ComfyUI/custom_nodes/ComfyUI-KJNodes/kjweb_async/purify.min.js +3 -0
  22. ComfyUI/custom_nodes/ComfyUI-KJNodes/kjweb_async/svg-path-properties.min.js +2 -0
  23. ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/__pycache__/audioscheduler_nodes.cpython-310.pyc +0 -0
  24. ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/__pycache__/batchcrop_nodes.cpython-310.pyc +0 -0
  25. ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/__pycache__/curve_nodes.cpython-310.pyc +0 -0
  26. ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/__pycache__/image_nodes.cpython-310.pyc +0 -0
  27. ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/__pycache__/intrinsic_lora_nodes.cpython-310.pyc +0 -0
  28. ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/__pycache__/mask_nodes.cpython-310.pyc +0 -0
  29. ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/__pycache__/nodes.cpython-310.pyc +0 -0
  30. ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/audioscheduler_nodes.py +251 -0
  31. ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/batchcrop_nodes.py +757 -0
  32. ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/curve_nodes.py +1393 -0
  33. ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/image_nodes.py +1678 -0
  34. ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/intrinsic_lora_nodes.py +115 -0
  35. ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/mask_nodes.py +1249 -0
  36. ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/nodes.py +1754 -0
  37. ComfyUI/custom_nodes/ComfyUI-KJNodes/pyproject.toml +15 -0
  38. ComfyUI/custom_nodes/ComfyUI-KJNodes/requirements.txt +7 -0
  39. ComfyUI/custom_nodes/ComfyUI-KJNodes/utility/__pycache__/utility.cpython-310.pyc +0 -0
  40. ComfyUI/custom_nodes/ComfyUI-KJNodes/utility/fluid.py +67 -0
  41. ComfyUI/custom_nodes/ComfyUI-KJNodes/utility/magictex.py +95 -0
  42. ComfyUI/custom_nodes/ComfyUI-KJNodes/utility/numerical.py +25 -0
  43. ComfyUI/custom_nodes/ComfyUI-KJNodes/utility/utility.py +39 -0
  44. ComfyUI/custom_nodes/ComfyUI-KJNodes/web/green.png +0 -0
  45. ComfyUI/custom_nodes/ComfyUI-KJNodes/web/js/appearance.js +23 -0
  46. ComfyUI/custom_nodes/ComfyUI-KJNodes/web/js/browserstatus.js +53 -0
  47. ComfyUI/custom_nodes/ComfyUI-KJNodes/web/js/contextmenu.js +152 -0
  48. ComfyUI/custom_nodes/ComfyUI-KJNodes/web/js/help_popup.js +325 -0
  49. ComfyUI/custom_nodes/ComfyUI-KJNodes/web/js/jsnodes.js +295 -0
  50. ComfyUI/custom_nodes/ComfyUI-KJNodes/web/js/point_editor.js +732 -0
ComfyUI/custom_nodes/ComfyUI-KJNodes/.github/workflows/publish.yml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Publish to Comfy registry
2
+ on:
3
+ workflow_dispatch:
4
+ push:
5
+ branches:
6
+ - main
7
+ paths:
8
+ - "pyproject.toml"
9
+
10
+ jobs:
11
+ publish-node:
12
+ name: Publish Custom Node to registry
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - name: Check out code
16
+ uses: actions/checkout@v4
17
+ - name: Publish Custom Node
18
+ uses: Comfy-Org/publish-node-action@main
19
+ with:
20
+ ## Add your own personal access token to your Github Repository secrets and reference it here.
21
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
ComfyUI/custom_nodes/ComfyUI-KJNodes/.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ /venv
3
+ *.code-workspace
4
+ .history
5
+ .vscode
6
+ *.ckpt
7
+ *.pth
8
+ types
9
+ models
10
+ jsconfig.json
ComfyUI/custom_nodes/ComfyUI-KJNodes/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/custom_nodes/ComfyUI-KJNodes/README.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # KJNodes for ComfyUI
2
+
3
+ Various quality of life and masking related -nodes and scripts made by combining functionality of existing nodes for ComfyUI.
4
+
5
+ I know I'm bad at documentation, especially this project that has grown from random practice nodes to... too many lines in one file.
6
+ I have however started to add descriptions to the nodes themselves, there's a small ? you can click for info what the node does.
7
+ This is still work in progress, like everything else.
8
+
9
+ # Installation
10
+ 1. Clone this repo into `custom_nodes` folder.
11
+ 2. Install dependencies: `pip install -r requirements.txt`
12
+ or if you use the portable install, run this in ComfyUI_windows_portable -folder:
13
+
14
+ `python_embeded\python.exe -m pip install -r ComfyUI\custom_nodes\ComfyUI-KJNodes\requirements.txt`
15
+
16
+
17
+ ## Javascript
18
+
19
+ ### browserstatus.js
20
+ Sets the favicon to green circle when not processing anything, sets it to red when processing and shows progress percentage and the lenghth of your queue.
21
+ Default off, needs to be enabled from options, overrides Custom-Scripts favicon when enabled.
22
+
23
+ ## Nodes:
24
+
25
+ ### Set/Get
26
+
27
+ Javascript nodes to set and get constants to reduce unnecessary lines. Takes in and returns anything, purely visual nodes.
28
+ On the right click menu of these nodes there's now an options to visualize the paths, as well as option to jump to the corresponding node on the other end.
29
+
30
+ **Known limitations**:
31
+ - Will not work with any node that dynamically sets it's outpute, such as reroute or other Set/Get node
32
+ - Will not work when directly connected to a bypassed node
33
+ - Other possible conflicts with javascript based nodes.
34
+
35
+ ### ColorToMask
36
+
37
+ RBG color value to mask, works with batches and AnimateDiff.
38
+
39
+ ### ConditioningMultiCombine
40
+
41
+ Combine any number of conditions, saves space.
42
+
43
+ ### ConditioningSetMaskAndCombine
44
+
45
+ Mask and combine two sets of conditions, saves space.
46
+
47
+ ### GrowMaskWithBlur
48
+
49
+ Grows or shrinks (with negative values) mask, option to invert input, returns mask and inverted mask. Additionally Blurs the mask, this is a slow operation especially with big batches.
50
+
51
+ ### RoundMask
52
+
53
+ ![image](https://github.com/kijai/ComfyUI-KJNodes/assets/40791699/52c85202-f74e-4b96-9dac-c8bda5ddcc40)
54
+
55
+ ### WidgetToString
56
+ Outputs the value of a widget on any node as a string
57
+ ![example of use](docs/images/2024-04-03_20_49_29-ComfyUI.png)
58
+
59
+ Enable node id display from Manager menu, to get the ID of the node you want to read a widget from:
60
+ ![enable node id display](docs/images/319121636-706b5081-9120-4a29-bd76-901691ada688.png)
61
+
62
+ Use the node id of the target node, and add the name of the widget to read from
63
+ ![use node id and widget name](docs/images/319121566-05f66385-7568-4b1f-8bbc-11053660b02f.png)
64
+
65
+ Recreating or reloading the target node will change its id, and the WidgetToString node will no longer be able to find it until you update the node id value with the new id.
ComfyUI/custom_nodes/ComfyUI-KJNodes/__init__.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .nodes.nodes import *
2
+ from .nodes.curve_nodes import *
3
+ from .nodes.batchcrop_nodes import *
4
+ from .nodes.audioscheduler_nodes import *
5
+ from .nodes.image_nodes import *
6
+ from .nodes.intrinsic_lora_nodes import *
7
+ from .nodes.mask_nodes import *
8
+ NODE_CONFIG = {
9
+ #constants
10
+ "INTConstant": {"class": INTConstant, "name": "INT Constant"},
11
+ "FloatConstant": {"class": FloatConstant, "name": "Float Constant"},
12
+ "StringConstant": {"class": StringConstant, "name": "String Constant"},
13
+ "StringConstantMultiline": {"class": StringConstantMultiline, "name": "String Constant Multiline"},
14
+ #conditioning
15
+ "ConditioningMultiCombine": {"class": ConditioningMultiCombine, "name": "Conditioning Multi Combine"},
16
+ "ConditioningSetMaskAndCombine": {"class": ConditioningSetMaskAndCombine, "name": "ConditioningSetMaskAndCombine"},
17
+ "ConditioningSetMaskAndCombine3": {"class": ConditioningSetMaskAndCombine3, "name": "ConditioningSetMaskAndCombine3"},
18
+ "ConditioningSetMaskAndCombine4": {"class": ConditioningSetMaskAndCombine4, "name": "ConditioningSetMaskAndCombine4"},
19
+ "ConditioningSetMaskAndCombine5": {"class": ConditioningSetMaskAndCombine5, "name": "ConditioningSetMaskAndCombine5"},
20
+ "CondPassThrough": {"class": CondPassThrough},
21
+ #masking
22
+ "DownloadAndLoadCLIPSeg": {"class": DownloadAndLoadCLIPSeg, "name": "(Down)load CLIPSeg"},
23
+ "BatchCLIPSeg": {"class": BatchCLIPSeg, "name": "Batch CLIPSeg"},
24
+ "ColorToMask": {"class": ColorToMask, "name": "Color To Mask"},
25
+ "CreateGradientMask": {"class": CreateGradientMask, "name": "Create Gradient Mask"},
26
+ "CreateTextMask": {"class": CreateTextMask, "name": "Create Text Mask"},
27
+ "CreateAudioMask": {"class": CreateAudioMask, "name": "Create Audio Mask"},
28
+ "CreateFadeMask": {"class": CreateFadeMask, "name": "Create Fade Mask"},
29
+ "CreateFadeMaskAdvanced": {"class": CreateFadeMaskAdvanced, "name": "Create Fade Mask Advanced"},
30
+ "CreateFluidMask": {"class": CreateFluidMask, "name": "Create Fluid Mask"},
31
+ "CreateShapeMask": {"class": CreateShapeMask, "name": "Create Shape Mask"},
32
+ "CreateVoronoiMask": {"class": CreateVoronoiMask, "name": "Create Voronoi Mask"},
33
+ "CreateMagicMask": {"class": CreateMagicMask, "name": "Create Magic Mask"},
34
+ "GetMaskSizeAndCount": {"class": GetMaskSizeAndCount, "name": "Get Mask Size & Count"},
35
+ "GrowMaskWithBlur": {"class": GrowMaskWithBlur, "name": "Grow Mask With Blur"},
36
+ "MaskBatchMulti": {"class": MaskBatchMulti, "name": "Mask Batch Multi"},
37
+ "OffsetMask": {"class": OffsetMask, "name": "Offset Mask"},
38
+ "RemapMaskRange": {"class": RemapMaskRange, "name": "Remap Mask Range"},
39
+ "ResizeMask": {"class": ResizeMask, "name": "Resize Mask"},
40
+ "RoundMask": {"class": RoundMask, "name": "Round Mask"},
41
+ #images
42
+ "AddLabel": {"class": AddLabel, "name": "Add Label"},
43
+ "ColorMatch": {"class": ColorMatch, "name": "Color Match"},
44
+ "CrossFadeImages": {"class": CrossFadeImages, "name": "Cross Fade Images"},
45
+ "GetImagesFromBatchIndexed": {"class": GetImagesFromBatchIndexed, "name": "Get Images From Batch Indexed"},
46
+ "GetImageRangeFromBatch": {"class": GetImageRangeFromBatch, "name": "Get Image or Mask Range From Batch"},
47
+ "GetImageSizeAndCount": {"class": GetImageSizeAndCount, "name": "Get Image Size & Count"},
48
+ "ImageAndMaskPreview": {"class": ImageAndMaskPreview},
49
+ "ImageAddMulti": {"class": ImageAddMulti, "name": "Image Add Multi"},
50
+ "ImageBatchMulti": {"class": ImageBatchMulti, "name": "Image Batch Multi"},
51
+ "ImageBatchRepeatInterleaving": {"class": ImageBatchRepeatInterleaving},
52
+ "ImageBatchTestPattern": {"class": ImageBatchTestPattern, "name": "Image Batch Test Pattern"},
53
+ "ImageConcanate": {"class": ImageConcanate, "name": "Image Concatenate"},
54
+ "ImageConcatMulti": {"class": ImageConcatMulti, "name": "Image Concatenate Multi"},
55
+ "ImageGrabPIL": {"class": ImageGrabPIL, "name": "Image Grab PIL"},
56
+ "ImageGridComposite2x2": {"class": ImageGridComposite2x2, "name": "Image Grid Composite 2x2"},
57
+ "ImageGridComposite3x3": {"class": ImageGridComposite3x3, "name": "Image Grid Composite 3x3"},
58
+ "ImageNormalize_Neg1_To_1": {"class": ImageNormalize_Neg1_To_1, "name": "Image Normalize -1 to 1"},
59
+ "ImagePass": {"class": ImagePass},
60
+ "ImagePadForOutpaintMasked": {"class": ImagePadForOutpaintMasked, "name": "Image Pad For Outpaint Masked"},
61
+ "ImagePadForOutpaintTargetSize": {"class": ImagePadForOutpaintTargetSize, "name": "Image Pad For Outpaint Target Size"},
62
+ "ImageResizeKJ": {"class": ImageResizeKJ, "name": "Resize Image"},
63
+ "ImageUpscaleWithModelBatched": {"class": ImageUpscaleWithModelBatched, "name": "Image Upscale With Model Batched"},
64
+ "InsertImagesToBatchIndexed": {"class": InsertImagesToBatchIndexed, "name": "Insert Images To Batch Indexed"},
65
+ "LoadAndResizeImage": {"class": LoadAndResizeImage, "name": "Load & Resize Image"},
66
+ "MergeImageChannels": {"class": MergeImageChannels, "name": "Merge Image Channels"},
67
+ "PreviewAnimation": {"class": PreviewAnimation, "name": "Preview Animation"},
68
+ "RemapImageRange": {"class": RemapImageRange, "name": "Remap Image Range"},
69
+ "ReverseImageBatch": {"class": ReverseImageBatch, "name": "Reverse Image Batch"},
70
+ "ReplaceImagesInBatch": {"class": ReplaceImagesInBatch, "name": "Replace Images In Batch"},
71
+ "SaveImageWithAlpha": {"class": SaveImageWithAlpha, "name": "Save Image With Alpha"},
72
+ "SplitImageChannels": {"class": SplitImageChannels, "name": "Split Image Channels"},
73
+ #batch cropping
74
+ "BatchCropFromMask": {"class": BatchCropFromMask, "name": "Batch Crop From Mask"},
75
+ "BatchCropFromMaskAdvanced": {"class": BatchCropFromMaskAdvanced, "name": "Batch Crop From Mask Advanced"},
76
+ "FilterZeroMasksAndCorrespondingImages": {"class": FilterZeroMasksAndCorrespondingImages},
77
+ "InsertImageBatchByIndexes": {"class": InsertImageBatchByIndexes, "name": "Insert Image Batch By Indexes"},
78
+ "BatchUncrop": {"class": BatchUncrop, "name": "Batch Uncrop"},
79
+ "BatchUncropAdvanced": {"class": BatchUncropAdvanced, "name": "Batch Uncrop Advanced"},
80
+ "SplitBboxes": {"class": SplitBboxes, "name": "Split Bboxes"},
81
+ "BboxToInt": {"class": BboxToInt, "name": "Bbox To Int"},
82
+ "BboxVisualize": {"class": BboxVisualize, "name": "Bbox Visualize"},
83
+ #noise
84
+ "GenerateNoise": {"class": GenerateNoise, "name": "Generate Noise"},
85
+ "FlipSigmasAdjusted": {"class": FlipSigmasAdjusted, "name": "Flip Sigmas Adjusted"},
86
+ "InjectNoiseToLatent": {"class": InjectNoiseToLatent, "name": "Inject Noise To Latent"},
87
+ "CustomSigmas": {"class": CustomSigmas, "name": "Custom Sigmas"},
88
+ #utility
89
+ "WidgetToString": {"class": WidgetToString, "name": "Widget To String"},
90
+ "DummyOut": {"class": DummyOut, "name": "Dummy Out"},
91
+ "GetLatentsFromBatchIndexed": {"class": GetLatentsFromBatchIndexed, "name": "Get Latents From Batch Indexed"},
92
+ "ScaleBatchPromptSchedule": {"class": ScaleBatchPromptSchedule, "name": "Scale Batch Prompt Schedule"},
93
+ "CameraPoseVisualizer": {"class": CameraPoseVisualizer, "name": "Camera Pose Visualizer"},
94
+ "JoinStrings": {"class": JoinStrings, "name": "Join Strings"},
95
+ "JoinStringMulti": {"class": JoinStringMulti, "name": "Join String Multi"},
96
+ "SomethingToString": {"class": SomethingToString, "name": "Something To String"},
97
+ "Sleep": {"class": Sleep, "name": "Sleep"},
98
+ "VRAM_Debug": {"class": VRAM_Debug, "name": "VRAM Debug"},
99
+ "SomethingToString": {"class": SomethingToString, "name": "Something To String"},
100
+ "EmptyLatentImagePresets": {"class": EmptyLatentImagePresets, "name": "Empty Latent Image Presets"},
101
+ "ModelPassThrough": {"class": ModelPassThrough, "name": "ModelPass"},
102
+ #audioscheduler stuff
103
+ "NormalizedAmplitudeToMask": {"class": NormalizedAmplitudeToMask},
104
+ "NormalizedAmplitudeToFloatList": {"class": NormalizedAmplitudeToFloatList},
105
+ "OffsetMaskByNormalizedAmplitude": {"class": OffsetMaskByNormalizedAmplitude},
106
+ "ImageTransformByNormalizedAmplitude": {"class": ImageTransformByNormalizedAmplitude},
107
+ #curve nodes
108
+ "SplineEditor": {"class": SplineEditor, "name": "Spline Editor"},
109
+ "CreateShapeImageOnPath": {"class": CreateShapeImageOnPath, "name": "Create Shape Image On Path"},
110
+ "CreateShapeMaskOnPath": {"class": CreateShapeMaskOnPath, "name": "Create Shape Mask On Path"},
111
+ "CreateTextOnPath": {"class": CreateTextOnPath, "name": "Create Text On Path"},
112
+ "CreateGradientFromCoords": {"class": CreateGradientFromCoords, "name": "Create Gradient From Coords"},
113
+ "GradientToFloat": {"class": GradientToFloat, "name": "Gradient To Float"},
114
+ "WeightScheduleExtend": {"class": WeightScheduleExtend, "name": "Weight Schedule Extend"},
115
+ "MaskOrImageToWeight": {"class": MaskOrImageToWeight, "name": "Mask Or Image To Weight"},
116
+ "WeightScheduleConvert": {"class": WeightScheduleConvert, "name": "Weight Schedule Convert"},
117
+ "FloatToMask": {"class": FloatToMask, "name": "Float To Mask"},
118
+ "FloatToSigmas": {"class": FloatToSigmas, "name": "Float To Sigmas"},
119
+ "PlotCoordinates": {"class": PlotCoordinates, "name": "Plot Coordinates"},
120
+ "InterpolateCoords": {"class": InterpolateCoords, "name": "Interpolate Coords"},
121
+ "PointsEditor": {"class": PointsEditor, "name": "Points Editor"},
122
+ #experimental
123
+ "StabilityAPI_SD3": {"class": StabilityAPI_SD3, "name": "Stability API SD3"},
124
+ "SoundReactive": {"class": SoundReactive, "name": "Sound Reactive"},
125
+ "StableZero123_BatchSchedule": {"class": StableZero123_BatchSchedule, "name": "Stable Zero123 Batch Schedule"},
126
+ "SV3D_BatchSchedule": {"class": SV3D_BatchSchedule, "name": "SV3D Batch Schedule"},
127
+ "LoadResAdapterNormalization": {"class": LoadResAdapterNormalization},
128
+ "Superprompt": {"class": Superprompt, "name": "Superprompt"},
129
+ "GLIGENTextBoxApplyBatchCoords": {"class": GLIGENTextBoxApplyBatchCoords},
130
+ "Intrinsic_lora_sampling": {"class": Intrinsic_lora_sampling, "name": "Intrinsic Lora Sampling"},
131
+ "CheckpointPerturbWeights": {"class": CheckpointPerturbWeights, "name": "CheckpointPerturbWeights"},
132
+ "Screencap_mss": {"class": Screencap_mss, "name": "Screencap mss"},
133
+ "WebcamCaptureCV2": {"class": WebcamCaptureCV2, "name": "Webcam Capture CV2"},
134
+
135
+ #instance diffusion
136
+ "CreateInstanceDiffusionTracking": {"class": CreateInstanceDiffusionTracking},
137
+ "AppendInstanceDiffusionTracking": {"class": AppendInstanceDiffusionTracking},
138
+ "DrawInstanceDiffusionTracking": {"class": DrawInstanceDiffusionTracking},
139
+ }
140
+
141
+ def generate_node_mappings(node_config):
142
+ node_class_mappings = {}
143
+ node_display_name_mappings = {}
144
+
145
+ for node_name, node_info in node_config.items():
146
+ node_class_mappings[node_name] = node_info["class"]
147
+ node_display_name_mappings[node_name] = node_info.get("name", node_info["class"].__name__)
148
+
149
+ return node_class_mappings, node_display_name_mappings
150
+
151
+ NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS = generate_node_mappings(NODE_CONFIG)
152
+
153
+ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
154
+
155
+ WEB_DIRECTORY = "./web"
156
+
157
+ from aiohttp import web
158
+ from server import PromptServer
159
+ from pathlib import Path
160
+
161
+ if hasattr(PromptServer, "instance"):
162
+
163
+ # NOTE: we add an extra static path to avoid comfy mechanism
164
+ # that loads every script in web.
165
+ PromptServer.instance.app.add_routes(
166
+ [web.static("/kjweb_async", (Path(__file__).parent.absolute() / "kjweb_async").as_posix())]
167
+ )
ComfyUI/custom_nodes/ComfyUI-KJNodes/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (8.03 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-KJNodes/config.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "sai_api_key": "your_api_key_here"
3
+ }
ComfyUI/custom_nodes/ComfyUI-KJNodes/docs/images/2024-04-03_20_49_29-ComfyUI.png ADDED
ComfyUI/custom_nodes/ComfyUI-KJNodes/docs/images/319121566-05f66385-7568-4b1f-8bbc-11053660b02f.png ADDED
ComfyUI/custom_nodes/ComfyUI-KJNodes/docs/images/319121636-706b5081-9120-4a29-bd76-901691ada688.png ADDED
ComfyUI/custom_nodes/ComfyUI-KJNodes/fonts/FreeMono.ttf ADDED
Binary file (344 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-KJNodes/fonts/FreeMonoBoldOblique.otf ADDED
Binary file (238 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-KJNodes/fonts/TTNorms-Black.otf ADDED
Binary file (153 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-KJNodes/intrinsic_loras/intrinsic_lora_sd15_albedo.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d897f04ff2bb452e29a8f2a3c5c3cd5c55e95f314242cd645fbbe24a5ac59961
3
+ size 6416109
ComfyUI/custom_nodes/ComfyUI-KJNodes/intrinsic_loras/intrinsic_lora_sd15_depth.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f199d6bf3180fe7271073c3769dcb764b40f35f41b30fcb183ae5bf4b6a9997f
3
+ size 6416109
ComfyUI/custom_nodes/ComfyUI-KJNodes/intrinsic_loras/intrinsic_lora_sd15_normal.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:02934db0a0b92a9cdda402e42548560beda7d31b268e561dbc6815551e876268
3
+ size 6416109
ComfyUI/custom_nodes/ComfyUI-KJNodes/intrinsic_loras/intrinsic_lora_sd15_shading.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:635e998063a10211633edd3e4b1676201822cd67f790ec71dba5f32d8b625c8b
3
+ size 6416109
ComfyUI/custom_nodes/ComfyUI-KJNodes/intrinsic_loras/intrinsic_loras.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ source for the loras:
2
+ https://github.com/duxiaodan/intrinsic-lora
3
+
4
+ Renamed and conveted to .safetensors
ComfyUI/custom_nodes/ComfyUI-KJNodes/kjweb_async/marked.min.js ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ /**
2
+ * marked v12.0.1 - a markdown parser
3
+ * Copyright (c) 2011-2024, Christopher Jeffrey. (MIT Licensed)
4
+ * https://github.com/markedjs/marked
5
+ */
6
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).marked={})}(this,(function(e){"use strict";function t(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function n(t){e.defaults=t}e.defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};const s=/[&<>"']/,r=new RegExp(s.source,"g"),i=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,l=new RegExp(i.source,"g"),o={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},a=e=>o[e];function c(e,t){if(t){if(s.test(e))return e.replace(r,a)}else if(i.test(e))return e.replace(l,a);return e}const h=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi;function p(e){return e.replace(h,((e,t)=>"colon"===(t=t.toLowerCase())?":":"#"===t.charAt(0)?"x"===t.charAt(1)?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}const u=/(^|[^\[])\^/g;function k(e,t){let n="string"==typeof e?e:e.source;t=t||"";const s={replace:(e,t)=>{let r="string"==typeof t?t:t.source;return r=r.replace(u,"$1"),n=n.replace(e,r),s},getRegex:()=>new RegExp(n,t)};return s}function g(e){try{e=encodeURI(e).replace(/%25/g,"%")}catch(e){return null}return e}const f={exec:()=>null};function d(e,t){const n=e.replace(/\|/g,((e,t,n)=>{let s=!1,r=t;for(;--r>=0&&"\\"===n[r];)s=!s;return s?"|":" |"})).split(/ \|/);let s=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(/\\\|/g,"|");return n}function x(e,t,n){const s=e.length;if(0===s)return"";let r=0;for(;r<s;){const i=e.charAt(s-r-1);if(i!==t||n){if(i===t||!n)break;r++}else r++}return e.slice(0,s-r)}function b(e,t,n,s){const r=t.href,i=t.title?c(t.title):null,l=e[1].replace(/\\([\[\]])/g,"$1");if("!"!==e[0].charAt(0)){s.state.inLink=!0;const e={type:"link",raw:n,href:r,title:i,text:l,tokens:s.inlineTokens(l)};return s.state.inLink=!1,e}return{type:"image",raw:n,href:r,title:i,text:c(l)}}class w{options;rules;lexer;constructor(t){this.options=t||e.defaults}space(e){const t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const e=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?e:x(e,"\n")}}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const e=t[0],n=function(e,t){const n=e.match(/^(\s+)(?:```)/);if(null===n)return t;const s=n[1];return t.split("\n").map((e=>{const t=e.match(/^\s+/);if(null===t)return e;const[n]=t;return n.length>=s.length?e.slice(s.length):e})).join("\n")}(e,t[3]||"");return{type:"code",raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(/#$/.test(e)){const t=x(e,"#");this.options.pedantic?e=t.trim():t&&!/ $/.test(t)||(e=t.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:t[0]}}blockquote(e){const t=this.rules.block.blockquote.exec(e);if(t){const e=x(t[0].replace(/^ *>[ \t]?/gm,""),"\n"),n=this.lexer.state.top;this.lexer.state.top=!0;const s=this.lexer.blockTokens(e);return this.lexer.state.top=n,{type:"blockquote",raw:t[0],tokens:s,text:e}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim();const s=n.length>1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");const i=new RegExp(`^( {0,3}${n})((?:[\t ][^\\n]*)?(?:\\n|$))`);let l="",o="",a=!1;for(;e;){let n=!1;if(!(t=i.exec(e)))break;if(this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let s=t[2].split("\n",1)[0].replace(/^\t+/,(e=>" ".repeat(3*e.length))),c=e.split("\n",1)[0],h=0;this.options.pedantic?(h=2,o=s.trimStart()):(h=t[2].search(/[^ ]/),h=h>4?1:h,o=s.slice(h),h+=t[1].length);let p=!1;if(!s&&/^ *$/.test(c)&&(l+=c+"\n",e=e.substring(c.length+1),n=!0),!n){const t=new RegExp(`^ {0,${Math.min(3,h-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),n=new RegExp(`^ {0,${Math.min(3,h-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),r=new RegExp(`^ {0,${Math.min(3,h-1)}}(?:\`\`\`|~~~)`),i=new RegExp(`^ {0,${Math.min(3,h-1)}}#`);for(;e;){const a=e.split("\n",1)[0];if(c=a,this.options.pedantic&&(c=c.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),r.test(c))break;if(i.test(c))break;if(t.test(c))break;if(n.test(e))break;if(c.search(/[^ ]/)>=h||!c.trim())o+="\n"+c.slice(h);else{if(p)break;if(s.search(/[^ ]/)>=4)break;if(r.test(s))break;if(i.test(s))break;if(n.test(s))break;o+="\n"+c}p||c.trim()||(p=!0),l+=a+"\n",e=e.substring(a.length+1),s=c.slice(h)}}r.loose||(a?r.loose=!0:/\n *\n *$/.test(l)&&(a=!0));let u,k=null;this.options.gfm&&(k=/^\[[ xX]\] /.exec(o),k&&(u="[ ] "!==k[0],o=o.replace(/^\[[ xX]\] +/,""))),r.items.push({type:"list_item",raw:l,task:!!k,checked:u,loose:!1,text:o,tokens:[]}),r.raw+=l}r.items[r.items.length-1].raw=l.trimEnd(),r.items[r.items.length-1].text=o.trimEnd(),r.raw=r.raw.trimEnd();for(let e=0;e<r.items.length;e++)if(this.lexer.state.top=!1,r.items[e].tokens=this.lexer.blockTokens(r.items[e].text,[]),!r.loose){const t=r.items[e].tokens.filter((e=>"space"===e.type)),n=t.length>0&&t.some((e=>/\n.*\n/.test(e.raw)));r.loose=n}if(r.loose)for(let e=0;e<r.items.length;e++)r.items[e].loose=!0;return r}}html(e){const t=this.rules.block.html.exec(e);if(t){return{type:"html",block:!0,raw:t[0],pre:"pre"===t[1]||"script"===t[1]||"style"===t[1],text:t[0]}}}def(e){const t=this.rules.block.def.exec(e);if(t){const e=t[1].toLowerCase().replace(/\s+/g," "),n=t[2]?t[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:e,raw:t[0],href:n,title:s}}}table(e){const t=this.rules.block.table.exec(e);if(!t)return;if(!/[:|]/.test(t[2]))return;const n=d(t[1]),s=t[2].replace(/^\||\| *$/g,"").split("|"),r=t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split("\n"):[],i={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===s.length){for(const e of s)/^ *-+: *$/.test(e)?i.align.push("right"):/^ *:-+: *$/.test(e)?i.align.push("center"):/^ *:-+ *$/.test(e)?i.align.push("left"):i.align.push(null);for(const e of n)i.header.push({text:e,tokens:this.lexer.inline(e)});for(const e of r)i.rows.push(d(e,i.header.length).map((e=>({text:e,tokens:this.lexer.inline(e)}))));return i}}lheading(e){const t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:"="===t[2].charAt(0)?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){const t=this.rules.block.paragraph.exec(e);if(t){const e="\n"===t[1].charAt(t[1].length-1)?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){const t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){const t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:c(t[1])}}tag(e){const t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&/^<a /i.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){const t=this.rules.inline.link.exec(e);if(t){const e=t[2].trim();if(!this.options.pedantic&&/^</.test(e)){if(!/>$/.test(e))return;const t=x(e.slice(0,-1),"\\");if((e.length-t.length)%2==0)return}else{const e=function(e,t){if(-1===e.indexOf(t[1]))return-1;let n=0;for(let s=0;s<e.length;s++)if("\\"===e[s])s++;else if(e[s]===t[0])n++;else if(e[s]===t[1]&&(n--,n<0))return s;return-1}(t[2],"()");if(e>-1){const n=(0===t[0].indexOf("!")?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let n=t[2],s="";if(this.options.pedantic){const e=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);e&&(n=e[1],s=e[3])}else s=t[3]?t[3].slice(1,-1):"";return n=n.trim(),/^</.test(n)&&(n=this.options.pedantic&&!/>$/.test(e)?n.slice(1):n.slice(1,-1)),b(t,{href:n?n.replace(this.rules.inline.anyPunctuation,"$1"):n,title:s?s.replace(this.rules.inline.anyPunctuation,"$1"):s},t[0],this.lexer)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){const e=t[(n[2]||n[1]).replace(/\s+/g," ").toLowerCase()];if(!e){const e=n[0].charAt(0);return{type:"text",raw:e,text:e}}return b(n,e,n[0],this.lexer)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s)return;if(s[3]&&n.match(/[\p{L}\p{N}]/u))return;if(!(s[1]||s[2]||"")||!n||this.rules.inline.punctuation.exec(n)){const n=[...s[0]].length-1;let r,i,l=n,o=0;const a="*"===s[0][0]?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(a.lastIndex=0,t=t.slice(-1*e.length+n);null!=(s=a.exec(t));){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(i=[...r].length,s[3]||s[4]){l+=i;continue}if((s[5]||s[6])&&n%3&&!((n+i)%3)){o+=i;continue}if(l-=i,l>0)continue;i=Math.min(i,i+l+o);const t=[...s[0]][0].length,a=e.slice(0,n+s.index+t+i);if(Math.min(n,i)%2){const e=a.slice(1,-1);return{type:"em",raw:a,text:e,tokens:this.lexer.inlineTokens(e)}}const c=a.slice(2,-2);return{type:"strong",raw:a,text:c,tokens:this.lexer.inlineTokens(c)}}}}codespan(e){const t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(/\n/g," ");const n=/[^ ]/.test(e),s=/^ /.test(e)&&/ $/.test(e);return n&&s&&(e=e.substring(1,e.length-1)),e=c(e,!0),{type:"codespan",raw:t[0],text:e}}}br(e){const t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){const t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){const t=this.rules.inline.autolink.exec(e);if(t){let e,n;return"@"===t[2]?(e=c(t[1]),n="mailto:"+e):(e=c(t[1]),n=e),{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if("@"===t[2])e=c(t[0]),n="mailto:"+e;else{let s;do{s=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??""}while(s!==t[0]);e=c(t[0]),n="www."===t[1]?"http://"+t[0]:t[0]}return{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}inlineText(e){const t=this.rules.inline.text.exec(e);if(t){let e;return e=this.lexer.state.inRawBlock?t[0]:c(t[0]),{type:"text",raw:t[0],text:e}}}}const m=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,y=/(?:[*+-]|\d{1,9}[.)])/,$=k(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,y).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),z=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,T=/(?!\s*\])(?:\\.|[^\[\]\\])+/,R=k(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",T).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),_=k(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,y).getRegex(),A="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",S=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,I=k("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",S).replace("tag",A).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),E=k(z).replace("hr",m).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex(),q={blockquote:k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",E).getRegex(),code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,def:R,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hr:m,html:I,lheading:$,list:_,newline:/^(?: *(?:\n|$))+/,paragraph:E,table:f,text:/^[^\n]+/},Z=k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",m).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex(),L={...q,table:Z,paragraph:k(z).replace("hr",m).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Z).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex()},P={...q,html:k("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",S).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:f,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:k(z).replace("hr",m).replace("heading"," *#{1,6} *[^\n]").replace("lheading",$).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Q=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,v=/^( {2,}|\\)\n(?!\s*$)/,B="\\p{P}\\p{S}",C=k(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,B).getRegex(),M=k(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,B).getRegex(),O=k("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,B).getRegex(),D=k("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,B).getRegex(),j=k(/\\([punct])/,"gu").replace(/punct/g,B).getRegex(),H=k(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),U=k(S).replace("(?:--\x3e|$)","--\x3e").getRegex(),X=k("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",U).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),F=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,N=k(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",F).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),G=k(/^!?\[(label)\]\[(ref)\]/).replace("label",F).replace("ref",T).getRegex(),J=k(/^!?\[(ref)\](?:\[\])?/).replace("ref",T).getRegex(),K={_backpedal:f,anyPunctuation:j,autolink:H,blockSkip:/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,br:v,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,del:f,emStrongLDelim:M,emStrongRDelimAst:O,emStrongRDelimUnd:D,escape:Q,link:N,nolink:J,punctuation:C,reflink:G,reflinkSearch:k("reflink|nolink(?!\\()","g").replace("reflink",G).replace("nolink",J).getRegex(),tag:X,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,url:f},V={...K,link:k(/^!?\[(label)\]\((.*?)\)/).replace("label",F).getRegex(),reflink:k(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",F).getRegex()},W={...K,escape:k(Q).replace("])","~|])").getRegex(),url:k(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},Y={...W,br:k(v).replace("{2,}","*").getRegex(),text:k(W.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ee={normal:q,gfm:L,pedantic:P},te={normal:K,gfm:W,breaks:Y,pedantic:V};class ne{tokens;options;state;tokenizer;inlineQueue;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||e.defaults,this.options.tokenizer=this.options.tokenizer||new w,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const n={block:ee.normal,inline:te.normal};this.options.pedantic?(n.block=ee.pedantic,n.inline=te.pedantic):this.options.gfm&&(n.block=ee.gfm,this.options.breaks?n.inline=te.breaks:n.inline=te.gfm),this.tokenizer.rules=n}static get rules(){return{block:ee,inline:te}}static lex(e,t){return new ne(t).lex(e)}static lexInline(e,t){return new ne(t).inlineTokens(e)}lex(e){e=e.replace(/\r\n|\r/g,"\n"),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){const t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[]){let n,s,r,i;for(e=this.options.pedantic?e.replace(/\t/g," ").replace(/^ +$/gm,""):e.replace(/^( *)(\t+)/gm,((e,t,n)=>t+" ".repeat(n.length)));e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some((s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.space(e))e=e.substring(n.raw.length),1===n.raw.length&&t.length>0?t[t.length-1].raw+="\n":t.push(n);else if(n=this.tokenizer.code(e))e=e.substring(n.raw.length),s=t[t.length-1],!s||"paragraph"!==s.type&&"text"!==s.type?t.push(n):(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue[this.inlineQueue.length-1].src=s.text);else if(n=this.tokenizer.fences(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.heading(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.hr(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.blockquote(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.list(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.html(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.def(e))e=e.substring(n.raw.length),s=t[t.length-1],!s||"paragraph"!==s.type&&"text"!==s.type?this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title}):(s.raw+="\n"+n.raw,s.text+="\n"+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=s.text);else if(n=this.tokenizer.table(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.lheading(e))e=e.substring(n.raw.length),t.push(n);else{if(r=e,this.options.extensions&&this.options.extensions.startBlock){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startBlock.forEach((e=>{s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(this.state.top&&(n=this.tokenizer.paragraph(r)))s=t[t.length-1],i&&"paragraph"===s.type?(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s.text):t.push(n),i=r.length!==e.length,e=e.substring(n.raw.length);else if(n=this.tokenizer.text(e))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===s.type?(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n,s,r,i,l,o,a=e;if(this.tokens.links){const e=Object.keys(this.tokens.links);if(e.length>0)for(;null!=(i=this.tokenizer.rules.inline.reflinkSearch.exec(a));)e.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(i=this.tokenizer.rules.inline.blockSkip.exec(a));)a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;null!=(i=this.tokenizer.rules.inline.anyPunctuation.exec(a));)a=a.slice(0,i.index)+"++"+a.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;e;)if(l||(o=""),l=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some((s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.escape(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.tag(e))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.link(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.reflink(e,this.tokens.links))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.emStrong(e,a,o))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.codespan(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.br(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.del(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.autolink(e))e=e.substring(n.raw.length),t.push(n);else if(this.state.inLink||!(n=this.tokenizer.url(e))){if(r=e,this.options.extensions&&this.options.extensions.startInline){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startInline.forEach((e=>{s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(n=this.tokenizer.inlineText(r))e=e.substring(n.raw.length),"_"!==n.raw.slice(-1)&&(o=n.raw.slice(-1)),l=!0,s=t[t.length-1],s&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}else e=e.substring(n.raw.length),t.push(n);return t}}class se{options;constructor(t){this.options=t||e.defaults}code(e,t,n){const s=(t||"").match(/^\S*/)?.[0];return e=e.replace(/\n$/,"")+"\n",s?'<pre><code class="language-'+c(s)+'">'+(n?e:c(e,!0))+"</code></pre>\n":"<pre><code>"+(n?e:c(e,!0))+"</code></pre>\n"}blockquote(e){return`<blockquote>\n${e}</blockquote>\n`}html(e,t){return e}heading(e,t,n){return`<h${t}>${e}</h${t}>\n`}hr(){return"<hr>\n"}list(e,t,n){const s=t?"ol":"ul";return"<"+s+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"</"+s+">\n"}listitem(e,t,n){return`<li>${e}</li>\n`}checkbox(e){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph(e){return`<p>${e}</p>\n`}table(e,t){return t&&(t=`<tbody>${t}</tbody>`),"<table>\n<thead>\n"+e+"</thead>\n"+t+"</table>\n"}tablerow(e){return`<tr>\n${e}</tr>\n`}tablecell(e,t){const n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>\n`}strong(e){return`<strong>${e}</strong>`}em(e){return`<em>${e}</em>`}codespan(e){return`<code>${e}</code>`}br(){return"<br>"}del(e){return`<del>${e}</del>`}link(e,t,n){const s=g(e);if(null===s)return n;let r='<a href="'+(e=s)+'"';return t&&(r+=' title="'+t+'"'),r+=">"+n+"</a>",r}image(e,t,n){const s=g(e);if(null===s)return n;let r=`<img src="${e=s}" alt="${n}"`;return t&&(r+=` title="${t}"`),r+=">",r}text(e){return e}}class re{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,t,n){return""+n}image(e,t,n){return""+n}br(){return""}}class ie{options;renderer;textRenderer;constructor(t){this.options=t||e.defaults,this.options.renderer=this.options.renderer||new se,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new re}static parse(e,t){return new ie(t).parse(e)}static parseInline(e,t){return new ie(t).parseInline(e)}parse(e,t=!0){let n="";for(let s=0;s<e.length;s++){const r=e[s];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[r.type]){const e=r,t=this.options.extensions.renderers[e.type].call({parser:this},e);if(!1!==t||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(e.type)){n+=t||"";continue}}switch(r.type){case"space":continue;case"hr":n+=this.renderer.hr();continue;case"heading":{const e=r;n+=this.renderer.heading(this.parseInline(e.tokens),e.depth,p(this.parseInline(e.tokens,this.textRenderer)));continue}case"code":{const e=r;n+=this.renderer.code(e.text,e.lang,!!e.escaped);continue}case"table":{const e=r;let t="",s="";for(let t=0;t<e.header.length;t++)s+=this.renderer.tablecell(this.parseInline(e.header[t].tokens),{header:!0,align:e.align[t]});t+=this.renderer.tablerow(s);let i="";for(let t=0;t<e.rows.length;t++){const n=e.rows[t];s="";for(let t=0;t<n.length;t++)s+=this.renderer.tablecell(this.parseInline(n[t].tokens),{header:!1,align:e.align[t]});i+=this.renderer.tablerow(s)}n+=this.renderer.table(t,i);continue}case"blockquote":{const e=r,t=this.parse(e.tokens);n+=this.renderer.blockquote(t);continue}case"list":{const e=r,t=e.ordered,s=e.start,i=e.loose;let l="";for(let t=0;t<e.items.length;t++){const n=e.items[t],s=n.checked,r=n.task;let o="";if(n.task){const e=this.renderer.checkbox(!!s);i?n.tokens.length>0&&"paragraph"===n.tokens[0].type?(n.tokens[0].text=e+" "+n.tokens[0].text,n.tokens[0].tokens&&n.tokens[0].tokens.length>0&&"text"===n.tokens[0].tokens[0].type&&(n.tokens[0].tokens[0].text=e+" "+n.tokens[0].tokens[0].text)):n.tokens.unshift({type:"text",text:e+" "}):o+=e+" "}o+=this.parse(n.tokens,i),l+=this.renderer.listitem(o,r,!!s)}n+=this.renderer.list(l,t,s);continue}case"html":{const e=r;n+=this.renderer.html(e.text,e.block);continue}case"paragraph":{const e=r;n+=this.renderer.paragraph(this.parseInline(e.tokens));continue}case"text":{let i=r,l=i.tokens?this.parseInline(i.tokens):i.text;for(;s+1<e.length&&"text"===e[s+1].type;)i=e[++s],l+="\n"+(i.tokens?this.parseInline(i.tokens):i.text);n+=t?this.renderer.paragraph(l):l;continue}default:{const e='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}parseInline(e,t){t=t||this.renderer;let n="";for(let s=0;s<e.length;s++){const r=e[s];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[r.type]){const e=this.options.extensions.renderers[r.type].call({parser:this},r);if(!1!==e||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){n+=e||"";continue}}switch(r.type){case"escape":{const e=r;n+=t.text(e.text);break}case"html":{const e=r;n+=t.html(e.text);break}case"link":{const e=r;n+=t.link(e.href,e.title,this.parseInline(e.tokens,t));break}case"image":{const e=r;n+=t.image(e.href,e.title,e.text);break}case"strong":{const e=r;n+=t.strong(this.parseInline(e.tokens,t));break}case"em":{const e=r;n+=t.em(this.parseInline(e.tokens,t));break}case"codespan":{const e=r;n+=t.codespan(e.text);break}case"br":n+=t.br();break;case"del":{const e=r;n+=t.del(this.parseInline(e.tokens,t));break}case"text":{const e=r;n+=t.text(e.text);break}default:{const e='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}}class le{options;constructor(t){this.options=t||e.defaults}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}}class oe{defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};options=this.setOptions;parse=this.#e(ne.lex,ie.parse);parseInline=this.#e(ne.lexInline,ie.parseInline);Parser=ie;Renderer=se;TextRenderer=re;Lexer=ne;Tokenizer=w;Hooks=le;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(const s of e)switch(n=n.concat(t.call(this,s)),s.type){case"table":{const e=s;for(const s of e.header)n=n.concat(this.walkTokens(s.tokens,t));for(const s of e.rows)for(const e of s)n=n.concat(this.walkTokens(e.tokens,t));break}case"list":{const e=s;n=n.concat(this.walkTokens(e.items,t));break}default:{const e=s;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach((s=>{const r=e[s].flat(1/0);n=n.concat(this.walkTokens(r,t))})):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){const t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((e=>{const n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach((e=>{if(!e.name)throw new Error("extension name required");if("renderer"in e){const n=t.renderers[e.name];t.renderers[e.name]=n?function(...t){let s=e.renderer.apply(this,t);return!1===s&&(s=n.apply(this,t)),s}:e.renderer}if("tokenizer"in e){if(!e.level||"block"!==e.level&&"inline"!==e.level)throw new Error("extension level must be 'block' or 'inline'");const n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&("block"===e.level?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:"inline"===e.level&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}"childTokens"in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)})),n.extensions=t),e.renderer){const t=this.defaults.renderer||new se(this.defaults);for(const n in e.renderer){if(!(n in t))throw new Error(`renderer '${n}' does not exist`);if("options"===n)continue;const s=n,r=e.renderer[s],i=t[s];t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n||""}}n.renderer=t}if(e.tokenizer){const t=this.defaults.tokenizer||new w(this.defaults);for(const n in e.tokenizer){if(!(n in t))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;const s=n,r=e.tokenizer[s],i=t[s];t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){const t=this.defaults.hooks||new le;for(const n in e.hooks){if(!(n in t))throw new Error(`hook '${n}' does not exist`);if("options"===n)continue;const s=n,r=e.hooks[s],i=t[s];le.passThroughHooks.has(n)?t[s]=e=>{if(this.defaults.async)return Promise.resolve(r.call(t,e)).then((e=>i.call(t,e)));const n=r.call(t,e);return i.call(t,n)}:t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){const t=this.defaults.walkTokens,s=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(s.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}})),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ne.lex(e,t??this.defaults)}parser(e,t){return ie.parse(e,t??this.defaults)}#e(e,t){return(n,s)=>{const r={...s},i={...this.defaults,...r};!0===this.defaults.async&&!1===r.async&&(i.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),i.async=!0);const l=this.#t(!!i.silent,!!i.async);if(null==n)return l(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof n)return l(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(i.hooks&&(i.hooks.options=i),i.async)return Promise.resolve(i.hooks?i.hooks.preprocess(n):n).then((t=>e(t,i))).then((e=>i.hooks?i.hooks.processAllTokens(e):e)).then((e=>i.walkTokens?Promise.all(this.walkTokens(e,i.walkTokens)).then((()=>e)):e)).then((e=>t(e,i))).then((e=>i.hooks?i.hooks.postprocess(e):e)).catch(l);try{i.hooks&&(n=i.hooks.preprocess(n));let s=e(n,i);i.hooks&&(s=i.hooks.processAllTokens(s)),i.walkTokens&&this.walkTokens(s,i.walkTokens);let r=t(s,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return l(e)}}}#t(e,t){return n=>{if(n.message+="\nPlease report this to https://github.com/markedjs/marked.",e){const e="<p>An error occurred:</p><pre>"+c(n.message+"",!0)+"</pre>";return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}}const ae=new oe;function ce(e,t){return ae.parse(e,t)}ce.options=ce.setOptions=function(e){return ae.setOptions(e),ce.defaults=ae.defaults,n(ce.defaults),ce},ce.getDefaults=t,ce.defaults=e.defaults,ce.use=function(...e){return ae.use(...e),ce.defaults=ae.defaults,n(ce.defaults),ce},ce.walkTokens=function(e,t){return ae.walkTokens(e,t)},ce.parseInline=ae.parseInline,ce.Parser=ie,ce.parser=ie.parse,ce.Renderer=se,ce.TextRenderer=re,ce.Lexer=ne,ce.lexer=ne.lex,ce.Tokenizer=w,ce.Hooks=le,ce.parse=ce;const he=ce.options,pe=ce.setOptions,ue=ce.use,ke=ce.walkTokens,ge=ce.parseInline,fe=ce,de=ie.parse,xe=ne.lex;e.Hooks=le,e.Lexer=ne,e.Marked=oe,e.Parser=ie,e.Renderer=se,e.TextRenderer=re,e.Tokenizer=w,e.getDefaults=t,e.lexer=xe,e.marked=ce,e.options=he,e.parse=fe,e.parseInline=ge,e.parser=de,e.setOptions=pe,e.use=ue,e.walkTokens=ke}));
ComfyUI/custom_nodes/ComfyUI-KJNodes/kjweb_async/protovis.min.js ADDED
The diff for this file is too large to render. See raw diff
 
ComfyUI/custom_nodes/ComfyUI-KJNodes/kjweb_async/purify.min.js ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ /*! @license DOMPurify 3.0.11 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.0.11/LICENSE */
2
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).DOMPurify=t()}(this,(function(){"use strict";const{entries:e,setPrototypeOf:t,isFrozen:n,getPrototypeOf:o,getOwnPropertyDescriptor:r}=Object;let{freeze:i,seal:a,create:l}=Object,{apply:c,construct:s}="undefined"!=typeof Reflect&&Reflect;i||(i=function(e){return e}),a||(a=function(e){return e}),c||(c=function(e,t,n){return e.apply(t,n)}),s||(s=function(e,t){return new e(...t)});const u=b(Array.prototype.forEach),m=b(Array.prototype.pop),p=b(Array.prototype.push),f=b(String.prototype.toLowerCase),d=b(String.prototype.toString),h=b(String.prototype.match),g=b(String.prototype.replace),T=b(String.prototype.indexOf),y=b(String.prototype.trim),E=b(Object.prototype.hasOwnProperty),A=b(RegExp.prototype.test),_=(N=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return s(N,t)});var N;function b(e){return function(t){for(var n=arguments.length,o=new Array(n>1?n-1:0),r=1;r<n;r++)o[r-1]=arguments[r];return c(e,t,o)}}function S(e,o){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:f;t&&t(e,null);let i=o.length;for(;i--;){let t=o[i];if("string"==typeof t){const e=r(t);e!==t&&(n(o)||(o[i]=e),t=e)}e[t]=!0}return e}function R(e){for(let t=0;t<e.length;t++){E(e,t)||(e[t]=null)}return e}function w(t){const n=l(null);for(const[o,r]of e(t)){E(t,o)&&(Array.isArray(r)?n[o]=R(r):r&&"object"==typeof r&&r.constructor===Object?n[o]=w(r):n[o]=r)}return n}function L(e,t){for(;null!==e;){const n=r(e,t);if(n){if(n.get)return b(n.get);if("function"==typeof n.value)return b(n.value)}e=o(e)}return function(){return null}}const D=i(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),C=i(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),O=i(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),x=i(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),v=i(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),k=i(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),M=i(["#text"]),I=i(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),U=i(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),P=i(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),F=i(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),H=a(/\{\{[\w\W]*|[\w\W]*\}\}/gm),z=a(/<%[\w\W]*|[\w\W]*%>/gm),B=a(/\${[\w\W]*}/gm),W=a(/^data-[\-\w.\u00B7-\uFFFF]/),G=a(/^aria-[\-\w]+$/),Y=a(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),j=a(/^(?:\w+script|data):/i),X=a(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),q=a(/^html$/i),$=a(/^[a-z][.\w]*(-[.\w]+)+$/i);var K=Object.freeze({__proto__:null,MUSTACHE_EXPR:H,ERB_EXPR:z,TMPLIT_EXPR:B,DATA_ATTR:W,ARIA_ATTR:G,IS_ALLOWED_URI:Y,IS_SCRIPT_OR_DATA:j,ATTR_WHITESPACE:X,DOCTYPE_NAME:q,CUSTOM_ELEMENT:$});const V=function(){return"undefined"==typeof window?null:window},Z=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const o="data-tt-policy-suffix";t&&t.hasAttribute(o)&&(n=t.getAttribute(o));const r="dompurify"+(n?"#"+n:"");try{return e.createPolicy(r,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+r+" could not be created."),null}};var J=function t(){let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:V();const o=e=>t(e);if(o.version="3.0.11",o.removed=[],!n||!n.document||9!==n.document.nodeType)return o.isSupported=!1,o;let{document:r}=n;const a=r,c=a.currentScript,{DocumentFragment:s,HTMLTemplateElement:N,Node:b,Element:R,NodeFilter:H,NamedNodeMap:z=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:B,DOMParser:W,trustedTypes:G}=n,j=R.prototype,X=L(j,"cloneNode"),$=L(j,"nextSibling"),J=L(j,"childNodes"),Q=L(j,"parentNode");if("function"==typeof N){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let ee,te="";const{implementation:ne,createNodeIterator:oe,createDocumentFragment:re,getElementsByTagName:ie}=r,{importNode:ae}=a;let le={};o.isSupported="function"==typeof e&&"function"==typeof Q&&ne&&void 0!==ne.createHTMLDocument;const{MUSTACHE_EXPR:ce,ERB_EXPR:se,TMPLIT_EXPR:ue,DATA_ATTR:me,ARIA_ATTR:pe,IS_SCRIPT_OR_DATA:fe,ATTR_WHITESPACE:de,CUSTOM_ELEMENT:he}=K;let{IS_ALLOWED_URI:ge}=K,Te=null;const ye=S({},[...D,...C,...O,...v,...M]);let Ee=null;const Ae=S({},[...I,...U,...P,...F]);let _e=Object.seal(l(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Ne=null,be=null,Se=!0,Re=!0,we=!1,Le=!0,De=!1,Ce=!0,Oe=!1,xe=!1,ve=!1,ke=!1,Me=!1,Ie=!1,Ue=!0,Pe=!1;const Fe="user-content-";let He=!0,ze=!1,Be={},We=null;const Ge=S({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Ye=null;const je=S({},["audio","video","img","source","image","track"]);let Xe=null;const qe=S({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),$e="http://www.w3.org/1998/Math/MathML",Ke="http://www.w3.org/2000/svg",Ve="http://www.w3.org/1999/xhtml";let Ze=Ve,Je=!1,Qe=null;const et=S({},[$e,Ke,Ve],d);let tt=null;const nt=["application/xhtml+xml","text/html"],ot="text/html";let rt=null,it=null;const at=r.createElement("form"),lt=function(e){return e instanceof RegExp||e instanceof Function},ct=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!it||it!==e){if(e&&"object"==typeof e||(e={}),e=w(e),tt=-1===nt.indexOf(e.PARSER_MEDIA_TYPE)?ot:e.PARSER_MEDIA_TYPE,rt="application/xhtml+xml"===tt?d:f,Te=E(e,"ALLOWED_TAGS")?S({},e.ALLOWED_TAGS,rt):ye,Ee=E(e,"ALLOWED_ATTR")?S({},e.ALLOWED_ATTR,rt):Ae,Qe=E(e,"ALLOWED_NAMESPACES")?S({},e.ALLOWED_NAMESPACES,d):et,Xe=E(e,"ADD_URI_SAFE_ATTR")?S(w(qe),e.ADD_URI_SAFE_ATTR,rt):qe,Ye=E(e,"ADD_DATA_URI_TAGS")?S(w(je),e.ADD_DATA_URI_TAGS,rt):je,We=E(e,"FORBID_CONTENTS")?S({},e.FORBID_CONTENTS,rt):Ge,Ne=E(e,"FORBID_TAGS")?S({},e.FORBID_TAGS,rt):{},be=E(e,"FORBID_ATTR")?S({},e.FORBID_ATTR,rt):{},Be=!!E(e,"USE_PROFILES")&&e.USE_PROFILES,Se=!1!==e.ALLOW_ARIA_ATTR,Re=!1!==e.ALLOW_DATA_ATTR,we=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Le=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,De=e.SAFE_FOR_TEMPLATES||!1,Ce=!1!==e.SAFE_FOR_XML,Oe=e.WHOLE_DOCUMENT||!1,ke=e.RETURN_DOM||!1,Me=e.RETURN_DOM_FRAGMENT||!1,Ie=e.RETURN_TRUSTED_TYPE||!1,ve=e.FORCE_BODY||!1,Ue=!1!==e.SANITIZE_DOM,Pe=e.SANITIZE_NAMED_PROPS||!1,He=!1!==e.KEEP_CONTENT,ze=e.IN_PLACE||!1,ge=e.ALLOWED_URI_REGEXP||Y,Ze=e.NAMESPACE||Ve,_e=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&lt(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(_e.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&lt(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(_e.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(_e.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),De&&(Re=!1),Me&&(ke=!0),Be&&(Te=S({},M),Ee=[],!0===Be.html&&(S(Te,D),S(Ee,I)),!0===Be.svg&&(S(Te,C),S(Ee,U),S(Ee,F)),!0===Be.svgFilters&&(S(Te,O),S(Ee,U),S(Ee,F)),!0===Be.mathMl&&(S(Te,v),S(Ee,P),S(Ee,F))),e.ADD_TAGS&&(Te===ye&&(Te=w(Te)),S(Te,e.ADD_TAGS,rt)),e.ADD_ATTR&&(Ee===Ae&&(Ee=w(Ee)),S(Ee,e.ADD_ATTR,rt)),e.ADD_URI_SAFE_ATTR&&S(Xe,e.ADD_URI_SAFE_ATTR,rt),e.FORBID_CONTENTS&&(We===Ge&&(We=w(We)),S(We,e.FORBID_CONTENTS,rt)),He&&(Te["#text"]=!0),Oe&&S(Te,["html","head","body"]),Te.table&&(S(Te,["tbody"]),delete Ne.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw _('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw _('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');ee=e.TRUSTED_TYPES_POLICY,te=ee.createHTML("")}else void 0===ee&&(ee=Z(G,c)),null!==ee&&"string"==typeof te&&(te=ee.createHTML(""));i&&i(e),it=e}},st=S({},["mi","mo","mn","ms","mtext"]),ut=S({},["foreignobject","desc","title","annotation-xml"]),mt=S({},["title","style","font","a","script"]),pt=S({},[...C,...O,...x]),ft=S({},[...v,...k]),dt=function(e){let t=Q(e);t&&t.tagName||(t={namespaceURI:Ze,tagName:"template"});const n=f(e.tagName),o=f(t.tagName);return!!Qe[e.namespaceURI]&&(e.namespaceURI===Ke?t.namespaceURI===Ve?"svg"===n:t.namespaceURI===$e?"svg"===n&&("annotation-xml"===o||st[o]):Boolean(pt[n]):e.namespaceURI===$e?t.namespaceURI===Ve?"math"===n:t.namespaceURI===Ke?"math"===n&&ut[o]:Boolean(ft[n]):e.namespaceURI===Ve?!(t.namespaceURI===Ke&&!ut[o])&&(!(t.namespaceURI===$e&&!st[o])&&(!ft[n]&&(mt[n]||!pt[n]))):!("application/xhtml+xml"!==tt||!Qe[e.namespaceURI]))},ht=function(e){p(o.removed,{element:e});try{e.parentNode.removeChild(e)}catch(t){e.remove()}},gt=function(e,t){try{p(o.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){p(o.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e&&!Ee[e])if(ke||Me)try{ht(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Tt=function(e){let t=null,n=null;if(ve)e="<remove></remove>"+e;else{const t=h(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===tt&&Ze===Ve&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const o=ee?ee.createHTML(e):e;if(Ze===Ve)try{t=(new W).parseFromString(o,tt)}catch(e){}if(!t||!t.documentElement){t=ne.createDocument(Ze,"template",null);try{t.documentElement.innerHTML=Je?te:o}catch(e){}}const i=t.body||t.documentElement;return e&&n&&i.insertBefore(r.createTextNode(n),i.childNodes[0]||null),Ze===Ve?ie.call(t,Oe?"html":"body")[0]:Oe?t.documentElement:i},yt=function(e){return oe.call(e.ownerDocument||e,e,H.SHOW_ELEMENT|H.SHOW_COMMENT|H.SHOW_TEXT|H.SHOW_PROCESSING_INSTRUCTION|H.SHOW_CDATA_SECTION,null)},Et=function(e){return e instanceof B&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof z)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},At=function(e){return"function"==typeof b&&e instanceof b},_t=function(e,t,n){le[e]&&u(le[e],(e=>{e.call(o,t,n,it)}))},Nt=function(e){let t=null;if(_t("beforeSanitizeElements",e,null),Et(e))return ht(e),!0;const n=rt(e.nodeName);if(_t("uponSanitizeElement",e,{tagName:n,allowedTags:Te}),e.hasChildNodes()&&!At(e.firstElementChild)&&A(/<[/\w]/g,e.innerHTML)&&A(/<[/\w]/g,e.textContent))return ht(e),!0;if(7===e.nodeType)return ht(e),!0;if(Ce&&8===e.nodeType&&A(/<[/\w]/g,e.data))return ht(e),!0;if(!Te[n]||Ne[n]){if(!Ne[n]&&St(n)){if(_e.tagNameCheck instanceof RegExp&&A(_e.tagNameCheck,n))return!1;if(_e.tagNameCheck instanceof Function&&_e.tagNameCheck(n))return!1}if(He&&!We[n]){const t=Q(e)||e.parentNode,n=J(e)||e.childNodes;if(n&&t){for(let o=n.length-1;o>=0;--o)t.insertBefore(X(n[o],!0),$(e))}}return ht(e),!0}return e instanceof R&&!dt(e)?(ht(e),!0):"noscript"!==n&&"noembed"!==n&&"noframes"!==n||!A(/<\/no(script|embed|frames)/i,e.innerHTML)?(De&&3===e.nodeType&&(t=e.textContent,u([ce,se,ue],(e=>{t=g(t,e," ")})),e.textContent!==t&&(p(o.removed,{element:e.cloneNode()}),e.textContent=t)),_t("afterSanitizeElements",e,null),!1):(ht(e),!0)},bt=function(e,t,n){if(Ue&&("id"===t||"name"===t)&&(n in r||n in at))return!1;if(Re&&!be[t]&&A(me,t));else if(Se&&A(pe,t));else if(!Ee[t]||be[t]){if(!(St(e)&&(_e.tagNameCheck instanceof RegExp&&A(_e.tagNameCheck,e)||_e.tagNameCheck instanceof Function&&_e.tagNameCheck(e))&&(_e.attributeNameCheck instanceof RegExp&&A(_e.attributeNameCheck,t)||_e.attributeNameCheck instanceof Function&&_e.attributeNameCheck(t))||"is"===t&&_e.allowCustomizedBuiltInElements&&(_e.tagNameCheck instanceof RegExp&&A(_e.tagNameCheck,n)||_e.tagNameCheck instanceof Function&&_e.tagNameCheck(n))))return!1}else if(Xe[t]);else if(A(ge,g(n,de,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==T(n,"data:")||!Ye[e]){if(we&&!A(fe,g(n,de,"")));else if(n)return!1}else;return!0},St=function(e){return"annotation-xml"!==e&&h(e,he)},Rt=function(e){_t("beforeSanitizeAttributes",e,null);const{attributes:t}=e;if(!t)return;const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Ee};let r=t.length;for(;r--;){const i=t[r],{name:a,namespaceURI:l,value:c}=i,s=rt(a);let p="value"===a?c:y(c);if(n.attrName=s,n.attrValue=p,n.keepAttr=!0,n.forceKeepAttr=void 0,_t("uponSanitizeAttribute",e,n),p=n.attrValue,n.forceKeepAttr)continue;if(gt(a,e),!n.keepAttr)continue;if(!Le&&A(/\/>/i,p)){gt(a,e);continue}De&&u([ce,se,ue],(e=>{p=g(p,e," ")}));const f=rt(e.nodeName);if(bt(f,s,p)){if(!Pe||"id"!==s&&"name"!==s||(gt(a,e),p=Fe+p),ee&&"object"==typeof G&&"function"==typeof G.getAttributeType)if(l);else switch(G.getAttributeType(f,s)){case"TrustedHTML":p=ee.createHTML(p);break;case"TrustedScriptURL":p=ee.createScriptURL(p)}try{l?e.setAttributeNS(l,a,p):e.setAttribute(a,p),m(o.removed)}catch(e){}}}_t("afterSanitizeAttributes",e,null)},wt=function e(t){let n=null;const o=yt(t);for(_t("beforeSanitizeShadowDOM",t,null);n=o.nextNode();)_t("uponSanitizeShadowNode",n,null),Nt(n)||(n.content instanceof s&&e(n.content),Rt(n));_t("afterSanitizeShadowDOM",t,null)};return o.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=null,r=null,i=null,l=null;if(Je=!e,Je&&(e="\x3c!--\x3e"),"string"!=typeof e&&!At(e)){if("function"!=typeof e.toString)throw _("toString is not a function");if("string"!=typeof(e=e.toString()))throw _("dirty is not a string, aborting")}if(!o.isSupported)return e;if(xe||ct(t),o.removed=[],"string"==typeof e&&(ze=!1),ze){if(e.nodeName){const t=rt(e.nodeName);if(!Te[t]||Ne[t])throw _("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof b)n=Tt("\x3c!----\x3e"),r=n.ownerDocument.importNode(e,!0),1===r.nodeType&&"BODY"===r.nodeName||"HTML"===r.nodeName?n=r:n.appendChild(r);else{if(!ke&&!De&&!Oe&&-1===e.indexOf("<"))return ee&&Ie?ee.createHTML(e):e;if(n=Tt(e),!n)return ke?null:Ie?te:""}n&&ve&&ht(n.firstChild);const c=yt(ze?e:n);for(;i=c.nextNode();)Nt(i)||(i.content instanceof s&&wt(i.content),Rt(i));if(ze)return e;if(ke){if(Me)for(l=re.call(n.ownerDocument);n.firstChild;)l.appendChild(n.firstChild);else l=n;return(Ee.shadowroot||Ee.shadowrootmode)&&(l=ae.call(a,l,!0)),l}let m=Oe?n.outerHTML:n.innerHTML;return Oe&&Te["!doctype"]&&n.ownerDocument&&n.ownerDocument.doctype&&n.ownerDocument.doctype.name&&A(q,n.ownerDocument.doctype.name)&&(m="<!DOCTYPE "+n.ownerDocument.doctype.name+">\n"+m),De&&u([ce,se,ue],(e=>{m=g(m,e," ")})),ee&&Ie?ee.createHTML(m):m},o.setConfig=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};ct(e),xe=!0},o.clearConfig=function(){it=null,xe=!1},o.isValidAttribute=function(e,t,n){it||ct({});const o=rt(e),r=rt(t);return bt(o,r,n)},o.addHook=function(e,t){"function"==typeof t&&(le[e]=le[e]||[],p(le[e],t))},o.removeHook=function(e){if(le[e])return m(le[e])},o.removeHooks=function(e){le[e]&&(le[e]=[])},o.removeAllHooks=function(){le={}},o}();return J}));
3
+ //# sourceMappingURL=purify.min.js.map
ComfyUI/custom_nodes/ComfyUI-KJNodes/kjweb_async/svg-path-properties.min.js ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ // http://geoexamples.com/path-properties/ v1.2.0 Copyright 2023 Roger Veciana i Rovira
2
+ !function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((t="undefined"!=typeof globalThis?globalThis:t||self).svgPathProperties={})}(this,(function(t){"use strict";function n(t,n){for(var e=0;e<n.length;e++){var i=n[e];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,s(i.key),i)}}function e(t,e,i){return e&&n(t.prototype,e),i&&n(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t}function i(t,n,e){return(n=s(n))in t?Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[n]=e,t}function r(t){return function(t){if(Array.isArray(t))return h(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,n){if(!t)return;if("string"==typeof t)return h(t,n);var e=Object.prototype.toString.call(t).slice(8,-1);"Object"===e&&t.constructor&&(e=t.constructor.name);if("Map"===e||"Set"===e)return Array.from(t);if("Arguments"===e||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e))return h(t,n)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function h(t,n){(null==n||n>t.length)&&(n=t.length);for(var e=0,i=new Array(n);e<n;e++)i[e]=t[e];return i}function s(t){var n=function(t,n){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,n||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===n?String:Number)(t)}(t,"string");return"symbol"==typeof n?n:String(n)}var a={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},o=/([astvzqmhlc])([^astvzqmhlc]*)/gi,g=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi,u=function(t){var n=t.match(g);return n?n.map(Number):[]},l=e((function(t,n,e,r){var h=this;i(this,"x0",void 0),i(this,"x1",void 0),i(this,"y0",void 0),i(this,"y1",void 0),i(this,"getTotalLength",(function(){return Math.sqrt(Math.pow(h.x0-h.x1,2)+Math.pow(h.y0-h.y1,2))})),i(this,"getPointAtLength",(function(t){var n=t/Math.sqrt(Math.pow(h.x0-h.x1,2)+Math.pow(h.y0-h.y1,2));n=Number.isNaN(n)?1:n;var e=(h.x1-h.x0)*n,i=(h.y1-h.y0)*n;return{x:h.x0+e,y:h.y0+i}})),i(this,"getTangentAtLength",(function(t){var n=Math.sqrt((h.x1-h.x0)*(h.x1-h.x0)+(h.y1-h.y0)*(h.y1-h.y0));return{x:(h.x1-h.x0)/n,y:(h.y1-h.y0)/n}})),i(this,"getPropertiesAtLength",(function(t){var n=h.getPointAtLength(t),e=h.getTangentAtLength(t);return{x:n.x,y:n.y,tangentX:e.x,tangentY:e.y}})),this.x0=t,this.x1=n,this.y0=e,this.y1=r})),c=e((function(t,n,e,r,h,s,a,o,g){var u=this;i(this,"x0",void 0),i(this,"y0",void 0),i(this,"rx",void 0),i(this,"ry",void 0),i(this,"xAxisRotate",void 0),i(this,"LargeArcFlag",void 0),i(this,"SweepFlag",void 0),i(this,"x1",void 0),i(this,"y1",void 0),i(this,"length",void 0),i(this,"getTotalLength",(function(){return u.length})),i(this,"getPointAtLength",(function(t){t<0?t=0:t>u.length&&(t=u.length);var n=f({x:u.x0,y:u.y0},u.rx,u.ry,u.xAxisRotate,u.LargeArcFlag,u.SweepFlag,{x:u.x1,y:u.y1},t/u.length);return{x:n.x,y:n.y}})),i(this,"getTangentAtLength",(function(t){t<0?t=0:t>u.length&&(t=u.length);var n,e=.05,i=u.getPointAtLength(t);t<0?t=0:t>u.length&&(t=u.length);var r=(n=t<u.length-e?u.getPointAtLength(t+e):u.getPointAtLength(t-e)).x-i.x,h=n.y-i.y,s=Math.sqrt(r*r+h*h);return t<u.length-e?{x:-r/s,y:-h/s}:{x:r/s,y:h/s}})),i(this,"getPropertiesAtLength",(function(t){var n=u.getTangentAtLength(t),e=u.getPointAtLength(t);return{x:e.x,y:e.y,tangentX:n.x,tangentY:n.y}})),this.x0=t,this.y0=n,this.rx=e,this.ry=r,this.xAxisRotate=h,this.LargeArcFlag=s,this.SweepFlag=a,this.x1=o,this.y1=g;var l=y(300,(function(i){return f({x:t,y:n},e,r,h,s,a,{x:o,y:g},i)}));this.length=l.arcLength})),f=function(t,n,e,i,r,h,s,a){n=Math.abs(n),e=Math.abs(e),i=p(i,360);var o=x(i);if(t.x===s.x&&t.y===s.y)return{x:t.x,y:t.y,ellipticalArcAngle:0};if(0===n||0===e)return{x:0,y:0,ellipticalArcAngle:0};var g=(t.x-s.x)/2,u=(t.y-s.y)/2,l={x:Math.cos(o)*g+Math.sin(o)*u,y:-Math.sin(o)*g+Math.cos(o)*u},c=Math.pow(l.x,2)/Math.pow(n,2)+Math.pow(l.y,2)/Math.pow(e,2);c>1&&(n=Math.sqrt(c)*n,e=Math.sqrt(c)*e);var f=(Math.pow(n,2)*Math.pow(e,2)-Math.pow(n,2)*Math.pow(l.y,2)-Math.pow(e,2)*Math.pow(l.x,2))/(Math.pow(n,2)*Math.pow(l.y,2)+Math.pow(e,2)*Math.pow(l.x,2));f=f<0?0:f;var y=(r!==h?1:-1)*Math.sqrt(f),v=y*(n*l.y/e),M=y*(-e*l.x/n),L={x:Math.cos(o)*v-Math.sin(o)*M+(t.x+s.x)/2,y:Math.sin(o)*v+Math.cos(o)*M+(t.y+s.y)/2},d={x:(l.x-v)/n,y:(l.y-M)/e},A=w({x:1,y:0},d),b=w(d,{x:(-l.x-v)/n,y:(-l.y-M)/e});!h&&b>0?b-=2*Math.PI:h&&b<0&&(b+=2*Math.PI);var P=A+(b%=2*Math.PI)*a,m=n*Math.cos(P),T=e*Math.sin(P);return{x:Math.cos(o)*m-Math.sin(o)*T+L.x,y:Math.sin(o)*m+Math.cos(o)*T+L.y,ellipticalArcStartAngle:A,ellipticalArcEndAngle:A+b,ellipticalArcAngle:P,ellipticalArcCenter:L,resultantRx:n,resultantRy:e}},y=function(t,n){t=t||500;for(var e,i=0,r=[],h=[],s=n(0),a=0;a<t;a++){var o=M(a*(1/t),0,1);e=n(o),i+=v(s,e),h.push([s,e]),r.push({t:o,arcLength:i}),s=e}return e=n(1),h.push([s,e]),i+=v(s,e),r.push({t:1,arcLength:i}),{arcLength:i,arcLengthMap:r,approximationLines:h}},p=function(t,n){return(t%n+n)%n},x=function(t){return t*(Math.PI/180)},v=function(t,n){return Math.sqrt(Math.pow(n.x-t.x,2)+Math.pow(n.y-t.y,2))},M=function(t,n,e){return Math.min(Math.max(t,n),e)},w=function(t,n){var e=t.x*n.x+t.y*n.y,i=Math.sqrt((Math.pow(t.x,2)+Math.pow(t.y,2))*(Math.pow(n.x,2)+Math.pow(n.y,2)));return(t.x*n.y-t.y*n.x<0?-1:1)*Math.acos(e/i)},L=[[],[],[-.5773502691896257,.5773502691896257],[0,-.7745966692414834,.7745966692414834],[-.33998104358485626,.33998104358485626,-.8611363115940526,.8611363115940526],[0,-.5384693101056831,.5384693101056831,-.906179845938664,.906179845938664],[.6612093864662645,-.6612093864662645,-.2386191860831969,.2386191860831969,-.932469514203152,.932469514203152],[0,.4058451513773972,-.4058451513773972,-.7415311855993945,.7415311855993945,-.9491079123427585,.9491079123427585],[-.1834346424956498,.1834346424956498,-.525532409916329,.525532409916329,-.7966664774136267,.7966664774136267,-.9602898564975363,.9602898564975363],[0,-.8360311073266358,.8360311073266358,-.9681602395076261,.9681602395076261,-.3242534234038089,.3242534234038089,-.6133714327005904,.6133714327005904],[-.14887433898163122,.14887433898163122,-.4333953941292472,.4333953941292472,-.6794095682990244,.6794095682990244,-.8650633666889845,.8650633666889845,-.9739065285171717,.9739065285171717],[0,-.26954315595234496,.26954315595234496,-.5190961292068118,.5190961292068118,-.7301520055740494,.7301520055740494,-.8870625997680953,.8870625997680953,-.978228658146057,.978228658146057],[-.1252334085114689,.1252334085114689,-.3678314989981802,.3678314989981802,-.5873179542866175,.5873179542866175,-.7699026741943047,.7699026741943047,-.9041172563704749,.9041172563704749,-.9815606342467192,.9815606342467192],[0,-.2304583159551348,.2304583159551348,-.44849275103644687,.44849275103644687,-.6423493394403402,.6423493394403402,-.8015780907333099,.8015780907333099,-.9175983992229779,.9175983992229779,-.9841830547185881,.9841830547185881],[-.10805494870734367,.10805494870734367,-.31911236892788974,.31911236892788974,-.5152486363581541,.5152486363581541,-.6872929048116855,.6872929048116855,-.827201315069765,.827201315069765,-.9284348836635735,.9284348836635735,-.9862838086968123,.9862838086968123],[0,-.20119409399743451,.20119409399743451,-.3941513470775634,.3941513470775634,-.5709721726085388,.5709721726085388,-.7244177313601701,.7244177313601701,-.8482065834104272,.8482065834104272,-.937273392400706,.937273392400706,-.9879925180204854,.9879925180204854],[-.09501250983763744,.09501250983763744,-.2816035507792589,.2816035507792589,-.45801677765722737,.45801677765722737,-.6178762444026438,.6178762444026438,-.755404408355003,.755404408355003,-.8656312023878318,.8656312023878318,-.9445750230732326,.9445750230732326,-.9894009349916499,.9894009349916499],[0,-.17848418149584785,.17848418149584785,-.3512317634538763,.3512317634538763,-.5126905370864769,.5126905370864769,-.6576711592166907,.6576711592166907,-.7815140038968014,.7815140038968014,-.8802391537269859,.8802391537269859,-.9506755217687678,.9506755217687678,-.9905754753144174,.9905754753144174],[-.0847750130417353,.0847750130417353,-.2518862256915055,.2518862256915055,-.41175116146284263,.41175116146284263,-.5597708310739475,.5597708310739475,-.6916870430603532,.6916870430603532,-.8037049589725231,.8037049589725231,-.8926024664975557,.8926024664975557,-.9558239495713977,.9558239495713977,-.9915651684209309,.9915651684209309],[0,-.16035864564022537,.16035864564022537,-.31656409996362983,.31656409996362983,-.46457074137596094,.46457074137596094,-.600545304661681,.600545304661681,-.7209661773352294,.7209661773352294,-.8227146565371428,.8227146565371428,-.9031559036148179,.9031559036148179,-.96020815213483,.96020815213483,-.9924068438435844,.9924068438435844],[-.07652652113349734,.07652652113349734,-.22778585114164507,.22778585114164507,-.37370608871541955,.37370608871541955,-.5108670019508271,.5108670019508271,-.636053680726515,.636053680726515,-.7463319064601508,.7463319064601508,-.8391169718222188,.8391169718222188,-.912234428251326,.912234428251326,-.9639719272779138,.9639719272779138,-.9931285991850949,.9931285991850949],[0,-.1455618541608951,.1455618541608951,-.2880213168024011,.2880213168024011,-.4243421202074388,.4243421202074388,-.5516188358872198,.5516188358872198,-.6671388041974123,.6671388041974123,-.7684399634756779,.7684399634756779,-.8533633645833173,.8533633645833173,-.9200993341504008,.9200993341504008,-.9672268385663063,.9672268385663063,-.9937521706203895,.9937521706203895],[-.06973927331972223,.06973927331972223,-.20786042668822127,.20786042668822127,-.34193582089208424,.34193582089208424,-.469355837986757,.469355837986757,-.5876404035069116,.5876404035069116,-.6944872631866827,.6944872631866827,-.7878168059792081,.7878168059792081,-.8658125777203002,.8658125777203002,-.926956772187174,.926956772187174,-.9700604978354287,.9700604978354287,-.9942945854823992,.9942945854823992],[0,-.1332568242984661,.1332568242984661,-.26413568097034495,.26413568097034495,-.3903010380302908,.3903010380302908,-.5095014778460075,.5095014778460075,-.6196098757636461,.6196098757636461,-.7186613631319502,.7186613631319502,-.8048884016188399,.8048884016188399,-.8767523582704416,.8767523582704416,-.9329710868260161,.9329710868260161,-.9725424712181152,.9725424712181152,-.9947693349975522,.9947693349975522],[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213]],d=[[],[],[1,1],[.8888888888888888,.5555555555555556,.5555555555555556],[.6521451548625461,.6521451548625461,.34785484513745385,.34785484513745385],[.5688888888888889,.47862867049936647,.47862867049936647,.23692688505618908,.23692688505618908],[.3607615730481386,.3607615730481386,.46791393457269104,.46791393457269104,.17132449237917036,.17132449237917036],[.4179591836734694,.3818300505051189,.3818300505051189,.27970539148927664,.27970539148927664,.1294849661688697,.1294849661688697],[.362683783378362,.362683783378362,.31370664587788727,.31370664587788727,.22238103445337448,.22238103445337448,.10122853629037626,.10122853629037626],[.3302393550012598,.1806481606948574,.1806481606948574,.08127438836157441,.08127438836157441,.31234707704000286,.31234707704000286,.26061069640293544,.26061069640293544],[.29552422471475287,.29552422471475287,.26926671930999635,.26926671930999635,.21908636251598204,.21908636251598204,.1494513491505806,.1494513491505806,.06667134430868814,.06667134430868814],[.2729250867779006,.26280454451024665,.26280454451024665,.23319376459199048,.23319376459199048,.18629021092773426,.18629021092773426,.1255803694649046,.1255803694649046,.05566856711617366,.05566856711617366],[.24914704581340277,.24914704581340277,.2334925365383548,.2334925365383548,.20316742672306592,.20316742672306592,.16007832854334622,.16007832854334622,.10693932599531843,.10693932599531843,.04717533638651183,.04717533638651183],[.2325515532308739,.22628318026289723,.22628318026289723,.2078160475368885,.2078160475368885,.17814598076194574,.17814598076194574,.13887351021978725,.13887351021978725,.09212149983772845,.09212149983772845,.04048400476531588,.04048400476531588],[.2152638534631578,.2152638534631578,.2051984637212956,.2051984637212956,.18553839747793782,.18553839747793782,.15720316715819355,.15720316715819355,.12151857068790319,.12151857068790319,.08015808715976021,.08015808715976021,.03511946033175186,.03511946033175186],[.2025782419255613,.19843148532711158,.19843148532711158,.1861610000155622,.1861610000155622,.16626920581699392,.16626920581699392,.13957067792615432,.13957067792615432,.10715922046717194,.10715922046717194,.07036604748810812,.07036604748810812,.03075324199611727,.03075324199611727],[.1894506104550685,.1894506104550685,.18260341504492358,.18260341504492358,.16915651939500254,.16915651939500254,.14959598881657674,.14959598881657674,.12462897125553388,.12462897125553388,.09515851168249279,.09515851168249279,.062253523938647894,.062253523938647894,.027152459411754096,.027152459411754096],[.17944647035620653,.17656270536699264,.17656270536699264,.16800410215645004,.16800410215645004,.15404576107681028,.15404576107681028,.13513636846852548,.13513636846852548,.11188384719340397,.11188384719340397,.08503614831717918,.08503614831717918,.0554595293739872,.0554595293739872,.02414830286854793,.02414830286854793],[.1691423829631436,.1691423829631436,.16427648374583273,.16427648374583273,.15468467512626524,.15468467512626524,.14064291467065065,.14064291467065065,.12255520671147846,.12255520671147846,.10094204410628717,.10094204410628717,.07642573025488905,.07642573025488905,.0497145488949698,.0497145488949698,.02161601352648331,.02161601352648331],[.1610544498487837,.15896884339395434,.15896884339395434,.15276604206585967,.15276604206585967,.1426067021736066,.1426067021736066,.12875396253933621,.12875396253933621,.11156664554733399,.11156664554733399,.09149002162245,.09149002162245,.06904454273764123,.06904454273764123,.0448142267656996,.0448142267656996,.019461788229726478,.019461788229726478],[.15275338713072584,.15275338713072584,.14917298647260374,.14917298647260374,.14209610931838204,.14209610931838204,.13168863844917664,.13168863844917664,.11819453196151841,.11819453196151841,.10193011981724044,.10193011981724044,.08327674157670475,.08327674157670475,.06267204833410907,.06267204833410907,.04060142980038694,.04060142980038694,.017614007139152118,.017614007139152118],[.14608113364969041,.14452440398997005,.14452440398997005,.13988739479107315,.13988739479107315,.13226893863333747,.13226893863333747,.12183141605372853,.12183141605372853,.10879729916714838,.10879729916714838,.09344442345603386,.09344442345603386,.0761001136283793,.0761001136283793,.057134425426857205,.057134425426857205,.036953789770852494,.036953789770852494,.016017228257774335,.016017228257774335],[.13925187285563198,.13925187285563198,.13654149834601517,.13654149834601517,.13117350478706238,.13117350478706238,.12325237681051242,.12325237681051242,.11293229608053922,.11293229608053922,.10041414444288096,.10041414444288096,.08594160621706773,.08594160621706773,.06979646842452049,.06979646842452049,.052293335152683286,.052293335152683286,.03377490158481415,.03377490158481415,.0146279952982722,.0146279952982722],[.13365457218610619,.1324620394046966,.1324620394046966,.12890572218808216,.12890572218808216,.12304908430672953,.12304908430672953,.11499664022241136,.11499664022241136,.10489209146454141,.10489209146454141,.09291576606003515,.09291576606003515,.07928141177671895,.07928141177671895,.06423242140852585,.06423242140852585,.04803767173108467,.04803767173108467,.030988005856979445,.030988005856979445,.013411859487141771,.013411859487141771],[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872]],A=[[1],[1,1],[1,2,1],[1,3,3,1]],b=function(t,n,e){return{x:(1-e)*(1-e)*(1-e)*t[0]+3*(1-e)*(1-e)*e*t[1]+3*(1-e)*e*e*t[2]+e*e*e*t[3],y:(1-e)*(1-e)*(1-e)*n[0]+3*(1-e)*(1-e)*e*n[1]+3*(1-e)*e*e*n[2]+e*e*e*n[3]}},P=function(t,n,e){return T([3*(t[1]-t[0]),3*(t[2]-t[1]),3*(t[3]-t[2])],[3*(n[1]-n[0]),3*(n[2]-n[1]),3*(n[3]-n[2])],e)},m=function(t,n,e){var i,r,h;i=e/2,r=0;for(var s=0;s<20;s++)h=i*L[20][s]+i,r+=d[20][s]*S(t,n,h);return i*r},T=function(t,n,e){return{x:(1-e)*(1-e)*t[0]+2*(1-e)*e*t[1]+e*e*t[2],y:(1-e)*(1-e)*n[0]+2*(1-e)*e*n[1]+e*e*n[2]}},q=function(t,n,e){void 0===e&&(e=1);var i=t[0]-2*t[1]+t[2],r=n[0]-2*n[1]+n[2],h=2*t[1]-2*t[0],s=2*n[1]-2*n[0],a=4*(i*i+r*r),o=4*(i*h+r*s),g=h*h+s*s;if(0===a)return e*Math.sqrt(Math.pow(t[2]-t[0],2)+Math.pow(n[2]-n[0],2));var u=o/(2*a),l=e+u,c=g/a-u*u,f=l*l+c>0?Math.sqrt(l*l+c):0,y=u*u+c>0?Math.sqrt(u*u+c):0,p=u+Math.sqrt(u*u+c)!==0&&(l+f)/(u+y)!=0?c*Math.log(Math.abs((l+f)/(u+y))):0;return Math.sqrt(a)/2*(l*f-u*y+p)},_=function(t,n,e){return{x:2*(1-e)*(t[1]-t[0])+2*e*(t[2]-t[1]),y:2*(1-e)*(n[1]-n[0])+2*e*(n[2]-n[1])}};function S(t,n,e){var i=N(1,e,t),r=N(1,e,n),h=i*i+r*r;return Math.sqrt(h)}var N=function t(n,e,i){var r,h,s=i.length-1;if(0===s)return 0;if(0===n){h=0;for(var a=0;a<=s;a++)h+=A[s][a]*Math.pow(1-e,s-a)*Math.pow(e,a)*i[a];return h}r=new Array(s);for(var o=0;o<s;o++)r[o]=s*(i[o+1]-i[o]);return t(n-1,e,r)},C=function(t,n,e){for(var i=1,r=t/n,h=(t-e(r))/n,s=0;i>.001;){var a=e(r+h),o=Math.abs(t-a)/n;if(o<i)i=o,r+=h;else{var g=e(r-h),u=Math.abs(t-g)/n;u<i?(i=u,r-=h):h/=2}if(++s>500)break}return r},j=e((function(t,n,e,r,h,s,a,o){var g=this;i(this,"a",void 0),i(this,"b",void 0),i(this,"c",void 0),i(this,"d",void 0),i(this,"length",void 0),i(this,"getArcLength",void 0),i(this,"getPoint",void 0),i(this,"getDerivative",void 0),i(this,"getTotalLength",(function(){return g.length})),i(this,"getPointAtLength",(function(t){var n=[g.a.x,g.b.x,g.c.x,g.d.x],e=[g.a.y,g.b.y,g.c.y,g.d.y],i=C(t,g.length,(function(t){return g.getArcLength(n,e,t)}));return g.getPoint(n,e,i)})),i(this,"getTangentAtLength",(function(t){var n=[g.a.x,g.b.x,g.c.x,g.d.x],e=[g.a.y,g.b.y,g.c.y,g.d.y],i=C(t,g.length,(function(t){return g.getArcLength(n,e,t)})),r=g.getDerivative(n,e,i),h=Math.sqrt(r.x*r.x+r.y*r.y);return h>0?{x:r.x/h,y:r.y/h}:{x:0,y:0}})),i(this,"getPropertiesAtLength",(function(t){var n,e=[g.a.x,g.b.x,g.c.x,g.d.x],i=[g.a.y,g.b.y,g.c.y,g.d.y],r=C(t,g.length,(function(t){return g.getArcLength(e,i,t)})),h=g.getDerivative(e,i,r),s=Math.sqrt(h.x*h.x+h.y*h.y);n=s>0?{x:h.x/s,y:h.y/s}:{x:0,y:0};var a=g.getPoint(e,i,r);return{x:a.x,y:a.y,tangentX:n.x,tangentY:n.y}})),i(this,"getC",(function(){return g.c})),i(this,"getD",(function(){return g.d})),this.a={x:t,y:n},this.b={x:e,y:r},this.c={x:h,y:s},void 0!==a&&void 0!==o?(this.getArcLength=m,this.getPoint=b,this.getDerivative=P,this.d={x:a,y:o}):(this.getArcLength=q,this.getPoint=T,this.getDerivative=_,this.d={x:0,y:0}),this.length=this.getArcLength([this.a.x,this.b.x,this.c.x,this.d.x],[this.a.y,this.b.y,this.c.y,this.d.y],1)})),O=e((function(t){var n=this;i(this,"length",0),i(this,"partial_lengths",[]),i(this,"functions",[]),i(this,"initial_point",null),i(this,"getPartAtLength",(function(t){t<0?t=0:t>n.length&&(t=n.length);for(var e=n.partial_lengths.length-1;n.partial_lengths[e]>=t&&e>0;)e--;return e++,{fraction:t-n.partial_lengths[e-1],i:e}})),i(this,"getTotalLength",(function(){return n.length})),i(this,"getPointAtLength",(function(t){var e=n.getPartAtLength(t),i=n.functions[e.i];if(i)return i.getPointAtLength(e.fraction);if(n.initial_point)return n.initial_point;throw new Error("Wrong function at this part.")})),i(this,"getTangentAtLength",(function(t){var e=n.getPartAtLength(t),i=n.functions[e.i];if(i)return i.getTangentAtLength(e.fraction);if(n.initial_point)return{x:0,y:0};throw new Error("Wrong function at this part.")})),i(this,"getPropertiesAtLength",(function(t){var e=n.getPartAtLength(t),i=n.functions[e.i];if(i)return i.getPropertiesAtLength(e.fraction);if(n.initial_point)return{x:n.initial_point.x,y:n.initial_point.y,tangentX:0,tangentY:0};throw new Error("Wrong function at this part.")})),i(this,"getParts",(function(){for(var t=[],e=0;e<n.functions.length;e++)if(null!==n.functions[e]){n.functions[e]=n.functions[e];var i={start:n.functions[e].getPointAtLength(0),end:n.functions[e].getPointAtLength(n.partial_lengths[e]-n.partial_lengths[e-1]),length:n.partial_lengths[e]-n.partial_lengths[e-1],getPointAtLength:n.functions[e].getPointAtLength,getTangentAtLength:n.functions[e].getTangentAtLength,getPropertiesAtLength:n.functions[e].getPropertiesAtLength};t.push(i)}return t}));for(var e,h=Array.isArray(t)?t:function(t){var n=(t&&t.length>0?t:"M0,0").match(o);if(!n)throw new Error("No path elements found in string ".concat(t));return n.reduce((function(t,n){var e=n.charAt(0),i=e.toLowerCase(),h=u(n.substring(1));if("m"===i&&h.length>2&&(t.push([e].concat(r(h.splice(0,2)))),i="l",e="m"===e?"l":"L"),"a"===i.toLowerCase()&&(5===h.length||6===h.length)){var s=n.substring(1).trim().split(" ");h=[Number(s[0]),Number(s[1]),Number(s[2]),Number(s[3].charAt(0)),Number(s[3].charAt(1)),Number(s[3].substring(2)),Number(s[4])]}for(;h.length>=0;){if(h.length===a[i]){t.push([e].concat(r(h.splice(0,a[i]))));break}if(h.length<a[i])throw new Error('Malformed path data: "'.concat(e,'" must have ').concat(a[i]," elements and has ").concat(h.length,": ").concat(n));t.push([e].concat(r(h.splice(0,a[i]))))}return t}),[])}(t),s=[0,0],g=[0,0],f=[0,0],y=0;y<h.length;y++){if("M"===h[y][0])f=[(s=[h[y][1],h[y][2]])[0],s[1]],this.functions.push(null),0===y&&(this.initial_point={x:h[y][1],y:h[y][2]});else if("m"===h[y][0])f=[(s=[h[y][1]+s[0],h[y][2]+s[1]])[0],s[1]],this.functions.push(null);else if("L"===h[y][0])this.length+=Math.sqrt(Math.pow(s[0]-h[y][1],2)+Math.pow(s[1]-h[y][2],2)),this.functions.push(new l(s[0],h[y][1],s[1],h[y][2])),s=[h[y][1],h[y][2]];else if("l"===h[y][0])this.length+=Math.sqrt(Math.pow(h[y][1],2)+Math.pow(h[y][2],2)),this.functions.push(new l(s[0],h[y][1]+s[0],s[1],h[y][2]+s[1])),s=[h[y][1]+s[0],h[y][2]+s[1]];else if("H"===h[y][0])this.length+=Math.abs(s[0]-h[y][1]),this.functions.push(new l(s[0],h[y][1],s[1],s[1])),s[0]=h[y][1];else if("h"===h[y][0])this.length+=Math.abs(h[y][1]),this.functions.push(new l(s[0],s[0]+h[y][1],s[1],s[1])),s[0]=h[y][1]+s[0];else if("V"===h[y][0])this.length+=Math.abs(s[1]-h[y][1]),this.functions.push(new l(s[0],s[0],s[1],h[y][1])),s[1]=h[y][1];else if("v"===h[y][0])this.length+=Math.abs(h[y][1]),this.functions.push(new l(s[0],s[0],s[1],s[1]+h[y][1])),s[1]=h[y][1]+s[1];else if("z"===h[y][0]||"Z"===h[y][0])this.length+=Math.sqrt(Math.pow(f[0]-s[0],2)+Math.pow(f[1]-s[1],2)),this.functions.push(new l(s[0],f[0],s[1],f[1])),s=[f[0],f[1]];else if("C"===h[y][0])e=new j(s[0],s[1],h[y][1],h[y][2],h[y][3],h[y][4],h[y][5],h[y][6]),this.length+=e.getTotalLength(),s=[h[y][5],h[y][6]],this.functions.push(e);else if("c"===h[y][0])(e=new j(s[0],s[1],s[0]+h[y][1],s[1]+h[y][2],s[0]+h[y][3],s[1]+h[y][4],s[0]+h[y][5],s[1]+h[y][6])).getTotalLength()>0?(this.length+=e.getTotalLength(),this.functions.push(e),s=[h[y][5]+s[0],h[y][6]+s[1]]):this.functions.push(new l(s[0],s[0],s[1],s[1]));else if("S"===h[y][0]){if(y>0&&["C","c","S","s"].indexOf(h[y-1][0])>-1){if(e){var p=e.getC();e=new j(s[0],s[1],2*s[0]-p.x,2*s[1]-p.y,h[y][1],h[y][2],h[y][3],h[y][4])}}else e=new j(s[0],s[1],s[0],s[1],h[y][1],h[y][2],h[y][3],h[y][4]);e&&(this.length+=e.getTotalLength(),s=[h[y][3],h[y][4]],this.functions.push(e))}else if("s"===h[y][0]){if(y>0&&["C","c","S","s"].indexOf(h[y-1][0])>-1){if(e){var x=e.getC(),v=e.getD();e=new j(s[0],s[1],s[0]+v.x-x.x,s[1]+v.y-x.y,s[0]+h[y][1],s[1]+h[y][2],s[0]+h[y][3],s[1]+h[y][4])}}else e=new j(s[0],s[1],s[0],s[1],s[0]+h[y][1],s[1]+h[y][2],s[0]+h[y][3],s[1]+h[y][4]);e&&(this.length+=e.getTotalLength(),s=[h[y][3]+s[0],h[y][4]+s[1]],this.functions.push(e))}else if("Q"===h[y][0]){if(s[0]==h[y][1]&&s[1]==h[y][2]){var M=new l(h[y][1],h[y][3],h[y][2],h[y][4]);this.length+=M.getTotalLength(),this.functions.push(M)}else e=new j(s[0],s[1],h[y][1],h[y][2],h[y][3],h[y][4],void 0,void 0),this.length+=e.getTotalLength(),this.functions.push(e);s=[h[y][3],h[y][4]],g=[h[y][1],h[y][2]]}else if("q"===h[y][0]){if(0!=h[y][1]||0!=h[y][2])e=new j(s[0],s[1],s[0]+h[y][1],s[1]+h[y][2],s[0]+h[y][3],s[1]+h[y][4],void 0,void 0),this.length+=e.getTotalLength(),this.functions.push(e);else{var w=new l(s[0]+h[y][1],s[0]+h[y][3],s[1]+h[y][2],s[1]+h[y][4]);this.length+=w.getTotalLength(),this.functions.push(w)}g=[s[0]+h[y][1],s[1]+h[y][2]],s=[h[y][3]+s[0],h[y][4]+s[1]]}else if("T"===h[y][0]){if(y>0&&["Q","q","T","t"].indexOf(h[y-1][0])>-1)e=new j(s[0],s[1],2*s[0]-g[0],2*s[1]-g[1],h[y][1],h[y][2],void 0,void 0),this.functions.push(e),this.length+=e.getTotalLength();else{var L=new l(s[0],h[y][1],s[1],h[y][2]);this.functions.push(L),this.length+=L.getTotalLength()}g=[2*s[0]-g[0],2*s[1]-g[1]],s=[h[y][1],h[y][2]]}else if("t"===h[y][0]){if(y>0&&["Q","q","T","t"].indexOf(h[y-1][0])>-1)e=new j(s[0],s[1],2*s[0]-g[0],2*s[1]-g[1],s[0]+h[y][1],s[1]+h[y][2],void 0,void 0),this.length+=e.getTotalLength(),this.functions.push(e);else{var d=new l(s[0],s[0]+h[y][1],s[1],s[1]+h[y][2]);this.length+=d.getTotalLength(),this.functions.push(d)}g=[2*s[0]-g[0],2*s[1]-g[1]],s=[h[y][1]+s[0],h[y][2]+s[1]]}else if("A"===h[y][0]){var A=new c(s[0],s[1],h[y][1],h[y][2],h[y][3],1===h[y][4],1===h[y][5],h[y][6],h[y][7]);this.length+=A.getTotalLength(),s=[h[y][6],h[y][7]],this.functions.push(A)}else if("a"===h[y][0]){var b=new c(s[0],s[1],h[y][1],h[y][2],h[y][3],1===h[y][4],1===h[y][5],s[0]+h[y][6],s[1]+h[y][7]);this.length+=b.getTotalLength(),s=[s[0]+h[y][6],s[1]+h[y][7]],this.functions.push(b)}this.partial_lengths.push(this.length)}})),E=e((function(t){var n=this;if(i(this,"inst",void 0),i(this,"getTotalLength",(function(){return n.inst.getTotalLength()})),i(this,"getPointAtLength",(function(t){return n.inst.getPointAtLength(t)})),i(this,"getTangentAtLength",(function(t){return n.inst.getTangentAtLength(t)})),i(this,"getPropertiesAtLength",(function(t){return n.inst.getPropertiesAtLength(t)})),i(this,"getParts",(function(){return n.inst.getParts()})),this.inst=new O(t),!(this instanceof E))return new E(t)}));t.svgPathProperties=E}));
ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/__pycache__/audioscheduler_nodes.cpython-310.pyc ADDED
Binary file (6.18 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/__pycache__/batchcrop_nodes.cpython-310.pyc ADDED
Binary file (17.4 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/__pycache__/curve_nodes.cpython-310.pyc ADDED
Binary file (37 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/__pycache__/image_nodes.cpython-310.pyc ADDED
Binary file (45.4 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/__pycache__/intrinsic_lora_nodes.cpython-310.pyc ADDED
Binary file (4.23 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/__pycache__/mask_nodes.cpython-310.pyc ADDED
Binary file (33.1 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/__pycache__/nodes.cpython-310.pyc ADDED
Binary file (49.9 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/audioscheduler_nodes.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # to be used with https://github.com/a1lazydog/ComfyUI-AudioScheduler
2
+ import torch
3
+ from torchvision.transforms import functional as TF
4
+ from PIL import Image, ImageDraw
5
+ import numpy as np
6
+ from ..utility.utility import pil2tensor
7
+ from nodes import MAX_RESOLUTION
8
+
9
+ class NormalizedAmplitudeToMask:
10
+ @classmethod
11
+ def INPUT_TYPES(s):
12
+ return {"required": {
13
+ "normalized_amp": ("NORMALIZED_AMPLITUDE",),
14
+ "width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
15
+ "height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
16
+ "frame_offset": ("INT", {"default": 0,"min": -255, "max": 255, "step": 1}),
17
+ "location_x": ("INT", {"default": 256,"min": 0, "max": 4096, "step": 1}),
18
+ "location_y": ("INT", {"default": 256,"min": 0, "max": 4096, "step": 1}),
19
+ "size": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}),
20
+ "shape": (
21
+ [
22
+ 'none',
23
+ 'circle',
24
+ 'square',
25
+ 'triangle',
26
+ ],
27
+ {
28
+ "default": 'none'
29
+ }),
30
+ "color": (
31
+ [
32
+ 'white',
33
+ 'amplitude',
34
+ ],
35
+ {
36
+ "default": 'amplitude'
37
+ }),
38
+ },}
39
+
40
+ CATEGORY = "KJNodes/audio"
41
+ RETURN_TYPES = ("MASK",)
42
+ FUNCTION = "convert"
43
+ DESCRIPTION = """
44
+ Works as a bridge to the AudioScheduler -nodes:
45
+ https://github.com/a1lazydog/ComfyUI-AudioScheduler
46
+ Creates masks based on the normalized amplitude.
47
+ """
48
+
49
+ def convert(self, normalized_amp, width, height, frame_offset, shape, location_x, location_y, size, color):
50
+ # Ensure normalized_amp is an array and within the range [0, 1]
51
+ normalized_amp = np.clip(normalized_amp, 0.0, 1.0)
52
+
53
+ # Offset the amplitude values by rolling the array
54
+ normalized_amp = np.roll(normalized_amp, frame_offset)
55
+
56
+ # Initialize an empty list to hold the image tensors
57
+ out = []
58
+ # Iterate over each amplitude value to create an image
59
+ for amp in normalized_amp:
60
+ # Scale the amplitude value to cover the full range of grayscale values
61
+ if color == 'amplitude':
62
+ grayscale_value = int(amp * 255)
63
+ elif color == 'white':
64
+ grayscale_value = 255
65
+ # Convert the grayscale value to an RGB format
66
+ gray_color = (grayscale_value, grayscale_value, grayscale_value)
67
+ finalsize = size * amp
68
+
69
+ if shape == 'none':
70
+ shapeimage = Image.new("RGB", (width, height), gray_color)
71
+ else:
72
+ shapeimage = Image.new("RGB", (width, height), "black")
73
+
74
+ draw = ImageDraw.Draw(shapeimage)
75
+ if shape == 'circle' or shape == 'square':
76
+ # Define the bounding box for the shape
77
+ left_up_point = (location_x - finalsize, location_y - finalsize)
78
+ right_down_point = (location_x + finalsize,location_y + finalsize)
79
+ two_points = [left_up_point, right_down_point]
80
+
81
+ if shape == 'circle':
82
+ draw.ellipse(two_points, fill=gray_color)
83
+ elif shape == 'square':
84
+ draw.rectangle(two_points, fill=gray_color)
85
+
86
+ elif shape == 'triangle':
87
+ # Define the points for the triangle
88
+ left_up_point = (location_x - finalsize, location_y + finalsize) # bottom left
89
+ right_down_point = (location_x + finalsize, location_y + finalsize) # bottom right
90
+ top_point = (location_x, location_y) # top point
91
+ draw.polygon([top_point, left_up_point, right_down_point], fill=gray_color)
92
+
93
+ shapeimage = pil2tensor(shapeimage)
94
+ mask = shapeimage[:, :, :, 0]
95
+ out.append(mask)
96
+
97
+ return (torch.cat(out, dim=0),)
98
+
99
+ class NormalizedAmplitudeToFloatList:
100
+ @classmethod
101
+ def INPUT_TYPES(s):
102
+ return {"required": {
103
+ "normalized_amp": ("NORMALIZED_AMPLITUDE",),
104
+ },}
105
+
106
+ CATEGORY = "KJNodes/audio"
107
+ RETURN_TYPES = ("FLOAT",)
108
+ FUNCTION = "convert"
109
+ DESCRIPTION = """
110
+ Works as a bridge to the AudioScheduler -nodes:
111
+ https://github.com/a1lazydog/ComfyUI-AudioScheduler
112
+ Creates a list of floats from the normalized amplitude.
113
+ """
114
+
115
+ def convert(self, normalized_amp):
116
+ # Ensure normalized_amp is an array and within the range [0, 1]
117
+ normalized_amp = np.clip(normalized_amp, 0.0, 1.0)
118
+ return (normalized_amp.tolist(),)
119
+
120
+ class OffsetMaskByNormalizedAmplitude:
121
+ @classmethod
122
+ def INPUT_TYPES(s):
123
+ return {
124
+ "required": {
125
+ "normalized_amp": ("NORMALIZED_AMPLITUDE",),
126
+ "mask": ("MASK",),
127
+ "x": ("INT", { "default": 0, "min": -4096, "max": MAX_RESOLUTION, "step": 1, "display": "number" }),
128
+ "y": ("INT", { "default": 0, "min": -4096, "max": MAX_RESOLUTION, "step": 1, "display": "number" }),
129
+ "rotate": ("BOOLEAN", { "default": False }),
130
+ "angle_multiplier": ("FLOAT", { "default": 0.0, "min": -1.0, "max": 1.0, "step": 0.001, "display": "number" }),
131
+ }
132
+ }
133
+
134
+ RETURN_TYPES = ("MASK",)
135
+ RETURN_NAMES = ("mask",)
136
+ FUNCTION = "offset"
137
+ CATEGORY = "KJNodes/audio"
138
+ DESCRIPTION = """
139
+ Works as a bridge to the AudioScheduler -nodes:
140
+ https://github.com/a1lazydog/ComfyUI-AudioScheduler
141
+ Offsets masks based on the normalized amplitude.
142
+ """
143
+
144
+ def offset(self, mask, x, y, angle_multiplier, rotate, normalized_amp):
145
+
146
+ # Ensure normalized_amp is an array and within the range [0, 1]
147
+ offsetmask = mask.clone()
148
+ normalized_amp = np.clip(normalized_amp, 0.0, 1.0)
149
+
150
+ batch_size, height, width = mask.shape
151
+
152
+ if rotate:
153
+ for i in range(batch_size):
154
+ rotation_amp = int(normalized_amp[i] * (360 * angle_multiplier))
155
+ rotation_angle = rotation_amp
156
+ offsetmask[i] = TF.rotate(offsetmask[i].unsqueeze(0), rotation_angle).squeeze(0)
157
+ if x != 0 or y != 0:
158
+ for i in range(batch_size):
159
+ offset_amp = normalized_amp[i] * 10
160
+ shift_x = min(x*offset_amp, width-1)
161
+ shift_y = min(y*offset_amp, height-1)
162
+ if shift_x != 0:
163
+ offsetmask[i] = torch.roll(offsetmask[i], shifts=int(shift_x), dims=1)
164
+ if shift_y != 0:
165
+ offsetmask[i] = torch.roll(offsetmask[i], shifts=int(shift_y), dims=0)
166
+
167
+ return offsetmask,
168
+
169
+ class ImageTransformByNormalizedAmplitude:
170
+ @classmethod
171
+ def INPUT_TYPES(s):
172
+ return {"required": {
173
+ "normalized_amp": ("NORMALIZED_AMPLITUDE",),
174
+ "zoom_scale": ("FLOAT", { "default": 0.0, "min": -1.0, "max": 1.0, "step": 0.001, "display": "number" }),
175
+ "x_offset": ("INT", { "default": 0, "min": (1 -MAX_RESOLUTION), "max": MAX_RESOLUTION, "step": 1, "display": "number" }),
176
+ "y_offset": ("INT", { "default": 0, "min": (1 -MAX_RESOLUTION), "max": MAX_RESOLUTION, "step": 1, "display": "number" }),
177
+ "cumulative": ("BOOLEAN", { "default": False }),
178
+ "image": ("IMAGE",),
179
+ }}
180
+
181
+ RETURN_TYPES = ("IMAGE",)
182
+ FUNCTION = "amptransform"
183
+ CATEGORY = "KJNodes/audio"
184
+ DESCRIPTION = """
185
+ Works as a bridge to the AudioScheduler -nodes:
186
+ https://github.com/a1lazydog/ComfyUI-AudioScheduler
187
+ Transforms image based on the normalized amplitude.
188
+ """
189
+
190
+ def amptransform(self, image, normalized_amp, zoom_scale, cumulative, x_offset, y_offset):
191
+ # Ensure normalized_amp is an array and within the range [0, 1]
192
+ normalized_amp = np.clip(normalized_amp, 0.0, 1.0)
193
+ transformed_images = []
194
+
195
+ # Initialize the cumulative zoom factor
196
+ prev_amp = 0.0
197
+
198
+ for i in range(image.shape[0]):
199
+ img = image[i] # Get the i-th image in the batch
200
+ amp = normalized_amp[i] # Get the corresponding amplitude value
201
+
202
+ # Incrementally increase the cumulative zoom factor
203
+ if cumulative:
204
+ prev_amp += amp
205
+ amp += prev_amp
206
+
207
+ # Convert the image tensor from BxHxWxC to CxHxW format expected by torchvision
208
+ img = img.permute(2, 0, 1)
209
+
210
+ # Convert PyTorch tensor to PIL Image for processing
211
+ pil_img = TF.to_pil_image(img)
212
+
213
+ # Calculate the crop size based on the amplitude
214
+ width, height = pil_img.size
215
+ crop_size = int(min(width, height) * (1 - amp * zoom_scale))
216
+ crop_size = max(crop_size, 1)
217
+
218
+ # Calculate the crop box coordinates (centered crop)
219
+ left = (width - crop_size) // 2
220
+ top = (height - crop_size) // 2
221
+ right = (width + crop_size) // 2
222
+ bottom = (height + crop_size) // 2
223
+
224
+ # Crop and resize back to original size
225
+ cropped_img = TF.crop(pil_img, top, left, crop_size, crop_size)
226
+ resized_img = TF.resize(cropped_img, (height, width))
227
+
228
+ # Convert back to tensor in CxHxW format
229
+ tensor_img = TF.to_tensor(resized_img)
230
+
231
+ # Convert the tensor back to BxHxWxC format
232
+ tensor_img = tensor_img.permute(1, 2, 0)
233
+
234
+ # Offset the image based on the amplitude
235
+ offset_amp = amp * 10 # Calculate the offset magnitude based on the amplitude
236
+ shift_x = min(x_offset * offset_amp, img.shape[1] - 1) # Calculate the shift in x direction
237
+ shift_y = min(y_offset * offset_amp, img.shape[0] - 1) # Calculate the shift in y direction
238
+
239
+ # Apply the offset to the image tensor
240
+ if shift_x != 0:
241
+ tensor_img = torch.roll(tensor_img, shifts=int(shift_x), dims=1)
242
+ if shift_y != 0:
243
+ tensor_img = torch.roll(tensor_img, shifts=int(shift_y), dims=0)
244
+
245
+ # Add to the list
246
+ transformed_images.append(tensor_img)
247
+
248
+ # Stack all transformed images into a batch
249
+ transformed_batch = torch.stack(transformed_images)
250
+
251
+ return (transformed_batch,)
ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/batchcrop_nodes.py ADDED
@@ -0,0 +1,757 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ..utility.utility import tensor2pil, pil2tensor
2
+ from PIL import Image, ImageDraw, ImageFilter
3
+ import numpy as np
4
+ import torch
5
+ from torchvision.transforms import Resize, CenterCrop, InterpolationMode
6
+ import math
7
+
8
+ #based on nodes from mtb https://github.com/melMass/comfy_mtb
9
+
10
+ def bbox_to_region(bbox, target_size=None):
11
+ bbox = bbox_check(bbox, target_size)
12
+ return (bbox[0], bbox[1], bbox[0] + bbox[2], bbox[1] + bbox[3])
13
+
14
+ def bbox_check(bbox, target_size=None):
15
+ if not target_size:
16
+ return bbox
17
+
18
+ new_bbox = (
19
+ bbox[0],
20
+ bbox[1],
21
+ min(target_size[0] - bbox[0], bbox[2]),
22
+ min(target_size[1] - bbox[1], bbox[3]),
23
+ )
24
+ return new_bbox
25
+
26
+ class BatchCropFromMask:
27
+
28
+ @classmethod
29
+ def INPUT_TYPES(cls):
30
+ return {
31
+ "required": {
32
+ "original_images": ("IMAGE",),
33
+ "masks": ("MASK",),
34
+ "crop_size_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}),
35
+ "bbox_smooth_alpha": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
36
+ },
37
+ }
38
+
39
+ RETURN_TYPES = (
40
+ "IMAGE",
41
+ "IMAGE",
42
+ "BBOX",
43
+ "INT",
44
+ "INT",
45
+ )
46
+ RETURN_NAMES = (
47
+ "original_images",
48
+ "cropped_images",
49
+ "bboxes",
50
+ "width",
51
+ "height",
52
+ )
53
+ FUNCTION = "crop"
54
+ CATEGORY = "KJNodes/masking"
55
+
56
+ def smooth_bbox_size(self, prev_bbox_size, curr_bbox_size, alpha):
57
+ if alpha == 0:
58
+ return prev_bbox_size
59
+ return round(alpha * curr_bbox_size + (1 - alpha) * prev_bbox_size)
60
+
61
+ def smooth_center(self, prev_center, curr_center, alpha=0.5):
62
+ if alpha == 0:
63
+ return prev_center
64
+ return (
65
+ round(alpha * curr_center[0] + (1 - alpha) * prev_center[0]),
66
+ round(alpha * curr_center[1] + (1 - alpha) * prev_center[1])
67
+ )
68
+
69
+ def crop(self, masks, original_images, crop_size_mult, bbox_smooth_alpha):
70
+
71
+ bounding_boxes = []
72
+ cropped_images = []
73
+
74
+ self.max_bbox_width = 0
75
+ self.max_bbox_height = 0
76
+
77
+ # First, calculate the maximum bounding box size across all masks
78
+ curr_max_bbox_width = 0
79
+ curr_max_bbox_height = 0
80
+ for mask in masks:
81
+ _mask = tensor2pil(mask)[0]
82
+ non_zero_indices = np.nonzero(np.array(_mask))
83
+ min_x, max_x = np.min(non_zero_indices[1]), np.max(non_zero_indices[1])
84
+ min_y, max_y = np.min(non_zero_indices[0]), np.max(non_zero_indices[0])
85
+ width = max_x - min_x
86
+ height = max_y - min_y
87
+ curr_max_bbox_width = max(curr_max_bbox_width, width)
88
+ curr_max_bbox_height = max(curr_max_bbox_height, height)
89
+
90
+ # Smooth the changes in the bounding box size
91
+ self.max_bbox_width = self.smooth_bbox_size(self.max_bbox_width, curr_max_bbox_width, bbox_smooth_alpha)
92
+ self.max_bbox_height = self.smooth_bbox_size(self.max_bbox_height, curr_max_bbox_height, bbox_smooth_alpha)
93
+
94
+ # Apply the crop size multiplier
95
+ self.max_bbox_width = round(self.max_bbox_width * crop_size_mult)
96
+ self.max_bbox_height = round(self.max_bbox_height * crop_size_mult)
97
+ bbox_aspect_ratio = self.max_bbox_width / self.max_bbox_height
98
+
99
+ # Then, for each mask and corresponding image...
100
+ for i, (mask, img) in enumerate(zip(masks, original_images)):
101
+ _mask = tensor2pil(mask)[0]
102
+ non_zero_indices = np.nonzero(np.array(_mask))
103
+ min_x, max_x = np.min(non_zero_indices[1]), np.max(non_zero_indices[1])
104
+ min_y, max_y = np.min(non_zero_indices[0]), np.max(non_zero_indices[0])
105
+
106
+ # Calculate center of bounding box
107
+ center_x = np.mean(non_zero_indices[1])
108
+ center_y = np.mean(non_zero_indices[0])
109
+ curr_center = (round(center_x), round(center_y))
110
+
111
+ # If this is the first frame, initialize prev_center with curr_center
112
+ if not hasattr(self, 'prev_center'):
113
+ self.prev_center = curr_center
114
+
115
+ # Smooth the changes in the center coordinates from the second frame onwards
116
+ if i > 0:
117
+ center = self.smooth_center(self.prev_center, curr_center, bbox_smooth_alpha)
118
+ else:
119
+ center = curr_center
120
+
121
+ # Update prev_center for the next frame
122
+ self.prev_center = center
123
+
124
+ # Create bounding box using max_bbox_width and max_bbox_height
125
+ half_box_width = round(self.max_bbox_width / 2)
126
+ half_box_height = round(self.max_bbox_height / 2)
127
+ min_x = max(0, center[0] - half_box_width)
128
+ max_x = min(img.shape[1], center[0] + half_box_width)
129
+ min_y = max(0, center[1] - half_box_height)
130
+ max_y = min(img.shape[0], center[1] + half_box_height)
131
+
132
+ # Append bounding box coordinates
133
+ bounding_boxes.append((min_x, min_y, max_x - min_x, max_y - min_y))
134
+
135
+ # Crop the image from the bounding box
136
+ cropped_img = img[min_y:max_y, min_x:max_x, :]
137
+
138
+ # Calculate the new dimensions while maintaining the aspect ratio
139
+ new_height = min(cropped_img.shape[0], self.max_bbox_height)
140
+ new_width = round(new_height * bbox_aspect_ratio)
141
+
142
+ # Resize the image
143
+ resize_transform = Resize((new_height, new_width))
144
+ resized_img = resize_transform(cropped_img.permute(2, 0, 1))
145
+
146
+ # Perform the center crop to the desired size
147
+ crop_transform = CenterCrop((self.max_bbox_height, self.max_bbox_width)) # swap the order here if necessary
148
+ cropped_resized_img = crop_transform(resized_img)
149
+
150
+ cropped_images.append(cropped_resized_img.permute(1, 2, 0))
151
+
152
+ cropped_out = torch.stack(cropped_images, dim=0)
153
+
154
+ return (original_images, cropped_out, bounding_boxes, self.max_bbox_width, self.max_bbox_height, )
155
+
156
+ class BatchUncrop:
157
+
158
+ @classmethod
159
+ def INPUT_TYPES(cls):
160
+ return {
161
+ "required": {
162
+ "original_images": ("IMAGE",),
163
+ "cropped_images": ("IMAGE",),
164
+ "bboxes": ("BBOX",),
165
+ "border_blending": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 1.0, "step": 0.01}, ),
166
+ "crop_rescale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
167
+ "border_top": ("BOOLEAN", {"default": True}),
168
+ "border_bottom": ("BOOLEAN", {"default": True}),
169
+ "border_left": ("BOOLEAN", {"default": True}),
170
+ "border_right": ("BOOLEAN", {"default": True}),
171
+ }
172
+ }
173
+
174
+ RETURN_TYPES = ("IMAGE",)
175
+ FUNCTION = "uncrop"
176
+
177
+ CATEGORY = "KJNodes/masking"
178
+
179
+ def uncrop(self, original_images, cropped_images, bboxes, border_blending, crop_rescale, border_top, border_bottom, border_left, border_right):
180
+ def inset_border(image, border_width, border_color, border_top, border_bottom, border_left, border_right):
181
+ draw = ImageDraw.Draw(image)
182
+ width, height = image.size
183
+ if border_top:
184
+ draw.rectangle((0, 0, width, border_width), fill=border_color)
185
+ if border_bottom:
186
+ draw.rectangle((0, height - border_width, width, height), fill=border_color)
187
+ if border_left:
188
+ draw.rectangle((0, 0, border_width, height), fill=border_color)
189
+ if border_right:
190
+ draw.rectangle((width - border_width, 0, width, height), fill=border_color)
191
+ return image
192
+
193
+ if len(original_images) != len(cropped_images):
194
+ raise ValueError(f"The number of original_images ({len(original_images)}) and cropped_images ({len(cropped_images)}) should be the same")
195
+
196
+ # Ensure there are enough bboxes, but drop the excess if there are more bboxes than images
197
+ if len(bboxes) > len(original_images):
198
+ print(f"Warning: Dropping excess bounding boxes. Expected {len(original_images)}, but got {len(bboxes)}")
199
+ bboxes = bboxes[:len(original_images)]
200
+ elif len(bboxes) < len(original_images):
201
+ raise ValueError("There should be at least as many bboxes as there are original and cropped images")
202
+
203
+ input_images = tensor2pil(original_images)
204
+ crop_imgs = tensor2pil(cropped_images)
205
+
206
+ out_images = []
207
+ for i in range(len(input_images)):
208
+ img = input_images[i]
209
+ crop = crop_imgs[i]
210
+ bbox = bboxes[i]
211
+
212
+ # uncrop the image based on the bounding box
213
+ bb_x, bb_y, bb_width, bb_height = bbox
214
+
215
+ paste_region = bbox_to_region((bb_x, bb_y, bb_width, bb_height), img.size)
216
+
217
+ # scale factors
218
+ scale_x = crop_rescale
219
+ scale_y = crop_rescale
220
+
221
+ # scaled paste_region
222
+ paste_region = (round(paste_region[0]*scale_x), round(paste_region[1]*scale_y), round(paste_region[2]*scale_x), round(paste_region[3]*scale_y))
223
+
224
+ # rescale the crop image to fit the paste_region
225
+ crop = crop.resize((round(paste_region[2]-paste_region[0]), round(paste_region[3]-paste_region[1])))
226
+ crop_img = crop.convert("RGB")
227
+
228
+ if border_blending > 1.0:
229
+ border_blending = 1.0
230
+ elif border_blending < 0.0:
231
+ border_blending = 0.0
232
+
233
+ blend_ratio = (max(crop_img.size) / 2) * float(border_blending)
234
+
235
+ blend = img.convert("RGBA")
236
+ mask = Image.new("L", img.size, 0)
237
+
238
+ mask_block = Image.new("L", (paste_region[2]-paste_region[0], paste_region[3]-paste_region[1]), 255)
239
+ mask_block = inset_border(mask_block, round(blend_ratio / 2), (0), border_top, border_bottom, border_left, border_right)
240
+
241
+ mask.paste(mask_block, paste_region)
242
+ blend.paste(crop_img, paste_region)
243
+
244
+ mask = mask.filter(ImageFilter.BoxBlur(radius=blend_ratio / 4))
245
+ mask = mask.filter(ImageFilter.GaussianBlur(radius=blend_ratio / 4))
246
+
247
+ blend.putalpha(mask)
248
+ img = Image.alpha_composite(img.convert("RGBA"), blend)
249
+ out_images.append(img.convert("RGB"))
250
+
251
+ return (pil2tensor(out_images),)
252
+
253
+ class BatchCropFromMaskAdvanced:
254
+
255
+ @classmethod
256
+ def INPUT_TYPES(cls):
257
+ return {
258
+ "required": {
259
+ "original_images": ("IMAGE",),
260
+ "masks": ("MASK",),
261
+ "crop_size_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
262
+ "bbox_smooth_alpha": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
263
+ },
264
+ }
265
+
266
+ RETURN_TYPES = (
267
+ "IMAGE",
268
+ "IMAGE",
269
+ "MASK",
270
+ "IMAGE",
271
+ "MASK",
272
+ "BBOX",
273
+ "BBOX",
274
+ "INT",
275
+ "INT",
276
+ )
277
+ RETURN_NAMES = (
278
+ "original_images",
279
+ "cropped_images",
280
+ "cropped_masks",
281
+ "combined_crop_image",
282
+ "combined_crop_masks",
283
+ "bboxes",
284
+ "combined_bounding_box",
285
+ "bbox_width",
286
+ "bbox_height",
287
+ )
288
+ FUNCTION = "crop"
289
+ CATEGORY = "KJNodes/masking"
290
+
291
+ def smooth_bbox_size(self, prev_bbox_size, curr_bbox_size, alpha):
292
+ return round(alpha * curr_bbox_size + (1 - alpha) * prev_bbox_size)
293
+
294
+ def smooth_center(self, prev_center, curr_center, alpha=0.5):
295
+ return (round(alpha * curr_center[0] + (1 - alpha) * prev_center[0]),
296
+ round(alpha * curr_center[1] + (1 - alpha) * prev_center[1]))
297
+
298
+ def crop(self, masks, original_images, crop_size_mult, bbox_smooth_alpha):
299
+ bounding_boxes = []
300
+ combined_bounding_box = []
301
+ cropped_images = []
302
+ cropped_masks = []
303
+ cropped_masks_out = []
304
+ combined_crop_out = []
305
+ combined_cropped_images = []
306
+ combined_cropped_masks = []
307
+
308
+ def calculate_bbox(mask):
309
+ non_zero_indices = np.nonzero(np.array(mask))
310
+
311
+ # handle empty masks
312
+ min_x, max_x, min_y, max_y = 0, 0, 0, 0
313
+ if len(non_zero_indices[1]) > 0 and len(non_zero_indices[0]) > 0:
314
+ min_x, max_x = np.min(non_zero_indices[1]), np.max(non_zero_indices[1])
315
+ min_y, max_y = np.min(non_zero_indices[0]), np.max(non_zero_indices[0])
316
+
317
+ width = max_x - min_x
318
+ height = max_y - min_y
319
+ bbox_size = max(width, height)
320
+ return min_x, max_x, min_y, max_y, bbox_size
321
+
322
+ combined_mask = torch.max(masks, dim=0)[0]
323
+ _mask = tensor2pil(combined_mask)[0]
324
+ new_min_x, new_max_x, new_min_y, new_max_y, combined_bbox_size = calculate_bbox(_mask)
325
+ center_x = (new_min_x + new_max_x) / 2
326
+ center_y = (new_min_y + new_max_y) / 2
327
+ half_box_size = round(combined_bbox_size // 2)
328
+ new_min_x = max(0, round(center_x - half_box_size))
329
+ new_max_x = min(original_images[0].shape[1], round(center_x + half_box_size))
330
+ new_min_y = max(0, round(center_y - half_box_size))
331
+ new_max_y = min(original_images[0].shape[0], round(center_y + half_box_size))
332
+
333
+ combined_bounding_box.append((new_min_x, new_min_y, new_max_x - new_min_x, new_max_y - new_min_y))
334
+
335
+ self.max_bbox_size = 0
336
+
337
+ # First, calculate the maximum bounding box size across all masks
338
+ curr_max_bbox_size = max(calculate_bbox(tensor2pil(mask)[0])[-1] for mask in masks)
339
+ # Smooth the changes in the bounding box size
340
+ self.max_bbox_size = self.smooth_bbox_size(self.max_bbox_size, curr_max_bbox_size, bbox_smooth_alpha)
341
+ # Apply the crop size multiplier
342
+ self.max_bbox_size = round(self.max_bbox_size * crop_size_mult)
343
+ # Make sure max_bbox_size is divisible by 16, if not, round it upwards so it is
344
+ self.max_bbox_size = math.ceil(self.max_bbox_size / 16) * 16
345
+
346
+ if self.max_bbox_size > original_images[0].shape[0] or self.max_bbox_size > original_images[0].shape[1]:
347
+ # max_bbox_size can only be as big as our input's width or height, and it has to be even
348
+ self.max_bbox_size = math.floor(min(original_images[0].shape[0], original_images[0].shape[1]) / 2) * 2
349
+
350
+ # Then, for each mask and corresponding image...
351
+ for i, (mask, img) in enumerate(zip(masks, original_images)):
352
+ _mask = tensor2pil(mask)[0]
353
+ non_zero_indices = np.nonzero(np.array(_mask))
354
+
355
+ # check for empty masks
356
+ if len(non_zero_indices[0]) > 0 and len(non_zero_indices[1]) > 0:
357
+ min_x, max_x = np.min(non_zero_indices[1]), np.max(non_zero_indices[1])
358
+ min_y, max_y = np.min(non_zero_indices[0]), np.max(non_zero_indices[0])
359
+
360
+ # Calculate center of bounding box
361
+ center_x = np.mean(non_zero_indices[1])
362
+ center_y = np.mean(non_zero_indices[0])
363
+ curr_center = (round(center_x), round(center_y))
364
+
365
+ # If this is the first frame, initialize prev_center with curr_center
366
+ if not hasattr(self, 'prev_center'):
367
+ self.prev_center = curr_center
368
+
369
+ # Smooth the changes in the center coordinates from the second frame onwards
370
+ if i > 0:
371
+ center = self.smooth_center(self.prev_center, curr_center, bbox_smooth_alpha)
372
+ else:
373
+ center = curr_center
374
+
375
+ # Update prev_center for the next frame
376
+ self.prev_center = center
377
+
378
+ # Create bounding box using max_bbox_size
379
+ half_box_size = self.max_bbox_size // 2
380
+ min_x = max(0, center[0] - half_box_size)
381
+ max_x = min(img.shape[1], center[0] + half_box_size)
382
+ min_y = max(0, center[1] - half_box_size)
383
+ max_y = min(img.shape[0], center[1] + half_box_size)
384
+
385
+ # Append bounding box coordinates
386
+ bounding_boxes.append((min_x, min_y, max_x - min_x, max_y - min_y))
387
+
388
+ # Crop the image from the bounding box
389
+ cropped_img = img[min_y:max_y, min_x:max_x, :]
390
+ cropped_mask = mask[min_y:max_y, min_x:max_x]
391
+
392
+ # Resize the cropped image to a fixed size
393
+ new_size = max(cropped_img.shape[0], cropped_img.shape[1])
394
+ resize_transform = Resize(new_size, interpolation=InterpolationMode.NEAREST, max_size=max(img.shape[0], img.shape[1]))
395
+ resized_mask = resize_transform(cropped_mask.unsqueeze(0).unsqueeze(0)).squeeze(0).squeeze(0)
396
+ resized_img = resize_transform(cropped_img.permute(2, 0, 1))
397
+ # Perform the center crop to the desired size
398
+ # Constrain the crop to the smaller of our bbox or our image so we don't expand past the image dimensions.
399
+ crop_transform = CenterCrop((min(self.max_bbox_size, resized_img.shape[1]), min(self.max_bbox_size, resized_img.shape[2])))
400
+
401
+ cropped_resized_img = crop_transform(resized_img)
402
+ cropped_images.append(cropped_resized_img.permute(1, 2, 0))
403
+
404
+ cropped_resized_mask = crop_transform(resized_mask)
405
+ cropped_masks.append(cropped_resized_mask)
406
+
407
+ combined_cropped_img = original_images[i][new_min_y:new_max_y, new_min_x:new_max_x, :]
408
+ combined_cropped_images.append(combined_cropped_img)
409
+
410
+ combined_cropped_mask = masks[i][new_min_y:new_max_y, new_min_x:new_max_x]
411
+ combined_cropped_masks.append(combined_cropped_mask)
412
+ else:
413
+ bounding_boxes.append((0, 0, img.shape[1], img.shape[0]))
414
+ cropped_images.append(img)
415
+ cropped_masks.append(mask)
416
+ combined_cropped_images.append(img)
417
+ combined_cropped_masks.append(mask)
418
+
419
+ cropped_out = torch.stack(cropped_images, dim=0)
420
+ combined_crop_out = torch.stack(combined_cropped_images, dim=0)
421
+ cropped_masks_out = torch.stack(cropped_masks, dim=0)
422
+ combined_crop_mask_out = torch.stack(combined_cropped_masks, dim=0)
423
+
424
+ return (original_images, cropped_out, cropped_masks_out, combined_crop_out, combined_crop_mask_out, bounding_boxes, combined_bounding_box, self.max_bbox_size, self.max_bbox_size)
425
+
426
+ class FilterZeroMasksAndCorrespondingImages:
427
+
428
+ @classmethod
429
+ def INPUT_TYPES(cls):
430
+ return {
431
+ "required": {
432
+ "masks": ("MASK",),
433
+ },
434
+ "optional": {
435
+ "original_images": ("IMAGE",),
436
+ },
437
+ }
438
+
439
+ RETURN_TYPES = ("MASK", "IMAGE", "IMAGE", "INDEXES",)
440
+ RETURN_NAMES = ("non_zero_masks_out", "non_zero_mask_images_out", "zero_mask_images_out", "zero_mask_images_out_indexes",)
441
+ FUNCTION = "filter"
442
+ CATEGORY = "KJNodes/masking"
443
+ DESCRIPTION = """
444
+ Filter out all the empty (i.e. all zero) mask in masks
445
+ Also filter out all the corresponding images in original_images by indexes if provide
446
+
447
+ original_images (optional): If provided, need have same length as masks.
448
+ """
449
+
450
+ def filter(self, masks, original_images=None):
451
+ non_zero_masks = []
452
+ non_zero_mask_images = []
453
+ zero_mask_images = []
454
+ zero_mask_images_indexes = []
455
+
456
+ masks_num = len(masks)
457
+ also_process_images = False
458
+ if original_images is not None:
459
+ imgs_num = len(original_images)
460
+ if len(original_images) == masks_num:
461
+ also_process_images = True
462
+ else:
463
+ print(f"[WARNING] ignore input: original_images, due to number of original_images ({imgs_num}) is not equal to number of masks ({masks_num})")
464
+
465
+ for i in range(masks_num):
466
+ non_zero_num = np.count_nonzero(np.array(masks[i]))
467
+ if non_zero_num > 0:
468
+ non_zero_masks.append(masks[i])
469
+ if also_process_images:
470
+ non_zero_mask_images.append(original_images[i])
471
+ else:
472
+ zero_mask_images.append(original_images[i])
473
+ zero_mask_images_indexes.append(i)
474
+
475
+ non_zero_masks_out = torch.stack(non_zero_masks, dim=0)
476
+ non_zero_mask_images_out = zero_mask_images_out = zero_mask_images_out_indexes = None
477
+
478
+ if also_process_images:
479
+ non_zero_mask_images_out = torch.stack(non_zero_mask_images, dim=0)
480
+ if len(zero_mask_images) > 0:
481
+ zero_mask_images_out = torch.stack(zero_mask_images, dim=0)
482
+ zero_mask_images_out_indexes = zero_mask_images_indexes
483
+
484
+ return (non_zero_masks_out, non_zero_mask_images_out, zero_mask_images_out, zero_mask_images_out_indexes)
485
+
486
+ class InsertImageBatchByIndexes:
487
+
488
+ @classmethod
489
+ def INPUT_TYPES(cls):
490
+ return {
491
+ "required": {
492
+ "images": ("IMAGE",),
493
+ "images_to_insert": ("IMAGE",),
494
+ "insert_indexes": ("INDEXES",),
495
+ },
496
+ }
497
+
498
+ RETURN_TYPES = ("IMAGE", )
499
+ RETURN_NAMES = ("images_after_insert", )
500
+ FUNCTION = "insert"
501
+ CATEGORY = "KJNodes/image"
502
+ DESCRIPTION = """
503
+ This node is designed to be use with node FilterZeroMasksAndCorrespondingImages
504
+ It inserts the images_to_insert into images according to insert_indexes
505
+
506
+ Returns:
507
+ images_after_insert: updated original images with origonal sequence order
508
+ """
509
+
510
+ def insert(self, images, images_to_insert, insert_indexes):
511
+ images_after_insert = images
512
+
513
+ if images_to_insert is not None and insert_indexes is not None:
514
+ images_to_insert_num = len(images_to_insert)
515
+ insert_indexes_num = len(insert_indexes)
516
+ if images_to_insert_num == insert_indexes_num:
517
+ images_after_insert = []
518
+
519
+ i_images = 0
520
+ for i in range(len(images) + images_to_insert_num):
521
+ if i in insert_indexes:
522
+ images_after_insert.append(images_to_insert[insert_indexes.index(i)])
523
+ else:
524
+ images_after_insert.append(images[i_images])
525
+ i_images += 1
526
+
527
+ images_after_insert = torch.stack(images_after_insert, dim=0)
528
+
529
+ else:
530
+ print(f"[WARNING] skip this node, due to number of images_to_insert ({images_to_insert_num}) is not equal to number of insert_indexes ({insert_indexes_num})")
531
+
532
+
533
+ return (images_after_insert, )
534
+
535
+ class BatchUncropAdvanced:
536
+
537
+ @classmethod
538
+ def INPUT_TYPES(cls):
539
+ return {
540
+ "required": {
541
+ "original_images": ("IMAGE",),
542
+ "cropped_images": ("IMAGE",),
543
+ "cropped_masks": ("MASK",),
544
+ "combined_crop_mask": ("MASK",),
545
+ "bboxes": ("BBOX",),
546
+ "border_blending": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 1.0, "step": 0.01}, ),
547
+ "crop_rescale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
548
+ "use_combined_mask": ("BOOLEAN", {"default": False}),
549
+ "use_square_mask": ("BOOLEAN", {"default": True}),
550
+ },
551
+ "optional": {
552
+ "combined_bounding_box": ("BBOX", {"default": None}),
553
+ },
554
+ }
555
+
556
+ RETURN_TYPES = ("IMAGE",)
557
+ FUNCTION = "uncrop"
558
+ CATEGORY = "KJNodes/masking"
559
+
560
+
561
+ def uncrop(self, original_images, cropped_images, cropped_masks, combined_crop_mask, bboxes, border_blending, crop_rescale, use_combined_mask, use_square_mask, combined_bounding_box = None):
562
+
563
+ def inset_border(image, border_width=20, border_color=(0)):
564
+ width, height = image.size
565
+ bordered_image = Image.new(image.mode, (width, height), border_color)
566
+ bordered_image.paste(image, (0, 0))
567
+ draw = ImageDraw.Draw(bordered_image)
568
+ draw.rectangle((0, 0, width - 1, height - 1), outline=border_color, width=border_width)
569
+ return bordered_image
570
+
571
+ if len(original_images) != len(cropped_images):
572
+ raise ValueError(f"The number of original_images ({len(original_images)}) and cropped_images ({len(cropped_images)}) should be the same")
573
+
574
+ # Ensure there are enough bboxes, but drop the excess if there are more bboxes than images
575
+ if len(bboxes) > len(original_images):
576
+ print(f"Warning: Dropping excess bounding boxes. Expected {len(original_images)}, but got {len(bboxes)}")
577
+ bboxes = bboxes[:len(original_images)]
578
+ elif len(bboxes) < len(original_images):
579
+ raise ValueError("There should be at least as many bboxes as there are original and cropped images")
580
+
581
+ crop_imgs = tensor2pil(cropped_images)
582
+ input_images = tensor2pil(original_images)
583
+ out_images = []
584
+
585
+ for i in range(len(input_images)):
586
+ img = input_images[i]
587
+ crop = crop_imgs[i]
588
+ bbox = bboxes[i]
589
+
590
+ if use_combined_mask:
591
+ bb_x, bb_y, bb_width, bb_height = combined_bounding_box[0]
592
+ paste_region = bbox_to_region((bb_x, bb_y, bb_width, bb_height), img.size)
593
+ mask = combined_crop_mask[i]
594
+ else:
595
+ bb_x, bb_y, bb_width, bb_height = bbox
596
+ paste_region = bbox_to_region((bb_x, bb_y, bb_width, bb_height), img.size)
597
+ mask = cropped_masks[i]
598
+
599
+ # scale paste_region
600
+ scale_x = scale_y = crop_rescale
601
+ paste_region = (round(paste_region[0]*scale_x), round(paste_region[1]*scale_y), round(paste_region[2]*scale_x), round(paste_region[3]*scale_y))
602
+
603
+ # rescale the crop image to fit the paste_region
604
+ crop = crop.resize((round(paste_region[2]-paste_region[0]), round(paste_region[3]-paste_region[1])))
605
+ crop_img = crop.convert("RGB")
606
+
607
+ #border blending
608
+ if border_blending > 1.0:
609
+ border_blending = 1.0
610
+ elif border_blending < 0.0:
611
+ border_blending = 0.0
612
+
613
+ blend_ratio = (max(crop_img.size) / 2) * float(border_blending)
614
+ blend = img.convert("RGBA")
615
+
616
+ if use_square_mask:
617
+ mask = Image.new("L", img.size, 0)
618
+ mask_block = Image.new("L", (paste_region[2]-paste_region[0], paste_region[3]-paste_region[1]), 255)
619
+ mask_block = inset_border(mask_block, round(blend_ratio / 2), (0))
620
+ mask.paste(mask_block, paste_region)
621
+ else:
622
+ original_mask = tensor2pil(mask)[0]
623
+ original_mask = original_mask.resize((paste_region[2]-paste_region[0], paste_region[3]-paste_region[1]))
624
+ mask = Image.new("L", img.size, 0)
625
+ mask.paste(original_mask, paste_region)
626
+
627
+ mask = mask.filter(ImageFilter.BoxBlur(radius=blend_ratio / 4))
628
+ mask = mask.filter(ImageFilter.GaussianBlur(radius=blend_ratio / 4))
629
+
630
+ blend.paste(crop_img, paste_region)
631
+ blend.putalpha(mask)
632
+
633
+ img = Image.alpha_composite(img.convert("RGBA"), blend)
634
+ out_images.append(img.convert("RGB"))
635
+
636
+ return (pil2tensor(out_images),)
637
+
638
+ class SplitBboxes:
639
+
640
+ @classmethod
641
+ def INPUT_TYPES(cls):
642
+ return {
643
+ "required": {
644
+ "bboxes": ("BBOX",),
645
+ "index": ("INT", {"default": 0,"min": 0, "max": 99999999, "step": 1}),
646
+ },
647
+ }
648
+
649
+ RETURN_TYPES = ("BBOX","BBOX",)
650
+ RETURN_NAMES = ("bboxes_a","bboxes_b",)
651
+ FUNCTION = "splitbbox"
652
+ CATEGORY = "KJNodes/masking"
653
+ DESCRIPTION = """
654
+ Splits the specified bbox list at the given index into two lists.
655
+ """
656
+
657
+ def splitbbox(self, bboxes, index):
658
+ bboxes_a = bboxes[:index] # Sub-list from the start of bboxes up to (but not including) the index
659
+ bboxes_b = bboxes[index:] # Sub-list from the index to the end of bboxes
660
+
661
+ return (bboxes_a, bboxes_b,)
662
+
663
+ class BboxToInt:
664
+
665
+ @classmethod
666
+ def INPUT_TYPES(cls):
667
+ return {
668
+ "required": {
669
+ "bboxes": ("BBOX",),
670
+ "index": ("INT", {"default": 0,"min": 0, "max": 99999999, "step": 1}),
671
+ },
672
+ }
673
+
674
+ RETURN_TYPES = ("INT","INT","INT","INT","INT","INT",)
675
+ RETURN_NAMES = ("x_min","y_min","width","height", "center_x","center_y",)
676
+ FUNCTION = "bboxtoint"
677
+ CATEGORY = "KJNodes/masking"
678
+ DESCRIPTION = """
679
+ Returns selected index from bounding box list as integers.
680
+ """
681
+ def bboxtoint(self, bboxes, index):
682
+ x_min, y_min, width, height = bboxes[index]
683
+ center_x = int(x_min + width / 2)
684
+ center_y = int(y_min + height / 2)
685
+
686
+ return (x_min, y_min, width, height, center_x, center_y,)
687
+
688
+ class BboxVisualize:
689
+
690
+ @classmethod
691
+ def INPUT_TYPES(cls):
692
+ return {
693
+ "required": {
694
+ "images": ("IMAGE",),
695
+ "bboxes": ("BBOX",),
696
+ "line_width": ("INT", {"default": 1,"min": 1, "max": 10, "step": 1}),
697
+ },
698
+ }
699
+
700
+ RETURN_TYPES = ("IMAGE",)
701
+ RETURN_NAMES = ("images",)
702
+ FUNCTION = "visualizebbox"
703
+ DESCRIPTION = """
704
+ Visualizes the specified bbox on the image.
705
+ """
706
+
707
+ CATEGORY = "KJNodes/masking"
708
+
709
+ def visualizebbox(self, bboxes, images, line_width):
710
+ image_list = []
711
+ for image, bbox in zip(images, bboxes):
712
+ x_min, y_min, width, height = bbox
713
+
714
+ # Ensure bbox coordinates are integers
715
+ x_min = int(x_min)
716
+ y_min = int(y_min)
717
+ width = int(width)
718
+ height = int(height)
719
+
720
+ # Permute the image dimensions
721
+ image = image.permute(2, 0, 1)
722
+
723
+ # Clone the image to draw bounding boxes
724
+ img_with_bbox = image.clone()
725
+
726
+ # Define the color for the bbox, e.g., red
727
+ color = torch.tensor([1, 0, 0], dtype=torch.float32)
728
+
729
+ # Ensure color tensor matches the image channels
730
+ if color.shape[0] != img_with_bbox.shape[0]:
731
+ color = color.unsqueeze(1).expand(-1, line_width)
732
+
733
+ # Draw lines for each side of the bbox with the specified line width
734
+ for lw in range(line_width):
735
+ # Top horizontal line
736
+ if y_min + lw < img_with_bbox.shape[1]:
737
+ img_with_bbox[:, y_min + lw, x_min:x_min + width] = color[:, None]
738
+
739
+ # Bottom horizontal line
740
+ if y_min + height - lw < img_with_bbox.shape[1]:
741
+ img_with_bbox[:, y_min + height - lw, x_min:x_min + width] = color[:, None]
742
+
743
+ # Left vertical line
744
+ if x_min + lw < img_with_bbox.shape[2]:
745
+ img_with_bbox[:, y_min:y_min + height, x_min + lw] = color[:, None]
746
+
747
+ # Right vertical line
748
+ if x_min + width - lw < img_with_bbox.shape[2]:
749
+ img_with_bbox[:, y_min:y_min + height, x_min + width - lw] = color[:, None]
750
+
751
+ # Permute the image dimensions back
752
+ img_with_bbox = img_with_bbox.permute(1, 2, 0).unsqueeze(0)
753
+ image_list.append(img_with_bbox)
754
+
755
+ return (torch.cat(image_list, dim=0),)
756
+
757
+ return (torch.cat(image_list, dim=0),)
ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/curve_nodes.py ADDED
@@ -0,0 +1,1393 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torchvision import transforms
3
+ import json
4
+ from PIL import Image, ImageDraw, ImageFont, ImageColor, ImageFilter
5
+ import numpy as np
6
+ from ..utility.utility import pil2tensor
7
+ import folder_paths
8
+ from comfy.utils import common_upscale
9
+
10
+ def plot_coordinates_to_tensor(coordinates, height, width, bbox_height, bbox_width, size_multiplier, prompt):
11
+ import matplotlib
12
+ matplotlib.use('Agg')
13
+ from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
14
+ text_color = '#999999'
15
+ bg_color = '#353535'
16
+ matplotlib.pyplot.rcParams['text.color'] = text_color
17
+ fig, ax = matplotlib.pyplot.subplots(figsize=(width/100, height/100), dpi=100)
18
+ fig.patch.set_facecolor(bg_color)
19
+ ax.set_facecolor(bg_color)
20
+ ax.grid(color=text_color, linestyle='-', linewidth=0.5)
21
+ ax.set_xlabel('x', color=text_color)
22
+ ax.set_ylabel('y', color=text_color)
23
+ for text in ax.get_xticklabels() + ax.get_yticklabels():
24
+ text.set_color(text_color)
25
+ ax.set_title('position for: ' + prompt)
26
+ ax.set_xlabel('X Coordinate')
27
+ ax.set_ylabel('Y Coordinate')
28
+ #ax.legend().remove()
29
+ ax.set_xlim(0, width) # Set the x-axis to match the input latent width
30
+ ax.set_ylim(height, 0) # Set the y-axis to match the input latent height, with (0,0) at top-left
31
+ # Adjust the margins of the subplot
32
+ matplotlib.pyplot.subplots_adjust(left=0.08, right=0.95, bottom=0.05, top=0.95, wspace=0.2, hspace=0.2)
33
+
34
+ cmap = matplotlib.pyplot.get_cmap('rainbow')
35
+ image_batch = []
36
+ canvas = FigureCanvas(fig)
37
+ width, height = fig.get_size_inches() * fig.get_dpi()
38
+ # Draw a box at each coordinate
39
+ for i, ((x, y), size) in enumerate(zip(coordinates, size_multiplier)):
40
+ color_index = i / (len(coordinates) - 1)
41
+ color = cmap(color_index)
42
+ draw_height = bbox_height * size
43
+ draw_width = bbox_width * size
44
+ rect = matplotlib.patches.Rectangle((x - draw_width/2, y - draw_height/2), draw_width, draw_height,
45
+ linewidth=1, edgecolor=color, facecolor='none', alpha=0.5)
46
+ ax.add_patch(rect)
47
+
48
+ # Check if there is a next coordinate to draw an arrow to
49
+ if i < len(coordinates) - 1:
50
+ x1, y1 = coordinates[i]
51
+ x2, y2 = coordinates[i + 1]
52
+ ax.annotate("", xy=(x2, y2), xytext=(x1, y1),
53
+ arrowprops=dict(arrowstyle="->",
54
+ linestyle="-",
55
+ lw=1,
56
+ color=color,
57
+ mutation_scale=20))
58
+ canvas.draw()
59
+ image_np = np.frombuffer(canvas.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3).copy()
60
+ image_tensor = torch.from_numpy(image_np).float() / 255.0
61
+ image_tensor = image_tensor.unsqueeze(0)
62
+ image_batch.append(image_tensor)
63
+
64
+ matplotlib.pyplot.close(fig)
65
+ image_batch_tensor = torch.cat(image_batch, dim=0)
66
+
67
+ return image_batch_tensor
68
+
69
+ class PlotCoordinates:
70
+ @classmethod
71
+ def INPUT_TYPES(s):
72
+ return {"required": {
73
+ "coordinates": ("STRING", {"forceInput": True}),
74
+ "text": ("STRING", {"default": 'title', "multiline": False}),
75
+ "width": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}),
76
+ "height": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}),
77
+ "bbox_width": ("INT", {"default": 128, "min": 8, "max": 4096, "step": 8}),
78
+ "bbox_height": ("INT", {"default": 128, "min": 8, "max": 4096, "step": 8}),
79
+ },
80
+ "optional": {"size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True})},
81
+ }
82
+ RETURN_TYPES = ("IMAGE", "INT", "INT", "INT", "INT",)
83
+ RETURN_NAMES = ("images", "width", "height", "bbox_width", "bbox_height",)
84
+ FUNCTION = "append"
85
+ CATEGORY = "KJNodes/experimental"
86
+ DESCRIPTION = """
87
+ Plots coordinates to sequence of images using Matplotlib.
88
+
89
+ """
90
+
91
+ def append(self, coordinates, text, width, height, bbox_width, bbox_height, size_multiplier=[1.0]):
92
+ coordinates = json.loads(coordinates.replace("'", '"'))
93
+ coordinates = [(coord['x'], coord['y']) for coord in coordinates]
94
+ batch_size = len(coordinates)
95
+ if len(size_multiplier) != batch_size:
96
+ size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)]
97
+
98
+ plot_image_tensor = plot_coordinates_to_tensor(coordinates, height, width, bbox_height, bbox_width, size_multiplier, text)
99
+
100
+ return (plot_image_tensor, width, height, bbox_width, bbox_height)
101
+
102
+ class SplineEditor:
103
+
104
+ @classmethod
105
+ def INPUT_TYPES(cls):
106
+ return {
107
+ "required": {
108
+ "points_store": ("STRING", {"multiline": False}),
109
+ "coordinates": ("STRING", {"multiline": False}),
110
+ "mask_width": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}),
111
+ "mask_height": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}),
112
+ "points_to_sample": ("INT", {"default": 16, "min": 2, "max": 1000, "step": 1}),
113
+ "sampling_method": (
114
+ [
115
+ 'path',
116
+ 'time',
117
+ 'controlpoints'
118
+ ],
119
+ {
120
+ "default": 'time'
121
+ }),
122
+ "interpolation": (
123
+ [
124
+ 'cardinal',
125
+ 'monotone',
126
+ 'basis',
127
+ 'linear',
128
+ 'step-before',
129
+ 'step-after',
130
+ 'polar',
131
+ 'polar-reverse',
132
+ ],
133
+ {
134
+ "default": 'cardinal'
135
+ }),
136
+ "tension": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
137
+ "repeat_output": ("INT", {"default": 1, "min": 1, "max": 4096, "step": 1}),
138
+ "float_output_type": (
139
+ [
140
+ 'list',
141
+ 'pandas series',
142
+ 'tensor',
143
+ ],
144
+ {
145
+ "default": 'list'
146
+ }),
147
+ },
148
+ "optional": {
149
+ "min_value": ("FLOAT", {"default": 0.0, "min": -10000.0, "max": 10000.0, "step": 0.01}),
150
+ "max_value": ("FLOAT", {"default": 1.0, "min": -10000.0, "max": 10000.0, "step": 0.01}),
151
+ }
152
+ }
153
+
154
+ RETURN_TYPES = ("MASK", "STRING", "FLOAT", "INT", "STRING",)
155
+ RETURN_NAMES = ("mask", "coord_str", "float", "count", "normalized_str",)
156
+ FUNCTION = "splinedata"
157
+ CATEGORY = "KJNodes/weights"
158
+ DESCRIPTION = """
159
+ # WORK IN PROGRESS
160
+ Do not count on this as part of your workflow yet,
161
+ probably contains lots of bugs and stability is not
162
+ guaranteed!!
163
+
164
+ ## Graphical editor to create values for various
165
+ ## schedules and/or mask batches.
166
+
167
+ **Shift + click** to add control point at end.
168
+ **Ctrl + click** to add control point (subdivide) between two points.
169
+ **Right click on a point** to delete it.
170
+ Note that you can't delete from start/end.
171
+
172
+ Right click on canvas for context menu:
173
+ These are purely visual options, doesn't affect the output:
174
+ - Toggle handles visibility
175
+ - Display sample points: display the points to be returned.
176
+
177
+ **points_to_sample** value sets the number of samples
178
+ returned from the **drawn spline itself**, this is independent from the
179
+ actual control points, so the interpolation type matters.
180
+ sampling_method:
181
+ - time: samples along the time axis, used for schedules
182
+ - path: samples along the path itself, useful for coordinates
183
+
184
+ output types:
185
+ - mask batch
186
+ example compatible nodes: anything that takes masks
187
+ - list of floats
188
+ example compatible nodes: IPAdapter weights
189
+ - pandas series
190
+ example compatible nodes: anything that takes Fizz'
191
+ nodes Batch Value Schedule
192
+ - torch tensor
193
+ example compatible nodes: unknown
194
+ """
195
+
196
+ def splinedata(self, mask_width, mask_height, coordinates, float_output_type, interpolation,
197
+ points_to_sample, sampling_method, points_store, tension, repeat_output, min_value=0.0, max_value=1.0):
198
+
199
+ coordinates = json.loads(coordinates)
200
+ normalized = []
201
+ normalized_y_values = []
202
+ for coord in coordinates:
203
+ coord['x'] = int(round(coord['x']))
204
+ coord['y'] = int(round(coord['y']))
205
+ norm_x = (1.0 - (coord['x'] / mask_height) - 0.0) * (max_value - min_value) + min_value
206
+ norm_y = (1.0 - (coord['y'] / mask_height) - 0.0) * (max_value - min_value) + min_value
207
+ normalized_y_values.append(norm_y)
208
+ normalized.append({'x':norm_x, 'y':norm_y})
209
+ if float_output_type == 'list':
210
+ out_floats = normalized_y_values * repeat_output
211
+ elif float_output_type == 'pandas series':
212
+ try:
213
+ import pandas as pd
214
+ except:
215
+ raise Exception("MaskOrImageToWeight: pandas is not installed. Please install pandas to use this output_type")
216
+ out_floats = pd.Series(normalized_y_values * repeat_output),
217
+ elif float_output_type == 'tensor':
218
+ out_floats = torch.tensor(normalized_y_values * repeat_output, dtype=torch.float32)
219
+ # Create a color map for grayscale intensities
220
+ color_map = lambda y: torch.full((mask_height, mask_width, 3), y, dtype=torch.float32)
221
+
222
+ # Create image tensors for each normalized y value
223
+ mask_tensors = [color_map(y) for y in normalized_y_values]
224
+ masks_out = torch.stack(mask_tensors)
225
+ masks_out = masks_out.repeat(repeat_output, 1, 1, 1)
226
+ masks_out = masks_out.mean(dim=-1)
227
+ return (masks_out, json.dumps(coordinates), out_floats, len(out_floats) , json.dumps(normalized))
228
+
229
+ class CreateShapeMaskOnPath:
230
+
231
+ RETURN_TYPES = ("MASK", "MASK",)
232
+ RETURN_NAMES = ("mask", "mask_inverted",)
233
+ FUNCTION = "createshapemask"
234
+ CATEGORY = "KJNodes/masking/generate"
235
+ DESCRIPTION = """
236
+ Creates a mask or batch of masks with the specified shape.
237
+ Locations are center locations.
238
+ """
239
+
240
+ @classmethod
241
+ def INPUT_TYPES(s):
242
+ return {
243
+ "required": {
244
+ "shape": (
245
+ [ 'circle',
246
+ 'square',
247
+ 'triangle',
248
+ ],
249
+ {
250
+ "default": 'circle'
251
+ }),
252
+ "coordinates": ("STRING", {"forceInput": True}),
253
+ "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
254
+ "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
255
+ "shape_width": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}),
256
+ "shape_height": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}),
257
+ },
258
+ "optional": {
259
+ "size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True}),
260
+ }
261
+ }
262
+
263
+ def createshapemask(self, coordinates, frame_width, frame_height, shape_width, shape_height, shape, size_multiplier=[1.0]):
264
+ # Define the number of images in the batch
265
+ coordinates = coordinates.replace("'", '"')
266
+ coordinates = json.loads(coordinates)
267
+
268
+ batch_size = len(coordinates)
269
+ out = []
270
+ color = "white"
271
+ if len(size_multiplier) != batch_size:
272
+ size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)]
273
+ for i, coord in enumerate(coordinates):
274
+ image = Image.new("RGB", (frame_width, frame_height), "black")
275
+ draw = ImageDraw.Draw(image)
276
+
277
+ # Calculate the size for this frame and ensure it's not less than 0
278
+ current_width = max(0, shape_width + i * size_multiplier[i])
279
+ current_height = max(0, shape_height + i * size_multiplier[i])
280
+
281
+ location_x = coord['x']
282
+ location_y = coord['y']
283
+
284
+ if shape == 'circle' or shape == 'square':
285
+ # Define the bounding box for the shape
286
+ left_up_point = (location_x - current_width // 2, location_y - current_height // 2)
287
+ right_down_point = (location_x + current_width // 2, location_y + current_height // 2)
288
+ two_points = [left_up_point, right_down_point]
289
+
290
+ if shape == 'circle':
291
+ draw.ellipse(two_points, fill=color)
292
+ elif shape == 'square':
293
+ draw.rectangle(two_points, fill=color)
294
+
295
+ elif shape == 'triangle':
296
+ # Define the points for the triangle
297
+ left_up_point = (location_x - current_width // 2, location_y + current_height // 2) # bottom left
298
+ right_down_point = (location_x + current_width // 2, location_y + current_height // 2) # bottom right
299
+ top_point = (location_x, location_y - current_height // 2) # top point
300
+ draw.polygon([top_point, left_up_point, right_down_point], fill=color)
301
+
302
+ image = pil2tensor(image)
303
+ mask = image[:, :, :, 0]
304
+ out.append(mask)
305
+ outstack = torch.cat(out, dim=0)
306
+ return (outstack, 1.0 - outstack,)
307
+
308
+ class CreateShapeImageOnPath:
309
+
310
+ RETURN_TYPES = ("IMAGE", "MASK",)
311
+ RETURN_NAMES = ("image","mask", )
312
+ FUNCTION = "createshapemask"
313
+ CATEGORY = "KJNodes/image"
314
+ DESCRIPTION = """
315
+ Creates an image or batch of images with the specified shape.
316
+ Locations are center locations.
317
+ """
318
+
319
+ @classmethod
320
+ def INPUT_TYPES(s):
321
+ return {
322
+ "required": {
323
+ "shape": (
324
+ [ 'circle',
325
+ 'square',
326
+ 'triangle',
327
+ ],
328
+ {
329
+ "default": 'circle'
330
+ }),
331
+ "coordinates": ("STRING", {"forceInput": True}),
332
+ "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
333
+ "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
334
+ "shape_width": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}),
335
+ "shape_height": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}),
336
+ "shape_color": ("STRING", {"default": 'white'}),
337
+ "bg_color": ("STRING", {"default": 'black'}),
338
+ "blur_radius": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100, "step": 0.1}),
339
+ "intensity": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 100.0, "step": 0.01}),
340
+ },
341
+ "optional": {
342
+ "size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True}),
343
+ }
344
+ }
345
+
346
+ def createshapemask(self, coordinates, frame_width, frame_height, shape_width, shape_height, shape_color,
347
+ bg_color, blur_radius, shape, intensity, size_multiplier=[1.0]):
348
+ # Define the number of images in the batch
349
+ coordinates = coordinates.replace("'", '"')
350
+ coordinates = json.loads(coordinates)
351
+
352
+ batch_size = len(coordinates)
353
+ images_list = []
354
+ masks_list = []
355
+
356
+ if len(size_multiplier) != batch_size:
357
+ size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)]
358
+ for i, coord in enumerate(coordinates):
359
+ image = Image.new("RGB", (frame_width, frame_height), bg_color)
360
+ draw = ImageDraw.Draw(image)
361
+
362
+ # Calculate the size for this frame and ensure it's not less than 0
363
+ current_width = max(0, shape_width + i * size_multiplier[i])
364
+ current_height = max(0, shape_height + i * size_multiplier[i])
365
+
366
+ location_x = coord['x']
367
+ location_y = coord['y']
368
+
369
+ if shape == 'circle' or shape == 'square':
370
+ # Define the bounding box for the shape
371
+ left_up_point = (location_x - current_width // 2, location_y - current_height // 2)
372
+ right_down_point = (location_x + current_width // 2, location_y + current_height // 2)
373
+ two_points = [left_up_point, right_down_point]
374
+
375
+ if shape == 'circle':
376
+ draw.ellipse(two_points, fill=shape_color)
377
+ elif shape == 'square':
378
+ draw.rectangle(two_points, fill=shape_color)
379
+
380
+ elif shape == 'triangle':
381
+ # Define the points for the triangle
382
+ left_up_point = (location_x - current_width // 2, location_y + current_height // 2) # bottom left
383
+ right_down_point = (location_x + current_width // 2, location_y + current_height // 2) # bottom right
384
+ top_point = (location_x, location_y - current_height // 2) # top point
385
+ draw.polygon([top_point, left_up_point, right_down_point], fill=shape_color)
386
+
387
+ if blur_radius != 0:
388
+ image = image.filter(ImageFilter.GaussianBlur(blur_radius))
389
+
390
+ image = pil2tensor(image)
391
+ image = image * intensity
392
+ mask = image[:, :, :, 0]
393
+ masks_list.append(mask)
394
+ images_list.append(image)
395
+ out_images = torch.cat(images_list, dim=0).cpu().float()
396
+ out_masks = torch.cat(masks_list, dim=0)
397
+ return (out_images, out_masks)
398
+
399
+ class CreateTextOnPath:
400
+
401
+ RETURN_TYPES = ("IMAGE", "MASK", "MASK",)
402
+ RETURN_NAMES = ("image", "mask", "mask_inverted",)
403
+ FUNCTION = "createtextmask"
404
+ CATEGORY = "KJNodes/masking/generate"
405
+ DESCRIPTION = """
406
+ Creates a mask or batch of masks with the specified text.
407
+ Locations are center locations.
408
+ """
409
+
410
+ @classmethod
411
+ def INPUT_TYPES(s):
412
+ return {
413
+ "required": {
414
+ "coordinates": ("STRING", {"forceInput": True}),
415
+ "text": ("STRING", {"default": 'text', "multiline": True}),
416
+ "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
417
+ "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
418
+ "font": (folder_paths.get_filename_list("kjnodes_fonts"), ),
419
+ "font_size": ("INT", {"default": 42}),
420
+ "alignment": (
421
+ [ 'left',
422
+ 'center',
423
+ 'right'
424
+ ],
425
+ {"default": 'center'}
426
+ ),
427
+ "text_color": ("STRING", {"default": 'white'}),
428
+ },
429
+ "optional": {
430
+ "size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True}),
431
+ }
432
+ }
433
+
434
+ def createtextmask(self, coordinates, frame_width, frame_height, font, font_size, text, text_color, alignment, size_multiplier=[1.0]):
435
+ coordinates = coordinates.replace("'", '"')
436
+ coordinates = json.loads(coordinates)
437
+
438
+ batch_size = len(coordinates)
439
+ mask_list = []
440
+ image_list = []
441
+ color = text_color
442
+ font_path = folder_paths.get_full_path("kjnodes_fonts", font)
443
+
444
+ if len(size_multiplier) != batch_size:
445
+ size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)]
446
+
447
+ for i, coord in enumerate(coordinates):
448
+ image = Image.new("RGB", (frame_width, frame_height), "black")
449
+ draw = ImageDraw.Draw(image)
450
+ lines = text.split('\n') # Split the text into lines
451
+ # Apply the size multiplier to the font size for this iteration
452
+ current_font_size = int(font_size * size_multiplier[i])
453
+ current_font = ImageFont.truetype(font_path, current_font_size)
454
+ line_heights = [current_font.getbbox(line)[3] for line in lines] # List of line heights
455
+ total_text_height = sum(line_heights) # Total height of text block
456
+
457
+ # Calculate the starting Y position to center the block of text
458
+ start_y = coord['y'] - total_text_height // 2
459
+ for j, line in enumerate(lines):
460
+ text_width, text_height = current_font.getbbox(line)[2], line_heights[j]
461
+ if alignment == 'left':
462
+ location_x = coord['x']
463
+ elif alignment == 'center':
464
+ location_x = int(coord['x'] - text_width // 2)
465
+ elif alignment == 'right':
466
+ location_x = int(coord['x'] - text_width)
467
+
468
+ location_y = int(start_y + sum(line_heights[:j]))
469
+ text_position = (location_x, location_y)
470
+ # Draw the text
471
+ try:
472
+ draw.text(text_position, line, fill=color, font=current_font, features=['-liga'])
473
+ except:
474
+ draw.text(text_position, line, fill=color, font=current_font)
475
+
476
+ image = pil2tensor(image)
477
+ non_black_pixels = (image > 0).any(dim=-1)
478
+ mask = non_black_pixels.to(image.dtype)
479
+ mask_list.append(mask)
480
+ image_list.append(image)
481
+
482
+ out_images = torch.cat(image_list, dim=0).cpu().float()
483
+ out_masks = torch.cat(mask_list, dim=0)
484
+ return (out_images, out_masks, 1.0 - out_masks,)
485
+
486
+ class CreateGradientFromCoords:
487
+
488
+ RETURN_TYPES = ("IMAGE", )
489
+ RETURN_NAMES = ("image", )
490
+ FUNCTION = "generate"
491
+ CATEGORY = "KJNodes/image"
492
+ DESCRIPTION = """
493
+ Creates a gradient image from coordinates.
494
+ """
495
+
496
+ @classmethod
497
+ def INPUT_TYPES(s):
498
+ return {
499
+ "required": {
500
+ "coordinates": ("STRING", {"forceInput": True}),
501
+ "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
502
+ "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
503
+ "start_color": ("STRING", {"default": 'white'}),
504
+ "end_color": ("STRING", {"default": 'black'}),
505
+ "multiplier": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 100.0, "step": 0.01}),
506
+ },
507
+ }
508
+
509
+ def generate(self, coordinates, frame_width, frame_height, start_color, end_color, multiplier):
510
+ # Parse the coordinates
511
+ coordinates = json.loads(coordinates.replace("'", '"'))
512
+
513
+ # Create an image
514
+ image = Image.new("RGB", (frame_width, frame_height))
515
+ draw = ImageDraw.Draw(image)
516
+
517
+ # Extract start and end points for the gradient
518
+ start_coord = coordinates[0]
519
+ end_coord = coordinates[1]
520
+
521
+ start_color = ImageColor.getrgb(start_color)
522
+ end_color = ImageColor.getrgb(end_color)
523
+
524
+ # Calculate the gradient direction (vector)
525
+ gradient_direction = (end_coord['x'] - start_coord['x'], end_coord['y'] - start_coord['y'])
526
+ gradient_length = (gradient_direction[0] ** 2 + gradient_direction[1] ** 2) ** 0.5
527
+
528
+ # Iterate over each pixel in the image
529
+ for y in range(frame_height):
530
+ for x in range(frame_width):
531
+ # Calculate the projection of the point on the gradient line
532
+ point_vector = (x - start_coord['x'], y - start_coord['y'])
533
+ projection = (point_vector[0] * gradient_direction[0] + point_vector[1] * gradient_direction[1]) / gradient_length
534
+ projection = max(min(projection, gradient_length), 0) # Clamp the projection value
535
+
536
+ # Calculate the blend factor for the current pixel
537
+ blend = projection * multiplier / gradient_length
538
+
539
+ # Determine the color of the current pixel
540
+ color = (
541
+ int(start_color[0] + (end_color[0] - start_color[0]) * blend),
542
+ int(start_color[1] + (end_color[1] - start_color[1]) * blend),
543
+ int(start_color[2] + (end_color[2] - start_color[2]) * blend)
544
+ )
545
+
546
+ # Set the pixel color
547
+ draw.point((x, y), fill=color)
548
+
549
+ # Convert the PIL image to a tensor (assuming such a function exists in your context)
550
+ image_tensor = pil2tensor(image)
551
+
552
+ return (image_tensor,)
553
+
554
+ class GradientToFloat:
555
+
556
+ RETURN_TYPES = ("FLOAT", "FLOAT",)
557
+ RETURN_NAMES = ("float_x", "float_y", )
558
+ FUNCTION = "sample"
559
+ CATEGORY = "KJNodes/image"
560
+ DESCRIPTION = """
561
+ Calculates list of floats from image.
562
+ """
563
+
564
+ @classmethod
565
+ def INPUT_TYPES(s):
566
+ return {
567
+ "required": {
568
+ "image": ("IMAGE", ),
569
+ "steps": ("INT", {"default": 10, "min": 2, "max": 10000, "step": 1}),
570
+ },
571
+ }
572
+
573
+ def sample(self, image, steps):
574
+ # Assuming image is a tensor with shape [B, H, W, C]
575
+ B, H, W, C = image.shape
576
+
577
+ # Sample along the width axis (W)
578
+ w_intervals = torch.linspace(0, W - 1, steps=steps, dtype=torch.int64)
579
+ # Assuming we're sampling from the first batch and the first channel
580
+ w_sampled = image[0, :, w_intervals, 0]
581
+
582
+ # Sample along the height axis (H)
583
+ h_intervals = torch.linspace(0, H - 1, steps=steps, dtype=torch.int64)
584
+ # Assuming we're sampling from the first batch and the first channel
585
+ h_sampled = image[0, h_intervals, :, 0]
586
+
587
+ # Taking the mean across the height for width sampling, and across the width for height sampling
588
+ w_values = w_sampled.mean(dim=0).tolist()
589
+ h_values = h_sampled.mean(dim=1).tolist()
590
+
591
+ return (w_values, h_values)
592
+
593
+ class MaskOrImageToWeight:
594
+
595
+ @classmethod
596
+ def INPUT_TYPES(s):
597
+ return {
598
+ "required": {
599
+ "output_type": (
600
+ [
601
+ 'list',
602
+ 'pandas series',
603
+ 'tensor',
604
+ 'string'
605
+ ],
606
+ {
607
+ "default": 'list'
608
+ }),
609
+ },
610
+ "optional": {
611
+ "images": ("IMAGE",),
612
+ "masks": ("MASK",),
613
+ },
614
+
615
+ }
616
+ RETURN_TYPES = ("FLOAT", "STRING",)
617
+ FUNCTION = "execute"
618
+ CATEGORY = "KJNodes/weights"
619
+ DESCRIPTION = """
620
+ Gets the mean values from mask or image batch
621
+ and returns that as the selected output type.
622
+ """
623
+
624
+ def execute(self, output_type, images=None, masks=None):
625
+ mean_values = []
626
+ if masks is not None and images is None:
627
+ for mask in masks:
628
+ mean_values.append(mask.mean().item())
629
+ elif masks is None and images is not None:
630
+ for image in images:
631
+ mean_values.append(image.mean().item())
632
+ elif masks is not None and images is not None:
633
+ raise Exception("MaskOrImageToWeight: Use either mask or image input only.")
634
+
635
+ # Convert mean_values to the specified output_type
636
+ if output_type == 'list':
637
+ out = mean_values
638
+ elif output_type == 'pandas series':
639
+ try:
640
+ import pandas as pd
641
+ except:
642
+ raise Exception("MaskOrImageToWeight: pandas is not installed. Please install pandas to use this output_type")
643
+ out = pd.Series(mean_values),
644
+ elif output_type == 'tensor':
645
+ out = torch.tensor(mean_values, dtype=torch.float32),
646
+ return (out, [str(value) for value in mean_values],)
647
+
648
+ class WeightScheduleConvert:
649
+
650
+ @classmethod
651
+ def INPUT_TYPES(s):
652
+ return {
653
+ "required": {
654
+ "input_values": ("FLOAT", {"default": 0.0, "forceInput": True}),
655
+ "output_type": (
656
+ [
657
+ 'match_input',
658
+ 'list',
659
+ 'pandas series',
660
+ 'tensor',
661
+ ],
662
+ {
663
+ "default": 'list'
664
+ }),
665
+ "invert": ("BOOLEAN", {"default": False}),
666
+ "repeat": ("INT", {"default": 1,"min": 1, "max": 255, "step": 1}),
667
+ },
668
+ "optional": {
669
+ "remap_to_frames": ("INT", {"default": 0}),
670
+ "interpolation_curve": ("FLOAT", {"forceInput": True}),
671
+ "remap_values": ("BOOLEAN", {"default": False}),
672
+ "remap_min": ("FLOAT", {"default": 0.0, "min": -100000, "max": 100000.0, "step": 0.01}),
673
+ "remap_max": ("FLOAT", {"default": 1.0, "min": -100000, "max": 100000.0, "step": 0.01}),
674
+ },
675
+
676
+ }
677
+ RETURN_TYPES = ("FLOAT", "STRING", "INT",)
678
+ FUNCTION = "execute"
679
+ CATEGORY = "KJNodes/weights"
680
+ DESCRIPTION = """
681
+ Converts different value lists/series to another type.
682
+ """
683
+
684
+ def detect_input_type(self, input_values):
685
+ import pandas as pd
686
+ if isinstance(input_values, list):
687
+ return 'list'
688
+ elif isinstance(input_values, pd.Series):
689
+ return 'pandas series'
690
+ elif isinstance(input_values, torch.Tensor):
691
+ return 'tensor'
692
+ else:
693
+ raise ValueError("Unsupported input type")
694
+
695
+ def execute(self, input_values, output_type, invert, repeat, remap_to_frames=0, interpolation_curve=None, remap_min=0.0, remap_max=1.0, remap_values=False):
696
+ import pandas as pd
697
+ input_type = self.detect_input_type(input_values)
698
+
699
+ if input_type == 'pandas series':
700
+ float_values = input_values.tolist()
701
+ elif input_type == 'tensor':
702
+ float_values = input_values
703
+ else:
704
+ float_values = input_values
705
+
706
+ if invert:
707
+ float_values = [1 - value for value in float_values]
708
+
709
+ if interpolation_curve is not None:
710
+ interpolated_pattern = []
711
+ orig_float_values = float_values
712
+ for value in interpolation_curve:
713
+ min_val = min(orig_float_values)
714
+ max_val = max(orig_float_values)
715
+ # Normalize the values to [0, 1]
716
+ normalized_values = [(value - min_val) / (max_val - min_val) for value in orig_float_values]
717
+ # Interpolate the normalized values to the new frame count
718
+ remapped_float_values = np.interp(np.linspace(0, 1, int(remap_to_frames * value)), np.linspace(0, 1, len(normalized_values)), normalized_values).tolist()
719
+ interpolated_pattern.extend(remapped_float_values)
720
+ float_values = interpolated_pattern
721
+ else:
722
+ # Remap float_values to match target_frame_amount
723
+ if remap_to_frames > 0 and remap_to_frames != len(float_values):
724
+ min_val = min(float_values)
725
+ max_val = max(float_values)
726
+ # Normalize the values to [0, 1]
727
+ normalized_values = [(value - min_val) / (max_val - min_val) for value in float_values]
728
+ # Interpolate the normalized values to the new frame count
729
+ float_values = np.interp(np.linspace(0, 1, remap_to_frames), np.linspace(0, 1, len(normalized_values)), normalized_values).tolist()
730
+
731
+ float_values = float_values * repeat
732
+ if remap_values:
733
+ float_values = self.remap_values(float_values, remap_min, remap_max)
734
+
735
+ if output_type == 'list':
736
+ out = float_values,
737
+ elif output_type == 'pandas series':
738
+ out = pd.Series(float_values),
739
+ elif output_type == 'tensor':
740
+ if input_type == 'pandas series':
741
+ out = torch.tensor(float_values.values, dtype=torch.float32),
742
+ else:
743
+ out = torch.tensor(float_values, dtype=torch.float32),
744
+ elif output_type == 'match_input':
745
+ out = float_values,
746
+ return (out, [str(value) for value in float_values], [int(value) for value in float_values])
747
+
748
+ def remap_values(self, values, target_min, target_max):
749
+ # Determine the current range
750
+ current_min = min(values)
751
+ current_max = max(values)
752
+ current_range = current_max - current_min
753
+
754
+ # Determine the target range
755
+ target_range = target_max - target_min
756
+
757
+ # Perform the linear interpolation for each value
758
+ remapped_values = [(value - current_min) / current_range * target_range + target_min for value in values]
759
+
760
+ return remapped_values
761
+
762
+
763
+ class FloatToMask:
764
+
765
+ @classmethod
766
+ def INPUT_TYPES(s):
767
+ return {
768
+ "required": {
769
+ "input_values": ("FLOAT", {"forceInput": True, "default": 0}),
770
+ "width": ("INT", {"default": 100, "min": 1}),
771
+ "height": ("INT", {"default": 100, "min": 1}),
772
+ },
773
+ }
774
+ RETURN_TYPES = ("MASK",)
775
+ FUNCTION = "execute"
776
+ CATEGORY = "KJNodes/masking/generate"
777
+ DESCRIPTION = """
778
+ Generates a batch of masks based on the input float values.
779
+ The batch size is determined by the length of the input float values.
780
+ Each mask is generated with the specified width and height.
781
+ """
782
+
783
+ def execute(self, input_values, width, height):
784
+ import pandas as pd
785
+ # Ensure input_values is a list
786
+ if isinstance(input_values, (float, int)):
787
+ input_values = [input_values]
788
+ elif isinstance(input_values, pd.Series):
789
+ input_values = input_values.tolist()
790
+ elif isinstance(input_values, list) and all(isinstance(item, list) for item in input_values):
791
+ input_values = [item for sublist in input_values for item in sublist]
792
+
793
+ # Generate a batch of masks based on the input_values
794
+ masks = []
795
+ for value in input_values:
796
+ # Assuming value is a float between 0 and 1 representing the mask's intensity
797
+ mask = torch.ones((height, width), dtype=torch.float32) * value
798
+ masks.append(mask)
799
+ masks_out = torch.stack(masks, dim=0)
800
+
801
+ return(masks_out,)
802
+ class WeightScheduleExtend:
803
+
804
+ @classmethod
805
+ def INPUT_TYPES(s):
806
+ return {
807
+ "required": {
808
+ "input_values_1": ("FLOAT", {"default": 0.0, "forceInput": True}),
809
+ "input_values_2": ("FLOAT", {"default": 0.0, "forceInput": True}),
810
+ "output_type": (
811
+ [
812
+ 'match_input',
813
+ 'list',
814
+ 'pandas series',
815
+ 'tensor',
816
+ ],
817
+ {
818
+ "default": 'match_input'
819
+ }),
820
+ },
821
+
822
+ }
823
+ RETURN_TYPES = ("FLOAT",)
824
+ FUNCTION = "execute"
825
+ CATEGORY = "KJNodes/weights"
826
+ DESCRIPTION = """
827
+ Extends, and converts if needed, different value lists/series
828
+ """
829
+
830
+ def detect_input_type(self, input_values):
831
+ import pandas as pd
832
+ if isinstance(input_values, list):
833
+ return 'list'
834
+ elif isinstance(input_values, pd.Series):
835
+ return 'pandas series'
836
+ elif isinstance(input_values, torch.Tensor):
837
+ return 'tensor'
838
+ else:
839
+ raise ValueError("Unsupported input type")
840
+
841
+ def execute(self, input_values_1, input_values_2, output_type):
842
+ import pandas as pd
843
+ input_type_1 = self.detect_input_type(input_values_1)
844
+ input_type_2 = self.detect_input_type(input_values_2)
845
+ # Convert input_values_2 to the same format as input_values_1 if they do not match
846
+ if not input_type_1 == input_type_2:
847
+ print("Converting input_values_2 to the same format as input_values_1")
848
+ if input_type_1 == 'pandas series':
849
+ # Convert input_values_2 to a pandas Series
850
+ float_values_2 = pd.Series(input_values_2)
851
+ elif input_type_1 == 'tensor':
852
+ # Convert input_values_2 to a tensor
853
+ float_values_2 = torch.tensor(input_values_2, dtype=torch.float32)
854
+ else:
855
+ print("Input types match, no conversion needed")
856
+ # If the types match, no conversion is needed
857
+ float_values_2 = input_values_2
858
+
859
+ float_values = input_values_1 + float_values_2
860
+
861
+ if output_type == 'list':
862
+ return float_values,
863
+ elif output_type == 'pandas series':
864
+ return pd.Series(float_values),
865
+ elif output_type == 'tensor':
866
+ if input_type_1 == 'pandas series':
867
+ return torch.tensor(float_values.values, dtype=torch.float32),
868
+ else:
869
+ return torch.tensor(float_values, dtype=torch.float32),
870
+ elif output_type == 'match_input':
871
+ return float_values,
872
+ else:
873
+ raise ValueError(f"Unsupported output_type: {output_type}")
874
+
875
+ class FloatToSigmas:
876
+ @classmethod
877
+ def INPUT_TYPES(s):
878
+ return {"required":
879
+ {
880
+ "float_list": ("FLOAT", {"default": 0.0, "forceInput": True}),
881
+ }
882
+ }
883
+ RETURN_TYPES = ("SIGMAS",)
884
+ RETURN_NAMES = ("SIGMAS",)
885
+ CATEGORY = "KJNodes/noise"
886
+ FUNCTION = "customsigmas"
887
+ DESCRIPTION = """
888
+ Creates a sigmas tensor from list of float values.
889
+
890
+ """
891
+ def customsigmas(self, float_list):
892
+ return torch.tensor(float_list, dtype=torch.float32),
893
+
894
+ class GLIGENTextBoxApplyBatchCoords:
895
+ @classmethod
896
+ def INPUT_TYPES(s):
897
+ return {"required": {"conditioning_to": ("CONDITIONING", ),
898
+ "latents": ("LATENT", ),
899
+ "clip": ("CLIP", ),
900
+ "gligen_textbox_model": ("GLIGEN", ),
901
+ "coordinates": ("STRING", {"forceInput": True}),
902
+ "text": ("STRING", {"multiline": True}),
903
+ "width": ("INT", {"default": 128, "min": 8, "max": 4096, "step": 8}),
904
+ "height": ("INT", {"default": 128, "min": 8, "max": 4096, "step": 8}),
905
+ },
906
+ "optional": {"size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True})},
907
+ }
908
+ RETURN_TYPES = ("CONDITIONING", "IMAGE", )
909
+ RETURN_NAMES = ("conditioning", "coord_preview", )
910
+ FUNCTION = "append"
911
+ CATEGORY = "KJNodes/experimental"
912
+ DESCRIPTION = """
913
+ This node allows scheduling GLIGEN text box positions in a batch,
914
+ to be used with AnimateDiff-Evolved. Intended to pair with the
915
+ Spline Editor -node.
916
+
917
+ GLIGEN model can be downloaded through the Manage's "Install Models" menu.
918
+ Or directly from here:
919
+ https://huggingface.co/comfyanonymous/GLIGEN_pruned_safetensors/tree/main
920
+
921
+ Inputs:
922
+ - **latents** input is used to calculate batch size
923
+ - **clip** is your standard text encoder, use same as for the main prompt
924
+ - **gligen_textbox_model** connects to GLIGEN Loader
925
+ - **coordinates** takes a json string of points, directly compatible
926
+ with the spline editor node.
927
+ - **text** is the part of the prompt to set position for
928
+ - **width** and **height** are the size of the GLIGEN bounding box
929
+
930
+ Outputs:
931
+ - **conditioning** goes between to clip text encode and the sampler
932
+ - **coord_preview** is an optional preview of the coordinates and
933
+ bounding boxes.
934
+
935
+ """
936
+
937
+ def append(self, latents, coordinates, conditioning_to, clip, gligen_textbox_model, text, width, height, size_multiplier=[1.0]):
938
+ coordinates = json.loads(coordinates.replace("'", '"'))
939
+ coordinates = [(coord['x'], coord['y']) for coord in coordinates]
940
+
941
+ batch_size = sum(tensor.size(0) for tensor in latents.values())
942
+ if len(coordinates) != batch_size:
943
+ print("GLIGENTextBoxApplyBatchCoords WARNING: The number of coordinates does not match the number of latents")
944
+
945
+ c = []
946
+ _, cond_pooled = clip.encode_from_tokens(clip.tokenize(text), return_pooled=True)
947
+
948
+ for t in conditioning_to:
949
+ n = [t[0], t[1].copy()]
950
+
951
+ position_params_batch = [[] for _ in range(batch_size)] # Initialize a list of empty lists for each batch item
952
+ if len(size_multiplier) != batch_size:
953
+ size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)]
954
+
955
+ for i in range(batch_size):
956
+ x_position, y_position = coordinates[i]
957
+ position_param = (cond_pooled, int((height // 8) * size_multiplier[i]), int((width // 8) * size_multiplier[i]), (y_position - height // 2) // 8, (x_position - width // 2) // 8)
958
+ position_params_batch[i].append(position_param) # Append position_param to the correct sublist
959
+
960
+ prev = []
961
+ if "gligen" in n[1]:
962
+ prev = n[1]['gligen'][2]
963
+ else:
964
+ prev = [[] for _ in range(batch_size)]
965
+ # Concatenate prev and position_params_batch, ensuring both are lists of lists
966
+ # and each sublist corresponds to a batch item
967
+ combined_position_params = [prev_item + batch_item for prev_item, batch_item in zip(prev, position_params_batch)]
968
+ n[1]['gligen'] = ("position_batched", gligen_textbox_model, combined_position_params)
969
+ c.append(n)
970
+
971
+ image_height = latents['samples'].shape[-2] * 8
972
+ image_width = latents['samples'].shape[-1] * 8
973
+ plot_image_tensor = plot_coordinates_to_tensor(coordinates, image_height, image_width, height, width, size_multiplier, text)
974
+
975
+ return (c, plot_image_tensor,)
976
+
977
+ class CreateInstanceDiffusionTracking:
978
+
979
+ RETURN_TYPES = ("TRACKING", "STRING", "INT", "INT", "INT", "INT",)
980
+ RETURN_NAMES = ("tracking", "prompt", "width", "height", "bbox_width", "bbox_height",)
981
+ FUNCTION = "tracking"
982
+ CATEGORY = "KJNodes/InstanceDiffusion"
983
+ DESCRIPTION = """
984
+ Creates tracking data to be used with InstanceDiffusion:
985
+ https://github.com/logtd/ComfyUI-InstanceDiffusion
986
+
987
+ InstanceDiffusion prompt format:
988
+ "class_id.class_name": "prompt",
989
+ for example:
990
+ "1.head": "((head))",
991
+ """
992
+
993
+ @classmethod
994
+ def INPUT_TYPES(s):
995
+ return {
996
+ "required": {
997
+ "coordinates": ("STRING", {"forceInput": True}),
998
+ "width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
999
+ "height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
1000
+ "bbox_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
1001
+ "bbox_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
1002
+ "class_name": ("STRING", {"default": "class_name"}),
1003
+ "class_id": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}),
1004
+ "prompt": ("STRING", {"default": "prompt", "multiline": True}),
1005
+ },
1006
+ "optional": {
1007
+ "size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True}),
1008
+ "fit_in_frame": ("BOOLEAN", {"default": True}),
1009
+ }
1010
+ }
1011
+
1012
+ def tracking(self, coordinates, class_name, class_id, width, height, bbox_width, bbox_height, prompt, size_multiplier=[1.0], fit_in_frame=True):
1013
+ # Define the number of images in the batch
1014
+ coordinates = coordinates.replace("'", '"')
1015
+ coordinates = json.loads(coordinates)
1016
+
1017
+ tracked = {}
1018
+ tracked[class_name] = {}
1019
+ batch_size = len(coordinates)
1020
+ # Initialize a list to hold the coordinates for the current ID
1021
+ id_coordinates = []
1022
+ if len(size_multiplier) != batch_size:
1023
+ size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)]
1024
+ for i, coord in enumerate(coordinates):
1025
+ x = coord['x']
1026
+ y = coord['y']
1027
+ adjusted_bbox_width = bbox_width * size_multiplier[i]
1028
+ adjusted_bbox_height = bbox_height * size_multiplier[i]
1029
+ # Calculate the top left and bottom right coordinates
1030
+ top_left_x = x - adjusted_bbox_width // 2
1031
+ top_left_y = y - adjusted_bbox_height // 2
1032
+ bottom_right_x = x + adjusted_bbox_width // 2
1033
+ bottom_right_y = y + adjusted_bbox_height // 2
1034
+
1035
+ if fit_in_frame:
1036
+ # Clip the coordinates to the frame boundaries
1037
+ top_left_x = max(0, top_left_x)
1038
+ top_left_y = max(0, top_left_y)
1039
+ bottom_right_x = min(width, bottom_right_x)
1040
+ bottom_right_y = min(height, bottom_right_y)
1041
+ # Ensure width and height are positive
1042
+ adjusted_bbox_width = max(1, bottom_right_x - top_left_x)
1043
+ adjusted_bbox_height = max(1, bottom_right_y - top_left_y)
1044
+
1045
+ # Update the coordinates with the new width and height
1046
+ bottom_right_x = top_left_x + adjusted_bbox_width
1047
+ bottom_right_y = top_left_y + adjusted_bbox_height
1048
+
1049
+ # Append the top left and bottom right coordinates to the list for the current ID
1050
+ id_coordinates.append([top_left_x, top_left_y, bottom_right_x, bottom_right_y, width, height])
1051
+
1052
+ class_id = int(class_id)
1053
+ # Assign the list of coordinates to the specified ID within the class_id dictionary
1054
+ tracked[class_name][class_id] = id_coordinates
1055
+
1056
+ prompt_string = ""
1057
+ for class_name, class_data in tracked.items():
1058
+ for class_id in class_data.keys():
1059
+ class_id_str = str(class_id)
1060
+ # Use the incoming prompt for each class name and ID
1061
+ prompt_string += f'"{class_id_str}.{class_name}": "({prompt})",\n'
1062
+
1063
+ # Remove the last comma and newline
1064
+ prompt_string = prompt_string.rstrip(",\n")
1065
+
1066
+ return (tracked, prompt_string, width, height, bbox_width, bbox_height)
1067
+
1068
+ class AppendInstanceDiffusionTracking:
1069
+
1070
+ RETURN_TYPES = ("TRACKING", "STRING",)
1071
+ RETURN_NAMES = ("tracking", "prompt",)
1072
+ FUNCTION = "append"
1073
+ CATEGORY = "KJNodes/InstanceDiffusion"
1074
+ DESCRIPTION = """
1075
+ Appends tracking data to be used with InstanceDiffusion:
1076
+ https://github.com/logtd/ComfyUI-InstanceDiffusion
1077
+
1078
+ """
1079
+
1080
+ @classmethod
1081
+ def INPUT_TYPES(s):
1082
+ return {
1083
+ "required": {
1084
+ "tracking_1": ("TRACKING", {"forceInput": True}),
1085
+ "tracking_2": ("TRACKING", {"forceInput": True}),
1086
+ },
1087
+ "optional": {
1088
+ "prompt_1": ("STRING", {"default": "", "forceInput": True}),
1089
+ "prompt_2": ("STRING", {"default": "", "forceInput": True}),
1090
+ }
1091
+ }
1092
+
1093
+ def append(self, tracking_1, tracking_2, prompt_1="", prompt_2=""):
1094
+ tracking_copy = tracking_1.copy()
1095
+ # Check for existing class names and class IDs, and raise an error if they exist
1096
+ for class_name, class_data in tracking_2.items():
1097
+ if class_name not in tracking_copy:
1098
+ tracking_copy[class_name] = class_data
1099
+ else:
1100
+ # If the class name exists, merge the class data from tracking_2 into tracking_copy
1101
+ # This will add new class IDs under the same class name without raising an error
1102
+ tracking_copy[class_name].update(class_data)
1103
+ prompt_string = prompt_1 + "," + prompt_2
1104
+ return (tracking_copy, prompt_string)
1105
+
1106
+ class InterpolateCoords:
1107
+
1108
+ RETURN_TYPES = ("STRING",)
1109
+ RETURN_NAMES = ("coordinates",)
1110
+ FUNCTION = "interpolate"
1111
+ CATEGORY = "KJNodes/experimental"
1112
+ DESCRIPTION = """
1113
+ Interpolates coordinates based on a curve.
1114
+ """
1115
+
1116
+ @classmethod
1117
+ def INPUT_TYPES(s):
1118
+ return {
1119
+ "required": {
1120
+ "coordinates": ("STRING", {"forceInput": True}),
1121
+ "interpolation_curve": ("FLOAT", {"forceInput": True}),
1122
+
1123
+ },
1124
+ }
1125
+
1126
+ def interpolate(self, coordinates, interpolation_curve):
1127
+ # Parse the JSON string to get the list of coordinates
1128
+ coordinates = json.loads(coordinates.replace("'", '"'))
1129
+
1130
+ # Convert the list of dictionaries to a list of (x, y) tuples for easier processing
1131
+ coordinates = [(coord['x'], coord['y']) for coord in coordinates]
1132
+
1133
+ # Calculate the total length of the original path
1134
+ path_length = sum(np.linalg.norm(np.array(coordinates[i]) - np.array(coordinates[i-1]))
1135
+ for i in range(1, len(coordinates)))
1136
+
1137
+ # Initialize variables for interpolation
1138
+ interpolated_coords = []
1139
+ current_length = 0
1140
+ current_index = 0
1141
+
1142
+ # Iterate over the normalized curve
1143
+ for normalized_length in interpolation_curve:
1144
+ target_length = normalized_length * path_length # Convert to the original scale
1145
+ while current_index < len(coordinates) - 1:
1146
+ segment_start, segment_end = np.array(coordinates[current_index]), np.array(coordinates[current_index + 1])
1147
+ segment_length = np.linalg.norm(segment_end - segment_start)
1148
+ if current_length + segment_length >= target_length:
1149
+ break
1150
+ current_length += segment_length
1151
+ current_index += 1
1152
+
1153
+ # Interpolate between the last two points
1154
+ if current_index < len(coordinates) - 1:
1155
+ p1, p2 = np.array(coordinates[current_index]), np.array(coordinates[current_index + 1])
1156
+ segment_length = np.linalg.norm(p2 - p1)
1157
+ if segment_length > 0:
1158
+ t = (target_length - current_length) / segment_length
1159
+ interpolated_point = p1 + t * (p2 - p1)
1160
+ interpolated_coords.append(interpolated_point.tolist())
1161
+ else:
1162
+ interpolated_coords.append(p1.tolist())
1163
+ else:
1164
+ # If the target_length is at or beyond the end of the path, add the last coordinate
1165
+ interpolated_coords.append(coordinates[-1])
1166
+
1167
+ # Convert back to string format if necessary
1168
+ interpolated_coords_str = "[" + ", ".join([f"{{'x': {round(coord[0])}, 'y': {round(coord[1])}}}" for coord in interpolated_coords]) + "]"
1169
+ print(interpolated_coords_str)
1170
+
1171
+ return (interpolated_coords_str,)
1172
+
1173
+ class DrawInstanceDiffusionTracking:
1174
+
1175
+ RETURN_TYPES = ("IMAGE",)
1176
+ RETURN_NAMES = ("image", )
1177
+ FUNCTION = "draw"
1178
+ CATEGORY = "KJNodes/InstanceDiffusion"
1179
+ DESCRIPTION = """
1180
+ Draws the tracking data from
1181
+ CreateInstanceDiffusionTracking -node.
1182
+
1183
+ """
1184
+
1185
+ @classmethod
1186
+ def INPUT_TYPES(s):
1187
+ return {
1188
+ "required": {
1189
+ "image": ("IMAGE", ),
1190
+ "tracking": ("TRACKING", {"forceInput": True}),
1191
+ "box_line_width": ("INT", {"default": 2, "min": 1, "max": 10, "step": 1}),
1192
+ "draw_text": ("BOOLEAN", {"default": True}),
1193
+ "font": (folder_paths.get_filename_list("kjnodes_fonts"), ),
1194
+ "font_size": ("INT", {"default": 20}),
1195
+ },
1196
+ }
1197
+
1198
+ def draw(self, image, tracking, box_line_width, draw_text, font, font_size):
1199
+ import matplotlib.cm as cm
1200
+
1201
+ modified_images = []
1202
+
1203
+ colormap = cm.get_cmap('rainbow', len(tracking))
1204
+ if draw_text:
1205
+ font_path = folder_paths.get_full_path("kjnodes_fonts", font)
1206
+ font = ImageFont.truetype(font_path, font_size)
1207
+
1208
+ # Iterate over each image in the batch
1209
+ for i in range(image.shape[0]):
1210
+ # Extract the current image and convert it to a PIL image
1211
+ current_image = image[i, :, :, :].permute(2, 0, 1)
1212
+ pil_image = transforms.ToPILImage()(current_image)
1213
+
1214
+ draw = ImageDraw.Draw(pil_image)
1215
+
1216
+ # Iterate over the bounding boxes for the current image
1217
+ for j, (class_name, class_data) in enumerate(tracking.items()):
1218
+ for class_id, bbox_list in class_data.items():
1219
+ # Check if the current index is within the bounds of the bbox_list
1220
+ if i < len(bbox_list):
1221
+ bbox = bbox_list[i]
1222
+ # Ensure bbox is a list or tuple before unpacking
1223
+ if isinstance(bbox, (list, tuple)):
1224
+ x1, y1, x2, y2, _, _ = bbox
1225
+ # Convert coordinates to integers
1226
+ x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
1227
+ # Generate a color from the rainbow colormap
1228
+ color = tuple(int(255 * x) for x in colormap(j / len(tracking)))[:3]
1229
+ # Draw the bounding box on the image with the generated color
1230
+ draw.rectangle([x1, y1, x2, y2], outline=color, width=box_line_width)
1231
+ if draw_text:
1232
+ # Draw the class name and ID as text above the box with the generated color
1233
+ text = f"{class_id}.{class_name}"
1234
+ # Calculate the width and height of the text
1235
+ _, _, text_width, text_height = draw.textbbox((0, 0), text=text, font=font)
1236
+ # Position the text above the top-left corner of the box
1237
+ text_position = (x1, y1 - text_height)
1238
+ draw.text(text_position, text, fill=color, font=font)
1239
+ else:
1240
+ print(f"Unexpected data type for bbox: {type(bbox)}")
1241
+
1242
+ # Convert the drawn image back to a torch tensor and adjust back to (H, W, C)
1243
+ modified_image_tensor = transforms.ToTensor()(pil_image).permute(1, 2, 0)
1244
+ modified_images.append(modified_image_tensor)
1245
+
1246
+ # Stack the modified images back into a batch
1247
+ image_tensor_batch = torch.stack(modified_images).cpu().float()
1248
+
1249
+ return image_tensor_batch,
1250
+
1251
+ class PointsEditor:
1252
+ @classmethod
1253
+ def INPUT_TYPES(cls):
1254
+ return {
1255
+ "required": {
1256
+ "points_store": ("STRING", {"multiline": False}),
1257
+ "coordinates": ("STRING", {"multiline": False}),
1258
+ "neg_coordinates": ("STRING", {"multiline": False}),
1259
+ "bbox_store": ("STRING", {"multiline": False}),
1260
+ "bboxes": ("STRING", {"multiline": False}),
1261
+ "bbox_format": (
1262
+ [
1263
+ 'xyxy',
1264
+ 'xywh',
1265
+ ],
1266
+ ),
1267
+ "width": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}),
1268
+ "height": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}),
1269
+ "normalize": ("BOOLEAN", {"default": False}),
1270
+ },
1271
+ "optional": {
1272
+ "bg_image": ("IMAGE", ),
1273
+ },
1274
+ }
1275
+
1276
+ RETURN_TYPES = ("STRING", "STRING", "BBOX", "MASK", "IMAGE")
1277
+ RETURN_NAMES = ("positive_coords", "negative_coords", "bbox", "bbox_mask", "cropped_image")
1278
+ FUNCTION = "pointdata"
1279
+ CATEGORY = "KJNodes/experimental"
1280
+ DESCRIPTION = """
1281
+ # WORK IN PROGRESS
1282
+ Do not count on this as part of your workflow yet,
1283
+ probably contains lots of bugs and stability is not
1284
+ guaranteed!!
1285
+
1286
+ ## Graphical editor to create coordinates
1287
+
1288
+ **Shift + click** to add a positive (green) point.
1289
+ **Shift + right click** to add a negative (red) point.
1290
+ **Ctrl + click** to draw a box.
1291
+ **Right click on a point** to delete it.
1292
+ Note that you can't delete from start/end of the points array.
1293
+
1294
+ To add an image select the node and copy/paste or drag in the image.
1295
+ Or from the bg_image input on queue (first frame of the batch).
1296
+
1297
+ **THE IMAGE IS SAVED TO THE NODE AND WORKFLOW METADATA**
1298
+ you can clear the image from the context menu by right clicking on the canvas
1299
+
1300
+ """
1301
+
1302
+ def pointdata(self, points_store, bbox_store, width, height, coordinates, neg_coordinates, normalize, bboxes, bbox_format="xyxy", bg_image=None):
1303
+ import io
1304
+ import base64
1305
+
1306
+ coordinates = json.loads(coordinates)
1307
+ pos_coordinates = []
1308
+ for coord in coordinates:
1309
+ coord['x'] = int(round(coord['x']))
1310
+ coord['y'] = int(round(coord['y']))
1311
+ if normalize:
1312
+ norm_x = coord['x'] / width
1313
+ norm_y = coord['y'] / height
1314
+ pos_coordinates.append({'x': norm_x, 'y': norm_y})
1315
+ else:
1316
+ pos_coordinates.append({'x': coord['x'], 'y': coord['y']})
1317
+
1318
+ if neg_coordinates:
1319
+ coordinates = json.loads(neg_coordinates)
1320
+ neg_coordinates = []
1321
+ for coord in coordinates:
1322
+ coord['x'] = int(round(coord['x']))
1323
+ coord['y'] = int(round(coord['y']))
1324
+ if normalize:
1325
+ norm_x = coord['x'] / width
1326
+ norm_y = coord['y'] / height
1327
+ neg_coordinates.append({'x': norm_x, 'y': norm_y})
1328
+ else:
1329
+ neg_coordinates.append({'x': coord['x'], 'y': coord['y']})
1330
+
1331
+ # Create a blank mask
1332
+ mask = np.zeros((height, width), dtype=np.uint8)
1333
+ bboxes = json.loads(bboxes)
1334
+ print(bboxes)
1335
+ valid_bboxes = []
1336
+ for bbox in bboxes:
1337
+ if (bbox.get("startX") is None or
1338
+ bbox.get("startY") is None or
1339
+ bbox.get("endX") is None or
1340
+ bbox.get("endY") is None):
1341
+ continue # Skip this bounding box if any value is None
1342
+ else:
1343
+ # Ensure that endX and endY are greater than startX and startY
1344
+ x_min = min(int(bbox["startX"]), int(bbox["endX"]))
1345
+ y_min = min(int(bbox["startY"]), int(bbox["endY"]))
1346
+ x_max = max(int(bbox["startX"]), int(bbox["endX"]))
1347
+ y_max = max(int(bbox["startY"]), int(bbox["endY"]))
1348
+
1349
+ valid_bboxes.append((x_min, y_min, x_max, y_max))
1350
+
1351
+ bboxes_xyxy = []
1352
+ for bbox in valid_bboxes:
1353
+ x_min, y_min, x_max, y_max = bbox
1354
+ bboxes_xyxy.append((x_min, y_min, x_max, y_max))
1355
+ mask[y_min:y_max, x_min:x_max] = 1 # Fill the bounding box area with 1s
1356
+
1357
+ if bbox_format == "xywh":
1358
+ bboxes_xywh = []
1359
+ for bbox in valid_bboxes:
1360
+ x_min, y_min, x_max, y_max = bbox
1361
+ width = x_max - x_min
1362
+ height = y_max - y_min
1363
+ bboxes_xywh.append((x_min, y_min, width, height))
1364
+ bboxes = bboxes_xywh
1365
+ else:
1366
+ bboxes = bboxes_xyxy
1367
+
1368
+ mask_tensor = torch.from_numpy(mask)
1369
+ mask_tensor = mask_tensor.unsqueeze(0).float().cpu()
1370
+
1371
+ if bg_image is not None and len(valid_bboxes) > 0:
1372
+ x_min, y_min, x_max, y_max = bboxes[0]
1373
+ cropped_image = bg_image[:, y_min:y_max, x_min:x_max, :]
1374
+
1375
+ elif bg_image is not None:
1376
+ cropped_image = bg_image
1377
+
1378
+ if bg_image is None:
1379
+ return (json.dumps(pos_coordinates), json.dumps(neg_coordinates), bboxes, mask_tensor)
1380
+ else:
1381
+ transform = transforms.ToPILImage()
1382
+ image = transform(bg_image[0].permute(2, 0, 1))
1383
+ buffered = io.BytesIO()
1384
+ image.save(buffered, format="JPEG", quality=75)
1385
+
1386
+ # Step 3: Encode the image bytes to a Base64 string
1387
+ img_bytes = buffered.getvalue()
1388
+ img_base64 = base64.b64encode(img_bytes).decode('utf-8')
1389
+
1390
+ return {
1391
+ "ui": {"bg_image": [img_base64]},
1392
+ "result": (json.dumps(pos_coordinates), json.dumps(neg_coordinates), bboxes, mask_tensor, cropped_image)
1393
+ }
ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/image_nodes.py ADDED
@@ -0,0 +1,1678 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import time
3
+ import torch
4
+ import torch.nn.functional as F
5
+ import random
6
+ import math
7
+ import os
8
+ import re
9
+ import json
10
+ import hashlib
11
+ try:
12
+ import cv2
13
+ except:
14
+ print("OpenCV not installed")
15
+ pass
16
+ from PIL import ImageGrab, ImageDraw, ImageFont, Image, ImageSequence, ImageOps
17
+
18
+ from nodes import MAX_RESOLUTION, SaveImage
19
+ from comfy_extras.nodes_mask import ImageCompositeMasked
20
+ from comfy.cli_args import args
21
+ from comfy.utils import ProgressBar, common_upscale
22
+ import folder_paths
23
+ import model_management
24
+
25
+ script_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
26
+
27
+ class ImagePass:
28
+ @classmethod
29
+ def INPUT_TYPES(s):
30
+ return {
31
+ "required": {
32
+ "image": ("IMAGE",),
33
+ },
34
+ }
35
+ RETURN_TYPES = ("IMAGE",)
36
+ FUNCTION = "passthrough"
37
+ CATEGORY = "KJNodes/image"
38
+ DESCRIPTION = """
39
+ Passes the image through without modifying it.
40
+ """
41
+
42
+ def passthrough(self, image):
43
+ return image,
44
+
45
+ class ColorMatch:
46
+ @classmethod
47
+ def INPUT_TYPES(cls):
48
+ return {
49
+ "required": {
50
+ "image_ref": ("IMAGE",),
51
+ "image_target": ("IMAGE",),
52
+ "method": (
53
+ [
54
+ 'mkl',
55
+ 'hm',
56
+ 'reinhard',
57
+ 'mvgd',
58
+ 'hm-mvgd-hm',
59
+ 'hm-mkl-hm',
60
+ ], {
61
+ "default": 'mkl'
62
+ }),
63
+ },
64
+ "optional": {
65
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
66
+ }
67
+ }
68
+
69
+ CATEGORY = "KJNodes/image"
70
+
71
+ RETURN_TYPES = ("IMAGE",)
72
+ RETURN_NAMES = ("image",)
73
+ FUNCTION = "colormatch"
74
+ DESCRIPTION = """
75
+ color-matcher enables color transfer across images which comes in handy for automatic
76
+ color-grading of photographs, paintings and film sequences as well as light-field
77
+ and stopmotion corrections.
78
+
79
+ The methods behind the mappings are based on the approach from Reinhard et al.,
80
+ the Monge-Kantorovich Linearization (MKL) as proposed by Pitie et al. and our analytical solution
81
+ to a Multi-Variate Gaussian Distribution (MVGD) transfer in conjunction with classical histogram
82
+ matching. As shown below our HM-MVGD-HM compound outperforms existing methods.
83
+ https://github.com/hahnec/color-matcher/
84
+
85
+ """
86
+
87
+ def colormatch(self, image_ref, image_target, method, strength=1.0):
88
+ try:
89
+ from color_matcher import ColorMatcher
90
+ except:
91
+ raise Exception("Can't import color-matcher, did you install requirements.txt? Manual install: pip install color-matcher")
92
+ cm = ColorMatcher()
93
+ image_ref = image_ref.cpu()
94
+ image_target = image_target.cpu()
95
+ batch_size = image_target.size(0)
96
+ out = []
97
+ images_target = image_target.squeeze()
98
+ images_ref = image_ref.squeeze()
99
+
100
+ image_ref_np = images_ref.numpy()
101
+ images_target_np = images_target.numpy()
102
+
103
+ if image_ref.size(0) > 1 and image_ref.size(0) != batch_size:
104
+ raise ValueError("ColorMatch: Use either single reference image or a matching batch of reference images.")
105
+
106
+ for i in range(batch_size):
107
+ image_target_np = images_target_np if batch_size == 1 else images_target[i].numpy()
108
+ image_ref_np_i = image_ref_np if image_ref.size(0) == 1 else images_ref[i].numpy()
109
+ try:
110
+ image_result = cm.transfer(src=image_target_np, ref=image_ref_np_i, method=method)
111
+ except BaseException as e:
112
+ print(f"Error occurred during transfer: {e}")
113
+ break
114
+ # Apply the strength multiplier
115
+ image_result = image_target_np + strength * (image_result - image_target_np)
116
+ out.append(torch.from_numpy(image_result))
117
+
118
+ out = torch.stack(out, dim=0).to(torch.float32)
119
+ out.clamp_(0, 1)
120
+ return (out,)
121
+
122
+ class SaveImageWithAlpha:
123
+ def __init__(self):
124
+ self.output_dir = folder_paths.get_output_directory()
125
+ self.type = "output"
126
+ self.prefix_append = ""
127
+
128
+ @classmethod
129
+ def INPUT_TYPES(s):
130
+ return {"required":
131
+ {"images": ("IMAGE", ),
132
+ "mask": ("MASK", ),
133
+ "filename_prefix": ("STRING", {"default": "ComfyUI"})},
134
+ "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
135
+ }
136
+
137
+ RETURN_TYPES = ()
138
+ FUNCTION = "save_images_alpha"
139
+ OUTPUT_NODE = True
140
+ CATEGORY = "KJNodes/image"
141
+ DESCRIPTION = """
142
+ Saves an image and mask as .PNG with the mask as the alpha channel.
143
+ """
144
+
145
+ def save_images_alpha(self, images, mask, filename_prefix="ComfyUI_image_with_alpha", prompt=None, extra_pnginfo=None):
146
+ from PIL.PngImagePlugin import PngInfo
147
+ filename_prefix += self.prefix_append
148
+ full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir, images[0].shape[1], images[0].shape[0])
149
+ results = list()
150
+ if mask.dtype == torch.float16:
151
+ mask = mask.to(torch.float32)
152
+ def file_counter():
153
+ max_counter = 0
154
+ # Loop through the existing files
155
+ for existing_file in os.listdir(full_output_folder):
156
+ # Check if the file matches the expected format
157
+ match = re.fullmatch(fr"{filename}_(\d+)_?\.[a-zA-Z0-9]+", existing_file)
158
+ if match:
159
+ # Extract the numeric portion of the filename
160
+ file_counter = int(match.group(1))
161
+ # Update the maximum counter value if necessary
162
+ if file_counter > max_counter:
163
+ max_counter = file_counter
164
+ return max_counter
165
+
166
+ for image, alpha in zip(images, mask):
167
+ i = 255. * image.cpu().numpy()
168
+ a = 255. * alpha.cpu().numpy()
169
+ img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
170
+
171
+ # Resize the mask to match the image size
172
+ a_resized = Image.fromarray(a).resize(img.size, Image.LANCZOS)
173
+ a_resized = np.clip(a_resized, 0, 255).astype(np.uint8)
174
+ img.putalpha(Image.fromarray(a_resized, mode='L'))
175
+ metadata = None
176
+ if not args.disable_metadata:
177
+ metadata = PngInfo()
178
+ if prompt is not None:
179
+ metadata.add_text("prompt", json.dumps(prompt))
180
+ if extra_pnginfo is not None:
181
+ for x in extra_pnginfo:
182
+ metadata.add_text(x, json.dumps(extra_pnginfo[x]))
183
+
184
+ # Increment the counter by 1 to get the next available value
185
+ counter = file_counter() + 1
186
+ file = f"{filename}_{counter:05}.png"
187
+ img.save(os.path.join(full_output_folder, file), pnginfo=metadata, compress_level=4)
188
+ results.append({
189
+ "filename": file,
190
+ "subfolder": subfolder,
191
+ "type": self.type
192
+ })
193
+
194
+ return { "ui": { "images": results } }
195
+
196
+ class ImageConcanate:
197
+ @classmethod
198
+ def INPUT_TYPES(s):
199
+ return {"required": {
200
+ "image1": ("IMAGE",),
201
+ "image2": ("IMAGE",),
202
+ "direction": (
203
+ [ 'right',
204
+ 'down',
205
+ 'left',
206
+ 'up',
207
+ ],
208
+ {
209
+ "default": 'right'
210
+ }),
211
+ "match_image_size": ("BOOLEAN", {"default": False}),
212
+ }}
213
+
214
+ RETURN_TYPES = ("IMAGE",)
215
+ FUNCTION = "concanate"
216
+ CATEGORY = "KJNodes/image"
217
+ DESCRIPTION = """
218
+ Concatenates the image2 to image1 in the specified direction.
219
+ """
220
+
221
+ def concanate(self, image1, image2, direction, match_image_size, first_image_shape=None):
222
+ # Check if the batch sizes are different
223
+ batch_size1 = image1.shape[0]
224
+ batch_size2 = image2.shape[0]
225
+
226
+ if batch_size1 != batch_size2:
227
+ # Calculate the number of repetitions needed
228
+ max_batch_size = max(batch_size1, batch_size2)
229
+ repeats1 = max_batch_size // batch_size1
230
+ repeats2 = max_batch_size // batch_size2
231
+
232
+ # Repeat the images to match the largest batch size
233
+ image1 = image1.repeat(repeats1, 1, 1, 1)
234
+ image2 = image2.repeat(repeats2, 1, 1, 1)
235
+
236
+ if match_image_size:
237
+ # Use first_image_shape if provided; otherwise, default to image1's shape
238
+ target_shape = first_image_shape if first_image_shape is not None else image1.shape
239
+
240
+ original_height = image2.shape[1]
241
+ original_width = image2.shape[2]
242
+ original_aspect_ratio = original_width / original_height
243
+
244
+ if direction in ['left', 'right']:
245
+ # Match the height and adjust the width to preserve aspect ratio
246
+ target_height = target_shape[1] # B, H, W, C format
247
+ target_width = int(target_height * original_aspect_ratio)
248
+ elif direction in ['up', 'down']:
249
+ # Match the width and adjust the height to preserve aspect ratio
250
+ target_width = target_shape[2] # B, H, W, C format
251
+ target_height = int(target_width / original_aspect_ratio)
252
+
253
+ # Adjust image2 to the expected format for common_upscale
254
+ image2_for_upscale = image2.movedim(-1, 1) # Move C to the second position (B, C, H, W)
255
+
256
+ # Resize image2 to match the target size while preserving aspect ratio
257
+ image2_resized = common_upscale(image2_for_upscale, target_width, target_height, "lanczos", "disabled")
258
+
259
+ # Adjust image2 back to the original format (B, H, W, C) after resizing
260
+ image2_resized = image2_resized.movedim(1, -1)
261
+ else:
262
+ image2_resized = image2
263
+
264
+ # Concatenate based on the specified direction
265
+ if direction == 'right':
266
+ concatenated_image = torch.cat((image1, image2_resized), dim=2) # Concatenate along width
267
+ elif direction == 'down':
268
+ concatenated_image = torch.cat((image1, image2_resized), dim=1) # Concatenate along height
269
+ elif direction == 'left':
270
+ concatenated_image = torch.cat((image2_resized, image1), dim=2) # Concatenate along width
271
+ elif direction == 'up':
272
+ concatenated_image = torch.cat((image2_resized, image1), dim=1) # Concatenate along height
273
+ return concatenated_image,
274
+
275
+ class ImageGridComposite2x2:
276
+ @classmethod
277
+ def INPUT_TYPES(s):
278
+ return {"required": {
279
+ "image1": ("IMAGE",),
280
+ "image2": ("IMAGE",),
281
+ "image3": ("IMAGE",),
282
+ "image4": ("IMAGE",),
283
+ }}
284
+
285
+ RETURN_TYPES = ("IMAGE",)
286
+ FUNCTION = "compositegrid"
287
+ CATEGORY = "KJNodes/image"
288
+ DESCRIPTION = """
289
+ Concatenates the 4 input images into a 2x2 grid.
290
+ """
291
+
292
+ def compositegrid(self, image1, image2, image3, image4):
293
+ top_row = torch.cat((image1, image2), dim=2)
294
+ bottom_row = torch.cat((image3, image4), dim=2)
295
+ grid = torch.cat((top_row, bottom_row), dim=1)
296
+ return (grid,)
297
+
298
+ class ImageGridComposite3x3:
299
+ @classmethod
300
+ def INPUT_TYPES(s):
301
+ return {"required": {
302
+ "image1": ("IMAGE",),
303
+ "image2": ("IMAGE",),
304
+ "image3": ("IMAGE",),
305
+ "image4": ("IMAGE",),
306
+ "image5": ("IMAGE",),
307
+ "image6": ("IMAGE",),
308
+ "image7": ("IMAGE",),
309
+ "image8": ("IMAGE",),
310
+ "image9": ("IMAGE",),
311
+ }}
312
+
313
+ RETURN_TYPES = ("IMAGE",)
314
+ FUNCTION = "compositegrid"
315
+ CATEGORY = "KJNodes/image"
316
+ DESCRIPTION = """
317
+ Concatenates the 9 input images into a 3x3 grid.
318
+ """
319
+
320
+ def compositegrid(self, image1, image2, image3, image4, image5, image6, image7, image8, image9):
321
+ top_row = torch.cat((image1, image2, image3), dim=2)
322
+ mid_row = torch.cat((image4, image5, image6), dim=2)
323
+ bottom_row = torch.cat((image7, image8, image9), dim=2)
324
+ grid = torch.cat((top_row, mid_row, bottom_row), dim=1)
325
+ return (grid,)
326
+
327
+ class ImageBatchTestPattern:
328
+ @classmethod
329
+ def INPUT_TYPES(s):
330
+ return {"required": {
331
+ "batch_size": ("INT", {"default": 1,"min": 1, "max": 255, "step": 1}),
332
+ "start_from": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}),
333
+ "text_x": ("INT", {"default": 256,"min": 0, "max": 4096, "step": 1}),
334
+ "text_y": ("INT", {"default": 256,"min": 0, "max": 4096, "step": 1}),
335
+ "width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
336
+ "height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
337
+ "font": (folder_paths.get_filename_list("kjnodes_fonts"), ),
338
+ "font_size": ("INT", {"default": 255,"min": 8, "max": 4096, "step": 1}),
339
+ }}
340
+
341
+ RETURN_TYPES = ("IMAGE",)
342
+ FUNCTION = "generatetestpattern"
343
+ CATEGORY = "KJNodes/text"
344
+
345
+ def generatetestpattern(self, batch_size, font, font_size, start_from, width, height, text_x, text_y):
346
+ out = []
347
+ # Generate the sequential numbers for each image
348
+ numbers = np.arange(start_from, start_from + batch_size)
349
+ font_path = folder_paths.get_full_path("kjnodes_fonts", font)
350
+
351
+ for number in numbers:
352
+ # Create a black image with the number as a random color text
353
+ image = Image.new("RGB", (width, height), color='black')
354
+ draw = ImageDraw.Draw(image)
355
+
356
+ # Generate a random color for the text
357
+ font_color = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
358
+
359
+ font = ImageFont.truetype(font_path, font_size)
360
+
361
+ # Get the size of the text and position it in the center
362
+ text = str(number)
363
+
364
+ try:
365
+ draw.text((text_x, text_y), text, font=font, fill=font_color, features=['-liga'])
366
+ except:
367
+ draw.text((text_x, text_y), text, font=font, fill=font_color,)
368
+
369
+ # Convert the image to a numpy array and normalize the pixel values
370
+ image_np = np.array(image).astype(np.float32) / 255.0
371
+ image_tensor = torch.from_numpy(image_np).unsqueeze(0)
372
+ out.append(image_tensor)
373
+ out_tensor = torch.cat(out, dim=0)
374
+
375
+ return (out_tensor,)
376
+
377
+ class ImageGrabPIL:
378
+
379
+ @classmethod
380
+ def IS_CHANGED(cls):
381
+
382
+ return
383
+
384
+ RETURN_TYPES = ("IMAGE",)
385
+ RETURN_NAMES = ("image",)
386
+ FUNCTION = "screencap"
387
+ CATEGORY = "KJNodes/experimental"
388
+ DESCRIPTION = """
389
+ Captures an area specified by screen coordinates.
390
+ Can be used for realtime diffusion with autoqueue.
391
+ """
392
+
393
+ @classmethod
394
+ def INPUT_TYPES(s):
395
+ return {
396
+ "required": {
397
+ "x": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}),
398
+ "y": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}),
399
+ "width": ("INT", {"default": 512,"min": 0, "max": 4096, "step": 1}),
400
+ "height": ("INT", {"default": 512,"min": 0, "max": 4096, "step": 1}),
401
+ "num_frames": ("INT", {"default": 1,"min": 1, "max": 255, "step": 1}),
402
+ "delay": ("FLOAT", {"default": 0.1,"min": 0.0, "max": 10.0, "step": 0.01}),
403
+ },
404
+ }
405
+
406
+ def screencap(self, x, y, width, height, num_frames, delay):
407
+ start_time = time.time()
408
+ captures = []
409
+ bbox = (x, y, x + width, y + height)
410
+
411
+ for _ in range(num_frames):
412
+ # Capture screen
413
+ screen_capture = ImageGrab.grab(bbox=bbox)
414
+ screen_capture_torch = torch.from_numpy(np.array(screen_capture, dtype=np.float32) / 255.0).unsqueeze(0)
415
+ captures.append(screen_capture_torch)
416
+
417
+ # Wait for a short delay if more than one frame is to be captured
418
+ if num_frames > 1:
419
+ time.sleep(delay)
420
+
421
+ elapsed_time = time.time() - start_time
422
+ print(f"screengrab took {elapsed_time} seconds.")
423
+
424
+ return (torch.cat(captures, dim=0),)
425
+
426
+ class Screencap_mss:
427
+
428
+ @classmethod
429
+ def IS_CHANGED(cls):
430
+
431
+ return
432
+
433
+ RETURN_TYPES = ("IMAGE",)
434
+ RETURN_NAMES = ("image",)
435
+ FUNCTION = "screencap"
436
+ CATEGORY = "KJNodes/experimental"
437
+ DESCRIPTION = """
438
+ Captures an area specified by screen coordinates.
439
+ Can be used for realtime diffusion with autoqueue.
440
+ """
441
+
442
+ @classmethod
443
+ def INPUT_TYPES(s):
444
+ return {
445
+ "required": {
446
+ "x": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}),
447
+ "y": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}),
448
+ "width": ("INT", {"default": 512,"min": 0, "max": 4096, "step": 1}),
449
+ "height": ("INT", {"default": 512,"min": 0, "max": 4096, "step": 1}),
450
+ "num_frames": ("INT", {"default": 1,"min": 1, "max": 255, "step": 1}),
451
+ "delay": ("FLOAT", {"default": 0.1,"min": 0.0, "max": 10.0, "step": 0.01}),
452
+ },
453
+ }
454
+
455
+ def screencap(self, x, y, width, height, num_frames, delay):
456
+ from mss import mss
457
+ captures = []
458
+ with mss() as sct:
459
+ bbox = {'top': y, 'left': x, 'width': width, 'height': height}
460
+
461
+ for _ in range(num_frames):
462
+ sct_img = sct.grab(bbox)
463
+ img_np = np.array(sct_img)
464
+ img_torch = torch.from_numpy(img_np[..., [2, 1, 0]]).float() / 255.0
465
+ captures.append(img_torch)
466
+
467
+ if num_frames > 1:
468
+ time.sleep(delay)
469
+
470
+ return (torch.stack(captures, 0),)
471
+
472
+ class WebcamCaptureCV2:
473
+
474
+ @classmethod
475
+ def IS_CHANGED(cls):
476
+ return
477
+
478
+ RETURN_TYPES = ("IMAGE",)
479
+ RETURN_NAMES = ("image",)
480
+ FUNCTION = "capture"
481
+ CATEGORY = "KJNodes/experimental"
482
+ DESCRIPTION = """
483
+ Captures a frame from a webcam using CV2.
484
+ Can be used for realtime diffusion with autoqueue.
485
+ """
486
+
487
+ @classmethod
488
+ def INPUT_TYPES(s):
489
+ return {
490
+ "required": {
491
+ "x": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}),
492
+ "y": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}),
493
+ "width": ("INT", {"default": 512,"min": 0, "max": 4096, "step": 1}),
494
+ "height": ("INT", {"default": 512,"min": 0, "max": 4096, "step": 1}),
495
+ "cam_index": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}),
496
+ "release": ("BOOLEAN", {"default": False}),
497
+ },
498
+ }
499
+
500
+ def capture(self, x, y, cam_index, width, height, release):
501
+ # Check if the camera index has changed or the capture object doesn't exist
502
+ if not hasattr(self, "cap") or self.cap is None or self.current_cam_index != cam_index:
503
+ if hasattr(self, "cap") and self.cap is not None:
504
+ self.cap.release()
505
+ self.current_cam_index = cam_index
506
+ self.cap = cv2.VideoCapture(cam_index)
507
+ try:
508
+ self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
509
+ self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
510
+ except:
511
+ pass
512
+ if not self.cap.isOpened():
513
+ raise Exception("Could not open webcam")
514
+
515
+ ret, frame = self.cap.read()
516
+ if not ret:
517
+ raise Exception("Failed to capture image from webcam")
518
+
519
+ # Crop the frame to the specified bbox
520
+ frame = frame[y:y+height, x:x+width]
521
+ img_torch = torch.from_numpy(frame[..., [2, 1, 0]]).float() / 255.0
522
+
523
+ if release:
524
+ self.cap.release()
525
+ self.cap = None
526
+
527
+ return (img_torch.unsqueeze(0),)
528
+
529
+ class AddLabel:
530
+ @classmethod
531
+ def INPUT_TYPES(s):
532
+ return {"required": {
533
+ "image":("IMAGE",),
534
+ "text_x": ("INT", {"default": 10, "min": 0, "max": 4096, "step": 1}),
535
+ "text_y": ("INT", {"default": 2, "min": 0, "max": 4096, "step": 1}),
536
+ "height": ("INT", {"default": 48, "min": 0, "max": 4096, "step": 1}),
537
+ "font_size": ("INT", {"default": 32, "min": 0, "max": 4096, "step": 1}),
538
+ "font_color": ("STRING", {"default": "white"}),
539
+ "label_color": ("STRING", {"default": "black"}),
540
+ "font": (folder_paths.get_filename_list("kjnodes_fonts"), ),
541
+ "text": ("STRING", {"default": "Text"}),
542
+ "direction": (
543
+ [ 'up',
544
+ 'down',
545
+ 'left',
546
+ 'right',
547
+ 'overlay'
548
+ ],
549
+ {
550
+ "default": 'up'
551
+ }),
552
+ },
553
+ "optional":{
554
+ "caption": ("STRING", {"default": "", "forceInput": True}),
555
+ }
556
+ }
557
+ RETURN_TYPES = ("IMAGE",)
558
+ FUNCTION = "addlabel"
559
+ CATEGORY = "KJNodes/text"
560
+ DESCRIPTION = """
561
+ Creates a new with the given text, and concatenates it to
562
+ either above or below the input image.
563
+ Note that this changes the input image's height!
564
+ Fonts are loaded from this folder:
565
+ ComfyUI/custom_nodes/ComfyUI-KJNodes/fonts
566
+ """
567
+
568
+ def addlabel(self, image, text_x, text_y, text, height, font_size, font_color, label_color, font, direction, caption=""):
569
+ batch_size = image.shape[0]
570
+ width = image.shape[2]
571
+
572
+ font_path = os.path.join(script_directory, "fonts", "TTNorms-Black.otf") if font == "TTNorms-Black.otf" else folder_paths.get_full_path("kjnodes_fonts", font)
573
+
574
+ def process_image(input_image, caption_text):
575
+ if direction == 'overlay':
576
+ pil_image = Image.fromarray((input_image.cpu().numpy() * 255).astype(np.uint8))
577
+ else:
578
+ label_image = Image.new("RGB", (width, height), label_color)
579
+ pil_image = label_image
580
+
581
+ draw = ImageDraw.Draw(pil_image)
582
+ font = ImageFont.truetype(font_path, font_size)
583
+
584
+ words = caption_text.split()
585
+
586
+ lines = []
587
+ current_line = []
588
+ current_line_width = 0
589
+ for word in words:
590
+ word_width = font.getbbox(word)[2]
591
+ if current_line_width + word_width <= width - 2 * text_x:
592
+ current_line.append(word)
593
+ current_line_width += word_width + font.getbbox(" ")[2] # Add space width
594
+ else:
595
+ lines.append(" ".join(current_line))
596
+ current_line = [word]
597
+ current_line_width = word_width
598
+
599
+ if current_line:
600
+ lines.append(" ".join(current_line))
601
+
602
+ y_offset = text_y
603
+ for line in lines:
604
+ try:
605
+ draw.text((text_x, y_offset), line, font=font, fill=font_color, features=['-liga'])
606
+ except:
607
+ draw.text((text_x, y_offset), line, font=font, fill=font_color)
608
+ y_offset += font_size # Move to the next line
609
+
610
+ processed_image = torch.from_numpy(np.array(pil_image).astype(np.float32) / 255.0).unsqueeze(0)
611
+ return processed_image
612
+
613
+ if caption == "":
614
+ processed_images = [process_image(img, text) for img in image]
615
+ else:
616
+ assert len(caption) == batch_size, f"Number of captions {(len(caption))} does not match number of images"
617
+ processed_images = [process_image(img, cap) for img, cap in zip(image, caption)]
618
+ processed_batch = torch.cat(processed_images, dim=0)
619
+
620
+ # Combine images based on direction
621
+ if direction == 'down':
622
+ combined_images = torch.cat((image, processed_batch), dim=1)
623
+ elif direction == 'up':
624
+ combined_images = torch.cat((processed_batch, image), dim=1)
625
+ elif direction == 'left':
626
+ processed_batch = torch.rot90(processed_batch, 3, (2, 3)).permute(0, 3, 1, 2)
627
+ combined_images = torch.cat((processed_batch, image), dim=2)
628
+ elif direction == 'right':
629
+ processed_batch = torch.rot90(processed_batch, 3, (2, 3)).permute(0, 3, 1, 2)
630
+ combined_images = torch.cat((image, processed_batch), dim=2)
631
+ else:
632
+ combined_images = processed_batch
633
+
634
+ return (combined_images,)
635
+
636
+ class GetImageSizeAndCount:
637
+ @classmethod
638
+ def INPUT_TYPES(s):
639
+ return {"required": {
640
+ "image": ("IMAGE",),
641
+ }}
642
+
643
+ RETURN_TYPES = ("IMAGE","INT", "INT", "INT",)
644
+ RETURN_NAMES = ("image", "width", "height", "count",)
645
+ FUNCTION = "getsize"
646
+ CATEGORY = "KJNodes/image"
647
+ DESCRIPTION = """
648
+ Returns width, height and batch size of the image,
649
+ and passes it through unchanged.
650
+
651
+ """
652
+
653
+ def getsize(self, image):
654
+ width = image.shape[2]
655
+ height = image.shape[1]
656
+ count = image.shape[0]
657
+ return {"ui": {
658
+ "text": [f"{count}x{width}x{height}"]},
659
+ "result": (image, width, height, count)
660
+ }
661
+
662
+ class ImageBatchRepeatInterleaving:
663
+
664
+ RETURN_TYPES = ("IMAGE",)
665
+ FUNCTION = "repeat"
666
+ CATEGORY = "KJNodes/image"
667
+ DESCRIPTION = """
668
+ Repeats each image in a batch by the specified number of times.
669
+ Example batch of 5 images: 0, 1 ,2, 3, 4
670
+ with repeats 2 becomes batch of 10 images: 0, 0, 1, 1, 2, 2, 3, 3, 4, 4
671
+ """
672
+
673
+ @classmethod
674
+ def INPUT_TYPES(s):
675
+ return {
676
+ "required": {
677
+ "images": ("IMAGE",),
678
+ "repeats": ("INT", {"default": 1, "min": 1, "max": 4096}),
679
+ },
680
+ }
681
+
682
+ def repeat(self, images, repeats):
683
+
684
+ repeated_images = torch.repeat_interleave(images, repeats=repeats, dim=0)
685
+ return (repeated_images, )
686
+
687
+ class ImageUpscaleWithModelBatched:
688
+ @classmethod
689
+ def INPUT_TYPES(s):
690
+ return {"required": { "upscale_model": ("UPSCALE_MODEL",),
691
+ "images": ("IMAGE",),
692
+ "per_batch": ("INT", {"default": 16, "min": 1, "max": 4096, "step": 1}),
693
+ }}
694
+ RETURN_TYPES = ("IMAGE",)
695
+ FUNCTION = "upscale"
696
+ CATEGORY = "KJNodes/image"
697
+ DESCRIPTION = """
698
+ Same as ComfyUI native model upscaling node,
699
+ but allows setting sub-batches for reduced VRAM usage.
700
+ """
701
+ def upscale(self, upscale_model, images, per_batch):
702
+
703
+ device = model_management.get_torch_device()
704
+ upscale_model.to(device)
705
+ in_img = images.movedim(-1,-3)
706
+
707
+ steps = in_img.shape[0]
708
+ pbar = ProgressBar(steps)
709
+ t = []
710
+
711
+ for start_idx in range(0, in_img.shape[0], per_batch):
712
+ sub_images = upscale_model(in_img[start_idx:start_idx+per_batch].to(device))
713
+ t.append(sub_images.cpu())
714
+ # Calculate the number of images processed in this batch
715
+ batch_count = sub_images.shape[0]
716
+ # Update the progress bar by the number of images processed in this batch
717
+ pbar.update(batch_count)
718
+ upscale_model.cpu()
719
+
720
+ t = torch.cat(t, dim=0).permute(0, 2, 3, 1).cpu()
721
+
722
+ return (t,)
723
+
724
+ class ImageNormalize_Neg1_To_1:
725
+ @classmethod
726
+ def INPUT_TYPES(s):
727
+ return {"required": {
728
+ "images": ("IMAGE",),
729
+
730
+ }}
731
+ RETURN_TYPES = ("IMAGE",)
732
+ FUNCTION = "normalize"
733
+ CATEGORY = "KJNodes/image"
734
+ DESCRIPTION = """
735
+ Normalize the images to be in the range [-1, 1]
736
+ """
737
+
738
+ def normalize(self,images):
739
+ images = images * 2.0 - 1.0
740
+ return (images,)
741
+
742
+ class RemapImageRange:
743
+ @classmethod
744
+ def INPUT_TYPES(s):
745
+ return {"required": {
746
+ "image": ("IMAGE",),
747
+ "min": ("FLOAT", {"default": 0.0,"min": -10.0, "max": 1.0, "step": 0.01}),
748
+ "max": ("FLOAT", {"default": 1.0,"min": 0.0, "max": 10.0, "step": 0.01}),
749
+ "clamp": ("BOOLEAN", {"default": True}),
750
+ },
751
+ }
752
+
753
+ RETURN_TYPES = ("IMAGE",)
754
+ FUNCTION = "remap"
755
+ CATEGORY = "KJNodes/image"
756
+ DESCRIPTION = """
757
+ Remaps the image values to the specified range.
758
+ """
759
+
760
+ def remap(self, image, min, max, clamp):
761
+ if image.dtype == torch.float16:
762
+ image = image.to(torch.float32)
763
+ image = min + image * (max - min)
764
+ if clamp:
765
+ image = torch.clamp(image, min=0.0, max=1.0)
766
+ return (image, )
767
+
768
+ class SplitImageChannels:
769
+ @classmethod
770
+ def INPUT_TYPES(s):
771
+ return {"required": {
772
+ "image": ("IMAGE",),
773
+ },
774
+ }
775
+
776
+ RETURN_TYPES = ("IMAGE", "IMAGE", "IMAGE", "MASK")
777
+ RETURN_NAMES = ("red", "green", "blue", "mask")
778
+ FUNCTION = "split"
779
+ CATEGORY = "KJNodes/image"
780
+ DESCRIPTION = """
781
+ Splits image channels into images where the selected channel
782
+ is repeated for all channels, and the alpha as a mask.
783
+ """
784
+
785
+ def split(self, image):
786
+ red = image[:, :, :, 0:1] # Red channel
787
+ green = image[:, :, :, 1:2] # Green channel
788
+ blue = image[:, :, :, 2:3] # Blue channel
789
+ alpha = image[:, :, :, 3:4] # Alpha channel
790
+ alpha = alpha.squeeze(-1)
791
+
792
+ # Repeat the selected channel for all channels
793
+ red = torch.cat([red, red, red], dim=3)
794
+ green = torch.cat([green, green, green], dim=3)
795
+ blue = torch.cat([blue, blue, blue], dim=3)
796
+ return (red, green, blue, alpha)
797
+
798
+ class MergeImageChannels:
799
+ @classmethod
800
+ def INPUT_TYPES(s):
801
+ return {"required": {
802
+ "red": ("IMAGE",),
803
+ "green": ("IMAGE",),
804
+ "blue": ("IMAGE",),
805
+
806
+ },
807
+ "optional": {
808
+ "alpha": ("MASK", {"default": None}),
809
+ },
810
+ }
811
+
812
+ RETURN_TYPES = ("IMAGE",)
813
+ RETURN_NAMES = ("image",)
814
+ FUNCTION = "merge"
815
+ CATEGORY = "KJNodes/image"
816
+ DESCRIPTION = """
817
+ Merges channel data into an image.
818
+ """
819
+
820
+ def merge(self, red, green, blue, alpha=None):
821
+ image = torch.stack([
822
+ red[..., 0, None], # Red channel
823
+ green[..., 1, None], # Green channel
824
+ blue[..., 2, None] # Blue channel
825
+ ], dim=-1)
826
+ image = image.squeeze(-2)
827
+ if alpha is not None:
828
+ image = torch.cat([image, alpha.unsqueeze(-1)], dim=-1)
829
+ return (image,)
830
+
831
+ class ImagePadForOutpaintMasked:
832
+
833
+ @classmethod
834
+ def INPUT_TYPES(s):
835
+ return {
836
+ "required": {
837
+ "image": ("IMAGE",),
838
+ "left": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
839
+ "top": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
840
+ "right": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
841
+ "bottom": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
842
+ "feathering": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
843
+ },
844
+ "optional": {
845
+ "mask": ("MASK",),
846
+ }
847
+ }
848
+
849
+ RETURN_TYPES = ("IMAGE", "MASK")
850
+ FUNCTION = "expand_image"
851
+
852
+ CATEGORY = "image"
853
+
854
+ def expand_image(self, image, left, top, right, bottom, feathering, mask=None):
855
+ if mask is not None:
856
+ if torch.allclose(mask, torch.zeros_like(mask)):
857
+ print("Warning: The incoming mask is fully black. Handling it as None.")
858
+ mask = None
859
+ B, H, W, C = image.size()
860
+
861
+ new_image = torch.ones(
862
+ (B, H + top + bottom, W + left + right, C),
863
+ dtype=torch.float32,
864
+ ) * 0.5
865
+
866
+ new_image[:, top:top + H, left:left + W, :] = image
867
+
868
+ if mask is None:
869
+ new_mask = torch.ones(
870
+ (B, H + top + bottom, W + left + right),
871
+ dtype=torch.float32,
872
+ )
873
+
874
+ t = torch.zeros(
875
+ (B, H, W),
876
+ dtype=torch.float32
877
+ )
878
+ else:
879
+ # If a mask is provided, pad it to fit the new image size
880
+ mask = F.pad(mask, (left, right, top, bottom), mode='constant', value=0)
881
+ mask = 1 - mask
882
+ t = torch.zeros_like(mask)
883
+
884
+ if feathering > 0 and feathering * 2 < H and feathering * 2 < W:
885
+
886
+ for i in range(H):
887
+ for j in range(W):
888
+ dt = i if top != 0 else H
889
+ db = H - i if bottom != 0 else H
890
+
891
+ dl = j if left != 0 else W
892
+ dr = W - j if right != 0 else W
893
+
894
+ d = min(dt, db, dl, dr)
895
+
896
+ if d >= feathering:
897
+ continue
898
+
899
+ v = (feathering - d) / feathering
900
+
901
+ if mask is None:
902
+ t[:, i, j] = v * v
903
+ else:
904
+ t[:, top + i, left + j] = v * v
905
+
906
+ if mask is None:
907
+ new_mask[:, top:top + H, left:left + W] = t
908
+ return (new_image, new_mask,)
909
+ else:
910
+ return (new_image, mask,)
911
+
912
+ class ImagePadForOutpaintTargetSize:
913
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
914
+ @classmethod
915
+ def INPUT_TYPES(s):
916
+ return {
917
+ "required": {
918
+ "image": ("IMAGE",),
919
+ "target_width": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
920
+ "target_height": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 8}),
921
+ "feathering": ("INT", {"default": 0, "min": 0, "max": MAX_RESOLUTION, "step": 1}),
922
+ "upscale_method": (s.upscale_methods,),
923
+ },
924
+ "optional": {
925
+ "mask": ("MASK",),
926
+ }
927
+ }
928
+
929
+ RETURN_TYPES = ("IMAGE", "MASK")
930
+ FUNCTION = "expand_image"
931
+
932
+ CATEGORY = "image"
933
+
934
+ def expand_image(self, image, target_width, target_height, feathering, upscale_method, mask=None):
935
+ B, H, W, C = image.size()
936
+ new_height = 0
937
+ new_width = 0
938
+ # Calculate the scaling factor while maintaining aspect ratio
939
+ scaling_factor = min(target_width / W, target_height / H)
940
+
941
+ # Check if the image needs to be downscaled
942
+ if scaling_factor < 1:
943
+ image = image.movedim(-1,1)
944
+ # Calculate the new width and height after downscaling
945
+ new_width = int(W * scaling_factor)
946
+ new_height = int(H * scaling_factor)
947
+
948
+ # Downscale the image
949
+ image_scaled = common_upscale(image, new_width, new_height, upscale_method, "disabled").movedim(1,-1)
950
+ if mask is not None:
951
+ mask_scaled = mask.unsqueeze(0) # Add an extra dimension for batch size
952
+ mask_scaled = F.interpolate(mask_scaled, size=(new_height, new_width), mode="nearest")
953
+ mask_scaled = mask_scaled.squeeze(0) # Remove the extra dimension after interpolation
954
+ else:
955
+ mask_scaled = mask
956
+ else:
957
+ # If downscaling is not needed, use the original image dimensions
958
+ image_scaled = image
959
+ mask_scaled = mask
960
+
961
+ # Calculate how much padding is needed to reach the target dimensions
962
+ pad_top = max(0, (target_height - new_height) // 2)
963
+ pad_bottom = max(0, target_height - new_height - pad_top)
964
+ pad_left = max(0, (target_width - new_width) // 2)
965
+ pad_right = max(0, target_width - new_width - pad_left)
966
+
967
+ # Now call the original expand_image with the calculated padding
968
+ return ImagePadForOutpaintMasked.expand_image(self, image_scaled, pad_left, pad_top, pad_right, pad_bottom, feathering, mask_scaled)
969
+
970
+ class ImageAndMaskPreview(SaveImage):
971
+ def __init__(self):
972
+ self.output_dir = folder_paths.get_temp_directory()
973
+ self.type = "temp"
974
+ self.prefix_append = "_temp_" + ''.join(random.choice("abcdefghijklmnopqrstupvxyz") for x in range(5))
975
+ self.compress_level = 4
976
+
977
+ @classmethod
978
+ def INPUT_TYPES(s):
979
+ return {
980
+ "required": {
981
+ "mask_opacity": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
982
+ "mask_color": ("STRING", {"default": "255, 255, 255"}),
983
+ "pass_through": ("BOOLEAN", {"default": False}),
984
+ },
985
+ "optional": {
986
+ "image": ("IMAGE",),
987
+ "mask": ("MASK",),
988
+ },
989
+ "hidden": {"prompt": "PROMPT", "extra_pnginfo": "EXTRA_PNGINFO"},
990
+ }
991
+ RETURN_TYPES = ("IMAGE",)
992
+ RETURN_NAMES = ("composite",)
993
+ FUNCTION = "execute"
994
+ CATEGORY = "KJNodes"
995
+ DESCRIPTION = """
996
+ Preview an image or a mask, when both inputs are used
997
+ composites the mask on top of the image.
998
+ with pass_through on the preview is disabled and the
999
+ composite is returned from the composite slot instead,
1000
+ this allows for the preview to be passed for video combine
1001
+ nodes for example.
1002
+ """
1003
+
1004
+ def execute(self, mask_opacity, mask_color, pass_through, filename_prefix="ComfyUI", image=None, mask=None, prompt=None, extra_pnginfo=None):
1005
+ if mask is not None and image is None:
1006
+ preview = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])).movedim(1, -1).expand(-1, -1, -1, 3)
1007
+ elif mask is None and image is not None:
1008
+ preview = image
1009
+ elif mask is not None and image is not None:
1010
+ mask_adjusted = mask * mask_opacity
1011
+ mask_image = mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])).movedim(1, -1).expand(-1, -1, -1, 3).clone()
1012
+
1013
+ if ',' in mask_color:
1014
+ color_list = np.clip([int(channel) for channel in mask_color.split(',')], 0, 255) # RGB format
1015
+ else:
1016
+ mask_color = mask_color.lstrip('#')
1017
+ color_list = [int(mask_color[i:i+2], 16) for i in (0, 2, 4)] # Hex format
1018
+ mask_image[:, :, :, 0] = color_list[0] / 255 # Red channel
1019
+ mask_image[:, :, :, 1] = color_list[1] / 255 # Green channel
1020
+ mask_image[:, :, :, 2] = color_list[2] / 255 # Blue channel
1021
+
1022
+ preview, = ImageCompositeMasked.composite(self, image, mask_image, 0, 0, True, mask_adjusted)
1023
+ if pass_through:
1024
+ return (preview, )
1025
+ return(self.save_images(preview, filename_prefix, prompt, extra_pnginfo))
1026
+
1027
+ class CrossFadeImages:
1028
+
1029
+ RETURN_TYPES = ("IMAGE",)
1030
+ FUNCTION = "crossfadeimages"
1031
+ CATEGORY = "KJNodes/image"
1032
+
1033
+ @classmethod
1034
+ def INPUT_TYPES(s):
1035
+ return {
1036
+ "required": {
1037
+ "images_1": ("IMAGE",),
1038
+ "images_2": ("IMAGE",),
1039
+ "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out", "bounce", "elastic", "glitchy", "exponential_ease_out"],),
1040
+ "transition_start_index": ("INT", {"default": 1,"min": 0, "max": 4096, "step": 1}),
1041
+ "transitioning_frames": ("INT", {"default": 1,"min": 0, "max": 4096, "step": 1}),
1042
+ "start_level": ("FLOAT", {"default": 0.0,"min": 0.0, "max": 1.0, "step": 0.01}),
1043
+ "end_level": ("FLOAT", {"default": 1.0,"min": 0.0, "max": 1.0, "step": 0.01}),
1044
+ },
1045
+ }
1046
+
1047
+ def crossfadeimages(self, images_1, images_2, transition_start_index, transitioning_frames, interpolation, start_level, end_level):
1048
+
1049
+ def crossfade(images_1, images_2, alpha):
1050
+ crossfade = (1 - alpha) * images_1 + alpha * images_2
1051
+ return crossfade
1052
+ def ease_in(t):
1053
+ return t * t
1054
+ def ease_out(t):
1055
+ return 1 - (1 - t) * (1 - t)
1056
+ def ease_in_out(t):
1057
+ return 3 * t * t - 2 * t * t * t
1058
+ def bounce(t):
1059
+ if t < 0.5:
1060
+ return self.ease_out(t * 2) * 0.5
1061
+ else:
1062
+ return self.ease_in((t - 0.5) * 2) * 0.5 + 0.5
1063
+ def elastic(t):
1064
+ return math.sin(13 * math.pi / 2 * t) * math.pow(2, 10 * (t - 1))
1065
+ def glitchy(t):
1066
+ return t + 0.1 * math.sin(40 * t)
1067
+ def exponential_ease_out(t):
1068
+ return 1 - (1 - t) ** 4
1069
+
1070
+ easing_functions = {
1071
+ "linear": lambda t: t,
1072
+ "ease_in": ease_in,
1073
+ "ease_out": ease_out,
1074
+ "ease_in_out": ease_in_out,
1075
+ "bounce": bounce,
1076
+ "elastic": elastic,
1077
+ "glitchy": glitchy,
1078
+ "exponential_ease_out": exponential_ease_out,
1079
+ }
1080
+
1081
+ crossfade_images = []
1082
+
1083
+ alphas = torch.linspace(start_level, end_level, transitioning_frames)
1084
+ for i in range(transitioning_frames):
1085
+ alpha = alphas[i]
1086
+ image1 = images_1[i + transition_start_index]
1087
+ image2 = images_2[i + transition_start_index]
1088
+ easing_function = easing_functions.get(interpolation)
1089
+ alpha = easing_function(alpha) # Apply the easing function to the alpha value
1090
+
1091
+ crossfade_image = crossfade(image1, image2, alpha)
1092
+ crossfade_images.append(crossfade_image)
1093
+
1094
+ # Convert crossfade_images to tensor
1095
+ crossfade_images = torch.stack(crossfade_images, dim=0)
1096
+ # Get the last frame result of the interpolation
1097
+ last_frame = crossfade_images[-1]
1098
+ # Calculate the number of remaining frames from images_2
1099
+ remaining_frames = len(images_2) - (transition_start_index + transitioning_frames)
1100
+ # Crossfade the remaining frames with the last used alpha value
1101
+ for i in range(remaining_frames):
1102
+ alpha = alphas[-1]
1103
+ image1 = images_1[i + transition_start_index + transitioning_frames]
1104
+ image2 = images_2[i + transition_start_index + transitioning_frames]
1105
+ easing_function = easing_functions.get(interpolation)
1106
+ alpha = easing_function(alpha) # Apply the easing function to the alpha value
1107
+
1108
+ crossfade_image = crossfade(image1, image2, alpha)
1109
+ crossfade_images = torch.cat([crossfade_images, crossfade_image.unsqueeze(0)], dim=0)
1110
+ # Append the beginning of images_1
1111
+ beginning_images_1 = images_1[:transition_start_index]
1112
+ crossfade_images = torch.cat([beginning_images_1, crossfade_images], dim=0)
1113
+ return (crossfade_images, )
1114
+
1115
+ class GetImageRangeFromBatch:
1116
+
1117
+ RETURN_TYPES = ("IMAGE", "MASK", )
1118
+ FUNCTION = "imagesfrombatch"
1119
+ CATEGORY = "KJNodes/image"
1120
+ DESCRIPTION = """
1121
+ Creates a new batch using images from the input,
1122
+ batch, starting from start_index.
1123
+ """
1124
+
1125
+ @classmethod
1126
+ def INPUT_TYPES(s):
1127
+ return {
1128
+ "required": {
1129
+ "start_index": ("INT", {"default": 0,"min": -1, "max": 4096, "step": 1}),
1130
+ "num_frames": ("INT", {"default": 1,"min": 1, "max": 4096, "step": 1}),
1131
+ },
1132
+ "optional": {
1133
+ "images": ("IMAGE",),
1134
+ "masks": ("MASK",),
1135
+ }
1136
+ }
1137
+
1138
+ def imagesfrombatch(self, start_index, num_frames, images=None, masks=None):
1139
+
1140
+ chosen_images = None
1141
+ chosen_masks = None
1142
+
1143
+ # Process images if provided
1144
+ if images is not None:
1145
+ if start_index == -1:
1146
+ start_index = len(images) - num_frames
1147
+ if start_index < 0 or start_index >= len(images):
1148
+ raise ValueError("Start index is out of range")
1149
+ end_index = start_index + num_frames
1150
+ if end_index > len(images):
1151
+ raise ValueError("End index is out of range")
1152
+ chosen_images = images[start_index:end_index]
1153
+
1154
+ # Process masks if provided
1155
+ if masks is not None:
1156
+ if start_index == -1:
1157
+ start_index = len(masks) - num_frames
1158
+ if start_index < 0 or start_index >= len(masks):
1159
+ raise ValueError("Start index is out of range for masks")
1160
+ end_index = start_index + num_frames
1161
+ if end_index > len(masks):
1162
+ raise ValueError("End index is out of range for masks")
1163
+ chosen_masks = masks[start_index:end_index]
1164
+
1165
+ return (chosen_images, chosen_masks,)
1166
+
1167
+ class GetImagesFromBatchIndexed:
1168
+
1169
+ RETURN_TYPES = ("IMAGE",)
1170
+ FUNCTION = "indexedimagesfrombatch"
1171
+ CATEGORY = "KJNodes/image"
1172
+ DESCRIPTION = """
1173
+ Selects and returns the images at the specified indices as an image batch.
1174
+ """
1175
+
1176
+ @classmethod
1177
+ def INPUT_TYPES(s):
1178
+ return {
1179
+ "required": {
1180
+ "images": ("IMAGE",),
1181
+ "indexes": ("STRING", {"default": "0, 1, 2", "multiline": True}),
1182
+ },
1183
+ }
1184
+
1185
+ def indexedimagesfrombatch(self, images, indexes):
1186
+
1187
+ # Parse the indexes string into a list of integers
1188
+ index_list = [int(index.strip()) for index in indexes.split(',')]
1189
+
1190
+ # Convert list of indices to a PyTorch tensor
1191
+ indices_tensor = torch.tensor(index_list, dtype=torch.long)
1192
+
1193
+ # Select the images at the specified indices
1194
+ chosen_images = images[indices_tensor]
1195
+
1196
+ return (chosen_images,)
1197
+
1198
+ class InsertImagesToBatchIndexed:
1199
+
1200
+ RETURN_TYPES = ("IMAGE",)
1201
+ FUNCTION = "insertimagesfrombatch"
1202
+ CATEGORY = "KJNodes/image"
1203
+ DESCRIPTION = """
1204
+ Inserts images at the specified indices into the original image batch.
1205
+ """
1206
+
1207
+ @classmethod
1208
+ def INPUT_TYPES(s):
1209
+ return {
1210
+ "required": {
1211
+ "original_images": ("IMAGE",),
1212
+ "images_to_insert": ("IMAGE",),
1213
+ "indexes": ("STRING", {"default": "0, 1, 2", "multiline": True}),
1214
+ },
1215
+ }
1216
+
1217
+ def insertimagesfrombatch(self, original_images, images_to_insert, indexes):
1218
+
1219
+ # Parse the indexes string into a list of integers
1220
+ index_list = [int(index.strip()) for index in indexes.split(',')]
1221
+
1222
+ # Convert list of indices to a PyTorch tensor
1223
+ indices_tensor = torch.tensor(index_list, dtype=torch.long)
1224
+
1225
+ # Ensure the images_to_insert is a tensor
1226
+ if not isinstance(images_to_insert, torch.Tensor):
1227
+ images_to_insert = torch.tensor(images_to_insert)
1228
+
1229
+ # Insert the images at the specified indices
1230
+ for index, image in zip(indices_tensor, images_to_insert):
1231
+ original_images[index] = image
1232
+
1233
+ return (original_images,)
1234
+
1235
+ class ReplaceImagesInBatch:
1236
+
1237
+ RETURN_TYPES = ("IMAGE",)
1238
+ FUNCTION = "replace"
1239
+ CATEGORY = "KJNodes/image"
1240
+ DESCRIPTION = """
1241
+ Replaces the images in a batch, starting from the specified start index,
1242
+ with the replacement images.
1243
+ """
1244
+
1245
+ @classmethod
1246
+ def INPUT_TYPES(s):
1247
+ return {
1248
+ "required": {
1249
+ "original_images": ("IMAGE",),
1250
+ "replacement_images": ("IMAGE",),
1251
+ "start_index": ("INT", {"default": 1,"min": 0, "max": 4096, "step": 1}),
1252
+ },
1253
+ }
1254
+
1255
+ def replace(self, original_images, replacement_images, start_index):
1256
+ images = None
1257
+ if start_index >= len(original_images):
1258
+ raise ValueError("GetImageRangeFromBatch: Start index is out of range")
1259
+ end_index = start_index + len(replacement_images)
1260
+ if end_index > len(original_images):
1261
+ raise ValueError("GetImageRangeFromBatch: End index is out of range")
1262
+ # Create a copy of the original_images tensor
1263
+ original_images_copy = original_images.clone()
1264
+ original_images_copy[start_index:end_index] = replacement_images
1265
+ images = original_images_copy
1266
+ return (images, )
1267
+
1268
+
1269
+ class ReverseImageBatch:
1270
+
1271
+ RETURN_TYPES = ("IMAGE",)
1272
+ FUNCTION = "reverseimagebatch"
1273
+ CATEGORY = "KJNodes/image"
1274
+ DESCRIPTION = """
1275
+ Reverses the order of the images in a batch.
1276
+ """
1277
+
1278
+ @classmethod
1279
+ def INPUT_TYPES(s):
1280
+ return {
1281
+ "required": {
1282
+ "images": ("IMAGE",),
1283
+ },
1284
+ }
1285
+
1286
+ def reverseimagebatch(self, images):
1287
+ reversed_images = torch.flip(images, [0])
1288
+ return (reversed_images, )
1289
+
1290
+ class ImageBatchMulti:
1291
+ @classmethod
1292
+ def INPUT_TYPES(s):
1293
+ return {
1294
+ "required": {
1295
+ "inputcount": ("INT", {"default": 2, "min": 2, "max": 1000, "step": 1}),
1296
+ "image_1": ("IMAGE", ),
1297
+ "image_2": ("IMAGE", ),
1298
+ },
1299
+ }
1300
+
1301
+ RETURN_TYPES = ("IMAGE",)
1302
+ RETURN_NAMES = ("images",)
1303
+ FUNCTION = "combine"
1304
+ CATEGORY = "KJNodes/image"
1305
+ DESCRIPTION = """
1306
+ Creates an image batch from multiple images.
1307
+ You can set how many inputs the node has,
1308
+ with the **inputcount** and clicking update.
1309
+ """
1310
+
1311
+ def combine(self, inputcount, **kwargs):
1312
+ from nodes import ImageBatch
1313
+ image_batch_node = ImageBatch()
1314
+ image = kwargs["image_1"]
1315
+ for c in range(1, inputcount):
1316
+ new_image = kwargs[f"image_{c + 1}"]
1317
+ image, = image_batch_node.batch(image, new_image)
1318
+ return (image,)
1319
+
1320
+ class ImageAddMulti:
1321
+ @classmethod
1322
+ def INPUT_TYPES(s):
1323
+ return {
1324
+ "required": {
1325
+ "inputcount": ("INT", {"default": 2, "min": 2, "max": 1000, "step": 1}),
1326
+ "image_1": ("IMAGE", ),
1327
+ "image_2": ("IMAGE", ),
1328
+ "blending": (
1329
+ [ 'add',
1330
+ 'subtract',
1331
+ 'multiply',
1332
+ 'difference',
1333
+ ],
1334
+ {
1335
+ "default": 'add'
1336
+ }),
1337
+ },
1338
+ }
1339
+
1340
+ RETURN_TYPES = ("IMAGE",)
1341
+ RETURN_NAMES = ("images",)
1342
+ FUNCTION = "add"
1343
+ CATEGORY = "KJNodes/image"
1344
+ DESCRIPTION = """
1345
+ Add blends multiple images together.
1346
+ You can set how many inputs the node has,
1347
+ with the **inputcount** and clicking update.
1348
+ """
1349
+
1350
+ def add(self, inputcount, blending, **kwargs):
1351
+ image = kwargs["image_1"]
1352
+ for c in range(1, inputcount):
1353
+ new_image = kwargs[f"image_{c + 1}"]
1354
+ if blending == "add":
1355
+ image = torch.add(image * 0.5, new_image * 0.5)
1356
+ elif blending == "subtract":
1357
+ image = torch.sub(image * 0.5, new_image * 0.5)
1358
+ elif blending == "multiply":
1359
+ image = torch.mul(image * 0.5, new_image * 0.5)
1360
+ elif blending == "difference":
1361
+ image = torch.sub(image, new_image)
1362
+ return (image,)
1363
+
1364
+ class ImageConcatMulti:
1365
+ @classmethod
1366
+ def INPUT_TYPES(s):
1367
+ return {
1368
+ "required": {
1369
+ "inputcount": ("INT", {"default": 2, "min": 2, "max": 1000, "step": 1}),
1370
+ "image_1": ("IMAGE", ),
1371
+ "image_2": ("IMAGE", ),
1372
+ "direction": (
1373
+ [ 'right',
1374
+ 'down',
1375
+ 'left',
1376
+ 'up',
1377
+ ],
1378
+ {
1379
+ "default": 'right'
1380
+ }),
1381
+ "match_image_size": ("BOOLEAN", {"default": False}),
1382
+ },
1383
+ }
1384
+
1385
+ RETURN_TYPES = ("IMAGE",)
1386
+ RETURN_NAMES = ("images",)
1387
+ FUNCTION = "combine"
1388
+ CATEGORY = "KJNodes/image"
1389
+ DESCRIPTION = """
1390
+ Creates an image from multiple images.
1391
+ You can set how many inputs the node has,
1392
+ with the **inputcount** and clicking update.
1393
+ """
1394
+
1395
+ def combine(self, inputcount, direction, match_image_size, **kwargs):
1396
+ image = kwargs["image_1"]
1397
+ first_image_shape = None
1398
+ if first_image_shape is None:
1399
+ first_image_shape = image.shape
1400
+ for c in range(1, inputcount):
1401
+ new_image = kwargs[f"image_{c + 1}"]
1402
+ image, = ImageConcanate.concanate(self, image, new_image, direction, match_image_size, first_image_shape=first_image_shape)
1403
+ first_image_shape = None
1404
+ return (image,)
1405
+
1406
+ class PreviewAnimation:
1407
+ def __init__(self):
1408
+ self.output_dir = folder_paths.get_temp_directory()
1409
+ self.type = "temp"
1410
+ self.prefix_append = "_temp_" + ''.join(random.choice("abcdefghijklmnopqrstupvxyz") for x in range(5))
1411
+ self.compress_level = 1
1412
+
1413
+ methods = {"default": 4, "fastest": 0, "slowest": 6}
1414
+ @classmethod
1415
+ def INPUT_TYPES(s):
1416
+ return {"required":
1417
+ {
1418
+ "fps": ("FLOAT", {"default": 8.0, "min": 0.01, "max": 1000.0, "step": 0.01}),
1419
+ },
1420
+ "optional": {
1421
+ "images": ("IMAGE", ),
1422
+ "masks": ("MASK", ),
1423
+ },
1424
+ }
1425
+
1426
+ RETURN_TYPES = ()
1427
+ FUNCTION = "preview"
1428
+ OUTPUT_NODE = True
1429
+ CATEGORY = "KJNodes/image"
1430
+
1431
+ def preview(self, fps, images=None, masks=None):
1432
+ filename_prefix = "AnimPreview"
1433
+ full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir)
1434
+ results = list()
1435
+
1436
+ pil_images = []
1437
+
1438
+ if images is not None and masks is not None:
1439
+ for image in images:
1440
+ i = 255. * image.cpu().numpy()
1441
+ img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
1442
+ pil_images.append(img)
1443
+ for mask in masks:
1444
+ if pil_images:
1445
+ mask_np = mask.cpu().numpy()
1446
+ mask_np = np.clip(mask_np * 255, 0, 255).astype(np.uint8) # Convert to values between 0 and 255
1447
+ mask_img = Image.fromarray(mask_np, mode='L')
1448
+ img = pil_images.pop(0) # Remove and get the first image
1449
+ img = img.convert("RGBA") # Convert base image to RGBA
1450
+
1451
+ # Create a new RGBA image based on the grayscale mask
1452
+ rgba_mask_img = Image.new("RGBA", img.size, (255, 255, 255, 255))
1453
+ rgba_mask_img.putalpha(mask_img) # Use the mask image as the alpha channel
1454
+
1455
+ # Composite the RGBA mask onto the base image
1456
+ composited_img = Image.alpha_composite(img, rgba_mask_img)
1457
+ pil_images.append(composited_img) # Add the composited image back
1458
+
1459
+ elif images is not None and masks is None:
1460
+ for image in images:
1461
+ i = 255. * image.cpu().numpy()
1462
+ img = Image.fromarray(np.clip(i, 0, 255).astype(np.uint8))
1463
+ pil_images.append(img)
1464
+
1465
+ elif masks is not None and images is None:
1466
+ for mask in masks:
1467
+ mask_np = 255. * mask.cpu().numpy()
1468
+ mask_img = Image.fromarray(np.clip(mask_np, 0, 255).astype(np.uint8))
1469
+ pil_images.append(mask_img)
1470
+ else:
1471
+ print("PreviewAnimation: No images or masks provided")
1472
+ return { "ui": { "images": results, "animated": (None,), "text": "empty" }}
1473
+
1474
+ num_frames = len(pil_images)
1475
+
1476
+ c = len(pil_images)
1477
+ for i in range(0, c, num_frames):
1478
+ file = f"{filename}_{counter:05}_.webp"
1479
+ pil_images[i].save(os.path.join(full_output_folder, file), save_all=True, duration=int(1000.0/fps), append_images=pil_images[i + 1:i + num_frames], lossless=False, quality=80, method=4)
1480
+ results.append({
1481
+ "filename": file,
1482
+ "subfolder": subfolder,
1483
+ "type": self.type
1484
+ })
1485
+ counter += 1
1486
+
1487
+ animated = num_frames != 1
1488
+ return { "ui": { "images": results, "animated": (animated,), "text": [f"{num_frames}x{pil_images[0].size[0]}x{pil_images[0].size[1]}"] } }
1489
+
1490
+ class ImageResizeKJ:
1491
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
1492
+ @classmethod
1493
+ def INPUT_TYPES(s):
1494
+ return {
1495
+ "required": {
1496
+ "image": ("IMAGE",),
1497
+ "width": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8, }),
1498
+ "height": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8, }),
1499
+ "upscale_method": (s.upscale_methods,),
1500
+ "keep_proportion": ("BOOLEAN", { "default": False }),
1501
+ "divisible_by": ("INT", { "default": 2, "min": 0, "max": 512, "step": 1, }),
1502
+ },
1503
+ "optional" : {
1504
+ "width_input": ("INT", { "forceInput": True}),
1505
+ "height_input": ("INT", { "forceInput": True}),
1506
+ "get_image_size": ("IMAGE",),
1507
+ }
1508
+ }
1509
+
1510
+ RETURN_TYPES = ("IMAGE", "INT", "INT",)
1511
+ RETURN_NAMES = ("IMAGE", "width", "height",)
1512
+ FUNCTION = "resize"
1513
+ CATEGORY = "KJNodes/image"
1514
+ DESCRIPTION = """
1515
+ Resizes the image to the specified width and height.
1516
+ Size can be retrieved from the inputs, and the final scale
1517
+ is determined in this order of importance:
1518
+ - get_image_size
1519
+ - width_input and height_input
1520
+ - width and height widgets
1521
+
1522
+ Keep proportions keeps the aspect ratio of the image, by
1523
+ highest dimension.
1524
+ """
1525
+
1526
+ def resize(self, image, width, height, keep_proportion, upscale_method, divisible_by, width_input=None, height_input=None, get_image_size=None):
1527
+ B, H, W, C = image.shape
1528
+ if width_input:
1529
+ width = width_input
1530
+ if height_input:
1531
+ height = height_input
1532
+ if get_image_size is not None:
1533
+ _, height, width, _ = get_image_size.shape
1534
+
1535
+ if keep_proportion and get_image_size is None:
1536
+ # If one of the dimensions is zero, calculate it to maintain the aspect ratio
1537
+ if width == 0 and height != 0:
1538
+ ratio = height / H
1539
+ width = round(W * ratio)
1540
+ elif height == 0 and width != 0:
1541
+ ratio = width / W
1542
+ height = round(H * ratio)
1543
+ elif width != 0 and height != 0:
1544
+ # Scale based on which dimension is smaller in proportion to the desired dimensions
1545
+ ratio = min(width / W, height / H)
1546
+ width = round(W * ratio)
1547
+ height = round(H * ratio)
1548
+ else:
1549
+ if width == 0:
1550
+ width = W
1551
+ if height == 0:
1552
+ height = H
1553
+
1554
+ if divisible_by > 1 and get_image_size is None:
1555
+ width = width - (width % divisible_by)
1556
+ height = height - (height % divisible_by)
1557
+
1558
+ image = image.movedim(-1,1)
1559
+ scaled = common_upscale(image, width, height, upscale_method, 'disabled')
1560
+ scaled = scaled.movedim(1,-1)
1561
+
1562
+ return(scaled, scaled.shape[2], scaled.shape[1],)
1563
+
1564
+ class LoadAndResizeImage:
1565
+ _color_channels = ["alpha", "red", "green", "blue"]
1566
+ @classmethod
1567
+ def INPUT_TYPES(s):
1568
+ input_dir = folder_paths.get_input_directory()
1569
+ files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f))]
1570
+ return {"required":
1571
+ {
1572
+ "image": (sorted(files), {"image_upload": True}),
1573
+ "resize": ("BOOLEAN", { "default": False }),
1574
+ "width": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8, }),
1575
+ "height": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8, }),
1576
+ "repeat": ("INT", { "default": 1, "min": 1, "max": 4096, "step": 1, }),
1577
+ "keep_proportion": ("BOOLEAN", { "default": False }),
1578
+ "divisible_by": ("INT", { "default": 2, "min": 0, "max": 512, "step": 1, }),
1579
+ "mask_channel": (s._color_channels, ),
1580
+ },
1581
+ }
1582
+
1583
+ CATEGORY = "KJNodes/image"
1584
+ RETURN_TYPES = ("IMAGE", "MASK", "INT", "INT",)
1585
+ RETURN_NAMES = ("image", "mask", "width", "height",)
1586
+ FUNCTION = "load_image"
1587
+
1588
+ def load_image(self, image, resize, width, height, repeat, keep_proportion, divisible_by, mask_channel):
1589
+ image_path = folder_paths.get_annotated_filepath(image)
1590
+
1591
+ import node_helpers
1592
+ img = node_helpers.pillow(Image.open, image_path)
1593
+
1594
+ output_images = []
1595
+ output_masks = []
1596
+ w, h = None, None
1597
+
1598
+ excluded_formats = ['MPO']
1599
+
1600
+ W, H = img.size
1601
+ if resize:
1602
+ if keep_proportion:
1603
+ ratio = min(width / W, height / H)
1604
+ width = round(W * ratio)
1605
+ height = round(H * ratio)
1606
+ else:
1607
+ if width == 0:
1608
+ width = W
1609
+ if height == 0:
1610
+ height = H
1611
+
1612
+ if divisible_by > 1:
1613
+ width = width - (width % divisible_by)
1614
+ height = height - (height % divisible_by)
1615
+ else:
1616
+ width, height = W, H
1617
+
1618
+ for i in ImageSequence.Iterator(img):
1619
+ i = node_helpers.pillow(ImageOps.exif_transpose, i)
1620
+
1621
+ if i.mode == 'I':
1622
+ i = i.point(lambda i: i * (1 / 255))
1623
+ image = i.convert("RGB")
1624
+
1625
+ if len(output_images) == 0:
1626
+ w = image.size[0]
1627
+ h = image.size[1]
1628
+
1629
+ if image.size[0] != w or image.size[1] != h:
1630
+ continue
1631
+ if resize:
1632
+ image = image.resize((width, height), Image.Resampling.BILINEAR)
1633
+
1634
+ image = np.array(image).astype(np.float32) / 255.0
1635
+ image = torch.from_numpy(image)[None,]
1636
+ mask = None
1637
+ c = mask_channel[0].upper()
1638
+ if c in i.getbands():
1639
+ if resize:
1640
+ i = i.resize((width, height), Image.Resampling.BILINEAR)
1641
+ mask = np.array(i.getchannel(c)).astype(np.float32) / 255.0
1642
+ mask = torch.from_numpy(mask)
1643
+ if c == 'A':
1644
+ mask = 1. - mask
1645
+ else:
1646
+ mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
1647
+
1648
+ output_images.append(image)
1649
+ output_masks.append(mask.unsqueeze(0))
1650
+
1651
+ if len(output_images) > 1 and img.format not in excluded_formats:
1652
+ output_image = torch.cat(output_images, dim=0)
1653
+ output_mask = torch.cat(output_masks, dim=0)
1654
+ else:
1655
+ output_image = output_images[0]
1656
+ output_mask = output_masks[0]
1657
+ if repeat > 1:
1658
+ output_image = output_image.repeat(repeat, 1, 1, 1)
1659
+ output_mask = output_mask.repeat(repeat, 1, 1)
1660
+
1661
+
1662
+ return (output_image, output_mask, width, height)
1663
+
1664
+
1665
+ @classmethod
1666
+ def IS_CHANGED(s, image):
1667
+ image_path = folder_paths.get_annotated_filepath(image)
1668
+ m = hashlib.sha256()
1669
+ with open(image_path, 'rb') as f:
1670
+ m.update(f.read())
1671
+ return m.digest().hex()
1672
+
1673
+ @classmethod
1674
+ def VALIDATE_INPUTS(s, image):
1675
+ if not folder_paths.exists_annotated_filepath(image):
1676
+ return "Invalid image file: {}".format(image)
1677
+
1678
+ return True
ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/intrinsic_lora_nodes.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import folder_paths
2
+ import os
3
+ import torch
4
+ import torch.nn.functional as F
5
+ from comfy.utils import ProgressBar, load_torch_file
6
+ import comfy.sample
7
+ from nodes import CLIPTextEncode
8
+
9
+ script_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
10
+ folder_paths.add_model_folder_path("intrinsic_loras", os.path.join(script_directory, "intrinsic_loras"))
11
+
12
+ class Intrinsic_lora_sampling:
13
+ def __init__(self):
14
+ self.loaded_lora = None
15
+
16
+ @classmethod
17
+ def INPUT_TYPES(s):
18
+ return {"required": { "model": ("MODEL",),
19
+ "lora_name": (folder_paths.get_filename_list("intrinsic_loras"), ),
20
+ "task": (
21
+ [
22
+ 'depth map',
23
+ 'surface normals',
24
+ 'albedo',
25
+ 'shading',
26
+ ],
27
+ {
28
+ "default": 'depth map'
29
+ }),
30
+ "text": ("STRING", {"multiline": True, "default": ""}),
31
+ "clip": ("CLIP", ),
32
+ "vae": ("VAE", ),
33
+ "per_batch": ("INT", {"default": 16, "min": 1, "max": 4096, "step": 1}),
34
+ },
35
+ "optional": {
36
+ "image": ("IMAGE",),
37
+ "optional_latent": ("LATENT",),
38
+ },
39
+ }
40
+
41
+ RETURN_TYPES = ("IMAGE", "LATENT",)
42
+ FUNCTION = "onestepsample"
43
+ CATEGORY = "KJNodes"
44
+ DESCRIPTION = """
45
+ Sampler to use the intrinsic loras:
46
+ https://github.com/duxiaodan/intrinsic-lora
47
+ These LoRAs are tiny and thus included
48
+ with this node pack.
49
+ """
50
+
51
+ def onestepsample(self, model, lora_name, clip, vae, text, task, per_batch, image=None, optional_latent=None):
52
+ pbar = ProgressBar(3)
53
+
54
+ if optional_latent is None:
55
+ image_list = []
56
+ for start_idx in range(0, image.shape[0], per_batch):
57
+ sub_pixels = vae.vae_encode_crop_pixels(image[start_idx:start_idx+per_batch])
58
+ image_list.append(vae.encode(sub_pixels[:,:,:,:3]))
59
+ sample = torch.cat(image_list, dim=0)
60
+ else:
61
+ sample = optional_latent["samples"]
62
+ noise = torch.zeros(sample.size(), dtype=sample.dtype, layout=sample.layout, device="cpu")
63
+ prompt = task + "," + text
64
+ positive, = CLIPTextEncode.encode(self, clip, prompt)
65
+ negative = positive #negative shouldn't do anything in this scenario
66
+
67
+ pbar.update(1)
68
+
69
+ #custom model sampling to pass latent through as it is
70
+ class X0_PassThrough(comfy.model_sampling.EPS):
71
+ def calculate_denoised(self, sigma, model_output, model_input):
72
+ return model_output
73
+ def calculate_input(self, sigma, noise):
74
+ return noise
75
+ sampling_base = comfy.model_sampling.ModelSamplingDiscrete
76
+ sampling_type = X0_PassThrough
77
+
78
+ class ModelSamplingAdvanced(sampling_base, sampling_type):
79
+ pass
80
+ model_sampling = ModelSamplingAdvanced(model.model.model_config)
81
+
82
+ #load lora
83
+ model_clone = model.clone()
84
+ lora_path = folder_paths.get_full_path("intrinsic_loras", lora_name)
85
+ lora = load_torch_file(lora_path, safe_load=True)
86
+ self.loaded_lora = (lora_path, lora)
87
+
88
+ model_clone_with_lora = comfy.sd.load_lora_for_models(model_clone, None, lora, 1.0, 0)[0]
89
+
90
+ model_clone_with_lora.add_object_patch("model_sampling", model_sampling)
91
+
92
+ samples = {"samples": comfy.sample.sample(model_clone_with_lora, noise, 1, 1.0, "euler", "simple", positive, negative, sample,
93
+ denoise=1.0, disable_noise=True, start_step=0, last_step=1,
94
+ force_full_denoise=True, noise_mask=None, callback=None, disable_pbar=True, seed=None)}
95
+ pbar.update(1)
96
+
97
+ decoded = []
98
+ for start_idx in range(0, samples["samples"].shape[0], per_batch):
99
+ decoded.append(vae.decode(samples["samples"][start_idx:start_idx+per_batch]))
100
+ image_out = torch.cat(decoded, dim=0)
101
+
102
+ pbar.update(1)
103
+
104
+ if task == 'depth map':
105
+ imax = image_out.max()
106
+ imin = image_out.min()
107
+ image_out = (image_out-imin)/(imax-imin)
108
+ image_out = torch.max(image_out, dim=3, keepdim=True)[0].repeat(1, 1, 1, 3)
109
+ elif task == 'surface normals':
110
+ image_out = F.normalize(image_out * 2 - 1, dim=3) / 2 + 0.5
111
+ image_out = 1.0 - image_out
112
+ else:
113
+ image_out = image_out.clamp(-1.,1.)
114
+
115
+ return (image_out, samples,)
ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/mask_nodes.py ADDED
@@ -0,0 +1,1249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn.functional as F
3
+ from torchvision.transforms import functional as TF
4
+ from PIL import Image, ImageDraw, ImageFilter, ImageFont
5
+ import scipy.ndimage
6
+ import numpy as np
7
+ from contextlib import nullcontext
8
+ import os
9
+
10
+ import model_management
11
+ from comfy.utils import ProgressBar
12
+ from nodes import MAX_RESOLUTION
13
+
14
+ import folder_paths
15
+
16
+ from ..utility.utility import tensor2pil, pil2tensor
17
+
18
+ script_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
19
+
20
+ class BatchCLIPSeg:
21
+
22
+ def __init__(self):
23
+ pass
24
+
25
+ @classmethod
26
+ def INPUT_TYPES(s):
27
+
28
+ return {"required":
29
+ {
30
+ "images": ("IMAGE",),
31
+ "text": ("STRING", {"multiline": False}),
32
+ "threshold": ("FLOAT", {"default": 0.5,"min": 0.0, "max": 10.0, "step": 0.001}),
33
+ "binary_mask": ("BOOLEAN", {"default": True}),
34
+ "combine_mask": ("BOOLEAN", {"default": False}),
35
+ "use_cuda": ("BOOLEAN", {"default": True}),
36
+ },
37
+ "optional":
38
+ {
39
+ "blur_sigma": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.1}),
40
+ "opt_model": ("CLIPSEGMODEL", ),
41
+ "prev_mask": ("MASK", {"default": None}),
42
+ "image_bg_level": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
43
+ "invert": ("BOOLEAN", {"default": False}),
44
+ }
45
+ }
46
+
47
+ CATEGORY = "KJNodes/masking"
48
+ RETURN_TYPES = ("MASK", "IMAGE", )
49
+ RETURN_NAMES = ("Mask", "Image", )
50
+ FUNCTION = "segment_image"
51
+ DESCRIPTION = """
52
+ Segments an image or batch of images using CLIPSeg.
53
+ """
54
+
55
+ def segment_image(self, images, text, threshold, binary_mask, combine_mask, use_cuda, blur_sigma=0.0, opt_model=None, prev_mask=None, invert= False, image_bg_level=0.5):
56
+ from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation
57
+ import torchvision.transforms as transforms
58
+ offload_device = model_management.unet_offload_device()
59
+ device = model_management.get_torch_device()
60
+ if not use_cuda:
61
+ device = torch.device("cpu")
62
+ dtype = model_management.unet_dtype()
63
+
64
+ if opt_model is None:
65
+ checkpoint_path = os.path.join(folder_paths.models_dir,'clip_seg', 'clipseg-rd64-refined-fp16')
66
+ if not hasattr(self, "model"):
67
+ try:
68
+ if not os.path.exists(checkpoint_path):
69
+ from huggingface_hub import snapshot_download
70
+ snapshot_download(repo_id="Kijai/clipseg-rd64-refined-fp16", local_dir=checkpoint_path, local_dir_use_symlinks=False)
71
+ self.model = CLIPSegForImageSegmentation.from_pretrained(checkpoint_path)
72
+ except:
73
+ checkpoint_path = "CIDAS/clipseg-rd64-refined"
74
+ self.model = CLIPSegForImageSegmentation.from_pretrained(checkpoint_path)
75
+ processor = CLIPSegProcessor.from_pretrained(checkpoint_path)
76
+
77
+ else:
78
+ self.model = opt_model['model']
79
+ processor = opt_model['processor']
80
+
81
+ self.model.to(dtype).to(device)
82
+
83
+ B, H, W, C = images.shape
84
+ images = images.to(device)
85
+
86
+ autocast_condition = (dtype != torch.float32) and not model_management.is_device_mps(device)
87
+ with torch.autocast(model_management.get_autocast_device(device), dtype=dtype) if autocast_condition else nullcontext():
88
+
89
+ PIL_images = [Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)) for image in images ]
90
+ prompt = [text] * len(images)
91
+ input_prc = processor(text=prompt, images=PIL_images, return_tensors="pt")
92
+
93
+ for key in input_prc:
94
+ input_prc[key] = input_prc[key].to(device)
95
+ outputs = self.model(**input_prc)
96
+
97
+ mask_tensor = torch.sigmoid(outputs.logits)
98
+ mask_tensor = (mask_tensor - mask_tensor.min()) / (mask_tensor.max() - mask_tensor.min())
99
+ mask_tensor = torch.where(mask_tensor > (threshold), mask_tensor, torch.tensor(0, dtype=torch.float))
100
+ print(mask_tensor.shape)
101
+ if len(mask_tensor.shape) == 2:
102
+ mask_tensor = mask_tensor.unsqueeze(0)
103
+ mask_tensor = F.interpolate(mask_tensor.unsqueeze(1), size=(H, W), mode='nearest')
104
+ mask_tensor = mask_tensor.squeeze(1)
105
+
106
+ self.model.to(offload_device)
107
+
108
+ if binary_mask:
109
+ mask_tensor = (mask_tensor > 0).float()
110
+ if blur_sigma > 0:
111
+ kernel_size = int(6 * int(blur_sigma) + 1)
112
+ blur = transforms.GaussianBlur(kernel_size=(kernel_size, kernel_size), sigma=(blur_sigma, blur_sigma))
113
+ mask_tensor = blur(mask_tensor)
114
+
115
+ if combine_mask:
116
+ mask_tensor = torch.max(mask_tensor, dim=0)[0]
117
+ mask_tensor = mask_tensor.unsqueeze(0).repeat(len(images),1,1)
118
+
119
+ del outputs
120
+ model_management.soft_empty_cache()
121
+
122
+ if prev_mask is not None:
123
+ if prev_mask.shape != mask_tensor.shape:
124
+ prev_mask = F.interpolate(prev_mask.unsqueeze(1), size=(H, W), mode='nearest')
125
+ mask_tensor = mask_tensor + prev_mask.to(device)
126
+ torch.clamp(mask_tensor, min=0.0, max=1.0)
127
+
128
+ if invert:
129
+ mask_tensor = 1 - mask_tensor
130
+
131
+ image_tensor = images * mask_tensor.unsqueeze(-1) + (1 - mask_tensor.unsqueeze(-1)) * image_bg_level
132
+ image_tensor = torch.clamp(image_tensor, min=0.0, max=1.0).cpu().float()
133
+
134
+ mask_tensor = mask_tensor.cpu().float()
135
+
136
+ return mask_tensor, image_tensor,
137
+
138
+ class DownloadAndLoadCLIPSeg:
139
+
140
+ def __init__(self):
141
+ pass
142
+
143
+ @classmethod
144
+ def INPUT_TYPES(s):
145
+
146
+ return {"required":
147
+ {
148
+ "model": (
149
+ [ 'Kijai/clipseg-rd64-refined-fp16',
150
+ 'CIDAS/clipseg-rd64-refined',
151
+ ],
152
+ ),
153
+ },
154
+ }
155
+
156
+ CATEGORY = "KJNodes/masking"
157
+ RETURN_TYPES = ("CLIPSEGMODEL",)
158
+ RETURN_NAMES = ("clipseg_model",)
159
+ FUNCTION = "segment_image"
160
+ DESCRIPTION = """
161
+ Downloads and loads CLIPSeg model with huggingface_hub,
162
+ to ComfyUI/models/clip_seg
163
+ """
164
+
165
+ def segment_image(self, model):
166
+ from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation
167
+ checkpoint_path = os.path.join(folder_paths.models_dir,'clip_seg', os.path.basename(model))
168
+ if not hasattr(self, "model"):
169
+ if not os.path.exists(checkpoint_path):
170
+ from huggingface_hub import snapshot_download
171
+ snapshot_download(repo_id=model, local_dir=checkpoint_path, local_dir_use_symlinks=False)
172
+ self.model = CLIPSegForImageSegmentation.from_pretrained(checkpoint_path)
173
+
174
+ processor = CLIPSegProcessor.from_pretrained(checkpoint_path)
175
+
176
+ clipseg_model = {}
177
+ clipseg_model['model'] = self.model
178
+ clipseg_model['processor'] = processor
179
+
180
+ return clipseg_model,
181
+
182
+ class CreateTextMask:
183
+
184
+ RETURN_TYPES = ("IMAGE", "MASK",)
185
+ FUNCTION = "createtextmask"
186
+ CATEGORY = "KJNodes/text"
187
+ DESCRIPTION = """
188
+ Creates a text image and mask.
189
+ Looks for fonts from this folder:
190
+ ComfyUI/custom_nodes/ComfyUI-KJNodes/fonts
191
+
192
+ If start_rotation and/or end_rotation are different values,
193
+ creates animation between them.
194
+ """
195
+
196
+ @classmethod
197
+ def INPUT_TYPES(s):
198
+ return {
199
+ "required": {
200
+ "invert": ("BOOLEAN", {"default": False}),
201
+ "frames": ("INT", {"default": 1,"min": 1, "max": 4096, "step": 1}),
202
+ "text_x": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}),
203
+ "text_y": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}),
204
+ "font_size": ("INT", {"default": 32,"min": 8, "max": 4096, "step": 1}),
205
+ "font_color": ("STRING", {"default": "white"}),
206
+ "text": ("STRING", {"default": "HELLO!", "multiline": True}),
207
+ "font": (folder_paths.get_filename_list("kjnodes_fonts"), ),
208
+ "width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
209
+ "height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
210
+ "start_rotation": ("INT", {"default": 0,"min": 0, "max": 359, "step": 1}),
211
+ "end_rotation": ("INT", {"default": 0,"min": -359, "max": 359, "step": 1}),
212
+ },
213
+ }
214
+
215
+ def createtextmask(self, frames, width, height, invert, text_x, text_y, text, font_size, font_color, font, start_rotation, end_rotation):
216
+ # Define the number of images in the batch
217
+ batch_size = frames
218
+ out = []
219
+ masks = []
220
+ rotation = start_rotation
221
+ if start_rotation != end_rotation:
222
+ rotation_increment = (end_rotation - start_rotation) / (batch_size - 1)
223
+
224
+ font_path = folder_paths.get_full_path("kjnodes_fonts", font)
225
+ # Generate the text
226
+ for i in range(batch_size):
227
+ image = Image.new("RGB", (width, height), "black")
228
+ draw = ImageDraw.Draw(image)
229
+ font = ImageFont.truetype(font_path, font_size)
230
+
231
+ # Split the text into words
232
+ words = text.split()
233
+
234
+ # Initialize variables for line creation
235
+ lines = []
236
+ current_line = []
237
+ current_line_width = 0
238
+ try: #new pillow
239
+ # Iterate through words to create lines
240
+ for word in words:
241
+ word_width = font.getbbox(word)[2]
242
+ if current_line_width + word_width <= width - 2 * text_x:
243
+ current_line.append(word)
244
+ current_line_width += word_width + font.getbbox(" ")[2] # Add space width
245
+ else:
246
+ lines.append(" ".join(current_line))
247
+ current_line = [word]
248
+ current_line_width = word_width
249
+ except: #old pillow
250
+ for word in words:
251
+ word_width = font.getsize(word)[0]
252
+ if current_line_width + word_width <= width - 2 * text_x:
253
+ current_line.append(word)
254
+ current_line_width += word_width + font.getsize(" ")[0] # Add space width
255
+ else:
256
+ lines.append(" ".join(current_line))
257
+ current_line = [word]
258
+ current_line_width = word_width
259
+
260
+ # Add the last line if it's not empty
261
+ if current_line:
262
+ lines.append(" ".join(current_line))
263
+
264
+ # Draw each line of text separately
265
+ y_offset = text_y
266
+ for line in lines:
267
+ text_width = font.getlength(line)
268
+ text_height = font_size
269
+ text_center_x = text_x + text_width / 2
270
+ text_center_y = y_offset + text_height / 2
271
+ try:
272
+ draw.text((text_x, y_offset), line, font=font, fill=font_color, features=['-liga'])
273
+ except:
274
+ draw.text((text_x, y_offset), line, font=font, fill=font_color)
275
+ y_offset += text_height # Move to the next line
276
+
277
+ if start_rotation != end_rotation:
278
+ image = image.rotate(rotation, center=(text_center_x, text_center_y))
279
+ rotation += rotation_increment
280
+
281
+ image = np.array(image).astype(np.float32) / 255.0
282
+ image = torch.from_numpy(image)[None,]
283
+ mask = image[:, :, :, 0]
284
+ masks.append(mask)
285
+ out.append(image)
286
+
287
+ if invert:
288
+ return (1.0 - torch.cat(out, dim=0), 1.0 - torch.cat(masks, dim=0),)
289
+ return (torch.cat(out, dim=0),torch.cat(masks, dim=0),)
290
+
291
+ class ColorToMask:
292
+
293
+ RETURN_TYPES = ("MASK",)
294
+ FUNCTION = "clip"
295
+ CATEGORY = "KJNodes/masking"
296
+ DESCRIPTION = """
297
+ Converts chosen RGB value to a mask.
298
+ With batch inputs, the **per_batch**
299
+ controls the number of images processed at once.
300
+ """
301
+
302
+ @classmethod
303
+ def INPUT_TYPES(s):
304
+ return {
305
+ "required": {
306
+ "images": ("IMAGE",),
307
+ "invert": ("BOOLEAN", {"default": False}),
308
+ "red": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}),
309
+ "green": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}),
310
+ "blue": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}),
311
+ "threshold": ("INT", {"default": 10,"min": 0, "max": 255, "step": 1}),
312
+ "per_batch": ("INT", {"default": 16, "min": 1, "max": 4096, "step": 1}),
313
+ },
314
+ }
315
+
316
+ def clip(self, images, red, green, blue, threshold, invert, per_batch):
317
+
318
+ color = torch.tensor([red, green, blue], dtype=torch.uint8)
319
+ black = torch.tensor([0, 0, 0], dtype=torch.uint8)
320
+ white = torch.tensor([255, 255, 255], dtype=torch.uint8)
321
+
322
+ if invert:
323
+ black, white = white, black
324
+
325
+ steps = images.shape[0]
326
+ pbar = ProgressBar(steps)
327
+ tensors_out = []
328
+
329
+ for start_idx in range(0, images.shape[0], per_batch):
330
+
331
+ # Calculate color distances
332
+ color_distances = torch.norm(images[start_idx:start_idx+per_batch] * 255 - color, dim=-1)
333
+
334
+ # Create a mask based on the threshold
335
+ mask = color_distances <= threshold
336
+
337
+ # Apply the mask to create new images
338
+ mask_out = torch.where(mask.unsqueeze(-1), white, black).float()
339
+ mask_out = mask_out.mean(dim=-1)
340
+
341
+ tensors_out.append(mask_out.cpu())
342
+ batch_count = mask_out.shape[0]
343
+ pbar.update(batch_count)
344
+
345
+ tensors_out = torch.cat(tensors_out, dim=0)
346
+ tensors_out = torch.clamp(tensors_out, min=0.0, max=1.0)
347
+ return tensors_out,
348
+
349
+ class CreateFluidMask:
350
+
351
+ RETURN_TYPES = ("IMAGE", "MASK")
352
+ FUNCTION = "createfluidmask"
353
+ CATEGORY = "KJNodes/masking/generate"
354
+
355
+ @classmethod
356
+ def INPUT_TYPES(s):
357
+ return {
358
+ "required": {
359
+ "invert": ("BOOLEAN", {"default": False}),
360
+ "frames": ("INT", {"default": 1,"min": 1, "max": 4096, "step": 1}),
361
+ "width": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
362
+ "height": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
363
+ "inflow_count": ("INT", {"default": 3,"min": 0, "max": 255, "step": 1}),
364
+ "inflow_velocity": ("INT", {"default": 1,"min": 0, "max": 255, "step": 1}),
365
+ "inflow_radius": ("INT", {"default": 8,"min": 0, "max": 255, "step": 1}),
366
+ "inflow_padding": ("INT", {"default": 50,"min": 0, "max": 255, "step": 1}),
367
+ "inflow_duration": ("INT", {"default": 60,"min": 0, "max": 255, "step": 1}),
368
+ },
369
+ }
370
+ #using code from https://github.com/GregTJ/stable-fluids
371
+ def createfluidmask(self, frames, width, height, invert, inflow_count, inflow_velocity, inflow_radius, inflow_padding, inflow_duration):
372
+ from ..utility.fluid import Fluid
373
+ try:
374
+ from scipy.special import erf
375
+ except:
376
+ from scipy.spatial import erf
377
+ out = []
378
+ masks = []
379
+ RESOLUTION = width, height
380
+ DURATION = frames
381
+
382
+ INFLOW_PADDING = inflow_padding
383
+ INFLOW_DURATION = inflow_duration
384
+ INFLOW_RADIUS = inflow_radius
385
+ INFLOW_VELOCITY = inflow_velocity
386
+ INFLOW_COUNT = inflow_count
387
+
388
+ print('Generating fluid solver, this may take some time.')
389
+ fluid = Fluid(RESOLUTION, 'dye')
390
+
391
+ center = np.floor_divide(RESOLUTION, 2)
392
+ r = np.min(center) - INFLOW_PADDING
393
+
394
+ points = np.linspace(-np.pi, np.pi, INFLOW_COUNT, endpoint=False)
395
+ points = tuple(np.array((np.cos(p), np.sin(p))) for p in points)
396
+ normals = tuple(-p for p in points)
397
+ points = tuple(r * p + center for p in points)
398
+
399
+ inflow_velocity = np.zeros_like(fluid.velocity)
400
+ inflow_dye = np.zeros(fluid.shape)
401
+ for p, n in zip(points, normals):
402
+ mask = np.linalg.norm(fluid.indices - p[:, None, None], axis=0) <= INFLOW_RADIUS
403
+ inflow_velocity[:, mask] += n[:, None] * INFLOW_VELOCITY
404
+ inflow_dye[mask] = 1
405
+
406
+
407
+ for f in range(DURATION):
408
+ print(f'Computing frame {f + 1} of {DURATION}.')
409
+ if f <= INFLOW_DURATION:
410
+ fluid.velocity += inflow_velocity
411
+ fluid.dye += inflow_dye
412
+
413
+ curl = fluid.step()[1]
414
+ # Using the error function to make the contrast a bit higher.
415
+ # Any other sigmoid function e.g. smoothstep would work.
416
+ curl = (erf(curl * 2) + 1) / 4
417
+
418
+ color = np.dstack((curl, np.ones(fluid.shape), fluid.dye))
419
+ color = (np.clip(color, 0, 1) * 255).astype('uint8')
420
+ image = np.array(color).astype(np.float32) / 255.0
421
+ image = torch.from_numpy(image)[None,]
422
+ mask = image[:, :, :, 0]
423
+ masks.append(mask)
424
+ out.append(image)
425
+
426
+ if invert:
427
+ return (1.0 - torch.cat(out, dim=0),1.0 - torch.cat(masks, dim=0),)
428
+ return (torch.cat(out, dim=0),torch.cat(masks, dim=0),)
429
+
430
+ class CreateAudioMask:
431
+
432
+ RETURN_TYPES = ("IMAGE",)
433
+ FUNCTION = "createaudiomask"
434
+ CATEGORY = "KJNodes/deprecated"
435
+
436
+ @classmethod
437
+ def INPUT_TYPES(s):
438
+ return {
439
+ "required": {
440
+ "invert": ("BOOLEAN", {"default": False}),
441
+ "frames": ("INT", {"default": 16,"min": 1, "max": 255, "step": 1}),
442
+ "scale": ("FLOAT", {"default": 0.5,"min": 0.0, "max": 2.0, "step": 0.01}),
443
+ "audio_path": ("STRING", {"default": "audio.wav"}),
444
+ "width": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
445
+ "height": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
446
+ },
447
+ }
448
+
449
+ def createaudiomask(self, frames, width, height, invert, audio_path, scale):
450
+ try:
451
+ import librosa
452
+ except ImportError:
453
+ raise Exception("Can not import librosa. Install it with 'pip install librosa'")
454
+ batch_size = frames
455
+ out = []
456
+ masks = []
457
+ if audio_path == "audio.wav": #I don't know why relative path won't work otherwise...
458
+ audio_path = os.path.join(script_directory, audio_path)
459
+ audio, sr = librosa.load(audio_path)
460
+ spectrogram = np.abs(librosa.stft(audio))
461
+
462
+ for i in range(batch_size):
463
+ image = Image.new("RGB", (width, height), "black")
464
+ draw = ImageDraw.Draw(image)
465
+ frame = spectrogram[:, i]
466
+ circle_radius = int(height * np.mean(frame))
467
+ circle_radius *= scale
468
+ circle_center = (width // 2, height // 2) # Calculate the center of the image
469
+
470
+ draw.ellipse([(circle_center[0] - circle_radius, circle_center[1] - circle_radius),
471
+ (circle_center[0] + circle_radius, circle_center[1] + circle_radius)],
472
+ fill='white')
473
+
474
+ image = np.array(image).astype(np.float32) / 255.0
475
+ image = torch.from_numpy(image)[None,]
476
+ mask = image[:, :, :, 0]
477
+ masks.append(mask)
478
+ out.append(image)
479
+
480
+ if invert:
481
+ return (1.0 - torch.cat(out, dim=0),)
482
+ return (torch.cat(out, dim=0),torch.cat(masks, dim=0),)
483
+
484
+ class CreateGradientMask:
485
+
486
+ RETURN_TYPES = ("MASK",)
487
+ FUNCTION = "createmask"
488
+ CATEGORY = "KJNodes/masking/generate"
489
+
490
+ @classmethod
491
+ def INPUT_TYPES(s):
492
+ return {
493
+ "required": {
494
+ "invert": ("BOOLEAN", {"default": False}),
495
+ "frames": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}),
496
+ "width": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
497
+ "height": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
498
+ },
499
+ }
500
+ def createmask(self, frames, width, height, invert):
501
+ # Define the number of images in the batch
502
+ batch_size = frames
503
+ out = []
504
+ # Create an empty array to store the image batch
505
+ image_batch = np.zeros((batch_size, height, width), dtype=np.float32)
506
+ # Generate the black to white gradient for each image
507
+ for i in range(batch_size):
508
+ gradient = np.linspace(1.0, 0.0, width, dtype=np.float32)
509
+ time = i / frames # Calculate the time variable
510
+ offset_gradient = gradient - time # Offset the gradient values based on time
511
+ image_batch[i] = offset_gradient.reshape(1, -1)
512
+ output = torch.from_numpy(image_batch)
513
+ mask = output
514
+ out.append(mask)
515
+ if invert:
516
+ return (1.0 - torch.cat(out, dim=0),)
517
+ return (torch.cat(out, dim=0),)
518
+
519
+ class CreateFadeMask:
520
+
521
+ RETURN_TYPES = ("MASK",)
522
+ FUNCTION = "createfademask"
523
+ CATEGORY = "KJNodes/deprecated"
524
+
525
+ @classmethod
526
+ def INPUT_TYPES(s):
527
+ return {
528
+ "required": {
529
+ "invert": ("BOOLEAN", {"default": False}),
530
+ "frames": ("INT", {"default": 2,"min": 2, "max": 255, "step": 1}),
531
+ "width": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
532
+ "height": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
533
+ "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out"],),
534
+ "start_level": ("FLOAT", {"default": 1.0,"min": 0.0, "max": 1.0, "step": 0.01}),
535
+ "midpoint_level": ("FLOAT", {"default": 0.5,"min": 0.0, "max": 1.0, "step": 0.01}),
536
+ "end_level": ("FLOAT", {"default": 0.0,"min": 0.0, "max": 1.0, "step": 0.01}),
537
+ "midpoint_frame": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}),
538
+ },
539
+ }
540
+
541
+ def createfademask(self, frames, width, height, invert, interpolation, start_level, midpoint_level, end_level, midpoint_frame):
542
+ def ease_in(t):
543
+ return t * t
544
+
545
+ def ease_out(t):
546
+ return 1 - (1 - t) * (1 - t)
547
+
548
+ def ease_in_out(t):
549
+ return 3 * t * t - 2 * t * t * t
550
+
551
+ batch_size = frames
552
+ out = []
553
+ image_batch = np.zeros((batch_size, height, width), dtype=np.float32)
554
+
555
+ if midpoint_frame == 0:
556
+ midpoint_frame = batch_size // 2
557
+
558
+ for i in range(batch_size):
559
+ if i <= midpoint_frame:
560
+ t = i / midpoint_frame
561
+ if interpolation == "ease_in":
562
+ t = ease_in(t)
563
+ elif interpolation == "ease_out":
564
+ t = ease_out(t)
565
+ elif interpolation == "ease_in_out":
566
+ t = ease_in_out(t)
567
+ color = start_level - t * (start_level - midpoint_level)
568
+ else:
569
+ t = (i - midpoint_frame) / (batch_size - midpoint_frame)
570
+ if interpolation == "ease_in":
571
+ t = ease_in(t)
572
+ elif interpolation == "ease_out":
573
+ t = ease_out(t)
574
+ elif interpolation == "ease_in_out":
575
+ t = ease_in_out(t)
576
+ color = midpoint_level - t * (midpoint_level - end_level)
577
+
578
+ color = np.clip(color, 0, 255)
579
+ image = np.full((height, width), color, dtype=np.float32)
580
+ image_batch[i] = image
581
+
582
+ output = torch.from_numpy(image_batch)
583
+ mask = output
584
+ out.append(mask)
585
+
586
+ if invert:
587
+ return (1.0 - torch.cat(out, dim=0),)
588
+ return (torch.cat(out, dim=0),)
589
+
590
+ class CreateFadeMaskAdvanced:
591
+
592
+ RETURN_TYPES = ("MASK",)
593
+ FUNCTION = "createfademask"
594
+ CATEGORY = "KJNodes/masking/generate"
595
+ DESCRIPTION = """
596
+ Create a batch of masks interpolated between given frames and values.
597
+ Uses same syntax as Fizz' BatchValueSchedule.
598
+ First value is the frame index (not that this starts from 0, not 1)
599
+ and the second value inside the brackets is the float value of the mask in range 0.0 - 1.0
600
+
601
+ For example the default values:
602
+ 0:(0.0)
603
+ 7:(1.0)
604
+ 15:(0.0)
605
+
606
+ Would create a mask batch fo 16 frames, starting from black,
607
+ interpolating with the chosen curve to fully white at the 8th frame,
608
+ and interpolating from that to fully black at the 16th frame.
609
+ """
610
+
611
+ @classmethod
612
+ def INPUT_TYPES(s):
613
+ return {
614
+ "required": {
615
+ "points_string": ("STRING", {"default": "0:(0.0),\n7:(1.0),\n15:(0.0)\n", "multiline": True}),
616
+ "invert": ("BOOLEAN", {"default": False}),
617
+ "frames": ("INT", {"default": 16,"min": 2, "max": 255, "step": 1}),
618
+ "width": ("INT", {"default": 512,"min": 1, "max": 4096, "step": 1}),
619
+ "height": ("INT", {"default": 512,"min": 1, "max": 4096, "step": 1}),
620
+ "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out"],),
621
+ },
622
+ }
623
+
624
+ def createfademask(self, frames, width, height, invert, points_string, interpolation):
625
+ def ease_in(t):
626
+ return t * t
627
+
628
+ def ease_out(t):
629
+ return 1 - (1 - t) * (1 - t)
630
+
631
+ def ease_in_out(t):
632
+ return 3 * t * t - 2 * t * t * t
633
+
634
+ # Parse the input string into a list of tuples
635
+ points = []
636
+ points_string = points_string.rstrip(',\n')
637
+ for point_str in points_string.split(','):
638
+ frame_str, color_str = point_str.split(':')
639
+ frame = int(frame_str.strip())
640
+ color = float(color_str.strip()[1:-1]) # Remove parentheses around color
641
+ points.append((frame, color))
642
+
643
+ # Check if the last frame is already in the points
644
+ if len(points) == 0 or points[-1][0] != frames - 1:
645
+ # If not, add it with the color of the last specified frame
646
+ points.append((frames - 1, points[-1][1] if points else 0))
647
+
648
+ # Sort the points by frame number
649
+ points.sort(key=lambda x: x[0])
650
+
651
+ batch_size = frames
652
+ out = []
653
+ image_batch = np.zeros((batch_size, height, width), dtype=np.float32)
654
+
655
+ # Index of the next point to interpolate towards
656
+ next_point = 1
657
+
658
+ for i in range(batch_size):
659
+ while next_point < len(points) and i > points[next_point][0]:
660
+ next_point += 1
661
+
662
+ # Interpolate between the previous point and the next point
663
+ prev_point = next_point - 1
664
+ t = (i - points[prev_point][0]) / (points[next_point][0] - points[prev_point][0])
665
+ if interpolation == "ease_in":
666
+ t = ease_in(t)
667
+ elif interpolation == "ease_out":
668
+ t = ease_out(t)
669
+ elif interpolation == "ease_in_out":
670
+ t = ease_in_out(t)
671
+ elif interpolation == "linear":
672
+ pass # No need to modify `t` for linear interpolation
673
+
674
+ color = points[prev_point][1] - t * (points[prev_point][1] - points[next_point][1])
675
+ color = np.clip(color, 0, 255)
676
+ image = np.full((height, width), color, dtype=np.float32)
677
+ image_batch[i] = image
678
+
679
+ output = torch.from_numpy(image_batch)
680
+ mask = output
681
+ out.append(mask)
682
+
683
+ if invert:
684
+ return (1.0 - torch.cat(out, dim=0),)
685
+ return (torch.cat(out, dim=0),)
686
+
687
+ class CreateMagicMask:
688
+
689
+ RETURN_TYPES = ("MASK", "MASK",)
690
+ RETURN_NAMES = ("mask", "mask_inverted",)
691
+ FUNCTION = "createmagicmask"
692
+ CATEGORY = "KJNodes/masking/generate"
693
+
694
+ @classmethod
695
+ def INPUT_TYPES(s):
696
+ return {
697
+ "required": {
698
+ "frames": ("INT", {"default": 16,"min": 2, "max": 4096, "step": 1}),
699
+ "depth": ("INT", {"default": 12,"min": 1, "max": 500, "step": 1}),
700
+ "distortion": ("FLOAT", {"default": 1.5,"min": 0.0, "max": 100.0, "step": 0.01}),
701
+ "seed": ("INT", {"default": 123,"min": 0, "max": 99999999, "step": 1}),
702
+ "transitions": ("INT", {"default": 1,"min": 1, "max": 20, "step": 1}),
703
+ "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
704
+ "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
705
+ },
706
+ }
707
+
708
+ def createmagicmask(self, frames, transitions, depth, distortion, seed, frame_width, frame_height):
709
+ from ..utility.magictex import coordinate_grid, random_transform, magic
710
+ import matplotlib.pyplot as plt
711
+ rng = np.random.default_rng(seed)
712
+ out = []
713
+ coords = coordinate_grid((frame_width, frame_height))
714
+
715
+ # Calculate the number of frames for each transition
716
+ frames_per_transition = frames // transitions
717
+
718
+ # Generate a base set of parameters
719
+ base_params = {
720
+ "coords": random_transform(coords, rng),
721
+ "depth": depth,
722
+ "distortion": distortion,
723
+ }
724
+ for t in range(transitions):
725
+ # Generate a second set of parameters that is at most max_diff away from the base parameters
726
+ params1 = base_params.copy()
727
+ params2 = base_params.copy()
728
+
729
+ params1['coords'] = random_transform(coords, rng)
730
+ params2['coords'] = random_transform(coords, rng)
731
+
732
+ for i in range(frames_per_transition):
733
+ # Compute the interpolation factor
734
+ alpha = i / frames_per_transition
735
+
736
+ # Interpolate between the two sets of parameters
737
+ params = params1.copy()
738
+ params['coords'] = (1 - alpha) * params1['coords'] + alpha * params2['coords']
739
+
740
+ tex = magic(**params)
741
+
742
+ dpi = frame_width / 10
743
+ fig = plt.figure(figsize=(10, 10), dpi=dpi)
744
+
745
+ ax = fig.add_subplot(111)
746
+ plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
747
+
748
+ ax.get_yaxis().set_ticks([])
749
+ ax.get_xaxis().set_ticks([])
750
+ ax.imshow(tex, aspect='auto')
751
+
752
+ fig.canvas.draw()
753
+ img = np.array(fig.canvas.renderer._renderer)
754
+
755
+ plt.close(fig)
756
+
757
+ pil_img = Image.fromarray(img).convert("L")
758
+ mask = torch.tensor(np.array(pil_img)) / 255.0
759
+
760
+ out.append(mask)
761
+
762
+ return (torch.stack(out, dim=0), 1.0 - torch.stack(out, dim=0),)
763
+
764
+ class CreateShapeMask:
765
+
766
+ RETURN_TYPES = ("MASK", "MASK",)
767
+ RETURN_NAMES = ("mask", "mask_inverted",)
768
+ FUNCTION = "createshapemask"
769
+ CATEGORY = "KJNodes/masking/generate"
770
+ DESCRIPTION = """
771
+ Creates a mask or batch of masks with the specified shape.
772
+ Locations are center locations.
773
+ Grow value is the amount to grow the shape on each frame, creating animated masks.
774
+ """
775
+
776
+ @classmethod
777
+ def INPUT_TYPES(s):
778
+ return {
779
+ "required": {
780
+ "shape": (
781
+ [ 'circle',
782
+ 'square',
783
+ 'triangle',
784
+ ],
785
+ {
786
+ "default": 'circle'
787
+ }),
788
+ "frames": ("INT", {"default": 1,"min": 1, "max": 4096, "step": 1}),
789
+ "location_x": ("INT", {"default": 256,"min": 0, "max": 4096, "step": 1}),
790
+ "location_y": ("INT", {"default": 256,"min": 0, "max": 4096, "step": 1}),
791
+ "grow": ("INT", {"default": 0, "min": -512, "max": 512, "step": 1}),
792
+ "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
793
+ "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
794
+ "shape_width": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}),
795
+ "shape_height": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}),
796
+ },
797
+ }
798
+
799
+ def createshapemask(self, frames, frame_width, frame_height, location_x, location_y, shape_width, shape_height, grow, shape):
800
+ # Define the number of images in the batch
801
+ batch_size = frames
802
+ out = []
803
+ color = "white"
804
+ for i in range(batch_size):
805
+ image = Image.new("RGB", (frame_width, frame_height), "black")
806
+ draw = ImageDraw.Draw(image)
807
+
808
+ # Calculate the size for this frame and ensure it's not less than 0
809
+ current_width = max(0, shape_width + i*grow)
810
+ current_height = max(0, shape_height + i*grow)
811
+
812
+ if shape == 'circle' or shape == 'square':
813
+ # Define the bounding box for the shape
814
+ left_up_point = (location_x - current_width // 2, location_y - current_height // 2)
815
+ right_down_point = (location_x + current_width // 2, location_y + current_height // 2)
816
+ two_points = [left_up_point, right_down_point]
817
+
818
+ if shape == 'circle':
819
+ draw.ellipse(two_points, fill=color)
820
+ elif shape == 'square':
821
+ draw.rectangle(two_points, fill=color)
822
+
823
+ elif shape == 'triangle':
824
+ # Define the points for the triangle
825
+ left_up_point = (location_x - current_width // 2, location_y + current_height // 2) # bottom left
826
+ right_down_point = (location_x + current_width // 2, location_y + current_height // 2) # bottom right
827
+ top_point = (location_x, location_y - current_height // 2) # top point
828
+ draw.polygon([top_point, left_up_point, right_down_point], fill=color)
829
+
830
+ image = pil2tensor(image)
831
+ mask = image[:, :, :, 0]
832
+ out.append(mask)
833
+ outstack = torch.cat(out, dim=0)
834
+ return (outstack, 1.0 - outstack,)
835
+
836
+ class CreateVoronoiMask:
837
+
838
+ RETURN_TYPES = ("MASK", "MASK",)
839
+ RETURN_NAMES = ("mask", "mask_inverted",)
840
+ FUNCTION = "createvoronoi"
841
+ CATEGORY = "KJNodes/masking/generate"
842
+
843
+ @classmethod
844
+ def INPUT_TYPES(s):
845
+ return {
846
+ "required": {
847
+ "frames": ("INT", {"default": 16,"min": 2, "max": 4096, "step": 1}),
848
+ "num_points": ("INT", {"default": 15,"min": 1, "max": 4096, "step": 1}),
849
+ "line_width": ("INT", {"default": 4,"min": 1, "max": 4096, "step": 1}),
850
+ "speed": ("FLOAT", {"default": 0.5,"min": 0.0, "max": 1.0, "step": 0.01}),
851
+ "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
852
+ "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
853
+ },
854
+ }
855
+
856
+ def createvoronoi(self, frames, num_points, line_width, speed, frame_width, frame_height):
857
+ from scipy.spatial import Voronoi
858
+ # Define the number of images in the batch
859
+ batch_size = frames
860
+ out = []
861
+
862
+ # Calculate aspect ratio
863
+ aspect_ratio = frame_width / frame_height
864
+
865
+ # Create start and end points for each point, considering the aspect ratio
866
+ start_points = np.random.rand(num_points, 2)
867
+ start_points[:, 0] *= aspect_ratio
868
+
869
+ end_points = np.random.rand(num_points, 2)
870
+ end_points[:, 0] *= aspect_ratio
871
+
872
+ for i in range(batch_size):
873
+ # Interpolate the points' positions based on the current frame
874
+ t = (i * speed) / (batch_size - 1) # normalize to [0, 1] over the frames
875
+ t = np.clip(t, 0, 1) # ensure t is in [0, 1]
876
+ points = (1 - t) * start_points + t * end_points # lerp
877
+
878
+ # Adjust points for aspect ratio
879
+ points[:, 0] *= aspect_ratio
880
+
881
+ vor = Voronoi(points)
882
+
883
+ # Create a blank image with a white background
884
+ fig, ax = plt.subplots()
885
+ plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
886
+ ax.set_xlim([0, aspect_ratio]); ax.set_ylim([0, 1]) # adjust x limits
887
+ ax.axis('off')
888
+ ax.margins(0, 0)
889
+ fig.set_size_inches(aspect_ratio * frame_height/100, frame_height/100) # adjust figure size
890
+ ax.fill_between([0, 1], [0, 1], color='white')
891
+
892
+ # Plot each Voronoi ridge
893
+ for simplex in vor.ridge_vertices:
894
+ simplex = np.asarray(simplex)
895
+ if np.all(simplex >= 0):
896
+ plt.plot(vor.vertices[simplex, 0], vor.vertices[simplex, 1], 'k-', linewidth=line_width)
897
+
898
+ fig.canvas.draw()
899
+ img = np.array(fig.canvas.renderer._renderer)
900
+
901
+ plt.close(fig)
902
+
903
+ pil_img = Image.fromarray(img).convert("L")
904
+ mask = torch.tensor(np.array(pil_img)) / 255.0
905
+
906
+ out.append(mask)
907
+
908
+ return (torch.stack(out, dim=0), 1.0 - torch.stack(out, dim=0),)
909
+
910
+ class GetMaskSizeAndCount:
911
+ @classmethod
912
+ def INPUT_TYPES(s):
913
+ return {"required": {
914
+ "mask": ("MASK",),
915
+ }}
916
+
917
+ RETURN_TYPES = ("MASK","INT", "INT", "INT",)
918
+ RETURN_NAMES = ("mask", "width", "height", "count",)
919
+ FUNCTION = "getsize"
920
+ CATEGORY = "KJNodes/masking"
921
+ DESCRIPTION = """
922
+ Returns the width, height and batch size of the mask,
923
+ and passes it through unchanged.
924
+
925
+ """
926
+
927
+ def getsize(self, mask):
928
+ width = mask.shape[2]
929
+ height = mask.shape[1]
930
+ count = mask.shape[0]
931
+ return {"ui": {
932
+ "text": [f"{count}x{width}x{height}"]},
933
+ "result": (mask, width, height, count)
934
+ }
935
+
936
+ class GrowMaskWithBlur:
937
+ @classmethod
938
+ def INPUT_TYPES(cls):
939
+ return {
940
+ "required": {
941
+ "mask": ("MASK",),
942
+ "expand": ("INT", {"default": 0, "min": -MAX_RESOLUTION, "max": MAX_RESOLUTION, "step": 1}),
943
+ "incremental_expandrate": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.1}),
944
+ "tapered_corners": ("BOOLEAN", {"default": True}),
945
+ "flip_input": ("BOOLEAN", {"default": False}),
946
+ "blur_radius": ("FLOAT", {
947
+ "default": 0.0,
948
+ "min": 0.0,
949
+ "max": 100,
950
+ "step": 0.1
951
+ }),
952
+ "lerp_alpha": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
953
+ "decay_factor": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
954
+ },
955
+ "optional": {
956
+ "fill_holes": ("BOOLEAN", {"default": False}),
957
+ },
958
+ }
959
+
960
+ CATEGORY = "KJNodes/masking"
961
+ RETURN_TYPES = ("MASK", "MASK",)
962
+ RETURN_NAMES = ("mask", "mask_inverted",)
963
+ FUNCTION = "expand_mask"
964
+ DESCRIPTION = """
965
+ # GrowMaskWithBlur
966
+ - mask: Input mask or mask batch
967
+ - expand: Expand or contract mask or mask batch by a given amount
968
+ - incremental_expandrate: increase expand rate by a given amount per frame
969
+ - tapered_corners: use tapered corners
970
+ - flip_input: flip input mask
971
+ - blur_radius: value higher than 0 will blur the mask
972
+ - lerp_alpha: alpha value for interpolation between frames
973
+ - decay_factor: decay value for interpolation between frames
974
+ - fill_holes: fill holes in the mask (slow)"""
975
+
976
+ def expand_mask(self, mask, expand, tapered_corners, flip_input, blur_radius, incremental_expandrate, lerp_alpha, decay_factor, fill_holes=False):
977
+ alpha = lerp_alpha
978
+ decay = decay_factor
979
+ if flip_input:
980
+ mask = 1.0 - mask
981
+ c = 0 if tapered_corners else 1
982
+ kernel = np.array([[c, 1, c],
983
+ [1, 1, 1],
984
+ [c, 1, c]])
985
+ growmask = mask.reshape((-1, mask.shape[-2], mask.shape[-1])).cpu()
986
+ out = []
987
+ previous_output = None
988
+ current_expand = expand
989
+ for m in growmask:
990
+ output = m.numpy().astype(np.float32)
991
+ for _ in range(abs(round(current_expand))):
992
+ if current_expand < 0:
993
+ output = scipy.ndimage.grey_erosion(output, footprint=kernel)
994
+ else:
995
+ output = scipy.ndimage.grey_dilation(output, footprint=kernel)
996
+ if current_expand < 0:
997
+ current_expand -= abs(incremental_expandrate)
998
+ else:
999
+ current_expand += abs(incremental_expandrate)
1000
+ if fill_holes:
1001
+ binary_mask = output > 0
1002
+ output = scipy.ndimage.binary_fill_holes(binary_mask)
1003
+ output = output.astype(np.float32) * 255
1004
+ output = torch.from_numpy(output)
1005
+ if alpha < 1.0 and previous_output is not None:
1006
+ # Interpolate between the previous and current frame
1007
+ output = alpha * output + (1 - alpha) * previous_output
1008
+ if decay < 1.0 and previous_output is not None:
1009
+ # Add the decayed previous output to the current frame
1010
+ output += decay * previous_output
1011
+ output = output / output.max()
1012
+ previous_output = output
1013
+ out.append(output)
1014
+
1015
+ if blur_radius != 0:
1016
+ # Convert the tensor list to PIL images, apply blur, and convert back
1017
+ for idx, tensor in enumerate(out):
1018
+ # Convert tensor to PIL image
1019
+ pil_image = tensor2pil(tensor.cpu().detach())[0]
1020
+ # Apply Gaussian blur
1021
+ pil_image = pil_image.filter(ImageFilter.GaussianBlur(blur_radius))
1022
+ # Convert back to tensor
1023
+ out[idx] = pil2tensor(pil_image)
1024
+ blurred = torch.cat(out, dim=0)
1025
+ return (blurred, 1.0 - blurred)
1026
+ else:
1027
+ return (torch.stack(out, dim=0), 1.0 - torch.stack(out, dim=0),)
1028
+
1029
+ class MaskBatchMulti:
1030
+ @classmethod
1031
+ def INPUT_TYPES(s):
1032
+ return {
1033
+ "required": {
1034
+ "inputcount": ("INT", {"default": 2, "min": 2, "max": 1000, "step": 1}),
1035
+ "mask_1": ("MASK", ),
1036
+ "mask_2": ("MASK", ),
1037
+ },
1038
+ }
1039
+
1040
+ RETURN_TYPES = ("MASK",)
1041
+ RETURN_NAMES = ("masks",)
1042
+ FUNCTION = "combine"
1043
+ CATEGORY = "KJNodes/masking"
1044
+ DESCRIPTION = """
1045
+ Creates an image batch from multiple masks.
1046
+ You can set how many inputs the node has,
1047
+ with the **inputcount** and clicking update.
1048
+ """
1049
+
1050
+ def combine(self, inputcount, **kwargs):
1051
+ mask = kwargs["mask_1"]
1052
+ for c in range(1, inputcount):
1053
+ new_mask = kwargs[f"mask_{c + 1}"]
1054
+ if mask.shape[1:] != new_mask.shape[1:]:
1055
+ new_mask = F.interpolate(new_mask.unsqueeze(1), size=(mask.shape[1], mask.shape[2]), mode="bicubic").squeeze(1)
1056
+ mask = torch.cat((mask, new_mask), dim=0)
1057
+ return (mask,)
1058
+
1059
+ class OffsetMask:
1060
+ @classmethod
1061
+ def INPUT_TYPES(s):
1062
+ return {
1063
+ "required": {
1064
+ "mask": ("MASK",),
1065
+ "x": ("INT", { "default": 0, "min": -4096, "max": MAX_RESOLUTION, "step": 1, "display": "number" }),
1066
+ "y": ("INT", { "default": 0, "min": -4096, "max": MAX_RESOLUTION, "step": 1, "display": "number" }),
1067
+ "angle": ("INT", { "default": 0, "min": -360, "max": 360, "step": 1, "display": "number" }),
1068
+ "duplication_factor": ("INT", { "default": 1, "min": 1, "max": 1000, "step": 1, "display": "number" }),
1069
+ "roll": ("BOOLEAN", { "default": False }),
1070
+ "incremental": ("BOOLEAN", { "default": False }),
1071
+ "padding_mode": (
1072
+ [
1073
+ 'empty',
1074
+ 'border',
1075
+ 'reflection',
1076
+
1077
+ ], {
1078
+ "default": 'empty'
1079
+ }),
1080
+ }
1081
+ }
1082
+
1083
+ RETURN_TYPES = ("MASK",)
1084
+ RETURN_NAMES = ("mask",)
1085
+ FUNCTION = "offset"
1086
+ CATEGORY = "KJNodes/masking"
1087
+ DESCRIPTION = """
1088
+ Offsets the mask by the specified amount.
1089
+ - mask: Input mask or mask batch
1090
+ - x: Horizontal offset
1091
+ - y: Vertical offset
1092
+ - angle: Angle in degrees
1093
+ - roll: roll edge wrapping
1094
+ - duplication_factor: Number of times to duplicate the mask to form a batch
1095
+ - border padding_mode: Padding mode for the mask
1096
+ """
1097
+
1098
+ def offset(self, mask, x, y, angle, roll=False, incremental=False, duplication_factor=1, padding_mode="empty"):
1099
+ # Create duplicates of the mask batch
1100
+ mask = mask.repeat(duplication_factor, 1, 1).clone()
1101
+
1102
+ batch_size, height, width = mask.shape
1103
+
1104
+ if angle != 0 and incremental:
1105
+ for i in range(batch_size):
1106
+ rotation_angle = angle * (i+1)
1107
+ mask[i] = TF.rotate(mask[i].unsqueeze(0), rotation_angle).squeeze(0)
1108
+ elif angle > 0:
1109
+ for i in range(batch_size):
1110
+ mask[i] = TF.rotate(mask[i].unsqueeze(0), angle).squeeze(0)
1111
+
1112
+ if roll:
1113
+ if incremental:
1114
+ for i in range(batch_size):
1115
+ shift_x = min(x*(i+1), width-1)
1116
+ shift_y = min(y*(i+1), height-1)
1117
+ if shift_x != 0:
1118
+ mask[i] = torch.roll(mask[i], shifts=shift_x, dims=1)
1119
+ if shift_y != 0:
1120
+ mask[i] = torch.roll(mask[i], shifts=shift_y, dims=0)
1121
+ else:
1122
+ shift_x = min(x, width-1)
1123
+ shift_y = min(y, height-1)
1124
+ if shift_x != 0:
1125
+ mask = torch.roll(mask, shifts=shift_x, dims=2)
1126
+ if shift_y != 0:
1127
+ mask = torch.roll(mask, shifts=shift_y, dims=1)
1128
+ else:
1129
+
1130
+ for i in range(batch_size):
1131
+ if incremental:
1132
+ temp_x = min(x * (i+1), width-1)
1133
+ temp_y = min(y * (i+1), height-1)
1134
+ else:
1135
+ temp_x = min(x, width-1)
1136
+ temp_y = min(y, height-1)
1137
+ if temp_x > 0:
1138
+ if padding_mode == 'empty':
1139
+ mask[i] = torch.cat([torch.zeros((height, temp_x)), mask[i, :, :-temp_x]], dim=1)
1140
+ elif padding_mode in ['replicate', 'reflect']:
1141
+ mask[i] = F.pad(mask[i, :, :-temp_x], (0, temp_x), mode=padding_mode)
1142
+ elif temp_x < 0:
1143
+ if padding_mode == 'empty':
1144
+ mask[i] = torch.cat([mask[i, :, :temp_x], torch.zeros((height, -temp_x))], dim=1)
1145
+ elif padding_mode in ['replicate', 'reflect']:
1146
+ mask[i] = F.pad(mask[i, :, -temp_x:], (temp_x, 0), mode=padding_mode)
1147
+
1148
+ if temp_y > 0:
1149
+ if padding_mode == 'empty':
1150
+ mask[i] = torch.cat([torch.zeros((temp_y, width)), mask[i, :-temp_y, :]], dim=0)
1151
+ elif padding_mode in ['replicate', 'reflect']:
1152
+ mask[i] = F.pad(mask[i, :-temp_y, :], (0, temp_y), mode=padding_mode)
1153
+ elif temp_y < 0:
1154
+ if padding_mode == 'empty':
1155
+ mask[i] = torch.cat([mask[i, :temp_y, :], torch.zeros((-temp_y, width))], dim=0)
1156
+ elif padding_mode in ['replicate', 'reflect']:
1157
+ mask[i] = F.pad(mask[i, -temp_y:, :], (temp_y, 0), mode=padding_mode)
1158
+
1159
+ return mask,
1160
+
1161
+ class RoundMask:
1162
+ @classmethod
1163
+ def INPUT_TYPES(s):
1164
+ return {"required": {
1165
+ "mask": ("MASK",),
1166
+ }}
1167
+
1168
+ RETURN_TYPES = ("MASK",)
1169
+ FUNCTION = "round"
1170
+ CATEGORY = "KJNodes/masking"
1171
+ DESCRIPTION = """
1172
+ Rounds the mask or batch of masks to a binary mask.
1173
+ <img src="https://github.com/kijai/ComfyUI-KJNodes/assets/40791699/52c85202-f74e-4b96-9dac-c8bda5ddcc40" width="300" height="250" alt="RoundMask example">
1174
+
1175
+ """
1176
+
1177
+ def round(self, mask):
1178
+ mask = mask.round()
1179
+ return (mask,)
1180
+
1181
+ class ResizeMask:
1182
+ @classmethod
1183
+ def INPUT_TYPES(s):
1184
+ return {
1185
+ "required": {
1186
+ "mask": ("MASK",),
1187
+ "width": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8, "display": "number" }),
1188
+ "height": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 8, "display": "number" }),
1189
+ "keep_proportions": ("BOOLEAN", { "default": False }),
1190
+ }
1191
+ }
1192
+
1193
+ RETURN_TYPES = ("MASK", "INT", "INT",)
1194
+ RETURN_NAMES = ("mask", "width", "height",)
1195
+ FUNCTION = "resize"
1196
+ CATEGORY = "KJNodes/masking"
1197
+ DESCRIPTION = """
1198
+ Resizes the mask or batch of masks to the specified width and height.
1199
+ """
1200
+
1201
+ def resize(self, mask, width, height, keep_proportions):
1202
+ if keep_proportions:
1203
+ _, oh, ow = mask.shape
1204
+ width = ow if width == 0 else width
1205
+ height = oh if height == 0 else height
1206
+ ratio = min(width / ow, height / oh)
1207
+ width = round(ow*ratio)
1208
+ height = round(oh*ratio)
1209
+ outputs = mask.unsqueeze(1)
1210
+ outputs = F.interpolate(outputs, size=(height, width), mode="nearest")
1211
+ outputs = outputs.squeeze(1)
1212
+
1213
+ return(outputs, outputs.shape[2], outputs.shape[1],)
1214
+
1215
+ class RemapMaskRange:
1216
+ @classmethod
1217
+ def INPUT_TYPES(s):
1218
+ return {
1219
+ "required": {
1220
+ "mask": ("MASK",),
1221
+ "min": ("FLOAT", {"default": 0.0,"min": -10.0, "max": 1.0, "step": 0.01}),
1222
+ "max": ("FLOAT", {"default": 1.0,"min": 0.0, "max": 10.0, "step": 0.01}),
1223
+ }
1224
+ }
1225
+
1226
+ RETURN_TYPES = ("MASK",)
1227
+ RETURN_NAMES = ("mask",)
1228
+ FUNCTION = "remap"
1229
+ CATEGORY = "KJNodes/masking"
1230
+ DESCRIPTION = """
1231
+ Sets new min and max values for the mask.
1232
+ """
1233
+
1234
+ def remap(self, mask, min, max):
1235
+
1236
+ # Find the maximum value in the mask
1237
+ mask_max = torch.max(mask)
1238
+
1239
+ # If the maximum mask value is zero, avoid division by zero by setting it to 1
1240
+ mask_max = mask_max if mask_max > 0 else 1
1241
+
1242
+ # Scale the mask values to the new range defined by min and max
1243
+ # The highest pixel value in the mask will be scaled to max
1244
+ scaled_mask = (mask / mask_max) * (max - min) + min
1245
+
1246
+ # Clamp the values to ensure they are within [0.0, 1.0]
1247
+ scaled_mask = torch.clamp(scaled_mask, min=0.0, max=1.0)
1248
+
1249
+ return (scaled_mask, )
ComfyUI/custom_nodes/ComfyUI-KJNodes/nodes/nodes.py ADDED
@@ -0,0 +1,1754 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from PIL import Image
4
+
5
+ import json, re, os, io, time
6
+
7
+ import model_management
8
+ import folder_paths
9
+ from nodes import MAX_RESOLUTION
10
+ from comfy.utils import common_upscale, ProgressBar
11
+
12
+ script_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
13
+ folder_paths.add_model_folder_path("kjnodes_fonts", os.path.join(script_directory, "fonts"))
14
+
15
+ class AnyType(str):
16
+ """A special class that is always equal in not equal comparisons. Credit to pythongosssss"""
17
+
18
+ def __ne__(self, __value: object) -> bool:
19
+ return False
20
+ any = AnyType("*")
21
+
22
+ class INTConstant:
23
+ @classmethod
24
+ def INPUT_TYPES(s):
25
+ return {"required": {
26
+ "value": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
27
+ },
28
+ }
29
+ RETURN_TYPES = ("INT",)
30
+ RETURN_NAMES = ("value",)
31
+ FUNCTION = "get_value"
32
+ CATEGORY = "KJNodes/constants"
33
+
34
+ def get_value(self, value):
35
+ return (value,)
36
+
37
+ class FloatConstant:
38
+ @classmethod
39
+ def INPUT_TYPES(s):
40
+ return {"required": {
41
+ "value": ("FLOAT", {"default": 0.0, "min": -0xffffffffffffffff, "max": 0xffffffffffffffff, "step": 0.001}),
42
+ },
43
+ }
44
+
45
+ RETURN_TYPES = ("FLOAT",)
46
+ RETURN_NAMES = ("value",)
47
+ FUNCTION = "get_value"
48
+ CATEGORY = "KJNodes/constants"
49
+
50
+ def get_value(self, value):
51
+ return (value,)
52
+
53
+ class StringConstant:
54
+ @classmethod
55
+ def INPUT_TYPES(cls):
56
+ return {
57
+ "required": {
58
+ "string": ("STRING", {"default": '', "multiline": False}),
59
+ }
60
+ }
61
+ RETURN_TYPES = ("STRING",)
62
+ FUNCTION = "passtring"
63
+ CATEGORY = "KJNodes/constants"
64
+
65
+ def passtring(self, string):
66
+ return (string, )
67
+
68
+ class StringConstantMultiline:
69
+ @classmethod
70
+ def INPUT_TYPES(cls):
71
+ return {
72
+ "required": {
73
+ "string": ("STRING", {"default": "", "multiline": True}),
74
+ "strip_newlines": ("BOOLEAN", {"default": True}),
75
+ }
76
+ }
77
+ RETURN_TYPES = ("STRING",)
78
+ FUNCTION = "stringify"
79
+ CATEGORY = "KJNodes/constants"
80
+
81
+ def stringify(self, string, strip_newlines):
82
+ new_string = []
83
+ for line in io.StringIO(string):
84
+ if not line.strip().startswith("\n") and strip_newlines:
85
+ line = line.replace("\n", '')
86
+ new_string.append(line)
87
+ new_string = "\n".join(new_string)
88
+
89
+ return (new_string, )
90
+
91
+
92
+
93
+ class ScaleBatchPromptSchedule:
94
+
95
+ RETURN_TYPES = ("STRING",)
96
+ FUNCTION = "scaleschedule"
97
+ CATEGORY = "KJNodes"
98
+ DESCRIPTION = """
99
+ Scales a batch schedule from Fizz' nodes BatchPromptSchedule
100
+ to a different frame count.
101
+ """
102
+
103
+ @classmethod
104
+ def INPUT_TYPES(s):
105
+ return {
106
+ "required": {
107
+ "input_str": ("STRING", {"forceInput": True,"default": "0:(0.0),\n7:(1.0),\n15:(0.0)\n"}),
108
+ "old_frame_count": ("INT", {"forceInput": True,"default": 1,"min": 1, "max": 4096, "step": 1}),
109
+ "new_frame_count": ("INT", {"forceInput": True,"default": 1,"min": 1, "max": 4096, "step": 1}),
110
+
111
+ },
112
+ }
113
+
114
+ def scaleschedule(self, old_frame_count, input_str, new_frame_count):
115
+ pattern = r'"(\d+)"\s*:\s*"(.*?)"(?:,|\Z)'
116
+ frame_strings = dict(re.findall(pattern, input_str))
117
+
118
+ # Calculate the scaling factor
119
+ scaling_factor = (new_frame_count - 1) / (old_frame_count - 1)
120
+
121
+ # Initialize a dictionary to store the new frame numbers and strings
122
+ new_frame_strings = {}
123
+
124
+ # Iterate over the frame numbers and strings
125
+ for old_frame, string in frame_strings.items():
126
+ # Calculate the new frame number
127
+ new_frame = int(round(int(old_frame) * scaling_factor))
128
+
129
+ # Store the new frame number and corresponding string
130
+ new_frame_strings[new_frame] = string
131
+
132
+ # Format the output string
133
+ output_str = ', '.join([f'"{k}":"{v}"' for k, v in sorted(new_frame_strings.items())])
134
+ return (output_str,)
135
+
136
+
137
+ class GetLatentsFromBatchIndexed:
138
+
139
+ RETURN_TYPES = ("LATENT",)
140
+ FUNCTION = "indexedlatentsfrombatch"
141
+ CATEGORY = "KJNodes"
142
+ DESCRIPTION = """
143
+ Selects and returns the latents at the specified indices as an latent batch.
144
+ """
145
+
146
+ @classmethod
147
+ def INPUT_TYPES(s):
148
+ return {
149
+ "required": {
150
+ "latents": ("LATENT",),
151
+ "indexes": ("STRING", {"default": "0, 1, 2", "multiline": True}),
152
+ },
153
+ }
154
+
155
+ def indexedlatentsfrombatch(self, latents, indexes):
156
+
157
+ samples = latents.copy()
158
+ latent_samples = samples["samples"]
159
+
160
+ # Parse the indexes string into a list of integers
161
+ index_list = [int(index.strip()) for index in indexes.split(',')]
162
+
163
+ # Convert list of indices to a PyTorch tensor
164
+ indices_tensor = torch.tensor(index_list, dtype=torch.long)
165
+
166
+ # Select the latents at the specified indices
167
+ chosen_latents = latent_samples[indices_tensor]
168
+
169
+ samples["samples"] = chosen_latents
170
+ return (samples,)
171
+
172
+
173
+ class ConditioningMultiCombine:
174
+ @classmethod
175
+ def INPUT_TYPES(s):
176
+ return {
177
+ "required": {
178
+ "inputcount": ("INT", {"default": 2, "min": 2, "max": 20, "step": 1}),
179
+ "conditioning_1": ("CONDITIONING", ),
180
+ "conditioning_2": ("CONDITIONING", ),
181
+ },
182
+ }
183
+
184
+ RETURN_TYPES = ("CONDITIONING", "INT")
185
+ RETURN_NAMES = ("combined", "inputcount")
186
+ FUNCTION = "combine"
187
+ CATEGORY = "KJNodes/masking/conditioning"
188
+ DESCRIPTION = """
189
+ Combines multiple conditioning nodes into one
190
+ """
191
+
192
+ def combine(self, inputcount, **kwargs):
193
+ from nodes import ConditioningCombine
194
+ cond_combine_node = ConditioningCombine()
195
+ cond = kwargs["conditioning_1"]
196
+ for c in range(1, inputcount):
197
+ new_cond = kwargs[f"conditioning_{c + 1}"]
198
+ cond = cond_combine_node.combine(new_cond, cond)[0]
199
+ return (cond, inputcount,)
200
+
201
+
202
+ class JoinStrings:
203
+ @classmethod
204
+ def INPUT_TYPES(cls):
205
+ return {
206
+ "required": {
207
+ "string1": ("STRING", {"default": '', "forceInput": True}),
208
+ "string2": ("STRING", {"default": '', "forceInput": True}),
209
+ "delimiter": ("STRING", {"default": ' ', "multiline": False}),
210
+ }
211
+ }
212
+ RETURN_TYPES = ("STRING",)
213
+ FUNCTION = "joinstring"
214
+ CATEGORY = "KJNodes/constants"
215
+
216
+ def joinstring(self, string1, string2, delimiter):
217
+ joined_string = string1 + delimiter + string2
218
+ return (joined_string, )
219
+
220
+ class JoinStringMulti:
221
+ @classmethod
222
+ def INPUT_TYPES(s):
223
+ return {
224
+ "required": {
225
+ "inputcount": ("INT", {"default": 2, "min": 2, "max": 1000, "step": 1}),
226
+ "string_1": ("STRING", {"default": '', "forceInput": True}),
227
+ "string_2": ("STRING", {"default": '', "forceInput": True}),
228
+ "delimiter": ("STRING", {"default": ' ', "multiline": False}),
229
+ "return_list": ("BOOLEAN", {"default": False}),
230
+ },
231
+ }
232
+
233
+ RETURN_TYPES = ("STRING",)
234
+ RETURN_NAMES = ("string",)
235
+ FUNCTION = "combine"
236
+ CATEGORY = "KJNodes"
237
+ DESCRIPTION = """
238
+ Creates single string, or a list of strings, from
239
+ multiple input strings.
240
+ You can set how many inputs the node has,
241
+ with the **inputcount** and clicking update.
242
+ """
243
+
244
+ def combine(self, inputcount, delimiter, **kwargs):
245
+ string = kwargs["string_1"]
246
+ return_list = kwargs["return_list"]
247
+ strings = [string] # Initialize a list with the first string
248
+ for c in range(1, inputcount):
249
+ new_string = kwargs[f"string_{c + 1}"]
250
+ if return_list:
251
+ strings.append(new_string) # Add new string to the list
252
+ else:
253
+ string = string + delimiter + new_string
254
+ if return_list:
255
+ return (strings,) # Return the list of strings
256
+ else:
257
+ return (string,) # Return the combined string
258
+
259
+ class CondPassThrough:
260
+ @classmethod
261
+ def INPUT_TYPES(s):
262
+ return {
263
+ "required": {
264
+ "positive": ("CONDITIONING", ),
265
+ "negative": ("CONDITIONING", ),
266
+ },
267
+ }
268
+
269
+ RETURN_TYPES = ("CONDITIONING", "CONDITIONING",)
270
+ RETURN_NAMES = ("positive", "negative")
271
+ FUNCTION = "passthrough"
272
+ CATEGORY = "KJNodes/misc"
273
+ DESCRIPTION = """
274
+ Simply passes through the positive and negative conditioning,
275
+ workaround for Set node not allowing bypassed inputs.
276
+ """
277
+
278
+ def passthrough(self, positive, negative):
279
+ return (positive, negative,)
280
+
281
+ class ModelPassThrough:
282
+ @classmethod
283
+ def INPUT_TYPES(s):
284
+ return {
285
+ "required": {
286
+ "model": ("MODEL", ),
287
+ },
288
+ }
289
+
290
+ RETURN_TYPES = ("MODEL", )
291
+ RETURN_NAMES = ("model",)
292
+ FUNCTION = "passthrough"
293
+ CATEGORY = "KJNodes/misc"
294
+ DESCRIPTION = """
295
+ Simply passes through the model,
296
+ workaround for Set node not allowing bypassed inputs.
297
+ """
298
+
299
+ def passthrough(self, model):
300
+ return (model,)
301
+
302
+ def append_helper(t, mask, c, set_area_to_bounds, strength):
303
+ n = [t[0], t[1].copy()]
304
+ _, h, w = mask.shape
305
+ n[1]['mask'] = mask
306
+ n[1]['set_area_to_bounds'] = set_area_to_bounds
307
+ n[1]['mask_strength'] = strength
308
+ c.append(n)
309
+
310
+ class ConditioningSetMaskAndCombine:
311
+ @classmethod
312
+ def INPUT_TYPES(cls):
313
+ return {
314
+ "required": {
315
+ "positive_1": ("CONDITIONING", ),
316
+ "negative_1": ("CONDITIONING", ),
317
+ "positive_2": ("CONDITIONING", ),
318
+ "negative_2": ("CONDITIONING", ),
319
+ "mask_1": ("MASK", ),
320
+ "mask_2": ("MASK", ),
321
+ "mask_1_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
322
+ "mask_2_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
323
+ "set_cond_area": (["default", "mask bounds"],),
324
+ }
325
+ }
326
+
327
+ RETURN_TYPES = ("CONDITIONING","CONDITIONING",)
328
+ RETURN_NAMES = ("combined_positive", "combined_negative",)
329
+ FUNCTION = "append"
330
+ CATEGORY = "KJNodes/masking/conditioning"
331
+ DESCRIPTION = """
332
+ Bundles multiple conditioning mask and combine nodes into one,functionality is identical to ComfyUI native nodes
333
+ """
334
+
335
+ def append(self, positive_1, negative_1, positive_2, negative_2, mask_1, mask_2, set_cond_area, mask_1_strength, mask_2_strength):
336
+ c = []
337
+ c2 = []
338
+ set_area_to_bounds = False
339
+ if set_cond_area != "default":
340
+ set_area_to_bounds = True
341
+ if len(mask_1.shape) < 3:
342
+ mask_1 = mask_1.unsqueeze(0)
343
+ if len(mask_2.shape) < 3:
344
+ mask_2 = mask_2.unsqueeze(0)
345
+ for t in positive_1:
346
+ append_helper(t, mask_1, c, set_area_to_bounds, mask_1_strength)
347
+ for t in positive_2:
348
+ append_helper(t, mask_2, c, set_area_to_bounds, mask_2_strength)
349
+ for t in negative_1:
350
+ append_helper(t, mask_1, c2, set_area_to_bounds, mask_1_strength)
351
+ for t in negative_2:
352
+ append_helper(t, mask_2, c2, set_area_to_bounds, mask_2_strength)
353
+ return (c, c2)
354
+
355
+ class ConditioningSetMaskAndCombine3:
356
+ @classmethod
357
+ def INPUT_TYPES(cls):
358
+ return {
359
+ "required": {
360
+ "positive_1": ("CONDITIONING", ),
361
+ "negative_1": ("CONDITIONING", ),
362
+ "positive_2": ("CONDITIONING", ),
363
+ "negative_2": ("CONDITIONING", ),
364
+ "positive_3": ("CONDITIONING", ),
365
+ "negative_3": ("CONDITIONING", ),
366
+ "mask_1": ("MASK", ),
367
+ "mask_2": ("MASK", ),
368
+ "mask_3": ("MASK", ),
369
+ "mask_1_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
370
+ "mask_2_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
371
+ "mask_3_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
372
+ "set_cond_area": (["default", "mask bounds"],),
373
+ }
374
+ }
375
+
376
+ RETURN_TYPES = ("CONDITIONING","CONDITIONING",)
377
+ RETURN_NAMES = ("combined_positive", "combined_negative",)
378
+ FUNCTION = "append"
379
+ CATEGORY = "KJNodes/masking/conditioning"
380
+ DESCRIPTION = """
381
+ Bundles multiple conditioning mask and combine nodes into one,functionality is identical to ComfyUI native nodes
382
+ """
383
+
384
+ def append(self, positive_1, negative_1, positive_2, positive_3, negative_2, negative_3, mask_1, mask_2, mask_3, set_cond_area, mask_1_strength, mask_2_strength, mask_3_strength):
385
+ c = []
386
+ c2 = []
387
+ set_area_to_bounds = False
388
+ if set_cond_area != "default":
389
+ set_area_to_bounds = True
390
+ if len(mask_1.shape) < 3:
391
+ mask_1 = mask_1.unsqueeze(0)
392
+ if len(mask_2.shape) < 3:
393
+ mask_2 = mask_2.unsqueeze(0)
394
+ if len(mask_3.shape) < 3:
395
+ mask_3 = mask_3.unsqueeze(0)
396
+ for t in positive_1:
397
+ append_helper(t, mask_1, c, set_area_to_bounds, mask_1_strength)
398
+ for t in positive_2:
399
+ append_helper(t, mask_2, c, set_area_to_bounds, mask_2_strength)
400
+ for t in positive_3:
401
+ append_helper(t, mask_3, c, set_area_to_bounds, mask_3_strength)
402
+ for t in negative_1:
403
+ append_helper(t, mask_1, c2, set_area_to_bounds, mask_1_strength)
404
+ for t in negative_2:
405
+ append_helper(t, mask_2, c2, set_area_to_bounds, mask_2_strength)
406
+ for t in negative_3:
407
+ append_helper(t, mask_3, c2, set_area_to_bounds, mask_3_strength)
408
+ return (c, c2)
409
+
410
+ class ConditioningSetMaskAndCombine4:
411
+ @classmethod
412
+ def INPUT_TYPES(cls):
413
+ return {
414
+ "required": {
415
+ "positive_1": ("CONDITIONING", ),
416
+ "negative_1": ("CONDITIONING", ),
417
+ "positive_2": ("CONDITIONING", ),
418
+ "negative_2": ("CONDITIONING", ),
419
+ "positive_3": ("CONDITIONING", ),
420
+ "negative_3": ("CONDITIONING", ),
421
+ "positive_4": ("CONDITIONING", ),
422
+ "negative_4": ("CONDITIONING", ),
423
+ "mask_1": ("MASK", ),
424
+ "mask_2": ("MASK", ),
425
+ "mask_3": ("MASK", ),
426
+ "mask_4": ("MASK", ),
427
+ "mask_1_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
428
+ "mask_2_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
429
+ "mask_3_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
430
+ "mask_4_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
431
+ "set_cond_area": (["default", "mask bounds"],),
432
+ }
433
+ }
434
+
435
+ RETURN_TYPES = ("CONDITIONING","CONDITIONING",)
436
+ RETURN_NAMES = ("combined_positive", "combined_negative",)
437
+ FUNCTION = "append"
438
+ CATEGORY = "KJNodes/masking/conditioning"
439
+ DESCRIPTION = """
440
+ Bundles multiple conditioning mask and combine nodes into one,functionality is identical to ComfyUI native nodes
441
+ """
442
+
443
+ def append(self, positive_1, negative_1, positive_2, positive_3, positive_4, negative_2, negative_3, negative_4, mask_1, mask_2, mask_3, mask_4, set_cond_area, mask_1_strength, mask_2_strength, mask_3_strength, mask_4_strength):
444
+ c = []
445
+ c2 = []
446
+ set_area_to_bounds = False
447
+ if set_cond_area != "default":
448
+ set_area_to_bounds = True
449
+ if len(mask_1.shape) < 3:
450
+ mask_1 = mask_1.unsqueeze(0)
451
+ if len(mask_2.shape) < 3:
452
+ mask_2 = mask_2.unsqueeze(0)
453
+ if len(mask_3.shape) < 3:
454
+ mask_3 = mask_3.unsqueeze(0)
455
+ if len(mask_4.shape) < 3:
456
+ mask_4 = mask_4.unsqueeze(0)
457
+ for t in positive_1:
458
+ append_helper(t, mask_1, c, set_area_to_bounds, mask_1_strength)
459
+ for t in positive_2:
460
+ append_helper(t, mask_2, c, set_area_to_bounds, mask_2_strength)
461
+ for t in positive_3:
462
+ append_helper(t, mask_3, c, set_area_to_bounds, mask_3_strength)
463
+ for t in positive_4:
464
+ append_helper(t, mask_4, c, set_area_to_bounds, mask_4_strength)
465
+ for t in negative_1:
466
+ append_helper(t, mask_1, c2, set_area_to_bounds, mask_1_strength)
467
+ for t in negative_2:
468
+ append_helper(t, mask_2, c2, set_area_to_bounds, mask_2_strength)
469
+ for t in negative_3:
470
+ append_helper(t, mask_3, c2, set_area_to_bounds, mask_3_strength)
471
+ for t in negative_4:
472
+ append_helper(t, mask_4, c2, set_area_to_bounds, mask_4_strength)
473
+ return (c, c2)
474
+
475
+ class ConditioningSetMaskAndCombine5:
476
+ @classmethod
477
+ def INPUT_TYPES(cls):
478
+ return {
479
+ "required": {
480
+ "positive_1": ("CONDITIONING", ),
481
+ "negative_1": ("CONDITIONING", ),
482
+ "positive_2": ("CONDITIONING", ),
483
+ "negative_2": ("CONDITIONING", ),
484
+ "positive_3": ("CONDITIONING", ),
485
+ "negative_3": ("CONDITIONING", ),
486
+ "positive_4": ("CONDITIONING", ),
487
+ "negative_4": ("CONDITIONING", ),
488
+ "positive_5": ("CONDITIONING", ),
489
+ "negative_5": ("CONDITIONING", ),
490
+ "mask_1": ("MASK", ),
491
+ "mask_2": ("MASK", ),
492
+ "mask_3": ("MASK", ),
493
+ "mask_4": ("MASK", ),
494
+ "mask_5": ("MASK", ),
495
+ "mask_1_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
496
+ "mask_2_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
497
+ "mask_3_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
498
+ "mask_4_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
499
+ "mask_5_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
500
+ "set_cond_area": (["default", "mask bounds"],),
501
+ }
502
+ }
503
+
504
+ RETURN_TYPES = ("CONDITIONING","CONDITIONING",)
505
+ RETURN_NAMES = ("combined_positive", "combined_negative",)
506
+ FUNCTION = "append"
507
+ CATEGORY = "KJNodes/masking/conditioning"
508
+ DESCRIPTION = """
509
+ Bundles multiple conditioning mask and combine nodes into one,functionality is identical to ComfyUI native nodes
510
+ """
511
+
512
+ def append(self, positive_1, negative_1, positive_2, positive_3, positive_4, positive_5, negative_2, negative_3, negative_4, negative_5, mask_1, mask_2, mask_3, mask_4, mask_5, set_cond_area, mask_1_strength, mask_2_strength, mask_3_strength, mask_4_strength, mask_5_strength):
513
+ c = []
514
+ c2 = []
515
+ set_area_to_bounds = False
516
+ if set_cond_area != "default":
517
+ set_area_to_bounds = True
518
+ if len(mask_1.shape) < 3:
519
+ mask_1 = mask_1.unsqueeze(0)
520
+ if len(mask_2.shape) < 3:
521
+ mask_2 = mask_2.unsqueeze(0)
522
+ if len(mask_3.shape) < 3:
523
+ mask_3 = mask_3.unsqueeze(0)
524
+ if len(mask_4.shape) < 3:
525
+ mask_4 = mask_4.unsqueeze(0)
526
+ if len(mask_5.shape) < 3:
527
+ mask_5 = mask_5.unsqueeze(0)
528
+ for t in positive_1:
529
+ append_helper(t, mask_1, c, set_area_to_bounds, mask_1_strength)
530
+ for t in positive_2:
531
+ append_helper(t, mask_2, c, set_area_to_bounds, mask_2_strength)
532
+ for t in positive_3:
533
+ append_helper(t, mask_3, c, set_area_to_bounds, mask_3_strength)
534
+ for t in positive_4:
535
+ append_helper(t, mask_4, c, set_area_to_bounds, mask_4_strength)
536
+ for t in positive_5:
537
+ append_helper(t, mask_5, c, set_area_to_bounds, mask_5_strength)
538
+ for t in negative_1:
539
+ append_helper(t, mask_1, c2, set_area_to_bounds, mask_1_strength)
540
+ for t in negative_2:
541
+ append_helper(t, mask_2, c2, set_area_to_bounds, mask_2_strength)
542
+ for t in negative_3:
543
+ append_helper(t, mask_3, c2, set_area_to_bounds, mask_3_strength)
544
+ for t in negative_4:
545
+ append_helper(t, mask_4, c2, set_area_to_bounds, mask_4_strength)
546
+ for t in negative_5:
547
+ append_helper(t, mask_5, c2, set_area_to_bounds, mask_5_strength)
548
+ return (c, c2)
549
+
550
+ class VRAM_Debug:
551
+
552
+ @classmethod
553
+
554
+ def INPUT_TYPES(s):
555
+ return {
556
+ "required": {
557
+
558
+ "empty_cache": ("BOOLEAN", {"default": True}),
559
+ "gc_collect": ("BOOLEAN", {"default": True}),
560
+ "unload_all_models": ("BOOLEAN", {"default": False}),
561
+ },
562
+ "optional": {
563
+ "any_input": (any, {}),
564
+ "image_pass": ("IMAGE",),
565
+ "model_pass": ("MODEL",),
566
+ }
567
+ }
568
+
569
+ RETURN_TYPES = (any, "IMAGE","MODEL","INT", "INT",)
570
+ RETURN_NAMES = ("any_output", "image_pass", "model_pass", "freemem_before", "freemem_after")
571
+ FUNCTION = "VRAMdebug"
572
+ CATEGORY = "KJNodes/misc"
573
+ DESCRIPTION = """
574
+ Returns the inputs unchanged, they are only used as triggers,
575
+ and performs comfy model management functions and garbage collection,
576
+ reports free VRAM before and after the operations.
577
+ """
578
+
579
+ def VRAMdebug(self, gc_collect, empty_cache, unload_all_models, image_pass=None, model_pass=None, any_input=None):
580
+ freemem_before = model_management.get_free_memory()
581
+ print("VRAMdebug: free memory before: ", f"{freemem_before:,.0f}")
582
+ if empty_cache:
583
+ model_management.soft_empty_cache()
584
+ if unload_all_models:
585
+ model_management.unload_all_models()
586
+ if gc_collect:
587
+ import gc
588
+ gc.collect()
589
+ freemem_after = model_management.get_free_memory()
590
+ print("VRAMdebug: free memory after: ", f"{freemem_after:,.0f}")
591
+ print("VRAMdebug: freed memory: ", f"{freemem_after - freemem_before:,.0f}")
592
+ return {"ui": {
593
+ "text": [f"{freemem_before:,.0f}x{freemem_after:,.0f}"]},
594
+ "result": (any_input, image_pass, model_pass, freemem_before, freemem_after)
595
+ }
596
+
597
+ class SomethingToString:
598
+ @classmethod
599
+
600
+ def INPUT_TYPES(s):
601
+ return {
602
+ "required": {
603
+ "input": (any, {}),
604
+ },
605
+ "optional": {
606
+ "prefix": ("STRING", {"default": ""}),
607
+ "suffix": ("STRING", {"default": ""}),
608
+ }
609
+ }
610
+ RETURN_TYPES = ("STRING",)
611
+ FUNCTION = "stringify"
612
+ CATEGORY = "KJNodes/text"
613
+ DESCRIPTION = """
614
+ Converts any type to a string.
615
+ """
616
+
617
+ def stringify(self, input, prefix="", suffix=""):
618
+ if isinstance(input, (int, float, bool)):
619
+ stringified = str(input)
620
+ elif isinstance(input, list):
621
+ stringified = ', '.join(str(item) for item in input)
622
+ else:
623
+ return
624
+ if prefix: # Check if prefix is not empty
625
+ stringified = prefix + stringified # Add the prefix
626
+ if suffix: # Check if suffix is not empty
627
+ stringified = stringified + suffix # Add the suffix
628
+
629
+ return (stringified,)
630
+
631
+ class Sleep:
632
+ @classmethod
633
+ def INPUT_TYPES(s):
634
+ return {
635
+ "required": {
636
+ "input": (any, {}),
637
+ "minutes": ("INT", {"default": 0, "min": 0, "max": 1439}),
638
+ "seconds": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 59.99, "step": 0.01}),
639
+ },
640
+ }
641
+ RETURN_TYPES = (any,)
642
+ FUNCTION = "sleepdelay"
643
+ CATEGORY = "KJNodes/misc"
644
+ DESCRIPTION = """
645
+ Delays the execution for the input amount of time.
646
+ """
647
+
648
+ def sleepdelay(self, input, minutes, seconds):
649
+ total_seconds = minutes * 60 + seconds
650
+ time.sleep(total_seconds)
651
+ return input,
652
+
653
+ class EmptyLatentImagePresets:
654
+ @classmethod
655
+ def INPUT_TYPES(cls):
656
+ return {
657
+ "required": {
658
+ "dimensions": (
659
+ [ '512 x 512',
660
+ '768 x 512',
661
+ '960 x 512',
662
+ '1024 x 512',
663
+ '1536 x 640',
664
+ '1344 x 768',
665
+ '1216 x 832',
666
+ '1152 x 896',
667
+ '1024 x 1024',
668
+ ],
669
+ {
670
+ "default": '512 x 512'
671
+ }),
672
+
673
+ "invert": ("BOOLEAN", {"default": False}),
674
+ "batch_size": ("INT", {
675
+ "default": 1,
676
+ "min": 1,
677
+ "max": 4096
678
+ }),
679
+ },
680
+ }
681
+
682
+ RETURN_TYPES = ("LATENT", "INT", "INT")
683
+ RETURN_NAMES = ("Latent", "Width", "Height")
684
+ FUNCTION = "generate"
685
+ CATEGORY = "KJNodes"
686
+
687
+ def generate(self, dimensions, invert, batch_size):
688
+ from nodes import EmptyLatentImage
689
+ result = [x.strip() for x in dimensions.split('x')]
690
+
691
+ if invert:
692
+ width = int(result[1].split(' ')[0])
693
+ height = int(result[0])
694
+ else:
695
+ width = int(result[0])
696
+ height = int(result[1].split(' ')[0])
697
+ latent = EmptyLatentImage().generate(width, height, batch_size)[0]
698
+
699
+ return (latent, int(width), int(height),)
700
+
701
+
702
+
703
+ class WidgetToString:
704
+ @classmethod
705
+ def IS_CHANGED(cls, **kwargs):
706
+ return float("NaN")
707
+
708
+ @classmethod
709
+ def INPUT_TYPES(cls):
710
+ return {
711
+ "required": {
712
+ "id": ("INT", {"default": 0}),
713
+ "widget_name": ("STRING", {"multiline": False}),
714
+ "return_all": ("BOOLEAN", {"default": False}),
715
+ },
716
+ "optional": {
717
+ "any_input": (any, {}),
718
+ "node_title": ("STRING", {"multiline": False}),
719
+ },
720
+ "hidden": {"extra_pnginfo": "EXTRA_PNGINFO",
721
+ "prompt": "PROMPT",
722
+ "unique_id": "UNIQUE_ID",},
723
+ }
724
+
725
+ RETURN_TYPES = ("STRING", )
726
+ FUNCTION = "get_widget_value"
727
+ CATEGORY = "KJNodes/text"
728
+ DESCRIPTION = """
729
+ Selects a node and it's specified widget and outputs the value as a string.
730
+ If no node id or title is provided it will use the 'any_input' link and use that node.
731
+ To see node id's, enable node id display from Manager badge menu.
732
+ Alternatively you can search with the node title. Node titles ONLY exist if they
733
+ are manually edited!
734
+ The 'any_input' is required for making sure the node you want the value from exists in the workflow.
735
+ """
736
+
737
+ def get_widget_value(self, id, widget_name, extra_pnginfo, prompt, unique_id, return_all=False, any_input=None, node_title=""):
738
+ workflow = extra_pnginfo["workflow"]
739
+ #print(json.dumps(workflow, indent=4))
740
+ results = []
741
+ node_id = None # Initialize node_id to handle cases where no match is found
742
+ link_id = None
743
+ link_to_node_map = {}
744
+
745
+ for node in workflow["nodes"]:
746
+ if node_title:
747
+ if "title" in node:
748
+ if node["title"] == node_title:
749
+ node_id = node["id"]
750
+ break
751
+ else:
752
+ print("Node title not found.")
753
+ elif id != 0:
754
+ if node["id"] == id:
755
+ node_id = id
756
+ break
757
+ elif any_input is not None:
758
+ if node["type"] == "WidgetToString" and node["id"] == int(unique_id) and not link_id:
759
+ for node_input in node["inputs"]:
760
+ link_id = node_input["link"]
761
+
762
+ # Construct a map of links to node IDs for future reference
763
+ node_outputs = node.get("outputs", None)
764
+ if not node_outputs:
765
+ continue
766
+ for output in node_outputs:
767
+ node_links = output.get("links", None)
768
+ if not node_links:
769
+ continue
770
+ for link in node_links:
771
+ link_to_node_map[link] = node["id"]
772
+ if link_id and link == link_id:
773
+ break
774
+
775
+ if link_id:
776
+ node_id = link_to_node_map.get(link_id, None)
777
+
778
+ if node_id is None:
779
+ raise ValueError("No matching node found for the given title or id")
780
+
781
+ values = prompt[str(node_id)]
782
+ if "inputs" in values:
783
+ if return_all:
784
+ results.append(', '.join(f'{k}: {str(v)}' for k, v in values["inputs"].items()))
785
+ elif widget_name in values["inputs"]:
786
+ v = str(values["inputs"][widget_name]) # Convert to string here
787
+ return (v, )
788
+ else:
789
+ raise NameError(f"Widget not found: {node_id}.{widget_name}")
790
+ if not results:
791
+ raise NameError(f"Node not found: {node_id}")
792
+ return (', '.join(results).strip(', '), )
793
+
794
+ class DummyOut:
795
+
796
+ @classmethod
797
+ def INPUT_TYPES(cls):
798
+ return {
799
+ "required": {
800
+ "any_input": (any, {}),
801
+ }
802
+ }
803
+
804
+ RETURN_TYPES = (any,)
805
+ FUNCTION = "dummy"
806
+ CATEGORY = "KJNodes/misc"
807
+ OUTPUT_NODE = True
808
+ DESCRIPTION = """
809
+ Does nothing, used to trigger generic workflow output.
810
+ A way to get previews in the UI without saving anything to disk.
811
+ """
812
+
813
+ def dummy(self, any_input):
814
+ return (any_input,)
815
+
816
+ class FlipSigmasAdjusted:
817
+ @classmethod
818
+ def INPUT_TYPES(s):
819
+ return {"required":
820
+ {"sigmas": ("SIGMAS", ),
821
+ "divide_by_last_sigma": ("BOOLEAN", {"default": False}),
822
+ "divide_by": ("FLOAT", {"default": 1,"min": 1, "max": 255, "step": 0.01}),
823
+ "offset_by": ("INT", {"default": 1,"min": -100, "max": 100, "step": 1}),
824
+ }
825
+ }
826
+ RETURN_TYPES = ("SIGMAS", "STRING",)
827
+ RETURN_NAMES = ("SIGMAS", "sigmas_string",)
828
+ CATEGORY = "KJNodes/noise"
829
+ FUNCTION = "get_sigmas_adjusted"
830
+
831
+ def get_sigmas_adjusted(self, sigmas, divide_by_last_sigma, divide_by, offset_by):
832
+
833
+ sigmas = sigmas.flip(0)
834
+ if sigmas[0] == 0:
835
+ sigmas[0] = 0.0001
836
+ adjusted_sigmas = sigmas.clone()
837
+ #offset sigma
838
+ for i in range(1, len(sigmas)):
839
+ offset_index = i - offset_by
840
+ if 0 <= offset_index < len(sigmas):
841
+ adjusted_sigmas[i] = sigmas[offset_index]
842
+ else:
843
+ adjusted_sigmas[i] = 0.0001
844
+ if adjusted_sigmas[0] == 0:
845
+ adjusted_sigmas[0] = 0.0001
846
+ if divide_by_last_sigma:
847
+ adjusted_sigmas = adjusted_sigmas / adjusted_sigmas[-1]
848
+
849
+ sigma_np_array = adjusted_sigmas.numpy()
850
+ array_string = np.array2string(sigma_np_array, precision=2, separator=', ', threshold=np.inf)
851
+ adjusted_sigmas = adjusted_sigmas / divide_by
852
+ return (adjusted_sigmas, array_string,)
853
+
854
+ class CustomSigmas:
855
+ @classmethod
856
+ def INPUT_TYPES(s):
857
+ return {"required":
858
+ {
859
+ "sigmas_string" :("STRING", {"default": "14.615, 6.475, 3.861, 2.697, 1.886, 1.396, 0.963, 0.652, 0.399, 0.152, 0.029","multiline": True}),
860
+ "interpolate_to_steps": ("INT", {"default": 10,"min": 0, "max": 255, "step": 1}),
861
+ }
862
+ }
863
+ RETURN_TYPES = ("SIGMAS",)
864
+ RETURN_NAMES = ("SIGMAS",)
865
+ CATEGORY = "KJNodes/noise"
866
+ FUNCTION = "customsigmas"
867
+ DESCRIPTION = """
868
+ Creates a sigmas tensor from a string of comma separated values.
869
+ Examples:
870
+
871
+ Nvidia's optimized AYS 10 step schedule for SD 1.5:
872
+ 14.615, 6.475, 3.861, 2.697, 1.886, 1.396, 0.963, 0.652, 0.399, 0.152, 0.029
873
+ SDXL:
874
+ 14.615, 6.315, 3.771, 2.181, 1.342, 0.862, 0.555, 0.380, 0.234, 0.113, 0.029
875
+ SVD:
876
+ 700.00, 54.5, 15.886, 7.977, 4.248, 1.789, 0.981, 0.403, 0.173, 0.034, 0.002
877
+ """
878
+ def customsigmas(self, sigmas_string, interpolate_to_steps):
879
+ sigmas_list = sigmas_string.split(', ')
880
+ sigmas_float_list = [float(sigma) for sigma in sigmas_list]
881
+ sigmas_tensor = torch.FloatTensor(sigmas_float_list)
882
+ if len(sigmas_tensor) != interpolate_to_steps + 1:
883
+ sigmas_tensor = self.loglinear_interp(sigmas_tensor, interpolate_to_steps + 1)
884
+ sigmas_tensor[-1] = 0
885
+ return (sigmas_tensor.float(),)
886
+
887
+ def loglinear_interp(self, t_steps, num_steps):
888
+ """
889
+ Performs log-linear interpolation of a given array of decreasing numbers.
890
+ """
891
+ t_steps_np = t_steps.numpy()
892
+
893
+ xs = np.linspace(0, 1, len(t_steps_np))
894
+ ys = np.log(t_steps_np[::-1])
895
+
896
+ new_xs = np.linspace(0, 1, num_steps)
897
+ new_ys = np.interp(new_xs, xs, ys)
898
+
899
+ interped_ys = np.exp(new_ys)[::-1].copy()
900
+ interped_ys_tensor = torch.tensor(interped_ys)
901
+ return interped_ys_tensor
902
+
903
+
904
+ class InjectNoiseToLatent:
905
+ @classmethod
906
+ def INPUT_TYPES(s):
907
+ return {"required": {
908
+ "latents":("LATENT",),
909
+ "strength": ("FLOAT", {"default": 0.1, "min": 0.0, "max": 200.0, "step": 0.0001}),
910
+ "noise": ("LATENT",),
911
+ "normalize": ("BOOLEAN", {"default": False}),
912
+ "average": ("BOOLEAN", {"default": False}),
913
+ },
914
+ "optional":{
915
+ "mask": ("MASK", ),
916
+ "mix_randn_amount": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1000.0, "step": 0.001}),
917
+ "seed": ("INT", {"default": 123,"min": 0, "max": 0xffffffffffffffff, "step": 1}),
918
+ }
919
+ }
920
+
921
+ RETURN_TYPES = ("LATENT",)
922
+ FUNCTION = "injectnoise"
923
+ CATEGORY = "KJNodes/noise"
924
+
925
+ def injectnoise(self, latents, strength, noise, normalize, average, mix_randn_amount=0, seed=None, mask=None):
926
+ samples = latents.copy()
927
+ if latents["samples"].shape != noise["samples"].shape:
928
+ raise ValueError("InjectNoiseToLatent: Latent and noise must have the same shape")
929
+ if average:
930
+ noised = (samples["samples"].clone() + noise["samples"].clone()) / 2
931
+ else:
932
+ noised = samples["samples"].clone() + noise["samples"].clone() * strength
933
+ if normalize:
934
+ noised = noised / noised.std()
935
+ if mask is not None:
936
+ mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(noised.shape[2], noised.shape[3]), mode="bilinear")
937
+ mask = mask.expand((-1,noised.shape[1],-1,-1))
938
+ if mask.shape[0] < noised.shape[0]:
939
+ mask = mask.repeat((noised.shape[0] -1) // mask.shape[0] + 1, 1, 1, 1)[:noised.shape[0]]
940
+ noised = mask * noised + (1-mask) * latents["samples"]
941
+ if mix_randn_amount > 0:
942
+ if seed is not None:
943
+ generator = torch.manual_seed(seed)
944
+ rand_noise = torch.randn(noised.size(), dtype=noised.dtype, layout=noised.layout, generator=generator, device="cpu")
945
+ noised = noised + (mix_randn_amount * rand_noise)
946
+ samples["samples"] = noised
947
+ return (samples,)
948
+
949
+ class SoundReactive:
950
+ @classmethod
951
+ def INPUT_TYPES(s):
952
+ return {"required": {
953
+ "sound_level": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 99999, "step": 0.01}),
954
+ "start_range_hz": ("INT", {"default": 150, "min": 0, "max": 9999, "step": 1}),
955
+ "end_range_hz": ("INT", {"default": 2000, "min": 0, "max": 9999, "step": 1}),
956
+ "multiplier": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 99999, "step": 0.01}),
957
+ "smoothing_factor": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
958
+ "normalize": ("BOOLEAN", {"default": False}),
959
+ },
960
+ }
961
+
962
+ RETURN_TYPES = ("FLOAT","INT",)
963
+ RETURN_NAMES =("sound_level", "sound_level_int",)
964
+ FUNCTION = "react"
965
+ CATEGORY = "KJNodes/audio"
966
+ DESCRIPTION = """
967
+ Reacts to the sound level of the input.
968
+ Uses your browsers sound input options and requires.
969
+ Meant to be used with realtime diffusion with autoqueue.
970
+ """
971
+
972
+ def react(self, sound_level, start_range_hz, end_range_hz, smoothing_factor, multiplier, normalize):
973
+
974
+ sound_level *= multiplier
975
+
976
+ if normalize:
977
+ sound_level /= 255
978
+
979
+ sound_level_int = int(sound_level)
980
+ return (sound_level, sound_level_int, )
981
+
982
+ class GenerateNoise:
983
+ @classmethod
984
+ def INPUT_TYPES(s):
985
+ return {"required": {
986
+ "width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
987
+ "height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
988
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}),
989
+ "seed": ("INT", {"default": 123,"min": 0, "max": 0xffffffffffffffff, "step": 1}),
990
+ "multiplier": ("FLOAT", {"default": 1.0,"min": 0.0, "max": 4096, "step": 0.01}),
991
+ "constant_batch_noise": ("BOOLEAN", {"default": False}),
992
+ "normalize": ("BOOLEAN", {"default": False}),
993
+ },
994
+ "optional": {
995
+ "model": ("MODEL", ),
996
+ "sigmas": ("SIGMAS", ),
997
+ "latent_channels": (
998
+ [ '4',
999
+ '16',
1000
+ ],
1001
+ ),
1002
+ }
1003
+ }
1004
+
1005
+ RETURN_TYPES = ("LATENT",)
1006
+ FUNCTION = "generatenoise"
1007
+ CATEGORY = "KJNodes/noise"
1008
+ DESCRIPTION = """
1009
+ Generates noise for injection or to be used as empty latents on samplers with add_noise off.
1010
+ """
1011
+
1012
+ def generatenoise(self, batch_size, width, height, seed, multiplier, constant_batch_noise, normalize, sigmas=None, model=None, latent_channels=4):
1013
+
1014
+ generator = torch.manual_seed(seed)
1015
+ noise = torch.randn([batch_size, int(latent_channels), height // 8, width // 8], dtype=torch.float32, layout=torch.strided, generator=generator, device="cpu")
1016
+ if sigmas is not None:
1017
+ sigma = sigmas[0] - sigmas[-1]
1018
+ sigma /= model.model.latent_format.scale_factor
1019
+ noise *= sigma
1020
+
1021
+ noise *=multiplier
1022
+
1023
+ if normalize:
1024
+ noise = noise / noise.std()
1025
+ if constant_batch_noise:
1026
+ noise = noise[0].repeat(batch_size, 1, 1, 1)
1027
+
1028
+
1029
+ return ({"samples":noise}, )
1030
+
1031
+ def camera_embeddings(elevation, azimuth):
1032
+ elevation = torch.as_tensor([elevation])
1033
+ azimuth = torch.as_tensor([azimuth])
1034
+ embeddings = torch.stack(
1035
+ [
1036
+ torch.deg2rad(
1037
+ (90 - elevation) - (90)
1038
+ ), # Zero123 polar is 90-elevation
1039
+ torch.sin(torch.deg2rad(azimuth)),
1040
+ torch.cos(torch.deg2rad(azimuth)),
1041
+ torch.deg2rad(
1042
+ 90 - torch.full_like(elevation, 0)
1043
+ ),
1044
+ ], dim=-1).unsqueeze(1)
1045
+
1046
+ return embeddings
1047
+
1048
+ def interpolate_angle(start, end, fraction):
1049
+ # Calculate the difference in angles and adjust for wraparound if necessary
1050
+ diff = (end - start + 540) % 360 - 180
1051
+ # Apply fraction to the difference
1052
+ interpolated = start + fraction * diff
1053
+ # Normalize the result to be within the range of -180 to 180
1054
+ return (interpolated + 180) % 360 - 180
1055
+
1056
+
1057
+ class StableZero123_BatchSchedule:
1058
+ @classmethod
1059
+ def INPUT_TYPES(s):
1060
+ return {"required": { "clip_vision": ("CLIP_VISION",),
1061
+ "init_image": ("IMAGE",),
1062
+ "vae": ("VAE",),
1063
+ "width": ("INT", {"default": 256, "min": 16, "max": MAX_RESOLUTION, "step": 8}),
1064
+ "height": ("INT", {"default": 256, "min": 16, "max": MAX_RESOLUTION, "step": 8}),
1065
+ "batch_size": ("INT", {"default": 1, "min": 1, "max": 4096}),
1066
+ "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out"],),
1067
+ "azimuth_points_string": ("STRING", {"default": "0:(0.0),\n7:(1.0),\n15:(0.0)\n", "multiline": True}),
1068
+ "elevation_points_string": ("STRING", {"default": "0:(0.0),\n7:(0.0),\n15:(0.0)\n", "multiline": True}),
1069
+ }}
1070
+
1071
+ RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "LATENT")
1072
+ RETURN_NAMES = ("positive", "negative", "latent")
1073
+ FUNCTION = "encode"
1074
+ CATEGORY = "KJNodes/experimental"
1075
+
1076
+ def encode(self, clip_vision, init_image, vae, width, height, batch_size, azimuth_points_string, elevation_points_string, interpolation):
1077
+ output = clip_vision.encode_image(init_image)
1078
+ pooled = output.image_embeds.unsqueeze(0)
1079
+ pixels = common_upscale(init_image.movedim(-1,1), width, height, "bilinear", "center").movedim(1,-1)
1080
+ encode_pixels = pixels[:,:,:,:3]
1081
+ t = vae.encode(encode_pixels)
1082
+
1083
+ def ease_in(t):
1084
+ return t * t
1085
+ def ease_out(t):
1086
+ return 1 - (1 - t) * (1 - t)
1087
+ def ease_in_out(t):
1088
+ return 3 * t * t - 2 * t * t * t
1089
+
1090
+ # Parse the azimuth input string into a list of tuples
1091
+ azimuth_points = []
1092
+ azimuth_points_string = azimuth_points_string.rstrip(',\n')
1093
+ for point_str in azimuth_points_string.split(','):
1094
+ frame_str, azimuth_str = point_str.split(':')
1095
+ frame = int(frame_str.strip())
1096
+ azimuth = float(azimuth_str.strip()[1:-1])
1097
+ azimuth_points.append((frame, azimuth))
1098
+ # Sort the points by frame number
1099
+ azimuth_points.sort(key=lambda x: x[0])
1100
+
1101
+ # Parse the elevation input string into a list of tuples
1102
+ elevation_points = []
1103
+ elevation_points_string = elevation_points_string.rstrip(',\n')
1104
+ for point_str in elevation_points_string.split(','):
1105
+ frame_str, elevation_str = point_str.split(':')
1106
+ frame = int(frame_str.strip())
1107
+ elevation_val = float(elevation_str.strip()[1:-1])
1108
+ elevation_points.append((frame, elevation_val))
1109
+ # Sort the points by frame number
1110
+ elevation_points.sort(key=lambda x: x[0])
1111
+
1112
+ # Index of the next point to interpolate towards
1113
+ next_point = 1
1114
+ next_elevation_point = 1
1115
+
1116
+ positive_cond_out = []
1117
+ positive_pooled_out = []
1118
+ negative_cond_out = []
1119
+ negative_pooled_out = []
1120
+
1121
+ #azimuth interpolation
1122
+ for i in range(batch_size):
1123
+ # Find the interpolated azimuth for the current frame
1124
+ while next_point < len(azimuth_points) and i >= azimuth_points[next_point][0]:
1125
+ next_point += 1
1126
+ # If next_point is equal to the length of points, we've gone past the last point
1127
+ if next_point == len(azimuth_points):
1128
+ next_point -= 1 # Set next_point to the last index of points
1129
+ prev_point = max(next_point - 1, 0) # Ensure prev_point is not less than 0
1130
+
1131
+ # Calculate fraction
1132
+ if azimuth_points[next_point][0] != azimuth_points[prev_point][0]: # Prevent division by zero
1133
+ fraction = (i - azimuth_points[prev_point][0]) / (azimuth_points[next_point][0] - azimuth_points[prev_point][0])
1134
+ if interpolation == "ease_in":
1135
+ fraction = ease_in(fraction)
1136
+ elif interpolation == "ease_out":
1137
+ fraction = ease_out(fraction)
1138
+ elif interpolation == "ease_in_out":
1139
+ fraction = ease_in_out(fraction)
1140
+
1141
+ # Use the new interpolate_angle function
1142
+ interpolated_azimuth = interpolate_angle(azimuth_points[prev_point][1], azimuth_points[next_point][1], fraction)
1143
+ else:
1144
+ interpolated_azimuth = azimuth_points[prev_point][1]
1145
+ # Interpolate the elevation
1146
+ next_elevation_point = 1
1147
+ while next_elevation_point < len(elevation_points) and i >= elevation_points[next_elevation_point][0]:
1148
+ next_elevation_point += 1
1149
+ if next_elevation_point == len(elevation_points):
1150
+ next_elevation_point -= 1
1151
+ prev_elevation_point = max(next_elevation_point - 1, 0)
1152
+
1153
+ if elevation_points[next_elevation_point][0] != elevation_points[prev_elevation_point][0]:
1154
+ fraction = (i - elevation_points[prev_elevation_point][0]) / (elevation_points[next_elevation_point][0] - elevation_points[prev_elevation_point][0])
1155
+ if interpolation == "ease_in":
1156
+ fraction = ease_in(fraction)
1157
+ elif interpolation == "ease_out":
1158
+ fraction = ease_out(fraction)
1159
+ elif interpolation == "ease_in_out":
1160
+ fraction = ease_in_out(fraction)
1161
+
1162
+ interpolated_elevation = interpolate_angle(elevation_points[prev_elevation_point][1], elevation_points[next_elevation_point][1], fraction)
1163
+ else:
1164
+ interpolated_elevation = elevation_points[prev_elevation_point][1]
1165
+
1166
+ cam_embeds = camera_embeddings(interpolated_elevation, interpolated_azimuth)
1167
+ cond = torch.cat([pooled, cam_embeds.repeat((pooled.shape[0], 1, 1))], dim=-1)
1168
+
1169
+ positive_pooled_out.append(t)
1170
+ positive_cond_out.append(cond)
1171
+ negative_pooled_out.append(torch.zeros_like(t))
1172
+ negative_cond_out.append(torch.zeros_like(pooled))
1173
+
1174
+ # Concatenate the conditions and pooled outputs
1175
+ final_positive_cond = torch.cat(positive_cond_out, dim=0)
1176
+ final_positive_pooled = torch.cat(positive_pooled_out, dim=0)
1177
+ final_negative_cond = torch.cat(negative_cond_out, dim=0)
1178
+ final_negative_pooled = torch.cat(negative_pooled_out, dim=0)
1179
+
1180
+ # Structure the final output
1181
+ final_positive = [[final_positive_cond, {"concat_latent_image": final_positive_pooled}]]
1182
+ final_negative = [[final_negative_cond, {"concat_latent_image": final_negative_pooled}]]
1183
+
1184
+ latent = torch.zeros([batch_size, 4, height // 8, width // 8])
1185
+ return (final_positive, final_negative, {"samples": latent})
1186
+
1187
+ def linear_interpolate(start, end, fraction):
1188
+ return start + (end - start) * fraction
1189
+
1190
+ class SV3D_BatchSchedule:
1191
+ @classmethod
1192
+ def INPUT_TYPES(s):
1193
+ return {"required": { "clip_vision": ("CLIP_VISION",),
1194
+ "init_image": ("IMAGE",),
1195
+ "vae": ("VAE",),
1196
+ "width": ("INT", {"default": 576, "min": 16, "max": MAX_RESOLUTION, "step": 8}),
1197
+ "height": ("INT", {"default": 576, "min": 16, "max": MAX_RESOLUTION, "step": 8}),
1198
+ "batch_size": ("INT", {"default": 21, "min": 1, "max": 4096}),
1199
+ "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out"],),
1200
+ "azimuth_points_string": ("STRING", {"default": "0:(0.0),\n9:(180.0),\n20:(360.0)\n", "multiline": True}),
1201
+ "elevation_points_string": ("STRING", {"default": "0:(0.0),\n9:(0.0),\n20:(0.0)\n", "multiline": True}),
1202
+ }}
1203
+
1204
+ RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "LATENT")
1205
+ RETURN_NAMES = ("positive", "negative", "latent")
1206
+ FUNCTION = "encode"
1207
+ CATEGORY = "KJNodes/experimental"
1208
+ DESCRIPTION = """
1209
+ Allow scheduling of the azimuth and elevation conditions for SV3D.
1210
+ Note that SV3D is still a video model and the schedule needs to always go forward
1211
+ https://huggingface.co/stabilityai/sv3d
1212
+ """
1213
+
1214
+ def encode(self, clip_vision, init_image, vae, width, height, batch_size, azimuth_points_string, elevation_points_string, interpolation):
1215
+ output = clip_vision.encode_image(init_image)
1216
+ pooled = output.image_embeds.unsqueeze(0)
1217
+ pixels = common_upscale(init_image.movedim(-1,1), width, height, "bilinear", "center").movedim(1,-1)
1218
+ encode_pixels = pixels[:,:,:,:3]
1219
+ t = vae.encode(encode_pixels)
1220
+
1221
+ def ease_in(t):
1222
+ return t * t
1223
+ def ease_out(t):
1224
+ return 1 - (1 - t) * (1 - t)
1225
+ def ease_in_out(t):
1226
+ return 3 * t * t - 2 * t * t * t
1227
+
1228
+ # Parse the azimuth input string into a list of tuples
1229
+ azimuth_points = []
1230
+ azimuth_points_string = azimuth_points_string.rstrip(',\n')
1231
+ for point_str in azimuth_points_string.split(','):
1232
+ frame_str, azimuth_str = point_str.split(':')
1233
+ frame = int(frame_str.strip())
1234
+ azimuth = float(azimuth_str.strip()[1:-1])
1235
+ azimuth_points.append((frame, azimuth))
1236
+ # Sort the points by frame number
1237
+ azimuth_points.sort(key=lambda x: x[0])
1238
+
1239
+ # Parse the elevation input string into a list of tuples
1240
+ elevation_points = []
1241
+ elevation_points_string = elevation_points_string.rstrip(',\n')
1242
+ for point_str in elevation_points_string.split(','):
1243
+ frame_str, elevation_str = point_str.split(':')
1244
+ frame = int(frame_str.strip())
1245
+ elevation_val = float(elevation_str.strip()[1:-1])
1246
+ elevation_points.append((frame, elevation_val))
1247
+ # Sort the points by frame number
1248
+ elevation_points.sort(key=lambda x: x[0])
1249
+
1250
+ # Index of the next point to interpolate towards
1251
+ next_point = 1
1252
+ next_elevation_point = 1
1253
+ elevations = []
1254
+ azimuths = []
1255
+ # For azimuth interpolation
1256
+ for i in range(batch_size):
1257
+ # Find the interpolated azimuth for the current frame
1258
+ while next_point < len(azimuth_points) and i >= azimuth_points[next_point][0]:
1259
+ next_point += 1
1260
+ if next_point == len(azimuth_points):
1261
+ next_point -= 1
1262
+ prev_point = max(next_point - 1, 0)
1263
+
1264
+ if azimuth_points[next_point][0] != azimuth_points[prev_point][0]:
1265
+ fraction = (i - azimuth_points[prev_point][0]) / (azimuth_points[next_point][0] - azimuth_points[prev_point][0])
1266
+ # Apply the ease function to the fraction
1267
+ if interpolation == "ease_in":
1268
+ fraction = ease_in(fraction)
1269
+ elif interpolation == "ease_out":
1270
+ fraction = ease_out(fraction)
1271
+ elif interpolation == "ease_in_out":
1272
+ fraction = ease_in_out(fraction)
1273
+
1274
+ interpolated_azimuth = linear_interpolate(azimuth_points[prev_point][1], azimuth_points[next_point][1], fraction)
1275
+ else:
1276
+ interpolated_azimuth = azimuth_points[prev_point][1]
1277
+
1278
+ # Interpolate the elevation
1279
+ next_elevation_point = 1
1280
+ while next_elevation_point < len(elevation_points) and i >= elevation_points[next_elevation_point][0]:
1281
+ next_elevation_point += 1
1282
+ if next_elevation_point == len(elevation_points):
1283
+ next_elevation_point -= 1
1284
+ prev_elevation_point = max(next_elevation_point - 1, 0)
1285
+
1286
+ if elevation_points[next_elevation_point][0] != elevation_points[prev_elevation_point][0]:
1287
+ fraction = (i - elevation_points[prev_elevation_point][0]) / (elevation_points[next_elevation_point][0] - elevation_points[prev_elevation_point][0])
1288
+ # Apply the ease function to the fraction
1289
+ if interpolation == "ease_in":
1290
+ fraction = ease_in(fraction)
1291
+ elif interpolation == "ease_out":
1292
+ fraction = ease_out(fraction)
1293
+ elif interpolation == "ease_in_out":
1294
+ fraction = ease_in_out(fraction)
1295
+
1296
+ interpolated_elevation = linear_interpolate(elevation_points[prev_elevation_point][1], elevation_points[next_elevation_point][1], fraction)
1297
+ else:
1298
+ interpolated_elevation = elevation_points[prev_elevation_point][1]
1299
+
1300
+ azimuths.append(interpolated_azimuth)
1301
+ elevations.append(interpolated_elevation)
1302
+
1303
+ #print("azimuths", azimuths)
1304
+ #print("elevations", elevations)
1305
+
1306
+ # Structure the final output
1307
+ final_positive = [[pooled, {"concat_latent_image": t, "elevation": elevations, "azimuth": azimuths}]]
1308
+ final_negative = [[torch.zeros_like(pooled), {"concat_latent_image": torch.zeros_like(t),"elevation": elevations, "azimuth": azimuths}]]
1309
+
1310
+ latent = torch.zeros([batch_size, 4, height // 8, width // 8])
1311
+ return (final_positive, final_negative, {"samples": latent})
1312
+
1313
+ class LoadResAdapterNormalization:
1314
+ @classmethod
1315
+ def INPUT_TYPES(s):
1316
+ return {
1317
+ "required": {
1318
+ "model": ("MODEL",),
1319
+ "resadapter_path": (folder_paths.get_filename_list("checkpoints"), )
1320
+ }
1321
+ }
1322
+
1323
+ RETURN_TYPES = ("MODEL",)
1324
+ FUNCTION = "load_res_adapter"
1325
+ CATEGORY = "KJNodes/experimental"
1326
+
1327
+ def load_res_adapter(self, model, resadapter_path):
1328
+ print("ResAdapter: Checking ResAdapter path")
1329
+ resadapter_full_path = folder_paths.get_full_path("checkpoints", resadapter_path)
1330
+ if not os.path.exists(resadapter_full_path):
1331
+ raise Exception("Invalid model path")
1332
+ else:
1333
+ print("ResAdapter: Loading ResAdapter normalization weights")
1334
+ from comfy.utils import load_torch_file
1335
+ prefix_to_remove = 'diffusion_model.'
1336
+ model_clone = model.clone()
1337
+ norm_state_dict = load_torch_file(resadapter_full_path)
1338
+ new_values = {key[len(prefix_to_remove):]: value for key, value in norm_state_dict.items() if key.startswith(prefix_to_remove)}
1339
+ print("ResAdapter: Attempting to add patches with ResAdapter weights")
1340
+ try:
1341
+ for key in model.model.diffusion_model.state_dict().keys():
1342
+ if key in new_values:
1343
+ original_tensor = model.model.diffusion_model.state_dict()[key]
1344
+ new_tensor = new_values[key].to(model.model.diffusion_model.dtype)
1345
+ if original_tensor.shape == new_tensor.shape:
1346
+ model_clone.add_object_patch(f"diffusion_model.{key}.data", new_tensor)
1347
+ else:
1348
+ print("ResAdapter: No match for key: ",key)
1349
+ except:
1350
+ raise Exception("Could not patch model, this way of patching was added to ComfyUI on March 3rd 2024, is your ComfyUI up to date?")
1351
+ print("ResAdapter: Added resnet normalization patches")
1352
+ return (model_clone, )
1353
+
1354
+ class Superprompt:
1355
+ @classmethod
1356
+ def INPUT_TYPES(s):
1357
+ return {
1358
+ "required": {
1359
+ "instruction_prompt": ("STRING", {"default": 'Expand the following prompt to add more detail', "multiline": True}),
1360
+ "prompt": ("STRING", {"default": '', "multiline": True, "forceInput": True}),
1361
+ "max_new_tokens": ("INT", {"default": 128, "min": 1, "max": 4096, "step": 1}),
1362
+ }
1363
+ }
1364
+
1365
+ RETURN_TYPES = ("STRING",)
1366
+ FUNCTION = "process"
1367
+ CATEGORY = "KJNodes/text"
1368
+ DESCRIPTION = """
1369
+ # SuperPrompt
1370
+ A T5 model fine-tuned on the SuperPrompt dataset for
1371
+ upsampling text prompts to more detailed descriptions.
1372
+ Meant to be used as a pre-generation step for text-to-image
1373
+ models that benefit from more detailed prompts.
1374
+ https://huggingface.co/roborovski/superprompt-v1
1375
+ """
1376
+
1377
+ def process(self, instruction_prompt, prompt, max_new_tokens):
1378
+ device = model_management.get_torch_device()
1379
+ from transformers import T5Tokenizer, T5ForConditionalGeneration
1380
+
1381
+ checkpoint_path = os.path.join(script_directory, "models","superprompt-v1")
1382
+ if not os.path.exists(checkpoint_path):
1383
+ print(f"Downloading model to: {checkpoint_path}")
1384
+ from huggingface_hub import snapshot_download
1385
+ snapshot_download(repo_id="roborovski/superprompt-v1",
1386
+ local_dir=checkpoint_path,
1387
+ local_dir_use_symlinks=False)
1388
+ tokenizer = T5Tokenizer.from_pretrained("google/flan-t5-small", legacy=False)
1389
+
1390
+ model = T5ForConditionalGeneration.from_pretrained(checkpoint_path, device_map=device)
1391
+ model.to(device)
1392
+ input_text = instruction_prompt + ": " + prompt
1393
+
1394
+ input_ids = tokenizer(input_text, return_tensors="pt").input_ids.to(device)
1395
+ outputs = model.generate(input_ids, max_new_tokens=max_new_tokens)
1396
+ out = (tokenizer.decode(outputs[0]))
1397
+ out = out.replace('<pad>', '')
1398
+ out = out.replace('</s>', '')
1399
+
1400
+ return (out, )
1401
+
1402
+
1403
+ class CameraPoseVisualizer:
1404
+
1405
+ @classmethod
1406
+ def INPUT_TYPES(s):
1407
+ return {"required": {
1408
+ "pose_file_path": ("STRING", {"default": '', "multiline": False}),
1409
+ "base_xval": ("FLOAT", {"default": 0.2,"min": 0, "max": 100, "step": 0.01}),
1410
+ "zval": ("FLOAT", {"default": 0.3,"min": 0, "max": 100, "step": 0.01}),
1411
+ "scale": ("FLOAT", {"default": 1.0,"min": 0.01, "max": 10.0, "step": 0.01}),
1412
+ "use_exact_fx": ("BOOLEAN", {"default": False}),
1413
+ "relative_c2w": ("BOOLEAN", {"default": True}),
1414
+ "use_viewer": ("BOOLEAN", {"default": False}),
1415
+ },
1416
+ "optional": {
1417
+ "cameractrl_poses": ("CAMERACTRL_POSES", {"default": None}),
1418
+ }
1419
+ }
1420
+
1421
+ RETURN_TYPES = ("IMAGE",)
1422
+ FUNCTION = "plot"
1423
+ CATEGORY = "KJNodes/misc"
1424
+ DESCRIPTION = """
1425
+ Visualizes the camera poses, from Animatediff-Evolved CameraCtrl Pose
1426
+ or a .txt file with RealEstate camera intrinsics and coordinates, in a 3D plot.
1427
+ """
1428
+
1429
+ def plot(self, pose_file_path, scale, base_xval, zval, use_exact_fx, relative_c2w, use_viewer, cameractrl_poses=None):
1430
+ import matplotlib as mpl
1431
+ import matplotlib.pyplot as plt
1432
+ from torchvision.transforms import ToTensor
1433
+
1434
+ x_min = -2.0 * scale
1435
+ x_max = 2.0 * scale
1436
+ y_min = -2.0 * scale
1437
+ y_max = 2.0 * scale
1438
+ z_min = -2.0 * scale
1439
+ z_max = 2.0 * scale
1440
+ plt.rcParams['text.color'] = '#999999'
1441
+ self.fig = plt.figure(figsize=(18, 7))
1442
+ self.fig.patch.set_facecolor('#353535')
1443
+ self.ax = self.fig.add_subplot(projection='3d')
1444
+ self.ax.set_facecolor('#353535') # Set the background color here
1445
+ self.ax.grid(color='#999999', linestyle='-', linewidth=0.5)
1446
+ self.plotly_data = None # plotly data traces
1447
+ self.ax.set_aspect("auto")
1448
+ self.ax.set_xlim(x_min, x_max)
1449
+ self.ax.set_ylim(y_min, y_max)
1450
+ self.ax.set_zlim(z_min, z_max)
1451
+ self.ax.set_xlabel('x', color='#999999')
1452
+ self.ax.set_ylabel('y', color='#999999')
1453
+ self.ax.set_zlabel('z', color='#999999')
1454
+ for text in self.ax.get_xticklabels() + self.ax.get_yticklabels() + self.ax.get_zticklabels():
1455
+ text.set_color('#999999')
1456
+ print('initialize camera pose visualizer')
1457
+
1458
+ if pose_file_path != "":
1459
+ with open(pose_file_path, 'r') as f:
1460
+ poses = f.readlines()
1461
+ w2cs = [np.asarray([float(p) for p in pose.strip().split(' ')[7:]]).reshape(3, 4) for pose in poses[1:]]
1462
+ fxs = [float(pose.strip().split(' ')[1]) for pose in poses[1:]]
1463
+ #print(poses)
1464
+ elif cameractrl_poses is not None:
1465
+ poses = cameractrl_poses
1466
+ w2cs = [np.array(pose[7:]).reshape(3, 4) for pose in cameractrl_poses]
1467
+ fxs = [pose[1] for pose in cameractrl_poses]
1468
+ else:
1469
+ raise ValueError("Please provide either pose_file_path or cameractrl_poses")
1470
+
1471
+ total_frames = len(w2cs)
1472
+ transform_matrix = np.asarray([[1, 0, 0, 0], [0, 0, 1, 0], [0, -1, 0, 0], [0, 0, 0, 1]]).reshape(4, 4)
1473
+ last_row = np.zeros((1, 4))
1474
+ last_row[0, -1] = 1.0
1475
+
1476
+ w2cs = [np.concatenate((w2c, last_row), axis=0) for w2c in w2cs]
1477
+ c2ws = self.get_c2w(w2cs, transform_matrix, relative_c2w)
1478
+
1479
+ for frame_idx, c2w in enumerate(c2ws):
1480
+ self.extrinsic2pyramid(c2w, frame_idx / total_frames, hw_ratio=1/1, base_xval=base_xval,
1481
+ zval=(fxs[frame_idx] if use_exact_fx else zval))
1482
+
1483
+ # Create the colorbar
1484
+ cmap = mpl.cm.rainbow
1485
+ norm = mpl.colors.Normalize(vmin=0, vmax=total_frames)
1486
+ colorbar = self.fig.colorbar(mpl.cm.ScalarMappable(norm=norm, cmap=cmap), ax=self.ax, orientation='vertical')
1487
+
1488
+ # Change the colorbar label
1489
+ colorbar.set_label('Frame', color='#999999') # Change the label and its color
1490
+
1491
+ # Change the tick colors
1492
+ colorbar.ax.yaxis.set_tick_params(colors='#999999') # Change the tick color
1493
+
1494
+ # Change the tick frequency
1495
+ # Assuming you want to set the ticks at every 10th frame
1496
+ ticks = np.arange(0, total_frames, 10)
1497
+ colorbar.ax.yaxis.set_ticks(ticks)
1498
+
1499
+ plt.title('')
1500
+ plt.draw()
1501
+ buf = io.BytesIO()
1502
+ plt.savefig(buf, format='png', bbox_inches='tight', pad_inches=0)
1503
+ buf.seek(0)
1504
+ img = Image.open(buf)
1505
+ tensor_img = ToTensor()(img)
1506
+ buf.close()
1507
+ tensor_img = tensor_img.permute(1, 2, 0).unsqueeze(0)
1508
+ if use_viewer:
1509
+ time.sleep(1)
1510
+ plt.show()
1511
+ return (tensor_img,)
1512
+
1513
+ def extrinsic2pyramid(self, extrinsic, color_map='red', hw_ratio=1/1, base_xval=1, zval=3):
1514
+ from mpl_toolkits.mplot3d.art3d import Poly3DCollection
1515
+ vertex_std = np.array([[0, 0, 0, 1],
1516
+ [base_xval, -base_xval * hw_ratio, zval, 1],
1517
+ [base_xval, base_xval * hw_ratio, zval, 1],
1518
+ [-base_xval, base_xval * hw_ratio, zval, 1],
1519
+ [-base_xval, -base_xval * hw_ratio, zval, 1]])
1520
+ vertex_transformed = vertex_std @ extrinsic.T
1521
+ meshes = [[vertex_transformed[0, :-1], vertex_transformed[1][:-1], vertex_transformed[2, :-1]],
1522
+ [vertex_transformed[0, :-1], vertex_transformed[2, :-1], vertex_transformed[3, :-1]],
1523
+ [vertex_transformed[0, :-1], vertex_transformed[3, :-1], vertex_transformed[4, :-1]],
1524
+ [vertex_transformed[0, :-1], vertex_transformed[4, :-1], vertex_transformed[1, :-1]],
1525
+ [vertex_transformed[1, :-1], vertex_transformed[2, :-1], vertex_transformed[3, :-1], vertex_transformed[4, :-1]]]
1526
+
1527
+ color = color_map if isinstance(color_map, str) else plt.cm.rainbow(color_map)
1528
+
1529
+ self.ax.add_collection3d(
1530
+ Poly3DCollection(meshes, facecolors=color, linewidths=0.3, edgecolors=color, alpha=0.25))
1531
+
1532
+ def customize_legend(self, list_label):
1533
+ from matplotlib.patches import Patch
1534
+ import matplotlib.pyplot as plt
1535
+ list_handle = []
1536
+ for idx, label in enumerate(list_label):
1537
+ color = plt.cm.rainbow(idx / len(list_label))
1538
+ patch = Patch(color=color, label=label)
1539
+ list_handle.append(patch)
1540
+ plt.legend(loc='right', bbox_to_anchor=(1.8, 0.5), handles=list_handle)
1541
+
1542
+ def get_c2w(self, w2cs, transform_matrix, relative_c2w):
1543
+ if relative_c2w:
1544
+ target_cam_c2w = np.array([
1545
+ [1, 0, 0, 0],
1546
+ [0, 1, 0, 0],
1547
+ [0, 0, 1, 0],
1548
+ [0, 0, 0, 1]
1549
+ ])
1550
+ abs2rel = target_cam_c2w @ w2cs[0]
1551
+ ret_poses = [target_cam_c2w, ] + [abs2rel @ np.linalg.inv(w2c) for w2c in w2cs[1:]]
1552
+ else:
1553
+ ret_poses = [np.linalg.inv(w2c) for w2c in w2cs]
1554
+ ret_poses = [transform_matrix @ x for x in ret_poses]
1555
+ return np.array(ret_poses, dtype=np.float32)
1556
+
1557
+
1558
+
1559
+ class StabilityAPI_SD3:
1560
+
1561
+ @classmethod
1562
+ def INPUT_TYPES(cls):
1563
+ return {
1564
+ "required": {
1565
+ "prompt": ("STRING", {"multiline": True}),
1566
+ "n_prompt": ("STRING", {"multiline": True}),
1567
+ "seed": ("INT", {"default": 123,"min": 0, "max": 4294967294, "step": 1}),
1568
+ "model": (
1569
+ [
1570
+ 'sd3',
1571
+ 'sd3-turbo',
1572
+ ],
1573
+ {
1574
+ "default": 'sd3'
1575
+ }),
1576
+ "aspect_ratio": (
1577
+ [
1578
+ '1:1',
1579
+ '16:9',
1580
+ '21:9',
1581
+ '2:3',
1582
+ '3:2',
1583
+ '4:5',
1584
+ '5:4',
1585
+ '9:16',
1586
+ '9:21',
1587
+ ],
1588
+ {
1589
+ "default": '1:1'
1590
+ }),
1591
+ "output_format": (
1592
+ [
1593
+ 'png',
1594
+ 'jpeg',
1595
+ ],
1596
+ {
1597
+ "default": 'jpeg'
1598
+ }),
1599
+ },
1600
+ "optional": {
1601
+ "api_key": ("STRING", {"multiline": True}),
1602
+ "image": ("IMAGE",),
1603
+ "img2img_strength": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
1604
+ "disable_metadata": ("BOOLEAN", {"default": True}),
1605
+ },
1606
+ }
1607
+
1608
+ RETURN_TYPES = ("IMAGE",)
1609
+ FUNCTION = "apicall"
1610
+
1611
+ CATEGORY = "KJNodes/experimental"
1612
+ DESCRIPTION = """
1613
+ ## Calls StabilityAI API
1614
+
1615
+ Although you may have multiple keys in your account,
1616
+ you should use the same key for all requests to this API.
1617
+
1618
+ Get your API key here: https://platform.stability.ai/account/keys
1619
+ Recommended to set the key in the config.json -file under this
1620
+ node packs folder.
1621
+ # WARNING:
1622
+ Otherwise the API key may get saved in the image metadata even
1623
+ with "disable_metadata" on if the workflow includes save nodes
1624
+ separate from this node.
1625
+
1626
+ sd3 requires 6.5 credits per generation
1627
+ sd3-turbo requires 4 credits per generation
1628
+
1629
+ If no image is provided, mode is set to text-to-image
1630
+
1631
+ """
1632
+
1633
+ def apicall(self, prompt, n_prompt, model, seed, aspect_ratio, output_format,
1634
+ img2img_strength=0.5, image=None, disable_metadata=True, api_key=""):
1635
+ from comfy.cli_args import args
1636
+ if disable_metadata:
1637
+ args.disable_metadata = True
1638
+ else:
1639
+ args.disable_metadata = False
1640
+
1641
+ import requests
1642
+ from torchvision import transforms
1643
+
1644
+ data = {
1645
+ "mode": "text-to-image",
1646
+ "prompt": prompt,
1647
+ "model": model,
1648
+ "seed": seed,
1649
+ "output_format": output_format
1650
+ }
1651
+
1652
+ if image is not None:
1653
+ image = image.permute(0, 3, 1, 2).squeeze(0)
1654
+ to_pil = transforms.ToPILImage()
1655
+ pil_image = to_pil(image)
1656
+ # Save the PIL Image to a BytesIO object
1657
+ buffer = io.BytesIO()
1658
+ pil_image.save(buffer, format='PNG')
1659
+ buffer.seek(0)
1660
+ files = {"image": ("image.png", buffer, "image/png")}
1661
+
1662
+ data["mode"] = "image-to-image"
1663
+ data["image"] = pil_image
1664
+ data["strength"] = img2img_strength
1665
+ else:
1666
+ data["aspect_ratio"] = aspect_ratio,
1667
+ files = {"none": ''}
1668
+
1669
+ if model != "sd3-turbo":
1670
+ data["negative_prompt"] = n_prompt
1671
+
1672
+ headers={
1673
+ "accept": "image/*"
1674
+ }
1675
+
1676
+ if api_key != "":
1677
+ headers["authorization"] = api_key
1678
+ else:
1679
+ config_file_path = os.path.join(script_directory,"config.json")
1680
+ with open(config_file_path, 'r') as file:
1681
+ config = json.load(file)
1682
+ api_key_from_config = config.get("sai_api_key")
1683
+ headers["authorization"] = api_key_from_config
1684
+
1685
+ response = requests.post(
1686
+ f"https://api.stability.ai/v2beta/stable-image/generate/sd3",
1687
+ headers=headers,
1688
+ files = files,
1689
+ data = data,
1690
+ )
1691
+
1692
+ if response.status_code == 200:
1693
+ # Convert the response content to a PIL Image
1694
+ image = Image.open(io.BytesIO(response.content))
1695
+ # Convert the PIL Image to a PyTorch tensor
1696
+ transform = transforms.ToTensor()
1697
+ tensor_image = transform(image)
1698
+ tensor_image = tensor_image.unsqueeze(0)
1699
+ tensor_image = tensor_image.permute(0, 2, 3, 1).cpu().float()
1700
+ return (tensor_image,)
1701
+ else:
1702
+ try:
1703
+ # Attempt to parse the response as JSON
1704
+ error_data = response.json()
1705
+ raise Exception(f"Server error: {error_data}")
1706
+ except json.JSONDecodeError:
1707
+ # If the response is not valid JSON, raise a different exception
1708
+ raise Exception(f"Server error: {response.text}")
1709
+
1710
+ class CheckpointPerturbWeights:
1711
+
1712
+ @classmethod
1713
+ def INPUT_TYPES(s):
1714
+ return {"required": {
1715
+ "model": ("MODEL",),
1716
+ "joint_blocks": ("FLOAT", {"default": 0.02, "min": 0.001, "max": 10.0, "step": 0.001}),
1717
+ "final_layer": ("FLOAT", {"default": 0.02, "min": 0.001, "max": 10.0, "step": 0.001}),
1718
+ "rest_of_the_blocks": ("FLOAT", {"default": 0.02, "min": 0.001, "max": 10.0, "step": 0.001}),
1719
+ "seed": ("INT", {"default": 123,"min": 0, "max": 0xffffffffffffffff, "step": 1}),
1720
+ }
1721
+ }
1722
+ RETURN_TYPES = ("MODEL",)
1723
+ FUNCTION = "mod"
1724
+ OUTPUT_NODE = True
1725
+
1726
+ CATEGORY = "KJNodes/experimental"
1727
+
1728
+ def mod(self, seed, model, joint_blocks, final_layer, rest_of_the_blocks):
1729
+ import copy
1730
+ torch.manual_seed(seed)
1731
+ torch.cuda.manual_seed_all(seed)
1732
+ device = model_management.get_torch_device()
1733
+ model_copy = copy.deepcopy(model)
1734
+ model_copy.model.to(device)
1735
+ keys = model_copy.model.diffusion_model.state_dict().keys()
1736
+
1737
+ dict = {}
1738
+ for key in keys:
1739
+ dict[key] = model_copy.model.diffusion_model.state_dict()[key]
1740
+
1741
+ pbar = ProgressBar(len(keys))
1742
+ for k in keys:
1743
+ v = dict[k]
1744
+ print(f'{k}: {v.std()}')
1745
+ if k.startswith('joint_blocks'):
1746
+ multiplier = joint_blocks
1747
+ elif k.startswith('final_layer'):
1748
+ multiplier = final_layer
1749
+ else:
1750
+ multiplier = rest_of_the_blocks
1751
+ dict[k] += torch.normal(torch.zeros_like(v) * v.mean(), torch.ones_like(v) * v.std() * multiplier).to(device)
1752
+ pbar.update(1)
1753
+ model_copy.model.diffusion_model.load_state_dict(dict)
1754
+ return model_copy,
ComfyUI/custom_nodes/ComfyUI-KJNodes/pyproject.toml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "comfyui-kjnodes"
3
+ description = "Various quality of life -nodes for ComfyUI, mostly just visual stuff to improve usability."
4
+ version = "1.0.1"
5
+ license = {file = "LICENSE"}
6
+ dependencies = ["librosa", "numpy", "pillow>=10.3.0", "scipy", "color-matcher", "matplotlib", "huggingface_hub"]
7
+
8
+ [project.urls]
9
+ Repository = "https://github.com/kijai/ComfyUI-KJNodes"
10
+ # Used by Comfy Registry https://comfyregistry.org
11
+
12
+ [tool.comfy]
13
+ PublisherId = "kijai"
14
+ DisplayName = "ComfyUI-KJNodes"
15
+ Icon = ""
ComfyUI/custom_nodes/ComfyUI-KJNodes/requirements.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ pillow>=10.3.0
2
+ scipy
3
+ color-matcher
4
+ matplotlib
5
+ huggingface_hub
6
+ mss
7
+ opencv-python
ComfyUI/custom_nodes/ComfyUI-KJNodes/utility/__pycache__/utility.cpython-310.pyc ADDED
Binary file (1.97 kB). View file
 
ComfyUI/custom_nodes/ComfyUI-KJNodes/utility/fluid.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy.ndimage import map_coordinates, spline_filter
3
+ from scipy.sparse.linalg import factorized
4
+
5
+ from .numerical import difference, operator
6
+
7
+
8
+ class Fluid:
9
+ def __init__(self, shape, *quantities, pressure_order=1, advect_order=3):
10
+ self.shape = shape
11
+ self.dimensions = len(shape)
12
+
13
+ # Prototyping is simplified by dynamically
14
+ # creating advected quantities as needed.
15
+ self.quantities = quantities
16
+ for q in quantities:
17
+ setattr(self, q, np.zeros(shape))
18
+
19
+ self.indices = np.indices(shape)
20
+ self.velocity = np.zeros((self.dimensions, *shape))
21
+
22
+ laplacian = operator(shape, difference(2, pressure_order))
23
+ self.pressure_solver = factorized(laplacian)
24
+
25
+ self.advect_order = advect_order
26
+
27
+ def step(self):
28
+ # Advection is computed backwards in time as described in Stable Fluids.
29
+ advection_map = self.indices - self.velocity
30
+
31
+ # SciPy's spline filter introduces checkerboard divergence.
32
+ # A linear blend of the filtered and unfiltered fields based
33
+ # on some value epsilon eliminates this error.
34
+ def advect(field, filter_epsilon=10e-2, mode='constant'):
35
+ filtered = spline_filter(field, order=self.advect_order, mode=mode)
36
+ field = filtered * (1 - filter_epsilon) + field * filter_epsilon
37
+ return map_coordinates(field, advection_map, prefilter=False, order=self.advect_order, mode=mode)
38
+
39
+ # Apply advection to each axis of the
40
+ # velocity field and each user-defined quantity.
41
+ for d in range(self.dimensions):
42
+ self.velocity[d] = advect(self.velocity[d])
43
+
44
+ for q in self.quantities:
45
+ setattr(self, q, advect(getattr(self, q)))
46
+
47
+ # Compute the jacobian at each point in the
48
+ # velocity field to extract curl and divergence.
49
+ jacobian_shape = (self.dimensions,) * 2
50
+ partials = tuple(np.gradient(d) for d in self.velocity)
51
+ jacobian = np.stack(partials).reshape(*jacobian_shape, *self.shape)
52
+
53
+ divergence = jacobian.trace()
54
+
55
+ # If this curl calculation is extended to 3D, the y-axis value must be negated.
56
+ # This corresponds to the coefficients of the levi-civita symbol in that dimension.
57
+ # Higher dimensions do not have a vector -> scalar, or vector -> vector,
58
+ # correspondence between velocity and curl due to differing isomorphisms
59
+ # between exterior powers in dimensions != 2 or 3 respectively.
60
+ curl_mask = np.triu(np.ones(jacobian_shape, dtype=bool), k=1)
61
+ curl = (jacobian[curl_mask] - jacobian[curl_mask.T]).squeeze()
62
+
63
+ # Apply the pressure correction to the fluid's velocity field.
64
+ pressure = self.pressure_solver(divergence.flatten()).reshape(self.shape)
65
+ self.velocity -= np.gradient(pressure)
66
+
67
+ return divergence, curl, pressure
ComfyUI/custom_nodes/ComfyUI-KJNodes/utility/magictex.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generates psychedelic color textures in the spirit of Blender's magic texture shader using Python/Numpy
2
+
3
+ https://github.com/cheind/magic-texture
4
+ """
5
+ from typing import Tuple, Optional
6
+ import numpy as np
7
+
8
+
9
+ def coordinate_grid(shape: Tuple[int, int], dtype=np.float32):
10
+ """Returns a three-dimensional coordinate grid of given shape for use in `magic`."""
11
+ x = np.linspace(-1, 1, shape[1], endpoint=True, dtype=dtype)
12
+ y = np.linspace(-1, 1, shape[0], endpoint=True, dtype=dtype)
13
+ X, Y = np.meshgrid(x, y)
14
+ XYZ = np.stack((X, Y, np.ones_like(X)), -1)
15
+ return XYZ
16
+
17
+
18
+ def random_transform(coords: np.ndarray, rng: np.random.Generator = None):
19
+ """Returns randomly transformed coordinates"""
20
+ H, W = coords.shape[:2]
21
+ rng = rng or np.random.default_rng()
22
+ m = rng.uniform(-1.0, 1.0, size=(3, 3)).astype(coords.dtype)
23
+ return (coords.reshape(-1, 3) @ m.T).reshape(H, W, 3)
24
+
25
+
26
+ def magic(
27
+ coords: np.ndarray,
28
+ depth: Optional[int] = None,
29
+ distortion: Optional[int] = None,
30
+ rng: np.random.Generator = None,
31
+ ):
32
+ """Returns color magic color texture.
33
+
34
+ The implementation is based on Blender's (https://www.blender.org/) magic
35
+ texture shader. The following adaptions have been made:
36
+ - we exchange the nested if-cascade by a probabilistic iterative approach
37
+
38
+ Kwargs
39
+ ------
40
+ coords: HxWx3 array
41
+ Coordinates transformed into colors by this method. See
42
+ `magictex.coordinate_grid` to generate the default.
43
+ depth: int (optional)
44
+ Number of transformations applied. Higher numbers lead to more
45
+ nested patterns. If not specified, randomly sampled.
46
+ distortion: float (optional)
47
+ Distortion of patterns. Larger values indicate more distortion,
48
+ lower values tend to generate smoother patterns. If not specified,
49
+ randomly sampled.
50
+ rng: np.random.Generator
51
+ Optional random generator to draw samples from.
52
+
53
+ Returns
54
+ -------
55
+ colors: HxWx3 array
56
+ Three channel color image in range [0,1]
57
+ """
58
+ rng = rng or np.random.default_rng()
59
+ if distortion is None:
60
+ distortion = rng.uniform(1, 4)
61
+ if depth is None:
62
+ depth = rng.integers(1, 5)
63
+
64
+ H, W = coords.shape[:2]
65
+ XYZ = coords
66
+ x = np.sin((XYZ[..., 0] + XYZ[..., 1] + XYZ[..., 2]) * distortion)
67
+ y = np.cos((-XYZ[..., 0] + XYZ[..., 1] - XYZ[..., 2]) * distortion)
68
+ z = -np.cos((-XYZ[..., 0] - XYZ[..., 1] + XYZ[..., 2]) * distortion)
69
+
70
+ if depth > 0:
71
+ x *= distortion
72
+ y *= distortion
73
+ z *= distortion
74
+ y = -np.cos(x - y + z)
75
+ y *= distortion
76
+
77
+ xyz = [x, y, z]
78
+ fns = [np.cos, np.sin]
79
+ for _ in range(1, depth):
80
+ axis = rng.choice(3)
81
+ fn = fns[rng.choice(2)]
82
+ signs = rng.binomial(n=1, p=0.5, size=4) * 2 - 1
83
+
84
+ xyz[axis] = signs[-1] * fn(
85
+ signs[0] * xyz[0] + signs[1] * xyz[1] + signs[2] * xyz[2]
86
+ )
87
+ xyz[axis] *= distortion
88
+
89
+ x, y, z = xyz
90
+ x /= 2 * distortion
91
+ y /= 2 * distortion
92
+ z /= 2 * distortion
93
+ c = 0.5 - np.stack((x, y, z), -1)
94
+ np.clip(c, 0, 1.0)
95
+ return c
ComfyUI/custom_nodes/ComfyUI-KJNodes/utility/numerical.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from functools import reduce
2
+ from itertools import cycle
3
+ from math import factorial
4
+
5
+ import numpy as np
6
+ import scipy.sparse as sp
7
+
8
+
9
+ def difference(derivative, accuracy=1):
10
+ # Central differences implemented based on the article here:
11
+ # http://web.media.mit.edu/~crtaylor/calculator.html
12
+ derivative += 1
13
+ radius = accuracy + derivative // 2 - 1
14
+ points = range(-radius, radius + 1)
15
+ coefficients = np.linalg.inv(np.vander(points))
16
+ return coefficients[-derivative] * factorial(derivative - 1), points
17
+
18
+
19
+ def operator(shape, *differences):
20
+ # Credit to Philip Zucker for figuring out
21
+ # that kronsum's argument order is reversed.
22
+ # Without that bit of wisdom I'd have lost it.
23
+ differences = zip(shape, cycle(differences))
24
+ factors = (sp.diags(*diff, shape=(dim,) * 2) for dim, diff in differences)
25
+ return reduce(lambda a, f: sp.kronsum(f, a, format='csc'), factors)
ComfyUI/custom_nodes/ComfyUI-KJNodes/utility/utility.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import numpy as np
3
+ from PIL import Image
4
+ from typing import Union, List
5
+
6
+ # Utility functions from mtb nodes: https://github.com/melMass/comfy_mtb
7
+ def pil2tensor(image: Union[Image.Image, List[Image.Image]]) -> torch.Tensor:
8
+ if isinstance(image, list):
9
+ return torch.cat([pil2tensor(img) for img in image], dim=0)
10
+
11
+ return torch.from_numpy(np.array(image).astype(np.float32) / 255.0).unsqueeze(0)
12
+
13
+
14
+ def np2tensor(img_np: Union[np.ndarray, List[np.ndarray]]) -> torch.Tensor:
15
+ if isinstance(img_np, list):
16
+ return torch.cat([np2tensor(img) for img in img_np], dim=0)
17
+
18
+ return torch.from_numpy(img_np.astype(np.float32) / 255.0).unsqueeze(0)
19
+
20
+
21
+ def tensor2np(tensor: torch.Tensor):
22
+ if len(tensor.shape) == 3: # Single image
23
+ return np.clip(255.0 * tensor.cpu().numpy(), 0, 255).astype(np.uint8)
24
+ else: # Batch of images
25
+ return [np.clip(255.0 * t.cpu().numpy(), 0, 255).astype(np.uint8) for t in tensor]
26
+
27
+ def tensor2pil(image: torch.Tensor) -> List[Image.Image]:
28
+ batch_count = image.size(0) if len(image.shape) > 3 else 1
29
+ if batch_count > 1:
30
+ out = []
31
+ for i in range(batch_count):
32
+ out.extend(tensor2pil(image[i]))
33
+ return out
34
+
35
+ return [
36
+ Image.fromarray(
37
+ np.clip(255.0 * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)
38
+ )
39
+ ]
ComfyUI/custom_nodes/ComfyUI-KJNodes/web/green.png ADDED
ComfyUI/custom_nodes/ComfyUI-KJNodes/web/js/appearance.js ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../../scripts/app.js";
2
+
3
+ app.registerExtension({
4
+ name: "KJNodes.appearance",
5
+ nodeCreated(node) {
6
+ switch (node.comfyClass) {
7
+ case "INTConstant":
8
+ node.setSize([200, 58]);
9
+ node.color = "#1b4669";
10
+ node.bgcolor = "#29699c";
11
+ break;
12
+ case "FloatConstant":
13
+ node.setSize([200, 58]);
14
+ node.color = LGraphCanvas.node_colors.green.color;
15
+ node.bgcolor = LGraphCanvas.node_colors.green.bgcolor;
16
+ break;
17
+ case "ConditioningMultiCombine":
18
+ node.color = LGraphCanvas.node_colors.brown.color;
19
+ node.bgcolor = LGraphCanvas.node_colors.brown.bgcolor;
20
+ break;
21
+ }
22
+ }
23
+ });
ComfyUI/custom_nodes/ComfyUI-KJNodes/web/js/browserstatus.js ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { api } from "../../../scripts/api.js";
2
+ import { app } from "../../../scripts/app.js";
3
+
4
+ app.registerExtension({
5
+ name: "KJNodes.browserstatus",
6
+ setup() {
7
+ if (!app.ui.settings.getSettingValue("KJNodes.browserStatus")) {
8
+ return;
9
+ }
10
+ api.addEventListener("status", ({ detail }) => {
11
+ let title = "ComfyUI";
12
+ let favicon = "green";
13
+ let queueRemaining = detail && detail.exec_info.queue_remaining;
14
+
15
+ if (queueRemaining) {
16
+ favicon = "red";
17
+ title = `00% - ${queueRemaining} | ${title}`;
18
+ }
19
+ let link = document.querySelector("link[rel~='icon']");
20
+ if (!link) {
21
+ link = document.createElement("link");
22
+ link.rel = "icon";
23
+ document.head.appendChild(link);
24
+ }
25
+ link.href = new URL(`../${favicon}.png`, import.meta.url);
26
+ document.title = title;
27
+ });
28
+ //add progress to the title
29
+ api.addEventListener("progress", ({ detail }) => {
30
+ const { value, max } = detail;
31
+ const progress = Math.floor((value / max) * 100);
32
+ let title = document.title;
33
+
34
+ if (!isNaN(progress) && progress >= 0 && progress <= 100) {
35
+ const paddedProgress = String(progress).padStart(2, '0');
36
+ title = `${paddedProgress}% ${title.replace(/^\d+%\s/, '')}`;
37
+ }
38
+ document.title = title;
39
+ });
40
+ },
41
+ init() {
42
+ if (!app.ui.settings.getSettingValue("KJNodes.browserStatus")) {
43
+ return;
44
+ }
45
+ const pythongossFeed = app.extensions.find(
46
+ (e) => e.name === 'pysssss.FaviconStatus',
47
+ )
48
+ if (pythongossFeed) {
49
+ console.warn("KJNodes - Overriding pysssss.FaviconStatus")
50
+ app.extensions = app.extensions.filter(item => item !== pythongossFeed);
51
+ }
52
+ },
53
+ });
ComfyUI/custom_nodes/ComfyUI-KJNodes/web/js/contextmenu.js ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../../scripts/app.js";
2
+
3
+ // Adds context menu entries, code partly from pyssssscustom-scripts
4
+
5
+ function addMenuHandler(nodeType, cb) {
6
+ const getOpts = nodeType.prototype.getExtraMenuOptions;
7
+ nodeType.prototype.getExtraMenuOptions = function () {
8
+ const r = getOpts.apply(this, arguments);
9
+ cb.apply(this, arguments);
10
+ return r;
11
+ };
12
+ }
13
+
14
+ function addNode(name, nextTo, options) {
15
+ console.log("name:", name);
16
+ console.log("nextTo:", nextTo);
17
+ options = { side: "left", select: true, shiftY: 0, shiftX: 0, ...(options || {}) };
18
+ const node = LiteGraph.createNode(name);
19
+ app.graph.add(node);
20
+
21
+ node.pos = [
22
+ options.side === "left" ? nextTo.pos[0] - (node.size[0] + options.offset): nextTo.pos[0] + nextTo.size[0] + options.offset,
23
+
24
+ nextTo.pos[1] + options.shiftY,
25
+ ];
26
+ if (options.select) {
27
+ app.canvas.selectNode(node, false);
28
+ }
29
+ return node;
30
+ }
31
+
32
+ app.registerExtension({
33
+ name: "KJNodesContextmenu",
34
+ async beforeRegisterNodeDef(nodeType, nodeData, app) {
35
+ if (nodeData.input && nodeData.input.required) {
36
+ addMenuHandler(nodeType, function (_, options) {
37
+ options.unshift(
38
+ {
39
+ content: "Add GetNode",
40
+ callback: () => {addNode("GetNode", this, { side:"left", offset: 30});}
41
+ },
42
+ {
43
+ content: "Add SetNode",
44
+ callback: () => {addNode("SetNode", this, { side:"right", offset: 30 });
45
+ },
46
+ });
47
+ });
48
+ }
49
+ },
50
+ async setup(app) {
51
+ const onChange = (value) => {
52
+ if (value) {
53
+ const valuesToAddToIn = ["GetNode"];
54
+ const valuesToAddToOut = ["SetNode"];
55
+
56
+ for (const arr of Object.values(LiteGraph.slot_types_default_in)) {
57
+ for (const valueToAdd of valuesToAddToIn) {
58
+ const idx = arr.indexOf(valueToAdd);
59
+ if (idx !== 0) {
60
+ arr.splice(idx, 1);
61
+ }
62
+ arr.unshift(valueToAdd);
63
+ }
64
+ }
65
+
66
+ for (const arr of Object.values(LiteGraph.slot_types_default_out)) {
67
+ for (const valueToAdd of valuesToAddToOut) {
68
+ const idx = arr.indexOf(valueToAdd);
69
+ if (idx !== 0) {
70
+ arr.splice(idx, 1);
71
+ }
72
+ arr.unshift(valueToAdd);
73
+ }
74
+ }
75
+ }
76
+ };
77
+
78
+ app.ui.settings.addSetting({
79
+ id: "🦛 KJNodes.SetGetMenu",
80
+ name: "🦛 KJNodes: Make Set/Get -nodes defaults (turn off and reload to disable)",
81
+ defaultValue: false,
82
+ type: "boolean",
83
+ options: (value) => [
84
+ {
85
+ value: true,
86
+ text: "On",
87
+ selected: value === true,
88
+ },
89
+ {
90
+ value: false,
91
+ text: "Off",
92
+ selected: value === false,
93
+ },
94
+ ],
95
+ onChange: onChange,
96
+
97
+ });
98
+ app.ui.settings.addSetting({
99
+ id: "KJNodes.DisableMiddleClickDefault",
100
+ name: "🦛 KJNodes: Middle click default node adding",
101
+ defaultValue: false,
102
+ type: "boolean",
103
+ options: (value) => [
104
+ { value: true, text: "On", selected: value === true },
105
+ { value: false, text: "Off", selected: value === false },
106
+ ],
107
+ onChange: (value) => {
108
+ LiteGraph.middle_click_slot_add_default_node = value;
109
+ },
110
+ });
111
+ app.ui.settings.addSetting({
112
+ id: "KJNodes.nodeAutoColor",
113
+ name: "🦛 KJNodes: Automatically set node colors",
114
+ defaultValue: true,
115
+ type: "boolean",
116
+ options: (value) => [
117
+ { value: true, text: "On", selected: value === true },
118
+ { value: false, text: "Off", selected: value === false },
119
+ ],
120
+ });
121
+ app.ui.settings.addSetting({
122
+ id: "KJNodes.helpPopup",
123
+ name: "🦛 KJNodes: Help popups",
124
+ defaultValue: true,
125
+ type: "boolean",
126
+ options: (value) => [
127
+ { value: true, text: "On", selected: value === true },
128
+ { value: false, text: "Off", selected: value === false },
129
+ ],
130
+ });
131
+ app.ui.settings.addSetting({
132
+ id: "KJNodes.disablePrefix",
133
+ name: "🦛 KJNodes: Disable automatic Set_ and Get_ prefix",
134
+ defaultValue: false,
135
+ type: "boolean",
136
+ options: (value) => [
137
+ { value: true, text: "On", selected: value === true },
138
+ { value: false, text: "Off", selected: value === false },
139
+ ],
140
+ });
141
+ app.ui.settings.addSetting({
142
+ id: "KJNodes.browserStatus",
143
+ name: "🦛 KJNodes: 🟢 Stoplight browser status icon 🔴",
144
+ defaultValue: false,
145
+ type: "boolean",
146
+ options: (value) => [
147
+ { value: true, text: "On", selected: value === true },
148
+ { value: false, text: "Off", selected: value === false },
149
+ ],
150
+ });
151
+ }
152
+ });
ComfyUI/custom_nodes/ComfyUI-KJNodes/web/js/help_popup.js ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../../scripts/app.js";
2
+
3
+ // code based on mtb nodes by Mel Massadian https://github.com/melMass/comfy_mtb/
4
+ export const loadScript = (
5
+ FILE_URL,
6
+ async = true,
7
+ type = 'text/javascript',
8
+ ) => {
9
+ return new Promise((resolve, reject) => {
10
+ try {
11
+ // Check if the script already exists
12
+ const existingScript = document.querySelector(`script[src="${FILE_URL}"]`)
13
+ if (existingScript) {
14
+ resolve({ status: true, message: 'Script already loaded' })
15
+ return
16
+ }
17
+
18
+ const scriptEle = document.createElement('script')
19
+ scriptEle.type = type
20
+ scriptEle.async = async
21
+ scriptEle.src = FILE_URL
22
+
23
+ scriptEle.addEventListener('load', (ev) => {
24
+ resolve({ status: true })
25
+ })
26
+
27
+ scriptEle.addEventListener('error', (ev) => {
28
+ reject({
29
+ status: false,
30
+ message: `Failed to load the script ${FILE_URL}`,
31
+ })
32
+ })
33
+
34
+ document.body.appendChild(scriptEle)
35
+ } catch (error) {
36
+ reject(error)
37
+ }
38
+ })
39
+ }
40
+
41
+ loadScript('/kjweb_async/marked.min.js').catch((e) => {
42
+ console.log(e)
43
+ })
44
+ loadScript('/kjweb_async/purify.min.js').catch((e) => {
45
+ console.log(e)
46
+ })
47
+
48
+ const categories = ["KJNodes", "SUPIR", "VoiceCraft", "Marigold", "IC-Light"];
49
+ app.registerExtension({
50
+ name: "KJNodes.HelpPopup",
51
+ async beforeRegisterNodeDef(nodeType, nodeData) {
52
+
53
+ if (app.ui.settings.getSettingValue("KJNodes.helpPopup") === false) {
54
+ return;
55
+ }
56
+ try {
57
+ categories.forEach(category => {
58
+ if (nodeData?.category?.startsWith(category)) {
59
+ addDocumentation(nodeData, nodeType);
60
+ }
61
+ else return
62
+ });
63
+ } catch (error) {
64
+ console.error("Error in registering KJNodes.HelpPopup", error);
65
+ }
66
+ },
67
+ });
68
+
69
+ const create_documentation_stylesheet = () => {
70
+ const tag = 'kj-documentation-stylesheet'
71
+
72
+ let styleTag = document.head.querySelector(tag)
73
+
74
+ if (!styleTag) {
75
+ styleTag = document.createElement('style')
76
+ styleTag.type = 'text/css'
77
+ styleTag.id = tag
78
+ styleTag.innerHTML = `
79
+ .kj-documentation-popup {
80
+ background: var(--comfy-menu-bg);
81
+ position: absolute;
82
+ color: var(--fg-color);
83
+ font: 12px monospace;
84
+ line-height: 1.5em;
85
+ padding: 10px;
86
+ border-radius: 10px;
87
+ border-style: solid;
88
+ border-width: medium;
89
+ border-color: var(--border-color);
90
+ z-index: 5;
91
+ overflow: hidden;
92
+ }
93
+ .content-wrapper {
94
+ overflow: auto;
95
+ max-height: 100%;
96
+ /* Scrollbar styling for Chrome */
97
+ &::-webkit-scrollbar {
98
+ width: 6px;
99
+ }
100
+ &::-webkit-scrollbar-track {
101
+ background: var(--bg-color);
102
+ }
103
+ &::-webkit-scrollbar-thumb {
104
+ background-color: var(--fg-color);
105
+ border-radius: 6px;
106
+ border: 3px solid var(--bg-color);
107
+ }
108
+
109
+ /* Scrollbar styling for Firefox */
110
+ scrollbar-width: thin;
111
+ scrollbar-color: var(--fg-color) var(--bg-color);
112
+ a {
113
+ color: yellow;
114
+ }
115
+ a:visited {
116
+ color: orange;
117
+ }
118
+ a:hover {
119
+ color: red;
120
+ }
121
+ }
122
+ `
123
+ document.head.appendChild(styleTag)
124
+ }
125
+ }
126
+
127
+ /** Add documentation widget to the selected node */
128
+ export const addDocumentation = (
129
+ nodeData,
130
+ nodeType,
131
+ opts = { icon_size: 14, icon_margin: 4 },) => {
132
+
133
+ opts = opts || {}
134
+ const iconSize = opts.icon_size ? opts.icon_size : 14
135
+ const iconMargin = opts.icon_margin ? opts.icon_margin : 4
136
+ let docElement = null
137
+ let contentWrapper = null
138
+ //if no description in the node python code, don't do anything
139
+ if (!nodeData.description) {
140
+ return
141
+ }
142
+
143
+ const drawFg = nodeType.prototype.onDrawForeground
144
+ nodeType.prototype.onDrawForeground = function (ctx) {
145
+ const r = drawFg ? drawFg.apply(this, arguments) : undefined
146
+ if (this.flags.collapsed) return r
147
+
148
+ // icon position
149
+ const x = this.size[0] - iconSize - iconMargin
150
+
151
+ // create the popup
152
+ if (this.show_doc && docElement === null) {
153
+ docElement = document.createElement('div')
154
+ contentWrapper = document.createElement('div');
155
+ docElement.appendChild(contentWrapper);
156
+
157
+ create_documentation_stylesheet()
158
+ contentWrapper.classList.add('content-wrapper');
159
+ docElement.classList.add('kj-documentation-popup')
160
+
161
+ //parse the string from the python node code to html with marked, and sanitize the html with DOMPurify
162
+ contentWrapper.innerHTML = DOMPurify.sanitize(marked.parse(nodeData.description,))
163
+
164
+ // resize handle
165
+ const resizeHandle = document.createElement('div');
166
+ resizeHandle.style.width = '0';
167
+ resizeHandle.style.height = '0';
168
+ resizeHandle.style.position = 'absolute';
169
+ resizeHandle.style.bottom = '0';
170
+ resizeHandle.style.right = '0';
171
+ resizeHandle.style.cursor = 'se-resize';
172
+
173
+ // Add pseudo-elements to create a triangle shape
174
+ const borderColor = getComputedStyle(document.documentElement).getPropertyValue('--border-color').trim();
175
+ resizeHandle.style.borderTop = '10px solid transparent';
176
+ resizeHandle.style.borderLeft = '10px solid transparent';
177
+ resizeHandle.style.borderBottom = `10px solid ${borderColor}`;
178
+ resizeHandle.style.borderRight = `10px solid ${borderColor}`;
179
+
180
+ docElement.appendChild(resizeHandle)
181
+ let isResizing = false
182
+ let startX, startY, startWidth, startHeight
183
+
184
+ resizeHandle.addEventListener('mousedown', function (e) {
185
+ e.preventDefault();
186
+ e.stopPropagation();
187
+ isResizing = true;
188
+ startX = e.clientX;
189
+ startY = e.clientY;
190
+ startWidth = parseInt(document.defaultView.getComputedStyle(docElement).width, 10);
191
+ startHeight = parseInt(document.defaultView.getComputedStyle(docElement).height, 10);
192
+ },
193
+ { signal: this.docCtrl.signal },
194
+ );
195
+
196
+ // close button
197
+ const closeButton = document.createElement('div');
198
+ closeButton.textContent = '❌';
199
+ closeButton.style.position = 'absolute';
200
+ closeButton.style.top = '0';
201
+ closeButton.style.right = '0';
202
+ closeButton.style.cursor = 'pointer';
203
+ closeButton.style.padding = '5px';
204
+ closeButton.style.color = 'red';
205
+ closeButton.style.fontSize = '12px';
206
+
207
+ docElement.appendChild(closeButton)
208
+
209
+ closeButton.addEventListener('mousedown', (e) => {
210
+ e.stopPropagation();
211
+ this.show_doc = !this.show_doc
212
+ docElement.parentNode.removeChild(docElement)
213
+ docElement = null
214
+ if (contentWrapper) {
215
+ contentWrapper.remove()
216
+ contentWrapper = null
217
+ }
218
+ },
219
+ { signal: this.docCtrl.signal },
220
+ );
221
+
222
+ document.addEventListener('mousemove', function (e) {
223
+ if (!isResizing) return;
224
+ const scale = app.canvas.ds.scale;
225
+ const newWidth = startWidth + (e.clientX - startX) / scale;
226
+ const newHeight = startHeight + (e.clientY - startY) / scale;;
227
+ docElement.style.width = `${newWidth}px`;
228
+ docElement.style.height = `${newHeight}px`;
229
+ },
230
+ { signal: this.docCtrl.signal },
231
+ );
232
+
233
+ document.addEventListener('mouseup', function () {
234
+ isResizing = false
235
+ },
236
+ { signal: this.docCtrl.signal },
237
+ )
238
+
239
+ document.body.appendChild(docElement)
240
+ }
241
+ // close the popup
242
+ else if (!this.show_doc && docElement !== null) {
243
+ docElement.parentNode.removeChild(docElement)
244
+ docElement = null
245
+ }
246
+ // update position of the popup
247
+ if (this.show_doc && docElement !== null) {
248
+ const rect = ctx.canvas.getBoundingClientRect()
249
+ const scaleX = rect.width / ctx.canvas.width
250
+ const scaleY = rect.height / ctx.canvas.height
251
+
252
+ const transform = new DOMMatrix()
253
+ .scaleSelf(scaleX, scaleY)
254
+ .multiplySelf(ctx.getTransform())
255
+ .translateSelf(this.size[0] * scaleX * Math.max(1.0,window.devicePixelRatio) , 0)
256
+ .translateSelf(10, -32)
257
+
258
+ const scale = new DOMMatrix()
259
+ .scaleSelf(transform.a, transform.d);
260
+
261
+ const styleObject = {
262
+ transformOrigin: '0 0',
263
+ transform: scale,
264
+ left: `${transform.a + transform.e}px`,
265
+ top: `${transform.d + transform.f}px`,
266
+ };
267
+ Object.assign(docElement.style, styleObject);
268
+ }
269
+
270
+ ctx.save()
271
+ ctx.translate(x - 2, iconSize - 34)
272
+ ctx.scale(iconSize / 32, iconSize / 32)
273
+ ctx.strokeStyle = 'rgba(255,255,255,0.3)'
274
+ ctx.lineCap = 'round'
275
+ ctx.lineJoin = 'round'
276
+ ctx.lineWidth = 2.4
277
+ ctx.font = 'bold 36px monospace'
278
+ ctx.fillStyle = 'orange';
279
+ ctx.fillText('?', 0, 24)
280
+ ctx.restore()
281
+ return r
282
+ }
283
+ // handle clicking of the icon
284
+ const mouseDown = nodeType.prototype.onMouseDown
285
+ nodeType.prototype.onMouseDown = function (e, localPos, canvas) {
286
+ const r = mouseDown ? mouseDown.apply(this, arguments) : undefined
287
+ const iconX = this.size[0] - iconSize - iconMargin
288
+ const iconY = iconSize - 34
289
+ if (
290
+ localPos[0] > iconX &&
291
+ localPos[0] < iconX + iconSize &&
292
+ localPos[1] > iconY &&
293
+ localPos[1] < iconY + iconSize
294
+ ) {
295
+ if (this.show_doc === undefined) {
296
+ this.show_doc = true
297
+ } else {
298
+ this.show_doc = !this.show_doc
299
+ }
300
+ if (this.show_doc) {
301
+ this.docCtrl = new AbortController()
302
+ } else {
303
+ this.docCtrl.abort()
304
+ }
305
+ return true;
306
+ }
307
+ return r;
308
+ }
309
+ const onRem = nodeType.prototype.onRemoved
310
+
311
+ nodeType.prototype.onRemoved = function () {
312
+ const r = onRem ? onRem.apply(this, []) : undefined
313
+
314
+ if (docElement) {
315
+ docElement.remove()
316
+ docElement = null
317
+ }
318
+
319
+ if (contentWrapper) {
320
+ contentWrapper.remove()
321
+ contentWrapper = null
322
+ }
323
+ return r
324
+ }
325
+ }
ComfyUI/custom_nodes/ComfyUI-KJNodes/web/js/jsnodes.js ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../../scripts/app.js";
2
+
3
+ app.registerExtension({
4
+ name: "KJNodes.jsnodes",
5
+ async beforeRegisterNodeDef(nodeType, nodeData, app) {
6
+ if(!nodeData?.category?.startsWith("KJNodes")) {
7
+ return;
8
+ }
9
+ switch (nodeData.name) {
10
+ case "ConditioningMultiCombine":
11
+ nodeType.prototype.onNodeCreated = function () {
12
+ this.cond_type = "CONDITIONING"
13
+ this.inputs_offset = nodeData.name.includes("selective")?1:0
14
+ this.addWidget("button", "Update inputs", null, () => {
15
+ if (!this.inputs) {
16
+ this.inputs = [];
17
+ }
18
+ const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"];
19
+ if(target_number_of_inputs===this.inputs.length)return; // already set, do nothing
20
+
21
+ if(target_number_of_inputs < this.inputs.length){
22
+ for(let i = this.inputs.length; i>=this.inputs_offset+target_number_of_inputs; i--)
23
+ this.removeInput(i)
24
+ }
25
+ else{
26
+ for(let i = this.inputs.length+1-this.inputs_offset; i <= target_number_of_inputs; ++i)
27
+ this.addInput(`conditioning_${i}`, this.cond_type)
28
+ }
29
+ });
30
+ }
31
+ break;
32
+ case "ImageBatchMulti":
33
+ case "ImageAddMulti":
34
+ case "ImageConcatMulti":
35
+ nodeType.prototype.onNodeCreated = function () {
36
+ this._type = "IMAGE"
37
+ this.inputs_offset = nodeData.name.includes("selective")?1:0
38
+ this.addWidget("button", "Update inputs", null, () => {
39
+ if (!this.inputs) {
40
+ this.inputs = [];
41
+ }
42
+ const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"];
43
+ if(target_number_of_inputs===this.inputs.length)return; // already set, do nothing
44
+
45
+ if(target_number_of_inputs < this.inputs.length){
46
+ for(let i = this.inputs.length; i>=this.inputs_offset+target_number_of_inputs; i--)
47
+ this.removeInput(i)
48
+ }
49
+ else{
50
+ for(let i = this.inputs.length+1-this.inputs_offset; i <= target_number_of_inputs; ++i)
51
+ this.addInput(`image_${i}`, this._type)
52
+ }
53
+ });
54
+ }
55
+ break;
56
+ case "MaskBatchMulti":
57
+ nodeType.prototype.onNodeCreated = function () {
58
+ this._type = "MASK"
59
+ this.inputs_offset = nodeData.name.includes("selective")?1:0
60
+ this.addWidget("button", "Update inputs", null, () => {
61
+ if (!this.inputs) {
62
+ this.inputs = [];
63
+ }
64
+ const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"];
65
+ if(target_number_of_inputs===this.inputs.length)return; // already set, do nothing
66
+
67
+ if(target_number_of_inputs < this.inputs.length){
68
+ for(let i = this.inputs.length; i>=this.inputs_offset+target_number_of_inputs; i--)
69
+ this.removeInput(i)
70
+ }
71
+ else{
72
+ for(let i = this.inputs.length+1-this.inputs_offset; i <= target_number_of_inputs; ++i)
73
+ this.addInput(`mask_${i}`, this._type)
74
+ }
75
+ });
76
+ }
77
+ break;
78
+
79
+ case "GetMaskSizeAndCount":
80
+ const onGetMaskSizeConnectInput = nodeType.prototype.onConnectInput;
81
+ nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) {
82
+ const v = onGetMaskSizeConnectInput? onGetMaskSizeConnectInput.apply(this, arguments): undefined
83
+ this.outputs[1]["name"] = "width"
84
+ this.outputs[2]["name"] = "height"
85
+ this.outputs[3]["name"] = "count"
86
+ return v;
87
+ }
88
+ const onGetMaskSizeExecuted = nodeType.prototype.onExecuted;
89
+ nodeType.prototype.onExecuted = function(message) {
90
+ const r = onGetMaskSizeExecuted? onGetMaskSizeExecuted.apply(this,arguments): undefined
91
+ let values = message["text"].toString().split('x').map(Number);
92
+ this.outputs[1]["name"] = values[1] + " width"
93
+ this.outputs[2]["name"] = values[2] + " height"
94
+ this.outputs[3]["name"] = values[0] + " count"
95
+ return r
96
+ }
97
+ break;
98
+
99
+ case "GetImageSizeAndCount":
100
+ const onGetImageSizeConnectInput = nodeType.prototype.onConnectInput;
101
+ nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) {
102
+ const v = onGetImageSizeConnectInput? onGetImageSizeConnectInput.apply(this, arguments): undefined
103
+ this.outputs[1]["name"] = "width"
104
+ this.outputs[2]["name"] = "height"
105
+ this.outputs[3]["name"] = "count"
106
+ return v;
107
+ }
108
+ const onGetImageSizeExecuted = nodeType.prototype.onExecuted;
109
+ nodeType.prototype.onExecuted = function(message) {
110
+ const r = onGetImageSizeExecuted? onGetImageSizeExecuted.apply(this,arguments): undefined
111
+ let values = message["text"].toString().split('x').map(Number);
112
+ this.outputs[1]["name"] = values[1] + " width"
113
+ this.outputs[2]["name"] = values[2] + " height"
114
+ this.outputs[3]["name"] = values[0] + " count"
115
+ return r
116
+ }
117
+ break;
118
+
119
+ case "PreviewAnimation":
120
+ const onPreviewAnimationConnectInput = nodeType.prototype.onConnectInput;
121
+ nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) {
122
+ const v = onPreviewAnimationConnectInput? onPreviewAnimationConnectInput.apply(this, arguments): undefined
123
+ this.title = "Preview Animation"
124
+ return v;
125
+ }
126
+ const onPreviewAnimationExecuted = nodeType.prototype.onExecuted;
127
+ nodeType.prototype.onExecuted = function(message) {
128
+ const r = onPreviewAnimationExecuted? onPreviewAnimationExecuted.apply(this,arguments): undefined
129
+ let values = message["text"].toString();
130
+ this.title = "Preview Animation " + values
131
+ return r
132
+ }
133
+ break;
134
+
135
+ case "VRAM_Debug":
136
+ const onVRAM_DebugConnectInput = nodeType.prototype.onConnectInput;
137
+ nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) {
138
+ const v = onVRAM_DebugConnectInput? onVRAM_DebugConnectInput.apply(this, arguments): undefined
139
+ this.outputs[3]["name"] = "freemem_before"
140
+ this.outputs[4]["name"] = "freemem_after"
141
+ return v;
142
+ }
143
+ const onVRAM_DebugExecuted = nodeType.prototype.onExecuted;
144
+ nodeType.prototype.onExecuted = function(message) {
145
+ const r = onVRAM_DebugExecuted? onVRAM_DebugExecuted.apply(this,arguments): undefined
146
+ let values = message["text"].toString().split('x');
147
+ this.outputs[3]["name"] = values[0] + " freemem_before"
148
+ this.outputs[4]["name"] = values[1] + " freemem_after"
149
+ return r
150
+ }
151
+ break;
152
+
153
+ case "JoinStringMulti":
154
+ nodeType.prototype.onNodeCreated = function () {
155
+ this._type = "STRING"
156
+ this.inputs_offset = nodeData.name.includes("selective")?1:0
157
+ this.addWidget("button", "Update inputs", null, () => {
158
+ if (!this.inputs) {
159
+ this.inputs = [];
160
+ }
161
+ const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"];
162
+ if(target_number_of_inputs===this.inputs.length)return; // already set, do nothing
163
+
164
+ if(target_number_of_inputs < this.inputs.length){
165
+ for(let i = this.inputs.length; i>=this.inputs_offset+target_number_of_inputs; i--)
166
+ this.removeInput(i)
167
+ }
168
+ else{
169
+ for(let i = this.inputs.length+1-this.inputs_offset; i <= target_number_of_inputs; ++i)
170
+ this.addInput(`string_${i}`, this._type)
171
+ }
172
+ });
173
+ }
174
+ break;
175
+ case "SoundReactive":
176
+ nodeType.prototype.onNodeCreated = function () {
177
+ let audioContext;
178
+ let microphoneStream;
179
+ let animationFrameId;
180
+ let analyser;
181
+ let dataArray;
182
+ let startRangeHz;
183
+ let endRangeHz;
184
+ let smoothingFactor = 0.5;
185
+ let smoothedSoundLevel = 0;
186
+
187
+ // Function to update the widget value in real-time
188
+ const updateWidgetValueInRealTime = () => {
189
+ // Ensure analyser and dataArray are defined before using them
190
+ if (analyser && dataArray) {
191
+ analyser.getByteFrequencyData(dataArray);
192
+
193
+ const startRangeHzWidget = this.widgets.find(w => w.name === "start_range_hz");
194
+ if (startRangeHzWidget) startRangeHz = startRangeHzWidget.value;
195
+ const endRangeHzWidget = this.widgets.find(w => w.name === "end_range_hz");
196
+ if (endRangeHzWidget) endRangeHz = endRangeHzWidget.value;
197
+ const smoothingFactorWidget = this.widgets.find(w => w.name === "smoothing_factor");
198
+ if (smoothingFactorWidget) smoothingFactor = smoothingFactorWidget.value;
199
+
200
+ // Calculate frequency bin width (frequency resolution)
201
+ const frequencyBinWidth = audioContext.sampleRate / analyser.fftSize;
202
+ // Convert the widget values from Hz to indices
203
+ const startRangeIndex = Math.floor(startRangeHz / frequencyBinWidth);
204
+ const endRangeIndex = Math.floor(endRangeHz / frequencyBinWidth);
205
+
206
+ // Function to calculate the average value for a frequency range
207
+ const calculateAverage = (start, end) => {
208
+ const sum = dataArray.slice(start, end).reduce((acc, val) => acc + val, 0);
209
+ const average = sum / (end - start);
210
+
211
+ // Apply exponential moving average smoothing
212
+ smoothedSoundLevel = (average * (1 - smoothingFactor)) + (smoothedSoundLevel * smoothingFactor);
213
+ return smoothedSoundLevel;
214
+ };
215
+ // Calculate the average levels for each frequency range
216
+ const soundLevel = calculateAverage(startRangeIndex, endRangeIndex);
217
+
218
+ // Update the widget values
219
+
220
+ const lowLevelWidget = this.widgets.find(w => w.name === "sound_level");
221
+ if (lowLevelWidget) lowLevelWidget.value = soundLevel;
222
+
223
+ animationFrameId = requestAnimationFrame(updateWidgetValueInRealTime);
224
+ }
225
+ };
226
+
227
+ // Function to start capturing audio from the microphone
228
+ const startMicrophoneCapture = () => {
229
+ // Only create the audio context and analyser once
230
+ if (!audioContext) {
231
+ audioContext = new (window.AudioContext || window.webkitAudioContext)();
232
+ // Access the sample rate of the audio context
233
+ console.log(`Sample rate: ${audioContext.sampleRate}Hz`);
234
+ analyser = audioContext.createAnalyser();
235
+ analyser.fftSize = 2048;
236
+ dataArray = new Uint8Array(analyser.frequencyBinCount);
237
+ // Get the range values from widgets (assumed to be in Hz)
238
+ const lowRangeWidget = this.widgets.find(w => w.name === "low_range_hz");
239
+ if (lowRangeWidget) startRangeHz = lowRangeWidget.value;
240
+
241
+ const midRangeWidget = this.widgets.find(w => w.name === "mid_range_hz");
242
+ if (midRangeWidget) endRangeHz = midRangeWidget.value;
243
+ }
244
+
245
+ navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
246
+ microphoneStream = stream;
247
+ const microphone = audioContext.createMediaStreamSource(stream);
248
+ microphone.connect(analyser);
249
+ updateWidgetValueInRealTime();
250
+ }).catch(error => {
251
+ console.error('Access to microphone was denied or an error occurred:', error);
252
+ });
253
+ };
254
+
255
+ // Function to stop capturing audio from the microphone
256
+ const stopMicrophoneCapture = () => {
257
+ if (animationFrameId) {
258
+ cancelAnimationFrame(animationFrameId);
259
+ }
260
+ if (microphoneStream) {
261
+ microphoneStream.getTracks().forEach(track => track.stop());
262
+ }
263
+ if (audioContext) {
264
+ audioContext.close();
265
+ // Reset audioContext to ensure it can be created again when starting
266
+ audioContext = null;
267
+ }
268
+ };
269
+
270
+ // Add start button
271
+ this.addWidget("button", "Start mic capture", null, startMicrophoneCapture);
272
+
273
+ // Add stop button
274
+ this.addWidget("button", "Stop mic capture", null, stopMicrophoneCapture);
275
+ };
276
+ break;
277
+
278
+ }
279
+
280
+ },
281
+ async setup() {
282
+ // to keep Set/Get node virtual connections visible when offscreen
283
+ const originalComputeVisibleNodes = LGraphCanvas.prototype.computeVisibleNodes;
284
+ LGraphCanvas.prototype.computeVisibleNodes = function () {
285
+ const visibleNodesSet = new Set(originalComputeVisibleNodes.apply(this, arguments));
286
+ for (const node of this.graph._nodes) {
287
+ if ((node.type === "SetNode" || node.type === "GetNode") && node.drawConnection) {
288
+ visibleNodesSet.add(node);
289
+ }
290
+ }
291
+ return Array.from(visibleNodesSet);
292
+ };
293
+
294
+ }
295
+ });
ComfyUI/custom_nodes/ComfyUI-KJNodes/web/js/point_editor.js ADDED
@@ -0,0 +1,732 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from '../../../scripts/app.js'
2
+
3
+ //from melmass
4
+ export function makeUUID() {
5
+ let dt = new Date().getTime()
6
+ const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
7
+ const r = ((dt + Math.random() * 16) % 16) | 0
8
+ dt = Math.floor(dt / 16)
9
+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
10
+ })
11
+ return uuid
12
+ }
13
+
14
+ export const loadScript = (
15
+ FILE_URL,
16
+ async = true,
17
+ type = 'text/javascript',
18
+ ) => {
19
+ return new Promise((resolve, reject) => {
20
+ try {
21
+ // Check if the script already exists
22
+ const existingScript = document.querySelector(`script[src="${FILE_URL}"]`)
23
+ if (existingScript) {
24
+ resolve({ status: true, message: 'Script already loaded' })
25
+ return
26
+ }
27
+
28
+ const scriptEle = document.createElement('script')
29
+ scriptEle.type = type
30
+ scriptEle.async = async
31
+ scriptEle.src = FILE_URL
32
+
33
+ scriptEle.addEventListener('load', (ev) => {
34
+ resolve({ status: true })
35
+ })
36
+
37
+ scriptEle.addEventListener('error', (ev) => {
38
+ reject({
39
+ status: false,
40
+ message: `Failed to load the script ${FILE_URL}`,
41
+ })
42
+ })
43
+
44
+ document.body.appendChild(scriptEle)
45
+ } catch (error) {
46
+ reject(error)
47
+ }
48
+ })
49
+ }
50
+ const create_documentation_stylesheet = () => {
51
+ const tag = 'kj-pointseditor-stylesheet'
52
+
53
+ let styleTag = document.head.querySelector(tag)
54
+
55
+ if (!styleTag) {
56
+ styleTag = document.createElement('style')
57
+ styleTag.type = 'text/css'
58
+ styleTag.id = tag
59
+ styleTag.innerHTML = `
60
+ .points-editor {
61
+
62
+ position: absolute;
63
+
64
+ font: 12px monospace;
65
+ line-height: 1.5em;
66
+ padding: 10px;
67
+ z-index: 0;
68
+ overflow: hidden;
69
+ }
70
+ `
71
+ document.head.appendChild(styleTag)
72
+ }
73
+ }
74
+
75
+ loadScript('/kjweb_async/svg-path-properties.min.js').catch((e) => {
76
+ console.log(e)
77
+ })
78
+ loadScript('/kjweb_async/protovis.min.js').catch((e) => {
79
+ console.log(e)
80
+ })
81
+ create_documentation_stylesheet()
82
+
83
+ function chainCallback(object, property, callback) {
84
+ if (object == undefined) {
85
+ //This should not happen.
86
+ console.error("Tried to add callback to non-existant object")
87
+ return;
88
+ }
89
+ if (property in object) {
90
+ const callback_orig = object[property]
91
+ object[property] = function () {
92
+ const r = callback_orig.apply(this, arguments);
93
+ callback.apply(this, arguments);
94
+ return r
95
+ };
96
+ } else {
97
+ object[property] = callback;
98
+ }
99
+ }
100
+ app.registerExtension({
101
+ name: 'KJNodes.PointEditor',
102
+
103
+ async beforeRegisterNodeDef(nodeType, nodeData) {
104
+ if (nodeData?.name === 'PointsEditor') {
105
+ chainCallback(nodeType.prototype, "onNodeCreated", function () {
106
+
107
+ hideWidgetForGood(this, this.widgets.find(w => w.name === "coordinates"))
108
+ hideWidgetForGood(this, this.widgets.find(w => w.name === "neg_coordinates"))
109
+ hideWidgetForGood(this, this.widgets.find(w => w.name === "bboxes"))
110
+
111
+ var element = document.createElement("div");
112
+ this.uuid = makeUUID()
113
+ element.id = `points-editor-${this.uuid}`
114
+
115
+ // fake image widget to allow copy/paste
116
+ const fakeimagewidget = this.addWidget("COMBO", "image", null, () => { }, {});
117
+ hideWidgetForGood(this, fakeimagewidget)
118
+
119
+ this.pointsEditor = this.addDOMWidget(nodeData.name, "PointsEditorWidget", element, {
120
+ serialize: false,
121
+ hideOnZoom: false,
122
+ });
123
+
124
+ // context menu
125
+ this.contextMenu = document.createElement("div");
126
+ this.contextMenu.id = "context-menu";
127
+ this.contextMenu.style.display = "none";
128
+ this.contextMenu.style.position = "absolute";
129
+ this.contextMenu.style.backgroundColor = "#202020";
130
+ this.contextMenu.style.minWidth = "100px";
131
+ this.contextMenu.style.boxShadow = "0px 8px 16px 0px rgba(0,0,0,0.2)";
132
+ this.contextMenu.style.zIndex = "100";
133
+ this.contextMenu.style.padding = "5px";
134
+
135
+ function styleMenuItem(menuItem) {
136
+ menuItem.style.display = "block";
137
+ menuItem.style.padding = "5px";
138
+ menuItem.style.color = "#FFF";
139
+ menuItem.style.fontFamily = "Arial, sans-serif";
140
+ menuItem.style.fontSize = "16px";
141
+ menuItem.style.textDecoration = "none";
142
+ menuItem.style.marginBottom = "5px";
143
+ }
144
+ function createMenuItem(id, textContent) {
145
+ let menuItem = document.createElement("a");
146
+ menuItem.href = "#";
147
+ menuItem.id = `menu-item-${id}`;
148
+ menuItem.textContent = textContent;
149
+ styleMenuItem(menuItem);
150
+ return menuItem;
151
+ }
152
+
153
+ // Create an array of menu items using the createMenuItem function
154
+ this.menuItems = [
155
+ createMenuItem(0, "Load Image"),
156
+ createMenuItem(1, "Clear Image"),
157
+ ];
158
+
159
+ // Add mouseover and mouseout event listeners to each menu item for styling
160
+ this.menuItems.forEach(menuItem => {
161
+ menuItem.addEventListener('mouseover', function () {
162
+ this.style.backgroundColor = "gray";
163
+ });
164
+
165
+ menuItem.addEventListener('mouseout', function () {
166
+ this.style.backgroundColor = "#202020";
167
+ });
168
+ });
169
+
170
+ // Append each menu item to the context menu
171
+ this.menuItems.forEach(menuItem => {
172
+ this.contextMenu.appendChild(menuItem);
173
+ });
174
+
175
+ document.body.appendChild(this.contextMenu);
176
+
177
+ this.addWidget("button", "New canvas", null, () => {
178
+ if (!this.properties || !("points" in this.properties)) {
179
+ this.editor = new PointsEditor(this);
180
+ this.addProperty("points", this.constructor.type, "string");
181
+ this.addProperty("neg_points", this.constructor.type, "string");
182
+
183
+ }
184
+ else {
185
+ this.editor = new PointsEditor(this, true);
186
+ }
187
+ });
188
+
189
+ this.setSize([550, 550]);
190
+ this.resizable = false;
191
+ this.pointsEditor.parentEl = document.createElement("div");
192
+ this.pointsEditor.parentEl.className = "points-editor";
193
+ this.pointsEditor.parentEl.id = `points-editor-${this.uuid}`
194
+ element.appendChild(this.pointsEditor.parentEl);
195
+
196
+ chainCallback(this, "onConfigure", function () {
197
+ this.editor = new PointsEditor(this);
198
+ });
199
+ chainCallback(this, "onExecuted", function (message) {
200
+ let bg_image = message["bg_image"];
201
+ this.properties.imgData = {
202
+ name: "bg_image",
203
+ base64: bg_image
204
+ };
205
+ this.editor.refreshBackgroundImage(this);
206
+ });
207
+
208
+ }); // onAfterGraphConfigured
209
+ }//node created
210
+ } //before register
211
+ })//register
212
+
213
+ class PointsEditor {
214
+ constructor(context, reset = false) {
215
+ this.node = context;
216
+ this.reset = reset;
217
+ const self = this; // Keep a reference to the main class context
218
+
219
+ console.log("creatingPointEditor")
220
+
221
+ this.node.pasteFile = (file) => {
222
+ if (file.type.startsWith("image/")) {
223
+ this.handleImageFile(file);
224
+ return true;
225
+ }
226
+ return false;
227
+ };
228
+
229
+ this.node.onDragOver = function (e) {
230
+ if (e.dataTransfer && e.dataTransfer.items) {
231
+ return [...e.dataTransfer.items].some(f => f.kind === "file" && f.type.startsWith("image/"));
232
+ }
233
+ return false;
234
+ };
235
+
236
+ // On drop upload files
237
+ this.node.onDragDrop = (e) => {
238
+ console.log("onDragDrop called");
239
+ let handled = false;
240
+ for (const file of e.dataTransfer.files) {
241
+ if (file.type.startsWith("image/")) {
242
+ this.handleImageFile(file);
243
+ handled = true;
244
+ }
245
+ }
246
+ return handled;
247
+ };
248
+
249
+ // context menu
250
+ this.createContextMenu();
251
+
252
+ if (reset && context.pointsEditor.element) {
253
+ context.pointsEditor.element.innerHTML = ''; // Clear the container
254
+ }
255
+ this.pos_coordWidget = context.widgets.find(w => w.name === "coordinates");
256
+ this.neg_coordWidget = context.widgets.find(w => w.name === "neg_coordinates");
257
+ this.pointsStoreWidget = context.widgets.find(w => w.name === "points_store");
258
+ this.widthWidget = context.widgets.find(w => w.name === "width");
259
+ this.heightWidget = context.widgets.find(w => w.name === "height");
260
+ this.bboxStoreWidget = context.widgets.find(w => w.name === "bbox_store");
261
+ this.bboxWidget = context.widgets.find(w => w.name === "bboxes");
262
+
263
+ //widget callbacks
264
+ this.widthWidget.callback = () => {
265
+ this.width = this.widthWidget.value;
266
+ if (this.width > 256) {
267
+ context.setSize([this.width + 45, context.size[1]]);
268
+ }
269
+ this.vis.width(this.width);
270
+ this.updateData();
271
+ }
272
+ this.heightWidget.callback = () => {
273
+ this.height = this.heightWidget.value
274
+ this.vis.height(this.height)
275
+ context.setSize([context.size[0], this.height + 300]);
276
+ this.updateData();
277
+ }
278
+ this.pointsStoreWidget.callback = () => {
279
+ this.points = JSON.parse(pointsStoreWidget.value).positive;
280
+ this.neg_points = JSON.parse(pointsStoreWidget.value).negative;
281
+ this.updateData();
282
+ }
283
+ this.bboxStoreWidget.callback = () => {
284
+ this.bbox = JSON.parse(bboxStoreWidget.value)
285
+ this.updateData();
286
+ }
287
+
288
+ this.width = this.widthWidget.value;
289
+ this.height = this.heightWidget.value;
290
+ var i = 3;
291
+ this.points = [];
292
+ this.neg_points = [];
293
+ this.bbox = [{}];
294
+ var drawing = false;
295
+
296
+ // Initialize or reset points array
297
+ if (!reset && this.pointsStoreWidget.value != "") {
298
+ this.points = JSON.parse(this.pointsStoreWidget.value).positive;
299
+ this.neg_points = JSON.parse(this.pointsStoreWidget.value).negative;
300
+ this.bbox = JSON.parse(this.bboxStoreWidget.value);
301
+ console.log(this.bbox)
302
+ } else {
303
+ this.points = [
304
+ {
305
+ x: this.width / 2, // Middle point horizontally centered
306
+ y: this.height / 2 // Middle point vertically centered
307
+ }
308
+ ];
309
+ this.neg_points = [
310
+ {
311
+ x: 0, // Middle point horizontally centered
312
+ y: 0 // Middle point vertically centered
313
+ }
314
+ ];
315
+ const combinedPoints = {
316
+ positive: this.points,
317
+ negative: this.neg_points,
318
+ };
319
+ this.pointsStoreWidget.value = JSON.stringify(combinedPoints);
320
+ this.bboxStoreWidget.value = JSON.stringify(this.bbox);
321
+ }
322
+
323
+ //create main canvas panel
324
+ this.vis = new pv.Panel()
325
+ .width(this.width)
326
+ .height(this.height)
327
+ .fillStyle("#222")
328
+ .strokeStyle("gray")
329
+ .lineWidth(2)
330
+ .antialias(false)
331
+ .margin(10)
332
+ .event("mousedown", function () {
333
+ if (pv.event.shiftKey && pv.event.button === 2) { // Use pv.event to access the event object
334
+ let scaledMouse = {
335
+ x: this.mouse().x / app.canvas.ds.scale,
336
+ y: this.mouse().y / app.canvas.ds.scale
337
+ };
338
+ i = self.neg_points.push(scaledMouse) - 1;
339
+ self.updateData();
340
+ return this;
341
+ }
342
+ else if (pv.event.shiftKey) {
343
+ let scaledMouse = {
344
+ x: this.mouse().x / app.canvas.ds.scale,
345
+ y: this.mouse().y / app.canvas.ds.scale
346
+ };
347
+ i = self.points.push(scaledMouse) - 1;
348
+ self.updateData();
349
+ return this;
350
+ }
351
+ else if (pv.event.ctrlKey) {
352
+ console.log("start drawing at " + this.mouse().x / app.canvas.ds.scale + ", " + this.mouse().y / app.canvas.ds.scale);
353
+ drawing = true;
354
+ self.bbox[0].startX = this.mouse().x / app.canvas.ds.scale;
355
+ self.bbox[0].startY = this.mouse().y / app.canvas.ds.scale;
356
+ }
357
+ else if (pv.event.button === 2) {
358
+ self.node.contextMenu.style.display = 'block';
359
+ self.node.contextMenu.style.left = `${pv.event.clientX}px`;
360
+ self.node.contextMenu.style.top = `${pv.event.clientY}px`;
361
+ }
362
+ })
363
+ .event("mousemove", function () {
364
+ if (drawing) {
365
+ self.bbox[0].endX = this.mouse().x / app.canvas.ds.scale;
366
+ self.bbox[0].endY = this.mouse().y / app.canvas.ds.scale;
367
+ self.vis.render();
368
+ }
369
+ })
370
+ .event("mouseup", function () {
371
+ console.log("end drawing at " + this.mouse().x / app.canvas.ds.scale + ", " + this.mouse().y / app.canvas.ds.scale);
372
+ drawing = false;
373
+ self.updateData();
374
+ });
375
+
376
+ this.backgroundImage = this.vis.add(pv.Image).visible(false)
377
+
378
+ //create bounding box
379
+ this.bounding_box = this.vis.add(pv.Area)
380
+ .data(function () {
381
+ if (drawing || (self.bbox && self.bbox[0] && Object.keys(self.bbox[0]).length > 0)) {
382
+ return [self.bbox[0].startX, self.bbox[0].endX];
383
+ } else {
384
+ return [];
385
+ }
386
+ })
387
+ .bottom(function () {return self.height - Math.max(self.bbox[0].startY, self.bbox[0].endY); })
388
+ .left(function (d) {return d; })
389
+ .height(function () {return Math.abs(self.bbox[0].startY - self.bbox[0].endY);})
390
+ .fillStyle("rgba(70, 130, 180, 0.5)")
391
+ .strokeStyle("steelblue")
392
+ .visible(function () {return drawing || Object.keys(self.bbox[0]).length > 0; })
393
+ .add(pv.Dot)
394
+ .visible(function () {return drawing || Object.keys(self.bbox[0]).length > 0; })
395
+ .data(() => {
396
+ if (self.bbox && Object.keys(self.bbox[0]).length > 0) {
397
+ return [{
398
+ x: self.bbox[0].endX,
399
+ y: self.bbox[0].endY
400
+ }];
401
+ } else {
402
+ return [];
403
+ }
404
+ })
405
+ .left(d => d.x)
406
+ .top(d => d.y)
407
+ .radius(Math.log(Math.min(self.width, self.height)) * 1)
408
+ .shape("square")
409
+ .cursor("move")
410
+ .strokeStyle("steelblue")
411
+ .lineWidth(2)
412
+ .fillStyle(function () { return "rgba(100, 100, 100, 0.6)"; })
413
+ .event("mousedown", pv.Behavior.drag())
414
+ .event("drag", function () {
415
+ let adjustedX = this.mouse().x / app.canvas.ds.scale; // Adjust the new position by the inverse of the scale factor
416
+ let adjustedY = this.mouse().y / app.canvas.ds.scale;
417
+
418
+ // Adjust the new position if it would place the dot outside the bounds of the vis.Panel
419
+ adjustedX = Math.max(0, Math.min(self.vis.width(), adjustedX));
420
+ adjustedY = Math.max(0, Math.min(self.vis.height(), adjustedY));
421
+ self.bbox[0].endX = this.mouse().x / app.canvas.ds.scale;
422
+ self.bbox[0].endY = this.mouse().y / app.canvas.ds.scale;
423
+ self.vis.render();
424
+ })
425
+ .event("dragend", function () {
426
+ self.updateData();
427
+ });
428
+
429
+ //create positive points
430
+ this.vis.add(pv.Dot)
431
+ .data(() => this.points)
432
+ .left(d => d.x)
433
+ .top(d => d.y)
434
+ .radius(Math.log(Math.min(self.width, self.height)) * 4)
435
+ .shape("circle")
436
+ .cursor("move")
437
+ .strokeStyle(function () { return i == this.index ? "#07f907" : "#139613"; })
438
+ .lineWidth(4)
439
+ .fillStyle(function () { return "rgba(100, 100, 100, 0.6)"; })
440
+ .event("mousedown", pv.Behavior.drag())
441
+ .event("dragstart", function () {
442
+ i = this.index;
443
+ })
444
+ .event("dragend", function () {
445
+ if (pv.event.button === 2 && i !== 0 && i !== self.points.length - 1) {
446
+ this.index = i;
447
+ self.points.splice(i--, 1);
448
+ }
449
+ self.updateData();
450
+
451
+ })
452
+ .event("drag", function () {
453
+ let adjustedX = this.mouse().x / app.canvas.ds.scale; // Adjust the new X position by the inverse of the scale factor
454
+ let adjustedY = this.mouse().y / app.canvas.ds.scale; // Adjust the new Y position by the inverse of the scale factor
455
+ // Determine the bounds of the vis.Panel
456
+ const panelWidth = self.vis.width();
457
+ const panelHeight = self.vis.height();
458
+
459
+ // Adjust the new position if it would place the dot outside the bounds of the vis.Panel
460
+ adjustedX = Math.max(0, Math.min(panelWidth, adjustedX));
461
+ adjustedY = Math.max(0, Math.min(panelHeight, adjustedY));
462
+ self.points[this.index] = { x: adjustedX, y: adjustedY }; // Update the point's position
463
+ self.vis.render(); // Re-render the visualization to reflect the new position
464
+ })
465
+
466
+ .anchor("center")
467
+ .add(pv.Label)
468
+ .left(d => d.x < this.width / 2 ? d.x + 30 : d.x - 35) // Shift label to right if on left half, otherwise shift to left
469
+ .top(d => d.y < this.height / 2 ? d.y + 25 : d.y - 25) // Shift label down if on top half, otherwise shift up
470
+ .font(25 + "px sans-serif")
471
+ .text(d => {return this.points.indexOf(d); })
472
+ .textStyle("#139613")
473
+ .textShadow("2px 2px 2px black")
474
+ .add(pv.Dot) // Add smaller point in the center
475
+ .data(() => this.points)
476
+ .left(d => d.x)
477
+ .top(d => d.y)
478
+ .radius(2) // Smaller radius for the center point
479
+ .shape("circle")
480
+ .fillStyle("red") // Color for the center point
481
+ .lineWidth(1); // Stroke thickness for the center point
482
+
483
+ //create negative points
484
+ this.vis.add(pv.Dot)
485
+ .data(() => this.neg_points)
486
+ .left(d => d.x)
487
+ .top(d => d.y)
488
+ .radius(Math.log(Math.min(self.width, self.height)) * 4)
489
+ .shape("circle")
490
+ .cursor("move")
491
+ .strokeStyle(function () { return i == this.index ? "#f91111" : "#891616"; })
492
+ .lineWidth(4)
493
+ .fillStyle(function () { return "rgba(100, 100, 100, 0.6)"; })
494
+ .event("mousedown", pv.Behavior.drag())
495
+ .event("dragstart", function () {
496
+ i = this.index;
497
+ })
498
+ .event("dragend", function () {
499
+ if (pv.event.button === 2 && i !== 0 && i !== self.neg_points.length - 1) {
500
+ this.index = i;
501
+ self.neg_points.splice(i--, 1);
502
+ }
503
+ self.updateData();
504
+
505
+ })
506
+ .event("drag", function () {
507
+ let adjustedX = this.mouse().x / app.canvas.ds.scale; // Adjust the new X position by the inverse of the scale factor
508
+ let adjustedY = this.mouse().y / app.canvas.ds.scale; // Adjust the new Y position by the inverse of the scale factor
509
+ // Determine the bounds of the vis.Panel
510
+ const panelWidth = self.vis.width();
511
+ const panelHeight = self.vis.height();
512
+
513
+ // Adjust the new position if it would place the dot outside the bounds of the vis.Panel
514
+ adjustedX = Math.max(0, Math.min(panelWidth, adjustedX));
515
+ adjustedY = Math.max(0, Math.min(panelHeight, adjustedY));
516
+ self.neg_points[this.index] = { x: adjustedX, y: adjustedY }; // Update the point's position
517
+ self.vis.render(); // Re-render the visualization to reflect the new position
518
+ })
519
+ .anchor("center")
520
+ .add(pv.Label)
521
+ .left(d => d.x < this.width / 2 ? d.x + 30 : d.x - 35) // Shift label to right if on left half, otherwise shift to left
522
+ .top(d => d.y < this.height / 2 ? d.y + 25 : d.y - 25) // Shift label down if on top half, otherwise shift up
523
+ .font(25 + "px sans-serif")
524
+ .text(d => {return this.neg_points.indexOf(d); })
525
+ .textStyle("red")
526
+ .textShadow("2px 2px 2px black")
527
+ .add(pv.Dot) // Add smaller point in the center
528
+ .data(() => this.neg_points)
529
+ .left(d => d.x)
530
+ .top(d => d.y)
531
+ .radius(2) // Smaller radius for the center point
532
+ .shape("circle")
533
+ .fillStyle("red") // Color for the center point
534
+ .lineWidth(1); // Stroke thickness for the center point
535
+
536
+ if (this.points.length != 0) {
537
+ this.vis.render();
538
+ }
539
+
540
+ var svgElement = this.vis.canvas();
541
+ svgElement.style['zIndex'] = "2"
542
+ svgElement.style['position'] = "relative"
543
+ this.node.pointsEditor.element.appendChild(svgElement);
544
+
545
+ if (this.width > 256) {
546
+ this.node.setSize([this.width + 45, this.node.size[1]]);
547
+ }
548
+ this.node.setSize([this.node.size[0], this.height + 300]);
549
+ this.updateData();
550
+ this.refreshBackgroundImage();
551
+
552
+ }//end constructor
553
+
554
+ updateData = () => {
555
+ if (this.points.length == 0) {
556
+ console.log("no points")
557
+ return
558
+ }
559
+ const combinedPoints = {
560
+ positive: this.points,
561
+ negative: this.neg_points,
562
+ };
563
+ this.pointsStoreWidget.value = JSON.stringify(combinedPoints);
564
+ this.pos_coordWidget.value = JSON.stringify(this.points);
565
+ this.neg_coordWidget.value = JSON.stringify(this.neg_points);
566
+
567
+ if (this.bbox.length != 0) {
568
+ let bboxString = JSON.stringify(this.bbox);
569
+ this.bboxStoreWidget.value = bboxString;
570
+ this.bboxWidget.value = bboxString;
571
+ }
572
+
573
+ this.vis.render();
574
+ };
575
+
576
+ handleImageLoad = (img, file, base64String) => {
577
+ console.log(img.width, img.height); // Access width and height here
578
+ this.widthWidget.value = img.width;
579
+ this.heightWidget.value = img.height;
580
+
581
+ if (img.width != this.vis.width() || img.height != this.vis.height()) {
582
+ if (img.width > 256) {
583
+ this.node.setSize([img.width + 45, this.node.size[1]]);
584
+ }
585
+ this.node.setSize([this.node.size[0], img.height + 300]);
586
+ this.vis.width(img.width);
587
+ this.vis.height(img.height);
588
+ this.height = img.height;
589
+ this.width = img.width;
590
+ this.updateData();
591
+ }
592
+ this.backgroundImage.url(file ? URL.createObjectURL(file) : `data:${this.node.properties.imgData.type};base64,${base64String}`).visible(true).root.render();
593
+ };
594
+
595
+ processImage = (img, file) => {
596
+ const canvas = document.createElement('canvas');
597
+ const ctx = canvas.getContext('2d');
598
+
599
+ const maxWidth = 800; // maximum width
600
+ const maxHeight = 600; // maximum height
601
+ let width = img.width;
602
+ let height = img.height;
603
+
604
+ // Calculate the new dimensions while preserving the aspect ratio
605
+ if (width > height) {
606
+ if (width > maxWidth) {
607
+ height *= maxWidth / width;
608
+ width = maxWidth;
609
+ }
610
+ } else {
611
+ if (height > maxHeight) {
612
+ width *= maxHeight / height;
613
+ height = maxHeight;
614
+ }
615
+ }
616
+
617
+ canvas.width = width;
618
+ canvas.height = height;
619
+ ctx.drawImage(img, 0, 0, width, height);
620
+
621
+ // Get the compressed image data as a Base64 string
622
+ const base64String = canvas.toDataURL('image/jpeg', 0.5).replace('data:', '').replace(/^.+,/, ''); // 0.5 is the quality from 0 to 1
623
+
624
+ this.node.properties.imgData = {
625
+ name: file.name,
626
+ lastModified: file.lastModified,
627
+ size: file.size,
628
+ type: file.type,
629
+ base64: base64String
630
+ };
631
+ handleImageLoad(img, file, base64String);
632
+ };
633
+
634
+ handleImageFile = (file) => {
635
+ const reader = new FileReader();
636
+ reader.onloadend = () => {
637
+ const img = new Image();
638
+ img.src = reader.result;
639
+ img.onload = () => processImage(img, file);
640
+ };
641
+ reader.readAsDataURL(file);
642
+
643
+ const imageUrl = URL.createObjectURL(file);
644
+ const img = new Image();
645
+ img.src = imageUrl;
646
+ img.onload = () => this.handleImageLoad(img, file, null);
647
+ };
648
+
649
+ refreshBackgroundImage = () => {
650
+ if (this.node.properties.imgData && this.node.properties.imgData.base64) {
651
+ const base64String = this.node.properties.imgData.base64;
652
+ const imageUrl = `data:${this.node.properties.imgData.type};base64,${base64String}`;
653
+ const img = new Image();
654
+ img.src = imageUrl;
655
+ img.onload = () => this.handleImageLoad(img, null, base64String);
656
+ }
657
+ };
658
+
659
+ createContextMenu = () => {
660
+ self = this;
661
+ document.addEventListener('contextmenu', function (e) {
662
+ e.preventDefault();
663
+ });
664
+
665
+ document.addEventListener('click', function (e) {
666
+ if (!self.node.contextMenu.contains(e.target)) {
667
+ self.node.contextMenu.style.display = 'none';
668
+ }
669
+ });
670
+
671
+ this.node.menuItems.forEach((menuItem, index) => {
672
+ self = this;
673
+ menuItem.addEventListener('click', function (e) {
674
+ e.preventDefault();
675
+ switch (index) {
676
+ case 0:
677
+ // Create file input element
678
+ const fileInput = document.createElement('input');
679
+ fileInput.type = 'file';
680
+ fileInput.accept = 'image/*'; // Accept only image files
681
+
682
+ // Listen for file selection
683
+ fileInput.addEventListener('change', function (event) {
684
+ const file = event.target.files[0]; // Get the selected file
685
+
686
+ if (file) {
687
+ const imageUrl = URL.createObjectURL(file);
688
+ let img = new Image();
689
+ img.src = imageUrl;
690
+ img.onload = () => self.handleImageLoad(img, file, null);
691
+ }
692
+ });
693
+
694
+ fileInput.click();
695
+
696
+ self.node.contextMenu.style.display = 'none';
697
+ break;
698
+ case 1:
699
+ self.backgroundImage.visible(false).root.render();
700
+ self.node.properties.imgData = null;
701
+ self.node.contextMenu.style.display = 'none';
702
+ break;
703
+ }
704
+ });
705
+ });
706
+ }//end createContextMenu
707
+ }//end class
708
+
709
+
710
+ //from melmass
711
+ export function hideWidgetForGood(node, widget, suffix = '') {
712
+ widget.origType = widget.type
713
+ widget.origComputeSize = widget.computeSize
714
+ widget.origSerializeValue = widget.serializeValue
715
+ widget.computeSize = () => [0, -4] // -4 is due to the gap litegraph adds between widgets automatically
716
+ widget.type = "converted-widget" + suffix
717
+ // widget.serializeValue = () => {
718
+ // // Prevent serializing the widget if we have no input linked
719
+ // const w = node.inputs?.find((i) => i.widget?.name === widget.name);
720
+ // if (w?.link == null) {
721
+ // return undefined;
722
+ // }
723
+ // return widget.origSerializeValue ? widget.origSerializeValue() : widget.value;
724
+ // };
725
+
726
+ // Hide any linked widgets, e.g. seed+seedControl
727
+ if (widget.linkedWidgets) {
728
+ for (const w of widget.linkedWidgets) {
729
+ hideWidgetForGood(node, w, ':' + widget.name)
730
+ }
731
+ }
732
+ }