@celljs/ta-lips 0.0.0-stage → 4.28.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/README.en.md ADDED
@@ -0,0 +1,9 @@
1
+ # @celljs/ta-lips
2
+
3
+ In video calls, the lower half of the person's face is drawn again on this computer for each thing Ta says (MuseTalk 1.5), so that her lips match the captions and the voice. Design: `docs/design/ta-call.md` 12.
4
+
5
+ - As the first video call begins the user is asked once whether to download it (about 5 GB); Settings can download or remove it too. Without it the clips play as they are.
6
+ - Server side (host): a Python of its own made with uv in `~/.ta/tools/lips`, with MuseTalk, its models, and the latents and masks of each clip prepared once (`python/lips.py setup`); `lips.py serve` starts as a call begins and stops after a minute unused.
7
+ - Page: through `registerCallMouth` it gets the PCM of Ta's voice and the frame of the clip shown at each moment, and lays the lower face drawn (a WebP with soft edges) over that moment.
8
+ - Captions, voice, clip and mouth share one clock, the time the sound plays; a reading waits about 1.2 s so that its first frames are drawn.
9
+ - Only where the page reaches this computer directly (`files.byUrl`): frames never go through a relay.
package/README.md CHANGED
@@ -1,3 +1,9 @@
1
- # Temporary Holding Version
1
+ # @celljs/ta-lips
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 视频通话时在这台电脑上为 Ta 说的每句话重画人物的下半张脸(MuseTalk 1.5),让嘴型和字幕、声音对上。设计见 `docs/design/ta-call.md` 12。
4
+
5
+ - 第一次视频通话时问一次是否下载(约 5 GB),也可以在设置里下载或移除;不同意就照常播放片段。
6
+ - 服务端(host):用 uv 在 `~/.ta/tools/lips` 建一个独立的 Python,下载 MuseTalk、模型,并为每段片段预先算好人脸潜变量和遮罩(`python/lips.py setup`);通话开始时启动 `lips.py serve`,一分钟没人用就停。
7
+ - 页面:通过 `registerCallMouth` 接收 Ta 声音的 PCM 和每个时刻要显示的片段帧,取回画好的下半脸(带透明边的 WebP),在那一刻贴到片段上。
8
+ - 字幕、声音、片段、口型共用同一条时间线(声音实际播放的时刻);朗读会先等约 1.2 秒,让第一批口型来得及画好。
9
+ - 只在页面能直连这台电脑时启用(`files.byUrl`),不经中继传画面。
package/host/index.mjs ADDED
@@ -0,0 +1,262 @@
1
+ // web-src/host.ts
2
+ import { spawn } from "node:child_process";
3
+ import { existsSync, mkdirSync, rmSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { createInterface } from "node:readline";
7
+
8
+ // web-src/lips-protocol.ts
9
+ var NAME = "@celljs/ta-lips";
10
+ var PYTHON = "3.11";
11
+ var REQUIREMENTS = [
12
+ "torch==2.15.0",
13
+ "torchvision==0.29.2",
14
+ "diffusers==0.30.2",
15
+ "accelerate==0.28.0",
16
+ "transformers==4.39.2",
17
+ "huggingface_hub==0.30.2",
18
+ "numpy==1.26.4",
19
+ "opencv-python==4.11.0.86",
20
+ "librosa==0.11.0",
21
+ "soundfile==0.14.0",
22
+ "einops==0.8.2",
23
+ "omegaconf==2.4.0",
24
+ "safetensors",
25
+ "pillow"
26
+ ];
27
+
28
+ // web-src/host.ts
29
+ var KEEP_FRAMES = 240;
30
+ var IDLE_MS = 5 * 60000;
31
+
32
+ class LipsHost {
33
+ root;
34
+ home;
35
+ setupRun;
36
+ status;
37
+ server;
38
+ serverReady;
39
+ frames = new Map;
40
+ idle;
41
+ constructor(root, home = join(homedir(), ".ta", "tools", "lips")) {
42
+ this.root = root;
43
+ this.home = home;
44
+ this.status = { state: existsSync(join(home, "ready")) ? "ready" : "none", progress: 0 };
45
+ }
46
+ get script() {
47
+ return join(this.root, "python", "lips.py");
48
+ }
49
+ get faces() {
50
+ const built = join(this.root, "..", "..", "..", "public", "faces");
51
+ return existsSync(join(built, "lips.json")) ? built : join(this.root, "..", "ta-web", "public", "faces");
52
+ }
53
+ get python() {
54
+ return join(this.home, "venv", process.platform === "win32" ? "Scripts/python.exe" : "bin/python");
55
+ }
56
+ state() {
57
+ return { ...this.status, supported: LipsHost.supported() };
58
+ }
59
+ setup() {
60
+ if (!LipsHost.supported()) {
61
+ throw new Error("Drawing the mouth needs a Mac with Apple silicon, or a computer with an NVIDIA GPU.");
62
+ }
63
+ if (this.status.state !== "ready" && !this.setupRun) {
64
+ this.status = { state: "setting-up", progress: 0, step: "python" };
65
+ this.setupRun = this.runSetup().then(() => {
66
+ this.status = { state: "ready", progress: 1 };
67
+ }, (error) => {
68
+ this.status = { state: "failed", progress: this.status.progress, error: error instanceof Error ? error.message : String(error) };
69
+ });
70
+ this.setupRun.finally(() => {
71
+ this.setupRun = undefined;
72
+ });
73
+ }
74
+ return this.state();
75
+ }
76
+ remove() {
77
+ this.stopServer();
78
+ rmSync(this.home, { recursive: true, force: true });
79
+ this.status = { state: "none", progress: 0 };
80
+ return this.state();
81
+ }
82
+ async start() {
83
+ if (this.status.state !== "ready") {
84
+ throw new Error("The mouth is not set up.");
85
+ }
86
+ this.touch();
87
+ return { fps: await this.ensureServer() };
88
+ }
89
+ tell(message) {
90
+ this.touch();
91
+ if (message.op === "cut") {
92
+ this.drop(String(message.id));
93
+ }
94
+ this.server?.stdin?.write(`${JSON.stringify(message)}
95
+ `);
96
+ }
97
+ take(id) {
98
+ this.touch();
99
+ const out = [];
100
+ for (const [key, frame] of this.frames) {
101
+ if (key.startsWith(`${id}:`)) {
102
+ out.push(frame);
103
+ this.frames.delete(key);
104
+ }
105
+ }
106
+ return out;
107
+ }
108
+ stop() {
109
+ this.stopServer();
110
+ }
111
+ drop(id) {
112
+ for (const key of this.frames.keys()) {
113
+ if (key.startsWith(`${id}:`)) {
114
+ this.frames.delete(key);
115
+ }
116
+ }
117
+ }
118
+ touch() {
119
+ clearTimeout(this.idle);
120
+ this.idle = setTimeout(() => this.stopServer(), IDLE_MS);
121
+ this.idle.unref?.();
122
+ }
123
+ ensureServer() {
124
+ if (this.serverReady) {
125
+ return this.serverReady;
126
+ }
127
+ const child = spawn(this.python, [this.script, "serve", "--home", this.home, "--faces", this.faces], {
128
+ stdio: ["pipe", "pipe", "ignore"],
129
+ env: { ...process.env, PYTHONUNBUFFERED: "1", PYTORCH_ENABLE_MPS_FALLBACK: "1" }
130
+ });
131
+ this.server = child;
132
+ child.stdin?.on("error", () => {
133
+ return;
134
+ });
135
+ this.serverReady = new Promise((resolve, reject) => {
136
+ const gone = (error) => {
137
+ reject(error);
138
+ if (this.server === child) {
139
+ this.server = undefined;
140
+ this.serverReady = undefined;
141
+ this.frames.clear();
142
+ }
143
+ };
144
+ const lines = createInterface({ input: child.stdout });
145
+ lines.on("line", (line) => {
146
+ let message;
147
+ try {
148
+ message = JSON.parse(line);
149
+ } catch {
150
+ return;
151
+ }
152
+ if ("ready" in message) {
153
+ resolve(message.fps);
154
+ } else if ("error" in message && message.error) {
155
+ reject(new Error(message.error));
156
+ } else if ("frames" in message) {
157
+ for (const frame of message.frames) {
158
+ this.frames.set(`${message.id}:${frame.slot}`, frame);
159
+ }
160
+ while (this.frames.size > KEEP_FRAMES) {
161
+ this.frames.delete(this.frames.keys().next().value);
162
+ }
163
+ }
164
+ });
165
+ child.on("error", gone);
166
+ child.on("exit", (code) => gone(new Error(`The mouth stopped (${code}).`)));
167
+ });
168
+ this.serverReady.catch(() => this.stopServer());
169
+ return this.serverReady;
170
+ }
171
+ stopServer() {
172
+ clearTimeout(this.idle);
173
+ const child = this.server;
174
+ this.server = undefined;
175
+ this.serverReady = undefined;
176
+ this.frames.clear();
177
+ child?.kill();
178
+ }
179
+ async runSetup() {
180
+ mkdirSync(this.home, { recursive: true });
181
+ const uv = await this.uv();
182
+ if (!existsSync(this.python)) {
183
+ await this.run(uv, ["venv", "--python", PYTHON, join(this.home, "venv")], "python");
184
+ }
185
+ await this.run(uv, ["pip", "install", "--python", this.python, ...REQUIREMENTS], "packages");
186
+ await this.run(this.python, [this.script, "setup", "--home", this.home, "--faces", this.faces], "models");
187
+ await this.run(process.execPath, ["-e", `require('fs').writeFileSync(${JSON.stringify(join(this.home, "ready"))}, '')`], "done");
188
+ }
189
+ async uv() {
190
+ const own = join(this.home, "uv", process.platform === "win32" ? "uv.exe" : "uv");
191
+ if (existsSync(own)) {
192
+ return own;
193
+ }
194
+ try {
195
+ await this.run("uv", ["--version"], "python");
196
+ return "uv";
197
+ } catch {
198
+ const url = process.platform === "win32" ? "https://astral.sh/uv/install.ps1" : "https://astral.sh/uv/install.sh";
199
+ const env = { UV_INSTALL_DIR: join(this.home, "uv"), UV_NO_MODIFY_PATH: "1" };
200
+ if (process.platform === "win32") {
201
+ await this.run("powershell", ["-ExecutionPolicy", "ByPass", "-c", `irm ${url} | iex`], "python", env);
202
+ } else {
203
+ await this.run("sh", ["-c", `curl -LsSf ${url} | sh`], "python", env);
204
+ }
205
+ return own;
206
+ }
207
+ }
208
+ run(command, args, step, env = {}) {
209
+ const share = { python: [0, 0.03], packages: [0.03, 0.2], models: [0.2, 1], done: [1, 1] };
210
+ const [from, to] = share[step] ?? [0, 1];
211
+ if (this.status.state === "setting-up") {
212
+ this.status = { ...this.status, step, progress: Math.max(this.status.progress, from) };
213
+ }
214
+ return new Promise((resolve, reject) => {
215
+ const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], env: { ...process.env, ...env } });
216
+ let tail = "";
217
+ const lines = createInterface({ input: child.stdout });
218
+ lines.on("line", (line) => {
219
+ try {
220
+ const message = JSON.parse(line);
221
+ if (typeof message.progress === "number" && this.status.state === "setting-up") {
222
+ this.status = { ...this.status, progress: from + (to - from) * message.progress };
223
+ }
224
+ if (message.error) {
225
+ tail = message.error;
226
+ }
227
+ } catch {}
228
+ });
229
+ child.stderr?.on("data", (data) => {
230
+ tail = `${tail}${data}`.slice(-600);
231
+ });
232
+ child.on("error", reject);
233
+ child.on("exit", (code) => code === 0 ? resolve() : reject(new Error(tail.trim().split(`
234
+ `).slice(-3).join(`
235
+ `) || `${step} failed (${code})`)));
236
+ });
237
+ }
238
+ static supported(platform = process.platform, arch = process.arch) {
239
+ return platform === "darwin" && arch === "arm64" || platform === "linux" || platform === "win32";
240
+ }
241
+ }
242
+ async function activate(host) {
243
+ const root = (await host.listPackages()).find((pkg) => pkg.name === NAME)?.root;
244
+ if (!root) {
245
+ return {};
246
+ }
247
+ const lips = new LipsHost(root);
248
+ return {
249
+ dispose: () => lips.stop(),
250
+ state: () => lips.state(),
251
+ setup: () => lips.setup(),
252
+ remove: () => lips.remove(),
253
+ start: () => lips.start(),
254
+ tell: (message) => lips.tell(message),
255
+ take: (id) => lips.take(String(id)),
256
+ stop: () => lips.stop()
257
+ };
258
+ }
259
+ export {
260
+ activate as default,
261
+ LipsHost
262
+ };
package/package.json CHANGED
@@ -1,6 +1,68 @@
1
1
  {
2
2
  "name": "@celljs/ta-lips",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "4.28.0",
4
+ "description": "A pi package for Ta: the mouth of the person of a video call drawn on this computer for what Ta says (MuseTalk), so that her lips match the words, set up only when the user asks",
5
+ "keywords": [
6
+ "pi-package"
7
+ ],
8
+ "homepage": "https://github.com/cellbang/ta",
9
+ "bugs": {
10
+ "url": "https://github.com/cellbang/ta/issues"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "https://github.com/cellbang/cell.git"
15
+ },
16
+ "license": "MIT",
17
+ "files": [
18
+ "web",
19
+ "host",
20
+ "python",
21
+ "!python/try_*.py",
22
+ "!**/__pycache__",
23
+ "!**/*.map"
24
+ ],
25
+ "scripts": {
26
+ "build": "tsc -b && bun build web-src/index.tsx --format esm --target browser --outfile web/index.js && bun build web-src/host.ts --format esm --target node --outfile host/index.mjs",
27
+ "clean": "rm -rf lib web host *.tsbuildinfo",
28
+ "test": "bun test ./lib",
29
+ "watch": "tsc -b -w --preserveWatchOutput"
30
+ },
31
+ "devDependencies": {
32
+ "@celljs/ta-protocol": "4.28.0",
33
+ "@celljs/ta-web": "4.28.0",
34
+ "@types/react": "^19.3.0"
35
+ },
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "pi": {
40
+ "title": {
41
+ "en": "Lifelike mouth",
42
+ "zh-CN": "真人口型",
43
+ "zh-TW": "真人口型",
44
+ "ja-JP": "リアルな口元"
45
+ },
46
+ "summary": {
47
+ "en": "In video calls, her mouth is drawn again on this computer for each thing Ta says, so that her lips match the words and the voice. Downloads about 5 GB the first time you agree.",
48
+ "zh-CN": "视频通话时在这台电脑上按 Ta 说的每句话重画她的嘴,让嘴型和字、声音对上。第一次同意后下载约 5 GB。",
49
+ "zh-TW": "視訊通話時在這台電腦上按 Ta 說的每句話重畫她的嘴,讓嘴型和字、聲音對上。第一次同意後下載約 5 GB。",
50
+ "ja-JP": "ビデオ通話で、Ta が話すたびにこのコンピューターで口元を描き直し、言葉と声に口の動きを合わせます。初めて同意したときに約 5 GB をダウンロードします。"
51
+ },
52
+ "icon": "Sparkles",
53
+ "web": [
54
+ "./web/index.js"
55
+ ],
56
+ "host": "./host/index.mjs",
57
+ "permissions": {
58
+ "host": {
59
+ "state": "models.use",
60
+ "start": "models.use",
61
+ "tell": "models.use",
62
+ "take": "models.use",
63
+ "stop": "models.use",
64
+ "*": "settings.manage"
65
+ }
66
+ }
67
+ }
68
+ }
package/python/lips.py ADDED
@@ -0,0 +1,482 @@
1
+ """
2
+ The mouth of the person of a video call, made as Ta speaks (docs/design/ta-call.md 12): MuseTalk 1.5 draws the lower
3
+ half of her face again for each frame of a clip, from the sound of Ta's voice, and only that part goes to the page,
4
+ with its edges soft, to lay over the frame it was drawn for.
5
+
6
+ python lips.py setup --home <dir> --faces <dir> downloads MuseTalk and its models, and prepares the clips
7
+ python lips.py serve --home <dir> --faces <dir> answers on stdin and stdout, a JSON object a line
8
+
9
+ What serve is told:
10
+ {"op": "say", "id": <utterance>, "pcm": <base64 of PCM16 mono>, "rate": <Hz>, "fps": <slots a second>, "slots": [[clip, frame], ...], "first": <slot>, "final": bool}
11
+ the next part of what Ta says, and the frame of a clip shown at each 1/fps of it (fps of its first part); `first`
12
+ is the slot of the first of them: one heard from its middle (the service started late) is not drawn
13
+ {"op": "at", "id": <utterance>, "slot": <n>} the slot that shows now: those before it are not drawn any more
14
+ {"op": "cut", "id": <utterance>} what Ta says stopped
15
+ What it says:
16
+ {"ready": true, "fps": <frames a second it draws>}, then {"id": <utterance>, "frames": [{"slot", "clip", "frame", "box": [x, y, w, h], "data": <base64 WebP>}]}
17
+ """
18
+ import argparse
19
+ import base64
20
+ import hashlib
21
+ import json
22
+ import os
23
+ import shutil
24
+ import sys
25
+ import tarfile
26
+ import threading
27
+ import time
28
+ import urllib.request
29
+
30
+ MUSETALK = '2536eaf06b85f775d8e04b7fd81bf6699155a58d'
31
+ MUSETALK_URL = f'https://codeload.github.com/TMElyralab/MuseTalk/tar.gz/{MUSETALK}'
32
+ MODELS = [
33
+ ('TMElyralab/MuseTalk', 'musetalkV15/musetalk.json', 'musetalkV15/musetalk.json'),
34
+ ('TMElyralab/MuseTalk', 'musetalkV15/unet.pth', 'musetalkV15/unet.pth'),
35
+ ('stabilityai/sd-vae-ft-mse', 'config.json', 'sd-vae/config.json'),
36
+ ('stabilityai/sd-vae-ft-mse', 'diffusion_pytorch_model.bin', 'sd-vae/diffusion_pytorch_model.bin'),
37
+ ('openai/whisper-tiny', 'config.json', 'whisper/config.json'),
38
+ ('openai/whisper-tiny', 'pytorch_model.bin', 'whisper/pytorch_model.bin'),
39
+ ('openai/whisper-tiny', 'preprocessor_config.json', 'whisper/preprocessor_config.json'),
40
+ ('madebyollin/taesd', 'config.json', 'taesd/config.json'),
41
+ ('madebyollin/taesd', 'diffusion_pytorch_model.safetensors', 'taesd/diffusion_pytorch_model.safetensors'),
42
+ ('camenduru/MuseTalk', 'face-parse-bisent/79999_iter.pth', 'face-parse-bisent/79999_iter.pth'),
43
+ ]
44
+ RESNET_URL = 'https://download.pytorch.org/models/resnet18-5c106cde.pth'
45
+ # How much of the whole each step of setup is, roughly by the time it takes.
46
+ WEIGHT = {'source': 0.02, 'models': 0.78, 'prepare': 0.2}
47
+ BATCH = 8
48
+ WEBP_QUALITY = 82
49
+ lock = threading.Lock()
50
+
51
+
52
+ def emit(message):
53
+ with lock:
54
+ sys.stdout.write(json.dumps(message, separators=(',', ':')) + '\n')
55
+ sys.stdout.flush()
56
+
57
+
58
+ def reachable(url):
59
+ try:
60
+ urllib.request.urlopen(urllib.request.Request(url, method='HEAD'), timeout=6)
61
+ return True
62
+ except Exception:
63
+ return False
64
+
65
+
66
+ def fetch(url, path, progress=None):
67
+ """A file of the web into path, through a part file, so that a broken download is never taken for a whole one."""
68
+ os.makedirs(os.path.dirname(path), exist_ok=True)
69
+ part = path + '.part'
70
+ have = os.path.getsize(part) if os.path.exists(part) else 0
71
+ request = urllib.request.Request(url, headers={'Range': f'bytes={have}-'} if have else {})
72
+ with urllib.request.urlopen(request, timeout=60) as response:
73
+ if have and response.status != 206:
74
+ have = 0
75
+ total = have + int(response.headers.get('Content-Length') or 0)
76
+ with open(part, 'ab' if have else 'wb') as out:
77
+ done = have
78
+ while True:
79
+ chunk = response.read(1 << 20)
80
+ if not chunk:
81
+ break
82
+ out.write(chunk)
83
+ done += len(chunk)
84
+ if progress and total:
85
+ progress(done / total)
86
+ os.replace(part, path)
87
+
88
+
89
+ class Paths:
90
+ def __init__(self, home, faces):
91
+ self.home = home
92
+ self.faces = faces
93
+ self.source = os.path.join(home, 'MuseTalk')
94
+ self.models = os.path.join(home, 'models')
95
+ self.cache = os.path.join(home, 'cache')
96
+
97
+ def model(self, *parts):
98
+ return os.path.join(self.models, *parts)
99
+
100
+
101
+ def setup(paths):
102
+ os.makedirs(paths.home, exist_ok=True)
103
+ step = {'at': 0.0}
104
+
105
+ def report(name, part, within):
106
+ emit({'step': name, 'progress': round(step['at'] + WEIGHT[part] * within, 4)})
107
+
108
+ if not os.path.exists(os.path.join(paths.source, 'musetalk')):
109
+ archive = os.path.join(paths.home, 'musetalk.tar.gz')
110
+ fetch(MUSETALK_URL, archive, lambda f: report('source', 'source', f))
111
+ with tarfile.open(archive) as tar:
112
+ tar.extractall(paths.home)
113
+ shutil.rmtree(paths.source, ignore_errors=True)
114
+ os.replace(os.path.join(paths.home, f'MuseTalk-{MUSETALK}'), paths.source)
115
+ os.remove(archive)
116
+ step['at'] += WEIGHT['source']
117
+ base = 'https://huggingface.co' if reachable('https://huggingface.co/api/models/openai/whisper-tiny') else 'https://hf-mirror.com'
118
+ # The model of MuseTalk is most of it: its share by its size.
119
+ sizes = [3400 if name.endswith('unet.pth') else 330 if 'sd-vae' in name and name.endswith('.bin') else 150 if 'whisper' in name and name.endswith('.bin') else 60 for _, _, name in MODELS]
120
+ total = sum(sizes) + 45
121
+ done = 0
122
+ for (repo, file, name), size in zip(MODELS, sizes):
123
+ target = paths.model(*name.split('/'))
124
+ fp16 = target.replace('unet.pth', 'unet-fp16.pth')
125
+ if not os.path.exists(target) and not (name.endswith('unet.pth') and os.path.exists(fp16)):
126
+ fetch(f'{base}/{repo}/resolve/main/{file}', target, lambda f, d=done, s=size: report('models', 'models', (d + s * f) / total))
127
+ done += size
128
+ resnet = paths.model('face-parse-bisent', 'resnet18-5c106cde.pth')
129
+ if not os.path.exists(resnet):
130
+ fetch(RESNET_URL, resnet)
131
+ step['at'] += WEIGHT['models']
132
+ prepare(paths, lambda f: report('prepare', 'prepare', f))
133
+ emit({'step': 'done', 'progress': 1})
134
+
135
+
136
+ def runtime(paths):
137
+ sys.path.insert(0, paths.source)
138
+ os.chdir(paths.source)
139
+ import torch
140
+ if torch.backends.mps.is_available():
141
+ device = torch.device('mps')
142
+ elif torch.cuda.is_available():
143
+ device = torch.device('cuda')
144
+ else:
145
+ device = torch.device('cpu')
146
+ return torch, device
147
+
148
+
149
+ def unet_path(paths, torch):
150
+ """MuseTalk's UNet in half precision, as it runs: written once from the download, which is then let go."""
151
+ fp16 = paths.model('musetalkV15', 'unet-fp16.pth')
152
+ full = paths.model('musetalkV15', 'unet.pth')
153
+ if not os.path.exists(fp16):
154
+ weights = torch.load(full, map_location='cpu', weights_only=True)
155
+ torch.save({key: value.half() for key, value in weights.items()}, fp16 + '.part')
156
+ os.replace(fp16 + '.part', fp16)
157
+ os.remove(full)
158
+ return fp16
159
+
160
+
161
+ def clip_hash(path):
162
+ digest = hashlib.sha1()
163
+ with open(path, 'rb') as file:
164
+ digest.update(file.read())
165
+ return digest.hexdigest()
166
+
167
+
168
+ def prepare(paths, progress):
169
+ """
170
+ Of each clip, once (again as a clip changes): the latents of the lower half of her face in each frame, what of the
171
+ frame around it is drawn again (its box and the mask of her jaw, soft), and that part of the frame itself.
172
+ """
173
+ torch, device = runtime(paths)
174
+ import cv2
175
+ import numpy as np
176
+ from musetalk.models.vae import VAE
177
+ from musetalk.utils.blending import get_image_prepare_material
178
+
179
+ boxes = json.load(open(os.path.join(paths.faces, 'lips.json')))
180
+ os.makedirs(paths.cache, exist_ok=True)
181
+ index_path = os.path.join(paths.cache, 'index.json')
182
+ index = json.load(open(index_path)) if os.path.exists(index_path) else {}
183
+ todo = []
184
+ for clip in boxes['clips']:
185
+ digest = clip_hash(os.path.join(paths.faces, f'{clip}.mp4'))
186
+ if index.get(clip) != digest or not os.path.exists(os.path.join(paths.cache, f'{clip}.pt')):
187
+ todo.append((clip, digest))
188
+ if not todo:
189
+ return
190
+ unet_path(paths, torch)
191
+ vae = VAE(model_path=paths.model('sd-vae'))
192
+ vae.vae = vae.vae.half().to(device)
193
+ vae.device = device
194
+ from musetalk.utils import face_parsing
195
+ parsing = face_parsing_at(face_parsing, paths)
196
+ for n, (clip, digest) in enumerate(todo):
197
+ capture = cv2.VideoCapture(os.path.join(paths.faces, f'{clip}.mp4'))
198
+ frames = []
199
+ while True:
200
+ ok, frame = capture.read()
201
+ if not ok:
202
+ break
203
+ frames.append(frame)
204
+ latents, crops, masks, parts, faces = [], [], [], [], []
205
+ for k, frame in enumerate(frames):
206
+ x1, y1, x2, y2 = boxes['clips'][clip][min(k, len(boxes['clips'][clip]) - 1)]
207
+ y2 = min(y2 + 10, frame.shape[0])
208
+ face = cv2.resize(frame[y1:y2, x1:x2], (256, 256), interpolation=cv2.INTER_LANCZOS4)
209
+ latents.append(vae.get_latents_for_unet(face).cpu())
210
+ mask, crop = get_image_prepare_material(frame, [x1, y1, x2, y2], fp=parsing, mode='jaw')
211
+ xs, ys, xe, ye = crop
212
+ part = np.zeros((ye - ys, xe - xs, 3), np.uint8)
213
+ sx, sy = max(0, xs), max(0, ys)
214
+ ex, ey = min(frame.shape[1], xe), min(frame.shape[0], ye)
215
+ part[sy - ys:ey - ys, sx - xs:ex - xs] = frame[sy:ey, sx:ex]
216
+ crops.append(crop)
217
+ masks.append(mask)
218
+ parts.append(part)
219
+ faces.append((x1, y1, x2, y2))
220
+ progress((n + (k + 1) / len(frames)) / len(todo))
221
+ torch.save({'latents': torch.cat(latents), 'crops': crops, 'masks': masks, 'parts': parts, 'faces': faces}, os.path.join(paths.cache, f'{clip}.pt'))
222
+ index[clip] = digest
223
+ json.dump(index, open(index_path, 'w'))
224
+
225
+
226
+ def face_parsing_at(module, paths):
227
+ """MuseTalk's FaceParsing, its weights read from the models of Ta rather than its own directory."""
228
+ original = module.FaceParsing.model_init
229
+
230
+ def model_init(self, resnet_path=None, model_pth=None):
231
+ return original(self, paths.model('face-parse-bisent', 'resnet18-5c106cde.pth'), paths.model('face-parse-bisent', '79999_iter.pth'))
232
+
233
+ module.FaceParsing.model_init = model_init
234
+ return module.FaceParsing(left_cheek_width=90, right_cheek_width=90)
235
+
236
+
237
+ class Utterance:
238
+ def __init__(self, id):
239
+ self.id = id
240
+ self.audio = []
241
+ self.length = 0
242
+ self.slots = []
243
+ self.next = 0
244
+ self.final = False
245
+ self.fps = 24
246
+ self.features = None
247
+ self.featured = -1
248
+
249
+
250
+ class Server:
251
+ def __init__(self, paths):
252
+ self.paths = paths
253
+ torch, device = runtime(paths)
254
+ self.torch, self.device = torch, device
255
+ import numpy as np
256
+ from diffusers import AutoencoderTiny
257
+ from transformers import WhisperModel
258
+ from musetalk.utils.audio_processor import AudioProcessor
259
+ self.np = np
260
+ dtype = torch.float16 if device.type != 'cpu' else torch.float32
261
+ self.dtype = dtype
262
+ from musetalk.models.unet import PositionalEncoding, UNet
263
+ unet = UNet(unet_config=paths.model('musetalkV15', 'musetalk.json'), model_path=unet_path(paths, torch), device=device)
264
+ self.unet = unet.model.to(device, dtype=dtype).eval()
265
+ self.pe = PositionalEncoding(d_model=384).to(device, dtype=dtype)
266
+ self.tiny = AutoencoderTiny.from_pretrained(paths.model('taesd')).to(device, dtype=dtype).eval()
267
+ self.audio = AudioProcessor(feature_extractor_path=paths.model('whisper'))
268
+ self.whisper = WhisperModel.from_pretrained(paths.model('whisper')).to(device, dtype=dtype).eval()
269
+ self.timesteps = torch.tensor([0], device=device)
270
+ # Clips new or changed since setup (a Ta with other clips) are prepared first.
271
+ prepare(paths, lambda done: None)
272
+ self.clips = {}
273
+ for name in json.load(open(os.path.join(paths.cache, 'index.json'))):
274
+ self.clips[name] = torch.load(os.path.join(paths.cache, f'{name}.pt'), weights_only=False)
275
+ self.fps = json.load(open(os.path.join(paths.faces, 'lips.json'))).get('fps', 24)
276
+ self.now = None
277
+ # Utterances heard from their middle: their sound and slots would not line up.
278
+ self.skipped = set()
279
+ self.wake = threading.Event()
280
+ import queue
281
+ self.made = queue.Queue()
282
+ self.speed = self.warm()
283
+
284
+ def warm(self):
285
+ """Runs the models once, as the first runs are slow, and measures how many frames a second they draw."""
286
+ silence = self.np.zeros(32000, self.np.float32)
287
+ u = Utterance('warm')
288
+ u.audio, u.length, u.final, u.fps = [silence], len(silence), True, self.fps
289
+ u.slots = [[next(iter(self.clips)), k] for k in range(BATCH * 2)]
290
+ self.draw(u, u.slots[:BATCH], 0, emit_frames=False)
291
+ if self.device.type == 'mps':
292
+ self.torch.mps.synchronize()
293
+ began = time.time()
294
+ self.draw(u, u.slots[BATCH:], BATCH, emit_frames=False)
295
+ if self.device.type == 'mps':
296
+ self.torch.mps.synchronize()
297
+ return BATCH / max(1e-3, time.time() - began)
298
+
299
+ def take(self, message):
300
+ op, id = message.get('op'), message.get('id')
301
+ if op == 'say':
302
+ if id in self.skipped:
303
+ return
304
+ u = self.now if self.now and self.now.id == id else Utterance(id)
305
+ if u is not self.now:
306
+ if int(message.get('first') or 0) > 0:
307
+ self.skipped.add(id)
308
+ return
309
+ u.fps = int(message.get('fps') or self.fps)
310
+ self.now = u
311
+ pcm = self.np.frombuffer(base64.b64decode(message.get('pcm') or ''), self.np.int16).astype(self.np.float32) / 32768
312
+ rate = int(message.get('rate') or 16000)
313
+ if len(pcm) and rate != 16000:
314
+ n = int(round(len(pcm) * 16000 / rate))
315
+ pcm = self.np.interp(self.np.linspace(0, len(pcm) - 1, n), self.np.arange(len(pcm)), pcm).astype(self.np.float32)
316
+ u.audio.append(pcm)
317
+ u.length += len(pcm)
318
+ u.slots.extend(message.get('slots') or [])
319
+ u.final = u.final or bool(message.get('final'))
320
+ elif op == 'at' and self.now and self.now.id == id:
321
+ # What shows now is late already: the next drawn is a little after it.
322
+ self.now.next = max(self.now.next, int(message.get('slot', 0)) + 2)
323
+ elif op == 'cut' and self.now and self.now.id == id:
324
+ self.now = None
325
+ self.wake.set()
326
+
327
+ def ready(self, u):
328
+ """The slots of u that can be drawn now: the sound of each and a little after it is there, or all of it is."""
329
+ if u.final:
330
+ return len(u.slots)
331
+ heard = u.length / 16000
332
+ return min(len(u.slots), max(0, int((heard - 0.1) * u.fps)))
333
+
334
+ def features(self, u):
335
+ torch = self.torch
336
+ if u.featured == u.length:
337
+ return u.features
338
+ audio = self.np.concatenate(u.audio) if len(u.audio) > 1 else u.audio[0]
339
+ u.audio = [audio]
340
+ segments = [audio[i:i + 30 * 16000] for i in range(0, len(audio), 30 * 16000)] or [audio]
341
+ inputs = [self.audio.feature_extractor(s, return_tensors='pt', sampling_rate=16000).input_features.to(dtype=self.dtype) for s in segments]
342
+ with torch.no_grad():
343
+ u.features = self.audio.get_whisper_chunk(inputs, self.device, self.dtype, self.whisper, len(audio), fps=u.fps, audio_padding_length_left=2, audio_padding_length_right=2)
344
+ u.featured = u.length
345
+ return u.features
346
+
347
+ def draw(self, u, slots, start, emit_frames=True):
348
+ torch, np = self.torch, self.np
349
+ import cv2
350
+ chunks = self.features(u)
351
+ # Of the clips it prepared: one it has not (a Ta with more clips, not set up again) shows as it is.
352
+ rows = [i for i in range(len(slots)) if start + i < len(chunks) and slots[i][0] in self.clips]
353
+ if not rows:
354
+ return
355
+ audio = torch.stack([chunks[start + i] for i in rows]).to(self.device)
356
+ latents = []
357
+ for i in rows:
358
+ own = self.clips[slots[i][0]]['latents']
359
+ latents.append(own[slots[i][1] % len(own)][None])
360
+ latents = torch.cat(latents).to(self.device, dtype=self.dtype)
361
+ with torch.no_grad():
362
+ predicted = self.unet(latents, self.timesteps, encoder_hidden_states=self.pe(audio)).sample
363
+ images = self.tiny.decode(predicted).sample
364
+ images = ((images.float().clamp(-1, 1) + 1) * 127.5).permute(0, 2, 3, 1).cpu().numpy()[..., ::-1].astype(np.uint8)
365
+ if emit_frames:
366
+ self.made.put((u.id, [(start + row, slots[row][0], slots[row][1], image) for row, image in zip(rows, images)]))
367
+
368
+ def finish(self):
369
+ """Lays what the model drew into its frames and sends them, beside the model drawing the next ones."""
370
+ import cv2
371
+ np = self.np
372
+ while True:
373
+ id, rows = self.made.get()
374
+ out = [self.patch(cv2, np, slot, clip, frame, image) for slot, clip, frame, image in rows]
375
+ emit({'id': id, 'frames': [f for f in out if f]})
376
+
377
+ def patch(self, cv2, np, slot, clip, frame, image):
378
+ data = self.clips.get(clip)
379
+ if not data:
380
+ return None
381
+ k = frame % len(data['parts'])
382
+ x1, y1, x2, y2 = data['faces'][k]
383
+ xs, ys, xe, ye = data['crops'][k]
384
+ part = data['parts'][k].copy()
385
+ original = data['parts'][k]
386
+ face = cv2.resize(image, (x2 - x1, y2 - y1), interpolation=cv2.INTER_LINEAR)
387
+ part[y1 - ys:y2 - ys, x1 - xs:x2 - xs] = face
388
+ part = detail(cv2, np, part, original)
389
+ mask = data['masks'][k]
390
+ if mask.ndim == 3:
391
+ mask = mask[..., 0]
392
+ ys_, xs_ = np.nonzero(mask > 2)
393
+ if not len(ys_):
394
+ return None
395
+ top, bottom, left, right = ys_.min(), ys_.max() + 1, xs_.min(), xs_.max() + 1
396
+ rgba = np.dstack([part[top:bottom, left:right], mask[top:bottom, left:right]])
397
+ ok, webp = cv2.imencode('.webp', rgba, [cv2.IMWRITE_WEBP_QUALITY, WEBP_QUALITY])
398
+ if not ok:
399
+ return None
400
+ return {'slot': slot, 'clip': clip, 'frame': k, 'box': [int(xs + left), int(ys + top), int(right - left), int(bottom - top)], 'data': base64.b64encode(webp.tobytes()).decode()}
401
+
402
+ def run(self):
403
+ threading.Thread(target=self.finish, daemon=True).start()
404
+ emit({'ready': True, 'fps': round(self.speed, 1)})
405
+ while True:
406
+ u = self.now
407
+ if not u:
408
+ self.wake.wait(0.5)
409
+ self.wake.clear()
410
+ continue
411
+ limit = self.ready(u)
412
+ if u.next >= limit:
413
+ if u.final and u.next >= len(u.slots):
414
+ self.now = None if self.now is u else self.now
415
+ self.wake.wait(0.05)
416
+ self.wake.clear()
417
+ continue
418
+ start = u.next
419
+ end = min(limit, start + BATCH)
420
+ u.next = end
421
+ self.draw(u, u.slots[start:end], start)
422
+
423
+
424
+ def detail(cv2, np, made, original, sigma=5.0, sharp=0.6):
425
+ """
426
+ Where what MuseTalk drew is the frame as it was (the cheeks, the chin), the colour and the fine detail of the frame
427
+ come back; where it differs (the lips), it takes the colour of the skin around and is sharpened a little.
428
+ """
429
+ made = made.astype(np.float32)
430
+ original = original.astype(np.float32)
431
+ made = tone(cv2, np, made, original, sigma)
432
+ soft_made = cv2.GaussianBlur(made, (0, 0), 1.6)
433
+ soft_original = cv2.GaussianBlur(original, (0, 0), 1.6)
434
+ same = np.exp(-np.abs(soft_made - soft_original).mean(2, keepdims=True) / sigma)
435
+ out = soft_made + same * (original - soft_original) + (1 - same) * (1 + sharp) * (made - soft_made)
436
+ return np.clip(out, 0, 255).astype(np.uint8)
437
+
438
+
439
+ def tone(cv2, np, made, original, sigma):
440
+ """
441
+ The colour of what MuseTalk drew made the frame's (its decoder shifts it a little): the shift is measured where the two
442
+ are alike (the skin), smoothly, and taken away everywhere, the lips with the shift of the skin around them.
443
+ """
444
+ alike = np.exp(-np.abs(cv2.GaussianBlur(made, (0, 0), 3) - cv2.GaussianBlur(original, (0, 0), 3)).mean(2, keepdims=True) / (sigma * 2))
445
+ shift = original - made
446
+ # Of the skin alone: the shift where they are alike, spread over where they are not (normalized blur).
447
+ spread = 12
448
+ near = cv2.GaussianBlur(alike, (0, 0), spread)[..., None] + 1e-3
449
+ local = cv2.GaussianBlur(shift * alike, (0, 0), spread) / near
450
+ return made + local
451
+
452
+
453
+ def serve(paths):
454
+ server = Server(paths)
455
+
456
+ def read():
457
+ for line in sys.stdin:
458
+ line = line.strip()
459
+ if line:
460
+ try:
461
+ server.take(json.loads(line))
462
+ except Exception as error:
463
+ emit({'error': str(error)})
464
+ os._exit(0)
465
+
466
+ threading.Thread(target=read, daemon=True).start()
467
+ server.run()
468
+
469
+
470
+ if __name__ == '__main__':
471
+ os.environ.setdefault('TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD', '1')
472
+ parser = argparse.ArgumentParser()
473
+ parser.add_argument('command', choices=['setup', 'serve'])
474
+ parser.add_argument('--home', required=True)
475
+ parser.add_argument('--faces', required=True)
476
+ args = parser.parse_args()
477
+ paths = Paths(os.path.abspath(args.home), os.path.abspath(args.faces))
478
+ try:
479
+ setup(paths) if args.command == 'setup' else serve(paths)
480
+ except Exception as error:
481
+ emit({'error': f'{type(error).__name__}: {error}'})
482
+ sys.exit(1)
package/web/index.js ADDED
@@ -0,0 +1,376 @@
1
+ // ../ta-protocol/esm/common/language.js
2
+ var TaLanguageUtil;
3
+ (function(TaLanguageUtil2) {
4
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
5
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
6
+ function of(tag) {
7
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
8
+ if (/^zh(\b|-)/.test(said)) {
9
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
10
+ }
11
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
12
+ }
13
+ TaLanguageUtil2.of = of;
14
+ function server(env = typeof process === "undefined" ? {} : process.env) {
15
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
16
+ }
17
+ TaLanguageUtil2.server = server;
18
+ function pick(language, words) {
19
+ return words[of(language)];
20
+ }
21
+ TaLanguageUtil2.pick = pick;
22
+ function say(words) {
23
+ return words[server()];
24
+ }
25
+ TaLanguageUtil2.say = say;
26
+ function chinese(language) {
27
+ return of(language).startsWith("zh");
28
+ }
29
+ TaLanguageUtil2.chinese = chinese;
30
+ function cjk(language) {
31
+ return of(language) !== "en-US";
32
+ }
33
+ TaLanguageUtil2.cjk = cjk;
34
+ function list(language, items) {
35
+ return items.join(cjk(language) ? "、" : ", ");
36
+ }
37
+ TaLanguageUtil2.list = list;
38
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
39
+
40
+ // web-src/i18n.ts
41
+ var EN = {
42
+ title: "Lifelike mouth in video calls",
43
+ hint: "Draws her mouth again on this computer for each thing Ta says, so that her lips match the words. It downloads about 5 GB once.",
44
+ get: "Download",
45
+ getting: "Downloading {percent}%",
46
+ ready: "On",
47
+ remove: "Remove",
48
+ failed: "Could not set it up: {error}",
49
+ unsupported: "Needs a Mac with Apple silicon or a computer with an NVIDIA GPU.",
50
+ askTitle: "Make her mouth match the words?",
51
+ ask: "Ta can draw her mouth again on this computer as she speaks, so that her lips match what she says. It downloads about 5 GB once, then works offline. This call goes on as it is meanwhile.",
52
+ askYes: "Download",
53
+ askNo: "Not now",
54
+ started: "Downloading in the background; the next video call will use it."
55
+ };
56
+ var ZH = {
57
+ title: "视频通话口型更真",
58
+ hint: "在这台电脑上按 Ta 说的每句话重画她的嘴,让嘴型对上字和声音。第一次需要下载约 5 GB。",
59
+ get: "下载",
60
+ getting: "正在下载 {percent}%",
61
+ ready: "已开启",
62
+ remove: "移除",
63
+ failed: "没装好:{error}",
64
+ unsupported: "需要 Apple 芯片的 Mac,或带 NVIDIA 显卡的电脑。",
65
+ askTitle: "让她的嘴型对上说的话?",
66
+ ask: "Ta 可以在这台电脑上边说边重画她的嘴,让嘴型和字、声音一致。需要下载约 5 GB,只下一次,之后离线也能用。这次通话先照常进行。",
67
+ askYes: "下载",
68
+ askNo: "以后再说",
69
+ started: "已在后台下载,下次视频通话就会用上。"
70
+ };
71
+ var ZH_TW = {
72
+ title: "視訊通話口型更真",
73
+ hint: "在這台電腦上按 Ta 說的每句話重畫她的嘴,讓嘴型對上字和聲音。第一次需要下載約 5 GB。",
74
+ get: "下載",
75
+ getting: "正在下載 {percent}%",
76
+ ready: "已開啟",
77
+ remove: "移除",
78
+ failed: "沒裝好:{error}",
79
+ unsupported: "需要 Apple 晶片的 Mac,或有 NVIDIA 顯示卡的電腦。",
80
+ askTitle: "讓她的嘴型對上說的話?",
81
+ ask: "Ta 可以在這台電腦上邊說邊重畫她的嘴,讓嘴型和字、聲音一致。需要下載約 5 GB,只下一次,之後離線也能用。這次通話先照常進行。",
82
+ askYes: "下載",
83
+ askNo: "以後再說",
84
+ started: "已在背景下載,下次視訊通話就會用上。"
85
+ };
86
+ var JA = {
87
+ title: "ビデオ通話の口元をリアルに",
88
+ hint: "Ta が話すたびにこのコンピューターで口元を描き直し、言葉と口の動きを合わせます。初回に約 5 GB をダウンロードします。",
89
+ get: "ダウンロード",
90
+ getting: "ダウンロード中 {percent}%",
91
+ ready: "オン",
92
+ remove: "削除",
93
+ failed: "セットアップできませんでした:{error}",
94
+ unsupported: "Apple シリコンの Mac か、NVIDIA GPU のあるコンピューターが必要です。",
95
+ askTitle: "口の動きを言葉に合わせますか?",
96
+ ask: "Ta は話しながらこのコンピューターで口元を描き直し、言葉と声に口の動きを合わせられます。約 5 GB を一度だけダウンロードし、その後はオフラインでも使えます。この通話はこのまま続きます。",
97
+ askYes: "ダウンロード",
98
+ askNo: "あとで",
99
+ started: "バックグラウンドでダウンロード中です。次のビデオ通話から使われます。"
100
+ };
101
+ var WORDS = { "zh-CN": ZH, "zh-TW": ZH_TW, "en-US": EN, "ja-JP": JA };
102
+ var LipsWords;
103
+ ((LipsWords) => {
104
+ function of(language) {
105
+ return TaLanguageUtil.pick(language, WORDS);
106
+ }
107
+ LipsWords.of = of;
108
+ function fill(text, values) {
109
+ return text.replace(/\{(\w+)\}/g, (_, key) => String(values[key] ?? ""));
110
+ }
111
+ LipsWords.fill = fill;
112
+ })(LipsWords ||= {});
113
+
114
+ // web-src/lips-protocol.ts
115
+ var LIPS_FPS = 12;
116
+ var HOLD_MS = 1200;
117
+ var POLL_MS = 120;
118
+ var STARTS_MS = 9000;
119
+ var KEEP_ALIVE_MS = 20000;
120
+
121
+ // web-src/react.ts
122
+ var React;
123
+ function bind(react) {
124
+ React = react;
125
+ }
126
+
127
+ // web-src/style.ts
128
+ var STYLE = `
129
+ .ta-lips-row { display: inline-flex; align-items: center; gap: 8px; }
130
+ .ta-lips-note { color: var(--ta-secondary); font-size: calc(13px * var(--ta-font-scale)); }
131
+ .ta-lips-button { height: 32px; padding: 0 12px; border-radius: 8px; border: 1px solid var(--ta-border); background: transparent; color: var(--ta-text); font: inherit; font-weight: 500; cursor: pointer; }
132
+ .ta-lips-primary { background: var(--ta-accent); border-color: var(--ta-accent); color: #fff; }
133
+ .ta-lips-ask { margin: 0 0 16px; color: var(--ta-secondary); line-height: 1.6; }
134
+ .ta-lips-actions { display: flex; justify-content: flex-end; gap: 8px; }
135
+ `;
136
+ function injectStyle() {
137
+ const element = document.createElement("style");
138
+ element.dataset.taPackage = "ta-lips";
139
+ element.textContent = STYLE;
140
+ document.head.appendChild(element);
141
+ return () => element.remove();
142
+ }
143
+
144
+ // web-src/index.tsx
145
+ var ASKED = "asked";
146
+ function activate(pi) {
147
+ bind(pi.React);
148
+ if (!pi.registerCallMouth) {
149
+ return () => {
150
+ return;
151
+ };
152
+ }
153
+ const removeStyle = injectStyle();
154
+ pi.registerCallMouth({ open: () => LipsMouth.open(pi) });
155
+ pi.registerSettings({ title: () => LipsWords.of(pi.ui.language).title, icon: pi.ui.icons.Sparkles, group: "ta", rows: [setupRow(pi)] });
156
+ return removeStyle;
157
+ }
158
+
159
+ class LipsMouth {
160
+ pi;
161
+ holdMs = HOLD_MS;
162
+ fps = LIPS_FPS;
163
+ frames = new Map;
164
+ reading = new Set;
165
+ timer;
166
+ alive;
167
+ closed = false;
168
+ started = false;
169
+ openedAt = Date.now();
170
+ constructor(pi) {
171
+ this.pi = pi;
172
+ }
173
+ static async open(pi) {
174
+ if (!pi.files.byUrl) {
175
+ return;
176
+ }
177
+ const status = await LipsMouth.state(pi);
178
+ if (!status?.supported) {
179
+ return;
180
+ }
181
+ if (status.state !== "ready") {
182
+ if (status.state === "none" && !await pi.storage.get(ASKED)) {
183
+ await pi.storage.set(ASKED, true);
184
+ pi.ui.custom?.(({ close }) => /* @__PURE__ */ React.createElement(AskSetup, {
185
+ pi,
186
+ close
187
+ }));
188
+ }
189
+ return;
190
+ }
191
+ const mouth = new LipsMouth(pi);
192
+ pi.callHost("start").then(() => {
193
+ mouth.started = true;
194
+ }, () => mouth.close());
195
+ mouth.keepAlive();
196
+ return mouth;
197
+ }
198
+ keepAlive() {
199
+ this.alive = setInterval(() => void this.pi.callHost("start").catch(() => {
200
+ return;
201
+ }), KEEP_ALIVE_MS);
202
+ }
203
+ static async state(pi, tries = 4) {
204
+ for (let i = 0;; i++) {
205
+ try {
206
+ return await pi.callHost("state");
207
+ } catch {
208
+ if (i + 1 >= tries) {
209
+ return;
210
+ }
211
+ await new Promise((done) => setTimeout(done, 1500));
212
+ }
213
+ }
214
+ }
215
+ sound(say, pcm, rate, slots, first) {
216
+ if (this.closed) {
217
+ return;
218
+ }
219
+ this.reading.add(say);
220
+ this.poll();
221
+ const message = { op: "say", id: String(say), pcm: pcm ? LipsMouth.base64(pcm) : "", rate, fps: this.fps, slots, first, final: !pcm };
222
+ this.pi.callHost("tell", message).catch(() => {
223
+ return;
224
+ });
225
+ }
226
+ at(say, slot) {
227
+ this.pi.callHost("tell", { op: "at", id: String(say), slot }).catch(() => {
228
+ return;
229
+ });
230
+ for (const key of this.frames.keys()) {
231
+ const [id, at] = key.split(":").map(Number);
232
+ if (id !== say || at < slot - 1) {
233
+ this.frames.delete(key);
234
+ }
235
+ }
236
+ }
237
+ readyIn() {
238
+ return this.started ? 0 : Math.max(500, STARTS_MS - (Date.now() - this.openedAt));
239
+ }
240
+ cut(say) {
241
+ this.reading.delete(say);
242
+ this.pi.callHost("tell", { op: "cut", id: String(say) }).catch(() => {
243
+ return;
244
+ });
245
+ }
246
+ frame(say, slot) {
247
+ return this.frames.get(`${say}:${slot}`);
248
+ }
249
+ close() {
250
+ this.closed = true;
251
+ clearInterval(this.timer);
252
+ clearInterval(this.alive);
253
+ for (const say of this.reading) {
254
+ this.cut(say);
255
+ }
256
+ this.frames.clear();
257
+ }
258
+ poll() {
259
+ if (this.timer) {
260
+ return;
261
+ }
262
+ this.timer = setInterval(() => {
263
+ if (!this.reading.size) {
264
+ clearInterval(this.timer);
265
+ this.timer = undefined;
266
+ return;
267
+ }
268
+ for (const say of this.reading) {
269
+ this.pi.callHost("take", String(say)).then((frames) => frames.forEach((frame) => void this.decode(say, frame)), () => {
270
+ return;
271
+ });
272
+ }
273
+ }, POLL_MS);
274
+ }
275
+ async decode(say, frame) {
276
+ const bytes = Uint8Array.from(atob(frame.data), (char) => char.charCodeAt(0));
277
+ const image = await createImageBitmap(new Blob([bytes], { type: "image/webp" }));
278
+ if (!this.closed) {
279
+ this.frames.set(`${say}:${frame.slot}`, { clip: frame.clip, frame: frame.frame, box: frame.box, image });
280
+ }
281
+ }
282
+ static base64(bytes) {
283
+ let text = "";
284
+ for (let i = 0;i < bytes.length; i += 32768) {
285
+ text += String.fromCharCode(...bytes.subarray(i, i + 32768));
286
+ }
287
+ return btoa(text);
288
+ }
289
+ }
290
+ function useStatus(pi) {
291
+ const [status, setStatus] = React.useState();
292
+ React.useEffect(() => {
293
+ let live = true;
294
+ const read = () => pi.callHost("state").then((next) => live && setStatus(next), () => {
295
+ return;
296
+ });
297
+ read();
298
+ const timer = setInterval(read, 1000);
299
+ return () => {
300
+ live = false;
301
+ clearInterval(timer);
302
+ };
303
+ }, [pi]);
304
+ return [status, setStatus];
305
+ }
306
+ function setupRow(pi) {
307
+ return {
308
+ key: "setup",
309
+ label: () => LipsWords.of(pi.ui.language).title,
310
+ description: () => LipsWords.of(pi.ui.language).hint,
311
+ render: () => /* @__PURE__ */ React.createElement(SetupControl, {
312
+ pi
313
+ })
314
+ };
315
+ }
316
+ function SetupControl({ pi }) {
317
+ const words = LipsWords.of(pi.ui.language);
318
+ const [status, setStatus] = useStatus(pi);
319
+ const act = (method) => pi.callHost(method).then(setStatus, (error) => pi.ui.notify(String(error?.message ?? error), "error"));
320
+ if (!status) {
321
+ return null;
322
+ }
323
+ if (!status.supported) {
324
+ return /* @__PURE__ */ React.createElement("span", {
325
+ className: "ta-lips-note"
326
+ }, words.unsupported);
327
+ }
328
+ if (status.state === "setting-up") {
329
+ return /* @__PURE__ */ React.createElement("span", {
330
+ className: "ta-lips-note"
331
+ }, LipsWords.fill(words.getting, { percent: Math.floor(status.progress * 100) }));
332
+ }
333
+ if (status.state === "ready") {
334
+ return /* @__PURE__ */ React.createElement("button", {
335
+ type: "button",
336
+ className: "ta-lips-button",
337
+ onClick: () => act("remove")
338
+ }, words.remove);
339
+ }
340
+ return /* @__PURE__ */ React.createElement("span", {
341
+ className: "ta-lips-row"
342
+ }, status.state === "failed" && /* @__PURE__ */ React.createElement("span", {
343
+ className: "ta-lips-note"
344
+ }, LipsWords.fill(words.failed, { error: status.error ?? "" })), /* @__PURE__ */ React.createElement("button", {
345
+ type: "button",
346
+ className: "ta-lips-button",
347
+ onClick: () => act("setup")
348
+ }, words.get));
349
+ }
350
+ function AskSetup({ pi, close }) {
351
+ const words = LipsWords.of(pi.ui.language);
352
+ const Dialog = pi.ui.Dialog;
353
+ return /* @__PURE__ */ React.createElement(Dialog, {
354
+ title: words.askTitle,
355
+ onClose: close
356
+ }, /* @__PURE__ */ React.createElement("p", {
357
+ className: "ta-lips-ask"
358
+ }, words.ask), /* @__PURE__ */ React.createElement("div", {
359
+ className: "ta-lips-actions"
360
+ }, /* @__PURE__ */ React.createElement("button", {
361
+ type: "button",
362
+ className: "ta-lips-button",
363
+ onClick: close
364
+ }, words.askNo), /* @__PURE__ */ React.createElement("button", {
365
+ type: "button",
366
+ className: "ta-lips-button ta-lips-primary",
367
+ onClick: () => {
368
+ close();
369
+ pi.callHost("setup").then(() => pi.ui.notify(words.started), (error) => pi.ui.notify(String(error?.message ?? error), "error"));
370
+ }
371
+ }, words.askYes)));
372
+ }
373
+ export {
374
+ activate as default,
375
+ LipsMouth
376
+ };