Fix linter issues under script (#2667)

pull/2668/head
Chenlei Hu 2024-02-29 04:58:34 +00:00 committed by GitHub
parent 976c595150
commit 44e0875956
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
16 changed files with 48 additions and 52 deletions

View File

@ -8,7 +8,8 @@ exclude = [
"web_tests",
"example",
"extract_controlnet_diff.py",
"scripts",
"scripts/global_state.py",
"scripts/movie2movie.py",
]
ignore = [

View File

@ -2,9 +2,8 @@ import torch
import torch.nn as nn
from collections import OrderedDict
from omegaconf import OmegaConf
from copy import deepcopy
from modules import devices, lowvram, shared, scripts
from modules import devices
cond_cast_unet = getattr(devices, 'cond_cast_unet', lambda x: x)
@ -137,7 +136,7 @@ class ResnetBlock(nn.Module):
def __init__(self, in_c, out_c, down, ksize=3, sk=False, use_conv=True):
super().__init__()
ps = ksize//2
if in_c != out_c or sk==False:
if in_c != out_c or sk is False:
self.in_conv = nn.Conv2d(in_c, out_c, ksize, 1, ps)
else:
# print('n_in')
@ -145,17 +144,17 @@ class ResnetBlock(nn.Module):
self.block1 = nn.Conv2d(out_c, out_c, 3, 1, 1)
self.act = nn.ReLU()
self.block2 = nn.Conv2d(out_c, out_c, ksize, 1, ps)
if sk==False:
if sk is False:
self.skep = nn.Conv2d(in_c, out_c, ksize, 1, ps)
else:
self.skep = None
self.down = down
if self.down == True:
if self.down is True:
self.down_opt = Downsample(in_c, use_conv=use_conv)
def forward(self, x):
if self.down == True:
if self.down is True:
x = self.down_opt(x)
if self.in_conv is not None: # edit
x = self.in_conv(x)
@ -334,11 +333,11 @@ class extractor(nn.Module):
self.body = nn.Sequential(*self.body)
self.out_conv = nn.Conv2d(inter_c, out_c, 1, 1, 0)
self.down = down
if self.down == True:
if self.down is True:
self.down_opt = Downsample(in_c, use_conv=False)
def forward(self, x):
if self.down == True:
if self.down is True:
x = self.down_opt(x)
x = self.in_conv(x)
x = self.body(x)

View File

@ -9,7 +9,7 @@ from PIL import Image
import gradio as gr
from modules.api.models import *
from modules.api.models import * # noqa:F403
from modules.api import api
from scripts import external_code, global_state
@ -193,5 +193,5 @@ try:
import modules.script_callbacks as script_callbacks
script_callbacks.on_app_started(controlnet_api)
except:
pass
except Exception:
logger.warn("Unable to mount ControlNet API.")

View File

@ -8,7 +8,7 @@ try:
from sgm.modules.diffusionmodules.openaimodel import conv_nd, linear, zero_module, timestep_embedding, \
TimestepEmbedSequential, ResBlock, Downsample, SpatialTransformer, exists
using_sgm = True
except:
except ImportError:
from ldm.modules.diffusionmodules.openaimodel import conv_nd, linear, zero_module, timestep_embedding, \
TimestepEmbedSequential, ResBlock, Downsample, SpatialTransformer, exists
using_sgm = False

View File

@ -225,7 +225,7 @@ class PerceiverAttention(nn.Module):
x = self.norm1(x)
latents = self.norm2(latents)
b, l, _ = latents.shape
b, l, _ = latents.shape # noqa: E741
q = self.to_q(latents)
kv_input = torch.cat((x, latents), dim=-2)

View File

@ -4,7 +4,7 @@ import os
import logging
from collections import OrderedDict
from copy import copy
from typing import Dict, Optional, Tuple, List, NamedTuple
from typing import Dict, Optional, Tuple, List, Union
import modules.scripts as scripts
from modules import shared, devices, script_callbacks, processing, masking, images
from modules.api.api import decode_base64_to_image
@ -14,7 +14,7 @@ import time
from einops import rearrange
from scripts import global_state, hook, external_code, batch_hijack, controlnet_version, utils
from scripts.controlnet_lora import bind_control_lora, unbind_control_lora
from scripts.processor import *
from scripts.processor import HWC3, preprocessor_sliders_config
from scripts.controlnet_lllite import clear_all_lllite
from scripts.controlmodel_ipadapter import clear_all_ip_adapter
from scripts.utils import load_state_dict, get_unique_axis0, align_dim_latent
@ -321,10 +321,10 @@ class Script(scripts.Script, metaclass=(
controls.append(state)
else:
with gr.Column():
group, state = self.uigroup(f"ControlNet", is_img2img, elem_id_tabname, photopea)
group, state = self.uigroup("ControlNet", is_img2img, elem_id_tabname, photopea)
ui_groups.append(group)
controls.append(state)
with gr.Accordion(f"Batch Options", open=False, elem_id="controlnet_batch_options"):
with gr.Accordion("Batch Options", open=False, elem_id="controlnet_batch_options"):
self.ui_batch_options(is_img2img, elem_id_tabname)
for i, ui_group in enumerate(ui_groups):
@ -374,7 +374,7 @@ class Script(scripts.Script, metaclass=(
@staticmethod
def build_control_model(p, unet, model) -> ControlModel:
if model is None or model == 'None':
raise RuntimeError(f"You have not selected any ControlNet Model.")
raise RuntimeError("You have not selected any ControlNet Model.")
model_path = global_state.cn_models.get(model, None)
if model_path is None:
@ -1229,7 +1229,8 @@ class Script(scripts.Script, metaclass=(
def batch_tab_process_each(self, p, *args, **kwargs):
for unit_i, unit in enumerate(self.enabled_units):
if getattr(unit, 'loopback', False) and batch_hijack.instance.batch_index > 0: continue
if getattr(unit, 'loopback', False) and batch_hijack.instance.batch_index > 0:
continue
unit.image = next(unit.batch_images)
@ -1245,7 +1246,8 @@ class Script(scripts.Script, metaclass=(
def batch_tab_postprocess(self, p, *args, **kwargs):
self.enabled_units.clear()
self.input_image = None
if self.latest_network is None: return
if self.latest_network is None:
return
self.latest_network.restore()
self.latest_network = None

View File

@ -1,9 +1,6 @@
# https://gist.github.com/takuma104/4adfb3d968d80bea1d18a30c06439242
# 2nd editing by lllyasviel
import torch
# =================#
# UNet Conversion #
# =================#

View File

@ -3,8 +3,6 @@
import re
import torch
from modules import devices
class LLLiteModule(torch.nn.Module):
def __init__(
@ -146,7 +144,7 @@ class PlugableControlLLLite(torch.nn.Module):
cond_emb_dim=weights["conditioning1.0.weight"].shape[0] * 2,
mlp_dim=weights["down.0.weight"].shape[0],
)
info = module.load_state_dict(weights)
module.load_state_dict(weights)
modules[module_name] = module
setattr(self, module_name, module)
if len(modules) == 1:

View File

@ -526,7 +526,7 @@ class ControlNetUiGroup(object):
with gr.Row(elem_classes=["controlnet_control_type", "controlnet_row"]):
self.type_filter = gr.Radio(
list(preprocessor_filters.keys()),
label=f"Control Type",
label="Control Type",
value="All",
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_type_filter_radio",
elem_classes="controlnet_control_type_filter_group",
@ -535,7 +535,7 @@ class ControlNetUiGroup(object):
with gr.Row(elem_classes=["controlnet_preprocessor_model", "controlnet_row"]):
self.module = gr.Dropdown(
global_state.ui_preprocessor_keys,
label=f"Preprocessor",
label="Preprocessor",
value=self.default_unit.module,
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_preprocessor_dropdown",
)
@ -548,7 +548,7 @@ class ControlNetUiGroup(object):
)
self.model = gr.Dropdown(
list(global_state.cn_models.keys()),
label=f"Model",
label="Model",
value=self.default_unit.model,
elem_id=f"{elem_id_tabname}_{tabname}_controlnet_model_dropdown",
)
@ -560,7 +560,7 @@ class ControlNetUiGroup(object):
with gr.Row(elem_classes=["controlnet_weight_steps", "controlnet_row"]):
self.weight = gr.Slider(
label=f"Control Weight",
label="Control Weight",
value=self.default_unit.weight,
minimum=0.0,
maximum=2.0,

View File

@ -52,7 +52,7 @@ class OpenposeEditor(object):
# immediately navigate. Most of controlnet units do not need
# openpose editor active. Only navigate when the user first click
# 'Edit'. The navigation logic is in `openpose_editor.js`.
f'<iframe src="about:blank"></iframe>',
'<iframe src="about:blank"></iframe>',
open_button_text="Edit",
open_button_classes=["cnet-edit-pose"],
open_button_extra_attrs=f'title="Send pose to {OpenposeEditor.editor_url} for edit."',

View File

@ -131,7 +131,7 @@ class Photopea(object):
# Use about:blank here as placeholder so that the iframe does not
# immediately navigate. Only navigate when the user first click
# 'Edit'. The navigation logic is in `photopea.js`.
f"""
"""
<div class="photopea-button-group">
<button class="photopea-button photopea-fetch">Fetch from ControlNet</button>
<button class="photopea-button photopea-send">Send to ControlNet</button>
@ -172,7 +172,7 @@ class Photopea(object):
visible=False,
source="upload",
type="numpy",
elem_classes=[f"cnet-photopea-output"],
elem_classes=["cnet-photopea-output"],
)
output.upload(

View File

@ -1,7 +1,7 @@
version_flag = 'v1.1.440'
from scripts.logging import logger
version_flag = 'v1.1.440'
logger.info(f"ControlNet {version_flag}")
# A smart trick to know if user has updated as well as if user has restarted terminal.
# Note that in "controlnet.py" we do NOT use "importlib.reload" to reload this "controlnet_version.py"

View File

@ -1 +1 @@
from internal_controlnet.external_code import *
from internal_controlnet.external_code import * # noqa: F403

View File

@ -5,7 +5,7 @@ from collections import OrderedDict
from modules import shared, scripts, sd_models
from modules.paths import models_path
from scripts.processor import *
from scripts.processor import * # noqa: E403
import scripts.processor as processor
from scripts.utils import ndarray_lru_cache
from scripts.logging import logger

View File

@ -10,8 +10,6 @@ from scripts.enums import ControlModelType, AutoMachine, HiResFixOption
from scripts.controlmodel_ipadapter import ImageEmbed
from modules import devices, lowvram, shared, scripts
cond_cast_unet = getattr(devices, 'cond_cast_unet', lambda x: x)
from ldm.modules.diffusionmodules.util import timestep_embedding, make_beta_schedule
from ldm.modules.diffusionmodules.openaimodel import UNetModel
from ldm.modules.attention import BasicTransformerBlock
@ -23,10 +21,11 @@ from modules.processing import StableDiffusionProcessing
try:
from sgm.modules.attention import BasicTransformerBlock as BasicTransformerBlockSGM
except:
except ImportError:
print('Warning: ControlNet failed to load SGM - will use LDM instead.')
BasicTransformerBlockSGM = BasicTransformerBlock
cond_cast_unet = getattr(devices, 'cond_cast_unet', lambda x: x)
POSITIVE_MARK_TOKEN = 1024
NEGATIVE_MARK_TOKEN = - POSITIVE_MARK_TOKEN
@ -388,9 +387,9 @@ class UnetHook(nn.Module):
vae_output = p.sd_model.encode_first_stage(x)
vae_output = p.sd_model.get_first_stage_encoding(vae_output)
if torch.all(torch.isnan(vae_output)).item():
logger.info(f'ControlNet find Nans in the VAE encoding. \n '
f'Now ControlNet will automatically retry.\n '
f'To always start with 32-bit VAE, use --no-half-vae commandline flag.')
logger.info('ControlNet find Nans in the VAE encoding. \n '
'Now ControlNet will automatically retry.\n '
'To always start with 32-bit VAE, use --no-half-vae commandline flag.')
devices.dtype_vae = torch.float32
x = x.to(devices.dtype_vae)
p.sd_model.first_stage_model.to(devices.dtype_vae)
@ -562,7 +561,7 @@ class UnetHook(nn.Module):
x_in = x[:, :4, ...]
require_inpaint_hijack = True
assert param.used_hint_cond is not None, f"Controlnet is enabled but no input image is given"
assert param.used_hint_cond is not None, "Controlnet is enabled but no input image is given"
hint = param.used_hint_cond
if param.control_model_type == ControlModelType.InstantID:
@ -676,8 +675,8 @@ class UnetHook(nn.Module):
try:
# Trigger the register_forward_pre_hook
outer.sd_ldm.model()
except:
pass
except Exception as e:
logger.error(e)
# Clear attention and AdaIn cache
for module in outer.attn_module_list:

View File

@ -56,7 +56,7 @@ model_canny = None
def canny(img, res=512, thr_a=100, thr_b=200, **kwargs):
l, h = thr_a, thr_b
l, h = thr_a, thr_b # noqa: E741
img, remove_pad = resize_image_with_pad(img, res)
global model_canny
if model_canny is None:
@ -750,10 +750,10 @@ class InsightFaceModel:
img = HWC3(img)
faces = self.model.get(img)
if not faces:
raise Exception(f"Insightface: No face found in image.")
raise Exception("Insightface: No face found in image.")
if len(faces) > 1:
logger.warn("Insightface: More than one face is detected in the image. "
f"Only the first one will be used.")
"Only the first one will be used.")
return torch.from_numpy(faces[0].normed_embedding).unsqueeze(0), False
def run_model_instant_id(
@ -803,10 +803,10 @@ class InsightFaceModel:
img, remove_pad = resize_image_with_pad(img, res)
face_info = self.model.get(img)
if not face_info:
raise Exception(f"Insightface: No face found in image.")
raise Exception("Insightface: No face found in image.")
if len(face_info) > 1:
logger.warn("Insightface: More than one face is detected in the image. "
f"Only the biggest one will be used.")
"Only the biggest one will be used.")
# only use the maximum face
face_info = sorted(face_info, key=lambda x:(x['bbox'][2]-x['bbox'][0])*(x['bbox'][3]-x['bbox'][1]))[-1]
if return_keypoints: