openzilo-gesture 0.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- openzilo_gesture/__init__.py +8 -0
- openzilo_gesture/bundle.py +212 -0
- openzilo_gesture/config.py +116 -0
- openzilo_gesture/preprocessing.py +82 -0
- openzilo_gesture/py.typed +0 -0
- openzilo_gesture/recognizer.py +122 -0
- openzilo_gesture/segmentation.py +177 -0
- openzilo_gesture-0.2.0.dist-info/METADATA +220 -0
- openzilo_gesture-0.2.0.dist-info/RECORD +13 -0
- openzilo_gesture-0.2.0.dist-info/WHEEL +5 -0
- openzilo_gesture-0.2.0.dist-info/licenses/LICENSE +373 -0
- openzilo_gesture-0.2.0.dist-info/licenses/NOTICE.md +23 -0
- openzilo_gesture-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Load Studio exports and recognize gestures without GUI or Bluetooth dependencies."""
|
|
3
|
+
from .bundle import GestureBundle
|
|
4
|
+
from .config import AXES, PipelineConfig, SegmentationConfig, RejectionCalibration
|
|
5
|
+
from .recognizer import GestureRecognizer, Prediction
|
|
6
|
+
|
|
7
|
+
__version__ = "0.2.0"
|
|
8
|
+
__all__ = ["AXES", "GestureBundle", "GestureRecognizer", "PipelineConfig", "Prediction", "SegmentationConfig", "RejectionCalibration"]
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Portable, versioned JSON exports. Loading never executes pickle payloads."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass, field
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import tempfile
|
|
10
|
+
from typing import Any
|
|
11
|
+
|
|
12
|
+
from hmmlearn.hmm import GaussianHMM
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
from .config import AXES, N_FEATURES, PipelineConfig, SegmentationConfig, RejectionCalibration
|
|
16
|
+
|
|
17
|
+
FORMAT = "hmm-gesture"
|
|
18
|
+
FORMAT_VERSION = 2
|
|
19
|
+
MAX_BUNDLE_BYTES = 32 * 1024 * 1024
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def validate_name(name: object) -> str:
|
|
23
|
+
if not isinstance(name, str) or not name.strip() or len(name) > 128 or any(ord(c) < 32 for c in name):
|
|
24
|
+
raise ValueError("Gesture name must be nonempty text, at most 128 characters, without control characters")
|
|
25
|
+
return name
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def write_json(path: str | Path, data: object, *, max_bytes: int | None = None) -> Path:
|
|
29
|
+
"""Replace a JSON file atomically, leaving any existing export intact on error."""
|
|
30
|
+
path = Path(path)
|
|
31
|
+
text = json.dumps(data, ensure_ascii=False, indent=2, allow_nan=False)
|
|
32
|
+
if max_bytes is not None and len(text.encode("utf-8")) > max_bytes:
|
|
33
|
+
raise ValueError("Bundle is too large; export fewer gestures")
|
|
34
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
35
|
+
temporary = None
|
|
36
|
+
try:
|
|
37
|
+
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=path.parent,
|
|
38
|
+
prefix=f".{path.name}.", suffix=".tmp", delete=False) as stream:
|
|
39
|
+
temporary = Path(stream.name)
|
|
40
|
+
stream.write(text)
|
|
41
|
+
os.replace(temporary, path)
|
|
42
|
+
finally:
|
|
43
|
+
if temporary is not None:
|
|
44
|
+
temporary.unlink(missing_ok=True)
|
|
45
|
+
return path
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _model_arrays(model: GaussianHMM) -> dict[str, np.ndarray]:
|
|
49
|
+
if not isinstance(model, GaussianHMM) or model.covariance_type != "diag":
|
|
50
|
+
raise ValueError("Only diagonal Gaussian HMMs are supported")
|
|
51
|
+
try:
|
|
52
|
+
arrays = {"startprob": np.asarray(model.startprob_, dtype=float),
|
|
53
|
+
"transmat": np.asarray(model.transmat_, dtype=float),
|
|
54
|
+
"means": np.asarray(model.means_, dtype=float),
|
|
55
|
+
"covars": np.asarray(model._covars_, dtype=float)}
|
|
56
|
+
except (AttributeError, TypeError, ValueError) as exc:
|
|
57
|
+
raise ValueError("Model has missing or invalid fitted parameters") from exc
|
|
58
|
+
states = model.n_components
|
|
59
|
+
if not isinstance(states, int) or not 1 <= states <= 512:
|
|
60
|
+
raise ValueError("A model must have between 1 and 512 states")
|
|
61
|
+
shapes = {"startprob": (states,), "transmat": (states, states),
|
|
62
|
+
"means": (states, N_FEATURES), "covars": (states, N_FEATURES)}
|
|
63
|
+
for name, array in arrays.items():
|
|
64
|
+
if array.shape != shapes[name] or not np.isfinite(array).all():
|
|
65
|
+
raise ValueError(f"Invalid {name}: expected finite array with shape {shapes[name]}")
|
|
66
|
+
for name in ("startprob", "transmat"):
|
|
67
|
+
array = arrays[name]
|
|
68
|
+
if (array < 0).any() or not np.allclose(array.sum(axis=-1), 1, rtol=1e-7, atol=1e-8):
|
|
69
|
+
raise ValueError(f"Invalid {name}: probabilities must be nonnegative and sum to one")
|
|
70
|
+
if (arrays["covars"] <= 0).any():
|
|
71
|
+
raise ValueError("Model variances must be strictly positive")
|
|
72
|
+
return arrays
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _reject_constant(value: str) -> None:
|
|
76
|
+
raise ValueError(f"Invalid JSON number: {value}")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _load_model(raw: object) -> GaussianHMM:
|
|
80
|
+
if not isinstance(raw, dict) or raw.get("type") != "gaussian-hmm" or raw.get("covariance_type") != "diag":
|
|
81
|
+
raise ValueError("Unsupported model type or covariance type")
|
|
82
|
+
try:
|
|
83
|
+
means = np.asarray(raw["means"], dtype=float)
|
|
84
|
+
if means.ndim != 2:
|
|
85
|
+
raise ValueError("Model means must be a matrix")
|
|
86
|
+
model = GaussianHMM(n_components=len(means), covariance_type="diag", init_params="")
|
|
87
|
+
model.startprob_ = np.asarray(raw["startprob"], dtype=float)
|
|
88
|
+
model.transmat_ = np.asarray(raw["transmat"], dtype=float)
|
|
89
|
+
model.means_ = means
|
|
90
|
+
model.covars_ = np.asarray(raw["covars"], dtype=float)
|
|
91
|
+
_model_arrays(model)
|
|
92
|
+
model._check()
|
|
93
|
+
return model
|
|
94
|
+
except (KeyError, TypeError, ValueError, IndexError) as exc:
|
|
95
|
+
raise ValueError(f"Invalid model parameters: {exc}") from exc
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _config_dict(config, version):
|
|
99
|
+
fields = asdict(config)
|
|
100
|
+
if version == 1:
|
|
101
|
+
# Version 1 always used zero filter state and baseline-motion segmentation.
|
|
102
|
+
for key in ("filter_initialization", "mode", "post_roll"):
|
|
103
|
+
fields.pop(key, None)
|
|
104
|
+
return fields
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _load_config(cls: type, raw: object, version: int = FORMAT_VERSION) -> Any:
|
|
108
|
+
fields = set(cls.__dataclass_fields__)
|
|
109
|
+
if version == 1:
|
|
110
|
+
fields -= {"filter_initialization", "mode", "post_roll"}
|
|
111
|
+
if not isinstance(raw, dict) or set(raw) != fields:
|
|
112
|
+
raise ValueError(f"Missing or unsupported fields in {cls.__name__}")
|
|
113
|
+
try:
|
|
114
|
+
return cls(**raw)
|
|
115
|
+
except (ValueError, TypeError) as exc:
|
|
116
|
+
raise ValueError(f"Invalid {cls.__name__}: {exc}") from exc
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
@dataclass
|
|
120
|
+
class GestureBundle:
|
|
121
|
+
models: dict[str, GaussianHMM]
|
|
122
|
+
pipeline: PipelineConfig = field(default_factory=PipelineConfig)
|
|
123
|
+
segmentation: SegmentationConfig = field(default_factory=SegmentationConfig)
|
|
124
|
+
metadata: dict[str, Any] = field(default_factory=dict)
|
|
125
|
+
rejection: dict[str, RejectionCalibration] | None = None
|
|
126
|
+
|
|
127
|
+
def __post_init__(self) -> None:
|
|
128
|
+
if not isinstance(self.pipeline, PipelineConfig) or not isinstance(self.segmentation, SegmentationConfig):
|
|
129
|
+
raise ValueError("Bundle requires PipelineConfig and SegmentationConfig")
|
|
130
|
+
if not isinstance(self.models, dict) or not self.models:
|
|
131
|
+
raise ValueError("A gesture bundle must contain at least one model")
|
|
132
|
+
for name, model in self.models.items():
|
|
133
|
+
validate_name(name)
|
|
134
|
+
_model_arrays(model)
|
|
135
|
+
if self.rejection is not None:
|
|
136
|
+
if not isinstance(self.rejection, dict) or set(self.rejection) != set(self.models):
|
|
137
|
+
raise ValueError("Rejection calibration must cover every gesture exactly")
|
|
138
|
+
for calibration in self.rejection.values():
|
|
139
|
+
if not isinstance(calibration, RejectionCalibration):
|
|
140
|
+
raise ValueError("Invalid rejection calibration")
|
|
141
|
+
calibration.__post_init__()
|
|
142
|
+
if not isinstance(self.metadata, dict):
|
|
143
|
+
raise ValueError("Bundle metadata must be an object")
|
|
144
|
+
try:
|
|
145
|
+
json.dumps(self.metadata, allow_nan=False)
|
|
146
|
+
except (TypeError, ValueError) as exc:
|
|
147
|
+
raise ValueError("Bundle metadata must contain finite JSON values") from exc
|
|
148
|
+
|
|
149
|
+
@property
|
|
150
|
+
def gesture_names(self) -> tuple[str, ...]:
|
|
151
|
+
return tuple(self.models)
|
|
152
|
+
|
|
153
|
+
def save(self, path: str | Path) -> Path:
|
|
154
|
+
self.__post_init__()
|
|
155
|
+
gestures = []
|
|
156
|
+
for name, model in self.models.items():
|
|
157
|
+
params = {key: value.tolist() for key, value in _model_arrays(model).items()}
|
|
158
|
+
gestures.append({"name": name, "model": {"type": "gaussian-hmm",
|
|
159
|
+
"covariance_type": "diag", **params}})
|
|
160
|
+
version = (1 if self.rejection is None and self.pipeline.filter_initialization == "zero"
|
|
161
|
+
and self.segmentation.mode == "motion" and self.segmentation.post_roll == 0 else FORMAT_VERSION)
|
|
162
|
+
data = {"format": FORMAT, "version": version,
|
|
163
|
+
"axes": list(AXES), "units": "raw_int16",
|
|
164
|
+
"pipeline": _config_dict(self.pipeline, version),
|
|
165
|
+
"segmentation": _config_dict(self.segmentation, version),
|
|
166
|
+
"gestures": gestures, "metadata": self.metadata}
|
|
167
|
+
if version >= 2:
|
|
168
|
+
data["rejection"] = ({name: asdict(value) for name, value in self.rejection.items()}
|
|
169
|
+
if self.rejection is not None else None)
|
|
170
|
+
return write_json(path, data, max_bytes=MAX_BUNDLE_BYTES)
|
|
171
|
+
|
|
172
|
+
@classmethod
|
|
173
|
+
def load(cls, path: str | Path) -> GestureBundle:
|
|
174
|
+
path = Path(path)
|
|
175
|
+
if path.stat().st_size > MAX_BUNDLE_BYTES:
|
|
176
|
+
raise ValueError("Bundle exceeds the 32 MiB size limit")
|
|
177
|
+
try:
|
|
178
|
+
raw = json.loads(path.read_text(encoding="utf-8"), parse_constant=_reject_constant)
|
|
179
|
+
except (json.JSONDecodeError, UnicodeError) as exc:
|
|
180
|
+
raise ValueError("Not a valid UTF-8 gesture JSON bundle (pickle is not supported)") from exc
|
|
181
|
+
if not isinstance(raw, dict) or raw.get("format") != FORMAT:
|
|
182
|
+
raise ValueError("Not a openzilo-gesture bundle; retrain/export legacy pickle models in Studio")
|
|
183
|
+
if type(raw.get("version")) is not int or raw["version"] not in (1, FORMAT_VERSION):
|
|
184
|
+
raise ValueError(f"Unsupported gesture bundle version: {raw.get('version')}")
|
|
185
|
+
if raw.get("axes") != list(AXES) or raw.get("units") != "raw_int16":
|
|
186
|
+
raise ValueError("Unsupported axis order or sensor units")
|
|
187
|
+
version = raw["version"]
|
|
188
|
+
pipeline = _load_config(PipelineConfig, raw.get("pipeline"), version)
|
|
189
|
+
segmentation = _load_config(SegmentationConfig, raw.get("segmentation"), version)
|
|
190
|
+
gestures = raw.get("gestures")
|
|
191
|
+
if not isinstance(gestures, list) or not gestures:
|
|
192
|
+
raise ValueError("Bundle must contain a nonempty gestures list")
|
|
193
|
+
models = {}
|
|
194
|
+
for entry in gestures:
|
|
195
|
+
if not isinstance(entry, dict):
|
|
196
|
+
raise ValueError("Invalid gesture entry")
|
|
197
|
+
name = validate_name(entry.get("name"))
|
|
198
|
+
if name in models:
|
|
199
|
+
raise ValueError(f"Duplicate gesture name: {name}")
|
|
200
|
+
models[name] = _load_model(entry.get("model"))
|
|
201
|
+
rejection = None
|
|
202
|
+
if version >= 2:
|
|
203
|
+
if "rejection" not in raw:
|
|
204
|
+
raise ValueError("Version 2 requires an explicit rejection field")
|
|
205
|
+
if raw["rejection"] is not None:
|
|
206
|
+
if not isinstance(raw["rejection"], dict):
|
|
207
|
+
raise ValueError("Rejection calibration must be an object or null")
|
|
208
|
+
rejection = {name: _load_config(RejectionCalibration, value)
|
|
209
|
+
for name, value in raw["rejection"].items()}
|
|
210
|
+
elif "rejection" in raw:
|
|
211
|
+
raise ValueError("Version 1 cannot contain rejection calibration")
|
|
212
|
+
return cls(models, pipeline, segmentation, raw.get("metadata", {}), rejection)
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Versioned preprocessing and stream segmentation settings."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
import math
|
|
7
|
+
|
|
8
|
+
AXES = ("ax", "ay", "az", "gx", "gy", "gz")
|
|
9
|
+
N_FEATURES = 24
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def positive_number(name: str, value: float) -> None:
|
|
13
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:
|
|
14
|
+
raise ValueError(f"{name} must be finite and positive")
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def integer(name: str, value: int, minimum: int = 1) -> None:
|
|
18
|
+
if isinstance(value, bool) or not isinstance(value, int) or value < minimum:
|
|
19
|
+
raise ValueError(f"{name} must be an integer >= {minimum}")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class PipelineConfig:
|
|
24
|
+
sample_rate_hz: float = 25.0
|
|
25
|
+
cutoff_hz: float = 10.0
|
|
26
|
+
filter_order: int = 2
|
|
27
|
+
median_kernel: int = 5
|
|
28
|
+
window_size: int = 8
|
|
29
|
+
window_overlap: int = 4
|
|
30
|
+
filter_initialization: str = "zero" # v1 compatibility; new Studio uses steady state.
|
|
31
|
+
|
|
32
|
+
def __post_init__(self) -> None:
|
|
33
|
+
positive_number("sample_rate_hz", self.sample_rate_hz)
|
|
34
|
+
positive_number("cutoff_hz", self.cutoff_hz)
|
|
35
|
+
if self.cutoff_hz >= self.sample_rate_hz / 2:
|
|
36
|
+
raise ValueError("cutoff_hz must be below half the sample rate")
|
|
37
|
+
integer("filter_order", self.filter_order)
|
|
38
|
+
integer("median_kernel", self.median_kernel)
|
|
39
|
+
if self.median_kernel % 2 != 1:
|
|
40
|
+
raise ValueError("median_kernel must be odd")
|
|
41
|
+
integer("window_size", self.window_size, 2)
|
|
42
|
+
integer("window_overlap", self.window_overlap, 0)
|
|
43
|
+
if self.window_overlap >= self.window_size:
|
|
44
|
+
raise ValueError("window_overlap must be smaller than window_size")
|
|
45
|
+
if not isinstance(self.filter_initialization, str) or self.filter_initialization not in {"zero", "steady"}:
|
|
46
|
+
raise ValueError("filter_initialization must be zero or steady")
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def min_samples(self) -> int:
|
|
50
|
+
"""At least two complete feature windows."""
|
|
51
|
+
return self.window_size * 2 - self.window_overlap
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True)
|
|
55
|
+
class SegmentationConfig:
|
|
56
|
+
energy_threshold: float = 1500.0
|
|
57
|
+
min_onset_frames: int = 3
|
|
58
|
+
min_offset_frames: int = 5
|
|
59
|
+
min_gesture_len: int = 12
|
|
60
|
+
max_gesture_len: int = 125
|
|
61
|
+
pre_roll: int = 3
|
|
62
|
+
cooldown_frames: int = 15
|
|
63
|
+
mode: str = "motion"
|
|
64
|
+
post_roll: int = 0
|
|
65
|
+
|
|
66
|
+
def __post_init__(self) -> None:
|
|
67
|
+
positive_number("energy_threshold", self.energy_threshold)
|
|
68
|
+
for name in ("min_onset_frames", "min_offset_frames", "min_gesture_len", "max_gesture_len"):
|
|
69
|
+
integer(name, getattr(self, name))
|
|
70
|
+
integer("pre_roll", self.pre_roll, 0)
|
|
71
|
+
integer("cooldown_frames", self.cooldown_frames, 0)
|
|
72
|
+
if self.min_gesture_len > self.max_gesture_len:
|
|
73
|
+
raise ValueError("min_gesture_len must not exceed max_gesture_len")
|
|
74
|
+
if not isinstance(self.mode, str) or self.mode not in {"motion", "impulse"}:
|
|
75
|
+
raise ValueError("segmentation mode must be motion or impulse")
|
|
76
|
+
integer("post_roll", self.post_roll, 0)
|
|
77
|
+
if self.mode == "impulse":
|
|
78
|
+
if self.post_roll < 1:
|
|
79
|
+
raise ValueError("impulse segmentation requires post_roll >= 1")
|
|
80
|
+
if not self.min_gesture_len <= self.pre_roll + 1 + self.post_roll <= self.max_gesture_len:
|
|
81
|
+
raise ValueError("impulse context length must be within gesture length limits")
|
|
82
|
+
|
|
83
|
+
@classmethod
|
|
84
|
+
def for_sample_rate(cls, sample_rate_hz: float, *, mode: str = "motion",
|
|
85
|
+
energy_threshold: float = 1500.0, min_samples: int = 12):
|
|
86
|
+
"""Explicit time-based Studio presets; legacy constructors keep v1 frame counts."""
|
|
87
|
+
positive_number("sample_rate_hz", sample_rate_hz)
|
|
88
|
+
integer("min_samples", min_samples)
|
|
89
|
+
frames = lambda seconds: max(1, round(seconds * sample_rate_hz))
|
|
90
|
+
pre = frames(0.12)
|
|
91
|
+
post = max(frames(0.28), min_samples - pre - 1) if mode == "impulse" else 0
|
|
92
|
+
return cls(energy_threshold=energy_threshold,
|
|
93
|
+
min_onset_frames=1 if mode == "impulse" else frames(0.12),
|
|
94
|
+
min_offset_frames=frames(0.20),
|
|
95
|
+
min_gesture_len=min_samples if mode == "impulse" else max(min_samples, frames(0.48)),
|
|
96
|
+
max_gesture_len=max(frames(5.0), min_samples, pre + post + 1),
|
|
97
|
+
pre_roll=pre, cooldown_frames=frames(0.60), mode=mode, post_roll=post)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
@dataclass(frozen=True)
|
|
101
|
+
class RejectionCalibration:
|
|
102
|
+
"""Positive-example acceptance limits, NOT a calibrated probability of a gesture."""
|
|
103
|
+
score_floor: float
|
|
104
|
+
peak_floor: float
|
|
105
|
+
min_samples: int
|
|
106
|
+
max_samples: int
|
|
107
|
+
|
|
108
|
+
def __post_init__(self):
|
|
109
|
+
if isinstance(self.score_floor, bool) or not isinstance(self.score_floor, (int, float)) or not math.isfinite(self.score_floor):
|
|
110
|
+
raise ValueError("score_floor must be finite")
|
|
111
|
+
if isinstance(self.peak_floor, bool) or not isinstance(self.peak_floor, (int, float)) or not math.isfinite(self.peak_floor) or self.peak_floor < 0:
|
|
112
|
+
raise ValueError("peak_floor must be finite and nonnegative")
|
|
113
|
+
integer("min_samples", self.min_samples)
|
|
114
|
+
integer("max_samples", self.max_samples)
|
|
115
|
+
if self.min_samples > self.max_samples:
|
|
116
|
+
raise ValueError("calibration min_samples must not exceed max_samples")
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Shared, deterministic preprocessing for both training and inference."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import numpy as np
|
|
6
|
+
from scipy.signal import butter, medfilt, sosfilt, sosfilt_zi
|
|
7
|
+
|
|
8
|
+
from .config import PipelineConfig, integer
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def validate_samples(samples: object, *, allow_empty: bool = False) -> np.ndarray:
|
|
12
|
+
"""Validate raw IMU rows without silently wrapping out-of-range int16 data."""
|
|
13
|
+
try:
|
|
14
|
+
data = np.asarray(samples, dtype=np.float64)
|
|
15
|
+
except (TypeError, ValueError) as exc:
|
|
16
|
+
raise ValueError("Samples must be numeric rows in ax,ay,az,gx,gy,gz order") from exc
|
|
17
|
+
if allow_empty and data.shape == (0,):
|
|
18
|
+
return np.empty((0, 6), dtype=np.float64)
|
|
19
|
+
if data.ndim != 2 or data.shape[1] != 6:
|
|
20
|
+
raise ValueError("Samples must have shape (N, 6): ax,ay,az,gx,gy,gz")
|
|
21
|
+
if not allow_empty and not len(data):
|
|
22
|
+
raise ValueError("Samples must not be empty")
|
|
23
|
+
if not np.isfinite(data).all():
|
|
24
|
+
raise ValueError("Samples must contain only finite numbers")
|
|
25
|
+
if np.any(data < -32768) or np.any(data > 32767):
|
|
26
|
+
raise ValueError("Samples must use raw signed 16-bit IMU units")
|
|
27
|
+
return data
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class SignalFilter:
|
|
31
|
+
def __init__(self, sample_rate: float = 25.0, cutoff_hz: float = 10.0,
|
|
32
|
+
order: int = 2, median_kernel: int = 5, initialization: str = "zero"):
|
|
33
|
+
PipelineConfig(sample_rate_hz=sample_rate, cutoff_hz=cutoff_hz,
|
|
34
|
+
filter_order=order, median_kernel=median_kernel,
|
|
35
|
+
filter_initialization=initialization)
|
|
36
|
+
self.sample_rate = sample_rate
|
|
37
|
+
self.cutoff_hz = cutoff_hz
|
|
38
|
+
self.order = order
|
|
39
|
+
self.median_kernel = median_kernel
|
|
40
|
+
self.initialization = initialization
|
|
41
|
+
self._sos = butter(order, cutoff_hz / (sample_rate / 2), btype="low", output="sos")
|
|
42
|
+
|
|
43
|
+
def apply(self, raw: np.ndarray) -> np.ndarray:
|
|
44
|
+
data = validate_samples(raw).copy()
|
|
45
|
+
for ax in range(6):
|
|
46
|
+
if self.median_kernel > 1:
|
|
47
|
+
data[:, ax] = medfilt(data[:, ax], kernel_size=self.median_kernel)
|
|
48
|
+
if self.initialization == "steady":
|
|
49
|
+
data[:, ax], _ = sosfilt(self._sos, data[:, ax], zi=sosfilt_zi(self._sos) * data[0, ax])
|
|
50
|
+
else:
|
|
51
|
+
data[:, ax] = sosfilt(self._sos, data[:, ax])
|
|
52
|
+
return data
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class FeatureExtractor:
|
|
56
|
+
def __init__(self, window_size: int = 8, overlap: int = 4):
|
|
57
|
+
integer("window_size", window_size, 2)
|
|
58
|
+
integer("overlap", overlap, 0)
|
|
59
|
+
if overlap >= window_size:
|
|
60
|
+
raise ValueError("overlap must be smaller than window_size")
|
|
61
|
+
self.window_size = window_size
|
|
62
|
+
self.overlap = overlap
|
|
63
|
+
|
|
64
|
+
def extract(self, filtered: np.ndarray) -> np.ndarray:
|
|
65
|
+
data = np.asarray(filtered, dtype=np.float64)
|
|
66
|
+
if data.ndim != 2 or data.shape[1] != 6 or not np.isfinite(data).all():
|
|
67
|
+
raise ValueError("Filtered data must have shape (N, 6) and be finite")
|
|
68
|
+
frames = []
|
|
69
|
+
for start in range(0, len(data) - self.window_size + 1, self.window_size - self.overlap):
|
|
70
|
+
window = data[start:start + self.window_size]
|
|
71
|
+
mean = window.mean(axis=0)
|
|
72
|
+
var = window.var(axis=0)
|
|
73
|
+
rms = np.sqrt(np.mean(window ** 2, axis=0))
|
|
74
|
+
zcr = np.count_nonzero(np.diff(np.sign(window), axis=0), axis=0) / self.window_size
|
|
75
|
+
frames.append(np.concatenate([mean, var, rms, zcr]))
|
|
76
|
+
return np.asarray(frames) if frames else np.empty((0, 24))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def make_pipeline(config: PipelineConfig) -> tuple[SignalFilter, FeatureExtractor]:
|
|
80
|
+
return (SignalFilter(config.sample_rate_hz, config.cutoff_hz,
|
|
81
|
+
config.filter_order, config.median_kernel, config.filter_initialization),
|
|
82
|
+
FeatureExtractor(config.window_size, config.window_overlap))
|
|
File without changes
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Public inference API: no GUI, BLE SDK, or training-platform imports."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import asdict, dataclass, replace
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
import math
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from .bundle import GestureBundle
|
|
12
|
+
from .preprocessing import make_pipeline, validate_samples
|
|
13
|
+
from .segmentation import MotionSegmenter, impulse_peak, prepare_recording
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass(frozen=True)
|
|
17
|
+
class Prediction:
|
|
18
|
+
name: str
|
|
19
|
+
confidence: float | None # No comparative confidence exists with only one label.
|
|
20
|
+
score: float
|
|
21
|
+
scores: dict[str, float]
|
|
22
|
+
# Half-open indices in the feed() stream since reset(); None for predict().
|
|
23
|
+
start_sample: int | None = None
|
|
24
|
+
end_sample: int | None = None
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class GestureRecognizer:
|
|
28
|
+
"""Classify recorded segments or consume continuous raw six-axis batches.
|
|
29
|
+
|
|
30
|
+
Confidence is a relative score-gap heuristic, NOT a calibrated probability
|
|
31
|
+
or unknown-gesture detector. With one model it is None, never a fixed 0.8.
|
|
32
|
+
Calibrated bundles additionally reject implausible scores/strengths/lengths.
|
|
33
|
+
A single uncalibrated model cannot be used for automatic stream detection.
|
|
34
|
+
Instances maintain stream state and should not be shared across threads.
|
|
35
|
+
"""
|
|
36
|
+
def __init__(self, bundle: GestureBundle, min_confidence: float = 0.0):
|
|
37
|
+
if not math.isfinite(min_confidence) or not 0 <= min_confidence <= 1:
|
|
38
|
+
raise ValueError("min_confidence must be between 0 and 1")
|
|
39
|
+
self.bundle = bundle
|
|
40
|
+
self.min_confidence = min_confidence
|
|
41
|
+
self.filter, self.extractor = make_pipeline(bundle.pipeline)
|
|
42
|
+
self.segmenter = MotionSegmenter(**asdict(bundle.segmentation))
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def load(cls, path: str | Path, *, min_confidence: float = 0.0) -> GestureRecognizer:
|
|
46
|
+
return cls(GestureBundle.load(path), min_confidence=min_confidence)
|
|
47
|
+
|
|
48
|
+
@property
|
|
49
|
+
def gesture_names(self) -> tuple[str, ...]:
|
|
50
|
+
return self.bundle.gesture_names
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def sample_rate_hz(self) -> float:
|
|
54
|
+
return self.bundle.pipeline.sample_rate_hz
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def has_rejection(self) -> bool:
|
|
58
|
+
return self.bundle.rejection is not None
|
|
59
|
+
|
|
60
|
+
def reset(self) -> None:
|
|
61
|
+
"""Reset stream state and baseline, e.g. after disconnect/reconnect."""
|
|
62
|
+
self.segmenter.reset()
|
|
63
|
+
|
|
64
|
+
def _check_rate(self, sample_rate_hz: float | None) -> None:
|
|
65
|
+
if sample_rate_hz is not None and sample_rate_hz != self.sample_rate_hz:
|
|
66
|
+
raise ValueError(f"Expected {self.sample_rate_hz:g} Hz, received {sample_rate_hz} Hz; no automatic resampling")
|
|
67
|
+
|
|
68
|
+
def predict(self, samples: object, *, sample_rate_hz: float | None = None) -> Prediction | None:
|
|
69
|
+
"""Classify a complete (N, 6) gesture; return None if too short/rejected."""
|
|
70
|
+
self._check_rate(sample_rate_hz)
|
|
71
|
+
data = validate_samples(samples, allow_empty=True)
|
|
72
|
+
if len(data) < self.bundle.pipeline.min_samples:
|
|
73
|
+
return None
|
|
74
|
+
data = prepare_recording(data, self.bundle.segmentation)
|
|
75
|
+
return self._predict_segment(data) if data is not None else None
|
|
76
|
+
|
|
77
|
+
def _predict_segment(self, data: np.ndarray) -> Prediction | None:
|
|
78
|
+
if len(data) < self.bundle.pipeline.min_samples:
|
|
79
|
+
return None
|
|
80
|
+
features = self.extractor.extract(self.filter.apply(data))
|
|
81
|
+
scores = {}
|
|
82
|
+
for name, model in self.bundle.models.items():
|
|
83
|
+
score = float(model.score(features))
|
|
84
|
+
if np.isfinite(score):
|
|
85
|
+
scores[name] = score
|
|
86
|
+
if not scores:
|
|
87
|
+
return None
|
|
88
|
+
ranked = sorted(scores, key=scores.get, reverse=True)
|
|
89
|
+
best = ranked[0]
|
|
90
|
+
# Scores are per feature frame for comparability across segment lengths.
|
|
91
|
+
normalized = {name: score / len(features) for name, score in scores.items()}
|
|
92
|
+
if self.bundle.rejection is not None:
|
|
93
|
+
limits = self.bundle.rejection[best]
|
|
94
|
+
if (not limits.min_samples <= len(data) <= limits.max_samples
|
|
95
|
+
or normalized[best] < limits.score_floor
|
|
96
|
+
or impulse_peak(data) < limits.peak_floor):
|
|
97
|
+
return None
|
|
98
|
+
confidence = None if len(ranked) == 1 else float(-np.expm1(-(scores[best] - scores[ranked[1]]) / 10.0))
|
|
99
|
+
if ((confidence is None and self.min_confidence > 0)
|
|
100
|
+
or (confidence is not None and confidence < self.min_confidence)):
|
|
101
|
+
return None
|
|
102
|
+
return Prediction(best, confidence, normalized[best], normalized)
|
|
103
|
+
|
|
104
|
+
def feed(self, samples: object, *, sample_rate_hz: float | None = None) -> list[Prediction]:
|
|
105
|
+
"""Consume a batch, returning ALL completed predictions (possibly none).
|
|
106
|
+
|
|
107
|
+
Feed some resting samples first to establish the motion baseline. A
|
|
108
|
+
trailing rest ends a gesture; incomplete segments are not auto-flushed.
|
|
109
|
+
"""
|
|
110
|
+
self._check_rate(sample_rate_hz)
|
|
111
|
+
data = validate_samples(samples, allow_empty=True)
|
|
112
|
+
if not len(data):
|
|
113
|
+
return []
|
|
114
|
+
if len(self.bundle.models) == 1 and not self.has_rejection:
|
|
115
|
+
raise ValueError("单类模型缺少拒识标定,无法区分普通运动;请用至少 3 次录制重新训练并开启拒识标定")
|
|
116
|
+
results = []
|
|
117
|
+
for segment in self.segmenter.feed_segments(data):
|
|
118
|
+
prediction = self._predict_segment(segment.samples)
|
|
119
|
+
if prediction is not None:
|
|
120
|
+
results.append(replace(prediction, start_sample=segment.start_sample,
|
|
121
|
+
end_sample=segment.end_sample))
|
|
122
|
+
return results
|