-
Notifications
You must be signed in to change notification settings - Fork 6
Use pooch for dataset downloads (#244) #251
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
5e53ad1
Use pooch for dataset downloads (#244)
eroell 2d0f450
Merge branch 'main' into feature/use-pooch-for-downloads
eroell 40bb779
Drop EHRDATA_DOWNLOAD_* retry env vars
eroell 93b789e
Drop retry params and filelock from downloader; force fresh CI download
eroell b95f3b2
Serialize same-path dataset tests onto one xdist worker
eroell e1470bf
Polish download output and fix physionet2019 full-dataset load
eroell 8b2866d
polish
eroell 4da2c1b
fix pr nr in changelog
eroell File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,30 +1,27 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import logging | ||
| import os | ||
| import shutil | ||
| import tempfile | ||
| import time | ||
| import warnings | ||
| from pathlib import Path, PurePath | ||
| from typing import Literal, get_args | ||
| from urllib.parse import urlparse | ||
|
|
||
| import requests | ||
| from filelock import FileLock | ||
| from requests.exceptions import RequestException | ||
| from rich.progress import Progress | ||
|
|
||
| from ehrdata._logger import logger | ||
|
|
||
| with warnings.catch_warnings(): | ||
| warnings.filterwarnings("ignore", message="IProgress not found") | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should we really do this?
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. an ugly warning is raised during import without this, since right now I use tqdm, instead of rich+ipywidgets |
||
| import pooch | ||
|
|
||
| pooch.get_logger().setLevel(logging.WARNING) | ||
|
|
||
| COMPRESSION_FORMATS = Literal["tar.gz", "gztar", "zip", "tar", "gz", "bz", "xz"] | ||
| COMPRESSION_FORMATS_LIST = list(get_args(COMPRESSION_FORMATS)) | ||
| RAW_FORMATS = Literal["csv", "txt", "parquet", "h5ad", "zarr"] | ||
| RAW_FORMATS_LIST = list(get_args(RAW_FORMATS)) | ||
|
|
||
| # Retry defaults. CI can override these via environment variables to fail fast instead of waiting through | ||
| # the full exponential backoff; regular users never need to set them. | ||
| DEFAULT_MAX_RETRIES = max(1, int(os.environ.get("EHRDATA_DOWNLOAD_MAX_RETRIES", "5"))) | ||
| DEFAULT_RETRY_DELAY = int(os.environ.get("EHRDATA_DOWNLOAD_RETRY_DELAY", "10")) | ||
|
|
||
|
|
||
| def _download( | ||
| url: str, | ||
|
|
@@ -36,11 +33,12 @@ def _download( | |
| *, | ||
| overwrite: bool = False, | ||
| timeout: int = 60, | ||
| max_retries: int = DEFAULT_MAX_RETRIES, | ||
| retry_delay: int = DEFAULT_RETRY_DELAY, | ||
| ) -> None | Path: # pragma: no cover | ||
| """Downloads a file irrespective of format. | ||
|
|
||
| The download itself, including retries and caching, is delegated to | ||
| `pooch <https://www.fatiando.org/pooch/>`_, in line with the scverse ecosystem. | ||
|
|
||
| Args: | ||
| url: URL to download. | ||
| output_filename: Name of the file to download. If not specified, the file name will be inferred from the URL. | ||
|
|
@@ -50,8 +48,6 @@ def _download( | |
| block_size: Block size for downloads in bytes. | ||
| overwrite: Whether to overwrite existing files. | ||
| timeout: Request timeout in seconds. | ||
| max_retries: Maximum number of download attempts before giving up. Defaults to 5. | ||
| retry_delay: Base delay in seconds between attempts (grows exponentially). Defaults to 10. | ||
| """ | ||
|
|
||
| def _sanitize_filename(filename: str) -> str: | ||
|
|
@@ -69,6 +65,7 @@ def _remove_archive_extension(filename: str) -> str: | |
| output_path = tempfile.gettempdir() | ||
|
|
||
| output_path = Path(output_path) | ||
| output_path.mkdir(parents=True, exist_ok=True) | ||
|
|
||
| url_filename = PurePath(urlparse(url).path).name | ||
| suffix = url_filename.split(".")[-1] | ||
|
|
@@ -83,83 +80,40 @@ def _remove_archive_extension(filename: str) -> str: | |
| file_ending = suffix | ||
|
|
||
| if file_ending in RAW_FORMATS_LIST: | ||
| download_dir = output_path | ||
| raw_data_output_path = output_path / output_filename | ||
| path_to_check = raw_data_output_path | ||
| elif file_ending in COMPRESSION_FORMATS_LIST: | ||
| tmpdir = tempfile.mkdtemp() | ||
| raw_data_output_path = Path(tmpdir) / output_filename | ||
| download_dir = Path(tempfile.mkdtemp()) | ||
| raw_data_output_path = download_dir / output_filename | ||
| path_to_check = output_path / _remove_archive_extension(output_filename) | ||
| else: | ||
| msg = f"Unknown file format: {file_ending}" | ||
| raise RuntimeError(msg) | ||
|
|
||
| lock_path = f"{path_to_check}.lock" | ||
| with FileLock(lock_path, timeout=600): | ||
| if path_to_check.exists(): | ||
| warning = f"File {path_to_check} already exists!" | ||
| if not overwrite: | ||
| return path_to_check | ||
| else: | ||
| logger.warning(f"{warning} Overwriting...") | ||
|
|
||
| temp_filename = f"{raw_data_output_path}.part" | ||
|
|
||
| retry_count = 0 | ||
| while retry_count < max_retries: | ||
| try: | ||
| headers = {"User-Agent": "ehrdata/1.0.0 (https://github.com/theislab/ehrdata)"} | ||
| head_response = requests.head(url, timeout=timeout, headers=headers) | ||
| head_response.raise_for_status() | ||
| content_length = int(head_response.headers.get("content-length", 0)) | ||
| free_space = shutil.disk_usage(output_path).free | ||
|
|
||
| if content_length > free_space: | ||
| msg = f"Insufficient disk space. Need {content_length} bytes, but only {free_space} available." | ||
| raise OSError(msg) | ||
|
|
||
| response = requests.get(url, stream=True, headers=headers, timeout=timeout) | ||
| response.raise_for_status() | ||
| total = int(response.headers.get("content-length", 0)) | ||
|
|
||
| with Progress(refresh_per_second=5) as progress: | ||
| task = progress.add_task("[red]Downloading...", total=total) | ||
| with Path(temp_filename).open("wb") as file: | ||
| for data in response.iter_content(block_size): | ||
| file.write(data) | ||
| progress.update(task, advance=len(data)) | ||
| progress.update(task, completed=total, refresh=True) | ||
|
|
||
| Path(temp_filename).replace(raw_data_output_path) | ||
|
|
||
| if file_ending in COMPRESSION_FORMATS_LIST: | ||
| shutil.unpack_archive(raw_data_output_path, output_path) | ||
|
|
||
| return path_to_check | ||
|
|
||
| except (OSError, RequestException) as e: | ||
| retry_count += 1 | ||
| if retry_count < max_retries: | ||
| # Exponential backoff: base delay * 2^(attempt-1) | ||
| backoff_delay = retry_delay * (2 ** (retry_count - 1)) | ||
| logger.warning( | ||
| f"Download attempt {retry_count}/{max_retries} failed: {e!s}. Retrying in {backoff_delay} seconds..." | ||
| ) | ||
| time.sleep(backoff_delay) | ||
| else: | ||
| # Final attempt failed: surface the error instead of silently returning a missing path. | ||
| logger.error(f"Download failed after {max_retries} attempts: {e!s}") | ||
| if Path(temp_filename).exists(): | ||
| Path(temp_filename).unlink(missing_ok=True) | ||
| raise | ||
|
|
||
| except Exception as e: | ||
| logger.error(f"Download failed: {e!s}") | ||
| if Path(temp_filename).exists(): | ||
| Path(temp_filename).unlink(missing_ok=True) | ||
| raise | ||
| finally: | ||
| if Path(temp_filename).exists(): | ||
| Path(temp_filename).unlink(missing_ok=True) | ||
| Path(lock_path).unlink(missing_ok=True) | ||
|
|
||
| return path_to_check | ||
| if path_to_check.exists(): | ||
| warning = f"File {path_to_check} already exists!" | ||
| if not overwrite: | ||
| return path_to_check | ||
| logger.warning(f"{warning} Overwriting...") | ||
| # pooch does not re-fetch an existing file when no hash is given, so remove it to force a download. | ||
| if raw_data_output_path.exists(): | ||
| raw_data_output_path.unlink() | ||
|
|
||
| pooch.retrieve( | ||
| url=url, | ||
| known_hash=None, | ||
| fname=output_filename, | ||
| path=str(download_dir), | ||
| downloader=pooch.HTTPDownloader( | ||
| progressbar=True, | ||
| chunk_size=block_size, | ||
| timeout=timeout, | ||
| headers={"User-Agent": "ehrdata/1.0.0 (https://github.com/theislab/ehrdata)"}, | ||
| ), | ||
| ) | ||
|
|
||
| if file_ending in COMPRESSION_FORMATS_LIST: | ||
| shutil.unpack_archive(raw_data_output_path, output_path) | ||
|
|
||
| return path_to_check | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We don't need tqdm as dependency because rich itself can already render the progressbar.
https://github.com/scverse/pertpy/blob/main/pertpy/data/_dataloader.py#L12
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Opted for a simpler progressbar with tqdm, and not rich
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Like this we need a new dependency tho and it's not necessary