@hackbuild/vision 0.0.0-stage → 0.1.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.
@@ -0,0 +1,294 @@
1
+ /**
2
+ * Perception signals: raw per frame face and hand readings become steady
3
+ * signals (present, facing, smile, surprise, frown, gesture) and a few
4
+ * discrete events (arrived, left, smiled, gesture). Everything is smoothed
5
+ * or held for a moment, so one noisy frame never fires a reaction.
6
+ *
7
+ * `SignalTracker.feed(raw, now)` is pure apart from its own state: the
8
+ * clock comes in with each frame. `rawFromLandmarks` builds a frame from
9
+ * the `landmarks` results of this package (face points plus blendshapes,
10
+ * and optional hands from the gesture recognizer or the hand landmarker).
11
+ * Hands are optional; the tracker runs on faces alone.
12
+ *
13
+ * `SeenNotes` turns the signals into one short lowercase line for a
14
+ * language model, written only when it changed. Frames never leave the
15
+ * tab: only these signals and the text made from them do.
16
+ *
17
+ * Thresholds below are vendor figures from earlier builds; none was
18
+ * measured here.
19
+ */
20
+ // all vendor
21
+ const PRESENT_GRACE_MS = 2500;
22
+ const LEFT_AFTER_MS = 8000;
23
+ const ARRIVE_AFTER_ABSENCE_MS = 20000;
24
+ const SMILE_ON = 0.55;
25
+ const SMILE_OFF = 0.3;
26
+ const SMILE_HOLD_MS = 500;
27
+ const SMILE_COOLDOWN_MS = 10000;
28
+ const GESTURE_HOLD_MS = 350;
29
+ const GESTURE_COOLDOWN_MS = 4000;
30
+ const GESTURE_MIN_SCORE = 0.6;
31
+ const WAVE_WINDOW_MS = 1500;
32
+ const WAVE_SWING = 0.035;
33
+ const WAVE_REVERSALS = 2;
34
+ const EASE = 0.35;
35
+ const FACING_YAW = 0.22;
36
+ const FACING_PITCH = 0.3;
37
+ /** Canned recognizer labels to gesture names. */
38
+ export const CANNED_GESTURES = {
39
+ Open_Palm: "open_palm",
40
+ Thumb_Up: "thumbs_up",
41
+ Thumb_Down: "thumbs_down",
42
+ Victory: "victory",
43
+ Pointing_Up: "pointing_up",
44
+ Closed_Fist: "fist",
45
+ ILoveYou: "love",
46
+ };
47
+ const absent = () => ({ present: false, face: null, facing: false, smile: 0, surprise: 0, frown: 0, gesture: null });
48
+ export class SignalTracker {
49
+ p = absent();
50
+ lastSeen = -Infinity;
51
+ absentSince = -Infinity;
52
+ announced = false;
53
+ smileSince = null;
54
+ smiling = false;
55
+ lastSmile = -Infinity;
56
+ held = null;
57
+ lastGesture = new Map();
58
+ wrist = [];
59
+ get perception() {
60
+ return this.p;
61
+ }
62
+ /** Feed one frame; returns the events it fired, usually none. */
63
+ feed(raw, now) {
64
+ const events = [];
65
+ this.trackFace(raw.face, now, events);
66
+ if (raw.hands)
67
+ this.trackHands(raw.hands, now, events);
68
+ this.p = { ...this.p };
69
+ return events;
70
+ }
71
+ reset() {
72
+ this.p = absent();
73
+ this.lastSeen = this.absentSince = this.lastSmile = -Infinity;
74
+ this.announced = this.smiling = false;
75
+ this.smileSince = null;
76
+ this.held = null;
77
+ this.lastGesture.clear();
78
+ this.wrist = [];
79
+ }
80
+ trackFace(f, now, events) {
81
+ const p = this.p;
82
+ if (f) {
83
+ if (!p.present && now - this.absentSince > ARRIVE_AFTER_ABSENCE_MS)
84
+ events.push({ type: "arrived" });
85
+ this.lastSeen = now;
86
+ p.present = true;
87
+ this.announced = true;
88
+ // the person's right side shows on the image left, which is the character's left too
89
+ const x = (0.5 - f.x) * 2;
90
+ const y = (0.5 - f.y) * 2;
91
+ p.face = p.face ? { x: p.face.x + (x - p.face.x) * EASE, y: p.face.y + (y - p.face.y) * EASE } : { x, y };
92
+ p.facing = Math.abs(f.yaw) < FACING_YAW && Math.abs(f.pitch) < FACING_PITCH;
93
+ p.smile += (f.smile - p.smile) * EASE;
94
+ p.surprise += (f.surprise - p.surprise) * EASE;
95
+ p.frown += (f.frown - p.frown) * EASE;
96
+ }
97
+ else if (p.present && now - this.lastSeen > PRESENT_GRACE_MS) {
98
+ p.present = false;
99
+ p.face = null;
100
+ p.facing = false;
101
+ p.smile = p.surprise = p.frown = 0;
102
+ this.absentSince = this.lastSeen;
103
+ }
104
+ if (!p.present && this.announced && now - this.lastSeen > LEFT_AFTER_MS) {
105
+ this.announced = false;
106
+ events.push({ type: "left" });
107
+ }
108
+ this.trackSmile(now, events);
109
+ }
110
+ trackSmile(now, events) {
111
+ const s = this.p.smile;
112
+ if (s < SMILE_OFF) {
113
+ this.smiling = false;
114
+ this.smileSince = null;
115
+ return;
116
+ }
117
+ if (s < SMILE_ON || this.smiling)
118
+ return;
119
+ this.smileSince ??= now;
120
+ if (now - this.smileSince >= SMILE_HOLD_MS && now - this.lastSmile > SMILE_COOLDOWN_MS) {
121
+ this.smiling = true;
122
+ this.lastSmile = now;
123
+ events.push({ type: "smiled" });
124
+ }
125
+ }
126
+ trackHands(hands, now, events) {
127
+ // the highest hand counts
128
+ const hand = hands.reduce((best, h) => (!best || h.y < best.y ? h : best), null);
129
+ const label = hand && hand.score >= GESTURE_MIN_SCORE && hand.gesture ? (CANNED_GESTURES[hand.gesture] ?? null) : null;
130
+ const wave = hand ? this.waving(hand, now) : false;
131
+ if (!hand)
132
+ this.wrist = [];
133
+ const g = wave ? "wave" : label;
134
+ this.p.gesture = g;
135
+ if (!g) {
136
+ this.held = null;
137
+ return;
138
+ }
139
+ if (this.held?.gesture !== g)
140
+ this.held = { gesture: g, since: now };
141
+ const hold = g === "wave" ? 0 : GESTURE_HOLD_MS;
142
+ if (now - this.held.since >= hold && now - (this.lastGesture.get(g) ?? -Infinity) > GESTURE_COOLDOWN_MS) {
143
+ this.lastGesture.set(g, now);
144
+ events.push({ type: "gesture", gesture: g });
145
+ }
146
+ }
147
+ // A raised hand swinging side to side: the wrist reverses a few times
148
+ // inside the window, each swing wider than a small margin.
149
+ waving(hand, now) {
150
+ const faceY = this.p.face ? 0.5 - this.p.face.y / 2 : 0.5;
151
+ if (hand.y > faceY + 0.25) {
152
+ this.wrist = [];
153
+ return false;
154
+ }
155
+ this.wrist.push({ x: hand.x, t: now });
156
+ while (this.wrist.length && now - this.wrist[0].t > WAVE_WINDOW_MS)
157
+ this.wrist.shift();
158
+ let reversals = 0;
159
+ let dir = 0;
160
+ let anchor = this.wrist[0]?.x ?? hand.x;
161
+ for (const { x } of this.wrist) {
162
+ const d = x - anchor;
163
+ if (Math.abs(d) < WAVE_SWING)
164
+ continue;
165
+ const s = Math.sign(d);
166
+ if (dir && s !== dir)
167
+ reversals++;
168
+ dir = s;
169
+ anchor = x;
170
+ }
171
+ return reversals >= WAVE_REVERSALS;
172
+ }
173
+ }
174
+ const mean = (b, ...names) => names.reduce((n, k) => n + (b[k] ?? 0), 0) / names.length;
175
+ /** Face point indices: nose tip, left cheek, right cheek, top, chin. MediaPipe 478 points, then the 68 point layout (brow middle as the top). */
176
+ const LAYOUTS = [
177
+ { min: 455, nose: 1, left: 234, right: 454, top: [10], chin: 152 },
178
+ { min: 68, nose: 30, left: 0, right: 16, top: [19, 24], chin: 8 },
179
+ ];
180
+ /** One raw face from a face landmark result, or null. Expressions read 0 without blendshapes. */
181
+ export function rawFace(lm, index = 0) {
182
+ const pts = lm.points[index];
183
+ if (!pts?.length)
184
+ return null;
185
+ const b = lm.blendshapes?.[index] ?? {};
186
+ const smile = mean(b, "mouthSmileLeft", "mouthSmileRight");
187
+ const surprise = Math.max(mean(b, "browInnerUp"), mean(b, "eyeWideLeft", "eyeWideRight"), mean(b, "jawOpen") * 0.7);
188
+ // brows come down when smiling or squinting too, so they count toward a frown only without a smile
189
+ const frown = Math.max(mean(b, "mouthFrownLeft", "mouthFrownRight"), mean(b, "browDownLeft", "browDownRight") * 0.7) * (1 - smile);
190
+ const L = LAYOUTS.find((l) => pts.length >= l.min && pts.length <= (l.min === 68 ? 68 : Infinity));
191
+ if (!L) {
192
+ let x0 = 1, x1 = 0, y0 = 1, y1 = 0;
193
+ for (const [x, y] of pts) {
194
+ x0 = Math.min(x0, x);
195
+ x1 = Math.max(x1, x);
196
+ y0 = Math.min(y0, y);
197
+ y1 = Math.max(y1, y);
198
+ }
199
+ // no layout known: the box centre, and a head pose that cannot be read counts as facing
200
+ return { x: (x0 + x1) / 2, y: (y0 + y1) / 2, yaw: 0, pitch: 0, smile, surprise, frown };
201
+ }
202
+ const p = (i) => pts[i];
203
+ const left = p(L.left);
204
+ const right = p(L.right);
205
+ const top = L.top.map(p).reduce((a, q) => [a[0] + q[0] / L.top.length, a[1] + q[1] / L.top.length, 0], [0, 0, 0]);
206
+ const chin = p(L.chin);
207
+ const nose = p(L.nose);
208
+ const w = Math.abs(right[0] - left[0]) || 1e-3;
209
+ const h = Math.abs(chin[1] - top[1]) || 1e-3;
210
+ const cx = (left[0] + right[0]) / 2;
211
+ const cy = (top[1] + chin[1]) / 2;
212
+ return { x: cx, y: cy, yaw: (nose[0] - cx) / w, pitch: (nose[1] - cy) / h, smile, surprise, frown };
213
+ }
214
+ /** Raw hands from a gesture recognizer or hand landmarker result: the wrist (point 0) and the top gesture. */
215
+ export function rawHands(lm) {
216
+ return lm.points.flatMap((pts, i) => {
217
+ const w = pts[0];
218
+ if (!w)
219
+ return [];
220
+ const g = lm.gestures?.[i] ?? null;
221
+ return [{ x: w[0], y: w[1], gesture: g?.name ?? null, score: g?.score ?? 0 }];
222
+ });
223
+ }
224
+ /** A tracker frame from `landmarks` results. Leave `hands` out on frames where hands were not checked. */
225
+ export function rawFromLandmarks(face, hands) {
226
+ return { face: face ? rawFace(face) : null, hands: hands ? rawHands(hands) : null };
227
+ }
228
+ const GESTURE_WORDS = {
229
+ wave: "waving",
230
+ thumbs_up: "giving a thumbs up",
231
+ thumbs_down: "giving a thumbs down",
232
+ open_palm: "holding up an open hand",
233
+ victory: "making a peace sign",
234
+ pointing_up: "pointing up",
235
+ fist: "making a fist",
236
+ love: "making a love you sign",
237
+ };
238
+ /** Perception as one short lowercase line for a language model. */
239
+ export function describePerception(p) {
240
+ if (!p.present)
241
+ return "you are not in view";
242
+ const parts = ["you are here", p.facing ? "looking at me" : "looking away"];
243
+ // vendor thresholds
244
+ if (p.smile > 0.5)
245
+ parts.push("smiling");
246
+ else if (p.surprise > 0.55)
247
+ parts.push("looking surprised");
248
+ else if (p.frown > 0.5)
249
+ parts.push("frowning");
250
+ if (p.gesture)
251
+ parts.push(GESTURE_WORDS[p.gesture]);
252
+ return parts.join(", ");
253
+ }
254
+ /**
255
+ * The seen note for a turn: null when nothing changed since the last note,
256
+ * so a chat about anything else is not padded with the same observation.
257
+ * A caption from an on demand look is always included.
258
+ */
259
+ export class SeenNotes {
260
+ last = "";
261
+ next(p, caption) {
262
+ const now = describePerception(p);
263
+ if (!caption && now === this.last)
264
+ return null;
265
+ this.last = now;
266
+ return caption ? `${now}; i can see: ${caption.trim().toLowerCase()}` : now;
267
+ }
268
+ reset() {
269
+ this.last = "";
270
+ }
271
+ }
272
+ /** Questions that call for an on demand look rather than the steady signals. Replace it to suit a persona. */
273
+ export const LOOK_PATTERN = /\b(what (am i|is this|'?s this|do you see|can you see)|can you see|do you see|look at (this|me|my)|what('?s| is) in my hand|holding|wearing|show(ing)? you)\b/i;
274
+ export const wantsLook = (text, pattern = LOOK_PATTERN) => pattern.test(text);
275
+ /** Default reactions (vendor): greet on arrival, smile back after 600 ms at 0.7 chance, answer waves and a few gestures. */
276
+ export const DEFAULT_REACTIONS = [
277
+ { on: "arrived", kind: "mood", name: "happy" },
278
+ { on: "arrived", kind: "gesture", name: "wave" },
279
+ { on: "smiled", kind: "mood", name: "happy", delayMs: 600, chance: 0.7 },
280
+ { on: "gesture", gesture: "wave", kind: "gesture", name: "wave" },
281
+ { on: "gesture", gesture: "thumbs_up", kind: "mood", name: "happy" },
282
+ { on: "gesture", gesture: "thumbs_down", kind: "mood", name: "sad" },
283
+ { on: "gesture", gesture: "victory", kind: "gesture", name: "peace" },
284
+ { on: "gesture", gesture: "love", kind: "mood", name: "love" },
285
+ ];
286
+ /** The reactions an event calls for. A chance is drawn once per reaction from the injected `rng`. */
287
+ export function reactionsFor(e, rng, table = DEFAULT_REACTIONS) {
288
+ return table.filter((r) => r.on === e.type && (e.type !== "gesture" || r.gesture === e.gesture) && (r.chance === undefined || rng() < r.chance));
289
+ }
290
+ /** Where the character should look, -1 to 1, with a gain (vendor 1.3) so small head moves read; null when nobody is in view. */
291
+ export function gazeTarget(p, gain = 1.3) {
292
+ const clamp = (v) => Math.max(-1, Math.min(1, v));
293
+ return p.face ? { x: clamp(p.face.x * gain), y: clamp(p.face.y * gain) } : null;
294
+ }