ruff linting fixes

This commit is contained in:
Vladimir Mandic
2023-06-13 12:22:39 -04:00
parent cb307399dd
commit 1d9e490ef9
33 changed files with 86 additions and 86 deletions
+5 -1
View File
@@ -2,6 +2,9 @@
## Update for 06/13/2023
One bigger update...
Both some **new functionality** as well as **massive merges** from upstream
- new cache for models/lora/lyco metadata: `metadata.json`
drastically reduces disk access on app startup
- allow saving of **ui default values**
@@ -10,7 +13,8 @@
default is to auto-load model on startup, can be changed in settings -> stable diffusion
if disabled, model will be loaded on first request, e.g. when you click generate
- updated `accelerate` and `xformers`
- huge nubmer of changes ported from a1111 upstream
- huge nubmer of changes ported from **A1111** upstream
this was a massive merge
hopefully this does not cause any regressions
+4 -4
View File
@@ -163,8 +163,8 @@ async def lora(params):
if not os.path.exists(folder):
log.error({ 'lora directory not found': folder })
return
models1 = [f for f in Path(folder).glob('*.safetensors')]
models2 = [f for f in Path(folder).glob('*.ckpt')]
models1 = list(Path(folder).glob('*.safetensors'))
models2 = list(Path(folder).glob('*.ckpt'))
models = [f.stem for f in models1 + models2]
log.info({ 'loras': len(models) })
for model in models:
@@ -204,8 +204,8 @@ async def lyco(params):
if not os.path.exists(folder):
log.error({ 'lyco directory not found': folder })
return
models1 = [f for f in Path(folder).glob('*.safetensors')]
models2 = [f for f in Path(folder).glob('*.ckpt')]
models1 = list(Path(folder).glob('*.safetensors'))
models2 = list(Path(folder).glob('*.ckpt'))
models = [f.stem for f in models1 + models2]
log.info({ 'lycos': len(models) })
for model in models:
+2 -2
View File
@@ -72,7 +72,7 @@ def exif(info, i = None, op = 'generate'):
template += ' | grid {num}'.format(num = sd.generate.batch_size * sd.generate.n_iter) # pylint: disable=consider-using-f-string
ifd = ImageFileDirectory_v2()
exif_stream = io.BytesIO()
_TAGS = dict(((v, k) for k, v in TAGS.items())) # enumerate possible exif tags
_TAGS = {v: k for k, v in TAGS.items()} # enumerate possible exif tags
ifd[_TAGS['ImageDescription']] = template
ifd.save(exif_stream)
val = b'Exif\x00\x00' + exif_stream.getvalue()
@@ -337,7 +337,7 @@ async def main():
scheduler = sampler(params, options)
t0 = time.perf_counter()
data = await generate() # generate returns list of images
if not 'image' in data:
if 'image' not in data:
break
stats.images += len(data.image)
t1 = time.perf_counter()
+3 -3
View File
@@ -16,8 +16,8 @@ class Exif: # pylint: disable=single-string-used-for-slots
def __init__(self, image = None):
super(Exif, self).__setattr__('exif', Image.Exif())
self.pnginfo = PngImagePlugin.PngInfo()
self.tags = {**dict(((k, v) for k, v in ExifTags.TAGS.items())), **dict(((k, v) for k, v in ExifTags.GPSTAGS.items()))}
self.ids = {**dict(((v, k) for k, v in ExifTags.TAGS.items())), **dict(((v, k) for k, v in ExifTags.GPSTAGS.items()))}
self.tags = {**dict(ExifTags.TAGS.items()), **dict(ExifTags.GPSTAGS.items())}
self.ids = {**{v: k for k, v in ExifTags.TAGS.items()}, **{v: k for k, v in ExifTags.GPSTAGS.items()}}
if image is not None:
self.load(image)
@@ -101,6 +101,6 @@ if __name__ == '__main__':
if os.path.isfile(fn):
read_exif(fn)
elif os.path.isdir(fn):
for root, dirs, files in os.walk(fn):
for root, _dirs, files in os.walk(fn):
for file in files:
read_exif(os.path.join(root, file))
+1 -1
View File
@@ -39,7 +39,7 @@ def get_exif(image):
def set_exif(d: dict):
ifd = ImageFileDirectory_v2()
_TAGS = dict(((v, k) for k, v in TAGS.items())) # enumerate possible exif tags
_TAGS = {v: k for k, v in TAGS.items()} # enumerate possible exif tags
for k, v in d.items():
ifd[_TAGS[k]] = v
exif_stream = io.BytesIO()
+3 -3
View File
@@ -21,7 +21,7 @@ all_images_by_type = {}
class Result(object):
def __init__(self, typ: str, fn: str, tag: str = None, requested: list = []):
def __init__(self, typ: str, fn: str, tag: str = None, requested: list = []): # noqa: B006
self.type = typ
self.input = fn
self.output = ''
@@ -139,7 +139,7 @@ def upscale_restore_image(res: Result, upscale: bool = False, restore: bool = Fa
res.ops.append('upscale')
if restore:
kwargs.codeformer_visibility = 1.0
kwargs.codeformer_weight: 0.2
kwargs.codeformer_weight = 0.2
res.ops.append('restore')
if upscale or restore:
result = sdapi.postsync('/sdapi/v1/extra-single-image', kwargs)
@@ -260,7 +260,7 @@ def save_image(res: Result, folder: str):
return res
def file(filename: str, folder: str, tag = None, requested = []):
def file(filename: str, folder: str, tag = None, requested = []): # noqa: B006
# initialize result dict
res = Result(fn = filename, typ='unknown', tag=tag, requested = requested)
# open image
+5 -5
View File
@@ -59,9 +59,9 @@ if __name__ == '__main__':
results = {}
times = []
print('eager initial eval:', timed(lambda: evaluate(model, inp))[1])
for i in range(N_ITERS):
for _i in range(N_ITERS):
inp = generate_data(16)[0]
_res, time = timed(lambda: evaluate(model, inp))
_res, time = timed(lambda: evaluate(model, inp)) # noqa: B023
times.append(time)
results['default'] = np.median(times)
@@ -71,11 +71,11 @@ if __name__ == '__main__':
# required before changing backends
torch._dynamo.reset() # pylint: disable=protected-access
eval_dyn = dynamo.optimize(backend)(evaluate)
print('dynamo initial eval:', backend, timed(lambda: eval_dyn(model, inp))[1])
print('dynamo initial eval:', backend, timed(lambda: eval_dyn(model, inp))[1]) # noqa: B023
times = []
for i in range(N_ITERS):
for _i in range(N_ITERS):
inp = generate_data(16)[0]
_res, time = timed(lambda: eval_dyn(model, inp))
_res, time = timed(lambda: eval_dyn(model, inp)) # noqa: B023
times.append(time)
results[backend] = np.median(times)
except Exception as err:
+1 -1
View File
@@ -399,7 +399,7 @@ if __name__ == '__main__':
train_embedding()
if args.type == 'lora' or args.type == 'lyco' or args.type == 'dreambooth':
train_lora()
except KeyboardInterrupt as e:
except KeyboardInterrupt:
log.error('interrupt requested')
sdapi.interrupt()
mem_stats()
+1 -1
View File
@@ -91,7 +91,7 @@ def print_profile(profile: cProfile.Profile, msg: str):
ps.sort_stats(pstats.SortKey.CUMULATIVE).print_stats(15)
profile = None
lines = stream.getvalue().split('\n')
lines = [l for l in lines if '<frozen' not in l and '{built-in' not in l and '/logging' not in l and '/rich' not in l]
lines = [line for line in lines if '<frozen' not in line and '{built-in' not in line and '/logging' not in line and '/rich' not in line]
print(f'Profile {msg}:', '\n'.join(lines))
+3 -3
View File
@@ -165,7 +165,7 @@ class CodeFormer(VQAutoEncoder):
connect_list=('32', '64', '128', '256'),
fix_modules=('quantize', 'generator')):
super(CodeFormer, self).__init__(512, 64, [1, 2, 2, 4, 4, 8], 'nearest',2, [16], codebook_size)
if fix_modules is not None:
for module in fix_modules:
for param in getattr(self, module).parameters():
@@ -222,7 +222,7 @@ class CodeFormer(VQAutoEncoder):
enc_feat_dict = {}
out_list = [self.fuse_encoder_block[f_size] for f_size in self.connect_list]
for i, block in enumerate(self.encoder.blocks):
x = block(x)
x = block(x)
if i in out_list:
enc_feat_dict[str(x.shape[-1])] = x.clone()
@@ -267,7 +267,7 @@ class CodeFormer(VQAutoEncoder):
fuse_list = [self.fuse_generator_block[f_size] for f_size in self.connect_list]
for i, block in enumerate(self.generator.blocks):
x = block(x)
x = block(x)
if i in fuse_list: # fuse after i-th block
f_size = str(x.shape[-1])
if w>0:
+19 -19
View File
@@ -15,7 +15,7 @@ from basicsr.utils.registry import ARCH_REGISTRY
def normalize(in_channels):
return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
@torch.jit.script
def swish(x):
@@ -212,15 +212,15 @@ class AttnBlock(nn.Module):
# compute attention
b, c, h, w = q.shape
q = q.reshape(b, c, h*w)
q = q.permute(0, 2, 1)
q = q.permute(0, 2, 1)
k = k.reshape(b, c, h*w)
w_ = torch.bmm(q, k)
w_ = torch.bmm(q, k)
w_ = w_ * (int(c)**(-0.5))
w_ = F.softmax(w_, dim=2)
# attend to values
v = v.reshape(b, c, h*w)
w_ = w_.permute(0, 2, 1)
w_ = w_.permute(0, 2, 1)
h_ = torch.bmm(v, w_)
h_ = h_.reshape(b, c, h, w)
@@ -272,18 +272,18 @@ class Encoder(nn.Module):
def forward(self, x):
for block in self.blocks:
x = block(x)
return x
class Generator(nn.Module):
def __init__(self, nf, emb_dim, ch_mult, res_blocks, img_size, attn_resolutions):
super().__init__()
self.nf = nf
self.ch_mult = ch_mult
self.nf = nf
self.ch_mult = ch_mult
self.num_resolutions = len(self.ch_mult)
self.num_res_blocks = res_blocks
self.resolution = img_size
self.resolution = img_size
self.attn_resolutions = attn_resolutions
self.in_channels = emb_dim
self.out_channels = 3
@@ -317,24 +317,24 @@ class Generator(nn.Module):
blocks.append(nn.Conv2d(block_in_ch, self.out_channels, kernel_size=3, stride=1, padding=1))
self.blocks = nn.ModuleList(blocks)
def forward(self, x):
for block in self.blocks:
x = block(x)
return x
@ARCH_REGISTRY.register()
class VQAutoEncoder(nn.Module):
def __init__(self, img_size, nf, ch_mult, quantizer="nearest", res_blocks=2, attn_resolutions=None, codebook_size=1024, emb_dim=256,
beta=0.25, gumbel_straight_through=False, gumbel_kl_weight=1e-8, model_path=None):
super().__init__()
logger = get_root_logger()
self.in_channels = 3
self.nf = nf
self.n_blocks = res_blocks
self.in_channels = 3
self.nf = nf
self.n_blocks = res_blocks
self.codebook_size = codebook_size
self.embed_dim = emb_dim
self.ch_mult = ch_mult
@@ -365,11 +365,11 @@ class VQAutoEncoder(nn.Module):
self.kl_weight
)
self.generator = Generator(
self.nf,
self.nf,
self.embed_dim,
self.ch_mult,
self.n_blocks,
self.resolution,
self.ch_mult,
self.n_blocks,
self.resolution,
self.attn_resolutions
)
@@ -434,4 +434,4 @@ class VQGANDiscriminator(nn.Module):
raise ValueError('Wrong params!')
def forward(self, x):
return self.main(x)
return self.main(x)
+3 -3
View File
@@ -19,7 +19,7 @@ traceback_install(console=console, extra_lines=1, width=console.width, word_wrap
already_displayed = {}
def install(suppress=[]):
def install(suppress=[]): # noqa: B006
warnings.filterwarnings("ignore", category=UserWarning)
pretty_install(console=console)
traceback_install(console=console, extra_lines=1, width=console.width, word_wrap=False, indent_guides=False, suppress=suppress)
@@ -34,7 +34,7 @@ def print_error_explanation(message):
log.error(line)
def display(e: Exception, task, suppress=[]):
def display(e: Exception, task, suppress=[]): # noqa: B006
log.error(f"{task or 'error'}: {type(e).__name__}")
console.print_exception(show_locals=False, max_frames=5, extra_lines=1, suppress=suppress, theme="ansi_dark", word_wrap=False, width=min([console.width, 200]))
@@ -53,5 +53,5 @@ def run(code, task):
display(e, task)
def exception(suppress=[]):
def exception(suppress=[]): # noqa: B006
console.print_exception(show_locals=False, max_frames=10, extra_lines=2, suppress=suppress, theme="ansi_dark", word_wrap=False, width=min([console.width, 200]))
+1 -1
View File
@@ -104,7 +104,7 @@ class ResidualDenseBlock_5C(nn.Module):
Modified options that can be used:
- "Partial Convolution based Padding" arXiv:1811.11718
- "Spectral normalization" arXiv:1802.05957
- "ICASSP 2020 - ESRGAN+ : Further Improving ESRGAN" N. C.
- "ICASSP 2020 - ESRGAN+ : Further Improving ESRGAN" N. C.
{Rakotonirina} and A. {Rasoanaivo}
"""
+1 -1
View File
@@ -368,7 +368,7 @@ class FilenameGenerator:
time_format = args[0] if len(args) > 0 and args[0] != "" else self.default_time_format
try:
time_zone = pytz.timezone(args[1]) if len(args) > 1 else None
except pytz.exceptions.UnknownTimeZoneError as _:
except pytz.exceptions.UnknownTimeZoneError:
time_zone = None
time_zone_time = time_datetime.astimezone(time_zone)
try:
+1 -1
View File
@@ -42,7 +42,7 @@ def process_batch(p, input_dir, output_dir, inpaint_mask_dir, args):
# try to find corresponding mask for an image using simple filename matching
mask_image_path = os.path.join(inpaint_mask_dir, os.path.basename(image))
# if not found use first one ("same mask for all images" use-case)
if not mask_image_path in inpaint_masks:
if mask_image_path not in inpaint_masks:
mask_image_path = inpaint_masks[0]
mask_image = Image.open(mask_image_path)
p.image_mask = mask_image
+5 -3
View File
@@ -195,7 +195,7 @@ class DDPM(pl.LightningModule):
print(f"{context}: Restored training weights")
def init_from_ckpt(self, path, ignore_keys=None, only_model=False):
ignore_keys = ignore_keys or []
ignore_keys = ignore_keys or []
sd = torch.load(path, map_location="cpu")
if "state_dict" in list(sd.keys()):
sd = sd["state_dict"]
@@ -1212,8 +1212,10 @@ class LatentDiffusion(DDPM):
if i % log_every_t == 0 or i == timesteps - 1:
intermediates.append(img)
if callback: callback(i)
if img_callback: img_callback(img, i)
if callback:
callback(i)
if img_callback:
img_callback(img, i)
if return_intermediates:
return img, intermediates
+2 -2
View File
@@ -29,10 +29,10 @@ class UniPCSampler(object):
# first time we have all the info to get the real parameters from the ui
# value from the hires steps slider:
num_inference_steps = t[0] + 1
approx_denoise_strength = num_inference_steps / self.inflated_steps
num_inference_steps / self.inflated_steps
self.denoise_steps = max(num_inference_steps, shared.opts.uni_pc_order)
init_timestep = max(self.inflated_steps - self.denoise_steps, 0)
max(self.inflated_steps - self.denoise_steps, 0)
# actual number of steps we'll run
+2 -2
View File
@@ -752,7 +752,7 @@ class UniPC:
t_T = self.noise_schedule.T if t_start is None else t_start
device = x.device
if method == 'multistep':
if timesteps == None:
if timesteps is None:
timesteps = get_time_steps(self.noise_schedule, skip_type=skip_type, t_T=t_T, t_0=t_0, N=steps, device=device)
#print(f"Running UniPC Sampling with {timesteps.shape[0]} timesteps, order {order}")
assert steps >= order, "UniPC order must be < sampling steps"
@@ -773,7 +773,7 @@ class UniPC:
if self.after_update is not None:
self.after_update(x, model_x)
model_prev_list.append(model_x)
t_prev_list.append(vec_t)
t_prev_list.append(vec_t)
progress.update(task, advance=1, description=f"Progress {round(len(vec_t) * init_order / (time.time() - t), 2)}it/s")
# for step in trange(order, steps + 1):
for step in range(order, steps + 1):
+1 -1
View File
@@ -36,7 +36,7 @@ path_dirs = [
paths = {}
for d, must_exist, what, options in path_dirs:
for d, must_exist, what, _options in path_dirs:
must_exist_path = os.path.abspath(os.path.join(script_path, d, must_exist))
if not os.path.exists(must_exist_path):
print(f"Warning: {what} not found at path {must_exist_path}", file=sys.stderr)
+1 -1
View File
@@ -493,7 +493,7 @@ def print_profile(profile, msg: str):
ps.sort_stats(pstats.SortKey.CUMULATIVE).print_stats(15)
profile = None
lines = stream.getvalue().split('\n')
lines = [l for l in lines if '<frozen' not in l and '{built-in' not in l and '/logging' not in l and '/rich' not in l]
lines = [line for line in lines if '<frozen' not in line and '{built-in' not in line and '/logging' not in line and '/rich' not in line]
print(f'Profile {msg}:', '\n'.join(lines))
-2
View File
@@ -325,7 +325,6 @@ class ScriptRunner:
inputs_alwayson += [script.alwayson for _ in controls]
script.args_to = len(inputs)
s = []
with gr.Group(elem_id='scripts_alwayson_img2img' if self.is_img2img else 'scripts_alwayson_txt2img'):
for script in self.alwayson_scripts:
t0 = time.time()
@@ -337,7 +336,6 @@ class ScriptRunner:
dropdown = gr.Dropdown(label="Script", elem_id="script_list", choices=["None"] + self.titles, value="None", type="index")
inputs[0] = dropdown
s = []
for script in self.selectable_scripts:
with gr.Group(visible=False) as group:
t0 = time.time()
+1 -1
View File
@@ -34,7 +34,7 @@ def apply_optimizations():
ldm.modules.diffusionmodules.model.nonlinearity = silu
ldm.modules.diffusionmodules.openaimodel.th = sd_hijack_unet.th
optimization_method = None
can_use_sdp = hasattr(torch.nn.functional, "scaled_dot_product_attention") and callable(getattr(torch.nn.functional, "scaled_dot_product_attention"))
can_use_sdp = hasattr(torch.nn.functional, "scaled_dot_product_attention") and callable(torch.nn.functional.scaled_dot_product_attention)
if devices.device == torch.device("cpu"):
if opts.cross_attention_optimization == "Scaled-Dot-Product":
shared.log.warning("Scaled dot product cross attention is not available on CPU")
+1 -1
View File
@@ -6,4 +6,4 @@ def should_hijack_ip2p(checkpoint_info):
ckpt_basename = os.path.basename(checkpoint_info.filename).lower()
cfg_basename = os.path.basename(sd_models_config.find_checkpoint_config_near_filename(checkpoint_info)).lower()
return "pix2pix" in ckpt_basename and not "pix2pix" in cfg_basename
return "pix2pix" in ckpt_basename and "pix2pix" not in cfg_basename
+7 -7
View File
@@ -67,7 +67,7 @@ def split_cross_attention_forward_v1(self, x, context=None, mask=None): # pylint
v_in = self.to_v(context_v)
del context, context_k, context_v, x
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q_in, k_in, v_in))
q, k, v = (rearrange(t, 'b n (h d) -> (b h) n d', h=h) for t in (q_in, k_in, v_in))
del q_in, k_in, v_in
dtype = q.dtype
@@ -111,7 +111,7 @@ def split_cross_attention_forward(self, x, context=None, mask=None): # pylint: d
with devices.without_autocast(disable=not shared.opts.upcast_attn):
k_in = k_in * self.scale
del context, x
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q_in, k_in, v_in))
q, k, v = (rearrange(t, 'b n (h d) -> (b h) n d', h=h) for t in (q_in, k_in, v_in))
del q_in, k_in, v_in
r1 = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device, dtype=q.dtype)
mem_free_total = get_available_vram()
@@ -252,7 +252,7 @@ def split_cross_attention_forward_invokeAI(self, x, context=None, mask=None): #
with devices.without_autocast(disable=not shared.opts.upcast_attn):
k = k * self.scale
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
q, k, v = (rearrange(t, 'b n (h d) -> (b h) n d', h=h) for t in (q, k, v))
r = einsum_op(q, k, v)
r = r.to(dtype)
return self.to_out(rearrange(r, '(b h) n d -> b n (h d)', h=h))
@@ -357,7 +357,7 @@ def xformers_attention_forward(self, x, context=None, mask=None): # pylint: disa
k_in = self.to_k(context_k)
v_in = self.to_v(context_v)
q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b n h d', h=h), (q_in, k_in, v_in))
q, k, v = (rearrange(t, 'b n (h d) -> b n h d', h=h) for t in (q_in, k_in, v_in))
del q_in, k_in, v_in
dtype = q.dtype
@@ -485,7 +485,7 @@ def xformers_attnblock_forward(self, x):
k = self.k(h_)
v = self.v(h_)
b, c, h, w = q.shape # pylint: disable=unused-variable
q, k, v = map(lambda t: rearrange(t, 'b c h w -> b (h w) c'), (q, k, v))
q, k, v = (rearrange(t, 'b c h w -> b (h w) c') for t in (q, k, v))
dtype = q.dtype
if shared.opts.upcast_attn:
q, k = q.float(), k.float()
@@ -507,7 +507,7 @@ def sdp_attnblock_forward(self, x):
k = self.k(h_)
v = self.v(h_)
b, c, h, w = q.shape # pylint: disable=unused-variable
q, k, v = map(lambda t: rearrange(t, 'b c h w -> b (h w) c'), (q, k, v))
q, k, v = (rearrange(t, 'b c h w -> b (h w) c') for t in (q, k, v))
dtype = q.dtype
if shared.opts.upcast_attn:
q, k, v = q.float(), k.float(), v.float()
@@ -535,7 +535,7 @@ def sub_quad_attnblock_forward(self, x):
k = self.k(h_)
v = self.v(h_)
b, c, h, w = q.shape # pylint: disable=unused-variable
q, k, v = map(lambda t: rearrange(t, 'b c h w -> b (h w) c'), (q, k, v))
q, k, v = (rearrange(t, 'b c h w -> b (h w) c') for t in (q, k, v))
q = q.contiguous()
k = k.contiguous()
v = v.contiguous()
+1 -1
View File
@@ -422,7 +422,7 @@ def enable_midas_autodownload():
def repair_config(sd_config):
if not "use_ema" in sd_config.model.params:
if "use_ema" not in sd_config.model.params:
sd_config.model.params.use_ema = False
if shared.opts.no_half:
sd_config.model.params.unet_config.params.use_fp16 = False
+1 -1
View File
@@ -331,7 +331,7 @@ class KDiffusionSampler:
return BrownianTreeNoiseSampler(x.to("cpu"), sigma_min, sigma_max, seed=current_iter_seeds, transform=lambda x: x.to("cpu"), transform_last=lambda x: x.to(shared.device)) # pylint: disable=E1123
except Exception:
print("ERROR Please apply this patch to repositories/k-diffusion/k_diffusion/sampling.py: https://github.com/crowsonkb/k-diffusion/pull/68/files")
return None
return None
else:
return BrownianTreeNoiseSampler(x, sigma_min, sigma_max, seed=current_iter_seeds)
+3 -3
View File
@@ -421,7 +421,7 @@ options_templates.update(options_section(('ui', "User interface"), {
"keyedit_precision_extra": OptionInfo(0.05, "Ctrl+up/down precision when editing <extra networks:0.9>", gr.Slider, {"minimum": 0.01, "maximum": 0.2, "step": 0.001}),
"keyedit_delimiters": OptionInfo(".,\/!?%^*;:{}=`~()", "Ctrl+up/down word delimiters"), # pylint: disable=anomalous-backslash-in-string
"quicksettings_list": OptionInfo(["sd_model_checkpoint"], "Quicksettings list", ui_components.DropdownMulti, lambda: {"choices": list(opts.data_labels.keys())}),
"hidden_tabs": OptionInfo([], "Hidden UI tabs", ui_components.DropdownMulti, lambda: {"choices": [x for x in tab_names]}),
"hidden_tabs": OptionInfo([], "Hidden UI tabs", ui_components.DropdownMulti, lambda: {"choices": list(tab_names)}),
"ui_tab_reorder": OptionInfo("From Text, From Image, Process Image", "UI tabs order"),
"ui_scripts_reorder": OptionInfo("Enable Dynamic Thresholding, ControlNet", "UI scripts order"),
"ui_reorder": OptionInfo(", ".join(ui_reorder_categories), "txt2img/img2img UI item order"),
@@ -501,7 +501,7 @@ options_templates.update(options_section(('upscaling', "Upscaling"), {
"ESRGAN_tile": OptionInfo(192, "Tile size for ESRGAN upscalers (0 = no tiling)", gr.Slider, {"minimum": 0, "maximum": 512, "step": 16}),
"ESRGAN_tile_overlap": OptionInfo(8, "Tile overlap in pixels for ESRGAN upscalers", gr.Slider, {"minimum": 0, "maximum": 48, "step": 1}),
"SCUNET_tile": OptionInfo(256, "Tile size for SCUNET upscalers (0 = no tiling)", gr.Slider, {"minimum": 0, "maximum": 512, "step": 16}),
"SCUNET_tile_overlap": OptionInfo(8, "Tile overlap, in pixels for SCUNET upscalers (low values = visible seam)", gr.Slider, {"minimum": 0, "maximum": 64, "step": 1}),
"SCUNET_tile_overlap": OptionInfo(8, "Tile overlap, in pixels for SCUNET upscalers (low values = visible seam)", gr.Slider, {"minimum": 0, "maximum": 64, "step": 1}),
"use_old_hires_fix_width_height": OptionInfo(False, "Hires fix uses width & height to set final resolution rather than first pass"),
"dont_fix_second_order_samplers_schedule": OptionInfo(False, "Do not fix prompt schedule for second order samplers"),
}))
@@ -524,7 +524,7 @@ options_templates.update(options_section(('extra_networks', "Extra Networks"), {
"extra_networks_card_width": OptionInfo(0, "Card width for Extra Networks (px)"),
"extra_networks_card_height": OptionInfo(0, "Card height for Extra Networks (px)"),
"extra_networks_add_text_separator": OptionInfo(" ", "Extra text to add before <...> when adding extra network to prompt"),
"sd_hypernetwork": OptionInfo("None", "Add hypernetwork to prompt", gr.Dropdown, lambda: {"choices": ["None"] + [x for x in hypernetworks.keys()]}, refresh=reload_hypernetworks),
"sd_hypernetwork": OptionInfo("None", "Add hypernetwork to prompt", gr.Dropdown, lambda: {"choices": ["None"] + list(hypernetworks.keys())}, refresh=reload_hypernetworks),
}))
options_templates.update(options_section(('token_merging', 'Token Merging'), {
+3 -3
View File
@@ -315,7 +315,7 @@ def create_sampler_and_steps_selection(choices, tabname):
def ordered_ui_categories():
user_order = {x.strip(): i * 2 + 1 for i, x in enumerate(modules.shared.opts.ui_reorder.split(","))}
for i, category in sorted(enumerate(modules.shared.ui_reorder_categories), key=lambda x: user_order.get(x[1], x[0] * 2 + 0)):
for _i, category in sorted(enumerate(modules.shared.ui_reorder_categories), key=lambda x: user_order.get(x[1], x[0] * 2 + 0)):
yield category
@@ -1452,7 +1452,7 @@ def create_ui():
with gr.Blocks(theme=modules.shared.gradio_theme, analytics_enabled=False, title="SD.Next", allowed_paths=[cmd_opts.data_dir]) as demo:
with gr.Row(elem_id="quicksettings", variant="compact"):
for i, k, item in sorted(quicksettings_list, key=lambda x: quicksettings_names.get(x[1], x[0])):
for _i, k, _item in sorted(quicksettings_list, key=lambda x: quicksettings_names.get(x[1], x[0])):
component = create_setting_component(k, is_quicksettings=True)
component_dict[k] = component
@@ -1483,7 +1483,7 @@ def create_ui():
restart_submit.click(fn=lambda x: modules.shared.restart_server(restart=True), _js="restart_reload")
shutdown_submit.click(fn=lambda x: modules.shared.restart_server(restart=False), _js="restart_reload")
for i, k, item in quicksettings_list:
for _i, k, _item in quicksettings_list:
component = component_dict[k]
info = opts.data_labels[k]
@@ -14,7 +14,7 @@ class ExtraNetworksPageTextualInversion(ui_extra_networks.ExtraNetworksPage):
sd_hijack.model_hijack.embedding_db.load_textual_inversion_embeddings(force_reload=True)
def list_items(self):
embeddings = [emb for emb in sd_hijack.model_hijack.embedding_db.word_embeddings.values()]
embeddings = list(sd_hijack.model_hijack.embedding_db.word_embeddings.values())
if len(embeddings) == 0: # maybe not loaded yet, so lets just look them up
for root, _dirs, fns in os.walk(shared.opts.embeddings_dir, followlinks=True):
for fn in fns:
-4
View File
@@ -29,11 +29,7 @@ ignore = [
"F401", # Imported but unused
]
[tool.ruff.per-file-ignores]
"webui.py" = ["E402"] # Module level import not at top of file
[tool.ruff.flake8-bugbear]
# Allow default arguments like, e.g., `data: List[str] = fastapi.Query(None)`.
extend-immutable-calls = ["fastapi.Depends", "fastapi.security.HTTPBasic"]
[tool.pytest.ini_options]
+1 -1
View File
@@ -69,7 +69,7 @@ def get_matched_noise(_np_src_image, np_mask_rgb, noise_q=1, color_variation=0.0
height = _np_src_image.shape[1]
num_channels = _np_src_image.shape[2]
np_src_image = _np_src_image[:] * (1. - np_mask_rgb)
_np_src_image[:] * (1. - np_mask_rgb)
np_mask_grey = np.sum(np_mask_rgb, axis=2) / 3.
img_mask = np_mask_grey > 1e-6
ref_mask = np_mask_grey < 1e-3
+2 -2
View File
@@ -54,7 +54,7 @@ class Script(scripts.Script):
work = []
for y, h, row in grid.tiles:
for _y, _h, row in grid.tiles:
for tiledata in row:
work.append(tiledata[2])
@@ -83,7 +83,7 @@ class Script(scripts.Script):
work_results += processed.images
image_index = 0
for y, h, row in grid.tiles:
for _y, _h, row in grid.tiles:
for tiledata in row:
tiledata[2] = work_results[image_index] if image_index < len(work_results) else Image.new("RGB", (p.width, p.height))
image_index += 1