@hackbuild/vision 0.0.0-stage → 0.1.1

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,37 @@
1
+ /**
2
+ * A MediaPipe tasks-vision provider for the models hub. One wasm fileset
3
+ * per page; one task per record, created with the GPU delegate on a
4
+ * "webgl" rung and the CPU delegate on a "wasm" rung, so a failed GPU
5
+ * delegate falls to the CPU one (FaceSwap and an earlier scene app had no fallback).
6
+ * Results are turned into the package's Detector, Segmenter and
7
+ * Landmarker shapes.
8
+ */
9
+ import type { Factory } from "@hackbuild/models";
10
+ import type { WeightStore } from "@hackbuild/weights";
11
+ export declare const TASKS_VISION = "1.2.3";
12
+ interface TaskClass {
13
+ createFromOptions(fileset: unknown, opts: Record<string, unknown>): Promise<Record<string, (...a: unknown[]) => unknown>>;
14
+ }
15
+ /** The parts of @mediapipe/tasks-vision the provider touches. Tests pass a fake. */
16
+ export interface TasksVision {
17
+ FilesetResolver: {
18
+ forVisionTasks(base: string): Promise<unknown>;
19
+ };
20
+ ObjectDetector?: TaskClass;
21
+ ImageSegmenter?: TaskClass;
22
+ FaceLandmarker?: TaskClass;
23
+ HandLandmarker?: TaskClass;
24
+ PoseLandmarker?: TaskClass;
25
+ GestureRecognizer?: TaskClass;
26
+ }
27
+ export declare function tasksVisionUrls(version?: string): string[];
28
+ export declare function tasksVisionWasm(version?: string): string;
29
+ export declare const loadTasksVision: (version?: string) => () => Promise<TasksVision>;
30
+ export interface MediapipeProviderOptions {
31
+ runtime: () => Promise<TasksVision>;
32
+ wasmBase?: string;
33
+ /** Read model files through the weight store (resume, sha-256, licence line) and pass them as buffers. */
34
+ store?: WeightStore;
35
+ }
36
+ export declare function mediapipeProvider(opts: MediapipeProviderOptions): Factory;
37
+ export {};
@@ -0,0 +1,116 @@
1
+ /**
2
+ * A MediaPipe tasks-vision provider for the models hub. One wasm fileset
3
+ * per page; one task per record, created with the GPU delegate on a
4
+ * "webgl" rung and the CPU delegate on a "wasm" rung, so a failed GPU
5
+ * delegate falls to the CPU one (FaceSwap and an earlier scene app had no fallback).
6
+ * Results are turned into the package's Detector, Segmenter and
7
+ * Landmarker shapes.
8
+ */
9
+ import { importEsm } from "@hackbuild/ai-env";
10
+ export const TASKS_VISION = "1.2.3";
11
+ export function tasksVisionUrls(version = TASKS_VISION) {
12
+ return [`https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@${version}/vision_bundle.mjs`];
13
+ }
14
+ export function tasksVisionWasm(version = TASKS_VISION) {
15
+ return `https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@${version}/wasm`;
16
+ }
17
+ export const loadTasksVision = (version = TASKS_VISION) => () => importEsm(tasksVisionUrls(version));
18
+ const CLASS = {
19
+ detect: "ObjectDetector",
20
+ "segment.person": "ImageSegmenter",
21
+ "landmarks.face": "FaceLandmarker",
22
+ "landmarks.hand": "HandLandmarker",
23
+ "landmarks.pose": "PoseLandmarker",
24
+ "landmarks.gesture": "GestureRecognizer",
25
+ };
26
+ const call = (t, name, ...a) => t[name](...a);
27
+ function detector(t, video) {
28
+ return {
29
+ async detect(image, o = {}) {
30
+ const r = (video ? call(t, "detectForVideo", image, o.timestamp ?? 0) : call(t, "detect", image));
31
+ return r.detections
32
+ .map((d) => {
33
+ const c = d.categories[0] ?? { score: 0 };
34
+ const b = d.boundingBox ?? { originX: 0, originY: 0, width: 0, height: 0 };
35
+ return { label: c.categoryName ?? c.displayName ?? "", score: c.score, box: { x: b.originX, y: b.originY, w: b.width, h: b.height } };
36
+ })
37
+ .filter((d) => d.score >= (o.scoreThreshold ?? 0))
38
+ .slice(0, o.maxResults ?? Infinity);
39
+ },
40
+ dispose: () => call(t, "close"),
41
+ };
42
+ }
43
+ function segmenter(t) {
44
+ return {
45
+ async segment(image) {
46
+ const r = call(t, "segment", image);
47
+ const conf = r.confidenceMasks?.[r.confidenceMasks.length - 1];
48
+ if (conf) {
49
+ const f = conf.getAsFloat32Array();
50
+ return [{ width: conf.width, height: conf.height, data: Uint8Array.from(f, (v) => Math.round(Math.max(0, Math.min(1, v)) * 255)) }];
51
+ }
52
+ const m = r.categoryMask;
53
+ return m ? [{ width: m.width, height: m.height, data: Uint8Array.from(m.getAsUint8Array(), (v) => (v ? 255 : 0)) }] : [];
54
+ },
55
+ dispose: () => call(t, "close"),
56
+ };
57
+ }
58
+ function landmarker(t, kind, video, source) {
59
+ return {
60
+ async detect(image, o = {}) {
61
+ const g = kind === "landmarks.gesture";
62
+ const r = (video ? call(t, g ? "recognizeForVideo" : "detectForVideo", image, o.timestamp ?? 0) : call(t, g ? "recognize" : "detect", image));
63
+ const lists = (kind === "landmarks.face" ? r.faceLandmarks : r.landmarks) ?? [];
64
+ const out = {
65
+ points: lists.map((l) => l.map((p) => [p.x, p.y, p.z])),
66
+ source,
67
+ };
68
+ if (r.faceBlendshapes)
69
+ out.blendshapes = r.faceBlendshapes.map((b) => Object.fromEntries(b.categories.map((c) => [c.categoryName ?? "", c.score])));
70
+ const hd = r.handedness ?? r.handednesses;
71
+ if (hd)
72
+ out.handedness = hd.map((h) => h[0]?.categoryName ?? "");
73
+ if (g)
74
+ out.gestures = lists.map((_, i) => {
75
+ const top = r.gestures?.[i]?.[0];
76
+ return top && top.categoryName && top.categoryName !== "None" ? { name: top.categoryName, score: top.score } : null;
77
+ });
78
+ return out;
79
+ },
80
+ dispose: () => call(t, "close"),
81
+ };
82
+ }
83
+ export function mediapipeProvider(opts) {
84
+ let fileset = null;
85
+ return async ({ record, rung, signal }) => {
86
+ const tv = await opts.runtime();
87
+ fileset ??= tv.FilesetResolver.forVisionTasks(opts.wasmBase ?? tasksVisionWasm());
88
+ const fs = await fileset;
89
+ const cap = record.provides[0];
90
+ const cls = tv[CLASS[cap] ?? ""];
91
+ if (!cls)
92
+ throw new Error(`${record.id}: no mediapipe task for ${cap}`);
93
+ const url = record.source.url;
94
+ if (!url)
95
+ throw new Error(`${record.id}: a mediapipe record needs source.url`);
96
+ const base = { delegate: rung.device === "webgl" ? "GPU" : "CPU" };
97
+ if (opts.store) {
98
+ const ref = { url, licence: record.licence, ...(record.source.sha256 ? { sha256: record.source.sha256 } : {}) };
99
+ base.modelAssetBuffer = new Uint8Array(await (await opts.store.get(ref, signal ? { signal } : {})).arrayBuffer());
100
+ }
101
+ else
102
+ base.modelAssetPath = url;
103
+ const video = rung.options?.runningMode === "VIDEO";
104
+ const extra = { runningMode: video ? "VIDEO" : "IMAGE", ...(rung.options ?? {}) };
105
+ if (cap === "landmarks.face")
106
+ extra.outputFaceBlendshapes ??= true;
107
+ if (cap === "segment.person")
108
+ extra.outputConfidenceMasks ??= true;
109
+ const task = await cls.createFromOptions(fs, { baseOptions: base, ...extra });
110
+ if (cap === "detect")
111
+ return detector(task, video);
112
+ if (cap === "segment.person")
113
+ return segmenter(task);
114
+ return landmarker(task, cap, video, record.id);
115
+ };
116
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Vision records for the models hub. Licences are the model cards' as of
3
+ * 2026-11-22; sizes are inferred from the builds and parameter counts.
4
+ * YOLO weights are AGPL-3.0 (Ultralytics): they are never registered by
5
+ * default, and `yoloRecord` builds a record only for a URL the app
6
+ * supplies.
7
+ */
8
+ import type { ModelRecord, Rung } from "@hackbuild/models";
9
+ export declare const MP_MODELS = "https://storage.googleapis.com/mediapipe-models/";
10
+ /** MediaPipe ladder: GPU delegate (webgl), then the CPU delegate (wasm). */
11
+ export declare const mediapipeLadder: () => Rung[];
12
+ export declare const VISION_RECORDS: ModelRecord[];
13
+ /** A face landmark fallback record over face-api.js tiny nets (code MIT; weights MIT from @vladmandic/face-api). */
14
+ export declare function faceApiRecord(baseUrl: string): ModelRecord;
15
+ /** YOLOv8n exported to ONNX (640 input, [1, 84, 8400] output). External: the app supplies the URL and accepts the weight licence. */
16
+ export declare function yoloRecord(o: {
17
+ url: string;
18
+ sha256?: string;
19
+ id?: string;
20
+ licence?: string;
21
+ labels?: string[];
22
+ }): ModelRecord;
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Vision records for the models hub. Licences are the model cards' as of
3
+ * 2026-11-22; sizes are inferred from the builds and parameter counts.
4
+ * YOLO weights are AGPL-3.0 (Ultralytics): they are never registered by
5
+ * default, and `yoloRecord` builds a record only for a URL the app
6
+ * supplies.
7
+ */
8
+ import { LADDERS, tjsLadder } from "@hackbuild/devices";
9
+ export const MP_MODELS = "https://storage.googleapis.com/mediapipe-models/";
10
+ /** MediaPipe ladder: GPU delegate (webgl), then the CPU delegate (wasm). */
11
+ export const mediapipeLadder = () => [{ device: "webgl" }, { device: "wasm" }];
12
+ const mp = (id, provides, path, sizeMB, label) => ({
13
+ id,
14
+ label,
15
+ provides: [provides],
16
+ provider: "mediapipe",
17
+ source: { url: MP_MODELS + path },
18
+ sizeMB,
19
+ sizeSource: "inferred",
20
+ ladder: mediapipeLadder(),
21
+ licence: "Apache-2.0",
22
+ commercial: true,
23
+ place: "main",
24
+ runtime: "@mediapipe/tasks-vision@1.2.3",
25
+ });
26
+ export const VISION_RECORDS = [
27
+ {
28
+ id: "depth-anything-v2-small",
29
+ label: "depth anything v2 small",
30
+ provides: ["depth"],
31
+ provider: "tjs",
32
+ source: { modelId: "onnx-community/depth-anything-v2-small" },
33
+ sizeMB: 100,
34
+ sizeSource: "inferred",
35
+ ladder: LADDERS.depth(),
36
+ licence: "Apache-2.0",
37
+ commercial: true,
38
+ place: "cpu-worker",
39
+ runtime: "@huggingface/transformers@4.3.2",
40
+ notes: ["earlier builds: fp16 on webgpu, fp32 on the same device after a failure"],
41
+ },
42
+ mp("efficientdet-lite0", "detect", "object_detector/efficientdet_lite0/float16/1/efficientdet_lite0.tflite", 7, "mediapipe efficientdet lite0 (coco, 80 classes)"),
43
+ mp("selfie-segmenter", "segment.person", "image_segmenter/selfie_segmenter/float16/latest/selfie_segmenter.tflite", 1, "mediapipe selfie segmenter"),
44
+ mp("face-landmarker", "landmarks.face", "face_landmarker/face_landmarker/float16/1/face_landmarker.task", 4, "mediapipe face landmarker with blendshapes"),
45
+ mp("hand-landmarker", "landmarks.hand", "hand_landmarker/hand_landmarker/float16/1/hand_landmarker.task", 8, "mediapipe hand landmarker"),
46
+ {
47
+ ...mp("gesture-recognizer", "landmarks.gesture", "gesture_recognizer/gesture_recognizer/float16/1/gesture_recognizer.task", 8, "mediapipe gesture recognizer (7 canned gestures)"),
48
+ // the model card's licence was not checked when this record was added
49
+ licence: "unknown, check the mediapipe model card",
50
+ commercial: "unknown",
51
+ notes: ["optional: hands feed waves and canned gestures to the signal tracker, which runs on faces alone"],
52
+ },
53
+ mp("pose-landmarker-lite", "landmarks.pose", "pose_landmarker/pose_landmarker_lite/float16/1/pose_landmarker_lite.task", 6, "mediapipe pose landmarker lite"),
54
+ {
55
+ id: "slimsam-77-uniform",
56
+ label: "slimsam 77 uniform (point prompts)",
57
+ provides: ["segment"],
58
+ provider: "tjs",
59
+ source: { modelId: "Xenova/slimsam-77-uniform" },
60
+ sizeMB: 40,
61
+ sizeSource: "inferred",
62
+ ladder: tjsLadder({ webgpu: ["fp16", "fp32"], wasm: ["fp32"] }),
63
+ licence: "Apache-2.0",
64
+ commercial: true,
65
+ place: "cpu-worker",
66
+ runtime: "@huggingface/transformers@4.3.2",
67
+ notes: ["earlier builds: one image embedding, then any number of point prompts"],
68
+ },
69
+ {
70
+ id: "smolvlm-256m-instruct",
71
+ label: "smolvlm 256m",
72
+ provides: ["vision.caption", "vision.ask"],
73
+ provider: "tjs",
74
+ source: { modelId: "HuggingFaceTB/SmolVLM-256M-Instruct" },
75
+ sizeMB: 260,
76
+ sizeSource: "inferred",
77
+ ladder: LADDERS.smolvlm(),
78
+ quirks: { repetitionPenalty: 1.3, maxTokensAction: 64 },
79
+ licence: "Apache-2.0",
80
+ commercial: true,
81
+ place: "cpu-worker",
82
+ runtime: "@huggingface/transformers@4.3.2",
83
+ },
84
+ {
85
+ id: "lfm2-vl-450m",
86
+ label: "lfm2-vl 450m",
87
+ provides: ["vision.caption", "vision.ask"],
88
+ provider: "tjs",
89
+ source: { modelId: "onnx-community/LFM2-VL-450M-ONNX" },
90
+ sizeMB: 320,
91
+ sizeSource: "inferred",
92
+ ladder: LADDERS.vlmGpuOnly(),
93
+ // transformers.js 4.3.2 Lfm2VlProcessor._call(images, text): text first threw
94
+ // "undefined is not iterable" in the browser pass (measured 2026-11-23)
95
+ quirks: { maxTokensAction: 72, processorImagesFirst: true },
96
+ licence: "LFM Open License v1.0",
97
+ commercial: "unknown",
98
+ place: "gpu",
99
+ runtime: "@huggingface/transformers@4.3.2",
100
+ notes: ["earlier builds: q4f16 on webgpu only; the licence limits commercial use by revenue, read it before shipping"],
101
+ },
102
+ ];
103
+ /** A face landmark fallback record over face-api.js tiny nets (code MIT; weights MIT from @vladmandic/face-api). */
104
+ export function faceApiRecord(baseUrl) {
105
+ return {
106
+ id: "face-api-tiny",
107
+ label: "face-api tiny landmarks (68 points)",
108
+ provides: ["landmarks.face"],
109
+ provider: "faceapi",
110
+ source: { url: baseUrl },
111
+ sizeMB: 1,
112
+ sizeSource: "inferred",
113
+ ladder: [{ device: "wasm" }],
114
+ licence: "MIT",
115
+ commercial: true,
116
+ place: "main",
117
+ };
118
+ }
119
+ /** YOLOv8n exported to ONNX (640 input, [1, 84, 8400] output). External: the app supplies the URL and accepts the weight licence. */
120
+ export function yoloRecord(o) {
121
+ return {
122
+ id: o.id ?? "yolov8n",
123
+ label: "yolov8n (external)",
124
+ provides: ["detect"],
125
+ provider: "ort",
126
+ source: { url: o.url, ...(o.sha256 ? { sha256: o.sha256 } : {}) },
127
+ sizeMB: 13,
128
+ sizeSource: "inferred",
129
+ ladder: [
130
+ { device: "webgpu", ort: { executionProviders: ["webgpu", "wasm"] } },
131
+ { device: "wasm", ort: { executionProviders: ["wasm"] } },
132
+ ],
133
+ licence: o.licence ?? "AGPL-3.0 (Ultralytics YOLOv8 weights), supplied by the app",
134
+ commercial: false,
135
+ place: "gpu",
136
+ notes: ["earlier builds: 640 letterbox, per class nms at iou 0.45, at most 13 boxes"],
137
+ };
138
+ }
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Prompted segmentation with one image embedding per image. The encoder
3
+ * runs once per image; every later point or box prompt on that image
4
+ * decodes from the cached embedding (as the earlier mask studio did, one
5
+ * embedding per image, then hover and click decode from it).
6
+ */
7
+ import type { ImageInput, Mask, SegmentPrompt, Segmenter } from "./types.js";
8
+ /**
9
+ * Least recently used embeddings by image. A key is a string the caller
10
+ * picks (an image hash) or the image object itself. Encodes in flight are
11
+ * shared, so a hover and a click on a fresh image encode once.
12
+ */
13
+ export declare class EmbeddingCache<E = unknown> {
14
+ readonly max: number;
15
+ private readonly m;
16
+ hits: number;
17
+ misses: number;
18
+ constructor(max?: number);
19
+ has(key: unknown): boolean;
20
+ /** The cached embedding, or undefined; counts nothing. */
21
+ peek(key: unknown): Promise<E> | undefined;
22
+ set(key: unknown, v: E | Promise<E>): void;
23
+ /** The embedding for `key`, encoding it with `make` on a miss. A failed encode is not kept. */
24
+ getOr(key: unknown, make: () => Promise<E>): Promise<E>;
25
+ delete(key: unknown): boolean;
26
+ clear(): void;
27
+ get size(): number;
28
+ }
29
+ export interface PromptSegmenterOptions<E> {
30
+ /** The image encoder: runs once per image. */
31
+ encode(image: ImageInput): Promise<E>;
32
+ /** The prompt decoder: runs per prompt against the cached embedding. */
33
+ decode(embedding: E, prompt: SegmentPrompt, image: ImageInput): Promise<Mask[]>;
34
+ /** Shared cache; a fresh one holding 4 images when omitted. */
35
+ cache?: EmbeddingCache<E>;
36
+ dispose?(): unknown;
37
+ }
38
+ /** True when the prompt has a point or a box. */
39
+ export declare function hasPrompt(p?: SegmentPrompt): boolean;
40
+ /** A segmenter from an encoder and a decoder, with the embedding cache on `cache`. Masks come best first, scores clamped to 0 to 1. */
41
+ export declare function promptSegmenter<E>(o: PromptSegmenterOptions<E>): Segmenter & {
42
+ cache: EmbeddingCache<E>;
43
+ };
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Prompted segmentation with one image embedding per image. The encoder
3
+ * runs once per image; every later point or box prompt on that image
4
+ * decodes from the cached embedding (as the earlier mask studio did, one
5
+ * embedding per image, then hover and click decode from it).
6
+ */
7
+ /**
8
+ * Least recently used embeddings by image. A key is a string the caller
9
+ * picks (an image hash) or the image object itself. Encodes in flight are
10
+ * shared, so a hover and a click on a fresh image encode once.
11
+ */
12
+ export class EmbeddingCache {
13
+ max;
14
+ m = new Map();
15
+ hits = 0;
16
+ misses = 0;
17
+ constructor(max = 4) {
18
+ this.max = max;
19
+ }
20
+ has(key) {
21
+ return this.m.has(key);
22
+ }
23
+ /** The cached embedding, or undefined; counts nothing. */
24
+ peek(key) {
25
+ return this.m.get(key);
26
+ }
27
+ set(key, v) {
28
+ this.m.delete(key);
29
+ this.m.set(key, Promise.resolve(v));
30
+ while (this.m.size > this.max)
31
+ this.m.delete(this.m.keys().next().value);
32
+ }
33
+ /** The embedding for `key`, encoding it with `make` on a miss. A failed encode is not kept. */
34
+ getOr(key, make) {
35
+ const v = this.m.get(key);
36
+ if (v) {
37
+ this.hits++;
38
+ this.m.delete(key);
39
+ this.m.set(key, v);
40
+ return v;
41
+ }
42
+ this.misses++;
43
+ const p = make();
44
+ this.set(key, p);
45
+ p.catch(() => {
46
+ if (this.m.get(key) === p)
47
+ this.m.delete(key);
48
+ });
49
+ return p;
50
+ }
51
+ delete(key) {
52
+ return this.m.delete(key);
53
+ }
54
+ clear() {
55
+ this.m.clear();
56
+ }
57
+ get size() {
58
+ return this.m.size;
59
+ }
60
+ }
61
+ /** True when the prompt has a point or a box. */
62
+ export function hasPrompt(p) {
63
+ return !!(p && (p.points?.length || p.box));
64
+ }
65
+ /** A segmenter from an encoder and a decoder, with the embedding cache on `cache`. Masks come best first, scores clamped to 0 to 1. */
66
+ export function promptSegmenter(o) {
67
+ const own = o.cache ?? new EmbeddingCache();
68
+ const seg = {
69
+ cache: own,
70
+ async segment(image, prompt = {}, so = {}) {
71
+ if (!hasPrompt(prompt))
72
+ throw new Error("a prompt needs at least one point or a box");
73
+ const cache = so.cache ?? own;
74
+ const emb = await cache.getOr(so.key ?? image, () => o.encode(image));
75
+ const masks = await o.decode(emb, prompt, image);
76
+ for (const m of masks)
77
+ if (m.score !== undefined)
78
+ m.score = Math.min(1, Math.max(0, m.score));
79
+ return masks.sort((a, b) => (b.score ?? 0) - (a.score ?? 0));
80
+ },
81
+ };
82
+ if (o.dispose)
83
+ seg.dispose = () => o.dispose();
84
+ return seg;
85
+ }
@@ -0,0 +1,131 @@
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
+ import type { Landmarks } from "./types.js";
21
+ export type HandGesture = "wave" | "thumbs_up" | "thumbs_down" | "open_palm" | "victory" | "pointing_up" | "fist" | "love";
22
+ export interface Perception {
23
+ present: boolean;
24
+ /** The face in the viewer's frame, -1 to 1 on both axes: +x the character's left (the person's right), +y up. Null when no face is seen. */
25
+ face: {
26
+ x: number;
27
+ y: number;
28
+ } | null;
29
+ /** Facing the screen rather than turned away. */
30
+ facing: boolean;
31
+ /** Expression strengths, 0 to 1, smoothed. */
32
+ smile: number;
33
+ surprise: number;
34
+ frown: number;
35
+ gesture: HandGesture | null;
36
+ }
37
+ export type PerceptionEvent = {
38
+ type: "arrived";
39
+ } | {
40
+ type: "left";
41
+ } | {
42
+ type: "smiled";
43
+ } | {
44
+ type: "gesture";
45
+ gesture: HandGesture;
46
+ };
47
+ /** One face reading before smoothing. Image coordinates are 0 to 1 in the raw (unmirrored) camera frame. */
48
+ export interface RawFace {
49
+ x: number;
50
+ y: number;
51
+ /** Head turn and tilt as the nose offset from the face centre, in face widths and heights; near zero when facing the camera. */
52
+ yaw: number;
53
+ pitch: number;
54
+ smile: number;
55
+ surprise: number;
56
+ frown: number;
57
+ }
58
+ export interface RawHand {
59
+ /** Wrist position. */
60
+ x: number;
61
+ y: number;
62
+ /** The recognizer's canned label (Open_Palm, Thumb_Up, ...), if any. */
63
+ gesture: string | null;
64
+ score: number;
65
+ }
66
+ export interface RawFrame {
67
+ face: RawFace | null;
68
+ /** Null on frames where hands were not checked. */
69
+ hands: RawHand[] | null;
70
+ }
71
+ /** Canned recognizer labels to gesture names. */
72
+ export declare const CANNED_GESTURES: Readonly<Record<string, HandGesture>>;
73
+ export declare class SignalTracker {
74
+ private p;
75
+ private lastSeen;
76
+ private absentSince;
77
+ private announced;
78
+ private smileSince;
79
+ private smiling;
80
+ private lastSmile;
81
+ private held;
82
+ private lastGesture;
83
+ private wrist;
84
+ get perception(): Perception;
85
+ /** Feed one frame; returns the events it fired, usually none. */
86
+ feed(raw: RawFrame, now: number): PerceptionEvent[];
87
+ reset(): void;
88
+ private trackFace;
89
+ private trackSmile;
90
+ private trackHands;
91
+ private waving;
92
+ }
93
+ /** One raw face from a face landmark result, or null. Expressions read 0 without blendshapes. */
94
+ export declare function rawFace(lm: Landmarks, index?: number): RawFace | null;
95
+ /** Raw hands from a gesture recognizer or hand landmarker result: the wrist (point 0) and the top gesture. */
96
+ export declare function rawHands(lm: Landmarks): RawHand[];
97
+ /** A tracker frame from `landmarks` results. Leave `hands` out on frames where hands were not checked. */
98
+ export declare function rawFromLandmarks(face: Landmarks | null | undefined, hands?: Landmarks | null): RawFrame;
99
+ /** Perception as one short lowercase line for a language model. */
100
+ export declare function describePerception(p: Perception): string;
101
+ /**
102
+ * The seen note for a turn: null when nothing changed since the last note,
103
+ * so a chat about anything else is not padded with the same observation.
104
+ * A caption from an on demand look is always included.
105
+ */
106
+ export declare class SeenNotes {
107
+ private last;
108
+ next(p: Perception, caption?: string | null): string | null;
109
+ reset(): void;
110
+ }
111
+ /** Questions that call for an on demand look rather than the steady signals. Replace it to suit a persona. */
112
+ export declare const LOOK_PATTERN: RegExp;
113
+ export declare const wantsLook: (text: string, pattern?: RegExp) => boolean;
114
+ /** One reaction to a perception event: a mood or a gesture by common name, after a delay, with a chance. */
115
+ export interface Reaction {
116
+ on: PerceptionEvent["type"];
117
+ gesture?: HandGesture;
118
+ kind: "mood" | "gesture";
119
+ name: string;
120
+ delayMs?: number;
121
+ chance?: number;
122
+ }
123
+ /** Default reactions (vendor): greet on arrival, smile back after 600 ms at 0.7 chance, answer waves and a few gestures. */
124
+ export declare const DEFAULT_REACTIONS: readonly Reaction[];
125
+ /** The reactions an event calls for. A chance is drawn once per reaction from the injected `rng`. */
126
+ export declare function reactionsFor(e: PerceptionEvent, rng: () => number, table?: readonly Reaction[]): Reaction[];
127
+ /** 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. */
128
+ export declare function gazeTarget(p: Perception, gain?: number): {
129
+ x: number;
130
+ y: number;
131
+ } | null;