-
Notifications
You must be signed in to change notification settings - Fork 26
Add validation + compatibility tests for DeepLabCut-live #56
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
base: master
Are you sure you want to change the base?
Changes from all commits
41db059
4c97d58
1ad9a61
7e4b753
d9c0fdf
693c931
622722b
60a0e8a
990654b
882717b
e52477f
34b8727
edec653
fd17969
ebfad63
5c03b4e
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -10,12 +10,13 @@ | |
| from collections import deque | ||
| from contextlib import contextmanager | ||
| from dataclasses import dataclass | ||
| from enum import Enum, auto | ||
| from typing import Any | ||
|
|
||
| import numpy as np | ||
| from PySide6.QtCore import QObject, Signal | ||
|
|
||
| from dlclivegui.config import DLCProcessorSettings | ||
| from dlclivegui.config import DLCProcessorSettings, ModelType | ||
| from dlclivegui.processors.processor_utils import instantiate_from_scan | ||
| from dlclivegui.temp import Engine # type: ignore # TODO use main package enum when released | ||
|
|
||
|
|
@@ -33,10 +34,74 @@ | |
| DLCLive = None # type: ignore[assignment] | ||
|
|
||
|
|
||
| class PoseBackends(Enum): | ||
| DLC_LIVE = auto() | ||
|
|
||
|
|
||
| @dataclass | ||
| class PoseResult: | ||
| pose: np.ndarray | None | ||
| timestamp: float | ||
| packet: PosePacket | None = None | ||
|
|
||
|
|
||
| @dataclass(slots=True, frozen=True) | ||
| class PoseSource: | ||
| backend: PoseBackends # e.g. "DLCLive" | ||
| model_type: ModelType | None = None | ||
|
|
||
|
|
||
| @dataclass(slots=True, frozen=True) | ||
| class PosePacket: | ||
| schema_version: int = 0 | ||
| keypoints: np.ndarray | None = None | ||
| keypoint_names: list[str] | None = None | ||
| individual_ids: list[str] | None = None | ||
| source: PoseSource = PoseSource(backend=PoseBackends.DLC_LIVE) | ||
| raw: Any | None = None | ||
|
|
||
|
|
||
| def validate_pose_array(pose: Any, *, source_backend: PoseBackends = PoseBackends.DLC_LIVE) -> np.ndarray: | ||
| """ | ||
| Validate pose output shape and dtype. | ||
|
|
||
| Accepted runner output shapes: | ||
| - (K, 3): single-animal | ||
| - (N, K, 3): multi-animal | ||
| """ | ||
| try: | ||
| arr = np.asarray(pose) | ||
| except Exception as exc: | ||
| raise ValueError( | ||
| f"{source_backend} returned an invalid pose output format: could not convert to array ({exc})" | ||
|
Comment on lines
+64
to
+76
|
||
| ) from exc | ||
|
|
||
| if arr.ndim not in (2, 3): | ||
| raise ValueError( | ||
| f"{source_backend} returned an invalid pose output format:" | ||
| f" expected a 2D or 3D array, got ndim={arr.ndim}, shape={arr.shape!r}" | ||
| ) | ||
|
|
||
| if arr.shape[-1] != 3: | ||
| raise ValueError( | ||
| f"{source_backend} returned an invalid pose output format:" | ||
| f" expected last dimension size 3 (x, y, likelihood), got shape={arr.shape!r}" | ||
| ) | ||
|
|
||
| if arr.ndim == 2 and arr.shape[0] <= 0: | ||
| raise ValueError(f"{source_backend} returned an invalid pose output format: expected at least one keypoint") | ||
| if arr.ndim == 3 and (arr.shape[0] <= 0 or arr.shape[1] <= 0): | ||
| raise ValueError( | ||
| f"{source_backend} returned an invalid pose output format:" | ||
| f" expected at least one individual and one keypoint, got shape={arr.shape!r}" | ||
| ) | ||
|
|
||
| if not np.issubdtype(arr.dtype, np.number): | ||
| raise ValueError( | ||
| f"{source_backend} returned an invalid pose output format: expected numeric values, got dtype={arr.dtype}" | ||
| ) | ||
|
|
||
| return arr | ||
|
|
||
|
|
||
| @dataclass | ||
|
|
@@ -60,9 +125,6 @@ class ProcessorStats: | |
| avg_processor_overhead: float = 0.0 # Socket processor overhead | ||
|
|
||
|
|
||
| # _SENTINEL = object() | ||
|
|
||
|
|
||
| class DLCLiveProcessor(QObject): | ||
| """Background pose estimation using DLCLive with queue-based threading.""" | ||
|
|
||
|
|
@@ -269,8 +331,17 @@ def _process_frame( | |
| # Time GPU inference (and processor overhead when present) | ||
| with self._timed_processor() as proc_holder: | ||
| inference_start = time.perf_counter() | ||
| pose = self._dlc.get_pose(frame, frame_time=timestamp) | ||
| raw_pose: Any = self._dlc.get_pose(frame, frame_time=timestamp) | ||
| inference_time = time.perf_counter() - inference_start | ||
| pose_arr: np.ndarray = validate_pose_array(raw_pose, source_backend=PoseBackends.DLC_LIVE) | ||
| pose_packet = PosePacket( | ||
| schema_version=0, | ||
| keypoints=pose_arr, | ||
| keypoint_names=None, | ||
| individual_ids=None, | ||
| source=PoseSource(backend=PoseBackends.DLC_LIVE, model_type=self._settings.model_type), | ||
| raw=raw_pose, | ||
| ) | ||
|
|
||
| processor_overhead = 0.0 | ||
| gpu_inference_time = inference_time | ||
|
|
@@ -280,7 +351,7 @@ def _process_frame( | |
|
|
||
| # Emit pose (measure signal overhead) | ||
| signal_start = time.perf_counter() | ||
| self.pose_ready.emit(PoseResult(pose=pose, timestamp=timestamp)) | ||
| self.pose_ready.emit(PoseResult(pose=pose_packet.keypoints, timestamp=timestamp, packet=pose_packet)) | ||
| signal_time = time.perf_counter() - signal_start | ||
|
|
||
| end_ts = time.perf_counter() | ||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,10 @@ | ||||||||||||||||||||||||||||
| # tests/compat/conftest.py | ||||||||||||||||||||||||||||
| import sys | ||||||||||||||||||||||||||||
| import types | ||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||
| # Stub out torch imports to avoid ImportError when torch is not installed in DLCLive package. | ||||||||||||||||||||||||||||
| # This allows testing of DLCLive API compatibility without requiring torch. | ||||||||||||||||||||||||||||
| # Ideally imports should be guarded in the package itself, but this is a pragmatic solution for now. | ||||||||||||||||||||||||||||
| # IMPORTANT NOTE: This should ideally be removed and replaced whenever possible. | ||||||||||||||||||||||||||||
| if "torch" not in sys.modules: | ||||||||||||||||||||||||||||
|
Comment on lines
+4
to
+9
|
||||||||||||||||||||||||||||
| # Stub out torch imports to avoid ImportError when torch is not installed in DLCLive package. | |
| # This allows testing of DLCLive API compatibility without requiring torch. | |
| # Ideally imports should be guarded in the package itself, but this is a pragmatic solution for now. | |
| # IMPORTANT NOTE: This should ideally be removed and replaced whenever possible. | |
| if "torch" not in sys.modules: | |
| import importlib.util | |
| # Stub out torch imports to avoid ImportError when torch is not installed in DLCLive package. | |
| # This allows testing of DLCLive API compatibility without requiring torch. | |
| # Ideally imports should be guarded in the package itself, but this is a pragmatic solution for now. | |
| # IMPORTANT NOTE: This should ideally be removed and replaced whenever possible. | |
| if importlib.util.find_spec("torch") is None: |
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,128 @@ | ||||||||||||||||||||||||||||||||||||
| from __future__ import annotations | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| import importlib.metadata | ||||||||||||||||||||||||||||||||||||
| import inspect | ||||||||||||||||||||||||||||||||||||
| import os | ||||||||||||||||||||||||||||||||||||
| from pathlib import Path | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| import numpy as np | ||||||||||||||||||||||||||||||||||||
| import pytest | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| def _get_signature_params(callable_obj) -> tuple[set[str], bool]: | ||||||||||||||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||||||||||||||
| Return allowed keyword names for callable, allowing for **kwargs. | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| Example: | ||||||||||||||||||||||||||||||||||||
| >>> params, accepts_var_kw = _get_signature_params(lambda x, y, **kwargs: None, {"x", "y"}) | ||||||||||||||||||||||||||||||||||||
| >>> params == {"x", "y"} | ||||||||||||||||||||||||||||||||||||
| True | ||||||||||||||||||||||||||||||||||||
| >>> accepts_var_kw | ||||||||||||||||||||||||||||||||||||
| True | ||||||||||||||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||||||||||||||
| sig = inspect.signature(callable_obj) | ||||||||||||||||||||||||||||||||||||
| params = sig.parameters | ||||||||||||||||||||||||||||||||||||
| accepts_var_kw = any(p.kind == inspect.Parameter.VAR_KEYWORD for p in params.values()) | ||||||||||||||||||||||||||||||||||||
| return params, accepts_var_kw | ||||||||||||||||||||||||||||||||||||
|
Comment on lines
+12
to
+26
|
||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| @pytest.mark.dlclive_compat | ||||||||||||||||||||||||||||||||||||
| def test_dlclive_package_is_importable(): | ||||||||||||||||||||||||||||||||||||
| from dlclive import DLCLive # noqa: PLC0415 | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| assert DLCLive is not None | ||||||||||||||||||||||||||||||||||||
| # Helpful for CI logs to confirm matrix install result. | ||||||||||||||||||||||||||||||||||||
| _ = importlib.metadata.version("deeplabcut-live") | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| @pytest.mark.dlclive_compat | ||||||||||||||||||||||||||||||||||||
| def test_dlclive_constructor_accepts_gui_expected_kwargs(): | ||||||||||||||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||||||||||||||
| GUI passes these kwargs when constructing DLCLive. | ||||||||||||||||||||||||||||||||||||
| This test catches upstream API changes that would break initialization. | ||||||||||||||||||||||||||||||||||||
| """ | ||||||||||||||||||||||||||||||||||||
| from dlclive import DLCLive # noqa: PLC0415 | ||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||
| expected = { | ||||||||||||||||||||||||||||||||||||
| "model_path", | ||||||||||||||||||||||||||||||||||||
| "model_type", | ||||||||||||||||||||||||||||||||||||
| "processor", | ||||||||||||||||||||||||||||||||||||
| "dynamic", | ||||||||||||||||||||||||||||||||||||
| "resize", | ||||||||||||||||||||||||||||||||||||
| "precision", | ||||||||||||||||||||||||||||||||||||
| "single_animal", | ||||||||||||||||||||||||||||||||||||
| "device", | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
| params, _ = _get_signature_params(DLCLive.__init__) | ||||||||||||||||||||||||||||||||||||
| params = { | ||||||||||||||||||||||||||||||||||||
| name | ||||||||||||||||||||||||||||||||||||
| for name, p in params.items() | ||||||||||||||||||||||||||||||||||||
| if p.kind in (inspect.Parameter.KEYWORD_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD) | ||||||||||||||||||||||||||||||||||||
| } | ||||||||||||||||||||||||||||||||||||
| missing = {name for name in expected if name not in params} | ||||||||||||||||||||||||||||||||||||
|
Comment on lines
+56
to
+62
|
||||||||||||||||||||||||||||||||||||
| params, _ = _get_signature_params(DLCLive.__init__) | |
| params = { | |
| name | |
| for name, p in params.items() | |
| if p.kind in (inspect.Parameter.KEYWORD_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD) | |
| } | |
| missing = {name for name in expected if name not in params} | |
| params, accepts_var_kw = _get_signature_params(DLCLive.__init__) | |
| params = { | |
| name | |
| for name, p in params.items() | |
| if p.kind in (inspect.Parameter.KEYWORD_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD) | |
| } | |
| missing = {name for name in expected if name not in params} | |
| if missing and accepts_var_kw: | |
| # DLCLive.__init__ accepts **kwargs, so GUI-passed kwargs are still supported. | |
| missing = set() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
PR description mentions enforcing "value constraints" on pose outputs, but
validate_pose_arraycurrently only enforces shape and numeric dtype (it doesn’t check for finite values like NaN/Inf). Either add a finiteness check here (to match the stated contract) or update the stated contract/tests to reflect that NaN/Inf are allowed.