3v324v23 commited on
Commit
1e3b872
·
0 Parent(s):
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +64 -0
  2. ComfyUI-Advanced-ControlNet/LICENSE +674 -0
  3. ComfyUI-Advanced-ControlNet/README.md +202 -0
  4. ComfyUI-Advanced-ControlNet/__init__.py +3 -0
  5. ComfyUI-Advanced-ControlNet/__pycache__/__init__.cpython-310.pyc +0 -0
  6. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control.cpython-310.pyc +0 -0
  7. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_lllite.cpython-310.pyc +0 -0
  8. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_reference.cpython-310.pyc +0 -0
  9. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_sparsectrl.cpython-310.pyc +0 -0
  10. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_svd.cpython-310.pyc +0 -0
  11. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/logger.cpython-310.pyc +0 -0
  12. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes.cpython-310.pyc +0 -0
  13. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_deprecated.cpython-310.pyc +0 -0
  14. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_keyframes.cpython-310.pyc +0 -0
  15. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_loosecontrol.cpython-310.pyc +0 -0
  16. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_reference.cpython-310.pyc +0 -0
  17. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_sparsectrl.cpython-310.pyc +0 -0
  18. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_weight.cpython-310.pyc +0 -0
  19. ComfyUI-Advanced-ControlNet/adv_control/__pycache__/utils.cpython-310.pyc +0 -0
  20. ComfyUI-Advanced-ControlNet/adv_control/control.py +899 -0
  21. ComfyUI-Advanced-ControlNet/adv_control/control_lllite.py +254 -0
  22. ComfyUI-Advanced-ControlNet/adv_control/control_reference.py +833 -0
  23. ComfyUI-Advanced-ControlNet/adv_control/control_sparsectrl.py +1081 -0
  24. ComfyUI-Advanced-ControlNet/adv_control/control_svd.py +517 -0
  25. ComfyUI-Advanced-ControlNet/adv_control/logger.py +36 -0
  26. ComfyUI-Advanced-ControlNet/adv_control/nodes.py +237 -0
  27. ComfyUI-Advanced-ControlNet/adv_control/nodes_deprecated.py +71 -0
  28. ComfyUI-Advanced-ControlNet/adv_control/nodes_keyframes.py +461 -0
  29. ComfyUI-Advanced-ControlNet/adv_control/nodes_loosecontrol.py +67 -0
  30. ComfyUI-Advanced-ControlNet/adv_control/nodes_reference.py +90 -0
  31. ComfyUI-Advanced-ControlNet/adv_control/nodes_sparsectrl.py +182 -0
  32. ComfyUI-Advanced-ControlNet/adv_control/nodes_weight.py +233 -0
  33. ComfyUI-Advanced-ControlNet/adv_control/utils.py +927 -0
  34. ComfyUI-Advanced-ControlNet/pyproject.toml +15 -0
  35. ComfyUI-Advanced-ControlNet/requirements.txt +0 -0
  36. ComfyUI-Allor/LICENSE +21 -0
  37. ComfyUI-Allor/Loader.py +351 -0
  38. ComfyUI-Allor/README.MD +54 -0
  39. ComfyUI-Allor/__init__.py +12 -0
  40. ComfyUI-Allor/__pycache__/Loader.cpython-310.pyc +0 -0
  41. ComfyUI-Allor/__pycache__/__init__.cpython-310.pyc +0 -0
  42. ComfyUI-Allor/config.json +35 -0
  43. ComfyUI-Allor/install.bat +148 -0
  44. ComfyUI-Allor/install.sh +86 -0
  45. ComfyUI-Allor/modules/AlphaChanel.py +170 -0
  46. ComfyUI-Allor/modules/Clamp.py +275 -0
  47. ComfyUI-Allor/modules/ImageBatch.py +199 -0
  48. ComfyUI-Allor/modules/ImageComposite.py +377 -0
  49. ComfyUI-Allor/modules/ImageContainer.py +315 -0
  50. ComfyUI-Allor/modules/ImageDraw.py +1847 -0
.gitattributes ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ comfyui_controlnet_aux/ckpts/LayerNorm/DensePose-TorchScript-with-hint-image/densepose_r101_fpn_dl.torchscript filter=lfs diff=lfs merge=lfs -text
2
+ comfyui_controlnet_aux/ckpts/LayerNorm/DensePose-TorchScript-with-hint-image/densepose_r50_fpn_dl.torchscript filter=lfs diff=lfs merge=lfs -text
3
+ comfyui_controlnet_aux/ckpts/hr16/DWPose-TorchScript-BatchSize5/dw-ll_ucoco_384_bs5.torchscript.pt filter=lfs diff=lfs merge=lfs -text
4
+ comfyui_controlnet_aux/ckpts/hr16/UnJIT-DWPose/dw-ll_ucoco.onnx filter=lfs diff=lfs merge=lfs -text
5
+ comfyui_controlnet_aux/ckpts/hr16/yolo-nas-fp16/yolo_nas_s_fp16.onnx filter=lfs diff=lfs merge=lfs -text
6
+ comfyui_controlnet_aux/ckpts/hr16/ControlNet-HandRefiner-pruned/hrnetv2_w64_imagenet_pretrained.pth filter=lfs diff=lfs merge=lfs -text
7
+ comfyui_controlnet_aux/ckpts/hr16/ControlNet-HandRefiner-pruned/graphormer_hand_state_dict.bin filter=lfs diff=lfs merge=lfs -text
8
+ comfyui_controlnet_aux/ckpts/lllyasviel/Annotators/ZoeD_M12_N.pt filter=lfs diff=lfs merge=lfs -text
9
+ comfyui_controlnet_aux/ckpts/lllyasviel/Annotators/dpt_hybrid-midas-501f0c75.pt filter=lfs diff=lfs merge=lfs -text
10
+ comfyui_controlnet_aux/ckpts/lllyasviel/Annotators/150_16_swin_l_oneformer_coco_100ep.pth filter=lfs diff=lfs merge=lfs -text
11
+ comfyui_controlnet_aux/ckpts/lllyasviel/Annotators/250_16_swin_l_oneformer_ade20k_160k.pth filter=lfs diff=lfs merge=lfs -text
12
+ comfyui_controlnet_aux/ckpts/yzd-v/DWPose/dw-ll_ucoco_384.onnx filter=lfs diff=lfs merge=lfs -text
13
+ comfyui_controlnet_aux/ckpts/yzd-v/DWPose/yolox_l.onnx filter=lfs diff=lfs merge=lfs -text
14
+ comfyui_controlnet_aux/ckpts/dhkim2810/MobileSAM/mobile_sam.pt filter=lfs diff=lfs merge=lfs -text
15
+ comfyui_controlnet_aux/examples/example_mesh_graphormer.png filter=lfs diff=lfs merge=lfs -text
16
+ comfyui_controlnet_aux/src/controlnet_aux/mesh_graphormer/hand_landmarker.task filter=lfs diff=lfs merge=lfs -text
17
+ ComfyUI-Flowty-LDSR/example_highres.png filter=lfs diff=lfs merge=lfs -text
18
+ ComfyUI-Frame-Interpolation/test_vfi_schedule.gif filter=lfs diff=lfs merge=lfs -text
19
+ ComfyUI-Frame-Interpolation/ckpts/rife/rife47.pth filter=lfs diff=lfs merge=lfs -text
20
+ ComfyUI-KJNodes/intrinsic_loras/intrinsic_lora_sd15_albedo.safetensors filter=lfs diff=lfs merge=lfs -text
21
+ ComfyUI-KJNodes/intrinsic_loras/intrinsic_lora_sd15_depth.safetensors filter=lfs diff=lfs merge=lfs -text
22
+ ComfyUI-KJNodes/intrinsic_loras/intrinsic_lora_sd15_normal.safetensors filter=lfs diff=lfs merge=lfs -text
23
+ ComfyUI-KJNodes/intrinsic_loras/intrinsic_lora_sd15_shading.safetensors filter=lfs diff=lfs merge=lfs -text
24
+ ComfyUI-MimicMotionWrapper/assets/example_data/videos/pose1.mp4 filter=lfs diff=lfs merge=lfs -text
25
+ comfyui-mixlab-nodes/assets/fonts/庞门正道粗书体6.0.ttf filter=lfs diff=lfs merge=lfs -text
26
+ comfyui-mixlab-nodes/assets/fonts/有爱黑体ARHei.ttf filter=lfs diff=lfs merge=lfs -text
27
+ comfyui-mixlab-nodes/assets/fonts/有爱黑体arheiuhk_bd.ttf filter=lfs diff=lfs merge=lfs -text
28
+ comfyui-mixlab-nodes/assets/fonts/王汉宗颜楷体繁.ttf filter=lfs diff=lfs merge=lfs -text
29
+ comfyui-mixlab-nodes/assets/FangSong.ttf filter=lfs diff=lfs merge=lfs -text
30
+ comfyui-mixlab-nodes/assets/MaterialsVariantsShoe.glb filter=lfs diff=lfs merge=lfs -text
31
+ comfyui-mixlab-nodes/assets/NeilArmstrong.glb filter=lfs diff=lfs merge=lfs -text
32
+ comfyui-mixlab-nodes/assets/layers-workflow.svg filter=lfs diff=lfs merge=lfs -text
33
+ comfyui-mixlab-nodes/assets/poster-workflow.svg filter=lfs diff=lfs merge=lfs -text
34
+ ComfyUI-Universal-Styler/LORAS/demo_nai00.safetensors filter=lfs diff=lfs merge=lfs -text
35
+ efficiency-nodes-comfyui/images/nodes/AnimateDiff[[:space:]]&[[:space:]]HiResFix[[:space:]]Scripts.gif filter=lfs diff=lfs merge=lfs -text
36
+ efficiency-nodes-comfyui/images/nodes/HighResFix[[:space:]]-[[:space:]]Node[[:space:]]Example.gif filter=lfs diff=lfs merge=lfs -text
37
+ efficiency-nodes-comfyui/images/nodes/Tiled[[:space:]]Upscaler[[:space:]]-[[:space:]]Node[[:space:]]Example.gif filter=lfs diff=lfs merge=lfs -text
38
+ efficiency-nodes-comfyui/images/ComfyUI_temp_vpose_00005_.png filter=lfs diff=lfs merge=lfs -text
39
+ efficiency-nodes-comfyui/py/sd15_resizer.pt filter=lfs diff=lfs merge=lfs -text
40
+ efficiency-nodes-comfyui/py/sdxl_resizer.pt filter=lfs diff=lfs merge=lfs -text
41
+ efficiency-nodes-comfyui/workflows/AnimateDiff[[:space:]]&[[:space:]]HiResFix[[:space:]]Scripts.gif filter=lfs diff=lfs merge=lfs -text
42
+ efficiency-nodes-comfyui/workflows/Eff_multiKsampler_withScriptsSDXL.png filter=lfs diff=lfs merge=lfs -text
43
+ efficiency-nodes-comfyui/workflows/eff_animatescriptWF001.gif filter=lfs diff=lfs merge=lfs -text
44
+ Lora-Training-in-Comfy/sd-scripts/bitsandbytes_windows/libbitsandbytes_cuda118.dll filter=lfs diff=lfs merge=lfs -text
45
+ was-node-suite-comfyui/repos/SAM/notebooks/predictor_example.ipynb filter=lfs diff=lfs merge=lfs -text
46
+ wefa-door/huggingface-cloth-segmentation/model/cloth_segm.pth filter=lfs diff=lfs merge=lfs -text
47
+ # Track all image files in specific directories
48
+ ComfyUI-Flowty-LDSR/*.png filter=lfs diff=lfs merge=lfs -text
49
+ ComfyUI-Frame-Interpolation/**/*.png filter=lfs diff=lfs merge=lfs -text
50
+ ComfyUI-YOLO/doc/*.png filter=lfs diff=lfs merge=lfs -text
51
+ efficiency-nodes-comfyui/images/**/*.png filter=lfs diff=lfs merge=lfs -text
52
+ efficiency-nodes-comfyui/images/**/*.gif filter=lfs diff=lfs merge=lfs -text
53
+ efficiency-nodes-comfyui/workflows/*.png filter=lfs diff=lfs merge=lfs -text
54
+ was-node-suite-comfyui/repos/SAM/assets/*.png filter=lfs diff=lfs merge=lfs -text
55
+ was-node-suite-comfyui/repos/SAM/assets/*.gif filter=lfs diff=lfs merge=lfs -text
56
+ # Specific large data or model files
57
+ ComfyUI_tinyterraNodes/images/*.png filter=lfs diff=lfs merge=lfs -text
58
+ Lora-Training-in-Comfy/sd-scripts/bitsandbytes_windows/*.dll filter=lfs diff=lfs merge=lfs -text
59
+ comfyui-mixlab-nodes/web/lib/miniPaint-4.14.2/images/*.gif filter=lfs diff=lfs merge=lfs -text
60
+ comfyui_controlnet_aux/src/custom_mesh_graphormer/modeling/data/*.pkl filter=lfs diff=lfs merge=lfs -text
61
+ comfyui_controlnet_aux/src/custom_mesh_graphormer/modeling/data/*.npz filter=lfs diff=lfs merge=lfs -text
62
+ comfyui_controlnet_aux/src/custom_oneformer/data/*.txt.gz filter=lfs diff=lfs merge=lfs -text
63
+ rgthree-comfy/docs/*.png filter=lfs diff=lfs merge=lfs -text
64
+ comfyui-mixlab-nodes/assets/VisualStylePrompting.png filter=lfs diff=lfs merge=lfs -text
ComfyUI-Advanced-ControlNet/LICENSE ADDED
@@ -0,0 +1,674 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ GNU GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+ Preamble
9
+
10
+ The GNU General Public License is a free, copyleft license for
11
+ software and other kinds of works.
12
+
13
+ The licenses for most software and other practical works are designed
14
+ to take away your freedom to share and change the works. By contrast,
15
+ the GNU General Public License is intended to guarantee your freedom to
16
+ share and change all versions of a program--to make sure it remains free
17
+ software for all its users. We, the Free Software Foundation, use the
18
+ GNU General Public License for most of our software; it applies also to
19
+ any other work released this way by its authors. You can apply it to
20
+ your programs, too.
21
+
22
+ When we speak of free software, we are referring to freedom, not
23
+ price. Our General Public Licenses are designed to make sure that you
24
+ have the freedom to distribute copies of free software (and charge for
25
+ them if you wish), that you receive source code or can get it if you
26
+ want it, that you can change the software or use pieces of it in new
27
+ free programs, and that you know you can do these things.
28
+
29
+ To protect your rights, we need to prevent others from denying you
30
+ these rights or asking you to surrender the rights. Therefore, you have
31
+ certain responsibilities if you distribute copies of the software, or if
32
+ you modify it: responsibilities to respect the freedom of others.
33
+
34
+ For example, if you distribute copies of such a program, whether
35
+ gratis or for a fee, you must pass on to the recipients the same
36
+ freedoms that you received. You must make sure that they, too, receive
37
+ or can get the source code. And you must show them these terms so they
38
+ know their rights.
39
+
40
+ Developers that use the GNU GPL protect your rights with two steps:
41
+ (1) assert copyright on the software, and (2) offer you this License
42
+ giving you legal permission to copy, distribute and/or modify it.
43
+
44
+ For the developers' and authors' protection, the GPL clearly explains
45
+ that there is no warranty for this free software. For both users' and
46
+ authors' sake, the GPL requires that modified versions be marked as
47
+ changed, so that their problems will not be attributed erroneously to
48
+ authors of previous versions.
49
+
50
+ Some devices are designed to deny users access to install or run
51
+ modified versions of the software inside them, although the manufacturer
52
+ can do so. This is fundamentally incompatible with the aim of
53
+ protecting users' freedom to change the software. The systematic
54
+ pattern of such abuse occurs in the area of products for individuals to
55
+ use, which is precisely where it is most unacceptable. Therefore, we
56
+ have designed this version of the GPL to prohibit the practice for those
57
+ products. If such problems arise substantially in other domains, we
58
+ stand ready to extend this provision to those domains in future versions
59
+ of the GPL, as needed to protect the freedom of users.
60
+
61
+ Finally, every program is threatened constantly by software patents.
62
+ States should not allow patents to restrict development and use of
63
+ software on general-purpose computers, but in those that do, we wish to
64
+ avoid the special danger that patents applied to a free program could
65
+ make it effectively proprietary. To prevent this, the GPL assures that
66
+ patents cannot be used to render the program non-free.
67
+
68
+ The precise terms and conditions for copying, distribution and
69
+ modification follow.
70
+
71
+ TERMS AND CONDITIONS
72
+
73
+ 0. Definitions.
74
+
75
+ "This License" refers to version 3 of the GNU General Public License.
76
+
77
+ "Copyright" also means copyright-like laws that apply to other kinds of
78
+ works, such as semiconductor masks.
79
+
80
+ "The Program" refers to any copyrightable work licensed under this
81
+ License. Each licensee is addressed as "you". "Licensees" and
82
+ "recipients" may be individuals or organizations.
83
+
84
+ To "modify" a work means to copy from or adapt all or part of the work
85
+ in a fashion requiring copyright permission, other than the making of an
86
+ exact copy. The resulting work is called a "modified version" of the
87
+ earlier work or a work "based on" the earlier work.
88
+
89
+ A "covered work" means either the unmodified Program or a work based
90
+ on the Program.
91
+
92
+ To "propagate" a work means to do anything with it that, without
93
+ permission, would make you directly or secondarily liable for
94
+ infringement under applicable copyright law, except executing it on a
95
+ computer or modifying a private copy. Propagation includes copying,
96
+ distribution (with or without modification), making available to the
97
+ public, and in some countries other activities as well.
98
+
99
+ To "convey" a work means any kind of propagation that enables other
100
+ parties to make or receive copies. Mere interaction with a user through
101
+ a computer network, with no transfer of a copy, is not conveying.
102
+
103
+ An interactive user interface displays "Appropriate Legal Notices"
104
+ to the extent that it includes a convenient and prominently visible
105
+ feature that (1) displays an appropriate copyright notice, and (2)
106
+ tells the user that there is no warranty for the work (except to the
107
+ extent that warranties are provided), that licensees may convey the
108
+ work under this License, and how to view a copy of this License. If
109
+ the interface presents a list of user commands or options, such as a
110
+ menu, a prominent item in the list meets this criterion.
111
+
112
+ 1. Source Code.
113
+
114
+ The "source code" for a work means the preferred form of the work
115
+ for making modifications to it. "Object code" means any non-source
116
+ form of a work.
117
+
118
+ A "Standard Interface" means an interface that either is an official
119
+ standard defined by a recognized standards body, or, in the case of
120
+ interfaces specified for a particular programming language, one that
121
+ is widely used among developers working in that language.
122
+
123
+ The "System Libraries" of an executable work include anything, other
124
+ than the work as a whole, that (a) is included in the normal form of
125
+ packaging a Major Component, but which is not part of that Major
126
+ Component, and (b) serves only to enable use of the work with that
127
+ Major Component, or to implement a Standard Interface for which an
128
+ implementation is available to the public in source code form. A
129
+ "Major Component", in this context, means a major essential component
130
+ (kernel, window system, and so on) of the specific operating system
131
+ (if any) on which the executable work runs, or a compiler used to
132
+ produce the work, or an object code interpreter used to run it.
133
+
134
+ The "Corresponding Source" for a work in object code form means all
135
+ the source code needed to generate, install, and (for an executable
136
+ work) run the object code and to modify the work, including scripts to
137
+ control those activities. However, it does not include the work's
138
+ System Libraries, or general-purpose tools or generally available free
139
+ programs which are used unmodified in performing those activities but
140
+ which are not part of the work. For example, Corresponding Source
141
+ includes interface definition files associated with source files for
142
+ the work, and the source code for shared libraries and dynamically
143
+ linked subprograms that the work is specifically designed to require,
144
+ such as by intimate data communication or control flow between those
145
+ subprograms and other parts of the work.
146
+
147
+ The Corresponding Source need not include anything that users
148
+ can regenerate automatically from other parts of the Corresponding
149
+ Source.
150
+
151
+ The Corresponding Source for a work in source code form is that
152
+ same work.
153
+
154
+ 2. Basic Permissions.
155
+
156
+ All rights granted under this License are granted for the term of
157
+ copyright on the Program, and are irrevocable provided the stated
158
+ conditions are met. This License explicitly affirms your unlimited
159
+ permission to run the unmodified Program. The output from running a
160
+ covered work is covered by this License only if the output, given its
161
+ content, constitutes a covered work. This License acknowledges your
162
+ rights of fair use or other equivalent, as provided by copyright law.
163
+
164
+ You may make, run and propagate covered works that you do not
165
+ convey, without conditions so long as your license otherwise remains
166
+ in force. You may convey covered works to others for the sole purpose
167
+ of having them make modifications exclusively for you, or provide you
168
+ with facilities for running those works, provided that you comply with
169
+ the terms of this License in conveying all material for which you do
170
+ not control copyright. Those thus making or running the covered works
171
+ for you must do so exclusively on your behalf, under your direction
172
+ and control, on terms that prohibit them from making any copies of
173
+ your copyrighted material outside their relationship with you.
174
+
175
+ Conveying under any other circumstances is permitted solely under
176
+ the conditions stated below. Sublicensing is not allowed; section 10
177
+ makes it unnecessary.
178
+
179
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180
+
181
+ No covered work shall be deemed part of an effective technological
182
+ measure under any applicable law fulfilling obligations under article
183
+ 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184
+ similar laws prohibiting or restricting circumvention of such
185
+ measures.
186
+
187
+ When you convey a covered work, you waive any legal power to forbid
188
+ circumvention of technological measures to the extent such circumvention
189
+ is effected by exercising rights under this License with respect to
190
+ the covered work, and you disclaim any intention to limit operation or
191
+ modification of the work as a means of enforcing, against the work's
192
+ users, your or third parties' legal rights to forbid circumvention of
193
+ technological measures.
194
+
195
+ 4. Conveying Verbatim Copies.
196
+
197
+ You may convey verbatim copies of the Program's source code as you
198
+ receive it, in any medium, provided that you conspicuously and
199
+ appropriately publish on each copy an appropriate copyright notice;
200
+ keep intact all notices stating that this License and any
201
+ non-permissive terms added in accord with section 7 apply to the code;
202
+ keep intact all notices of the absence of any warranty; and give all
203
+ recipients a copy of this License along with the Program.
204
+
205
+ You may charge any price or no price for each copy that you convey,
206
+ and you may offer support or warranty protection for a fee.
207
+
208
+ 5. Conveying Modified Source Versions.
209
+
210
+ You may convey a work based on the Program, or the modifications to
211
+ produce it from the Program, in the form of source code under the
212
+ terms of section 4, provided that you also meet all of these conditions:
213
+
214
+ a) The work must carry prominent notices stating that you modified
215
+ it, and giving a relevant date.
216
+
217
+ b) The work must carry prominent notices stating that it is
218
+ released under this License and any conditions added under section
219
+ 7. This requirement modifies the requirement in section 4 to
220
+ "keep intact all notices".
221
+
222
+ c) You must license the entire work, as a whole, under this
223
+ License to anyone who comes into possession of a copy. This
224
+ License will therefore apply, along with any applicable section 7
225
+ additional terms, to the whole of the work, and all its parts,
226
+ regardless of how they are packaged. This License gives no
227
+ permission to license the work in any other way, but it does not
228
+ invalidate such permission if you have separately received it.
229
+
230
+ d) If the work has interactive user interfaces, each must display
231
+ Appropriate Legal Notices; however, if the Program has interactive
232
+ interfaces that do not display Appropriate Legal Notices, your
233
+ work need not make them do so.
234
+
235
+ A compilation of a covered work with other separate and independent
236
+ works, which are not by their nature extensions of the covered work,
237
+ and which are not combined with it such as to form a larger program,
238
+ in or on a volume of a storage or distribution medium, is called an
239
+ "aggregate" if the compilation and its resulting copyright are not
240
+ used to limit the access or legal rights of the compilation's users
241
+ beyond what the individual works permit. Inclusion of a covered work
242
+ in an aggregate does not cause this License to apply to the other
243
+ parts of the aggregate.
244
+
245
+ 6. Conveying Non-Source Forms.
246
+
247
+ You may convey a covered work in object code form under the terms
248
+ of sections 4 and 5, provided that you also convey the
249
+ machine-readable Corresponding Source under the terms of this License,
250
+ in one of these ways:
251
+
252
+ a) Convey the object code in, or embodied in, a physical product
253
+ (including a physical distribution medium), accompanied by the
254
+ Corresponding Source fixed on a durable physical medium
255
+ customarily used for software interchange.
256
+
257
+ b) Convey the object code in, or embodied in, a physical product
258
+ (including a physical distribution medium), accompanied by a
259
+ written offer, valid for at least three years and valid for as
260
+ long as you offer spare parts or customer support for that product
261
+ model, to give anyone who possesses the object code either (1) a
262
+ copy of the Corresponding Source for all the software in the
263
+ product that is covered by this License, on a durable physical
264
+ medium customarily used for software interchange, for a price no
265
+ more than your reasonable cost of physically performing this
266
+ conveying of source, or (2) access to copy the
267
+ Corresponding Source from a network server at no charge.
268
+
269
+ c) Convey individual copies of the object code with a copy of the
270
+ written offer to provide the Corresponding Source. This
271
+ alternative is allowed only occasionally and noncommercially, and
272
+ only if you received the object code with such an offer, in accord
273
+ with subsection 6b.
274
+
275
+ d) Convey the object code by offering access from a designated
276
+ place (gratis or for a charge), and offer equivalent access to the
277
+ Corresponding Source in the same way through the same place at no
278
+ further charge. You need not require recipients to copy the
279
+ Corresponding Source along with the object code. If the place to
280
+ copy the object code is a network server, the Corresponding Source
281
+ may be on a different server (operated by you or a third party)
282
+ that supports equivalent copying facilities, provided you maintain
283
+ clear directions next to the object code saying where to find the
284
+ Corresponding Source. Regardless of what server hosts the
285
+ Corresponding Source, you remain obligated to ensure that it is
286
+ available for as long as needed to satisfy these requirements.
287
+
288
+ e) Convey the object code using peer-to-peer transmission, provided
289
+ you inform other peers where the object code and Corresponding
290
+ Source of the work are being offered to the general public at no
291
+ charge under subsection 6d.
292
+
293
+ A separable portion of the object code, whose source code is excluded
294
+ from the Corresponding Source as a System Library, need not be
295
+ included in conveying the object code work.
296
+
297
+ A "User Product" is either (1) a "consumer product", which means any
298
+ tangible personal property which is normally used for personal, family,
299
+ or household purposes, or (2) anything designed or sold for incorporation
300
+ into a dwelling. In determining whether a product is a consumer product,
301
+ doubtful cases shall be resolved in favor of coverage. For a particular
302
+ product received by a particular user, "normally used" refers to a
303
+ typical or common use of that class of product, regardless of the status
304
+ of the particular user or of the way in which the particular user
305
+ actually uses, or expects or is expected to use, the product. A product
306
+ is a consumer product regardless of whether the product has substantial
307
+ commercial, industrial or non-consumer uses, unless such uses represent
308
+ the only significant mode of use of the product.
309
+
310
+ "Installation Information" for a User Product means any methods,
311
+ procedures, authorization keys, or other information required to install
312
+ and execute modified versions of a covered work in that User Product from
313
+ a modified version of its Corresponding Source. The information must
314
+ suffice to ensure that the continued functioning of the modified object
315
+ code is in no case prevented or interfered with solely because
316
+ modification has been made.
317
+
318
+ If you convey an object code work under this section in, or with, or
319
+ specifically for use in, a User Product, and the conveying occurs as
320
+ part of a transaction in which the right of possession and use of the
321
+ User Product is transferred to the recipient in perpetuity or for a
322
+ fixed term (regardless of how the transaction is characterized), the
323
+ Corresponding Source conveyed under this section must be accompanied
324
+ by the Installation Information. But this requirement does not apply
325
+ if neither you nor any third party retains the ability to install
326
+ modified object code on the User Product (for example, the work has
327
+ been installed in ROM).
328
+
329
+ The requirement to provide Installation Information does not include a
330
+ requirement to continue to provide support service, warranty, or updates
331
+ for a work that has been modified or installed by the recipient, or for
332
+ the User Product in which it has been modified or installed. Access to a
333
+ network may be denied when the modification itself materially and
334
+ adversely affects the operation of the network or violates the rules and
335
+ protocols for communication across the network.
336
+
337
+ Corresponding Source conveyed, and Installation Information provided,
338
+ in accord with this section must be in a format that is publicly
339
+ documented (and with an implementation available to the public in
340
+ source code form), and must require no special password or key for
341
+ unpacking, reading or copying.
342
+
343
+ 7. Additional Terms.
344
+
345
+ "Additional permissions" are terms that supplement the terms of this
346
+ License by making exceptions from one or more of its conditions.
347
+ Additional permissions that are applicable to the entire Program shall
348
+ be treated as though they were included in this License, to the extent
349
+ that they are valid under applicable law. If additional permissions
350
+ apply only to part of the Program, that part may be used separately
351
+ under those permissions, but the entire Program remains governed by
352
+ this License without regard to the additional permissions.
353
+
354
+ When you convey a copy of a covered work, you may at your option
355
+ remove any additional permissions from that copy, or from any part of
356
+ it. (Additional permissions may be written to require their own
357
+ removal in certain cases when you modify the work.) You may place
358
+ additional permissions on material, added by you to a covered work,
359
+ for which you have or can give appropriate copyright permission.
360
+
361
+ Notwithstanding any other provision of this License, for material you
362
+ add to a covered work, you may (if authorized by the copyright holders of
363
+ that material) supplement the terms of this License with terms:
364
+
365
+ a) Disclaiming warranty or limiting liability differently from the
366
+ terms of sections 15 and 16 of this License; or
367
+
368
+ b) Requiring preservation of specified reasonable legal notices or
369
+ author attributions in that material or in the Appropriate Legal
370
+ Notices displayed by works containing it; or
371
+
372
+ c) Prohibiting misrepresentation of the origin of that material, or
373
+ requiring that modified versions of such material be marked in
374
+ reasonable ways as different from the original version; or
375
+
376
+ d) Limiting the use for publicity purposes of names of licensors or
377
+ authors of the material; or
378
+
379
+ e) Declining to grant rights under trademark law for use of some
380
+ trade names, trademarks, or service marks; or
381
+
382
+ f) Requiring indemnification of licensors and authors of that
383
+ material by anyone who conveys the material (or modified versions of
384
+ it) with contractual assumptions of liability to the recipient, for
385
+ any liability that these contractual assumptions directly impose on
386
+ those licensors and authors.
387
+
388
+ All other non-permissive additional terms are considered "further
389
+ restrictions" within the meaning of section 10. If the Program as you
390
+ received it, or any part of it, contains a notice stating that it is
391
+ governed by this License along with a term that is a further
392
+ restriction, you may remove that term. If a license document contains
393
+ a further restriction but permits relicensing or conveying under this
394
+ License, you may add to a covered work material governed by the terms
395
+ of that license document, provided that the further restriction does
396
+ not survive such relicensing or conveying.
397
+
398
+ If you add terms to a covered work in accord with this section, you
399
+ must place, in the relevant source files, a statement of the
400
+ additional terms that apply to those files, or a notice indicating
401
+ where to find the applicable terms.
402
+
403
+ Additional terms, permissive or non-permissive, may be stated in the
404
+ form of a separately written license, or stated as exceptions;
405
+ the above requirements apply either way.
406
+
407
+ 8. Termination.
408
+
409
+ You may not propagate or modify a covered work except as expressly
410
+ provided under this License. Any attempt otherwise to propagate or
411
+ modify it is void, and will automatically terminate your rights under
412
+ this License (including any patent licenses granted under the third
413
+ paragraph of section 11).
414
+
415
+ However, if you cease all violation of this License, then your
416
+ license from a particular copyright holder is reinstated (a)
417
+ provisionally, unless and until the copyright holder explicitly and
418
+ finally terminates your license, and (b) permanently, if the copyright
419
+ holder fails to notify you of the violation by some reasonable means
420
+ prior to 60 days after the cessation.
421
+
422
+ Moreover, your license from a particular copyright holder is
423
+ reinstated permanently if the copyright holder notifies you of the
424
+ violation by some reasonable means, this is the first time you have
425
+ received notice of violation of this License (for any work) from that
426
+ copyright holder, and you cure the violation prior to 30 days after
427
+ your receipt of the notice.
428
+
429
+ Termination of your rights under this section does not terminate the
430
+ licenses of parties who have received copies or rights from you under
431
+ this License. If your rights have been terminated and not permanently
432
+ reinstated, you do not qualify to receive new licenses for the same
433
+ material under section 10.
434
+
435
+ 9. Acceptance Not Required for Having Copies.
436
+
437
+ You are not required to accept this License in order to receive or
438
+ run a copy of the Program. Ancillary propagation of a covered work
439
+ occurring solely as a consequence of using peer-to-peer transmission
440
+ to receive a copy likewise does not require acceptance. However,
441
+ nothing other than this License grants you permission to propagate or
442
+ modify any covered work. These actions infringe copyright if you do
443
+ not accept this License. Therefore, by modifying or propagating a
444
+ covered work, you indicate your acceptance of this License to do so.
445
+
446
+ 10. Automatic Licensing of Downstream Recipients.
447
+
448
+ Each time you convey a covered work, the recipient automatically
449
+ receives a license from the original licensors, to run, modify and
450
+ propagate that work, subject to this License. You are not responsible
451
+ for enforcing compliance by third parties with this License.
452
+
453
+ An "entity transaction" is a transaction transferring control of an
454
+ organization, or substantially all assets of one, or subdividing an
455
+ organization, or merging organizations. If propagation of a covered
456
+ work results from an entity transaction, each party to that
457
+ transaction who receives a copy of the work also receives whatever
458
+ licenses to the work the party's predecessor in interest had or could
459
+ give under the previous paragraph, plus a right to possession of the
460
+ Corresponding Source of the work from the predecessor in interest, if
461
+ the predecessor has it or can get it with reasonable efforts.
462
+
463
+ You may not impose any further restrictions on the exercise of the
464
+ rights granted or affirmed under this License. For example, you may
465
+ not impose a license fee, royalty, or other charge for exercise of
466
+ rights granted under this License, and you may not initiate litigation
467
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
468
+ any patent claim is infringed by making, using, selling, offering for
469
+ sale, or importing the Program or any portion of it.
470
+
471
+ 11. Patents.
472
+
473
+ A "contributor" is a copyright holder who authorizes use under this
474
+ License of the Program or a work on which the Program is based. The
475
+ work thus licensed is called the contributor's "contributor version".
476
+
477
+ A contributor's "essential patent claims" are all patent claims
478
+ owned or controlled by the contributor, whether already acquired or
479
+ hereafter acquired, that would be infringed by some manner, permitted
480
+ by this License, of making, using, or selling its contributor version,
481
+ but do not include claims that would be infringed only as a
482
+ consequence of further modification of the contributor version. For
483
+ purposes of this definition, "control" includes the right to grant
484
+ patent sublicenses in a manner consistent with the requirements of
485
+ this License.
486
+
487
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
488
+ patent license under the contributor's essential patent claims, to
489
+ make, use, sell, offer for sale, import and otherwise run, modify and
490
+ propagate the contents of its contributor version.
491
+
492
+ In the following three paragraphs, a "patent license" is any express
493
+ agreement or commitment, however denominated, not to enforce a patent
494
+ (such as an express permission to practice a patent or covenant not to
495
+ sue for patent infringement). To "grant" such a patent license to a
496
+ party means to make such an agreement or commitment not to enforce a
497
+ patent against the party.
498
+
499
+ If you convey a covered work, knowingly relying on a patent license,
500
+ and the Corresponding Source of the work is not available for anyone
501
+ to copy, free of charge and under the terms of this License, through a
502
+ publicly available network server or other readily accessible means,
503
+ then you must either (1) cause the Corresponding Source to be so
504
+ available, or (2) arrange to deprive yourself of the benefit of the
505
+ patent license for this particular work, or (3) arrange, in a manner
506
+ consistent with the requirements of this License, to extend the patent
507
+ license to downstream recipients. "Knowingly relying" means you have
508
+ actual knowledge that, but for the patent license, your conveying the
509
+ covered work in a country, or your recipient's use of the covered work
510
+ in a country, would infringe one or more identifiable patents in that
511
+ country that you have reason to believe are valid.
512
+
513
+ If, pursuant to or in connection with a single transaction or
514
+ arrangement, you convey, or propagate by procuring conveyance of, a
515
+ covered work, and grant a patent license to some of the parties
516
+ receiving the covered work authorizing them to use, propagate, modify
517
+ or convey a specific copy of the covered work, then the patent license
518
+ you grant is automatically extended to all recipients of the covered
519
+ work and works based on it.
520
+
521
+ A patent license is "discriminatory" if it does not include within
522
+ the scope of its coverage, prohibits the exercise of, or is
523
+ conditioned on the non-exercise of one or more of the rights that are
524
+ specifically granted under this License. You may not convey a covered
525
+ work if you are a party to an arrangement with a third party that is
526
+ in the business of distributing software, under which you make payment
527
+ to the third party based on the extent of your activity of conveying
528
+ the work, and under which the third party grants, to any of the
529
+ parties who would receive the covered work from you, a discriminatory
530
+ patent license (a) in connection with copies of the covered work
531
+ conveyed by you (or copies made from those copies), or (b) primarily
532
+ for and in connection with specific products or compilations that
533
+ contain the covered work, unless you entered into that arrangement,
534
+ or that patent license was granted, prior to 28 March 2007.
535
+
536
+ Nothing in this License shall be construed as excluding or limiting
537
+ any implied license or other defenses to infringement that may
538
+ otherwise be available to you under applicable patent law.
539
+
540
+ 12. No Surrender of Others' Freedom.
541
+
542
+ If conditions are imposed on you (whether by court order, agreement or
543
+ otherwise) that contradict the conditions of this License, they do not
544
+ excuse you from the conditions of this License. If you cannot convey a
545
+ covered work so as to satisfy simultaneously your obligations under this
546
+ License and any other pertinent obligations, then as a consequence you may
547
+ not convey it at all. For example, if you agree to terms that obligate you
548
+ to collect a royalty for further conveying from those to whom you convey
549
+ the Program, the only way you could satisfy both those terms and this
550
+ License would be to refrain entirely from conveying the Program.
551
+
552
+ 13. Use with the GNU Affero General Public License.
553
+
554
+ Notwithstanding any other provision of this License, you have
555
+ permission to link or combine any covered work with a work licensed
556
+ under version 3 of the GNU Affero General Public License into a single
557
+ combined work, and to convey the resulting work. The terms of this
558
+ License will continue to apply to the part which is the covered work,
559
+ but the special requirements of the GNU Affero General Public License,
560
+ section 13, concerning interaction through a network will apply to the
561
+ combination as such.
562
+
563
+ 14. Revised Versions of this License.
564
+
565
+ The Free Software Foundation may publish revised and/or new versions of
566
+ the GNU General Public License from time to time. Such new versions will
567
+ be similar in spirit to the present version, but may differ in detail to
568
+ address new problems or concerns.
569
+
570
+ Each version is given a distinguishing version number. If the
571
+ Program specifies that a certain numbered version of the GNU General
572
+ Public License "or any later version" applies to it, you have the
573
+ option of following the terms and conditions either of that numbered
574
+ version or of any later version published by the Free Software
575
+ Foundation. If the Program does not specify a version number of the
576
+ GNU General Public License, you may choose any version ever published
577
+ by the Free Software Foundation.
578
+
579
+ If the Program specifies that a proxy can decide which future
580
+ versions of the GNU General Public License can be used, that proxy's
581
+ public statement of acceptance of a version permanently authorizes you
582
+ to choose that version for the Program.
583
+
584
+ Later license versions may give you additional or different
585
+ permissions. However, no additional obligations are imposed on any
586
+ author or copyright holder as a result of your choosing to follow a
587
+ later version.
588
+
589
+ 15. Disclaimer of Warranty.
590
+
591
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592
+ APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593
+ HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594
+ OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595
+ THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596
+ PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597
+ IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598
+ ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599
+
600
+ 16. Limitation of Liability.
601
+
602
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603
+ WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604
+ THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605
+ GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606
+ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607
+ DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608
+ PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609
+ EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610
+ SUCH DAMAGES.
611
+
612
+ 17. Interpretation of Sections 15 and 16.
613
+
614
+ If the disclaimer of warranty and limitation of liability provided
615
+ above cannot be given local legal effect according to their terms,
616
+ reviewing courts shall apply local law that most closely approximates
617
+ an absolute waiver of all civil liability in connection with the
618
+ Program, unless a warranty or assumption of liability accompanies a
619
+ copy of the Program in return for a fee.
620
+
621
+ END OF TERMS AND CONDITIONS
622
+
623
+ How to Apply These Terms to Your New Programs
624
+
625
+ If you develop a new program, and you want it to be of the greatest
626
+ possible use to the public, the best way to achieve this is to make it
627
+ free software which everyone can redistribute and change under these terms.
628
+
629
+ To do so, attach the following notices to the program. It is safest
630
+ to attach them to the start of each source file to most effectively
631
+ state the exclusion of warranty; and each file should have at least
632
+ the "copyright" line and a pointer to where the full notice is found.
633
+
634
+ <one line to give the program's name and a brief idea of what it does.>
635
+ Copyright (C) <year> <name of author>
636
+
637
+ This program is free software: you can redistribute it and/or modify
638
+ it under the terms of the GNU General Public License as published by
639
+ the Free Software Foundation, either version 3 of the License, or
640
+ (at your option) any later version.
641
+
642
+ This program is distributed in the hope that it will be useful,
643
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
644
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645
+ GNU General Public License for more details.
646
+
647
+ You should have received a copy of the GNU General Public License
648
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
649
+
650
+ Also add information on how to contact you by electronic and paper mail.
651
+
652
+ If the program does terminal interaction, make it output a short
653
+ notice like this when it starts in an interactive mode:
654
+
655
+ <program> Copyright (C) <year> <name of author>
656
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657
+ This is free software, and you are welcome to redistribute it
658
+ under certain conditions; type `show c' for details.
659
+
660
+ The hypothetical commands `show w' and `show c' should show the appropriate
661
+ parts of the General Public License. Of course, your program's commands
662
+ might be different; for a GUI interface, you would use an "about box".
663
+
664
+ You should also get your employer (if you work as a programmer) or school,
665
+ if any, to sign a "copyright disclaimer" for the program, if necessary.
666
+ For more information on this, and how to apply and follow the GNU GPL, see
667
+ <https://www.gnu.org/licenses/>.
668
+
669
+ The GNU General Public License does not permit incorporating your program
670
+ into proprietary programs. If your program is a subroutine library, you
671
+ may consider it more useful to permit linking proprietary applications with
672
+ the library. If this is what you want to do, use the GNU Lesser General
673
+ Public License instead of this License. But first, please read
674
+ <https://www.gnu.org/licenses/why-not-lgpl.html>.
ComfyUI-Advanced-ControlNet/README.md ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ComfyUI-Advanced-ControlNet
2
+ Nodes for scheduling ControlNet strength across timesteps and batched latents, as well as applying custom weights and attention masks. The ControlNet nodes here fully support sliding context sampling, like the one used in the [ComfyUI-AnimateDiff-Evolved](https://github.com/Kosinkadink/ComfyUI-AnimateDiff-Evolved) nodes. Currently supports ControlNets, T2IAdapters, ControlLoRAs, ControlLLLite, SparseCtrls, SVD-ControlNets, and Reference.
3
+
4
+ Custom weights allow replication of the "My prompt is more important" feature of Auto1111's sd-webui ControlNet extension via Soft Weights, and the "ControlNet is more important" feature can be granularly controlled by changing the uncond_multiplier on the same Soft Weights.
5
+
6
+ ControlNet preprocessors are available through [comfyui_controlnet_aux](https://github.com/Fannovel16/comfyui_controlnet_aux) nodes.
7
+
8
+ ## Features
9
+ - Timestep and latent strength scheduling
10
+ - Attention masks
11
+ - Replicate ***"My prompt is more important"*** feature from sd-webui-controlnet extension via ***Soft Weights***, and allow softness to be tweaked via ***base_multiplier***
12
+ - Replicate ***"ControlNet is more important"*** feature from sd-webui-controlnet extension via ***uncond_multiplier*** on ***Soft Weights***
13
+ - uncond_multiplier=0.0 gives identical results of auto1111's feature, but values between 0.0 and 1.0 can be used without issue to granularly control the setting.
14
+ - ControlNet, T2IAdapter, and ControlLoRA support for sliding context windows
15
+ - ControlLLLite support (requires model_optional to be passed into and out of Apply Advanced ControlNet node)
16
+ - SparseCtrl support
17
+ - SVD-ControlNet support
18
+ - Stable Video Diffusion ControlNets trained by **CiaraRowles**: [Depth](https://huggingface.co/CiaraRowles/temporal-controlnet-depth-svd-v1/tree/main/controlnet), [Lineart](https://huggingface.co/CiaraRowles/temporal-controlnet-lineart-svd-v1/tree/main/controlnet)
19
+ - Reference support
20
+ - Supports ```reference_attn```, ```reference_adain```, and ```refrence_adain+attn``` modes. ```style_fidelity``` and ```ref_weight``` are equivalent to style_fidelity and control_weight in Auto1111, respectively, and strength of the Apply ControlNet is the balance between ref-influenced result and no-ref result. There is also a Reference ControlNet (Finetune) node that allows adjust the style_fidelity, weight, and strength of attn and adain separately.
21
+
22
+ ## Table of Contents:
23
+ - [Scheduling Explanation](#scheduling-explanation)
24
+ - [Nodes](#nodes)
25
+ - [Usage](#usage) (will fill this out soon)
26
+
27
+
28
+ # Scheduling Explanation
29
+
30
+ The two core concepts for scheduling are ***Timestep Keyframes*** and ***Latent Keyframes***.
31
+
32
+ ***Timestep Keyframes*** hold the values that guide the settings for a controlnet, and begin to take effect based on their start_percent, which corresponds to the percentage of the sampling process. They can contain masks for the strengths of each latent, control_net_weights, and latent_keyframes (specific strengths for each latent), all optional.
33
+
34
+ ***Latent Keyframes*** determine the strength of the controlnet for specific latents - all they contain is the batch_index of the latent, and the strength the controlnet should apply for that latent. As a concept, latent keyframes achieve the same affect as a uniform mask with the chosen strength value.
35
+
36
+ ![advcn_image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/e6275264-6c3f-4246-a319-111ee48f4cd9)
37
+
38
+ # Nodes
39
+
40
+ The ControlNet nodes provided here are the ***Apply Advanced ControlNet*** and ***Load Advanced ControlNet Model*** (or diff) nodes. The vanilla ControlNet nodes are also compatible, and can be used almost interchangeably - the only difference is that **at least one of these nodes must be used** for Advanced versions of ControlNets to be used (important for sliding context sampling, like with AnimateDiff-Evolved).
41
+
42
+ Key:
43
+ - 🟩 - required inputs
44
+ - 🟨 - optional inputs
45
+ - 🟦 - start as widgets, can be converted to inputs
46
+ - 🟥 - optional input/output, but not recommended to use unless needed
47
+ - 🟪 - output
48
+
49
+ ## Apply Advanced ControlNet
50
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/dc541d41-70df-4a71-b832-efa65af98f06)
51
+
52
+ Same functionality as the vanilla Apply Advanced ControlNet (Advanced) node, except with Advanced ControlNet features added to it. Automatically converts any ControlNet from ControlNet loaders into Advanced versions.
53
+
54
+ ### Inputs
55
+ - 🟩***positive***: conditioning (positive).
56
+ - 🟩***negative***: conditioning (negative).
57
+ - 🟩***control_net***: loaded controlnet; will be converted to Advanced version automatically by this node, if it's a supported type.
58
+ - 🟩***image***: images to guide controlnets - if the loaded controlnet requires it, they must preprocessed images. If one image provided, will be used for all latents. If more images provided, will use each image separately for each latent. If not enough images to meet latent count, will repeat the images from the beginning to match vanilla ControlNet functionality.
59
+ - 🟨***mask_optional***: attention masks to apply to controlnets; basically, decides what part of the image the controlnet to apply to (and the relative strength, if the mask is not binary). Same as image input, if you provide more than one mask, each can apply to a different latent.
60
+ - 🟨***timestep_kf***: timestep keyframes to guide controlnet effect throughout sampling steps.
61
+ - 🟨***latent_kf_override***: override for latent keyframes, useful if no other features from timestep keyframes is needed. *NOTE: this latent keyframe will be applied to ALL timesteps, regardless if there are other latent keyframes attached to connected timestep keyframes.*
62
+ - 🟨***weights_override***: override for weights, useful if no other features from timestep keyframes is needed. *NOTE: this weight will be applied to ALL timesteps, regardless if there are other weights attached to connected timestep keyframes.*
63
+ - 🟦***strength***: strength of controlnet; 1.0 is full strength, 0.0 is no effect at all.
64
+ - 🟦***start_percent***: sampling step percentage at which controlnet should start to be applied - no matter what start_percent is set on timestep keyframes, they won't take effect until this start_percent is reached.
65
+ - 🟦***stop_percent***: sampling step percentage at which controlnet should stop being applied - no matter what start_percent is set on timestep keyframes, they won't take effect once this end_percent is reached.
66
+
67
+ ### Outputs
68
+ - 🟪***positive***: conditioning (positive) with applied controlnets
69
+ - 🟪***negative***: conditioning (negative) with applied controlnets
70
+
71
+ ## Load Advanced ControlNet Model
72
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/4a7f58a9-783d-4da4-bf82-bc9c167e4722)
73
+
74
+ Loads a ControlNet model and converts it into an Advanced version that supports all the features in this repo. When used with **Apply Advanced ControlNet** node, there is no reason to use the timestep_keyframe input on this node - use timestep_kf on the Apply node instead.
75
+
76
+ ### Inputs
77
+ - 🟥***timestep_keyframe***: optional and likely unnecessary input to have ControlNet use selected timestep_keyframes - should not be used unless you need to. Useful if this node is not attached to **Apply Advanced ControlNet** node, but still want to use Timestep Keyframe, or to use TK_SHORTCUT outputs from ControlWeights in the same scenario. Will be overriden by the timestep_kf input on **Apply Advanced ControlNet** node, if one is provided there.
78
+ - 🟨***model***: model to plug into the diff version of the node. Some controlnets are designed for receive the model; if you don't know what this does, you probably don't want tot use the diff version of the node.
79
+
80
+ ### Outputs
81
+ - 🟪***CONTROL_NET***: loaded Advanced ControlNet
82
+
83
+ ## Timestep Keyframe
84
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/404f3cfe-5852-4eed-935b-37e32493d1b5)
85
+
86
+ Scheduling node across timesteps (sampling steps) based on the set start_percent. Chaining Timestep Keyframes allows ControlNet scheduling across sampling steps (percentage-wise), through a timestep keyframe schedule.
87
+
88
+ ### Inputs
89
+ - 🟨***prev_timestep_kf***: used to chain Timestep Keyframes together to create a schedule. The order does not matter - the Timestep Keyframes sort themselves automatically by their start_percent. *Any Timestep Keyframe contained in the prev_timestep_keyframe that contains the same start_percent as the Timestep Keyframe will be overwritten.*
90
+ - 🟨***cn_weights***: weights to apply to controlnet while this Timestep Keyframe is in effect. Must be compatible with the loaded controlnet, or will throw an error explaining what weight types are compatible. If inherit_missing is True, if no control_net_weight is passed in, will attempt to reuse the last-used weights in the timestep keyframe schedule. *If Apply Advanced ControlNet node has a weight_override, the weight_override will be used during sampling instead of control_net_weight.*
91
+ - 🟨***latent_keyframe***: latent keyframes to apply to controlnet while this Timestep Keyframe is in effect. If inherit_missing is True, if no latent_keyframe is passed in, will attempt to reuse the last-used weights in the timestep keyframe schedule. *If Apply Advanced ControlNet node has a latent_kf_override, the latent_lf_override will be used during sampling instead of latent_keyframe.*
92
+ - 🟨***mask_optional***: attention masks to apply to controlnets; basically, decides what part of the image the controlnet to apply to (and the relative strength, if the mask is not binary). Same as mask_optional on the Apply Advanced ControlNet node, can apply either one maks to all latents, or individual masks for each latent. If inherit_missing is True, if no mask_optional is passed in, will attempt to reuse the last-used mask_optional in the timestep keyframe schedule. It is NOT overriden by mask_optional on the Apply Advanced ControlNet node; will be used together.
93
+ - 🟦***start_percent***: sampling step percentage at which this Timestep Keyframe qualifies to be used. Acts as the 'key' for the Timestep Keyframe in the timestep keyframe schedule.
94
+ - 🟦***strength***: strength of the controlnet; multiplies the controlnet by this value, basically, applied alongside the strength on the Apply ControlNet node. If set to 0.0 will not have any effect during the duration of this Timestep Keyframe's effect, and will increase sampling speed by not doing any work.
95
+ - 🟦***null_latent_kf_strength***: strength to assign to latents that are unaccounted for in the passed in latent_keyframes. Has no effect if no latent_keyframes are passed in, or no batch_indeces are unaccounted in the latent_keyframes for during sampling.
96
+ - 🟦***inherit_missing***: determines if should reuse values from previous Timestep Keyframes for optional values (control_net_weights, latent_keyframe, and mask_option) that are not included on this TimestepKeyframe. To inherit only specific inputs, use default inputs.
97
+ - 🟦***guarantee_steps***: when 1 or greater, even if a Timestep Keyframe's start_percent ahead of this one in the schedule is closer to current sampling percentage, this Timestep Keyframe will still be used for the specified amount of steps before moving on to the next selected Timestep Keyframe in the following step. Whether the Timestep Keyframe is used or not, its inputs will still be accounted for inherit_missing purposes.
98
+
99
+ ### Outputs
100
+ - 🟪***TIMESTEP_KF***: the created Timestep Keyframe, that can either be linked to another or into a Timestep Keyframe input.
101
+
102
+ ## Timestep Keyframe Interpolation
103
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/9789617c-202c-4271-92a2-0909bcf9b108)
104
+
105
+ Allows to create Timestep Keyframe with interpolated strength values in a given percent range. (The first generated keyframe will have guarantee_steps=1, rest that follow will have guarantee_steps=0).
106
+
107
+ ### Inputs
108
+ - 🟨***prev_timestep_kf***: used to chain Timestep Keyframes together to create a schedule. The order does not matter - the Timestep Keyframes sort themselves automatically by their start_percent. *Any Timestep Keyframe contained in the prev_timestep_keyframe that contains the same start_percent as the Timestep Keyframe will be overwritten.*
109
+ - 🟨***cn_weights***: weights to apply to controlnet while this Timestep Keyframe is in effect. Must be compatible with the loaded controlnet, or will throw an error explaining what weight types are compatible. If inherit_missing is True, if no control_net_weight is passed in, will attempt to reuse the last-used weights in the timestep keyframe schedule. *If Apply Advanced ControlNet node has a weight_override, the weight_override will be used during sampling instead of control_net_weight.*
110
+ - 🟨***latent_keyframe***: latent keyframes to apply to controlnet while this Timestep Keyframe is in effect. If inherit_missing is True, if no latent_keyframe is passed in, will attempt to reuse the last-used weights in the timestep keyframe schedule. *If Apply Advanced ControlNet node has a latent_kf_override, the latent_lf_override will be used during sampling instead of latent_keyframe.*
111
+ - 🟨***mask_optional***: attention masks to apply to controlnets; basically, decides what part of the image the controlnet to apply to (and the relative strength, if the mask is not binary). Same as mask_optional on the Apply Advanced ControlNet node, can apply either one maks to all latents, or individual masks for each latent. If inherit_missing is True, if no mask_optional is passed in, will attempt to reuse the last-used mask_optional in the timestep keyframe schedule. It is NOT overriden by mask_optional on the Apply Advanced ControlNet node; will be used together.
112
+ - 🟦***start_percent***: sampling step percentage at which the first generated Timestep Keyframe qualifies to be used.
113
+ - 🟦***end_percent***: sampling step percentage at which the last generated Timestep Keyframe qualifies to be used.
114
+ - 🟦***strength_start***: strength of the Timestep Keyframe at start of range.
115
+ - 🟦***strength_end***: strength of the Timestep Keyframe at end of range.
116
+ - 🟦***interpolation***: the method of interpolation.
117
+ - 🟦***intervals***: the amount of keyframes to generate in total - the first will have its start_percent equal to start_percent, the last will have its start_percent equal to end_percent.
118
+ - 🟦***null_latent_kf_strength***: strength to assign to latents that are unaccounted for in the passed in latent_keyframes. Has no effect if no latent_keyframes are passed in, or no batch_indeces are unaccounted in the latent_keyframes for during sampling.
119
+ - 🟦***inherit_missing***: determines if should reuse values from previous Timestep Keyframes for optional values (control_net_weights, latent_keyframe, and mask_option) that are not included on this TimestepKeyframe. To inherit only specific inputs, use default inputs.
120
+ - 🟦***print_keyframes***: if True, will print the Timestep Keyframes generated by this node for debugging purposes.
121
+
122
+ ### Outputs
123
+ - 🟪***TIMESTEP_KF***: the created Timestep Keyframe, that can either be linked to another or into a Timestep Keyframe input.
124
+
125
+ ## Timestep Keyframe From List
126
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/9e9c23bf-6f82-4ce7-b4d1-3016fd14707d)
127
+
128
+ Allows to create Timestep Keyframe via a list of floats, such as with Batch Value Schedule from [ComfyUI_FizzNodes](https://github.com/FizzleDorf/ComfyUI_FizzNodes) nodes. (The first generated keyframe will have guarantee_steps=1, rest that follow will have guarantee_steps=0).
129
+
130
+ ### Inputs
131
+ - 🟨***prev_timestep_kf***: used to chain Timestep Keyframes together to create a schedule. The order does not matter - the Timestep Keyframes sort themselves automatically by their start_percent. *Any Timestep Keyframe contained in the prev_timestep_keyframe that contains the same start_percent as the Timestep Keyframe will be overwritten.*
132
+ - 🟨***cn_weights***: weights to apply to controlnet while this Timestep Keyframe is in effect. Must be compatible with the loaded controlnet, or will throw an error explaining what weight types are compatible. If inherit_missing is True, if no control_net_weight is passed in, will attempt to reuse the last-used weights in the timestep keyframe schedule. *If Apply Advanced ControlNet node has a weight_override, the weight_override will be used during sampling instead of control_net_weight.*
133
+ - 🟨***latent_keyframe***: latent keyframes to apply to controlnet while this Timestep Keyframe is in effect. If inherit_missing is True, if no latent_keyframe is passed in, will attempt to reuse the last-used weights in the timestep keyframe schedule. *If Apply Advanced ControlNet node has a latent_kf_override, the latent_lf_override will be used during sampling instead of latent_keyframe.*
134
+ - 🟨***mask_optional***: attention masks to apply to controlnets; basically, decides what part of the image the controlnet to apply to (and the relative strength, if the mask is not binary). Same as mask_optional on the Apply Advanced ControlNet node, can apply either one maks to all latents, or individual masks for each latent. If inherit_missing is True, if no mask_optional is passed in, will attempt to reuse the last-used mask_optional in the timestep keyframe schedule. It is NOT overriden by mask_optional on the Apply Advanced ControlNet node; will be used together.
135
+ - 🟩***float_strengths***: a list of floats, that will correspond to the strength of each Timestep Keyframe; first will be assigned to start_percent, last will be assigned to end_percent, and the rest spread linearly between.
136
+ - 🟦***start_percent***: sampling step percentage at which the first generated Timestep Keyframe qualifies to be used.
137
+ - 🟦***end_percent***: sampling step percentage at which the last generated Timestep Keyframe qualifies to be used.
138
+ - 🟦***null_latent_kf_strength***: strength to assign to latents that are unaccounted for in the passed in latent_keyframes. Has no effect if no latent_keyframes are passed in, or no batch_indeces are unaccounted in the latent_keyframes for during sampling.
139
+ - 🟦***inherit_missing***: determines if should reuse values from previous Timestep Keyframes for optional values (control_net_weights, latent_keyframe, and mask_option) that are not included on this TimestepKeyframe. To inherit only specific inputs, use default inputs.
140
+ - 🟦***print_keyframes***: if True, will print the Timestep Keyframes generated by this node for debugging purposes.
141
+
142
+ ### Outputs
143
+ - 🟪***TIMESTEP_KF***: the created Timestep Keyframe, that can either be linked to another or into a Timestep Keyframe input.
144
+
145
+ ## Latent Keyframe
146
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/7eb2cc4c-255c-4f32-b09b-699f713fada3)
147
+
148
+ A singular Latent Keyframe, selects the strength for a specific batch_index. If batch_index is not present during sampling, will simply have no effect. Can be chained with any other Latent Keyframe-type node to create a latent keyframe schedule.
149
+
150
+ ### Inputs
151
+ - 🟨***prev_latent_kf***: used to chain Latent Keyframes together to create a schedule. *If a Latent Keyframe contained in prev_latent_keyframes have the same batch_index as this Latent Keyframe, they will take priority over this node's value.*
152
+ - 🟦***batch_index***: index of latent in batch to apply controlnet strength to. Acts as the 'key' for the Latent Keyframe in the latent keyframe schedule.
153
+ - 🟦***strength***: strength of controlnet to apply to the corresponding latent.
154
+
155
+ ### Outputs
156
+ - 🟪***LATENT_KF***: the created Latent Keyframe, that can either be linked to another or into a Latent Keyframe input.
157
+
158
+ ## Latent Keyframe Group
159
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/5ce3b795-f5fc-4dc3-ae30-a4c7f87e278c)
160
+
161
+ Allows to create Latent Keyframes via individual indeces or python-style ranges.
162
+
163
+ ### Inputs
164
+ - 🟨***prev_latent_kf***: used to chain Latent Keyframes together to create a schedule. *If any Latent Keyframes contained in prev_latent_keyframes have the same batch_index as a this Latent Keyframe, they will take priority over this node's version.*
165
+ - 🟨***latent_optional***: the latents expected to be passed in for sampling; only required if you wish to use negative indeces (will be automatically converted to real values).
166
+ - 🟦***index_strengths***: string list of indeces or python-style ranges of indeces to assign strengths to. If latent_optional is passed in, can contain negative indeces or ranges that contain negative numbers, python-style. The different indeces must be comma separated. Individual latents can be specified by ```batch_index=strength```, like ```0=0.9```. Ranges can be specified by ```start_index_inclusive:end_index_exclusive=strength```, like ```0:8=strength```. Negative indeces are possible when latents_optional has an input, with a string such as ```0,-4=0.25```.
167
+ - 🟦***print_keyframes***: if True, will print the Latent Keyframes generated by this node for debugging purposes.
168
+
169
+ ### Outputs
170
+ - 🟪***LATENT_KF***: the created Latent Keyframe, that can either be linked to another or into a Latent Keyframe input.
171
+
172
+ ## Latent Keyframe Interpolation
173
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/7986c737-83b9-46bc-aab0-ae4c368df446)
174
+
175
+ Allows to create Latent Keyframes with interpolated values in a range.
176
+
177
+ ### Inputs
178
+ - 🟨***prev_latent_kf***: used to chain Latent Keyframes together to create a schedule. *If any Latent Keyframes contained in prev_latent_keyframes have the same batch_index as a this Latent Keyframe, they will take priority over this node's version.*
179
+ - 🟦***batch_index_from***: starting batch_index of range, included.
180
+ - 🟦***batch_index_to***: end batch_index of range, excluded (python-style range).
181
+ - 🟦***strength_from***: starting strength of interpolation.
182
+ - 🟦***strength_to***: end strength of interpolation.
183
+ - 🟦***interpolation***: the method of interpolation.
184
+ - 🟦***print_keyframes***: if True, will print the Latent Keyframes generated by this node for debugging purposes.
185
+
186
+ ### Outputs
187
+ - 🟪***LATENT_KF***: the created Latent Keyframe, that can either be linked to another or into a Latent Keyframe input.
188
+
189
+ ## Latent Keyframe From List
190
+ ![image](https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet/assets/7365912/6cec701f-6183-4aeb-af5c-cac76f5591b7)
191
+
192
+ Allows to create Latent Keyframes via a list of floats, such as with Batch Value Schedule from [ComfyUI_FizzNodes](https://github.com/FizzleDorf/ComfyUI_FizzNodes) nodes.
193
+
194
+ ### Inputs
195
+ - 🟨***prev_latent_kf***: used to chain Latent Keyframes together to create a schedule. *If any Latent Keyframes contained in prev_latent_keyframes have the same batch_index as a this Latent Keyframe, they will take priority over this node's version.*
196
+ - 🟩***float_strengths***: a list of floats, that will correspond to the strength of each Latent Keyframe; the batch_index is the index of each float value in the list.
197
+ - 🟦***print_keyframes***: if True, will print the Latent Keyframes generated by this node for debugging purposes.
198
+
199
+ ### Outputs
200
+ - 🟪***LATENT_KF***: the created Latent Keyframe, that can either be linked to another or into a Latent Keyframe input.
201
+
202
+ # There are more nodes to document and show usage - will add this soon! TODO
ComfyUI-Advanced-ControlNet/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .adv_control.nodes import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
2
+
3
+ __all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
ComfyUI-Advanced-ControlNet/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (299 Bytes). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control.cpython-310.pyc ADDED
Binary file (26 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_lllite.cpython-310.pyc ADDED
Binary file (6.49 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_reference.cpython-310.pyc ADDED
Binary file (24.9 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_sparsectrl.cpython-310.pyc ADDED
Binary file (32.1 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/control_svd.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/logger.cpython-310.pyc ADDED
Binary file (1.13 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes.cpython-310.pyc ADDED
Binary file (7.45 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_deprecated.cpython-310.pyc ADDED
Binary file (2.28 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_keyframes.cpython-310.pyc ADDED
Binary file (12.5 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_loosecontrol.cpython-310.pyc ADDED
Binary file (2.25 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_reference.cpython-310.pyc ADDED
Binary file (3.48 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_sparsectrl.cpython-310.pyc ADDED
Binary file (6.63 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/nodes_weight.cpython-310.pyc ADDED
Binary file (6.61 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/__pycache__/utils.cpython-310.pyc ADDED
Binary file (31.3 kB). View file
 
ComfyUI-Advanced-ControlNet/adv_control/control.py ADDED
@@ -0,0 +1,899 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Union
2
+ from torch import Tensor
3
+ import torch
4
+ import os
5
+
6
+ import comfy.ops
7
+ import comfy.utils
8
+ import comfy.model_management
9
+ import comfy.model_detection
10
+ import comfy.controlnet as comfy_cn
11
+ from comfy.controlnet import ControlBase, ControlNet, ControlLora, T2IAdapter
12
+ from comfy.model_patcher import ModelPatcher
13
+
14
+ from .control_sparsectrl import SparseModelPatcher, SparseControlNet, SparseCtrlMotionWrapper, SparseMethod, SparseSettings, SparseSpreadMethod, PreprocSparseRGBWrapper, SparseConst
15
+ from .control_lllite import LLLiteModule, LLLitePatch
16
+ from .control_svd import svd_unet_config_from_diffusers_unet, SVDControlNet, svd_unet_to_diffusers
17
+ from .utils import (AdvancedControlBase, TimestepKeyframeGroup, LatentKeyframeGroup, ControlWeightType, ControlWeights, WeightTypeException,
18
+ manual_cast_clean_groupnorm, disable_weight_init_clean_groupnorm, prepare_mask_batch, get_properly_arranged_t2i_weights, load_torch_file_with_dict_factory,
19
+ broadcast_image_to_extend, extend_to_batch_size)
20
+ from .logger import logger
21
+
22
+
23
+ class ControlNetAdvanced(ControlNet, AdvancedControlBase):
24
+ def __init__(self, control_model, timestep_keyframes: TimestepKeyframeGroup, global_average_pooling=False, device=None, load_device=None, manual_cast_dtype=None):
25
+ super().__init__(control_model=control_model, global_average_pooling=global_average_pooling, device=device, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
26
+ AdvancedControlBase.__init__(self, super(), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.controlnet())
27
+
28
+ def get_universal_weights(self) -> ControlWeights:
29
+ raw_weights = [(self.weights.base_multiplier ** float(12 - i)) for i in range(13)]
30
+ return self.weights.copy_with_new_weights(raw_weights)
31
+
32
+ def get_control_advanced(self, x_noisy, t, cond, batched_number):
33
+ # perform special version of get_control that supports sliding context and masks
34
+ return self.sliding_get_control(x_noisy, t, cond, batched_number)
35
+
36
+ def sliding_get_control(self, x_noisy: Tensor, t, cond, batched_number):
37
+ control_prev = None
38
+ if self.previous_controlnet is not None:
39
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
40
+
41
+ if self.timestep_range is not None:
42
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
43
+ if control_prev is not None:
44
+ return control_prev
45
+ else:
46
+ return None
47
+
48
+ dtype = self.control_model.dtype
49
+ if self.manual_cast_dtype is not None:
50
+ dtype = self.manual_cast_dtype
51
+
52
+ output_dtype = x_noisy.dtype
53
+ # make cond_hint appropriate dimensions
54
+ # TODO: change this to not require cond_hint upscaling every step when self.sub_idxs are present
55
+ if self.sub_idxs is not None or self.cond_hint is None or x_noisy.shape[2] * 8 != self.cond_hint.shape[2] or x_noisy.shape[3] * 8 != self.cond_hint.shape[3]:
56
+ if self.cond_hint is not None:
57
+ del self.cond_hint
58
+ self.cond_hint = None
59
+ # if self.cond_hint_original length greater or equal to real latent count, subdivide it before scaling
60
+ if self.sub_idxs is not None:
61
+ actual_cond_hint_orig = self.cond_hint_original
62
+ if self.cond_hint_original.size(0) < self.full_latent_length:
63
+ actual_cond_hint_orig = extend_to_batch_size(tensor=actual_cond_hint_orig, batch_size=self.full_latent_length)
64
+ self.cond_hint = comfy.utils.common_upscale(actual_cond_hint_orig[self.sub_idxs], x_noisy.shape[3] * 8, x_noisy.shape[2] * 8, 'nearest-exact', "center").to(dtype).to(self.device)
65
+ else:
66
+ self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, x_noisy.shape[3] * 8, x_noisy.shape[2] * 8, 'nearest-exact', "center").to(dtype).to(self.device)
67
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
68
+ self.cond_hint = broadcast_image_to_extend(self.cond_hint, x_noisy.shape[0], batched_number)
69
+
70
+ # prepare mask_cond_hint
71
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number, dtype=dtype)
72
+
73
+ context = cond.get('crossattn_controlnet', cond['c_crossattn'])
74
+ # uses 'y' in new ComfyUI update
75
+ y = cond.get('y', None)
76
+ if y is None: # TODO: remove this in the future since no longer used by newest ComfyUI
77
+ y = cond.get('c_adm', None)
78
+ if y is not None:
79
+ y = y.to(dtype)
80
+ timestep = self.model_sampling_current.timestep(t)
81
+ x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
82
+
83
+ control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.float(), context=context.to(dtype), y=y)
84
+ return self.control_merge(None, control, control_prev, output_dtype)
85
+
86
+ def copy(self):
87
+ c = ControlNetAdvanced(self.control_model, self.timestep_keyframes, global_average_pooling=self.global_average_pooling, load_device=self.load_device, manual_cast_dtype=self.manual_cast_dtype)
88
+ self.copy_to(c)
89
+ self.copy_to_advanced(c)
90
+ return c
91
+
92
+ @staticmethod
93
+ def from_vanilla(v: ControlNet, timestep_keyframe: TimestepKeyframeGroup=None) -> 'ControlNetAdvanced':
94
+ return ControlNetAdvanced(control_model=v.control_model, timestep_keyframes=timestep_keyframe,
95
+ global_average_pooling=v.global_average_pooling, device=v.device, load_device=v.load_device, manual_cast_dtype=v.manual_cast_dtype)
96
+
97
+
98
+ class T2IAdapterAdvanced(T2IAdapter, AdvancedControlBase):
99
+ def __init__(self, t2i_model, timestep_keyframes: TimestepKeyframeGroup, channels_in, compression_ratio=8, upscale_algorithm="nearest_exact", device=None):
100
+ super().__init__(t2i_model=t2i_model, channels_in=channels_in, compression_ratio=compression_ratio, upscale_algorithm=upscale_algorithm, device=device)
101
+ AdvancedControlBase.__init__(self, super(), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.t2iadapter())
102
+
103
+ def control_merge_inject(self, control_input, control_output, control_prev, output_dtype):
104
+ # if has uncond multiplier, need to make sure control shapes are the same batch size as expected
105
+ if self.weights.has_uncond_multiplier or self.weights.has_uncond_mask:
106
+ if control_input is not None:
107
+ for i in range(len(control_input)):
108
+ x = control_input[i]
109
+ if x is not None:
110
+ if x.size(0) < self.batch_size:
111
+ control_input[i] = x.repeat(self.batched_number, 1, 1, 1)[:self.batch_size]
112
+ if control_output is not None:
113
+ for i in range(len(control_output)):
114
+ x = control_output[i]
115
+ if x is not None:
116
+ if x.size(0) < self.batch_size:
117
+ control_output[i] = x.repeat(self.batched_number, 1, 1, 1)[:self.batch_size]
118
+ return AdvancedControlBase.control_merge_inject(self, control_input, control_output, control_prev, output_dtype)
119
+
120
+ def get_universal_weights(self) -> ControlWeights:
121
+ raw_weights = [(self.weights.base_multiplier ** float(7 - i)) for i in range(8)]
122
+ raw_weights = [raw_weights[-8], raw_weights[-3], raw_weights[-2], raw_weights[-1]]
123
+ raw_weights = get_properly_arranged_t2i_weights(raw_weights)
124
+ return self.weights.copy_with_new_weights(raw_weights)
125
+
126
+ def get_calc_pow(self, idx: int, layers: int) -> int:
127
+ # match how T2IAdapterAdvanced deals with universal weights
128
+ indeces = [7 - i for i in range(8)]
129
+ indeces = [indeces[-8], indeces[-3], indeces[-2], indeces[-1]]
130
+ indeces = get_properly_arranged_t2i_weights(indeces)
131
+ return indeces[idx]
132
+
133
+ def get_control_advanced(self, x_noisy, t, cond, batched_number):
134
+ try:
135
+ # if sub indexes present, replace original hint with subsection
136
+ if self.sub_idxs is not None:
137
+ # cond hints
138
+ full_cond_hint_original = self.cond_hint_original
139
+ actual_cond_hint_orig = full_cond_hint_original
140
+ del self.cond_hint
141
+ self.cond_hint = None
142
+ if full_cond_hint_original.size(0) < self.full_latent_length:
143
+ actual_cond_hint_orig = extend_to_batch_size(tensor=full_cond_hint_original, batch_size=full_cond_hint_original.size(0))
144
+ self.cond_hint_original = actual_cond_hint_orig[self.sub_idxs]
145
+ # mask hints
146
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number)
147
+ return super().get_control(x_noisy, t, cond, batched_number)
148
+ finally:
149
+ if self.sub_idxs is not None:
150
+ # replace original cond hint
151
+ self.cond_hint_original = full_cond_hint_original
152
+ del full_cond_hint_original
153
+
154
+ def copy(self):
155
+ c = T2IAdapterAdvanced(self.t2i_model, self.timestep_keyframes, self.channels_in, self.compression_ratio, self.upscale_algorithm)
156
+ self.copy_to(c)
157
+ self.copy_to_advanced(c)
158
+ return c
159
+
160
+ def cleanup(self):
161
+ super().cleanup()
162
+ self.cleanup_advanced()
163
+
164
+ @staticmethod
165
+ def from_vanilla(v: T2IAdapter, timestep_keyframe: TimestepKeyframeGroup=None) -> 'T2IAdapterAdvanced':
166
+ return T2IAdapterAdvanced(t2i_model=v.t2i_model, timestep_keyframes=timestep_keyframe, channels_in=v.channels_in,
167
+ compression_ratio=v.compression_ratio, upscale_algorithm=v.upscale_algorithm, device=v.device)
168
+
169
+
170
+ class ControlLoraAdvanced(ControlLora, AdvancedControlBase):
171
+ def __init__(self, control_weights, timestep_keyframes: TimestepKeyframeGroup, global_average_pooling=False, device=None):
172
+ super().__init__(control_weights=control_weights, global_average_pooling=global_average_pooling, device=device)
173
+ AdvancedControlBase.__init__(self, super(), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.controllora())
174
+ # use some functions from ControlNetAdvanced
175
+ self.get_control_advanced = ControlNetAdvanced.get_control_advanced.__get__(self, type(self))
176
+ self.sliding_get_control = ControlNetAdvanced.sliding_get_control.__get__(self, type(self))
177
+
178
+ def get_universal_weights(self) -> ControlWeights:
179
+ raw_weights = [(self.weights.base_multiplier ** float(9 - i)) for i in range(10)]
180
+ return self.weights.copy_with_new_weights(raw_weights)
181
+
182
+ def copy(self):
183
+ c = ControlLoraAdvanced(self.control_weights, self.timestep_keyframes, global_average_pooling=self.global_average_pooling)
184
+ self.copy_to(c)
185
+ self.copy_to_advanced(c)
186
+ return c
187
+
188
+ def cleanup(self):
189
+ super().cleanup()
190
+ self.cleanup_advanced()
191
+
192
+ @staticmethod
193
+ def from_vanilla(v: ControlLora, timestep_keyframe: TimestepKeyframeGroup=None) -> 'ControlLoraAdvanced':
194
+ return ControlLoraAdvanced(control_weights=v.control_weights, timestep_keyframes=timestep_keyframe,
195
+ global_average_pooling=v.global_average_pooling, device=v.device)
196
+
197
+
198
+ class SVDControlNetAdvanced(ControlNetAdvanced):
199
+ def __init__(self, control_model: SVDControlNet, timestep_keyframes: TimestepKeyframeGroup, global_average_pooling=False, device=None, load_device=None, manual_cast_dtype=None):
200
+ super().__init__(control_model=control_model, timestep_keyframes=timestep_keyframes, global_average_pooling=global_average_pooling, device=device, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
201
+
202
+ def set_cond_hint(self, *args, **kwargs):
203
+ to_return = super().set_cond_hint(*args, **kwargs)
204
+ # cond hint for SVD-ControlNet needs to be scaled between (-1, 1) instead of (0, 1)
205
+ self.cond_hint_original = self.cond_hint_original * 2.0 - 1.0
206
+ return to_return
207
+
208
+ def get_control_advanced(self, x_noisy, t, cond, batched_number):
209
+ control_prev = None
210
+ if self.previous_controlnet is not None:
211
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
212
+
213
+ if self.timestep_range is not None:
214
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
215
+ if control_prev is not None:
216
+ return control_prev
217
+ else:
218
+ return None
219
+
220
+ dtype = self.control_model.dtype
221
+ if self.manual_cast_dtype is not None:
222
+ dtype = self.manual_cast_dtype
223
+
224
+ output_dtype = x_noisy.dtype
225
+ # make cond_hint appropriate dimensions
226
+ # TODO: change this to not require cond_hint upscaling every step when self.sub_idxs are present
227
+ if self.sub_idxs is not None or self.cond_hint is None or x_noisy.shape[2] * 8 != self.cond_hint.shape[2] or x_noisy.shape[3] * 8 != self.cond_hint.shape[3]:
228
+ if self.cond_hint is not None:
229
+ del self.cond_hint
230
+ self.cond_hint = None
231
+ # if self.cond_hint_original length greater or equal to real latent count, subdivide it before scaling
232
+ if self.sub_idxs is not None:
233
+ actual_cond_hint_orig = self.cond_hint_original
234
+ if self.cond_hint_original.size(0) < self.full_latent_length:
235
+ actual_cond_hint_orig = extend_to_batch_size(tensor=actual_cond_hint_orig, batch_size=self.full_latent_length)
236
+ self.cond_hint = comfy.utils.common_upscale(actual_cond_hint_orig[self.sub_idxs], x_noisy.shape[3] * 8, x_noisy.shape[2] * 8, 'nearest-exact', "center").to(dtype).to(self.device)
237
+ else:
238
+ self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, x_noisy.shape[3] * 8, x_noisy.shape[2] * 8, 'nearest-exact', "center").to(dtype).to(self.device)
239
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
240
+ self.cond_hint = broadcast_image_to_extend(self.cond_hint, x_noisy.shape[0], batched_number)
241
+
242
+ # prepare mask_cond_hint
243
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number, dtype=dtype)
244
+
245
+ context = cond.get('crossattn_controlnet', cond['c_crossattn'])
246
+ # uses 'y' in new ComfyUI update
247
+ y = cond.get('y', None)
248
+ if y is not None:
249
+ y = y.to(dtype)
250
+ timestep = self.model_sampling_current.timestep(t)
251
+ x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
252
+ # concat c_concat if exists (should exist for SVD), doubling channels to 8
253
+ if cond.get('c_concat', None) is not None:
254
+ x_noisy = torch.cat([x_noisy] + [cond['c_concat']], dim=1)
255
+
256
+ control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.float(), context=context.to(dtype), y=y, cond=cond)
257
+ return self.control_merge(None, control, control_prev, output_dtype)
258
+
259
+ def copy(self):
260
+ c = SVDControlNetAdvanced(self.control_model, self.timestep_keyframes, global_average_pooling=self.global_average_pooling, load_device=self.load_device, manual_cast_dtype=self.manual_cast_dtype)
261
+ self.copy_to(c)
262
+ self.copy_to_advanced(c)
263
+ return c
264
+
265
+
266
+ class SparseCtrlAdvanced(ControlNetAdvanced):
267
+ def __init__(self, control_model, timestep_keyframes: TimestepKeyframeGroup, sparse_settings: SparseSettings=None, global_average_pooling=False, device=None, load_device=None, manual_cast_dtype=None):
268
+ super().__init__(control_model=control_model, timestep_keyframes=timestep_keyframes, global_average_pooling=global_average_pooling, device=device, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
269
+ self.control_model_wrapped = SparseModelPatcher(self.control_model, load_device=load_device, offload_device=comfy.model_management.unet_offload_device())
270
+ self.add_compatible_weight(ControlWeightType.SPARSECTRL)
271
+ self.control_model: SparseControlNet = self.control_model # does nothing except help with IDE hints
272
+ self.sparse_settings = sparse_settings if sparse_settings is not None else SparseSettings.default()
273
+ self.latent_format = None
274
+ self.preprocessed = False
275
+
276
+ def get_control_advanced(self, x_noisy: Tensor, t, cond, batched_number: int):
277
+ # normal ControlNet stuff
278
+ control_prev = None
279
+ if self.previous_controlnet is not None:
280
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
281
+
282
+ if self.timestep_range is not None:
283
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
284
+ if control_prev is not None:
285
+ return control_prev
286
+ else:
287
+ return None
288
+
289
+ dtype = self.control_model.dtype
290
+ if self.manual_cast_dtype is not None:
291
+ dtype = self.manual_cast_dtype
292
+ output_dtype = x_noisy.dtype
293
+ # set actual input length on motion model
294
+ actual_length = x_noisy.size(0)//batched_number
295
+ full_length = actual_length if self.sub_idxs is None else self.full_latent_length
296
+ self.control_model.set_actual_length(actual_length=actual_length, full_length=full_length)
297
+ # prepare cond_hint, if needed
298
+ dim_mult = 1 if self.control_model.use_simplified_conditioning_embedding else 8
299
+ if self.sub_idxs is not None or self.cond_hint is None or x_noisy.shape[2]*dim_mult != self.cond_hint.shape[2] or x_noisy.shape[3]*dim_mult != self.cond_hint.shape[3]:
300
+ # clear out cond_hint and conditioning_mask
301
+ if self.cond_hint is not None:
302
+ del self.cond_hint
303
+ self.cond_hint = None
304
+ # first, figure out which cond idxs are relevant, and where they fit in
305
+ cond_idxs, hint_order = self.sparse_settings.sparse_method.get_indexes(hint_length=self.cond_hint_original.size(0), full_length=full_length,
306
+ sub_idxs=self.sub_idxs if self.sparse_settings.is_context_aware() else None)
307
+ range_idxs = list(range(full_length)) if self.sub_idxs is None else self.sub_idxs
308
+ hint_idxs = [] # idxs in cond_idxs
309
+ local_idxs = [] # idx to put in final cond_hint
310
+ for i,cond_idx in enumerate(cond_idxs):
311
+ if cond_idx in range_idxs:
312
+ hint_idxs.append(i)
313
+ local_idxs.append(range_idxs.index(cond_idx))
314
+ # log_string = f"cond_idxs: {cond_idxs}, local_idxs: {local_idxs}, hint_idxs: {hint_idxs}, hint_order: {hint_order}"
315
+ # if self.sub_idxs is not None:
316
+ # log_string += f" sub_idxs: {self.sub_idxs[0]}-{self.sub_idxs[-1]}"
317
+ # logger.warn(log_string)
318
+ # determine cond/uncond indexes that will get masked
319
+ self.local_sparse_idxs = []
320
+ self.local_sparse_idxs_inverse = list(range(x_noisy.size(0)))
321
+ for batch_idx in range(batched_number):
322
+ for i in local_idxs:
323
+ actual_i = i+(batch_idx*actual_length)
324
+ self.local_sparse_idxs.append(actual_i)
325
+ if actual_i in self.local_sparse_idxs_inverse:
326
+ self.local_sparse_idxs_inverse.remove(actual_i)
327
+ # sub_cond_hint now contains the hints relevant to current x_noisy
328
+ if hint_order is None:
329
+ sub_cond_hint = self.cond_hint_original[hint_idxs].to(dtype).to(self.device)
330
+ else:
331
+ sub_cond_hint = self.cond_hint_original[hint_order][hint_idxs].to(dtype).to(self.device)
332
+ # scale cond_hints to match noisy input
333
+ if self.control_model.use_simplified_conditioning_embedding:
334
+ # RGB SparseCtrl; the inputs are latents - use bilinear to avoid blocky artifacts
335
+ sub_cond_hint = self.latent_format.process_in(sub_cond_hint) # multiplies by model scale factor
336
+ sub_cond_hint = comfy.utils.common_upscale(sub_cond_hint, x_noisy.shape[3], x_noisy.shape[2], "nearest-exact", "center").to(dtype).to(self.device)
337
+ else:
338
+ # other SparseCtrl; inputs are typical images
339
+ sub_cond_hint = comfy.utils.common_upscale(sub_cond_hint, x_noisy.shape[3] * 8, x_noisy.shape[2] * 8, 'nearest-exact', "center").to(dtype).to(self.device)
340
+ # prepare cond_hint (b, c, h ,w)
341
+ cond_shape = list(sub_cond_hint.shape)
342
+ cond_shape[0] = len(range_idxs)
343
+ self.cond_hint = torch.zeros(cond_shape).to(dtype).to(self.device)
344
+ self.cond_hint[local_idxs] = sub_cond_hint[:]
345
+ # prepare cond_mask (b, 1, h, w)
346
+ cond_shape[1] = 1
347
+ cond_mask = torch.zeros(cond_shape).to(dtype).to(self.device)
348
+ cond_mask[local_idxs] = self.sparse_settings.sparse_mask_mult * self.weights.extras.get(SparseConst.MASK_MULT, 1.0)
349
+ # combine cond_hint and cond_mask into (b, c+1, h, w)
350
+ if not self.sparse_settings.merged:
351
+ self.cond_hint = torch.cat([self.cond_hint, cond_mask], dim=1)
352
+ del sub_cond_hint
353
+ del cond_mask
354
+ # make cond_hint match x_noisy batch
355
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
356
+ self.cond_hint = broadcast_image_to_extend(self.cond_hint, x_noisy.shape[0], batched_number)
357
+
358
+ # prepare mask_cond_hint
359
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number, dtype=dtype)
360
+
361
+ context = cond['c_crossattn']
362
+ y = cond.get('y', None)
363
+ if y is not None:
364
+ y = y.to(dtype)
365
+ timestep = self.model_sampling_current.timestep(t)
366
+ x_noisy = self.model_sampling_current.calculate_input(t, x_noisy)
367
+
368
+ control = self.control_model(x=x_noisy.to(dtype), hint=self.cond_hint, timesteps=timestep.float(), context=context.to(dtype), y=y)
369
+ return self.control_merge(None, control, control_prev, output_dtype)
370
+
371
+ def apply_advanced_strengths_and_masks(self, x: Tensor, batched_number: int):
372
+ # apply mults to indexes with and without a direct condhint
373
+ x[self.local_sparse_idxs] *= self.sparse_settings.sparse_hint_mult * self.weights.extras.get(SparseConst.HINT_MULT, 1.0)
374
+ x[self.local_sparse_idxs_inverse] *= self.sparse_settings.sparse_nonhint_mult * self.weights.extras.get(SparseConst.NONHINT_MULT, 1.0)
375
+ return super().apply_advanced_strengths_and_masks(x, batched_number)
376
+
377
+ def pre_run_advanced(self, model, percent_to_timestep_function):
378
+ super().pre_run_advanced(model, percent_to_timestep_function)
379
+ if type(self.cond_hint_original) == PreprocSparseRGBWrapper:
380
+ if not self.control_model.use_simplified_conditioning_embedding:
381
+ raise ValueError("Any model besides RGB SparseCtrl should NOT have its images go through the RGB SparseCtrl preprocessor.")
382
+ self.cond_hint_original = self.cond_hint_original.condhint
383
+ self.latent_format = model.latent_format # LatentFormat object, used to process_in latent cond hint
384
+ if self.control_model.motion_wrapper is not None:
385
+ self.control_model.motion_wrapper.reset()
386
+ self.control_model.motion_wrapper.set_strength(self.sparse_settings.motion_strength)
387
+ self.control_model.motion_wrapper.set_scale_multiplier(self.sparse_settings.motion_scale)
388
+
389
+ def cleanup_advanced(self):
390
+ super().cleanup_advanced()
391
+ if self.latent_format is not None:
392
+ del self.latent_format
393
+ self.latent_format = None
394
+ self.local_sparse_idxs = None
395
+ self.local_sparse_idxs_inverse = None
396
+
397
+ def copy(self):
398
+ c = SparseCtrlAdvanced(self.control_model, self.timestep_keyframes, self.sparse_settings, self.global_average_pooling, self.device, self.load_device, self.manual_cast_dtype)
399
+ self.copy_to(c)
400
+ self.copy_to_advanced(c)
401
+ return c
402
+
403
+
404
+ class ControlLLLiteAdvanced(ControlBase, AdvancedControlBase):
405
+ # This ControlNet is more of an attention patch than a traditional controlnet
406
+ def __init__(self, patch_attn1: LLLitePatch, patch_attn2: LLLitePatch, timestep_keyframes: TimestepKeyframeGroup, device=None):
407
+ super().__init__(device)
408
+ AdvancedControlBase.__init__(self, super(), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.controllllite(), require_model=True)
409
+ self.patch_attn1 = patch_attn1.set_control(self)
410
+ self.patch_attn2 = patch_attn2.set_control(self)
411
+ self.latent_dims_div2 = None
412
+ self.latent_dims_div4 = None
413
+
414
+ def patch_model(self, model: ModelPatcher):
415
+ model.set_model_attn1_patch(self.patch_attn1)
416
+ model.set_model_attn2_patch(self.patch_attn2)
417
+
418
+ def set_cond_hint(self, *args, **kwargs):
419
+ to_return = super().set_cond_hint(*args, **kwargs)
420
+ # cond hint for LLLite needs to be scaled between (-1, 1) instead of (0, 1)
421
+ self.cond_hint_original = self.cond_hint_original * 2.0 - 1.0
422
+ return to_return
423
+
424
+ def pre_run_advanced(self, *args, **kwargs):
425
+ AdvancedControlBase.pre_run_advanced(self, *args, **kwargs)
426
+ #logger.error(f"in cn: {id(self.patch_attn1)},{id(self.patch_attn2)}")
427
+ self.patch_attn1.set_control(self)
428
+ self.patch_attn2.set_control(self)
429
+ #logger.warn(f"in pre_run_advanced: {id(self)}")
430
+
431
+ def get_control_advanced(self, x_noisy: Tensor, t, cond, batched_number: int):
432
+ # normal ControlNet stuff
433
+ control_prev = None
434
+ if self.previous_controlnet is not None:
435
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
436
+
437
+ if self.timestep_range is not None:
438
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
439
+ return control_prev
440
+
441
+ dtype = x_noisy.dtype
442
+ # prepare cond_hint
443
+ if self.sub_idxs is not None or self.cond_hint is None or x_noisy.shape[2] * 8 != self.cond_hint.shape[2] or x_noisy.shape[3] * 8 != self.cond_hint.shape[3]:
444
+ if self.cond_hint is not None:
445
+ del self.cond_hint
446
+ self.cond_hint = None
447
+ # if self.cond_hint_original length greater or equal to real latent count, subdivide it before scaling
448
+ if self.sub_idxs is not None:
449
+ actual_cond_hint_orig = self.cond_hint_original
450
+ if self.cond_hint_original.size(0) < self.full_latent_length:
451
+ actual_cond_hint_orig = extend_to_batch_size(tensor=actual_cond_hint_orig, batch_size=self.full_latent_length)
452
+ self.cond_hint = comfy.utils.common_upscale(actual_cond_hint_orig[self.sub_idxs], x_noisy.shape[3] * 8, x_noisy.shape[2] * 8, 'nearest-exact', "center").to(dtype).to(self.device)
453
+ else:
454
+ self.cond_hint = comfy.utils.common_upscale(self.cond_hint_original, x_noisy.shape[3] * 8, x_noisy.shape[2] * 8, 'nearest-exact', "center").to(dtype).to(self.device)
455
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
456
+ self.cond_hint = broadcast_image_to_extend(self.cond_hint, x_noisy.shape[0], batched_number)
457
+ # some special logic here compared to other controlnets:
458
+ # * The cond_emb in attn patches will divide latent dims by 2 or 4, integer
459
+ # * Due to this loss, the cond_emb will become smaller than x input if latent dims are not divisble by 2 or 4
460
+ divisible_by_2_h = x_noisy.shape[2]%2==0
461
+ divisible_by_2_w = x_noisy.shape[3]%2==0
462
+ if not (divisible_by_2_h and divisible_by_2_w):
463
+ #logger.warn(f"{x_noisy.shape} not divisible by 2!")
464
+ new_h = (x_noisy.shape[2]//2)*2
465
+ new_w = (x_noisy.shape[3]//2)*2
466
+ if not divisible_by_2_h:
467
+ new_h += 2
468
+ if not divisible_by_2_w:
469
+ new_w += 2
470
+ self.latent_dims_div2 = (new_h, new_w)
471
+ divisible_by_4_h = x_noisy.shape[2]%4==0
472
+ divisible_by_4_w = x_noisy.shape[3]%4==0
473
+ if not (divisible_by_4_h and divisible_by_4_w):
474
+ #logger.warn(f"{x_noisy.shape} not divisible by 4!")
475
+ new_h = (x_noisy.shape[2]//4)*4
476
+ new_w = (x_noisy.shape[3]//4)*4
477
+ if not divisible_by_4_h:
478
+ new_h += 4
479
+ if not divisible_by_4_w:
480
+ new_w += 4
481
+ self.latent_dims_div4 = (new_h, new_w)
482
+ # prepare mask
483
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number)
484
+ # done preparing; model patches will take care of everything now.
485
+ # return normal controlnet stuff
486
+ return control_prev
487
+
488
+ def cleanup_advanced(self):
489
+ super().cleanup_advanced()
490
+ self.patch_attn1.cleanup()
491
+ self.patch_attn2.cleanup()
492
+ self.latent_dims_div2 = None
493
+ self.latent_dims_div4 = None
494
+
495
+ def copy(self):
496
+ c = ControlLLLiteAdvanced(self.patch_attn1, self.patch_attn2, self.timestep_keyframes)
497
+ self.copy_to(c)
498
+ self.copy_to_advanced(c)
499
+ return c
500
+
501
+ # deepcopy needs to properly keep track of objects to work between model.clone calls!
502
+ # def __deepcopy__(self, *args, **kwargs):
503
+ # self.cleanup_advanced()
504
+ # return self
505
+
506
+ # def get_models(self):
507
+ # # get_models is called once at the start of every KSampler run - use to reset already_patched status
508
+ # out = super().get_models()
509
+ # logger.error(f"in get_models! {id(self)}")
510
+ # return out
511
+
512
+
513
+ def load_controlnet(ckpt_path, timestep_keyframe: TimestepKeyframeGroup=None, model=None):
514
+ controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
515
+ control = None
516
+ # check if a non-vanilla ControlNet
517
+ controlnet_type = ControlWeightType.DEFAULT
518
+ has_controlnet_key = False
519
+ has_motion_modules_key = False
520
+ has_temporal_res_block_key = False
521
+ for key in controlnet_data:
522
+ # LLLite check
523
+ if "lllite" in key:
524
+ controlnet_type = ControlWeightType.CONTROLLLLITE
525
+ break
526
+ # SparseCtrl check
527
+ elif "motion_modules" in key:
528
+ has_motion_modules_key = True
529
+ elif "controlnet" in key:
530
+ has_controlnet_key = True
531
+ # SVD-ControlNet check
532
+ elif "temporal_res_block" in key:
533
+ has_temporal_res_block_key = True
534
+ if has_controlnet_key and has_motion_modules_key:
535
+ controlnet_type = ControlWeightType.SPARSECTRL
536
+ elif has_controlnet_key and has_temporal_res_block_key:
537
+ controlnet_type = ControlWeightType.SVD_CONTROLNET
538
+
539
+ if controlnet_type != ControlWeightType.DEFAULT:
540
+ if controlnet_type == ControlWeightType.CONTROLLLLITE:
541
+ control = load_controllllite(ckpt_path, controlnet_data=controlnet_data, timestep_keyframe=timestep_keyframe)
542
+ elif controlnet_type == ControlWeightType.SPARSECTRL:
543
+ control = load_sparsectrl(ckpt_path, controlnet_data=controlnet_data, timestep_keyframe=timestep_keyframe, model=model)
544
+ elif controlnet_type == ControlWeightType.SVD_CONTROLNET:
545
+ control = load_svdcontrolnet(ckpt_path, controlnet_data=controlnet_data, timestep_keyframe=timestep_keyframe)
546
+ #raise Exception(f"SVD-ControlNet is not supported yet!")
547
+ #control = comfy_cn.load_controlnet(ckpt_path, model=model)
548
+ # otherwise, load vanilla ControlNet
549
+ else:
550
+ try:
551
+ # hacky way of getting load_torch_file in load_controlnet to use already-present controlnet_data and not redo loading
552
+ orig_load_torch_file = comfy.utils.load_torch_file
553
+ comfy.utils.load_torch_file = load_torch_file_with_dict_factory(controlnet_data, orig_load_torch_file)
554
+ control = comfy_cn.load_controlnet(ckpt_path, model=model)
555
+ finally:
556
+ comfy.utils.load_torch_file = orig_load_torch_file
557
+ return convert_to_advanced(control, timestep_keyframe=timestep_keyframe)
558
+
559
+
560
+ def convert_to_advanced(control, timestep_keyframe: TimestepKeyframeGroup=None):
561
+ # if already advanced, leave it be
562
+ if is_advanced_controlnet(control):
563
+ return control
564
+ # if exactly ControlNet returned, transform it into ControlNetAdvanced
565
+ if type(control) == ControlNet:
566
+ return ControlNetAdvanced.from_vanilla(v=control, timestep_keyframe=timestep_keyframe)
567
+ # if exactly ControlLora returned, transform it into ControlLoraAdvanced
568
+ elif type(control) == ControlLora:
569
+ return ControlLoraAdvanced.from_vanilla(v=control, timestep_keyframe=timestep_keyframe)
570
+ # if T2IAdapter returned, transform it into T2IAdapterAdvanced
571
+ elif isinstance(control, T2IAdapter):
572
+ return T2IAdapterAdvanced.from_vanilla(v=control, timestep_keyframe=timestep_keyframe)
573
+ # otherwise, leave it be - might be something I am not supporting yet
574
+ return control
575
+
576
+
577
+ def is_advanced_controlnet(input_object):
578
+ return hasattr(input_object, "sub_idxs")
579
+
580
+
581
+ def load_sparsectrl(ckpt_path: str, controlnet_data: dict[str, Tensor]=None, timestep_keyframe: TimestepKeyframeGroup=None, sparse_settings=SparseSettings.default(), model=None) -> SparseCtrlAdvanced:
582
+ if controlnet_data is None:
583
+ controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
584
+ # first, separate out motion part from normal controlnet part and attempt to load that portion
585
+ motion_data = {}
586
+ for key in list(controlnet_data.keys()):
587
+ if "temporal" in key:
588
+ motion_data[key] = controlnet_data.pop(key)
589
+ if len(motion_data) == 0:
590
+ raise ValueError(f"No motion-related keys in '{ckpt_path}'; not a valid SparseCtrl model!")
591
+
592
+ # now, load as if it was a normal controlnet - mostly copied from comfy load_controlnet function
593
+ controlnet_config: dict[str] = None
594
+ is_diffusers = False
595
+ use_simplified_conditioning_embedding = False
596
+ if "controlnet_cond_embedding.conv_in.weight" in controlnet_data:
597
+ is_diffusers = True
598
+ if "controlnet_cond_embedding.weight" in controlnet_data:
599
+ is_diffusers = True
600
+ use_simplified_conditioning_embedding = True
601
+ if is_diffusers: #diffusers format
602
+ unet_dtype = comfy.model_management.unet_dtype()
603
+ controlnet_config = comfy.model_detection.unet_config_from_diffusers_unet(controlnet_data, unet_dtype)
604
+ diffusers_keys = comfy.utils.unet_to_diffusers(controlnet_config)
605
+ diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
606
+ diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
607
+
608
+ count = 0
609
+ loop = True
610
+ while loop:
611
+ suffix = [".weight", ".bias"]
612
+ for s in suffix:
613
+ k_in = "controlnet_down_blocks.{}{}".format(count, s)
614
+ k_out = "zero_convs.{}.0{}".format(count, s)
615
+ if k_in not in controlnet_data:
616
+ loop = False
617
+ break
618
+ diffusers_keys[k_in] = k_out
619
+ count += 1
620
+ # normal conditioning embedding
621
+ if not use_simplified_conditioning_embedding:
622
+ count = 0
623
+ loop = True
624
+ while loop:
625
+ suffix = [".weight", ".bias"]
626
+ for s in suffix:
627
+ if count == 0:
628
+ k_in = "controlnet_cond_embedding.conv_in{}".format(s)
629
+ else:
630
+ k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
631
+ k_out = "input_hint_block.{}{}".format(count * 2, s)
632
+ if k_in not in controlnet_data:
633
+ k_in = "controlnet_cond_embedding.conv_out{}".format(s)
634
+ loop = False
635
+ diffusers_keys[k_in] = k_out
636
+ count += 1
637
+ # simplified conditioning embedding
638
+ else:
639
+ count = 0
640
+ suffix = [".weight", ".bias"]
641
+ for s in suffix:
642
+ k_in = "controlnet_cond_embedding{}".format(s)
643
+ k_out = "input_hint_block.{}{}".format(count, s)
644
+ diffusers_keys[k_in] = k_out
645
+
646
+ new_sd = {}
647
+ for k in diffusers_keys:
648
+ if k in controlnet_data:
649
+ new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
650
+
651
+ leftover_keys = controlnet_data.keys()
652
+ if len(leftover_keys) > 0:
653
+ logger.info("leftover keys:", leftover_keys)
654
+ controlnet_data = new_sd
655
+
656
+ pth_key = 'control_model.zero_convs.0.0.weight'
657
+ pth = False
658
+ key = 'zero_convs.0.0.weight'
659
+ if pth_key in controlnet_data:
660
+ pth = True
661
+ key = pth_key
662
+ prefix = "control_model."
663
+ elif key in controlnet_data:
664
+ prefix = ""
665
+ else:
666
+ raise ValueError("The provided model is not a valid SparseCtrl model! [ErrorCode: HORSERADISH]")
667
+
668
+ if controlnet_config is None:
669
+ unet_dtype = comfy.model_management.unet_dtype()
670
+ controlnet_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, unet_dtype, True).unet_config
671
+ load_device = comfy.model_management.get_torch_device()
672
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
673
+ if manual_cast_dtype is not None:
674
+ controlnet_config["operations"] = manual_cast_clean_groupnorm
675
+ else:
676
+ controlnet_config["operations"] = disable_weight_init_clean_groupnorm
677
+ controlnet_config.pop("out_channels")
678
+ # get proper hint channels
679
+ if use_simplified_conditioning_embedding:
680
+ controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
681
+ controlnet_config["use_simplified_conditioning_embedding"] = use_simplified_conditioning_embedding
682
+ else:
683
+ controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
684
+ controlnet_config["use_simplified_conditioning_embedding"] = use_simplified_conditioning_embedding
685
+ control_model = SparseControlNet(**controlnet_config)
686
+
687
+ if pth:
688
+ if 'difference' in controlnet_data:
689
+ if model is not None:
690
+ comfy.model_management.load_models_gpu([model])
691
+ model_sd = model.model_state_dict()
692
+ for x in controlnet_data:
693
+ c_m = "control_model."
694
+ if x.startswith(c_m):
695
+ sd_key = "diffusion_model.{}".format(x[len(c_m):])
696
+ if sd_key in model_sd:
697
+ cd = controlnet_data[x]
698
+ cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
699
+ else:
700
+ logger.warning("WARNING: Loaded a diff SparseCtrl without a model. It will very likely not work.")
701
+
702
+ class WeightsLoader(torch.nn.Module):
703
+ pass
704
+ w = WeightsLoader()
705
+ w.control_model = control_model
706
+ missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
707
+ else:
708
+ missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
709
+ if len(missing) > 0 or len(unexpected) > 0:
710
+ logger.info(f"SparseCtrl ControlNet: {missing}, {unexpected}")
711
+
712
+ global_average_pooling = False
713
+ filename = os.path.splitext(ckpt_path)[0]
714
+ if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
715
+ global_average_pooling = True
716
+
717
+ # actually load motion portion of model now
718
+ motion_wrapper: SparseCtrlMotionWrapper = SparseCtrlMotionWrapper(motion_data, ops=controlnet_config.get("operations", None)).to(comfy.model_management.unet_dtype())
719
+ missing, unexpected = motion_wrapper.load_state_dict(motion_data)
720
+ if len(missing) > 0 or len(unexpected) > 0:
721
+ logger.info(f"SparseCtrlMotionWrapper: {missing}, {unexpected}")
722
+
723
+ # both motion portion and controlnet portions are loaded; bring them together if using motion model
724
+ if sparse_settings.use_motion:
725
+ motion_wrapper.inject(control_model)
726
+
727
+ control = SparseCtrlAdvanced(control_model, timestep_keyframes=timestep_keyframe, sparse_settings=sparse_settings, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
728
+ return control
729
+
730
+
731
+ def load_controllllite(ckpt_path: str, controlnet_data: dict[str, Tensor]=None, timestep_keyframe: TimestepKeyframeGroup=None):
732
+ if controlnet_data is None:
733
+ controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
734
+ # adapted from https://github.com/kohya-ss/ControlNet-LLLite-ComfyUI
735
+ # first, split weights for each module
736
+ module_weights = {}
737
+ for key, value in controlnet_data.items():
738
+ fragments = key.split(".")
739
+ module_name = fragments[0]
740
+ weight_name = ".".join(fragments[1:])
741
+
742
+ if module_name not in module_weights:
743
+ module_weights[module_name] = {}
744
+ module_weights[module_name][weight_name] = value
745
+
746
+ # next, load each module
747
+ modules = {}
748
+ for module_name, weights in module_weights.items():
749
+ # kohya planned to do something about how these should be chosen, so I'm not touching this
750
+ # since I am not familiar with the logic for this
751
+ if "conditioning1.4.weight" in weights:
752
+ depth = 3
753
+ elif weights["conditioning1.2.weight"].shape[-1] == 4:
754
+ depth = 2
755
+ else:
756
+ depth = 1
757
+
758
+ module = LLLiteModule(
759
+ name=module_name,
760
+ is_conv2d=weights["down.0.weight"].ndim == 4,
761
+ in_dim=weights["down.0.weight"].shape[1],
762
+ depth=depth,
763
+ cond_emb_dim=weights["conditioning1.0.weight"].shape[0] * 2,
764
+ mlp_dim=weights["down.0.weight"].shape[0],
765
+ )
766
+ # load weights into module
767
+ module.load_state_dict(weights)
768
+ modules[module_name] = module
769
+ if len(modules) == 1:
770
+ module.is_first = True
771
+
772
+ #logger.info(f"loaded {ckpt_path} successfully, {len(modules)} modules")
773
+
774
+ patch_attn1 = LLLitePatch(modules=modules, patch_type=LLLitePatch.ATTN1)
775
+ patch_attn2 = LLLitePatch(modules=modules, patch_type=LLLitePatch.ATTN2)
776
+ control = ControlLLLiteAdvanced(patch_attn1=patch_attn1, patch_attn2=patch_attn2, timestep_keyframes=timestep_keyframe)
777
+ return control
778
+
779
+
780
+ def load_svdcontrolnet(ckpt_path: str, controlnet_data: dict[str, Tensor]=None, timestep_keyframe: TimestepKeyframeGroup=None, model=None):
781
+ if controlnet_data is None:
782
+ controlnet_data = comfy.utils.load_torch_file(ckpt_path, safe_load=True)
783
+
784
+ controlnet_config = None
785
+ if "controlnet_cond_embedding.conv_in.weight" in controlnet_data: #diffusers format
786
+ unet_dtype = comfy.model_management.unet_dtype()
787
+ controlnet_config = svd_unet_config_from_diffusers_unet(controlnet_data, unet_dtype)
788
+ diffusers_keys = svd_unet_to_diffusers(controlnet_config)
789
+ diffusers_keys["controlnet_mid_block.weight"] = "middle_block_out.0.weight"
790
+ diffusers_keys["controlnet_mid_block.bias"] = "middle_block_out.0.bias"
791
+
792
+ count = 0
793
+ loop = True
794
+ while loop:
795
+ suffix = [".weight", ".bias"]
796
+ for s in suffix:
797
+ k_in = "controlnet_down_blocks.{}{}".format(count, s)
798
+ k_out = "zero_convs.{}.0{}".format(count, s)
799
+ if k_in not in controlnet_data:
800
+ loop = False
801
+ break
802
+ diffusers_keys[k_in] = k_out
803
+ count += 1
804
+
805
+ count = 0
806
+ loop = True
807
+ while loop:
808
+ suffix = [".weight", ".bias"]
809
+ for s in suffix:
810
+ if count == 0:
811
+ k_in = "controlnet_cond_embedding.conv_in{}".format(s)
812
+ else:
813
+ k_in = "controlnet_cond_embedding.blocks.{}{}".format(count - 1, s)
814
+ k_out = "input_hint_block.{}{}".format(count * 2, s)
815
+ if k_in not in controlnet_data:
816
+ k_in = "controlnet_cond_embedding.conv_out{}".format(s)
817
+ loop = False
818
+ diffusers_keys[k_in] = k_out
819
+ count += 1
820
+
821
+ new_sd = {}
822
+ for k in diffusers_keys:
823
+ if k in controlnet_data:
824
+ new_sd[diffusers_keys[k]] = controlnet_data.pop(k)
825
+
826
+ leftover_keys = controlnet_data.keys()
827
+ if len(leftover_keys) > 0:
828
+ spatial_leftover_keys = []
829
+ temporal_leftover_keys = []
830
+ other_leftover_keys = []
831
+ for key in leftover_keys:
832
+ if "spatial" in key:
833
+ spatial_leftover_keys.append(key)
834
+ elif "temporal" in key:
835
+ temporal_leftover_keys.append(key)
836
+ else:
837
+ other_leftover_keys.append(key)
838
+ logger.warn(f"spatial_leftover_keys ({len(spatial_leftover_keys)}): {spatial_leftover_keys}")
839
+ logger.warn(f"temporal_leftover_keys ({len(temporal_leftover_keys)}): {temporal_leftover_keys}")
840
+ logger.warn(f"other_leftover_keys ({len(other_leftover_keys)}): {other_leftover_keys}")
841
+ #print("leftover keys:", leftover_keys)
842
+ controlnet_data = new_sd
843
+
844
+ pth_key = 'control_model.zero_convs.0.0.weight'
845
+ pth = False
846
+ key = 'zero_convs.0.0.weight'
847
+ if pth_key in controlnet_data:
848
+ pth = True
849
+ key = pth_key
850
+ prefix = "control_model."
851
+ elif key in controlnet_data:
852
+ prefix = ""
853
+ else:
854
+ raise ValueError("The provided model is not a valid SVD-ControlNet model! [ErrorCode: MUSTARD]")
855
+
856
+ if controlnet_config is None:
857
+ unet_dtype = comfy.model_management.unet_dtype()
858
+ controlnet_config = comfy.model_detection.model_config_from_unet(controlnet_data, prefix, unet_dtype, True).unet_config
859
+ load_device = comfy.model_management.get_torch_device()
860
+ manual_cast_dtype = comfy.model_management.unet_manual_cast(unet_dtype, load_device)
861
+ if manual_cast_dtype is not None:
862
+ controlnet_config["operations"] = comfy.ops.manual_cast
863
+ controlnet_config.pop("out_channels")
864
+ controlnet_config["hint_channels"] = controlnet_data["{}input_hint_block.0.weight".format(prefix)].shape[1]
865
+ control_model = SVDControlNet(**controlnet_config)
866
+
867
+ if pth:
868
+ if 'difference' in controlnet_data:
869
+ if model is not None:
870
+ comfy.model_management.load_models_gpu([model])
871
+ model_sd = model.model_state_dict()
872
+ for x in controlnet_data:
873
+ c_m = "control_model."
874
+ if x.startswith(c_m):
875
+ sd_key = "diffusion_model.{}".format(x[len(c_m):])
876
+ if sd_key in model_sd:
877
+ cd = controlnet_data[x]
878
+ cd += model_sd[sd_key].type(cd.dtype).to(cd.device)
879
+ else:
880
+ print("WARNING: Loaded a diff controlnet without a model. It will very likely not work.")
881
+
882
+ class WeightsLoader(torch.nn.Module):
883
+ pass
884
+ w = WeightsLoader()
885
+ w.control_model = control_model
886
+ missing, unexpected = w.load_state_dict(controlnet_data, strict=False)
887
+ else:
888
+ missing, unexpected = control_model.load_state_dict(controlnet_data, strict=False)
889
+ if len(missing) > 0 or len(unexpected) > 0:
890
+ logger.info(f"SVD-ControlNet: {missing}, {unexpected}")
891
+
892
+ global_average_pooling = False
893
+ filename = os.path.splitext(ckpt_path)[0]
894
+ if filename.endswith("_shuffle") or filename.endswith("_shuffle_fp16"): #TODO: smarter way of enabling global_average_pooling
895
+ global_average_pooling = True
896
+
897
+ control = SVDControlNetAdvanced(control_model, timestep_keyframes=timestep_keyframe, global_average_pooling=global_average_pooling, load_device=load_device, manual_cast_dtype=manual_cast_dtype)
898
+ return control
899
+
ComfyUI-Advanced-ControlNet/adv_control/control_lllite.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # adapted from https://github.com/kohya-ss/ControlNet-LLLite-ComfyUI
2
+ # basically, all the LLLite core code is from there, which I then combined with
3
+ # Advanced-ControlNet features and QoL
4
+ import math
5
+ from typing import Union
6
+ from torch import Tensor
7
+ import torch
8
+ import os
9
+
10
+ import comfy.utils
11
+ from comfy.controlnet import ControlBase
12
+
13
+ from .logger import logger
14
+ from .utils import AdvancedControlBase, deepcopy_with_sharing, prepare_mask_batch
15
+
16
+
17
+ def extra_options_to_module_prefix(extra_options):
18
+ # extra_options = {'transformer_index': 2, 'block_index': 8, 'original_shape': [2, 4, 128, 128], 'block': ('input', 7), 'n_heads': 20, 'dim_head': 64}
19
+
20
+ # block is: [('input', 4), ('input', 5), ('input', 7), ('input', 8), ('middle', 0),
21
+ # ('output', 0), ('output', 1), ('output', 2), ('output', 3), ('output', 4), ('output', 5)]
22
+ # transformer_index is: [0, 1, 2, 3, 4, 5, 6, 7, 8], for each block
23
+ # block_index is: 0-1 or 0-9, depends on the block
24
+ # input 7 and 8, middle has 10 blocks
25
+
26
+ # make module name from extra_options
27
+ block = extra_options["block"]
28
+ block_index = extra_options["block_index"]
29
+ if block[0] == "input":
30
+ module_pfx = f"lllite_unet_input_blocks_{block[1]}_1_transformer_blocks_{block_index}"
31
+ elif block[0] == "middle":
32
+ module_pfx = f"lllite_unet_middle_block_1_transformer_blocks_{block_index}"
33
+ elif block[0] == "output":
34
+ module_pfx = f"lllite_unet_output_blocks_{block[1]}_1_transformer_blocks_{block_index}"
35
+ else:
36
+ raise Exception(f"ControlLLLite: invalid block name '{block[0]}'. Expected 'input', 'middle', or 'output'.")
37
+ return module_pfx
38
+
39
+
40
+ class LLLitePatch:
41
+ ATTN1 = "attn1"
42
+ ATTN2 = "attn2"
43
+ def __init__(self, modules: dict[str, 'LLLiteModule'], patch_type: str, control: Union[AdvancedControlBase, ControlBase]=None):
44
+ self.modules = modules
45
+ self.control = control
46
+ self.patch_type = patch_type
47
+ #logger.error(f"create LLLitePatch: {id(self)},{control}")
48
+
49
+ def __call__(self, q, k, v, extra_options):
50
+ #logger.error(f"in __call__: {id(self)}")
51
+ # determine if have anything to run
52
+ if self.control.timestep_range is not None:
53
+ # it turns out comparing single-value tensors to floats is extremely slow
54
+ # a: Tensor = extra_options["sigmas"][0]
55
+ if self.control.t > self.control.timestep_range[0] or self.control.t < self.control.timestep_range[1]:
56
+ return q, k, v
57
+
58
+ module_pfx = extra_options_to_module_prefix(extra_options)
59
+
60
+ is_attn1 = q.shape[-1] == k.shape[-1] # self attention
61
+ if is_attn1:
62
+ module_pfx = module_pfx + "_attn1"
63
+ else:
64
+ module_pfx = module_pfx + "_attn2"
65
+
66
+ module_pfx_to_q = module_pfx + "_to_q"
67
+ module_pfx_to_k = module_pfx + "_to_k"
68
+ module_pfx_to_v = module_pfx + "_to_v"
69
+
70
+ if module_pfx_to_q in self.modules:
71
+ q = q + self.modules[module_pfx_to_q](q, self.control)
72
+ if module_pfx_to_k in self.modules:
73
+ k = k + self.modules[module_pfx_to_k](k, self.control)
74
+ if module_pfx_to_v in self.modules:
75
+ v = v + self.modules[module_pfx_to_v](v, self.control)
76
+
77
+ return q, k, v
78
+
79
+ def to(self, device):
80
+ #logger.info(f"to... has control? {self.control}")
81
+ for d in self.modules.keys():
82
+ self.modules[d] = self.modules[d].to(device)
83
+ return self
84
+
85
+ def set_control(self, control: Union[AdvancedControlBase, ControlBase]) -> 'LLLitePatch':
86
+ self.control = control
87
+ return self
88
+ #logger.error(f"set control for LLLitePatch: {id(self)}, cn: {id(control)}")
89
+
90
+ def clone_with_control(self, control: AdvancedControlBase):
91
+ #logger.error(f"clone-set control for LLLitePatch: {id(self)},{id(control)}")
92
+ return LLLitePatch(self.modules, self.patch_type, control)
93
+
94
+ def cleanup(self):
95
+ #total_cleaned = 0
96
+ for module in self.modules.values():
97
+ module.cleanup()
98
+ # total_cleaned += 1
99
+ #logger.info(f"cleaned modules: {total_cleaned}, {id(self)}")
100
+ #logger.error(f"cleanup LLLitePatch: {id(self)}")
101
+
102
+ # make sure deepcopy does not copy control, and deepcopied LLLitePatch should be assigned to control
103
+ def __deepcopy__(self, memo):
104
+ self.cleanup()
105
+ to_return: LLLitePatch = deepcopy_with_sharing(self, shared_attribute_names = ['control'], memo=memo)
106
+ #logger.warn(f"patch {id(self)} turned into {id(to_return)}")
107
+ try:
108
+ if self.patch_type == self.ATTN1:
109
+ to_return.control.patch_attn1 = to_return
110
+ elif self.patch_type == self.ATTN2:
111
+ to_return.control.patch_attn2 = to_return
112
+ except Exception:
113
+ pass
114
+ return to_return
115
+
116
+
117
+ # TODO: use comfy.ops to support fp8 properly
118
+ class LLLiteModule(torch.nn.Module):
119
+ def __init__(
120
+ self,
121
+ name: str,
122
+ is_conv2d: bool,
123
+ in_dim: int,
124
+ depth: int,
125
+ cond_emb_dim: int,
126
+ mlp_dim: int,
127
+ ):
128
+ super().__init__()
129
+ self.name = name
130
+ self.is_conv2d = is_conv2d
131
+ self.is_first = False
132
+
133
+ modules = []
134
+ modules.append(torch.nn.Conv2d(3, cond_emb_dim // 2, kernel_size=4, stride=4, padding=0)) # to latent (from VAE) size*2
135
+ if depth == 1:
136
+ modules.append(torch.nn.ReLU(inplace=True))
137
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim, kernel_size=2, stride=2, padding=0))
138
+ elif depth == 2:
139
+ modules.append(torch.nn.ReLU(inplace=True))
140
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim, kernel_size=4, stride=4, padding=0))
141
+ elif depth == 3:
142
+ # kernel size 8 is too large, so set it to 4
143
+ modules.append(torch.nn.ReLU(inplace=True))
144
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim // 2, kernel_size=4, stride=4, padding=0))
145
+ modules.append(torch.nn.ReLU(inplace=True))
146
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim, kernel_size=2, stride=2, padding=0))
147
+
148
+ self.conditioning1 = torch.nn.Sequential(*modules)
149
+
150
+ if self.is_conv2d:
151
+ self.down = torch.nn.Sequential(
152
+ torch.nn.Conv2d(in_dim, mlp_dim, kernel_size=1, stride=1, padding=0),
153
+ torch.nn.ReLU(inplace=True),
154
+ )
155
+ self.mid = torch.nn.Sequential(
156
+ torch.nn.Conv2d(mlp_dim + cond_emb_dim, mlp_dim, kernel_size=1, stride=1, padding=0),
157
+ torch.nn.ReLU(inplace=True),
158
+ )
159
+ self.up = torch.nn.Sequential(
160
+ torch.nn.Conv2d(mlp_dim, in_dim, kernel_size=1, stride=1, padding=0),
161
+ )
162
+ else:
163
+ self.down = torch.nn.Sequential(
164
+ torch.nn.Linear(in_dim, mlp_dim),
165
+ torch.nn.ReLU(inplace=True),
166
+ )
167
+ self.mid = torch.nn.Sequential(
168
+ torch.nn.Linear(mlp_dim + cond_emb_dim, mlp_dim),
169
+ torch.nn.ReLU(inplace=True),
170
+ )
171
+ self.up = torch.nn.Sequential(
172
+ torch.nn.Linear(mlp_dim, in_dim),
173
+ )
174
+
175
+ self.depth = depth
176
+ self.cond_emb = None
177
+ self.cx_shape = None
178
+ self.prev_batch = 0
179
+ self.prev_sub_idxs = None
180
+
181
+ def cleanup(self):
182
+ del self.cond_emb
183
+ self.cond_emb = None
184
+ self.cx_shape = None
185
+ self.prev_batch = 0
186
+ self.prev_sub_idxs = None
187
+
188
+ def forward(self, x: Tensor, control: Union[AdvancedControlBase, ControlBase]):
189
+ mask = None
190
+ mask_tk = None
191
+ #logger.info(x.shape)
192
+ if self.cond_emb is None or control.sub_idxs != self.prev_sub_idxs or x.shape[0] != self.prev_batch:
193
+ # print(f"cond_emb is None, {self.name}")
194
+ cond_hint = control.cond_hint.to(x.device, dtype=x.dtype)
195
+ if control.latent_dims_div2 is not None and x.shape[-1] != 1280:
196
+ cond_hint = comfy.utils.common_upscale(cond_hint, control.latent_dims_div2[0] * 8, control.latent_dims_div2[1] * 8, 'nearest-exact', "center").to(x.device, dtype=x.dtype)
197
+ elif control.latent_dims_div4 is not None and x.shape[-1] == 1280:
198
+ cond_hint = comfy.utils.common_upscale(cond_hint, control.latent_dims_div4[0] * 8, control.latent_dims_div4[1] * 8, 'nearest-exact', "center").to(x.device, dtype=x.dtype)
199
+ cx = self.conditioning1(cond_hint)
200
+ self.cx_shape = cx.shape
201
+ if not self.is_conv2d:
202
+ # reshape / b,c,h,w -> b,h*w,c
203
+ n, c, h, w = cx.shape
204
+ cx = cx.view(n, c, h * w).permute(0, 2, 1)
205
+ self.cond_emb = cx
206
+ # save prev values
207
+ self.prev_batch = x.shape[0]
208
+ self.prev_sub_idxs = control.sub_idxs
209
+
210
+ cx: torch.Tensor = self.cond_emb
211
+ # print(f"forward {self.name}, {cx.shape}, {x.shape}")
212
+
213
+ # TODO: make masks work for conv2d (could not find any ControlLLLites at this time that use them)
214
+ # create masks
215
+ if not self.is_conv2d:
216
+ n, c, h, w = self.cx_shape
217
+ if control.mask_cond_hint is not None:
218
+ mask = prepare_mask_batch(control.mask_cond_hint, (1, 1, h, w)).to(cx.dtype)
219
+ mask = mask.view(mask.shape[0], 1, h * w).permute(0, 2, 1)
220
+ if control.tk_mask_cond_hint is not None:
221
+ mask_tk = prepare_mask_batch(control.mask_cond_hint, (1, 1, h, w)).to(cx.dtype)
222
+ mask_tk = mask_tk.view(mask_tk.shape[0], 1, h * w).permute(0, 2, 1)
223
+
224
+ # x in uncond/cond doubles batch size
225
+ if x.shape[0] != cx.shape[0]:
226
+ if self.is_conv2d:
227
+ cx = cx.repeat(x.shape[0] // cx.shape[0], 1, 1, 1)
228
+ else:
229
+ # print("x.shape[0] != cx.shape[0]", x.shape[0], cx.shape[0])
230
+ cx = cx.repeat(x.shape[0] // cx.shape[0], 1, 1)
231
+ if mask is not None:
232
+ mask = mask.repeat(x.shape[0] // mask.shape[0], 1, 1)
233
+ if mask_tk is not None:
234
+ mask_tk = mask_tk.repeat(x.shape[0] // mask_tk.shape[0], 1, 1)
235
+
236
+ if mask is None:
237
+ mask = 1.0
238
+ elif mask_tk is not None:
239
+ mask = mask * mask_tk
240
+
241
+ #logger.info(f"cs: {cx.shape}, x: {x.shape}, is_conv2d: {self.is_conv2d}")
242
+ cx = torch.cat([cx, self.down(x)], dim=1 if self.is_conv2d else 2)
243
+ cx = self.mid(cx)
244
+ cx = self.up(cx)
245
+ if control.latent_keyframes is not None:
246
+ cx = cx * control.calc_latent_keyframe_mults(x=cx, batched_number=control.batched_number)
247
+ if control.weights is not None and control.weights.has_uncond_multiplier:
248
+ cond_or_uncond = control.batched_number.cond_or_uncond
249
+ actual_length = cx.size(0) // control.batched_number
250
+ for idx, cond_type in enumerate(cond_or_uncond):
251
+ # if uncond, set to weight's uncond_multiplier
252
+ if cond_type == 1:
253
+ cx[actual_length*idx:actual_length*(idx+1)] *= control.weights.uncond_multiplier
254
+ return cx * mask * control.strength * control._current_timestep_keyframe.strength
ComfyUI-Advanced-ControlNet/adv_control/control_reference.py ADDED
@@ -0,0 +1,833 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Callable, Union
2
+
3
+ import math
4
+ import torch
5
+ from torch import Tensor
6
+
7
+ import comfy.sample
8
+ import comfy.model_patcher
9
+ import comfy.utils
10
+ from comfy.controlnet import ControlBase
11
+ from comfy.model_patcher import ModelPatcher
12
+ from comfy.ldm.modules.attention import BasicTransformerBlock
13
+ from comfy.ldm.modules.diffusionmodules import openaimodel
14
+
15
+ from .logger import logger
16
+ from .utils import (AdvancedControlBase, ControlWeights, TimestepKeyframeGroup, AbstractPreprocWrapper,
17
+ deepcopy_with_sharing, prepare_mask_batch, broadcast_image_to_extend)
18
+
19
+
20
+ def refcn_sample_factory(orig_comfy_sample: Callable, is_custom=False) -> Callable:
21
+ def get_refcn(control: ControlBase, order: int=-1):
22
+ ref_set: set[ReferenceAdvanced] = set()
23
+ if control is None:
24
+ return ref_set
25
+ if type(control) == ReferenceAdvanced:
26
+ control.order = order
27
+ order -= 1
28
+ ref_set.add(control)
29
+ ref_set.update(get_refcn(control.previous_controlnet, order=order))
30
+ return ref_set
31
+
32
+ def refcn_sample(model: ModelPatcher, *args, **kwargs):
33
+ # check if positive or negative conds contain ref cn
34
+ positive = args[-3]
35
+ negative = args[-2]
36
+ ref_set = set()
37
+ if positive is not None:
38
+ for cond in positive:
39
+ if "control" in cond[1]:
40
+ ref_set.update(get_refcn(cond[1]["control"]))
41
+ if negative is not None:
42
+ for cond in negative:
43
+ if "control" in cond[1]:
44
+ ref_set.update(get_refcn(cond[1]["control"]))
45
+ # if no ref cn found, do original function immediately
46
+ if len(ref_set) == 0:
47
+ return orig_comfy_sample(model, *args, **kwargs)
48
+ # otherwise, injection time
49
+ try:
50
+ # inject
51
+ # storage for all Reference-related injections
52
+ reference_injections = ReferenceInjections()
53
+
54
+ # first, handle attn module injection
55
+ all_modules = torch_dfs(model.model)
56
+ attn_modules: list[RefBasicTransformerBlock] = []
57
+ for module in all_modules:
58
+ if isinstance(module, BasicTransformerBlock):
59
+ attn_modules.append(module)
60
+ attn_modules = [module for module in all_modules if isinstance(module, BasicTransformerBlock)]
61
+ attn_modules = sorted(attn_modules, key=lambda x: -x.norm1.normalized_shape[0])
62
+ for i, module in enumerate(attn_modules):
63
+ injection_holder = InjectionBasicTransformerBlockHolder(block=module, idx=i)
64
+ injection_holder.attn_weight = float(i) / float(len(attn_modules))
65
+ if hasattr(module, "_forward"): # backward compatibility
66
+ module._forward = _forward_inject_BasicTransformerBlock.__get__(module, type(module))
67
+ else:
68
+ module.forward = _forward_inject_BasicTransformerBlock.__get__(module, type(module))
69
+ module.injection_holder = injection_holder
70
+ reference_injections.attn_modules.append(module)
71
+ # figure out which module is middle block
72
+ if hasattr(model.model.diffusion_model, "middle_block"):
73
+ mid_modules = torch_dfs(model.model.diffusion_model.middle_block)
74
+ mid_attn_modules: list[RefBasicTransformerBlock] = [module for module in mid_modules if isinstance(module, BasicTransformerBlock)]
75
+ for module in mid_attn_modules:
76
+ module.injection_holder.is_middle = True
77
+
78
+ # next, handle gn module injection (TimestepEmbedSequential)
79
+ # TODO: figure out the logic behind these hardcoded indexes
80
+ if type(model.model).__name__ == "SDXL":
81
+ input_block_indices = [4, 5, 7, 8]
82
+ output_block_indices = [0, 1, 2, 3, 4, 5]
83
+ else:
84
+ input_block_indices = [4, 5, 7, 8, 10, 11]
85
+ output_block_indices = [0, 1, 2, 3, 4, 5, 6, 7]
86
+ if hasattr(model.model.diffusion_model, "middle_block"):
87
+ module = model.model.diffusion_model.middle_block
88
+ injection_holder = InjectionTimestepEmbedSequentialHolder(block=module, idx=0, is_middle=True)
89
+ injection_holder.gn_weight = 0.0
90
+ module.injection_holder = injection_holder
91
+ reference_injections.gn_modules.append(module)
92
+ for w, i in enumerate(input_block_indices):
93
+ module = model.model.diffusion_model.input_blocks[i]
94
+ injection_holder = InjectionTimestepEmbedSequentialHolder(block=module, idx=i, is_input=True)
95
+ injection_holder.gn_weight = 1.0 - float(w) / float(len(input_block_indices))
96
+ module.injection_holder = injection_holder
97
+ reference_injections.gn_modules.append(module)
98
+ for w, i in enumerate(output_block_indices):
99
+ module = model.model.diffusion_model.output_blocks[i]
100
+ injection_holder = InjectionTimestepEmbedSequentialHolder(block=module, idx=i, is_output=True)
101
+ injection_holder.gn_weight = float(w) / float(len(output_block_indices))
102
+ module.injection_holder = injection_holder
103
+ reference_injections.gn_modules.append(module)
104
+ # hack gn_module forwards and update weights
105
+ for i, module in enumerate(reference_injections.gn_modules):
106
+ module.injection_holder.gn_weight *= 2
107
+
108
+ # handle diffusion_model forward injection
109
+ reference_injections.diffusion_model_orig_forward = model.model.diffusion_model.forward
110
+ model.model.diffusion_model.forward = factory_forward_inject_UNetModel(reference_injections).__get__(model.model.diffusion_model, type(model.model.diffusion_model))
111
+ # store ordered ref cns in model's transformer options
112
+ orig_model_options = model.model_options
113
+ new_model_options = model.model_options.copy()
114
+ new_model_options["transformer_options"] = model.model_options["transformer_options"].copy()
115
+ ref_list: list[ReferenceAdvanced] = list(ref_set)
116
+ new_model_options["transformer_options"][REF_CONTROL_LIST_ALL] = sorted(ref_list, key=lambda x: x.order)
117
+ model.model_options = new_model_options
118
+ # continue with original function
119
+ return orig_comfy_sample(model, *args, **kwargs)
120
+ finally:
121
+ # cleanup injections
122
+ # restore attn modules
123
+ attn_modules: list[RefBasicTransformerBlock] = reference_injections.attn_modules
124
+ for module in attn_modules:
125
+ module.injection_holder.restore(module)
126
+ module.injection_holder.clean()
127
+ del module.injection_holder
128
+ del attn_modules
129
+ # restore gn modules
130
+ gn_modules: list[RefTimestepEmbedSequential] = reference_injections.gn_modules
131
+ for module in gn_modules:
132
+ module.injection_holder.restore(module)
133
+ module.injection_holder.clean()
134
+ del module.injection_holder
135
+ del gn_modules
136
+ # restore diffusion_model forward function
137
+ model.model.diffusion_model.forward = reference_injections.diffusion_model_orig_forward.__get__(model.model.diffusion_model, type(model.model.diffusion_model))
138
+ # restore model_options
139
+ model.model_options = orig_model_options
140
+ # cleanup
141
+ reference_injections.cleanup()
142
+ return refcn_sample
143
+ # inject sample functions
144
+ comfy.sample.sample = refcn_sample_factory(comfy.sample.sample)
145
+ comfy.sample.sample_custom = refcn_sample_factory(comfy.sample.sample_custom, is_custom=True)
146
+
147
+
148
+ REF_ATTN_CONTROL_LIST = "ref_attn_control_list"
149
+ REF_ADAIN_CONTROL_LIST = "ref_adain_control_list"
150
+ REF_CONTROL_LIST_ALL = "ref_control_list_all"
151
+ REF_CONTROL_INFO = "ref_control_info"
152
+ REF_ATTN_MACHINE_STATE = "ref_attn_machine_state"
153
+ REF_ADAIN_MACHINE_STATE = "ref_adain_machine_state"
154
+ REF_COND_IDXS = "ref_cond_idxs"
155
+ REF_UNCOND_IDXS = "ref_uncond_idxs"
156
+
157
+
158
+ class MachineState:
159
+ WRITE = "write"
160
+ READ = "read"
161
+ STYLEALIGN = "stylealign"
162
+ OFF = "off"
163
+
164
+
165
+ class ReferenceType:
166
+ ATTN = "reference_attn"
167
+ ADAIN = "reference_adain"
168
+ ATTN_ADAIN = "reference_attn+adain"
169
+ STYLE_ALIGN = "StyleAlign"
170
+
171
+ _LIST = [ATTN, ADAIN, ATTN_ADAIN]
172
+ _LIST_ATTN = [ATTN, ATTN_ADAIN]
173
+ _LIST_ADAIN = [ADAIN, ATTN_ADAIN]
174
+
175
+ @classmethod
176
+ def is_attn(cls, ref_type: str):
177
+ return ref_type in cls._LIST_ATTN
178
+
179
+ @classmethod
180
+ def is_adain(cls, ref_type: str):
181
+ return ref_type in cls._LIST_ADAIN
182
+
183
+
184
+ class ReferenceOptions:
185
+ def __init__(self, reference_type: str,
186
+ attn_style_fidelity: float, adain_style_fidelity: float,
187
+ attn_ref_weight: float, adain_ref_weight: float,
188
+ attn_strength: float=1.0, adain_strength: float=1.0,
189
+ ref_with_other_cns: bool=False):
190
+ self.reference_type = reference_type
191
+ # attn
192
+ self.original_attn_style_fidelity = attn_style_fidelity
193
+ self.attn_style_fidelity = attn_style_fidelity
194
+ self.attn_ref_weight = attn_ref_weight
195
+ self.attn_strength = attn_strength
196
+ # adain
197
+ self.original_adain_style_fidelity = adain_style_fidelity
198
+ self.adain_style_fidelity = adain_style_fidelity
199
+ self.adain_ref_weight = adain_ref_weight
200
+ self.adain_strength = adain_strength
201
+ # other
202
+ self.ref_with_other_cns = ref_with_other_cns
203
+
204
+ def clone(self):
205
+ return ReferenceOptions(reference_type=self.reference_type,
206
+ attn_style_fidelity=self.original_attn_style_fidelity, adain_style_fidelity=self.original_adain_style_fidelity,
207
+ attn_ref_weight=self.attn_ref_weight, adain_ref_weight=self.adain_ref_weight,
208
+ attn_strength=self.attn_strength, adain_strength=self.adain_strength,
209
+ ref_with_other_cns=self.ref_with_other_cns)
210
+
211
+ @staticmethod
212
+ def create_combo(reference_type: str, style_fidelity: float, ref_weight: float, ref_with_other_cns: bool=False):
213
+ return ReferenceOptions(reference_type=reference_type,
214
+ attn_style_fidelity=style_fidelity, adain_style_fidelity=style_fidelity,
215
+ attn_ref_weight=ref_weight, adain_ref_weight=ref_weight,
216
+ ref_with_other_cns=ref_with_other_cns)
217
+
218
+
219
+
220
+ class ReferencePreprocWrapper(AbstractPreprocWrapper):
221
+ error_msg = error_msg = "Invalid use of Reference Preprocess output. The output of RGB SparseCtrl preprocessor is NOT a usual image, but a latent pretending to be an image - you must connect the output directly to an Apply Advanced ControlNet node. It cannot be used for anything else that accepts IMAGE input."
222
+ def __init__(self, condhint: Tensor):
223
+ super().__init__(condhint)
224
+
225
+
226
+ class ReferenceAdvanced(ControlBase, AdvancedControlBase):
227
+ CHANNEL_TO_MULT = {320: 1, 640: 2, 1280: 4}
228
+
229
+ def __init__(self, ref_opts: ReferenceOptions, timestep_keyframes: TimestepKeyframeGroup, device=None):
230
+ super().__init__(device)
231
+ AdvancedControlBase.__init__(self, super(), timestep_keyframes=timestep_keyframes, weights_default=ControlWeights.controllllite())
232
+ self.ref_opts = ref_opts
233
+ self.order = 0
234
+ self.latent_format = None
235
+ self.model_sampling_current = None
236
+ self.should_apply_attn_effective_strength = False
237
+ self.should_apply_adain_effective_strength = False
238
+ self.should_apply_effective_masks = False
239
+ self.latent_shape = None
240
+
241
+ def any_attn_strength_to_apply(self):
242
+ return self.should_apply_attn_effective_strength or self.should_apply_effective_masks
243
+
244
+ def any_adain_strength_to_apply(self):
245
+ return self.should_apply_adain_effective_strength or self.should_apply_effective_masks
246
+
247
+ def get_effective_strength(self):
248
+ effective_strength = self.strength
249
+ if self._current_timestep_keyframe is not None:
250
+ effective_strength = effective_strength * self._current_timestep_keyframe.strength
251
+ return effective_strength
252
+
253
+ def get_effective_attn_mask_or_float(self, x: Tensor, channels: int, is_mid: bool):
254
+ if not self.should_apply_effective_masks:
255
+ return self.get_effective_strength() * self.ref_opts.attn_strength
256
+ if is_mid:
257
+ div = 8
258
+ else:
259
+ div = self.CHANNEL_TO_MULT[channels]
260
+ real_mask = torch.ones([self.latent_shape[0], 1, self.latent_shape[2]//div, self.latent_shape[3]//div]).to(dtype=x.dtype, device=x.device) * self.strength * self.ref_opts.attn_strength
261
+ self.apply_advanced_strengths_and_masks(x=real_mask, batched_number=self.batched_number)
262
+ # mask is now shape [b, 1, h ,w]; need to turn into [b, h*w, 1]
263
+ b, c, h, w = real_mask.shape
264
+ real_mask = real_mask.permute(0, 2, 3, 1).reshape(b, h*w, c)
265
+ return real_mask
266
+
267
+ def get_effective_adain_mask_or_float(self, x: Tensor):
268
+ if not self.should_apply_effective_masks:
269
+ return self.get_effective_strength() * self.ref_opts.adain_strength
270
+ b, c, h, w = x.shape
271
+ real_mask = torch.ones([b, 1, h, w]).to(dtype=x.dtype, device=x.device) * self.strength * self.ref_opts.adain_strength
272
+ self.apply_advanced_strengths_and_masks(x=real_mask, batched_number=self.batched_number)
273
+ return real_mask
274
+
275
+ def should_run(self):
276
+ running = super().should_run()
277
+ if not running:
278
+ return running
279
+ attn_run = False
280
+ adain_run = False
281
+ if ReferenceType.is_attn(self.ref_opts.reference_type):
282
+ # attn will run as long as neither weight or strength is zero
283
+ attn_run = not (math.isclose(self.ref_opts.attn_ref_weight, 0.0) or math.isclose(self.ref_opts.attn_strength, 0.0))
284
+ if ReferenceType.is_adain(self.ref_opts.reference_type):
285
+ # adain will run as long as neither weight or strength is zero
286
+ adain_run = not (math.isclose(self.ref_opts.adain_ref_weight, 0.0) or math.isclose(self.ref_opts.adain_strength, 0.0))
287
+ return attn_run or adain_run
288
+
289
+ def pre_run_advanced(self, model, percent_to_timestep_function):
290
+ AdvancedControlBase.pre_run_advanced(self, model, percent_to_timestep_function)
291
+ if type(self.cond_hint_original) == ReferencePreprocWrapper:
292
+ self.cond_hint_original = self.cond_hint_original.condhint
293
+ self.latent_format = model.latent_format # LatentFormat object, used to process_in latent cond_hint
294
+ self.model_sampling_current = model.model_sampling
295
+ # SDXL is more sensitive to style_fidelity according to sd-webui-controlnet comments
296
+ if type(model).__name__ == "SDXL":
297
+ self.ref_opts.attn_style_fidelity = self.ref_opts.original_attn_style_fidelity ** 3.0
298
+ self.ref_opts.adain_style_fidelity = self.ref_opts.original_adain_style_fidelity ** 3.0
299
+ else:
300
+ self.ref_opts.attn_style_fidelity = self.ref_opts.original_attn_style_fidelity
301
+ self.ref_opts.adain_style_fidelity = self.ref_opts.original_adain_style_fidelity
302
+
303
+ def get_control_advanced(self, x_noisy: Tensor, t, cond, batched_number: int):
304
+ # normal ControlNet stuff
305
+ control_prev = None
306
+ if self.previous_controlnet is not None:
307
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
308
+
309
+ if self.timestep_range is not None:
310
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
311
+ return control_prev
312
+
313
+ dtype = x_noisy.dtype
314
+ # prepare cond_hint - it is a latent, NOT an image
315
+ #if self.sub_idxs is not None or self.cond_hint is None or x_noisy.shape[2] != self.cond_hint.shape[2] or x_noisy.shape[3] != self.cond_hint.shape[3]:
316
+ if self.cond_hint is not None:
317
+ del self.cond_hint
318
+ self.cond_hint = None
319
+ # if self.cond_hint_original length greater or equal to real latent count, subdivide it before scaling
320
+ if self.sub_idxs is not None and self.cond_hint_original.size(0) >= self.full_latent_length:
321
+ self.cond_hint = comfy.utils.common_upscale(
322
+ self.cond_hint_original[self.sub_idxs],
323
+ x_noisy.shape[3], x_noisy.shape[2], 'nearest-exact', "center").to(dtype).to(self.device)
324
+ else:
325
+ self.cond_hint = comfy.utils.common_upscale(
326
+ self.cond_hint_original,
327
+ x_noisy.shape[3], x_noisy.shape[2], 'nearest-exact', "center").to(dtype).to(self.device)
328
+ if x_noisy.shape[0] != self.cond_hint.shape[0]:
329
+ self.cond_hint = broadcast_image_to_extend(self.cond_hint, x_noisy.shape[0], batched_number, except_one=False)
330
+ # noise cond_hint based on sigma (current step)
331
+ self.cond_hint = self.latent_format.process_in(self.cond_hint)
332
+ self.cond_hint = ref_noise_latents(self.cond_hint, sigma=t, noise=None)
333
+ timestep = self.model_sampling_current.timestep(t)
334
+ self.should_apply_attn_effective_strength = not (math.isclose(self.strength, 1.0) and math.isclose(self._current_timestep_keyframe.strength, 1.0) and math.isclose(self.ref_opts.attn_strength, 1.0))
335
+ self.should_apply_adain_effective_strength = not (math.isclose(self.strength, 1.0) and math.isclose(self._current_timestep_keyframe.strength, 1.0) and math.isclose(self.ref_opts.adain_strength, 1.0))
336
+ # prepare mask - use direct_attn, so the mask dims will match source latents (and be smaller)
337
+ self.prepare_mask_cond_hint(x_noisy=x_noisy, t=t, cond=cond, batched_number=batched_number, direct_attn=True)
338
+ self.should_apply_effective_masks = self.latent_keyframes is not None or self.mask_cond_hint is not None or self.tk_mask_cond_hint is not None
339
+ self.latent_shape = list(x_noisy.shape)
340
+ # done preparing; model patches will take care of everything now.
341
+ # return normal controlnet stuff
342
+ return control_prev
343
+
344
+ def cleanup_advanced(self):
345
+ super().cleanup_advanced()
346
+ del self.latent_format
347
+ self.latent_format = None
348
+ del self.model_sampling_current
349
+ self.model_sampling_current = None
350
+ self.should_apply_attn_effective_strength = False
351
+ self.should_apply_adain_effective_strength = False
352
+ self.should_apply_effective_masks = False
353
+
354
+ def copy(self):
355
+ c = ReferenceAdvanced(self.ref_opts, self.timestep_keyframes)
356
+ c.order = self.order
357
+ self.copy_to(c)
358
+ self.copy_to_advanced(c)
359
+ return c
360
+
361
+ # avoid deepcopy shenanigans by making deepcopy not do anything to the reference
362
+ # TODO: do the bookkeeping to do this in a proper way for all Adv-ControlNets
363
+ def __deepcopy__(self, memo):
364
+ return self
365
+
366
+
367
+ def ref_noise_latents(latents: Tensor, sigma: Tensor, noise: Tensor=None):
368
+ sigma = sigma.unsqueeze(-1).unsqueeze(-1).unsqueeze(-1)
369
+ alpha_cumprod = 1 / ((sigma * sigma) + 1)
370
+ sqrt_alpha_prod = alpha_cumprod ** 0.5
371
+ sqrt_one_minus_alpha_prod = (1. - alpha_cumprod) ** 0.5
372
+ if noise is None:
373
+ # generator = torch.Generator(device="cuda")
374
+ # generator.manual_seed(0)
375
+ # noise = torch.empty_like(latents).normal_(generator=generator)
376
+ # generator = torch.Generator()
377
+ # generator.manual_seed(0)
378
+ # noise = torch.randn(latents.size(), generator=generator).to(latents.device)
379
+ noise = torch.randn_like(latents).to(latents.device)
380
+ return sqrt_alpha_prod * latents + sqrt_one_minus_alpha_prod * noise
381
+
382
+
383
+ def simple_noise_latents(latents: Tensor, sigma: float, noise: Tensor=None):
384
+ if noise is None:
385
+ noise = torch.rand_like(latents)
386
+ return latents + noise * sigma
387
+
388
+
389
+ class BankStylesBasicTransformerBlock:
390
+ def __init__(self):
391
+ self.bank = []
392
+ self.style_cfgs = []
393
+ self.cn_idx: list[int] = []
394
+
395
+ def get_avg_style_fidelity(self):
396
+ return sum(self.style_cfgs) / float(len(self.style_cfgs))
397
+
398
+ def clean(self):
399
+ del self.bank
400
+ self.bank = []
401
+ del self.style_cfgs
402
+ self.style_cfgs = []
403
+ del self.cn_idx
404
+ self.cn_idx = []
405
+
406
+
407
+ class BankStylesTimestepEmbedSequential:
408
+ def __init__(self):
409
+ self.var_bank = []
410
+ self.mean_bank = []
411
+ self.style_cfgs = []
412
+ self.cn_idx: list[int] = []
413
+
414
+ def get_avg_var_bank(self):
415
+ return sum(self.var_bank) / float(len(self.var_bank))
416
+
417
+ def get_avg_mean_bank(self):
418
+ return sum(self.mean_bank) / float(len(self.mean_bank))
419
+
420
+ def get_avg_style_fidelity(self):
421
+ return sum(self.style_cfgs) / float(len(self.style_cfgs))
422
+
423
+ def clean(self):
424
+ del self.mean_bank
425
+ self.mean_bank = []
426
+ del self.var_bank
427
+ self.var_bank = []
428
+ del self.style_cfgs
429
+ self.style_cfgs = []
430
+ del self.cn_idx
431
+ self.cn_idx = []
432
+
433
+
434
+ class InjectionBasicTransformerBlockHolder:
435
+ def __init__(self, block: BasicTransformerBlock, idx=None):
436
+ if hasattr(block, "_forward"): # backward compatibility
437
+ self.original_forward = block._forward
438
+ else:
439
+ self.original_forward = block.forward
440
+ self.idx = idx
441
+ self.attn_weight = 1.0
442
+ self.is_middle = False
443
+ self.bank_styles = BankStylesBasicTransformerBlock()
444
+
445
+ def restore(self, block: BasicTransformerBlock):
446
+ if hasattr(block, "_forward"): # backward compatibility
447
+ block._forward = self.original_forward
448
+ else:
449
+ block.forward = self.original_forward
450
+
451
+ def clean(self):
452
+ self.bank_styles.clean()
453
+
454
+
455
+ class InjectionTimestepEmbedSequentialHolder:
456
+ def __init__(self, block: openaimodel.TimestepEmbedSequential, idx=None, is_middle=False, is_input=False, is_output=False):
457
+ self.original_forward = block.forward
458
+ self.idx = idx
459
+ self.gn_weight = 1.0
460
+ self.is_middle = is_middle
461
+ self.is_input = is_input
462
+ self.is_output = is_output
463
+ self.bank_styles = BankStylesTimestepEmbedSequential()
464
+
465
+ def restore(self, block: openaimodel.TimestepEmbedSequential):
466
+ block.forward = self.original_forward
467
+
468
+ def clean(self):
469
+ self.bank_styles.clean()
470
+
471
+
472
+ class ReferenceInjections:
473
+ def __init__(self, attn_modules: list['RefBasicTransformerBlock']=None, gn_modules: list['RefTimestepEmbedSequential']=None):
474
+ self.attn_modules = attn_modules if attn_modules else []
475
+ self.gn_modules = gn_modules if gn_modules else []
476
+ self.diffusion_model_orig_forward: Callable = None
477
+
478
+ def clean_module_mem(self):
479
+ for attn_module in self.attn_modules:
480
+ try:
481
+ attn_module.injection_holder.clean()
482
+ except Exception:
483
+ pass
484
+ for gn_module in self.gn_modules:
485
+ try:
486
+ gn_module.injection_holder.clean()
487
+ except Exception:
488
+ pass
489
+
490
+ def cleanup(self):
491
+ self.clean_module_mem()
492
+ del self.attn_modules
493
+ self.attn_modules = []
494
+ del self.gn_modules
495
+ self.gn_modules = []
496
+ self.diffusion_model_orig_forward = None
497
+
498
+
499
+ def factory_forward_inject_UNetModel(reference_injections: ReferenceInjections):
500
+ def forward_inject_UNetModel(self, x: Tensor, *args, **kwargs):
501
+ # get control and transformer_options from kwargs
502
+ real_args = list(args)
503
+ real_kwargs = list(kwargs.keys())
504
+ control = kwargs.get("control", None)
505
+ transformer_options = kwargs.get("transformer_options", None)
506
+ # look for ReferenceAttnPatch objects to get ReferenceAdvanced objects
507
+ ref_controlnets: list[ReferenceAdvanced] = transformer_options[REF_CONTROL_LIST_ALL]
508
+ # discard any controlnets that should not run
509
+ ref_controlnets = [x for x in ref_controlnets if x.should_run()]
510
+ # if nothing related to reference controlnets, do nothing special
511
+ if len(ref_controlnets) == 0:
512
+ return reference_injections.diffusion_model_orig_forward(x, *args, **kwargs)
513
+ try:
514
+ # assign cond and uncond idxs
515
+ batched_number = len(transformer_options["cond_or_uncond"])
516
+ per_batch = x.shape[0] // batched_number
517
+ indiv_conds = []
518
+ for cond_type in transformer_options["cond_or_uncond"]:
519
+ indiv_conds.extend([cond_type] * per_batch)
520
+ transformer_options[REF_UNCOND_IDXS] = [i for i, x in enumerate(indiv_conds) if x == 1]
521
+ transformer_options[REF_COND_IDXS] = [i for i, x in enumerate(indiv_conds) if x == 0]
522
+ # check which controlnets do which thing
523
+ attn_controlnets = []
524
+ adain_controlnets = []
525
+ for control in ref_controlnets:
526
+ if ReferenceType.is_attn(control.ref_opts.reference_type):
527
+ attn_controlnets.append(control)
528
+ if ReferenceType.is_adain(control.ref_opts.reference_type):
529
+ adain_controlnets.append(control)
530
+ if len(adain_controlnets) > 0:
531
+ # ComfyUI uses forward_timestep_embed with the TimestepEmbedSequential passed into it
532
+ orig_forward_timestep_embed = openaimodel.forward_timestep_embed
533
+ openaimodel.forward_timestep_embed = forward_timestep_embed_ref_inject_factory(orig_forward_timestep_embed)
534
+ # handle running diffusion with ref cond hints
535
+ for control in ref_controlnets:
536
+ if ReferenceType.is_attn(control.ref_opts.reference_type):
537
+ transformer_options[REF_ATTN_MACHINE_STATE] = MachineState.WRITE
538
+ else:
539
+ transformer_options[REF_ATTN_MACHINE_STATE] = MachineState.OFF
540
+ if ReferenceType.is_adain(control.ref_opts.reference_type):
541
+ transformer_options[REF_ADAIN_MACHINE_STATE] = MachineState.WRITE
542
+ else:
543
+ transformer_options[REF_ADAIN_MACHINE_STATE] = MachineState.OFF
544
+ transformer_options[REF_ATTN_CONTROL_LIST] = [control]
545
+ transformer_options[REF_ADAIN_CONTROL_LIST] = [control]
546
+
547
+ orig_kwargs = kwargs
548
+ if not control.ref_opts.ref_with_other_cns:
549
+ kwargs = kwargs.copy()
550
+ kwargs["control"] = None
551
+ reference_injections.diffusion_model_orig_forward(control.cond_hint.to(dtype=x.dtype).to(device=x.device), *args, **kwargs)
552
+ kwargs = orig_kwargs
553
+ # run diffusion for real now
554
+ transformer_options[REF_ATTN_MACHINE_STATE] = MachineState.READ
555
+ transformer_options[REF_ADAIN_MACHINE_STATE] = MachineState.READ
556
+ transformer_options[REF_ATTN_CONTROL_LIST] = attn_controlnets
557
+ transformer_options[REF_ADAIN_CONTROL_LIST] = adain_controlnets
558
+ return reference_injections.diffusion_model_orig_forward(x, *args, **kwargs)
559
+ finally:
560
+ # make sure banks are cleared no matter what happens - otherwise, RIP VRAM
561
+ reference_injections.clean_module_mem()
562
+ if len(adain_controlnets) > 0:
563
+ openaimodel.forward_timestep_embed = orig_forward_timestep_embed
564
+
565
+ return forward_inject_UNetModel
566
+
567
+
568
+ # dummy class just to help IDE keep track of injected variables
569
+ class RefBasicTransformerBlock(BasicTransformerBlock):
570
+ injection_holder: InjectionBasicTransformerBlockHolder = None
571
+
572
+ def _forward_inject_BasicTransformerBlock(self: RefBasicTransformerBlock, x: Tensor, context: Tensor=None, transformer_options: dict[str]={}):
573
+ extra_options = {}
574
+ block = transformer_options.get("block", None)
575
+ block_index = transformer_options.get("block_index", 0)
576
+ transformer_patches = {}
577
+ transformer_patches_replace = {}
578
+
579
+ for k in transformer_options:
580
+ if k == "patches":
581
+ transformer_patches = transformer_options[k]
582
+ elif k == "patches_replace":
583
+ transformer_patches_replace = transformer_options[k]
584
+ else:
585
+ extra_options[k] = transformer_options[k]
586
+
587
+ extra_options["n_heads"] = self.n_heads
588
+ extra_options["dim_head"] = self.d_head
589
+
590
+ if self.ff_in:
591
+ x_skip = x
592
+ x = self.ff_in(self.norm_in(x))
593
+ if self.is_res:
594
+ x += x_skip
595
+
596
+ n: Tensor = self.norm1(x)
597
+ if self.disable_self_attn:
598
+ context_attn1 = context
599
+ else:
600
+ context_attn1 = None
601
+ value_attn1 = None
602
+
603
+ # Reference CN stuff
604
+ uc_idx_mask = transformer_options.get(REF_UNCOND_IDXS, [])
605
+ c_idx_mask = transformer_options.get(REF_COND_IDXS, [])
606
+ # WRITE mode will only have one ReferenceAdvanced, other modes will have all ReferenceAdvanced
607
+ ref_controlnets: list[ReferenceAdvanced] = transformer_options.get(REF_ATTN_CONTROL_LIST, None)
608
+ ref_machine_state: str = transformer_options.get(REF_ATTN_MACHINE_STATE, None)
609
+ # if in WRITE mode, save n and style_fidelity
610
+ if ref_controlnets and ref_machine_state == MachineState.WRITE:
611
+ if ref_controlnets[0].ref_opts.attn_ref_weight > self.injection_holder.attn_weight:
612
+ self.injection_holder.bank_styles.bank.append(n.detach().clone())
613
+ self.injection_holder.bank_styles.style_cfgs.append(ref_controlnets[0].ref_opts.attn_style_fidelity)
614
+ self.injection_holder.bank_styles.cn_idx.append(ref_controlnets[0].order)
615
+
616
+ if "attn1_patch" in transformer_patches:
617
+ patch = transformer_patches["attn1_patch"]
618
+ if context_attn1 is None:
619
+ context_attn1 = n
620
+ value_attn1 = context_attn1
621
+ for p in patch:
622
+ n, context_attn1, value_attn1 = p(n, context_attn1, value_attn1, extra_options)
623
+
624
+ if block is not None:
625
+ transformer_block = (block[0], block[1], block_index)
626
+ else:
627
+ transformer_block = None
628
+ attn1_replace_patch = transformer_patches_replace.get("attn1", {})
629
+ block_attn1 = transformer_block
630
+ if block_attn1 not in attn1_replace_patch:
631
+ block_attn1 = block
632
+
633
+ if block_attn1 in attn1_replace_patch:
634
+ if context_attn1 is None:
635
+ context_attn1 = n
636
+ value_attn1 = n
637
+ n = self.attn1.to_q(n)
638
+ # Reference CN READ - use attn1_replace_patch appropriately
639
+ if ref_machine_state == MachineState.READ and len(self.injection_holder.bank_styles.bank) > 0:
640
+ bank_styles = self.injection_holder.bank_styles
641
+ style_fidelity = bank_styles.get_avg_style_fidelity()
642
+ real_bank = bank_styles.bank.copy()
643
+ cn_idx = 0
644
+ for idx, order in enumerate(bank_styles.cn_idx):
645
+ # make sure matching ref cn is selected
646
+ for i in range(cn_idx, len(ref_controlnets)):
647
+ if ref_controlnets[i].order == order:
648
+ cn_idx = i
649
+ break
650
+ assert order == ref_controlnets[cn_idx].order
651
+ if ref_controlnets[cn_idx].any_attn_strength_to_apply():
652
+ effective_strength = ref_controlnets[cn_idx].get_effective_attn_mask_or_float(x=n, channels=n.shape[2], is_mid=self.injection_holder.is_middle)
653
+ real_bank[idx] = real_bank[idx] * effective_strength + context_attn1 * (1-effective_strength)
654
+ n_uc = self.attn1.to_out(attn1_replace_patch[block_attn1](
655
+ n,
656
+ self.attn1.to_k(torch.cat([context_attn1] + real_bank, dim=1)),
657
+ self.attn1.to_v(torch.cat([value_attn1] + real_bank, dim=1)),
658
+ extra_options))
659
+ n_c = n_uc.clone()
660
+ if len(uc_idx_mask) > 0 and not math.isclose(style_fidelity, 0.0):
661
+ n_c[uc_idx_mask] = self.attn1.to_out(attn1_replace_patch[block_attn1](
662
+ n[uc_idx_mask],
663
+ self.attn1.to_k(context_attn1[uc_idx_mask]),
664
+ self.attn1.to_v(value_attn1[uc_idx_mask]),
665
+ extra_options))
666
+ n = style_fidelity * n_c + (1.0-style_fidelity) * n_uc
667
+ bank_styles.clean()
668
+ else:
669
+ context_attn1 = self.attn1.to_k(context_attn1)
670
+ value_attn1 = self.attn1.to_v(value_attn1)
671
+ n = attn1_replace_patch[block_attn1](n, context_attn1, value_attn1, extra_options)
672
+ n = self.attn1.to_out(n)
673
+ else:
674
+ # Reference CN READ - no attn1_replace_patch
675
+ if ref_machine_state == MachineState.READ and len(self.injection_holder.bank_styles.bank) > 0:
676
+ if context_attn1 is None:
677
+ context_attn1 = n
678
+ bank_styles = self.injection_holder.bank_styles
679
+ style_fidelity = bank_styles.get_avg_style_fidelity()
680
+ real_bank = bank_styles.bank.copy()
681
+ cn_idx = 0
682
+ for idx, order in enumerate(bank_styles.cn_idx):
683
+ # make sure matching ref cn is selected
684
+ for i in range(cn_idx, len(ref_controlnets)):
685
+ if ref_controlnets[i].order == order:
686
+ cn_idx = i
687
+ break
688
+ assert order == ref_controlnets[cn_idx].order
689
+ if ref_controlnets[cn_idx].any_attn_strength_to_apply():
690
+ effective_strength = ref_controlnets[cn_idx].get_effective_attn_mask_or_float(x=n, channels=n.shape[2], is_mid=self.injection_holder.is_middle)
691
+ real_bank[idx] = real_bank[idx] * effective_strength + context_attn1 * (1-effective_strength)
692
+ n_uc: Tensor = self.attn1(
693
+ n,
694
+ context=torch.cat([context_attn1] + real_bank, dim=1),
695
+ value=torch.cat([value_attn1] + real_bank, dim=1) if value_attn1 is not None else value_attn1)
696
+ n_c = n_uc.clone()
697
+ if len(uc_idx_mask) > 0 and not math.isclose(style_fidelity, 0.0):
698
+ n_c[uc_idx_mask] = self.attn1(
699
+ n[uc_idx_mask],
700
+ context=context_attn1[uc_idx_mask],
701
+ value=value_attn1[uc_idx_mask] if value_attn1 is not None else value_attn1)
702
+ n = style_fidelity * n_c + (1.0-style_fidelity) * n_uc
703
+ bank_styles.clean()
704
+ else:
705
+ n = self.attn1(n, context=context_attn1, value=value_attn1)
706
+
707
+ if "attn1_output_patch" in transformer_patches:
708
+ patch = transformer_patches["attn1_output_patch"]
709
+ for p in patch:
710
+ n = p(n, extra_options)
711
+
712
+ x += n
713
+ if "middle_patch" in transformer_patches:
714
+ patch = transformer_patches["middle_patch"]
715
+ for p in patch:
716
+ x = p(x, extra_options)
717
+
718
+ if self.attn2 is not None:
719
+ n = self.norm2(x)
720
+ if self.switch_temporal_ca_to_sa:
721
+ context_attn2 = n
722
+ else:
723
+ context_attn2 = context
724
+ value_attn2 = None
725
+ if "attn2_patch" in transformer_patches:
726
+ patch = transformer_patches["attn2_patch"]
727
+ value_attn2 = context_attn2
728
+ for p in patch:
729
+ n, context_attn2, value_attn2 = p(n, context_attn2, value_attn2, extra_options)
730
+
731
+ attn2_replace_patch = transformer_patches_replace.get("attn2", {})
732
+ block_attn2 = transformer_block
733
+ if block_attn2 not in attn2_replace_patch:
734
+ block_attn2 = block
735
+
736
+ if block_attn2 in attn2_replace_patch:
737
+ if value_attn2 is None:
738
+ value_attn2 = context_attn2
739
+ n = self.attn2.to_q(n)
740
+ context_attn2 = self.attn2.to_k(context_attn2)
741
+ value_attn2 = self.attn2.to_v(value_attn2)
742
+ n = attn2_replace_patch[block_attn2](n, context_attn2, value_attn2, extra_options)
743
+ n = self.attn2.to_out(n)
744
+ else:
745
+ n = self.attn2(n, context=context_attn2, value=value_attn2)
746
+
747
+ if "attn2_output_patch" in transformer_patches:
748
+ patch = transformer_patches["attn2_output_patch"]
749
+ for p in patch:
750
+ n = p(n, extra_options)
751
+
752
+ x += n
753
+ if self.is_res:
754
+ x_skip = x
755
+ x = self.ff(self.norm3(x))
756
+ if self.is_res:
757
+ x += x_skip
758
+
759
+ return x
760
+
761
+
762
+ class RefTimestepEmbedSequential(openaimodel.TimestepEmbedSequential):
763
+ injection_holder: InjectionTimestepEmbedSequentialHolder = None
764
+
765
+ def forward_timestep_embed_ref_inject_factory(orig_timestep_embed_inject_factory: Callable):
766
+ def forward_timestep_embed_ref_inject(*args, **kwargs):
767
+ ts: RefTimestepEmbedSequential = args[0]
768
+ if not hasattr(ts, "injection_holder"):
769
+ return orig_timestep_embed_inject_factory(*args, **kwargs)
770
+ eps = 1e-6
771
+ x: Tensor = orig_timestep_embed_inject_factory(*args, **kwargs)
772
+ y: Tensor = None
773
+ transformer_options: dict[str] = args[4]
774
+ # Reference CN stuff
775
+ uc_idx_mask = transformer_options.get(REF_UNCOND_IDXS, [])
776
+ c_idx_mask = transformer_options.get(REF_COND_IDXS, [])
777
+ # WRITE mode will only have one ReferenceAdvanced, other modes will have all ReferenceAdvanced
778
+ ref_controlnets: list[ReferenceAdvanced] = transformer_options.get(REF_ADAIN_CONTROL_LIST, None)
779
+ ref_machine_state: str = transformer_options.get(REF_ADAIN_MACHINE_STATE, None)
780
+
781
+ # if in WRITE mode, save var, mean, and style_cfg
782
+ if ref_machine_state == MachineState.WRITE:
783
+ if ref_controlnets[0].ref_opts.adain_ref_weight > ts.injection_holder.gn_weight:
784
+ var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)
785
+ ts.injection_holder.bank_styles.var_bank.append(var)
786
+ ts.injection_holder.bank_styles.mean_bank.append(mean)
787
+ ts.injection_holder.bank_styles.style_cfgs.append(ref_controlnets[0].ref_opts.adain_style_fidelity)
788
+ ts.injection_holder.bank_styles.cn_idx.append(ref_controlnets[0].order)
789
+ # if in READ mode, do math with saved var, mean, and style_cfg
790
+ if ref_machine_state == MachineState.READ:
791
+ if len(ts.injection_holder.bank_styles.var_bank) > 0:
792
+ bank_styles = ts.injection_holder.bank_styles
793
+ var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)
794
+ std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
795
+ y_uc = torch.zeros_like(x)
796
+ cn_idx = 0
797
+ for idx, order in enumerate(bank_styles.cn_idx):
798
+ # make sure matching ref cn is selected
799
+ for i in range(cn_idx, len(ref_controlnets)):
800
+ if ref_controlnets[i].order == order:
801
+ cn_idx = i
802
+ break
803
+ assert order == ref_controlnets[cn_idx].order
804
+ style_fidelity = bank_styles.style_cfgs[idx]
805
+ var_acc = bank_styles.var_bank[idx]
806
+ mean_acc = bank_styles.mean_bank[idx]
807
+ std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
808
+ sub_y_uc = (((x - mean) / std) * std_acc) + mean_acc
809
+ if ref_controlnets[cn_idx].any_adain_strength_to_apply():
810
+ effective_strength = ref_controlnets[cn_idx].get_effective_adain_mask_or_float(x=x)
811
+ sub_y_uc = sub_y_uc * effective_strength + x * (1-effective_strength)
812
+ y_uc += sub_y_uc
813
+ # get average, if more than one
814
+ if len(bank_styles.cn_idx) > 1:
815
+ y_uc /= len(bank_styles.cn_idx)
816
+ y_c = y_uc.clone()
817
+ if len(uc_idx_mask) > 0 and not math.isclose(style_fidelity, 0.0):
818
+ y_c[uc_idx_mask] = x.to(y_c.dtype)[uc_idx_mask]
819
+ y = style_fidelity * y_c + (1.0 - style_fidelity) * y_uc
820
+ ts.injection_holder.bank_styles.clean()
821
+
822
+ if y is None:
823
+ y = x
824
+ return y.to(x.dtype)
825
+
826
+ return forward_timestep_embed_ref_inject
827
+
828
+ # DFS Search for Torch.nn.Module, Written by Lvmin
829
+ def torch_dfs(model: torch.nn.Module):
830
+ result = [model]
831
+ for child in model.children():
832
+ result += torch_dfs(child)
833
+ return result
ComfyUI-Advanced-ControlNet/adv_control/control_sparsectrl.py ADDED
@@ -0,0 +1,1081 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #taken from: https://github.com/lllyasviel/ControlNet
2
+ #and modified
3
+ #and then taken from comfy/cldm/cldm.py and modified again
4
+
5
+ from abc import ABC, abstractmethod
6
+ import copy
7
+ import math
8
+ import numpy as np
9
+ from typing import Iterable, Union
10
+ import torch
11
+ import torch as th
12
+ import torch.nn as nn
13
+ from torch import Tensor
14
+ from einops import rearrange, repeat
15
+
16
+ from comfy.ldm.modules.diffusionmodules.util import (
17
+ zero_module,
18
+ timestep_embedding,
19
+ )
20
+
21
+ from comfy.cli_args import args
22
+ from comfy.cldm.cldm import ControlNet as ControlNetCLDM
23
+ from comfy.ldm.modules.attention import SpatialTransformer
24
+ from comfy.ldm.modules.attention import attention_basic, attention_pytorch, attention_split, attention_sub_quad, default
25
+ from comfy.ldm.modules.attention import FeedForward, SpatialTransformer
26
+ from comfy.ldm.modules.diffusionmodules.openaimodel import TimestepEmbedSequential, ResBlock, Downsample
27
+ from comfy.model_patcher import ModelPatcher
28
+ import comfy.ops
29
+ import comfy.model_management
30
+
31
+ from .logger import logger
32
+ from .utils import (BIGMAX, TimestepKeyframeGroup, disable_weight_init_clean_groupnorm,
33
+ prepare_mask_batch, broadcast_image_to_extend, extend_to_batch_size)
34
+
35
+
36
+ # until xformers bug is fixed, do not use xformers for VersatileAttention! TODO: change this when fix is out
37
+ # logic for choosing optimized_attention method taken from comfy/ldm/modules/attention.py
38
+ # a fallback_attention_mm is selected to avoid CUDA configuration limitation with pytorch's scaled_dot_product
39
+ optimized_attention_mm = attention_basic
40
+ fallback_attention_mm = attention_basic
41
+ if comfy.model_management.xformers_enabled():
42
+ pass
43
+ #optimized_attention_mm = attention_xformers
44
+ if comfy.model_management.pytorch_attention_enabled():
45
+ optimized_attention_mm = attention_pytorch
46
+ if args.use_split_cross_attention:
47
+ fallback_attention_mm = attention_split
48
+ else:
49
+ fallback_attention_mm = attention_sub_quad
50
+ else:
51
+ if args.use_split_cross_attention:
52
+ optimized_attention_mm = attention_split
53
+ else:
54
+ optimized_attention_mm = attention_sub_quad
55
+
56
+
57
+ class SparseConst:
58
+ HINT_MULT = "sparse_hint_mult"
59
+ NONHINT_MULT = "sparse_nonhint_mult"
60
+ MASK_MULT = "sparse_mask_mult"
61
+
62
+
63
+ class SparseControlNet(ControlNetCLDM):
64
+ def __init__(self, *args,**kwargs):
65
+ super().__init__(*args, **kwargs)
66
+ hint_channels = kwargs.get("hint_channels")
67
+ operations: disable_weight_init_clean_groupnorm = kwargs.get("operations", disable_weight_init_clean_groupnorm)
68
+ device = kwargs.get("device", None)
69
+ self.use_simplified_conditioning_embedding = kwargs.get("use_simplified_conditioning_embedding", False)
70
+ if self.use_simplified_conditioning_embedding:
71
+ self.input_hint_block = TimestepEmbedSequential(
72
+ zero_module(operations.conv_nd(self.dims, hint_channels, self.model_channels, 3, padding=1, dtype=self.dtype, device=device)),
73
+ )
74
+ self.motion_wrapper: SparseCtrlMotionWrapper = None
75
+
76
+ def set_actual_length(self, actual_length: int, full_length: int):
77
+ if self.motion_wrapper is not None:
78
+ self.motion_wrapper.set_video_length(video_length=actual_length, full_length=full_length)
79
+
80
+ def forward(self, x: Tensor, hint: Tensor, timesteps, context, y=None, **kwargs):
81
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
82
+ emb = self.time_embed(t_emb)
83
+
84
+ # SparseCtrl sets noisy input to zeros
85
+ x = torch.zeros_like(x)
86
+ guided_hint = self.input_hint_block(hint, emb, context)
87
+
88
+ outs = []
89
+
90
+ hs = []
91
+ if self.num_classes is not None:
92
+ assert y.shape[0] == x.shape[0]
93
+ emb = emb + self.label_emb(y)
94
+
95
+ h = x
96
+ for module, zero_conv in zip(self.input_blocks, self.zero_convs):
97
+ if guided_hint is not None:
98
+ h = module(h, emb, context)
99
+ h += guided_hint
100
+ guided_hint = None
101
+ else:
102
+ h = module(h, emb, context)
103
+ outs.append(zero_conv(h, emb, context))
104
+
105
+ h = self.middle_block(h, emb, context)
106
+ outs.append(self.middle_block_out(h, emb, context))
107
+
108
+ return outs
109
+
110
+
111
+ class SparseModelPatcher(ModelPatcher):
112
+ def __init__(self, *args, **kwargs):
113
+ self.model: SparseControlNet
114
+ super().__init__(*args, **kwargs)
115
+
116
+ def patch_model_lowvram(self, device_to=None, *args, **kwargs):
117
+ patched_model = super().patch_model_lowvram(device_to, *args, **kwargs)
118
+
119
+ if self.model.motion_wrapper is not None:
120
+ # figure out the tensors (likely pe's) that should be cast to device besides just the named_modules
121
+ remaining_tensors = list(self.model.motion_wrapper.state_dict().keys())
122
+ named_modules = []
123
+ for n, _ in self.model.motion_wrapper.named_modules():
124
+ named_modules.append(n)
125
+ named_modules.append(f"{n}.weight")
126
+ named_modules.append(f"{n}.bias")
127
+ for name in named_modules:
128
+ if name in remaining_tensors:
129
+ remaining_tensors.remove(name)
130
+
131
+ for key in remaining_tensors:
132
+ self.patch_weight_to_device(key, device_to)
133
+ if device_to is not None:
134
+ comfy.utils.set_attr(self.model.motion_wrapper, key, comfy.utils.get_attr(self.model.motion_wrapper, key).to(device_to))
135
+
136
+ return patched_model
137
+
138
+ def clone(self):
139
+ # normal ModelPatcher clone actions
140
+ n = SparseModelPatcher(self.model, self.load_device, self.offload_device, self.size, self.current_device, weight_inplace_update=self.weight_inplace_update)
141
+ n.patches = {}
142
+ for k in self.patches:
143
+ n.patches[k] = self.patches[k][:]
144
+ if hasattr(n, "patches_uuid"):
145
+ self.patches_uuid = n.patches_uuid
146
+
147
+ n.object_patches = self.object_patches.copy()
148
+ n.model_options = copy.deepcopy(self.model_options)
149
+ if hasattr(n, "model_keys"):
150
+ n.model_keys = self.model_keys
151
+ if hasattr(n, "backup"):
152
+ self.backup = n.backup
153
+ if hasattr(n, "object_patches_backup"):
154
+ self.object_patches_backup = n.object_patches_backup
155
+
156
+
157
+ class PreprocSparseRGBWrapper:
158
+ error_msg = "Invalid use of RGB SparseCtrl output. The output of RGB SparseCtrl preprocessor is NOT a usual image, but a latent pretending to be an image - you must connect the output directly to an Apply ControlNet node (advanced or otherwise). It cannot be used for anything else that accepts IMAGE input."
159
+ def __init__(self, condhint: Tensor):
160
+ self.condhint = condhint
161
+
162
+ def movedim(self, *args, **kwargs):
163
+ return self
164
+
165
+ def __getattr__(self, *args, **kwargs):
166
+ raise AttributeError(self.error_msg)
167
+
168
+ def __setattr__(self, name, value):
169
+ if name != "condhint":
170
+ raise AttributeError(self.error_msg)
171
+ super().__setattr__(name, value)
172
+
173
+ def __iter__(self, *args, **kwargs):
174
+ raise AttributeError(self.error_msg)
175
+
176
+ def __next__(self, *args, **kwargs):
177
+ raise AttributeError(self.error_msg)
178
+
179
+ def __len__(self, *args, **kwargs):
180
+ raise AttributeError(self.error_msg)
181
+
182
+ def __getitem__(self, *args, **kwargs):
183
+ raise AttributeError(self.error_msg)
184
+
185
+ def __setitem__(self, *args, **kwargs):
186
+ raise AttributeError(self.error_msg)
187
+
188
+
189
+ class SparseContextAware:
190
+ NEAREST_HINT = "nearest_hint"
191
+ OFF = "off"
192
+
193
+ LIST = [NEAREST_HINT, OFF]
194
+
195
+
196
+ class SparseSettings:
197
+ def __init__(self, sparse_method: 'SparseMethod', use_motion: bool=True, motion_strength=1.0, motion_scale=1.0, merged=False,
198
+ sparse_mask_mult=1.0, sparse_hint_mult=1.0, sparse_nonhint_mult=1.0, context_aware=SparseContextAware.NEAREST_HINT):
199
+ # account for Steerable-Motion workflow incompatibility;
200
+ # doing this to for my own peace of mind (not an issue with my code)
201
+ if type(sparse_method) == str:
202
+ logger.warn("Outdated Steerable-Motion workflow detected; attempting to auto-convert indexes input. If you experience an error here, consult Steerable-Motion github, NOT Advanced-ControlNet.")
203
+ sparse_method = SparseIndexMethod(get_idx_list_from_str(sparse_method))
204
+ self.sparse_method = sparse_method
205
+ self.use_motion = use_motion
206
+ self.motion_strength = motion_strength
207
+ self.motion_scale = motion_scale
208
+ self.merged = merged
209
+ self.sparse_mask_mult = float(sparse_mask_mult)
210
+ self.sparse_hint_mult = float(sparse_hint_mult)
211
+ self.sparse_nonhint_mult = float(sparse_nonhint_mult)
212
+ self.context_aware = context_aware
213
+
214
+ def is_context_aware(self):
215
+ return self.context_aware != SparseContextAware.OFF
216
+
217
+ @classmethod
218
+ def default(cls):
219
+ return SparseSettings(sparse_method=SparseSpreadMethod(), use_motion=True)
220
+
221
+
222
+ class SparseMethod(ABC):
223
+ SPREAD = "spread"
224
+ INDEX = "index"
225
+ def __init__(self, method: str):
226
+ self.method = method
227
+
228
+ @abstractmethod
229
+ def _get_indexes(self, hint_length: int, full_length: int) -> list[int]:
230
+ pass
231
+
232
+ def get_indexes(self, hint_length: int, full_length: int, sub_idxs: list[int]=None) -> tuple[list[int], list[int]]:
233
+ returned_idxs = self._get_indexes(hint_length, full_length)
234
+ if sub_idxs is None:
235
+ return returned_idxs, None
236
+ # need to map full indexes to condhint indexes
237
+ index_mapping = {}
238
+ for i, value in enumerate(returned_idxs):
239
+ index_mapping[value] = i
240
+ def get_mapped_idxs(idxs: list[int]):
241
+ return [index_mapping[idx] for idx in idxs]
242
+ # check if returned_idxs fit within subidxs
243
+ fitting_idxs = []
244
+ for sub_idx in sub_idxs:
245
+ if sub_idx in returned_idxs:
246
+ fitting_idxs.append(sub_idx)
247
+ # if have any fitting_idxs, deal with it
248
+ if len(fitting_idxs) > 0:
249
+ return fitting_idxs, get_mapped_idxs(fitting_idxs)
250
+
251
+ # since no returned_idxs fit in sub_idxs, need to get the next-closest hint images based on strategy
252
+ def get_closest_idx(target_idx: int, idxs: list[int]):
253
+ min_idx = -1
254
+ min_dist = BIGMAX
255
+ for idx in idxs:
256
+ new_dist = abs(idx-target_idx)
257
+ if new_dist < min_dist:
258
+ min_idx = idx
259
+ min_dist = new_dist
260
+ if min_dist == 1:
261
+ return min_idx, min_dist
262
+ return min_idx, min_dist
263
+ start_closest_idx, start_dist = get_closest_idx(sub_idxs[0], returned_idxs)
264
+ end_closest_idx, end_dist = get_closest_idx(sub_idxs[-1], returned_idxs)
265
+ # if only one cond hint exists, do special behavior
266
+ if hint_length == 1:
267
+ # if same distance from start and end,
268
+ if start_dist == end_dist:
269
+ # find center index of sub_idxs
270
+ center_idx = sub_idxs[np.linspace(0, len(sub_idxs)-1, 3, endpoint=True, dtype=int)[1]]
271
+ return [center_idx], get_mapped_idxs([start_closest_idx])
272
+ # otherwise, return closest
273
+ if start_dist < end_dist:
274
+ return [sub_idxs[0]], get_mapped_idxs([start_closest_idx])
275
+ return [sub_idxs[-1]], get_mapped_idxs([end_closest_idx])
276
+ # otherwise, select up to two closest images, or just 1, whichever one applies best
277
+ # if same distance from start and end, return two images to use
278
+ if start_dist == end_dist:
279
+ return [sub_idxs[0], sub_idxs[-1]], get_mapped_idxs([start_closest_idx, end_closest_idx])
280
+ # else, use just one
281
+ if start_dist < end_dist:
282
+ return [sub_idxs[0]], get_mapped_idxs([start_closest_idx])
283
+ return [sub_idxs[-1]], get_mapped_idxs([end_closest_idx])
284
+
285
+
286
+ class SparseSpreadMethod(SparseMethod):
287
+ UNIFORM = "uniform"
288
+ STARTING = "starting"
289
+ ENDING = "ending"
290
+ CENTER = "center"
291
+
292
+ LIST = [UNIFORM, STARTING, ENDING, CENTER]
293
+
294
+ def __init__(self, spread=UNIFORM):
295
+ super().__init__(self.SPREAD)
296
+ self.spread = spread
297
+
298
+ def _get_indexes(self, hint_length: int, full_length: int) -> list[int]:
299
+ # if hint_length >= full_length, limit hints to full_length
300
+ if hint_length >= full_length:
301
+ return list(range(full_length))
302
+ # handle special case of 1 hint image
303
+ if hint_length == 1:
304
+ if self.spread in [self.UNIFORM, self.STARTING]:
305
+ return [0]
306
+ elif self.spread == self.ENDING:
307
+ return [full_length-1]
308
+ elif self.spread == self.CENTER:
309
+ # return second (of three) values as the center
310
+ return [np.linspace(0, full_length-1, 3, endpoint=True, dtype=int)[1]]
311
+ else:
312
+ raise ValueError(f"Unrecognized spread: {self.spread}")
313
+ # otherwise, handle other cases
314
+ if self.spread == self.UNIFORM:
315
+ return list(np.linspace(0, full_length-1, hint_length, endpoint=True, dtype=int))
316
+ elif self.spread == self.STARTING:
317
+ # make split 1 larger, remove last element
318
+ return list(np.linspace(0, full_length-1, hint_length+1, endpoint=True, dtype=int))[:-1]
319
+ elif self.spread == self.ENDING:
320
+ # make split 1 larger, remove first element
321
+ return list(np.linspace(0, full_length-1, hint_length+1, endpoint=True, dtype=int))[1:]
322
+ elif self.spread == self.CENTER:
323
+ # if hint length is not 3 greater than full length, do STARTING behavior
324
+ if full_length-hint_length < 3:
325
+ return list(np.linspace(0, full_length-1, hint_length+1, endpoint=True, dtype=int))[:-1]
326
+ # otherwise, get linspace of 2 greater than needed, then cut off first and last
327
+ return list(np.linspace(0, full_length-1, hint_length+2, endpoint=True, dtype=int))[1:-1]
328
+ return ValueError(f"Unrecognized spread: {self.spread}")
329
+
330
+
331
+ class SparseIndexMethod(SparseMethod):
332
+ def __init__(self, idxs: list[int]):
333
+ super().__init__(self.INDEX)
334
+ self.idxs = idxs
335
+
336
+ def _get_indexes(self, hint_length: int, full_length: int) -> list[int]:
337
+ orig_hint_length = hint_length
338
+ if hint_length > full_length:
339
+ hint_length = full_length
340
+ # if idxs is less than hint_length, throw error
341
+ if len(self.idxs) < hint_length:
342
+ err_msg = f"There are not enough indexes ({len(self.idxs)}) provided to fit the usable {hint_length} input images."
343
+ if orig_hint_length != hint_length:
344
+ err_msg = f"{err_msg} (original input images: {orig_hint_length})"
345
+ raise ValueError(err_msg)
346
+ # cap idxs to hint_length
347
+ idxs = self.idxs[:hint_length]
348
+ new_idxs = []
349
+ real_idxs = set()
350
+ for idx in idxs:
351
+ if idx < 0:
352
+ real_idx = full_length+idx
353
+ if real_idx in real_idxs:
354
+ raise ValueError(f"Index '{idx}' maps to '{real_idx}' and is duplicate - indexes in Sparse Index Method must be unique.")
355
+ else:
356
+ real_idx = idx
357
+ if real_idx in real_idxs:
358
+ raise ValueError(f"Index '{idx}' is duplicate (or a negative index is equivalent) - indexes in Sparse Index Method must be unique.")
359
+ real_idxs.add(real_idx)
360
+ new_idxs.append(real_idx)
361
+ return new_idxs
362
+
363
+
364
+ def get_idx_list_from_str(indexes: str) -> list[int]:
365
+ idxs = []
366
+ unique_idxs = set()
367
+ # get indeces from string
368
+ str_idxs = [x.strip() for x in indexes.strip().split(",")]
369
+ for str_idx in str_idxs:
370
+ try:
371
+ idx = int(str_idx)
372
+ if idx in unique_idxs:
373
+ raise ValueError(f"'{idx}' is duplicated; indexes must be unique.")
374
+ idxs.append(idx)
375
+ unique_idxs.add(idx)
376
+ except ValueError:
377
+ raise ValueError(f"'{str_idx}' is not a valid integer index.")
378
+ if len(idxs) == 0:
379
+ raise ValueError(f"No indexes were listed in Sparse Index Method.")
380
+ return idxs
381
+
382
+
383
+ #########################################
384
+ # motion-related portion of controlnet
385
+ class BlockType:
386
+ UP = "up"
387
+ DOWN = "down"
388
+ MID = "mid"
389
+
390
+ def get_down_block_max(mm_state_dict: dict[str, Tensor]) -> int:
391
+ return get_block_max(mm_state_dict, "down_blocks")
392
+
393
+ def get_up_block_max(mm_state_dict: dict[str, Tensor]) -> int:
394
+ return get_block_max(mm_state_dict, "up_blocks")
395
+
396
+ def get_block_max(mm_state_dict: dict[str, Tensor], block_name: str) -> int:
397
+ # keep track of biggest down_block count in module
398
+ biggest_block = -1
399
+ for key in mm_state_dict.keys():
400
+ if block_name in key:
401
+ try:
402
+ block_int = key.split(".")[1]
403
+ block_num = int(block_int)
404
+ if block_num > biggest_block:
405
+ biggest_block = block_num
406
+ except ValueError:
407
+ pass
408
+ return biggest_block
409
+
410
+ def has_mid_block(mm_state_dict: dict[str, Tensor]):
411
+ # check if keys contain mid_block
412
+ for key in mm_state_dict.keys():
413
+ if key.startswith("mid_block."):
414
+ return True
415
+ return False
416
+
417
+ def get_position_encoding_max_len(mm_state_dict: dict[str, Tensor], mm_name: str=None) -> int:
418
+ # use pos_encoder.pe entries to determine max length - [1, {max_length}, {320|640|1280}]
419
+ for key in mm_state_dict.keys():
420
+ if key.endswith("pos_encoder.pe"):
421
+ return mm_state_dict[key].size(1) # get middle dim
422
+ raise ValueError(f"No pos_encoder.pe found in SparseCtrl state_dict - {mm_name} is not a valid SparseCtrl model!")
423
+
424
+
425
+ class SparseCtrlMotionWrapper(nn.Module):
426
+ def __init__(self, mm_state_dict: dict[str, Tensor], ops=disable_weight_init_clean_groupnorm):
427
+ super().__init__()
428
+ self.down_blocks: Iterable[MotionModule] = None
429
+ self.up_blocks: Iterable[MotionModule] = None
430
+ self.mid_block: MotionModule = None
431
+ self.encoding_max_len = get_position_encoding_max_len(mm_state_dict, "")
432
+ layer_channels = (320, 640, 1280, 1280)
433
+ if get_down_block_max(mm_state_dict) > -1:
434
+ self.down_blocks = nn.ModuleList([])
435
+ for c in layer_channels:
436
+ self.down_blocks.append(MotionModule(c, temporal_position_encoding_max_len=self.encoding_max_len, block_type=BlockType.DOWN, ops=ops))
437
+ if get_up_block_max(mm_state_dict) > -1:
438
+ self.up_blocks = nn.ModuleList([])
439
+ for c in reversed(layer_channels):
440
+ self.up_blocks.append(MotionModule(c, temporal_position_encoding_max_len=self.encoding_max_len, block_type=BlockType.UP, ops=ops))
441
+ if has_mid_block(mm_state_dict):
442
+ self.mid_block = MotionModule(1280, temporal_position_encoding_max_len=self.encoding_max_len, block_type=BlockType.MID, ops=ops)
443
+
444
+ def inject(self, unet: SparseControlNet):
445
+ # inject input (down) blocks
446
+ self._inject(unet.input_blocks, self.down_blocks)
447
+ # inject mid block, if present
448
+ if self.mid_block is not None:
449
+ self._inject([unet.middle_block], [self.mid_block])
450
+ unet.motion_wrapper = self
451
+
452
+ def _inject(self, unet_blocks: nn.ModuleList, mm_blocks: nn.ModuleList):
453
+ # Rules for injection:
454
+ # For each component list in a unet block:
455
+ # if SpatialTransformer exists in list, place next block after last occurrence
456
+ # elif ResBlock exists in list, place next block after first occurrence
457
+ # else don't place block
458
+ injection_count = 0
459
+ unet_idx = 0
460
+ # details about blocks passed in
461
+ per_block = len(mm_blocks[0].motion_modules)
462
+ injection_goal = len(mm_blocks) * per_block
463
+ # only stop injecting when modules exhausted
464
+ while injection_count < injection_goal:
465
+ # figure out which VanillaTemporalModule from mm to inject
466
+ mm_blk_idx, mm_vtm_idx = injection_count // per_block, injection_count % per_block
467
+ # figure out layout of unet block components
468
+ st_idx = -1 # SpatialTransformer index
469
+ res_idx = -1 # first ResBlock index
470
+ # first, figure out indeces of relevant blocks
471
+ for idx, component in enumerate(unet_blocks[unet_idx]):
472
+ if type(component) == SpatialTransformer:
473
+ st_idx = idx
474
+ elif type(component).__name__ == "ResBlock" and res_idx < 0:
475
+ res_idx = idx
476
+ # if SpatialTransformer exists, inject right after
477
+ if st_idx >= 0:
478
+ unet_blocks[unet_idx].insert(st_idx+1, mm_blocks[mm_blk_idx].motion_modules[mm_vtm_idx])
479
+ injection_count += 1
480
+ # otherwise, if only ResBlock exists, inject right after
481
+ elif res_idx >= 0:
482
+ unet_blocks[unet_idx].insert(res_idx+1, mm_blocks[mm_blk_idx].motion_modules[mm_vtm_idx])
483
+ injection_count += 1
484
+ # increment unet_idx
485
+ unet_idx += 1
486
+
487
+ def eject(self, unet: SparseControlNet):
488
+ # remove from input blocks (downblocks)
489
+ self._eject(unet.input_blocks)
490
+ # remove from middle block (encapsulate in list to make compatible)
491
+ self._eject([unet.middle_block])
492
+ del unet.motion_wrapper
493
+ unet.motion_wrapper = None
494
+
495
+ def _eject(self, unet_blocks: nn.ModuleList):
496
+ # eject all VanillaTemporalModule objects from all blocks
497
+ for block in unet_blocks:
498
+ idx_to_pop = []
499
+ for idx, component in enumerate(block):
500
+ if type(component) == VanillaTemporalModule:
501
+ idx_to_pop.append(idx)
502
+ # pop in backwards order, as to not disturb what the indeces refer to
503
+ for idx in sorted(idx_to_pop, reverse=True):
504
+ block.pop(idx)
505
+
506
+ def set_video_length(self, video_length: int, full_length: int):
507
+ self.AD_video_length = video_length
508
+ if self.down_blocks is not None:
509
+ for block in self.down_blocks:
510
+ block.set_video_length(video_length, full_length)
511
+ if self.up_blocks is not None:
512
+ for block in self.up_blocks:
513
+ block.set_video_length(video_length, full_length)
514
+ if self.mid_block is not None:
515
+ self.mid_block.set_video_length(video_length, full_length)
516
+
517
+ def set_scale_multiplier(self, multiplier: Union[float, None]):
518
+ if self.down_blocks is not None:
519
+ for block in self.down_blocks:
520
+ block.set_scale_multiplier(multiplier)
521
+ if self.up_blocks is not None:
522
+ for block in self.up_blocks:
523
+ block.set_scale_multiplier(multiplier)
524
+ if self.mid_block is not None:
525
+ self.mid_block.set_scale_multiplier(multiplier)
526
+
527
+ def set_strength(self, strength: float):
528
+ if self.down_blocks is not None:
529
+ for block in self.down_blocks:
530
+ block.set_strength(strength)
531
+ if self.up_blocks is not None:
532
+ for block in self.up_blocks:
533
+ block.set_strength(strength)
534
+ if self.mid_block is not None:
535
+ self.mid_block.set_strength(strength)
536
+
537
+ def reset_temp_vars(self):
538
+ if self.down_blocks is not None:
539
+ for block in self.down_blocks:
540
+ block.reset_temp_vars()
541
+ if self.up_blocks is not None:
542
+ for block in self.up_blocks:
543
+ block.reset_temp_vars()
544
+ if self.mid_block is not None:
545
+ self.mid_block.reset_temp_vars()
546
+
547
+ def reset_scale_multiplier(self):
548
+ self.set_scale_multiplier(None)
549
+
550
+ def reset(self):
551
+ self.reset_scale_multiplier()
552
+ self.reset_temp_vars()
553
+
554
+
555
+ class MotionModule(nn.Module):
556
+ def __init__(self, in_channels, temporal_position_encoding_max_len=24, block_type: str=BlockType.DOWN, ops=disable_weight_init_clean_groupnorm):
557
+ super().__init__()
558
+ if block_type == BlockType.MID:
559
+ # mid blocks contain only a single VanillaTemporalModule
560
+ self.motion_modules: Iterable[VanillaTemporalModule] = nn.ModuleList([get_motion_module(in_channels, temporal_position_encoding_max_len, ops=ops)])
561
+ else:
562
+ # down blocks contain two VanillaTemporalModules
563
+ self.motion_modules: Iterable[VanillaTemporalModule] = nn.ModuleList(
564
+ [
565
+ get_motion_module(in_channels, temporal_position_encoding_max_len, ops=ops),
566
+ get_motion_module(in_channels, temporal_position_encoding_max_len, ops=ops)
567
+ ]
568
+ )
569
+ # up blocks contain one additional VanillaTemporalModule
570
+ if block_type == BlockType.UP:
571
+ self.motion_modules.append(get_motion_module(in_channels, temporal_position_encoding_max_len, ops=ops))
572
+
573
+ def set_video_length(self, video_length: int, full_length: int):
574
+ for motion_module in self.motion_modules:
575
+ motion_module.set_video_length(video_length, full_length)
576
+
577
+ def set_scale_multiplier(self, multiplier: Union[float, None]):
578
+ for motion_module in self.motion_modules:
579
+ motion_module.set_scale_multiplier(multiplier)
580
+
581
+ def set_masks(self, masks: Tensor, min_val: float, max_val: float):
582
+ for motion_module in self.motion_modules:
583
+ motion_module.set_masks(masks, min_val, max_val)
584
+
585
+ def set_sub_idxs(self, sub_idxs: list[int]):
586
+ for motion_module in self.motion_modules:
587
+ motion_module.set_sub_idxs(sub_idxs)
588
+
589
+ def set_strength(self, strength: float):
590
+ for motion_module in self.motion_modules:
591
+ motion_module.set_strength(strength)
592
+
593
+ def reset_temp_vars(self):
594
+ for motion_module in self.motion_modules:
595
+ motion_module.reset_temp_vars()
596
+
597
+
598
+ def get_motion_module(in_channels, temporal_position_encoding_max_len, ops=disable_weight_init_clean_groupnorm):
599
+ # unlike normal AD, there is only one attention block expected in SparseCtrl models
600
+ return VanillaTemporalModule(in_channels=in_channels, attention_block_types=("Temporal_Self",), temporal_position_encoding_max_len=temporal_position_encoding_max_len, ops=ops)
601
+
602
+
603
+ class VanillaTemporalModule(nn.Module):
604
+ def __init__(
605
+ self,
606
+ in_channels,
607
+ num_attention_heads=8,
608
+ num_transformer_block=1,
609
+ attention_block_types=("Temporal_Self", "Temporal_Self"),
610
+ cross_frame_attention_mode=None,
611
+ temporal_position_encoding=True,
612
+ temporal_position_encoding_max_len=24,
613
+ temporal_attention_dim_div=1,
614
+ zero_initialize=True,
615
+ ops=disable_weight_init_clean_groupnorm,
616
+ ):
617
+ super().__init__()
618
+ self.strength = 1.0
619
+ self.temporal_transformer = TemporalTransformer3DModel(
620
+ in_channels=in_channels,
621
+ num_attention_heads=num_attention_heads,
622
+ attention_head_dim=in_channels
623
+ // num_attention_heads
624
+ // temporal_attention_dim_div,
625
+ num_layers=num_transformer_block,
626
+ attention_block_types=attention_block_types,
627
+ cross_frame_attention_mode=cross_frame_attention_mode,
628
+ temporal_position_encoding=temporal_position_encoding,
629
+ temporal_position_encoding_max_len=temporal_position_encoding_max_len,
630
+ ops=ops,
631
+ )
632
+
633
+ if zero_initialize:
634
+ self.temporal_transformer.proj_out = zero_module(
635
+ self.temporal_transformer.proj_out
636
+ )
637
+
638
+ def set_video_length(self, video_length: int, full_length: int):
639
+ self.temporal_transformer.set_video_length(video_length, full_length)
640
+
641
+ def set_scale_multiplier(self, multiplier: Union[float, None]):
642
+ self.temporal_transformer.set_scale_multiplier(multiplier)
643
+
644
+ def set_masks(self, masks: Tensor, min_val: float, max_val: float):
645
+ self.temporal_transformer.set_masks(masks, min_val, max_val)
646
+
647
+ def set_sub_idxs(self, sub_idxs: list[int]):
648
+ self.temporal_transformer.set_sub_idxs(sub_idxs)
649
+
650
+ def set_strength(self, strength: float):
651
+ self.strength = strength
652
+
653
+ def reset_temp_vars(self):
654
+ self.set_strength(1.0)
655
+ self.temporal_transformer.reset_temp_vars()
656
+
657
+ def forward(self, input_tensor, encoder_hidden_states=None, attention_mask=None):
658
+ if math.isclose(self.strength, 1.0):
659
+ return self.temporal_transformer(input_tensor, encoder_hidden_states, attention_mask)
660
+ elif math.isclose(self.strength, 0.0):
661
+ return input_tensor
662
+ # elif self.strength > 1.0:
663
+ # return self.temporal_transformer(input_tensor, encoder_hidden_states, attention_mask)*self.strength
664
+ else:
665
+ return self.temporal_transformer(input_tensor, encoder_hidden_states, attention_mask)*self.strength + input_tensor*(1.0-self.strength)
666
+
667
+
668
+ class TemporalTransformer3DModel(nn.Module):
669
+ def __init__(
670
+ self,
671
+ in_channels,
672
+ num_attention_heads,
673
+ attention_head_dim,
674
+ num_layers,
675
+ attention_block_types=(
676
+ "Temporal_Self",
677
+ "Temporal_Self",
678
+ ),
679
+ dropout=0.0,
680
+ norm_num_groups=32,
681
+ cross_attention_dim=768,
682
+ activation_fn="geglu",
683
+ attention_bias=False,
684
+ upcast_attention=False,
685
+ cross_frame_attention_mode=None,
686
+ temporal_position_encoding=False,
687
+ temporal_position_encoding_max_len=24,
688
+ ops=disable_weight_init_clean_groupnorm,
689
+ ):
690
+ super().__init__()
691
+ self.video_length = 16
692
+ self.full_length = 16
693
+ self.scale_min = 1.0
694
+ self.scale_max = 1.0
695
+ self.raw_scale_mask: Union[Tensor, None] = None
696
+ self.temp_scale_mask: Union[Tensor, None] = None
697
+ self.sub_idxs: Union[list[int], None] = None
698
+ self.prev_hidden_states_batch = 0
699
+
700
+
701
+ inner_dim = num_attention_heads * attention_head_dim
702
+
703
+ self.norm = ops.GroupNorm(
704
+ num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True
705
+ )
706
+ self.proj_in = ops.Linear(in_channels, inner_dim)
707
+
708
+ self.transformer_blocks: Iterable[TemporalTransformerBlock] = nn.ModuleList(
709
+ [
710
+ TemporalTransformerBlock(
711
+ dim=inner_dim,
712
+ num_attention_heads=num_attention_heads,
713
+ attention_head_dim=attention_head_dim,
714
+ attention_block_types=attention_block_types,
715
+ dropout=dropout,
716
+ norm_num_groups=norm_num_groups,
717
+ cross_attention_dim=cross_attention_dim,
718
+ activation_fn=activation_fn,
719
+ attention_bias=attention_bias,
720
+ upcast_attention=upcast_attention,
721
+ cross_frame_attention_mode=cross_frame_attention_mode,
722
+ temporal_position_encoding=temporal_position_encoding,
723
+ temporal_position_encoding_max_len=temporal_position_encoding_max_len,
724
+ ops=ops,
725
+ )
726
+ for d in range(num_layers)
727
+ ]
728
+ )
729
+ self.proj_out = ops.Linear(inner_dim, in_channels)
730
+
731
+ def set_video_length(self, video_length: int, full_length: int):
732
+ self.video_length = video_length
733
+ self.full_length = full_length
734
+
735
+ def set_scale_multiplier(self, multiplier: Union[float, None]):
736
+ for block in self.transformer_blocks:
737
+ block.set_scale_multiplier(multiplier)
738
+
739
+ def set_masks(self, masks: Tensor, min_val: float, max_val: float):
740
+ self.scale_min = min_val
741
+ self.scale_max = max_val
742
+ self.raw_scale_mask = masks
743
+
744
+ def set_sub_idxs(self, sub_idxs: list[int]):
745
+ self.sub_idxs = sub_idxs
746
+ for block in self.transformer_blocks:
747
+ block.set_sub_idxs(sub_idxs)
748
+
749
+ def reset_temp_vars(self):
750
+ del self.temp_scale_mask
751
+ self.temp_scale_mask = None
752
+ self.prev_hidden_states_batch = 0
753
+ for block in self.transformer_blocks:
754
+ block.reset_temp_vars()
755
+
756
+ def get_scale_mask(self, hidden_states: Tensor) -> Union[Tensor, None]:
757
+ # if no raw mask, return None
758
+ if self.raw_scale_mask is None:
759
+ return None
760
+ shape = hidden_states.shape
761
+ batch, channel, height, width = shape
762
+ # if temp mask already calculated, return it
763
+ if self.temp_scale_mask != None:
764
+ # check if hidden_states batch matches
765
+ if batch == self.prev_hidden_states_batch:
766
+ if self.sub_idxs is not None:
767
+ return self.temp_scale_mask[:, self.sub_idxs, :]
768
+ return self.temp_scale_mask
769
+ # if does not match, reset cached temp_scale_mask and recalculate it
770
+ del self.temp_scale_mask
771
+ self.temp_scale_mask = None
772
+ # otherwise, calculate temp mask
773
+ self.prev_hidden_states_batch = batch
774
+ mask = prepare_mask_batch(self.raw_scale_mask, shape=(self.full_length, 1, height, width))
775
+ mask = extend_to_batch_size(mask, self.full_length)
776
+ # if mask not the same amount length as full length, make it match
777
+ if self.full_length != mask.shape[0]:
778
+ mask = broadcast_image_to_extend(mask, self.full_length, 1)
779
+ # reshape mask to attention K shape (h*w, latent_count, 1)
780
+ batch, channel, height, width = mask.shape
781
+ # first, perform same operations as on hidden_states,
782
+ # turning (b, c, h, w) -> (b, h*w, c)
783
+ mask = mask.permute(0, 2, 3, 1).reshape(batch, height*width, channel)
784
+ # then, make it the same shape as attention's k, (h*w, b, c)
785
+ mask = mask.permute(1, 0, 2)
786
+ # make masks match the expected length of h*w
787
+ batched_number = shape[0] // self.video_length
788
+ if batched_number > 1:
789
+ mask = torch.cat([mask] * batched_number, dim=0)
790
+ # cache mask and set to proper device
791
+ self.temp_scale_mask = mask
792
+ # move temp_scale_mask to proper dtype + device
793
+ self.temp_scale_mask = self.temp_scale_mask.to(dtype=hidden_states.dtype, device=hidden_states.device)
794
+ # return subset of masks, if needed
795
+ if self.sub_idxs is not None:
796
+ return self.temp_scale_mask[:, self.sub_idxs, :]
797
+ return self.temp_scale_mask
798
+
799
+ def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None):
800
+ batch, channel, height, width = hidden_states.shape
801
+ residual = hidden_states
802
+ scale_mask = self.get_scale_mask(hidden_states)
803
+ # add some casts for fp8 purposes - does not affect speed otherwise
804
+ hidden_states = self.norm(hidden_states).to(hidden_states.dtype)
805
+ inner_dim = hidden_states.shape[1]
806
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(
807
+ batch, height * width, inner_dim
808
+ )
809
+ hidden_states = self.proj_in(hidden_states).to(hidden_states.dtype)
810
+
811
+ # Transformer Blocks
812
+ for block in self.transformer_blocks:
813
+ hidden_states = block(
814
+ hidden_states,
815
+ encoder_hidden_states=encoder_hidden_states,
816
+ attention_mask=attention_mask,
817
+ video_length=self.video_length,
818
+ scale_mask=scale_mask
819
+ )
820
+
821
+ # output
822
+ hidden_states = self.proj_out(hidden_states)
823
+ hidden_states = (
824
+ hidden_states.reshape(batch, height, width, inner_dim)
825
+ .permute(0, 3, 1, 2)
826
+ .contiguous()
827
+ )
828
+
829
+ output = hidden_states + residual
830
+
831
+ return output
832
+
833
+
834
+ class TemporalTransformerBlock(nn.Module):
835
+ def __init__(
836
+ self,
837
+ dim,
838
+ num_attention_heads,
839
+ attention_head_dim,
840
+ attention_block_types=(
841
+ "Temporal_Self",
842
+ "Temporal_Self",
843
+ ),
844
+ dropout=0.0,
845
+ norm_num_groups=32,
846
+ cross_attention_dim=768,
847
+ activation_fn="geglu",
848
+ attention_bias=False,
849
+ upcast_attention=False,
850
+ cross_frame_attention_mode=None,
851
+ temporal_position_encoding=False,
852
+ temporal_position_encoding_max_len=24,
853
+ ops=disable_weight_init_clean_groupnorm,
854
+ ):
855
+ super().__init__()
856
+
857
+ attention_blocks = []
858
+ norms = []
859
+
860
+ for block_name in attention_block_types:
861
+ attention_blocks.append(
862
+ VersatileAttention(
863
+ attention_mode=block_name.split("_")[0],
864
+ context_dim=cross_attention_dim # called context_dim for ComfyUI impl
865
+ if block_name.endswith("_Cross")
866
+ else None,
867
+ query_dim=dim,
868
+ heads=num_attention_heads,
869
+ dim_head=attention_head_dim,
870
+ dropout=dropout,
871
+ #bias=attention_bias, # remove for Comfy CrossAttention
872
+ #upcast_attention=upcast_attention, # remove for Comfy CrossAttention
873
+ cross_frame_attention_mode=cross_frame_attention_mode,
874
+ temporal_position_encoding=temporal_position_encoding,
875
+ temporal_position_encoding_max_len=temporal_position_encoding_max_len,
876
+ ops=ops,
877
+ )
878
+ )
879
+ norms.append(ops.LayerNorm(dim))
880
+
881
+ self.attention_blocks: Iterable[VersatileAttention] = nn.ModuleList(attention_blocks)
882
+ self.norms = nn.ModuleList(norms)
883
+
884
+ self.ff = FeedForward(dim, dropout=dropout, glu=(activation_fn == "geglu"), operations=ops)
885
+ self.ff_norm = ops.LayerNorm(dim)
886
+
887
+ def set_scale_multiplier(self, multiplier: Union[float, None]):
888
+ for block in self.attention_blocks:
889
+ block.set_scale_multiplier(multiplier)
890
+
891
+ def set_sub_idxs(self, sub_idxs: list[int]):
892
+ for block in self.attention_blocks:
893
+ block.set_sub_idxs(sub_idxs)
894
+
895
+ def reset_temp_vars(self):
896
+ for block in self.attention_blocks:
897
+ block.reset_temp_vars()
898
+
899
+ def forward(
900
+ self,
901
+ hidden_states,
902
+ encoder_hidden_states=None,
903
+ attention_mask=None,
904
+ video_length=None,
905
+ scale_mask=None
906
+ ):
907
+ for attention_block, norm in zip(self.attention_blocks, self.norms):
908
+ norm_hidden_states = norm(hidden_states).to(hidden_states.dtype)
909
+ hidden_states = (
910
+ attention_block(
911
+ norm_hidden_states,
912
+ encoder_hidden_states=encoder_hidden_states
913
+ if attention_block.is_cross_attention
914
+ else None,
915
+ attention_mask=attention_mask,
916
+ video_length=video_length,
917
+ scale_mask=scale_mask
918
+ )
919
+ + hidden_states
920
+ )
921
+
922
+ hidden_states = self.ff(self.ff_norm(hidden_states)) + hidden_states
923
+
924
+ output = hidden_states
925
+ return output
926
+
927
+
928
+ class PositionalEncoding(nn.Module):
929
+ def __init__(self, d_model, dropout=0.0, max_len=24):
930
+ super().__init__()
931
+ self.dropout = nn.Dropout(p=dropout)
932
+ position = torch.arange(max_len).unsqueeze(1)
933
+ div_term = torch.exp(
934
+ torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model)
935
+ )
936
+ pe = torch.zeros(1, max_len, d_model)
937
+ pe[0, :, 0::2] = torch.sin(position * div_term)
938
+ pe[0, :, 1::2] = torch.cos(position * div_term)
939
+ self.register_buffer("pe", pe)
940
+ self.sub_idxs = None
941
+
942
+ def set_sub_idxs(self, sub_idxs: list[int]):
943
+ self.sub_idxs = sub_idxs
944
+
945
+ def forward(self, x):
946
+ #if self.sub_idxs is not None:
947
+ # x = x + self.pe[:, self.sub_idxs]
948
+ #else:
949
+ x = x + self.pe[:, : x.size(1)]
950
+ return self.dropout(x)
951
+
952
+
953
+ class CrossAttentionMMSparse(nn.Module):
954
+ def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0., dtype=None, device=None,
955
+ operations=disable_weight_init_clean_groupnorm):
956
+ super().__init__()
957
+ inner_dim = dim_head * heads
958
+ context_dim = default(context_dim, query_dim)
959
+
960
+ self.actual_attention = optimized_attention_mm
961
+ self.heads = heads
962
+ self.dim_head = dim_head
963
+ self.scale = None
964
+
965
+ self.to_q = operations.Linear(query_dim, inner_dim, bias=False, dtype=dtype, device=device)
966
+ self.to_k = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
967
+ self.to_v = operations.Linear(context_dim, inner_dim, bias=False, dtype=dtype, device=device)
968
+
969
+ self.to_out = nn.Sequential(operations.Linear(inner_dim, query_dim, dtype=dtype, device=device), nn.Dropout(dropout))
970
+
971
+ def reset_attention_type(self):
972
+ self.actual_attention = optimized_attention_mm
973
+
974
+ def forward(self, x, context=None, value=None, mask=None, scale_mask=None):
975
+ q = self.to_q(x)
976
+ context = default(context, x)
977
+ k: Tensor = self.to_k(context)
978
+ if value is not None:
979
+ v = self.to_v(value)
980
+ del value
981
+ else:
982
+ v = self.to_v(context)
983
+
984
+ # apply custom scale by multiplying k by scale factor
985
+ if self.scale is not None:
986
+ k *= self.scale
987
+
988
+ # apply scale mask, if present
989
+ if scale_mask is not None:
990
+ k *= scale_mask
991
+
992
+ try:
993
+ out = self.actual_attention(q, k, v, self.heads, mask)
994
+ except RuntimeError as e:
995
+ if str(e).startswith("CUDA error: invalid configuration argument"):
996
+ self.actual_attention = fallback_attention_mm
997
+ out = self.actual_attention(q, k, v, self.heads, mask)
998
+ else:
999
+ raise
1000
+ return self.to_out(out)
1001
+
1002
+
1003
+ class VersatileAttention(CrossAttentionMMSparse):
1004
+ def __init__(
1005
+ self,
1006
+ attention_mode=None,
1007
+ cross_frame_attention_mode=None,
1008
+ temporal_position_encoding=False,
1009
+ temporal_position_encoding_max_len=24,
1010
+ ops=disable_weight_init_clean_groupnorm,
1011
+ *args,
1012
+ **kwargs,
1013
+ ):
1014
+ super().__init__(operations=ops, *args, **kwargs)
1015
+ assert attention_mode == "Temporal"
1016
+
1017
+ self.attention_mode = attention_mode
1018
+ self.is_cross_attention = kwargs["context_dim"] is not None
1019
+
1020
+ self.pos_encoder = (
1021
+ PositionalEncoding(
1022
+ kwargs["query_dim"],
1023
+ dropout=0.0,
1024
+ max_len=temporal_position_encoding_max_len,
1025
+ )
1026
+ if (temporal_position_encoding and attention_mode == "Temporal")
1027
+ else None
1028
+ )
1029
+
1030
+ def extra_repr(self):
1031
+ return f"(Module Info) Attention_Mode: {self.attention_mode}, Is_Cross_Attention: {self.is_cross_attention}"
1032
+
1033
+ def set_scale_multiplier(self, multiplier: Union[float, None]):
1034
+ if multiplier is None or math.isclose(multiplier, 1.0):
1035
+ self.scale = None
1036
+ else:
1037
+ self.scale = multiplier
1038
+
1039
+ def set_sub_idxs(self, sub_idxs: list[int]):
1040
+ if self.pos_encoder != None:
1041
+ self.pos_encoder.set_sub_idxs(sub_idxs)
1042
+
1043
+ def reset_temp_vars(self):
1044
+ self.reset_attention_type()
1045
+
1046
+ def forward(
1047
+ self,
1048
+ hidden_states: Tensor,
1049
+ encoder_hidden_states=None,
1050
+ attention_mask=None,
1051
+ video_length=None,
1052
+ scale_mask=None,
1053
+ ):
1054
+ if self.attention_mode != "Temporal":
1055
+ raise NotImplementedError
1056
+
1057
+ d = hidden_states.shape[1]
1058
+ hidden_states = rearrange(
1059
+ hidden_states, "(b f) d c -> (b d) f c", f=video_length
1060
+ )
1061
+
1062
+ if self.pos_encoder is not None:
1063
+ hidden_states = self.pos_encoder(hidden_states).to(hidden_states.dtype)
1064
+
1065
+ encoder_hidden_states = (
1066
+ repeat(encoder_hidden_states, "b n c -> (b d) n c", d=d)
1067
+ if encoder_hidden_states is not None
1068
+ else encoder_hidden_states
1069
+ )
1070
+
1071
+ hidden_states = super().forward(
1072
+ hidden_states,
1073
+ encoder_hidden_states,
1074
+ value=None,
1075
+ mask=attention_mask,
1076
+ scale_mask=scale_mask,
1077
+ )
1078
+
1079
+ hidden_states = rearrange(hidden_states, "(b d) f c -> (b f) d c", d=d)
1080
+
1081
+ return hidden_states
ComfyUI-Advanced-ControlNet/adv_control/control_svd.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from torch import Tensor
4
+
5
+ import comfy.model_detection
6
+ from comfy.utils import UNET_MAP_BASIC, UNET_MAP_RESNET, UNET_MAP_ATTENTIONS, TRANSFORMER_BLOCKS
7
+
8
+ import torch
9
+
10
+
11
+ from comfy.ldm.modules.diffusionmodules.util import (
12
+ zero_module,
13
+ timestep_embedding,
14
+ )
15
+
16
+ from comfy.ldm.modules.attention import SpatialVideoTransformer
17
+ from comfy.ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, VideoResBlock, Downsample
18
+ from comfy.ldm.util import exists
19
+ import comfy.ops
20
+
21
+
22
+ class SVDControlNet(nn.Module):
23
+ def __init__(
24
+ self,
25
+ image_size,
26
+ in_channels,
27
+ model_channels,
28
+ hint_channels,
29
+ num_res_blocks,
30
+ dropout=0,
31
+ channel_mult=(1, 2, 4, 8),
32
+ conv_resample=True,
33
+ dims=2,
34
+ num_classes=None,
35
+ use_checkpoint=False,
36
+ dtype=torch.float32,
37
+ num_heads=-1,
38
+ num_head_channels=-1,
39
+ num_heads_upsample=-1,
40
+ use_scale_shift_norm=False,
41
+ resblock_updown=False,
42
+ use_new_attention_order=False,
43
+ use_spatial_transformer=False, # custom transformer support
44
+ transformer_depth=1, # custom transformer support
45
+ context_dim=None, # custom transformer support
46
+ n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
47
+ legacy=True,
48
+ disable_self_attentions=None,
49
+ num_attention_blocks=None,
50
+ disable_middle_self_attn=False,
51
+ use_linear_in_transformer=False,
52
+ adm_in_channels=None,
53
+ transformer_depth_middle=None,
54
+ transformer_depth_output=None,
55
+ use_spatial_context=False,
56
+ extra_ff_mix_layer=False,
57
+ merge_strategy="fixed",
58
+ merge_factor=0.5,
59
+ video_kernel_size=3,
60
+ device=None,
61
+ operations=comfy.ops.disable_weight_init,
62
+ **kwargs,
63
+ ):
64
+ super().__init__()
65
+ assert use_spatial_transformer == True, "use_spatial_transformer has to be true"
66
+ if use_spatial_transformer:
67
+ assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
68
+
69
+ if context_dim is not None:
70
+ assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
71
+ # from omegaconf.listconfig import ListConfig
72
+ # if type(context_dim) == ListConfig:
73
+ # context_dim = list(context_dim)
74
+
75
+ if num_heads_upsample == -1:
76
+ num_heads_upsample = num_heads
77
+
78
+ if num_heads == -1:
79
+ assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
80
+
81
+ if num_head_channels == -1:
82
+ assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
83
+
84
+ self.dims = dims
85
+ self.image_size = image_size
86
+ self.in_channels = in_channels
87
+ self.model_channels = model_channels
88
+
89
+ if isinstance(num_res_blocks, int):
90
+ self.num_res_blocks = len(channel_mult) * [num_res_blocks]
91
+ else:
92
+ if len(num_res_blocks) != len(channel_mult):
93
+ raise ValueError("provide num_res_blocks either as an int (globally constant) or "
94
+ "as a list/tuple (per-level) with the same length as channel_mult")
95
+ self.num_res_blocks = num_res_blocks
96
+
97
+ if disable_self_attentions is not None:
98
+ # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
99
+ assert len(disable_self_attentions) == len(channel_mult)
100
+ if num_attention_blocks is not None:
101
+ assert len(num_attention_blocks) == len(self.num_res_blocks)
102
+ assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
103
+
104
+ transformer_depth = transformer_depth[:]
105
+
106
+ self.dropout = dropout
107
+ self.channel_mult = channel_mult
108
+ self.conv_resample = conv_resample
109
+ self.num_classes = num_classes
110
+ self.use_checkpoint = use_checkpoint
111
+ self.dtype = dtype
112
+ self.num_heads = num_heads
113
+ self.num_head_channels = num_head_channels
114
+ self.num_heads_upsample = num_heads_upsample
115
+ self.predict_codebook_ids = n_embed is not None
116
+
117
+ time_embed_dim = model_channels * 4
118
+ self.time_embed = nn.Sequential(
119
+ operations.Linear(model_channels, time_embed_dim, dtype=self.dtype, device=device),
120
+ nn.SiLU(),
121
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
122
+ )
123
+
124
+ if self.num_classes is not None:
125
+ if isinstance(self.num_classes, int):
126
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
127
+ elif self.num_classes == "continuous":
128
+ print("setting up linear c_adm embedding layer")
129
+ self.label_emb = nn.Linear(1, time_embed_dim)
130
+ elif self.num_classes == "sequential":
131
+ assert adm_in_channels is not None
132
+ self.label_emb = nn.Sequential(
133
+ nn.Sequential(
134
+ operations.Linear(adm_in_channels, time_embed_dim, dtype=self.dtype, device=device),
135
+ nn.SiLU(),
136
+ operations.Linear(time_embed_dim, time_embed_dim, dtype=self.dtype, device=device),
137
+ )
138
+ )
139
+ else:
140
+ raise ValueError()
141
+
142
+ self.input_blocks = nn.ModuleList(
143
+ [
144
+ TimestepEmbedSequential(
145
+ operations.conv_nd(dims, in_channels, model_channels, 3, padding=1, dtype=self.dtype, device=device)
146
+ )
147
+ ]
148
+ )
149
+ self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels, operations=operations, dtype=self.dtype, device=device)])
150
+
151
+ self.input_hint_block = TimestepEmbedSequential(
152
+ operations.conv_nd(dims, hint_channels, 16, 3, padding=1, dtype=self.dtype, device=device),
153
+ nn.SiLU(),
154
+ operations.conv_nd(dims, 16, 16, 3, padding=1, dtype=self.dtype, device=device),
155
+ nn.SiLU(),
156
+ operations.conv_nd(dims, 16, 32, 3, padding=1, stride=2, dtype=self.dtype, device=device),
157
+ nn.SiLU(),
158
+ operations.conv_nd(dims, 32, 32, 3, padding=1, dtype=self.dtype, device=device),
159
+ nn.SiLU(),
160
+ operations.conv_nd(dims, 32, 96, 3, padding=1, stride=2, dtype=self.dtype, device=device),
161
+ nn.SiLU(),
162
+ operations.conv_nd(dims, 96, 96, 3, padding=1, dtype=self.dtype, device=device),
163
+ nn.SiLU(),
164
+ operations.conv_nd(dims, 96, 256, 3, padding=1, stride=2, dtype=self.dtype, device=device),
165
+ nn.SiLU(),
166
+ operations.conv_nd(dims, 256, model_channels, 3, padding=1, dtype=self.dtype, device=device)
167
+ )
168
+
169
+ self._feature_size = model_channels
170
+ input_block_chans = [model_channels]
171
+ ch = model_channels
172
+ ds = 1
173
+ for level, mult in enumerate(channel_mult):
174
+ for nr in range(self.num_res_blocks[level]):
175
+ layers = [
176
+ VideoResBlock(
177
+ ch,
178
+ time_embed_dim,
179
+ dropout,
180
+ out_channels=mult * model_channels,
181
+ dims=dims,
182
+ use_checkpoint=use_checkpoint,
183
+ use_scale_shift_norm=use_scale_shift_norm,
184
+ dtype=self.dtype,
185
+ device=device,
186
+ operations=operations,
187
+ video_kernel_size=video_kernel_size,
188
+ merge_strategy=merge_strategy, merge_factor=merge_factor,
189
+ )
190
+ ]
191
+ ch = mult * model_channels
192
+ num_transformers = transformer_depth.pop(0)
193
+ if num_transformers > 0:
194
+ if num_head_channels == -1:
195
+ dim_head = ch // num_heads
196
+ else:
197
+ num_heads = ch // num_head_channels
198
+ dim_head = num_head_channels
199
+ if legacy:
200
+ #num_heads = 1
201
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
202
+ if exists(disable_self_attentions):
203
+ disabled_sa = disable_self_attentions[level]
204
+ else:
205
+ disabled_sa = False
206
+
207
+ if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
208
+ layers.append(
209
+ SpatialVideoTransformer(
210
+ ch, num_heads, dim_head, depth=num_transformers, context_dim=context_dim,
211
+ disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
212
+ checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations,
213
+ use_spatial_context=use_spatial_context, ff_in=extra_ff_mix_layer,
214
+ merge_strategy=merge_strategy, merge_factor=merge_factor,
215
+ )
216
+ )
217
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
218
+ self.zero_convs.append(self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device))
219
+ self._feature_size += ch
220
+ input_block_chans.append(ch)
221
+ if level != len(channel_mult) - 1:
222
+ out_ch = ch
223
+ self.input_blocks.append(
224
+ TimestepEmbedSequential(
225
+ VideoResBlock(
226
+ ch,
227
+ time_embed_dim,
228
+ dropout,
229
+ out_channels=out_ch,
230
+ dims=dims,
231
+ use_checkpoint=use_checkpoint,
232
+ use_scale_shift_norm=use_scale_shift_norm,
233
+ down=True,
234
+ dtype=self.dtype,
235
+ device=device,
236
+ operations=operations,
237
+ video_kernel_size=video_kernel_size,
238
+ merge_strategy=merge_strategy, merge_factor=merge_factor,
239
+ )
240
+ if resblock_updown
241
+ else Downsample(
242
+ ch, conv_resample, dims=dims, out_channels=out_ch, dtype=self.dtype, device=device, operations=operations
243
+ )
244
+ )
245
+ )
246
+ ch = out_ch
247
+ input_block_chans.append(ch)
248
+ self.zero_convs.append(self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device))
249
+ ds *= 2
250
+ self._feature_size += ch
251
+
252
+ if num_head_channels == -1:
253
+ dim_head = ch // num_heads
254
+ else:
255
+ num_heads = ch // num_head_channels
256
+ dim_head = num_head_channels
257
+ if legacy:
258
+ #num_heads = 1
259
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
260
+ mid_block = [
261
+ VideoResBlock(
262
+ ch,
263
+ time_embed_dim,
264
+ dropout,
265
+ dims=dims,
266
+ use_checkpoint=use_checkpoint,
267
+ use_scale_shift_norm=use_scale_shift_norm,
268
+ dtype=self.dtype,
269
+ device=device,
270
+ operations=operations,
271
+ video_kernel_size=video_kernel_size,
272
+ merge_strategy=merge_strategy, merge_factor=merge_factor,
273
+ )]
274
+ if transformer_depth_middle >= 0:
275
+ mid_block += [SpatialVideoTransformer( # always uses a self-attn
276
+ ch, num_heads, dim_head, depth=transformer_depth_middle, context_dim=context_dim,
277
+ disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
278
+ checkpoint=use_checkpoint, dtype=self.dtype, device=device, operations=operations,
279
+ use_spatial_context=use_spatial_context, ff_in=extra_ff_mix_layer,
280
+ merge_strategy=merge_strategy, merge_factor=merge_factor,
281
+ ),
282
+ VideoResBlock(
283
+ ch,
284
+ time_embed_dim,
285
+ dropout,
286
+ dims=dims,
287
+ use_checkpoint=use_checkpoint,
288
+ use_scale_shift_norm=use_scale_shift_norm,
289
+ dtype=self.dtype,
290
+ device=device,
291
+ operations=operations,
292
+ video_kernel_size=video_kernel_size,
293
+ merge_strategy=merge_strategy, merge_factor=merge_factor,
294
+ )]
295
+ self.middle_block = TimestepEmbedSequential(*mid_block)
296
+ self.middle_block_out = self.make_zero_conv(ch, operations=operations, dtype=self.dtype, device=device)
297
+ self._feature_size += ch
298
+
299
+ def make_zero_conv(self, channels, operations=None, dtype=None, device=None):
300
+ return TimestepEmbedSequential(operations.conv_nd(self.dims, channels, channels, 1, padding=0, dtype=dtype, device=device))
301
+
302
+ def forward(self, x, hint, timesteps, context, y=None, **kwargs):
303
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False).to(x.dtype)
304
+ emb = self.time_embed(t_emb)
305
+
306
+ cond = kwargs["cond"]
307
+ num_video_frames = cond["num_video_frames"]
308
+ image_only_indicator = cond.get("image_only_indicator", None)
309
+ time_context = cond.get("time_context", None)
310
+ del cond
311
+
312
+ guided_hint = self.input_hint_block(hint, emb, context, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator)
313
+
314
+ outs = []
315
+
316
+ hs = []
317
+ if self.num_classes is not None:
318
+ assert y.shape[0] == x.shape[0]
319
+ emb = emb + self.label_emb(y)
320
+
321
+ h = x
322
+ for module, zero_conv in zip(self.input_blocks, self.zero_convs):
323
+ if guided_hint is not None:
324
+ h = module(h, emb, context, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator)
325
+ h += guided_hint
326
+ guided_hint = None
327
+ else:
328
+ h = module(h, emb, context, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator)
329
+ outs.append(zero_conv(h, emb, context, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator))
330
+
331
+ h = self.middle_block(h, emb, context, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator)
332
+ outs.append(self.middle_block_out(h, emb, context, time_context=time_context, num_video_frames=num_video_frames, image_only_indicator=image_only_indicator))
333
+
334
+ return outs
335
+
336
+
337
+ TEMPORAL_TRANSFORMER_BLOCKS = {
338
+ "norm_in.weight",
339
+ "norm_in.bias",
340
+ "ff_in.net.0.proj.weight",
341
+ "ff_in.net.0.proj.bias",
342
+ "ff_in.net.2.weight",
343
+ "ff_in.net.2.bias",
344
+ }
345
+ TEMPORAL_TRANSFORMER_BLOCKS.update(TRANSFORMER_BLOCKS)
346
+
347
+
348
+ TEMPORAL_UNET_MAP_ATTENTIONS = {
349
+ "time_mixer.mix_factor",
350
+ }
351
+ TEMPORAL_UNET_MAP_ATTENTIONS.update(UNET_MAP_ATTENTIONS)
352
+
353
+
354
+ TEMPORAL_TRANSFORMER_MAP = {
355
+ "time_pos_embed.0.weight": "time_pos_embed.linear_1.weight",
356
+ "time_pos_embed.0.bias": "time_pos_embed.linear_1.bias",
357
+ "time_pos_embed.2.weight": "time_pos_embed.linear_2.weight",
358
+ "time_pos_embed.2.bias": "time_pos_embed.linear_2.bias",
359
+ }
360
+
361
+
362
+ TEMPORAL_RESNET = {
363
+ "time_mixer.mix_factor",
364
+ }
365
+
366
+
367
+ def svd_unet_config_from_diffusers_unet(state_dict: dict[str, Tensor], dtype):
368
+ match = {}
369
+ transformer_depth = []
370
+
371
+ attn_res = 1
372
+ down_blocks = comfy.model_detection.count_blocks(state_dict, "down_blocks.{}")
373
+ for i in range(down_blocks):
374
+ attn_blocks = comfy.model_detection.count_blocks(state_dict, "down_blocks.{}.attentions.".format(i) + '{}')
375
+ for ab in range(attn_blocks):
376
+ transformer_count = comfy.model_detection.count_blocks(state_dict, "down_blocks.{}.attentions.{}.transformer_blocks.".format(i, ab) + '{}')
377
+ transformer_depth.append(transformer_count)
378
+ if transformer_count > 0:
379
+ match["context_dim"] = state_dict["down_blocks.{}.attentions.{}.transformer_blocks.0.attn2.to_k.weight".format(i, ab)].shape[1]
380
+
381
+ attn_res *= 2
382
+ if attn_blocks == 0:
383
+ transformer_depth.append(0)
384
+ transformer_depth.append(0)
385
+
386
+ match["transformer_depth"] = transformer_depth
387
+
388
+ match["model_channels"] = state_dict["conv_in.weight"].shape[0]
389
+ match["in_channels"] = state_dict["conv_in.weight"].shape[1]
390
+ match["adm_in_channels"] = None
391
+ if "class_embedding.linear_1.weight" in state_dict:
392
+ match["adm_in_channels"] = state_dict["class_embedding.linear_1.weight"].shape[1]
393
+ elif "add_embedding.linear_1.weight" in state_dict:
394
+ match["adm_in_channels"] = state_dict["add_embedding.linear_1.weight"].shape[1]
395
+
396
+ # based on unet_config of SVD
397
+ SVD = {
398
+ 'use_checkpoint': False,
399
+ 'image_size': 32,
400
+ 'use_spatial_transformer': True,
401
+ 'legacy': False,
402
+ 'num_classes': 'sequential',
403
+ 'adm_in_channels': 768,
404
+ 'dtype': dtype,
405
+ 'in_channels': 8,
406
+ 'out_channels': 4,
407
+ 'model_channels': 320,
408
+ 'num_res_blocks': [2, 2, 2, 2],
409
+ 'transformer_depth': [1, 1, 1, 1, 1, 1, 0, 0],
410
+ 'transformer_depth_output': [1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0],
411
+ 'channel_mult': [1, 2, 4, 4],
412
+ 'transformer_depth_middle': 1,
413
+ 'use_linear_in_transformer': True,
414
+ 'context_dim': 1024,
415
+ 'extra_ff_mix_layer': True,
416
+ 'use_spatial_context': True,
417
+ 'merge_strategy': 'learned_with_images',
418
+ 'merge_factor': 0.0,
419
+ 'video_kernel_size': [3, 1, 1],
420
+ 'use_temporal_attention': True,
421
+ 'use_temporal_resblock': True,
422
+ 'num_heads': -1,
423
+ 'num_head_channels': 64,
424
+ }
425
+
426
+ supported_models = [SVD]
427
+
428
+ for unet_config in supported_models:
429
+ matches = True
430
+ for k in match:
431
+ if match[k] != unet_config[k]:
432
+ matches = False
433
+ break
434
+ if matches:
435
+ return comfy.model_detection.convert_config(unet_config)
436
+ return None
437
+
438
+
439
+ def svd_unet_to_diffusers(unet_config):
440
+ num_res_blocks = unet_config["num_res_blocks"]
441
+ channel_mult = unet_config["channel_mult"]
442
+ transformer_depth = unet_config["transformer_depth"][:]
443
+ transformer_depth_output = unet_config["transformer_depth_output"][:]
444
+ num_blocks = len(channel_mult)
445
+
446
+ transformers_mid = unet_config.get("transformer_depth_middle", None)
447
+
448
+ diffusers_unet_map = {}
449
+ for x in range(num_blocks):
450
+ n = 1 + (num_res_blocks[x] + 1) * x
451
+ for i in range(num_res_blocks[x]):
452
+ for b in TEMPORAL_RESNET:
453
+ diffusers_unet_map["down_blocks.{}.resnets.{}.{}".format(x, i, b)] = "input_blocks.{}.0.{}".format(n, b)
454
+ for b in UNET_MAP_RESNET:
455
+ diffusers_unet_map["down_blocks.{}.resnets.{}.spatial_res_block.{}".format(x, i, UNET_MAP_RESNET[b])] = "input_blocks.{}.0.{}".format(n, b)
456
+ diffusers_unet_map["down_blocks.{}.resnets.{}.temporal_res_block.{}".format(x, i, UNET_MAP_RESNET[b])] = "input_blocks.{}.0.time_stack.{}".format(n, b)
457
+ #diffusers_unet_map["down_blocks.{}.resnets.{}.{}".format(x, i, UNET_MAP_RESNET[b])] = "input_blocks.{}.0.{}".format(n, b)
458
+ num_transformers = transformer_depth.pop(0)
459
+ if num_transformers > 0:
460
+ for b in TEMPORAL_UNET_MAP_ATTENTIONS:
461
+ diffusers_unet_map["down_blocks.{}.attentions.{}.{}".format(x, i, b)] = "input_blocks.{}.1.{}".format(n, b)
462
+ for b in TEMPORAL_TRANSFORMER_MAP:
463
+ diffusers_unet_map["down_blocks.{}.attentions.{}.{}".format(x, i, TEMPORAL_TRANSFORMER_MAP[b])] = "input_blocks.{}.1.{}".format(n, b)
464
+ for t in range(num_transformers):
465
+ for b in TRANSFORMER_BLOCKS:
466
+ diffusers_unet_map["down_blocks.{}.attentions.{}.transformer_blocks.{}.{}".format(x, i, t, b)] = "input_blocks.{}.1.transformer_blocks.{}.{}".format(n, t, b)
467
+ for b in TEMPORAL_TRANSFORMER_BLOCKS:
468
+ diffusers_unet_map["down_blocks.{}.attentions.{}.temporal_transformer_blocks.{}.{}".format(x, i, t, b)] = "input_blocks.{}.1.time_stack.{}.{}".format(n, t, b)
469
+ n += 1
470
+ for k in ["weight", "bias"]:
471
+ diffusers_unet_map["down_blocks.{}.downsamplers.0.conv.{}".format(x, k)] = "input_blocks.{}.0.op.{}".format(n, k)
472
+
473
+ i = 0
474
+ for b in TEMPORAL_UNET_MAP_ATTENTIONS:
475
+ diffusers_unet_map["mid_block.attentions.{}.{}".format(i, b)] = "middle_block.1.{}".format(b)
476
+ for b in TEMPORAL_TRANSFORMER_MAP:
477
+ diffusers_unet_map["mid_block.attentions.{}.{}".format(i, TEMPORAL_TRANSFORMER_MAP[b])] = "middle_block.1.{}".format(b)
478
+ for t in range(transformers_mid):
479
+ for b in TRANSFORMER_BLOCKS:
480
+ diffusers_unet_map["mid_block.attentions.{}.transformer_blocks.{}.{}".format(i, t, b)] = "middle_block.1.transformer_blocks.{}.{}".format(t, b)
481
+ for b in TEMPORAL_TRANSFORMER_BLOCKS:
482
+ diffusers_unet_map["mid_block.attentions.{}.temporal_transformer_blocks.{}.{}".format(i, t, b)] = "middle_block.1.time_stack.{}.{}".format(t, b)
483
+
484
+ for i, n in enumerate([0, 2]):
485
+ for b in TEMPORAL_RESNET:
486
+ diffusers_unet_map["mid_block.resnets.{}.{}".format(i, b)] = "middle_block.{}.{}".format(n, b)
487
+ for b in UNET_MAP_RESNET:
488
+ diffusers_unet_map["mid_block.resnets.{}.spatial_res_block.{}".format(i, UNET_MAP_RESNET[b])] = "middle_block.{}.{}".format(n, b)
489
+ diffusers_unet_map["mid_block.resnets.{}.temporal_res_block.{}".format(i, UNET_MAP_RESNET[b])] = "middle_block.{}.time_stack.{}".format(n, b)
490
+ #diffusers_unet_map["mid_block.resnets.{}.{}".format(i, UNET_MAP_RESNET[b])] = "middle_block.{}.{}".format(n, b)
491
+
492
+ num_res_blocks = list(reversed(num_res_blocks))
493
+ for x in range(num_blocks):
494
+ n = (num_res_blocks[x] + 1) * x
495
+ l = num_res_blocks[x] + 1
496
+ for i in range(l):
497
+ c = 0
498
+ for b in UNET_MAP_RESNET:
499
+ diffusers_unet_map["up_blocks.{}.resnets.{}.{}".format(x, i, UNET_MAP_RESNET[b])] = "output_blocks.{}.0.{}".format(n, b)
500
+ c += 1
501
+ num_transformers = transformer_depth_output.pop()
502
+ if num_transformers > 0:
503
+ c += 1
504
+ for b in UNET_MAP_ATTENTIONS:
505
+ diffusers_unet_map["up_blocks.{}.attentions.{}.{}".format(x, i, b)] = "output_blocks.{}.1.{}".format(n, b)
506
+ for t in range(num_transformers):
507
+ for b in TRANSFORMER_BLOCKS:
508
+ diffusers_unet_map["up_blocks.{}.attentions.{}.transformer_blocks.{}.{}".format(x, i, t, b)] = "output_blocks.{}.1.transformer_blocks.{}.{}".format(n, t, b)
509
+ if i == l - 1:
510
+ for k in ["weight", "bias"]:
511
+ diffusers_unet_map["up_blocks.{}.upsamplers.0.conv.{}".format(x, k)] = "output_blocks.{}.{}.conv.{}".format(n, c, k)
512
+ n += 1
513
+
514
+ for k in UNET_MAP_BASIC:
515
+ diffusers_unet_map[k[1]] = k[0]
516
+
517
+ return diffusers_unet_map
ComfyUI-Advanced-ControlNet/adv_control/logger.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ import copy
3
+ import logging
4
+
5
+
6
+ class ColoredFormatter(logging.Formatter):
7
+ COLORS = {
8
+ "DEBUG": "\033[0;36m", # CYAN
9
+ "INFO": "\033[0;32m", # GREEN
10
+ "WARNING": "\033[0;33m", # YELLOW
11
+ "ERROR": "\033[0;31m", # RED
12
+ "CRITICAL": "\033[0;37;41m", # WHITE ON RED
13
+ "RESET": "\033[0m", # RESET COLOR
14
+ }
15
+
16
+ def format(self, record):
17
+ colored_record = copy.copy(record)
18
+ levelname = colored_record.levelname
19
+ seq = self.COLORS.get(levelname, self.COLORS["RESET"])
20
+ colored_record.levelname = f"{seq}{levelname}{self.COLORS['RESET']}"
21
+ return super().format(colored_record)
22
+
23
+
24
+ # Create a new logger
25
+ logger = logging.getLogger("Advanced-ControlNet")
26
+ logger.propagate = False
27
+
28
+ # Add handler if we don't have one.
29
+ if not logger.handlers:
30
+ handler = logging.StreamHandler(sys.stdout)
31
+ handler.setFormatter(ColoredFormatter("[%(name)s] - %(levelname)s - %(message)s"))
32
+ logger.addHandler(handler)
33
+
34
+ # Configure logger
35
+ loglevel = logging.INFO
36
+ logger.setLevel(loglevel)
ComfyUI-Advanced-ControlNet/adv_control/nodes.py ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from torch import Tensor
3
+
4
+ import folder_paths
5
+ from comfy.model_patcher import ModelPatcher
6
+
7
+ from .control import load_controlnet, convert_to_advanced, is_advanced_controlnet
8
+ from .utils import ControlWeights, LatentKeyframeGroup, TimestepKeyframeGroup, BIGMAX
9
+ from .nodes_weight import (DefaultWeights, ScaledSoftMaskedUniversalWeights, ScaledSoftUniversalWeights, SoftControlNetWeights, CustomControlNetWeights,
10
+ SoftT2IAdapterWeights, CustomT2IAdapterWeights)
11
+ from .nodes_keyframes import (LatentKeyframeGroupNode, LatentKeyframeInterpolationNode, LatentKeyframeBatchedGroupNode, LatentKeyframeNode,
12
+ TimestepKeyframeNode, TimestepKeyframeInterpolationNode, TimestepKeyframeFromStrengthListNode)
13
+ from .nodes_sparsectrl import SparseCtrlMergedLoaderAdvanced, SparseCtrlLoaderAdvanced, SparseIndexMethodNode, SparseSpreadMethodNode, RgbSparseCtrlPreprocessor, SparseWeightExtras
14
+ from .nodes_reference import ReferenceControlNetNode, ReferenceControlFinetune, ReferencePreprocessorNode
15
+ from .nodes_loosecontrol import ControlNetLoaderWithLoraAdvanced
16
+ from .nodes_deprecated import LoadImagesFromDirectory
17
+ from .logger import logger
18
+
19
+
20
+ class ControlNetLoaderAdvanced:
21
+ @classmethod
22
+ def INPUT_TYPES(s):
23
+ return {
24
+ "required": {
25
+ "control_net_name": (folder_paths.get_filename_list("controlnet"), ),
26
+ },
27
+ "optional": {
28
+ "timestep_keyframe": ("TIMESTEP_KEYFRAME", ),
29
+ }
30
+ }
31
+
32
+ RETURN_TYPES = ("CONTROL_NET", )
33
+ FUNCTION = "load_controlnet"
34
+
35
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝"
36
+
37
+ def load_controlnet(self, control_net_name,
38
+ timestep_keyframe: TimestepKeyframeGroup=None
39
+ ):
40
+ controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
41
+ controlnet = load_controlnet(controlnet_path, timestep_keyframe)
42
+ return (controlnet,)
43
+
44
+
45
+ class DiffControlNetLoaderAdvanced:
46
+ @classmethod
47
+ def INPUT_TYPES(s):
48
+ return {
49
+ "required": {
50
+ "model": ("MODEL",),
51
+ "control_net_name": (folder_paths.get_filename_list("controlnet"), )
52
+ },
53
+ "optional": {
54
+ "timestep_keyframe": ("TIMESTEP_KEYFRAME", ),
55
+ }
56
+ }
57
+
58
+ RETURN_TYPES = ("CONTROL_NET", )
59
+ FUNCTION = "load_controlnet"
60
+
61
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝"
62
+
63
+ def load_controlnet(self, control_net_name, model,
64
+ timestep_keyframe: TimestepKeyframeGroup=None
65
+ ):
66
+ controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
67
+ controlnet = load_controlnet(controlnet_path, timestep_keyframe, model)
68
+ if is_advanced_controlnet(controlnet):
69
+ controlnet.verify_all_weights()
70
+ return (controlnet,)
71
+
72
+
73
+ class AdvancedControlNetApply:
74
+ @classmethod
75
+ def INPUT_TYPES(s):
76
+ return {
77
+ "required": {
78
+ "positive": ("CONDITIONING", ),
79
+ "negative": ("CONDITIONING", ),
80
+ "control_net": ("CONTROL_NET", ),
81
+ "image": ("IMAGE", ),
82
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.01}),
83
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}),
84
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001})
85
+ },
86
+ "optional": {
87
+ "mask_optional": ("MASK", ),
88
+ "timestep_kf": ("TIMESTEP_KEYFRAME", ),
89
+ "latent_kf_override": ("LATENT_KEYFRAME", ),
90
+ "weights_override": ("CONTROL_NET_WEIGHTS", ),
91
+ "model_optional": ("MODEL",),
92
+ }
93
+ }
94
+
95
+ RETURN_TYPES = ("CONDITIONING","CONDITIONING","MODEL",)
96
+ RETURN_NAMES = ("positive", "negative", "model_opt")
97
+ FUNCTION = "apply_controlnet"
98
+
99
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝"
100
+
101
+ def apply_controlnet(self, positive, negative, control_net, image, strength, start_percent, end_percent,
102
+ mask_optional: Tensor=None, model_optional: ModelPatcher=None,
103
+ timestep_kf: TimestepKeyframeGroup=None, latent_kf_override: LatentKeyframeGroup=None,
104
+ weights_override: ControlWeights=None):
105
+ if strength == 0:
106
+ return (positive, negative, model_optional)
107
+ if model_optional:
108
+ model_optional = model_optional.clone()
109
+
110
+ control_hint = image.movedim(-1,1)
111
+ cnets = {}
112
+
113
+ out = []
114
+ for conditioning in [positive, negative]:
115
+ c = []
116
+ for t in conditioning:
117
+ d = t[1].copy()
118
+
119
+ prev_cnet = d.get('control', None)
120
+ if prev_cnet in cnets:
121
+ c_net = cnets[prev_cnet]
122
+ else:
123
+ # copy, convert to advanced if needed, and set cond
124
+ c_net = convert_to_advanced(control_net.copy()).set_cond_hint(control_hint, strength, (start_percent, end_percent))
125
+ if is_advanced_controlnet(c_net):
126
+ # disarm node check
127
+ c_net.disarm()
128
+ # if model required, verify model is passed in, and if so patch it
129
+ if c_net.require_model:
130
+ if not model_optional:
131
+ raise Exception(f"Type '{type(c_net).__name__}' requires model_optional input, but got None.")
132
+ c_net.patch_model(model=model_optional)
133
+ # apply optional parameters and overrides, if provided
134
+ if timestep_kf is not None:
135
+ c_net.set_timestep_keyframes(timestep_kf)
136
+ if latent_kf_override is not None:
137
+ c_net.latent_keyframe_override = latent_kf_override
138
+ if weights_override is not None:
139
+ c_net.weights_override = weights_override
140
+ # verify weights are compatible
141
+ c_net.verify_all_weights()
142
+ # set cond hint mask
143
+ if mask_optional is not None:
144
+ mask_optional = mask_optional.clone()
145
+ # if not in the form of a batch, make it so
146
+ if len(mask_optional.shape) < 3:
147
+ mask_optional = mask_optional.unsqueeze(0)
148
+ c_net.set_cond_hint_mask(mask_optional)
149
+ c_net.set_previous_controlnet(prev_cnet)
150
+ cnets[prev_cnet] = c_net
151
+
152
+ d['control'] = c_net
153
+ d['control_apply_to_uncond'] = False
154
+ n = [t[0], d]
155
+ c.append(n)
156
+ out.append(c)
157
+ return (out[0], out[1], model_optional)
158
+
159
+
160
+ # NODE MAPPING
161
+ NODE_CLASS_MAPPINGS = {
162
+ # Keyframes
163
+ "TimestepKeyframe": TimestepKeyframeNode,
164
+ "ACN_TimestepKeyframeInterpolation": TimestepKeyframeInterpolationNode,
165
+ "ACN_TimestepKeyframeFromStrengthList": TimestepKeyframeFromStrengthListNode,
166
+ "LatentKeyframe": LatentKeyframeNode,
167
+ "LatentKeyframeTiming": LatentKeyframeInterpolationNode,
168
+ "LatentKeyframeBatchedGroup": LatentKeyframeBatchedGroupNode,
169
+ "LatentKeyframeGroup": LatentKeyframeGroupNode,
170
+ # Conditioning
171
+ "ACN_AdvancedControlNetApply": AdvancedControlNetApply,
172
+ # Loaders
173
+ "ControlNetLoaderAdvanced": ControlNetLoaderAdvanced,
174
+ "DiffControlNetLoaderAdvanced": DiffControlNetLoaderAdvanced,
175
+ # Weights
176
+ "ScaledSoftControlNetWeights": ScaledSoftUniversalWeights,
177
+ "ScaledSoftMaskedUniversalWeights": ScaledSoftMaskedUniversalWeights,
178
+ "SoftControlNetWeights": SoftControlNetWeights,
179
+ "CustomControlNetWeights": CustomControlNetWeights,
180
+ "SoftT2IAdapterWeights": SoftT2IAdapterWeights,
181
+ "CustomT2IAdapterWeights": CustomT2IAdapterWeights,
182
+ "ACN_DefaultUniversalWeights": DefaultWeights,
183
+ # SparseCtrl
184
+ "ACN_SparseCtrlRGBPreprocessor": RgbSparseCtrlPreprocessor,
185
+ "ACN_SparseCtrlLoaderAdvanced": SparseCtrlLoaderAdvanced,
186
+ "ACN_SparseCtrlMergedLoaderAdvanced": SparseCtrlMergedLoaderAdvanced,
187
+ "ACN_SparseCtrlIndexMethodNode": SparseIndexMethodNode,
188
+ "ACN_SparseCtrlSpreadMethodNode": SparseSpreadMethodNode,
189
+ "ACN_SparseCtrlWeightExtras": SparseWeightExtras,
190
+ # Reference
191
+ "ACN_ReferencePreprocessor": ReferencePreprocessorNode,
192
+ "ACN_ReferenceControlNet": ReferenceControlNetNode,
193
+ "ACN_ReferenceControlNetFinetune": ReferenceControlFinetune,
194
+ # LOOSEControl
195
+ #"ACN_ControlNetLoaderWithLoraAdvanced": ControlNetLoaderWithLoraAdvanced,
196
+ # Deprecated
197
+ "LoadImagesFromDirectory": LoadImagesFromDirectory,
198
+ }
199
+
200
+ NODE_DISPLAY_NAME_MAPPINGS = {
201
+ # Keyframes
202
+ "TimestepKeyframe": "Timestep Keyframe 🛂🅐🅒🅝",
203
+ "ACN_TimestepKeyframeInterpolation": "Timestep Keyframe Interpolation 🛂🅐🅒🅝",
204
+ "ACN_TimestepKeyframeFromStrengthList": "Timestep Keyframe From List 🛂🅐🅒🅝",
205
+ "LatentKeyframe": "Latent Keyframe 🛂🅐🅒🅝",
206
+ "LatentKeyframeTiming": "Latent Keyframe Interpolation 🛂🅐🅒🅝",
207
+ "LatentKeyframeBatchedGroup": "Latent Keyframe From List 🛂🅐🅒🅝",
208
+ "LatentKeyframeGroup": "Latent Keyframe Group 🛂🅐🅒🅝",
209
+ # Conditioning
210
+ "ACN_AdvancedControlNetApply": "Apply Advanced ControlNet 🛂🅐🅒🅝",
211
+ # Loaders
212
+ "ControlNetLoaderAdvanced": "Load Advanced ControlNet Model 🛂🅐🅒🅝",
213
+ "DiffControlNetLoaderAdvanced": "Load Advanced ControlNet Model (diff) 🛂🅐🅒🅝",
214
+ # Weights
215
+ "ScaledSoftControlNetWeights": "Scaled Soft Weights 🛂🅐🅒🅝",
216
+ "ScaledSoftMaskedUniversalWeights": "Scaled Soft Masked Weights 🛂🅐🅒🅝",
217
+ "SoftControlNetWeights": "ControlNet Soft Weights 🛂🅐🅒🅝",
218
+ "CustomControlNetWeights": "ControlNet Custom Weights 🛂🅐🅒🅝",
219
+ "SoftT2IAdapterWeights": "T2IAdapter Soft Weights 🛂🅐🅒🅝",
220
+ "CustomT2IAdapterWeights": "T2IAdapter Custom Weights 🛂🅐🅒🅝",
221
+ "ACN_DefaultUniversalWeights": "Default Weights 🛂🅐🅒🅝",
222
+ # SparseCtrl
223
+ "ACN_SparseCtrlRGBPreprocessor": "RGB SparseCtrl 🛂🅐🅒🅝",
224
+ "ACN_SparseCtrlLoaderAdvanced": "Load SparseCtrl Model 🛂🅐🅒🅝",
225
+ "ACN_SparseCtrlMergedLoaderAdvanced": "🧪Load Merged SparseCtrl Model 🛂🅐🅒🅝",
226
+ "ACN_SparseCtrlIndexMethodNode": "SparseCtrl Index Method 🛂🅐🅒🅝",
227
+ "ACN_SparseCtrlSpreadMethodNode": "SparseCtrl Spread Method 🛂🅐🅒🅝",
228
+ "ACN_SparseCtrlWeightExtras": "SparseCtrl Weight Extras 🛂🅐🅒🅝",
229
+ # Reference
230
+ "ACN_ReferencePreprocessor": "Reference Preproccessor 🛂🅐🅒🅝",
231
+ "ACN_ReferenceControlNet": "Reference ControlNet 🛂🅐🅒🅝",
232
+ "ACN_ReferenceControlNetFinetune": "Reference ControlNet (Finetune) 🛂🅐🅒🅝",
233
+ # LOOSEControl
234
+ #"ACN_ControlNetLoaderWithLoraAdvanced": "Load Adv. ControlNet Model w/ LoRA 🛂🅐🅒🅝",
235
+ # Deprecated
236
+ "LoadImagesFromDirectory": "🚫Load Images [DEPRECATED] 🛂🅐🅒🅝",
237
+ }
ComfyUI-Advanced-ControlNet/adv_control/nodes_deprecated.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import torch
4
+
5
+ import numpy as np
6
+ from PIL import Image, ImageOps
7
+ from .utils import BIGMAX
8
+ from .logger import logger
9
+
10
+
11
+ class LoadImagesFromDirectory:
12
+ @classmethod
13
+ def INPUT_TYPES(s):
14
+ return {
15
+ "required": {
16
+ "directory": ("STRING", {"default": ""}),
17
+ },
18
+ "optional": {
19
+ "image_load_cap": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1}),
20
+ "start_index": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1}),
21
+ }
22
+ }
23
+
24
+ RETURN_TYPES = ("IMAGE", "MASK", "INT")
25
+ FUNCTION = "load_images"
26
+
27
+ CATEGORY = ""
28
+
29
+ def load_images(self, directory: str, image_load_cap: int = 0, start_index: int = 0):
30
+ if not os.path.isdir(directory):
31
+ raise FileNotFoundError(f"Directory '{directory} cannot be found.'")
32
+ dir_files = os.listdir(directory)
33
+ if len(dir_files) == 0:
34
+ raise FileNotFoundError(f"No files in directory '{directory}'.")
35
+
36
+ dir_files = sorted(dir_files)
37
+ dir_files = [os.path.join(directory, x) for x in dir_files]
38
+ # start at start_index
39
+ dir_files = dir_files[start_index:]
40
+
41
+ images = []
42
+ masks = []
43
+
44
+ limit_images = False
45
+ if image_load_cap > 0:
46
+ limit_images = True
47
+ image_count = 0
48
+
49
+ for image_path in dir_files:
50
+ if os.path.isdir(image_path):
51
+ continue
52
+ if limit_images and image_count >= image_load_cap:
53
+ break
54
+ i = Image.open(image_path)
55
+ i = ImageOps.exif_transpose(i)
56
+ image = i.convert("RGB")
57
+ image = np.array(image).astype(np.float32) / 255.0
58
+ image = torch.from_numpy(image)[None,]
59
+ if 'A' in i.getbands():
60
+ mask = np.array(i.getchannel('A')).astype(np.float32) / 255.0
61
+ mask = 1. - torch.from_numpy(mask)
62
+ else:
63
+ mask = torch.zeros((64,64), dtype=torch.float32, device="cpu")
64
+ images.append(image)
65
+ masks.append(mask)
66
+ image_count += 1
67
+
68
+ if len(images) == 0:
69
+ raise FileNotFoundError(f"No images could be loaded from directory '{directory}'.")
70
+
71
+ return (torch.cat(images, dim=0), torch.stack(masks, dim=0), image_count)
ComfyUI-Advanced-ControlNet/adv_control/nodes_keyframes.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Union
2
+ import numpy as np
3
+ from collections.abc import Iterable
4
+
5
+ from .utils import ControlWeights, TimestepKeyframe, TimestepKeyframeGroup, LatentKeyframe, LatentKeyframeGroup, BIGMIN, BIGMAX
6
+ from .utils import StrengthInterpolation as SI
7
+ from .logger import logger
8
+
9
+
10
+ class TimestepKeyframeNode:
11
+ OUTDATED_DUMMY = -39
12
+
13
+ @classmethod
14
+ def INPUT_TYPES(s):
15
+ return {
16
+ "required": {
17
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}, ),
18
+ },
19
+ "optional": {
20
+ "prev_timestep_kf": ("TIMESTEP_KEYFRAME", ),
21
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
22
+ "cn_weights": ("CONTROL_NET_WEIGHTS", ),
23
+ "latent_keyframe": ("LATENT_KEYFRAME", ),
24
+ "null_latent_kf_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
25
+ "inherit_missing": ("BOOLEAN", {"default": True}, ),
26
+ "guarantee_steps": ("INT", {"default": 1, "min": 0, "max": BIGMAX}),
27
+ "mask_optional": ("MASK", ),
28
+ }
29
+ }
30
+
31
+ RETURN_NAMES = ("TIMESTEP_KF", )
32
+ RETURN_TYPES = ("TIMESTEP_KEYFRAME", )
33
+ FUNCTION = "load_keyframe"
34
+
35
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
36
+
37
+ def load_keyframe(self,
38
+ start_percent: float,
39
+ strength: float=1.0,
40
+ cn_weights: ControlWeights=None, control_net_weights: ControlWeights=None, # old name
41
+ latent_keyframe: LatentKeyframeGroup=None,
42
+ prev_timestep_kf: TimestepKeyframeGroup=None, prev_timestep_keyframe: TimestepKeyframeGroup=None, # old name
43
+ null_latent_kf_strength: float=0.0,
44
+ inherit_missing=True,
45
+ guarantee_steps=OUTDATED_DUMMY,
46
+ guarantee_usage=True, # old input
47
+ mask_optional=None,):
48
+ # if using outdated dummy value, means node on workflow is outdated and should appropriately convert behavior
49
+ if guarantee_steps == self.OUTDATED_DUMMY:
50
+ guarantee_steps = int(guarantee_usage)
51
+ control_net_weights = control_net_weights if control_net_weights else cn_weights
52
+ prev_timestep_keyframe = prev_timestep_keyframe if prev_timestep_keyframe else prev_timestep_kf
53
+ if not prev_timestep_keyframe:
54
+ prev_timestep_keyframe = TimestepKeyframeGroup()
55
+ else:
56
+ prev_timestep_keyframe = prev_timestep_keyframe.clone()
57
+ keyframe = TimestepKeyframe(start_percent=start_percent, strength=strength, null_latent_kf_strength=null_latent_kf_strength,
58
+ control_weights=control_net_weights, latent_keyframes=latent_keyframe, inherit_missing=inherit_missing,
59
+ guarantee_steps=guarantee_steps, mask_hint_orig=mask_optional)
60
+ prev_timestep_keyframe.add(keyframe)
61
+ return (prev_timestep_keyframe,)
62
+
63
+
64
+ class TimestepKeyframeInterpolationNode:
65
+ @classmethod
66
+ def INPUT_TYPES(s):
67
+ return {
68
+ "required": {
69
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001},),
70
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}),
71
+ "strength_start": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001},),
72
+ "strength_end": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001},),
73
+ "interpolation": (SI._LIST, ),
74
+ "intervals": ("INT", {"default": 50, "min": 2, "max": 100, "step": 1}),
75
+ },
76
+ "optional": {
77
+ "prev_timestep_kf": ("TIMESTEP_KEYFRAME", ),
78
+ "cn_weights": ("CONTROL_NET_WEIGHTS", ),
79
+ "latent_keyframe": ("LATENT_KEYFRAME", ),
80
+ "null_latent_kf_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 10.0, "step": 0.001},),
81
+ "inherit_missing": ("BOOLEAN", {"default": True},),
82
+ "mask_optional": ("MASK", ),
83
+ "print_keyframes": ("BOOLEAN", {"default": False}),
84
+ }
85
+ }
86
+
87
+ RETURN_NAMES = ("TIMESTEP_KF", )
88
+ RETURN_TYPES = ("TIMESTEP_KEYFRAME", )
89
+ FUNCTION = "load_keyframe"
90
+
91
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
92
+
93
+ def load_keyframe(self,
94
+ start_percent: float, end_percent: float,
95
+ strength_start: float, strength_end: float, interpolation: str, intervals: int,
96
+ cn_weights: ControlWeights=None,
97
+ latent_keyframe: LatentKeyframeGroup=None,
98
+ prev_timestep_kf: TimestepKeyframeGroup=None,
99
+ null_latent_kf_strength: float=0.0,
100
+ inherit_missing=True,
101
+ guarantee_steps=1,
102
+ mask_optional=None, print_keyframes=False):
103
+ if not prev_timestep_kf:
104
+ prev_timestep_kf = TimestepKeyframeGroup()
105
+ else:
106
+ prev_timestep_kf = prev_timestep_kf.clone()
107
+
108
+ percents = SI.get_weights(num_from=start_percent, num_to=end_percent, length=intervals, method=SI.LINEAR)
109
+ strengths = SI.get_weights(num_from=strength_start, num_to=strength_end, length=intervals, method=interpolation)
110
+
111
+ is_first = True
112
+ for percent, strength in zip(percents, strengths):
113
+ guarantee_steps = 0
114
+ if is_first:
115
+ guarantee_steps = 1
116
+ is_first = False
117
+ prev_timestep_kf.add(TimestepKeyframe(start_percent=percent, strength=strength, null_latent_kf_strength=null_latent_kf_strength,
118
+ control_weights=cn_weights, latent_keyframes=latent_keyframe, inherit_missing=inherit_missing,
119
+ guarantee_steps=guarantee_steps, mask_hint_orig=mask_optional))
120
+ if print_keyframes:
121
+ logger.info(f"TimestepKeyframe - start_percent:{percent} = {strength}")
122
+ return (prev_timestep_kf,)
123
+
124
+
125
+ class TimestepKeyframeFromStrengthListNode:
126
+ @classmethod
127
+ def INPUT_TYPES(s):
128
+ return {
129
+ "required": {
130
+ "float_strengths": ("FLOAT", {"default": -1, "min": -1, "step": 0.001, "forceInput": True}),
131
+ "start_percent": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001},),
132
+ "end_percent": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}),
133
+ },
134
+ "optional": {
135
+ "prev_timestep_kf": ("TIMESTEP_KEYFRAME", ),
136
+ "cn_weights": ("CONTROL_NET_WEIGHTS", ),
137
+ "latent_keyframe": ("LATENT_KEYFRAME", ),
138
+ "null_latent_kf_strength": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 10.0, "step": 0.001},),
139
+ "inherit_missing": ("BOOLEAN", {"default": True},),
140
+ "mask_optional": ("MASK", ),
141
+ "print_keyframes": ("BOOLEAN", {"default": False}),
142
+ }
143
+ }
144
+
145
+ RETURN_NAMES = ("TIMESTEP_KF", )
146
+ RETURN_TYPES = ("TIMESTEP_KEYFRAME", )
147
+ FUNCTION = "load_keyframe"
148
+
149
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
150
+
151
+ def load_keyframe(self,
152
+ start_percent: float, end_percent: float,
153
+ float_strengths: float,
154
+ cn_weights: ControlWeights=None,
155
+ latent_keyframe: LatentKeyframeGroup=None,
156
+ prev_timestep_kf: TimestepKeyframeGroup=None,
157
+ null_latent_kf_strength: float=0.0,
158
+ inherit_missing=True,
159
+ guarantee_steps=1,
160
+ mask_optional=None, print_keyframes=False):
161
+ if not prev_timestep_kf:
162
+ prev_timestep_kf = TimestepKeyframeGroup()
163
+ else:
164
+ prev_timestep_kf = prev_timestep_kf.clone()
165
+
166
+ if type(float_strengths) in (float, int):
167
+ float_strengths = [float(float_strengths)]
168
+ elif isinstance(float_strengths, Iterable):
169
+ pass
170
+ else:
171
+ raise Exception(f"strengths_float must be either an iterable input or a float, but was {type(float_strengths).__repr__}.")
172
+ percents = SI.get_weights(num_from=start_percent, num_to=end_percent, length=len(float_strengths), method=SI.LINEAR)
173
+
174
+ is_first = True
175
+ for percent, strength in zip(percents, float_strengths):
176
+ guarantee_steps = 0
177
+ if is_first:
178
+ guarantee_steps = 1
179
+ is_first = False
180
+ prev_timestep_kf.add(TimestepKeyframe(start_percent=percent, strength=strength, null_latent_kf_strength=null_latent_kf_strength,
181
+ control_weights=cn_weights, latent_keyframes=latent_keyframe, inherit_missing=inherit_missing,
182
+ guarantee_steps=guarantee_steps, mask_hint_orig=mask_optional))
183
+ if print_keyframes:
184
+ logger.info(f"TimestepKeyframe - start_percent:{percent} = {strength}")
185
+ return (prev_timestep_kf,)
186
+
187
+
188
+ class LatentKeyframeNode:
189
+ @classmethod
190
+ def INPUT_TYPES(s):
191
+ return {
192
+ "required": {
193
+ "batch_index": ("INT", {"default": 0, "min": BIGMIN, "max": BIGMAX, "step": 1}),
194
+ "strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
195
+ },
196
+ "optional": {
197
+ "prev_latent_kf": ("LATENT_KEYFRAME", ),
198
+ }
199
+ }
200
+
201
+ RETURN_NAMES = ("LATENT_KF", )
202
+ RETURN_TYPES = ("LATENT_KEYFRAME", )
203
+ FUNCTION = "load_keyframe"
204
+
205
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
206
+
207
+ def load_keyframe(self,
208
+ batch_index: int,
209
+ strength: float,
210
+ prev_latent_kf: LatentKeyframeGroup=None,
211
+ prev_latent_keyframe: LatentKeyframeGroup=None, # old name
212
+ ):
213
+ prev_latent_keyframe = prev_latent_keyframe if prev_latent_keyframe else prev_latent_kf
214
+ if not prev_latent_keyframe:
215
+ prev_latent_keyframe = LatentKeyframeGroup()
216
+ else:
217
+ prev_latent_keyframe = prev_latent_keyframe.clone()
218
+ keyframe = LatentKeyframe(batch_index, strength)
219
+ prev_latent_keyframe.add(keyframe)
220
+ return (prev_latent_keyframe,)
221
+
222
+
223
+ class LatentKeyframeGroupNode:
224
+ @classmethod
225
+ def INPUT_TYPES(s):
226
+ return {
227
+ "required": {
228
+ "index_strengths": ("STRING", {"multiline": True, "default": ""}),
229
+ },
230
+ "optional": {
231
+ "prev_latent_kf": ("LATENT_KEYFRAME", ),
232
+ "latent_optional": ("LATENT", ),
233
+ "print_keyframes": ("BOOLEAN", {"default": False})
234
+ }
235
+ }
236
+
237
+ RETURN_NAMES = ("LATENT_KF", )
238
+ RETURN_TYPES = ("LATENT_KEYFRAME", )
239
+ FUNCTION = "load_keyframes"
240
+
241
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
242
+
243
+ def validate_index(self, index: int, latent_count: int = 0, is_range: bool = False, allow_negative = False) -> int:
244
+ # if part of range, do nothing
245
+ if is_range:
246
+ return index
247
+ # otherwise, validate index
248
+ # validate not out of range - only when latent_count is passed in
249
+ if latent_count > 0 and index > latent_count-1:
250
+ raise IndexError(f"Index '{index}' out of range for the total {latent_count} latents.")
251
+ # if negative, validate not out of range
252
+ if index < 0:
253
+ if not allow_negative:
254
+ raise IndexError(f"Negative indeces not allowed, but was {index}.")
255
+ conv_index = latent_count+index
256
+ if conv_index < 0:
257
+ raise IndexError(f"Index '{index}', converted to '{conv_index}' out of range for the total {latent_count} latents.")
258
+ index = conv_index
259
+ return index
260
+
261
+ def convert_to_index_int(self, raw_index: str, latent_count: int = 0, is_range: bool = False, allow_negative = False) -> int:
262
+ try:
263
+ return self.validate_index(int(raw_index), latent_count=latent_count, is_range=is_range, allow_negative=allow_negative)
264
+ except ValueError as e:
265
+ raise ValueError(f"index '{raw_index}' must be an integer.", e)
266
+
267
+ def convert_to_latent_keyframes(self, latent_indeces: str, latent_count: int) -> set[LatentKeyframe]:
268
+ if not latent_indeces:
269
+ return set()
270
+ int_latent_indeces = [i for i in range(0, latent_count)]
271
+ allow_negative = latent_count > 0
272
+ chosen_indeces = set()
273
+ # parse string - allow positive ints, negative ints, and ranges separated by ':'
274
+ groups = latent_indeces.split(",")
275
+ groups = [g.strip() for g in groups]
276
+ for g in groups:
277
+ # parse strengths - default to 1.0 if no strength given
278
+ strength = 1.0
279
+ if '=' in g:
280
+ g, strength_str = g.split("=", 1)
281
+ g = g.strip()
282
+ try:
283
+ strength = float(strength_str.strip())
284
+ except ValueError as e:
285
+ raise ValueError(f"strength '{strength_str}' must be a float.", e)
286
+ if strength < 0:
287
+ raise ValueError(f"Strength '{strength}' cannot be negative.")
288
+ # parse range of indeces (e.g. 2:16)
289
+ if ':' in g:
290
+ index_range = g.split(":", 1)
291
+ index_range = [r.strip() for r in index_range]
292
+ start_index = self.convert_to_index_int(index_range[0], latent_count=latent_count, is_range=True, allow_negative=allow_negative)
293
+ end_index = self.convert_to_index_int(index_range[1], latent_count=latent_count, is_range=True, allow_negative=allow_negative)
294
+ # if latents were passed in, base indeces on known latent count
295
+ if len(int_latent_indeces) > 0:
296
+ for i in int_latent_indeces[start_index:end_index]:
297
+ chosen_indeces.add(LatentKeyframe(i, strength))
298
+ # otherwise, assume indeces are valid
299
+ else:
300
+ for i in range(start_index, end_index):
301
+ chosen_indeces.add(LatentKeyframe(i, strength))
302
+ # parse individual indeces
303
+ else:
304
+ chosen_indeces.add(LatentKeyframe(self.convert_to_index_int(g, latent_count=latent_count, allow_negative=allow_negative), strength))
305
+ return chosen_indeces
306
+
307
+ def load_keyframes(self,
308
+ index_strengths: str,
309
+ prev_latent_kf: LatentKeyframeGroup=None,
310
+ prev_latent_keyframe: LatentKeyframeGroup=None, # old name
311
+ latent_image_opt=None,
312
+ print_keyframes=False):
313
+ prev_latent_keyframe = prev_latent_keyframe if prev_latent_keyframe else prev_latent_kf
314
+ if not prev_latent_keyframe:
315
+ prev_latent_keyframe = LatentKeyframeGroup()
316
+ else:
317
+ prev_latent_keyframe = prev_latent_keyframe.clone()
318
+ curr_latent_keyframe = LatentKeyframeGroup()
319
+
320
+ latent_count = -1
321
+ if latent_image_opt:
322
+ latent_count = latent_image_opt['samples'].size()[0]
323
+ latent_keyframes = self.convert_to_latent_keyframes(index_strengths, latent_count=latent_count)
324
+
325
+ for latent_keyframe in latent_keyframes:
326
+ curr_latent_keyframe.add(latent_keyframe)
327
+
328
+ if print_keyframes:
329
+ for keyframe in curr_latent_keyframe.keyframes:
330
+ logger.info(f"LatentKeyframe {keyframe.batch_index}={keyframe.strength}")
331
+
332
+ # replace values with prev_latent_keyframes
333
+ for latent_keyframe in prev_latent_keyframe.keyframes:
334
+ curr_latent_keyframe.add(latent_keyframe)
335
+
336
+ return (curr_latent_keyframe,)
337
+
338
+
339
+ class LatentKeyframeInterpolationNode:
340
+ @classmethod
341
+ def INPUT_TYPES(s):
342
+ return {
343
+ "required": {
344
+ "batch_index_from": ("INT", {"default": 0, "min": BIGMIN, "max": BIGMAX, "step": 1}),
345
+ "batch_index_to_excl": ("INT", {"default": 0, "min": BIGMIN, "max": BIGMAX, "step": 1}),
346
+ "strength_from": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
347
+ "strength_to": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
348
+ "interpolation": (SI._LIST, ),
349
+ },
350
+ "optional": {
351
+ "prev_latent_kf": ("LATENT_KEYFRAME", ),
352
+ "print_keyframes": ("BOOLEAN", {"default": False})
353
+ }
354
+ }
355
+
356
+ RETURN_NAMES = ("LATENT_KF", )
357
+ RETURN_TYPES = ("LATENT_KEYFRAME", )
358
+ FUNCTION = "load_keyframe"
359
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
360
+
361
+ def load_keyframe(self,
362
+ batch_index_from: int,
363
+ strength_from: float,
364
+ batch_index_to_excl: int,
365
+ strength_to: float,
366
+ interpolation: str,
367
+ prev_latent_kf: LatentKeyframeGroup=None,
368
+ prev_latent_keyframe: LatentKeyframeGroup=None, # old name
369
+ print_keyframes=False):
370
+
371
+ if (batch_index_from > batch_index_to_excl):
372
+ raise ValueError("batch_index_from must be less than or equal to batch_index_to.")
373
+
374
+ if (batch_index_from < 0 and batch_index_to_excl >= 0):
375
+ raise ValueError("batch_index_from and batch_index_to must be either both positive or both negative.")
376
+
377
+ prev_latent_keyframe = prev_latent_keyframe if prev_latent_keyframe else prev_latent_kf
378
+ if not prev_latent_keyframe:
379
+ prev_latent_keyframe = LatentKeyframeGroup()
380
+ else:
381
+ prev_latent_keyframe = prev_latent_keyframe.clone()
382
+ curr_latent_keyframe = LatentKeyframeGroup()
383
+
384
+ steps = batch_index_to_excl - batch_index_from
385
+ diff = strength_to - strength_from
386
+ if interpolation == SI.LINEAR:
387
+ weights = np.linspace(strength_from, strength_to, steps)
388
+ elif interpolation == SI.EASE_IN:
389
+ index = np.linspace(0, 1, steps)
390
+ weights = diff * np.power(index, 2) + strength_from
391
+ elif interpolation == SI.EASE_OUT:
392
+ index = np.linspace(0, 1, steps)
393
+ weights = diff * (1 - np.power(1 - index, 2)) + strength_from
394
+ elif interpolation == SI.EASE_IN_OUT:
395
+ index = np.linspace(0, 1, steps)
396
+ weights = diff * ((1 - np.cos(index * np.pi)) / 2) + strength_from
397
+
398
+ for i in range(steps):
399
+ keyframe = LatentKeyframe(batch_index_from + i, float(weights[i]))
400
+ curr_latent_keyframe.add(keyframe)
401
+
402
+ if print_keyframes:
403
+ for keyframe in curr_latent_keyframe.keyframes:
404
+ logger.info(f"LatentKeyframe {keyframe.batch_index}={keyframe.strength}")
405
+
406
+ # replace values with prev_latent_keyframes
407
+ for latent_keyframe in prev_latent_keyframe.keyframes:
408
+ curr_latent_keyframe.add(latent_keyframe)
409
+
410
+ return (curr_latent_keyframe,)
411
+
412
+
413
+ class LatentKeyframeBatchedGroupNode:
414
+ @classmethod
415
+ def INPUT_TYPES(s):
416
+ return {
417
+ "required": {
418
+ "float_strengths": ("FLOAT", {"default": -1, "min": -1, "step": 0.001, "forceInput": True}),
419
+ },
420
+ "optional": {
421
+ "prev_latent_kf": ("LATENT_KEYFRAME", ),
422
+ "print_keyframes": ("BOOLEAN", {"default": False})
423
+ }
424
+ }
425
+
426
+ RETURN_NAMES = ("LATENT_KF", )
427
+ RETURN_TYPES = ("LATENT_KEYFRAME", )
428
+ FUNCTION = "load_keyframe"
429
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/keyframes"
430
+
431
+ def load_keyframe(self, float_strengths: Union[float, list[float]],
432
+ prev_latent_kf: LatentKeyframeGroup=None,
433
+ prev_latent_keyframe: LatentKeyframeGroup=None, # old name
434
+ print_keyframes=False):
435
+ prev_latent_keyframe = prev_latent_keyframe if prev_latent_keyframe else prev_latent_kf
436
+ if not prev_latent_keyframe:
437
+ prev_latent_keyframe = LatentKeyframeGroup()
438
+ else:
439
+ prev_latent_keyframe = prev_latent_keyframe.clone()
440
+ curr_latent_keyframe = LatentKeyframeGroup()
441
+
442
+ # if received a normal float input, do nothing
443
+ if type(float_strengths) in (float, int):
444
+ logger.info("No batched float_strengths passed into Latent Keyframe Batch Group node; will not create any new keyframes.")
445
+ # if iterable, attempt to create LatentKeyframes with chosen strengths
446
+ elif isinstance(float_strengths, Iterable):
447
+ for idx, strength in enumerate(float_strengths):
448
+ keyframe = LatentKeyframe(idx, strength)
449
+ curr_latent_keyframe.add(keyframe)
450
+ else:
451
+ raise ValueError(f"Expected strengths to be an iterable input, but was {type(float_strengths).__repr__}.")
452
+
453
+ if print_keyframes:
454
+ for keyframe in curr_latent_keyframe.keyframes:
455
+ logger.info(f"LatentKeyframe {keyframe.batch_index}={keyframe.strength}")
456
+
457
+ # replace values with prev_latent_keyframes
458
+ for latent_keyframe in prev_latent_keyframe.keyframes:
459
+ curr_latent_keyframe.add(latent_keyframe)
460
+
461
+ return (curr_latent_keyframe,)
ComfyUI-Advanced-ControlNet/adv_control/nodes_loosecontrol.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import folder_paths
2
+ import comfy.utils
3
+ import comfy.model_detection
4
+ import comfy.model_management
5
+ import comfy.lora
6
+ from comfy.model_patcher import ModelPatcher
7
+
8
+ from .utils import TimestepKeyframeGroup
9
+ from .control import ControlNetAdvanced, load_controlnet
10
+
11
+
12
+
13
+
14
+ def convert_cn_lora_from_diffusers(cn_model: ModelPatcher, lora_path: str):
15
+ lora_data = comfy.utils.load_torch_file(lora_path, safe_load=True)
16
+ unet_dtype = comfy.model_management.unet_dtype()
17
+ for key, value in lora_data.items():
18
+ lora_data[key] = value.to(unet_dtype)
19
+ diffusers_keys = comfy.utils.unet_to_diffusers(cn_model.model.state_dict())
20
+
21
+ #lora_data = comfy.model_detection.unet_config_from_diffusers_unet(lora_data, dtype=unet_dtype)
22
+
23
+
24
+
25
+ #key_map = comfy.lora.model_lora_keys_unet(cn_model.model, key_map)
26
+ lora_data = comfy.lora.load_lora(lora_data, to_load=diffusers_keys)
27
+
28
+ # TODO: detect if diffusers for sure? not sure if needed at this time, since cn loras are
29
+ # only used currently for LOOSEControl, and those are all in diffusers format
30
+ #unet_dtype = comfy.model_management.unet_dtype()
31
+ #lora_data = comfy.model_detection.unet_config_from_diffusers_unet(lora_data, unet_dtype)
32
+ return lora_data
33
+
34
+
35
+ class ControlNetLoaderWithLoraAdvanced:
36
+ @classmethod
37
+ def INPUT_TYPES(s):
38
+ return {
39
+ "required": {
40
+ "control_net_name": (folder_paths.get_filename_list("controlnet"), ),
41
+ "cn_lora_name": (folder_paths.get_filename_list("controlnet"), ),
42
+ "cn_lora_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}),
43
+ },
44
+ "optional": {
45
+ "timestep_keyframe": ("TIMESTEP_KEYFRAME", ),
46
+ }
47
+ }
48
+
49
+ RETURN_TYPES = ("CONTROL_NET", )
50
+ FUNCTION = "load_controlnet"
51
+
52
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/LOOSEControl"
53
+
54
+ def load_controlnet(self, control_net_name, cn_lora_name, cn_lora_strength: float,
55
+ timestep_keyframe: TimestepKeyframeGroup=None
56
+ ):
57
+ controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
58
+ controlnet: ControlNetAdvanced = load_controlnet(controlnet_path, timestep_keyframe)
59
+ if not isinstance(controlnet, ControlNetAdvanced):
60
+ raise ValueError("Type {} is not compatible with CN LoRA features at this time.")
61
+ # now, try to load CN LoRA
62
+ lora_path = folder_paths.get_full_path("controlnet", cn_lora_name)
63
+ lora_data = convert_cn_lora_from_diffusers(cn_model=controlnet.control_model_wrapped, lora_path=lora_path)
64
+ # apply patches to wrapped control_model
65
+ controlnet.control_model_wrapped.add_patches(lora_data, strength_patch=cn_lora_strength)
66
+ # all done
67
+ return (controlnet,)
ComfyUI-Advanced-ControlNet/adv_control/nodes_reference.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import Tensor
2
+
3
+ from nodes import VAEEncode
4
+ import comfy.utils
5
+ from comfy.sd import VAE
6
+
7
+ from .control_reference import ReferenceAdvanced, ReferenceOptions, ReferenceType, ReferencePreprocWrapper
8
+
9
+
10
+ # node for ReferenceCN
11
+ class ReferenceControlNetNode:
12
+ @classmethod
13
+ def INPUT_TYPES(s):
14
+ return {
15
+ "required": {
16
+ "reference_type": (ReferenceType._LIST,),
17
+ "style_fidelity": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
18
+ "ref_weight": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
19
+ },
20
+ }
21
+
22
+ RETURN_TYPES = ("CONTROL_NET", )
23
+ FUNCTION = "load_controlnet"
24
+
25
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/Reference"
26
+
27
+ def load_controlnet(self, reference_type: str, style_fidelity: float, ref_weight: float):
28
+ ref_opts = ReferenceOptions.create_combo(reference_type=reference_type, style_fidelity=style_fidelity, ref_weight=ref_weight)
29
+ controlnet = ReferenceAdvanced(ref_opts=ref_opts, timestep_keyframes=None)
30
+ return (controlnet,)
31
+
32
+
33
+ class ReferenceControlFinetune:
34
+ @classmethod
35
+ def INPUT_TYPES(s):
36
+ return {
37
+ "required": {
38
+ "attn_style_fidelity": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
39
+ "attn_ref_weight": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
40
+ "attn_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
41
+ "adain_style_fidelity": ("FLOAT", {"default": 0.5, "min": 0.0, "max": 1.0, "step": 0.01}),
42
+ "adain_ref_weight": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
43
+ "adain_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}),
44
+ },
45
+ }
46
+
47
+ RETURN_TYPES = ("CONTROL_NET", )
48
+ FUNCTION = "load_controlnet"
49
+
50
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/Reference"
51
+
52
+ def load_controlnet(self,
53
+ attn_style_fidelity: float, attn_ref_weight: float, attn_strength: float,
54
+ adain_style_fidelity: float, adain_ref_weight: float, adain_strength: float):
55
+ ref_opts = ReferenceOptions(reference_type=ReferenceType.ATTN_ADAIN,
56
+ attn_style_fidelity=attn_style_fidelity, attn_ref_weight=attn_ref_weight, attn_strength=attn_strength,
57
+ adain_style_fidelity=adain_style_fidelity, adain_ref_weight=adain_ref_weight, adain_strength=adain_strength)
58
+ controlnet = ReferenceAdvanced(ref_opts=ref_opts, timestep_keyframes=None)
59
+ return (controlnet,)
60
+
61
+
62
+ class ReferencePreprocessorNode:
63
+ @classmethod
64
+ def INPUT_TYPES(s):
65
+ return {
66
+ "required": {
67
+ "image": ("IMAGE", ),
68
+ "vae": ("VAE", ),
69
+ "latent_size": ("LATENT", ),
70
+ }
71
+ }
72
+
73
+ RETURN_TYPES = ("IMAGE",)
74
+ RETURN_NAMES = ("proc_IMAGE",)
75
+ FUNCTION = "preprocess_images"
76
+
77
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/Reference/preprocess"
78
+
79
+ def preprocess_images(self, vae: VAE, image: Tensor, latent_size: Tensor):
80
+ # first, resize image to match latents
81
+ image = image.movedim(-1,1)
82
+ image = comfy.utils.common_upscale(image, latent_size["samples"].shape[3] * 8, latent_size["samples"].shape[2] * 8, 'nearest-exact', "center")
83
+ image = image.movedim(1,-1)
84
+ # then, vae encode
85
+ try:
86
+ image = vae.vae_encode_crop_pixels(image)
87
+ except Exception:
88
+ image = VAEEncode.vae_encode_crop_pixels(image)
89
+ encoded = vae.encode(image[:,:,:,:3])
90
+ return (ReferencePreprocWrapper(condhint=encoded),)
ComfyUI-Advanced-ControlNet/adv_control/nodes_sparsectrl.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import Tensor
2
+
3
+ import folder_paths
4
+ from nodes import VAEEncode
5
+ import comfy.utils
6
+ from comfy.sd import VAE
7
+
8
+ from .utils import TimestepKeyframeGroup
9
+ from .control_sparsectrl import SparseMethod, SparseIndexMethod, SparseSettings, SparseSpreadMethod, PreprocSparseRGBWrapper, SparseConst, SparseContextAware, get_idx_list_from_str
10
+ from .control import load_sparsectrl, load_controlnet, ControlNetAdvanced, SparseCtrlAdvanced
11
+
12
+
13
+ # node for SparseCtrl loading
14
+ class SparseCtrlLoaderAdvanced:
15
+ @classmethod
16
+ def INPUT_TYPES(s):
17
+ return {
18
+ "required": {
19
+ "sparsectrl_name": (folder_paths.get_filename_list("controlnet"), ),
20
+ "use_motion": ("BOOLEAN", {"default": True}, ),
21
+ "motion_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
22
+ "motion_scale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
23
+ },
24
+ "optional": {
25
+ "sparse_method": ("SPARSE_METHOD", ),
26
+ "tk_optional": ("TIMESTEP_KEYFRAME", ),
27
+ "context_aware": (SparseContextAware.LIST, ),
28
+ "sparse_hint_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
29
+ "sparse_nonhint_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
30
+ "sparse_mask_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
31
+ }
32
+ }
33
+
34
+ RETURN_TYPES = ("CONTROL_NET", )
35
+ FUNCTION = "load_controlnet"
36
+
37
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/SparseCtrl"
38
+
39
+ def load_controlnet(self, sparsectrl_name: str, use_motion: bool, motion_strength: float, motion_scale: float, sparse_method: SparseMethod=SparseSpreadMethod(), tk_optional: TimestepKeyframeGroup=None,
40
+ context_aware=SparseContextAware.NEAREST_HINT, sparse_hint_mult=1.0, sparse_nonhint_mult=1.0, sparse_mask_mult=1.0):
41
+ sparsectrl_path = folder_paths.get_full_path("controlnet", sparsectrl_name)
42
+ sparse_settings = SparseSettings(sparse_method=sparse_method, use_motion=use_motion, motion_strength=motion_strength, motion_scale=motion_scale,
43
+ context_aware=context_aware,
44
+ sparse_mask_mult=sparse_mask_mult, sparse_hint_mult=sparse_hint_mult, sparse_nonhint_mult=sparse_nonhint_mult)
45
+ sparsectrl = load_sparsectrl(sparsectrl_path, timestep_keyframe=tk_optional, sparse_settings=sparse_settings)
46
+ return (sparsectrl,)
47
+
48
+
49
+ class SparseCtrlMergedLoaderAdvanced:
50
+ @classmethod
51
+ def INPUT_TYPES(s):
52
+ return {
53
+ "required": {
54
+ "sparsectrl_name": (folder_paths.get_filename_list("controlnet"), ),
55
+ "control_net_name": (folder_paths.get_filename_list("controlnet"), ),
56
+ "use_motion": ("BOOLEAN", {"default": True}, ),
57
+ "motion_strength": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
58
+ "motion_scale": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
59
+ },
60
+ "optional": {
61
+ "sparse_method": ("SPARSE_METHOD", ),
62
+ "tk_optional": ("TIMESTEP_KEYFRAME", ),
63
+ }
64
+ }
65
+
66
+ RETURN_TYPES = ("CONTROL_NET", )
67
+ FUNCTION = "load_controlnet"
68
+
69
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/SparseCtrl/experimental"
70
+
71
+ def load_controlnet(self, sparsectrl_name: str, control_net_name: str, use_motion: bool, motion_strength: float, motion_scale: float, sparse_method: SparseMethod=SparseSpreadMethod(), tk_optional: TimestepKeyframeGroup=None):
72
+ sparsectrl_path = folder_paths.get_full_path("controlnet", sparsectrl_name)
73
+ controlnet_path = folder_paths.get_full_path("controlnet", control_net_name)
74
+ sparse_settings = SparseSettings(sparse_method=sparse_method, use_motion=use_motion, motion_strength=motion_strength, motion_scale=motion_scale, merged=True)
75
+ # first, load normal controlnet
76
+ controlnet = load_controlnet(controlnet_path, timestep_keyframe=tk_optional)
77
+ # confirm that controlnet is ControlNetAdvanced
78
+ if controlnet is None or type(controlnet) != ControlNetAdvanced:
79
+ raise ValueError(f"controlnet_path must point to a normal ControlNet, but instead: {type(controlnet).__name__}")
80
+ # next, load sparsectrl, making sure to load motion portion
81
+ sparsectrl = load_sparsectrl(sparsectrl_path, timestep_keyframe=tk_optional, sparse_settings=SparseSettings.default())
82
+ # now, combine state dicts
83
+ new_state_dict = controlnet.control_model.state_dict()
84
+ for key, value in sparsectrl.control_model.motion_holder.motion_wrapper.state_dict().items():
85
+ new_state_dict[key] = value
86
+ # now, reload sparsectrl with real settings
87
+ sparsectrl = load_sparsectrl(sparsectrl_path, controlnet_data=new_state_dict, timestep_keyframe=tk_optional, sparse_settings=sparse_settings)
88
+ return (sparsectrl,)
89
+
90
+
91
+ class SparseIndexMethodNode:
92
+ @classmethod
93
+ def INPUT_TYPES(s):
94
+ return {
95
+ "required": {
96
+ "indexes": ("STRING", {"default": "0"}),
97
+ }
98
+ }
99
+
100
+ RETURN_TYPES = ("SPARSE_METHOD",)
101
+ FUNCTION = "get_method"
102
+
103
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/SparseCtrl"
104
+
105
+ def get_method(self, indexes: str):
106
+ idxs = get_idx_list_from_str(indexes)
107
+ return (SparseIndexMethod(idxs),)
108
+
109
+
110
+ class SparseSpreadMethodNode:
111
+ @classmethod
112
+ def INPUT_TYPES(s):
113
+ return {
114
+ "required": {
115
+ "spread": (SparseSpreadMethod.LIST,),
116
+ }
117
+ }
118
+
119
+ RETURN_TYPES = ("SPARSE_METHOD",)
120
+ FUNCTION = "get_method"
121
+
122
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/SparseCtrl"
123
+
124
+ def get_method(self, spread: str):
125
+ return (SparseSpreadMethod(spread=spread),)
126
+
127
+
128
+ class RgbSparseCtrlPreprocessor:
129
+ @classmethod
130
+ def INPUT_TYPES(s):
131
+ return {
132
+ "required": {
133
+ "image": ("IMAGE", ),
134
+ "vae": ("VAE", ),
135
+ "latent_size": ("LATENT", ),
136
+ }
137
+ }
138
+
139
+ RETURN_TYPES = ("IMAGE",)
140
+ RETURN_NAMES = ("proc_IMAGE",)
141
+ FUNCTION = "preprocess_images"
142
+
143
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/SparseCtrl/preprocess"
144
+
145
+ def preprocess_images(self, vae: VAE, image: Tensor, latent_size: Tensor):
146
+ # first, resize image to match latents
147
+ image = image.movedim(-1,1)
148
+ image = comfy.utils.common_upscale(image, latent_size["samples"].shape[3] * 8, latent_size["samples"].shape[2] * 8, 'nearest-exact', "center")
149
+ image = image.movedim(1,-1)
150
+ # then, vae encode
151
+ try:
152
+ image = vae.vae_encode_crop_pixels(image)
153
+ except Exception:
154
+ image = VAEEncode.vae_encode_crop_pixels(image)
155
+ encoded = vae.encode(image[:,:,:,:3])
156
+ return (PreprocSparseRGBWrapper(condhint=encoded),)
157
+
158
+
159
+ class SparseWeightExtras:
160
+ @classmethod
161
+ def INPUT_TYPES(s):
162
+ return {
163
+ "optional": {
164
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
165
+ "sparse_hint_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
166
+ "sparse_nonhint_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
167
+ "sparse_mask_mult": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
168
+ }
169
+ }
170
+
171
+ RETURN_TYPES = ("CN_WEIGHTS_EXTRAS", )
172
+ RETURN_NAMES = ("cn_extras", )
173
+ FUNCTION = "create_weight_extras"
174
+
175
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/SparseCtrl/extras"
176
+
177
+ def create_weight_extras(self, cn_extras: dict[str]={}, sparse_hint_mult=1.0, sparse_nonhint_mult=1.0, sparse_mask_mult=1.0):
178
+ cn_extras = cn_extras.copy()
179
+ cn_extras[SparseConst.HINT_MULT] = sparse_hint_mult
180
+ cn_extras[SparseConst.NONHINT_MULT] = sparse_nonhint_mult
181
+ cn_extras[SparseConst.MASK_MULT] = sparse_mask_mult
182
+ return (cn_extras, )
ComfyUI-Advanced-ControlNet/adv_control/nodes_weight.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch import Tensor
2
+ import torch
3
+ from .utils import TimestepKeyframe, TimestepKeyframeGroup, ControlWeights, get_properly_arranged_t2i_weights, linear_conversion
4
+ from .logger import logger
5
+
6
+
7
+ WEIGHTS_RETURN_NAMES = ("CN_WEIGHTS", "TK_SHORTCUT")
8
+
9
+
10
+ class DefaultWeights:
11
+ @classmethod
12
+ def INPUT_TYPES(s):
13
+ return {
14
+ "optional": {
15
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
16
+ }
17
+ }
18
+
19
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
20
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
21
+ FUNCTION = "load_weights"
22
+
23
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights"
24
+
25
+ def load_weights(self, cn_extras: dict[str]={}):
26
+ weights = ControlWeights.default(extras=cn_extras)
27
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
28
+
29
+
30
+ class ScaledSoftMaskedUniversalWeights:
31
+ @classmethod
32
+ def INPUT_TYPES(s):
33
+ return {
34
+ "required": {
35
+ "mask": ("MASK", ),
36
+ "min_base_multiplier": ("FLOAT", {"default": 0.0, "min": 0.0, "max": 1.0, "step": 0.001}, ),
37
+ "max_base_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.001}, ),
38
+ #"lock_min": ("BOOLEAN", {"default": False}, ),
39
+ #"lock_max": ("BOOLEAN", {"default": False}, ),
40
+ },
41
+ "optional": {
42
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
43
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
44
+ }
45
+ }
46
+
47
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
48
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
49
+ FUNCTION = "load_weights"
50
+
51
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights"
52
+
53
+ def load_weights(self, mask: Tensor, min_base_multiplier: float, max_base_multiplier: float, lock_min=False, lock_max=False,
54
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
55
+ # normalize mask
56
+ mask = mask.clone()
57
+ x_min = 0.0 if lock_min else mask.min()
58
+ x_max = 1.0 if lock_max else mask.max()
59
+ if x_min == x_max:
60
+ mask = torch.ones_like(mask) * max_base_multiplier
61
+ else:
62
+ mask = linear_conversion(mask, x_min, x_max, min_base_multiplier, max_base_multiplier)
63
+ weights = ControlWeights.universal_mask(weight_mask=mask, uncond_multiplier=uncond_multiplier, extras=cn_extras)
64
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
65
+
66
+
67
+ class ScaledSoftUniversalWeights:
68
+ @classmethod
69
+ def INPUT_TYPES(s):
70
+ return {
71
+ "required": {
72
+ "base_multiplier": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 1.0, "step": 0.001}, ),
73
+ "flip_weights": ("BOOLEAN", {"default": False}),
74
+ },
75
+ "optional": {
76
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
77
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
78
+ }
79
+ }
80
+
81
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
82
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
83
+ FUNCTION = "load_weights"
84
+
85
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights"
86
+
87
+ def load_weights(self, base_multiplier, flip_weights, uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
88
+ weights = ControlWeights.universal(base_multiplier=base_multiplier, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=cn_extras)
89
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
90
+
91
+
92
+ class SoftControlNetWeights:
93
+ @classmethod
94
+ def INPUT_TYPES(s):
95
+ return {
96
+ "required": {
97
+ "weight_00": ("FLOAT", {"default": 0.09941396206337118, "min": 0.0, "max": 10.0, "step": 0.001}, ),
98
+ "weight_01": ("FLOAT", {"default": 0.12050177219802567, "min": 0.0, "max": 10.0, "step": 0.001}, ),
99
+ "weight_02": ("FLOAT", {"default": 0.14606275417942507, "min": 0.0, "max": 10.0, "step": 0.001}, ),
100
+ "weight_03": ("FLOAT", {"default": 0.17704576264172736, "min": 0.0, "max": 10.0, "step": 0.001}, ),
101
+ "weight_04": ("FLOAT", {"default": 0.214600924414215, "min": 0.0, "max": 10.0, "step": 0.001}, ),
102
+ "weight_05": ("FLOAT", {"default": 0.26012233262329093, "min": 0.0, "max": 10.0, "step": 0.001}, ),
103
+ "weight_06": ("FLOAT", {"default": 0.3152997971191405, "min": 0.0, "max": 10.0, "step": 0.001}, ),
104
+ "weight_07": ("FLOAT", {"default": 0.3821815722656249, "min": 0.0, "max": 10.0, "step": 0.001}, ),
105
+ "weight_08": ("FLOAT", {"default": 0.4632503906249999, "min": 0.0, "max": 10.0, "step": 0.001}, ),
106
+ "weight_09": ("FLOAT", {"default": 0.561515625, "min": 0.0, "max": 10.0, "step": 0.001}, ),
107
+ "weight_10": ("FLOAT", {"default": 0.6806249999999999, "min": 0.0, "max": 10.0, "step": 0.001}, ),
108
+ "weight_11": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 10.0, "step": 0.001}, ),
109
+ "weight_12": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
110
+ "flip_weights": ("BOOLEAN", {"default": False}),
111
+ },
112
+ "optional": {
113
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
114
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
115
+ }
116
+ }
117
+
118
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
119
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
120
+ FUNCTION = "load_weights"
121
+
122
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/ControlNet"
123
+
124
+ def load_weights(self, weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
125
+ weight_07, weight_08, weight_09, weight_10, weight_11, weight_12, flip_weights,
126
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
127
+ weights = [weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
128
+ weight_07, weight_08, weight_09, weight_10, weight_11, weight_12]
129
+ weights = ControlWeights.controlnet(weights, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=cn_extras)
130
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
131
+
132
+
133
+ class CustomControlNetWeights:
134
+ @classmethod
135
+ def INPUT_TYPES(s):
136
+ return {
137
+ "required": {
138
+ "weight_00": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
139
+ "weight_01": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
140
+ "weight_02": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
141
+ "weight_03": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
142
+ "weight_04": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
143
+ "weight_05": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
144
+ "weight_06": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
145
+ "weight_07": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
146
+ "weight_08": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
147
+ "weight_09": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
148
+ "weight_10": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
149
+ "weight_11": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
150
+ "weight_12": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
151
+ "flip_weights": ("BOOLEAN", {"default": False}),
152
+ },
153
+ "optional": {
154
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
155
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
156
+ }
157
+ }
158
+
159
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
160
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
161
+ FUNCTION = "load_weights"
162
+
163
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/ControlNet"
164
+
165
+ def load_weights(self, weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
166
+ weight_07, weight_08, weight_09, weight_10, weight_11, weight_12, flip_weights,
167
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
168
+ weights = [weight_00, weight_01, weight_02, weight_03, weight_04, weight_05, weight_06,
169
+ weight_07, weight_08, weight_09, weight_10, weight_11, weight_12]
170
+ weights = ControlWeights.controlnet(weights, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=cn_extras)
171
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
172
+
173
+
174
+ class SoftT2IAdapterWeights:
175
+ @classmethod
176
+ def INPUT_TYPES(s):
177
+ return {
178
+ "required": {
179
+ "weight_00": ("FLOAT", {"default": 0.25, "min": 0.0, "max": 10.0, "step": 0.001}, ),
180
+ "weight_01": ("FLOAT", {"default": 0.62, "min": 0.0, "max": 10.0, "step": 0.001}, ),
181
+ "weight_02": ("FLOAT", {"default": 0.825, "min": 0.0, "max": 10.0, "step": 0.001}, ),
182
+ "weight_03": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
183
+ "flip_weights": ("BOOLEAN", {"default": False}),
184
+ },
185
+ "optional": {
186
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
187
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
188
+ }
189
+ }
190
+
191
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
192
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
193
+ FUNCTION = "load_weights"
194
+
195
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒���/weights/T2IAdapter"
196
+
197
+ def load_weights(self, weight_00, weight_01, weight_02, weight_03, flip_weights,
198
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
199
+ weights = [weight_00, weight_01, weight_02, weight_03]
200
+ weights = get_properly_arranged_t2i_weights(weights)
201
+ weights = ControlWeights.t2iadapter(weights, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=cn_extras)
202
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
203
+
204
+
205
+ class CustomT2IAdapterWeights:
206
+ @classmethod
207
+ def INPUT_TYPES(s):
208
+ return {
209
+ "required": {
210
+ "weight_00": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
211
+ "weight_01": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
212
+ "weight_02": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
213
+ "weight_03": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 10.0, "step": 0.001}, ),
214
+ "flip_weights": ("BOOLEAN", {"default": False}),
215
+ },
216
+ "optional": {
217
+ "uncond_multiplier": ("FLOAT", {"default": 1.0, "min": 0.0, "max": 1.0, "step": 0.01}, ),
218
+ "cn_extras": ("CN_WEIGHTS_EXTRAS",),
219
+ }
220
+ }
221
+
222
+ RETURN_TYPES = ("CONTROL_NET_WEIGHTS", "TIMESTEP_KEYFRAME",)
223
+ RETURN_NAMES = WEIGHTS_RETURN_NAMES
224
+ FUNCTION = "load_weights"
225
+
226
+ CATEGORY = "Adv-ControlNet 🛂🅐🅒🅝/weights/T2IAdapter"
227
+
228
+ def load_weights(self, weight_00, weight_01, weight_02, weight_03, flip_weights,
229
+ uncond_multiplier: float=1.0, cn_extras: dict[str]={}):
230
+ weights = [weight_00, weight_01, weight_02, weight_03]
231
+ weights = get_properly_arranged_t2i_weights(weights)
232
+ weights = ControlWeights.t2iadapter(weights, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=cn_extras)
233
+ return (weights, TimestepKeyframeGroup.default(TimestepKeyframe(control_weights=weights)))
ComfyUI-Advanced-ControlNet/adv_control/utils.py ADDED
@@ -0,0 +1,927 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from copy import deepcopy
2
+ from typing import Callable, Union
3
+ import torch
4
+ from torch import Tensor
5
+ import torch.nn.functional
6
+ import numpy as np
7
+ import math
8
+
9
+ import comfy.ops
10
+ import comfy.utils
11
+ import comfy.sample
12
+ import comfy.samplers
13
+ import comfy.model_base
14
+
15
+ from comfy.controlnet import ControlBase
16
+ from comfy.model_patcher import ModelPatcher
17
+
18
+ from .logger import logger
19
+
20
+ BIGMIN = -(2**53-1)
21
+ BIGMAX = (2**53-1)
22
+
23
+ def load_torch_file_with_dict_factory(controlnet_data: dict[str, Tensor], orig_load_torch_file: Callable):
24
+ def load_torch_file_with_dict(*args, **kwargs):
25
+ # immediately restore load_torch_file to original version
26
+ comfy.utils.load_torch_file = orig_load_torch_file
27
+ return controlnet_data
28
+ return load_torch_file_with_dict
29
+
30
+ # wrapping len function so that it will save the thing len is trying to get the length of;
31
+ # this will be assumed to be the cond_or_uncond variable;
32
+ # automatically restores len to original function after running
33
+ def wrapper_len_factory(orig_len: Callable) -> Callable:
34
+ def wrapper_len(*args, **kwargs):
35
+ cond_or_uncond = args[0]
36
+ real_length = orig_len(*args, **kwargs)
37
+ if real_length > 0 and type(cond_or_uncond) == list and (cond_or_uncond[0] in [0, 1]):
38
+ try:
39
+ to_return = IntWithCondOrUncond(real_length)
40
+ setattr(to_return, "cond_or_uncond", cond_or_uncond)
41
+ return to_return
42
+ finally:
43
+ __builtins__["len"] = orig_len
44
+ else:
45
+ return real_length
46
+ return wrapper_len
47
+
48
+ # wrapping cond_cat function so that it will wrap around len function to get cond_or_uncond variable value
49
+ # from comfy.samplers.calc_conds_batch
50
+ def wrapper_cond_cat_factory(orig_cond_cat: Callable):
51
+ def wrapper_cond_cat(*args, **kwargs):
52
+ __builtins__["len"] = wrapper_len_factory(__builtins__["len"])
53
+ return orig_cond_cat(*args, **kwargs)
54
+ return wrapper_cond_cat
55
+ orig_cond_cat = comfy.samplers.cond_cat
56
+ comfy.samplers.cond_cat = wrapper_cond_cat_factory(orig_cond_cat)
57
+
58
+
59
+ # wrapping apply_model so that len function will be cleaned up fairly soon after being injected
60
+ def apply_model_uncond_cleanup_factory(orig_apply_model, orig_len):
61
+ def apply_model_uncond_cleanup_wrapper(self, *args, **kwargs):
62
+ __builtins__["len"] = orig_len
63
+ return orig_apply_model(self, *args, **kwargs)
64
+ return apply_model_uncond_cleanup_wrapper
65
+ global_orig_len = __builtins__["len"]
66
+ orig_apply_model = comfy.model_base.BaseModel.apply_model
67
+ comfy.model_base.BaseModel.apply_model = apply_model_uncond_cleanup_factory(orig_apply_model, global_orig_len)
68
+
69
+
70
+ def uncond_multiplier_check_cn_sample_factory(orig_comfy_sample: Callable, is_custom=False) -> Callable:
71
+ def contains_uncond_multiplier(control: Union[ControlBase, 'AdvancedControlBase']):
72
+ if control is None:
73
+ return False
74
+ if not isinstance(control, AdvancedControlBase):
75
+ return contains_uncond_multiplier(control.previous_controlnet)
76
+ # check if weights_override has an uncond_multiplier
77
+ if control.weights_override is not None and control.weights_override.has_uncond_multiplier:
78
+ return True
79
+ # check if any timestep_keyframes have an uncond_multiplier on their weights
80
+ if control.timestep_keyframes is not None:
81
+ for tk in control.timestep_keyframes.keyframes:
82
+ if tk.has_control_weights() and tk.control_weights.has_uncond_multiplier:
83
+ return True
84
+ return contains_uncond_multiplier(control.previous_controlnet)
85
+
86
+ # check if positive or negative conds contain Adv. Cns that use multiply_negative on weights
87
+ def uncond_multiplier_check_cn_sample(model: ModelPatcher, *args, **kwargs):
88
+ positive = args[-3]
89
+ negative = args[-2]
90
+ has_uncond_multiplier = False
91
+ if positive is not None:
92
+ for cond in positive:
93
+ if "control" in cond[1]:
94
+ has_uncond_multiplier = contains_uncond_multiplier(cond[1]["control"])
95
+ if has_uncond_multiplier:
96
+ break
97
+ if negative is not None and not has_uncond_multiplier:
98
+ for cond in negative:
99
+ if "control" in cond[1]:
100
+ has_uncond_multiplier = contains_uncond_multiplier(cond[1]["control"])
101
+ if has_uncond_multiplier:
102
+ break
103
+ try:
104
+ # if uncond_multiplier found, continue to use wrapped version of function
105
+ if has_uncond_multiplier:
106
+ return orig_comfy_sample(model, *args, **kwargs)
107
+ # otherwise, use original version of function to prevent even the smallest of slowdowns (0.XX%)
108
+ try:
109
+ wrapped_cond_cat = comfy.samplers.cond_cat
110
+ comfy.samplers.cond_cat = orig_cond_cat
111
+ return orig_comfy_sample(model, *args, **kwargs)
112
+ finally:
113
+ comfy.samplers.cond_cat = wrapped_cond_cat
114
+ finally:
115
+ # make sure len function is unwrapped by the time sampling is done, just in case
116
+ __builtins__["len"] = global_orig_len
117
+ return uncond_multiplier_check_cn_sample
118
+ # inject sample functions
119
+ comfy.sample.sample = uncond_multiplier_check_cn_sample_factory(comfy.sample.sample)
120
+ comfy.sample.sample_custom = uncond_multiplier_check_cn_sample_factory(comfy.sample.sample_custom, is_custom=True)
121
+
122
+
123
+ class IntWithCondOrUncond(int):
124
+ def __new__(cls, *args, **kwargs):
125
+ return super(IntWithCondOrUncond, cls).__new__(cls, *args, **kwargs)
126
+
127
+ def __init__(self, *args, **kwargs):
128
+ super().__init__()
129
+ self.cond_or_uncond = None
130
+
131
+
132
+
133
+ def get_properly_arranged_t2i_weights(initial_weights: list[float]):
134
+ new_weights = []
135
+ new_weights.extend([initial_weights[0]]*3)
136
+ new_weights.extend([initial_weights[1]]*3)
137
+ new_weights.extend([initial_weights[2]]*3)
138
+ new_weights.extend([initial_weights[3]]*3)
139
+ return new_weights
140
+
141
+
142
+ class ControlWeightType:
143
+ DEFAULT = "default"
144
+ UNIVERSAL = "universal"
145
+ T2IADAPTER = "t2iadapter"
146
+ CONTROLNET = "controlnet"
147
+ CONTROLLORA = "controllora"
148
+ CONTROLLLLITE = "controllllite"
149
+ SVD_CONTROLNET = "svd_controlnet"
150
+ SPARSECTRL = "sparsectrl"
151
+
152
+
153
+ class ControlWeights:
154
+ def __init__(self, weight_type: str, base_multiplier: float=1.0, flip_weights: bool=False, weights: list[float]=None, weight_mask: Tensor=None,
155
+ uncond_multiplier=1.0, uncond_mask: Tensor=None, extras: dict[str]={},):
156
+ self.weight_type = weight_type
157
+ self.base_multiplier = base_multiplier
158
+ self.flip_weights = flip_weights
159
+ self.weights = weights
160
+ if self.weights is not None and self.flip_weights:
161
+ self.weights.reverse()
162
+ self.weight_mask = weight_mask
163
+ self.uncond_multiplier = float(uncond_multiplier)
164
+ self.has_uncond_multiplier = not math.isclose(self.uncond_multiplier, 1.0)
165
+ self.uncond_mask = uncond_mask if uncond_mask is not None else 1.0
166
+ self.has_uncond_mask = uncond_mask is not None
167
+ self.extras = extras
168
+
169
+ def get(self, idx: int, default=1.0) -> Union[float, Tensor]:
170
+ # if weights is not none, return index
171
+ if self.weights is not None:
172
+ # this implies weights list is not aligning with expectations - will need to adjust code
173
+ if idx >= len(self.weights):
174
+ return default
175
+ return self.weights[idx]
176
+ return 1.0
177
+
178
+ def copy_with_new_weights(self, new_weights: list[float]):
179
+ return ControlWeights(weight_type=self.weight_type, base_multiplier=self.base_multiplier, flip_weights=self.flip_weights,
180
+ weights=new_weights, weight_mask=self.weight_mask, uncond_multiplier=self.uncond_multiplier, extras=self.extras)
181
+
182
+ @classmethod
183
+ def default(cls, extras: dict[str]={}):
184
+ return cls(ControlWeightType.DEFAULT, extras=extras)
185
+
186
+ @classmethod
187
+ def universal(cls, base_multiplier: float, flip_weights: bool=False, uncond_multiplier: float=1.0, extras: dict[str]={}):
188
+ return cls(ControlWeightType.UNIVERSAL, base_multiplier=base_multiplier, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=extras)
189
+
190
+ @classmethod
191
+ def universal_mask(cls, weight_mask: Tensor, uncond_multiplier: float=1.0, extras: dict[str]={}):
192
+ return cls(ControlWeightType.UNIVERSAL, weight_mask=weight_mask, uncond_multiplier=uncond_multiplier, extras=extras)
193
+
194
+ @classmethod
195
+ def t2iadapter(cls, weights: list[float]=None, flip_weights: bool=False, uncond_multiplier: float=1.0, extras: dict[str]={}):
196
+ if weights is None:
197
+ weights = [1.0]*12
198
+ return cls(ControlWeightType.T2IADAPTER, weights=weights,flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=extras)
199
+
200
+ @classmethod
201
+ def controlnet(cls, weights: list[float]=None, flip_weights: bool=False, uncond_multiplier: float=1.0, extras: dict[str]={}):
202
+ if weights is None:
203
+ weights = [1.0]*13
204
+ return cls(ControlWeightType.CONTROLNET, weights=weights, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=extras)
205
+
206
+ @classmethod
207
+ def controllora(cls, weights: list[float]=None, flip_weights: bool=False, uncond_multiplier: float=1.0, extras: dict[str]={}):
208
+ if weights is None:
209
+ weights = [1.0]*10
210
+ return cls(ControlWeightType.CONTROLLORA, weights=weights, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=extras)
211
+
212
+ @classmethod
213
+ def controllllite(cls, weights: list[float]=None, flip_weights: bool=False, uncond_multiplier: float=1.0, extras: dict[str]={}):
214
+ if weights is None:
215
+ # TODO: make this have a real value
216
+ weights = [1.0]*200
217
+ return cls(ControlWeightType.CONTROLLLLITE, weights=weights, flip_weights=flip_weights, uncond_multiplier=uncond_multiplier, extras=extras)
218
+
219
+
220
+ class StrengthInterpolation:
221
+ LINEAR = "linear"
222
+ EASE_IN = "ease-in"
223
+ EASE_OUT = "ease-out"
224
+ EASE_IN_OUT = "ease-in-out"
225
+ NONE = "none"
226
+
227
+ _LIST = [LINEAR, EASE_IN, EASE_OUT, EASE_IN_OUT]
228
+ _LIST_WITH_NONE = [LINEAR, EASE_IN, EASE_OUT, EASE_IN_OUT, NONE]
229
+
230
+ @classmethod
231
+ def get_weights(cls, num_from: float, num_to: float, length: int, method: str, reverse=False):
232
+ diff = num_to - num_from
233
+ if method == cls.LINEAR:
234
+ weights = torch.linspace(num_from, num_to, length)
235
+ elif method == cls.EASE_IN:
236
+ index = torch.linspace(0, 1, length)
237
+ weights = diff * np.power(index, 2) + num_from
238
+ elif method == cls.EASE_OUT:
239
+ index = torch.linspace(0, 1, length)
240
+ weights = diff * (1 - np.power(1 - index, 2)) + num_from
241
+ elif method == cls.EASE_IN_OUT:
242
+ index = torch.linspace(0, 1, length)
243
+ weights = diff * ((1 - np.cos(index * np.pi)) / 2) + num_from
244
+ else:
245
+ raise ValueError(f"Unrecognized interpolation method '{method}'.")
246
+ if reverse:
247
+ weights = weights.flip(dims=(0,))
248
+ return weights
249
+
250
+
251
+ class LatentKeyframe:
252
+ def __init__(self, batch_index: int, strength: float) -> None:
253
+ self.batch_index = batch_index
254
+ self.strength = strength
255
+
256
+
257
+ # always maintain sorted state (by batch_index of LatentKeyframe)
258
+ class LatentKeyframeGroup:
259
+ def __init__(self) -> None:
260
+ self.keyframes: list[LatentKeyframe] = []
261
+
262
+ def add(self, keyframe: LatentKeyframe) -> None:
263
+ added = False
264
+ # replace existing keyframe if same batch_index
265
+ for i in range(len(self.keyframes)):
266
+ if self.keyframes[i].batch_index == keyframe.batch_index:
267
+ self.keyframes[i] = keyframe
268
+ added = True
269
+ break
270
+ if not added:
271
+ self.keyframes.append(keyframe)
272
+ self.keyframes.sort(key=lambda k: k.batch_index)
273
+
274
+ def get_index(self, index: int) -> Union[LatentKeyframe, None]:
275
+ try:
276
+ return self.keyframes[index]
277
+ except IndexError:
278
+ return None
279
+
280
+ def __getitem__(self, index) -> LatentKeyframe:
281
+ return self.keyframes[index]
282
+
283
+ def is_empty(self) -> bool:
284
+ return len(self.keyframes) == 0
285
+
286
+ def clone(self) -> 'LatentKeyframeGroup':
287
+ cloned = LatentKeyframeGroup()
288
+ for tk in self.keyframes:
289
+ cloned.add(tk)
290
+ return cloned
291
+
292
+
293
+ class TimestepKeyframe:
294
+ def __init__(self,
295
+ start_percent: float = 0.0,
296
+ strength: float = 1.0,
297
+ control_weights: ControlWeights = None,
298
+ latent_keyframes: LatentKeyframeGroup = None,
299
+ null_latent_kf_strength: float = 0.0,
300
+ inherit_missing: bool = True,
301
+ guarantee_steps: int = 1,
302
+ mask_hint_orig: Tensor = None) -> None:
303
+ self.start_percent = float(start_percent)
304
+ self.start_t = 999999999.9
305
+ self.strength = strength
306
+ self.control_weights = control_weights
307
+ self.latent_keyframes = latent_keyframes
308
+ self.null_latent_kf_strength = null_latent_kf_strength
309
+ self.inherit_missing = inherit_missing
310
+ self.guarantee_steps = guarantee_steps
311
+ self.mask_hint_orig = mask_hint_orig
312
+
313
+ def has_control_weights(self):
314
+ return self.control_weights is not None
315
+
316
+ def has_latent_keyframes(self):
317
+ return self.latent_keyframes is not None
318
+
319
+ def has_mask_hint(self):
320
+ return self.mask_hint_orig is not None
321
+
322
+
323
+ @staticmethod
324
+ def default() -> 'TimestepKeyframe':
325
+ return TimestepKeyframe(start_percent=0.0, guarantee_steps=0)
326
+
327
+
328
+ # always maintain sorted state (by start_percent of TimestepKeyFrame)
329
+ class TimestepKeyframeGroup:
330
+ def __init__(self) -> None:
331
+ self.keyframes: list[TimestepKeyframe] = []
332
+ self.keyframes.append(TimestepKeyframe.default())
333
+
334
+ def add(self, keyframe: TimestepKeyframe) -> None:
335
+ # add to end of list, then sort
336
+ self.keyframes.append(keyframe)
337
+ self.keyframes = get_sorted_list_via_attr(self.keyframes, attr="start_percent")
338
+
339
+ def get_index(self, index: int) -> Union[TimestepKeyframe, None]:
340
+ try:
341
+ return self.keyframes[index]
342
+ except IndexError:
343
+ return None
344
+
345
+ def has_index(self, index: int) -> int:
346
+ return index >=0 and index < len(self.keyframes)
347
+
348
+ def __getitem__(self, index) -> TimestepKeyframe:
349
+ return self.keyframes[index]
350
+
351
+ def __len__(self) -> int:
352
+ return len(self.keyframes)
353
+
354
+ def is_empty(self) -> bool:
355
+ return len(self.keyframes) == 0
356
+
357
+ def clone(self) -> 'TimestepKeyframeGroup':
358
+ cloned = TimestepKeyframeGroup()
359
+ # already sorted, so don't use add function to make cloning quicker
360
+ for tk in self.keyframes:
361
+ cloned.keyframes.append(tk)
362
+ return cloned
363
+
364
+ @classmethod
365
+ def default(cls, keyframe: TimestepKeyframe) -> 'TimestepKeyframeGroup':
366
+ group = cls()
367
+ group.keyframes[0] = keyframe
368
+ return group
369
+
370
+
371
+ class AbstractPreprocWrapper:
372
+ error_msg = "Invalid use of [InsertHere] output. The output of [InsertHere] preprocessor is NOT a usual image, but a latent pretending to be an image - you must connect the output directly to an Apply ControlNet node (advanced or otherwise). It cannot be used for anything else that accepts IMAGE input."
373
+ def __init__(self, condhint: Tensor):
374
+ self.condhint = condhint
375
+
376
+ def movedim(self, *args, **kwargs):
377
+ return self
378
+
379
+ def __getattr__(self, *args, **kwargs):
380
+ raise AttributeError(self.error_msg)
381
+
382
+ def __setattr__(self, name, value):
383
+ if name != "condhint":
384
+ raise AttributeError(self.error_msg)
385
+ super().__setattr__(name, value)
386
+
387
+ def __iter__(self, *args, **kwargs):
388
+ raise AttributeError(self.error_msg)
389
+
390
+ def __next__(self, *args, **kwargs):
391
+ raise AttributeError(self.error_msg)
392
+
393
+ def __len__(self, *args, **kwargs):
394
+ raise AttributeError(self.error_msg)
395
+
396
+ def __getitem__(self, *args, **kwargs):
397
+ raise AttributeError(self.error_msg)
398
+
399
+ def __setitem__(self, *args, **kwargs):
400
+ raise AttributeError(self.error_msg)
401
+
402
+
403
+ # depending on model, AnimateDiff may inject into GroupNorm, so make sure GroupNorm will be clean
404
+ class disable_weight_init_clean_groupnorm(comfy.ops.disable_weight_init):
405
+ class GroupNorm(comfy.ops.disable_weight_init.GroupNorm):
406
+ def forward_comfy_cast_weights(self, input):
407
+ weight, bias = comfy.ops.cast_bias_weight(self, input)
408
+ return torch.nn.functional.group_norm(input, self.num_groups, weight, bias, self.eps)
409
+
410
+ def forward(self, input):
411
+ if self.comfy_cast_weights:
412
+ return self.forward_comfy_cast_weights(input)
413
+ else:
414
+ return torch.nn.functional.group_norm(input, self.num_groups, self.weight, self.bias, self.eps)
415
+
416
+ class manual_cast_clean_groupnorm(comfy.ops.manual_cast):
417
+ class GroupNorm(disable_weight_init_clean_groupnorm.GroupNorm):
418
+ comfy_cast_weights = True
419
+
420
+
421
+ # adapted from comfy/sample.py
422
+ def prepare_mask_batch(mask: Tensor, shape: Tensor, multiplier: int=1, match_dim1=False):
423
+ mask = mask.clone()
424
+ mask = torch.nn.functional.interpolate(mask.reshape((-1, 1, mask.shape[-2], mask.shape[-1])), size=(shape[2]*multiplier, shape[3]*multiplier), mode="bilinear")
425
+ if match_dim1:
426
+ mask = torch.cat([mask] * shape[1], dim=1)
427
+ return mask
428
+
429
+
430
+ # applies min-max normalization, from:
431
+ # https://stackoverflow.com/questions/68791508/min-max-normalization-of-a-tensor-in-pytorch
432
+ def normalize_min_max(x: Tensor, new_min = 0.0, new_max = 1.0):
433
+ x_min, x_max = x.min(), x.max()
434
+ return (((x - x_min)/(x_max - x_min)) * (new_max - new_min)) + new_min
435
+
436
+ def linear_conversion(x, x_min=0.0, x_max=1.0, new_min=0.0, new_max=1.0):
437
+ return (((x - x_min)/(x_max - x_min)) * (new_max - new_min)) + new_min
438
+
439
+ def extend_to_batch_size(tensor: Tensor, batch_size: int):
440
+ if tensor.shape[0] > batch_size:
441
+ return tensor[:batch_size]
442
+ elif tensor.shape[0] < batch_size:
443
+ remainder = batch_size-tensor.shape[0]
444
+ return torch.cat([tensor] + [tensor[-1:]]*remainder, dim=0)
445
+ return tensor
446
+
447
+ def broadcast_image_to_extend(tensor, target_batch_size, batched_number, except_one=True):
448
+ current_batch_size = tensor.shape[0]
449
+ #print(current_batch_size, target_batch_size)
450
+ if except_one and current_batch_size == 1:
451
+ return tensor
452
+
453
+ per_batch = target_batch_size // batched_number
454
+ tensor = tensor[:per_batch]
455
+
456
+ if per_batch > tensor.shape[0]:
457
+ tensor = extend_to_batch_size(tensor=tensor, batch_size=per_batch)
458
+
459
+ current_batch_size = tensor.shape[0]
460
+ if current_batch_size == target_batch_size:
461
+ return tensor
462
+ else:
463
+ return torch.cat([tensor] * batched_number, dim=0)
464
+
465
+
466
+ # from https://stackoverflow.com/a/24621200
467
+ def deepcopy_with_sharing(obj, shared_attribute_names, memo=None):
468
+ '''
469
+ Deepcopy an object, except for a given list of attributes, which should
470
+ be shared between the original object and its copy.
471
+
472
+ obj is some object
473
+ shared_attribute_names: A list of strings identifying the attributes that
474
+ should be shared between the original and its copy.
475
+ memo is the dictionary passed into __deepcopy__. Ignore this argument if
476
+ not calling from within __deepcopy__.
477
+ '''
478
+ assert isinstance(shared_attribute_names, (list, tuple))
479
+
480
+ shared_attributes = {k: getattr(obj, k) for k in shared_attribute_names}
481
+
482
+ if hasattr(obj, '__deepcopy__'):
483
+ # Do hack to prevent infinite recursion in call to deepcopy
484
+ deepcopy_method = obj.__deepcopy__
485
+ obj.__deepcopy__ = None
486
+
487
+ for attr in shared_attribute_names:
488
+ del obj.__dict__[attr]
489
+
490
+ clone = deepcopy(obj)
491
+
492
+ for attr, val in shared_attributes.items():
493
+ setattr(obj, attr, val)
494
+ setattr(clone, attr, val)
495
+
496
+ if hasattr(obj, '__deepcopy__'):
497
+ # Undo hack
498
+ obj.__deepcopy__ = deepcopy_method
499
+ del clone.__deepcopy__
500
+
501
+ return clone
502
+
503
+
504
+ def get_sorted_list_via_attr(objects: list, attr: str) -> list:
505
+ if not objects:
506
+ return objects
507
+ elif len(objects) <= 1:
508
+ return [x for x in objects]
509
+ # now that we know we have to sort, do it following these rules:
510
+ # a) if objects have same value of attribute, maintain their relative order
511
+ # b) perform sorting of the groups of objects with same attributes
512
+ unique_attrs = {}
513
+ for o in objects:
514
+ val_attr = getattr(o, attr)
515
+ attr_list: list = unique_attrs.get(val_attr, list())
516
+ attr_list.append(o)
517
+ if val_attr not in unique_attrs:
518
+ unique_attrs[val_attr] = attr_list
519
+ # now that we have the unique attr values grouped together in relative order, sort them by key
520
+ sorted_attrs = dict(sorted(unique_attrs.items()))
521
+ # now flatten out the dict into a list to return
522
+ sorted_list = []
523
+ for object_list in sorted_attrs.values():
524
+ sorted_list.extend(object_list)
525
+ return sorted_list
526
+
527
+
528
+ class WeightTypeException(TypeError):
529
+ "Raised when weight not compatible with AdvancedControlBase object"
530
+ pass
531
+
532
+
533
+ class AdvancedControlBase:
534
+ def __init__(self, base: ControlBase, timestep_keyframes: TimestepKeyframeGroup, weights_default: ControlWeights, require_model=False):
535
+ self.base = base
536
+ self.compatible_weights = [ControlWeightType.UNIVERSAL, ControlWeightType.DEFAULT]
537
+ self.add_compatible_weight(weights_default.weight_type)
538
+ # mask for which parts of controlnet output to keep
539
+ self.mask_cond_hint_original = None
540
+ self.mask_cond_hint = None
541
+ self.tk_mask_cond_hint_original = None
542
+ self.tk_mask_cond_hint = None
543
+ self.weight_mask_cond_hint = None
544
+ # actual index values
545
+ self.sub_idxs = None
546
+ self.full_latent_length = 0
547
+ self.context_length = 0
548
+ # timesteps
549
+ self.t: Tensor = None
550
+ self.batched_number: Union[int, IntWithCondOrUncond] = None
551
+ self.batch_size: int = 0
552
+ # weights + override
553
+ self.weights: ControlWeights = None
554
+ self.weights_default: ControlWeights = weights_default
555
+ self.weights_override: ControlWeights = None
556
+ # latent keyframe + override
557
+ self.latent_keyframes: LatentKeyframeGroup = None
558
+ self.latent_keyframe_override: LatentKeyframeGroup = None
559
+ # initialize timestep_keyframes
560
+ self.set_timestep_keyframes(timestep_keyframes)
561
+ # override some functions
562
+ self.get_control = self.get_control_inject
563
+ self.control_merge = self.control_merge_inject
564
+ self.pre_run = self.pre_run_inject
565
+ self.cleanup = self.cleanup_inject
566
+ self.set_previous_controlnet = self.set_previous_controlnet_inject
567
+ # require model to be passed into Apply Advanced ControlNet 🛂🅐🅒🅝 node
568
+ self.require_model = require_model
569
+ # disarm - when set to False, used to force usage of Apply Advanced ControlNet 🛂🅐🅒🅝 node (which will set it to True)
570
+ self.disarmed = not require_model
571
+
572
+ def patch_model(self, model: ModelPatcher):
573
+ pass
574
+
575
+ def add_compatible_weight(self, control_weight_type: str):
576
+ self.compatible_weights.append(control_weight_type)
577
+
578
+ def verify_all_weights(self, throw_error=True):
579
+ # first, check if override exists - if so, only need to check the override
580
+ if self.weights_override is not None:
581
+ if self.weights_override.weight_type not in self.compatible_weights:
582
+ msg = f"Weight override is type {self.weights_override.weight_type}, but loaded {type(self).__name__}" + \
583
+ f"only supports {self.compatible_weights} weights."
584
+ raise WeightTypeException(msg)
585
+ # otherwise, check all timestep keyframe weights
586
+ else:
587
+ for tk in self.timestep_keyframes.keyframes:
588
+ if tk.has_control_weights() and tk.control_weights.weight_type not in self.compatible_weights:
589
+ msg = f"Weight on Timestep Keyframe with start_percent={tk.start_percent} is type " + \
590
+ f"{tk.control_weights.weight_type}, but loaded {type(self).__name__} only supports {self.compatible_weights} weights."
591
+ raise WeightTypeException(msg)
592
+
593
+ def set_timestep_keyframes(self, timestep_keyframes: TimestepKeyframeGroup):
594
+ self.timestep_keyframes = timestep_keyframes if timestep_keyframes else TimestepKeyframeGroup()
595
+ # prepare first timestep_keyframe related stuff
596
+ self._current_timestep_keyframe = None
597
+ self._current_timestep_index = -1
598
+ self._current_used_steps = 0
599
+ self.weights = None
600
+ self.latent_keyframes = None
601
+
602
+ def prepare_current_timestep(self, t: Tensor, batched_number: int):
603
+ self.t = float(t[0])
604
+ self.batched_number = batched_number
605
+ self.batch_size = len(t)
606
+ # get current step percent
607
+ curr_t: float = self.t
608
+ prev_index = self._current_timestep_index
609
+ # if met guaranteed steps (or no current keyframe), look for next keyframe in case need to switch
610
+ if self._current_timestep_keyframe is None or self._current_used_steps >= self._current_timestep_keyframe.guarantee_steps:
611
+ # if has next index, loop through and see if need to switch
612
+ if self.timestep_keyframes.has_index(self._current_timestep_index+1):
613
+ for i in range(self._current_timestep_index+1, len(self.timestep_keyframes)):
614
+ eval_tk = self.timestep_keyframes[i]
615
+ # check if start percent is less or equal to curr_t
616
+ if eval_tk.start_t >= curr_t:
617
+ self._current_timestep_index = i
618
+ self._current_timestep_keyframe = eval_tk
619
+ self._current_used_steps = 0
620
+ # keep track of control weights, latent keyframes, and masks,
621
+ # accounting for inherit_missing
622
+ if self._current_timestep_keyframe.has_control_weights():
623
+ self.weights = self._current_timestep_keyframe.control_weights
624
+ elif not self._current_timestep_keyframe.inherit_missing:
625
+ self.weights = self.weights_default
626
+ if self._current_timestep_keyframe.has_latent_keyframes():
627
+ self.latent_keyframes = self._current_timestep_keyframe.latent_keyframes
628
+ elif not self._current_timestep_keyframe.inherit_missing:
629
+ self.latent_keyframes = None
630
+ if self._current_timestep_keyframe.has_mask_hint():
631
+ self.tk_mask_cond_hint_original = self._current_timestep_keyframe.mask_hint_orig
632
+ elif not self._current_timestep_keyframe.inherit_missing:
633
+ del self.tk_mask_cond_hint_original
634
+ self.tk_mask_cond_hint_original = None
635
+ # if guarantee_steps greater than zero, stop searching for other keyframes
636
+ if self._current_timestep_keyframe.guarantee_steps > 0:
637
+ break
638
+ # if eval_tk is outside of percent range, stop looking further
639
+ else:
640
+ break
641
+
642
+ # update steps current keyframe is used
643
+ self._current_used_steps += 1
644
+ # if index changed, apply overrides
645
+ if prev_index != self._current_timestep_index:
646
+ if self.weights_override is not None:
647
+ self.weights = self.weights_override
648
+ if self.latent_keyframe_override is not None:
649
+ self.latent_keyframes = self.latent_keyframe_override
650
+
651
+ # make sure weights and latent_keyframes are in a workable state
652
+ # Note: each AdvancedControlBase should create their own get_universal_weights class
653
+ self.prepare_weights()
654
+
655
+ def prepare_weights(self):
656
+ if self.weights is None:
657
+ self.weights = self.weights_default
658
+ elif self.weights.weight_type == ControlWeightType.UNIVERSAL:
659
+ # if universal and weight_mask present, no need to convert
660
+ if self.weights.weight_mask is not None:
661
+ return
662
+ self.weights = self.get_universal_weights()
663
+
664
+ def get_universal_weights(self) -> ControlWeights:
665
+ return self.weights
666
+
667
+ def set_cond_hint_mask(self, mask_hint):
668
+ self.mask_cond_hint_original = mask_hint
669
+ return self
670
+
671
+ def pre_run_inject(self, model, percent_to_timestep_function):
672
+ self.base.pre_run(model, percent_to_timestep_function)
673
+ self.pre_run_advanced(model, percent_to_timestep_function)
674
+
675
+ def pre_run_advanced(self, model, percent_to_timestep_function):
676
+ # for each timestep keyframe, calculate the start_t
677
+ for tk in self.timestep_keyframes.keyframes:
678
+ tk.start_t = percent_to_timestep_function(tk.start_percent)
679
+ # clear variables
680
+ self.cleanup_advanced()
681
+
682
+ def set_previous_controlnet_inject(self, *args, **kwargs):
683
+ to_return = self.base.set_previous_controlnet(*args, **kwargs)
684
+ if not self.disarmed:
685
+ raise Exception(f"Type '{type(self).__name__}' must be used with Apply Advanced ControlNet 🛂🅐🅒🅝 node (with model_optional passed in); otherwise, it will not work.")
686
+ return to_return
687
+
688
+ def disarm(self):
689
+ self.disarmed = True
690
+
691
+ def should_run(self):
692
+ if math.isclose(self.strength, 0.0) or math.isclose(self._current_timestep_keyframe.strength, 0.0):
693
+ return False
694
+ if self.timestep_range is not None:
695
+ if self.t > self.timestep_range[0] or self.t < self.timestep_range[1]:
696
+ return False
697
+ return True
698
+
699
+ def get_control_inject(self, x_noisy, t, cond, batched_number):
700
+ # prepare timestep and everything related
701
+ self.prepare_current_timestep(t=t, batched_number=batched_number)
702
+ # if should not perform any actions for the controlnet, exit without doing any work
703
+ if self.strength == 0.0 or self._current_timestep_keyframe.strength == 0.0:
704
+ return self.default_control_actions(x_noisy, t, cond, batched_number)
705
+ # otherwise, perform normal function
706
+ return self.get_control_advanced(x_noisy, t, cond, batched_number)
707
+
708
+ def get_control_advanced(self, x_noisy, t, cond, batched_number):
709
+ return self.default_control_actions(x_noisy, t, cond, batched_number)
710
+
711
+ def default_control_actions(self, x_noisy, t, cond, batched_number):
712
+ control_prev = None
713
+ if self.previous_controlnet is not None:
714
+ control_prev = self.previous_controlnet.get_control(x_noisy, t, cond, batched_number)
715
+ return control_prev
716
+
717
+ def calc_weight(self, idx: int, x: Tensor, layers: int) -> Union[float, Tensor]:
718
+ if self.weights.weight_mask is not None:
719
+ # prepare weight mask
720
+ self.prepare_weight_mask_cond_hint(x, self.batched_number)
721
+ # adjust mask for current layer and return
722
+ return torch.pow(self.weight_mask_cond_hint, self.get_calc_pow(idx=idx, layers=layers))
723
+ return self.weights.get(idx=idx)
724
+
725
+ def get_calc_pow(self, idx: int, layers: int) -> int:
726
+ return (layers-1)-idx
727
+
728
+ def calc_latent_keyframe_mults(self, x: Tensor, batched_number: int) -> Tensor:
729
+ # apply strengths, and get batch indeces to null out
730
+ # AKA latents that should not be influenced by ControlNet
731
+ final_mults = [1.0] * x.shape[0]
732
+ if self.latent_keyframes:
733
+ latent_count = x.shape[0] // batched_number
734
+ indeces_to_null = set(range(latent_count))
735
+ mapped_indeces = None
736
+ # if expecting subdivision, will need to translate between subset and actual idx values
737
+ if self.sub_idxs:
738
+ mapped_indeces = {}
739
+ for i, actual in enumerate(self.sub_idxs):
740
+ mapped_indeces[actual] = i
741
+ for keyframe in self.latent_keyframes:
742
+ real_index = keyframe.batch_index
743
+ # if negative, count from end
744
+ if real_index < 0:
745
+ real_index += latent_count if self.sub_idxs is None else self.full_latent_length
746
+
747
+ # if not mapping indeces, what you see is what you get
748
+ if mapped_indeces is None:
749
+ if real_index in indeces_to_null:
750
+ indeces_to_null.remove(real_index)
751
+ # otherwise, see if batch_index is even included in this set of latents
752
+ else:
753
+ real_index = mapped_indeces.get(real_index, None)
754
+ if real_index is None:
755
+ continue
756
+ indeces_to_null.remove(real_index)
757
+
758
+ # if real_index is outside the bounds of latents, don't apply
759
+ if real_index >= latent_count or real_index < 0:
760
+ continue
761
+
762
+ # apply strength for each batched cond/uncond
763
+ for b in range(batched_number):
764
+ final_mults[(latent_count*b)+real_index] = keyframe.strength
765
+ # null them out by multiplying by null_latent_kf_strength
766
+ for batch_index in indeces_to_null:
767
+ # apply null for each batched cond/uncond
768
+ for b in range(batched_number):
769
+ final_mults[(latent_count*b)+batch_index] = self._current_timestep_keyframe.null_latent_kf_strength
770
+ # convert final_mults into tensor and match expected dimension count
771
+ final_tensor = torch.tensor(final_mults, dtype=x.dtype, device=x.device)
772
+ while len(final_tensor.shape) < len(x.shape):
773
+ final_tensor = final_tensor.unsqueeze(-1)
774
+ return final_tensor
775
+
776
+ def apply_advanced_strengths_and_masks(self, x: Tensor, batched_number: int):
777
+ # handle weight's uncond_multiplier, if applicable
778
+ if self.weights.has_uncond_multiplier:
779
+ cond_or_uncond = self.batched_number.cond_or_uncond
780
+ actual_length = x.size(0) // batched_number
781
+ for idx, cond_type in enumerate(cond_or_uncond):
782
+ # if uncond, set to weight's uncond_multiplier
783
+ if cond_type == 1:
784
+ x[actual_length*idx:actual_length*(idx+1)] *= self.weights.uncond_multiplier
785
+ if self.weights.has_uncond_mask:
786
+ pass
787
+
788
+ if self.latent_keyframes is not None:
789
+ x[:] = x[:] * self.calc_latent_keyframe_mults(x=x, batched_number=batched_number)
790
+ # apply masks, resizing mask to required dims
791
+ if self.mask_cond_hint is not None:
792
+ masks = prepare_mask_batch(self.mask_cond_hint, x.shape)
793
+ x[:] = x[:] * masks
794
+ if self.tk_mask_cond_hint is not None:
795
+ masks = prepare_mask_batch(self.tk_mask_cond_hint, x.shape)
796
+ x[:] = x[:] * masks
797
+ # apply timestep keyframe strengths
798
+ if self._current_timestep_keyframe.strength != 1.0:
799
+ x[:] *= self._current_timestep_keyframe.strength
800
+
801
+ def control_merge_inject(self: 'AdvancedControlBase', control_input, control_output, control_prev, output_dtype):
802
+ out = {'input':[], 'middle':[], 'output': []}
803
+
804
+ if control_input is not None:
805
+ for i in range(len(control_input)):
806
+ key = 'input'
807
+ x = control_input[i]
808
+ if x is not None:
809
+ self.apply_advanced_strengths_and_masks(x, self.batched_number)
810
+
811
+ x *= self.strength * self.calc_weight(i, x, len(control_input))
812
+ if x.dtype != output_dtype:
813
+ x = x.to(output_dtype)
814
+ out[key].insert(0, x)
815
+
816
+ if control_output is not None:
817
+ for i in range(len(control_output)):
818
+ if i == (len(control_output) - 1):
819
+ key = 'middle'
820
+ index = 0
821
+ else:
822
+ key = 'output'
823
+ index = i
824
+ x = control_output[i]
825
+ if x is not None:
826
+ self.apply_advanced_strengths_and_masks(x, self.batched_number)
827
+
828
+ if self.global_average_pooling:
829
+ x = torch.mean(x, dim=(2, 3), keepdim=True).repeat(1, 1, x.shape[2], x.shape[3])
830
+
831
+ x *= self.strength * self.calc_weight(i, x, len(control_output))
832
+ if x.dtype != output_dtype:
833
+ x = x.to(output_dtype)
834
+
835
+ out[key].append(x)
836
+ if control_prev is not None:
837
+ for x in ['input', 'middle', 'output']:
838
+ o = out[x]
839
+ for i in range(len(control_prev[x])):
840
+ prev_val = control_prev[x][i]
841
+ if i >= len(o):
842
+ o.append(prev_val)
843
+ elif prev_val is not None:
844
+ if o[i] is None:
845
+ o[i] = prev_val
846
+ else:
847
+ if o[i].shape[0] < prev_val.shape[0]:
848
+ o[i] = prev_val + o[i]
849
+ else:
850
+ o[i] += prev_val
851
+ return out
852
+
853
+ def prepare_mask_cond_hint(self, x_noisy: Tensor, t, cond, batched_number, dtype=None, direct_attn=False):
854
+ self._prepare_mask("mask_cond_hint", self.mask_cond_hint_original, x_noisy, t, cond, batched_number, dtype, direct_attn=direct_attn)
855
+ self.prepare_tk_mask_cond_hint(x_noisy, t, cond, batched_number, dtype, direct_attn=direct_attn)
856
+
857
+ def prepare_tk_mask_cond_hint(self, x_noisy: Tensor, t, cond, batched_number, dtype=None, direct_attn=False):
858
+ return self._prepare_mask("tk_mask_cond_hint", self._current_timestep_keyframe.mask_hint_orig, x_noisy, t, cond, batched_number, dtype, direct_attn=direct_attn)
859
+
860
+ def prepare_weight_mask_cond_hint(self, x_noisy: Tensor, batched_number, dtype=None):
861
+ return self._prepare_mask("weight_mask_cond_hint", self.weights.weight_mask, x_noisy, t=None, cond=None, batched_number=batched_number, dtype=dtype, direct_attn=True)
862
+
863
+ def _prepare_mask(self, attr_name, orig_mask: Tensor, x_noisy: Tensor, t, cond, batched_number, dtype=None, direct_attn=False):
864
+ # make mask appropriate dimensions, if present
865
+ if orig_mask is not None:
866
+ out_mask = getattr(self, attr_name)
867
+ multiplier = 1 if direct_attn else 8
868
+ if self.sub_idxs is not None or out_mask is None or x_noisy.shape[2] * multiplier != out_mask.shape[1] or x_noisy.shape[3] * multiplier != out_mask.shape[2]:
869
+ self._reset_attr(attr_name)
870
+ del out_mask
871
+ # TODO: perform upscale on only the sub_idxs masks at a time instead of all to conserve RAM
872
+ # resize mask and match batch count
873
+ out_mask = prepare_mask_batch(orig_mask, x_noisy.shape, multiplier=multiplier)
874
+ actual_latent_length = x_noisy.shape[0] // batched_number
875
+ out_mask = extend_to_batch_size(out_mask, actual_latent_length if self.sub_idxs is None else self.full_latent_length)
876
+ if self.sub_idxs is not None:
877
+ out_mask = out_mask[self.sub_idxs]
878
+ # make cond_hint_mask length match x_noise
879
+ if x_noisy.shape[0] != out_mask.shape[0]:
880
+ out_mask = broadcast_image_to_extend(out_mask, x_noisy.shape[0], batched_number)
881
+ # default dtype to be same as x_noisy
882
+ if dtype is None:
883
+ dtype = x_noisy.dtype
884
+ setattr(self, attr_name, out_mask.to(dtype=dtype).to(self.device))
885
+ del out_mask
886
+
887
+ def _reset_attr(self, attr_name, new_value=None):
888
+ if hasattr(self, attr_name):
889
+ delattr(self, attr_name)
890
+ setattr(self, attr_name, new_value)
891
+
892
+ def cleanup_inject(self):
893
+ self.base.cleanup()
894
+ self.cleanup_advanced()
895
+
896
+ def cleanup_advanced(self):
897
+ self.sub_idxs = None
898
+ self.full_latent_length = 0
899
+ self.context_length = 0
900
+ self.t = None
901
+ self.batched_number = None
902
+ self.batch_size = 0
903
+ self.weights = None
904
+ self.latent_keyframes = None
905
+ # timestep stuff
906
+ self._current_timestep_keyframe = None
907
+ self._current_timestep_index = -1
908
+ self._current_used_steps = 0
909
+ # clear mask hints
910
+ if self.mask_cond_hint is not None:
911
+ del self.mask_cond_hint
912
+ self.mask_cond_hint = None
913
+ if self.tk_mask_cond_hint_original is not None:
914
+ del self.tk_mask_cond_hint_original
915
+ self.tk_mask_cond_hint_original = None
916
+ if self.tk_mask_cond_hint is not None:
917
+ del self.tk_mask_cond_hint
918
+ self.tk_mask_cond_hint = None
919
+ if self.weight_mask_cond_hint is not None:
920
+ del self.weight_mask_cond_hint
921
+ self.weight_mask_cond_hint = None
922
+
923
+ def copy_to_advanced(self, copied: 'AdvancedControlBase'):
924
+ copied.mask_cond_hint_original = self.mask_cond_hint_original
925
+ copied.weights_override = self.weights_override
926
+ copied.latent_keyframe_override = self.latent_keyframe_override
927
+ copied.disarmed = self.disarmed
ComfyUI-Advanced-ControlNet/pyproject.toml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "comfyui-advanced-controlnet"
3
+ description = "Nodes for scheduling ControlNet strength across timesteps and batched latents, as well as applying custom weights and attention masks."
4
+ version = "1.0.5"
5
+ license = "LICENSE"
6
+ dependencies = []
7
+
8
+ [project.urls]
9
+ Repository = "https://github.com/Kosinkadink/ComfyUI-Advanced-ControlNet"
10
+
11
+ # Used by Comfy Registry https://comfyregistry.org
12
+ [tool.comfy]
13
+ PublisherId = "kosinkadink"
14
+ DisplayName = "ComfyUI-Advanced-ControlNet"
15
+ Icon = ""
ComfyUI-Advanced-ControlNet/requirements.txt ADDED
File without changes
ComfyUI-Allor/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Nourepide
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
ComfyUI-Allor/Loader.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ import platform
4
+ import time
5
+
6
+ from pathlib import Path
7
+
8
+ import folder_paths
9
+ import nodes
10
+
11
+
12
+ class Loader:
13
+ def __init__(self):
14
+ pass
15
+
16
+ __ROOT_PATH = os.path.dirname(os.path.abspath(__file__))
17
+ __TEMPLATE_PATH = os.path.join(__ROOT_PATH, "resources/template.json")
18
+ __TIMESTAMP_PATH = os.path.join(__ROOT_PATH, "resources/timestamp.json")
19
+ __CONFIG_PATH = os.path.join(__ROOT_PATH, "config.json")
20
+ __GIT_PATH = Path(os.path.join(__ROOT_PATH, ".git"))
21
+
22
+ __DAY_SECONDS = 24 * 60 * 60
23
+ __WEEK_SECONDS = 7 * __DAY_SECONDS
24
+ __MONTH_SECONDS = 30 * __DAY_SECONDS
25
+
26
+ def __log(self, text):
27
+ print("\033[92m[Allor]\033[0m: " + text)
28
+
29
+ def __error(self, text):
30
+ print("\033[91m[Allor]\033[0m: " + text)
31
+
32
+ def __notification(self, text):
33
+ print("\033[94m[Allor]\033[0m: " + text)
34
+
35
+ def __new_line(self):
36
+ print()
37
+
38
+ def __create_config(self):
39
+ with open(self.__CONFIG_PATH, "w", encoding="utf-8") as f:
40
+ json.dump(self.__template(), f, ensure_ascii=False, indent=4)
41
+
42
+ def __create_timestamp(self):
43
+ with open(self.__TIMESTAMP_PATH, "w", encoding="utf-8") as f:
44
+ json.dump({"timestamp": 0}, f, ensure_ascii=False, indent=4)
45
+
46
+ def __get_template(self):
47
+ with open(self.__TEMPLATE_PATH, "r") as f:
48
+ template = json.load(f)
49
+
50
+ if "__comment" in template:
51
+ del template["__comment"]
52
+
53
+ return template
54
+
55
+ def __get_config(self):
56
+ with open(self.__CONFIG_PATH, "r") as f:
57
+ return json.load(f)
58
+
59
+ def __get_timestamp(self):
60
+ with open(self.__TIMESTAMP_PATH, "r") as f:
61
+ return json.load(f)
62
+
63
+ def __update_config(self, template, source):
64
+ def update_source(__template, __source):
65
+ for k, v in __template.items():
66
+ if k not in __source:
67
+ if isinstance(v, dict):
68
+ __source[k] = {}
69
+ else:
70
+ __source[k] = v
71
+
72
+ if isinstance(v, dict):
73
+ __source[k] = update_source(v, __source[k])
74
+
75
+ return __source
76
+
77
+ def delete_keys(__template, __source):
78
+ keys_to_delete = [k for k in __source if k not in __template]
79
+
80
+ for k in keys_to_delete:
81
+ del __source[k]
82
+
83
+ return __source
84
+
85
+ def sync_order(__template, __source):
86
+ new_source = {}
87
+
88
+ for key in __template:
89
+ if key in __source:
90
+ if isinstance(__template[key], dict):
91
+ new_source[key] = sync_order(__template[key], __source[key])
92
+ else:
93
+ new_source[key] = __source[key]
94
+
95
+ return new_source
96
+
97
+ source = update_source(template, source)
98
+ source = delete_keys(template, source)
99
+ source = sync_order(template, source)
100
+
101
+ with open(self.__CONFIG_PATH, "w", encoding="utf-8") as f:
102
+ json.dump(source, f, ensure_ascii=False, indent=4)
103
+
104
+ def __update_timestamp(self):
105
+ with open(self.__TIMESTAMP_PATH, "w", encoding="utf-8") as f:
106
+ json.dump({"timestamp": time.time()}, f, ensure_ascii=False, indent=4)
107
+
108
+ __template = __get_template
109
+ __config = __get_config
110
+ __timestamp = __get_timestamp
111
+
112
+ def __get_fonts_folder_path(self):
113
+ system = platform.system()
114
+ user_home = os.path.expanduser('~')
115
+
116
+ config_font_path = os.path.join(folder_paths.base_path, *self.__config()["fonts"]["folder_path"].replace("\\", "/").split("/"))
117
+
118
+ if not os.path.exists(config_font_path):
119
+ os.makedirs(config_font_path, exist_ok=True)
120
+
121
+ paths = [config_font_path]
122
+
123
+ if self.__config()["fonts"]["system_fonts"]:
124
+ if system == "Windows":
125
+ paths.append(os.path.join(os.environ["WINDIR"], "Fonts"))
126
+ elif system == "Darwin":
127
+ paths.append(os.path.join("/Library", "Fonts"))
128
+ elif system == "Linux":
129
+ paths.append(os.path.join("/usr", "share", "fonts"))
130
+ paths.append(os.path.join("/usr", "local", "share", "fonts"))
131
+
132
+ if self.__config()["fonts"]["user_fonts"]:
133
+ if system == "Darwin":
134
+ paths.append(os.path.join(user_home, "Library", "Fonts"))
135
+ elif system == "Linux":
136
+ paths.append(os.path.join(user_home, ".fonts"))
137
+
138
+ return [path for path in paths if os.path.exists(path)]
139
+
140
+ def __get_keys(self, json_obj, prefix=''):
141
+ keys = []
142
+
143
+ for k, v in json_obj.items():
144
+ if isinstance(v, dict):
145
+ keys.extend(self.__get_keys(v, prefix + k + '.'))
146
+ else:
147
+ keys.append(prefix + k)
148
+
149
+ return set(keys)
150
+
151
+ def __check_json_keys(self, json1, json2):
152
+ keys1 = self.__get_keys(json1)
153
+ keys2 = self.__get_keys(json2)
154
+
155
+ return keys1 == keys2
156
+
157
+ def setup_config(self):
158
+ if not os.path.exists(self.__CONFIG_PATH):
159
+ self.__log("Creating config.json")
160
+ self.__create_config()
161
+ else:
162
+ if not self.__check_json_keys(self.__template(), self.__config()):
163
+ self.__log("Updating config.json")
164
+ self.__update_config(self.__template(), self.__config())
165
+
166
+ def setup_timestamp(self):
167
+ if not os.path.exists(self.__TIMESTAMP_PATH):
168
+ self.__log("Creating timestamp.json")
169
+ self.__create_timestamp()
170
+
171
+ def check_updates(self):
172
+ branch_name = self.__config()["updates"]["branch_name"]
173
+ update_frequency = self.__config()["updates"]["update_frequency"].lower()
174
+ valid_frequencies = ["always", "day", "week", "month", "never"]
175
+ time_difference = time.time() - self.__timestamp()["timestamp"]
176
+
177
+ if update_frequency == valid_frequencies[0]:
178
+ it_is_time_for_update = True
179
+ elif update_frequency == valid_frequencies[1]:
180
+ it_is_time_for_update = time_difference >= self.__DAY_SECONDS
181
+ elif update_frequency == valid_frequencies[2]:
182
+ it_is_time_for_update = time_difference >= self.__WEEK_SECONDS
183
+ elif update_frequency == valid_frequencies[3]:
184
+ it_is_time_for_update = time_difference >= self.__MONTH_SECONDS
185
+ elif update_frequency == valid_frequencies[4]:
186
+ it_is_time_for_update = False
187
+ else:
188
+ self.__error(f"Unknown update frequency - {update_frequency}, available: {valid_frequencies}")
189
+
190
+ return
191
+
192
+ if it_is_time_for_update:
193
+ if not (self.__GIT_PATH.exists() or self.__GIT_PATH.is_dir()):
194
+ self.__error("Root directory of Allor is not a git repository. Update canceled.")
195
+
196
+ return
197
+
198
+ try:
199
+ import git
200
+
201
+ from git import Repo
202
+ from git import GitCommandError
203
+
204
+ # noinspection PyTypeChecker, PyUnboundLocalVariable
205
+ repo = Repo(self.__ROOT_PATH, odbt=git.db.GitDB)
206
+ current_commit = repo.head.commit.hexsha
207
+
208
+ repo.remotes.origin.fetch()
209
+
210
+ latest_commit = getattr(repo.remotes.origin.refs, branch_name).commit.hexsha
211
+
212
+ if current_commit == latest_commit:
213
+ if self.__config()["updates"]["notify_if_no_new_updates"]:
214
+ self.__notification("No new updates.")
215
+ else:
216
+ if self.__config()["updates"]["notify_if_has_new_updates"]:
217
+ self.__notification("New updates are available.")
218
+
219
+ if self.__config()["updates"]["auto_update"]:
220
+ update_mode = self.__config()["updates"]["update_mode"].lower()
221
+ valid_modes = ["soft", "hard"]
222
+
223
+ if repo.active_branch.name != branch_name:
224
+ try:
225
+ repo.git.checkout(branch_name)
226
+ except GitCommandError:
227
+ self.__error(f"An error occurred while switching to the branch {branch_name}.")
228
+
229
+ return
230
+
231
+ if update_mode == "soft":
232
+ try:
233
+ repo.git.pull()
234
+ except GitCommandError:
235
+ self.__error("An error occurred during the update. "
236
+ "It is recommended to use \"hard\" update mode. "
237
+ "But be careful, it erases all personal changes from Allor repository.")
238
+
239
+ elif update_mode == "hard":
240
+ repo.git.reset('--hard', 'origin/' + branch_name)
241
+ else:
242
+ self.__error(f"Unknown update mode - {update_mode}, available: {valid_modes}")
243
+
244
+ return
245
+
246
+ self.__notification("Update complete.")
247
+
248
+ self.__update_timestamp()
249
+
250
+ except ImportError:
251
+ self.__error("GitPython is not installed.")
252
+
253
+ def setup_rembg(self):
254
+ os.environ["U2NET_HOME"] = folder_paths.models_dir + "/onnx"
255
+
256
+ def setup_paths(self):
257
+ fonts_folder_path = self.__get_fonts_folder_path()
258
+
259
+ folder_paths.folder_names_and_paths["onnx"] = ([os.path.join(folder_paths.models_dir, "onnx")], {".onnx"})
260
+ folder_paths.folder_names_and_paths["fonts"] = (fonts_folder_path, {".otf", ".ttf"})
261
+
262
+ def setup_override(self):
263
+ override_nodes_len = 0
264
+
265
+ def override(function):
266
+ start_len = nodes.NODE_CLASS_MAPPINGS.__len__()
267
+
268
+ nodes.NODE_CLASS_MAPPINGS = dict(
269
+ filter(function, nodes.NODE_CLASS_MAPPINGS.items())
270
+ )
271
+
272
+ return start_len - nodes.NODE_CLASS_MAPPINGS.__len__()
273
+
274
+ if self.__config()["override"]["postprocessing"]:
275
+ override_nodes_len += override(lambda item: not item[1].CATEGORY.startswith("image/postprocessing"))
276
+
277
+ if self.__config()["override"]["transform"]:
278
+ override_nodes_len += override(lambda item: not item[0] == "ImageScale" and not item[0] == "ImageScaleBy" and not item[0] == "ImageInvert")
279
+
280
+ if self.__config()["override"]["debug"]:
281
+ nodes.VAEDecodeTiled.CATEGORY = "latent"
282
+ nodes.VAEEncodeTiled.CATEGORY = "latent"
283
+
284
+ override_nodes_len += override(lambda item: not item[1].CATEGORY.startswith("_for_testing"))
285
+
286
+ self.__log(str(override_nodes_len) + " nodes were overridden.")
287
+
288
+ def get_modules(self):
289
+ modules = dict()
290
+
291
+ if self.__config()["modules"]["AlphaChanel"]:
292
+ from .modules import AlphaChanel
293
+ modules.update(AlphaChanel.NODE_CLASS_MAPPINGS)
294
+
295
+ if self.__config()["modules"]["Clamp"]:
296
+ from .modules import Clamp
297
+ modules.update(Clamp.NODE_CLASS_MAPPINGS)
298
+
299
+ if self.__config()["modules"]["ImageBatch"]:
300
+ from .modules import ImageBatch
301
+ modules.update(ImageBatch.NODE_CLASS_MAPPINGS)
302
+
303
+ if self.__config()["modules"]["ImageComposite"]:
304
+ from .modules import ImageComposite
305
+ modules.update(ImageComposite.NODE_CLASS_MAPPINGS)
306
+
307
+ if self.__config()["modules"]["ImageContainer"]:
308
+ from .modules import ImageContainer
309
+ modules.update(ImageContainer.NODE_CLASS_MAPPINGS)
310
+
311
+ if self.__config()["modules"]["ImageDraw"]:
312
+ from .modules import ImageDraw
313
+ modules.update(ImageDraw.NODE_CLASS_MAPPINGS)
314
+
315
+ if self.__config()["modules"]["ImageEffects"]:
316
+ from .modules import ImageEffects
317
+ modules.update(ImageEffects.NODE_CLASS_MAPPINGS)
318
+
319
+ if self.__config()["modules"]["ImageFilter"]:
320
+ from .modules import ImageFilter
321
+ modules.update(ImageFilter.NODE_CLASS_MAPPINGS)
322
+
323
+ if self.__config()["modules"]["ImageNoise"]:
324
+ from .modules import ImageNoise
325
+ modules.update(ImageNoise.NODE_CLASS_MAPPINGS)
326
+
327
+ if self.__config()["modules"]["ImageSegmentation"]:
328
+ from .modules import ImageSegmentation
329
+ modules.update(ImageSegmentation.NODE_CLASS_MAPPINGS)
330
+
331
+ if self.__config()["modules"]["ImageText"]:
332
+ from .modules import ImageText
333
+ modules.update(ImageText.NODE_CLASS_MAPPINGS)
334
+
335
+ if self.__config()["modules"]["ImageTransform"]:
336
+ from .modules import ImageTransform
337
+ modules.update(ImageTransform.NODE_CLASS_MAPPINGS)
338
+
339
+ modules_len = dict(
340
+ filter(
341
+ lambda item: item[1],
342
+ self.__config()["modules"].items()
343
+ )
344
+ ).__len__()
345
+
346
+ nodes_len = modules.__len__()
347
+
348
+ self.__log(str(modules_len) + " modules were enabled.")
349
+ self.__log(str(nodes_len) + " nodes were loaded.")
350
+
351
+ return modules
ComfyUI-Allor/README.MD ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ![logo](https://raw.githubusercontent.com/Nourepide/ComfyUI-Allor-Res/c4147e55cf8ec26ca79fe3df6e1af71aca58c19e/v.2/logo_v.2_git.png)
2
+
3
+ <details>
4
+ <summary>This image from start to end was done in ComfyUI. How?</summary>
5
+
6
+ 1. Install plugin.
7
+ 2. Load fonts [Overlock SC](https://fonts.google.com/specimen/Overlock+SC) and [Merienda](https://fonts.google.com/specimen/Merienda).
8
+ 3. Put `OverlockSC-Regular.ttf` and `Merienda-Regular.ttf` in to `fonts` folder.
9
+ 4. Load [RealESRNet_x4plus.pth](https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth) and put in to `models/upscale` folder.
10
+ 5. Load [AOM3A1B_orangemixs.safetensors](https://huggingface.co/WarriorMama777/OrangeMixs/resolve/main/Models/AbyssOrangeMix3/AOM3A1B_orangemixs.safetensors) and put in to `models/chekpoints` folder.
11
+ 6. Load [orangemix.vae.pt](https://huggingface.co/WarriorMama777/OrangeMixs/resolve/main/VAEs/orangemix.vae.pt) and put in to `models/vae` folder.
12
+ 7. Drag-and-drop this [image](resources/logo.png) to ComfyUI or load [JSON](https://raw.githubusercontent.com/Nourepide/ComfyUI-Allor-Res/c4147e55cf8ec26ca79fe3df6e1af71aca58c19e/v.2/logo_v.2.json).
13
+ 8. Press the `Queue Promt` button.
14
+
15
+ </details>
16
+
17
+ ## About Allor:
18
+ * Allor is a high-performance ComfyUI plugin designed for image processing.
19
+ * It comprises more than 90 nodes, each with numerous parameters for your needs.
20
+ * It supports transparency and multi-image processing across all modules and nodes.
21
+ * Allor is fully configurable, offering the option to disable any functionality that is not required.
22
+ * The majority of its operations are implemented in tensor space to avoid unnecessary data transformations.
23
+
24
+ ## Documentation
25
+
26
+ We are pleased to present to you our new documentation.
27
+
28
+ The [documentation](https://nourepide.github.io/ComfyUI-Allor-Doc/) includes information about [installation](https://nourepide.github.io/ComfyUI-Allor-Doc/installation-allor.html), [updating](https://nourepide.github.io/ComfyUI-Allor-Doc/updating.html), all [nodes](https://nourepide.github.io/ComfyUI-Allor-Doc/modules.html) including their parameters and much more.
29
+
30
+ ## Image Rebasing
31
+
32
+ We recently rebased the **Allor** repository by **removing all images** from the history, which resulted in a significant reduction in its size - by a factor of about **344**.
33
+
34
+ However, because of this change, you may encounter **problems with updates**.
35
+
36
+ We have instructions in the documentation to help you:
37
+
38
+ * [Troubleshooting for Auto-Update](https://nourepide.github.io/ComfyUI-Allor-Doc/updating.html#troubleshooting_auto_update)
39
+ * [Troubleshooting for Git](https://nourepide.github.io/ComfyUI-Allor-Doc/updating.html#troubleshooting_git)
40
+
41
+ ## Contributing:
42
+ ComfyUI Allor is an open source project and I welcome any contributions from the community.
43
+
44
+ * **Suggest ideas**: If you have thoughts on improving this plugin, feel free to share them on GitHub.
45
+
46
+ * **Report bugs**: If you find a bug or problem, please report it in the Issue with steps to reproduce it.
47
+
48
+ * **Make pull requests**: If you’d like to help with the plugin’s code, you can copy this repository, make your changes, and I’ll check and include them if they work well with the plugin.
49
+
50
+ ## Jupiter Notebook:
51
+
52
+ To run Allor on another cloud service, you can use this [Jupiter Notebook](resources/allor.ipynb).
53
+
54
+ If you have a subscription to [Colab Pro](https://colab.research.google.com/signup), then you can run Allor in [Google Colab](https://colab.research.google.com/drive/1qOALtMEG_f6DN0o9mxUih6x_7PTPYM8X?usp=sharing).
ComfyUI-Allor/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .Loader import Loader
2
+
3
+ loader = Loader()
4
+
5
+ loader.setup_config()
6
+ loader.setup_timestamp()
7
+ loader.check_updates()
8
+ loader.setup_rembg()
9
+ loader.setup_paths()
10
+ loader.setup_override()
11
+
12
+ NODE_CLASS_MAPPINGS = loader.get_modules()
ComfyUI-Allor/__pycache__/Loader.cpython-310.pyc ADDED
Binary file (11.5 kB). View file
 
ComfyUI-Allor/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (395 Bytes). View file
 
ComfyUI-Allor/config.json ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "modules": {
3
+ "AlphaChanel": true,
4
+ "Clamp": true,
5
+ "ImageBatch": true,
6
+ "ImageComposite": true,
7
+ "ImageContainer": true,
8
+ "ImageDraw": true,
9
+ "ImageEffects": true,
10
+ "ImageFilter": true,
11
+ "ImageNoise": true,
12
+ "ImageSegmentation": true,
13
+ "ImageText": true,
14
+ "ImageTransform": true
15
+ },
16
+ "override": {
17
+ "postprocessing": false,
18
+ "transform": false,
19
+ "debug": false
20
+ },
21
+ "updates": {
22
+ "update_frequency": "day",
23
+ "notify_if_has_new_updates": true,
24
+ "notify_if_no_new_updates": true,
25
+ "auto_update": true,
26
+ "branch_name": "main",
27
+ "update_mode": "soft",
28
+ "confirm_unstable_agreement": false
29
+ },
30
+ "fonts": {
31
+ "folder_path": "comfy_extras/fonts",
32
+ "system_fonts": false,
33
+ "user_fonts": false
34
+ }
35
+ }
ComfyUI-Allor/install.bat ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 0<0# : ^
2
+ '''
3
+ @echo off
4
+ setlocal enabledelayedexpansion
5
+
6
+ REM Save the current directory
7
+ set CURRENT_DIR=!cd!
8
+
9
+ REM Initialize a flag for venv activation
10
+ set VENV_ACTIVATED=0
11
+
12
+ REM Initialize a variable for the Python executable
13
+ set PYTHON_EXECUTABLE=python
14
+
15
+ echo [Allor]: Searching for Python environments.
16
+
17
+ REM Check if the environment directory exists two levels up
18
+ if exist "..\..\venv\" goto venv
19
+
20
+ REM Check if the environment directory exists three levels up
21
+ if exist "..\..\..\python_embeded\" goto portable
22
+
23
+ REM Check if the environment directory exists in system
24
+ where /q python && if !ERRORLEVEL! equ 0 goto system
25
+
26
+ REM Error if the environment not exist
27
+ goto not_found_environment
28
+
29
+ :venv
30
+ REM Go two levels up from the current directory
31
+ cd ..\..
32
+
33
+ REM Check if the activate script exists in the venv
34
+ if exist "venv\Scripts\activate" (
35
+ echo [Allor]: Found venv Python environment.
36
+
37
+ REM Activate the virtual environment
38
+ call venv\Scripts\activate
39
+
40
+ REM Set the flag for venv activation
41
+ set VENV_ACTIVATED=1
42
+
43
+ REM Go back to the original directory
44
+ cd !CURRENT_DIR!
45
+
46
+ REM Check if the requirements.txt file exists in the current directory
47
+ if exist "requirements.txt" (
48
+ REM Install dependencies from the requirements.txt file
49
+ pip install -r requirements.txt --no-warn-script-location --quiet
50
+ ) else (
51
+ echo [Allor]: requirements.txt not found in the current directory.
52
+ exit /b
53
+ )
54
+ )
55
+ goto git
56
+
57
+ :portable
58
+ REM Go three levels up from the current directory
59
+ cd ..\..\..
60
+
61
+ REM Check if python.exe exists in the python_embedded directory
62
+ if exist "python_embeded\python.exe" (
63
+ echo [Allor]: Found portable Python environment.
64
+
65
+ REM Set the flag for venv activation
66
+ set VENV_ACTIVATED=2
67
+
68
+ REM Set the Python executable to the python.exe in the python_embedded directory
69
+ set PYTHON_EXECUTABLE=!cd!\python_embeded\python.exe
70
+
71
+ REM Execute python.exe with the specified arguments
72
+ call !PYTHON_EXECUTABLE! -s -m pip install -r !CURRENT_DIR!\requirements.txt --no-warn-script-location --quiet
73
+
74
+ REM Go back to the original directory
75
+ cd !CURRENT_DIR!
76
+ )
77
+ goto git
78
+
79
+ :system
80
+ set /p user_input=[Allor]: Only the system Python environment is detected. Should this be used for Allor dependencies? (y/N):
81
+
82
+ if /i "%user_input%"=="y" goto confirmed
83
+ if /i "%user_input%"=="yes" goto confirmed
84
+ goto not_found_environment
85
+
86
+ :confirmed
87
+ REM Set the flag for venv activation
88
+ set VENV_ACTIVATED=3
89
+
90
+ REM Execute python.exe with the specified arguments
91
+ call !PYTHON_EXECUTABLE! -s -m pip install -r !CURRENT_DIR!\requirements.txt --no-warn-script-location --quiet
92
+
93
+ REM Go back to the original directory
94
+ cd !CURRENT_DIR!
95
+ goto git
96
+
97
+ :not_found_environment
98
+ REM If neither venv nor python_embeded were found, print an error and exit
99
+ echo [Allor]: None of the Python environments were found.
100
+ exit /b
101
+
102
+ :git
103
+ where /q git && if !ERRORLEVEL! equ 0 (
104
+ echo [Allor]: Git found.
105
+
106
+ REM Check if the current directory is a git repository
107
+ if not exist ".git" (
108
+ echo [Allor]: This directory is not a git repository. Initializing a new repository.
109
+
110
+ git init -b main
111
+ git remote add origin https://github.com/Nourepide/ComfyUI-Allor
112
+ git fetch origin main
113
+ git reset --hard origin/main
114
+ ) else (
115
+ echo [Allor]: This directory is already a git repository.
116
+ )
117
+ ) else (
118
+ echo [Allor]: Git is not installed. Using GitPython instead.
119
+
120
+ REM Run a Python script that uses GitPython to do the same thing
121
+ call !PYTHON_EXECUTABLE! %~f0
122
+ )
123
+
124
+ REM Deactivate the virtual environment if it was activated
125
+ if !VENV_ACTIVATED! equ 1 (
126
+ deactivate
127
+ )
128
+
129
+ echo [Allor]: Install complete successful.
130
+
131
+ endlocal
132
+ exit /b
133
+ '''
134
+ import git
135
+ from pathlib import Path
136
+
137
+ # Check if the current directory is a git repository
138
+ if not (Path('.git').exists() or Path('.git').is_dir()):
139
+ from git import Repo
140
+
141
+ print("[Allor]: This directory is not a git repository. Initializing a new repository.")
142
+
143
+ repo = Repo.init(initial_branch='main')
144
+ origin = repo.create_remote('origin', 'https://github.com/Nourepide/ComfyUI-Allor')
145
+ origin.fetch('main')
146
+ repo.git.reset('--hard', 'origin/main')
147
+ else:
148
+ print('[Allor]: This directory is already a git repository.')
ComfyUI-Allor/install.sh ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Save the current directory
4
+ CURRENT_DIR=$(pwd)
5
+
6
+ VENV_ACTIVE=false
7
+
8
+ echo -e "\e[34m[Allor]\e[0m: Searching for Python environments."
9
+
10
+ if [ -d "../../venv" ]; then
11
+ echo -e "\e[34m[Allor]\e[0m: Found venv Python environment."
12
+
13
+ cd ../..
14
+
15
+ # Check if the activate script exists in the venv
16
+ if [ -f "venv/bin/activate" ]; then
17
+ # Activate the virtual environment
18
+ source venv/bin/activate
19
+
20
+ VENV_ACTIVE=true
21
+
22
+ # Go back to the original directory
23
+ cd $CURRENT_DIR
24
+ else
25
+ echo -e "\e[31m[Allor]\e[0m: Activation script not found."
26
+ exit 1
27
+ fi
28
+ elif command -v python3 &> /dev/null; then
29
+ printf "\e[34m[Allor]\e[0m: Only the system Python environment is detected. Should this be used for Allor dependencies? (y/N): "
30
+ read answer
31
+
32
+ [[ $answer =~ ^[yY] ]] || echo -e "\e[31m[Allor]\e[0m: None of the Python environments were found." && exit 1
33
+ else
34
+ echo -e "\e[31m[Allor]\e[0m: None of the Python environments were found."
35
+ exit 1
36
+ fi
37
+
38
+ if [ -f "requirements.txt" ]; then
39
+ echo -e "\e[34m[Allor]\e[0m: Install dependencies from the requirements.txt file."
40
+ pip install -r requirements.txt --no-warn-script-location --quiet --disable-pip-version-check
41
+ else
42
+ echo -e "\e[31m[Allor]\e[0m: requirements.txt not found in the current directory."
43
+ exit 1
44
+ fi
45
+
46
+ if command -v git >/dev/null 2>&1; then
47
+ echo -e "\e[34m[Allor]\e[0m: Git found."
48
+
49
+ # Check if the current directory is a git repository
50
+ if [ ! -d ".git" ]; then
51
+ echo -e "\e[34m[Allor]\e[0m: This directory is not a git repository. Initializing a new repository."
52
+
53
+ git init -b main
54
+ git remote add origin https://github.com/Nourepide/ComfyUI-Allor
55
+ git pull origin master
56
+ else
57
+ echo -e "\e[34m[Allor]\e[0m: This directory is already a git repository."
58
+ fi
59
+ else
60
+ echo -e "\e[34m[Allor]\e[0m: Git is not installed. Using GitPython instead."
61
+
62
+ # Run a Python script that uses GitPython to do the same thing
63
+ python -c '
64
+ import git
65
+
66
+ from git import Repo
67
+ from pathlib import Path
68
+
69
+ # Check if the current directory is a git repository
70
+ if not (Path(".git").exists() or Path(".git").is_dir()):
71
+ print("\033[94m[Allor]\033[0m: This directory is not a git repository. Initializing a new repository.")
72
+
73
+ repo = Repo.init(initial_branch='main')
74
+ origin = repo.create_remote("origin", "https://github.com/Nourepide/ComfyUI-Allor")
75
+ origin.fetch("main")
76
+ repo.git.reset("--hard", "origin/main")
77
+ else:
78
+ print("\033[94m[Allor]\033[0m: This directory is already a git repository.")
79
+ '
80
+ fi
81
+
82
+ if [ $VENV_ACTIVE ]; then
83
+ deactivate
84
+ fi
85
+
86
+ echo -e "\e[32m[Allor]\e[0m: Install complete successful."
ComfyUI-Allor/modules/AlphaChanel.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+
4
+ class AlphaChanelAdd:
5
+ def __init__(self):
6
+ pass
7
+
8
+ @classmethod
9
+ def INPUT_TYPES(cls):
10
+ return {
11
+ "required": {
12
+ "images": ("IMAGE",),
13
+ },
14
+ }
15
+
16
+ RETURN_TYPES = ("IMAGE",)
17
+ FUNCTION = "node"
18
+ CATEGORY = "image/alpha"
19
+
20
+ def node(self, images):
21
+ batch, height, width, channels = images.shape
22
+
23
+ if channels == 4:
24
+ return images
25
+
26
+ alpha = torch.ones((batch, height, width, 1))
27
+
28
+ return (torch.cat((images, alpha), dim=-1),)
29
+
30
+
31
+ class AlphaChanelAddByMask:
32
+ def __init__(self):
33
+ pass
34
+
35
+ @classmethod
36
+ def INPUT_TYPES(cls):
37
+ return {
38
+ "required": {
39
+ "images": ("IMAGE",),
40
+ "mask": ("MASK",),
41
+ "method": (["default", "invert"],),
42
+ },
43
+ }
44
+
45
+ RETURN_TYPES = ("IMAGE",)
46
+ FUNCTION = "node"
47
+ CATEGORY = "image/alpha"
48
+
49
+ def node(self, images, mask, method):
50
+ img_count, img_height, img_width = images[:, :, :, 0].shape
51
+ mask_count, mask_height, mask_width = mask.shape
52
+
53
+ if mask_width == 64 and mask_height == 64:
54
+ mask = torch.zeros((img_count, img_height, img_width))
55
+ else:
56
+ if img_height != mask_height or img_width != mask_width:
57
+ raise ValueError(
58
+ "[AlphaChanelByMask]: Size of images not equals size of mask. " +
59
+ "Images: [" + str(img_width) + ", " + str(img_height) + "] - " +
60
+ "Mask: [" + str(mask_width) + ", " + str(mask_height) + "]."
61
+ )
62
+
63
+ if img_count != mask_count:
64
+ mask = mask.expand((img_count, -1, -1))
65
+
66
+ if method == "default":
67
+ return (torch.stack([
68
+ torch.stack((
69
+ images[i, :, :, 0],
70
+ images[i, :, :, 1],
71
+ images[i, :, :, 2],
72
+ 1. - mask[i]
73
+ ), dim=-1) for i in range(len(images))
74
+ ]),)
75
+ else:
76
+ return (torch.stack([
77
+ torch.stack((
78
+ images[i, :, :, 0],
79
+ images[i, :, :, 1],
80
+ images[i, :, :, 2],
81
+ mask[i]
82
+ ), dim=-1) for i in range(len(images))
83
+ ]),)
84
+
85
+
86
+ class AlphaChanelAsMask:
87
+ def __init__(self):
88
+ pass
89
+
90
+ @classmethod
91
+ def INPUT_TYPES(cls):
92
+ return {
93
+ "required": {
94
+ "images": ("IMAGE",),
95
+ "method": (["default", "invert"],),
96
+ },
97
+ }
98
+
99
+ RETURN_TYPES = ("MASK",)
100
+ FUNCTION = "node"
101
+ CATEGORY = "image/alpha"
102
+
103
+ def node(self, images, method):
104
+ if images[0, 0, 0].shape[0] != 4:
105
+ raise ValueError("Alpha chanel not exist.")
106
+
107
+ if method == "default":
108
+ return (1.0 - images[0, :, :, 3],)
109
+ elif method == "invert":
110
+ return (images[0, :, :, 3],)
111
+ else:
112
+ raise ValueError("Unexpected method.")
113
+
114
+
115
+ class AlphaChanelRestore:
116
+ def __init__(self):
117
+ pass
118
+
119
+ @classmethod
120
+ def INPUT_TYPES(cls):
121
+ return {
122
+ "required": {
123
+ "images": ("IMAGE",),
124
+ },
125
+ }
126
+
127
+ RETURN_TYPES = ("IMAGE",)
128
+ FUNCTION = "node"
129
+ CATEGORY = "image/alpha"
130
+
131
+ def node(self, images):
132
+ batch, height, width, channels = images.shape
133
+
134
+ if channels != 4:
135
+ return images
136
+
137
+ tensor = images.clone().detach()
138
+
139
+ tensor[:, :, :, 3] = torch.ones((batch, height, width))
140
+
141
+ return (tensor,)
142
+
143
+
144
+ class AlphaChanelRemove:
145
+ def __init__(self):
146
+ pass
147
+
148
+ @classmethod
149
+ def INPUT_TYPES(cls):
150
+ return {
151
+ "required": {
152
+ "images": ("IMAGE",),
153
+ },
154
+ }
155
+
156
+ RETURN_TYPES = ("IMAGE",)
157
+ FUNCTION = "node"
158
+ CATEGORY = "image/alpha"
159
+
160
+ def node(self, images):
161
+ return (images[:, :, :, 0:3],)
162
+
163
+
164
+ NODE_CLASS_MAPPINGS = {
165
+ "AlphaChanelAdd": AlphaChanelAdd,
166
+ "AlphaChanelAddByMask": AlphaChanelAddByMask,
167
+ "AlphaChanelAsMask": AlphaChanelAsMask,
168
+ "AlphaChanelRestore": AlphaChanelRestore,
169
+ "AlphaChanelRemove": AlphaChanelRemove
170
+ }
ComfyUI-Allor/modules/Clamp.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ class ClipClamp:
2
+ def __init__(self):
3
+ pass
4
+
5
+ @classmethod
6
+ def INPUT_TYPES(cls):
7
+ return {
8
+ "required": {
9
+ "clip": ("CLIP",),
10
+ },
11
+ }
12
+
13
+ RETURN_TYPES = ("CLIP",)
14
+ FUNCTION = "node"
15
+ CATEGORY = "clamp"
16
+
17
+ def node(self, clip):
18
+ return (clip,)
19
+
20
+
21
+ class ClipVisionClamp:
22
+ def __init__(self):
23
+ pass
24
+
25
+ @classmethod
26
+ def INPUT_TYPES(cls):
27
+ return {
28
+ "required": {
29
+ "clip_vision": ("CLIP_VISION",),
30
+ },
31
+ }
32
+
33
+ RETURN_TYPES = ("CLIP_VISION",)
34
+ FUNCTION = "node"
35
+ CATEGORY = "clamp"
36
+
37
+ def node(self, clip_vision):
38
+ return (clip_vision,)
39
+
40
+
41
+ class ClipVisionOutputClamp:
42
+ def __init__(self):
43
+ pass
44
+
45
+ @classmethod
46
+ def INPUT_TYPES(cls):
47
+ return {
48
+ "required": {
49
+ "clip_vision_output": ("CLIP_VISION_OUTPUT",),
50
+ },
51
+ }
52
+
53
+ RETURN_TYPES = ("CLIP_VISION_OUTPUT",)
54
+ FUNCTION = "node"
55
+ CATEGORY = "clamp"
56
+
57
+ def node(self, clip_vision_output):
58
+ return (clip_vision_output,)
59
+
60
+
61
+ class ConditioningClamp:
62
+ def __init__(self):
63
+ pass
64
+
65
+ @classmethod
66
+ def INPUT_TYPES(cls):
67
+ return {
68
+ "required": {
69
+ "conditioning": ("CONDITIONING",),
70
+ },
71
+ }
72
+
73
+ RETURN_TYPES = ("CONDITIONING",)
74
+ FUNCTION = "node"
75
+ CATEGORY = "clamp"
76
+
77
+ def node(self, conditioning):
78
+ return (conditioning,)
79
+
80
+
81
+ class ControlNetClamp:
82
+ def __init__(self):
83
+ pass
84
+
85
+ @classmethod
86
+ def INPUT_TYPES(cls):
87
+ return {
88
+ "required": {
89
+ "control_net_clamp": ("CONTROL_NET",),
90
+ },
91
+ }
92
+
93
+ RETURN_TYPES = ("CONTROL_NET",)
94
+ FUNCTION = "node"
95
+ CATEGORY = "clamp"
96
+
97
+ def node(self, control_net_clamp):
98
+ return (control_net_clamp,)
99
+
100
+
101
+ class GligenClamp:
102
+ def __init__(self):
103
+ pass
104
+
105
+ @classmethod
106
+ def INPUT_TYPES(cls):
107
+ return {
108
+ "required": {
109
+ "gligen": ("GLIGEN",),
110
+ },
111
+ }
112
+
113
+ RETURN_TYPES = ("GLIGEN",)
114
+ FUNCTION = "node"
115
+ CATEGORY = "clamp"
116
+
117
+ def node(self, gligen):
118
+ return (gligen,)
119
+
120
+
121
+ class ImageClamp:
122
+ def __init__(self):
123
+ pass
124
+
125
+ @classmethod
126
+ def INPUT_TYPES(cls):
127
+ return {
128
+ "required": {
129
+ "image": ("IMAGE",),
130
+ },
131
+ }
132
+
133
+ RETURN_TYPES = ("IMAGE",)
134
+ FUNCTION = "node"
135
+ CATEGORY = "clamp"
136
+
137
+ def node(self, image):
138
+ return (image,)
139
+
140
+
141
+ class LatentClamp:
142
+ def __init__(self):
143
+ pass
144
+
145
+ @classmethod
146
+ def INPUT_TYPES(cls):
147
+ return {
148
+ "required": {
149
+ "latent": ("LATENT",),
150
+ },
151
+ }
152
+
153
+ RETURN_TYPES = ("LATENT",)
154
+ FUNCTION = "node"
155
+ CATEGORY = "clamp"
156
+
157
+ def node(self, latent):
158
+ return (latent,)
159
+
160
+
161
+ class MaskClamp:
162
+ def __init__(self):
163
+ pass
164
+
165
+ @classmethod
166
+ def INPUT_TYPES(cls):
167
+ return {
168
+ "required": {
169
+ "mask": ("MASK",),
170
+ },
171
+ }
172
+
173
+ RETURN_TYPES = ("MASK",)
174
+ FUNCTION = "node"
175
+ CATEGORY = "clamp"
176
+
177
+ def node(self, mask):
178
+ return (mask,)
179
+
180
+
181
+ class ModelClamp:
182
+ def __init__(self):
183
+ pass
184
+
185
+ @classmethod
186
+ def INPUT_TYPES(cls):
187
+ return {
188
+ "required": {
189
+ "model": ("MODEL",),
190
+ },
191
+ }
192
+
193
+ RETURN_TYPES = ("MODEL",)
194
+ FUNCTION = "node"
195
+ CATEGORY = "clamp"
196
+
197
+ def node(self, model):
198
+ return (model,)
199
+
200
+
201
+ class StyleModelClamp:
202
+ def __init__(self):
203
+ pass
204
+
205
+ @classmethod
206
+ def INPUT_TYPES(cls):
207
+ return {
208
+ "required": {
209
+ "style_model": ("STYLE_MODEL",),
210
+ },
211
+ }
212
+
213
+ RETURN_TYPES = ("STYLE_MODEL",)
214
+ FUNCTION = "node"
215
+ CATEGORY = "clamp"
216
+
217
+ def node(self, style_model):
218
+ return (style_model,)
219
+
220
+
221
+ class UpscaleModelClamp:
222
+ def __init__(self):
223
+ pass
224
+
225
+ @classmethod
226
+ def INPUT_TYPES(cls):
227
+ return {
228
+ "required": {
229
+ "upscale_model": ("UPSCALE_MODEL",),
230
+ },
231
+ }
232
+
233
+ RETURN_TYPES = ("UPSCALE_MODEL",)
234
+ FUNCTION = "node"
235
+ CATEGORY = "clamp"
236
+
237
+ def node(self, upscale_model):
238
+ return (upscale_model,)
239
+
240
+
241
+ class VaeClamp:
242
+ def __init__(self):
243
+ pass
244
+
245
+ @classmethod
246
+ def INPUT_TYPES(cls):
247
+ return {
248
+ "required": {
249
+ "vae": ("VAE",),
250
+ }
251
+ }
252
+
253
+ RETURN_TYPES = ("VAE",)
254
+ FUNCTION = "node"
255
+ CATEGORY = "clamp"
256
+
257
+ def node(self, vae):
258
+ return (vae,)
259
+
260
+
261
+ NODE_CLASS_MAPPINGS = {
262
+ "ClipClamp": ClipClamp,
263
+ "ClipVisionClamp": ClipVisionClamp,
264
+ "ClipVisionOutputClamp": ClipVisionOutputClamp,
265
+ "ConditioningClamp": ConditioningClamp,
266
+ "ControlNetClamp": ControlNetClamp,
267
+ "GligenClamp": GligenClamp,
268
+ "ImageClamp": ImageClamp,
269
+ "LatentClamp": LatentClamp,
270
+ "MaskClamp": MaskClamp,
271
+ "ModelClamp": ModelClamp,
272
+ "StyleModelClamp": StyleModelClamp,
273
+ "UpscaleModelClamp": UpscaleModelClamp,
274
+ "VaeClamp": VaeClamp,
275
+ }
ComfyUI-Allor/modules/ImageBatch.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+
3
+ import torch
4
+
5
+
6
+ class ImageBatchGet:
7
+ def __init__(self):
8
+ pass
9
+
10
+ @classmethod
11
+ def INPUT_TYPES(cls):
12
+ return {
13
+ "required": {
14
+ "images": ("IMAGE",),
15
+ "index": ("INT", {
16
+ "default": 1,
17
+ "min": 1,
18
+ "step": 1
19
+ }),
20
+ },
21
+ }
22
+
23
+ RETURN_TYPES = ("IMAGE",)
24
+ FUNCTION = "node"
25
+ CATEGORY = "image/batch"
26
+
27
+ def node(self, images, index):
28
+ batch = images.shape[0]
29
+ index = min(batch, index) - 1
30
+
31
+ return (images[index].unsqueeze(0),)
32
+
33
+
34
+ class ImageBatchCopy:
35
+ def __init__(self):
36
+ pass
37
+
38
+ @classmethod
39
+ def INPUT_TYPES(cls):
40
+ return {
41
+ "required": {
42
+ "images": ("IMAGE",),
43
+ "index": ("INT", {
44
+ "default": 1,
45
+ "min": 1,
46
+ "step": 1
47
+ }),
48
+ "quantity": ("INT", {
49
+ "default": 1,
50
+ "min": 2,
51
+ "step": 1
52
+ }),
53
+ },
54
+ }
55
+
56
+ RETURN_TYPES = ("IMAGE",)
57
+ FUNCTION = "node"
58
+ CATEGORY = "image/batch"
59
+
60
+ def node(self, images, index, quantity):
61
+ batch = images.shape[0]
62
+ index = min(batch, index) - 1
63
+
64
+ return (images[index].repeat(quantity, 1, 1, 1),)
65
+
66
+
67
+ class ImageBatchRemove:
68
+ def __init__(self):
69
+ pass
70
+
71
+ @classmethod
72
+ def INPUT_TYPES(cls):
73
+ return {
74
+ "required": {
75
+ "images": ("IMAGE",),
76
+ "index": ("INT", {
77
+ "default": 1,
78
+ "min": 1,
79
+ "step": 1
80
+ }),
81
+ },
82
+ }
83
+
84
+ RETURN_TYPES = ("IMAGE",)
85
+ FUNCTION = "node"
86
+ CATEGORY = "image/batch"
87
+
88
+ def node(self, images, index):
89
+ batch = images.shape[0]
90
+ index = min(batch, index - 1)
91
+
92
+ return (torch.cat((images[:index], images[index + 1:]), dim=0),)
93
+
94
+
95
+ class ImageBatchFork:
96
+ def __init__(self):
97
+ pass
98
+
99
+ @classmethod
100
+ def INPUT_TYPES(cls):
101
+ return {
102
+ "required": {
103
+ "images": ("IMAGE",),
104
+ "priority": (["first", "second"],),
105
+ },
106
+ }
107
+
108
+ RETURN_TYPES = ("IMAGE", "IMAGE")
109
+ FUNCTION = "node"
110
+ CATEGORY = "image/batch"
111
+
112
+ def node(self, images, priority):
113
+ batch = images.shape[0]
114
+
115
+ if batch == 1:
116
+ return images, images
117
+ elif batch % 2 == 0:
118
+ first = batch // 2
119
+ second = batch // 2
120
+ else:
121
+ if priority == "first":
122
+ first = batch // 2 + 1
123
+ second = batch // 2
124
+ elif priority == "second":
125
+ first = batch // 2
126
+ second = batch // 2 + 1
127
+ else:
128
+ raise ValueError("Not existing priority.")
129
+
130
+ return images[:first], images[-second:]
131
+
132
+
133
+ class ImageBatchJoin:
134
+ def __init__(self):
135
+ pass
136
+
137
+ @classmethod
138
+ def INPUT_TYPES(cls):
139
+ return {
140
+ "required": {
141
+ "images_a": ("IMAGE",),
142
+ "images_b": ("IMAGE",),
143
+ },
144
+ }
145
+
146
+ RETURN_TYPES = ("IMAGE",)
147
+ FUNCTION = "node"
148
+ CATEGORY = "image/batch"
149
+
150
+ def node(self, images_a, images_b):
151
+ height_a, width_a, channels_a = images_a[0].shape
152
+ height_b, width_b, channels_b = images_b[0].shape
153
+
154
+ if height_a != height_b:
155
+ raise ValueError("Height of images_a not equals of images_b. You can use ImageTransformResize for fix it.")
156
+
157
+ if width_a != width_b:
158
+ raise ValueError("Width of images_a not equals of images_b. You can use ImageTransformResize for fix it.")
159
+
160
+ if channels_a != channels_b:
161
+ raise ValueError("Channels of images_a not equals of images_b. Your can add or delete alpha channels with AlphaChanel module.")
162
+
163
+ return (torch.cat((images_a, images_b)),)
164
+
165
+
166
+ class ImageBatchPermute:
167
+ def __init__(self):
168
+ pass
169
+
170
+ @classmethod
171
+ def INPUT_TYPES(cls):
172
+ return {
173
+ "required": {
174
+ "images": ("IMAGE",),
175
+ "permute": ("STRING", {"multiline": False}),
176
+ "start_with_zero": ("BOOLEAN",),
177
+ },
178
+ }
179
+
180
+ RETURN_TYPES = ("IMAGE",)
181
+ FUNCTION = "node"
182
+ CATEGORY = "image/batch"
183
+
184
+ def node(self, images, permute, start_with_zero):
185
+ order = [int(num) - 1 if not start_with_zero else int(num) for num in re.findall(r'\d+', permute)]
186
+ order = torch.tensor(order)
187
+ order = order.clamp(0, images.shape[0] - 1)
188
+
189
+ return (images.index_select(0, order),)
190
+
191
+
192
+ NODE_CLASS_MAPPINGS = {
193
+ "ImageBatchGet": ImageBatchGet,
194
+ "ImageBatchCopy": ImageBatchCopy,
195
+ "ImageBatchRemove": ImageBatchRemove,
196
+ "ImageBatchFork": ImageBatchFork,
197
+ "ImageBatchJoin": ImageBatchJoin,
198
+ "ImageBatchPermute": ImageBatchPermute
199
+ }
ComfyUI-Allor/modules/ImageComposite.py ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from PIL import Image as ImageF
3
+
4
+
5
+ class ImageCompositeAbsolute:
6
+ def __init__(self):
7
+ pass
8
+
9
+ @classmethod
10
+ def INPUT_TYPES(cls):
11
+ return {
12
+ "required": {
13
+ "images_a": ("IMAGE",),
14
+ "images_b": ("IMAGE",),
15
+ "images_a_x": ("INT", {
16
+ "default": 0,
17
+ "step": 1
18
+ }),
19
+ "images_a_y": ("INT", {
20
+ "default": 0,
21
+ "step": 1
22
+ }),
23
+ "images_b_x": ("INT", {
24
+ "default": 0,
25
+ "step": 1
26
+ }),
27
+ "images_b_y": ("INT", {
28
+ "default": 0,
29
+ "step": 1
30
+ }),
31
+ "container_width": ("INT", {
32
+ "default": 0,
33
+ "step": 1
34
+ }),
35
+ "container_height": ("INT", {
36
+ "default": 0,
37
+ "step": 1
38
+ }),
39
+ "background": (["images_a", "images_b"],),
40
+ "method": (["pair", "matrix"],),
41
+ },
42
+ }
43
+
44
+ RETURN_TYPES = ("IMAGE",)
45
+ FUNCTION = "node"
46
+ CATEGORY = "image/composite"
47
+
48
+ def node(
49
+ self,
50
+ images_a,
51
+ images_b,
52
+ images_a_x,
53
+ images_a_y,
54
+ images_b_x,
55
+ images_b_y,
56
+ container_width,
57
+ container_height,
58
+ background,
59
+ method
60
+ ):
61
+ def clip(value: float):
62
+ return value if value >= 0 else 0
63
+
64
+ # noinspection PyUnresolvedReferences
65
+ def composite(image_a, image_b):
66
+ img_a_height, img_a_width, img_a_dim = image_a.shape
67
+ img_b_height, img_b_width, img_b_dim = image_b.shape
68
+
69
+ if img_a_dim == 3:
70
+ image_a = torch.stack([
71
+ image_a[:, :, 0],
72
+ image_a[:, :, 1],
73
+ image_a[:, :, 2],
74
+ torch.ones((img_a_height, img_a_width))
75
+ ], dim=2)
76
+
77
+ if img_b_dim == 3:
78
+ image_b = torch.stack([
79
+ image_b[:, :, 0],
80
+ image_b[:, :, 1],
81
+ image_b[:, :, 2],
82
+ torch.ones((img_b_height, img_b_width))
83
+ ], dim=2)
84
+
85
+ container_x = max(img_a_width, img_b_width) if container_width == 0 else container_width
86
+ container_y = max(img_a_height, img_b_height) if container_height == 0 else container_height
87
+
88
+ container_a = torch.zeros((container_y, container_x, 4))
89
+ container_b = torch.zeros((container_y, container_x, 4))
90
+
91
+ img_a_height_c, img_a_width_c = [
92
+ clip((images_a_y + img_a_height) - container_y),
93
+ clip((images_a_x + img_a_width) - container_x)
94
+ ]
95
+
96
+ img_b_height_c, img_b_width_c = [
97
+ clip((images_b_y + img_b_height) - container_y),
98
+ clip((images_b_x + img_b_width) - container_x)
99
+ ]
100
+
101
+ if img_a_height_c <= img_a_height and img_a_width_c <= img_a_width:
102
+ container_a[
103
+ images_a_y:img_a_height + images_a_y - img_a_height_c,
104
+ images_a_x:img_a_width + images_a_x - img_a_width_c
105
+ ] = image_a[
106
+ :img_a_height - img_a_height_c,
107
+ :img_a_width - img_a_width_c
108
+ ]
109
+
110
+ if img_b_height_c <= img_b_height and img_b_width_c <= img_b_width:
111
+ container_b[
112
+ images_b_y:img_b_height + images_b_y - img_b_height_c,
113
+ images_b_x:img_b_width + images_b_x - img_b_width_c
114
+ ] = image_b[
115
+ :img_b_height - img_b_height_c,
116
+ :img_b_width - img_b_width_c
117
+ ]
118
+
119
+ if background == "images_a":
120
+ return ImageF.alpha_composite(
121
+ container_a.tensor_to_image(),
122
+ container_b.tensor_to_image()
123
+ ).image_to_tensor()
124
+ else:
125
+ return ImageF.alpha_composite(
126
+ container_b.tensor_to_image(),
127
+ container_a.tensor_to_image()
128
+ ).image_to_tensor()
129
+
130
+ if method == "pair":
131
+ if len(images_a) != len(images_b):
132
+ raise ValueError("Size of image_a and image_b not equals for pair batch type.")
133
+
134
+ return (torch.stack([
135
+ composite(images_a[i], images_b[i]) for i in range(len(images_a))
136
+ ]),)
137
+ elif method == "matrix":
138
+ return (torch.stack([
139
+ composite(images_a[i], images_b[j]) for i in range(len(images_a)) for j in range(len(images_b))
140
+ ]),)
141
+
142
+ return None
143
+
144
+
145
+ class ImageCompositeAbsoluteByContainer:
146
+ def __init__(self):
147
+ pass
148
+
149
+ @classmethod
150
+ def INPUT_TYPES(cls):
151
+ return {
152
+ "required": {
153
+ "container": ("IMAGE",),
154
+ "images_a": ("IMAGE",),
155
+ "images_b": ("IMAGE",),
156
+ "images_a_x": ("INT", {
157
+ "default": 0,
158
+ "step": 1
159
+ }),
160
+ "images_a_y": ("INT", {
161
+ "default": 0,
162
+ "step": 1
163
+ }),
164
+ "images_b_x": ("INT", {
165
+ "default": 0,
166
+ "step": 1
167
+ }),
168
+ "images_b_y": ("INT", {
169
+ "default": 0,
170
+ "step": 1
171
+ }),
172
+ "background": (["images_a", "images_b"],),
173
+ "method": (["pair", "matrix"],),
174
+ },
175
+ }
176
+
177
+ RETURN_TYPES = ("IMAGE",)
178
+ FUNCTION = "node"
179
+ CATEGORY = "image/composite"
180
+
181
+ def node(
182
+ self,
183
+ container,
184
+ images_a,
185
+ images_b,
186
+ images_a_x,
187
+ images_a_y,
188
+ images_b_x,
189
+ images_b_y,
190
+ background,
191
+ method
192
+ ):
193
+ return ImageCompositeAbsolute().node(
194
+ images_a,
195
+ images_b,
196
+ images_a_x,
197
+ images_a_y,
198
+ images_b_x,
199
+ images_b_y,
200
+ container[0, :, :, 0].shape[1],
201
+ container[0, :, :, 0].shape[0],
202
+ background,
203
+ method
204
+ )
205
+
206
+
207
+ class ImageCompositeRelative:
208
+ def __init__(self):
209
+ pass
210
+
211
+ @classmethod
212
+ def INPUT_TYPES(cls):
213
+ return {
214
+ "required": {
215
+ "images_a": ("IMAGE",),
216
+ "images_b": ("IMAGE",),
217
+ "images_a_x": ("FLOAT", {
218
+ "default": 0.0,
219
+ "max": 1.0,
220
+ "step": 0.01
221
+ }),
222
+ "images_a_y": ("FLOAT", {
223
+ "default": 0.0,
224
+ "max": 1.0,
225
+ "step": 0.01
226
+ }),
227
+ "images_b_x": ("FLOAT", {
228
+ "default": 0.0,
229
+ "max": 1.0,
230
+ "step": 0.01
231
+ }),
232
+ "images_b_y": ("FLOAT", {
233
+ "default": 0.0,
234
+ "max": 1.0,
235
+ "step": 0.01
236
+ }),
237
+ "background": (["images_a", "images_b"],),
238
+ "container_size_type": (["max", "sum", "sum_width", "sum_height"],),
239
+ "method": (["pair", "matrix"],),
240
+ },
241
+ }
242
+
243
+ RETURN_TYPES = ("IMAGE",)
244
+ FUNCTION = "node"
245
+ CATEGORY = "image/composite"
246
+
247
+ def node(
248
+ self,
249
+ images_a,
250
+ images_b,
251
+ images_a_x,
252
+ images_a_y,
253
+ images_b_x,
254
+ images_b_y,
255
+ background,
256
+ container_size_type,
257
+ method
258
+ ):
259
+ def offset_by_percent(container_size: int, image_size: int, percent: float):
260
+ return int((container_size - image_size) * percent)
261
+
262
+ img_a_height, img_a_width = images_a[0, :, :, 0].shape
263
+ img_b_height, img_b_width = images_b[0, :, :, 0].shape
264
+
265
+ if container_size_type == "max":
266
+ container_width = max(img_a_width, img_b_width)
267
+ container_height = max(img_a_height, img_b_height)
268
+ elif container_size_type == "sum":
269
+ container_width = img_a_width + img_b_width
270
+ container_height = img_a_height + img_b_height
271
+ elif container_size_type == "sum_width":
272
+ container_width = img_a_width + img_b_width
273
+ container_height = max(img_a_height, img_b_height)
274
+ elif container_size_type == "sum_height":
275
+ container_width = max(img_a_width, img_b_width)
276
+ container_height = img_a_height + img_a_height
277
+ else:
278
+ raise ValueError()
279
+
280
+ return ImageCompositeAbsolute().node(
281
+ images_a,
282
+ images_b,
283
+ offset_by_percent(container_width, img_a_width, images_a_x),
284
+ offset_by_percent(container_height, img_a_height, images_a_y),
285
+ offset_by_percent(container_width, img_b_width, images_b_x),
286
+ offset_by_percent(container_height, img_b_height, images_b_y),
287
+ container_width,
288
+ container_height,
289
+ background,
290
+ method
291
+ )
292
+
293
+
294
+ class ImageCompositeRelativeByContainer:
295
+ def __init__(self):
296
+ pass
297
+
298
+ @classmethod
299
+ def INPUT_TYPES(cls):
300
+ return {
301
+ "required": {
302
+ "container": ("IMAGE",),
303
+ "images_a": ("IMAGE",),
304
+ "images_b": ("IMAGE",),
305
+ "images_a_x": ("FLOAT", {
306
+ "default": 0.0,
307
+ "max": 1.0,
308
+ "step": 0.01
309
+ }),
310
+ "images_a_y": ("FLOAT", {
311
+ "default": 0.0,
312
+ "max": 1.0,
313
+ "step": 0.01
314
+ }),
315
+ "images_b_x": ("FLOAT", {
316
+ "default": 0.0,
317
+ "max": 1.0,
318
+ "step": 0.01
319
+ }),
320
+ "images_b_y": ("FLOAT", {
321
+ "default": 0.0,
322
+ "max": 1.0,
323
+ "step": 0.01
324
+ }),
325
+ "background": (["images_a", "images_b"],),
326
+ "method": (["pair", "matrix"],),
327
+ },
328
+ }
329
+
330
+ RETURN_TYPES = ("IMAGE",)
331
+ FUNCTION = "node"
332
+ CATEGORY = "image/composite"
333
+
334
+ def node(
335
+ self,
336
+ container,
337
+ images_a,
338
+ images_b,
339
+ images_a_x,
340
+ images_a_y,
341
+ images_b_x,
342
+ images_b_y,
343
+ background,
344
+ method
345
+ ):
346
+ def offset_by_percent(container_size: int, image_size: int, percent: float):
347
+ return int((container_size - image_size) * percent)
348
+
349
+ img_a_height, img_a_width = images_a[0, :, :, 0].shape
350
+ img_b_height, img_b_width = images_b[0, :, :, 0].shape
351
+
352
+ container_width = container[0, :, :, 0].shape[1]
353
+ container_height = container[0, :, :, 0].shape[0]
354
+
355
+ if container_width < max(img_a_width, img_b_width) or container_height < max(img_a_height, img_b_height):
356
+ raise ValueError("Container can't be smaller then max width or height of images.")
357
+
358
+ return ImageCompositeAbsolute().node(
359
+ images_a,
360
+ images_b,
361
+ offset_by_percent(container_width, img_a_width, images_a_x),
362
+ offset_by_percent(container_height, img_a_height, images_a_y),
363
+ offset_by_percent(container_width, img_b_width, images_b_x),
364
+ offset_by_percent(container_height, img_b_height, images_b_y),
365
+ container_width,
366
+ container_height,
367
+ background,
368
+ method
369
+ )
370
+
371
+
372
+ NODE_CLASS_MAPPINGS = {
373
+ "ImageCompositeAbsolute": ImageCompositeAbsolute,
374
+ "ImageCompositeAbsoluteByContainer": ImageCompositeAbsoluteByContainer,
375
+ "ImageCompositeRelative": ImageCompositeRelative,
376
+ "ImageCompositeRelativeByContainer": ImageCompositeRelativeByContainer
377
+ }
ComfyUI-Allor/modules/ImageContainer.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+
3
+ from .Utils import create_rgba_image
4
+
5
+
6
+ class ImageContainer:
7
+ def __init__(self):
8
+ pass
9
+
10
+ @classmethod
11
+ def INPUT_TYPES(cls):
12
+ return {
13
+ "required": {
14
+ "width": ("INT", {
15
+ "default": 512,
16
+ "min": 1,
17
+ "step": 1
18
+ }),
19
+ "height": ("INT", {
20
+ "default": 512,
21
+ "min": 1,
22
+ "step": 1
23
+ }),
24
+ "red": ("INT", {
25
+ "default": 255,
26
+ "max": 255,
27
+ "step": 1
28
+ }),
29
+ "green": ("INT", {
30
+ "default": 255,
31
+ "max": 255,
32
+ "step": 1
33
+ }),
34
+ "blue": ("INT", {
35
+ "default": 255,
36
+ "max": 255,
37
+ "step": 1
38
+ }),
39
+ "alpha": ("FLOAT", {
40
+ "default": 0.0,
41
+ "max": 1.0,
42
+ "step": 0.01
43
+ }),
44
+ },
45
+ }
46
+
47
+ RETURN_TYPES = ("IMAGE",)
48
+ FUNCTION = "node"
49
+ CATEGORY = "image/container"
50
+
51
+ def node(self, width, height, red, green, blue, alpha):
52
+ return (create_rgba_image(width, height, (red, green, blue, int(alpha * 255))).image_to_tensor().unsqueeze(0),)
53
+
54
+
55
+ class ImageContainerInheritanceAdd:
56
+ def __init__(self):
57
+ pass
58
+
59
+ @classmethod
60
+ def INPUT_TYPES(cls):
61
+ return {
62
+ "required": {
63
+ "images": ("IMAGE",),
64
+ "add_width": ("INT", {
65
+ "default": 0,
66
+ "step": 1
67
+ }),
68
+ "add_height": ("INT", {
69
+ "default": 0,
70
+ "step": 1
71
+ }),
72
+ "red": ("INT", {
73
+ "default": 255,
74
+ "max": 255,
75
+ "step": 1
76
+ }),
77
+ "green": ("INT", {
78
+ "default": 255,
79
+ "max": 255,
80
+ "step": 1
81
+ }),
82
+ "blue": ("INT", {
83
+ "default": 255,
84
+ "max": 255,
85
+ "step": 1
86
+ }),
87
+ "alpha": ("FLOAT", {
88
+ "default": 0.0,
89
+ "max": 1.0,
90
+ "step": 0.01
91
+ }),
92
+ "method": (["single", "for_each"],),
93
+ },
94
+ }
95
+
96
+ RETURN_TYPES = ("IMAGE",)
97
+ FUNCTION = "node"
98
+ CATEGORY = "image/container"
99
+
100
+ def node(self, images, add_width, add_height, red, green, blue, alpha, method):
101
+ width, height = images[0, :, :, 0].shape
102
+
103
+ width = width + add_width
104
+ height = height + add_height
105
+
106
+ image = create_rgba_image(width, height, (red, green, blue, int(alpha * 255))).image_to_tensor()
107
+
108
+ if method == "single":
109
+ return (image.unsqueeze(0),)
110
+ else:
111
+ length = len(images)
112
+
113
+ images = torch.zeros(length, height, width, 4)
114
+ images[:, :, :] = image
115
+ return (images,)
116
+
117
+
118
+ class ImageContainerInheritanceScale:
119
+ def __init__(self):
120
+ pass
121
+
122
+ @classmethod
123
+ def INPUT_TYPES(cls):
124
+ return {
125
+ "required": {
126
+ "images": ("IMAGE",),
127
+ "scale_width": ("FLOAT", {
128
+ "default": 1.0,
129
+ "step": 0.1
130
+ }),
131
+ "scale_height": ("FLOAT", {
132
+ "default": 1.0,
133
+ "step": 0.1
134
+ }),
135
+ "red": ("INT", {
136
+ "default": 255,
137
+ "max": 255,
138
+ "step": 1
139
+ }),
140
+ "green": ("INT", {
141
+ "default": 255,
142
+ "max": 255,
143
+ "step": 1
144
+ }),
145
+ "blue": ("INT", {
146
+ "default": 255,
147
+ "max": 255,
148
+ "step": 1
149
+ }),
150
+ "alpha": ("FLOAT", {
151
+ "default": 0.0,
152
+ "max": 1.0,
153
+ "step": 0.01
154
+ }),
155
+ "method": (["single", "for_each"],),
156
+ },
157
+ }
158
+
159
+ RETURN_TYPES = ("IMAGE",)
160
+ FUNCTION = "node"
161
+ CATEGORY = "image/container"
162
+
163
+ def node(self, images, scale_width, scale_height, red, green, blue, alpha, method):
164
+ height, width = images[0, :, :, 0].shape
165
+
166
+ width = int((width * scale_width) - width)
167
+ height = int((height * scale_height) - height)
168
+
169
+ return ImageContainerInheritanceAdd() \
170
+ .node(images, width, height, red, green, blue, alpha, method)
171
+
172
+
173
+ class ImageContainerInheritanceMax:
174
+ def __init__(self):
175
+ pass
176
+
177
+ @classmethod
178
+ def INPUT_TYPES(cls):
179
+ return {
180
+ "required": {
181
+ "images_a": ("IMAGE",),
182
+ "images_b": ("IMAGE",),
183
+ "red": ("INT", {
184
+ "default": 255,
185
+ "max": 255,
186
+ "step": 1
187
+ }),
188
+ "green": ("INT", {
189
+ "default": 255,
190
+ "max": 255,
191
+ "step": 1
192
+ }),
193
+ "blue": ("INT", {
194
+ "default": 255,
195
+ "max": 255,
196
+ "step": 1
197
+ }),
198
+ "alpha": ("FLOAT", {
199
+ "default": 0.0,
200
+ "max": 1.0,
201
+ "step": 0.01
202
+ }),
203
+ "method": (["single", "for_each_pair", "for_each_matrix"],),
204
+ },
205
+ }
206
+
207
+ RETURN_TYPES = ("IMAGE",)
208
+ FUNCTION = "node"
209
+ CATEGORY = "image/container"
210
+
211
+ def node(self, images_a, images_b, red, green, blue, alpha, method):
212
+ img_a_height, img_a_width = images_a[0, :, :, 0].shape
213
+ img_b_height, img_b_width = images_b[0, :, :, 0].shape
214
+
215
+ width = max(img_a_width, img_b_width)
216
+ height = max(img_a_height, img_b_height)
217
+
218
+ image = create_rgba_image(width, height, (red, green, blue, int(alpha * 255))).image_to_tensor()
219
+
220
+ if method == "single":
221
+ return (image.unsqueeze(0),)
222
+ elif method == "for_each_pair":
223
+ length = len(images_a)
224
+ images = torch.zeros(length, height, width, 4)
225
+ else:
226
+ length = len(images_a) * len(images_b)
227
+ images = torch.zeros(length, height, width, 4)
228
+
229
+ images[:, :, :] = image
230
+ return (images,)
231
+
232
+
233
+ class ImageContainerInheritanceSum:
234
+ def __init__(self):
235
+ pass
236
+
237
+ @classmethod
238
+ def INPUT_TYPES(cls):
239
+ return {
240
+ "required": {
241
+ "images_a": ("IMAGE",),
242
+ "images_b": ("IMAGE",),
243
+ "red": ("INT", {
244
+ "default": 255,
245
+ "max": 255,
246
+ "step": 1
247
+ }),
248
+ "green": ("INT", {
249
+ "default": 255,
250
+ "max": 255,
251
+ "step": 1
252
+ }),
253
+ "blue": ("INT", {
254
+ "default": 255,
255
+ "max": 255,
256
+ "step": 1
257
+ }),
258
+ "alpha": ("FLOAT", {
259
+ "default": 0.0,
260
+ "max": 1.0,
261
+ "step": 0.01
262
+ }),
263
+ "container_size_type": (["sum", "sum_width", "sum_height"],),
264
+ "method": (["single", "for_each_pair", "for_each_matrix"],),
265
+ },
266
+ }
267
+
268
+ RETURN_TYPES = ("IMAGE",)
269
+ FUNCTION = "node"
270
+ CATEGORY = "image/container"
271
+
272
+ def node(self, images_a, images_b, red, green, blue, alpha, container_size_type, method):
273
+ img_a_height, img_a_width = images_a[0, :, :, 0].shape
274
+ img_b_height, img_b_width = images_b[0, :, :, 0].shape
275
+
276
+ if container_size_type == "sum":
277
+ width = img_a_width + img_b_width
278
+ height = img_a_height + img_b_height
279
+ elif container_size_type == "sum_width":
280
+ if img_a_height != img_b_height:
281
+ raise ValueError()
282
+
283
+ width = img_a_width + img_b_width
284
+ height = img_a_height
285
+ elif container_size_type == "sum_height":
286
+ if img_a_width != img_b_width:
287
+ raise ValueError()
288
+
289
+ width = img_a_width
290
+ height = img_a_height + img_b_height
291
+ else:
292
+ raise ValueError()
293
+
294
+ image = create_rgba_image(width, height, (red, green, blue, int(alpha * 255))).image_to_tensor()
295
+
296
+ if method == "single":
297
+ return (image.unsqueeze(0),)
298
+ elif method == "for_each_pair":
299
+ length = len(images_a)
300
+ images = torch.zeros(length, height, width, 4)
301
+ else:
302
+ length = len(images_a) * len(images_b)
303
+ images = torch.zeros(length, height, width, 4)
304
+
305
+ images[:, :, :] = image
306
+ return (images,)
307
+
308
+
309
+ NODE_CLASS_MAPPINGS = {
310
+ "ImageContainer": ImageContainer,
311
+ "ImageContainerInheritanceAdd": ImageContainerInheritanceAdd,
312
+ "ImageContainerInheritanceScale": ImageContainerInheritanceScale,
313
+ "ImageContainerInheritanceMax": ImageContainerInheritanceMax,
314
+ "ImageContainerInheritanceSum": ImageContainerInheritanceSum
315
+ }
ComfyUI-Allor/modules/ImageDraw.py ADDED
@@ -0,0 +1,1847 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import ImageDraw, Image
2
+
3
+ from .Utils import get_sampler_by_name
4
+
5
+
6
+ class ImageDrawArc:
7
+ def __init__(self):
8
+ pass
9
+
10
+ @classmethod
11
+ def INPUT_TYPES(cls):
12
+ return {
13
+ "required": {
14
+ "width": ("INT", {
15
+ "default": 256,
16
+ "min": 1,
17
+ "step": 1
18
+ }),
19
+ "height": ("INT", {
20
+ "default": 256,
21
+ "min": 1,
22
+ "step": 1
23
+ }),
24
+ "size": ("INT", {
25
+ "default": 1,
26
+ "min": 1,
27
+ "step": 1
28
+ }),
29
+ "start_x": ("FLOAT", {
30
+ "default": 0.0,
31
+ "max": 1.0,
32
+ "step": 0.01
33
+ }),
34
+ "start_y": ("FLOAT", {
35
+ "default": 0.0,
36
+ "max": 1.0,
37
+ "step": 0.01
38
+ }),
39
+ "end_x": ("FLOAT", {
40
+ "default": 1.0,
41
+ "max": 1.0,
42
+ "step": 0.01
43
+ }),
44
+ "end_y": ("FLOAT", {
45
+ "default": 1.0,
46
+ "max": 1.0,
47
+ "step": 0.01
48
+ }),
49
+ "start": ("INT", {
50
+ "default": 0,
51
+ "max": 360,
52
+ "step": 1
53
+ }),
54
+ "end": ("INT", {
55
+ "default": 180,
56
+ "max": 360,
57
+ "step": 1
58
+ }),
59
+ "red": ("INT", {
60
+ "default": 255,
61
+ "max": 255,
62
+ "step": 1
63
+ }),
64
+ "green": ("INT", {
65
+ "default": 255,
66
+ "max": 255,
67
+ "step": 1
68
+ }),
69
+ "blue": ("INT", {
70
+ "default": 255,
71
+ "max": 255,
72
+ "step": 1
73
+ }),
74
+ "alpha": ("FLOAT", {
75
+ "default": 1.0,
76
+ "max": 1.0,
77
+ "step": 0.01
78
+ }),
79
+ "SSAA": ("INT", {
80
+ "default": 4,
81
+ "min": 1,
82
+ "max": 16,
83
+ "step": 1
84
+ }),
85
+ "method": (["lanczos", "bicubic", "hamming", "bilinear", "box", "nearest"],),
86
+ },
87
+ }
88
+
89
+ RETURN_TYPES = ("IMAGE",)
90
+ FUNCTION = "node"
91
+ CATEGORY = "image/draw"
92
+
93
+ # noinspection PyPep8Naming, PyUnresolvedReferences
94
+ def node(self, width, height, size, start_x, start_y, end_x, end_y, start, end, red, green, blue, alpha, SSAA, method):
95
+ canvas = Image.new("RGBA", (width * SSAA, height * SSAA), (0, 0, 0, 0))
96
+
97
+ draw = ImageDraw.Draw(canvas)
98
+ draw.arc(
99
+ [
100
+ (width * start_x * SSAA, height * start_y * SSAA),
101
+ (width * end_x * SSAA, height * end_y * SSAA)
102
+ ],
103
+ start, end, (red, green, blue, int(alpha * 255)), size * SSAA
104
+ )
105
+
106
+ canvas = canvas.resize((width, height), get_sampler_by_name(method))
107
+
108
+ return (canvas.image_to_tensor().unsqueeze(0),)
109
+
110
+
111
+ class ImageDrawArcByContainer:
112
+ def __init__(self):
113
+ pass
114
+
115
+ @classmethod
116
+ def INPUT_TYPES(cls):
117
+ return {
118
+ "required": {
119
+ "container": ("IMAGE",),
120
+ "size": ("INT", {
121
+ "default": 1,
122
+ "min": 1,
123
+ "step": 1
124
+ }),
125
+ "start_x": ("FLOAT", {
126
+ "default": 0.0,
127
+ "max": 1.0,
128
+ "step": 0.01
129
+ }),
130
+ "start_y": ("FLOAT", {
131
+ "default": 0.0,
132
+ "max": 1.0,
133
+ "step": 0.01
134
+ }),
135
+ "end_x": ("FLOAT", {
136
+ "default": 1.0,
137
+ "max": 1.0,
138
+ "step": 0.01
139
+ }),
140
+ "end_y": ("FLOAT", {
141
+ "default": 1.0,
142
+ "max": 1.0,
143
+ "step": 0.01
144
+ }),
145
+ "start": ("INT", {
146
+ "default": 0,
147
+ "max": 360,
148
+ "step": 1
149
+ }),
150
+ "end": ("INT", {
151
+ "default": 180,
152
+ "max": 360,
153
+ "step": 1
154
+ }),
155
+ "red": ("INT", {
156
+ "default": 255,
157
+ "max": 255,
158
+ "step": 1
159
+ }),
160
+ "green": ("INT", {
161
+ "default": 255,
162
+ "max": 255,
163
+ "step": 1
164
+ }),
165
+ "blue": ("INT", {
166
+ "default": 255,
167
+ "max": 255,
168
+ "step": 1
169
+ }),
170
+ "alpha": ("FLOAT", {
171
+ "default": 1.0,
172
+ "max": 1.0,
173
+ "step": 0.01
174
+ }),
175
+ "SSAA": ("INT", {
176
+ "default": 4,
177
+ "min": 1,
178
+ "max": 16,
179
+ "step": 1
180
+ }),
181
+ "method": (["lanczos", "bicubic", "hamming", "bilinear", "box", "nearest"],),
182
+ },
183
+ }
184
+
185
+ RETURN_TYPES = ("IMAGE",)
186
+ FUNCTION = "node"
187
+ CATEGORY = "image/draw"
188
+
189
+ # noinspection PyPep8Naming
190
+ def node(self, container, size, start_x, start_y, end_x, end_y, start, end, red, green, blue, alpha, SSAA, method):
191
+ return ImageDrawArc().node(
192
+ container[0, :, :, 0].shape[1],
193
+ container[0, :, :, 0].shape[0],
194
+ size,
195
+ start_x,
196
+ start_y,
197
+ end_x,
198
+ end_y,
199
+ start,
200
+ end,
201
+ red,
202
+ green,
203
+ blue,
204
+ alpha,
205
+ SSAA,
206
+ method
207
+ )
208
+
209
+
210
+ class ImageDrawChord:
211
+ def __init__(self):
212
+ pass
213
+
214
+ @classmethod
215
+ def INPUT_TYPES(cls):
216
+ return {
217
+ "required": {
218
+ "width": ("INT", {
219
+ "default": 256,
220
+ "min": 1,
221
+ "step": 1
222
+ }),
223
+ "height": ("INT", {
224
+ "default": 256,
225
+ "min": 1,
226
+ "step": 1
227
+ }),
228
+ "size": ("INT", {
229
+ "default": 1,
230
+ "min": 1,
231
+ "step": 1
232
+ }),
233
+ "start_x": ("FLOAT", {
234
+ "default": 0.0,
235
+ "max": 1.0,
236
+ "step": 0.01
237
+ }),
238
+ "start_y": ("FLOAT", {
239
+ "default": 0.0,
240
+ "max": 1.0,
241
+ "step": 0.01
242
+ }),
243
+ "end_x": ("FLOAT", {
244
+ "default": 1.0,
245
+ "max": 1.0,
246
+ "step": 0.01
247
+ }),
248
+ "end_y": ("FLOAT", {
249
+ "default": 1.0,
250
+ "max": 1.0,
251
+ "step": 0.01
252
+ }),
253
+ "start": ("INT", {
254
+ "default": 0,
255
+ "max": 360,
256
+ "step": 1
257
+ }),
258
+ "end": ("INT", {
259
+ "default": 180,
260
+ "max": 360,
261
+ "step": 1
262
+ }),
263
+ "red": ("INT", {
264
+ "default": 255,
265
+ "max": 255,
266
+ "step": 1
267
+ }),
268
+ "green": ("INT", {
269
+ "default": 255,
270
+ "max": 255,
271
+ "step": 1
272
+ }),
273
+ "blue": ("INT", {
274
+ "default": 255,
275
+ "max": 255,
276
+ "step": 1
277
+ }),
278
+ "alpha": ("FLOAT", {
279
+ "default": 1.0,
280
+ "max": 1.0,
281
+ "step": 0.01
282
+ }),
283
+ "SSAA": ("INT", {
284
+ "default": 4,
285
+ "min": 1,
286
+ "max": 16,
287
+ "step": 1
288
+ }),
289
+ "method": (["lanczos", "bicubic", "hamming", "bilinear", "box", "nearest"],),
290
+ },
291
+ }
292
+
293
+ RETURN_TYPES = ("IMAGE",)
294
+ FUNCTION = "node"
295
+ CATEGORY = "image/draw"
296
+
297
+ # noinspection PyPep8Naming, PyUnresolvedReferences
298
+ def node(self, width, height, size, start_x, start_y, end_x, end_y, start, end, red, green, blue, alpha, SSAA, method):
299
+ canvas = Image.new("RGBA", (width * SSAA, height * SSAA), (0, 0, 0, 0))
300
+
301
+ draw = ImageDraw.Draw(canvas)
302
+ draw.chord(
303
+ [
304
+ (width * start_x * SSAA, height * start_y * SSAA),
305
+ (width * end_x * SSAA, height * end_y * SSAA)
306
+ ],
307
+ start, end, (red, green, blue, int(alpha * 255)), size * SSAA
308
+ )
309
+
310
+ canvas = canvas.resize((width, height), get_sampler_by_name(method))
311
+
312
+ return (canvas.image_to_tensor().unsqueeze(0),)
313
+
314
+
315
+ class ImageDrawChordByContainer:
316
+ def __init__(self):
317
+ pass
318
+
319
+ @classmethod
320
+ def INPUT_TYPES(cls):
321
+ return {
322
+ "required": {
323
+ "container": ("IMAGE",),
324
+ "size": ("INT", {
325
+ "default": 1,
326
+ "min": 1,
327
+ "step": 1
328
+ }),
329
+ "start_x": ("FLOAT", {
330
+ "default": 0.0,
331
+ "max": 1.0,
332
+ "step": 0.01
333
+ }),
334
+ "start_y": ("FLOAT", {
335
+ "default": 0.0,
336
+ "max": 1.0,
337
+ "step": 0.01
338
+ }),
339
+ "end_x": ("FLOAT", {
340
+ "default": 1.0,
341
+ "max": 1.0,
342
+ "step": 0.01
343
+ }),
344
+ "end_y": ("FLOAT", {
345
+ "default": 1.0,
346
+ "max": 1.0,
347
+ "step": 0.01
348
+ }),
349
+ "start": ("INT", {
350
+ "default": 0,
351
+ "max": 360,
352
+ "step": 1
353
+ }),
354
+ "end": ("INT", {
355
+ "default": 180,
356
+ "max": 360,
357
+ "step": 1
358
+ }),
359
+ "red": ("INT", {
360
+ "default": 255,
361
+ "max": 255,
362
+ "step": 1
363
+ }),
364
+ "green": ("INT", {
365
+ "default": 255,
366
+ "max": 255,
367
+ "step": 1
368
+ }),
369
+ "blue": ("INT", {
370
+ "default": 255,
371
+ "max": 255,
372
+ "step": 1
373
+ }),
374
+ "alpha": ("FLOAT", {
375
+ "default": 1.0,
376
+ "max": 1.0,
377
+ "step": 0.01
378
+ }),
379
+ "SSAA": ("INT", {
380
+ "default": 4,
381
+ "min": 1,
382
+ "max": 16,
383
+ "step": 1
384
+ }),
385
+ "method": (["lanczos", "bicubic", "hamming", "bilinear", "box", "nearest"],),
386
+ },
387
+ }
388
+
389
+ RETURN_TYPES = ("IMAGE",)
390
+ FUNCTION = "node"
391
+ CATEGORY = "image/draw"
392
+
393
+ # noinspection PyPep8Naming
394
+ def node(self, container, size, start_x, start_y, end_x, end_y, start, end, red, green, blue, alpha, SSAA, method):
395
+ return ImageDrawChord().node(
396
+ container[0, :, :, 0].shape[1],
397
+ container[0, :, :, 0].shape[0],
398
+ size,
399
+ start_x,
400
+ start_y,
401
+ end_x,
402
+ end_y,
403
+ start,
404
+ end,
405
+ red,
406
+ green,
407
+ blue,
408
+ alpha,
409
+ SSAA,
410
+ method
411
+ )
412
+
413
+
414
+ class ImageDrawEllipse:
415
+ def __init__(self):
416
+ pass
417
+
418
+ @classmethod
419
+ def INPUT_TYPES(cls):
420
+ return {
421
+ "required": {
422
+ "width": ("INT", {
423
+ "default": 256,
424
+ "min": 1,
425
+ "step": 1
426
+ }),
427
+ "height": ("INT", {
428
+ "default": 256,
429
+ "min": 1,
430
+ "step": 1
431
+ }),
432
+ "start_x": ("FLOAT", {
433
+ "default": 0.0,
434
+ "max": 1.0,
435
+ "step": 0.01
436
+ }),
437
+ "start_y": ("FLOAT", {
438
+ "default": 0.0,
439
+ "max": 1.0,
440
+ "step": 0.01
441
+ }),
442
+ "end_x": ("FLOAT", {
443
+ "default": 1.0,
444
+ "max": 1.0,
445
+ "step": 0.01
446
+ }),
447
+ "end_y": ("FLOAT", {
448
+ "default": 1.0,
449
+ "max": 1.0,
450
+ "step": 0.01
451
+ }),
452
+ "outline_size": ("INT", {
453
+ "default": 1,
454
+ "step": 1
455
+ }),
456
+ "outline_red": ("INT", {
457
+ "default": 0,
458
+ "max": 255,
459
+ "step": 1
460
+ }),
461
+ "outline_green": ("INT", {
462
+ "default": 0,
463
+ "max": 255,
464
+ "step": 1
465
+ }),
466
+ "outline_blue": ("INT", {
467
+ "default": 0,
468
+ "max": 255,
469
+ "step": 1
470
+ }),
471
+ "outline_alpha": ("FLOAT", {
472
+ "default": 1.0,
473
+ "max": 1.0,
474
+ "step": 0.01
475
+ }),
476
+ "fill_red": ("INT", {
477
+ "default": 255,
478
+ "max": 255,
479
+ "step": 1
480
+ }),
481
+ "fill_green": ("INT", {
482
+ "default": 255,
483
+ "max": 255,
484
+ "step": 1
485
+ }),
486
+ "fill_blue": ("INT", {
487
+ "default": 255,
488
+ "max": 255,
489
+ "step": 1
490
+ }),
491
+ "fill_alpha": ("FLOAT", {
492
+ "default": 1.0,
493
+ "max": 1.0,
494
+ "step": 0.01
495
+ }),
496
+ "SSAA": ("INT", {
497
+ "default": 4,
498
+ "min": 1,
499
+ "max": 16,
500
+ "step": 1
501
+ }),
502
+ "method": (["lanczos", "bicubic", "hamming", "bilinear", "box", "nearest"],),
503
+ },
504
+ }
505
+
506
+ RETURN_TYPES = ("IMAGE",)
507
+ FUNCTION = "node"
508
+ CATEGORY = "image/draw"
509
+
510
+ # noinspection PyPep8Naming, PyUnresolvedReferences
511
+ def node(
512
+ self,
513
+ width,
514
+ height,
515
+ start_x,
516
+ start_y,
517
+ end_x,
518
+ end_y,
519
+ outline_size,
520
+ outline_red,
521
+ outline_green,
522
+ outline_blue,
523
+ outline_alpha,
524
+ fill_red,
525
+ fill_green,
526
+ fill_blue,
527
+ fill_alpha,
528
+ SSAA,
529
+ method
530
+ ):
531
+ canvas = Image.new("RGBA", (width * SSAA, height * SSAA), (0, 0, 0, 0))
532
+
533
+ draw = ImageDraw.Draw(canvas)
534
+ draw.ellipse(
535
+ [
536
+ (width * start_x * SSAA, height * start_y * SSAA),
537
+ (width * end_x * SSAA, height * end_y * SSAA)
538
+ ],
539
+ (fill_red, fill_green, fill_blue, int(fill_alpha * 255)),
540
+ (outline_red, outline_green, outline_blue, int(outline_alpha * 255)),
541
+ outline_size * SSAA
542
+ )
543
+
544
+ canvas = canvas.resize((width, height), get_sampler_by_name(method))
545
+
546
+ return (canvas.image_to_tensor().unsqueeze(0),)
547
+
548
+
549
+ class ImageDrawEllipseByContainer:
550
+ def __init__(self):
551
+ pass
552
+
553
+ @classmethod
554
+ def INPUT_TYPES(cls):
555
+ return {
556
+ "required": {
557
+ "container": ("IMAGE",),
558
+ "start_x": ("FLOAT", {
559
+ "default": 0.0,
560
+ "max": 1.0,
561
+ "step": 0.01
562
+ }),
563
+ "start_y": ("FLOAT", {
564
+ "default": 0.0,
565
+ "max": 1.0,
566
+ "step": 0.01
567
+ }),
568
+ "end_x": ("FLOAT", {
569
+ "default": 1.0,
570
+ "max": 1.0,
571
+ "step": 0.01
572
+ }),
573
+ "end_y": ("FLOAT", {
574
+ "default": 1.0,
575
+ "max": 1.0,
576
+ "step": 0.01
577
+ }),
578
+ "outline_size": ("INT", {
579
+ "default": 1,
580
+ "step": 1
581
+ }),
582
+ "outline_red": ("INT", {
583
+ "default": 0,
584
+ "max": 255,
585
+ "step": 1
586
+ }),
587
+ "outline_green": ("INT", {
588
+ "default": 0,
589
+ "max": 255,
590
+ "step": 1
591
+ }),
592
+ "outline_blue": ("INT", {
593
+ "default": 0,
594
+ "max": 255,
595
+ "step": 1
596
+ }),
597
+ "outline_alpha": ("FLOAT", {
598
+ "default": 1.0,
599
+ "max": 1.0,
600
+ "step": 0.01
601
+ }),
602
+ "fill_red": ("INT", {
603
+ "default": 255,
604
+ "max": 255,
605
+ "step": 1
606
+ }),
607
+ "fill_green": ("INT", {
608
+ "default": 255,
609
+ "max": 255,
610
+ "step": 1
611
+ }),
612
+ "fill_blue": ("INT", {
613
+ "default": 255,
614
+ "max": 255,
615
+ "step": 1
616
+ }),
617
+ "fill_alpha": ("FLOAT", {
618
+ "default": 1.0,
619
+ "max": 1.0,
620
+ "step": 0.01
621
+ }),
622
+ "SSAA": ("INT", {
623
+ "default": 4,
624
+ "min": 1,
625
+ "max": 16,
626
+ "step": 1
627
+ }),
628
+ "method": (["lanczos", "bicubic", "hamming", "bilinear", "box", "nearest"],),
629
+ },
630
+ }
631
+
632
+ RETURN_TYPES = ("IMAGE",)
633
+ FUNCTION = "node"
634
+ CATEGORY = "image/draw"
635
+
636
+ # noinspection PyPep8Naming
637
+ def node(
638
+ self,
639
+ container,
640
+ start_x,
641
+ start_y,
642
+ end_x,
643
+ end_y,
644
+ outline_size,
645
+ outline_red,
646
+ outline_green,
647
+ outline_blue,
648
+ outline_alpha,
649
+ fill_red,
650
+ fill_green,
651
+ fill_blue,
652
+ fill_alpha,
653
+ SSAA,
654
+ method
655
+ ):
656
+ return ImageDrawEllipse().node(
657
+ container[0, :, :, 0].shape[1],
658
+ container[0, :, :, 0].shape[0],
659
+ start_x,
660
+ start_y,
661
+ end_x,
662
+ end_y,
663
+ outline_size,
664
+ outline_red,
665
+ outline_green,
666
+ outline_blue,
667
+ outline_alpha,
668
+ fill_red,
669
+ fill_green,
670
+ fill_blue,
671
+ fill_alpha,
672
+ SSAA,
673
+ method
674
+ )
675
+
676
+
677
+ class ImageDrawLine:
678
+ def __init__(self):
679
+ pass
680
+
681
+ @classmethod
682
+ def INPUT_TYPES(cls):
683
+ return {
684
+ "required": {
685
+ "width": ("INT", {
686
+ "default": 256,
687
+ "min": 1,
688
+ "step": 1
689
+ }),
690
+ "height": ("INT", {
691
+ "default": 256,
692
+ "min": 1,
693
+ "step": 1
694
+ }),
695
+ "size": ("INT", {
696
+ "default": 1,
697
+ "min": 1,
698
+ "step": 1
699
+ }),
700
+ "start_x": ("FLOAT", {
701
+ "default": 0.0,
702
+ "max": 1.0,
703
+ "step": 0.01
704
+ }),
705
+ "start_y": ("FLOAT", {
706
+ "default": 0.0,
707
+ "max": 1.0,
708
+ "step": 0.01
709
+ }),
710
+ "end_x": ("FLOAT", {
711
+ "default": 1.0,
712
+ "max": 1.0,
713
+ "step": 0.01
714
+ }),
715
+ "end_y": ("FLOAT", {
716
+ "default": 1.0,
717
+ "max": 1.0,
718
+ "step": 0.01
719
+ }),
720
+ "red": ("INT", {
721
+ "default": 255,
722
+ "max": 255,
723
+ "step": 1
724
+ }),
725
+ "green": ("INT", {
726
+ "default": 255,
727
+ "max": 255,
728
+ "step": 1
729
+ }),
730
+ "blue": ("INT", {
731
+ "default": 255,
732
+ "max": 255,
733
+ "step": 1
734
+ }),
735
+ "alpha": ("FLOAT", {
736
+ "default": 1.0,
737
+ "max": 1.0,
738
+ "step": 0.01
739
+ }),
740
+ "SSAA": ("INT", {
741
+ "default": 4,
742
+ "min": 1,
743
+ "max": 16,
744
+ "step": 1
745
+ }),
746
+ "method": (["lanczos", "bicubic", "hamming", "bilinear", "box", "nearest"],),
747
+ },
748
+ }
749
+
750
+ RETURN_TYPES = ("IMAGE",)
751
+ FUNCTION = "node"
752
+ CATEGORY = "image/draw"
753
+
754
+ # noinspection PyPep8Naming, PyUnresolvedReferences
755
+ def node(self, width, height, size, start_x, start_y, end_x, end_y, red, green, blue, alpha, SSAA, method):
756
+ canvas = Image.new("RGBA", (width * SSAA, height * SSAA), (0, 0, 0, 0))
757
+
758
+ draw = ImageDraw.Draw(canvas)
759
+ draw.line(
760
+ [
761
+ (width * start_x * SSAA, height * start_y * SSAA),
762
+ (width * end_x * SSAA, height * end_y * SSAA)
763
+ ],
764
+ (red, green, blue, int(alpha * 255)), size * SSAA
765
+ )
766
+
767
+ canvas = canvas.resize((width, height), get_sampler_by_name(method))
768
+
769
+ return (canvas.image_to_tensor().unsqueeze(0),)
770
+
771
+
772
+ class ImageDrawLineByContainer:
773
+ def __init__(self):
774
+ pass
775
+
776
+ @classmethod
777
+ def INPUT_TYPES(cls):
778
+ return {
779
+ "required": {
780
+ "container": ("IMAGE",),
781
+ "size": ("INT", {
782
+ "default": 1,
783
+ "min": 1,
784
+ "step": 1
785
+ }),
786
+ "start_x": ("FLOAT", {
787
+ "default": 0.0,
788
+ "max": 1.0,
789
+ "step": 0.01
790
+ }),
791
+ "start_y": ("FLOAT", {
792
+ "default": 0.0,
793
+ "max": 1.0,
794
+ "step": 0.01
795
+ }),
796
+ "end_x": ("FLOAT", {
797
+ "default": 1.0,
798
+ "max": 1.0,
799
+ "step": 0.01
800
+ }),
801
+ "end_y": ("FLOAT", {
802
+ "default": 1.0,
803
+ "max": 1.0,
804
+ "step": 0.01
805
+ }),
806
+ "red": ("INT", {
807
+ "default": 255,
808
+ "max": 255,
809
+ "step": 1
810
+ }),
811
+ "green": ("INT", {
812
+ "default": 255,
813
+ "max": 255,
814
+ "step": 1
815
+ }),
816
+ "blue": ("INT", {
817
+ "default": 255,
818
+ "max": 255,
819
+ "step": 1
820
+ }),
821
+ "alpha": ("FLOAT", {
822
+ "default": 1.0,
823
+ "max": 1.0,
824
+ "step": 0.01
825
+ }),
826
+ "SSAA": ("INT", {
827
+ "default": 4,
828
+ "min": 1,
829
+ "max": 16,
830
+ "step": 1
831
+ }),
832
+ "method": (["lanczos", "bicubic", "hamming", "bilinear", "box", "nearest"],),
833
+ },
834
+ }
835
+
836
+ RETURN_TYPES = ("IMAGE",)
837
+ FUNCTION = "node"
838
+ CATEGORY = "image/draw"
839
+
840
+ # noinspection PyPep8Naming
841
+ def node(self, container, size, start_x, start_y, end_x, end_y, red, green, blue, alpha, SSAA, method):
842
+ return ImageDrawLine().node(
843
+ container[0, :, :, 0].shape[1],
844
+ container[0, :, :, 0].shape[0],
845
+ size,
846
+ start_x,
847
+ start_y,
848
+ end_x,
849
+ end_y,
850
+ red,
851
+ green,
852
+ blue,
853
+ alpha,
854
+ SSAA,
855
+ method
856
+ )
857
+
858
+
859
+ class ImageDrawPieslice:
860
+ def __init__(self):
861
+ pass
862
+
863
+ @classmethod
864
+ def INPUT_TYPES(cls):
865
+ return {
866
+ "required": {
867
+ "width": ("INT", {
868
+ "default": 256,
869
+ "min": 1,
870
+ "step": 1
871
+ }),
872
+ "height": ("INT", {
873
+ "default": 256,
874
+ "min": 1,
875
+ "step": 1
876
+ }),
877
+ "start_x": ("FLOAT", {
878
+ "default": 0.0,
879
+ "max": 1.0,
880
+ "step": 0.01
881
+ }),
882
+ "start_y": ("FLOAT", {
883
+ "default": 0.0,
884
+ "max": 1.0,
885
+ "step": 0.01
886
+ }),
887
+ "end_x": ("FLOAT", {
888
+ "default": 1.0,
889
+ "max": 1.0,
890
+ "step": 0.01
891
+ }),
892
+ "end_y": ("FLOAT", {
893
+ "default": 1.0,
894
+ "max": 1.0,
895
+ "step": 0.01
896
+ }),
897
+ "start": ("INT", {
898
+ "default": 0,
899
+ "max": 360,
900
+ "step": 1
901
+ }),
902
+ "end": ("INT", {
903
+ "default": 240,
904
+ "max": 360,
905
+ "step": 1
906
+ }),
907
+ "outline_size": ("INT", {
908
+ "default": 1,
909
+ "step": 1
910
+ }),
911
+ "outline_red": ("INT", {
912
+ "default": 0,
913
+ "max": 255,
914
+ "step": 1
915
+ }),
916
+ "outline_green": ("INT", {
917
+ "default": 0,
918
+ "max": 255,
919
+ "step": 1
920
+ }),
921
+ "outline_blue": ("INT", {
922
+ "default": 0,
923
+ "max": 255,
924
+ "step": 1
925
+ }),
926
+ "outline_alpha": ("FLOAT", {
927
+ "default": 1.0,
928
+ "max": 1.0,
929
+ "step": 0.01
930
+ }),
931
+ "fill_red": ("INT", {
932
+ "default": 255,
933
+ "max": 255,
934
+ "step": 1
935
+ }),
936
+ "fill_green": ("INT", {
937
+ "default": 255,
938
+ "max": 255,
939
+ "step": 1
940
+ }),
941
+ "fill_blue": ("INT", {
942
+ "default": 255,
943
+ "max": 255,
944
+ "step": 1
945
+ }),
946
+ "fill_alpha": ("FLOAT", {
947
+ "default": 1.0,
948
+ "max": 1.0,
949
+ "step": 0.01
950
+ }),
951
+ "SSAA": ("INT", {
952
+ "default": 4,
953
+ "min": 1,
954
+ "max": 16,
955
+ "step": 1
956
+ }),
957
+ "method": (["lanczos", "bicubic", "hamming", "bilinear", "box", "nearest"],),
958
+ },
959
+ }
960
+
961
+ RETURN_TYPES = ("IMAGE",)
962
+ FUNCTION = "node"
963
+ CATEGORY = "image/draw"
964
+
965
+ # noinspection PyPep8Naming, PyUnresolvedReferences
966
+ def node(
967
+ self,
968
+ width,
969
+ height,
970
+ start_x,
971
+ start_y,
972
+ end_x,
973
+ end_y,
974
+ start,
975
+ end,
976
+ outline_size,
977
+ outline_red,
978
+ outline_green,
979
+ outline_blue,
980
+ outline_alpha,
981
+ fill_red,
982
+ fill_green,
983
+ fill_blue,
984
+ fill_alpha,
985
+ SSAA,
986
+ method
987
+ ):
988
+ canvas = Image.new("RGBA", (width * SSAA, height * SSAA), (0, 0, 0, 0))
989
+
990
+ draw = ImageDraw.Draw(canvas)
991
+ draw.pieslice(
992
+ (
993
+ (width * start_x * SSAA, height * start_y * SSAA),
994
+ (width * end_x * SSAA, height * end_y * SSAA)
995
+ ),
996
+ start, end,
997
+ (fill_red, fill_green, fill_blue, int(fill_alpha * 255)),
998
+ (outline_red, outline_green, outline_blue, int(outline_alpha * 255)),
999
+ outline_size * SSAA
1000
+ )
1001
+
1002
+ canvas = canvas.resize((width, height), get_sampler_by_name(method))
1003
+
1004
+ return (canvas.image_to_tensor().unsqueeze(0),)
1005
+
1006
+
1007
+ class ImageDrawPiesliceByContainer:
1008
+ def __init__(self):
1009
+ pass
1010
+
1011
+ @classmethod
1012
+ def INPUT_TYPES(cls):
1013
+ return {
1014
+ "required": {
1015
+ "container": ("IMAGE",),
1016
+ "start_x": ("FLOAT", {
1017
+ "default": 0.0,
1018
+ "max": 1.0,
1019
+ "step": 0.01
1020
+ }),
1021
+ "start_y": ("FLOAT", {
1022
+ "default": 0.0,
1023
+ "max": 1.0,
1024
+ "step": 0.01
1025
+ }),
1026
+ "end_x": ("FLOAT", {
1027
+ "default": 1.0,
1028
+ "max": 1.0,
1029
+ "step": 0.01
1030
+ }),
1031
+ "end_y": ("FLOAT", {
1032
+ "default": 1.0,
1033
+ "max": 1.0,
1034
+ "step": 0.01
1035
+ }),
1036
+ "start": ("INT", {
1037
+ "default": 0,
1038
+ "max": 360,
1039
+ "step": 1
1040
+ }),
1041
+ "end": ("INT", {
1042
+ "default": 240,
1043
+ "max": 360,
1044
+ "step": 1
1045
+ }),
1046
+ "outline_size": ("INT", {
1047
+ "default": 1,
1048
+ "step": 1
1049
+ }),
1050
+ "outline_red": ("INT", {
1051
+ "default": 0,
1052
+ "max": 255,
1053
+ "step": 1
1054
+ }),
1055
+ "outline_green": ("INT", {
1056
+ "default": 0,
1057
+ "max": 255,
1058
+ "step": 1
1059
+ }),
1060
+ "outline_blue": ("INT", {
1061
+ "default": 0,
1062
+ "max": 255,
1063
+ "step": 1
1064
+ }),
1065
+ "outline_alpha": ("FLOAT", {
1066
+ "default": 1.0,
1067
+ "max": 1.0,
1068
+ "step": 0.01
1069
+ }),
1070
+ "fill_red": ("INT", {
1071
+ "default": 255,
1072
+ "max": 255,
1073
+ "step": 1
1074
+ }),
1075
+ "fill_green": ("INT", {
1076
+ "default": 255,
1077
+ "max": 255,
1078
+ "step": 1
1079
+ }),
1080
+ "fill_blue": ("INT", {
1081
+ "default": 255,
1082
+ "max": 255,
1083
+ "step": 1
1084
+ }),
1085
+ "fill_alpha": ("FLOAT", {
1086
+ "default": 1.0,
1087
+ "max": 1.0,
1088
+ "step": 0.01
1089
+ }),
1090
+ "SSAA": ("INT", {
1091
+ "default": 4,
1092
+ "min": 1,
1093
+ "max": 16,
1094
+ "step": 1
1095
+ }),
1096
+ "method": (["lanczos", "bicubic", "hamming", "bilinear", "box", "nearest"],),
1097
+ },
1098
+ }
1099
+
1100
+ RETURN_TYPES = ("IMAGE",)
1101
+ FUNCTION = "node"
1102
+ CATEGORY = "image/draw"
1103
+
1104
+ # noinspection PyPep8Naming
1105
+ def node(
1106
+ self,
1107
+ container,
1108
+ start_x,
1109
+ start_y,
1110
+ end_x,
1111
+ end_y,
1112
+ start,
1113
+ end,
1114
+ outline_size,
1115
+ outline_red,
1116
+ outline_green,
1117
+ outline_blue,
1118
+ outline_alpha,
1119
+ fill_red,
1120
+ fill_green,
1121
+ fill_blue,
1122
+ fill_alpha,
1123
+ SSAA,
1124
+ method
1125
+ ):
1126
+ return ImageDrawPieslice().node(
1127
+ container[0, :, :, 0].shape[1],
1128
+ container[0, :, :, 0].shape[0],
1129
+ start_x,
1130
+ start_y,
1131
+ end_x,
1132
+ end_y,
1133
+ start,
1134
+ end,
1135
+ outline_size,
1136
+ outline_red,
1137
+ outline_green,
1138
+ outline_blue,
1139
+ outline_alpha,
1140
+ fill_red,
1141
+ fill_green,
1142
+ fill_blue,
1143
+ fill_alpha,
1144
+ SSAA,
1145
+ method
1146
+ )
1147
+
1148
+
1149
+ class ImageDrawRectangle:
1150
+ def __init__(self):
1151
+ pass
1152
+
1153
+ @classmethod
1154
+ def INPUT_TYPES(cls):
1155
+ return {
1156
+ "required": {
1157
+ "width": ("INT", {
1158
+ "default": 256,
1159
+ "min": 1,
1160
+ "step": 1
1161
+ }),
1162
+ "height": ("INT", {
1163
+ "default": 256,
1164
+ "min": 1,
1165
+ "step": 1
1166
+ }),
1167
+ "start_x": ("FLOAT", {
1168
+ "default": 0.1,
1169
+ "max": 1.0,
1170
+ "step": 0.01
1171
+ }),
1172
+ "start_y": ("FLOAT", {
1173
+ "default": 0.2,
1174
+ "max": 1.0,
1175
+ "step": 0.01
1176
+ }),
1177
+ "end_x": ("FLOAT", {
1178
+ "default": 0.9,
1179
+ "max": 1.0,
1180
+ "step": 0.01
1181
+ }),
1182
+ "end_y": ("FLOAT", {
1183
+ "default": 0.8,
1184
+ "max": 1.0,
1185
+ "step": 0.01
1186
+ }),
1187
+ "outline_size": ("INT", {
1188
+ "default": 1,
1189
+ "step": 1
1190
+ }),
1191
+ "outline_red": ("INT", {
1192
+ "default": 0,
1193
+ "max": 255,
1194
+ "step": 1
1195
+ }),
1196
+ "outline_green": ("INT", {
1197
+ "default": 0,
1198
+ "max": 255,
1199
+ "step": 1
1200
+ }),
1201
+ "outline_blue": ("INT", {
1202
+ "default": 0,
1203
+ "max": 255,
1204
+ "step": 1
1205
+ }),
1206
+ "outline_alpha": ("FLOAT", {
1207
+ "default": 1.0,
1208
+ "max": 1.0,
1209
+ "step": 0.01
1210
+ }),
1211
+ "fill_red": ("INT", {
1212
+ "default": 255,
1213
+ "max": 255,
1214
+ "step": 1
1215
+ }),
1216
+ "fill_green": ("INT", {
1217
+ "default": 255,
1218
+ "max": 255,
1219
+ "step": 1
1220
+ }),
1221
+ "fill_blue": ("INT", {
1222
+ "default": 255,
1223
+ "max": 255,
1224
+ "step": 1
1225
+ }),
1226
+ "fill_alpha": ("FLOAT", {
1227
+ "default": 1.0,
1228
+ "max": 1.0,
1229
+ "step": 0.01
1230
+ }),
1231
+ "SSAA": ("INT", {
1232
+ "default": 4,
1233
+ "min": 1,
1234
+ "max": 16,
1235
+ "step": 1
1236
+ }),
1237
+ "method": (["lanczos", "bicubic", "hamming", "bilinear", "box", "nearest"],),
1238
+ },
1239
+ }
1240
+
1241
+ RETURN_TYPES = ("IMAGE",)
1242
+ FUNCTION = "node"
1243
+ CATEGORY = "image/draw"
1244
+
1245
+ # noinspection PyPep8Naming, PyUnresolvedReferences
1246
+ def node(
1247
+ self,
1248
+ width,
1249
+ height,
1250
+ start_x,
1251
+ start_y,
1252
+ end_x,
1253
+ end_y,
1254
+ outline_size,
1255
+ outline_red,
1256
+ outline_green,
1257
+ outline_blue,
1258
+ outline_alpha,
1259
+ fill_red,
1260
+ fill_green,
1261
+ fill_blue,
1262
+ fill_alpha,
1263
+ SSAA,
1264
+ method
1265
+ ):
1266
+ canvas = Image.new("RGBA", (width * SSAA, height * SSAA), (0, 0, 0, 0))
1267
+
1268
+ draw = ImageDraw.Draw(canvas)
1269
+ draw.rectangle(
1270
+ (
1271
+ (width * start_x * SSAA, height * start_y * SSAA),
1272
+ (width * end_x * SSAA, height * end_y * SSAA)
1273
+ ),
1274
+ (fill_red, fill_green, fill_blue, int(fill_alpha * 255)),
1275
+ (outline_red, outline_green, outline_blue, int(outline_alpha * 255)),
1276
+ outline_size * SSAA
1277
+ )
1278
+
1279
+ canvas = canvas.resize((width, height), get_sampler_by_name(method))
1280
+
1281
+ return (canvas.image_to_tensor().unsqueeze(0),)
1282
+
1283
+
1284
+ class ImageDrawRectangleByContainer:
1285
+ def __init__(self):
1286
+ pass
1287
+
1288
+ @classmethod
1289
+ def INPUT_TYPES(cls):
1290
+ return {
1291
+ "required": {
1292
+ "container": ("IMAGE",),
1293
+ "start_x": ("FLOAT", {
1294
+ "default": 0.1,
1295
+ "max": 1.0,
1296
+ "step": 0.01
1297
+ }),
1298
+ "start_y": ("FLOAT", {
1299
+ "default": 0.2,
1300
+ "max": 1.0,
1301
+ "step": 0.01
1302
+ }),
1303
+ "end_x": ("FLOAT", {
1304
+ "default": 0.9,
1305
+ "max": 1.0,
1306
+ "step": 0.01
1307
+ }),
1308
+ "end_y": ("FLOAT", {
1309
+ "default": 0.8,
1310
+ "max": 1.0,
1311
+ "step": 0.01
1312
+ }),
1313
+ "outline_size": ("INT", {
1314
+ "default": 1,
1315
+ "step": 1
1316
+ }),
1317
+ "outline_red": ("INT", {
1318
+ "default": 0,
1319
+ "max": 255,
1320
+ "step": 1
1321
+ }),
1322
+ "outline_green": ("INT", {
1323
+ "default": 0,
1324
+ "max": 255,
1325
+ "step": 1
1326
+ }),
1327
+ "outline_blue": ("INT", {
1328
+ "default": 0,
1329
+ "max": 255,
1330
+ "step": 1
1331
+ }),
1332
+ "outline_alpha": ("FLOAT", {
1333
+ "default": 1.0,
1334
+ "max": 1.0,
1335
+ "step": 0.01
1336
+ }),
1337
+ "fill_red": ("INT", {
1338
+ "default": 255,
1339
+ "max": 255,
1340
+ "step": 1
1341
+ }),
1342
+ "fill_green": ("INT", {
1343
+ "default": 255,
1344
+ "max": 255,
1345
+ "step": 1
1346
+ }),
1347
+ "fill_blue": ("INT", {
1348
+ "default": 255,
1349
+ "max": 255,
1350
+ "step": 1
1351
+ }),
1352
+ "fill_alpha": ("FLOAT", {
1353
+ "default": 1.0,
1354
+ "max": 1.0,
1355
+ "step": 0.01
1356
+ }),
1357
+ "SSAA": ("INT", {
1358
+ "default": 4,
1359
+ "min": 1,
1360
+ "max": 16,
1361
+ "step": 1
1362
+ }),
1363
+ "method": (["lanczos", "bicubic", "hamming", "bilinear", "box", "nearest"],),
1364
+ },
1365
+ }
1366
+
1367
+ RETURN_TYPES = ("IMAGE",)
1368
+ FUNCTION = "node"
1369
+ CATEGORY = "image/draw"
1370
+
1371
+ # noinspection PyPep8Naming
1372
+ def node(
1373
+ self,
1374
+ container,
1375
+ start_x,
1376
+ start_y,
1377
+ end_x,
1378
+ end_y,
1379
+ outline_size,
1380
+ outline_red,
1381
+ outline_green,
1382
+ outline_blue,
1383
+ outline_alpha,
1384
+ fill_red,
1385
+ fill_green,
1386
+ fill_blue,
1387
+ fill_alpha,
1388
+ SSAA,
1389
+ method
1390
+ ):
1391
+ return ImageDrawRectangle().node(
1392
+ container[0, :, :, 0].shape[1],
1393
+ container[0, :, :, 0].shape[0],
1394
+ start_x,
1395
+ start_y,
1396
+ end_x,
1397
+ end_y,
1398
+ outline_size,
1399
+ outline_red,
1400
+ outline_green,
1401
+ outline_blue,
1402
+ outline_alpha,
1403
+ fill_red,
1404
+ fill_green,
1405
+ fill_blue,
1406
+ fill_alpha,
1407
+ SSAA,
1408
+ method
1409
+ )
1410
+
1411
+
1412
+ class ImageDrawRectangleRounded:
1413
+ def __init__(self):
1414
+ pass
1415
+
1416
+ @classmethod
1417
+ def INPUT_TYPES(cls):
1418
+ return {
1419
+ "required": {
1420
+ "width": ("INT", {
1421
+ "default": 256,
1422
+ "min": 1,
1423
+ "step": 1
1424
+ }),
1425
+ "height": ("INT", {
1426
+ "default": 256,
1427
+ "min": 1,
1428
+ "step": 1
1429
+ }),
1430
+ "start_x": ("FLOAT", {
1431
+ "default": 0.1,
1432
+ "max": 1.0,
1433
+ "step": 0.01
1434
+ }),
1435
+ "start_y": ("FLOAT", {
1436
+ "default": 0.2,
1437
+ "max": 1.0,
1438
+ "step": 0.01
1439
+ }),
1440
+ "end_x": ("FLOAT", {
1441
+ "default": 0.9,
1442
+ "max": 1.0,
1443
+ "step": 0.01
1444
+ }),
1445
+ "end_y": ("FLOAT", {
1446
+ "default": 0.8,
1447
+ "max": 1.0,
1448
+ "step": 0.01
1449
+ }),
1450
+ "radius": ("INT", {
1451
+ "default": 180,
1452
+ "max": 360,
1453
+ "step": 1
1454
+ }),
1455
+ "outline_size": ("INT", {
1456
+ "default": 1,
1457
+ "step": 1
1458
+ }),
1459
+ "outline_red": ("INT", {
1460
+ "default": 0,
1461
+ "max": 255,
1462
+ "step": 1
1463
+ }),
1464
+ "outline_green": ("INT", {
1465
+ "default": 0,
1466
+ "max": 255,
1467
+ "step": 1
1468
+ }),
1469
+ "outline_blue": ("INT", {
1470
+ "default": 0,
1471
+ "max": 255,
1472
+ "step": 1
1473
+ }),
1474
+ "outline_alpha": ("FLOAT", {
1475
+ "default": 1.0,
1476
+ "max": 1.0,
1477
+ "step": 0.01
1478
+ }),
1479
+ "fill_red": ("INT", {
1480
+ "default": 255,
1481
+ "max": 255,
1482
+ "step": 1
1483
+ }),
1484
+ "fill_green": ("INT", {
1485
+ "default": 255,
1486
+ "max": 255,
1487
+ "step": 1
1488
+ }),
1489
+ "fill_blue": ("INT", {
1490
+ "default": 255,
1491
+ "max": 255,
1492
+ "step": 1
1493
+ }),
1494
+ "fill_alpha": ("FLOAT", {
1495
+ "default": 1.0,
1496
+ "max": 1.0,
1497
+ "step": 0.01
1498
+ }),
1499
+ "top_left_corner": (["true", "false"],),
1500
+ "top_right_corner": (["true", "false"],),
1501
+ "bottom_right_corner": (["true", "false"],),
1502
+ "bottom_left_corner": (["true", "false"],),
1503
+ "SSAA": ("INT", {
1504
+ "default": 4,
1505
+ "min": 1,
1506
+ "max": 16,
1507
+ "step": 1
1508
+ }),
1509
+ "method": (["lanczos", "bicubic", "hamming", "bilinear", "box", "nearest"],),
1510
+ },
1511
+ }
1512
+
1513
+ RETURN_TYPES = ("IMAGE",)
1514
+ FUNCTION = "node"
1515
+ CATEGORY = "image/draw"
1516
+
1517
+ # noinspection PyPep8Naming, PyUnresolvedReferences, PyArgumentList
1518
+ def node(
1519
+ self,
1520
+ width,
1521
+ height,
1522
+ start_x,
1523
+ start_y,
1524
+ end_x,
1525
+ end_y,
1526
+ radius,
1527
+ outline_size,
1528
+ outline_red,
1529
+ outline_green,
1530
+ outline_blue,
1531
+ outline_alpha,
1532
+ fill_red,
1533
+ fill_green,
1534
+ fill_blue,
1535
+ fill_alpha,
1536
+ top_left_corner,
1537
+ top_right_corner,
1538
+ bottom_right_corner,
1539
+ bottom_left_corner,
1540
+ SSAA,
1541
+ method
1542
+ ):
1543
+ canvas = Image.new("RGBA", (width * SSAA, height * SSAA), (0, 0, 0, 0))
1544
+
1545
+ draw = ImageDraw.Draw(canvas)
1546
+ draw.rounded_rectangle(
1547
+ (
1548
+ (width * start_x * SSAA, height * start_y * SSAA),
1549
+ (width * end_x * SSAA, height * end_y * SSAA)
1550
+ ),
1551
+ radius * SSAA,
1552
+ (fill_red, fill_green, fill_blue, int(fill_alpha * 255)),
1553
+ (outline_red, outline_green, outline_blue, int(outline_alpha * 255)),
1554
+ outline_size * SSAA,
1555
+ corners=(
1556
+ True if top_left_corner == "true" else False,
1557
+ True if top_right_corner == "true" else False,
1558
+ True if bottom_right_corner == "true" else False,
1559
+ True if bottom_left_corner == "true" else False
1560
+ )
1561
+ )
1562
+
1563
+ canvas = canvas.resize((width, height), get_sampler_by_name(method))
1564
+
1565
+ return (canvas.image_to_tensor().unsqueeze(0),)
1566
+
1567
+
1568
+ class ImageDrawRectangleRoundedByContainer:
1569
+ def __init__(self):
1570
+ pass
1571
+
1572
+ @classmethod
1573
+ def INPUT_TYPES(cls):
1574
+ return {
1575
+ "required": {
1576
+ "container": ("IMAGE",),
1577
+ "start_x": ("FLOAT", {
1578
+ "default": 0.1,
1579
+ "max": 1.0,
1580
+ "step": 0.01
1581
+ }),
1582
+ "start_y": ("FLOAT", {
1583
+ "default": 0.2,
1584
+ "max": 1.0,
1585
+ "step": 0.01
1586
+ }),
1587
+ "end_x": ("FLOAT", {
1588
+ "default": 0.9,
1589
+ "max": 1.0,
1590
+ "step": 0.01
1591
+ }),
1592
+ "end_y": ("FLOAT", {
1593
+ "default": 0.8,
1594
+ "max": 1.0,
1595
+ "step": 0.01
1596
+ }),
1597
+ "radius": ("INT", {
1598
+ "default": 180,
1599
+ "max": 360,
1600
+ "step": 1
1601
+ }),
1602
+ "outline_size": ("INT", {
1603
+ "default": 1,
1604
+ "step": 1
1605
+ }),
1606
+ "outline_red": ("INT", {
1607
+ "default": 0,
1608
+ "max": 255,
1609
+ "step": 1
1610
+ }),
1611
+ "outline_green": ("INT", {
1612
+ "default": 0,
1613
+ "max": 255,
1614
+ "step": 1
1615
+ }),
1616
+ "outline_blue": ("INT", {
1617
+ "default": 0,
1618
+ "max": 255,
1619
+ "step": 1
1620
+ }),
1621
+ "outline_alpha": ("FLOAT", {
1622
+ "default": 1.0,
1623
+ "max": 1.0,
1624
+ "step": 0.01
1625
+ }),
1626
+ "fill_red": ("INT", {
1627
+ "default": 255,
1628
+ "max": 255,
1629
+ "step": 1
1630
+ }),
1631
+ "fill_green": ("INT", {
1632
+ "default": 255,
1633
+ "max": 255,
1634
+ "step": 1
1635
+ }),
1636
+ "fill_blue": ("INT", {
1637
+ "default": 255,
1638
+ "max": 255,
1639
+ "step": 1
1640
+ }),
1641
+ "fill_alpha": ("FLOAT", {
1642
+ "default": 1.0,
1643
+ "max": 1.0,
1644
+ "step": 0.01
1645
+ }),
1646
+ "top_left_corner": (["true", "false"],),
1647
+ "top_right_corner": (["true", "false"],),
1648
+ "bottom_right_corner": (["true", "false"],),
1649
+ "bottom_left_corner": (["true", "false"],),
1650
+ "SSAA": ("INT", {
1651
+ "default": 4,
1652
+ "min": 1,
1653
+ "max": 16,
1654
+ "step": 1
1655
+ }),
1656
+ "method": (["lanczos", "bicubic", "hamming", "bilinear", "box", "nearest"],),
1657
+ },
1658
+ }
1659
+
1660
+ RETURN_TYPES = ("IMAGE",)
1661
+ FUNCTION = "node"
1662
+ CATEGORY = "image/draw"
1663
+
1664
+ # noinspection PyPep8Naming, PyUnresolvedReferences, PyArgumentList
1665
+ def node(
1666
+ self,
1667
+ container,
1668
+ start_x,
1669
+ start_y,
1670
+ end_x,
1671
+ end_y,
1672
+ radius,
1673
+ outline_size,
1674
+ outline_red,
1675
+ outline_green,
1676
+ outline_blue,
1677
+ outline_alpha,
1678
+ fill_red,
1679
+ fill_green,
1680
+ fill_blue,
1681
+ fill_alpha,
1682
+ top_left_corner,
1683
+ top_right_corner,
1684
+ bottom_right_corner,
1685
+ bottom_left_corner,
1686
+ SSAA,
1687
+ method
1688
+ ):
1689
+ return ImageDrawRectangleRounded().image_draw_rounded(
1690
+ container[0, :, :, 0].shape[1],
1691
+ container[0, :, :, 0].shape[0],
1692
+ start_x,
1693
+ start_y,
1694
+ end_x,
1695
+ end_y,
1696
+ radius,
1697
+ outline_size,
1698
+ outline_red,
1699
+ outline_green,
1700
+ outline_blue,
1701
+ outline_alpha,
1702
+ fill_red,
1703
+ fill_green,
1704
+ fill_blue,
1705
+ fill_alpha,
1706
+ top_left_corner,
1707
+ top_right_corner,
1708
+ bottom_right_corner,
1709
+ bottom_left_corner,
1710
+ SSAA,
1711
+ method
1712
+ )
1713
+
1714
+
1715
+ class ImageDrawPolygon:
1716
+ def __init__(self):
1717
+ pass
1718
+
1719
+ @classmethod
1720
+ def INPUT_TYPES(cls):
1721
+ return {
1722
+ "required": {
1723
+ "size": ("INT", {
1724
+ "default": 256,
1725
+ "min": 1,
1726
+ "step": 1
1727
+ }),
1728
+ "sides": ("INT", {
1729
+ "default": 5,
1730
+ "min": 3,
1731
+ "step": 1
1732
+ }),
1733
+ "rotation": ("INT", {
1734
+ "default": 0,
1735
+ "max": 360,
1736
+ "step": 1
1737
+ }),
1738
+ "outline_size": ("INT", {
1739
+ "default": 1,
1740
+ "step": 1
1741
+ }),
1742
+ "outline_red": ("INT", {
1743
+ "default": 0,
1744
+ "max": 255,
1745
+ "step": 1
1746
+ }),
1747
+ "outline_green": ("INT", {
1748
+ "default": 0,
1749
+ "max": 255,
1750
+ "step": 1
1751
+ }),
1752
+ "outline_blue": ("INT", {
1753
+ "default": 0,
1754
+ "max": 255,
1755
+ "step": 1
1756
+ }),
1757
+ "outline_alpha": ("FLOAT", {
1758
+ "default": 1.0,
1759
+ "max": 1.0,
1760
+ "step": 0.01
1761
+ }),
1762
+ "fill_red": ("INT", {
1763
+ "default": 255,
1764
+ "max": 255,
1765
+ "step": 1
1766
+ }),
1767
+ "fill_green": ("INT", {
1768
+ "default": 255,
1769
+ "max": 255,
1770
+ "step": 1
1771
+ }),
1772
+ "fill_blue": ("INT", {
1773
+ "default": 255,
1774
+ "max": 255,
1775
+ "step": 1
1776
+ }),
1777
+ "fill_alpha": ("FLOAT", {
1778
+ "default": 1.0,
1779
+ "max": 1.0,
1780
+ "step": 0.01
1781
+ }),
1782
+ "SSAA": ("INT", {
1783
+ "default": 4,
1784
+ "min": 1,
1785
+ "max": 16,
1786
+ "step": 1
1787
+ }),
1788
+ "method": (["lanczos", "bicubic", "hamming", "bilinear", "box", "nearest"],),
1789
+ },
1790
+ }
1791
+
1792
+ RETURN_TYPES = ("IMAGE",)
1793
+ FUNCTION = "node"
1794
+ CATEGORY = "image/draw"
1795
+
1796
+ # noinspection PyPep8Naming, PyUnresolvedReferences
1797
+ def node(
1798
+ self,
1799
+ size,
1800
+ sides,
1801
+ rotation,
1802
+ outline_size,
1803
+ outline_red,
1804
+ outline_green,
1805
+ outline_blue,
1806
+ outline_alpha,
1807
+ fill_red,
1808
+ fill_green,
1809
+ fill_blue,
1810
+ fill_alpha,
1811
+ SSAA,
1812
+ method
1813
+ ):
1814
+ canvas = Image.new("RGBA", (size * SSAA, size * SSAA), (0, 0, 0, 0))
1815
+
1816
+ draw = ImageDraw.Draw(canvas)
1817
+ draw.regular_polygon(
1818
+ (size * SSAA / 2, size * SSAA / 2, size * SSAA / 2),
1819
+ sides, rotation,
1820
+ (fill_red, fill_green, fill_blue, int(fill_alpha * 255)),
1821
+ (outline_red, outline_green, outline_blue, int(outline_alpha * 255)),
1822
+ # TODO: Uncomment after the release of PIL 9.6.0
1823
+ # outline_size * SSAA
1824
+ )
1825
+
1826
+ canvas = canvas.resize((size, size), get_sampler_by_name(method))
1827
+
1828
+ return (canvas.image_to_tensor().unsqueeze(0),)
1829
+
1830
+
1831
+ NODE_CLASS_MAPPINGS = {
1832
+ "ImageDrawArc": ImageDrawArc,
1833
+ "ImageDrawArcByContainer": ImageDrawArcByContainer,
1834
+ "ImageDrawChord": ImageDrawChord,
1835
+ "ImageDrawChordByContainer": ImageDrawChordByContainer,
1836
+ "ImageDrawEllipse": ImageDrawEllipse,
1837
+ "ImageDrawEllipseByContainer": ImageDrawEllipseByContainer,
1838
+ "ImageDrawLine": ImageDrawLine,
1839
+ "ImageDrawLineByContainer": ImageDrawLineByContainer,
1840
+ "ImageDrawPieslice": ImageDrawPieslice,
1841
+ "ImageDrawPiesliceByContainer": ImageDrawPiesliceByContainer,
1842
+ "ImageDrawRectangle": ImageDrawRectangle,
1843
+ "ImageDrawRectangleByContainer": ImageDrawRectangleByContainer,
1844
+ "ImageDrawRectangleRounded": ImageDrawRectangleRounded,
1845
+ "ImageDrawRectangleRoundedByContainer": ImageDrawRectangleRoundedByContainer,
1846
+ "ImageDrawPolygon": ImageDrawPolygon,
1847
+ }