π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(onnx): one cache entry per remote file, CachedDownloader argument checks, sample download timeout (#5911)
Dmytro Mishkin9eeb553d11ef
diff --git a/changelog.d/5911.breaking.md b/changelog.d/5911.breaking.mdnew file mode 100644index 000000000..a2a349405--- /dev/null+++ b/changelog.d/5911.breaking.md@@ -0,0 +1 @@+`kornia.onnx.download.CachedDownloader.download_to_cache` takes `cache_dir` and `suffix` as keyword-only parameters and raises `TypeError` for any other keyword. `ONNXLoader.load_model` and `ONNXLoader.load_config` raise it for any keyword but `cache_dir`, whatever the model name or URL, and `HFONNXComunnityModelLoader.load_model` for any keyword. An unknown keyword, such as a misspelt `cachedir=`, used to be ignored, and the file was cached in the default directory. `download_to_cache` also raises `ValueError` for a `name` that is absolute or has a drive or an empty, `.` or `..` component, and for a `suffix` that adds a directory to the file name; so does `ONNXLoader.load_model` for an `hf://` name whose folder is `..`, and `HFONNXComunnityModelLoader` for such a `model_name`. Such names used to be joined to the cache directory as they were: `..` stored the file outside the cache directory, and an absolute name was stored below it on POSIX (an absolute `model_name` replaced it). `ONNXLoader.load_model` and `load_config` raise `ValueError` for a URL without a host, such as `https:///a/m.onnx`, which `urlopen` refuses to fetch.diff --git a/changelog.d/5911.fixed.md b/changelog.d/5911.fixed.mdnew file mode 100644index 000000000..d3a7eba88--- /dev/null+++ b/changelog.d/5911.fixed.md@@ -0,0 +1 @@+`kornia.onnx.utils.ONNXLoader` caches every remote file under a path of its own. `HFONNXComunnityModelLoader.load_preprocessing`, which `DepthAnythingBuilder.build` calls, caches each repository's `preprocessor_config.json` beside its model in `<cache_dir>/<model_name>/`; every repository used to share `<hub_cache_dir>/preprocessor_config.json`, so a model built after another one could load the other model's preprocessing. `ONNXLoader.load_model("hf://<folder>/<a>/<b>")` caches `<a>/<b>.onnx` instead of `<a>.onnx` for every model under `<a>`. `load_model` and `load_config` cache a URL at `<scheme>/<host>/<directories of its path>/<file name>` under `cache_dir` or the default directory, with `%3A<port>` after the host when the URL has a port and a `%3F<hash>` directory before the file name when it has a query. A URL used to be cached under its last path component alone, query included, so two URLs that ended in the same file name, such as the `onnx/model.onnx` of two onnx-community repositories, shared one file. Files cached under the old names are neither reused nor moved, since they may hold another file's content: the affected configs and models are downloaded once more, and the old files, `<hub_cache_dir>/preprocessor_config.json` among them, can be deleted. The ONNX models of `HFONNXComunnityModelLoader` and `DepthAnythingBuilder`, and `hf://<folder>/<name>` models, keep their cache paths. `kornia.onnx.download.CachedDownloader.download` and `download_to_cache` accept a path without a directory part, which is a file in the working directory (or `cache_dir=""`), instead of raising `FileNotFoundError`. `kornia.io.get_sample_images` takes its download timeout from `KORNIA_DOWNLOAD_TIMEOUT` (30 s when it is unset), as kornia's other downloads do, instead of always using 30 s.diff --git a/kornia/io/sample.py b/kornia/io/sample.pyindex bb232faa3..cf9a6be7b 100644--- a/kornia/io/sample.py+++ b/kornia/io/sample.py@@ -28,6 +28,7 @@ from urllib.request import urlopenimport torchfrom kornia.config import kornia_config+from kornia.core.download import _resolve_timeoutfrom .io import load_image@@ -55,10 +56,16 @@ def download_image(url: str, save_to: str) -> None:refused keeps the copy already there only if its bytes match the download, and removes its own temporary file. Arefused replacement with a missing, unreadable, or different destination still raises the replacement error.+ The download fails once the server goes ``KORNIA_DOWNLOAD_TIMEOUT`` seconds (30 s when it is unset) without+ answering, as kornia's other downloads do.+Args:url: The URL of the image to download.save_to: The file path where the downloaded image will be saved.+ Raises:+ ValueError: If ``KORNIA_DOWNLOAD_TIMEOUT`` is set to anything but a positive number of seconds.+"""_download(url, save_to)@@ -70,8 +77,9 @@ def _download(url: str, save_to: str, load: Optional[Callable[[str], torch.Tenso``save_to``, which a concurrent call may be replacing (Windows refuses to open a file while it is replaced). A bodythat ``load`` rejects never reaches ``save_to``: the temporary file is removed and the error propagates."""- # get_sample_images only routes http(s) URLs here (default: the https:// literals above).- with urlopen(url, timeout=30) as resp: # noqa: S310+ # get_sample_images only routes http(s) URLs here (default: the https:// literals above). The timeout is the one+ # kornia's other downloads use: KORNIA_DOWNLOAD_TIMEOUT, or 30 s when it is unset.+ with urlopen(url, timeout=_resolve_timeout(None)) as resp: # noqa: S310data = resp.read()# a unique name in the destination directory keeps the rename atomic and concurrent calls apart; open() with "x"# creates the file with the usual permissions (tempfile.mkstemp would make the cached image private, 0o600).@@ -121,6 +129,8 @@ def get_sample_images(- A path is a URL only when its scheme is ``http`` or ``https``. A URL is cached under ``cache_dir`` with thefile name of its path, byte for byte as downloaded, and a cached file is loaded without downloading itagain. With ``download=False``, a URL that is not cached logs an error and raises ``FileNotFoundError``.+ A download fails once the server goes ``KORNIA_DOWNLOAD_TIMEOUT`` seconds (30 s when it is unset) without+ answering, and an unusable value of that variable raises ``ValueError``.- ``resize`` is ``(height, width)`` and goes to :func:`~kornia.geometry.transform.resize`; ``divisible_factor``is applied after it by :func:`~kornia.geometry.transform.resize_to_be_divisible`, so the final size candiffer from ``resize``. ``**kwargs`` reach both.diff --git a/kornia/models/_hf_models/hf_onnx_community.py b/kornia/models/_hf_models/hf_onnx_community.pyindex 80d19a564..5c929aba6 100644--- a/kornia/models/_hf_models/hf_onnx_community.py+++ b/kornia/models/_hf_models/hf_onnx_community.py@@ -17,6 +17,7 @@from __future__ import annotations+import jsonimport osfrom typing import Any, Optional@@ -28,6 +29,7 @@ from kornia.core.external import onnxfrom kornia.geometry.transform import resizefrom kornia.models.base import ModelBaseMixinfrom kornia.onnx import ONNXSequential+from kornia.onnx.download import _relative_path_componentsfrom kornia.onnx.utils import ONNXLoader, io_name_conversionfrom .preprocessor import PreprocessingLoader@@ -39,10 +41,15 @@ class HFONNXComunnityModelLoader:Args:model_name: The name of the model to load.model_type: The type of the model to load.- cache_dir: The directory where models are cached locally.+ cache_dir: The directory where models are cached locally. The model, its weights and its preprocessing+ config are stored in ``<cache_dir>/<model_name>/``.Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.with_data: Whether to download the model weights such as `model.onnx_data`.+ Raises:+ ValueError: If ``model_name`` is absolute, has a drive (on Windows) or has an empty, ``.`` or ``..``+ component, which would put the cache outside ``cache_dir``.+"""def __init__(@@ -54,6 +61,9 @@ class HFONNXComunnityModelLoader:if cache_dir is None:cache_dir = kornia_config.hub_onnx_dir+ # the model, its weights and its preprocessing config are cached in <cache_dir>/<model_name>/, so the name must+ # not leave cache_dir ("../x", an absolute path), where a file already there would be loaded without a download+ _relative_path_components(model_name, "model_name")self.cache_dir = os.path.join(cache_dir, self.model_name)self.model_url = (f"https://huggingface.co/onnx-community/{self.model_name}/resolve/main/onnx/{self.model_type}.onnx"@@ -74,15 +84,27 @@ class HFONNXComunnityModelLoader:output names after loading. This is useful when composing the modelwith Kornia pre-processing or post-processing graphs that expectspecific tensor names.- kwargs: Additional keyword arguments forwarded to :class:`ONNXLoader`.+ kwargs: Not used; any keyword raises ``TypeError``. Kept for compatibility.Returns:The loaded ONNX model graph. If ``io_name_mapping`` is provided, the graphis returned after its input and output names have been converted."""- onnx_model = ONNXLoader.load_model(- self.model_url, download=download, with_data=self.with_data, cache_dir=self.cache_dir, **kwargs+ # <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)+ if self.with_data: # beside the model, under the name the model refers to+ ONNXLoader.download_to_cache(+ f"{self.model_url}_data",+ self.model_type,+ download,+ cache_dir=self.cache_dir,+ suffix=".onnx_data",+ **kwargs,+ )+ onnx_model = onnx.load(file_path) # type:ignoreif io_name_mapping is not None:onnx_model = io_name_conversion(onnx_model, io_name_mapping)@@ -103,8 +125,10 @@ class HFONNXComunnityModelLoader:Sequential Kornia image preprocessing module built from the repositoryconfiguration."""- json_req = ONNXLoader.load_config(self.config_url)- return PreprocessingLoader.from_json(json_req)+ # <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))class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):diff --git a/kornia/onnx/download.py b/kornia/onnx/download.pyindex 7f379d7dc..20828e20a 100644--- a/kornia/onnx/download.py+++ b/kornia/onnx/download.py@@ -20,7 +20,7 @@ from __future__ import annotationsimport loggingimport osimport urllib.error-from typing import Any, Optional+from typing import Optionalfrom kornia.config import kornia_configfrom kornia.core import download as _core_download@@ -30,6 +30,28 @@ __all__ = ["CachedDownloader"]_logger = logging.getLogger(__name__)+def _relative_path_components(name: str, label: str = "name") -> list[str]:+ """Split ``name``, a relative path inside a cache directory, into its components, separated by ``/`` or ``os.sep``.++ Args:+ name: The relative path.+ label: What ``name`` is, for the error message.++ Raises:+ ValueError: If ``name`` is absolute, has a drive (on Windows) or has an empty, ``.`` or ``..`` component, which+ would put the path outside the cache directory or name no file.+ """+ # the component test of kornia.core.download._check_cache_file_name; os.path.basename also catches a Windows+ # drive ("C:", "d:x"), which os.path.join would not keep under the cache directory+ components = name.replace(os.sep, "/").split("/")+ if any(c in _core_download._NOT_A_FILE_NAME or os.path.basename(c) != c for c in components):+ raise ValueError(+ f"{label} must be a relative path inside the cache directory, without a drive or an empty, '.' or '..' "+ f"component; got {name!r}."+ )+ return components++class CachedDownloader:"""Downloads files from URLs to the local cache or .kornia_hub directory."""@@ -38,57 +60,77 @@ class CachedDownloader:"""Construct the file path for the ONNX model based on the model name and cache directory.Args:- model_name: The name of the model or operator, typically in the format 'operators/model_name'.+ model_name: The name of the model or operator, typically in the format 'operators/model_name': a relative+ path whose components are separated by ``/`` (or ``os.sep``).cache_dir: The directory where the model should be cached.- Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.+ Defaults to None, which will use the default ``kornia.config.kornia_config.hub_cache_dir`` directory.suffix: Optional file suffix when the filename is the model name.Returns:str: The full local path where the model should be stored or loaded from.+ Raises:+ ValueError: If ``model_name`` is absolute, has a drive (on Windows) or has an empty, ``.`` or ``..``+ component, which would put the file outside ``cache_dir`` or name no file, or if ``suffix`` adds a+ directory or a drive to the file name.+"""+ components = _relative_path_components(model_name)+# Determine the local file pathif cache_dir is None:cache_dir = kornia_config.hub_cache_dircache_dir = os.path.expanduser(cache_dir)# The filename is the model name (without directory path)- if suffix is not None and not model_name.endswith(suffix):- file_name = f"{os.path.split(model_name)[-1]}{suffix}"- else:- file_name = os.path.split(model_name)[-1]+ file_name = components[-1]+ if suffix is not None and not file_name.endswith(suffix):+ file_name = f"{file_name}{suffix}"+ # the suffix joins the name after the check above, so it must not add a directory or a drive either+ if os.path.basename(file_name) != file_name:+ raise ValueError(f"suffix must not add a directory or a drive to the file name; got {suffix!r}.")- return os.path.join(cache_dir, *model_name.split(os.sep)[:-1], file_name)+ return os.path.join(cache_dir, *components[:-1], file_name)@classmethod- def download_to_cache(cls, url: str, name: str, download: bool = True, **kwargs: Any) -> str:+ def download_to_cache(+ cls,+ url: str,+ name: str,+ download: bool = True,+ *,+ cache_dir: Optional[str] = None,+ suffix: Optional[str] = None,+ ) -> str:"""Resolve a remote file into Kornia's local cache and download it when needed.Args:url: HTTP or HTTPS URL of the file to cache.name: Logical model or operator name used to construct the cache- path. Directory components in ``name`` are preserved under the- cache directory.+ path. Directory components in ``name``, separated by ``/``, are+ preserved under the cache directory.download: If ``True``, download the file when it is not alreadypresent in the cache. If ``False``, require the cached file toexist.- kwargs: Optional cache parameters. Supported keys include- ``cache_dir`` for overriding the default cache root and- ``suffix`` for appending a filename suffix when needed.+ cache_dir: The cache root. Defaults to ``None``, which uses+ ``kornia.config.kornia_config.hub_cache_dir``; ``""`` is the+ current working directory.+ suffix: Appended to the file name unless it already ends with it.Returns:Local filesystem path to the cached file.Raises:- ValueError: If ``url`` is not an HTTP or HTTPS URL, if download is- disabled and the file is missing, or if the server answers with an HTTP error.+ 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.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``).+ http.client.IncompleteRead: If a chunked body is cut mid-chunk (see ``download``)."""if url.startswith(("http:", "https:")):- cache_dir = kwargs.get("cache_dir")- suffix = kwargs.get("suffix")file_path = cls._get_file_path(name, cache_dir, suffix=suffix)cls.download(url, file_path, download_if_not_exists=download)return file_path@@ -116,6 +158,7 @@ class CachedDownloader:answering. Nothing is left at ``file_path``.urllib.error.ContentTooShortError: If the body is shorter than its ``Content-Length``. Nothing isleft 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``.urllib.error.URLError: If the server cannot be reached."""@@ -127,7 +170,9 @@ class CachedDownloader:if not download_if_not_exists:raise ValueError(f"`{file_path}` not found. You may set `download=True`.")- os.makedirs(os.path.dirname(file_path), exist_ok=True)+ directory = os.path.dirname(file_path)+ if directory: # a path without a directory part is a file in the working directory+ os.makedirs(directory, exist_ok=True)if url.startswith(("http:", "https:")):try:diff --git a/kornia/onnx/module.py b/kornia/onnx/module.pyindex fedcada22..aea5dc4ad 100644--- a/kornia/onnx/module.py+++ b/kornia/onnx/module.py@@ -36,7 +36,7 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):providers: A list of execution providers for ONNXRuntime(e.g., ['CUDAExecutionProvider', 'CPUExecutionProvider']).session_options: Optional ONNXRuntime session options for optimizing the session.- cache_dir: The directory where ONNX models are cached locally (only for downloading from HuggingFace).+ cache_dir: The directory where downloaded ONNX models (``hf://`` names and URLs) are cached locally.Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.target_ir_version: The target IR version to convert to.target_opset_version: The target OPSET version to convert to.diff --git a/kornia/onnx/sequential.py b/kornia/onnx/sequential.pyindex 8338c9bed..759d56fb8 100644--- a/kornia/onnx/sequential.py+++ b/kornia/onnx/sequential.py@@ -40,7 +40,7 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):If None, we assume the default input name and output name are "input" and "output" accordingly, andonly one input and output node for each graph.If not None, `io_maps[0]` shall represent the `io_map` for combining the first and second ONNX models.- cache_dir: The directory where ONNX models are cached locally (only for downloading from HuggingFace).+ cache_dir: The directory where downloaded ONNX models (``hf://`` names and URLs) are cached locally.Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.auto_ir_version_conversion: If True, convert the models to one IR version and one OPSET version beforecombining them: IR version 9, and the highest OPSET version among the models, to which the others arediff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.pyindex 72360bdb2..f86092714 100644--- a/kornia/onnx/utils.py+++ b/kornia/onnx/utils.py@@ -17,12 +17,15 @@from __future__ import annotations+import hashlibimport jsonimport loggingimport os+import posixpathimport pprintimport urllib.errorfrom typing import Any, Optional+from urllib.parse import quote, urlsplit, urlunsplitfrom urllib.request import urlopenimport kornia@@ -36,6 +39,65 @@ __all__ = ["ONNXLoader", "add_metadata", "io_name_conversion"]_logger = logging.getLogger(__name__)+# Characters a cache directory keeps besides letters, digits and "_.-~"; quote() percent-encodes every other one, "%"+# included, so no directory is refused on Windows (``:``, ``*``, ``|``, ...) and two different URL directories never+# become one cache directory+_SAFE_DIRECTORY_CHARACTERS = "!$&'()+,;=@[]~"+++def _url_cache_name(url: str) -> str:+ """Return the name, relative to the cache directory, that :class:`ONNXLoader` caches ``url`` under.++ The name is ``<scheme>/<host>[%3A<port>]/<directories of the URL's path>[/%3F<hash>]/<file name>``, under an+ explicit ``cache_dir`` as under the default directory. Two URLs share a file only when they differ in nothing but+ credentials, the fragment, ``.``, ``..`` or empty directories (resolved as RFC 3986 resolves them, which most+ servers follow), or a ``.onnx`` / ``.json`` extension that one of them lacks. The scheme keeps a file fetched over+ ``http`` from being served for ``https``, and keeps URLs apart from the ``hf://`` folders in the same directory. A+ query can name the file (``?id=...``, ``?ref=...``), so a URL with one is stored in a directory named after the+ query's hash; the query itself is not part of any name, since ``?`` cannot be in a file name on Windows. The host+ (an IPv6 address in its brackets) and the directories are percent-encoded (see ``_SAFE_DIRECTORY_CHARACTERS``),+ and so are the ``:`` before the port and the ``?`` before the query's hash, which no host or directory of a URL+ can become, as ``%`` itself is encoded: ``%3A8080`` is never a host and ``%3F<hash>`` never a directory of the+ path. The file name is kept as it is, because a model refers to its ``.onnx_data`` weights by name.++ Raises:+ ValueError: If the URL has no host, or its path does not end in a file name.+ """+ parts = urlsplit(url)+ *directories, file_name = parts.path.split("/")+ if file_name in ("", ".", ".."):+ raise ValueError(f"{url!r} does not end in a file name to cache it under.")+ host = parts.hostname # lower-cased, without any user name or password+ if not host: # urlopen refuses it too; without the host, "https:///a/m" would be cached as "https://a/m"+ raise ValueError(f"{url!r} has no host to cache it under.")+ if ":" in host: # an IPv6 address keeps its brackets, so that "[::1]:8000" stays apart from "[::1:8000]"+ host = f"[{host}]"+ if parts.port is not None:+ host = f"{host}:{parts.port}"+ # the leading "/" makes the path absolute, so normpath drops every ".." that would climb above it+ directory = posixpath.normpath("/" + "/".join(directories))+ components = [parts.scheme, quote(host, safe=_SAFE_DIRECTORY_CHARACTERS)]+ components += [quote(c, safe=_SAFE_DIRECTORY_CHARACTERS) for c in directory.split("/") if c]+ if parts.query:+ components.append(quote("?") + hashlib.sha256(parts.query.encode()).hexdigest()[:16])+ return "/".join([*components, file_name])+++def _check_keywords(method: str, kwargs: dict[str, Any]) -> None:+ """Raise Python's ``TypeError`` for any keyword of ``method`` but ``cache_dir``, whichever branch it takes.++ A local model, or a config URL that is not HTTP(S), never reaches ``download_to_cache``, which would raise it.+ """+ for key in kwargs:+ if key != "cache_dir":+ raise TypeError(f"{method}() got an unexpected keyword argument {key!r}")+++def _onnx_data_name(name: str) -> str:+ """Return the name of the ``.onnx_data`` weights stored beside the model ``name``, with or without ``.onnx``."""+ return (name[: -len(".onnx")] if name.endswith(".onnx") else name) + ".onnx_data"++class ONNXLoader(CachedDownloader):"""Manages ONNX models, handling local caching, downloading from Hugging Face, and loading models."""@@ -46,20 +108,20 @@ class ONNXLoader(CachedDownloader):Args:url: The URL of the preprocessor config to load.download: If True, the config will be downloaded if it's not already in the local cache.- kwargs: Additional download arguments.+ 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``+ or ``""`` means ``kornia_config.hub_cache_dir``. Any other keyword raises ``TypeError``, whatever+ ``url`` is.Returns:dict[str, Any]: The loaded preprocessor config."""+ _check_keywords("ONNXLoader.load_config", kwargs)if url.startswith(("http:", "https:")):- file_path = cls.download_to_cache(- url,- os.path.split(url)[-1],- download=download,- suffix=".json",- **kwargs,- )+ 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)@@ -78,49 +140,48 @@ class ONNXLoader(CachedDownloader):https://huggingface.co/kornia/ONNX_models.Or a URL to the ONNX model.download: If True, the model will be downloaded from Hugging Face if it's not already in the local cache.- cache_dir: The directory where the model should be cached.- Defaults to None, which will use a default `{kornia_config.hub_onnx_dir}` directory.- with_data: If True, the model will be loaded with its `.onnx_data` weights.- **kwargs: Additional arguments to pass to the download method, if needed.+ cache_dir: The root of the cache. An ``hf://`` model is stored under it at the path of its name after+ the folder (``<cache_dir>/a/b.onnx`` for ``hf://models/a/b``): the kornia/ONNX_models names are fully+ qualified (``kornia.color.gray.RgbToGrayscale``), so the folders never share a name. A URL is stored at+ ``<cache_dir>/<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, so that two URLs share a file only when they+ differ in nothing but credentials, the fragment, ``.``, ``..`` or empty directories, or an ``.onnx``+ extension that one of them lacks. Defaults to None (``""`` too): an ``hf://`` model goes to+ ``<kornia_config.hub_onnx_dir>/<folder>/``, and a URL under ``kornia_config.hub_onnx_dir``.+ Limitations: on Windows, a URL whose file name is not a valid file name there, or whose cache path+ is longer than ``MAX_PATH`` (260 characters) while long paths are disabled, cannot be cached, and+ 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.+ **kwargs: Only ``cache_dir``; any other keyword raises ``TypeError``, whatever ``model_name`` is.Returns:onnx.ModelProto: The loaded ONNX model."""+ _check_keywords("ONNXLoader.load_model", kwargs)if model_name.startswith("hf://"):model_name = model_name[len("hf://") :]url = f"https://huggingface.co/kornia/ONNX_models/resolve/main/{model_name}.onnx"- cache_dir = kwargs.get("cache_dir") or os.path.join(kornia_config.hub_onnx_dir, model_name.split("/")[0])- kwargs.update({"cache_dir": cache_dir})- file_path = cls.download_to_cache(- url, model_name.split("/")[1], download=download, suffix=".onnx", **kwargs- )+ if kwargs.get("cache_dir"):+ name = model_name.partition("/")[2] # under an explicit cache_dir, the path after the folder+ 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)if with_data:url_data = f"https://huggingface.co/kornia/ONNX_models/resolve/main/{model_name}.onnx_data"- cls.download_to_cache(- url_data, model_name.split("/")[1], download=download, suffix=".onnx_data", **kwargs- )+ cls.download_to_cache(url_data, name, download=download, suffix=".onnx_data", **kwargs)return onnx.load(file_path) # type:ignoreif model_name.startswith(("http://", "https://")):- cache_dir = kwargs.get("cache_dir") or kornia_config.hub_onnx_dir- kwargs.update({"cache_dir": cache_dir})- file_path = cls.download_to_cache(- model_name,- os.path.split(model_name)[-1],- download=download,- suffix=".onnx",- **kwargs,- )+ 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)if with_data:- url_data = model_name[:-5] + ".onnx_data"- cls.download_to_cache(- url_data,- os.path.split(model_name)[-1][:-5] + ".onnx_data",- download=download,- suffix=".onnx_data",- **kwargs,- )+ 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) # type:ignoreif os.path.exists(model_name):diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.pyindex f2d37369d..c4cfa76d8 100644--- a/tests/io/test_io_image.py+++ b/tests/io/test_io_image.py@@ -684,6 +684,50 @@ class TestSampleImages:assert sorted(p.name for p in cache.iterdir()) == ["palette.png"]assert (out[0][:, 0, 0] * 255).round().tolist() == [255.0, 0.0, 0.0] # index 2 is red: the palette applies+ @pytest.mark.parametrize("entry_point", ["get_sample_images", "download_image"])+ @pytest.mark.parametrize(("variable", "timeout"), [(None, 30.0), ("5", 5.0), (" 0.5 ", 0.5)])+ def test_downloads_take_their_timeout_from_kornia_download_timeout(+ self, tmp_path: Path, monkeypatch, entry_point, variable, timeout+ ) -> None:+ # #5904: the fetch always used timeout=30, whatever KORNIA_DOWNLOAD_TIMEOUT said+ from unittest import mock++ from kornia.io.sample import download_image, get_sample_images++ if variable is None:+ monkeypatch.delenv("KORNIA_DOWNLOAD_TIMEOUT", raising=False)+ else:+ monkeypatch.setenv("KORNIA_DOWNLOAD_TIMEOUT", variable)+ source = tmp_path / "source.png"+ write_image(source, create_random_img8_torch(4, 5, 3))+ url = "https://example.invalid/sample.png"+ with mock.patch("kornia.io.sample.urlopen") as mock_urlopen:+ mock_urlopen.return_value.__enter__.return_value.read.return_value = source.read_bytes()+ if entry_point == "get_sample_images":+ get_sample_images(paths=[url], cache_dir=str(tmp_path / "cache"))+ else:+ download_image(url, str(tmp_path / "saved.png"))+ assert mock_urlopen.call_args.kwargs["timeout"] == timeout++ @pytest.mark.parametrize("variable", ["abc", "0", "-1"])+ def test_an_unusable_kornia_download_timeout_raises_before_downloading(+ self, tmp_path: Path, monkeypatch, variable+ ) -> None:+ from unittest import mock++ from kornia.io import get_sample_images++ monkeypatch.setenv("KORNIA_DOWNLOAD_TIMEOUT", variable)+ source = tmp_path / "source.png"+ write_image(source, create_random_img8_torch(4, 5, 3))+ cache = tmp_path / "cache"+ with mock.patch("kornia.io.sample.urlopen") as mock_urlopen:+ mock_urlopen.return_value.__enter__.return_value.read.return_value = source.read_bytes()+ with pytest.raises(ValueError, match="KORNIA_DOWNLOAD_TIMEOUT"):+ get_sample_images(paths=["https://example.invalid/sample.png"], cache_dir=str(cache))+ mock_urlopen.assert_not_called()+ assert not cache.exists() or list(cache.iterdir()) == []+@pytest.mark.parametrize("url", ["https://example.invalid", "https://example.invalid/", "https://example.invalid/dir/"])diff --git a/tests/models/test_hf_onnx_community.py b/tests/models/test_hf_onnx_community.pyindex 8e996532c..c022e1408 100644--- a/tests/models/test_hf_onnx_community.py+++ b/tests/models/test_hf_onnx_community.py@@ -66,3 +66,87 @@ def test_to_onnx_keeps_one_metadata_entry_per_key(include_pre_and_post_processor("date", "2"),]onnx.checker.check_model(exported)+++def test_each_repository_preprocessing_config_is_cached_beside_its_model(monkeypatch, tmp_path):+ # #5902: every onnx-community repository's preprocessor_config.json used to be cached as one file,+ # <hub_cache_dir>/preprocessor_config.json, outside the loader's cache_dir, so the second model built loaded the+ # first one's preprocessing+ import json+ from pathlib import Path+ from unittest import mock++ import torch++ from kornia.config import kornia_config+ from kornia.models._hf_models import HFONNXComunnityModelLoader++ monkeypatch.chdir(tmp_path)+ monkeypatch.setattr(kornia_config, "hub_cache_dir", str(tmp_path / "hub"))+ sizes = {"depth-anything-v2-small": 14, "depth-anything-v2-large": 28}++ def serve(url, dst, **kwargs):+ (size,) = (size for name, size in sizes.items() if f"/onnx-community/{name}/" in url)+ config = {+ "image_processor_type": "DPTImageProcessor",+ "do_pad": False,+ "do_resize": True,+ "size": {"height": size, "width": size},+ "do_rescale": False,+ "do_normalize": False,+ }+ Path(dst).write_text(json.dumps(config))++ # one root, as DepthAnythingBuilder.build(cache_dir=None) uses for every repository+ loaders = {name: HFONNXComunnityModelLoader(name, cache_dir=str(tmp_path / "hub")) for name in sizes}+ image = torch.rand(1, 3, 7, 9)+ with mock.patch("kornia.core.download._download_url_to_file", side_effect=serve):+ for name, loader in loaders.items():+ preprocessing = loader.load_preprocessing()+ assert preprocessing(image).shape[-2:] == (sizes[name], sizes[name]), name++ assert sorted(p.relative_to(tmp_path).as_posix() for p in tmp_path.rglob("*.json")) == [+ "hub/depth-anything-v2-large/preprocessor_config.json",+ "hub/depth-anything-v2-small/preprocessor_config.json",+ ]++[email protected]("with_data", [False, True])+def test_loader_keeps_the_model_cache_paths_of_earlier_releases(with_data, tmp_path):+ # <cache_dir>/<model_name>/<model_type>.onnx(_data): a model of up to 1.3 GB that is already cached there must not+ # be downloaded again+ from unittest import mock++ from kornia.models._hf_models import HFONNXComunnityModelLoader+ from kornia.onnx.utils import ONNXLoader++ loader = HFONNXComunnityModelLoader(+ "depth-anything-v2-large", "model_fp16", cache_dir=str(tmp_path), with_data=with_data+ )+ with mock.patch.object(ONNXLoader, "download") as mock_download, mock.patch("onnx.load"):+ loader.load_model()+ url = "https://huggingface.co/onnx-community/depth-anything-v2-large/resolve/main/onnx/model_fp16.onnx"+ expected = [(url, str(tmp_path / "depth-anything-v2-large" / "model_fp16.onnx"))]+ if with_data:+ expected.append((url + "_data", str(tmp_path / "depth-anything-v2-large" / "model_fp16.onnx_data")))+ assert [c.args[:2] for c in mock_download.call_args_list] == expected++[email protected]("model_name", ["../outside", "a/../../outside", "", ".", "ABSOLUTE"])+def test_loader_refuses_a_model_name_outside_the_cache_directory(model_name, tmp_path):+ # the model, its weights and its preprocessing config are cached in <cache_dir>/<model_name>/: a name that leaves+ # cache_dir would load a file already there, such as <cache_dir>/../outside/preprocessor_config.json, unfetched+ from unittest import mock++ from kornia.models._hf_models import HFONNXComunnityModelLoader+ from kornia.onnx.utils import ONNXLoader++ root = tmp_path / "hub"+ outside = tmp_path / "outside"+ outside.mkdir()+ (outside / "preprocessor_config.json").write_text("{}")+ if model_name == "ABSOLUTE":+ model_name = str(outside)+ 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()diff --git a/tests/onnx/test_download.py b/tests/onnx/test_download.pyindex cc73bd090..b0a3c551e 100644--- a/tests/onnx/test_download.py+++ b/tests/onnx/test_download.py@@ -116,6 +116,71 @@ class TestCachedDownloader:assert hits == ["/model"]assert list((tmp_path / "cwd").iterdir()) == []+ def test_path_without_a_directory_is_downloaded_into_the_working_directory(+ self, download_server, monkeypatch, tmp_path+ ):+ # #5903: os.makedirs("") raised FileNotFoundError before any request+ monkeypatch.chdir(tmp_path)+ responses, base_url, hits = download_server+ responses["/model"] = (b"weights", 7)++ CachedDownloader.download(f"{base_url}/model", "plain.pth")+ path = CachedDownloader.download_to_cache(f"{base_url}/model", "m", cache_dir="", suffix=".pth")++ assert path == "m.pth"+ assert (tmp_path / "plain.pth").read_bytes() == b"weights"+ assert (tmp_path / "m.pth").read_bytes() == b"weights"+ assert hits == ["/model", "/model"]++ def test_unknown_keyword_raises(self, monkeypatch, tmp_path):+ # #5903: a misspelt keyword was dropped, and the file was cached in the default directory under another name+ monkeypatch.chdir(tmp_path)+ url = "http://127.0.0.1:9/model"++ with mock.patch("kornia.core.download._download_url_to_file") as transfer:+ with pytest.raises(TypeError, match="cachedir"):+ CachedDownloader.download_to_cache(url, "k", cachedir="mine", suffix=".pth")+ with pytest.raises(TypeError, match="suffx"):+ CachedDownloader.download_to_cache(url, "k", cache_dir="mine", suffx=".pth")++ transfer.assert_not_called()+ assert list(tmp_path.iterdir()) == []++ @pytest.mark.parametrize(+ "name",+ ["../../escape", "a/../../../escape", "/abs/escape", os.path.abspath("escape"), "", ".", "dir/", "a//b"],+ )+ def test_name_that_is_not_a_relative_path_inside_the_cache_raises(self, name, monkeypatch, tmp_path):+ # #5903: "../../escape" was written two levels above cache_dir, although the name's directory components are+ # documented to stay under the cache directory+ monkeypatch.chdir(tmp_path)++ with (+ mock.patch("kornia.core.download._download_url_to_file") as transfer,+ pytest.raises(ValueError, match="relative path inside the cache directory"),+ ):+ CachedDownloader.download_to_cache("http://127.0.0.1:9/model", name, cache_dir="cache/a/b", suffix=".pth")++ transfer.assert_not_called()+ assert list(tmp_path.iterdir()) == []++ @pytest.mark.parametrize("suffix", ["/../../../escape", "/x", "/"])+ def test_suffix_that_leaves_the_file_name_raises(self, suffix, monkeypatch, tmp_path):+ # the suffix is appended after the name is checked, so it is checked on its own: "model" + "/../../../escape"+ # would put the file three levels above cache_dir+ monkeypatch.chdir(tmp_path)++ with (+ mock.patch("kornia.core.download._download_url_to_file") as transfer,+ pytest.raises(ValueError, match="suffix"),+ ):+ CachedDownloader.download_to_cache(+ "http://127.0.0.1:9/model", "model", cache_dir="cache/a/b", suffix=suffix+ )++ transfer.assert_not_called()+ assert list(tmp_path.iterdir()) == []+def test_short_transfer_is_not_cached(self, download_server, monkeypatch, tmp_path):monkeypatch.chdir(tmp_path)responses, base_url, hits = download_serverdiff --git a/tests/onnx/test_utils.py b/tests/onnx/test_utils.pyindex abaef4788..23fc9db8a 100644--- a/tests/onnx/test_utils.py+++ b/tests/onnx/test_utils.py@@ -15,6 +15,7 @@# limitations under the License.#+import hashlibimport osimport urllibfrom pathlib import Path@@ -28,6 +29,9 @@ onnx = pytest.importorskip("onnx")from kornia.onnx.utils import ONNXLoader # noqa: E402+# the directory that a URL whose query is "download=1" is cached in+_Q_DOWNLOAD_1 = "%3F" + hashlib.sha256(b"download=1").hexdigest()[:16]+class TestONNXLoader:def test_get_file_path(self):@@ -36,6 +40,29 @@ class TestONNXLoader:expected_path = os.path.join(".kornia_hub", "some_model.onnx")assert ONNXLoader._get_file_path(model_name, None, suffix=".onnx") == expected_path+ @pytest.mark.parametrize("name", ["a/b", "a\\b"])+ def test_get_file_path_on_windows_splits_on_both_separators(self, name, monkeypatch):+ # hf:// names and URL paths use "/", and a name built with os.path.join uses "\\" on Windows: both split+ import ntpath+ from types import SimpleNamespace++ import kornia.onnx.download++ monkeypatch.setattr(kornia.onnx.download, "os", SimpleNamespace(sep="\\", path=ntpath))+ assert ONNXLoader._get_file_path(name, "cache", suffix=".onnx") == ntpath.join("cache", "a", "b.onnx")++ @pytest.mark.parametrize("name", ["C:x", "C:\\abs\\x", "d:/x", "a/C:", "\\\\server\\share\\x"])+ def test_get_file_path_on_windows_rejects_a_drive(self, name, monkeypatch):+ # os.path.join("cache", "C:x") is "C:x", a path on drive C:, not a name inside cache+ import ntpath+ from types import SimpleNamespace++ import kornia.onnx.download++ monkeypatch.setattr(kornia.onnx.download, "os", SimpleNamespace(sep="\\", path=ntpath))+ with pytest.raises(ValueError, match="relative path inside the cache directory, without a drive"):+ ONNXLoader._get_file_path(name, "cache", suffix=".onnx")+def test_load_model_local(self):from unittest import mock@@ -94,6 +121,331 @@ class TestONNXLoader:download_if_not_exists=True,)+ @pytest.mark.parametrize("explicit_cache_dir", [False, True])+ def test_load_model_hf_name_keeps_every_path_component(self, explicit_cache_dir, monkeypatch, tmp_path):+ # #5902: hf://models/a/b and hf://models/a/c used to share one cache file, <dir>/a.onnx, and so did their+ # .onnx_data weights; each must keep its own path below the folder, with the weights beside the model+ from unittest import mock++ from kornia.config import kornia_config++ hub_dir = str(tmp_path / "onnx_models")+ monkeypatch.setattr(kornia_config, "hub_onnx_dir", hub_dir)+ cache_dir = str(tmp_path / "mine") if explicit_cache_dir else os.path.join(hub_dir, "models")+ kwargs = {"cache_dir": cache_dir} if explicit_cache_dir else {}++ with mock.patch.object(ONNXLoader, "download") as mock_download, mock.patch("onnx.load") as mock_onnx_load:+ ONNXLoader.load_model("hf://models/a/b", with_data=True, **kwargs)+ ONNXLoader.load_model("hf://models/a/c", **kwargs)++ base = "https://huggingface.co/kornia/ONNX_models/resolve/main/models/a"+ assert mock_download.call_args_list == [+ mock.call(f"{base}/b.onnx", os.path.join(cache_dir, "a", "b.onnx"), download_if_not_exists=True),+ mock.call(f"{base}/b.onnx_data", os.path.join(cache_dir, "a", "b.onnx_data"), download_if_not_exists=True),+ mock.call(f"{base}/c.onnx", os.path.join(cache_dir, "a", "c.onnx"), download_if_not_exists=True),+ ]+ assert [c.args[0] for c in mock_onnx_load.call_args_list] == [+ os.path.join(cache_dir, "a", "b.onnx"),+ os.path.join(cache_dir, "a", "c.onnx"),+ ]++ def test_load_model_url_cache_path_follows_the_url(self, monkeypatch, tmp_path):+ # #5902: a URL was cached under its last component only, query included (m.onnx?download=1.onnx), so URLs+ # that end in the same file name shared one entry. The entry follows the scheme, the host and the path; a query+ # gets a directory named after its hash, shared by the model and its weights.+ from unittest import mock++ from kornia.config import kornia_config++ hub_dir = str(tmp_path / "onnx_models")+ monkeypatch.setattr(kornia_config, "hub_onnx_dir", hub_dir)+ urls = [+ "https://example.invalid/x/m.onnx?download=1",+ "https://example.invalid/y/m.onnx",+ "https://other.invalid/x/m.onnx",+ ]++ with mock.patch.object(ONNXLoader, "download") as mock_download, mock.patch("onnx.load"):+ ONNXLoader.load_model(urls[0], with_data=True)+ for url in urls[1:]:+ ONNXLoader.load_model(url)++ q = _Q_DOWNLOAD_1+ assert mock_download.call_args_list == [+ mock.call(+ urls[0],+ os.path.join(hub_dir, "https", "example.invalid", "x", q, "m.onnx"),+ download_if_not_exists=True,+ ),+ mock.call(+ "https://example.invalid/x/m.onnx_data?download=1",+ os.path.join(hub_dir, "https", "example.invalid", "x", q, "m.onnx_data"),+ download_if_not_exists=True,+ ),+ mock.call(+ urls[1], os.path.join(hub_dir, "https", "example.invalid", "y", "m.onnx"), download_if_not_exists=True+ ),+ mock.call(+ urls[2], os.path.join(hub_dir, "https", "other.invalid", "x", "m.onnx"), download_if_not_exists=True+ ),+ ]++ def test_load_model_url_without_onnx_extension_fetches_its_weights_beside_it(self, monkeypatch, tmp_path):+ from unittest import mock++ from kornia.config import kornia_config++ hub_dir = str(tmp_path / "onnx_models")+ monkeypatch.setattr(kornia_config, "hub_onnx_dir", hub_dir)+ with mock.patch.object(ONNXLoader, "download") as mock_download, mock.patch("onnx.load"):+ ONNXLoader.load_model("https://example.invalid/x/model", with_data=True)+ directory = os.path.join(hub_dir, "https", "example.invalid", "x")+ assert [c.args[:2] for c in mock_download.call_args_list] == [+ ("https://example.invalid/x/model", os.path.join(directory, "model.onnx")),+ ("https://example.invalid/x/model.onnx_data", os.path.join(directory, "model.onnx_data")),+ ]++ @pytest.mark.parametrize(+ ("url", "expected"),+ [+ ("https://example.invalid/x/m.onnx#part", "https/example.invalid/x/m.onnx"),+ ("https://Example.INVALID/X/m.onnx", "https/example.invalid/X/m.onnx"),+ ("https://user:[email protected]/m.onnx", "https/example.invalid/m.onnx"),+ # the ":" before a port, and those of an IPv6 address, are encoded as "%" is, so no host name can be+ # mistaken for a host with a port; the brackets keep "[::1]:8000" apart from "[::1:8000]"+ ("http://127.0.0.1:8000/m.onnx", "http/127.0.0.1%3A8000/m.onnx"),+ ("http://a_8000/m.onnx", "http/a_8000/m.onnx"),+ ("http://[::1]/m.onnx", "http/[%3A%3A1]/m.onnx"),+ ("http://[::1]:8000/m.onnx", "http/[%3A%3A1]%3A8000/m.onnx"),+ ("http://[::1:8000]/m.onnx", "http/[%3A%3A1%3A8000]/m.onnx"),+ ("http://__1_8000/m.onnx", "http/__1_8000/m.onnx"),+ ("https://example.invalid/a/../b/./m.onnx", "https/example.invalid/b/m.onnx"),+ ("https://example.invalid/../../m.onnx", "https/example.invalid/m.onnx"),+ ("https://example.invalid//x//m.onnx", "https/example.invalid/x/m.onnx"),+ ("https://example.invalid/x/model", "https/example.invalid/x/model.onnx"),+ ("https://example.invalid/x/m.onnx?download=1", f"https/example.invalid/x/{_Q_DOWNLOAD_1}/m.onnx"),+ # a directory of the path never becomes the query's: its "%" is encoded+ (+ f"https://example.invalid/x/{_Q_DOWNLOAD_1}/m.onnx",+ f"https/example.invalid/x/%25{_Q_DOWNLOAD_1[1:]}/m.onnx",+ ),+ # a directory keeps no character that Windows refuses (":" would also make "C:" a drive), and "%" is+ # encoded too, so that "x:y" and "x%3Ay" stay two directories+ ("https://example.invalid/x:y/a b/m.onnx", "https/example.invalid/x%3Ay/a%20b/m.onnx"),+ ("https://example.invalid/x%3Ay/m.onnx", "https/example.invalid/x%253Ay/m.onnx"),+ ("https://example.invalid/C:/m.onnx", "https/example.invalid/C%3A/m.onnx"),+ ('https://example.invalid/<a>|"*\\/m.onnx', "https/example.invalid/%3Ca%3E%7C%22%2A%5C/m.onnx"),+ ],+ )+ @pytest.mark.parametrize("cache_dir", ["absent", None, ""])+ def test_load_model_url_default_cache_path(self, url, expected, cache_dir, monkeypatch, tmp_path):+ # the entry stays inside the hub directory: no credentials, ":" or ".." reach the path; an empty cache_dir+ # means the default directory, as it does for hf:// names+ from unittest import mock++ from kornia.config import kornia_config++ hub_dir = str(tmp_path / "onnx_models")+ monkeypatch.setattr(kornia_config, "hub_onnx_dir", hub_dir)+ kwargs = {} if cache_dir == "absent" else {"cache_dir": cache_dir}+ with mock.patch.object(ONNXLoader, "download") as mock_download, mock.patch("onnx.load"):+ ONNXLoader.load_model(url, **kwargs)++ mock_download.assert_called_once_with(+ url, os.path.join(hub_dir, *expected.split("/")), download_if_not_exists=True+ )++ def test_load_model_url_with_cache_dir_follows_the_url_below_it(self, tmp_path):+ # an explicit cache_dir is the root the URL's entry is stored under, as the default directory is: every+ # onnx-community repository names its model onnx/model.onnx, and two of them must not share one file+ from unittest import mock++ cache_dir = str(tmp_path / "mine")+ urls = [f"https://huggingface.co/onnx-community/{m}/resolve/main/onnx/model.onnx" for m in ("small", "large")]+ with mock.patch.object(ONNXLoader, "download") as mock_download, mock.patch("onnx.load"):+ for url in urls:+ ONNXLoader.load_model(url, with_data=True, cache_dir=cache_dir)++ repo = os.path.join(cache_dir, "https", "huggingface.co", "onnx-community")+ assert [c.args[1] for c in mock_download.call_args_list] == [+ os.path.join(repo, "small", "resolve", "main", "onnx", "model.onnx"),+ os.path.join(repo, "small", "resolve", "main", "onnx", "model.onnx_data"),+ os.path.join(repo, "large", "resolve", "main", "onnx", "model.onnx"),+ os.path.join(repo, "large", "resolve", "main", "onnx", "model.onnx_data"),+ ]++ @pytest.mark.parametrize("cache_dir", [None, "mine"])+ def test_urls_that_differ_in_their_query_or_scheme_are_cached_apart(self, cache_dir, monkeypatch, tmp_path):+ # a query can name the file (?id=, ?ref=), and a file fetched over http must never be served for https+ import json+ from unittest import mock++ from kornia.config import kornia_config++ monkeypatch.chdir(tmp_path)+ monkeypatch.setattr(kornia_config, "hub_cache_dir", str(tmp_path / "hub"))+ urls = [+ "https://a.invalid/uc?export=download&id=AAA",+ "https://a.invalid/uc?export=download&id=BBB",+ "http://a.invalid/uc?export=download&id=AAA",+ "https://a.invalid/uc",+ ]++ def serve(url, dst, **kwargs):+ Path(dst).write_text(json.dumps({"url": url}))++ kwargs = {} if cache_dir is None else {"cache_dir": cache_dir}+ with mock.patch("kornia.core.download._download_url_to_file", side_effect=serve):+ assert [ONNXLoader.load_config(url, **kwargs)["url"] for url in urls] == urls+ assert [ONNXLoader.load_config(url, **kwargs)["url"] for url in urls] == urls # served from the cache++ def test_urls_that_spell_out_a_cache_directory_are_cached_apart(self, monkeypatch, tmp_path):+ # the query's directory and the port are added to the name, and a URL whose own directory or host is spelt+ # like them must not be served the other's file: "q-<hash>" and "<host>_<port>" used to be such names+ import json+ from unittest import mock++ from kornia.config import kornia_config++ monkeypatch.chdir(tmp_path)+ monkeypatch.setattr(kornia_config, "hub_cache_dir", str(tmp_path / "hub"))+ q = hashlib.sha256(b"revision=trusted").hexdigest()[:16]+ urls = [+ "https://models.invalid/download/model.json?revision=trusted",+ f"https://models.invalid/download/q-{q}/model.json",+ f"https://models.invalid/download/%3F{q}/model.json",+ "https://a.invalid:8080/model.json",+ "https://a.invalid_8080/model.json",+ "https://a.invalid%3A8080/model.json",+ ]++ def serve(url, dst, **kwargs):+ Path(dst).write_text(json.dumps({"url": url}))++ with mock.patch("kornia.core.download._download_url_to_file", side_effect=serve):+ assert [ONNXLoader.load_config(url)["url"] for url in urls] == urls+ assert [ONNXLoader.load_config(url)["url"] for url in reversed(urls)] == urls[::-1] # from the cache++ @pytest.mark.parametrize("url", ["https:///m.onnx", "https:///a/m.onnx", "https://user@/a/m.onnx"])+ def test_load_model_url_without_a_host_raises(self, url, monkeypatch, tmp_path):+ # without its host, "https:///a/m.onnx" would be cached as "https://a/m.onnx", which urlopen fetches while it+ # refuses the former+ from unittest import mock++ monkeypatch.chdir(tmp_path)+ with (+ mock.patch.object(ONNXLoader, "download") as mock_download,+ mock.patch("onnx.load"),+ pytest.raises(ValueError, match="no host"),+ ):+ ONNXLoader.load_model(url)+ mock_download.assert_not_called()++ def test_load_config_with_an_empty_cache_dir_uses_the_default_directory(self, monkeypatch, tmp_path):+ # as for load_model: "" is the default directory, not the working directory+ import json+ from unittest import mock++ from kornia.config import kornia_config++ monkeypatch.chdir(tmp_path)+ monkeypatch.setattr(kornia_config, "hub_cache_dir", str(tmp_path / "hub"))++ def serve(url, dst, **kwargs):+ Path(dst).write_text(json.dumps({"url": url}))++ with mock.patch("kornia.core.download._download_url_to_file", side_effect=serve):+ ONNXLoader.load_config("https://a.invalid/x/cfg.json", cache_dir="")++ assert [p.relative_to(tmp_path).as_posix() for p in tmp_path.rglob("*.json")] == [+ "hub/https/a.invalid/x/cfg.json"+ ]++ def test_load_config_caches_each_url_separately(self, monkeypatch, tmp_path):+ # #5902: every config was cached as <hub_cache_dir>/<last URL component>, so the first one downloaded was+ # served for every other URL ending in the same file name+ import json+ from unittest import mock++ from kornia.config import kornia_config++ monkeypatch.chdir(tmp_path)+ monkeypatch.setattr(kornia_config, "hub_cache_dir", str(tmp_path / "hub"))+ urls = [+ "https://a.invalid/preprocessor_config.json",+ "https://a.invalid/other/preprocessor_config.json",+ "https://b.invalid/preprocessor_config.json",+ "https://b.invalid/cfg.json?x=1",+ ]++ def serve(url, dst, **kwargs):+ Path(dst).write_text(json.dumps({"url": url}))++ with mock.patch("kornia.core.download._download_url_to_file", side_effect=serve):+ assert [ONNXLoader.load_config(url)["url"] for url in urls] == urls+ assert [ONNXLoader.load_config(url)["url"] for url in urls] == urls # served from the cache++ q = "%3F" + hashlib.sha256(b"x=1").hexdigest()[:16]+ assert sorted(p.relative_to(tmp_path).as_posix() for p in tmp_path.rglob("*.json")) == [+ "hub/https/a.invalid/other/preprocessor_config.json",+ "hub/https/a.invalid/preprocessor_config.json",+ f"hub/https/b.invalid/{q}/cfg.json",+ "hub/https/b.invalid/preprocessor_config.json",+ ]++ @pytest.mark.parametrize(+ "url", ["https://example.invalid", "https://example.invalid/", "https://example.invalid/d/"]+ )+ def test_load_model_url_without_a_file_name_raises(self, url, monkeypatch, tmp_path):+ from unittest import mock++ monkeypatch.chdir(tmp_path)+ with (+ mock.patch.object(ONNXLoader, "download") as mock_download,+ mock.patch("onnx.load"),+ pytest.raises(ValueError, match="file name"),+ ):+ ONNXLoader.load_model(url)+ mock_download.assert_not_called()++ def test_load_model_hf_name_outside_the_hub_directory_raises(self, monkeypatch, tmp_path):+ # the folder of an hf:// name is joined into the default directory, so it is checked as the rest is+ from unittest import mock++ monkeypatch.chdir(tmp_path)+ with mock.patch.object(ONNXLoader, "download") as mock_download, pytest.raises(ValueError, match="relative"):+ ONNXLoader.load_model("hf://../x")+ mock_download.assert_not_called()++ def test_load_model_rejects_an_unknown_keyword(self, monkeypatch, tmp_path):+ # #5903: load_model forwards its keyword arguments to download_to_cache, which used to drop a misspelt one+ from unittest import mock++ monkeypatch.chdir(tmp_path)+ with (+ mock.patch.object(ONNXLoader, "download") as mock_download,+ mock.patch("onnx.load"),+ pytest.raises(TypeError, match="cachedir"),+ ):+ ONNXLoader.load_model("hf://operators/some_model", cachedir="mine")+ mock_download.assert_not_called()++ def test_unknown_keyword_raises_for_every_kind_of_name(self, tmp_path):+ # a local model or a config URL that is not http(s) never reaches download_to_cache, so the keywords are+ # checked on entry: a misspelt cache_dir must not pass silently on one branch only+ from unittest import mock++ local = tmp_path / "local.onnx"+ local.write_bytes(b"")+ with mock.patch("onnx.load") as mock_onnx_load:+ with pytest.raises(TypeError, match="cachedir"):+ ONNXLoader.load_model(str(local), cachedir="mine")+ with pytest.raises(TypeError, match="cachedir"):+ ONNXLoader.load_model("https://example.invalid/m.onnx", download=False, cachedir="mine")+ mock_onnx_load.assert_not_called()+ with pytest.raises(TypeError, match="cachedir"):+ ONNXLoader.load_config(str(tmp_path / "cfg.json"), cachedir="mine")+def test_load_model_not_found(self):model_name = "non_existent_model.onnx"with pytest.raises(ValueError, match=f"File {model_name} not found"):