-
Notifications
You must be signed in to change notification settings - Fork 7
Fix datasets import failing by developing standalone dataset system #111
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 4 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
aa84f45
Refactor dataset handling in _dataset.py
marcovarrone aa683cc
Enhance Figshare URL normalization and improve error handling in _dat…
marcovarrone dbf29b6
Update dependencies and bump to 0.3.6
marcovarrone 2dd3f8b
Update torchgmm dependency version to 0.1.4 in pyproject.toml
marcovarrone 0c680f3
Update Python versions in GitHub Actions workflow to 3.11 and 3.13
marcovarrone 6895994
Remove comment
marcovarrone 9e7cc28
Add functionality to download and validate codex_adata fixture in tests
marcovarrone 27cd77d
Increase timeout for codex download and ensure re-download on failure
marcovarrone 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,18 +1,120 @@ | ||
| from copy import copy | ||
| from __future__ import annotations | ||
|
|
||
| from squidpy.datasets._utils import AMetadata | ||
| import os | ||
| from dataclasses import dataclass | ||
| from pathlib import Path | ||
| from urllib.error import HTTPError, URLError | ||
| from urllib.parse import urlparse | ||
| from urllib.request import Request, urlopen | ||
|
|
||
| _codex_mouse_spleen = AMetadata( | ||
| import anndata as ad | ||
|
|
||
| try: | ||
| from tqdm.auto import tqdm | ||
| except ImportError: # pragma: no cover - optional dependency | ||
| tqdm = None | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class DatasetMetadata: | ||
| name: str | ||
| doc_header: str | ||
| shape: tuple[int, int] | ||
| url: str | ||
| filename: str | ||
|
|
||
|
|
||
| _codex_mouse_spleen = DatasetMetadata( | ||
| name="codex_mouse_spleen", | ||
| doc_header="Pre-processed CODEX dataset of mouse spleen from `Goltsev et al " | ||
| "<https://doi.org/10.1016/j.cell.2018.07.010>`__.", | ||
| shape=(707474, 29), | ||
| url="https://figshare.com/ndownloader/files/38538101", | ||
| url="https://ndownloader.figshare.com/files/38538101", | ||
| filename="codex_mouse_spleen.h5ad", | ||
| ) | ||
|
|
||
| for name, var in copy(locals()).items(): | ||
| if isinstance(var, AMetadata): | ||
| var._create_function(name, globals()) | ||
|
|
||
| def _default_datasets_dir() -> Path: | ||
| return Path(os.environ.get("CELLCHARTER_DATA_DIR", Path.home() / ".cache" / "cellcharter" / "datasets")) | ||
|
|
||
|
|
||
| def _is_hdf5_file(path: Path) -> bool: | ||
| if not path.exists() or path.stat().st_size < 8: | ||
| return False | ||
| with path.open("rb") as input_file: | ||
| return input_file.read(8) == b"\x89HDF\r\n\x1a\n" | ||
|
|
||
|
|
||
| def _normalize_figshare_url(url: str) -> str: | ||
| parsed = urlparse(url) | ||
| if parsed.netloc == "figshare.com" and parsed.path.startswith("/ndownloader/files/"): | ||
| # Strip the /ndownloader prefix, keeping only /files/... | ||
| return f"https://ndownloader.figshare.com{parsed.path.removeprefix('/ndownloader')}" | ||
| return url | ||
|
|
||
|
|
||
| def _download_file(url: str, destination: Path) -> None: | ||
| destination.parent.mkdir(parents=True, exist_ok=True) | ||
| tmp_destination = destination.with_suffix(f"{destination.suffix}.part") | ||
|
|
||
| request = Request(_normalize_figshare_url(url), headers={"User-Agent": "cellcharter-datasets"}) | ||
| progress = None | ||
| try: | ||
| with urlopen(request, timeout=60) as response, tmp_destination.open("wb") as output: | ||
| content_length = response.headers.get("Content-Length") | ||
| total = int(content_length) if content_length and content_length.isdigit() else None | ||
| if tqdm is not None: | ||
| progress = tqdm(total=total, unit="B", unit_scale=True, desc=f"Downloading {destination.name}") | ||
|
|
||
| chunk_size = 1024 * 1024 | ||
| while True: | ||
| chunk = response.read(chunk_size) | ||
| if not chunk: | ||
| break | ||
| output.write(chunk) | ||
| if progress is not None: | ||
| progress.update(len(chunk)) | ||
| except Exception as error: # noqa: B902 | ||
| if tmp_destination.exists(): | ||
| tmp_destination.unlink() | ||
| if isinstance(error, (HTTPError, URLError)): | ||
| raise RuntimeError(f"Failed to download dataset from {url}.") from error | ||
| raise error | ||
| finally: | ||
| if progress is not None: | ||
| progress.close() | ||
|
|
||
| if not _is_hdf5_file(tmp_destination): | ||
| tmp_destination.unlink(missing_ok=True) | ||
| raise RuntimeError( | ||
| f"Downloaded file from {url} is not a valid HDF5 file. " "Please check network access and dataset URL." | ||
| ) | ||
|
|
||
| tmp_destination.replace(destination) | ||
|
|
||
|
|
||
| def _resolve_dataset_path(metadata: DatasetMetadata, path: str | Path | None = None) -> Path: | ||
| base_dir = _default_datasets_dir() if path is None else Path(path) | ||
| if base_dir.suffix: | ||
| return base_dir | ||
| return base_dir / metadata.filename | ||
|
|
||
|
|
||
| def _fetch_dataset_file( | ||
| metadata: DatasetMetadata, path: str | Path | None = None, force_download: bool = False | ||
| ) -> Path: | ||
| dataset_path = _resolve_dataset_path(metadata, path=path) | ||
| should_download = force_download or not dataset_path.exists() or not _is_hdf5_file(dataset_path) | ||
| if should_download: | ||
| dataset_path.unlink(missing_ok=True) | ||
| _download_file(metadata.url, dataset_path) | ||
| return dataset_path | ||
|
|
||
|
|
||
| def codex_mouse_spleen(path: str | Path | None = None, force_download: bool = False) -> ad.AnnData: | ||
| """Pre-processed CODEX dataset of mouse spleen from `Goltsev et al <https://doi.org/10.1016/j.cell.2018.07.010>`__.""" | ||
| dataset_path = _fetch_dataset_file(_codex_mouse_spleen, path=path, force_download=force_download) | ||
| return ad.read_h5ad(dataset_path) | ||
|
|
||
|
|
||
| __all__ = ["codex_mouse_spleen"] # noqa: F822 | ||
| __all__ = ["codex_mouse_spleen"] |
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.