Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
automatic1111
GitHub Repository: automatic1111/stable-diffusion-webui
Path: blob/master/scripts/xyz_grid.py
3055 views
1
from collections import namedtuple
2
from copy import copy
3
from itertools import permutations, chain
4
import random
5
import csv
6
import os.path
7
from io import StringIO
8
from PIL import Image
9
import numpy as np
10
11
import modules.scripts as scripts
12
import gradio as gr
13
14
from modules import images, sd_samplers, processing, sd_models, sd_vae, sd_schedulers, errors
15
from modules.processing import process_images, Processed, StableDiffusionProcessingTxt2Img
16
from modules.shared import opts, state
17
import modules.shared as shared
18
import modules.sd_samplers
19
import modules.sd_models
20
import modules.sd_vae
21
import re
22
23
from modules.ui_components import ToolButton
24
25
fill_values_symbol = "\U0001f4d2" # 📒
26
27
AxisInfo = namedtuple('AxisInfo', ['axis', 'values'])
28
29
30
def apply_field(field):
31
def fun(p, x, xs):
32
setattr(p, field, x)
33
34
return fun
35
36
37
def apply_prompt(p, x, xs):
38
if xs[0] not in p.prompt and xs[0] not in p.negative_prompt:
39
raise RuntimeError(f"Prompt S/R did not find {xs[0]} in prompt or negative prompt.")
40
41
p.prompt = p.prompt.replace(xs[0], x)
42
p.negative_prompt = p.negative_prompt.replace(xs[0], x)
43
44
45
def apply_order(p, x, xs):
46
token_order = []
47
48
# Initially grab the tokens from the prompt, so they can be replaced in order of earliest seen
49
for token in x:
50
token_order.append((p.prompt.find(token), token))
51
52
token_order.sort(key=lambda t: t[0])
53
54
prompt_parts = []
55
56
# Split the prompt up, taking out the tokens
57
for _, token in token_order:
58
n = p.prompt.find(token)
59
prompt_parts.append(p.prompt[0:n])
60
p.prompt = p.prompt[n + len(token):]
61
62
# Rebuild the prompt with the tokens in the order we want
63
prompt_tmp = ""
64
for idx, part in enumerate(prompt_parts):
65
prompt_tmp += part
66
prompt_tmp += x[idx]
67
p.prompt = prompt_tmp + p.prompt
68
69
70
def confirm_samplers(p, xs):
71
for x in xs:
72
if x.lower() not in sd_samplers.samplers_map:
73
raise RuntimeError(f"Unknown sampler: {x}")
74
75
76
def apply_checkpoint(p, x, xs):
77
info = modules.sd_models.get_closet_checkpoint_match(x)
78
if info is None:
79
raise RuntimeError(f"Unknown checkpoint: {x}")
80
p.override_settings['sd_model_checkpoint'] = info.name
81
82
83
def confirm_checkpoints(p, xs):
84
for x in xs:
85
if modules.sd_models.get_closet_checkpoint_match(x) is None:
86
raise RuntimeError(f"Unknown checkpoint: {x}")
87
88
89
def confirm_checkpoints_or_none(p, xs):
90
for x in xs:
91
if x in (None, "", "None", "none"):
92
continue
93
94
if modules.sd_models.get_closet_checkpoint_match(x) is None:
95
raise RuntimeError(f"Unknown checkpoint: {x}")
96
97
98
def confirm_range(min_val, max_val, axis_label):
99
"""Generates a AxisOption.confirm() function that checks all values are within the specified range."""
100
101
def confirm_range_fun(p, xs):
102
for x in xs:
103
if not (max_val >= x >= min_val):
104
raise ValueError(f'{axis_label} value "{x}" out of range [{min_val}, {max_val}]')
105
106
return confirm_range_fun
107
108
109
def apply_size(p, x: str, xs) -> None:
110
try:
111
width, _, height = x.partition('x')
112
width = int(width.strip())
113
height = int(height.strip())
114
p.width = width
115
p.height = height
116
except ValueError:
117
print(f"Invalid size in XYZ plot: {x}")
118
119
120
def find_vae(name: str):
121
if (name := name.strip().lower()) in ('auto', 'automatic'):
122
return 'Automatic'
123
elif name == 'none':
124
return 'None'
125
return next((k for k in modules.sd_vae.vae_dict if k.lower() == name), print(f'No VAE found for {name}; using Automatic') or 'Automatic')
126
127
128
def apply_vae(p, x, xs):
129
p.override_settings['sd_vae'] = find_vae(x)
130
131
132
def apply_styles(p: StableDiffusionProcessingTxt2Img, x: str, _):
133
p.styles.extend(x.split(','))
134
135
136
def apply_uni_pc_order(p, x, xs):
137
p.override_settings['uni_pc_order'] = min(x, p.steps - 1)
138
139
140
def apply_face_restore(p, opt, x):
141
opt = opt.lower()
142
if opt == 'codeformer':
143
is_active = True
144
p.face_restoration_model = 'CodeFormer'
145
elif opt == 'gfpgan':
146
is_active = True
147
p.face_restoration_model = 'GFPGAN'
148
else:
149
is_active = opt in ('true', 'yes', 'y', '1')
150
151
p.restore_faces = is_active
152
153
154
def apply_override(field, boolean: bool = False):
155
def fun(p, x, xs):
156
if boolean:
157
x = True if x.lower() == "true" else False
158
p.override_settings[field] = x
159
160
return fun
161
162
163
def boolean_choice(reverse: bool = False):
164
def choice():
165
return ["False", "True"] if reverse else ["True", "False"]
166
167
return choice
168
169
170
def format_value_add_label(p, opt, x):
171
if type(x) == float:
172
x = round(x, 8)
173
174
return f"{opt.label}: {x}"
175
176
177
def format_value(p, opt, x):
178
if type(x) == float:
179
x = round(x, 8)
180
return x
181
182
183
def format_value_join_list(p, opt, x):
184
return ", ".join(x)
185
186
187
def do_nothing(p, x, xs):
188
pass
189
190
191
def format_nothing(p, opt, x):
192
return ""
193
194
195
def format_remove_path(p, opt, x):
196
return os.path.basename(x)
197
198
199
def str_permutations(x):
200
"""dummy function for specifying it in AxisOption's type when you want to get a list of permutations"""
201
return x
202
203
204
def list_to_csv_string(data_list):
205
with StringIO() as o:
206
csv.writer(o).writerow(data_list)
207
return o.getvalue().strip()
208
209
210
def csv_string_to_list_strip(data_str):
211
return list(map(str.strip, chain.from_iterable(csv.reader(StringIO(data_str), skipinitialspace=True))))
212
213
214
class AxisOption:
215
def __init__(self, label, type, apply, format_value=format_value_add_label, confirm=None, cost=0.0, choices=None, prepare=None):
216
self.label = label
217
self.type = type
218
self.apply = apply
219
self.format_value = format_value
220
self.confirm = confirm
221
self.cost = cost
222
self.prepare = prepare
223
self.choices = choices
224
225
226
class AxisOptionImg2Img(AxisOption):
227
def __init__(self, *args, **kwargs):
228
super().__init__(*args, **kwargs)
229
self.is_img2img = True
230
231
232
class AxisOptionTxt2Img(AxisOption):
233
def __init__(self, *args, **kwargs):
234
super().__init__(*args, **kwargs)
235
self.is_img2img = False
236
237
238
axis_options = [
239
AxisOption("Nothing", str, do_nothing, format_value=format_nothing),
240
AxisOption("Seed", int, apply_field("seed")),
241
AxisOption("Var. seed", int, apply_field("subseed")),
242
AxisOption("Var. strength", float, apply_field("subseed_strength")),
243
AxisOption("Steps", int, apply_field("steps")),
244
AxisOptionTxt2Img("Hires steps", int, apply_field("hr_second_pass_steps")),
245
AxisOption("CFG Scale", float, apply_field("cfg_scale")),
246
AxisOptionImg2Img("Image CFG Scale", float, apply_field("image_cfg_scale")),
247
AxisOption("Prompt S/R", str, apply_prompt, format_value=format_value),
248
AxisOption("Prompt order", str_permutations, apply_order, format_value=format_value_join_list),
249
AxisOptionTxt2Img("Sampler", str, apply_field("sampler_name"), format_value=format_value, confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers if x.name not in opts.hide_samplers]),
250
AxisOptionTxt2Img("Hires sampler", str, apply_field("hr_sampler_name"), confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers_for_img2img if x.name not in opts.hide_samplers]),
251
AxisOptionImg2Img("Sampler", str, apply_field("sampler_name"), format_value=format_value, confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers_for_img2img if x.name not in opts.hide_samplers]),
252
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)),
253
AxisOption("Negative Guidance minimum sigma", float, apply_field("s_min_uncond")),
254
AxisOption("Sigma Churn", float, apply_field("s_churn")),
255
AxisOption("Sigma min", float, apply_field("s_tmin")),
256
AxisOption("Sigma max", float, apply_field("s_tmax")),
257
AxisOption("Sigma noise", float, apply_field("s_noise")),
258
AxisOption("Schedule type", str, apply_field("scheduler"), choices=lambda: [x.label for x in sd_schedulers.schedulers]),
259
AxisOption("Schedule min sigma", float, apply_override("sigma_min")),
260
AxisOption("Schedule max sigma", float, apply_override("sigma_max")),
261
AxisOption("Schedule rho", float, apply_override("rho")),
262
AxisOption("Beta schedule alpha", float, apply_override("beta_dist_alpha")),
263
AxisOption("Beta schedule beta", float, apply_override("beta_dist_beta")),
264
AxisOption("Eta", float, apply_field("eta")),
265
AxisOption("Clip skip", int, apply_override('CLIP_stop_at_last_layers')),
266
AxisOption("Denoising", float, apply_field("denoising_strength")),
267
AxisOption("Initial noise multiplier", float, apply_field("initial_noise_multiplier")),
268
AxisOption("Extra noise", float, apply_override("img2img_extra_noise")),
269
AxisOptionTxt2Img("Hires upscaler", str, apply_field("hr_upscaler"), choices=lambda: [*shared.latent_upscale_modes, *[x.name for x in shared.sd_upscalers]]),
270
AxisOptionImg2Img("Cond. Image Mask Weight", float, apply_field("inpainting_mask_weight")),
271
AxisOption("VAE", str, apply_vae, cost=0.7, choices=lambda: ['Automatic', 'None'] + list(sd_vae.vae_dict)),
272
AxisOption("Styles", str, apply_styles, choices=lambda: list(shared.prompt_styles.styles)),
273
AxisOption("UniPC Order", int, apply_uni_pc_order, cost=0.5),
274
AxisOption("Face restore", str, apply_face_restore, format_value=format_value),
275
AxisOption("Token merging ratio", float, apply_override('token_merging_ratio')),
276
AxisOption("Token merging ratio high-res", float, apply_override('token_merging_ratio_hr')),
277
AxisOption("Always discard next-to-last sigma", str, apply_override('always_discard_next_to_last_sigma', boolean=True), choices=boolean_choice(reverse=True)),
278
AxisOption("SGM noise multiplier", str, apply_override('sgm_noise_multiplier', boolean=True), choices=boolean_choice(reverse=True)),
279
AxisOption("Refiner checkpoint", str, apply_field('refiner_checkpoint'), format_value=format_remove_path, confirm=confirm_checkpoints_or_none, cost=1.0, choices=lambda: ['None'] + sorted(sd_models.checkpoints_list, key=str.casefold)),
280
AxisOption("Refiner switch at", float, apply_field('refiner_switch_at')),
281
AxisOption("RNG source", str, apply_override("randn_source"), choices=lambda: ["GPU", "CPU", "NV"]),
282
AxisOption("FP8 mode", str, apply_override("fp8_storage"), cost=0.9, choices=lambda: ["Disable", "Enable for SDXL", "Enable"]),
283
AxisOption("Size", str, apply_size),
284
]
285
286
287
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):
288
hor_texts = [[images.GridAnnotation(x)] for x in x_labels]
289
ver_texts = [[images.GridAnnotation(y)] for y in y_labels]
290
title_texts = [[images.GridAnnotation(z)] for z in z_labels]
291
292
list_size = (len(xs) * len(ys) * len(zs))
293
294
processed_result = None
295
296
state.job_count = list_size * p.n_iter
297
298
def process_cell(x, y, z, ix, iy, iz):
299
nonlocal processed_result
300
301
def index(ix, iy, iz):
302
return ix + iy * len(xs) + iz * len(xs) * len(ys)
303
304
state.job = f"{index(ix, iy, iz) + 1} out of {list_size}"
305
306
processed: Processed = cell(x, y, z, ix, iy, iz)
307
308
if processed_result is None:
309
# Use our first processed result object as a template container to hold our full results
310
processed_result = copy(processed)
311
processed_result.images = [None] * list_size
312
processed_result.all_prompts = [None] * list_size
313
processed_result.all_seeds = [None] * list_size
314
processed_result.infotexts = [None] * list_size
315
processed_result.index_of_first_image = 1
316
317
idx = index(ix, iy, iz)
318
if processed.images:
319
# Non-empty list indicates some degree of success.
320
processed_result.images[idx] = processed.images[0]
321
processed_result.all_prompts[idx] = processed.prompt
322
processed_result.all_seeds[idx] = processed.seed
323
processed_result.infotexts[idx] = processed.infotexts[0]
324
else:
325
cell_mode = "P"
326
cell_size = (processed_result.width, processed_result.height)
327
if processed_result.images[0] is not None:
328
cell_mode = processed_result.images[0].mode
329
# This corrects size in case of batches:
330
cell_size = processed_result.images[0].size
331
processed_result.images[idx] = Image.new(cell_mode, cell_size)
332
333
if first_axes_processed == 'x':
334
for ix, x in enumerate(xs):
335
if second_axes_processed == 'y':
336
for iy, y in enumerate(ys):
337
for iz, z in enumerate(zs):
338
process_cell(x, y, z, ix, iy, iz)
339
else:
340
for iz, z in enumerate(zs):
341
for iy, y in enumerate(ys):
342
process_cell(x, y, z, ix, iy, iz)
343
elif first_axes_processed == 'y':
344
for iy, y in enumerate(ys):
345
if second_axes_processed == 'x':
346
for ix, x in enumerate(xs):
347
for iz, z in enumerate(zs):
348
process_cell(x, y, z, ix, iy, iz)
349
else:
350
for iz, z in enumerate(zs):
351
for ix, x in enumerate(xs):
352
process_cell(x, y, z, ix, iy, iz)
353
elif first_axes_processed == 'z':
354
for iz, z in enumerate(zs):
355
if second_axes_processed == 'x':
356
for ix, x in enumerate(xs):
357
for iy, y in enumerate(ys):
358
process_cell(x, y, z, ix, iy, iz)
359
else:
360
for iy, y in enumerate(ys):
361
for ix, x in enumerate(xs):
362
process_cell(x, y, z, ix, iy, iz)
363
364
if not processed_result:
365
# Should never happen, I've only seen it on one of four open tabs and it needed to refresh.
366
print("Unexpected error: Processing could not begin, you may need to refresh the tab or restart the service.")
367
return Processed(p, [])
368
elif not any(processed_result.images):
369
print("Unexpected error: draw_xyz_grid failed to return even a single processed image")
370
return Processed(p, [])
371
372
z_count = len(zs)
373
374
for i in range(z_count):
375
start_index = (i * len(xs) * len(ys)) + i
376
end_index = start_index + len(xs) * len(ys)
377
grid = images.image_grid(processed_result.images[start_index:end_index], rows=len(ys))
378
if draw_legend:
379
grid_max_w, grid_max_h = map(max, zip(*(img.size for img in processed_result.images[start_index:end_index])))
380
grid = images.draw_grid_annotations(grid, grid_max_w, grid_max_h, hor_texts, ver_texts, margin_size)
381
processed_result.images.insert(i, grid)
382
processed_result.all_prompts.insert(i, processed_result.all_prompts[start_index])
383
processed_result.all_seeds.insert(i, processed_result.all_seeds[start_index])
384
processed_result.infotexts.insert(i, processed_result.infotexts[start_index])
385
386
z_grid = images.image_grid(processed_result.images[:z_count], rows=1)
387
z_sub_grid_max_w, z_sub_grid_max_h = map(max, zip(*(img.size for img in processed_result.images[:z_count])))
388
if draw_legend:
389
z_grid = images.draw_grid_annotations(z_grid, z_sub_grid_max_w, z_sub_grid_max_h, title_texts, [[images.GridAnnotation()]])
390
processed_result.images.insert(0, z_grid)
391
# TODO: Deeper aspects of the program rely on grid info being misaligned between metadata arrays, which is not ideal.
392
# processed_result.all_prompts.insert(0, processed_result.all_prompts[0])
393
# processed_result.all_seeds.insert(0, processed_result.all_seeds[0])
394
processed_result.infotexts.insert(0, processed_result.infotexts[0])
395
396
return processed_result
397
398
399
class SharedSettingsStackHelper(object):
400
def __enter__(self):
401
pass
402
403
def __exit__(self, exc_type, exc_value, tb):
404
modules.sd_models.reload_model_weights()
405
modules.sd_vae.reload_vae_weights()
406
407
408
re_range = re.compile(r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\(([+-]\d+)\s*\))?\s*")
409
re_range_float = re.compile(r"\s*([+-]?\s*\d+(?:.\d*)?)\s*-\s*([+-]?\s*\d+(?:.\d*)?)(?:\s*\(([+-]\d+(?:.\d*)?)\s*\))?\s*")
410
411
re_range_count = re.compile(r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\[(\d+)\s*])?\s*")
412
re_range_count_float = re.compile(r"\s*([+-]?\s*\d+(?:.\d*)?)\s*-\s*([+-]?\s*\d+(?:.\d*)?)(?:\s*\[(\d+(?:.\d*)?)\s*])?\s*")
413
414
415
class Script(scripts.Script):
416
def title(self):
417
return "X/Y/Z plot"
418
419
def ui(self, is_img2img):
420
self.current_axis_options = [x for x in axis_options if type(x) == AxisOption or x.is_img2img == is_img2img]
421
422
with gr.Row():
423
with gr.Column(scale=19):
424
with gr.Row():
425
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"))
426
x_values = gr.Textbox(label="X values", lines=1, elem_id=self.elem_id("x_values"))
427
x_values_dropdown = gr.Dropdown(label="X values", visible=False, multiselect=True, interactive=True)
428
fill_x_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_x_tool_button", visible=False)
429
430
with gr.Row():
431
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"))
432
y_values = gr.Textbox(label="Y values", lines=1, elem_id=self.elem_id("y_values"))
433
y_values_dropdown = gr.Dropdown(label="Y values", visible=False, multiselect=True, interactive=True)
434
fill_y_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_y_tool_button", visible=False)
435
436
with gr.Row():
437
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"))
438
z_values = gr.Textbox(label="Z values", lines=1, elem_id=self.elem_id("z_values"))
439
z_values_dropdown = gr.Dropdown(label="Z values", visible=False, multiselect=True, interactive=True)
440
fill_z_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_z_tool_button", visible=False)
441
442
with gr.Row(variant="compact", elem_id="axis_options"):
443
with gr.Column():
444
draw_legend = gr.Checkbox(label='Draw legend', value=True, elem_id=self.elem_id("draw_legend"))
445
no_fixed_seeds = gr.Checkbox(label='Keep -1 for seeds', value=False, elem_id=self.elem_id("no_fixed_seeds"))
446
with gr.Row():
447
vary_seeds_x = gr.Checkbox(label='Vary seeds for X', value=False, min_width=80, elem_id=self.elem_id("vary_seeds_x"), tooltip="Use different seeds for images along X axis.")
448
vary_seeds_y = gr.Checkbox(label='Vary seeds for Y', value=False, min_width=80, elem_id=self.elem_id("vary_seeds_y"), tooltip="Use different seeds for images along Y axis.")
449
vary_seeds_z = gr.Checkbox(label='Vary seeds for Z', value=False, min_width=80, elem_id=self.elem_id("vary_seeds_z"), tooltip="Use different seeds for images along Z axis.")
450
with gr.Column():
451
include_lone_images = gr.Checkbox(label='Include Sub Images', value=False, elem_id=self.elem_id("include_lone_images"))
452
include_sub_grids = gr.Checkbox(label='Include Sub Grids', value=False, elem_id=self.elem_id("include_sub_grids"))
453
csv_mode = gr.Checkbox(label='Use text inputs instead of dropdowns', value=False, elem_id=self.elem_id("csv_mode"))
454
with gr.Column():
455
margin_size = gr.Slider(label="Grid margins (px)", minimum=0, maximum=500, value=0, step=2, elem_id=self.elem_id("margin_size"))
456
457
with gr.Row(variant="compact", elem_id="swap_axes"):
458
swap_xy_axes_button = gr.Button(value="Swap X/Y axes", elem_id="xy_grid_swap_axes_button")
459
swap_yz_axes_button = gr.Button(value="Swap Y/Z axes", elem_id="yz_grid_swap_axes_button")
460
swap_xz_axes_button = gr.Button(value="Swap X/Z axes", elem_id="xz_grid_swap_axes_button")
461
462
def swap_axes(axis1_type, axis1_values, axis1_values_dropdown, axis2_type, axis2_values, axis2_values_dropdown):
463
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
464
465
xy_swap_args = [x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown]
466
swap_xy_axes_button.click(swap_axes, inputs=xy_swap_args, outputs=xy_swap_args)
467
yz_swap_args = [y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown]
468
swap_yz_axes_button.click(swap_axes, inputs=yz_swap_args, outputs=yz_swap_args)
469
xz_swap_args = [x_type, x_values, x_values_dropdown, z_type, z_values, z_values_dropdown]
470
swap_xz_axes_button.click(swap_axes, inputs=xz_swap_args, outputs=xz_swap_args)
471
472
def fill(axis_type, csv_mode):
473
axis = self.current_axis_options[axis_type]
474
if axis.choices:
475
if csv_mode:
476
return list_to_csv_string(axis.choices()), gr.update()
477
else:
478
return gr.update(), axis.choices()
479
else:
480
return gr.update(), gr.update()
481
482
fill_x_button.click(fn=fill, inputs=[x_type, csv_mode], outputs=[x_values, x_values_dropdown])
483
fill_y_button.click(fn=fill, inputs=[y_type, csv_mode], outputs=[y_values, y_values_dropdown])
484
fill_z_button.click(fn=fill, inputs=[z_type, csv_mode], outputs=[z_values, z_values_dropdown])
485
486
def select_axis(axis_type, axis_values, axis_values_dropdown, csv_mode):
487
axis_type = axis_type or 0 # if axle type is None set to 0
488
489
choices = self.current_axis_options[axis_type].choices
490
has_choices = choices is not None
491
492
if has_choices:
493
choices = choices()
494
if csv_mode:
495
if axis_values_dropdown:
496
axis_values = list_to_csv_string(list(filter(lambda x: x in choices, axis_values_dropdown)))
497
axis_values_dropdown = []
498
else:
499
if axis_values:
500
axis_values_dropdown = list(filter(lambda x: x in choices, csv_string_to_list_strip(axis_values)))
501
axis_values = ""
502
503
return (gr.Button.update(visible=has_choices), gr.Textbox.update(visible=not has_choices or csv_mode, value=axis_values),
504
gr.update(choices=choices if has_choices else None, visible=has_choices and not csv_mode, value=axis_values_dropdown))
505
506
x_type.change(fn=select_axis, inputs=[x_type, x_values, x_values_dropdown, csv_mode], outputs=[fill_x_button, x_values, x_values_dropdown])
507
y_type.change(fn=select_axis, inputs=[y_type, y_values, y_values_dropdown, csv_mode], outputs=[fill_y_button, y_values, y_values_dropdown])
508
z_type.change(fn=select_axis, inputs=[z_type, z_values, z_values_dropdown, csv_mode], outputs=[fill_z_button, z_values, z_values_dropdown])
509
510
def change_choice_mode(csv_mode, x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown):
511
_fill_x_button, _x_values, _x_values_dropdown = select_axis(x_type, x_values, x_values_dropdown, csv_mode)
512
_fill_y_button, _y_values, _y_values_dropdown = select_axis(y_type, y_values, y_values_dropdown, csv_mode)
513
_fill_z_button, _z_values, _z_values_dropdown = select_axis(z_type, z_values, z_values_dropdown, csv_mode)
514
return _fill_x_button, _x_values, _x_values_dropdown, _fill_y_button, _y_values, _y_values_dropdown, _fill_z_button, _z_values, _z_values_dropdown
515
516
csv_mode.change(fn=change_choice_mode, inputs=[csv_mode, x_type, x_values, x_values_dropdown, y_type, y_values, y_values_dropdown, z_type, z_values, z_values_dropdown], outputs=[fill_x_button, x_values, x_values_dropdown, fill_y_button, y_values, y_values_dropdown, fill_z_button, z_values, z_values_dropdown])
517
518
def get_dropdown_update_from_params(axis, params):
519
val_key = f"{axis} Values"
520
vals = params.get(val_key, "")
521
valslist = csv_string_to_list_strip(vals)
522
return gr.update(value=valslist)
523
524
self.infotext_fields = (
525
(x_type, "X Type"),
526
(x_values, "X Values"),
527
(x_values_dropdown, lambda params: get_dropdown_update_from_params("X", params)),
528
(y_type, "Y Type"),
529
(y_values, "Y Values"),
530
(y_values_dropdown, lambda params: get_dropdown_update_from_params("Y", params)),
531
(z_type, "Z Type"),
532
(z_values, "Z Values"),
533
(z_values_dropdown, lambda params: get_dropdown_update_from_params("Z", params)),
534
)
535
536
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, vary_seeds_x, vary_seeds_y, vary_seeds_z, margin_size, csv_mode]
537
538
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, vary_seeds_x, vary_seeds_y, vary_seeds_z, margin_size, csv_mode):
539
x_type, y_type, z_type = x_type or 0, y_type or 0, z_type or 0 # if axle type is None set to 0
540
541
if not no_fixed_seeds:
542
modules.processing.fix_seed(p)
543
544
if not opts.return_grid:
545
p.batch_size = 1
546
547
def process_axis(opt, vals, vals_dropdown):
548
if opt.label == 'Nothing':
549
return [0]
550
551
if opt.choices is not None and not csv_mode:
552
valslist = vals_dropdown
553
elif opt.prepare is not None:
554
valslist = opt.prepare(vals)
555
else:
556
valslist = csv_string_to_list_strip(vals)
557
558
if opt.type == int:
559
valslist_ext = []
560
561
for val in valslist:
562
if val.strip() == '':
563
continue
564
m = re_range.fullmatch(val)
565
mc = re_range_count.fullmatch(val)
566
if m is not None:
567
start = int(m.group(1))
568
end = int(m.group(2)) + 1
569
step = int(m.group(3)) if m.group(3) is not None else 1
570
571
valslist_ext += list(range(start, end, step))
572
elif mc is not None:
573
start = int(mc.group(1))
574
end = int(mc.group(2))
575
num = int(mc.group(3)) if mc.group(3) is not None else 1
576
577
valslist_ext += [int(x) for x in np.linspace(start=start, stop=end, num=num).tolist()]
578
else:
579
valslist_ext.append(val)
580
581
valslist = valslist_ext
582
elif opt.type == float:
583
valslist_ext = []
584
585
for val in valslist:
586
if val.strip() == '':
587
continue
588
m = re_range_float.fullmatch(val)
589
mc = re_range_count_float.fullmatch(val)
590
if m is not None:
591
start = float(m.group(1))
592
end = float(m.group(2))
593
step = float(m.group(3)) if m.group(3) is not None else 1
594
595
valslist_ext += np.arange(start, end + step, step).tolist()
596
elif mc is not None:
597
start = float(mc.group(1))
598
end = float(mc.group(2))
599
num = int(mc.group(3)) if mc.group(3) is not None else 1
600
601
valslist_ext += np.linspace(start=start, stop=end, num=num).tolist()
602
else:
603
valslist_ext.append(val)
604
605
valslist = valslist_ext
606
elif opt.type == str_permutations:
607
valslist = list(permutations(valslist))
608
609
valslist = [opt.type(x) for x in valslist]
610
611
# Confirm options are valid before starting
612
if opt.confirm:
613
opt.confirm(p, valslist)
614
615
return valslist
616
617
x_opt = self.current_axis_options[x_type]
618
if x_opt.choices is not None and not csv_mode:
619
x_values = list_to_csv_string(x_values_dropdown)
620
xs = process_axis(x_opt, x_values, x_values_dropdown)
621
622
y_opt = self.current_axis_options[y_type]
623
if y_opt.choices is not None and not csv_mode:
624
y_values = list_to_csv_string(y_values_dropdown)
625
ys = process_axis(y_opt, y_values, y_values_dropdown)
626
627
z_opt = self.current_axis_options[z_type]
628
if z_opt.choices is not None and not csv_mode:
629
z_values = list_to_csv_string(z_values_dropdown)
630
zs = process_axis(z_opt, z_values, z_values_dropdown)
631
632
# this could be moved to common code, but unlikely to be ever triggered anywhere else
633
Image.MAX_IMAGE_PIXELS = None # disable check in Pillow and rely on check below to allow large custom image sizes
634
grid_mp = round(len(xs) * len(ys) * len(zs) * p.width * p.height / 1000000)
635
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)'
636
637
def fix_axis_seeds(axis_opt, axis_list):
638
if axis_opt.label in ['Seed', 'Var. seed']:
639
return [int(random.randrange(4294967294)) if val is None or val == '' or val == -1 else val for val in axis_list]
640
else:
641
return axis_list
642
643
if not no_fixed_seeds:
644
xs = fix_axis_seeds(x_opt, xs)
645
ys = fix_axis_seeds(y_opt, ys)
646
zs = fix_axis_seeds(z_opt, zs)
647
648
if x_opt.label == 'Steps':
649
total_steps = sum(xs) * len(ys) * len(zs)
650
elif y_opt.label == 'Steps':
651
total_steps = sum(ys) * len(xs) * len(zs)
652
elif z_opt.label == 'Steps':
653
total_steps = sum(zs) * len(xs) * len(ys)
654
else:
655
total_steps = p.steps * len(xs) * len(ys) * len(zs)
656
657
if isinstance(p, StableDiffusionProcessingTxt2Img) and p.enable_hr:
658
if x_opt.label == "Hires steps":
659
total_steps += sum(xs) * len(ys) * len(zs)
660
elif y_opt.label == "Hires steps":
661
total_steps += sum(ys) * len(xs) * len(zs)
662
elif z_opt.label == "Hires steps":
663
total_steps += sum(zs) * len(xs) * len(ys)
664
elif p.hr_second_pass_steps:
665
total_steps += p.hr_second_pass_steps * len(xs) * len(ys) * len(zs)
666
else:
667
total_steps *= 2
668
669
total_steps *= p.n_iter
670
671
image_cell_count = p.n_iter * p.batch_size
672
cell_console_text = f"; {image_cell_count} images per cell" if image_cell_count > 1 else ""
673
plural_s = 's' if len(zs) > 1 else ''
674
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})")
675
shared.total_tqdm.updateTotal(total_steps)
676
677
state.xyz_plot_x = AxisInfo(x_opt, xs)
678
state.xyz_plot_y = AxisInfo(y_opt, ys)
679
state.xyz_plot_z = AxisInfo(z_opt, zs)
680
681
# If one of the axes is very slow to change between (like SD model
682
# checkpoint), then make sure it is in the outer iteration of the nested
683
# `for` loop.
684
first_axes_processed = 'z'
685
second_axes_processed = 'y'
686
if x_opt.cost > y_opt.cost and x_opt.cost > z_opt.cost:
687
first_axes_processed = 'x'
688
if y_opt.cost > z_opt.cost:
689
second_axes_processed = 'y'
690
else:
691
second_axes_processed = 'z'
692
elif y_opt.cost > x_opt.cost and y_opt.cost > z_opt.cost:
693
first_axes_processed = 'y'
694
if x_opt.cost > z_opt.cost:
695
second_axes_processed = 'x'
696
else:
697
second_axes_processed = 'z'
698
elif z_opt.cost > x_opt.cost and z_opt.cost > y_opt.cost:
699
first_axes_processed = 'z'
700
if x_opt.cost > y_opt.cost:
701
second_axes_processed = 'x'
702
else:
703
second_axes_processed = 'y'
704
705
grid_infotext = [None] * (1 + len(zs))
706
707
def cell(x, y, z, ix, iy, iz):
708
if shared.state.interrupted or state.stopping_generation:
709
return Processed(p, [], p.seed, "")
710
711
pc = copy(p)
712
pc.styles = pc.styles[:]
713
x_opt.apply(pc, x, xs)
714
y_opt.apply(pc, y, ys)
715
z_opt.apply(pc, z, zs)
716
717
xdim = len(xs) if vary_seeds_x else 1
718
ydim = len(ys) if vary_seeds_y else 1
719
720
if vary_seeds_x:
721
pc.seed += ix
722
if vary_seeds_y:
723
pc.seed += iy * xdim
724
if vary_seeds_z:
725
pc.seed += iz * xdim * ydim
726
727
try:
728
res = process_images(pc)
729
except Exception as e:
730
errors.display(e, "generating image for xyz plot")
731
732
res = Processed(p, [], p.seed, "")
733
734
# Sets subgrid infotexts
735
subgrid_index = 1 + iz
736
if grid_infotext[subgrid_index] is None and ix == 0 and iy == 0:
737
pc.extra_generation_params = copy(pc.extra_generation_params)
738
pc.extra_generation_params['Script'] = self.title()
739
740
if x_opt.label != 'Nothing':
741
pc.extra_generation_params["X Type"] = x_opt.label
742
pc.extra_generation_params["X Values"] = x_values
743
if x_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds:
744
pc.extra_generation_params["Fixed X Values"] = ", ".join([str(x) for x in xs])
745
746
if y_opt.label != 'Nothing':
747
pc.extra_generation_params["Y Type"] = y_opt.label
748
pc.extra_generation_params["Y Values"] = y_values
749
if y_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds:
750
pc.extra_generation_params["Fixed Y Values"] = ", ".join([str(y) for y in ys])
751
752
grid_infotext[subgrid_index] = processing.create_infotext(pc, pc.all_prompts, pc.all_seeds, pc.all_subseeds)
753
754
# Sets main grid infotext
755
if grid_infotext[0] is None and ix == 0 and iy == 0 and iz == 0:
756
pc.extra_generation_params = copy(pc.extra_generation_params)
757
758
if z_opt.label != 'Nothing':
759
pc.extra_generation_params["Z Type"] = z_opt.label
760
pc.extra_generation_params["Z Values"] = z_values
761
if z_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds:
762
pc.extra_generation_params["Fixed Z Values"] = ", ".join([str(z) for z in zs])
763
764
grid_infotext[0] = processing.create_infotext(pc, pc.all_prompts, pc.all_seeds, pc.all_subseeds)
765
766
return res
767
768
with SharedSettingsStackHelper():
769
processed = draw_xyz_grid(
770
p,
771
xs=xs,
772
ys=ys,
773
zs=zs,
774
x_labels=[x_opt.format_value(p, x_opt, x) for x in xs],
775
y_labels=[y_opt.format_value(p, y_opt, y) for y in ys],
776
z_labels=[z_opt.format_value(p, z_opt, z) for z in zs],
777
cell=cell,
778
draw_legend=draw_legend,
779
include_lone_images=include_lone_images,
780
include_sub_grids=include_sub_grids,
781
first_axes_processed=first_axes_processed,
782
second_axes_processed=second_axes_processed,
783
margin_size=margin_size
784
)
785
786
if not processed.images:
787
# It broke, no further handling needed.
788
return processed
789
790
z_count = len(zs)
791
792
# Set the grid infotexts to the real ones with extra_generation_params (1 main grid + z_count sub-grids)
793
processed.infotexts[:1 + z_count] = grid_infotext[:1 + z_count]
794
795
if not include_lone_images:
796
# Don't need sub-images anymore, drop from list:
797
processed.images = processed.images[:z_count + 1]
798
799
if opts.grid_save:
800
# Auto-save main and sub-grids:
801
grid_count = z_count + 1 if z_count > 1 else 1
802
for g in range(grid_count):
803
# TODO: See previous comment about intentional data misalignment.
804
adj_g = g - 1 if g > 0 else g
805
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)
806
if not include_sub_grids: # if not include_sub_grids then skip saving after the first grid
807
break
808
809
if not include_sub_grids:
810
# Done with sub-grids, drop all related information:
811
for _ in range(z_count):
812
del processed.images[1]
813
del processed.all_prompts[1]
814
del processed.all_seeds[1]
815
del processed.infotexts[1]
816
817
return processed
818
819