callable-lipsync 0.1.0__py3-none-any.whl

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.
Files changed (41) hide show
  1. callable_lipsync/__init__.py +93 -0
  2. callable_lipsync/__main__.py +32 -0
  3. callable_lipsync/arkit.py +115 -0
  4. callable_lipsync/data/arkit/arkit.bin +0 -0
  5. callable_lipsync/data/arkit/arkit.json +388 -0
  6. callable_lipsync/data/nano/fe.onnx +0 -0
  7. callable_lipsync/data/nano/meta.json +167 -0
  8. callable_lipsync/data/nano/out.onnx +0 -0
  9. callable_lipsync/data/nano/s0.onnx +0 -0
  10. callable_lipsync/data/nano/s1.onnx +0 -0
  11. callable_lipsync/data/nano/t0.onnx +0 -0
  12. callable_lipsync/data/nano/t1.onnx +0 -0
  13. callable_lipsync/data/nano/t2.onnx +0 -0
  14. callable_lipsync/data/nano/t3.onnx +0 -0
  15. callable_lipsync/data/nano/t4.onnx +0 -0
  16. callable_lipsync/data/tiny/aud.onnx +0 -0
  17. callable_lipsync/data/tiny/ctx.onnx +0 -0
  18. callable_lipsync/data/tiny/digit.onnx +0 -0
  19. callable_lipsync/data/tiny/face.onnx +0 -0
  20. callable_lipsync/data/tiny/fe.onnx +0 -0
  21. callable_lipsync/data/tiny/gru.onnx +0 -0
  22. callable_lipsync/data/tiny/head.onnx +0 -0
  23. callable_lipsync/data/tiny/meta.json +242 -0
  24. callable_lipsync/data/tiny/open.onnx +0 -0
  25. callable_lipsync/data/tiny/s0.onnx +0 -0
  26. callable_lipsync/data/tiny/s1.onnx +0 -0
  27. callable_lipsync/data/tiny/t0.onnx +0 -0
  28. callable_lipsync/data/tiny/t1.onnx +0 -0
  29. callable_lipsync/data/tiny/t2.onnx +0 -0
  30. callable_lipsync/data/tiny/t3.onnx +0 -0
  31. callable_lipsync/data/tiny/t4.onnx +0 -0
  32. callable_lipsync/data/tiny/t5.onnx +0 -0
  33. callable_lipsync/data/tiny/tables.bin +0 -0
  34. callable_lipsync/data/tiny/vqdec.onnx +0 -0
  35. callable_lipsync/engine.py +281 -0
  36. callable_lipsync-0.1.0.dist-info/METADATA +311 -0
  37. callable_lipsync-0.1.0.dist-info/RECORD +41 -0
  38. callable_lipsync-0.1.0.dist-info/WHEEL +4 -0
  39. callable_lipsync-0.1.0.dist-info/entry_points.txt +2 -0
  40. callable_lipsync-0.1.0.dist-info/licenses/LICENSE +202 -0
  41. callable_lipsync-0.1.0.dist-info/licenses/NOTICE +4 -0
