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
10 changes: 10 additions & 0 deletions dlccore/project/api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,13 @@
from dlccore.project.content import (
FailedRead,
FileFingerprint,
InspectedLabeledDataFile,
LabeledDataEntry,
ProjectLabeledData,
ResourcesFileFingerprint,
compare_file_fingerprints,
inspect_labeled_data_file,
read_project_labeled_data,
resources_file_fingerprint,
)
from dlccore.project.inspection import inspect_project, project_name
Expand All @@ -27,11 +32,16 @@
"FailedRead",
"FileFingerprint",
"FileResourceKind",
"InspectedLabeledDataFile",
"LabeledDataEntry",
"ProjectLabeledData",
"ResourcesFileFingerprint",
"compare_file_fingerprints",
"findings_in_scope",
"helpers",
"inspect_labeled_data_file",
"inspect_project",
"project_name",
"read_project_labeled_data",
"resources_file_fingerprint",
]
12 changes: 12 additions & 0 deletions dlccore/project/content/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,24 @@
compare_file_fingerprints,
resources_file_fingerprint,
)
from dlccore.project.content.labeled_data import (
InspectedLabeledDataFile,
LabeledDataEntry,
ProjectLabeledData,
inspect_labeled_data_file,
read_project_labeled_data,
)
from dlccore.project.content.reads import FailedRead

__all__ = [
"FailedRead",
"FileFingerprint",
"InspectedLabeledDataFile",
"LabeledDataEntry",
"ProjectLabeledData",
"ResourcesFileFingerprint",
"compare_file_fingerprints",
"inspect_labeled_data_file",
"read_project_labeled_data",
"resources_file_fingerprint",
]
172 changes: 172 additions & 0 deletions dlccore/project/content/labeled_data/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
#
# 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
#

"""Labeled-data files, of a snapshot or at a path, read through ``dlccore.io`` with findings about each one."""

from __future__ import annotations

from dataclasses import dataclass
from pathlib import Path

from pydantic import JsonValue

from dlccore.io import UnreadableFileError
from dlccore.io.labeled_data import LabeledDataFile, read_labeled_data
from dlccore.project.content.labeled_data.validate import validate_labeled_data_file
from dlccore.project.content.reads import FailedRead, present_files_in_scope
from dlccore.project.discovery.position import LayoutPosition, locate_in_layout
from dlccore.project.inspection import inspect_project
from dlccore.project.schemas.base.core import ProjectRelativePath, SchemaId
from dlccore.project.schemas.base.filesystem import LayoutIndex
from dlccore.project.schemas.base.finding_codes import LabeledDataFindingCode
from dlccore.project.schemas.base.findings import Finding
from dlccore.project.schemas.locations import Location, node_location
from dlccore.project.schemas.project_layout.labeled_data import HUMAN_LABELS, MACHINE_LABELS, MACHINE_LABELS_CSV
from dlccore.project.schemas.project_layout.project import PROJECT_INDEX
from dlccore.project.schemas.scope import Scope, findings_in_scope
from dlccore.project.schemas.snapshots import ProjectSnapshot
from dlccore.project.validation.results import ValidationResult

_LABELS = frozenset({HUMAN_LABELS.schema_id, MACHINE_LABELS.schema_id, MACHINE_LABELS_CSV.schema_id})


@dataclass(frozen=True)
class LabeledDataEntry:
"""One labels file read through the project layer, with its layout anchor.

Attributes:
schema_id: The layout node of the file.
project_relative_path: The path as the snapshot observed it.
data: The file as ``dlccore.io`` read it.
"""

schema_id: SchemaId
project_relative_path: ProjectRelativePath
data: LabeledDataFile


@dataclass(frozen=True)
class ProjectLabeledData:
"""The labels files read, those that could not be, and the snapshot with their findings merged.

Attributes:
snapshot: The input snapshot with the findings about the files requested merged in, those read and those
not; use it, not the input, for any policy decision about them.
read: One entry per requested file that could be read.
failed: One entry per requested file that could not be read.
"""

snapshot: ProjectSnapshot
read: tuple[LabeledDataEntry, ...] = ()
failed: tuple[FailedRead, ...] = ()


@dataclass(frozen=True)
class InspectedLabeledDataFile:
"""One labels file inspected from its path, inside a project or not.

Attributes:
position: Where the path sits in the layout, as far as it is certain.
data: The file as ``dlccore.io`` read it; ``None`` exactly when it could not be read.
findings: Every finding in scope of the file, anchored at ``position.location``.
snapshot: The project's snapshot, when ``position`` found a project root.
"""

position: LayoutPosition
data: LabeledDataFile | None
findings: tuple[Finding, ...]
snapshot: ProjectSnapshot | None = None


