scripts
Browse files- scripts/__pycache__/custom_code.cpython-38.pyc +0 -0
- scripts/__pycache__/img2imgalt.cpython-38.pyc +0 -0
- scripts/__pycache__/loopback.cpython-38.pyc +0 -0
- scripts/__pycache__/outpainting_mk_2.cpython-38.pyc +0 -0
- scripts/__pycache__/poor_mans_outpainting.cpython-38.pyc +0 -0
- scripts/__pycache__/postprocessing_codeformer.cpython-38.pyc +0 -0
- scripts/__pycache__/postprocessing_gfpgan.cpython-38.pyc +0 -0
- scripts/__pycache__/postprocessing_upscale.cpython-38.pyc +0 -0
- scripts/__pycache__/prompt_matrix.cpython-38.pyc +0 -0
- scripts/__pycache__/prompts_from_file.cpython-38.pyc +0 -0
- scripts/__pycache__/sd_upscale.cpython-38.pyc +0 -0
- scripts/__pycache__/xyz_grid.cpython-38.pyc +0 -0
- scripts/custom_code.py +41 -0
- scripts/img2imgalt.py +218 -0
- scripts/loopback.py +140 -0
- scripts/outpainting_mk_2.py +283 -0
- scripts/poor_mans_outpainting.py +146 -0
- scripts/postprocessing_codeformer.py +36 -0
- scripts/postprocessing_gfpgan.py +33 -0
- scripts/postprocessing_upscale.py +133 -0
- scripts/prompt_matrix.py +111 -0
- scripts/prompts_from_file.py +177 -0
- scripts/sd_upscale.py +101 -0
- scripts/xyz_grid.py +685 -0
scripts/__pycache__/custom_code.cpython-38.pyc
ADDED
|
Binary file (1.63 kB). View file
|
|
|
scripts/__pycache__/img2imgalt.cpython-38.pyc
ADDED
|
Binary file (6.45 kB). View file
|
|
|
scripts/__pycache__/loopback.cpython-38.pyc
ADDED
|
Binary file (3.55 kB). View file
|
|
|
scripts/__pycache__/outpainting_mk_2.cpython-38.pyc
ADDED
|
Binary file (8.63 kB). View file
|
|
|
scripts/__pycache__/poor_mans_outpainting.cpython-38.pyc
ADDED
|
Binary file (4.18 kB). View file
|
|
|
scripts/__pycache__/postprocessing_codeformer.cpython-38.pyc
ADDED
|
Binary file (1.6 kB). View file
|
|
|
scripts/__pycache__/postprocessing_gfpgan.cpython-38.pyc
ADDED
|
Binary file (1.37 kB). View file
|
|
|
scripts/__pycache__/postprocessing_upscale.cpython-38.pyc
ADDED
|
Binary file (5.92 kB). View file
|
|
|
scripts/__pycache__/prompt_matrix.cpython-38.pyc
ADDED
|
Binary file (4.29 kB). View file
|
|
|
scripts/__pycache__/prompts_from_file.cpython-38.pyc
ADDED
|
Binary file (5.01 kB). View file
|
|
|
scripts/__pycache__/sd_upscale.cpython-38.pyc
ADDED
|
Binary file (3.64 kB). View file
|
|
|
scripts/__pycache__/xyz_grid.cpython-38.pyc
ADDED
|
Binary file (22.9 kB). View file
|
|
|
scripts/custom_code.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import modules.scripts as scripts
|
| 2 |
+
import gradio as gr
|
| 3 |
+
|
| 4 |
+
from modules.processing import Processed
|
| 5 |
+
from modules.shared import opts, cmd_opts, state
|
| 6 |
+
|
| 7 |
+
class Script(scripts.Script):
|
| 8 |
+
|
| 9 |
+
def title(self):
|
| 10 |
+
return "Custom code"
|
| 11 |
+
|
| 12 |
+
def show(self, is_img2img):
|
| 13 |
+
return cmd_opts.allow_code
|
| 14 |
+
|
| 15 |
+
def ui(self, is_img2img):
|
| 16 |
+
code = gr.Textbox(label="Python code", lines=1, elem_id=self.elem_id("code"))
|
| 17 |
+
|
| 18 |
+
return [code]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def run(self, p, code):
|
| 22 |
+
assert cmd_opts.allow_code, '--allow-code option must be enabled'
|
| 23 |
+
|
| 24 |
+
display_result_data = [[], -1, ""]
|
| 25 |
+
|
| 26 |
+
def display(imgs, s=display_result_data[1], i=display_result_data[2]):
|
| 27 |
+
display_result_data[0] = imgs
|
| 28 |
+
display_result_data[1] = s
|
| 29 |
+
display_result_data[2] = i
|
| 30 |
+
|
| 31 |
+
from types import ModuleType
|
| 32 |
+
compiled = compile(code, '', 'exec')
|
| 33 |
+
module = ModuleType("testmodule")
|
| 34 |
+
module.__dict__.update(globals())
|
| 35 |
+
module.p = p
|
| 36 |
+
module.display = display
|
| 37 |
+
exec(compiled, module.__dict__)
|
| 38 |
+
|
| 39 |
+
return Processed(p, *display_result_data)
|
| 40 |
+
|
| 41 |
+
|
scripts/img2imgalt.py
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import namedtuple
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
from tqdm import trange
|
| 5 |
+
|
| 6 |
+
import modules.scripts as scripts
|
| 7 |
+
import gradio as gr
|
| 8 |
+
|
| 9 |
+
from modules import processing, shared, sd_samplers, sd_samplers_common
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import k_diffusion as K
|
| 13 |
+
|
| 14 |
+
def find_noise_for_image(p, cond, uncond, cfg_scale, steps):
|
| 15 |
+
x = p.init_latent
|
| 16 |
+
|
| 17 |
+
s_in = x.new_ones([x.shape[0]])
|
| 18 |
+
if shared.sd_model.parameterization == "v":
|
| 19 |
+
dnw = K.external.CompVisVDenoiser(shared.sd_model)
|
| 20 |
+
skip = 1
|
| 21 |
+
else:
|
| 22 |
+
dnw = K.external.CompVisDenoiser(shared.sd_model)
|
| 23 |
+
skip = 0
|
| 24 |
+
sigmas = dnw.get_sigmas(steps).flip(0)
|
| 25 |
+
|
| 26 |
+
shared.state.sampling_steps = steps
|
| 27 |
+
|
| 28 |
+
for i in trange(1, len(sigmas)):
|
| 29 |
+
shared.state.sampling_step += 1
|
| 30 |
+
|
| 31 |
+
x_in = torch.cat([x] * 2)
|
| 32 |
+
sigma_in = torch.cat([sigmas[i] * s_in] * 2)
|
| 33 |
+
cond_in = torch.cat([uncond, cond])
|
| 34 |
+
|
| 35 |
+
image_conditioning = torch.cat([p.image_conditioning] * 2)
|
| 36 |
+
cond_in = {"c_concat": [image_conditioning], "c_crossattn": [cond_in]}
|
| 37 |
+
|
| 38 |
+
c_out, c_in = [K.utils.append_dims(k, x_in.ndim) for k in dnw.get_scalings(sigma_in)[skip:]]
|
| 39 |
+
t = dnw.sigma_to_t(sigma_in)
|
| 40 |
+
|
| 41 |
+
eps = shared.sd_model.apply_model(x_in * c_in, t, cond=cond_in)
|
| 42 |
+
denoised_uncond, denoised_cond = (x_in + eps * c_out).chunk(2)
|
| 43 |
+
|
| 44 |
+
denoised = denoised_uncond + (denoised_cond - denoised_uncond) * cfg_scale
|
| 45 |
+
|
| 46 |
+
d = (x - denoised) / sigmas[i]
|
| 47 |
+
dt = sigmas[i] - sigmas[i - 1]
|
| 48 |
+
|
| 49 |
+
x = x + d * dt
|
| 50 |
+
|
| 51 |
+
sd_samplers_common.store_latent(x)
|
| 52 |
+
|
| 53 |
+
# This shouldn't be necessary, but solved some VRAM issues
|
| 54 |
+
del x_in, sigma_in, cond_in, c_out, c_in, t,
|
| 55 |
+
del eps, denoised_uncond, denoised_cond, denoised, d, dt
|
| 56 |
+
|
| 57 |
+
shared.state.nextjob()
|
| 58 |
+
|
| 59 |
+
return x / x.std()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
Cached = namedtuple("Cached", ["noise", "cfg_scale", "steps", "latent", "original_prompt", "original_negative_prompt", "sigma_adjustment"])
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# Based on changes suggested by briansemrau in https://github.com/AUTOMATIC1111/stable-diffusion-webui/issues/736
|
| 66 |
+
def find_noise_for_image_sigma_adjustment(p, cond, uncond, cfg_scale, steps):
|
| 67 |
+
x = p.init_latent
|
| 68 |
+
|
| 69 |
+
s_in = x.new_ones([x.shape[0]])
|
| 70 |
+
if shared.sd_model.parameterization == "v":
|
| 71 |
+
dnw = K.external.CompVisVDenoiser(shared.sd_model)
|
| 72 |
+
skip = 1
|
| 73 |
+
else:
|
| 74 |
+
dnw = K.external.CompVisDenoiser(shared.sd_model)
|
| 75 |
+
skip = 0
|
| 76 |
+
sigmas = dnw.get_sigmas(steps).flip(0)
|
| 77 |
+
|
| 78 |
+
shared.state.sampling_steps = steps
|
| 79 |
+
|
| 80 |
+
for i in trange(1, len(sigmas)):
|
| 81 |
+
shared.state.sampling_step += 1
|
| 82 |
+
|
| 83 |
+
x_in = torch.cat([x] * 2)
|
| 84 |
+
sigma_in = torch.cat([sigmas[i - 1] * s_in] * 2)
|
| 85 |
+
cond_in = torch.cat([uncond, cond])
|
| 86 |
+
|
| 87 |
+
image_conditioning = torch.cat([p.image_conditioning] * 2)
|
| 88 |
+
cond_in = {"c_concat": [image_conditioning], "c_crossattn": [cond_in]}
|
| 89 |
+
|
| 90 |
+
c_out, c_in = [K.utils.append_dims(k, x_in.ndim) for k in dnw.get_scalings(sigma_in)[skip:]]
|
| 91 |
+
|
| 92 |
+
if i == 1:
|
| 93 |
+
t = dnw.sigma_to_t(torch.cat([sigmas[i] * s_in] * 2))
|
| 94 |
+
else:
|
| 95 |
+
t = dnw.sigma_to_t(sigma_in)
|
| 96 |
+
|
| 97 |
+
eps = shared.sd_model.apply_model(x_in * c_in, t, cond=cond_in)
|
| 98 |
+
denoised_uncond, denoised_cond = (x_in + eps * c_out).chunk(2)
|
| 99 |
+
|
| 100 |
+
denoised = denoised_uncond + (denoised_cond - denoised_uncond) * cfg_scale
|
| 101 |
+
|
| 102 |
+
if i == 1:
|
| 103 |
+
d = (x - denoised) / (2 * sigmas[i])
|
| 104 |
+
else:
|
| 105 |
+
d = (x - denoised) / sigmas[i - 1]
|
| 106 |
+
|
| 107 |
+
dt = sigmas[i] - sigmas[i - 1]
|
| 108 |
+
x = x + d * dt
|
| 109 |
+
|
| 110 |
+
sd_samplers_common.store_latent(x)
|
| 111 |
+
|
| 112 |
+
# This shouldn't be necessary, but solved some VRAM issues
|
| 113 |
+
del x_in, sigma_in, cond_in, c_out, c_in, t,
|
| 114 |
+
del eps, denoised_uncond, denoised_cond, denoised, d, dt
|
| 115 |
+
|
| 116 |
+
shared.state.nextjob()
|
| 117 |
+
|
| 118 |
+
return x / sigmas[-1]
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class Script(scripts.Script):
|
| 122 |
+
def __init__(self):
|
| 123 |
+
self.cache = None
|
| 124 |
+
|
| 125 |
+
def title(self):
|
| 126 |
+
return "img2img alternative test"
|
| 127 |
+
|
| 128 |
+
def show(self, is_img2img):
|
| 129 |
+
return is_img2img
|
| 130 |
+
|
| 131 |
+
def ui(self, is_img2img):
|
| 132 |
+
info = gr.Markdown('''
|
| 133 |
+
* `CFG Scale` should be 2 or lower.
|
| 134 |
+
''')
|
| 135 |
+
|
| 136 |
+
override_sampler = gr.Checkbox(label="Override `Sampling method` to Euler?(this method is built for it)", value=True, elem_id=self.elem_id("override_sampler"))
|
| 137 |
+
|
| 138 |
+
override_prompt = gr.Checkbox(label="Override `prompt` to the same value as `original prompt`?(and `negative prompt`)", value=True, elem_id=self.elem_id("override_prompt"))
|
| 139 |
+
original_prompt = gr.Textbox(label="Original prompt", lines=1, elem_id=self.elem_id("original_prompt"))
|
| 140 |
+
original_negative_prompt = gr.Textbox(label="Original negative prompt", lines=1, elem_id=self.elem_id("original_negative_prompt"))
|
| 141 |
+
|
| 142 |
+
override_steps = gr.Checkbox(label="Override `Sampling Steps` to the same value as `Decode steps`?", value=True, elem_id=self.elem_id("override_steps"))
|
| 143 |
+
st = gr.Slider(label="Decode steps", minimum=1, maximum=150, step=1, value=50, elem_id=self.elem_id("st"))
|
| 144 |
+
|
| 145 |
+
override_strength = gr.Checkbox(label="Override `Denoising strength` to 1?", value=True, elem_id=self.elem_id("override_strength"))
|
| 146 |
+
|
| 147 |
+
cfg = gr.Slider(label="Decode CFG scale", minimum=0.0, maximum=15.0, step=0.1, value=1.0, elem_id=self.elem_id("cfg"))
|
| 148 |
+
randomness = gr.Slider(label="Randomness", minimum=0.0, maximum=1.0, step=0.01, value=0.0, elem_id=self.elem_id("randomness"))
|
| 149 |
+
sigma_adjustment = gr.Checkbox(label="Sigma adjustment for finding noise for image", value=False, elem_id=self.elem_id("sigma_adjustment"))
|
| 150 |
+
|
| 151 |
+
return [
|
| 152 |
+
info,
|
| 153 |
+
override_sampler,
|
| 154 |
+
override_prompt, original_prompt, original_negative_prompt,
|
| 155 |
+
override_steps, st,
|
| 156 |
+
override_strength,
|
| 157 |
+
cfg, randomness, sigma_adjustment,
|
| 158 |
+
]
|
| 159 |
+
|
| 160 |
+
def run(self, p, _, override_sampler, override_prompt, original_prompt, original_negative_prompt, override_steps, st, override_strength, cfg, randomness, sigma_adjustment):
|
| 161 |
+
# Override
|
| 162 |
+
if override_sampler:
|
| 163 |
+
p.sampler_name = "Euler"
|
| 164 |
+
if override_prompt:
|
| 165 |
+
p.prompt = original_prompt
|
| 166 |
+
p.negative_prompt = original_negative_prompt
|
| 167 |
+
if override_steps:
|
| 168 |
+
p.steps = st
|
| 169 |
+
if override_strength:
|
| 170 |
+
p.denoising_strength = 1.0
|
| 171 |
+
|
| 172 |
+
def sample_extra(conditioning, unconditional_conditioning, seeds, subseeds, subseed_strength, prompts):
|
| 173 |
+
lat = (p.init_latent.cpu().numpy() * 10).astype(int)
|
| 174 |
+
|
| 175 |
+
same_params = self.cache is not None and self.cache.cfg_scale == cfg and self.cache.steps == st \
|
| 176 |
+
and self.cache.original_prompt == original_prompt \
|
| 177 |
+
and self.cache.original_negative_prompt == original_negative_prompt \
|
| 178 |
+
and self.cache.sigma_adjustment == sigma_adjustment
|
| 179 |
+
same_everything = same_params and self.cache.latent.shape == lat.shape and np.abs(self.cache.latent-lat).sum() < 100
|
| 180 |
+
|
| 181 |
+
if same_everything:
|
| 182 |
+
rec_noise = self.cache.noise
|
| 183 |
+
else:
|
| 184 |
+
shared.state.job_count += 1
|
| 185 |
+
cond = p.sd_model.get_learned_conditioning(p.batch_size * [original_prompt])
|
| 186 |
+
uncond = p.sd_model.get_learned_conditioning(p.batch_size * [original_negative_prompt])
|
| 187 |
+
if sigma_adjustment:
|
| 188 |
+
rec_noise = find_noise_for_image_sigma_adjustment(p, cond, uncond, cfg, st)
|
| 189 |
+
else:
|
| 190 |
+
rec_noise = find_noise_for_image(p, cond, uncond, cfg, st)
|
| 191 |
+
self.cache = Cached(rec_noise, cfg, st, lat, original_prompt, original_negative_prompt, sigma_adjustment)
|
| 192 |
+
|
| 193 |
+
rand_noise = processing.create_random_tensors(p.init_latent.shape[1:], seeds=seeds, subseeds=subseeds, subseed_strength=p.subseed_strength, seed_resize_from_h=p.seed_resize_from_h, seed_resize_from_w=p.seed_resize_from_w, p=p)
|
| 194 |
+
|
| 195 |
+
combined_noise = ((1 - randomness) * rec_noise + randomness * rand_noise) / ((randomness**2 + (1-randomness)**2) ** 0.5)
|
| 196 |
+
|
| 197 |
+
sampler = sd_samplers.create_sampler(p.sampler_name, p.sd_model)
|
| 198 |
+
|
| 199 |
+
sigmas = sampler.model_wrap.get_sigmas(p.steps)
|
| 200 |
+
|
| 201 |
+
noise_dt = combined_noise - (p.init_latent / sigmas[0])
|
| 202 |
+
|
| 203 |
+
p.seed = p.seed + 1
|
| 204 |
+
|
| 205 |
+
return sampler.sample_img2img(p, p.init_latent, noise_dt, conditioning, unconditional_conditioning, image_conditioning=p.image_conditioning)
|
| 206 |
+
|
| 207 |
+
p.sample = sample_extra
|
| 208 |
+
|
| 209 |
+
p.extra_generation_params["Decode prompt"] = original_prompt
|
| 210 |
+
p.extra_generation_params["Decode negative prompt"] = original_negative_prompt
|
| 211 |
+
p.extra_generation_params["Decode CFG scale"] = cfg
|
| 212 |
+
p.extra_generation_params["Decode steps"] = st
|
| 213 |
+
p.extra_generation_params["Randomness"] = randomness
|
| 214 |
+
p.extra_generation_params["Sigma Adjustment"] = sigma_adjustment
|
| 215 |
+
|
| 216 |
+
processed = processing.process_images(p)
|
| 217 |
+
|
| 218 |
+
return processed
|
scripts/loopback.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import modules.scripts as scripts
|
| 5 |
+
from modules import deepbooru, images, processing, shared
|
| 6 |
+
from modules.processing import Processed
|
| 7 |
+
from modules.shared import opts, state
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class Script(scripts.Script):
|
| 11 |
+
def title(self):
|
| 12 |
+
return "Loopback"
|
| 13 |
+
|
| 14 |
+
def show(self, is_img2img):
|
| 15 |
+
return is_img2img
|
| 16 |
+
|
| 17 |
+
def ui(self, is_img2img):
|
| 18 |
+
loops = gr.Slider(minimum=1, maximum=32, step=1, label='Loops', value=4, elem_id=self.elem_id("loops"))
|
| 19 |
+
final_denoising_strength = gr.Slider(minimum=0, maximum=1, step=0.01, label='Final denoising strength', value=0.5, elem_id=self.elem_id("final_denoising_strength"))
|
| 20 |
+
denoising_curve = gr.Dropdown(label="Denoising strength curve", choices=["Aggressive", "Linear", "Lazy"], value="Linear")
|
| 21 |
+
append_interrogation = gr.Dropdown(label="Append interrogated prompt at each iteration", choices=["None", "CLIP", "DeepBooru"], value="None")
|
| 22 |
+
|
| 23 |
+
return [loops, final_denoising_strength, denoising_curve, append_interrogation]
|
| 24 |
+
|
| 25 |
+
def run(self, p, loops, final_denoising_strength, denoising_curve, append_interrogation):
|
| 26 |
+
processing.fix_seed(p)
|
| 27 |
+
batch_count = p.n_iter
|
| 28 |
+
p.extra_generation_params = {
|
| 29 |
+
"Final denoising strength": final_denoising_strength,
|
| 30 |
+
"Denoising curve": denoising_curve
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
p.batch_size = 1
|
| 34 |
+
p.n_iter = 1
|
| 35 |
+
|
| 36 |
+
info = None
|
| 37 |
+
initial_seed = None
|
| 38 |
+
initial_info = None
|
| 39 |
+
initial_denoising_strength = p.denoising_strength
|
| 40 |
+
|
| 41 |
+
grids = []
|
| 42 |
+
all_images = []
|
| 43 |
+
original_init_image = p.init_images
|
| 44 |
+
original_prompt = p.prompt
|
| 45 |
+
original_inpainting_fill = p.inpainting_fill
|
| 46 |
+
state.job_count = loops * batch_count
|
| 47 |
+
|
| 48 |
+
initial_color_corrections = [processing.setup_color_correction(p.init_images[0])]
|
| 49 |
+
|
| 50 |
+
def calculate_denoising_strength(loop):
|
| 51 |
+
strength = initial_denoising_strength
|
| 52 |
+
|
| 53 |
+
if loops == 1:
|
| 54 |
+
return strength
|
| 55 |
+
|
| 56 |
+
progress = loop / (loops - 1)
|
| 57 |
+
if denoising_curve == "Aggressive":
|
| 58 |
+
strength = math.sin((progress) * math.pi * 0.5)
|
| 59 |
+
elif denoising_curve == "Lazy":
|
| 60 |
+
strength = 1 - math.cos((progress) * math.pi * 0.5)
|
| 61 |
+
else:
|
| 62 |
+
strength = progress
|
| 63 |
+
|
| 64 |
+
change = (final_denoising_strength - initial_denoising_strength) * strength
|
| 65 |
+
return initial_denoising_strength + change
|
| 66 |
+
|
| 67 |
+
history = []
|
| 68 |
+
|
| 69 |
+
for n in range(batch_count):
|
| 70 |
+
# Reset to original init image at the start of each batch
|
| 71 |
+
p.init_images = original_init_image
|
| 72 |
+
|
| 73 |
+
# Reset to original denoising strength
|
| 74 |
+
p.denoising_strength = initial_denoising_strength
|
| 75 |
+
|
| 76 |
+
last_image = None
|
| 77 |
+
|
| 78 |
+
for i in range(loops):
|
| 79 |
+
p.n_iter = 1
|
| 80 |
+
p.batch_size = 1
|
| 81 |
+
p.do_not_save_grid = True
|
| 82 |
+
|
| 83 |
+
if opts.img2img_color_correction:
|
| 84 |
+
p.color_corrections = initial_color_corrections
|
| 85 |
+
|
| 86 |
+
if append_interrogation != "None":
|
| 87 |
+
p.prompt = original_prompt + ", " if original_prompt != "" else ""
|
| 88 |
+
if append_interrogation == "CLIP":
|
| 89 |
+
p.prompt += shared.interrogator.interrogate(p.init_images[0])
|
| 90 |
+
elif append_interrogation == "DeepBooru":
|
| 91 |
+
p.prompt += deepbooru.model.tag(p.init_images[0])
|
| 92 |
+
|
| 93 |
+
state.job = f"Iteration {i + 1}/{loops}, batch {n + 1}/{batch_count}"
|
| 94 |
+
|
| 95 |
+
processed = processing.process_images(p)
|
| 96 |
+
|
| 97 |
+
# Generation cancelled.
|
| 98 |
+
if state.interrupted:
|
| 99 |
+
break
|
| 100 |
+
|
| 101 |
+
if initial_seed is None:
|
| 102 |
+
initial_seed = processed.seed
|
| 103 |
+
initial_info = processed.info
|
| 104 |
+
|
| 105 |
+
p.seed = processed.seed + 1
|
| 106 |
+
p.denoising_strength = calculate_denoising_strength(i + 1)
|
| 107 |
+
|
| 108 |
+
if state.skipped:
|
| 109 |
+
break
|
| 110 |
+
|
| 111 |
+
last_image = processed.images[0]
|
| 112 |
+
p.init_images = [last_image]
|
| 113 |
+
p.inpainting_fill = 1 # Set "masked content" to "original" for next loop.
|
| 114 |
+
|
| 115 |
+
if batch_count == 1:
|
| 116 |
+
history.append(last_image)
|
| 117 |
+
all_images.append(last_image)
|
| 118 |
+
|
| 119 |
+
if batch_count > 1 and not state.skipped and not state.interrupted:
|
| 120 |
+
history.append(last_image)
|
| 121 |
+
all_images.append(last_image)
|
| 122 |
+
|
| 123 |
+
p.inpainting_fill = original_inpainting_fill
|
| 124 |
+
|
| 125 |
+
if state.interrupted:
|
| 126 |
+
break
|
| 127 |
+
|
| 128 |
+
if len(history) > 1:
|
| 129 |
+
grid = images.image_grid(history, rows=1)
|
| 130 |
+
if opts.grid_save:
|
| 131 |
+
images.save_image(grid, p.outpath_grids, "grid", initial_seed, p.prompt, opts.grid_format, info=info, short_filename=not opts.grid_extended_filename, grid=True, p=p)
|
| 132 |
+
|
| 133 |
+
if opts.return_grid:
|
| 134 |
+
grids.append(grid)
|
| 135 |
+
|
| 136 |
+
all_images = grids + all_images
|
| 137 |
+
|
| 138 |
+
processed = Processed(p, all_images, initial_seed, initial_info)
|
| 139 |
+
|
| 140 |
+
return processed
|
scripts/outpainting_mk_2.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import skimage
|
| 5 |
+
|
| 6 |
+
import modules.scripts as scripts
|
| 7 |
+
import gradio as gr
|
| 8 |
+
from PIL import Image, ImageDraw
|
| 9 |
+
|
| 10 |
+
from modules import images, processing, devices
|
| 11 |
+
from modules.processing import Processed, process_images
|
| 12 |
+
from modules.shared import opts, cmd_opts, state
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# this function is taken from https://github.com/parlance-zz/g-diffuser-bot
|
| 16 |
+
def get_matched_noise(_np_src_image, np_mask_rgb, noise_q=1, color_variation=0.05):
|
| 17 |
+
# helper fft routines that keep ortho normalization and auto-shift before and after fft
|
| 18 |
+
def _fft2(data):
|
| 19 |
+
if data.ndim > 2: # has channels
|
| 20 |
+
out_fft = np.zeros((data.shape[0], data.shape[1], data.shape[2]), dtype=np.complex128)
|
| 21 |
+
for c in range(data.shape[2]):
|
| 22 |
+
c_data = data[:, :, c]
|
| 23 |
+
out_fft[:, :, c] = np.fft.fft2(np.fft.fftshift(c_data), norm="ortho")
|
| 24 |
+
out_fft[:, :, c] = np.fft.ifftshift(out_fft[:, :, c])
|
| 25 |
+
else: # one channel
|
| 26 |
+
out_fft = np.zeros((data.shape[0], data.shape[1]), dtype=np.complex128)
|
| 27 |
+
out_fft[:, :] = np.fft.fft2(np.fft.fftshift(data), norm="ortho")
|
| 28 |
+
out_fft[:, :] = np.fft.ifftshift(out_fft[:, :])
|
| 29 |
+
|
| 30 |
+
return out_fft
|
| 31 |
+
|
| 32 |
+
def _ifft2(data):
|
| 33 |
+
if data.ndim > 2: # has channels
|
| 34 |
+
out_ifft = np.zeros((data.shape[0], data.shape[1], data.shape[2]), dtype=np.complex128)
|
| 35 |
+
for c in range(data.shape[2]):
|
| 36 |
+
c_data = data[:, :, c]
|
| 37 |
+
out_ifft[:, :, c] = np.fft.ifft2(np.fft.fftshift(c_data), norm="ortho")
|
| 38 |
+
out_ifft[:, :, c] = np.fft.ifftshift(out_ifft[:, :, c])
|
| 39 |
+
else: # one channel
|
| 40 |
+
out_ifft = np.zeros((data.shape[0], data.shape[1]), dtype=np.complex128)
|
| 41 |
+
out_ifft[:, :] = np.fft.ifft2(np.fft.fftshift(data), norm="ortho")
|
| 42 |
+
out_ifft[:, :] = np.fft.ifftshift(out_ifft[:, :])
|
| 43 |
+
|
| 44 |
+
return out_ifft
|
| 45 |
+
|
| 46 |
+
def _get_gaussian_window(width, height, std=3.14, mode=0):
|
| 47 |
+
window_scale_x = float(width / min(width, height))
|
| 48 |
+
window_scale_y = float(height / min(width, height))
|
| 49 |
+
|
| 50 |
+
window = np.zeros((width, height))
|
| 51 |
+
x = (np.arange(width) / width * 2. - 1.) * window_scale_x
|
| 52 |
+
for y in range(height):
|
| 53 |
+
fy = (y / height * 2. - 1.) * window_scale_y
|
| 54 |
+
if mode == 0:
|
| 55 |
+
window[:, y] = np.exp(-(x ** 2 + fy ** 2) * std)
|
| 56 |
+
else:
|
| 57 |
+
window[:, y] = (1 / ((x ** 2 + 1.) * (fy ** 2 + 1.))) ** (std / 3.14) # hey wait a minute that's not gaussian
|
| 58 |
+
|
| 59 |
+
return window
|
| 60 |
+
|
| 61 |
+
def _get_masked_window_rgb(np_mask_grey, hardness=1.):
|
| 62 |
+
np_mask_rgb = np.zeros((np_mask_grey.shape[0], np_mask_grey.shape[1], 3))
|
| 63 |
+
if hardness != 1.:
|
| 64 |
+
hardened = np_mask_grey[:] ** hardness
|
| 65 |
+
else:
|
| 66 |
+
hardened = np_mask_grey[:]
|
| 67 |
+
for c in range(3):
|
| 68 |
+
np_mask_rgb[:, :, c] = hardened[:]
|
| 69 |
+
return np_mask_rgb
|
| 70 |
+
|
| 71 |
+
width = _np_src_image.shape[0]
|
| 72 |
+
height = _np_src_image.shape[1]
|
| 73 |
+
num_channels = _np_src_image.shape[2]
|
| 74 |
+
|
| 75 |
+
np_src_image = _np_src_image[:] * (1. - np_mask_rgb)
|
| 76 |
+
np_mask_grey = (np.sum(np_mask_rgb, axis=2) / 3.)
|
| 77 |
+
img_mask = np_mask_grey > 1e-6
|
| 78 |
+
ref_mask = np_mask_grey < 1e-3
|
| 79 |
+
|
| 80 |
+
windowed_image = _np_src_image * (1. - _get_masked_window_rgb(np_mask_grey))
|
| 81 |
+
windowed_image /= np.max(windowed_image)
|
| 82 |
+
windowed_image += np.average(_np_src_image) * np_mask_rgb # / (1.-np.average(np_mask_rgb)) # rather than leave the masked area black, we get better results from fft by filling the average unmasked color
|
| 83 |
+
|
| 84 |
+
src_fft = _fft2(windowed_image) # get feature statistics from masked src img
|
| 85 |
+
src_dist = np.absolute(src_fft)
|
| 86 |
+
src_phase = src_fft / src_dist
|
| 87 |
+
|
| 88 |
+
# create a generator with a static seed to make outpainting deterministic / only follow global seed
|
| 89 |
+
rng = np.random.default_rng(0)
|
| 90 |
+
|
| 91 |
+
noise_window = _get_gaussian_window(width, height, mode=1) # start with simple gaussian noise
|
| 92 |
+
noise_rgb = rng.random((width, height, num_channels))
|
| 93 |
+
noise_grey = (np.sum(noise_rgb, axis=2) / 3.)
|
| 94 |
+
noise_rgb *= color_variation # the colorfulness of the starting noise is blended to greyscale with a parameter
|
| 95 |
+
for c in range(num_channels):
|
| 96 |
+
noise_rgb[:, :, c] += (1. - color_variation) * noise_grey
|
| 97 |
+
|
| 98 |
+
noise_fft = _fft2(noise_rgb)
|
| 99 |
+
for c in range(num_channels):
|
| 100 |
+
noise_fft[:, :, c] *= noise_window
|
| 101 |
+
noise_rgb = np.real(_ifft2(noise_fft))
|
| 102 |
+
shaped_noise_fft = _fft2(noise_rgb)
|
| 103 |
+
shaped_noise_fft[:, :, :] = np.absolute(shaped_noise_fft[:, :, :]) ** 2 * (src_dist ** noise_q) * src_phase # perform the actual shaping
|
| 104 |
+
|
| 105 |
+
brightness_variation = 0. # color_variation # todo: temporarily tieing brightness variation to color variation for now
|
| 106 |
+
contrast_adjusted_np_src = _np_src_image[:] * (brightness_variation + 1.) - brightness_variation * 2.
|
| 107 |
+
|
| 108 |
+
# scikit-image is used for histogram matching, very convenient!
|
| 109 |
+
shaped_noise = np.real(_ifft2(shaped_noise_fft))
|
| 110 |
+
shaped_noise -= np.min(shaped_noise)
|
| 111 |
+
shaped_noise /= np.max(shaped_noise)
|
| 112 |
+
shaped_noise[img_mask, :] = skimage.exposure.match_histograms(shaped_noise[img_mask, :] ** 1., contrast_adjusted_np_src[ref_mask, :], channel_axis=1)
|
| 113 |
+
shaped_noise = _np_src_image[:] * (1. - np_mask_rgb) + shaped_noise * np_mask_rgb
|
| 114 |
+
|
| 115 |
+
matched_noise = shaped_noise[:]
|
| 116 |
+
|
| 117 |
+
return np.clip(matched_noise, 0., 1.)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class Script(scripts.Script):
|
| 122 |
+
def title(self):
|
| 123 |
+
return "Outpainting mk2"
|
| 124 |
+
|
| 125 |
+
def show(self, is_img2img):
|
| 126 |
+
return is_img2img
|
| 127 |
+
|
| 128 |
+
def ui(self, is_img2img):
|
| 129 |
+
if not is_img2img:
|
| 130 |
+
return None
|
| 131 |
+
|
| 132 |
+
info = gr.HTML("<p style=\"margin-bottom:0.75em\">Recommended settings: Sampling Steps: 80-100, Sampler: Euler a, Denoising strength: 0.8</p>")
|
| 133 |
+
|
| 134 |
+
pixels = gr.Slider(label="Pixels to expand", minimum=8, maximum=256, step=8, value=128, elem_id=self.elem_id("pixels"))
|
| 135 |
+
mask_blur = gr.Slider(label='Mask blur', minimum=0, maximum=64, step=1, value=8, elem_id=self.elem_id("mask_blur"))
|
| 136 |
+
direction = gr.CheckboxGroup(label="Outpainting direction", choices=['left', 'right', 'up', 'down'], value=['left', 'right', 'up', 'down'], elem_id=self.elem_id("direction"))
|
| 137 |
+
noise_q = gr.Slider(label="Fall-off exponent (lower=higher detail)", minimum=0.0, maximum=4.0, step=0.01, value=1.0, elem_id=self.elem_id("noise_q"))
|
| 138 |
+
color_variation = gr.Slider(label="Color variation", minimum=0.0, maximum=1.0, step=0.01, value=0.05, elem_id=self.elem_id("color_variation"))
|
| 139 |
+
|
| 140 |
+
return [info, pixels, mask_blur, direction, noise_q, color_variation]
|
| 141 |
+
|
| 142 |
+
def run(self, p, _, pixels, mask_blur, direction, noise_q, color_variation):
|
| 143 |
+
initial_seed_and_info = [None, None]
|
| 144 |
+
|
| 145 |
+
process_width = p.width
|
| 146 |
+
process_height = p.height
|
| 147 |
+
|
| 148 |
+
p.mask_blur = mask_blur*4
|
| 149 |
+
p.inpaint_full_res = False
|
| 150 |
+
p.inpainting_fill = 1
|
| 151 |
+
p.do_not_save_samples = True
|
| 152 |
+
p.do_not_save_grid = True
|
| 153 |
+
|
| 154 |
+
left = pixels if "left" in direction else 0
|
| 155 |
+
right = pixels if "right" in direction else 0
|
| 156 |
+
up = pixels if "up" in direction else 0
|
| 157 |
+
down = pixels if "down" in direction else 0
|
| 158 |
+
|
| 159 |
+
init_img = p.init_images[0]
|
| 160 |
+
target_w = math.ceil((init_img.width + left + right) / 64) * 64
|
| 161 |
+
target_h = math.ceil((init_img.height + up + down) / 64) * 64
|
| 162 |
+
|
| 163 |
+
if left > 0:
|
| 164 |
+
left = left * (target_w - init_img.width) // (left + right)
|
| 165 |
+
|
| 166 |
+
if right > 0:
|
| 167 |
+
right = target_w - init_img.width - left
|
| 168 |
+
|
| 169 |
+
if up > 0:
|
| 170 |
+
up = up * (target_h - init_img.height) // (up + down)
|
| 171 |
+
|
| 172 |
+
if down > 0:
|
| 173 |
+
down = target_h - init_img.height - up
|
| 174 |
+
|
| 175 |
+
def expand(init, count, expand_pixels, is_left=False, is_right=False, is_top=False, is_bottom=False):
|
| 176 |
+
is_horiz = is_left or is_right
|
| 177 |
+
is_vert = is_top or is_bottom
|
| 178 |
+
pixels_horiz = expand_pixels if is_horiz else 0
|
| 179 |
+
pixels_vert = expand_pixels if is_vert else 0
|
| 180 |
+
|
| 181 |
+
images_to_process = []
|
| 182 |
+
output_images = []
|
| 183 |
+
for n in range(count):
|
| 184 |
+
res_w = init[n].width + pixels_horiz
|
| 185 |
+
res_h = init[n].height + pixels_vert
|
| 186 |
+
process_res_w = math.ceil(res_w / 64) * 64
|
| 187 |
+
process_res_h = math.ceil(res_h / 64) * 64
|
| 188 |
+
|
| 189 |
+
img = Image.new("RGB", (process_res_w, process_res_h))
|
| 190 |
+
img.paste(init[n], (pixels_horiz if is_left else 0, pixels_vert if is_top else 0))
|
| 191 |
+
mask = Image.new("RGB", (process_res_w, process_res_h), "white")
|
| 192 |
+
draw = ImageDraw.Draw(mask)
|
| 193 |
+
draw.rectangle((
|
| 194 |
+
expand_pixels + mask_blur if is_left else 0,
|
| 195 |
+
expand_pixels + mask_blur if is_top else 0,
|
| 196 |
+
mask.width - expand_pixels - mask_blur if is_right else res_w,
|
| 197 |
+
mask.height - expand_pixels - mask_blur if is_bottom else res_h,
|
| 198 |
+
), fill="black")
|
| 199 |
+
|
| 200 |
+
np_image = (np.asarray(img) / 255.0).astype(np.float64)
|
| 201 |
+
np_mask = (np.asarray(mask) / 255.0).astype(np.float64)
|
| 202 |
+
noised = get_matched_noise(np_image, np_mask, noise_q, color_variation)
|
| 203 |
+
output_images.append(Image.fromarray(np.clip(noised * 255., 0., 255.).astype(np.uint8), mode="RGB"))
|
| 204 |
+
|
| 205 |
+
target_width = min(process_width, init[n].width + pixels_horiz) if is_horiz else img.width
|
| 206 |
+
target_height = min(process_height, init[n].height + pixels_vert) if is_vert else img.height
|
| 207 |
+
p.width = target_width if is_horiz else img.width
|
| 208 |
+
p.height = target_height if is_vert else img.height
|
| 209 |
+
|
| 210 |
+
crop_region = (
|
| 211 |
+
0 if is_left else output_images[n].width - target_width,
|
| 212 |
+
0 if is_top else output_images[n].height - target_height,
|
| 213 |
+
target_width if is_left else output_images[n].width,
|
| 214 |
+
target_height if is_top else output_images[n].height,
|
| 215 |
+
)
|
| 216 |
+
mask = mask.crop(crop_region)
|
| 217 |
+
p.image_mask = mask
|
| 218 |
+
|
| 219 |
+
image_to_process = output_images[n].crop(crop_region)
|
| 220 |
+
images_to_process.append(image_to_process)
|
| 221 |
+
|
| 222 |
+
p.init_images = images_to_process
|
| 223 |
+
|
| 224 |
+
latent_mask = Image.new("RGB", (p.width, p.height), "white")
|
| 225 |
+
draw = ImageDraw.Draw(latent_mask)
|
| 226 |
+
draw.rectangle((
|
| 227 |
+
expand_pixels + mask_blur * 2 if is_left else 0,
|
| 228 |
+
expand_pixels + mask_blur * 2 if is_top else 0,
|
| 229 |
+
mask.width - expand_pixels - mask_blur * 2 if is_right else res_w,
|
| 230 |
+
mask.height - expand_pixels - mask_blur * 2 if is_bottom else res_h,
|
| 231 |
+
), fill="black")
|
| 232 |
+
p.latent_mask = latent_mask
|
| 233 |
+
|
| 234 |
+
proc = process_images(p)
|
| 235 |
+
|
| 236 |
+
if initial_seed_and_info[0] is None:
|
| 237 |
+
initial_seed_and_info[0] = proc.seed
|
| 238 |
+
initial_seed_and_info[1] = proc.info
|
| 239 |
+
|
| 240 |
+
for n in range(count):
|
| 241 |
+
output_images[n].paste(proc.images[n], (0 if is_left else output_images[n].width - proc.images[n].width, 0 if is_top else output_images[n].height - proc.images[n].height))
|
| 242 |
+
output_images[n] = output_images[n].crop((0, 0, res_w, res_h))
|
| 243 |
+
|
| 244 |
+
return output_images
|
| 245 |
+
|
| 246 |
+
batch_count = p.n_iter
|
| 247 |
+
batch_size = p.batch_size
|
| 248 |
+
p.n_iter = 1
|
| 249 |
+
state.job_count = batch_count * ((1 if left > 0 else 0) + (1 if right > 0 else 0) + (1 if up > 0 else 0) + (1 if down > 0 else 0))
|
| 250 |
+
all_processed_images = []
|
| 251 |
+
|
| 252 |
+
for i in range(batch_count):
|
| 253 |
+
imgs = [init_img] * batch_size
|
| 254 |
+
state.job = f"Batch {i + 1} out of {batch_count}"
|
| 255 |
+
|
| 256 |
+
if left > 0:
|
| 257 |
+
imgs = expand(imgs, batch_size, left, is_left=True)
|
| 258 |
+
if right > 0:
|
| 259 |
+
imgs = expand(imgs, batch_size, right, is_right=True)
|
| 260 |
+
if up > 0:
|
| 261 |
+
imgs = expand(imgs, batch_size, up, is_top=True)
|
| 262 |
+
if down > 0:
|
| 263 |
+
imgs = expand(imgs, batch_size, down, is_bottom=True)
|
| 264 |
+
|
| 265 |
+
all_processed_images += imgs
|
| 266 |
+
|
| 267 |
+
all_images = all_processed_images
|
| 268 |
+
|
| 269 |
+
combined_grid_image = images.image_grid(all_processed_images)
|
| 270 |
+
unwanted_grid_because_of_img_count = len(all_processed_images) < 2 and opts.grid_only_if_multiple
|
| 271 |
+
if opts.return_grid and not unwanted_grid_because_of_img_count:
|
| 272 |
+
all_images = [combined_grid_image] + all_processed_images
|
| 273 |
+
|
| 274 |
+
res = Processed(p, all_images, initial_seed_and_info[0], initial_seed_and_info[1])
|
| 275 |
+
|
| 276 |
+
if opts.samples_save:
|
| 277 |
+
for img in all_processed_images:
|
| 278 |
+
images.save_image(img, p.outpath_samples, "", res.seed, p.prompt, opts.grid_format, info=res.info, p=p)
|
| 279 |
+
|
| 280 |
+
if opts.grid_save and not unwanted_grid_because_of_img_count:
|
| 281 |
+
images.save_image(combined_grid_image, p.outpath_grids, "grid", res.seed, p.prompt, opts.grid_format, info=res.info, short_filename=not opts.grid_extended_filename, grid=True, p=p)
|
| 282 |
+
|
| 283 |
+
return res
|
scripts/poor_mans_outpainting.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import modules.scripts as scripts
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from PIL import Image, ImageDraw
|
| 6 |
+
|
| 7 |
+
from modules import images, processing, devices
|
| 8 |
+
from modules.processing import Processed, process_images
|
| 9 |
+
from modules.shared import opts, cmd_opts, state
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Script(scripts.Script):
|
| 13 |
+
def title(self):
|
| 14 |
+
return "Poor man's outpainting"
|
| 15 |
+
|
| 16 |
+
def show(self, is_img2img):
|
| 17 |
+
return is_img2img
|
| 18 |
+
|
| 19 |
+
def ui(self, is_img2img):
|
| 20 |
+
if not is_img2img:
|
| 21 |
+
return None
|
| 22 |
+
|
| 23 |
+
pixels = gr.Slider(label="Pixels to expand", minimum=8, maximum=256, step=8, value=128, elem_id=self.elem_id("pixels"))
|
| 24 |
+
mask_blur = gr.Slider(label='Mask blur', minimum=0, maximum=64, step=1, value=4, elem_id=self.elem_id("mask_blur"))
|
| 25 |
+
inpainting_fill = gr.Radio(label='Masked content', choices=['fill', 'original', 'latent noise', 'latent nothing'], value='fill', type="index", elem_id=self.elem_id("inpainting_fill"))
|
| 26 |
+
direction = gr.CheckboxGroup(label="Outpainting direction", choices=['left', 'right', 'up', 'down'], value=['left', 'right', 'up', 'down'], elem_id=self.elem_id("direction"))
|
| 27 |
+
|
| 28 |
+
return [pixels, mask_blur, inpainting_fill, direction]
|
| 29 |
+
|
| 30 |
+
def run(self, p, pixels, mask_blur, inpainting_fill, direction):
|
| 31 |
+
initial_seed = None
|
| 32 |
+
initial_info = None
|
| 33 |
+
|
| 34 |
+
p.mask_blur = mask_blur * 2
|
| 35 |
+
p.inpainting_fill = inpainting_fill
|
| 36 |
+
p.inpaint_full_res = False
|
| 37 |
+
|
| 38 |
+
left = pixels if "left" in direction else 0
|
| 39 |
+
right = pixels if "right" in direction else 0
|
| 40 |
+
up = pixels if "up" in direction else 0
|
| 41 |
+
down = pixels if "down" in direction else 0
|
| 42 |
+
|
| 43 |
+
init_img = p.init_images[0]
|
| 44 |
+
target_w = math.ceil((init_img.width + left + right) / 64) * 64
|
| 45 |
+
target_h = math.ceil((init_img.height + up + down) / 64) * 64
|
| 46 |
+
|
| 47 |
+
if left > 0:
|
| 48 |
+
left = left * (target_w - init_img.width) // (left + right)
|
| 49 |
+
if right > 0:
|
| 50 |
+
right = target_w - init_img.width - left
|
| 51 |
+
|
| 52 |
+
if up > 0:
|
| 53 |
+
up = up * (target_h - init_img.height) // (up + down)
|
| 54 |
+
|
| 55 |
+
if down > 0:
|
| 56 |
+
down = target_h - init_img.height - up
|
| 57 |
+
|
| 58 |
+
img = Image.new("RGB", (target_w, target_h))
|
| 59 |
+
img.paste(init_img, (left, up))
|
| 60 |
+
|
| 61 |
+
mask = Image.new("L", (img.width, img.height), "white")
|
| 62 |
+
draw = ImageDraw.Draw(mask)
|
| 63 |
+
draw.rectangle((
|
| 64 |
+
left + (mask_blur * 2 if left > 0 else 0),
|
| 65 |
+
up + (mask_blur * 2 if up > 0 else 0),
|
| 66 |
+
mask.width - right - (mask_blur * 2 if right > 0 else 0),
|
| 67 |
+
mask.height - down - (mask_blur * 2 if down > 0 else 0)
|
| 68 |
+
), fill="black")
|
| 69 |
+
|
| 70 |
+
latent_mask = Image.new("L", (img.width, img.height), "white")
|
| 71 |
+
latent_draw = ImageDraw.Draw(latent_mask)
|
| 72 |
+
latent_draw.rectangle((
|
| 73 |
+
left + (mask_blur//2 if left > 0 else 0),
|
| 74 |
+
up + (mask_blur//2 if up > 0 else 0),
|
| 75 |
+
mask.width - right - (mask_blur//2 if right > 0 else 0),
|
| 76 |
+
mask.height - down - (mask_blur//2 if down > 0 else 0)
|
| 77 |
+
), fill="black")
|
| 78 |
+
|
| 79 |
+
devices.torch_gc()
|
| 80 |
+
|
| 81 |
+
grid = images.split_grid(img, tile_w=p.width, tile_h=p.height, overlap=pixels)
|
| 82 |
+
grid_mask = images.split_grid(mask, tile_w=p.width, tile_h=p.height, overlap=pixels)
|
| 83 |
+
grid_latent_mask = images.split_grid(latent_mask, tile_w=p.width, tile_h=p.height, overlap=pixels)
|
| 84 |
+
|
| 85 |
+
p.n_iter = 1
|
| 86 |
+
p.batch_size = 1
|
| 87 |
+
p.do_not_save_grid = True
|
| 88 |
+
p.do_not_save_samples = True
|
| 89 |
+
|
| 90 |
+
work = []
|
| 91 |
+
work_mask = []
|
| 92 |
+
work_latent_mask = []
|
| 93 |
+
work_results = []
|
| 94 |
+
|
| 95 |
+
for (y, h, row), (_, _, row_mask), (_, _, row_latent_mask) in zip(grid.tiles, grid_mask.tiles, grid_latent_mask.tiles):
|
| 96 |
+
for tiledata, tiledata_mask, tiledata_latent_mask in zip(row, row_mask, row_latent_mask):
|
| 97 |
+
x, w = tiledata[0:2]
|
| 98 |
+
|
| 99 |
+
if x >= left and x+w <= img.width - right and y >= up and y+h <= img.height - down:
|
| 100 |
+
continue
|
| 101 |
+
|
| 102 |
+
work.append(tiledata[2])
|
| 103 |
+
work_mask.append(tiledata_mask[2])
|
| 104 |
+
work_latent_mask.append(tiledata_latent_mask[2])
|
| 105 |
+
|
| 106 |
+
batch_count = len(work)
|
| 107 |
+
print(f"Poor man's outpainting will process a total of {len(work)} images tiled as {len(grid.tiles[0][2])}x{len(grid.tiles)}.")
|
| 108 |
+
|
| 109 |
+
state.job_count = batch_count
|
| 110 |
+
|
| 111 |
+
for i in range(batch_count):
|
| 112 |
+
p.init_images = [work[i]]
|
| 113 |
+
p.image_mask = work_mask[i]
|
| 114 |
+
p.latent_mask = work_latent_mask[i]
|
| 115 |
+
|
| 116 |
+
state.job = f"Batch {i + 1} out of {batch_count}"
|
| 117 |
+
processed = process_images(p)
|
| 118 |
+
|
| 119 |
+
if initial_seed is None:
|
| 120 |
+
initial_seed = processed.seed
|
| 121 |
+
initial_info = processed.info
|
| 122 |
+
|
| 123 |
+
p.seed = processed.seed + 1
|
| 124 |
+
work_results += processed.images
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
image_index = 0
|
| 128 |
+
for y, h, row in grid.tiles:
|
| 129 |
+
for tiledata in row:
|
| 130 |
+
x, w = tiledata[0:2]
|
| 131 |
+
|
| 132 |
+
if x >= left and x+w <= img.width - right and y >= up and y+h <= img.height - down:
|
| 133 |
+
continue
|
| 134 |
+
|
| 135 |
+
tiledata[2] = work_results[image_index] if image_index < len(work_results) else Image.new("RGB", (p.width, p.height))
|
| 136 |
+
image_index += 1
|
| 137 |
+
|
| 138 |
+
combined_image = images.combine_grid(grid)
|
| 139 |
+
|
| 140 |
+
if opts.samples_save:
|
| 141 |
+
images.save_image(combined_image, p.outpath_samples, "", initial_seed, p.prompt, opts.grid_format, info=initial_info, p=p)
|
| 142 |
+
|
| 143 |
+
processed = Processed(p, [combined_image], initial_seed, initial_info)
|
| 144 |
+
|
| 145 |
+
return processed
|
| 146 |
+
|
scripts/postprocessing_codeformer.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
from modules import scripts_postprocessing, codeformer_model
|
| 5 |
+
import gradio as gr
|
| 6 |
+
|
| 7 |
+
from modules.ui_components import FormRow
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ScriptPostprocessingCodeFormer(scripts_postprocessing.ScriptPostprocessing):
|
| 11 |
+
name = "CodeFormer"
|
| 12 |
+
order = 3000
|
| 13 |
+
|
| 14 |
+
def ui(self):
|
| 15 |
+
with FormRow():
|
| 16 |
+
codeformer_visibility = gr.Slider(minimum=0.0, maximum=1.0, step=0.001, label="CodeFormer visibility", value=0, elem_id="extras_codeformer_visibility")
|
| 17 |
+
codeformer_weight = gr.Slider(minimum=0.0, maximum=1.0, step=0.001, label="CodeFormer weight (0 = maximum effect, 1 = minimum effect)", value=0, elem_id="extras_codeformer_weight")
|
| 18 |
+
|
| 19 |
+
return {
|
| 20 |
+
"codeformer_visibility": codeformer_visibility,
|
| 21 |
+
"codeformer_weight": codeformer_weight,
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
def process(self, pp: scripts_postprocessing.PostprocessedImage, codeformer_visibility, codeformer_weight):
|
| 25 |
+
if codeformer_visibility == 0:
|
| 26 |
+
return
|
| 27 |
+
|
| 28 |
+
restored_img = codeformer_model.codeformer.restore(np.array(pp.image, dtype=np.uint8), w=codeformer_weight)
|
| 29 |
+
res = Image.fromarray(restored_img)
|
| 30 |
+
|
| 31 |
+
if codeformer_visibility < 1.0:
|
| 32 |
+
res = Image.blend(pp.image, res, codeformer_visibility)
|
| 33 |
+
|
| 34 |
+
pp.image = res
|
| 35 |
+
pp.info["CodeFormer visibility"] = round(codeformer_visibility, 3)
|
| 36 |
+
pp.info["CodeFormer weight"] = round(codeformer_weight, 3)
|
scripts/postprocessing_gfpgan.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
from modules import scripts_postprocessing, gfpgan_model
|
| 5 |
+
import gradio as gr
|
| 6 |
+
|
| 7 |
+
from modules.ui_components import FormRow
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class ScriptPostprocessingGfpGan(scripts_postprocessing.ScriptPostprocessing):
|
| 11 |
+
name = "GFPGAN"
|
| 12 |
+
order = 2000
|
| 13 |
+
|
| 14 |
+
def ui(self):
|
| 15 |
+
with FormRow():
|
| 16 |
+
gfpgan_visibility = gr.Slider(minimum=0.0, maximum=1.0, step=0.001, label="GFPGAN visibility", value=0, elem_id="extras_gfpgan_visibility")
|
| 17 |
+
|
| 18 |
+
return {
|
| 19 |
+
"gfpgan_visibility": gfpgan_visibility,
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
def process(self, pp: scripts_postprocessing.PostprocessedImage, gfpgan_visibility):
|
| 23 |
+
if gfpgan_visibility == 0:
|
| 24 |
+
return
|
| 25 |
+
|
| 26 |
+
restored_img = gfpgan_model.gfpgan_fix_faces(np.array(pp.image, dtype=np.uint8))
|
| 27 |
+
res = Image.fromarray(restored_img)
|
| 28 |
+
|
| 29 |
+
if gfpgan_visibility < 1.0:
|
| 30 |
+
res = Image.blend(pp.image, res, gfpgan_visibility)
|
| 31 |
+
|
| 32 |
+
pp.image = res
|
| 33 |
+
pp.info["GFPGAN visibility"] = round(gfpgan_visibility, 3)
|
scripts/postprocessing_upscale.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
from modules import scripts_postprocessing, shared
|
| 5 |
+
import gradio as gr
|
| 6 |
+
|
| 7 |
+
from modules.ui_components import FormRow
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
upscale_cache = {}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class ScriptPostprocessingUpscale(scripts_postprocessing.ScriptPostprocessing):
|
| 14 |
+
name = "Upscale"
|
| 15 |
+
order = 1000
|
| 16 |
+
|
| 17 |
+
def ui(self):
|
| 18 |
+
selected_tab = gr.State(value=0)
|
| 19 |
+
|
| 20 |
+
with gr.Column():
|
| 21 |
+
with FormRow():
|
| 22 |
+
with gr.Tabs(elem_id="extras_resize_mode"):
|
| 23 |
+
with gr.TabItem('Scale by', elem_id="extras_scale_by_tab") as tab_scale_by:
|
| 24 |
+
upscaling_resize = gr.Slider(minimum=1.0, maximum=8.0, step=0.05, label="Resize", value=4, elem_id="extras_upscaling_resize")
|
| 25 |
+
|
| 26 |
+
with gr.TabItem('Scale to', elem_id="extras_scale_to_tab") as tab_scale_to:
|
| 27 |
+
with FormRow():
|
| 28 |
+
upscaling_resize_w = gr.Number(label="Width", value=512, precision=0, elem_id="extras_upscaling_resize_w")
|
| 29 |
+
upscaling_resize_h = gr.Number(label="Height", value=512, precision=0, elem_id="extras_upscaling_resize_h")
|
| 30 |
+
upscaling_crop = gr.Checkbox(label='Crop to fit', value=True, elem_id="extras_upscaling_crop")
|
| 31 |
+
|
| 32 |
+
with FormRow():
|
| 33 |
+
extras_upscaler_1 = gr.Dropdown(label='Upscaler 1', elem_id="extras_upscaler_1", choices=[x.name for x in shared.sd_upscalers], value=shared.sd_upscalers[0].name)
|
| 34 |
+
|
| 35 |
+
with FormRow():
|
| 36 |
+
extras_upscaler_2 = gr.Dropdown(label='Upscaler 2', elem_id="extras_upscaler_2", choices=[x.name for x in shared.sd_upscalers], value=shared.sd_upscalers[0].name)
|
| 37 |
+
extras_upscaler_2_visibility = gr.Slider(minimum=0.0, maximum=1.0, step=0.001, label="Upscaler 2 visibility", value=0.0, elem_id="extras_upscaler_2_visibility")
|
| 38 |
+
|
| 39 |
+
tab_scale_by.select(fn=lambda: 0, inputs=[], outputs=[selected_tab])
|
| 40 |
+
tab_scale_to.select(fn=lambda: 1, inputs=[], outputs=[selected_tab])
|
| 41 |
+
|
| 42 |
+
return {
|
| 43 |
+
"upscale_mode": selected_tab,
|
| 44 |
+
"upscale_by": upscaling_resize,
|
| 45 |
+
"upscale_to_width": upscaling_resize_w,
|
| 46 |
+
"upscale_to_height": upscaling_resize_h,
|
| 47 |
+
"upscale_crop": upscaling_crop,
|
| 48 |
+
"upscaler_1_name": extras_upscaler_1,
|
| 49 |
+
"upscaler_2_name": extras_upscaler_2,
|
| 50 |
+
"upscaler_2_visibility": extras_upscaler_2_visibility,
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
def upscale(self, image, info, upscaler, upscale_mode, upscale_by, upscale_to_width, upscale_to_height, upscale_crop):
|
| 54 |
+
if upscale_mode == 1:
|
| 55 |
+
upscale_by = max(upscale_to_width/image.width, upscale_to_height/image.height)
|
| 56 |
+
info["Postprocess upscale to"] = f"{upscale_to_width}x{upscale_to_height}"
|
| 57 |
+
else:
|
| 58 |
+
info["Postprocess upscale by"] = upscale_by
|
| 59 |
+
|
| 60 |
+
cache_key = (hash(np.array(image.getdata()).tobytes()), upscaler.name, upscale_mode, upscale_by, upscale_to_width, upscale_to_height, upscale_crop)
|
| 61 |
+
cached_image = upscale_cache.pop(cache_key, None)
|
| 62 |
+
|
| 63 |
+
if cached_image is not None:
|
| 64 |
+
image = cached_image
|
| 65 |
+
else:
|
| 66 |
+
image = upscaler.scaler.upscale(image, upscale_by, upscaler.data_path)
|
| 67 |
+
|
| 68 |
+
upscale_cache[cache_key] = image
|
| 69 |
+
if len(upscale_cache) > shared.opts.upscaling_max_images_in_cache:
|
| 70 |
+
upscale_cache.pop(next(iter(upscale_cache), None), None)
|
| 71 |
+
|
| 72 |
+
if upscale_mode == 1 and upscale_crop:
|
| 73 |
+
cropped = Image.new("RGB", (upscale_to_width, upscale_to_height))
|
| 74 |
+
cropped.paste(image, box=(upscale_to_width // 2 - image.width // 2, upscale_to_height // 2 - image.height // 2))
|
| 75 |
+
image = cropped
|
| 76 |
+
info["Postprocess crop to"] = f"{image.width}x{image.height}"
|
| 77 |
+
|
| 78 |
+
return image
|
| 79 |
+
|
| 80 |
+
def process(self, pp: scripts_postprocessing.PostprocessedImage, upscale_mode=1, upscale_by=2.0, upscale_to_width=None, upscale_to_height=None, upscale_crop=False, upscaler_1_name=None, upscaler_2_name=None, upscaler_2_visibility=0.0):
|
| 81 |
+
if upscaler_1_name == "None":
|
| 82 |
+
upscaler_1_name = None
|
| 83 |
+
|
| 84 |
+
upscaler1 = next(iter([x for x in shared.sd_upscalers if x.name == upscaler_1_name]), None)
|
| 85 |
+
assert upscaler1 or (upscaler_1_name is None), f'could not find upscaler named {upscaler_1_name}'
|
| 86 |
+
|
| 87 |
+
if not upscaler1:
|
| 88 |
+
return
|
| 89 |
+
|
| 90 |
+
if upscaler_2_name == "None":
|
| 91 |
+
upscaler_2_name = None
|
| 92 |
+
|
| 93 |
+
upscaler2 = next(iter([x for x in shared.sd_upscalers if x.name == upscaler_2_name and x.name != "None"]), None)
|
| 94 |
+
assert upscaler2 or (upscaler_2_name is None), f'could not find upscaler named {upscaler_2_name}'
|
| 95 |
+
|
| 96 |
+
upscaled_image = self.upscale(pp.image, pp.info, upscaler1, upscale_mode, upscale_by, upscale_to_width, upscale_to_height, upscale_crop)
|
| 97 |
+
pp.info[f"Postprocess upscaler"] = upscaler1.name
|
| 98 |
+
|
| 99 |
+
if upscaler2 and upscaler_2_visibility > 0:
|
| 100 |
+
second_upscale = self.upscale(pp.image, pp.info, upscaler2, upscale_mode, upscale_by, upscale_to_width, upscale_to_height, upscale_crop)
|
| 101 |
+
upscaled_image = Image.blend(upscaled_image, second_upscale, upscaler_2_visibility)
|
| 102 |
+
|
| 103 |
+
pp.info[f"Postprocess upscaler 2"] = upscaler2.name
|
| 104 |
+
|
| 105 |
+
pp.image = upscaled_image
|
| 106 |
+
|
| 107 |
+
def image_changed(self):
|
| 108 |
+
upscale_cache.clear()
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class ScriptPostprocessingUpscaleSimple(ScriptPostprocessingUpscale):
|
| 112 |
+
name = "Simple Upscale"
|
| 113 |
+
order = 900
|
| 114 |
+
|
| 115 |
+
def ui(self):
|
| 116 |
+
with FormRow():
|
| 117 |
+
upscaler_name = gr.Dropdown(label='Upscaler', choices=[x.name for x in shared.sd_upscalers], value=shared.sd_upscalers[0].name)
|
| 118 |
+
upscale_by = gr.Slider(minimum=0.05, maximum=8.0, step=0.05, label="Upscale by", value=2)
|
| 119 |
+
|
| 120 |
+
return {
|
| 121 |
+
"upscale_by": upscale_by,
|
| 122 |
+
"upscaler_name": upscaler_name,
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
def process(self, pp: scripts_postprocessing.PostprocessedImage, upscale_by=2.0, upscaler_name=None):
|
| 126 |
+
if upscaler_name is None or upscaler_name == "None":
|
| 127 |
+
return
|
| 128 |
+
|
| 129 |
+
upscaler1 = next(iter([x for x in shared.sd_upscalers if x.name == upscaler_name]), None)
|
| 130 |
+
assert upscaler1, f'could not find upscaler named {upscaler_name}'
|
| 131 |
+
|
| 132 |
+
pp.image = self.upscale(pp.image, pp.info, upscaler1, 0, upscale_by, 0, 0, False)
|
| 133 |
+
pp.info[f"Postprocess upscaler"] = upscaler1.name
|
scripts/prompt_matrix.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from collections import namedtuple
|
| 3 |
+
from copy import copy
|
| 4 |
+
import random
|
| 5 |
+
|
| 6 |
+
import modules.scripts as scripts
|
| 7 |
+
import gradio as gr
|
| 8 |
+
|
| 9 |
+
from modules import images
|
| 10 |
+
from modules.processing import process_images, Processed
|
| 11 |
+
from modules.shared import opts, cmd_opts, state
|
| 12 |
+
import modules.sd_samplers
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def draw_xy_grid(xs, ys, x_label, y_label, cell):
|
| 16 |
+
res = []
|
| 17 |
+
|
| 18 |
+
ver_texts = [[images.GridAnnotation(y_label(y))] for y in ys]
|
| 19 |
+
hor_texts = [[images.GridAnnotation(x_label(x))] for x in xs]
|
| 20 |
+
|
| 21 |
+
first_processed = None
|
| 22 |
+
|
| 23 |
+
state.job_count = len(xs) * len(ys)
|
| 24 |
+
|
| 25 |
+
for iy, y in enumerate(ys):
|
| 26 |
+
for ix, x in enumerate(xs):
|
| 27 |
+
state.job = f"{ix + iy * len(xs) + 1} out of {len(xs) * len(ys)}"
|
| 28 |
+
|
| 29 |
+
processed = cell(x, y)
|
| 30 |
+
if first_processed is None:
|
| 31 |
+
first_processed = processed
|
| 32 |
+
|
| 33 |
+
res.append(processed.images[0])
|
| 34 |
+
|
| 35 |
+
grid = images.image_grid(res, rows=len(ys))
|
| 36 |
+
grid = images.draw_grid_annotations(grid, res[0].width, res[0].height, hor_texts, ver_texts)
|
| 37 |
+
|
| 38 |
+
first_processed.images = [grid]
|
| 39 |
+
|
| 40 |
+
return first_processed
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class Script(scripts.Script):
|
| 44 |
+
def title(self):
|
| 45 |
+
return "Prompt matrix"
|
| 46 |
+
|
| 47 |
+
def ui(self, is_img2img):
|
| 48 |
+
gr.HTML('<br />')
|
| 49 |
+
with gr.Row():
|
| 50 |
+
with gr.Column():
|
| 51 |
+
put_at_start = gr.Checkbox(label='Put variable parts at start of prompt', value=False, elem_id=self.elem_id("put_at_start"))
|
| 52 |
+
different_seeds = gr.Checkbox(label='Use different seed for each picture', value=False, elem_id=self.elem_id("different_seeds"))
|
| 53 |
+
with gr.Column():
|
| 54 |
+
prompt_type = gr.Radio(["positive", "negative"], label="Select prompt", elem_id=self.elem_id("prompt_type"), value="positive")
|
| 55 |
+
variations_delimiter = gr.Radio(["comma", "space"], label="Select joining char", elem_id=self.elem_id("variations_delimiter"), value="comma")
|
| 56 |
+
with gr.Column():
|
| 57 |
+
margin_size = gr.Slider(label="Grid margins (px)", minimum=0, maximum=500, value=0, step=2, elem_id=self.elem_id("margin_size"))
|
| 58 |
+
|
| 59 |
+
return [put_at_start, different_seeds, prompt_type, variations_delimiter, margin_size]
|
| 60 |
+
|
| 61 |
+
def run(self, p, put_at_start, different_seeds, prompt_type, variations_delimiter, margin_size):
|
| 62 |
+
modules.processing.fix_seed(p)
|
| 63 |
+
# Raise error if promp type is not positive or negative
|
| 64 |
+
if prompt_type not in ["positive", "negative"]:
|
| 65 |
+
raise ValueError(f"Unknown prompt type {prompt_type}")
|
| 66 |
+
# Raise error if variations delimiter is not comma or space
|
| 67 |
+
if variations_delimiter not in ["comma", "space"]:
|
| 68 |
+
raise ValueError(f"Unknown variations delimiter {variations_delimiter}")
|
| 69 |
+
|
| 70 |
+
prompt = p.prompt if prompt_type == "positive" else p.negative_prompt
|
| 71 |
+
original_prompt = prompt[0] if type(prompt) == list else prompt
|
| 72 |
+
positive_prompt = p.prompt[0] if type(p.prompt) == list else p.prompt
|
| 73 |
+
|
| 74 |
+
delimiter = ", " if variations_delimiter == "comma" else " "
|
| 75 |
+
|
| 76 |
+
all_prompts = []
|
| 77 |
+
prompt_matrix_parts = original_prompt.split("|")
|
| 78 |
+
combination_count = 2 ** (len(prompt_matrix_parts) - 1)
|
| 79 |
+
for combination_num in range(combination_count):
|
| 80 |
+
selected_prompts = [text.strip().strip(',') for n, text in enumerate(prompt_matrix_parts[1:]) if combination_num & (1 << n)]
|
| 81 |
+
|
| 82 |
+
if put_at_start:
|
| 83 |
+
selected_prompts = selected_prompts + [prompt_matrix_parts[0]]
|
| 84 |
+
else:
|
| 85 |
+
selected_prompts = [prompt_matrix_parts[0]] + selected_prompts
|
| 86 |
+
|
| 87 |
+
all_prompts.append(delimiter.join(selected_prompts))
|
| 88 |
+
|
| 89 |
+
p.n_iter = math.ceil(len(all_prompts) / p.batch_size)
|
| 90 |
+
p.do_not_save_grid = True
|
| 91 |
+
|
| 92 |
+
print(f"Prompt matrix will create {len(all_prompts)} images using a total of {p.n_iter} batches.")
|
| 93 |
+
|
| 94 |
+
if prompt_type == "positive":
|
| 95 |
+
p.prompt = all_prompts
|
| 96 |
+
else:
|
| 97 |
+
p.negative_prompt = all_prompts
|
| 98 |
+
p.seed = [p.seed + (i if different_seeds else 0) for i in range(len(all_prompts))]
|
| 99 |
+
p.prompt_for_display = positive_prompt
|
| 100 |
+
processed = process_images(p)
|
| 101 |
+
|
| 102 |
+
grid = images.image_grid(processed.images, p.batch_size, rows=1 << ((len(prompt_matrix_parts) - 1) // 2))
|
| 103 |
+
grid = images.draw_prompt_matrix(grid, processed.images[0].width, processed.images[0].height, prompt_matrix_parts, margin_size)
|
| 104 |
+
processed.images.insert(0, grid)
|
| 105 |
+
processed.index_of_first_image = 1
|
| 106 |
+
processed.infotexts.insert(0, processed.infotexts[0])
|
| 107 |
+
|
| 108 |
+
if opts.grid_save:
|
| 109 |
+
images.save_image(processed.images[0], p.outpath_grids, "prompt_matrix", extension=opts.grid_format, prompt=original_prompt, seed=processed.seed, grid=True, p=p)
|
| 110 |
+
|
| 111 |
+
return processed
|
scripts/prompts_from_file.py
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import copy
|
| 2 |
+
import math
|
| 3 |
+
import os
|
| 4 |
+
import random
|
| 5 |
+
import sys
|
| 6 |
+
import traceback
|
| 7 |
+
import shlex
|
| 8 |
+
|
| 9 |
+
import modules.scripts as scripts
|
| 10 |
+
import gradio as gr
|
| 11 |
+
|
| 12 |
+
from modules import sd_samplers
|
| 13 |
+
from modules.processing import Processed, process_images
|
| 14 |
+
from PIL import Image
|
| 15 |
+
from modules.shared import opts, cmd_opts, state
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def process_string_tag(tag):
|
| 19 |
+
return tag
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def process_int_tag(tag):
|
| 23 |
+
return int(tag)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def process_float_tag(tag):
|
| 27 |
+
return float(tag)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def process_boolean_tag(tag):
|
| 31 |
+
return True if (tag == "true") else False
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
prompt_tags = {
|
| 35 |
+
"sd_model": None,
|
| 36 |
+
"outpath_samples": process_string_tag,
|
| 37 |
+
"outpath_grids": process_string_tag,
|
| 38 |
+
"prompt_for_display": process_string_tag,
|
| 39 |
+
"prompt": process_string_tag,
|
| 40 |
+
"negative_prompt": process_string_tag,
|
| 41 |
+
"styles": process_string_tag,
|
| 42 |
+
"seed": process_int_tag,
|
| 43 |
+
"subseed_strength": process_float_tag,
|
| 44 |
+
"subseed": process_int_tag,
|
| 45 |
+
"seed_resize_from_h": process_int_tag,
|
| 46 |
+
"seed_resize_from_w": process_int_tag,
|
| 47 |
+
"sampler_index": process_int_tag,
|
| 48 |
+
"sampler_name": process_string_tag,
|
| 49 |
+
"batch_size": process_int_tag,
|
| 50 |
+
"n_iter": process_int_tag,
|
| 51 |
+
"steps": process_int_tag,
|
| 52 |
+
"cfg_scale": process_float_tag,
|
| 53 |
+
"width": process_int_tag,
|
| 54 |
+
"height": process_int_tag,
|
| 55 |
+
"restore_faces": process_boolean_tag,
|
| 56 |
+
"tiling": process_boolean_tag,
|
| 57 |
+
"do_not_save_samples": process_boolean_tag,
|
| 58 |
+
"do_not_save_grid": process_boolean_tag
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def cmdargs(line):
|
| 63 |
+
args = shlex.split(line)
|
| 64 |
+
pos = 0
|
| 65 |
+
res = {}
|
| 66 |
+
|
| 67 |
+
while pos < len(args):
|
| 68 |
+
arg = args[pos]
|
| 69 |
+
|
| 70 |
+
assert arg.startswith("--"), f'must start with "--": {arg}'
|
| 71 |
+
assert pos+1 < len(args), f'missing argument for command line option {arg}'
|
| 72 |
+
|
| 73 |
+
tag = arg[2:]
|
| 74 |
+
|
| 75 |
+
if tag == "prompt" or tag == "negative_prompt":
|
| 76 |
+
pos += 1
|
| 77 |
+
prompt = args[pos]
|
| 78 |
+
pos += 1
|
| 79 |
+
while pos < len(args) and not args[pos].startswith("--"):
|
| 80 |
+
prompt += " "
|
| 81 |
+
prompt += args[pos]
|
| 82 |
+
pos += 1
|
| 83 |
+
res[tag] = prompt
|
| 84 |
+
continue
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
func = prompt_tags.get(tag, None)
|
| 88 |
+
assert func, f'unknown commandline option: {arg}'
|
| 89 |
+
|
| 90 |
+
val = args[pos+1]
|
| 91 |
+
if tag == "sampler_name":
|
| 92 |
+
val = sd_samplers.samplers_map.get(val.lower(), None)
|
| 93 |
+
|
| 94 |
+
res[tag] = func(val)
|
| 95 |
+
|
| 96 |
+
pos += 2
|
| 97 |
+
|
| 98 |
+
return res
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def load_prompt_file(file):
|
| 102 |
+
if file is None:
|
| 103 |
+
lines = []
|
| 104 |
+
else:
|
| 105 |
+
lines = [x.strip() for x in file.decode('utf8', errors='ignore').split("\n")]
|
| 106 |
+
|
| 107 |
+
return None, "\n".join(lines), gr.update(lines=7)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class Script(scripts.Script):
|
| 111 |
+
def title(self):
|
| 112 |
+
return "Prompts from file or textbox"
|
| 113 |
+
|
| 114 |
+
def ui(self, is_img2img):
|
| 115 |
+
checkbox_iterate = gr.Checkbox(label="Iterate seed every line", value=False, elem_id=self.elem_id("checkbox_iterate"))
|
| 116 |
+
checkbox_iterate_batch = gr.Checkbox(label="Use same random seed for all lines", value=False, elem_id=self.elem_id("checkbox_iterate_batch"))
|
| 117 |
+
|
| 118 |
+
prompt_txt = gr.Textbox(label="List of prompt inputs", lines=1, elem_id=self.elem_id("prompt_txt"))
|
| 119 |
+
file = gr.File(label="Upload prompt inputs", type='binary', elem_id=self.elem_id("file"))
|
| 120 |
+
|
| 121 |
+
file.change(fn=load_prompt_file, inputs=[file], outputs=[file, prompt_txt, prompt_txt])
|
| 122 |
+
|
| 123 |
+
# We start at one line. When the text changes, we jump to seven lines, or two lines if no \n.
|
| 124 |
+
# We don't shrink back to 1, because that causes the control to ignore [enter], and it may
|
| 125 |
+
# be unclear to the user that shift-enter is needed.
|
| 126 |
+
prompt_txt.change(lambda tb: gr.update(lines=7) if ("\n" in tb) else gr.update(lines=2), inputs=[prompt_txt], outputs=[prompt_txt])
|
| 127 |
+
return [checkbox_iterate, checkbox_iterate_batch, prompt_txt]
|
| 128 |
+
|
| 129 |
+
def run(self, p, checkbox_iterate, checkbox_iterate_batch, prompt_txt: str):
|
| 130 |
+
lines = [x.strip() for x in prompt_txt.splitlines()]
|
| 131 |
+
lines = [x for x in lines if len(x) > 0]
|
| 132 |
+
|
| 133 |
+
p.do_not_save_grid = True
|
| 134 |
+
|
| 135 |
+
job_count = 0
|
| 136 |
+
jobs = []
|
| 137 |
+
|
| 138 |
+
for line in lines:
|
| 139 |
+
if "--" in line:
|
| 140 |
+
try:
|
| 141 |
+
args = cmdargs(line)
|
| 142 |
+
except Exception:
|
| 143 |
+
print(f"Error parsing line {line} as commandline:", file=sys.stderr)
|
| 144 |
+
print(traceback.format_exc(), file=sys.stderr)
|
| 145 |
+
args = {"prompt": line}
|
| 146 |
+
else:
|
| 147 |
+
args = {"prompt": line}
|
| 148 |
+
|
| 149 |
+
job_count += args.get("n_iter", p.n_iter)
|
| 150 |
+
|
| 151 |
+
jobs.append(args)
|
| 152 |
+
|
| 153 |
+
print(f"Will process {len(lines)} lines in {job_count} jobs.")
|
| 154 |
+
if (checkbox_iterate or checkbox_iterate_batch) and p.seed == -1:
|
| 155 |
+
p.seed = int(random.randrange(4294967294))
|
| 156 |
+
|
| 157 |
+
state.job_count = job_count
|
| 158 |
+
|
| 159 |
+
images = []
|
| 160 |
+
all_prompts = []
|
| 161 |
+
infotexts = []
|
| 162 |
+
for n, args in enumerate(jobs):
|
| 163 |
+
state.job = f"{state.job_no + 1} out of {state.job_count}"
|
| 164 |
+
|
| 165 |
+
copy_p = copy.copy(p)
|
| 166 |
+
for k, v in args.items():
|
| 167 |
+
setattr(copy_p, k, v)
|
| 168 |
+
|
| 169 |
+
proc = process_images(copy_p)
|
| 170 |
+
images += proc.images
|
| 171 |
+
|
| 172 |
+
if checkbox_iterate:
|
| 173 |
+
p.seed = p.seed + (p.batch_size * p.n_iter)
|
| 174 |
+
all_prompts += proc.all_prompts
|
| 175 |
+
infotexts += proc.infotexts
|
| 176 |
+
|
| 177 |
+
return Processed(p, images, p.seed, "", all_prompts=all_prompts, infotexts=infotexts)
|
scripts/sd_upscale.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
|
| 3 |
+
import modules.scripts as scripts
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
from modules import processing, shared, sd_samplers, images, devices
|
| 8 |
+
from modules.processing import Processed
|
| 9 |
+
from modules.shared import opts, cmd_opts, state
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Script(scripts.Script):
|
| 13 |
+
def title(self):
|
| 14 |
+
return "SD upscale"
|
| 15 |
+
|
| 16 |
+
def show(self, is_img2img):
|
| 17 |
+
return is_img2img
|
| 18 |
+
|
| 19 |
+
def ui(self, is_img2img):
|
| 20 |
+
info = gr.HTML("<p style=\"margin-bottom:0.75em\">Will upscale the image by the selected scale factor; use width and height sliders to set tile size</p>")
|
| 21 |
+
overlap = gr.Slider(minimum=0, maximum=256, step=16, label='Tile overlap', value=64, elem_id=self.elem_id("overlap"))
|
| 22 |
+
scale_factor = gr.Slider(minimum=1.0, maximum=4.0, step=0.05, label='Scale Factor', value=2.0, elem_id=self.elem_id("scale_factor"))
|
| 23 |
+
upscaler_index = gr.Radio(label='Upscaler', choices=[x.name for x in shared.sd_upscalers], value=shared.sd_upscalers[0].name, type="index", elem_id=self.elem_id("upscaler_index"))
|
| 24 |
+
|
| 25 |
+
return [info, overlap, upscaler_index, scale_factor]
|
| 26 |
+
|
| 27 |
+
def run(self, p, _, overlap, upscaler_index, scale_factor):
|
| 28 |
+
if isinstance(upscaler_index, str):
|
| 29 |
+
upscaler_index = [x.name.lower() for x in shared.sd_upscalers].index(upscaler_index.lower())
|
| 30 |
+
processing.fix_seed(p)
|
| 31 |
+
upscaler = shared.sd_upscalers[upscaler_index]
|
| 32 |
+
|
| 33 |
+
p.extra_generation_params["SD upscale overlap"] = overlap
|
| 34 |
+
p.extra_generation_params["SD upscale upscaler"] = upscaler.name
|
| 35 |
+
|
| 36 |
+
initial_info = None
|
| 37 |
+
seed = p.seed
|
| 38 |
+
|
| 39 |
+
init_img = p.init_images[0]
|
| 40 |
+
init_img = images.flatten(init_img, opts.img2img_background_color)
|
| 41 |
+
|
| 42 |
+
if upscaler.name != "None":
|
| 43 |
+
img = upscaler.scaler.upscale(init_img, scale_factor, upscaler.data_path)
|
| 44 |
+
else:
|
| 45 |
+
img = init_img
|
| 46 |
+
|
| 47 |
+
devices.torch_gc()
|
| 48 |
+
|
| 49 |
+
grid = images.split_grid(img, tile_w=p.width, tile_h=p.height, overlap=overlap)
|
| 50 |
+
|
| 51 |
+
batch_size = p.batch_size
|
| 52 |
+
upscale_count = p.n_iter
|
| 53 |
+
p.n_iter = 1
|
| 54 |
+
p.do_not_save_grid = True
|
| 55 |
+
p.do_not_save_samples = True
|
| 56 |
+
|
| 57 |
+
work = []
|
| 58 |
+
|
| 59 |
+
for y, h, row in grid.tiles:
|
| 60 |
+
for tiledata in row:
|
| 61 |
+
work.append(tiledata[2])
|
| 62 |
+
|
| 63 |
+
batch_count = math.ceil(len(work) / batch_size)
|
| 64 |
+
state.job_count = batch_count * upscale_count
|
| 65 |
+
|
| 66 |
+
print(f"SD upscaling will process a total of {len(work)} images tiled as {len(grid.tiles[0][2])}x{len(grid.tiles)} per upscale in a total of {state.job_count} batches.")
|
| 67 |
+
|
| 68 |
+
result_images = []
|
| 69 |
+
for n in range(upscale_count):
|
| 70 |
+
start_seed = seed + n
|
| 71 |
+
p.seed = start_seed
|
| 72 |
+
|
| 73 |
+
work_results = []
|
| 74 |
+
for i in range(batch_count):
|
| 75 |
+
p.batch_size = batch_size
|
| 76 |
+
p.init_images = work[i * batch_size:(i + 1) * batch_size]
|
| 77 |
+
|
| 78 |
+
state.job = f"Batch {i + 1 + n * batch_count} out of {state.job_count}"
|
| 79 |
+
processed = processing.process_images(p)
|
| 80 |
+
|
| 81 |
+
if initial_info is None:
|
| 82 |
+
initial_info = processed.info
|
| 83 |
+
|
| 84 |
+
p.seed = processed.seed + 1
|
| 85 |
+
work_results += processed.images
|
| 86 |
+
|
| 87 |
+
image_index = 0
|
| 88 |
+
for y, h, row in grid.tiles:
|
| 89 |
+
for tiledata in row:
|
| 90 |
+
tiledata[2] = work_results[image_index] if image_index < len(work_results) else Image.new("RGB", (p.width, p.height))
|
| 91 |
+
image_index += 1
|
| 92 |
+
|
| 93 |
+
combined_image = images.combine_grid(grid)
|
| 94 |
+
result_images.append(combined_image)
|
| 95 |
+
|
| 96 |
+
if opts.samples_save:
|
| 97 |
+
images.save_image(combined_image, p.outpath_samples, "", start_seed, p.prompt, opts.samples_format, info=initial_info, p=p)
|
| 98 |
+
|
| 99 |
+
processed = Processed(p, result_images, seed, initial_info)
|
| 100 |
+
|
| 101 |
+
return processed
|
scripts/xyz_grid.py
ADDED
|
@@ -0,0 +1,685 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import namedtuple
|
| 2 |
+
from copy import copy
|
| 3 |
+
from itertools import permutations, chain
|
| 4 |
+
import random
|
| 5 |
+
import csv
|
| 6 |
+
from io import StringIO
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
import modules.scripts as scripts
|
| 11 |
+
import gradio as gr
|
| 12 |
+
|
| 13 |
+
from modules import images, paths, sd_samplers, processing, sd_models, sd_vae
|
| 14 |
+
from modules.processing import process_images, Processed, StableDiffusionProcessingTxt2Img
|
| 15 |
+
from modules.shared import opts, cmd_opts, state
|
| 16 |
+
import modules.shared as shared
|
| 17 |
+
import modules.sd_samplers
|
| 18 |
+
import modules.sd_models
|
| 19 |
+
import modules.sd_vae
|
| 20 |
+
import glob
|
| 21 |
+
import os
|
| 22 |
+
import re
|
| 23 |
+
|
| 24 |
+
from modules.ui_components import ToolButton
|
| 25 |
+
|
| 26 |
+
fill_values_symbol = "\U0001f4d2" # 📒
|
| 27 |
+
|
| 28 |
+
AxisInfo = namedtuple('AxisInfo', ['axis', 'values'])
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def apply_field(field):
|
| 32 |
+
def fun(p, x, xs):
|
| 33 |
+
setattr(p, field, x)
|
| 34 |
+
|
| 35 |
+
return fun
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def apply_prompt(p, x, xs):
|
| 39 |
+
if xs[0] not in p.prompt and xs[0] not in p.negative_prompt:
|
| 40 |
+
raise RuntimeError(f"Prompt S/R did not find {xs[0]} in prompt or negative prompt.")
|
| 41 |
+
|
| 42 |
+
p.prompt = p.prompt.replace(xs[0], x)
|
| 43 |
+
p.negative_prompt = p.negative_prompt.replace(xs[0], x)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def apply_order(p, x, xs):
|
| 47 |
+
token_order = []
|
| 48 |
+
|
| 49 |
+
# Initally grab the tokens from the prompt, so they can be replaced in order of earliest seen
|
| 50 |
+
for token in x:
|
| 51 |
+
token_order.append((p.prompt.find(token), token))
|
| 52 |
+
|
| 53 |
+
token_order.sort(key=lambda t: t[0])
|
| 54 |
+
|
| 55 |
+
prompt_parts = []
|
| 56 |
+
|
| 57 |
+
# Split the prompt up, taking out the tokens
|
| 58 |
+
for _, token in token_order:
|
| 59 |
+
n = p.prompt.find(token)
|
| 60 |
+
prompt_parts.append(p.prompt[0:n])
|
| 61 |
+
p.prompt = p.prompt[n + len(token):]
|
| 62 |
+
|
| 63 |
+
# Rebuild the prompt with the tokens in the order we want
|
| 64 |
+
prompt_tmp = ""
|
| 65 |
+
for idx, part in enumerate(prompt_parts):
|
| 66 |
+
prompt_tmp += part
|
| 67 |
+
prompt_tmp += x[idx]
|
| 68 |
+
p.prompt = prompt_tmp + p.prompt
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def apply_sampler(p, x, xs):
|
| 72 |
+
sampler_name = sd_samplers.samplers_map.get(x.lower(), None)
|
| 73 |
+
if sampler_name is None:
|
| 74 |
+
raise RuntimeError(f"Unknown sampler: {x}")
|
| 75 |
+
|
| 76 |
+
p.sampler_name = sampler_name
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def confirm_samplers(p, xs):
|
| 80 |
+
for x in xs:
|
| 81 |
+
if x.lower() not in sd_samplers.samplers_map:
|
| 82 |
+
raise RuntimeError(f"Unknown sampler: {x}")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def apply_checkpoint(p, x, xs):
|
| 86 |
+
info = modules.sd_models.get_closet_checkpoint_match(x)
|
| 87 |
+
if info is None:
|
| 88 |
+
raise RuntimeError(f"Unknown checkpoint: {x}")
|
| 89 |
+
modules.sd_models.reload_model_weights(shared.sd_model, info)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def confirm_checkpoints(p, xs):
|
| 93 |
+
for x in xs:
|
| 94 |
+
if modules.sd_models.get_closet_checkpoint_match(x) is None:
|
| 95 |
+
raise RuntimeError(f"Unknown checkpoint: {x}")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def apply_clip_skip(p, x, xs):
|
| 99 |
+
opts.data["CLIP_stop_at_last_layers"] = x
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def apply_upscale_latent_space(p, x, xs):
|
| 103 |
+
if x.lower().strip() != '0':
|
| 104 |
+
opts.data["use_scale_latent_for_hires_fix"] = True
|
| 105 |
+
else:
|
| 106 |
+
opts.data["use_scale_latent_for_hires_fix"] = False
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def find_vae(name: str):
|
| 110 |
+
if name.lower() in ['auto', 'automatic']:
|
| 111 |
+
return modules.sd_vae.unspecified
|
| 112 |
+
if name.lower() == 'none':
|
| 113 |
+
return None
|
| 114 |
+
else:
|
| 115 |
+
choices = [x for x in sorted(modules.sd_vae.vae_dict, key=lambda x: len(x)) if name.lower().strip() in x.lower()]
|
| 116 |
+
if len(choices) == 0:
|
| 117 |
+
print(f"No VAE found for {name}; using automatic")
|
| 118 |
+
return modules.sd_vae.unspecified
|
| 119 |
+
else:
|
| 120 |
+
return modules.sd_vae.vae_dict[choices[0]]
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def apply_vae(p, x, xs):
|
| 124 |
+
modules.sd_vae.reload_vae_weights(shared.sd_model, vae_file=find_vae(x))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def apply_styles(p: StableDiffusionProcessingTxt2Img, x: str, _):
|
| 128 |
+
p.styles.extend(x.split(','))
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def apply_uni_pc_order(p, x, xs):
|
| 132 |
+
opts.data["uni_pc_order"] = min(x, p.steps - 1)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def apply_face_restore(p, opt, x):
|
| 136 |
+
opt = opt.lower()
|
| 137 |
+
if opt == 'codeformer':
|
| 138 |
+
is_active = True
|
| 139 |
+
p.face_restoration_model = 'CodeFormer'
|
| 140 |
+
elif opt == 'gfpgan':
|
| 141 |
+
is_active = True
|
| 142 |
+
p.face_restoration_model = 'GFPGAN'
|
| 143 |
+
else:
|
| 144 |
+
is_active = opt in ('true', 'yes', 'y', '1')
|
| 145 |
+
|
| 146 |
+
p.restore_faces = is_active
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def format_value_add_label(p, opt, x):
|
| 150 |
+
if type(x) == float:
|
| 151 |
+
x = round(x, 8)
|
| 152 |
+
|
| 153 |
+
return f"{opt.label}: {x}"
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def format_value(p, opt, x):
|
| 157 |
+
if type(x) == float:
|
| 158 |
+
x = round(x, 8)
|
| 159 |
+
return x
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def format_value_join_list(p, opt, x):
|
| 163 |
+
return ", ".join(x)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def do_nothing(p, x, xs):
|
| 167 |
+
pass
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def format_nothing(p, opt, x):
|
| 171 |
+
return ""
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def str_permutations(x):
|
| 175 |
+
"""dummy function for specifying it in AxisOption's type when you want to get a list of permutations"""
|
| 176 |
+
return x
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class AxisOption:
|
| 180 |
+
def __init__(self, label, type, apply, format_value=format_value_add_label, confirm=None, cost=0.0, choices=None):
|
| 181 |
+
self.label = label
|
| 182 |
+
self.type = type
|
| 183 |
+
self.apply = apply
|
| 184 |
+
self.format_value = format_value
|
| 185 |
+
self.confirm = confirm
|
| 186 |
+
self.cost = cost
|
| 187 |
+
self.choices = choices
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class AxisOptionImg2Img(AxisOption):
|
| 191 |
+
def __init__(self, *args, **kwargs):
|
| 192 |
+
super().__init__(*args, **kwargs)
|
| 193 |
+
self.is_img2img = True
|
| 194 |
+
|
| 195 |
+
class AxisOptionTxt2Img(AxisOption):
|
| 196 |
+
def __init__(self, *args, **kwargs):
|
| 197 |
+
super().__init__(*args, **kwargs)
|
| 198 |
+
self.is_img2img = False
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
axis_options = [
|
| 202 |
+
AxisOption("Nothing", str, do_nothing, format_value=format_nothing),
|
| 203 |
+
AxisOption("Seed", int, apply_field("seed")),
|
| 204 |
+
AxisOption("Var. seed", int, apply_field("subseed")),
|
| 205 |
+
AxisOption("Var. strength", float, apply_field("subseed_strength")),
|
| 206 |
+
AxisOption("Steps", int, apply_field("steps")),
|
| 207 |
+
AxisOptionTxt2Img("Hires steps", int, apply_field("hr_second_pass_steps")),
|
| 208 |
+
AxisOption("CFG Scale", float, apply_field("cfg_scale")),
|
| 209 |
+
AxisOptionImg2Img("Image CFG Scale", float, apply_field("image_cfg_scale")),
|
| 210 |
+
AxisOption("Prompt S/R", str, apply_prompt, format_value=format_value),
|
| 211 |
+
AxisOption("Prompt order", str_permutations, apply_order, format_value=format_value_join_list),
|
| 212 |
+
AxisOptionTxt2Img("Sampler", str, apply_sampler, format_value=format_value, confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers]),
|
| 213 |
+
AxisOptionImg2Img("Sampler", str, apply_sampler, format_value=format_value, confirm=confirm_samplers, choices=lambda: [x.name for x in sd_samplers.samplers_for_img2img]),
|
| 214 |
+
AxisOption("Checkpoint name", str, apply_checkpoint, format_value=format_value, confirm=confirm_checkpoints, cost=1.0, choices=lambda: list(sd_models.checkpoints_list)),
|
| 215 |
+
AxisOption("Sigma Churn", float, apply_field("s_churn")),
|
| 216 |
+
AxisOption("Sigma min", float, apply_field("s_tmin")),
|
| 217 |
+
AxisOption("Sigma max", float, apply_field("s_tmax")),
|
| 218 |
+
AxisOption("Sigma noise", float, apply_field("s_noise")),
|
| 219 |
+
AxisOption("Eta", float, apply_field("eta")),
|
| 220 |
+
AxisOption("Clip skip", int, apply_clip_skip),
|
| 221 |
+
AxisOption("Denoising", float, apply_field("denoising_strength")),
|
| 222 |
+
AxisOptionTxt2Img("Hires upscaler", str, apply_field("hr_upscaler"), choices=lambda: [*shared.latent_upscale_modes, *[x.name for x in shared.sd_upscalers]]),
|
| 223 |
+
AxisOptionImg2Img("Cond. Image Mask Weight", float, apply_field("inpainting_mask_weight")),
|
| 224 |
+
AxisOption("VAE", str, apply_vae, cost=0.7, choices=lambda: list(sd_vae.vae_dict)),
|
| 225 |
+
AxisOption("Styles", str, apply_styles, choices=lambda: list(shared.prompt_styles.styles)),
|
| 226 |
+
AxisOption("UniPC Order", int, apply_uni_pc_order, cost=0.5),
|
| 227 |
+
AxisOption("Face restore", str, apply_face_restore, format_value=format_value),
|
| 228 |
+
]
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
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):
|
| 232 |
+
hor_texts = [[images.GridAnnotation(x)] for x in x_labels]
|
| 233 |
+
ver_texts = [[images.GridAnnotation(y)] for y in y_labels]
|
| 234 |
+
title_texts = [[images.GridAnnotation(z)] for z in z_labels]
|
| 235 |
+
|
| 236 |
+
list_size = (len(xs) * len(ys) * len(zs))
|
| 237 |
+
|
| 238 |
+
processed_result = None
|
| 239 |
+
|
| 240 |
+
state.job_count = list_size * p.n_iter
|
| 241 |
+
|
| 242 |
+
def process_cell(x, y, z, ix, iy, iz):
|
| 243 |
+
nonlocal processed_result
|
| 244 |
+
|
| 245 |
+
def index(ix, iy, iz):
|
| 246 |
+
return ix + iy * len(xs) + iz * len(xs) * len(ys)
|
| 247 |
+
|
| 248 |
+
state.job = f"{index(ix, iy, iz) + 1} out of {list_size}"
|
| 249 |
+
|
| 250 |
+
processed: Processed = cell(x, y, z, ix, iy, iz)
|
| 251 |
+
|
| 252 |
+
if processed_result is None:
|
| 253 |
+
# Use our first processed result object as a template container to hold our full results
|
| 254 |
+
processed_result = copy(processed)
|
| 255 |
+
processed_result.images = [None] * list_size
|
| 256 |
+
processed_result.all_prompts = [None] * list_size
|
| 257 |
+
processed_result.all_seeds = [None] * list_size
|
| 258 |
+
processed_result.infotexts = [None] * list_size
|
| 259 |
+
processed_result.index_of_first_image = 1
|
| 260 |
+
|
| 261 |
+
idx = index(ix, iy, iz)
|
| 262 |
+
if processed.images:
|
| 263 |
+
# Non-empty list indicates some degree of success.
|
| 264 |
+
processed_result.images[idx] = processed.images[0]
|
| 265 |
+
processed_result.all_prompts[idx] = processed.prompt
|
| 266 |
+
processed_result.all_seeds[idx] = processed.seed
|
| 267 |
+
processed_result.infotexts[idx] = processed.infotexts[0]
|
| 268 |
+
else:
|
| 269 |
+
cell_mode = "P"
|
| 270 |
+
cell_size = (processed_result.width, processed_result.height)
|
| 271 |
+
if processed_result.images[0] is not None:
|
| 272 |
+
cell_mode = processed_result.images[0].mode
|
| 273 |
+
#This corrects size in case of batches:
|
| 274 |
+
cell_size = processed_result.images[0].size
|
| 275 |
+
processed_result.images[idx] = Image.new(cell_mode, cell_size)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
if first_axes_processed == 'x':
|
| 279 |
+
for ix, x in enumerate(xs):
|
| 280 |
+
if second_axes_processed == 'y':
|
| 281 |
+
for iy, y in enumerate(ys):
|
| 282 |
+
for iz, z in enumerate(zs):
|
| 283 |
+
process_cell(x, y, z, ix, iy, iz)
|
| 284 |
+
else:
|
| 285 |
+
for iz, z in enumerate(zs):
|
| 286 |
+
for iy, y in enumerate(ys):
|
| 287 |
+
process_cell(x, y, z, ix, iy, iz)
|
| 288 |
+
elif first_axes_processed == 'y':
|
| 289 |
+
for iy, y in enumerate(ys):
|
| 290 |
+
if second_axes_processed == 'x':
|
| 291 |
+
for ix, x in enumerate(xs):
|
| 292 |
+
for iz, z in enumerate(zs):
|
| 293 |
+
process_cell(x, y, z, ix, iy, iz)
|
| 294 |
+
else:
|
| 295 |
+
for iz, z in enumerate(zs):
|
| 296 |
+
for ix, x in enumerate(xs):
|
| 297 |
+
process_cell(x, y, z, ix, iy, iz)
|
| 298 |
+
elif first_axes_processed == 'z':
|
| 299 |
+
for iz, z in enumerate(zs):
|
| 300 |
+
if second_axes_processed == 'x':
|
| 301 |
+
for ix, x in enumerate(xs):
|
| 302 |
+
for iy, y in enumerate(ys):
|
| 303 |
+
process_cell(x, y, z, ix, iy, iz)
|
| 304 |
+
else:
|
| 305 |
+
for iy, y in enumerate(ys):
|
| 306 |
+
for ix, x in enumerate(xs):
|
| 307 |
+
process_cell(x, y, z, ix, iy, iz)
|
| 308 |
+
|
| 309 |
+
if not processed_result:
|
| 310 |
+
# Should never happen, I've only seen it on one of four open tabs and it needed to refresh.
|
| 311 |
+
print("Unexpected error: Processing could not begin, you may need to refresh the tab or restart the service.")
|
| 312 |
+
return Processed(p, [])
|
| 313 |
+
elif not any(processed_result.images):
|
| 314 |
+
print("Unexpected error: draw_xyz_grid failed to return even a single processed image")
|
| 315 |
+
return Processed(p, [])
|
| 316 |
+
|
| 317 |
+
z_count = len(zs)
|
| 318 |
+
sub_grids = [None] * z_count
|
| 319 |
+
for i in range(z_count):
|
| 320 |
+
start_index = (i * len(xs) * len(ys)) + i
|
| 321 |
+
end_index = start_index + len(xs) * len(ys)
|
| 322 |
+
grid = images.image_grid(processed_result.images[start_index:end_index], rows=len(ys))
|
| 323 |
+
if draw_legend:
|
| 324 |
+
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)
|
| 325 |
+
processed_result.images.insert(i, grid)
|
| 326 |
+
processed_result.all_prompts.insert(i, processed_result.all_prompts[start_index])
|
| 327 |
+
processed_result.all_seeds.insert(i, processed_result.all_seeds[start_index])
|
| 328 |
+
processed_result.infotexts.insert(i, processed_result.infotexts[start_index])
|
| 329 |
+
|
| 330 |
+
sub_grid_size = processed_result.images[0].size
|
| 331 |
+
z_grid = images.image_grid(processed_result.images[:z_count], rows=1)
|
| 332 |
+
if draw_legend:
|
| 333 |
+
z_grid = images.draw_grid_annotations(z_grid, sub_grid_size[0], sub_grid_size[1], title_texts, [[images.GridAnnotation()]])
|
| 334 |
+
processed_result.images.insert(0, z_grid)
|
| 335 |
+
#TODO: Deeper aspects of the program rely on grid info being misaligned between metadata arrays, which is not ideal.
|
| 336 |
+
#processed_result.all_prompts.insert(0, processed_result.all_prompts[0])
|
| 337 |
+
#processed_result.all_seeds.insert(0, processed_result.all_seeds[0])
|
| 338 |
+
processed_result.infotexts.insert(0, processed_result.infotexts[0])
|
| 339 |
+
|
| 340 |
+
return processed_result
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class SharedSettingsStackHelper(object):
|
| 344 |
+
def __enter__(self):
|
| 345 |
+
self.CLIP_stop_at_last_layers = opts.CLIP_stop_at_last_layers
|
| 346 |
+
self.vae = opts.sd_vae
|
| 347 |
+
self.uni_pc_order = opts.uni_pc_order
|
| 348 |
+
|
| 349 |
+
def __exit__(self, exc_type, exc_value, tb):
|
| 350 |
+
opts.data["sd_vae"] = self.vae
|
| 351 |
+
opts.data["uni_pc_order"] = self.uni_pc_order
|
| 352 |
+
modules.sd_models.reload_model_weights()
|
| 353 |
+
modules.sd_vae.reload_vae_weights()
|
| 354 |
+
|
| 355 |
+
opts.data["CLIP_stop_at_last_layers"] = self.CLIP_stop_at_last_layers
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
re_range = re.compile(r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\(([+-]\d+)\s*\))?\s*")
|
| 359 |
+
re_range_float = re.compile(r"\s*([+-]?\s*\d+(?:.\d*)?)\s*-\s*([+-]?\s*\d+(?:.\d*)?)(?:\s*\(([+-]\d+(?:.\d*)?)\s*\))?\s*")
|
| 360 |
+
|
| 361 |
+
re_range_count = re.compile(r"\s*([+-]?\s*\d+)\s*-\s*([+-]?\s*\d+)(?:\s*\[(\d+)\s*\])?\s*")
|
| 362 |
+
re_range_count_float = re.compile(r"\s*([+-]?\s*\d+(?:.\d*)?)\s*-\s*([+-]?\s*\d+(?:.\d*)?)(?:\s*\[(\d+(?:.\d*)?)\s*\])?\s*")
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class Script(scripts.Script):
|
| 366 |
+
def title(self):
|
| 367 |
+
return "X/Y/Z plot"
|
| 368 |
+
|
| 369 |
+
def ui(self, is_img2img):
|
| 370 |
+
self.current_axis_options = [x for x in axis_options if type(x) == AxisOption or x.is_img2img == is_img2img]
|
| 371 |
+
|
| 372 |
+
with gr.Row():
|
| 373 |
+
with gr.Column(scale=19):
|
| 374 |
+
with gr.Row():
|
| 375 |
+
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"))
|
| 376 |
+
x_values = gr.Textbox(label="X values", lines=1, elem_id=self.elem_id("x_values"))
|
| 377 |
+
fill_x_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_x_tool_button", visible=False)
|
| 378 |
+
|
| 379 |
+
with gr.Row():
|
| 380 |
+
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"))
|
| 381 |
+
y_values = gr.Textbox(label="Y values", lines=1, elem_id=self.elem_id("y_values"))
|
| 382 |
+
fill_y_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_y_tool_button", visible=False)
|
| 383 |
+
|
| 384 |
+
with gr.Row():
|
| 385 |
+
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"))
|
| 386 |
+
z_values = gr.Textbox(label="Z values", lines=1, elem_id=self.elem_id("z_values"))
|
| 387 |
+
fill_z_button = ToolButton(value=fill_values_symbol, elem_id="xyz_grid_fill_z_tool_button", visible=False)
|
| 388 |
+
|
| 389 |
+
with gr.Row(variant="compact", elem_id="axis_options"):
|
| 390 |
+
with gr.Column():
|
| 391 |
+
draw_legend = gr.Checkbox(label='Draw legend', value=True, elem_id=self.elem_id("draw_legend"))
|
| 392 |
+
no_fixed_seeds = gr.Checkbox(label='Keep -1 for seeds', value=False, elem_id=self.elem_id("no_fixed_seeds"))
|
| 393 |
+
with gr.Column():
|
| 394 |
+
include_lone_images = gr.Checkbox(label='Include Sub Images', value=False, elem_id=self.elem_id("include_lone_images"))
|
| 395 |
+
include_sub_grids = gr.Checkbox(label='Include Sub Grids', value=False, elem_id=self.elem_id("include_sub_grids"))
|
| 396 |
+
with gr.Column():
|
| 397 |
+
margin_size = gr.Slider(label="Grid margins (px)", minimum=0, maximum=500, value=0, step=2, elem_id=self.elem_id("margin_size"))
|
| 398 |
+
|
| 399 |
+
with gr.Row(variant="compact", elem_id="swap_axes"):
|
| 400 |
+
swap_xy_axes_button = gr.Button(value="Swap X/Y axes", elem_id="xy_grid_swap_axes_button")
|
| 401 |
+
swap_yz_axes_button = gr.Button(value="Swap Y/Z axes", elem_id="yz_grid_swap_axes_button")
|
| 402 |
+
swap_xz_axes_button = gr.Button(value="Swap X/Z axes", elem_id="xz_grid_swap_axes_button")
|
| 403 |
+
|
| 404 |
+
def swap_axes(axis1_type, axis1_values, axis2_type, axis2_values):
|
| 405 |
+
return self.current_axis_options[axis2_type].label, axis2_values, self.current_axis_options[axis1_type].label, axis1_values
|
| 406 |
+
|
| 407 |
+
xy_swap_args = [x_type, x_values, y_type, y_values]
|
| 408 |
+
swap_xy_axes_button.click(swap_axes, inputs=xy_swap_args, outputs=xy_swap_args)
|
| 409 |
+
yz_swap_args = [y_type, y_values, z_type, z_values]
|
| 410 |
+
swap_yz_axes_button.click(swap_axes, inputs=yz_swap_args, outputs=yz_swap_args)
|
| 411 |
+
xz_swap_args = [x_type, x_values, z_type, z_values]
|
| 412 |
+
swap_xz_axes_button.click(swap_axes, inputs=xz_swap_args, outputs=xz_swap_args)
|
| 413 |
+
|
| 414 |
+
def fill(x_type):
|
| 415 |
+
axis = self.current_axis_options[x_type]
|
| 416 |
+
return ", ".join(axis.choices()) if axis.choices else gr.update()
|
| 417 |
+
|
| 418 |
+
fill_x_button.click(fn=fill, inputs=[x_type], outputs=[x_values])
|
| 419 |
+
fill_y_button.click(fn=fill, inputs=[y_type], outputs=[y_values])
|
| 420 |
+
fill_z_button.click(fn=fill, inputs=[z_type], outputs=[z_values])
|
| 421 |
+
|
| 422 |
+
def select_axis(x_type):
|
| 423 |
+
return gr.Button.update(visible=self.current_axis_options[x_type].choices is not None)
|
| 424 |
+
|
| 425 |
+
x_type.change(fn=select_axis, inputs=[x_type], outputs=[fill_x_button])
|
| 426 |
+
y_type.change(fn=select_axis, inputs=[y_type], outputs=[fill_y_button])
|
| 427 |
+
z_type.change(fn=select_axis, inputs=[z_type], outputs=[fill_z_button])
|
| 428 |
+
|
| 429 |
+
self.infotext_fields = (
|
| 430 |
+
(x_type, "X Type"),
|
| 431 |
+
(x_values, "X Values"),
|
| 432 |
+
(y_type, "Y Type"),
|
| 433 |
+
(y_values, "Y Values"),
|
| 434 |
+
(z_type, "Z Type"),
|
| 435 |
+
(z_values, "Z Values"),
|
| 436 |
+
)
|
| 437 |
+
|
| 438 |
+
return [x_type, x_values, y_type, y_values, z_type, z_values, draw_legend, include_lone_images, include_sub_grids, no_fixed_seeds, margin_size]
|
| 439 |
+
|
| 440 |
+
def run(self, p, x_type, x_values, y_type, y_values, z_type, z_values, draw_legend, include_lone_images, include_sub_grids, no_fixed_seeds, margin_size):
|
| 441 |
+
if not no_fixed_seeds:
|
| 442 |
+
modules.processing.fix_seed(p)
|
| 443 |
+
|
| 444 |
+
if not opts.return_grid:
|
| 445 |
+
p.batch_size = 1
|
| 446 |
+
|
| 447 |
+
def process_axis(opt, vals):
|
| 448 |
+
if opt.label == 'Nothing':
|
| 449 |
+
return [0]
|
| 450 |
+
|
| 451 |
+
valslist = [x.strip() for x in chain.from_iterable(csv.reader(StringIO(vals))) if x]
|
| 452 |
+
|
| 453 |
+
if opt.type == int:
|
| 454 |
+
valslist_ext = []
|
| 455 |
+
|
| 456 |
+
for val in valslist:
|
| 457 |
+
m = re_range.fullmatch(val)
|
| 458 |
+
mc = re_range_count.fullmatch(val)
|
| 459 |
+
if m is not None:
|
| 460 |
+
start = int(m.group(1))
|
| 461 |
+
end = int(m.group(2))+1
|
| 462 |
+
step = int(m.group(3)) if m.group(3) is not None else 1
|
| 463 |
+
|
| 464 |
+
valslist_ext += list(range(start, end, step))
|
| 465 |
+
elif mc is not None:
|
| 466 |
+
start = int(mc.group(1))
|
| 467 |
+
end = int(mc.group(2))
|
| 468 |
+
num = int(mc.group(3)) if mc.group(3) is not None else 1
|
| 469 |
+
|
| 470 |
+
valslist_ext += [int(x) for x in np.linspace(start=start, stop=end, num=num).tolist()]
|
| 471 |
+
else:
|
| 472 |
+
valslist_ext.append(val)
|
| 473 |
+
|
| 474 |
+
valslist = valslist_ext
|
| 475 |
+
elif opt.type == float:
|
| 476 |
+
valslist_ext = []
|
| 477 |
+
|
| 478 |
+
for val in valslist:
|
| 479 |
+
m = re_range_float.fullmatch(val)
|
| 480 |
+
mc = re_range_count_float.fullmatch(val)
|
| 481 |
+
if m is not None:
|
| 482 |
+
start = float(m.group(1))
|
| 483 |
+
end = float(m.group(2))
|
| 484 |
+
step = float(m.group(3)) if m.group(3) is not None else 1
|
| 485 |
+
|
| 486 |
+
valslist_ext += np.arange(start, end + step, step).tolist()
|
| 487 |
+
elif mc is not None:
|
| 488 |
+
start = float(mc.group(1))
|
| 489 |
+
end = float(mc.group(2))
|
| 490 |
+
num = int(mc.group(3)) if mc.group(3) is not None else 1
|
| 491 |
+
|
| 492 |
+
valslist_ext += np.linspace(start=start, stop=end, num=num).tolist()
|
| 493 |
+
else:
|
| 494 |
+
valslist_ext.append(val)
|
| 495 |
+
|
| 496 |
+
valslist = valslist_ext
|
| 497 |
+
elif opt.type == str_permutations:
|
| 498 |
+
valslist = list(permutations(valslist))
|
| 499 |
+
|
| 500 |
+
valslist = [opt.type(x) for x in valslist]
|
| 501 |
+
|
| 502 |
+
# Confirm options are valid before starting
|
| 503 |
+
if opt.confirm:
|
| 504 |
+
opt.confirm(p, valslist)
|
| 505 |
+
|
| 506 |
+
return valslist
|
| 507 |
+
|
| 508 |
+
x_opt = self.current_axis_options[x_type]
|
| 509 |
+
xs = process_axis(x_opt, x_values)
|
| 510 |
+
|
| 511 |
+
y_opt = self.current_axis_options[y_type]
|
| 512 |
+
ys = process_axis(y_opt, y_values)
|
| 513 |
+
|
| 514 |
+
z_opt = self.current_axis_options[z_type]
|
| 515 |
+
zs = process_axis(z_opt, z_values)
|
| 516 |
+
|
| 517 |
+
# this could be moved to common code, but unlikely to be ever triggered anywhere else
|
| 518 |
+
Image.MAX_IMAGE_PIXELS = None # disable check in Pillow and rely on check below to allow large custom image sizes
|
| 519 |
+
grid_mp = round(len(xs) * len(ys) * len(zs) * p.width * p.height / 1000000)
|
| 520 |
+
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)'
|
| 521 |
+
|
| 522 |
+
def fix_axis_seeds(axis_opt, axis_list):
|
| 523 |
+
if axis_opt.label in ['Seed', 'Var. seed']:
|
| 524 |
+
return [int(random.randrange(4294967294)) if val is None or val == '' or val == -1 else val for val in axis_list]
|
| 525 |
+
else:
|
| 526 |
+
return axis_list
|
| 527 |
+
|
| 528 |
+
if not no_fixed_seeds:
|
| 529 |
+
xs = fix_axis_seeds(x_opt, xs)
|
| 530 |
+
ys = fix_axis_seeds(y_opt, ys)
|
| 531 |
+
zs = fix_axis_seeds(z_opt, zs)
|
| 532 |
+
|
| 533 |
+
if x_opt.label == 'Steps':
|
| 534 |
+
total_steps = sum(xs) * len(ys) * len(zs)
|
| 535 |
+
elif y_opt.label == 'Steps':
|
| 536 |
+
total_steps = sum(ys) * len(xs) * len(zs)
|
| 537 |
+
elif z_opt.label == 'Steps':
|
| 538 |
+
total_steps = sum(zs) * len(xs) * len(ys)
|
| 539 |
+
else:
|
| 540 |
+
total_steps = p.steps * len(xs) * len(ys) * len(zs)
|
| 541 |
+
|
| 542 |
+
if isinstance(p, StableDiffusionProcessingTxt2Img) and p.enable_hr:
|
| 543 |
+
if x_opt.label == "Hires steps":
|
| 544 |
+
total_steps += sum(xs) * len(ys) * len(zs)
|
| 545 |
+
elif y_opt.label == "Hires steps":
|
| 546 |
+
total_steps += sum(ys) * len(xs) * len(zs)
|
| 547 |
+
elif z_opt.label == "Hires steps":
|
| 548 |
+
total_steps += sum(zs) * len(xs) * len(ys)
|
| 549 |
+
elif p.hr_second_pass_steps:
|
| 550 |
+
total_steps += p.hr_second_pass_steps * len(xs) * len(ys) * len(zs)
|
| 551 |
+
else:
|
| 552 |
+
total_steps *= 2
|
| 553 |
+
|
| 554 |
+
total_steps *= p.n_iter
|
| 555 |
+
|
| 556 |
+
image_cell_count = p.n_iter * p.batch_size
|
| 557 |
+
cell_console_text = f"; {image_cell_count} images per cell" if image_cell_count > 1 else ""
|
| 558 |
+
plural_s = 's' if len(zs) > 1 else ''
|
| 559 |
+
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})")
|
| 560 |
+
shared.total_tqdm.updateTotal(total_steps)
|
| 561 |
+
|
| 562 |
+
state.xyz_plot_x = AxisInfo(x_opt, xs)
|
| 563 |
+
state.xyz_plot_y = AxisInfo(y_opt, ys)
|
| 564 |
+
state.xyz_plot_z = AxisInfo(z_opt, zs)
|
| 565 |
+
|
| 566 |
+
# If one of the axes is very slow to change between (like SD model
|
| 567 |
+
# checkpoint), then make sure it is in the outer iteration of the nested
|
| 568 |
+
# `for` loop.
|
| 569 |
+
first_axes_processed = 'z'
|
| 570 |
+
second_axes_processed = 'y'
|
| 571 |
+
if x_opt.cost > y_opt.cost and x_opt.cost > z_opt.cost:
|
| 572 |
+
first_axes_processed = 'x'
|
| 573 |
+
if y_opt.cost > z_opt.cost:
|
| 574 |
+
second_axes_processed = 'y'
|
| 575 |
+
else:
|
| 576 |
+
second_axes_processed = 'z'
|
| 577 |
+
elif y_opt.cost > x_opt.cost and y_opt.cost > z_opt.cost:
|
| 578 |
+
first_axes_processed = 'y'
|
| 579 |
+
if x_opt.cost > z_opt.cost:
|
| 580 |
+
second_axes_processed = 'x'
|
| 581 |
+
else:
|
| 582 |
+
second_axes_processed = 'z'
|
| 583 |
+
elif z_opt.cost > x_opt.cost and z_opt.cost > y_opt.cost:
|
| 584 |
+
first_axes_processed = 'z'
|
| 585 |
+
if x_opt.cost > y_opt.cost:
|
| 586 |
+
second_axes_processed = 'x'
|
| 587 |
+
else:
|
| 588 |
+
second_axes_processed = 'y'
|
| 589 |
+
|
| 590 |
+
grid_infotext = [None] * (1 + len(zs))
|
| 591 |
+
|
| 592 |
+
def cell(x, y, z, ix, iy, iz):
|
| 593 |
+
if shared.state.interrupted:
|
| 594 |
+
return Processed(p, [], p.seed, "")
|
| 595 |
+
|
| 596 |
+
pc = copy(p)
|
| 597 |
+
pc.styles = pc.styles[:]
|
| 598 |
+
x_opt.apply(pc, x, xs)
|
| 599 |
+
y_opt.apply(pc, y, ys)
|
| 600 |
+
z_opt.apply(pc, z, zs)
|
| 601 |
+
|
| 602 |
+
res = process_images(pc)
|
| 603 |
+
|
| 604 |
+
# Sets subgrid infotexts
|
| 605 |
+
subgrid_index = 1 + iz
|
| 606 |
+
if grid_infotext[subgrid_index] is None and ix == 0 and iy == 0:
|
| 607 |
+
pc.extra_generation_params = copy(pc.extra_generation_params)
|
| 608 |
+
pc.extra_generation_params['Script'] = self.title()
|
| 609 |
+
|
| 610 |
+
if x_opt.label != 'Nothing':
|
| 611 |
+
pc.extra_generation_params["X Type"] = x_opt.label
|
| 612 |
+
pc.extra_generation_params["X Values"] = x_values
|
| 613 |
+
if x_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds:
|
| 614 |
+
pc.extra_generation_params["Fixed X Values"] = ", ".join([str(x) for x in xs])
|
| 615 |
+
|
| 616 |
+
if y_opt.label != 'Nothing':
|
| 617 |
+
pc.extra_generation_params["Y Type"] = y_opt.label
|
| 618 |
+
pc.extra_generation_params["Y Values"] = y_values
|
| 619 |
+
if y_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds:
|
| 620 |
+
pc.extra_generation_params["Fixed Y Values"] = ", ".join([str(y) for y in ys])
|
| 621 |
+
|
| 622 |
+
grid_infotext[subgrid_index] = processing.create_infotext(pc, pc.all_prompts, pc.all_seeds, pc.all_subseeds)
|
| 623 |
+
|
| 624 |
+
# Sets main grid infotext
|
| 625 |
+
if grid_infotext[0] is None and ix == 0 and iy == 0 and iz == 0:
|
| 626 |
+
pc.extra_generation_params = copy(pc.extra_generation_params)
|
| 627 |
+
|
| 628 |
+
if z_opt.label != 'Nothing':
|
| 629 |
+
pc.extra_generation_params["Z Type"] = z_opt.label
|
| 630 |
+
pc.extra_generation_params["Z Values"] = z_values
|
| 631 |
+
if z_opt.label in ["Seed", "Var. seed"] and not no_fixed_seeds:
|
| 632 |
+
pc.extra_generation_params["Fixed Z Values"] = ", ".join([str(z) for z in zs])
|
| 633 |
+
|
| 634 |
+
grid_infotext[0] = processing.create_infotext(pc, pc.all_prompts, pc.all_seeds, pc.all_subseeds)
|
| 635 |
+
|
| 636 |
+
return res
|
| 637 |
+
|
| 638 |
+
with SharedSettingsStackHelper():
|
| 639 |
+
processed = draw_xyz_grid(
|
| 640 |
+
p,
|
| 641 |
+
xs=xs,
|
| 642 |
+
ys=ys,
|
| 643 |
+
zs=zs,
|
| 644 |
+
x_labels=[x_opt.format_value(p, x_opt, x) for x in xs],
|
| 645 |
+
y_labels=[y_opt.format_value(p, y_opt, y) for y in ys],
|
| 646 |
+
z_labels=[z_opt.format_value(p, z_opt, z) for z in zs],
|
| 647 |
+
cell=cell,
|
| 648 |
+
draw_legend=draw_legend,
|
| 649 |
+
include_lone_images=include_lone_images,
|
| 650 |
+
include_sub_grids=include_sub_grids,
|
| 651 |
+
first_axes_processed=first_axes_processed,
|
| 652 |
+
second_axes_processed=second_axes_processed,
|
| 653 |
+
margin_size=margin_size
|
| 654 |
+
)
|
| 655 |
+
|
| 656 |
+
if not processed.images:
|
| 657 |
+
# It broke, no further handling needed.
|
| 658 |
+
return processed
|
| 659 |
+
|
| 660 |
+
z_count = len(zs)
|
| 661 |
+
|
| 662 |
+
# Set the grid infotexts to the real ones with extra_generation_params (1 main grid + z_count sub-grids)
|
| 663 |
+
processed.infotexts[:1+z_count] = grid_infotext[:1+z_count]
|
| 664 |
+
|
| 665 |
+
if not include_lone_images:
|
| 666 |
+
# Don't need sub-images anymore, drop from list:
|
| 667 |
+
processed.images = processed.images[:z_count+1]
|
| 668 |
+
|
| 669 |
+
if opts.grid_save:
|
| 670 |
+
# Auto-save main and sub-grids:
|
| 671 |
+
grid_count = z_count + 1 if z_count > 1 else 1
|
| 672 |
+
for g in range(grid_count):
|
| 673 |
+
#TODO: See previous comment about intentional data misalignment.
|
| 674 |
+
adj_g = g-1 if g > 0 else g
|
| 675 |
+
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)
|
| 676 |
+
|
| 677 |
+
if not include_sub_grids:
|
| 678 |
+
# Done with sub-grids, drop all related information:
|
| 679 |
+
for sg in range(z_count):
|
| 680 |
+
del processed.images[1]
|
| 681 |
+
del processed.all_prompts[1]
|
| 682 |
+
del processed.all_seeds[1]
|
| 683 |
+
del processed.infotexts[1]
|
| 684 |
+
|
| 685 |
+
return processed
|