Revert "much stricter ruff linting"

This reverts commit 310dbf1574.
This commit is contained in:
Vladimir Mandic
2026-05-11 08:13:57 +02:00
parent 8296d07ff8
commit c8d6fd5cf8
132 changed files with 363 additions and 292 deletions
+1 -1
View File
@@ -7,7 +7,7 @@ from modules.control.util import HWC3, resize_image
class CannyDetector:
def __call__(self, input_image=None, low_threshold=100, high_threshold=200, detect_resolution=512, image_resolution=512, output_type=None, **kwargs):
if "img" in kwargs:
warnings.warn("img is deprecated, please use `input_image=...` instead.", DeprecationWarning, stacklevel=2)
warnings.warn("img is deprecated, please use `input_image=...` instead.", DeprecationWarning)
input_image = kwargs.pop("img")
if input_image is None:
raise ValueError("input_image must be defined.")
@@ -1,4 +1,7 @@
import random
from PIL import Image, ImageOps, ImageFilter
import torch
from torchvision import transforms
import torch.nn.functional as F
import numpy as np
+1 -1
View File
@@ -16,7 +16,7 @@ class DepthProDetector:
self.processor = processor
@classmethod
def from_pretrained(cls, pretrained_model_or_path: str = "apple/DepthPro-hf", cache_dir: str | None = None, local_files_only = False) -> "DepthProDetector":
def from_pretrained(cls, pretrained_model_or_path: str = "apple/DepthPro-hf", cache_dir: str = None, local_files_only = False) -> "DepthProDetector":
from transformers import AutoImageProcessor, DepthProForDepthEstimation
processor = AutoImageProcessor.from_pretrained(pretrained_model_or_path, cache_dir=cache_dir, local_files_only=local_files_only)
+1 -1
View File
@@ -33,7 +33,7 @@ class EdgeDetector:
params.PFmode = pf
ed.setParams(params)
if "img" in kwargs:
warnings.warn("img is deprecated, please use `input_image=...` instead.", DeprecationWarning, stacklevel=2)
warnings.warn("img is deprecated, please use `input_image=...` instead.", DeprecationWarning)
input_image = kwargs.pop("img")
if input_image is None:
raise ValueError("input_image must be defined.")
@@ -5,7 +5,7 @@ import torch.nn as nn
try:
from urllib import urlretrieve
except ImportError:
pass
from urllib.request import urlretrieve
__all__ = ['resnext101_32x8d']
@@ -1,3 +1,4 @@
import torch
import torch.nn as nn
from . import network_auxi as network
@@ -384,7 +384,7 @@ class SenceUnderstand(nn.Module):
self.initial_params()
def forward(self, x):
n, _c, h, w = x.size()
n, c, h, w = x.size()
x = self.conv1(x)
x = self.pool(x)
x = x.view(n, -1)
@@ -1,8 +1,8 @@
import argparse
import os
from ...pix2pix.util import util # noqa: TID252
from ...pix2pix.util import util
# import torch
from ...pix2pix import models # noqa: TID252
from ...pix2pix import models
# import pix2pix.data
import numpy as np
@@ -113,7 +113,7 @@ class MarigoldPipeline(DiffusionPipeline):
batch_size: int = 0,
color_map: str = "Spectral",
show_progress_bar: bool = True,
ensemble_kwargs: Dict | None = None,
ensemble_kwargs: Dict = None,
) -> MarigoldDepthOutput:
"""
Function invoked when calling the pipeline.
@@ -43,7 +43,7 @@ def ensemble_depths(
max_iter: int = 2,
tol: float = 1e-3,
reduction: str = "median",
max_res: int | None = None,
max_res: int = None,
):
"""
To ensemble multiple affine-invariant depth images (up to scale and shift),
@@ -28,6 +28,6 @@ def seed_all(seed: int = 0):
Set random seeds of all components.
"""
random.seed(seed)
np.random.seed(seed)
np.random.seed(seed) # noqa
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
+1
View File
@@ -16,6 +16,7 @@ def check_dependencies():
if not installed(pkg[1], quiet=True):
install(pkg[0], pkg[1], ignore=False)
try:
import mediapipe as mp # pylint: disable=unused-import
checked_ok = True
return True
except Exception as e:
+1
View File
@@ -2,6 +2,7 @@
import cv2
import os
import torch
import torch.nn as nn
from torchvision.transforms import Compose
@@ -5,6 +5,7 @@ from .vit import (
_make_pretrained_vitb_rn50_384,
_make_pretrained_vitl16_384,
_make_pretrained_vitb16_384,
forward_vit,
)
def _make_encoder(backbone, features, use_pretrained, groups=1, expand=False, exportable=True, hooks=None, use_vit_only=False, use_readout="ignore",):
@@ -1,8 +1,10 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
from .base_model import BaseModel
from .blocks import (
FeatureFusionBlock,
FeatureFusionBlock_custom,
Interpolate,
_make_encoder,
@@ -6,7 +6,7 @@ import torch
import torch.nn as nn
from .base_model import BaseModel
from .blocks import FeatureFusionBlock_custom, Interpolate, _make_encoder
from .blocks import FeatureFusionBlock, FeatureFusionBlock_custom, Interpolate, _make_encoder
class MidasNet_small(BaseModel):
+2 -2
View File
@@ -54,7 +54,7 @@ class Transpose(nn.Module):
def forward_vit(pretrained, x):
_b, _c, h, w = x.shape
b, c, h, w = x.shape
pretrained.model.forward_flex(x)
@@ -115,7 +115,7 @@ def _resize_pos_embed(self, posemb, gs_h, gs_w):
def forward_flex(self, x):
_b, _c, h, w = x.shape
b, c, h, w = x.shape
pos_embed = self._resize_pos_embed(
self.pos_embed, h // self.patch_size[1], w // self.patch_size[0]
+2 -2
View File
@@ -75,7 +75,7 @@ def write_pfm(path, image, scale=1):
if len(image.shape) == 3 and image.shape[2] == 3: # color image
color = True
elif (
len(image.shape) == 2 or (len(image.shape) == 3 and image.shape[2] == 1)
len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1
): # greyscale
color = False
else:
@@ -86,7 +86,7 @@ def write_pfm(path, image, scale=1):
endian = image.dtype.byteorder
if endian == "<" or (endian == "=" and sys.byteorder == "little"):
if endian == "<" or endian == "=" and sys.byteorder == "little":
scale = -scale
file.write("%f\n".encode() % scale)
@@ -1,3 +1,5 @@
import os
import sys
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
@@ -1,3 +1,5 @@
import os
import sys
import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
+4 -3
View File
@@ -9,6 +9,7 @@ Copyright 2021-present NAVER Corp.
Apache License v2.0
'''
import os
import numpy as np
import cv2
import torch
@@ -21,7 +22,7 @@ def deccode_output_score_and_ptss(tpMap, topk_n = 200, ksize = 5):
center: tpMap[1, 0, :, :]
displacement: tpMap[1, 1:5, :, :]
'''
b, _c, _h, w = tpMap.shape
b, c, h, w = tpMap.shape
assert b==1, 'only support bsize==1'
displacement = tpMap[:, 1:5, :, :][0]
center = tpMap[:, 0, :, :]
@@ -470,9 +471,9 @@ def pred_squares(image,
square[end_idx]
# check whether outside or inside
_start_position, start_min, start_cover_param, start_peri_param = check_outside_inside(start_segments,
start_position, start_min, start_cover_param, start_peri_param = check_outside_inside(start_segments,
connect_idx)
_end_position, end_min, end_cover_param, end_peri_param = check_outside_inside(end_segments, connect_idx)
end_position, end_min, end_cover_param, end_peri_param = check_outside_inside(end_segments, connect_idx)
cover += dist_segments[connect_idx] + start_cover_param * start_min + end_cover_param * end_min
perimeter += dist_segments[connect_idx] + start_peri_param * start_min + end_peri_param * end_min
+3 -3
View File
@@ -194,14 +194,14 @@ class OpenposeDetector:
def __call__(self, input_image, detect_resolution=512, image_resolution=512, include_body=True, include_hand=False, include_face=False, hand_and_face=None, output_type="pil", **kwargs):
self.to(devices.device)
if hand_and_face is not None:
warnings.warn("hand_and_face is deprecated. Use include_hand and include_face instead.", DeprecationWarning, stacklevel=2)
warnings.warn("hand_and_face is deprecated. Use include_hand and include_face instead.", DeprecationWarning)
include_hand = hand_and_face
include_face = hand_and_face
if "return_pil" in kwargs:
warnings.warn("return_pil is deprecated. Use output_type instead.", DeprecationWarning, stacklevel=2)
warnings.warn("return_pil is deprecated. Use output_type instead.", DeprecationWarning)
output_type = "pil" if kwargs["return_pil"] else "np"
if type(output_type) is bool:
warnings.warn("Passing `True` or `False` to `output_type` is deprecated and will raise an error in future versions", stacklevel=2)
warnings.warn("Passing `True` or `False` to `output_type` is deprecated and will raise an error in future versions")
if output_type:
output_type = "pil"
if not isinstance(input_image, np.ndarray):
+1 -1
View File
@@ -328,7 +328,7 @@ class Face(object):
def __call__(self, face_img):
device = next(iter(self.model.parameters())).device
H, W, _C = face_img.shape
H, W, C = face_img.shape
w_size = 384
x_data = torch.from_numpy(util.smart_resize(face_img, (w_size, w_size))).permute([2, 0, 1]) / 256.0 - 0.5
+1 -1
View File
@@ -32,7 +32,7 @@ class Hand(object):
wsize = 128
heatmap_avg = np.zeros((wsize, wsize, 22))
Hr, Wr, _Cr = oriImgRaw.shape
Hr, Wr, Cr = oriImgRaw.shape
oriImg = cv2.GaussianBlur(oriImgRaw, (0, 0), 0.8)
@@ -53,7 +53,7 @@ class SamDetector:
def __call__(self, input_image: Union[np.ndarray, Image.Image]=None, detect_resolution=512, image_resolution=512, output_type="pil", **kwargs) -> Image.Image:
if "image" in kwargs:
warnings.warn("image is deprecated, please use `input_image=...` instead.", DeprecationWarning, stacklevel=2)
warnings.warn("image is deprecated, please use `input_image=...` instead.", DeprecationWarning)
input_image = kwargs.pop("image")
if input_image is None:
raise ValueError("input_image must be defined.")
@@ -25,8 +25,8 @@ class Sam(nn.Module):
image_encoder: Union[ImageEncoderViT, TinyViT],
prompt_encoder: PromptEncoder,
mask_decoder: MaskDecoder,
pixel_mean: List[float] | None = None,
pixel_std: List[float] | None = None,
pixel_mean: List[float] = None,
pixel_std: List[float] = None,
) -> None:
"""
SAM predicts object masks from an image and input prompts.
@@ -79,7 +79,7 @@ class TwoWayTransformer(nn.Module):
torch.Tensor: the processed image_embedding
"""
# BxCxHxW -> BxHWxC == B x N_image_tokens x C
_bs, _c, _h, _w = image_embedding.shape
bs, c, h, w = image_embedding.shape
image_embedding = image_embedding.flatten(2).permute(0, 2, 1)
image_pe = image_pe.flatten(2).permute(0, 2, 1)
@@ -10,7 +10,7 @@ from torch.nn import functional as F
from typing import Tuple
from ..modeling import Sam # noqa: TID252
from ..modeling import Sam
from .amg import calculate_stability_score
+5 -5
View File
@@ -10,10 +10,10 @@ from modules.control.util import HWC3, img2mask, make_noise_disk, resize_image
class ContentShuffleDetector:
def __call__(self, input_image, h=None, w=None, f=None, detect_resolution=512, image_resolution=512, output_type="pil", **kwargs):
if "return_pil" in kwargs:
warnings.warn("return_pil is deprecated. Use output_type instead.", DeprecationWarning, stacklevel=2)
warnings.warn("return_pil is deprecated. Use output_type instead.", DeprecationWarning)
output_type = "pil" if kwargs["return_pil"] else "np"
if type(output_type) is bool:
warnings.warn("Passing `True` or `False` to `output_type` is deprecated and will raise an error in future versions", stacklevel=2)
warnings.warn("Passing `True` or `False` to `output_type` is deprecated and will raise an error in future versions")
if output_type:
output_type = "pil"
@@ -49,7 +49,7 @@ class ContentShuffleDetector:
class ColorShuffleDetector:
def __call__(self, img):
H, W, C = img.shape
F = np.random.randint(64, 384)
F = np.random.randint(64, 384) # noqa
A = make_noise_disk(H, W, 3, F)
B = make_noise_disk(H, W, 3, F)
C = (A + B) / 2.0
@@ -82,11 +82,11 @@ class DownSampleDetector:
def __call__(self, img, level=3, k=16.0):
h = img.astype(np.float32)
for _ in range(level):
h += np.random.normal(loc=0.0, scale=k, size=h.shape)
h += np.random.normal(loc=0.0, scale=k, size=h.shape) # noqa
h = cv2.pyrDown(h)
for _ in range(level):
h = cv2.pyrUp(h)
h += np.random.normal(loc=0.0, scale=k, size=h.shape)
h += np.random.normal(loc=0.0, scale=k, size=h.shape) # noqa
return h.clip(0, 255).astype(np.uint8)
@@ -66,7 +66,7 @@ def attention_forward(self, x, resolution, shared_rel_pos_bias: Optional[torch.T
"""
Modification of timm.models.beit.py: Attention.forward to support arbitrary window sizes.
"""
B, N, _C = x.shape
B, N, C = x.shape
qkv_bias = torch.cat((self.q_bias, self.k_bias, self.v_bias)) if self.q_bias is not None else None
qkv = F.linear(input=x, weight=self.qkv.weight, bias=qkv_bias)
@@ -81,7 +81,7 @@ def forward_default(pretrained, x, function_name="forward_features"):
def forward_adapted_unflatten(pretrained, x, function_name="forward_features"):
_b, _c, h, w = x.shape
b, c, h, w = x.shape
exec(f"glob = pretrained.model.{function_name}(x)")
@@ -31,7 +31,7 @@ def _resize_pos_embed(self, posemb, gs_h, gs_w):
def forward_flex(self, x):
_b, _c, h, w = x.shape
b, c, h, w = x.shape
pos_embed = self._resize_pos_embed(
self.pos_embed, h // self.patch_size[1], w // self.patch_size[0]
@@ -5,6 +5,10 @@ from .backbones.beit import (
_make_pretrained_beitl16_512,
_make_pretrained_beitl16_384,
_make_pretrained_beitb16_384,
forward_beit,
)
from .backbones.swin_common import (
forward_swin,
)
from .backbones.swin2 import (
_make_pretrained_swin2l24_384,
@@ -16,11 +20,13 @@ from .backbones.swin import (
)
from .backbones.levit import (
_make_pretrained_levit_384,
forward_levit,
)
from .backbones.vit import (
_make_pretrained_vitb_rn50_384,
_make_pretrained_vitl16_384,
_make_pretrained_vitb16_384,
forward_vit,
)
def _make_encoder(backbone, features, use_pretrained, groups=1, expand=False, exportable=True, hooks=None,
@@ -6,7 +6,7 @@ import torch
import torch.nn as nn
from .base_model import BaseModel
from .blocks import FeatureFusionBlock_custom, Interpolate, _make_encoder
from .blocks import FeatureFusionBlock, FeatureFusionBlock_custom, Interpolate, _make_encoder
class MidasNet_small(BaseModel):
@@ -100,7 +100,7 @@ class AttractorLayer(nn.Module):
A = self._net(x)
eps = 1e-3
A = A + eps
n, _c, h, w = A.shape
n, c, h, w = A.shape
A = A.view(n, self.n_attractors, 2, h, w)
A_normed = A / A.sum(dim=2, keepdim=True) # n, a, 2, h, w
A_normed = A[:, :, 0, ...] # n, na, h, w
@@ -177,7 +177,7 @@ class AttractorLayerUnnormed(nn.Module):
x = x + prev_b_embedding
A = self._net(x)
_n, _c, h, w = A.shape
n, c, h, w = A.shape
b_prev = nn.functional.interpolate(
b_prev, (h, w), mode='bilinear', align_corners=True)
@@ -146,7 +146,7 @@ class LinearSplitter(nn.Module):
S = self._net(x)
eps = 1e-3
S = S + eps
n, _c, h, w = S.shape
n, c, h, w = S.shape
S = S.view(n, self.prev_nbins, self.split_factor, h, w)
S_normed = S / S.sum(dim=2, keepdim=True) # fractional splits
@@ -26,13 +26,13 @@ import itertools
import torch
import torch.nn as nn
from ..depth_model import DepthModel # noqa: TID252
from ..base_models.midas import MidasCore # noqa: TID252
from ..layers.attractor import AttractorLayer, AttractorLayerUnnormed # noqa: TID252
from ..layers.dist_layers import ConditionalLogBinomial # noqa: TID252
from ..layers.localbins_layers import (Projector, SeedBinRegressor, # noqa: TID252
from ..depth_model import DepthModel
from ..base_models.midas import MidasCore
from ..layers.attractor import AttractorLayer, AttractorLayerUnnormed
from ..layers.dist_layers import ConditionalLogBinomial
from ..layers.localbins_layers import (Projector, SeedBinRegressor,
SeedBinRegressorUnnormed)
from ..model_io import load_state_from_resource # noqa: TID252
from ..model_io import load_state_from_resource
class ZoeDepth(DepthModel):
@@ -139,7 +139,7 @@ class ZoeDepth(DepthModel):
- probs (torch.Tensor): Output probability distribution of shape (B, n_bins, H, W). Present only if return_probs is True
"""
b, _c, h, w = x.shape
b, c, h, w = x.shape
# print("input shape ", x.shape)
self.orig_input_width = w
self.orig_input_height = h
@@ -27,14 +27,14 @@ import itertools
import torch
import torch.nn as nn
from ..depth_model import DepthModel # noqa: TID252
from ..base_models.midas import MidasCore # noqa: TID252
from ..layers.attractor import AttractorLayer, AttractorLayerUnnormed # noqa: TID252
from ..layers.dist_layers import ConditionalLogBinomial # noqa: TID252
from ..layers.localbins_layers import (Projector, SeedBinRegressor, # noqa: TID252
from ..depth_model import DepthModel
from ..base_models.midas import MidasCore
from ..layers.attractor import AttractorLayer, AttractorLayerUnnormed
from ..layers.dist_layers import ConditionalLogBinomial
from ..layers.localbins_layers import (Projector, SeedBinRegressor,
SeedBinRegressorUnnormed)
from ..layers.patch_transformer import PatchTransformerEncoder # noqa: TID252
from ..model_io import load_state_from_resource # noqa: TID252
from ..layers.patch_transformer import PatchTransformerEncoder
from ..model_io import load_state_from_resource
class ZoeDepthNK(DepthModel):
def __init__(self, core, bin_conf, bin_centers_type="softplus", bin_embedding_dim=128,
@@ -173,10 +173,10 @@ class ZoeDepthNK(DepthModel):
- "bin_centers": Bin centers of shape (B, N, H, W). Present only if return_final_centers is True
- "probs": Bin probabilities of shape (B, N, H, W). Present only if return_probs is True
"""
b, _c, h, w = x.shape
b, c, h, w = x.shape
self.orig_input_width = w
self.orig_input_height = h
_rel_depth, out = self.core(x, denorm=denorm, return_rel_depth=True)
rel_depth, out = self.core(x, denorm=denorm, return_rel_depth=True)
outconv_activation = out[0]
btlnck = out[1]