@celljs/ta-lips 4.28.0 → 4.30.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/host/index.mjs +73 -6
- package/package.json +3 -3
- package/python/lips.py +379 -45
- package/web/index.js +73 -14
package/host/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// web-src/host.ts
|
|
2
2
|
import { spawn } from "node:child_process";
|
|
3
|
-
import { existsSync, mkdirSync, rmSync } from "node:fs";
|
|
3
|
+
import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { createInterface } from "node:readline";
|
|
@@ -28,19 +28,25 @@ var REQUIREMENTS = [
|
|
|
28
28
|
// web-src/host.ts
|
|
29
29
|
var KEEP_FRAMES = 240;
|
|
30
30
|
var IDLE_MS = 5 * 60000;
|
|
31
|
+
var HER_ON = "her";
|
|
31
32
|
|
|
32
33
|
class LipsHost {
|
|
33
34
|
root;
|
|
34
35
|
home;
|
|
36
|
+
own;
|
|
35
37
|
setupRun;
|
|
36
38
|
status;
|
|
37
39
|
server;
|
|
38
40
|
serverReady;
|
|
39
41
|
frames = new Map;
|
|
40
42
|
idle;
|
|
41
|
-
|
|
43
|
+
herRun;
|
|
44
|
+
herProgress = 0;
|
|
45
|
+
herError;
|
|
46
|
+
constructor(root, home = join(homedir(), ".ta", "tools", "lips"), own = async () => []) {
|
|
42
47
|
this.root = root;
|
|
43
48
|
this.home = home;
|
|
49
|
+
this.own = own;
|
|
44
50
|
this.status = { state: existsSync(join(home, "ready")) ? "ready" : "none", progress: 0 };
|
|
45
51
|
}
|
|
46
52
|
get script() {
|
|
@@ -54,7 +60,53 @@ class LipsHost {
|
|
|
54
60
|
return join(this.home, "venv", process.platform === "win32" ? "Scripts/python.exe" : "bin/python");
|
|
55
61
|
}
|
|
56
62
|
state() {
|
|
57
|
-
return { ...this.status, supported: LipsHost.supported() };
|
|
63
|
+
return { ...this.status, supported: LipsHost.supported(), her: this.herState(), herProgress: this.herProgress, herError: this.herError };
|
|
64
|
+
}
|
|
65
|
+
herState() {
|
|
66
|
+
return this.herRun ? "getting" : existsSync(join(this.home, HER_ON)) && existsSync(this.herFile) ? "on" : "off";
|
|
67
|
+
}
|
|
68
|
+
get herFile() {
|
|
69
|
+
return join(this.home, "models", "her", "her-v3.pth");
|
|
70
|
+
}
|
|
71
|
+
her(on) {
|
|
72
|
+
if (this.status.state !== "ready") {
|
|
73
|
+
throw new Error("The mouth is not set up.");
|
|
74
|
+
}
|
|
75
|
+
if (!on) {
|
|
76
|
+
rmSync(join(this.home, HER_ON), { force: true });
|
|
77
|
+
this.stopServer();
|
|
78
|
+
} else if (existsSync(this.herFile)) {
|
|
79
|
+
writeFileSync(join(this.home, HER_ON), "");
|
|
80
|
+
this.stopServer();
|
|
81
|
+
} else if (!this.herRun) {
|
|
82
|
+
this.herProgress = 0;
|
|
83
|
+
this.herRun = this.runHer().then(() => {
|
|
84
|
+
writeFileSync(join(this.home, HER_ON), "");
|
|
85
|
+
this.stopServer();
|
|
86
|
+
}, (error) => {
|
|
87
|
+
this.herError = error instanceof Error ? error.message : String(error);
|
|
88
|
+
});
|
|
89
|
+
this.herRun.finally(() => {
|
|
90
|
+
this.herRun = undefined;
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
return this.state();
|
|
94
|
+
}
|
|
95
|
+
runHer() {
|
|
96
|
+
this.herError = undefined;
|
|
97
|
+
return new Promise((resolve, reject) => {
|
|
98
|
+
const child = spawn(this.python, [this.script, "her", "--home", this.home, "--faces", this.faces], { stdio: ["ignore", "pipe", "ignore"] });
|
|
99
|
+
let error = "";
|
|
100
|
+
createInterface({ input: child.stdout }).on("line", (line) => {
|
|
101
|
+
try {
|
|
102
|
+
const message = JSON.parse(line);
|
|
103
|
+
this.herProgress = message.progress ?? this.herProgress;
|
|
104
|
+
error = message.error ?? error;
|
|
105
|
+
} catch {}
|
|
106
|
+
});
|
|
107
|
+
child.on("error", reject);
|
|
108
|
+
child.on("exit", (code) => code === 0 ? resolve() : reject(new Error(error || `her mouth failed (${code})`)));
|
|
109
|
+
});
|
|
58
110
|
}
|
|
59
111
|
setup() {
|
|
60
112
|
if (!LipsHost.supported()) {
|
|
@@ -79,11 +131,22 @@ class LipsHost {
|
|
|
79
131
|
this.status = { state: "none", progress: 0 };
|
|
80
132
|
return this.state();
|
|
81
133
|
}
|
|
134
|
+
get more() {
|
|
135
|
+
return join(this.home, "more.json");
|
|
136
|
+
}
|
|
137
|
+
async listOwn() {
|
|
138
|
+
const clips = await this.own().catch(() => []);
|
|
139
|
+
mkdirSync(this.home, { recursive: true });
|
|
140
|
+
writeFileSync(this.more, JSON.stringify(Array.isArray(clips) ? clips : []));
|
|
141
|
+
}
|
|
82
142
|
async start() {
|
|
83
143
|
if (this.status.state !== "ready") {
|
|
84
144
|
throw new Error("The mouth is not set up.");
|
|
85
145
|
}
|
|
86
146
|
this.touch();
|
|
147
|
+
if (!this.serverReady) {
|
|
148
|
+
await this.listOwn();
|
|
149
|
+
}
|
|
87
150
|
return { fps: await this.ensureServer() };
|
|
88
151
|
}
|
|
89
152
|
tell(message) {
|
|
@@ -124,7 +187,8 @@ class LipsHost {
|
|
|
124
187
|
if (this.serverReady) {
|
|
125
188
|
return this.serverReady;
|
|
126
189
|
}
|
|
127
|
-
const
|
|
190
|
+
const her = this.herState() === "on" ? ["--her"] : [];
|
|
191
|
+
const child = spawn(this.python, [this.script, "serve", "--home", this.home, "--faces", this.faces, "--more", this.more, ...her], {
|
|
128
192
|
stdio: ["pipe", "pipe", "ignore"],
|
|
129
193
|
env: { ...process.env, PYTHONUNBUFFERED: "1", PYTORCH_ENABLE_MPS_FALLBACK: "1" }
|
|
130
194
|
});
|
|
@@ -183,7 +247,9 @@ class LipsHost {
|
|
|
183
247
|
await this.run(uv, ["venv", "--python", PYTHON, join(this.home, "venv")], "python");
|
|
184
248
|
}
|
|
185
249
|
await this.run(uv, ["pip", "install", "--python", this.python, ...REQUIREMENTS], "packages");
|
|
186
|
-
await this.
|
|
250
|
+
await this.listOwn();
|
|
251
|
+
await this.run(this.python, [this.script, "setup", "--home", this.home, "--faces", this.faces, "--more", this.more], "models");
|
|
252
|
+
writeFileSync(join(this.home, HER_ON), "");
|
|
187
253
|
await this.run(process.execPath, ["-e", `require('fs').writeFileSync(${JSON.stringify(join(this.home, "ready"))}, '')`], "done");
|
|
188
254
|
}
|
|
189
255
|
async uv() {
|
|
@@ -244,12 +310,13 @@ async function activate(host) {
|
|
|
244
310
|
if (!root) {
|
|
245
311
|
return {};
|
|
246
312
|
}
|
|
247
|
-
const lips = new LipsHost(root);
|
|
313
|
+
const lips = new LipsHost(root, undefined, async () => await host.callPackageHost("@celljs/ta-moves", "clips"));
|
|
248
314
|
return {
|
|
249
315
|
dispose: () => lips.stop(),
|
|
250
316
|
state: () => lips.state(),
|
|
251
317
|
setup: () => lips.setup(),
|
|
252
318
|
remove: () => lips.remove(),
|
|
319
|
+
her: (on) => lips.her(!!on),
|
|
253
320
|
start: () => lips.start(),
|
|
254
321
|
tell: (message) => lips.tell(message),
|
|
255
322
|
take: (id) => lips.take(String(id)),
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@celljs/ta-lips",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.30.0",
|
|
4
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
5
|
"keywords": [
|
|
6
6
|
"pi-package"
|
|
@@ -29,8 +29,8 @@
|
|
|
29
29
|
"watch": "tsc -b -w --preserveWatchOutput"
|
|
30
30
|
},
|
|
31
31
|
"devDependencies": {
|
|
32
|
-
"@celljs/ta-protocol": "4.
|
|
33
|
-
"@celljs/ta-web": "4.
|
|
32
|
+
"@celljs/ta-protocol": "4.30.0",
|
|
33
|
+
"@celljs/ta-web": "4.30.0",
|
|
34
34
|
"@types/react": "^19.3.0"
|
|
35
35
|
},
|
|
36
36
|
"publishConfig": {
|
package/python/lips.py
CHANGED
|
@@ -4,7 +4,9 @@ half of her face again for each frame of a clip, from the sound of Ta's voice, a
|
|
|
4
4
|
with its edges soft, to lay over the frame it was drawn for.
|
|
5
5
|
|
|
6
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
|
|
7
|
+
python lips.py serve --home <dir> --faces <dir> [--her] answers on stdin and stdout, a JSON object a line;
|
|
8
|
+
--her: with her own mouth (HER), when it is there
|
|
9
|
+
python lips.py her --home <dir> --faces <dir> downloads her own mouth alone (a Ta set up before it)
|
|
8
10
|
|
|
9
11
|
What serve is told:
|
|
10
12
|
{"op": "say", "id": <utterance>, "pcm": <base64 of PCM16 mono>, "rate": <Hz>, "fps": <slots a second>, "slots": [[clip, frame], ...], "first": <slot>, "final": bool}
|
|
@@ -17,8 +19,10 @@ What it says:
|
|
|
17
19
|
"""
|
|
18
20
|
import argparse
|
|
19
21
|
import base64
|
|
22
|
+
import bisect
|
|
20
23
|
import hashlib
|
|
21
24
|
import json
|
|
25
|
+
import math
|
|
22
26
|
import os
|
|
23
27
|
import shutil
|
|
24
28
|
import sys
|
|
@@ -42,10 +46,29 @@ MODELS = [
|
|
|
42
46
|
('camenduru/MuseTalk', 'face-parse-bisent/79999_iter.pth', 'face-parse-bisent/79999_iter.pth'),
|
|
43
47
|
]
|
|
44
48
|
RESNET_URL = 'https://download.pytorch.org/models/resnet18-5c106cde.pth'
|
|
49
|
+
# Her own mouth: the up blocks of MuseTalk's UNet trained on her clips, on Ta's voice (docs/design/ta-call.md 12), laid
|
|
50
|
+
# over the model as it loads. In parts, as the bucket that serves them takes no file over 300 MB in one upload.
|
|
51
|
+
HER = {'url': 'https://download.cellbang.com/ta/lips/her-v3.pth', 'parts': 5, 'size': 1011414445,
|
|
52
|
+
'sha256': '2e4b5d25bc54a023f4b2ca1705fcbea72e47737e1b15bdcd8b3d257d9542312a'}
|
|
45
53
|
# How much of the whole each step of setup is, roughly by the time it takes.
|
|
46
|
-
WEIGHT = {'source': 0.02, 'models': 0.
|
|
54
|
+
WEIGHT = {'source': 0.02, 'models': 0.6, 'her': 0.18, 'prepare': 0.2}
|
|
47
55
|
BATCH = 8
|
|
56
|
+
# How far apart the slots MuseTalk draws (keys) may be: those between are drawn from the two keys around them, so that a
|
|
57
|
+
# computer too slow to draw 24 a second (an M4 Pro draws about 23) still shows a mouth on each frame of a clip.
|
|
58
|
+
MOST_APART = 3
|
|
59
|
+
# How much of each of the two keys beside it a key takes in: MuseTalk draws each frame alone, and they jitter.
|
|
60
|
+
SMOOTH = 0.2
|
|
61
|
+
# What shows this close to the last key drawn, in s, does not wait for the key after it (see Server.near).
|
|
62
|
+
NEAR_S = 0.4
|
|
63
|
+
# The threads that lay the faces drawn into their frames (OpenCV lets go of the GIL as it works).
|
|
64
|
+
PATCHERS = 3
|
|
48
65
|
WEBP_QUALITY = 82
|
|
66
|
+
# What prepare keeps of a clip changed: a cache of before is prepared again.
|
|
67
|
+
PREPARED = 3
|
|
68
|
+
# Of her face at 256 px: lips of fewer pixels are covered (a hand); a mouth wider smiles, as the look of a clip (laugh,
|
|
69
|
+
# happy): MuseTalk would draw a plain mouth over either, and she would look like someone else.
|
|
70
|
+
LIPS_SEEN = 900
|
|
71
|
+
LIPS_SMILE = 116
|
|
49
72
|
lock = threading.Lock()
|
|
50
73
|
|
|
51
74
|
|
|
@@ -68,7 +91,9 @@ def fetch(url, path, progress=None):
|
|
|
68
91
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
69
92
|
part = path + '.part'
|
|
70
93
|
have = os.path.getsize(part) if os.path.exists(part) else 0
|
|
71
|
-
|
|
94
|
+
# A user agent of its own: Cloudflare turns Python's away.
|
|
95
|
+
headers = {'User-Agent': 'Ta-lips', **({'Range': f'bytes={have}-'} if have else {})}
|
|
96
|
+
request = urllib.request.Request(url, headers=headers)
|
|
72
97
|
with urllib.request.urlopen(request, timeout=60) as response:
|
|
73
98
|
if have and response.status != 206:
|
|
74
99
|
have = 0
|
|
@@ -87,9 +112,11 @@ def fetch(url, path, progress=None):
|
|
|
87
112
|
|
|
88
113
|
|
|
89
114
|
class Paths:
|
|
90
|
-
def __init__(self, home, faces):
|
|
115
|
+
def __init__(self, home, faces, more=None):
|
|
91
116
|
self.home = home
|
|
92
117
|
self.faces = faces
|
|
118
|
+
# A JSON list of more clips, [{"clip": name, "path": file}]: the user's own (@celljs/ta-moves).
|
|
119
|
+
self.more = more
|
|
93
120
|
self.source = os.path.join(home, 'MuseTalk')
|
|
94
121
|
self.models = os.path.join(home, 'models')
|
|
95
122
|
self.cache = os.path.join(home, 'cache')
|
|
@@ -129,10 +156,46 @@ def setup(paths):
|
|
|
129
156
|
if not os.path.exists(resnet):
|
|
130
157
|
fetch(RESNET_URL, resnet)
|
|
131
158
|
step['at'] += WEIGHT['models']
|
|
159
|
+
fetch_her(paths, lambda f: report('models', 'her', f))
|
|
160
|
+
step['at'] += WEIGHT['her']
|
|
132
161
|
prepare(paths, lambda f: report('prepare', 'prepare', f))
|
|
133
162
|
emit({'step': 'done', 'progress': 1})
|
|
134
163
|
|
|
135
164
|
|
|
165
|
+
def her_path(paths):
|
|
166
|
+
return paths.model('her', 'her-v3.pth')
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def fetch_her(paths, progress):
|
|
170
|
+
"""Her own mouth, its parts one after another into one file, checked whole before it is kept."""
|
|
171
|
+
target = her_path(paths)
|
|
172
|
+
if os.path.exists(target):
|
|
173
|
+
return
|
|
174
|
+
whole = target + '.whole'
|
|
175
|
+
os.makedirs(os.path.dirname(target), exist_ok=True)
|
|
176
|
+
digest = hashlib.sha256()
|
|
177
|
+
try:
|
|
178
|
+
with open(whole, 'wb') as out:
|
|
179
|
+
for i in range(HER['parts']):
|
|
180
|
+
part = f'{target}.{i}'
|
|
181
|
+
if not os.path.exists(part):
|
|
182
|
+
fetch(f"{HER['url']}.{i}", part, lambda f, i=i: progress((i + f) / HER['parts']))
|
|
183
|
+
with open(part, 'rb') as file:
|
|
184
|
+
data = file.read()
|
|
185
|
+
digest.update(data)
|
|
186
|
+
out.write(data)
|
|
187
|
+
except BaseException:
|
|
188
|
+
os.remove(whole)
|
|
189
|
+
raise
|
|
190
|
+
for i in range(HER['parts']):
|
|
191
|
+
os.remove(f'{target}.{i}')
|
|
192
|
+
if digest.hexdigest() != HER['sha256']:
|
|
193
|
+
os.remove(whole)
|
|
194
|
+
raise RuntimeError('Her mouth did not download whole: try again.')
|
|
195
|
+
os.replace(whole, target)
|
|
196
|
+
progress(1)
|
|
197
|
+
|
|
198
|
+
|
|
136
199
|
def runtime(paths):
|
|
137
200
|
sys.path.insert(0, paths.source)
|
|
138
201
|
os.chdir(paths.source)
|
|
@@ -177,13 +240,18 @@ def prepare(paths, progress):
|
|
|
177
240
|
from musetalk.utils.blending import get_image_prepare_material
|
|
178
241
|
|
|
179
242
|
boxes = json.load(open(os.path.join(paths.faces, 'lips.json')))
|
|
243
|
+
files = {clip: os.path.join(paths.faces, f'{clip}.mp4') for clip in boxes['clips']}
|
|
244
|
+
for extra in more_clips(paths):
|
|
245
|
+
files[extra['clip']] = extra['path']
|
|
180
246
|
os.makedirs(paths.cache, exist_ok=True)
|
|
181
247
|
index_path = os.path.join(paths.cache, 'index.json')
|
|
182
248
|
index = json.load(open(index_path)) if os.path.exists(index_path) else {}
|
|
183
249
|
todo = []
|
|
184
|
-
for clip in
|
|
185
|
-
digest = clip_hash(
|
|
186
|
-
if index.get(clip)
|
|
250
|
+
for clip, path in files.items():
|
|
251
|
+
digest = f"{clip_hash(path)}:{PREPARED}"
|
|
252
|
+
if index.get(clip) == f'{digest}:none':
|
|
253
|
+
continue
|
|
254
|
+
if index.get(clip) != digest or not os.path.exists(cache_file(paths, clip)):
|
|
187
255
|
todo.append((clip, digest))
|
|
188
256
|
if not todo:
|
|
189
257
|
return
|
|
@@ -194,19 +262,26 @@ def prepare(paths, progress):
|
|
|
194
262
|
from musetalk.utils import face_parsing
|
|
195
263
|
parsing = face_parsing_at(face_parsing, paths)
|
|
196
264
|
for n, (clip, digest) in enumerate(todo):
|
|
197
|
-
capture = cv2.VideoCapture(
|
|
265
|
+
capture = cv2.VideoCapture(files[clip])
|
|
198
266
|
frames = []
|
|
199
267
|
while True:
|
|
200
268
|
ok, frame = capture.read()
|
|
201
269
|
if not ok:
|
|
202
270
|
break
|
|
203
271
|
frames.append(frame)
|
|
204
|
-
|
|
272
|
+
# The user's clips come without where her face is: found here (OpenCV), as Ta's own were (MediaPipe).
|
|
273
|
+
known = boxes['clips'].get(clip) or detect_boxes(cv2, frames)
|
|
274
|
+
if not known:
|
|
275
|
+
index[clip] = f'{digest}:none'
|
|
276
|
+
json.dump(index, open(index_path, 'w'))
|
|
277
|
+
continue
|
|
278
|
+
latents, crops, masks, parts, faces, lips = [], [], [], [], [], []
|
|
205
279
|
for k, frame in enumerate(frames):
|
|
206
|
-
x1, y1, x2, y2 =
|
|
280
|
+
x1, y1, x2, y2 = known[min(k, len(known) - 1)]
|
|
207
281
|
y2 = min(y2 + 10, frame.shape[0])
|
|
208
282
|
face = cv2.resize(frame[y1:y2, x1:x2], (256, 256), interpolation=cv2.INTER_LANCZOS4)
|
|
209
283
|
latents.append(vae.get_latents_for_unet(face).cpu())
|
|
284
|
+
lips.append(lips_of(cv2, np, torch, parsing, face))
|
|
210
285
|
mask, crop = get_image_prepare_material(frame, [x1, y1, x2, y2], fp=parsing, mode='jaw')
|
|
211
286
|
xs, ys, xe, ye = crop
|
|
212
287
|
part = np.zeros((ye - ys, xe - xs, 3), np.uint8)
|
|
@@ -218,11 +293,71 @@ def prepare(paths, progress):
|
|
|
218
293
|
parts.append(part)
|
|
219
294
|
faces.append((x1, y1, x2, y2))
|
|
220
295
|
progress((n + (k + 1) / len(frames)) / len(todo))
|
|
221
|
-
torch.save({'latents': torch.cat(latents), 'crops': crops, 'masks': masks, 'parts': parts, 'faces': faces},
|
|
296
|
+
torch.save({'latents': torch.cat(latents), 'crops': crops, 'masks': masks, 'parts': parts, 'faces': faces, 'lips': lips}, cache_file(paths, clip))
|
|
222
297
|
index[clip] = digest
|
|
223
298
|
json.dump(index, open(index_path, 'w'))
|
|
224
299
|
|
|
225
300
|
|
|
301
|
+
def more_clips(paths):
|
|
302
|
+
"""The user's own clips the host listed (@celljs/ta-moves), those whose files are there."""
|
|
303
|
+
if not paths.more or not os.path.exists(paths.more):
|
|
304
|
+
return []
|
|
305
|
+
try:
|
|
306
|
+
listed = json.load(open(paths.more))
|
|
307
|
+
except ValueError:
|
|
308
|
+
return []
|
|
309
|
+
return [one for one in listed if isinstance(one, dict) and isinstance(one.get('clip'), str) and os.path.exists(str(one.get('path')))]
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def person(clip):
|
|
313
|
+
"""The person of a clip: the directory of its file in faces/ ('blonde/talk-1': 'blonde'), '' for the first."""
|
|
314
|
+
return clip.rsplit('/', 1)[0] if '/' in clip else ''
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def cache_file(paths, clip):
|
|
318
|
+
"""Where what was prepared of a clip is kept: its name made safe for a file (the user's are own:<name>)."""
|
|
319
|
+
return os.path.join(paths.cache, clip.replace(':', '_').replace('/', '_') + '.pt')
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def detect_boxes(cv2, frames):
|
|
323
|
+
"""
|
|
324
|
+
Where the face is in each frame of a clip, as lips.json has it (x1, y1, x2, y2): OpenCV's frontal face finder,
|
|
325
|
+
followed from frame to frame (the highest face of the first frame that has one, as what it takes for one below is
|
|
326
|
+
her chest; then in each frame the face near the one before, as large: one elsewhere, a shelf or her hands, is left
|
|
327
|
+
out). Frames without
|
|
328
|
+
one take the nearest that has (her mouth is drawn there only where its lips are seen, prepare), smoothed over five
|
|
329
|
+
frames; the box made as MediaPipe's were (a little narrower than the face found). None when no frame has a face.
|
|
330
|
+
"""
|
|
331
|
+
finder = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
|
|
332
|
+
found = []
|
|
333
|
+
for frame in frames:
|
|
334
|
+
grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
|
|
335
|
+
size = max(48, frame.shape[1] // 6)
|
|
336
|
+
found.append([tuple(int(v) for v in face) for face in finder.detectMultiScale(grey, 1.1, 5, minSize=(size, size))])
|
|
337
|
+
first = next((faces for faces in found if faces), None)
|
|
338
|
+
if not first:
|
|
339
|
+
return None
|
|
340
|
+
last = min(first, key=lambda face: face[1])
|
|
341
|
+
kept = []
|
|
342
|
+
for faces in found:
|
|
343
|
+
near = [face for face in faces if abs(face[0] + face[2] / 2 - last[0] - last[2] / 2) < 0.5 * last[2]
|
|
344
|
+
and abs(face[1] + face[3] / 2 - last[1] - last[3] / 2) < 0.5 * last[3] and 0.7 < face[2] / last[2] < 1.4]
|
|
345
|
+
pick = min(near, key=lambda face: abs(face[0] - last[0]) + abs(face[1] - last[1])) if near else None
|
|
346
|
+
if pick:
|
|
347
|
+
last = pick
|
|
348
|
+
kept.append(pick)
|
|
349
|
+
seen = [k for k, face in enumerate(kept) if face is not None]
|
|
350
|
+
boxes = []
|
|
351
|
+
for k in range(len(kept)):
|
|
352
|
+
x, y, w, h = kept[min(seen, key=lambda s: abs(s - k))]
|
|
353
|
+
boxes.append([x + 0.09 * w, y + 0.02 * h, x + 0.91 * w, y + h])
|
|
354
|
+
smooth = []
|
|
355
|
+
for k in range(len(boxes)):
|
|
356
|
+
near = boxes[max(0, k - 2):k + 3]
|
|
357
|
+
smooth.append([int(sorted(b[i] for b in near)[len(near) // 2]) for i in range(4)])
|
|
358
|
+
return smooth
|
|
359
|
+
|
|
360
|
+
|
|
226
361
|
def face_parsing_at(module, paths):
|
|
227
362
|
"""MuseTalk's FaceParsing, its weights read from the models of Ta rather than its own directory."""
|
|
228
363
|
original = module.FaceParsing.model_init
|
|
@@ -240,15 +375,25 @@ class Utterance:
|
|
|
240
375
|
self.audio = []
|
|
241
376
|
self.length = 0
|
|
242
377
|
self.slots = []
|
|
378
|
+
# The first slot still wanted: those before it showed already.
|
|
243
379
|
self.next = 0
|
|
244
380
|
self.final = False
|
|
245
381
|
self.fps = 24
|
|
246
382
|
self.features = None
|
|
247
383
|
self.featured = -1
|
|
384
|
+
# MuseTalk draws the slots `apart` apart (its keys), those between are drawn from the two around them: the next
|
|
385
|
+
# key to draw, the latents drawn of the keys, the first slot not sent yet, and when it fell behind last.
|
|
386
|
+
self.apart = 1
|
|
387
|
+
self.key = 0
|
|
388
|
+
self.keys = {}
|
|
389
|
+
self.sent = 0
|
|
390
|
+
self.slowed = 0.0
|
|
391
|
+
# The slot that shows now, as the page last said.
|
|
392
|
+
self.shown = -1
|
|
248
393
|
|
|
249
394
|
|
|
250
395
|
class Server:
|
|
251
|
-
def __init__(self, paths):
|
|
396
|
+
def __init__(self, paths, her=False):
|
|
252
397
|
self.paths = paths
|
|
253
398
|
torch, device = runtime(paths)
|
|
254
399
|
self.torch, self.device = torch, device
|
|
@@ -261,7 +406,16 @@ class Server:
|
|
|
261
406
|
self.dtype = dtype
|
|
262
407
|
from musetalk.models.unet import PositionalEncoding, UNet
|
|
263
408
|
unet = UNet(unet_config=paths.model('musetalkV15', 'musetalk.json'), model_path=unet_path(paths, torch), device=device)
|
|
409
|
+
# Her own mouth is of the first person alone (her clips at the top of faces/): the up blocks of each kept on the
|
|
410
|
+
# CPU, swapped in as a reading of the other person begins (PERSON), and back.
|
|
411
|
+
self.mine = None
|
|
412
|
+
if her and os.path.exists(her_path(paths)):
|
|
413
|
+
mine = torch.load(her_path(paths), map_location='cpu', weights_only=True)
|
|
414
|
+
own = unet.model.state_dict()
|
|
415
|
+
self.mine = {'her': {key: value.to(dtype) for key, value in mine.items()}, 'base': {key: own[key].detach().to('cpu', dtype) for key in mine if key in own}}
|
|
264
416
|
self.unet = unet.model.to(device, dtype=dtype).eval()
|
|
417
|
+
self.wearing = None
|
|
418
|
+
self.wear('her' if self.mine else None)
|
|
265
419
|
self.pe = PositionalEncoding(d_model=384).to(device, dtype=dtype)
|
|
266
420
|
self.tiny = AutoencoderTiny.from_pretrained(paths.model('taesd')).to(device, dtype=dtype).eval()
|
|
267
421
|
self.audio = AudioProcessor(feature_extractor_path=paths.model('whisper'))
|
|
@@ -271,7 +425,8 @@ class Server:
|
|
|
271
425
|
prepare(paths, lambda done: None)
|
|
272
426
|
self.clips = {}
|
|
273
427
|
for name in json.load(open(os.path.join(paths.cache, 'index.json'))):
|
|
274
|
-
|
|
428
|
+
if os.path.exists(cache_file(paths, name)):
|
|
429
|
+
self.clips[name] = torch.load(cache_file(paths, name), weights_only=False)
|
|
275
430
|
self.fps = json.load(open(os.path.join(paths.faces, 'lips.json'))).get('fps', 24)
|
|
276
431
|
self.now = None
|
|
277
432
|
# Utterances heard from their middle: their sound and slots would not line up.
|
|
@@ -280,18 +435,33 @@ class Server:
|
|
|
280
435
|
import queue
|
|
281
436
|
self.made = queue.Queue()
|
|
282
437
|
self.speed = self.warm()
|
|
438
|
+
# Keys further apart for the readings after one fell behind (the computer is busy), back by one a reading in time.
|
|
439
|
+
self.slower = 0
|
|
440
|
+
# About how long a batch takes to draw and send, in s.
|
|
441
|
+
self.took = BATCH / max(1.0, self.speed)
|
|
442
|
+
|
|
443
|
+
def wear(self, which):
|
|
444
|
+
"""The mouth the UNet draws: her own ('her'), MuseTalk's ('base'), or as it is (None)."""
|
|
445
|
+
if not getattr(self, 'mine', None) or which is None or which == self.wearing:
|
|
446
|
+
return
|
|
447
|
+
self.unet.load_state_dict(self.mine[which], strict=False)
|
|
448
|
+
self.wearing = which
|
|
449
|
+
|
|
450
|
+
def spacing(self, fps):
|
|
451
|
+
"""How far apart the keys of a reading are, for this computer to draw them in time with a fourth to spare."""
|
|
452
|
+
return max(1, min(MOST_APART, math.ceil(fps * 1.25 / max(1.0, self.speed)) + self.slower))
|
|
283
453
|
|
|
284
454
|
def warm(self):
|
|
285
|
-
"""Runs the models once, as the first runs are slow, and measures how many
|
|
455
|
+
"""Runs the models once, as the first runs are slow, and measures how many keys a second they draw."""
|
|
286
456
|
silence = self.np.zeros(32000, self.np.float32)
|
|
287
457
|
u = Utterance('warm')
|
|
288
458
|
u.audio, u.length, u.final, u.fps = [silence], len(silence), True, self.fps
|
|
289
459
|
u.slots = [[next(iter(self.clips)), k] for k in range(BATCH * 2)]
|
|
290
|
-
self.
|
|
460
|
+
self.decode(self.stack(self.infer(u, list(range(BATCH)))))
|
|
291
461
|
if self.device.type == 'mps':
|
|
292
462
|
self.torch.mps.synchronize()
|
|
293
463
|
began = time.time()
|
|
294
|
-
self.
|
|
464
|
+
self.decode(self.stack(self.infer(u, list(range(BATCH, BATCH * 2)))))
|
|
295
465
|
if self.device.type == 'mps':
|
|
296
466
|
self.torch.mps.synchronize()
|
|
297
467
|
return BATCH / max(1e-3, time.time() - began)
|
|
@@ -307,6 +477,10 @@ class Server:
|
|
|
307
477
|
self.skipped.add(id)
|
|
308
478
|
return
|
|
309
479
|
u.fps = int(message.get('fps') or self.fps)
|
|
480
|
+
u.apart = self.spacing(u.fps)
|
|
481
|
+
first = (message.get('slots') or [[None]])[0][0]
|
|
482
|
+
if first:
|
|
483
|
+
self.wear('her' if person(first) == '' else 'base')
|
|
310
484
|
self.now = u
|
|
311
485
|
pcm = self.np.frombuffer(base64.b64decode(message.get('pcm') or ''), self.np.int16).astype(self.np.float32) / 32768
|
|
312
486
|
rate = int(message.get('rate') or 16000)
|
|
@@ -318,8 +492,21 @@ class Server:
|
|
|
318
492
|
u.slots.extend(message.get('slots') or [])
|
|
319
493
|
u.final = u.final or bool(message.get('final'))
|
|
320
494
|
elif op == 'at' and self.now and self.now.id == id:
|
|
495
|
+
u = self.now
|
|
321
496
|
# What shows now is late already: the next drawn is a little after it.
|
|
322
|
-
|
|
497
|
+
slot = int(message.get('slot', 0))
|
|
498
|
+
u.shown = slot
|
|
499
|
+
wanted = slot + 2
|
|
500
|
+
if wanted > max(u.sent, u.next) and self.ready(u) >= wanted + u.fps * NEAR_S:
|
|
501
|
+
# Behind, its sound there but not drawn (not the voice that stopped short): what is drawn next is what
|
|
502
|
+
# shows once a batch is drawn (one due before then is never seen), and the keys of this reading and of
|
|
503
|
+
# the next go further apart.
|
|
504
|
+
wanted = slot + 2 + math.ceil(self.took * u.fps)
|
|
505
|
+
if u.apart < MOST_APART and time.time() - u.slowed > 1:
|
|
506
|
+
u.apart += 1
|
|
507
|
+
u.slowed = time.time()
|
|
508
|
+
self.slower = min(MOST_APART, self.slower + 1)
|
|
509
|
+
u.next = max(u.next, wanted)
|
|
323
510
|
elif op == 'cut' and self.now and self.now.id == id:
|
|
324
511
|
self.now = None
|
|
325
512
|
self.wake.set()
|
|
@@ -344,34 +531,120 @@ class Server:
|
|
|
344
531
|
u.featured = u.length
|
|
345
532
|
return u.features
|
|
346
533
|
|
|
347
|
-
def
|
|
348
|
-
|
|
349
|
-
|
|
534
|
+
def infer(self, u, keys):
|
|
535
|
+
"""The latents MuseTalk draws for these slots of u, each from its frame of a clip and the sound at it."""
|
|
536
|
+
torch = self.torch
|
|
350
537
|
chunks = self.features(u)
|
|
351
538
|
# Of the clips it prepared: one it has not (a Ta with more clips, not set up again) shows as it is.
|
|
352
|
-
rows = [
|
|
539
|
+
rows = [s for s in keys if s < len(chunks) and u.slots[s][0] in self.clips]
|
|
353
540
|
if not rows:
|
|
354
|
-
return
|
|
355
|
-
audio = torch.stack([chunks[
|
|
541
|
+
return {}
|
|
542
|
+
audio = torch.stack([chunks[s] for s in rows]).to(self.device)
|
|
356
543
|
latents = []
|
|
357
|
-
for
|
|
358
|
-
own = self.clips[slots[
|
|
359
|
-
latents.append(own[slots[
|
|
544
|
+
for s in rows:
|
|
545
|
+
own = self.clips[u.slots[s][0]]['latents']
|
|
546
|
+
latents.append(own[u.slots[s][1] % len(own)][None])
|
|
360
547
|
latents = torch.cat(latents).to(self.device, dtype=self.dtype)
|
|
361
548
|
with torch.no_grad():
|
|
362
549
|
predicted = self.unet(latents, self.timesteps, encoder_hidden_states=self.pe(audio)).sample
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
550
|
+
return {s: predicted[n] for n, s in enumerate(rows)}
|
|
551
|
+
|
|
552
|
+
def stack(self, latents):
|
|
553
|
+
return self.torch.stack(list(latents.values()))
|
|
554
|
+
|
|
555
|
+
def decode(self, latents):
|
|
556
|
+
"""The faces (256 px, BGR) of latents."""
|
|
557
|
+
np = self.np
|
|
558
|
+
with self.torch.no_grad():
|
|
559
|
+
images = self.tiny.decode(latents).sample
|
|
560
|
+
return ((images.float().clamp(-1, 1) + 1) * 127.5).permute(0, 2, 3, 1).cpu().numpy()[..., ::-1].astype(np.uint8)
|
|
561
|
+
|
|
562
|
+
def end(self, u):
|
|
563
|
+
"""The slots of u that can be drawn: all, but those past its sound once it is all there."""
|
|
564
|
+
return min(len(u.slots), len(self.features(u))) if u.final else len(u.slots)
|
|
565
|
+
|
|
566
|
+
def near(self, u):
|
|
567
|
+
"""
|
|
568
|
+
What shows is close to the last key drawn (the voice stopped short, or the drawing fell behind): the last key
|
|
569
|
+
and the last slot whose sound is there go out without waiting for the key after them.
|
|
570
|
+
"""
|
|
571
|
+
return u.shown >= 0 and max(u.keys, default=u.sent) - u.shown <= u.fps * NEAR_S
|
|
572
|
+
|
|
573
|
+
def next_keys(self, u, near=False):
|
|
574
|
+
"""The keys of u to draw next, as many as a batch, of the slots whose sound is there."""
|
|
575
|
+
end = self.end(u)
|
|
576
|
+
limit = min(self.ready(u), end)
|
|
577
|
+
key = max(u.key, u.next)
|
|
578
|
+
keys = []
|
|
579
|
+
while key < limit and len(keys) < BATCH:
|
|
580
|
+
keys.append(key)
|
|
581
|
+
key += u.apart
|
|
582
|
+
# Its last slot is a key too, for the slots after the last key to be drawn towards it.
|
|
583
|
+
last = end - 1
|
|
584
|
+
if u.final and limit == end and key > last >= u.next and len(keys) < BATCH and last not in u.keys and (keys or [-1])[-1] < last:
|
|
585
|
+
keys.append(last)
|
|
586
|
+
elif near and not u.final and keys[-1:] != [limit - 1] and limit - 1 >= max(u.next, max(u.keys, default=-1) + 1) and len(keys) < BATCH:
|
|
587
|
+
keys.append(limit - 1)
|
|
588
|
+
return keys
|
|
589
|
+
|
|
590
|
+
def smoothed(self, u, drawn, i):
|
|
591
|
+
"""The latent of the key drawn[i], with a little of the keys beside it: each drawn alone, they jitter."""
|
|
592
|
+
k = drawn[i]
|
|
593
|
+
|
|
594
|
+
def beside(j):
|
|
595
|
+
return u.keys[drawn[j]] if 0 <= j < len(drawn) and abs(drawn[j] - k) <= MOST_APART else u.keys[k]
|
|
596
|
+
|
|
597
|
+
return u.keys[k] * (1 - 2 * SMOOTH) + (beside(i - 1) + beside(i + 1)) * SMOOTH
|
|
598
|
+
|
|
599
|
+
def between(self, u, drawn, s):
|
|
600
|
+
"""The latent of slot s: of its key, or of the two keys around it, as far from each as it is."""
|
|
601
|
+
if u.slots[s][0] not in self.clips:
|
|
602
|
+
return None
|
|
603
|
+
i = bisect.bisect_left(drawn, s)
|
|
604
|
+
if i < len(drawn) and drawn[i] == s:
|
|
605
|
+
return self.smoothed(u, drawn, i)
|
|
606
|
+
if i == 0 or i == len(drawn) or drawn[i] - drawn[i - 1] > MOST_APART:
|
|
607
|
+
return None
|
|
608
|
+
a, b = drawn[i - 1], drawn[i]
|
|
609
|
+
t = (s - a) / (b - a)
|
|
610
|
+
return self.smoothed(u, drawn, i - 1) * (1 - t) + self.smoothed(u, drawn, i) * t
|
|
611
|
+
|
|
612
|
+
def send(self, u, near=False):
|
|
613
|
+
"""
|
|
614
|
+
Decodes the slots of u up to its last key (all of them once its last slot is drawn) and gives them to finish:
|
|
615
|
+
the last key waits for the one after it, to be smoothed with it and the slots between to be drawn towards it.
|
|
616
|
+
"""
|
|
617
|
+
drawn = sorted(u.keys)
|
|
618
|
+
if not drawn:
|
|
619
|
+
return False
|
|
620
|
+
start = max(u.sent, u.next)
|
|
621
|
+
end = self.end(u)
|
|
622
|
+
upto = end if u.final and drawn[-1] == end - 1 else min(drawn[-1] + (1 if near else 0), end)
|
|
623
|
+
if upto <= start:
|
|
624
|
+
return False
|
|
625
|
+
rows, latents = [], []
|
|
626
|
+
for s in range(start, upto):
|
|
627
|
+
z = self.between(u, drawn, s)
|
|
628
|
+
if z is not None:
|
|
629
|
+
rows.append(s)
|
|
630
|
+
latents.append(z)
|
|
631
|
+
u.sent = upto
|
|
632
|
+
for n in range(0, len(rows), BATCH * 2):
|
|
633
|
+
images = self.decode(self.torch.stack(latents[n:n + BATCH * 2]))
|
|
634
|
+
self.made.put((u.id, [(s, u.slots[s][0], u.slots[s][1], image) for s, image in zip(rows[n:n + BATCH * 2], images)]))
|
|
635
|
+
for k in drawn[:-2]:
|
|
636
|
+
del u.keys[k]
|
|
637
|
+
return True
|
|
367
638
|
|
|
368
639
|
def finish(self):
|
|
369
640
|
"""Lays what the model drew into its frames and sends them, beside the model drawing the next ones."""
|
|
370
641
|
import cv2
|
|
642
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
371
643
|
np = self.np
|
|
644
|
+
pool = ThreadPoolExecutor(PATCHERS)
|
|
372
645
|
while True:
|
|
373
646
|
id, rows = self.made.get()
|
|
374
|
-
out =
|
|
647
|
+
out = list(pool.map(lambda row: self.patch(cv2, np, *row), rows))
|
|
375
648
|
emit({'id': id, 'frames': [f for f in out if f]})
|
|
376
649
|
|
|
377
650
|
def patch(self, cv2, np, slot, clip, frame, image):
|
|
@@ -383,6 +656,10 @@ class Server:
|
|
|
383
656
|
xs, ys, xe, ye = data['crops'][k]
|
|
384
657
|
part = data['parts'][k].copy()
|
|
385
658
|
original = data['parts'][k]
|
|
659
|
+
if 'lips' in data:
|
|
660
|
+
if not data['lips'][k]:
|
|
661
|
+
return None
|
|
662
|
+
image = lip_colour(cv2, np, image, data['lips'][k])
|
|
386
663
|
face = cv2.resize(image, (x2 - x1, y2 - y1), interpolation=cv2.INTER_LINEAR)
|
|
387
664
|
part[y1 - ys:y2 - ys, x1 - xs:x2 - xs] = face
|
|
388
665
|
part = detail(cv2, np, part, original)
|
|
@@ -399,6 +676,19 @@ class Server:
|
|
|
399
676
|
return None
|
|
400
677
|
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
678
|
|
|
679
|
+
def step(self, u):
|
|
680
|
+
"""Draws the next keys of u and sends what it can: whether there was any to draw or send."""
|
|
681
|
+
began = time.time()
|
|
682
|
+
near = self.near(u)
|
|
683
|
+
keys = self.next_keys(u, near)
|
|
684
|
+
if keys:
|
|
685
|
+
u.keys.update(self.infer(u, keys))
|
|
686
|
+
u.key = max(keys) + u.apart
|
|
687
|
+
sent = self.send(u, near)
|
|
688
|
+
if keys and sent:
|
|
689
|
+
self.took = self.took * 0.7 + (time.time() - began) * 0.3
|
|
690
|
+
return bool(keys) or sent
|
|
691
|
+
|
|
402
692
|
def run(self):
|
|
403
693
|
threading.Thread(target=self.finish, daemon=True).start()
|
|
404
694
|
emit({'ready': True, 'fps': round(self.speed, 1)})
|
|
@@ -408,17 +698,54 @@ class Server:
|
|
|
408
698
|
self.wake.wait(0.5)
|
|
409
699
|
self.wake.clear()
|
|
410
700
|
continue
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
701
|
+
if not self.step(u):
|
|
702
|
+
if u.final and max(u.sent, u.next) >= self.end(u) and self.now is u:
|
|
703
|
+
self.now = None
|
|
704
|
+
if not u.slowed:
|
|
705
|
+
self.slower = max(0, self.slower - 1)
|
|
415
706
|
self.wake.wait(0.05)
|
|
416
707
|
self.wake.clear()
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
708
|
+
|
|
709
|
+
|
|
710
|
+
def lips_of(cv2, np, torch, parsing, face):
|
|
711
|
+
"""
|
|
712
|
+
Of her face in a frame (256 px, as MuseTalk draws it): where her lips are and around them, her skin, and the colour
|
|
713
|
+
of her lips (mean and spread in Lab), for lip_colour; None when no mouth is to be drawn on that frame (her lips
|
|
714
|
+
covered, or a wide smile of hers).
|
|
715
|
+
"""
|
|
716
|
+
from PIL import Image
|
|
717
|
+
with torch.no_grad():
|
|
718
|
+
image = parsing.preprocess(Image.fromarray(face[..., ::-1]).resize((512, 512), Image.BILINEAR)).unsqueeze(0)
|
|
719
|
+
labels = parsing.net(image)[0].squeeze(0).argmax(0).cpu().numpy().astype(np.uint8)
|
|
720
|
+
labels = cv2.resize(labels, (256, 256), interpolation=cv2.INTER_NEAREST)
|
|
721
|
+
lips = np.isin(labels, [12, 13])
|
|
722
|
+
xs = np.nonzero(np.isin(labels, [11, 12, 13]))[1]
|
|
723
|
+
if lips.sum() < LIPS_SEEN or xs.max() - xs.min() > LIPS_SMILE:
|
|
724
|
+
return None
|
|
725
|
+
near = cv2.dilate(lips.astype(np.uint8), np.ones((25, 25), np.uint8)) > 0
|
|
726
|
+
lab = cv2.cvtColor(face, cv2.COLOR_BGR2LAB).astype(np.float32)[lips]
|
|
727
|
+
return {'near': np.packbits(near), 'skin': np.packbits((labels == 1) & ~near), 'mean': lab.mean(0), 'spread': lab.std(0) + 1e-3}
|
|
728
|
+
|
|
729
|
+
|
|
730
|
+
def lip_colour(cv2, np, made, lips):
|
|
731
|
+
"""
|
|
732
|
+
The lips MuseTalk drew, in the colour of hers in that frame: it draws them redder and plainer than she has them, and
|
|
733
|
+
they made her look like someone else. Its lips are where it drew redder than her skin around them.
|
|
734
|
+
"""
|
|
735
|
+
if not lips:
|
|
736
|
+
return made
|
|
737
|
+
near = np.unpackbits(lips['near'])[:256 * 256].reshape(256, 256).astype(bool)
|
|
738
|
+
skin = np.unpackbits(lips['skin'])[:256 * 256].reshape(256, 256).astype(bool)
|
|
739
|
+
lab = cv2.cvtColor(made, cv2.COLOR_BGR2LAB).astype(np.float32)
|
|
740
|
+
skin_a = np.median(lab[..., 1][skin]) if skin.any() else np.median(lab[..., 1])
|
|
741
|
+
redness = np.clip((lab[..., 1] - skin_a - 4) / 10, 0, 1) * near
|
|
742
|
+
drawn = redness > 0.5
|
|
743
|
+
if drawn.sum() < 20:
|
|
744
|
+
return made
|
|
745
|
+
weight = cv2.GaussianBlur(redness.astype(np.float32), (0, 0), 1.5)[..., None]
|
|
746
|
+
mean, spread = lab[drawn].mean(0), lab[drawn].std(0) + 1e-3
|
|
747
|
+
to = (lab - mean) * np.minimum(1.3, lips['spread'] / spread) + lips['mean']
|
|
748
|
+
return cv2.cvtColor(np.clip(lab * (1 - weight) + to * weight, 0, 255).astype(np.uint8), cv2.COLOR_LAB2BGR)
|
|
422
749
|
|
|
423
750
|
|
|
424
751
|
def detail(cv2, np, made, original, sigma=5.0, sharp=0.6):
|
|
@@ -450,8 +777,8 @@ def tone(cv2, np, made, original, sigma):
|
|
|
450
777
|
return made + local
|
|
451
778
|
|
|
452
779
|
|
|
453
|
-
def serve(paths):
|
|
454
|
-
server = Server(paths)
|
|
780
|
+
def serve(paths, her=False):
|
|
781
|
+
server = Server(paths, her)
|
|
455
782
|
|
|
456
783
|
def read():
|
|
457
784
|
for line in sys.stdin:
|
|
@@ -470,13 +797,20 @@ def serve(paths):
|
|
|
470
797
|
if __name__ == '__main__':
|
|
471
798
|
os.environ.setdefault('TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD', '1')
|
|
472
799
|
parser = argparse.ArgumentParser()
|
|
473
|
-
parser.add_argument('command', choices=['setup', 'serve'])
|
|
800
|
+
parser.add_argument('command', choices=['setup', 'serve', 'her'])
|
|
474
801
|
parser.add_argument('--home', required=True)
|
|
475
802
|
parser.add_argument('--faces', required=True)
|
|
803
|
+
parser.add_argument('--more')
|
|
804
|
+
parser.add_argument('--her', action='store_true', help='serve with her own mouth')
|
|
476
805
|
args = parser.parse_args()
|
|
477
|
-
paths = Paths(os.path.abspath(args.home), os.path.abspath(args.faces))
|
|
806
|
+
paths = Paths(os.path.abspath(args.home), os.path.abspath(args.faces), args.more and os.path.abspath(args.more))
|
|
478
807
|
try:
|
|
479
|
-
|
|
808
|
+
if args.command == 'setup':
|
|
809
|
+
setup(paths)
|
|
810
|
+
elif args.command == 'her':
|
|
811
|
+
fetch_her(paths, lambda f: emit({'step': 'her', 'progress': round(f, 4)}))
|
|
812
|
+
else:
|
|
813
|
+
serve(paths, args.her)
|
|
480
814
|
except Exception as error:
|
|
481
815
|
emit({'error': f'{type(error).__name__}: {error}'})
|
|
482
816
|
sys.exit(1)
|
package/web/index.js
CHANGED
|
@@ -40,7 +40,8 @@ var TaLanguageUtil;
|
|
|
40
40
|
// web-src/i18n.ts
|
|
41
41
|
var EN = {
|
|
42
42
|
title: "Lifelike mouth in video calls",
|
|
43
|
-
|
|
43
|
+
section: "Mouth",
|
|
44
|
+
hint: "Draws her mouth again on this computer for each thing Ta says, so that her lips match the words. It downloads about 6 GB once.",
|
|
44
45
|
get: "Download",
|
|
45
46
|
getting: "Downloading {percent}%",
|
|
46
47
|
ready: "On",
|
|
@@ -48,14 +49,18 @@ var EN = {
|
|
|
48
49
|
failed: "Could not set it up: {error}",
|
|
49
50
|
unsupported: "Needs a Mac with Apple silicon or a computer with an NVIDIA GPU.",
|
|
50
51
|
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
|
|
52
|
+
ask: "Ta can draw her mouth again on this computer as she speaks, so that her lips match what she says. It downloads about 6 GB once, then works offline. This call goes on as it is meanwhile.",
|
|
52
53
|
askYes: "Download",
|
|
53
54
|
askNo: "Not now",
|
|
54
|
-
started: "Downloading in the background; the next video call will use it."
|
|
55
|
+
started: "Downloading in the background; the next video call will use it.",
|
|
56
|
+
herTitle: "Her own mouth",
|
|
57
|
+
herHint: "A mouth trained on her own videos and on Ta's voice: it looks like her and follows the words better. Off draws the general one. About 1 GB more, downloaded once.",
|
|
58
|
+
herLater: "After the download above"
|
|
55
59
|
};
|
|
56
60
|
var ZH = {
|
|
57
61
|
title: "视频通话口型更真",
|
|
58
|
-
|
|
62
|
+
section: "口型",
|
|
63
|
+
hint: "在这台电脑上按 Ta 说的每句话重画她的嘴,让嘴型对上字和声音。第一次需要下载约 6 GB。",
|
|
59
64
|
get: "下载",
|
|
60
65
|
getting: "正在下载 {percent}%",
|
|
61
66
|
ready: "已开启",
|
|
@@ -63,14 +68,18 @@ var ZH = {
|
|
|
63
68
|
failed: "没装好:{error}",
|
|
64
69
|
unsupported: "需要 Apple 芯片的 Mac,或带 NVIDIA 显卡的电脑。",
|
|
65
70
|
askTitle: "让她的嘴型对上说的话?",
|
|
66
|
-
ask: "Ta 可以在这台电脑上边说边重画她的嘴,让嘴型和字、声音一致。需要下载约
|
|
71
|
+
ask: "Ta 可以在这台电脑上边说边重画她的嘴,让嘴型和字、声音一致。需要下载约 6 GB,只下一次,之后离线也能用。这次通话先照常进行。",
|
|
67
72
|
askYes: "下载",
|
|
68
73
|
askNo: "以后再说",
|
|
69
|
-
started: "已在后台下载,下次视频通话就会用上。"
|
|
74
|
+
started: "已在后台下载,下次视频通话就会用上。",
|
|
75
|
+
herTitle: "用她自己的嘴型",
|
|
76
|
+
herHint: "用她自己的视频和 Ta 的声音训练过的嘴型,更像她本人,也更跟得上说的话。关掉就用通用嘴型。多下载约 1 GB,只下一次。",
|
|
77
|
+
herLater: "先完成上面的下载"
|
|
70
78
|
};
|
|
71
79
|
var ZH_TW = {
|
|
72
80
|
title: "視訊通話口型更真",
|
|
73
|
-
|
|
81
|
+
section: "口型",
|
|
82
|
+
hint: "在這台電腦上按 Ta 說的每句話重畫她的嘴,讓嘴型對上字和聲音。第一次需要下載約 6 GB。",
|
|
74
83
|
get: "下載",
|
|
75
84
|
getting: "正在下載 {percent}%",
|
|
76
85
|
ready: "已開啟",
|
|
@@ -78,14 +87,18 @@ var ZH_TW = {
|
|
|
78
87
|
failed: "沒裝好:{error}",
|
|
79
88
|
unsupported: "需要 Apple 晶片的 Mac,或有 NVIDIA 顯示卡的電腦。",
|
|
80
89
|
askTitle: "讓她的嘴型對上說的話?",
|
|
81
|
-
ask: "Ta 可以在這台電腦上邊說邊重畫她的嘴,讓嘴型和字、聲音一致。需要下載約
|
|
90
|
+
ask: "Ta 可以在這台電腦上邊說邊重畫她的嘴,讓嘴型和字、聲音一致。需要下載約 6 GB,只下一次,之後離線也能用。這次通話先照常進行。",
|
|
82
91
|
askYes: "下載",
|
|
83
92
|
askNo: "以後再說",
|
|
84
|
-
started: "已在背景下載,下次視訊通話就會用上。"
|
|
93
|
+
started: "已在背景下載,下次視訊通話就會用上。",
|
|
94
|
+
herTitle: "用她自己的嘴型",
|
|
95
|
+
herHint: "用她自己的影片和 Ta 的聲音訓練過的嘴型,更像她本人,也更跟得上說的話。關掉就用通用嘴型。多下載約 1 GB,只下一次。",
|
|
96
|
+
herLater: "先完成上面的下載"
|
|
85
97
|
};
|
|
86
98
|
var JA = {
|
|
87
99
|
title: "ビデオ通話の口元をリアルに",
|
|
88
|
-
|
|
100
|
+
section: "口元",
|
|
101
|
+
hint: "Ta が話すたびにこのコンピューターで口元を描き直し、言葉と口の動きを合わせます。初回に約 6 GB をダウンロードします。",
|
|
89
102
|
get: "ダウンロード",
|
|
90
103
|
getting: "ダウンロード中 {percent}%",
|
|
91
104
|
ready: "オン",
|
|
@@ -93,10 +106,13 @@ var JA = {
|
|
|
93
106
|
failed: "セットアップできませんでした:{error}",
|
|
94
107
|
unsupported: "Apple シリコンの Mac か、NVIDIA GPU のあるコンピューターが必要です。",
|
|
95
108
|
askTitle: "口の動きを言葉に合わせますか?",
|
|
96
|
-
ask: "Ta は話しながらこのコンピューターで口元を描き直し、言葉と声に口の動きを合わせられます。約
|
|
109
|
+
ask: "Ta は話しながらこのコンピューターで口元を描き直し、言葉と声に口の動きを合わせられます。約 6 GB を一度だけダウンロードし、その後はオフラインでも使えます。この通話はこのまま続きます。",
|
|
97
110
|
askYes: "ダウンロード",
|
|
98
111
|
askNo: "あとで",
|
|
99
|
-
started: "バックグラウンドでダウンロード中です。次のビデオ通話から使われます。"
|
|
112
|
+
started: "バックグラウンドでダウンロード中です。次のビデオ通話から使われます。",
|
|
113
|
+
herTitle: "彼女自身の口元",
|
|
114
|
+
herHint: "彼女自身の動画と Ta の声で学習した口元です。本人らしく見え、言葉にもよく合います。オフにすると汎用の口元になります。追加で約 1 GB を一度だけダウンロードします。",
|
|
115
|
+
herLater: "上のダウンロードのあとで"
|
|
100
116
|
};
|
|
101
117
|
var WORDS = { "zh-CN": ZH, "zh-TW": ZH_TW, "en-US": EN, "ja-JP": JA };
|
|
102
118
|
var LipsWords;
|
|
@@ -112,7 +128,7 @@ var LipsWords;
|
|
|
112
128
|
})(LipsWords ||= {});
|
|
113
129
|
|
|
114
130
|
// web-src/lips-protocol.ts
|
|
115
|
-
var LIPS_FPS =
|
|
131
|
+
var LIPS_FPS = 24;
|
|
116
132
|
var HOLD_MS = 1200;
|
|
117
133
|
var POLL_MS = 120;
|
|
118
134
|
var STARTS_MS = 9000;
|
|
@@ -152,7 +168,13 @@ function activate(pi) {
|
|
|
152
168
|
}
|
|
153
169
|
const removeStyle = injectStyle();
|
|
154
170
|
pi.registerCallMouth({ open: () => LipsMouth.open(pi) });
|
|
155
|
-
pi.registerSettings({
|
|
171
|
+
pi.registerSettings({
|
|
172
|
+
title: () => LipsWords.of(pi.ui.language).section,
|
|
173
|
+
icon: pi.ui.icons.Sparkles,
|
|
174
|
+
group: "voice",
|
|
175
|
+
order: 30,
|
|
176
|
+
rows: [setupRow(pi), herRow(pi)]
|
|
177
|
+
});
|
|
156
178
|
return removeStyle;
|
|
157
179
|
}
|
|
158
180
|
|
|
@@ -313,6 +335,43 @@ function setupRow(pi) {
|
|
|
313
335
|
})
|
|
314
336
|
};
|
|
315
337
|
}
|
|
338
|
+
function herRow(pi) {
|
|
339
|
+
return {
|
|
340
|
+
key: "her",
|
|
341
|
+
label: () => LipsWords.of(pi.ui.language).herTitle,
|
|
342
|
+
description: () => LipsWords.of(pi.ui.language).herHint,
|
|
343
|
+
render: () => /* @__PURE__ */ React.createElement(HerControl, {
|
|
344
|
+
pi
|
|
345
|
+
})
|
|
346
|
+
};
|
|
347
|
+
}
|
|
348
|
+
function HerControl({ pi }) {
|
|
349
|
+
const words = LipsWords.of(pi.ui.language);
|
|
350
|
+
const [status, setStatus] = useStatus(pi);
|
|
351
|
+
if (status?.state !== "ready") {
|
|
352
|
+
return /* @__PURE__ */ React.createElement("span", {
|
|
353
|
+
className: "ta-lips-note"
|
|
354
|
+
}, words.herLater);
|
|
355
|
+
}
|
|
356
|
+
if (status.her === "getting") {
|
|
357
|
+
return /* @__PURE__ */ React.createElement("span", {
|
|
358
|
+
className: "ta-lips-note"
|
|
359
|
+
}, LipsWords.fill(words.getting, { percent: Math.floor((status.herProgress ?? 0) * 100) }));
|
|
360
|
+
}
|
|
361
|
+
const Switch = pi.ui.Switch;
|
|
362
|
+
return /* @__PURE__ */ React.createElement("span", {
|
|
363
|
+
className: "ta-lips-row"
|
|
364
|
+
}, status.herError && /* @__PURE__ */ React.createElement("span", {
|
|
365
|
+
className: "ta-lips-note"
|
|
366
|
+
}, LipsWords.fill(words.failed, { error: status.herError })), /* @__PURE__ */ React.createElement(Switch, {
|
|
367
|
+
checked: status.her === "on",
|
|
368
|
+
label: words.herTitle,
|
|
369
|
+
onChange: (on) => pi.callHost("her", on).then(setStatus, (error) => {
|
|
370
|
+
pi.ui.notify(String(error?.message ?? error), "error");
|
|
371
|
+
throw error;
|
|
372
|
+
})
|
|
373
|
+
}));
|
|
374
|
+
}
|
|
316
375
|
function SetupControl({ pi }) {
|
|
317
376
|
const words = LipsWords.of(pi.ui.language);
|
|
318
377
|
const [status, setStatus] = useStatus(pi);
|