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
3 changes: 3 additions & 0 deletions dlccore/project/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,14 @@
"""Public entry points of ``dlccore.project``; consumer helpers are in ``api.helpers``. Re-exports only."""

from dlccore.project.api import helpers
from dlccore.project.inspection import inspect_project, project_name
from dlccore.project.schemas.base.resources import FileResourceKind
from dlccore.project.schemas.scope import findings_in_scope

__all__ = [
"FileResourceKind",
"findings_in_scope",
"helpers",
"inspect_project",
"project_name",
]
83 changes: 83 additions & 0 deletions dlccore/project/capabilities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
#
# 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 dlccore.project.schemas.base.filesystem import (
NodeSchema,
child_schemas,
index_layout,
)
from dlccore.project.schemas.capabilities import (
BaselineValidationCapability,
LayoutCapability,
ProjectManagerCapabilities,
ValidationCapability,
)
from dlccore.project.schemas.project_layout.project import PROJECT
from dlccore.project.schemas.snapshots import (
PROJECT_SNAPSHOT_VERSION,
)
from dlccore.project.validation.baseline import (
iter_baseline_check_registrations,
)
from dlccore.project.validation.registry import (
iter_validator_registrations,
)


def get_project_manager_capabilities() -> ProjectManagerCapabilities:
"""Return the layout and validations supported by this installation."""

baseline_validations = tuple(
BaselineValidationCapability(
code=registration.code,
description=registration.description,
)
for registration in iter_baseline_check_registrations()
)

validations = tuple(
ValidationCapability(
kind=kind,
supported_depths=tuple(registration.supported_depths),
)
for kind, registration in iter_validator_registrations()
)

return ProjectManagerCapabilities(
snapshot_version=PROJECT_SNAPSHOT_VERSION,
layout=_describe_layout(PROJECT, inside_repeated=index_layout(PROJECT).inside_repeated),
baseline_validations=baseline_validations,
validations=validations,
)


def _describe_layout(
schema: NodeSchema,
*,
inside_repeated: frozenset[str],
repeated: bool = False,
) -> LayoutCapability:
"""Project one schema node into public capability metadata."""

return LayoutCapability(
schema_id=schema.schema_id,
kind=schema.kind,
required=schema.required,
management=schema.management,
repeated=repeated,
inside_repeated=schema.schema_id in inside_repeated,
children=tuple(
_describe_layout(child, inside_repeated=inside_repeated, repeated=child_repeated)
for child, child_repeated in child_schemas(schema)
),
)
132 changes: 132 additions & 0 deletions dlccore/project/inspection.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
#
# 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
#

"""Inspect a DeepLabCut project into a snapshot, and read DeepLabCut's name for it."""

from __future__ import annotations

import re
from datetime import date
from pathlib import Path

from dlccore.project.discovery.observer import discover_project
from dlccore.project.errors import ProjectValidationError, _blocking_findings
from dlccore.project.schemas.base.findings import Finding
from dlccore.project.schemas.snapshots import ProjectSnapshot
from dlccore.project.validation import ProjectValidationRequest, validate_project
from dlccore.project.validation.config import validate_project_config

# DeepLabCut's create_new_project: config ``date`` is the 3-letter month and unpadded day, e.g. "Oct30".
_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
_ISO_DATE = re.compile(r"\d{4}-\d{2}-\d{2}")


def inspect_project(
path: str | Path,
*,
validation: ProjectValidationRequest | None = None,
raise_on_validation_error: bool = False,
) -> ProjectSnapshot:
"""Inspect a DeepLabCut project without modifying its contents.

Args:
path: Path to a project root directory or its ``config.yaml`` file.
validation: Resource validation to request, or ``None`` for baseline only.
raise_on_validation_error: Whether to raise when a finding is of blocking severity.

Raises:
FileNotFoundError: If the supplied project root does not exist.
ValueError: If the supplied existing file is not named ``config.yaml``.
ProjectValidationError: If requested and a finding has ``ERROR`` severity.
"""

project_root = _resolve_project_root(path)
config_path = project_root / "config.yaml"

config_observation = None
config_findings: tuple[Finding, ...] = ()

if config_path.is_file():
config_observation, config_findings = validate_project_config(config_path)

project = discover_project(project_root)

snapshot = ProjectSnapshot.from_project(
project_root=project_root,
config_observation=config_observation,
project=project,
findings=config_findings,
)
validation_result = validate_project(
snapshot,
request=validation,
)

snapshot = snapshot.with_validation_result(validation_result)

if raise_on_validation_error and _blocking_findings(snapshot):
raise ProjectValidationError(snapshot)

