-
Notifications
You must be signed in to change notification settings - Fork 33
Populate per-asset dataStandard for BIDS, HED, NWB, and extensions #1811
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
Open
yarikoptic
wants to merge
8
commits into
master
Choose a base branch
from
hed
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
bad5ad0
feat: populate per-asset dataStandard for BIDS, HED, NWB, and OME/NGFF
yarikoptic 9d5ea64
feat: extract NWB extensions and HED library schemas into dataStandard
yarikoptic 1cd1d6a
chore: git ignore uv.lock
yarikoptic 7dfde13
refactor: centralize dandischema compat guard as _SCHEMA_BAREASSET_HA…
yarikoptic dcb03b4
refactor: move imports to top level, document import policy in CLAUDE.md
yarikoptic 7170ec3
fix: guard hed_standard import for compat with released dandischema
yarikoptic 4f7d154
fix: resolve lint (E402) and typing errors for dandischema compat
yarikoptic 279c297
Extract NWB spec version into dataStandard
bendichter 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -16,3 +16,4 @@ sandbox/ | |
| venv/ | ||
| venvs/ | ||
| .DS_Store | ||
| uv.lock | ||
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 |
|---|---|---|
|
|
@@ -3,15 +3,32 @@ | |
| from collections import defaultdict | ||
| from dataclasses import dataclass, field | ||
| from datetime import datetime | ||
| import json | ||
| from pathlib import Path | ||
| from threading import Lock | ||
| import weakref | ||
|
|
||
| from dandischema.models import BareAsset | ||
| from dandischema.models import ( | ||
| BareAsset, | ||
| StandardsType, | ||
| bids_standard, | ||
| ome_ngff_standard, | ||
| ) | ||
|
|
||
| import dandi | ||
| from dandi.bids_validator_deno import bids_validate | ||
|
|
||
| from .bases import GenericAsset, LocalFileAsset, NWBAsset | ||
| from .bases import ( | ||
| _SCHEMA_BAREASSET_HAS_DATASTANDARD, | ||
| GenericAsset, | ||
| LocalFileAsset, | ||
| NWBAsset, | ||
| ) | ||
|
|
||
| if _SCHEMA_BAREASSET_HAS_DATASTANDARD: | ||
| from dandischema.models import hed_standard # type: ignore[attr-defined] | ||
| else: | ||
| hed_standard = None # type: ignore[assignment] | ||
| from .zarr import ZarrAsset | ||
| from ..consts import ZARR_MIME_TYPE, dandiset_metadata_file | ||
| from ..metadata.core import add_common_metadata, prepare_metadata | ||
|
|
@@ -23,10 +40,32 @@ | |
| ValidationResult, | ||
| ) | ||
|
|
||
| lgr = dandi.get_logger() | ||
|
|
||
| BIDS_ASSET_ERRORS = ("BIDS.NON_BIDS_PATH_PLACEHOLDER",) | ||
| BIDS_DATASET_ERRORS = ("BIDS.MANDATORY_FILE_MISSING_PLACEHOLDER",) | ||
|
|
||
|
|
||
| def _add_standard( | ||
|
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. line 542 of bases appears to have similar logic |
||
| metadata: BareAsset, | ||
| standard_dict: dict, | ||
| version: str | None = None, | ||
| ) -> None: | ||
| """Add a data standard to asset metadata if the field is available.""" | ||
| if not _SCHEMA_BAREASSET_HAS_DATASTANDARD: | ||
| return | ||
| kwargs = dict(standard_dict) | ||
| if version: | ||
| kwargs["version"] = version | ||
| standard = StandardsType(**kwargs) | ||
| # TODO: use metadata.dataStandard directly once min dandischema >= 0.12.2 | ||
| cur = getattr(metadata, "dataStandard", None) | ||
| if cur is None: | ||
| setattr(metadata, "dataStandard", [standard]) | ||
| elif standard not in cur: | ||
| cur.append(standard) | ||
|
|
||
|
|
||
| @dataclass | ||
| class BIDSDatasetDescriptionAsset(LocalFileAsset): | ||
| """ | ||
|
|
@@ -192,7 +231,48 @@ | |
| assert self._dataset_errors is not None | ||
| return self._dataset_errors.copy() | ||
|
|
||
| # get_metadata(): inherit use of default metadata from LocalFileAsset | ||
| def get_metadata( | ||
| self, | ||
| digest: Digest | None = None, | ||
| ignore_errors: bool = True, | ||
| ) -> BareAsset: | ||
| metadata = super().get_metadata(digest=digest, ignore_errors=ignore_errors) | ||
| try: | ||
| with open(self.filepath) as f: | ||
| desc = json.load(f) | ||
| except (OSError, json.JSONDecodeError) as e: | ||
| lgr.warning("Failed to read %s: %s", self.filepath, e) | ||
| _add_standard(metadata, bids_standard) | ||
| return metadata | ||
| _add_standard(metadata, bids_standard, version=desc.get("BIDSVersion")) | ||
| if hed_standard and (hed_version := desc.get("HEDVersion")): | ||
| # HEDVersion can be a string or list. | ||
| # List form: ["8.2.0", "sc:1.0.0"] where first element is base | ||
| # HED version and subsequent "prefix:version" entries are library | ||
| # schemas recorded as extensions. | ||
| if isinstance(hed_version, list): | ||
| version = hed_version[0] if hed_version else None | ||
| library_entries = hed_version[1:] | ||
| else: | ||
| version = hed_version | ||
| library_entries = [] | ||
| kwargs: dict = dict(hed_standard) | ||
| if version: | ||
| kwargs["version"] = version | ||
| if library_entries: | ||
| extensions = [] | ||
| for entry in library_entries: | ||
| # Format is "prefix:version" (e.g. "sc:1.0.0") | ||
| if ":" in str(entry): | ||
| lib_name, lib_ver = str(entry).split(":", 1) | ||
| else: | ||
| lib_name, lib_ver = str(entry), None | ||
| ext = StandardsType(name=lib_name, version=lib_ver) # type: ignore[call-arg] | ||
| extensions.append(ext.model_dump(mode="json", exclude_none=True)) | ||
| if extensions: | ||
| kwargs["extensions"] = extensions | ||
| _add_standard(metadata, kwargs) | ||
| return metadata | ||
|
|
||
|
|
||
| @dataclass | ||
|
|
@@ -312,6 +392,8 @@ | |
| add_common_metadata(metadata, self.filepath, start_time, end_time, digest) | ||
| metadata.path = self.path | ||
| metadata.encodingFormat = ZARR_MIME_TYPE | ||
| if Path(self.path).suffixes == [".ome", ".zarr"]: | ||
| _add_standard(metadata, ome_ngff_standard) | ||
| return metadata | ||
|
|
||
|
|
||
|
|
||
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.
Check notice
Code scanning / CodeQL
Cyclic import Note
Copilot Autofix
AI 4 days ago
In general, the clean way to break an import cycle is to avoid having two modules that directly depend on each other’s runtime definitions. For class hierarchies, this usually means either (1) moving shared abstractions into a third, lower-level module, or (2) converting some imports to type-only imports using
typing.TYPE_CHECKING, so the runtime import no longer occurs.Within
dandi/files/bids.py, we can break the cycle without changing behavior by changing how we import from.bases. The key is to avoid importingGenericAsset(a base abstraction that likely needs to stay independent), while still ensuring that any references to it remain valid for static typing. Since Python 3.7+ withfrom __future__ import annotationssupports postponed evaluation of annotations, we can safely importGenericAssetonly underTYPE_CHECKING. At runtime, code inbids.pydoes not need theGenericAssetname unless it is used directly (e.g., forisinstancechecks); if it is only used in type hints, moving it underTYPE_CHECKINGremoves the cycle.Concretely, in
dandi/files/bids.pywe will:LocalFileAssetandNWBAssetfrom.basesat runtime.GenericAssetat runtime.TYPE_CHECKINGguarded import forGenericAssetso type checkers still see it.This involves:
from typing import TYPE_CHECKINGto the imports..basesimport block so thatGenericAssetis no longer in the runtime import.if TYPE_CHECKING:block that importsGenericAssetfrom.basesfor typing only.No functionality changes for executed code, but the runtime import graph changes so that
bids.pyno longer pulls inGenericAssetduring module initialization, thus breaking or at least relaxing the cycle.