xyz_grid.py 32.9 KB
Newer Older
A
scripts  
AUTOMATIC 已提交
1 2
from collections import namedtuple
from copy import copy
D
DepFA 已提交
3
from itertools import permutations, chain
A
scripts  
AUTOMATIC 已提交
4
import random
D
DepFA 已提交
5
import csv
6
import os.path
D
DepFA 已提交
7
from io import StringIO
8
from PIL import Image
9 10
import numpy as np

A
scripts  
AUTOMATIC 已提交
11 12 13
import modules.scripts as scripts
import gradio as gr

14
from modules import images, sd_samplers, processing, sd_models, sd_vae, sd_samplers_kdiffusion, errors
15
from modules.processing import process_images, Processed, StableDiffusionProcessingTxt2Img
A
AUTOMATIC 已提交
16
from modules.shared import opts, state
17
import modules.shared as shared
A
scripts  
AUTOMATIC 已提交
18
import modules.sd_samplers
19
import modules.sd_models
20
import modules.sd_vae
A
AUTOMATIC 已提交
21
import re
A
scripts  
AUTOMATIC 已提交
22

23
from modules.ui_components import ToolButton
A
scripts  
AUTOMATIC 已提交
24

25
fill_values_symbol = "\U0001f4d2"  # 📒
S
space-nuko 已提交
26

27 28
AxisInfo = namedtuple('AxisInfo', ['axis', 'values'])

S
space-nuko 已提交
29

A
scripts  
AUTOMATIC 已提交
30 31 32 33 34 35 36 37
def apply_field(field):
    def fun(p, x, xs):
        setattr(p, field, x)

    return fun


def apply_prompt(p, x, xs):
38 39
    if xs[0] not in p.prompt and xs[0] not in p.negative_prompt:
        raise RuntimeError(f"Prompt S/R did not find {xs[0]} in prompt or negative prompt.")
40

A
scripts  
AUTOMATIC 已提交
41
    p.prompt = p.prompt.replace(xs[0], x)
42
    p.negative_prompt = p.negative_prompt.replace(xs[0], x)
A
scripts  
AUTOMATIC 已提交
43 44


45 46 47
def apply_order(p, x, xs):
    token_order = []

A
AUTOMATIC 已提交
48
    # Initally grab the tokens from the prompt, so they can be replaced in order of earliest seen
49 50 51 52 53
    for token in x:
        token_order.append((p.prompt.find(token), token))

    token_order.sort(key=lambda t: t[0])

54 55 56 57 58 59 60 61 62 63 64 65 66 67
    prompt_parts = []

    # Split the prompt up, taking out the tokens
    for _, token in token_order:
        n = p.prompt.find(token)
        prompt_parts.append(p.prompt[0:n])
        p.prompt = p.prompt[n + len(token):]

    # Rebuild the prompt with the tokens in the order we want
    prompt_tmp = ""
    for idx, part in enumerate(prompt_parts):
        prompt_tmp += part
        prompt_tmp += x[idx]
    p.prompt = prompt_tmp + p.prompt
A
scripts  
AUTOMATIC 已提交
68 69 70


def apply_sampler(p, x, xs):
71
    sampler_name = sd_samplers.samplers_map.get(x.lower(), None)
72
    if sampler_name is None:
A
scripts  
AUTOMATIC 已提交
73 74
        raise RuntimeError(f"Unknown sampler: {x}")

75
    p.sampler_name = sampler_name
A
scripts  
AUTOMATIC 已提交
76 77


M
Milly 已提交
78 79
def confirm_samplers(p, xs):
    for x in xs:
80
        if x.lower() not in sd_samplers.samplers_map:
M
Milly 已提交
81
            raise RuntimeError(f"Unknown sampler: {x}")
A
scripts  
AUTOMATIC 已提交
82 83


84
def apply_checkpoint(p, x, xs):
D
DepFA 已提交
85
    info = modules.sd_models.get_closet_checkpoint_match(x)
M
Milly 已提交
86 87
    if info is None:
        raise RuntimeError(f"Unknown checkpoint: {x}")
W
w-e-w 已提交
88
    p.override_settings['sd_model_checkpoint'] = info.name
89 90


M
Milly 已提交
91 92 93 94 95 96
def confirm_checkpoints(p, xs):
    for x in xs:
        if modules.sd_models.get_closet_checkpoint_match(x) is None:
            raise RuntimeError(f"Unknown checkpoint: {x}")


A
AUTOMATIC 已提交
97
def apply_clip_skip(p, x, xs):
98
    opts.data["CLIP_stop_at_last_layers"] = x
A
AUTOMATIC 已提交
99 100


101 102 103 104 105 106 107 108
def apply_upscale_latent_space(p, x, xs):
    if x.lower().strip() != '0':
        opts.data["use_scale_latent_for_hires_fix"] = True
    else:
        opts.data["use_scale_latent_for_hires_fix"] = False


def find_vae(name: str):
109 110 111 112
    if name.lower() in ['auto', 'automatic']:
        return modules.sd_vae.unspecified
    if name.lower() == 'none':
        return None
113
    else:
114 115 116 117
        choices = [x for x in sorted(modules.sd_vae.vae_dict, key=lambda x: len(x)) if name.lower().strip() in x.lower()]
        if len(choices) == 0:
            print(f"No VAE found for {name}; using automatic")
            return modules.sd_vae.unspecified
