ddoc commited on
Commit
a4ef135
·
1 Parent(s): da5abf4

Upload !adetailer.py

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