Browse Source

Simplify a bunch of `len(x) > 0`/`len(x) == 0` style expressions

Aarni Koskela 2 years ago
parent
commit
51864790fd

+ 2 - 1
extensions-builtin/LDSR/sd_hijack_autoencoder.py

@@ -91,8 +91,9 @@ class VQModel(pl.LightningModule):
                     del sd[k]
         missing, unexpected = self.load_state_dict(sd, strict=False)
         print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
-        if len(missing) > 0:
+        if missing:
             print(f"Missing Keys: {missing}")
+        if unexpected:
             print(f"Unexpected Keys: {unexpected}")
 
     def on_train_batch_end(self, *args, **kwargs):

+ 2 - 2
extensions-builtin/LDSR/sd_hijack_ddpm_v1.py

@@ -195,9 +195,9 @@ class DDPMV1(pl.LightningModule):
         missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
             sd, strict=False)
         print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
-        if len(missing) > 0:
+        if missing:
             print(f"Missing Keys: {missing}")
-        if len(unexpected) > 0:
+        if unexpected:
             print(f"Unexpected Keys: {unexpected}")
 
     def q_mean_variance(self, x_start, t):

+ 2 - 2
extensions-builtin/Lora/extra_networks_lora.py

@@ -9,14 +9,14 @@ class ExtraNetworkLora(extra_networks.ExtraNetwork):
     def activate(self, p, params_list):
         additional = shared.opts.sd_lora
 
-        if additional != "None" and additional in lora.available_loras and len([x for x in params_list if x.items[0] == additional]) == 0:
+        if additional != "None" and additional in lora.available_loras and not any(x for x in params_list if x.items[0] == additional):
             p.all_prompts = [x + f"<lora:{additional}:{shared.opts.extra_networks_default_multiplier}>" for x in p.all_prompts]
             params_list.append(extra_networks.ExtraNetworkParams(items=[additional, shared.opts.extra_networks_default_multiplier]))
 
         names = []
         multipliers = []
         for params in params_list:
-            assert len(params.items) > 0
+            assert params.items
 
             names.append(params.items[0])
             multipliers.append(float(params.items[1]) if len(params.items) > 1 else 1.0)

+ 2 - 2
extensions-builtin/Lora/lora.py

@@ -219,7 +219,7 @@ def load_lora(name, lora_on_disk):
         else:
             raise AssertionError(f"Bad Lora layer name: {key_diffusers} - must end in lora_up.weight, lora_down.weight or alpha")
 
-    if len(keys_failed_to_match) > 0:
+    if keys_failed_to_match:
         print(f"Failed to match keys when loading Lora {lora_on_disk.filename}: {keys_failed_to_match}")
 
     return lora
@@ -267,7 +267,7 @@ def load_loras(names, multipliers=None):
         lora.multiplier = multipliers[i] if multipliers else 1.0
         loaded_loras.append(lora)
 
-    if len(failed_to_load_loras) > 0:
+    if failed_to_load_loras:
         sd_hijack.model_hijack.comments.append("Failed to find Loras: " + ", ".join(failed_to_load_loras))
 
 

+ 1 - 1
extensions-builtin/extra-options-section/scripts/extra_options_section.py

@@ -21,7 +21,7 @@ class ExtraOptionsSection(scripts.Script):
         self.setting_names = []
 
         with gr.Blocks() as interface:
-            with gr.Accordion("Options", open=False) if shared.opts.extra_options_accordion and len(shared.opts.extra_options) > 0 else gr.Group(), gr.Row():
+            with gr.Accordion("Options", open=False) if shared.opts.extra_options_accordion and shared.opts.extra_options else gr.Group(), gr.Row():
                 for setting_name in shared.opts.extra_options:
                     with FormColumn():
                         comp = ui_settings.create_setting_component(setting_name)

+ 1 - 1
modules/api/api.py

@@ -280,7 +280,7 @@ class Api:
             script_args[0] = selectable_idx + 1
 
         # Now check for always on scripts
