Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

refactor(io): replace requests with the standard library (#4302)

Dmytro Mishkinb21d179dfa75
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7b093cd90..3feafb464 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -310,6 +310,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* `kornia.io.get_sample_images` and `kornia.onnx.ONNXLoader.list_operators` / `list_models` no longer need
+ `requests`, which `pip install kornia` never installed; they fetch with the standard library `urllib` instead.
+ The failure exceptions change with it, all still `OSError` subclasses: a sample-image URL that returns 404 now
+ raises `urllib.error.HTTPError` instead of `PIL.UnidentifiedImageError`, and an unreachable host raises
+ `urllib.error.URLError` instead of `requests.exceptions.ConnectionError`. A 404 from the Hugging Face listing
+ still raises the same `ValueError` (#4302)
* `packaging` is no longer a runtime dependency; it was never imported. The `dev` extra no longer lists
`pytest-cov` (CI runs `coverage run -m pytest`), `ruff` (the pre-commit hook installs the pinned copy) or a
`numpy<3` cap, and `uv.lock` is regenerated to match (#4296).
diff --git a/kornia/core/external.py b/kornia/core/external.py
index 6bf4752fc..c90fd1bc5 100644
--- a/kornia/core/external.py
+++ b/kornia/core/external.py
@@ -157,4 +157,3 @@ transformers = LazyLoader("transformers")
onnxruntime = LazyLoader("onnxruntime")
boxmot = LazyLoader("boxmot")
segmentation_models_pytorch = LazyLoader("segmentation_models_pytorch")
-requests = LazyLoader("requests")
diff --git a/kornia/io/sample.py b/kornia/io/sample.py
index fbde83b30..120ccb25e 100644
--- a/kornia/io/sample.py
+++ b/kornia/io/sample.py
@@ -17,14 +17,15 @@
from __future__ import annotations
+import io
import logging
import os
from typing import Any, List, Optional, Tuple, Union
+from urllib.request import urlopen
import torch
from kornia.core.external import PILImage as Image
-from kornia.core.external import requests
from .io import load_image
@@ -50,7 +51,9 @@ def download_image(url: str, save_to: str) -> None:
save_to: The file path where the downloaded image will be saved.
"""
- im = Image.open(requests.get(url, stream=True, timeout=30).raw) # type:ignore
+ # get_sample_images only routes paths that start with "http" here (default: the https:// literals above).
+ with urlopen(url, timeout=30) as resp: # noqa: S310
+ im = Image.open(io.BytesIO(resp.read()))
im.save(save_to)
diff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.py
index ddd8649a5..e3a9f580d 100644
--- a/kornia/onnx/utils.py
+++ b/kornia/onnx/utils.py
@@ -21,12 +21,14 @@ import json
import logging
import os
import pprint
+import urllib.error
from typing import Any, Optional
+from urllib.request import urlopen
import kornia
from kornia.config import kornia_config
from kornia.core.external import numpy as np
-from kornia.core.external import onnx, requests
+from kornia.core.external import onnx
from kornia.onnx.download import CachedDownloader
__all__ = ["ONNXLoader", "add_metadata", "io_name_conversion"]
@@ -139,12 +141,12 @@ class ONNXLoader(CachedDownloader):
"""
url = f"https://huggingface.co/api/models/kornia/ONNX_models/tree/main/{folder}"
- response = requests.get(url, timeout=10) # type:ignore
-
- if response.status_code == 200:
- return response.json() # Returns the JSON content of the repo
- else:
- raise ValueError(f"Failed to fetch repository contents: {response.status_code}")
+ try:
+ # url is a fixed https:// literal built from a hardcoded Hugging Face API prefix.
+ with urlopen(url, timeout=10) as response:
+ return json.loads(response.read()) # Returns the JSON content of the repo
+ except urllib.error.HTTPError as e:
+ raise ValueError(f"Failed to fetch repository contents: {e.code}") from e
@classmethod
def list_operators(cls) -> None:
diff --git a/pyproject.toml b/pyproject.toml
index 7ad028b0c..7d35a8027 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -47,7 +47,6 @@ dev = [
"pre-commit",
"pytest",
"pytest-timeout",
- "requests",
"setuptools", # torch.compile / triton on py3.11 + torch 2.5.1, which does not declare it there
"transformers<5.11",
]
diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.py
index 82b8dc28f..d2c903542 100644
--- a/tests/io/test_io_image.py
+++ b/tests/io/test_io_image.py
@@ -18,10 +18,10 @@
import io
import sys
from pathlib import Path
+from urllib.request import urlopen
import numpy as np
import pytest
-import requests
import torch
from kornia.core._compat import torch_version_ge
@@ -50,7 +50,9 @@ def _download_image(url: str, filename: str = "") -> Path:
filename = url.rsplit("/", maxsplit=1)[-1] if len(filename) == 0 else filename
# Download
- bytesio = io.BytesIO(requests.get(url, timeout=60).content)
+ # url is a fixed https:// literal defined by each fixture above.
+ with urlopen(url, timeout=60) as resp: # noqa: S310
+ bytesio = io.BytesIO(resp.read())
# Save file
with open(filename, "wb") as outfile:
outfile.write(bytesio.getbuffer())
@@ -166,3 +168,45 @@ class TestIoImage:
write_image(file_path, img_th)
assert file_path.is_file()
+
+
+class TestDownloadImage:
+ """Offline pins for ``kornia.io.sample.download_image``; ``urlopen`` is mocked, no network is touched."""
+
+ URL = "https://raw.githubusercontent.com/kornia/data/main/panda.jpg"
+
+ def test_saves_the_fetched_bytes(self, tmp_path):
+ from unittest import mock
+
+ from PIL import Image as PILImage
+
+ from kornia.io.sample import download_image
+
+ payload = io.BytesIO()
+ PILImage.new("RGB", (4, 3), (10, 20, 30)).save(payload, format="PNG")
+ with mock.patch("kornia.io.sample.urlopen") as mock_urlopen:
+ mock_urlopen.return_value.__enter__.return_value.read.return_value = payload.getvalue()
+ dst = tmp_path / "panda.png"
+ download_image(self.URL, str(dst))
+
+ mock_urlopen.assert_called_once_with(self.URL, timeout=30)
+ with PILImage.open(dst) as saved:
+ assert saved.size == (4, 3)
+ assert saved.getpixel((0, 0)) == (10, 20, 30)
+
+ def test_http_error_propagates(self, tmp_path):
+ import urllib.error
+ from unittest import mock
+
+ from kornia.io.sample import download_image
+
+ dst = tmp_path / "panda.png"
+ with (
+ mock.patch(
+ "kornia.io.sample.urlopen",
+ side_effect=urllib.error.HTTPError(self.URL, 404, "Not Found", {}, None),
+ ),
+ pytest.raises(urllib.error.HTTPError, match="404"),
+ ):
+ download_image(self.URL, str(dst))
+ assert not dst.exists()
diff --git a/tests/onnx/test_utils.py b/tests/onnx/test_utils.py
index c191b7fca..dd7dfc04a 100644
--- a/tests/onnx/test_utils.py
+++ b/tests/onnx/test_utils.py
@@ -109,14 +109,14 @@ class TestONNXLoader:
ONNXLoader.download(url, file_path)
def test_fetch_repo_contents_success(self):
+ import json
import os
from unittest import mock
- with mock.patch("requests.get") as mock_get:
- mock_response = mock.Mock()
- mock_response.status_code = 200
- mock_response.json.return_value = [{"path": os.path.join("operators", "model.onnx")}]
- mock_get.return_value = mock_response
+ with mock.patch("kornia.onnx.utils.urlopen") as mock_urlopen:
+ mock_response = mock.MagicMock()
+ mock_response.read.return_value = json.dumps([{"path": os.path.join("operators", "model.onnx")}]).encode()
+ mock_urlopen.return_value.__enter__.return_value = mock_response
contents = ONNXLoader._fetch_repo_contents("operators")
assert contents == [{"path": os.path.join("operators", "model.onnx")}]
@@ -124,11 +124,11 @@ class TestONNXLoader:
def test_fetch_repo_contents_failure(self):
from unittest import mock
- with mock.patch("requests.get") as mock_get:
- mock_response = mock.Mock()
- mock_response.status_code = 404
- mock_get.return_value = mock_response
-
+ url = "https://huggingface.co/api/models/kornia/ONNX_models/tree/main/operators"
+ with mock.patch(
+ "kornia.onnx.utils.urlopen",
+ side_effect=urllib.error.HTTPError(url, 404, "Not Found", {}, None),
+ ):
with pytest.raises(ValueError, match="Failed to fetch repository contents"):
ONNXLoader._fetch_repo_contents("operators")
diff --git a/uv.lock b/uv.lock
index 28514366e..857fb59b6 100644
--- a/uv.lock
+++ b/uv.lock
@@ -823,7 +823,6 @@ dev = [
{ name = "pre-commit" },
{ name = "pytest" },
{ name = "pytest-timeout" },
- { name = "requests" },
{ name = "setuptools" },
{ name = "transformers" },
]
@@ -862,7 +861,6 @@ requires-dist = [
{ name = "pydata-sphinx-theme", marker = "extra == 'docs'", specifier = ">=0.21,<0.22" },
{ name = "pytest", marker = "extra == 'dev'" },
{ name = "pytest-timeout", marker = "extra == 'dev'" },
- { name = "requests", marker = "extra == 'dev'" },
{ name = "setuptools", marker = "extra == 'dev'" },
{ name = "sphinx", marker = "extra == 'docs'" },
{ name = "sphinx-autodoc-defaultargs", marker = "extra == 'docs'" },