Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions dandi/cli/cmd_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,17 @@
"With 'ask' (the default when --sync is passed without a value), prompt before "
"deleting. With 'do', delete without prompting.",
)
@click.option(
"--zarr",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should this be an explicit option or inferred from metadata like neuroglancer does? or a hint when the user/agent knows specifically to do so.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we infer already based on extensions IIRC; this is just an a new option for filter... I guess we might better call it that --zarr-filter (with --z-f shortcut)

"zarr_filters",
multiple=True,
metavar="FILTER",
help=(
"Filter entries within Zarr assets. Format: TYPE:PATTERN where TYPE "
"is 'glob', 'path', or 'regex'. Predefined: 'metadata'. "
"Can be specified multiple times (OR logic)."
),
)
@instance_option(
default=None,
help=(
Expand Down Expand Up @@ -165,6 +176,7 @@ def download(
format: DownloadFormat,
download_types: set[str],
sync: str | None,
zarr_filters: tuple[str, ...],
dandi_instance: str,
path_type: PathType,
preserve_tree: bool,
Expand Down Expand Up @@ -205,6 +217,7 @@ def download(
get_assets="assets" in download_types or preserve_tree,
preserve_tree=preserve_tree,
sync=SyncMode(sync) if sync is not None else None,
zarr_filters=zarr_filters,
path_type=path_type,
# develop_debug=develop_debug
)
19 changes: 18 additions & 1 deletion dandi/cli/cmd_ls.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,13 @@
from .base import devel_option, lgr, map_to_click_exceptions
from .formatter import JSONFormatter, JSONLinesFormatter, PYOUTFormatter, YAMLFormatter
from ..consts import ZARR_EXTENSIONS, metadata_all_fields
from ..dandiarchive import DandisetURL, _dandi_url_parser, parse_dandi_url
from ..dandiapi import BaseRemoteZarrAsset
from ..dandiarchive import (
AssetZarrEntryURL,
DandisetURL,
_dandi_url_parser,
parse_dandi_url,
)
from ..dandiset import Dandiset
from ..misctypes import Digest
from ..support.pyout import PYOUT_SHORT_NAMES, PYOUT_SHORT_NAMES_rev
Expand Down Expand Up @@ -143,6 +149,17 @@ def assets_gen():
if metadata in ("all", "assets"):
rec["metadata"] = a.get_raw_metadata()
yield rec
# If URL points into a zarr, also list entries
if isinstance(parsed_url, AssetZarrEntryURL) and isinstance(
a, BaseRemoteZarrAsset
):
for entry in a.iterfiles(
prefix=parsed_url.zarr_subpath
):
yield {
"path": f"{a.path}/{entry}",
"size": entry.size,
}
else:
# For now we support only individual files
yield path
Expand Down
41 changes: 27 additions & 14 deletions dandi/cli/cmd_upload.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
)
from ..consts import SyncMode
from ..exceptions import UploadValidationError
from ..upload import UploadExisting, UploadValidation
from ..upload import UploadExisting, UploadValidation, ZarrMode


@click.command()
Expand Down Expand Up @@ -58,6 +58,16 @@
default="require",
show_default=True,
)
@click.option(
"--zarr-mode",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

same comment here. we are increasing the CLI surface and should ask if these should be there or inferred.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

and the same reply here: it is not about the fact that we are dealing with zarr, but rather an option specific if working with zarr(s). Let's also add shortcut --z-m

type=click.Choice(list(ZarrMode)),
default="full",
help=(
"Zarr sync mode: 'full' (default) syncs completely; "
"'patch' uploads/updates without deleting remote files."
),
show_default=True,
)
@click.argument("paths", nargs=-1) # , type=click.Path(exists=True, dir_okay=False))
# &
# Development options: Set DANDI_DEVEL for them to become available
Expand Down Expand Up @@ -85,6 +95,7 @@ def upload(
dandi_instance: str,
existing: UploadExisting,
validation: UploadValidation,
zarr_mode: ZarrMode,
# Development options should come as kwargs
allow_any_path: bool = False,
upload_dandiset_metadata: bool = False,
Expand Down Expand Up @@ -120,19 +131,21 @@ def upload(
validation_companion_path(ctx.obj.logfile) if ctx.obj is not None else None
)


try:
upload_(
paths,
existing=existing,
validation=validation,
dandi_instance=dandi_instance,
allow_any_path=allow_any_path,
upload_dandiset_metadata=upload_dandiset_metadata,
devel_debug=devel_debug,
jobs=jobs,
jobs_per_file=jobs_per_file,
sync=SyncMode(sync) if sync is not None else None,
validation_log_path=companion,
)
upload_(
paths,
existing=existing,
validation=validation,
dandi_instance=dandi_instance,
allow_any_path=allow_any_path,
upload_dandiset_metadata=upload_dandiset_metadata,
devel_debug=devel_debug,
jobs=jobs,
jobs_per_file=jobs_per_file,
sync=SyncMode(sync) if sync is not None else None,
zarr_mode=zarr_mode,
validation_log_path=companion,
)
except UploadValidationError as exc:
raise click.ClickException(str(exc))
7 changes: 7 additions & 0 deletions dandi/cli/tests/test_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ def test_download_defaults(mocker):
get_assets=True,
preserve_tree=False,
sync=None,
zarr_filters=(),
path_type=PathType.EXACT,
)

Expand All @@ -44,6 +45,7 @@ def test_download_all_types(mocker):
get_assets=True,
preserve_tree=False,
sync=None,
zarr_filters=(),
path_type=PathType.EXACT,
)