-        if request.alwayson_scripts and (len(request.alwayson_scripts) > 0):
+        if request.alwayson_scripts:
             for alwayson_script_name in request.alwayson_scripts.keys():
                 alwayson_script = self.get_script(alwayson_script_name, script_runner)
                 if alwayson_script is None:

+ 1 - 1
modules/call_queue.py

@@ -21,7 +21,7 @@ def wrap_gradio_gpu_call(func, extra_outputs=None):
     def f(*args, **kwargs):
 
         # if the first argument is a string that says "task(...)", it is treated as a job id
-        if len(args) > 0 and type(args[0]) == str and args[0][0:5] == "task(" and args[0][-1] == ")":
+        if args and type(args[0]) == str and args[0].startswith("task(") and args[0].endswith(")"):
             id_task = args[0]
             progress.add_task_to_queue(id_task)
         else:

+ 2 - 2
modules/extra_networks_hypernet.py

@@ -9,7 +9,7 @@ class ExtraNetworkHypernet(extra_networks.ExtraNetwork):
     def activate(self, p, params_list):
         additional = shared.opts.sd_hypernetwork
 
-        if additional != "None" and additional in shared.hypernetworks and len([x for x in params_list if x.items[0] == additional]) == 0:
+        if additional != "None" and additional in shared.hypernetworks and not any(x for x in params_list if x.items[0] == additional):
             hypernet_prompt_text = f"<hypernet:{additional}:{shared.opts.extra_networks_default_multiplier}>"
             p.all_prompts = [f"{prompt}{hypernet_prompt_text}" for prompt in p.all_prompts]
             params_list.append(extra_networks.ExtraNetworkParams(items=[additional, shared.opts.extra_networks_default_multiplier]))
@@ -17,7 +17,7 @@ class ExtraNetworkHypernet(extra_networks.ExtraNetwork):
         names = []
         multipliers = []
         for params in params_list:
-            assert len(params.items) > 0
+            assert params.items
 
             names.append(params.items[0])
             multipliers.append(float(params.items[1]) if len(params.items) > 1 else 1.0)

+ 2 - 4
modules/generation_parameters_copypaste.py

@@ -55,7 +55,7 @@ def image_from_url_text(filedata):
     if filedata is None:
         return None
 
-    if type(filedata) == list and len(filedata) > 0 and type(filedata[0]) == dict and filedata[0].get("is_file", False):
+    if type(filedata) == list and filedata and type(filedata[0]) == dict and filedata[0].get("is_file", False):
         filedata = filedata[0]
 
     if type(filedata) == dict and filedata.get("is_file", False):