118
        else:
119
            return modules.sd_vae.vae_dict[choices[0]]
120 121 122


def apply_vae(p, x, xs):
123
    modules.sd_vae.reload_vae_weights(shared.sd_model, vae_file=find_vae(x))
124 125 126


def apply_styles(p: StableDiffusionProcessingTxt2Img, x: str, _):
127
    p.styles.extend(x.split(','))
128 129


S
space-nuko 已提交
130 131 132 133
def apply_uni_pc_order(p, x, xs):
    opts.data["uni_pc_order"] = min(x, p.steps - 1)


134 135 136 137 138 139 140 141 142 143 144 145 146 147
def apply_face_restore(p, opt, x):
    opt = opt.lower()
    if opt == 'codeformer':
        is_active = True
        p.face_restoration_model = 'CodeFormer'
    elif opt == 'gfpgan':
        is_active = True
        p.face_restoration_model = 'GFPGAN'
    else:
        is_active = opt in ('true', 'yes', 'y', '1')

    p.restore_faces = is_active


W
w-e-w 已提交
148
def apply_override(field, boolean: bool = False):
W
w-e-w 已提交
149
    def fun(p, x, xs):
W
w-e-w 已提交
150
        if boolean:
W
w-e-w 已提交
151
            x = True if x.lower() == "true" else False
W
w-e-w 已提交
152 153 154
        p.override_settings[field] = x
    return fun

W
w-e-w 已提交
155

W
w-e-w 已提交
156 157 158 159
def boolean_choice(reverse: bool = False):
    def choice():
        return ["False", "True"] if reverse else ["True", "False"]
    return choice
W
w-e-w 已提交
160 161


A
scripts  
AUTOMATIC 已提交
162
def format_value_add_label(p, opt, x):
163 164 165
    if type(x) == float:
        x = round(x, 8)

A
scripts  
AUTOMATIC 已提交
166 167 168 169
    return f"{opt.label}: {x}"


def format_value(p, opt, x):
170 171
    if type(x) == float:
        x = round(x, 8)
A
scripts  
AUTOMATIC 已提交
172 173
    return x

A
AUTOMATIC 已提交
174 175 176 177 178

def format_value_join_list(p, opt, x):
    return ", ".join(x)


179 180 181
def do_nothing(p, x, xs):
    pass

A
AUTOMATIC 已提交
182

183 184 185
def format_nothing(p, opt, x):
    return ""

186 187
def format_remove_path(p, opt, x):
    return os.path.basename(x)
A
scripts  
AUTOMATIC 已提交
188

A
AUTOMATIC 已提交
189 190 191 192
def str_permutations(x):
    """dummy function for specifying it in AxisOption's type when you want to get a list of permutations"""
    return x

193 194 195 196 197 198 199 200 201 202 203 204 205

class AxisOption:
    def __init__(self, label, type, apply, format_value=format_value_add_label, confirm=None, cost=0.0, choices=None):
        self.label = label
        self.type = type
        self.apply = apply
        self.format_value = format_value
        self.confirm = confirm
        self.cost = cost
        self.choices = choices


class AxisOptionImg2Img(AxisOption):
206 207 208 209 210
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.is_img2img = True

class AxisOptionTxt2Img(AxisOption):
211 212 213
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.is_img2img = False
A
scripts  
AUTOMATIC 已提交
214 215 216


axis_options = [
217 218 219 220 221
    AxisOption("Nothing", str, do_nothing, format_value=format_nothing),
    AxisOption("Seed", int, apply_field("seed")),
    AxisOption("Var. seed", int, apply_field("subseed")),
    AxisOption("Var. strength", float, apply_field("subseed_strength")),
    AxisOption("Steps", int, apply_field("steps")),
222
    AxisOptionTxt2Img("Hires steps", int, apply_field("hr_second_pass_steps")),
223
    AxisOption("CFG Scale", float, apply_field("cfg_scale")),
K
Kyle 已提交
224
    AxisOptionImg2Img("Image CFG Scale", float, apply_field("image_cfg_scale")),
225 226
    AxisOption("Prompt S/R", str, apply_prompt, format_value=format_value),
    AxisOption("Prompt order", str_permutations, apply_order, format_value=format_value_join_list),
227 228
    AxisOptionTxt2Img("Sampler", str, apply_sampler, format_value=format_value, confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers]),
    AxisOptionImg2Img("Sampler", str, apply_sampler, format_value=format_value, confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers_for_img2img]),
229
    AxisOption("Checkpoint name", str, apply_checkpoint, format_value=format_remove_path, confirm=confirm_checkpoints, cost=1.0, choices=lambda: sorted(sd_models.checkpoints_list, key=str.casefold)),
D
devdn 已提交
230
    AxisOption("Negative Guidance minimum sigma", float, apply_field("s_min_uncond")),
231 232 233 234
    AxisOption("Sigma Churn", float, apply_field("s_churn")),
    AxisOption("Sigma min", float, apply_field("s_tmin")),
    AxisOption("Sigma max", float, apply_field("s_tmax")),
    AxisOption("Sigma noise", float, apply_field("s_noise")),
