π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): time out LightGlue ONNX downloads (#5375)
Karnajeet Gosavi77da580e9419
diff --git a/changelog.d/5375.fixed.md b/changelog.d/5375.fixed.mdnew file mode 100644index 000000000..3477d48fc--- /dev/null+++ b/changelog.d/5375.fixed.md@@ -0,0 +1 @@+LightGlue ONNX downloads (`download_onnx_from_url`, which `OnnxLightGlue` uses) now go through `kornia.core.download`. A server that stalls fails the attempt after `KORNIA_DOWNLOAD_TIMEOUT` seconds (30 s by default) instead of hanging, a transfer shorter than its `Content-Length` is no longer cached as the model, transient failures are retried, a `~` in `model_dir` is expanded, and `check_hash=True` also checks a file already in the cache and fetches it again on a mismatch. A failed download now raises `RuntimeError` naming the URL and the cache path, with the original error chained as its cause; it used to raise that error (`urllib.error.HTTPError`, `urllib.error.URLError`) directly.diff --git a/kornia/core/download.py b/kornia/core/download.pyindex 5e2570b5b..1412c38ed 100644--- a/kornia/core/download.py+++ b/kornia/core/download.py@@ -1035,9 +1035,7 @@ def load_state_dict_from_url(url: str | list[str], *, timeout: float | None = Noleaves torch with nothing to report. Nothing process-global is touched:redirecting :data:`sys.stdout` around the call would divert unrelatedthreads' output for the whole transfer, and concurrent calls restoring out- of order would leave stdout permanently pointing at stderr. This mirrors- :func:`kornia.feature.lightglue_onnx.utils.download.download_onnx_from_url`,- which already reimplements torch's caching for the same reason.+ of order would leave stdout permanently pointing at stderr.When multiple URLs are given and ``file_name`` is not already in *kwargs*,the basename of the **first** URL is used as the local cache filename fordiff --git a/kornia/feature/lightglue_onnx/utils/download.py b/kornia/feature/lightglue_onnx/utils/download.pyindex 6ccb79f98..0ffa54326 100644--- a/kornia/feature/lightglue_onnx/utils/download.py+++ b/kornia/feature/lightglue_onnx/utils/download.py@@ -17,12 +17,14 @@from __future__ import annotations+import hashlibimport os-import sysfrom typing import Optionalfrom urllib.parse import urlparse-from torch.hub import HASH_REGEX, download_url_to_file, get_dir+from torch.hub import HASH_REGEX++from kornia.core import download as core_downloaddef download_onnx_from_url(@@ -31,50 +33,62 @@ def download_onnx_from_url(progress: bool = True,check_hash: bool = False,file_name: Optional[str] = None,+ timeout: Optional[float] = None,) -> str:- r"""Load the ONNX model at the given URL.-- If downloaded file is a zip file, it will be automatically- decompressed.+ r"""Download the ONNX model at the given URL into the cache and return its path.- If the object is already present in `model_dir`, it's deserialized and- returned.+ A file already present in ``model_dir`` is returned without a request.The default value of ``model_dir`` is ``<hub_dir>/checkpoints`` where``hub_dir`` is the directory returned by :func:`~torch.hub.get_dir`.+ The transfer goes through :func:`kornia.core.download.download_file_from_url`,+ which bounds a stalled server, retries transient failures and leaves no+ partial file in the cache.Args:url (str): URL of the object to download- model_dir (str, optional): directory in which to save the object+ model_dir (str, optional): directory in which to save the object; a leading ``~`` is expandedprogress (bool, optional): whether or not to display a progress bar to stderr.Default: Truecheck_hash(bool, optional): If True, the filename part of the URL should follow the naming convention``filename-<sha256>.ext`` where ``<sha256>`` is the first eight or moredigits of the SHA256 hash of the contents of the file. The hash is used to- ensure unique names and to verify the contents of the file.+ ensure unique names and to verify the contents of the file. A file already in the cache+ is checked too, and fetched again if it does not match.Default: Falsefile_name (str, optional): name for the downloaded file. Filename from ``url`` will be used if not set.+ timeout (float, optional): maximum seconds a connection or read may stall. Defaults to the+ ``KORNIA_DOWNLOAD_TIMEOUT`` environment variable or 30 seconds.++ Returns:+ The path of the cached file.++ Raises:+ RuntimeError: if the download fails, or with ``check_hash`` the file does not match its hash. The+ original error is chained as the cause.Example:>>> model = download_onnx_from_url('https://github.com/fabio-sim/LightGlue-ONNX/releases/download/v1.0.0/disk_lightglue_fused_fp16.onnx')"""- if model_dir is None:- hub_dir = get_dir()- model_dir = os.path.join(hub_dir, "checkpoints")-- os.makedirs(model_dir, exist_ok=True)-parts = urlparse(url)filename = os.path.basename(parts.path)if file_name is not None:filename = file_name- cached_file = os.path.join(model_dir, filename)- if not os.path.exists(cached_file):- sys.stderr.write(f'Downloading: "{url}" to {cached_file}\n')- hash_prefix = None- if check_hash:- r = HASH_REGEX.search(filename) # r is Optional[Match[str]]- hash_prefix = r.group(1) if r else None- download_url_to_file(url, cached_file, hash_prefix, progress=progress)+ validate = None+ if check_hash:+ match = HASH_REGEX.search(filename)+ if match is not None:+ hash_prefix = match.group(1)++ def validate(file_path: str) -> None:+ digest = hashlib.sha256()+ with open(file_path, "rb") as file:+ for chunk in iter(lambda: file.read(128 * 1024), b""):+ digest.update(chunk)+ actual_hash = digest.hexdigest()+ if actual_hash[: len(hash_prefix)] != hash_prefix:+ raise RuntimeError(f'invalid hash value (expected "{hash_prefix}", got "{actual_hash}")')- return cached_file+ return core_download.download_file_from_url(+ url, file_name=filename, model_dir=model_dir, progress=progress, validate=validate, timeout=timeout+ )diff --git a/testing/doctest_downloads.py b/testing/doctest_downloads.pyindex 87daddb33..f2b63d3ee 100644--- a/testing/doctest_downloads.py+++ b/testing/doctest_downloads.py@@ -40,15 +40,11 @@ DOWNLOAD_ENV_VAR = "KORNIA_DOCTEST_DOWNLOAD"# Entry points that reach the network only on a cache miss, as# ``(module, attribute)`` pairs resolved lazily at patch time.-#-# ``kornia.feature.lightglue_onnx.utils.download`` binds ``download_url_to_file``-# at import time, so patching ``torch.hub`` alone would not cover it._DOWNLOAD_PRIMITIVES: tuple[tuple[str, str], ...] = (# kornia.core.download runs its own transfer (torch's has no timeout), so every# load_state_dict_from_url / download_file_from_url cache miss reaches the network here.("kornia.core.download", "_download_url_to_file"),("torch.hub", "download_url_to_file"),- ("kornia.feature.lightglue_onnx.utils.download", "download_url_to_file"),# kornia.onnx.download.CachedDownloader.download reaches the network here.("urllib.request", "urlretrieve"),)diff --git a/tests/core/test_weights_prefetch.py b/tests/core/test_weights_prefetch.pyindex 39b66d7c5..8933c7c58 100644--- a/tests/core/test_weights_prefetch.py+++ b/tests/core/test_weights_prefetch.py@@ -36,10 +36,10 @@ Scope: this guards the checkpoints that go throughenumerated in :data:`WEIGHT_REGISTRIES`). Two other download paths live in``kornia/`` and are invisible to the prefetch list -- ``download_file_from_url``as the vision-language builders (``kornia/models/{kimi_vl,siglip2}/builder.py``)-call it, to fetch a ``model.safetensors``, and ``CachedDownloader`` into+call it, to fetch a ``model.safetensors``, and as ``kornia/feature/lightglue_onnx/utils/download.py``+calls it, to fetch the LightGlue ONNX models -- and ``CachedDownloader`` into``.kornia_hub/`` (``kornia/models/small_sr.py``, ``kornia/contrib/super_resolution.py``,-``kornia/onnx/utils.py``, ``kornia/models/_hf_models/hf_onnx_community.py``,-``kornia/feature/lightglue_onnx/utils/download.py``). Nothing in the PR matrix+``kornia/onnx/utils.py``, ``kornia/models/_hf_models/hf_onnx_community.py``). Nothing in the PR matrixdownloads through either today; a test that did would fetch live from everymatrix cell with this file still green.@@ -195,6 +195,7 @@ _DOWNLOAD_CALL_ALLOWLIST = {# entry for it would be exactly the dead exemption# ``test_no_allowlisted_module_has_stopped_downloading`` exists to catch."kornia/core/download.py": "defines the functions",+ "kornia/feature/lightglue_onnx/utils/download.py": "fetches the URL it is handed; OnnxLightGlue's tests refuse it","kornia/feature/lightglue.py": "builds its URLs in __init__; captured by _lightglue_sources","kornia/models/base.py": "loads whatever checkpoint the config it is handed carries","kornia/models/kimi_vl/builder.py": "one safetensors checkpoint, hundreds of MB, integration tests only",diff --git a/tests/feature/test_lightglue_download.py b/tests/feature/test_lightglue_download.pynew file mode 100644index 000000000..2a2a8008f--- /dev/null+++ b/tests/feature/test_lightglue_download.py@@ -0,0 +1,73 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import hashlib++import pytest++import kornia.feature.lightglue_onnx.utils.download as download_utils+++def test_download_routes_through_core_helper(monkeypatch, tmp_path):+ call = {}++ def fake_download(url, **kwargs):+ call["url"] = url+ call.update(kwargs)+ return str(tmp_path / kwargs["file_name"])++ monkeypatch.setattr(download_utils.core_download, "download_file_from_url", fake_download)++ path = download_utils.download_onnx_from_url(+ "https://example.org/model.onnx", model_dir=str(tmp_path), progress=False, timeout=2.5+ )++ assert path == str(tmp_path / "model.onnx")+ assert call == {+ "url": "https://example.org/model.onnx",+ "file_name": "model.onnx",+ "model_dir": str(tmp_path),+ "progress": False,+ "validate": None,+ "timeout": 2.5,+ }++[email protected]("valid", [True, False])+def test_check_hash_is_preserved_as_core_validator(monkeypatch, tmp_path, valid):+ expected = b"model bytes"+ payload = expected if valid else b"wrong bytes"+ prefix = hashlib.sha256(expected).hexdigest()[:8]+ file_name = f"model-{prefix}.onnx"++ def fake_download(_url, **kwargs):+ path = tmp_path / kwargs["file_name"]+ path.write_bytes(payload)+ kwargs["validate"](str(path))+ return str(path)++ monkeypatch.setattr(download_utils.core_download, "download_file_from_url", fake_download)++ if valid:+ assert download_utils.download_onnx_from_url(+ f"https://example.org/{file_name}", model_dir=str(tmp_path), check_hash=True+ ) == str(tmp_path / file_name)+ else:+ with pytest.raises(RuntimeError, match="invalid hash value"):+ download_utils.download_onnx_from_url(+ f"https://example.org/{file_name}", model_dir=str(tmp_path), check_hash=True+ )diff --git a/tests/test_doctest_downloads.py b/tests/test_doctest_downloads.pyindex 4b3a2947c..0fed8b317 100644--- a/tests/test_doctest_downloads.py+++ b/tests/test_doctest_downloads.py@@ -115,17 +115,18 @@ class TestPrimitivesStillExist:assert callable(getattr(module, attribute))def test_guard_covers_lightglue_downloader(self, monkeypatch, tmp_path) -> None:- # lightglue_onnx binds download_url_to_file at import time, so patching- # torch.hub alone would leave this path downloading.+ # LightGlue calls the shared Kornia downloader, whose low-level transfer+ # primitive is covered by the same guard as other pretrained weights.from kornia.feature.lightglue_onnx.utils.download import download_onnx_from_urlseen: list[str] = []with monkeypatch.context() as m:install_download_guard(m.setattr, _record_and_raise(seen))- with pytest.raises(_Blocked):+ with pytest.raises(RuntimeError) as exc_info:download_onnx_from_url("http://example.com/model.onnx", model_dir=str(tmp_path))assert seen == ["http://example.com/model.onnx"]+ assert isinstance(exc_info.value.__cause__, _Blocked)def test_guard_covers_kornia_core_downloader(self, monkeypatch, tmp_path) -> None:# kornia.core.download runs its own transfer rather than torch.hub's, so