multimodalart HF Staff commited on
Commit
708238a
·
verified ·
1 Parent(s): 6fa3b0c

Upload 83 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. custom_nodes/.DS_Store +0 -0
  3. custom_nodes/ComfyUI-GGUF/.DS_Store +0 -0
  4. custom_nodes/ComfyUI-GGUF/.github/workflows/registry.yaml +21 -0
  5. custom_nodes/ComfyUI-GGUF/.gitignore +167 -0
  6. custom_nodes/ComfyUI-GGUF/.tracking +17 -0
  7. custom_nodes/ComfyUI-GGUF/LICENSE +201 -0
  8. custom_nodes/ComfyUI-GGUF/README.md +49 -0
  9. custom_nodes/ComfyUI-GGUF/__init__.py +9 -0
  10. custom_nodes/ComfyUI-GGUF/dequant.py +248 -0
  11. custom_nodes/ComfyUI-GGUF/loader.py +353 -0
  12. custom_nodes/ComfyUI-GGUF/nodes.py +305 -0
  13. custom_nodes/ComfyUI-GGUF/ops.py +281 -0
  14. custom_nodes/ComfyUI-GGUF/pyproject.toml +14 -0
  15. custom_nodes/ComfyUI-GGUF/requirements.txt +5 -0
  16. custom_nodes/ComfyUI-GGUF/tools/README.md +93 -0
  17. custom_nodes/ComfyUI-GGUF/tools/convert.py +365 -0
  18. custom_nodes/ComfyUI-GGUF/tools/fix_5d_tensors.py +82 -0
  19. custom_nodes/ComfyUI-GGUF/tools/fix_lines_ending.py +31 -0
  20. custom_nodes/ComfyUI-GGUF/tools/lcpp.patch +451 -0
  21. custom_nodes/ComfyUI-GGUF/tools/read_tensors.py +21 -0
  22. custom_nodes/comfyui-kjnodes/.DS_Store +0 -0
  23. custom_nodes/comfyui-kjnodes/.github/FUNDING.yml +2 -0
  24. custom_nodes/comfyui-kjnodes/.github/workflows/publish.yml +25 -0
  25. custom_nodes/comfyui-kjnodes/.gitignore +11 -0
  26. custom_nodes/comfyui-kjnodes/.tracking +49 -0
  27. custom_nodes/comfyui-kjnodes/LICENSE +674 -0
  28. custom_nodes/comfyui-kjnodes/README.md +65 -0
  29. custom_nodes/comfyui-kjnodes/__init__.py +245 -0
  30. custom_nodes/comfyui-kjnodes/custom_dimensions_example.json +22 -0
  31. custom_nodes/comfyui-kjnodes/docs/images/2024-04-03_20_49_29-ComfyUI.png +3 -0
  32. custom_nodes/comfyui-kjnodes/docs/images/319121566-05f66385-7568-4b1f-8bbc-11053660b02f.png +0 -0
  33. custom_nodes/comfyui-kjnodes/docs/images/319121636-706b5081-9120-4a29-bd76-901691ada688.png +0 -0
  34. custom_nodes/comfyui-kjnodes/example_workflows/leapfusion_hunyuuanvideo_i2v_native_testing.json +1188 -0
  35. custom_nodes/comfyui-kjnodes/fonts/FreeMono.ttf +3 -0
  36. custom_nodes/comfyui-kjnodes/fonts/FreeMonoBoldOblique.otf +3 -0
  37. custom_nodes/comfyui-kjnodes/fonts/TTNorms-Black.otf +3 -0
  38. custom_nodes/comfyui-kjnodes/intrinsic_loras/intrinsic_lora_sd15_albedo.safetensors +3 -0
  39. custom_nodes/comfyui-kjnodes/intrinsic_loras/intrinsic_lora_sd15_depth.safetensors +3 -0
  40. custom_nodes/comfyui-kjnodes/intrinsic_loras/intrinsic_lora_sd15_normal.safetensors +3 -0
  41. custom_nodes/comfyui-kjnodes/intrinsic_loras/intrinsic_lora_sd15_shading.safetensors +3 -0
  42. custom_nodes/comfyui-kjnodes/intrinsic_loras/intrinsic_loras.txt +4 -0
  43. custom_nodes/comfyui-kjnodes/kjweb_async/marked.min.js +6 -0
  44. custom_nodes/comfyui-kjnodes/kjweb_async/protovis.min.js +0 -0
  45. custom_nodes/comfyui-kjnodes/kjweb_async/purify.min.js +3 -0
  46. custom_nodes/comfyui-kjnodes/kjweb_async/svg-path-properties.min.js +2 -0
  47. custom_nodes/comfyui-kjnodes/nodes/__pycache__/audioscheduler_nodes.cpython-310.pyc +0 -0
  48. custom_nodes/comfyui-kjnodes/nodes/__pycache__/batchcrop_nodes.cpython-310.pyc +0 -0
  49. custom_nodes/comfyui-kjnodes/nodes/__pycache__/curve_nodes.cpython-310.pyc +0 -0
  50. custom_nodes/comfyui-kjnodes/nodes/__pycache__/image_nodes.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -35,3 +35,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  input/tmpip5bak5z.png filter=lfs diff=lfs merge=lfs -text
37
  input/tmpvhslhwc_.png filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
  input/tmpip5bak5z.png filter=lfs diff=lfs merge=lfs -text
37
  input/tmpvhslhwc_.png filter=lfs diff=lfs merge=lfs -text
38
+ custom_nodes/comfyui-kjnodes/docs/images/2024-04-03_20_49_29-ComfyUI.png filter=lfs diff=lfs merge=lfs -text
39
+ custom_nodes/comfyui-kjnodes/fonts/FreeMono.ttf filter=lfs diff=lfs merge=lfs -text
40
+ custom_nodes/comfyui-kjnodes/fonts/FreeMonoBoldOblique.otf filter=lfs diff=lfs merge=lfs -text
41
+ custom_nodes/comfyui-kjnodes/fonts/TTNorms-Black.otf filter=lfs diff=lfs merge=lfs -text
custom_nodes/.DS_Store ADDED
Binary file (6.15 kB). View file
 
custom_nodes/ComfyUI-GGUF/.DS_Store ADDED
Binary file (6.15 kB). View file
 