235 236 237 238
    AxisOption("Schedule type", str, apply_override("k_sched_type"), choices=lambda: list(sd_samplers_kdiffusion.k_diffusion_scheduler)),
    AxisOption("Schedule min sigma", float, apply_override("sigma_min")),
    AxisOption("Schedule max sigma", float, apply_override("sigma_max")),
    AxisOption("Schedule rho", float, apply_override("rho")),
239 240 241
    AxisOption("Eta", float, apply_field("eta")),
    AxisOption("Clip skip", int, apply_clip_skip),
    AxisOption("Denoising", float, apply_field("denoising_strength")),
242 243
    AxisOptionTxt2Img("Hires upscaler", str, apply_field("hr_upscaler"), choices=lambda: [*shared.latent_upscale_modes, *[x.name for x in shared.sd_upscalers]]),
    AxisOptionImg2Img("Cond. Image Mask Weight", float, apply_field("inpainting_mask_weight")),
W
Weiming Dong 已提交
244
    AxisOption("VAE", str, apply_vae, cost=0.7, choices=lambda: ['None'] + list(sd_vae.vae_dict)),
245
    AxisOption("Styles", str, apply_styles, choices=lambda: list(shared.prompt_styles.styles)),
S
space-nuko 已提交
246
    AxisOption("UniPC Order", int, apply_uni_pc_order, cost=0.5),
247
    AxisOption("Face restore", str, apply_face_restore, format_value=format_value),
W
w-e-w 已提交
248 249
    AxisOption("Token merging ratio", float, apply_override('token_merging_ratio')),
    AxisOption("Token merging ratio high-res", float, apply_override('token_merging_ratio_hr')),
W
w-e-w 已提交
250
    AxisOption("Always discard next-to-last sigma", str, apply_override('always_discard_next_to_last_sigma', boolean=True), choices=boolean_choice(reverse=True)),
A
scripts  
AUTOMATIC 已提交
251 252 253
]


254
def draw_xyz_grid(p, xs, ys, zs, x_labels, y_labels, z_labels, cell, draw_legend, include_lone_images, include_sub_grids, first_axes_processed, second_axes_processed, margin_size):
255
    hor_texts = [[images.GridAnnotation(x)] for x in x_labels]
256
    ver_texts = [[images.GridAnnotation(y)] for y in y_labels]
E
EllangoK 已提交
257
    title_texts = [[images.GridAnnotation(z)] for z in z_labels]
A
scripts  
AUTOMATIC 已提交
258

259
    list_size = (len(xs) * len(ys) * len(zs))
G
Greg Fuller 已提交
260 261

    processed_result = None
A
scripts  
AUTOMATIC 已提交
262

263
    state.job_count = list_size * p.n_iter
A
AUTOMATIC 已提交
264

E
EllangoK 已提交
265
    def process_cell(x, y, z, ix, iy, iz):
266
        nonlocal processed_result
267

E
EllangoK 已提交
268
        def index(ix, iy, iz):
269
            return ix + iy * len(xs) + iz * len(xs) * len(ys)
270

271
        state.job = f"{index(ix, iy, iz) + 1} out of {list_size}"
E
EllangoK 已提交
272

273
        processed: Processed = cell(x, y, z, ix, iy, iz)
274

275 276 277 278 279 280 281
        if processed_result is None:
            # Use our first processed result object as a template container to hold our full results
            processed_result = copy(processed)
            processed_result.images = [None] * list_size
            processed_result.all_prompts = [None] * list_size
            processed_result.all_seeds = [None] * list_size
            processed_result.infotexts = [None] * list_size
D
DejitaruJin 已提交
282
            processed_result.index_of_first_image = 1
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299

        idx = index(ix, iy, iz)
        if processed.images:
            # Non-empty list indicates some degree of success.
            processed_result.images[idx] = processed.images[0]
            processed_result.all_prompts[idx] = processed.prompt
            processed_result.all_seeds[idx] = processed.seed
            processed_result.infotexts[idx] = processed.infotexts[0]
        else:
            cell_mode = "P"
            cell_size = (processed_result.width, processed_result.height)
            if processed_result.images[0] is not None:
                cell_mode = processed_result.images[0].mode
                #This corrects size in case of batches:
                cell_size = processed_result.images[0].size
            processed_result.images[idx] = Image.new(cell_mode, cell_size)

300

301
    if first_axes_processed == 'x':
A
scripts  
AUTOMATIC 已提交
302
        for ix, x in enumerate(xs):
303 304 305 306 307 308 309 310 311
            if second_axes_processed == 'y':
                for iy, y in enumerate(ys):
                    for iz, z in enumerate(zs):
                        process_cell(x, y, z, ix, iy, iz)
            else:
                for iz, z in enumerate(zs):
                    for iy, y in enumerate(ys):
                        process_cell(x, y, z, ix, iy, iz)
    elif first_axes_processed == 'y':
312
        for iy, y in enumerate(ys):
313 314 315 316 317
            if second_axes_processed == 'x':
                for ix, x in enumerate(xs):
                    for iz, z in enumerate(zs):
                        process_cell(x, y, z, ix, iy, iz)
            else:
E
EllangoK 已提交
318
                for iz, z in enumerate(zs):
319 320 321 322 323 324 325 326 327 328 329 330
                    for ix, x in enumerate(xs):
                        process_cell(x, y, z, ix, iy, iz)
    elif first_axes_processed == 'z':
        for iz, z in enumerate(zs):
            if second_axes_processed == 'x':
                for ix, x in enumerate(xs):
                    for iy, y in enumerate(ys):
                        process_cell(x, y, z, ix, iy, iz)
            else:
                for iy, y in enumerate(ys):
                    for ix, x in enumerate(xs):
                        process_cell(x, y, z, ix, iy, iz)
G
Greg Fuller 已提交
331 332

    if not processed_result:
333 334 335 336
        # Should never happen, I've only seen it on one of four open tabs and it needed to refresh.
        print("Unexpected error: Processing could not begin, you may need to refresh the tab or restart the service.")
        return Processed(p, [])
    elif not any(processed_result.images):
E
EllangoK 已提交
337
        print("Unexpected error: draw_xyz_grid failed to return even a single processed image")
338
        return Processed(p, [])
A
scripts  
AUTOMATIC 已提交
339

340
    z_count = len(zs)
A
AUTOMATIC 已提交
341

342 343
    for i in range(z_count):
        start_index = (i * len(xs) * len(ys)) + i
E
EllangoK 已提交
344
        end_index = start_index + len(xs) * len(ys)
345
        grid = images.image_grid(processed_result.images[start_index:end_index], rows=len(ys))
E
EllangoK 已提交
346
        if draw_legend:
347 348 349 350 351 352 353 354
            grid = images.draw_grid_annotations(grid, processed_result.images[start_index].size[0], processed_result.images[start_index].size[1], hor_texts, ver_texts, margin_size)
        processed_result.images.insert(i, grid)
        processed_result.all_prompts.insert(i, processed_result.all_prompts[start_index])
        processed_result.all_seeds.insert(i, processed_result.all_seeds[start_index])
        processed_result.infotexts.insert(i, processed_result.infotexts[start_index])

    sub_grid_size = processed_result.images[0].size
    z_grid = images.image_grid(processed_result.images[:z_count], rows=1)
355 356
    if draw_legend:
        z_grid = images.draw_grid_annotations(z_grid, sub_grid_size[0], sub_grid_size[1], title_texts, [[images.GridAnnotation()]])
357
    processed_result.images.insert(0, z_grid)
D
DejitaruJin 已提交
358
    #TODO: Deeper aspects of the program rely on grid info being misaligned between metadata arrays, which is not ideal.
D
DejitaruJin 已提交
359 360
    #processed_result.all_prompts.insert(0, processed_result.all_prompts[0])
    #processed_result.all_seeds.insert(0, processed_result.all_seeds[0])
361
    processed_result.infotexts.insert(0, processed_result.infotexts[0])
A
scripts  
AUTOMATIC 已提交
362

363
    return processed_result
A
scripts  
AUTOMATIC 已提交
364 365


366 367 368
class SharedSettingsStackHelper(object):
    def __enter__(self):
        self.CLIP_stop_at_last_layers = opts.CLIP_stop_at_last_layers
369
        self.vae = opts.sd_vae
S
space-nuko 已提交
370
        self.uni_pc_order = opts.uni_pc_order
W
Weiming Dong 已提交
371

372
    def __exit__(self, exc_type, exc_value, tb):
373
        opts.data["sd_vae"] = self.vae
S
space-nuko 已提交
374
        opts.data["uni_pc_order"] = self.uni_pc_order
375 376
        modules.sd_models.reload_model_weights()
        modules.sd_vae.reload_vae_weights()
A
scripts  
AUTOMATIC 已提交
377

378
        opts.data["CLIP_stop_at_last_layers"] = self.CLIP_stop_at_last_layers
A
scripts  
AUTOMATIC 已提交
379 380


A
AUTOMATIC 已提交
381
re_range = re.compile(r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\(([+-]\d+)\s*\))?\s*")
382
re_range_float = re.compile(r"\s*([+-]?\s*\d+(?:.\d*)?)\s*-\s*([+-]?\s*\d+(?:.\d*)?)(?:\s*\(([+-]\d+(?:.\d*)?)\s*\))?\s*")
A
AUTOMATIC 已提交
383

D
DepFA 已提交
384 385 386
re_range_count = re.compile(r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\[(\d+)\s*\])?\s*")
re_range_count_float = re.compile(r"\s*([+-]?\s*\d+(?:.\d*)?)\s*-\s*([+-]?\s*\d+(?:.\d*)?)(?:\s*\[(\d+(?:.\d*)?)\s*\])?\s*")

387

A
scripts  
AUTOMATIC 已提交
388 389
class Script(scripts.Script):
    def title(self):
E
EllangoK 已提交
390
        return "X/Y/Z plot"
A
scripts  
AUTOMATIC 已提交
391 392

    def ui(self, is_img2img):
393
        self.current_axis_options = [x for x in axis_options if type(x) == AxisOption or x.is_img2img == is_img2img]
A
scripts  
AUTOMATIC 已提交
394 395

        with gr.Row():
S
space-nuko 已提交
396 397
            with gr.Column(scale=19):
                with gr.Row():