return snapshot


def project_name(snapshot: ProjectSnapshot) -> str | None:
"""Return DeepLabCut's name for the project, ``Task-scorer-YYYY-MM-DD``, as ``create_new_project`` built it.

Read from the project folder's name when it is exactly that and agrees with the config's ``date``; ``None``
otherwise, since ``date`` alone (``Oct30``) has no year. The config's ``project_path`` is not read: DeepLabCut
rewrites it to the current location whenever it loads the config.

Raises:
ConfigUnavailableError: If the config was not loaded.
"""

config = snapshot.config
prefix = f"{config.Task}-{config.scorer}-"
folder = snapshot.project_root.name

if folder.startswith(prefix) and _agrees_with(folder.removeprefix(prefix), str(config.date)):
return folder

return None


def _agrees_with(stamp: str, config_date: str) -> bool:
if not _ISO_DATE.fullmatch(stamp):
return False
try:
created = date.fromisoformat(stamp)
except ValueError:
return False

return f"{_MONTHS[created.month - 1]}{created.day}" == config_date


def _resolve_project_root(
path: str | Path,
) -> Path:
"""Resolve an absolute project root from a directory or ``config.yaml`` path, without following links."""

supplied_path = Path(path).absolute()

if supplied_path.is_dir():
return supplied_path

if supplied_path.is_file():
if supplied_path.name != "config.yaml":
raise ValueError(f"A project file input must be named 'config.yaml': {supplied_path}")

return supplied_path.parent

if supplied_path.name == "config.yaml":
return supplied_path.parent

raise FileNotFoundError(f"Project path does not exist: {supplied_path}")
56 changes: 56 additions & 0 deletions dlccore/project/schemas/capabilities.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#
# 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 dlccore.project.schemas.base.core import FrozenModel, SchemaId
from dlccore.project.schemas.base.resources import (
ResourceKind,
ResourceManagement,
)
from dlccore.project.schemas.base.validation import (
ValidationDepth,
)


class LayoutCapability(FrozenModel):
"""One node in the declared DeepLabCut project layout."""

schema_id: SchemaId
kind: ResourceKind
required: bool
management: ResourceManagement
repeated: bool = False
inside_repeated: bool = False
children: tuple[LayoutCapability, ...] = ()


class BaselineValidationCapability(FrozenModel):
"""One automatic project-level validation capability."""

code: str
description: str


class ValidationCapability(FrozenModel):
"""Validation depths available for one resource kind."""

kind: ResourceKind
supported_depths: tuple[ValidationDepth, ...]


class ProjectManagerCapabilities(FrozenModel):
"""Versioned description of project-management affordances."""

snapshot_version: str
layout: LayoutCapability
baseline_validations: tuple[BaselineValidationCapability, ...] = ()
validations: tuple[ValidationCapability, ...] = ()
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ ini_options.filterwarnings = [
"error:The default of observed=False is deprecated:FutureWarning",
]
ini_options.markers = [
"data_validator(code): declares coverage of a registered validation suite",
"destination(repo): repository this test ultimately belongs to; a file carries exactly one",
"""\
owed_before_release(reason, raises): prototype maintenance; a strict xfail expecting `raises` while the package and \
Expand Down
18 changes: 18 additions & 0 deletions tests/project/discovery/test_observer.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@

import pytest

from dlccore.project.api import inspect_project
from dlccore.project.discovery.observer import discover_directory_node, discover_project
from dlccore.project.schemas.base.filesystem import (
DirectorySchema,
Expand Down Expand Up @@ -374,3 +375,20 @@ def test_without_file_ids_a_subdirectory_is_not_a_symlink_loop(tmp_path: Path) -
assert by_path[Path("videos")].status == NodeStatus.PRESENT
assert by_path[Path("labeled-data")].status == NodeStatus.PRESENT
assert by_path[Path("labeled-data")].traversal_error_type is None


@pytest.mark.xfail(
reason="on a case-insensitive filesystem, a layout directory spelled differently on disk is discovered twice: "
"as the layout node under the layout's spelling, and as an unclaimed directory under its own",
strict=True,
raises=AssertionError,
)
def test_a_differently_cased_layout_directory_is_one_resource(tmp_path: Path) -> None:
(tmp_path / "VIDEOS").mkdir()

if not (tmp_path / "videos").exists():
pytest.skip("case-sensitive filesystem: VIDEOS is simply another directory")

resources = inspect_project(tmp_path).resources

assert len([resource for resource in resources if str(resource.project_relative_path).lower() == "videos"]) == 1
Loading
Loading