custom_nodes/ComfyUI-GGUF/.github/workflows/registry.yaml ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: ComfyUI Registry publish
2
+ on:
3
+ workflow_dispatch:
4
+ push:
5
+ branches:
6
+ - stable
7
+ paths:
8
+ - "pyproject.toml"
9
+
10
+ jobs:
11
+ publish-node:
12
+ name: ComfyUI Registry publish
13
+ runs-on: ubuntu-latest
14
+ if: github.event.repository.fork == false
15
+ steps:
16
+ - name: Check out code
17
+ uses: actions/checkout@v4
18
+ - name: Publish Custom Node
19
+ uses: Comfy-Org/publish-node-action@main
20
+ with:
21
+ personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
custom_nodes/ComfyUI-GGUF/.gitignore ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.bin
2
+ *.gguf
3
+ *.safetensors
4
+ tools/llama.cpp*
5
+
6
+ # Byte-compiled / optimized / DLL files
7
+ __pycache__/
8
+ *.py[cod]
9
+ *$py.class
10
+
11
+ # C extensions
12
+ *.so
13
+
14
+ # Distribution / packaging
15
+ .Python
16
+ build/
17
+ develop-eggs/
18
+ dist/
19
+ downloads/
20
+ eggs/
21
+ .eggs/
22
+ lib/
23
+ lib64/
24
+ parts/
25
+ sdist/
26
+ var/
27
+ wheels/
28
+ share/python-wheels/
29
+ *.egg-info/
30
+ .installed.cfg
31
+ *.egg
32
+ MANIFEST
33
+
34
+ # PyInstaller
35
+ # Usually these files are written by a python script from a template
36
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
37
+ *.manifest
38
+ *.spec
39
+
40
+ # Installer logs
41
+ pip-log.txt
42
+ pip-delete-this-directory.txt
43
+
44
+ # Unit test / coverage reports
45
+ htmlcov/
46
+ .tox/
47
+ .nox/
48
+ .coverage
49
+ .coverage.*
50
+ .cache
51
+ nosetests.xml
52
+ coverage.xml
53
+ *.cover
54
+ *.py,cover
55
+ .hypothesis/
56
+ .pytest_cache/
57
+ cover/
58
+
59
+ # Translations
60
+ *.mo
61
+ *.pot
62
+
63
+ # Django stuff:
64
+ *.log
65
+ local_settings.py
66
+ db.sqlite3
67
+ db.sqlite3-journal
68
+
69
+ # Flask stuff:
70
+ instance/
71
+ .webassets-cache
72
+
73
+ # Scrapy stuff:
74
+ .scrapy
75
+
76
+ # Sphinx documentation
77
+ docs/_build/
78
+
79
+ # PyBuilder
80
+ .pybuilder/
81
+ target/
82
+
83
+ # Jupyter Notebook
84
+ .ipynb_checkpoints
85
+
86
+ # IPython
87
+ profile_default/
88
+ ipython_config.py
89
+
90
+ # pyenv
91
+ # For a library or package, you might want to ignore these files since the code is
92
+ # intended to run in multiple environments; otherwise, check them in:
93
+ # .python-version
94
+
95
+ # pipenv
96
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
97
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
98
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
99
+ # install all needed dependencies.
100
+ #Pipfile.lock
101
+
102
+ # poetry
103
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
104
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
105
+ # commonly ignored for libraries.
106
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
107
+ #poetry.lock
108
+
109
+ # pdm
110
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
111
+ #pdm.lock
112
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
113
+ # in version control.
114
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
115
+ .pdm.toml
116
+ .pdm-python
117
+ .pdm-build/
118
+
119
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
120
+ __pypackages__/
121
+
122
+ # Celery stuff
123
+ celerybeat-schedule
124
+ celerybeat.pid
125
+
126
+ # SageMath parsed files
127
+ *.sage.py
128
+
129
+ # Environments
130
+ .env
131
+ .venv
132
+ env/
133
+ venv/
134
+ ENV/
135
+ env.bak/
136
+ venv.bak/
137
+
138
+ # Spyder project settings
139
+ .spyderproject
140
+ .spyproject
141
+
142
+ # Rope project settings
143
+ .ropeproject
144
+
145
+ # mkdocs documentation
146
+ /site
147
+
148
+ # mypy
149
+ .mypy_cache/
150
+ .dmypy.json
151
+ dmypy.json
152
+
153
+ # Pyre type checker
154
+ .pyre/
155
+
156
+ # pytype static type analyzer
157
+ .pytype/
158
+
159
+ # Cython debug symbols
160
+ cython_debug/
161
+
162
+ # PyCharm
163
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
164
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
165
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
166
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
167
+ #.idea/
custom_nodes/ComfyUI-GGUF/.tracking ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .github/workflows/registry.yaml
2
+ .gitignore
3
+ LICENSE
4
+ README.md
5
+ __init__.py
6
+ dequant.py
7
+ loader.py
8
+ nodes.py
9
+ ops.py
10
+ pyproject.toml
11
+ requirements.txt
12
+ tools/README.md
13
+ tools/convert.py
14
+ tools/fix_5d_tensors.py
15
+ tools/fix_lines_ending.py
16
+ tools/lcpp.patch
17
+ tools/read_tensors.py
custom_nodes/ComfyUI-GGUF/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
custom_nodes/ComfyUI-GGUF/README.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ComfyUI-GGUF
2
+ GGUF Quantization support for native ComfyUI models
3
+
4
+ This is currently very much WIP. These custom nodes provide support for model files stored in the GGUF format popularized by [llama.cpp](https://github.com/ggerganov/llama.cpp).
5
+
6
+ While quantization wasn't feasible for regular UNET models (conv2d), transformer/DiT models such as flux seem less affected by quantization. This allows running it in much lower bits per weight variable bitrate quants on low-end GPUs. For further VRAM savings, a node to load a quantized version of the T5 text encoder is also included.
7
+
8
+ ![Comfy_Flux1_dev_Q4_0_GGUF_1024](https://github.com/user-attachments/assets/70d16d97-c522-4ef4-9435-633f128644c8)
9
+
10
+ Note: The "Force/Set CLIP Device" is **NOT** part of this node pack. Do not install it if you only have one GPU. Do not set it to cuda:0 then complain about OOM errors if you do not undestand what it is for. There is not need to copy the workflow above, just use your own workflow and replace the stock "Load Diffusion Model" with the "Unet Loader (GGUF)" node.
11
+
12
+ ## Installation
13
+
14
+ > [!IMPORTANT]
15
+ > Make sure your ComfyUI is on a recent-enough version to support custom ops when loading the UNET-only.
16
+
17
+ To install the custom node normally, git clone this repository into your custom nodes folder (`ComfyUI/custom_nodes`) and install the only dependency for inference (`pip install --upgrade gguf`)
18
+
19
+ ```
20
+ git clone https://github.com/city96/ComfyUI-GGUF
21
+ ```
22
+
23
+ To install the custom node on a standalone ComfyUI release, open a CMD inside the "ComfyUI_windows_portable" folder (where your `run_nvidia_gpu.bat` file is) and use the following commands:
24
+
25
+ ```
26
+ git clone https://github.com/city96/ComfyUI-GGUF ComfyUI/custom_nodes/ComfyUI-GGUF
27
+ .\python_embeded\python.exe -s -m pip install -r .\ComfyUI\custom_nodes\ComfyUI-GGUF\requirements.txt
28
+ ```
29
+
30
+ On MacOS sequoia, torch 2.4.1 seems to be required, as 2.6.X nightly versions cause a "M1 buffer is not large enough" error. See [this issue](https://github.com/city96/ComfyUI-GGUF/issues/107) for more information/workarounds.
31
+
32
+ ## Usage
33
+
34
+ Simply use the GGUF Unet loader found under the `bootleg` category. Place the .gguf model files in your `ComfyUI/models/unet` folder.
35
+
36
+ LoRA loading is experimental but it should work with just the built-in LoRA loader node(s).
37
+
38
+ Pre-quantized models:
39
+
40
+ - [flux1-dev GGUF](https://huggingface.co/city96/FLUX.1-dev-gguf)
41
+ - [flux1-schnell GGUF](https://huggingface.co/city96/FLUX.1-schnell-gguf)
42
+ - [stable-diffusion-3.5-large GGUF](https://huggingface.co/city96/stable-diffusion-3.5-large-gguf)
43
+ - [stable-diffusion-3.5-large-turbo GGUF](https://huggingface.co/city96/stable-diffusion-3.5-large-turbo-gguf)
44
+
45
+ Initial support for quantizing T5 has also been added recently, these can be used using the various `*CLIPLoader (gguf)` nodes which can be used inplace of the regular ones. For the CLIP model, use whatever model you were using before for CLIP. The loader can handle both types of files - `gguf` and regular `safetensors`/`bin`.
46
+
47
+ - [t5_v1.1-xxl GGUF](https://huggingface.co/city96/t5-v1_1-xxl-encoder-gguf)
48
+
49
+ See the instructions in the [tools](https://github.com/city96/ComfyUI-GGUF/tree/main/tools) folder for how to create your own quants.
custom_nodes/ComfyUI-GGUF/__init__.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # only import if running as a custom node
2
+ try:
3
+ import comfy.utils
4
+ except ImportError:
5
+ pass
6
+ else:
7
+ from .nodes import NODE_CLASS_MAPPINGS
8
+ NODE_DISPLAY_NAME_MAPPINGS = {k:v.TITLE for k,v in NODE_CLASS_MAPPINGS.items()}
9
+ __all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
custom_nodes/ComfyUI-GGUF/dequant.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
2
+ import gguf
3
+ import torch
4
+ from tqdm import tqdm
5
+
6
+
7
+ TORCH_COMPATIBLE_QTYPES = (None, gguf.GGMLQuantizationType.F32, gguf.GGMLQuantizationType.F16)
8
+
9
+ def is_torch_compatible(tensor):
10
+ return tensor is None or getattr(tensor, "tensor_type", None) in TORCH_COMPATIBLE_QTYPES
11
+
12
+ def is_quantized(tensor):
13
+ return not is_torch_compatible(tensor)
14
+
15
+ def dequantize_tensor(tensor, dtype=None, dequant_dtype=None):
16
+ qtype = getattr(tensor, "tensor_type", None)
17
+ oshape = getattr(tensor, "tensor_shape", tensor.shape)
18
+
19
+ if qtype in TORCH_COMPATIBLE_QTYPES:
20
+ return tensor.to(dtype)
21
+ elif qtype in dequantize_functions:
22
+ dequant_dtype = dtype if dequant_dtype == "target" else dequant_dtype
23
+ return dequantize(tensor.data, qtype, oshape, dtype=dequant_dtype).to(dtype)
24
+ else:
25
+ # this is incredibly slow
26
+ tqdm.write(f"Falling back to numpy dequant for qtype: {qtype}")
27
+ new = gguf.quants.dequantize(tensor.cpu().numpy(), qtype)
28
+ return torch.from_numpy(new).to(tensor.device, dtype=dtype)
29
+
30
+ def dequantize(data, qtype, oshape, dtype=None):
31
+ """
32
+ Dequantize tensor back to usable shape/dtype
33
+ """
34
+ block_size, type_size = gguf.GGML_QUANT_SIZES[qtype]
35
+ dequantize_blocks = dequantize_functions[qtype]
36
+
37
+ rows = data.reshape(
38
+ (-1, data.shape[-1])
39
+ ).view(torch.uint8)
40
+
41
+ n_blocks = rows.numel() // type_size
42
+ blocks = rows.reshape((n_blocks, type_size))
43
+ blocks = dequantize_blocks(blocks, block_size, type_size, dtype)
44
+ return blocks.reshape(oshape)
45
+
46
+ def to_uint32(x):
47
+ # no uint32 :(
48
+ x = x.view(torch.uint8).to(torch.int32)
49
+ return (x[:, 0] | x[:, 1] << 8 | x[:, 2] << 16 | x[:, 3] << 24).unsqueeze(1)
50
+
51
+ def split_block_dims(blocks, *args):
52
+ n_max = blocks.shape[1]
53
+ dims = list(args) + [n_max - sum(args)]
54
+ return torch.split(blocks, dims, dim=1)
55
+
56
+ # Full weights #
57
+ def dequantize_blocks_BF16(blocks, block_size, type_size, dtype=None):
58
+ return (blocks.view(torch.int16).to(torch.int32) << 16).view(torch.float32)
59
+
60
+ # Legacy Quants #
61
+ def dequantize_blocks_Q8_0(blocks, block_size, type_size, dtype=None):
62
+ d, x = split_block_dims(blocks, 2)
63
+ d = d.view(torch.float16).to(dtype)
64
+ x = x.view(torch.int8)
65
+ return (d * x)
66
+
67
+ def dequantize_blocks_Q5_1(blocks, block_size, type_size, dtype=None):
68
+ n_blocks = blocks.shape[0]
69
+
70
+ d, m, qh, qs = split_block_dims(blocks, 2, 2, 4)
71
+ d = d.view(torch.float16).to(dtype)
72
+ m = m.view(torch.float16).to(dtype)
73
+ qh = to_uint32(qh)
74
+
75
+ qh = qh.reshape((n_blocks, 1)) >> torch.arange(32, device=d.device, dtype=torch.int32).reshape(1, 32)
76
+ ql = qs.reshape((n_blocks, -1, 1, block_size // 2)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape(1, 1, 2, 1)
77
+ qh = (qh & 1).to(torch.uint8)
78
+ ql = (ql & 0x0F).reshape((n_blocks, -1))
79
+
80
+ qs = (ql | (qh << 4))
81
+ return (d * qs) + m
82
+
83
+ def dequantize_blocks_Q5_0(blocks, block_size, type_size, dtype=None):
84
+ n_blocks = blocks.shape[0]
85
+
86
+ d, qh, qs = split_block_dims(blocks, 2, 4)
87
+ d = d.view(torch.float16).to(dtype)
88
+ qh = to_uint32(qh)
89
+
90
+ qh = qh.reshape(n_blocks, 1) >> torch.arange(32, device=d.device, dtype=torch.int32).reshape(1, 32)
91
+ ql = qs.reshape(n_blocks, -1, 1, block_size // 2) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape(1, 1, 2, 1)
92
+
93
+ qh = (qh & 1).to(torch.uint8)
94
+ ql = (ql & 0x0F).reshape(n_blocks, -1)
95
+
96
+ qs = (ql | (qh << 4)).to(torch.int8) - 16
97
+ return (d * qs)
98
+
99
+ def dequantize_blocks_Q4_1(blocks, block_size, type_size, dtype=None):
100
+ n_blocks = blocks.shape[0]
101
+
102
+ d, m, qs = split_block_dims(blocks, 2, 2)
103
+ d = d.view(torch.float16).to(dtype)
104
+ m = m.view(torch.float16).to(dtype)
105
+
106
+ qs = qs.reshape((n_blocks, -1, 1, block_size // 2)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape(1, 1, 2, 1)
107
+ qs = (qs & 0x0F).reshape(n_blocks, -1)
108
+
109
+ return (d * qs) + m
110
+
111
+ def dequantize_blocks_Q4_0(blocks, block_size, type_size, dtype=None):
112
+ n_blocks = blocks.shape[0]
113
+
114
+ d, qs = split_block_dims(blocks, 2)
115
+ d = d.view(torch.float16).to(dtype)
116
+
117
+ qs = qs.reshape((n_blocks, -1, 1, block_size // 2)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape((1, 1, 2, 1))
118
+ qs = (qs & 0x0F).reshape((n_blocks, -1)).to(torch.int8) - 8
119
+ return (d * qs)
120
+
121
+ # K Quants #
122
+ QK_K = 256
123
+ K_SCALE_SIZE = 12
124
+
125
+ def get_scale_min(scales):
126
+ n_blocks = scales.shape[0]
127
+ scales = scales.view(torch.uint8)
128
+ scales = scales.reshape((n_blocks, 3, 4))
129
+
130
+ d, m, m_d = torch.split(scales, scales.shape[-2] // 3, dim=-2)
131
+
132
+ sc = torch.cat([d & 0x3F, (m_d & 0x0F) | ((d >> 2) & 0x30)], dim=-1)
133
+ min = torch.cat([m & 0x3F, (m_d >> 4) | ((m >> 2) & 0x30)], dim=-1)
134
+
135
+ return (sc.reshape((n_blocks, 8)), min.reshape((n_blocks, 8)))
136
+
137
+ def dequantize_blocks_Q6_K(blocks, block_size, type_size, dtype=None):
138
+ n_blocks = blocks.shape[0]
139
+
140
+ ql, qh, scales, d, = split_block_dims(blocks, QK_K // 2, QK_K // 4, QK_K // 16)
141
+
142
+ scales = scales.view(torch.int8).to(dtype)
143
+ d = d.view(torch.float16).to(dtype)
144
+ d = (d * scales).reshape((n_blocks, QK_K // 16, 1))
145
+
146
+ ql = ql.reshape((n_blocks, -1, 1, 64)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape((1, 1, 2, 1))
147
+ ql = (ql & 0x0F).reshape((n_blocks, -1, 32))
148
+ qh = qh.reshape((n_blocks, -1, 1, 32)) >> torch.tensor([0, 2, 4, 6], device=d.device, dtype=torch.uint8).reshape((1, 1, 4, 1))
149
+ qh = (qh & 0x03).reshape((n_blocks, -1, 32))
150
+ q = (ql | (qh << 4)).to(torch.int8) - 32
151
+ q = q.reshape((n_blocks, QK_K // 16, -1))
152
+
153
+ return (d * q).reshape((n_blocks, QK_K))
154
+
155
+ def dequantize_blocks_Q5_K(blocks, block_size, type_size, dtype=None):
156
+ n_blocks = blocks.shape[0]
157
+
158
+ d, dmin, scales, qh, qs = split_block_dims(blocks, 2, 2, K_SCALE_SIZE, QK_K // 8)
159
+
160
+ d = d.view(torch.float16).to(dtype)
161
+ dmin = dmin.view(torch.float16).to(dtype)
162
+
163
+ sc, m = get_scale_min(scales)
164
+
165
+ d = (d * sc).reshape((n_blocks, -1, 1))
166
+ dm = (dmin * m).reshape((n_blocks, -1, 1))
167
+
168
+ ql = qs.reshape((n_blocks, -1, 1, 32)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape((1, 1, 2, 1))
169
+ qh = qh.reshape((n_blocks, -1, 1, 32)) >> torch.tensor([i for i in range(8)], device=d.device, dtype=torch.uint8).reshape((1, 1, 8, 1))
170
+ ql = (ql & 0x0F).reshape((n_blocks, -1, 32))
171
+ qh = (qh & 0x01).reshape((n_blocks, -1, 32))
172
+ q = (ql | (qh << 4))
173
+
174
+ return (d * q - dm).reshape((n_blocks, QK_K))
175
+
176
+ def dequantize_blocks_Q4_K(blocks, block_size, type_size, dtype=None):
177
+ n_blocks = blocks.shape[0]
178
+
179
+ d, dmin, scales, qs = split_block_dims(blocks, 2, 2, K_SCALE_SIZE)
180
+ d = d.view(torch.float16).to(dtype)
181
+ dmin = dmin.view(torch.float16).to(dtype)
182
+
183
+ sc, m = get_scale_min(scales)
184
+
185
+ d = (d * sc).reshape((n_blocks, -1, 1))
186
+ dm = (dmin * m).reshape((n_blocks, -1, 1))
187
+
188
+ qs = qs.reshape((n_blocks, -1, 1, 32)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape((1, 1, 2, 1))
189
+ qs = (qs & 0x0F).reshape((n_blocks, -1, 32))
190
+
191
+ return (d * qs - dm).reshape((n_blocks, QK_K))
192
+
193
+ def dequantize_blocks_Q3_K(blocks, block_size, type_size, dtype=None):
194
+ n_blocks = blocks.shape[0]
195
+
196
+ hmask, qs, scales, d = split_block_dims(blocks, QK_K // 8, QK_K // 4, 12)
197
+ d = d.view(torch.float16).to(dtype)
198
+
199
+ lscales, hscales = scales[:, :8], scales[:, 8:]
200
+ lscales = lscales.reshape((n_blocks, 1, 8)) >> torch.tensor([0, 4], device=d.device, dtype=torch.uint8).reshape((1, 2, 1))
201
+ lscales = lscales.reshape((n_blocks, 16))
202
+ hscales = hscales.reshape((n_blocks, 1, 4)) >> torch.tensor([0, 2, 4, 6], device=d.device, dtype=torch.uint8).reshape((1, 4, 1))
203
+ hscales = hscales.reshape((n_blocks, 16))
204
+ scales = (lscales & 0x0F) | ((hscales & 0x03) << 4)
205
+ scales = (scales.to(torch.int8) - 32)
206
+
207
+ dl = (d * scales).reshape((n_blocks, 16, 1))
208
+
209
+ ql = qs.reshape((n_blocks, -1, 1, 32)) >> torch.tensor([0, 2, 4, 6], device=d.device, dtype=torch.uint8).reshape((1, 1, 4, 1))
210
+ qh = hmask.reshape(n_blocks, -1, 1, 32) >> torch.tensor([i for i in range(8)], device=d.device, dtype=torch.uint8).reshape((1, 1, 8, 1))
211
+ ql = ql.reshape((n_blocks, 16, QK_K // 16)) & 3
212
+ qh = (qh.reshape((n_blocks, 16, QK_K // 16)) & 1) ^ 1
213
+ q = (ql.to(torch.int8) - (qh << 2).to(torch.int8))
214
+
215
+ return (dl * q).reshape((n_blocks, QK_K))
216
+
217
+ def dequantize_blocks_Q2_K(blocks, block_size, type_size, dtype=None):
218
+ n_blocks = blocks.shape[0]
219
+
220
+ scales, qs, d, dmin = split_block_dims(blocks, QK_K // 16, QK_K // 4, 2)
221
+ d = d.view(torch.float16).to(dtype)
222
+ dmin = dmin.view(torch.float16).to(dtype)
223
+
224
+ # (n_blocks, 16, 1)
225
+ dl = (d * (scales & 0xF)).reshape((n_blocks, QK_K // 16, 1))
226
+ ml = (dmin * (scales >> 4)).reshape((n_blocks, QK_K // 16, 1))
227
+
228
+ shift = torch.tensor([0, 2, 4, 6], device=d.device, dtype=torch.uint8).reshape((1, 1, 4, 1))
229
+
230
+ qs = (qs.reshape((n_blocks, -1, 1, 32)) >> shift) & 3
231
+ qs = qs.reshape((n_blocks, QK_K // 16, 16))
232
+ qs = dl * qs - ml
233
+
234
+ return qs.reshape((n_blocks, -1))
235
+
236
+ dequantize_functions = {
237
+ gguf.GGMLQuantizationType.BF16: dequantize_blocks_BF16,
238
+ gguf.GGMLQuantizationType.Q8_0: dequantize_blocks_Q8_0,
239
+ gguf.GGMLQuantizationType.Q5_1: dequantize_blocks_Q5_1,
240
+ gguf.GGMLQuantizationType.Q5_0: dequantize_blocks_Q5_0,
241
+ gguf.GGMLQuantizationType.Q4_1: dequantize_blocks_Q4_1,
242
+ gguf.GGMLQuantizationType.Q4_0: dequantize_blocks_Q4_0,
243
+ gguf.GGMLQuantizationType.Q6_K: dequantize_blocks_Q6_K,
244
+ gguf.GGMLQuantizationType.Q5_K: dequantize_blocks_Q5_K,
245
+ gguf.GGMLQuantizationType.Q4_K: dequantize_blocks_Q4_K,
246
+ gguf.GGMLQuantizationType.Q3_K: dequantize_blocks_Q3_K,
247
+ gguf.GGMLQuantizationType.Q2_K: dequantize_blocks_Q2_K,
248
+ }
custom_nodes/ComfyUI-GGUF/loader.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
2
+ import warnings
3
+ import logging
4
+ import torch
5
+ import gguf
6
+ import re
7
+ import os
8
+
9
+ from .ops import GGMLTensor
10
+ from .dequant import is_quantized, dequantize_tensor
11
+
12
+ IMG_ARCH_LIST = {"flux", "sd1", "sdxl", "sd3", "aura", "hidream", "cosmos", "ltxv", "hyvid", "wan", "lumina2", "qwen_image"}
13
+ TXT_ARCH_LIST = {"t5", "t5encoder", "llama", "qwen2vl"}
14
+ VIS_TYPE_LIST = {"clip-vision"}
15
+
16
+ def get_orig_shape(reader, tensor_name):
17
+ field_key = f"comfy.gguf.orig_shape.{tensor_name}"
18
+ field = reader.get_field(field_key)
19
+ if field is None:
20
+ return None
21
+ # Has original shape metadata, so we try to decode it.
22
+ if len(field.types) != 2 or field.types[0] != gguf.GGUFValueType.ARRAY or field.types[1] != gguf.GGUFValueType.INT32:
23
+ raise TypeError(f"Bad original shape metadata for {field_key}: Expected ARRAY of INT32, got {field.types}")
24
+ return torch.Size(tuple(int(field.parts[part_idx][0]) for part_idx in field.data))
25
+
26
+ def get_field(reader, field_name, field_type):
27
+ field = reader.get_field(field_name)
28
+ if field is None:
29
+ return None
30
+ elif field_type == str:
31
+ # extra check here as this is used for checking arch string
32
+ if len(field.types) != 1 or field.types[0] != gguf.GGUFValueType.STRING:
33
+ raise TypeError(f"Bad type for GGUF {field_name} key: expected string, got {field.types!r}")
34
+ return str(field.parts[field.data[-1]], encoding="utf-8")
35
+ elif field_type in [int, float, bool]:
36
+ return field_type(field.parts[field.data[-1]])
37
+ else:
38
+ raise TypeError(f"Unknown field type {field_type}")
39
+
40
+ def get_list_field(reader, field_name, field_type):
41
+ field = reader.get_field(field_name)
42
+ if field is None:
43
+ return None
44
+ elif field_type == str:
45
+ return tuple(str(field.parts[part_idx], encoding="utf-8") for part_idx in field.data)
46
+ elif field_type in [int, float, bool]:
47
+ return tuple(field_type(field.parts[part_idx][0]) for part_idx in field.data)
48
+ else:
49
+ raise TypeError(f"Unknown field type {field_type}")
50
+
51
+ def gguf_sd_loader(path, handle_prefix="model.diffusion_model.", return_arch=False, is_text_model=False):
52
+ """
53
+ Read state dict as fake tensors
54
+ """
55
+ reader = gguf.GGUFReader(path)
56
+
57
+ # filter and strip prefix
58
+ has_prefix = False
59
+ if handle_prefix is not None:
60
+ prefix_len = len(handle_prefix)
61
+ tensor_names = set(tensor.name for tensor in reader.tensors)
62
+ has_prefix = any(s.startswith(handle_prefix) for s in tensor_names)
63
+
64
+ tensors = []
65
+ for tensor in reader.tensors:
66
+ sd_key = tensor_name = tensor.name
67
+ if has_prefix:
68
+ if not tensor_name.startswith(handle_prefix):
69
+ continue
70
+ sd_key = tensor_name[prefix_len:]
71
+ tensors.append((sd_key, tensor))
72
+
73
+ # detect and verify architecture
74
+ compat = None
75
+ arch_str = get_field(reader, "general.architecture", str)
76
+ type_str = get_field(reader, "general.type", str)
77
+ if arch_str in [None, "pig"]:
78
+ if is_text_model:
79
+ raise ValueError(f"This text model is incompatible with llama.cpp!\nConsider using the safetensors version\n({path})")
80
+ compat = "sd.cpp" if arch_str is None else arch_str
81
+ # import here to avoid changes to convert.py breaking regular models
82
+ from .tools.convert import detect_arch
83
+ try:
84
+ arch_str = detect_arch(set(val[0] for val in tensors)).arch
85
+ except Exception as e:
86
+ raise ValueError(f"This model is not currently supported - ({e})")
87
+ elif arch_str not in TXT_ARCH_LIST and is_text_model:
88
+ if type_str not in VIS_TYPE_LIST:
89
+ raise ValueError(f"Unexpected text model architecture type in GGUF file: {arch_str!r}")
90
+ elif arch_str not in IMG_ARCH_LIST and not is_text_model:
91
+ raise ValueError(f"Unexpected architecture type in GGUF file: {arch_str!r}")
92
+
93
+ if compat:
94
+ logging.warning(f"Warning: This gguf model file is loaded in compatibility mode '{compat}' [arch:{arch_str}]")
95
+
96
+ # main loading loop
97
+ state_dict = {}
98
+ qtype_dict = {}
99
+ for sd_key, tensor in tensors:
100
+ tensor_name = tensor.name
101
+ # torch_tensor = torch.from_numpy(tensor.data) # mmap
102
+
103
+ # NOTE: line above replaced with this block to avoid persistent numpy warning about mmap
104
+ with warnings.catch_warnings():
105
+ warnings.filterwarnings("ignore", message="The given NumPy array is not writable")
106
+ torch_tensor = torch.from_numpy(tensor.data) # mmap
107
+
108
+ shape = get_orig_shape(reader, tensor_name)
109
+ if shape is None:
110
+ shape = torch.Size(tuple(int(v) for v in reversed(tensor.shape)))
111
+ # Workaround for stable-diffusion.cpp SDXL detection.
112
+ if compat == "sd.cpp" and arch_str == "sdxl":
113
+ if any([tensor_name.endswith(x) for x in (".proj_in.weight", ".proj_out.weight")]):
114
+ while len(shape) > 2 and shape[-1] == 1:
115
+ shape = shape[:-1]
116
+
117
+ # add to state dict
118
+ if tensor.tensor_type in {gguf.GGMLQuantizationType.F32, gguf.GGMLQuantizationType.F16}:
119
+ torch_tensor = torch_tensor.view(*shape)
120
+ state_dict[sd_key] = GGMLTensor(torch_tensor, tensor_type=tensor.tensor_type, tensor_shape=shape)
121
+
122
+ # keep track of loaded tensor types
123
+ tensor_type_str = getattr(tensor.tensor_type, "name", repr(tensor.tensor_type))
124
+ qtype_dict[tensor_type_str] = qtype_dict.get(tensor_type_str, 0) + 1
125
+
126
+ # print loaded tensor type counts
127
+ logging.info("gguf qtypes: " + ", ".join(f"{k} ({v})" for k, v in qtype_dict.items()))
128
+
129
+ # mark largest tensor for vram estimation
130
+ qsd = {k:v for k,v in state_dict.items() if is_quantized(v)}
131
+ if len(qsd) > 0:
132
+ max_key = max(qsd.keys(), key=lambda k: qsd[k].numel())
133
+ state_dict[max_key].is_largest_weight = True
134
+
135
+ if return_arch:
136
+ return (state_dict, arch_str)
137
+ return state_dict
138
+
139
+ # for remapping llama.cpp -> original key names
140
+ T5_SD_MAP = {
141
+ "enc.": "encoder.",
142
+ ".blk.": ".block.",
143
+ "token_embd": "shared",
144
+ "output_norm": "final_layer_norm",
145
+ "attn_q": "layer.0.SelfAttention.q",
146
+ "attn_k": "layer.0.SelfAttention.k",
147
+ "attn_v": "layer.0.SelfAttention.v",
148
+ "attn_o": "layer.0.SelfAttention.o",
149
+ "attn_norm": "layer.0.layer_norm",
150
+ "attn_rel_b": "layer.0.SelfAttention.relative_attention_bias",
151
+ "ffn_up": "layer.1.DenseReluDense.wi_1",
152
+ "ffn_down": "layer.1.DenseReluDense.wo",
153
+ "ffn_gate": "layer.1.DenseReluDense.wi_0",
154
+ "ffn_norm": "layer.1.layer_norm",
155
+ }
156
+
157
+ LLAMA_SD_MAP = {
158
+ "blk.": "model.layers.",
159
+ "attn_norm": "input_layernorm",
160
+ "attn_q": "self_attn.q_proj",
161
+ "attn_k": "self_attn.k_proj",
162
+ "attn_v": "self_attn.v_proj",
163
+ "attn_output": "self_attn.o_proj",
164
+ "ffn_up": "mlp.up_proj",
165
+ "ffn_down": "mlp.down_proj",
166
+ "ffn_gate": "mlp.gate_proj",
167
+ "ffn_norm": "post_attention_layernorm",
168
+ "token_embd": "model.embed_tokens",
169
+ "output_norm": "model.norm",
170
+ "output.weight": "lm_head.weight",
171
+ }
172
+
173
+ CLIP_VISION_SD_MAP = {
174
+ "mm.": "visual.merger.mlp.",
175
+ "v.post_ln.": "visual.merger.ln_q.",
176
+ "v.patch_embd": "visual.patch_embed.proj",
177
+ "v.blk.": "visual.blocks.",
178
+ "ffn_up": "mlp.up_proj",
179
+ "ffn_down": "mlp.down_proj",
180
+ "ffn_gate": "mlp.gate_proj",
181
+ "attn_out.": "attn.proj.",
182
+ "ln1.": "norm1.",
183
+ "ln2.": "norm2.",
184
+ }
185
+
186
+ def sd_map_replace(raw_sd, key_map):
187
+ sd = {}
188
+ for k,v in raw_sd.items():
189
+ for s,d in key_map.items():
190
+ k = k.replace(s,d)
191
+ sd[k] = v
192
+ return sd
193
+
194
+ def llama_permute(raw_sd, n_head, n_head_kv):
195
+ # Reverse version of LlamaModel.permute in llama.cpp convert script
196
+ sd = {}
197
+ permute = lambda x,h: x.reshape(h, x.shape[0] // h // 2, 2, *x.shape[1:]).swapaxes(1, 2).reshape(x.shape)
198
+ for k,v in raw_sd.items():
199
+ if k.endswith(("q_proj.weight", "q_proj.bias")):
200
+ v.data = permute(v.data, n_head)
201
+ if k.endswith(("k_proj.weight", "k_proj.bias")):
202
+ v.data = permute(v.data, n_head_kv)
203
+ sd[k] = v
204
+ return sd
205
+
206
+ def strip_quant_suffix(name):
207
+ pattern = r"[-_]?(?:ud-)?i?q[0-9]_[a-z0-9_\-]{1,8}$"
208
+ match = re.search(pattern, name, re.IGNORECASE)
209
+ if match:
210
+ name = name[:match.start()]
211
+ return name
212
+
213
+ def gguf_mmproj_loader(path):
214
+ # Reverse version of Qwen2VLVisionModel.modify_tensors
215
+ logging.info("Attenpting to find mmproj file for text encoder...")
216
+
217
+ # get name to match w/o quant suffix
218
+ tenc_fname = os.path.basename(path)
219
+ tenc = os.path.splitext(tenc_fname)[0].lower()
220
+ tenc = strip_quant_suffix(tenc)
221
+
222
+ # try and find matching mmproj
223
+ target = []
224
+ root = os.path.dirname(path)
225
+ for fname in os.listdir(root):
226
+ name, ext = os.path.splitext(fname)
227
+ if ext.lower() != ".gguf":
228
+ continue
229
+ if "mmproj" not in name.lower():
230
+ continue
231
+ if tenc in name.lower():
232
+ target.append(fname)
233
+
234
+ if len(target) == 0:
235
+ logging.error(f"Error: Can't find mmproj file for '{tenc_fname}' (matching:'{tenc}')! Qwen-Image-Edit will be broken!")
236
+ return {}
237
+ if len(target) > 1:
238
+ logging.error(f"Ambiguous mmproj for text encoder '{tenc_fname}', will use first match.")
239
+
240
+ logging.info(f"Using mmproj '{target[0]}' for text encoder '{tenc_fname}'.")
241
+ target = os.path.join(root, target[0])
242
+ vsd = gguf_sd_loader(target, is_text_model=True)
243
+
244
+ # concat 4D to 5D
245
+ if "v.patch_embd.weight.1" in vsd:
246
+ w1 = dequantize_tensor(vsd.pop("v.patch_embd.weight"), dtype=torch.float32)
247
+ w2 = dequantize_tensor(vsd.pop("v.patch_embd.weight.1"), dtype=torch.float32)
248
+ vsd["v.patch_embd.weight"] = torch.stack([w1, w2], dim=2)
249
+
250
+ # run main replacement
251
+ vsd = sd_map_replace(vsd, CLIP_VISION_SD_MAP)
252
+
253
+ # handle split Q/K/V
254
+ if "visual.blocks.0.attn_q.weight" in vsd:
255
+ attns = {}
256
+ # filter out attentions + group
257
+ for k,v in vsd.items():
258
+ if any(x in k for x in ["attn_q", "attn_k", "attn_v"]):
259
+ k_attn, k_name = k.rsplit(".attn_", 1)
260
+ k_attn += ".attn.qkv." + k_name.split(".")[-1]
261
+ if k_attn not in attns:
262
+ attns[k_attn] = {}
263
+ attns[k_attn][k_name] = dequantize_tensor(
264
+ v, dtype=(torch.bfloat16 if is_quantized(v) else torch.float16)
265
+ )
266
+
267
+ # recombine
268
+ for k,v in attns.items():
269
+ suffix = k.split(".")[-1]
270
+ vsd[k] = torch.cat([
271
+ v[f"q.{suffix}"],
272
+ v[f"k.{suffix}"],
273
+ v[f"v.{suffix}"],
274
+ ], dim=0)
275
+ del attns
276
+
277
+ return vsd
278
+
279
+ def gguf_tokenizer_loader(path, temb_shape):
280
+ # convert gguf tokenizer to spiece
281
+ logging.info("Attempting to recreate sentencepiece tokenizer from GGUF file metadata...")
282
+ try:
283
+ from sentencepiece import sentencepiece_model_pb2 as model
284
+ except ImportError:
285
+ raise ImportError("Please make sure sentencepiece and protobuf are installed.\npip install sentencepiece protobuf")
286
+ spm = model.ModelProto()
287
+
288
+ reader = gguf.GGUFReader(path)
289
+
290
+ if get_field(reader, "tokenizer.ggml.model", str) == "t5":
291
+ if temb_shape == (256384, 4096): # probably UMT5
292
+ spm.trainer_spec.model_type == 1 # Unigram (do we have a T5 w/ BPE?)
293
+ else:
294
+ raise NotImplementedError("Unknown model, can't set tokenizer!")
295
+ else:
296
+ raise NotImplementedError("Unknown model, can't set tokenizer!")
297
+
298
+ spm.normalizer_spec.add_dummy_prefix = get_field(reader, "tokenizer.ggml.add_space_prefix", bool)
299
+ spm.normalizer_spec.remove_extra_whitespaces = get_field(reader, "tokenizer.ggml.remove_extra_whitespaces", bool)
300
+
301
+ tokens = get_list_field(reader, "tokenizer.ggml.tokens", str)
302
+ scores = get_list_field(reader, "tokenizer.ggml.scores", float)
303
+ toktypes = get_list_field(reader, "tokenizer.ggml.token_type", int)
304
+
305
+ for idx, (token, score, toktype) in enumerate(zip(tokens, scores, toktypes)):
306
+ # # These aren't present in the original?
307
+ # if toktype == 5 and idx >= temb_shape[0]%1000):
308
+ # continue
309
+
310
+ piece = spm.SentencePiece()
311
+ piece.piece = token
312
+ piece.score = score
313
+ piece.type = toktype
314
+ spm.pieces.append(piece)
315
+
316
+ # unsure if any of these are correct
317
+ spm.trainer_spec.byte_fallback = True
318
+ spm.trainer_spec.vocab_size = len(tokens) # split off unused?
319
+ spm.trainer_spec.max_sentence_length = 4096
320
+ spm.trainer_spec.eos_id = get_field(reader, "tokenizer.ggml.eos_token_id", int)
321
+ spm.trainer_spec.pad_id = get_field(reader, "tokenizer.ggml.padding_token_id", int)
322
+
323
+ logging.info(f"Created tokenizer with vocab size of {len(spm.pieces)}")
324
+ del reader
325
+ return torch.ByteTensor(list(spm.SerializeToString()))
326
+
327
+ def gguf_clip_loader(path):
328
+ sd, arch = gguf_sd_loader(path, return_arch=True, is_text_model=True)
329
+ if arch in {"t5", "t5encoder"}:
330
+ temb_key = "token_embd.weight"
331
+ if temb_key in sd and sd[temb_key].shape == (256384, 4096):
332
+ # non-standard Comfy-Org tokenizer
333
+ sd["spiece_model"] = gguf_tokenizer_loader(path, sd[temb_key].shape)
334
+ # TODO: dequantizing token embed here is janky but otherwise we OOM due to tensor being massive.
335
+ logging.warning(f"Dequantizing {temb_key} to prevent runtime OOM.")
336
+ sd[temb_key] = dequantize_tensor(sd[temb_key], dtype=torch.float16)
337
+ sd = sd_map_replace(sd, T5_SD_MAP)
338
+ elif arch in {"llama", "qwen2vl"}:
339
+ # TODO: pass model_options["vocab_size"] to loader somehow
340
+ temb_key = "token_embd.weight"
341
+ if temb_key in sd and sd[temb_key].shape[0] >= (64 * 1024):
342
+ # See note above for T5.
343
+ logging.warning(f"Dequantizing {temb_key} to prevent runtime OOM.")
344
+ sd[temb_key] = dequantize_tensor(sd[temb_key], dtype=torch.float16)
345
+ sd = sd_map_replace(sd, LLAMA_SD_MAP)
346
+ if arch == "llama":
347
+ sd = llama_permute(sd, 32, 8) # L3
348
+ if arch == "qwen2vl":
349
+ vsd = gguf_mmproj_loader(path)
350
+ sd.update(vsd)
351
+ else:
352
+ pass
353
+ return sd
custom_nodes/ComfyUI-GGUF/nodes.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
2
+ import torch
3
+ import logging
4
+ import collections
5
+
6
+ import nodes
7
+ import comfy.sd
8
+ import comfy.lora
9
+ import comfy.float
10
+ import comfy.utils
11
+ import comfy.model_patcher
12
+ import comfy.model_management
13
+ import folder_paths
14
+
15
+ from .ops import GGMLOps, move_patch_to_device
16
+ from .loader import gguf_sd_loader, gguf_clip_loader
17
+ from .dequant import is_quantized, is_torch_compatible
18
+
19
+ def update_folder_names_and_paths(key, targets=[]):
20
+ # check for existing key
21
+ base = folder_paths.folder_names_and_paths.get(key, ([], {}))
22
+ base = base[0] if isinstance(base[0], (list, set, tuple)) else []
23
+ # find base key & add w/ fallback, sanity check + warning
24
+ target = next((x for x in targets if x in folder_paths.folder_names_and_paths), targets[0])
25
+ orig, _ = folder_paths.folder_names_and_paths.get(target, ([], {}))
26
+ folder_paths.folder_names_and_paths[key] = (orig or base, {".gguf"})
27
+ if base and base != orig:
28
+ logging.warning(f"Unknown file list already present on key {key}: {base}")
29
+
30
+ # Add a custom keys for files ending in .gguf
31
+ update_folder_names_and_paths("unet_gguf", ["diffusion_models", "unet"])
32
+ update_folder_names_and_paths("clip_gguf", ["text_encoders", "clip"])
33
+
34
+ class GGUFModelPatcher(comfy.model_patcher.ModelPatcher):
35
+ patch_on_device = False
36
+
37
+ def patch_weight_to_device(self, key, device_to=None, inplace_update=False):
38
+ if key not in self.patches:
39
+ return
40
+ weight = comfy.utils.get_attr(self.model, key)
41
+
42
+ patches = self.patches[key]
43
+ if is_quantized(weight):
44
+ out_weight = weight.to(device_to)
45
+ patches = move_patch_to_device(patches, self.load_device if self.patch_on_device else self.offload_device)
46
+ # TODO: do we ever have legitimate duplicate patches? (i.e. patch on top of patched weight)
47
+ out_weight.patches = [(patches, key)]
48
+ else:
49
+ inplace_update = self.weight_inplace_update or inplace_update
50
+ if key not in self.backup:
51
+ self.backup[key] = collections.namedtuple('Dimension', ['weight', 'inplace_update'])(
52
+ weight.to(device=self.offload_device, copy=inplace_update), inplace_update
53
+ )
54
+
55
+ if device_to is not None:
56
+ temp_weight = comfy.model_management.cast_to_device(weight, device_to, torch.float32, copy=True)
57
+ else:
58
+ temp_weight = weight.to(torch.float32, copy=True)
59
+
60
+ out_weight = comfy.lora.calculate_weight(patches, temp_weight, key)
61
+ out_weight = comfy.float.stochastic_rounding(out_weight, weight.dtype)
62
+
63
+ if inplace_update:
64
+ comfy.utils.copy_to_param(self.model, key, out_weight)
65
+ else:
66
+ comfy.utils.set_attr_param(self.model, key, out_weight)
67
+
68
+ def unpatch_model(self, device_to=None, unpatch_weights=True):
69
+ if unpatch_weights:
70
+ for p in self.model.parameters():
71
+ if is_torch_compatible(p):
72
+ continue
73
+ patches = getattr(p, "patches", [])
74
+ if len(patches) > 0:
75
+ p.patches = []
76
+ # TODO: Find another way to not unload after patches
77
+ return super().unpatch_model(device_to=device_to, unpatch_weights=unpatch_weights)
78
+
79
+ mmap_released = False
80
+ def load(self, *args, force_patch_weights=False, **kwargs):
81
+ # always call `patch_weight_to_device` even for lowvram
82
+ super().load(*args, force_patch_weights=True, **kwargs)
83
+
84
+ # make sure nothing stays linked to mmap after first load
85
+ if not self.mmap_released:
86
+ linked = []
87
+ if kwargs.get("lowvram_model_memory", 0) > 0:
88
+ for n, m in self.model.named_modules():
89
+ if hasattr(m, "weight"):
90
+ device = getattr(m.weight, "device", None)
91
+ if device == self.offload_device:
92
+ linked.append((n, m))
93
+ continue
94
+ if hasattr(m, "bias"):
95
+ device = getattr(m.bias, "device", None)
96
+ if device == self.offload_device:
97
+ linked.append((n, m))
98
+ continue
99
+ if linked and self.load_device != self.offload_device:
100
+ logging.info(f"Attempting to release mmap ({len(linked)})")
101
+ for n, m in linked:
102
+ # TODO: possible to OOM, find better way to detach
103
+ m.to(self.load_device).to(self.offload_device)
104
+ self.mmap_released = True
105
+
106
+ def clone(self, *args, **kwargs):
107
+ src_cls = self.__class__
108
+ self.__class__ = GGUFModelPatcher
109
+ n = super().clone(*args, **kwargs)
110
+ n.__class__ = GGUFModelPatcher
111
+ self.__class__ = src_cls
112
+ # GGUF specific clone values below
113
+ n.patch_on_device = getattr(self, "patch_on_device", False)
114
+ if src_cls != GGUFModelPatcher:
115
+ n.size = 0 # force recalc
116
+ return n
117
+
118
+ class UnetLoaderGGUF:
119
+ @classmethod
120
+ def INPUT_TYPES(s):
121
+ unet_names = [x for x in folder_paths.get_filename_list("unet_gguf")]
122
+ return {
123
+ "required": {
124
+ "unet_name": (unet_names,),
125
+ }
126
+ }
127
+
128
+ RETURN_TYPES = ("MODEL",)
129
+ FUNCTION = "load_unet"
130
+ CATEGORY = "bootleg"
131
+ TITLE = "Unet Loader (GGUF)"
132
+
133
+ def load_unet(self, unet_name, dequant_dtype=None, patch_dtype=None, patch_on_device=None):
134
+ ops = GGMLOps()
135
+
136
+ if dequant_dtype in ("default", None):
137
+ ops.Linear.dequant_dtype = None
138
+ elif dequant_dtype in ["target"]:
139
+ ops.Linear.dequant_dtype = dequant_dtype
140
+ else:
141
+ ops.Linear.dequant_dtype = getattr(torch, dequant_dtype)
142
+
143
+ if patch_dtype in ("default", None):
144
+ ops.Linear.patch_dtype = None
145
+ elif patch_dtype in ["target"]:
146
+ ops.Linear.patch_dtype = patch_dtype
147
+ else:
148
+ ops.Linear.patch_dtype = getattr(torch, patch_dtype)
149
+
150
+ # init model
151
+ unet_path = folder_paths.get_full_path("unet", unet_name)
152
+ sd = gguf_sd_loader(unet_path)
153
+ model = comfy.sd.load_diffusion_model_state_dict(
154
+ sd, model_options={"custom_operations": ops}
155
+ )
156
+ if model is None:
157
+ logging.error("ERROR UNSUPPORTED UNET {}".format(unet_path))
158
+ raise RuntimeError("ERROR: Could not detect model type of: {}".format(unet_path))
159
+ model = GGUFModelPatcher.clone(model)
160
+ model.patch_on_device = patch_on_device
161
+ return (model,)
162
+
163
+ class UnetLoaderGGUFAdvanced(UnetLoaderGGUF):
164
+ @classmethod
165
+ def INPUT_TYPES(s):
166
+ unet_names = [x for x in folder_paths.get_filename_list("unet_gguf")]
167
+ return {
168
+ "required": {
169
+ "unet_name": (unet_names,),
170
+ "dequant_dtype": (["default", "target", "float32", "float16", "bfloat16"], {"default": "default"}),
171
+ "patch_dtype": (["default", "target", "float32", "float16", "bfloat16"], {"default": "default"}),
172
+ "patch_on_device": ("BOOLEAN", {"default": False}),
173
+ }
174
+ }
175
+ TITLE = "Unet Loader (GGUF/Advanced)"
176
+
177
+ class CLIPLoaderGGUF:
178
+ @classmethod
179
+ def INPUT_TYPES(s):
180
+ base = nodes.CLIPLoader.INPUT_TYPES()
181
+ return {
182
+ "required": {
183
+ "clip_name": (s.get_filename_list(),),
184
+ "type": base["required"]["type"],
185
+ }
186
+ }
187
+
188
+ RETURN_TYPES = ("CLIP",)
189
+ FUNCTION = "load_clip"
190
+ CATEGORY = "bootleg"
191
+ TITLE = "CLIPLoader (GGUF)"
192
+
193
+ @classmethod
194
+ def get_filename_list(s):
195
+ files = []
196
+ files += folder_paths.get_filename_list("clip")
197
+ files += folder_paths.get_filename_list("clip_gguf")
198
+ return sorted(files)
199
+
200
+ def load_data(self, ckpt_paths):
201
+ clip_data = []
202
+ for p in ckpt_paths:
203
+ if p.endswith(".gguf"):
204
+ sd = gguf_clip_loader(p)
205
+ else:
206
+ sd = comfy.utils.load_torch_file(p, safe_load=True)
207
+ if "scaled_fp8" in sd: # NOTE: Scaled FP8 would require different custom ops, but only one can be active
208
+ raise NotImplementedError(f"Mixing scaled FP8 with GGUF is not supported! Use regular CLIP loader or switch model(s)\n({p})")
209
+ clip_data.append(sd)
210
+ return clip_data
211
+
212
+ def load_patcher(self, clip_paths, clip_type, clip_data):
213
+ clip = comfy.sd.load_text_encoder_state_dicts(
214
+ clip_type = clip_type,
215
+ state_dicts = clip_data,
216
+ model_options = {
217
+ "custom_operations": GGMLOps,
218
+ "initial_device": comfy.model_management.text_encoder_offload_device()
219
+ },
220
+ embedding_directory = folder_paths.get_folder_paths("embeddings"),
221
+ )
222
+ clip.patcher = GGUFModelPatcher.clone(clip.patcher)
223
+ return clip
224
+
225
+ def load_clip(self, clip_name, type="stable_diffusion"):
226
+ clip_path = folder_paths.get_full_path("clip", clip_name)
227
+ clip_type = getattr(comfy.sd.CLIPType, type.upper(), comfy.sd.CLIPType.STABLE_DIFFUSION)
228
+ return (self.load_patcher([clip_path], clip_type, self.load_data([clip_path])),)
229
+
230
+ class DualCLIPLoaderGGUF(CLIPLoaderGGUF):
231
+ @classmethod
232
+ def INPUT_TYPES(s):
233
+ base = nodes.DualCLIPLoader.INPUT_TYPES()
234
+ file_options = (s.get_filename_list(), )
235
+ return {
236
+ "required": {
237
+ "clip_name1": file_options,
238
+ "clip_name2": file_options,
239
+ "type": base["required"]["type"],
240
+ }
241
+ }
242
+
243
+ TITLE = "DualCLIPLoader (GGUF)"
244
+
245
+ def load_clip(self, clip_name1, clip_name2, type):
246
+ clip_path1 = folder_paths.get_full_path("clip", clip_name1)
247
+ clip_path2 = folder_paths.get_full_path("clip", clip_name2)
248
+ clip_paths = (clip_path1, clip_path2)
249
+ clip_type = getattr(comfy.sd.CLIPType, type.upper(), comfy.sd.CLIPType.STABLE_DIFFUSION)
250
+ return (self.load_patcher(clip_paths, clip_type, self.load_data(clip_paths)),)
251
+
252
+ class TripleCLIPLoaderGGUF(CLIPLoaderGGUF):
253
+ @classmethod
254
+ def INPUT_TYPES(s):
255
+ file_options = (s.get_filename_list(), )
256
+ return {
257
+ "required": {
258
+ "clip_name1": file_options,
259
+ "clip_name2": file_options,
260
+ "clip_name3": file_options,
261
+ }
262
+ }
263
+
264
+ TITLE = "TripleCLIPLoader (GGUF)"
265
+
266
+ def load_clip(self, clip_name1, clip_name2, clip_name3, type="sd3"):
267
+ clip_path1 = folder_paths.get_full_path("clip", clip_name1)
268
+ clip_path2 = folder_paths.get_full_path("clip", clip_name2)
269
+ clip_path3 = folder_paths.get_full_path("clip", clip_name3)
270
+ clip_paths = (clip_path1, clip_path2, clip_path3)
271
+ clip_type = getattr(comfy.sd.CLIPType, type.upper(), comfy.sd.CLIPType.STABLE_DIFFUSION)
272
+ return (self.load_patcher(clip_paths, clip_type, self.load_data(clip_paths)),)
273
+
274
+ class QuadrupleCLIPLoaderGGUF(CLIPLoaderGGUF):
275
+ @classmethod
276
+ def INPUT_TYPES(s):
277
+ file_options = (s.get_filename_list(), )
278
+ return {
279
+ "required": {
280
+ "clip_name1": file_options,
281
+ "clip_name2": file_options,
282
+ "clip_name3": file_options,
283
+ "clip_name4": file_options,
284
+ }
285
+ }
286
+
287
+ TITLE = "QuadrupleCLIPLoader (GGUF)"
288
+
289
+ def load_clip(self, clip_name1, clip_name2, clip_name3, clip_name4, type="stable_diffusion"):
290
+ clip_path1 = folder_paths.get_full_path("clip", clip_name1)
291
+ clip_path2 = folder_paths.get_full_path("clip", clip_name2)
292
+ clip_path3 = folder_paths.get_full_path("clip", clip_name3)
293
+ clip_path4 = folder_paths.get_full_path("clip", clip_name4)
294
+ clip_paths = (clip_path1, clip_path2, clip_path3, clip_path4)
295
+ clip_type = getattr(comfy.sd.CLIPType, type.upper(), comfy.sd.CLIPType.STABLE_DIFFUSION)
296
+ return (self.load_patcher(clip_paths, clip_type, self.load_data(clip_paths)),)
297
+
298
+ NODE_CLASS_MAPPINGS = {
299
+ "UnetLoaderGGUF": UnetLoaderGGUF,
300
+ "CLIPLoaderGGUF": CLIPLoaderGGUF,
301
+ "DualCLIPLoaderGGUF": DualCLIPLoaderGGUF,
302
+ "TripleCLIPLoaderGGUF": TripleCLIPLoaderGGUF,
303
+ "QuadrupleCLIPLoaderGGUF": QuadrupleCLIPLoaderGGUF,
304
+ "UnetLoaderGGUFAdvanced": UnetLoaderGGUFAdvanced,
305
+ }
custom_nodes/ComfyUI-GGUF/ops.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
2
+ import gguf
3
+ import torch
4
+ import logging
5
+
6
+ import comfy.ops
7
+ import comfy.lora
8
+ import comfy.model_management
9
+ from .dequant import dequantize_tensor, is_quantized
10
+
11
+ def chained_hasattr(obj, chained_attr):
12
+ probe = obj
13
+ for attr in chained_attr.split('.'):
14
+ if hasattr(probe, attr):
15
+ probe = getattr(probe, attr)
16
+ else:
17
+ return False
18
+ return True
19
+
20
+ # A bakcward and forward compatible way to get `torch.compiler.disable`.
21
+ def get_torch_compiler_disable_decorator():
22
+ def dummy_decorator(*args, **kwargs):
23
+ def noop(x):
24
+ return x
25
+ return noop
26
+
27
+ from packaging import version
28
+
29
+ if not chained_hasattr(torch, "compiler.disable"):
30
+ logging.info("ComfyUI-GGUF: Torch too old for torch.compile - bypassing")
31
+ return dummy_decorator # torch too old
32
+ elif version.parse(torch.__version__) >= version.parse("2.8"):
33
+ logging.info("ComfyUI-GGUF: Allowing full torch compile")
34
+ return dummy_decorator # torch compile works
35
+ if chained_hasattr(torch, "_dynamo.config.nontraceable_tensor_subclasses"):
36
+ logging.info("ComfyUI-GGUF: Allowing full torch compile (nightly)")
37
+ return dummy_decorator # torch compile works, nightly before 2.8 release
38
+ else:
39
+ logging.info("ComfyUI-GGUF: Partial torch compile only, consider updating pytorch")
40
+ return torch.compiler.disable
41
+
42
+ torch_compiler_disable = get_torch_compiler_disable_decorator()
43
+
44
+ class GGMLTensor(torch.Tensor):
45
+ """
46
+ Main tensor-like class for storing quantized weights
47
+ """
48
+ def __init__(self, *args, tensor_type, tensor_shape, patches=[], **kwargs):
49
+ super().__init__()
50
+ self.tensor_type = tensor_type
51
+ self.tensor_shape = tensor_shape
52
+ self.patches = patches
53
+
54
+ def __new__(cls, *args, tensor_type, tensor_shape, patches=[], **kwargs):
55
+ return super().__new__(cls, *args, **kwargs)
56
+
57
+ def to(self, *args, **kwargs):
58
+ new = super().to(*args, **kwargs)
59
+ new.tensor_type = getattr(self, "tensor_type", None)
60
+ new.tensor_shape = getattr(self, "tensor_shape", new.data.shape)
61
+ new.patches = getattr(self, "patches", []).copy()
62
+ return new
63
+
64
+ def clone(self, *args, **kwargs):
65
+ return self
66
+
67
+ def detach(self, *args, **kwargs):
68
+ return self
69
+
70
+ def copy_(self, *args, **kwargs):
71
+ # fixes .weight.copy_ in comfy/clip_model/CLIPTextModel
72
+ try:
73
+ return super().copy_(*args, **kwargs)
74
+ except Exception as e:
75
+ logging.warning(f"ignoring 'copy_' on tensor: {e}")
76
+
77
+ def new_empty(self, size, *args, **kwargs):
78
+ # Intel Arc fix, ref#50
79
+ new_tensor = super().new_empty(size, *args, **kwargs)
80
+ return GGMLTensor(
81
+ new_tensor,
82
+ tensor_type = getattr(self, "tensor_type", None),
83
+ tensor_shape = size,
84
+ patches = getattr(self, "patches", []).copy()
85
+ )
86
+
87
+ @property
88
+ def shape(self):
89
+ if not hasattr(self, "tensor_shape"):
90
+ self.tensor_shape = self.size()
91
+ return self.tensor_shape
92
+
93
+ class GGMLLayer(torch.nn.Module):
94
+ """
95
+ This (should) be responsible for de-quantizing on the fly
96
+ """
97
+ comfy_cast_weights = True
98
+ dequant_dtype = None
99
+ patch_dtype = None
100
+ largest_layer = False
101
+ torch_compatible_tensor_types = {None, gguf.GGMLQuantizationType.F32, gguf.GGMLQuantizationType.F16}
102
+
103
+ def is_ggml_quantized(self, *, weight=None, bias=None):
104
+ if weight is None:
105
+ weight = self.weight
106
+ if bias is None:
107
+ bias = self.bias
108
+ return is_quantized(weight) or is_quantized(bias)
109
+
110
+ def _load_from_state_dict(self, state_dict, prefix, *args, **kwargs):
111
+ weight, bias = state_dict.get(f"{prefix}weight"), state_dict.get(f"{prefix}bias")
112
+ # NOTE: using modified load for linear due to not initializing on creation, see GGMLOps todo
113
+ if self.is_ggml_quantized(weight=weight, bias=bias) or isinstance(self, torch.nn.Linear):
114
+ return self.ggml_load_from_state_dict(state_dict, prefix, *args, **kwargs)
115
+ # Not strictly required, but fixes embedding shape mismatch. Threshold set in loader.py
116
+ if isinstance(self, torch.nn.Embedding) and self.weight.shape[0] >= (64 * 1024):
117
+ return self.ggml_load_from_state_dict(state_dict, prefix, *args, **kwargs)
118
+ return super()._load_from_state_dict(state_dict, prefix, *args, **kwargs)
119
+
120
+ def ggml_load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
121
+ prefix_len = len(prefix)
122
+ for k,v in state_dict.items():
123
+ if k[prefix_len:] == "weight":
124
+ self.weight = torch.nn.Parameter(v, requires_grad=False)
125
+ elif k[prefix_len:] == "bias" and v is not None:
126
+ self.bias = torch.nn.Parameter(v, requires_grad=False)
127
+ else:
128
+ unexpected_keys.append(k)
129
+
130
+ # For Linear layer with missing weight
131
+ if self.weight is None and isinstance(self, torch.nn.Linear):
132
+ v = torch.zeros(self.in_features, self.out_features)
133
+ self.weight = torch.nn.Parameter(v, requires_grad=False)
134
+ missing_keys.append(prefix+"weight")
135
+
136
+ # for vram estimation (TODO: less fragile logic?)
137
+ if getattr(self.weight, "is_largest_weight", False):
138
+ self.largest_layer = True
139
+
140
+ def _save_to_state_dict(self, *args, **kwargs):
141
+ if self.is_ggml_quantized():
142
+ return self.ggml_save_to_state_dict(*args, **kwargs)
143
+ return super()._save_to_state_dict(*args, **kwargs)
144
+
145
+ def ggml_save_to_state_dict(self, destination, prefix, keep_vars):
146
+ # This is a fake state dict for vram estimation
147
+ weight = torch.zeros_like(self.weight, device=torch.device("meta"))
148
+ destination[prefix + "weight"] = weight
149
+ if self.bias is not None:
150
+ bias = torch.zeros_like(self.bias, device=torch.device("meta"))
151
+ destination[prefix + "bias"] = bias
152
+
153
+ # Take into account space required for dequantizing the largest tensor
154
+ if self.largest_layer:
155
+ shape = getattr(self.weight, "tensor_shape", self.weight.shape)
156
+ dtype = self.dequant_dtype or torch.float16
157
+ temp = torch.empty(*shape, device=torch.device("meta"), dtype=dtype)
158
+ destination[prefix + "temp.weight"] = temp
159
+
160
+ return
161
+ # This would return the dequantized state dict
162
+ destination[prefix + "weight"] = self.get_weight(self.weight)
163
+ if bias is not None:
164
+ destination[prefix + "bias"] = self.get_weight(self.bias)
165
+
166
+ def get_weight(self, tensor, dtype):
167
+ if tensor is None:
168
+ return
169
+
170
+ # consolidate and load patches to GPU in async
171
+ patch_list = []
172
+ device = tensor.device
173
+ for patches, key in getattr(tensor, "patches", []):
174
+ patch_list += move_patch_to_device(patches, device)
175
+
176
+ # dequantize tensor while patches load
177
+ weight = dequantize_tensor(tensor, dtype, self.dequant_dtype)
178
+
179
+ # prevent propagating custom tensor class
180
+ if isinstance(weight, GGMLTensor):
181
+ weight = torch.Tensor(weight)
182
+
183
+ # apply patches
184
+ if len(patch_list) > 0:
185
+ if self.patch_dtype is None:
186
+ weight = comfy.lora.calculate_weight(patch_list, weight, key)
187
+ else:
188
+ # for testing, may degrade image quality
189
+ patch_dtype = dtype if self.patch_dtype == "target" else self.patch_dtype
190
+ weight = comfy.lora.calculate_weight(patch_list, weight, key, patch_dtype)
191
+ return weight
192
+
193
+ @torch_compiler_disable()
194
+ def cast_bias_weight(s, input=None, dtype=None, device=None, bias_dtype=None):
195
+ if input is not None:
196
+ if dtype is None:
197
+ dtype = getattr(input, "dtype", torch.float32)
198
+ if bias_dtype is None:
199
+ bias_dtype = dtype
200
+ if device is None:
201
+ device = input.device
202
+
203
+ bias = None
204
+ non_blocking = comfy.model_management.device_supports_non_blocking(device)
205
+ if s.bias is not None:
206
+ bias = s.get_weight(s.bias.to(device), dtype)
207
+ bias = comfy.ops.cast_to(bias, bias_dtype, device, non_blocking=non_blocking, copy=False)
208
+
209
+ weight = s.get_weight(s.weight.to(device), dtype)
210
+ weight = comfy.ops.cast_to(weight, dtype, device, non_blocking=non_blocking, copy=False)
211
+ return weight, bias
212
+
213
+ def forward_comfy_cast_weights(self, input, *args, **kwargs):
214
+ if self.is_ggml_quantized():
215
+ out = self.forward_ggml_cast_weights(input, *args, **kwargs)
216
+ else:
217
+ out = super().forward_comfy_cast_weights(input, *args, **kwargs)
218
+
219
+ # non-ggml forward might still propagate custom tensor class
220
+ if isinstance(out, GGMLTensor):
221
+ out = torch.Tensor(out)
222
+ return out
223
+
224
+ def forward_ggml_cast_weights(self, input):
225
+ raise NotImplementedError
226
+
227
+ class GGMLOps(comfy.ops.manual_cast):
228
+ """
229
+ Dequantize weights on the fly before doing the compute
230
+ """
231
+ class Linear(GGMLLayer, comfy.ops.manual_cast.Linear):
232
+ def __init__(self, in_features, out_features, bias=True, device=None, dtype=None):
233
+ torch.nn.Module.__init__(self)
234
+ # TODO: better workaround for reserved memory spike on windows
235
+ # Issue is with `torch.empty` still reserving the full memory for the layer
236
+ # Windows doesn't over-commit memory so without this 24GB+ of pagefile is used
237
+ self.in_features = in_features
238
+ self.out_features = out_features
239
+ self.weight = None
240
+ self.bias = None
241
+
242
+ def forward_ggml_cast_weights(self, input):
243
+ weight, bias = self.cast_bias_weight(input)
244
+ return torch.nn.functional.linear(input, weight, bias)
245
+
246
+ class Conv2d(GGMLLayer, comfy.ops.manual_cast.Conv2d):
247
+ def forward_ggml_cast_weights(self, input):
248
+ weight, bias = self.cast_bias_weight(input)
249
+ return self._conv_forward(input, weight, bias)
250
+
251
+ class Embedding(GGMLLayer, comfy.ops.manual_cast.Embedding):
252
+ def forward_ggml_cast_weights(self, input, out_dtype=None):
253
+ output_dtype = out_dtype
254
+ if self.weight.dtype == torch.float16 or self.weight.dtype == torch.bfloat16:
255
+ out_dtype = None
256
+ weight, _bias = self.cast_bias_weight(self, device=input.device, dtype=out_dtype)
257
+ return torch.nn.functional.embedding(
258
+ input, weight, self.padding_idx, self.max_norm, self.norm_type, self.scale_grad_by_freq, self.sparse
259
+ ).to(dtype=output_dtype)
260
+
261
+ class LayerNorm(GGMLLayer, comfy.ops.manual_cast.LayerNorm):
262
+ def forward_ggml_cast_weights(self, input):
263
+ if self.weight is None:
264
+ return super().forward_comfy_cast_weights(input)
265
+ weight, bias = self.cast_bias_weight(input)
266
+ return torch.nn.functional.layer_norm(input, self.normalized_shape, weight, bias, self.eps)
267
+
268
+ class GroupNorm(GGMLLayer, comfy.ops.manual_cast.GroupNorm):
269
+ def forward_ggml_cast_weights(self, input):
270
+ weight, bias = self.cast_bias_weight(input)
271
+ return torch.nn.functional.group_norm(input, self.num_groups, weight, bias, self.eps)
272
+
273
+ def move_patch_to_device(item, device):
274
+ if isinstance(item, torch.Tensor):
275
+ return item.to(device, non_blocking=True)
276
+ elif isinstance(item, tuple):
277
+ return tuple(move_patch_to_device(x, device) for x in item)
278
+ elif isinstance(item, list):
279
+ return [move_patch_to_device(x, device) for x in item]
280
+ else:
281
+ return item
custom_nodes/ComfyUI-GGUF/pyproject.toml ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "ComfyUI-GGUF"
3
+ description = "GGUF Quantization support for native ComfyUI models."
4
+ version = "1.1.4" # 2.0.0 = GitHub main, 1.X.X = ComfyUI Registry
5
+ license = { file = "LICENSE" }
6
+ dependencies = ["gguf>=0.13.0", "sentencepiece", "protobuf"]
7
+
8
+ [project.urls]
9
+ Repository = "https://github.com/city96/ComfyUI-GGUF"
10
+
11
+ [tool.comfy]
12
+ PublisherId = "city96"
13
+ DisplayName = "ComfyUI-GGUF"
14
+ Icon = ""
custom_nodes/ComfyUI-GGUF/requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # main
2
+ gguf>=0.13.0
3
+ # optional - tokenizer
4
+ sentencepiece
5
+ protobuf
custom_nodes/ComfyUI-GGUF/tools/README.md ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Converting initial model
2
+
3
+ To convert your initial safetensors/ckpt model to FP16/BF16 GGUF, run the following command:
4
+
5
+ ```
6
+ python convert.py --src E:\models\unet\flux1-dev.safetensors
7
+ ```
8
+ Make sure `gguf>=0.13.0` is installed for this step. Optionally, specify the output gguf file with the `--dst` arg.
9
+
10
+ > [!NOTE]
11
+ > Do not use the diffusers UNET format for flux, it won't work, use the default/reference checkpoint key format. This is due to q/k/v being merged into one qkv key.
12
+ > You can convert it by loading it in ComfyUI and saving it using the built-in "ModelSave" node.
13
+
14
+ > [!WARNING]
15
+ > For hunyuan video/wan 2.1, you will see a warning about 5D tensors. This means the script will save a **non functional** model to disk first, that you can quantize. I recommend saving these in a separate `raw` folder to avoid confusion.
16
+ >
17
+ > After quantization, you will have to run `fix_5d_tensor.py` manually to add back the missing key that was saved by the conversion code.
18
+
19
+ ## Quantizing using custom llama.cpp
20
+
21
+ Depending on your git settings, you may need to run the following script first in order to make sure the patch file is valid. It will convert Windows (CRLF) line endings to Unix (LF) ones.
22
+
23
+ ```
24
+ python fix_lines_ending.py
25
+ ```
26
+
27
+ Git clone llama.cpp into the current folder:
28
+
29
+ ```
30
+ git clone https://github.com/ggerganov/llama.cpp
31
+ ```
32
+
33
+ Check out the correct branch, then apply the custom patch needed to add image model support to the repo you just cloned.
34
+
35
+ ```
36
+ cd llama.cpp
37
+ git checkout tags/b3962
38
+ git apply ..\lcpp.patch
39
+ ```
40
+
41
+ Compile the llama-quantize binary. This example uses cmake, on linux you can just use make.
42
+
43
+ ### Visual Studio 2019, Linux, etc...
44
+
45
+ ```
46
+ mkdir build
47
+ cmake -B build
48
+ cmake --build build --config Debug -j10 --target llama-quantize
49
+ cd ..
50
+ ```
51
+
52
+ ### Visual Studio 2022
53
+
54
+ ```
55
+ mkdir build
56
+ cmake -B build -DCMAKE_CXX_STANDARD=17 -DCMAKE_CXX_STANDARD_REQUIRED=ON -DCMAKE_CXX_FLAGS="-std=c++17"
57
+ ```
58
+
59
+ Edit the `llama.cpp\common\log.cpp` file, inserts two lines after the existing first line:
60
+
61
+ ```
62
+ #include "log.h"
63
+
64
+ #define _SILENCE_CXX23_CHRONO_DEPRECATION_WARNING
65
+ #include <chrono>
66
+ ```
67
+
68
+ Then you can build the project:
69
+ ```
70
+ cmake --build build --config Debug -j10 --target llama-quantize
71
+ cd ..
72
+ ```
73
+
74
+ ### Quantize your model
75
+
76
+
77
+ Now you can use the newly build binary to quantize your model to the desired format:
78
+ ```
79
+ llama.cpp\build\bin\Debug\llama-quantize.exe E:\models\unet\flux1-dev-BF16.gguf E:\models\unet\flux1-dev-Q4_K_S.gguf Q4_K_S
80
+ ```
81
+
82
+ You can extract the patch again with `git diff src\llama.cpp > lcpp.patch` if you wish to change something and contribute back.
83
+
84
+ > [!WARNING]
85
+ > For hunyuan video/wan 2.1, you will have to run `fix_5d_tensor.py` after the quantization step is done.
86
+ >
87
+ > Example usage: `fix_5d_tensors.py --src E:\models\video\raw\wan2.1-t2v-1.3b-Q8_0.gguf --dst E:\models\video\wan2.1-t2v-1.3b-Q8_0.gguf`
88
+ >
89
+ > By default, this also saves a `fix_5d_tensors_[arch].safetensors` file in the `ComfyUI-GGUF/tools` folder, it's recommended to delete this after all models have been converted.
90
+
91
+ > [!NOTE]
92
+ > Do not quantize SDXL / SD1 / other Conv2D heavy models. If you do, make sure to **extract the UNET model first**.
93
+ >This should be obvious, but also don't use the resulting llama-quantize binary with LLMs.
custom_nodes/ComfyUI-GGUF/tools/convert.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
2
+ import os
3
+ import gguf
4
+ import torch
5
+ import logging
6
+ import argparse
7
+ from tqdm import tqdm
8
+ from safetensors.torch import load_file, save_file
9
+
10
+ QUANTIZATION_THRESHOLD = 1024
11
+ REARRANGE_THRESHOLD = 512
12
+ MAX_TENSOR_NAME_LENGTH = 127
13
+ MAX_TENSOR_DIMS = 4
14
+
15
+ class ModelTemplate:
16
+ arch = "invalid" # string describing architecture
17
+ shape_fix = False # whether to reshape tensors
18
+ keys_detect = [] # list of lists to match in state dict
19
+ keys_banned = [] # list of keys that should mark model as invalid for conversion
20
+ keys_hiprec = [] # list of keys that need to be kept in fp32 for some reason
21
+ keys_ignore = [] # list of strings to ignore keys by when found
22
+
23
+ def handle_nd_tensor(self, key, data):
24
+ raise NotImplementedError(f"Tensor detected that exceeds dims supported by C++ code! ({key} @ {data.shape})")
25
+
26
+ class ModelFlux(ModelTemplate):
27
+ arch = "flux"
28
+ keys_detect = [
29
+ ("transformer_blocks.0.attn.norm_added_k.weight",),
30
+ ("double_blocks.0.img_attn.proj.weight",),
31
+ ]
32
+ keys_banned = ["transformer_blocks.0.attn.norm_added_k.weight",]
33
+
34
+ class ModelSD3(ModelTemplate):
35
+ arch = "sd3"
36
+ keys_detect = [
37
+ ("transformer_blocks.0.attn.add_q_proj.weight",),
38
+ ("joint_blocks.0.x_block.attn.qkv.weight",),
39
+ ]
40
+ keys_banned = ["transformer_blocks.0.attn.add_q_proj.weight",]
41
+
42
+ class ModelAura(ModelTemplate):
43
+ arch = "aura"
44
+ keys_detect = [
45
+ ("double_layers.3.modX.1.weight",),
46
+ ("joint_transformer_blocks.3.ff_context.out_projection.weight",),
47
+ ]
48
+ keys_banned = ["joint_transformer_blocks.3.ff_context.out_projection.weight",]
49
+
50
+ class ModelHiDream(ModelTemplate):
51
+ arch = "hidream"
52
+ keys_detect = [
53
+ (
54
+ "caption_projection.0.linear.weight",
55
+ "double_stream_blocks.0.block.ff_i.shared_experts.w3.weight"
56
+ )
57
+ ]
58
+ keys_hiprec = [
59
+ # nn.parameter, can't load from BF16 ver
60
+ ".ff_i.gate.weight",
61
+ "img_emb.emb_pos"
62
+ ]
63
+
64
+ class CosmosPredict2(ModelTemplate):
65
+ arch = "cosmos"
66
+ keys_detect = [
67
+ (
68
+ "blocks.0.mlp.layer1.weight",
69
+ "blocks.0.adaln_modulation_cross_attn.1.weight",
70
+ )
71
+ ]
72
+ keys_hiprec = ["pos_embedder"]
73
+ keys_ignore = ["_extra_state", "accum_"]
74
+
75
+ class ModelHyVid(ModelTemplate):
76
+ arch = "hyvid"
77
+ keys_detect = [
78
+ (
79
+ "double_blocks.0.img_attn_proj.weight",
80
+ "txt_in.individual_token_refiner.blocks.1.self_attn_qkv.weight",
81
+ )
82
+ ]
83
+
84
+ def handle_nd_tensor(self, key, data):
85
+ # hacky but don't have any better ideas
86
+ path = f"./fix_5d_tensors_{self.arch}.safetensors" # TODO: somehow get a path here??
87
+ if os.path.isfile(path):
88
+ raise RuntimeError(f"5D tensor fix file already exists! {path}")
89
+ fsd = {key: torch.from_numpy(data)}
90
+ tqdm.write(f"5D key found in state dict! Manual fix required! - {key} {data.shape}")
91
+ save_file(fsd, path)
92
+
93
+ class ModelWan(ModelHyVid):
94
+ arch = "wan"
95
+ keys_detect = [
96
+ (
97
+ "blocks.0.self_attn.norm_q.weight",
98
+ "text_embedding.2.weight",
99
+ "head.modulation",
100
+ )
101
+ ]
102
+ keys_hiprec = [
103
+ ".modulation" # nn.parameter, can't load from BF16 ver
104
+ ]
105
+
106
+ class ModelLTXV(ModelTemplate):
107
+ arch = "ltxv"
108
+ keys_detect = [
109
+ (
110
+ "adaln_single.emb.timestep_embedder.linear_2.weight",
111
+ "transformer_blocks.27.scale_shift_table",
112
+ "caption_projection.linear_2.weight",
113
+ )
114
+ ]
115
+ keys_hiprec = [
116
+ "scale_shift_table" # nn.parameter, can't load from BF16 base quant
117
+ ]
118
+
119
+ class ModelSDXL(ModelTemplate):
120
+ arch = "sdxl"
121
+ shape_fix = True
122
+ keys_detect = [
123
+ ("down_blocks.0.downsamplers.0.conv.weight", "add_embedding.linear_1.weight",),
124
+ (
125
+ "input_blocks.3.0.op.weight", "input_blocks.6.0.op.weight",
126
+ "output_blocks.2.2.conv.weight", "output_blocks.5.2.conv.weight",
127
+ ), # Non-diffusers
128
+ ("label_emb.0.0.weight",),
129
+ ]
130
+
131
+ class ModelSD1(ModelTemplate):
132
+ arch = "sd1"
133
+ shape_fix = True
134
+ keys_detect = [
135
+ ("down_blocks.0.downsamplers.0.conv.weight",),
136
+ (
137
+ "input_blocks.3.0.op.weight", "input_blocks.6.0.op.weight", "input_blocks.9.0.op.weight",
138
+ "output_blocks.2.1.conv.weight", "output_blocks.5.2.conv.weight", "output_blocks.8.2.conv.weight"
139
+ ), # Non-diffusers
140
+ ]
141
+
142
+ class ModelLumina2(ModelTemplate):
143
+ arch = "lumina2"
144
+ keys_detect = [
145
+ ("cap_embedder.1.weight", "context_refiner.0.attention.qkv.weight")
146
+ ]
147
+
148
+ arch_list = [ModelFlux, ModelSD3, ModelAura, ModelHiDream, CosmosPredict2,
149
+ ModelLTXV, ModelHyVid, ModelWan, ModelSDXL, ModelSD1, ModelLumina2]
150
+
151
+ def is_model_arch(model, state_dict):
152
+ # check if model is correct
153
+ matched = False
154
+ invalid = False
155
+ for match_list in model.keys_detect:
156
+ if all(key in state_dict for key in match_list):
157
+ matched = True
158
+ invalid = any(key in state_dict for key in model.keys_banned)
159
+ break
160
+ assert not invalid, "Model architecture not allowed for conversion! (i.e. reference VS diffusers format)"
161
+ return matched
162
+
163
+ def detect_arch(state_dict):
164
+ model_arch = None
165
+ for arch in arch_list:
166
+ if is_model_arch(arch, state_dict):
167
+ model_arch = arch()
168
+ break
169
+ assert model_arch is not None, "Unknown model architecture!"
170
+ return model_arch
171
+
172
+ def parse_args():
173
+ parser = argparse.ArgumentParser(description="Generate F16 GGUF files from single UNET")
174
+ parser.add_argument("--src", required=True, help="Source model ckpt file.")
175
+ parser.add_argument("--dst", help="Output unet gguf file.")
176
+ args = parser.parse_args()
177
+
178
+ if not os.path.isfile(args.src):
179
+ parser.error("No input provided!")
180
+
181
+ return args
182
+
183
+ def strip_prefix(state_dict):
184
+ # prefix for mixed state dict
185
+ prefix = None
186
+ for pfx in ["model.diffusion_model.", "model."]:
187
+ if any([x.startswith(pfx) for x in state_dict.keys()]):
188
+ prefix = pfx
189
+ break
190
+
191
+ # prefix for uniform state dict
192
+ if prefix is None:
193
+ for pfx in ["net."]:
194
+ if all([x.startswith(pfx) for x in state_dict.keys()]):
195
+ prefix = pfx
196
+ break
197
+
198
+ # strip prefix if found
199
+ if prefix is not None:
200
+ logging.info(f"State dict prefix found: '{prefix}'")
201
+ sd = {}
202
+ for k, v in state_dict.items():
203
+ if prefix not in k:
204
+ continue
205
+ k = k.replace(prefix, "")
206
+ sd[k] = v
207
+ else:
208
+ logging.debug("State dict has no prefix")
209
+ sd = state_dict
210
+
211
+ return sd
212
+
213
+ def load_state_dict(path):
214
+ if any(path.endswith(x) for x in [".ckpt", ".pt", ".bin", ".pth"]):
215
+ state_dict = torch.load(path, map_location="cpu", weights_only=True)
216
+ for subkey in ["model", "module"]:
217
+ if subkey in state_dict:
218
+ state_dict = state_dict[subkey]
219
+ break
220
+ if len(state_dict) < 20:
221
+ raise RuntimeError(f"pt subkey load failed: {state_dict.keys()}")
222
+ else:
223
+ state_dict = load_file(path)
224
+
225
+ return strip_prefix(state_dict)
226
+
227
+ def handle_tensors(writer, state_dict, model_arch):
228
+ name_lengths = tuple(sorted(
229
+ ((key, len(key)) for key in state_dict.keys()),
230
+ key=lambda item: item[1],
231
+ reverse=True,
232
+ ))
233
+ if not name_lengths:
234
+ return
235
+ max_name_len = name_lengths[0][1]
236
+ if max_name_len > MAX_TENSOR_NAME_LENGTH:
237
+ bad_list = ", ".join(f"{key!r} ({namelen})" for key, namelen in name_lengths if namelen > MAX_TENSOR_NAME_LENGTH)
238
+ raise ValueError(f"Can only handle tensor names up to {MAX_TENSOR_NAME_LENGTH} characters. Tensors exceeding the limit: {bad_list}")
239
+ for key, data in tqdm(state_dict.items()):
240
+ old_dtype = data.dtype
241
+
242
+ if any(x in key for x in model_arch.keys_ignore):
243
+ tqdm.write(f"Filtering ignored key: '{key}'")
244
+ continue
245
+
246
+ if data.dtype == torch.bfloat16:
247
+ data = data.to(torch.float32).numpy()
248
+ # this is so we don't break torch 2.0.X
249
+ elif data.dtype in [getattr(torch, "float8_e4m3fn", "_invalid"), getattr(torch, "float8_e5m2", "_invalid")]:
250
+ data = data.to(torch.float16).numpy()
251
+ else:
252
+ data = data.numpy()
253
+
254
+ n_dims = len(data.shape)
255
+ data_shape = data.shape
256
+ if old_dtype == torch.bfloat16:
257
+ data_qtype = gguf.GGMLQuantizationType.BF16
258
+ # elif old_dtype == torch.float32:
259
+ # data_qtype = gguf.GGMLQuantizationType.F32
260
+ else:
261
+ data_qtype = gguf.GGMLQuantizationType.F16
262
+
263
+ # The max no. of dimensions that can be handled by the quantization code is 4
264
+ if len(data.shape) > MAX_TENSOR_DIMS:
265
+ model_arch.handle_nd_tensor(key, data)
266
+ continue # needs to be added back later
267
+
268
+ # get number of parameters (AKA elements) in this tensor
269
+ n_params = 1
270
+ for dim_size in data_shape:
271
+ n_params *= dim_size
272
+
273
+ if old_dtype in (torch.float32, torch.bfloat16):
274
+ if n_dims == 1:
275
+ # one-dimensional tensors should be kept in F32
276
+ # also speeds up inference due to not dequantizing
277
+ data_qtype = gguf.GGMLQuantizationType.F32
278
+
279
+ elif n_params <= QUANTIZATION_THRESHOLD:
280
+ # very small tensors
281
+ data_qtype = gguf.GGMLQuantizationType.F32
282
+
283
+ elif any(x in key for x in model_arch.keys_hiprec):
284
+ # tensors that require max precision
285
+ data_qtype = gguf.GGMLQuantizationType.F32
286
+
287
+ if (model_arch.shape_fix # NEVER reshape for models such as flux
288
+ and n_dims > 1 # Skip one-dimensional tensors
289
+ and n_params >= REARRANGE_THRESHOLD # Only rearrange tensors meeting the size requirement
290
+ and (n_params / 256).is_integer() # Rearranging only makes sense if total elements is divisible by 256
291
+ and not (data.shape[-1] / 256).is_integer() # Only need to rearrange if the last dimension is not divisible by 256
292
+ ):
293
+ orig_shape = data.shape
294
+ data = data.reshape(n_params // 256, 256)
295
+ writer.add_array(f"comfy.gguf.orig_shape.{key}", tuple(int(dim) for dim in orig_shape))
296
+
297
+ try:
298
+ data = gguf.quants.quantize(data, data_qtype)
299
+ except (AttributeError, gguf.QuantError) as e:
300
+ tqdm.write(f"falling back to F16: {e}")
301
+ data_qtype = gguf.GGMLQuantizationType.F16
302
+ data = gguf.quants.quantize(data, data_qtype)
303
+
304
+ new_name = key # do we need to rename?
305
+
306
+ shape_str = f"{{{', '.join(str(n) for n in reversed(data.shape))}}}"
307
+ tqdm.write(f"{f'%-{max_name_len + 4}s' % f'{new_name}'} {old_dtype} --> {data_qtype.name}, shape = {shape_str}")
308
+
309
+ writer.add_tensor(new_name, data, raw_dtype=data_qtype)
310
+
311
+ def convert_file(path, dst_path=None, interact=True, overwrite=False):
312
+ # load & run model detection logic
313
+ state_dict = load_state_dict(path)
314
+ model_arch = detect_arch(state_dict)
315
+ logging.info(f"* Architecture detected from input: {model_arch.arch}")
316
+
317
+ # detect & set dtype for output file
318
+ dtypes = [x.dtype for x in state_dict.values()]
319
+ dtypes = {x:dtypes.count(x) for x in set(dtypes)}
320
+ main_dtype = max(dtypes, key=dtypes.get)
321
+
322
+ if main_dtype == torch.bfloat16:
323
+ ftype_name = "BF16"
324
+ ftype_gguf = gguf.LlamaFileType.MOSTLY_BF16
325
+ # elif main_dtype == torch.float32:
326
+ # ftype_name = "F32"
327
+ # ftype_gguf = None
328
+ else:
329
+ ftype_name = "F16"
330
+ ftype_gguf = gguf.LlamaFileType.MOSTLY_F16
331
+
332
+ if dst_path is None:
333
+ dst_path = f"{os.path.splitext(path)[0]}-{ftype_name}.gguf"
334
+ elif "{ftype}" in dst_path: # lcpp logic
335
+ dst_path = dst_path.replace("{ftype}", ftype_name)
336
+
337
+ if os.path.isfile(dst_path) and not overwrite:
338
+ if interact:
339
+ input("Output exists enter to continue or ctrl+c to abort!")
340
+ else:
341
+ raise OSError("Output exists and overwriting is disabled!")
342
+
343
+ # handle actual file
344
+ writer = gguf.GGUFWriter(path=None, arch=model_arch.arch)
345
+ writer.add_quantization_version(gguf.GGML_QUANT_VERSION)
346
+ if ftype_gguf is not None:
347
+ writer.add_file_type(ftype_gguf)
348
+
349
+ handle_tensors(writer, state_dict, model_arch)
350
+ writer.write_header_to_file(path=dst_path)
351
+ writer.write_kv_data_to_file()
352
+ writer.write_tensors_to_file(progress=True)
353
+ writer.close()
354
+
355
+ fix = f"./fix_5d_tensors_{model_arch.arch}.safetensors"
356
+ if os.path.isfile(fix):
357
+ logging.warning(f"\n### Warning! Fix file found at '{fix}'")
358
+ logging.warning(" you most likely need to run 'fix_5d_tensors.py' after quantization.")
359
+
360
+ return dst_path, model_arch
361
+
362
+ if __name__ == "__main__":
363
+ args = parse_args()
364
+ convert_file(args.src, args.dst)
365
+
custom_nodes/ComfyUI-GGUF/tools/fix_5d_tensors.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # (c) City96 || Apache-2.0 (apache.org/licenses/LICENSE-2.0)
2
+ import os
3
+ import gguf
4
+ import torch
5
+ import argparse
6
+ from tqdm import tqdm
7
+ from safetensors.torch import load_file
8
+
9
+ def get_args():
10
+ parser = argparse.ArgumentParser()
11
+ parser.add_argument("--src", required=True)
12
+ parser.add_argument("--dst", required=True)
13
+ parser.add_argument("--fix", required=False, help="Defaults to ./fix_5d_tensors_[arch].pt")
14
+ parser.add_argument("--overwrite", action="store_true")
15
+ args = parser.parse_args()
16
+
17
+ if not os.path.isfile(args.src):
18
+ parser.error(f"Invalid source file '{args.src}'")
19
+ if not args.overwrite and os.path.exists(args.dst):
20
+ parser.error(f"Output exists, use '--overwrite' ({args.dst})")
21
+
22
+ return args
23
+
24
+ def get_arch_str(reader):
25
+ field = reader.get_field("general.architecture")
26
+ return str(field.parts[field.data[-1]], encoding="utf-8")
27
+
28
+ def get_file_type(reader):
29
+ field = reader.get_field("general.file_type")
30
+ ft = int(field.parts[field.data[-1]])
31
+ return gguf.LlamaFileType(ft)
32
+
33
+ if __name__ == "__main__":
34
+ args = get_args()
35
+
36
+ # read existing
37
+ reader = gguf.GGUFReader(args.src)
38
+ arch = get_arch_str(reader)
39
+ file_type = get_file_type(reader)
40
+ print(f"Detected arch: '{arch}' (ftype: {str(file_type)})")
41
+
42
+ # prep fix
43
+ if args.fix is None:
44
+ args.fix = f"./fix_5d_tensors_{arch}.safetensors"
45
+
46
+ if not os.path.isfile(args.fix):
47
+ raise OSError(f"No 5D tensor fix file: {args.fix}")
48
+
49
+ sd5d = load_file(args.fix)
50
+ sd5d = {k:v.numpy() for k,v in sd5d.items()}
51
+ print("5D tensors:", sd5d.keys())
52
+
53
+ # prep output
54
+ writer = gguf.GGUFWriter(path=None, arch=arch)
55
+ writer.add_quantization_version(gguf.GGML_QUANT_VERSION)
56
+ writer.add_file_type(file_type)
57
+
58
+ added = []
59
+ def add_extra_key(writer, key, data):
60
+ global added
61
+ data_qtype = gguf.GGMLQuantizationType.F32
62
+ data = gguf.quants.quantize(data, data_qtype)
63
+ tqdm.write(f"Adding key {key} ({data.shape})")
64
+ writer.add_tensor(key, data, raw_dtype=data_qtype)
65
+ added.append(key)
66
+
67
+ # main loop to add missing 5D tensor(s)
68
+ for tensor in tqdm(reader.tensors):
69
+ writer.add_tensor(tensor.name, tensor.data, raw_dtype=tensor.tensor_type)
70
+ key5d = tensor.name.replace(".bias", ".weight")
71
+ if key5d in sd5d.keys():
72
+ add_extra_key(writer, key5d, sd5d[key5d])
73
+
74
+ # brute force for any missed
75
+ for key, data in sd5d.items():
76
+ if key not in added:
77
+ add_extra_key(writer, key, data)
78
+
79
+ writer.write_header_to_file(path=args.dst)
80
+ writer.write_kv_data_to_file()
81
+ writer.write_tensors_to_file(progress=True)
82
+ writer.close()
custom_nodes/ComfyUI-GGUF/tools/fix_lines_ending.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ files = ["lcpp.patch", "lcpp_sd3.patch"]
4
+
5
+ def has_unix_line_endings(file_path):
6
+ try:
7
+ with open(file_path, 'rb') as file:
8
+ content = file.read()
9
+ return b'\r\n' not in content
10
+ except Exception as e:
11
+ print(f"Error checking '{file_path}': {e}")
12
+ return False
13
+
14
+ def convert_to_linux_format(file_path):
15
+ try:
16
+ with open(file_path, 'rb') as file:
17
+ content = file.read().replace(b'\r\n', b'\n')
18
+ with open(file_path, 'wb') as file:
19
+ file.write(content)
20
+ print(f"'{file_path}' converted to Linux line endings (LF).")
21
+ except Exception as e:
22
+ print(f"Error processing '{file_path}': {e}")
23
+
24
+ for file in files:
25
+ if os.path.exists(file):
26
+ if has_unix_line_endings(file):
27
+ print(f"'{file}' already has Unix line endings (LF). No conversion needed.")
28
+ else:
29
+ convert_to_linux_format(file)
30
+ else:
31
+ print(f"File '{file}' does not exist.")
custom_nodes/ComfyUI-GGUF/tools/lcpp.patch ADDED
@@ -0,0 +1,451 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h
2
+ index de3c706f..0267c1fa 100644
3
+ --- a/ggml/include/ggml.h
4
+ +++ b/ggml/include/ggml.h
5
+ @@ -223,7 +223,7 @@
6
+ #define GGML_MAX_OP_PARAMS 64
7
+
8
+ #ifndef GGML_MAX_NAME
9
+ -# define GGML_MAX_NAME 64
10
+ +# define GGML_MAX_NAME 128
11
+ #endif
12
+
13
+ #define GGML_DEFAULT_N_THREADS 4
14
+ @@ -2449,6 +2449,7 @@ extern "C" {
15
+
16
+ // manage tensor info
17
+ GGML_API void gguf_add_tensor(struct gguf_context * ctx, const struct ggml_tensor * tensor);
18
+ + GGML_API void gguf_set_tensor_ndim(struct gguf_context * ctx, const char * name, int n_dim);
19
+ GGML_API void gguf_set_tensor_type(struct gguf_context * ctx, const char * name, enum ggml_type type);
20
+ GGML_API void gguf_set_tensor_data(struct gguf_context * ctx, const char * name, const void * data, size_t size);
21
+
22
+ diff --git a/ggml/src/ggml.c b/ggml/src/ggml.c
23
+ index b16c462f..6d1568f1 100644
24
+ --- a/ggml/src/ggml.c
25
+ +++ b/ggml/src/ggml.c
26
+ @@ -22960,6 +22960,14 @@ void gguf_add_tensor(
27
+ ctx->header.n_tensors++;
28
+ }
29
+
30
+ +void gguf_set_tensor_ndim(struct gguf_context * ctx, const char * name, const int n_dim) {
31
+ + const int idx = gguf_find_tensor(ctx, name);
32
+ + if (idx < 0) {
33
+ + GGML_ABORT("tensor not found");
34
+ + }
35
+ + ctx->infos[idx].n_dims = n_dim;
36
+ +}
37
+ +
38
+ void gguf_set_tensor_type(struct gguf_context * ctx, const char * name, enum ggml_type type) {
39
+ const int idx = gguf_find_tensor(ctx, name);
40
+ if (idx < 0) {
41
+ diff --git a/src/llama.cpp b/src/llama.cpp
42
+ index 24e1f1f0..25db4c69 100644
43
+ --- a/src/llama.cpp
44
+ +++ b/src/llama.cpp
45
+ @@ -205,6 +205,17 @@ enum llm_arch {
46
+ LLM_ARCH_GRANITE,
47
+ LLM_ARCH_GRANITE_MOE,
48
+ LLM_ARCH_CHAMELEON,
49
+ + LLM_ARCH_FLUX,
50
+ + LLM_ARCH_SD1,
51
+ + LLM_ARCH_SDXL,
52
+ + LLM_ARCH_SD3,
53
+ + LLM_ARCH_AURA,
54
+ + LLM_ARCH_LTXV,
55
+ + LLM_ARCH_HYVID,
56
+ + LLM_ARCH_WAN,
57
+ + LLM_ARCH_HIDREAM,
58
+ + LLM_ARCH_COSMOS,
59
+ + LLM_ARCH_LUMINA2,
60
+ LLM_ARCH_UNKNOWN,
61
+ };
62
+
63
+ @@ -258,6 +269,17 @@ static const std::map<llm_arch, const char *> LLM_ARCH_NAMES = {
64
+ { LLM_ARCH_GRANITE, "granite" },
65
+ { LLM_ARCH_GRANITE_MOE, "granitemoe" },
66
+ { LLM_ARCH_CHAMELEON, "chameleon" },
67
+ + { LLM_ARCH_FLUX, "flux" },
68
+ + { LLM_ARCH_SD1, "sd1" },
69
+ + { LLM_ARCH_SDXL, "sdxl" },
70
+ + { LLM_ARCH_SD3, "sd3" },
71
+ + { LLM_ARCH_AURA, "aura" },
72
+ + { LLM_ARCH_LTXV, "ltxv" },
73
+ + { LLM_ARCH_HYVID, "hyvid" },
74
+ + { LLM_ARCH_WAN, "wan" },
75
+ + { LLM_ARCH_HIDREAM, "hidream" },
76
+ + { LLM_ARCH_COSMOS, "cosmos" },
77
+ + { LLM_ARCH_LUMINA2, "lumina2" },
78
+ { LLM_ARCH_UNKNOWN, "(unknown)" },
79
+ };
80
+
81
+ @@ -1531,6 +1553,17 @@ static const std::map<llm_arch, std::map<llm_tensor, const char *>> LLM_TENSOR_N
82
+ { LLM_TENSOR_ATTN_K_NORM, "blk.%d.attn_k_norm" },
83
+ },
84
+ },
85
+ + { LLM_ARCH_FLUX, {}},
86
+ + { LLM_ARCH_SD1, {}},
87
+ + { LLM_ARCH_SDXL, {}},
88
+ + { LLM_ARCH_SD3, {}},
89
+ + { LLM_ARCH_AURA, {}},
90
+ + { LLM_ARCH_LTXV, {}},
91
+ + { LLM_ARCH_HYVID, {}},
92
+ + { LLM_ARCH_WAN, {}},
93
+ + { LLM_ARCH_HIDREAM, {}},
94
+ + { LLM_ARCH_COSMOS, {}},
95
+ + { LLM_ARCH_LUMINA2, {}},
96
+ {
97
+ LLM_ARCH_UNKNOWN,
98
+ {
99
+ @@ -5403,6 +5436,25 @@ static void llm_load_hparams(
100
+ // get general kv
101
+ ml.get_key(LLM_KV_GENERAL_NAME, model.name, false);
102
+
103
+ + // Disable LLM metadata for image models
104
+ + switch (model.arch) {
105
+ + case LLM_ARCH_FLUX:
106
+ + case LLM_ARCH_SD1:
107
+ + case LLM_ARCH_SDXL:
108
+ + case LLM_ARCH_SD3:
109
+ + case LLM_ARCH_AURA:
110
+ + case LLM_ARCH_LTXV:
111
+ + case LLM_ARCH_HYVID:
112
+ + case LLM_ARCH_WAN:
113
+ + case LLM_ARCH_HIDREAM:
114
+ + case LLM_ARCH_COSMOS:
115
+ + case LLM_ARCH_LUMINA2:
116
+ + model.ftype = ml.ftype;
117
+ + return;
118
+ + default:
119
+ + break;
120
+ + }
121
+ +
122
+ // get hparams kv
123
+ ml.get_key(LLM_KV_VOCAB_SIZE, hparams.n_vocab, false) || ml.get_arr_n(LLM_KV_TOKENIZER_LIST, hparams.n_vocab);
124
+
125
+ @@ -18016,6 +18068,134 @@ static void llama_tensor_dequantize_internal(
126
+ workers.clear();
127
+ }
128
+
129
+ +static ggml_type img_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
130
+ + // Special function for quantizing image model tensors
131
+ + const std::string name = ggml_get_name(tensor);
132
+ + const llm_arch arch = qs.model.arch;
133
+ +
134
+ + // Sanity check
135
+ + if (
136
+ + (name.find("model.diffusion_model.") != std::string::npos) ||
137
+ + (name.find("first_stage_model.") != std::string::npos) ||
138
+ + (name.find("single_transformer_blocks.") != std::string::npos) ||
139
+ + (name.find("joint_transformer_blocks.") != std::string::npos)
140
+ + ) {
141
+ + throw std::runtime_error("Invalid input GGUF file. This is not a supported UNET model");
142
+ + }
143
+ +
144
+ + // Unsupported quant types - exclude all IQ quants for now
145
+ + if (ftype == LLAMA_FTYPE_MOSTLY_IQ2_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ2_XS ||
146
+ + ftype == LLAMA_FTYPE_MOSTLY_IQ2_S || ftype == LLAMA_FTYPE_MOSTLY_IQ2_M ||
147
+ + ftype == LLAMA_FTYPE_MOSTLY_IQ3_XXS || ftype == LLAMA_FTYPE_MOSTLY_IQ1_S ||
148
+ + ftype == LLAMA_FTYPE_MOSTLY_IQ1_M || ftype == LLAMA_FTYPE_MOSTLY_IQ4_NL ||
149
+ + ftype == LLAMA_FTYPE_MOSTLY_IQ4_XS || ftype == LLAMA_FTYPE_MOSTLY_IQ3_S ||
150
+ + ftype == LLAMA_FTYPE_MOSTLY_IQ3_M || ftype == LLAMA_FTYPE_MOSTLY_Q4_0_4_4 ||
151
+ + ftype == LLAMA_FTYPE_MOSTLY_Q4_0_4_8 || ftype == LLAMA_FTYPE_MOSTLY_Q4_0_8_8) {
152
+ + throw std::runtime_error("Invalid quantization type for image model (Not supported)");
153
+ + }
154
+ +
155
+ + if ( // Rules for to_v attention
156
+ + (name.find("attn_v.weight") != std::string::npos) ||
157
+ + (name.find(".to_v.weight") != std::string::npos) ||
158
+ + (name.find(".v.weight") != std::string::npos) ||
159
+ + (name.find(".attn.w1v.weight") != std::string::npos) ||
160
+ + (name.find(".attn.w2v.weight") != std::string::npos) ||
161
+ + (name.find("_attn.v_proj.weight") != std::string::npos)
162
+ + ){
163
+ + if (ftype == LLAMA_FTYPE_MOSTLY_Q2_K) {
164
+ + new_type = GGML_TYPE_Q3_K;
165
+ + }
166
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
167
+ + new_type = qs.i_attention_wv < 2 ? GGML_TYPE_Q5_K : GGML_TYPE_Q4_K;
168
+ + }
169
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
170
+ + new_type = GGML_TYPE_Q5_K;
171
+ + }
172
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) {
173
+ + new_type = GGML_TYPE_Q6_K;
174
+ + }
175
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S && qs.i_attention_wv < 4) {
176
+ + new_type = GGML_TYPE_Q5_K;
177
+ + }
178
+ + ++qs.i_attention_wv;
179
+ + } else if ( // Rules for fused qkv attention
180
+ + (name.find("attn_qkv.weight") != std::string::npos) ||
181
+ + (name.find("attn.qkv.weight") != std::string::npos) ||
182
+ + (name.find("attention.qkv.weight") != std::string::npos)
183
+ + ) {
184
+ + if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M || ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
185
+ + new_type = GGML_TYPE_Q4_K;
186
+ + }
187
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
188
+ + new_type = GGML_TYPE_Q5_K;
189
+ + }
190
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) {
191
+ + new_type = GGML_TYPE_Q6_K;
192
+ + }
193
+ + } else if ( // Rules for ffn
194
+ + (name.find("ffn_down") != std::string::npos) ||
195
+ + ((name.find("experts.") != std::string::npos) && (name.find(".w2.weight") != std::string::npos)) ||
196
+ + (name.find(".ffn.2.weight") != std::string::npos) || // is this even the right way around?
197
+ + (name.find(".ff.net.2.weight") != std::string::npos) ||
198
+ + (name.find(".mlp.layer2.weight") != std::string::npos) ||
199
+ + (name.find(".adaln_modulation_mlp.2.weight") != std::string::npos) ||
200
+ + (name.find(".feed_forward.w2.weight") != std::string::npos)
201
+ + ) {
202
+ + // TODO: add back `layer_info` with some model specific logic + logic further down
203
+ + if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_M) {
204
+ + new_type = GGML_TYPE_Q4_K;
205
+ + }
206
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q3_K_L) {
207
+ + new_type = GGML_TYPE_Q5_K;
208
+ + }
209
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_S) {
210
+ + new_type = GGML_TYPE_Q5_K;
211
+ + }
212
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_K_M) {
213
+ + new_type = GGML_TYPE_Q6_K;
214
+ + }
215
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_K_M) {
216
+ + new_type = GGML_TYPE_Q6_K;
217
+ + }
218
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q4_0) {
219
+ + new_type = GGML_TYPE_Q4_1;
220
+ + }
221
+ + else if (ftype == LLAMA_FTYPE_MOSTLY_Q5_0) {
222
+ + new_type = GGML_TYPE_Q5_1;
223
+ + }
224
+ + ++qs.i_ffn_down;
225
+ + }
226
+ +
227
+ + // Sanity check for row shape
228
+ + bool convert_incompatible_tensor = false;
229
+ + if (new_type == GGML_TYPE_Q2_K || new_type == GGML_TYPE_Q3_K || new_type == GGML_TYPE_Q4_K ||
230
+ + new_type == GGML_TYPE_Q5_K || new_type == GGML_TYPE_Q6_K) {
231
+ + int nx = tensor->ne[0];
232
+ + int ny = tensor->ne[1];
233
+ + if (nx % QK_K != 0) {
234
+ + LLAMA_LOG_WARN("\n\n%s : tensor cols %d x %d are not divisible by %d, required for %s", __func__, nx, ny, QK_K, ggml_type_name(new_type));
235
+ + convert_incompatible_tensor = true;
236
+ + } else {
237
+ + ++qs.n_k_quantized;
238
+ + }
239
+ + }
240
+ + if (convert_incompatible_tensor) {
241
+ + // TODO: Possibly reenable this in the future
242
+ + // switch (new_type) {
243
+ + // case GGML_TYPE_Q2_K:
244
+ + // case GGML_TYPE_Q3_K:
245
+ + // case GGML_TYPE_Q4_K: new_type = GGML_TYPE_Q5_0; break;
246
+ + // case GGML_TYPE_Q5_K: new_type = GGML_TYPE_Q5_1; break;
247
+ + // case GGML_TYPE_Q6_K: new_type = GGML_TYPE_Q8_0; break;
248
+ + // default: throw std::runtime_error("\nUnsupported tensor size encountered\n");
249
+ + // }
250
+ + new_type = GGML_TYPE_F16;
251
+ + LLAMA_LOG_WARN(" - using fallback quantization %s\n", ggml_type_name(new_type));
252
+ + ++qs.n_fallback;
253
+ + }
254
+ + return new_type;
255
+ +}
256
+ +
257
+ static ggml_type llama_tensor_get_type(quantize_state_internal & qs, ggml_type new_type, const ggml_tensor * tensor, llama_ftype ftype) {
258
+ const std::string name = ggml_get_name(tensor);
259
+
260
+ @@ -18513,7 +18693,9 @@ static void llama_model_quantize_internal(const std::string & fname_inp, const s
261
+ if (llama_model_has_encoder(&model)) {
262
+ n_attn_layer *= 3;
263
+ }
264
+ - GGML_ASSERT((qs.n_attention_wv == n_attn_layer) && "n_attention_wv is unexpected");
265
+ + if (model.arch != LLM_ARCH_HYVID) { // TODO: Check why this fails
266
+ + GGML_ASSERT((qs.n_attention_wv == n_attn_layer) && "n_attention_wv is unexpected");
267
+ + }
268
+ }
269
+
270
+ size_t total_size_org = 0;
271
+ @@ -18547,6 +18729,51 @@ static void llama_model_quantize_internal(const std::string & fname_inp, const s
272
+ ctx_outs[i_split] = gguf_init_empty();
273
+ }
274
+ gguf_add_tensor(ctx_outs[i_split], tensor);
275
+ + // SD3 pos_embed needs special fix as first dim is 1, which gets truncated here
276
+ + if (model.arch == LLM_ARCH_SD3) {
277
+ + const std::string name = ggml_get_name(tensor);
278
+ + if (name == "pos_embed" && tensor->ne[2] == 1) {
279
+ + const int n_dim = 3;
280
+ + gguf_set_tensor_ndim(ctx_outs[i_split], "pos_embed", n_dim);
281
+ + LLAMA_LOG_INFO("\n%s: Correcting pos_embed shape for SD3: [key:%s]\n", __func__, tensor->name);
282
+ + }
283
+ + }
284
+ + // same goes for auraflow
285
+ + if (model.arch == LLM_ARCH_AURA) {
286
+ + const std::string name = ggml_get_name(tensor);
287
+ + if (name == "positional_encoding" && tensor->ne[2] == 1) {
288
+ + const int n_dim = 3;
289
+ + gguf_set_tensor_ndim(ctx_outs[i_split], "positional_encoding", n_dim);
290
+ + LLAMA_LOG_INFO("\n%s: Correcting positional_encoding shape for AuraFlow: [key:%s]\n", __func__, tensor->name);
291
+ + }
292
+ + if (name == "register_tokens" && tensor->ne[2] == 1) {
293
+ + const int n_dim = 3;
294
+ + gguf_set_tensor_ndim(ctx_outs[i_split], "register_tokens", n_dim);
295
+ + LLAMA_LOG_INFO("\n%s: Correcting register_tokens shape for AuraFlow: [key:%s]\n", __func__, tensor->name);
296
+ + }
297
+ + }
298
+ + // conv3d fails due to max dims - unsure what to do here as we never even reach this check
299
+ + if (model.arch == LLM_ARCH_HYVID) {
300
+ + const std::string name = ggml_get_name(tensor);
301
+ + if (name == "img_in.proj.weight" && tensor->ne[5] != 1 ) {
302
+ + throw std::runtime_error("img_in.proj.weight size failed for HyVid");
303
+ + }
304
+ + }
305
+ + // All the modulation layers also have dim1, and I think conv3d fails here too but we segfaul way before that...
306
+ + if (model.arch == LLM_ARCH_WAN) {
307
+ + const std::string name = ggml_get_name(tensor);
308
+ + if (name.find(".modulation") != std::string::npos && tensor->ne[2] == 1) {
309
+ + const int n_dim = 3;
310
+ + gguf_set_tensor_ndim(ctx_outs[i_split], tensor->name, n_dim);
311
+ + LLAMA_LOG_INFO("\n%s: Correcting shape for Wan: [key:%s]\n", __func__, tensor->name);
312
+ + }
313
+ + // FLF2V model only
314
+ + if (name == "img_emb.emb_pos") {
315
+ + const int n_dim = 3;
316
+ + gguf_set_tensor_ndim(ctx_outs[i_split], tensor->name, n_dim);
317
+ + LLAMA_LOG_INFO("\n%s: Correcting shape for Wan FLF2V: [key:%s]\n", __func__, tensor->name);
318
+ + }
319
+ + }
320
+ }
321
+
322
+ // Set split info if needed
323
+ @@ -18647,6 +18874,110 @@ static void llama_model_quantize_internal(const std::string & fname_inp, const s
324
+ // do not quantize relative position bias (T5)
325
+ quantize &= name.find("attn_rel_b.weight") == std::string::npos;
326
+
327
+ + // rules for image models
328
+ + bool image_model = false;
329
+ + if (model.arch == LLM_ARCH_FLUX) {
330
+ + image_model = true;
331
+ + quantize &= name.find("txt_in.") == std::string::npos;
332
+ + quantize &= name.find("img_in.") == std::string::npos;
333
+ + quantize &= name.find("time_in.") == std::string::npos;
334
+ + quantize &= name.find("vector_in.") == std::string::npos;
335
+ + quantize &= name.find("guidance_in.") == std::string::npos;
336
+ + quantize &= name.find("final_layer.") == std::string::npos;
337
+ + }
338
+ + if (model.arch == LLM_ARCH_SD1 || model.arch == LLM_ARCH_SDXL) {
339
+ + image_model = true;
340
+ + quantize &= name.find("class_embedding.") == std::string::npos;
341
+ + quantize &= name.find("time_embedding.") == std::string::npos;
342
+ + quantize &= name.find("add_embedding.") == std::string::npos;
343
+ + quantize &= name.find("time_embed.") == std::string::npos;
344
+ + quantize &= name.find("label_emb.") == std::string::npos;
345
+ + quantize &= name.find("conv_in.") == std::string::npos;
346
+ + quantize &= name.find("conv_out.") == std::string::npos;
347
+ + quantize &= name != "input_blocks.0.0.weight";
348
+ + quantize &= name != "out.2.weight";
349
+ + }
350
+ + if (model.arch == LLM_ARCH_SD3) {
351
+ + image_model = true;
352
+ + quantize &= name.find("final_layer.") == std::string::npos;
353
+ + quantize &= name.find("time_text_embed.") == std::string::npos;
354
+ + quantize &= name.find("context_embedder.") == std::string::npos;
355
+ + quantize &= name.find("t_embedder.") == std::string::npos;
356
+ + quantize &= name.find("y_embedder.") == std::string::npos;
357
+ + quantize &= name.find("x_embedder.") == std::string::npos;
358
+ + quantize &= name != "proj_out.weight";
359
+ + quantize &= name != "pos_embed";
360
+ + }
361
+ + if (model.arch == LLM_ARCH_AURA) {
362
+ + image_model = true;
363
+ + quantize &= name.find("t_embedder.") == std::string::npos;
364
+ + quantize &= name.find("init_x_linear.") == std::string::npos;
365
+ + quantize &= name != "modF.1.weight";
366
+ + quantize &= name != "cond_seq_linear.weight";
367
+ + quantize &= name != "final_linear.weight";
368
+ + quantize &= name != "final_linear.weight";
369
+ + quantize &= name != "positional_encoding";
370
+ + quantize &= name != "register_tokens";
371
+ + }
372
+ + if (model.arch == LLM_ARCH_LTXV) {
373
+ + image_model = true;
374
+ + quantize &= name.find("adaln_single.") == std::string::npos;
375
+ + quantize &= name.find("caption_projection.") == std::string::npos;
376
+ + quantize &= name.find("patchify_proj.") == std::string::npos;
377
+ + quantize &= name.find("proj_out.") == std::string::npos;
378
+ + quantize &= name.find("scale_shift_table") == std::string::npos; // last block too
379
+ + }
380
+ + if (model.arch == LLM_ARCH_HYVID) {
381
+ + image_model = true;
382
+ + quantize &= name.find("txt_in.") == std::string::npos;
383
+ + quantize &= name.find("img_in.") == std::string::npos;
384
+ + quantize &= name.find("time_in.") == std::string::npos;
385
+ + quantize &= name.find("vector_in.") == std::string::npos;
386
+ + quantize &= name.find("guidance_in.") == std::string::npos;
387
+ + quantize &= name.find("final_layer.") == std::string::npos;
388
+ + }
389
+ + if (model.arch == LLM_ARCH_WAN) {
390
+ + image_model = true;
391
+ + quantize &= name.find("modulation.") == std::string::npos;
392
+ + quantize &= name.find("patch_embedding.") == std::string::npos;
393
+ + quantize &= name.find("text_embedding.") == std::string::npos;
394
+ + quantize &= name.find("time_projection.") == std::string::npos;
395
+ + quantize &= name.find("time_embedding.") == std::string::npos;
396
+ + quantize &= name.find("img_emb.") == std::string::npos;
397
+ + quantize &= name.find("head.") == std::string::npos;
398
+ + }
399
+ + if (model.arch == LLM_ARCH_HIDREAM) {
400
+ + image_model = true;
401
+ + quantize &= name.find("p_embedder.") == std::string::npos;
402
+ + quantize &= name.find("t_embedder.") == std::string::npos;
403
+ + quantize &= name.find("x_embedder.") == std::string::npos;
404
+ + quantize &= name.find("final_layer.") == std::string::npos;
405
+ + quantize &= name.find(".ff_i.gate.weight") == std::string::npos;
406
+ + quantize &= name.find("caption_projection.") == std::string::npos;
407
+ + }
408
+ + if (model.arch == LLM_ARCH_COSMOS) {
409
+ + image_model = true;
410
+ + quantize &= name.find("p_embedder.") == std::string::npos;
411
+ + quantize &= name.find("t_embedder.") == std::string::npos;
412
+ + quantize &= name.find("t_embedding_norm.") == std::string::npos;
413
+ + quantize &= name.find("x_embedder.") == std::string::npos;
414
+ + quantize &= name.find("pos_embedder.") == std::string::npos;
415
+ + quantize &= name.find("final_layer.") == std::string::npos;
416
+ + }
417
+ + if (model.arch == LLM_ARCH_LUMINA2) {
418
+ + image_model = true;
419
+ + quantize &= name.find("t_embedder.") == std::string::npos;
420
+ + quantize &= name.find("x_embedder.") == std::string::npos;
421
+ + quantize &= name.find("final_layer.") == std::string::npos;
422
+ + quantize &= name.find("cap_embedder.") == std::string::npos;
423
+ + quantize &= name.find("context_refiner.") == std::string::npos;
424
+ + quantize &= name.find("noise_refiner.") == std::string::npos;
425
+ + }
426
+ + // ignore 3D/4D tensors for image models as the code was never meant to handle these
427
+ + if (image_model) {
428
+ + quantize &= ggml_n_dims(tensor) == 2;
429
+ + }
430
+ +
431
+ enum ggml_type new_type;
432
+ void * new_data;
433
+ size_t new_size;
434
+ @@ -18655,6 +18986,9 @@ static void llama_model_quantize_internal(const std::string & fname_inp, const s
435
+ new_type = default_type;
436
+
437
+ // get more optimal quantization type based on the tensor shape, layer, etc.
438
+ + if (image_model) {
439
+ + new_type = img_tensor_get_type(qs, new_type, tensor, ftype);
440
+ + } else {
441
+ if (!params->pure && ggml_is_quantized(default_type)) {
442
+ new_type = llama_tensor_get_type(qs, new_type, tensor, ftype);
443
+ }
444
+ @@ -18664,6 +18998,7 @@ static void llama_model_quantize_internal(const std::string & fname_inp, const s
445
+ if (params->output_tensor_type < GGML_TYPE_COUNT && strcmp(tensor->name, "output.weight") == 0) {
446
+ new_type = params->output_tensor_type;
447
+ }
448
+ + }
449
+
450
+ // If we've decided to quantize to the same type the tensor is already
451
+ // in then there's nothing to do.
custom_nodes/ComfyUI-GGUF/tools/read_tensors.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ import os
3
+ import sys
4
+ import gguf
5
+
6
+ def read_tensors(path):
7
+ reader = gguf.GGUFReader(path)
8
+ for tensor in reader.tensors:
9
+ if tensor.tensor_type == gguf.GGMLQuantizationType.F32:
10
+ continue
11
+ print(f"{str(tensor.tensor_type):32}: {tensor.name}")
12
+
13
+ try:
14
+ path = sys.argv[1]
15
+ assert os.path.isfile(path), "Invalid path"
16
+ print(f"input: {path}")
17
+ except Exception as e:
18
+ input(f"failed: {e}")
19
+ else:
20
+ read_tensors(path)
21
+ input()
custom_nodes/comfyui-kjnodes/.DS_Store ADDED
Binary file (6.15 kB). View file
 
custom_nodes/comfyui-kjnodes/.github/FUNDING.yml ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ github: [kijai]
2
+ custom: ["https://www.paypal.me/kijaidesign"]
custom_nodes/comfyui-kjnodes/.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 }}
custom_nodes/comfyui-kjnodes/.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
custom_nodes/comfyui-kjnodes/.tracking ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .github/FUNDING.yml
2
+ .github/workflows/publish.yml
3
+ .gitignore
4
+ LICENSE
5
+ README.md
6
+ __init__.py
7
+ custom_dimensions_example.json
8
+ docs/images/2024-04-03_20_49_29-ComfyUI.png
9
+ docs/images/319121566-05f66385-7568-4b1f-8bbc-11053660b02f.png
10
+ docs/images/319121636-706b5081-9120-4a29-bd76-901691ada688.png
11
+ example_workflows/leapfusion_hunyuuanvideo_i2v_native_testing.json
12
+ fonts/FreeMono.ttf
13
+ fonts/FreeMonoBoldOblique.otf
14
+ fonts/TTNorms-Black.otf
15
+ intrinsic_loras/intrinsic_lora_sd15_albedo.safetensors
16
+ intrinsic_loras/intrinsic_lora_sd15_depth.safetensors
17
+ intrinsic_loras/intrinsic_lora_sd15_normal.safetensors
18
+ intrinsic_loras/intrinsic_lora_sd15_shading.safetensors
19
+ intrinsic_loras/intrinsic_loras.txt
20
+ kjweb_async/marked.min.js
21
+ kjweb_async/protovis.min.js
22
+ kjweb_async/purify.min.js
23
+ kjweb_async/svg-path-properties.min.js
24
+ nodes/audioscheduler_nodes.py
25
+ nodes/batchcrop_nodes.py
26
+ nodes/curve_nodes.py
27
+ nodes/image_nodes.py
28
+ nodes/intrinsic_lora_nodes.py
29
+ nodes/lora_nodes.py
30
+ nodes/mask_nodes.py
31
+ nodes/model_optimization_nodes.py
32
+ nodes/nodes.py
33
+ pyproject.toml
34
+ requirements.txt
35
+ utility/fluid.py
36
+ utility/magictex.py
37
+ utility/numerical.py
38
+ utility/utility.py
39
+ web/green.png
40
+ web/js/appearance.js
41
+ web/js/browserstatus.js
42
+ web/js/contextmenu.js
43
+ web/js/fast_preview.js
44
+ web/js/help_popup.js
45
+ web/js/jsnodes.js
46
+ web/js/point_editor.js
47
+ web/js/setgetnodes.js
48
+ web/js/spline_editor.js
49
+ web/red.png
custom_nodes/comfyui-kjnodes/LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
custom_nodes/comfyui-kjnodes/README.md ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # KJNodes for ComfyUI
2
+
3
+ Various quality of life and masking related -nodes and scripts made by combining functionality of existing nodes for ComfyUI.
4
+
5
+ I know I'm bad at documentation, especially this project that has grown from random practice nodes to... too many lines in one file.
6
+ I have however started to add descriptions to the nodes themselves, there's a small ? you can click for info what the node does.
7
+ This is still work in progress, like everything else.
8
+
9
+ # Installation
10
+ 1. Clone this repo into `custom_nodes` folder.
11
+ 2. Install dependencies: `pip install -r requirements.txt`
12
+ or if you use the portable install, run this in ComfyUI_windows_portable -folder:
13
+
14
+ `python_embeded\python.exe -m pip install -r ComfyUI\custom_nodes\ComfyUI-KJNodes\requirements.txt`
15
+
16
+
17
+ ## Javascript
18
+
19
+ ### browserstatus.js
20
+ Sets the favicon to green circle when not processing anything, sets it to red when processing and shows progress percentage and the 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.
custom_nodes/comfyui-kjnodes/__init__.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "DownloadAndLoadCLIPSeg": {"class": DownloadAndLoadCLIPSeg, "name": "(Down)load CLIPSeg"},
26
+ "BatchCLIPSeg": {"class": BatchCLIPSeg, "name": "Batch CLIPSeg"},
27
+ "ColorToMask": {"class": ColorToMask, "name": "Color To Mask"},
28
+ "CreateGradientMask": {"class": CreateGradientMask, "name": "Create Gradient Mask"},
29
+ "CreateTextMask": {"class": CreateTextMask, "name": "Create Text Mask"},
30
+ "CreateAudioMask": {"class": CreateAudioMask, "name": "Create Audio Mask"},
31
+ "CreateFadeMask": {"class": CreateFadeMask, "name": "Create Fade Mask"},
32
+ "CreateFadeMaskAdvanced": {"class": CreateFadeMaskAdvanced, "name": "Create Fade Mask Advanced"},
33
+ "CreateFluidMask": {"class": CreateFluidMask, "name": "Create Fluid Mask"},
34
+ "CreateShapeMask": {"class": CreateShapeMask, "name": "Create Shape Mask"},
35
+ "CreateVoronoiMask": {"class": CreateVoronoiMask, "name": "Create Voronoi Mask"},
36
+ "CreateMagicMask": {"class": CreateMagicMask, "name": "Create Magic Mask"},
37
+ "GetMaskSizeAndCount": {"class": GetMaskSizeAndCount, "name": "Get Mask Size & Count"},
38
+ "GrowMaskWithBlur": {"class": GrowMaskWithBlur, "name": "Grow Mask With Blur"},
39
+ "MaskBatchMulti": {"class": MaskBatchMulti, "name": "Mask Batch Multi"},
40
+ "OffsetMask": {"class": OffsetMask, "name": "Offset Mask"},
41
+ "RemapMaskRange": {"class": RemapMaskRange, "name": "Remap Mask Range"},
42
+ "ResizeMask": {"class": ResizeMask, "name": "Resize Mask"},
43
+ "RoundMask": {"class": RoundMask, "name": "Round Mask"},
44
+ "SeparateMasks": {"class": SeparateMasks, "name": "Separate Masks"},
45
+ #images
46
+ "AddLabel": {"class": AddLabel, "name": "Add Label"},
47
+ "ColorMatch": {"class": ColorMatch, "name": "Color Match"},
48
+ "ImageTensorList": {"class": ImageTensorList, "name": "Image Tensor List"},
49
+ "CrossFadeImages": {"class": CrossFadeImages, "name": "Cross Fade Images"},
50
+ "CrossFadeImagesMulti": {"class": CrossFadeImagesMulti, "name": "Cross Fade Images Multi"},
51
+ "GetImagesFromBatchIndexed": {"class": GetImagesFromBatchIndexed, "name": "Get Images From Batch Indexed"},
52
+ "GetImageRangeFromBatch": {"class": GetImageRangeFromBatch, "name": "Get Image or Mask Range From Batch"},
53
+ "GetLatentRangeFromBatch": {"class": GetLatentRangeFromBatch, "name": "Get Latent Range From Batch"},
54
+ "GetLatentSizeAndCount": {"class": GetLatentSizeAndCount, "name": "Get Latent Size & Count"},
55
+ "GetImageSizeAndCount": {"class": GetImageSizeAndCount, "name": "Get Image Size & Count"},
56
+ "FastPreview": {"class": FastPreview, "name": "Fast Preview"},
57
+ "ImageBatchFilter": {"class": ImageBatchFilter, "name": "Image Batch Filter"},
58
+ "ImageAndMaskPreview": {"class": ImageAndMaskPreview},
59
+ "ImageAddMulti": {"class": ImageAddMulti, "name": "Image Add Multi"},
60
+ "ImageBatchJoinWithTransition": {"class": ImageBatchJoinWithTransition, "name": "Image Batch Join With Transition"},
61
+ "ImageBatchMulti": {"class": ImageBatchMulti, "name": "Image Batch Multi"},
62
+ "ImageBatchRepeatInterleaving": {"class": ImageBatchRepeatInterleaving},
63
+ "ImageBatchTestPattern": {"class": ImageBatchTestPattern, "name": "Image Batch Test Pattern"},
64
+ "ImageConcanate": {"class": ImageConcanate, "name": "Image Concatenate"},
65
+ "ImageConcatFromBatch": {"class": ImageConcatFromBatch, "name": "Image Concatenate From Batch"},
66
+ "ImageConcatMulti": {"class": ImageConcatMulti, "name": "Image Concatenate Multi"},
67
+ "ImageCropByMask": {"class": ImageCropByMask, "name": "Image Crop By Mask"},
68
+ "ImageCropByMaskAndResize": {"class": ImageCropByMaskAndResize, "name": "Image Crop By Mask And Resize"},
69
+ "ImageCropByMaskBatch": {"class": ImageCropByMaskBatch, "name": "Image Crop By Mask Batch"},
70
+ "ImageUncropByMask": {"class": ImageUncropByMask, "name": "Image Uncrop By Mask"},
71
+ "ImageGrabPIL": {"class": ImageGrabPIL, "name": "Image Grab PIL"},
72
+ "ImageGridComposite2x2": {"class": ImageGridComposite2x2, "name": "Image Grid Composite 2x2"},
73
+ "ImageGridComposite3x3": {"class": ImageGridComposite3x3, "name": "Image Grid Composite 3x3"},
74
+ "ImageGridtoBatch": {"class": ImageGridtoBatch, "name": "Image Grid To Batch"},
75
+ "ImageNoiseAugmentation": {"class": ImageNoiseAugmentation, "name": "Image Noise Augmentation"},
76
+ "ImageNormalize_Neg1_To_1": {"class": ImageNormalize_Neg1_To_1, "name": "Image Normalize -1 to 1"},
77
+ "ImagePass": {"class": ImagePass},
78
+ "ImagePadKJ": {"class": ImagePadKJ, "name": "ImagePad KJ"},
79
+ "ImagePadForOutpaintMasked": {"class": ImagePadForOutpaintMasked, "name": "Image Pad For Outpaint Masked"},
80
+ "ImagePadForOutpaintTargetSize": {"class": ImagePadForOutpaintTargetSize, "name": "Image Pad For Outpaint Target Size"},
81
+ "ImagePrepForICLora": {"class": ImagePrepForICLora, "name": "Image Prep For ICLora"},
82
+ "ImageResizeKJ": {"class": ImageResizeKJ, "name": "Resize Image (deprecated)"},
83
+ "ImageResizeKJv2": {"class": ImageResizeKJv2, "name": "Resize Image v2"},
84
+ "ImageUpscaleWithModelBatched": {"class": ImageUpscaleWithModelBatched, "name": "Image Upscale With Model Batched"},
85
+ "InsertImagesToBatchIndexed": {"class": InsertImagesToBatchIndexed, "name": "Insert Images To Batch Indexed"},
86
+ "InsertLatentToIndexed": {"class": InsertLatentToIndex, "name": "Insert Latent To Index"},
87
+ "LoadAndResizeImage": {"class": LoadAndResizeImage, "name": "Load & Resize Image"},
88
+ "LoadImagesFromFolderKJ": {"class": LoadImagesFromFolderKJ, "name": "Load Images From Folder (KJ)"},
89
+ "LoadVideosFromFolder": {"class": LoadVideosFromFolder, "name": "Load Videos From Folder"},
90
+ "MergeImageChannels": {"class": MergeImageChannels, "name": "Merge Image Channels"},
91
+ "PadImageBatchInterleaved": {"class": PadImageBatchInterleaved, "name": "Pad Image Batch Interleaved"},
92
+ "PreviewAnimation": {"class": PreviewAnimation, "name": "Preview Animation"},
93
+ "RemapImageRange": {"class": RemapImageRange, "name": "Remap Image Range"},
94
+ "ReverseImageBatch": {"class": ReverseImageBatch, "name": "Reverse Image Batch"},
95
+ "ReplaceImagesInBatch": {"class": ReplaceImagesInBatch, "name": "Replace Images In Batch"},
96
+ "SaveImageWithAlpha": {"class": SaveImageWithAlpha, "name": "Save Image With Alpha"},
97
+ "SaveImageKJ": {"class": SaveImageKJ, "name": "Save Image KJ"},
98
+ "ShuffleImageBatch": {"class": ShuffleImageBatch, "name": "Shuffle Image Batch"},
99
+ "SplitImageChannels": {"class": SplitImageChannels, "name": "Split Image Channels"},
100
+ "TransitionImagesMulti": {"class": TransitionImagesMulti, "name": "Transition Images Multi"},
101
+ "TransitionImagesInBatch": {"class": TransitionImagesInBatch, "name": "Transition Images In Batch"},
102
+ #batch cropping
103
+ "BatchCropFromMask": {"class": BatchCropFromMask, "name": "Batch Crop From Mask"},
104
+ "BatchCropFromMaskAdvanced": {"class": BatchCropFromMaskAdvanced, "name": "Batch Crop From Mask Advanced"},
105
+ "FilterZeroMasksAndCorrespondingImages": {"class": FilterZeroMasksAndCorrespondingImages},
106
+ "InsertImageBatchByIndexes": {"class": InsertImageBatchByIndexes, "name": "Insert Image Batch By Indexes"},
107
+ "BatchUncrop": {"class": BatchUncrop, "name": "Batch Uncrop"},
108
+ "BatchUncropAdvanced": {"class": BatchUncropAdvanced, "name": "Batch Uncrop Advanced"},
109
+ "SplitBboxes": {"class": SplitBboxes, "name": "Split Bboxes"},
110
+ "BboxToInt": {"class": BboxToInt, "name": "Bbox To Int"},
111
+ "BboxVisualize": {"class": BboxVisualize, "name": "Bbox Visualize"},
112
+ #noise
113
+ "GenerateNoise": {"class": GenerateNoise, "name": "Generate Noise"},
114
+ "FlipSigmasAdjusted": {"class": FlipSigmasAdjusted, "name": "Flip Sigmas Adjusted"},
115
+ "InjectNoiseToLatent": {"class": InjectNoiseToLatent, "name": "Inject Noise To Latent"},
116
+ "CustomSigmas": {"class": CustomSigmas, "name": "Custom Sigmas"},
117
+ #utility
118
+ "StringToFloatList": {"class": StringToFloatList, "name": "String to Float List"},
119
+ "WidgetToString": {"class": WidgetToString, "name": "Widget To String"},
120
+ "SaveStringKJ": {"class": SaveStringKJ, "name": "Save String KJ"},
121
+ "DummyOut": {"class": DummyOut, "name": "Dummy Out"},
122
+ "GetLatentsFromBatchIndexed": {"class": GetLatentsFromBatchIndexed, "name": "Get Latents From Batch Indexed"},
123
+ "ScaleBatchPromptSchedule": {"class": ScaleBatchPromptSchedule, "name": "Scale Batch Prompt Schedule"},
124
+ "CameraPoseVisualizer": {"class": CameraPoseVisualizer, "name": "Camera Pose Visualizer"},
125
+ "AppendStringsToList": {"class": AppendStringsToList, "name": "Append Strings To List"},
126
+ "JoinStrings": {"class": JoinStrings, "name": "Join Strings"},
127
+ "JoinStringMulti": {"class": JoinStringMulti, "name": "Join String Multi"},
128
+ "SomethingToString": {"class": SomethingToString, "name": "Something To String"},
129
+ "Sleep": {"class": Sleep, "name": "Sleep"},
130
+ "VRAM_Debug": {"class": VRAM_Debug, "name": "VRAM Debug"},
131
+ "SomethingToString": {"class": SomethingToString, "name": "Something To String"},
132
+ "EmptyLatentImagePresets": {"class": EmptyLatentImagePresets, "name": "Empty Latent Image Presets"},
133
+ "EmptyLatentImageCustomPresets": {"class": EmptyLatentImageCustomPresets, "name": "Empty Latent Image Custom Presets"},
134
+ "ModelPassThrough": {"class": ModelPassThrough, "name": "ModelPass"},
135
+ "ModelSaveKJ": {"class": ModelSaveKJ, "name": "Model Save KJ"},
136
+ "SetShakkerLabsUnionControlNetType": {"class": SetShakkerLabsUnionControlNetType, "name": "Set Shakker Labs Union ControlNet Type"},
137
+ "StyleModelApplyAdvanced": {"class": StyleModelApplyAdvanced, "name": "Style Model Apply Advanced"},
138
+ "DiffusionModelSelector": {"class": DiffusionModelSelector, "name": "Diffusion Model Selector"},
139
+ "LazySwitchKJ": {"class": LazySwitchKJ, "name": "Lazy Switch KJ"},
140
+ #audioscheduler stuff
141
+ "NormalizedAmplitudeToMask": {"class": NormalizedAmplitudeToMask},
142
+ "NormalizedAmplitudeToFloatList": {"class": NormalizedAmplitudeToFloatList},
143
+ "OffsetMaskByNormalizedAmplitude": {"class": OffsetMaskByNormalizedAmplitude},
144
+ "ImageTransformByNormalizedAmplitude": {"class": ImageTransformByNormalizedAmplitude},
145
+ "AudioConcatenate": {"class": AudioConcatenate},
146
+ #curve nodes
147
+ "SplineEditor": {"class": SplineEditor, "name": "Spline Editor"},
148
+ "CreateShapeImageOnPath": {"class": CreateShapeImageOnPath, "name": "Create Shape Image On Path"},
149
+ "CreateShapeMaskOnPath": {"class": CreateShapeMaskOnPath, "name": "Create Shape Mask On Path"},
150
+ "CreateTextOnPath": {"class": CreateTextOnPath, "name": "Create Text On Path"},
151
+ "CreateGradientFromCoords": {"class": CreateGradientFromCoords, "name": "Create Gradient From Coords"},
152
+ "CutAndDragOnPath": {"class": CutAndDragOnPath, "name": "Cut And Drag On Path"},
153
+ "GradientToFloat": {"class": GradientToFloat, "name": "Gradient To Float"},
154
+ "WeightScheduleExtend": {"class": WeightScheduleExtend, "name": "Weight Schedule Extend"},
155
+ "MaskOrImageToWeight": {"class": MaskOrImageToWeight, "name": "Mask Or Image To Weight"},
156
+ "WeightScheduleConvert": {"class": WeightScheduleConvert, "name": "Weight Schedule Convert"},
157
+ "FloatToMask": {"class": FloatToMask, "name": "Float To Mask"},
158
+ "FloatToSigmas": {"class": FloatToSigmas, "name": "Float To Sigmas"},
159
+ "SigmasToFloat": {"class": SigmasToFloat, "name": "Sigmas To Float"},
160
+ "PlotCoordinates": {"class": PlotCoordinates, "name": "Plot Coordinates"},
161
+ "InterpolateCoords": {"class": InterpolateCoords, "name": "Interpolate Coords"},
162
+ "PointsEditor": {"class": PointsEditor, "name": "Points Editor"},
163
+ #experimental
164
+ "SoundReactive": {"class": SoundReactive, "name": "Sound Reactive"},
165
+ "StableZero123_BatchSchedule": {"class": StableZero123_BatchSchedule, "name": "Stable Zero123 Batch Schedule"},
166
+ "SV3D_BatchSchedule": {"class": SV3D_BatchSchedule, "name": "SV3D Batch Schedule"},
167
+ "LoadResAdapterNormalization": {"class": LoadResAdapterNormalization},
168
+ "Superprompt": {"class": Superprompt, "name": "Superprompt"},
169
+ "GLIGENTextBoxApplyBatchCoords": {"class": GLIGENTextBoxApplyBatchCoords},
170
+ "Intrinsic_lora_sampling": {"class": Intrinsic_lora_sampling, "name": "Intrinsic Lora Sampling"},
171
+ "CheckpointPerturbWeights": {"class": CheckpointPerturbWeights, "name": "CheckpointPerturbWeights"},
172
+ "Screencap_mss": {"class": Screencap_mss, "name": "Screencap mss"},
173
+ "WebcamCaptureCV2": {"class": WebcamCaptureCV2, "name": "Webcam Capture CV2"},
174
+ "DifferentialDiffusionAdvanced": {"class": DifferentialDiffusionAdvanced, "name": "Differential Diffusion Advanced"},
175
+ "DiTBlockLoraLoader": {"class": DiTBlockLoraLoader, "name": "DiT Block Lora Loader"},
176
+ "FluxBlockLoraSelect": {"class": FluxBlockLoraSelect, "name": "Flux Block Lora Select"},
177
+ "HunyuanVideoBlockLoraSelect": {"class": HunyuanVideoBlockLoraSelect, "name": "Hunyuan Video Block Lora Select"},
178
+ "Wan21BlockLoraSelect": {"class": Wan21BlockLoraSelect, "name": "Wan21 Block Lora Select"},
179
+ "CustomControlNetWeightsFluxFromList": {"class": CustomControlNetWeightsFluxFromList, "name": "Custom ControlNet Weights Flux From List"},
180
+ "CheckpointLoaderKJ": {"class": CheckpointLoaderKJ, "name": "CheckpointLoaderKJ"},
181
+ "DiffusionModelLoaderKJ": {"class": DiffusionModelLoaderKJ, "name": "Diffusion Model Loader KJ"},
182
+ "TorchCompileModelFluxAdvanced": {"class": TorchCompileModelFluxAdvanced, "name": "TorchCompileModelFluxAdvanced"},
183
+ "TorchCompileModelFluxAdvancedV2": {"class": TorchCompileModelFluxAdvancedV2, "name": "TorchCompileModelFluxAdvancedV2"},
184
+ "TorchCompileModelHyVideo": {"class": TorchCompileModelHyVideo, "name": "TorchCompileModelHyVideo"},
185
+ "TorchCompileVAE": {"class": TorchCompileVAE, "name": "TorchCompileVAE"},
186
+ "TorchCompileControlNet": {"class": TorchCompileControlNet, "name": "TorchCompileControlNet"},
187
+ "PatchModelPatcherOrder": {"class": PatchModelPatcherOrder, "name": "Patch Model Patcher Order"},
188
+ "TorchCompileLTXModel": {"class": TorchCompileLTXModel, "name": "TorchCompileLTXModel"},
189
+ "TorchCompileCosmosModel": {"class": TorchCompileCosmosModel, "name": "TorchCompileCosmosModel"},
190
+ "TorchCompileModelQwenImage": {"class": TorchCompileModelQwenImage, "name": "TorchCompileModelQwenImage"},
191
+ "TorchCompileModelWanVideo": {"class": TorchCompileModelWanVideo, "name": "TorchCompileModelWanVideo"},
192
+ "TorchCompileModelWanVideoV2": {"class": TorchCompileModelWanVideoV2, "name": "TorchCompileModelWanVideoV2"},
193
+ "PathchSageAttentionKJ": {"class": PathchSageAttentionKJ, "name": "Patch Sage Attention KJ"},
194
+ "LeapfusionHunyuanI2VPatcher": {"class": LeapfusionHunyuanI2V, "name": "Leapfusion Hunyuan I2V Patcher"},
195
+ "VAELoaderKJ": {"class": VAELoaderKJ, "name": "VAELoader KJ"},
196
+ "ScheduledCFGGuidance": {"class": ScheduledCFGGuidance, "name": "Scheduled CFG Guidance"},
197
+ "ApplyRifleXRoPE_HunuyanVideo": {"class": ApplyRifleXRoPE_HunuyanVideo, "name": "Apply RifleXRoPE HunuyanVideo"},
198
+ "ApplyRifleXRoPE_WanVideo": {"class": ApplyRifleXRoPE_WanVideo, "name": "Apply RifleXRoPE WanVideo"},
199
+ "WanVideoTeaCacheKJ": {"class": WanVideoTeaCacheKJ, "name": "WanVideo Tea Cache (native)"},
200
+ "WanVideoEnhanceAVideoKJ": {"class": WanVideoEnhanceAVideoKJ, "name": "WanVideo Enhance A Video (native)"},
201
+ "SkipLayerGuidanceWanVideo": {"class": SkipLayerGuidanceWanVideo, "name": "Skip Layer Guidance WanVideo"},
202
+ "TimerNodeKJ": {"class": TimerNodeKJ, "name": "Timer Node KJ"},
203
+ "HunyuanVideoEncodeKeyframesToCond": {"class": HunyuanVideoEncodeKeyframesToCond, "name": "HunyuanVideo Encode Keyframes To Cond"},
204
+ "CFGZeroStarAndInit": {"class": CFGZeroStarAndInit, "name": "CFG Zero Star/Init"},
205
+ "ModelPatchTorchSettings": {"class": ModelPatchTorchSettings, "name": "Model Patch Torch Settings"},
206
+ "WanVideoNAG": {"class": WanVideoNAG, "name": "WanVideoNAG"},
207
+
208
+ #instance diffusion
209
+ "CreateInstanceDiffusionTracking": {"class": CreateInstanceDiffusionTracking},
210
+ "AppendInstanceDiffusionTracking": {"class": AppendInstanceDiffusionTracking},
211
+ "DrawInstanceDiffusionTracking": {"class": DrawInstanceDiffusionTracking},
212
+
213
+ #lora
214
+ "LoraExtractKJ": {"class": LoraExtractKJ, "name": "LoraExtractKJ"},
215
+ }
216
+
217
+ def generate_node_mappings(node_config):
218
+ node_class_mappings = {}
219
+ node_display_name_mappings = {}
220
+
221
+ for node_name, node_info in node_config.items():
222
+ node_class_mappings[node_name] = node_info["class"]
223
+ node_display_name_mappings[node_name] = node_info.get("name", node_info["class"].__name__)
224
+
225
+ return node_class_mappings, node_display_name_mappings
226
+
227
+ NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS = generate_node_mappings(NODE_CONFIG)
228
+
229
+ __all__ = ["NODE_CLASS_MAPPINGS", "NODE_DISPLAY_NAME_MAPPINGS", "WEB_DIRECTORY"]
230
+
231
+ WEB_DIRECTORY = "./web"
232
+
233
+ from aiohttp import web
234
+ from server import PromptServer
235
+ from pathlib import Path
236
+
237
+ if hasattr(PromptServer, "instance"):
238
+ try:
239
+ # NOTE: we add an extra static path to avoid comfy mechanism
240
+ # that loads every script in web.
241
+ PromptServer.instance.app.add_routes(
242
+ [web.static("/kjweb_async", (Path(__file__).parent.absolute() / "kjweb_async").as_posix())]
243
+ )
244
+ except:
245
+ pass
custom_nodes/comfyui-kjnodes/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
+ ]
custom_nodes/comfyui-kjnodes/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
custom_nodes/comfyui-kjnodes/docs/images/319121566-05f66385-7568-4b1f-8bbc-11053660b02f.png ADDED
custom_nodes/comfyui-kjnodes/docs/images/319121636-706b5081-9120-4a29-bd76-901691ada688.png ADDED
custom_nodes/comfyui-kjnodes/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
+ }
custom_nodes/comfyui-kjnodes/fonts/FreeMono.ttf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a7c692ad545c308b7b8fc2db770760c4a5d15ca50f12addf58c8f5360370e831
3
+ size 343980
custom_nodes/comfyui-kjnodes/fonts/FreeMonoBoldOblique.otf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:96187651ee033d0d9791dc2beeebfba5d1f070ab410fce1a5c16483ca249c588
3
+ size 237600
custom_nodes/comfyui-kjnodes/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
custom_nodes/comfyui-kjnodes/intrinsic_loras/intrinsic_lora_sd15_albedo.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d897f04ff2bb452e29a8f2a3c5c3cd5c55e95f314242cd645fbbe24a5ac59961
3
+ size 6416109
custom_nodes/comfyui-kjnodes/intrinsic_loras/intrinsic_lora_sd15_depth.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f199d6bf3180fe7271073c3769dcb764b40f35f41b30fcb183ae5bf4b6a9997f
3
+ size 6416109
custom_nodes/comfyui-kjnodes/intrinsic_loras/intrinsic_lora_sd15_normal.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:02934db0a0b92a9cdda402e42548560beda7d31b268e561dbc6815551e876268
3
+ size 6416109
custom_nodes/comfyui-kjnodes/intrinsic_loras/intrinsic_lora_sd15_shading.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:635e998063a10211633edd3e4b1676201822cd67f790ec71dba5f32d8b625c8b
3
+ size 6416109
custom_nodes/comfyui-kjnodes/intrinsic_loras/intrinsic_loras.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ source for the loras:
2
+ https://github.com/duxiaodan/intrinsic-lora
3
+
4
+ Renamed and conveted to .safetensors
custom_nodes/comfyui-kjnodes/kjweb_async/marked.min.js ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ /**
2
+ * marked v12.0.1 - a markdown parser
3
+ * Copyright (c) 2011-2024, Christopher Jeffrey. (MIT Licensed)
4
+ * https://github.com/markedjs/marked
5
+ */
6
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).marked={})}(this,(function(e){"use strict";function t(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}function n(t){e.defaults=t}e.defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};const s=/[&<>"']/,r=new RegExp(s.source,"g"),i=/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,l=new RegExp(i.source,"g"),o={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},a=e=>o[e];function c(e,t){if(t){if(s.test(e))return e.replace(r,a)}else if(i.test(e))return e.replace(l,a);return e}const h=/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/gi;function p(e){return e.replace(h,((e,t)=>"colon"===(t=t.toLowerCase())?":":"#"===t.charAt(0)?"x"===t.charAt(1)?String.fromCharCode(parseInt(t.substring(2),16)):String.fromCharCode(+t.substring(1)):""))}const u=/(^|[^\[])\^/g;function k(e,t){let n="string"==typeof e?e:e.source;t=t||"";const s={replace:(e,t)=>{let r="string"==typeof t?t:t.source;return r=r.replace(u,"$1"),n=n.replace(e,r),s},getRegex:()=>new RegExp(n,t)};return s}function g(e){try{e=encodeURI(e).replace(/%25/g,"%")}catch(e){return null}return e}const f={exec:()=>null};function d(e,t){const n=e.replace(/\|/g,((e,t,n)=>{let s=!1,r=t;for(;--r>=0&&"\\"===n[r];)s=!s;return s?"|":" |"})).split(/ \|/);let s=0;if(n[0].trim()||n.shift(),n.length>0&&!n[n.length-1].trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(/\\\|/g,"|");return n}function x(e,t,n){const s=e.length;if(0===s)return"";let r=0;for(;r<s;){const i=e.charAt(s-r-1);if(i!==t||n){if(i===t||!n)break;r++}else r++}return e.slice(0,s-r)}function b(e,t,n,s){const r=t.href,i=t.title?c(t.title):null,l=e[1].replace(/\\([\[\]])/g,"$1");if("!"!==e[0].charAt(0)){s.state.inLink=!0;const e={type:"link",raw:n,href:r,title:i,text:l,tokens:s.inlineTokens(l)};return s.state.inLink=!1,e}return{type:"image",raw:n,href:r,title:i,text:c(l)}}class w{options;rules;lexer;constructor(t){this.options=t||e.defaults}space(e){const t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){const t=this.rules.block.code.exec(e);if(t){const e=t[0].replace(/^ {1,4}/gm,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?e:x(e,"\n")}}}fences(e){const t=this.rules.block.fences.exec(e);if(t){const e=t[0],n=function(e,t){const n=e.match(/^(\s+)(?:```)/);if(null===n)return t;const s=n[1];return t.split("\n").map((e=>{const t=e.match(/^\s+/);if(null===t)return e;const[n]=t;return n.length>=s.length?e.slice(s.length):e})).join("\n")}(e,t[3]||"");return{type:"code",raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:n}}}heading(e){const t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(/#$/.test(e)){const t=x(e,"#");this.options.pedantic?e=t.trim():t&&!/ $/.test(t)||(e=t.trim())}return{type:"heading",raw:t[0],depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){const t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:t[0]}}blockquote(e){const t=this.rules.block.blockquote.exec(e);if(t){const e=x(t[0].replace(/^ *>[ \t]?/gm,""),"\n"),n=this.lexer.state.top;this.lexer.state.top=!0;const s=this.lexer.blockTokens(e);return this.lexer.state.top=n,{type:"blockquote",raw:t[0],tokens:s,text:e}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim();const s=n.length>1,r={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");const i=new RegExp(`^( {0,3}${n})((?:[\t ][^\\n]*)?(?:\\n|$))`);let l="",o="",a=!1;for(;e;){let n=!1;if(!(t=i.exec(e)))break;if(this.rules.block.hr.test(e))break;l=t[0],e=e.substring(l.length);let s=t[2].split("\n",1)[0].replace(/^\t+/,(e=>" ".repeat(3*e.length))),c=e.split("\n",1)[0],h=0;this.options.pedantic?(h=2,o=s.trimStart()):(h=t[2].search(/[^ ]/),h=h>4?1:h,o=s.slice(h),h+=t[1].length);let p=!1;if(!s&&/^ *$/.test(c)&&(l+=c+"\n",e=e.substring(c.length+1),n=!0),!n){const t=new RegExp(`^ {0,${Math.min(3,h-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ \t][^\\n]*)?(?:\\n|$))`),n=new RegExp(`^ {0,${Math.min(3,h-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),r=new RegExp(`^ {0,${Math.min(3,h-1)}}(?:\`\`\`|~~~)`),i=new RegExp(`^ {0,${Math.min(3,h-1)}}#`);for(;e;){const a=e.split("\n",1)[0];if(c=a,this.options.pedantic&&(c=c.replace(/^ {1,4}(?=( {4})*[^ ])/g," ")),r.test(c))break;if(i.test(c))break;if(t.test(c))break;if(n.test(e))break;if(c.search(/[^ ]/)>=h||!c.trim())o+="\n"+c.slice(h);else{if(p)break;if(s.search(/[^ ]/)>=4)break;if(r.test(s))break;if(i.test(s))break;if(n.test(s))break;o+="\n"+c}p||c.trim()||(p=!0),l+=a+"\n",e=e.substring(a.length+1),s=c.slice(h)}}r.loose||(a?r.loose=!0:/\n *\n *$/.test(l)&&(a=!0));let u,k=null;this.options.gfm&&(k=/^\[[ xX]\] /.exec(o),k&&(u="[ ] "!==k[0],o=o.replace(/^\[[ xX]\] +/,""))),r.items.push({type:"list_item",raw:l,task:!!k,checked:u,loose:!1,text:o,tokens:[]}),r.raw+=l}r.items[r.items.length-1].raw=l.trimEnd(),r.items[r.items.length-1].text=o.trimEnd(),r.raw=r.raw.trimEnd();for(let e=0;e<r.items.length;e++)if(this.lexer.state.top=!1,r.items[e].tokens=this.lexer.blockTokens(r.items[e].text,[]),!r.loose){const t=r.items[e].tokens.filter((e=>"space"===e.type)),n=t.length>0&&t.some((e=>/\n.*\n/.test(e.raw)));r.loose=n}if(r.loose)for(let e=0;e<r.items.length;e++)r.items[e].loose=!0;return r}}html(e){const t=this.rules.block.html.exec(e);if(t){return{type:"html",block:!0,raw:t[0],pre:"pre"===t[1]||"script"===t[1]||"style"===t[1],text:t[0]}}}def(e){const t=this.rules.block.def.exec(e);if(t){const e=t[1].toLowerCase().replace(/\s+/g," "),n=t[2]?t[2].replace(/^<(.*)>$/,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",s=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:e,raw:t[0],href:n,title:s}}}table(e){const t=this.rules.block.table.exec(e);if(!t)return;if(!/[:|]/.test(t[2]))return;const n=d(t[1]),s=t[2].replace(/^\||\| *$/g,"").split("|"),r=t[3]&&t[3].trim()?t[3].replace(/\n[ \t]*$/,"").split("\n"):[],i={type:"table",raw:t[0],header:[],align:[],rows:[]};if(n.length===s.length){for(const e of s)/^ *-+: *$/.test(e)?i.align.push("right"):/^ *:-+: *$/.test(e)?i.align.push("center"):/^ *:-+ *$/.test(e)?i.align.push("left"):i.align.push(null);for(const e of n)i.header.push({text:e,tokens:this.lexer.inline(e)});for(const e of r)i.rows.push(d(e,i.header.length).map((e=>({text:e,tokens:this.lexer.inline(e)}))));return i}}lheading(e){const t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:"="===t[2].charAt(0)?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}paragraph(e){const t=this.rules.block.paragraph.exec(e);if(t){const e="\n"===t[1].charAt(t[1].length-1)?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:e,tokens:this.lexer.inline(e)}}}text(e){const t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){const t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:c(t[1])}}tag(e){const t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&/^<a /i.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&/^<\/a>/i.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&/^<(pre|code|kbd|script)(\s|>)/i.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&/^<\/(pre|code|kbd|script)(\s|>)/i.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){const t=this.rules.inline.link.exec(e);if(t){const e=t[2].trim();if(!this.options.pedantic&&/^</.test(e)){if(!/>$/.test(e))return;const t=x(e.slice(0,-1),"\\");if((e.length-t.length)%2==0)return}else{const e=function(e,t){if(-1===e.indexOf(t[1]))return-1;let n=0;for(let s=0;s<e.length;s++)if("\\"===e[s])s++;else if(e[s]===t[0])n++;else if(e[s]===t[1]&&(n--,n<0))return s;return-1}(t[2],"()");if(e>-1){const n=(0===t[0].indexOf("!")?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=""}}let n=t[2],s="";if(this.options.pedantic){const e=/^([^'"]*[^\s])\s+(['"])(.*)\2/.exec(n);e&&(n=e[1],s=e[3])}else s=t[3]?t[3].slice(1,-1):"";return n=n.trim(),/^</.test(n)&&(n=this.options.pedantic&&!/>$/.test(e)?n.slice(1):n.slice(1,-1)),b(t,{href:n?n.replace(this.rules.inline.anyPunctuation,"$1"):n,title:s?s.replace(this.rules.inline.anyPunctuation,"$1"):s},t[0],this.lexer)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){const e=t[(n[2]||n[1]).replace(/\s+/g," ").toLowerCase()];if(!e){const e=n[0].charAt(0);return{type:"text",raw:e,text:e}}return b(n,e,n[0],this.lexer)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s)return;if(s[3]&&n.match(/[\p{L}\p{N}]/u))return;if(!(s[1]||s[2]||"")||!n||this.rules.inline.punctuation.exec(n)){const n=[...s[0]].length-1;let r,i,l=n,o=0;const a="*"===s[0][0]?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(a.lastIndex=0,t=t.slice(-1*e.length+n);null!=(s=a.exec(t));){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(i=[...r].length,s[3]||s[4]){l+=i;continue}if((s[5]||s[6])&&n%3&&!((n+i)%3)){o+=i;continue}if(l-=i,l>0)continue;i=Math.min(i,i+l+o);const t=[...s[0]][0].length,a=e.slice(0,n+s.index+t+i);if(Math.min(n,i)%2){const e=a.slice(1,-1);return{type:"em",raw:a,text:e,tokens:this.lexer.inlineTokens(e)}}const c=a.slice(2,-2);return{type:"strong",raw:a,text:c,tokens:this.lexer.inlineTokens(c)}}}}codespan(e){const t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(/\n/g," ");const n=/[^ ]/.test(e),s=/^ /.test(e)&&/ $/.test(e);return n&&s&&(e=e.substring(1,e.length-1)),e=c(e,!0),{type:"codespan",raw:t[0],text:e}}}br(e){const t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e){const t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}autolink(e){const t=this.rules.inline.autolink.exec(e);if(t){let e,n;return"@"===t[2]?(e=c(t[1]),n="mailto:"+e):(e=c(t[1]),n=e),{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if("@"===t[2])e=c(t[0]),n="mailto:"+e;else{let s;do{s=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??""}while(s!==t[0]);e=c(t[0]),n="www."===t[1]?"http://"+t[0]:t[0]}return{type:"link",raw:t[0],text:e,href:n,tokens:[{type:"text",raw:e,text:e}]}}}inlineText(e){const t=this.rules.inline.text.exec(e);if(t){let e;return e=this.lexer.state.inRawBlock?t[0]:c(t[0]),{type:"text",raw:t[0],text:e}}}}const m=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,y=/(?:[*+-]|\d{1,9}[.)])/,$=k(/^(?!bull |blockCode|fences|blockquote|heading|html)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html))+?)\n {0,3}(=+|-+) *(?:\n+|$)/).replace(/bull/g,y).replace(/blockCode/g,/ {4}/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).getRegex(),z=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,T=/(?!\s*\])(?:\\.|[^\[\]\\])+/,R=k(/^ {0,3}\[(label)\]: *(?:\n *)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n *)?| *\n *)(title))? *(?:\n+|$)/).replace("label",T).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),_=k(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,y).getRegex(),A="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",S=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,I=k("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|<![A-Z][\\s\\S]*?(?:>\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>\\n*|$)|</?(tag)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n *)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n *)+\\n|$))","i").replace("comment",S).replace("tag",A).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),E=k(z).replace("hr",m).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex(),q={blockquote:k(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",E).getRegex(),code:/^( {4}[^\n]+(?:\n(?: *(?:\n|$))*)?)+/,def:R,fences:/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,heading:/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,hr:m,html:I,lheading:$,list:_,newline:/^(?: *(?:\n|$))+/,paragraph:E,table:f,text:/^[^\n]+/},Z=k("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",m).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code"," {4}[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex(),L={...q,table:Z,paragraph:k(z).replace("hr",m).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Z).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html","</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)").replace("tag",A).getRegex()},P={...q,html:k("^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\s[^'\"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))").replace("comment",S).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:f,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:k(z).replace("hr",m).replace("heading"," *#{1,6} *[^\n]").replace("lheading",$).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Q=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,v=/^( {2,}|\\)\n(?!\s*$)/,B="\\p{P}\\p{S}",C=k(/^((?![*_])[\spunctuation])/,"u").replace(/punctuation/g,B).getRegex(),M=k(/^(?:\*+(?:((?!\*)[punct])|[^\s*]))|^_+(?:((?!_)[punct])|([^\s_]))/,"u").replace(/punct/g,B).getRegex(),O=k("^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)[punct](\\*+)(?=[\\s]|$)|[^punct\\s](\\*+)(?!\\*)(?=[punct\\s]|$)|(?!\\*)[punct\\s](\\*+)(?=[^punct\\s])|[\\s](\\*+)(?!\\*)(?=[punct])|(?!\\*)[punct](\\*+)(?!\\*)(?=[punct])|[^punct\\s](\\*+)(?=[^punct\\s])","gu").replace(/punct/g,B).getRegex(),D=k("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)[punct](_+)(?=[\\s]|$)|[^punct\\s](_+)(?!_)(?=[punct\\s]|$)|(?!_)[punct\\s](_+)(?=[^punct\\s])|[\\s](_+)(?!_)(?=[punct])|(?!_)[punct](_+)(?!_)(?=[punct])","gu").replace(/punct/g,B).getRegex(),j=k(/\\([punct])/,"gu").replace(/punct/g,B).getRegex(),H=k(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),U=k(S).replace("(?:--\x3e|$)","--\x3e").getRegex(),X=k("^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",U).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),F=/(?:\[(?:\\.|[^\[\]\\])*\]|\\.|`[^`]*`|[^\[\]\\`])*?/,N=k(/^!?\[(label)\]\(\s*(href)(?:\s+(title))?\s*\)/).replace("label",F).replace("href",/<(?:\\.|[^\n<>\\])+>|[^\s\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),G=k(/^!?\[(label)\]\[(ref)\]/).replace("label",F).replace("ref",T).getRegex(),J=k(/^!?\[(ref)\](?:\[\])?/).replace("ref",T).getRegex(),K={_backpedal:f,anyPunctuation:j,autolink:H,blockSkip:/\[[^[\]]*?\]\([^\(\)]*?\)|`[^`]*?`|<[^<>]*?>/g,br:v,code:/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,del:f,emStrongLDelim:M,emStrongRDelimAst:O,emStrongRDelimUnd:D,escape:Q,link:N,nolink:J,punctuation:C,reflink:G,reflinkSearch:k("reflink|nolink(?!\\()","g").replace("reflink",G).replace("nolink",J).getRegex(),tag:X,text:/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,url:f},V={...K,link:k(/^!?\[(label)\]\((.*?)\)/).replace("label",F).getRegex(),reflink:k(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",F).getRegex()},W={...K,escape:k(Q).replace("])","~|])").getRegex(),url:k(/^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/,"i").replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])([\s\S]*?[^\s~])\1(?=[^~]|$)/,text:/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/},Y={...W,br:k(v).replace("{2,}","*").getRegex(),text:k(W.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},ee={normal:q,gfm:L,pedantic:P},te={normal:K,gfm:W,breaks:Y,pedantic:V};class ne{tokens;options;state;tokenizer;inlineQueue;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||e.defaults,this.options.tokenizer=this.options.tokenizer||new w,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};const n={block:ee.normal,inline:te.normal};this.options.pedantic?(n.block=ee.pedantic,n.inline=te.pedantic):this.options.gfm&&(n.block=ee.gfm,this.options.breaks?n.inline=te.breaks:n.inline=te.gfm),this.tokenizer.rules=n}static get rules(){return{block:ee,inline:te}}static lex(e,t){return new ne(t).lex(e)}static lexInline(e,t){return new ne(t).inlineTokens(e)}lex(e){e=e.replace(/\r\n|\r/g,"\n"),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){const t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[]){let n,s,r,i;for(e=this.options.pedantic?e.replace(/\t/g," ").replace(/^ +$/gm,""):e.replace(/^( *)(\t+)/gm,((e,t,n)=>t+" ".repeat(n.length)));e;)if(!(this.options.extensions&&this.options.extensions.block&&this.options.extensions.block.some((s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.space(e))e=e.substring(n.raw.length),1===n.raw.length&&t.length>0?t[t.length-1].raw+="\n":t.push(n);else if(n=this.tokenizer.code(e))e=e.substring(n.raw.length),s=t[t.length-1],!s||"paragraph"!==s.type&&"text"!==s.type?t.push(n):(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue[this.inlineQueue.length-1].src=s.text);else if(n=this.tokenizer.fences(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.heading(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.hr(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.blockquote(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.list(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.html(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.def(e))e=e.substring(n.raw.length),s=t[t.length-1],!s||"paragraph"!==s.type&&"text"!==s.type?this.tokens.links[n.tag]||(this.tokens.links[n.tag]={href:n.href,title:n.title}):(s.raw+="\n"+n.raw,s.text+="\n"+n.raw,this.inlineQueue[this.inlineQueue.length-1].src=s.text);else if(n=this.tokenizer.table(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.lheading(e))e=e.substring(n.raw.length),t.push(n);else{if(r=e,this.options.extensions&&this.options.extensions.startBlock){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startBlock.forEach((e=>{s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(this.state.top&&(n=this.tokenizer.paragraph(r)))s=t[t.length-1],i&&"paragraph"===s.type?(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s.text):t.push(n),i=r.length!==e.length,e=e.substring(n.raw.length);else if(n=this.tokenizer.text(e))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===s.type?(s.raw+="\n"+n.raw,s.text+="\n"+n.text,this.inlineQueue.pop(),this.inlineQueue[this.inlineQueue.length-1].src=s.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){let n,s,r,i,l,o,a=e;if(this.tokens.links){const e=Object.keys(this.tokens.links);if(e.length>0)for(;null!=(i=this.tokenizer.rules.inline.reflinkSearch.exec(a));)e.includes(i[0].slice(i[0].lastIndexOf("[")+1,-1))&&(a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;null!=(i=this.tokenizer.rules.inline.blockSkip.exec(a));)a=a.slice(0,i.index)+"["+"a".repeat(i[0].length-2)+"]"+a.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);for(;null!=(i=this.tokenizer.rules.inline.anyPunctuation.exec(a));)a=a.slice(0,i.index)+"++"+a.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);for(;e;)if(l||(o=""),l=!1,!(this.options.extensions&&this.options.extensions.inline&&this.options.extensions.inline.some((s=>!!(n=s.call({lexer:this},e,t))&&(e=e.substring(n.raw.length),t.push(n),!0)))))if(n=this.tokenizer.escape(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.tag(e))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.link(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.reflink(e,this.tokens.links))e=e.substring(n.raw.length),s=t[t.length-1],s&&"text"===n.type&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(n=this.tokenizer.emStrong(e,a,o))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.codespan(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.br(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.del(e))e=e.substring(n.raw.length),t.push(n);else if(n=this.tokenizer.autolink(e))e=e.substring(n.raw.length),t.push(n);else if(this.state.inLink||!(n=this.tokenizer.url(e))){if(r=e,this.options.extensions&&this.options.extensions.startInline){let t=1/0;const n=e.slice(1);let s;this.options.extensions.startInline.forEach((e=>{s=e.call({lexer:this},n),"number"==typeof s&&s>=0&&(t=Math.min(t,s))})),t<1/0&&t>=0&&(r=e.substring(0,t+1))}if(n=this.tokenizer.inlineText(r))e=e.substring(n.raw.length),"_"!==n.raw.slice(-1)&&(o=n.raw.slice(-1)),l=!0,s=t[t.length-1],s&&"text"===s.type?(s.raw+=n.raw,s.text+=n.text):t.push(n);else if(e){const t="Infinite loop on byte: "+e.charCodeAt(0);if(this.options.silent){console.error(t);break}throw new Error(t)}}else e=e.substring(n.raw.length),t.push(n);return t}}class se{options;constructor(t){this.options=t||e.defaults}code(e,t,n){const s=(t||"").match(/^\S*/)?.[0];return e=e.replace(/\n$/,"")+"\n",s?'<pre><code class="language-'+c(s)+'">'+(n?e:c(e,!0))+"</code></pre>\n":"<pre><code>"+(n?e:c(e,!0))+"</code></pre>\n"}blockquote(e){return`<blockquote>\n${e}</blockquote>\n`}html(e,t){return e}heading(e,t,n){return`<h${t}>${e}</h${t}>\n`}hr(){return"<hr>\n"}list(e,t,n){const s=t?"ol":"ul";return"<"+s+(t&&1!==n?' start="'+n+'"':"")+">\n"+e+"</"+s+">\n"}listitem(e,t,n){return`<li>${e}</li>\n`}checkbox(e){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox">'}paragraph(e){return`<p>${e}</p>\n`}table(e,t){return t&&(t=`<tbody>${t}</tbody>`),"<table>\n<thead>\n"+e+"</thead>\n"+t+"</table>\n"}tablerow(e){return`<tr>\n${e}</tr>\n`}tablecell(e,t){const n=t.header?"th":"td";return(t.align?`<${n} align="${t.align}">`:`<${n}>`)+e+`</${n}>\n`}strong(e){return`<strong>${e}</strong>`}em(e){return`<em>${e}</em>`}codespan(e){return`<code>${e}</code>`}br(){return"<br>"}del(e){return`<del>${e}</del>`}link(e,t,n){const s=g(e);if(null===s)return n;let r='<a href="'+(e=s)+'"';return t&&(r+=' title="'+t+'"'),r+=">"+n+"</a>",r}image(e,t,n){const s=g(e);if(null===s)return n;let r=`<img src="${e=s}" alt="${n}"`;return t&&(r+=` title="${t}"`),r+=">",r}text(e){return e}}class re{strong(e){return e}em(e){return e}codespan(e){return e}del(e){return e}html(e){return e}text(e){return e}link(e,t,n){return""+n}image(e,t,n){return""+n}br(){return""}}class ie{options;renderer;textRenderer;constructor(t){this.options=t||e.defaults,this.options.renderer=this.options.renderer||new se,this.renderer=this.options.renderer,this.renderer.options=this.options,this.textRenderer=new re}static parse(e,t){return new ie(t).parse(e)}static parseInline(e,t){return new ie(t).parseInline(e)}parse(e,t=!0){let n="";for(let s=0;s<e.length;s++){const r=e[s];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[r.type]){const e=r,t=this.options.extensions.renderers[e.type].call({parser:this},e);if(!1!==t||!["space","hr","heading","code","table","blockquote","list","html","paragraph","text"].includes(e.type)){n+=t||"";continue}}switch(r.type){case"space":continue;case"hr":n+=this.renderer.hr();continue;case"heading":{const e=r;n+=this.renderer.heading(this.parseInline(e.tokens),e.depth,p(this.parseInline(e.tokens,this.textRenderer)));continue}case"code":{const e=r;n+=this.renderer.code(e.text,e.lang,!!e.escaped);continue}case"table":{const e=r;let t="",s="";for(let t=0;t<e.header.length;t++)s+=this.renderer.tablecell(this.parseInline(e.header[t].tokens),{header:!0,align:e.align[t]});t+=this.renderer.tablerow(s);let i="";for(let t=0;t<e.rows.length;t++){const n=e.rows[t];s="";for(let t=0;t<n.length;t++)s+=this.renderer.tablecell(this.parseInline(n[t].tokens),{header:!1,align:e.align[t]});i+=this.renderer.tablerow(s)}n+=this.renderer.table(t,i);continue}case"blockquote":{const e=r,t=this.parse(e.tokens);n+=this.renderer.blockquote(t);continue}case"list":{const e=r,t=e.ordered,s=e.start,i=e.loose;let l="";for(let t=0;t<e.items.length;t++){const n=e.items[t],s=n.checked,r=n.task;let o="";if(n.task){const e=this.renderer.checkbox(!!s);i?n.tokens.length>0&&"paragraph"===n.tokens[0].type?(n.tokens[0].text=e+" "+n.tokens[0].text,n.tokens[0].tokens&&n.tokens[0].tokens.length>0&&"text"===n.tokens[0].tokens[0].type&&(n.tokens[0].tokens[0].text=e+" "+n.tokens[0].tokens[0].text)):n.tokens.unshift({type:"text",text:e+" "}):o+=e+" "}o+=this.parse(n.tokens,i),l+=this.renderer.listitem(o,r,!!s)}n+=this.renderer.list(l,t,s);continue}case"html":{const e=r;n+=this.renderer.html(e.text,e.block);continue}case"paragraph":{const e=r;n+=this.renderer.paragraph(this.parseInline(e.tokens));continue}case"text":{let i=r,l=i.tokens?this.parseInline(i.tokens):i.text;for(;s+1<e.length&&"text"===e[s+1].type;)i=e[++s],l+="\n"+(i.tokens?this.parseInline(i.tokens):i.text);n+=t?this.renderer.paragraph(l):l;continue}default:{const e='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}parseInline(e,t){t=t||this.renderer;let n="";for(let s=0;s<e.length;s++){const r=e[s];if(this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[r.type]){const e=this.options.extensions.renderers[r.type].call({parser:this},r);if(!1!==e||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(r.type)){n+=e||"";continue}}switch(r.type){case"escape":{const e=r;n+=t.text(e.text);break}case"html":{const e=r;n+=t.html(e.text);break}case"link":{const e=r;n+=t.link(e.href,e.title,this.parseInline(e.tokens,t));break}case"image":{const e=r;n+=t.image(e.href,e.title,e.text);break}case"strong":{const e=r;n+=t.strong(this.parseInline(e.tokens,t));break}case"em":{const e=r;n+=t.em(this.parseInline(e.tokens,t));break}case"codespan":{const e=r;n+=t.codespan(e.text);break}case"br":n+=t.br();break;case"del":{const e=r;n+=t.del(this.parseInline(e.tokens,t));break}case"text":{const e=r;n+=t.text(e.text);break}default:{const e='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(e),"";throw new Error(e)}}}return n}}class le{options;constructor(t){this.options=t||e.defaults}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}}class oe{defaults={async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null};options=this.setOptions;parse=this.#e(ne.lex,ie.parse);parseInline=this.#e(ne.lexInline,ie.parseInline);Parser=ie;Renderer=se;TextRenderer=re;Lexer=ne;Tokenizer=w;Hooks=le;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(const s of e)switch(n=n.concat(t.call(this,s)),s.type){case"table":{const e=s;for(const s of e.header)n=n.concat(this.walkTokens(s.tokens,t));for(const s of e.rows)for(const e of s)n=n.concat(this.walkTokens(e.tokens,t));break}case"list":{const e=s;n=n.concat(this.walkTokens(e.items,t));break}default:{const e=s;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach((s=>{const r=e[s].flat(1/0);n=n.concat(this.walkTokens(r,t))})):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){const t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach((e=>{const n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach((e=>{if(!e.name)throw new Error("extension name required");if("renderer"in e){const n=t.renderers[e.name];t.renderers[e.name]=n?function(...t){let s=e.renderer.apply(this,t);return!1===s&&(s=n.apply(this,t)),s}:e.renderer}if("tokenizer"in e){if(!e.level||"block"!==e.level&&"inline"!==e.level)throw new Error("extension level must be 'block' or 'inline'");const n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&("block"===e.level?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:"inline"===e.level&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}"childTokens"in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)})),n.extensions=t),e.renderer){const t=this.defaults.renderer||new se(this.defaults);for(const n in e.renderer){if(!(n in t))throw new Error(`renderer '${n}' does not exist`);if("options"===n)continue;const s=n,r=e.renderer[s],i=t[s];t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n||""}}n.renderer=t}if(e.tokenizer){const t=this.defaults.tokenizer||new w(this.defaults);for(const n in e.tokenizer){if(!(n in t))throw new Error(`tokenizer '${n}' does not exist`);if(["options","rules","lexer"].includes(n))continue;const s=n,r=e.tokenizer[s],i=t[s];t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){const t=this.defaults.hooks||new le;for(const n in e.hooks){if(!(n in t))throw new Error(`hook '${n}' does not exist`);if("options"===n)continue;const s=n,r=e.hooks[s],i=t[s];le.passThroughHooks.has(n)?t[s]=e=>{if(this.defaults.async)return Promise.resolve(r.call(t,e)).then((e=>i.call(t,e)));const n=r.call(t,e);return i.call(t,n)}:t[s]=(...e)=>{let n=r.apply(t,e);return!1===n&&(n=i.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){const t=this.defaults.walkTokens,s=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(s.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}})),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return ne.lex(e,t??this.defaults)}parser(e,t){return ie.parse(e,t??this.defaults)}#e(e,t){return(n,s)=>{const r={...s},i={...this.defaults,...r};!0===this.defaults.async&&!1===r.async&&(i.silent||console.warn("marked(): The async option was set to true by an extension. The async: false option sent to parse will be ignored."),i.async=!0);const l=this.#t(!!i.silent,!!i.async);if(null==n)return l(new Error("marked(): input parameter is undefined or null"));if("string"!=typeof n)return l(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(i.hooks&&(i.hooks.options=i),i.async)return Promise.resolve(i.hooks?i.hooks.preprocess(n):n).then((t=>e(t,i))).then((e=>i.hooks?i.hooks.processAllTokens(e):e)).then((e=>i.walkTokens?Promise.all(this.walkTokens(e,i.walkTokens)).then((()=>e)):e)).then((e=>t(e,i))).then((e=>i.hooks?i.hooks.postprocess(e):e)).catch(l);try{i.hooks&&(n=i.hooks.preprocess(n));let s=e(n,i);i.hooks&&(s=i.hooks.processAllTokens(s)),i.walkTokens&&this.walkTokens(s,i.walkTokens);let r=t(s,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return l(e)}}}#t(e,t){return n=>{if(n.message+="\nPlease report this to https://github.com/markedjs/marked.",e){const e="<p>An error occurred:</p><pre>"+c(n.message+"",!0)+"</pre>";return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}}const ae=new oe;function ce(e,t){return ae.parse(e,t)}ce.options=ce.setOptions=function(e){return ae.setOptions(e),ce.defaults=ae.defaults,n(ce.defaults),ce},ce.getDefaults=t,ce.defaults=e.defaults,ce.use=function(...e){return ae.use(...e),ce.defaults=ae.defaults,n(ce.defaults),ce},ce.walkTokens=function(e,t){return ae.walkTokens(e,t)},ce.parseInline=ae.parseInline,ce.Parser=ie,ce.parser=ie.parse,ce.Renderer=se,ce.TextRenderer=re,ce.Lexer=ne,ce.lexer=ne.lex,ce.Tokenizer=w,ce.Hooks=le,ce.parse=ce;const he=ce.options,pe=ce.setOptions,ue=ce.use,ke=ce.walkTokens,ge=ce.parseInline,fe=ce,de=ie.parse,xe=ne.lex;e.Hooks=le,e.Lexer=ne,e.Marked=oe,e.Parser=ie,e.Renderer=se,e.TextRenderer=re,e.Tokenizer=w,e.getDefaults=t,e.lexer=xe,e.marked=ce,e.options=he,e.parse=fe,e.parseInline=ge,e.parser=de,e.setOptions=pe,e.use=ue,e.walkTokens=ke}));
custom_nodes/comfyui-kjnodes/kjweb_async/protovis.min.js ADDED
The diff for this file is too large to render. See raw diff
 
custom_nodes/comfyui-kjnodes/kjweb_async/purify.min.js ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ /*! @license DOMPurify 3.0.11 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.0.11/LICENSE */
2
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).DOMPurify=t()}(this,(function(){"use strict";const{entries:e,setPrototypeOf:t,isFrozen:n,getPrototypeOf:o,getOwnPropertyDescriptor:r}=Object;let{freeze:i,seal:a,create:l}=Object,{apply:c,construct:s}="undefined"!=typeof Reflect&&Reflect;i||(i=function(e){return e}),a||(a=function(e){return e}),c||(c=function(e,t,n){return e.apply(t,n)}),s||(s=function(e,t){return new e(...t)});const u=b(Array.prototype.forEach),m=b(Array.prototype.pop),p=b(Array.prototype.push),f=b(String.prototype.toLowerCase),d=b(String.prototype.toString),h=b(String.prototype.match),g=b(String.prototype.replace),T=b(String.prototype.indexOf),y=b(String.prototype.trim),E=b(Object.prototype.hasOwnProperty),A=b(RegExp.prototype.test),_=(N=TypeError,function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return s(N,t)});var N;function b(e){return function(t){for(var n=arguments.length,o=new Array(n>1?n-1:0),r=1;r<n;r++)o[r-1]=arguments[r];return c(e,t,o)}}function S(e,o){let r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:f;t&&t(e,null);let i=o.length;for(;i--;){let t=o[i];if("string"==typeof t){const e=r(t);e!==t&&(n(o)||(o[i]=e),t=e)}e[t]=!0}return e}function R(e){for(let t=0;t<e.length;t++){E(e,t)||(e[t]=null)}return e}function w(t){const n=l(null);for(const[o,r]of e(t)){E(t,o)&&(Array.isArray(r)?n[o]=R(r):r&&"object"==typeof r&&r.constructor===Object?n[o]=w(r):n[o]=r)}return n}function L(e,t){for(;null!==e;){const n=r(e,t);if(n){if(n.get)return b(n.get);if("function"==typeof n.value)return b(n.value)}e=o(e)}return function(){return null}}const D=i(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","section","select","shadow","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),C=i(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","filter","font","g","glyph","glyphref","hkern","image","line","lineargradient","marker","mask","metadata","mpath","path","pattern","polygon","polyline","radialgradient","rect","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),O=i(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),x=i(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),v=i(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),k=i(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),M=i(["#text"]),I=i(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","face","for","headers","height","hidden","high","href","hreflang","id","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","pattern","placeholder","playsinline","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),U=i(["accent-height","accumulate","additive","alignment-baseline","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),P=i(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),F=i(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),H=a(/\{\{[\w\W]*|[\w\W]*\}\}/gm),z=a(/<%[\w\W]*|[\w\W]*%>/gm),B=a(/\${[\w\W]*}/gm),W=a(/^data-[\-\w.\u00B7-\uFFFF]/),G=a(/^aria-[\-\w]+$/),Y=a(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),j=a(/^(?:\w+script|data):/i),X=a(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),q=a(/^html$/i),$=a(/^[a-z][.\w]*(-[.\w]+)+$/i);var K=Object.freeze({__proto__:null,MUSTACHE_EXPR:H,ERB_EXPR:z,TMPLIT_EXPR:B,DATA_ATTR:W,ARIA_ATTR:G,IS_ALLOWED_URI:Y,IS_SCRIPT_OR_DATA:j,ATTR_WHITESPACE:X,DOCTYPE_NAME:q,CUSTOM_ELEMENT:$});const V=function(){return"undefined"==typeof window?null:window},Z=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const o="data-tt-policy-suffix";t&&t.hasAttribute(o)&&(n=t.getAttribute(o));const r="dompurify"+(n?"#"+n:"");try{return e.createPolicy(r,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+r+" could not be created."),null}};var J=function t(){let n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:V();const o=e=>t(e);if(o.version="3.0.11",o.removed=[],!n||!n.document||9!==n.document.nodeType)return o.isSupported=!1,o;let{document:r}=n;const a=r,c=a.currentScript,{DocumentFragment:s,HTMLTemplateElement:N,Node:b,Element:R,NodeFilter:H,NamedNodeMap:z=n.NamedNodeMap||n.MozNamedAttrMap,HTMLFormElement:B,DOMParser:W,trustedTypes:G}=n,j=R.prototype,X=L(j,"cloneNode"),$=L(j,"nextSibling"),J=L(j,"childNodes"),Q=L(j,"parentNode");if("function"==typeof N){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let ee,te="";const{implementation:ne,createNodeIterator:oe,createDocumentFragment:re,getElementsByTagName:ie}=r,{importNode:ae}=a;let le={};o.isSupported="function"==typeof e&&"function"==typeof Q&&ne&&void 0!==ne.createHTMLDocument;const{MUSTACHE_EXPR:ce,ERB_EXPR:se,TMPLIT_EXPR:ue,DATA_ATTR:me,ARIA_ATTR:pe,IS_SCRIPT_OR_DATA:fe,ATTR_WHITESPACE:de,CUSTOM_ELEMENT:he}=K;let{IS_ALLOWED_URI:ge}=K,Te=null;const ye=S({},[...D,...C,...O,...v,...M]);let Ee=null;const Ae=S({},[...I,...U,...P,...F]);let _e=Object.seal(l(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),Ne=null,be=null,Se=!0,Re=!0,we=!1,Le=!0,De=!1,Ce=!0,Oe=!1,xe=!1,ve=!1,ke=!1,Me=!1,Ie=!1,Ue=!0,Pe=!1;const Fe="user-content-";let He=!0,ze=!1,Be={},We=null;const Ge=S({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let Ye=null;const je=S({},["audio","video","img","source","image","track"]);let Xe=null;const qe=S({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),$e="http://www.w3.org/1998/Math/MathML",Ke="http://www.w3.org/2000/svg",Ve="http://www.w3.org/1999/xhtml";let Ze=Ve,Je=!1,Qe=null;const et=S({},[$e,Ke,Ve],d);let tt=null;const nt=["application/xhtml+xml","text/html"],ot="text/html";let rt=null,it=null;const at=r.createElement("form"),lt=function(e){return e instanceof RegExp||e instanceof Function},ct=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!it||it!==e){if(e&&"object"==typeof e||(e={}),e=w(e),tt=-1===nt.indexOf(e.PARSER_MEDIA_TYPE)?ot:e.PARSER_MEDIA_TYPE,rt="application/xhtml+xml"===tt?d:f,Te=E(e,"ALLOWED_TAGS")?S({},e.ALLOWED_TAGS,rt):ye,Ee=E(e,"ALLOWED_ATTR")?S({},e.ALLOWED_ATTR,rt):Ae,Qe=E(e,"ALLOWED_NAMESPACES")?S({},e.ALLOWED_NAMESPACES,d):et,Xe=E(e,"ADD_URI_SAFE_ATTR")?S(w(qe),e.ADD_URI_SAFE_ATTR,rt):qe,Ye=E(e,"ADD_DATA_URI_TAGS")?S(w(je),e.ADD_DATA_URI_TAGS,rt):je,We=E(e,"FORBID_CONTENTS")?S({},e.FORBID_CONTENTS,rt):Ge,Ne=E(e,"FORBID_TAGS")?S({},e.FORBID_TAGS,rt):{},be=E(e,"FORBID_ATTR")?S({},e.FORBID_ATTR,rt):{},Be=!!E(e,"USE_PROFILES")&&e.USE_PROFILES,Se=!1!==e.ALLOW_ARIA_ATTR,Re=!1!==e.ALLOW_DATA_ATTR,we=e.ALLOW_UNKNOWN_PROTOCOLS||!1,Le=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,De=e.SAFE_FOR_TEMPLATES||!1,Ce=!1!==e.SAFE_FOR_XML,Oe=e.WHOLE_DOCUMENT||!1,ke=e.RETURN_DOM||!1,Me=e.RETURN_DOM_FRAGMENT||!1,Ie=e.RETURN_TRUSTED_TYPE||!1,ve=e.FORCE_BODY||!1,Ue=!1!==e.SANITIZE_DOM,Pe=e.SANITIZE_NAMED_PROPS||!1,He=!1!==e.KEEP_CONTENT,ze=e.IN_PLACE||!1,ge=e.ALLOWED_URI_REGEXP||Y,Ze=e.NAMESPACE||Ve,_e=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&lt(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(_e.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&lt(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(_e.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(_e.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),De&&(Re=!1),Me&&(ke=!0),Be&&(Te=S({},M),Ee=[],!0===Be.html&&(S(Te,D),S(Ee,I)),!0===Be.svg&&(S(Te,C),S(Ee,U),S(Ee,F)),!0===Be.svgFilters&&(S(Te,O),S(Ee,U),S(Ee,F)),!0===Be.mathMl&&(S(Te,v),S(Ee,P),S(Ee,F))),e.ADD_TAGS&&(Te===ye&&(Te=w(Te)),S(Te,e.ADD_TAGS,rt)),e.ADD_ATTR&&(Ee===Ae&&(Ee=w(Ee)),S(Ee,e.ADD_ATTR,rt)),e.ADD_URI_SAFE_ATTR&&S(Xe,e.ADD_URI_SAFE_ATTR,rt),e.FORBID_CONTENTS&&(We===Ge&&(We=w(We)),S(We,e.FORBID_CONTENTS,rt)),He&&(Te["#text"]=!0),Oe&&S(Te,["html","head","body"]),Te.table&&(S(Te,["tbody"]),delete Ne.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw _('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw _('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');ee=e.TRUSTED_TYPES_POLICY,te=ee.createHTML("")}else void 0===ee&&(ee=Z(G,c)),null!==ee&&"string"==typeof te&&(te=ee.createHTML(""));i&&i(e),it=e}},st=S({},["mi","mo","mn","ms","mtext"]),ut=S({},["foreignobject","desc","title","annotation-xml"]),mt=S({},["title","style","font","a","script"]),pt=S({},[...C,...O,...x]),ft=S({},[...v,...k]),dt=function(e){let t=Q(e);t&&t.tagName||(t={namespaceURI:Ze,tagName:"template"});const n=f(e.tagName),o=f(t.tagName);return!!Qe[e.namespaceURI]&&(e.namespaceURI===Ke?t.namespaceURI===Ve?"svg"===n:t.namespaceURI===$e?"svg"===n&&("annotation-xml"===o||st[o]):Boolean(pt[n]):e.namespaceURI===$e?t.namespaceURI===Ve?"math"===n:t.namespaceURI===Ke?"math"===n&&ut[o]:Boolean(ft[n]):e.namespaceURI===Ve?!(t.namespaceURI===Ke&&!ut[o])&&(!(t.namespaceURI===$e&&!st[o])&&(!ft[n]&&(mt[n]||!pt[n]))):!("application/xhtml+xml"!==tt||!Qe[e.namespaceURI]))},ht=function(e){p(o.removed,{element:e});try{e.parentNode.removeChild(e)}catch(t){e.remove()}},gt=function(e,t){try{p(o.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){p(o.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e&&!Ee[e])if(ke||Me)try{ht(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Tt=function(e){let t=null,n=null;if(ve)e="<remove></remove>"+e;else{const t=h(e,/^[\r\n\t ]+/);n=t&&t[0]}"application/xhtml+xml"===tt&&Ze===Ve&&(e='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+e+"</body></html>");const o=ee?ee.createHTML(e):e;if(Ze===Ve)try{t=(new W).parseFromString(o,tt)}catch(e){}if(!t||!t.documentElement){t=ne.createDocument(Ze,"template",null);try{t.documentElement.innerHTML=Je?te:o}catch(e){}}const i=t.body||t.documentElement;return e&&n&&i.insertBefore(r.createTextNode(n),i.childNodes[0]||null),Ze===Ve?ie.call(t,Oe?"html":"body")[0]:Oe?t.documentElement:i},yt=function(e){return oe.call(e.ownerDocument||e,e,H.SHOW_ELEMENT|H.SHOW_COMMENT|H.SHOW_TEXT|H.SHOW_PROCESSING_INSTRUCTION|H.SHOW_CDATA_SECTION,null)},Et=function(e){return e instanceof B&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof z)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},At=function(e){return"function"==typeof b&&e instanceof b},_t=function(e,t,n){le[e]&&u(le[e],(e=>{e.call(o,t,n,it)}))},Nt=function(e){let t=null;if(_t("beforeSanitizeElements",e,null),Et(e))return ht(e),!0;const n=rt(e.nodeName);if(_t("uponSanitizeElement",e,{tagName:n,allowedTags:Te}),e.hasChildNodes()&&!At(e.firstElementChild)&&A(/<[/\w]/g,e.innerHTML)&&A(/<[/\w]/g,e.textContent))return ht(e),!0;if(7===e.nodeType)return ht(e),!0;if(Ce&&8===e.nodeType&&A(/<[/\w]/g,e.data))return ht(e),!0;if(!Te[n]||Ne[n]){if(!Ne[n]&&St(n)){if(_e.tagNameCheck instanceof RegExp&&A(_e.tagNameCheck,n))return!1;if(_e.tagNameCheck instanceof Function&&_e.tagNameCheck(n))return!1}if(He&&!We[n]){const t=Q(e)||e.parentNode,n=J(e)||e.childNodes;if(n&&t){for(let o=n.length-1;o>=0;--o)t.insertBefore(X(n[o],!0),$(e))}}return ht(e),!0}return e instanceof R&&!dt(e)?(ht(e),!0):"noscript"!==n&&"noembed"!==n&&"noframes"!==n||!A(/<\/no(script|embed|frames)/i,e.innerHTML)?(De&&3===e.nodeType&&(t=e.textContent,u([ce,se,ue],(e=>{t=g(t,e," ")})),e.textContent!==t&&(p(o.removed,{element:e.cloneNode()}),e.textContent=t)),_t("afterSanitizeElements",e,null),!1):(ht(e),!0)},bt=function(e,t,n){if(Ue&&("id"===t||"name"===t)&&(n in r||n in at))return!1;if(Re&&!be[t]&&A(me,t));else if(Se&&A(pe,t));else if(!Ee[t]||be[t]){if(!(St(e)&&(_e.tagNameCheck instanceof RegExp&&A(_e.tagNameCheck,e)||_e.tagNameCheck instanceof Function&&_e.tagNameCheck(e))&&(_e.attributeNameCheck instanceof RegExp&&A(_e.attributeNameCheck,t)||_e.attributeNameCheck instanceof Function&&_e.attributeNameCheck(t))||"is"===t&&_e.allowCustomizedBuiltInElements&&(_e.tagNameCheck instanceof RegExp&&A(_e.tagNameCheck,n)||_e.tagNameCheck instanceof Function&&_e.tagNameCheck(n))))return!1}else if(Xe[t]);else if(A(ge,g(n,de,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==T(n,"data:")||!Ye[e]){if(we&&!A(fe,g(n,de,"")));else if(n)return!1}else;return!0},St=function(e){return"annotation-xml"!==e&&h(e,he)},Rt=function(e){_t("beforeSanitizeAttributes",e,null);const{attributes:t}=e;if(!t)return;const n={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:Ee};let r=t.length;for(;r--;){const i=t[r],{name:a,namespaceURI:l,value:c}=i,s=rt(a);let p="value"===a?c:y(c);if(n.attrName=s,n.attrValue=p,n.keepAttr=!0,n.forceKeepAttr=void 0,_t("uponSanitizeAttribute",e,n),p=n.attrValue,n.forceKeepAttr)continue;if(gt(a,e),!n.keepAttr)continue;if(!Le&&A(/\/>/i,p)){gt(a,e);continue}De&&u([ce,se,ue],(e=>{p=g(p,e," ")}));const f=rt(e.nodeName);if(bt(f,s,p)){if(!Pe||"id"!==s&&"name"!==s||(gt(a,e),p=Fe+p),ee&&"object"==typeof G&&"function"==typeof G.getAttributeType)if(l);else switch(G.getAttributeType(f,s)){case"TrustedHTML":p=ee.createHTML(p);break;case"TrustedScriptURL":p=ee.createScriptURL(p)}try{l?e.setAttributeNS(l,a,p):e.setAttribute(a,p),m(o.removed)}catch(e){}}}_t("afterSanitizeAttributes",e,null)},wt=function e(t){let n=null;const o=yt(t);for(_t("beforeSanitizeShadowDOM",t,null);n=o.nextNode();)_t("uponSanitizeShadowNode",n,null),Nt(n)||(n.content instanceof s&&e(n.content),Rt(n));_t("afterSanitizeShadowDOM",t,null)};return o.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=null,r=null,i=null,l=null;if(Je=!e,Je&&(e="\x3c!--\x3e"),"string"!=typeof e&&!At(e)){if("function"!=typeof e.toString)throw _("toString is not a function");if("string"!=typeof(e=e.toString()))throw _("dirty is not a string, aborting")}if(!o.isSupported)return e;if(xe||ct(t),o.removed=[],"string"==typeof e&&(ze=!1),ze){if(e.nodeName){const t=rt(e.nodeName);if(!Te[t]||Ne[t])throw _("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof b)n=Tt("\x3c!----\x3e"),r=n.ownerDocument.importNode(e,!0),1===r.nodeType&&"BODY"===r.nodeName||"HTML"===r.nodeName?n=r:n.appendChild(r);else{if(!ke&&!De&&!Oe&&-1===e.indexOf("<"))return ee&&Ie?ee.createHTML(e):e;if(n=Tt(e),!n)return ke?null:Ie?te:""}n&&ve&&ht(n.firstChild);const c=yt(ze?e:n);for(;i=c.nextNode();)Nt(i)||(i.content instanceof s&&wt(i.content),Rt(i));if(ze)return e;if(ke){if(Me)for(l=re.call(n.ownerDocument);n.firstChild;)l.appendChild(n.firstChild);else l=n;return(Ee.shadowroot||Ee.shadowrootmode)&&(l=ae.call(a,l,!0)),l}let m=Oe?n.outerHTML:n.innerHTML;return Oe&&Te["!doctype"]&&n.ownerDocument&&n.ownerDocument.doctype&&n.ownerDocument.doctype.name&&A(q,n.ownerDocument.doctype.name)&&(m="<!DOCTYPE "+n.ownerDocument.doctype.name+">\n"+m),De&&u([ce,se,ue],(e=>{m=g(m,e," ")})),ee&&Ie?ee.createHTML(m):m},o.setConfig=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};ct(e),xe=!0},o.clearConfig=function(){it=null,xe=!1},o.isValidAttribute=function(e,t,n){it||ct({});const o=rt(e),r=rt(t);return bt(o,r,n)},o.addHook=function(e,t){"function"==typeof t&&(le[e]=le[e]||[],p(le[e],t))},o.removeHook=function(e){if(le[e])return m(le[e])},o.removeHooks=function(e){le[e]&&(le[e]=[])},o.removeAllHooks=function(){le={}},o}();return J}));
3
+ //# sourceMappingURL=purify.min.js.map
custom_nodes/comfyui-kjnodes/kjweb_async/svg-path-properties.min.js ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ // http://geoexamples.com/path-properties/ v1.2.0 Copyright 2023 Roger Veciana i Rovira
2
+ !function(t,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n((t="undefined"!=typeof globalThis?globalThis:t||self).svgPathProperties={})}(this,(function(t){"use strict";function n(t,n){for(var e=0;e<n.length;e++){var i=n[e];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(t,s(i.key),i)}}function e(t,e,i){return e&&n(t.prototype,e),i&&n(t,i),Object.defineProperty(t,"prototype",{writable:!1}),t}function i(t,n,e){return(n=s(n))in t?Object.defineProperty(t,n,{value:e,enumerable:!0,configurable:!0,writable:!0}):t[n]=e,t}function r(t){return function(t){if(Array.isArray(t))return h(t)}(t)||function(t){if("undefined"!=typeof Symbol&&null!=t[Symbol.iterator]||null!=t["@@iterator"])return Array.from(t)}(t)||function(t,n){if(!t)return;if("string"==typeof t)return h(t,n);var e=Object.prototype.toString.call(t).slice(8,-1);"Object"===e&&t.constructor&&(e=t.constructor.name);if("Map"===e||"Set"===e)return Array.from(t);if("Arguments"===e||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e))return h(t,n)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function h(t,n){(null==n||n>t.length)&&(n=t.length);for(var e=0,i=new Array(n);e<n;e++)i[e]=t[e];return i}function s(t){var n=function(t,n){if("object"!=typeof t||null===t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,n||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===n?String:Number)(t)}(t,"string");return"symbol"==typeof n?n:String(n)}var a={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},o=/([astvzqmhlc])([^astvzqmhlc]*)/gi,g=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi,u=function(t){var n=t.match(g);return n?n.map(Number):[]},l=e((function(t,n,e,r){var h=this;i(this,"x0",void 0),i(this,"x1",void 0),i(this,"y0",void 0),i(this,"y1",void 0),i(this,"getTotalLength",(function(){return Math.sqrt(Math.pow(h.x0-h.x1,2)+Math.pow(h.y0-h.y1,2))})),i(this,"getPointAtLength",(function(t){var n=t/Math.sqrt(Math.pow(h.x0-h.x1,2)+Math.pow(h.y0-h.y1,2));n=Number.isNaN(n)?1:n;var e=(h.x1-h.x0)*n,i=(h.y1-h.y0)*n;return{x:h.x0+e,y:h.y0+i}})),i(this,"getTangentAtLength",(function(t){var n=Math.sqrt((h.x1-h.x0)*(h.x1-h.x0)+(h.y1-h.y0)*(h.y1-h.y0));return{x:(h.x1-h.x0)/n,y:(h.y1-h.y0)/n}})),i(this,"getPropertiesAtLength",(function(t){var n=h.getPointAtLength(t),e=h.getTangentAtLength(t);return{x:n.x,y:n.y,tangentX:e.x,tangentY:e.y}})),this.x0=t,this.x1=n,this.y0=e,this.y1=r})),c=e((function(t,n,e,r,h,s,a,o,g){var u=this;i(this,"x0",void 0),i(this,"y0",void 0),i(this,"rx",void 0),i(this,"ry",void 0),i(this,"xAxisRotate",void 0),i(this,"LargeArcFlag",void 0),i(this,"SweepFlag",void 0),i(this,"x1",void 0),i(this,"y1",void 0),i(this,"length",void 0),i(this,"getTotalLength",(function(){return u.length})),i(this,"getPointAtLength",(function(t){t<0?t=0:t>u.length&&(t=u.length);var n=f({x:u.x0,y:u.y0},u.rx,u.ry,u.xAxisRotate,u.LargeArcFlag,u.SweepFlag,{x:u.x1,y:u.y1},t/u.length);return{x:n.x,y:n.y}})),i(this,"getTangentAtLength",(function(t){t<0?t=0:t>u.length&&(t=u.length);var n,e=.05,i=u.getPointAtLength(t);t<0?t=0:t>u.length&&(t=u.length);var r=(n=t<u.length-e?u.getPointAtLength(t+e):u.getPointAtLength(t-e)).x-i.x,h=n.y-i.y,s=Math.sqrt(r*r+h*h);return t<u.length-e?{x:-r/s,y:-h/s}:{x:r/s,y:h/s}})),i(this,"getPropertiesAtLength",(function(t){var n=u.getTangentAtLength(t),e=u.getPointAtLength(t);return{x:e.x,y:e.y,tangentX:n.x,tangentY:n.y}})),this.x0=t,this.y0=n,this.rx=e,this.ry=r,this.xAxisRotate=h,this.LargeArcFlag=s,this.SweepFlag=a,this.x1=o,this.y1=g;var l=y(300,(function(i){return f({x:t,y:n},e,r,h,s,a,{x:o,y:g},i)}));this.length=l.arcLength})),f=function(t,n,e,i,r,h,s,a){n=Math.abs(n),e=Math.abs(e),i=p(i,360);var o=x(i);if(t.x===s.x&&t.y===s.y)return{x:t.x,y:t.y,ellipticalArcAngle:0};if(0===n||0===e)return{x:0,y:0,ellipticalArcAngle:0};var g=(t.x-s.x)/2,u=(t.y-s.y)/2,l={x:Math.cos(o)*g+Math.sin(o)*u,y:-Math.sin(o)*g+Math.cos(o)*u},c=Math.pow(l.x,2)/Math.pow(n,2)+Math.pow(l.y,2)/Math.pow(e,2);c>1&&(n=Math.sqrt(c)*n,e=Math.sqrt(c)*e);var f=(Math.pow(n,2)*Math.pow(e,2)-Math.pow(n,2)*Math.pow(l.y,2)-Math.pow(e,2)*Math.pow(l.x,2))/(Math.pow(n,2)*Math.pow(l.y,2)+Math.pow(e,2)*Math.pow(l.x,2));f=f<0?0:f;var y=(r!==h?1:-1)*Math.sqrt(f),v=y*(n*l.y/e),M=y*(-e*l.x/n),L={x:Math.cos(o)*v-Math.sin(o)*M+(t.x+s.x)/2,y:Math.sin(o)*v+Math.cos(o)*M+(t.y+s.y)/2},d={x:(l.x-v)/n,y:(l.y-M)/e},A=w({x:1,y:0},d),b=w(d,{x:(-l.x-v)/n,y:(-l.y-M)/e});!h&&b>0?b-=2*Math.PI:h&&b<0&&(b+=2*Math.PI);var P=A+(b%=2*Math.PI)*a,m=n*Math.cos(P),T=e*Math.sin(P);return{x:Math.cos(o)*m-Math.sin(o)*T+L.x,y:Math.sin(o)*m+Math.cos(o)*T+L.y,ellipticalArcStartAngle:A,ellipticalArcEndAngle:A+b,ellipticalArcAngle:P,ellipticalArcCenter:L,resultantRx:n,resultantRy:e}},y=function(t,n){t=t||500;for(var e,i=0,r=[],h=[],s=n(0),a=0;a<t;a++){var o=M(a*(1/t),0,1);e=n(o),i+=v(s,e),h.push([s,e]),r.push({t:o,arcLength:i}),s=e}return e=n(1),h.push([s,e]),i+=v(s,e),r.push({t:1,arcLength:i}),{arcLength:i,arcLengthMap:r,approximationLines:h}},p=function(t,n){return(t%n+n)%n},x=function(t){return t*(Math.PI/180)},v=function(t,n){return Math.sqrt(Math.pow(n.x-t.x,2)+Math.pow(n.y-t.y,2))},M=function(t,n,e){return Math.min(Math.max(t,n),e)},w=function(t,n){var e=t.x*n.x+t.y*n.y,i=Math.sqrt((Math.pow(t.x,2)+Math.pow(t.y,2))*(Math.pow(n.x,2)+Math.pow(n.y,2)));return(t.x*n.y-t.y*n.x<0?-1:1)*Math.acos(e/i)},L=[[],[],[-.5773502691896257,.5773502691896257],[0,-.7745966692414834,.7745966692414834],[-.33998104358485626,.33998104358485626,-.8611363115940526,.8611363115940526],[0,-.5384693101056831,.5384693101056831,-.906179845938664,.906179845938664],[.6612093864662645,-.6612093864662645,-.2386191860831969,.2386191860831969,-.932469514203152,.932469514203152],[0,.4058451513773972,-.4058451513773972,-.7415311855993945,.7415311855993945,-.9491079123427585,.9491079123427585],[-.1834346424956498,.1834346424956498,-.525532409916329,.525532409916329,-.7966664774136267,.7966664774136267,-.9602898564975363,.9602898564975363],[0,-.8360311073266358,.8360311073266358,-.9681602395076261,.9681602395076261,-.3242534234038089,.3242534234038089,-.6133714327005904,.6133714327005904],[-.14887433898163122,.14887433898163122,-.4333953941292472,.4333953941292472,-.6794095682990244,.6794095682990244,-.8650633666889845,.8650633666889845,-.9739065285171717,.9739065285171717],[0,-.26954315595234496,.26954315595234496,-.5190961292068118,.5190961292068118,-.7301520055740494,.7301520055740494,-.8870625997680953,.8870625997680953,-.978228658146057,.978228658146057],[-.1252334085114689,.1252334085114689,-.3678314989981802,.3678314989981802,-.5873179542866175,.5873179542866175,-.7699026741943047,.7699026741943047,-.9041172563704749,.9041172563704749,-.9815606342467192,.9815606342467192],[0,-.2304583159551348,.2304583159551348,-.44849275103644687,.44849275103644687,-.6423493394403402,.6423493394403402,-.8015780907333099,.8015780907333099,-.9175983992229779,.9175983992229779,-.9841830547185881,.9841830547185881],[-.10805494870734367,.10805494870734367,-.31911236892788974,.31911236892788974,-.5152486363581541,.5152486363581541,-.6872929048116855,.6872929048116855,-.827201315069765,.827201315069765,-.9284348836635735,.9284348836635735,-.9862838086968123,.9862838086968123],[0,-.20119409399743451,.20119409399743451,-.3941513470775634,.3941513470775634,-.5709721726085388,.5709721726085388,-.7244177313601701,.7244177313601701,-.8482065834104272,.8482065834104272,-.937273392400706,.937273392400706,-.9879925180204854,.9879925180204854],[-.09501250983763744,.09501250983763744,-.2816035507792589,.2816035507792589,-.45801677765722737,.45801677765722737,-.6178762444026438,.6178762444026438,-.755404408355003,.755404408355003,-.8656312023878318,.8656312023878318,-.9445750230732326,.9445750230732326,-.9894009349916499,.9894009349916499],[0,-.17848418149584785,.17848418149584785,-.3512317634538763,.3512317634538763,-.5126905370864769,.5126905370864769,-.6576711592166907,.6576711592166907,-.7815140038968014,.7815140038968014,-.8802391537269859,.8802391537269859,-.9506755217687678,.9506755217687678,-.9905754753144174,.9905754753144174],[-.0847750130417353,.0847750130417353,-.2518862256915055,.2518862256915055,-.41175116146284263,.41175116146284263,-.5597708310739475,.5597708310739475,-.6916870430603532,.6916870430603532,-.8037049589725231,.8037049589725231,-.8926024664975557,.8926024664975557,-.9558239495713977,.9558239495713977,-.9915651684209309,.9915651684209309],[0,-.16035864564022537,.16035864564022537,-.31656409996362983,.31656409996362983,-.46457074137596094,.46457074137596094,-.600545304661681,.600545304661681,-.7209661773352294,.7209661773352294,-.8227146565371428,.8227146565371428,-.9031559036148179,.9031559036148179,-.96020815213483,.96020815213483,-.9924068438435844,.9924068438435844],[-.07652652113349734,.07652652113349734,-.22778585114164507,.22778585114164507,-.37370608871541955,.37370608871541955,-.5108670019508271,.5108670019508271,-.636053680726515,.636053680726515,-.7463319064601508,.7463319064601508,-.8391169718222188,.8391169718222188,-.912234428251326,.912234428251326,-.9639719272779138,.9639719272779138,-.9931285991850949,.9931285991850949],[0,-.1455618541608951,.1455618541608951,-.2880213168024011,.2880213168024011,-.4243421202074388,.4243421202074388,-.5516188358872198,.5516188358872198,-.6671388041974123,.6671388041974123,-.7684399634756779,.7684399634756779,-.8533633645833173,.8533633645833173,-.9200993341504008,.9200993341504008,-.9672268385663063,.9672268385663063,-.9937521706203895,.9937521706203895],[-.06973927331972223,.06973927331972223,-.20786042668822127,.20786042668822127,-.34193582089208424,.34193582089208424,-.469355837986757,.469355837986757,-.5876404035069116,.5876404035069116,-.6944872631866827,.6944872631866827,-.7878168059792081,.7878168059792081,-.8658125777203002,.8658125777203002,-.926956772187174,.926956772187174,-.9700604978354287,.9700604978354287,-.9942945854823992,.9942945854823992],[0,-.1332568242984661,.1332568242984661,-.26413568097034495,.26413568097034495,-.3903010380302908,.3903010380302908,-.5095014778460075,.5095014778460075,-.6196098757636461,.6196098757636461,-.7186613631319502,.7186613631319502,-.8048884016188399,.8048884016188399,-.8767523582704416,.8767523582704416,-.9329710868260161,.9329710868260161,-.9725424712181152,.9725424712181152,-.9947693349975522,.9947693349975522],[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213]],d=[[],[],[1,1],[.8888888888888888,.5555555555555556,.5555555555555556],[.6521451548625461,.6521451548625461,.34785484513745385,.34785484513745385],[.5688888888888889,.47862867049936647,.47862867049936647,.23692688505618908,.23692688505618908],[.3607615730481386,.3607615730481386,.46791393457269104,.46791393457269104,.17132449237917036,.17132449237917036],[.4179591836734694,.3818300505051189,.3818300505051189,.27970539148927664,.27970539148927664,.1294849661688697,.1294849661688697],[.362683783378362,.362683783378362,.31370664587788727,.31370664587788727,.22238103445337448,.22238103445337448,.10122853629037626,.10122853629037626],[.3302393550012598,.1806481606948574,.1806481606948574,.08127438836157441,.08127438836157441,.31234707704000286,.31234707704000286,.26061069640293544,.26061069640293544],[.29552422471475287,.29552422471475287,.26926671930999635,.26926671930999635,.21908636251598204,.21908636251598204,.1494513491505806,.1494513491505806,.06667134430868814,.06667134430868814],[.2729250867779006,.26280454451024665,.26280454451024665,.23319376459199048,.23319376459199048,.18629021092773426,.18629021092773426,.1255803694649046,.1255803694649046,.05566856711617366,.05566856711617366],[.24914704581340277,.24914704581340277,.2334925365383548,.2334925365383548,.20316742672306592,.20316742672306592,.16007832854334622,.16007832854334622,.10693932599531843,.10693932599531843,.04717533638651183,.04717533638651183],[.2325515532308739,.22628318026289723,.22628318026289723,.2078160475368885,.2078160475368885,.17814598076194574,.17814598076194574,.13887351021978725,.13887351021978725,.09212149983772845,.09212149983772845,.04048400476531588,.04048400476531588],[.2152638534631578,.2152638534631578,.2051984637212956,.2051984637212956,.18553839747793782,.18553839747793782,.15720316715819355,.15720316715819355,.12151857068790319,.12151857068790319,.08015808715976021,.08015808715976021,.03511946033175186,.03511946033175186],[.2025782419255613,.19843148532711158,.19843148532711158,.1861610000155622,.1861610000155622,.16626920581699392,.16626920581699392,.13957067792615432,.13957067792615432,.10715922046717194,.10715922046717194,.07036604748810812,.07036604748810812,.03075324199611727,.03075324199611727],[.1894506104550685,.1894506104550685,.18260341504492358,.18260341504492358,.16915651939500254,.16915651939500254,.14959598881657674,.14959598881657674,.12462897125553388,.12462897125553388,.09515851168249279,.09515851168249279,.062253523938647894,.062253523938647894,.027152459411754096,.027152459411754096],[.17944647035620653,.17656270536699264,.17656270536699264,.16800410215645004,.16800410215645004,.15404576107681028,.15404576107681028,.13513636846852548,.13513636846852548,.11188384719340397,.11188384719340397,.08503614831717918,.08503614831717918,.0554595293739872,.0554595293739872,.02414830286854793,.02414830286854793],[.1691423829631436,.1691423829631436,.16427648374583273,.16427648374583273,.15468467512626524,.15468467512626524,.14064291467065065,.14064291467065065,.12255520671147846,.12255520671147846,.10094204410628717,.10094204410628717,.07642573025488905,.07642573025488905,.0497145488949698,.0497145488949698,.02161601352648331,.02161601352648331],[.1610544498487837,.15896884339395434,.15896884339395434,.15276604206585967,.15276604206585967,.1426067021736066,.1426067021736066,.12875396253933621,.12875396253933621,.11156664554733399,.11156664554733399,.09149002162245,.09149002162245,.06904454273764123,.06904454273764123,.0448142267656996,.0448142267656996,.019461788229726478,.019461788229726478],[.15275338713072584,.15275338713072584,.14917298647260374,.14917298647260374,.14209610931838204,.14209610931838204,.13168863844917664,.13168863844917664,.11819453196151841,.11819453196151841,.10193011981724044,.10193011981724044,.08327674157670475,.08327674157670475,.06267204833410907,.06267204833410907,.04060142980038694,.04060142980038694,.017614007139152118,.017614007139152118],[.14608113364969041,.14452440398997005,.14452440398997005,.13988739479107315,.13988739479107315,.13226893863333747,.13226893863333747,.12183141605372853,.12183141605372853,.10879729916714838,.10879729916714838,.09344442345603386,.09344442345603386,.0761001136283793,.0761001136283793,.057134425426857205,.057134425426857205,.036953789770852494,.036953789770852494,.016017228257774335,.016017228257774335],[.13925187285563198,.13925187285563198,.13654149834601517,.13654149834601517,.13117350478706238,.13117350478706238,.12325237681051242,.12325237681051242,.11293229608053922,.11293229608053922,.10041414444288096,.10041414444288096,.08594160621706773,.08594160621706773,.06979646842452049,.06979646842452049,.052293335152683286,.052293335152683286,.03377490158481415,.03377490158481415,.0146279952982722,.0146279952982722],[.13365457218610619,.1324620394046966,.1324620394046966,.12890572218808216,.12890572218808216,.12304908430672953,.12304908430672953,.11499664022241136,.11499664022241136,.10489209146454141,.10489209146454141,.09291576606003515,.09291576606003515,.07928141177671895,.07928141177671895,.06423242140852585,.06423242140852585,.04803767173108467,.04803767173108467,.030988005856979445,.030988005856979445,.013411859487141771,.013411859487141771],[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872]],A=[[1],[1,1],[1,2,1],[1,3,3,1]],b=function(t,n,e){return{x:(1-e)*(1-e)*(1-e)*t[0]+3*(1-e)*(1-e)*e*t[1]+3*(1-e)*e*e*t[2]+e*e*e*t[3],y:(1-e)*(1-e)*(1-e)*n[0]+3*(1-e)*(1-e)*e*n[1]+3*(1-e)*e*e*n[2]+e*e*e*n[3]}},P=function(t,n,e){return T([3*(t[1]-t[0]),3*(t[2]-t[1]),3*(t[3]-t[2])],[3*(n[1]-n[0]),3*(n[2]-n[1]),3*(n[3]-n[2])],e)},m=function(t,n,e){var i,r,h;i=e/2,r=0;for(var s=0;s<20;s++)h=i*L[20][s]+i,r+=d[20][s]*S(t,n,h);return i*r},T=function(t,n,e){return{x:(1-e)*(1-e)*t[0]+2*(1-e)*e*t[1]+e*e*t[2],y:(1-e)*(1-e)*n[0]+2*(1-e)*e*n[1]+e*e*n[2]}},q=function(t,n,e){void 0===e&&(e=1);var i=t[0]-2*t[1]+t[2],r=n[0]-2*n[1]+n[2],h=2*t[1]-2*t[0],s=2*n[1]-2*n[0],a=4*(i*i+r*r),o=4*(i*h+r*s),g=h*h+s*s;if(0===a)return e*Math.sqrt(Math.pow(t[2]-t[0],2)+Math.pow(n[2]-n[0],2));var u=o/(2*a),l=e+u,c=g/a-u*u,f=l*l+c>0?Math.sqrt(l*l+c):0,y=u*u+c>0?Math.sqrt(u*u+c):0,p=u+Math.sqrt(u*u+c)!==0&&(l+f)/(u+y)!=0?c*Math.log(Math.abs((l+f)/(u+y))):0;return Math.sqrt(a)/2*(l*f-u*y+p)},_=function(t,n,e){return{x:2*(1-e)*(t[1]-t[0])+2*e*(t[2]-t[1]),y:2*(1-e)*(n[1]-n[0])+2*e*(n[2]-n[1])}};function S(t,n,e){var i=N(1,e,t),r=N(1,e,n),h=i*i+r*r;return Math.sqrt(h)}var N=function t(n,e,i){var r,h,s=i.length-1;if(0===s)return 0;if(0===n){h=0;for(var a=0;a<=s;a++)h+=A[s][a]*Math.pow(1-e,s-a)*Math.pow(e,a)*i[a];return h}r=new Array(s);for(var o=0;o<s;o++)r[o]=s*(i[o+1]-i[o]);return t(n-1,e,r)},C=function(t,n,e){for(var i=1,r=t/n,h=(t-e(r))/n,s=0;i>.001;){var a=e(r+h),o=Math.abs(t-a)/n;if(o<i)i=o,r+=h;else{var g=e(r-h),u=Math.abs(t-g)/n;u<i?(i=u,r-=h):h/=2}if(++s>500)break}return r},j=e((function(t,n,e,r,h,s,a,o){var g=this;i(this,"a",void 0),i(this,"b",void 0),i(this,"c",void 0),i(this,"d",void 0),i(this,"length",void 0),i(this,"getArcLength",void 0),i(this,"getPoint",void 0),i(this,"getDerivative",void 0),i(this,"getTotalLength",(function(){return g.length})),i(this,"getPointAtLength",(function(t){var n=[g.a.x,g.b.x,g.c.x,g.d.x],e=[g.a.y,g.b.y,g.c.y,g.d.y],i=C(t,g.length,(function(t){return g.getArcLength(n,e,t)}));return g.getPoint(n,e,i)})),i(this,"getTangentAtLength",(function(t){var n=[g.a.x,g.b.x,g.c.x,g.d.x],e=[g.a.y,g.b.y,g.c.y,g.d.y],i=C(t,g.length,(function(t){return g.getArcLength(n,e,t)})),r=g.getDerivative(n,e,i),h=Math.sqrt(r.x*r.x+r.y*r.y);return h>0?{x:r.x/h,y:r.y/h}:{x:0,y:0}})),i(this,"getPropertiesAtLength",(function(t){var n,e=[g.a.x,g.b.x,g.c.x,g.d.x],i=[g.a.y,g.b.y,g.c.y,g.d.y],r=C(t,g.length,(function(t){return g.getArcLength(e,i,t)})),h=g.getDerivative(e,i,r),s=Math.sqrt(h.x*h.x+h.y*h.y);n=s>0?{x:h.x/s,y:h.y/s}:{x:0,y:0};var a=g.getPoint(e,i,r);return{x:a.x,y:a.y,tangentX:n.x,tangentY:n.y}})),i(this,"getC",(function(){return g.c})),i(this,"getD",(function(){return g.d})),this.a={x:t,y:n},this.b={x:e,y:r},this.c={x:h,y:s},void 0!==a&&void 0!==o?(this.getArcLength=m,this.getPoint=b,this.getDerivative=P,this.d={x:a,y:o}):(this.getArcLength=q,this.getPoint=T,this.getDerivative=_,this.d={x:0,y:0}),this.length=this.getArcLength([this.a.x,this.b.x,this.c.x,this.d.x],[this.a.y,this.b.y,this.c.y,this.d.y],1)})),O=e((function(t){var n=this;i(this,"length",0),i(this,"partial_lengths",[]),i(this,"functions",[]),i(this,"initial_point",null),i(this,"getPartAtLength",(function(t){t<0?t=0:t>n.length&&(t=n.length);for(var e=n.partial_lengths.length-1;n.partial_lengths[e]>=t&&e>0;)e--;return e++,{fraction:t-n.partial_lengths[e-1],i:e}})),i(this,"getTotalLength",(function(){return n.length})),i(this,"getPointAtLength",(function(t){var e=n.getPartAtLength(t),i=n.functions[e.i];if(i)return i.getPointAtLength(e.fraction);if(n.initial_point)return n.initial_point;throw new Error("Wrong function at this part.")})),i(this,"getTangentAtLength",(function(t){var e=n.getPartAtLength(t),i=n.functions[e.i];if(i)return i.getTangentAtLength(e.fraction);if(n.initial_point)return{x:0,y:0};throw new Error("Wrong function at this part.")})),i(this,"getPropertiesAtLength",(function(t){var e=n.getPartAtLength(t),i=n.functions[e.i];if(i)return i.getPropertiesAtLength(e.fraction);if(n.initial_point)return{x:n.initial_point.x,y:n.initial_point.y,tangentX:0,tangentY:0};throw new Error("Wrong function at this part.")})),i(this,"getParts",(function(){for(var t=[],e=0;e<n.functions.length;e++)if(null!==n.functions[e]){n.functions[e]=n.functions[e];var i={start:n.functions[e].getPointAtLength(0),end:n.functions[e].getPointAtLength(n.partial_lengths[e]-n.partial_lengths[e-1]),length:n.partial_lengths[e]-n.partial_lengths[e-1],getPointAtLength:n.functions[e].getPointAtLength,getTangentAtLength:n.functions[e].getTangentAtLength,getPropertiesAtLength:n.functions[e].getPropertiesAtLength};t.push(i)}return t}));for(var e,h=Array.isArray(t)?t:function(t){var n=(t&&t.length>0?t:"M0,0").match(o);if(!n)throw new Error("No path elements found in string ".concat(t));return n.reduce((function(t,n){var e=n.charAt(0),i=e.toLowerCase(),h=u(n.substring(1));if("m"===i&&h.length>2&&(t.push([e].concat(r(h.splice(0,2)))),i="l",e="m"===e?"l":"L"),"a"===i.toLowerCase()&&(5===h.length||6===h.length)){var s=n.substring(1).trim().split(" ");h=[Number(s[0]),Number(s[1]),Number(s[2]),Number(s[3].charAt(0)),Number(s[3].charAt(1)),Number(s[3].substring(2)),Number(s[4])]}for(;h.length>=0;){if(h.length===a[i]){t.push([e].concat(r(h.splice(0,a[i]))));break}if(h.length<a[i])throw new Error('Malformed path data: "'.concat(e,'" must have ').concat(a[i]," elements and has ").concat(h.length,": ").concat(n));t.push([e].concat(r(h.splice(0,a[i]))))}return t}),[])}(t),s=[0,0],g=[0,0],f=[0,0],y=0;y<h.length;y++){if("M"===h[y][0])f=[(s=[h[y][1],h[y][2]])[0],s[1]],this.functions.push(null),0===y&&(this.initial_point={x:h[y][1],y:h[y][2]});else if("m"===h[y][0])f=[(s=[h[y][1]+s[0],h[y][2]+s[1]])[0],s[1]],this.functions.push(null);else if("L"===h[y][0])this.length+=Math.sqrt(Math.pow(s[0]-h[y][1],2)+Math.pow(s[1]-h[y][2],2)),this.functions.push(new l(s[0],h[y][1],s[1],h[y][2])),s=[h[y][1],h[y][2]];else if("l"===h[y][0])this.length+=Math.sqrt(Math.pow(h[y][1],2)+Math.pow(h[y][2],2)),this.functions.push(new l(s[0],h[y][1]+s[0],s[1],h[y][2]+s[1])),s=[h[y][1]+s[0],h[y][2]+s[1]];else if("H"===h[y][0])this.length+=Math.abs(s[0]-h[y][1]),this.functions.push(new l(s[0],h[y][1],s[1],s[1])),s[0]=h[y][1];else if("h"===h[y][0])this.length+=Math.abs(h[y][1]),this.functions.push(new l(s[0],s[0]+h[y][1],s[1],s[1])),s[0]=h[y][1]+s[0];else if("V"===h[y][0])this.length+=Math.abs(s[1]-h[y][1]),this.functions.push(new l(s[0],s[0],s[1],h[y][1])),s[1]=h[y][1];else if("v"===h[y][0])this.length+=Math.abs(h[y][1]),this.functions.push(new l(s[0],s[0],s[1],s[1]+h[y][1])),s[1]=h[y][1]+s[1];else if("z"===h[y][0]||"Z"===h[y][0])this.length+=Math.sqrt(Math.pow(f[0]-s[0],2)+Math.pow(f[1]-s[1],2)),this.functions.push(new l(s[0],f[0],s[1],f[1])),s=[f[0],f[1]];else if("C"===h[y][0])e=new j(s[0],s[1],h[y][1],h[y][2],h[y][3],h[y][4],h[y][5],h[y][6]),this.length+=e.getTotalLength(),s=[h[y][5],h[y][6]],this.functions.push(e);else if("c"===h[y][0])(e=new j(s[0],s[1],s[0]+h[y][1],s[1]+h[y][2],s[0]+h[y][3],s[1]+h[y][4],s[0]+h[y][5],s[1]+h[y][6])).getTotalLength()>0?(this.length+=e.getTotalLength(),this.functions.push(e),s=[h[y][5]+s[0],h[y][6]+s[1]]):this.functions.push(new l(s[0],s[0],s[1],s[1]));else if("S"===h[y][0]){if(y>0&&["C","c","S","s"].indexOf(h[y-1][0])>-1){if(e){var p=e.getC();e=new j(s[0],s[1],2*s[0]-p.x,2*s[1]-p.y,h[y][1],h[y][2],h[y][3],h[y][4])}}else e=new j(s[0],s[1],s[0],s[1],h[y][1],h[y][2],h[y][3],h[y][4]);e&&(this.length+=e.getTotalLength(),s=[h[y][3],h[y][4]],this.functions.push(e))}else if("s"===h[y][0]){if(y>0&&["C","c","S","s"].indexOf(h[y-1][0])>-1){if(e){var x=e.getC(),v=e.getD();e=new j(s[0],s[1],s[0]+v.x-x.x,s[1]+v.y-x.y,s[0]+h[y][1],s[1]+h[y][2],s[0]+h[y][3],s[1]+h[y][4])}}else e=new j(s[0],s[1],s[0],s[1],s[0]+h[y][1],s[1]+h[y][2],s[0]+h[y][3],s[1]+h[y][4]);e&&(this.length+=e.getTotalLength(),s=[h[y][3]+s[0],h[y][4]+s[1]],this.functions.push(e))}else if("Q"===h[y][0]){if(s[0]==h[y][1]&&s[1]==h[y][2]){var M=new l(h[y][1],h[y][3],h[y][2],h[y][4]);this.length+=M.getTotalLength(),this.functions.push(M)}else e=new j(s[0],s[1],h[y][1],h[y][2],h[y][3],h[y][4],void 0,void 0),this.length+=e.getTotalLength(),this.functions.push(e);s=[h[y][3],h[y][4]],g=[h[y][1],h[y][2]]}else if("q"===h[y][0]){if(0!=h[y][1]||0!=h[y][2])e=new j(s[0],s[1],s[0]+h[y][1],s[1]+h[y][2],s[0]+h[y][3],s[1]+h[y][4],void 0,void 0),this.length+=e.getTotalLength(),this.functions.push(e);else{var w=new l(s[0]+h[y][1],s[0]+h[y][3],s[1]+h[y][2],s[1]+h[y][4]);this.length+=w.getTotalLength(),this.functions.push(w)}g=[s[0]+h[y][1],s[1]+h[y][2]],s=[h[y][3]+s[0],h[y][4]+s[1]]}else if("T"===h[y][0]){if(y>0&&["Q","q","T","t"].indexOf(h[y-1][0])>-1)e=new j(s[0],s[1],2*s[0]-g[0],2*s[1]-g[1],h[y][1],h[y][2],void 0,void 0),this.functions.push(e),this.length+=e.getTotalLength();else{var L=new l(s[0],h[y][1],s[1],h[y][2]);this.functions.push(L),this.length+=L.getTotalLength()}g=[2*s[0]-g[0],2*s[1]-g[1]],s=[h[y][1],h[y][2]]}else if("t"===h[y][0]){if(y>0&&["Q","q","T","t"].indexOf(h[y-1][0])>-1)e=new j(s[0],s[1],2*s[0]-g[0],2*s[1]-g[1],s[0]+h[y][1],s[1]+h[y][2],void 0,void 0),this.length+=e.getTotalLength(),this.functions.push(e);else{var d=new l(s[0],s[0]+h[y][1],s[1],s[1]+h[y][2]);this.length+=d.getTotalLength(),this.functions.push(d)}g=[2*s[0]-g[0],2*s[1]-g[1]],s=[h[y][1]+s[0],h[y][2]+s[1]]}else if("A"===h[y][0]){var A=new c(s[0],s[1],h[y][1],h[y][2],h[y][3],1===h[y][4],1===h[y][5],h[y][6],h[y][7]);this.length+=A.getTotalLength(),s=[h[y][6],h[y][7]],this.functions.push(A)}else if("a"===h[y][0]){var b=new c(s[0],s[1],h[y][1],h[y][2],h[y][3],1===h[y][4],1===h[y][5],s[0]+h[y][6],s[1]+h[y][7]);this.length+=b.getTotalLength(),s=[s[0]+h[y][6],s[1]+h[y][7]],this.functions.push(b)}this.partial_lengths.push(this.length)}})),E=e((function(t){var n=this;if(i(this,"inst",void 0),i(this,"getTotalLength",(function(){return n.inst.getTotalLength()})),i(this,"getPointAtLength",(function(t){return n.inst.getPointAtLength(t)})),i(this,"getTangentAtLength",(function(t){return n.inst.getTangentAtLength(t)})),i(this,"getPropertiesAtLength",(function(t){return n.inst.getPropertiesAtLength(t)})),i(this,"getParts",(function(){return n.inst.getParts()})),this.inst=new O(t),!(this instanceof E))return new E(t)}));t.svgPathProperties=E}));
custom_nodes/comfyui-kjnodes/nodes/__pycache__/audioscheduler_nodes.cpython-310.pyc ADDED
Binary file (6.19 kB). View file
 
custom_nodes/comfyui-kjnodes/nodes/__pycache__/batchcrop_nodes.cpython-310.pyc ADDED
Binary file (17.6 kB). View file
 
custom_nodes/comfyui-kjnodes/nodes/__pycache__/curve_nodes.cpython-310.pyc ADDED
Binary file (42.2 kB). View file
 
custom_nodes/comfyui-kjnodes/nodes/__pycache__/image_nodes.cpython-310.pyc ADDED
Binary file (94.4 kB). View file