Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
12 changes: 12 additions & 0 deletions dlccore/project/__init__.py
Original file line number Diff line number Diff line change
@@ -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."""
10 changes: 10 additions & 0 deletions dlccore/project/schemas/__init__.py
Original file line number Diff line number Diff line change
@@ -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
#
28 changes: 28 additions & 0 deletions dlccore/project/schemas/base/__init__.py
Original file line number Diff line number Diff line change
@@ -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",
]
139 changes: 139 additions & 0 deletions dlccore/project/schemas/base/core.py
Original file line number Diff line number Diff line change
@@ -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.<segment>[.<segment>...]'")

return value


SchemaId = Annotated[str, AfterValidator(check_schema_id_format)]
82 changes: 82 additions & 0 deletions dlccore/project/schemas/base/probes.py
Original file line number Diff line number Diff line change
@@ -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
111 changes: 111 additions & 0 deletions dlccore/project/schemas/base/resources.py
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading