Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(onnx): add force_download to refresh cached models (#6139)

Muhammad Talhae057dd4594f4
diff --git a/changelog.d/6139.added.md b/changelog.d/6139.added.md
new file mode 100644
index 000000000..38eff96e5
--- /dev/null
+++ b/changelog.d/6139.added.md
@@ -0,0 +1 @@
+Added `force_download=True` to `CachedDownloader` and the ONNX loaders, including the Hugging Face community loader and `DepthAnythingONNXBuilder`, to refresh cached models, external weights, and preprocessing configs. Failed downloads preserve the previous cached file. Errors when loading cached models or parsing configs now suggest the option.
diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.py
index 758635d4f..a5abcf9fa 100644
--- a/kornia/core/mixin/onnx.py
+++ b/kornia/core/mixin/onnx.py
@@ -584,6 +584,7 @@ class ONNXMixin:
self,
arg: Union[onnx.ModelProto, str, os.PathLike],
cache_dir: Optional[str] = None,
+ force_download: bool = False,
) -> onnx.ModelProto:
"""Load an ONNX model, either from a file path or use the provided ONNX ModelProto.
@@ -591,6 +592,8 @@ class ONNXMixin:
arg: An ONNX ModelProto object; a ``str`` file path, ``hf://`` name or URL of an ONNX model; or an
:class:`os.PathLike` file path, which always names a local file. A local path may start with ``~``.
cache_dir: Where to read onnx objects from if stored on disk.
+ force_download: If True, download an ``hf://`` name or a URL again, replacing the cached file, even when
+ it is cached. It has no effect on a ``ModelProto`` or a path to a local file.
Returns:
onnx.ModelProto: The loaded ONNX model.
@@ -603,7 +606,7 @@ class ONNXMixin:
if isinstance(arg, onnx.ModelProto):
return arg
if isinstance(arg, (str, os.PathLike)):
- return kornia.onnx.utils.ONNXLoader.load_model(arg, cache_dir=cache_dir)
+ return kornia.onnx.utils.ONNXLoader.load_model(arg, cache_dir=cache_dir, force_download=force_download)
hint = " For a serialized model, pass onnx.load_model_from_string(data)." if isinstance(arg, bytes) else ""
raise TypeError(
"Expected an onnx.ModelProto, a str (a file path, an 'hf://' name or a URL), or an os.PathLike file path, "
@@ -614,6 +617,7 @@ class ONNXMixin:
self,
*args: Union[onnx.ModelProto, str, os.PathLike],
cache_dir: Optional[str] = None,
+ force_download: bool = False,
) -> list[onnx.ModelProto]:
"""Load multiple ONNX models or operators and returns them as a list.
@@ -623,6 +627,8 @@ class ONNXMixin:
'hf://model_name' (a ``str``). Valid `model_name` can be found on
https://huggingface.co/kornia/ONNX_models. Or a URL to the ONNX model.
cache_dir: Where to read operations from if stored on disk.
+ force_download: If True, download every ``hf://`` name and URL again, replacing the cached files, even when
+ they are cached.
Returns:
list[onnx.ModelProto]: The loaded ONNX models as a list of ONNX graphs.
@@ -630,7 +636,7 @@ class ONNXMixin:
"""
op_list = []
for arg in args:
- op_list.append(self._load_op(arg, cache_dir=cache_dir))
+ op_list.append(self._load_op(arg, cache_dir=cache_dir, force_download=force_download))
return op_list
def _combine(
diff --git a/kornia/models/_hf_models/hf_onnx_community.py b/kornia/models/_hf_models/hf_onnx_community.py
index 35d479767..6904300ac 100644
--- a/kornia/models/_hf_models/hf_onnx_community.py
+++ b/kornia/models/_hf_models/hf_onnx_community.py
@@ -17,7 +17,6 @@
from __future__ import annotations
-import json
import os
from typing import Any, Optional
@@ -31,7 +30,7 @@ from kornia.geometry.transform import resize
from kornia.models.base import ModelBaseMixin
from kornia.onnx import ONNXSequential
from kornia.onnx.download import _relative_path_components
-from kornia.onnx.utils import ONNXLoader, io_name_conversion
+from kornia.onnx.utils import ONNXLoader, _cached_file_hint, _load_cached_json, _load_cached_onnx, io_name_conversion
from .preprocessor import PreprocessingLoader
@@ -74,10 +73,17 @@ class HFONNXComunnityModelLoader:
)
def load_model(
- self, download: bool = True, io_name_mapping: Optional[dict[str, str]] = None, **kwargs: Any
+ self,
+ download: bool = True,
+ io_name_mapping: Optional[dict[str, str]] = None,
+ *,
+ force_download: bool = False,
+ **kwargs: Any,
) -> onnx.ModelProto:
"""Load the ONNX model file from the configured onnx-community repository.
+ A model that is in the cache is used as it is, however old: pass ``force_download=True`` to fetch it again.
+
Args:
download: Whether to download the remote ONNX file when it is not already
available in the local cache directory.
@@ -85,6 +91,10 @@ class HFONNXComunnityModelLoader:
output names after loading. This is useful when composing the model
with Kornia pre-processing or post-processing graphs that expect
specific tensor names.
+ force_download: Whether to download the model, and its weights when ``with_data`` is set, again and replace
+ the cached files, even when they are cached. The model is replaced before the weights are fetched: if
+ the weights then fail to download, the cache holds the new model with the old weights, so call again
+ with ``force_download=True`` before loading it. Needs ``download=True``.
kwargs: Not used; any keyword raises ``TypeError``. Kept for compatibility.
Returns:
@@ -94,7 +104,13 @@ class HFONNXComunnityModelLoader:
# <cache_dir>/<model_name>/<model_type>.onnx: the repository's own directory, where earlier releases cached
# these models too, so they are not downloaded again
file_path = ONNXLoader.download_to_cache(
- self.model_url, self.model_type, download, cache_dir=self.cache_dir, suffix=".onnx", **kwargs
+ self.model_url,
+ self.model_type,
+ download,
+ cache_dir=self.cache_dir,
+ suffix=".onnx",
+ force_download=force_download,
+ **kwargs,
)
if self.with_data: # beside the model, under the name the model refers to
ONNXLoader.download_to_cache(
@@ -103,18 +119,17 @@ class HFONNXComunnityModelLoader:
download,
cache_dir=self.cache_dir,
suffix=".onnx_data",
+ force_download=force_download,
**kwargs,
)
- onnx_model = onnx.load(file_path)
+ onnx_model = _load_cached_onnx(file_path)
if io_name_mapping is not None:
onnx_model = io_name_conversion(onnx_model, io_name_mapping)
return onnx_model
- def load_preprocessing(
- self,
- ) -> ImageSequential:
+ def load_preprocessing(self, *, force_download: bool = False) -> ImageSequential:
"""Load the preprocessing pipeline described by the remote processor config.
The Hugging Face onnx-community repositories store image preprocessing
@@ -122,14 +137,24 @@ class HFONNXComunnityModelLoader:
converts the supported operations, such as resize, rescale, and normalize, into
a Kornia :class:`~kornia.core.ImageSequential` module.
+ Args:
+ force_download: Whether to download ``preprocessor_config.json`` again and replace the cached file, even
+ when it is cached.
+
Returns:
Sequential Kornia image preprocessing module built from the repository
configuration.
"""
# <cache_dir>/<model_name>/preprocessor_config.json, beside the repository's model
- file_path = ONNXLoader.download_to_cache(self.config_url, "preprocessor_config.json", cache_dir=self.cache_dir)
- with open(file_path) as f:
- return PreprocessingLoader.from_json(json.load(f))
+ file_path = ONNXLoader.download_to_cache(
+ self.config_url, "preprocessor_config.json", cache_dir=self.cache_dir, force_download=force_download
+ )
+ config = _load_cached_json(file_path)
+ try:
+ return PreprocessingLoader.from_json(config)
+ except KeyError as exc: # valid JSON that lacks what a processor config has: a file that is not the hub's
+ exc.add_note(_cached_file_hint(file_path))
+ raise
class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):
diff --git a/kornia/models/depth_estimation/depth_anything.py b/kornia/models/depth_estimation/depth_anything.py
index d73a4d881..517dc609c 100644
--- a/kornia/models/depth_estimation/depth_anything.py
+++ b/kornia/models/depth_estimation/depth_anything.py
@@ -31,7 +31,11 @@ class DepthAnythingONNXBuilder:
@staticmethod
def build(
- model_name: str = "depth-anything-v2-small", model_type: str = "model", cache_dir: Optional[str] = None
+ model_name: str = "depth-anything-v2-small",
+ model_type: str = "model",
+ cache_dir: Optional[str] = None,
+ *,
+ force_download: bool = False,
) -> DepthEstimation:
"""Build a ``DepthEstimation`` around the onnx-community graph (downloaded on first use).
@@ -59,6 +63,10 @@ class DepthAnythingONNXBuilder:
- `model_uint8`
cache_dir:
The directory where the model should be cached.
+ force_download:
+ Whether to download the model and its ``preprocessor_config.json`` again and replace the cached
+ files, even when they are cached. By default a cached file is used as it is, however old, and one
+ that does not load fails every time until it is deleted.
Returns:
DepthEstimation: The depth estimation model.
@@ -77,8 +85,9 @@ class DepthAnythingONNXBuilder:
onnx_model = loader.load_model(
download=True,
io_name_mapping={"pixel_values": "input", "predicted_depth": "output"},
+ force_download=force_download,
)
- preprocessing = loader.load_preprocessing()
+ preprocessing = loader.load_preprocessing(force_download=force_download)
resize = next((m for m in preprocessing if isinstance(m, _DPTResize)), None)
others = [m for m in preprocessing if not isinstance(m, _DPTResize)]
preproc = ImageSequential(*others).to_onnx(save=False) if others else None
diff --git a/kornia/onnx/download.py b/kornia/onnx/download.py
index 20828e20a..9cbe6299e 100644
--- a/kornia/onnx/download.py
+++ b/kornia/onnx/download.py
@@ -101,9 +101,14 @@ class CachedDownloader:
*,
cache_dir: Optional[str] = None,
suffix: Optional[str] = None,
+ force_download: bool = False,
) -> str:
"""Resolve a remote file into Kornia's local cache and download it when needed.
+ A file that is in the cache is used as it is, for as long as it exists: a model updated on the server is not
+ fetched again, and a cached file that is damaged, or was replaced by hand, stays so. Pass
+ ``force_download=True`` to fetch the file again, or delete the cached file.
+
Args:
url: HTTP or HTTPS URL of the file to cache.
name: Logical model or operator name used to construct the cache
@@ -116,6 +121,9 @@ class CachedDownloader:
``kornia.config.kornia_config.hub_cache_dir``; ``""`` is the
current working directory.
suffix: Appended to the file name unless it already ends with it.
+ force_download: If ``True``, fetch the file from ``url`` even when it is already cached, and replace the
+ cached file with it. The old file is replaced only once the new one is complete, so a fetch that
+ fails leaves it as it was. Needs ``download=True``. Defaults to ``False``.
Returns:
Local filesystem path to the cached file.
@@ -123,8 +131,9 @@ class CachedDownloader:
Raises:
ValueError: If ``url`` is not an HTTP or HTTPS URL, if ``name`` is absolute or has a drive or an empty,
``.`` or ``..`` component, if ``suffix`` adds a directory to the file name, if download is disabled
- and the file is missing, if the server answers with an HTTP error, or if ``KORNIA_DOWNLOAD_TIMEOUT``
- is set to anything but a positive number of seconds.
+ and the file is missing, if ``force_download`` is ``True`` while ``download`` is ``False``, if the
+ server answers with an HTTP error, or if ``KORNIA_DOWNLOAD_TIMEOUT`` is set to anything but a
+ positive number of seconds.
TimeoutError: If the server goes ``KORNIA_DOWNLOAD_TIMEOUT`` seconds without answering (see ``download``).
urllib.error.URLError: If the server cannot be reached, or ``urllib.error.ContentTooShortError``
if the body is shorter than its ``Content-Length`` (see ``download``).
@@ -132,7 +141,9 @@ class CachedDownloader:
"""
if url.startswith(("http:", "https:")):
file_path = cls._get_file_path(name, cache_dir, suffix=suffix)
- cls.download(url, file_path, download_if_not_exists=download)
+ # passed only when set, so that a subclass whose ``download`` predates the keyword keeps working
+ extra = {"force_download": True} if force_download else {}
+ cls.download(url, file_path, download_if_not_exists=download, **extra)
return file_path
raise ValueError(f"URL must start with 'http:' or 'https:'. Got {url}")
@@ -142,6 +153,8 @@ class CachedDownloader:
url: str,
file_path: str,
download_if_not_exists: bool = True,
+ *,
+ force_download: bool = False,
) -> None:
"""Download an ONNX model from the specified URL and save it to the specified file path.
@@ -149,21 +162,30 @@ class CachedDownloader:
url: The URL of the ONNX model to download.
file_path: The local path where the downloaded model should be saved.
download_if_not_exists: If True, the file will be downloaded if it's not already downloaded.
+ force_download: If True, download the file even when ``file_path`` exists, and replace it. The old file
+ is replaced only once the new one is complete, so a download that fails leaves it as it was. Needs
+ ``download_if_not_exists=True``.
Raises:
- ValueError: If the file is missing and ``download_if_not_exists`` is ``False``, if ``url`` is not an
- HTTP or HTTPS URL, if the server answers with an HTTP error, or if ``KORNIA_DOWNLOAD_TIMEOUT`` is
- set to anything but a positive number of seconds.
+ ValueError: If the file is missing and ``download_if_not_exists`` is ``False``, if ``force_download`` is
+ ``True`` while ``download_if_not_exists`` is ``False``, if ``url`` is not an HTTP or HTTPS URL, if
+ the server answers with an HTTP error, or if ``KORNIA_DOWNLOAD_TIMEOUT`` is set to anything but a
+ positive number of seconds.
TimeoutError: If the server goes ``KORNIA_DOWNLOAD_TIMEOUT`` seconds (30 s when it is unset) without
- answering. Nothing is left at ``file_path``.
- urllib.error.ContentTooShortError: If the body is shorter than its ``Content-Length``. Nothing is
- left at ``file_path``, so the next call downloads again.
- http.client.IncompleteRead: If a chunked body is cut mid-chunk. Nothing is left at ``file_path``.
+ answering. An existing cached file is left unchanged.
+ urllib.error.ContentTooShortError: If the body is shorter than its ``Content-Length``. An existing cached
+ file is left unchanged.
+ http.client.IncompleteRead: If a chunked body is cut mid-chunk. An existing cached file is left unchanged.
urllib.error.URLError: If the server cannot be reached.
"""
file_path = os.path.expanduser(file_path)
- if os.path.exists(file_path):
+ if force_download and not download_if_not_exists:
+ # the two flags ask for opposite things, and ignoring either would hide a mistake in the call
+ raise ValueError(
+ "`force_download=True` needs `download=True`: it cannot fetch a file that may not be downloaded."
+ )
+ if os.path.exists(file_path) and not force_download:
_logger.info(f"Loading `{url}` from `{file_path}`.")
return
diff --git a/kornia/onnx/module.py b/kornia/onnx/module.py
index 55d58265a..729c30d30 100644
--- a/kornia/onnx/module.py
+++ b/kornia/onnx/module.py
@@ -45,6 +45,9 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):
Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.
target_ir_version: The IR version to convert the model to. If None, the model keeps its IR version.
target_opset_version: The OPSET version to convert the model to. If None, the model keeps its OPSET version.
+ force_download: If True, an ``hf://`` name or a URL is downloaded again, and replaces the cached file, even
+ when it is cached. By default a cached file is used as it is, however old, and one that does not load
+ fails every time until it is deleted. It has no effect on a model object or a path to a local file.
"""
@@ -56,8 +59,10 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):
cache_dir: Optional[str] = None,
target_ir_version: Optional[int] = None,
target_opset_version: Optional[int] = None,
+ *,
+ force_download: bool = False,
) -> None:
- self.op = self._load_op(op, cache_dir)
+ self.op = self._load_op(op, cache_dir, force_download=force_download)
if target_ir_version is not None or target_opset_version is not None:
self.op = self._onnx_version_conversion(
self.op, target_ir_version=target_ir_version, target_opset_version=target_opset_version
@@ -108,7 +113,7 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):
return super()._add_metadata(self.op, additional_metadata)
-def load(model_name: Union[onnx.ModelProto, str, os.PathLike]) -> ONNXModule:
+def load(model_name: Union[onnx.ModelProto, str, os.PathLike], *, force_download: bool = False) -> ONNXModule:
"""Load an ONNX model from either a file path or HuggingFace.
The loaded model is an ONNXModule object, of which you may run the model with
@@ -119,6 +124,7 @@ def load(model_name: Union[onnx.ModelProto, str, os.PathLike]) -> ONNXModule:
always names a local file), or an ONNX ModelProto object. For Hugging Face-hosted models,
use the format 'hf://model_name'. Valid `model_name` can be found on
https://huggingface.co/kornia/ONNX_models. Or a URL to the ONNX model.
+ force_download: If True, download the model again and replace the cached file, even when it is cached.
"""
- return ONNXModule(model_name)
+ return ONNXModule(model_name, force_download=force_download)
diff --git a/kornia/onnx/sequential.py b/kornia/onnx/sequential.py
index 420215edb..1101531d3 100644
--- a/kornia/onnx/sequential.py
+++ b/kornia/onnx/sequential.py
@@ -66,6 +66,9 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):
error: the ONNX version converter's where it has no adapter for an operator (for example ``Resize`` or
``Pad`` from opset 18 to 17), ``onnx.checker``'s where the converted graph is invalid (for example a
``ReduceMean`` from opset 18 to 17), or ONNX Runtime's where it does not support the target IR version.
+ force_download: If True, every ``hf://`` name and URL is downloaded again, and replaces the cached file, even
+ when it is cached. By default a cached file is used as it is, however old, and one that does not load
+ fails every time until it is deleted. It has no effect on a model object or a path to a local file.
"""
@@ -79,8 +82,9 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):
auto_ir_version_conversion: bool = False,
target_ir_version: Optional[int] = None,
target_opset_version: Optional[int] = None,
+ force_download: bool = False,
) -> None:
- self.operators = self._load_ops(*args, cache_dir=cache_dir)
+ self.operators = self._load_ops(*args, cache_dir=cache_dir, force_download=force_download)
if auto_ir_version_conversion:
self.operators = self._auto_version_conversion(
*self.operators, target_ir_version=target_ir_version, target_opset_version=target_opset_version
diff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.py
index 2eccf6c2d..23bce6181 100644
--- a/kornia/onnx/utils.py
+++ b/kornia/onnx/utils.py
@@ -111,19 +111,62 @@ def _onnx_data_name(name: str) -> str:
return (name[: -len(".onnx")] if name.endswith(".onnx") else name) + ".onnx_data"
+def _cached_file_hint(file_path: str) -> str:
+ """Return what to do when the cached file ``file_path`` does not load."""
+ return (
+ f"If the cached file `{file_path}` is damaged, or was replaced by hand, pass force_download=True to download "
+ "it again, or delete the file."
+ )
+
+
+def _load_cached_onnx(file_path: str) -> onnx.ModelProto:
+ """Load the ONNX model cached at ``file_path``; the error for a file that does not load names the way out.
+
+ The error is raised as it is, so a caller that catches ``google.protobuf.message.DecodeError`` still does; the
+ hint is a note on it (:meth:`BaseException.add_note`), which a traceback prints.
+ """
+ try:
+ return onnx.load(file_path)
+ except MemoryError: # a file too large to load is not a damaged one
+ raise
+ except Exception as exc:
+ exc.add_note(_cached_file_hint(file_path))
+ raise
+
+
+def _load_cached_json(file_path: str) -> Any:
+ """Load the JSON cached at ``file_path``; the error for a file that does not parse names the way out.
+
+ The error is raised as it is, so a caller that catches ``json.JSONDecodeError`` still does; the hint is a note on
+ it (:meth:`BaseException.add_note`), which a traceback prints.
+ """
+ try:
+ with open(file_path, "rb") as f: # json.load detects UTF-8, -16 or -32 in bytes, whatever the locale
+ return json.load(f)
+ except (json.JSONDecodeError, UnicodeDecodeError) as exc: # both are ValueErrors
+ exc.add_note(_cached_file_hint(file_path))
+ raise
+
+
class ONNXLoader(CachedDownloader):
"""Manages ONNX models, handling local caching, downloading from Hugging Face, and loading models."""
@classmethod
- def load_config(cls, url: Union[str, os.PathLike], download: bool = True, **kwargs: Any) -> dict[str, Any]:
+ def load_config(
+ cls, url: Union[str, os.PathLike], download: bool = True, *, force_download: bool = False, **kwargs: Any
+ ) -> dict[str, Any]:
"""Load JSON config from the specified URL or local file.
+ A config that is in the cache is used as it is, however old: pass ``force_download=True`` to fetch it again.
+
Args:
url: The HTTP(S) URL of the preprocessor config to load, or the path of a local JSON file, which is read
as it is: a ``str``, or an :class:`os.PathLike`, which always names a local file. A local path may
start with ``~``.
download: If True, the config will be downloaded if it's not already in the local cache. A local file
is read either way.
+ force_download: If True, fetch an HTTP(S) config again and replace the cached file, even when it is
+ cached. Needs ``download=True``. It has no effect on a local file. Defaults to False.
kwargs: Keyword arguments of ``CachedDownloader.download_to_cache``. Only ``cache_dir`` applies: the root
the config is stored under, at ``<scheme>/<host>/<directories of the URL's path>/<file name>``, with a
``%3F<hash>`` directory before the file name when the URL has a query, as for ``load_model``. ``None``
@@ -143,9 +186,10 @@ class ONNXLoader(CachedDownloader):
url = _path_text("ONNXLoader.load_config", url)
if not local and url.startswith(("http:", "https:")):
kwargs["cache_dir"] = kwargs.get("cache_dir") or None # "" is the default directory, as for load_model
- file_path = cls.download_to_cache(url, _url_cache_name(url), download=download, suffix=".json", **kwargs)
- with open(file_path) as f:
- return json.load(f)
+ file_path = cls.download_to_cache(
+ url, _url_cache_name(url), download=download, suffix=".json", force_download=force_download, **kwargs
+ )
+ return _load_cached_json(file_path)
path = os.path.expanduser(url)
if os.path.isfile(path):
@@ -158,10 +202,19 @@ class ONNXLoader(CachedDownloader):
@classmethod
def load_model(
- cls, model_name: Union[str, os.PathLike], download: bool = True, with_data: bool = False, **kwargs
+ cls,
+ model_name: Union[str, os.PathLike],
+ download: bool = True,
+ with_data: bool = False,
+ *,
+ force_download: bool = False,
+ **kwargs,
) -> onnx.ModelProto:
"""Load an ONNX model from the local cache or downloads it from Hugging Face if necessary.
+ A model that is in the cache is used as it is, however old, and a cached file that does not load fails every
+ time: pass ``force_download=True`` to fetch it again, or delete the file.
+
Args:
model_name: The name of the ONNX model or operator. For Hugging Face-hosted models,
use the format 'hf://model_name'. Valid `model_name` can be found on
@@ -182,6 +235,12 @@ class ONNXLoader(CachedDownloader):
neither can a directory with a reserved name (``con``); on a case-insensitive file system, URLs that
differ only in letter case share a file.
with_data: If True, the model will be loaded with its `.onnx_data` weights, stored beside the model.
+ force_download: If True, fetch the model, and its `.onnx_data` weights with ``with_data``, again and
+ replace the cached files, even when they are cached. A file is replaced only once its download is
+ complete, so a download that fails leaves the cached one as it was. The model is replaced before the
+ weights are fetched: if the weights then fail to download, the cache holds the new model with the old
+ weights, so call again with ``force_download=True`` before loading it. Needs ``download=True``. It has
+ no effect on a model given as a path to a local file, which is never downloaded. Defaults to False.
**kwargs: Only ``cache_dir``; any other keyword raises ``TypeError``, whatever ``model_name`` is.
Returns:
@@ -202,21 +261,34 @@ class ONNXLoader(CachedDownloader):
else:
kwargs["cache_dir"] = kornia_config.hub_onnx_dir
name = model_name # "<folder>/<a>/<b>": the folder is checked as the other components are
- file_path = cls.download_to_cache(url, name, download=download, suffix=".onnx", **kwargs)
+ file_path = cls.download_to_cache(
+ url, name, download=download, suffix=".onnx", force_download=force_download, **kwargs
+ )
if with_data:
url_data = f"https://huggingface.co/kornia/ONNX_models/resolve/main/{model_name}.onnx_data"
- cls.download_to_cache(url_data, name, download=download, suffix=".onnx_data", **kwargs)
- return onnx.load(file_path)
+ cls.download_to_cache(
+ url_data, name, download=download, suffix=".onnx_data", force_download=force_download, **kwargs
+ )
+ return _load_cached_onnx(file_path)
if not local and model_name.startswith(("http://", "https://")):
name = _url_cache_name(model_name)
kwargs["cache_dir"] = kwargs.get("cache_dir") or kornia_config.hub_onnx_dir # "" is the default too
- file_path = cls.download_to_cache(model_name, name, download=download, suffix=".onnx", **kwargs)
+ file_path = cls.download_to_cache(
+ model_name, name, download=download, suffix=".onnx", force_download=force_download, **kwargs
+ )
if with_data:
parts = urlsplit(model_name)
url_data = urlunsplit(parts._replace(path=_onnx_data_name(parts.path)))
- cls.download_to_cache(url_data, _onnx_data_name(name), download=download, suffix=".onnx_data", **kwargs)
- return onnx.load(file_path)
+ cls.download_to_cache(
+ url_data,
+ _onnx_data_name(name),
+ download=download,
+ suffix=".onnx_data",
+ force_download=force_download,
+ **kwargs,
+ )
+ return _load_cached_onnx(file_path)
path = os.path.expanduser(model_name)
if os.path.exists(path):
diff --git a/tests/models/test_depth_estimation.py b/tests/models/test_depth_estimation.py
index ab98971f1..a5eb6bc9b 100644
--- a/tests/models/test_depth_estimation.py
+++ b/tests/models/test_depth_estimation.py
@@ -444,7 +444,7 @@ def test_builder_resizes_in_torch_before_the_graph(monkeypatch):
monkeypatch.setattr(
HFONNXComunnityModelLoader,
"load_preprocessing",
- lambda self: PreprocessingLoader.from_json(dict(_DEPTH_ANYTHING_V2_SMALL_CONFIG)),
+ lambda self, **kwargs: PreprocessingLoader.from_json(dict(_DEPTH_ANYTHING_V2_SMALL_CONFIG)),
)
model = DepthAnythingONNXBuilder.build()
@@ -455,3 +455,30 @@ def test_builder_resizes_in_torch_before_the_graph(monkeypatch):
depth = model(torch.rand(1, 3, 300, 400))
assert [tuple(x.shape) for x in spy.inputs] == [(1, 3, 392, 518)]
assert depth.shape == (1, 1, 300, 400)
+
+
+ ("kwargs", "expected"), [({}, False), ({"force_download": False}, False), ({"force_download": True}, True)]
+)
+def test_builder_passes_force_download_to_the_model_and_the_preprocessing_config(monkeypatch, kwargs, expected):
+ from kornia.models._hf_models import HFONNXComunnityModelLoader
+ from kornia.models._hf_models.preprocessor import PreprocessingLoader
+ from kornia.models.depth_estimation import DepthAnythingONNXBuilder
+
+ seen = []
+
+ def load_model(self, **kwargs):
+ seen.append(("model", kwargs["force_download"]))
+ return _stand_in_graph()
+
+ def load_preprocessing(self, **kwargs):
+ seen.append(("preprocessing", kwargs["force_download"]))
+ return PreprocessingLoader.from_json(dict(_DEPTH_ANYTHING_V2_SMALL_CONFIG))
+
+ monkeypatch.setattr(HFONNXComunnityModelLoader, "load_model", load_model)
+ monkeypatch.setattr(HFONNXComunnityModelLoader, "load_preprocessing", load_preprocessing)
+
+ DepthAnythingONNXBuilder.build(**kwargs)
+
+ assert seen == [("model", expected), ("preprocessing", expected)]
diff --git a/tests/models/test_hf_onnx_community.py b/tests/models/test_hf_onnx_community.py
index 9bd8b807a..09c6cd87a 100644
--- a/tests/models/test_hf_onnx_community.py
+++ b/tests/models/test_hf_onnx_community.py
@@ -197,3 +197,152 @@ def test_loader_refuses_a_model_name_outside_the_cache_directory(model_name, tmp
with mock.patch.object(ONNXLoader, "download") as mock_download, pytest.raises(ValueError, match="model_name"):
HFONNXComunnityModelLoader(model_name, cache_dir=str(root)).load_preprocessing()
mock_download.assert_not_called()
+
+
+_DPT_CONFIG = {
+ "image_processor_type": "DPTImageProcessor",
+ "do_pad": False,
+ "do_resize": True,
+ "size": {"height": 14, "width": 14},
+ "do_rescale": False,
+ "do_normalize": False,
+}
+
+
+def fake_repository():
+ """Serve a repository's model, weights and preprocessing config, and record the file name of every fetch."""
+ import json
+ from pathlib import Path
+ from unittest import mock
+
+ versions = {"model": "1", "config": 1}
+ fetched: list[str] = []
+
+ def serve(url, dst, **kwargs):
+ name = url.rsplit("/", 1)[-1]
+ fetched.append(name)
+ if name == "preprocessor_config.json":
+ content = json.dumps({**_DPT_CONFIG, "size": {"height": 14 * versions["config"], "width": 14}}).encode()
+ elif name.endswith(".onnx_data"):
+ content = b"weights"
+ else:
+ content = _identity_model(("version", versions["model"])).SerializeToString()
+ Path(dst).write_bytes(content)
+
+ with mock.patch("kornia.core.download._download_url_to_file", side_effect=serve):
+ yield versions, fetched
+
+
+def test_loader_force_download_fetches_the_model_weights_and_config_again(fake_repository, tmp_path):
+ # a cached file of an onnx-community repository was used for as long as it existed: an updated model was never
+ # fetched again
+ import torch
+
+ from kornia.models._hf_models import HFONNXComunnityModelLoader
+
+ versions, fetched = fake_repository
+ loader = HFONNXComunnityModelLoader("depth-anything-v2-small", cache_dir=str(tmp_path), with_data=True)
+
+ def version(model):
+ return {p.key: p.value for p in model.metadata_props}["version"]
+
+ def height(preprocessing):
+ return preprocessing(torch.rand(1, 3, 7, 9)).shape[-2]
+
+ assert version(loader.load_model()) == "1"
+ assert height(loader.load_preprocessing()) == 14
+ assert fetched == ["model.onnx", "model.onnx_data", "preprocessor_config.json"]
+
+ versions["model"], versions["config"] = "2", 2 # the repository changed
+ assert version(loader.load_model()) == "1"
+ assert height(loader.load_preprocessing()) == 14
+ assert len(fetched) == 3 # the cached files are used as they are
+
+ assert version(loader.load_model(force_download=True)) == "2"
+ assert fetched[3:] == ["model.onnx", "model.onnx_data"] # the weights beside the model, as they go together
+ assert height(loader.load_preprocessing(force_download=True)) == 28
+ assert fetched[5:] == ["preprocessor_config.json"]
+
+ assert version(loader.load_model()) == "2" # the new files are the cached ones
+ assert height(loader.load_preprocessing()) == 28
+ assert len(fetched) == 6
+
+
+def test_loader_damaged_cached_files_name_force_download(fake_repository, tmp_path):
+ import json
+
+ from google.protobuf.message import DecodeError
+
+ from kornia.models._hf_models import HFONNXComunnityModelLoader
+
+ _, fetched = fake_repository
+ loader = HFONNXComunnityModelLoader("depth-anything-v2-small", cache_dir=str(tmp_path))
+ loader.load_model()
+ loader.load_preprocessing()
+ model, config = (
+ tmp_path / "depth-anything-v2-small" / "model.onnx",
+ tmp_path / "depth-anything-v2-small" / "preprocessor_config.json",
+ )
+ model.write_bytes(b"<html>Bad gateway</html>")
+ config.write_text("<html>Bad gateway</html>")
+
+ with pytest.raises(DecodeError) as model_error:
+ loader.load_model()
+ with pytest.raises(json.JSONDecodeError) as config_error:
+ loader.load_preprocessing()
+ assert "force_download=True" in model_error.value.__notes__[0]
+ assert "force_download=True" in config_error.value.__notes__[0]
+ assert len(fetched) == 2
+
+ loader.load_model(force_download=True)
+ loader.load_preprocessing(force_download=True)
+ assert len(fetched) == 4
+ loader.load_model()
+ loader.load_preprocessing()
+
+
+def test_loader_force_download_without_download_raises(fake_repository, tmp_path):
+ from kornia.models._hf_models import HFONNXComunnityModelLoader
+
+ _, fetched = fake_repository
+ loader = HFONNXComunnityModelLoader("depth-anything-v2-small", cache_dir=str(tmp_path))
+ loader.load_model()
+
+ with pytest.raises(ValueError, match=r"force_download=True.*download=True"):
+ loader.load_model(download=False, force_download=True)
+ assert fetched == ["model.onnx"]
+
+
+def test_loader_config_that_is_json_but_not_a_processor_config_names_force_download(fake_repository, tmp_path):
+ from kornia.models._hf_models import HFONNXComunnityModelLoader
+
+ _, fetched = fake_repository
+ loader = HFONNXComunnityModelLoader("depth-anything-v2-small", cache_dir=str(tmp_path))
+ loader.load_preprocessing()
+ config = tmp_path / "depth-anything-v2-small" / "preprocessor_config.json"
+ config.write_text("{}") # parses, but lacks what a processor config has
+
+ with pytest.raises(KeyError) as exc_info:
+ loader.load_preprocessing()
+ (note,) = exc_info.value.__notes__
+ assert "force_download=True" in note
+ assert str(config) in note
+ assert fetched == ["preprocessor_config.json"]
+
+ loader.load_preprocessing(force_download=True)
+ assert fetched == ["preprocessor_config.json"] * 2
+ loader.load_preprocessing()
+
+
+def test_loader_unsupported_processor_type_is_not_called_a_damaged_file(fake_repository, tmp_path):
+ # a config the loader does not support is not a damaged one: force_download would fetch the same config again
+ from kornia.models._hf_models import HFONNXComunnityModelLoader
+
+ loader = HFONNXComunnityModelLoader("depth-anything-v2-small", cache_dir=str(tmp_path))
+ loader.load_preprocessing()
+ (tmp_path / "depth-anything-v2-small" / "preprocessor_config.json").write_text('{"image_processor_type": "Other"}')
+
+ with pytest.raises(RuntimeError, match="Unsupported image processor type") as exc_info:
+ loader.load_preprocessing()
+ assert not hasattr(exc_info.value, "__notes__")
diff --git a/tests/onnx/test_download.py b/tests/onnx/test_download.py
index b0a3c551e..f7b4082e1 100644
--- a/tests/onnx/test_download.py
+++ b/tests/onnx/test_download.py
@@ -357,3 +357,109 @@ class TestCachedDownloader:
server.shutdown()
server.server_close()
assert path.read_bytes() == payload
+
+
+class TestForceDownload:
+ @staticmethod
+ def _cache(url: str, tmp_path: Path, **kwargs) -> str:
+ return CachedDownloader.download_to_cache(url, "model", cache_dir=str(tmp_path), suffix=".pth", **kwargs)
+
+ def test_a_cached_file_is_fetched_again_only_when_forced(self, download_server, tmp_path):
+ responses, base_url, hits = download_server
+ url = f"{base_url}/model"
+ responses["/model"] = (b"old", 3)
+ path = self._cache(url, tmp_path)
+
+ responses["/model"] = (b"new weights", 11) # the file changed on the server
+ assert self._cache(url, tmp_path) == path
+ assert self._cache(url, tmp_path, force_download=False) == path
+ assert Path(path).read_bytes() == b"old" # a cached file is used as it is
+ assert hits == ["/model"]
+
+ assert self._cache(url, tmp_path, force_download=True) == path
+ assert Path(path).read_bytes() == b"new weights"
+ assert hits == ["/model", "/model"]
+ assert [p.name for p in tmp_path.iterdir()] == ["model.pth"] # no partial file is left beside it
+
+ assert self._cache(url, tmp_path) == path # the new file is the cached one
+ assert Path(path).read_bytes() == b"new weights"
+ assert hits == ["/model", "/model"]
+
+ def test_forcing_a_file_that_is_not_cached_downloads_it_once(self, download_server, tmp_path):
+ responses, base_url, hits = download_server
+ responses["/model"] = (b"weights", 7)
+
+ path = self._cache(f"{base_url}/model", tmp_path, force_download=True)
+
+ assert Path(path).read_bytes() == b"weights"
+ assert hits == ["/model"]
+
+ def test_download_replaces_the_file_when_forced(self, download_server, tmp_path):
+ responses, base_url, hits = download_server
+ path = tmp_path / "plain.pth"
+ path.write_bytes(b"damaged")
+ responses["/model"] = (b"weights", 7)
+
+ CachedDownloader.download(f"{base_url}/model", str(path))
+ assert path.read_bytes() == b"damaged"
+ assert hits == []
+
+ CachedDownloader.download(f"{base_url}/model", str(path), force_download=True)
+ assert path.read_bytes() == b"weights"
+ assert hits == ["/model"]
+
+ @pytest.mark.parametrize("failure", ["http_error", "truncated"])
+ def test_a_failed_fetch_leaves_the_cached_file_as_it_was(self, download_server, tmp_path, failure):
+ responses, base_url, hits = download_server
+ url = f"{base_url}/model"
+ responses["/model"] = (b"old", 3)
+ path = self._cache(url, tmp_path)
+
+ if failure == "http_error":
+ del responses["/model"]
+ expected = ValueError # the server answers 404
+ else:
+ responses["/model"] = (b"new", 100) # the body ends before its Content-Length
+ expected = ContentTooShortError
+ with pytest.raises(expected):
+ self._cache(url, tmp_path, force_download=True)
+
+ assert hits == ["/model", "/model"]
+ assert Path(path).read_bytes() == b"old"
+ assert [p.name for p in tmp_path.iterdir()] == ["model.pth"]
+
+ def test_forcing_without_downloading_raises_before_any_fetch(self, download_server, tmp_path):
+ responses, base_url, hits = download_server
+ url = f"{base_url}/model"
+ responses["/model"] = (b"old", 3)
+ path = self._cache(url, tmp_path)
+
+ with pytest.raises(ValueError, match=r"force_download=True.*download=True"):
+ self._cache(url, tmp_path, download=False, force_download=True)
+ with pytest.raises(ValueError, match=r"force_download=True.*download=True"):
+ CachedDownloader.download(url, path, download_if_not_exists=False, force_download=True)
+
+ assert hits == ["/model"]
+ assert Path(path).read_bytes() == b"old"
+
+ def test_force_download_is_keyword_only(self, tmp_path):
+ with pytest.raises(TypeError):
+ CachedDownloader.download_to_cache("http://127.0.0.1:9/model", "m", True, True) # type: ignore[misc]
+ with pytest.raises(TypeError):
+ CachedDownloader.download("http://127.0.0.1:9/model", str(tmp_path / "m"), True, True) # type: ignore[misc]
+
+ def test_a_download_override_that_predates_the_keyword_keeps_working(self, tmp_path):
+ # CachedDownloader.download is a public classmethod, so a subclass may override it with the old signature:
+ # download_to_cache hands it force_download only when it is set
+ calls = []
+
+ class Legacy(CachedDownloader):
+ @classmethod
+ def download(cls, url, file_path, download_if_not_exists=True):
+ calls.append((url, file_path, download_if_not_exists))
+
+ path = Legacy.download_to_cache("http://example.com/m", "m", cache_dir=str(tmp_path), suffix=".pth")
+
+ assert calls == [("http://example.com/m", path, True)]
+ with pytest.raises(TypeError, match="force_download"):
+ Legacy.download_to_cache("http://example.com/m", "m", cache_dir=str(tmp_path), force_download=True)
diff --git a/tests/onnx/test_sequential.py b/tests/onnx/test_sequential.py
index 7b429927d..1542b894c 100644
--- a/tests/onnx/test_sequential.py
+++ b/tests/onnx/test_sequential.py
@@ -589,3 +589,98 @@ class TestONNXSequentialComposition:
assert seq(torch.tensor([1.0, 2.0]).numpy())[0].tolist() == [1.0, 2.0]
assert _props(seq._combined_op) == [("k", "2")]
+
+
+class TestForceDownloadReachesTheLoader:
+ @pytest.fixture
+ def model(self):
+ input_info = onnx.helper.make_tensor_value_info("input", onnx.TensorProto.FLOAT, [1, 2])
+ output_info = onnx.helper.make_tensor_value_info("output", onnx.TensorProto.FLOAT, [1, 2])
+ graph = onnx.helper.make_graph(
+ [onnx.helper.make_node("Identity", ["input"], ["output"])], "g", [input_info], [output_info]
+ )
+ return onnx.helper.make_model(graph, opset_imports=[onnx.helper.make_opsetid("", 17)], ir_version=9)
+
+ @pytest.mark.parametrize("force_download", [False, True])
+ def test_sequential(self, model, force_download):
+ from unittest import mock
+
+ with mock.patch("kornia.onnx.utils.ONNXLoader.load_model", return_value=model) as load_model:
+ ONNXSequential("https://example.com/a.onnx", cache_dir="cache", force_download=force_download)
+
+ load_model.assert_called_once_with(
+ "https://example.com/a.onnx", cache_dir="cache", force_download=force_download
+ )
+
+ def test_sequential_downloads_nothing_again_by_default(self, model):
+ from unittest import mock
+
+ with mock.patch("kornia.onnx.utils.ONNXLoader.load_model", return_value=model) as load_model:
+ ONNXSequential("hf://operators/a")
+
+ load_model.assert_called_once_with("hf://operators/a", cache_dir=None, force_download=False)
+
+ def test_sequential_does_not_load_a_model_object(self, model):
+ from unittest import mock
+
+ with mock.patch("kornia.onnx.utils.ONNXLoader.load_model") as load_model:
+ ONNXSequential(model, force_download=True)
+
+ load_model.assert_not_called()
+
+ @pytest.mark.parametrize("force_download", [False, True])
+ def test_module(self, model, force_download):
+ from unittest import mock
+
+ from kornia.onnx.module import ONNXModule
+
+ with mock.patch("kornia.onnx.utils.ONNXLoader.load_model", return_value=model) as load_model:
+ ONNXModule("https://example.com/a.onnx", cache_dir="cache", force_download=force_download)
+
+ load_model.assert_called_once_with(
+ "https://example.com/a.onnx", cache_dir="cache", force_download=force_download
+ )
+
+ @pytest.mark.parametrize("force_download", [False, True])
+ def test_load(self, model, force_download):
+ from unittest import mock
+
+ from kornia.onnx.module import load
+
+ with mock.patch("kornia.onnx.utils.ONNXLoader.load_model", return_value=model) as load_model:
+ load("https://example.com/a.onnx", force_download=force_download)
+
+ load_model.assert_called_once_with("https://example.com/a.onnx", cache_dir=None, force_download=force_download)
+
+ @pytest.fixture
+ def fetched(self, model):
+ """Serve ``model`` for any URL, and list the URLs that were fetched."""
+ from pathlib import Path
+ from unittest import mock
+
+ urls = []
+
+ def serve(url, dst, **kwargs):
+ urls.append(url)
+ Path(dst).write_bytes(model.SerializeToString())
+
+ with mock.patch("kornia.core.download._download_url_to_file", side_effect=serve):
+ yield urls
+
+ @pytest.mark.parametrize("wrapper", ["module", "sequential"])
+ def test_a_cached_model_is_fetched_again_only_when_forced(self, fetched, tmp_path, wrapper):
+ # the flag is not dropped between the wrapper and the download: the cached file is replaced, not reused
+ from kornia.onnx.module import ONNXModule
+
+ build = ONNXModule if wrapper == "module" else ONNXSequential
+ url = "https://example.com/m.onnx"
+
+ build(url, cache_dir=str(tmp_path))
+ build(url, cache_dir=str(tmp_path))
+ assert fetched == [url]
+
+ build(url, cache_dir=str(tmp_path), force_download=True)
+ assert fetched == [url, url]
+
+ build(url, cache_dir=str(tmp_path))
+ assert fetched == [url, url]
diff --git a/tests/onnx/test_utils.py b/tests/onnx/test_utils.py
index f2c6c9ef4..e73102e24 100644
--- a/tests/onnx/test_utils.py
+++ b/tests/onnx/test_utils.py
@@ -16,6 +16,7 @@
#
import hashlib
+import json
import os
import urllib
from pathlib import Path
@@ -751,3 +752,215 @@ def test_add_metadata_merges_duplicate_keys_already_in_the_model():
("date", "20261001"),
]
onnx.checker.check_model(model)
+
+
+_MODEL_URL = "https://example.com/models/m.onnx"
+_CONFIG_URL = "https://example.com/configs/preprocessor_config.json"
+
+
+def _model_bytes(version: str) -> bytes:
+ """A small valid ONNX model whose ``version`` metadata tells which one it is."""
+ graph = onnx.helper.make_graph(
+ [onnx.helper.make_node("Identity", ["x"], ["y"])],
+ "g",
+ [onnx.helper.make_tensor_value_info("x", onnx.TensorProto.FLOAT, [1])],
+ [onnx.helper.make_tensor_value_info("y", onnx.TensorProto.FLOAT, [1])],
+ )
+ model = onnx.helper.make_model(graph, opset_imports=[onnx.helper.make_opsetid("", 18)])
+ model.metadata_props.add(key="version", value=version)
+ return model.SerializeToString()
+
+
+def _version(model) -> str:
+ return {p.key: p.value for p in model.metadata_props}["version"]
+
+
+def fake_hub():
+ """Replace the transfer of a download by one that serves ``contents[url]`` and records every URL it is asked for."""
+ from unittest import mock
+
+ contents: dict[str, bytes] = {}
+ fetched: list[str] = []
+
+ def serve(url, dst, **kwargs):
+ fetched.append(url)
+ Path(dst).write_bytes(contents[url])
+
+ with mock.patch("kornia.core.download._download_url_to_file", side_effect=serve):
+ yield contents, fetched
+
+
+class TestONNXLoaderForceDownload:
+ @pytest.mark.parametrize("name", ["url", "hf"])
+ def test_load_model_fetches_a_cached_model_again_only_when_forced(self, name, fake_hub, tmp_path):
+ contents, fetched = fake_hub
+ if name == "url":
+ model_name = url = _MODEL_URL
+ else:
+ model_name = "hf://operators/some_model"
+ url = "https://huggingface.co/kornia/ONNX_models/resolve/main/operators/some_model.onnx"
+ contents[url] = _model_bytes("1")
+
+ def load(**kwargs):
+ return ONNXLoader.load_model(model_name, cache_dir=str(tmp_path), **kwargs)
+
+ assert _version(load()) == "1"
+ contents[url] = _model_bytes("2") # the model changed on the hub
+ assert _version(load()) == "1" # a cached model is used as it is
+ assert _version(load(force_download=False)) == "1"
+ assert fetched == [url]
+
+ assert _version(load(force_download=True)) == "2"
+ assert fetched == [url, url]
+
+ assert _version(load()) == "2" # the new model is the cached one
+ assert fetched == [url, url]
+
+ @pytest.mark.parametrize("name", ["url", "hf"])
+ def test_load_model_force_download_fetches_the_weights_again_too(self, name, fake_hub, tmp_path):
+ contents, fetched = fake_hub
+ if name == "url":
+ model_name, url = _MODEL_URL, _MODEL_URL
+ else:
+ model_name = "hf://operators/some_model"
+ url = "https://huggingface.co/kornia/ONNX_models/resolve/main/operators/some_model.onnx"
+ contents[url] = _model_bytes("1")
+ contents[f"{url}_data"] = b"weights 1"
+
+ def load(**kwargs):
+ return ONNXLoader.load_model(model_name, with_data=True, cache_dir=str(tmp_path), **kwargs)
+
+ load()
+ load()
+ assert fetched == [url, f"{url}_data"]
+
+ contents[f"{url}_data"] = b"weights 2"
+ load(force_download=True)
+ assert fetched == [url, f"{url}_data", url, f"{url}_data"]
+ assert next(tmp_path.rglob("*.onnx_data")).read_bytes() == b"weights 2"
+
+ @pytest.mark.parametrize("damage", ["not an onnx file", "truncated"])
+ @pytest.mark.parametrize("name", ["url", "hf"])
+ def test_load_model_damaged_cached_model_names_force_download(self, name, damage, fake_hub, tmp_path):
+ from google.protobuf.message import DecodeError
+
+ contents, fetched = fake_hub
+ if name == "url":
+ model_name = url = _MODEL_URL
+ else:
+ model_name = "hf://operators/some_model"
+ url = "https://huggingface.co/kornia/ONNX_models/resolve/main/operators/some_model.onnx"
+ contents[url] = _model_bytes("1")
+
+ def load(**kwargs):
+ return ONNXLoader.load_model(model_name, cache_dir=str(tmp_path), **kwargs)
+
+ load()
+ (cached,) = tmp_path.rglob("*.onnx")
+ cached.write_bytes(b"<html>Bad gateway</html>" if damage == "not an onnx file" else contents[url][:20])
+
+ # the error is still a DecodeError, and says what to do about the file, which is not fetched again by itself
+ with pytest.raises(DecodeError) as exc_info:
+ load()
+ (note,) = exc_info.value.__notes__
+ assert "force_download=True" in note
+ assert str(cached) in note
+ assert fetched == [url]
+
+ assert _version(load(force_download=True)) == "1"
+ assert fetched == [url, url]
+ assert _version(load()) == "1" # the damaged file was replaced
+ assert fetched == [url, url]
+
+ def test_load_model_force_download_leaves_a_local_file_alone(self, fake_hub, tmp_path):
+ _, fetched = fake_hub
+ path = tmp_path / "local.onnx"
+ path.write_bytes(_model_bytes("local"))
+
+ assert _version(ONNXLoader.load_model(str(path), force_download=True)) == "local"
+ assert fetched == []
+
+ def test_load_model_force_download_without_download_raises(self, fake_hub, tmp_path):
+ contents, fetched = fake_hub
+ contents[_MODEL_URL] = _model_bytes("1")
+ ONNXLoader.load_model(_MODEL_URL, cache_dir=str(tmp_path))
+
+ with pytest.raises(ValueError, match=r"force_download=True.*download=True"):
+ ONNXLoader.load_model(_MODEL_URL, download=False, force_download=True, cache_dir=str(tmp_path))
+
+ assert fetched == [_MODEL_URL]
+ assert _version(ONNXLoader.load_model(_MODEL_URL, download=False, cache_dir=str(tmp_path))) == "1"
+
+ def test_load_config_fetches_a_cached_config_again_only_when_forced(self, fake_hub, tmp_path):
+ contents, fetched = fake_hub
+ contents[_CONFIG_URL] = json.dumps({"size": 1}).encode()
+
+ def load(**kwargs):
+ return ONNXLoader.load_config(_CONFIG_URL, cache_dir=str(tmp_path), **kwargs)
+
+ assert load() == {"size": 1}
+ contents[_CONFIG_URL] = json.dumps({"size": 2}).encode()
+ assert load() == {"size": 1}
+ assert fetched == [_CONFIG_URL]
+
+ assert load(force_download=True) == {"size": 2}
+ assert fetched == [_CONFIG_URL, _CONFIG_URL]
+ assert load() == {"size": 2}
+ assert fetched == [_CONFIG_URL, _CONFIG_URL]
+
+ @pytest.mark.parametrize(
+ ("damage", "error"),
+ [(b"<html>Bad gateway</html>", json.JSONDecodeError), (b"\x89PNG\r\n\x1a\n\x81", UnicodeDecodeError)],
+ ids=["not json", "not text"],
+ )
+ def test_load_config_damaged_cached_config_names_force_download(self, fake_hub, tmp_path, damage, error):
+ contents, fetched = fake_hub
+ contents[_CONFIG_URL] = json.dumps({"size": 1}).encode()
+ ONNXLoader.load_config(_CONFIG_URL, cache_dir=str(tmp_path))
+ (cached,) = tmp_path.rglob("*.json")
+ cached.write_bytes(damage)
+
+ with pytest.raises(error) as exc_info:
+ ONNXLoader.load_config(_CONFIG_URL, cache_dir=str(tmp_path))
+ (note,) = exc_info.value.__notes__
+ assert "force_download=True" in note
+ assert str(cached) in note
+ assert fetched == [_CONFIG_URL]
+
+ assert ONNXLoader.load_config(_CONFIG_URL, cache_dir=str(tmp_path), force_download=True) == {"size": 1}
+ assert fetched == [_CONFIG_URL, _CONFIG_URL]
+
+ def test_load_config_reads_a_utf8_config_whatever_the_locale(self, fake_hub, tmp_path):
+ # the cached bytes are decoded by json, not by the locale's encoding (cp1252 on Windows)
+ contents, _ = fake_hub
+ contents[_CONFIG_URL] = json.dumps({"name": "r\u00e9sum\u00e9"}, ensure_ascii=False).encode("utf-8")
+ assert ONNXLoader.load_config(_CONFIG_URL, cache_dir=str(tmp_path)) == {"name": "r\u00e9sum\u00e9"}
+
+ def test_load_config_force_download_without_download_raises(self, fake_hub, tmp_path):
+ with pytest.raises(ValueError, match=r"force_download=True.*download=True"):
+ ONNXLoader.load_config(_CONFIG_URL, download=False, force_download=True, cache_dir=str(tmp_path))
+
+ def test_load_model_does_not_call_a_file_too_large_to_load_damaged(self, fake_hub, tmp_path):
+ from unittest import mock
+
+ contents, _ = fake_hub
+ contents[_MODEL_URL] = _model_bytes("1")
+ ONNXLoader.load_model(_MODEL_URL, cache_dir=str(tmp_path))
+
+ with mock.patch("onnx.load", side_effect=MemoryError) as onnx_load, pytest.raises(MemoryError) as exc_info:
+ ONNXLoader.load_model(_MODEL_URL, cache_dir=str(tmp_path))
+
+ onnx_load.assert_called_once()
+ assert not hasattr(exc_info.value, "__notes__")
+
+ def test_load_model_local_file_that_does_not_load_gets_no_cache_hint(self, tmp_path):
+ from google.protobuf.message import DecodeError
+
+ path = tmp_path / "local.onnx"
+ path.write_bytes(b"<html>Bad gateway</html>")
+
+ with pytest.raises(DecodeError) as exc_info:
+ ONNXLoader.load_model(str(path))
+
+ assert not hasattr(exc_info.value, "__notes__") # the file is not in the cache, force_download would not help