callable-lipsync 0.0.0-stage → 0.2.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.
package/js/engine.js ADDED
@@ -0,0 +1,147 @@
1
+ // callable-lipsync as a stream: 16 kHz audio in, FLAME 2023 Open frames out at 25 fps
2
+ // (118 numbers: 100 expression, 3 chest rotation, 3 jaw, 3 neck, 6 eyes, 3 travel in m).
3
+ // Runs the model's ONNX graphs with onnxruntime (web or node); works in a page, a worker or Node.
4
+ //
5
+ // Audio ahead of a frame: the lips use `wait` frames of it (4 = 0.16 s, the model's full view; fewer: silence stands
6
+ // in for the rest), the head `known` frames more past that (12 = 0.64 s in all; 8, 4, 0; -4 with wait 0 = none).
7
+ // `quiet` (default on): after 0.4 s without sound the mouth is eased to the model's closed pose (meta.closed), and released as sound returns.
8
+ // `floor`: the level of a faint noise added to the audio (1e-4 = -80 dB; 0 = none), so that long digital silence reads as a quiet room.
9
+ // Every block of the network keeps its past outputs, so a new 40 ms of audio costs one frame of each block.
10
+ const FRAME = 640, LOUD = 1e-5, HOLD = 10; // samples a frame; the mean square of a frame with sound in it (-50 dB); frames after the last sound before the mouth is eased shut
11
+ function rng(seed) { let a = seed >>> 0; return () => { a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
12
+
13
+ export class Engine {
14
+ static async create(ort, load, options = {}) {
15
+ const e = new Engine(); e.ort = ort; e.meta = JSON.parse(new TextDecoder().decode(await load('meta.json'))); e.s = {}; e.bytes = 0;
16
+ for (const n of e.meta.graphs) { const b = await load(n + '.onnx'); e.bytes += b.byteLength; e.s[n] = await ort.InferenceSession.create(new Uint8Array(b), options.session || {}); }
17
+ e.nano = e.meta.kind === 'nano'; // the small model: face, jaw and the head's rotation straight from the audio; no draws, no chest, eyes or blinks; always 0.16 s of audio ahead
18
+ if (!e.nano) { const tb = await load('tables.bin'), T = e.meta.tables; e.dig = new Float32Array(tb, T.dig.offset, T.dig.shape[0] * T.dig.shape[1]); e.template = new Float32Array(tb, T.template.offset, T.template.shape[0] * T.template.shape[1]); }
19
+ e.layers = []; let src = 'e'; e.meta.trunk.forEach((b, i) => { e.layers.push({ name: 't' + i, src, ...b }); src = 't' + i; }); e.hName = src; e.meta.slow.forEach((b, i) => { e.layers.push({ name: 's' + i, src, ...b }); src = 's' + i; }); e.sName = src;
20
+ e.zero = new Float32Array(e.meta.width); e.reset({}); return e;
21
+ }
22
+ reset({ known = 12, wait = 4, guide = 2, temp = 1, blinkTemp = 1, smooth = 0.75, seed = 1, hop = null, record = false, floor = 1e-4, quiet = true } = {}) {
23
+ const m = this.meta; if (this.nano) { wait = m.future; known = 0; hop = 1; } Object.assign(this, { known, wait, guide, temp, blinkTemp, smooth, record, floor, quiet }); this.en = []; this.enAcc = 0; this.enN = 0; this.lastLoud = -1e9; this.gate = 0; this.hiss = rng(0x5bd1e995); // the noise floor is the same on every run: the lips do not depend on the seed
24
+ this.hop = hop || (wait === m.future && known >= m.stride ? m.stride : 1); this.rand = rng(seed); this.blinkRand = rng(seed ^ 0x9e3779b9); // blinks draw from their own sequence, so the motion does not depend on how the audio was cut into chunks
25
+ this.audio = new Float32Array(1 << 16); this.a0 = 0; this.an = 0; // samples [a0, an) are held
26
+ this.col = { e: [] }; this.n = { e: 0 }; for (const l of this.layers) { this.col[l.name] = []; this.n[l.name] = 0; } // each block's outputs per frame, final up to n
27
+ this.naux = 0; this.aux = []; this.nface = 0; this.face = [];
28
+ if (!this.nano) { this.ha = new Float32Array(2 * m.ahid); this.hb = new Float32Array(2 * m.ahid); this.hx = new Float32Array(4 * m.hid); } this.blinkLast = 0; this.blinkStart = -1;
29
+ this.nb = 0; this.q = []; this.pose = []; this.y1 = null; this.y2 = null; this.out = 0;
30
+ this.ms = { lips: 0, heads: 0, tokens: 0, frames: 0, calls: 0 }; this.log = { digits: [], probs: [], blinks: [], face: [] };
31
+ }
32
+ push(x) {
33
+ if (this.an - this.a0 + x.length > this.audio.length) { const from = Math.max(this.a0, this.an - 16 * FRAME); let n = this.audio.length; while (n < this.an - from + x.length) n *= 2; const b = new Float32Array(n); b.set(this.audio.subarray(from - this.a0, this.an - this.a0)); this.audio = b; this.a0 = from; }
34
+ const o = this.an - this.a0, a = this.audio, g = 2 * this.floor, r = this.hiss; this.an += x.length;
35
+ for (let i = 0; i < x.length; i++) { this.enAcc += x[i] * x[i]; if (++this.enN === FRAME) { this.en.push(this.enAcc / FRAME > LOUD); this.enAcc = 0; this.enN = 0; } } // per frame: is there sound (over -50 dB)
36
+ if (g) for (let i = 0; i < x.length; i++) a[o + i] = x[i] + g * (r() + r() + r() - 1.5); else a.set(x, o); // a noise floor (-80 dB): exact digital silence is something the model never heard, and after 2.5 s of it the lips drift open
37
+ }
38
+ t(data, dims) { return new this.ort.Tensor('float32', data, dims); }
39
+ async run(name, feeds) { this.ms.calls++; return this.s[name].run(feeds); }
40
+ window(f0, f1, end) { // audio of frames [f0, f1), zeros before the stream and from sample `end` on
41
+ const x = new Float32Array((f1 - f0) * FRAME), a = Math.max(f0 * FRAME, this.a0, 0), b = Math.min(f1 * FRAME, end, this.an); if (b > a) x.set(this.audio.subarray(a - this.a0, b - this.a0), a - f0 * FRAME); return x;
42
+ }
43
+ async fe(f0, f1, end) { // the vectors into the trunk for frames [f0, f1) -> rows
44
+ const w = this.meta.width, x = this.window(f0 - 2, f1, end), r = (await this.run('fe', { audio: this.t(x, [1, x.length]) })).e.data, o = []; for (let i = f0; i < f1; i++) o.push(r.slice((i - f0 + 2) * w, (i - f0 + 3) * w)); return o;
45
+ }
46
+ async blockCols(l, frames, get) { // block l at `frames` from its input's columns
47
+ const w = this.meta.width, N = frames.length, x = new Float32Array(N * w * 3);
48
+ for (let i = 0; i < N; i++) { const t = frames[i], taps = l.ahead ? [t - l.d, t, t + l.d] : [t - 2 * l.d, t - l.d, t]; for (let k = 0; k < 3; k++) { const c = await get(l.src, taps[k]); for (let j = 0; j < w; j++) x[(i * w + j) * 3 + k] = c[j]; } }
49
+ const y = (await this.run(l.name, { x: this.t(x, [N, w, 3]) })).y.data, o = []; for (let i = 0; i < N; i++) o.push(y.slice(i * w, (i + 1) * w)); return o;
50
+ }
51
+ async final(nE) { // everything the audio up to frame nE (exclusive) settles for good
52
+ if (nE > this.n.e) { (await this.fe(this.n.e, nE, nE * FRAME)).forEach((c, i) => { this.col.e[this.n.e + i] = c; }); this.n.e = nE; }
53
+ const get = async (name, t) => (t < 0 ? this.zero : this.col[name][t]);
54
+ for (const l of this.layers) { const lim = this.n[l.src] - (l.ahead ? l.d : 0); if (lim > this.n[l.name]) { const fr = []; for (let t = this.n[l.name]; t < lim; t++) fr.push(t); (await this.blockCols(l, fr, get)).forEach((c, i) => { this.col[l.name][fr[i]] = c; }); this.n[l.name] = lim; } }
55
+ }
56
+ async spec(f) { // frame f's features [h, s] from audio up to frame f + wait only, silence after it
57
+ const nE = f + this.wait + 1, lim = { e: nE }, sc = { e: [] }; for (const l of this.layers) { lim[l.name] = lim[l.src] - (l.ahead ? l.d : 0); sc[l.name] = []; }
58
+ (await this.fe(nE, f + this.meta.future + 1, nE * FRAME)).forEach((c, i) => { sc.e[nE + i] = c; });
59
+ const get = async (name, t) => { if (t < 0) return this.zero; if (t < lim[name]) return this.col[name][t]; if (!sc[name][t]) sc[name][t] = (await this.blockCols(this.layers.find(l => l.name === name), [t], get))[0]; return sc[name][t]; };
60
+ return [await get(this.hName, f), await get(this.sName, f)];
61
+ }
62
+ async faces(H) { // output frames [nface, nface + H): face, upper face, blinks
63
+ const m = this.meta, w = m.width, hs = new Float32Array(H * w), fh = new Float32Array(2 * w * H);
64
+ for (let i = 0; i < H; i++) { const t = this.nface + i, [h, s] = this.wait === m.future ? [this.col[this.hName][t], this.col[this.sName][t]] : await this.spec(t); hs.set(h, i * w); for (let c = 0; c < w; c++) { fh[c * H + i] = h[c]; fh[(w + c) * H + i] = s[c]; } }
65
+ const fc = new Float32Array((await this.run('face', { h: this.t(hs, [H, w]) })).face.data), closed = this.meta.closed;
66
+ for (let i = 0; i < H; i++) { // no sound for a while (as far as this frame may hear): the mouth eases to the model's own closed pose. Left alone it drifts half open in long silences
67
+ const tt = this.nface + i, upto = Math.min(this.en.length - 1, tt + this.wait); for (let k = Math.max(0, tt - HOLD); k <= upto; k++) if (this.en[k]) this.lastLoud = Math.max(this.lastLoud, k);
68
+ const silent = this.lastLoud < tt - HOLD; this.gate = silent ? this.gate + 0.2 * (1 - this.gate) : this.gate * 0.45; const gt = this.quiet && closed ? this.gate : 0;
69
+ if (this.record) this.log.face.push(Array.from(fc.subarray(i * 101, i * 101 + 101)));
70
+ if (gt > 1e-3) for (let c = 0; c < 101; c++) fc[i * 101 + c] += gt * (closed[c] - fc[i * 101 + c]);
71
+ }
72
+ const hd = await this.run('head', { f: this.t(fh, [1, 2 * w, H]) }), B = m.blink, Z = m.Z, z = new Float32Array(hd.z.data);
73
+ for (let i = 0; i < H; i++) {
74
+ const tt = this.nface + i, bucket = Math.min(Math.floor((tt - this.blinkLast) / 5), B.since - 1), p = 1 / (1 + Math.exp(-hd.blink.data[i * B.since + bucket] / this.blinkTemp));
75
+ if ((tt - this.blinkLast >= B.gap || this.blinkStart < 0) && this.blinkRand() < p) { this.blinkStart = tt; this.blinkLast = tt + 1; if (this.record) this.log.blinks.push(tt); }
76
+ if (this.blinkStart >= 0 && tt - this.blinkStart < B.len) for (let k = 0; k < Z; k++) z[i * Z + k] += this.template[(tt - this.blinkStart) * Z + k];
77
+ }
78
+ const o = await this.run('open', { face: this.t(fc, [H, 101]), z: this.t(z, [H, Z]) });
79
+ for (let i = 0; i < H; i++) this.face[this.nface + i] = { expr: o.expr.data.slice(i * 100, i * 100 + 100), jaw: o.jaw.data.slice(i * 3, i * 3 + 3) };
80
+ this.nface += H;
81
+ }
82
+ async sides() { // what the audio sides say for the frames whose features are final
83
+ const m = this.meta, w = m.width, a = this.naux, b = this.n[this.sName], H = b - a, fw = new Float32Array(2 * w * (H + 4)); // their first convolution reads 4 frames back (zeros before the stream)
84
+ for (let i = 0; i < H + 4; i++) { const t = a - 4 + i; if (t < 0) continue; const h = this.col[this.hName][t], s = this.col[this.sName][t]; for (let c = 0; c < w; c++) { fw[c * (H + 4) + i] = h[c]; fw[(w + c) * (H + 4) + i] = s[c]; } }
85
+ const au = await this.run('aud', { f: this.t(fw, [1, 2 * w, H + 4]), ha: this.t(this.ha, [2, 1, m.ahid]), hb: this.t(this.hb, [2, 1, m.ahid]) }); this.ha = au.ha2.data; this.hb = au.hb2.data;
86
+ for (let i = 0; i < H; i++) this.aux[a + i] = au.aux.data.slice(i * 34, i * 34 + 34); this.naux = b;
87
+ }
88
+ async block() { // the pose of frames [nb * stride, (nb + 1) * stride)
89
+ const m = this.meta, S = m.stride, K = S + m.look, i0 = this.nb * S, v = new Float32Array(35 * K);
90
+ for (let k = 0; k < K; k++) { if (k - S >= this.known) continue; v[34 * K + k] = 1; const a = this.aux[i0 - S + k]; if (a) for (let c = 0; c < 34; c++) v[c * K + k] = a[c]; }
91
+ const bank = Math.min(Math.max(Math.floor((m.look - this.known + 3) / 4), 0), m.bank - 1), c = (await this.run('ctx', { v: this.t(v, [1, 35 * K]) })).c.data.slice(bank * m.hid, (bank + 1) * m.hid);
92
+ const D = m.dim, n = this.q.length, q1 = n ? this.q[n - 1] : new Float32Array(D), q2 = n > 1 ? this.q[n - 2] : q1;
93
+ const g = await this.run('gru', { c: this.t(c, [1, m.hid]), q1: this.t(q1, [1, D]), q2: this.t(q2, [1, D]), first: this.t(new Float32Array([n ? 0 : 1]), [1]), hx: this.t(this.hx, [2, 2, m.hid]) });
94
+ this.hx = g.hx2.data; const h = new Float32Array(g.h.data), q = new Float32Array(D), dg = [], pr = [];
95
+ for (let d = 0; d < D; d++) {
96
+ const p = (await this.run('digit', { h: this.t(h, [2, m.hid]), d: new this.ort.Tensor('int64', BigInt64Array.from([BigInt(d)]), []), guide: this.t(new Float32Array([this.guide]), []), temp: this.t(new Float32Array([this.temp]), []) })).p.data;
97
+ let u = this.rand(), t = 0, acc = 0; for (; t < m.levels[d] - 1; t++) { acc += p[t]; if (u < acc) break; }
98
+ const row = (d * m.Lm + t) * m.hid; for (let k = 0; k < m.hid; k++) { h[k] += this.dig[row + k]; h[m.hid + k] += this.dig[row + k]; }
99
+ q[d] = (t - m.half[d]) / m.half[d]; if (this.record) { dg.push(t); pr.push(Array.from(p)); }
100
+ }
101
+ if (this.record) { this.log.digits.push(dg); this.log.probs.push(pr); }
102
+ this.q.push(q); if (this.q.length > m.dec_blocks) this.q.shift(); const N = this.q.length, qw = new Float32Array(N * D); this.q.forEach((x, j) => qw.set(x, j * D));
103
+ const pose = (await this.run('vqdec', { q: this.t(qw, [1, N, D]) })).pose.data, body = [0, 1, 2, 12, 13, 14];
104
+ for (let j = 0; j < S; j++) {
105
+ const p = pose.slice(j * 15, j * 15 + 15);
106
+ if (this.smooth < 1) { if (!this.y1) { this.y1 = body.map(b => p[b]); this.y2 = this.y1.slice(); } body.forEach((b, k) => { this.y1[k] += this.smooth * (p[b] - this.y1[k]); this.y2[k] += this.smooth * (this.y1[k] - this.y2[k]); p[b] = this.y2[k]; }); }
107
+ this.pose[i0 + j] = p;
108
+ }
109
+ this.nb++;
110
+ }
111
+ mute(tt) { // the silence gate's value for frame tt (frames in order)
112
+ const upto = Math.min(this.en.length - 1, tt + this.wait); for (let k = Math.max(0, tt - HOLD); k <= upto; k++) if (this.en[k]) this.lastLoud = Math.max(this.lastLoud, k);
113
+ this.gate = this.lastLoud < tt - HOLD ? this.gate + 0.2 * (1 - this.gate) : this.gate * 0.45; return this.quiet && this.meta.closed ? this.gate : 0;
114
+ }
115
+ async stepNano() {
116
+ const m = this.meta, w = m.width, done = [], have = Math.floor(this.an / FRAME), t0 = performance.now(); if (have > this.n.e) await this.final(have);
117
+ for (let lim = Math.min(this.n[this.hName], this.n[this.sName]); this.out < lim;) {
118
+ const H = Math.min(8, lim - this.out), h = new Float32Array(H * w), s = new Float32Array(H * w); for (let i = 0; i < H; i++) { h.set(this.col[this.hName][this.out + i], i * w); s.set(this.col[this.sName][this.out + i], i * w); }
119
+ const o = await this.run('out', { h: this.t(h, [H, w]), s: this.t(s, [H, w]) }), closed = m.closed;
120
+ for (let i = 0; i < H; i++) {
121
+ const d = new Float32Array(118), fc = new Float32Array(103); fc.set(o.expr.data.subarray(i * 100, i * 100 + 100)); fc.set(o.jaw.data.subarray(i * 3, i * 3 + 3), 100); if (this.record) this.log.face.push(Array.from(fc));
122
+ const gt = this.mute(this.out); if (gt > 1e-3) for (let c = 0; c < 103; c++) fc[c] += gt * (closed[c] - fc[c]);
123
+ d.set(fc.subarray(0, 100)); d.set(fc.subarray(100, 103), 103); d.set(o.rot.data.subarray(i * 3, i * 3 + 3), 106); // the head's rotation goes on the neck
124
+ done.push({ index: this.out, data: d }); const old = this.out - 160; if (old >= 0) for (const k in this.col) delete this.col[k][old]; this.out++; this.ms.frames++;
125
+ }
126
+ }
127
+ this.ms.lips += performance.now() - t0; return done;
128
+ }
129
+ // Runs whatever the audio pushed so far allows; returns the new frames [{index, data}] in order.
130
+ async step() {
131
+ if (this.nano) return this.stepNano();
132
+ const m = this.meta, S = m.stride, done = [], have = Math.floor(this.an / FRAME); let t0 = performance.now();
133
+ const nE = this.hop > 1 ? Math.floor((have - m.future) / this.hop) * this.hop + m.future : have;
134
+ if (nE > this.n.e) await this.final(nE);
135
+ const H = Math.min(nE - this.wait, this.wait === m.future ? this.n[this.sName] : 1e9) - this.nface; if (H > 0) for (let i = 0; i < H; i += 8) await this.faces(Math.min(8, H - i));
136
+ this.ms.lips += performance.now() - t0; t0 = performance.now();
137
+ if (this.n[this.sName] > this.naux) await this.sides();
138
+ this.ms.heads += performance.now() - t0; t0 = performance.now();
139
+ while (this.nb * S < this.nface && this.naux >= this.nb * S + this.known) await this.block();
140
+ this.ms.tokens += performance.now() - t0;
141
+ while (this.out < this.nface && this.out < this.nb * S) {
142
+ const fr = this.face[this.out], p = this.pose[this.out], d = new Float32Array(118); d.set(fr.expr); d.set(p.subarray(0, 3), 100); d.set(fr.jaw, 103); d.set(p.subarray(3, 15), 106);
143
+ done.push({ index: this.out, data: d }); delete this.face[this.out]; delete this.pose[this.out]; const old = this.out - 160; if (old >= 0) { delete this.aux[old]; for (const k in this.col) delete this.col[k][old]; } this.out++; this.ms.frames++;
144
+ }
145
+ return done;
146
+ }
147
+ }
package/js/index.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ export declare const SAMPLE_RATE: 16000, FPS: 25, FRAME: 640;
2
+ export declare const LAYOUT: Record<'expression' | 'chest' | 'jaw' | 'neck' | 'leftEye' | 'rightEye' | 'travel', [number, number]>;
3
+ export declare const AHEAD: Record<number, { known: number; wait: number; ready: number }>;
4
+ export type ModelName = 'tiny' | 'nano';
5
+ export type Load = (name: string) => Promise<ArrayBuffer>;
6
+ export interface Settings { ahead?: 0.64 | 0.48 | 0.32 | 0.16 | 0.08 | 0; seed?: number | null; expressiveness?: number }
7
+ export interface LoadOptions extends Settings { model?: ModelName; base?: string | null; load?: Load | null; session?: object | null }
8
+ export declare function loader(model?: ModelName, base?: string | null): Promise<Load>;
9
+ export declare class LipSync {
10
+ static load(ort: unknown, options?: LoadOptions): Promise<LipSync>;
11
+ readonly nano: boolean; ahead: number; expressiveness: number; seed: number;
12
+ /** A frame is ready this many frames (of 40 ms) after its own start. */
13
+ delayFrames: number;
14
+ engine: Engine;
15
+ reset(settings?: Settings): void;
16
+ /** 16 kHz mono samples in, the frames they settled out (118 numbers each, see LAYOUT). */
17
+ process(samples: Float32Array): Promise<Float32Array[]>;
18
+ flush(): Promise<Float32Array[]>;
19
+ }
20
+ export interface EngineOptions { known?: number; wait?: number; guide?: number; temp?: number; blinkTemp?: number; smooth?: number; seed?: number; hop?: number | null; record?: boolean; floor?: number; quiet?: boolean }
21
+ export declare class Engine {
22
+ static create(ort: unknown, load: Load, options?: { session?: object }): Promise<Engine>;
23
+ readonly nano: boolean; out: number; meta: Record<string, unknown>;
24
+ reset(options?: EngineOptions): void;
25
+ push(samples: Float32Array): void;
26
+ step(): Promise<{ index: number; data: Float32Array }[]>;
27
+ }
28
+ export interface ArkitOptions { model?: ModelName; rest?: ArrayLike<number> | null; base?: string | null; load?: Load | null; jaw?: number; lookRange?: number }
29
+ /** Frames as the 51 ARKit blendshape weights. */
30
+ export declare class Arkit {
31
+ static load(options?: ArkitOptions): Promise<Arkit>;
32
+ /** The blendshape names, in the order of the weights. */
33
+ readonly names: string[];
34
+ readonly index: Record<string, number>;
35
+ /** A frame (118 numbers) to its 51 weights, each 0..1. The returned array is reused by the next call. */
36
+ convert(frame: ArrayLike<number>): Float32Array;
37
+ }
package/js/index.js ADDED
@@ -0,0 +1,44 @@
1
+ // callable-lipsync: 16 kHz speech in, FLAME 2023 Open frames out at 25 fps. Runs on onnxruntime-web, in a page, a worker or Node.
2
+ //
3
+ // import * as ort from 'onnxruntime-web';
4
+ // import { LipSync } from 'callable-lipsync';
5
+ // const model = await LipSync.load(ort, { model: 'tiny', base: '/models/tiny/' }); // in Node, leave `base` out
6
+ // const frames = await model.process(samples); // Float32Array, 16 kHz mono -> [Float32Array(118), ...]
7
+ import { Engine } from './engine.js';
8
+ export { Engine };
9
+ export { Arkit } from './arkit.js';
10
+
11
+ export const SAMPLE_RATE = 16000, FPS = 25, FRAME = 640;
12
+ // what the 118 numbers of a frame are: [first, one past the last]. Rotations are axis-angle, in radians.
13
+ export const LAYOUT = { expression: [0, 100], chest: [100, 103], jaw: [103, 106], neck: [106, 109], leftEye: [109, 112], rightEye: [112, 115], travel: [115, 118] };
14
+ // seconds of audio ahead of a frame -> the engine's settings; `ready`: frames after a frame's own start until it is computed
15
+ export const AHEAD = { 0.64: { known: 12, wait: 4, ready: 16 }, 0.48: { known: 8, wait: 4, ready: 12 }, 0.32: { known: 4, wait: 4, ready: 8 }, 0.16: { known: 0, wait: 4, ready: 5 }, 0.08: { known: -2, wait: 2, ready: 3 }, 0: { known: -4, wait: 0, ready: 1 } };
16
+
17
+ // A function that fetches a model's files ('tiny', 'nano', or 'arkit' for the blendshape converter's data): from `base` (a URL ending in /), or, in Node, from this package's models/ folder.
18
+ export async function loader(model = 'tiny', base = null) {
19
+ if (base) return async name => { const r = await fetch(base + name); if (!r.ok) throw new Error(`callable-lipsync: ${base + name}: ${r.status}`); return r.arrayBuffer(); };
20
+ if (typeof process === 'undefined' || !process.versions?.node) throw new Error('callable-lipsync: in a browser, pass { base } (the URL of the folder with the model\'s files)');
21
+ const fs = await import(/* @vite-ignore */ 'node:fs/promises'), dir = new URL(`../models/${model}/`, import.meta.url);
22
+ return async name => { const b = await fs.readFile(new URL(name, dir)); return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength); };
23
+ }
24
+
25
+ export class LipSync {
26
+ // ort: onnxruntime-web (or anything with the same InferenceSession and Tensor). options:
27
+ // model 'tiny' (lips, jaw, face, blinks, gaze, head, neck, upper body) or 'nano' (lips, jaw, face, head)
28
+ // base URL of the folder with the model's files (browser); load: your own (name) => ArrayBuffer
29
+ // ahead, seed, expressiveness: see reset(); session: options for InferenceSession.create
30
+ static async load(ort, { model = 'tiny', base = null, load = null, session = null, ...settings } = {}) {
31
+ const m = new LipSync(); m.engine = await Engine.create(ort, load || await loader(model, base), session ? { session } : {}); m.nano = m.engine.nano; m.ahead = 0.64; m.expressiveness = 2; m.reset(settings); return m;
32
+ }
33
+ // Start a new stream. ahead: seconds of audio the model may hear before a frame is due (0.64, 0.48, 0.32, 0.16, 0.08, 0;
34
+ // nano always uses 0.16). seed: same seed and audio give the same motion (default: a new one). expressiveness: 1 to 3 (tiny).
35
+ reset({ ahead = this.ahead, seed = null, expressiveness = this.expressiveness } = {}) {
36
+ if (this.nano) ahead = 0.16; const mode = AHEAD[ahead]; if (!mode) throw new Error('callable-lipsync: ahead must be one of ' + Object.keys(AHEAD).join(', '));
37
+ this.ahead = +ahead; this.expressiveness = expressiveness; this.delayFrames = mode.ready; this.seed = seed ?? (Math.random() * 2 ** 31) | 0; this.samples = 0;
38
+ this.engine.reset({ known: mode.known, wait: mode.wait, guide: expressiveness, seed: this.seed });
39
+ }
40
+ // Feed 16 kHz mono samples (any length); resolves to the frames it settled, in order (possibly none).
41
+ async process(samples) { this.samples += samples.length; this.engine.push(samples); return (await this.engine.step()).map(f => f.data); }
42
+ // The frames still owed for the audio fed so far (the model waits for audio ahead; this feeds it silence).
43
+ async flush() { const want = Math.floor(this.samples / FRAME) - this.engine.out; if (want <= 0) return []; return (await this.process(new Float32Array((this.delayFrames + 12) * FRAME))).slice(0, want); }
44
+ }
Binary file
@@ -0,0 +1,388 @@
1
+ {
2
+ "names": [
3
+ "browDownLeft",
4
+ "browDownRight",
5
+ "browInnerUp",
6
+ "browOuterUpLeft",
7
+ "browOuterUpRight",
8
+ "cheekPuff",
9
+ "cheekSquintLeft",
10
+ "cheekSquintRight",
11
+ "eyeBlinkLeft",
12
+ "eyeBlinkRight",
13
+ "eyeLookDownLeft",
14
+ "eyeLookDownRight",
15
+ "eyeLookInLeft",
16
+ "eyeLookInRight",
17
+ "eyeLookOutLeft",
18
+ "eyeLookOutRight",
19
+ "eyeLookUpLeft",
20
+ "eyeLookUpRight",
21
+ "eyeSquintLeft",
22
+ "eyeSquintRight",
23
+ "eyeWideLeft",
24
+ "eyeWideRight",
25
+ "jawForward",
26
+ "jawLeft",
27
+ "jawOpen",
28
+ "jawRight",
29
+ "mouthClose",
30
+ "mouthDimpleLeft",
31
+ "mouthDimpleRight",
32
+ "mouthFrownLeft",
33
+ "mouthFrownRight",
34
+ "mouthFunnel",
35
+ "mouthLeft",
36
+ "mouthLowerDownLeft",
37
+ "mouthLowerDownRight",
38
+ "mouthPressLeft",
39
+ "mouthPressRight",
40
+ "mouthPucker",
41
+ "mouthRight",
42
+ "mouthRollLower",
43
+ "mouthRollUpper",
44
+ "mouthShrugLower",
45
+ "mouthShrugUpper",
46
+ "mouthSmileLeft",
47
+ "mouthSmileRight",
48
+ "mouthStretchLeft",
49
+ "mouthStretchRight",
50
+ "mouthUpperUpLeft",
51
+ "mouthUpperUpRight",
52
+ "noseSneerLeft",
53
+ "noseSneerRight"
54
+ ],
55
+ "arrays": {
56
+ "template": {
57
+ "offset": 0,
58
+ "shape": [
59
+ 668,
60
+ 3
61
+ ],
62
+ "dtype": "float32"
63
+ },
64
+ "expr": {
65
+ "offset": 8016,
66
+ "shape": [
67
+ 100,
68
+ 668,
69
+ 3
70
+ ],
71
+ "dtype": "float32"
72
+ },
73
+ "jaw_dirs": {
74
+ "offset": 809616,
75
+ "shape": [
76
+ 9,
77
+ 668,
78
+ 3
79
+ ],
80
+ "dtype": "float32"
81
+ },
82
+ "jaw_weight": {
83
+ "offset": 881760,
84
+ "shape": [
85
+ 668
86
+ ],
87
+ "dtype": "float32"
88
+ },
89
+ "jaw_joint": {
90
+ "offset": 884432,
91
+ "shape": [
92
+ 3
93
+ ],
94
+ "dtype": "float32"
95
+ },
96
+ "jaw_joint_expr": {
97
+ "offset": 884444,
98
+ "shape": [
99
+ 100,
100
+ 3
101
+ ],
102
+ "dtype": "float32"
103
+ },
104
+ "skin": {
105
+ "offset": 885644,
106
+ "shape": [
107
+ 448
108
+ ],
109
+ "dtype": "uint32"
110
+ },
111
+ "corners": {
112
+ "offset": 887436,
113
+ "shape": [
114
+ 118,
115
+ 3
116
+ ],
117
+ "dtype": "uint32"
118
+ },
119
+ "bary": {
120
+ "offset": 888852,
121
+ "shape": [
122
+ 118,
123
+ 3
124
+ ],
125
+ "dtype": "float32"
126
+ },
127
+ "point_weight": {
128
+ "offset": 890268,
129
+ "shape": [
130
+ 118
131
+ ],
132
+ "dtype": "float32"
133
+ },
134
+ "shapes": {
135
+ "offset": 890740,
136
+ "shape": [
137
+ 51,
138
+ 1698
139
+ ],
140
+ "dtype": "float32"
141
+ }
142
+ },
143
+ "rest": {
144
+ "tiny": [
145
+ 0.38546,
146
+ -0.03481,
147
+ -0.23742,
148
+ 0.12059,
149
+ 0.37501,
150
+ -0.46343,
151
+ -0.1219,
152
+ -0.13206,
153
+ -0.07986,
154
+ 1.02781,
155
+ -1.30594,
156
+ 0.545,
157
+ -0.37063,
158
+ 1.01231,
159
+ -0.39495,
160
+ 0.75081,
161
+ 0.63606,
162
+ 0.01536,
163
+ 0.14338,
164
+ -0.10859,
165
+ -0.4963,
166
+ 0.29094,
167
+ 0.77542,
168
+ 0.44657,
169
+ 0.09927,
170
+ 0.92726,
171
+ 1.52795,
172
+ -0.46422,
173
+ -0.42572,
174
+ 0.45075,
175
+ -0.42351,
176
+ -0.46409,
177
+ -1.35411,
178
+ 0.61854,
179
+ 0.15368,
180
+ -0.06088,
181
+ 1.4417,
182
+ -1.22899,
183
+ 0.59709,
184
+ 0.74121,
185
+ 0.1327,
186
+ 0.94605,
187
+ -1.33102,
188
+ 0.02867,
189
+ 0.0728,
190
+ -0.24098,
191
+ -0.265,
192
+ -0.18357,
193
+ -0.25485,
194
+ 0.09712,
195
+ 0.01877,
196
+ -0.1998,
197
+ 0.57824,
198
+ -1.14738,
199
+ 0.00444,
200
+ -0.18779,
201
+ -0.12486,
202
+ 0.39704,
203
+ 0.60483,
204
+ 0.54499,
205
+ -0.44999,
206
+ 0.13643,
207
+ 0.17282,
208
+ 0.68905,
209
+ 1.00009,
210
+ 1.21451,
211
+ -0.4832,
212
+ 0.5581,
213
+ -0.19617,
214
+ -0.88051,
215
+ -0.2006,
216
+ 1.13215,
217
+ 0.39915,
218
+ 0.40073,
219
+ 0.63,
220
+ -1.20541,
221
+ -0.38822,
222
+ 1.00746,
223
+ -0.95966,
224
+ -0.82895,
225
+ 0.01394,
226
+ 0.813,
227
+ -1.25293,
228
+ 0.2938,
229
+ 0.8264,
230
+ 0.04283,
231
+ 0.21433,
232
+ -0.16759,
233
+ 0.19677,
234
+ -0.26609,
235
+ 0.32573,
236
+ -0.73741,
237
+ 0.40871,
238
+ 0.40484,
239
+ -0.54043,
240
+ -0.36415,
241
+ 0.46143,
242
+ -0.16722,
243
+ 0.41432,
244
+ -1.33305,
245
+ 0.0,
246
+ 0.0,
247
+ 0.0,
248
+ 0.01263,
249
+ -0.00429,
250
+ -0.00061,
251
+ 0.0,
252
+ 0.0,
253
+ 0.0,
254
+ 0.0,
255
+ 0.0,
256
+ 0.0,
257
+ 0.0,
258
+ 0.0,
259
+ 0.0,
260
+ 0.0,
261
+ 0.0,
262
+ 0.0
263
+ ],
264
+ "nano": [
265
+ 0.44378,
266
+ 0.25824,
267
+ -0.32263,
268
+ 0.00956,
269
+ 0.0882,
270
+ -0.61232,
271
+ -0.24783,
272
+ 0.06467,
273
+ 0.12358,
274
+ 0.88769,
275
+ -1.0587,
276
+ 0.56084,
277
+ -0.72062,
278
+ 1.36247,
279
+ -0.05103,
280
+ 0.43382,
281
+ 1.15729,
282
+ 0.59062,
283
+ 0.49616,
284
+ -0.3903,
285
+ -0.60362,
286
+ -0.32784,
287
+ 1.86152,
288
+ 1.24852,
289
+ -0.09766,
290
+ 0.46979,
291
+ 1.35082,
292
+ -0.85406,
293
+ -0.70051,
294
+ 0.85585,
295
+ -0.10142,
296
+ 0.20048,
297
+ -1.02354,
298
+ 0.4706,
299
+ 0.61823,
300
+ -0.23791,
301
+ 1.0677,
302
+ -0.58181,
303
+ 0.42903,
304
+ 0.77527,
305
+ 0.05077,
306
+ 0.89467,
307
+ -0.86563,
308
+ 0.20787,
309
+ 0.37786,
310
+ 0.22094,
311
+ -0.36139,
312
+ -0.61378,
313
+ -0.10488,
314
+ 0.22147,
315
+ -0.30432,
316
+ -0.53116,
317
+ 1.41581,
318
+ -0.2985,
319
+ -0.15176,
320
+ -0.08286,
321
+ 0.41819,
322
+ -0.67413,
323
+ 0.52626,
324
+ 0.63745,
325
+ -0.20417,
326
+ 0.6027,
327
+ -0.35459,
328
+ 0.90899,
329
+ 0.55678,
330
+ 1.5165,
331
+ -0.74859,
332
+ 1.11415,
333
+ -0.30887,
334
+ -1.179,
335
+ 0.2518,
336
+ 2.1573,
337
+ 0.77769,
338
+ 0.28971,
339
+ 0.34467,
340
+ -0.27504,
341
+ -0.90126,
342
+ 0.70707,
343
+ -1.15814,
344
+ -0.96354,
345
+ -1.01306,
346
+ 0.26372,
347
+ -2.15937,
348
+ 1.30361,
349
+ 0.51309,
350
+ 0.27957,
351
+ -0.22498,
352
+ -0.59751,
353
+ 0.66905,
354
+ -0.95996,
355
+ 0.57674,
356
+ -0.22706,
357
+ 0.05292,
358
+ 0.78784,
359
+ -1.04712,
360
+ 0.09177,
361
+ 0.44341,
362
+ -0.15273,
363
+ 0.69825,
364
+ -1.19288,
365
+ 0.0,
366
+ 0.0,
367
+ 0.0,
368
+ 0.00927,
369
+ 0.0,
370
+ 0.0,
371
+ 0.0,
372
+ 0.0,
373
+ 0.0,
374
+ 0.0,
375
+ 0.0,
376
+ 0.0,
377
+ 0.0,
378
+ 0.0,
379
+ 0.0,
380
+ 0.0,
381
+ 0.0,
382
+ 0.0
383
+ ]
384
+ },
385
+ "vertices": 668,
386
+ "skin": 448,
387
+ "points": 118
388
+ }
Binary file