File size: 7,957 Bytes
375924d
 
 
56a15bc
375924d
 
 
 
 
56a15bc
375924d
 
ce51e88
375924d
8539a00
375924d
948a968
 
375924d
948a968
 
8539a00
375924d
948a968
56a15bc
948a968
 
 
 
 
 
 
 
 
 
375924d
948a968
375924d
 
c269c95
375924d
 
8539a00
ce51e88
948a968
9a82bce
375924d
 
 
 
 
56a15bc
948a968
56a15bc
375924d
 
 
 
 
 
 
 
 
 
948a968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375924d
 
 
948a968
375924d
 
 
 
 
 
 
 
948a968
56a15bc
 
375924d
948a968
375924d
ce51e88
375924d
 
 
c269c95
375924d
c269c95
56a15bc
 
 
 
948a968
af222c8
375924d
c269c95
948a968
c269c95
9a82bce
 
948a968
9a82bce
 
375924d
 
948a968
 
 
 
375924d
 
56a15bc
 
 
8539a00
 
 
 
 
 
 
 
 
375924d
 
 
8539a00
 
 
 
 
 
 
948a968
8539a00
 
 
 
 
948a968
 
 
 
1f17a48
948a968
 
 
 
 
 
 
 
1f17a48
948a968
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375924d
 
 
 
 
 
 
 
ce51e88
 
 
 
375924d
948a968
 
375924d
ce51e88
 
 
 
c269c95
ce51e88
 
8539a00
ce51e88
948a968
9a82bce
ce51e88
375924d
 
ce51e88
 
 
 
 
 
 
 
 
 
375924d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import { useRef, useCallback, useState, useEffect } from "react";
import {
  FaceLandmarker,
  GestureRecognizer,
  FilesetResolver,
} from "@mediapipe/tasks-vision";
import type { SensingState } from "../types";
import {
  classifyAffect,
  mapGestureLabel,
  GazeTracker,
  AirWriter,
  HeadPoseTracker,
} from "../lib/sensing";
import { recognizeInkStroke } from "../lib/inkRecognizer";

const GESTURE_DEBOUNCE_FRAMES = 3;
const AFFECT_DEBOUNCE_FRAMES  = 8;

const AIRWRITING_ENABLED = import.meta.env.VITE_AIRWRITING_ENABLED !== "false";
const GAZE_ENABLED       = import.meta.env.VITE_GAZE_ENABLED !== "false";

