hand-guest-control 0.1.0 → 0.3.0

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.
@@ -1,276 +0,0 @@
1
- import { HAND_STATES, LANDMARKS, DEFAULT_CONFIG } from './constants.js';
2
- import { HandGestureDetector } from './HandGestureDetector.js';
3
-
4
- export class HandStateManager {
5
- constructor(config = {}) {
6
- this.config = { ...DEFAULT_CONFIG, ...config };
7
- this.gestureDetector = new HandGestureDetector(this.config);
8
-
9
- this.initializeState();
10
- }
11
-
12
- initializeState() {
13
- this.histories = {
14
- centroid: new Array(this.config.maxCentroidHistorySize).fill(null),
15
- landmark0: new Array(this.config.maxHistorySize).fill(null),
16
- open: new Array(this.config.minOpenConfidence).fill(false),
17
- pointing: new Array(this.config.minPointingConfidence).fill(false),
18
- flipping: new Array(this.config.minFlippingConfidence).fill(false),
19
- closed: new Array(this.config.minClosedConfidence).fill(false)
20
- };
21
-
22
- this.indices = {
23
- history: 0,
24
- centroid: 0,
25
- open: 0,
26
- pointing: 0,
27
- flipping: 0,
28
- closed: 0
29
- };
30
-
31
- this.resetTrackingState();
32
- }
33
-
34
- resetTrackingState() {
35
- this.prevLandmark0 = null;
36
- this.lastActionTime = 0;
37
- this.pointingCount = 0;
38
- this.flippingCount = 0;
39
- this.detectionPausedUntil = 0;
40
- this.noDetectionStartTime = 0;
41
- this.lastDetectionTime = 0;
42
- this.lastState = null;
43
- }
44
-
45
- calculateCentroid(landmarks, now) {
46
- if (!landmarks?.length) {
47
- return { x: 0, y: 0 };
48
- }
49
-
50
- const landmark0 = landmarks[LANDMARKS.WRIST] || landmarks[0];
51
- this.histories.landmark0[this.indices.history] = {
52
- x: landmark0.x,
53
- y: landmark0.y,
54
- time: now
55
- };
56
- this.indices.history = (this.indices.history + 1) % this.config.maxHistorySize;
57
-
58
- const validPoints = this.histories.landmark0.filter(Boolean);
59
- if (!validPoints.length) {
60
- return { x: landmark0.x, y: landmark0.y };
61
- }
62
-
63
- const sum = validPoints.reduce(
64
- (acc, p) => ({ x: acc.x + p.x, y: acc.y + p.y }),
65
- { x: 0, y: 0 }
66
- );
67
-
68
- return {
69
- x: sum.x / validPoints.length,
70
- y: sum.y / validPoints.length
71
- };
72
- }
73
-
74
- getRotation(landmarks, centroid) {
75
- if (!landmarks?.[LANDMARKS.MIDDLE_TIP]) {
76
- return [0, 0, 0];
77
- }
78
-
79
- const handSize = HandGestureDetector.getDistance(
80
- landmarks[LANDMARKS.WRIST],
81
- landmarks[LANDMARKS.THUMB_TIP]
82
- ) || 0.15;
83
-
84
- const scaleFactor = 0.15 / handSize;
85
- const delta = this.prevLandmark0 ? {
86
- x: (centroid.x - this.prevLandmark0.x) * scaleFactor,
87
- y: (centroid.y - this.prevLandmark0.y) * scaleFactor
88
- } : { x: 0, y: 0 };
89
-
90
- this.prevLandmark0 = { x: centroid.x, y: centroid.y };
91
-
92
- return [
93
- delta.y * this.config.rotationSensitivity,
94
- delta.x * this.config.rotationSensitivity,
95
- 0
96
- ];
97
- }
98
-
99
- handleNoDetection(now) {
100
- this.pointingCount = 0;
101
- this.flippingCount = 0;
102
-
103
- if (!this.noDetectionStartTime) {
104
- this.noDetectionStartTime = now;
105
- }
106
-
107
- const noDetectionDuration = now - this.noDetectionStartTime;
108
-
109
- if (noDetectionDuration < this.config.detectionTolerance) {
110
- return { state: this.lastState || HAND_STATES.NOT_DETECTED, rotation: [0, 0, 0] };
111
- }
112
-
113
- if (noDetectionDuration >= this.config.waitingTimeout) {
114
- this.lastState = HAND_STATES.WAITING;
115
- if (this.config.debug) {
116
- console.log(`Transitioned to WAITING after ${this.config.waitingTimeout / 1000}s`);
117
- }
118
- return { state: HAND_STATES.WAITING, rotation: [0, 0, 0] };
119
- }
120
-
121
- this.lastState = HAND_STATES.NOT_DETECTED;
122
- if (this.config.debug) {
123
- console.log(`Transitioned to NOT_DETECTED after ${this.config.detectionTolerance / 1000}s`);
124
- }
125
- return { state: HAND_STATES.NOT_DETECTED, rotation: [0, 0, 0] };
126
- }
127
-
128
- handleDetectionReconnection(now) {
129
- const isWaitingOrNotDetected = [HAND_STATES.WAITING, HAND_STATES.NOT_DETECTED].includes(this.lastState);
130
- const isReconnection = ![HAND_STATES.WAITING, HAND_STATES.NOT_DETECTED, HAND_STATES.STARTING].includes(this.lastState) &&
131
- now - this.lastDetectionTime <= this.config.detectionTolerance;
132
-
133
- if (isReconnection) {
134
- if (this.config.debug) {
135
- console.log(`Short reconnection (${(now - this.lastDetectionTime) / 1000}s), continuing with last state: ${this.lastState}`);
136
- }
137
- } else if (isWaitingOrNotDetected) {
138
- this.detectionPausedUntil = now + this.config.startingDelay;
139
- this.noDetectionStartTime = 0;
140
- this.lastState = HAND_STATES.STARTING;
141
- return { state: HAND_STATES.STARTING, rotation: [0, 0, 0] };
142
- }
143
-
144
- return null;
145
- }
146
-
147
- determineHandState(distances) {
148
- if (this.gestureDetector.checkSwipeNext(
149
- this.histories.landmark0, distances, this.histories, this.indices,
150
- this.pointingCount, this.lastActionTime
151
- )) {
152
- this.resetSwipeState();
153
- return HAND_STATES.SWIPE_NEXT;
154
- }
155
-
156
- if (this.gestureDetector.checkSwipePrevious(
157
- this.histories.landmark0, distances, this.histories, this.indices,
158
- this.pointingCount, this.lastActionTime
159
- )) {
160
- this.resetSwipeState();
161
- return HAND_STATES.SWIPE_PREVIOUS;
162
- }
163
-
164
- if (this.gestureDetector.isFlipping(distances, this.histories, this.indices)) {
165
- return HAND_STATES.FLIPPING;
166
- }
167
-
168
- if (this.gestureDetector.checkClosedHand(distances, this.histories, this.indices)) {
169
- return HAND_STATES.CLOSED;
170
- }
171
-
172
- if (this.gestureDetector.checkOpenHand(distances, this.histories, this.indices)) {
173
- return HAND_STATES.OPEN;
174
- }
175
-
176
- if (this.gestureDetector.isPointing(distances, this.histories, this.indices)) {
177
- return HAND_STATES.POINTING;
178
- }
179
-
180
- return HAND_STATES.CLOSED;
181
- }
182
-
183
- resetSwipeState() {
184
- this.histories.landmark0.fill(null);
185
- this.indices.history = 0;
186
- this.lastActionTime = Date.now();
187
- this.pointingCount = 0;
188
- this.flippingCount = 0;
189
- }
190
-
191
- validateStateTransition(newState) {
192
- const validTransitionStates = [HAND_STATES.OPEN, HAND_STATES.POINTING, HAND_STATES.CLOSED, HAND_STATES.FLIPPING];
193
-
194
- if (newState === this.lastState || !validTransitionStates.includes(newState)) {
195
- return newState;
196
- }
197
-
198
- const historyKeys = {
199
- [HAND_STATES.OPEN]: 'open',
200
- [HAND_STATES.POINTING]: 'pointing',
201
- [HAND_STATES.CLOSED]: 'closed',
202
- [HAND_STATES.FLIPPING]: 'flipping'
203
- };
204
-
205
- const historyKey = historyKeys[newState];
206
- if (!historyKey) return newState;
207
-
208
- const requiredConfidence = this.config[`min${historyKey.charAt(0).toUpperCase() + historyKey.slice(1)}Confidence`];
209
- const actualConfidence = this.histories[historyKey].filter(Boolean).length;
210
-
211
- if (actualConfidence < requiredConfidence * 0.9) {
212
- return this.lastState;
213
- }
214
-
215
- return newState;
216
- }
217
-
218
- clearAllHistory() {
219
- Object.values(this.histories).forEach((history) => history.fill(null));
220
- Object.keys(this.indices).forEach((key) => { this.indices[key] = 0; });
221
- this.resetTrackingState();
222
- }
223
-
224
- processLandmarks(landmarks) {
225
- const now = Date.now();
226
-
227
- if (this.detectionPausedUntil > now) {
228
- if (this.config.debug) {
229
- console.log(`In STARTING state until ${new Date(this.detectionPausedUntil).toLocaleTimeString()}`);
230
- }
231
- return { state: HAND_STATES.STARTING, rotation: [0, 0, 0] };
232
- }
233
-
234
- if (!landmarks?.[LANDMARKS.PINKY_TIP]) {
235
- return this.handleNoDetection(now);
236
- }
237
-
238
- this.lastDetectionTime = now;
239
- const reconnectionResult = this.handleDetectionReconnection(now);
240
- if (reconnectionResult) {
241
- return reconnectionResult;
242
- }
243
-
244
- this.noDetectionStartTime = 0;
245
- this.detectionPausedUntil = 0;
246
-
247
- const distances = this.gestureDetector.computeDistances(landmarks);
248
- const centroid = this.calculateCentroid(landmarks, now);
249
-
250
- this.histories.centroid[this.indices.centroid] = { x: centroid.x, y: centroid.y, time: now };
251
- this.indices.centroid = (this.indices.centroid + 1) % this.config.maxCentroidHistorySize;
252
-
253
- const rotation = this.getRotation(landmarks, centroid);
254
-
255
- this.pointingCount += this.gestureDetector.isPointing(distances, this.histories, this.indices) ? 1 : 0;
256
- this.flippingCount += this.gestureDetector.isFlipping(distances, this.histories, this.indices) ? 1 : 0;
257
-
258
- let newState = this.determineHandState(distances);
259
- newState = this.validateStateTransition(newState);
260
-
261
- this.lastState = newState;
262
-
263
- const rotationDisabledStates = [
264
- HAND_STATES.POINTING,
265
- HAND_STATES.SWIPE_NEXT,
266
- HAND_STATES.SWIPE_PREVIOUS,
267
- HAND_STATES.FLIPPING
268
- ];
269
-
270
- if (rotationDisabledStates.includes(newState)) {
271
- rotation.fill(0);
272
- }
273
-
274
- return { state: newState, rotation };
275
- }
276
- }
package/src/constants.js DELETED
@@ -1,52 +0,0 @@
1
- export const HAND_STATES = {
2
- NOT_DETECTED: 'not_detected',
3
- WAITING: 'waiting',
4
- STARTING: 'starting',
5
- OPEN: 'open',
6
- CLOSED: 'closed',
7
- POINTING: 'pointing',
8
- FLIPPING: 'flipping',
9
- SWIPE_NEXT: 'swipe_next',
10
- SWIPE_PREVIOUS: 'swipe_previous'
11
- };
12
-
13
- export const LANDMARKS = {
14
- WRIST: 0,
15
- THUMB_TIP: 4,
16
- INDEX_TIP: 8,
17
- MIDDLE_TIP: 12,
18
- RING_TIP: 16,
19
- PINKY_TIP: 20
20
- };
21
-
22
- export const HAND_CONNECTIONS = [
23
- [0, 1], [1, 2], [2, 3], [3, 4],
24
- [0, 5], [5, 6], [6, 7], [7, 8],
25
- [0, 9], [9, 10], [10, 11], [11, 12],
26
- [0, 13], [13, 14], [14, 15], [15, 16],
27
- [0, 17], [17, 18], [18, 19], [19, 20],
28
- [5, 9], [9, 13], [13, 17]
29
- ];
30
-
31
- export const DEFAULT_CONFIG = {
32
- maxHistorySize: 10,
33
- maxCentroidHistorySize: 10,
34
- rotationSensitivity: 4,
35
- detectionTolerance: 2000,
36
- startingDelay: 1000,
37
- waitingTimeout: 3000,
38
- minOpenConfidence: 5,
39
- minPointingConfidence: 25,
40
- minFlippingConfidence: 25,
41
- minClosedConfidence: 5,
42
- minPointingCount: 5,
43
- pointingThreshold: 0.3,
44
- openHandThresholds: {
45
- fingerSpread: 0.2,
46
- indexToMiddle: 0.15,
47
- minExtendedFingers: 4,
48
- maxExtendedFingers: 6,
49
- middleAngle: 50
50
- },
51
- debug: false
52
- };
package/src/index.js DELETED
@@ -1,9 +0,0 @@
1
- export {
2
- HAND_STATES,
3
- LANDMARKS,
4
- HAND_CONNECTIONS,
5
- DEFAULT_CONFIG
6
- } from './constants.js';
7
-
8
- export { HandGestureDetector } from './HandGestureDetector.js';
9
- export { HandStateManager } from './HandStateManager.js';
package/src/mediapipe.js DELETED
@@ -1,59 +0,0 @@
1
- import { HandLandmarker, FilesetResolver } from '@mediapipe/tasks-vision';
2
-
3
- export const DEFAULT_MEDIAPIPE_CONFIG = {
4
- wasmPath: 'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.0/wasm',
5
- modelPath: 'https://storage.googleapis.com/mediapipe-models/hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task'
6
- };
7
-
8
- export const DEFAULT_DETECTION_CONFIG = {
9
- runningMode: 'VIDEO',
10
- numHands: 1,
11
- minHandDetectionConfidence: 0.6,
12
- minHandPresenceConfidence: 0.6,
13
- minTrackingConfidence: 0.5
14
- };
15
-
16
- /**
17
- * Create a MediaPipe HandLandmarker with GPU fallback to CPU.
18
- * @param {object} [options]
19
- * @param {string} [options.wasmPath]
20
- * @param {string} [options.modelPath]
21
- * @param {import('@mediapipe/tasks-vision').RunningMode} [options.runningMode]
22
- * @param {number} [options.numHands]
23
- * @param {number} [options.minHandDetectionConfidence]
24
- * @param {number} [options.minHandPresenceConfidence]
25
- * @param {number} [options.minTrackingConfidence]
26
- */
27
- export async function createHandLandmarker(options = {}) {
28
- const config = {
29
- ...DEFAULT_MEDIAPIPE_CONFIG,
30
- ...DEFAULT_DETECTION_CONFIG,
31
- ...options
32
- };
33
-
34
- const vision = await FilesetResolver.forVisionTasks(config.wasmPath);
35
-
36
- const landmarkerOptions = {
37
- baseOptions: {
38
- modelAssetPath: config.modelPath,
39
- delegate: 'GPU'
40
- },
41
- runningMode: config.runningMode,
42
- numHands: config.numHands,
43
- minHandDetectionConfidence: config.minHandDetectionConfidence,
44
- minHandPresenceConfidence: config.minHandPresenceConfidence,
45
- minTrackingConfidence: config.minTrackingConfidence
46
- };
47
-
48
- try {
49
- return await HandLandmarker.createFromOptions(vision, landmarkerOptions);
50
- } catch (gpuError) {
51
- console.warn('GPU delegate failed, falling back to CPU:', gpuError);
52
- return HandLandmarker.createFromOptions(vision, {
53
- ...landmarkerOptions,
54
- baseOptions: {
55
- modelAssetPath: config.modelPath
56
- }
57
- });
58
- }
59
- }