398
                    x_type = gr.Dropdown(label="X type", choices=[x.label for x in self.current_axis_options], value=self.current_axis_options[1].label, type="index", elem_id=self.elem_id("x_type"))
S
space-nuko 已提交
399
                    x_values = gr.Textbox(label="X values", lines=1, elem_id=self.elem_id("x_values"))
P
pangbo13 已提交
400
                    x_values_dropdown = gr.Dropdown(label="X values",visible=False,multiselect=True,interactive=True)
E
EllangoK 已提交
401
                    fill_x_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_x_tool_button", visible=False)
S
space-nuko 已提交
402 403

                with gr.Row():
404
                    y_type = gr.Dropdown(label="Y type", choices=[x.label for x in self.current_axis_options], value=self.current_axis_options[0].label, type="index", elem_id=self.elem_id("y_type"))
S
space-nuko 已提交
405
                    y_values = gr.Textbox(label="Y values", lines=1, elem_id=self.elem_id("y_values"))
P
pangbo13 已提交
406
                    y_values_dropdown = gr.Dropdown(label="Y values",visible=False,multiselect=True,interactive=True)
407
                    fill_y_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_y_tool_button", visible=False)
E
EllangoK 已提交
408 409 410 411

                with gr.Row():
                    z_type = gr.Dropdown(label="Z type", choices=[x.label for x in self.current_axis_options], value=self.current_axis_options[0].label, type="index", elem_id=self.elem_id("z_type"))
                    z_values = gr.Textbox(label="Z values", lines=1, elem_id=self.elem_id("z_values"))
P
pangbo13 已提交
412
                    z_values_dropdown = gr.Dropdown(label="Z values",visible=False,multiselect=True,interactive=True)
E
EllangoK 已提交
413
                    fill_z_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_z_tool_button", visible=False)
414

E
EllangoK 已提交
415
        with gr.Row(variant="compact", elem_id="axis_options"):
416 417 418 419 420 421 422
            with gr.Column():
                draw_legend = gr.Checkbox(label='Draw legend', value=True, elem_id=self.elem_id("draw_legend"))
                no_fixed_seeds = gr.Checkbox(label='Keep -1 for seeds', value=False, elem_id=self.elem_id("no_fixed_seeds"))
            with gr.Column():
                include_lone_images = gr.Checkbox(label='Include Sub Images', value=False, elem_id=self.elem_id("include_lone_images"))
                include_sub_grids = gr.Checkbox(label='Include Sub Grids', value=False, elem_id=self.elem_id("include_sub_grids"))
            with gr.Column():
423
                margin_size = gr.Slider(label="Grid margins (px)", minimum=0, maximum=500, value=0, step=2, elem_id=self.elem_id("margin_size"))
W
Weiming Dong 已提交
424

425
        with gr.Row(variant="compact", elem_id="swap_axes"):
E
EllangoK 已提交
426 427 428
            swap_xy_axes_button = gr.Button(value="Swap X/Y axes", elem_id="xy_grid_swap_axes_button")
            swap_yz_axes_button = gr.Button(value="Swap Y/Z axes", elem_id="yz_grid_swap_axes_button")
            swap_xz_axes_button = gr.Button(value="Swap X/Z axes", elem_id="xz_grid_swap_axes_button")
A
scripts  
AUTOMATIC 已提交
429

P
pangbo13 已提交
430 431
        def swap_axes(axis1_type, axis1_values, axis1_values_dropdown, axis2_type, axis2_values, axis2_values_dropdown):
            return self.current_axis_options[axis2_type].label, axis2_values, axis2_values_dropdown, self.current_axis_options[axis1_type].label, axis1_values, axis1_values_dropdown
S
space-nuko 已提交
432

P
pangbo13 已提交
433
        xy_swap_args = [x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown]
E
EllangoK 已提交
434
        swap_xy_axes_button.click(swap_axes, inputs=xy_swap_args, outputs=xy_swap_args)
P
pangbo13 已提交
435
        yz_swap_args = [y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown]
E
EllangoK 已提交
436
        swap_yz_axes_button.click(swap_axes, inputs=yz_swap_args, outputs=yz_swap_args)
P
pangbo13 已提交
437
        xz_swap_args = [x_type, x_values, x_values_dropdown, z_type, z_values, z_values_dropdown]
E
EllangoK 已提交
438
        swap_xz_axes_button.click(swap_axes, inputs=xz_swap_args, outputs=xz_swap_args)
S
space-nuko 已提交
439

440
        def fill(x_type):
441
            axis = self.current_axis_options[x_type]
P
pangbo13 已提交
442
            return axis.choices() if axis.choices else gr.update()
443

P
pangbo13 已提交
444 445 446
        fill_x_button.click(fn=fill, inputs=[x_type], outputs=[x_values_dropdown])
        fill_y_button.click(fn=fill, inputs=[y_type], outputs=[y_values_dropdown])
        fill_z_button.click(fn=fill, inputs=[z_type], outputs=[z_values_dropdown])
447

P
pangbo13 已提交
448 449
        def select_axis(axis_type,axis_values_dropdown):
            choices = self.current_axis_options[axis_type].choices
P
pangbo13 已提交
450
            has_choices = choices is not None