@@ -0,0 +1,281 @@
1
+ """callable-lipsync as a stream: 16 kHz audio in, FLAME 2023 Open frames out at 25 fps.
2
+
3
+ The same engine as js/engine.js, on onnxruntime: every block of the network keeps its past outputs, so a new 40 ms
4
+ of audio costs one frame of each block. With the same seed and audio the two give the same motion.
5
+ """
6
+ import json
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+ import onnxruntime as ort
11
+
12
+ FRAME = 640 # samples per frame (40 ms at 16 kHz)
13
+ LOUD = 1e-5 # the mean square of a frame with sound in it (-50 dB)
14
+ HOLD = 10 # frames after the last sound before the mouth is eased shut
15
+ _M = 0xFFFFFFFF
16
+
17
+
18
+ class _Rng:
19
+ """mulberry32, as in the JavaScript engine (so both draw the same numbers)."""
20
+
21
+ def __init__(self, seed):
22
+ self.a = int(seed) & _M
23
+
24
+ def many(self, n):
25
+ a = (self.a + np.arange(1, n + 1, dtype=np.uint64) * np.uint64(0x6D2B79F5)) & np.uint64(_M)
26
+ self.a = int(a[-1]) if n else self.a
27
+ t = ((a ^ (a >> np.uint64(15))) * (a | np.uint64(1))) & np.uint64(_M)
28
+ t = ((t + (((t ^ (t >> np.uint64(7))) * (t | np.uint64(61))) & np.uint64(_M))) & np.uint64(_M)) ^ t
29
+ return ((t ^ (t >> np.uint64(14))) & np.uint64(_M)).astype(np.float64) / 4294967296.0
30
+
31
+ def __call__(self):
32
+ return float(self.many(1)[0])
33
+
34
+
35
+ class Engine:
36
+ """The streaming engine. Most users want `callable_lipsync.LipSync`, a thin wrapper around this.
37
+
38
+ reset() options:
39
+ known, wait audio ahead of a frame: the lips use `wait` frames of it (4 = 0.16 s, the model's full view; fewer:
40
+ silence stands in for the rest), the head `known` frames more past that (12 = 0.64 s in all; 8, 4,
41
+ 0; -4 with wait 0 = none). The nano model always uses wait 4 and has no `known`.
42
+ guide 1 to 3: how strongly head and eyes react to the speech (tiny)
43
+ seed same seed and audio give the same motion
44
+ smooth a light filter on chest and travel (1 = off)
45
+ quiet after 0.4 s without sound the mouth is eased to the model's closed pose, and released as sound returns
46
+ floor the level of a faint noise added to the audio (1e-4 = -80 dB; 0 = none), so that long digital
47
+ silence reads as a quiet room
48
+ """
49
+
50
+ def __init__(self, path, threads=1, providers=("CPUExecutionProvider",)):
51
+ path = Path(path)
52
+ self.meta = m = json.loads((path / "meta.json").read_text())
53
+ so = ort.SessionOptions()
54
+ so.intra_op_num_threads = threads
55
+ so.inter_op_num_threads = 1
56
+ self.s = {n: ort.InferenceSession(str(path / f"{n}.onnx"), so, providers=list(providers)) for n in m["graphs"]}
57
+ self.nano = m.get("kind") == "nano"
58
+ if not self.nano:
59
+ tb, T = (path / "tables.bin").read_bytes(), m["tables"]
60
+ self.dig = np.frombuffer(tb, np.float32, int(np.prod(T["dig"]["shape"])), T["dig"]["offset"]).reshape(T["dig"]["shape"])
61
+ self.template = np.frombuffer(tb, np.float32, int(np.prod(T["template"]["shape"])), T["template"]["offset"]).reshape(T["template"]["shape"])
62
+ self.layers, src = [], "e"
63
+ for i, b in enumerate(m["trunk"]):
64
+ self.layers.append(dict(name=f"t{i}", src=src, **b)); src = f"t{i}"
65
+ self.h_name = src
66
+ for i, b in enumerate(m["slow"]):
67
+ self.layers.append(dict(name=f"s{i}", src=src, **b)); src = f"s{i}"
68
+ self.s_name = src
69
+ self.by_name = {l["name"]: l for l in self.layers}
70
+ self.zero = np.zeros(m["width"], np.float32)
71
+ self.closed = np.asarray(m["closed"], np.float64) if m.get("closed") else None
72
+ self.reset()
73
+
74
+ def reset(self, known=12, wait=4, guide=2.0, temp=1.0, blink_temp=1.0, smooth=0.75, seed=1, hop=None, floor=1e-4, quiet=True):
75
+ m = self.meta
76
+ if self.nano:
77
+ wait, known, hop = m["future"], 0, 1
78
+ self.known, self.wait, self.guide, self.temp, self.blink_temp, self.smooth, self.floor, self.quiet = known, wait, guide, temp, blink_temp, smooth, floor, quiet
79
+ self.en, self.en_rest, self.last_loud, self.gate = [], np.zeros(0), -1e9, 0.0
80
+ self.hiss, self.rand, self.blink_rand = _Rng(0x5BD1E995), _Rng(seed), _Rng((int(seed) ^ 0x9E3779B9) & _M) # the noise floor is the same on every run; blinks draw from their own sequence, so the motion does not depend on how the audio was cut into chunks
81
+ self.hop = hop or (m["stride"] if wait == m["future"] and known >= m["stride"] else 1)
82
+ self.audio, self.a0, self.an = np.zeros(0, np.float32), 0, 0 # samples [a0, an) are held
83
+ self.col = {"e": {}}; self.n = {"e": 0}
84
+ for l in self.layers:
85
+ self.col[l["name"]] = {}; self.n[l["name"]] = 0 # each block's outputs per frame, final up to n
86
+ self.naux, self.aux, self.nface, self.face = 0, {}, 0, {}
87
+ self.blink_last, self.blink_start = 0, -1
88
+ self.nb, self.q, self.pose, self.y1, self.y2, self.out = 0, [], {}, None, None, 0
89
+ if not self.nano:
90
+ self.ha = np.zeros((2, 1, m["ahid"]), np.float32); self.hb = np.zeros((2, 1, m["ahid"]), np.float32); self.hx = np.zeros((2, 2, m["hid"]), np.float32)
91
+
92
+ # ---- audio in
93
+ def push(self, x):
94
+ x = np.asarray(x, np.float32).reshape(-1)
95
+ e = np.concatenate([self.en_rest, x.astype(np.float64)]); k = len(e) // FRAME
96
+ if k:
97
+ self.en.extend(((e[:k * FRAME].reshape(k, FRAME) ** 2).sum(1) / FRAME > LOUD).tolist())
98
+ self.en_rest = e[k * FRAME:]
99
+ if self.floor: # a noise floor: exact digital silence is something the model never heard
100
+ r = self.hiss.many(3 * len(x)).reshape(-1, 3)
101
+ x = (x.astype(np.float64) + 2 * self.floor * (r[:, 0] + r[:, 1] + r[:, 2] - 1.5)).astype(np.float32)
102
+ keep = max(self.a0, self.an - 16 * FRAME)
103
+ self.audio = np.concatenate([self.audio[keep - self.a0:], x]); self.a0 = keep; self.an += len(x)
104
+
105
+ def _window(self, f0, f1, end): # audio of frames [f0, f1), zeros before the stream and from sample `end` on
106
+ x = np.zeros((f1 - f0) * FRAME, np.float32); a, b = max(f0 * FRAME, self.a0, 0), min(f1 * FRAME, end, self.an)
107
+ if b > a:
108
+ x[a - f0 * FRAME:b - f0 * FRAME] = self.audio[a - self.a0:b - self.a0]
109
+ return x
110
+
111
+ def _run(self, name, **feeds):
112
+ s = self.s[name]
113
+ return dict(zip([o.name for o in s.get_outputs()], s.run(None, feeds)))
114
+
115
+ def _fe(self, f0, f1, end): # the vectors into the trunk for frames [f0, f1)
116
+ r = self._run("fe", audio=self._window(f0 - 2, f1, end)[None])["e"]
117
+ return [r[i - f0 + 2].copy() for i in range(f0, f1)]
118
+
119
+ def _block_cols(self, l, frames, get): # block l at `frames` from its input's columns
120
+ x = np.empty((len(frames), self.meta["width"], 3), np.float32); d = l["d"]
121
+ for i, t in enumerate(frames):
122
+ for k, tap in enumerate((t - d, t, t + d) if l["ahead"] else (t - 2 * d, t - d, t)):
123
+ x[i, :, k] = get(l["src"], tap)
124
+ y = self._run(l["name"], x=x)["y"]
125
+ return [y[i].copy() for i in range(len(frames))]
126
+
127
+ def _final(self, n_e): # everything the audio up to frame n_e (exclusive) settles for good
128
+ if n_e > self.n["e"]:
129
+ for i, c in enumerate(self._fe(self.n["e"], n_e, n_e * FRAME)):
130
+ self.col["e"][self.n["e"] + i] = c
131
+ self.n["e"] = n_e
132
+ get = lambda name, t: self.zero if t < 0 else self.col[name][t]
133
+ for l in self.layers:
134
+ lim = self.n[l["src"]] - (l["d"] if l["ahead"] else 0)
135
+ if lim > self.n[l["name"]]:
136
+ fr = list(range(self.n[l["name"]], lim))
137
+ for t, c in zip(fr, self._block_cols(l, fr, get)):
138
+ self.col[l["name"]][t] = c
139
+ self.n[l["name"]] = lim
140
+
141
+ def _spec(self, f): # frame f's features [h, s] from audio up to frame f + wait only, silence after it
142
+ n_e = f + self.wait + 1; lim = {"e": n_e}; sc = {"e": {}}
143
+ for l in self.layers:
144
+ lim[l["name"]] = lim[l["src"]] - (l["d"] if l["ahead"] else 0); sc[l["name"]] = {}
145
+ for i, c in enumerate(self._fe(n_e, f + self.meta["future"] + 1, n_e * FRAME)):
146
+ sc["e"][n_e + i] = c
147
+
148
+ def get(name, t):
149
+ if t < 0:
150
+ return self.zero
151
+ if t < lim[name]:
152
+ return self.col[name][t]
153
+ if t not in sc[name]:
154
+ sc[name][t] = self._block_cols(self.by_name[name], [t], get)[0]
155
+ return sc[name][t]
156
+ return get(self.h_name, f), get(self.s_name, f)
157
+
158
+ def _mute(self, tt): # the silence gate's value for frame tt (frames in order)
159
+ for k in range(max(0, tt - HOLD), min(len(self.en) - 1, tt + self.wait) + 1):
160
+ if self.en[k]:
161
+ self.last_loud = max(self.last_loud, k)
162
+ self.gate = self.gate + 0.2 * (1 - self.gate) if self.last_loud < tt - HOLD else self.gate * 0.45
163
+ return self.gate if self.quiet and self.closed is not None else 0.0
164
+
165
+ # ---- tiny
166
+ def _faces(self, H): # output frames [nface, nface + H): face, upper face, blinks
167
+ m = self.meta; w = m["width"]; hs = np.empty((H, w), np.float32); fh = np.empty((1, 2 * w, H), np.float32)
168
+ for i in range(H):
169
+ t = self.nface + i
170
+ h, s = (self.col[self.h_name][t], self.col[self.s_name][t]) if self.wait == m["future"] else self._spec(t)
171
+ hs[i] = h; fh[0, :w, i] = h; fh[0, w:, i] = s
172
+ fc = self._run("face", h=hs)["face"].copy()
173
+ for i in range(H):
174
+ gt = self._mute(self.nface + i)
175
+ if gt > 1e-3:
176
+ fc[i] = (fc[i].astype(np.float64) + gt * (self.closed - fc[i])).astype(np.float32)
177
+ hd = self._run("head", f=fh); z = hd["z"].copy(); B = m["blink"]
178
+ for i in range(H):
179
+ tt = self.nface + i; bucket = min((tt - self.blink_last) // 5, B["since"] - 1)
180
+ p = 1 / (1 + np.exp(-float(hd["blink"][i, bucket]) / self.blink_temp))
181
+ if (tt - self.blink_last >= B["gap"] or self.blink_start < 0) and self.blink_rand() < p:
182
+ self.blink_start = tt; self.blink_last = tt + 1
183
+ if self.blink_start >= 0 and tt - self.blink_start < B["len"]:
184
+ z[i] += self.template[tt - self.blink_start]
185
+ o = self._run("open", face=fc, z=z)
186
+ for i in range(H):
187
+ self.face[self.nface + i] = (o["expr"][i].copy(), o["jaw"][i].copy())
188
+ self.nface += H
189
+
190
+ def _sides(self): # what the audio sides say for the frames whose features are final
191
+ m = self.meta; w = m["width"]; a, b = self.naux, self.n[self.s_name]; H = b - a
192
+ fw = np.zeros((1, 2 * w, H + 4), np.float32) # their first convolution reads 4 frames back (zeros before the stream)
193
+ for i in range(H + 4):
194
+ t = a - 4 + i
195
+ if t >= 0:
196
+ fw[0, :w, i] = self.col[self.h_name][t]; fw[0, w:, i] = self.col[self.s_name][t]
197
+ au = self._run("aud", f=fw, ha=self.ha, hb=self.hb); self.ha, self.hb = au["ha2"], au["hb2"]
198
+ for i in range(H):
199
+ self.aux[a + i] = au["aux"][i].copy()
200
+ self.naux = b
201
+
202
+ def _block(self): # the pose of frames [nb * stride, (nb + 1) * stride)
203
+ m = self.meta; S = m["stride"]; K = S + m["look"]; i0 = self.nb * S; hid, D = m["hid"], m["dim"]
204
+ v = np.zeros((35, K), np.float32)
205
+ for k in range(K):
206
+ if k - S >= self.known:
207
+ continue
208
+ v[34, k] = 1; a = self.aux.get(i0 - S + k)
209
+ if a is not None:
210
+ v[:34, k] = a
211
+ bank = min(max((m["look"] - self.known + 3) // 4, 0), m["bank"] - 1)
212
+ c = self._run("ctx", v=v.reshape(1, -1))["c"][bank:bank + 1]
213
+ n = len(self.q); q1 = self.q[-1] if n else np.zeros(D, np.float32); q2 = self.q[-2] if n > 1 else q1
214
+ g = self._run("gru", c=c, q1=q1[None], q2=q2[None], first=np.array([0.0 if n else 1.0], np.float32), hx=self.hx)
215
+ self.hx = g["hx2"]; h = g["h"].copy(); q = np.zeros(D, np.float32)
216
+ guide, temp = np.array(self.guide, np.float32), np.array(self.temp, np.float32)
217
+ for d in range(D):
218
+ p = self._run("digit", h=h, d=np.array(d, np.int64), guide=guide, temp=temp)["p"]
219
+ u, acc, L = self.rand(), 0.0, m["levels"][d]; t = L - 1
220
+ for i in range(L - 1):
221
+ acc += float(p[i])
222
+ if u < acc:
223
+ t = i; break
224
+ h += self.dig[d * m["Lm"] + t]
225
+ q[d] = (t - m["half"][d]) / m["half"][d]
226
+ self.q.append(q); self.q = self.q[-m["dec_blocks"]:]
227
+ pose = self._run("vqdec", q=np.stack(self.q)[None])["pose"]; body = (0, 1, 2, 12, 13, 14)
228
+ for j in range(S):
229
+ p = pose[j].copy()
230
+ if self.smooth < 1:
231
+ if self.y1 is None:
232
+ self.y1 = [float(p[b]) for b in body]; self.y2 = list(self.y1)
233
+ for k, b in enumerate(body):
234
+ self.y1[k] += self.smooth * (float(p[b]) - self.y1[k]); self.y2[k] += self.smooth * (self.y1[k] - self.y2[k]); p[b] = self.y2[k]
235
+ self.pose[i0 + j] = p
236
+ self.nb += 1
237
+
238
+ def _forget(self):
239
+ old = self.out - 160
240
+ if old >= 0:
241
+ self.aux.pop(old, None)
242
+ for c in self.col.values():
243
+ c.pop(old, None)
244
+
245
+ def _step_nano(self):
246
+ m = self.meta; done = []; have = self.an // FRAME
247
+ if have > self.n["e"]:
248
+ self._final(have)
249
+ lim = min(self.n[self.h_name], self.n[self.s_name])
250
+ while self.out < lim:
251
+ H = min(8, lim - self.out)
252
+ o = self._run("out", h=np.stack([self.col[self.h_name][self.out + i] for i in range(H)]), s=np.stack([self.col[self.s_name][self.out + i] for i in range(H)]))
253
+ for i in range(H):
254
+ fc = np.concatenate([o["expr"][i], o["jaw"][i]]); gt = self._mute(self.out)
255
+ if gt > 1e-3:
256
+ fc = (fc.astype(np.float64) + gt * (self.closed - fc)).astype(np.float32)
257
+ d = np.zeros(118, np.float32); d[:100] = fc[:100]; d[103:106] = fc[100:]; d[106:109] = o["rot"][i] # the head's rotation goes on the neck
258
+ done.append(d); self._forget(); self.out += 1
259
+ return done
260
+
261
+ def step(self):
262
+ """Runs whatever the audio pushed so far allows; returns the new frames, in order, as an array (n, 118)."""
263
+ if self.nano:
264
+ done = self._step_nano()
265
+ else:
266
+ m = self.meta; S = m["stride"]; done = []; have = self.an // FRAME
267
+ n_e = (have - m["future"]) // self.hop * self.hop + m["future"] if self.hop > 1 else have
268
+ if n_e > self.n["e"]:
269
+ self._final(n_e)
270
+ H = min(n_e - self.wait, self.n[self.s_name] if self.wait == m["future"] else 10 ** 9) - self.nface
271
+ for i in range(0, max(H, 0), 8):
272
+ self._faces(min(8, H - i))
273
+ if self.n[self.s_name] > self.naux:
274
+ self._sides()
275
+ while self.nb * S < self.nface and self.naux >= self.nb * S + self.known:
276
+ self._block()
277
+ while self.out < self.nface and self.out < self.nb * S:
278
+ (expr, jaw), p = self.face.pop(self.out), self.pose.pop(self.out)
279
+ d = np.zeros(118, np.float32); d[:100] = expr; d[100:103] = p[:3]; d[103:106] = jaw; d[106:118] = p[3:15]
280
+ done.append(d); self._forget(); self.out += 1
281
+ return np.stack(done) if done else np.zeros((0, 118), np.float32)
@@ -0,0 +1,311 @@
1
+ Metadata-Version: 2.5
2
+ Name: callable-lipsync
3
+ Version: 0.1.0
4
+ Summary: A tiny speech-to-face model: streaming lip sync, blinks, gaze and head motion on one CPU thread
5
+ Project-URL: Homepage, https://callable.com.ai
6
+ Project-URL: Repository, https://github.com/callabledev/callable-lipsync
7
+ Project-URL: Issues, https://github.com/callabledev/callable-lipsync/issues
8
+ Author-email: Callable <support@callable.com.ai>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ Keywords: FLAME,animation,avatar,lip sync,lipsync,onnx,speech,talking head
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Multimedia :: Graphics :: 3D Modeling
24
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
25
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
26
+ Requires-Python: >=3.9
27
+ Requires-Dist: numpy
28
+ Requires-Dist: onnxruntime>=1.17
29
+ Provides-Extra: test
30
+ Requires-Dist: pytest; extra == 'test'
31
+ Description-Content-Type: text/markdown
32
+
33
+ [![Email](https://img.shields.io/badge/Email-gray.svg?style=for-the-badge&logo=gmail)](mailto:support@callable.com.ai) [![Website](https://img.shields.io/badge/callable.com.ai-blue.svg?style=for-the-badge)](https://callable.com.ai) [![Demo](https://img.shields.io/badge/Live_demo-green.svg?style=for-the-badge)](https://research.callable.com.ai/lipsync/) [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-lightgrey.svg?style=for-the-badge)](https://github.com/callabledev/callable-lipsync/blob/main/LICENSE)
34
+
35
+ [![PyPI version](https://img.shields.io/pypi/v/callable-lipsync)](https://pypi.org/project/callable-lipsync/) [![npm version](https://img.shields.io/npm/v/callable-lipsync)](https://www.npmjs.com/package/callable-lipsync) [![Python version](https://img.shields.io/pypi/pyversions/callable-lipsync)](https://pypi.org/project/callable-lipsync/)
36
+
37
+ <br/>
38
+ <h1 align="center">callable-lipsync</h1>
39
+ <br/>
40
+
41
+ **callable-lipsync** - a tiny pre-trained streaming speech-to-face model by [Callable](https://callable.com.ai/). Speech (audio) goes in, face animation parameters come out (FLAME 2023 Open / ARKit). Needs 160ms lookahead for lips+face and 640ms for head movements. Try the [live demo](https://research.callable.com.ai/lipsync/).
42
+
43
+ Comes in 2 sizes: `tiny` (16.8M; 36x realtime) and `nano` (2.4M; 95x realtime), on one CPU thread in Python. In a browser (WebAssembly) they run at 7x and 18x realtime.
44
+
45
+ Trained on English, might work on other languages.
46
+
47
+ <br/>
48
+
49
+ <p align="center">
50
+ <img src="https://raw.githubusercontent.com/callabledev/callable-lipsync/main/files/demo.gif" width="720" />
51
+ </p>
52
+
53
+ <details>
54
+ <summary>Demo with sound</summary>
55
+
56
+ [files/demo.mp4](https://github.com/callabledev/callable-lipsync/blob/main/files/demo.mp4)
57
+
58
+ A recorded two-person conversation. The avatar voices one speaker and listens to the other. Both faces are drawn from the same frames of the `tiny` model: a FLAME 2023 Open head, and a 2D face driven by ARKit blendshape weights.
59
+
60
+ </details>
61
+
62
+ <br/>
63
+
64
+ <h2 align="center">Fast start</h2>
65
+ <br/>
66
+
67
+ <details>
68
+ <summary>Dependencies</summary>
69
+
70
+ Python:
71
+
72
+ - `python 3.9+`;
73
+ - `onnxruntime>=1.17` and `numpy` (installed with the package);
74
+ - no GPU, no PyTorch.
75
+
76
+ JavaScript:
77
+
78
+ - `onnxruntime-web>=1.17` (a peer dependency);
79
+ - any current browser, or Node 18+.
80
+
81
+ The model files ship inside both packages (about 21 MB for the two models and the ARKit converter's data together). Nothing is downloaded at run time.
82
+
83
+ </details>
84
+
85
+ **Using pip**:
86
+ `pip install callable-lipsync`
87
+
88
+ ```python3
89
+ from callable_lipsync import LipSync
90
+
91
+ model = LipSync("tiny") # or "nano"
92
+ for chunk in audio_stream: # float32, 16 kHz mono, any chunk size
93
+ frames = model(chunk) # (n, 118): the frames this audio settled, 25 per second
94
+ ```
95
+
96
+ A whole clip at once:
97
+
98
+ ```python3
99
+ from callable_lipsync import animate
100
+
101
+ frames = animate(wav, model="tiny") # (len(wav) // 640, 118)
102
+ ```
103
+
104
+ **Using npm**:
105
+ `npm install callable-lipsync onnxruntime-web`
106
+
107
+ ```js
108
+ import * as ort from 'onnxruntime-web';
109
+ import { LipSync } from 'callable-lipsync';
110
+
111
+ // in a browser: serve node_modules/callable-lipsync/models/ and point `base` at it; in Node, leave `base` out
112
+ const model = await LipSync.load(ort, { model: 'tiny', base: '/models/tiny/' });
113
+ const frames = await model.process(samples); // Float32Array, 16 kHz mono -> [Float32Array(118), ...]
114
+ ```
115
+
116
+ Python and JavaScript run the same engine: the same audio and seed give the same frames in both.
117
+
118
+ <br/>
119
+
120
+ <h2 align="center">Key Features</h2>
121
+ <br/>
122
+
123
+ - **Tiny**
124
+
125
+ Two sizes. `tiny` is 16.8M parameters and a 17.4 MB download. `nano` is 2.4M parameters and 2.5 MB.
126
+
127
+ - **Fast**
128
+
129
+ One 40 ms frame takes about **1 ms** on a single CPU thread in Python and about **6 ms** in WebAssembly in a browser (`tiny`). `nano` takes 0.4 ms and 2 ms.
130
+
131
+ - **The whole face, not only the lips**
132
+
133
+ `tiny` gives lips, jaw, cheeks and brows, blinks, gaze, head and neck rotation and a little upper-body sway. `nano` gives lips, jaw, face and head rotation.
134
+
135
+ - **Streaming**
136
+
137
+ Feed it audio in chunks of any size as it arrives. It keeps its own state and costs the same per frame however long the stream runs.
138
+
139
+ - **Works with any amount of audio ahead**
140
+
141
+ A text-to-speech engine usually has audio ready slightly before it is heard, and the model uses that to make the head move with the words. With a live microphone it has none, and it still works: tell it how much it gets (0 to 0.64 s), the same weights handle all of it.
142
+
143
+ - **FLAME and ARKit output**
144
+
145
+ Frames are [FLAME 2023 Open](https://flame.is.tue.mpg.de/) parameters. For avatars rigged with ARKit blendshapes, a converter in both packages turns each frame into the 51 ARKit weights (see [Output](#output)).
146
+
147
+ - **No Strings Attached**
148
+
149
+ Published under a permissive license (Apache 2.0). No telemetry, no keys, no registration, no server: the model runs where your code runs.
150
+
151
+ <br/>
152
+
153
+ <h2 align="center">Models</h2>
154
+ <br/>
155
+
156
+ | | tiny | nano |
157
+ |---|:---:|:---:|
158
+ | Lips and jaw | ✅ | ✅ |
159
+ | Cheeks, brows, rest of the face | ✅ | ✅ |
160
+ | Head rotation | ✅ | ✅ |
161
+ | Blinks | ✅ | ❌ |
162
+ | Gaze | ✅ | ❌ |
163
+ | Neck separate from the chest | ✅ | ❌ |
164
+ | Upper-body sway | ✅ | ❌ |
165
+ | Works with no audio ahead (live microphone) | ✅ | ❌ |
166
+ | Head motion planned on up to 0.64 s of audio ahead | ✅ | ❌ |
167
+ | New head and eye motion on every run | ✅ | ❌ |
168
+ | Streaming, any chunk size | ✅ | ✅ |
169
+ | ARKit blendshape weights | ✅ | ✅ |
170
+ | Python and JavaScript | ✅ | ✅ |
171
+ | Parameters | 16.8M | 2.4M |
172
+ | Size (ONNX, 8-bit weights) | 17.4 MB | 2.5 MB |
173
+ | Audio ahead | 0 to 0.64 s, your choice | 0.16 s, fixed |
174
+ | Python, one thread | 1.1 ms a frame | 0.4 ms a frame |
175
+ | Browser (WebAssembly), one thread | 5.8 ms a frame | 2.2 ms a frame |
176
+
177
+ Measured on an AMD Ryzen 7 9700X; a frame is 40 ms of audio. `tiny` at 0.64 s of audio ahead.
178
+
179
+ How much audio `tiny` gets ahead of each frame decides how well the head follows the speech:
180
+
181
+ | Audio ahead | Lips | Head, eyes, body |
182
+ |---|---|---|
183
+ | 0.64 s | full | turns and nods land on the speech (the reference) |
184
+ | 0.32 s | full | nods about 75% of that, turns about 55% |
185
+ | 0.16 s | full | nods about 40%; turns no longer follow the speech |
186
+ | none | lip error about 30% higher | natural motion, not timed to the speech |
187
+
188
+ ```python3
189
+ model = LipSync("tiny", ahead=0.16) # 0.64, 0.48, 0.32, 0.16, 0.08 or 0
190
+ ```
191
+
192
+ <br/>
193
+
194
+ <h2 align="center">Output</h2>
195
+ <br/>
196
+
197
+ 25 frames a second, 118 numbers each. Rotations are axis-angle, in radians.
198
+
199
+ | Numbers | What |
200
+ |---|---|
201
+ | 0..99 | FLAME 2023 Open expression |
202
+ | 100..102 | chest rotation |
203
+ | 103..105 | jaw |
204
+ | 106..108 | neck |
205
+ | 109..114 | left and right eye |
206
+ | 115..117 | travel of the upper body, metres |
207
+
208
+ `nano` fills expression, jaw and neck and leaves the rest at zero. In Python, `callable_lipsync.LAYOUT` has these as slices.
209
+
210
+ **ARKit blendshapes**
211
+
212
+ If your avatar is rigged with ARKit blendshapes (as most game-engine and phone-tracked faces are), convert the frames to the 51 ARKit weights, 0 to 1 each: `jawOpen`, `mouthFunnel`, `mouthSmileLeft`, `eyeBlinkLeft`, `browInnerUp` and the rest. The converter is in both packages and gives the same weights in both.
213
+
214
+ ```python3
215
+ from callable_lipsync import LipSync, Arkit
216
+
217
+ model, arkit = LipSync("tiny"), Arkit("tiny")
218
+ weights = arkit(model(chunk)) # (n, 51), in the order of arkit.names
219
+ ```
220
+
221
+ ```js
222
+ import { LipSync, Arkit } from 'callable-lipsync';
223
+
224
+ const arkit = await Arkit.load({ model: 'tiny', base: '/models/arkit/' }); // in Node, leave `base` out
225
+ for (const frame of await model.process(samples)) {
226
+ const weights = arkit.convert(frame); // Float32Array(51), in the order of arkit.names
227
+ }
228
+ ```
229
+
230
+ It takes about 0.2 ms a frame. `jawOpen` and the eight `eyeLook` weights come straight from the jaw's and the eyes' rotation; the others are solved from the face's shape. The head, neck and chest rotations and the travel are not blendshapes: apply them to your rig's bones from the frame itself. It is an approximation: ARKit's 51 shapes reproduce about three quarters of `tiny`'s face motion, so treat the weights as a starting point.
231
+
232
+ <br/>
233
+
234
+ <h2 align="center">Typical Use Cases</h2>
235
+ <br/>
236
+
237
+ - Faces for voice agents and voice bots, driven by the text-to-speech audio
238
+ - Avatars in games, apps and video calls, driven by a live microphone
239
+ - Lip sync for characters in the browser with no server and no GPU
240
+ - Batch animation of recorded speech
241
+
242
+ <br/>
243
+ <h2 align="center">Roadmap</h2>
244
+ <br/>
245
+
246
+ **Done**
247
+
248
+ - ✅ `tiny` and `nano` models, streaming, with a choice of lookahead
249
+ - ✅ Python package (`pip install callable-lipsync`)
250
+ - ✅ JavaScript package (`npm install callable-lipsync`), for browsers and Node
251
+ - ✅ FLAME 2023 Open output
252
+ - ✅ ARKit blendshape converter in both packages
253
+ - ✅ Browser demo
254
+
255
+ **Planned**
256
+
257
+ - ⬜ Benchmarks
258
+ - ⬜ Unreal Engine MetaHuman support
259
+ - ⬜ VRM model support
260
+ - ⬜ Unity support
261
+
262
+ <br/>
263
+ <h2 align="center">Links</h2>
264
+ <br/>
265
+
266
+ - [Live demo](https://research.callable.com.ai/lipsync/), and its [source](https://github.com/callabledev/callable-lipsync/tree/main/examples/browser): both models on a recorded conversation, a 3D head and a 2D face
267
+ - The ARKit converter [in JavaScript](https://github.com/callabledev/callable-lipsync/blob/main/js/arkit.js) and [in Python](https://github.com/callabledev/callable-lipsync/blob/main/src/callable_lipsync/arkit.py)
268
+ - [Python example](https://github.com/callabledev/callable-lipsync/blob/main/examples/python/wav_to_frames.py) and [Node example](https://github.com/callabledev/callable-lipsync/blob/main/examples/node/wav_to_frames.mjs)
269
+ - [The engine in JavaScript](https://github.com/callabledev/callable-lipsync/blob/main/js/engine.js) and [in Python](https://github.com/callabledev/callable-lipsync/blob/main/src/callable_lipsync/engine.py)
270
+ - [Callable](https://callable.com.ai)
271
+
272
+ <br/>
273
+ <h2 align="center">Get In Touch</h2>
274
+ <br/>
275
+
276
+ Try the models, create an [issue](https://github.com/callabledev/callable-lipsync/issues/new), or [email](mailto:support@callable.com.ai) us. More about what we build at [callable.com.ai](https://callable.com.ai).
277
+
278
+ **Limitations**
279
+
280
+ - One speaker at a time. Feed it a mix of two voices and it will lip-sync both.
281
+ - Measured mostly on English. It listens to sound, not text, so other languages work, but we have not measured how well.
282
+ - No tongue and no teeth in the output.
283
+ - Input is 16 kHz mono. Resample other audio first.
284
+
285
+ **Model card**
286
+
287
+ | | |
288
+ |---|---|
289
+ | Model | callable-lipsync tiny and nano, by Callable |
290
+ | License | [Apache 2.0](https://github.com/callabledev/callable-lipsync/blob/main/LICENSE) (weights and code) |
291
+ | Training data | Callable's proprietary dataset |
292
+
293
+ **Citations**
294
+
295
+ ```
296
+ @misc{callable-lipsync,
297
+ author = {Callable},
298
+ title = {callable-lipsync: a tiny streaming speech-to-face model},
299
+ year = {2026},
300
+ publisher = {GitHub},
301
+ journal = {GitHub repository},
302
+ howpublished = {\url{https://github.com/callabledev/callable-lipsync}},
303
+ email = {support@callable.com.ai}
304
+ }
305
+ ```
306
+
307
+ <br/>
308
+ <h2 align="center">Third-party material</h2>
309
+ <br/>
310
+
311
+ The browser demo uses the [FLAME 2023 Open](https://flame.is.tue.mpg.de/) head model (CC BY 4.0), conversations from [DailyTalkContiguous](https://huggingface.co/datasets/kyutai/DailyTalkContiguous) (CC BY-SA 4.0, unmodified), [ONNX Runtime Web](https://onnxruntime.ai/) and [three.js](https://threejs.org/). The demo video uses the same head model and one of those conversations.
@@ -0,0 +1,41 @@
1
+ callable_lipsync/__init__.py,sha256=7xA1o-NmrU7FHOhkry33pCEVkevOhqpSuTs0mWMcFds,4864
2
+ callable_lipsync/__main__.py,sha256=uhS2gXhwjuZv2nMJrkCAAnFmNU_DkC7yFXDztA1pWoU,1232
3
+ callable_lipsync/arkit.py,sha256=XqLVNmOA3WTog0_ufFtLfkoyphshk3u1HLrq_z0lEDE,7401
4
+ callable_lipsync/engine.py,sha256=YlJEMMilCBH_78LMtkjjvNKzUik0rKi2Yeo9EBtLE2c,15648
5
+ callable_lipsync/data/arkit/arkit.bin,sha256=nCcpIAXpdkk1zzJvjVB6ejRUiuoaVm1nWWdFz-6Oh28,1237132
6
+ callable_lipsync/data/arkit/arkit.json,sha256=FlseQXhDBt-J1s6CX_LhpwfApHrEyJnR5YSqAnSoeis,4968
7
+ callable_lipsync/data/nano/fe.onnx,sha256=EfMDs1h17pIyXYOemsJFqEE8Uk0FHbu0jU2Roa2rISk,558998
8
+ callable_lipsync/data/nano/meta.json,sha256=-QtHw59vMkn0n84GvQt6xIEJg6gOQlPJxLYg52g6Qcw,1842
9
+ callable_lipsync/data/nano/out.onnx,sha256=-8eDK1DeaFW3_um7JnFpunApZ0rm9lKWkn52qSKscIY,55167
10
+ callable_lipsync/data/nano/s0.onnx,sha256=pY91ceNWuj7fzhgTcxwNCSh6ze5Axt_XjauiPMEScf4,271541
11
+ callable_lipsync/data/nano/s1.onnx,sha256=_RzP1cHBjxJmaTdZYP0V7q6I1wa1YaxtpWolcJn-E80,271541
12
+ callable_lipsync/data/nano/t0.onnx,sha256=XXR2YreFwU9lPq_PnXBv3HqeC62mq-1XXBqKbADr-8Y,271541
13
+ callable_lipsync/data/nano/t1.onnx,sha256=TeYb6o7w8xWIzgKwc6zWdV4gc5Zd3zvHK3EiGMDK54I,271541
14
+ callable_lipsync/data/nano/t2.onnx,sha256=582m9CeAJoeTZV2craAFIZaowWlOj9iIfss6ephr3R8,271541
15
+ callable_lipsync/data/nano/t3.onnx,sha256=kOzSssjO_6IEsCxJAxKibITLCGHgRwMyNWvZZD1JINY,271541
16
+ callable_lipsync/data/nano/t4.onnx,sha256=Yklrj70fxlAfTuwnQbOD4CXuGeyFEYf_PIEdxmcA340,271541
17
+ callable_lipsync/data/tiny/aud.onnx,sha256=7qyYq5K-mz7oHh84jRcpzPjqEmQcgS5YlI9SgO5ZUZ4,3776332
18
+ callable_lipsync/data/tiny/ctx.onnx,sha256=HcB9s3Nv60yQ0xvQWzLkhLSGAE4xISGQ1IJgHf1rV7Q,3690124
19
+ callable_lipsync/data/tiny/digit.onnx,sha256=7IiADgPFuHlvG18lIMabKm_CNhVKT3ObM8P5TCjmeoE,188788
20
+ callable_lipsync/data/tiny/face.onnx,sha256=70TgfrdRslinOdrNcLOQQstxt1MK9pHZPpztYlXj6X4,54979
21
+ callable_lipsync/data/tiny/fe.onnx,sha256=bGRoZcufGaxxPL00X4InOMWFA35AD0OZhyMNmjG4cDI,1242960
22
+ callable_lipsync/data/tiny/gru.onnx,sha256=6vRjyjp7q3za9_8toKr5BsH4v29EYnSNsfzrpzaL9q8,1831631
23
+ callable_lipsync/data/tiny/head.onnx,sha256=N7Flfya5xeLaqvDgoh5uK_LfDbjpHHhfw7ipD5u2rJ0,337362
24
+ callable_lipsync/data/tiny/meta.json,sha256=sdolz-WhyNHSFWfo13EJ0Ra4_c9wQuJBIqS6URFfzZo,2542
25
+ callable_lipsync/data/tiny/open.onnx,sha256=1FiaY4oDiqtK4ayl0pJLZU0PeBdSb7C11tNFcrRDFAI,16575
26
+ callable_lipsync/data/tiny/s0.onnx,sha256=nkufEHl2mbnYcW1yO5uMB4K38ydKCDctLhjukSacEC4,604429
27
+ callable_lipsync/data/tiny/s1.onnx,sha256=o20YAaycl2mKIUuOHVHAk2IeHQ_zoZZ9rJVjaMnL7Vs,604429
28
+ callable_lipsync/data/tiny/t0.onnx,sha256=GkVpF6luOznVLf5znGAL-K9mSoGlhI2m6uUq3UX2zlU,604429
29
+ callable_lipsync/data/tiny/t1.onnx,sha256=-x95fTj9DrjjcXXW-Igkpv71vOaGh3-o_NqBMn30qs8,604429
30
+ callable_lipsync/data/tiny/t2.onnx,sha256=7_oh-uyDeMbUkd3hipmZRSf_Bqr3lRKe8Zklw621A7M,604429
31
+ callable_lipsync/data/tiny/t3.onnx,sha256=BBBmL6u6rOkl4LpJ846OpyGTonbs1I9aUHFhGqXyZe4,604429
32
+ callable_lipsync/data/tiny/t4.onnx,sha256=sKbSV0g6zbAX8hR40FWCaVqAV8e0hz-iQm3ZhDJ7AEQ,604429
33
+ callable_lipsync/data/tiny/t5.onnx,sha256=IaYQkXCjMZmBJWkiUondnBpVI5ntHA4Jydb-0dbx0B8,604429
34
+ callable_lipsync/data/tiny/tables.bin,sha256=F4C_AIEmaFAvqhet6fhIrNWpCI4_-ebmYtajBXBXxfs,129792
35
+ callable_lipsync/data/tiny/vqdec.onnx,sha256=ccxXVGr-DpBq3yOsJUsjahpGlEWjd89WJLqd-brMlSc,1247500
36
+ callable_lipsync-0.1.0.dist-info/METADATA,sha256=RR1iyhBXeqogNOEvw7OvrM2rJviAdy0IAXJ86QE7dpE,12883
37
+ callable_lipsync-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
38
+ callable_lipsync-0.1.0.dist-info/entry_points.txt,sha256=LuJG9DFetxRJOB3oog4JMaMhSbTSM_F8rzngH1V7vek,68
39
+ callable_lipsync-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
40
+ callable_lipsync-0.1.0.dist-info/licenses/NOTICE,sha256=_EkQ0e6eM0ZSQeWapO82PnQIZyl1E3l88s8NGr2fqWo,118
41
+ callable_lipsync-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ callable-lipsync = callable_lipsync.__main__:main