Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

refactor: hide accidental module globals (#4141)

fly1d754cd9342d5d
diff --git a/kornia/constants.py b/kornia/constants.py
index 15aba0ac1..1ced39b1a 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -25,8 +25,8 @@ __all__ = ["BorderType", "DType", "Resample", "SamplePadding", "TKEnum", "pi"]
pi = torch.tensor(3.14159265358979323846)
-T = TypeVar("T", bound=Enum)
-TKEnum = Union[str, int, T]
+_T = TypeVar("_T", bound=Enum)
+TKEnum = Union[str, int, _T]
class _KORNIA_EnumMeta(EnumMeta):
@@ -48,7 +48,7 @@ class _KORNIA_EnumMeta(EnumMeta):
return " | ".join(f"{self.__name__}.{val.name}" for val in self)
-def _get(cls: Type[T], value: TKEnum[T]) -> T:
+def _get(cls: Type[_T], value: TKEnum[_T]) -> _T:
if isinstance(value, str):
return cls[value.upper()]
diff --git a/kornia/contrib/boxmot_tracker.py b/kornia/contrib/boxmot_tracker.py
index a6a351d62..9db8b71aa 100644
--- a/kornia/contrib/boxmot_tracker.py
+++ b/kornia/contrib/boxmot_tracker.py
@@ -34,7 +34,7 @@ from kornia.io import write_image
__all__ = ["BoxMotTracker"]
-logger = logging.getLogger(__name__)
+_logger = logging.getLogger(__name__)
class BoxMotTracker:
@@ -179,4 +179,4 @@ class BoxMotTracker:
os.path.join(directory, f"{str(0).zfill(6)}.jpg"),
output.byte(),
)
- logger.info(f"Outputs are saved in {directory}")
+ _logger.info(f"Outputs are saved in {directory}")
diff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.py
index 6e71e8a48..447c8b3b9 100644
--- a/kornia/contrib/super_resolution.py
+++ b/kornia/contrib/super_resolution.py
@@ -31,7 +31,7 @@ from kornia.onnx.download import CachedDownloader
__all__ = ["RRDBNetBuilder", "SmallSRBuilder", "SuperResolution"]
-URLs = {
+_URLs = {
"RealESRGAN_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",
"RealESRNet_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.1/RealESRNet_x4plus.pth",
"RealESRGAN_x4plus_anime_6B": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth",
@@ -210,7 +210,7 @@ class RRDBNetBuilder:
model_path = None
if pretrained:
- url = URLs[model_name]
+ url = _URLs[model_name]
model_path = CachedDownloader.download_to_cache(
url, model_name, download=True, suffix=".pth", cache_dir=kornia_config.hub_onnx_dir
)
diff --git a/kornia/core/check.py b/kornia/core/check.py
index 1fc5e82e5..39eeaeb84 100644
--- a/kornia/core/check.py
+++ b/kornia/core/check.py
@@ -266,10 +266,10 @@ def KORNIA_UNWRAP(maybe_obj: Any, typ: Any) -> Any:
return cast(typ, maybe_obj)
-T = TypeVar("T", bound=type)
+_T = TypeVar("_T", bound=type)
-def KORNIA_CHECK_TYPE(x: Any, typ: T | tuple[T, ...], msg: Optional[str] = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_TYPE(x: Any, typ: _T | tuple[_T, ...], msg: Optional[str] = None, raises: bool = True) -> bool:
"""Check the type of an aribratry variable.
Args:
diff --git a/kornia/feature/lightglue_onnx/lightglue.py b/kornia/feature/lightglue_onnx/lightglue.py
index 52f92ca1a..ebb25d864 100644
--- a/kornia/feature/lightglue_onnx/lightglue.py
+++ b/kornia/feature/lightglue_onnx/lightglue.py
@@ -26,11 +26,11 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CH
from .utils import download_onnx_from_url, normalize_keypoints
try:
- import numpy as np
- import onnxruntime as ort
+ import numpy as _np # noqa: ICN001
+ import onnxruntime as _ort
except ImportError:
- np = None # type: ignore
- ort = None
+ _np = None # type: ignore
+ _ort = None
__all__ = ["OnnxLightGlue"]
@@ -62,8 +62,8 @@ class OnnxLightGlue:
required_data_keys: ClassVar[list[str]] = ["image0", "image1"]
def __init__(self, weights: str | None = None, device: Union[str, torch.device, None] = "cpu") -> None:
- KORNIA_CHECK(ort is not None, "onnxruntime is not installed.")
- KORNIA_CHECK(np is not None, "numpy is not installed.")
+ KORNIA_CHECK(_ort is not None, "onnxruntime is not installed.")
+ KORNIA_CHECK(_np is not None, "numpy is not installed.")
device = torch.device(device) # type: ignore
self.device = device
@@ -88,7 +88,7 @@ class OnnxLightGlue:
weights = download_onnx_from_url(url)
- self.session = ort.InferenceSession(weights, providers=providers)
+ self.session = _ort.InferenceSession(weights, providers=providers)
def __call__(self, data: dict[str, dict[str, torch.Tensor]]) -> dict[str, torch.Tensor]:
"""Run the ONNX LightGlue matcher.
@@ -173,7 +173,7 @@ class OnnxLightGlue:
name,
device_type=self.device.type,
device_id=0,
- element_type=np.float32,
+ element_type=_np.float32,
shape=tuple(tensor.shape),
buffer_ptr=tensor.data_ptr(),
)
diff --git a/kornia/io/sample.py b/kornia/io/sample.py
index e681a3d67..fbde83b30 100644
--- a/kornia/io/sample.py
+++ b/kornia/io/sample.py
@@ -32,7 +32,7 @@ __all__ = [
"get_sample_images",
]
-IMAGE_URLS: List[str] = [
+_IMAGE_URLS: List[str] = [
"https://raw.githubusercontent.com/kornia/data/main/panda.jpg",
"https://raw.githubusercontent.com/kornia/data/main/simba.png",
"https://raw.githubusercontent.com/kornia/data/main/girona.png",
@@ -56,7 +56,7 @@ def download_image(url: str, save_to: str) -> None:
def get_sample_images(
resize: Optional[Tuple[int, int]] = None,
- paths: List[str] = IMAGE_URLS,
+ paths: List[str] = _IMAGE_URLS,
download: bool = True,
cache_dir: Optional[str] = None,
as_list: Optional[bool] = None,
@@ -72,7 +72,7 @@ def get_sample_images(
Args:
paths: A list of path or URL from which to load or download images.
- Defaults to a pre-defined constant `IMAGE_URLS` if not provided.
+ Defaults to the pre-defined sample image URLs if not provided.
resize: Optional target size for resizing all images as a tuple (height, width).
If not provided, the images will not be resized, and their original sizes will be retained.
download: Whether to download the images if they are not already cached. Defaults to True.
diff --git a/kornia/models/dexined.py b/kornia/models/dexined.py
index 164d6eff3..974fa5caa 100644
--- a/kornia/models/dexined.py
+++ b/kornia/models/dexined.py
@@ -32,7 +32,7 @@ from kornia.core.mixin.onnx import ONNXExportMixin
__all__ = ["DexiNed"]
-url: str | list[str] = [
+_url: str | list[str] = [
hf_url("dexined", "DexiNed_BIPED_10.pth"),
"http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth",
]
@@ -241,7 +241,7 @@ class DexiNed(ONNXExportMixin, nn.Module):
# self.block_cat = CoFusion(6,6)# cats fusion method
if pretrained:
- self.load_from_file(url)
+ self.load_from_file(_url)
else:
self.apply(weight_init)
diff --git a/kornia/models/kimi_vl/builder.py b/kornia/models/kimi_vl/builder.py
index 3e69756d1..7008fe350 100644
--- a/kornia/models/kimi_vl/builder.py
+++ b/kornia/models/kimi_vl/builder.py
@@ -27,7 +27,7 @@ import torch
from .config import KimiVLConfig, _kimi_vl_a3b_instruct_config
from .model import KimiVLModel
-logger = logging.getLogger(__name__)
+_logger = logging.getLogger(__name__)
__all__ = ["KimiVLBuilder"]
@@ -44,7 +44,7 @@ def _download_weights(model_name: str, cache_dir: Optional[str]) -> dict[str, to
"huggingface_hub and safetensors are required for loading model weights. "
"Install them with: pip install huggingface_hub safetensors"
)
- logger.error(error_msg)
+ _logger.error(error_msg)
raise ImportError(error_msg) from e
weights_path = hf_hub_download(repo_id=model_name, filename="model.safetensors", cache_dir=cache_dir)
diff --git a/kornia/models/siglip2/builder.py b/kornia/models/siglip2/builder.py
index ed8675a67..f06476a33 100644
--- a/kornia/models/siglip2/builder.py
+++ b/kornia/models/siglip2/builder.py
@@ -27,7 +27,7 @@ import torch
from .config import SigLip2Config
from .model import SigLip2Model
-logger = logging.getLogger(__name__)
+_logger = logging.getLogger(__name__)
__all__ = ["SigLip2Builder"]
@@ -41,7 +41,7 @@ def _download_weights(model_name: str, cache_dir: Optional[str]) -> dict[str, to
error_msg = (
"safetensors library is required for loading model weights. Install it with: pip install safetensors"
)
- logger.error(error_msg)
+ _logger.error(error_msg)
raise ImportError(error_msg) from e
try:
@@ -55,7 +55,7 @@ def _download_weights(model_name: str, cache_dir: Optional[str]) -> dict[str, to
error_msg = (
f"Could not find model.safetensors for {model_name}. The model must be available in safetensors format."
)
- logger.error(error_msg)
+ _logger.error(error_msg)
raise FileNotFoundError(error_msg) from e
diff --git a/kornia/models/yunet/model.py b/kornia/models/yunet/model.py
index 8c62d3acb..aef7d5bf6 100644
--- a/kornia/models/yunet/model.py
+++ b/kornia/models/yunet/model.py
@@ -26,7 +26,7 @@ from kornia.core.download import hf_url, load_state_dict_from_url
__all__ = ["YuNet"]
-url: Union[str, List[str]] = [
+_url: Union[str, List[str]] = [
hf_url("yunet", "yunet_final.pth"),
"https://github.com/kornia/data/raw/main/yunet_final.pth",
]
@@ -109,7 +109,7 @@ class YuNet(nn.Module):
# use torch.hub to load pretrained model
if pretrained:
- pretrained_dict = load_state_dict_from_url(url, map_location=torch.device("cpu"))
+ pretrained_dict = load_state_dict_from_url(_url, map_location=torch.device("cpu"))
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
diff --git a/kornia/onnx/download.py b/kornia/onnx/download.py
index 3f8cfcc1f..7e7a02661 100644
--- a/kornia/onnx/download.py
+++ b/kornia/onnx/download.py
@@ -26,7 +26,7 @@ from kornia.config import kornia_config
__all__ = ["CachedDownloader"]
-logger = logging.getLogger(__name__)
+_logger = logging.getLogger(__name__)
class CachedDownloader:
@@ -105,7 +105,7 @@ class CachedDownloader:
"""
if os.path.exists(file_path):
- logger.info(f"Loading `{url}` from `{file_path}`.")
+ _logger.info(f"Loading `{url}` from `{file_path}`.")
return
if not download_if_not_exists:
@@ -115,7 +115,7 @@ class CachedDownloader:
if url.startswith(("http:", "https:")):
try:
- logger.info(f"Downloading `{url}` to `{file_path}`.")
+ _logger.info(f"Downloading `{url}` to `{file_path}`.")
urllib.request.urlretrieve(url, file_path) # noqa: S310
except urllib.error.HTTPError as e:
raise ValueError(f"Error in resolving `{url}`.") from e
diff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.py
index 70325f23c..ddd8649a5 100644
--- a/kornia/onnx/utils.py
+++ b/kornia/onnx/utils.py
@@ -31,7 +31,7 @@ from kornia.onnx.download import CachedDownloader
__all__ = ["ONNXLoader", "add_metadata", "io_name_conversion"]
-logger = logging.getLogger(__name__)
+_logger = logging.getLogger(__name__)
class ONNXLoader(CachedDownloader):
diff --git a/tests/core/test_weights_prefetch.py b/tests/core/test_weights_prefetch.py
index 76b81b668..fdcea9033 100644
--- a/tests/core/test_weights_prefetch.py
+++ b/tests/core/test_weights_prefetch.py
@@ -123,13 +123,13 @@ WEIGHT_REGISTRIES: dict[str, tuple[ModuleType, dict[str, Any]]] = {
"dedode": (dedode, dedode.urls),
"rt_detr": (rt_detr, rt_detr.URLs),
"keynet": (keynet, {"keynet": keynet.KeyNet_URL}),
- "yunet": (yunet, {"yunet": yunet.url}),
+ "yunet": (yunet, {"yunet": yunet._url}),
# Two independent registries, identical today, both loading the same cache
# name -- which is what hides the models copy from the coverage check: the
# filters copy accounts for the name either way. Holding both to MODELS also
# holds the two copies equal to each other.
"dexined": (dexined, {"dexined": dexined.url}),
- "dexined_model": (dexined_model, {"dexined": dexined_model.url}),
+ "dexined_model": (dexined_model, {"dexined": dexined_model._url}),
"xfeat": (xfeat, {"xfeat": xfeat.XFeat.weights_url}),
"dedode_encoder": (dedode_encoder, dedode_encoder.urls),
"tiny_vit": (tiny_vit, tiny_vit.urls),