P
pangbo13 已提交
451 452 453 454 455 456 457 458 459 460 461 462 463
            current_values = axis_values_dropdown
            if has_choices:
                choices = choices()
                if isinstance(current_values,str):
                    current_values = current_values.split(",")
                current_values = list(filter(lambda x: x in choices, current_values))
            return gr.Button.update(visible=has_choices),gr.Textbox.update(visible=not has_choices),gr.update(choices=choices if has_choices else None,visible=has_choices,value=current_values)

        x_type.change(fn=select_axis, inputs=[x_type,x_values_dropdown], outputs=[fill_x_button,x_values,x_values_dropdown])
        y_type.change(fn=select_axis, inputs=[y_type,y_values_dropdown], outputs=[fill_y_button,y_values,y_values_dropdown])
        z_type.change(fn=select_axis, inputs=[z_type,z_values_dropdown], outputs=[fill_z_button,z_values,z_values_dropdown])

        def get_dropdown_update_from_params(axis,params):
464
            val_key = f"{axis} Values"
P
pangbo13 已提交
465 466 467
            vals = params.get(val_key,"")
            valslist = [x.strip() for x in chain.from_iterable(csv.reader(StringIO(vals))) if x]
            return gr.update(value = valslist)
468

E
EllangoK 已提交
469 470 471
        self.infotext_fields = (
            (x_type, "X Type"),
            (x_values, "X Values"),
P
pangbo13 已提交
472
            (x_values_dropdown, lambda params:get_dropdown_update_from_params("X",params)),
E
EllangoK 已提交
473 474
            (y_type, "Y Type"),
            (y_values, "Y Values"),
P
pangbo13 已提交
475
            (y_values_dropdown, lambda params:get_dropdown_update_from_params("Y",params)),
E
EllangoK 已提交
476 477
            (z_type, "Z Type"),
            (z_values, "Z Values"),
P
pangbo13 已提交
478
            (z_values_dropdown, lambda params:get_dropdown_update_from_params("Z",params)),
E
EllangoK 已提交
479 480
        )

P
pangbo13 已提交
481
        return [x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown, draw_legend, include_lone_images, include_sub_grids, no_fixed_seeds, margin_size]
482

P
pangbo13 已提交
483
    def run(self, p, x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown, draw_legend, include_lone_images, include_sub_grids, no_fixed_seeds, margin_size):
484 485 486
        if not no_fixed_seeds:
            modules.processing.fix_seed(p)

487 488
        if not opts.return_grid:
            p.batch_size = 1
A
scripts  
AUTOMATIC 已提交
489

P
pangbo13 已提交
490
        def process_axis(opt, vals, vals_dropdown):
491 492 493
            if opt.label == 'Nothing':
                return [0]

P
pangbo13 已提交
494 495 496 497
            if opt.choices is not None:
                valslist = vals_dropdown
            else:
                valslist = [x.strip() for x in chain.from_iterable(csv.reader(StringIO(vals))) if x]
A
scripts  
AUTOMATIC 已提交
498 499 500 501 502

            if opt.type == int:
                valslist_ext = []

                for val in valslist:
A
AUTOMATIC 已提交
503
                    m = re_range.fullmatch(val)
D
DepFA 已提交
504
                    mc = re_range_count.fullmatch(val)
A
AUTOMATIC 已提交
505 506 507 508 509
                    if m is not None:
                        start = int(m.group(1))
                        end = int(m.group(2))+1
                        step = int(m.group(3)) if m.group(3) is not None else 1

A
scripts  
AUTOMATIC 已提交
510
                        valslist_ext += list(range(start, end, step))
D
DepFA 已提交
511 512 513 514
                    elif mc is not None:
                        start = int(mc.group(1))
                        end   = int(mc.group(2))
                        num   = int(mc.group(3)) if mc.group(3) is not None else 1
W
Weiming Dong 已提交
515

516
                        valslist_ext += [int(x) for x in np.linspace(start=start, stop=end, num=num).tolist()]
A
scripts  
AUTOMATIC 已提交
517 518 519 520
                    else:
                        valslist_ext.append(val)

                valslist = valslist_ext
521 522 523 524 525
            elif opt.type == float:
                valslist_ext = []

                for val in valslist:
                    m = re_range_float.fullmatch(val)
D
DepFA 已提交
526
                    mc = re_range_count_float.fullmatch(val)
527 528 529 530 531 532
                    if m is not None:
                        start = float(m.group(1))
                        end = float(m.group(2))
                        step = float(m.group(3)) if m.group(3) is not None else 1

                        valslist_ext += np.arange(start, end + step, step).tolist()
D
DepFA 已提交
533 534 535 536
                    elif mc is not None:
                        start = float(mc.group(1))
                        end   = float(mc.group(2))
                        num   = int(mc.group(3)) if mc.group(3) is not None else 1
W
Weiming Dong 已提交
537

538
                        valslist_ext += np.linspace(start=start, stop=end, num=num).tolist()
539 540 541 542
                    else:
                        valslist_ext.append(val)

                valslist = valslist_ext
A
AUTOMATIC 已提交
543 544
            elif opt.type == str_permutations:
                valslist = list(permutations(valslist))
A
scripts  
AUTOMATIC 已提交
545 546 547

            valslist = [opt.type(x) for x in valslist]

548
            # Confirm options are valid before starting
M
Milly 已提交
549 550
            if opt.confirm:
                opt.confirm(p, valslist)
A
scripts  
AUTOMATIC 已提交
551 552 553

            return valslist

554
        x_opt = self.current_axis_options[x_type]
P
pangbo13 已提交
555 556
        if x_opt.choices is not None:
            x_values = ",".join(x_values_dropdown)
P
pangbo13 已提交
557
        xs = process_axis(x_opt, x_values, x_values_dropdown)
A
scripts  
AUTOMATIC 已提交
558

559
        y_opt = self.current_axis_options[y_type]
P
pangbo13 已提交
560 561
        if y_opt.choices is not None:
            y_values = ",".join(y_values_dropdown)
P
pangbo13 已提交
562
        ys = process_axis(y_opt, y_values, y_values_dropdown)
A
scripts  
AUTOMATIC 已提交
563

E
EllangoK 已提交
564
        z_opt = self.current_axis_options[z_type]
P
pangbo13 已提交
565 566
        if z_opt.choices is not None:
            z_values = ",".join(z_values_dropdown)
P
pangbo13 已提交
567
        zs = process_axis(z_opt, z_values, z_values_dropdown)
E
EllangoK 已提交
568

569
        # this could be moved to common code, but unlikely to be ever triggered anywhere else
V
Vladimir Mandic 已提交
570
        Image.MAX_IMAGE_PIXELS = None # disable check in Pillow and rely on check below to allow large custom image sizes
571
        grid_mp = round(len(xs) * len(ys) * len(zs) * p.width * p.height / 1000000)
V
Vladimir Mandic 已提交
572
        assert grid_mp < opts.img_max_size_mp, f'Error: Resulting grid would be too large ({grid_mp} MPixels) (max configured size is {opts.img_max_size_mp} MPixels)'
573

574
        def fix_axis_seeds(axis_opt, axis_list):
575
            if axis_opt.label in ['Seed', 'Var. seed']:
576 577 578 579
                return [int(random.randrange(4294967294)) if val is None or val == '' or val == -1 else val for val in axis_list]
            else:
                return axis_list

580
        if not no_fixed_seeds:
581 582
            xs = fix_axis_seeds(x_opt, xs)
            ys = fix_axis_seeds(y_opt, ys)
E
EllangoK 已提交
583
            zs = fix_axis_seeds(z_opt, zs)
584 585

        if x_opt.label == 'Steps':
E
EllangoK 已提交
586
            total_steps = sum(xs) * len(ys) * len(zs)
587
        elif y_opt.label == 'Steps':
E
EllangoK 已提交
588 589 590
            total_steps = sum(ys) * len(xs) * len(zs)
        elif z_opt.label == 'Steps':
            total_steps = sum(zs) * len(xs) * len(ys)
591
        else:
E
EllangoK 已提交
592
            total_steps = p.steps * len(xs) * len(ys) * len(zs)
593

594
        if isinstance(p, StableDiffusionProcessingTxt2Img) and p.enable_hr:
595
            if x_opt.label == "Hires steps":
E
EllangoK 已提交
596
                total_steps += sum(xs) * len(ys) * len(zs)
597
            elif y_opt.label == "Hires steps":
E
EllangoK 已提交
598 599 600
                total_steps += sum(ys) * len(xs) * len(zs)
            elif z_opt.label == "Hires steps":
                total_steps += sum(zs) * len(xs) * len(ys)
601
            elif p.hr_second_pass_steps:
E
EllangoK 已提交
602
                total_steps += p.hr_second_pass_steps * len(xs) * len(ys) * len(zs)
603 604 605 606
            else:
                total_steps *= 2

        total_steps *= p.n_iter
607

608 609
        image_cell_count = p.n_iter * p.batch_size
        cell_console_text = f"; {image_cell_count} images per cell" if image_cell_count > 1 else ""
E
EllangoK 已提交
610
        plural_s = 's' if len(zs) > 1 else ''
611
        print(f"X/Y/Z plot will create {len(xs) * len(ys) * len(zs) * image_cell_count} images on {len(zs)} {len(xs)}x{len(ys)} grid{plural_s}{cell_console_text}. (Total steps to process: {total_steps})")
612
        shared.total_tqdm.updateTotal(total_steps)
613

614 615 616 617
        state.xyz_plot_x = AxisInfo(x_opt, xs)
        state.xyz_plot_y = AxisInfo(y_opt, ys)
        state.xyz_plot_z = AxisInfo(z_opt, zs)

618 619 620
        # If one of the axes is very slow to change between (like SD model
        # checkpoint), then make sure it is in the outer iteration of the nested
        # `for` loop.
621
        first_axes_processed = 'z'
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
        second_axes_processed = 'y'
        if x_opt.cost > y_opt.cost and x_opt.cost > z_opt.cost:
            first_axes_processed = 'x'
            if y_opt.cost > z_opt.cost:
                second_axes_processed = 'y'
            else:
                second_axes_processed = 'z'
        elif y_opt.cost > x_opt.cost and y_opt.cost > z_opt.cost:
            first_axes_processed = 'y'
            if x_opt.cost > z_opt.cost:
                second_axes_processed = 'x'
            else:
                second_axes_processed = 'z'
        elif z_opt.cost > x_opt.cost and z_opt.cost > y_opt.cost:
            first_axes_processed = 'z'
            if x_opt.cost > y_opt.cost:
                second_axes_processed = 'x'
            else:
                second_axes_processed = 'y'
