π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(io): load a sample download from its own temporary file before publishing it (#5853)
Dmytro Mishkindea669d9c156
diff --git a/changelog.d/5808.breaking.md b/changelog.d/5808.breaking.mdindex 084dae2ca..9ce1650fc 100644--- a/changelog.d/5808.breaking.md+++ b/changelog.d/5808.breaking.md@@ -12,5 +12,5 @@ where kornia-rs raised a `TypeError`. Writing into a directory that does not exithe directory, and writing under a path that is a file raises `NotADirectoryError`; both used to raise a bare`Exception`. `get_sample_images` caches downloads under `<kornia_config.hub_cache_dir>/images` by default instead ofa hard-coded `.kornia_hub/images`; the two are the same path unless `hub_cache_dir` is changed. A download that is not-an image raises `ValueError` naming the cached file, which is deleted, where it raised `PIL.UnidentifiedImageError`, an-`OSError`, so an `except OSError` clause no longer catches it.+an image raises `ValueError` and is not cached, where it raised `PIL.UnidentifiedImageError`, an `OSError`, so an+`except OSError` clause no longer catches it.diff --git a/kornia/io/sample.py b/kornia/io/sample.pyindex f8e4b6bf4..ab5881fa4 100644--- a/kornia/io/sample.py+++ b/kornia/io/sample.py@@ -21,7 +21,7 @@ import contextlibimport loggingimport osimport uuid-from typing import Any, List, Optional, Tuple, Union+from typing import Any, Callable, List, Optional, Tuple, Unionfrom urllib.parse import urlparsefrom urllib.request import urlopen@@ -51,24 +51,37 @@ def download_image(url: str, save_to: str) -> None:Each call writes the bytes to a temporary file of its own next to ``save_to`` and renames it onto ``save_to`` onlyonce the write is complete, removing it if the write fails. An interrupted download therefore never leaves apartial file at ``save_to``, and concurrent downloads of the same file each leave a complete copy there. Windows- cannot replace a file that is open, for example one that a concurrent call has just put there and is reading; the- later call keeps that copy only if its bytes match the download and removes its own temporary file. A refused- replacement with a missing, unreadable, or different destination still raises the replacement error.+ cannot replace a file that is open, for example one that another call is reading; a call whose replacement is+ refused keeps the copy already there only if its bytes match the download, and removes its own temporary file. A+ refused replacement with a missing, unreadable, or different destination still raises the replacement error.Args:url: The URL of the image to download.save_to: The file path where the downloaded image will be saved.+ """+ _download(url, save_to)+++def _download(url: str, save_to: str, load: Optional[Callable[[str], torch.Tensor]] = None) -> Optional[torch.Tensor]:+ """Download ``url`` to ``save_to`` as :func:`download_image` does; return ``load`` of the download, or ``None``.++ ``load`` reads the call's own temporary file before it is renamed onto ``save_to``, so the call does not load+ ``save_to``, which a concurrent call may be replacing (Windows refuses to open a file while it is replaced). A body+ that ``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: 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)- part = f"{save_to}.{uuid.uuid4().hex}.part"+ # creates the file with the usual permissions (tempfile.mkstemp would make the cached image private, 0o600).+ # A file to load ends with the destination's extension, which load_image picks its decoder by.+ suffix = os.path.splitext(save_to)[1] if load is not None else ""+ part = f"{save_to}.{uuid.uuid4().hex}.part{suffix}"try:with open(part, "xb") as f:f.write(data)+ image = None if load is None else load(part)try:os.replace(part, save_to)except PermissionError:@@ -86,6 +99,7 @@ def download_image(url: str, save_to: str) -> None:with contextlib.suppress(FileNotFoundError):os.remove(part)raise+ return imagedef get_sample_images(@@ -112,8 +126,9 @@ def get_sample_images(download: Whether to download the images if they are not already cached. Defaults to True.cache_dir: The directory where the downloaded images will be cached.Defaults to ``<kornia_config.hub_cache_dir>/images``, relative to the working directory unless configured- otherwise. Created when an image has to be downloaded. A downloaded file that does not load as an image is- deleted before the error propagates, so it is not cached.+ otherwise. Created when an image has to be downloaded. A download is loaded from a temporary file of its+ own before it is renamed into the cache, so a download that does not load as an image never reaches the+ cache: its temporary file is removed and the error propagates.as_list: if to keep the output as a list. If None and `resize` is None, the output will be a list.If None and `resize` is not None, the output will be a single tensor.divisible_factor:@@ -132,7 +147,7 @@ def get_sample_images(cache_dir = os.path.join(kornia_config.hub_cache_dir, "images")tensors = []for path in paths:- downloaded = False+ img_tensor: Optional[torch.Tensor] = Noneurl = urlparse(path)if url.scheme in ("http", "https"):name = os.path.basename(url.path) # the cache file is named without the URL's query or fragment@@ -142,20 +157,15 @@ def get_sample_images(if not os.path.exists(fname) and download:os.makedirs(cache_dir, exist_ok=True)logging.info(f"Downloading `{path}` to `{fname}`.")- download_image(path, fname)- downloaded = True+ img_tensor = _download(path, fname, load_image)elif not os.path.exists(fname) and not download:logging.error(f"Image `{path}` not found at `{fname}`. You may want to set `download=True` to download it.")else:fname = path- try:- img_tensor = load_image(fname)- except Exception:- if downloaded:- os.remove(fname) # a body that is not an image must not stay in the cache- raise+ if img_tensor is None:+ img_tensor = load_image(fname) # a local file or a cached copy; a failure here deletes nothingif resize is not None:img_tensor = kornia.geometry.resize(img_tensor, resize, **kwargs)if divisible_factor is not None:diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.pyindex 07e1b54a5..0f54c565a 100644--- a/tests/io/test_io_image.py+++ b/tests/io/test_io_image.py@@ -666,8 +666,12 @@ class TestSampleImages:mock_urlopen.assert_not_called()assert not cache.exists()- @pytest.mark.parametrize("refuse_replacing_a_file", [False, True], ids=["posix_replace", "windows_replace"])- def test_concurrent_downloads_of_the_same_image_both_succeed(self, tmp_path: Path, refuse_replacing_a_file) -> None:+ @pytest.mark.parametrize(+ "windows",+ [None, "refuses_replacing_an_open_file", "refuses_reading_a_file_being_replaced"],+ ids=["posix_replace", "windows_replace", "windows_read_during_replace"],+ )+ def test_concurrent_downloads_of_the_same_image_both_succeed(self, tmp_path: Path, windows) -> None:import osimport threadingfrom concurrent.futures import ThreadPoolExecutor@@ -682,22 +686,46 @@ class TestSampleImages:cache = tmp_path / "cache"both_written = threading.Barrier(2, timeout=10)one_replace_at_a_time = threading.Lock()+ replacing = set() # the threads whose os.replace has been called and has not returned yet+ a_call_moved_on = threading.Event() # a call has returned or raised, or a read of the cache file was refusedreal_replace = os.replace+ real_open = opendef replace_after_both_writes(src, dst):- both_written.wait() # both calls have missed the cache and finished writing before either replaces- with one_replace_at_a_time:- if refuse_replacing_a_file and os.path.exists(dst):- # Windows refuses to replace a file that the call which put it there is reading- raise PermissionError(13, "Access is denied", dst)- return real_replace(src, dst)+ replacing.add(threading.get_ident())+ try:+ both_written.wait() # both calls have missed the cache and finished writing before either replaces+ with one_replace_at_a_time:+ if windows == "refuses_replacing_an_open_file" and os.path.exists(dst):+ # Windows refuses to replace a file that another call has open+ raise PermissionError(13, "Access is denied", dst)+ if windows == "refuses_reading_a_file_being_replaced" and os.path.exists(dst):+ a_call_moved_on.wait(timeout=10) # this replace is still in flight while the other call goes on+ return real_replace(src, dst)+ finally:+ replacing.discard(threading.get_ident())++ def open_refused_while_another_call_replaces(path, mode="r", *args, **kwargs):+ if (+ windows == "refuses_reading_a_file_being_replaced"+ and Path(path) == cache / "same.png"+ and replacing - {threading.get_ident()}+ ):+ a_call_moved_on.set()+ # Windows: opening a file that another call is replacing fails with access denied+ raise PermissionError(13, "Permission denied", str(path))+ return real_open(path, mode, *args, **kwargs)def fetch():- return get_sample_images(paths=["https://example.invalid/x/same.png"], cache_dir=str(cache))[0]+ try:+ return get_sample_images(paths=["https://example.invalid/x/same.png"], cache_dir=str(cache))[0]+ finally:+ a_call_moved_on.set()with (mock.patch("kornia.io.sample.urlopen") as mock_urlopen,mock.patch("kornia.io.sample.os.replace", replace_after_both_writes),+ mock.patch("kornia.io.io.open", open_refused_while_another_call_replaces, create=True),ThreadPoolExecutor(max_workers=2) as pool,):mock_urlopen.return_value.__enter__.return_value.read.return_value = payload@@ -718,7 +746,28 @@ class TestSampleImages:mock_urlopen.return_value.__enter__.return_value.read.return_value = b"<html>not found</html>"with pytest.raises(ValueError, match=re.escape("sample.png")):get_sample_images(paths=["https://example.invalid/sample.png"], cache_dir=str(cache))- assert not (cache / "sample.png").exists()+ assert list(cache.iterdir()) == [] # neither the cache file nor the temporary file++ def test_a_download_that_is_not_an_image_leaves_another_calls_copy_in_place(self, tmp_path: Path) -> None:+ from unittest import mock++ from kornia.io import get_sample_images++ image = create_random_img8_torch(4, 5, 3)+ source = tmp_path / "source.png"+ write_image(source, image)+ cache = tmp_path / "cache"++ def body_read_while_another_call_publishes():+ (cache / "same.png").write_bytes(source.read_bytes()) # a call that also missed the cache publishes first+ return b"<html>not found</html>"++ with mock.patch("kornia.io.sample.urlopen") as mock_urlopen:+ mock_urlopen.return_value.__enter__.return_value.read.side_effect = body_read_while_another_call_publishes+ with pytest.raises(ValueError, match=re.escape("same.png")):+ get_sample_images(paths=["https://example.invalid/x/same.png"], cache_dir=str(cache))+ assert sorted(p.name for p in cache.iterdir()) == ["same.png"] # no temporary file is left behind+ assert (cache / "same.png").read_bytes() == source.read_bytes()class TestDownloadImage: