diff --git a/dlccore/project/__init__.py b/dlccore/project/__init__.py new file mode 100644 index 0000000..c187ccb --- /dev/null +++ b/dlccore/project/__init__.py @@ -0,0 +1,12 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +"""Schema-driven, read-only DeepLabCut project inspection.""" diff --git a/dlccore/project/schemas/__init__.py b/dlccore/project/schemas/__init__.py new file mode 100644 index 0000000..d329f1d --- /dev/null +++ b/dlccore/project/schemas/__init__.py @@ -0,0 +1,10 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# diff --git a/dlccore/project/schemas/base/__init__.py b/dlccore/project/schemas/base/__init__.py new file mode 100644 index 0000000..9b027ac --- /dev/null +++ b/dlccore/project/schemas/base/__init__.py @@ -0,0 +1,28 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +from .resources import ( + DirectoryResourceKind, + FileResourceKind, + ProjectResource, + ResourceKind, + ResourceManagement, + UnknownResourceKind, +) + +__all__ = [ + "DirectoryResourceKind", + "FileResourceKind", + "ProjectResource", + "ResourceKind", + "ResourceManagement", + "UnknownResourceKind", +] diff --git a/dlccore/project/schemas/base/core.py b/dlccore/project/schemas/base/core.py new file mode 100644 index 0000000..203264d --- /dev/null +++ b/dlccore/project/schemas/base/core.py @@ -0,0 +1,139 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +import re +from pathlib import Path, PurePosixPath, PureWindowsPath +from typing import Annotated + +from pydantic import AfterValidator, BaseModel, ConfigDict, StringConstraints + + +class FrozenModel(BaseModel): + """Common behavior for all results and schema models. + + - Unexpected fields are forbidden + - Cannot be modified after creation + - Serializable via pydantic + - Can produce JSON + """ + + model_config = ConfigDict( + extra="forbid", + frozen=True, + ) + + +def path_anchor( + value: str | Path, +) -> str: + """Return the drive and root a path carries under either filesystem, or ``""``. + + ``Path`` takes the host filesystem, so a Windows drive is invisible on POSIX. + Both filesystems are asked, because a path is written on one platform and read on another. + """ + + text = str(value) + + for filesystem in (PureWindowsPath, PurePosixPath): + anchor = filesystem(text).anchor + + if anchor: + return anchor + + return "" + + +def is_absolute_path( + value: str | Path, +) -> bool: + r"""Return whether a path is absolute under either filesystem. + + Stricter than carrying an anchor: ``C:project`` and ``\\project`` are anchored but relative. + """ + + text = str(value) + + return PureWindowsPath(text).is_absolute() or PurePosixPath(text).is_absolute() + + +def reject_anchored_path( + value: Path, +) -> Path: + """Reject a path carrying a drive or a root, whatever the host. + + Raises: + ValueError: If the path is anchored under either filesystem. + """ + + anchor = path_anchor(value) + + if anchor: + raise ValueError(f"must be project-relative, but {str(value)!r} carries the anchor {anchor!r}") + + return value + + +ProjectRelativePath = Annotated[Path, AfterValidator(reject_anchored_path)] +Sha256Hex = Annotated[str, StringConstraints(pattern=r"^[0-9a-f]{64}$")] + + +def reject_non_segment(value: tuple[str | int, ...]) -> tuple[str | int, ...]: + r"""Reject problematic instance segments: empty, joined or anchored. + + ``..`` is user data, reported by validation rather than refused here, as for + ``ProjectRelativePath``. ``\`` and ``:`` are legal inside POSIX file names, so + the anchor is checked on the joined segments, under both filesystems. + + Raises: + ValueError: If a segment is empty or contains ``/``, or the segments carry a drive or root. + """ + + for segment in value: + if isinstance(segment, str) and (segment == "" or "/" in segment): + raise ValueError(f"{segment!r} is not one project-relative path segment") + + if value: + reject_anchored_path(Path("/".join(str(segment) for segment in value))) + + return value + + +# Project-relative path segments, then a logical node's key as ints (e.g. shuffle's 95, 2). +LayoutInstance = Annotated[tuple[str | int, ...], AfterValidator(reject_non_segment)] + + +def instance_from_path(path: Path) -> tuple[str, ...]: + """Return a project-relative path's segments, as a layout instance. + + Raises: + ValueError: If the path is anchored under either filesystem. + """ + + return reject_anchored_path(path).parts + + +_SCHEMA_ID = re.compile(r"dlc(\.[a-z0-9_]+)+") + + +def check_schema_id_format(value: str) -> str: + """Reject a malformed layout schema ID. Does not check if a declared node is named. + + Raises: + ValueError: If the ID is not ``dlc`` followed by dot-separated lowercase segments. + """ + + if _SCHEMA_ID.fullmatch(value) is None: + raise ValueError(f"{value!r} is not a layout schema ID of the form 'dlc.[....]'") + + return value + + +SchemaId = Annotated[str, AfterValidator(check_schema_id_format)] diff --git a/dlccore/project/schemas/base/probes.py b/dlccore/project/schemas/base/probes.py new file mode 100644 index 0000000..5b8c259 --- /dev/null +++ b/dlccore/project/schemas/base/probes.py @@ -0,0 +1,82 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +"""Typed filesystem probe vocabulary. + +A ``PathProbe`` records raw filesystem facts about one path: whether it is +missing, what kind of entry it is, and symlink-target details. It never +assigns validation findings, severity, remediation, or project-level +validity, those remain the responsibility of discovery and validation. +""" + +from __future__ import annotations + +from enum import Enum + +from pydantic import model_validator +from typing_extensions import Self + +from dlccore.project.schemas.base.core import FrozenModel +from dlccore.project.schemas.base.symlinks import SymlinkObservation + + +class FilesystemEntryKind(str, Enum): + """Observed kind of a directory entry itself (not its symlink target).""" + + FILE = "file" + DIRECTORY = "directory" + SYMLINK = "symlink" + OTHER = "other" + + +class PathProbeStatus(str, Enum): + """Outcome of attempting to observe one directory entry. + + Describes the entry only. A symlink target that could not be read is + recorded by ``SymlinkObservation.target_kind``, not here. + """ + + OBSERVED = "observed" + MISSING = "missing" + INACCESSIBLE = "inaccessible" + + +class PathProbe(FrozenModel): + """Read-only, schema-neutral observation of one filesystem path.""" + + status: PathProbeStatus + entry_kind: FilesystemEntryKind | None = None + symlink: SymlinkObservation | None = None + error_type: str | None = None + error_message: str | None = None + + @model_validator(mode="after") + def validate_probe_shape(self) -> Self: + """Enforce invariants between status, entry kind, and symlink details.""" + + if self.status == PathProbeStatus.MISSING and (self.entry_kind is not None or self.symlink is not None): + raise ValueError("A missing probe must not carry an entry kind or symlink details.") + + has_symlink_kind = self.entry_kind == FilesystemEntryKind.SYMLINK + has_symlink_details = self.symlink is not None + + if has_symlink_kind != has_symlink_details: + raise ValueError( + "A symlink probe must include SymlinkObservation details, and only a symlink probe may include them." + ) + + if self.status == PathProbeStatus.INACCESSIBLE and self.error_type is None: + raise ValueError("An inaccessible probe must retain structured failure information.") + + if self.status == PathProbeStatus.INACCESSIBLE and self.entry_kind is not None: + raise ValueError("An inaccessible probe must not carry an entry kind, the entry itself was not observed.") + + return self diff --git a/dlccore/project/schemas/base/resources.py b/dlccore/project/schemas/base/resources.py new file mode 100644 index 0000000..62c779f --- /dev/null +++ b/dlccore/project/schemas/base/resources.py @@ -0,0 +1,111 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +"""Basic project resource types. + +Vocabulary only. +""" + +from __future__ import annotations + +from enum import Enum + +from pydantic import model_validator +from typing_extensions import Self + +from dlccore.project.schemas.base.core import FrozenModel, ProjectRelativePath +from dlccore.project.schemas.base.symlinks import SymlinkObservation + + +class ResourceManagement(str, Enum): + """Describe whether DeepLabCut manages a resource or not.""" + + # DLC manages the resource (e.g., config.yaml) + MANAGED = "managed" + # DLC does not manage the resource, but knows about it (e.g. .napari-deeplabcut JSON metadata) + KNOWN_UNMANAGED = "known_unmanaged" + # DLC does not manage the resource and does not know about it + UNDETERMINED = "undetermined" + + +class DirectoryResourceKind(str, Enum): + # Project folder + PROJECT_ROOT = "project_root" + + # Videos + VIDEOS_DIRECTORY = "videos_directory" + + # Labeled data + LABELED_DATA_DIRECTORY = "labeled_data_directory" # hosts all labeled datasets + LABELED_DATASET = "labeled_dataset" # frames + labels + + # Extend later... + + # Unknown resources + UNKNOWN_DIRECTORY = "unknown_directory" + + +class FileResourceKind(str, Enum): + # Project config file + PROJECT_CONFIG = "project_config" + + # Videos + SOURCE_VIDEO = "source_video" + + # Labeled data + LABELED_FRAME = "labeled_frame" # image file + HUMAN_LABELS = "human_labels" # keypoints + MACHINE_LABELS = "machine_labels" # keypoints + NAPARI_DLC_METADATA = "napari_dlc_metadata" # JSON metadata for napari plugin + + # Unknown resources + UNKNOWN_FILE = "unknown_file" + + +class UnknownResourceKind(str, Enum): + """An entry with an unknown resource kind.""" + + UNKNOWN = "unknown" + + +ResourceKind = DirectoryResourceKind | FileResourceKind | UnknownResourceKind + + +class ProjectResource(FrozenModel): + """A single project resource, as observed on disk.""" + + project_relative_path: ProjectRelativePath + symlink: SymlinkObservation | None = None + kind: ResourceKind + management: ResourceManagement = ResourceManagement.MANAGED + + @model_validator(mode="after") + def validate_kind_and_management( + self, + ) -> Self: + """Ensure semantic kind and management status agree.""" + + unknown_kinds = { + FileResourceKind.UNKNOWN_FILE, + DirectoryResourceKind.UNKNOWN_DIRECTORY, + UnknownResourceKind.UNKNOWN, + } + has_unknown_kind = self.kind in unknown_kinds + has_undetermined_management = self.management == ResourceManagement.UNDETERMINED + + if has_unknown_kind != has_undetermined_management: + raise ValueError( + "Unknown resource kinds must use undetermined " + "management, and undetermined management may " + "only be used with an unknown resource kind." + ) + + return self diff --git a/dlccore/project/schemas/base/symlinks.py b/dlccore/project/schemas/base/symlinks.py new file mode 100644 index 0000000..29f40b3 --- /dev/null +++ b/dlccore/project/schemas/base/symlinks.py @@ -0,0 +1,35 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +from __future__ import annotations + +from enum import Enum +from pathlib import Path + +from dlccore.project.schemas.base.core import FrozenModel + + +class SymlinkTargetKind(str, Enum): + """Observed type of a symbolic-link target.""" + + FILE = "file" + DIRECTORY = "directory" + MISSING = "missing" + OTHER = "other" + INACCESSIBLE = "inaccessible" + + +class SymlinkObservation(FrozenModel): + """Read-only observation of one symbolic link and its target.""" + + raw_target: Path + absolute_target: Path + target_kind: SymlinkTargetKind diff --git a/tests/project/resources/test_res_invariants.py b/tests/project/resources/test_res_invariants.py new file mode 100644 index 0000000..8d1f175 --- /dev/null +++ b/tests/project/resources/test_res_invariants.py @@ -0,0 +1,93 @@ +# +# DeepLabCut Toolbox (deeplabcut.org) +# © A. & M.W. Mathis Labs +# https://github.com/DeepLabCut/dlccore +# +# Contributors: +# https://github.com/DeepLabCut/dlccore/graphs/contributors +# +# Licensed under GNU Lesser General Public License v3.0 +# + +from pathlib import Path + +import pytest +from pydantic import ValidationError + +from dlccore.project.schemas.base.resources import ( + DirectoryResourceKind, + FileResourceKind, + ProjectResource, + ResourceManagement, +) + + +@pytest.mark.parametrize( + ("kind", "management"), + [ + ( + FileResourceKind.SOURCE_VIDEO, + ResourceManagement.MANAGED, + ), + ( + FileResourceKind.NAPARI_DLC_METADATA, + ResourceManagement.KNOWN_UNMANAGED, + ), + ( + FileResourceKind.UNKNOWN_FILE, + ResourceManagement.UNDETERMINED, + ), + ( + DirectoryResourceKind.UNKNOWN_DIRECTORY, + ResourceManagement.UNDETERMINED, + ), + ], +) +def test_resource_kind_and_management_accept_coherent_combinations( + kind: FileResourceKind | DirectoryResourceKind, + management: ResourceManagement, +) -> None: + resource = ProjectResource( + project_relative_path=Path("resource"), + kind=kind, + management=management, + ) + + assert resource.kind == kind + assert resource.management == management + + +@pytest.mark.parametrize( + ("kind", "management"), + [ + ( + FileResourceKind.UNKNOWN_FILE, + ResourceManagement.MANAGED, + ), + ( + DirectoryResourceKind.UNKNOWN_DIRECTORY, + ResourceManagement.KNOWN_UNMANAGED, + ), + ( + FileResourceKind.SOURCE_VIDEO, + ResourceManagement.UNDETERMINED, + ), + ( + FileResourceKind.NAPARI_DLC_METADATA, + ResourceManagement.UNDETERMINED, + ), + ], +) +def test_resource_kind_and_management_reject_incoherent_combinations( + kind: FileResourceKind | DirectoryResourceKind, + management: ResourceManagement, +) -> None: + with pytest.raises( + ValidationError, + match=("Unknown resource kinds must use undetermined management"), + ): + ProjectResource( + project_relative_path=Path("resource"), + kind=kind, + management=management, + )