ddoc commited on
Commit
98f577c
·
1 Parent(s): eff57cb

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