641

642 643 644
        grid_infotext = [None] * (1 + len(zs))

        def cell(x, y, z, ix, iy, iz):
645 646 647
            if shared.state.interrupted:
                return Processed(p, [], p.seed, "")

A
scripts  
AUTOMATIC 已提交
648
            pc = copy(p)
649
            pc.styles = pc.styles[:]
A
scripts  
AUTOMATIC 已提交
650 651
            x_opt.apply(pc, x, xs)
            y_opt.apply(pc, y, ys)
E
EllangoK 已提交
652
            z_opt.apply(pc, z, zs)
A
scripts  
AUTOMATIC 已提交
653

654 655 656 657 658 659
            try:
                res = process_images(pc)
            except Exception as e:
                errors.display(e, "generating image for xyz plot")

                res = Processed(p, [], p.seed, "")
660

661 662 663
            # Sets subgrid infotexts
            subgrid_index = 1 + iz
            if grid_infotext[subgrid_index] is None and ix == 0 and iy == 0:
664
                pc.extra_generation_params = copy(pc.extra_generation_params)
E
EllangoK 已提交
665
                pc.extra_generation_params['Script'] = self.title()
666 667 668 669 670 671 672 673 674 675 676 677

                if x_opt.label != 'Nothing':
                    pc.extra_generation_params["X Type"] = x_opt.label
                    pc.extra_generation_params["X Values"] = x_values
                    if x_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds:
                        pc.extra_generation_params["Fixed X Values"] = ", ".join([str(x) for x in xs])

                if y_opt.label != 'Nothing':
                    pc.extra_generation_params["Y Type"] = y_opt.label
                    pc.extra_generation_params["Y Values"] = y_values
                    if y_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds:
                        pc.extra_generation_params["Fixed Y Values"] = ", ".join([str(y) for y in ys])
A
scripts  
AUTOMATIC 已提交
678

679 680 681 682 683 684
                grid_infotext[subgrid_index] = processing.create_infotext(pc, pc.all_prompts, pc.all_seeds, pc.all_subseeds)

            # Sets main grid infotext
            if grid_infotext[0] is None and ix == 0 and iy == 0 and iz == 0:
                pc.extra_generation_params = copy(pc.extra_generation_params)

E
EllangoK 已提交
685 686 687 688 689 690
                if z_opt.label != 'Nothing':
                    pc.extra_generation_params["Z Type"] = z_opt.label
                    pc.extra_generation_params["Z Values"] = z_values
                    if z_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds:
                        pc.extra_generation_params["Fixed Z Values"] = ", ".join([str(z) for z in zs])

691
                grid_infotext[0] = processing.create_infotext(pc, pc.all_prompts, pc.all_seeds, pc.all_subseeds)
692

693
            return res
694

695
        with SharedSettingsStackHelper():
696
            processed = draw_xyz_grid(
697 698 699
                p,
                xs=xs,
                ys=ys,
E
EllangoK 已提交
700
                zs=zs,
701 702
                x_labels=[x_opt.format_value(p, x_opt, x) for x in xs],
                y_labels=[y_opt.format_value(p, y_opt, y) for y in ys],
703
                z_labels=[z_opt.format_value(p, z_opt, z) for z in zs],
704 705
                cell=cell,
                draw_legend=draw_legend,
706
                include_lone_images=include_lone_images,
707
                include_sub_grids=include_sub_grids,
708
                first_axes_processed=first_axes_processed,
709 710
                second_axes_processed=second_axes_processed,
                margin_size=margin_size
711
            )
A
scripts  
AUTOMATIC 已提交
712

D
DejitaruJin 已提交
713 714 715 716
        if not processed.images:
            # It broke, no further handling needed.
            return processed

717 718
        z_count = len(zs)

719 720 721
        # Set the grid infotexts to the real ones with extra_generation_params (1 main grid + z_count sub-grids)
        processed.infotexts[:1+z_count] = grid_infotext[:1+z_count]

722 723 724
        if not include_lone_images:
            # Don't need sub-images anymore, drop from list:
            processed.images = processed.images[:z_count+1]
725

A
AUTOMATIC 已提交
726
        if opts.grid_save:
727 728 729
            # Auto-save main and sub-grids:
            grid_count = z_count + 1 if z_count > 1 else 1
            for g in range(grid_count):
D
DejitaruJin 已提交
730 731 732
                #TODO: See previous comment about intentional data misalignment.
                adj_g = g-1 if g > 0 else g
                images.save_image(processed.images[g], p.outpath_grids, "xyz_grid", info=processed.infotexts[g], extension=opts.grid_format, prompt=processed.all_prompts[adj_g], seed=processed.all_seeds[adj_g], grid=True, p=processed)
733 734 735

        if not include_sub_grids:
            # Done with sub-grids, drop all related information:
A
AUTOMATIC 已提交
736
            for _ in range(z_count):
737 738 739 740
                del processed.images[1]
                del processed.all_prompts[1]
                del processed.all_seeds[1]
                del processed.infotexts[1]
741

A
scripts  
AUTOMATIC 已提交
742
        return processed