ddoc commited on
Commit
446fe63
·
1 Parent(s): 76f726a

Upload !adetailer.py

Browse files
Files changed (1) hide show
  1. !adetailer.py +666 -0
!adetailer.py ADDED
@@ -0,0 +1,666 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import platform
5
+ import re
6
+ import sys
7
+ import traceback
8
+ from contextlib import contextmanager
9
+ from copy import copy, deepcopy
10
+ from pathlib import Path
11
+ from textwrap import dedent
12
+ from typing import Any
13
+
14
+
15
+
16
+ import gradio as gr
17
+ import torch
18
+
19
+ import modules # noqa: F401
20
+
21
+ from modules import scripts as script1
22
+ from modules import script_callbacks as scriptcall
23
+ from modules import sd_samplers_compvis, sd_samplers_kdiffusion, sd_samplers_common
24
+
25
+ from adetailer import (
26
+ AFTER_DETAILER,
27
+ __version__,
28
+ get_models,
29
+ mediapipe_predict,
30
+ ultralytics_predict,
31
+ )
32
+ from adetailer.args import ALL_ARGS, BBOX_SORTBY, ADetailerArgs, EnableChecker
33
+ from adetailer.common import PredictOutput
34
+ from adetailer.mask import filter_by_ratio, mask_preprocess, sort_bboxes
35
+ from adetailer.ui import adui, ordinal, suffix
36
+ from controlnet_ext import ControlNetExt, controlnet_exists
37
+ from controlnet_ext.restore import (
38
+ CNHijackRestore,
39
+ cn_allow_script_control,
40
+ cn_restore_unet_hook,
41
+ )
42
+ from sd_webui import images, safe, script_callbacks, scripts, shared
43
+ from sd_webui.paths import data_path, models_path
44
+ from sd_webui.processing import (
45
+ StableDiffusionProcessingImg2Img,
46
+ create_infotext,
47
+ process_images,
48
+ )
49
+ from sd_webui.shared import cmd_opts, opts, state
50
+
51
+ try:
52
+ from rich import print
53
+ from rich.traceback import install
54
+
55
+ install(show_locals=True)
56
+ except Exception:
57
+ pass
58
+
59
+ no_huggingface = getattr(cmd_opts, "ad_no_huggingface", False)
60
+ adetailer_dir = Path(models_path, "adetailer")
61
+ model_mapping = get_models(adetailer_dir, huggingface=not no_huggingface)
62
+ txt2img_submit_button = img2img_submit_button = None
63
+ SCRIPT_DEFAULT = "dynamic_prompting,dynamic_thresholding,wildcard_recursive,wildcards"
64
+
65
+ if (
66
+ not adetailer_dir.exists()
67
+ and adetailer_dir.parent.exists()
68
+ and os.access(adetailer_dir.parent, os.W_OK)
69
+ ):
70
+ adetailer_dir.mkdir()
71
+
72
+ print(
73
+ f"[-] ADetailer initialized. version: {__version__}, num models: {len(model_mapping)}"
74
+ )
75
+
76
+
77
+ @contextmanager
78
+ def change_torch_load():
79
+ orig = torch.load
80
+ try:
81
+ torch.load = safe.unsafe_torch_load
82
+ yield
83
+ finally:
84
+ torch.load = orig
85
+
86
+
87
+ @contextmanager
88
+ def pause_total_tqdm():
89
+ orig = opts.data.get("multiple_tqdm", True)
90
+ try:
91
+ opts.data["multiple_tqdm"] = False
92
+ yield
93
+ finally:
94
+ opts.data["multiple_tqdm"] = orig
95
+
96
+
97
+ class AfterDetailerScript(scripts.Script):
98
+ def __init__(self):
99
+ super().__init__()
100
+ self.ultralytics_device = self.get_ultralytics_device()
101
+
102
+ self.controlnet_ext = None
103
+ self.cn_script = None
104
+ self.cn_latest_network = None
105
+
106
+ def title(self):
107
+ return AFTER_DETAILER
108
+
109
+ def show(self, is_img2img):
110
+ return scripts.AlwaysVisible
111
+
112
+ def ui(self, is_img2img):
113
+ num_models = opts.data.get("ad_max_models", 2)
114
+ model_list = list(model_mapping.keys())
115
+
116
+ components, infotext_fields = adui(
117
+ num_models,
118
+ is_img2img,
119
+ model_list,
120
+ txt2img_submit_button,
121
+ img2img_submit_button,
122
+ )
123
+
124
+ self.infotext_fields = infotext_fields
125
+ return components
126
+
127
+ def init_controlnet_ext(self) -> None:
128
+ if self.controlnet_ext is not None:
129
+ return
130
+ self.controlnet_ext = ControlNetExt()
131
+
132
+ if controlnet_exists:
133
+ try:
134
+ self.controlnet_ext.init_controlnet()
135
+ except ImportError:
136
+ error = traceback.format_exc()
137
+ print(
138
+ f"[-] ADetailer: ControlNetExt init failed:\n{error}",
139
+ file=sys.stderr,
140
+ )
141
+
142
+ def update_controlnet_args(self, p, args: ADetailerArgs) -> None:
143
+ if self.controlnet_ext is None:
144
+ self.init_controlnet_ext()
145
+
146
+ if (
147
+ self.controlnet_ext is not None
148
+ and self.controlnet_ext.cn_available
149
+ and args.ad_controlnet_model != "None"
150
+ ):
151
+ self.controlnet_ext.update_scripts_args(
152
+ p, args.ad_controlnet_model, args.ad_controlnet_weight
153
+ )
154
+
155
+ def is_ad_enabled(self, *args_) -> bool:
156
+ if len(args_) == 0 or (len(args_) == 1 and isinstance(args_[0], bool)):
157
+ message = f"""
158
+ [-] ADetailer: Not enough arguments passed to ADetailer.
159
+ input: {args_!r}
160
+ """
161
+ raise ValueError(dedent(message))
162
+ a0 = args_[0]
163
+ a1 = args_[1] if len(args_) > 1 else None
164
+ checker = EnableChecker(a0=a0, a1=a1)
165
+ return checker.is_enabled()
166
+
167
+ def get_args(self, *args_) -> list[ADetailerArgs]:
168
+ """
169
+ `args_` is at least 1 in length by `is_ad_enabled` immediately above
170
+ """
171
+ args = [arg for arg in args_ if isinstance(arg, dict)]
172
+
173
+ if not args:
174
+ message = f"[-] ADetailer: Invalid arguments passed to ADetailer: {args_!r}"
175
+ raise ValueError(message)
176
+
177
+ all_inputs = []
178
+
179
+ for n, arg_dict in enumerate(args, 1):
180
+ try:
181
+ inp = ADetailerArgs(**arg_dict)
182
+ except ValueError as e:
183
+ msgs = [
184
+ f"[-] ADetailer: ValidationError when validating {ordinal(n)} arguments: {e}\n"
185
+ ]
186
+ for attr in ALL_ARGS.attrs:
187
+ arg = arg_dict.get(attr)
188
+ dtype = type(arg)
189
+ arg = "DEFAULT" if arg is None else repr(arg)
190
+ msgs.append(f" {attr}: {arg} ({dtype})")
191
+ raise ValueError("\n".join(msgs)) from e
192
+
193
+ all_inputs.append(inp)
194
+
195
+ return all_inputs
196
+
197
+ def extra_params(self, arg_list: list[ADetailerArgs]) -> dict:
198
+ params = {}
199
+ for n, args in enumerate(arg_list):
200
+ params.update(args.extra_params(suffix=suffix(n)))
201
+ params["ADetailer version"] = __version__
202
+ return params
203
+
204
+ @staticmethod
205
+ def get_ultralytics_device() -> str:
206
+ '`device = ""` means autodetect'
207
+ device = ""
208
+ if platform.system() == "Darwin":
209
+ return device
210
+
211
+ if any(getattr(cmd_opts, vram, False) for vram in ["lowvram", "medvram"]):
212
+ device = "cpu"
213
+
214
+ return device
215
+
216
+ def prompt_blank_replacement(
217
+ self, all_prompts: list[str], i: int, default: str
218
+ ) -> str:
219
+ if not all_prompts:
220
+ return default
221
+ if i < len(all_prompts):
222
+ return all_prompts[i]
223
+ j = i % len(all_prompts)
224
+ return all_prompts[j]
225
+
226
+ def _get_prompt(
227
+ self, ad_prompt: str, all_prompts: list[str], i: int, default: str
228
+ ) -> list[str]:
229
+ prompts = re.split(r"\s*\[SEP\]\s*", ad_prompt)
230
+ blank_replacement = self.prompt_blank_replacement(all_prompts, i, default)
231
+ for n in range(len(prompts)):
232
+ if not prompts[n]:
233
+ prompts[n] = blank_replacement
234
+ return prompts
235
+
236
+ def get_prompt(self, p, args: ADetailerArgs) -> tuple[list[str], list[str]]:
237
+ i = p._idx
238
+
239
+ prompt = self._get_prompt(args.ad_prompt, p.all_prompts, i, p.prompt)
240
+ negative_prompt = self._get_prompt(
241
+ args.ad_negative_prompt, p.all_negative_prompts, i, p.negative_prompt
242
+ )
243
+
244
+ return prompt, negative_prompt
245
+
246
+ def get_seed(self, p) -> tuple[int, int]:
247
+ i = p._idx
248
+
249
+ if not p.all_seeds:
250
+ seed = p.seed
251
+ elif i < len(p.all_seeds):
252
+ seed = p.all_seeds[i]
253
+ else:
254
+ j = i % len(p.all_seeds)
255
+ seed = p.all_seeds[j]
256
+
257
+ if not p.all_subseeds:
258
+ subseed = p.subseed
259
+ elif i < len(p.all_subseeds):
260
+ subseed = p.all_subseeds[i]
261
+ else:
262
+ j = i % len(p.all_subseeds)
263
+ subseed = p.all_subseeds[j]
264
+
265
+ return seed, subseed
266
+
267
+ def get_width_height(self, p, args: ADetailerArgs) -> tuple[int, int]:
268
+ if args.ad_use_inpaint_width_height:
269
+ width = args.ad_inpaint_width
270
+ height = args.ad_inpaint_height
271
+ else:
272
+ width = p.width
273
+ height = p.height
274
+
275
+ return width, height
276
+
277
+ def get_steps(self, p, args: ADetailerArgs) -> int:
278
+ if args.ad_use_steps:
279
+ return args.ad_steps
280
+ return p.steps
281
+
282
+ def get_cfg_scale(self, p, args: ADetailerArgs) -> float:
283
+ if args.ad_use_cfg_scale:
284
+ return args.ad_cfg_scale
285
+ return p.cfg_scale
286
+
287
+ def infotext(self, p) -> str:
288
+ return create_infotext(
289
+ p, p.all_prompts, p.all_seeds, p.all_subseeds, None, 0, 0
290
+ )
291
+
292
+ def write_params_txt(self, p) -> None:
293
+ infotext = self.infotext(p)
294
+ params_txt = Path(data_path, "params.txt")
295
+ params_txt.write_text(infotext, encoding="utf-8")
296
+
297
+ def script_filter(self, p, args: ADetailerArgs):
298
+ script_runner = copy(p.scripts)
299
+ script_args = deepcopy(p.script_args)
300
+ self.disable_controlnet_units(script_args)
301
+
302
+ ad_only_seleted_scripts = opts.data.get("ad_only_seleted_scripts", True)
303
+ if not ad_only_seleted_scripts:
304
+ return script_runner, script_args
305
+
306
+ ad_script_names = opts.data.get("ad_script_names", SCRIPT_DEFAULT)
307
+ script_names_set = {
308
+ name
309
+ for script_name in ad_script_names.split(",")
310
+ for name in (script_name, script_name.strip())
311
+ }
312
+
313
+ if args.ad_controlnet_model != "None":
314
+ script_names_set.add("controlnet")
315
+
316
+ filtered_alwayson = []
317
+ for script_object in script_runner.alwayson_scripts:
318
+ filepath = script_object.filename
319
+ filename = Path(filepath).stem
320
+ if filename in script_names_set:
321
+ filtered_alwayson.append(script_object)
322
+ if filename == "controlnet":
323
+ self.cn_script = script_object
324
+ self.cn_latest_network = script_object.latest_network
325
+
326
+ script_runner.alwayson_scripts = filtered_alwayson
327
+ return script_runner, script_args
328
+
329
+ def disable_controlnet_units(self, script_args: list[Any]) -> None:
330
+ for obj in script_args:
331
+ if "controlnet" in obj.__class__.__name__.lower():
332
+ if hasattr(obj, "enabled"):
333
+ obj.enabled = False
334
+ if hasattr(obj, "input_mode"):
335
+ obj.input_mode = getattr(obj.input_mode, "SIMPLE", "simple")
336
+
337
+ elif isinstance(obj, dict) and "module" in obj:
338
+ obj["enabled"] = False
339
+
340
+ def get_i2i_p(self, p, args: ADetailerArgs, image):
341
+ seed, subseed = self.get_seed(p)
342
+ width, height = self.get_width_height(p, args)
343
+ steps = self.get_steps(p, args)
344
+ cfg_scale = self.get_cfg_scale(p, args)
345
+
346
+ sampler_name = p.sampler_name
347
+ if sampler_name in ["PLMS", "UniPC"]:
348
+ sampler_name = "Euler"
349
+
350
+ i2i = StableDiffusionProcessingImg2Img(
351
+ init_images=[image],
352
+ resize_mode=0,
353
+ denoising_strength=args.ad_denoising_strength,
354
+ mask=None,
355
+ mask_blur=args.ad_mask_blur,
356
+ inpainting_fill=1,
357
+ inpaint_full_res=args.ad_inpaint_full_res,
358
+ inpaint_full_res_padding=args.ad_inpaint_full_res_padding,
359
+ inpainting_mask_invert=0,
360
+ sd_model=p.sd_model,
361
+ outpath_samples=p.outpath_samples,
362
+ outpath_grids=p.outpath_grids,
363
+ prompt="", # replace later
364
+ negative_prompt="",
365
+ styles=p.styles,
366
+ seed=seed,
367
+ subseed=subseed,
368
+ subseed_strength=p.subseed_strength,
369
+ seed_resize_from_h=p.seed_resize_from_h,
370
+ seed_resize_from_w=p.seed_resize_from_w,
371
+ sampler_name=sampler_name,
372
+ batch_size=1,
373
+ n_iter=1,
374
+ steps=steps,
375
+ cfg_scale=cfg_scale,
376
+ width=width,
377
+ height=height,
378
+ restore_faces=args.ad_restore_face,
379
+ tiling=p.tiling,
380
+ extra_generation_params=p.extra_generation_params,
381
+ do_not_save_samples=True,
382
+ do_not_save_grid=True,
383
+ )
384
+
385
+ i2i.scripts, i2i.script_args = self.script_filter(p, args)
386
+ i2i._disable_adetailer = True
387
+
388
+ if args.ad_controlnet_model != "None":
389
+ self.update_controlnet_args(i2i, args)
390
+ else:
391
+ i2i.control_net_enabled = False
392
+
393
+ return i2i
394
+
395
+ def save_image(self, p, image, *, condition: str, suffix: str) -> None:
396
+ i = p._idx
397
+ seed, _ = self.get_seed(p)
398
+
399
+ if opts.data.get(condition, False):
400
+ images.save_image(
401
+ image=image,
402
+ path=p.outpath_samples,
403
+ basename="",
404
+ seed=seed,
405
+ prompt=p.all_prompts[i] if i < len(p.all_prompts) else p.prompt,
406
+ extension=opts.samples_format,
407
+ info=self.infotext(p),
408
+ p=p,
409
+ suffix=suffix,
410
+ )
411
+
412
+ def get_ad_model(self, name: str):
413
+ if name not in model_mapping:
414
+ msg = f"[-] ADetailer: Model {name!r} not found. Available models: {list(model_mapping.keys())}"
415
+ raise ValueError(msg)
416
+ return model_mapping[name]
417
+
418
+ def sort_bboxes(self, pred: PredictOutput) -> PredictOutput:
419
+ sortby = opts.data.get("ad_bbox_sortby", BBOX_SORTBY[0])
420
+ sortby_idx = BBOX_SORTBY.index(sortby)
421
+ pred = sort_bboxes(pred, sortby_idx)
422
+ return pred
423
+
424
+ def pred_preprocessing(self, pred: PredictOutput, args: ADetailerArgs):
425
+ pred = filter_by_ratio(
426
+ pred, low=args.ad_mask_min_ratio, high=args.ad_mask_max_ratio
427
+ )
428
+ pred = self.sort_bboxes(pred)
429
+ return mask_preprocess(
430
+ pred.masks,
431
+ kernel=args.ad_dilate_erode,
432
+ x_offset=args.ad_x_offset,
433
+ y_offset=args.ad_y_offset,
434
+ merge_invert=args.ad_mask_merge_invert,
435
+ )
436
+
437
+ def i2i_prompts_replace(
438
+ self, i2i, prompts: list[str], negative_prompts: list[str], j: int
439
+ ):
440
+ i1 = min(j, len(prompts) - 1)
441
+ i2 = min(j, len(negative_prompts) - 1)
442
+ prompt = prompts[i1]
443
+ negative_prompt = negative_prompts[i2]
444
+ i2i.prompt = prompt
445
+ i2i.negative_prompt = negative_prompt
446
+
447
+ def is_need_call_process(self, p):
448
+ i = p._idx
449
+ n_iter = p.iteration
450
+ bs = p.batch_size
451
+ return (i == (n_iter + 1) * bs - 1) and (i != len(p.all_prompts) - 1)
452
+
453
+ def process(self, p, *args_):
454
+ if getattr(p, "_disable_adetailer", False):
455
+ return
456
+
457
+ if self.is_ad_enabled(*args_):
458
+ arg_list = self.get_args(*args_)
459
+ extra_params = self.extra_params(arg_list)
460
+ p.extra_generation_params.update(extra_params)
461
+
462
+ p._idx = -1
463
+
464
+ def _postprocess_image(self, p, pp, args: ADetailerArgs, *, n: int = 0) -> bool:
465
+ """
466
+ Returns
467
+ -------
468
+ bool
469
+
470
+ `True` if image was processed, `False` otherwise.
471
+ """
472
+ if state.interrupted:
473
+ return False
474
+
475
+ i = p._idx
476
+
477
+ i2i = self.get_i2i_p(p, args, pp.image)
478
+ seed, subseed = self.get_seed(p)
479
+ ad_prompts, ad_negatives = self.get_prompt(p, args)
480
+
481
+ is_mediapipe = args.ad_model.lower().startswith("mediapipe")
482
+
483
+ kwargs = {}
484
+ if is_mediapipe:
485
+ predictor = mediapipe_predict
486
+ ad_model = args.ad_model
487
+ else:
488
+ predictor = ultralytics_predict
489
+ ad_model = self.get_ad_model(args.ad_model)
490
+ kwargs["device"] = self.ultralytics_device
491
+
492
+ with change_torch_load():
493
+ pred = predictor(ad_model, pp.image, args.ad_conf, **kwargs)
494
+
495
+ masks = self.pred_preprocessing(pred, args)
496
+
497
+ if not masks:
498
+ print(
499
+ f"[-] ADetailer: nothing detected on image {i + 1} with {ordinal(n + 1)} settings."
500
+ )
501
+ return False
502
+
503
+ self.save_image(
504
+ p,
505
+ pred.preview,
506
+ condition="ad_save_previews",
507
+ suffix="-ad-preview" + suffix(n, "-"),
508
+ )
509
+
510
+ steps = len(masks)
511
+ processed = None
512
+ state.job_count += steps
513
+
514
+ if is_mediapipe:
515
+ print(f"mediapipe: {steps} detected.")
516
+
517
+ p2 = copy(i2i)
518
+ for j in range(steps):
519
+ p2.image_mask = masks[j]
520
+ self.i2i_prompts_replace(p2, ad_prompts, ad_negatives, j)
521
+
522
+ if not re.match(r"^\s*\[SKIP\]\s*$", p2.prompt):
523
+ if args.ad_controlnet_model == "None":
524
+ cn_restore_unet_hook(p2, self.cn_latest_network)
525
+ processed = process_images(p2)
526
+
527
+ p2 = copy(i2i)
528
+ p2.init_images = [processed.images[0]]
529
+
530
+ p2.seed = seed + j + 1
531
+ p2.subseed = subseed + j + 1
532
+
533
+ if processed is not None:
534
+ pp.image = processed.images[0]
535
+ return True
536
+
537
+ return False
538
+
539
+ def postprocess_image(self, p, pp, *args_):
540
+ if getattr(p, "_disable_adetailer", False):
541
+ return
542
+
543
+ if not self.is_ad_enabled(*args_):
544
+ return
545
+
546
+ p._idx = getattr(p, "_idx", -1) + 1
547
+ init_image = copy(pp.image)
548
+ arg_list = self.get_args(*args_)
549
+
550
+ is_processed = False
551
+ with CNHijackRestore(), pause_total_tqdm(), cn_allow_script_control():
552
+ for n, args in enumerate(arg_list):
553
+ if args.ad_model == "None":
554
+ continue
555
+ is_processed |= self._postprocess_image(p, pp, args, n=n)
556
+
557
+ if is_processed:
558
+ self.save_image(
559
+ p, init_image, condition="ad_save_images_before", suffix="-ad-before"
560
+ )
561
+
562
+ if self.cn_script is not None and self.is_need_call_process(p):
563
+ self.cn_script.process(p)
564
+
565
+ try:
566
+ if p._idx == len(p.all_prompts) - 1:
567
+ self.write_params_txt(p)
568
+ except Exception:
569
+ pass
570
+
571
+
572
+ def on_after_component(component, **_kwargs):
573
+ global txt2img_submit_button, img2img_submit_button
574
+ if getattr(component, "elem_id", None) == "txt2img_generate":
575
+ txt2img_submit_button = component
576
+ return
577
+
578
+ if getattr(component, "elem_id", None) == "img2img_generate":
579
+ img2img_submit_button = component
580
+
581
+
582
+ def on_ui_settings():
583
+ section = ("ADetailer", AFTER_DETAILER)
584
+ shared.opts.add_option(
585
+ "ad_max_models",
586
+ shared.OptionInfo(
587
+ default=2,
588
+ label="Max models",
589
+ component=gr.Slider,
590
+ component_args={"minimum": 1, "maximum": 5, "step": 1},
591
+ section=section,
592
+ ),
593
+ )
594
+
595
+ shared.opts.add_option(
596
+ "ad_save_previews",
597
+ shared.OptionInfo(False, "Save mask previews", section=section),
598
+ )
599
+
600
+ shared.opts.add_option(
601
+ "ad_save_images_before",
602
+ shared.OptionInfo(False, "Save images before ADetailer", section=section),
603
+ )
604
+
605
+ shared.opts.add_option(
606
+ "ad_only_seleted_scripts",
607
+ shared.OptionInfo(
608
+ True, "Apply only selected scripts to ADetailer", section=section
609
+ ),
610
+ )
611
+
612
+ textbox_args = {
613
+ "placeholder": "comma-separated list of script names",
614
+ "interactive": True,
615
+ }
616
+
617
+ shared.opts.add_option(
618
+ "ad_script_names",
619
+ shared.OptionInfo(
620
+ default=SCRIPT_DEFAULT,
621
+ label="Script names to apply to ADetailer (separated by comma)",
622
+ component=gr.Textbox,
623
+ component_args=textbox_args,
624
+ section=section,
625
+ ),
626
+ )
627
+
628
+ shared.opts.add_option(
629
+ "ad_bbox_sortby",
630
+ shared.OptionInfo(
631
+ default="None",
632
+ label="Sort bounding boxes by",
633
+ component=gr.Radio,
634
+ component_args={"choices": BBOX_SORTBY},
635
+ section=section,
636
+ ),
637
+ )
638
+
639
+ ########################################################
640
+
641
+ def make_axis_options():
642
+ xyz_grid = [x for x in script1.scripts_data if x.script_class.__module__ == "xyz_grid.py"][0].module
643
+
644
+ def apply_mimic_scale(p, x, xs):
645
+ args.ad_denoising_strength = getattr(p, 'inp denoising strength', args.ad_denoising_strength)
646
+
647
+ extra_axis_options = [
648
+ xyz_grid.AxisOption("[ade] inpaint denoising strength", float, xyz_grid.apply_field("inp denoising strength"))
649
+
650
+ ]
651
+ xyz_grid.axis_options.extend(extra_axis_options)
652
+ def callbackBeforeUi():
653
+ make_axis_options()
654
+
655
+
656
+
657
+
658
+
659
+
660
+
661
+
662
+ scriptcall.on_before_ui(callbackBeforeUi)
663
+
664
+
665
+ script_callbacks.on_ui_settings(on_ui_settings)
666
+ script_callbacks.on_after_component(on_after_component)