Expand All @@ -63,6 +65,7 @@ def test_download_metadata_only(mocker):
get_assets=False,
preserve_tree=False,
sync=None,
zarr_filters=(),
path_type=PathType.EXACT,
)

Expand All @@ -82,6 +85,7 @@ def test_download_assets_only(mocker):
get_assets=True,
preserve_tree=False,
sync=None,
zarr_filters=(),
path_type=PathType.EXACT,
)

Expand Down Expand Up @@ -117,6 +121,7 @@ def test_download_gui_instance_in_dandiset(mocker, tmp_path, monkeypatch):
get_assets=True,
preserve_tree=False,
sync=None,
zarr_filters=(),
path_type=PathType.EXACT,
)

Expand Down Expand Up @@ -144,6 +149,7 @@ def test_download_api_instance_in_dandiset(mocker, tmp_path, monkeypatch):
get_assets=True,
preserve_tree=False,
sync=None,
zarr_filters=(),
path_type=PathType.EXACT,
)

Expand All @@ -170,6 +176,7 @@ def test_download_url_instance_match(mocker):
get_assets=True,
preserve_tree=False,
sync=None,
zarr_filters=(),
path_type=PathType.EXACT,
)

Expand Down
91 changes: 85 additions & 6 deletions dandi/dandiarchive.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
REDIRECT_HEAD_TIMEOUT,
RETRY_STATUSES,
VERSION_REGEX,
ZARR_EXTENSIONS,
DandiInstance,
known_instances,
)
Expand Down Expand Up @@ -446,6 +447,72 @@ def get_assets(
)


def split_zarr_location(location: str) -> tuple[str, str] | None:
"""Split a location into ``(asset_path, zarr_subpath)`` if it crosses a zarr boundary.

Scans path components for segments ending with a Zarr extension
(``.zarr``, ``.ngff``). If found **and** there are remaining components
after the boundary, returns the split; otherwise returns ``None``.

Parameters
----------
location : str
A POSIX-style path, e.g. ``"sub-1/file.ome.zarr/0/0/0"``.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

zarr doesn't have to have a / separator. a local zarr could have been generated with a different separator (e.g. zarr/0.0.0) or sharded.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if sharded -- don't we upload it "as is" with all its shardiness?

it is a new info for me and I guess refers to dimension_separator in v2 and now chunk_key_encoding in v3? (docs: https://zarr.readthedocs.io/en/v3.1.0/api/zarr/)

good to know but I wonder if that is an issue bigger than this "docstring fix" e.g.

likely worth a concerted effort to support such ones (unless I am wrong and we already do). Pragmatically, does any of the actively working with DANDI groups use alternative separators @satra @kabilar ? I think worth a separate issue, and if you see what to change here specifically -- please leave a suggestion @satra


Returns
-------
tuple[str, str] | None
``(asset_path, zarr_subpath)`` when a zarr boundary with a subpath
is detected, otherwise ``None``.

Examples
--------
>>> split_zarr_location("sub-1/file.ome.zarr/0/0/0")
('sub-1/file.ome.zarr', '0/0/0')
>>> split_zarr_location("sub-1/file.ome.zarr") # no subpath
>>> split_zarr_location("sub-1/file.nwb") # no zarr extension
"""
parts = [p for p in location.split("/") if p]
for i, part in enumerate(parts):
if any(part.endswith(ext) for ext in ZARR_EXTENSIONS):
asset_path = "/".join(parts[: i + 1])
zarr_subpath = "/".join(parts[i + 1 :])
return (asset_path, zarr_subpath) if zarr_subpath else None
return None


@dataclass
class AssetZarrEntryURL(SingleAssetURL):
"""Parsed from a URL that points into entries within a Zarr asset.

For example, ``dandi://dandi/000108/sub-1/file.ome.zarr/0/0/0`` would
produce ``asset_path="sub-1/file.ome.zarr"`` and ``zarr_subpath="0/0/0"``.
"""

asset_path: str # e.g., "sub-1/file.ome.zarr"
zarr_subpath: str # e.g., "0/0/0"

def get_assets(
self, client: DandiAPIClient, order: str | None = None, strict: bool = False
) -> Iterator[BaseRemoteAsset]:
"""Yield the zarr asset whose path equals ``asset_path``.

If the asset does not exist, a `NotFoundError` is raised when
``strict`` is true; otherwise nothing is yielded.
"""
try:
dandiset = self.get_dandiset(client, lazy=not strict)
assert dandiset is not None
dandiset.version_id # Force version evaluation
except NotFoundError:
if strict:
raise
else:
return
with _maybe_strict(strict):
yield dandiset.get_asset_by_path(self.asset_path)


@dataclass
class AssetFolderURL(MultiAssetURL):
"""
Expand Down Expand Up @@ -846,12 +913,24 @@ def parse(
path=location,
)
else:
parsed_url = AssetItemURL(
instance=instance,
dandiset_id=dandiset_id,
version_id=version_id,
path=location,
)
# Check if location crosses a zarr boundary
zarr_split = split_zarr_location(location)
if zarr_split is not None:
asset_path, zarr_subpath = zarr_split
parsed_url = AssetZarrEntryURL(
instance=instance,
dandiset_id=dandiset_id,
version_id=version_id,
asset_path=asset_path,
zarr_subpath=zarr_subpath,
)
else:
parsed_url = AssetItemURL(
instance=instance,
dandiset_id=dandiset_id,
version_id=version_id,
path=location,
)
elif asset_id:
if dandiset_id is None:
parsed_url = BaseAssetIDURL(instance=instance, asset_id=asset_id)
Expand Down
Loading
Loading