export function useSensing() {
  const faceLandmarkerRef    = useRef<FaceLandmarker | null>(null);
  const gestureRecognizerRef = useRef<GestureRecognizer | null>(null);
  const gazeTrackerRef  = useRef(new GazeTracker());
  const airWriterRef    = useRef(new AirWriter());
  const inkBusyRef      = useRef(false);
  const headTrackerRef  = useRef(new HeadPoseTracker());
  const headDebugRef    = useRef({ pitch: 0, yaw: 0, roll: 0, crossings: 0 });
  const gestureCountRef = useRef<{ tag: SensingState["gestureTag"]; count: number }>({ tag: null, count: 0 });
  const affectCountRef  = useRef<{ affect: SensingState["affect"]; count: number }>({ affect: null, count: 0 });
  const initingRef      = useRef(false);

  const [ready, setReady]       = useState(false);
  const [initError, setInitError] = useState<string | null>(null);
  const [sensing, setSensing]   = useState<SensingState>({
    affect: null,
    gestureTag: null,
    gazeZone: null,
    gazeBucket: null,
    airWrittenText: "",
    airWritingActive: false,
    headSignal: null,
    headCalibrated: false,
    headDebug: { pitch: 0, yaw: 0, roll: 0, crossings: 0 },
  });

  useEffect(() => {
    return () => {
      faceLandmarkerRef.current?.close();
      gestureRecognizerRef.current?.close();
      faceLandmarkerRef.current    = null;
      gestureRecognizerRef.current = null;
    };
  }, []);

  const init = useCallback(async (): Promise<boolean> => {
    if (faceLandmarkerRef.current || initingRef.current) return true;
    initingRef.current = true;
    try {
      const vision = await FilesetResolver.forVisionTasks(
        "https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm"
      );
      faceLandmarkerRef.current = await FaceLandmarker.createFromOptions(vision, {
        baseOptions: {
          modelAssetPath:
            "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task",
          delegate: "GPU",
        },
        runningMode: "VIDEO",
        numFaces: 1,
        outputFaceBlendshapes: true,
        outputFacialTransformationMatrixes: true,
      });
      gestureRecognizerRef.current = await GestureRecognizer.createFromOptions(vision, {
        baseOptions: {
          modelAssetPath:
            "https://storage.googleapis.com/mediapipe-models/gesture_recognizer/gesture_recognizer/float16/1/gesture_recognizer.task",
          delegate: "GPU",
        },
        runningMode: "VIDEO",
        numHands: 1,
      });
      setReady(true);
      return true;
    } catch (e) {
      setInitError(e instanceof Error ? e.message : "Failed to load MediaPipe models");
      return false;
    } finally {
      initingRef.current = false;
    }
  }, []);

  const processFrame = useCallback(
    (video: HTMLVideoElement, timestamp: number) => {
      const faceLandmarker    = faceLandmarkerRef.current;
      const gestureRecognizer = gestureRecognizerRef.current;
      if (!faceLandmarker || !gestureRecognizer) return;

      let affect: SensingState["affect"]       = null;
      let gazeBucket: SensingState["gazeBucket"] = null;
      let headSignal: SensingState["headSignal"] = null;

      const faceResult = faceLandmarker.detectForVideo(video, timestamp);
      if (faceResult.faceLandmarks && faceResult.faceLandmarks.length > 0) {
        const matrix = faceResult.facialTransformationMatrixes?.[0] ?? null;

        const bs: Record<string, number> = {};
        if (faceResult.faceBlendshapes && faceResult.faceBlendshapes.length > 0) {
          for (const cat of faceResult.faceBlendshapes[0].categories) {
            bs[cat.categoryName] = cat.score;
          }
          affect = classifyAffect(bs);
        }

        if (GAZE_ENABLED) {
          gazeBucket = gazeTrackerRef.current.process(matrix, bs);
        }

        if (matrix) {
          headSignal = headTrackerRef.current.process(matrix);
          headDebugRef.current = headTrackerRef.current.debug;
        }
      }

      // Always call recognizeForVideo every frame — VIDEO-mode models maintain
      // internal temporal state and produce stale results if frames are skipped.
      const gestureResult = gestureRecognizer.recognizeForVideo(video, timestamp);

      let gestureTag: SensingState["gestureTag"] = null;

      if (gestureResult.gestures && gestureResult.gestures.length > 0) {
        const topGesture = gestureResult.gestures[0][0];
        gestureTag = mapGestureLabel(topGesture.categoryName);
        if (AIRWRITING_ENABLED) {
          const handLandmarks = gestureResult.landmarks[0];
          airWriterRef.current.processHandLandmarks(
            handLandmarks,
            video.videoWidth,
            video.videoHeight
          );
        }
      } else if (AIRWRITING_ENABLED) {
        airWriterRef.current.noHand();
      }

      if (AIRWRITING_ENABLED) {
        const completedStroke = airWriterRef.current.getCompletedStroke();
        if (completedStroke && !inkBusyRef.current) {
          inkBusyRef.current = true;
          recognizeInkStroke(completedStroke).then((text) => {
            inkBusyRef.current = false;
            if (text) {
              setSensing((prev) => ({ ...prev, airWrittenText: prev.airWrittenText + text }));
            }
          });
        }
      }

      if (gestureTag === gestureCountRef.current.tag) {
        gestureCountRef.current.count++;
      } else {
        gestureCountRef.current = { tag: gestureTag, count: 1 };
      }
      const stableGesture = gestureCountRef.current.count >= GESTURE_DEBOUNCE_FRAMES
        ? gestureTag
        : null;

      if (affect === affectCountRef.current.affect) {
        affectCountRef.current.count++;
      } else {
        affectCountRef.current = { affect, count: 1 };
      }
      const stableAffect = affectCountRef.current.count >= AFFECT_DEBOUNCE_FRAMES
        ? affect
        : null;

      setSensing((prev) => ({
        affect: stableAffect ?? prev.affect,
        gestureTag: stableGesture,
        gazeZone: GAZE_ENABLED ? gazeTrackerRef.current.activeZone : null,
        gazeBucket: gazeBucket ?? prev.gazeBucket,
        airWrittenText: prev.airWrittenText,
        airWritingActive: airWriterRef.current.strokeActive,
        headSignal: headSignal ?? prev.headSignal,
        headCalibrated: headTrackerRef.current.calibrated,
        headDebug: headDebugRef.current,
      }));
    },
    []
  );

  const clearAirWrittenText = useCallback(() => {
    setSensing((prev) => ({ ...prev, airWrittenText: "" }));
  }, []);

  const clearHeadSignal = useCallback(() => {
    setSensing((prev) => ({ ...prev, headSignal: null }));
  }, []);

  const resetCalibration = useCallback(() => {
    gestureCountRef.current = { tag: null, count: 0 };
    affectCountRef.current  = { affect: null, count: 0 };
    gazeTrackerRef.current.reset();
    headTrackerRef.current.reset();
    setSensing({
      affect: null,
      gestureTag: null,
      gazeZone: null,
      gazeBucket: null,
      airWrittenText: "",
      airWritingActive: false,
      headSignal: null,
      headCalibrated: false,
      headDebug: { pitch: 0, yaw: 0, roll: 0, crossings: 0 },
    });
  }, []);

  return {
    sensing,
    ready,
    initError,
    init,
    processFrame,
    clearAirWrittenText,
    clearHeadSignal,
    resetCalibration,
  };
}