From 1d9e490ef916055b95f2a1b9d0c6c898ea733631 Mon Sep 17 00:00:00 2001 From: Vladimir Mandic Date: Tue, 13 Jun 2023 12:22:39 -0400 Subject: [PATCH] ruff linting fixes --- CHANGELOG.md | 6 ++- cli/create-previews.py | 8 ++-- cli/generate.py | 4 +- cli/image-exif.py | 6 +-- cli/image-watermark.py | 2 +- cli/process.py | 6 +-- cli/torch-compile.py | 10 ++--- cli/train.py | 2 +- extensions-builtin/sd-extension-system-info | 2 +- installer.py | 2 +- modules/codeformer/codeformer_arch.py | 6 +-- modules/codeformer/vqgan_arch.py | 38 +++++++++---------- modules/errors.py | 6 +-- modules/esrgan_model_arch.py | 2 +- modules/images.py | 2 +- modules/img2img.py | 2 +- modules/models/diffusion/ddpm_edit.py | 8 ++-- modules/models/diffusion/uni_pc/sampler.py | 4 +- modules/models/diffusion/uni_pc/uni_pc.py | 4 +- modules/paths.py | 2 +- modules/processing.py | 2 +- modules/scripts.py | 2 - modules/sd_hijack.py | 2 +- modules/sd_hijack_ip2p.py | 2 +- modules/sd_hijack_optimizations.py | 14 +++---- modules/sd_models.py | 2 +- modules/sd_samplers_kdiffusion.py | 2 +- modules/shared.py | 6 +-- modules/ui.py | 6 +-- .../ui_extra_networks_textual_inversion.py | 2 +- pyproject.toml | 4 -- scripts/outpainting_mk_2.py | 2 +- scripts/sd_upscale.py | 4 +- 33 files changed, 86 insertions(+), 86 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 68b1dc707..7df4b94b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/cli/create-previews.py b/cli/create-previews.py index 19d779a08..0a42d3cc4 100755 --- a/cli/create-previews.py +++ b/cli/create-previews.py @@ -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: diff --git a/cli/generate.py b/cli/generate.py index 5cfd9b0fd..9e56dd3b0 100755 --- a/cli/generate.py +++ b/cli/generate.py @@ -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() diff --git a/cli/image-exif.py b/cli/image-exif.py index 311797737..c6cdf69e9 100755 --- a/cli/image-exif.py +++ b/cli/image-exif.py @@ -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)) diff --git a/cli/image-watermark.py b/cli/image-watermark.py index aea4b5729..7e6c4b288 100755 --- a/cli/image-watermark.py +++ b/cli/image-watermark.py @@ -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() diff --git a/cli/process.py b/cli/process.py index a2104bf0c..b134fc222 100644 --- a/cli/process.py +++ b/cli/process.py @@ -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 diff --git a/cli/torch-compile.py b/cli/torch-compile.py index f4f4d194b..00d08b11c 100755 --- a/cli/torch-compile.py +++ b/cli/torch-compile.py @@ -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: diff --git a/cli/train.py b/cli/train.py index afb3aee63..01dad9800 100755 --- a/cli/train.py +++ b/cli/train.py @@ -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() diff --git a/extensions-builtin/sd-extension-system-info b/extensions-builtin/sd-extension-system-info index 064c856ac..acfc8d68b 160000 --- a/extensions-builtin/sd-extension-system-info +++ b/extensions-builtin/sd-extension-system-info @@ -1 +1 @@ -Subproject commit 064c856acaed8c73c3a232e39df8c37d0bb9a15c +Subproject commit acfc8d68b887cb482a94870f005a3a0661670aea diff --git a/installer.py b/installer.py index d67b432b1..403eaaa8d 100644 --- a/installer.py +++ b/installer.py @@ -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 '0: diff --git a/modules/codeformer/vqgan_arch.py b/modules/codeformer/vqgan_arch.py index 6e72d341b..3acb121b6 100644 --- a/modules/codeformer/vqgan_arch.py +++ b/modules/codeformer/vqgan_arch.py @@ -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) \ No newline at end of file + return self.main(x) diff --git a/modules/errors.py b/modules/errors.py index 8b4f1b6b4..de4c987fd 100644 --- a/modules/errors.py +++ b/modules/errors.py @@ -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])) diff --git a/modules/esrgan_model_arch.py b/modules/esrgan_model_arch.py index a2e7e1dc0..fb8ed9741 100644 --- a/modules/esrgan_model_arch.py +++ b/modules/esrgan_model_arch.py @@ -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} """ diff --git a/modules/images.py b/modules/images.py index 2e9d7f2a8..2d36b081d 100644 --- a/modules/images.py +++ b/modules/images.py @@ -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: diff --git a/modules/img2img.py b/modules/img2img.py index 2e2ccd9eb..e1cb15483 100644 --- a/modules/img2img.py +++ b/modules/img2img.py @@ -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 diff --git a/modules/models/diffusion/ddpm_edit.py b/modules/models/diffusion/ddpm_edit.py index 7dc66d15e..c847bfd68 100644 --- a/modules/models/diffusion/ddpm_edit.py +++ b/modules/models/diffusion/ddpm_edit.py @@ -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 diff --git a/modules/models/diffusion/uni_pc/sampler.py b/modules/models/diffusion/uni_pc/sampler.py index 7d7a8e641..41455c94d 100644 --- a/modules/models/diffusion/uni_pc/sampler.py +++ b/modules/models/diffusion/uni_pc/sampler.py @@ -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 diff --git a/modules/models/diffusion/uni_pc/uni_pc.py b/modules/models/diffusion/uni_pc/uni_pc.py index 433ab07ee..6dddbcfbd 100644 --- a/modules/models/diffusion/uni_pc/uni_pc.py +++ b/modules/models/diffusion/uni_pc/uni_pc.py @@ -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): diff --git a/modules/paths.py b/modules/paths.py index 966567563..deb022c75 100644 --- a/modules/paths.py +++ b/modules/paths.py @@ -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) diff --git a/modules/processing.py b/modules/processing.py index ab1e4d6a7..5553894af 100644 --- a/modules/processing.py +++ b/modules/processing.py @@ -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 ' (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() diff --git a/modules/sd_models.py b/modules/sd_models.py index e56dbdcba..9acfcbfe3 100644 --- a/modules/sd_models.py +++ b/modules/sd_models.py @@ -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 diff --git a/modules/sd_samplers_kdiffusion.py b/modules/sd_samplers_kdiffusion.py index 203880447..2393b2ec2 100644 --- a/modules/sd_samplers_kdiffusion.py +++ b/modules/sd_samplers_kdiffusion.py @@ -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) diff --git a/modules/shared.py b/modules/shared.py index 2fd01c172..cfcbc548e 100644 --- a/modules/shared.py +++ b/modules/shared.py @@ -421,7 +421,7 @@ options_templates.update(options_section(('ui', "User interface"), { "keyedit_precision_extra": OptionInfo(0.05, "Ctrl+up/down precision when editing ", 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'), { diff --git a/modules/ui.py b/modules/ui.py index fbfb1d642..8f5b07694 100644 --- a/modules/ui.py +++ b/modules/ui.py @@ -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] diff --git a/modules/ui_extra_networks_textual_inversion.py b/modules/ui_extra_networks_textual_inversion.py index 47b8cdd5a..9e99ba211 100644 --- a/modules/ui_extra_networks_textual_inversion.py +++ b/modules/ui_extra_networks_textual_inversion.py @@ -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: diff --git a/pyproject.toml b/pyproject.toml index 7fdb6e960..c2a238aed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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] diff --git a/scripts/outpainting_mk_2.py b/scripts/outpainting_mk_2.py index f546fd94e..bf1daf55f 100644 --- a/scripts/outpainting_mk_2.py +++ b/scripts/outpainting_mk_2.py @@ -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 diff --git a/scripts/sd_upscale.py b/scripts/sd_upscale.py index 2ce97a6c4..4b594177b 100644 --- a/scripts/sd_upscale.py +++ b/scripts/sd_upscale.py @@ -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