def read_project_labeled_data(
snapshot: ProjectSnapshot,
scope: Scope,
*,
index: LayoutIndex = PROJECT_INDEX,
) -> ProjectLabeledData:
"""Read every present human or machine labels file ``scope`` covers in ``snapshot``, without rediscovering.

Each such file is in ``read`` or in ``failed``, never both. A file that cannot be read yields a
``LABELED_DATA_UNREADABLE`` finding, carried by its ``FailedRead``; a file read yields its findings from
``validate_labeled_data_file``. Both are merged into the returned snapshot; the input is not modified.

Args:
snapshot: A snapshot from ``inspect_project``.
scope: The nodes whose labels files to read, each within its instance prefix; see ``Scope.covers``.
index: The layout the snapshot was observed against.

Raises:
ValueError: If ``scope`` names a node the layout does not declare.
"""

read: list[LabeledDataEntry] = []
failed: list[FailedRead] = []
about_read: list[Finding] = []

for node in present_files_in_scope(snapshot, scope, _LABELS & set(scope.file_schema_ids(index=index)), index=index):
at = node_location(node.schema_id, node.project_relative_path, index=index)
data, findings = _read(snapshot.project_root / node.project_relative_path, node.kind.value, at)

if data is None:
failed.append(FailedRead(node.schema_id, node.project_relative_path, findings))
continue

read.append(LabeledDataEntry(node.schema_id, node.project_relative_path, data))
about_read += findings

findings = (*(finding for failure in failed for finding in failure.findings), *about_read)

return ProjectLabeledData(
snapshot=snapshot.with_validation_result(ValidationResult(findings=findings)),
read=tuple(read),
failed=tuple(failed),
)


def inspect_labeled_data_file(path: Path, *, index: LayoutIndex = PROJECT_INDEX) -> InspectedLabeledDataFile:
"""Read one labels file from its path and report it, placing it in the layout by scanning upward.

Inside a project, the project is inspected and the file read as ``read_project_labeled_data`` reads it, so
project-level findings in its scope are included. Outside one, the file gets the same per-file findings.

Raises:
ValueError: If the file's name matches no labels node of the layout, or several.
"""

position = locate_in_layout(path, index=index)
at = position.location
node = index.schemas[at["schema_id"]]
if node.schema_id not in _LABELS:
raise ValueError(f"{path.name!r} is a {node.schema_id} file, not a labels file.")

if position.project_root is None:
data, findings = _read(path, node.kind.value, at)
return InspectedLabeledDataFile(position, data, findings)

scope = Scope(node, within=at["instance"])
result = read_project_labeled_data(inspect_project(position.project_root), scope, index=index)
data = next((entry.data for entry in result.read), None)
return InspectedLabeledDataFile(position, data, findings_in_scope(result.snapshot, scope), result.snapshot)


def _read(path: Path, resource_kind: str, at: Location) -> tuple[LabeledDataFile | None, tuple[Finding, ...]]:
"""Read one labels file and return it with its findings, or ``None`` with the finding that it is unreadable."""

try:
data = read_labeled_data(path)
except UnreadableFileError as error:
evidence: dict[str, JsonValue] = {
"resource_kind": resource_kind,
"error_type": type(error.__cause__ or error).__name__,
"error_message": str(error),
}
return None, (Finding(code=LabeledDataFindingCode.LABELED_DATA_UNREADABLE, **at, path=path, evidence=evidence),)
return data, validate_labeled_data_file(data, at)
142 changes: 142 additions & 0 deletions dlccore/project/content/labeled_data/file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
#
# 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
#

"""Findings about a labeled-data file as stored, one report per code, each turning one check's fact into findings."""

from __future__ import annotations

from pydantic import JsonValue

from dlccore.io.labeled_data import Keypoint, LabeledDataFile
from dlccore.io.labeled_data._checks.file import (
frame_absorbed_into_index_names,
frames_of_other_depth,
frames_with_unnamed_parts,
has_no_frames,
header_is_unrecognised,
keypoints_with_unrecognised_coords,
keypoints_without_the_likelihood_others_store,
legacy_h5_key,
non_numeric_columns,
row_index_is_unrecognised,
unknown_h5_key,
unread_h5_keys,
)
from dlccore.project.content.labeled_data.report import Report, finding
from dlccore.project.schemas.base.finding_codes import LabeledDataFindingCode as Code
from dlccore.project.schemas.base.findings import Finding
from dlccore.project.schemas.locations import Location


def keypoint_evidence(keypoint: Keypoint) -> dict[str, JsonValue]:
"""A keypoint as evidence: its scorer, individual (``None`` without an individuals level) and bodypart."""

return {"scorer": keypoint.scorer, "individual": keypoint.individual, "bodypart": keypoint.bodypart}


def _multi_key(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]:
selection = data.key_selection
if selection is None or not unread_h5_keys(selection):
return ()
keys_found: list[JsonValue] = list(selection.keys_found)
return finding(Code.LABELED_DATA_H5_MULTI_KEY, data, at, keys_found=keys_found, selected_key=selection.selected_key)


def _legacy_key(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]:
key = legacy_h5_key(data.key_selection)
return finding(Code.LABELED_DATA_H5_LEGACY_KEY, data, at, key=key) if key else ()


