6740428533df2221747f574764f854c868e77752bef4ae9123d3eed0913b2cef
Browse files- extensions/microsoftexcel-controlnet/scripts/__pycache__/hook.cpython-310.pyc +0 -0
- extensions/microsoftexcel-controlnet/scripts/__pycache__/lvminthin.cpython-310.pyc +0 -0
- extensions/microsoftexcel-controlnet/scripts/__pycache__/movie2movie.cpython-310.pyc +0 -0
- extensions/microsoftexcel-controlnet/scripts/__pycache__/processor.cpython-310.pyc +0 -0
- extensions/microsoftexcel-controlnet/scripts/__pycache__/utils.cpython-310.pyc +0 -0
- extensions/microsoftexcel-controlnet/scripts/__pycache__/xyz_grid_support.cpython-310.pyc +0 -0
- extensions/microsoftexcel-controlnet/scripts/adapter.py +397 -0
- extensions/microsoftexcel-controlnet/scripts/api.py +92 -0
- extensions/microsoftexcel-controlnet/scripts/batch_hijack.py +215 -0
- extensions/microsoftexcel-controlnet/scripts/cldm.py +372 -0
- extensions/microsoftexcel-controlnet/scripts/controlnet.py +920 -0
- extensions/microsoftexcel-controlnet/scripts/controlnet_version.py +7 -0
- extensions/microsoftexcel-controlnet/scripts/external_code.py +346 -0
- extensions/microsoftexcel-controlnet/scripts/global_state.py +222 -0
- extensions/microsoftexcel-controlnet/scripts/hook.py +749 -0
- extensions/microsoftexcel-controlnet/scripts/lvminthin.py +88 -0
- extensions/microsoftexcel-controlnet/scripts/movie2movie.py +176 -0
- extensions/microsoftexcel-controlnet/scripts/processor.py +871 -0
- extensions/microsoftexcel-controlnet/scripts/ui/__pycache__/controlnet_ui_group.cpython-310.pyc +0 -0
- extensions/microsoftexcel-controlnet/scripts/ui/controlnet_ui_group.py +974 -0
- extensions/microsoftexcel-controlnet/scripts/utils.py +109 -0
- extensions/microsoftexcel-controlnet/scripts/xyz_grid_support.py +443 -0
- extensions/microsoftexcel-controlnet/tests/annotator_tests/openpose_tests/body_test.py +50 -0
- extensions/microsoftexcel-controlnet/tests/annotator_tests/openpose_tests/detection_test.py +109 -0
- extensions/microsoftexcel-controlnet/tests/annotator_tests/openpose_tests/json_encode_test.py +81 -0
- extensions/microsoftexcel-controlnet/tests/annotator_tests/openpose_tests/openpose_e2e_test.py +95 -0
- extensions/microsoftexcel-controlnet/tests/cn_script/__init__.py +0 -0
- extensions/microsoftexcel-controlnet/tests/cn_script/batch_hijack_test.py +332 -0
- extensions/microsoftexcel-controlnet/tests/cn_script/utils_test.py +65 -0
- extensions/microsoftexcel-controlnet/tests/external_code_api/__init__.py +0 -0
- extensions/microsoftexcel-controlnet/tests/external_code_api/external_code_test.py +120 -0
- extensions/microsoftexcel-controlnet/tests/external_code_api/script_args_test.py +34 -0
- extensions/microsoftexcel-controlnet/tests/images/expected_ski_output.png +0 -0
- extensions/microsoftexcel-controlnet/tests/images/expected_woman_all_output.png +0 -0
- extensions/microsoftexcel-controlnet/tests/images/expected_woman_face_output.png +0 -0
- extensions/microsoftexcel-controlnet/tests/images/expected_woman_hand_output.png +0 -0
- extensions/microsoftexcel-controlnet/tests/images/ski.jpg +0 -0
- extensions/microsoftexcel-controlnet/tests/images/woman.jpeg +0 -0
- extensions/microsoftexcel-controlnet/tests/utils.py +40 -0
- extensions/microsoftexcel-controlnet/tests/web_api/__init__.py +0 -0
- extensions/microsoftexcel-controlnet/tests/web_api/detect_test.py +41 -0
- extensions/microsoftexcel-controlnet/tests/web_api/img2img_test.py +102 -0
- extensions/microsoftexcel-controlnet/tests/web_api/txt2img_test.py +134 -0
- extensions/microsoftexcel-images-browser.zip +3 -0
- extensions/microsoftexcel-supermerger/.gitignore +131 -0
- extensions/microsoftexcel-supermerger/LICENSE +663 -0
- extensions/microsoftexcel-supermerger/README.md +152 -0
- extensions/microsoftexcel-supermerger/README_ja.md +154 -0
- extensions/microsoftexcel-supermerger/calcmode_en.md +0 -0
- extensions/microsoftexcel-supermerger/changelog.md +57 -0
extensions/microsoftexcel-controlnet/scripts/__pycache__/hook.cpython-310.pyc
ADDED
Binary file (20.7 kB). View file
|
|
extensions/microsoftexcel-controlnet/scripts/__pycache__/lvminthin.cpython-310.pyc
ADDED
Binary file (2.67 kB). View file
|
|
extensions/microsoftexcel-controlnet/scripts/__pycache__/movie2movie.cpython-310.pyc
ADDED
Binary file (5.03 kB). View file
|
|
extensions/microsoftexcel-controlnet/scripts/__pycache__/processor.cpython-310.pyc
ADDED
Binary file (15.5 kB). View file
|
|
extensions/microsoftexcel-controlnet/scripts/__pycache__/utils.cpython-310.pyc
ADDED
Binary file (4.6 kB). View file
|
|
extensions/microsoftexcel-controlnet/scripts/__pycache__/xyz_grid_support.cpython-310.pyc
ADDED
Binary file (13.5 kB). View file
|
|
extensions/microsoftexcel-controlnet/scripts/adapter.py
ADDED
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
|
3 |
+
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
import importlib
|
6 |
+
from collections import OrderedDict
|
7 |
+
|
8 |
+
from omegaconf import OmegaConf
|
9 |
+
from copy import deepcopy
|
10 |
+
from modules import devices, lowvram, shared, scripts
|
11 |
+
cond_cast_unet = getattr(devices, 'cond_cast_unet', lambda x: x)
|
12 |
+
from ldm.modules.diffusionmodules.util import timestep_embedding
|
13 |
+
from ldm.modules.diffusionmodules.openaimodel import UNetModel
|
14 |
+
|
15 |
+
|
16 |
+
class TorchHijackForUnet:
|
17 |
+
"""
|
18 |
+
This is torch, but with cat that resizes tensors to appropriate dimensions if they do not match;
|
19 |
+
this makes it possible to create pictures with dimensions that are multiples of 8 rather than 64
|
20 |
+
"""
|
21 |
+
|
22 |
+
def __getattr__(self, item):
|
23 |
+
if item == 'cat':
|
24 |
+
return self.cat
|
25 |
+
|
26 |
+
if hasattr(torch, item):
|
27 |
+
return getattr(torch, item)
|
28 |
+
|
29 |
+
raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, item))
|
30 |
+
|
31 |
+
def cat(self, tensors, *args, **kwargs):
|
32 |
+
if len(tensors) == 2:
|
33 |
+
a, b = tensors
|
34 |
+
if a.shape[-2:] != b.shape[-2:]:
|
35 |
+
a = torch.nn.functional.interpolate(a, b.shape[-2:], mode="nearest")
|
36 |
+
|
37 |
+
tensors = (a, b)
|
38 |
+
|
39 |
+
return torch.cat(tensors, *args, **kwargs)
|
40 |
+
|
41 |
+
|
42 |
+
th = TorchHijackForUnet()
|
43 |
+
|
44 |
+
|
45 |
+
def align(hint, size):
|
46 |
+
b, c, h1, w1 = hint.shape
|
47 |
+
h, w = size
|
48 |
+
if h != h1 or w != w1:
|
49 |
+
hint = th.nn.functional.interpolate(hint, size=size, mode="nearest")
|
50 |
+
return hint
|
51 |
+
|
52 |
+
|
53 |
+
def get_node_name(name, parent_name):
|
54 |
+
if len(name) <= len(parent_name):
|
55 |
+
return False, ''
|
56 |
+
p = name[:len(parent_name)]
|
57 |
+
if p != parent_name:
|
58 |
+
return False, ''
|
59 |
+
return True, name[len(parent_name):]
|
60 |
+
|
61 |
+
|
62 |
+
def get_obj_from_str(string, reload=False):
|
63 |
+
module, cls = string.rsplit(".", 1)
|
64 |
+
if reload:
|
65 |
+
module_imp = importlib.import_module(module)
|
66 |
+
importlib.reload(module_imp)
|
67 |
+
return getattr(importlib.import_module(module, package=None), cls)
|
68 |
+
|
69 |
+
|
70 |
+
class PlugableAdapter(nn.Module):
|
71 |
+
def __init__(self, state_dict, config_path, lowvram=False, base_model=None) -> None:
|
72 |
+
super().__init__()
|
73 |
+
self.config = OmegaConf.load(config_path)
|
74 |
+
model = Adapter
|
75 |
+
try:
|
76 |
+
self.target = self.config.model.target
|
77 |
+
model = get_obj_from_str(self.config.model.target)
|
78 |
+
except ImportError:
|
79 |
+
pass
|
80 |
+
|
81 |
+
self.control_model = model(**self.config.model.params)
|
82 |
+
self.control_model.load_state_dict(state_dict)
|
83 |
+
self.lowvram = lowvram
|
84 |
+
self.control = None
|
85 |
+
self.hint_cond = None
|
86 |
+
|
87 |
+
if not self.lowvram:
|
88 |
+
self.control_model.to(devices.get_device_for("controlnet"))
|
89 |
+
|
90 |
+
def reset(self):
|
91 |
+
self.control = None
|
92 |
+
self.hint_cond = None
|
93 |
+
|
94 |
+
def forward(self, hint=None, x=None, *args, **kwargs):
|
95 |
+
if self.control is not None:
|
96 |
+
return deepcopy(self.control)
|
97 |
+
|
98 |
+
self.hint_cond = cond_cast_unet(hint)
|
99 |
+
hint_in = cond_cast_unet(hint)
|
100 |
+
|
101 |
+
if hasattr(self.control_model, 'conv_in') and self.control_model.conv_in.in_channels == 64:
|
102 |
+
hint_in = hint_in[:, 0:1, :, :]
|
103 |
+
|
104 |
+
self.control = self.control_model(hint_in)
|
105 |
+
return deepcopy(self.control)
|
106 |
+
|
107 |
+
|
108 |
+
def conv_nd(dims, *args, **kwargs):
|
109 |
+
"""
|
110 |
+
Create a 1D, 2D, or 3D convolution module.
|
111 |
+
"""
|
112 |
+
if dims == 1:
|
113 |
+
return nn.Conv1d(*args, **kwargs)
|
114 |
+
elif dims == 2:
|
115 |
+
return nn.Conv2d(*args, **kwargs)
|
116 |
+
elif dims == 3:
|
117 |
+
return nn.Conv3d(*args, **kwargs)
|
118 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
119 |
+
|
120 |
+
def avg_pool_nd(dims, *args, **kwargs):
|
121 |
+
"""
|
122 |
+
Create a 1D, 2D, or 3D average pooling module.
|
123 |
+
"""
|
124 |
+
if dims == 1:
|
125 |
+
return nn.AvgPool1d(*args, **kwargs)
|
126 |
+
elif dims == 2:
|
127 |
+
return nn.AvgPool2d(*args, **kwargs)
|
128 |
+
elif dims == 3:
|
129 |
+
return nn.AvgPool3d(*args, **kwargs)
|
130 |
+
raise ValueError(f"unsupported dimensions: {dims}")
|
131 |
+
|
132 |
+
|
133 |
+
class Downsample(nn.Module):
|
134 |
+
"""
|
135 |
+
A downsampling layer with an optional convolution.
|
136 |
+
:param channels: channels in the inputs and outputs.
|
137 |
+
:param use_conv: a bool determining if a convolution is applied.
|
138 |
+
:param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
|
139 |
+
downsampling occurs in the inner-two dimensions.
|
140 |
+
"""
|
141 |
+
|
142 |
+
def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1):
|
143 |
+
super().__init__()
|
144 |
+
self.channels = channels
|
145 |
+
self.out_channels = out_channels or channels
|
146 |
+
self.use_conv = use_conv
|
147 |
+
self.dims = dims
|
148 |
+
stride = 2 if dims != 3 else (1, 2, 2)
|
149 |
+
if use_conv:
|
150 |
+
self.op = conv_nd(
|
151 |
+
dims, self.channels, self.out_channels, 3, stride=stride, padding=padding
|
152 |
+
)
|
153 |
+
else:
|
154 |
+
assert self.channels == self.out_channels
|
155 |
+
self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
|
156 |
+
|
157 |
+
def forward(self, x):
|
158 |
+
assert x.shape[1] == self.channels
|
159 |
+
return self.op(x)
|
160 |
+
|
161 |
+
|
162 |
+
class ResnetBlock(nn.Module):
|
163 |
+
def __init__(self, in_c, out_c, down, ksize=3, sk=False, use_conv=True):
|
164 |
+
super().__init__()
|
165 |
+
ps = ksize//2
|
166 |
+
if in_c != out_c or sk==False:
|
167 |
+
self.in_conv = nn.Conv2d(in_c, out_c, ksize, 1, ps)
|
168 |
+
else:
|
169 |
+
# print('n_in')
|
170 |
+
self.in_conv = None
|
171 |
+
self.block1 = nn.Conv2d(out_c, out_c, 3, 1, 1)
|
172 |
+
self.act = nn.ReLU()
|
173 |
+
self.block2 = nn.Conv2d(out_c, out_c, ksize, 1, ps)
|
174 |
+
if sk==False:
|
175 |
+
self.skep = nn.Conv2d(in_c, out_c, ksize, 1, ps)
|
176 |
+
else:
|
177 |
+
# print('n_sk')
|
178 |
+
self.skep = None
|
179 |
+
|
180 |
+
self.down = down
|
181 |
+
if self.down == True:
|
182 |
+
self.down_opt = Downsample(in_c, use_conv=use_conv)
|
183 |
+
|
184 |
+
def forward(self, x):
|
185 |
+
if self.down == True:
|
186 |
+
x = self.down_opt(x)
|
187 |
+
if self.in_conv is not None: # edit
|
188 |
+
h = self.in_conv(x)
|
189 |
+
# x = self.in_conv(x)
|
190 |
+
# else:
|
191 |
+
# x = x
|
192 |
+
|
193 |
+
h = self.block1(h)
|
194 |
+
h = self.act(h)
|
195 |
+
h = self.block2(h)
|
196 |
+
if self.skep is not None:
|
197 |
+
return h + self.skep(x)
|
198 |
+
else:
|
199 |
+
return h + x
|
200 |
+
|
201 |
+
|
202 |
+
class ResnetBlock(nn.Module):
|
203 |
+
def __init__(self, in_c, out_c, down, ksize=3, sk=False, use_conv=True):
|
204 |
+
super().__init__()
|
205 |
+
ps = ksize//2
|
206 |
+
if in_c != out_c or sk==False:
|
207 |
+
self.in_conv = nn.Conv2d(in_c, out_c, ksize, 1, ps)
|
208 |
+
else:
|
209 |
+
# print('n_in')
|
210 |
+
self.in_conv = None
|
211 |
+
self.block1 = nn.Conv2d(out_c, out_c, 3, 1, 1)
|
212 |
+
self.act = nn.ReLU()
|
213 |
+
self.block2 = nn.Conv2d(out_c, out_c, ksize, 1, ps)
|
214 |
+
if sk==False:
|
215 |
+
self.skep = nn.Conv2d(in_c, out_c, ksize, 1, ps)
|
216 |
+
else:
|
217 |
+
self.skep = None
|
218 |
+
|
219 |
+
self.down = down
|
220 |
+
if self.down == True:
|
221 |
+
self.down_opt = Downsample(in_c, use_conv=use_conv)
|
222 |
+
|
223 |
+
def forward(self, x):
|
224 |
+
if self.down == True:
|
225 |
+
x = self.down_opt(x)
|
226 |
+
if self.in_conv is not None: # edit
|
227 |
+
x = self.in_conv(x)
|
228 |
+
|
229 |
+
h = self.block1(x)
|
230 |
+
h = self.act(h)
|
231 |
+
h = self.block2(h)
|
232 |
+
if self.skep is not None:
|
233 |
+
return h + self.skep(x)
|
234 |
+
else:
|
235 |
+
return h + x
|
236 |
+
|
237 |
+
|
238 |
+
class Adapter(nn.Module):
|
239 |
+
def __init__(self, channels=[320, 640, 1280, 1280], nums_rb=3, cin=64, ksize=3, sk=False, use_conv=True):
|
240 |
+
super(Adapter, self).__init__()
|
241 |
+
self.unshuffle = nn.PixelUnshuffle(8)
|
242 |
+
self.channels = channels
|
243 |
+
self.nums_rb = nums_rb
|
244 |
+
self.body = []
|
245 |
+
for i in range(len(channels)):
|
246 |
+
for j in range(nums_rb):
|
247 |
+
if (i!=0) and (j==0):
|
248 |
+
self.body.append(ResnetBlock(channels[i-1], channels[i], down=True, ksize=ksize, sk=sk, use_conv=use_conv))
|
249 |
+
else:
|
250 |
+
self.body.append(ResnetBlock(channels[i], channels[i], down=False, ksize=ksize, sk=sk, use_conv=use_conv))
|
251 |
+
self.body = nn.ModuleList(self.body)
|
252 |
+
self.conv_in = nn.Conv2d(cin, channels[0], 3, 1, 1)
|
253 |
+
|
254 |
+
def forward(self, x):
|
255 |
+
# unshuffle
|
256 |
+
x = self.unshuffle(x)
|
257 |
+
# extract features
|
258 |
+
features = []
|
259 |
+
x = self.conv_in(x)
|
260 |
+
for i in range(len(self.channels)):
|
261 |
+
for j in range(self.nums_rb):
|
262 |
+
idx = i*self.nums_rb +j
|
263 |
+
x = self.body[idx](x)
|
264 |
+
features.append(x)
|
265 |
+
|
266 |
+
return features
|
267 |
+
|
268 |
+
class LayerNorm(nn.LayerNorm):
|
269 |
+
"""Subclass torch's LayerNorm to handle fp16."""
|
270 |
+
|
271 |
+
def forward(self, x: torch.Tensor):
|
272 |
+
orig_type = x.dtype
|
273 |
+
ret = super().forward(x.type(torch.float32))
|
274 |
+
return ret.type(orig_type)
|
275 |
+
|
276 |
+
|
277 |
+
class QuickGELU(nn.Module):
|
278 |
+
|
279 |
+
def forward(self, x: torch.Tensor):
|
280 |
+
return x * torch.sigmoid(1.702 * x)
|
281 |
+
|
282 |
+
|
283 |
+
class ResidualAttentionBlock(nn.Module):
|
284 |
+
|
285 |
+
def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
|
286 |
+
super().__init__()
|
287 |
+
|
288 |
+
self.attn = nn.MultiheadAttention(d_model, n_head)
|
289 |
+
self.ln_1 = LayerNorm(d_model)
|
290 |
+
self.mlp = nn.Sequential(
|
291 |
+
OrderedDict([("c_fc", nn.Linear(d_model, d_model * 4)), ("gelu", QuickGELU()),
|
292 |
+
("c_proj", nn.Linear(d_model * 4, d_model))]))
|
293 |
+
self.ln_2 = LayerNorm(d_model)
|
294 |
+
self.attn_mask = attn_mask
|
295 |
+
|
296 |
+
def attention(self, x: torch.Tensor):
|
297 |
+
self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
|
298 |
+
return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
|
299 |
+
|
300 |
+
def forward(self, x: torch.Tensor):
|
301 |
+
x = x + self.attention(self.ln_1(x))
|
302 |
+
x = x + self.mlp(self.ln_2(x))
|
303 |
+
return x
|
304 |
+
|
305 |
+
|
306 |
+
class StyleAdapter(nn.Module):
|
307 |
+
|
308 |
+
def __init__(self, width=1024, context_dim=768, num_head=8, n_layes=3, num_token=4):
|
309 |
+
super().__init__()
|
310 |
+
|
311 |
+
scale = width ** -0.5
|
312 |
+
self.transformer_layes = nn.Sequential(*[ResidualAttentionBlock(width, num_head) for _ in range(n_layes)])
|
313 |
+
self.num_token = num_token
|
314 |
+
self.style_embedding = nn.Parameter(torch.randn(1, num_token, width) * scale)
|
315 |
+
self.ln_post = LayerNorm(width)
|
316 |
+
self.ln_pre = LayerNorm(width)
|
317 |
+
self.proj = nn.Parameter(scale * torch.randn(width, context_dim))
|
318 |
+
|
319 |
+
def forward(self, x):
|
320 |
+
# x shape [N, HW+1, C]
|
321 |
+
style_embedding = self.style_embedding + torch.zeros(
|
322 |
+
(x.shape[0], self.num_token, self.style_embedding.shape[-1]), device=x.device)
|
323 |
+
|
324 |
+
x = torch.cat([x, style_embedding], dim=1)
|
325 |
+
x = self.ln_pre(x)
|
326 |
+
x = x.permute(1, 0, 2) # NLD -> LND
|
327 |
+
x = self.transformer_layes(x)
|
328 |
+
x = x.permute(1, 0, 2) # LND -> NLD
|
329 |
+
|
330 |
+
x = self.ln_post(x[:, -self.num_token:, :])
|
331 |
+
x = x @ self.proj
|
332 |
+
|
333 |
+
return x
|
334 |
+
|
335 |
+
|
336 |
+
class ResnetBlock_light(nn.Module):
|
337 |
+
def __init__(self, in_c):
|
338 |
+
super().__init__()
|
339 |
+
self.block1 = nn.Conv2d(in_c, in_c, 3, 1, 1)
|
340 |
+
self.act = nn.ReLU()
|
341 |
+
self.block2 = nn.Conv2d(in_c, in_c, 3, 1, 1)
|
342 |
+
|
343 |
+
def forward(self, x):
|
344 |
+
h = self.block1(x)
|
345 |
+
h = self.act(h)
|
346 |
+
h = self.block2(h)
|
347 |
+
|
348 |
+
return h + x
|
349 |
+
|
350 |
+
|
351 |
+
class extractor(nn.Module):
|
352 |
+
def __init__(self, in_c, inter_c, out_c, nums_rb, down=False):
|
353 |
+
super().__init__()
|
354 |
+
self.in_conv = nn.Conv2d(in_c, inter_c, 1, 1, 0)
|
355 |
+
self.body = []
|
356 |
+
for _ in range(nums_rb):
|
357 |
+
self.body.append(ResnetBlock_light(inter_c))
|
358 |
+
self.body = nn.Sequential(*self.body)
|
359 |
+
self.out_conv = nn.Conv2d(inter_c, out_c, 1, 1, 0)
|
360 |
+
self.down = down
|
361 |
+
if self.down == True:
|
362 |
+
self.down_opt = Downsample(in_c, use_conv=False)
|
363 |
+
|
364 |
+
def forward(self, x):
|
365 |
+
if self.down == True:
|
366 |
+
x = self.down_opt(x)
|
367 |
+
x = self.in_conv(x)
|
368 |
+
x = self.body(x)
|
369 |
+
x = self.out_conv(x)
|
370 |
+
|
371 |
+
return x
|
372 |
+
|
373 |
+
|
374 |
+
class Adapter_light(nn.Module):
|
375 |
+
def __init__(self, channels=[320, 640, 1280, 1280], nums_rb=3, cin=64):
|
376 |
+
super(Adapter_light, self).__init__()
|
377 |
+
self.unshuffle = nn.PixelUnshuffle(8)
|
378 |
+
self.channels = channels
|
379 |
+
self.nums_rb = nums_rb
|
380 |
+
self.body = []
|
381 |
+
for i in range(len(channels)):
|
382 |
+
if i == 0:
|
383 |
+
self.body.append(extractor(in_c=cin, inter_c=channels[i]//4, out_c=channels[i], nums_rb=nums_rb, down=False))
|
384 |
+
else:
|
385 |
+
self.body.append(extractor(in_c=channels[i-1], inter_c=channels[i]//4, out_c=channels[i], nums_rb=nums_rb, down=True))
|
386 |
+
self.body = nn.ModuleList(self.body)
|
387 |
+
|
388 |
+
def forward(self, x):
|
389 |
+
# unshuffle
|
390 |
+
x = self.unshuffle(x)
|
391 |
+
# extract features
|
392 |
+
features = []
|
393 |
+
for i in range(len(self.channels)):
|
394 |
+
x = self.body[i](x)
|
395 |
+
features.append(x)
|
396 |
+
|
397 |
+
return features
|
extensions/microsoftexcel-controlnet/scripts/api.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
from fastapi import FastAPI, Body
|
3 |
+
from fastapi.exceptions import HTTPException
|
4 |
+
from PIL import Image
|
5 |
+
|
6 |
+
import gradio as gr
|
7 |
+
|
8 |
+
from modules.api.models import *
|
9 |
+
from modules.api import api
|
10 |
+
|
11 |
+
from scripts import external_code, global_state
|
12 |
+
from scripts.processor import preprocessor_sliders_config
|
13 |
+
|
14 |
+
def encode_to_base64(image):
|
15 |
+
if type(image) is str:
|
16 |
+
return image
|
17 |
+
elif type(image) is Image.Image:
|
18 |
+
return api.encode_pil_to_base64(image)
|
19 |
+
elif type(image) is np.ndarray:
|
20 |
+
return encode_np_to_base64(image)
|
21 |
+
else:
|
22 |
+
return ""
|
23 |
+
|
24 |
+
def encode_np_to_base64(image):
|
25 |
+
pil = Image.fromarray(image)
|
26 |
+
return api.encode_pil_to_base64(pil)
|
27 |
+
|
28 |
+
def controlnet_api(_: gr.Blocks, app: FastAPI):
|
29 |
+
@app.get("/controlnet/version")
|
30 |
+
async def version():
|
31 |
+
return {"version": external_code.get_api_version()}
|
32 |
+
|
33 |
+
@app.get("/controlnet/model_list")
|
34 |
+
async def model_list():
|
35 |
+
up_to_date_model_list = external_code.get_models(update=True)
|
36 |
+
print(up_to_date_model_list)
|
37 |
+
return {"model_list": up_to_date_model_list}
|
38 |
+
|
39 |
+
@app.get("/controlnet/module_list")
|
40 |
+
async def module_list(alias_names: bool = False):
|
41 |
+
_module_list = external_code.get_modules(alias_names)
|
42 |
+
print(_module_list)
|
43 |
+
|
44 |
+
return {
|
45 |
+
"module_list": _module_list,
|
46 |
+
"module_detail": external_code.get_modules_detail(alias_names)
|
47 |
+
}
|
48 |
+
|
49 |
+
@app.get("/controlnet/settings")
|
50 |
+
async def settings():
|
51 |
+
max_models_num = external_code.get_max_models_num()
|
52 |
+
return {"control_net_max_models_num":max_models_num}
|
53 |
+
|
54 |
+
cached_cn_preprocessors = global_state.cache_preprocessors(global_state.cn_preprocessor_modules)
|
55 |
+
@app.post("/controlnet/detect")
|
56 |
+
async def detect(
|
57 |
+
controlnet_module: str = Body("none", title='Controlnet Module'),
|
58 |
+
controlnet_input_images: List[str] = Body([], title='Controlnet Input Images'),
|
59 |
+
controlnet_processor_res: int = Body(512, title='Controlnet Processor Resolution'),
|
60 |
+
controlnet_threshold_a: float = Body(64, title='Controlnet Threshold a'),
|
61 |
+
controlnet_threshold_b: float = Body(64, title='Controlnet Threshold b')
|
62 |
+
):
|
63 |
+
controlnet_module = global_state.reverse_preprocessor_aliases.get(controlnet_module, controlnet_module)
|
64 |
+
|
65 |
+
if controlnet_module not in cached_cn_preprocessors:
|
66 |
+
raise HTTPException(
|
67 |
+
status_code=422, detail="Module not available")
|
68 |
+
|
69 |
+
if len(controlnet_input_images) == 0:
|
70 |
+
raise HTTPException(
|
71 |
+
status_code=422, detail="No image selected")
|
72 |
+
|
73 |
+
print(f"Detecting {str(len(controlnet_input_images))} images with the {controlnet_module} module.")
|
74 |
+
|
75 |
+
results = []
|
76 |
+
|
77 |
+
processor_module = cached_cn_preprocessors[controlnet_module]
|
78 |
+
|
79 |
+
for input_image in controlnet_input_images:
|
80 |
+
img = external_code.to_base64_nparray(input_image)
|
81 |
+
results.append(processor_module(img, res=controlnet_processor_res, thr_a=controlnet_threshold_a, thr_b=controlnet_threshold_b)[0])
|
82 |
+
|
83 |
+
global_state.cn_preprocessor_unloadable.get(controlnet_module, lambda: None)()
|
84 |
+
results64 = list(map(encode_to_base64, results))
|
85 |
+
return {"images": results64, "info": "Success"}
|
86 |
+
|
87 |
+
try:
|
88 |
+
import modules.script_callbacks as script_callbacks
|
89 |
+
|
90 |
+
script_callbacks.on_app_started(controlnet_api)
|
91 |
+
except:
|
92 |
+
pass
|
extensions/microsoftexcel-controlnet/scripts/batch_hijack.py
ADDED
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from copy import copy
|
3 |
+
from enum import Enum
|
4 |
+
from typing import Tuple, List
|
5 |
+
|
6 |
+
from modules import img2img, processing, shared, script_callbacks
|
7 |
+
from scripts import external_code
|
8 |
+
|
9 |
+
|
10 |
+
class BatchHijack:
|
11 |
+
def __init__(self):
|
12 |
+
self.is_batch = False
|
13 |
+
self.batch_index = 0
|
14 |
+
self.batch_size = 1
|
15 |
+
self.init_seed = None
|
16 |
+
self.init_subseed = None
|
17 |
+
self.process_batch_callbacks = [self.on_process_batch]
|
18 |
+
self.process_batch_each_callbacks = []
|
19 |
+
self.postprocess_batch_each_callbacks = [self.on_postprocess_batch_each]
|
20 |
+
self.postprocess_batch_callbacks = [self.on_postprocess_batch]
|
21 |
+
|
22 |
+
def img2img_process_batch_hijack(self, p, *args, **kwargs):
|
23 |
+
cn_is_batch, batches, output_dir, _ = get_cn_batches(p)
|
24 |
+
if not cn_is_batch:
|
25 |
+
return getattr(img2img, '__controlnet_original_process_batch')(p, *args, **kwargs)
|
26 |
+
|
27 |
+
self.dispatch_callbacks(self.process_batch_callbacks, p, batches, output_dir)
|
28 |
+
|
29 |
+
try:
|
30 |
+
return getattr(img2img, '__controlnet_original_process_batch')(p, *args, **kwargs)
|
31 |
+
finally:
|
32 |
+
self.dispatch_callbacks(self.postprocess_batch_callbacks, p)
|
33 |
+
|
34 |
+
def processing_process_images_hijack(self, p, *args, **kwargs):
|
35 |
+
if self.is_batch:
|
36 |
+
# we are in img2img batch tab, do a single batch iteration
|
37 |
+
return self.process_images_cn_batch(p, *args, **kwargs)
|
38 |
+
|
39 |
+
cn_is_batch, batches, output_dir, input_file_names = get_cn_batches(p)
|
40 |
+
if not cn_is_batch:
|
41 |
+
# we are not in batch mode, fallback to original function
|
42 |
+
return getattr(processing, '__controlnet_original_process_images_inner')(p, *args, **kwargs)
|
43 |
+
|
44 |
+
output_images = []
|
45 |
+
try:
|
46 |
+
self.dispatch_callbacks(self.process_batch_callbacks, p, batches, output_dir)
|
47 |
+
|
48 |
+
for batch_i in range(self.batch_size):
|
49 |
+
processed = self.process_images_cn_batch(p, *args, **kwargs)
|
50 |
+
if shared.opts.data.get('controlnet_show_batch_images_in_ui', False):
|
51 |
+
output_images.extend(processed.images[processed.index_of_first_image:])
|
52 |
+
|
53 |
+
if output_dir:
|
54 |
+
self.save_images(output_dir, input_file_names[batch_i], processed.images[processed.index_of_first_image:])
|
55 |
+
|
56 |
+
if shared.state.interrupted:
|
57 |
+
break
|
58 |
+
|
59 |
+
finally:
|
60 |
+
self.dispatch_callbacks(self.postprocess_batch_callbacks, p)
|
61 |
+
|
62 |
+
if output_images:
|
63 |
+
processed.images = output_images
|
64 |
+
else:
|
65 |
+
processed = processing.Processed(p, [], p.seed)
|
66 |
+
|
67 |
+
return processed
|
68 |
+
|
69 |
+
def process_images_cn_batch(self, p, *args, **kwargs):
|
70 |
+
self.dispatch_callbacks(self.process_batch_each_callbacks, p)
|
71 |
+
old_detectmap_output = shared.opts.data.get('control_net_no_detectmap', False)
|
72 |
+
try:
|
73 |
+
shared.opts.data.update({'control_net_no_detectmap': True})
|
74 |
+
processed = getattr(processing, '__controlnet_original_process_images_inner')(p, *args, **kwargs)
|
75 |
+
finally:
|
76 |
+
shared.opts.data.update({'control_net_no_detectmap': old_detectmap_output})
|
77 |
+
|
78 |
+
self.dispatch_callbacks(self.postprocess_batch_each_callbacks, p, processed)
|
79 |
+
|
80 |
+
# do not go past control net batch size
|
81 |
+
if self.batch_index >= self.batch_size:
|
82 |
+
shared.state.interrupted = True
|
83 |
+
|
84 |
+
return processed
|
85 |
+
|
86 |
+
def save_images(self, output_dir, init_image_path, output_images):
|
87 |
+
os.makedirs(output_dir, exist_ok=True)
|
88 |
+
for n, processed_image in enumerate(output_images):
|
89 |
+
filename = os.path.basename(init_image_path)
|
90 |
+
|
91 |
+
if n > 0:
|
92 |
+
left, right = os.path.splitext(filename)
|
93 |
+
filename = f"{left}-{n}{right}"
|
94 |
+
|
95 |
+
if processed_image.mode == 'RGBA':
|
96 |
+
processed_image = processed_image.convert("RGB")
|
97 |
+
processed_image.save(os.path.join(output_dir, filename))
|
98 |
+
|
99 |
+
def do_hijack(self):
|
100 |
+
script_callbacks.on_script_unloaded(self.undo_hijack)
|
101 |
+
hijack_function(
|
102 |
+
module=img2img,
|
103 |
+
name='process_batch',
|
104 |
+
new_name='__controlnet_original_process_batch',
|
105 |
+
new_value=self.img2img_process_batch_hijack,
|
106 |
+
)
|
107 |
+
hijack_function(
|
108 |
+
module=processing,
|
109 |
+
name='process_images_inner',
|
110 |
+
new_name='__controlnet_original_process_images_inner',
|
111 |
+
new_value=self.processing_process_images_hijack
|
112 |
+
)
|
113 |
+
|
114 |
+
def undo_hijack(self):
|
115 |
+
unhijack_function(
|
116 |
+
module=img2img,
|
117 |
+
name='process_batch',
|
118 |
+
new_name='__controlnet_original_process_batch',
|
119 |
+
)
|
120 |
+
unhijack_function(
|
121 |
+
module=processing,
|
122 |
+
name='process_images_inner',
|
123 |
+
new_name='__controlnet_original_process_images_inner',
|
124 |
+
)
|
125 |
+
|
126 |
+
def adjust_job_count(self, p):
|
127 |
+
if shared.state.job_count == -1:
|
128 |
+
shared.state.job_count = p.n_iter
|
129 |
+
shared.state.job_count *= self.batch_size
|
130 |
+
|
131 |
+
def on_process_batch(self, p, batches, output_dir, *args):
|
132 |
+
print('controlnet batch mode')
|
133 |
+
self.is_batch = True
|
134 |
+
self.batch_index = 0
|
135 |
+
self.batch_size = len(batches)
|
136 |
+
processing.fix_seed(p)
|
137 |
+
if shared.opts.data.get('controlnet_increment_seed_during_batch', False):
|
138 |
+
self.init_seed = p.seed
|
139 |
+
self.init_subseed = p.subseed
|
140 |
+
self.adjust_job_count(p)
|
141 |
+
p.do_not_save_grid = True
|
142 |
+
p.do_not_save_samples = bool(output_dir)
|
143 |
+
|
144 |
+
def on_postprocess_batch_each(self, p, *args):
|
145 |
+
self.batch_index += 1
|
146 |
+
if shared.opts.data.get('controlnet_increment_seed_during_batch', False):
|
147 |
+
p.seed = p.seed + len(p.all_prompts)
|
148 |
+
p.subseed = p.subseed + len(p.all_prompts)
|
149 |
+
|
150 |
+
def on_postprocess_batch(self, p, *args):
|
151 |
+
self.is_batch = False
|
152 |
+
self.batch_index = 0
|
153 |
+
self.batch_size = 1
|
154 |
+
if shared.opts.data.get('controlnet_increment_seed_during_batch', False):
|
155 |
+
p.seed = self.init_seed
|
156 |
+
p.all_seeds = [self.init_seed]
|
157 |
+
p.subseed = self.init_subseed
|
158 |
+
p.all_subseeds = [self.init_subseed]
|
159 |
+
|
160 |
+
def dispatch_callbacks(self, callbacks, *args):
|
161 |
+
for callback in callbacks:
|
162 |
+
callback(*args)
|
163 |
+
|
164 |
+
|
165 |
+
def hijack_function(module, name, new_name, new_value):
|
166 |
+
# restore original function in case of reload
|
167 |
+
unhijack_function(module=module, name=name, new_name=new_name)
|
168 |
+
setattr(module, new_name, getattr(module, name))
|
169 |
+
setattr(module, name, new_value)
|
170 |
+
|
171 |
+
|
172 |
+
def unhijack_function(module, name, new_name):
|
173 |
+
if hasattr(module, new_name):
|
174 |
+
setattr(module, name, getattr(module, new_name))
|
175 |
+
delattr(module, new_name)
|
176 |
+
|
177 |
+
|
178 |
+
class InputMode(Enum):
|
179 |
+
SIMPLE = "simple"
|
180 |
+
BATCH = "batch"
|
181 |
+
|
182 |
+
|
183 |
+
def get_cn_batches(p: processing.StableDiffusionProcessing) -> Tuple[bool, List[List[str]], str, List[str]]:
|
184 |
+
units = external_code.get_all_units_in_processing(p)
|
185 |
+
units = [copy(unit) for unit in units if getattr(unit, 'enabled', False)]
|
186 |
+
any_unit_is_batch = False
|
187 |
+
output_dir = ''
|
188 |
+
input_file_names = []
|
189 |
+
for unit in units:
|
190 |
+
if getattr(unit, 'input_mode', InputMode.SIMPLE) == InputMode.BATCH:
|
191 |
+
any_unit_is_batch = True
|
192 |
+
output_dir = getattr(unit, 'output_dir', '')
|
193 |
+
if isinstance(unit.batch_images, str):
|
194 |
+
unit.batch_images = shared.listfiles(unit.batch_images)
|
195 |
+
input_file_names = unit.batch_images
|
196 |
+
|
197 |
+
if any_unit_is_batch:
|
198 |
+
cn_batch_size = min(len(getattr(unit, 'batch_images', []))
|
199 |
+
for unit in units
|
200 |
+
if getattr(unit, 'input_mode', InputMode.SIMPLE) == InputMode.BATCH)
|
201 |
+
else:
|
202 |
+
cn_batch_size = 1
|
203 |
+
|
204 |
+
batches = [[] for _ in range(cn_batch_size)]
|
205 |
+
for i in range(cn_batch_size):
|
206 |
+
for unit in units:
|
207 |
+
if getattr(unit, 'input_mode', InputMode.SIMPLE) == InputMode.SIMPLE:
|
208 |
+
batches[i].append(unit.image)
|
209 |
+
else:
|
210 |
+
batches[i].append(unit.batch_images[i])
|
211 |
+
|
212 |
+
return any_unit_is_batch, batches, output_dir, input_file_names
|
213 |
+
|
214 |
+
|
215 |
+
instance = BatchHijack()
|
extensions/microsoftexcel-controlnet/scripts/cldm.py
ADDED
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from omegaconf import OmegaConf
|
4 |
+
from modules import devices, shared
|
5 |
+
|
6 |
+
cond_cast_unet = getattr(devices, 'cond_cast_unet', lambda x: x)
|
7 |
+
|
8 |
+
from ldm.util import exists
|
9 |
+
from ldm.modules.attention import SpatialTransformer
|
10 |
+
from ldm.modules.diffusionmodules.util import conv_nd, linear, zero_module, timestep_embedding
|
11 |
+
from ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, ResBlock, Downsample, AttentionBlock
|
12 |
+
|
13 |
+
|
14 |
+
class TorchHijackForUnet:
|
15 |
+
"""
|
16 |
+
This is torch, but with cat that resizes tensors to appropriate dimensions if they do not match;
|
17 |
+
this makes it possible to create pictures with dimensions that are multiples of 8 rather than 64
|
18 |
+
"""
|
19 |
+
|
20 |
+
def __getattr__(self, item):
|
21 |
+
if item == 'cat':
|
22 |
+
return self.cat
|
23 |
+
|
24 |
+
if hasattr(torch, item):
|
25 |
+
return getattr(torch, item)
|
26 |
+
|
27 |
+
raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, item))
|
28 |
+
|
29 |
+
def cat(self, tensors, *args, **kwargs):
|
30 |
+
if len(tensors) == 2:
|
31 |
+
a, b = tensors
|
32 |
+
if a.shape[-2:] != b.shape[-2:]:
|
33 |
+
a = torch.nn.functional.interpolate(a, b.shape[-2:], mode="nearest")
|
34 |
+
|
35 |
+
tensors = (a, b)
|
36 |
+
|
37 |
+
return torch.cat(tensors, *args, **kwargs)
|
38 |
+
|
39 |
+
|
40 |
+
th = TorchHijackForUnet()
|
41 |
+
|
42 |
+
|
43 |
+
def align(hint, size):
|
44 |
+
b, c, h1, w1 = hint.shape
|
45 |
+
h, w = size
|
46 |
+
if h != h1 or w != w1:
|
47 |
+
hint = th.nn.functional.interpolate(hint, size=size, mode="nearest")
|
48 |
+
return hint
|
49 |
+
|
50 |
+
|
51 |
+
def get_node_name(name, parent_name):
|
52 |
+
if len(name) <= len(parent_name):
|
53 |
+
return False, ''
|
54 |
+
p = name[:len(parent_name)]
|
55 |
+
if p != parent_name:
|
56 |
+
return False, ''
|
57 |
+
return True, name[len(parent_name):]
|
58 |
+
|
59 |
+
|
60 |
+
class PlugableControlModel(nn.Module):
|
61 |
+
def __init__(self, state_dict, config_path, lowvram=False, base_model=None) -> None:
|
62 |
+
super().__init__()
|
63 |
+
self.config = OmegaConf.load(config_path)
|
64 |
+
self.control_model = ControlNet(**self.config.model.params.control_stage_config.params)
|
65 |
+
|
66 |
+
if any([k.startswith("control_model.") for k, v in state_dict.items()]):
|
67 |
+
if 'difference' in state_dict and base_model is not None:
|
68 |
+
print('We will stop supporting diff models soon because of its lack of robustness.')
|
69 |
+
print('Please begin to use official models as soon as possible.')
|
70 |
+
|
71 |
+
unet_state_dict = base_model.state_dict()
|
72 |
+
unet_state_dict_keys = unet_state_dict.keys()
|
73 |
+
final_state_dict = {}
|
74 |
+
counter = 0
|
75 |
+
for key in state_dict.keys():
|
76 |
+
if not key.startswith("control_model."):
|
77 |
+
continue
|
78 |
+
p = state_dict[key]
|
79 |
+
is_control, node_name = get_node_name(key, 'control_')
|
80 |
+
key_name = node_name.replace("model.", "") if is_control else key
|
81 |
+
if key_name in unet_state_dict_keys:
|
82 |
+
p_new = p + unet_state_dict[key_name].clone().cpu()
|
83 |
+
counter += 1
|
84 |
+
else:
|
85 |
+
p_new = p
|
86 |
+
final_state_dict[key] = p_new
|
87 |
+
print(f'Diff model cloned: {counter} values')
|
88 |
+
state_dict = final_state_dict
|
89 |
+
state_dict = {k.replace("control_model.", ""): v for k, v in state_dict.items() if k.startswith("control_model.")}
|
90 |
+
|
91 |
+
self.control_model.load_state_dict(state_dict)
|
92 |
+
if not lowvram:
|
93 |
+
self.control_model.to(devices.get_device_for("controlnet"))
|
94 |
+
|
95 |
+
def reset(self):
|
96 |
+
pass
|
97 |
+
|
98 |
+
def forward(self, *args, **kwargs):
|
99 |
+
return self.control_model(*args, **kwargs)
|
100 |
+
|
101 |
+
|
102 |
+
class ControlNet(nn.Module):
|
103 |
+
def __init__(
|
104 |
+
self,
|
105 |
+
image_size,
|
106 |
+
in_channels,
|
107 |
+
model_channels,
|
108 |
+
hint_channels,
|
109 |
+
num_res_blocks,
|
110 |
+
attention_resolutions,
|
111 |
+
dropout=0,
|
112 |
+
channel_mult=(1, 2, 4, 8),
|
113 |
+
conv_resample=True,
|
114 |
+
dims=2,
|
115 |
+
use_checkpoint=False,
|
116 |
+
use_fp16=False,
|
117 |
+
num_heads=-1,
|
118 |
+
num_head_channels=-1,
|
119 |
+
num_heads_upsample=-1,
|
120 |
+
use_scale_shift_norm=False,
|
121 |
+
resblock_updown=False,
|
122 |
+
use_new_attention_order=False,
|
123 |
+
use_spatial_transformer=False, # custom transformer support
|
124 |
+
transformer_depth=1, # custom transformer support
|
125 |
+
context_dim=None, # custom transformer support
|
126 |
+
# custom support for prediction of discrete ids into codebook of first stage vq model
|
127 |
+
n_embed=None,
|
128 |
+
legacy=True,
|
129 |
+
disable_self_attentions=None,
|
130 |
+
num_attention_blocks=None,
|
131 |
+
disable_middle_self_attn=False,
|
132 |
+
use_linear_in_transformer=False,
|
133 |
+
):
|
134 |
+
use_fp16 = getattr(devices, 'dtype_unet', devices.dtype) == th.float16 and not getattr(shared.cmd_opts, "no_half_controlnet", False)
|
135 |
+
|
136 |
+
super().__init__()
|
137 |
+
if use_spatial_transformer:
|
138 |
+
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
|
139 |
+
|
140 |
+
if context_dim is not None:
|
141 |
+
assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
|
142 |
+
from omegaconf.listconfig import ListConfig
|
143 |
+
if type(context_dim) == ListConfig:
|
144 |
+
context_dim = list(context_dim)
|
145 |
+
|
146 |
+
if num_heads_upsample == -1:
|
147 |
+
num_heads_upsample = num_heads
|
148 |
+
|
149 |
+
if num_heads == -1:
|
150 |
+
assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
|
151 |
+
|
152 |
+
if num_head_channels == -1:
|
153 |
+
assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
|
154 |
+
|
155 |
+
self.dims = dims
|
156 |
+
self.image_size = image_size
|
157 |
+
self.in_channels = in_channels
|
158 |
+
self.model_channels = model_channels
|
159 |
+
if isinstance(num_res_blocks, int):
|
160 |
+
self.num_res_blocks = len(channel_mult) * [num_res_blocks]
|
161 |
+
else:
|
162 |
+
if len(num_res_blocks) != len(channel_mult):
|
163 |
+
raise ValueError("provide num_res_blocks either as an int (globally constant) or "
|
164 |
+
"as a list/tuple (per-level) with the same length as channel_mult")
|
165 |
+
self.num_res_blocks = num_res_blocks
|
166 |
+
if disable_self_attentions is not None:
|
167 |
+
# should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
|
168 |
+
assert len(disable_self_attentions) == len(channel_mult)
|
169 |
+
if num_attention_blocks is not None:
|
170 |
+
assert len(num_attention_blocks) == len(self.num_res_blocks)
|
171 |
+
assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(
|
172 |
+
len(num_attention_blocks))))
|
173 |
+
print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "
|
174 |
+
f"This option has LESS priority than attention_resolutions {attention_resolutions}, "
|
175 |
+
f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "
|
176 |
+
f"attention will still not be set.")
|
177 |
+
|
178 |
+
self.attention_resolutions = attention_resolutions
|
179 |
+
self.dropout = dropout
|
180 |
+
self.channel_mult = channel_mult
|
181 |
+
self.conv_resample = conv_resample
|
182 |
+
self.use_checkpoint = use_checkpoint
|
183 |
+
self.dtype = th.float16 if use_fp16 else th.float32
|
184 |
+
self.num_heads = num_heads
|
185 |
+
self.num_head_channels = num_head_channels
|
186 |
+
self.num_heads_upsample = num_heads_upsample
|
187 |
+
self.predict_codebook_ids = n_embed is not None
|
188 |
+
|
189 |
+
time_embed_dim = model_channels * 4
|
190 |
+
self.time_embed = nn.Sequential(
|
191 |
+
linear(model_channels, time_embed_dim),
|
192 |
+
nn.SiLU(),
|
193 |
+
linear(time_embed_dim, time_embed_dim),
|
194 |
+
)
|
195 |
+
|
196 |
+
self.input_blocks = nn.ModuleList(
|
197 |
+
[
|
198 |
+
TimestepEmbedSequential(
|
199 |
+
conv_nd(dims, in_channels, model_channels, 3, padding=1)
|
200 |
+
)
|
201 |
+
]
|
202 |
+
)
|
203 |
+
self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels)])
|
204 |
+
|
205 |
+
self.input_hint_block = TimestepEmbedSequential(
|
206 |
+
conv_nd(dims, hint_channels, 16, 3, padding=1),
|
207 |
+
nn.SiLU(),
|
208 |
+
conv_nd(dims, 16, 16, 3, padding=1),
|
209 |
+
nn.SiLU(),
|
210 |
+
conv_nd(dims, 16, 32, 3, padding=1, stride=2),
|
211 |
+
nn.SiLU(),
|
212 |
+
conv_nd(dims, 32, 32, 3, padding=1),
|
213 |
+
nn.SiLU(),
|
214 |
+
conv_nd(dims, 32, 96, 3, padding=1, stride=2),
|
215 |
+
nn.SiLU(),
|
216 |
+
conv_nd(dims, 96, 96, 3, padding=1),
|
217 |
+
nn.SiLU(),
|
218 |
+
conv_nd(dims, 96, 256, 3, padding=1, stride=2),
|
219 |
+
nn.SiLU(),
|
220 |
+
zero_module(conv_nd(dims, 256, model_channels, 3, padding=1))
|
221 |
+
)
|
222 |
+
|
223 |
+
self._feature_size = model_channels
|
224 |
+
input_block_chans = [model_channels]
|
225 |
+
ch = model_channels
|
226 |
+
ds = 1
|
227 |
+
for level, mult in enumerate(channel_mult):
|
228 |
+
for nr in range(self.num_res_blocks[level]):
|
229 |
+
layers = [
|
230 |
+
ResBlock(
|
231 |
+
ch,
|
232 |
+
time_embed_dim,
|
233 |
+
dropout,
|
234 |
+
out_channels=mult * model_channels,
|
235 |
+
dims=dims,
|
236 |
+
use_checkpoint=use_checkpoint,
|
237 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
238 |
+
)
|
239 |
+
]
|
240 |
+
ch = mult * model_channels
|
241 |
+
if ds in attention_resolutions:
|
242 |
+
if num_head_channels == -1:
|
243 |
+
dim_head = ch // num_heads
|
244 |
+
else:
|
245 |
+
num_heads = ch // num_head_channels
|
246 |
+
dim_head = num_head_channels
|
247 |
+
if legacy:
|
248 |
+
#num_heads = 1
|
249 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
250 |
+
if exists(disable_self_attentions):
|
251 |
+
disabled_sa = disable_self_attentions[level]
|
252 |
+
else:
|
253 |
+
disabled_sa = False
|
254 |
+
|
255 |
+
if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
|
256 |
+
layers.append(
|
257 |
+
AttentionBlock(
|
258 |
+
ch,
|
259 |
+
use_checkpoint=use_checkpoint,
|
260 |
+
num_heads=num_heads,
|
261 |
+
num_head_channels=dim_head,
|
262 |
+
use_new_attention_order=use_new_attention_order,
|
263 |
+
) if not use_spatial_transformer else SpatialTransformer(
|
264 |
+
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
265 |
+
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
266 |
+
use_checkpoint=use_checkpoint
|
267 |
+
)
|
268 |
+
)
|
269 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
270 |
+
self.zero_convs.append(self.make_zero_conv(ch))
|
271 |
+
self._feature_size += ch
|
272 |
+
input_block_chans.append(ch)
|
273 |
+
if level != len(channel_mult) - 1:
|
274 |
+
out_ch = ch
|
275 |
+
self.input_blocks.append(
|
276 |
+
TimestepEmbedSequential(
|
277 |
+
ResBlock(
|
278 |
+
ch,
|
279 |
+
time_embed_dim,
|
280 |
+
dropout,
|
281 |
+
out_channels=out_ch,
|
282 |
+
dims=dims,
|
283 |
+
use_checkpoint=use_checkpoint,
|
284 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
285 |
+
down=True,
|
286 |
+
)
|
287 |
+
if resblock_updown
|
288 |
+
else Downsample(
|
289 |
+
ch, conv_resample, dims=dims, out_channels=out_ch
|
290 |
+
)
|
291 |
+
)
|
292 |
+
)
|
293 |
+
ch = out_ch
|
294 |
+
input_block_chans.append(ch)
|
295 |
+
self.zero_convs.append(self.make_zero_conv(ch))
|
296 |
+
ds *= 2
|
297 |
+
self._feature_size += ch
|
298 |
+
|
299 |
+
if num_head_channels == -1:
|
300 |
+
dim_head = ch // num_heads
|
301 |
+
else:
|
302 |
+
num_heads = ch // num_head_channels
|
303 |
+
dim_head = num_head_channels
|
304 |
+
if legacy:
|
305 |
+
#num_heads = 1
|
306 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
307 |
+
self.middle_block = TimestepEmbedSequential(
|
308 |
+
ResBlock(
|
309 |
+
ch,
|
310 |
+
time_embed_dim,
|
311 |
+
dropout,
|
312 |
+
dims=dims,
|
313 |
+
use_checkpoint=use_checkpoint,
|
314 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
315 |
+
),
|
316 |
+
AttentionBlock(
|
317 |
+
ch,
|
318 |
+
use_checkpoint=use_checkpoint,
|
319 |
+
num_heads=num_heads,
|
320 |
+
num_head_channels=dim_head,
|
321 |
+
use_new_attention_order=use_new_attention_order,
|
322 |
+
# always uses a self-attn
|
323 |
+
) if not use_spatial_transformer else SpatialTransformer(
|
324 |
+
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
325 |
+
disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
|
326 |
+
use_checkpoint=use_checkpoint
|
327 |
+
),
|
328 |
+
ResBlock(
|
329 |
+
ch,
|
330 |
+
time_embed_dim,
|
331 |
+
dropout,
|
332 |
+
dims=dims,
|
333 |
+
use_checkpoint=use_checkpoint,
|
334 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
335 |
+
),
|
336 |
+
)
|
337 |
+
self.middle_block_out = self.make_zero_conv(ch)
|
338 |
+
self._feature_size += ch
|
339 |
+
|
340 |
+
def make_zero_conv(self, channels):
|
341 |
+
return TimestepEmbedSequential(zero_module(conv_nd(self.dims, channels, channels, 1, padding=0)))
|
342 |
+
|
343 |
+
def align(self, hint, h, w):
|
344 |
+
b, c, h1, w1 = hint.shape
|
345 |
+
if h != h1 or w != w1:
|
346 |
+
return align(hint, (h, w))
|
347 |
+
return hint
|
348 |
+
|
349 |
+
def forward(self, x, hint, timesteps, context, **kwargs):
|
350 |
+
t_emb = cond_cast_unet(timestep_embedding(timesteps, self.model_channels, repeat_only=False))
|
351 |
+
emb = self.time_embed(t_emb)
|
352 |
+
|
353 |
+
guided_hint = self.input_hint_block(cond_cast_unet(hint), emb, context)
|
354 |
+
outs = []
|
355 |
+
|
356 |
+
h1, w1 = x.shape[-2:]
|
357 |
+
guided_hint = self.align(guided_hint, h1, w1)
|
358 |
+
|
359 |
+
h = x.type(self.dtype)
|
360 |
+
for module, zero_conv in zip(self.input_blocks, self.zero_convs):
|
361 |
+
if guided_hint is not None:
|
362 |
+
h = module(h, emb, context)
|
363 |
+
h += guided_hint
|
364 |
+
guided_hint = None
|
365 |
+
else:
|
366 |
+
h = module(h, emb, context)
|
367 |
+
outs.append(zero_conv(h, emb, context))
|
368 |
+
|
369 |
+
h = self.middle_block(h, emb, context)
|
370 |
+
outs.append(self.middle_block_out(h, emb, context))
|
371 |
+
|
372 |
+
return outs
|
extensions/microsoftexcel-controlnet/scripts/controlnet.py
ADDED
@@ -0,0 +1,920 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gc
|
2 |
+
import os
|
3 |
+
from collections import OrderedDict
|
4 |
+
from copy import copy
|
5 |
+
from typing import Dict, Optional
|
6 |
+
import importlib
|
7 |
+
import modules.scripts as scripts
|
8 |
+
from modules import shared, devices, script_callbacks, processing, masking, images
|
9 |
+
import gradio as gr
|
10 |
+
|
11 |
+
from einops import rearrange
|
12 |
+
from scripts import global_state, hook, external_code, processor, batch_hijack, controlnet_version, utils
|
13 |
+
importlib.reload(processor)
|
14 |
+
importlib.reload(utils)
|
15 |
+
importlib.reload(global_state)
|
16 |
+
importlib.reload(hook)
|
17 |
+
importlib.reload(external_code)
|
18 |
+
importlib.reload(batch_hijack)
|
19 |
+
from scripts.cldm import PlugableControlModel
|
20 |
+
from scripts.processor import *
|
21 |
+
from scripts.adapter import PlugableAdapter
|
22 |
+
from scripts.utils import load_state_dict
|
23 |
+
from scripts.hook import ControlParams, UnetHook, ControlModelType
|
24 |
+
from scripts.ui.controlnet_ui_group import ControlNetUiGroup, UiControlNetUnit
|
25 |
+
from modules.processing import StableDiffusionProcessingImg2Img, StableDiffusionProcessingTxt2Img
|
26 |
+
from modules.images import save_image
|
27 |
+
|
28 |
+
import cv2
|
29 |
+
import numpy as np
|
30 |
+
import torch
|
31 |
+
|
32 |
+
from pathlib import Path
|
33 |
+
from PIL import Image, ImageFilter, ImageOps
|
34 |
+
from scripts.lvminthin import lvmin_thin, nake_nms
|
35 |
+
from scripts.processor import model_free_preprocessors
|
36 |
+
|
37 |
+
gradio_compat = True
|
38 |
+
try:
|
39 |
+
from distutils.version import LooseVersion
|
40 |
+
from importlib_metadata import version
|
41 |
+
if LooseVersion(version("gradio")) < LooseVersion("3.10"):
|
42 |
+
gradio_compat = False
|
43 |
+
except ImportError:
|
44 |
+
pass
|
45 |
+
|
46 |
+
def find_closest_lora_model_name(search: str):
|
47 |
+
if not search:
|
48 |
+
return None
|
49 |
+
if search in global_state.cn_models:
|
50 |
+
return search
|
51 |
+
search = search.lower()
|
52 |
+
if search in global_state.cn_models_names:
|
53 |
+
return global_state.cn_models_names.get(search)
|
54 |
+
applicable = [name for name in global_state.cn_models_names.keys()
|
55 |
+
if search in name.lower()]
|
56 |
+
if not applicable:
|
57 |
+
return None
|
58 |
+
applicable = sorted(applicable, key=lambda name: len(name))
|
59 |
+
return global_state.cn_models_names[applicable[0]]
|
60 |
+
|
61 |
+
|
62 |
+
def swap_img2img_pipeline(p: processing.StableDiffusionProcessingImg2Img):
|
63 |
+
p.__class__ = processing.StableDiffusionProcessingTxt2Img
|
64 |
+
dummy = processing.StableDiffusionProcessingTxt2Img()
|
65 |
+
for k,v in dummy.__dict__.items():
|
66 |
+
if hasattr(p, k):
|
67 |
+
continue
|
68 |
+
setattr(p, k, v)
|
69 |
+
|
70 |
+
|
71 |
+
global_state.update_cn_models()
|
72 |
+
|
73 |
+
|
74 |
+
def image_dict_from_any(image) -> Optional[Dict[str, np.ndarray]]:
|
75 |
+
if image is None:
|
76 |
+
return None
|
77 |
+
|
78 |
+
if isinstance(image, (tuple, list)):
|
79 |
+
image = {'image': image[0], 'mask': image[1]}
|
80 |
+
elif not isinstance(image, dict):
|
81 |
+
image = {'image': image, 'mask': None}
|
82 |
+
else: # type(image) is dict
|
83 |
+
# copy to enable modifying the dict and prevent response serialization error
|
84 |
+
image = dict(image)
|
85 |
+
|
86 |
+
if isinstance(image['image'], str):
|
87 |
+
if os.path.exists(image['image']):
|
88 |
+
image['image'] = np.array(Image.open(image['image'])).astype('uint8')
|
89 |
+
elif image['image']:
|
90 |
+
image['image'] = external_code.to_base64_nparray(image['image'])
|
91 |
+
else:
|
92 |
+
image['image'] = None
|
93 |
+
|
94 |
+
# If there is no image, return image with None image and None mask
|
95 |
+
if image['image'] is None:
|
96 |
+
image['mask'] = None
|
97 |
+
return image
|
98 |
+
|
99 |
+
if isinstance(image['mask'], str):
|
100 |
+
if os.path.exists(image['mask']):
|
101 |
+
image['mask'] = np.array(Image.open(image['mask'])).astype('uint8')
|
102 |
+
elif image['mask']:
|
103 |
+
image['mask'] = external_code.to_base64_nparray(image['mask'])
|
104 |
+
else:
|
105 |
+
image['mask'] = np.zeros_like(image['image'], dtype=np.uint8)
|
106 |
+
elif image['mask'] is None:
|
107 |
+
image['mask'] = np.zeros_like(image['image'], dtype=np.uint8)
|
108 |
+
|
109 |
+
return image
|
110 |
+
|
111 |
+
|
112 |
+
class Script(scripts.Script):
|
113 |
+
model_cache = OrderedDict()
|
114 |
+
|
115 |
+
def __init__(self) -> None:
|
116 |
+
super().__init__()
|
117 |
+
self.latest_network = None
|
118 |
+
self.preprocessor = global_state.cache_preprocessors(global_state.cn_preprocessor_modules)
|
119 |
+
self.unloadable = global_state.cn_preprocessor_unloadable
|
120 |
+
self.input_image = None
|
121 |
+
self.latest_model_hash = ""
|
122 |
+
self.enabled_units = []
|
123 |
+
self.detected_map = []
|
124 |
+
self.post_processors = []
|
125 |
+
batch_hijack.instance.process_batch_callbacks.append(self.batch_tab_process)
|
126 |
+
batch_hijack.instance.process_batch_each_callbacks.append(self.batch_tab_process_each)
|
127 |
+
batch_hijack.instance.postprocess_batch_each_callbacks.insert(0, self.batch_tab_postprocess_each)
|
128 |
+
batch_hijack.instance.postprocess_batch_callbacks.insert(0, self.batch_tab_postprocess)
|
129 |
+
|
130 |
+
def title(self):
|
131 |
+
return "ControlNet"
|
132 |
+
|
133 |
+
def show(self, is_img2img):
|
134 |
+
return scripts.AlwaysVisible
|
135 |
+
|
136 |
+
def get_threshold_block(self, proc):
|
137 |
+
pass
|
138 |
+
|
139 |
+
def get_default_ui_unit(self, is_ui=True):
|
140 |
+
cls = UiControlNetUnit if is_ui else external_code.ControlNetUnit
|
141 |
+
return cls(
|
142 |
+
enabled=False,
|
143 |
+
module="none",
|
144 |
+
model="None"
|
145 |
+
)
|
146 |
+
|
147 |
+
def uigroup(self, tabname: str, is_img2img: bool, elem_id_tabname: str):
|
148 |
+
group = ControlNetUiGroup(
|
149 |
+
gradio_compat,
|
150 |
+
self.infotext_fields,
|
151 |
+
self.get_default_ui_unit(),
|
152 |
+
self.preprocessor,
|
153 |
+
)
|
154 |
+
group.render(tabname, elem_id_tabname)
|
155 |
+
group.register_callbacks(is_img2img)
|
156 |
+
return group.render_and_register_unit(tabname, is_img2img)
|
157 |
+
|
158 |
+
def ui(self, is_img2img):
|
159 |
+
"""this function should create gradio UI elements. See https://gradio.app/docs/#components
|
160 |
+
The return value should be an array of all components that are used in processing.
|
161 |
+
Values of those returned components will be passed to run() and process() functions.
|
162 |
+
"""
|
163 |
+
self.infotext_fields = []
|
164 |
+
self.paste_field_names = []
|
165 |
+
controls = ()
|
166 |
+
max_models = shared.opts.data.get("control_net_max_models_num", 1)
|
167 |
+
elem_id_tabname = ("img2img" if is_img2img else "txt2img") + "_controlnet"
|
168 |
+
with gr.Group(elem_id=elem_id_tabname):
|
169 |
+
with gr.Accordion(f"ControlNet {controlnet_version.version_flag}", open = False, elem_id="controlnet"):
|
170 |
+
if max_models > 1:
|
171 |
+
with gr.Tabs(elem_id=f"{elem_id_tabname}_tabs"):
|
172 |
+
for i in range(max_models):
|
173 |
+
with gr.Tab(f"ControlNet Unit {i}"):
|
174 |
+
controls += (self.uigroup(f"ControlNet-{i}", is_img2img, elem_id_tabname),)
|
175 |
+
else:
|
176 |
+
with gr.Column():
|
177 |
+
controls += (self.uigroup(f"ControlNet", is_img2img, elem_id_tabname),)
|
178 |
+
|
179 |
+
if shared.opts.data.get("control_net_sync_field_args", False):
|
180 |
+
for _, field_name in self.infotext_fields:
|
181 |
+
self.paste_field_names.append(field_name)
|
182 |
+
|
183 |
+
return controls
|
184 |
+
|
185 |
+
def clear_control_model_cache(self):
|
186 |
+
Script.model_cache.clear()
|
187 |
+
gc.collect()
|
188 |
+
devices.torch_gc()
|
189 |
+
|
190 |
+
def load_control_model(self, p, unet, model, lowvram):
|
191 |
+
if model in Script.model_cache:
|
192 |
+
print(f"Loading model from cache: {model}")
|
193 |
+
return Script.model_cache[model]
|
194 |
+
|
195 |
+
# Remove model from cache to clear space before building another model
|
196 |
+
if len(Script.model_cache) > 0 and len(Script.model_cache) >= shared.opts.data.get("control_net_model_cache_size", 2):
|
197 |
+
Script.model_cache.popitem(last=False)
|
198 |
+
gc.collect()
|
199 |
+
devices.torch_gc()
|
200 |
+
|
201 |
+
model_net = self.build_control_model(p, unet, model, lowvram)
|
202 |
+
|
203 |
+
if shared.opts.data.get("control_net_model_cache_size", 2) > 0:
|
204 |
+
Script.model_cache[model] = model_net
|
205 |
+
|
206 |
+
return model_net
|
207 |
+
|
208 |
+
def build_control_model(self, p, unet, model, lowvram):
|
209 |
+
if model is None or model == 'None':
|
210 |
+
raise RuntimeError(f"You have not selected any ControlNet Model.")
|
211 |
+
|
212 |
+
model_path = global_state.cn_models.get(model, None)
|
213 |
+
if model_path is None:
|
214 |
+
model = find_closest_lora_model_name(model)
|
215 |
+
model_path = global_state.cn_models.get(model, None)
|
216 |
+
|
217 |
+
if model_path is None:
|
218 |
+
raise RuntimeError(f"model not found: {model}")
|
219 |
+
|
220 |
+
# trim '"' at start/end
|
221 |
+
if model_path.startswith("\"") and model_path.endswith("\""):
|
222 |
+
model_path = model_path[1:-1]
|
223 |
+
|
224 |
+
if not os.path.exists(model_path):
|
225 |
+
raise ValueError(f"file not found: {model_path}")
|
226 |
+
|
227 |
+
print(f"Loading model: {model}")
|
228 |
+
state_dict = load_state_dict(model_path)
|
229 |
+
network_module = PlugableControlModel
|
230 |
+
network_config = shared.opts.data.get("control_net_model_config", global_state.default_conf)
|
231 |
+
if not os.path.isabs(network_config):
|
232 |
+
network_config = os.path.join(global_state.script_dir, network_config)
|
233 |
+
|
234 |
+
if any([k.startswith("body.") or k == 'style_embedding' for k, v in state_dict.items()]):
|
235 |
+
# adapter model
|
236 |
+
network_module = PlugableAdapter
|
237 |
+
network_config = shared.opts.data.get("control_net_model_adapter_config", global_state.default_conf_adapter)
|
238 |
+
if not os.path.isabs(network_config):
|
239 |
+
network_config = os.path.join(global_state.script_dir, network_config)
|
240 |
+
|
241 |
+
model_path = os.path.abspath(model_path)
|
242 |
+
model_stem = Path(model_path).stem
|
243 |
+
model_dir_name = os.path.dirname(model_path)
|
244 |
+
|
245 |
+
possible_config_filenames = [
|
246 |
+
os.path.join(model_dir_name, model_stem + ".yaml"),
|
247 |
+
os.path.join(global_state.script_dir, 'models', model_stem + ".yaml"),
|
248 |
+
os.path.join(model_dir_name, model_stem.replace('_fp16', '') + ".yaml"),
|
249 |
+
os.path.join(global_state.script_dir, 'models', model_stem.replace('_fp16', '') + ".yaml"),
|
250 |
+
os.path.join(model_dir_name, model_stem.replace('_diff', '') + ".yaml"),
|
251 |
+
os.path.join(global_state.script_dir, 'models', model_stem.replace('_diff', '') + ".yaml"),
|
252 |
+
os.path.join(model_dir_name, model_stem.replace('-fp16', '') + ".yaml"),
|
253 |
+
os.path.join(global_state.script_dir, 'models', model_stem.replace('-fp16', '') + ".yaml"),
|
254 |
+
os.path.join(model_dir_name, model_stem.replace('-diff', '') + ".yaml"),
|
255 |
+
os.path.join(global_state.script_dir, 'models', model_stem.replace('-diff', '') + ".yaml")
|
256 |
+
]
|
257 |
+
|
258 |
+
override_config = possible_config_filenames[0]
|
259 |
+
|
260 |
+
for possible_config_filename in possible_config_filenames:
|
261 |
+
if os.path.exists(possible_config_filename):
|
262 |
+
override_config = possible_config_filename
|
263 |
+
break
|
264 |
+
|
265 |
+
if 'v11' in model_stem.lower() or 'shuffle' in model_stem.lower():
|
266 |
+
assert os.path.exists(override_config), f'Error: The model config {override_config} is missing. ControlNet 1.1 must have configs.'
|
267 |
+
|
268 |
+
if os.path.exists(override_config):
|
269 |
+
network_config = override_config
|
270 |
+
else:
|
271 |
+
print(f'ERROR: ControlNet cannot find model config [{override_config}] \n'
|
272 |
+
f'ERROR: ControlNet will use a WRONG config [{network_config}] to load your model. \n'
|
273 |
+
f'ERROR: The WRONG config may not match your model. The generated results can be bad. \n'
|
274 |
+
f'ERROR: You are using a ControlNet model [{model_stem}] without correct YAML config file. \n'
|
275 |
+
f'ERROR: The performance of this model may be worse than your expectation. \n'
|
276 |
+
f'ERROR: If this model cannot get good results, the reason is that you do not have a YAML file for the model. \n'
|
277 |
+
f'Solution: Please download YAML file, or ask your model provider to provide [{override_config}] for you to download.\n'
|
278 |
+
f'Hint: You can take a look at [{os.path.join(global_state.script_dir, "models")}] to find many existing YAML files.\n')
|
279 |
+
|
280 |
+
print(f"Loading config: {network_config}")
|
281 |
+
network = network_module(
|
282 |
+
state_dict=state_dict,
|
283 |
+
config_path=network_config,
|
284 |
+
lowvram=lowvram,
|
285 |
+
base_model=unet,
|
286 |
+
)
|
287 |
+
network.to(p.sd_model.device, dtype=p.sd_model.dtype)
|
288 |
+
print(f"ControlNet model {model} loaded.")
|
289 |
+
return network
|
290 |
+
|
291 |
+
@staticmethod
|
292 |
+
def get_remote_call(p, attribute, default=None, idx=0, strict=False, force=False):
|
293 |
+
if not force and not shared.opts.data.get("control_net_allow_script_control", False):
|
294 |
+
return default
|
295 |
+
|
296 |
+
def get_element(obj, strict=False):
|
297 |
+
if not isinstance(obj, list):
|
298 |
+
return obj if not strict or idx == 0 else None
|
299 |
+
elif idx < len(obj):
|
300 |
+
return obj[idx]
|
301 |
+
else:
|
302 |
+
return None
|
303 |
+
|
304 |
+
attribute_value = get_element(getattr(p, attribute, None), strict)
|
305 |
+
default_value = get_element(default)
|
306 |
+
return attribute_value if attribute_value is not None else default_value
|
307 |
+
|
308 |
+
def parse_remote_call(self, p, unit: external_code.ControlNetUnit, idx):
|
309 |
+
selector = self.get_remote_call
|
310 |
+
|
311 |
+
unit.enabled = selector(p, "control_net_enabled", unit.enabled, idx, strict=True)
|
312 |
+
unit.module = selector(p, "control_net_module", unit.module, idx)
|
313 |
+
unit.model = selector(p, "control_net_model", unit.model, idx)
|
314 |
+
unit.weight = selector(p, "control_net_weight", unit.weight, idx)
|
315 |
+
unit.image = selector(p, "control_net_image", unit.image, idx)
|
316 |
+
unit.resize_mode = selector(p, "control_net_resize_mode", unit.resize_mode, idx)
|
317 |
+
unit.low_vram = selector(p, "control_net_lowvram", unit.low_vram, idx)
|
318 |
+
unit.processor_res = selector(p, "control_net_pres", unit.processor_res, idx)
|
319 |
+
unit.threshold_a = selector(p, "control_net_pthr_a", unit.threshold_a, idx)
|
320 |
+
unit.threshold_b = selector(p, "control_net_pthr_b", unit.threshold_b, idx)
|
321 |
+
unit.guidance_start = selector(p, "control_net_guidance_start", unit.guidance_start, idx)
|
322 |
+
unit.guidance_end = selector(p, "control_net_guidance_end", unit.guidance_end, idx)
|
323 |
+
unit.guidance_end = selector(p, "control_net_guidance_strength", unit.guidance_end, idx)
|
324 |
+
unit.control_mode = selector(p, "control_net_control_mode", unit.control_mode, idx)
|
325 |
+
unit.pixel_perfect = selector(p, "control_net_pixel_perfect", unit.pixel_perfect, idx)
|
326 |
+
|
327 |
+
return unit
|
328 |
+
|
329 |
+
def detectmap_proc(self, detected_map, module, resize_mode, h, w):
|
330 |
+
|
331 |
+
if 'inpaint' in module:
|
332 |
+
detected_map = detected_map.astype(np.float32)
|
333 |
+
else:
|
334 |
+
detected_map = HWC3(detected_map)
|
335 |
+
|
336 |
+
def safe_numpy(x):
|
337 |
+
# A very safe method to make sure that Apple/Mac works
|
338 |
+
y = x
|
339 |
+
|
340 |
+
# below is very boring but do not change these. If you change these Apple or Mac may fail.
|
341 |
+
y = y.copy()
|
342 |
+
y = np.ascontiguousarray(y)
|
343 |
+
y = y.copy()
|
344 |
+
return y
|
345 |
+
|
346 |
+
def get_pytorch_control(x):
|
347 |
+
# A very safe method to make sure that Apple/Mac works
|
348 |
+
y = x
|
349 |
+
|
350 |
+
# below is very boring but do not change these. If you change these Apple or Mac may fail.
|
351 |
+
y = torch.from_numpy(y)
|
352 |
+
y = y.float() / 255.0
|
353 |
+
y = rearrange(y, 'h w c -> 1 c h w')
|
354 |
+
y = y.clone()
|
355 |
+
y = y.to(devices.get_device_for("controlnet"))
|
356 |
+
y = y.clone()
|
357 |
+
return y
|
358 |
+
|
359 |
+
def high_quality_resize(x, size):
|
360 |
+
# Written by lvmin
|
361 |
+
# Super high-quality control map up-scaling, considering binary, seg, and one-pixel edges
|
362 |
+
|
363 |
+
inpaint_mask = None
|
364 |
+
if x.ndim == 3 and x.shape[2] == 4:
|
365 |
+
inpaint_mask = x[:, :, 3]
|
366 |
+
x = x[:, :, 0:3]
|
367 |
+
|
368 |
+
new_size_is_smaller = (size[0] * size[1]) < (x.shape[0] * x.shape[1])
|
369 |
+
new_size_is_bigger = (size[0] * size[1]) > (x.shape[0] * x.shape[1])
|
370 |
+
unique_color_count = np.unique(x.reshape(-1, x.shape[2]), axis=0).shape[0]
|
371 |
+
is_one_pixel_edge = False
|
372 |
+
is_binary = False
|
373 |
+
if unique_color_count == 2:
|
374 |
+
is_binary = np.min(x) < 16 and np.max(x) > 240
|
375 |
+
if is_binary:
|
376 |
+
xc = x
|
377 |
+
xc = cv2.erode(xc, np.ones(shape=(3, 3), dtype=np.uint8), iterations=1)
|
378 |
+
xc = cv2.dilate(xc, np.ones(shape=(3, 3), dtype=np.uint8), iterations=1)
|
379 |
+
one_pixel_edge_count = np.where(xc < x)[0].shape[0]
|
380 |
+
all_edge_count = np.where(x > 127)[0].shape[0]
|
381 |
+
is_one_pixel_edge = one_pixel_edge_count * 2 > all_edge_count
|
382 |
+
|
383 |
+
if 2 < unique_color_count < 200:
|
384 |
+
interpolation = cv2.INTER_NEAREST
|
385 |
+
elif new_size_is_smaller:
|
386 |
+
interpolation = cv2.INTER_AREA
|
387 |
+
else:
|
388 |
+
interpolation = cv2.INTER_CUBIC # Must be CUBIC because we now use nms. NEVER CHANGE THIS
|
389 |
+
|
390 |
+
y = cv2.resize(x, size, interpolation=interpolation)
|
391 |
+
if inpaint_mask is not None:
|
392 |
+
inpaint_mask = cv2.resize(inpaint_mask, size, interpolation=interpolation)
|
393 |
+
|
394 |
+
if is_binary:
|
395 |
+
y = np.mean(y.astype(np.float32), axis=2).clip(0, 255).astype(np.uint8)
|
396 |
+
if is_one_pixel_edge:
|
397 |
+
y = nake_nms(y)
|
398 |
+
_, y = cv2.threshold(y, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
399 |
+
y = lvmin_thin(y, prunings=new_size_is_bigger)
|
400 |
+
else:
|
401 |
+
_, y = cv2.threshold(y, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
|
402 |
+
y = np.stack([y] * 3, axis=2)
|
403 |
+
|
404 |
+
if inpaint_mask is not None:
|
405 |
+
inpaint_mask = (inpaint_mask > 127).astype(np.float32) * 255.0
|
406 |
+
inpaint_mask = inpaint_mask[:, :, None].clip(0, 255).astype(np.uint8)
|
407 |
+
y = np.concatenate([y, inpaint_mask], axis=2)
|
408 |
+
|
409 |
+
return y
|
410 |
+
|
411 |
+
if resize_mode == external_code.ResizeMode.RESIZE:
|
412 |
+
detected_map = high_quality_resize(detected_map, (w, h))
|
413 |
+
detected_map = safe_numpy(detected_map)
|
414 |
+
return get_pytorch_control(detected_map), detected_map
|
415 |
+
|
416 |
+
old_h, old_w, _ = detected_map.shape
|
417 |
+
old_w = float(old_w)
|
418 |
+
old_h = float(old_h)
|
419 |
+
k0 = float(h) / old_h
|
420 |
+
k1 = float(w) / old_w
|
421 |
+
|
422 |
+
safeint = lambda x: int(np.round(x))
|
423 |
+
|
424 |
+
if resize_mode == external_code.ResizeMode.OUTER_FIT:
|
425 |
+
k = min(k0, k1)
|
426 |
+
borders = np.concatenate([detected_map[0, :, :], detected_map[-1, :, :], detected_map[:, 0, :], detected_map[:, -1, :]], axis=0)
|
427 |
+
high_quality_border_color = np.median(borders, axis=0).astype(detected_map.dtype)
|
428 |
+
if len(high_quality_border_color) == 4:
|
429 |
+
# Inpaint hijack
|
430 |
+
high_quality_border_color[3] = 255
|
431 |
+
high_quality_background = np.tile(high_quality_border_color[None, None], [h, w, 1])
|
432 |
+
detected_map = high_quality_resize(detected_map, (safeint(old_w * k), safeint(old_h * k)))
|
433 |
+
new_h, new_w, _ = detected_map.shape
|
434 |
+
pad_h = max(0, (h - new_h) // 2)
|
435 |
+
pad_w = max(0, (w - new_w) // 2)
|
436 |
+
high_quality_background[pad_h:pad_h + new_h, pad_w:pad_w + new_w] = detected_map
|
437 |
+
detected_map = high_quality_background
|
438 |
+
detected_map = safe_numpy(detected_map)
|
439 |
+
return get_pytorch_control(detected_map), detected_map
|
440 |
+
else:
|
441 |
+
k = max(k0, k1)
|
442 |
+
detected_map = high_quality_resize(detected_map, (safeint(old_w * k), safeint(old_h * k)))
|
443 |
+
new_h, new_w, _ = detected_map.shape
|
444 |
+
pad_h = max(0, (new_h - h) // 2)
|
445 |
+
pad_w = max(0, (new_w - w) // 2)
|
446 |
+
detected_map = detected_map[pad_h:pad_h+h, pad_w:pad_w+w]
|
447 |
+
detected_map = safe_numpy(detected_map)
|
448 |
+
return get_pytorch_control(detected_map), detected_map
|
449 |
+
|
450 |
+
def get_enabled_units(self, p):
|
451 |
+
units = external_code.get_all_units_in_processing(p)
|
452 |
+
enabled_units = []
|
453 |
+
|
454 |
+
if len(units) == 0:
|
455 |
+
# fill a null group
|
456 |
+
remote_unit = self.parse_remote_call(p, self.get_default_ui_unit(), 0)
|
457 |
+
if remote_unit.enabled:
|
458 |
+
units.append(remote_unit)
|
459 |
+
|
460 |
+
for idx, unit in enumerate(units):
|
461 |
+
unit = self.parse_remote_call(p, unit, idx)
|
462 |
+
if not unit.enabled:
|
463 |
+
continue
|
464 |
+
|
465 |
+
enabled_units.append(copy(unit))
|
466 |
+
if len(units) != 1:
|
467 |
+
log_key = f"ControlNet {idx}"
|
468 |
+
else:
|
469 |
+
log_key = "ControlNet"
|
470 |
+
|
471 |
+
log_value = {
|
472 |
+
"preprocessor": unit.module,
|
473 |
+
"model": unit.model,
|
474 |
+
"weight": unit.weight,
|
475 |
+
"starting/ending": str((unit.guidance_start, unit.guidance_end)),
|
476 |
+
"resize mode": str(unit.resize_mode),
|
477 |
+
"pixel perfect": str(unit.pixel_perfect),
|
478 |
+
"control mode": str(unit.control_mode),
|
479 |
+
"preprocessor params": str((unit.processor_res, unit.threshold_a, unit.threshold_b)),
|
480 |
+
}
|
481 |
+
log_value = str(log_value).replace('\'', '').replace('{', '').replace('}', '')
|
482 |
+
|
483 |
+
p.extra_generation_params.update({log_key: log_value})
|
484 |
+
|
485 |
+
return enabled_units
|
486 |
+
|
487 |
+
def process(self, p, *args):
|
488 |
+
"""
|
489 |
+
This function is called before processing begins for AlwaysVisible scripts.
|
490 |
+
You can modify the processing object (p) here, inject hooks, etc.
|
491 |
+
args contains all values returned by components from ui()
|
492 |
+
"""
|
493 |
+
|
494 |
+
sd_ldm = p.sd_model
|
495 |
+
unet = sd_ldm.model.diffusion_model
|
496 |
+
|
497 |
+
if self.latest_network is not None:
|
498 |
+
# always restore (~0.05s)
|
499 |
+
self.latest_network.restore(unet)
|
500 |
+
|
501 |
+
if not batch_hijack.instance.is_batch:
|
502 |
+
self.enabled_units = self.get_enabled_units(p)
|
503 |
+
|
504 |
+
if len(self.enabled_units) == 0:
|
505 |
+
self.latest_network = None
|
506 |
+
return
|
507 |
+
|
508 |
+
detected_maps = []
|
509 |
+
forward_params = []
|
510 |
+
post_processors = []
|
511 |
+
hook_lowvram = False
|
512 |
+
|
513 |
+
# cache stuff
|
514 |
+
if self.latest_model_hash != p.sd_model.sd_model_hash:
|
515 |
+
self.clear_control_model_cache()
|
516 |
+
|
517 |
+
# unload unused preproc
|
518 |
+
module_list = [unit.module for unit in self.enabled_units]
|
519 |
+
for key in self.unloadable:
|
520 |
+
if key not in module_list:
|
521 |
+
self.unloadable.get(key, lambda:None)()
|
522 |
+
|
523 |
+
self.latest_model_hash = p.sd_model.sd_model_hash
|
524 |
+
for idx, unit in enumerate(self.enabled_units):
|
525 |
+
unit.module = global_state.get_module_basename(unit.module)
|
526 |
+
p_input_image = self.get_remote_call(p, "control_net_input_image", None, idx)
|
527 |
+
image = image_dict_from_any(unit.image)
|
528 |
+
if image is not None:
|
529 |
+
while len(image['mask'].shape) < 3:
|
530 |
+
image['mask'] = image['mask'][..., np.newaxis]
|
531 |
+
|
532 |
+
resize_mode = external_code.resize_mode_from_value(unit.resize_mode)
|
533 |
+
control_mode = external_code.control_mode_from_value(unit.control_mode)
|
534 |
+
|
535 |
+
if unit.low_vram:
|
536 |
+
hook_lowvram = True
|
537 |
+
|
538 |
+
if unit.module in model_free_preprocessors:
|
539 |
+
model_net = None
|
540 |
+
else:
|
541 |
+
model_net = self.load_control_model(p, unet, unit.model, unit.low_vram)
|
542 |
+
model_net.reset()
|
543 |
+
|
544 |
+
if batch_hijack.instance.is_batch and getattr(p, "image_control", None) is not None:
|
545 |
+
input_image = HWC3(np.asarray(p.image_control))
|
546 |
+
elif p_input_image is not None:
|
547 |
+
if isinstance(p_input_image, dict) and "mask" in p_input_image and "image" in p_input_image:
|
548 |
+
color = HWC3(np.asarray(p_input_image['image']))
|
549 |
+
alpha = np.asarray(p_input_image['mask'])[..., None]
|
550 |
+
input_image = np.concatenate([color, alpha], axis=2)
|
551 |
+
else:
|
552 |
+
input_image = HWC3(np.asarray(p_input_image))
|
553 |
+
elif image is not None:
|
554 |
+
# Need to check the image for API compatibility
|
555 |
+
if isinstance(image['image'], str):
|
556 |
+
from modules.api.api import decode_base64_to_image
|
557 |
+
input_image = HWC3(np.asarray(decode_base64_to_image(image['image'])))
|
558 |
+
else:
|
559 |
+
input_image = HWC3(image['image'])
|
560 |
+
|
561 |
+
have_mask = 'mask' in image and not ((image['mask'][:, :, 0] == 0).all() or (image['mask'][:, :, 0] == 255).all())
|
562 |
+
|
563 |
+
if 'inpaint' in unit.module:
|
564 |
+
print("using inpaint as input")
|
565 |
+
color = HWC3(image['image'])
|
566 |
+
if have_mask:
|
567 |
+
alpha = image['mask'][:, :, 0:1]
|
568 |
+
else:
|
569 |
+
alpha = np.zeros_like(color)[:, :, 0:1]
|
570 |
+
input_image = np.concatenate([color, alpha], axis=2)
|
571 |
+
else:
|
572 |
+
if have_mask:
|
573 |
+
print("using mask as input")
|
574 |
+
input_image = HWC3(image['mask'][:, :, 0])
|
575 |
+
unit.module = 'none' # Always use black bg and white line
|
576 |
+
else:
|
577 |
+
# use img2img init_image as default
|
578 |
+
input_image = getattr(p, "init_images", [None])[0]
|
579 |
+
if input_image is None:
|
580 |
+
if batch_hijack.instance.is_batch:
|
581 |
+
shared.state.interrupted = True
|
582 |
+
raise ValueError('controlnet is enabled but no input image is given')
|
583 |
+
|
584 |
+
input_image = HWC3(np.asarray(input_image))
|
585 |
+
a1111_i2i_resize_mode = getattr(p, "resize_mode", None)
|
586 |
+
if a1111_i2i_resize_mode is not None:
|
587 |
+
if a1111_i2i_resize_mode == 0:
|
588 |
+
resize_mode = external_code.ResizeMode.RESIZE
|
589 |
+
elif a1111_i2i_resize_mode == 1:
|
590 |
+
resize_mode = external_code.ResizeMode.INNER_FIT
|
591 |
+
elif a1111_i2i_resize_mode == 2:
|
592 |
+
resize_mode = external_code.ResizeMode.OUTER_FIT
|
593 |
+
|
594 |
+
has_mask = False
|
595 |
+
if input_image.ndim == 3:
|
596 |
+
if input_image.shape[2] == 4:
|
597 |
+
if np.max(input_image[:, :, 3]) > 127:
|
598 |
+
has_mask = True
|
599 |
+
|
600 |
+
a1111_mask = getattr(p, "image_mask", None)
|
601 |
+
if 'inpaint' in unit.module and not has_mask and a1111_mask is not None:
|
602 |
+
a1111_mask = a1111_mask.convert('L')
|
603 |
+
if getattr(p, "inpainting_mask_invert", False):
|
604 |
+
a1111_mask = ImageOps.invert(a1111_mask)
|
605 |
+
if getattr(p, "mask_blur", 0) > 0:
|
606 |
+
a1111_mask = a1111_mask.filter(ImageFilter.GaussianBlur(p.mask_blur))
|
607 |
+
a1111_mask = np.asarray(a1111_mask)
|
608 |
+
if a1111_mask.ndim == 2:
|
609 |
+
if a1111_mask.shape[0] == input_image.shape[0]:
|
610 |
+
if a1111_mask.shape[1] == input_image.shape[1]:
|
611 |
+
input_image = np.concatenate([input_image[:, :, 0:3], a1111_mask[:, :, None]], axis=2)
|
612 |
+
input_image = np.ascontiguousarray(input_image.copy()).copy()
|
613 |
+
a1111_i2i_resize_mode = getattr(p, "resize_mode", None)
|
614 |
+
if a1111_i2i_resize_mode is not None:
|
615 |
+
if a1111_i2i_resize_mode == 0:
|
616 |
+
resize_mode = external_code.ResizeMode.RESIZE
|
617 |
+
elif a1111_i2i_resize_mode == 1:
|
618 |
+
resize_mode = external_code.ResizeMode.INNER_FIT
|
619 |
+
elif a1111_i2i_resize_mode == 2:
|
620 |
+
resize_mode = external_code.ResizeMode.OUTER_FIT
|
621 |
+
|
622 |
+
if 'reference' not in unit.module and issubclass(type(p), StableDiffusionProcessingImg2Img) \
|
623 |
+
and p.inpaint_full_res and p.image_mask is not None:
|
624 |
+
|
625 |
+
input_image = [input_image[:, :, i] for i in range(input_image.shape[2])]
|
626 |
+
input_image = [Image.fromarray(x) for x in input_image]
|
627 |
+
|
628 |
+
mask = p.image_mask.convert('L')
|
629 |
+
if p.inpainting_mask_invert:
|
630 |
+
mask = ImageOps.invert(mask)
|
631 |
+
if p.mask_blur > 0:
|
632 |
+
mask = mask.filter(ImageFilter.GaussianBlur(p.mask_blur))
|
633 |
+
|
634 |
+
crop_region = masking.get_crop_region(np.array(mask), p.inpaint_full_res_padding)
|
635 |
+
crop_region = masking.expand_crop_region(crop_region, p.width, p.height, mask.width, mask.height)
|
636 |
+
|
637 |
+
if resize_mode == external_code.ResizeMode.INNER_FIT:
|
638 |
+
input_image = [images.resize_image(1, i, mask.width, mask.height) for i in input_image]
|
639 |
+
elif resize_mode == external_code.ResizeMode.OUTER_FIT:
|
640 |
+
input_image = [images.resize_image(2, i, mask.width, mask.height) for i in input_image]
|
641 |
+
else:
|
642 |
+
input_image = [images.resize_image(0, i, mask.width, mask.height) for i in input_image]
|
643 |
+
|
644 |
+
input_image = [x.crop(crop_region) for x in input_image]
|
645 |
+
input_image = [images.resize_image(2, x, p.width, p.height) for x in input_image]
|
646 |
+
|
647 |
+
input_image = [np.asarray(x)[:, :, 0] for x in input_image]
|
648 |
+
input_image = np.stack(input_image, axis=2)
|
649 |
+
|
650 |
+
if 'inpaint' in unit.module and issubclass(type(p), StableDiffusionProcessingImg2Img) \
|
651 |
+
and p.inpainting_fill and p.image_mask is not None:
|
652 |
+
print('A1111 inpaint and ControlNet inpaint duplicated. ControlNet support enabled.')
|
653 |
+
unit.module = 'inpaint'
|
654 |
+
|
655 |
+
try:
|
656 |
+
tmp_seed = int(p.all_seeds[0] if p.seed == -1 else max(int(p.seed), 0))
|
657 |
+
tmp_subseed = int(p.all_seeds[0] if p.subseed == -1 else max(int(p.subseed), 0))
|
658 |
+
np.random.seed((tmp_seed + tmp_subseed) & 0xFFFFFFFF)
|
659 |
+
except Exception as e:
|
660 |
+
print(e)
|
661 |
+
print('Warning: Failed to use consistent random seed.')
|
662 |
+
|
663 |
+
# safe numpy
|
664 |
+
input_image = np.ascontiguousarray(input_image.copy()).copy()
|
665 |
+
|
666 |
+
print(f"Loading preprocessor: {unit.module}")
|
667 |
+
preprocessor = self.preprocessor[unit.module]
|
668 |
+
h, w, bsz = p.height, p.width, p.batch_size
|
669 |
+
|
670 |
+
h = (h // 8) * 8
|
671 |
+
w = (w // 8) * 8
|
672 |
+
|
673 |
+
preprocessor_resolution = unit.processor_res
|
674 |
+
if unit.pixel_perfect:
|
675 |
+
raw_H, raw_W, _ = input_image.shape
|
676 |
+
target_H, target_W = h, w
|
677 |
+
|
678 |
+
k0 = float(target_H) / float(raw_H)
|
679 |
+
k1 = float(target_W) / float(raw_W)
|
680 |
+
|
681 |
+
if resize_mode == external_code.ResizeMode.OUTER_FIT:
|
682 |
+
estimation = min(k0, k1) * float(min(raw_H, raw_W))
|
683 |
+
else:
|
684 |
+
estimation = max(k0, k1) * float(min(raw_H, raw_W))
|
685 |
+
|
686 |
+
preprocessor_resolution = int(np.round(estimation))
|
687 |
+
|
688 |
+
print(f'Pixel Perfect Mode Enabled.')
|
689 |
+
print(f'resize_mode = {str(resize_mode)}')
|
690 |
+
print(f'raw_H = {raw_H}')
|
691 |
+
print(f'raw_W = {raw_W}')
|
692 |
+
print(f'target_H = {target_H}')
|
693 |
+
print(f'target_W = {target_W}')
|
694 |
+
print(f'estimation = {estimation}')
|
695 |
+
|
696 |
+
print(f'preprocessor resolution = {preprocessor_resolution}')
|
697 |
+
detected_map, is_image = preprocessor(input_image, res=preprocessor_resolution, thr_a=unit.threshold_a, thr_b=unit.threshold_b)
|
698 |
+
|
699 |
+
if unit.module == "none" and "style" in unit.model:
|
700 |
+
detected_map_bytes = detected_map[:,:,0].tobytes()
|
701 |
+
detected_map = np.ndarray((round(input_image.shape[0]/4),input_image.shape[1]),dtype="float32",buffer=detected_map_bytes)
|
702 |
+
detected_map = torch.Tensor(detected_map).to(devices.get_device_for("controlnet"))
|
703 |
+
is_image = False
|
704 |
+
|
705 |
+
if isinstance(p, StableDiffusionProcessingTxt2Img) and p.enable_hr:
|
706 |
+
if p.hr_resize_x == 0 and p.hr_resize_y == 0:
|
707 |
+
hr_y = int(p.height * p.hr_scale)
|
708 |
+
hr_x = int(p.width * p.hr_scale)
|
709 |
+
else:
|
710 |
+
hr_y, hr_x = p.hr_resize_y, p.hr_resize_x
|
711 |
+
|
712 |
+
hr_y = (hr_y // 8) * 8
|
713 |
+
hr_x = (hr_x // 8) * 8
|
714 |
+
|
715 |
+
if is_image:
|
716 |
+
hr_control, hr_detected_map = self.detectmap_proc(detected_map, unit.module, resize_mode, hr_y, hr_x)
|
717 |
+
detected_maps.append((hr_detected_map, unit.module))
|
718 |
+
else:
|
719 |
+
hr_control = detected_map
|
720 |
+
else:
|
721 |
+
hr_control = None
|
722 |
+
|
723 |
+
if is_image:
|
724 |
+
control, detected_map = self.detectmap_proc(detected_map, unit.module, resize_mode, h, w)
|
725 |
+
detected_maps.append((detected_map, unit.module))
|
726 |
+
else:
|
727 |
+
control = detected_map
|
728 |
+
if unit.module == 'clip_vision':
|
729 |
+
detected_maps.append((processor.clip_vision_visualization(detected_map), unit.module))
|
730 |
+
|
731 |
+
control_model_type = ControlModelType.ControlNet
|
732 |
+
|
733 |
+
if isinstance(model_net, PlugableAdapter):
|
734 |
+
control_model_type = ControlModelType.T2I_Adapter
|
735 |
+
|
736 |
+
if getattr(model_net, "target", None) == "scripts.adapter.StyleAdapter":
|
737 |
+
control_model_type = ControlModelType.T2I_StyleAdapter
|
738 |
+
|
739 |
+
if 'reference' in unit.module:
|
740 |
+
control_model_type = ControlModelType.AttentionInjection
|
741 |
+
|
742 |
+
global_average_pooling = False
|
743 |
+
|
744 |
+
if model_net is not None:
|
745 |
+
if model_net.config.model.params.get("global_average_pooling", False):
|
746 |
+
global_average_pooling = True
|
747 |
+
|
748 |
+
preprocessor_dict = dict(
|
749 |
+
name=unit.module,
|
750 |
+
preprocessor_resolution=preprocessor_resolution,
|
751 |
+
threshold_a=unit.threshold_a,
|
752 |
+
threshold_b=unit.threshold_b
|
753 |
+
)
|
754 |
+
|
755 |
+
forward_param = ControlParams(
|
756 |
+
control_model=model_net,
|
757 |
+
preprocessor=preprocessor_dict,
|
758 |
+
hint_cond=control,
|
759 |
+
weight=unit.weight,
|
760 |
+
guidance_stopped=False,
|
761 |
+
start_guidance_percent=unit.guidance_start,
|
762 |
+
stop_guidance_percent=unit.guidance_end,
|
763 |
+
advanced_weighting=None,
|
764 |
+
control_model_type=control_model_type,
|
765 |
+
global_average_pooling=global_average_pooling,
|
766 |
+
hr_hint_cond=hr_control,
|
767 |
+
soft_injection=control_mode != external_code.ControlMode.BALANCED,
|
768 |
+
cfg_injection=control_mode == external_code.ControlMode.CONTROL,
|
769 |
+
)
|
770 |
+
forward_params.append(forward_param)
|
771 |
+
|
772 |
+
if unit.module == 'inpaint_only':
|
773 |
+
|
774 |
+
final_inpaint_feed = hr_control if hr_control is not None else control
|
775 |
+
final_inpaint_feed = final_inpaint_feed.detach().cpu().numpy()
|
776 |
+
final_inpaint_feed = np.ascontiguousarray(final_inpaint_feed).copy()
|
777 |
+
final_inpaint_mask = final_inpaint_feed[0, 3, :, :].astype(np.float32)
|
778 |
+
final_inpaint_raw = final_inpaint_feed[0, :3].astype(np.float32)
|
779 |
+
sigma = 7
|
780 |
+
final_inpaint_mask = cv2.dilate(final_inpaint_mask, np.ones((sigma, sigma), dtype=np.uint8))
|
781 |
+
final_inpaint_mask = cv2.blur(final_inpaint_mask, (sigma, sigma))[None]
|
782 |
+
_, Hmask, Wmask = final_inpaint_mask.shape
|
783 |
+
final_inpaint_raw = torch.from_numpy(np.ascontiguousarray(final_inpaint_raw).copy())
|
784 |
+
final_inpaint_mask = torch.from_numpy(np.ascontiguousarray(final_inpaint_mask).copy())
|
785 |
+
|
786 |
+
def inpaint_only_post_processing(x):
|
787 |
+
_, H, W = x.shape
|
788 |
+
if Hmask != H or Wmask != W:
|
789 |
+
print('Error: ControlNet find post-processing resolution mismatch. This could be related to other extensions hacked processing.')
|
790 |
+
return x
|
791 |
+
r = final_inpaint_raw.to(x.dtype).to(x.device)
|
792 |
+
m = final_inpaint_mask.to(x.dtype).to(x.device)
|
793 |
+
return m * x + (1 - m) * r
|
794 |
+
|
795 |
+
post_processors.append(inpaint_only_post_processing)
|
796 |
+
|
797 |
+
del model_net
|
798 |
+
|
799 |
+
self.latest_network = UnetHook(lowvram=hook_lowvram)
|
800 |
+
self.latest_network.hook(model=unet, sd_ldm=sd_ldm, control_params=forward_params, process=p)
|
801 |
+
self.detected_map = detected_maps
|
802 |
+
self.post_processors = post_processors
|
803 |
+
|
804 |
+
def postprocess_batch(self, p, *args, **kwargs):
|
805 |
+
images = kwargs.get('images', [])
|
806 |
+
for post_processor in self.post_processors:
|
807 |
+
for i in range(images.shape[0]):
|
808 |
+
images[i] = post_processor(images[i])
|
809 |
+
return
|
810 |
+
|
811 |
+
def postprocess(self, p, processed, *args):
|
812 |
+
processor_params_flag = (', '.join(getattr(processed, 'extra_generation_params', []))).lower()
|
813 |
+
|
814 |
+
if not batch_hijack.instance.is_batch:
|
815 |
+
self.enabled_units.clear()
|
816 |
+
|
817 |
+
if shared.opts.data.get("control_net_detectmap_autosaving", False) and self.latest_network is not None:
|
818 |
+
for detect_map, module in self.detected_map:
|
819 |
+
detectmap_dir = os.path.join(shared.opts.data.get("control_net_detectedmap_dir", ""), module)
|
820 |
+
if not os.path.isabs(detectmap_dir):
|
821 |
+
detectmap_dir = os.path.join(p.outpath_samples, detectmap_dir)
|
822 |
+
if module != "none":
|
823 |
+
os.makedirs(detectmap_dir, exist_ok=True)
|
824 |
+
img = Image.fromarray(np.ascontiguousarray(detect_map.clip(0, 255).astype(np.uint8)).copy())
|
825 |
+
save_image(img, detectmap_dir, module)
|
826 |
+
|
827 |
+
if self.latest_network is None:
|
828 |
+
return
|
829 |
+
|
830 |
+
if not batch_hijack.instance.is_batch:
|
831 |
+
if not shared.opts.data.get("control_net_no_detectmap", False):
|
832 |
+
if 'sd upscale' not in processor_params_flag:
|
833 |
+
if self.detected_map is not None:
|
834 |
+
for detect_map, module in self.detected_map:
|
835 |
+
if detect_map is None:
|
836 |
+
continue
|
837 |
+
detect_map = np.ascontiguousarray(detect_map.copy()).copy()
|
838 |
+
if detect_map.ndim == 3 and detect_map.shape[2] == 4:
|
839 |
+
inpaint_mask = detect_map[:, :, 3]
|
840 |
+
detect_map = detect_map[:, :, 0:3]
|
841 |
+
detect_map[inpaint_mask > 127] = 0
|
842 |
+
processed.images.extend([
|
843 |
+
Image.fromarray(
|
844 |
+
detect_map.clip(0, 255).astype(np.uint8)
|
845 |
+
)
|
846 |
+
])
|
847 |
+
|
848 |
+
self.input_image = None
|
849 |
+
self.latest_network.restore(p.sd_model.model.diffusion_model)
|
850 |
+
self.latest_network = None
|
851 |
+
self.detected_map.clear()
|
852 |
+
|
853 |
+
gc.collect()
|
854 |
+
devices.torch_gc()
|
855 |
+
|
856 |
+
def batch_tab_process(self, p, batches, *args, **kwargs):
|
857 |
+
self.enabled_units = self.get_enabled_units(p)
|
858 |
+
for unit_i, unit in enumerate(self.enabled_units):
|
859 |
+
unit.batch_images = iter([batch[unit_i] for batch in batches])
|
860 |
+
|
861 |
+
def batch_tab_process_each(self, p, *args, **kwargs):
|
862 |
+
for unit_i, unit in enumerate(self.enabled_units):
|
863 |
+
if getattr(unit, 'loopback', False) and batch_hijack.instance.batch_index > 0: continue
|
864 |
+
|
865 |
+
unit.image = next(unit.batch_images)
|
866 |
+
|
867 |
+
def batch_tab_postprocess_each(self, p, processed, *args, **kwargs):
|
868 |
+
for unit_i, unit in enumerate(self.enabled_units):
|
869 |
+
if getattr(unit, 'loopback', False):
|
870 |
+
output_images = getattr(processed, 'images', [])[processed.index_of_first_image:]
|
871 |
+
if output_images:
|
872 |
+
unit.image = np.array(output_images[0])
|
873 |
+
else:
|
874 |
+
print(f'Warning: No loopback image found for controlnet unit {unit_i}. Using control map from last batch iteration instead')
|
875 |
+
|
876 |
+
def batch_tab_postprocess(self, p, *args, **kwargs):
|
877 |
+
self.enabled_units.clear()
|
878 |
+
self.input_image = None
|
879 |
+
if self.latest_network is None: return
|
880 |
+
|
881 |
+
self.latest_network.restore(shared.sd_model.model.diffusion_model)
|
882 |
+
self.latest_network = None
|
883 |
+
self.detected_map.clear()
|
884 |
+
|
885 |
+
|
886 |
+
def on_ui_settings():
|
887 |
+
section = ('control_net', "ControlNet")
|
888 |
+
shared.opts.add_option("control_net_model_config", shared.OptionInfo(
|
889 |
+
global_state.default_conf, "Config file for Control Net models", section=section))
|
890 |
+
shared.opts.add_option("control_net_model_adapter_config", shared.OptionInfo(
|
891 |
+
global_state.default_conf_adapter, "Config file for Adapter models", section=section))
|
892 |
+
shared.opts.add_option("control_net_detectedmap_dir", shared.OptionInfo(
|
893 |
+
global_state.default_detectedmap_dir, "Directory for detected maps auto saving", section=section))
|
894 |
+
shared.opts.add_option("control_net_models_path", shared.OptionInfo(
|
895 |
+
"", "Extra path to scan for ControlNet models (e.g. training output directory)", section=section))
|
896 |
+
shared.opts.add_option("control_net_modules_path", shared.OptionInfo(
|
897 |
+
"", "Path to directory containing annotator model directories (requires restart, overrides corresponding command line flag)", section=section))
|
898 |
+
shared.opts.add_option("control_net_max_models_num", shared.OptionInfo(
|
899 |
+
1, "Multi ControlNet: Max models amount (requires restart)", gr.Slider, {"minimum": 1, "maximum": 10, "step": 1}, section=section))
|
900 |
+
shared.opts.add_option("control_net_model_cache_size", shared.OptionInfo(
|
901 |
+
1, "Model cache size (requires restart)", gr.Slider, {"minimum": 1, "maximum": 5, "step": 1}, section=section))
|
902 |
+
shared.opts.add_option("control_net_no_detectmap", shared.OptionInfo(
|
903 |
+
False, "Do not append detectmap to output", gr.Checkbox, {"interactive": True}, section=section))
|
904 |
+
shared.opts.add_option("control_net_detectmap_autosaving", shared.OptionInfo(
|
905 |
+
False, "Allow detectmap auto saving", gr.Checkbox, {"interactive": True}, section=section))
|
906 |
+
shared.opts.add_option("control_net_allow_script_control", shared.OptionInfo(
|
907 |
+
False, "Allow other script to control this extension", gr.Checkbox, {"interactive": True}, section=section))
|
908 |
+
shared.opts.add_option("control_net_sync_field_args", shared.OptionInfo(
|
909 |
+
False, "Passing ControlNet parameters with \"Send to img2img\"", gr.Checkbox, {"interactive": True}, section=section))
|
910 |
+
shared.opts.add_option("controlnet_show_batch_images_in_ui", shared.OptionInfo(
|
911 |
+
False, "Show batch images in gradio gallery output", gr.Checkbox, {"interactive": True}, section=section))
|
912 |
+
shared.opts.add_option("controlnet_increment_seed_during_batch", shared.OptionInfo(
|
913 |
+
False, "Increment seed after each controlnet batch iteration", gr.Checkbox, {"interactive": True}, section=section))
|
914 |
+
shared.opts.add_option("controlnet_disable_control_type", shared.OptionInfo(
|
915 |
+
False, "Disable control type selection", gr.Checkbox, {"interactive": True}, section=section))
|
916 |
+
|
917 |
+
|
918 |
+
batch_hijack.instance.do_hijack()
|
919 |
+
script_callbacks.on_ui_settings(on_ui_settings)
|
920 |
+
script_callbacks.on_after_component(ControlNetUiGroup.on_after_component)
|
extensions/microsoftexcel-controlnet/scripts/controlnet_version.py
ADDED
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
version_flag = 'v1.1.210'
|
2 |
+
print(f'ControlNet {version_flag}')
|
3 |
+
# A smart trick to know if user has updated as well as if user has restarted terminal.
|
4 |
+
# Note that in "controlnet.py" we do NOT use "importlib.reload" to reload this "controlnet_version.py"
|
5 |
+
# This means if user did not completely restart terminal, the "version_flag" will be the previous version.
|
6 |
+
# Then, if we get a screenshot from user, we will know that if that user has restarted the terminal.
|
7 |
+
# And we will also know what version the user is using so that bug track becomes easier.
|
extensions/microsoftexcel-controlnet/scripts/external_code.py
ADDED
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from enum import Enum
|
2 |
+
from typing import List, Any, Optional, Union, Tuple, Dict
|
3 |
+
import numpy as np
|
4 |
+
from modules import scripts, processing, shared
|
5 |
+
from scripts import global_state
|
6 |
+
from scripts.processor import preprocessor_sliders_config, model_free_preprocessors
|
7 |
+
|
8 |
+
from modules.api import api
|
9 |
+
|
10 |
+
|
11 |
+
def get_api_version() -> int:
|
12 |
+
return 2
|
13 |
+
|
14 |
+
|
15 |
+
class ControlMode(Enum):
|
16 |
+
"""
|
17 |
+
The improved guess mode.
|
18 |
+
"""
|
19 |
+
|
20 |
+
BALANCED = "Balanced"
|
21 |
+
PROMPT = "My prompt is more important"
|
22 |
+
CONTROL = "ControlNet is more important"
|
23 |
+
|
24 |
+
|
25 |
+
class ResizeMode(Enum):
|
26 |
+
"""
|
27 |
+
Resize modes for ControlNet input images.
|
28 |
+
"""
|
29 |
+
|
30 |
+
RESIZE = "Just Resize"
|
31 |
+
INNER_FIT = "Crop and Resize"
|
32 |
+
OUTER_FIT = "Resize and Fill"
|
33 |
+
|
34 |
+
|
35 |
+
resize_mode_aliases = {
|
36 |
+
'Inner Fit (Scale to Fit)': 'Crop and Resize',
|
37 |
+
'Outer Fit (Shrink to Fit)': 'Resize and Fill',
|
38 |
+
'Scale to Fit (Inner Fit)': 'Crop and Resize',
|
39 |
+
'Envelope (Outer Fit)': 'Resize and Fill',
|
40 |
+
}
|
41 |
+
|
42 |
+
|
43 |
+
def resize_mode_from_value(value: Union[str, int, ResizeMode]) -> ResizeMode:
|
44 |
+
if isinstance(value, str):
|
45 |
+
return ResizeMode(resize_mode_aliases.get(value, value))
|
46 |
+
elif isinstance(value, int):
|
47 |
+
return [e for e in ResizeMode][value]
|
48 |
+
else:
|
49 |
+
return value
|
50 |
+
|
51 |
+
|
52 |
+
def control_mode_from_value(value: Union[str, int, ControlMode]) -> ControlMode:
|
53 |
+
if isinstance(value, str):
|
54 |
+
return ControlMode(value)
|
55 |
+
elif isinstance(value, int):
|
56 |
+
return [e for e in ControlMode][value]
|
57 |
+
else:
|
58 |
+
return value
|
59 |
+
|
60 |
+
|
61 |
+
InputImage = Union[np.ndarray, str]
|
62 |
+
InputImage = Union[Dict[str, InputImage], Tuple[InputImage, InputImage], InputImage]
|
63 |
+
|
64 |
+
|
65 |
+
class ControlNetUnit:
|
66 |
+
"""
|
67 |
+
Represents an entire ControlNet processing unit.
|
68 |
+
"""
|
69 |
+
|
70 |
+
def __init__(
|
71 |
+
self,
|
72 |
+
enabled: bool=True,
|
73 |
+
module: Optional[str]=None,
|
74 |
+
model: Optional[str]=None,
|
75 |
+
weight: float=1.0,
|
76 |
+
image: Optional[InputImage]=None,
|
77 |
+
resize_mode: Union[ResizeMode, int, str] = ResizeMode.INNER_FIT,
|
78 |
+
low_vram: bool=False,
|
79 |
+
processor_res: int=512,
|
80 |
+
threshold_a: float=64,
|
81 |
+
threshold_b: float=64,
|
82 |
+
guidance_start: float=0.0,
|
83 |
+
guidance_end: float=1.0,
|
84 |
+
pixel_perfect: bool=False,
|
85 |
+
control_mode: Union[ControlMode, int, str] = ControlMode.BALANCED,
|
86 |
+
**_kwargs,
|
87 |
+
):
|
88 |
+
self.enabled = enabled
|
89 |
+
self.module = module
|
90 |
+
self.model = model
|
91 |
+
self.weight = weight
|
92 |
+
self.image = image
|
93 |
+
self.resize_mode = resize_mode
|
94 |
+
self.low_vram = low_vram
|
95 |
+
self.processor_res = processor_res
|
96 |
+
self.threshold_a = threshold_a
|
97 |
+
self.threshold_b = threshold_b
|
98 |
+
self.guidance_start = guidance_start
|
99 |
+
self.guidance_end = guidance_end
|
100 |
+
self.pixel_perfect = pixel_perfect
|
101 |
+
self.control_mode = control_mode
|
102 |
+
|
103 |
+
def __eq__(self, other):
|
104 |
+
if not isinstance(other, ControlNetUnit):
|
105 |
+
return False
|
106 |
+
|
107 |
+
return vars(self) == vars(other)
|
108 |
+
|
109 |
+
|
110 |
+
def to_base64_nparray(encoding: str):
|
111 |
+
"""
|
112 |
+
Convert a base64 image into the image type the extension uses
|
113 |
+
"""
|
114 |
+
|
115 |
+
return np.array(api.decode_base64_to_image(encoding)).astype('uint8')
|
116 |
+
|
117 |
+
|
118 |
+
def get_all_units_in_processing(p: processing.StableDiffusionProcessing) -> List[ControlNetUnit]:
|
119 |
+
"""
|
120 |
+
Fetch ControlNet processing units from a StableDiffusionProcessing.
|
121 |
+
"""
|
122 |
+
|
123 |
+
return get_all_units(p.scripts, p.script_args)
|
124 |
+
|
125 |
+
|
126 |
+
def get_all_units(script_runner: scripts.ScriptRunner, script_args: List[Any]) -> List[ControlNetUnit]:
|
127 |
+
"""
|
128 |
+
Fetch ControlNet processing units from an existing script runner.
|
129 |
+
Use this function to fetch units from the list of all scripts arguments.
|
130 |
+
"""
|
131 |
+
|
132 |
+
cn_script = find_cn_script(script_runner)
|
133 |
+
if cn_script:
|
134 |
+
return get_all_units_from(script_args[cn_script.args_from:cn_script.args_to])
|
135 |
+
|
136 |
+
return []
|
137 |
+
|
138 |
+
|
139 |
+
def get_all_units_from(script_args: List[Any]) -> List[ControlNetUnit]:
|
140 |
+
"""
|
141 |
+
Fetch ControlNet processing units from ControlNet script arguments.
|
142 |
+
Use `external_code.get_all_units` to fetch units from the list of all scripts arguments.
|
143 |
+
"""
|
144 |
+
|
145 |
+
units = []
|
146 |
+
i = 0
|
147 |
+
while i < len(script_args):
|
148 |
+
if script_args[i] is not None:
|
149 |
+
units.append(to_processing_unit(script_args[i]))
|
150 |
+
i += 1
|
151 |
+
|
152 |
+
return units
|
153 |
+
|
154 |
+
|
155 |
+
def get_single_unit_from(script_args: List[Any], index: int=0) -> Optional[ControlNetUnit]:
|
156 |
+
"""
|
157 |
+
Fetch a single ControlNet processing unit from ControlNet script arguments.
|
158 |
+
The list must not contain script positional arguments. It must only contain processing units.
|
159 |
+
"""
|
160 |
+
|
161 |
+
i = 0
|
162 |
+
while i < len(script_args) and index >= 0:
|
163 |
+
if index == 0 and script_args[i] is not None:
|
164 |
+
return to_processing_unit(script_args[i])
|
165 |
+
i += 1
|
166 |
+
|
167 |
+
index -= 1
|
168 |
+
|
169 |
+
return None
|
170 |
+
|
171 |
+
def get_max_models_num():
|
172 |
+
"""
|
173 |
+
Fetch the maximum number of allowed ControlNet models.
|
174 |
+
"""
|
175 |
+
|
176 |
+
max_models_num = shared.opts.data.get("control_net_max_models_num", 1)
|
177 |
+
return max_models_num
|
178 |
+
|
179 |
+
def to_processing_unit(unit: Union[Dict[str, Any], ControlNetUnit]) -> ControlNetUnit:
|
180 |
+
"""
|
181 |
+
Convert different types to processing unit.
|
182 |
+
If `unit` is a dict, alternative keys are supported. See `ext_compat_keys` in implementation for details.
|
183 |
+
"""
|
184 |
+
|
185 |
+
ext_compat_keys = {
|
186 |
+
'guessmode': 'guess_mode',
|
187 |
+
'guidance': 'guidance_end',
|
188 |
+
'lowvram': 'low_vram',
|
189 |
+
'input_image': 'image'
|
190 |
+
}
|
191 |
+
|
192 |
+
if isinstance(unit, dict):
|
193 |
+
unit = {ext_compat_keys.get(k, k): v for k, v in unit.items()}
|
194 |
+
|
195 |
+
mask = None
|
196 |
+
if 'mask' in unit:
|
197 |
+
mask = unit['mask']
|
198 |
+
del unit['mask']
|
199 |
+
|
200 |
+
if 'image' in unit and not isinstance(unit['image'], dict):
|
201 |
+
unit['image'] = {'image': unit['image'], 'mask': mask} if mask is not None else unit['image'] if unit['image'] else None
|
202 |
+
|
203 |
+
if 'guess_mode' in unit:
|
204 |
+
print('Guess Mode is removed since 1.1.136. Please use Control Mode instead.')
|
205 |
+
|
206 |
+
unit = ControlNetUnit(**unit)
|
207 |
+
|
208 |
+
# temporary, check #602
|
209 |
+
#assert isinstance(unit, ControlNetUnit), f'bad argument to controlnet extension: {unit}\nexpected Union[dict[str, Any], ControlNetUnit]'
|
210 |
+
return unit
|
211 |
+
|
212 |
+
|
213 |
+
def update_cn_script_in_processing(
|
214 |
+
p: processing.StableDiffusionProcessing,
|
215 |
+
cn_units: List[ControlNetUnit],
|
216 |
+
**_kwargs, # for backwards compatibility
|
217 |
+
):
|
218 |
+
"""
|
219 |
+
Update the arguments of the ControlNet script in `p.script_args` in place, reading from `cn_units`.
|
220 |
+
`cn_units` and its elements are not modified. You can call this function repeatedly, as many times as you want.
|
221 |
+
|
222 |
+
Does not update `p.script_args` if any of the folling is true:
|
223 |
+
- ControlNet is not present in `p.scripts`
|
224 |
+
- `p.script_args` is not filled with script arguments for scripts that are processed before ControlNet
|
225 |
+
"""
|
226 |
+
|
227 |
+
cn_units_type = type(cn_units) if type(cn_units) in (list, tuple) else list
|
228 |
+
script_args = list(p.script_args)
|
229 |
+
update_cn_script_in_place(p.scripts, script_args, cn_units)
|
230 |
+
p.script_args = cn_units_type(script_args)
|
231 |
+
|
232 |
+
|
233 |
+
def update_cn_script_in_place(
|
234 |
+
script_runner: scripts.ScriptRunner,
|
235 |
+
script_args: List[Any],
|
236 |
+
cn_units: List[ControlNetUnit],
|
237 |
+
**_kwargs, # for backwards compatibility
|
238 |
+
):
|
239 |
+
"""
|
240 |
+
Update the arguments of the ControlNet script in `script_args` in place, reading from `cn_units`.
|
241 |
+
`cn_units` and its elements are not modified. You can call this function repeatedly, as many times as you want.
|
242 |
+
|
243 |
+
Does not update `script_args` if any of the folling is true:
|
244 |
+
- ControlNet is not present in `script_runner`
|
245 |
+
- `script_args` is not filled with script arguments for scripts that are processed before ControlNet
|
246 |
+
"""
|
247 |
+
|
248 |
+
cn_script = find_cn_script(script_runner)
|
249 |
+
if cn_script is None or len(script_args) < cn_script.args_from:
|
250 |
+
return
|
251 |
+
|
252 |
+
# fill in remaining parameters to satisfy max models, just in case script needs it.
|
253 |
+
max_models = shared.opts.data.get("control_net_max_models_num", 1)
|
254 |
+
cn_units = cn_units + [ControlNetUnit(enabled=False)] * max(max_models - len(cn_units), 0)
|
255 |
+
|
256 |
+
cn_script_args_diff = 0
|
257 |
+
for script in script_runner.alwayson_scripts:
|
258 |
+
if script is cn_script:
|
259 |
+
cn_script_args_diff = len(cn_units) - (cn_script.args_to - cn_script.args_from)
|
260 |
+
script_args[script.args_from:script.args_to] = cn_units
|
261 |
+
script.args_to = script.args_from + len(cn_units)
|
262 |
+
else:
|
263 |
+
script.args_from += cn_script_args_diff
|
264 |
+
script.args_to += cn_script_args_diff
|
265 |
+
|
266 |
+
|
267 |
+
def get_models(update: bool=False) -> List[str]:
|
268 |
+
"""
|
269 |
+
Fetch the list of available models.
|
270 |
+
Each value is a valid candidate of `ControlNetUnit.model`.
|
271 |
+
|
272 |
+
Keyword arguments:
|
273 |
+
update -- Whether to refresh the list from disk. (default False)
|
274 |
+
"""
|
275 |
+
|
276 |
+
if update:
|
277 |
+
global_state.update_cn_models()
|
278 |
+
|
279 |
+
return list(global_state.cn_models_names.values())
|
280 |
+
|
281 |
+
|
282 |
+
def get_modules(alias_names: bool = False) -> List[str]:
|
283 |
+
"""
|
284 |
+
Fetch the list of available preprocessors.
|
285 |
+
Each value is a valid candidate of `ControlNetUnit.module`.
|
286 |
+
|
287 |
+
Keyword arguments:
|
288 |
+
alias_names -- Whether to get the ui alias names instead of internal keys
|
289 |
+
"""
|
290 |
+
|
291 |
+
modules = list(global_state.cn_preprocessor_modules.keys())
|
292 |
+
|
293 |
+
if alias_names:
|
294 |
+
modules = [global_state.preprocessor_aliases.get(module, module) for module in modules]
|
295 |
+
|
296 |
+
return modules
|
297 |
+
|
298 |
+
|
299 |
+
def get_modules_detail(alias_names: bool = False) -> Dict[str, Any]:
|
300 |
+
"""
|
301 |
+
get the detail of all preprocessors including
|
302 |
+
sliders: the slider config in Auto1111 webUI
|
303 |
+
|
304 |
+
Keyword arguments:
|
305 |
+
alias_names -- Whether to get the module detail with alias names instead of internal keys
|
306 |
+
"""
|
307 |
+
|
308 |
+
_module_detail = {}
|
309 |
+
_module_list = get_modules(False)
|
310 |
+
_module_list_alias = get_modules(True)
|
311 |
+
|
312 |
+
_output_list = _module_list if not alias_names else _module_list_alias
|
313 |
+
for index, module in enumerate(_output_list):
|
314 |
+
if _module_list[index] in preprocessor_sliders_config:
|
315 |
+
_module_detail[module] = {
|
316 |
+
"model_free": module in model_free_preprocessors,
|
317 |
+
"sliders": preprocessor_sliders_config[_module_list[index]]
|
318 |
+
}
|
319 |
+
else:
|
320 |
+
_module_detail[module] = {
|
321 |
+
"model_free": False,
|
322 |
+
"sliders": []
|
323 |
+
}
|
324 |
+
|
325 |
+
return _module_detail
|
326 |
+
|
327 |
+
|
328 |
+
def find_cn_script(script_runner: scripts.ScriptRunner) -> Optional[scripts.Script]:
|
329 |
+
"""
|
330 |
+
Find the ControlNet script in `script_runner`. Returns `None` if `script_runner` does not contain a ControlNet script.
|
331 |
+
"""
|
332 |
+
|
333 |
+
if script_runner is None:
|
334 |
+
return None
|
335 |
+
|
336 |
+
for script in script_runner.alwayson_scripts:
|
337 |
+
if is_cn_script(script):
|
338 |
+
return script
|
339 |
+
|
340 |
+
|
341 |
+
def is_cn_script(script: scripts.Script) -> bool:
|
342 |
+
"""
|
343 |
+
Determine whether `script` is a ControlNet script.
|
344 |
+
"""
|
345 |
+
|
346 |
+
return script.title().lower() == 'controlnet'
|
extensions/microsoftexcel-controlnet/scripts/global_state.py
ADDED
@@ -0,0 +1,222 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os.path
|
2 |
+
import stat
|
3 |
+
import functools
|
4 |
+
from collections import OrderedDict
|
5 |
+
|
6 |
+
from modules import shared, scripts, sd_models
|
7 |
+
from modules.paths import models_path
|
8 |
+
from scripts.processor import *
|
9 |
+
from scripts.utils import ndarray_lru_cache
|
10 |
+
|
11 |
+
from typing import Dict, Callable, Optional
|
12 |
+
|
13 |
+
CN_MODEL_EXTS = [".pt", ".pth", ".ckpt", ".safetensors"]
|
14 |
+
cn_models_dir = os.path.join(models_path, "ControlNet")
|
15 |
+
cn_models_dir_old = os.path.join(scripts.basedir(), "models")
|
16 |
+
cn_models = OrderedDict() # "My_Lora(abcd1234)" -> C:/path/to/model.safetensors
|
17 |
+
cn_models_names = {} # "my_lora" -> "My_Lora(abcd1234)"
|
18 |
+
|
19 |
+
def cache_preprocessors(preprocessor_modules: Dict[str, Callable]) -> Dict[str, Callable]:
|
20 |
+
""" We want to share the preprocessor results in a single big cache, instead of a small
|
21 |
+
cache for each preprocessor function. """
|
22 |
+
CACHE_SIZE = shared.cmd_opts.controlnet_preprocessor_cache_size
|
23 |
+
|
24 |
+
# Set CACHE_SIZE = 0 will completely remove the caching layer. This can be
|
25 |
+
# helpful when debugging preprocessor code.
|
26 |
+
if CACHE_SIZE == 0:
|
27 |
+
return preprocessor_modules
|
28 |
+
|
29 |
+
print(f'Create LRU cache (max_size={CACHE_SIZE}) for preprocessor results.')
|
30 |
+
|
31 |
+
@ndarray_lru_cache(max_size=CACHE_SIZE)
|
32 |
+
def unified_preprocessor(preprocessor_name: str, *args, **kwargs):
|
33 |
+
# TODO: Make this a debug log?
|
34 |
+
print(f'Calling preprocessor {preprocessor_name} outside of cache.')
|
35 |
+
return preprocessor_modules[preprocessor_name](*args, **kwargs)
|
36 |
+
|
37 |
+
# TODO: Introduce a seed parameter for shuffle preprocessor?
|
38 |
+
uncacheable_preprocessors = ['shuffle']
|
39 |
+
|
40 |
+
return {
|
41 |
+
k: (
|
42 |
+
v if k in uncacheable_preprocessors
|
43 |
+
else functools.partial(unified_preprocessor, k)
|
44 |
+
)
|
45 |
+
for k, v
|
46 |
+
in preprocessor_modules.items()
|
47 |
+
}
|
48 |
+
|
49 |
+
cn_preprocessor_modules = {
|
50 |
+
"none": lambda x, *args, **kwargs: (x, True),
|
51 |
+
"canny": canny,
|
52 |
+
"depth": midas,
|
53 |
+
"depth_leres": functools.partial(leres, boost=False),
|
54 |
+
"depth_leres++": functools.partial(leres, boost=True),
|
55 |
+
"hed": hed,
|
56 |
+
"hed_safe": hed_safe,
|
57 |
+
"mediapipe_face": mediapipe_face,
|
58 |
+
"mlsd": mlsd,
|
59 |
+
"normal_map": midas_normal,
|
60 |
+
"openpose": functools.partial(g_openpose_model.run_model, include_body=True, include_hand=False, include_face=False),
|
61 |
+
"openpose_hand": functools.partial(g_openpose_model.run_model, include_body=True, include_hand=True, include_face=False),
|
62 |
+
"openpose_face": functools.partial(g_openpose_model.run_model, include_body=True, include_hand=False, include_face=True),
|
63 |
+
"openpose_faceonly": functools.partial(g_openpose_model.run_model, include_body=False, include_hand=False, include_face=True),
|
64 |
+
"openpose_full": functools.partial(g_openpose_model.run_model, include_body=True, include_hand=True, include_face=True),
|
65 |
+
"clip_vision": clip,
|
66 |
+
"color": color,
|
67 |
+
"pidinet": pidinet,
|
68 |
+
"pidinet_safe": pidinet_safe,
|
69 |
+
"pidinet_sketch": pidinet_ts,
|
70 |
+
"pidinet_scribble": scribble_pidinet,
|
71 |
+
"scribble_xdog": scribble_xdog,
|
72 |
+
"scribble_hed": scribble_hed,
|
73 |
+
"segmentation": uniformer,
|
74 |
+
"threshold": threshold,
|
75 |
+
"depth_zoe": zoe_depth,
|
76 |
+
"normal_bae": normal_bae,
|
77 |
+
"oneformer_coco": oneformer_coco,
|
78 |
+
"oneformer_ade20k": oneformer_ade20k,
|
79 |
+
"lineart": lineart,
|
80 |
+
"lineart_coarse": lineart_coarse,
|
81 |
+
"lineart_anime": lineart_anime,
|
82 |
+
"lineart_standard": lineart_standard,
|
83 |
+
"shuffle": shuffle,
|
84 |
+
"tile_resample": tile_resample,
|
85 |
+
"invert": invert,
|
86 |
+
"lineart_anime_denoise": lineart_anime_denoise,
|
87 |
+
"reference_only": identity,
|
88 |
+
"reference_adain": identity,
|
89 |
+
"reference_adain+attn": identity,
|
90 |
+
"inpaint": identity,
|
91 |
+
"inpaint_only": identity,
|
92 |
+
"tile_colorfix": identity,
|
93 |
+
"tile_colorfix+sharp": identity,
|
94 |
+
}
|
95 |
+
|
96 |
+
cn_preprocessor_unloadable = {
|
97 |
+
"hed": unload_hed,
|
98 |
+
"fake_scribble": unload_hed,
|
99 |
+
"mlsd": unload_mlsd,
|
100 |
+
"clip": unload_clip,
|
101 |
+
"depth": unload_midas,
|
102 |
+
"depth_leres": unload_leres,
|
103 |
+
"normal_map": unload_midas,
|
104 |
+
"pidinet": unload_pidinet,
|
105 |
+
"openpose": g_openpose_model.unload,
|
106 |
+
"openpose_hand": g_openpose_model.unload,
|
107 |
+
"openpose_face": g_openpose_model.unload,
|
108 |
+
"openpose_full": g_openpose_model.unload,
|
109 |
+
"segmentation": unload_uniformer,
|
110 |
+
"depth_zoe": unload_zoe_depth,
|
111 |
+
"normal_bae": unload_normal_bae,
|
112 |
+
"oneformer_coco": unload_oneformer_coco,
|
113 |
+
"oneformer_ade20k": unload_oneformer_ade20k,
|
114 |
+
"lineart": unload_lineart,
|
115 |
+
"lineart_coarse": unload_lineart_coarse,
|
116 |
+
"lineart_anime": unload_lineart_anime,
|
117 |
+
"lineart_anime_denoise": unload_lineart_anime_denoise
|
118 |
+
}
|
119 |
+
|
120 |
+
preprocessor_aliases = {
|
121 |
+
"invert": "invert (from white bg & black line)",
|
122 |
+
"lineart_standard": "lineart_standard (from white bg & black line)",
|
123 |
+
"lineart": "lineart_realistic",
|
124 |
+
"color": "t2ia_color_grid",
|
125 |
+
"clip_vision": "t2ia_style_clipvision",
|
126 |
+
"pidinet_sketch": "t2ia_sketch_pidi",
|
127 |
+
"depth": "depth_midas",
|
128 |
+
"normal_map": "normal_midas",
|
129 |
+
"hed": "softedge_hed",
|
130 |
+
"hed_safe": "softedge_hedsafe",
|
131 |
+
"pidinet": "softedge_pidinet",
|
132 |
+
"pidinet_safe": "softedge_pidisafe",
|
133 |
+
"segmentation": "seg_ufade20k",
|
134 |
+
"oneformer_coco": "seg_ofcoco",
|
135 |
+
"oneformer_ade20k": "seg_ofade20k",
|
136 |
+
"pidinet_scribble": "scribble_pidinet",
|
137 |
+
"inpaint": "inpaint_global_harmonious",
|
138 |
+
}
|
139 |
+
|
140 |
+
ui_preprocessor_keys = ['none', preprocessor_aliases['invert']]
|
141 |
+
ui_preprocessor_keys += sorted([preprocessor_aliases.get(k, k)
|
142 |
+
for k in cn_preprocessor_modules.keys()
|
143 |
+
if preprocessor_aliases.get(k, k) not in ui_preprocessor_keys])
|
144 |
+
|
145 |
+
reverse_preprocessor_aliases = {preprocessor_aliases[k]: k for k in preprocessor_aliases.keys()}
|
146 |
+
|
147 |
+
def get_module_basename(module: Optional[str]) -> str:
|
148 |
+
if module is None:
|
149 |
+
module = 'none'
|
150 |
+
return reverse_preprocessor_aliases.get(module, module)
|
151 |
+
|
152 |
+
default_conf = os.path.join("models", "cldm_v15.yaml")
|
153 |
+
default_conf_adapter = os.path.join("models", "t2iadapter_sketch_sd14v1.yaml")
|
154 |
+
cn_detectedmap_dir = os.path.join("detected_maps")
|
155 |
+
default_detectedmap_dir = cn_detectedmap_dir
|
156 |
+
script_dir = scripts.basedir()
|
157 |
+
|
158 |
+
os.makedirs(cn_models_dir, exist_ok=True)
|
159 |
+
os.makedirs(cn_detectedmap_dir, exist_ok=True)
|
160 |
+
|
161 |
+
|
162 |
+
def traverse_all_files(curr_path, model_list):
|
163 |
+
f_list = [(os.path.join(curr_path, entry.name), entry.stat())
|
164 |
+
for entry in os.scandir(curr_path)]
|
165 |
+
for f_info in f_list:
|
166 |
+
fname, fstat = f_info
|
167 |
+
if os.path.splitext(fname)[1] in CN_MODEL_EXTS:
|
168 |
+
model_list.append(f_info)
|
169 |
+
elif stat.S_ISDIR(fstat.st_mode):
|
170 |
+
model_list = traverse_all_files(fname, model_list)
|
171 |
+
return model_list
|
172 |
+
|
173 |
+
|
174 |
+
def get_all_models(sort_by, filter_by, path):
|
175 |
+
res = OrderedDict()
|
176 |
+
fileinfos = traverse_all_files(path, [])
|
177 |
+
filter_by = filter_by.strip(" ")
|
178 |
+
if len(filter_by) != 0:
|
179 |
+
fileinfos = [x for x in fileinfos if filter_by.lower()
|
180 |
+
in os.path.basename(x[0]).lower()]
|
181 |
+
if sort_by == "name":
|
182 |
+
fileinfos = sorted(fileinfos, key=lambda x: os.path.basename(x[0]))
|
183 |
+
elif sort_by == "date":
|
184 |
+
fileinfos = sorted(fileinfos, key=lambda x: -x[1].st_mtime)
|
185 |
+
elif sort_by == "path name":
|
186 |
+
fileinfos = sorted(fileinfos)
|
187 |
+
|
188 |
+
for finfo in fileinfos:
|
189 |
+
filename = finfo[0]
|
190 |
+
name = os.path.splitext(os.path.basename(filename))[0]
|
191 |
+
# Prevent a hypothetical "None.pt" from being listed.
|
192 |
+
if name != "None":
|
193 |
+
res[name + f" [{sd_models.model_hash(filename)}]"] = filename
|
194 |
+
|
195 |
+
return res
|
196 |
+
|
197 |
+
|
198 |
+
def update_cn_models():
|
199 |
+
cn_models.clear()
|
200 |
+
ext_dirs = (shared.opts.data.get("control_net_models_path", None), getattr(shared.cmd_opts, 'controlnet_dir', None))
|
201 |
+
extra_lora_paths = (extra_lora_path for extra_lora_path in ext_dirs
|
202 |
+
if extra_lora_path is not None and os.path.exists(extra_lora_path))
|
203 |
+
paths = [cn_models_dir, cn_models_dir_old, *extra_lora_paths]
|
204 |
+
|
205 |
+
for path in paths:
|
206 |
+
sort_by = shared.opts.data.get(
|
207 |
+
"control_net_models_sort_models_by", "name")
|
208 |
+
filter_by = shared.opts.data.get("control_net_models_name_filter", "")
|
209 |
+
found = get_all_models(sort_by, filter_by, path)
|
210 |
+
cn_models.update({**found, **cn_models})
|
211 |
+
|
212 |
+
# insert "None" at the beginning of `cn_models` in-place
|
213 |
+
cn_models_copy = OrderedDict(cn_models)
|
214 |
+
cn_models.clear()
|
215 |
+
cn_models.update({**{"None": None}, **cn_models_copy})
|
216 |
+
|
217 |
+
cn_models_names.clear()
|
218 |
+
for name_and_hash, filename in cn_models.items():
|
219 |
+
if filename is None:
|
220 |
+
continue
|
221 |
+
name = os.path.splitext(os.path.basename(filename))[0].lower()
|
222 |
+
cn_models_names[name] = name_and_hash
|
extensions/microsoftexcel-controlnet/scripts/hook.py
ADDED
@@ -0,0 +1,749 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import einops
|
3 |
+
import hashlib
|
4 |
+
import numpy as np
|
5 |
+
import torch.nn as nn
|
6 |
+
|
7 |
+
from enum import Enum
|
8 |
+
from modules import devices, lowvram, shared, scripts
|
9 |
+
|
10 |
+
cond_cast_unet = getattr(devices, 'cond_cast_unet', lambda x: x)
|
11 |
+
|
12 |
+
from ldm.modules.diffusionmodules.util import timestep_embedding
|
13 |
+
from ldm.modules.diffusionmodules.openaimodel import UNetModel
|
14 |
+
from ldm.modules.attention import BasicTransformerBlock
|
15 |
+
from ldm.models.diffusion.ddpm import extract_into_tensor
|
16 |
+
|
17 |
+
from modules.prompt_parser import MulticondLearnedConditioning, ComposableScheduledPromptConditioning, ScheduledPromptConditioning
|
18 |
+
|
19 |
+
|
20 |
+
POSITIVE_MARK_TOKEN = 1024
|
21 |
+
NEGATIVE_MARK_TOKEN = - POSITIVE_MARK_TOKEN
|
22 |
+
MARK_EPS = 1e-3
|
23 |
+
|
24 |
+
|
25 |
+
def prompt_context_is_marked(x):
|
26 |
+
t = x[..., 0, :]
|
27 |
+
m = torch.abs(t) - POSITIVE_MARK_TOKEN
|
28 |
+
m = torch.mean(torch.abs(m)).detach().cpu().float().numpy()
|
29 |
+
return float(m) < MARK_EPS
|
30 |
+
|
31 |
+
|
32 |
+
def mark_prompt_context(x, positive):
|
33 |
+
if isinstance(x, list):
|
34 |
+
for i in range(len(x)):
|
35 |
+
x[i] = mark_prompt_context(x[i], positive)
|
36 |
+
return x
|
37 |
+
if isinstance(x, MulticondLearnedConditioning):
|
38 |
+
x.batch = mark_prompt_context(x.batch, positive)
|
39 |
+
return x
|
40 |
+
if isinstance(x, ComposableScheduledPromptConditioning):
|
41 |
+
x.schedules = mark_prompt_context(x.schedules, positive)
|
42 |
+
return x
|
43 |
+
if isinstance(x, ScheduledPromptConditioning):
|
44 |
+
cond = x.cond
|
45 |
+
if prompt_context_is_marked(cond):
|
46 |
+
return x
|
47 |
+
mark = POSITIVE_MARK_TOKEN if positive else NEGATIVE_MARK_TOKEN
|
48 |
+
cond = torch.cat([torch.zeros_like(cond)[:1] + mark, cond], dim=0)
|
49 |
+
return ScheduledPromptConditioning(end_at_step=x.end_at_step, cond=cond)
|
50 |
+
return x
|
51 |
+
|
52 |
+
|
53 |
+
disable_controlnet_prompt_warning = True
|
54 |
+
# You can disable this warning using disable_controlnet_prompt_warning.
|
55 |
+
|
56 |
+
|
57 |
+
def unmark_prompt_context(x):
|
58 |
+
if not prompt_context_is_marked(x):
|
59 |
+
# ControlNet must know whether a prompt is conditional prompt (positive prompt) or unconditional conditioning prompt (negative prompt).
|
60 |
+
# You can use the hook.py's `mark_prompt_context` to mark the prompts that will be seen by ControlNet.
|
61 |
+
# Let us say XXX is a MulticondLearnedConditioning or a ComposableScheduledPromptConditioning or a ScheduledPromptConditioning or a list of these components,
|
62 |
+
# if XXX is a positive prompt, you should call mark_prompt_context(XXX, positive=True)
|
63 |
+
# if XXX is a negative prompt, you should call mark_prompt_context(XXX, positive=False)
|
64 |
+
# After you mark the prompts, the ControlNet will know which prompt is cond/uncond and works as expected.
|
65 |
+
# After you mark the prompts, the mismatch errors will disappear.
|
66 |
+
if not disable_controlnet_prompt_warning:
|
67 |
+
print('ControlNet Error: Failed to detect whether an instance is cond or uncond!')
|
68 |
+
print('ControlNet Error: This is mainly because other extension(s) blocked A1111\'s \"process.sample()\" and deleted ControlNet\'s sample function.')
|
69 |
+
print('ControlNet Error: ControlNet will shift to a backup backend but the results will be worse than expectation.')
|
70 |
+
print('Solution (For extension developers): Take a look at ControlNet\' hook.py '
|
71 |
+
'UnetHook.hook.process_sample and manually call mark_prompt_context to mark cond/uncond prompts.')
|
72 |
+
mark_batch = torch.ones(size=(x.shape[0], 1, 1, 1), dtype=x.dtype, device=x.device)
|
73 |
+
uc_indices = []
|
74 |
+
context = x
|
75 |
+
return mark_batch, uc_indices, context
|
76 |
+
mark = x[:, 0, :]
|
77 |
+
context = x[:, 1:, :]
|
78 |
+
mark = torch.mean(torch.abs(mark - NEGATIVE_MARK_TOKEN), dim=1)
|
79 |
+
mark = (mark > MARK_EPS).float()
|
80 |
+
mark_batch = mark[:, None, None, None].to(x.dtype).to(x.device)
|
81 |
+
uc_indices = mark.detach().cpu().numpy().tolist()
|
82 |
+
uc_indices = [i for i, item in enumerate(uc_indices) if item < 0.5]
|
83 |
+
return mark_batch, uc_indices, context
|
84 |
+
|
85 |
+
|
86 |
+
class ControlModelType(Enum):
|
87 |
+
"""
|
88 |
+
The type of Control Models (supported or not).
|
89 |
+
"""
|
90 |
+
|
91 |
+
ControlNet = "ControlNet, Lvmin Zhang"
|
92 |
+
T2I_Adapter = "T2I_Adapter, Chong Mou"
|
93 |
+
T2I_StyleAdapter = "T2I_StyleAdapter, Chong Mou"
|
94 |
+
T2I_CoAdapter = "T2I_CoAdapter, Chong Mou"
|
95 |
+
MasaCtrl = "MasaCtrl, Mingdeng Cao"
|
96 |
+
GLIGEN = "GLIGEN, Yuheng Li"
|
97 |
+
AttentionInjection = "AttentionInjection, Lvmin Zhang" # A simple attention injection written by Lvmin
|
98 |
+
StableSR = "StableSR, Jianyi Wang"
|
99 |
+
PromptDiffusion = "PromptDiffusion, Zhendong Wang"
|
100 |
+
ControlLoRA = "ControlLoRA, Wu Hecong"
|
101 |
+
|
102 |
+
|
103 |
+
# Written by Lvmin
|
104 |
+
class AutoMachine(Enum):
|
105 |
+
"""
|
106 |
+
Lvmin's algorithm for Attention/AdaIn AutoMachine States.
|
107 |
+
"""
|
108 |
+
|
109 |
+
Read = "Read"
|
110 |
+
Write = "Write"
|
111 |
+
|
112 |
+
|
113 |
+
class TorchHijackForUnet:
|
114 |
+
"""
|
115 |
+
This is torch, but with cat that resizes tensors to appropriate dimensions if they do not match;
|
116 |
+
this makes it possible to create pictures with dimensions that are multiples of 8 rather than 64
|
117 |
+
"""
|
118 |
+
|
119 |
+
def __getattr__(self, item):
|
120 |
+
if item == 'cat':
|
121 |
+
return self.cat
|
122 |
+
|
123 |
+
if hasattr(torch, item):
|
124 |
+
return getattr(torch, item)
|
125 |
+
|
126 |
+
raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, item))
|
127 |
+
|
128 |
+
def cat(self, tensors, *args, **kwargs):
|
129 |
+
if len(tensors) == 2:
|
130 |
+
a, b = tensors
|
131 |
+
if a.shape[-2:] != b.shape[-2:]:
|
132 |
+
a = torch.nn.functional.interpolate(a, b.shape[-2:], mode="nearest")
|
133 |
+
|
134 |
+
tensors = (a, b)
|
135 |
+
|
136 |
+
return torch.cat(tensors, *args, **kwargs)
|
137 |
+
|
138 |
+
|
139 |
+
th = TorchHijackForUnet()
|
140 |
+
|
141 |
+
|
142 |
+
class ControlParams:
|
143 |
+
def __init__(
|
144 |
+
self,
|
145 |
+
control_model,
|
146 |
+
preprocessor,
|
147 |
+
hint_cond,
|
148 |
+
weight,
|
149 |
+
guidance_stopped,
|
150 |
+
start_guidance_percent,
|
151 |
+
stop_guidance_percent,
|
152 |
+
advanced_weighting,
|
153 |
+
control_model_type,
|
154 |
+
hr_hint_cond,
|
155 |
+
global_average_pooling,
|
156 |
+
soft_injection,
|
157 |
+
cfg_injection,
|
158 |
+
**kwargs # To avoid errors
|
159 |
+
):
|
160 |
+
self.control_model = control_model
|
161 |
+
self.preprocessor = preprocessor
|
162 |
+
self._hint_cond = hint_cond
|
163 |
+
self.weight = weight
|
164 |
+
self.guidance_stopped = guidance_stopped
|
165 |
+
self.start_guidance_percent = start_guidance_percent
|
166 |
+
self.stop_guidance_percent = stop_guidance_percent
|
167 |
+
self.advanced_weighting = advanced_weighting
|
168 |
+
self.control_model_type = control_model_type
|
169 |
+
self.global_average_pooling = global_average_pooling
|
170 |
+
self.hr_hint_cond = hr_hint_cond
|
171 |
+
self.used_hint_cond = None
|
172 |
+
self.used_hint_cond_latent = None
|
173 |
+
self.used_hint_inpaint_hijack = None
|
174 |
+
self.soft_injection = soft_injection
|
175 |
+
self.cfg_injection = cfg_injection
|
176 |
+
|
177 |
+
@property
|
178 |
+
def hint_cond(self):
|
179 |
+
return self._hint_cond
|
180 |
+
|
181 |
+
# fix for all the extensions that modify hint_cond,
|
182 |
+
# by forcing used_hint_cond to update on the next timestep
|
183 |
+
# hr_hint_cond can stay the same, since most extensions dont modify the hires pass
|
184 |
+
# but if they do, it will cause problems
|
185 |
+
@hint_cond.setter
|
186 |
+
def hint_cond(self, new_hint_cond):
|
187 |
+
self._hint_cond = new_hint_cond
|
188 |
+
self.used_hint_cond = None
|
189 |
+
self.used_hint_cond_latent = None
|
190 |
+
self.used_hint_inpaint_hijack = None
|
191 |
+
|
192 |
+
|
193 |
+
def aligned_adding(base, x, require_channel_alignment):
|
194 |
+
if isinstance(x, float):
|
195 |
+
if x == 0.0:
|
196 |
+
return base
|
197 |
+
return base + x
|
198 |
+
|
199 |
+
if require_channel_alignment:
|
200 |
+
zeros = torch.zeros_like(base)
|
201 |
+
zeros[:, :x.shape[1], ...] = x
|
202 |
+
x = zeros
|
203 |
+
|
204 |
+
# resize to sample resolution
|
205 |
+
base_h, base_w = base.shape[-2:]
|
206 |
+
xh, xw = x.shape[-2:]
|
207 |
+
if base_h != xh or base_w != xw:
|
208 |
+
print('[Warning] ControlNet finds unexpected mis-alignment in tensor shape.')
|
209 |
+
x = th.nn.functional.interpolate(x, size=(base_h, base_w), mode="nearest")
|
210 |
+
|
211 |
+
return base + x
|
212 |
+
|
213 |
+
|
214 |
+
# DFS Search for Torch.nn.Module, Written by Lvmin
|
215 |
+
def torch_dfs(model: torch.nn.Module):
|
216 |
+
result = [model]
|
217 |
+
for child in model.children():
|
218 |
+
result += torch_dfs(child)
|
219 |
+
return result
|
220 |
+
|
221 |
+
|
222 |
+
def predict_start_from_noise(ldm, x_t, t, noise):
|
223 |
+
return extract_into_tensor(ldm.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - extract_into_tensor(ldm.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
|
224 |
+
|
225 |
+
|
226 |
+
def predict_noise_from_start(ldm, x_t, t, x0):
|
227 |
+
return (extract_into_tensor(ldm.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - x0) / extract_into_tensor(ldm.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
|
228 |
+
|
229 |
+
|
230 |
+
def blur(x, k):
|
231 |
+
y = torch.nn.functional.pad(x, (k, k, k, k), mode='replicate')
|
232 |
+
y = torch.nn.functional.avg_pool2d(y, (k*2+1, k*2+1), stride=(1, 1))
|
233 |
+
return y
|
234 |
+
|
235 |
+
|
236 |
+
class TorchCache:
|
237 |
+
def __init__(self):
|
238 |
+
self.cache = {}
|
239 |
+
|
240 |
+
def hash(self, key):
|
241 |
+
v = key.detach().cpu().numpy().astype(np.float32)
|
242 |
+
v = (v * 1000.0).astype(np.int32)
|
243 |
+
v = np.ascontiguousarray(v.copy())
|
244 |
+
sha = hashlib.sha1(v).hexdigest()
|
245 |
+
return sha
|
246 |
+
|
247 |
+
def get(self, key):
|
248 |
+
key = self.hash(key)
|
249 |
+
return self.cache.get(key, None)
|
250 |
+
|
251 |
+
def set(self, key, value):
|
252 |
+
self.cache[self.hash(key)] = value
|
253 |
+
|
254 |
+
|
255 |
+
class UnetHook(nn.Module):
|
256 |
+
def __init__(self, lowvram=False) -> None:
|
257 |
+
super().__init__()
|
258 |
+
self.lowvram = lowvram
|
259 |
+
self.model = None
|
260 |
+
self.sd_ldm = None
|
261 |
+
self.control_params = None
|
262 |
+
self.attention_auto_machine = AutoMachine.Read
|
263 |
+
self.attention_auto_machine_weight = 1.0
|
264 |
+
self.gn_auto_machine = AutoMachine.Read
|
265 |
+
self.gn_auto_machine_weight = 1.0
|
266 |
+
self.current_style_fidelity = 0.0
|
267 |
+
self.current_uc_indices = None
|
268 |
+
|
269 |
+
def guidance_schedule_handler(self, x):
|
270 |
+
for param in self.control_params:
|
271 |
+
current_sampling_percent = (x.sampling_step / x.total_sampling_steps)
|
272 |
+
param.guidance_stopped = current_sampling_percent < param.start_guidance_percent or current_sampling_percent > param.stop_guidance_percent
|
273 |
+
|
274 |
+
def hook(self, model, sd_ldm, control_params, process):
|
275 |
+
self.model = model
|
276 |
+
self.sd_ldm = sd_ldm
|
277 |
+
self.control_params = control_params
|
278 |
+
|
279 |
+
outer = self
|
280 |
+
|
281 |
+
def process_sample(*args, **kwargs):
|
282 |
+
# ControlNet must know whether a prompt is conditional prompt (positive prompt) or unconditional conditioning prompt (negative prompt).
|
283 |
+
# You can use the hook.py's `mark_prompt_context` to mark the prompts that will be seen by ControlNet.
|
284 |
+
# Let us say XXX is a MulticondLearnedConditioning or a ComposableScheduledPromptConditioning or a ScheduledPromptConditioning or a list of these components,
|
285 |
+
# if XXX is a positive prompt, you should call mark_prompt_context(XXX, positive=True)
|
286 |
+
# if XXX is a negative prompt, you should call mark_prompt_context(XXX, positive=False)
|
287 |
+
# After you mark the prompts, the ControlNet will know which prompt is cond/uncond and works as expected.
|
288 |
+
# After you mark the prompts, the mismatch errors will disappear.
|
289 |
+
mark_prompt_context(kwargs.get('conditioning', []), positive=True)
|
290 |
+
mark_prompt_context(kwargs.get('unconditional_conditioning', []), positive=False)
|
291 |
+
mark_prompt_context(getattr(process, 'hr_c', []), positive=True)
|
292 |
+
mark_prompt_context(getattr(process, 'hr_uc', []), positive=False)
|
293 |
+
return process.sample_before_CN_hack(*args, **kwargs)
|
294 |
+
|
295 |
+
def vae_forward(x, batch_size, mask=None):
|
296 |
+
try:
|
297 |
+
if x.shape[1] > 3:
|
298 |
+
x = x[:, 0:3, :, :]
|
299 |
+
x = x * 2.0 - 1.0
|
300 |
+
if mask is not None:
|
301 |
+
x = x * (1.0 - mask)
|
302 |
+
x = x.type(devices.dtype_vae)
|
303 |
+
vae_output = outer.vae_cache.get(x)
|
304 |
+
if vae_output is None:
|
305 |
+
with devices.autocast():
|
306 |
+
vae_output = outer.sd_ldm.encode_first_stage(x)
|
307 |
+
vae_output = outer.sd_ldm.get_first_stage_encoding(vae_output)
|
308 |
+
outer.vae_cache.set(x, vae_output)
|
309 |
+
print(f'ControlNet used {str(devices.dtype_vae)} VAE to encode {vae_output.shape}.')
|
310 |
+
latent = vae_output
|
311 |
+
if latent.shape[0] != batch_size:
|
312 |
+
latent = torch.cat([latent.clone() for _ in range(batch_size)], dim=0)
|
313 |
+
latent = latent.type(devices.dtype_unet)
|
314 |
+
return latent
|
315 |
+
except Exception as e:
|
316 |
+
print(e)
|
317 |
+
raise ValueError('ControlNet failed to use VAE. Please try to add `--no-half-vae`, `--no-half` and remove `--precision full` in launch cmd.')
|
318 |
+
|
319 |
+
def forward(self, x, timesteps=None, context=None, **kwargs):
|
320 |
+
total_controlnet_embedding = [0.0] * 13
|
321 |
+
total_t2i_adapter_embedding = [0.0] * 4
|
322 |
+
require_inpaint_hijack = False
|
323 |
+
is_in_high_res_fix = False
|
324 |
+
batch_size = int(x.shape[0])
|
325 |
+
|
326 |
+
# Handle cond-uncond marker
|
327 |
+
cond_mark, outer.current_uc_indices, context = unmark_prompt_context(context)
|
328 |
+
# print(str(cond_mark[:, 0, 0, 0].detach().cpu().numpy().tolist()) + ' - ' + str(outer.current_uc_indices))
|
329 |
+
|
330 |
+
# High-res fix
|
331 |
+
for param in outer.control_params:
|
332 |
+
# select which hint_cond to use
|
333 |
+
if param.used_hint_cond is None:
|
334 |
+
param.used_hint_cond = param.hint_cond
|
335 |
+
param.used_hint_cond_latent = None
|
336 |
+
param.used_hint_inpaint_hijack = None
|
337 |
+
|
338 |
+
# has high-res fix
|
339 |
+
if param.hr_hint_cond is not None and x.ndim == 4 and param.hint_cond.ndim == 4 and param.hr_hint_cond.ndim == 4:
|
340 |
+
_, _, h_lr, w_lr = param.hint_cond.shape
|
341 |
+
_, _, h_hr, w_hr = param.hr_hint_cond.shape
|
342 |
+
_, _, h, w = x.shape
|
343 |
+
h, w = h * 8, w * 8
|
344 |
+
if abs(h - h_lr) < abs(h - h_hr):
|
345 |
+
is_in_high_res_fix = False
|
346 |
+
if param.used_hint_cond is not param.hint_cond:
|
347 |
+
param.used_hint_cond = param.hint_cond
|
348 |
+
param.used_hint_cond_latent = None
|
349 |
+
param.used_hint_inpaint_hijack = None
|
350 |
+
else:
|
351 |
+
is_in_high_res_fix = True
|
352 |
+
if param.used_hint_cond is not param.hr_hint_cond:
|
353 |
+
param.used_hint_cond = param.hr_hint_cond
|
354 |
+
param.used_hint_cond_latent = None
|
355 |
+
param.used_hint_inpaint_hijack = None
|
356 |
+
|
357 |
+
# Convert control image to latent
|
358 |
+
for param in outer.control_params:
|
359 |
+
if param.used_hint_cond_latent is not None:
|
360 |
+
continue
|
361 |
+
if param.control_model_type not in [ControlModelType.AttentionInjection] \
|
362 |
+
and 'colorfix' not in param.preprocessor['name'] \
|
363 |
+
and 'inpaint_only' not in param.preprocessor['name']:
|
364 |
+
continue
|
365 |
+
param.used_hint_cond_latent = vae_forward(param.used_hint_cond, batch_size=batch_size)
|
366 |
+
|
367 |
+
# handle prompt token control
|
368 |
+
for param in outer.control_params:
|
369 |
+
if param.guidance_stopped:
|
370 |
+
continue
|
371 |
+
|
372 |
+
if param.control_model_type not in [ControlModelType.T2I_StyleAdapter]:
|
373 |
+
continue
|
374 |
+
|
375 |
+
param.control_model.to(devices.get_device_for("controlnet"))
|
376 |
+
control = param.control_model(x=x, hint=param.used_hint_cond, timesteps=timesteps, context=context)
|
377 |
+
control = torch.cat([control.clone() for _ in range(batch_size)], dim=0)
|
378 |
+
control *= param.weight
|
379 |
+
control *= cond_mark[:, :, :, 0]
|
380 |
+
context = torch.cat([context, control.clone()], dim=1)
|
381 |
+
|
382 |
+
# handle ControlNet / T2I_Adapter
|
383 |
+
for param in outer.control_params:
|
384 |
+
if param.guidance_stopped:
|
385 |
+
continue
|
386 |
+
|
387 |
+
if param.control_model_type not in [ControlModelType.ControlNet, ControlModelType.T2I_Adapter]:
|
388 |
+
continue
|
389 |
+
|
390 |
+
param.control_model.to(devices.get_device_for("controlnet"))
|
391 |
+
# inpaint model workaround
|
392 |
+
x_in = x
|
393 |
+
control_model = param.control_model.control_model
|
394 |
+
|
395 |
+
if param.control_model_type == ControlModelType.ControlNet:
|
396 |
+
if x.shape[1] != control_model.input_blocks[0][0].in_channels and x.shape[1] == 9:
|
397 |
+
# inpaint_model: 4 data + 4 downscaled image + 1 mask
|
398 |
+
x_in = x[:, :4, ...]
|
399 |
+
require_inpaint_hijack = True
|
400 |
+
|
401 |
+
assert param.used_hint_cond is not None, f"Controlnet is enabled but no input image is given"
|
402 |
+
|
403 |
+
hint = param.used_hint_cond
|
404 |
+
|
405 |
+
# ControlNet inpaint protocol
|
406 |
+
if hint.shape[1] == 4:
|
407 |
+
c = hint[:, 0:3, :, :]
|
408 |
+
m = hint[:, 3:4, :, :]
|
409 |
+
m = (m > 0.5).float()
|
410 |
+
hint = c * (1 - m) - m
|
411 |
+
|
412 |
+
control = param.control_model(x=x_in, hint=hint, timesteps=timesteps, context=context)
|
413 |
+
control_scales = ([param.weight] * 13)
|
414 |
+
|
415 |
+
if outer.lowvram:
|
416 |
+
param.control_model.to("cpu")
|
417 |
+
|
418 |
+
if param.cfg_injection or param.global_average_pooling:
|
419 |
+
if param.control_model_type == ControlModelType.T2I_Adapter:
|
420 |
+
control = [torch.cat([c.clone() for _ in range(batch_size)], dim=0) for c in control]
|
421 |
+
control = [c * cond_mark for c in control]
|
422 |
+
|
423 |
+
if param.soft_injection or is_in_high_res_fix:
|
424 |
+
# important! use the soft weights with high-res fix can significantly reduce artifacts.
|
425 |
+
if param.control_model_type == ControlModelType.T2I_Adapter:
|
426 |
+
control_scales = [param.weight * x for x in (0.25, 0.62, 0.825, 1.0)]
|
427 |
+
elif param.control_model_type == ControlModelType.ControlNet:
|
428 |
+
control_scales = [param.weight * (0.825 ** float(12 - i)) for i in range(13)]
|
429 |
+
|
430 |
+
if param.advanced_weighting is not None:
|
431 |
+
control_scales = param.advanced_weighting
|
432 |
+
|
433 |
+
control = [c * scale for c, scale in zip(control, control_scales)]
|
434 |
+
if param.global_average_pooling:
|
435 |
+
control = [torch.mean(c, dim=(2, 3), keepdim=True) for c in control]
|
436 |
+
|
437 |
+
for idx, item in enumerate(control):
|
438 |
+
target = None
|
439 |
+
if param.control_model_type == ControlModelType.ControlNet:
|
440 |
+
target = total_controlnet_embedding
|
441 |
+
if param.control_model_type == ControlModelType.T2I_Adapter:
|
442 |
+
target = total_t2i_adapter_embedding
|
443 |
+
if target is not None:
|
444 |
+
target[idx] = item + target[idx]
|
445 |
+
|
446 |
+
# Clear attention and AdaIn cache
|
447 |
+
for module in outer.attn_module_list:
|
448 |
+
module.bank = []
|
449 |
+
module.style_cfgs = []
|
450 |
+
for module in outer.gn_module_list:
|
451 |
+
module.mean_bank = []
|
452 |
+
module.var_bank = []
|
453 |
+
module.style_cfgs = []
|
454 |
+
|
455 |
+
# Handle attention and AdaIn control
|
456 |
+
for param in outer.control_params:
|
457 |
+
if param.guidance_stopped:
|
458 |
+
continue
|
459 |
+
|
460 |
+
if param.used_hint_cond_latent is None:
|
461 |
+
continue
|
462 |
+
|
463 |
+
if param.control_model_type not in [ControlModelType.AttentionInjection]:
|
464 |
+
continue
|
465 |
+
|
466 |
+
ref_xt = outer.sd_ldm.q_sample(param.used_hint_cond_latent, torch.round(timesteps.float()).long())
|
467 |
+
|
468 |
+
# Inpaint Hijack
|
469 |
+
if x.shape[1] == 9:
|
470 |
+
ref_xt = torch.cat([
|
471 |
+
ref_xt,
|
472 |
+
torch.zeros_like(ref_xt)[:, 0:1, :, :],
|
473 |
+
param.used_hint_cond_latent
|
474 |
+
], dim=1)
|
475 |
+
|
476 |
+
outer.current_style_fidelity = float(param.preprocessor['threshold_a'])
|
477 |
+
outer.current_style_fidelity = max(0.0, min(1.0, outer.current_style_fidelity))
|
478 |
+
|
479 |
+
if param.cfg_injection:
|
480 |
+
outer.current_style_fidelity = 1.0
|
481 |
+
elif param.soft_injection or is_in_high_res_fix:
|
482 |
+
outer.current_style_fidelity = 0.0
|
483 |
+
|
484 |
+
control_name = param.preprocessor['name']
|
485 |
+
|
486 |
+
if control_name in ['reference_only', 'reference_adain+attn']:
|
487 |
+
outer.attention_auto_machine = AutoMachine.Write
|
488 |
+
outer.attention_auto_machine_weight = param.weight
|
489 |
+
|
490 |
+
if control_name in ['reference_adain', 'reference_adain+attn']:
|
491 |
+
outer.gn_auto_machine = AutoMachine.Write
|
492 |
+
outer.gn_auto_machine_weight = param.weight
|
493 |
+
|
494 |
+
outer.original_forward(
|
495 |
+
x=ref_xt.to(devices.dtype_unet),
|
496 |
+
timesteps=timesteps.to(devices.dtype_unet),
|
497 |
+
context=context.to(devices.dtype_unet)
|
498 |
+
)
|
499 |
+
|
500 |
+
outer.attention_auto_machine = AutoMachine.Read
|
501 |
+
outer.gn_auto_machine = AutoMachine.Read
|
502 |
+
|
503 |
+
# Replace x_t to support inpaint models
|
504 |
+
for param in outer.control_params:
|
505 |
+
if param.used_hint_cond.shape[1] != 4:
|
506 |
+
continue
|
507 |
+
if x.shape[1] != 9:
|
508 |
+
continue
|
509 |
+
if param.used_hint_inpaint_hijack is None:
|
510 |
+
mask_pixel = param.used_hint_cond[:, 3:4, :, :]
|
511 |
+
image_pixel = param.used_hint_cond[:, 0:3, :, :]
|
512 |
+
mask_pixel = (mask_pixel > 0.5).to(mask_pixel.dtype)
|
513 |
+
masked_latent = vae_forward(image_pixel, batch_size, mask=mask_pixel)
|
514 |
+
mask_latent = torch.nn.functional.max_pool2d(mask_pixel, (8, 8))
|
515 |
+
if mask_latent.shape[0] != batch_size:
|
516 |
+
mask_latent = torch.cat([mask_latent.clone() for _ in range(batch_size)], dim=0)
|
517 |
+
param.used_hint_inpaint_hijack = torch.cat([mask_latent, masked_latent], dim=1)
|
518 |
+
param.used_hint_inpaint_hijack.to(x.dtype).to(x.device)
|
519 |
+
x = torch.cat([x[:, :4, :, :], param.used_hint_inpaint_hijack], dim=1)
|
520 |
+
|
521 |
+
# A1111 fix for medvram.
|
522 |
+
if shared.cmd_opts.medvram:
|
523 |
+
try:
|
524 |
+
# Trigger the register_forward_pre_hook
|
525 |
+
outer.sd_ldm.model()
|
526 |
+
except:
|
527 |
+
pass
|
528 |
+
|
529 |
+
# U-Net Encoder
|
530 |
+
hs = []
|
531 |
+
with th.no_grad():
|
532 |
+
t_emb = cond_cast_unet(timestep_embedding(timesteps, self.model_channels, repeat_only=False))
|
533 |
+
emb = self.time_embed(t_emb)
|
534 |
+
h = x.type(self.dtype)
|
535 |
+
for i, module in enumerate(self.input_blocks):
|
536 |
+
h = module(h, emb, context)
|
537 |
+
|
538 |
+
if (i + 1) % 3 == 0:
|
539 |
+
h = aligned_adding(h, total_t2i_adapter_embedding.pop(0), require_inpaint_hijack)
|
540 |
+
|
541 |
+
hs.append(h)
|
542 |
+
h = self.middle_block(h, emb, context)
|
543 |
+
|
544 |
+
# U-Net Middle Block
|
545 |
+
h = aligned_adding(h, total_controlnet_embedding.pop(), require_inpaint_hijack)
|
546 |
+
|
547 |
+
# U-Net Decoder
|
548 |
+
for i, module in enumerate(self.output_blocks):
|
549 |
+
h = th.cat([h, aligned_adding(hs.pop(), total_controlnet_embedding.pop(), require_inpaint_hijack)], dim=1)
|
550 |
+
h = module(h, emb, context)
|
551 |
+
|
552 |
+
# U-Net Output
|
553 |
+
h = h.type(x.dtype)
|
554 |
+
h = self.out(h)
|
555 |
+
|
556 |
+
# Post-processing for color fix
|
557 |
+
for param in outer.control_params:
|
558 |
+
if param.used_hint_cond_latent is None:
|
559 |
+
continue
|
560 |
+
if 'colorfix' not in param.preprocessor['name']:
|
561 |
+
continue
|
562 |
+
|
563 |
+
k = int(param.preprocessor['threshold_a'])
|
564 |
+
if is_in_high_res_fix:
|
565 |
+
k *= 2
|
566 |
+
|
567 |
+
# Inpaint hijack
|
568 |
+
xt = x[:, :4, :, :]
|
569 |
+
|
570 |
+
x0_origin = param.used_hint_cond_latent
|
571 |
+
t = torch.round(timesteps.float()).long()
|
572 |
+
x0_prd = predict_start_from_noise(outer.sd_ldm, xt, t, h)
|
573 |
+
x0 = x0_prd - blur(x0_prd, k) + blur(x0_origin, k)
|
574 |
+
|
575 |
+
if '+sharp' in param.preprocessor['name']:
|
576 |
+
detail_weight = float(param.preprocessor['threshold_b']) * 0.01
|
577 |
+
neg = detail_weight * blur(x0, k) + (1 - detail_weight) * x0
|
578 |
+
x0 = cond_mark * x0 + (1 - cond_mark) * neg
|
579 |
+
|
580 |
+
eps_prd = predict_noise_from_start(outer.sd_ldm, xt, t, x0)
|
581 |
+
|
582 |
+
w = max(0.0, min(1.0, float(param.weight)))
|
583 |
+
h = eps_prd * w + h * (1 - w)
|
584 |
+
|
585 |
+
# Post-processing for restore
|
586 |
+
for param in outer.control_params:
|
587 |
+
if param.used_hint_cond_latent is None:
|
588 |
+
continue
|
589 |
+
if 'inpaint_only' not in param.preprocessor['name']:
|
590 |
+
continue
|
591 |
+
if param.used_hint_cond.shape[1] != 4:
|
592 |
+
continue
|
593 |
+
|
594 |
+
# Inpaint hijack
|
595 |
+
xt = x[:, :4, :, :]
|
596 |
+
|
597 |
+
mask = param.used_hint_cond[:, 3:4, :, :]
|
598 |
+
mask = torch.nn.functional.max_pool2d(mask, (10, 10), stride=(8, 8), padding=1)
|
599 |
+
|
600 |
+
x0_origin = param.used_hint_cond_latent
|
601 |
+
t = torch.round(timesteps.float()).long()
|
602 |
+
x0_prd = predict_start_from_noise(outer.sd_ldm, xt, t, h)
|
603 |
+
x0 = x0_prd * mask + x0_origin * (1 - mask)
|
604 |
+
eps_prd = predict_noise_from_start(outer.sd_ldm, xt, t, x0)
|
605 |
+
|
606 |
+
w = max(0.0, min(1.0, float(param.weight)))
|
607 |
+
h = eps_prd * w + h * (1 - w)
|
608 |
+
|
609 |
+
return h
|
610 |
+
|
611 |
+
def forward_webui(*args, **kwargs):
|
612 |
+
# webui will handle other compoments
|
613 |
+
try:
|
614 |
+
if shared.cmd_opts.lowvram:
|
615 |
+
lowvram.send_everything_to_cpu()
|
616 |
+
|
617 |
+
return forward(*args, **kwargs)
|
618 |
+
finally:
|
619 |
+
if self.lowvram:
|
620 |
+
for param in self.control_params:
|
621 |
+
if isinstance(param.control_model, torch.nn.Module):
|
622 |
+
param.control_model.to("cpu")
|
623 |
+
|
624 |
+
def hacked_basic_transformer_inner_forward(self, x, context=None):
|
625 |
+
x_norm1 = self.norm1(x)
|
626 |
+
self_attn1 = None
|
627 |
+
if self.disable_self_attn:
|
628 |
+
# Do not use self-attention
|
629 |
+
self_attn1 = self.attn1(x_norm1, context=context)
|
630 |
+
else:
|
631 |
+
# Use self-attention
|
632 |
+
self_attention_context = x_norm1
|
633 |
+
if outer.attention_auto_machine == AutoMachine.Write:
|
634 |
+
if outer.attention_auto_machine_weight > self.attn_weight:
|
635 |
+
self.bank.append(self_attention_context.detach().clone())
|
636 |
+
self.style_cfgs.append(outer.current_style_fidelity)
|
637 |
+
if outer.attention_auto_machine == AutoMachine.Read:
|
638 |
+
if len(self.bank) > 0:
|
639 |
+
style_cfg = sum(self.style_cfgs) / float(len(self.style_cfgs))
|
640 |
+
self_attn1_uc = self.attn1(x_norm1, context=torch.cat([self_attention_context] + self.bank, dim=1))
|
641 |
+
self_attn1_c = self_attn1_uc.clone()
|
642 |
+
if len(outer.current_uc_indices) > 0 and style_cfg > 1e-5:
|
643 |
+
self_attn1_c[outer.current_uc_indices] = self.attn1(
|
644 |
+
x_norm1[outer.current_uc_indices],
|
645 |
+
context=self_attention_context[outer.current_uc_indices])
|
646 |
+
self_attn1 = style_cfg * self_attn1_c + (1.0 - style_cfg) * self_attn1_uc
|
647 |
+
self.bank = []
|
648 |
+
self.style_cfgs = []
|
649 |
+
if self_attn1 is None:
|
650 |
+
self_attn1 = self.attn1(x_norm1, context=self_attention_context)
|
651 |
+
|
652 |
+
x = self_attn1.to(x.dtype) + x
|
653 |
+
x = self.attn2(self.norm2(x), context=context) + x
|
654 |
+
x = self.ff(self.norm3(x)) + x
|
655 |
+
return x
|
656 |
+
|
657 |
+
def hacked_group_norm_forward(self, *args, **kwargs):
|
658 |
+
eps = 1e-6
|
659 |
+
x = self.original_forward(*args, **kwargs)
|
660 |
+
y = None
|
661 |
+
if outer.gn_auto_machine == AutoMachine.Write:
|
662 |
+
if outer.gn_auto_machine_weight > self.gn_weight:
|
663 |
+
var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)
|
664 |
+
self.mean_bank.append(mean)
|
665 |
+
self.var_bank.append(var)
|
666 |
+
self.style_cfgs.append(outer.current_style_fidelity)
|
667 |
+
if outer.gn_auto_machine == AutoMachine.Read:
|
668 |
+
if len(self.mean_bank) > 0 and len(self.var_bank) > 0:
|
669 |
+
style_cfg = sum(self.style_cfgs) / float(len(self.style_cfgs))
|
670 |
+
var, mean = torch.var_mean(x, dim=(2, 3), keepdim=True, correction=0)
|
671 |
+
std = torch.maximum(var, torch.zeros_like(var) + eps) ** 0.5
|
672 |
+
mean_acc = sum(self.mean_bank) / float(len(self.mean_bank))
|
673 |
+
var_acc = sum(self.var_bank) / float(len(self.var_bank))
|
674 |
+
std_acc = torch.maximum(var_acc, torch.zeros_like(var_acc) + eps) ** 0.5
|
675 |
+
y_uc = (((x - mean) / std) * std_acc) + mean_acc
|
676 |
+
y_c = y_uc.clone()
|
677 |
+
if len(outer.current_uc_indices) > 0 and style_cfg > 1e-5:
|
678 |
+
y_c[outer.current_uc_indices] = x.to(y_c.dtype)[outer.current_uc_indices]
|
679 |
+
y = style_cfg * y_c + (1.0 - style_cfg) * y_uc
|
680 |
+
self.mean_bank = []
|
681 |
+
self.var_bank = []
|
682 |
+
self.style_cfgs = []
|
683 |
+
if y is None:
|
684 |
+
y = x
|
685 |
+
return y.to(x.dtype)
|
686 |
+
|
687 |
+
if getattr(process, 'sample_before_CN_hack', None) is None:
|
688 |
+
process.sample_before_CN_hack = process.sample
|
689 |
+
process.sample = process_sample
|
690 |
+
|
691 |
+
model._original_forward = model.forward
|
692 |
+
outer.original_forward = model.forward
|
693 |
+
model.forward = forward_webui.__get__(model, UNetModel)
|
694 |
+
|
695 |
+
outer.vae_cache = TorchCache()
|
696 |
+
|
697 |
+
all_modules = torch_dfs(model)
|
698 |
+
|
699 |
+
attn_modules = [module for module in all_modules if isinstance(module, BasicTransformerBlock)]
|
700 |
+
attn_modules = sorted(attn_modules, key=lambda x: - x.norm1.normalized_shape[0])
|
701 |
+
|
702 |
+
for i, module in enumerate(attn_modules):
|
703 |
+
if getattr(module, '_original_inner_forward', None) is None:
|
704 |
+
module._original_inner_forward = module._forward
|
705 |
+
module._forward = hacked_basic_transformer_inner_forward.__get__(module, BasicTransformerBlock)
|
706 |
+
module.bank = []
|
707 |
+
module.style_cfgs = []
|
708 |
+
module.attn_weight = float(i) / float(len(attn_modules))
|
709 |
+
|
710 |
+
gn_modules = [model.middle_block]
|
711 |
+
model.middle_block.gn_weight = 0
|
712 |
+
|
713 |
+
input_block_indices = [4, 5, 7, 8, 10, 11]
|
714 |
+
for w, i in enumerate(input_block_indices):
|
715 |
+
module = model.input_blocks[i]
|
716 |
+
module.gn_weight = 1.0 - float(w) / float(len(input_block_indices))
|
717 |
+
gn_modules.append(module)
|
718 |
+
|
719 |
+
output_block_indices = [0, 1, 2, 3, 4, 5, 6, 7]
|
720 |
+
for w, i in enumerate(output_block_indices):
|
721 |
+
module = model.output_blocks[i]
|
722 |
+
module.gn_weight = float(w) / float(len(output_block_indices))
|
723 |
+
gn_modules.append(module)
|
724 |
+
|
725 |
+
for i, module in enumerate(gn_modules):
|
726 |
+
if getattr(module, 'original_forward', None) is None:
|
727 |
+
module.original_forward = module.forward
|
728 |
+
module.forward = hacked_group_norm_forward.__get__(module, torch.nn.Module)
|
729 |
+
module.mean_bank = []
|
730 |
+
module.var_bank = []
|
731 |
+
module.style_cfgs = []
|
732 |
+
module.gn_weight *= 2
|
733 |
+
|
734 |
+
outer.attn_module_list = attn_modules
|
735 |
+
outer.gn_module_list = gn_modules
|
736 |
+
|
737 |
+
scripts.script_callbacks.on_cfg_denoiser(self.guidance_schedule_handler)
|
738 |
+
|
739 |
+
def restore(self, model):
|
740 |
+
scripts.script_callbacks.remove_callbacks_for_function(self.guidance_schedule_handler)
|
741 |
+
if hasattr(self, "control_params"):
|
742 |
+
del self.control_params
|
743 |
+
|
744 |
+
if not hasattr(model, "_original_forward"):
|
745 |
+
# no such handle, ignore
|
746 |
+
return
|
747 |
+
|
748 |
+
model.forward = model._original_forward
|
749 |
+
del model._original_forward
|
extensions/microsoftexcel-controlnet/scripts/lvminthin.py
ADDED
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# High Quality Edge Thinning using Pure Python
|
2 |
+
# Written by Lvmin Zhang
|
3 |
+
# 2023 April
|
4 |
+
# Stanford University
|
5 |
+
# If you use this, please Cite "High Quality Edge Thinning using Pure Python", Lvmin Zhang, In Mikubill/sd-webui-controlnet.
|
6 |
+
|
7 |
+
|
8 |
+
import cv2
|
9 |
+
import numpy as np
|
10 |
+
|
11 |
+
|
12 |
+
lvmin_kernels_raw = [
|
13 |
+
np.array([
|
14 |
+
[-1, -1, -1],
|
15 |
+
[0, 1, 0],
|
16 |
+
[1, 1, 1]
|
17 |
+
], dtype=np.int32),
|
18 |
+
np.array([
|
19 |
+
[0, -1, -1],
|
20 |
+
[1, 1, -1],
|
21 |
+
[0, 1, 0]
|
22 |
+
], dtype=np.int32)
|
23 |
+
]
|
24 |
+
|
25 |
+
lvmin_kernels = []
|
26 |
+
lvmin_kernels += [np.rot90(x, k=0, axes=(0, 1)) for x in lvmin_kernels_raw]
|
27 |
+
lvmin_kernels += [np.rot90(x, k=1, axes=(0, 1)) for x in lvmin_kernels_raw]
|
28 |
+
lvmin_kernels += [np.rot90(x, k=2, axes=(0, 1)) for x in lvmin_kernels_raw]
|
29 |
+
lvmin_kernels += [np.rot90(x, k=3, axes=(0, 1)) for x in lvmin_kernels_raw]
|
30 |
+
|
31 |
+
lvmin_prunings_raw = [
|
32 |
+
np.array([
|
33 |
+
[-1, -1, -1],
|
34 |
+
[-1, 1, -1],
|
35 |
+
[0, 0, -1]
|
36 |
+
], dtype=np.int32),
|
37 |
+
np.array([
|
38 |
+
[-1, -1, -1],
|
39 |
+
[-1, 1, -1],
|
40 |
+
[-1, 0, 0]
|
41 |
+
], dtype=np.int32)
|
42 |
+
]
|
43 |
+
|
44 |
+
lvmin_prunings = []
|
45 |
+
lvmin_prunings += [np.rot90(x, k=0, axes=(0, 1)) for x in lvmin_prunings_raw]
|
46 |
+
lvmin_prunings += [np.rot90(x, k=1, axes=(0, 1)) for x in lvmin_prunings_raw]
|
47 |
+
lvmin_prunings += [np.rot90(x, k=2, axes=(0, 1)) for x in lvmin_prunings_raw]
|
48 |
+
lvmin_prunings += [np.rot90(x, k=3, axes=(0, 1)) for x in lvmin_prunings_raw]
|
49 |
+
|
50 |
+
|
51 |
+
def remove_pattern(x, kernel):
|
52 |
+
objects = cv2.morphologyEx(x, cv2.MORPH_HITMISS, kernel)
|
53 |
+
objects = np.where(objects > 127)
|
54 |
+
x[objects] = 0
|
55 |
+
return x, objects[0].shape[0] > 0
|
56 |
+
|
57 |
+
|
58 |
+
def thin_one_time(x, kernels):
|
59 |
+
y = x
|
60 |
+
is_done = True
|
61 |
+
for k in kernels:
|
62 |
+
y, has_update = remove_pattern(y, k)
|
63 |
+
if has_update:
|
64 |
+
is_done = False
|
65 |
+
return y, is_done
|
66 |
+
|
67 |
+
|
68 |
+
def lvmin_thin(x, prunings=True):
|
69 |
+
y = x
|
70 |
+
for i in range(32):
|
71 |
+
y, is_done = thin_one_time(y, lvmin_kernels)
|
72 |
+
if is_done:
|
73 |
+
break
|
74 |
+
if prunings:
|
75 |
+
y, _ = thin_one_time(y, lvmin_prunings)
|
76 |
+
return y
|
77 |
+
|
78 |
+
|
79 |
+
def nake_nms(x):
|
80 |
+
f1 = np.array([[0, 0, 0], [1, 1, 1], [0, 0, 0]], dtype=np.uint8)
|
81 |
+
f2 = np.array([[0, 1, 0], [0, 1, 0], [0, 1, 0]], dtype=np.uint8)
|
82 |
+
f3 = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]], dtype=np.uint8)
|
83 |
+
f4 = np.array([[0, 0, 1], [0, 1, 0], [1, 0, 0]], dtype=np.uint8)
|
84 |
+
y = np.zeros_like(x)
|
85 |
+
for f in [f1, f2, f3, f4]:
|
86 |
+
np.putmask(y, cv2.dilate(x, kernel=f) == x, x)
|
87 |
+
return y
|
88 |
+
|
extensions/microsoftexcel-controlnet/scripts/movie2movie.py
ADDED
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import os
|
3 |
+
import shutil
|
4 |
+
|
5 |
+
import cv2
|
6 |
+
import gradio as gr
|
7 |
+
import modules.scripts as scripts
|
8 |
+
|
9 |
+
from modules import images
|
10 |
+
from modules.processing import process_images
|
11 |
+
from modules.shared import opts
|
12 |
+
from PIL import Image
|
13 |
+
|
14 |
+
import numpy as np
|
15 |
+
|
16 |
+
_BASEDIR = "/controlnet-m2m"
|
17 |
+
_BASEFILE = "animation"
|
18 |
+
|
19 |
+
def get_all_frames(video_path):
|
20 |
+
if video_path is None:
|
21 |
+
return None
|
22 |
+
cap = cv2.VideoCapture(video_path)
|
23 |
+
frame_list = []
|
24 |
+
if not cap.isOpened():
|
25 |
+
return
|
26 |
+
while True:
|
27 |
+
ret, frame = cap.read()
|
28 |
+
if ret:
|
29 |
+
frame_list.append(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
|
30 |
+
else:
|
31 |
+
return frame_list
|
32 |
+
|
33 |
+
def get_min_frame_num(video_list):
|
34 |
+
min_frame_num = -1
|
35 |
+
for video in video_list:
|
36 |
+
if video is None:
|
37 |
+
continue
|
38 |
+
else:
|
39 |
+
frame_num = len(video)
|
40 |
+
print(frame_num)
|
41 |
+
if min_frame_num < 0:
|
42 |
+
min_frame_num = frame_num
|
43 |
+
elif frame_num < min_frame_num:
|
44 |
+
min_frame_num = frame_num
|
45 |
+
return min_frame_num
|
46 |
+
|
47 |
+
def pil2cv(image):
|
48 |
+
new_image = np.array(image, dtype=np.uint8)
|
49 |
+
if new_image.ndim == 2:
|
50 |
+
pass
|
51 |
+
elif new_image.shape[2] == 3:
|
52 |
+
new_image = new_image[:, :, ::-1]
|
53 |
+
elif new_image.shape[2] == 4:
|
54 |
+
new_image = new_image[:, :, [2, 1, 0, 3]]
|
55 |
+
return new_image
|
56 |
+
|
57 |
+
|
58 |
+
def save_gif(path, image_list, name, duration):
|
59 |
+
tmp_dir = path + "/tmp/"
|
60 |
+
if os.path.isdir(tmp_dir):
|
61 |
+
shutil.rmtree(tmp_dir)
|
62 |
+
os.mkdir(tmp_dir)
|
63 |
+
for i, image in enumerate(image_list):
|
64 |
+
images.save_image(image, tmp_dir, f"output_{i}")
|
65 |
+
|
66 |
+
os.makedirs(f"{path}{_BASEDIR}", exist_ok=True)
|
67 |
+
|
68 |
+
image_list[0].save(f"{path}{_BASEDIR}/{name}.gif", save_all=True, append_images=image_list[1:], optimize=False, duration=duration, loop=0)
|
69 |
+
|
70 |
+
|
71 |
+
class Script(scripts.Script):
|
72 |
+
|
73 |
+
def title(self):
|
74 |
+
return "controlnet m2m"
|
75 |
+
|
76 |
+
def show(self, is_img2img):
|
77 |
+
return True
|
78 |
+
|
79 |
+
def ui(self, is_img2img):
|
80 |
+
# How the script's is displayed in the UI. See https://gradio.app/docs/#components
|
81 |
+
# for the different UI components you can use and how to create them.
|
82 |
+
# Most UI components can return a value, such as a boolean for a checkbox.
|
83 |
+
# The returned values are passed to the run method as parameters.
|
84 |
+
|
85 |
+
ctrls_group = ()
|
86 |
+
max_models = opts.data.get("control_net_max_models_num", 1)
|
87 |
+
|
88 |
+
with gr.Group():
|
89 |
+
with gr.Accordion("ControlNet-M2M", open = False):
|
90 |
+
duration = gr.Slider(label=f"Duration", value=50.0, minimum=10.0, maximum=200.0, step=10, interactive=True, elem_id='controlnet_movie2movie_duration_slider')
|
91 |
+
with gr.Tabs():
|
92 |
+
for i in range(max_models):
|
93 |
+
with gr.Tab(f"ControlNet-{i}"):
|
94 |
+
with gr.TabItem("Movie Input"):
|
95 |
+
ctrls_group += (gr.Video(format='mp4', source='upload', elem_id = f"video_{i}"), )
|
96 |
+
with gr.TabItem("Image Input"):
|
97 |
+
ctrls_group += (gr.Image(source='upload', brush_radius=20, mirror_webcam=False, type='numpy', tool='sketch', elem_id=f'image_{i}'), )
|
98 |
+
ctrls_group += (gr.Checkbox(label=f"Save preprocessed", value=False, elem_id = f"save_pre_{i}"),)
|
99 |
+
|
100 |
+
ctrls_group += (duration,)
|
101 |
+
|
102 |
+
return ctrls_group
|
103 |
+
|
104 |
+
def run(self, p, *args):
|
105 |
+
# This is where the additional processing is implemented. The parameters include
|
106 |
+
# self, the model object "p" (a StableDiffusionProcessing class, see
|
107 |
+
# processing.py), and the parameters returned by the ui method.
|
108 |
+
# Custom functions can be defined here, and additional libraries can be imported
|
109 |
+
# to be used in processing. The return value should be a Processed object, which is
|
110 |
+
# what is returned by the process_images method.
|
111 |
+
|
112 |
+
contents_num = opts.data.get("control_net_max_models_num", 1)
|
113 |
+
arg_num = 3
|
114 |
+
item_list = []
|
115 |
+
video_list = []
|
116 |
+
for input_set in [tuple(args[:contents_num * arg_num][i:i+3]) for i in range(0, len(args[:contents_num * arg_num]), arg_num)]:
|
117 |
+
if input_set[0] is not None:
|
118 |
+
item_list.append([get_all_frames(input_set[0]), "video"])
|
119 |
+
video_list.append(get_all_frames(input_set[0]))
|
120 |
+
if input_set[1] is not None:
|
121 |
+
item_list.append([cv2.cvtColor(pil2cv(input_set[1]["image"]), cv2.COLOR_BGRA2RGB), "image"])
|
122 |
+
|
123 |
+
save_pre = list(args[2:contents_num * arg_num:3])
|
124 |
+
item_num = len(item_list)
|
125 |
+
video_num = len(video_list)
|
126 |
+
duration, = args[contents_num * arg_num:]
|
127 |
+
|
128 |
+
frame_num = get_min_frame_num(video_list)
|
129 |
+
if frame_num > 0:
|
130 |
+
output_image_list = []
|
131 |
+
pre_output_image_list = []
|
132 |
+
for i in range(item_num):
|
133 |
+
pre_output_image_list.append([])
|
134 |
+
|
135 |
+
for frame in range(frame_num):
|
136 |
+
copy_p = copy.copy(p)
|
137 |
+
copy_p.control_net_input_image = []
|
138 |
+
for item in item_list:
|
139 |
+
if item[1] == "video":
|
140 |
+
copy_p.control_net_input_image.append(item[0][frame])
|
141 |
+
elif item[1] == "image":
|
142 |
+
copy_p.control_net_input_image.append(item[0])
|
143 |
+
else:
|
144 |
+
continue
|
145 |
+
|
146 |
+
proc = process_images(copy_p)
|
147 |
+
img = proc.images[0]
|
148 |
+
output_image_list.append(img)
|
149 |
+
|
150 |
+
for i in range(len(save_pre)):
|
151 |
+
if save_pre[i]:
|
152 |
+
try:
|
153 |
+
pre_output_image_list[i].append(proc.images[i + 1])
|
154 |
+
except:
|
155 |
+
print(f"proc.images[{i} failed")
|
156 |
+
|
157 |
+
copy_p.close()
|
158 |
+
|
159 |
+
# filename format is seq-seed-animation.gif seq is 5 places left filled with 0
|
160 |
+
|
161 |
+
seq = images.get_next_sequence_number(f"{p.outpath_samples}{_BASEDIR}", "")
|
162 |
+
filename = f"{seq:05}-{proc.seed}-{_BASEFILE}"
|
163 |
+
save_gif(p.outpath_samples, output_image_list, filename, duration)
|
164 |
+
proc.images = [f"{p.outpath_samples}{_BASEDIR}/{filename}.gif"]
|
165 |
+
|
166 |
+
|
167 |
+
for i in range(len(save_pre)):
|
168 |
+
if save_pre[i]:
|
169 |
+
# control files add -controlX.gif where X is the controlnet number
|
170 |
+
save_gif(p.outpath_samples, pre_output_image_list[i], f"{filename}-control{i}", duration)
|
171 |
+
proc.images.append(f"{p.outpath_samples}{_BASEDIR}/{filename}-control{i}.gif")
|
172 |
+
|
173 |
+
else:
|
174 |
+
proc = process_images(p)
|
175 |
+
|
176 |
+
return proc
|
extensions/microsoftexcel-controlnet/scripts/processor.py
ADDED
@@ -0,0 +1,871 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import cv2
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
from annotator.util import HWC3
|
5 |
+
from typing import Callable, Tuple
|
6 |
+
|
7 |
+
|
8 |
+
def pad64(x):
|
9 |
+
return int(np.ceil(float(x) / 64.0) * 64 - x)
|
10 |
+
|
11 |
+
|
12 |
+
def safer_memory(x):
|
13 |
+
# Fix many MAC/AMD problems
|
14 |
+
return np.ascontiguousarray(x.copy()).copy()
|
15 |
+
|
16 |
+
|
17 |
+
def resize_image_with_pad(input_image, resolution):
|
18 |
+
img = HWC3(input_image)
|
19 |
+
H_raw, W_raw, _ = img.shape
|
20 |
+
k = float(resolution) / float(min(H_raw, W_raw))
|
21 |
+
interpolation = cv2.INTER_CUBIC if k > 1 else cv2.INTER_AREA
|
22 |
+
H_target = int(np.round(float(H_raw) * k))
|
23 |
+
W_target = int(np.round(float(W_raw) * k))
|
24 |
+
img = cv2.resize(img, (W_target, H_target), interpolation=interpolation)
|
25 |
+
H_pad, W_pad = pad64(H_target), pad64(W_target)
|
26 |
+
img_padded = np.pad(img, [[0, H_pad], [0, W_pad], [0, 0]], mode='edge')
|
27 |
+
|
28 |
+
def remove_pad(x):
|
29 |
+
return safer_memory(x[:H_target, :W_target])
|
30 |
+
|
31 |
+
return safer_memory(img_padded), remove_pad
|
32 |
+
|
33 |
+
|
34 |
+
model_canny = None
|
35 |
+
|
36 |
+
|
37 |
+
def canny(img, res=512, thr_a=100, thr_b=200, **kwargs):
|
38 |
+
l, h = thr_a, thr_b
|
39 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
40 |
+
global model_canny
|
41 |
+
if model_canny is None:
|
42 |
+
from annotator.canny import apply_canny
|
43 |
+
model_canny = apply_canny
|
44 |
+
result = model_canny(img, l, h)
|
45 |
+
return remove_pad(result), True
|
46 |
+
|
47 |
+
|
48 |
+
def scribble_thr(img, res=512, **kwargs):
|
49 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
50 |
+
result = np.zeros_like(img, dtype=np.uint8)
|
51 |
+
result[np.min(img, axis=2) < 127] = 255
|
52 |
+
return remove_pad(result), True
|
53 |
+
|
54 |
+
|
55 |
+
def scribble_xdog(img, res=512, thr_a=32, **kwargs):
|
56 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
57 |
+
g1 = cv2.GaussianBlur(img.astype(np.float32), (0, 0), 0.5)
|
58 |
+
g2 = cv2.GaussianBlur(img.astype(np.float32), (0, 0), 5.0)
|
59 |
+
dog = (255 - np.min(g2 - g1, axis=2)).clip(0, 255).astype(np.uint8)
|
60 |
+
result = np.zeros_like(img, dtype=np.uint8)
|
61 |
+
result[2 * (255 - dog) > thr_a] = 255
|
62 |
+
return remove_pad(result), True
|
63 |
+
|
64 |
+
|
65 |
+
def tile_resample(img, res=512, thr_a=1.0, **kwargs):
|
66 |
+
img = HWC3(img)
|
67 |
+
if thr_a < 1.1:
|
68 |
+
return img, True
|
69 |
+
H, W, C = img.shape
|
70 |
+
H = int(float(H) / float(thr_a))
|
71 |
+
W = int(float(W) / float(thr_a))
|
72 |
+
img = cv2.resize(img, (W, H), interpolation=cv2.INTER_AREA)
|
73 |
+
return img, True
|
74 |
+
|
75 |
+
|
76 |
+
def threshold(img, res=512, thr_a=127, **kwargs):
|
77 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
78 |
+
result = np.zeros_like(img, dtype=np.uint8)
|
79 |
+
result[np.min(img, axis=2) > thr_a] = 255
|
80 |
+
return remove_pad(result), True
|
81 |
+
|
82 |
+
|
83 |
+
def identity(img, **kwargs):
|
84 |
+
return img, True
|
85 |
+
|
86 |
+
|
87 |
+
def invert(img, res=512, **kwargs):
|
88 |
+
return 255 - HWC3(img), True
|
89 |
+
|
90 |
+
|
91 |
+
model_hed = None
|
92 |
+
|
93 |
+
|
94 |
+
def hed(img, res=512, **kwargs):
|
95 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
96 |
+
global model_hed
|
97 |
+
if model_hed is None:
|
98 |
+
from annotator.hed import apply_hed
|
99 |
+
model_hed = apply_hed
|
100 |
+
result = model_hed(img)
|
101 |
+
return remove_pad(result), True
|
102 |
+
|
103 |
+
|
104 |
+
def hed_safe(img, res=512, **kwargs):
|
105 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
106 |
+
global model_hed
|
107 |
+
if model_hed is None:
|
108 |
+
from annotator.hed import apply_hed
|
109 |
+
model_hed = apply_hed
|
110 |
+
result = model_hed(img, is_safe=True)
|
111 |
+
return remove_pad(result), True
|
112 |
+
|
113 |
+
|
114 |
+
def unload_hed():
|
115 |
+
global model_hed
|
116 |
+
if model_hed is not None:
|
117 |
+
from annotator.hed import unload_hed_model
|
118 |
+
unload_hed_model()
|
119 |
+
|
120 |
+
|
121 |
+
def scribble_hed(img, res=512, **kwargs):
|
122 |
+
result, _ = hed(img, res)
|
123 |
+
import cv2
|
124 |
+
from annotator.util import nms
|
125 |
+
result = nms(result, 127, 3.0)
|
126 |
+
result = cv2.GaussianBlur(result, (0, 0), 3.0)
|
127 |
+
result[result > 4] = 255
|
128 |
+
result[result < 255] = 0
|
129 |
+
return result, True
|
130 |
+
|
131 |
+
|
132 |
+
model_mediapipe_face = None
|
133 |
+
|
134 |
+
|
135 |
+
def mediapipe_face(img, res=512, thr_a: int = 10, thr_b: float = 0.5, **kwargs):
|
136 |
+
max_faces = int(thr_a)
|
137 |
+
min_confidence = thr_b
|
138 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
139 |
+
global model_mediapipe_face
|
140 |
+
if model_mediapipe_face is None:
|
141 |
+
from annotator.mediapipe_face import apply_mediapipe_face
|
142 |
+
model_mediapipe_face = apply_mediapipe_face
|
143 |
+
result = model_mediapipe_face(img, max_faces=max_faces, min_confidence=min_confidence)
|
144 |
+
return remove_pad(result), True
|
145 |
+
|
146 |
+
|
147 |
+
model_mlsd = None
|
148 |
+
|
149 |
+
|
150 |
+
def mlsd(img, res=512, thr_a=0.1, thr_b=0.1, **kwargs):
|
151 |
+
thr_v, thr_d = thr_a, thr_b
|
152 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
153 |
+
global model_mlsd
|
154 |
+
if model_mlsd is None:
|
155 |
+
from annotator.mlsd import apply_mlsd
|
156 |
+
model_mlsd = apply_mlsd
|
157 |
+
result = model_mlsd(img, thr_v, thr_d)
|
158 |
+
return remove_pad(result), True
|
159 |
+
|
160 |
+
|
161 |
+
def unload_mlsd():
|
162 |
+
global model_mlsd
|
163 |
+
if model_mlsd is not None:
|
164 |
+
from annotator.mlsd import unload_mlsd_model
|
165 |
+
unload_mlsd_model()
|
166 |
+
|
167 |
+
|
168 |
+
model_midas = None
|
169 |
+
|
170 |
+
|
171 |
+
def midas(img, res=512, a=np.pi * 2.0, **kwargs):
|
172 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
173 |
+
global model_midas
|
174 |
+
if model_midas is None:
|
175 |
+
from annotator.midas import apply_midas
|
176 |
+
model_midas = apply_midas
|
177 |
+
result, _ = model_midas(img, a)
|
178 |
+
return remove_pad(result), True
|
179 |
+
|
180 |
+
|
181 |
+
def midas_normal(img, res=512, a=np.pi * 2.0, thr_a=0.4, **kwargs): # bg_th -> thr_a
|
182 |
+
bg_th = thr_a
|
183 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
184 |
+
global model_midas
|
185 |
+
if model_midas is None:
|
186 |
+
from annotator.midas import apply_midas
|
187 |
+
model_midas = apply_midas
|
188 |
+
_, result = model_midas(img, a, bg_th)
|
189 |
+
return remove_pad(result), True
|
190 |
+
|
191 |
+
|
192 |
+
def unload_midas():
|
193 |
+
global model_midas
|
194 |
+
if model_midas is not None:
|
195 |
+
from annotator.midas import unload_midas_model
|
196 |
+
unload_midas_model()
|
197 |
+
|
198 |
+
|
199 |
+
model_leres = None
|
200 |
+
|
201 |
+
|
202 |
+
def leres(img, res=512, a=np.pi * 2.0, thr_a=0, thr_b=0, boost=False, **kwargs):
|
203 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
204 |
+
global model_leres
|
205 |
+
if model_leres is None:
|
206 |
+
from annotator.leres import apply_leres
|
207 |
+
model_leres = apply_leres
|
208 |
+
result = model_leres(img, thr_a, thr_b, boost=boost)
|
209 |
+
return remove_pad(result), True
|
210 |
+
|
211 |
+
|
212 |
+
def unload_leres():
|
213 |
+
global model_leres
|
214 |
+
if model_leres is not None:
|
215 |
+
from annotator.leres import unload_leres_model
|
216 |
+
unload_leres_model()
|
217 |
+
|
218 |
+
|
219 |
+
class OpenposeModel(object):
|
220 |
+
def __init__(self) -> None:
|
221 |
+
self.model_openpose = None
|
222 |
+
|
223 |
+
def run_model(
|
224 |
+
self,
|
225 |
+
img: np.ndarray,
|
226 |
+
include_body: bool,
|
227 |
+
include_hand: bool,
|
228 |
+
include_face: bool,
|
229 |
+
json_pose_callback: Callable[[str], None] = None,
|
230 |
+
res: int = 512,
|
231 |
+
**kwargs # Ignore rest of kwargs
|
232 |
+
) -> Tuple[np.ndarray, bool]:
|
233 |
+
"""Run the openpose model. Returns a tuple of
|
234 |
+
- result image
|
235 |
+
- is_image flag
|
236 |
+
|
237 |
+
The JSON format pose string is passed to `json_pose_callback`.
|
238 |
+
"""
|
239 |
+
if json_pose_callback is None:
|
240 |
+
json_pose_callback = lambda x: None
|
241 |
+
|
242 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
243 |
+
|
244 |
+
if self.model_openpose is None:
|
245 |
+
from annotator.openpose import OpenposeDetector
|
246 |
+
self.model_openpose = OpenposeDetector()
|
247 |
+
|
248 |
+
return remove_pad(self.model_openpose(
|
249 |
+
img,
|
250 |
+
include_body=include_body,
|
251 |
+
include_hand=include_hand,
|
252 |
+
include_face=include_face,
|
253 |
+
json_pose_callback=json_pose_callback
|
254 |
+
)), True
|
255 |
+
|
256 |
+
def unload(self):
|
257 |
+
if self.model_openpose is not None:
|
258 |
+
self.model_openpose.unload_model()
|
259 |
+
|
260 |
+
|
261 |
+
g_openpose_model = OpenposeModel()
|
262 |
+
|
263 |
+
model_uniformer = None
|
264 |
+
|
265 |
+
|
266 |
+
def uniformer(img, res=512, **kwargs):
|
267 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
268 |
+
global model_uniformer
|
269 |
+
if model_uniformer is None:
|
270 |
+
from annotator.uniformer import apply_uniformer
|
271 |
+
model_uniformer = apply_uniformer
|
272 |
+
result = model_uniformer(img)
|
273 |
+
return remove_pad(result), True
|
274 |
+
|
275 |
+
|
276 |
+
def unload_uniformer():
|
277 |
+
global model_uniformer
|
278 |
+
if model_uniformer is not None:
|
279 |
+
from annotator.uniformer import unload_uniformer_model
|
280 |
+
unload_uniformer_model()
|
281 |
+
|
282 |
+
|
283 |
+
model_pidinet = None
|
284 |
+
|
285 |
+
|
286 |
+
def pidinet(img, res=512, **kwargs):
|
287 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
288 |
+
global model_pidinet
|
289 |
+
if model_pidinet is None:
|
290 |
+
from annotator.pidinet import apply_pidinet
|
291 |
+
model_pidinet = apply_pidinet
|
292 |
+
result = model_pidinet(img)
|
293 |
+
return remove_pad(result), True
|
294 |
+
|
295 |
+
|
296 |
+
def pidinet_ts(img, res=512, **kwargs):
|
297 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
298 |
+
global model_pidinet
|
299 |
+
if model_pidinet is None:
|
300 |
+
from annotator.pidinet import apply_pidinet
|
301 |
+
model_pidinet = apply_pidinet
|
302 |
+
result = model_pidinet(img, apply_fliter=True)
|
303 |
+
return remove_pad(result), True
|
304 |
+
|
305 |
+
|
306 |
+
def pidinet_safe(img, res=512, **kwargs):
|
307 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
308 |
+
global model_pidinet
|
309 |
+
if model_pidinet is None:
|
310 |
+
from annotator.pidinet import apply_pidinet
|
311 |
+
model_pidinet = apply_pidinet
|
312 |
+
result = model_pidinet(img, is_safe=True)
|
313 |
+
return remove_pad(result), True
|
314 |
+
|
315 |
+
|
316 |
+
def scribble_pidinet(img, res=512, **kwargs):
|
317 |
+
result, _ = pidinet(img, res)
|
318 |
+
import cv2
|
319 |
+
from annotator.util import nms
|
320 |
+
result = nms(result, 127, 3.0)
|
321 |
+
result = cv2.GaussianBlur(result, (0, 0), 3.0)
|
322 |
+
result[result > 4] = 255
|
323 |
+
result[result < 255] = 0
|
324 |
+
return result, True
|
325 |
+
|
326 |
+
|
327 |
+
def unload_pidinet():
|
328 |
+
global model_pidinet
|
329 |
+
if model_pidinet is not None:
|
330 |
+
from annotator.pidinet import unload_pid_model
|
331 |
+
unload_pid_model()
|
332 |
+
|
333 |
+
|
334 |
+
clip_encoder = None
|
335 |
+
|
336 |
+
|
337 |
+
def clip(img, res=512, **kwargs):
|
338 |
+
img = HWC3(img)
|
339 |
+
global clip_encoder
|
340 |
+
if clip_encoder is None:
|
341 |
+
from annotator.clip import apply_clip
|
342 |
+
clip_encoder = apply_clip
|
343 |
+
result = clip_encoder(img)
|
344 |
+
return result, False
|
345 |
+
|
346 |
+
|
347 |
+
def clip_vision_visualization(x):
|
348 |
+
x = x.detach().cpu().numpy()[0]
|
349 |
+
x = np.ascontiguousarray(x).copy()
|
350 |
+
return np.ndarray((x.shape[0] * 4, x.shape[1]), dtype="uint8", buffer=x.tobytes())
|
351 |
+
|
352 |
+
|
353 |
+
def unload_clip():
|
354 |
+
global clip_encoder
|
355 |
+
if clip_encoder is not None:
|
356 |
+
from annotator.clip import unload_clip_model
|
357 |
+
unload_clip_model()
|
358 |
+
|
359 |
+
|
360 |
+
model_color = None
|
361 |
+
|
362 |
+
|
363 |
+
def color(img, res=512, **kwargs):
|
364 |
+
img = HWC3(img)
|
365 |
+
global model_color
|
366 |
+
if model_color is None:
|
367 |
+
from annotator.color import apply_color
|
368 |
+
model_color = apply_color
|
369 |
+
result = model_color(img, res=res)
|
370 |
+
return result, True
|
371 |
+
|
372 |
+
|
373 |
+
def lineart_standard(img, res=512, **kwargs):
|
374 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
375 |
+
x = img.astype(np.float32)
|
376 |
+
g = cv2.GaussianBlur(x, (0, 0), 6.0)
|
377 |
+
intensity = np.min(g - x, axis=2).clip(0, 255)
|
378 |
+
intensity /= max(16, np.median(intensity[intensity > 8]))
|
379 |
+
intensity *= 127
|
380 |
+
result = intensity.clip(0, 255).astype(np.uint8)
|
381 |
+
return remove_pad(result), True
|
382 |
+
|
383 |
+
|
384 |
+
model_lineart = None
|
385 |
+
|
386 |
+
|
387 |
+
def lineart(img, res=512, **kwargs):
|
388 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
389 |
+
global model_lineart
|
390 |
+
if model_lineart is None:
|
391 |
+
from annotator.lineart import LineartDetector
|
392 |
+
model_lineart = LineartDetector(LineartDetector.model_default)
|
393 |
+
|
394 |
+
# applied auto inversion
|
395 |
+
result = 255 - model_lineart(img)
|
396 |
+
return remove_pad(result), True
|
397 |
+
|
398 |
+
|
399 |
+
def unload_lineart():
|
400 |
+
global model_lineart
|
401 |
+
if model_lineart is not None:
|
402 |
+
model_lineart.unload_model()
|
403 |
+
|
404 |
+
|
405 |
+
model_lineart_coarse = None
|
406 |
+
|
407 |
+
|
408 |
+
def lineart_coarse(img, res=512, **kwargs):
|
409 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
410 |
+
global model_lineart_coarse
|
411 |
+
if model_lineart_coarse is None:
|
412 |
+
from annotator.lineart import LineartDetector
|
413 |
+
model_lineart_coarse = LineartDetector(LineartDetector.model_coarse)
|
414 |
+
|
415 |
+
# applied auto inversion
|
416 |
+
result = 255 - model_lineart_coarse(img)
|
417 |
+
return remove_pad(result), True
|
418 |
+
|
419 |
+
|
420 |
+
def unload_lineart_coarse():
|
421 |
+
global model_lineart_coarse
|
422 |
+
if model_lineart_coarse is not None:
|
423 |
+
model_lineart_coarse.unload_model()
|
424 |
+
|
425 |
+
|
426 |
+
model_lineart_anime = None
|
427 |
+
|
428 |
+
|
429 |
+
def lineart_anime(img, res=512, **kwargs):
|
430 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
431 |
+
global model_lineart_anime
|
432 |
+
if model_lineart_anime is None:
|
433 |
+
from annotator.lineart_anime import LineartAnimeDetector
|
434 |
+
model_lineart_anime = LineartAnimeDetector()
|
435 |
+
|
436 |
+
# applied auto inversion
|
437 |
+
result = 255 - model_lineart_anime(img)
|
438 |
+
return remove_pad(result), True
|
439 |
+
|
440 |
+
|
441 |
+
def unload_lineart_anime():
|
442 |
+
global model_lineart_anime
|
443 |
+
if model_lineart_anime is not None:
|
444 |
+
model_lineart_anime.unload_model()
|
445 |
+
|
446 |
+
|
447 |
+
model_manga_line = None
|
448 |
+
|
449 |
+
|
450 |
+
def lineart_anime_denoise(img, res=512, **kwargs):
|
451 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
452 |
+
global model_manga_line
|
453 |
+
if model_manga_line is None:
|
454 |
+
from annotator.manga_line import MangaLineExtration
|
455 |
+
model_manga_line = MangaLineExtration()
|
456 |
+
|
457 |
+
# applied auto inversion
|
458 |
+
result = model_manga_line(img)
|
459 |
+
return remove_pad(result), True
|
460 |
+
|
461 |
+
|
462 |
+
def unload_lineart_anime_denoise():
|
463 |
+
global model_manga_line
|
464 |
+
if model_manga_line is not None:
|
465 |
+
model_manga_line.unload_model()
|
466 |
+
|
467 |
+
|
468 |
+
model_zoe_depth = None
|
469 |
+
|
470 |
+
|
471 |
+
def zoe_depth(img, res=512, **kwargs):
|
472 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
473 |
+
global model_zoe_depth
|
474 |
+
if model_zoe_depth is None:
|
475 |
+
from annotator.zoe import ZoeDetector
|
476 |
+
model_zoe_depth = ZoeDetector()
|
477 |
+
result = model_zoe_depth(img)
|
478 |
+
return remove_pad(result), True
|
479 |
+
|
480 |
+
|
481 |
+
def unload_zoe_depth():
|
482 |
+
global model_zoe_depth
|
483 |
+
if model_zoe_depth is not None:
|
484 |
+
model_zoe_depth.unload_model()
|
485 |
+
|
486 |
+
|
487 |
+
model_normal_bae = None
|
488 |
+
|
489 |
+
|
490 |
+
def normal_bae(img, res=512, **kwargs):
|
491 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
492 |
+
global model_normal_bae
|
493 |
+
if model_normal_bae is None:
|
494 |
+
from annotator.normalbae import NormalBaeDetector
|
495 |
+
model_normal_bae = NormalBaeDetector()
|
496 |
+
result = model_normal_bae(img)
|
497 |
+
return remove_pad(result), True
|
498 |
+
|
499 |
+
|
500 |
+
def unload_normal_bae():
|
501 |
+
global model_normal_bae
|
502 |
+
if model_normal_bae is not None:
|
503 |
+
model_normal_bae.unload_model()
|
504 |
+
|
505 |
+
|
506 |
+
model_oneformer_coco = None
|
507 |
+
|
508 |
+
|
509 |
+
def oneformer_coco(img, res=512, **kwargs):
|
510 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
511 |
+
global model_oneformer_coco
|
512 |
+
if model_oneformer_coco is None:
|
513 |
+
from annotator.oneformer import OneformerDetector
|
514 |
+
model_oneformer_coco = OneformerDetector(OneformerDetector.configs["coco"])
|
515 |
+
result = model_oneformer_coco(img)
|
516 |
+
return remove_pad(result), True
|
517 |
+
|
518 |
+
|
519 |
+
def unload_oneformer_coco():
|
520 |
+
global model_oneformer_coco
|
521 |
+
if model_oneformer_coco is not None:
|
522 |
+
model_oneformer_coco.unload_model()
|
523 |
+
|
524 |
+
|
525 |
+
model_oneformer_ade20k = None
|
526 |
+
|
527 |
+
|
528 |
+
def oneformer_ade20k(img, res=512, **kwargs):
|
529 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
530 |
+
global model_oneformer_ade20k
|
531 |
+
if model_oneformer_ade20k is None:
|
532 |
+
from annotator.oneformer import OneformerDetector
|
533 |
+
model_oneformer_ade20k = OneformerDetector(OneformerDetector.configs["ade20k"])
|
534 |
+
result = model_oneformer_ade20k(img)
|
535 |
+
return remove_pad(result), True
|
536 |
+
|
537 |
+
|
538 |
+
def unload_oneformer_ade20k():
|
539 |
+
global model_oneformer_ade20k
|
540 |
+
if model_oneformer_ade20k is not None:
|
541 |
+
model_oneformer_ade20k.unload_model()
|
542 |
+
|
543 |
+
|
544 |
+
model_shuffle = None
|
545 |
+
|
546 |
+
|
547 |
+
def shuffle(img, res=512, **kwargs):
|
548 |
+
img, remove_pad = resize_image_with_pad(img, res)
|
549 |
+
img = remove_pad(img)
|
550 |
+
global model_shuffle
|
551 |
+
if model_shuffle is None:
|
552 |
+
from annotator.shuffle import ContentShuffleDetector
|
553 |
+
model_shuffle = ContentShuffleDetector()
|
554 |
+
result = model_shuffle(img)
|
555 |
+
return result, True
|
556 |
+
|
557 |
+
|
558 |
+
model_free_preprocessors = [
|
559 |
+
"reference_only",
|
560 |
+
"reference_adain",
|
561 |
+
"reference_adain+attn"
|
562 |
+
]
|
563 |
+
|
564 |
+
flag_preprocessor_resolution = "Preprocessor Resolution"
|
565 |
+
preprocessor_sliders_config = {
|
566 |
+
"none": [],
|
567 |
+
"inpaint": [],
|
568 |
+
"inpaint_only": [],
|
569 |
+
"canny": [
|
570 |
+
{
|
571 |
+
"name": flag_preprocessor_resolution,
|
572 |
+
"value": 512,
|
573 |
+
"min": 64,
|
574 |
+
"max": 2048
|
575 |
+
},
|
576 |
+
{
|
577 |
+
"name": "Canny Low Threshold",
|
578 |
+
"value": 100,
|
579 |
+
"min": 1,
|
580 |
+
"max": 255
|
581 |
+
},
|
582 |
+
{
|
583 |
+
"name": "Canny High Threshold",
|
584 |
+
"value": 200,
|
585 |
+
"min": 1,
|
586 |
+
"max": 255
|
587 |
+
},
|
588 |
+
],
|
589 |
+
"mlsd": [
|
590 |
+
{
|
591 |
+
"name": flag_preprocessor_resolution,
|
592 |
+
"min": 64,
|
593 |
+
"max": 2048,
|
594 |
+
"value": 512
|
595 |
+
},
|
596 |
+
{
|
597 |
+
"name": "MLSD Value Threshold",
|
598 |
+
"min": 0.01,
|
599 |
+
"max": 2.0,
|
600 |
+
"value": 0.1,
|
601 |
+
"step": 0.01
|
602 |
+
},
|
603 |
+
{
|
604 |
+
"name": "MLSD Distance Threshold",
|
605 |
+
"min": 0.01,
|
606 |
+
"max": 20.0,
|
607 |
+
"value": 0.1,
|
608 |
+
"step": 0.01
|
609 |
+
}
|
610 |
+
],
|
611 |
+
"hed": [
|
612 |
+
{
|
613 |
+
"name": flag_preprocessor_resolution,
|
614 |
+
"min": 64,
|
615 |
+
"max": 2048,
|
616 |
+
"value": 512
|
617 |
+
}
|
618 |
+
],
|
619 |
+
"scribble_hed": [
|
620 |
+
{
|
621 |
+
"name": flag_preprocessor_resolution,
|
622 |
+
"min": 64,
|
623 |
+
"max": 2048,
|
624 |
+
"value": 512
|
625 |
+
}
|
626 |
+
],
|
627 |
+
"hed_safe": [
|
628 |
+
{
|
629 |
+
"name": flag_preprocessor_resolution,
|
630 |
+
"min": 64,
|
631 |
+
"max": 2048,
|
632 |
+
"value": 512
|
633 |
+
}
|
634 |
+
],
|
635 |
+
"openpose": [
|
636 |
+
{
|
637 |
+
"name": flag_preprocessor_resolution,
|
638 |
+
"min": 64,
|
639 |
+
"max": 2048,
|
640 |
+
"value": 512
|
641 |
+
}
|
642 |
+
],
|
643 |
+
"openpose_full": [
|
644 |
+
{
|
645 |
+
"name": flag_preprocessor_resolution,
|
646 |
+
"min": 64,
|
647 |
+
"max": 2048,
|
648 |
+
"value": 512
|
649 |
+
}
|
650 |
+
],
|
651 |
+
"segmentation": [
|
652 |
+
{
|
653 |
+
"name": flag_preprocessor_resolution,
|
654 |
+
"min": 64,
|
655 |
+
"max": 2048,
|
656 |
+
"value": 512
|
657 |
+
}
|
658 |
+
],
|
659 |
+
"depth": [
|
660 |
+
{
|
661 |
+
"name": flag_preprocessor_resolution,
|
662 |
+
"min": 64,
|
663 |
+
"max": 2048,
|
664 |
+
"value": 512
|
665 |
+
}
|
666 |
+
],
|
667 |
+
"depth_leres": [
|
668 |
+
{
|
669 |
+
"name": flag_preprocessor_resolution,
|
670 |
+
"min": 64,
|
671 |
+
"max": 2048,
|
672 |
+
"value": 512
|
673 |
+
},
|
674 |
+
{
|
675 |
+
"name": "Remove Near %",
|
676 |
+
"min": 0,
|
677 |
+
"max": 100,
|
678 |
+
"value": 0,
|
679 |
+
"step": 0.1,
|
680 |
+
},
|
681 |
+
{
|
682 |
+
"name": "Remove Background %",
|
683 |
+
"min": 0,
|
684 |
+
"max": 100,
|
685 |
+
"value": 0,
|
686 |
+
"step": 0.1,
|
687 |
+
}
|
688 |
+
],
|
689 |
+
"depth_leres++": [
|
690 |
+
{
|
691 |
+
"name": flag_preprocessor_resolution,
|
692 |
+
"min": 64,
|
693 |
+
"max": 2048,
|
694 |
+
"value": 512
|
695 |
+
},
|
696 |
+
{
|
697 |
+
"name": "Remove Near %",
|
698 |
+
"min": 0,
|
699 |
+
"max": 100,
|
700 |
+
"value": 0,
|
701 |
+
"step": 0.1,
|
702 |
+
},
|
703 |
+
{
|
704 |
+
"name": "Remove Background %",
|
705 |
+
"min": 0,
|
706 |
+
"max": 100,
|
707 |
+
"value": 0,
|
708 |
+
"step": 0.1,
|
709 |
+
}
|
710 |
+
],
|
711 |
+
"normal_map": [
|
712 |
+
{
|
713 |
+
"name": flag_preprocessor_resolution,
|
714 |
+
"min": 64,
|
715 |
+
"max": 2048,
|
716 |
+
"value": 512
|
717 |
+
},
|
718 |
+
{
|
719 |
+
"name": "Normal Background Threshold",
|
720 |
+
"min": 0.0,
|
721 |
+
"max": 1.0,
|
722 |
+
"value": 0.4,
|
723 |
+
"step": 0.01
|
724 |
+
}
|
725 |
+
],
|
726 |
+
"threshold": [
|
727 |
+
{
|
728 |
+
"name": flag_preprocessor_resolution,
|
729 |
+
"value": 512,
|
730 |
+
"min": 64,
|
731 |
+
"max": 2048
|
732 |
+
},
|
733 |
+
{
|
734 |
+
"name": "Binarization Threshold",
|
735 |
+
"min": 0,
|
736 |
+
"max": 255,
|
737 |
+
"value": 127
|
738 |
+
}
|
739 |
+
],
|
740 |
+
|
741 |
+
"scribble_xdog": [
|
742 |
+
{
|
743 |
+
"name": flag_preprocessor_resolution,
|
744 |
+
"value": 512,
|
745 |
+
"min": 64,
|
746 |
+
"max": 2048
|
747 |
+
},
|
748 |
+
{
|
749 |
+
"name": "XDoG Threshold",
|
750 |
+
"min": 1,
|
751 |
+
"max": 64,
|
752 |
+
"value": 32,
|
753 |
+
}
|
754 |
+
],
|
755 |
+
"tile_resample": [
|
756 |
+
None,
|
757 |
+
{
|
758 |
+
"name": "Down Sampling Rate",
|
759 |
+
"value": 1.0,
|
760 |
+
"min": 1.0,
|
761 |
+
"max": 8.0,
|
762 |
+
"step": 0.01
|
763 |
+
}
|
764 |
+
],
|
765 |
+
"tile_colorfix": [
|
766 |
+
None,
|
767 |
+
{
|
768 |
+
"name": "Variation",
|
769 |
+
"value": 8.0,
|
770 |
+
"min": 3.0,
|
771 |
+
"max": 32.0,
|
772 |
+
"step": 1.0
|
773 |
+
}
|
774 |
+
],
|
775 |
+
"tile_colorfix+sharp": [
|
776 |
+
None,
|
777 |
+
{
|
778 |
+
"name": "Variation",
|
779 |
+
"value": 8.0,
|
780 |
+
"min": 3.0,
|
781 |
+
"max": 32.0,
|
782 |
+
"step": 1.0
|
783 |
+
},
|
784 |
+
{
|
785 |
+
"name": "Sharpness",
|
786 |
+
"value": 1.0,
|
787 |
+
"min": 0.0,
|
788 |
+
"max": 2.0,
|
789 |
+
"step": 0.01
|
790 |
+
}
|
791 |
+
],
|
792 |
+
"reference_only": [
|
793 |
+
None,
|
794 |
+
{
|
795 |
+
"name": r'Style Fidelity (only for "Balanced" mode)',
|
796 |
+
"value": 0.5,
|
797 |
+
"min": 0.0,
|
798 |
+
"max": 1.0,
|
799 |
+
"step": 0.01
|
800 |
+
}
|
801 |
+
],
|
802 |
+
"reference_adain": [
|
803 |
+
None,
|
804 |
+
{
|
805 |
+
"name": r'Style Fidelity (only for "Balanced" mode)',
|
806 |
+
"value": 0.5,
|
807 |
+
"min": 0.0,
|
808 |
+
"max": 1.0,
|
809 |
+
"step": 0.01
|
810 |
+
}
|
811 |
+
],
|
812 |
+
"reference_adain+attn": [
|
813 |
+
None,
|
814 |
+
{
|
815 |
+
"name": r'Style Fidelity (only for "Balanced" mode)',
|
816 |
+
"value": 0.5,
|
817 |
+
"min": 0.0,
|
818 |
+
"max": 1.0,
|
819 |
+
"step": 0.01
|
820 |
+
}
|
821 |
+
],
|
822 |
+
"color": [
|
823 |
+
{
|
824 |
+
"name": flag_preprocessor_resolution,
|
825 |
+
"value": 512,
|
826 |
+
"min": 64,
|
827 |
+
"max": 2048,
|
828 |
+
}
|
829 |
+
],
|
830 |
+
"mediapipe_face": [
|
831 |
+
{
|
832 |
+
"name": flag_preprocessor_resolution,
|
833 |
+
"value": 512,
|
834 |
+
"min": 64,
|
835 |
+
"max": 2048,
|
836 |
+
},
|
837 |
+
{
|
838 |
+
"name": "Max Faces",
|
839 |
+
"value": 1,
|
840 |
+
"min": 1,
|
841 |
+
"max": 10,
|
842 |
+
"step": 1
|
843 |
+
},
|
844 |
+
{
|
845 |
+
"name": "Min Face Confidence",
|
846 |
+
"value": 0.5,
|
847 |
+
"min": 0.01,
|
848 |
+
"max": 1.0,
|
849 |
+
"step": 0.01
|
850 |
+
}
|
851 |
+
],
|
852 |
+
}
|
853 |
+
|
854 |
+
preprocessor_filters = {
|
855 |
+
"All": "none",
|
856 |
+
"Canny": "canny",
|
857 |
+
"Depth": "depth_midas",
|
858 |
+
"Normal": "normal_bae",
|
859 |
+
"OpenPose": "openpose_full",
|
860 |
+
"MLSD": "mlsd",
|
861 |
+
"Lineart": "lineart_standard (from white bg & black line)",
|
862 |
+
"SoftEdge": "softedge_pidinet",
|
863 |
+
"Scribble": "scribble_pidinet",
|
864 |
+
"Seg": "seg_ofade20k",
|
865 |
+
"Shuffle": "shuffle",
|
866 |
+
"Tile": "tile_resample",
|
867 |
+
"Inpaint": "inpaint_only",
|
868 |
+
"IP2P": "none",
|
869 |
+
"Reference": "reference_only",
|
870 |
+
"T2IA": "none",
|
871 |
+
}
|
extensions/microsoftexcel-controlnet/scripts/ui/__pycache__/controlnet_ui_group.cpython-310.pyc
ADDED
Binary file (25.6 kB). View file
|
|
extensions/microsoftexcel-controlnet/scripts/ui/controlnet_ui_group.py
ADDED
@@ -0,0 +1,974 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import functools
|
3 |
+
from typing import List, Optional, Union, Dict, Callable
|
4 |
+
import numpy as np
|
5 |
+
import base64
|
6 |
+
|
7 |
+
from scripts.utils import svg_preprocess
|
8 |
+
from scripts import (
|
9 |
+
global_state,
|
10 |
+
external_code,
|
11 |
+
processor,
|
12 |
+
batch_hijack,
|
13 |
+
)
|
14 |
+
from scripts.processor import (
|
15 |
+
preprocessor_sliders_config,
|
16 |
+
flag_preprocessor_resolution,
|
17 |
+
model_free_preprocessors,
|
18 |
+
preprocessor_filters,
|
19 |
+
HWC3,
|
20 |
+
)
|
21 |
+
from modules import shared
|
22 |
+
from modules.ui_components import FormRow
|
23 |
+
|
24 |
+
|
25 |
+
class ToolButton(gr.Button, gr.components.FormComponent):
|
26 |
+
"""Small button with single emoji as text, fits inside gradio forms"""
|
27 |
+
|
28 |
+
def __init__(self, **kwargs):
|
29 |
+
super().__init__(variant="tool", elem_classes=["cnet-toolbutton"], **kwargs)
|
30 |
+
|
31 |
+
def get_block_name(self):
|
32 |
+
return "button"
|
33 |
+
|
34 |
+
|
35 |
+
class UiControlNetUnit(external_code.ControlNetUnit):
|
36 |
+
"""The data class that stores all states of a ControlNetUnit."""
|
37 |
+
|
38 |
+
def __init__(
|
39 |
+
self,
|
40 |
+
input_mode: batch_hijack.InputMode = batch_hijack.InputMode.SIMPLE,
|
41 |
+
batch_images: Optional[Union[str, List[external_code.InputImage]]] = None,
|
42 |
+
output_dir: str = "",
|
43 |
+
loopback: bool = False,
|
44 |
+
*args,
|
45 |
+
**kwargs,
|
46 |
+
):
|
47 |
+
super().__init__(*args, **kwargs)
|
48 |
+
self.is_ui = True
|
49 |
+
self.input_mode = input_mode
|
50 |
+
self.batch_images = batch_images
|
51 |
+
self.output_dir = output_dir
|
52 |
+
self.loopback = loopback
|
53 |
+
|
54 |
+
|
55 |
+
def update_json_download_link(json_string: str, file_name: str) -> Dict:
|
56 |
+
base64_encoded_json = base64.b64encode(json_string.encode("utf-8")).decode("utf-8")
|
57 |
+
data_uri = f"data:application/json;base64,{base64_encoded_json}"
|
58 |
+
style = """
|
59 |
+
position: absolute;
|
60 |
+
right: var(--size-2);
|
61 |
+
bottom: calc(var(--size-2) * 4);
|
62 |
+
font-size: x-small;
|
63 |
+
font-weight: bold;
|
64 |
+
padding: 2px;
|
65 |
+
|
66 |
+
box-shadow: var(--shadow-drop);
|
67 |
+
border: 1px solid var(--button-secondary-border-color);
|
68 |
+
border-radius: var(--radius-sm);
|
69 |
+
background: var(--background-fill-primary);
|
70 |
+
height: var(--size-5);
|
71 |
+
color: var(--block-label-text-color);
|
72 |
+
"""
|
73 |
+
hint = "Download the pose as .json file"
|
74 |
+
html = f"""<a href='{data_uri}' download='{file_name}' style="{style}" title="{hint}">
|
75 |
+
Json</a>"""
|
76 |
+
return gr.update(value=html, visible=(json_string != ""))
|
77 |
+
|
78 |
+
|
79 |
+
class ControlNetUiGroup(object):
|
80 |
+
# Note: Change symbol hints mapping in `javascript/hints.js` when you change the symbol values.
|
81 |
+
refresh_symbol = "\U0001f504" # 🔄
|
82 |
+
switch_values_symbol = "\U000021C5" # ⇅
|
83 |
+
camera_symbol = "\U0001F4F7" # 📷
|
84 |
+
reverse_symbol = "\U000021C4" # ⇄
|
85 |
+
tossup_symbol = "\u2934"
|
86 |
+
trigger_symbol = "\U0001F4A5" # 💥
|
87 |
+
open_symbol = "\U0001F4DD" # 📝
|
88 |
+
|
89 |
+
global_batch_input_dir = gr.Textbox(
|
90 |
+
label="Controlnet input directory",
|
91 |
+
placeholder="Leave empty to use input directory",
|
92 |
+
**shared.hide_dirs,
|
93 |
+
elem_id="controlnet_batch_input_dir",
|
94 |
+
)
|
95 |
+
img2img_batch_input_dir = None
|
96 |
+
img2img_batch_input_dir_callbacks = []
|
97 |
+
img2img_batch_output_dir = None
|
98 |
+
img2img_batch_output_dir_callbacks = []
|
99 |
+
txt2img_submit_button = None
|
100 |
+
img2img_submit_button = None
|
101 |
+
|
102 |
+
# Slider controls from A1111 WebUI.
|
103 |
+
txt2img_w_slider = None
|
104 |
+
txt2img_h_slider = None
|
105 |
+
img2img_w_slider = None
|
106 |
+
img2img_h_slider = None
|
107 |
+
|
108 |
+
def __init__(
|
109 |
+
self,
|
110 |
+
gradio_compat: bool,
|
111 |
+
infotext_fields: List[str],
|
112 |
+
default_unit: external_code.ControlNetUnit,
|
113 |
+
preprocessors: List[Callable],
|
114 |
+
):
|
115 |
+
self.gradio_compat = gradio_compat
|
116 |
+
self.infotext_fields = infotext_fields
|
117 |
+
self.default_unit = default_unit
|
118 |
+
self.preprocessors = preprocessors
|
119 |
+
self.webcam_enabled = False
|
120 |
+
self.webcam_mirrored = False
|
121 |
+
|
122 |
+
# Note: All gradio elements declared in `render` will be defined as member variable.
|
123 |
+
self.upload_tab = None
|
124 |
+
self.input_image = None
|
125 |
+
self.generated_image_group = None
|
126 |
+
self.generated_image = None
|
127 |
+
self.download_pose_link = None
|
128 |
+
self.batch_tab = None
|
129 |
+
self.batch_image_dir = None
|
130 |
+
self.create_canvas = None
|
131 |
+
self.canvas_width = None
|
132 |
+
self.canvas_height = None
|
133 |
+
self.canvas_create_button = None
|
134 |
+
self.canvas_cancel_button = None
|
135 |
+
self.open_new_canvas_button = None
|
136 |
+
self.webcam_enable = None
|
137 |
+
self.webcam_mirror = None
|
138 |
+
self.send_dimen_button = None
|
139 |
+
self.enabled = None
|
140 |
+
self.lowvram = None
|
141 |
+
self.pixel_perfect = None
|
142 |
+
self.preprocessor_preview = None
|
143 |
+
self.type_filter = None
|
144 |
+
self.module = None
|
145 |
+
self.trigger_preprocessor = None
|
146 |
+
self.model = None
|
147 |
+
self.refresh_models = None
|
148 |
+
self.weight = None
|
149 |
+
self.guidance_start = None
|
150 |
+
self.guidance_end = None
|
151 |
+
self.advanced = None
|
152 |
+
self.processor_res = None
|
153 |
+
self.threshold_a = None
|
154 |
+
self.threshold_b = None
|
155 |
+
self.control_mode = None
|
156 |
+
self.resize_mode = None
|
157 |
+
self.loopback = None
|
158 |
+
|
159 |
+
def render(self, tabname: str, elem_id_tabname: str) -> None:
|
160 |
+
"""The pure HTML structure of a single ControlNetUnit. Calling this
|
161 |
+
function will populate `self` with all gradio element declared
|
162 |
+
in local scope.
|
163 |
+
|
164 |
+
Args:
|
165 |
+
tabname:
|
166 |
+
elem_id_tabname:
|
167 |
+
|
168 |
+
Returns:
|
169 |
+
None
|
170 |
+
"""
|
171 |
+
with gr.Tabs():
|
172 |
+
with gr.Tab(label="Single Image") as self.upload_tab:
|
173 |
+
with gr.Row().style(equal_height=True):
|
174 |
+
self.input_image = gr.Image(
|
175 |
+
source="upload",
|
176 |
+
brush_radius=20,
|
177 |
+
mirror_webcam=False,
|
178 |
+
type="numpy",
|
179 |
+
tool="sketch",
|
180 |
+
elem_id=f"{elem_id_tabname}_{tabname}_input_image",
|
181 |
+
)
|
182 |
+
with gr.Group(visible=False) as self.generated_image_group:
|
183 |
+
self.generated_image = gr.Image(
|
184 |
+
label="Preprocessor Preview",
|
185 |
+
elem_id=f"{elem_id_tabname}_{tabname}_generated_image",
|
186 |
+
).style(
|
187 |
+
height=242
|
188 |
+
) # Gradio's magic number. Only 242 works.
|
189 |
+
self.download_pose_link = gr.HTML(value="", visible=False)
|
190 |
+
preview_close_button_style = """
|
191 |
+
position: absolute;
|
192 |
+
right: var(--size-2);
|
193 |
+
bottom: var(--size-2);
|
194 |
+
font-size: x-small;
|
195 |
+
font-weight: bold;
|
196 |
+
padding: 2px;
|
197 |
+
cursor: pointer;
|
198 |
+
|
199 |
+
box-shadow: var(--shadow-drop);
|
200 |
+
border: 1px solid var(--button-secondary-border-color);
|
201 |
+
border-radius: var(--radius-sm);
|
202 |
+
background: var(--background-fill-primary);
|
203 |
+
height: var(--size-5);
|
204 |
+
color: var(--block-label-text-color);
|
205 |
+
"""
|
206 |
+
preview_check_elem_id = f"{elem_id_tabname}_{tabname}_controlnet_preprocessor_preview_checkbox"
|
207 |
+
preview_close_button_js = f"document.querySelector('#{preview_check_elem_id} input[type=\\'checkbox\\']').click();"
|
208 |
+
gr.HTML(
|
209 |
+
value=f"""<a style="{preview_close_button_style}" title="Close Preview" onclick="{preview_close_button_js}">Close</a>""",
|
210 |
+
visible=True,
|
211 |
+
)
|
212 |
+
|
213 |
+
with gr.Tab(label="Batch") as self.batch_tab:
|
214 |
+
self.batch_image_dir = gr.Textbox(
|
215 |
+
label="Input Directory",
|
216 |
+
placeholder="Leave empty to use img2img batch controlnet input directory",
|
217 |
+
elem_id=f"{elem_id_tabname}_{tabname}_batch_image_dir",
|
218 |
+
)
|
219 |
+
|
220 |
+
with gr.Accordion(label="Open New Canvas", visible=False) as self.create_canvas:
|
221 |
+
self.canvas_width = gr.Slider(
|
222 |
+
label="New Canvas Width",
|
223 |
+
minimum=256,
|
224 |
+
maximum=1024,
|
225 |
+
value=512,
|
226 |
+
step=64,
|
227 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_canvas_width",
|
228 |
+
)
|
229 |
+
self.canvas_height = gr.Slider(
|
230 |
+
label="New Canvas Height",
|
231 |
+
minimum=256,
|
232 |
+
maximum=1024,
|
233 |
+
value=512,
|
234 |
+
step=64,
|
235 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_canvas_height",
|
236 |
+
)
|
237 |
+
with gr.Row():
|
238 |
+
self.canvas_create_button = gr.Button(
|
239 |
+
value="Create New Canvas",
|
240 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_canvas_create_button",
|
241 |
+
)
|
242 |
+
self.canvas_cancel_button = gr.Button(
|
243 |
+
value="Cancel",
|
244 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_canvas_cancel_button",
|
245 |
+
)
|
246 |
+
|
247 |
+
with gr.Row(elem_classes="controlnet_image_controls"):
|
248 |
+
gr.HTML(
|
249 |
+
value="<p>Set the preprocessor to [invert] If your image has white background and black lines.</p>",
|
250 |
+
elem_classes="controlnet_invert_warning",
|
251 |
+
)
|
252 |
+
self.open_new_canvas_button = ToolButton(
|
253 |
+
value=ControlNetUiGroup.open_symbol,
|
254 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_open_new_canvas_button",
|
255 |
+
)
|
256 |
+
self.webcam_enable = ToolButton(
|
257 |
+
value=ControlNetUiGroup.camera_symbol,
|
258 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_webcam_enable",
|
259 |
+
)
|
260 |
+
self.webcam_mirror = ToolButton(
|
261 |
+
value=ControlNetUiGroup.reverse_symbol,
|
262 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_webcam_mirror",
|
263 |
+
)
|
264 |
+
self.send_dimen_button = ToolButton(
|
265 |
+
value=ControlNetUiGroup.tossup_symbol,
|
266 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_send_dimen_button",
|
267 |
+
)
|
268 |
+
|
269 |
+
with FormRow(
|
270 |
+
elem_classes=["checkboxes-row", "controlnet_main_options"],
|
271 |
+
variant="compact",
|
272 |
+
):
|
273 |
+
self.enabled = gr.Checkbox(
|
274 |
+
label="Enable",
|
275 |
+
value=self.default_unit.enabled,
|
276 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_enable_checkbox",
|
277 |
+
)
|
278 |
+
self.lowvram = gr.Checkbox(
|
279 |
+
label="Low VRAM",
|
280 |
+
value=self.default_unit.low_vram,
|
281 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_low_vram_checkbox",
|
282 |
+
)
|
283 |
+
self.pixel_perfect = gr.Checkbox(
|
284 |
+
label="Pixel Perfect",
|
285 |
+
value=self.default_unit.pixel_perfect,
|
286 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_pixel_perfect_checkbox",
|
287 |
+
)
|
288 |
+
self.preprocessor_preview = gr.Checkbox(
|
289 |
+
label="Allow Preview", value=False, elem_id=preview_check_elem_id
|
290 |
+
)
|
291 |
+
|
292 |
+
if not shared.opts.data.get("controlnet_disable_control_type", False):
|
293 |
+
with gr.Row(elem_classes="controlnet_control_type"):
|
294 |
+
self.type_filter = gr.Radio(
|
295 |
+
list(preprocessor_filters.keys()),
|
296 |
+
label=f"Control Type",
|
297 |
+
value="All",
|
298 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_type_filter_radio",
|
299 |
+
elem_classes="controlnet_control_type_filter_group",
|
300 |
+
)
|
301 |
+
|
302 |
+
with gr.Row(elem_classes="controlnet_preprocessor_model"):
|
303 |
+
self.module = gr.Dropdown(
|
304 |
+
global_state.ui_preprocessor_keys,
|
305 |
+
label=f"Preprocessor",
|
306 |
+
value=self.default_unit.module,
|
307 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_preprocessor_dropdown",
|
308 |
+
)
|
309 |
+
self.trigger_preprocessor = ToolButton(
|
310 |
+
value=ControlNetUiGroup.trigger_symbol,
|
311 |
+
visible=True,
|
312 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_trigger_preprocessor",
|
313 |
+
)
|
314 |
+
self.model = gr.Dropdown(
|
315 |
+
list(global_state.cn_models.keys()),
|
316 |
+
label=f"Model",
|
317 |
+
value=self.default_unit.model,
|
318 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_model_dropdown",
|
319 |
+
)
|
320 |
+
self.refresh_models = ToolButton(
|
321 |
+
value=ControlNetUiGroup.refresh_symbol,
|
322 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_refresh_models",
|
323 |
+
)
|
324 |
+
|
325 |
+
with gr.Row(elem_classes="controlnet_weight_steps"):
|
326 |
+
self.weight = gr.Slider(
|
327 |
+
label=f"Control Weight",
|
328 |
+
value=self.default_unit.weight,
|
329 |
+
minimum=0.0,
|
330 |
+
maximum=2.0,
|
331 |
+
step=0.05,
|
332 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_control_weight_slider",
|
333 |
+
elem_classes="controlnet_control_weight_slider",
|
334 |
+
)
|
335 |
+
self.guidance_start = gr.Slider(
|
336 |
+
label="Starting Control Step",
|
337 |
+
value=self.default_unit.guidance_start,
|
338 |
+
minimum=0.0,
|
339 |
+
maximum=1.0,
|
340 |
+
interactive=True,
|
341 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_start_control_step_slider",
|
342 |
+
elem_classes="controlnet_start_control_step_slider",
|
343 |
+
)
|
344 |
+
self.guidance_end = gr.Slider(
|
345 |
+
label="Ending Control Step",
|
346 |
+
value=self.default_unit.guidance_end,
|
347 |
+
minimum=0.0,
|
348 |
+
maximum=1.0,
|
349 |
+
interactive=True,
|
350 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_ending_control_step_slider",
|
351 |
+
elem_classes="controlnet_ending_control_step_slider",
|
352 |
+
)
|
353 |
+
|
354 |
+
# advanced options
|
355 |
+
with gr.Column(visible=False) as self.advanced:
|
356 |
+
self.processor_res = gr.Slider(
|
357 |
+
label="Preprocessor resolution",
|
358 |
+
value=self.default_unit.processor_res,
|
359 |
+
minimum=64,
|
360 |
+
maximum=2048,
|
361 |
+
visible=False,
|
362 |
+
interactive=False,
|
363 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_preprocessor_resolution_slider",
|
364 |
+
)
|
365 |
+
self.threshold_a = gr.Slider(
|
366 |
+
label="Threshold A",
|
367 |
+
value=self.default_unit.threshold_a,
|
368 |
+
minimum=64,
|
369 |
+
maximum=1024,
|
370 |
+
visible=False,
|
371 |
+
interactive=False,
|
372 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_threshold_A_slider",
|
373 |
+
)
|
374 |
+
self.threshold_b = gr.Slider(
|
375 |
+
label="Threshold B",
|
376 |
+
value=self.default_unit.threshold_b,
|
377 |
+
minimum=64,
|
378 |
+
maximum=1024,
|
379 |
+
visible=False,
|
380 |
+
interactive=False,
|
381 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_threshold_B_slider",
|
382 |
+
)
|
383 |
+
|
384 |
+
self.control_mode = gr.Radio(
|
385 |
+
choices=[e.value for e in external_code.ControlMode],
|
386 |
+
value=self.default_unit.control_mode.value,
|
387 |
+
label="Control Mode",
|
388 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_control_mode_radio",
|
389 |
+
elem_classes="controlnet_control_mode_radio",
|
390 |
+
)
|
391 |
+
|
392 |
+
self.resize_mode = gr.Radio(
|
393 |
+
choices=[e.value for e in external_code.ResizeMode],
|
394 |
+
value=self.default_unit.resize_mode.value,
|
395 |
+
label="Resize Mode",
|
396 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_resize_mode_radio",
|
397 |
+
elem_classes="controlnet_resize_mode_radio",
|
398 |
+
)
|
399 |
+
|
400 |
+
self.loopback = gr.Checkbox(
|
401 |
+
label="[Loopback] Automatically send generated images to this ControlNet unit",
|
402 |
+
value=self.default_unit.loopback,
|
403 |
+
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_automatically_send_generated_images_checkbox",
|
404 |
+
elem_classes="controlnet_loopback_checkbox",
|
405 |
+
)
|
406 |
+
|
407 |
+
def register_send_dimensions(self, is_img2img: bool):
|
408 |
+
"""Register event handler for send dimension button."""
|
409 |
+
|
410 |
+
def send_dimensions(image):
|
411 |
+
def closesteight(num):
|
412 |
+
rem = num % 8
|
413 |
+
if rem <= 4:
|
414 |
+
return round(num - rem)
|
415 |
+
else:
|
416 |
+
return round(num + (8 - rem))
|
417 |
+
|
418 |
+
if image:
|
419 |
+
interm = np.asarray(image.get("image"))
|
420 |
+
return closesteight(interm.shape[1]), closesteight(interm.shape[0])
|
421 |
+
else:
|
422 |
+
return gr.Slider.update(), gr.Slider.update()
|
423 |
+
|
424 |
+
outputs = (
|
425 |
+
[
|
426 |
+
ControlNetUiGroup.img2img_w_slider,
|
427 |
+
ControlNetUiGroup.img2img_h_slider,
|
428 |
+
]
|
429 |
+
if is_img2img
|
430 |
+
else [
|
431 |
+
ControlNetUiGroup.txt2img_w_slider,
|
432 |
+
ControlNetUiGroup.txt2img_h_slider,
|
433 |
+
]
|
434 |
+
)
|
435 |
+
self.send_dimen_button.click(
|
436 |
+
fn=send_dimensions,
|
437 |
+
inputs=[self.input_image],
|
438 |
+
outputs=outputs,
|
439 |
+
)
|
440 |
+
|
441 |
+
def register_webcam_toggle(self):
|
442 |
+
def webcam_toggle():
|
443 |
+
self.webcam_enabled = not self.webcam_enabled
|
444 |
+
return {
|
445 |
+
"value": None,
|
446 |
+
"source": "webcam" if self.webcam_enabled else "upload",
|
447 |
+
"__type__": "update",
|
448 |
+
}
|
449 |
+
|
450 |
+
self.webcam_enable.click(webcam_toggle, inputs=None, outputs=self.input_image)
|
451 |
+
|
452 |
+
def register_webcam_mirror_toggle(self):
|
453 |
+
def webcam_mirror_toggle():
|
454 |
+
self.webcam_mirrored = not self.webcam_mirrored
|
455 |
+
return {"mirror_webcam": self.webcam_mirrored, "__type__": "update"}
|
456 |
+
|
457 |
+
self.webcam_mirror.click(
|
458 |
+
webcam_mirror_toggle, inputs=None, outputs=self.input_image
|
459 |
+
)
|
460 |
+
|
461 |
+
def register_refresh_all_models(self):
|
462 |
+
def refresh_all_models(*inputs):
|
463 |
+
global_state.update_cn_models()
|
464 |
+
|
465 |
+
dd = inputs[0]
|
466 |
+
selected = dd if dd in global_state.cn_models else "None"
|
467 |
+
return gr.Dropdown.update(
|
468 |
+
value=selected, choices=list(global_state.cn_models.keys())
|
469 |
+
)
|
470 |
+
|
471 |
+
self.refresh_models.click(refresh_all_models, self.model, self.model)
|
472 |
+
|
473 |
+
def register_build_sliders(self):
|
474 |
+
if not self.gradio_compat:
|
475 |
+
return
|
476 |
+
|
477 |
+
def build_sliders(module, pp):
|
478 |
+
grs = []
|
479 |
+
module = global_state.get_module_basename(module)
|
480 |
+
if module not in preprocessor_sliders_config:
|
481 |
+
grs += [
|
482 |
+
gr.update(
|
483 |
+
label=flag_preprocessor_resolution,
|
484 |
+
value=512,
|
485 |
+
minimum=64,
|
486 |
+
maximum=2048,
|
487 |
+
step=1,
|
488 |
+
visible=not pp,
|
489 |
+
interactive=not pp,
|
490 |
+
),
|
491 |
+
gr.update(visible=False, interactive=False),
|
492 |
+
gr.update(visible=False, interactive=False),
|
493 |
+
gr.update(visible=True),
|
494 |
+
]
|
495 |
+
else:
|
496 |
+
for slider_config in preprocessor_sliders_config[module]:
|
497 |
+
if isinstance(slider_config, dict):
|
498 |
+
visible = True
|
499 |
+
if slider_config["name"] == flag_preprocessor_resolution:
|
500 |
+
visible = not pp
|
501 |
+
grs.append(
|
502 |
+
gr.update(
|
503 |
+
label=slider_config["name"],
|
504 |
+
value=slider_config["value"],
|
505 |
+
minimum=slider_config["min"],
|
506 |
+
maximum=slider_config["max"],
|
507 |
+
step=slider_config["step"]
|
508 |
+
if "step" in slider_config
|
509 |
+
else 1,
|
510 |
+
visible=visible,
|
511 |
+
interactive=visible,
|
512 |
+
)
|
513 |
+
)
|
514 |
+
else:
|
515 |
+
grs.append(gr.update(visible=False, interactive=False))
|
516 |
+
while len(grs) < 3:
|
517 |
+
grs.append(gr.update(visible=False, interactive=False))
|
518 |
+
grs.append(gr.update(visible=True))
|
519 |
+
if module in model_free_preprocessors:
|
520 |
+
grs += [
|
521 |
+
gr.update(visible=False, value="None"),
|
522 |
+
gr.update(visible=False),
|
523 |
+
]
|
524 |
+
else:
|
525 |
+
grs += [gr.update(visible=True), gr.update(visible=True)]
|
526 |
+
return grs
|
527 |
+
|
528 |
+
inputs = [self.module, self.pixel_perfect]
|
529 |
+
outputs = [
|
530 |
+
self.processor_res,
|
531 |
+
self.threshold_a,
|
532 |
+
self.threshold_b,
|
533 |
+
self.advanced,
|
534 |
+
self.model,
|
535 |
+
self.refresh_models,
|
536 |
+
]
|
537 |
+
self.module.change(build_sliders, inputs=inputs, outputs=outputs)
|
538 |
+
self.pixel_perfect.change(build_sliders, inputs=inputs, outputs=outputs)
|
539 |
+
|
540 |
+
if self.type_filter is not None:
|
541 |
+
|
542 |
+
def filter_selected(k, pp):
|
543 |
+
default_option = preprocessor_filters[k]
|
544 |
+
pattern = k.lower()
|
545 |
+
preprocessor_list = global_state.ui_preprocessor_keys
|
546 |
+
model_list = list(global_state.cn_models.keys())
|
547 |
+
if pattern == "all":
|
548 |
+
return [
|
549 |
+
gr.Dropdown.update(value="none", choices=preprocessor_list),
|
550 |
+
gr.Dropdown.update(value="None", choices=model_list),
|
551 |
+
] + build_sliders("none", pp)
|
552 |
+
filtered_preprocessor_list = [
|
553 |
+
x
|
554 |
+
for x in preprocessor_list
|
555 |
+
if pattern in x.lower() or x.lower() == "none"
|
556 |
+
]
|
557 |
+
if pattern in ["canny", "lineart", "scribble", "mlsd"]:
|
558 |
+
filtered_preprocessor_list += [
|
559 |
+
x for x in preprocessor_list if "invert" in x.lower()
|
560 |
+
]
|
561 |
+
filtered_model_list = [
|
562 |
+
x for x in model_list if pattern in x.lower() or x.lower() == "none"
|
563 |
+
]
|
564 |
+
if default_option not in filtered_preprocessor_list:
|
565 |
+
default_option = filtered_preprocessor_list[0]
|
566 |
+
if len(filtered_model_list) == 1:
|
567 |
+
default_model = "None"
|
568 |
+
filtered_model_list = model_list
|
569 |
+
else:
|
570 |
+
default_model = filtered_model_list[1]
|
571 |
+
for x in filtered_model_list:
|
572 |
+
if "11" in x.split("[")[0]:
|
573 |
+
default_model = x
|
574 |
+
break
|
575 |
+
return [
|
576 |
+
gr.Dropdown.update(
|
577 |
+
value=default_option, choices=filtered_preprocessor_list
|
578 |
+
),
|
579 |
+
gr.Dropdown.update(
|
580 |
+
value=default_model, choices=filtered_model_list
|
581 |
+
),
|
582 |
+
] + build_sliders(default_option, pp)
|
583 |
+
|
584 |
+
self.type_filter.change(
|
585 |
+
filter_selected,
|
586 |
+
inputs=[self.type_filter, self.pixel_perfect],
|
587 |
+
outputs=[self.module, self.model, *outputs],
|
588 |
+
)
|
589 |
+
|
590 |
+
def register_run_annotator(self, is_img2img: bool):
|
591 |
+
def run_annotator(image, module, pres, pthr_a, pthr_b, t2i_w, t2i_h, pp, rm):
|
592 |
+
if image is None:
|
593 |
+
return gr.update(value=None, visible=True), gr.update(), gr.update()
|
594 |
+
|
595 |
+
img = HWC3(image["image"])
|
596 |
+
if not (
|
597 |
+
(image["mask"][:, :, 0] == 0).all()
|
598 |
+
or (image["mask"][:, :, 0] == 255).all()
|
599 |
+
):
|
600 |
+
img = HWC3(image["mask"][:, :, 0])
|
601 |
+
|
602 |
+
if "inpaint" in module:
|
603 |
+
color = HWC3(image["image"])
|
604 |
+
alpha = image["mask"][:, :, 0:1]
|
605 |
+
img = np.concatenate([color, alpha], axis=2)
|
606 |
+
|
607 |
+
module = global_state.get_module_basename(module)
|
608 |
+
preprocessor = self.preprocessors[module]
|
609 |
+
|
610 |
+
if pp:
|
611 |
+
raw_H, raw_W, _ = img.shape
|
612 |
+
target_H, target_W = t2i_h, t2i_w
|
613 |
+
rm = str(rm)
|
614 |
+
|
615 |
+
k0 = float(target_H) / float(raw_H)
|
616 |
+
k1 = float(target_W) / float(raw_W)
|
617 |
+
|
618 |
+
if rm == external_code.ResizeMode.OUTER_FIT.value:
|
619 |
+
estimation = min(k0, k1) * float(min(raw_H, raw_W))
|
620 |
+
else:
|
621 |
+
estimation = max(k0, k1) * float(min(raw_H, raw_W))
|
622 |
+
|
623 |
+
pres = int(np.round(estimation))
|
624 |
+
print(f"Pixel Perfect Mode Enabled In Preview.")
|
625 |
+
print(f"resize_mode = {rm}")
|
626 |
+
print(f"raw_H = {raw_H}")
|
627 |
+
print(f"raw_W = {raw_W}")
|
628 |
+
print(f"target_H = {target_H}")
|
629 |
+
print(f"target_W = {target_W}")
|
630 |
+
print(f"estimation = {estimation}")
|
631 |
+
|
632 |
+
class JsonAcceptor:
|
633 |
+
def __init__(self) -> None:
|
634 |
+
self.value = ""
|
635 |
+
|
636 |
+
def accept(self, json_string: str) -> None:
|
637 |
+
self.value = json_string
|
638 |
+
|
639 |
+
json_acceptor = JsonAcceptor()
|
640 |
+
|
641 |
+
print(f"Preview Resolution = {pres}")
|
642 |
+
|
643 |
+
def is_openpose(module: str):
|
644 |
+
return "openpose" in module
|
645 |
+
|
646 |
+
# Only openpose preprocessor returns a JSON output, pass json_acceptor
|
647 |
+
# only when a JSON output is expected. This will make preprocessor cache
|
648 |
+
# work for all other preprocessors other than openpose ones. JSON acceptor
|
649 |
+
# instance are different every call, which means cache will never take
|
650 |
+
# effect.
|
651 |
+
# TODO: Maybe we should let `preprocessor` return a Dict to alleviate this issue?
|
652 |
+
# This requires changing all callsites though.
|
653 |
+
result, is_image = preprocessor(
|
654 |
+
img,
|
655 |
+
res=pres,
|
656 |
+
thr_a=pthr_a,
|
657 |
+
thr_b=pthr_b,
|
658 |
+
json_pose_callback=json_acceptor.accept
|
659 |
+
if is_openpose(module)
|
660 |
+
else None,
|
661 |
+
)
|
662 |
+
|
663 |
+
if "clip" in module:
|
664 |
+
result = processor.clip_vision_visualization(result)
|
665 |
+
is_image = True
|
666 |
+
|
667 |
+
if is_image:
|
668 |
+
if result.ndim == 3 and result.shape[2] == 4:
|
669 |
+
inpaint_mask = result[:, :, 3]
|
670 |
+
result = result[:, :, 0:3]
|
671 |
+
result[inpaint_mask > 127] = 0
|
672 |
+
return (
|
673 |
+
# Update to `generated_image`
|
674 |
+
gr.update(value=result, visible=True, interactive=False),
|
675 |
+
# Update to `download_pose_link`
|
676 |
+
update_json_download_link(json_acceptor.value, "pose.json"),
|
677 |
+
# preprocessor_preview
|
678 |
+
gr.update(value=True),
|
679 |
+
)
|
680 |
+
|
681 |
+
return (
|
682 |
+
# Update to `generated_image`
|
683 |
+
gr.update(value=None, visible=True),
|
684 |
+
# Update to `download_pose_link`
|
685 |
+
update_json_download_link(json_acceptor.value, "pose.json"),
|
686 |
+
# preprocessor_preview
|
687 |
+
gr.update(value=True),
|
688 |
+
)
|
689 |
+
|
690 |
+
self.trigger_preprocessor.click(
|
691 |
+
fn=run_annotator,
|
692 |
+
inputs=[
|
693 |
+
self.input_image,
|
694 |
+
self.module,
|
695 |
+
self.processor_res,
|
696 |
+
self.threshold_a,
|
697 |
+
self.threshold_b,
|
698 |
+
ControlNetUiGroup.img2img_w_slider
|
699 |
+
if is_img2img
|
700 |
+
else ControlNetUiGroup.txt2img_w_slider,
|
701 |
+
ControlNetUiGroup.img2img_h_slider
|
702 |
+
if is_img2img
|
703 |
+
else ControlNetUiGroup.txt2img_h_slider,
|
704 |
+
self.pixel_perfect,
|
705 |
+
self.resize_mode,
|
706 |
+
],
|
707 |
+
outputs=[
|
708 |
+
self.generated_image,
|
709 |
+
self.download_pose_link,
|
710 |
+
self.preprocessor_preview,
|
711 |
+
],
|
712 |
+
)
|
713 |
+
|
714 |
+
def register_shift_preview(self):
|
715 |
+
def shift_preview(is_on):
|
716 |
+
return (
|
717 |
+
# generated_image
|
718 |
+
gr.update() if is_on else gr.update(value=None),
|
719 |
+
# generated_image_group
|
720 |
+
gr.update(visible=is_on),
|
721 |
+
# download_pose_link
|
722 |
+
gr.update() if is_on else gr.update(value=None),
|
723 |
+
)
|
724 |
+
|
725 |
+
self.preprocessor_preview.change(
|
726 |
+
fn=shift_preview,
|
727 |
+
inputs=[self.preprocessor_preview],
|
728 |
+
outputs=[
|
729 |
+
self.generated_image,
|
730 |
+
self.generated_image_group,
|
731 |
+
self.download_pose_link,
|
732 |
+
],
|
733 |
+
)
|
734 |
+
|
735 |
+
def register_create_canvas(self):
|
736 |
+
self.open_new_canvas_button.click(
|
737 |
+
lambda: gr.Accordion.update(visible=True),
|
738 |
+
inputs=None,
|
739 |
+
outputs=self.create_canvas,
|
740 |
+
)
|
741 |
+
self.canvas_cancel_button.click(
|
742 |
+
lambda: gr.Accordion.update(visible=False),
|
743 |
+
inputs=None,
|
744 |
+
outputs=self.create_canvas,
|
745 |
+
)
|
746 |
+
|
747 |
+
def fn_canvas(h, w):
|
748 |
+
return np.zeros(shape=(h, w, 3), dtype=np.uint8) + 255, gr.Accordion.update(
|
749 |
+
visible=False
|
750 |
+
)
|
751 |
+
|
752 |
+
self.canvas_create_button.click(
|
753 |
+
fn=fn_canvas,
|
754 |
+
inputs=[self.canvas_height, self.canvas_width],
|
755 |
+
outputs=[self.input_image, self.create_canvas],
|
756 |
+
)
|
757 |
+
|
758 |
+
def register_callbacks(self, is_img2img: bool):
|
759 |
+
"""Register callbacks on the UI elements.
|
760 |
+
|
761 |
+
Args:
|
762 |
+
is_img2img: Whether ControlNet is under img2img. False when in txt2img mode.
|
763 |
+
|
764 |
+
Returns:
|
765 |
+
None
|
766 |
+
"""
|
767 |
+
self.register_send_dimensions(is_img2img)
|
768 |
+
self.register_webcam_toggle()
|
769 |
+
self.register_webcam_mirror_toggle()
|
770 |
+
self.register_refresh_all_models()
|
771 |
+
self.register_build_sliders()
|
772 |
+
self.register_run_annotator(is_img2img)
|
773 |
+
self.register_shift_preview()
|
774 |
+
self.register_create_canvas()
|
775 |
+
|
776 |
+
def register_modules(self, tabname: str, params):
|
777 |
+
enabled, module, model, weight = params[4:8]
|
778 |
+
guidance_start, guidance_end, pixel_perfect, control_mode = params[-4:]
|
779 |
+
|
780 |
+
self.infotext_fields.extend(
|
781 |
+
[
|
782 |
+
(enabled, f"{tabname} Enabled"),
|
783 |
+
(module, f"{tabname} Preprocessor"),
|
784 |
+
(model, f"{tabname} Model"),
|
785 |
+
(weight, f"{tabname} Weight"),
|
786 |
+
(guidance_start, f"{tabname} Guidance Start"),
|
787 |
+
(guidance_end, f"{tabname} Guidance End"),
|
788 |
+
]
|
789 |
+
)
|
790 |
+
|
791 |
+
def render_and_register_unit(self, tabname: str, is_img2img: bool):
|
792 |
+
"""Render the invisible states elements for misc persistent
|
793 |
+
purposes. Register callbacks on loading/unloading the controlnet
|
794 |
+
unit and handle batch processes.
|
795 |
+
|
796 |
+
Args:
|
797 |
+
tabname:
|
798 |
+
is_img2img:
|
799 |
+
|
800 |
+
Returns:
|
801 |
+
The data class "ControlNetUnit" representing this ControlNetUnit.
|
802 |
+
"""
|
803 |
+
input_mode = gr.State(batch_hijack.InputMode.SIMPLE)
|
804 |
+
batch_image_dir_state = gr.State("")
|
805 |
+
output_dir_state = gr.State("")
|
806 |
+
unit_args = (
|
807 |
+
input_mode,
|
808 |
+
batch_image_dir_state,
|
809 |
+
output_dir_state,
|
810 |
+
self.loopback,
|
811 |
+
self.enabled,
|
812 |
+
self.module,
|
813 |
+
self.model,
|
814 |
+
self.weight,
|
815 |
+
self.input_image,
|
816 |
+
self.resize_mode,
|
817 |
+
self.lowvram,
|
818 |
+
self.processor_res,
|
819 |
+
self.threshold_a,
|
820 |
+
self.threshold_b,
|
821 |
+
self.guidance_start,
|
822 |
+
self.guidance_end,
|
823 |
+
self.pixel_perfect,
|
824 |
+
self.control_mode,
|
825 |
+
)
|
826 |
+
self.register_modules(tabname, unit_args)
|
827 |
+
|
828 |
+
self.input_image.preprocess = functools.partial(
|
829 |
+
svg_preprocess, preprocess=self.input_image.preprocess
|
830 |
+
)
|
831 |
+
|
832 |
+
unit = gr.State(self.default_unit)
|
833 |
+
for comp in unit_args:
|
834 |
+
event_subscribers = []
|
835 |
+
if hasattr(comp, "edit"):
|
836 |
+
event_subscribers.append(comp.edit)
|
837 |
+
elif hasattr(comp, "click"):
|
838 |
+
event_subscribers.append(comp.click)
|
839 |
+
elif isinstance(comp, gr.Slider) and hasattr(comp, "release"):
|
840 |
+
event_subscribers.append(comp.release)
|
841 |
+
elif hasattr(comp, "change"):
|
842 |
+
event_subscribers.append(comp.change)
|
843 |
+
|
844 |
+
if hasattr(comp, "clear"):
|
845 |
+
event_subscribers.append(comp.clear)
|
846 |
+
|
847 |
+
for event_subscriber in event_subscribers:
|
848 |
+
event_subscriber(
|
849 |
+
fn=UiControlNetUnit, inputs=list(unit_args), outputs=unit
|
850 |
+
)
|
851 |
+
|
852 |
+
# keep input_mode in sync
|
853 |
+
def ui_controlnet_unit_for_input_mode(input_mode, *args):
|
854 |
+
args = list(args)
|
855 |
+
args[0] = input_mode
|
856 |
+
return input_mode, UiControlNetUnit(*args)
|
857 |
+
|
858 |
+
for input_tab in (
|
859 |
+
(self.upload_tab, batch_hijack.InputMode.SIMPLE),
|
860 |
+
(self.batch_tab, batch_hijack.InputMode.BATCH),
|
861 |
+
):
|
862 |
+
input_tab[0].select(
|
863 |
+
fn=ui_controlnet_unit_for_input_mode,
|
864 |
+
inputs=[gr.State(input_tab[1])] + list(unit_args),
|
865 |
+
outputs=[input_mode, unit],
|
866 |
+
)
|
867 |
+
|
868 |
+
def determine_batch_dir(batch_dir, fallback_dir, fallback_fallback_dir):
|
869 |
+
if batch_dir:
|
870 |
+
return batch_dir
|
871 |
+
elif fallback_dir:
|
872 |
+
return fallback_dir
|
873 |
+
else:
|
874 |
+
return fallback_fallback_dir
|
875 |
+
|
876 |
+
# keep batch_dir in sync with global batch input textboxes
|
877 |
+
def subscribe_for_batch_dir():
|
878 |
+
batch_dirs = [
|
879 |
+
self.batch_image_dir,
|
880 |
+
ControlNetUiGroup.global_batch_input_dir,
|
881 |
+
ControlNetUiGroup.img2img_batch_input_dir,
|
882 |
+
]
|
883 |
+
for batch_dir_comp in batch_dirs:
|
884 |
+
subscriber = getattr(batch_dir_comp, "blur", None)
|
885 |
+
if subscriber is None:
|
886 |
+
continue
|
887 |
+
subscriber(
|
888 |
+
fn=determine_batch_dir,
|
889 |
+
inputs=batch_dirs,
|
890 |
+
outputs=[batch_image_dir_state],
|
891 |
+
queue=False,
|
892 |
+
)
|
893 |
+
|
894 |
+
if ControlNetUiGroup.img2img_batch_input_dir is None:
|
895 |
+
# we are too soon, subscribe later when available
|
896 |
+
ControlNetUiGroup.img2img_batch_input_dir_callbacks.append(
|
897 |
+
subscribe_for_batch_dir
|
898 |
+
)
|
899 |
+
else:
|
900 |
+
subscribe_for_batch_dir()
|
901 |
+
|
902 |
+
# keep output_dir in sync with global batch output textbox
|
903 |
+
def subscribe_for_output_dir():
|
904 |
+
ControlNetUiGroup.img2img_batch_output_dir.blur(
|
905 |
+
fn=lambda a: a,
|
906 |
+
inputs=[ControlNetUiGroup.img2img_batch_output_dir],
|
907 |
+
outputs=[output_dir_state],
|
908 |
+
queue=False,
|
909 |
+
)
|
910 |
+
|
911 |
+
if ControlNetUiGroup.img2img_batch_input_dir is None:
|
912 |
+
# we are too soon, subscribe later when available
|
913 |
+
ControlNetUiGroup.img2img_batch_output_dir_callbacks.append(
|
914 |
+
subscribe_for_output_dir
|
915 |
+
)
|
916 |
+
else:
|
917 |
+
subscribe_for_output_dir()
|
918 |
+
|
919 |
+
(
|
920 |
+
ControlNetUiGroup.img2img_submit_button
|
921 |
+
if is_img2img
|
922 |
+
else ControlNetUiGroup.txt2img_submit_button
|
923 |
+
).click(
|
924 |
+
fn=UiControlNetUnit,
|
925 |
+
inputs=list(unit_args),
|
926 |
+
outputs=unit,
|
927 |
+
queue=False,
|
928 |
+
)
|
929 |
+
|
930 |
+
return unit
|
931 |
+
|
932 |
+
@staticmethod
|
933 |
+
def on_after_component(component, **_kwargs):
|
934 |
+
elem_id = getattr(component, "elem_id", None)
|
935 |
+
|
936 |
+
if elem_id == "txt2img_generate":
|
937 |
+
ControlNetUiGroup.txt2img_submit_button = component
|
938 |
+
return
|
939 |
+
|
940 |
+
if elem_id == "img2img_generate":
|
941 |
+
ControlNetUiGroup.img2img_submit_button = component
|
942 |
+
return
|
943 |
+
|
944 |
+
if elem_id == "img2img_batch_input_dir":
|
945 |
+
ControlNetUiGroup.img2img_batch_input_dir = component
|
946 |
+
for callback in ControlNetUiGroup.img2img_batch_input_dir_callbacks:
|
947 |
+
callback()
|
948 |
+
return
|
949 |
+
|
950 |
+
if elem_id == "img2img_batch_output_dir":
|
951 |
+
ControlNetUiGroup.img2img_batch_output_dir = component
|
952 |
+
for callback in ControlNetUiGroup.img2img_batch_output_dir_callbacks:
|
953 |
+
callback()
|
954 |
+
return
|
955 |
+
|
956 |
+
if elem_id == "img2img_batch_inpaint_mask_dir":
|
957 |
+
ControlNetUiGroup.global_batch_input_dir.render()
|
958 |
+
return
|
959 |
+
|
960 |
+
if elem_id == "txt2img_width":
|
961 |
+
ControlNetUiGroup.txt2img_w_slider = component
|
962 |
+
return
|
963 |
+
|
964 |
+
if elem_id == "txt2img_height":
|
965 |
+
ControlNetUiGroup.txt2img_h_slider = component
|
966 |
+
return
|
967 |
+
|
968 |
+
if elem_id == "img2img_width":
|
969 |
+
ControlNetUiGroup.img2img_w_slider = component
|
970 |
+
return
|
971 |
+
|
972 |
+
if elem_id == "img2img_height":
|
973 |
+
ControlNetUiGroup.img2img_h_slider = component
|
974 |
+
return
|
extensions/microsoftexcel-controlnet/scripts/utils.py
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import os
|
3 |
+
import functools
|
4 |
+
import base64
|
5 |
+
import numpy as np
|
6 |
+
import gradio as gr
|
7 |
+
|
8 |
+
from typing import Any, Callable, Dict
|
9 |
+
|
10 |
+
|
11 |
+
def load_state_dict(ckpt_path, location="cpu"):
|
12 |
+
_, extension = os.path.splitext(ckpt_path)
|
13 |
+
if extension.lower() == ".safetensors":
|
14 |
+
import safetensors.torch
|
15 |
+
|
16 |
+
state_dict = safetensors.torch.load_file(ckpt_path, device=location)
|
17 |
+
else:
|
18 |
+
state_dict = get_state_dict(
|
19 |
+
torch.load(ckpt_path, map_location=torch.device(location))
|
20 |
+
)
|
21 |
+
state_dict = get_state_dict(state_dict)
|
22 |
+
print(f"Loaded state_dict from [{ckpt_path}]")
|
23 |
+
return state_dict
|
24 |
+
|
25 |
+
|
26 |
+
def get_state_dict(d):
|
27 |
+
return d.get("state_dict", d)
|
28 |
+
|
29 |
+
|
30 |
+
def ndarray_lru_cache(max_size: int = 128, typed: bool = False):
|
31 |
+
"""
|
32 |
+
Decorator to enable caching for functions with numpy array arguments.
|
33 |
+
Numpy arrays are mutable, and thus not directly usable as hash keys.
|
34 |
+
|
35 |
+
The idea here is to wrap the incoming arguments with type `np.ndarray`
|
36 |
+
as `HashableNpArray` so that `lru_cache` can correctly handles `np.ndarray`
|
37 |
+
arguments.
|
38 |
+
|
39 |
+
`HashableNpArray` functions exactly the same way as `np.ndarray` except
|
40 |
+
having `__hash__` and `__eq__` overriden.
|
41 |
+
"""
|
42 |
+
|
43 |
+
def decorator(func: Callable):
|
44 |
+
"""The actual decorator that accept function as input."""
|
45 |
+
|
46 |
+
class HashableNpArray(np.ndarray):
|
47 |
+
def __new__(cls, input_array):
|
48 |
+
# Input array is an instance of ndarray.
|
49 |
+
# The view makes the input array and returned array share the same data.
|
50 |
+
obj = np.asarray(input_array).view(cls)
|
51 |
+
return obj
|
52 |
+
|
53 |
+
def __eq__(self, other) -> bool:
|
54 |
+
return np.array_equal(self, other)
|
55 |
+
|
56 |
+
def __hash__(self):
|
57 |
+
# Hash the bytes representing the data of the array.
|
58 |
+
return hash(self.tobytes())
|
59 |
+
|
60 |
+
@functools.lru_cache(maxsize=max_size, typed=typed)
|
61 |
+
def cached_func(*args, **kwargs):
|
62 |
+
"""This function only accepts `HashableNpArray` as input params."""
|
63 |
+
return func(*args, **kwargs)
|
64 |
+
|
65 |
+
# Preserves original function.__name__ and __doc__.
|
66 |
+
@functools.wraps(func)
|
67 |
+
def decorated_func(*args, **kwargs):
|
68 |
+
"""The decorated function that delegates the original function."""
|
69 |
+
|
70 |
+
def convert_item(item: Any):
|
71 |
+
return HashableNpArray(item) if isinstance(item, np.ndarray) else item
|
72 |
+
|
73 |
+
args = [convert_item(arg) for arg in args]
|
74 |
+
kwargs = {k: convert_item(arg) for k, arg in kwargs.items()}
|
75 |
+
return cached_func(*args, **kwargs)
|
76 |
+
|
77 |
+
return decorated_func
|
78 |
+
|
79 |
+
return decorator
|
80 |
+
|
81 |
+
|
82 |
+
# svgsupports
|
83 |
+
svgsupport = False
|
84 |
+
try:
|
85 |
+
import io
|
86 |
+
from svglib.svglib import svg2rlg
|
87 |
+
from reportlab.graphics import renderPM
|
88 |
+
|
89 |
+
svgsupport = True
|
90 |
+
except ImportError:
|
91 |
+
pass
|
92 |
+
|
93 |
+
|
94 |
+
def svg_preprocess(inputs: Dict, preprocess: Callable):
|
95 |
+
if not inputs:
|
96 |
+
return None
|
97 |
+
|
98 |
+
if inputs["image"].startswith("data:image/svg+xml;base64,") and svgsupport:
|
99 |
+
svg_data = base64.b64decode(
|
100 |
+
inputs["image"].replace("data:image/svg+xml;base64,", "")
|
101 |
+
)
|
102 |
+
drawing = svg2rlg(io.BytesIO(svg_data))
|
103 |
+
png_data = renderPM.drawToString(drawing, fmt="PNG")
|
104 |
+
encoded_string = base64.b64encode(png_data)
|
105 |
+
base64_str = str(encoded_string, "utf-8")
|
106 |
+
base64_str = "data:image/png;base64," + base64_str
|
107 |
+
inputs["image"] = base64_str
|
108 |
+
return preprocess(inputs)
|
109 |
+
|
extensions/microsoftexcel-controlnet/scripts/xyz_grid_support.py
ADDED
@@ -0,0 +1,443 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import re
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
from modules import scripts, shared
|
5 |
+
|
6 |
+
try:
|
7 |
+
from scripts.global_state import update_cn_models, cn_models_names, cn_preprocessor_modules
|
8 |
+
from scripts.external_code import ResizeMode
|
9 |
+
except (ImportError, NameError):
|
10 |
+
import_error = True
|
11 |
+
else:
|
12 |
+
import_error = False
|
13 |
+
|
14 |
+
DEBUG_MODE = False
|
15 |
+
|
16 |
+
|
17 |
+
def debug_info(func):
|
18 |
+
def debug_info_(*args, **kwargs):
|
19 |
+
if DEBUG_MODE:
|
20 |
+
print(f"Debug info: {func.__name__}, {args}")
|
21 |
+
return func(*args, **kwargs)
|
22 |
+
return debug_info_
|
23 |
+
|
24 |
+
|
25 |
+
def find_dict(dict_list, keyword, search_key="name", stop=False):
|
26 |
+
result = next((d for d in dict_list if d[search_key] == keyword), None)
|
27 |
+
if result or not stop:
|
28 |
+
return result
|
29 |
+
else:
|
30 |
+
raise ValueError(f"Dictionary with value '{keyword}' in key '{search_key}' not found.")
|
31 |
+
|
32 |
+
|
33 |
+
def flatten(lst):
|
34 |
+
result = []
|
35 |
+
for element in lst:
|
36 |
+
if isinstance(element, list):
|
37 |
+
result.extend(flatten(element))
|
38 |
+
else:
|
39 |
+
result.append(element)
|
40 |
+
return result
|
41 |
+
|
42 |
+
|
43 |
+
def is_all_included(target_list, check_list, allow_blank=False, stop=False):
|
44 |
+
for element in flatten(target_list):
|
45 |
+
if allow_blank and str(element) in ["None", ""]:
|
46 |
+
continue
|
47 |
+
elif element not in check_list:
|
48 |
+
if not stop:
|
49 |
+
return False
|
50 |
+
else:
|
51 |
+
raise ValueError(f"'{element}' is not included in check list.")
|
52 |
+
return True
|
53 |
+
|
54 |
+
|
55 |
+
class ListParser():
|
56 |
+
"""This class restores a broken list caused by the following process
|
57 |
+
in the xyz_grid module.
|
58 |
+
-> valslist = [x.strip() for x in chain.from_iterable(
|
59 |
+
csv.reader(StringIO(vals)))]
|
60 |
+
It also performs type conversion,
|
61 |
+
adjusts the number of elements in the list, and other operations.
|
62 |
+
|
63 |
+
This class directly modifies the received list.
|
64 |
+
"""
|
65 |
+
numeric_pattern = {
|
66 |
+
int: {
|
67 |
+
"range": r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\(([+-]\d+)\s*\))?\s*",
|
68 |
+
"count": r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\[(\d+)\s*\])?\s*"
|
69 |
+
},
|
70 |
+
float: {
|
71 |
+
"range": r"\s*([+-]?\s*\d+(?:\.\d*)?)\s*-\s*([+-]?\s*\d+(?:\.\d*)?)(?:\s*\(([+-]\d+(?:\.\d*)?)\s*\))?\s*",
|
72 |
+
"count": r"\s*([+-]?\s*\d+(?:\.\d*)?)\s*-\s*([+-]?\s*\d+(?:\.\d*)?)(?:\s*\[(\d+(?:\.\d*)?)\s*\])?\s*"
|
73 |
+
}
|
74 |
+
}
|
75 |
+
|
76 |
+
################################################
|
77 |
+
#
|
78 |
+
# Initialization method from here.
|
79 |
+
#
|
80 |
+
################################################
|
81 |
+
|
82 |
+
def __init__(self, my_list, converter=None, allow_blank=True, exclude_list=None, run=True):
|
83 |
+
self.my_list = my_list
|
84 |
+
self.converter = converter
|
85 |
+
self.allow_blank = allow_blank
|
86 |
+
self.exclude_list = exclude_list
|
87 |
+
self.re_bracket_start = None
|
88 |
+
self.re_bracket_start_precheck = None
|
89 |
+
self.re_bracket_end = None
|
90 |
+
self.re_bracket_end_precheck = None
|
91 |
+
self.re_range = None
|
92 |
+
self.re_count = None
|
93 |
+
self.compile_regex()
|
94 |
+
if run:
|
95 |
+
self.auto_normalize()
|
96 |
+
|
97 |
+
def compile_regex(self):
|
98 |
+
exclude_pattern = "|".join(self.exclude_list) if self.exclude_list else None
|
99 |
+
if exclude_pattern is None:
|
100 |
+
self.re_bracket_start = re.compile(r"^\[")
|
101 |
+
self.re_bracket_end = re.compile(r"\]$")
|
102 |
+
else:
|
103 |
+
self.re_bracket_start = re.compile(fr"^\[(?!(?:{exclude_pattern})\])")
|
104 |
+
self.re_bracket_end = re.compile(fr"(?<!\[(?:{exclude_pattern}))\]$")
|
105 |
+
|
106 |
+
if self.converter not in self.numeric_pattern:
|
107 |
+
return self
|
108 |
+
# If the converter is either int or float.
|
109 |
+
self.re_range = re.compile(self.numeric_pattern[self.converter]["range"])
|
110 |
+
self.re_count = re.compile(self.numeric_pattern[self.converter]["count"])
|
111 |
+
self.re_bracket_start_precheck = None
|
112 |
+
self.re_bracket_end_precheck = self.re_count
|
113 |
+
return self
|
114 |
+
|
115 |
+
################################################
|
116 |
+
#
|
117 |
+
# Public method from here.
|
118 |
+
#
|
119 |
+
################################################
|
120 |
+
|
121 |
+
################################################
|
122 |
+
# This method is executed at the time of initialization.
|
123 |
+
#
|
124 |
+
def auto_normalize(self):
|
125 |
+
if not self.has_list_notation():
|
126 |
+
self.numeric_range_parser()
|
127 |
+
self.type_convert()
|
128 |
+
return self
|
129 |
+
else:
|
130 |
+
self.fix_structure()
|
131 |
+
self.numeric_range_parser()
|
132 |
+
self.type_convert()
|
133 |
+
self.fill_to_longest()
|
134 |
+
return self
|
135 |
+
|
136 |
+
def has_list_notation(self):
|
137 |
+
return any(self._search_bracket(s) for s in self.my_list)
|
138 |
+
|
139 |
+
def numeric_range_parser(self, my_list=None, depth=0):
|
140 |
+
if self.converter not in self.numeric_pattern:
|
141 |
+
return self
|
142 |
+
|
143 |
+
my_list = self.my_list if my_list is None else my_list
|
144 |
+
result = []
|
145 |
+
is_matched = False
|
146 |
+
for s in my_list:
|
147 |
+
if isinstance(s, list):
|
148 |
+
result.extend(self.numeric_range_parser(s, depth+1))
|
149 |
+
continue
|
150 |
+
|
151 |
+
match = self._numeric_range_to_list(s)
|
152 |
+
if s != match:
|
153 |
+
is_matched = True
|
154 |
+
result.extend(match if not depth else [match])
|
155 |
+
continue
|
156 |
+
else:
|
157 |
+
result.append(s)
|
158 |
+
continue
|
159 |
+
|
160 |
+
if depth:
|
161 |
+
return self._transpose(result) if is_matched else [result]
|
162 |
+
else:
|
163 |
+
my_list[:] = result
|
164 |
+
return self
|
165 |
+
|
166 |
+
def type_convert(self, my_list=None):
|
167 |
+
my_list = self.my_list if my_list is None else my_list
|
168 |
+
for i, s in enumerate(my_list):
|
169 |
+
if isinstance(s, list):
|
170 |
+
self.type_convert(s)
|
171 |
+
elif self.allow_blank and (str(s) in ["None", ""]):
|
172 |
+
my_list[i] = None
|
173 |
+
elif self.converter:
|
174 |
+
my_list[i] = self.converter(s)
|
175 |
+
else:
|
176 |
+
my_list[i] = s
|
177 |
+
return self
|
178 |
+
|
179 |
+
def fix_structure(self):
|
180 |
+
def is_same_length(list1, list2):
|
181 |
+
return len(list1) == len(list2)
|
182 |
+
|
183 |
+
start_indices, end_indices = [], []
|
184 |
+
for i, s in enumerate(self.my_list):
|
185 |
+
if is_same_length(start_indices, end_indices):
|
186 |
+
replace_string = self._search_bracket(s, "[", replace="")
|
187 |
+
if s != replace_string:
|
188 |
+
s = replace_string
|
189 |
+
start_indices.append(i)
|
190 |
+
if not is_same_length(start_indices, end_indices):
|
191 |
+
replace_string = self._search_bracket(s, "]", replace="")
|
192 |
+
if s != replace_string:
|
193 |
+
s = replace_string
|
194 |
+
end_indices.append(i + 1)
|
195 |
+
self.my_list[i] = s
|
196 |
+
if not is_same_length(start_indices, end_indices):
|
197 |
+
raise ValueError(f"Lengths of {start_indices} and {end_indices} are different.")
|
198 |
+
# Restore the structure of a list.
|
199 |
+
for i, j in zip(reversed(start_indices), reversed(end_indices)):
|
200 |
+
self.my_list[i:j] = [self.my_list[i:j]]
|
201 |
+
return self
|
202 |
+
|
203 |
+
def fill_to_longest(self, my_list=None, value=None, index=None):
|
204 |
+
my_list = self.my_list if my_list is None else my_list
|
205 |
+
if not self.sublist_exists(my_list):
|
206 |
+
return self
|
207 |
+
max_length = max(len(sub_list) for sub_list in my_list if isinstance(sub_list, list))
|
208 |
+
for i, sub_list in enumerate(my_list):
|
209 |
+
if isinstance(sub_list, list):
|
210 |
+
fill_value = value if index is None else sub_list[index]
|
211 |
+
my_list[i] = sub_list + [fill_value] * (max_length-len(sub_list))
|
212 |
+
return self
|
213 |
+
|
214 |
+
def sublist_exists(self, my_list=None):
|
215 |
+
my_list = self.my_list if my_list is None else my_list
|
216 |
+
return any(isinstance(item, list) for item in my_list)
|
217 |
+
|
218 |
+
def all_sublists(self, my_list=None): # Unused method
|
219 |
+
my_list = self.my_list if my_list is None else my_list
|
220 |
+
return all(isinstance(item, list) for item in my_list)
|
221 |
+
|
222 |
+
def get_list(self): # Unused method
|
223 |
+
return self.my_list
|
224 |
+
|
225 |
+
################################################
|
226 |
+
#
|
227 |
+
# Private method from here.
|
228 |
+
#
|
229 |
+
################################################
|
230 |
+
|
231 |
+
def _search_bracket(self, string, bracket="[", replace=None):
|
232 |
+
if bracket == "[":
|
233 |
+
pattern = self.re_bracket_start
|
234 |
+
precheck = self.re_bracket_start_precheck # None
|
235 |
+
elif bracket == "]":
|
236 |
+
pattern = self.re_bracket_end
|
237 |
+
precheck = self.re_bracket_end_precheck
|
238 |
+
else:
|
239 |
+
raise ValueError(f"Invalid argument provided. (bracket: {bracket})")
|
240 |
+
|
241 |
+
if precheck and precheck.fullmatch(string):
|
242 |
+
return None if replace is None else string
|
243 |
+
elif replace is None:
|
244 |
+
return pattern.search(string)
|
245 |
+
else:
|
246 |
+
return pattern.sub(replace, string)
|
247 |
+
|
248 |
+
def _numeric_range_to_list(self, string):
|
249 |
+
match = self.re_range.fullmatch(string)
|
250 |
+
if match is not None:
|
251 |
+
if self.converter == int:
|
252 |
+
start = int(match.group(1))
|
253 |
+
end = int(match.group(2)) + 1
|
254 |
+
step = int(match.group(3)) if match.group(3) is not None else 1
|
255 |
+
return list(range(start, end, step))
|
256 |
+
else: # float
|
257 |
+
start = float(match.group(1))
|
258 |
+
end = float(match.group(2))
|
259 |
+
step = float(match.group(3)) if match.group(3) is not None else 1
|
260 |
+
return np.arange(start, end + step, step).tolist()
|
261 |
+
|
262 |
+
match = self.re_count.fullmatch(string)
|
263 |
+
if match is not None:
|
264 |
+
if self.converter == int:
|
265 |
+
start = int(match.group(1))
|
266 |
+
end = int(match.group(2))
|
267 |
+
num = int(match.group(3)) if match.group(3) is not None else 1
|
268 |
+
return [int(x) for x in np.linspace(start=start, stop=end, num=num).tolist()]
|
269 |
+
else: # float
|
270 |
+
start = float(match.group(1))
|
271 |
+
end = float(match.group(2))
|
272 |
+
num = int(match.group(3)) if match.group(3) is not None else 1
|
273 |
+
return np.linspace(start=start, stop=end, num=num).tolist()
|
274 |
+
return string
|
275 |
+
|
276 |
+
def _transpose(self, my_list=None):
|
277 |
+
my_list = self.my_list if my_list is None else my_list
|
278 |
+
my_list = [item if isinstance(item, list) else [item] for item in my_list]
|
279 |
+
self.fill_to_longest(my_list, index=-1)
|
280 |
+
return np.array(my_list, dtype=object).T.tolist()
|
281 |
+
|
282 |
+
################################################
|
283 |
+
#
|
284 |
+
# The methods of ListParser class end here.
|
285 |
+
#
|
286 |
+
################################################
|
287 |
+
|
288 |
+
################################################################
|
289 |
+
################################################################
|
290 |
+
#
|
291 |
+
# Starting the main process of this module.
|
292 |
+
#
|
293 |
+
# functions are executed in this order:
|
294 |
+
# find_module
|
295 |
+
# add_axis_options
|
296 |
+
# identity
|
297 |
+
# enable_script_control
|
298 |
+
# apply_field
|
299 |
+
# confirm
|
300 |
+
# bool_
|
301 |
+
# choices_for
|
302 |
+
# make_excluded_list
|
303 |
+
# config lists for AxisOptions:
|
304 |
+
# validation_data
|
305 |
+
# extra_axis_options
|
306 |
+
################################################################
|
307 |
+
################################################################
|
308 |
+
|
309 |
+
|
310 |
+
def find_module(module_names):
|
311 |
+
if isinstance(module_names, str):
|
312 |
+
module_names = [s.strip() for s in module_names.split(",")]
|
313 |
+
for data in scripts.scripts_data:
|
314 |
+
if data.script_class.__module__ in module_names and hasattr(data, "module"):
|
315 |
+
return data.module
|
316 |
+
return None
|
317 |
+
|
318 |
+
|
319 |
+
def add_axis_options(xyz_grid):
|
320 |
+
|
321 |
+
################################################
|
322 |
+
#
|
323 |
+
# Define a function to pass to the AxisOption class from here.
|
324 |
+
#
|
325 |
+
################################################
|
326 |
+
|
327 |
+
################################################
|
328 |
+
# Set this function as the type attribute of the AxisOption class.
|
329 |
+
# To skip the following processing of xyz_grid module.
|
330 |
+
# -> valslist = [opt.type(x) for x in valslist]
|
331 |
+
# Perform type conversion using the function
|
332 |
+
# set to the confirm attribute instead.
|
333 |
+
#
|
334 |
+
def identity(x):
|
335 |
+
return x
|
336 |
+
|
337 |
+
def enable_script_control():
|
338 |
+
shared.opts.data["control_net_allow_script_control"] = True
|
339 |
+
|
340 |
+
def apply_field(field):
|
341 |
+
@debug_info
|
342 |
+
def apply_field_(p, x, xs):
|
343 |
+
enable_script_control()
|
344 |
+
setattr(p, field, x)
|
345 |
+
|
346 |
+
return apply_field_
|
347 |
+
|
348 |
+
################################################
|
349 |
+
# The confirm function defined in this module
|
350 |
+
# enables list notation and performs type conversion.
|
351 |
+
#
|
352 |
+
# Example:
|
353 |
+
# any = [any, any, any, ...]
|
354 |
+
# [any] = [any, None, None, ...]
|
355 |
+
# [None, None, any] = [None, None, any]
|
356 |
+
# [,,any] = [None, None, any]
|
357 |
+
# any, [,any,] = [any, any, any, ...], [None, any, None]
|
358 |
+
#
|
359 |
+
# Enabled Only:
|
360 |
+
# any = [any] = [any, None, None, ...]
|
361 |
+
# (any and [any] are considered equivalent)
|
362 |
+
#
|
363 |
+
def confirm(func_or_str):
|
364 |
+
@debug_info
|
365 |
+
def confirm_(p, xs):
|
366 |
+
if callable(func_or_str): # func_or_str is converter
|
367 |
+
ListParser(xs, func_or_str, allow_blank=True)
|
368 |
+
return
|
369 |
+
|
370 |
+
elif isinstance(func_or_str, str): # func_or_str is keyword
|
371 |
+
valid_data = find_dict(validation_data, func_or_str, stop=True)
|
372 |
+
converter = valid_data["type"]
|
373 |
+
exclude_list = valid_data["exclude"]() if valid_data["exclude"] else None
|
374 |
+
check_list = valid_data["check"]()
|
375 |
+
|
376 |
+
ListParser(xs, converter, allow_blank=True, exclude_list=exclude_list)
|
377 |
+
is_all_included(xs, check_list, allow_blank=True, stop=True)
|
378 |
+
return
|
379 |
+
|
380 |
+
else:
|
381 |
+
raise TypeError(f"Argument must be callable or str, not {type(func_or_str).__name__}.")
|
382 |
+
|
383 |
+
return confirm_
|
384 |
+
|
385 |
+
def bool_(string):
|
386 |
+
string = str(string)
|
387 |
+
if string in ["None", ""]:
|
388 |
+
return None
|
389 |
+
elif string.lower() in ["true", "1"]:
|
390 |
+
return True
|
391 |
+
elif string.lower() in ["false", "0"]:
|
392 |
+
return False
|
393 |
+
else:
|
394 |
+
raise ValueError(f"Could not convert string to boolean: {string}")
|
395 |
+
|
396 |
+
def choices_bool():
|
397 |
+
return ["False", "True"]
|
398 |
+
|
399 |
+
def choices_model():
|
400 |
+
update_cn_models()
|
401 |
+
return list(cn_models_names.values())
|
402 |
+
|
403 |
+
def choices_resize_mode():
|
404 |
+
return [e.value for e in ResizeMode]
|
405 |
+
|
406 |
+
def choices_preprocessor():
|
407 |
+
return list(cn_preprocessor_modules)
|
408 |
+
|
409 |
+
def make_excluded_list():
|
410 |
+
pattern = re.compile(r"\[(\w+)\]")
|
411 |
+
return [match.group(1) for s in choices_model()
|
412 |
+
for match in pattern.finditer(s)]
|
413 |
+
|
414 |
+
validation_data = [
|
415 |
+
{"name": "model", "type": str, "check": choices_model, "exclude": make_excluded_list},
|
416 |
+
{"name": "resize_mode", "type": str, "check": choices_resize_mode, "exclude": None},
|
417 |
+
{"name": "preprocessor", "type": str, "check": choices_preprocessor, "exclude": None},
|
418 |
+
]
|
419 |
+
|
420 |
+
extra_axis_options = [
|
421 |
+
xyz_grid.AxisOption("[ControlNet] Enabled", identity, apply_field("control_net_enabled"), confirm=confirm(bool_), choices=choices_bool),
|
422 |
+
xyz_grid.AxisOption("[ControlNet] Model", identity, apply_field("control_net_model"), confirm=confirm("model"), choices=choices_model, cost=0.9),
|
423 |
+
xyz_grid.AxisOption("[ControlNet] Weight", identity, apply_field("control_net_weight"), confirm=confirm(float)),
|
424 |
+
xyz_grid.AxisOption("[ControlNet] Guidance Start", identity, apply_field("control_net_guidance_start"), confirm=confirm(float)),
|
425 |
+
xyz_grid.AxisOption("[ControlNet] Guidance End", identity, apply_field("control_net_guidance_end"), confirm=confirm(float)),
|
426 |
+
xyz_grid.AxisOption("[ControlNet] Resize Mode", identity, apply_field("control_net_resize_mode"), confirm=confirm("resize_mode"), choices=choices_resize_mode),
|
427 |
+
xyz_grid.AxisOption("[ControlNet] Preprocessor", identity, apply_field("control_net_module"), confirm=confirm("preprocessor"), choices=choices_preprocessor),
|
428 |
+
xyz_grid.AxisOption("[ControlNet] Pre Resolution", identity, apply_field("control_net_pres"), confirm=confirm(int)),
|
429 |
+
xyz_grid.AxisOption("[ControlNet] Pre Threshold A", identity, apply_field("control_net_pthr_a"), confirm=confirm(float)),
|
430 |
+
xyz_grid.AxisOption("[ControlNet] Pre Threshold B", identity, apply_field("control_net_pthr_b"), confirm=confirm(float)),
|
431 |
+
]
|
432 |
+
|
433 |
+
xyz_grid.axis_options.extend(extra_axis_options)
|
434 |
+
|
435 |
+
|
436 |
+
def run():
|
437 |
+
xyz_grid = find_module("xyz_grid.py, xy_grid.py")
|
438 |
+
if xyz_grid:
|
439 |
+
add_axis_options(xyz_grid)
|
440 |
+
|
441 |
+
|
442 |
+
if not import_error:
|
443 |
+
run()
|
extensions/microsoftexcel-controlnet/tests/annotator_tests/openpose_tests/body_test.py
ADDED
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import unittest
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
import importlib
|
5 |
+
utils = importlib.import_module('extensions.sd-webui-controlnet.tests.utils', 'utils')
|
6 |
+
utils.setup_test_env()
|
7 |
+
|
8 |
+
from annotator.openpose.body import Body, Keypoint, BodyResult
|
9 |
+
|
10 |
+
class TestFormatBodyResult(unittest.TestCase):
|
11 |
+
def setUp(self):
|
12 |
+
self.candidate = np.array([
|
13 |
+
[10, 20, 0.9, 0],
|
14 |
+
[30, 40, 0.8, 1],
|
15 |
+
[50, 60, 0.7, 2],
|
16 |
+
[70, 80, 0.6, 3]
|
17 |
+
])
|
18 |
+
|
19 |
+
self.subset = np.array([
|
20 |
+
[-1, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1.7, 2],
|
21 |
+
[-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 3, 0.6, 1]
|
22 |
+
])
|
23 |
+
|
24 |
+
def test_format_body_result(self):
|
25 |
+
expected_result = [
|
26 |
+
BodyResult(
|
27 |
+
keypoints=[
|
28 |
+
None,
|
29 |
+
Keypoint(x=10, y=20, score=0.9, id=0),
|
30 |
+
Keypoint(x=30, y=40, score=0.8, id=1),
|
31 |
+
None
|
32 |
+
] + [None] * 14,
|
33 |
+
total_score=1.7,
|
34 |
+
total_parts=2
|
35 |
+
),
|
36 |
+
BodyResult(
|
37 |
+
keypoints=[None] * 17 + [
|
38 |
+
Keypoint(x=70, y=80, score=0.6, id=3)
|
39 |
+
],
|
40 |
+
total_score=0.6,
|
41 |
+
total_parts=1
|
42 |
+
)
|
43 |
+
]
|
44 |
+
|
45 |
+
result = Body.format_body_result(self.candidate, self.subset)
|
46 |
+
|
47 |
+
self.assertEqual(result, expected_result)
|
48 |
+
|
49 |
+
if __name__ == '__main__':
|
50 |
+
unittest.main()
|
extensions/microsoftexcel-controlnet/tests/annotator_tests/openpose_tests/detection_test.py
ADDED
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import unittest
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
import importlib
|
5 |
+
utils = importlib.import_module('extensions.sd-webui-controlnet.tests.utils', 'utils')
|
6 |
+
utils.setup_test_env()
|
7 |
+
|
8 |
+
from annotator.openpose.util import faceDetect, handDetect
|
9 |
+
from annotator.openpose.body import Keypoint, BodyResult
|
10 |
+
|
11 |
+
class TestFaceDetect(unittest.TestCase):
|
12 |
+
def test_no_faces(self):
|
13 |
+
oriImg = np.zeros((100, 100, 3), dtype=np.uint8)
|
14 |
+
body = BodyResult([None] * 18, total_score=3, total_parts=0)
|
15 |
+
expected_result = None
|
16 |
+
result = faceDetect(body, oriImg)
|
17 |
+
|
18 |
+
self.assertEqual(result, expected_result)
|
19 |
+
|
20 |
+
def test_single_face(self):
|
21 |
+
body = BodyResult([
|
22 |
+
Keypoint(50, 50),
|
23 |
+
*([None] * 13),
|
24 |
+
Keypoint(30, 40),
|
25 |
+
Keypoint(70, 40),
|
26 |
+
Keypoint(20, 50),
|
27 |
+
Keypoint(80, 50),
|
28 |
+
], total_score=2, total_parts=5)
|
29 |
+
|
30 |
+
oriImg = np.zeros((100, 100, 3), dtype=np.uint8)
|
31 |
+
|
32 |
+
expected_result = (0, 0, 120)
|
33 |
+
result = faceDetect(body, oriImg)
|
34 |
+
|
35 |
+
self.assertEqual(result, expected_result)
|
36 |
+
|
37 |
+
class TestHandDetect(unittest.TestCase):
|
38 |
+
def test_no_hands(self):
|
39 |
+
oriImg = np.zeros((100, 100, 3), dtype=np.uint8)
|
40 |
+
body = BodyResult([None] * 18, total_score=3, total_parts=0)
|
41 |
+
expected_result = []
|
42 |
+
result = handDetect(body, oriImg)
|
43 |
+
|
44 |
+
self.assertEqual(result, expected_result)
|
45 |
+
|
46 |
+
def test_single_left_hand(self):
|
47 |
+
oriImg = np.zeros((100, 100, 3), dtype=np.uint8)
|
48 |
+
|
49 |
+
body = BodyResult([
|
50 |
+
None, None, None, None, None,
|
51 |
+
Keypoint(20, 20),
|
52 |
+
Keypoint(40, 30),
|
53 |
+
Keypoint(60, 40),
|
54 |
+
*([None] * 8),
|
55 |
+
Keypoint(20, 60),
|
56 |
+
Keypoint(40, 70),
|
57 |
+
Keypoint(60, 80)
|
58 |
+
], total_score=3, total_parts=0.5)
|
59 |
+
|
60 |
+
expected_result = [(49, 26, 33, True)]
|
61 |
+
result = handDetect(body, oriImg)
|
62 |
+
|
63 |
+
self.assertEqual(result, expected_result)
|
64 |
+
|
65 |
+
def test_single_right_hand(self):
|
66 |
+
oriImg = np.zeros((100, 100, 3), dtype=np.uint8)
|
67 |
+
|
68 |
+
body = BodyResult([
|
69 |
+
None, None,
|
70 |
+
Keypoint(20, 20),
|
71 |
+
Keypoint(40, 30),
|
72 |
+
Keypoint(60, 40),
|
73 |
+
*([None] * 11),
|
74 |
+
Keypoint(20, 60),
|
75 |
+
Keypoint(40, 70),
|
76 |
+
Keypoint(60, 80)
|
77 |
+
], total_score=3, total_parts=0.5)
|
78 |
+
|
79 |
+
expected_result = [(49, 26, 33, False)]
|
80 |
+
result = handDetect(body, oriImg)
|
81 |
+
|
82 |
+
self.assertEqual(result, expected_result)
|
83 |
+
|
84 |
+
def test_multiple_hands(self):
|
85 |
+
body = BodyResult([
|
86 |
+
Keypoint(20, 20),
|
87 |
+
Keypoint(40, 30),
|
88 |
+
Keypoint(60, 40),
|
89 |
+
Keypoint(20, 60),
|
90 |
+
Keypoint(40, 70),
|
91 |
+
Keypoint(60, 80),
|
92 |
+
Keypoint(10, 10),
|
93 |
+
Keypoint(30, 20),
|
94 |
+
Keypoint(50, 30),
|
95 |
+
Keypoint(10, 50),
|
96 |
+
Keypoint(30, 60),
|
97 |
+
Keypoint(50, 70),
|
98 |
+
*([None] * 6),
|
99 |
+
], total_score=3, total_parts=0.5)
|
100 |
+
|
101 |
+
oriImg = np.zeros((100, 100, 3), dtype=np.uint8)
|
102 |
+
|
103 |
+
expected_result = [(0, 0, 100, True), (16, 43, 56, False)]
|
104 |
+
result = handDetect(body, oriImg)
|
105 |
+
self.assertEqual(result, expected_result)
|
106 |
+
|
107 |
+
|
108 |
+
if __name__ == '__main__':
|
109 |
+
unittest.main()
|
extensions/microsoftexcel-controlnet/tests/annotator_tests/openpose_tests/json_encode_test.py
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import json
|
2 |
+
import unittest
|
3 |
+
import numpy as np
|
4 |
+
|
5 |
+
import importlib
|
6 |
+
utils = importlib.import_module('extensions.sd-webui-controlnet.tests.utils', 'utils')
|
7 |
+
utils.setup_test_env()
|
8 |
+
|
9 |
+
from annotator.openpose import encode_poses_as_json, PoseResult, Keypoint
|
10 |
+
from annotator.openpose.body import BodyResult
|
11 |
+
|
12 |
+
class TestEncodePosesAsJson(unittest.TestCase):
|
13 |
+
def test_empty_list(self):
|
14 |
+
poses = []
|
15 |
+
canvas_height = 1080
|
16 |
+
canvas_width = 1920
|
17 |
+
result = encode_poses_as_json(poses, canvas_height, canvas_width)
|
18 |
+
expected = json.dumps({
|
19 |
+
'people': [],
|
20 |
+
'canvas_height': canvas_height,
|
21 |
+
'canvas_width': canvas_width,
|
22 |
+
}, indent=4)
|
23 |
+
self.assertEqual(result, expected)
|
24 |
+
|
25 |
+
def test_single_pose_no_keypoints(self):
|
26 |
+
poses = [PoseResult(BodyResult(None, 0, 0), None, None, None)]
|
27 |
+
canvas_height = 1080
|
28 |
+
canvas_width = 1920
|
29 |
+
result = encode_poses_as_json(poses, canvas_height, canvas_width)
|
30 |
+
expected = json.dumps({
|
31 |
+
'people': [
|
32 |
+
{
|
33 |
+
'pose_keypoints_2d': None,
|
34 |
+
'face_keypoints_2d': None,
|
35 |
+
'hand_left_keypoints_2d': None,
|
36 |
+
'hand_right_keypoints_2d': None,
|
37 |
+
},
|
38 |
+
],
|
39 |
+
'canvas_height': canvas_height,
|
40 |
+
'canvas_width': canvas_width,
|
41 |
+
}, indent=4)
|
42 |
+
self.assertEqual(result, expected)
|
43 |
+
|
44 |
+
def test_single_pose_with_keypoints(self):
|
45 |
+
keypoints = [Keypoint(np.float32(0.5), np.float32(0.5)), None, Keypoint(0.6, 0.6)]
|
46 |
+
poses = [PoseResult(BodyResult(keypoints, 0, 0), keypoints, keypoints, keypoints)]
|
47 |
+
canvas_height = 1080
|
48 |
+
canvas_width = 1920
|
49 |
+
result = encode_poses_as_json(poses, canvas_height, canvas_width)
|
50 |
+
expected = json.dumps({
|
51 |
+
'people': [
|
52 |
+
{
|
53 |
+
'pose_keypoints_2d': [
|
54 |
+
0.5, 0.5, 1.0,
|
55 |
+
0.0, 0.0, 0.0,
|
56 |
+
0.6, 0.6, 1.0,
|
57 |
+
],
|
58 |
+
'face_keypoints_2d': [
|
59 |
+
0.5, 0.5, 1.0,
|
60 |
+
0.0, 0.0, 0.0,
|
61 |
+
0.6, 0.6, 1.0,
|
62 |
+
],
|
63 |
+
'hand_left_keypoints_2d': [
|
64 |
+
0.5, 0.5, 1.0,
|
65 |
+
0.0, 0.0, 0.0,
|
66 |
+
0.6, 0.6, 1.0,
|
67 |
+
],
|
68 |
+
'hand_right_keypoints_2d': [
|
69 |
+
0.5, 0.5, 1.0,
|
70 |
+
0.0, 0.0, 0.0,
|
71 |
+
0.6, 0.6, 1.0,
|
72 |
+
],
|
73 |
+
},
|
74 |
+
],
|
75 |
+
'canvas_height': canvas_height,
|
76 |
+
'canvas_width': canvas_width,
|
77 |
+
}, indent=4)
|
78 |
+
self.assertEqual(result, expected)
|
79 |
+
|
80 |
+
if __name__ == '__main__':
|
81 |
+
unittest.main()
|
extensions/microsoftexcel-controlnet/tests/annotator_tests/openpose_tests/openpose_e2e_test.py
ADDED
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import unittest
|
2 |
+
import cv2
|
3 |
+
import numpy as np
|
4 |
+
from typing import Dict
|
5 |
+
|
6 |
+
|
7 |
+
import importlib
|
8 |
+
utils = importlib.import_module('extensions.sd-webui-controlnet.tests.utils', 'utils')
|
9 |
+
utils.setup_test_env()
|
10 |
+
|
11 |
+
from annotator.openpose import OpenposeDetector
|
12 |
+
|
13 |
+
class TestOpenposeDetector(unittest.TestCase):
|
14 |
+
image_path = './tests/images'
|
15 |
+
def setUp(self) -> None:
|
16 |
+
self.detector = OpenposeDetector()
|
17 |
+
self.detector.load_model()
|
18 |
+
|
19 |
+
def tearDown(self) -> None:
|
20 |
+
self.detector.unload_model()
|
21 |
+
|
22 |
+
def expect_same_image(self, img1, img2, diff_img_path: str):
|
23 |
+
# Calculate the difference between the two images
|
24 |
+
diff = cv2.absdiff(img1, img2)
|
25 |
+
|
26 |
+
# Set a threshold to highlight the different pixels
|
27 |
+
threshold = 30
|
28 |
+
diff_highlighted = np.where(diff > threshold, 255, 0).astype(np.uint8)
|
29 |
+
|
30 |
+
# Assert that the two images are similar within a tolerance
|
31 |
+
similar = np.allclose(img1, img2, rtol=1e-05, atol=1e-08)
|
32 |
+
if not similar:
|
33 |
+
# Save the diff_highlighted image to inspect the differences
|
34 |
+
cv2.imwrite(diff_img_path, diff_highlighted)
|
35 |
+
|
36 |
+
self.assertTrue(similar)
|
37 |
+
|
38 |
+
# Save expectation image as png so that no compression issue happens.
|
39 |
+
def template(self, test_image: str, expected_image: str, detector_config: Dict, overwrite_expectation: bool = False):
|
40 |
+
oriImg = cv2.imread(test_image)
|
41 |
+
canvas = self.detector(oriImg, **detector_config)
|
42 |
+
|
43 |
+
# Create expectation file
|
44 |
+
if overwrite_expectation:
|
45 |
+
cv2.imwrite(expected_image, canvas)
|
46 |
+
else:
|
47 |
+
expected_canvas = cv2.imread(expected_image)
|
48 |
+
self.expect_same_image(canvas, expected_canvas, diff_img_path=expected_image.replace('.png', '_diff.png'))
|
49 |
+
|
50 |
+
def test_body(self):
|
51 |
+
self.template(
|
52 |
+
test_image = f'{TestOpenposeDetector.image_path}/ski.jpg',
|
53 |
+
expected_image = f'{TestOpenposeDetector.image_path}/expected_ski_output.png',
|
54 |
+
detector_config=dict(),
|
55 |
+
overwrite_expectation=False
|
56 |
+
)
|
57 |
+
|
58 |
+
def test_hand(self):
|
59 |
+
self.template(
|
60 |
+
test_image = f'{TestOpenposeDetector.image_path}/woman.jpeg',
|
61 |
+
expected_image = f'{TestOpenposeDetector.image_path}/expected_woman_hand_output.png',
|
62 |
+
detector_config=dict(
|
63 |
+
include_body=False,
|
64 |
+
include_face=False,
|
65 |
+
include_hand=True,
|
66 |
+
),
|
67 |
+
overwrite_expectation=False
|
68 |
+
)
|
69 |
+
|
70 |
+
def test_face(self):
|
71 |
+
self.template(
|
72 |
+
test_image = f'{TestOpenposeDetector.image_path}/woman.jpeg',
|
73 |
+
expected_image = f'{TestOpenposeDetector.image_path}/expected_woman_face_output.png',
|
74 |
+
detector_config=dict(
|
75 |
+
include_body=False,
|
76 |
+
include_face=True,
|
77 |
+
include_hand=False,
|
78 |
+
),
|
79 |
+
overwrite_expectation=False
|
80 |
+
)
|
81 |
+
|
82 |
+
def test_all(self):
|
83 |
+
self.template(
|
84 |
+
test_image = f'{TestOpenposeDetector.image_path}/woman.jpeg',
|
85 |
+
expected_image = f'{TestOpenposeDetector.image_path}/expected_woman_all_output.png',
|
86 |
+
detector_config=dict(
|
87 |
+
include_body=True,
|
88 |
+
include_face=True,
|
89 |
+
include_hand=True,
|
90 |
+
),
|
91 |
+
overwrite_expectation=False
|
92 |
+
)
|
93 |
+
|
94 |
+
if __name__ == '__main__':
|
95 |
+
unittest.main()
|
extensions/microsoftexcel-controlnet/tests/cn_script/__init__.py
ADDED
File without changes
|
extensions/microsoftexcel-controlnet/tests/cn_script/batch_hijack_test.py
ADDED
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import unittest.mock
|
2 |
+
import importlib
|
3 |
+
from typing import Any
|
4 |
+
|
5 |
+
utils = importlib.import_module('extensions.sd-webui-controlnet.tests.utils', 'utils')
|
6 |
+
utils.setup_test_env()
|
7 |
+
|
8 |
+
from modules import processing, scripts, shared
|
9 |
+
from scripts import controlnet, external_code, batch_hijack
|
10 |
+
|
11 |
+
|
12 |
+
batch_hijack.instance.undo_hijack()
|
13 |
+
original_process_images_inner = processing.process_images_inner
|
14 |
+
|
15 |
+
|
16 |
+
class TestBatchHijack(unittest.TestCase):
|
17 |
+
@unittest.mock.patch('modules.script_callbacks.on_script_unloaded')
|
18 |
+
def setUp(self, on_script_unloaded_mock):
|
19 |
+
self.on_script_unloaded_mock = on_script_unloaded_mock
|
20 |
+
|
21 |
+
self.batch_hijack_object = batch_hijack.BatchHijack()
|
22 |
+
self.batch_hijack_object.do_hijack()
|
23 |
+
|
24 |
+
def tearDown(self):
|
25 |
+
self.batch_hijack_object.undo_hijack()
|
26 |
+
|
27 |
+
def test_do_hijack__registers_on_script_unloaded(self):
|
28 |
+
self.on_script_unloaded_mock.assert_called_once_with(self.batch_hijack_object.undo_hijack)
|
29 |
+
|
30 |
+
def test_do_hijack__call_once__hijacks_once(self):
|
31 |
+
self.assertEqual(getattr(processing, '__controlnet_original_process_images_inner'), original_process_images_inner)
|
32 |
+
self.assertEqual(processing.process_images_inner, self.batch_hijack_object.processing_process_images_hijack)
|
33 |
+
|
34 |
+
@unittest.mock.patch('modules.processing.__controlnet_original_process_images_inner')
|
35 |
+
def test_do_hijack__multiple_times__hijacks_once(self, process_images_inner_mock):
|
36 |
+
self.batch_hijack_object.do_hijack()
|
37 |
+
self.batch_hijack_object.do_hijack()
|
38 |
+
self.batch_hijack_object.do_hijack()
|
39 |
+
self.assertEqual(process_images_inner_mock, getattr(processing, '__controlnet_original_process_images_inner'))
|
40 |
+
|
41 |
+
|
42 |
+
class TestGetControlNetBatchesWorks(unittest.TestCase):
|
43 |
+
def setUp(self):
|
44 |
+
self.p = unittest.mock.MagicMock()
|
45 |
+
self.p.scripts = scripts.scripts_txt2img
|
46 |
+
self.cn_script = controlnet.Script()
|
47 |
+
self.p.scripts.alwayson_scripts = [self.cn_script]
|
48 |
+
self.p.script_args = []
|
49 |
+
|
50 |
+
def tearDown(self):
|
51 |
+
batch_hijack.instance.dispatch_callbacks(batch_hijack.instance.postprocess_batch_callbacks, self.p)
|
52 |
+
|
53 |
+
def assert_get_cn_batches_works(self, batch_images_list):
|
54 |
+
self.cn_script.args_from = 0
|
55 |
+
self.cn_script.args_to = self.cn_script.args_from + len(self.p.script_args)
|
56 |
+
|
57 |
+
is_cn_batch, batches, output_dir, _ = batch_hijack.get_cn_batches(self.p)
|
58 |
+
batch_hijack.instance.dispatch_callbacks(batch_hijack.instance.process_batch_callbacks, self.p, batches, output_dir)
|
59 |
+
|
60 |
+
batch_units = [unit for unit in self.p.script_args if getattr(unit, 'input_mode', batch_hijack.InputMode.SIMPLE) == batch_hijack.InputMode.BATCH]
|
61 |
+
if batch_units:
|
62 |
+
self.assertEqual(min(len(unit.batch_images) for unit in batch_units), len(batches))
|
63 |
+
else:
|
64 |
+
self.assertEqual(1, len(batches))
|
65 |
+
|
66 |
+
for i, unit in enumerate(self.cn_script.enabled_units):
|
67 |
+
self.assertListEqual(batch_images_list[i], list(unit.batch_images))
|
68 |
+
|
69 |
+
def test_get_cn_batches__empty(self):
|
70 |
+
is_batch, batches, _, _ = batch_hijack.get_cn_batches(self.p)
|
71 |
+
self.assertEqual(1, len(batches))
|
72 |
+
self.assertEqual(is_batch, False)
|
73 |
+
|
74 |
+
def test_get_cn_batches__1_simple(self):
|
75 |
+
self.p.script_args.append(external_code.ControlNetUnit(image=get_dummy_image()))
|
76 |
+
self.assert_get_cn_batches_works([
|
77 |
+
[self.p.script_args[0].image],
|
78 |
+
])
|
79 |
+
|
80 |
+
def test_get_cn_batches__2_simples(self):
|
81 |
+
self.p.script_args.extend([
|
82 |
+
external_code.ControlNetUnit(image=get_dummy_image(0)),
|
83 |
+
external_code.ControlNetUnit(image=get_dummy_image(1)),
|
84 |
+
])
|
85 |
+
self.assert_get_cn_batches_works([
|
86 |
+
[get_dummy_image(0)],
|
87 |
+
[get_dummy_image(1)],
|
88 |
+
])
|
89 |
+
|
90 |
+
def test_get_cn_batches__1_batch(self):
|
91 |
+
self.p.script_args.extend([
|
92 |
+
controlnet.UiControlNetUnit(
|
93 |
+
input_mode=batch_hijack.InputMode.BATCH,
|
94 |
+
batch_images=[
|
95 |
+
get_dummy_image(0),
|
96 |
+
get_dummy_image(1),
|
97 |
+
],
|
98 |
+
),
|
99 |
+
])
|
100 |
+
self.assert_get_cn_batches_works([
|
101 |
+
[
|
102 |
+
get_dummy_image(0),
|
103 |
+
get_dummy_image(1),
|
104 |
+
],
|
105 |
+
])
|
106 |
+
|
107 |
+
def test_get_cn_batches__2_batches(self):
|
108 |
+
self.p.script_args.extend([
|
109 |
+
controlnet.UiControlNetUnit(
|
110 |
+
input_mode=batch_hijack.InputMode.BATCH,
|
111 |
+
batch_images=[
|
112 |
+
get_dummy_image(0),
|
113 |
+
get_dummy_image(1),
|
114 |
+
],
|
115 |
+
),
|
116 |
+
controlnet.UiControlNetUnit(
|
117 |
+
input_mode=batch_hijack.InputMode.BATCH,
|
118 |
+
batch_images=[
|
119 |
+
get_dummy_image(2),
|
120 |
+
get_dummy_image(3),
|
121 |
+
],
|
122 |
+
),
|
123 |
+
])
|
124 |
+
self.assert_get_cn_batches_works([
|
125 |
+
[
|
126 |
+
get_dummy_image(0),
|
127 |
+
get_dummy_image(1),
|
128 |
+
],
|
129 |
+
[
|
130 |
+
get_dummy_image(2),
|
131 |
+
get_dummy_image(3),
|
132 |
+
],
|
133 |
+
])
|
134 |
+
|
135 |
+
def test_get_cn_batches__2_mixed(self):
|
136 |
+
self.p.script_args.extend([
|
137 |
+
external_code.ControlNetUnit(image=get_dummy_image(0)),
|
138 |
+
controlnet.UiControlNetUnit(
|
139 |
+
input_mode=batch_hijack.InputMode.BATCH,
|
140 |
+
batch_images=[
|
141 |
+
get_dummy_image(1),
|
142 |
+
get_dummy_image(2),
|
143 |
+
],
|
144 |
+
),
|
145 |
+
])
|
146 |
+
self.assert_get_cn_batches_works([
|
147 |
+
[
|
148 |
+
get_dummy_image(0),
|
149 |
+
get_dummy_image(0),
|
150 |
+
],
|
151 |
+
[
|
152 |
+
get_dummy_image(1),
|
153 |
+
get_dummy_image(2),
|
154 |
+
],
|
155 |
+
])
|
156 |
+
|
157 |
+
def test_get_cn_batches__3_mixed(self):
|
158 |
+
self.p.script_args.extend([
|
159 |
+
external_code.ControlNetUnit(image=get_dummy_image(0)),
|
160 |
+
controlnet.UiControlNetUnit(
|
161 |
+
input_mode=batch_hijack.InputMode.BATCH,
|
162 |
+
batch_images=[
|
163 |
+
get_dummy_image(1),
|
164 |
+
get_dummy_image(2),
|
165 |
+
get_dummy_image(3),
|
166 |
+
],
|
167 |
+
),
|
168 |
+
controlnet.UiControlNetUnit(
|
169 |
+
input_mode=batch_hijack.InputMode.BATCH,
|
170 |
+
batch_images=[
|
171 |
+
get_dummy_image(4),
|
172 |
+
get_dummy_image(5),
|
173 |
+
],
|
174 |
+
),
|
175 |
+
])
|
176 |
+
self.assert_get_cn_batches_works([
|
177 |
+
[
|
178 |
+
get_dummy_image(0),
|
179 |
+
get_dummy_image(0),
|
180 |
+
],
|
181 |
+
[
|
182 |
+
get_dummy_image(1),
|
183 |
+
get_dummy_image(2),
|
184 |
+
],
|
185 |
+
[
|
186 |
+
get_dummy_image(4),
|
187 |
+
get_dummy_image(5),
|
188 |
+
],
|
189 |
+
])
|
190 |
+
|
191 |
+
class TestProcessImagesPatchWorks(unittest.TestCase):
|
192 |
+
@unittest.mock.patch('modules.script_callbacks.on_script_unloaded')
|
193 |
+
def setUp(self, on_script_unloaded_mock):
|
194 |
+
self.on_script_unloaded_mock = on_script_unloaded_mock
|
195 |
+
self.p = unittest.mock.MagicMock()
|
196 |
+
self.p.scripts = scripts.scripts_txt2img
|
197 |
+
self.cn_script = controlnet.Script()
|
198 |
+
self.p.scripts.alwayson_scripts = [self.cn_script]
|
199 |
+
self.p.script_args = []
|
200 |
+
self.p.all_seeds = [0]
|
201 |
+
self.p.all_subseeds = [0]
|
202 |
+
self.old_model, shared.sd_model = shared.sd_model, unittest.mock.MagicMock()
|
203 |
+
|
204 |
+
self.batch_hijack_object = batch_hijack.BatchHijack()
|
205 |
+
self.callbacks_mock = unittest.mock.MagicMock()
|
206 |
+
self.batch_hijack_object.process_batch_callbacks.append(self.callbacks_mock.process)
|
207 |
+
self.batch_hijack_object.process_batch_each_callbacks.append(self.callbacks_mock.process_each)
|
208 |
+
self.batch_hijack_object.postprocess_batch_each_callbacks.insert(0, self.callbacks_mock.postprocess_each)
|
209 |
+
self.batch_hijack_object.postprocess_batch_callbacks.insert(0, self.callbacks_mock.postprocess)
|
210 |
+
self.batch_hijack_object.do_hijack()
|
211 |
+
shared.state.begin()
|
212 |
+
|
213 |
+
def tearDown(self):
|
214 |
+
shared.state.end()
|
215 |
+
self.batch_hijack_object.undo_hijack()
|
216 |
+
shared.sd_model = self.old_model
|
217 |
+
|
218 |
+
@unittest.mock.patch('modules.processing.__controlnet_original_process_images_inner')
|
219 |
+
def assert_process_images_hijack_called(self, process_images_mock, batch_count):
|
220 |
+
process_images_mock.return_value = processing.Processed(self.p, [get_dummy_image('output')])
|
221 |
+
with unittest.mock.patch.dict(shared.opts.data, {
|
222 |
+
'controlnet_show_batch_images_in_ui': True,
|
223 |
+
}):
|
224 |
+
res = processing.process_images_inner(self.p)
|
225 |
+
|
226 |
+
self.assertEqual(res, process_images_mock.return_value)
|
227 |
+
|
228 |
+
if batch_count > 0:
|
229 |
+
self.callbacks_mock.process.assert_called()
|
230 |
+
self.callbacks_mock.postprocess.assert_called()
|
231 |
+
else:
|
232 |
+
self.callbacks_mock.process.assert_not_called()
|
233 |
+
self.callbacks_mock.postprocess.assert_not_called()
|
234 |
+
|
235 |
+
self.assertEqual(self.callbacks_mock.process_each.call_count, batch_count)
|
236 |
+
self.assertEqual(self.callbacks_mock.postprocess_each.call_count, batch_count)
|
237 |
+
|
238 |
+
def test_process_images_no_units_forwards(self):
|
239 |
+
self.assert_process_images_hijack_called(batch_count=0)
|
240 |
+
|
241 |
+
def test_process_images__only_simple_units__forwards(self):
|
242 |
+
self.p.script_args = [
|
243 |
+
external_code.ControlNetUnit(image=get_dummy_image()),
|
244 |
+
external_code.ControlNetUnit(image=get_dummy_image()),
|
245 |
+
]
|
246 |
+
self.assert_process_images_hijack_called(batch_count=0)
|
247 |
+
|
248 |
+
def test_process_images__1_batch_1_unit__runs_1_batch(self):
|
249 |
+
self.p.script_args = [
|
250 |
+
controlnet.UiControlNetUnit(
|
251 |
+
input_mode=batch_hijack.InputMode.BATCH,
|
252 |
+
batch_images=[
|
253 |
+
get_dummy_image(),
|
254 |
+
],
|
255 |
+
),
|
256 |
+
]
|
257 |
+
self.assert_process_images_hijack_called(batch_count=1)
|
258 |
+
|
259 |
+
def test_process_images__2_batches_1_unit__runs_2_batches(self):
|
260 |
+
self.p.script_args = [
|
261 |
+
controlnet.UiControlNetUnit(
|
262 |
+
input_mode=batch_hijack.InputMode.BATCH,
|
263 |
+
batch_images=[
|
264 |
+
get_dummy_image(0),
|
265 |
+
get_dummy_image(1),
|
266 |
+
],
|
267 |
+
),
|
268 |
+
]
|
269 |
+
self.assert_process_images_hijack_called(batch_count=2)
|
270 |
+
|
271 |
+
def test_process_images__8_batches_1_unit__runs_8_batches(self):
|
272 |
+
batch_count = 8
|
273 |
+
self.p.script_args = [
|
274 |
+
controlnet.UiControlNetUnit(
|
275 |
+
input_mode=batch_hijack.InputMode.BATCH,
|
276 |
+
batch_images=[get_dummy_image(i) for i in range(batch_count)]
|
277 |
+
),
|
278 |
+
]
|
279 |
+
self.assert_process_images_hijack_called(batch_count=batch_count)
|
280 |
+
|
281 |
+
def test_process_images__1_batch_2_units__runs_1_batch(self):
|
282 |
+
self.p.script_args = [
|
283 |
+
controlnet.UiControlNetUnit(
|
284 |
+
input_mode=batch_hijack.InputMode.BATCH,
|
285 |
+
batch_images=[get_dummy_image(0)]
|
286 |
+
),
|
287 |
+
controlnet.UiControlNetUnit(
|
288 |
+
input_mode=batch_hijack.InputMode.BATCH,
|
289 |
+
batch_images=[get_dummy_image(1)]
|
290 |
+
),
|
291 |
+
]
|
292 |
+
self.assert_process_images_hijack_called(batch_count=1)
|
293 |
+
|
294 |
+
def test_process_images__2_batches_2_units__runs_2_batches(self):
|
295 |
+
self.p.script_args = [
|
296 |
+
controlnet.UiControlNetUnit(
|
297 |
+
input_mode=batch_hijack.InputMode.BATCH,
|
298 |
+
batch_images=[
|
299 |
+
get_dummy_image(0),
|
300 |
+
get_dummy_image(1),
|
301 |
+
],
|
302 |
+
),
|
303 |
+
controlnet.UiControlNetUnit(
|
304 |
+
input_mode=batch_hijack.InputMode.BATCH,
|
305 |
+
batch_images=[
|
306 |
+
get_dummy_image(2),
|
307 |
+
get_dummy_image(3),
|
308 |
+
],
|
309 |
+
),
|
310 |
+
]
|
311 |
+
self.assert_process_images_hijack_called(batch_count=2)
|
312 |
+
|
313 |
+
def test_process_images__3_batches_2_mixed_units__runs_3_batches(self):
|
314 |
+
self.p.script_args = [
|
315 |
+
controlnet.UiControlNetUnit(
|
316 |
+
input_mode=batch_hijack.InputMode.BATCH,
|
317 |
+
batch_images=[
|
318 |
+
get_dummy_image(0),
|
319 |
+
get_dummy_image(1),
|
320 |
+
get_dummy_image(2),
|
321 |
+
],
|
322 |
+
),
|
323 |
+
controlnet.UiControlNetUnit(
|
324 |
+
input_mode=batch_hijack.InputMode.SIMPLE,
|
325 |
+
image=get_dummy_image(3),
|
326 |
+
),
|
327 |
+
]
|
328 |
+
self.assert_process_images_hijack_called(batch_count=3)
|
329 |
+
|
330 |
+
|
331 |
+
def get_dummy_image(name: Any = 0):
|
332 |
+
return f'base64#{name}...'
|
extensions/microsoftexcel-controlnet/tests/cn_script/utils_test.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import importlib
|
2 |
+
utils = importlib.import_module('extensions.sd-webui-controlnet.tests.utils', 'utils')
|
3 |
+
utils.setup_test_env()
|
4 |
+
|
5 |
+
from scripts.utils import ndarray_lru_cache
|
6 |
+
|
7 |
+
import unittest
|
8 |
+
import numpy as np
|
9 |
+
|
10 |
+
class TestNumpyLruCache(unittest.TestCase):
|
11 |
+
|
12 |
+
def setUp(self):
|
13 |
+
self.arr1 = np.array([1, 2, 3, 4, 5])
|
14 |
+
self.arr2 = np.array([1, 2, 3, 4, 5])
|
15 |
+
|
16 |
+
@ndarray_lru_cache(max_size=128)
|
17 |
+
def add_one(self, arr):
|
18 |
+
return arr + 1
|
19 |
+
|
20 |
+
def test_same_array(self):
|
21 |
+
# Test that the decorator works with numpy arrays.
|
22 |
+
result1 = self.add_one(self.arr1)
|
23 |
+
result2 = self.add_one(self.arr1)
|
24 |
+
|
25 |
+
# If caching is working correctly, these should be the same object.
|
26 |
+
self.assertIs(result1, result2)
|
27 |
+
|
28 |
+
def test_different_array_same_data(self):
|
29 |
+
# Test that the decorator works with different numpy arrays with the same data.
|
30 |
+
result1 = self.add_one(self.arr1)
|
31 |
+
result2 = self.add_one(self.arr2)
|
32 |
+
|
33 |
+
# If caching is working correctly, these should be the same object.
|
34 |
+
self.assertIs(result1, result2)
|
35 |
+
|
36 |
+
def test_cache_size(self):
|
37 |
+
# Test that the cache size limit is respected.
|
38 |
+
arrs = [np.array([i]) for i in range(150)]
|
39 |
+
|
40 |
+
# Add all arrays to the cache.
|
41 |
+
|
42 |
+
result1 = self.add_one(arrs[0])
|
43 |
+
for arr in arrs[1:]:
|
44 |
+
self.add_one(arr)
|
45 |
+
|
46 |
+
# Check that the first array is no longer in the cache.
|
47 |
+
result2 = self.add_one(arrs[0])
|
48 |
+
|
49 |
+
# If the cache size limit is working correctly, these should not be the same object.
|
50 |
+
self.assertIsNot(result1, result2)
|
51 |
+
|
52 |
+
def test_large_array(self):
|
53 |
+
# Create two large arrays with the same elements in the beginning and end, but one different element in the middle.
|
54 |
+
arr1 = np.ones(10000)
|
55 |
+
arr2 = np.ones(10000)
|
56 |
+
arr2[len(arr2)//2] = 0
|
57 |
+
|
58 |
+
result1 = self.add_one(arr1)
|
59 |
+
result2 = self.add_one(arr2)
|
60 |
+
|
61 |
+
# If hashing is working correctly, these should not be the same object because the input arrays are not equal.
|
62 |
+
self.assertIsNot(result1, result2)
|
63 |
+
|
64 |
+
if __name__ == '__main__':
|
65 |
+
unittest.main()
|
extensions/microsoftexcel-controlnet/tests/external_code_api/__init__.py
ADDED
File without changes
|
extensions/microsoftexcel-controlnet/tests/external_code_api/external_code_test.py
ADDED
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import unittest
|
2 |
+
import importlib
|
3 |
+
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
utils = importlib.import_module('extensions.sd-webui-controlnet.tests.utils', 'utils')
|
7 |
+
utils.setup_test_env()
|
8 |
+
|
9 |
+
from copy import copy
|
10 |
+
from scripts import external_code
|
11 |
+
from scripts import controlnet
|
12 |
+
from modules import scripts, ui, shared
|
13 |
+
|
14 |
+
|
15 |
+
class TestExternalCodeWorking(unittest.TestCase):
|
16 |
+
max_models = 6
|
17 |
+
args_offset = 10
|
18 |
+
|
19 |
+
def setUp(self):
|
20 |
+
self.scripts = copy(scripts.scripts_txt2img)
|
21 |
+
self.scripts.initialize_scripts(False)
|
22 |
+
ui.create_ui()
|
23 |
+
self.cn_script = controlnet.Script()
|
24 |
+
self.cn_script.args_from = self.args_offset
|
25 |
+
self.cn_script.args_to = self.args_offset + self.max_models
|
26 |
+
self.scripts.alwayson_scripts = [self.cn_script]
|
27 |
+
self.script_args = [None] * self.cn_script.args_from
|
28 |
+
|
29 |
+
self.initial_max_models = shared.opts.data.get("control_net_max_models_num", 1)
|
30 |
+
shared.opts.data.update(control_net_max_models_num=self.max_models)
|
31 |
+
|
32 |
+
self.extra_models = 0
|
33 |
+
|
34 |
+
def tearDown(self):
|
35 |
+
shared.opts.data.update(control_net_max_models_num=self.initial_max_models)
|
36 |
+
|
37 |
+
def get_expected_args_to(self):
|
38 |
+
args_len = max(self.max_models, len(self.cn_units))
|
39 |
+
return self.args_offset + args_len
|
40 |
+
|
41 |
+
def assert_update_in_place_ok(self):
|
42 |
+
external_code.update_cn_script_in_place(self.scripts, self.script_args, self.cn_units)
|
43 |
+
self.assertEqual(self.cn_script.args_to, self.get_expected_args_to())
|
44 |
+
|
45 |
+
def test_empty_resizes_min_args(self):
|
46 |
+
self.cn_units = []
|
47 |
+
self.assert_update_in_place_ok()
|
48 |
+
|
49 |
+
def test_empty_resizes_extra_args(self):
|
50 |
+
extra_models = 1
|
51 |
+
self.cn_units = [external_code.ControlNetUnit()] * (self.max_models + extra_models)
|
52 |
+
self.assert_update_in_place_ok()
|
53 |
+
|
54 |
+
|
55 |
+
class TestControlNetUnitConversion(unittest.TestCase):
|
56 |
+
def setUp(self):
|
57 |
+
self.dummy_image = 'base64...'
|
58 |
+
self.input = {}
|
59 |
+
self.expected = external_code.ControlNetUnit()
|
60 |
+
|
61 |
+
def assert_converts_to_expected(self):
|
62 |
+
self.assertEqual(vars(external_code.to_processing_unit(self.input)), vars(self.expected))
|
63 |
+
|
64 |
+
def test_empty_dict_works(self):
|
65 |
+
self.assert_converts_to_expected()
|
66 |
+
|
67 |
+
def test_image_works(self):
|
68 |
+
self.input = {
|
69 |
+
'image': self.dummy_image
|
70 |
+
}
|
71 |
+
self.expected = external_code.ControlNetUnit(image=self.dummy_image)
|
72 |
+
self.assert_converts_to_expected()
|
73 |
+
|
74 |
+
def test_image_alias_works(self):
|
75 |
+
self.input = {
|
76 |
+
'input_image': self.dummy_image
|
77 |
+
}
|
78 |
+
self.expected = external_code.ControlNetUnit(image=self.dummy_image)
|
79 |
+
self.assert_converts_to_expected()
|
80 |
+
|
81 |
+
def test_masked_image_works(self):
|
82 |
+
self.input = {
|
83 |
+
'image': self.dummy_image,
|
84 |
+
'mask': self.dummy_image,
|
85 |
+
}
|
86 |
+
self.expected = external_code.ControlNetUnit(image={'image': self.dummy_image, 'mask': self.dummy_image})
|
87 |
+
self.assert_converts_to_expected()
|
88 |
+
|
89 |
+
|
90 |
+
class TestControlNetUnitImageToDict(unittest.TestCase):
|
91 |
+
def setUp(self):
|
92 |
+
self.dummy_image = utils.readImage("test/test_files/img2img_basic.png")
|
93 |
+
self.input = external_code.ControlNetUnit()
|
94 |
+
self.expected_image = external_code.to_base64_nparray(self.dummy_image)
|
95 |
+
self.expected_mask = external_code.to_base64_nparray(self.dummy_image)
|
96 |
+
|
97 |
+
def assert_dict_is_valid(self):
|
98 |
+
actual_dict = controlnet.image_dict_from_any(self.input.image)
|
99 |
+
self.assertEqual(actual_dict['image'].tolist(), self.expected_image.tolist())
|
100 |
+
self.assertEqual(actual_dict['mask'].tolist(), self.expected_mask.tolist())
|
101 |
+
|
102 |
+
def test_none(self):
|
103 |
+
self.assertEqual(controlnet.image_dict_from_any(self.input.image), None)
|
104 |
+
|
105 |
+
def test_image_without_mask(self):
|
106 |
+
self.input.image = self.dummy_image
|
107 |
+
self.expected_mask = np.zeros_like(self.expected_image, dtype=np.uint8)
|
108 |
+
self.assert_dict_is_valid()
|
109 |
+
|
110 |
+
def test_masked_image_tuple(self):
|
111 |
+
self.input.image = (self.dummy_image, self.dummy_image,)
|
112 |
+
self.assert_dict_is_valid()
|
113 |
+
|
114 |
+
def test_masked_image_dict(self):
|
115 |
+
self.input.image = {'image': self.dummy_image, 'mask': self.dummy_image}
|
116 |
+
self.assert_dict_is_valid()
|
117 |
+
|
118 |
+
|
119 |
+
if __name__ == '__main__':
|
120 |
+
unittest.main()
|
extensions/microsoftexcel-controlnet/tests/external_code_api/script_args_test.py
ADDED
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import unittest
|
2 |
+
import importlib
|
3 |
+
utils = importlib.import_module('extensions.sd-webui-controlnet.tests.utils', 'utils')
|
4 |
+
utils.setup_test_env()
|
5 |
+
|
6 |
+
from scripts import external_code
|
7 |
+
|
8 |
+
|
9 |
+
class TestGetAllUnitsFrom(unittest.TestCase):
|
10 |
+
def setUp(self):
|
11 |
+
self.control_unit = {
|
12 |
+
"module": "none",
|
13 |
+
"model": utils.get_model(),
|
14 |
+
"image": utils.readImage("test/test_files/img2img_basic.png"),
|
15 |
+
"resize_mode": 1,
|
16 |
+
"low_vram": False,
|
17 |
+
"processor_res": 64,
|
18 |
+
"control_mode": external_code.ControlMode.BALANCED.value,
|
19 |
+
}
|
20 |
+
self.object_unit = external_code.ControlNetUnit(**self.control_unit)
|
21 |
+
|
22 |
+
def test_empty_converts(self):
|
23 |
+
script_args = []
|
24 |
+
units = external_code.get_all_units_from(script_args)
|
25 |
+
self.assertListEqual(units, [])
|
26 |
+
|
27 |
+
def test_object_forwards(self):
|
28 |
+
script_args = [self.object_unit]
|
29 |
+
units = external_code.get_all_units_from(script_args)
|
30 |
+
self.assertListEqual(units, [self.object_unit])
|
31 |
+
|
32 |
+
|
33 |
+
if __name__ == '__main__':
|
34 |
+
unittest.main()
|
extensions/microsoftexcel-controlnet/tests/images/expected_ski_output.png
ADDED
extensions/microsoftexcel-controlnet/tests/images/expected_woman_all_output.png
ADDED
extensions/microsoftexcel-controlnet/tests/images/expected_woman_face_output.png
ADDED
extensions/microsoftexcel-controlnet/tests/images/expected_woman_hand_output.png
ADDED
extensions/microsoftexcel-controlnet/tests/images/ski.jpg
ADDED
extensions/microsoftexcel-controlnet/tests/images/woman.jpeg
ADDED
extensions/microsoftexcel-controlnet/tests/utils.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import sys
|
3 |
+
import cv2
|
4 |
+
from base64 import b64encode
|
5 |
+
|
6 |
+
import requests
|
7 |
+
|
8 |
+
BASE_URL = "http://localhost:7860"
|
9 |
+
|
10 |
+
|
11 |
+
def setup_test_env():
|
12 |
+
ext_root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
|
13 |
+
if ext_root not in sys.path:
|
14 |
+
sys.path.append(ext_root)
|
15 |
+
|
16 |
+
|
17 |
+
def readImage(path):
|
18 |
+
img = cv2.imread(path)
|
19 |
+
retval, buffer = cv2.imencode('.jpg', img)
|
20 |
+
b64img = b64encode(buffer).decode("utf-8")
|
21 |
+
return b64img
|
22 |
+
|
23 |
+
|
24 |
+
def get_model():
|
25 |
+
r = requests.get(BASE_URL+"/controlnet/model_list")
|
26 |
+
result = r.json()
|
27 |
+
if "model_list" in result:
|
28 |
+
result = result["model_list"]
|
29 |
+
for item in result:
|
30 |
+
print("Using model: ", item)
|
31 |
+
return item
|
32 |
+
return "None"
|
33 |
+
|
34 |
+
|
35 |
+
def get_modules():
|
36 |
+
return requests.get(f"{BASE_URL}/controlnet/module_list").json()
|
37 |
+
|
38 |
+
|
39 |
+
def detect(json):
|
40 |
+
return requests.post(BASE_URL+"/controlnet/detect", json=json)
|
extensions/microsoftexcel-controlnet/tests/web_api/__init__.py
ADDED
File without changes
|
extensions/microsoftexcel-controlnet/tests/web_api/detect_test.py
ADDED
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
import unittest
|
3 |
+
import importlib
|
4 |
+
utils = importlib.import_module(
|
5 |
+
'extensions.sd-webui-controlnet.tests.utils', 'utils')
|
6 |
+
utils.setup_test_env()
|
7 |
+
|
8 |
+
|
9 |
+
class TestDetectEndpointWorking(unittest.TestCase):
|
10 |
+
def setUp(self):
|
11 |
+
self.base_detect_args = {
|
12 |
+
"controlnet_module": "canny",
|
13 |
+
"controlnet_input_images": [utils.readImage("test/test_files/img2img_basic.png")],
|
14 |
+
"controlnet_processor_res": 512,
|
15 |
+
"controlnet_threshold_a": 0,
|
16 |
+
"controlnet_threshold_b": 0,
|
17 |
+
}
|
18 |
+
|
19 |
+
def test_detect_with_invalid_module_performed(self):
|
20 |
+
detect_args = self.base_detect_args.copy()
|
21 |
+
detect_args.update({
|
22 |
+
"controlnet_module": "INVALID",
|
23 |
+
})
|
24 |
+
self.assertEqual(utils.detect(detect_args).status_code, 422)
|
25 |
+
|
26 |
+
def test_detect_with_no_input_images_performed(self):
|
27 |
+
detect_args = self.base_detect_args.copy()
|
28 |
+
detect_args.update({
|
29 |
+
"controlnet_input_images": [],
|
30 |
+
})
|
31 |
+
self.assertEqual(utils.detect(detect_args).status_code, 422)
|
32 |
+
|
33 |
+
def test_detect_with_valid_args_performed(self):
|
34 |
+
detect_args = self.base_detect_args
|
35 |
+
response = utils.detect(detect_args)
|
36 |
+
|
37 |
+
self.assertEqual(response.status_code, 200)
|
38 |
+
|
39 |
+
|
40 |
+
if __name__ == "__main__":
|
41 |
+
unittest.main()
|
extensions/microsoftexcel-controlnet/tests/web_api/img2img_test.py
ADDED
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import unittest
|
2 |
+
import importlib
|
3 |
+
utils = importlib.import_module('extensions.sd-webui-controlnet.tests.utils', 'utils')
|
4 |
+
utils.setup_test_env()
|
5 |
+
import requests
|
6 |
+
|
7 |
+
|
8 |
+
|
9 |
+
class TestImg2ImgWorkingBase(unittest.TestCase):
|
10 |
+
def setUp(self):
|
11 |
+
controlnet_unit = {
|
12 |
+
"module": "none",
|
13 |
+
"model": utils.get_model(),
|
14 |
+
"weight": 1.0,
|
15 |
+
"input_image": utils.readImage("test/test_files/img2img_basic.png"),
|
16 |
+
"mask": utils.readImage("test/test_files/img2img_basic.png"),
|
17 |
+
"resize_mode": 1,
|
18 |
+
"lowvram": False,
|
19 |
+
"processor_res": 64,
|
20 |
+
"threshold_a": 64,
|
21 |
+
"threshold_b": 64,
|
22 |
+
"guidance_start": 0.0,
|
23 |
+
"guidance_end": 1.0,
|
24 |
+
"control_mode": 0,
|
25 |
+
}
|
26 |
+
setup_args = {"alwayson_scripts":{"ControlNet":{"args": ([controlnet_unit] * getattr(self, 'units_count', 1))}}}
|
27 |
+
self.setup_route(setup_args)
|
28 |
+
|
29 |
+
def setup_route(self, setup_args):
|
30 |
+
self.url_img2img = "http://localhost:7860/sdapi/v1/img2img"
|
31 |
+
self.simple_img2img = {
|
32 |
+
"init_images": [utils.readImage("test/test_files/img2img_basic.png")],
|
33 |
+
"resize_mode": 0,
|
34 |
+
"denoising_strength": 0.75,
|
35 |
+
"image_cfg_scale": 0,
|
36 |
+
"mask_blur": 4,
|
37 |
+
"inpainting_fill": 0,
|
38 |
+
"inpaint_full_res": True,
|
39 |
+
"inpaint_full_res_padding": 0,
|
40 |
+
"inpainting_mask_invert": 0,
|
41 |
+
"initial_noise_multiplier": 0,
|
42 |
+
"prompt": "example prompt",
|
43 |
+
"styles": [],
|
44 |
+
"seed": -1,
|
45 |
+
"subseed": -1,
|
46 |
+
"subseed_strength": 0,
|
47 |
+
"seed_resize_from_h": -1,
|
48 |
+
"seed_resize_from_w": -1,
|
49 |
+
"sampler_name": "Euler a",
|
50 |
+
"batch_size": 1,
|
51 |
+
"n_iter": 1,
|
52 |
+
"steps": 3,
|
53 |
+
"cfg_scale": 7,
|
54 |
+
"width": 64,
|
55 |
+
"height": 64,
|
56 |
+
"restore_faces": False,
|
57 |
+
"tiling": False,
|
58 |
+
"do_not_save_samples": False,
|
59 |
+
"do_not_save_grid": False,
|
60 |
+
"negative_prompt": "",
|
61 |
+
"eta": 0,
|
62 |
+
"s_churn": 0,
|
63 |
+
"s_tmax": 0,
|
64 |
+
"s_tmin": 0,
|
65 |
+
"s_noise": 1,
|
66 |
+
"override_settings": {},
|
67 |
+
"override_settings_restore_afterwards": True,
|
68 |
+
"sampler_index": "Euler a",
|
69 |
+
"include_init_images": False,
|
70 |
+
"send_images": True,
|
71 |
+
"save_images": False,
|
72 |
+
"alwayson_scripts": {}
|
73 |
+
}
|
74 |
+
self.simple_img2img.update(setup_args)
|
75 |
+
|
76 |
+
def assert_status_ok(self):
|
77 |
+
self.assertEqual(requests.post(self.url_img2img, json=self.simple_img2img).status_code, 200)
|
78 |
+
stderr = ""
|
79 |
+
with open('test/stderr.txt') as f:
|
80 |
+
stderr = f.read().lower()
|
81 |
+
with open('test/stderr.txt', 'w') as f:
|
82 |
+
# clear stderr file so we can easily parse the next test
|
83 |
+
f.write("")
|
84 |
+
self.assertFalse('error' in stderr, "Errors in stderr: \n" + stderr)
|
85 |
+
|
86 |
+
def test_img2img_simple_performed(self):
|
87 |
+
self.assert_status_ok()
|
88 |
+
|
89 |
+
def test_img2img_alwayson_scripts_default_units(self):
|
90 |
+
self.units_count = 0
|
91 |
+
self.setUp()
|
92 |
+
self.assert_status_ok()
|
93 |
+
|
94 |
+
def test_img2img_default_params(self):
|
95 |
+
self.simple_img2img["alwayson_scripts"]["ControlNet"]["args"] = [{
|
96 |
+
"input_image": utils.readImage("test/test_files/img2img_basic.png"),
|
97 |
+
"model": utils.get_model(),
|
98 |
+
}]
|
99 |
+
self.assert_status_ok()
|
100 |
+
|
101 |
+
if __name__ == "__main__":
|
102 |
+
unittest.main()
|
extensions/microsoftexcel-controlnet/tests/web_api/txt2img_test.py
ADDED
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import unittest
|
2 |
+
import importlib
|
3 |
+
utils = importlib.import_module('extensions.sd-webui-controlnet.tests.utils', 'utils')
|
4 |
+
utils.setup_test_env()
|
5 |
+
import requests
|
6 |
+
|
7 |
+
|
8 |
+
|
9 |
+
class TestAlwaysonTxt2ImgWorking(unittest.TestCase):
|
10 |
+
def setUp(self):
|
11 |
+
controlnet_unit = {
|
12 |
+
"enabled": True,
|
13 |
+
"module": "none",
|
14 |
+
"model": utils.get_model(),
|
15 |
+
"weight": 1.0,
|
16 |
+
"image": utils.readImage("test/test_files/img2img_basic.png"),
|
17 |
+
"mask": utils.readImage("test/test_files/img2img_basic.png"),
|
18 |
+
"resize_mode": 1,
|
19 |
+
"lowvram": False,
|
20 |
+
"processor_res": 64,
|
21 |
+
"threshold_a": 64,
|
22 |
+
"threshold_b": 64,
|
23 |
+
"guidance_start": 0.0,
|
24 |
+
"guidance_end": 1.0,
|
25 |
+
"control_mode": 0,
|
26 |
+
"pixel_perfect": False
|
27 |
+
}
|
28 |
+
setup_args = [controlnet_unit] * getattr(self, 'units_count', 1)
|
29 |
+
self.setup_route(setup_args)
|
30 |
+
|
31 |
+
def setup_route(self, setup_args):
|
32 |
+
self.url_txt2img = "http://localhost:7860/sdapi/v1/txt2img"
|
33 |
+
self.simple_txt2img = {
|
34 |
+
"enable_hr": False,
|
35 |
+
"denoising_strength": 0,
|
36 |
+
"firstphase_width": 0,
|
37 |
+
"firstphase_height": 0,
|
38 |
+
"prompt": "example prompt",
|
39 |
+
"styles": [],
|
40 |
+
"seed": -1,
|
41 |
+
"subseed": -1,
|
42 |
+
"subseed_strength": 0,
|
43 |
+
"seed_resize_from_h": -1,
|
44 |
+
"seed_resize_from_w": -1,
|
45 |
+
"batch_size": 1,
|
46 |
+
"n_iter": 1,
|
47 |
+
"steps": 3,
|
48 |
+
"cfg_scale": 7,
|
49 |
+
"width": 64,
|
50 |
+
"height": 64,
|
51 |
+
"restore_faces": False,
|
52 |
+
"tiling": False,
|
53 |
+
"negative_prompt": "",
|
54 |
+
"eta": 0,
|
55 |
+
"s_churn": 0,
|
56 |
+
"s_tmax": 0,
|
57 |
+
"s_tmin": 0,
|
58 |
+
"s_noise": 1,
|
59 |
+
"sampler_index": "Euler a",
|
60 |
+
"alwayson_scripts": {}
|
61 |
+
}
|
62 |
+
self.setup_controlnet_params(setup_args)
|
63 |
+
|
64 |
+
def setup_controlnet_params(self, setup_args):
|
65 |
+
self.simple_txt2img["alwayson_scripts"]["ControlNet"] = {
|
66 |
+
"args": setup_args
|
67 |
+
}
|
68 |
+
|
69 |
+
def assert_status_ok(self, msg=None):
|
70 |
+
self.assertEqual(requests.post(self.url_txt2img, json=self.simple_txt2img).status_code, 200, msg)
|
71 |
+
stderr = ""
|
72 |
+
with open('test/stderr.txt') as f:
|
73 |
+
stderr = f.read().lower()
|
74 |
+
with open('test/stderr.txt', 'w') as f:
|
75 |
+
# clear stderr file so that we can easily parse the next test
|
76 |
+
f.write("")
|
77 |
+
self.assertFalse('error' in stderr, "Errors in stderr: \n" + stderr)
|
78 |
+
|
79 |
+
def test_txt2img_simple_performed(self):
|
80 |
+
self.assert_status_ok()
|
81 |
+
|
82 |
+
def test_txt2img_alwayson_scripts_default_units(self):
|
83 |
+
self.units_count = 0
|
84 |
+
self.setUp()
|
85 |
+
self.assert_status_ok()
|
86 |
+
|
87 |
+
def test_txt2img_multiple_batches_performed(self):
|
88 |
+
self.simple_txt2img["n_iter"] = 2
|
89 |
+
self.assert_status_ok()
|
90 |
+
|
91 |
+
def test_txt2img_batch_performed(self):
|
92 |
+
self.simple_txt2img["batch_size"] = 2
|
93 |
+
self.assert_status_ok()
|
94 |
+
|
95 |
+
def test_txt2img_2_units(self):
|
96 |
+
self.units_count = 2
|
97 |
+
self.setUp()
|
98 |
+
self.assert_status_ok()
|
99 |
+
|
100 |
+
def test_txt2img_8_units(self):
|
101 |
+
self.units_count = 8
|
102 |
+
self.setUp()
|
103 |
+
self.assert_status_ok()
|
104 |
+
|
105 |
+
def test_txt2img_default_params(self):
|
106 |
+
self.simple_txt2img["alwayson_scripts"]["ControlNet"]["args"] = [
|
107 |
+
{
|
108 |
+
"input_image": utils.readImage("test/test_files/img2img_basic.png"),
|
109 |
+
"model": utils.get_model(),
|
110 |
+
}
|
111 |
+
]
|
112 |
+
|
113 |
+
self.assert_status_ok()
|
114 |
+
|
115 |
+
def test_call_with_preprocessors(self):
|
116 |
+
available_modules = utils.get_modules()
|
117 |
+
available_modules_list = available_modules.get('module_list', [])
|
118 |
+
available_modules_detail = available_modules.get('module_detail', {})
|
119 |
+
for module in ['depth', 'openpose_full']:
|
120 |
+
assert module in available_modules_list, f'Failed to find {module}.'
|
121 |
+
assert module in available_modules_detail, f"Failed to find {module}'s detail."
|
122 |
+
with self.subTest(module=module):
|
123 |
+
self.simple_txt2img["alwayson_scripts"]["ControlNet"]["args"] = [
|
124 |
+
{
|
125 |
+
"input_image": utils.readImage("test/test_files/img2img_basic.png"),
|
126 |
+
"model": utils.get_model(),
|
127 |
+
"module": module
|
128 |
+
}
|
129 |
+
]
|
130 |
+
self.assert_status_ok(f'Running preprocessor module: {module}')
|
131 |
+
|
132 |
+
|
133 |
+
if __name__ == "__main__":
|
134 |
+
unittest.main()
|
extensions/microsoftexcel-images-browser.zip
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7852a2ee362716b237cddcdc658b58811b3bb1ceebbe81592ef395f22e36c46e
|
3 |
+
size 68776
|
extensions/microsoftexcel-supermerger/.gitignore
ADDED
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Byte-compiled / optimized / DLL files
|
2 |
+
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
*$py.class
|
5 |
+
|
6 |
+
changelog.m
|
7 |
+
|
8 |
+
# C extensions
|
9 |
+
*.so
|
10 |
+
|
11 |
+
# Distribution / packaging
|
12 |
+
.Python
|
13 |
+
build/
|
14 |
+
develop-eggs/
|
15 |
+
dist/
|
16 |
+
downloads/
|
17 |
+
eggs/
|
18 |
+
.eggs/
|
19 |
+
lib/
|
20 |
+
lib64/
|
21 |
+
parts/
|
22 |
+
sdist/
|
23 |
+
var/
|
24 |
+
wheels/
|
25 |
+
pip-wheel-metadata/
|
26 |
+
share/python-wheels/
|
27 |
+
*.egg-info/
|
28 |
+
.installed.cfg
|
29 |
+
*.egg
|
30 |
+
MANIFEST
|
31 |
+
|
32 |
+
# PyInstaller
|
33 |
+
# Usually these files are written by a python script from a template
|
34 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
35 |
+
*.manifest
|
36 |
+
*.spec
|
37 |
+
|
38 |
+
# Installer logs
|
39 |
+
pip-log.txt
|
40 |
+
pip-delete-this-directory.txt
|
41 |
+
|
42 |
+
# Unit test / coverage reports
|
43 |
+
htmlcov/
|
44 |
+
.tox/
|
45 |
+
.nox/
|
46 |
+
.coverage
|
47 |
+
.coverage.*
|
48 |
+
.cache
|
49 |
+
nosetests.xml
|
50 |
+
coverage.xml
|
51 |
+
*.cover
|
52 |
+
*.py,cover
|
53 |
+
.hypothesis/
|
54 |
+
.pytest_cache/
|
55 |
+
|
56 |
+
# Translations
|
57 |
+
*.mo
|
58 |
+
*.pot
|
59 |
+
|
60 |
+
# Django stuff:
|
61 |
+
*.log
|
62 |
+
local_settings.py
|
63 |
+
db.sqlite3
|
64 |
+
db.sqlite3-journal
|
65 |
+
|
66 |
+
# Flask stuff:
|
67 |
+
instance/
|
68 |
+
.webassets-cache
|
69 |
+
|
70 |
+
# Scrapy stuff:
|
71 |
+
.scrapy
|
72 |
+
|
73 |
+
# Sphinx documentation
|
74 |
+
docs/_build/
|
75 |
+
|
76 |
+
# PyBuilder
|
77 |
+
target/
|
78 |
+
|
79 |
+
# Jupyter Notebook
|
80 |
+
.ipynb_checkpoints
|
81 |
+
|
82 |
+
# IPython
|
83 |
+
profile_default/
|
84 |
+
ipython_config.py
|
85 |
+
|
86 |
+
# pyenv
|
87 |
+
.python-version
|
88 |
+
|
89 |
+
# pipenv
|
90 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
91 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
92 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
93 |
+
# install all needed dependencies.
|
94 |
+
#Pipfile.lock
|
95 |
+
|
96 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
97 |
+
__pypackages__/
|
98 |
+
|
99 |
+
# Celery stuff
|
100 |
+
celerybeat-schedule
|
101 |
+
celerybeat.pid
|
102 |
+
|
103 |
+
# SageMath parsed files
|
104 |
+
*.sage.py
|
105 |
+
|
106 |
+
# Environments
|
107 |
+
.env
|
108 |
+
.venv
|
109 |
+
env/
|
110 |
+
venv/
|
111 |
+
ENV/
|
112 |
+
env.bak/
|
113 |
+
venv.bak/
|
114 |
+
|
115 |
+
# Spyder project settings
|
116 |
+
.spyderproject
|
117 |
+
.spyproject
|
118 |
+
|
119 |
+
# Rope project settings
|
120 |
+
.ropeproject
|
121 |
+
|
122 |
+
# mkdocs documentation
|
123 |
+
/site
|
124 |
+
|
125 |
+
# mypy
|
126 |
+
.mypy_cache/
|
127 |
+
.dmypy.json
|
128 |
+
dmypy.json
|
129 |
+
|
130 |
+
# Pyre type checker
|
131 |
+
.pyre/
|
extensions/microsoftexcel-supermerger/LICENSE
ADDED
@@ -0,0 +1,663 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU AFFERO GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 19 November 2007
|
3 |
+
|
4 |
+
Copyright (c) 2023 hako-mikan
|
5 |
+
|
6 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
7 |
+
Everyone is permitted to copy and distribute verbatim copies
|
8 |
+
of this license document, but changing it is not allowed.
|
9 |
+
|
10 |
+
Preamble
|
11 |
+
|
12 |
+
The GNU Affero General Public License is a free, copyleft license for
|
13 |
+
software and other kinds of works, specifically designed to ensure
|
14 |
+
cooperation with the community in the case of network server software.
|
15 |
+
|
16 |
+
The licenses for most software and other practical works are designed
|
17 |
+
to take away your freedom to share and change the works. By contrast,
|
18 |
+
our General Public Licenses are intended to guarantee your freedom to
|
19 |
+
share and change all versions of a program--to make sure it remains free
|
20 |
+
software for all its users.
|
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 |
+
Developers that use our General Public Licenses protect your rights
|
30 |
+
with two steps: (1) assert copyright on the software, and (2) offer
|
31 |
+
you this License which gives you legal permission to copy, distribute
|
32 |
+
and/or modify the software.
|
33 |
+
|
34 |
+
A secondary benefit of defending all users' freedom is that
|
35 |
+
improvements made in alternate versions of the program, if they
|
36 |
+
receive widespread use, become available for other developers to
|
37 |
+
incorporate. Many developers of free software are heartened and
|
38 |
+
encouraged by the resulting cooperation. However, in the case of
|
39 |
+
software used on network servers, this result may fail to come about.
|
40 |
+
The GNU General Public License permits making a modified version and
|
41 |
+
letting the public access it on a server without ever releasing its
|
42 |
+
source code to the public.
|
43 |
+
|
44 |
+
The GNU Affero General Public License is designed specifically to
|
45 |
+
ensure that, in such cases, the modified source code becomes available
|
46 |
+
to the community. It requires the operator of a network server to
|
47 |
+
provide the source code of the modified version running there to the
|
48 |
+
users of that server. Therefore, public use of a modified version, on
|
49 |
+
a publicly accessible server, gives the public access to the source
|
50 |
+
code of the modified version.
|
51 |
+
|
52 |
+
An older license, called the Affero General Public License and
|
53 |
+
published by Affero, was designed to accomplish similar goals. This is
|
54 |
+
a different license, not a version of the Affero GPL, but Affero has
|
55 |
+
released a new version of the Affero GPL which permits relicensing under
|
56 |
+
this license.
|
57 |
+
|
58 |
+
The precise terms and conditions for copying, distribution and
|
59 |
+
modification follow.
|
60 |
+
|
61 |
+
TERMS AND CONDITIONS
|
62 |
+
|
63 |
+
0. Definitions.
|
64 |
+
|
65 |
+
"This License" refers to version 3 of the GNU Affero General Public License.
|
66 |
+
|
67 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
68 |
+
works, such as semiconductor masks.
|
69 |
+
|
70 |
+
"The Program" refers to any copyrightable work licensed under this
|
71 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
72 |
+
"recipients" may be individuals or organizations.
|
73 |
+
|
74 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
75 |
+
in a fashion requiring copyright permission, other than the making of an
|
76 |
+
exact copy. The resulting work is called a "modified version" of the
|
77 |
+
earlier work or a work "based on" the earlier work.
|
78 |
+
|
79 |
+
A "covered work" means either the unmodified Program or a work based
|
80 |
+
on the Program.
|
81 |
+
|
82 |
+
To "propagate" a work means to do anything with it that, without
|
83 |
+
permission, would make you directly or secondarily liable for
|
84 |
+
infringement under applicable copyright law, except executing it on a
|
85 |
+
computer or modifying a private copy. Propagation includes copying,
|
86 |
+
distribution (with or without modification), making available to the
|
87 |
+
public, and in some countries other activities as well.
|
88 |
+
|
89 |
+
To "convey" a work means any kind of propagation that enables other
|
90 |
+
parties to make or receive copies. Mere interaction with a user through
|
91 |
+
a computer network, with no transfer of a copy, is not conveying.
|
92 |
+
|
93 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
94 |
+
to the extent that it includes a convenient and prominently visible
|
95 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
96 |
+
tells the user that there is no warranty for the work (except to the
|
97 |
+
extent that warranties are provided), that licensees may convey the
|
98 |
+
work under this License, and how to view a copy of this License. If
|
99 |
+
the interface presents a list of user commands or options, such as a
|
100 |
+
menu, a prominent item in the list meets this criterion.
|
101 |
+
|
102 |
+
1. Source Code.
|
103 |
+
|
104 |
+
The "source code" for a work means the preferred form of the work
|
105 |
+
for making modifications to it. "Object code" means any non-source
|
106 |
+
form of a work.
|
107 |
+
|
108 |
+
A "Standard Interface" means an interface that either is an official
|
109 |
+
standard defined by a recognized standards body, or, in the case of
|
110 |
+
interfaces specified for a particular programming language, one that
|
111 |
+
is widely used among developers working in that language.
|
112 |
+
|
113 |
+
The "System Libraries" of an executable work include anything, other
|
114 |
+
than the work as a whole, that (a) is included in the normal form of
|
115 |
+
packaging a Major Component, but which is not part of that Major
|
116 |
+
Component, and (b) serves only to enable use of the work with that
|
117 |
+
Major Component, or to implement a Standard Interface for which an
|
118 |
+
implementation is available to the public in source code form. A
|
119 |
+
"Major Component", in this context, means a major essential component
|
120 |
+
(kernel, window system, and so on) of the specific operating system
|
121 |
+
(if any) on which the executable work runs, or a compiler used to
|
122 |
+
produce the work, or an object code interpreter used to run it.
|
123 |
+
|
124 |
+
The "Corresponding Source" for a work in object code form means all
|
125 |
+
the source code needed to generate, install, and (for an executable
|
126 |
+
work) run the object code and to modify the work, including scripts to
|
127 |
+
control those activities. However, it does not include the work's
|
128 |
+
System Libraries, or general-purpose tools or generally available free
|
129 |
+
programs which are used unmodified in performing those activities but
|
130 |
+
which are not part of the work. For example, Corresponding Source
|
131 |
+
includes interface definition files associated with source files for
|
132 |
+
the work, and the source code for shared libraries and dynamically
|
133 |
+
linked subprograms that the work is specifically designed to require,
|
134 |
+
such as by intimate data communication or control flow between those
|
135 |
+
subprograms and other parts of the work.
|
136 |
+
|
137 |
+
The Corresponding Source need not include anything that users
|
138 |
+
can regenerate automatically from other parts of the Corresponding
|
139 |
+
Source.
|
140 |
+
|
141 |
+
The Corresponding Source for a work in source code form is that
|
142 |
+
same work.
|
143 |
+
|
144 |
+
2. Basic Permissions.
|
145 |
+
|
146 |
+
All rights granted under this License are granted for the term of
|
147 |
+
copyright on the Program, and are irrevocable provided the stated
|
148 |
+
conditions are met. This License explicitly affirms your unlimited
|
149 |
+
permission to run the unmodified Program. The output from running a
|
150 |
+
covered work is covered by this License only if the output, given its
|
151 |
+
content, constitutes a covered work. This License acknowledges your
|
152 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
153 |
+
|
154 |
+
You may make, run and propagate covered works that you do not
|
155 |
+
convey, without conditions so long as your license otherwise remains
|
156 |
+
in force. You may convey covered works to others for the sole purpose
|
157 |
+
of having them make modifications exclusively for you, or provide you
|
158 |
+
with facilities for running those works, provided that you comply with
|
159 |
+
the terms of this License in conveying all material for which you do
|
160 |
+
not control copyright. Those thus making or running the covered works
|
161 |
+
for you must do so exclusively on your behalf, under your direction
|
162 |
+
and control, on terms that prohibit them from making any copies of
|
163 |
+
your copyrighted material outside their relationship with you.
|
164 |
+
|
165 |
+
Conveying under any other circumstances is permitted solely under
|
166 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
167 |
+
makes it unnecessary.
|
168 |
+
|
169 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
170 |
+
|
171 |
+
No covered work shall be deemed part of an effective technological
|
172 |
+
measure under any applicable law fulfilling obligations under article
|
173 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
174 |
+
similar laws prohibiting or restricting circumvention of such
|
175 |
+
measures.
|
176 |
+
|
177 |
+
When you convey a covered work, you waive any legal power to forbid
|
178 |
+
circumvention of technological measures to the extent such circumvention
|
179 |
+
is effected by exercising rights under this License with respect to
|
180 |
+
the covered work, and you disclaim any intention to limit operation or
|
181 |
+
modification of the work as a means of enforcing, against the work's
|
182 |
+
users, your or third parties' legal rights to forbid circumvention of
|
183 |
+
technological measures.
|
184 |
+
|
185 |
+
4. Conveying Verbatim Copies.
|
186 |
+
|
187 |
+
You may convey verbatim copies of the Program's source code as you
|
188 |
+
receive it, in any medium, provided that you conspicuously and
|
189 |
+
appropriately publish on each copy an appropriate copyright notice;
|
190 |
+
keep intact all notices stating that this License and any
|
191 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
192 |
+
keep intact all notices of the absence of any warranty; and give all
|
193 |
+
recipients a copy of this License along with the Program.
|
194 |
+
|
195 |
+
You may charge any price or no price for each copy that you convey,
|
196 |
+
and you may offer support or warranty protection for a fee.
|
197 |
+
|
198 |
+
5. Conveying Modified Source Versions.
|
199 |
+
|
200 |
+
You may convey a work based on the Program, or the modifications to
|
201 |
+
produce it from the Program, in the form of source code under the
|
202 |
+
terms of section 4, provided that you also meet all of these conditions:
|
203 |
+
|
204 |
+
a) The work must carry prominent notices stating that you modified
|
205 |
+
it, and giving a relevant date.
|
206 |
+
|
207 |
+
b) The work must carry prominent notices stating that it is
|
208 |
+
released under this License and any conditions added under section
|
209 |
+
7. This requirement modifies the requirement in section 4 to
|
210 |
+
"keep intact all notices".
|
211 |
+
|
212 |
+
c) You must license the entire work, as a whole, under this
|
213 |
+
License to anyone who comes into possession of a copy. This
|
214 |
+
License will therefore apply, along with any applicable section 7
|
215 |
+
additional terms, to the whole of the work, and all its parts,
|
216 |
+
regardless of how they are packaged. This License gives no
|
217 |
+
permission to license the work in any other way, but it does not
|
218 |
+
invalidate such permission if you have separately received it.
|
219 |
+
|
220 |
+
d) If the work has interactive user interfaces, each must display
|
221 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
222 |
+
interfaces that do not display Appropriate Legal Notices, your
|
223 |
+
work need not make them do so.
|
224 |
+
|
225 |
+
A compilation of a covered work with other separate and independent
|
226 |
+
works, which are not by their nature extensions of the covered work,
|
227 |
+
and which are not combined with it such as to form a larger program,
|
228 |
+
in or on a volume of a storage or distribution medium, is called an
|
229 |
+
"aggregate" if the compilation and its resulting copyright are not
|
230 |
+
used to limit the access or legal rights of the compilation's users
|
231 |
+
beyond what the individual works permit. Inclusion of a covered work
|
232 |
+
in an aggregate does not cause this License to apply to the other
|
233 |
+
parts of the aggregate.
|
234 |
+
|
235 |
+
6. Conveying Non-Source Forms.
|
236 |
+
|
237 |
+
You may convey a covered work in object code form under the terms
|
238 |
+
of sections 4 and 5, provided that you also convey the
|
239 |
+
machine-readable Corresponding Source under the terms of this License,
|
240 |
+
in one of these ways:
|
241 |
+
|
242 |
+
a) Convey the object code in, or embodied in, a physical product
|
243 |
+
(including a physical distribution medium), accompanied by the
|
244 |
+
Corresponding Source fixed on a durable physical medium
|
245 |
+
customarily used for software interchange.
|
246 |
+
|
247 |
+
b) Convey the object code in, or embodied in, a physical product
|
248 |
+
(including a physical distribution medium), accompanied by a
|
249 |
+
written offer, valid for at least three years and valid for as
|
250 |
+
long as you offer spare parts or customer support for that product
|
251 |
+
model, to give anyone who possesses the object code either (1) a
|
252 |
+
copy of the Corresponding Source for all the software in the
|
253 |
+
product that is covered by this License, on a durable physical
|
254 |
+
medium customarily used for software interchange, for a price no
|
255 |
+
more than your reasonable cost of physically performing this
|
256 |
+
conveying of source, or (2) access to copy the
|
257 |
+
Corresponding Source from a network server at no charge.
|
258 |
+
|
259 |
+
c) Convey individual copies of the object code with a copy of the
|
260 |
+
written offer to provide the Corresponding Source. This
|
261 |
+
alternative is allowed only occasionally and noncommercially, and
|
262 |
+
only if you received the object code with such an offer, in accord
|
263 |
+
with subsection 6b.
|
264 |
+
|
265 |
+
d) Convey the object code by offering access from a designated
|
266 |
+
place (gratis or for a charge), and offer equivalent access to the
|
267 |
+
Corresponding Source in the same way through the same place at no
|
268 |
+
further charge. You need not require recipients to copy the
|
269 |
+
Corresponding Source along with the object code. If the place to
|
270 |
+
copy the object code is a network server, the Corresponding Source
|
271 |
+
may be on a different server (operated by you or a third party)
|
272 |
+
that supports equivalent copying facilities, provided you maintain
|
273 |
+
clear directions next to the object code saying where to find the
|
274 |
+
Corresponding Source. Regardless of what server hosts the
|
275 |
+
Corresponding Source, you remain obligated to ensure that it is
|
276 |
+
available for as long as needed to satisfy these requirements.
|
277 |
+
|
278 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
279 |
+
you inform other peers where the object code and Corresponding
|
280 |
+
Source of the work are being offered to the general public at no
|
281 |
+
charge under subsection 6d.
|
282 |
+
|
283 |
+
A separable portion of the object code, whose source code is excluded
|
284 |
+
from the Corresponding Source as a System Library, need not be
|
285 |
+
included in conveying the object code work.
|
286 |
+
|
287 |
+
A "User Product" is either (1) a "consumer product", which means any
|
288 |
+
tangible personal property which is normally used for personal, family,
|
289 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
290 |
+
into a dwelling. In determining whether a product is a consumer product,
|
291 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
292 |
+
product received by a particular user, "normally used" refers to a
|
293 |
+
typical or common use of that class of product, regardless of the status
|
294 |
+
of the particular user or of the way in which the particular user
|
295 |
+
actually uses, or expects or is expected to use, the product. A product
|
296 |
+
is a consumer product regardless of whether the product has substantial
|
297 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
298 |
+
the only significant mode of use of the product.
|
299 |
+
|
300 |
+
"Installation Information" for a User Product means any methods,
|
301 |
+
procedures, authorization keys, or other information required to install
|
302 |
+
and execute modified versions of a covered work in that User Product from
|
303 |
+
a modified version of its Corresponding Source. The information must
|
304 |
+
suffice to ensure that the continued functioning of the modified object
|
305 |
+
code is in no case prevented or interfered with solely because
|
306 |
+
modification has been made.
|
307 |
+
|
308 |
+
If you convey an object code work under this section in, or with, or
|
309 |
+
specifically for use in, a User Product, and the conveying occurs as
|
310 |
+
part of a transaction in which the right of possession and use of the
|
311 |
+
User Product is transferred to the recipient in perpetuity or for a
|
312 |
+
fixed term (regardless of how the transaction is characterized), the
|
313 |
+
Corresponding Source conveyed under this section must be accompanied
|
314 |
+
by the Installation Information. But this requirement does not apply
|
315 |
+
if neither you nor any third party retains the ability to install
|
316 |
+
modified object code on the User Product (for example, the work has
|
317 |
+
been installed in ROM).
|
318 |
+
|
319 |
+
The requirement to provide Installation Information does not include a
|
320 |
+
requirement to continue to provide support service, warranty, or updates
|
321 |
+
for a work that has been modified or installed by the recipient, or for
|
322 |
+
the User Product in which it has been modified or installed. Access to a
|
323 |
+
network may be denied when the modification itself materially and
|
324 |
+
adversely affects the operation of the network or violates the rules and
|
325 |
+
protocols for communication across the network.
|
326 |
+
|
327 |
+
Corresponding Source conveyed, and Installation Information provided,
|
328 |
+
in accord with this section must be in a format that is publicly
|
329 |
+
documented (and with an implementation available to the public in
|
330 |
+
source code form), and must require no special password or key for
|
331 |
+
unpacking, reading or copying.
|
332 |
+
|
333 |
+
7. Additional Terms.
|
334 |
+
|
335 |
+
"Additional permissions" are terms that supplement the terms of this
|
336 |
+
License by making exceptions from one or more of its conditions.
|
337 |
+
Additional permissions that are applicable to the entire Program shall
|
338 |
+
be treated as though they were included in this License, to the extent
|
339 |
+
that they are valid under applicable law. If additional permissions
|
340 |
+
apply only to part of the Program, that part may be used separately
|
341 |
+
under those permissions, but the entire Program remains governed by
|
342 |
+
this License without regard to the additional permissions.
|
343 |
+
|
344 |
+
When you convey a copy of a covered work, you may at your option
|
345 |
+
remove any additional permissions from that copy, or from any part of
|
346 |
+
it. (Additional permissions may be written to require their own
|
347 |
+
removal in certain cases when you modify the work.) You may place
|
348 |
+
additional permissions on material, added by you to a covered work,
|
349 |
+
for which you have or can give appropriate copyright permission.
|
350 |
+
|
351 |
+
Notwithstanding any other provision of this License, for material you
|
352 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
353 |
+
that material) supplement the terms of this License with terms:
|
354 |
+
|
355 |
+
a) Disclaiming warranty or limiting liability differently from the
|
356 |
+
terms of sections 15 and 16 of this License; or
|
357 |
+
|
358 |
+
b) Requiring preservation of specified reasonable legal notices or
|
359 |
+
author attributions in that material or in the Appropriate Legal
|
360 |
+
Notices displayed by works containing it; or
|
361 |
+
|
362 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
363 |
+
requiring that modified versions of such material be marked in
|
364 |
+
reasonable ways as different from the original version; or
|
365 |
+
|
366 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
367 |
+
authors of the material; or
|
368 |
+
|
369 |
+
e) Declining to grant rights under trademark law for use of some
|
370 |
+
trade names, trademarks, or service marks; or
|
371 |
+
|
372 |
+
f) Requiring indemnification of licensors and authors of that
|
373 |
+
material by anyone who conveys the material (or modified versions of
|
374 |
+
it) with contractual assumptions of liability to the recipient, for
|
375 |
+
any liability that these contractual assumptions directly impose on
|
376 |
+
those licensors and authors.
|
377 |
+
|
378 |
+
All other non-permissive additional terms are considered "further
|
379 |
+
restrictions" within the meaning of section 10. If the Program as you
|
380 |
+
received it, or any part of it, contains a notice stating that it is
|
381 |
+
governed by this License along with a term that is a further
|
382 |
+
restriction, you may remove that term. If a license document contains
|
383 |
+
a further restriction but permits relicensing or conveying under this
|
384 |
+
License, you may add to a covered work material governed by the terms
|
385 |
+
of that license document, provided that the further restriction does
|
386 |
+
not survive such relicensing or conveying.
|
387 |
+
|
388 |
+
If you add terms to a covered work in accord with this section, you
|
389 |
+
must place, in the relevant source files, a statement of the
|
390 |
+
additional terms that apply to those files, or a notice indicating
|
391 |
+
where to find the applicable terms.
|
392 |
+
|
393 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
394 |
+
form of a separately written license, or stated as exceptions;
|
395 |
+
the above requirements apply either way.
|
396 |
+
|
397 |
+
8. Termination.
|
398 |
+
|
399 |
+
You may not propagate or modify a covered work except as expressly
|
400 |
+
provided under this License. Any attempt otherwise to propagate or
|
401 |
+
modify it is void, and will automatically terminate your rights under
|
402 |
+
this License (including any patent licenses granted under the third
|
403 |
+
paragraph of section 11).
|
404 |
+
|
405 |
+
However, if you cease all violation of this License, then your
|
406 |
+
license from a particular copyright holder is reinstated (a)
|
407 |
+
provisionally, unless and until the copyright holder explicitly and
|
408 |
+
finally terminates your license, and (b) permanently, if the copyright
|
409 |
+
holder fails to notify you of the violation by some reasonable means
|
410 |
+
prior to 60 days after the cessation.
|
411 |
+
|
412 |
+
Moreover, your license from a particular copyright holder is
|
413 |
+
reinstated permanently if the copyright holder notifies you of the
|
414 |
+
violation by some reasonable means, this is the first time you have
|
415 |
+
received notice of violation of this License (for any work) from that
|
416 |
+
copyright holder, and you cure the violation prior to 30 days after
|
417 |
+
your receipt of the notice.
|
418 |
+
|
419 |
+
Termination of your rights under this section does not terminate the
|
420 |
+
licenses of parties who have received copies or rights from you under
|
421 |
+
this License. If your rights have been terminated and not permanently
|
422 |
+
reinstated, you do not qualify to receive new licenses for the same
|
423 |
+
material under section 10.
|
424 |
+
|
425 |
+
9. Acceptance Not Required for Having Copies.
|
426 |
+
|
427 |
+
You are not required to accept this License in order to receive or
|
428 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
429 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
430 |
+
to receive a copy likewise does not require acceptance. However,
|
431 |
+
nothing other than this License grants you permission to propagate or
|
432 |
+
modify any covered work. These actions infringe copyright if you do
|
433 |
+
not accept this License. Therefore, by modifying or propagating a
|
434 |
+
covered work, you indicate your acceptance of this License to do so.
|
435 |
+
|
436 |
+
10. Automatic Licensing of Downstream Recipients.
|
437 |
+
|
438 |
+
Each time you convey a covered work, the recipient automatically
|
439 |
+
receives a license from the original licensors, to run, modify and
|
440 |
+
propagate that work, subject to this License. You are not responsible
|
441 |
+
for enforcing compliance by third parties with this License.
|
442 |
+
|
443 |
+
An "entity transaction" is a transaction transferring control of an
|
444 |
+
organization, or substantially all assets of one, or subdividing an
|
445 |
+
organization, or merging organizations. If propagation of a covered
|
446 |
+
work results from an entity transaction, each party to that
|
447 |
+
transaction who receives a copy of the work also receives whatever
|
448 |
+
licenses to the work the party's predecessor in interest had or could
|
449 |
+
give under the previous paragraph, plus a right to possession of the
|
450 |
+
Corresponding Source of the work from the predecessor in interest, if
|
451 |
+
the predecessor has it or can get it with reasonable efforts.
|
452 |
+
|
453 |
+
You may not impose any further restrictions on the exercise of the
|
454 |
+
rights granted or affirmed under this License. For example, you may
|
455 |
+
not impose a license fee, royalty, or other charge for exercise of
|
456 |
+
rights granted under this License, and you may not initiate litigation
|
457 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
458 |
+
any patent claim is infringed by making, using, selling, offering for
|
459 |
+
sale, or importing the Program or any portion of it.
|
460 |
+
|
461 |
+
11. Patents.
|
462 |
+
|
463 |
+
A "contributor" is a copyright holder who authorizes use under this
|
464 |
+
License of the Program or a work on which the Program is based. The
|
465 |
+
work thus licensed is called the contributor's "contributor version".
|
466 |
+
|
467 |
+
A contributor's "essential patent claims" are all patent claims
|
468 |
+
owned or controlled by the contributor, whether already acquired or
|
469 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
470 |
+
by this License, of making, using, or selling its contributor version,
|
471 |
+
but do not include claims that would be infringed only as a
|
472 |
+
consequence of further modification of the contributor version. For
|
473 |
+
purposes of this definition, "control" includes the right to grant
|
474 |
+
patent sublicenses in a manner consistent with the requirements of
|
475 |
+
this License.
|
476 |
+
|
477 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
478 |
+
patent license under the contributor's essential patent claims, to
|
479 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
480 |
+
propagate the contents of its contributor version.
|
481 |
+
|
482 |
+
In the following three paragraphs, a "patent license" is any express
|
483 |
+
agreement or commitment, however denominated, not to enforce a patent
|
484 |
+
(such as an express permission to practice a patent or covenant not to
|
485 |
+
sue for patent infringement). To "grant" such a patent license to a
|
486 |
+
party means to make such an agreement or commitment not to enforce a
|
487 |
+
patent against the party.
|
488 |
+
|
489 |
+
If you convey a covered work, knowingly relying on a patent license,
|
490 |
+
and the Corresponding Source of the work is not available for anyone
|
491 |
+
to copy, free of charge and under the terms of this License, through a
|
492 |
+
publicly available network server or other readily accessible means,
|
493 |
+
then you must either (1) cause the Corresponding Source to be so
|
494 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
495 |
+
patent license for this particular work, or (3) arrange, in a manner
|
496 |
+
consistent with the requirements of this License, to extend the patent
|
497 |
+
license to downstream recipients. "Knowingly relying" means you have
|
498 |
+
actual knowledge that, but for the patent license, your conveying the
|
499 |
+
covered work in a country, or your recipient's use of the covered work
|
500 |
+
in a country, would infringe one or more identifiable patents in that
|
501 |
+
country that you have reason to believe are valid.
|
502 |
+
|
503 |
+
If, pursuant to or in connection with a single transaction or
|
504 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
505 |
+
covered work, and grant a patent license to some of the parties
|
506 |
+
receiving the covered work authorizing them to use, propagate, modify
|
507 |
+
or convey a specific copy of the covered work, then the patent license
|
508 |
+
you grant is automatically extended to all recipients of the covered
|
509 |
+
work and works based on it.
|
510 |
+
|
511 |
+
A patent license is "discriminatory" if it does not include within
|
512 |
+
the scope of its coverage, prohibits the exercise of, or is
|
513 |
+
conditioned on the non-exercise of one or more of the rights that are
|
514 |
+
specifically granted under this License. You may not convey a covered
|
515 |
+
work if you are a party to an arrangement with a third party that is
|
516 |
+
in the business of distributing software, under which you make payment
|
517 |
+
to the third party based on the extent of your activity of conveying
|
518 |
+
the work, and under which the third party grants, to any of the
|
519 |
+
parties who would receive the covered work from you, a discriminatory
|
520 |
+
patent license (a) in connection with copies of the covered work
|
521 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
522 |
+
for and in connection with specific products or compilations that
|
523 |
+
contain the covered work, unless you entered into that arrangement,
|
524 |
+
or that patent license was granted, prior to 28 March 2007.
|
525 |
+
|
526 |
+
Nothing in this License shall be construed as excluding or limiting
|
527 |
+
any implied license or other defenses to infringement that may
|
528 |
+
otherwise be available to you under applicable patent law.
|
529 |
+
|
530 |
+
12. No Surrender of Others' Freedom.
|
531 |
+
|
532 |
+
If conditions are imposed on you (whether by court order, agreement or
|
533 |
+
otherwise) that contradict the conditions of this License, they do not
|
534 |
+
excuse you from the conditions of this License. If you cannot convey a
|
535 |
+
covered work so as to satisfy simultaneously your obligations under this
|
536 |
+
License and any other pertinent obligations, then as a consequence you may
|
537 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
538 |
+
to collect a royalty for further conveying from those to whom you convey
|
539 |
+
the Program, the only way you could satisfy both those terms and this
|
540 |
+
License would be to refrain entirely from conveying the Program.
|
541 |
+
|
542 |
+
13. Remote Network Interaction; Use with the GNU General Public License.
|
543 |
+
|
544 |
+
Notwithstanding any other provision of this License, if you modify the
|
545 |
+
Program, your modified version must prominently offer all users
|
546 |
+
interacting with it remotely through a computer network (if your version
|
547 |
+
supports such interaction) an opportunity to receive the Corresponding
|
548 |
+
Source of your version by providing access to the Corresponding Source
|
549 |
+
from a network server at no charge, through some standard or customary
|
550 |
+
means of facilitating copying of software. This Corresponding Source
|
551 |
+
shall include the Corresponding Source for any work covered by version 3
|
552 |
+
of the GNU General Public License that is incorporated pursuant to the
|
553 |
+
following paragraph.
|
554 |
+
|
555 |
+
Notwithstanding any other provision of this License, you have
|
556 |
+
permission to link or combine any covered work with a work licensed
|
557 |
+
under version 3 of the GNU General Public License into a single
|
558 |
+
combined work, and to convey the resulting work. The terms of this
|
559 |
+
License will continue to apply to the part which is the covered work,
|
560 |
+
but the work with which it is combined will remain governed by version
|
561 |
+
3 of the GNU General Public License.
|
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 Affero General Public License from time to time. Such new versions
|
567 |
+
will 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 Affero 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 Affero 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 Affero 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 Affero General Public License as published
|
639 |
+
by 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 Affero General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
|
653 |
+
network, you should also make sure that it provides a way for users to
|
654 |
+
get its source. For example, if your program is a web application, its
|
655 |
+
interface could display a "Source" link that leads users to an archive
|
656 |
+
of the code. There are many ways you could offer source, and different
|
657 |
+
solutions will be better for different programs; see section 13 for the
|
658 |
+
specific requirements.
|
659 |
+
|
660 |
+
You should also get your employer (if you work as a programmer) or school,
|
661 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
662 |
+
For more information on this, and how to apply and follow the GNU AGPL, see
|
663 |
+
<https://www.gnu.org/licenses/>.
|
extensions/microsoftexcel-supermerger/README.md
ADDED
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# SuperMerger
|
2 |
+
- Model merge extention for [AUTOMATIC1111's stable-diffusion-webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui)
|
3 |
+
- Merge models can be loaded directly for generation without saving
|
4 |
+
|
5 |
+
### English / 日本語
|
6 |
+
日本語: [![jp](https://img.shields.io/badge/lang-日本語-green.svg)](https://github.com/hako-mikan/sd-webui-supermerger/blob/main/README_ja.md)
|
7 |
+
|
8 |
+
# Recent Update
|
9 |
+
All updates can be found [here](https://github.com/hako-mikan/sd-webui-supermerger/blob/main/changelog.md)
|
10 |
+
|
11 |
+
update 2023.05.02.1900(JST)
|
12 |
+
- bug fix : Resolved conflict with wildcard in dynamic prompt
|
13 |
+
- new feature : restore face and tile option added
|
14 |
+
|
15 |
+
update 2023.04.19.2030(JST)
|
16 |
+
- New feature, optimization using cosine similarity method updated [detail here](https://github.com/hako-mikan/sd-webui-supermerger/blob/main/calcmode_en.md#cosine)
|
17 |
+
- New feature, tensor merge added [detail here](https://github.com/hako-mikan/sd-webui-supermerger/blob/main/calcmode_en.md#tensor)
|
18 |
+
- New XY plot type : calcmode,prompt
|
19 |
+
|
20 |
+
## requirement
|
21 |
+
diffusers(0.10.2 to 0.14.0),sklearn is required to use some LoRA-related features
|
22 |
+
|
23 |
+
# overview
|
24 |
+
This extension allows merged models to be loaded as models for image generation without saving them.
|
25 |
+
This extension can prevent the use of HDD and SSD.
|
26 |
+
|
27 |
+
## Usage
|
28 |
+
|
29 |
+
### Merge mode
|
30 |
+
#### Weight sum
|
31 |
+
Normal merge. alpha is used. if MBW is enabled, MBW base is used as alpha.
|
32 |
+
#### Add difference
|
33 |
+
Add difference, if MBW is enabled, MBW base is used as alpha
|
34 |
+
#### Triple sum
|
35 |
+
Merge 3 models at the same time. alpha and beta are used. I added this function because there were three model selection windows, but I am not sure if it works effectively.
|
36 |
+
#### sum Twice
|
37 |
+
Weight sum twice, alpha and beta are used.
|
38 |
+
|
39 |
+
#### use MBW
|
40 |
+
If checked, block-by-block merging is enabled. Use the slider at the bottom of the screen to set the ratio of each block.
|
41 |
+
|
42 |
+
#### calcmode
|
43 |
+
If you select "cosine", the comparison is performed using cosine similarity, centered on the set ratio, and the ratio is calculated to eliminate loss due to merging. See below for more details.
|
44 |
+
Thanks to [recoilme](https://github.com/recoilme) for devising the idea and to [SwiftIllusion](https://github.com/SwiftIllusion) for introducing this technique.
|
45 |
+
https://github.com/hako-mikan/sd-webui-supermerger/issues/33
|
46 |
+
https://github.com/recoilme/losslessmix
|
47 |
+
|
48 |
+
### save metadate
|
49 |
+
Enable "save metadate" to embed merge conditions as metadata, only in safetensor format. Embedded conditions can be viewed in the Metadata tab.
|
50 |
+
|
51 |
+
## Each button
|
52 |
+
### Merge
|
53 |
+
After merging, load as a model for generation. **Note that a different model is loaded than the model information in the upper left corner.** It will be reset when you re-select the model in the model selection screen on the top left.
|
54 |
+
|
55 |
+
### Gen.
|
56 |
+
Image generation is performed using the settings in the text2image tab.
|
57 |
+
|
58 |
+
### Merge and Gen
|
59 |
+
Merge and Generate image after merging.
|
60 |
+
|
61 |
+
### Set from ID
|
62 |
+
Read settings from merge log. The log is updated each time a merge is performed, and a sequential ID starting from 1 is assigned. Set on -1 will read the last merged configuration. The merge log is saved in extension/sd-webui-supermerger/mergehistory.csv. You can browse and search in the History tab. You can search and/or by separating with a half-width space.
|
63 |
+
|
64 |
+
### Sequential XY Merge and Generation
|
65 |
+
Performs sequential merge image generation. Effective in all merge modes.
|
66 |
+
#### alpha,beta
|
67 |
+
Change alpha and beta.
|
68 |
+
#### alpha and beta
|
69 |
+
Change alpha and beta at the same time. Separate alpha and beta with a single space, and separate each element with a comma. If only one number is entered, the same value is entered for both alpha and beta.
|
70 |
+
Example: 0,0.5 0.1,0.3 0.4,0.5
|
71 |
+
#### MBW
|
72 |
+
Performs a block-byblock merge. Enter ratios separated by newlines. Presets can be used, but be careful to **separate on a new line**.For Triple and Twice, enter two lines as a set. An odd number of lines will result in an error.
|
73 |
+
#### seed
|
74 |
+
Changes the seed. Entering -1 will result in a fixed seed in the opposite axis direction.
|
75 |
+
#### model_A,B,C
|
76 |
+
Changes the model. The model selected in the model selection window is ignored.
|
77 |
+
#### pinpoint blocks
|
78 |
+
Changes only specific blocks in MBW. Choose alpha or beta for the opposite axis. If you enter a block ID, the alpha (beta) will change only for that block. As with the other types, use commas to separate them. Multiple blocks can be changed at the same time by separating them with a space or hyphen. NOT must be entered first to have any effect.
|
79 |
+
##### Input example
|
80 |
+
IN01,OUT10 OUT11, OUT03-OUT06,OUT07-OUT11,NOT M00 OUT03-OUT06
|
81 |
+
In this case
|
82 |
+
- 1:Only IN01 changes
|
83 |
+
- 2:OUT10 and OUT11 change
|
84 |
+
- 3:OUT03 to OUT06 change
|
85 |
+
- 4:OUT07 to OUT11 change
|
86 |
+
- 5:All except for M00 and OUT03 to OUT06 are changed.
|
87 |
+
|
88 |
+
Please be careful not to forget to input "0".
|
89 |
+
![xy_grid-0006-2934360860 0](https://user-images.githubusercontent.com/122196982/214343111-e82bb20a-799b-4026-8e3c-dd36e26841e3.jpg)
|
90 |
+
|
91 |
+
Block ID (only upper case letters are valid)
|
92 |
+
BASE,IN00,IN01,IN02,IN03,IN04,IN05,IN06,IN07,IN08,IN09,IN10,IN11,M00,OUT00,OUT01,OUT02,OUT03,OUT04,OUT05,OUT06,OUT07,OUT08,OUT09, OUT10,OUT11
|
93 |
+
|
94 |
+
#### calcmode
|
95 |
+
change calclation mode.
|
96 |
+
Note the correspondence between calculation mode and merge mode.
|
97 |
+
|
98 |
+
#### prompt
|
99 |
+
You can change the prompt. The negative prompt does not change. Separate with a new line.
|
100 |
+
|
101 |
+
### Reserve XY plot
|
102 |
+
The Reserve XY plot button reserves the execution of an XY plot for the setting at the time the button is pressed, instead of immediately executing the plot. The reserved XY plot will be executed after the normal XY plot is completed or by pressing the Start XY plot button on the Reservation tab. Reservations can be made at any time during the execution or non-execution of an XY plot. The reservation list is not automatically updated, so use the Reload button. If an error occurs, the plot is discarded and the next reservation is executed. Images will not be displayed until all reservations are finished, but those that have been marked "Finished" have finished generating the grid and can be viewed in the Image Browser or other applications.
|
103 |
+
|
104 |
+
It is also possible to move to an appointment at any location by using "|".
|
105 |
+
Inputing "0.1,0.2,0.3,0.4,0.5|0.6,0.7,0.8,0.9,1.0"
|
106 |
+
|
107 |
+
0.1,0.2,0.3,0.4,0.5
|
108 |
+
0.6,0.7,0.8,0.9,1.0
|
109 |
+
The grid is divided into two reservations, "0.1,0.2,0.3,0.4,0.5" and "0.6,0.7,0.8,0.9,1.0" executed. This may be useful when there are too many elements and the grid becomes too large.
|
110 |
+
|
111 |
+
### About Cache
|
112 |
+
By storing models in memory, continuous merging and other operations can be sped up.
|
113 |
+
Cache settings can be configured from web-ui's setting menu.
|
114 |
+
|
115 |
+
### unload button
|
116 |
+
Deletes the currently loaded model. This is used to free up GPU memory when using kohya-ss GUI. Once the model is deleted, you will not be able to generate images. If you want to generate images, please re-select models.
|
117 |
+
|
118 |
+
## LoRA
|
119 |
+
LoRA related functions. It is basically the same as kohya-ss scripts, but it supports block-by-block merging. Currently, it does not support V2.X series merging.
|
120 |
+
|
121 |
+
Note: LyCORIS supports only single merge due to its special structure. Only ratios of 1,0 can be used for single merges. If any other value is used, the result will not match the Block weight LoRA result, even if the value is "SAME TO STRENGTH".
|
122 |
+
LoCon will match reasonably well even with non-integers.
|
123 |
+
|
124 |
+
### merge to checkpoint
|
125 |
+
Merge LoRAs into a model. Multiple LoRAs can be merged at the same time.
|
126 |
+
Enter LoRA name1:ratio1:block1,LoRA name2:ratio2:block2,...
|
127 |
+
LoRA can also be used alone. The ":block" part can be omitted. The ratio can be any value, including negative values. There is no restriction that the total must sum to 1 (of course, if it greatly exceeds 1, it will break down).
|
128 |
+
|
129 |
+
### Make LoRA
|
130 |
+
Generates a LoRA from the difference of two models.
|
131 |
+
If you specify a demension, it will be created with the specified dimension. If no demension is specified, LoRAs are created with dim 128.
|
132 |
+
The blend ratio can be adjusted by alpha and beta. (alpha x Model_A - beta x Model B) alpha, beta = 1 is the normal LoRA creation.
|
133 |
+
|
134 |
+
#### caution in using google colab
|
135 |
+
It has been reported that many errors occur when using with colab. This seems to be caused by multiple reasons.
|
136 |
+
First is a memory problem. It is recommended that the fp16 model be used. If the full model is used, at least 8 GB of memory is required. This is the amount used by this script. Also, it seems that the error occurs if different versions of diffusers are installed. version 0.10.2 has been tested.
|
137 |
+
|
138 |
+
### merge LoRAs
|
139 |
+
Merges one or more LoRAs. kohya-ss's latest script is used, so LoRAs with different dimensions can be merged, but note that the generated images may differ significantly because LoRAs are recalculated when dimensions are converted.
|
140 |
+
|
141 |
+
The calculate dimention button calculates the dimensions of each LoRA and activates the display and sorting functions. The calculation is rather time-consuming and takes several tens of seconds for a LoRA of about 50. Newly merged LoRAs will not appear in the list, so please press the reload button. Dimension recalculation only calculates the added LoRAs.
|
142 |
+
|
143 |
+
### Difference between Normal Merge and SAME TO STRENGTH
|
144 |
+
If the same to Strength option is not used, the result is the same as the merge in the script created by kohya-ss. In this case, the result is different from the case where LoRA is applied on Web-ui as shown in the figure below. The reason for this is related to the mathematical formula used to adopt LoRA into U-net. kohya-ss's script multiplies the ratio as it is, but the formula used to apply LoRA squares the ratio, so if the ratio is set to a number other than 1, or to a negative value, the result will differ from Strength (strength when applied). Using the SAME TO STRENGTH option, the square root of the ratio is driven at merge time, so that Strength and the ratio are calculated to have the same meaning at apply time. It is also calculated so that a negative value will have the same effect. If you are not doing additional learning, for example, you may be fine using the SAME TO STRENGTH option, but if you are doing additional learning on the merged LoRA, you may not want to use anyone else's option.
|
145 |
+
The following figures show the generated images for each case of normal image generation/same to Strength option/normal merge, using merged LoRAs of figmization and ukiyoE. You can see that in the case of normal merge, even in the negative direction, the image is squared and positive.
|
146 |
+
![xyz_grid-0014-1534704891](https://user-images.githubusercontent.com/122196982/218322034-b7171298-5159-4619-be1d-ac684da92ed9.jpg)
|
147 |
+
|
148 |
+
For hierarchical merges see
|
149 |
+
|
150 |
+
https://github.com/bbc-mc/sdweb-merge-block-weighted-gui
|
151 |
+
|
152 |
+
This script uses some scripts from web-ui, mbw-merge and kohya-ss
|
extensions/microsoftexcel-supermerger/README_ja.md
ADDED
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# SuperMerger
|
2 |
+
- Model merge extention for [AUTOMATIC1111's stable-diffusion-webui](https://github.com/AUTOMATIC1111/stable-diffusion-webui)
|
3 |
+
- Merge models can be loaded directly for generation without saving
|
4 |
+
|
5 |
+
# Recent Update
|
6 |
+
すべての更新履歴は[こちら](https://github.com/hako-mikan/sd-webui-supermerger/blob/main/changelog.md)にあります。
|
7 |
+
All updates can be found [here](https://github.com/hako-mikan/sd-webui-supermerger/blob/main/changelog.md).
|
8 |
+
|
9 |
+
### English / 日本語
|
10 |
+
English: [![jp](https://img.shields.io/badge/lang-English-green.svg)](https://github.com/hako-mikan/sd-webui-supermerger/blob/main/README.md)
|
11 |
+
|
12 |
+
## Updates
|
13 |
+
- 機能更新, コサイン類似度を用いた最適値計算機能を強化しました[詳細](https://github.com/hako-mikan/sd-webui-supermerger/blob/main/calcmode_en.md#cosine)
|
14 |
+
- 新機能, 新しいマージ方式tensorを導入しました [詳細](https://github.com/hako-mikan/sd-webui-supermerger/blob/main/calcmode_en.md#tensor)
|
15 |
+
- XYプロットに新しい軸タイプを追加しました : calcmode,prompt
|
16 |
+
|
17 |
+
一部LoRA関係の機能を使用する場合diffusers(0.10.2以降),sklearnが必要です。
|
18 |
+
#
|
19 |
+
|
20 |
+
# 概要
|
21 |
+
このextentionではモデルをマージした際、保存せずに画像生成用のモデルとして読み込むことができます。
|
22 |
+
これまでマージしたモデルはいったん保存して気に入らなければ削除するということが必要でしたが、このextentionを使うことでHDDやSSDの消耗を防ぐことができます。
|
23 |
+
|
24 |
+
# 各種設定
|
25 |
+
## マージモード
|
26 |
+
### Weight sum
|
27 |
+
通常のマージです。alphaが使用されます。α=0の場合Model A, α=1 の時model Bになります。
|
28 |
+
### Add difference
|
29 |
+
差分マージです。
|
30 |
+
### Triple sum
|
31 |
+
マージを3モデル同時に行います。alpha,betaが使用されます。モデル選択窓が3つあったので追加した機能ですが、ちゃんと動くようです。MBWでも使えます。それぞれMBWのalpha,betaを入力してください。
|
32 |
+
### sum Twice
|
33 |
+
Weight sumを2回行います。alpha,betaが使用されます。MBWモードでも使えます。それぞれMBWのalpha,betaを入力してください。
|
34 |
+
|
35 |
+
### use MBW
|
36 |
+
チェックするとブロックごとのマージ(階層マージ)が有効になります。各ブロックごとの比率は下部のスライダーかプリセットで設定してください。
|
37 |
+
|
38 |
+
### 計算手法(calcmode)
|
39 |
+
cosineを選択すると、設定されたマージ比率を中心として、コサイン類似度を用いた比較を行い、マージによるロスをなくすような比率を計算し、その比率を用いてマージを行います。
|
40 |
+
詳しくは下記を参照して下さい(英語です)
|
41 |
+
考案された[recoilme](https://github.com/recoilme)氏とこの手法を紹介し最適化してくれた[SwiftIllusion](https://github.com/SwiftIllusion)氏に感謝します。
|
42 |
+
https://github.com/hako-mikan/sd-webui-supermerger/issues/33
|
43 |
+
https://github.com/recoilme/losslessmix
|
44 |
+
|
45 |
+
### 保存
|
46 |
+
save metadataを有効にするとマージ条件をメタデータとして埋め込めます。safetensor形式のみ有効です。埋め込まれた条件はMetadataタブで確認できます。
|
47 |
+
|
48 |
+
## 各ボタン
|
49 |
+
### Merge
|
50 |
+
マージした後、生成用モデルとして読み込みます。 __左上のモデル情報とは違うモデルがロードされていることに注意してください。__ 左上のモデル選択画面でモデルを選択しなおすとリセットされます
|
51 |
+
|
52 |
+
### Gen
|
53 |
+
text2imageタブの設定で画像生成を行います
|
54 |
+
|
55 |
+
### Merge and Gen
|
56 |
+
マージしたのち画像を生成します
|
57 |
+
|
58 |
+
### Set from ID
|
59 |
+
マージログから設定を読み込みます。ログはマージが行われるたびに更新され、1から始まる連番のIDが付与されます。IDを生成される画像やPNG infoに記載することも可能で、write merged model ID toから設定してください。-1でSetをすると最後にマージした設定を読み出します。マージログはextention/sd-webui-supermerger/mergehistory.csvに保存されます。他アプリで開いた状態だと読み取りエラーを起こすので注意してください。Historyタブで閲覧や検索が可能です。検索は半角スペースで区切ることでand/or検索が可能です。
|
60 |
+
|
61 |
+
## Hires-fix,batch size
|
62 |
+
Hires-fixを有効化できます。batch sizeを変更できます。batch sizeはXY plotでは無効化されます。
|
63 |
+
|
64 |
+
## Elemental merge
|
65 |
+
[こちら](https://github.com/hako-mikan/sd-webui-supermerger/blob/main/elemental_ja.md)を参照して下さい。
|
66 |
+
|
67 |
+
## Sequential XY Merge and Generation
|
68 |
+
連続マージ画像生成を行います。すべてのマージモードで有効です。
|
69 |
+
### alpha,beta
|
70 |
+
アルファ、ベータを変更します。tensorモードでも有効です。
|
71 |
+
### alpha and beta
|
72 |
+
アルファ、ベータを同時に変更します。アルファ、ベータの間は半角スペースで区���り、各要素はカンマで区切ってください。数字ひとつの場合はアルファベータ共に同じ値が入力されます。tensorモードでも有効です。
|
73 |
+
例: 0,0.5 0.1,0.3 0.4,0.5
|
74 |
+
### MBW
|
75 |
+
階層マージを行います。改行で区切った比率を入力してください。プリセットも使用可能ですが、**改行で区切る**ことに注意をして下さい。Triple,Twiceの場合は2行で1セットで入力して下さい。奇数行だとエラーになります。
|
76 |
+
### seed
|
77 |
+
シードを変更します。-1と入力すると、反対の軸方向には固定されたseedになります。
|
78 |
+
### model_A,B,C
|
79 |
+
モデルを変更します。モデル選択窓で選択されたモデルは無視されます。
|
80 |
+
### pinpoint blocks
|
81 |
+
MBWにおいて特定のブロックのみを変化させます。反対の軸はalphaまたはbetaを選んでください。ブロックIDを入力すると、そのブロックのみalpha(beta)が変わります。他のタイプと同様にカンマで区切ります。スペースまたはハイフンで区切ることで複数のブロックを同時に変化させることもできます。最初にNOTをつけることで変化対象が反転します。NOT IN09-OUT02とすると、IN09-OUT02以外が変化します。NOTは最初に入力しないと効果がありません。
|
82 |
+
#### 入力例
|
83 |
+
IN01,OUT10 OUT11, OUT03-OUT06,OUT07-OUT11,NOT M00 OUT03-OUT06
|
84 |
+
この場合
|
85 |
+
- 1:IN01のみ変化
|
86 |
+
- 2:OUT10およびOUT11が変化
|
87 |
+
- 3:OUT03からOUT06が変化
|
88 |
+
- 4:OUT07からOUT11が変化
|
89 |
+
- 5:M00およびOUT03からOUT06以外が変化
|
90 |
+
|
91 |
+
となります。0の打ち忘れに注意してください。
|
92 |
+
![xy_grid-0006-2934360860 0](https://user-images.githubusercontent.com/122196982/214343111-e82bb20a-799b-4026-8e3c-dd36e26841e3.jpg)
|
93 |
+
|
94 |
+
ブロックID(大文字のみ有効)
|
95 |
+
BASE,IN00,IN01,IN02,IN03,IN04,IN05,IN06,IN07,IN08,IN09,IN10,IN11,M00,OUT00,OUT01,OUT02,OUT03,OUT04,OUT05,OUT06,OUT07,OUT08,OUT09,OUT10,OUT11
|
96 |
+
|
97 |
+
### calcmode
|
98 |
+
計算方式を変更します。適用できるマージモードとの対応に注意して下さい。カンマで区切ります
|
99 |
+
|
100 |
+
### prompt
|
101 |
+
プロンプトを変更できます。txt2imgのプロンプトは無視されます。ネガティブプロンプトは有効です。
|
102 |
+
**改行で区切る**ことに注意をして下さい。
|
103 |
+
|
104 |
+
### XYプロットの予約
|
105 |
+
Reserve XY plotボタンはすぐさまプロットを実行せず、ボタンを押したときの設定のXYプロットの実行を予約します。予約したXYプロットは通常のXYプロットが終了した後か、ReservationタブのStart XY plotボタンを押すと実行が開始されます。予約はXYプロット実行時・未実行時いつでも可能です。予約一覧は自動更新されないのでリロードボタンを使用してください。エラー発生時はそのプロットを破棄して次の予約を実行します。すべての予約が終了するまで画像は表示されませんが、Finishedになったものについてはグリッドの生成は終わっているので、Image Browser等で見ることが可能です。
|
106 |
+
「|」を使用することで任意の場所で予約へ移動することも可能です。
|
107 |
+
0.1,0.2,0.3,0.4,0.5|0.6,0.7,0.8,0.9,1.0とすると
|
108 |
+
|
109 |
+
0.1,0.2,0.3,0.4,0.5
|
110 |
+
0.6,0.7,0.8,0.9,1.0
|
111 |
+
というふたつの予約に分割され実行されます。これは要素が多すぎてグリッドが大きくなってしまう場合などに有効でしょう。
|
112 |
+
|
113 |
+
### キャッシュについて
|
114 |
+
モデルをメモリ上に保存することにより連続マージなどを高速化することができます。
|
115 |
+
キャッシュの設定はweb-uiのsettingから行ってください。
|
116 |
+
|
117 |
+
### unloadボタン
|
118 |
+
現在ロードされているモデルを消去します。これはkohya-ssのGUIを使用するときなどGPUメモリを開放するときに使用します。消去すると画像の生成はできません。生成する場合にはモデルを選び直して下さい。
|
119 |
+
|
120 |
+
## LoRA
|
121 |
+
LoRA関連の機能です。基本的にはkohya-ssのスクリプトと同じですが、階層マージに対応します。現時点ではV2.X系のマージには対応していません。
|
122 |
+
|
123 |
+
注意:LyCORISは構造が特殊なため単独マージのみに対応しています。単独マージの比率は1,0のみ使用可能です。他の値を用いるとsame to Strengthでも階層LoRAの結果と一致しません。
|
124 |
+
LoConは整数以外でもそれなりに一致します。
|
125 |
+
|
126 |
+
### merge to checkpoint
|
127 |
+
モデルにLoRAをマージします。複数のLoRAを同時にマージできます。
|
128 |
+
LoRA名1:マージ比率1:階層,LoRA名2:階層,マージ比率2,LoRA名3:マージ比率3・・・
|
129 |
+
と入力します。LoRA単独でも使用可能です。「:階層」の部分は無くても問題ありません。比率はマイナスを含めどんな値でも入力できます。合計が1にならないといけないという制約もありません(���ちろん大きく1を越えると破綻します)。
|
130 |
+
|
131 |
+
### Make LoRA
|
132 |
+
ふたつのモデルの差分からLoRAを生成します。
|
133 |
+
demensionを指定すると指定されたdimensionで作製されます。無指定の場合は128で作製します。
|
134 |
+
alphaとbetaによって配合比率を調整することができます。(alpha x Model_A - beta x Model B) alpha, beta = 1が通常のLoRA作成となります。
|
135 |
+
|
136 |
+
#### google colab使用時の問題
|
137 |
+
colabで使用する場合に多くのエラーが発生することが報告されています。これは複数の原因によって発生しているようです。
|
138 |
+
まずはメモリの問題です。モデルはfp16モデルを使用することを推奨します。フルモデルを使用した場合8GB以上のメモリが必要になります。これはこのスクリプトが使用する量です。また、インストールされているdiffusersのバージョンが異なるとエラーが発生するようです。version 0.10.2で動作確認されています。
|
139 |
+
|
140 |
+
### merge LoRAs
|
141 |
+
ひとつまたは複数のLoRA同士をマージします。kohya-ss氏の最新のスクリプトを使用しているので、dimensionの異なるLoRA同氏もマージ可能ですが、dimensionの変換の際はLoRAの再計算を行うため、生成される画像が大きく異なる可能性があることに注意してください。
|
142 |
+
|
143 |
+
calculate dimentionボタンで各LoRAの次元を計算して表示・ソート機能が有効化します。計算にはわりと時間がかかって、50程度のLoRAでも数十秒かかります。新しくマージされたLoRAはリストに表示されないのでリロードボタンを押してください。次元の再計算は追加されたLoRAだけを計算します。
|
144 |
+
|
145 |
+
### 通常マージとsame to Strengthの違い
|
146 |
+
same to Strengthオプションを使用しない場合は、kohya-ss氏の作製したスクリプトのマージと同じ結果になります。この場合、下図のようにWeb-ui上でLoRAを適用した場合と異なる結果になります。これはLoRAをU-netに組み込む際の数式が関係しています。kohya-ss氏のスクリプトでは比率をそのまま掛けていますが、適用時の数式では比率が2乗されてしまうため、比率を1以外の数値に設定すると、あるいはマイナスに設定するとStrength(適用時の強度)と異なる結果となります。same to Strengthオプションを使用すると、マージ時には比率の平方根を駆けることで、適用時にはStrengthと比率が同じ意味を持つように計算しています。また、マイナスが効果が出るようにも計算しています。追加学習をしない場合などはsame to Strengthオプションを使用しても問題ないと思いますが、マージしたLoRAに対して追加学習をする場合はだれも使用しない方がいいかもしれません。
|
147 |
+
下図は通常適用/same to Strengthオプション/通常マージの各場合の生成画像です。figma化とukiyoE LoRAのマージを使用しています。通常マージの場合はマイナス方向でも2乗されてプラスになっていることが分かります。
|
148 |
+
![xyz_grid-0014-1534704891](https://user-images.githubusercontent.com/122196982/218322034-b7171298-5159-4619-be1d-ac684da92ed9.jpg)
|
149 |
+
|
150 |
+
階層別マージについては下記を参照してください
|
151 |
+
|
152 |
+
https://github.com/bbc-mc/sdweb-merge-block-weighted-gui
|
153 |
+
|
154 |
+
このスクリプトではweb-ui、mbw-merge、kohya-ssのスクリプトを一部使用しています
|
extensions/microsoftexcel-supermerger/calcmode_en.md
ADDED
The diff for this file is too large to render.
See raw diff
|
|
extensions/microsoftexcel-supermerger/changelog.md
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Changelog
|
2 |
+
### bug fix 2023.02.19.2330(JST)
|
3 |
+
いくつかのバグが修正されました
|
4 |
+
- LOWRAMオプション有効時にエラーになる問題
|
5 |
+
- Linuxでエラーになる問題
|
6 |
+
- XY plotが正常に終了しない問題
|
7 |
+
- 未ロードのモデルを設定時にエラーになる問題
|
8 |
+
|
9 |
+
### update to version 3 2023.02.17.2020(JST)
|
10 |
+
- LoRA関係の機能を追加しました
|
11 |
+
- Logを保存し、設定を呼び出せるようになりました
|
12 |
+
- safetensors,fp16形式での保存に対応しました
|
13 |
+
- weightのプリセットに対応しました
|
14 |
+
- XYプロットの予約が可能になりました
|
15 |
+
|
16 |
+
### bug fix 2023.02.19.2330(JST)
|
17 |
+
Several bugs have been fixed
|
18 |
+
- Error when LOWRAM option is enabled
|
19 |
+
- Error on Linux
|
20 |
+
- XY plot did not finish properly
|
21 |
+
- Error when setting unused models
|
22 |
+
|
23 |
+
### update to version 3 2023.02.17.2020(JST)
|
24 |
+
- Added LoRA related functions
|
25 |
+
- Logs can now be saved and settings can be recalled.
|
26 |
+
- Save in safetensors and fp16 format is now supported.
|
27 |
+
- Weight presets are now supported.
|
28 |
+
- Reservation of XY plots is now possible.
|
29 |
+
|
30 |
+
### bug fix 2023.01.29.0000(JST)
|
31 |
+
pinpoint blocksがX方向で使用できない問題を修正しました。
|
32 |
+
pinpoint blocks選択時Triple,Twiceを使用できない問題を解決しました
|
33 |
+
XY plot 使用時に一部軸タイプでMBWを使用できない問題を解決しました
|
34 |
+
Fixed a problem where pinpoint blocks could not be used in the X axis.
|
35 |
+
Fixed a problem in which Triple,Twice could not be used when selecting pinpoint blocks.
|
36 |
+
Problem solved where MBW could not be used with some axis types when using XY plot.
|
37 |
+
|
38 |
+
### bug fixed 2023.01.28.0100(JST)
|
39 |
+
MBWモードでSave current modelボタンが正常に動作しない問題を解決しました
|
40 |
+
ファイル名が長すぎて保存時にエラーが出る問題を解決しました
|
41 |
+
Problem solved where the "Save current model" button would not work properly in MBW mode
|
42 |
+
Problem solved where an error would occur when saving a file with too long a file name
|
43 |
+
|
44 |
+
### bug fixed 2023.01.26.2100(JST)
|
45 |
+
XY plotにおいてタイプMBWが使用できない不具合を修正しました
|
46 |
+
Fixed a bug that type of MBW could work in XY plot
|
47 |
+
|
48 |
+
### updated 2023.01.25.0000(JST)
|
49 |
+
added several features
|
50 |
+
- added new merge mode "Triple sum","sum Twice"
|
51 |
+
- added XY plot
|
52 |
+
- 新しいマージモードを追加しました "Triple sum","sum Twice"
|
53 |
+
- XY plot機能を追加しました
|
54 |
+
|
55 |
+
### bug fixed 2023.01.20.2350(JST)
|
56 |
+
png infoがうまく保存できない問題を解決しました。
|
57 |
+
Problem solved where png info could not be saved properly.
|