ddoc commited on
Commit
45d6d70
·
1 Parent(s): 0ceb118

Upload !adetailer.py

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