def _unknown_key(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]:
key = unknown_h5_key(data.key_selection)
return finding(Code.LABELED_DATA_H5_UNKNOWN_KEY, data, at, key=key) if key else ()


def _header(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]:
if not header_is_unrecognised(data.raw_header):
return ()
level_names: list[JsonValue] = [None if name is None else str(name) for name in data.raw_header.level_names]
return finding(Code.LABELED_DATA_HEADER_UNRECOGNISED, data, at, level_names=level_names)


def _coords(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]:
found = keypoints_with_unrecognised_coords(data.raw_header)
keypoints: list[JsonValue] = [{**keypoint_evidence(c.keypoint), "coords": list(c.coords)} for c in found]
return finding(Code.LABELED_DATA_COORDS_UNRECOGNISED, data, at, keypoints=keypoints) if found else ()


def _partial_likelihood(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]:
found = keypoints_without_the_likelihood_others_store(data.raw_header)
keypoints: list[JsonValue] = [keypoint_evidence(columns.keypoint) for columns in found]
return finding(Code.LABELED_DATA_LIKELIHOOD_PARTIAL, data, at, keypoints=keypoints) if found else ()


def _not_numeric(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]:
found = non_numeric_columns(data.to_raw_wide_df())
columns: list[JsonValue] = [
[str(level) for level in label] if isinstance(label, tuple) else str(label) for label in found
]
return finding(Code.LABELED_DATA_VALUES_NOT_NUMERIC, data, at, columns=columns) if found else ()


def _no_frames(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]:
return finding(Code.LABELED_DATA_NO_FRAMES, data, at) if has_no_frames(data.raw_row_index) else ()


def _row_index(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]:
row_index = data.raw_row_index
if not row_index_is_unrecognised(row_index):
return ()
first = next(entry for entry in row_index.entries if not isinstance(entry, str))
return finding(Code.LABELED_DATA_ROW_INDEX_UNRECOGNISED, data, at, first_entry=repr(first))


def _frame_rows(code: Code, rows: tuple[int, ...], data: LabeledDataFile, at: Location) -> tuple[Finding, ...]:
if not rows:
return ()
first_frame: list[JsonValue] = [repr(part) for part in data.raw_row_index.frames[rows[0]]]
return finding(code, data, at, row_count=len(rows), first_frame=first_frame)


def _frame_depth(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]:
return _frame_rows(Code.LABELED_DATA_FRAME_DEPTH, frames_of_other_depth(data.raw_row_index), data, at)


def _frame_part(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]:
return _frame_rows(Code.LABELED_DATA_FRAME_PART_UNNAMED, frames_with_unnamed_parts(data.raw_row_index), data, at)


def _absorbed(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]:
frame: list[JsonValue] = list(frame_absorbed_into_index_names(data.raw_row_index))
return finding(Code.LABELED_DATA_CSV_FRAME_ABSORBED, data, at, frame=frame) if frame else ()


def _stamp(data: LabeledDataFile, at: Location) -> tuple[Finding, ...]:
error = data.writer_stamp_error
return finding(Code.LABELED_DATA_WRITER_STAMP_MALFORMED, data, at, error_message=error) if error else ()


# Each emits as ``emit(data: LabeledDataFile, at: Location)``.
REPORTS: tuple[Report, ...] = (
Report(unread_h5_keys, Code.LABELED_DATA_H5_MULTI_KEY, _multi_key),
Report(legacy_h5_key, Code.LABELED_DATA_H5_LEGACY_KEY, _legacy_key),
Report(unknown_h5_key, Code.LABELED_DATA_H5_UNKNOWN_KEY, _unknown_key),
Report(header_is_unrecognised, Code.LABELED_DATA_HEADER_UNRECOGNISED, _header),
Report(keypoints_with_unrecognised_coords, Code.LABELED_DATA_COORDS_UNRECOGNISED, _coords),
Report(keypoints_without_the_likelihood_others_store, Code.LABELED_DATA_LIKELIHOOD_PARTIAL, _partial_likelihood),
Report(non_numeric_columns, Code.LABELED_DATA_VALUES_NOT_NUMERIC, _not_numeric),
Report(has_no_frames, Code.LABELED_DATA_NO_FRAMES, _no_frames),
Report(row_index_is_unrecognised, Code.LABELED_DATA_ROW_INDEX_UNRECOGNISED, _row_index),
Report(frames_of_other_depth, Code.LABELED_DATA_FRAME_DEPTH, _frame_depth),
Report(frames_with_unnamed_parts, Code.LABELED_DATA_FRAME_PART_UNNAMED, _frame_part),
Report(frame_absorbed_into_index_names, Code.LABELED_DATA_CSV_FRAME_ABSORBED, _absorbed),
Report(None, Code.LABELED_DATA_WRITER_STAMP_MALFORMED, _stamp),
)
Loading
Loading