sdgsdggds commited on
Commit
a71d879
·
1 Parent(s): eec6df0

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