aliensmn commited on
Commit
eb6c4d6
·
verified ·
1 Parent(s): c24e2d1

Mirror from https://github.com/kijai/ComfyUI-KJNodes

Browse files
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. .github/FUNDING.yml +2 -0
  3. .github/workflows/publish.yml +25 -0
  4. .gitignore +11 -0
  5. LICENSE +674 -0
  6. README.md +65 -0
  7. __init__.py +250 -0
  8. custom_dimensions_example.json +22 -0
  9. docs/images/2024-04-03_20_49_29-ComfyUI.png +3 -0
  10. docs/images/319121566-05f66385-7568-4b1f-8bbc-11053660b02f.png +0 -0
  11. docs/images/319121636-706b5081-9120-4a29-bd76-901691ada688.png +0 -0
  12. example_workflows/leapfusion_hunyuuanvideo_i2v_native_testing.json +1188 -0
  13. fonts/FreeMono.ttf +3 -0
  14. fonts/FreeMonoBoldOblique.otf +3 -0
  15. fonts/TTNorms-Black.otf +3 -0
  16. intrinsic_loras/intrinsic_lora_sd15_albedo.safetensors +3 -0
  17. intrinsic_loras/intrinsic_lora_sd15_depth.safetensors +3 -0
  18. intrinsic_loras/intrinsic_lora_sd15_normal.safetensors +3 -0
  19. intrinsic_loras/intrinsic_lora_sd15_shading.safetensors +3 -0
  20. intrinsic_loras/intrinsic_loras.txt +4 -0
  21. kjweb_async/marked.min.js +6 -0
  22. kjweb_async/protovis.min.js +0 -0
  23. kjweb_async/purify.min.js +3 -0
  24. kjweb_async/svg-path-properties.min.js +2 -0
  25. nodes/audioscheduler_nodes.py +251 -0
  26. nodes/batchcrop_nodes.py +768 -0
  27. nodes/curve_nodes.py +1636 -0
  28. nodes/image_nodes.py +0 -0
  29. nodes/intrinsic_lora_nodes.py +115 -0
  30. nodes/lora_nodes.py +568 -0
  31. nodes/mask_nodes.py +1669 -0
  32. nodes/model_optimization_nodes.py +0 -0
  33. nodes/nodes.py +0 -0
  34. pyproject.toml +15 -0
  35. requirements.txt +7 -0
  36. utility/fluid.py +67 -0
  37. utility/magictex.py +95 -0
  38. utility/numerical.py +25 -0
  39. utility/utility.py +39 -0
  40. web/green.png +0 -0
  41. web/js/appearance.js +23 -0
  42. web/js/browserstatus.js +55 -0
  43. web/js/contextmenu.js +147 -0
  44. web/js/fast_preview.js +95 -0
  45. web/js/help_popup.js +326 -0
  46. web/js/jsnodes.js +413 -0
  47. web/js/point_editor.js +734 -0
  48. web/js/setgetnodes.js +565 -0
  49. web/js/spline_editor.js +1379 -0
  50. web/red.png +0 -0
.gitattributes CHANGED
@@ -33,3 +33,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ docs/images/2024-04-03_20_49_29-ComfyUI.png filter=lfs diff=lfs merge=lfs -text
37
+ fonts/FreeMono.ttf filter=lfs diff=lfs merge=lfs -text
38
+ fonts/FreeMonoBoldOblique.otf filter=lfs diff=lfs merge=lfs -text
39
+ fonts/TTNorms-Black.otf filter=lfs diff=lfs merge=lfs -text
.github/FUNDING.yml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ github: [kijai]
2
+ custom: ["https://www.paypal.me/kijaidesign"]
.github/workflows/publish.yml ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Publish to Comfy registry
2
+ on:
3
+ workflow_dispatch:
4
+ push:
5
+ branches:
6
+ - main
7
+ paths:
8
+ - "pyproject.toml"
9
+
10
+ permissions:
11
+ issues: write
12
+
13
+ jobs:
14
+ publish-node:
15
+ name: Publish Custom Node to registry
16
+ runs-on: ubuntu-latest
17
+ if: ${{ github.repository_owner == 'kijai' }}
18
+ steps:
19
+ - name: Check out code
20
+ uses: actions/checkout@v4
21
+ - name: Publish Custom Node
22
+ uses: Comfy-Org/publish-node-action@v1
23
+ with:
24
+ ## Add your own personal access token to your Github Repository secrets and reference it here.
25
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
.gitignore ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ /venv
3
+ *.code-workspace
4
+ .history
5
+ .vscode
6
+ *.ckpt
7
+ *.pth
8
+ types
9
+ models
10
+ jsconfig.json
11
+ custom_dimensions.json
LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
README.md ADDED
@@ -0,0 +1,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 length 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.
__init__.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from .nodes.model_optimization_nodes import *
9
+ from .nodes.lora_nodes import *
10
+ NODE_CONFIG = {
11
+ #constants
12
+ "BOOLConstant": {"class": BOOLConstant, "name": "BOOL Constant"},
13
+ "INTConstant": {"class": INTConstant, "name": "INT Constant"},
14
+ "FloatConstant": {"class": FloatConstant, "name": "Float Constant"},
15
+ "StringConstant": {"class": StringConstant, "name": "String Constant"},
16
+ "StringConstantMultiline": {"class": StringConstantMultiline, "name": "String Constant Multiline"},
17
+ #conditioning
18
+ "ConditioningMultiCombine": {"class": ConditioningMultiCombine, "name": "Conditioning Multi Combine"},
19
+ "ConditioningSetMaskAndCombine": {"class": ConditioningSetMaskAndCombine, "name": "ConditioningSetMaskAndCombine"},
20
+ "ConditioningSetMaskAndCombine3": {"class": ConditioningSetMaskAndCombine3, "name": "ConditioningSetMaskAndCombine3"},
21
+ "ConditioningSetMaskAndCombine4": {"class": ConditioningSetMaskAndCombine4, "name": "ConditioningSetMaskAndCombine4"},
22
+ "ConditioningSetMaskAndCombine5": {"class": ConditioningSetMaskAndCombine5, "name": "ConditioningSetMaskAndCombine5"},
23
+ "CondPassThrough": {"class": CondPassThrough},
24
+ #masking
25
+ "DrawMaskOnImage": {"class": DrawMaskOnImage, "name": "Draw Mask On Image"},
26
+ "DownloadAndLoadCLIPSeg": {"class": DownloadAndLoadCLIPSeg, "name": "(Down)load CLIPSeg"},
27
+ "BatchCLIPSeg": {"class": BatchCLIPSeg, "name": "Batch CLIPSeg"},
28
+ "BlockifyMask": {"class": BlockifyMask, "name": "Blockify Mask"},
29
+ "ColorToMask": {"class": ColorToMask, "name": "Color To Mask"},
30
+ "CreateGradientMask": {"class": CreateGradientMask, "name": "Create Gradient Mask"},
31
+ "CreateTextMask": {"class": CreateTextMask, "name": "Create Text Mask"},
32
+ "CreateAudioMask": {"class": CreateAudioMask, "name": "Create Audio Mask"},
33
+ "CreateFadeMask": {"class": CreateFadeMask, "name": "Create Fade Mask"},
34
+ "CreateFadeMaskAdvanced": {"class": CreateFadeMaskAdvanced, "name": "Create Fade Mask Advanced"},
35
+ "CreateFluidMask": {"class": CreateFluidMask, "name": "Create Fluid Mask"},
36
+ "CreateShapeMask": {"class": CreateShapeMask, "name": "Create Shape Mask"},
37
+ "CreateVoronoiMask": {"class": CreateVoronoiMask, "name": "Create Voronoi Mask"},
38
+ "CreateMagicMask": {"class": CreateMagicMask, "name": "Create Magic Mask"},
39
+ "GetMaskSizeAndCount": {"class": GetMaskSizeAndCount, "name": "Get Mask Size & Count"},
40
+ "GrowMaskWithBlur": {"class": GrowMaskWithBlur, "name": "Grow Mask With Blur"},
41
+ "MaskBatchMulti": {"class": MaskBatchMulti, "name": "Mask Batch Multi"},
42
+ "OffsetMask": {"class": OffsetMask, "name": "Offset Mask"},
43
+ "RemapMaskRange": {"class": RemapMaskRange, "name": "Remap Mask Range"},
44
+ "ResizeMask": {"class": ResizeMask, "name": "Resize Mask"},
45
+ "RoundMask": {"class": RoundMask, "name": "Round Mask"},
46
+ "SeparateMasks": {"class": SeparateMasks, "name": "Separate Masks"},
47
+ "ConsolidateMasksKJ": {"class": ConsolidateMasksKJ, "name": "Consolidate Masks"},
48
+ #images
49
+ "AddLabel": {"class": AddLabel, "name": "Add Label"},
50
+ "ColorMatch": {"class": ColorMatch, "name": "Color Match"},
51
+ "ImageTensorList": {"class": ImageTensorList, "name": "Image Tensor List"},
52
+ "CrossFadeImages": {"class": CrossFadeImages, "name": "Cross Fade Images"},
53
+ "CrossFadeImagesMulti": {"class": CrossFadeImagesMulti, "name": "Cross Fade Images Multi"},
54
+ "GetImagesFromBatchIndexed": {"class": GetImagesFromBatchIndexed, "name": "Get Images From Batch Indexed"},
55
+ "GetImageRangeFromBatch": {"class": GetImageRangeFromBatch, "name": "Get Image or Mask Range From Batch"},
56
+ "GetLatentRangeFromBatch": {"class": GetLatentRangeFromBatch, "name": "Get Latent Range From Batch"},
57
+ "GetLatentSizeAndCount": {"class": GetLatentSizeAndCount, "name": "Get Latent Size & Count"},
58
+ "GetImageSizeAndCount": {"class": GetImageSizeAndCount, "name": "Get Image Size & Count"},
59
+ "FastPreview": {"class": FastPreview, "name": "Fast Preview"},
60
+ "ImageBatchFilter": {"class": ImageBatchFilter, "name": "Image Batch Filter"},
61
+ "ImageAndMaskPreview": {"class": ImageAndMaskPreview},
62
+ "ImageAddMulti": {"class": ImageAddMulti, "name": "Image Add Multi"},
63
+ "ImageBatchJoinWithTransition": {"class": ImageBatchJoinWithTransition, "name": "Image Batch Join With Transition"},
64
+ "ImageBatchMulti": {"class": ImageBatchMulti, "name": "Image Batch Multi"},
65
+ "ImageBatchRepeatInterleaving": {"class": ImageBatchRepeatInterleaving},
66
+ "ImageBatchTestPattern": {"class": ImageBatchTestPattern, "name": "Image Batch Test Pattern"},
67
+ "ImageConcanate": {"class": ImageConcanate, "name": "Image Concatenate"},
68
+ "ImageConcatFromBatch": {"class": ImageConcatFromBatch, "name": "Image Concatenate From Batch"},
69
+ "ImageConcatMulti": {"class": ImageConcatMulti, "name": "Image Concatenate Multi"},
70
+ "ImageCropByMask": {"class": ImageCropByMask, "name": "Image Crop By Mask"},
71
+ "ImageCropByMaskAndResize": {"class": ImageCropByMaskAndResize, "name": "Image Crop By Mask And Resize"},
72
+ "ImageCropByMaskBatch": {"class": ImageCropByMaskBatch, "name": "Image Crop By Mask Batch"},
73
+ "ImageUncropByMask": {"class": ImageUncropByMask, "name": "Image Uncrop By Mask"},
74
+ "ImageGrabPIL": {"class": ImageGrabPIL, "name": "Image Grab PIL"},
75
+ "ImageGridComposite2x2": {"class": ImageGridComposite2x2, "name": "Image Grid Composite 2x2"},
76
+ "ImageGridComposite3x3": {"class": ImageGridComposite3x3, "name": "Image Grid Composite 3x3"},
77
+ "ImageGridtoBatch": {"class": ImageGridtoBatch, "name": "Image Grid To Batch"},
78
+ "ImageNoiseAugmentation": {"class": ImageNoiseAugmentation, "name": "Image Noise Augmentation"},
79
+ "ImageNormalize_Neg1_To_1": {"class": ImageNormalize_Neg1_To_1, "name": "Image Normalize -1 to 1"},
80
+ "ImagePass": {"class": ImagePass},
81
+ "ImagePadKJ": {"class": ImagePadKJ, "name": "ImagePad KJ"},
82
+ "ImagePadForOutpaintMasked": {"class": ImagePadForOutpaintMasked, "name": "Image Pad For Outpaint Masked"},
83
+ "ImagePadForOutpaintTargetSize": {"class": ImagePadForOutpaintTargetSize, "name": "Image Pad For Outpaint Target Size"},
84
+ "ImagePrepForICLora": {"class": ImagePrepForICLora, "name": "Image Prep For ICLora"},
85
+ "ImageResizeKJ": {"class": ImageResizeKJ, "name": "Resize Image (deprecated)"},
86
+ "ImageResizeKJv2": {"class": ImageResizeKJv2, "name": "Resize Image v2"},
87
+ "ImageUpscaleWithModelBatched": {"class": ImageUpscaleWithModelBatched, "name": "Image Upscale With Model Batched"},
88
+ "InsertImagesToBatchIndexed": {"class": InsertImagesToBatchIndexed, "name": "Insert Images To Batch Indexed"},
89
+ "InsertLatentToIndexed": {"class": InsertLatentToIndex, "name": "Insert Latent To Index"},
90
+ "LoadAndResizeImage": {"class": LoadAndResizeImage, "name": "Load & Resize Image"},
91
+ "LoadImagesFromFolderKJ": {"class": LoadImagesFromFolderKJ, "name": "Load Images From Folder (KJ)"},
92
+ "LoadVideosFromFolder": {"class": LoadVideosFromFolder, "name": "Load Videos From Folder"},
93
+ "MergeImageChannels": {"class": MergeImageChannels, "name": "Merge Image Channels"},
94
+ "PadImageBatchInterleaved": {"class": PadImageBatchInterleaved, "name": "Pad Image Batch Interleaved"},
95
+ "PreviewAnimation": {"class": PreviewAnimation, "name": "Preview Animation"},
96
+ "RemapImageRange": {"class": RemapImageRange, "name": "Remap Image Range"},
97
+ "ReverseImageBatch": {"class": ReverseImageBatch, "name": "Reverse Image Batch"},
98
+ "ReplaceImagesInBatch": {"class": ReplaceImagesInBatch, "name": "Replace Images In Batch"},
99
+ "SaveImageWithAlpha": {"class": SaveImageWithAlpha, "name": "Save Image With Alpha"},
100
+ "SaveImageKJ": {"class": SaveImageKJ, "name": "Save Image KJ"},
101
+ "ShuffleImageBatch": {"class": ShuffleImageBatch, "name": "Shuffle Image Batch"},
102
+ "SplitImageChannels": {"class": SplitImageChannels, "name": "Split Image Channels"},
103
+ "TransitionImagesMulti": {"class": TransitionImagesMulti, "name": "Transition Images Multi"},
104
+ "TransitionImagesInBatch": {"class": TransitionImagesInBatch, "name": "Transition Images In Batch"},
105
+ #batch cropping
106
+ "BatchCropFromMask": {"class": BatchCropFromMask, "name": "Batch Crop From Mask"},
107
+ "BatchCropFromMaskAdvanced": {"class": BatchCropFromMaskAdvanced, "name": "Batch Crop From Mask Advanced"},
108
+ "FilterZeroMasksAndCorrespondingImages": {"class": FilterZeroMasksAndCorrespondingImages},
109
+ "InsertImageBatchByIndexes": {"class": InsertImageBatchByIndexes, "name": "Insert Image Batch By Indexes"},
110
+ "BatchUncrop": {"class": BatchUncrop, "name": "Batch Uncrop"},
111
+ "BatchUncropAdvanced": {"class": BatchUncropAdvanced, "name": "Batch Uncrop Advanced"},
112
+ "SplitBboxes": {"class": SplitBboxes, "name": "Split Bboxes"},
113
+ "BboxToInt": {"class": BboxToInt, "name": "Bbox To Int"},
114
+ "BboxVisualize": {"class": BboxVisualize, "name": "Bbox Visualize"},
115
+ #noise
116
+ "GenerateNoise": {"class": GenerateNoise, "name": "Generate Noise"},
117
+ "FlipSigmasAdjusted": {"class": FlipSigmasAdjusted, "name": "Flip Sigmas Adjusted"},
118
+ "InjectNoiseToLatent": {"class": InjectNoiseToLatent, "name": "Inject Noise To Latent"},
119
+ "CustomSigmas": {"class": CustomSigmas, "name": "Custom Sigmas"},
120
+ #utility
121
+ "StringToFloatList": {"class": StringToFloatList, "name": "String to Float List"},
122
+ "WidgetToString": {"class": WidgetToString, "name": "Widget To String"},
123
+ "SaveStringKJ": {"class": SaveStringKJ, "name": "Save String KJ"},
124
+ "DummyOut": {"class": DummyOut, "name": "Dummy Out"},
125
+ "GetLatentsFromBatchIndexed": {"class": GetLatentsFromBatchIndexed, "name": "Get Latents From Batch Indexed"},
126
+ "ScaleBatchPromptSchedule": {"class": ScaleBatchPromptSchedule, "name": "Scale Batch Prompt Schedule"},
127
+ "CameraPoseVisualizer": {"class": CameraPoseVisualizer, "name": "Camera Pose Visualizer"},
128
+ "AppendStringsToList": {"class": AppendStringsToList, "name": "Append Strings To List"},
129
+ "JoinStrings": {"class": JoinStrings, "name": "Join Strings"},
130
+ "JoinStringMulti": {"class": JoinStringMulti, "name": "Join String Multi"},
131
+ "SomethingToString": {"class": SomethingToString, "name": "Something To String"},
132
+ "Sleep": {"class": Sleep, "name": "Sleep"},
133
+ "VRAM_Debug": {"class": VRAM_Debug, "name": "VRAM Debug"},
134
+ "SomethingToString": {"class": SomethingToString, "name": "Something To String"},
135
+ "EmptyLatentImagePresets": {"class": EmptyLatentImagePresets, "name": "Empty Latent Image Presets"},
136
+ "EmptyLatentImageCustomPresets": {"class": EmptyLatentImageCustomPresets, "name": "Empty Latent Image Custom Presets"},
137
+ "ModelPassThrough": {"class": ModelPassThrough, "name": "ModelPass"},
138
+ "ModelSaveKJ": {"class": ModelSaveKJ, "name": "Model Save KJ"},
139
+ "SetShakkerLabsUnionControlNetType": {"class": SetShakkerLabsUnionControlNetType, "name": "Set Shakker Labs Union ControlNet Type"},
140
+ "StyleModelApplyAdvanced": {"class": StyleModelApplyAdvanced, "name": "Style Model Apply Advanced"},
141
+ "DiffusionModelSelector": {"class": DiffusionModelSelector, "name": "Diffusion Model Selector"},
142
+ "LazySwitchKJ": {"class": LazySwitchKJ, "name": "Lazy Switch KJ"},
143
+ #audioscheduler stuff
144
+ "NormalizedAmplitudeToMask": {"class": NormalizedAmplitudeToMask},
145
+ "NormalizedAmplitudeToFloatList": {"class": NormalizedAmplitudeToFloatList},
146
+ "OffsetMaskByNormalizedAmplitude": {"class": OffsetMaskByNormalizedAmplitude},
147
+ "ImageTransformByNormalizedAmplitude": {"class": ImageTransformByNormalizedAmplitude},
148
+ "AudioConcatenate": {"class": AudioConcatenate},
149
+ #curve nodes
150
+ "SplineEditor": {"class": SplineEditor, "name": "Spline Editor"},
151
+ "CreateShapeImageOnPath": {"class": CreateShapeImageOnPath, "name": "Create Shape Image On Path"},
152
+ "CreateShapeMaskOnPath": {"class": CreateShapeMaskOnPath, "name": "Create Shape Mask On Path"},
153
+ "CreateTextOnPath": {"class": CreateTextOnPath, "name": "Create Text On Path"},
154
+ "CreateGradientFromCoords": {"class": CreateGradientFromCoords, "name": "Create Gradient From Coords"},
155
+ "CutAndDragOnPath": {"class": CutAndDragOnPath, "name": "Cut And Drag On Path"},
156
+ "GradientToFloat": {"class": GradientToFloat, "name": "Gradient To Float"},
157
+ "WeightScheduleExtend": {"class": WeightScheduleExtend, "name": "Weight Schedule Extend"},
158
+ "MaskOrImageToWeight": {"class": MaskOrImageToWeight, "name": "Mask Or Image To Weight"},
159
+ "WeightScheduleConvert": {"class": WeightScheduleConvert, "name": "Weight Schedule Convert"},
160
+ "FloatToMask": {"class": FloatToMask, "name": "Float To Mask"},
161
+ "FloatToSigmas": {"class": FloatToSigmas, "name": "Float To Sigmas"},
162
+ "SigmasToFloat": {"class": SigmasToFloat, "name": "Sigmas To Float"},
163
+ "PlotCoordinates": {"class": PlotCoordinates, "name": "Plot Coordinates"},
164
+ "InterpolateCoords": {"class": InterpolateCoords, "name": "Interpolate Coords"},
165
+ "PointsEditor": {"class": PointsEditor, "name": "Points Editor"},
166
+ #experimental
167
+ "SoundReactive": {"class": SoundReactive, "name": "Sound Reactive"},
168
+ "StableZero123_BatchSchedule": {"class": StableZero123_BatchSchedule, "name": "Stable Zero123 Batch Schedule"},
169
+ "SV3D_BatchSchedule": {"class": SV3D_BatchSchedule, "name": "SV3D Batch Schedule"},
170
+ "LoadResAdapterNormalization": {"class": LoadResAdapterNormalization},
171
+ "Superprompt": {"class": Superprompt, "name": "Superprompt"},
172
+ "GLIGENTextBoxApplyBatchCoords": {"class": GLIGENTextBoxApplyBatchCoords},
173
+ "Intrinsic_lora_sampling": {"class": Intrinsic_lora_sampling, "name": "Intrinsic Lora Sampling"},
174
+ "CheckpointPerturbWeights": {"class": CheckpointPerturbWeights, "name": "CheckpointPerturbWeights"},
175
+ "Screencap_mss": {"class": Screencap_mss, "name": "Screencap mss"},
176
+ "WebcamCaptureCV2": {"class": WebcamCaptureCV2, "name": "Webcam Capture CV2"},
177
+ "DifferentialDiffusionAdvanced": {"class": DifferentialDiffusionAdvanced, "name": "Differential Diffusion Advanced"},
178
+ "DiTBlockLoraLoader": {"class": DiTBlockLoraLoader, "name": "DiT Block Lora Loader"},
179
+ "FluxBlockLoraSelect": {"class": FluxBlockLoraSelect, "name": "Flux Block Lora Select"},
180
+ "HunyuanVideoBlockLoraSelect": {"class": HunyuanVideoBlockLoraSelect, "name": "Hunyuan Video Block Lora Select"},
181
+ "Wan21BlockLoraSelect": {"class": Wan21BlockLoraSelect, "name": "Wan21 Block Lora Select"},
182
+ "CustomControlNetWeightsFluxFromList": {"class": CustomControlNetWeightsFluxFromList, "name": "Custom ControlNet Weights Flux From List"},
183
+ "CheckpointLoaderKJ": {"class": CheckpointLoaderKJ, "name": "CheckpointLoaderKJ"},
184
+ "DiffusionModelLoaderKJ": {"class": DiffusionModelLoaderKJ, "name": "Diffusion Model Loader KJ"},
185
+ "TorchCompileModelFluxAdvanced": {"class": TorchCompileModelFluxAdvanced, "name": "TorchCompileModelFluxAdvanced"},
186
+ "TorchCompileModelFluxAdvancedV2": {"class": TorchCompileModelFluxAdvancedV2, "name": "TorchCompileModelFluxAdvancedV2"},
187
+ "TorchCompileModelHyVideo": {"class": TorchCompileModelHyVideo, "name": "TorchCompileModelHyVideo"},
188
+ "TorchCompileVAE": {"class": TorchCompileVAE, "name": "TorchCompileVAE"},
189
+ "TorchCompileControlNet": {"class": TorchCompileControlNet, "name": "TorchCompileControlNet"},
190
+ "PatchModelPatcherOrder": {"class": PatchModelPatcherOrder, "name": "Patch Model Patcher Order"},
191
+ "TorchCompileLTXModel": {"class": TorchCompileLTXModel, "name": "TorchCompileLTXModel"},
192
+ "TorchCompileCosmosModel": {"class": TorchCompileCosmosModel, "name": "TorchCompileCosmosModel"},
193
+ "TorchCompileModelQwenImage": {"class": TorchCompileModelQwenImage, "name": "TorchCompileModelQwenImage"},
194
+ "TorchCompileModelWanVideo": {"class": TorchCompileModelWanVideo, "name": "TorchCompileModelWanVideo"},
195
+ "TorchCompileModelWanVideoV2": {"class": TorchCompileModelWanVideoV2, "name": "TorchCompileModelWanVideoV2"},
196
+ "PathchSageAttentionKJ": {"class": PathchSageAttentionKJ, "name": "Patch Sage Attention KJ"},
197
+ "LeapfusionHunyuanI2VPatcher": {"class": LeapfusionHunyuanI2V, "name": "Leapfusion Hunyuan I2V Patcher"},
198
+ "VAELoaderKJ": {"class": VAELoaderKJ, "name": "VAELoader KJ"},
199
+ "ScheduledCFGGuidance": {"class": ScheduledCFGGuidance, "name": "Scheduled CFG Guidance"},
200
+ "ApplyRifleXRoPE_HunuyanVideo": {"class": ApplyRifleXRoPE_HunuyanVideo, "name": "Apply RifleXRoPE HunuyanVideo"},
201
+ "ApplyRifleXRoPE_WanVideo": {"class": ApplyRifleXRoPE_WanVideo, "name": "Apply RifleXRoPE WanVideo"},
202
+ "WanVideoTeaCacheKJ": {"class": WanVideoTeaCacheKJ, "name": "WanVideo Tea Cache (native)"},
203
+ "WanVideoEnhanceAVideoKJ": {"class": WanVideoEnhanceAVideoKJ, "name": "WanVideo Enhance A Video (native)"},
204
+ "SkipLayerGuidanceWanVideo": {"class": SkipLayerGuidanceWanVideo, "name": "Skip Layer Guidance WanVideo"},
205
+ "TimerNodeKJ": {"class": TimerNodeKJ, "name": "Timer Node KJ"},
206
+ "HunyuanVideoEncodeKeyframesToCond": {"class": HunyuanVideoEncodeKeyframesToCond, "name": "HunyuanVideo Encode Keyframes To Cond"},
207
+ "CFGZeroStarAndInit": {"class": CFGZeroStarAndInit, "name": "CFG Zero Star/Init"},
208
+ "ModelPatchTorchSettings": {"class": ModelPatchTorchSettings, "name": "Model Patch Torch Settings"},
209
+ "WanVideoNAG": {"class": WanVideoNAG, "name": "WanVideoNAG"},
210
+ "GGUFLoaderKJ": {"class": GGUFLoaderKJ, "name": "GGUF Loader KJ"},
211
+
212
+ #instance diffusion
213
+ "CreateInstanceDiffusionTracking": {"class": CreateInstanceDiffusionTracking},
214
+ "AppendInstanceDiffusionTracking": {"class": AppendInstanceDiffusionTracking},
215
+ "DrawInstanceDiffusionTracking": {"class": DrawInstanceDiffusionTracking},
216
+
217
+ #lora
218
+ "LoraExtractKJ": {"class": LoraExtractKJ, "name": "LoraExtractKJ"},
219
+ "LoraReduceRankKJ": {"class": LoraReduceRank, "name": "LoraReduceRank"}
220
+ }
221
+
222
+ def generate_node_mappings(node_config):
223
+ node_class_mappings = {}
224
+ node_display_name_mappings = {}
225
+
226
+ for node_name, node_info in node_config.items():
227
+ node_class_mappings[node_name] = node_info["class"]
228
+ node_display_name_mappings[node_name] = node_info.get("name", node_info["class"].__name__)
229
+
230
+ return node_class_mappings, node_display_name_mappings
231
+
232
+ NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS = generate_node_mappings(NODE_CONFIG)
233
+
234
+ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
235
+
236
+ WEB_DIRECTORY = "./web"
237
+
238
+ from aiohttp import web
239
+ from server import PromptServer
240
+ from pathlib import Path
241
+
242
+ if hasattr(PromptServer, "instance"):
243
+ try:
244
+ # NOTE: we add an extra static path to avoid comfy mechanism
245
+ # that loads every script in web.
246
+ PromptServer.instance.app.add_routes(
247
+ [web.static("/kjweb_async", (Path(__file__).parent.absolute() / "kjweb_async").as_posix())]
248
+ )
249
+ except:
250
+ pass
custom_dimensions_example.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "label": "SD",
4
+ "value": "512x512"
5
+ },
6
+ {
7
+ "label": "HD",
8
+ "value": "768x768"
9
+ },
10
+ {
11
+ "label": "Full HD",
12
+ "value": "1024x1024"
13
+ },
14
+ {
15
+ "label": "4k",
16
+ "value": "2048x2048"
17
+ },
18
+ {
19
+ "label": "SVD",
20
+ "value": "1024x576"
21
+ }
22
+ ]
docs/images/2024-04-03_20_49_29-ComfyUI.png ADDED

Git LFS Details

  • SHA256: 85805d3c7ca8f5d281886ea0ad61f9a78edad755ef8014b3870f91b871807ac9
  • Pointer size: 131 Bytes
  • Size of remote file: 176 kB
docs/images/319121566-05f66385-7568-4b1f-8bbc-11053660b02f.png ADDED
docs/images/319121636-706b5081-9120-4a29-bd76-901691ada688.png ADDED
example_workflows/leapfusion_hunyuuanvideo_i2v_native_testing.json ADDED
@@ -0,0 +1,1188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "last_node_id": 86,
3
+ "last_link_id": 144,
4
+ "nodes": [
5
+ {
6
+ "id": 62,
7
+ "type": "FluxGuidance",
8
+ "pos": [
9
+ -630,
10
+ -170
11
+ ],
12
+ "size": [
13
+ 317.4000244140625,
14
+ 58
15
+ ],
16
+ "flags": {},
17
+ "order": 13,
18
+ "mode": 0,
19
+ "inputs": [
20
+ {
21
+ "name": "conditioning",
22
+ "type": "CONDITIONING",
23
+ "link": 82
24
+ }
25
+ ],
26
+ "outputs": [
27
+ {
28
+ "name": "CONDITIONING",
29
+ "type": "CONDITIONING",
30
+ "links": [
31
+ 83
32
+ ],
33
+ "slot_index": 0
34
+ }
35
+ ],
36
+ "properties": {
37
+ "Node name for S&R": "FluxGuidance"
38
+ },
39
+ "widgets_values": [
40
+ 6
41
+ ]
42
+ },
43
+ {
44
+ "id": 51,
45
+ "type": "KSamplerSelect",
46
+ "pos": [
47
+ -610,
48
+ -480
49
+ ],
50
+ "size": [
51
+ 315,
52
+ 58
53
+ ],
54
+ "flags": {},
55
+ "order": 0,
56
+ "mode": 0,
57
+ "inputs": [],
58
+ "outputs": [
59
+ {
60
+ "name": "SAMPLER",
61
+ "type": "SAMPLER",
62
+ "links": [
63
+ 61
64
+ ]
65
+ }
66
+ ],
67
+ "properties": {
68
+ "Node name for S&R": "KSamplerSelect"
69
+ },
70
+ "widgets_values": [
71
+ "euler"
72
+ ]
73
+ },
74
+ {
75
+ "id": 57,
76
+ "type": "VAEDecodeTiled",
77
+ "pos": [
78
+ -200,
79
+ 90
80
+ ],
81
+ "size": [
82
+ 315,
83
+ 150
84
+ ],
85
+ "flags": {},
86
+ "order": 20,
87
+ "mode": 0,
88
+ "inputs": [
89
+ {
90
+ "name": "samples",
91
+ "type": "LATENT",
92
+ "link": 142
93
+ },
94
+ {
95
+ "name": "vae",
96
+ "type": "VAE",
97
+ "link": 74
98
+ }
99
+ ],
100
+ "outputs": [
101
+ {
102
+ "name": "IMAGE",
103
+ "type": "IMAGE",
104
+ "links": [
105
+ 105
106
+ ],
107
+ "slot_index": 0
108
+ }
109
+ ],
110
+ "properties": {
111
+ "Node name for S&R": "VAEDecodeTiled"
112
+ },
113
+ "widgets_values": [
114
+ 128,
115
+ 64,
116
+ 64,
117
+ 8
118
+ ]
119
+ },
120
+ {
121
+ "id": 65,
122
+ "type": "LoadImage",
123
+ "pos": [
124
+ -2212.498779296875,
125
+ -632.4085083007812
126
+ ],
127
+ "size": [
128
+ 315,
129
+ 314
130
+ ],
131
+ "flags": {},
132
+ "order": 1,
133
+ "mode": 0,
134
+ "inputs": [],
135
+ "outputs": [
136
+ {
137
+ "name": "IMAGE",
138
+ "type": "IMAGE",
139
+ "links": [
140
+ 86
141
+ ],
142
+ "slot_index": 0
143
+ },
144
+ {
145
+ "name": "MASK",
146
+ "type": "MASK",
147
+ "links": null
148
+ }
149
+ ],
150
+ "properties": {
151
+ "Node name for S&R": "LoadImage"
152
+ },
153
+ "widgets_values": [
154
+ "Mona-Lisa-oil-wood-panel-Leonardo-da.webp",
155
+ "image"
156
+ ]
157
+ },
158
+ {
159
+ "id": 64,
160
+ "type": "VAEEncode",
161
+ "pos": [
162
+ -1336.7884521484375,
163
+ -492.5806884765625
164
+ ],
165
+ "size": [
166
+ 210,
167
+ 46
168
+ ],
169
+ "flags": {},
170
+ "order": 14,
171
+ "mode": 0,
172
+ "inputs": [
173
+ {
174
+ "name": "pixels",
175
+ "type": "IMAGE",
176
+ "link": 144
177
+ },
178
+ {
179
+ "name": "vae",
180
+ "type": "VAE",
181
+ "link": 88
182
+ }
183
+ ],
184
+ "outputs": [
185
+ {
186
+ "name": "LATENT",
187
+ "type": "LATENT",
188
+ "links": [
189
+ 137
190
+ ],
191
+ "slot_index": 0
192
+ }
193
+ ],
194
+ "properties": {
195
+ "Node name for S&R": "VAEEncode"
196
+ },
197
+ "widgets_values": []
198
+ },
199
+ {
200
+ "id": 44,
201
+ "type": "UNETLoader",
202
+ "pos": [
203
+ -2373.55029296875,
204
+ -193.91510009765625
205
+ ],
206
+ "size": [
207
+ 459.56060791015625,
208
+ 82
209
+ ],
210
+ "flags": {},
211
+ "order": 2,
212
+ "mode": 0,
213
+ "inputs": [],
214
+ "outputs": [
215
+ {
216
+ "name": "MODEL",
217
+ "type": "MODEL",
218
+ "links": [
219
+ 135
220
+ ],
221
+ "slot_index": 0
222
+ }
223
+ ],
224
+ "properties": {
225
+ "Node name for S&R": "UNETLoader"
226
+ },
227
+ "widgets_values": [
228
+ "hyvideo\\hunyuan_video_720_fp8_e4m3fn.safetensors",
229
+ "fp8_e4m3fn_fast"
230
+ ]
231
+ },
232
+ {
233
+ "id": 49,
234
+ "type": "VAELoader",
235
+ "pos": [
236
+ -1876.39306640625,
237
+ -35.19633865356445
238
+ ],
239
+ "size": [
240
+ 433.7603454589844,
241
+ 58.71116256713867
242
+ ],
243
+ "flags": {},
244
+ "order": 3,
245
+ "mode": 0,
246
+ "inputs": [],
247
+ "outputs": [
248
+ {
249
+ "name": "VAE",
250
+ "type": "VAE",
251
+ "links": [
252
+ 74,
253
+ 88
254
+ ],
255
+ "slot_index": 0
256
+ }
257
+ ],
258
+ "properties": {
259
+ "Node name for S&R": "VAELoader"
260
+ },
261
+ "widgets_values": [
262
+ "hyvid\\hunyuan_video_vae_bf16.safetensors"
263
+ ]
264
+ },
265
+ {
266
+ "id": 47,
267
+ "type": "DualCLIPLoader",
268
+ "pos": [
269
+ -2284.893798828125,
270
+ 150.4042205810547
271
+ ],
272
+ "size": [
273
+ 343.3958435058594,
274
+ 106.86042785644531
275
+ ],
276
+ "flags": {},
277
+ "order": 4,
278
+ "mode": 0,
279
+ "inputs": [],
280
+ "outputs": [
281
+ {
282
+ "name": "CLIP",
283
+ "type": "CLIP",
284
+ "links": [
285
+ 56
286
+ ],
287
+ "slot_index": 0
288
+ }
289
+ ],
290
+ "properties": {
291
+ "Node name for S&R": "DualCLIPLoader"
292
+ },
293
+ "widgets_values": [
294
+ "clip_l.safetensors",
295
+ "llava_llama3_fp16.safetensors",
296
+ "hunyuan_video",
297
+ "default"
298
+ ]
299
+ },
300
+ {
301
+ "id": 45,
302
+ "type": "CLIPTextEncode",
303
+ "pos": [
304
+ -1839.1649169921875,
305
+ 143.5203094482422
306
+ ],
307
+ "size": [
308
+ 400,
309
+ 200
310
+ ],
311
+ "flags": {},
312
+ "order": 8,
313
+ "mode": 0,
314
+ "inputs": [
315
+ {
316
+ "name": "clip",
317
+ "type": "CLIP",
318
+ "link": 56
319
+ }
320
+ ],
321
+ "outputs": [
322
+ {
323
+ "name": "CONDITIONING",
324
+ "type": "CONDITIONING",
325
+ "links": [
326
+ 69,
327
+ 82
328
+ ],
329
+ "slot_index": 0
330
+ }
331
+ ],
332
+ "properties": {
333
+ "Node name for S&R": "CLIPTextEncode"
334
+ },
335
+ "widgets_values": [
336
+ "woman puts on sunglasses"
337
+ ]
338
+ },
339
+ {
340
+ "id": 53,
341
+ "type": "EmptyHunyuanLatentVideo",
342
+ "pos": [
343
+ -1120,
344
+ 90
345
+ ],
346
+ "size": [
347
+ 315,
348
+ 130
349
+ ],
350
+ "flags": {},
351
+ "order": 10,
352
+ "mode": 0,
353
+ "inputs": [
354
+ {
355
+ "name": "width",
356
+ "type": "INT",
357
+ "link": 89,
358
+ "widget": {
359
+ "name": "width"
360
+ }
361
+ },
362
+ {
363
+ "name": "height",
364
+ "type": "INT",
365
+ "link": 90,
366
+ "widget": {
367
+ "name": "height"
368
+ }
369
+ }
370
+ ],
371
+ "outputs": [
372
+ {
373
+ "name": "LATENT",
374
+ "type": "LATENT",
375
+ "links": [
376
+ 119
377
+ ],
378
+ "slot_index": 0
379
+ }
380
+ ],
381
+ "properties": {
382
+ "Node name for S&R": "EmptyHunyuanLatentVideo"
383
+ },
384
+ "widgets_values": [
385
+ 960,
386
+ 544,
387
+ 65,
388
+ 1
389
+ ]
390
+ },
391
+ {
392
+ "id": 55,
393
+ "type": "ConditioningZeroOut",
394
+ "pos": [
395
+ -910,
396
+ 300
397
+ ],
398
+ "size": [
399
+ 251.14309692382812,
400
+ 26
401
+ ],
402
+ "flags": {
403
+ "collapsed": true
404
+ },
405
+ "order": 12,
406
+ "mode": 0,
407
+ "inputs": [
408
+ {
409
+ "name": "conditioning",
410
+ "type": "CONDITIONING",
411
+ "link": 69
412
+ }
413
+ ],
414
+ "outputs": [
415
+ {
416
+ "name": "CONDITIONING",
417
+ "type": "CONDITIONING",
418
+ "links": [
419
+ 70
420
+ ],
421
+ "slot_index": 0
422
+ }
423
+ ],
424
+ "properties": {
425
+ "Node name for S&R": "ConditioningZeroOut"
426
+ },
427
+ "widgets_values": []
428
+ },
429
+ {
430
+ "id": 52,
431
+ "type": "BasicScheduler",
432
+ "pos": [
433
+ -600,
434
+ -350
435
+ ],
436
+ "size": [
437
+ 315,
438
+ 106
439
+ ],
440
+ "flags": {},
441
+ "order": 17,
442
+ "mode": 0,
443
+ "inputs": [
444
+ {
445
+ "name": "model",
446
+ "type": "MODEL",
447
+ "link": 78
448
+ }
449
+ ],
450
+ "outputs": [
451
+ {
452
+ "name": "SIGMAS",
453
+ "type": "SIGMAS",
454
+ "links": [
455
+ 62
456
+ ],
457
+ "slot_index": 0
458
+ }
459
+ ],
460
+ "properties": {
461
+ "Node name for S&R": "BasicScheduler"
462
+ },
463
+ "widgets_values": [
464
+ "simple",
465
+ 20,
466
+ 1
467
+ ]
468
+ },
469
+ {
470
+ "id": 42,
471
+ "type": "SamplerCustom",
472
+ "pos": [
473
+ -640,
474
+ 10
475
+ ],
476
+ "size": [
477
+ 355.20001220703125,
478
+ 467.4666748046875
479
+ ],
480
+ "flags": {},
481
+ "order": 18,
482
+ "mode": 0,
483
+ "inputs": [
484
+ {
485
+ "name": "model",
486
+ "type": "MODEL",
487
+ "link": 77
488
+ },
489
+ {
490
+ "name": "positive",
491
+ "type": "CONDITIONING",
492
+ "link": 83
493
+ },
494
+ {
495
+ "name": "negative",
496
+ "type": "CONDITIONING",
497
+ "link": 70
498
+ },
499
+ {
500
+ "name": "sampler",
501
+ "type": "SAMPLER",
502
+ "link": 61
503
+ },
504
+ {
505
+ "name": "sigmas",
506
+ "type": "SIGMAS",
507
+ "link": 62
508
+ },
509
+ {
510
+ "name": "latent_image",
511
+ "type": "LATENT",
512
+ "link": 119
513
+ }
514
+ ],
515
+ "outputs": [
516
+ {
517
+ "name": "output",
518
+ "type": "LATENT",
519
+ "links": null
520
+ },
521
+ {
522
+ "name": "denoised_output",
523
+ "type": "LATENT",
524
+ "links": [
525
+ 141
526
+ ],
527
+ "slot_index": 1
528
+ }
529
+ ],
530
+ "properties": {
531
+ "Node name for S&R": "SamplerCustom"
532
+ },
533
+ "widgets_values": [
534
+ true,
535
+ 6,
536
+ "fixed",
537
+ 1,
538
+ null
539
+ ]
540
+ },
541
+ {
542
+ "id": 84,
543
+ "type": "GetLatentRangeFromBatch",
544
+ "pos": [
545
+ -240,
546
+ -100
547
+ ],
548
+ "size": [
549
+ 340.20001220703125,
550
+ 82
551
+ ],
552
+ "flags": {},
553
+ "order": 19,
554
+ "mode": 0,
555
+ "inputs": [
556
+ {
557
+ "name": "latents",
558
+ "type": "LATENT",
559
+ "link": 141
560
+ }
561
+ ],
562
+ "outputs": [
563
+ {
564
+ "name": "LATENT",
565
+ "type": "LATENT",
566
+ "links": [
567
+ 142
568
+ ],
569
+ "slot_index": 0
570
+ }
571
+ ],
572
+ "properties": {
573
+ "Node name for S&R": "GetLatentRangeFromBatch"
574
+ },
575
+ "widgets_values": [
576
+ 1,
577
+ -1
578
+ ]
579
+ },
580
+ {
581
+ "id": 50,
582
+ "type": "VHS_VideoCombine",
583
+ "pos": [
584
+ 165.77645874023438,
585
+ -619.0606079101562
586
+ ],
587
+ "size": [
588
+ 1112.6898193359375,
589
+ 1076.4598388671875
590
+ ],
591
+ "flags": {},
592
+ "order": 21,
593
+ "mode": 0,
594
+ "inputs": [
595
+ {
596
+ "name": "images",
597
+ "type": "IMAGE",
598
+ "link": 105
599
+ },
600
+ {
601
+ "name": "audio",
602
+ "type": "AUDIO",
603
+ "link": null,
604
+ "shape": 7
605
+ },
606
+ {
607
+ "name": "meta_batch",
608
+ "type": "VHS_BatchManager",
609
+ "link": null,
610
+ "shape": 7
611
+ },
612
+ {
613
+ "name": "vae",
614
+ "type": "VAE",
615
+ "link": null,
616
+ "shape": 7
617
+ }
618
+ ],
619
+ "outputs": [
620
+ {
621
+ "name": "Filenames",
622
+ "type": "VHS_FILENAMES",
623
+ "links": null
624
+ }
625
+ ],
626
+ "properties": {
627
+ "Node name for S&R": "VHS_VideoCombine"
628
+ },
629
+ "widgets_values": {
630
+ "frame_rate": 24,
631
+ "loop_count": 0,
632
+ "filename_prefix": "hyvidcomfy",
633
+ "format": "video/h264-mp4",
634
+ "pix_fmt": "yuv420p",
635
+ "crf": 19,
636
+ "save_metadata": true,
637
+ "trim_to_audio": false,
638
+ "pingpong": false,
639
+ "save_output": false,
640
+ "videopreview": {
641
+ "hidden": false,
642
+ "paused": false,
643
+ "params": {
644
+ "filename": "hyvidcomfy_00001.mp4",
645
+ "subfolder": "",
646
+ "type": "temp",
647
+ "format": "video/h264-mp4",
648
+ "frame_rate": 24,
649
+ "workflow": "hyvidcomfy_00001.png",
650
+ "fullpath": "N:\\AI\\ComfyUI\\temp\\hyvidcomfy_00001.mp4"
651
+ },
652
+ "muted": false
653
+ }
654
+ }
655
+ },
656
+ {
657
+ "id": 54,
658
+ "type": "ModelSamplingSD3",
659
+ "pos": [
660
+ -1079.9112548828125,
661
+ -146.69448852539062
662
+ ],
663
+ "size": [
664
+ 315,
665
+ 58
666
+ ],
667
+ "flags": {},
668
+ "order": 16,
669
+ "mode": 0,
670
+ "inputs": [
671
+ {
672
+ "name": "model",
673
+ "type": "MODEL",
674
+ "link": 117
675
+ }
676
+ ],
677
+ "outputs": [
678
+ {
679
+ "name": "MODEL",
680
+ "type": "MODEL",
681
+ "links": [
682
+ 77,
683
+ 78
684
+ ],
685
+ "slot_index": 0
686
+ }
687
+ ],
688
+ "properties": {
689
+ "Node name for S&R": "ModelSamplingSD3"
690
+ },
691
+ "widgets_values": [
692
+ 9
693
+ ]
694
+ },
695
+ {
696
+ "id": 80,
697
+ "type": "PathchSageAttentionKJ",
698
+ "pos": [
699
+ -2273.926513671875,
700
+ -36.720542907714844
701
+ ],
702
+ "size": [
703
+ 315,
704
+ 58
705
+ ],
706
+ "flags": {},
707
+ "order": 7,
708
+ "mode": 4,
709
+ "inputs": [
710
+ {
711
+ "name": "model",
712
+ "type": "MODEL",
713
+ "link": 135
714
+ }
715
+ ],
716
+ "outputs": [
717
+ {
718
+ "name": "MODEL",
719
+ "type": "MODEL",
720
+ "links": [
721
+ 136
722
+ ],
723
+ "slot_index": 0
724
+ }
725
+ ],
726
+ "properties": {
727
+ "Node name for S&R": "PathchSageAttentionKJ"
728
+ },
729
+ "widgets_values": [
730
+ "auto"
731
+ ]
732
+ },
733
+ {
734
+ "id": 85,
735
+ "type": "Note",
736
+ "pos": [
737
+ -1838.572265625,
738
+ -302.1575927734375
739
+ ],
740
+ "size": [
741
+ 408.4594421386719,
742
+ 58
743
+ ],
744
+ "flags": {},
745
+ "order": 5,
746
+ "mode": 0,
747
+ "inputs": [],
748
+ "outputs": [],
749
+ "properties": {},
750
+ "widgets_values": [
751
+ "https://huggingface.co/Kijai/Leapfusion-image2vid-comfy/blob/main/leapfusion_img2vid544p_comfy.safetensors"
752
+ ],
753
+ "color": "#432",
754
+ "bgcolor": "#653"
755
+ },
756
+ {
757
+ "id": 74,
758
+ "type": "LeapfusionHunyuanI2VPatcher",
759
+ "pos": [
760
+ -1059.552978515625,
761
+ -459.34674072265625
762
+ ],
763
+ "size": [
764
+ 277.3238525390625,
765
+ 150
766
+ ],
767
+ "flags": {},
768
+ "order": 15,
769
+ "mode": 0,
770
+ "inputs": [
771
+ {
772
+ "name": "model",
773
+ "type": "MODEL",
774
+ "link": 123
775
+ },
776
+ {
777
+ "name": "latent",
778
+ "type": "LATENT",
779
+ "link": 137
780
+ }
781
+ ],
782
+ "outputs": [
783
+ {
784
+ "name": "MODEL",
785
+ "type": "MODEL",
786
+ "links": [
787
+ 117
788
+ ],
789
+ "slot_index": 0
790
+ }
791
+ ],
792
+ "properties": {
793
+ "Node name for S&R": "LeapfusionHunyuanI2VPatcher"
794
+ },
795
+ "widgets_values": [
796
+ 0,
797
+ 0,
798
+ 1,
799
+ 0.8
800
+ ]
801
+ },
802
+ {
803
+ "id": 59,
804
+ "type": "LoraLoaderModelOnly",
805
+ "pos": [
806
+ -1870.3748779296875,
807
+ -194.6091766357422
808
+ ],
809
+ "size": [
810
+ 442.8438720703125,
811
+ 82
812
+ ],
813
+ "flags": {},
814
+ "order": 11,
815
+ "mode": 0,
816
+ "inputs": [
817
+ {
818
+ "name": "model",
819
+ "type": "MODEL",
820
+ "link": 136
821
+ }
822
+ ],
823
+ "outputs": [
824
+ {
825
+ "name": "MODEL",
826
+ "type": "MODEL",
827
+ "links": [
828
+ 123
829
+ ],
830
+ "slot_index": 0
831
+ }
832
+ ],
833
+ "properties": {
834
+ "Node name for S&R": "LoraLoaderModelOnly"
835
+ },
836
+ "widgets_values": [
837
+ "hyvid\\musubi-tuner\\img2vid544p.safetensors",
838
+ 1
839
+ ]
840
+ },
841
+ {
842
+ "id": 66,
843
+ "type": "ImageResizeKJ",
844
+ "pos": [
845
+ -1821.1531982421875,
846
+ -632.925048828125
847
+ ],
848
+ "size": [
849
+ 315,
850
+ 266
851
+ ],
852
+ "flags": {},
853
+ "order": 6,
854
+ "mode": 0,
855
+ "inputs": [
856
+ {
857
+ "name": "image",
858
+ "type": "IMAGE",
859
+ "link": 86
860
+ },
861
+ {
862
+ "name": "get_image_size",
863
+ "type": "IMAGE",
864
+ "link": null,
865
+ "shape": 7
866
+ },
867
+ {
868
+ "name": "width_input",
869
+ "type": "INT",
870
+ "link": null,
871
+ "widget": {
872
+ "name": "width_input"
873
+ },
874
+ "shape": 7
875
+ },
876
+ {
877
+ "name": "height_input",
878
+ "type": "INT",
879
+ "link": null,
880
+ "widget": {
881
+ "name": "height_input"
882
+ },
883
+ "shape": 7
884
+ }
885
+ ],
886
+ "outputs": [
887
+ {
888
+ "name": "IMAGE",
889
+ "type": "IMAGE",
890
+ "links": [
891
+ 143
892
+ ],
893
+ "slot_index": 0
894
+ },
895
+ {
896
+ "name": "width",
897
+ "type": "INT",
898
+ "links": [
899
+ 89
900
+ ],
901
+ "slot_index": 1
902
+ },
903
+ {
904
+ "name": "height",
905
+ "type": "INT",
906
+ "links": [
907
+ 90
908
+ ],
909
+ "slot_index": 2
910
+ }
911
+ ],
912
+ "properties": {
913
+ "Node name for S&R": "ImageResizeKJ"
914
+ },
915
+ "widgets_values": [
916
+ 960,
917
+ 640,
918
+ "lanczos",
919
+ false,
920
+ 2,
921
+ 0,
922
+ 0,
923
+ "center"
924
+ ]
925
+ },
926
+ {
927
+ "id": 86,
928
+ "type": "ImageNoiseAugmentation",
929
+ "pos": [
930
+ -1361.111572265625,
931
+ -667.0104370117188
932
+ ],
933
+ "size": [
934
+ 315,
935
+ 106
936
+ ],
937
+ "flags": {},
938
+ "order": 9,
939
+ "mode": 0,
940
+ "inputs": [
941
+ {
942
+ "name": "image",
943
+ "type": "IMAGE",
944
+ "link": 143
945
+ }
946
+ ],
947
+ "outputs": [
948
+ {
949
+ "name": "IMAGE",
950
+ "type": "IMAGE",
951
+ "links": [
952
+ 144
953
+ ],
954
+ "slot_index": 0
955
+ }
956
+ ],
957
+ "properties": {
958
+ "Node name for S&R": "ImageNoiseAugmentation"
959
+ },
960
+ "widgets_values": [
961
+ 0.05,
962
+ 123,
963
+ "fixed"
964
+ ]
965
+ }
966
+ ],
967
+ "links": [
968
+ [
969
+ 56,
970
+ 47,
971
+ 0,
972
+ 45,
973
+ 0,
974
+ "CLIP"
975
+ ],
976
+ [
977
+ 61,
978
+ 51,
979
+ 0,
980
+ 42,
981
+ 3,
982
+ "SAMPLER"
983
+ ],
984
+ [
985
+ 62,
986
+ 52,
987
+ 0,
988
+ 42,
989
+ 4,
990
+ "SIGMAS"
991
+ ],
992
+ [
993
+ 69,
994
+ 45,
995
+ 0,
996
+ 55,
997
+ 0,
998
+ "CONDITIONING"
999
+ ],
1000
+ [
1001
+ 70,
1002
+ 55,
1003
+ 0,
1004
+ 42,
1005
+ 2,
1006
+ "CONDITIONING"
1007
+ ],
1008
+ [
1009
+ 74,
1010
+ 49,
1011
+ 0,
1012
+ 57,
1013
+ 1,
1014
+ "VAE"
1015
+ ],
1016
+ [
1017
+ 77,
1018
+ 54,
1019
+ 0,
1020
+ 42,
1021
+ 0,
1022
+ "MODEL"
1023
+ ],
1024
+ [
1025
+ 78,
1026
+ 54,
1027
+ 0,
1028
+ 52,
1029
+ 0,
1030
+ "MODEL"
1031
+ ],
1032
+ [
1033
+ 82,
1034
+ 45,
1035
+ 0,
1036
+ 62,
1037
+ 0,
1038
+ "CONDITIONING"
1039
+ ],
1040
+ [
1041
+ 83,
1042
+ 62,
1043
+ 0,
1044
+ 42,
1045
+ 1,
1046
+ "CONDITIONING"
1047
+ ],
1048
+ [
1049
+ 86,
1050
+ 65,
1051
+ 0,
1052
+ 66,
1053
+ 0,
1054
+ "IMAGE"
1055
+ ],
1056
+ [
1057
+ 88,
1058
+ 49,
1059
+ 0,
1060
+ 64,
1061
+ 1,
1062
+ "VAE"
1063
+ ],
1064
+ [
1065
+ 89,
1066
+ 66,
1067
+ 1,
1068
+ 53,
1069
+ 0,
1070
+ "INT"
1071
+ ],
1072
+ [
1073
+ 90,
1074
+ 66,
1075
+ 2,
1076
+ 53,
1077
+ 1,
1078
+ "INT"
1079
+ ],
1080
+ [
1081
+ 105,
1082
+ 57,
1083
+ 0,
1084
+ 50,
1085
+ 0,
1086
+ "IMAGE"
1087
+ ],
1088
+ [
1089
+ 117,
1090
+ 74,
1091
+ 0,
1092
+ 54,
1093
+ 0,
1094
+ "MODEL"
1095
+ ],
1096
+ [
1097
+ 119,
1098
+ 53,
1099
+ 0,
1100
+ 42,
1101
+ 5,
1102
+ "LATENT"
1103
+ ],
1104
+ [
1105
+ 123,
1106
+ 59,
1107
+ 0,
1108
+ 74,
1109
+ 0,
1110
+ "MODEL"
1111
+ ],
1112
+ [
1113
+ 135,
1114
+ 44,
1115
+ 0,
1116
+ 80,
1117
+ 0,
1118
+ "MODEL"
1119
+ ],
1120
+ [
1121
+ 136,
1122
+ 80,
1123
+ 0,
1124
+ 59,
1125
+ 0,
1126
+ "MODEL"
1127
+ ],
1128
+ [
1129
+ 137,
1130
+ 64,
1131
+ 0,
1132
+ 74,
1133
+ 1,
1134
+ "LATENT"
1135
+ ],
1136
+ [
1137
+ 141,
1138
+ 42,
1139
+ 1,
1140
+ 84,
1141
+ 0,
1142
+ "LATENT"
1143
+ ],
1144
+ [
1145
+ 142,
1146
+ 84,
1147
+ 0,
1148
+ 57,
1149
+ 0,
1150
+ "LATENT"
1151
+ ],
1152
+ [
1153
+ 143,
1154
+ 66,
1155
+ 0,
1156
+ 86,
1157
+ 0,
1158
+ "IMAGE"
1159
+ ],
1160
+ [
1161
+ 144,
1162
+ 86,
1163
+ 0,
1164
+ 64,
1165
+ 0,
1166
+ "IMAGE"
1167
+ ]
1168
+ ],
1169
+ "groups": [],
1170
+ "config": {},
1171
+ "extra": {
1172
+ "ds": {
1173
+ "scale": 0.740024994425854,
1174
+ "offset": [
1175
+ 2525.036093151529,
1176
+ 802.59123935694
1177
+ ]
1178
+ },
1179
+ "node_versions": {
1180
+ "comfy-core": "0.3.13",
1181
+ "ComfyUI-KJNodes": "a8aeef670b3f288303f956bf94385cb87978ea93",
1182
+ "ComfyUI-VideoHelperSuite": "c47b10ca1798b4925ff5a5f07d80c51ca80a837d"
1183
+ },
1184
+ "VHS_latentpreview": true,
1185
+ "VHS_latentpreviewrate": 0
1186
+ },
1187
+ "version": 0.4
1188
+ }
fonts/FreeMono.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7c692ad545c308b7b8fc2db770760c4a5d15ca50f12addf58c8f5360370e831
3
+ size 343980
fonts/FreeMonoBoldOblique.otf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:96187651ee033d0d9791dc2beeebfba5d1f070ab410fce1a5c16483ca249c588
3
+ size 237600
fonts/TTNorms-Black.otf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:710977e683bf0db6416d6d41b427e0363c914e6c503a5291fcb330f30b8448ea
3
+ size 152736
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
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
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
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
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
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}));
kjweb_async/protovis.min.js ADDED
The diff for this file is too large to render. See raw diff
 
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
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}));
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,)
nodes/batchcrop_nodes.py ADDED
@@ -0,0 +1,768 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "bbox_format": (["xywh", "xyxy"], {"default": "xywh"}),
698
+ },
699
+ }
700
+
701
+ RETURN_TYPES = ("IMAGE",)
702
+ RETURN_NAMES = ("images",)
703
+ FUNCTION = "visualizebbox"
704
+ DESCRIPTION = """
705
+ Visualizes the specified bbox on the image.
706
+ """
707
+
708
+ CATEGORY = "KJNodes/masking"
709
+
710
+ def visualizebbox(self, bboxes, images, line_width, bbox_format):
711
+ image_list = []
712
+ for image, bbox in zip(images, bboxes):
713
+ # Ensure bbox is a sequence of 4 values
714
+ if isinstance(bbox, (list, tuple, np.ndarray)) and len(bbox) == 4:
715
+ if bbox_format == "xywh":
716
+ x_min, y_min, width, height = bbox
717
+ elif bbox_format == "xyxy":
718
+ x_min, y_min, x_max, y_max = bbox
719
+ width = x_max - x_min
720
+ height = y_max - y_min
721
+ else:
722
+ raise ValueError(f"Unknown bbox_format: {bbox_format}")
723
+ else:
724
+ print("Invalid bbox:", bbox)
725
+ continue
726
+
727
+ # Ensure bbox coordinates are integers
728
+ x_min = int(x_min)
729
+ y_min = int(y_min)
730
+ width = int(width)
731
+ height = int(height)
732
+
733
+ # Permute the image dimensions
734
+ image = image.permute(2, 0, 1)
735
+
736
+ # Clone the image to draw bounding boxes
737
+ img_with_bbox = image.clone()
738
+
739
+ # Define the color for the bbox, e.g., red
740
+ color = torch.tensor([1, 0, 0], dtype=torch.float32)
741
+
742
+ # Ensure color tensor matches the image channels
743
+ if color.shape[0] != img_with_bbox.shape[0]:
744
+ color = color.unsqueeze(1).expand(-1, line_width)
745
+
746
+ # Draw lines for each side of the bbox with the specified line width
747
+ for lw in range(line_width):
748
+ # Top horizontal line
749
+ if y_min + lw < img_with_bbox.shape[1]:
750
+ img_with_bbox[:, y_min + lw, x_min:x_min + width] = color[:, None]
751
+
752
+ # Bottom horizontal line
753
+ if y_min + height - lw < img_with_bbox.shape[1]:
754
+ img_with_bbox[:, y_min + height - lw, x_min:x_min + width] = color[:, None]
755
+
756
+ # Left vertical line
757
+ if x_min + lw < img_with_bbox.shape[2]:
758
+ img_with_bbox[:, y_min:y_min + height, x_min + lw] = color[:, None]
759
+
760
+ # Right vertical line
761
+ if x_min + width - lw < img_with_bbox.shape[2]:
762
+ img_with_bbox[:, y_min:y_min + height, x_min + width - lw] = color[:, None]
763
+
764
+ # Permute the image dimensions back
765
+ img_with_bbox = img_with_bbox.permute(1, 2, 0).unsqueeze(0)
766
+ image_list.append(img_with_bbox)
767
+
768
+ return (torch.cat(image_list, dim=0),)
nodes/curve_nodes.py ADDED
@@ -0,0 +1,1636 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torchvision import transforms
3
+ import json
4
+ from PIL import Image, ImageDraw, ImageFont, ImageColor, ImageFilter, ImageChops
5
+ import numpy as np
6
+ from ..utility.utility import pil2tensor, tensor2pil
7
+ import folder_paths
8
+ import io
9
+ import base64
10
+
11
+ from comfy.utils import common_upscale
12
+
13
+ def parse_color(color):
14
+ if isinstance(color, str) and ',' in color:
15
+ return tuple(int(c.strip()) for c in color.split(','))
16
+ return color
17
+
18
+ def parse_json_tracks(tracks):
19
+ tracks_data = []
20
+ try:
21
+ # If tracks is a string, try to parse it as JSON
22
+ if isinstance(tracks, str):
23
+ parsed = json.loads(tracks.replace("'", '"'))
24
+ tracks_data.extend(parsed)
25
+ else:
26
+ # If tracks is a list of strings, parse each one
27
+ for track_str in tracks:
28
+ parsed = json.loads(track_str.replace("'", '"'))
29
+ tracks_data.append(parsed)
30
+
31
+ # Check if we have a single track (dict with x,y) or a list of tracks
32
+ if tracks_data and isinstance(tracks_data[0], dict) and 'x' in tracks_data[0]:
33
+ # Single track detected, wrap it in a list
34
+ tracks_data = [tracks_data]
35
+ elif tracks_data and isinstance(tracks_data[0], list) and tracks_data[0] and isinstance(tracks_data[0][0], dict) and 'x' in tracks_data[0][0]:
36
+ # Already a list of tracks, nothing to do
37
+ pass
38
+ else:
39
+ # Unexpected format
40
+ print(f"Warning: Unexpected track format: {type(tracks_data[0])}")
41
+
42
+ except json.JSONDecodeError as e:
43
+ print(f"Error parsing tracks JSON: {e}")
44
+ tracks_data = []
45
+
46
+ return tracks_data
47
+
48
+ def plot_coordinates_to_tensor(coordinates, height, width, bbox_height, bbox_width, size_multiplier, prompt):
49
+ import matplotlib
50
+ matplotlib.use('Agg')
51
+ from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
52
+ text_color = '#999999'
53
+ bg_color = '#353535'
54
+ matplotlib.pyplot.rcParams['text.color'] = text_color
55
+ fig, ax = matplotlib.pyplot.subplots(figsize=(width/100, height/100), dpi=100)
56
+ fig.patch.set_facecolor(bg_color)
57
+ ax.set_facecolor(bg_color)
58
+ ax.grid(color=text_color, linestyle='-', linewidth=0.5)
59
+ ax.set_xlabel('x', color=text_color)
60
+ ax.set_ylabel('y', color=text_color)
61
+ for text in ax.get_xticklabels() + ax.get_yticklabels():
62
+ text.set_color(text_color)
63
+ ax.set_title('position for: ' + prompt)
64
+ ax.set_xlabel('X Coordinate')
65
+ ax.set_ylabel('Y Coordinate')
66
+ #ax.legend().remove()
67
+ ax.set_xlim(0, width) # Set the x-axis to match the input latent width
68
+ ax.set_ylim(height, 0) # Set the y-axis to match the input latent height, with (0,0) at top-left
69
+ # Adjust the margins of the subplot
70
+ matplotlib.pyplot.subplots_adjust(left=0.08, right=0.95, bottom=0.05, top=0.95, wspace=0.2, hspace=0.2)
71
+
72
+ cmap = matplotlib.pyplot.get_cmap('rainbow')
73
+ image_batch = []
74
+ canvas = FigureCanvas(fig)
75
+ width, height = fig.get_size_inches() * fig.get_dpi()
76
+ # Draw a box at each coordinate
77
+ for i, ((x, y), size) in enumerate(zip(coordinates, size_multiplier)):
78
+ color_index = i / (len(coordinates) - 1)
79
+ color = cmap(color_index)
80
+ draw_height = bbox_height * size
81
+ draw_width = bbox_width * size
82
+ rect = matplotlib.patches.Rectangle((x - draw_width/2, y - draw_height/2), draw_width, draw_height,
83
+ linewidth=1, edgecolor=color, facecolor='none', alpha=0.5)
84
+ ax.add_patch(rect)
85
+
86
+ # Check if there is a next coordinate to draw an arrow to
87
+ if i < len(coordinates) - 1:
88
+ x1, y1 = coordinates[i]
89
+ x2, y2 = coordinates[i + 1]
90
+ ax.annotate("", xy=(x2, y2), xytext=(x1, y1),
91
+ arrowprops=dict(arrowstyle="->",
92
+ linestyle="-",
93
+ lw=1,
94
+ color=color,
95
+ mutation_scale=20))
96
+ canvas.draw()
97
+ image_np = np.frombuffer(canvas.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3).copy()
98
+ image_tensor = torch.from_numpy(image_np).float() / 255.0
99
+ image_tensor = image_tensor.unsqueeze(0)
100
+ image_batch.append(image_tensor)
101
+
102
+ matplotlib.pyplot.close(fig)
103
+ image_batch_tensor = torch.cat(image_batch, dim=0)
104
+
105
+ return image_batch_tensor
106
+
107
+ class PlotCoordinates:
108
+ @classmethod
109
+ def INPUT_TYPES(s):
110
+ return {"required": {
111
+ "coordinates": ("STRING", {"forceInput": True}),
112
+ "text": ("STRING", {"default": 'title', "multiline": False}),
113
+ "width": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}),
114
+ "height": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}),
115
+ "bbox_width": ("INT", {"default": 128, "min": 8, "max": 4096, "step": 8}),
116
+ "bbox_height": ("INT", {"default": 128, "min": 8, "max": 4096, "step": 8}),
117
+ },
118
+ "optional": {"size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True})},
119
+ }
120
+ RETURN_TYPES = ("IMAGE", "INT", "INT", "INT", "INT",)
121
+ RETURN_NAMES = ("images", "width", "height", "bbox_width", "bbox_height",)
122
+ FUNCTION = "append"
123
+ CATEGORY = "KJNodes/experimental"
124
+ DESCRIPTION = """
125
+ Plots coordinates to sequence of images using Matplotlib.
126
+
127
+ """
128
+
129
+ def append(self, coordinates, text, width, height, bbox_width, bbox_height, size_multiplier=[1.0]):
130
+ coordinates = json.loads(coordinates.replace("'", '"'))
131
+ coordinates = [(coord['x'], coord['y']) for coord in coordinates]
132
+ batch_size = len(coordinates)
133
+ if not size_multiplier or len(size_multiplier) != batch_size:
134
+ size_multiplier = [0] * batch_size
135
+ else:
136
+ size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)]
137
+
138
+ plot_image_tensor = plot_coordinates_to_tensor(coordinates, height, width, bbox_height, bbox_width, size_multiplier, text)
139
+
140
+ return (plot_image_tensor, width, height, bbox_width, bbox_height)
141
+
142
+ class SplineEditor:
143
+
144
+ @classmethod
145
+ def INPUT_TYPES(cls):
146
+ return {
147
+ "required": {
148
+ "points_store": ("STRING", {"multiline": False}),
149
+ "coordinates": ("STRING", {"multiline": False}),
150
+ "mask_width": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}),
151
+ "mask_height": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}),
152
+ "points_to_sample": ("INT", {"default": 16, "min": 2, "max": 1000, "step": 1}),
153
+ "sampling_method": (
154
+ [
155
+ 'path',
156
+ 'time',
157
+ 'controlpoints',
158
+ 'speed'
159
+ ],
160
+ {
161
+ "default": 'time'
162
+ }),
163
+ "interpolation": (
164
+ [
165
+ 'cardinal',
166
+ 'monotone',
167
+ 'basis',
168
+ 'linear',
169
+ 'step-before',
170
+ 'step-after',
171
+ 'polar',
172
+ 'polar-reverse',
173
+ ],
174
+ {
175
+ "default": 'cardinal'
176
+ }),
177
+ "tension": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
178
+ "repeat_output": ("INT", {"default": 1, "min": 1, "max": 4096, "step": 1}),
179
+ "float_output_type": (
180
+ [
181
+ 'list',
182
+ 'pandas series',
183
+ 'tensor',
184
+ ],
185
+ {
186
+ "default": 'list'
187
+ }),
188
+ },
189
+ "optional": {
190
+ "min_value": ("FLOAT", {"default": 0.0, "min": -10000.0, "max": 10000.0, "step": 0.01}),
191
+ "max_value": ("FLOAT", {"default": 1.0, "min": -10000.0, "max": 10000.0, "step": 0.01}),
192
+ "bg_image": ("IMAGE", ),
193
+ }
194
+ }
195
+
196
+ RETURN_TYPES = ("MASK", "STRING", "FLOAT", "INT", "STRING",)
197
+ RETURN_NAMES = ("mask", "coord_str", "float", "count", "normalized_str",)
198
+ FUNCTION = "splinedata"
199
+ CATEGORY = "KJNodes/weights"
200
+ DESCRIPTION = """
201
+ # WORK IN PROGRESS
202
+ Do not count on this as part of your workflow yet,
203
+ probably contains lots of bugs and stability is not
204
+ guaranteed!!
205
+
206
+ ## Graphical editor to create values for various
207
+ ## schedules and/or mask batches.
208
+
209
+ **Shift + click** to add control point at end.
210
+ **Ctrl + click** to add control point (subdivide) between two points.
211
+ **Right click on a point** to delete it.
212
+ Note that you can't delete from start/end.
213
+
214
+ Right click on canvas for context menu:
215
+ NEW!:
216
+ - Add new spline
217
+ - Creates a new spline on same canvas, currently these paths are only outputed
218
+ as coordinates.
219
+ - Add single point
220
+ - Creates a single point that only returns it's current position coords
221
+ - Delete spline
222
+ - Deletes the currently selected spline, you can select a spline by clicking on
223
+ it's path, or cycle through them with the 'Next spline' -option.
224
+
225
+ These are purely visual options, doesn't affect the output:
226
+ - Toggle handles visibility
227
+ - Display sample points: display the points to be returned.
228
+
229
+ **points_to_sample** value sets the number of samples
230
+ returned from the **drawn spline itself**, this is independent from the
231
+ actual control points, so the interpolation type matters.
232
+ sampling_method:
233
+ - time: samples along the time axis, used for schedules
234
+ - path: samples along the path itself, useful for coordinates
235
+ - controlpoints: samples only the control points themselves
236
+
237
+ output types:
238
+ - mask batch
239
+ example compatible nodes: anything that takes masks
240
+ - list of floats
241
+ example compatible nodes: IPAdapter weights
242
+ - pandas series
243
+ example compatible nodes: anything that takes Fizz'
244
+ nodes Batch Value Schedule
245
+ - torch tensor
246
+ example compatible nodes: unknown
247
+ """
248
+
249
+ def splinedata(self, mask_width, mask_height, coordinates, float_output_type, interpolation,
250
+ points_to_sample, sampling_method, points_store, tension, repeat_output,
251
+ min_value=0.0, max_value=1.0, bg_image=None):
252
+
253
+ coordinates = json.loads(coordinates)
254
+
255
+ # Handle nested list structure if present
256
+ all_normalized = []
257
+ all_normalized_y_values = []
258
+
259
+ # Check if we have a nested list structure
260
+ if isinstance(coordinates, list) and len(coordinates) > 0 and isinstance(coordinates[0], list):
261
+ # Process each list of coordinates in the nested structure
262
+ coordinate_sets = coordinates
263
+ else:
264
+ # If not nested, treat as a single list of coordinates
265
+ coordinate_sets = [coordinates]
266
+
267
+ # Process each set of coordinates
268
+ for coord_set in coordinate_sets:
269
+ normalized = []
270
+ normalized_y_values = []
271
+
272
+ for coord in coord_set:
273
+ coord['x'] = int(round(coord['x']))
274
+ coord['y'] = int(round(coord['y']))
275
+ norm_x = (1.0 - (coord['x'] / mask_height) - 0.0) * (max_value - min_value) + min_value
276
+ norm_y = (1.0 - (coord['y'] / mask_height) - 0.0) * (max_value - min_value) + min_value
277
+ normalized_y_values.append(norm_y)
278
+ normalized.append({'x':norm_x, 'y':norm_y})
279
+
280
+ all_normalized.extend(normalized)
281
+ all_normalized_y_values.extend(normalized_y_values)
282
+
283
+ # Use the combined normalized values for output
284
+ if float_output_type == 'list':
285
+ out_floats = all_normalized_y_values * repeat_output
286
+ elif float_output_type == 'pandas series':
287
+ try:
288
+ import pandas as pd
289
+ except:
290
+ raise Exception("MaskOrImageToWeight: pandas is not installed. Please install pandas to use this output_type")
291
+ out_floats = pd.Series(all_normalized_y_values * repeat_output),
292
+ elif float_output_type == 'tensor':
293
+ out_floats = torch.tensor(all_normalized_y_values * repeat_output, dtype=torch.float32)
294
+
295
+ # Create a color map for grayscale intensities
296
+ color_map = lambda y: torch.full((mask_height, mask_width, 3), y, dtype=torch.float32)
297
+
298
+ # Create image tensors for each normalized y value
299
+ mask_tensors = [color_map(y) for y in all_normalized_y_values]
300
+ masks_out = torch.stack(mask_tensors)
301
+ masks_out = masks_out.repeat(repeat_output, 1, 1, 1)
302
+ masks_out = masks_out.mean(dim=-1)
303
+
304
+ if bg_image is None:
305
+ return (masks_out, json.dumps(coordinates if len(coordinates) > 1 else coordinates[0]), out_floats, len(out_floats), json.dumps(all_normalized))
306
+ else:
307
+ transform = transforms.ToPILImage()
308
+ image = transform(bg_image[0].permute(2, 0, 1))
309
+ buffered = io.BytesIO()
310
+ image.save(buffered, format="JPEG", quality=75)
311
+
312
+ # Encode the image bytes to a Base64 string
313
+ img_bytes = buffered.getvalue()
314
+ img_base64 = base64.b64encode(img_bytes).decode('utf-8')
315
+
316
+ return {
317
+ "ui": {"bg_image": [img_base64]},
318
+ "result": (masks_out, json.dumps(coordinates if len(coordinates) > 1 else coordinates[0]), out_floats, len(out_floats), json.dumps(all_normalized))
319
+ }
320
+
321
+
322
+ class CreateShapeMaskOnPath:
323
+
324
+ RETURN_TYPES = ("MASK", "MASK",)
325
+ RETURN_NAMES = ("mask", "mask_inverted",)
326
+ FUNCTION = "createshapemask"
327
+ CATEGORY = "KJNodes/masking/generate"
328
+ DESCRIPTION = """
329
+ Creates a mask or batch of masks with the specified shape.
330
+ Locations are center locations.
331
+ """
332
+ DEPRECATED = True
333
+
334
+ @classmethod
335
+ def INPUT_TYPES(s):
336
+ return {
337
+ "required": {
338
+ "shape": (
339
+ [ 'circle',
340
+ 'square',
341
+ 'triangle',
342
+ ],
343
+ {
344
+ "default": 'circle'
345
+ }),
346
+ "coordinates": ("STRING", {"forceInput": True}),
347
+ "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
348
+ "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
349
+ "shape_width": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}),
350
+ "shape_height": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}),
351
+ },
352
+ "optional": {
353
+ "size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True}),
354
+ }
355
+ }
356
+
357
+ def createshapemask(self, coordinates, frame_width, frame_height, shape_width, shape_height, shape, size_multiplier=[1.0]):
358
+ # Define the number of images in the batch
359
+ coordinates = coordinates.replace("'", '"')
360
+ coordinates = json.loads(coordinates)
361
+
362
+ batch_size = len(coordinates)
363
+ out = []
364
+ color = "white"
365
+ if not size_multiplier or len(size_multiplier) != batch_size:
366
+ size_multiplier = [0] * batch_size
367
+ else:
368
+ size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)]
369
+ for i, coord in enumerate(coordinates):
370
+ image = Image.new("RGB", (frame_width, frame_height), "black")
371
+ draw = ImageDraw.Draw(image)
372
+
373
+ # Calculate the size for this frame and ensure it's not less than 0
374
+ current_width = max(0, shape_width + i * size_multiplier[i])
375
+ current_height = max(0, shape_height + i * size_multiplier[i])
376
+
377
+ location_x = coord['x']
378
+ location_y = coord['y']
379
+
380
+ if shape == 'circle' or shape == 'square':
381
+ # Define the bounding box for the shape
382
+ left_up_point = (location_x - current_width // 2, location_y - current_height // 2)
383
+ right_down_point = (location_x + current_width // 2, location_y + current_height // 2)
384
+ two_points = [left_up_point, right_down_point]
385
+
386
+ if shape == 'circle':
387
+ draw.ellipse(two_points, fill=color)
388
+ elif shape == 'square':
389
+ draw.rectangle(two_points, fill=color)
390
+
391
+ elif shape == 'triangle':
392
+ # Define the points for the triangle
393
+ left_up_point = (location_x - current_width // 2, location_y + current_height // 2) # bottom left
394
+ right_down_point = (location_x + current_width // 2, location_y + current_height // 2) # bottom right
395
+ top_point = (location_x, location_y - current_height // 2) # top point
396
+ draw.polygon([top_point, left_up_point, right_down_point], fill=color)
397
+
398
+ image = pil2tensor(image)
399
+ mask = image[:, :, :, 0]
400
+ out.append(mask)
401
+ outstack = torch.cat(out, dim=0)
402
+ return (outstack, 1.0 - outstack,)
403
+
404
+
405
+
406
+ class CreateShapeImageOnPath:
407
+
408
+ RETURN_TYPES = ("IMAGE", "MASK",)
409
+ RETURN_NAMES = ("image","mask", )
410
+ FUNCTION = "createshapemask"
411
+ CATEGORY = "KJNodes/image"
412
+ DESCRIPTION = """
413
+ Creates an image or batch of images with the specified shape.
414
+ Locations are center locations.
415
+ """
416
+
417
+ @classmethod
418
+ def INPUT_TYPES(s):
419
+ return {
420
+ "required": {
421
+ "shape": (
422
+ [ 'circle',
423
+ 'square',
424
+ 'triangle',
425
+ ],
426
+ {
427
+ "default": 'circle'
428
+ }),
429
+ "coordinates": ("STRING", {"forceInput": True}),
430
+ "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
431
+ "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
432
+ "shape_width": ("INT", {"default": 128,"min": 2, "max": 4096, "step": 1}),
433
+ "shape_height": ("INT", {"default": 128,"min": 2, "max": 4096, "step": 1}),
434
+ "shape_color": ("STRING", {"default": 'white'}),
435
+ "bg_color": ("STRING", {"default": 'black'}),
436
+ "blur_radius": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100, "step": 0.1}),
437
+ "intensity": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 100.0, "step": 0.01}),
438
+ },
439
+ "optional": {
440
+ "size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True}),
441
+ "trailing": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
442
+ "border_width": ("INT", {"default": 0, "min": 0, "max": 100, "step": 1}),
443
+ "border_color": ("STRING", {"default": 'black'}),
444
+ }
445
+ }
446
+
447
+ def createshapemask(self, coordinates, frame_width, frame_height, shape_width, shape_height, shape_color,
448
+ bg_color, blur_radius, shape, intensity, size_multiplier=[1.0], trailing=1.0, border_width=0, border_color='black'):
449
+
450
+ shape_color = parse_color(shape_color)
451
+ border_color = parse_color(border_color)
452
+ bg_color = parse_color(bg_color)
453
+ coords_list = parse_json_tracks(coordinates)
454
+
455
+ batch_size = len(coords_list[0])
456
+ images_list = []
457
+ masks_list = []
458
+
459
+ if not size_multiplier or len(size_multiplier) != batch_size:
460
+ size_multiplier = [1] * batch_size
461
+ else:
462
+ size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)]
463
+
464
+ previous_output = None
465
+
466
+ for i in range(batch_size):
467
+ image = Image.new("RGB", (frame_width, frame_height), bg_color)
468
+ draw = ImageDraw.Draw(image)
469
+
470
+ # Calculate the size for this frame and ensure it's not less than 0
471
+ current_width = shape_width * size_multiplier[i]
472
+ current_height = shape_height * size_multiplier[i]
473
+
474
+ for coords in coords_list:
475
+ location_x = coords[i]['x']
476
+ location_y = coords[i]['y']
477
+
478
+ if shape == 'circle' or shape == 'square':
479
+ # Define the bounding box for the shape
480
+ left_up_point = (location_x - current_width // 2, location_y - current_height // 2)
481
+ right_down_point = (location_x + current_width // 2, location_y + current_height // 2)
482
+ two_points = [left_up_point, right_down_point]
483
+
484
+ if shape == 'circle':
485
+ if border_width > 0:
486
+ draw.ellipse(two_points, fill=shape_color, outline=border_color, width=border_width)
487
+ else:
488
+ draw.ellipse(two_points, fill=shape_color)
489
+ elif shape == 'square':
490
+ if border_width > 0:
491
+ draw.rectangle(two_points, fill=shape_color, outline=border_color, width=border_width)
492
+ else:
493
+ draw.rectangle(two_points, fill=shape_color)
494
+
495
+ elif shape == 'triangle':
496
+ # Define the points for the triangle
497
+ left_up_point = (location_x - current_width // 2, location_y + current_height // 2) # bottom left
498
+ right_down_point = (location_x + current_width // 2, location_y + current_height // 2) # bottom right
499
+ top_point = (location_x, location_y - current_height // 2) # top point
500
+
501
+ if border_width > 0:
502
+ draw.polygon([top_point, left_up_point, right_down_point], fill=shape_color, outline=border_color, width=border_width)
503
+ else:
504
+ draw.polygon([top_point, left_up_point, right_down_point], fill=shape_color)
505
+
506
+ if blur_radius != 0:
507
+ image = image.filter(ImageFilter.GaussianBlur(blur_radius))
508
+ # Blend the current image with the accumulated image
509
+
510
+ image = pil2tensor(image)
511
+ if trailing != 1.0 and previous_output is not None:
512
+ # Add the decayed previous output to the current frame
513
+ image += trailing * previous_output
514
+ image = image / image.max()
515
+ previous_output = image
516
+ image = image * intensity
517
+ mask = image[:, :, :, 0]
518
+ masks_list.append(mask)
519
+ images_list.append(image)
520
+ out_images = torch.cat(images_list, dim=0).cpu().float()
521
+ out_masks = torch.cat(masks_list, dim=0)
522
+ return (out_images, out_masks)
523
+
524
+ class CreateTextOnPath:
525
+
526
+ RETURN_TYPES = ("IMAGE", "MASK", "MASK",)
527
+ RETURN_NAMES = ("image", "mask", "mask_inverted",)
528
+ FUNCTION = "createtextmask"
529
+ CATEGORY = "KJNodes/masking/generate"
530
+ DESCRIPTION = """
531
+ Creates a mask or batch of masks with the specified text.
532
+ Locations are center locations.
533
+ """
534
+
535
+ @classmethod
536
+ def INPUT_TYPES(s):
537
+ return {
538
+ "required": {
539
+ "coordinates": ("STRING", {"forceInput": True}),
540
+ "text": ("STRING", {"default": 'text', "multiline": True}),
541
+ "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
542
+ "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
543
+ "font": (folder_paths.get_filename_list("kjnodes_fonts"), ),
544
+ "font_size": ("INT", {"default": 42}),
545
+ "alignment": (
546
+ [ 'left',
547
+ 'center',
548
+ 'right'
549
+ ],
550
+ {"default": 'center'}
551
+ ),
552
+ "text_color": ("STRING", {"default": 'white'}),
553
+ },
554
+ "optional": {
555
+ "size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True}),
556
+ }
557
+ }
558
+
559
+ def createtextmask(self, coordinates, frame_width, frame_height, font, font_size, text, text_color, alignment, size_multiplier=[1.0]):
560
+ coordinates = coordinates.replace("'", '"')
561
+ coordinates = json.loads(coordinates)
562
+
563
+ batch_size = len(coordinates)
564
+ mask_list = []
565
+ image_list = []
566
+ color = parse_color(text_color)
567
+ font_path = folder_paths.get_full_path("kjnodes_fonts", font)
568
+
569
+ if len(size_multiplier) != batch_size:
570
+ size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)]
571
+
572
+ for i, coord in enumerate(coordinates):
573
+ image = Image.new("RGB", (frame_width, frame_height), "black")
574
+ draw = ImageDraw.Draw(image)
575
+ lines = text.split('\n') # Split the text into lines
576
+ # Apply the size multiplier to the font size for this iteration
577
+ current_font_size = int(font_size * size_multiplier[i])
578
+ current_font = ImageFont.truetype(font_path, current_font_size)
579
+ line_heights = [current_font.getbbox(line)[3] for line in lines] # List of line heights
580
+ total_text_height = sum(line_heights) # Total height of text block
581
+
582
+ # Calculate the starting Y position to center the block of text
583
+ start_y = coord['y'] - total_text_height // 2
584
+ for j, line in enumerate(lines):
585
+ text_width, text_height = current_font.getbbox(line)[2], line_heights[j]
586
+ if alignment == 'left':
587
+ location_x = coord['x']
588
+ elif alignment == 'center':
589
+ location_x = int(coord['x'] - text_width // 2)
590
+ elif alignment == 'right':
591
+ location_x = int(coord['x'] - text_width)
592
+
593
+ location_y = int(start_y + sum(line_heights[:j]))
594
+ text_position = (location_x, location_y)
595
+ # Draw the text
596
+ try:
597
+ draw.text(text_position, line, fill=color, font=current_font, features=['-liga'])
598
+ except:
599
+ draw.text(text_position, line, fill=color, font=current_font)
600
+
601
+ image = pil2tensor(image)
602
+ non_black_pixels = (image > 0).any(dim=-1)
603
+ mask = non_black_pixels.to(image.dtype)
604
+ mask_list.append(mask)
605
+ image_list.append(image)
606
+
607
+ out_images = torch.cat(image_list, dim=0).cpu().float()
608
+ out_masks = torch.cat(mask_list, dim=0)
609
+ return (out_images, out_masks, 1.0 - out_masks,)
610
+
611
+ class CreateGradientFromCoords:
612
+
613
+ RETURN_TYPES = ("IMAGE", )
614
+ RETURN_NAMES = ("image", )
615
+ FUNCTION = "generate"
616
+ CATEGORY = "KJNodes/image"
617
+ DESCRIPTION = """
618
+ Creates a gradient image from coordinates.
619
+ """
620
+
621
+ @classmethod
622
+ def INPUT_TYPES(s):
623
+ return {
624
+ "required": {
625
+ "coordinates": ("STRING", {"forceInput": True}),
626
+ "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
627
+ "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
628
+ "start_color": ("STRING", {"default": 'white'}),
629
+ "end_color": ("STRING", {"default": 'black'}),
630
+ "multiplier": ("FLOAT", {"default": 1.0, "min": 0.01, "max": 100.0, "step": 0.01}),
631
+ },
632
+ }
633
+
634
+ def generate(self, coordinates, frame_width, frame_height, start_color, end_color, multiplier):
635
+ # Parse the coordinates
636
+ coordinates = json.loads(coordinates.replace("'", '"'))
637
+
638
+ # Create an image
639
+ image = Image.new("RGB", (frame_width, frame_height))
640
+ draw = ImageDraw.Draw(image)
641
+
642
+ # Extract start and end points for the gradient
643
+ start_coord = coordinates[0]
644
+ end_coord = coordinates[1]
645
+
646
+ start_color = parse_color(start_color)
647
+ end_color = parse_color(end_color)
648
+
649
+ # Calculate the gradient direction (vector)
650
+ gradient_direction = (end_coord['x'] - start_coord['x'], end_coord['y'] - start_coord['y'])
651
+ gradient_length = (gradient_direction[0] ** 2 + gradient_direction[1] ** 2) ** 0.5
652
+
653
+ # Iterate over each pixel in the image
654
+ for y in range(frame_height):
655
+ for x in range(frame_width):
656
+ # Calculate the projection of the point on the gradient line
657
+ point_vector = (x - start_coord['x'], y - start_coord['y'])
658
+ projection = (point_vector[0] * gradient_direction[0] + point_vector[1] * gradient_direction[1]) / gradient_length
659
+ projection = max(min(projection, gradient_length), 0) # Clamp the projection value
660
+
661
+ # Calculate the blend factor for the current pixel
662
+ blend = projection * multiplier / gradient_length
663
+
664
+ # Determine the color of the current pixel
665
+ color = (
666
+ int(start_color[0] + (end_color[0] - start_color[0]) * blend),
667
+ int(start_color[1] + (end_color[1] - start_color[1]) * blend),
668
+ int(start_color[2] + (end_color[2] - start_color[2]) * blend)
669
+ )
670
+
671
+ # Set the pixel color
672
+ draw.point((x, y), fill=color)
673
+
674
+ # Convert the PIL image to a tensor (assuming such a function exists in your context)
675
+ image_tensor = pil2tensor(image)
676
+
677
+ return (image_tensor,)
678
+
679
+ class GradientToFloat:
680
+
681
+ RETURN_TYPES = ("FLOAT", "FLOAT",)
682
+ RETURN_NAMES = ("float_x", "float_y", )
683
+ FUNCTION = "sample"
684
+ CATEGORY = "KJNodes/image"
685
+ DESCRIPTION = """
686
+ Calculates list of floats from image.
687
+ """
688
+
689
+ @classmethod
690
+ def INPUT_TYPES(s):
691
+ return {
692
+ "required": {
693
+ "image": ("IMAGE", ),
694
+ "steps": ("INT", {"default": 10, "min": 2, "max": 10000, "step": 1}),
695
+ },
696
+ }
697
+
698
+ def sample(self, image, steps):
699
+ # Assuming image is a tensor with shape [B, H, W, C]
700
+ B, H, W, C = image.shape
701
+
702
+ # Sample along the width axis (W)
703
+ w_intervals = torch.linspace(0, W - 1, steps=steps, dtype=torch.int64)
704
+ # Assuming we're sampling from the first batch and the first channel
705
+ w_sampled = image[0, :, w_intervals, 0]
706
+
707
+ # Sample along the height axis (H)
708
+ h_intervals = torch.linspace(0, H - 1, steps=steps, dtype=torch.int64)
709
+ # Assuming we're sampling from the first batch and the first channel
710
+ h_sampled = image[0, h_intervals, :, 0]
711
+
712
+ # Taking the mean across the height for width sampling, and across the width for height sampling
713
+ w_values = w_sampled.mean(dim=0).tolist()
714
+ h_values = h_sampled.mean(dim=1).tolist()
715
+
716
+ return (w_values, h_values)
717
+
718
+ class MaskOrImageToWeight:
719
+
720
+ @classmethod
721
+ def INPUT_TYPES(s):
722
+ return {
723
+ "required": {
724
+ "output_type": (
725
+ [
726
+ 'list',
727
+ 'pandas series',
728
+ 'tensor',
729
+ 'string'
730
+ ],
731
+ {
732
+ "default": 'list'
733
+ }),
734
+ },
735
+ "optional": {
736
+ "images": ("IMAGE",),
737
+ "masks": ("MASK",),
738
+ },
739
+
740
+ }
741
+ RETURN_TYPES = ("FLOAT", "STRING",)
742
+ FUNCTION = "execute"
743
+ CATEGORY = "KJNodes/weights"
744
+ DESCRIPTION = """
745
+ Gets the mean values from mask or image batch
746
+ and returns that as the selected output type.
747
+ """
748
+
749
+ def execute(self, output_type, images=None, masks=None):
750
+ mean_values = []
751
+ if masks is not None and images is None:
752
+ for mask in masks:
753
+ mean_values.append(mask.mean().item())
754
+ elif masks is None and images is not None:
755
+ for image in images:
756
+ mean_values.append(image.mean().item())
757
+ elif masks is not None and images is not None:
758
+ raise Exception("MaskOrImageToWeight: Use either mask or image input only.")
759
+
760
+ # Convert mean_values to the specified output_type
761
+ if output_type == 'list':
762
+ out = mean_values
763
+ elif output_type == 'pandas series':
764
+ try:
765
+ import pandas as pd
766
+ except:
767
+ raise Exception("MaskOrImageToWeight: pandas is not installed. Please install pandas to use this output_type")
768
+ out = pd.Series(mean_values),
769
+ elif output_type == 'tensor':
770
+ out = torch.tensor(mean_values, dtype=torch.float32),
771
+ return (out, [str(value) for value in mean_values],)
772
+
773
+ class WeightScheduleConvert:
774
+
775
+ @classmethod
776
+ def INPUT_TYPES(s):
777
+ return {
778
+ "required": {
779
+ "input_values": ("FLOAT", {"default": 0.0, "forceInput": True}),
780
+ "output_type": (
781
+ [
782
+ 'match_input',
783
+ 'list',
784
+ 'pandas series',
785
+ 'tensor',
786
+ ],
787
+ {
788
+ "default": 'list'
789
+ }),
790
+ "invert": ("BOOLEAN", {"default": False}),
791
+ "repeat": ("INT", {"default": 1,"min": 1, "max": 255, "step": 1}),
792
+ },
793
+ "optional": {
794
+ "remap_to_frames": ("INT", {"default": 0}),
795
+ "interpolation_curve": ("FLOAT", {"forceInput": True}),
796
+ "remap_values": ("BOOLEAN", {"default": False}),
797
+ "remap_min": ("FLOAT", {"default": 0.0, "min": -100000, "max": 100000.0, "step": 0.01}),
798
+ "remap_max": ("FLOAT", {"default": 1.0, "min": -100000, "max": 100000.0, "step": 0.01}),
799
+ },
800
+
801
+ }
802
+ RETURN_TYPES = ("FLOAT", "STRING", "INT",)
803
+ FUNCTION = "execute"
804
+ CATEGORY = "KJNodes/weights"
805
+ DESCRIPTION = """
806
+ Converts different value lists/series to another type.
807
+ """
808
+
809
+ def detect_input_type(self, input_values):
810
+ import pandas as pd
811
+ if isinstance(input_values, list):
812
+ return 'list'
813
+ elif isinstance(input_values, pd.Series):
814
+ return 'pandas series'
815
+ elif isinstance(input_values, torch.Tensor):
816
+ return 'tensor'
817
+ else:
818
+ raise ValueError("Unsupported input type")
819
+
820
+ 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):
821
+ import pandas as pd
822
+ input_type = self.detect_input_type(input_values)
823
+
824
+ if input_type == 'pandas series':
825
+ float_values = input_values.tolist()
826
+ elif input_type == 'tensor':
827
+ float_values = input_values
828
+ else:
829
+ float_values = input_values
830
+
831
+ if invert:
832
+ float_values = [1 - value for value in float_values]
833
+
834
+ if interpolation_curve is not None:
835
+ interpolated_pattern = []
836
+ orig_float_values = float_values
837
+ for value in interpolation_curve:
838
+ min_val = min(orig_float_values)
839
+ max_val = max(orig_float_values)
840
+ # Normalize the values to [0, 1]
841
+ normalized_values = [(value - min_val) / (max_val - min_val) for value in orig_float_values]
842
+ # Interpolate the normalized values to the new frame count
843
+ remapped_float_values = np.interp(np.linspace(0, 1, int(remap_to_frames * value)), np.linspace(0, 1, len(normalized_values)), normalized_values).tolist()
844
+ interpolated_pattern.extend(remapped_float_values)
845
+ float_values = interpolated_pattern
846
+ else:
847
+ # Remap float_values to match target_frame_amount
848
+ if remap_to_frames > 0 and remap_to_frames != len(float_values):
849
+ min_val = min(float_values)
850
+ max_val = max(float_values)
851
+ # Normalize the values to [0, 1]
852
+ normalized_values = [(value - min_val) / (max_val - min_val) for value in float_values]
853
+ # Interpolate the normalized values to the new frame count
854
+ float_values = np.interp(np.linspace(0, 1, remap_to_frames), np.linspace(0, 1, len(normalized_values)), normalized_values).tolist()
855
+
856
+ float_values = float_values * repeat
857
+ if remap_values:
858
+ float_values = self.remap_values(float_values, remap_min, remap_max)
859
+
860
+ if output_type == 'list':
861
+ out = float_values,
862
+ elif output_type == 'pandas series':
863
+ out = pd.Series(float_values),
864
+ elif output_type == 'tensor':
865
+ if input_type == 'pandas series':
866
+ out = torch.tensor(float_values.values, dtype=torch.float32),
867
+ else:
868
+ out = torch.tensor(float_values, dtype=torch.float32),
869
+ elif output_type == 'match_input':
870
+ out = float_values,
871
+ return (out, [str(value) for value in float_values], [int(value) for value in float_values])
872
+
873
+ def remap_values(self, values, target_min, target_max):
874
+ # Determine the current range
875
+ current_min = min(values)
876
+ current_max = max(values)
877
+ current_range = current_max - current_min
878
+
879
+ # Determine the target range
880
+ target_range = target_max - target_min
881
+
882
+ # Perform the linear interpolation for each value
883
+ remapped_values = [(value - current_min) / current_range * target_range + target_min for value in values]
884
+
885
+ return remapped_values
886
+
887
+
888
+ class FloatToMask:
889
+
890
+ @classmethod
891
+ def INPUT_TYPES(s):
892
+ return {
893
+ "required": {
894
+ "input_values": ("FLOAT", {"forceInput": True, "default": 0}),
895
+ "width": ("INT", {"default": 100, "min": 1}),
896
+ "height": ("INT", {"default": 100, "min": 1}),
897
+ },
898
+ }
899
+ RETURN_TYPES = ("MASK",)
900
+ FUNCTION = "execute"
901
+ CATEGORY = "KJNodes/masking/generate"
902
+ DESCRIPTION = """
903
+ Generates a batch of masks based on the input float values.
904
+ The batch size is determined by the length of the input float values.
905
+ Each mask is generated with the specified width and height.
906
+ """
907
+
908
+ def execute(self, input_values, width, height):
909
+ import pandas as pd
910
+ # Ensure input_values is a list
911
+ if isinstance(input_values, (float, int)):
912
+ input_values = [input_values]
913
+ elif isinstance(input_values, pd.Series):
914
+ input_values = input_values.tolist()
915
+ elif isinstance(input_values, list) and all(isinstance(item, list) for item in input_values):
916
+ input_values = [item for sublist in input_values for item in sublist]
917
+
918
+ # Generate a batch of masks based on the input_values
919
+ masks = []
920
+ for value in input_values:
921
+ # Assuming value is a float between 0 and 1 representing the mask's intensity
922
+ mask = torch.ones((height, width), dtype=torch.float32) * value
923
+ masks.append(mask)
924
+ masks_out = torch.stack(masks, dim=0)
925
+
926
+ return(masks_out,)
927
+ class WeightScheduleExtend:
928
+
929
+ @classmethod
930
+ def INPUT_TYPES(s):
931
+ return {
932
+ "required": {
933
+ "input_values_1": ("FLOAT", {"default": 0.0, "forceInput": True}),
934
+ "input_values_2": ("FLOAT", {"default": 0.0, "forceInput": True}),
935
+ "output_type": (
936
+ [
937
+ 'match_input',
938
+ 'list',
939
+ 'pandas series',
940
+ 'tensor',
941
+ ],
942
+ {
943
+ "default": 'match_input'
944
+ }),
945
+ },
946
+
947
+ }
948
+ RETURN_TYPES = ("FLOAT",)
949
+ FUNCTION = "execute"
950
+ CATEGORY = "KJNodes/weights"
951
+ DESCRIPTION = """
952
+ Extends, and converts if needed, different value lists/series
953
+ """
954
+
955
+ def detect_input_type(self, input_values):
956
+ import pandas as pd
957
+ if isinstance(input_values, list):
958
+ return 'list'
959
+ elif isinstance(input_values, pd.Series):
960
+ return 'pandas series'
961
+ elif isinstance(input_values, torch.Tensor):
962
+ return 'tensor'
963
+ else:
964
+ raise ValueError("Unsupported input type")
965
+
966
+ def execute(self, input_values_1, input_values_2, output_type):
967
+ import pandas as pd
968
+ input_type_1 = self.detect_input_type(input_values_1)
969
+ input_type_2 = self.detect_input_type(input_values_2)
970
+ # Convert input_values_2 to the same format as input_values_1 if they do not match
971
+ if not input_type_1 == input_type_2:
972
+ print("Converting input_values_2 to the same format as input_values_1")
973
+ if input_type_1 == 'pandas series':
974
+ # Convert input_values_2 to a pandas Series
975
+ float_values_2 = pd.Series(input_values_2)
976
+ elif input_type_1 == 'tensor':
977
+ # Convert input_values_2 to a tensor
978
+ float_values_2 = torch.tensor(input_values_2, dtype=torch.float32)
979
+ else:
980
+ print("Input types match, no conversion needed")
981
+ # If the types match, no conversion is needed
982
+ float_values_2 = input_values_2
983
+
984
+ float_values = input_values_1 + float_values_2
985
+
986
+ if output_type == 'list':
987
+ return float_values,
988
+ elif output_type == 'pandas series':
989
+ return pd.Series(float_values),
990
+ elif output_type == 'tensor':
991
+ if input_type_1 == 'pandas series':
992
+ return torch.tensor(float_values.values, dtype=torch.float32),
993
+ else:
994
+ return torch.tensor(float_values, dtype=torch.float32),
995
+ elif output_type == 'match_input':
996
+ return float_values,
997
+ else:
998
+ raise ValueError(f"Unsupported output_type: {output_type}")
999
+
1000
+ class FloatToSigmas:
1001
+ @classmethod
1002
+ def INPUT_TYPES(s):
1003
+ return {"required":
1004
+ {
1005
+ "float_list": ("FLOAT", {"default": 0.0, "forceInput": True}),
1006
+ }
1007
+ }
1008
+ RETURN_TYPES = ("SIGMAS",)
1009
+ RETURN_NAMES = ("SIGMAS",)
1010
+ CATEGORY = "KJNodes/noise"
1011
+ FUNCTION = "customsigmas"
1012
+ DESCRIPTION = """
1013
+ Creates a sigmas tensor from list of float values.
1014
+
1015
+ """
1016
+ def customsigmas(self, float_list):
1017
+ return torch.tensor(float_list, dtype=torch.float32),
1018
+
1019
+ class SigmasToFloat:
1020
+ @classmethod
1021
+ def INPUT_TYPES(s):
1022
+ return {"required":
1023
+ {
1024
+ "sigmas": ("SIGMAS",),
1025
+ }
1026
+ }
1027
+ RETURN_TYPES = ("FLOAT",)
1028
+ RETURN_NAMES = ("float",)
1029
+ CATEGORY = "KJNodes/noise"
1030
+ FUNCTION = "customsigmas"
1031
+ DESCRIPTION = """
1032
+ Creates a float list from sigmas tensors.
1033
+
1034
+ """
1035
+ def customsigmas(self, sigmas):
1036
+ return sigmas.tolist(),
1037
+
1038
+ class GLIGENTextBoxApplyBatchCoords:
1039
+ @classmethod
1040
+ def INPUT_TYPES(s):
1041
+ return {"required": {"conditioning_to": ("CONDITIONING", ),
1042
+ "latents": ("LATENT", ),
1043
+ "clip": ("CLIP", ),
1044
+ "gligen_textbox_model": ("GLIGEN", ),
1045
+ "coordinates": ("STRING", {"forceInput": True}),
1046
+ "text": ("STRING", {"multiline": True}),
1047
+ "width": ("INT", {"default": 128, "min": 8, "max": 4096, "step": 8}),
1048
+ "height": ("INT", {"default": 128, "min": 8, "max": 4096, "step": 8}),
1049
+ },
1050
+ "optional": {"size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True})},
1051
+ }
1052
+ RETURN_TYPES = ("CONDITIONING", "IMAGE", )
1053
+ RETURN_NAMES = ("conditioning", "coord_preview", )
1054
+ FUNCTION = "append"
1055
+ CATEGORY = "KJNodes/experimental"
1056
+ DESCRIPTION = """
1057
+ This node allows scheduling GLIGEN text box positions in a batch,
1058
+ to be used with AnimateDiff-Evolved. Intended to pair with the
1059
+ Spline Editor -node.
1060
+
1061
+ GLIGEN model can be downloaded through the Manage's "Install Models" menu.
1062
+ Or directly from here:
1063
+ https://huggingface.co/comfyanonymous/GLIGEN_pruned_safetensors/tree/main
1064
+
1065
+ Inputs:
1066
+ - **latents** input is used to calculate batch size
1067
+ - **clip** is your standard text encoder, use same as for the main prompt
1068
+ - **gligen_textbox_model** connects to GLIGEN Loader
1069
+ - **coordinates** takes a json string of points, directly compatible
1070
+ with the spline editor node.
1071
+ - **text** is the part of the prompt to set position for
1072
+ - **width** and **height** are the size of the GLIGEN bounding box
1073
+
1074
+ Outputs:
1075
+ - **conditioning** goes between to clip text encode and the sampler
1076
+ - **coord_preview** is an optional preview of the coordinates and
1077
+ bounding boxes.
1078
+
1079
+ """
1080
+
1081
+ def append(self, latents, coordinates, conditioning_to, clip, gligen_textbox_model, text, width, height, size_multiplier=[1.0]):
1082
+ coordinates = json.loads(coordinates.replace("'", '"'))
1083
+ coordinates = [(coord['x'], coord['y']) for coord in coordinates]
1084
+
1085
+ batch_size = sum(tensor.size(0) for tensor in latents.values())
1086
+ if len(coordinates) != batch_size:
1087
+ print("GLIGENTextBoxApplyBatchCoords WARNING: The number of coordinates does not match the number of latents")
1088
+
1089
+ c = []
1090
+ _, cond_pooled = clip.encode_from_tokens(clip.tokenize(text), return_pooled=True)
1091
+
1092
+ for t in conditioning_to:
1093
+ n = [t[0], t[1].copy()]
1094
+
1095
+ position_params_batch = [[] for _ in range(batch_size)] # Initialize a list of empty lists for each batch item
1096
+ if len(size_multiplier) != batch_size:
1097
+ size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)]
1098
+
1099
+ for i in range(batch_size):
1100
+ x_position, y_position = coordinates[i]
1101
+ 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)
1102
+ position_params_batch[i].append(position_param) # Append position_param to the correct sublist
1103
+
1104
+ prev = []
1105
+ if "gligen" in n[1]:
1106
+ prev = n[1]['gligen'][2]
1107
+ else:
1108
+ prev = [[] for _ in range(batch_size)]
1109
+ # Concatenate prev and position_params_batch, ensuring both are lists of lists
1110
+ # and each sublist corresponds to a batch item
1111
+ combined_position_params = [prev_item + batch_item for prev_item, batch_item in zip(prev, position_params_batch)]
1112
+ n[1]['gligen'] = ("position_batched", gligen_textbox_model, combined_position_params)
1113
+ c.append(n)
1114
+
1115
+ image_height = latents['samples'].shape[-2] * 8
1116
+ image_width = latents['samples'].shape[-1] * 8
1117
+ plot_image_tensor = plot_coordinates_to_tensor(coordinates, image_height, image_width, height, width, size_multiplier, text)
1118
+
1119
+ return (c, plot_image_tensor,)
1120
+
1121
+ class CreateInstanceDiffusionTracking:
1122
+
1123
+ RETURN_TYPES = ("TRACKING", "STRING", "INT", "INT", "INT", "INT",)
1124
+ RETURN_NAMES = ("tracking", "prompt", "width", "height", "bbox_width", "bbox_height",)
1125
+ FUNCTION = "tracking"
1126
+ CATEGORY = "KJNodes/InstanceDiffusion"
1127
+ DESCRIPTION = """
1128
+ Creates tracking data to be used with InstanceDiffusion:
1129
+ https://github.com/logtd/ComfyUI-InstanceDiffusion
1130
+
1131
+ InstanceDiffusion prompt format:
1132
+ "class_id.class_name": "prompt",
1133
+ for example:
1134
+ "1.head": "((head))",
1135
+ """
1136
+
1137
+ @classmethod
1138
+ def INPUT_TYPES(s):
1139
+ return {
1140
+ "required": {
1141
+ "coordinates": ("STRING", {"forceInput": True}),
1142
+ "width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
1143
+ "height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
1144
+ "bbox_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
1145
+ "bbox_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
1146
+ "class_name": ("STRING", {"default": "class_name"}),
1147
+ "class_id": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}),
1148
+ "prompt": ("STRING", {"default": "prompt", "multiline": True}),
1149
+ },
1150
+ "optional": {
1151
+ "size_multiplier": ("FLOAT", {"default": [1.0], "forceInput": True}),
1152
+ "fit_in_frame": ("BOOLEAN", {"default": True}),
1153
+ }
1154
+ }
1155
+
1156
+ def tracking(self, coordinates, class_name, class_id, width, height, bbox_width, bbox_height, prompt, size_multiplier=[1.0], fit_in_frame=True):
1157
+ # Define the number of images in the batch
1158
+ coordinates = coordinates.replace("'", '"')
1159
+ coordinates = json.loads(coordinates)
1160
+
1161
+ tracked = {}
1162
+ tracked[class_name] = {}
1163
+ batch_size = len(coordinates)
1164
+ # Initialize a list to hold the coordinates for the current ID
1165
+ id_coordinates = []
1166
+ if not size_multiplier or len(size_multiplier) != batch_size:
1167
+ size_multiplier = [0] * batch_size
1168
+ else:
1169
+ size_multiplier = size_multiplier * (batch_size // len(size_multiplier)) + size_multiplier[:batch_size % len(size_multiplier)]
1170
+ for i, coord in enumerate(coordinates):
1171
+ x = coord['x']
1172
+ y = coord['y']
1173
+ adjusted_bbox_width = bbox_width * size_multiplier[i]
1174
+ adjusted_bbox_height = bbox_height * size_multiplier[i]
1175
+ # Calculate the top left and bottom right coordinates
1176
+ top_left_x = x - adjusted_bbox_width // 2
1177
+ top_left_y = y - adjusted_bbox_height // 2
1178
+ bottom_right_x = x + adjusted_bbox_width // 2
1179
+ bottom_right_y = y + adjusted_bbox_height // 2
1180
+
1181
+ if fit_in_frame:
1182
+ # Clip the coordinates to the frame boundaries
1183
+ top_left_x = max(0, top_left_x)
1184
+ top_left_y = max(0, top_left_y)
1185
+ bottom_right_x = min(width, bottom_right_x)
1186
+ bottom_right_y = min(height, bottom_right_y)
1187
+ # Ensure width and height are positive
1188
+ adjusted_bbox_width = max(1, bottom_right_x - top_left_x)
1189
+ adjusted_bbox_height = max(1, bottom_right_y - top_left_y)
1190
+
1191
+ # Update the coordinates with the new width and height
1192
+ bottom_right_x = top_left_x + adjusted_bbox_width
1193
+ bottom_right_y = top_left_y + adjusted_bbox_height
1194
+
1195
+ # Append the top left and bottom right coordinates to the list for the current ID
1196
+ id_coordinates.append([top_left_x, top_left_y, bottom_right_x, bottom_right_y, width, height])
1197
+
1198
+ class_id = int(class_id)
1199
+ # Assign the list of coordinates to the specified ID within the class_id dictionary
1200
+ tracked[class_name][class_id] = id_coordinates
1201
+
1202
+ prompt_string = ""
1203
+ for class_name, class_data in tracked.items():
1204
+ for class_id in class_data.keys():
1205
+ class_id_str = str(class_id)
1206
+ # Use the incoming prompt for each class name and ID
1207
+ prompt_string += f'"{class_id_str}.{class_name}": "({prompt})",\n'
1208
+
1209
+ # Remove the last comma and newline
1210
+ prompt_string = prompt_string.rstrip(",\n")
1211
+
1212
+ return (tracked, prompt_string, width, height, bbox_width, bbox_height)
1213
+
1214
+ class AppendInstanceDiffusionTracking:
1215
+
1216
+ RETURN_TYPES = ("TRACKING", "STRING",)
1217
+ RETURN_NAMES = ("tracking", "prompt",)
1218
+ FUNCTION = "append"
1219
+ CATEGORY = "KJNodes/InstanceDiffusion"
1220
+ DESCRIPTION = """
1221
+ Appends tracking data to be used with InstanceDiffusion:
1222
+ https://github.com/logtd/ComfyUI-InstanceDiffusion
1223
+
1224
+ """
1225
+
1226
+ @classmethod
1227
+ def INPUT_TYPES(s):
1228
+ return {
1229
+ "required": {
1230
+ "tracking_1": ("TRACKING", {"forceInput": True}),
1231
+ "tracking_2": ("TRACKING", {"forceInput": True}),
1232
+ },
1233
+ "optional": {
1234
+ "prompt_1": ("STRING", {"default": "", "forceInput": True}),
1235
+ "prompt_2": ("STRING", {"default": "", "forceInput": True}),
1236
+ }
1237
+ }
1238
+
1239
+ def append(self, tracking_1, tracking_2, prompt_1="", prompt_2=""):
1240
+ tracking_copy = tracking_1.copy()
1241
+ # Check for existing class names and class IDs, and raise an error if they exist
1242
+ for class_name, class_data in tracking_2.items():
1243
+ if class_name not in tracking_copy:
1244
+ tracking_copy[class_name] = class_data
1245
+ else:
1246
+ # If the class name exists, merge the class data from tracking_2 into tracking_copy
1247
+ # This will add new class IDs under the same class name without raising an error
1248
+ tracking_copy[class_name].update(class_data)
1249
+ prompt_string = prompt_1 + "," + prompt_2
1250
+ return (tracking_copy, prompt_string)
1251
+
1252
+ class InterpolateCoords:
1253
+
1254
+ RETURN_TYPES = ("STRING",)
1255
+ RETURN_NAMES = ("coordinates",)
1256
+ FUNCTION = "interpolate"
1257
+ CATEGORY = "KJNodes/experimental"
1258
+ DESCRIPTION = """
1259
+ Interpolates coordinates based on a curve.
1260
+ """
1261
+
1262
+ @classmethod
1263
+ def INPUT_TYPES(s):
1264
+ return {
1265
+ "required": {
1266
+ "coordinates": ("STRING", {"forceInput": True}),
1267
+ "interpolation_curve": ("FLOAT", {"forceInput": True}),
1268
+
1269
+ },
1270
+ }
1271
+
1272
+ def interpolate(self, coordinates, interpolation_curve):
1273
+ # Parse the JSON string to get the list of coordinates
1274
+ coordinates = json.loads(coordinates.replace("'", '"'))
1275
+
1276
+ # Convert the list of dictionaries to a list of (x, y) tuples for easier processing
1277
+ coordinates = [(coord['x'], coord['y']) for coord in coordinates]
1278
+
1279
+ # Calculate the total length of the original path
1280
+ path_length = sum(np.linalg.norm(np.array(coordinates[i]) - np.array(coordinates[i-1]))
1281
+ for i in range(1, len(coordinates)))
1282
+
1283
+ # Initialize variables for interpolation
1284
+ interpolated_coords = []
1285
+ current_length = 0
1286
+ current_index = 0
1287
+
1288
+ # Iterate over the normalized curve
1289
+ for normalized_length in interpolation_curve:
1290
+ target_length = normalized_length * path_length # Convert to the original scale
1291
+ while current_index < len(coordinates) - 1:
1292
+ segment_start, segment_end = np.array(coordinates[current_index]), np.array(coordinates[current_index + 1])
1293
+ segment_length = np.linalg.norm(segment_end - segment_start)
1294
+ if current_length + segment_length >= target_length:
1295
+ break
1296
+ current_length += segment_length
1297
+ current_index += 1
1298
+
1299
+ # Interpolate between the last two points
1300
+ if current_index < len(coordinates) - 1:
1301
+ p1, p2 = np.array(coordinates[current_index]), np.array(coordinates[current_index + 1])
1302
+ segment_length = np.linalg.norm(p2 - p1)
1303
+ if segment_length > 0:
1304
+ t = (target_length - current_length) / segment_length
1305
+ interpolated_point = p1 + t * (p2 - p1)
1306
+ interpolated_coords.append(interpolated_point.tolist())
1307
+ else:
1308
+ interpolated_coords.append(p1.tolist())
1309
+ else:
1310
+ # If the target_length is at or beyond the end of the path, add the last coordinate
1311
+ interpolated_coords.append(coordinates[-1])
1312
+
1313
+ # Convert back to string format if necessary
1314
+ interpolated_coords_str = "[" + ", ".join([f"{{'x': {round(coord[0])}, 'y': {round(coord[1])}}}" for coord in interpolated_coords]) + "]"
1315
+ print(interpolated_coords_str)
1316
+
1317
+ return (interpolated_coords_str,)
1318
+
1319
+ class DrawInstanceDiffusionTracking:
1320
+
1321
+ RETURN_TYPES = ("IMAGE",)
1322
+ RETURN_NAMES = ("image", )
1323
+ FUNCTION = "draw"
1324
+ CATEGORY = "KJNodes/InstanceDiffusion"
1325
+ DESCRIPTION = """
1326
+ Draws the tracking data from
1327
+ CreateInstanceDiffusionTracking -node.
1328
+
1329
+ """
1330
+
1331
+ @classmethod
1332
+ def INPUT_TYPES(s):
1333
+ return {
1334
+ "required": {
1335
+ "image": ("IMAGE", ),
1336
+ "tracking": ("TRACKING", {"forceInput": True}),
1337
+ "box_line_width": ("INT", {"default": 2, "min": 1, "max": 10, "step": 1}),
1338
+ "draw_text": ("BOOLEAN", {"default": True}),
1339
+ "font": (folder_paths.get_filename_list("kjnodes_fonts"), ),
1340
+ "font_size": ("INT", {"default": 20}),
1341
+ },
1342
+ }
1343
+
1344
+ def draw(self, image, tracking, box_line_width, draw_text, font, font_size):
1345
+ import matplotlib.cm as cm
1346
+
1347
+ modified_images = []
1348
+
1349
+ colormap = cm.get_cmap('rainbow', len(tracking))
1350
+ if draw_text:
1351
+ font_path = folder_paths.get_full_path("kjnodes_fonts", font)
1352
+ font = ImageFont.truetype(font_path, font_size)
1353
+
1354
+ # Iterate over each image in the batch
1355
+ for i in range(image.shape[0]):
1356
+ # Extract the current image and convert it to a PIL image
1357
+ current_image = image[i, :, :, :].permute(2, 0, 1)
1358
+ pil_image = transforms.ToPILImage()(current_image)
1359
+
1360
+ draw = ImageDraw.Draw(pil_image)
1361
+
1362
+ # Iterate over the bounding boxes for the current image
1363
+ for j, (class_name, class_data) in enumerate(tracking.items()):
1364
+ for class_id, bbox_list in class_data.items():
1365
+ # Check if the current index is within the bounds of the bbox_list
1366
+ if i < len(bbox_list):
1367
+ bbox = bbox_list[i]
1368
+ # Ensure bbox is a list or tuple before unpacking
1369
+ if isinstance(bbox, (list, tuple)):
1370
+ x1, y1, x2, y2, _, _ = bbox
1371
+ # Convert coordinates to integers
1372
+ x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
1373
+ # Generate a color from the rainbow colormap
1374
+ color = tuple(int(255 * x) for x in colormap(j / len(tracking)))[:3]
1375
+ # Draw the bounding box on the image with the generated color
1376
+ draw.rectangle([x1, y1, x2, y2], outline=color, width=box_line_width)
1377
+ if draw_text:
1378
+ # Draw the class name and ID as text above the box with the generated color
1379
+ text = f"{class_id}.{class_name}"
1380
+ # Calculate the width and height of the text
1381
+ _, _, text_width, text_height = draw.textbbox((0, 0), text=text, font=font)
1382
+ # Position the text above the top-left corner of the box
1383
+ text_position = (x1, y1 - text_height)
1384
+ draw.text(text_position, text, fill=color, font=font)
1385
+ else:
1386
+ print(f"Unexpected data type for bbox: {type(bbox)}")
1387
+
1388
+ # Convert the drawn image back to a torch tensor and adjust back to (H, W, C)
1389
+ modified_image_tensor = transforms.ToTensor()(pil_image).permute(1, 2, 0)
1390
+ modified_images.append(modified_image_tensor)
1391
+
1392
+ # Stack the modified images back into a batch
1393
+ image_tensor_batch = torch.stack(modified_images).cpu().float()
1394
+
1395
+ return image_tensor_batch,
1396
+
1397
+ class PointsEditor:
1398
+ @classmethod
1399
+ def INPUT_TYPES(cls):
1400
+ return {
1401
+ "required": {
1402
+ "points_store": ("STRING", {"multiline": False}),
1403
+ "coordinates": ("STRING", {"multiline": False}),
1404
+ "neg_coordinates": ("STRING", {"multiline": False}),
1405
+ "bbox_store": ("STRING", {"multiline": False}),
1406
+ "bboxes": ("STRING", {"multiline": False}),
1407
+ "bbox_format": (
1408
+ [
1409
+ 'xyxy',
1410
+ 'xywh',
1411
+ ],
1412
+ ),
1413
+ "width": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}),
1414
+ "height": ("INT", {"default": 512, "min": 8, "max": 4096, "step": 8}),
1415
+ "normalize": ("BOOLEAN", {"default": False}),
1416
+ },
1417
+ "optional": {
1418
+ "bg_image": ("IMAGE", ),
1419
+ },
1420
+ }
1421
+
1422
+ RETURN_TYPES = ("STRING", "STRING", "BBOX", "MASK", "IMAGE")
1423
+ RETURN_NAMES = ("positive_coords", "negative_coords", "bbox", "bbox_mask", "cropped_image")
1424
+ FUNCTION = "pointdata"
1425
+ CATEGORY = "KJNodes/experimental"
1426
+ DESCRIPTION = """
1427
+ # WORK IN PROGRESS
1428
+ Do not count on this as part of your workflow yet,
1429
+ probably contains lots of bugs and stability is not
1430
+ guaranteed!!
1431
+
1432
+ ## Graphical editor to create coordinates
1433
+
1434
+ **Shift + click** to add a positive (green) point.
1435
+ **Shift + right click** to add a negative (red) point.
1436
+ **Ctrl + click** to draw a box.
1437
+ **Right click on a point** to delete it.
1438
+ Note that you can't delete from start/end of the points array.
1439
+
1440
+ To add an image select the node and copy/paste or drag in the image.
1441
+ Or from the bg_image input on queue (first frame of the batch).
1442
+
1443
+ **THE IMAGE IS SAVED TO THE NODE AND WORKFLOW METADATA**
1444
+ you can clear the image from the context menu by right clicking on the canvas
1445
+
1446
+ """
1447
+
1448
+ def pointdata(self, points_store, bbox_store, width, height, coordinates, neg_coordinates, normalize, bboxes, bbox_format="xyxy", bg_image=None):
1449
+ coordinates = json.loads(coordinates)
1450
+ pos_coordinates = []
1451
+ for coord in coordinates:
1452
+ coord['x'] = int(round(coord['x']))
1453
+ coord['y'] = int(round(coord['y']))
1454
+ if normalize:
1455
+ norm_x = coord['x'] / width
1456
+ norm_y = coord['y'] / height
1457
+ pos_coordinates.append({'x': norm_x, 'y': norm_y})
1458
+ else:
1459
+ pos_coordinates.append({'x': coord['x'], 'y': coord['y']})
1460
+
1461
+ if neg_coordinates:
1462
+ coordinates = json.loads(neg_coordinates)
1463
+ neg_coordinates = []
1464
+ for coord in coordinates:
1465
+ coord['x'] = int(round(coord['x']))
1466
+ coord['y'] = int(round(coord['y']))
1467
+ if normalize:
1468
+ norm_x = coord['x'] / width
1469
+ norm_y = coord['y'] / height
1470
+ neg_coordinates.append({'x': norm_x, 'y': norm_y})
1471
+ else:
1472
+ neg_coordinates.append({'x': coord['x'], 'y': coord['y']})
1473
+
1474
+ # Create a blank mask
1475
+ mask = np.zeros((height, width), dtype=np.uint8)
1476
+ bboxes = json.loads(bboxes)
1477
+ print(bboxes)
1478
+ valid_bboxes = []
1479
+ for bbox in bboxes:
1480
+ if (bbox.get("startX") is None or
1481
+ bbox.get("startY") is None or
1482
+ bbox.get("endX") is None or
1483
+ bbox.get("endY") is None):
1484
+ continue # Skip this bounding box if any value is None
1485
+ else:
1486
+ # Ensure that endX and endY are greater than startX and startY
1487
+ x_min = min(int(bbox["startX"]), int(bbox["endX"]))
1488
+ y_min = min(int(bbox["startY"]), int(bbox["endY"]))
1489
+ x_max = max(int(bbox["startX"]), int(bbox["endX"]))
1490
+ y_max = max(int(bbox["startY"]), int(bbox["endY"]))
1491
+
1492
+ valid_bboxes.append((x_min, y_min, x_max, y_max))
1493
+
1494
+ bboxes_xyxy = []
1495
+ for bbox in valid_bboxes:
1496
+ x_min, y_min, x_max, y_max = bbox
1497
+ bboxes_xyxy.append((x_min, y_min, x_max, y_max))
1498
+ mask[y_min:y_max, x_min:x_max] = 1 # Fill the bounding box area with 1s
1499
+
1500
+ if bbox_format == "xywh":
1501
+ bboxes_xywh = []
1502
+ for bbox in valid_bboxes:
1503
+ x_min, y_min, x_max, y_max = bbox
1504
+ width = x_max - x_min
1505
+ height = y_max - y_min
1506
+ bboxes_xywh.append((x_min, y_min, width, height))
1507
+ bboxes = bboxes_xywh
1508
+ else:
1509
+ bboxes = bboxes_xyxy
1510
+
1511
+ mask_tensor = torch.from_numpy(mask)
1512
+ mask_tensor = mask_tensor.unsqueeze(0).float().cpu()
1513
+
1514
+ if bg_image is not None and len(valid_bboxes) > 0:
1515
+ x_min, y_min, x_max, y_max = bboxes[0]
1516
+ cropped_image = bg_image[:, y_min:y_max, x_min:x_max, :]
1517
+
1518
+ elif bg_image is not None:
1519
+ cropped_image = bg_image
1520
+
1521
+ if bg_image is None:
1522
+ return (json.dumps(pos_coordinates), json.dumps(neg_coordinates), bboxes, mask_tensor)
1523
+ else:
1524
+ transform = transforms.ToPILImage()
1525
+ image = transform(bg_image[0].permute(2, 0, 1))
1526
+ buffered = io.BytesIO()
1527
+ image.save(buffered, format="JPEG", quality=75)
1528
+
1529
+ # Step 3: Encode the image bytes to a Base64 string
1530
+ img_bytes = buffered.getvalue()
1531
+ img_base64 = base64.b64encode(img_bytes).decode('utf-8')
1532
+
1533
+ return {
1534
+ "ui": {"bg_image": [img_base64]},
1535
+ "result": (json.dumps(pos_coordinates), json.dumps(neg_coordinates), bboxes, mask_tensor, cropped_image)
1536
+ }
1537
+
1538
+ class CutAndDragOnPath:
1539
+ RETURN_TYPES = ("IMAGE", "MASK",)
1540
+ RETURN_NAMES = ("image","mask", )
1541
+ FUNCTION = "cutanddrag"
1542
+ CATEGORY = "KJNodes/image"
1543
+ DESCRIPTION = """
1544
+ Cuts the masked area from the image, and drags it along the path. If inpaint is enabled, and no bg_image is provided, the cut area is filled using cv2 TELEA algorithm.
1545
+ """
1546
+
1547
+ @classmethod
1548
+ def INPUT_TYPES(s):
1549
+ return {
1550
+ "required": {
1551
+ "image": ("IMAGE",),
1552
+ "coordinates": ("STRING", {"forceInput": True}),
1553
+ "mask": ("MASK",),
1554
+ "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
1555
+ "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
1556
+ "inpaint": ("BOOLEAN", {"default": True}),
1557
+ },
1558
+ "optional": {
1559
+ "bg_image": ("IMAGE",),
1560
+ }
1561
+ }
1562
+
1563
+ def cutanddrag(self, image, coordinates, mask, frame_width, frame_height, inpaint, bg_image=None):
1564
+ # Parse coordinates
1565
+ coords_list = parse_json_tracks(coordinates)
1566
+
1567
+ batch_size = len(coords_list[0])
1568
+ images_list = []
1569
+ masks_list = []
1570
+
1571
+ # Convert input image and mask to PIL
1572
+ input_image = tensor2pil(image)[0]
1573
+ input_mask = tensor2pil(mask)[0]
1574
+
1575
+ # Find masked region bounds
1576
+ mask_array = np.array(input_mask)
1577
+ y_indices, x_indices = np.where(mask_array > 0)
1578
+ if len(x_indices) == 0 or len(y_indices) == 0:
1579
+ return (image, mask)
1580
+
1581
+ x_min, x_max = x_indices.min(), x_indices.max()
1582
+ y_min, y_max = y_indices.min(), y_indices.max()
1583
+
1584
+ # Cut out the masked region
1585
+ cut_width = x_max - x_min
1586
+ cut_height = y_max - y_min
1587
+ cut_image = input_image.crop((x_min, y_min, x_max, y_max))
1588
+ cut_mask = input_mask.crop((x_min, y_min, x_max, y_max))
1589
+
1590
+ # Create inpainted background
1591
+ if bg_image is None:
1592
+ background = input_image.copy()
1593
+ # Inpaint the cut area
1594
+ if inpaint:
1595
+ import cv2
1596
+ border = 5 # Create small border around cut area for better inpainting
1597
+ fill_mask = Image.new("L", background.size, 0)
1598
+ draw = ImageDraw.Draw(fill_mask)
1599
+ draw.rectangle([x_min-border, y_min-border, x_max+border, y_max+border], fill=255)
1600
+ background = cv2.inpaint(
1601
+ np.array(background),
1602
+ np.array(fill_mask),
1603
+ inpaintRadius=3,
1604
+ flags=cv2.INPAINT_TELEA
1605
+ )
1606
+ background = Image.fromarray(background)
1607
+ else:
1608
+ background = tensor2pil(bg_image)[0]
1609
+
1610
+ # Create batch of images with cut region at different positions
1611
+ for i in range(batch_size):
1612
+ # Create new image
1613
+ new_image = background.copy()
1614
+ new_mask = Image.new("L", (frame_width, frame_height), 0)
1615
+
1616
+ # Get target position from coordinates
1617
+ for coords in coords_list:
1618
+ target_x = int(coords[i]['x'] - cut_width/2)
1619
+ target_y = int(coords[i]['y'] - cut_height/2)
1620
+
1621
+ # Paste cut region at new position
1622
+ new_image.paste(cut_image, (target_x, target_y), cut_mask)
1623
+ new_mask.paste(cut_mask, (target_x, target_y))
1624
+
1625
+ # Convert to tensor and append
1626
+ image_tensor = pil2tensor(new_image)
1627
+ mask_tensor = pil2tensor(new_mask)
1628
+
1629
+ images_list.append(image_tensor)
1630
+ masks_list.append(mask_tensor)
1631
+
1632
+ # Stack tensors into batches
1633
+ out_images = torch.cat(images_list, dim=0).cpu().float()
1634
+ out_masks = torch.cat(masks_list, dim=0)
1635
+
1636
+ return (out_images, out_masks)
nodes/image_nodes.py ADDED
The diff for this file is too large to render. See raw diff
 
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,)
nodes/lora_nodes.py ADDED
@@ -0,0 +1,568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import comfy.model_management
3
+ import comfy.utils
4
+ import folder_paths
5
+ import os
6
+ import logging
7
+ from tqdm import tqdm
8
+ import numpy as np
9
+
10
+ device = comfy.model_management.get_torch_device()
11
+
12
+ CLAMP_QUANTILE = 0.99
13
+
14
+ def extract_lora(diff, key, rank, algorithm, lora_type, lowrank_iters=7, adaptive_param=1.0, clamp_quantile=True):
15
+ """
16
+ Extracts LoRA weights from a weight difference tensor using SVD.
17
+ """
18
+ conv2d = (len(diff.shape) == 4)
19
+ kernel_size = None if not conv2d else diff.size()[2:4]
20
+ conv2d_3x3 = conv2d and kernel_size != (1, 1)
21
+ out_dim, in_dim = diff.size()[0:2]
22
+
23
+ if conv2d:
24
+ if conv2d_3x3:
25
+ diff = diff.flatten(start_dim=1)
26
+ else:
27
+ diff = diff.squeeze()
28
+
29
+ diff_float = diff.float()
30
+ if algorithm == "svd_lowrank":
31
+ U, S, V = torch.svd_lowrank(diff_float, q=min(rank, in_dim, out_dim), niter=lowrank_iters)
32
+ U = U @ torch.diag(S)
33
+ Vh = V.t()
34
+ else:
35
+ #torch.linalg.svdvals()
36
+ U, S, Vh = torch.linalg.svd(diff_float)
37
+ # Flexible rank selection logic like locon: https://github.com/KohakuBlueleaf/LyCORIS/blob/main/tools/extract_locon.py
38
+ if "adaptive" in lora_type:
39
+ if lora_type == "adaptive_ratio":
40
+ min_s = torch.max(S) * adaptive_param
41
+ lora_rank = torch.sum(S > min_s).item()
42
+ elif lora_type == "adaptive_energy":
43
+ energy = torch.cumsum(S**2, dim=0)
44
+ total_energy = torch.sum(S**2)
45
+ threshold = adaptive_param * total_energy # e.g., adaptive_param=0.95 for 95%
46
+ lora_rank = torch.sum(energy < threshold).item() + 1
47
+ elif lora_type == "adaptive_quantile":
48
+ s_cum = torch.cumsum(S, dim=0)
49
+ min_cum_sum = adaptive_param * torch.sum(S)
50
+ lora_rank = torch.sum(s_cum < min_cum_sum).item()
51
+ elif lora_type == "adaptive_fro":
52
+ S_squared = S.pow(2)
53
+ S_fro_sq = float(torch.sum(S_squared))
54
+ sum_S_squared = torch.cumsum(S_squared, dim=0) / S_fro_sq
55
+ lora_rank = int(torch.searchsorted(sum_S_squared, adaptive_param**2)) + 1
56
+ lora_rank = max(1, min(lora_rank, len(S)))
57
+ else:
58
+ pass # Will print after capping
59
+
60
+ # Cap adaptive rank by the specified max rank
61
+ lora_rank = min(lora_rank, rank)
62
+
63
+ # Calculate and print actual fro percentage retained after capping
64
+ if lora_type == "adaptive_fro":
65
+ S_squared = S.pow(2)
66
+ s_fro = torch.sqrt(torch.sum(S_squared))
67
+ s_red_fro = torch.sqrt(torch.sum(S_squared[:lora_rank]))
68
+ fro_percent = float(s_red_fro / s_fro)
69
+ print(f"{key} Extracted LoRA rank: {lora_rank}, Frobenius retained: {fro_percent:.1%}")
70
+ else:
71
+ print(f"{key} Extracted LoRA rank: {lora_rank}")
72
+ else:
73
+ lora_rank = rank
74
+
75
+ lora_rank = max(1, lora_rank)
76
+ lora_rank = min(out_dim, in_dim, lora_rank)
77
+
78
+ U = U[:, :lora_rank]
79
+ S = S[:lora_rank]
80
+ U = U @ torch.diag(S)
81
+ Vh = Vh[:lora_rank, :]
82
+
83
+ if clamp_quantile:
84
+ dist = torch.cat([U.flatten(), Vh.flatten()])
85
+ if dist.numel() > 100_000:
86
+ # Sample 100,000 elements for quantile estimation
87
+ idx = torch.randperm(dist.numel(), device=dist.device)[:100_000]
88
+ dist_sample = dist[idx]
89
+ hi_val = torch.quantile(dist_sample, CLAMP_QUANTILE)
90
+ else:
91
+ hi_val = torch.quantile(dist, CLAMP_QUANTILE)
92
+ low_val = -hi_val
93
+
94
+ U = U.clamp(low_val, hi_val)
95
+ Vh = Vh.clamp(low_val, hi_val)
96
+ if conv2d:
97
+ U = U.reshape(out_dim, lora_rank, 1, 1)
98
+ Vh = Vh.reshape(lora_rank, in_dim, kernel_size[0], kernel_size[1])
99
+ return (U, Vh)
100
+
101
+
102
+ def calc_lora_model(model_diff, rank, prefix_model, prefix_lora, output_sd, lora_type, algorithm, lowrank_iters, out_dtype, bias_diff=False, adaptive_param=1.0, clamp_quantile=True):
103
+ comfy.model_management.load_models_gpu([model_diff], force_patch_weights=True)
104
+ model_diff.model.diffusion_model.cpu()
105
+ sd = model_diff.model_state_dict(filter_prefix=prefix_model)
106
+ del model_diff
107
+ comfy.model_management.soft_empty_cache()
108
+ for k, v in sd.items():
109
+ if isinstance(v, torch.Tensor):
110
+ sd[k] = v.cpu()
111
+
112
+ # Get total number of keys to process for progress bar
113
+ total_keys = len([k for k in sd if k.endswith(".weight") or (bias_diff and k.endswith(".bias"))])
114
+
115
+ # Create progress bar
116
+ progress_bar = tqdm(total=total_keys, desc=f"Extracting LoRA ({prefix_lora.strip('.')})")
117
+ comfy_pbar = comfy.utils.ProgressBar(total_keys)
118
+
119
+ for k in sd:
120
+ if k.endswith(".weight"):
121
+ weight_diff = sd[k]
122
+ if weight_diff.ndim == 5:
123
+ logging.info(f"Skipping 5D tensor for key {k}") #skip patch embed
124
+ progress_bar.update(1)
125
+ comfy_pbar.update(1)
126
+ continue
127
+ if lora_type != "full":
128
+ if weight_diff.ndim < 2:
129
+ if bias_diff:
130
+ output_sd["{}{}.diff".format(prefix_lora, k[len(prefix_model):-7])] = weight_diff.contiguous().to(out_dtype).cpu()
131
+ progress_bar.update(1)
132
+ comfy_pbar.update(1)
133
+ continue
134
+ try:
135
+ out = extract_lora(weight_diff.to(device), k, rank, algorithm, lora_type, lowrank_iters=lowrank_iters, adaptive_param=adaptive_param, clamp_quantile=clamp_quantile)
136
+ output_sd["{}{}.lora_up.weight".format(prefix_lora, k[len(prefix_model):-7])] = out[0].contiguous().to(out_dtype).cpu()
137
+ output_sd["{}{}.lora_down.weight".format(prefix_lora, k[len(prefix_model):-7])] = out[1].contiguous().to(out_dtype).cpu()
138
+ except Exception as e:
139
+ logging.warning(f"Could not generate lora weights for key {k}, error {e}")
140
+ else:
141
+ output_sd["{}{}.diff".format(prefix_lora, k[len(prefix_model):-7])] = weight_diff.contiguous().to(out_dtype).cpu()
142
+
143
+ progress_bar.update(1)
144
+ comfy_pbar.update(1)
145
+
146
+ elif bias_diff and k.endswith(".bias"):
147
+ output_sd["{}{}.diff_b".format(prefix_lora, k[len(prefix_model):-5])] = sd[k].contiguous().to(out_dtype).cpu()
148
+ progress_bar.update(1)
149
+ comfy_pbar.update(1)
150
+ progress_bar.close()
151
+ return output_sd
152
+
153
+ class LoraExtractKJ:
154
+ def __init__(self):
155
+ self.output_dir = folder_paths.get_output_directory()
156
+
157
+ @classmethod
158
+ def INPUT_TYPES(s):
159
+ return {"required":
160
+ {
161
+ "finetuned_model": ("MODEL",),
162
+ "original_model": ("MODEL",),
163
+ "filename_prefix": ("STRING", {"default": "loras/ComfyUI_extracted_lora"}),
164
+ "rank": ("INT", {"default": 8, "min": 1, "max": 4096, "step": 1, "tooltip": "The rank to use for standard LoRA, or maximum rank limit for adaptive methods."}),
165
+ "lora_type": (["standard", "full", "adaptive_ratio", "adaptive_quantile", "adaptive_energy", "adaptive_fro"],),
166
+ "algorithm": (["svd_linalg", "svd_lowrank"], {"default": "svd_linalg", "tooltip": "SVD algorithm to use, svd_lowrank is faster but less accurate."}),
167
+ "lowrank_iters": ("INT", {"default": 7, "min": 1, "max": 100, "step": 1, "tooltip": "The number of subspace iterations for lowrank SVD algorithm."}),
168
+ "output_dtype": (["fp16", "bf16", "fp32"], {"default": "fp16"}),
169
+ "bias_diff": ("BOOLEAN", {"default": True}),
170
+ "adaptive_param": ("FLOAT", {"default": 0.15, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "For ratio mode, this is the ratio of the maximum singular value. For quantile mode, this is the quantile of the singular values. For fro mode, this is the Frobenius norm retention ratio."}),
171
+ "clamp_quantile": ("BOOLEAN", {"default": True}),
172
+ },
173
+
174
+ }
175
+ RETURN_TYPES = ()
176
+ FUNCTION = "save"
177
+ OUTPUT_NODE = True
178
+
179
+ CATEGORY = "KJNodes/lora"
180
+
181
+ def save(self, finetuned_model, original_model, filename_prefix, rank, lora_type, algorithm, lowrank_iters, output_dtype, bias_diff, adaptive_param, clamp_quantile):
182
+ if algorithm == "svd_lowrank" and lora_type != "standard":
183
+ raise ValueError("svd_lowrank algorithm is only supported for standard LoRA extraction.")
184
+
185
+ dtype = {"fp8_e4m3fn": torch.float8_e4m3fn, "bf16": torch.bfloat16, "fp16": torch.float16, "fp16_fast": torch.float16, "fp32": torch.float32}[output_dtype]
186
+ m = finetuned_model.clone()
187
+ kp = original_model.get_key_patches("diffusion_model.")
188
+ for k in kp:
189
+ m.add_patches({k: kp[k]}, - 1.0, 1.0)
190
+ model_diff = m
191
+
192
+ full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(filename_prefix, self.output_dir)
193
+
194
+ output_sd = {}
195
+ if model_diff is not None:
196
+ output_sd = calc_lora_model(model_diff, rank, "diffusion_model.", "diffusion_model.", output_sd, lora_type, algorithm, lowrank_iters, dtype, bias_diff=bias_diff, adaptive_param=adaptive_param, clamp_quantile=clamp_quantile)
197
+ if "adaptive" in lora_type:
198
+ rank_str = f"{lora_type}_{adaptive_param:.2f}"
199
+ else:
200
+ rank_str = rank
201
+ output_checkpoint = f"{filename}_rank_{rank_str}_{output_dtype}_{counter:05}_.safetensors"
202
+ output_checkpoint = os.path.join(full_output_folder, output_checkpoint)
203
+
204
+ comfy.utils.save_torch_file(output_sd, output_checkpoint, metadata=None)
205
+ return {}
206
+
207
+ NODE_CLASS_MAPPINGS = {
208
+ "LoraExtractKJ": LoraExtractKJ
209
+ }
210
+
211
+ NODE_DISPLAY_NAME_MAPPINGS = {
212
+ "LoraExtractKJ": "LoraExtractKJ"
213
+ }
214
+
215
+ class LoraReduceRank:
216
+ def __init__(self):
217
+ self.output_dir = folder_paths.get_output_directory()
218
+
219
+ @classmethod
220
+ def INPUT_TYPES(s):
221
+ return {"required":
222
+ {
223
+ "lora_name": (folder_paths.get_filename_list("loras"), {"tooltip": "The name of the LoRA."}),
224
+ "new_rank": ("INT", {"default": 8, "min": 1, "max": 4096, "step": 1, "tooltip": "The new rank to resize the LoRA. Acts as max rank when using dynamic_method."}),
225
+ "dynamic_method": (["disabled", "sv_ratio", "sv_cumulative", "sv_fro"], {"default": "disabled", "tooltip": "Method to use for dynamically determining new alphas and dims"}),
226
+ "dynamic_param": ("FLOAT", {"default": 0.2, "min": 0.0, "max": 1.0, "step": 0.01, "tooltip": "Method to use for dynamically determining new alphas and dims"}),
227
+ "output_dtype": (["match_original", "fp16", "bf16", "fp32"], {"default": "match_original", "tooltip": "Data type to save the LoRA as."}),
228
+ "verbose": ("BOOLEAN", {"default": True}),
229
+ },
230
+
231
+ }
232
+ RETURN_TYPES = ()
233
+ FUNCTION = "save"
234
+ OUTPUT_NODE = True
235
+ EXPERIMENTAL = True
236
+ DESCRIPTION = "Resize a LoRA model by reducing it's rank. Based on kohya's sd-scripts: https://github.com/kohya-ss/sd-scripts/blob/main/networks/resize_lora.py"
237
+
238
+ CATEGORY = "KJNodes/lora"
239
+
240
+ def save(self, lora_name, new_rank, output_dtype, dynamic_method, dynamic_param, verbose):
241
+
242
+ lora_path = folder_paths.get_full_path("loras", lora_name)
243
+ lora_sd, metadata = comfy.utils.load_torch_file(lora_path, return_metadata=True)
244
+
245
+ if output_dtype == "fp16":
246
+ save_dtype = torch.float16
247
+ elif output_dtype == "bf16":
248
+ save_dtype = torch.bfloat16
249
+ elif output_dtype == "fp32":
250
+ save_dtype = torch.float32
251
+ elif output_dtype == "match_original":
252
+ first_weight_key = next(k for k in lora_sd if k.endswith(".weight") and isinstance(lora_sd[k], torch.Tensor))
253
+ save_dtype = lora_sd[first_weight_key].dtype
254
+
255
+ new_lora_sd = {}
256
+ for k, v in lora_sd.items():
257
+ new_lora_sd[k.replace(".default", "")] = v
258
+ del lora_sd
259
+ print("Resizing Lora...")
260
+ output_sd, old_dim, new_alpha, rank_list = resize_lora_model(new_lora_sd, new_rank, save_dtype, device, dynamic_method, dynamic_param, verbose)
261
+
262
+ # update metadata
263
+ if metadata is None:
264
+ metadata = {}
265
+
266
+ comment = metadata.get("ss_training_comment", "")
267
+
268
+ if dynamic_method == "disabled":
269
+ metadata["ss_training_comment"] = f"dimension is resized from {old_dim} to {new_rank}; {comment}"
270
+ metadata["ss_network_dim"] = str(new_rank)
271
+ metadata["ss_network_alpha"] = str(new_alpha)
272
+ else:
273
+ metadata["ss_training_comment"] = f"Dynamic resize with {dynamic_method}: {dynamic_param} from {old_dim}; {comment}"
274
+ metadata["ss_network_dim"] = "Dynamic"
275
+ metadata["ss_network_alpha"] = "Dynamic"
276
+
277
+ # cast to save_dtype before calculating hashes
278
+ for key in list(output_sd.keys()):
279
+ value = output_sd[key]
280
+ if type(value) == torch.Tensor and value.dtype.is_floating_point and value.dtype != save_dtype:
281
+ output_sd[key] = value.to(save_dtype)
282
+
283
+ output_filename_prefix = "loras/" + lora_name
284
+
285
+ full_output_folder, filename, counter, subfolder, filename_prefix = folder_paths.get_save_image_path(output_filename_prefix, self.output_dir)
286
+ output_dtype_str = f"_{output_dtype}" if output_dtype != "match_original" else ""
287
+ average_rank = str(int(np.mean(rank_list)))
288
+ rank_str = new_rank if dynamic_method == "disabled" else f"dynamic_{average_rank}"
289
+ output_checkpoint = f"{filename.replace('.safetensors', '')}_resized_from_{old_dim}_to_{rank_str}{output_dtype_str}_{counter:05}_.safetensors"
290
+ output_checkpoint = os.path.join(full_output_folder, output_checkpoint)
291
+ print(f"Saving resized LoRA to {output_checkpoint}")
292
+
293
+ comfy.utils.save_torch_file(output_sd, output_checkpoint, metadata=metadata)
294
+ return {}
295
+
296
+ NODE_CLASS_MAPPINGS = {
297
+ "LoraExtractKJ": LoraExtractKJ
298
+ }
299
+
300
+ NODE_DISPLAY_NAME_MAPPINGS = {
301
+ "LoraExtractKJ": "LoraExtractKJ"
302
+ }
303
+
304
+ # Convert LoRA to different rank approximation (should only be used to go to lower rank)
305
+ # This code is based off the extract_lora_from_models.py file which is based on https://github.com/cloneofsimo/lora/blob/develop/lora_diffusion/cli_svd.py
306
+ # Thanks to cloneofsimo
307
+
308
+ # This version is based on
309
+ # https://github.com/kohya-ss/sd-scripts/blob/main/networks/resize_lora.py
310
+
311
+ MIN_SV = 1e-6
312
+
313
+ LORA_DOWN_UP_FORMATS = [
314
+ ("lora_down", "lora_up"), # sd-scripts LoRA
315
+ ("lora_A", "lora_B"), # PEFT LoRA
316
+ ("down", "up"), # ControlLoRA
317
+ ]
318
+
319
+ # Indexing functions
320
+ def index_sv_cumulative(S, target):
321
+ original_sum = float(torch.sum(S))
322
+ cumulative_sums = torch.cumsum(S, dim=0) / original_sum
323
+ index = int(torch.searchsorted(cumulative_sums, target)) + 1
324
+ index = max(1, min(index, len(S) - 1))
325
+
326
+ return index
327
+
328
+
329
+ def index_sv_fro(S, target):
330
+ S_squared = S.pow(2)
331
+ S_fro_sq = float(torch.sum(S_squared))
332
+ sum_S_squared = torch.cumsum(S_squared, dim=0) / S_fro_sq
333
+ index = int(torch.searchsorted(sum_S_squared, target**2)) + 1
334
+ index = max(1, min(index, len(S) - 1))
335
+
336
+ return index
337
+
338
+
339
+ def index_sv_ratio(S, target):
340
+ max_sv = S[0]
341
+ min_sv = max_sv / target
342
+ index = int(torch.sum(S > min_sv).item())
343
+ index = max(1, min(index, len(S) - 1))
344
+
345
+ return index
346
+
347
+
348
+ # Modified from Kohaku-blueleaf's extract/merge functions
349
+ def extract_conv(weight, lora_rank, dynamic_method, dynamic_param, device, scale=1):
350
+ out_size, in_size, kernel_size, _ = weight.size()
351
+ if weight.dtype != torch.float32:
352
+ weight = weight.to(torch.float32)
353
+ U, S, Vh = torch.linalg.svd(weight.reshape(out_size, -1).to(device))
354
+
355
+ param_dict = rank_resize(S, lora_rank, dynamic_method, dynamic_param, scale)
356
+ lora_rank = param_dict["new_rank"]
357
+
358
+ U = U[:, :lora_rank]
359
+ S = S[:lora_rank]
360
+ U = U @ torch.diag(S)
361
+ Vh = Vh[:lora_rank, :]
362
+
363
+ param_dict["lora_down"] = Vh.reshape(lora_rank, in_size, kernel_size, kernel_size).cpu()
364
+ param_dict["lora_up"] = U.reshape(out_size, lora_rank, 1, 1).cpu()
365
+ del U, S, Vh, weight
366
+ return param_dict
367
+
368
+
369
+ def extract_linear(weight, lora_rank, dynamic_method, dynamic_param, device, scale=1):
370
+ out_size, in_size = weight.size()
371
+
372
+ if weight.dtype != torch.float32:
373
+ weight = weight.to(torch.float32)
374
+ U, S, Vh = torch.linalg.svd(weight.to(device))
375
+
376
+ param_dict = rank_resize(S, lora_rank, dynamic_method, dynamic_param, scale)
377
+ lora_rank = param_dict["new_rank"]
378
+
379
+ U = U[:, :lora_rank]
380
+ S = S[:lora_rank]
381
+ U = U @ torch.diag(S)
382
+ Vh = Vh[:lora_rank, :]
383
+
384
+ param_dict["lora_down"] = Vh.reshape(lora_rank, in_size).cpu()
385
+ param_dict["lora_up"] = U.reshape(out_size, lora_rank).cpu()
386
+ del U, S, Vh, weight
387
+ return param_dict
388
+
389
+
390
+ def merge_conv(lora_down, lora_up, device):
391
+ in_rank, in_size, kernel_size, k_ = lora_down.shape
392
+ out_size, out_rank, _, _ = lora_up.shape
393
+ assert in_rank == out_rank and kernel_size == k_, f"rank {in_rank} {out_rank} or kernel {kernel_size} {k_} mismatch"
394
+
395
+ lora_down = lora_down.to(device)
396
+ lora_up = lora_up.to(device)
397
+
398
+ merged = lora_up.reshape(out_size, -1) @ lora_down.reshape(in_rank, -1)
399
+ weight = merged.reshape(out_size, in_size, kernel_size, kernel_size)
400
+ del lora_up, lora_down
401
+ return weight
402
+
403
+
404
+ def merge_linear(lora_down, lora_up, device):
405
+ in_rank, in_size = lora_down.shape
406
+ out_size, out_rank = lora_up.shape
407
+ assert in_rank == out_rank, f"rank {in_rank} {out_rank} mismatch"
408
+
409
+ lora_down = lora_down.to(device)
410
+ lora_up = lora_up.to(device)
411
+
412
+ weight = lora_up @ lora_down
413
+ del lora_up, lora_down
414
+ return weight
415
+
416
+
417
+ # Calculate new rank
418
+
419
+
420
+ def rank_resize(S, rank, dynamic_method, dynamic_param, scale=1):
421
+ param_dict = {}
422
+
423
+ if dynamic_method == "sv_ratio":
424
+ # Calculate new dim and alpha based off ratio
425
+ new_rank = index_sv_ratio(S, dynamic_param) + 1
426
+ new_alpha = float(scale * new_rank)
427
+
428
+ elif dynamic_method == "sv_cumulative":
429
+ # Calculate new dim and alpha based off cumulative sum
430
+ new_rank = index_sv_cumulative(S, dynamic_param) + 1
431
+ new_alpha = float(scale * new_rank)
432
+
433
+ elif dynamic_method == "sv_fro":
434
+ # Calculate new dim and alpha based off sqrt sum of squares
435
+ new_rank = index_sv_fro(S, dynamic_param) + 1
436
+ new_alpha = float(scale * new_rank)
437
+ else:
438
+ new_rank = rank
439
+ new_alpha = float(scale * new_rank)
440
+
441
+ if S[0] <= MIN_SV: # Zero matrix, set dim to 1
442
+ new_rank = 1
443
+ new_alpha = float(scale * new_rank)
444
+ elif new_rank > rank: # cap max rank at rank
445
+ new_rank = rank
446
+ new_alpha = float(scale * new_rank)
447
+
448
+ # Calculate resize info
449
+ s_sum = torch.sum(torch.abs(S))
450
+ s_rank = torch.sum(torch.abs(S[:new_rank]))
451
+
452
+ S_squared = S.pow(2)
453
+ s_fro = torch.sqrt(torch.sum(S_squared))
454
+ s_red_fro = torch.sqrt(torch.sum(S_squared[:new_rank]))
455
+ fro_percent = float(s_red_fro / s_fro)
456
+
457
+ param_dict["new_rank"] = new_rank
458
+ param_dict["new_alpha"] = new_alpha
459
+ param_dict["sum_retained"] = (s_rank) / s_sum
460
+ param_dict["fro_retained"] = fro_percent
461
+ param_dict["max_ratio"] = S[0] / S[new_rank - 1]
462
+
463
+ return param_dict
464
+
465
+
466
+ def resize_lora_model(lora_sd, new_rank, save_dtype, device, dynamic_method, dynamic_param, verbose):
467
+ max_old_rank = None
468
+ new_alpha = None
469
+ verbose_str = "\n"
470
+ fro_list = []
471
+ rank_list = []
472
+
473
+ if dynamic_method:
474
+ print(f"Dynamically determining new alphas and dims based off {dynamic_method}: {dynamic_param}, max rank is {new_rank}")
475
+
476
+ lora_down_weight = None
477
+ lora_up_weight = None
478
+
479
+ o_lora_sd = lora_sd.copy()
480
+ block_down_name = None
481
+ block_up_name = None
482
+
483
+ total_keys = len([k for k in lora_sd if k.endswith(".weight")])
484
+
485
+ pbar = comfy.utils.ProgressBar(total_keys)
486
+ for key, value in tqdm(lora_sd.items(), leave=True, desc="Resizing LoRA weights"):
487
+ key_parts = key.split(".")
488
+ block_down_name = None
489
+ for _format in LORA_DOWN_UP_FORMATS:
490
+ # Currently we only match lora_down_name in the last two parts of key
491
+ # because ("down", "up") are general words and may appear in block_down_name
492
+ if len(key_parts) >= 2 and _format[0] == key_parts[-2]:
493
+ block_down_name = ".".join(key_parts[:-2])
494
+ lora_down_name = "." + _format[0]
495
+ lora_up_name = "." + _format[1]
496
+ weight_name = "." + key_parts[-1]
497
+ break
498
+ if len(key_parts) >= 1 and _format[0] == key_parts[-1]:
499
+ block_down_name = ".".join(key_parts[:-1])
500
+ lora_down_name = "." + _format[0]
501
+ lora_up_name = "." + _format[1]
502
+ weight_name = ""
503
+ break
504
+
505
+ if block_down_name is None:
506
+ # This parameter is not lora_down
507
+ continue
508
+
509
+ # Now weight_name can be ".weight" or ""
510
+ # Find corresponding lora_up and alpha
511
+ block_up_name = block_down_name
512
+ lora_down_weight = value
513
+ lora_up_weight = lora_sd.get(block_up_name + lora_up_name + weight_name, None)
514
+ lora_alpha = lora_sd.get(block_down_name + ".alpha", None)
515
+
516
+ weights_loaded = lora_down_weight is not None and lora_up_weight is not None
517
+
518
+ if weights_loaded:
519
+
520
+ conv2d = len(lora_down_weight.size()) == 4
521
+ old_rank = lora_down_weight.size()[0]
522
+ max_old_rank = max(max_old_rank or 0, old_rank)
523
+
524
+
525
+ if lora_alpha is None:
526
+ scale = 1.0
527
+ else:
528
+ scale = lora_alpha / old_rank
529
+
530
+ if conv2d:
531
+ full_weight_matrix = merge_conv(lora_down_weight, lora_up_weight, device)
532
+ param_dict = extract_conv(full_weight_matrix, new_rank, dynamic_method, dynamic_param, device, scale)
533
+ else:
534
+ full_weight_matrix = merge_linear(lora_down_weight, lora_up_weight, device)
535
+ param_dict = extract_linear(full_weight_matrix, new_rank, dynamic_method, dynamic_param, device, scale)
536
+
537
+ if verbose:
538
+ max_ratio = param_dict["max_ratio"]
539
+ sum_retained = param_dict["sum_retained"]
540
+ fro_retained = param_dict["fro_retained"]
541
+ if not np.isnan(fro_retained):
542
+ fro_list.append(float(fro_retained))
543
+ log_str = f"{block_down_name:75} | sum(S) retained: {sum_retained:.1%}, fro retained: {fro_retained:.1%}, max(S) ratio: {max_ratio:0.1f}, new dim: {param_dict['new_rank']}"
544
+ tqdm.write(log_str)
545
+ verbose_str += log_str
546
+
547
+ if verbose and dynamic_method:
548
+ verbose_str += f", dynamic | dim: {param_dict['new_rank']}, alpha: {param_dict['new_alpha']}\n"
549
+ else:
550
+ verbose_str += "\n"
551
+
552
+ new_alpha = param_dict["new_alpha"]
553
+ o_lora_sd[block_down_name + lora_down_name + weight_name] = param_dict["lora_down"].to(save_dtype).contiguous()
554
+ o_lora_sd[block_up_name + lora_up_name + weight_name] = param_dict["lora_up"].to(save_dtype).contiguous()
555
+ o_lora_sd[block_down_name + ".alpha"] = torch.tensor(param_dict["new_alpha"]).to(save_dtype)
556
+
557
+ block_down_name = None
558
+ block_up_name = None
559
+ lora_down_weight = None
560
+ lora_up_weight = None
561
+ weights_loaded = False
562
+ rank_list.append(param_dict["new_rank"])
563
+ del param_dict
564
+ pbar.update(1)
565
+
566
+ if verbose:
567
+ print(f"Average Frobenius norm retention: {np.mean(fro_list):.2%} | std: {np.std(fro_list):0.3f}")
568
+ return o_lora_sd, max_old_rank, new_alpha, rank_list
nodes/mask_nodes.py ADDED
@@ -0,0 +1,1669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from tqdm import tqdm
10
+
11
+ from comfy import model_management
12
+ from comfy.utils import ProgressBar
13
+ from comfy.utils import common_upscale
14
+ from nodes import MAX_RESOLUTION
15
+
16
+ import folder_paths
17
+
18
+ from ..utility.utility import tensor2pil, pil2tensor
19
+
20
+ script_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
+ main_device = model_management.get_torch_device()
22
+ offload_device = model_management.unet_offload_device()
23
+
24
+ class BatchCLIPSeg:
25
+
26
+ def __init__(self):
27
+ pass
28
+
29
+ @classmethod
30
+ def INPUT_TYPES(s):
31
+
32
+ return {"required":
33
+ {
34
+ "images": ("IMAGE",),
35
+ "text": ("STRING", {"multiline": False}),
36
+ "threshold": ("FLOAT", {"default": 0.5,"min": 0.0, "max": 10.0, "step": 0.001}),
37
+ "binary_mask": ("BOOLEAN", {"default": True}),
38
+ "combine_mask": ("BOOLEAN", {"default": False}),
39
+ "use_cuda": ("BOOLEAN", {"default": True}),
40
+ },
41
+ "optional":
42
+ {
43
+ "blur_sigma": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.1}),
44
+ "opt_model": ("CLIPSEGMODEL", ),
45
+ "prev_mask": ("MASK", {"default": None}),
46
+ "image_bg_level": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
47
+ "invert": ("BOOLEAN", {"default": False}),
48
+ }
49
+ }
50
+
51
+ CATEGORY = "KJNodes/masking"
52
+ RETURN_TYPES = ("MASK", "IMAGE", )
53
+ RETURN_NAMES = ("Mask", "Image", )
54
+ FUNCTION = "segment_image"
55
+ DESCRIPTION = """
56
+ Segments an image or batch of images using CLIPSeg.
57
+ """
58
+
59
+ 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):
60
+ from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation
61
+ import torchvision.transforms as transforms
62
+ offload_device = model_management.unet_offload_device()
63
+ device = model_management.get_torch_device()
64
+ if not use_cuda:
65
+ device = torch.device("cpu")
66
+ dtype = model_management.unet_dtype()
67
+
68
+ if opt_model is None:
69
+ checkpoint_path = os.path.join(folder_paths.models_dir,'clip_seg', 'clipseg-rd64-refined-fp16')
70
+ if not hasattr(self, "model"):
71
+ try:
72
+ if not os.path.exists(checkpoint_path):
73
+ from huggingface_hub import snapshot_download
74
+ snapshot_download(repo_id="Kijai/clipseg-rd64-refined-fp16", local_dir=checkpoint_path, local_dir_use_symlinks=False)
75
+ self.model = CLIPSegForImageSegmentation.from_pretrained(checkpoint_path)
76
+ except:
77
+ checkpoint_path = "CIDAS/clipseg-rd64-refined"
78
+ self.model = CLIPSegForImageSegmentation.from_pretrained(checkpoint_path)
79
+ processor = CLIPSegProcessor.from_pretrained(checkpoint_path)
80
+
81
+ else:
82
+ self.model = opt_model['model']
83
+ processor = opt_model['processor']
84
+
85
+ self.model.to(dtype).to(device)
86
+
87
+ B, H, W, C = images.shape
88
+ images = images.to(device)
89
+
90
+ autocast_condition = (dtype != torch.float32) and not model_management.is_device_mps(device)
91
+ with torch.autocast(model_management.get_autocast_device(device), dtype=dtype) if autocast_condition else nullcontext():
92
+
93
+ PIL_images = [Image.fromarray(np.clip(255. * image.cpu().numpy().squeeze(), 0, 255).astype(np.uint8)) for image in images ]
94
+ prompt = [text] * len(images)
95
+ input_prc = processor(text=prompt, images=PIL_images, return_tensors="pt")
96
+
97
+ for key in input_prc:
98
+ input_prc[key] = input_prc[key].to(device)
99
+ outputs = self.model(**input_prc)
100
+
101
+ mask_tensor = torch.sigmoid(outputs.logits)
102
+ mask_tensor = (mask_tensor - mask_tensor.min()) / (mask_tensor.max() - mask_tensor.min())
103
+ mask_tensor = torch.where(mask_tensor > (threshold), mask_tensor, torch.tensor(0, dtype=torch.float))
104
+ print(mask_tensor.shape)
105
+ if len(mask_tensor.shape) == 2:
106
+ mask_tensor = mask_tensor.unsqueeze(0)
107
+ mask_tensor = F.interpolate(mask_tensor.unsqueeze(1), size=(H, W), mode='nearest')
108
+ mask_tensor = mask_tensor.squeeze(1)
109
+
110
+ self.model.to(offload_device)
111
+
112
+ if binary_mask:
113
+ mask_tensor = (mask_tensor > 0).float()
114
+ if blur_sigma > 0:
115
+ kernel_size = int(6 * int(blur_sigma) + 1)
116
+ blur = transforms.GaussianBlur(kernel_size=(kernel_size, kernel_size), sigma=(blur_sigma, blur_sigma))
117
+ mask_tensor = blur(mask_tensor)
118
+
119
+ if combine_mask:
120
+ mask_tensor = torch.max(mask_tensor, dim=0)[0]
121
+ mask_tensor = mask_tensor.unsqueeze(0).repeat(len(images),1,1)
122
+
123
+ del outputs
124
+ model_management.soft_empty_cache()
125
+
126
+ if prev_mask is not None:
127
+ if prev_mask.shape != mask_tensor.shape:
128
+ prev_mask = F.interpolate(prev_mask.unsqueeze(1), size=(H, W), mode='nearest')
129
+ mask_tensor = mask_tensor + prev_mask.to(device)
130
+ torch.clamp(mask_tensor, min=0.0, max=1.0)
131
+
132
+ if invert:
133
+ mask_tensor = 1 - mask_tensor
134
+
135
+ image_tensor = images * mask_tensor.unsqueeze(-1) + (1 - mask_tensor.unsqueeze(-1)) * image_bg_level
136
+ image_tensor = torch.clamp(image_tensor, min=0.0, max=1.0).cpu().float()
137
+
138
+ mask_tensor = mask_tensor.cpu().float()
139
+
140
+ return mask_tensor, image_tensor,
141
+
142
+ class DownloadAndLoadCLIPSeg:
143
+
144
+ def __init__(self):
145
+ pass
146
+
147
+ @classmethod
148
+ def INPUT_TYPES(s):
149
+
150
+ return {"required":
151
+ {
152
+ "model": (
153
+ [ 'Kijai/clipseg-rd64-refined-fp16',
154
+ 'CIDAS/clipseg-rd64-refined',
155
+ ],
156
+ ),
157
+ },
158
+ }
159
+
160
+ CATEGORY = "KJNodes/masking"
161
+ RETURN_TYPES = ("CLIPSEGMODEL",)
162
+ RETURN_NAMES = ("clipseg_model",)
163
+ FUNCTION = "segment_image"
164
+ DESCRIPTION = """
165
+ Downloads and loads CLIPSeg model with huggingface_hub,
166
+ to ComfyUI/models/clip_seg
167
+ """
168
+
169
+ def segment_image(self, model):
170
+ from transformers import CLIPSegProcessor, CLIPSegForImageSegmentation
171
+ checkpoint_path = os.path.join(folder_paths.models_dir,'clip_seg', os.path.basename(model))
172
+ if not hasattr(self, "model"):
173
+ if not os.path.exists(checkpoint_path):
174
+ from huggingface_hub import snapshot_download
175
+ snapshot_download(repo_id=model, local_dir=checkpoint_path, local_dir_use_symlinks=False)
176
+ self.model = CLIPSegForImageSegmentation.from_pretrained(checkpoint_path)
177
+
178
+ processor = CLIPSegProcessor.from_pretrained(checkpoint_path)
179
+
180
+ clipseg_model = {}
181
+ clipseg_model['model'] = self.model
182
+ clipseg_model['processor'] = processor
183
+
184
+ return clipseg_model,
185
+
186
+ class CreateTextMask:
187
+
188
+ RETURN_TYPES = ("IMAGE", "MASK",)
189
+ FUNCTION = "createtextmask"
190
+ CATEGORY = "KJNodes/text"
191
+ DESCRIPTION = """
192
+ Creates a text image and mask.
193
+ Looks for fonts from this folder:
194
+ ComfyUI/custom_nodes/ComfyUI-KJNodes/fonts
195
+
196
+ If start_rotation and/or end_rotation are different values,
197
+ creates animation between them.
198
+ """
199
+
200
+ @classmethod
201
+ def INPUT_TYPES(s):
202
+ return {
203
+ "required": {
204
+ "invert": ("BOOLEAN", {"default": False}),
205
+ "frames": ("INT", {"default": 1,"min": 1, "max": 4096, "step": 1}),
206
+ "text_x": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}),
207
+ "text_y": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}),
208
+ "font_size": ("INT", {"default": 32,"min": 8, "max": 4096, "step": 1}),
209
+ "font_color": ("STRING", {"default": "white"}),
210
+ "text": ("STRING", {"default": "HELLO!", "multiline": True}),
211
+ "font": (folder_paths.get_filename_list("kjnodes_fonts"), ),
212
+ "width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
213
+ "height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
214
+ "start_rotation": ("INT", {"default": 0,"min": 0, "max": 359, "step": 1}),
215
+ "end_rotation": ("INT", {"default": 0,"min": -359, "max": 359, "step": 1}),
216
+ },
217
+ }
218
+
219
+ def createtextmask(self, frames, width, height, invert, text_x, text_y, text, font_size, font_color, font, start_rotation, end_rotation):
220
+ # Define the number of images in the batch
221
+ batch_size = frames
222
+ out = []
223
+ masks = []
224
+ rotation = start_rotation
225
+ if start_rotation != end_rotation:
226
+ rotation_increment = (end_rotation - start_rotation) / (batch_size - 1)
227
+
228
+ font_path = folder_paths.get_full_path("kjnodes_fonts", font)
229
+ # Generate the text
230
+ for i in range(batch_size):
231
+ image = Image.new("RGB", (width, height), "black")
232
+ draw = ImageDraw.Draw(image)
233
+ font = ImageFont.truetype(font_path, font_size)
234
+
235
+ # Split the text into words
236
+ words = text.split()
237
+
238
+ # Initialize variables for line creation
239
+ lines = []
240
+ current_line = []
241
+ current_line_width = 0
242
+ try: #new pillow
243
+ # Iterate through words to create lines
244
+ for word in words:
245
+ word_width = font.getbbox(word)[2]
246
+ if current_line_width + word_width <= width - 2 * text_x:
247
+ current_line.append(word)
248
+ current_line_width += word_width + font.getbbox(" ")[2] # Add space width
249
+ else:
250
+ lines.append(" ".join(current_line))
251
+ current_line = [word]
252
+ current_line_width = word_width
253
+ except: #old pillow
254
+ for word in words:
255
+ word_width = font.getsize(word)[0]
256
+ if current_line_width + word_width <= width - 2 * text_x:
257
+ current_line.append(word)
258
+ current_line_width += word_width + font.getsize(" ")[0] # Add space width
259
+ else:
260
+ lines.append(" ".join(current_line))
261
+ current_line = [word]
262
+ current_line_width = word_width
263
+
264
+ # Add the last line if it's not empty
265
+ if current_line:
266
+ lines.append(" ".join(current_line))
267
+
268
+ # Draw each line of text separately
269
+ y_offset = text_y
270
+ for line in lines:
271
+ text_width = font.getlength(line)
272
+ text_height = font_size
273
+ text_center_x = text_x + text_width / 2
274
+ text_center_y = y_offset + text_height / 2
275
+ try:
276
+ draw.text((text_x, y_offset), line, font=font, fill=font_color, features=['-liga'])
277
+ except:
278
+ draw.text((text_x, y_offset), line, font=font, fill=font_color)
279
+ y_offset += text_height # Move to the next line
280
+
281
+ if start_rotation != end_rotation:
282
+ image = image.rotate(rotation, center=(text_center_x, text_center_y))
283
+ rotation += rotation_increment
284
+
285
+ image = np.array(image).astype(np.float32) / 255.0
286
+ image = torch.from_numpy(image)[None,]
287
+ mask = image[:, :, :, 0]
288
+ masks.append(mask)
289
+ out.append(image)
290
+
291
+ if invert:
292
+ return (1.0 - torch.cat(out, dim=0), 1.0 - torch.cat(masks, dim=0),)
293
+ return (torch.cat(out, dim=0),torch.cat(masks, dim=0),)
294
+
295
+ class ColorToMask:
296
+
297
+ RETURN_TYPES = ("MASK",)
298
+ FUNCTION = "clip"
299
+ CATEGORY = "KJNodes/masking"
300
+ DESCRIPTION = """
301
+ Converts chosen RGB value to a mask.
302
+ With batch inputs, the **per_batch**
303
+ controls the number of images processed at once.
304
+ """
305
+
306
+ @classmethod
307
+ def INPUT_TYPES(s):
308
+ return {
309
+ "required": {
310
+ "images": ("IMAGE",),
311
+ "invert": ("BOOLEAN", {"default": False}),
312
+ "red": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}),
313
+ "green": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}),
314
+ "blue": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}),
315
+ "threshold": ("INT", {"default": 10,"min": 0, "max": 255, "step": 1}),
316
+ "per_batch": ("INT", {"default": 16, "min": 1, "max": 4096, "step": 1}),
317
+ },
318
+ }
319
+
320
+ def clip(self, images, red, green, blue, threshold, invert, per_batch):
321
+
322
+ color = torch.tensor([red, green, blue], dtype=torch.uint8)
323
+ black = torch.tensor([0, 0, 0], dtype=torch.uint8)
324
+ white = torch.tensor([255, 255, 255], dtype=torch.uint8)
325
+
326
+ if invert:
327
+ black, white = white, black
328
+
329
+ steps = images.shape[0]
330
+ pbar = ProgressBar(steps)
331
+ tensors_out = []
332
+
333
+ for start_idx in range(0, images.shape[0], per_batch):
334
+
335
+ # Calculate color distances
336
+ color_distances = torch.norm(images[start_idx:start_idx+per_batch] * 255 - color, dim=-1)
337
+
338
+ # Create a mask based on the threshold
339
+ mask = color_distances <= threshold
340
+
341
+ # Apply the mask to create new images
342
+ mask_out = torch.where(mask.unsqueeze(-1), white, black).float()
343
+ mask_out = mask_out.mean(dim=-1)
344
+
345
+ tensors_out.append(mask_out.cpu())
346
+ batch_count = mask_out.shape[0]
347
+ pbar.update(batch_count)
348
+
349
+ tensors_out = torch.cat(tensors_out, dim=0)
350
+ tensors_out = torch.clamp(tensors_out, min=0.0, max=1.0)
351
+ return tensors_out,
352
+
353
+ class CreateFluidMask:
354
+
355
+ RETURN_TYPES = ("IMAGE", "MASK")
356
+ FUNCTION = "createfluidmask"
357
+ CATEGORY = "KJNodes/masking/generate"
358
+
359
+ @classmethod
360
+ def INPUT_TYPES(s):
361
+ return {
362
+ "required": {
363
+ "invert": ("BOOLEAN", {"default": False}),
364
+ "frames": ("INT", {"default": 1,"min": 1, "max": 4096, "step": 1}),
365
+ "width": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
366
+ "height": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
367
+ "inflow_count": ("INT", {"default": 3,"min": 0, "max": 255, "step": 1}),
368
+ "inflow_velocity": ("INT", {"default": 1,"min": 0, "max": 255, "step": 1}),
369
+ "inflow_radius": ("INT", {"default": 8,"min": 0, "max": 255, "step": 1}),
370
+ "inflow_padding": ("INT", {"default": 50,"min": 0, "max": 255, "step": 1}),
371
+ "inflow_duration": ("INT", {"default": 60,"min": 0, "max": 255, "step": 1}),
372
+ },
373
+ }
374
+ #using code from https://github.com/GregTJ/stable-fluids
375
+ def createfluidmask(self, frames, width, height, invert, inflow_count, inflow_velocity, inflow_radius, inflow_padding, inflow_duration):
376
+ from ..utility.fluid import Fluid
377
+ try:
378
+ from scipy.special import erf
379
+ except:
380
+ from scipy.spatial import erf
381
+ out = []
382
+ masks = []
383
+ RESOLUTION = width, height
384
+ DURATION = frames
385
+
386
+ INFLOW_PADDING = inflow_padding
387
+ INFLOW_DURATION = inflow_duration
388
+ INFLOW_RADIUS = inflow_radius
389
+ INFLOW_VELOCITY = inflow_velocity
390
+ INFLOW_COUNT = inflow_count
391
+
392
+ print('Generating fluid solver, this may take some time.')
393
+ fluid = Fluid(RESOLUTION, 'dye')
394
+
395
+ center = np.floor_divide(RESOLUTION, 2)
396
+ r = np.min(center) - INFLOW_PADDING
397
+
398
+ points = np.linspace(-np.pi, np.pi, INFLOW_COUNT, endpoint=False)
399
+ points = tuple(np.array((np.cos(p), np.sin(p))) for p in points)
400
+ normals = tuple(-p for p in points)
401
+ points = tuple(r * p + center for p in points)
402
+
403
+ inflow_velocity = np.zeros_like(fluid.velocity)
404
+ inflow_dye = np.zeros(fluid.shape)
405
+ for p, n in zip(points, normals):
406
+ mask = np.linalg.norm(fluid.indices - p[:, None, None], axis=0) <= INFLOW_RADIUS
407
+ inflow_velocity[:, mask] += n[:, None] * INFLOW_VELOCITY
408
+ inflow_dye[mask] = 1
409
+
410
+
411
+ for f in range(DURATION):
412
+ print(f'Computing frame {f + 1} of {DURATION}.')
413
+ if f <= INFLOW_DURATION:
414
+ fluid.velocity += inflow_velocity
415
+ fluid.dye += inflow_dye
416
+
417
+ curl = fluid.step()[1]
418
+ # Using the error function to make the contrast a bit higher.
419
+ # Any other sigmoid function e.g. smoothstep would work.
420
+ curl = (erf(curl * 2) + 1) / 4
421
+
422
+ color = np.dstack((curl, np.ones(fluid.shape), fluid.dye))
423
+ color = (np.clip(color, 0, 1) * 255).astype('uint8')
424
+ image = np.array(color).astype(np.float32) / 255.0
425
+ image = torch.from_numpy(image)[None,]
426
+ mask = image[:, :, :, 0]
427
+ masks.append(mask)
428
+ out.append(image)
429
+
430
+ if invert:
431
+ return (1.0 - torch.cat(out, dim=0),1.0 - torch.cat(masks, dim=0),)
432
+ return (torch.cat(out, dim=0),torch.cat(masks, dim=0),)
433
+
434
+ class CreateAudioMask:
435
+
436
+ RETURN_TYPES = ("IMAGE",)
437
+ FUNCTION = "createaudiomask"
438
+ CATEGORY = "KJNodes/deprecated"
439
+
440
+ @classmethod
441
+ def INPUT_TYPES(s):
442
+ return {
443
+ "required": {
444
+ "invert": ("BOOLEAN", {"default": False}),
445
+ "frames": ("INT", {"default": 16,"min": 1, "max": 255, "step": 1}),
446
+ "scale": ("FLOAT", {"default": 0.5,"min": 0.0, "max": 2.0, "step": 0.01}),
447
+ "audio_path": ("STRING", {"default": "audio.wav"}),
448
+ "width": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
449
+ "height": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
450
+ },
451
+ }
452
+
453
+ def createaudiomask(self, frames, width, height, invert, audio_path, scale):
454
+ try:
455
+ import librosa
456
+ except ImportError:
457
+ raise Exception("Can not import librosa. Install it with 'pip install librosa'")
458
+ batch_size = frames
459
+ out = []
460
+ masks = []
461
+ if audio_path == "audio.wav": #I don't know why relative path won't work otherwise...
462
+ audio_path = os.path.join(script_directory, audio_path)
463
+ audio, sr = librosa.load(audio_path)
464
+ spectrogram = np.abs(librosa.stft(audio))
465
+
466
+ for i in range(batch_size):
467
+ image = Image.new("RGB", (width, height), "black")
468
+ draw = ImageDraw.Draw(image)
469
+ frame = spectrogram[:, i]
470
+ circle_radius = int(height * np.mean(frame))
471
+ circle_radius *= scale
472
+ circle_center = (width // 2, height // 2) # Calculate the center of the image
473
+
474
+ draw.ellipse([(circle_center[0] - circle_radius, circle_center[1] - circle_radius),
475
+ (circle_center[0] + circle_radius, circle_center[1] + circle_radius)],
476
+ fill='white')
477
+
478
+ image = np.array(image).astype(np.float32) / 255.0
479
+ image = torch.from_numpy(image)[None,]
480
+ mask = image[:, :, :, 0]
481
+ masks.append(mask)
482
+ out.append(image)
483
+
484
+ if invert:
485
+ return (1.0 - torch.cat(out, dim=0),)
486
+ return (torch.cat(out, dim=0),torch.cat(masks, dim=0),)
487
+
488
+ class CreateGradientMask:
489
+
490
+ RETURN_TYPES = ("MASK",)
491
+ FUNCTION = "createmask"
492
+ CATEGORY = "KJNodes/masking/generate"
493
+
494
+ @classmethod
495
+ def INPUT_TYPES(s):
496
+ return {
497
+ "required": {
498
+ "invert": ("BOOLEAN", {"default": False}),
499
+ "frames": ("INT", {"default": 0,"min": 0, "max": 255, "step": 1}),
500
+ "width": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
501
+ "height": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
502
+ },
503
+ }
504
+ def createmask(self, frames, width, height, invert):
505
+ # Define the number of images in the batch
506
+ batch_size = frames
507
+ out = []
508
+ # Create an empty array to store the image batch
509
+ image_batch = np.zeros((batch_size, height, width), dtype=np.float32)
510
+ # Generate the black to white gradient for each image
511
+ for i in range(batch_size):
512
+ gradient = np.linspace(1.0, 0.0, width, dtype=np.float32)
513
+ time = i / frames # Calculate the time variable
514
+ offset_gradient = gradient - time # Offset the gradient values based on time
515
+ image_batch[i] = offset_gradient.reshape(1, -1)
516
+ output = torch.from_numpy(image_batch)
517
+ mask = output
518
+ out.append(mask)
519
+ if invert:
520
+ return (1.0 - torch.cat(out, dim=0),)
521
+ return (torch.cat(out, dim=0),)
522
+
523
+ class CreateFadeMask:
524
+
525
+ RETURN_TYPES = ("MASK",)
526
+ FUNCTION = "createfademask"
527
+ CATEGORY = "KJNodes/deprecated"
528
+
529
+ @classmethod
530
+ def INPUT_TYPES(s):
531
+ return {
532
+ "required": {
533
+ "invert": ("BOOLEAN", {"default": False}),
534
+ "frames": ("INT", {"default": 2,"min": 2, "max": 10000, "step": 1}),
535
+ "width": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
536
+ "height": ("INT", {"default": 256,"min": 16, "max": 4096, "step": 1}),
537
+ "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out"],),
538
+ "start_level": ("FLOAT", {"default": 1.0,"min": 0.0, "max": 1.0, "step": 0.01}),
539
+ "midpoint_level": ("FLOAT", {"default": 0.5,"min": 0.0, "max": 1.0, "step": 0.01}),
540
+ "end_level": ("FLOAT", {"default": 0.0,"min": 0.0, "max": 1.0, "step": 0.01}),
541
+ "midpoint_frame": ("INT", {"default": 0,"min": 0, "max": 4096, "step": 1}),
542
+ },
543
+ }
544
+
545
+ def createfademask(self, frames, width, height, invert, interpolation, start_level, midpoint_level, end_level, midpoint_frame):
546
+ def ease_in(t):
547
+ return t * t
548
+
549
+ def ease_out(t):
550
+ return 1 - (1 - t) * (1 - t)
551
+
552
+ def ease_in_out(t):
553
+ return 3 * t * t - 2 * t * t * t
554
+
555
+ batch_size = frames
556
+ out = []
557
+ image_batch = np.zeros((batch_size, height, width), dtype=np.float32)
558
+
559
+ if midpoint_frame == 0:
560
+ midpoint_frame = batch_size // 2
561
+
562
+ for i in range(batch_size):
563
+ if i <= midpoint_frame:
564
+ t = i / midpoint_frame
565
+ if interpolation == "ease_in":
566
+ t = ease_in(t)
567
+ elif interpolation == "ease_out":
568
+ t = ease_out(t)
569
+ elif interpolation == "ease_in_out":
570
+ t = ease_in_out(t)
571
+ color = start_level - t * (start_level - midpoint_level)
572
+ else:
573
+ t = (i - midpoint_frame) / (batch_size - midpoint_frame)
574
+ if interpolation == "ease_in":
575
+ t = ease_in(t)
576
+ elif interpolation == "ease_out":
577
+ t = ease_out(t)
578
+ elif interpolation == "ease_in_out":
579
+ t = ease_in_out(t)
580
+ color = midpoint_level - t * (midpoint_level - end_level)
581
+
582
+ color = np.clip(color, 0, 255)
583
+ image = np.full((height, width), color, dtype=np.float32)
584
+ image_batch[i] = image
585
+
586
+ output = torch.from_numpy(image_batch)
587
+ mask = output
588
+ out.append(mask)
589
+
590
+ if invert:
591
+ return (1.0 - torch.cat(out, dim=0),)
592
+ return (torch.cat(out, dim=0),)
593
+
594
+ class CreateFadeMaskAdvanced:
595
+
596
+ RETURN_TYPES = ("MASK",)
597
+ FUNCTION = "createfademask"
598
+ CATEGORY = "KJNodes/masking/generate"
599
+ DESCRIPTION = """
600
+ Create a batch of masks interpolated between given frames and values.
601
+ Uses same syntax as Fizz' BatchValueSchedule.
602
+ First value is the frame index (not that this starts from 0, not 1)
603
+ and the second value inside the brackets is the float value of the mask in range 0.0 - 1.0
604
+
605
+ For example the default values:
606
+ 0:(0.0)
607
+ 7:(1.0)
608
+ 15:(0.0)
609
+
610
+ Would create a mask batch fo 16 frames, starting from black,
611
+ interpolating with the chosen curve to fully white at the 8th frame,
612
+ and interpolating from that to fully black at the 16th frame.
613
+ """
614
+
615
+ @classmethod
616
+ def INPUT_TYPES(s):
617
+ return {
618
+ "required": {
619
+ "points_string": ("STRING", {"default": "0:(0.0),\n7:(1.0),\n15:(0.0)\n", "multiline": True}),
620
+ "invert": ("BOOLEAN", {"default": False}),
621
+ "frames": ("INT", {"default": 16,"min": 2, "max": 10000, "step": 1}),
622
+ "width": ("INT", {"default": 512,"min": 1, "max": 4096, "step": 1}),
623
+ "height": ("INT", {"default": 512,"min": 1, "max": 4096, "step": 1}),
624
+ "interpolation": (["linear", "ease_in", "ease_out", "ease_in_out", "none", "default_to_black"],),
625
+ },
626
+ }
627
+
628
+ def createfademask(self, frames, width, height, invert, points_string, interpolation):
629
+ def ease_in(t):
630
+ return t * t
631
+
632
+ def ease_out(t):
633
+ return 1 - (1 - t) * (1 - t)
634
+
635
+ def ease_in_out(t):
636
+ return 3 * t * t - 2 * t * t * t
637
+
638
+ # Parse the input string into a list of tuples
639
+ points = []
640
+ points_string = points_string.rstrip(',\n')
641
+ for point_str in points_string.split(','):
642
+ frame_str, color_str = point_str.split(':')
643
+ frame = int(frame_str.strip())
644
+ color = float(color_str.strip()[1:-1]) # Remove parentheses around color
645
+ points.append((frame, color))
646
+
647
+ # Check if the last frame is already in the points
648
+ if (interpolation != "default_to_black") and (len(points) == 0 or points[-1][0] != frames - 1):
649
+ # If not, add it with the color of the last specified frame
650
+ points.append((frames - 1, points[-1][1] if points else 0))
651
+
652
+ # Sort the points by frame number
653
+ points.sort(key=lambda x: x[0])
654
+
655
+ batch_size = frames
656
+ out = []
657
+ image_batch = np.zeros((batch_size, height, width), dtype=np.float32)
658
+
659
+ # Index of the next point to interpolate towards
660
+ next_point = 1
661
+
662
+ for i in range(batch_size):
663
+ while next_point < len(points) and i > points[next_point][0]:
664
+ next_point += 1
665
+
666
+ # Interpolate between the previous point and the next point
667
+ prev_point = next_point - 1
668
+
669
+ if interpolation == "none":
670
+ exact_match = False
671
+ for p in points:
672
+ if p[0] == i: # Exact frame match
673
+ color = p[1]
674
+ exact_match = True
675
+ break
676
+ if not exact_match:
677
+ color = points[prev_point][1]
678
+
679
+ elif interpolation == "default_to_black":
680
+ exact_match = False
681
+ for p in points:
682
+ if p[0] == i: # Exact frame match
683
+ color = p[1]
684
+ exact_match = True
685
+ break
686
+ if not exact_match:
687
+ color = 0
688
+ else:
689
+ t = (i - points[prev_point][0]) / (points[next_point][0] - points[prev_point][0])
690
+ if interpolation == "ease_in":
691
+ t = ease_in(t)
692
+ elif interpolation == "ease_out":
693
+ t = ease_out(t)
694
+ elif interpolation == "ease_in_out":
695
+ t = ease_in_out(t)
696
+ elif interpolation == "linear":
697
+ pass # No need to modify `t` for linear interpolation
698
+
699
+ color = points[prev_point][1] - t * (points[prev_point][1] - points[next_point][1])
700
+
701
+ color = np.clip(color, 0, 255)
702
+ image = np.full((height, width), color, dtype=np.float32)
703
+ image_batch[i] = image
704
+
705
+ output = torch.from_numpy(image_batch)
706
+ mask = output
707
+ out.append(mask)
708
+
709
+ if invert:
710
+ return (1.0 - torch.cat(out, dim=0),)
711
+ return (torch.cat(out, dim=0),)
712
+
713
+ class CreateMagicMask:
714
+
715
+ RETURN_TYPES = ("MASK", "MASK",)
716
+ RETURN_NAMES = ("mask", "mask_inverted",)
717
+ FUNCTION = "createmagicmask"
718
+ CATEGORY = "KJNodes/masking/generate"
719
+
720
+ @classmethod
721
+ def INPUT_TYPES(s):
722
+ return {
723
+ "required": {
724
+ "frames": ("INT", {"default": 16,"min": 2, "max": 4096, "step": 1}),
725
+ "depth": ("INT", {"default": 12,"min": 1, "max": 500, "step": 1}),
726
+ "distortion": ("FLOAT", {"default": 1.5,"min": 0.0, "max": 100.0, "step": 0.01}),
727
+ "seed": ("INT", {"default": 123,"min": 0, "max": 99999999, "step": 1}),
728
+ "transitions": ("INT", {"default": 1,"min": 1, "max": 20, "step": 1}),
729
+ "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
730
+ "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
731
+ },
732
+ }
733
+
734
+ def createmagicmask(self, frames, transitions, depth, distortion, seed, frame_width, frame_height):
735
+ from ..utility.magictex import coordinate_grid, random_transform, magic
736
+ import matplotlib.pyplot as plt
737
+ rng = np.random.default_rng(seed)
738
+ out = []
739
+ coords = coordinate_grid((frame_width, frame_height))
740
+
741
+ # Calculate the number of frames for each transition
742
+ frames_per_transition = frames // transitions
743
+
744
+ # Generate a base set of parameters
745
+ base_params = {
746
+ "coords": random_transform(coords, rng),
747
+ "depth": depth,
748
+ "distortion": distortion,
749
+ }
750
+ for t in range(transitions):
751
+ # Generate a second set of parameters that is at most max_diff away from the base parameters
752
+ params1 = base_params.copy()
753
+ params2 = base_params.copy()
754
+
755
+ params1['coords'] = random_transform(coords, rng)
756
+ params2['coords'] = random_transform(coords, rng)
757
+
758
+ for i in range(frames_per_transition):
759
+ # Compute the interpolation factor
760
+ alpha = i / frames_per_transition
761
+
762
+ # Interpolate between the two sets of parameters
763
+ params = params1.copy()
764
+ params['coords'] = (1 - alpha) * params1['coords'] + alpha * params2['coords']
765
+
766
+ tex = magic(**params)
767
+
768
+ dpi = frame_width / 10
769
+ fig = plt.figure(figsize=(10, 10), dpi=dpi)
770
+
771
+ ax = fig.add_subplot(111)
772
+ plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
773
+
774
+ ax.get_yaxis().set_ticks([])
775
+ ax.get_xaxis().set_ticks([])
776
+ ax.imshow(tex, aspect='auto')
777
+
778
+ fig.canvas.draw()
779
+ img = np.array(fig.canvas.renderer._renderer)
780
+
781
+ plt.close(fig)
782
+
783
+ pil_img = Image.fromarray(img).convert("L")
784
+ mask = torch.tensor(np.array(pil_img)) / 255.0
785
+
786
+ out.append(mask)
787
+
788
+ return (torch.stack(out, dim=0), 1.0 - torch.stack(out, dim=0),)
789
+
790
+ class CreateShapeMask:
791
+
792
+ RETURN_TYPES = ("MASK", "MASK",)
793
+ RETURN_NAMES = ("mask", "mask_inverted",)
794
+ FUNCTION = "createshapemask"
795
+ CATEGORY = "KJNodes/masking/generate"
796
+ DESCRIPTION = """
797
+ Creates a mask or batch of masks with the specified shape.
798
+ Locations are center locations.
799
+ Grow value is the amount to grow the shape on each frame, creating animated masks.
800
+ """
801
+
802
+ @classmethod
803
+ def INPUT_TYPES(s):
804
+ return {
805
+ "required": {
806
+ "shape": (
807
+ [ 'circle',
808
+ 'square',
809
+ 'triangle',
810
+ ],
811
+ {
812
+ "default": 'circle'
813
+ }),
814
+ "frames": ("INT", {"default": 1,"min": 1, "max": 4096, "step": 1}),
815
+ "location_x": ("INT", {"default": 256,"min": 0, "max": 4096, "step": 1}),
816
+ "location_y": ("INT", {"default": 256,"min": 0, "max": 4096, "step": 1}),
817
+ "grow": ("INT", {"default": 0, "min": -512, "max": 512, "step": 1}),
818
+ "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
819
+ "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
820
+ "shape_width": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}),
821
+ "shape_height": ("INT", {"default": 128,"min": 8, "max": 4096, "step": 1}),
822
+ },
823
+ }
824
+
825
+ def createshapemask(self, frames, frame_width, frame_height, location_x, location_y, shape_width, shape_height, grow, shape):
826
+ # Define the number of images in the batch
827
+ batch_size = frames
828
+ out = []
829
+ color = "white"
830
+ for i in range(batch_size):
831
+ image = Image.new("RGB", (frame_width, frame_height), "black")
832
+ draw = ImageDraw.Draw(image)
833
+
834
+ # Calculate the size for this frame and ensure it's not less than 0
835
+ current_width = max(0, shape_width + i*grow)
836
+ current_height = max(0, shape_height + i*grow)
837
+
838
+ if shape == 'circle' or shape == 'square':
839
+ # Define the bounding box for the shape
840
+ left_up_point = (location_x - current_width // 2, location_y - current_height // 2)
841
+ right_down_point = (location_x + current_width // 2, location_y + current_height // 2)
842
+ two_points = [left_up_point, right_down_point]
843
+
844
+ if shape == 'circle':
845
+ draw.ellipse(two_points, fill=color)
846
+ elif shape == 'square':
847
+ draw.rectangle(two_points, fill=color)
848
+
849
+ elif shape == 'triangle':
850
+ # Define the points for the triangle
851
+ left_up_point = (location_x - current_width // 2, location_y + current_height // 2) # bottom left
852
+ right_down_point = (location_x + current_width // 2, location_y + current_height // 2) # bottom right
853
+ top_point = (location_x, location_y - current_height // 2) # top point
854
+ draw.polygon([top_point, left_up_point, right_down_point], fill=color)
855
+
856
+ image = pil2tensor(image)
857
+ mask = image[:, :, :, 0]
858
+ out.append(mask)
859
+ outstack = torch.cat(out, dim=0)
860
+ return (outstack, 1.0 - outstack,)
861
+
862
+ class CreateVoronoiMask:
863
+
864
+ RETURN_TYPES = ("MASK", "MASK",)
865
+ RETURN_NAMES = ("mask", "mask_inverted",)
866
+ FUNCTION = "createvoronoi"
867
+ CATEGORY = "KJNodes/masking/generate"
868
+
869
+ @classmethod
870
+ def INPUT_TYPES(s):
871
+ return {
872
+ "required": {
873
+ "frames": ("INT", {"default": 16,"min": 2, "max": 4096, "step": 1}),
874
+ "num_points": ("INT", {"default": 15,"min": 1, "max": 4096, "step": 1}),
875
+ "line_width": ("INT", {"default": 4,"min": 1, "max": 4096, "step": 1}),
876
+ "speed": ("FLOAT", {"default": 0.5,"min": 0.0, "max": 1.0, "step": 0.01}),
877
+ "frame_width": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
878
+ "frame_height": ("INT", {"default": 512,"min": 16, "max": 4096, "step": 1}),
879
+ },
880
+ }
881
+
882
+ def createvoronoi(self, frames, num_points, line_width, speed, frame_width, frame_height):
883
+ from scipy.spatial import Voronoi
884
+ # Define the number of images in the batch
885
+ batch_size = frames
886
+ out = []
887
+
888
+ # Calculate aspect ratio
889
+ aspect_ratio = frame_width / frame_height
890
+
891
+ # Create start and end points for each point, considering the aspect ratio
892
+ start_points = np.random.rand(num_points, 2)
893
+ start_points[:, 0] *= aspect_ratio
894
+
895
+ end_points = np.random.rand(num_points, 2)
896
+ end_points[:, 0] *= aspect_ratio
897
+
898
+ for i in range(batch_size):
899
+ # Interpolate the points' positions based on the current frame
900
+ t = (i * speed) / (batch_size - 1) # normalize to [0, 1] over the frames
901
+ t = np.clip(t, 0, 1) # ensure t is in [0, 1]
902
+ points = (1 - t) * start_points + t * end_points # lerp
903
+
904
+ # Adjust points for aspect ratio
905
+ points[:, 0] *= aspect_ratio
906
+
907
+ vor = Voronoi(points)
908
+
909
+ # Create a blank image with a white background
910
+ fig, ax = plt.subplots()
911
+ plt.subplots_adjust(left=0, right=1, bottom=0, top=1)
912
+ ax.set_xlim([0, aspect_ratio]); ax.set_ylim([0, 1]) # adjust x limits
913
+ ax.axis('off')
914
+ ax.margins(0, 0)
915
+ fig.set_size_inches(aspect_ratio * frame_height/100, frame_height/100) # adjust figure size
916
+ ax.fill_between([0, 1], [0, 1], color='white')
917
+
918
+ # Plot each Voronoi ridge
919
+ for simplex in vor.ridge_vertices:
920
+ simplex = np.asarray(simplex)
921
+ if np.all(simplex >= 0):
922
+ plt.plot(vor.vertices[simplex, 0], vor.vertices[simplex, 1], 'k-', linewidth=line_width)
923
+
924
+ fig.canvas.draw()
925
+ img = np.array(fig.canvas.renderer._renderer)
926
+
927
+ plt.close(fig)
928
+
929
+ pil_img = Image.fromarray(img).convert("L")
930
+ mask = torch.tensor(np.array(pil_img)) / 255.0
931
+
932
+ out.append(mask)
933
+
934
+ return (torch.stack(out, dim=0), 1.0 - torch.stack(out, dim=0),)
935
+
936
+ class GetMaskSizeAndCount:
937
+ @classmethod
938
+ def INPUT_TYPES(s):
939
+ return {"required": {
940
+ "mask": ("MASK",),
941
+ }}
942
+
943
+ RETURN_TYPES = ("MASK","INT", "INT", "INT",)
944
+ RETURN_NAMES = ("mask", "width", "height", "count",)
945
+ FUNCTION = "getsize"
946
+ CATEGORY = "KJNodes/masking"
947
+ DESCRIPTION = """
948
+ Returns the width, height and batch size of the mask,
949
+ and passes it through unchanged.
950
+
951
+ """
952
+
953
+ def getsize(self, mask):
954
+ width = mask.shape[2]
955
+ height = mask.shape[1]
956
+ count = mask.shape[0]
957
+ return {"ui": {
958
+ "text": [f"{count}x{width}x{height}"]},
959
+ "result": (mask, width, height, count)
960
+ }
961
+
962
+ class GrowMaskWithBlur:
963
+ @classmethod
964
+ def INPUT_TYPES(cls):
965
+ return {
966
+ "required": {
967
+ "mask": ("MASK",),
968
+ "expand": ("INT", {"default": 0, "min": -MAX_RESOLUTION, "max": MAX_RESOLUTION, "step": 1}),
969
+ "incremental_expandrate": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 100.0, "step": 0.1}),
970
+ "tapered_corners": ("BOOLEAN", {"default": True}),
971
+ "flip_input": ("BOOLEAN", {"default": False}),
972
+ "blur_radius": ("FLOAT", {
973
+ "default": 0.0,
974
+ "min": 0.0,
975
+ "max": 100,
976
+ "step": 0.1
977
+ }),
978
+ "lerp_alpha": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
979
+ "decay_factor": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
980
+ },
981
+ "optional": {
982
+ "fill_holes": ("BOOLEAN", {"default": False}),
983
+ },
984
+ }
985
+
986
+ CATEGORY = "KJNodes/masking"
987
+ RETURN_TYPES = ("MASK", "MASK",)
988
+ RETURN_NAMES = ("mask", "mask_inverted",)
989
+ FUNCTION = "expand_mask"
990
+ DESCRIPTION = """
991
+ # GrowMaskWithBlur
992
+ - mask: Input mask or mask batch
993
+ - expand: Expand or contract mask or mask batch by a given amount
994
+ - incremental_expandrate: increase expand rate by a given amount per frame
995
+ - tapered_corners: use tapered corners
996
+ - flip_input: flip input mask
997
+ - blur_radius: value higher than 0 will blur the mask
998
+ - lerp_alpha: alpha value for interpolation between frames
999
+ - decay_factor: decay value for interpolation between frames
1000
+ - fill_holes: fill holes in the mask (slow)"""
1001
+
1002
+ def expand_mask(self, mask, expand, tapered_corners, flip_input, blur_radius, incremental_expandrate, lerp_alpha, decay_factor, fill_holes=False):
1003
+ import kornia.morphology as morph
1004
+ alpha = lerp_alpha
1005
+ decay = decay_factor
1006
+ if flip_input:
1007
+ mask = 1.0 - mask
1008
+
1009
+ growmask = mask.reshape((-1, mask.shape[-2], mask.shape[-1]))
1010
+ out = []
1011
+ previous_output = None
1012
+ current_expand = expand
1013
+ for m in tqdm(growmask, desc="Expanding/Contracting Mask"):
1014
+ output = m.unsqueeze(0).unsqueeze(0).to(main_device) # Add batch and channel dims for kornia
1015
+ if abs(round(current_expand)) > 0:
1016
+ # Create kernel - kornia expects kernel on same device as input
1017
+ if tapered_corners:
1018
+ kernel = torch.tensor([[0, 1, 0],
1019
+ [1, 1, 1],
1020
+ [0, 1, 0]], dtype=torch.float32, device=output.device)
1021
+ else:
1022
+ kernel = torch.tensor([[1, 1, 1],
1023
+ [1, 1, 1],
1024
+ [1, 1, 1]], dtype=torch.float32, device=output.device)
1025
+
1026
+ for _ in range(abs(round(current_expand))):
1027
+ if current_expand < 0:
1028
+ output = morph.erosion(output, kernel)
1029
+ else:
1030
+ output = morph.dilation(output, kernel)
1031
+
1032
+ output = output.squeeze(0).squeeze(0) # Remove batch and channel dims
1033
+
1034
+ if current_expand < 0:
1035
+ current_expand -= abs(incremental_expandrate)
1036
+ else:
1037
+ current_expand += abs(incremental_expandrate)
1038
+
1039
+ if fill_holes:
1040
+ binary_mask = output > 0
1041
+ output_np = binary_mask.cpu().numpy()
1042
+ filled = scipy.ndimage.binary_fill_holes(output_np)
1043
+ output = torch.from_numpy(filled.astype(np.float32)).to(output.device)
1044
+
1045
+ if alpha < 1.0 and previous_output is not None:
1046
+ output = alpha * output + (1 - alpha) * previous_output
1047
+ if decay < 1.0 and previous_output is not None:
1048
+ output += decay * previous_output
1049
+ output = output / output.max()
1050
+ previous_output = output
1051
+ out.append(output.cpu())
1052
+
1053
+ if blur_radius != 0:
1054
+ # Convert the tensor list to PIL images, apply blur, and convert back
1055
+ for idx, tensor in enumerate(out):
1056
+ # Convert tensor to PIL image
1057
+ pil_image = tensor2pil(tensor.cpu().detach())[0]
1058
+ # Apply Gaussian blur
1059
+ pil_image = pil_image.filter(ImageFilter.GaussianBlur(blur_radius))
1060
+ # Convert back to tensor
1061
+ out[idx] = pil2tensor(pil_image)
1062
+ blurred = torch.cat(out, dim=0)
1063
+ return (blurred, 1.0 - blurred)
1064
+ else:
1065
+ return (torch.stack(out, dim=0), 1.0 - torch.stack(out, dim=0),)
1066
+
1067
+ class MaskBatchMulti:
1068
+ @classmethod
1069
+ def INPUT_TYPES(s):
1070
+ return {
1071
+ "required": {
1072
+ "inputcount": ("INT", {"default": 2, "min": 2, "max": 1000, "step": 1}),
1073
+ "mask_1": ("MASK", ),
1074
+ "mask_2": ("MASK", ),
1075
+ },
1076
+ }
1077
+
1078
+ RETURN_TYPES = ("MASK",)
1079
+ RETURN_NAMES = ("masks",)
1080
+ FUNCTION = "combine"
1081
+ CATEGORY = "KJNodes/masking"
1082
+ DESCRIPTION = """
1083
+ Creates an image batch from multiple masks.
1084
+ You can set how many inputs the node has,
1085
+ with the **inputcount** and clicking update.
1086
+ """
1087
+
1088
+ def combine(self, inputcount, **kwargs):
1089
+ mask = kwargs["mask_1"]
1090
+ for c in range(1, inputcount):
1091
+ new_mask = kwargs[f"mask_{c + 1}"]
1092
+ if mask.shape[1:] != new_mask.shape[1:]:
1093
+ new_mask = F.interpolate(new_mask.unsqueeze(1), size=(mask.shape[1], mask.shape[2]), mode="bicubic").squeeze(1)
1094
+ mask = torch.cat((mask, new_mask), dim=0)
1095
+ return (mask,)
1096
+
1097
+ class OffsetMask:
1098
+ @classmethod
1099
+ def INPUT_TYPES(s):
1100
+ return {
1101
+ "required": {
1102
+ "mask": ("MASK",),
1103
+ "x": ("INT", { "default": 0, "min": -4096, "max": MAX_RESOLUTION, "step": 1, "display": "number" }),
1104
+ "y": ("INT", { "default": 0, "min": -4096, "max": MAX_RESOLUTION, "step": 1, "display": "number" }),
1105
+ "angle": ("INT", { "default": 0, "min": -360, "max": 360, "step": 1, "display": "number" }),
1106
+ "duplication_factor": ("INT", { "default": 1, "min": 1, "max": 1000, "step": 1, "display": "number" }),
1107
+ "roll": ("BOOLEAN", { "default": False }),
1108
+ "incremental": ("BOOLEAN", { "default": False }),
1109
+ "padding_mode": (
1110
+ [
1111
+ 'empty',
1112
+ 'border',
1113
+ 'reflection',
1114
+
1115
+ ], {
1116
+ "default": 'empty'
1117
+ }),
1118
+ }
1119
+ }
1120
+
1121
+ RETURN_TYPES = ("MASK",)
1122
+ RETURN_NAMES = ("mask",)
1123
+ FUNCTION = "offset"
1124
+ CATEGORY = "KJNodes/masking"
1125
+ DESCRIPTION = """
1126
+ Offsets the mask by the specified amount.
1127
+ - mask: Input mask or mask batch
1128
+ - x: Horizontal offset
1129
+ - y: Vertical offset
1130
+ - angle: Angle in degrees
1131
+ - roll: roll edge wrapping
1132
+ - duplication_factor: Number of times to duplicate the mask to form a batch
1133
+ - border padding_mode: Padding mode for the mask
1134
+ """
1135
+
1136
+ def offset(self, mask, x, y, angle, roll=False, incremental=False, duplication_factor=1, padding_mode="empty"):
1137
+ # Create duplicates of the mask batch
1138
+ mask = mask.repeat(duplication_factor, 1, 1).clone()
1139
+
1140
+ batch_size, height, width = mask.shape
1141
+
1142
+ if angle != 0 and incremental:
1143
+ for i in range(batch_size):
1144
+ rotation_angle = angle * (i+1)
1145
+ mask[i] = TF.rotate(mask[i].unsqueeze(0), rotation_angle).squeeze(0)
1146
+ elif angle > 0:
1147
+ for i in range(batch_size):
1148
+ mask[i] = TF.rotate(mask[i].unsqueeze(0), angle).squeeze(0)
1149
+
1150
+ if roll:
1151
+ if incremental:
1152
+ for i in range(batch_size):
1153
+ shift_x = min(x*(i+1), width-1)
1154
+ shift_y = min(y*(i+1), height-1)
1155
+ if shift_x != 0:
1156
+ mask[i] = torch.roll(mask[i], shifts=shift_x, dims=1)
1157
+ if shift_y != 0:
1158
+ mask[i] = torch.roll(mask[i], shifts=shift_y, dims=0)
1159
+ else:
1160
+ shift_x = min(x, width-1)
1161
+ shift_y = min(y, height-1)
1162
+ if shift_x != 0:
1163
+ mask = torch.roll(mask, shifts=shift_x, dims=2)
1164
+ if shift_y != 0:
1165
+ mask = torch.roll(mask, shifts=shift_y, dims=1)
1166
+ else:
1167
+
1168
+ for i in range(batch_size):
1169
+ if incremental:
1170
+ temp_x = min(x * (i+1), width-1)
1171
+ temp_y = min(y * (i+1), height-1)
1172
+ else:
1173
+ temp_x = min(x, width-1)
1174
+ temp_y = min(y, height-1)
1175
+ if temp_x > 0:
1176
+ if padding_mode == 'empty':
1177
+ mask[i] = torch.cat([torch.zeros((height, temp_x)), mask[i, :, :-temp_x]], dim=1)
1178
+ elif padding_mode in ['replicate', 'reflect']:
1179
+ mask[i] = F.pad(mask[i, :, :-temp_x], (0, temp_x), mode=padding_mode)
1180
+ elif temp_x < 0:
1181
+ if padding_mode == 'empty':
1182
+ mask[i] = torch.cat([mask[i, :, :temp_x], torch.zeros((height, -temp_x))], dim=1)
1183
+ elif padding_mode in ['replicate', 'reflect']:
1184
+ mask[i] = F.pad(mask[i, :, -temp_x:], (temp_x, 0), mode=padding_mode)
1185
+
1186
+ if temp_y > 0:
1187
+ if padding_mode == 'empty':
1188
+ mask[i] = torch.cat([torch.zeros((temp_y, width)), mask[i, :-temp_y, :]], dim=0)
1189
+ elif padding_mode in ['replicate', 'reflect']:
1190
+ mask[i] = F.pad(mask[i, :-temp_y, :], (0, temp_y), mode=padding_mode)
1191
+ elif temp_y < 0:
1192
+ if padding_mode == 'empty':
1193
+ mask[i] = torch.cat([mask[i, :temp_y, :], torch.zeros((-temp_y, width))], dim=0)
1194
+ elif padding_mode in ['replicate', 'reflect']:
1195
+ mask[i] = F.pad(mask[i, -temp_y:, :], (temp_y, 0), mode=padding_mode)
1196
+
1197
+ return mask,
1198
+
1199
+ class RoundMask:
1200
+ @classmethod
1201
+ def INPUT_TYPES(s):
1202
+ return {"required": {
1203
+ "mask": ("MASK",),
1204
+ }}
1205
+
1206
+ RETURN_TYPES = ("MASK",)
1207
+ FUNCTION = "round"
1208
+ CATEGORY = "KJNodes/masking"
1209
+ DESCRIPTION = """
1210
+ Rounds the mask or batch of masks to a binary mask.
1211
+ <img src="https://github.com/kijai/ComfyUI-KJNodes/assets/40791699/52c85202-f74e-4b96-9dac-c8bda5ddcc40" width="300" height="250" alt="RoundMask example">
1212
+
1213
+ """
1214
+
1215
+ def round(self, mask):
1216
+ mask = mask.round()
1217
+ return (mask,)
1218
+
1219
+ class ResizeMask:
1220
+ upscale_methods = ["nearest-exact", "bilinear", "area", "bicubic", "lanczos"]
1221
+ @classmethod
1222
+ def INPUT_TYPES(s):
1223
+ return {
1224
+ "required": {
1225
+ "mask": ("MASK",),
1226
+ "width": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, "display": "number" }),
1227
+ "height": ("INT", { "default": 512, "min": 0, "max": MAX_RESOLUTION, "step": 1, "display": "number" }),
1228
+ "keep_proportions": ("BOOLEAN", { "default": False }),
1229
+ "upscale_method": (s.upscale_methods,),
1230
+ "crop": (["disabled","center"],),
1231
+ }
1232
+ }
1233
+
1234
+ RETURN_TYPES = ("MASK", "INT", "INT",)
1235
+ RETURN_NAMES = ("mask", "width", "height",)
1236
+ FUNCTION = "resize"
1237
+ CATEGORY = "KJNodes/masking"
1238
+ DESCRIPTION = """
1239
+ Resizes the mask or batch of masks to the specified width and height.
1240
+ """
1241
+
1242
+ def resize(self, mask, width, height, keep_proportions, upscale_method,crop):
1243
+ if keep_proportions:
1244
+ _, oh, ow = mask.shape
1245
+ width = ow if width == 0 else width
1246
+ height = oh if height == 0 else height
1247
+ ratio = min(width / ow, height / oh)
1248
+ width = round(ow*ratio)
1249
+ height = round(oh*ratio)
1250
+
1251
+ if upscale_method == "lanczos":
1252
+ out_mask = common_upscale(mask.unsqueeze(1).repeat(1, 3, 1, 1), width, height, upscale_method, crop=crop).movedim(1,-1)[:, :, :, 0]
1253
+ else:
1254
+ out_mask = common_upscale(mask.unsqueeze(1), width, height, upscale_method, crop=crop).squeeze(1)
1255
+
1256
+ return(out_mask, out_mask.shape[2], out_mask.shape[1],)
1257
+
1258
+ class RemapMaskRange:
1259
+ @classmethod
1260
+ def INPUT_TYPES(s):
1261
+ return {
1262
+ "required": {
1263
+ "mask": ("MASK",),
1264
+ "min": ("FLOAT", {"default": 0.0,"min": -10.0, "max": 1.0, "step": 0.01}),
1265
+ "max": ("FLOAT", {"default": 1.0,"min": 0.0, "max": 10.0, "step": 0.01}),
1266
+ }
1267
+ }
1268
+
1269
+ RETURN_TYPES = ("MASK",)
1270
+ RETURN_NAMES = ("mask",)
1271
+ FUNCTION = "remap"
1272
+ CATEGORY = "KJNodes/masking"
1273
+ DESCRIPTION = """
1274
+ Sets new min and max values for the mask.
1275
+ """
1276
+
1277
+ def remap(self, mask, min, max):
1278
+
1279
+ # Find the maximum value in the mask
1280
+ mask_max = torch.max(mask)
1281
+
1282
+ # If the maximum mask value is zero, avoid division by zero by setting it to 1
1283
+ mask_max = mask_max if mask_max > 0 else 1
1284
+
1285
+ # Scale the mask values to the new range defined by min and max
1286
+ # The highest pixel value in the mask will be scaled to max
1287
+ scaled_mask = (mask / mask_max) * (max - min) + min
1288
+
1289
+ # Clamp the values to ensure they are within [0.0, 1.0]
1290
+ scaled_mask = torch.clamp(scaled_mask, min=0.0, max=1.0)
1291
+
1292
+ return (scaled_mask, )
1293
+
1294
+
1295
+ def get_mask_polygon(self, mask_np):
1296
+ import cv2
1297
+ """Helper function to get polygon points from mask"""
1298
+ # Find contours
1299
+ contours, _ = cv2.findContours(mask_np, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
1300
+
1301
+ if not contours:
1302
+ return None
1303
+
1304
+ # Get the largest contour
1305
+ largest_contour = max(contours, key=cv2.contourArea)
1306
+
1307
+ # Approximate polygon
1308
+ epsilon = 0.02 * cv2.arcLength(largest_contour, True)
1309
+ polygon = cv2.approxPolyDP(largest_contour, epsilon, True)
1310
+
1311
+ return polygon.squeeze()
1312
+
1313
+ import cv2
1314
+ class SeparateMasks:
1315
+ @classmethod
1316
+ def INPUT_TYPES(cls):
1317
+ return {
1318
+ "required": {
1319
+ "mask": ("MASK", ),
1320
+ "size_threshold_width" : ("INT", {"default": 256, "min": 0.0, "max": 4096, "step": 1}),
1321
+ "size_threshold_height" : ("INT", {"default": 256, "min": 0.0, "max": 4096, "step": 1}),
1322
+ "mode": (["convex_polygons", "area", "box"],),
1323
+ "max_poly_points": ("INT", {"default": 8, "min": 3, "max": 32, "step": 1}),
1324
+
1325
+ },
1326
+ }
1327
+
1328
+ RETURN_TYPES = ("MASK",)
1329
+ RETURN_NAMES = ("mask",)
1330
+ FUNCTION = "separate"
1331
+ CATEGORY = "KJNodes/masking"
1332
+ OUTPUT_NODE = True
1333
+ DESCRIPTION = "Separates a mask into multiple masks based on the size of the connected components."
1334
+
1335
+ def polygon_to_mask(self, polygon, shape):
1336
+ mask = np.zeros((shape[0], shape[1]), dtype=np.uint8) # Fixed shape handling
1337
+
1338
+ if len(polygon.shape) == 2: # Check if polygon points are valid
1339
+ polygon = polygon.astype(np.int32)
1340
+ cv2.fillPoly(mask, [polygon], 1)
1341
+ return mask
1342
+
1343
+ def get_mask_polygon(self, mask_np, max_points):
1344
+ contours, _ = cv2.findContours(mask_np, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
1345
+ if not contours:
1346
+ return None
1347
+
1348
+ largest_contour = max(contours, key=cv2.contourArea)
1349
+ hull = cv2.convexHull(largest_contour)
1350
+
1351
+ # Initialize with smaller epsilon for more points
1352
+ perimeter = cv2.arcLength(hull, True)
1353
+ epsilon = perimeter * 0.01 # Start smaller
1354
+
1355
+ min_eps = perimeter * 0.001 # Much smaller minimum
1356
+ max_eps = perimeter * 0.2 # Smaller maximum
1357
+
1358
+ best_approx = None
1359
+ best_diff = float('inf')
1360
+ max_iterations = 20
1361
+
1362
+ #print(f"Target points: {max_points}, Perimeter: {perimeter}")
1363
+
1364
+ for i in range(max_iterations):
1365
+ curr_eps = (min_eps + max_eps) / 2
1366
+ approx = cv2.approxPolyDP(hull, curr_eps, True)
1367
+ points_diff = len(approx) - max_points
1368
+
1369
+ #print(f"Iteration {i}: points={len(approx)}, eps={curr_eps:.4f}")
1370
+
1371
+ if abs(points_diff) < best_diff:
1372
+ best_approx = approx
1373
+ best_diff = abs(points_diff)
1374
+
1375
+ if len(approx) > max_points:
1376
+ min_eps = curr_eps * 1.1 # More gradual adjustment
1377
+ elif len(approx) < max_points:
1378
+ max_eps = curr_eps * 0.9 # More gradual adjustment
1379
+ else:
1380
+ return approx.squeeze()
1381
+
1382
+ if abs(max_eps - min_eps) < perimeter * 0.0001: # Relative tolerance
1383
+ break
1384
+
1385
+ # If we didn't find exact match, return best approximation
1386
+ return best_approx.squeeze() if best_approx is not None else hull.squeeze()
1387
+
1388
+ def separate(self, mask: torch.Tensor, size_threshold_width: int, size_threshold_height: int, max_poly_points: int, mode: str):
1389
+ from scipy.ndimage import label, center_of_mass
1390
+ import numpy as np
1391
+
1392
+ B, H, W = mask.shape
1393
+ separated = []
1394
+
1395
+ mask = mask.round()
1396
+
1397
+ for b in range(B):
1398
+ mask_np = mask[b].cpu().numpy().astype(np.uint8)
1399
+ structure = np.ones((3, 3), dtype=np.int8)
1400
+ labeled, ncomponents = label(mask_np, structure=structure)
1401
+ pbar = ProgressBar(ncomponents)
1402
+
1403
+ for component in range(1, ncomponents + 1):
1404
+ component_mask_np = (labeled == component).astype(np.uint8)
1405
+
1406
+ rows = np.any(component_mask_np, axis=1)
1407
+ cols = np.any(component_mask_np, axis=0)
1408
+ y_min, y_max = np.where(rows)[0][[0, -1]]
1409
+ x_min, x_max = np.where(cols)[0][[0, -1]]
1410
+
1411
+ width = x_max - x_min + 1
1412
+ height = y_max - y_min + 1
1413
+ centroid_x = (x_min + x_max) / 2 # Calculate x centroid
1414
+ print(f"Component {component}: width={width}, height={height}, x_pos={centroid_x}")
1415
+
1416
+ if width >= size_threshold_width and height >= size_threshold_height:
1417
+ if mode == "convex_polygons":
1418
+ polygon = self.get_mask_polygon(component_mask_np, max_poly_points)
1419
+ if polygon is not None:
1420
+ poly_mask = self.polygon_to_mask(polygon, (H, W))
1421
+ poly_mask = torch.tensor(poly_mask, device=mask.device)
1422
+ separated.append((centroid_x, poly_mask))
1423
+ elif mode == "box":
1424
+ # Create bounding box mask
1425
+ box_mask = np.zeros((H, W), dtype=np.uint8)
1426
+ box_mask[y_min:y_max+1, x_min:x_max+1] = 1
1427
+ box_mask = torch.tensor(box_mask, device=mask.device)
1428
+ separated.append((centroid_x, box_mask))
1429
+ else:
1430
+ area_mask = torch.tensor(component_mask_np, device=mask.device)
1431
+ separated.append((centroid_x, area_mask))
1432
+ pbar.update(1)
1433
+
1434
+ if len(separated) > 0:
1435
+ # Sort by x position and extract only the masks
1436
+ separated.sort(key=lambda x: x[0])
1437
+ separated = [x[1] for x in separated]
1438
+ out_masks = torch.stack(separated, dim=0)
1439
+ return out_masks,
1440
+ else:
1441
+ return torch.empty((1, 64, 64), device=mask.device),
1442
+
1443
+
1444
+ class ConsolidateMasksKJ:
1445
+ @classmethod
1446
+ def INPUT_TYPES(s):
1447
+ return {
1448
+ "required": {
1449
+ "masks": ("MASK",),
1450
+ "width": ("INT", {"default": 512, "min": 0, "max": 4096, "step": 64}),
1451
+ "height": ("INT", {"default": 512, "min": 0, "max": 4096, "step": 64}),
1452
+ "padding": ("INT", {"default": 0, "min": 0, "max": 4096, "step": 1}),
1453
+ },
1454
+ }
1455
+
1456
+ RETURN_TYPES = ("MASK",)
1457
+ FUNCTION = "consolidate"
1458
+
1459
+ CATEGORY = "KJNodes/masking"
1460
+ DESCRIPTION = "Consolidates a batch of separate masks by finding the largest group of masks that fit inside a tile of the given width and height (including the padding), and repeating until no more masks can be combined."
1461
+
1462
+ def consolidate(self, masks, width=512, height=512, padding=0):
1463
+ B, H, W = masks.shape
1464
+
1465
+ def mask_fits(coords, candidate_coords):
1466
+ x_min, y_min, x_max, y_max = coords
1467
+ cx_min, cy_min, cx_max, cy_max = candidate_coords
1468
+ nx_min, ny_min = min(x_min, cx_min), min(y_min, cy_min)
1469
+ nx_max, ny_max = max(x_max, cx_max), max(y_max, cy_max)
1470
+ if nx_min + width < nx_max + padding or ny_min + height < ny_max + padding:
1471
+ return False, coords
1472
+ return True, (nx_min, ny_min, nx_max, ny_max)
1473
+
1474
+ separated = []
1475
+ final_masks = []
1476
+ for b in range(B):
1477
+ m = masks[b]
1478
+ rows, cols = m.any(dim=1), m.any(dim=0)
1479
+ y_min, y_max = torch.where(rows)[0][[0, -1]]
1480
+ x_min, x_max = torch.where(cols)[0][[0, -1]]
1481
+ w = x_max - x_min + 1
1482
+ h = y_max - y_min + 1
1483
+ separated.append(((x_min.item(), y_min.item(), x_max.item(), y_max.item()), m))
1484
+
1485
+ separated.sort(key=lambda x: x[0])
1486
+ fits = []
1487
+ for i, masks in enumerate(separated):
1488
+ coord = masks[0]
1489
+ fits_in_box = []
1490
+ for j, cand_mask in enumerate(separated):
1491
+ if i == j:
1492
+ continue
1493
+ r, coord = mask_fits(coord, cand_mask[0])
1494
+ if r:
1495
+ fits_in_box.append(j)
1496
+ fits.append((i, fits_in_box))
1497
+ fits.sort(key=lambda x: -len(x[1]))
1498
+ seen = []
1499
+ unique_fits = []
1500
+ for idx, fs in fits:
1501
+ uniq = [i for i in fs if i not in seen]
1502
+ unique_fits.append((idx, fs, uniq))
1503
+ seen.extend(uniq)
1504
+ unique_fits.sort(key=lambda x: (-len(x[1]), -len(x[2])))
1505
+ merged = []
1506
+ for mask_idx, fitting_masks, _ in unique_fits:
1507
+ if mask_idx in merged:
1508
+ continue
1509
+ fitting_masks = [i for i in fitting_masks if i not in merged]
1510
+ combined_mask = separated[mask_idx][1].clone()
1511
+ for i in fitting_masks:
1512
+ combined_mask += separated[i][1]
1513
+ merged.append(i)
1514
+ merged.append(mask_idx)
1515
+ final_masks.append(combined_mask)
1516
+
1517
+ print(f"Consolidated {B} masks into {len(final_masks)}")
1518
+ return (torch.stack(final_masks, dim=0),)
1519
+
1520
+
1521
+ class DrawMaskOnImage:
1522
+ @classmethod
1523
+ def INPUT_TYPES(s):
1524
+ return {"required": {
1525
+ "image": ("IMAGE", ),
1526
+ "mask": ("MASK", ),
1527
+ "color": ("STRING", {"default": "0, 0, 0", "tooltip": "Color as RGB values in range 0-255 or 0.0-1.0, separated by commas."}),
1528
+ },
1529
+ "optional": {
1530
+ "device": (["cpu", "gpu"], {"default": "cpu", "tooltip": "Device to use for processing"}),
1531
+ }
1532
+ }
1533
+
1534
+ RETURN_TYPES = ("IMAGE", )
1535
+ RETURN_NAMES = ("images",)
1536
+ FUNCTION = "apply"
1537
+ CATEGORY = "KJNodes/masking"
1538
+ DESCRIPTION = "Applies the provided masks to the input images."
1539
+
1540
+ def apply(self, image, mask, color, device="cpu"):
1541
+ B, H, W, C = image.shape
1542
+ BM, HM, WM = mask.shape
1543
+
1544
+ processing_device = main_device if device == "gpu" else torch.device("cpu")
1545
+
1546
+ in_masks = mask.clone().to(processing_device)
1547
+ in_images = image.clone().to(processing_device)
1548
+
1549
+ if HM != H or WM != W:
1550
+ in_masks = F.interpolate(mask.unsqueeze(1), size=(H, W), mode='nearest-exact').squeeze(1)
1551
+ if B > BM:
1552
+ in_masks = in_masks.repeat((B + BM - 1) // BM, 1, 1)[:B]
1553
+ elif BM > B:
1554
+ in_masks = in_masks[:B]
1555
+
1556
+ output_images = []
1557
+
1558
+ # Parse background color - detect if values are integers or floats
1559
+ bg_values = []
1560
+ for x in color.split(","):
1561
+ val_str = x.strip()
1562
+ if '.' in val_str:
1563
+ bg_values.append(float(val_str))
1564
+ else:
1565
+ bg_values.append(int(val_str) / 255.0)
1566
+
1567
+ background_color = torch.tensor(bg_values, dtype=torch.float32, device=in_images.device)
1568
+
1569
+ for i in tqdm(range(B), desc="DrawMaskOnImage batch"):
1570
+ curr_mask = in_masks[i]
1571
+ img_idx = min(i, B - 1)
1572
+ curr_image = in_images[img_idx]
1573
+ mask_expanded = curr_mask.unsqueeze(-1).expand(-1, -1, 3)
1574
+ masked_image = curr_image * (1 - mask_expanded) + background_color * (mask_expanded)
1575
+ output_images.append(masked_image)
1576
+
1577
+ # If no masks were processed, return empty tensor
1578
+ if not output_images:
1579
+ return (torch.zeros((0, H, W, 3), dtype=image.dtype),)
1580
+
1581
+ out_rgb = torch.stack(output_images, dim=0).cpu()
1582
+
1583
+ return (out_rgb, )
1584
+
1585
+
1586
+ class BlockifyMask:
1587
+ @classmethod
1588
+ def INPUT_TYPES(s):
1589
+ return {"required": {
1590
+ "masks": ("MASK",),
1591
+ "block_size": ("INT", {"default": 32, "min": 8, "max": 512, "step": 1, "tooltip": "Size of blocks in pixels (smaller = smaller blocks)"}),
1592
+ },
1593
+ "optional": {
1594
+ "device": (["cpu", "gpu"], {"default": "cpu", "tooltip": "Device to use for processing"}),
1595
+ }
1596
+ }
1597
+
1598
+ RETURN_TYPES = ("MASK", )
1599
+ RETURN_NAMES = ("mask",)
1600
+ FUNCTION = "process"
1601
+ CATEGORY = "KJNodes/masking"
1602
+ DESCRIPTION = "Creates a block mask by dividing the bounding box of each mask into blocks of the specified size and filling in blocks that contain any part of the original mask."
1603
+
1604
+ def process(self, masks, block_size, device="cpu"):
1605
+ processing_device = main_device if device == "gpu" else torch.device("cpu")
1606
+
1607
+ masks = masks.to(processing_device)
1608
+ batch_size, height, width = masks.shape
1609
+
1610
+ result_masks = torch.zeros_like(masks)
1611
+
1612
+ for i in tqdm(range(batch_size), desc="BlockifyMask batch"):
1613
+ mask = masks[i]
1614
+
1615
+ # Find bounding box efficiently
1616
+ mask_bool = mask > 0
1617
+ if not mask_bool.any():
1618
+ continue
1619
+
1620
+ y_indices = torch.nonzero(mask_bool.any(dim=1), as_tuple=True)[0]
1621
+ x_indices = torch.nonzero(mask_bool.any(dim=0), as_tuple=True)[0]
1622
+
1623
+ if len(y_indices) == 0 or len(x_indices) == 0:
1624
+ continue
1625
+
1626
+ y_min, y_max = y_indices[0], y_indices[-1]
1627
+ x_min, x_max = x_indices[0], x_indices[-1]
1628
+
1629
+ bbox_width = x_max - x_min + 1
1630
+ bbox_height = y_max - y_min + 1
1631
+
1632
+ # Calculate block grid
1633
+ w_divisions = max(1, bbox_width // block_size)
1634
+ h_divisions = max(1, bbox_height // block_size)
1635
+
1636
+ w_slice = bbox_width // w_divisions
1637
+ h_slice = bbox_height // h_divisions
1638
+
1639
+ # Create coordinate grids only for bbox region
1640
+ y_coords = torch.arange(y_min, y_max + 1, device=processing_device).view(-1, 1)
1641
+ x_coords = torch.arange(x_min, x_max + 1, device=processing_device).view(1, -1)
1642
+
1643
+ # Calculate block indices for bbox region
1644
+ w_block_indices = (x_coords - x_min) // w_slice
1645
+ h_block_indices = (y_coords - y_min) // h_slice
1646
+
1647
+ # Clamp to valid range
1648
+ w_block_indices = w_block_indices.clamp(0, w_divisions - 1)
1649
+ h_block_indices = h_block_indices.clamp(0, h_divisions - 1)
1650
+
1651
+ # Create unique block IDs by combining h and w indices
1652
+ block_ids = h_block_indices * w_divisions + w_block_indices
1653
+
1654
+ # Get mask region within bbox
1655
+ mask_region = mask[y_min:y_max+1, x_min:x_max+1]
1656
+
1657
+ # Find which blocks have content using scatter_add
1658
+ max_blocks = h_divisions * w_divisions
1659
+ block_content = torch.zeros(max_blocks, device=processing_device)
1660
+ block_content.scatter_add_(0, block_ids.flatten(), mask_region.flatten())
1661
+
1662
+ # Create result for blocks that have content
1663
+ has_content = block_content > 0
1664
+ block_mask = has_content[block_ids]
1665
+
1666
+ # Fill the result
1667
+ result_masks[i, y_min:y_max+1, x_min:x_max+1] = block_mask.float()
1668
+
1669
+ return (result_masks.clamp(0, 1),)
nodes/model_optimization_nodes.py ADDED
The diff for this file is too large to render. See raw diff
 
nodes/nodes.py ADDED
The diff for this file is too large to render. See raw diff
 
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.1.7"
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 = "https://avatars.githubusercontent.com/u/40791699"
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
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
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
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)
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
+ ]
web/green.png ADDED
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
+ });
web/js/browserstatus.js ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ pythongossFeed.setup = function() {
51
+ console.warn("Disabled by KJNodes")
52
+ };
53
+ }
54
+ },
55
+ });
web/js/contextmenu.js ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 updateSlots = (value) => {
52
+ const valuesToAddToIn = ["GetNode"];
53
+ const valuesToAddToOut = ["SetNode"];
54
+ // Remove entries if they exist
55
+ for (const arr of Object.values(LiteGraph.slot_types_default_in)) {
56
+ for (const valueToAdd of valuesToAddToIn) {
57
+ const idx = arr.indexOf(valueToAdd);
58
+ if (idx !== -1) {
59
+ arr.splice(idx, 1);
60
+ }
61
+ }
62
+ }
63
+
64
+ for (const arr of Object.values(LiteGraph.slot_types_default_out)) {
65
+ for (const valueToAdd of valuesToAddToOut) {
66
+ const idx = arr.indexOf(valueToAdd);
67
+ if (idx !== -1) {
68
+ arr.splice(idx, 1);
69
+ }
70
+ }
71
+ }
72
+ if (value!="disabled") {
73
+ for (const arr of Object.values(LiteGraph.slot_types_default_in)) {
74
+ for (const valueToAdd of valuesToAddToIn) {
75
+ const idx = arr.indexOf(valueToAdd);
76
+ if (idx !== -1) {
77
+ arr.splice(idx, 1);
78
+ }
79
+ if (value === "top") {
80
+ arr.unshift(valueToAdd);
81
+ } else {
82
+ arr.push(valueToAdd);
83
+ }
84
+ }
85
+ }
86
+
87
+ for (const arr of Object.values(LiteGraph.slot_types_default_out)) {
88
+ for (const valueToAdd of valuesToAddToOut) {
89
+ const idx = arr.indexOf(valueToAdd);
90
+ if (idx !== -1) {
91
+ arr.splice(idx, 1);
92
+ }
93
+ if (value === "top") {
94
+ arr.unshift(valueToAdd);
95
+ } else {
96
+ arr.push(valueToAdd);
97
+ }
98
+ }
99
+ }
100
+ }
101
+ };
102
+
103
+ app.ui.settings.addSetting({
104
+ id: "KJNodes.SetGetMenu",
105
+ name: "KJNodes: Make Set/Get -nodes defaults",
106
+ tooltip: 'Adds Set/Get nodes to the top or bottom of the list of available node suggestions.',
107
+ options: ['disabled', 'top', 'bottom'],
108
+ defaultValue: 'disabled',
109
+ type: "combo",
110
+ onChange: updateSlots,
111
+
112
+ });
113
+ app.ui.settings.addSetting({
114
+ id: "KJNodes.MiddleClickDefault",
115
+ name: "KJNodes: Middle click default node adding",
116
+ defaultValue: false,
117
+ type: "boolean",
118
+ onChange: (value) => {
119
+ LiteGraph.middle_click_slot_add_default_node = value;
120
+ },
121
+ });
122
+ app.ui.settings.addSetting({
123
+ id: "KJNodes.nodeAutoColor",
124
+ name: "KJNodes: Automatically set node colors",
125
+ type: "boolean",
126
+ defaultValue: true,
127
+ });
128
+ app.ui.settings.addSetting({
129
+ id: "KJNodes.helpPopup",
130
+ name: "KJNodes: Help popups",
131
+ defaultValue: true,
132
+ type: "boolean",
133
+ });
134
+ app.ui.settings.addSetting({
135
+ id: "KJNodes.disablePrefix",
136
+ name: "KJNodes: Disable automatic Set_ and Get_ prefix",
137
+ defaultValue: true,
138
+ type: "boolean",
139
+ });
140
+ app.ui.settings.addSetting({
141
+ id: "KJNodes.browserStatus",
142
+ name: "KJNodes: 🟢 Stoplight browser status icon 🔴",
143
+ defaultValue: false,
144
+ type: "boolean",
145
+ });
146
+ }
147
+ });
web/js/fast_preview.js ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ function chainCallback(object, property, callback) {
15
+ if (object == undefined) {
16
+ //This should not happen.
17
+ console.error("Tried to add callback to non-existant object")
18
+ return;
19
+ }
20
+ if (property in object) {
21
+ const callback_orig = object[property]
22
+ object[property] = function () {
23
+ const r = callback_orig.apply(this, arguments);
24
+ callback.apply(this, arguments);
25
+ return r
26
+ };
27
+ } else {
28
+ object[property] = callback;
29
+ }
30
+ }
31
+ app.registerExtension({
32
+ name: 'KJNodes.FastPreview',
33
+
34
+ async beforeRegisterNodeDef(nodeType, nodeData) {
35
+ if (nodeData?.name === 'FastPreview') {
36
+ chainCallback(nodeType.prototype, "onNodeCreated", function () {
37
+
38
+ var element = document.createElement("div");
39
+ this.uuid = makeUUID()
40
+ element.id = `fast-preview-${this.uuid}`
41
+
42
+ this.previewWidget = this.addDOMWidget(nodeData.name, "FastPreviewWidget", element, {
43
+ serialize: false,
44
+ hideOnZoom: false,
45
+ });
46
+
47
+ this.previewer = new Previewer(this);
48
+
49
+ this.setSize([550, 550]);
50
+ this.resizable = false;
51
+ this.previewWidget.parentEl = document.createElement("div");
52
+ this.previewWidget.parentEl.className = "fast-preview";
53
+ this.previewWidget.parentEl.id = `fast-preview-${this.uuid}`
54
+ element.appendChild(this.previewWidget.parentEl);
55
+
56
+ chainCallback(this, "onExecuted", function (message) {
57
+ let bg_image = message["bg_image"];
58
+ this.properties.imgData = {
59
+ name: "bg_image",
60
+ base64: bg_image
61
+ };
62
+ this.previewer.refreshBackgroundImage(this);
63
+ });
64
+
65
+
66
+ }); // onAfterGraphConfigured
67
+ }//node created
68
+ } //before register
69
+ })//register
70
+
71
+ class Previewer {
72
+ constructor(context) {
73
+ this.node = context;
74
+ this.previousWidth = null;
75
+ this.previousHeight = null;
76
+ }
77
+ refreshBackgroundImage = () => {
78
+ const imgData = this.node?.properties?.imgData;
79
+ if (imgData?.base64) {
80
+ const base64String = imgData.base64;
81
+ const imageUrl = `data:${imgData.type};base64,${base64String}`;
82
+ const img = new Image();
83
+ img.src = imageUrl;
84
+ img.onload = () => {
85
+ const { width, height } = img;
86
+ if (width !== this.previousWidth || height !== this.previousHeight) {
87
+ this.node.setSize([width, height]);
88
+ this.previousWidth = width;
89
+ this.previousHeight = height;
90
+ }
91
+ this.node.previewWidget.element.style.backgroundImage = `url(${imageUrl})`;
92
+ };
93
+ }
94
+ };
95
+ }
web/js/help_popup.js ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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", "WanVideoWrapper"];
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
+ const bcr = app.canvas.canvas.getBoundingClientRect()
261
+
262
+ const styleObject = {
263
+ transformOrigin: '0 0',
264
+ transform: scale,
265
+ left: `${transform.a + bcr.x + transform.e}px`,
266
+ top: `${transform.d + bcr.y + transform.f}px`,
267
+ };
268
+ Object.assign(docElement.style, styleObject);
269
+ }
270
+
271
+ ctx.save()
272
+ ctx.translate(x - 2, iconSize - 34)
273
+ ctx.scale(iconSize / 32, iconSize / 32)
274
+ ctx.strokeStyle = 'rgba(255,255,255,0.3)'
275
+ ctx.lineCap = 'round'
276
+ ctx.lineJoin = 'round'
277
+ ctx.lineWidth = 2.4
278
+ ctx.font = 'bold 36px monospace'
279
+ ctx.fillStyle = 'orange';
280
+ ctx.fillText('?', 0, 24)
281
+ ctx.restore()
282
+ return r
283
+ }
284
+ // handle clicking of the icon
285
+ const mouseDown = nodeType.prototype.onMouseDown
286
+ nodeType.prototype.onMouseDown = function (e, localPos, canvas) {
287
+ const r = mouseDown ? mouseDown.apply(this, arguments) : undefined
288
+ const iconX = this.size[0] - iconSize - iconMargin
289
+ const iconY = iconSize - 34
290
+ if (
291
+ localPos[0] > iconX &&
292
+ localPos[0] < iconX + iconSize &&
293
+ localPos[1] > iconY &&
294
+ localPos[1] < iconY + iconSize
295
+ ) {
296
+ if (this.show_doc === undefined) {
297
+ this.show_doc = true
298
+ } else {
299
+ this.show_doc = !this.show_doc
300
+ }
301
+ if (this.show_doc) {
302
+ this.docCtrl = new AbortController()
303
+ } else {
304
+ this.docCtrl.abort()
305
+ }
306
+ return true;
307
+ }
308
+ return r;
309
+ }
310
+ const onRem = nodeType.prototype.onRemoved
311
+
312
+ nodeType.prototype.onRemoved = function () {
313
+ const r = onRem ? onRem.apply(this, []) : undefined
314
+
315
+ if (docElement) {
316
+ docElement.remove()
317
+ docElement = null
318
+ }
319
+
320
+ if (contentWrapper) {
321
+ contentWrapper.remove()
322
+ contentWrapper = null
323
+ }
324
+ return r
325
+ }
326
+ }
web/js/jsnodes.js ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../../scripts/app.js";
2
+ import { applyTextReplacements } from "../../../scripts/utils.js";
3
+
4
+ app.registerExtension({
5
+ name: "KJNodes.jsnodes",
6
+ async beforeRegisterNodeDef(nodeType, nodeData, app) {
7
+ if(!nodeData?.category?.startsWith("KJNodes")) {
8
+ return;
9
+ }
10
+ switch (nodeData.name) {
11
+ case "ConditioningMultiCombine":
12
+ nodeType.prototype.onNodeCreated = function () {
13
+ this._type = "CONDITIONING"
14
+ this.inputs_offset = nodeData.name.includes("selective")?1:0
15
+ this.addWidget("button", "Update inputs", null, () => {
16
+ if (!this.inputs) {
17
+ this.inputs = [];
18
+ }
19
+ const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"];
20
+ const num_inputs = this.inputs.filter(input => input.type === this._type).length
21
+ if(target_number_of_inputs===num_inputs)return; // already set, do nothing
22
+
23
+ if(target_number_of_inputs < num_inputs){
24
+ const inputs_to_remove = num_inputs - target_number_of_inputs;
25
+ for(let i = 0; i < inputs_to_remove; i++) {
26
+ this.removeInput(this.inputs.length - 1);
27
+ }
28
+ }
29
+ else{
30
+ for(let i = num_inputs+1; i <= target_number_of_inputs; ++i)
31
+ this.addInput(`conditioning_${i}`, this._type)
32
+ }
33
+ });
34
+ }
35
+ break;
36
+ case "ImageBatchMulti":
37
+ case "ImageAddMulti":
38
+ case "ImageConcatMulti":
39
+ case "CrossFadeImagesMulti":
40
+ case "TransitionImagesMulti":
41
+ nodeType.prototype.onNodeCreated = function () {
42
+ this._type = "IMAGE"
43
+ this.addWidget("button", "Update inputs", null, () => {
44
+ if (!this.inputs) {
45
+ this.inputs = [];
46
+ }
47
+ const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"];
48
+ const num_inputs = this.inputs.filter(input => input.type === this._type).length
49
+ if(target_number_of_inputs===num_inputs)return; // already set, do nothing
50
+
51
+ if(target_number_of_inputs < num_inputs){
52
+ const inputs_to_remove = num_inputs - target_number_of_inputs;
53
+ for(let i = 0; i < inputs_to_remove; i++) {
54
+ this.removeInput(this.inputs.length - 1);
55
+ }
56
+ }
57
+ else{
58
+ for(let i = num_inputs+1; i <= target_number_of_inputs; ++i)
59
+ this.addInput(`image_${i}`, this._type, {shape: 7});
60
+ }
61
+
62
+ });
63
+ }
64
+ break;
65
+ case "MaskBatchMulti":
66
+ nodeType.prototype.onNodeCreated = function () {
67
+ this._type = "MASK"
68
+ this.addWidget("button", "Update inputs", null, () => {
69
+ if (!this.inputs) {
70
+ this.inputs = [];
71
+ }
72
+ const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"];
73
+ const num_inputs = this.inputs.filter(input => input.type === this._type).length
74
+ if(target_number_of_inputs===num_inputs)return; // already set, do nothing
75
+
76
+ if(target_number_of_inputs < num_inputs){
77
+ const inputs_to_remove = num_inputs - target_number_of_inputs;
78
+ for(let i = 0; i < inputs_to_remove; i++) {
79
+ this.removeInput(this.inputs.length - 1);
80
+ }
81
+ }
82
+ else{
83
+ for(let i = num_inputs+1; i <= target_number_of_inputs; ++i)
84
+ this.addInput(`mask_${i}`, this._type)
85
+ }
86
+ });
87
+ }
88
+ break;
89
+
90
+ case "FluxBlockLoraSelect":
91
+ case "HunyuanVideoBlockLoraSelect":
92
+ case "Wan21BlockLoraSelect":
93
+ nodeType.prototype.onNodeCreated = function () {
94
+ this.addWidget("button", "Set all", null, () => {
95
+ const userInput = prompt("Enter the values to set for widgets (e.g., s0,1,2-7=2.0, d0,1,2-7=2.0, or 1.0):", "");
96
+ if (userInput) {
97
+ const regex = /([sd])?(\d+(?:,\d+|-?\d+)*?)?=(\d+(\.\d+)?)/;
98
+ const match = userInput.match(regex);
99
+ if (match) {
100
+ const type = match[1];
101
+ const indicesPart = match[2];
102
+ const value = parseFloat(match[3]);
103
+
104
+ let targetWidgets = [];
105
+ if (type === 's') {
106
+ targetWidgets = this.widgets.filter(widget => widget.name.includes("single"));
107
+ } else if (type === 'd') {
108
+ targetWidgets = this.widgets.filter(widget => widget.name.includes("double"));
109
+ } else {
110
+ targetWidgets = this.widgets; // No type specified, all widgets
111
+ }
112
+
113
+ if (indicesPart) {
114
+ const indices = indicesPart.split(',').flatMap(part => {
115
+ if (part.includes('-')) {
116
+ const [start, end] = part.split('-').map(Number);
117
+ return Array.from({ length: end - start + 1 }, (_, i) => start + i);
118
+ }
119
+ return Number(part);
120
+ });
121
+
122
+ for (const index of indices) {
123
+ if (index < targetWidgets.length) {
124
+ targetWidgets[index].value = value;
125
+ }
126
+ }
127
+ } else {
128
+ // No indices provided, set value for all target widgets
129
+ for (const widget of targetWidgets) {
130
+ widget.value = value;
131
+ }
132
+ }
133
+ } else if (!isNaN(parseFloat(userInput))) {
134
+ // Single value provided, set it for all widgets
135
+ const value = parseFloat(userInput);
136
+ for (const widget of this.widgets) {
137
+ widget.value = value;
138
+ }
139
+ } else {
140
+ alert("Invalid input format. Please use the format s0,1,2-7=2.0, d0,1,2-7=2.0, or 1.0");
141
+ }
142
+ } else {
143
+ alert("Invalid input. Please enter a value.");
144
+ }
145
+ });
146
+ };
147
+ break;
148
+
149
+ case "GetMaskSizeAndCount":
150
+ const onGetMaskSizeConnectInput = nodeType.prototype.onConnectInput;
151
+ nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) {
152
+ const v = onGetMaskSizeConnectInput? onGetMaskSizeConnectInput.apply(this, arguments): undefined
153
+ this.outputs[1]["label"] = "width"
154
+ this.outputs[2]["label"] = "height"
155
+ this.outputs[3]["label"] = "count"
156
+ return v;
157
+ }
158
+ const onGetMaskSizeExecuted = nodeType.prototype.onAfterExecuteNode;
159
+ nodeType.prototype.onExecuted = function(message) {
160
+ const r = onGetMaskSizeExecuted? onGetMaskSizeExecuted.apply(this,arguments): undefined
161
+ let values = message["text"].toString().split('x').map(Number);
162
+ this.outputs[1]["label"] = values[1] + " width"
163
+ this.outputs[2]["label"] = values[2] + " height"
164
+ this.outputs[3]["label"] = values[0] + " count"
165
+ return r
166
+ }
167
+ break;
168
+
169
+ case "GetImageSizeAndCount":
170
+ const onGetImageSizeConnectInput = nodeType.prototype.onConnectInput;
171
+ nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) {
172
+ console.log(this)
173
+ const v = onGetImageSizeConnectInput? onGetImageSizeConnectInput.apply(this, arguments): undefined
174
+ //console.log(this)
175
+ this.outputs[1]["label"] = "width"
176
+ this.outputs[2]["label"] = "height"
177
+ this.outputs[3]["label"] = "count"
178
+ return v;
179
+ }
180
+ //const onGetImageSizeExecuted = nodeType.prototype.onExecuted;
181
+ const onGetImageSizeExecuted = nodeType.prototype.onAfterExecuteNode;
182
+ nodeType.prototype.onExecuted = function(message) {
183
+ console.log(this)
184
+ const r = onGetImageSizeExecuted? onGetImageSizeExecuted.apply(this,arguments): undefined
185
+ let values = message["text"].toString().split('x').map(Number);
186
+ console.log(values)
187
+ this.outputs[1]["label"] = values[1] + " width"
188
+ this.outputs[2]["label"] = values[2] + " height"
189
+ this.outputs[3]["label"] = values[0] + " count"
190
+ return r
191
+ }
192
+ break;
193
+
194
+ case "GetLatentSizeAndCount":
195
+ const onGetLatentConnectInput = nodeType.prototype.onConnectInput;
196
+ nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) {
197
+ console.log(this)
198
+ const v = onGetLatentConnectInput? onGetLatentConnectInput.apply(this, arguments): undefined
199
+ //console.log(this)
200
+ this.outputs[1]["label"] = "width"
201
+ this.outputs[2]["label"] = "height"
202
+ this.outputs[3]["label"] = "count"
203
+ return v;
204
+ }
205
+ //const onGetImageSizeExecuted = nodeType.prototype.onExecuted;
206
+ const onGetLatentSizeExecuted = nodeType.prototype.onAfterExecuteNode;
207
+ nodeType.prototype.onExecuted = function(message) {
208
+ console.log(this)
209
+ const r = onGetLatentSizeExecuted? onGetLatentSizeExecuted.apply(this,arguments): undefined
210
+ let values = message["text"].toString().split('x').map(Number);
211
+ console.log(values)
212
+ this.outputs[1]["label"] = values[0] + " batch"
213
+ this.outputs[2]["label"] = values[1] + " channels"
214
+ this.outputs[3]["label"] = values[2] + " frames"
215
+ this.outputs[4]["label"] = values[3] + " height"
216
+ this.outputs[5]["label"] = values[4] + " width"
217
+ return r
218
+ }
219
+ break;
220
+
221
+ case "PreviewAnimation":
222
+ const onPreviewAnimationConnectInput = nodeType.prototype.onConnectInput;
223
+ nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) {
224
+ const v = onPreviewAnimationConnectInput? onPreviewAnimationConnectInput.apply(this, arguments): undefined
225
+ this.title = "Preview Animation"
226
+ return v;
227
+ }
228
+ const onPreviewAnimationExecuted = nodeType.prototype.onAfterExecuteNode;
229
+ nodeType.prototype.onExecuted = function(message) {
230
+ const r = onPreviewAnimationExecuted? onPreviewAnimationExecuted.apply(this,arguments): undefined
231
+ let values = message["text"].toString();
232
+ this.title = "Preview Animation " + values
233
+ return r
234
+ }
235
+ break;
236
+
237
+ case "VRAM_Debug":
238
+ const onVRAM_DebugConnectInput = nodeType.prototype.onConnectInput;
239
+ nodeType.prototype.onConnectInput = function (targetSlot, type, output, originNode, originSlot) {
240
+ const v = onVRAM_DebugConnectInput? onVRAM_DebugConnectInput.apply(this, arguments): undefined
241
+ this.outputs[3]["label"] = "freemem_before"
242
+ this.outputs[4]["label"] = "freemem_after"
243
+ return v;
244
+ }
245
+ const onVRAM_DebugExecuted = nodeType.prototype.onAfterExecuteNode;
246
+ nodeType.prototype.onExecuted = function(message) {
247
+ const r = onVRAM_DebugExecuted? onVRAM_DebugExecuted.apply(this,arguments): undefined
248
+ let values = message["text"].toString().split('x');
249
+ this.outputs[3]["label"] = values[0] + " freemem_before"
250
+ this.outputs[4]["label"] = values[1] + " freemem_after"
251
+ return r
252
+ }
253
+ break;
254
+
255
+ case "JoinStringMulti":
256
+ const originalOnNodeCreated = nodeType.prototype.onNodeCreated || function() {};
257
+ nodeType.prototype.onNodeCreated = function () {
258
+ originalOnNodeCreated.apply(this, arguments);
259
+
260
+ this._type = "STRING";
261
+ this.addWidget("button", "Update inputs", null, () => {
262
+ if (!this.inputs) {
263
+ this.inputs = [];
264
+ }
265
+ const target_number_of_inputs = this.widgets.find(w => w.name === "inputcount")["value"];
266
+ const num_inputs = this.inputs.filter(input => input.name && input.name.toLowerCase().includes("string_")).length
267
+ if (target_number_of_inputs === num_inputs) return; // already set, do nothing
268
+
269
+ if(target_number_of_inputs < num_inputs){
270
+ const inputs_to_remove = num_inputs - target_number_of_inputs;
271
+ for(let i = 0; i < inputs_to_remove; i++) {
272
+ this.removeInput(this.inputs.length - 1);
273
+ }
274
+ }
275
+ else{
276
+ for(let i = num_inputs+1; i <= target_number_of_inputs; ++i)
277
+ this.addInput(`string_${i}`, this._type, {shape: 7});
278
+ }
279
+ });
280
+ }
281
+ break;
282
+ case "SoundReactive":
283
+ nodeType.prototype.onNodeCreated = function () {
284
+ let audioContext;
285
+ let microphoneStream;
286
+ let animationFrameId;
287
+ let analyser;
288
+ let dataArray;
289
+ let startRangeHz;
290
+ let endRangeHz;
291
+ let smoothingFactor = 0.5;
292
+ let smoothedSoundLevel = 0;
293
+
294
+ // Function to update the widget value in real-time
295
+ const updateWidgetValueInRealTime = () => {
296
+ // Ensure analyser and dataArray are defined before using them
297
+ if (analyser && dataArray) {
298
+ analyser.getByteFrequencyData(dataArray);
299
+
300
+ const startRangeHzWidget = this.widgets.find(w => w.name === "start_range_hz");
301
+ if (startRangeHzWidget) startRangeHz = startRangeHzWidget.value;
302
+ const endRangeHzWidget = this.widgets.find(w => w.name === "end_range_hz");
303
+ if (endRangeHzWidget) endRangeHz = endRangeHzWidget.value;
304
+ const smoothingFactorWidget = this.widgets.find(w => w.name === "smoothing_factor");
305
+ if (smoothingFactorWidget) smoothingFactor = smoothingFactorWidget.value;
306
+
307
+ // Calculate frequency bin width (frequency resolution)
308
+ const frequencyBinWidth = audioContext.sampleRate / analyser.fftSize;
309
+ // Convert the widget values from Hz to indices
310
+ const startRangeIndex = Math.floor(startRangeHz / frequencyBinWidth);
311
+ const endRangeIndex = Math.floor(endRangeHz / frequencyBinWidth);
312
+
313
+ // Function to calculate the average value for a frequency range
314
+ const calculateAverage = (start, end) => {
315
+ const sum = dataArray.slice(start, end).reduce((acc, val) => acc + val, 0);
316
+ const average = sum / (end - start);
317
+
318
+ // Apply exponential moving average smoothing
319
+ smoothedSoundLevel = (average * (1 - smoothingFactor)) + (smoothedSoundLevel * smoothingFactor);
320
+ return smoothedSoundLevel;
321
+ };
322
+ // Calculate the average levels for each frequency range
323
+ const soundLevel = calculateAverage(startRangeIndex, endRangeIndex);
324
+
325
+ // Update the widget values
326
+
327
+ const lowLevelWidget = this.widgets.find(w => w.name === "sound_level");
328
+ if (lowLevelWidget) lowLevelWidget.value = soundLevel;
329
+
330
+ animationFrameId = requestAnimationFrame(updateWidgetValueInRealTime);
331
+ }
332
+ };
333
+
334
+ // Function to start capturing audio from the microphone
335
+ const startMicrophoneCapture = () => {
336
+ // Only create the audio context and analyser once
337
+ if (!audioContext) {
338
+ audioContext = new (window.AudioContext || window.webkitAudioContext)();
339
+ // Access the sample rate of the audio context
340
+ console.log(`Sample rate: ${audioContext.sampleRate}Hz`);
341
+ analyser = audioContext.createAnalyser();
342
+ analyser.fftSize = 2048;
343
+ dataArray = new Uint8Array(analyser.frequencyBinCount);
344
+ // Get the range values from widgets (assumed to be in Hz)
345
+ const lowRangeWidget = this.widgets.find(w => w.name === "low_range_hz");
346
+ if (lowRangeWidget) startRangeHz = lowRangeWidget.value;
347
+
348
+ const midRangeWidget = this.widgets.find(w => w.name === "mid_range_hz");
349
+ if (midRangeWidget) endRangeHz = midRangeWidget.value;
350
+ }
351
+
352
+ navigator.mediaDevices.getUserMedia({ audio: true }).then(stream => {
353
+ microphoneStream = stream;
354
+ const microphone = audioContext.createMediaStreamSource(stream);
355
+ microphone.connect(analyser);
356
+ updateWidgetValueInRealTime();
357
+ }).catch(error => {
358
+ console.error('Access to microphone was denied or an error occurred:', error);
359
+ });
360
+ };
361
+
362
+ // Function to stop capturing audio from the microphone
363
+ const stopMicrophoneCapture = () => {
364
+ if (animationFrameId) {
365
+ cancelAnimationFrame(animationFrameId);
366
+ }
367
+ if (microphoneStream) {
368
+ microphoneStream.getTracks().forEach(track => track.stop());
369
+ }
370
+ if (audioContext) {
371
+ audioContext.close();
372
+ // Reset audioContext to ensure it can be created again when starting
373
+ audioContext = null;
374
+ }
375
+ };
376
+
377
+ // Add start button
378
+ this.addWidget("button", "Start mic capture", null, startMicrophoneCapture);
379
+
380
+ // Add stop button
381
+ this.addWidget("button", "Stop mic capture", null, stopMicrophoneCapture);
382
+ };
383
+ break;
384
+ case "SaveImageKJ":
385
+ const onNodeCreated = nodeType.prototype.onNodeCreated;
386
+ nodeType.prototype.onNodeCreated = function() {
387
+ const r = onNodeCreated ? onNodeCreated.apply(this, arguments) : void 0;
388
+ const widget = this.widgets.find((w) => w.name === "filename_prefix");
389
+ widget.serializeValue = () => {
390
+ return applyTextReplacements(app, widget.value);
391
+ };
392
+ return r;
393
+ };
394
+ break;
395
+
396
+ }
397
+
398
+ },
399
+ async setup() {
400
+ // to keep Set/Get node virtual connections visible when offscreen
401
+ const originalComputeVisibleNodes = LGraphCanvas.prototype.computeVisibleNodes;
402
+ LGraphCanvas.prototype.computeVisibleNodes = function () {
403
+ const visibleNodesSet = new Set(originalComputeVisibleNodes.apply(this, arguments));
404
+ for (const node of this.graph._nodes) {
405
+ if ((node.type === "SetNode" || node.type === "GetNode") && node.drawConnection) {
406
+ visibleNodesSet.add(node);
407
+ }
408
+ }
409
+ return Array.from(visibleNodesSet);
410
+ };
411
+
412
+ }
413
+ });
web/js/point_editor.js ADDED
@@ -0,0 +1,734 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ this.previewMediaType = 'image'
116
+
117
+ this.pointsEditor = this.addDOMWidget(nodeData.name, "PointsEditorWidget", element, {
118
+ serialize: false,
119
+ hideOnZoom: false,
120
+ });
121
+
122
+ // context menu
123
+ this.contextMenu = document.createElement("div");
124
+ this.contextMenu.id = "context-menu";
125
+ this.contextMenu.style.display = "none";
126
+ this.contextMenu.style.position = "absolute";
127
+ this.contextMenu.style.backgroundColor = "#202020";
128
+ this.contextMenu.style.minWidth = "100px";
129
+ this.contextMenu.style.boxShadow = "0px 8px 16px 0px rgba(0,0,0,0.2)";
130
+ this.contextMenu.style.zIndex = "100";
131
+ this.contextMenu.style.padding = "5px";
132
+
133
+ function styleMenuItem(menuItem) {
134
+ menuItem.style.display = "block";
135
+ menuItem.style.padding = "5px";
136
+ menuItem.style.color = "#FFF";
137
+ menuItem.style.fontFamily = "Arial, sans-serif";
138
+ menuItem.style.fontSize = "16px";
139
+ menuItem.style.textDecoration = "none";
140
+ menuItem.style.marginBottom = "5px";
141
+ }
142
+ function createMenuItem(id, textContent) {
143
+ let menuItem = document.createElement("a");
144
+ menuItem.href = "#";
145
+ menuItem.id = `menu-item-${id}`;
146
+ menuItem.textContent = textContent;
147
+ styleMenuItem(menuItem);
148
+ return menuItem;
149
+ }
150
+
151
+ // Create an array of menu items using the createMenuItem function
152
+ this.menuItems = [
153
+ createMenuItem(0, "Load Image"),
154
+ createMenuItem(1, "Clear Image"),
155
+ ];
156
+
157
+ // Add mouseover and mouseout event listeners to each menu item for styling
158
+ this.menuItems.forEach(menuItem => {
159
+ menuItem.addEventListener('mouseover', function () {
160
+ this.style.backgroundColor = "gray";
161
+ });
162
+
163
+ menuItem.addEventListener('mouseout', function () {
164
+ this.style.backgroundColor = "#202020";
165
+ });
166
+ });
167
+
168
+ // Append each menu item to the context menu
169
+ this.menuItems.forEach(menuItem => {
170
+ this.contextMenu.appendChild(menuItem);
171
+ });
172
+
173
+ document.body.appendChild(this.contextMenu);
174
+
175
+ this.addWidget("button", "New canvas", null, () => {
176
+ if (!this.properties || !("points" in this.properties)) {
177
+ this.editor = new PointsEditor(this);
178
+ this.addProperty("points", this.constructor.type, "string");
179
+ this.addProperty("neg_points", this.constructor.type, "string");
180
+
181
+ }
182
+ else {
183
+ this.editor = new PointsEditor(this, true);
184
+ }
185
+ });
186
+
187
+ this.setSize([550, 550]);
188
+ this.resizable = false;
189
+ this.pointsEditor.parentEl = document.createElement("div");
190
+ this.pointsEditor.parentEl.className = "points-editor";
191
+ this.pointsEditor.parentEl.id = `points-editor-${this.uuid}`
192
+ element.appendChild(this.pointsEditor.parentEl);
193
+
194
+ chainCallback(this, "onConfigure", function () {
195
+ try {
196
+ this.editor = new PointsEditor(this);
197
+ } catch (error) {
198
+ console.error("An error occurred while configuring the editor:", error);
199
+ }
200
+ });
201
+ chainCallback(this, "onExecuted", function (message) {
202
+ let bg_image = message["bg_image"];
203
+ this.properties.imgData = {
204
+ name: "bg_image",
205
+ base64: bg_image
206
+ };
207
+ this.editor.refreshBackgroundImage(this);
208
+ });
209
+
210
+ }); // onAfterGraphConfigured
211
+ }//node created
212
+ } //before register
213
+ })//register
214
+
215
+ class PointsEditor {
216
+ constructor(context, reset = false) {
217
+ this.node = context;
218
+ this.reset = reset;
219
+ const self = this; // Keep a reference to the main class context
220
+
221
+ console.log("creatingPointEditor")
222
+
223
+ this.node.pasteFile = (file) => {
224
+ if (file.type.startsWith("image/")) {
225
+ this.handleImageFile(file);
226
+ return true;
227
+ }
228
+ return false;
229
+ };
230
+
231
+ this.node.onDragOver = function (e) {
232
+ if (e.dataTransfer && e.dataTransfer.items) {
233
+ return [...e.dataTransfer.items].some(f => f.kind === "file" && f.type.startsWith("image/"));
234
+ }
235
+ return false;
236
+ };
237
+
238
+ // On drop upload files
239
+ this.node.onDragDrop = (e) => {
240
+ console.log("onDragDrop called");
241
+ let handled = false;
242
+ for (const file of e.dataTransfer.files) {
243
+ if (file.type.startsWith("image/")) {
244
+ this.handleImageFile(file);
245
+ handled = true;
246
+ }
247
+ }
248
+ return handled;
249
+ };
250
+
251
+ // context menu
252
+ this.createContextMenu();
253
+
254
+ if (reset && context.pointsEditor.element) {
255
+ context.pointsEditor.element.innerHTML = ''; // Clear the container
256
+ }
257
+ this.pos_coordWidget = context.widgets.find(w => w.name === "coordinates");
258
+ this.neg_coordWidget = context.widgets.find(w => w.name === "neg_coordinates");
259
+ this.pointsStoreWidget = context.widgets.find(w => w.name === "points_store");
260
+ this.widthWidget = context.widgets.find(w => w.name === "width");
261
+ this.heightWidget = context.widgets.find(w => w.name === "height");
262
+ this.bboxStoreWidget = context.widgets.find(w => w.name === "bbox_store");
263
+ this.bboxWidget = context.widgets.find(w => w.name === "bboxes");
264
+
265
+ //widget callbacks
266
+ this.widthWidget.callback = () => {
267
+ this.width = this.widthWidget.value;
268
+ if (this.width > 256) {
269
+ context.setSize([this.width + 45, context.size[1]]);
270
+ }
271
+ this.vis.width(this.width);
272
+ this.updateData();
273
+ }
274
+ this.heightWidget.callback = () => {
275
+ this.height = this.heightWidget.value
276
+ this.vis.height(this.height)
277
+ context.setSize([context.size[0], this.height + 300]);
278
+ this.updateData();
279
+ }
280
+ this.pointsStoreWidget.callback = () => {
281
+ this.points = JSON.parse(pointsStoreWidget.value).positive;
282
+ this.neg_points = JSON.parse(pointsStoreWidget.value).negative;
283
+ this.updateData();
284
+ }
285
+ this.bboxStoreWidget.callback = () => {
286
+ this.bbox = JSON.parse(bboxStoreWidget.value)
287
+ this.updateData();
288
+ }
289
+
290
+ this.width = this.widthWidget.value;
291
+ this.height = this.heightWidget.value;
292
+ var i = 3;
293
+ this.points = [];
294
+ this.neg_points = [];
295
+ this.bbox = [{}];
296
+ var drawing = false;
297
+
298
+ // Initialize or reset points array
299
+ if (!reset && this.pointsStoreWidget.value != "") {
300
+ this.points = JSON.parse(this.pointsStoreWidget.value).positive;
301
+ this.neg_points = JSON.parse(this.pointsStoreWidget.value).negative;
302
+ this.bbox = JSON.parse(this.bboxStoreWidget.value);
303
+ console.log(this.bbox)
304
+ } else {
305
+ this.points = [
306
+ {
307
+ x: this.width / 2, // Middle point horizontally centered
308
+ y: this.height / 2 // Middle point vertically centered
309
+ }
310
+ ];
311
+ this.neg_points = [
312
+ {
313
+ x: 0, // Middle point horizontally centered
314
+ y: 0 // Middle point vertically centered
315
+ }
316
+ ];
317
+ const combinedPoints = {
318
+ positive: this.points,
319
+ negative: this.neg_points,
320
+ };
321
+ this.pointsStoreWidget.value = JSON.stringify(combinedPoints);
322
+ this.bboxStoreWidget.value = JSON.stringify(this.bbox);
323
+ }
324
+
325
+ //create main canvas panel
326
+ this.vis = new pv.Panel()
327
+ .width(this.width)
328
+ .height(this.height)
329
+ .fillStyle("#222")
330
+ .strokeStyle("gray")
331
+ .lineWidth(2)
332
+ .antialias(false)
333
+ .margin(10)
334
+ .event("mousedown", function () {
335
+ if (pv.event.shiftKey && pv.event.button === 2) { // Use pv.event to access the event object
336
+ let scaledMouse = {
337
+ x: this.mouse().x / app.canvas.ds.scale,
338
+ y: this.mouse().y / app.canvas.ds.scale
339
+ };
340
+ i = self.neg_points.push(scaledMouse) - 1;
341
+ self.updateData();
342
+ return this;
343
+ }
344
+ else if (pv.event.shiftKey) {
345
+ let scaledMouse = {
346
+ x: this.mouse().x / app.canvas.ds.scale,
347
+ y: this.mouse().y / app.canvas.ds.scale
348
+ };
349
+ i = self.points.push(scaledMouse) - 1;
350
+ self.updateData();
351
+ return this;
352
+ }
353
+ else if (pv.event.ctrlKey) {
354
+ console.log("start drawing at " + this.mouse().x / app.canvas.ds.scale + ", " + this.mouse().y / app.canvas.ds.scale);
355
+ drawing = true;
356
+ self.bbox[0].startX = this.mouse().x / app.canvas.ds.scale;
357
+ self.bbox[0].startY = this.mouse().y / app.canvas.ds.scale;
358
+ }
359
+ else if (pv.event.button === 2) {
360
+ self.node.contextMenu.style.display = 'block';
361
+ self.node.contextMenu.style.left = `${pv.event.clientX}px`;
362
+ self.node.contextMenu.style.top = `${pv.event.clientY}px`;
363
+ }
364
+ })
365
+ .event("mousemove", function () {
366
+ if (drawing) {
367
+ self.bbox[0].endX = this.mouse().x / app.canvas.ds.scale;
368
+ self.bbox[0].endY = this.mouse().y / app.canvas.ds.scale;
369
+ self.vis.render();
370
+ }
371
+ })
372
+ .event("mouseup", function () {
373
+ console.log("end drawing at " + this.mouse().x / app.canvas.ds.scale + ", " + this.mouse().y / app.canvas.ds.scale);
374
+ drawing = false;
375
+ self.updateData();
376
+ });
377
+
378
+ this.backgroundImage = this.vis.add(pv.Image).visible(false)
379
+
380
+ //create bounding box
381
+ this.bounding_box = this.vis.add(pv.Area)
382
+ .data(function () {
383
+ if (drawing || (self.bbox && self.bbox[0] && Object.keys(self.bbox[0]).length > 0)) {
384
+ return [self.bbox[0].startX, self.bbox[0].endX];
385
+ } else {
386
+ return [];
387
+ }
388
+ })
389
+ .bottom(function () {return self.height - Math.max(self.bbox[0].startY, self.bbox[0].endY); })
390
+ .left(function (d) {return d; })
391
+ .height(function () {return Math.abs(self.bbox[0].startY - self.bbox[0].endY);})
392
+ .fillStyle("rgba(70, 130, 180, 0.5)")
393
+ .strokeStyle("steelblue")
394
+ .visible(function () {return drawing || Object.keys(self.bbox[0]).length > 0; })
395
+ .add(pv.Dot)
396
+ .visible(function () {return drawing || Object.keys(self.bbox[0]).length > 0; })
397
+ .data(() => {
398
+ if (self.bbox && Object.keys(self.bbox[0]).length > 0) {
399
+ return [{
400
+ x: self.bbox[0].endX,
401
+ y: self.bbox[0].endY
402
+ }];
403
+ } else {
404
+ return [];
405
+ }
406
+ })
407
+ .left(d => d.x)
408
+ .top(d => d.y)
409
+ .radius(Math.log(Math.min(self.width, self.height)) * 1)
410
+ .shape("square")
411
+ .cursor("move")
412
+ .strokeStyle("steelblue")
413
+ .lineWidth(2)
414
+ .fillStyle(function () { return "rgba(100, 100, 100, 0.6)"; })
415
+ .event("mousedown", pv.Behavior.drag())
416
+ .event("drag", function () {
417
+ let adjustedX = this.mouse().x / app.canvas.ds.scale; // Adjust the new position by the inverse of the scale factor
418
+ let adjustedY = this.mouse().y / app.canvas.ds.scale;
419
+
420
+ // Adjust the new position if it would place the dot outside the bounds of the vis.Panel
421
+ adjustedX = Math.max(0, Math.min(self.vis.width(), adjustedX));
422
+ adjustedY = Math.max(0, Math.min(self.vis.height(), adjustedY));
423
+ self.bbox[0].endX = this.mouse().x / app.canvas.ds.scale;
424
+ self.bbox[0].endY = this.mouse().y / app.canvas.ds.scale;
425
+ self.vis.render();
426
+ })
427
+ .event("dragend", function () {
428
+ self.updateData();
429
+ });
430
+
431
+ //create positive points
432
+ this.vis.add(pv.Dot)
433
+ .data(() => this.points)
434
+ .left(d => d.x)
435
+ .top(d => d.y)
436
+ .radius(Math.log(Math.min(self.width, self.height)) * 4)
437
+ .shape("circle")
438
+ .cursor("move")
439
+ .strokeStyle(function () { return i == this.index ? "#07f907" : "#139613"; })
440
+ .lineWidth(4)
441
+ .fillStyle(function () { return "rgba(100, 100, 100, 0.6)"; })
442
+ .event("mousedown", pv.Behavior.drag())
443
+ .event("dragstart", function () {
444
+ i = this.index;
445
+ })
446
+ .event("dragend", function () {
447
+ if (pv.event.button === 2 && i !== 0 && i !== self.points.length - 1) {
448
+ this.index = i;
449
+ self.points.splice(i--, 1);
450
+ }
451
+ self.updateData();
452
+
453
+ })
454
+ .event("drag", function () {
455
+ let adjustedX = this.mouse().x / app.canvas.ds.scale; // Adjust the new X position by the inverse of the scale factor
456
+ let adjustedY = this.mouse().y / app.canvas.ds.scale; // Adjust the new Y position by the inverse of the scale factor
457
+ // Determine the bounds of the vis.Panel
458
+ const panelWidth = self.vis.width();
459
+ const panelHeight = self.vis.height();
460
+
461
+ // Adjust the new position if it would place the dot outside the bounds of the vis.Panel
462
+ adjustedX = Math.max(0, Math.min(panelWidth, adjustedX));
463
+ adjustedY = Math.max(0, Math.min(panelHeight, adjustedY));
464
+ self.points[this.index] = { x: adjustedX, y: adjustedY }; // Update the point's position
465
+ self.vis.render(); // Re-render the visualization to reflect the new position
466
+ })
467
+
468
+ .anchor("center")
469
+ .add(pv.Label)
470
+ .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
471
+ .top(d => d.y < this.height / 2 ? d.y + 25 : d.y - 25) // Shift label down if on top half, otherwise shift up
472
+ .font(25 + "px sans-serif")
473
+ .text(d => {return this.points.indexOf(d); })
474
+ .textStyle("#139613")
475
+ .textShadow("2px 2px 2px black")
476
+ .add(pv.Dot) // Add smaller point in the center
477
+ .data(() => this.points)
478
+ .left(d => d.x)
479
+ .top(d => d.y)
480
+ .radius(2) // Smaller radius for the center point
481
+ .shape("circle")
482
+ .fillStyle("red") // Color for the center point
483
+ .lineWidth(1); // Stroke thickness for the center point
484
+
485
+ //create negative points
486
+ this.vis.add(pv.Dot)
487
+ .data(() => this.neg_points)
488
+ .left(d => d.x)
489
+ .top(d => d.y)
490
+ .radius(Math.log(Math.min(self.width, self.height)) * 4)
491
+ .shape("circle")
492
+ .cursor("move")
493
+ .strokeStyle(function () { return i == this.index ? "#f91111" : "#891616"; })
494
+ .lineWidth(4)
495
+ .fillStyle(function () { return "rgba(100, 100, 100, 0.6)"; })
496
+ .event("mousedown", pv.Behavior.drag())
497
+ .event("dragstart", function () {
498
+ i = this.index;
499
+ })
500
+ .event("dragend", function () {
501
+ if (pv.event.button === 2 && i !== 0 && i !== self.neg_points.length - 1) {
502
+ this.index = i;
503
+ self.neg_points.splice(i--, 1);
504
+ }
505
+ self.updateData();
506
+
507
+ })
508
+ .event("drag", function () {
509
+ let adjustedX = this.mouse().x / app.canvas.ds.scale; // Adjust the new X position by the inverse of the scale factor
510
+ let adjustedY = this.mouse().y / app.canvas.ds.scale; // Adjust the new Y position by the inverse of the scale factor
511
+ // Determine the bounds of the vis.Panel
512
+ const panelWidth = self.vis.width();
513
+ const panelHeight = self.vis.height();
514
+
515
+ // Adjust the new position if it would place the dot outside the bounds of the vis.Panel
516
+ adjustedX = Math.max(0, Math.min(panelWidth, adjustedX));
517
+ adjustedY = Math.max(0, Math.min(panelHeight, adjustedY));
518
+ self.neg_points[this.index] = { x: adjustedX, y: adjustedY }; // Update the point's position
519
+ self.vis.render(); // Re-render the visualization to reflect the new position
520
+ })
521
+ .anchor("center")
522
+ .add(pv.Label)
523
+ .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
524
+ .top(d => d.y < this.height / 2 ? d.y + 25 : d.y - 25) // Shift label down if on top half, otherwise shift up
525
+ .font(25 + "px sans-serif")
526
+ .text(d => {return this.neg_points.indexOf(d); })
527
+ .textStyle("red")
528
+ .textShadow("2px 2px 2px black")
529
+ .add(pv.Dot) // Add smaller point in the center
530
+ .data(() => this.neg_points)
531
+ .left(d => d.x)
532
+ .top(d => d.y)
533
+ .radius(2) // Smaller radius for the center point
534
+ .shape("circle")
535
+ .fillStyle("red") // Color for the center point
536
+ .lineWidth(1); // Stroke thickness for the center point
537
+
538
+ if (this.points.length != 0) {
539
+ this.vis.render();
540
+ }
541
+
542
+ var svgElement = this.vis.canvas();
543
+ svgElement.style['zIndex'] = "2"
544
+ svgElement.style['position'] = "relative"
545
+ this.node.pointsEditor.element.appendChild(svgElement);
546
+
547
+ if (this.width > 256) {
548
+ this.node.setSize([this.width + 45, this.node.size[1]]);
549
+ }
550
+ this.node.setSize([this.node.size[0], this.height + 300]);
551
+ this.updateData();
552
+ this.refreshBackgroundImage();
553
+
554
+ }//end constructor
555
+
556
+ updateData = () => {
557
+ if (!this.points || this.points.length === 0) {
558
+ console.log("no points");
559
+ return;
560
+ }
561
+ const combinedPoints = {
562
+ positive: this.points,
563
+ negative: this.neg_points,
564
+ };
565
+ this.pointsStoreWidget.value = JSON.stringify(combinedPoints);
566
+ this.pos_coordWidget.value = JSON.stringify(this.points);
567
+ this.neg_coordWidget.value = JSON.stringify(this.neg_points);
568
+
569
+ if (this.bbox.length != 0) {
570
+ let bboxString = JSON.stringify(this.bbox);
571
+ this.bboxStoreWidget.value = bboxString;
572
+ this.bboxWidget.value = bboxString;
573
+ }
574
+
575
+ this.vis.render();
576
+ };
577
+
578
+ handleImageLoad = (img, file, base64String) => {
579
+ console.log(img.width, img.height); // Access width and height here
580
+ this.widthWidget.value = img.width;
581
+ this.heightWidget.value = img.height;
582
+
583
+ if (img.width != this.vis.width() || img.height != this.vis.height()) {
584
+ if (img.width > 256) {
585
+ this.node.setSize([img.width + 45, this.node.size[1]]);
586
+ }
587
+ this.node.setSize([this.node.size[0], img.height + 300]);
588
+ this.vis.width(img.width);
589
+ this.vis.height(img.height);
590
+ this.height = img.height;
591
+ this.width = img.width;
592
+ this.updateData();
593
+ }
594
+ this.backgroundImage.url(file ? URL.createObjectURL(file) : `data:${this.node.properties.imgData.type};base64,${base64String}`).visible(true).root.render();
595
+ };
596
+
597
+ processImage = (img, file) => {
598
+ const canvas = document.createElement('canvas');
599
+ const ctx = canvas.getContext('2d');
600
+
601
+ const maxWidth = 800; // maximum width
602
+ const maxHeight = 600; // maximum height
603
+ let width = img.width;
604
+ let height = img.height;
605
+
606
+ // Calculate the new dimensions while preserving the aspect ratio
607
+ if (width > height) {
608
+ if (width > maxWidth) {
609
+ height *= maxWidth / width;
610
+ width = maxWidth;
611
+ }
612
+ } else {
613
+ if (height > maxHeight) {
614
+ width *= maxHeight / height;
615
+ height = maxHeight;
616
+ }
617
+ }
618
+
619
+ canvas.width = width;
620
+ canvas.height = height;
621
+ ctx.drawImage(img, 0, 0, width, height);
622
+
623
+ // Get the compressed image data as a Base64 string
624
+ const base64String = canvas.toDataURL('image/jpeg', 0.5).replace('data:', '').replace(/^.+,/, ''); // 0.5 is the quality from 0 to 1
625
+
626
+ this.node.properties.imgData = {
627
+ name: file.name,
628
+ lastModified: file.lastModified,
629
+ size: file.size,
630
+ type: file.type,
631
+ base64: base64String
632
+ };
633
+ handleImageLoad(img, file, base64String);
634
+ };
635
+
636
+ handleImageFile = (file) => {
637
+ const reader = new FileReader();
638
+ reader.onloadend = () => {
639
+ const img = new Image();
640
+ img.src = reader.result;
641
+ img.onload = () => processImage(img, file);
642
+ };
643
+ reader.readAsDataURL(file);
644
+
645
+ const imageUrl = URL.createObjectURL(file);
646
+ const img = new Image();
647
+ img.src = imageUrl;
648
+ img.onload = () => this.handleImageLoad(img, file, null);
649
+ };
650
+
651
+ refreshBackgroundImage = () => {
652
+ if (this.node.properties.imgData && this.node.properties.imgData.base64) {
653
+ const base64String = this.node.properties.imgData.base64;
654
+ const imageUrl = `data:${this.node.properties.imgData.type};base64,${base64String}`;
655
+ const img = new Image();
656
+ img.src = imageUrl;
657
+ img.onload = () => this.handleImageLoad(img, null, base64String);
658
+ }
659
+ };
660
+
661
+ createContextMenu = () => {
662
+ self = this;
663
+ document.addEventListener('contextmenu', function (e) {
664
+ e.preventDefault();
665
+ });
666
+
667
+ document.addEventListener('click', function (e) {
668
+ if (!self.node.contextMenu.contains(e.target)) {
669
+ self.node.contextMenu.style.display = 'none';
670
+ }
671
+ });
672
+
673
+ this.node.menuItems.forEach((menuItem, index) => {
674
+ self = this;
675
+ menuItem.addEventListener('click', function (e) {
676
+ e.preventDefault();
677
+ switch (index) {
678
+ case 0:
679
+ // Create file input element
680
+ const fileInput = document.createElement('input');
681
+ fileInput.type = 'file';
682
+ fileInput.accept = 'image/*'; // Accept only image files
683
+
684
+ // Listen for file selection
685
+ fileInput.addEventListener('change', function (event) {
686
+ const file = event.target.files[0]; // Get the selected file
687
+
688
+ if (file) {
689
+ const imageUrl = URL.createObjectURL(file);
690
+ let img = new Image();
691
+ img.src = imageUrl;
692
+ img.onload = () => self.handleImageLoad(img, file, null);
693
+ }
694
+ });
695
+
696
+ fileInput.click();
697
+
698
+ self.node.contextMenu.style.display = 'none';
699
+ break;
700
+ case 1:
701
+ self.backgroundImage.visible(false).root.render();
702
+ self.node.properties.imgData = null;
703
+ self.node.contextMenu.style.display = 'none';
704
+ break;
705
+ }
706
+ });
707
+ });
708
+ }//end createContextMenu
709
+ }//end class
710
+
711
+
712
+ //from melmass
713
+ export function hideWidgetForGood(node, widget, suffix = '') {
714
+ widget.origType = widget.type
715
+ widget.origComputeSize = widget.computeSize
716
+ widget.origSerializeValue = widget.serializeValue
717
+ widget.computeSize = () => [0, -4] // -4 is due to the gap litegraph adds between widgets automatically
718
+ widget.type = "converted-widget" + suffix
719
+ // widget.serializeValue = () => {
720
+ // // Prevent serializing the widget if we have no input linked
721
+ // const w = node.inputs?.find((i) => i.widget?.name === widget.name);
722
+ // if (w?.link == null) {
723
+ // return undefined;
724
+ // }
725
+ // return widget.origSerializeValue ? widget.origSerializeValue() : widget.value;
726
+ // };
727
+
728
+ // Hide any linked widgets, e.g. seed+seedControl
729
+ if (widget.linkedWidgets) {
730
+ for (const w of widget.linkedWidgets) {
731
+ hideWidgetForGood(node, w, ':' + widget.name)
732
+ }
733
+ }
734
+ }
web/js/setgetnodes.js ADDED
@@ -0,0 +1,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { app } from "../../../scripts/app.js";
2
+
3
+ //based on diffus3's SetGet: https://github.com/diffus3/ComfyUI-extensions
4
+
5
+ // Nodes that allow you to tunnel connections for cleaner graphs
6
+ function setColorAndBgColor(type) {
7
+ const colorMap = {
8
+ "MODEL": LGraphCanvas.node_colors.blue,
9
+ "LATENT": LGraphCanvas.node_colors.purple,
10
+ "VAE": LGraphCanvas.node_colors.red,
11
+ "CONDITIONING": LGraphCanvas.node_colors.brown,
12
+ "IMAGE": LGraphCanvas.node_colors.pale_blue,
13
+ "CLIP": LGraphCanvas.node_colors.yellow,
14
+ "FLOAT": LGraphCanvas.node_colors.green,
15
+ "MASK": { color: "#1c5715", bgcolor: "#1f401b"},
16
+ "INT": { color: "#1b4669", bgcolor: "#29699c"},
17
+ "CONTROL_NET": { color: "#156653", bgcolor: "#1c453b"},
18
+ "NOISE": { color: "#2e2e2e", bgcolor: "#242121"},
19
+ "GUIDER": { color: "#3c7878", bgcolor: "#1c453b"},
20
+ "SAMPLER": { color: "#614a4a", bgcolor: "#3b2c2c"},
21
+ "SIGMAS": { color: "#485248", bgcolor: "#272e27"},
22
+
23
+ };
24
+
25
+ const colors = colorMap[type];
26
+ if (colors) {
27
+ this.color = colors.color;
28
+ this.bgcolor = colors.bgcolor;
29
+ }
30
+ }
31
+ let disablePrefix = app.ui.settings.getSettingValue("KJNodes.disablePrefix")
32
+ const LGraphNode = LiteGraph.LGraphNode
33
+
34
+ function showAlert(message) {
35
+ app.extensionManager.toast.add({
36
+ severity: 'warn',
37
+ summary: "KJ Get/Set",
38
+ detail: `${message}. Most likely you're missing custom nodes`,
39
+ life: 5000,
40
+ })
41
+ }
42
+ app.registerExtension({
43
+ name: "SetNode",
44
+ registerCustomNodes() {
45
+ class SetNode extends LGraphNode {
46
+ defaultVisibility = true;
47
+ serialize_widgets = true;
48
+ drawConnection = false;
49
+ currentGetters = null;
50
+ slotColor = "#FFF";
51
+ canvas = app.canvas;
52
+ menuEntry = "Show connections";
53
+
54
+ constructor(title) {
55
+ super(title)
56
+ if (!this.properties) {
57
+ this.properties = {
58
+ "previousName": ""
59
+ };
60
+ }
61
+ this.properties.showOutputText = SetNode.defaultVisibility;
62
+
63
+ const node = this;
64
+
65
+ this.addWidget(
66
+ "text",
67
+ "Constant",
68
+ '',
69
+ (s, t, u, v, x) => {
70
+ node.validateName(node.graph);
71
+ if(this.widgets[0].value !== ''){
72
+ this.title = (!disablePrefix ? "Set_" : "") + this.widgets[0].value;
73
+ }
74
+ this.update();
75
+ this.properties.previousName = this.widgets[0].value;
76
+ },
77
+ {}
78
+ )
79
+
80
+ this.addInput("*", "*");
81
+ this.addOutput("*", '*');
82
+
83
+ this.onConnectionsChange = function(
84
+ slotType, //1 = input, 2 = output
85
+ slot,
86
+ isChangeConnect,
87
+ link_info,
88
+ output
89
+ ) {
90
+ //On Disconnect
91
+ if (slotType == 1 && !isChangeConnect) {
92
+ if(this.inputs[slot].name === ''){
93
+ this.inputs[slot].type = '*';
94
+ this.inputs[slot].name = '*';
95
+ this.title = "Set"
96
+ }
97
+ }
98
+ if (slotType == 2 && !isChangeConnect) {
99
+ if (this.outputs && this.outputs[slot]) {
100
+ this.outputs[slot].type = '*';
101
+ this.outputs[slot].name = '*';
102
+ }
103
+ }
104
+ //On Connect
105
+ if (link_info && node.graph && slotType == 1 && isChangeConnect) {
106
+ const fromNode = node.graph._nodes.find((otherNode) => otherNode.id == link_info.origin_id);
107
+
108
+ if (fromNode && fromNode.outputs && fromNode.outputs[link_info.origin_slot]) {
109
+ const type = fromNode.outputs[link_info.origin_slot].type;
110
+
111
+ if (this.title === "Set"){
112
+ this.title = (!disablePrefix ? "Set_" : "") + type;
113
+ }
114
+ if (this.widgets[0].value === '*'){
115
+ this.widgets[0].value = type
116
+ }
117
+
118
+ this.validateName(node.graph);
119
+ this.inputs[0].type = type;
120
+ this.inputs[0].name = type;
121
+
122
+ if (app.ui.settings.getSettingValue("KJNodes.nodeAutoColor")){
123
+ setColorAndBgColor.call(this, type);
124
+ }
125
+ } else {
126
+ showAlert("node input undefined.")
127
+ }
128
+ }
129
+ if (link_info && node.graph && slotType == 2 && isChangeConnect) {
130
+ const fromNode = node.graph._nodes.find((otherNode) => otherNode.id == link_info.origin_id);
131
+
132
+ if (fromNode && fromNode.inputs && fromNode.inputs[link_info.origin_slot]) {
133
+ const type = fromNode.inputs[link_info.origin_slot].type;
134
+
135
+ this.outputs[0].type = type;
136
+ this.outputs[0].name = type;
137
+ } else {
138
+ showAlert('node output undefined');
139
+ }
140
+ }
141
+
142
+
143
+ //Update either way
144
+ this.update();
145
+ }
146
+
147
+ this.validateName = function(graph) {
148
+ let widgetValue = node.widgets[0].value;
149
+
150
+ if (widgetValue !== '') {
151
+ let tries = 0;
152
+ const existingValues = new Set();
153
+
154
+ graph._nodes.forEach(otherNode => {
155
+ if (otherNode !== this && otherNode.type === 'SetNode') {
156
+ existingValues.add(otherNode.widgets[0].value);
157
+ }
158
+ });
159
+
160
+ while (existingValues.has(widgetValue)) {
161
+ widgetValue = node.widgets[0].value + "_" + tries;
162
+ tries++;
163
+ }
164
+
165
+ node.widgets[0].value = widgetValue;
166
+ this.update();
167
+ }
168
+ }
169
+
170
+ this.clone = function () {
171
+ const cloned = SetNode.prototype.clone.apply(this);
172
+ cloned.inputs[0].name = '*';
173
+ cloned.inputs[0].type = '*';
174
+ cloned.value = '';
175
+ cloned.properties.previousName = '';
176
+ cloned.size = cloned.computeSize();
177
+ return cloned;
178
+ };
179
+
180
+ this.onAdded = function(graph) {
181
+ this.validateName(graph);
182
+ }
183
+
184
+
185
+ this.update = function() {
186
+ if (!node.graph) {
187
+ return;
188
+ }
189
+
190
+ const getters = this.findGetters(node.graph);
191
+ getters.forEach(getter => {
192
+ getter.setType(this.inputs[0].type);
193
+ });
194
+
195
+ if (this.widgets[0].value) {
196
+ const gettersWithPreviousName = this.findGetters(node.graph, true);
197
+ gettersWithPreviousName.forEach(getter => {
198
+ getter.setName(this.widgets[0].value);
199
+ });
200
+ }
201
+
202
+ const allGetters = node.graph._nodes.filter(otherNode => otherNode.type === "GetNode");
203
+ allGetters.forEach(otherNode => {
204
+ if (otherNode.setComboValues) {
205
+ otherNode.setComboValues();
206
+ }
207
+ });
208
+ }
209
+
210
+
211
+ this.findGetters = function(graph, checkForPreviousName) {
212
+ const name = checkForPreviousName ? this.properties.previousName : this.widgets[0].value;
213
+ return graph._nodes.filter(otherNode => otherNode.type === 'GetNode' && otherNode.widgets[0].value === name && name !== '');
214
+ }
215
+
216
+
217
+ // This node is purely frontend and does not impact the resulting prompt so should not be serialized
218
+ this.isVirtualNode = true;
219
+ }
220
+
221
+
222
+ onRemoved() {
223
+ const allGetters = this.graph._nodes.filter((otherNode) => otherNode.type == "GetNode");
224
+ allGetters.forEach((otherNode) => {
225
+ if (otherNode.setComboValues) {
226
+ otherNode.setComboValues([this]);
227
+ }
228
+ })
229
+ }
230
+ getExtraMenuOptions(_, options) {
231
+ this.menuEntry = this.drawConnection ? "Hide connections" : "Show connections";
232
+ options.unshift(
233
+ {
234
+ content: this.menuEntry,
235
+ callback: () => {
236
+ this.currentGetters = this.findGetters(this.graph);
237
+ if (this.currentGetters.length == 0) return;
238
+ let linkType = (this.currentGetters[0].outputs[0].type);
239
+ this.slotColor = this.canvas.default_connection_color_byType[linkType]
240
+ this.menuEntry = this.drawConnection ? "Hide connections" : "Show connections";
241
+ this.drawConnection = !this.drawConnection;
242
+ this.canvas.setDirty(true, true);
243
+
244
+ },
245
+ has_submenu: true,
246
+ submenu: {
247
+ title: "Color",
248
+ options: [
249
+ {
250
+ content: "Highlight",
251
+ callback: () => {
252
+ this.slotColor = "orange"
253
+ this.canvas.setDirty(true, true);
254
+ }
255
+ }
256
+ ],
257
+ },
258
+ },
259
+ {
260
+ content: "Hide all connections",
261
+ callback: () => {
262
+ const allGetters = this.graph._nodes.filter(otherNode => otherNode.type === "GetNode" || otherNode.type === "SetNode");
263
+ allGetters.forEach(otherNode => {
264
+ otherNode.drawConnection = false;
265
+ console.log(otherNode);
266
+ });
267
+
268
+ this.menuEntry = "Show connections";
269
+ this.drawConnection = false
270
+ this.canvas.setDirty(true, true);
271
+
272
+ },
273
+
274
+ },
275
+ );
276
+ // Dynamically add a submenu for all getters
277
+ this.currentGetters = this.findGetters(this.graph);
278
+ if (this.currentGetters) {
279
+
280
+ let gettersSubmenu = this.currentGetters.map(getter => ({
281
+
282
+ content: `${getter.title} id: ${getter.id}`,
283
+ callback: () => {
284
+ this.canvas.centerOnNode(getter);
285
+ this.canvas.selectNode(getter, false);
286
+ this.canvas.setDirty(true, true);
287
+
288
+ },
289
+ }));
290
+
291
+ options.unshift({
292
+ content: "Getters",
293
+ has_submenu: true,
294
+ submenu: {
295
+ title: "GetNodes",
296
+ options: gettersSubmenu,
297
+ }
298
+ });
299
+ }
300
+ }
301
+
302
+
303
+ onDrawForeground(ctx, lGraphCanvas) {
304
+ if (this.drawConnection) {
305
+ this._drawVirtualLinks(lGraphCanvas, ctx);
306
+ }
307
+ }
308
+ // onDrawCollapsed(ctx, lGraphCanvas) {
309
+ // if (this.drawConnection) {
310
+ // this._drawVirtualLinks(lGraphCanvas, ctx);
311
+ // }
312
+ // }
313
+ _drawVirtualLinks(lGraphCanvas, ctx) {
314
+ if (!this.currentGetters?.length) return;
315
+ var title = this.getTitle ? this.getTitle() : this.title;
316
+ var title_width = ctx.measureText(title).width;
317
+ if (!this.flags.collapsed) {
318
+ var start_node_slotpos = [
319
+ this.size[0],
320
+ LiteGraph.NODE_TITLE_HEIGHT * 0.5,
321
+ ];
322
+ }
323
+ else {
324
+
325
+ var start_node_slotpos = [
326
+ title_width + 55,
327
+ -15,
328
+
329
+ ];
330
+ }
331
+ // Provide a default link object with necessary properties, to avoid errors as link can't be null anymore
332
+ const defaultLink = { type: 'default', color: this.slotColor };
333
+
334
+ for (const getter of this.currentGetters) {
335
+ if (!this.flags.collapsed) {
336
+ var end_node_slotpos = this.getConnectionPos(false, 0);
337
+ end_node_slotpos = [
338
+ getter.pos[0] - end_node_slotpos[0] + this.size[0],
339
+ getter.pos[1] - end_node_slotpos[1]
340
+ ];
341
+ }
342
+ else {
343
+ var end_node_slotpos = this.getConnectionPos(false, 0);
344
+ end_node_slotpos = [
345
+ getter.pos[0] - end_node_slotpos[0] + title_width + 50,
346
+ getter.pos[1] - end_node_slotpos[1] - 30
347
+ ];
348
+ }
349
+ lGraphCanvas.renderLink(
350
+ ctx,
351
+ start_node_slotpos,
352
+ end_node_slotpos,
353
+ defaultLink,
354
+ false,
355
+ null,
356
+ this.slotColor,
357
+ LiteGraph.RIGHT,
358
+ LiteGraph.LEFT
359
+ );
360
+ }
361
+ }
362
+ }
363
+
364
+ LiteGraph.registerNodeType(
365
+ "SetNode",
366
+ Object.assign(SetNode, {
367
+ title: "Set",
368
+ })
369
+ );
370
+
371
+ SetNode.category = "KJNodes";
372
+ },
373
+ });
374
+
375
+ app.registerExtension({
376
+ name: "GetNode",
377
+ registerCustomNodes() {
378
+ class GetNode extends LGraphNode {
379
+
380
+ defaultVisibility = true;
381
+ serialize_widgets = true;
382
+ drawConnection = false;
383
+ slotColor = "#FFF";
384
+ currentSetter = null;
385
+ canvas = app.canvas;
386
+
387
+ constructor(title) {
388
+ super(title)
389
+ if (!this.properties) {
390
+ this.properties = {};
391
+ }
392
+ this.properties.showOutputText = GetNode.defaultVisibility;
393
+ const node = this;
394
+ this.addWidget(
395
+ "combo",
396
+ "Constant",
397
+ "",
398
+ (e) => {
399
+ this.onRename();
400
+ },
401
+ {
402
+ values: () => {
403
+ const setterNodes = node.graph._nodes.filter((otherNode) => otherNode.type == 'SetNode');
404
+ return setterNodes.map((otherNode) => otherNode.widgets[0].value).sort();
405
+ }
406
+ }
407
+ )
408
+
409
+ this.addOutput("*", '*');
410
+ this.onConnectionsChange = function(
411
+ slotType, //0 = output, 1 = input
412
+ slot, //self-explanatory
413
+ isChangeConnect,
414
+ link_info,
415
+ output
416
+ ) {
417
+ this.validateLinks();
418
+ }
419
+
420
+ this.setName = function(name) {
421
+ node.widgets[0].value = name;
422
+ node.onRename();
423
+ node.serialize();
424
+ }
425
+
426
+ this.onRename = function() {
427
+ const setter = this.findSetter(node.graph);
428
+ if (setter) {
429
+ let linkType = (setter.inputs[0].type);
430
+
431
+ this.setType(linkType);
432
+ this.title = (!disablePrefix ? "Get_" : "") + setter.widgets[0].value;
433
+
434
+ if (app.ui.settings.getSettingValue("KJNodes.nodeAutoColor")){
435
+ setColorAndBgColor.call(this, linkType);
436
+ }
437
+
438
+ } else {
439
+ this.setType('*');
440
+ }
441
+ }
442
+
443
+ this.clone = function () {
444
+ const cloned = GetNode.prototype.clone.apply(this);
445
+ cloned.size = cloned.computeSize();
446
+ return cloned;
447
+ };
448
+
449
+ this.validateLinks = function() {
450
+ if (this.outputs[0].type !== '*' && this.outputs[0].links) {
451
+ this.outputs[0].links.filter(linkId => {
452
+ const link = node.graph.links[linkId];
453
+ return link && (!link.type.split(",").includes(this.outputs[0].type) && link.type !== '*');
454
+ }).forEach(linkId => {
455
+ node.graph.removeLink(linkId);
456
+ });
457
+ }
458
+ };
459
+
460
+ this.setType = function(type) {
461
+ this.outputs[0].name = type;
462
+ this.outputs[0].type = type;
463
+ this.validateLinks();
464
+ }
465
+
466
+ this.findSetter = function(graph) {
467
+ const name = this.widgets[0].value;
468
+ const foundNode = graph._nodes.find(otherNode => otherNode.type === 'SetNode' && otherNode.widgets[0].value === name && name !== '');
469
+ return foundNode;
470
+ };
471
+
472
+ this.goToSetter = function() {
473
+ const setter = this.findSetter(this.graph);
474
+ this.canvas.centerOnNode(setter);
475
+ this.canvas.selectNode(setter, false);
476
+ };
477
+
478
+ // This node is purely frontend and does not impact the resulting prompt so should not be serialized
479
+ this.isVirtualNode = true;
480
+ }
481
+
482
+ getInputLink(slot) {
483
+ const setter = this.findSetter(this.graph);
484
+
485
+ if (setter) {
486
+ const slotInfo = setter.inputs[slot];
487
+ const link = this.graph.links[slotInfo.link];
488
+ return link;
489
+ } else {
490
+ const errorMessage = "No SetNode found for " + this.widgets[0].value + "(" + this.type + ")";
491
+ showAlert(errorMessage);
492
+ //throw new Error(errorMessage);
493
+ }
494
+ }
495
+ onAdded(graph) {
496
+ }
497
+ getExtraMenuOptions(_, options) {
498
+ let menuEntry = this.drawConnection ? "Hide connections" : "Show connections";
499
+
500
+ options.unshift(
501
+ {
502
+ content: "Go to setter",
503
+ callback: () => {
504
+ this.goToSetter();
505
+ },
506
+ },
507
+ {
508
+ content: menuEntry,
509
+ callback: () => {
510
+ this.currentSetter = this.findSetter(this.graph);
511
+ if (this.currentSetter.length == 0) return;
512
+ let linkType = (this.currentSetter.inputs[0].type);
513
+ this.drawConnection = !this.drawConnection;
514
+ this.slotColor = this.canvas.default_connection_color_byType[linkType]
515
+ menuEntry = this.drawConnection ? "Hide connections" : "Show connections";
516
+ this.canvas.setDirty(true, true);
517
+ },
518
+ },
519
+ );
520
+ }
521
+
522
+ onDrawForeground(ctx, lGraphCanvas) {
523
+ if (this.drawConnection) {
524
+ this._drawVirtualLink(lGraphCanvas, ctx);
525
+ }
526
+ }
527
+ // onDrawCollapsed(ctx, lGraphCanvas) {
528
+ // if (this.drawConnection) {
529
+ // this._drawVirtualLink(lGraphCanvas, ctx);
530
+ // }
531
+ // }
532
+ _drawVirtualLink(lGraphCanvas, ctx) {
533
+ if (!this.currentSetter) return;
534
+
535
+ // Provide a default link object with necessary properties, to avoid errors as link can't be null anymore
536
+ const defaultLink = { type: 'default', color: this.slotColor };
537
+
538
+ let start_node_slotpos = this.currentSetter.getConnectionPos(false, 0);
539
+ start_node_slotpos = [
540
+ start_node_slotpos[0] - this.pos[0],
541
+ start_node_slotpos[1] - this.pos[1],
542
+ ];
543
+ let end_node_slotpos = [0, -LiteGraph.NODE_TITLE_HEIGHT * 0.5];
544
+ lGraphCanvas.renderLink(
545
+ ctx,
546
+ start_node_slotpos,
547
+ end_node_slotpos,
548
+ defaultLink,
549
+ false,
550
+ null,
551
+ this.slotColor
552
+ );
553
+ }
554
+ }
555
+
556
+ LiteGraph.registerNodeType(
557
+ "GetNode",
558
+ Object.assign(GetNode, {
559
+ title: "Get",
560
+ })
561
+ );
562
+
563
+ GetNode.category = "KJNodes";
564
+ },
565
+ });
web/js/spline_editor.js ADDED
@@ -0,0 +1,1379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-splineditor-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
+ .spline-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.SplineEditor',
102
+
103
+ async beforeRegisterNodeDef(nodeType, nodeData) {
104
+ if (nodeData?.name === 'SplineEditor') {
105
+ chainCallback(nodeType.prototype, "onNodeCreated", function () {
106
+
107
+ this.widgets.find(w => w.name === "coordinates").hidden = true
108
+
109
+ var element = document.createElement("div");
110
+ this.uuid = makeUUID()
111
+ element.id = `spline-editor-${this.uuid}`
112
+
113
+ this.previewMediaType = 'image'
114
+
115
+ this.splineEditor = this.addDOMWidget(nodeData.name, "SplineEditorWidget", element, {
116
+ serialize: false,
117
+ hideOnZoom: false,
118
+ });
119
+
120
+ // context menu
121
+ this.contextMenu = document.createElement("div");
122
+ this.contextMenu.className = 'spline-editor-context-menu';
123
+ this.contextMenu.id = "context-menu";
124
+ this.contextMenu.style.display = "none";
125
+ this.contextMenu.style.position = "absolute";
126
+ this.contextMenu.style.backgroundColor = "#202020";
127
+ this.contextMenu.style.minWidth = "100px";
128
+ this.contextMenu.style.boxShadow = "0px 8px 16px 0px rgba(0,0,0,0.2)";
129
+ this.contextMenu.style.zIndex = "100";
130
+ this.contextMenu.style.padding = "5px";
131
+
132
+ function styleMenuItem(menuItem) {
133
+ menuItem.style.display = "block";
134
+ menuItem.style.padding = "5px";
135
+ menuItem.style.color = "#FFF";
136
+ menuItem.style.fontFamily = "Arial, sans-serif";
137
+ menuItem.style.fontSize = "16px";
138
+ menuItem.style.textDecoration = "none";
139
+ menuItem.style.marginBottom = "5px";
140
+ }
141
+ function createMenuItem(id, textContent) {
142
+ let menuItem = document.createElement("a");
143
+ menuItem.href = "#";
144
+ menuItem.id = `menu-item-${id}`;
145
+ menuItem.textContent = textContent;
146
+ styleMenuItem(menuItem);
147
+ return menuItem;
148
+ }
149
+
150
+ // Create an array of menu items using the createMenuItem function
151
+ this.menuItems = [
152
+ createMenuItem(0, "Toggle handles"),
153
+ createMenuItem(1, "Display sample points"),
154
+ createMenuItem(2, "Switch point shape"),
155
+ createMenuItem(3, "Background image"),
156
+ createMenuItem(4, "Invert point order"),
157
+ createMenuItem(5, "Clear Image"),
158
+ createMenuItem(6, "Add new spline"),
159
+ createMenuItem(7, "Add new single point"),
160
+ createMenuItem(8, "Delete current spline"),
161
+ createMenuItem(9, "Next spline"),
162
+ ];
163
+
164
+ // Add mouseover and mouseout event listeners to each menu item for styling
165
+ this.menuItems.forEach(menuItem => {
166
+ menuItem.addEventListener('mouseover', function() {
167
+ this.style.backgroundColor = "gray";
168
+ });
169
+
170
+ menuItem.addEventListener('mouseout', function() {
171
+ this.style.backgroundColor = "#202020";
172
+ });
173
+ });
174
+
175
+ // Append each menu item to the context menu
176
+ this.menuItems.forEach(menuItem => {
177
+ this.contextMenu.appendChild(menuItem);
178
+ });
179
+
180
+ document.body.appendChild(this.contextMenu);
181
+
182
+ this.addWidget("button", "New canvas", null, () => {
183
+ if (!this.properties || !("points" in this.properties)) {
184
+ this.editor = new SplineEditor(this);
185
+ this.addProperty("points", this.constructor.type, "string");
186
+ }
187
+ else {
188
+ this.editor = new SplineEditor(this, true);
189
+ }
190
+ });
191
+
192
+ this.setSize([550, 1000]);
193
+ this.resizable = false;
194
+ this.splineEditor.parentEl = document.createElement("div");
195
+ this.splineEditor.parentEl.className = "spline-editor";
196
+ this.splineEditor.parentEl.id = `spline-editor-${this.uuid}`
197
+ element.appendChild(this.splineEditor.parentEl);
198
+
199
+ chainCallback(this, "onConfigure", function () {
200
+ try {
201
+ this.editor = new SplineEditor(this);
202
+ } catch (error) {
203
+ console.error("An error occurred while configuring the editor:", error);
204
+ }
205
+ });
206
+ chainCallback(this, "onExecuted", function (message) {
207
+ let bg_image = message["bg_image"];
208
+ this.properties.imgData = {
209
+ name: "bg_image",
210
+ base64: bg_image
211
+ };
212
+ this.editor.refreshBackgroundImage(this);
213
+ });
214
+
215
+ }); // onAfterGraphConfigured
216
+ }//node created
217
+ } //before register
218
+ })//register
219
+
220
+
221
+ class SplineEditor{
222
+ constructor(context, reset = false) {
223
+ this.node = context;
224
+ this.reset=reset;
225
+ const self = this;
226
+ console.log("creatingSplineEditor")
227
+
228
+ this.node.pasteFile = (file) => {
229
+ if (file.type.startsWith("image/")) {
230
+ this.handleImageFile(file);
231
+ return true;
232
+ }
233
+ return false;
234
+ };
235
+
236
+ this.node.onDragOver = function (e) {
237
+ if (e.dataTransfer && e.dataTransfer.items) {
238
+ return [...e.dataTransfer.items].some(f => f.kind === "file" && f.type.startsWith("image/"));
239
+ }
240
+ return false;
241
+ };
242
+
243
+ // On drop upload files
244
+ this.node.onDragDrop = (e) => {
245
+ console.log("onDragDrop called");
246
+ let handled = false;
247
+ for (const file of e.dataTransfer.files) {
248
+ if (file.type.startsWith("image/")) {
249
+ this.handleImageFile(file);
250
+ handled = true;
251
+ }
252
+ }
253
+ return handled;
254
+ };
255
+
256
+ // context menu
257
+ this.createContextMenu();
258
+
259
+
260
+ this.dotShape = "circle";
261
+ this.drawSamplePoints = false;
262
+
263
+ if (reset && context.splineEditor.element) {
264
+ context.splineEditor.element.innerHTML = ''; // Clear the container
265
+ }
266
+ this.coordWidget = context.widgets.find(w => w.name === "coordinates");
267
+ this.interpolationWidget = context.widgets.find(w => w.name === "interpolation");
268
+ this.pointsWidget = context.widgets.find(w => w.name === "points_to_sample");
269
+ this.pointsStoreWidget = context.widgets.find(w => w.name === "points_store");
270
+ this.tensionWidget = context.widgets.find(w => w.name === "tension");
271
+ this.minValueWidget = context.widgets.find(w => w.name === "min_value");
272
+ this.maxValueWidget = context.widgets.find(w => w.name === "max_value");
273
+ this.samplingMethodWidget = context.widgets.find(w => w.name === "sampling_method");
274
+ this.widthWidget = context.widgets.find(w => w.name === "mask_width");
275
+ this.heightWidget = context.widgets.find(w => w.name === "mask_height");
276
+
277
+ this.interpolation = this.interpolationWidget.value
278
+ this.tension = this.tensionWidget.value
279
+ this.points_to_sample = this.pointsWidget.value
280
+ this.rangeMin = this.minValueWidget.value
281
+ this.rangeMax = this.maxValueWidget.value
282
+ this.pointsLayer = null;
283
+ this.samplingMethod = this.samplingMethodWidget.value
284
+
285
+ if (this.samplingMethod == "path"||this.samplingMethod == "speed") {
286
+ this.dotShape = "triangle"
287
+ }
288
+
289
+
290
+ this.interpolationWidget.callback = () => {
291
+ this.interpolation = this.interpolationWidget.value
292
+ this.updatePath();
293
+ }
294
+ this.samplingMethodWidget.callback = () => {
295
+ this.samplingMethod = this.samplingMethodWidget.value
296
+ if (this.samplingMethod == "path") {
297
+ this.dotShape = "triangle"
298
+ }
299
+ else if (this.samplingMethod == "controlpoints") {
300
+ this.dotShape = "circle"
301
+ this.drawSamplePoints = true;
302
+ }
303
+ this.updatePath();
304
+ }
305
+ this.tensionWidget.callback = () => {
306
+ this.tension = this.tensionWidget.value
307
+ this.updatePath();
308
+ }
309
+ this.pointsWidget.callback = () => {
310
+ this.points_to_sample = this.pointsWidget.value
311
+ this.updatePath();
312
+ }
313
+ this.minValueWidget.callback = () => {
314
+ this.rangeMin = this.minValueWidget.value
315
+ this.updatePath();
316
+ }
317
+ this.maxValueWidget.callback = () => {
318
+ this.rangeMax = this.maxValueWidget.value
319
+ this.updatePath();
320
+ }
321
+ this.widthWidget.callback = () => {
322
+ this.width = this.widthWidget.value;
323
+ if (this.width > 256) {
324
+ context.setSize([this.width + 45, context.size[1]]);
325
+ }
326
+ this.vis.width(this.width);
327
+ this.updatePath();
328
+ }
329
+ this.heightWidget.callback = () => {
330
+ this.height = this.heightWidget.value
331
+ this.vis.height(this.height)
332
+ context.setSize([context.size[0], this.height + 450]);
333
+ this.updatePath();
334
+ }
335
+ this.pointsStoreWidget.callback = () => {
336
+ points = JSON.parse(this.pointsStoreWidget.value);
337
+ this.updatePath();
338
+ }
339
+
340
+ // Initialize or reset points array
341
+ this.drawHandles = false;
342
+ this.drawRuler = true;
343
+ var hoverIndex = -1;
344
+ var isDragging = false;
345
+ this.width = this.widthWidget.value;
346
+ this.height = this.heightWidget.value;
347
+ var i = 3;
348
+ this.splines = [];
349
+ this.activeSplineIndex = 0; // Track which spline is being edited
350
+ // init mouse position
351
+ this.lastMousePosition = { x: this.width/2, y: this.height/2 };
352
+
353
+ if (!reset && this.pointsStoreWidget.value != "") {
354
+ try {
355
+ const parsedData = JSON.parse(this.pointsStoreWidget.value);
356
+ // Check if it's already in the new format (array of splines)
357
+ if (Array.isArray(parsedData) && parsedData.length > 0 && parsedData[0].hasOwnProperty('points')) {
358
+ this.splines = parsedData;
359
+ } else {
360
+ // Convert old format (single array of points) to new format
361
+ this.splines = [{
362
+ points: parsedData,
363
+ color: "#1f77b4",
364
+ name: "Spline 1"
365
+ }];
366
+ }
367
+ } catch (e) {
368
+ console.error("Error parsing spline data:", e);
369
+ this.initializeDefaultSplines();
370
+ }
371
+ } else {
372
+ this.initializeDefaultSplines();
373
+ this.pointsStoreWidget.value = JSON.stringify(this.splines);
374
+ }
375
+
376
+ this.vis = new pv.Panel()
377
+ .width(this.width)
378
+ .height(this.height)
379
+ .fillStyle("#222")
380
+ .strokeStyle("gray")
381
+ .lineWidth(2)
382
+ .antialias(false)
383
+ .margin(10)
384
+ .event("mousedown", function () {
385
+ if (pv.event.shiftKey) { // Use pv.event to access the event object
386
+ let scaledMouse = {
387
+ x: this.mouse().x / app.canvas.ds.scale,
388
+ y: this.mouse().y / app.canvas.ds.scale
389
+ };
390
+ i = self.splines[self.activeSplineIndex].points.push(scaledMouse) - 1;
391
+ self.updatePath();
392
+ return this;
393
+ }
394
+ else if (pv.event.ctrlKey) {
395
+ // Capture the clicked location
396
+ let clickedPoint = {
397
+ x: this.mouse().x / app.canvas.ds.scale,
398
+ y: this.mouse().y / app.canvas.ds.scale
399
+ };
400
+
401
+ // Find the two closest points to the clicked location
402
+ const activePoints = self.splines[self.activeSplineIndex].points;
403
+ let { point1Index, point2Index } = self.findClosestPoints(self.splines[self.activeSplineIndex].points, clickedPoint);
404
+
405
+ // Calculate the midpoint between the two closest points
406
+ let midpoint = {
407
+ x: (activePoints[point1Index].x + activePoints[point2Index].x) / 2,
408
+ y: (activePoints[point1Index].y + activePoints[point2Index].y) / 2
409
+ };
410
+
411
+ // Insert the midpoint into the array
412
+ activePoints.splice(point2Index, 0, midpoint);
413
+ i = point2Index;
414
+ self.updatePath();
415
+ }
416
+ else if (pv.event.button === 2) {
417
+ // Store the current mouse position adjusted for scale
418
+ self.lastMousePosition = {
419
+ x: this.mouse().x / app.canvas.ds.scale,
420
+ y: this.mouse().y / app.canvas.ds.scale
421
+ };
422
+
423
+ self.node.contextMenu.style.display = 'block';
424
+ self.node.contextMenu.style.left = `${pv.event.clientX}px`;
425
+ self.node.contextMenu.style.top = `${pv.event.clientY}px`;
426
+ }
427
+ })
428
+ this.backgroundImage = this.vis.add(pv.Image).visible(false)
429
+
430
+ this.vis.add(pv.Rule)
431
+ .data(pv.range(0, this.height, 64))
432
+ .bottom(d => d)
433
+ .strokeStyle("gray")
434
+ .lineWidth(3)
435
+ .visible(() => self.drawRuler)
436
+
437
+ this.hoverSplineIndex = -1;
438
+
439
+ this.splines.forEach((spline, splineIndex) => {
440
+ const strokeObj = this.vis.add(pv.Line)
441
+ .data(() => spline.points)
442
+ .left(d => d.x)
443
+ .top(d => d.y)
444
+ .interpolate(() => this.interpolation)
445
+ .tension(() => this.tension)
446
+ .segmented(() => false)
447
+ .strokeStyle("black") // Stroke color
448
+ .lineWidth(() => {
449
+ // Make stroke slightly wider than the main line
450
+ if (splineIndex === this.activeSplineIndex) return 5;
451
+ if (splineIndex === this.hoverSplineIndex) return 4;
452
+ return 3.5;
453
+ });
454
+
455
+ this.vis.add(pv.Line)
456
+ .data(() => spline.points)
457
+ .left(d => d.x)
458
+ .top(d => d.y)
459
+ .interpolate(() => this.interpolation)
460
+ .tension(() => this.tension)
461
+ .segmented(() => false)
462
+ .strokeStyle(spline.color)
463
+ .lineWidth(() => {
464
+ // Change line width based on active or hover state
465
+ if (splineIndex === this.activeSplineIndex) return 3;
466
+ if (splineIndex === this.hoverSplineIndex) return 2;
467
+ return 1.5;
468
+ })
469
+ .event("mouseover", () => {
470
+ this.hoverSplineIndex = splineIndex;
471
+ this.vis.render();
472
+ })
473
+ .event("mouseout", () => {
474
+ this.hoverSplineIndex = -1;
475
+ this.vis.render();
476
+ })
477
+ .event("mousedown", () => {
478
+ if (this.activeSplineIndex !== splineIndex) {
479
+ this.activeSplineIndex = splineIndex;
480
+ this.refreshSplineElements();
481
+ }
482
+ });
483
+ });
484
+
485
+ this.vis.add(pv.Dot)
486
+ .data(() => {
487
+ const activeSpline = this.splines[this.activeSplineIndex];
488
+ // If this is a single point, don't show it in the main visualization
489
+ if (activeSpline.isSinglePoint || (activeSpline.points && activeSpline.points.length === 1)) {
490
+ return []; // Return empty array to hide in main visualization
491
+ }
492
+ return activeSpline.points;
493
+ })
494
+ .left(d => d.x)
495
+ .top(d => d.y)
496
+ .radius(12)
497
+ .shape(function() {
498
+ return self.dotShape;
499
+ })
500
+ .angle(function() {
501
+ const index = this.index;
502
+ let angle = 0;
503
+
504
+ if (self.dotShape === "triangle") {
505
+ const activePoints = self.splines[self.activeSplineIndex].points;
506
+ let dxNext = 0, dyNext = 0;
507
+ if (index < activePoints.length - 1) {
508
+ dxNext = activePoints[index + 1].x - activePoints[index].x;
509
+ dyNext = activePoints[index + 1].y - activePoints[index].y;
510
+ }
511
+
512
+ let dxPrev = 0, dyPrev = 0;
513
+ if (index > 0) {
514
+ dxPrev = activePoints[index].x - activePoints[index - 1].x;
515
+ dyPrev = activePoints[index].y - activePoints[index - 1].y;
516
+ }
517
+
518
+ const dx = (dxNext + dxPrev) / 2;
519
+ const dy = (dyNext + dyPrev) / 2;
520
+
521
+ angle = Math.atan2(dy, dx);
522
+ angle -= Math.PI / 2;
523
+ angle = (angle + 2 * Math.PI) % (2 * Math.PI);
524
+ }
525
+
526
+ return angle;
527
+ })
528
+ .cursor("move")
529
+ .strokeStyle(function () { return i == this.index ? "#ff7f0e" : "#1f77b4"; })
530
+ .fillStyle(function () { return "rgba(100, 100, 100, 0.3)"; })
531
+ .event("mousedown", pv.Behavior.drag())
532
+ .event("dragstart", function () {
533
+ i = this.index;
534
+ hoverIndex = this.index;
535
+ isDragging = true;
536
+ const activePoints = self.splines[self.activeSplineIndex].points;
537
+ if (pv.event.button === 2 && i !== 0 && i !== activePoints.length - 1) {
538
+ activePoints.splice(i--, 1);
539
+ self.vis.render();
540
+ }
541
+ return this;
542
+ })
543
+ .event("dragend", function() {
544
+ if (this.pathElements !== null) {
545
+ self.updatePath();
546
+ }
547
+ isDragging = false;
548
+ })
549
+ .event("drag", function () {
550
+ let adjustedX = this.mouse().x / app.canvas.ds.scale; // Adjust the new X position by the inverse of the scale factor
551
+ let adjustedY = this.mouse().y / app.canvas.ds.scale; // Adjust the new Y position by the inverse of the scale factor
552
+ // Determine the bounds of the vis.Panel
553
+ const panelWidth = self.vis.width();
554
+ const panelHeight = self.vis.height();
555
+
556
+ // Adjust the new position if it would place the dot outside the bounds of the vis.Panel
557
+ adjustedX = Math.max(0, Math.min(panelWidth, adjustedX));
558
+ adjustedY = Math.max(0, Math.min(panelHeight, adjustedY));
559
+ self.splines[self.activeSplineIndex].points[this.index] = { x: adjustedX, y: adjustedY }; // Update the point's position
560
+ self.vis.render(); // Re-render the visualization to reflect the new position
561
+ })
562
+ .event("mouseover", function() {
563
+ hoverIndex = this.index; // Set the hover index to the index of the hovered dot
564
+ self.vis.render(); // Re-render the visualization
565
+ })
566
+ .event("mouseout", function() {
567
+ !isDragging && (hoverIndex = -1); // Reset the hover index when the mouse leaves the dot
568
+ self.vis.render(); // Re-render the visualization
569
+ })
570
+ .anchor("center")
571
+ .add(pv.Label)
572
+ .visible(function() {
573
+ return hoverIndex === this.index; // Only show the label for the hovered dot
574
+ })
575
+ .left(d => d.x < this.width / 2 ? d.x + 80 : d.x - 70) // Shift label to right if on left half, otherwise shift to left
576
+ .top(d => d.y < this.height / 2 ? d.y + 20 : d.y - 20) // Shift label down if on top half, otherwise shift up
577
+ .font(12 + "px sans-serif")
578
+ .text(d => {
579
+ if (this.samplingMethod == "path") {
580
+ return `X: ${Math.round(d.x)}, Y: ${Math.round(d.y)}`;
581
+ } else {
582
+ let frame = Math.round((d.x / self.width) * self.points_to_sample);
583
+ let normalizedY = (1.0 - (d.y / self.height) - 0.0) * (self.rangeMax - self.rangeMin) + self.rangeMin;
584
+ let normalizedX = (d.x / self.width);
585
+ return `F: ${frame}, X: ${normalizedX.toFixed(2)}, Y: ${normalizedY.toFixed(2)}`;
586
+ }
587
+ })
588
+ .textStyle("orange")
589
+
590
+ // single points
591
+ this.vis.add(pv.Dot)
592
+ .data(() => {
593
+ // Collect all single points from all splines
594
+ const singlePoints = [];
595
+ this.splines.forEach((spline, splineIndex) => {
596
+ if (spline.isSinglePoint || (spline.points && spline.points.length === 1)) {
597
+ singlePoints.push({
598
+ x: spline.points[0].x,
599
+ y: spline.points[0].y,
600
+ splineIndex: splineIndex,
601
+ color: spline.color
602
+ });
603
+ }
604
+ });
605
+ return singlePoints;
606
+ })
607
+ .left(d => d.x)
608
+ .top(d => d.y)
609
+ .radius(6)
610
+ .shape("square")
611
+ .strokeStyle(d => d.splineIndex === this.activeSplineIndex ? "#ff7f0e" : d.color)
612
+ .fillStyle(d => "rgba(100, 100, 100, 0.9)")
613
+ .lineWidth(d => d.splineIndex === this.activeSplineIndex ? 3 : 1.5)
614
+ .cursor("move")
615
+ .event("mousedown", pv.Behavior.drag())
616
+ .event("dragstart", function(d) {
617
+ self.activeSplineIndex = d.splineIndex;
618
+ self.refreshSplineElements();
619
+ return this;
620
+ })
621
+ .event("drag", function(d) {
622
+ let adjustedX = this.mouse().x / app.canvas.ds.scale;
623
+ let adjustedY = this.mouse().y / app.canvas.ds.scale;
624
+
625
+ // Determine the bounds of the vis.Panel
626
+ const panelWidth = self.vis.width();
627
+ const panelHeight = self.vis.height();
628
+
629
+ // Adjust the new position if it would place the dot outside the bounds
630
+ adjustedX = Math.max(0, Math.min(panelWidth, adjustedX));
631
+ adjustedY = Math.max(0, Math.min(panelHeight, adjustedY));
632
+
633
+ // Update the point position
634
+ const spline = self.splines[d.splineIndex];
635
+ spline.points[0] = { x: adjustedX, y: adjustedY };
636
+
637
+ // For single points, we need to refresh the entire spline element
638
+ // to prevent the line-drawing effect
639
+
640
+ })
641
+ .event("dragend", function(d) {
642
+ self.refreshSplineElements();
643
+ self.updatePath();
644
+ })
645
+ .visible(d => true); // Make always visible
646
+
647
+ if (this.splines.length != 0) {
648
+ this.vis.render();
649
+ }
650
+ var svgElement = this.vis.canvas();
651
+ svgElement.style['zIndex'] = "2"
652
+ svgElement.style['position'] = "relative"
653
+ this.node.splineEditor.element.appendChild(svgElement);
654
+ this.pathElements = svgElement.getElementsByTagName('path'); // Get all path elements
655
+
656
+ if (this.width > 256) {
657
+ this.node.setSize([this.width + 45, this.node.size[1]]);
658
+ }
659
+ this.node.setSize([this.node.size[0], this.height + 450]);
660
+ this.updatePath();
661
+ this.refreshBackgroundImage();
662
+ }
663
+
664
+ updatePath = () => {
665
+ if (!this.splines || this.splines.length === 0) {
666
+ console.log("no splines");
667
+ return;
668
+ }
669
+ // Get active spline points
670
+ console.log("this.activeSplineIndex", this.activeSplineIndex);
671
+ const activeSpline = this.splines[this.activeSplineIndex];
672
+ const activePoints = activeSpline.points;
673
+
674
+ if (!activePoints || activePoints.length === 0) {
675
+ console.log("no points in active spline");
676
+ return;
677
+ }
678
+
679
+
680
+ let coords;
681
+ if (this.samplingMethod != "controlpoints") {
682
+ coords = this.samplePoints(this.pathElements[this.activeSplineIndex], this.points_to_sample, this.samplingMethod, this.width, this.activeSplineIndex);
683
+ } else {
684
+ coords = activePoints;
685
+ }
686
+
687
+ let allSplineCoords = [];
688
+ for (let i = 0; i < this.splines.length; i++) {
689
+ // Use the same sampling method for all splines
690
+ let splineCoords;
691
+ const pathElement = this.pathElements[i];
692
+
693
+ if (this.samplingMethod != "controlpoints" && pathElement) {
694
+ splineCoords = this.samplePoints(pathElement, this.points_to_sample, this.samplingMethod, this.width, i);
695
+ } else {
696
+ // Fall back to control points if no path element or sampling method is "controlpoints"
697
+ splineCoords = this.splines[i].points;
698
+ }
699
+
700
+ allSplineCoords.push(splineCoords);
701
+ }
702
+
703
+ if (this.drawSamplePoints) {
704
+ if (this.pointsLayer) {
705
+ // Update the data of the existing points layer
706
+ this.pointsLayer.data(coords);
707
+ } else {
708
+ // Create the points layer if it doesn't exist
709
+ this.pointsLayer = this.vis.add(pv.Dot)
710
+ .data(coords)
711
+ .left(function(d) { return d.x; })
712
+ .top(function(d) { return d.y; })
713
+ .radius(5) // Adjust the radius as needed
714
+ .fillStyle("red") // Change the color as needed
715
+ .strokeStyle("black") // Change the stroke color as needed
716
+ .lineWidth(1); // Adjust the line width as needed
717
+ }
718
+ } else {
719
+ if (this.pointsLayer) {
720
+ // Remove the points layer
721
+ this.pointsLayer.data([]);
722
+ this.vis.render();
723
+ }
724
+ }
725
+ this.pointsStoreWidget.value = JSON.stringify(this.splines);
726
+ if (this.coordWidget) {
727
+ this.coordWidget.value = JSON.stringify(allSplineCoords);
728
+ }
729
+ this.vis.render();
730
+ };
731
+
732
+ handleImageLoad = (img, file, base64String) => {
733
+ //console.log(img.width, img.height); // Access width and height here
734
+ this.widthWidget.value = img.width;
735
+ this.heightWidget.value = img.height;
736
+ this.drawRuler = false;
737
+
738
+ if (img.width != this.vis.width() || img.height != this.vis.height()) {
739
+ if (img.width > 256) {
740
+ this.node.setSize([img.width + 45, this.node.size[1]]);
741
+ }
742
+ this.node.setSize([this.node.size[0], img.height + 520]);
743
+ this.vis.width(img.width);
744
+ this.vis.height(img.height);
745
+ this.height = img.height;
746
+ this.width = img.width;
747
+
748
+ this.updatePath();
749
+ }
750
+ this.backgroundImage.url(file ? URL.createObjectURL(file) : `data:${this.node.properties.imgData.type};base64,${base64String}`).visible(true).root.render();
751
+ };
752
+
753
+ processImage = (img, file) => {
754
+ const canvas = document.createElement('canvas');
755
+ const ctx = canvas.getContext('2d');
756
+
757
+ const maxWidth = 800; // maximum width
758
+ const maxHeight = 600; // maximum height
759
+ let width = img.width;
760
+ let height = img.height;
761
+
762
+ // Calculate the new dimensions while preserving the aspect ratio
763
+ if (width > height) {
764
+ if (width > maxWidth) {
765
+ height *= maxWidth / width;
766
+ width = maxWidth;
767
+ }
768
+ } else {
769
+ if (height > maxHeight) {
770
+ width *= maxHeight / height;
771
+ height = maxHeight;
772
+ }
773
+ }
774
+
775
+ canvas.width = width;
776
+ canvas.height = height;
777
+ ctx.drawImage(img, 0, 0, width, height);
778
+
779
+ // Get the compressed image data as a Base64 string
780
+ const base64String = canvas.toDataURL('image/jpeg', 0.5).replace('data:', '').replace(/^.+,/, ''); // 0.5 is the quality from 0 to 1
781
+
782
+ this.node.properties.imgData = {
783
+ name: file.name,
784
+ lastModified: file.lastModified,
785
+ size: file.size,
786
+ type: file.type,
787
+ base64: base64String
788
+ };
789
+ handleImageLoad(img, file, base64String);
790
+ };
791
+
792
+ handleImageFile = (file) => {
793
+ const reader = new FileReader();
794
+ reader.onloadend = () => {
795
+ const img = new Image();
796
+ img.src = reader.result;
797
+ img.onload = () => processImage(img, file);
798
+ };
799
+ reader.readAsDataURL(file);
800
+
801
+ const imageUrl = URL.createObjectURL(file);
802
+ const img = new Image();
803
+ img.src = imageUrl;
804
+ img.onload = () => this.handleImageLoad(img, file, null);
805
+ };
806
+
807
+ refreshBackgroundImage = () => {
808
+ if (this.node.properties.imgData && this.node.properties.imgData.base64) {
809
+ const base64String = this.node.properties.imgData.base64;
810
+ const imageUrl = `data:${this.node.properties.imgData.type};base64,${base64String}`;
811
+ const img = new Image();
812
+ img.src = imageUrl;
813
+ img.onload = () => this.handleImageLoad(img, null, base64String);
814
+ }
815
+ };
816
+
817
+ refreshSplineElements = () => {
818
+ // Clear existing line elements and recreate them
819
+ const svgElement = this.vis.canvas();
820
+
821
+ // Remove all existing line elements
822
+ const oldLines = svgElement.querySelectorAll('path');
823
+ oldLines.forEach(line => line.remove());
824
+
825
+ this.pathElements = [];
826
+ this.lineObjects = [];
827
+
828
+ const originalChildren = [...this.vis.children];
829
+
830
+ // Find line objects to remove (those that represent splines)
831
+ const linesToRemove = originalChildren.filter(child =>
832
+ child instanceof pv.Line
833
+ );
834
+ linesToRemove.forEach(line => line.visible(false));
835
+
836
+ // Re-add all spline lines and store references to them
837
+ this.splines.forEach((spline, splineIndex) => {
838
+ // For single points, we need a special handling
839
+ if (spline.isSinglePoint || (spline.points && spline.points.length === 1)) {
840
+ const point = spline.points[0];
841
+ // For single points, create a tiny line at the same point
842
+ // This ensures we have a path element for the point
843
+ const lineObj = this.vis.add(pv.Line)
844
+ .data([point, {x: point.x + 0.001, y: point.y + 0.001}])
845
+ .left(d => d.x)
846
+ .top(d => d.y)
847
+ .strokeStyle(spline.color)
848
+ .lineWidth(() => {
849
+ if (splineIndex === this.activeSplineIndex) return 3;
850
+ if (splineIndex === this.hoverSplineIndex) return 2;
851
+ return 1.5;
852
+ })
853
+ .event("mouseover", () => {
854
+ this.hoverSplineIndex = splineIndex;
855
+ this.vis.render();
856
+ })
857
+ .event("mouseout", () => {
858
+ this.hoverSplineIndex = -1;
859
+ this.vis.render();
860
+ })
861
+ .event("mousedown", () => {
862
+ if (this.activeSplineIndex !== splineIndex) {
863
+ this.activeSplineIndex = splineIndex;
864
+ this.refreshSplineElements();
865
+ }
866
+ });
867
+ this.lineObjects.push(lineObj);
868
+ } else {
869
+ // For normal multi-point splines
870
+ const strokeObj = this.vis.add(pv.Line)
871
+ .data(() => spline.points)
872
+ .left(d => d.x)
873
+ .top(d => d.y)
874
+ .interpolate(() => this.interpolation)
875
+ .tension(() => this.tension)
876
+ .segmented(() => false)
877
+ .strokeStyle("black") // Stroke color
878
+ .lineWidth(() => {
879
+ // Make stroke slightly wider than the main line
880
+ if (splineIndex === this.activeSplineIndex) return 5;
881
+ if (splineIndex === this.hoverSplineIndex) return 4;
882
+ return 3.5;
883
+ });
884
+ const lineObj = this.vis.add(pv.Line)
885
+ .data(() => spline.points)
886
+ .left(d => d.x)
887
+ .top(d => d.y)
888
+ .interpolate(() => this.interpolation)
889
+ .tension(() => this.tension)
890
+ .segmented(() => false)
891
+ .strokeStyle(spline.color)
892
+ .lineWidth(() => {
893
+ if (splineIndex === this.activeSplineIndex) return 3;
894
+ if (splineIndex === this.hoverSplineIndex) return 2;
895
+ return 1.5;
896
+ })
897
+ .event("mouseover", () => {
898
+ this.hoverSplineIndex = splineIndex;
899
+ this.vis.render();
900
+ })
901
+ .event("mouseout", () => {
902
+ this.hoverSplineIndex = -1;
903
+ this.vis.render();
904
+ })
905
+ .event("mousedown", () => {
906
+ if (this.activeSplineIndex !== splineIndex) {
907
+ this.activeSplineIndex = splineIndex;
908
+ this.refreshSplineElements();
909
+ }
910
+ });
911
+
912
+ // // Add invisible wider hit area for easier selection
913
+ // this.vis.add(pv.Line)
914
+ // .data(() => spline.points)
915
+ // .left(d => d.x)
916
+ // .top(d => d.y)
917
+ // .interpolate(() => this.interpolation)
918
+ // .tension(() => this.tension)
919
+ // .segmented(() => false)
920
+ // .strokeStyle("rgba(0,0,0,0.01)") // Nearly invisible
921
+ // .lineWidth(15) // Much wider hit area
922
+ // .event("mouseover", () => {
923
+ // this.hoverSplineIndex = splineIndex;
924
+ // this.vis.render();
925
+ // })
926
+ // .event("mouseout", () => {
927
+ // this.hoverSplineIndex = -1;
928
+ // this.vis.render();
929
+ // })
930
+ // .event("mousedown", () => {
931
+ // if (pv.event.shiftKey) {
932
+ // if (this.activeSplineIndex !== splineIndex) {
933
+ // this.activeSplineIndex = splineIndex;
934
+ // this.refreshSplineElements();
935
+ // }
936
+ // }}
937
+ // );
938
+
939
+ this.lineObjects.push(lineObj);
940
+ }
941
+ });
942
+
943
+ this.vis.render();
944
+
945
+ requestAnimationFrame(() => {
946
+ const allPaths = Array.from(svgElement.querySelectorAll('path'));
947
+ this.pathElements = [];
948
+
949
+ // First try: look at paths with specific childIndex values
950
+ this.lineObjects.forEach((lineObj, i) => {
951
+ // Find paths that correspond to our line objects
952
+ const childIndex = lineObj.childIndex;
953
+ const matchingPath = allPaths.find(path =>
954
+ path.$scene && path.$scene.scenes &&
955
+ path.$scene.scenes.childIndex === childIndex
956
+ );
957
+
958
+ if (matchingPath) {
959
+ //console.log("matchingPath:", matchingPath);
960
+ this.pathElements[i] = matchingPath;
961
+ }
962
+ });
963
+
964
+ // Check if we found all paths
965
+ if (this.pathElements.filter(p => p).length !== this.splines.length) {
966
+ // Fallback to color matching
967
+ this.pathElements = [];
968
+ for (let i = 0; i < this.splines.length; i++) {
969
+ const color = this.splines[i].color;
970
+ const matchingPath = allPaths.find(p =>
971
+ p.getAttribute('style')?.includes(color) &&
972
+ !this.pathElements.includes(p)
973
+ );
974
+
975
+ if (matchingPath) {
976
+ this.pathElements[i] = matchingPath;
977
+ }
978
+ }
979
+ }
980
+
981
+ // If we still don't have the right number of paths, use the first N paths
982
+ if (this.pathElements.filter(p => p).length !== this.splines.length) {
983
+ this.pathElements = allPaths.slice(0, this.splines.length);
984
+ }
985
+
986
+ this.updatePath();
987
+ });
988
+ };
989
+
990
+
991
+ initializeDefaultSplines() {
992
+ this.splines = [{
993
+ points: pv.range(1, 4).map((i, index) => {
994
+ if (index === 0) {
995
+ return { x: 0, y: this.height };
996
+ } else if (index === 2) {
997
+ return { x: this.width, y: 0 };
998
+ } else {
999
+ return {
1000
+ x: i * this.width / 5,
1001
+ y: 50 + Math.random() * (this.height - 100)
1002
+ };
1003
+ }
1004
+ }),
1005
+ color: this.getSplineColor(0),
1006
+ name: "Spline 1"
1007
+ }];
1008
+ }
1009
+
1010
+ getSplineColor(index) {
1011
+ const colors = [
1012
+ "#1f77b4", "#ff7f0e", "#2ca02c", "#d62728",
1013
+ "#9467bd", "#8c564b", "#e377c2", "#7f7f7f",
1014
+ "#bcbd22", "#17becf"
1015
+ ];
1016
+ return colors[index % colors.length];
1017
+ }
1018
+
1019
+ createContextMenu = () => {
1020
+ const self = this;
1021
+ const oldMenu = this.node.contextMenu;
1022
+ const newMenu = oldMenu.cloneNode(true);
1023
+ oldMenu.parentNode.replaceChild(newMenu, oldMenu);
1024
+ this.node.contextMenu = newMenu;
1025
+
1026
+ document.addEventListener('contextmenu', function (e) {
1027
+ e.preventDefault();
1028
+ });
1029
+
1030
+ document.addEventListener('click', function (e) {
1031
+ document.querySelectorAll('.spline-editor-context-menu').forEach(menu => {
1032
+ menu.style.display = 'none';
1033
+ });
1034
+ });
1035
+
1036
+ this.node.contextMenu.addEventListener('click', function(e) {
1037
+ e.preventDefault();
1038
+ if (e.target.tagName === 'A') {
1039
+ const id = parseInt(e.target.id.split('-')[2]);
1040
+
1041
+ switch(id) {
1042
+ case 0:
1043
+ e.preventDefault();
1044
+ if (!self.drawHandles) {
1045
+ self.drawHandles = true
1046
+ self.vis.add(pv.Line)
1047
+ .data(() => self.splines[self.activeSplineIndex].points.map((point, index) => ({
1048
+ start: point,
1049
+ end: [index]
1050
+ })))
1051
+ .left(d => d.start.x)
1052
+ .top(d => d.start.y)
1053
+ .interpolate("linear")
1054
+ .tension(0) // Straight lines
1055
+ .strokeStyle("#ff7f0e") // Same color as control points
1056
+ .lineWidth(1)
1057
+ .visible(() => self.drawHandles);
1058
+ self.vis.render();
1059
+ } else {
1060
+ self.drawHandles = false
1061
+ self.vis.render();
1062
+ }
1063
+ self.node.contextMenu.style.display = 'none';
1064
+ break;
1065
+ case 1:
1066
+
1067
+ self.drawSamplePoints = !self.drawSamplePoints;
1068
+ self.updatePath();
1069
+ break;
1070
+ case 2:
1071
+ if (self.dotShape == "circle"){
1072
+ self.dotShape = "triangle"
1073
+ }
1074
+ else {
1075
+ self.dotShape = "circle"
1076
+ }
1077
+ self.updatePath();
1078
+ break;
1079
+ case 3:
1080
+ // Create file input element
1081
+ const fileInput = document.createElement('input');
1082
+ fileInput.type = 'file';
1083
+ fileInput.accept = 'image/*'; // Accept only image files
1084
+
1085
+ // Listen for file selection
1086
+ fileInput.addEventListener('change', function (event) {
1087
+ const file = event.target.files[0]; // Get the selected file
1088
+
1089
+ if (file) {
1090
+ const imageUrl = URL.createObjectURL(file);
1091
+ let img = new Image();
1092
+ img.src = imageUrl;
1093
+ img.onload = () => self.handleImageLoad(img, file, null);
1094
+ }
1095
+ });
1096
+
1097
+ fileInput.click();
1098
+
1099
+ self.node.contextMenu.style.display = 'none';
1100
+ break;
1101
+ case 4:
1102
+ self.splines[self.activeSplineIndex].points.reverse();
1103
+ self.updatePath();
1104
+ break;
1105
+ case 5:
1106
+ self.backgroundImage.visible(false).root.render();
1107
+ self.node.properties.imgData = null;
1108
+ self.node.contextMenu.style.display = 'none';
1109
+ break;
1110
+ case 6: // Add new spline
1111
+ const newSplineIndex = self.splines.length;
1112
+ self.splines.push({
1113
+ points: [
1114
+ // Create default points for the new spline
1115
+ { x: 0, y: self.height },
1116
+ { x: self.width/2, y: self.height/2 },
1117
+ { x: self.width, y: 0 }
1118
+ ],
1119
+ color: self.getSplineColor(newSplineIndex),
1120
+ name: `Spline ${newSplineIndex + 1}`
1121
+ });
1122
+ self.activeSplineIndex = newSplineIndex;
1123
+ self.refreshSplineElements();
1124
+ self.node.contextMenu.style.display = 'none';
1125
+ break;
1126
+ case 7: // Add new single point
1127
+ const newSingleSplineIndex = self.splines.length;
1128
+ self.splines.push({
1129
+ points: [
1130
+ { x: self.lastMousePosition.x, y: self.lastMousePosition.y },
1131
+ ],
1132
+ color: self.getSplineColor(newSingleSplineIndex),
1133
+ name: `Spline ${newSingleSplineIndex + 1}`,
1134
+ isSinglePoint: true
1135
+ });
1136
+ self.activeSplineIndex = newSingleSplineIndex;
1137
+ self.refreshSplineElements();
1138
+ self.node.contextMenu.style.display = 'none';
1139
+ break;
1140
+ case 8: // Delete current spline
1141
+ if (self.splines.length > 1) {
1142
+ self.splines.splice(self.activeSplineIndex, 1);
1143
+ self.activeSplineIndex = Math.min(self.activeSplineIndex, self.splines.length - 1);
1144
+ self.refreshSplineElements();
1145
+ }
1146
+ self.node.contextMenu.style.display = 'none';
1147
+ break;
1148
+ case 9: // Next spline
1149
+ self.activeSplineIndex = (self.activeSplineIndex + 1) % self.splines.length;
1150
+ self.refreshSplineElements();
1151
+ self.node.contextMenu.style.display = 'none';
1152
+ break;
1153
+ }
1154
+ }
1155
+ });
1156
+ }
1157
+
1158
+ samplePoints(svgPathElement, numSamples, samplingMethod, width, splineIndex) {
1159
+ const spline = this.splines[splineIndex];
1160
+
1161
+ // Check if this is a single point spline
1162
+ if (spline && (spline.isSinglePoint || (spline.points && spline.points.length === 1))) {
1163
+ // For a single point, return an array with the same coordinates repeated
1164
+ const point = spline.points[0];
1165
+ return Array(numSamples).fill().map(() => ({ x: point.x, y: point.y }));
1166
+ }
1167
+
1168
+ if (!svgPathElement) {
1169
+ console.warn(`Path element not found for spline index: ${splineIndex}. Available paths: ${this.pathElements.length}`);
1170
+
1171
+
1172
+ const splinePoints = this.splines[splineIndex].points;
1173
+
1174
+ // If we have no points, return an empty array
1175
+ if (!splinePoints || splinePoints.length === 0) {
1176
+ return [];
1177
+ }
1178
+
1179
+ // Create a simple interpolation between control points
1180
+ const result = [];
1181
+ for (let i = 0; i < numSamples; i++) {
1182
+ const t = i / (numSamples - 1);
1183
+ const idx = Math.min(
1184
+ Math.floor(t * (splinePoints.length - 1)),
1185
+ splinePoints.length - 2
1186
+ );
1187
+ const fraction = (t * (splinePoints.length - 1)) - idx;
1188
+
1189
+ const x = splinePoints[idx].x + fraction * (splinePoints[idx + 1].x - splinePoints[idx].x);
1190
+ const y = splinePoints[idx].y + fraction * (splinePoints[idx + 1].y - splinePoints[idx].y);
1191
+
1192
+ result.push({ x, y });
1193
+ }
1194
+ return result;
1195
+ }
1196
+
1197
+ var svgWidth = width; // Fixed width of the SVG element
1198
+ var pathLength = svgPathElement.getTotalLength();
1199
+ var points = [];
1200
+
1201
+ if (samplingMethod === "speed") {
1202
+ // Calculate control point distances along the path
1203
+ const controlPoints = this.splines[splineIndex].points;
1204
+ const pathPositions = [];
1205
+
1206
+ // Find approximate path positions for each control point
1207
+ for (const cp of controlPoints) {
1208
+ let bestDist = Infinity;
1209
+ let bestPos = 0;
1210
+
1211
+ // Sample the path to find closest point to each control point
1212
+ for (let pos = 0; pos <= pathLength; pos += pathLength / 100) {
1213
+ const pt = svgPathElement.getPointAtLength(pos);
1214
+ const dist = Math.sqrt(Math.pow(pt.x - cp.x, 2) + Math.pow(pt.y - cp.y, 2));
1215
+
1216
+ if (dist < bestDist) {
1217
+ bestDist = dist;
1218
+ bestPos = pos;
1219
+ }
1220
+ }
1221
+ pathPositions.push(bestPos);
1222
+ }
1223
+
1224
+ // Sort positions along path
1225
+ pathPositions.sort((a, b) => a - b);
1226
+
1227
+ // Create a smooth speed mapping function with synchronization
1228
+ const createSynchronizedMapping = () => {
1229
+ // Calculate segment lengths and densities
1230
+ const segments = [];
1231
+ let totalLength = pathPositions[pathPositions.length - 1] - pathPositions[0];
1232
+
1233
+ for (let i = 0; i < pathPositions.length - 1; i++) {
1234
+ const segLength = pathPositions[i+1] - pathPositions[i];
1235
+ // Inverse relationship - shorter segments = higher density = slower speed
1236
+ const density = 1 / Math.max(segLength, 0.0001);
1237
+ segments.push({
1238
+ position: pathPositions[i],
1239
+ length: segLength,
1240
+ density: density
1241
+ });
1242
+ }
1243
+
1244
+ // Create mapping function with forced synchronization at endpoints
1245
+ return t => {
1246
+ // Force synchronization at t=0 and t=1
1247
+ if (t === 0) return 0;
1248
+ if (t === 1) return pathLength;
1249
+
1250
+ // For intermediate points, use the speed control
1251
+ // Scale t to fit between first and last control points
1252
+ const firstPos = pathPositions[0];
1253
+ const lastPos = pathPositions[pathPositions.length - 1];
1254
+
1255
+ // Create a density-weighted position mapping
1256
+ let totalWeight = 0;
1257
+ let weights = [];
1258
+
1259
+ for (let i = 0; i < segments.length; i++) {
1260
+ totalWeight += segments[i].density;
1261
+ weights.push(segments[i].density);
1262
+ }
1263
+
1264
+ // Normalize weights
1265
+ const normalizedWeights = weights.map(w => w / totalWeight);
1266
+
1267
+ // Calculate cumulative weights
1268
+ let cumulativeWeight = 0;
1269
+ const cumulativeWeights = normalizedWeights.map(w => {
1270
+ cumulativeWeight += w;
1271
+ return cumulativeWeight;
1272
+ });
1273
+
1274
+ // Find the segment for this t value
1275
+ let segmentIndex = 0;
1276
+ for (let i = 0; i < cumulativeWeights.length; i++) {
1277
+ if (t <= cumulativeWeights[i]) {
1278
+ segmentIndex = i;
1279
+ break;
1280
+ }
1281
+ }
1282
+
1283
+ // Calculate position within segment
1284
+ const segmentStart = segmentIndex > 0 ? cumulativeWeights[segmentIndex - 1] : 0;
1285
+ const segmentEnd = cumulativeWeights[segmentIndex];
1286
+ const segmentT = (t - segmentStart) / (segmentEnd - segmentStart);
1287
+
1288
+ // Map to path position
1289
+ const pathStart = pathPositions[segmentIndex];
1290
+ const pathEnd = pathPositions[segmentIndex + 1];
1291
+ const pos = pathStart + segmentT * (pathEnd - pathStart);
1292
+
1293
+ // Scale to fill entire path
1294
+ return pos;
1295
+ };
1296
+ };
1297
+
1298
+ const mapToPath = createSynchronizedMapping();
1299
+
1300
+ // Sample using the synchronized mapping function
1301
+ for (let i = 0; i < numSamples; i++) {
1302
+ const t = i / (numSamples - 1);
1303
+ const pathPos = mapToPath(t);
1304
+ const point = svgPathElement.getPointAtLength(pathPos);
1305
+ points.push({ x: point.x, y: point.y });
1306
+ }
1307
+
1308
+ return points;
1309
+
1310
+ }
1311
+ else{
1312
+ for (var i = 0; i < numSamples; i++) {
1313
+ if (samplingMethod === "time") {
1314
+ // Calculate the x-coordinate for the current sample based on the SVG's width
1315
+ var x = (svgWidth / (numSamples - 1)) * i;
1316
+ // Find the point on the path that intersects the vertical line at the calculated x-coordinate
1317
+ var point = this.findPointAtX(svgPathElement, x, pathLength);
1318
+ }
1319
+ else if (samplingMethod === "path") {
1320
+ // Calculate the distance along the path for the current sample
1321
+ var distance = (pathLength / (numSamples - 1)) * i;
1322
+ // Get the point at the current distance
1323
+ var point = svgPathElement.getPointAtLength(distance);
1324
+ }
1325
+
1326
+ // Add the point to the array of points
1327
+ points.push({ x: point.x, y: point.y });
1328
+ }
1329
+ return points;
1330
+ }
1331
+ }
1332
+
1333
+ findClosestPoints(points, clickedPoint) {
1334
+ // Calculate distances from clickedPoint to each point in the array
1335
+ let distances = points.map(point => {
1336
+ let dx = clickedPoint.x - point.x;
1337
+ let dy = clickedPoint.y - point.y;
1338
+ return { index: points.indexOf(point), distance: Math.sqrt(dx * dx + dy * dy) };
1339
+ });
1340
+ // Sort distances and get the indices of the two closest points
1341
+ let sortedDistances = distances.sort((a, b) => a.distance - b.distance);
1342
+ let closestPoint1Index = sortedDistances[0].index;
1343
+ let closestPoint2Index = sortedDistances[1].index;
1344
+ // Ensure point1Index is always the smaller index
1345
+ if (closestPoint1Index > closestPoint2Index) {
1346
+ [closestPoint1Index, closestPoint2Index] = [closestPoint2Index, closestPoint1Index];
1347
+ }
1348
+ return { point1Index: closestPoint1Index, point2Index: closestPoint2Index };
1349
+ }
1350
+
1351
+ findPointAtX(svgPathElement, targetX, pathLength) {
1352
+ let low = 0;
1353
+ let high = pathLength;
1354
+ let bestPoint = svgPathElement.getPointAtLength(0);
1355
+
1356
+ while (low <= high) {
1357
+ let mid = low + (high - low) / 2;
1358
+ let point = svgPathElement.getPointAtLength(mid);
1359
+
1360
+ if (Math.abs(point.x - targetX) < 1) {
1361
+ return point; // The point is close enough to the target
1362
+ }
1363
+
1364
+ if (point.x < targetX) {
1365
+ low = mid + 1;
1366
+ } else {
1367
+ high = mid - 1;
1368
+ }
1369
+
1370
+ // Keep track of the closest point found so far
1371
+ if (Math.abs(point.x - targetX) < Math.abs(bestPoint.x - targetX)) {
1372
+ bestPoint = point;
1373
+ }
1374
+ }
1375
+
1376
+ // Return the closest point found
1377
+ return bestPoint;
1378
+ }
1379
+ }
web/red.png ADDED