@@ -437,7 +437,7 @@ def connect_paste(button, paste_fields, input_comp, override_settings_component,
 
             vals_pairs = [f"{k}: {v}" for k, v in vals.items()]
 
-            return gr.Dropdown.update(value=vals_pairs, choices=vals_pairs, visible=len(vals_pairs) > 0)
+            return gr.Dropdown.update(value=vals_pairs, choices=vals_pairs, visible=bool(vals_pairs))
 
         paste_fields = paste_fields + [(override_settings_component, paste_settings)]
 
@@ -454,5 +454,3 @@ def connect_paste(button, paste_fields, input_comp, override_settings_component,
         outputs=[],
         show_progress=False,
     )
-
-

+ 3 - 3
modules/images.py

@@ -406,7 +406,7 @@ class FilenameGenerator:
 
         prompt_no_style = self.prompt
         for style in shared.prompt_styles.get_style_prompts(self.p.styles):
-            if len(style) > 0:
+            if style:
                 for part in style.split("{prompt}"):
                     prompt_no_style = prompt_no_style.replace(part, "").replace(", ,", ",").strip().strip(',')
 
@@ -415,7 +415,7 @@ class FilenameGenerator:
         return sanitize_filename_part(prompt_no_style, replace_spaces=False)
 
     def prompt_words(self):
-        words = [x for x in re_nonletters.split(self.prompt or "") if len(x) > 0]
+        words = [x for x in re_nonletters.split(self.prompt or "") if x]
         if len(words) == 0:
             words = ["empty"]
         return sanitize_filename_part(" ".join(words[0:opts.directories_max_prompt_words]), replace_spaces=False)
@@ -423,7 +423,7 @@ class FilenameGenerator:
     def datetime(self, *args):
         time_datetime = datetime.datetime.now()
 
-        time_format = args[0] if len(args) > 0 and args[0] != "" else self.default_time_format
+        time_format = args[0] if (args 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:

+ 1 - 2
modules/img2img.py

@@ -21,8 +21,7 @@ def process_batch(p, input_dir, output_dir, inpaint_mask_dir, args):
     is_inpaint_batch = False
     if inpaint_mask_dir:
         inpaint_masks = shared.listfiles(inpaint_mask_dir)
-        is_inpaint_batch = len(inpaint_masks) > 0
-    if is_inpaint_batch:
+        is_inpaint_batch = bool(inpaint_masks)
         print(f"\nInpaint batch is enabled. {len(inpaint_masks)} masks found.")
 
     print(f"Will process {len(images)} images, creating {p.n_iter * p.batch_size} new images for each.")

+ 2 - 2
modules/models/diffusion/ddpm_edit.py

@@ -230,9 +230,9 @@ class DDPM(pl.LightningModule):
         missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
             sd, strict=False)
         print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
-        if len(missing) > 0:
+        if missing:
             print(f"Missing Keys: {missing}")
-        if len(unexpected) > 0:
+        if unexpected:
             print(f"Unexpected Keys: {unexpected}")
 
     def q_mean_variance(self, x_start, t):

+ 2 - 1
modules/processing.py

@@ -975,7 +975,8 @@ class StableDiffusionProcessingTxt2Img(StableDiffusionProcessing):
 
         latent_scale_mode = shared.latent_upscale_modes.get(self.hr_upscaler, None) if self.hr_upscaler is not None else shared.latent_upscale_modes.get(shared.latent_upscale_default_mode, "nearest")
         if self.enable_hr and latent_scale_mode is None:
-            assert len([x for x in shared.sd_upscalers if x.name == self.hr_upscaler]) > 0, f"could not find upscaler named {self.hr_upscaler}"
+            if not any(x.name == self.hr_upscaler for x in shared.sd_upscalers):
+                raise Exception(f"could not find upscaler named {self.hr_upscaler}")
 
         x = create_random_tensors([opt_C, self.height // opt_f, self.width // opt_f], seeds=seeds, subseeds=subseeds, subseed_strength=self.subseed_strength, seed_resize_from_h=self.seed_resize_from_h, seed_resize_from_w=self.seed_resize_from_w, p=self)
         samples = self.sampler.sample(self, x, conditioning, unconditional_conditioning, image_conditioning=self.txt2img_image_conditioning(x))

+ 3 - 3
modules/prompt_parser.py

@@ -336,11 +336,11 @@ def parse_prompt_attention(text):
             round_brackets.append(len(res))
         elif text == '[':
             square_brackets.append(len(res))
-        elif weight is not None and len(round_brackets) > 0:
+        elif weight is not None and round_brackets:
             multiply_range(round_brackets.pop(), float(weight))
-        elif text == ')' and len(round_brackets) > 0:
+        elif text == ')' and round_brackets:
             multiply_range(round_brackets.pop(), round_bracket_multiplier)
-        elif text == ']' and len(square_brackets) > 0:
+        elif text == ']' and square_brackets:
             multiply_range(square_brackets.pop(), square_bracket_multiplier)
         else:
             parts = re.split(re_break, text)

+ 2 - 2
modules/script_callbacks.py

@@ -287,14 +287,14 @@ def list_unets_callback():
 
 def add_callback(callbacks, fun):
     stack = [x for x in inspect.stack() if x.filename != __file__]
-    filename = stack[0].filename if len(stack) > 0 else 'unknown file'
+    filename = stack[0].filename if stack else 'unknown file'
 
     callbacks.append(ScriptCallback(filename, fun))
 
 
 def remove_current_script_callbacks():
     stack = [x for x in inspect.stack() if x.filename != __file__]
-    filename = stack[0].filename if len(stack) > 0 else 'unknown file'
+    filename = stack[0].filename if stack else 'unknown file'
     if filename == 'unknown file':
         return
     for callback_list in callback_map.values():

+ 1 - 1
modules/sd_hijack_clip.py

@@ -167,7 +167,7 @@ class FrozenCLIPEmbedderWithCustomWordsBase(torch.nn.Module):
                 chunk.multipliers += [weight] * emb_len
                 position += embedding_length_in_tokens
 
-        if len(chunk.tokens) > 0 or len(chunks) == 0:
+        if chunk.tokens or not chunks:
             next_chunk(is_last=True)
 
         return chunks, token_count

+ 1 - 1
modules/sd_hijack_clip_old.py

@@ -74,7 +74,7 @@ def forward_old(self: sd_hijack_clip.FrozenCLIPEmbedderWithCustomWordsBase, text
 
     self.hijack.comments += hijack_comments
 
-    if len(used_custom_terms) > 0:
+    if used_custom_terms:
         embedding_names = ", ".join(f"{word} [{checksum}]" for word, checksum in used_custom_terms)
         self.hijack.comments.append(f"Used embeddings: {embedding_names}")
 

+ 7 - 7
modules/textual_inversion/autocrop.py

@@ -77,27 +77,27 @@ def focal_point(im, settings):
     pois = []
 
     weight_pref_total = 0
-    if len(corner_points) > 0:
+    if corner_points:
       weight_pref_total += settings.corner_points_weight
-    if len(entropy_points) > 0:
+    if entropy_points:
       weight_pref_total += settings.entropy_points_weight
-    if len(face_points) > 0:
+    if face_points:
       weight_pref_total += settings.face_points_weight
 
     corner_centroid = None
-    if len(corner_points) > 0:
+    if corner_points:
       corner_centroid = centroid(corner_points)
       corner_centroid.weight = settings.corner_points_weight / weight_pref_total
       pois.append(corner_centroid)
 
     entropy_centroid = None
-    if len(entropy_points) > 0:
+    if entropy_points:
       entropy_centroid = centroid(entropy_points)
       entropy_centroid.weight = settings.entropy_points_weight / weight_pref_total
       pois.append(entropy_centroid)
 
     face_centroid = None
-    if len(face_points) > 0:
+    if face_points:
       face_centroid = centroid(face_points)
       face_centroid.weight = settings.face_points_weight / weight_pref_total
       pois.append(face_centroid)
@@ -187,7 +187,7 @@ def image_face_points(im, settings):
         except Exception:
           continue
 
-        if len(faces) > 0:
+        if faces:
           rects = [[f[0], f[1], f[0] + f[2], f[1] + f[3]] for f in faces]
           return [PointOfInterest((r[0] +r[2]) // 2, (r[1] + r[3]) // 2, size=abs(r[0]-r[2]), weight=1/len(rects)) for r in rects]
     return []

+ 1 - 1
modules/textual_inversion/dataset.py

@@ -32,7 +32,7 @@ class DatasetEntry:
 
 class PersonalizedBase(Dataset):
     def __init__(self, data_root, width, height, repeats, flip_p=0.5, placeholder_token="*", model=None, cond_model=None, device=None, template_file=None, include_cond=False, batch_size=1, gradient_step=1, shuffle_tags=False, tag_drop_out=0, latent_sampling_method='once', varsize=False, use_weight=False):
-        re_word = re.compile(shared.opts.dataset_filename_word_regex) if len(shared.opts.dataset_filename_word_regex) > 0 else None
+        re_word = re.compile(shared.opts.dataset_filename_word_regex) if shared.opts.dataset_filename_word_regex else None
 
         self.placeholder_token = placeholder_token
 

+ 2 - 2
modules/textual_inversion/preprocess.py

@@ -47,7 +47,7 @@ def save_pic_with_caption(image, index, params: PreprocessParams, existing_capti
         caption += shared.interrogator.generate_caption(image)
 
     if params.process_caption_deepbooru:
-        if len(caption) > 0:
+        if caption:
             caption += ", "
         caption += deepbooru.model.tag_multi(image)
 
@@ -67,7 +67,7 @@ def save_pic_with_caption(image, index, params: PreprocessParams, existing_capti
 
     caption = caption.strip()
 
-    if len(caption) > 0:
+    if caption:
         with open(os.path.join(params.dstdir, f"{basename}.txt"), "w", encoding="utf8") as file:
             file.write(caption)
 

+ 1 - 1
modules/textual_inversion/textual_inversion.py

@@ -251,7 +251,7 @@ class EmbeddingDatabase:
         if self.previously_displayed_embeddings != displayed_embeddings:
             self.previously_displayed_embeddings = displayed_embeddings
             print(f"Textual inversion embeddings loaded({len(self.word_embeddings)}): {', '.join(self.word_embeddings.keys())}")
-            if len(self.skipped_embeddings) > 0:
+            if self.skipped_embeddings:
                 print(f"Textual inversion embeddings skipped({len(self.skipped_embeddings)}): {', '.join(self.skipped_embeddings.keys())}")
 
     def find_embedding_at_position(self, tokens, offset):

+ 1 - 1
modules/ui.py

@@ -398,7 +398,7 @@ def create_override_settings_dropdown(tabname, row):
     dropdown = gr.Dropdown([], label="Override settings", visible=False, elem_id=f"{tabname}_override_settings", multiselect=True)
 
     dropdown.change(
-        fn=lambda x: gr.Dropdown.update(visible=len(x) > 0),
+        fn=lambda x: gr.Dropdown.update(visible=bool(x)),
         inputs=[dropdown],
         outputs=[dropdown],
     )

+ 3 - 2
modules/ui_extensions.py

@@ -333,7 +333,8 @@ def install_extension_from_url(dirname, url, branch_name=None):
     assert not os.path.exists(target_dir), f'Extension directory already exists: {target_dir}'
 
     normalized_url = normalize_git_url(url)
-    assert len([x for x in extensions.extensions if normalize_git_url(x.remote) == normalized_url]) == 0, 'Extension with this URL is already installed'
+    if any(x for x in extensions.extensions if normalize_git_url(x.remote) == normalized_url):
+        raise Exception(f'Extension with this URL is already installed: {url}')
 
     tmpdir = os.path.join(paths.data_path, "tmp", dirname)
 
@@ -449,7 +450,7 @@ def refresh_available_extensions_from_data(hide_tags, sort_column, filter_text="
         existing = installed_extension_urls.get(normalize_git_url(url), None)
         extension_tags = extension_tags + ["installed"] if existing else extension_tags
 
-        if len([x for x in extension_tags if x in tags_to_hide]) > 0:
+        if any(x for x in extension_tags if x in tags_to_hide):
             hidden += 1
             continue
 

+ 1 - 1
modules/ui_settings.py

@@ -81,7 +81,7 @@ class UiSettings:
             opts.save(shared.config_filename)
         except RuntimeError:
             return opts.dumpjson(), f'{len(changed)} settings changed without save: {", ".join(changed)}.'
-        return opts.dumpjson(), f'{len(changed)} settings changed{": " if len(changed) > 0 else ""}{", ".join(changed)}.'
+        return opts.dumpjson(), f'{len(changed)} settings changed{": " if changed else ""}{", ".join(changed)}.'
 
     def run_settings_single(self, value, key):
         if not opts.same_type(value, opts.data_labels[key].default):

+ 1 - 2
scripts/prompts_from_file.py

@@ -121,8 +121,7 @@ class Script(scripts.Script):
         return [checkbox_iterate, checkbox_iterate_batch, prompt_txt]
 
     def run(self, p, checkbox_iterate, checkbox_iterate_batch, prompt_txt: str):
-        lines = [x.strip() for x in prompt_txt.splitlines()]
-        lines = [x for x in lines if len(x) > 0]
+        lines = [x for x in (x.strip() for x in prompt_txt.splitlines()) if x]
 
         p.do_not_save_grid = True