@celljs/ta-lips 0.0.0-stage → 4.29.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/python/lips.py ADDED
@@ -0,0 +1,816 @@
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> [--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)
10
+
11
+ What serve is told:
12
+ {"op": "say", "id": <utterance>, "pcm": <base64 of PCM16 mono>, "rate": <Hz>, "fps": <slots a second>, "slots": [[clip, frame], ...], "first": <slot>, "final": bool}
13
+ 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`
14
+ is the slot of the first of them: one heard from its middle (the service started late) is not drawn
15
+ {"op": "at", "id": <utterance>, "slot": <n>} the slot that shows now: those before it are not drawn any more
16
+ {"op": "cut", "id": <utterance>} what Ta says stopped
17
+ What it says:
18
+ {"ready": true, "fps": <frames a second it draws>}, then {"id": <utterance>, "frames": [{"slot", "clip", "frame", "box": [x, y, w, h], "data": <base64 WebP>}]}
19
+ """
20
+ import argparse
21
+ import base64
22
+ import bisect
23
+ import hashlib
24
+ import json
25
+ import math
26
+ import os
27
+ import shutil
28
+ import sys
29
+ import tarfile
30
+ import threading
31
+ import time
32
+ import urllib.request
33
+
34
+ MUSETALK = '2536eaf06b85f775d8e04b7fd81bf6699155a58d'
35
+ MUSETALK_URL = f'https://codeload.github.com/TMElyralab/MuseTalk/tar.gz/{MUSETALK}'
36
+ MODELS = [
37
+ ('TMElyralab/MuseTalk', 'musetalkV15/musetalk.json', 'musetalkV15/musetalk.json'),
38
+ ('TMElyralab/MuseTalk', 'musetalkV15/unet.pth', 'musetalkV15/unet.pth'),
39
+ ('stabilityai/sd-vae-ft-mse', 'config.json', 'sd-vae/config.json'),
40
+ ('stabilityai/sd-vae-ft-mse', 'diffusion_pytorch_model.bin', 'sd-vae/diffusion_pytorch_model.bin'),
41
+ ('openai/whisper-tiny', 'config.json', 'whisper/config.json'),
42
+ ('openai/whisper-tiny', 'pytorch_model.bin', 'whisper/pytorch_model.bin'),
43
+ ('openai/whisper-tiny', 'preprocessor_config.json', 'whisper/preprocessor_config.json'),
44
+ ('madebyollin/taesd', 'config.json', 'taesd/config.json'),
45
+ ('madebyollin/taesd', 'diffusion_pytorch_model.safetensors', 'taesd/diffusion_pytorch_model.safetensors'),
46
+ ('camenduru/MuseTalk', 'face-parse-bisent/79999_iter.pth', 'face-parse-bisent/79999_iter.pth'),
47
+ ]
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'}
53
+ # How much of the whole each step of setup is, roughly by the time it takes.
54
+ WEIGHT = {'source': 0.02, 'models': 0.6, 'her': 0.18, 'prepare': 0.2}
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
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
72
+ lock = threading.Lock()
73
+
74
+
75
+ def emit(message):
76
+ with lock:
77
+ sys.stdout.write(json.dumps(message, separators=(',', ':')) + '\n')
78
+ sys.stdout.flush()
79
+
80
+
81
+ def reachable(url):
82
+ try:
83
+ urllib.request.urlopen(urllib.request.Request(url, method='HEAD'), timeout=6)
84
+ return True
85
+ except Exception:
86
+ return False
87
+
88
+
89
+ def fetch(url, path, progress=None):
90
+ """A file of the web into path, through a part file, so that a broken download is never taken for a whole one."""
91
+ os.makedirs(os.path.dirname(path), exist_ok=True)
92
+ part = path + '.part'
93
+ have = os.path.getsize(part) if os.path.exists(part) else 0
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)
97
+ with urllib.request.urlopen(request, timeout=60) as response:
98
+ if have and response.status != 206:
99
+ have = 0
100
+ total = have + int(response.headers.get('Content-Length') or 0)
101
+ with open(part, 'ab' if have else 'wb') as out:
102
+ done = have
103
+ while True:
104
+ chunk = response.read(1 << 20)
105
+ if not chunk:
106
+ break
107
+ out.write(chunk)
108
+ done += len(chunk)
109
+ if progress and total:
110
+ progress(done / total)
111
+ os.replace(part, path)
112
+
113
+
114
+ class Paths:
115
+ def __init__(self, home, faces, more=None):
116
+ self.home = home
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
120
+ self.source = os.path.join(home, 'MuseTalk')
121
+ self.models = os.path.join(home, 'models')
122
+ self.cache = os.path.join(home, 'cache')
123
+
124
+ def model(self, *parts):
125
+ return os.path.join(self.models, *parts)
126
+
127
+
128
+ def setup(paths):
129
+ os.makedirs(paths.home, exist_ok=True)
130
+ step = {'at': 0.0}
131
+
132
+ def report(name, part, within):
133
+ emit({'step': name, 'progress': round(step['at'] + WEIGHT[part] * within, 4)})
134
+
135
+ if not os.path.exists(os.path.join(paths.source, 'musetalk')):
136
+ archive = os.path.join(paths.home, 'musetalk.tar.gz')
137
+ fetch(MUSETALK_URL, archive, lambda f: report('source', 'source', f))
138
+ with tarfile.open(archive) as tar:
139
+ tar.extractall(paths.home)
140
+ shutil.rmtree(paths.source, ignore_errors=True)
141
+ os.replace(os.path.join(paths.home, f'MuseTalk-{MUSETALK}'), paths.source)
142
+ os.remove(archive)
143
+ step['at'] += WEIGHT['source']
144
+ base = 'https://huggingface.co' if reachable('https://huggingface.co/api/models/openai/whisper-tiny') else 'https://hf-mirror.com'
145
+ # The model of MuseTalk is most of it: its share by its size.
146
+ 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]
147
+ total = sum(sizes) + 45
148
+ done = 0
149
+ for (repo, file, name), size in zip(MODELS, sizes):
150
+ target = paths.model(*name.split('/'))
151
+ fp16 = target.replace('unet.pth', 'unet-fp16.pth')
152
+ if not os.path.exists(target) and not (name.endswith('unet.pth') and os.path.exists(fp16)):
153
+ fetch(f'{base}/{repo}/resolve/main/{file}', target, lambda f, d=done, s=size: report('models', 'models', (d + s * f) / total))
154
+ done += size
155
+ resnet = paths.model('face-parse-bisent', 'resnet18-5c106cde.pth')
156
+ if not os.path.exists(resnet):
157
+ fetch(RESNET_URL, resnet)
158
+ step['at'] += WEIGHT['models']
159
+ fetch_her(paths, lambda f: report('models', 'her', f))
160
+ step['at'] += WEIGHT['her']
161
+ prepare(paths, lambda f: report('prepare', 'prepare', f))
162
+ emit({'step': 'done', 'progress': 1})
163
+
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
+
199
+ def runtime(paths):
200
+ sys.path.insert(0, paths.source)
201
+ os.chdir(paths.source)
202
+ import torch
203
+ if torch.backends.mps.is_available():
204
+ device = torch.device('mps')
205
+ elif torch.cuda.is_available():
206
+ device = torch.device('cuda')
207
+ else:
208
+ device = torch.device('cpu')
209
+ return torch, device
210
+
211
+
212
+ def unet_path(paths, torch):
213
+ """MuseTalk's UNet in half precision, as it runs: written once from the download, which is then let go."""
214
+ fp16 = paths.model('musetalkV15', 'unet-fp16.pth')
215
+ full = paths.model('musetalkV15', 'unet.pth')
216
+ if not os.path.exists(fp16):
217
+ weights = torch.load(full, map_location='cpu', weights_only=True)
218
+ torch.save({key: value.half() for key, value in weights.items()}, fp16 + '.part')
219
+ os.replace(fp16 + '.part', fp16)
220
+ os.remove(full)
221
+ return fp16
222
+
223
+
224
+ def clip_hash(path):
225
+ digest = hashlib.sha1()
226
+ with open(path, 'rb') as file:
227
+ digest.update(file.read())
228
+ return digest.hexdigest()
229
+
230
+
231
+ def prepare(paths, progress):
232
+ """
233
+ Of each clip, once (again as a clip changes): the latents of the lower half of her face in each frame, what of the
234
+ frame around it is drawn again (its box and the mask of her jaw, soft), and that part of the frame itself.
235
+ """
236
+ torch, device = runtime(paths)
237
+ import cv2
238
+ import numpy as np
239
+ from musetalk.models.vae import VAE
240
+ from musetalk.utils.blending import get_image_prepare_material
241
+
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']
246
+ os.makedirs(paths.cache, exist_ok=True)
247
+ index_path = os.path.join(paths.cache, 'index.json')
248
+ index = json.load(open(index_path)) if os.path.exists(index_path) else {}
249
+ todo = []
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)):
255
+ todo.append((clip, digest))
256
+ if not todo:
257
+ return
258
+ unet_path(paths, torch)
259
+ vae = VAE(model_path=paths.model('sd-vae'))
260
+ vae.vae = vae.vae.half().to(device)
261
+ vae.device = device
262
+ from musetalk.utils import face_parsing
263
+ parsing = face_parsing_at(face_parsing, paths)
264
+ for n, (clip, digest) in enumerate(todo):
265
+ capture = cv2.VideoCapture(files[clip])
266
+ frames = []
267
+ while True:
268
+ ok, frame = capture.read()
269
+ if not ok:
270
+ break
271
+ frames.append(frame)
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 = [], [], [], [], [], []
279
+ for k, frame in enumerate(frames):
280
+ x1, y1, x2, y2 = known[min(k, len(known) - 1)]
281
+ y2 = min(y2 + 10, frame.shape[0])
282
+ face = cv2.resize(frame[y1:y2, x1:x2], (256, 256), interpolation=cv2.INTER_LANCZOS4)
283
+ latents.append(vae.get_latents_for_unet(face).cpu())
284
+ lips.append(lips_of(cv2, np, torch, parsing, face))
285
+ mask, crop = get_image_prepare_material(frame, [x1, y1, x2, y2], fp=parsing, mode='jaw')
286
+ xs, ys, xe, ye = crop
287
+ part = np.zeros((ye - ys, xe - xs, 3), np.uint8)
288
+ sx, sy = max(0, xs), max(0, ys)
289
+ ex, ey = min(frame.shape[1], xe), min(frame.shape[0], ye)
290
+ part[sy - ys:ey - ys, sx - xs:ex - xs] = frame[sy:ey, sx:ex]
291
+ crops.append(crop)
292
+ masks.append(mask)
293
+ parts.append(part)
294
+ faces.append((x1, y1, x2, y2))
295
+ progress((n + (k + 1) / len(frames)) / len(todo))
296
+ torch.save({'latents': torch.cat(latents), 'crops': crops, 'masks': masks, 'parts': parts, 'faces': faces, 'lips': lips}, cache_file(paths, clip))
297
+ index[clip] = digest
298
+ json.dump(index, open(index_path, 'w'))
299
+
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
+
361
+ def face_parsing_at(module, paths):
362
+ """MuseTalk's FaceParsing, its weights read from the models of Ta rather than its own directory."""
363
+ original = module.FaceParsing.model_init
364
+
365
+ def model_init(self, resnet_path=None, model_pth=None):
366
+ return original(self, paths.model('face-parse-bisent', 'resnet18-5c106cde.pth'), paths.model('face-parse-bisent', '79999_iter.pth'))
367
+
368
+ module.FaceParsing.model_init = model_init
369
+ return module.FaceParsing(left_cheek_width=90, right_cheek_width=90)
370
+
371
+
372
+ class Utterance:
373
+ def __init__(self, id):
374
+ self.id = id
375
+ self.audio = []
376
+ self.length = 0
377
+ self.slots = []
378
+ # The first slot still wanted: those before it showed already.
379
+ self.next = 0
380
+ self.final = False
381
+ self.fps = 24
382
+ self.features = None
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
393
+
394
+
395
+ class Server:
396
+ def __init__(self, paths, her=False):
397
+ self.paths = paths
398
+ torch, device = runtime(paths)
399
+ self.torch, self.device = torch, device
400
+ import numpy as np
401
+ from diffusers import AutoencoderTiny
402
+ from transformers import WhisperModel
403
+ from musetalk.utils.audio_processor import AudioProcessor
404
+ self.np = np
405
+ dtype = torch.float16 if device.type != 'cpu' else torch.float32
406
+ self.dtype = dtype
407
+ from musetalk.models.unet import PositionalEncoding, UNet
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}}
416
+ self.unet = unet.model.to(device, dtype=dtype).eval()
417
+ self.wearing = None
418
+ self.wear('her' if self.mine else None)
419
+ self.pe = PositionalEncoding(d_model=384).to(device, dtype=dtype)
420
+ self.tiny = AutoencoderTiny.from_pretrained(paths.model('taesd')).to(device, dtype=dtype).eval()
421
+ self.audio = AudioProcessor(feature_extractor_path=paths.model('whisper'))
422
+ self.whisper = WhisperModel.from_pretrained(paths.model('whisper')).to(device, dtype=dtype).eval()
423
+ self.timesteps = torch.tensor([0], device=device)
424
+ # Clips new or changed since setup (a Ta with other clips) are prepared first.
425
+ prepare(paths, lambda done: None)
426
+ self.clips = {}
427
+ for name in json.load(open(os.path.join(paths.cache, 'index.json'))):
428
+ if os.path.exists(cache_file(paths, name)):
429
+ self.clips[name] = torch.load(cache_file(paths, name), weights_only=False)
430
+ self.fps = json.load(open(os.path.join(paths.faces, 'lips.json'))).get('fps', 24)
431
+ self.now = None
432
+ # Utterances heard from their middle: their sound and slots would not line up.
433
+ self.skipped = set()
434
+ self.wake = threading.Event()
435
+ import queue
436
+ self.made = queue.Queue()
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))
453
+
454
+ def warm(self):
455
+ """Runs the models once, as the first runs are slow, and measures how many keys a second they draw."""
456
+ silence = self.np.zeros(32000, self.np.float32)
457
+ u = Utterance('warm')
458
+ u.audio, u.length, u.final, u.fps = [silence], len(silence), True, self.fps
459
+ u.slots = [[next(iter(self.clips)), k] for k in range(BATCH * 2)]
460
+ self.decode(self.stack(self.infer(u, list(range(BATCH)))))
461
+ if self.device.type == 'mps':
462
+ self.torch.mps.synchronize()
463
+ began = time.time()
464
+ self.decode(self.stack(self.infer(u, list(range(BATCH, BATCH * 2)))))
465
+ if self.device.type == 'mps':
466
+ self.torch.mps.synchronize()
467
+ return BATCH / max(1e-3, time.time() - began)
468
+
469
+ def take(self, message):
470
+ op, id = message.get('op'), message.get('id')
471
+ if op == 'say':
472
+ if id in self.skipped:
473
+ return
474
+ u = self.now if self.now and self.now.id == id else Utterance(id)
475
+ if u is not self.now:
476
+ if int(message.get('first') or 0) > 0:
477
+ self.skipped.add(id)
478
+ return
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')
484
+ self.now = u
485
+ pcm = self.np.frombuffer(base64.b64decode(message.get('pcm') or ''), self.np.int16).astype(self.np.float32) / 32768
486
+ rate = int(message.get('rate') or 16000)
487
+ if len(pcm) and rate != 16000:
488
+ n = int(round(len(pcm) * 16000 / rate))
489
+ pcm = self.np.interp(self.np.linspace(0, len(pcm) - 1, n), self.np.arange(len(pcm)), pcm).astype(self.np.float32)
490
+ u.audio.append(pcm)
491
+ u.length += len(pcm)
492
+ u.slots.extend(message.get('slots') or [])
493
+ u.final = u.final or bool(message.get('final'))
494
+ elif op == 'at' and self.now and self.now.id == id:
495
+ u = self.now
496
+ # What shows now is late already: the next drawn is a little after it.
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)
510
+ elif op == 'cut' and self.now and self.now.id == id:
511
+ self.now = None
512
+ self.wake.set()
513
+
514
+ def ready(self, u):
515
+ """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."""
516
+ if u.final:
517
+ return len(u.slots)
518
+ heard = u.length / 16000
519
+ return min(len(u.slots), max(0, int((heard - 0.1) * u.fps)))
520
+
521
+ def features(self, u):
522
+ torch = self.torch
523
+ if u.featured == u.length:
524
+ return u.features
525
+ audio = self.np.concatenate(u.audio) if len(u.audio) > 1 else u.audio[0]
526
+ u.audio = [audio]
527
+ segments = [audio[i:i + 30 * 16000] for i in range(0, len(audio), 30 * 16000)] or [audio]
528
+ inputs = [self.audio.feature_extractor(s, return_tensors='pt', sampling_rate=16000).input_features.to(dtype=self.dtype) for s in segments]
529
+ with torch.no_grad():
530
+ 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)
531
+ u.featured = u.length
532
+ return u.features
533
+
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
537
+ chunks = self.features(u)
538
+ # Of the clips it prepared: one it has not (a Ta with more clips, not set up again) shows as it is.
539
+ rows = [s for s in keys if s < len(chunks) and u.slots[s][0] in self.clips]
540
+ if not rows:
541
+ return {}
542
+ audio = torch.stack([chunks[s] for s in rows]).to(self.device)
543
+ latents = []
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])
547
+ latents = torch.cat(latents).to(self.device, dtype=self.dtype)
548
+ with torch.no_grad():
549
+ predicted = self.unet(latents, self.timesteps, encoder_hidden_states=self.pe(audio)).sample
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
638
+
639
+ def finish(self):
640
+ """Lays what the model drew into its frames and sends them, beside the model drawing the next ones."""
641
+ import cv2
642
+ from concurrent.futures import ThreadPoolExecutor
643
+ np = self.np
644
+ pool = ThreadPoolExecutor(PATCHERS)
645
+ while True:
646
+ id, rows = self.made.get()
647
+ out = list(pool.map(lambda row: self.patch(cv2, np, *row), rows))
648
+ emit({'id': id, 'frames': [f for f in out if f]})
649
+
650
+ def patch(self, cv2, np, slot, clip, frame, image):
651
+ data = self.clips.get(clip)
652
+ if not data:
653
+ return None
654
+ k = frame % len(data['parts'])
655
+ x1, y1, x2, y2 = data['faces'][k]
656
+ xs, ys, xe, ye = data['crops'][k]
657
+ part = data['parts'][k].copy()
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])
663
+ face = cv2.resize(image, (x2 - x1, y2 - y1), interpolation=cv2.INTER_LINEAR)
664
+ part[y1 - ys:y2 - ys, x1 - xs:x2 - xs] = face
665
+ part = detail(cv2, np, part, original)
666
+ mask = data['masks'][k]
667
+ if mask.ndim == 3:
668
+ mask = mask[..., 0]
669
+ ys_, xs_ = np.nonzero(mask > 2)
670
+ if not len(ys_):
671
+ return None
672
+ top, bottom, left, right = ys_.min(), ys_.max() + 1, xs_.min(), xs_.max() + 1
673
+ rgba = np.dstack([part[top:bottom, left:right], mask[top:bottom, left:right]])
674
+ ok, webp = cv2.imencode('.webp', rgba, [cv2.IMWRITE_WEBP_QUALITY, WEBP_QUALITY])
675
+ if not ok:
676
+ return None
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()}
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
+
692
+ def run(self):
693
+ threading.Thread(target=self.finish, daemon=True).start()
694
+ emit({'ready': True, 'fps': round(self.speed, 1)})
695
+ while True:
696
+ u = self.now
697
+ if not u:
698
+ self.wake.wait(0.5)
699
+ self.wake.clear()
700
+ continue
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)
706
+ self.wake.wait(0.05)
707
+ self.wake.clear()
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)
749
+
750
+
751
+ def detail(cv2, np, made, original, sigma=5.0, sharp=0.6):
752
+ """
753
+ Where what MuseTalk drew is the frame as it was (the cheeks, the chin), the colour and the fine detail of the frame
754
+ come back; where it differs (the lips), it takes the colour of the skin around and is sharpened a little.
755
+ """
756
+ made = made.astype(np.float32)
757
+ original = original.astype(np.float32)
758
+ made = tone(cv2, np, made, original, sigma)
759
+ soft_made = cv2.GaussianBlur(made, (0, 0), 1.6)
760
+ soft_original = cv2.GaussianBlur(original, (0, 0), 1.6)
761
+ same = np.exp(-np.abs(soft_made - soft_original).mean(2, keepdims=True) / sigma)
762
+ out = soft_made + same * (original - soft_original) + (1 - same) * (1 + sharp) * (made - soft_made)
763
+ return np.clip(out, 0, 255).astype(np.uint8)
764
+
765
+
766
+ def tone(cv2, np, made, original, sigma):
767
+ """
768
+ The colour of what MuseTalk drew made the frame's (its decoder shifts it a little): the shift is measured where the two
769
+ are alike (the skin), smoothly, and taken away everywhere, the lips with the shift of the skin around them.
770
+ """
771
+ alike = np.exp(-np.abs(cv2.GaussianBlur(made, (0, 0), 3) - cv2.GaussianBlur(original, (0, 0), 3)).mean(2, keepdims=True) / (sigma * 2))
772
+ shift = original - made
773
+ # Of the skin alone: the shift where they are alike, spread over where they are not (normalized blur).
774
+ spread = 12
775
+ near = cv2.GaussianBlur(alike, (0, 0), spread)[..., None] + 1e-3
776
+ local = cv2.GaussianBlur(shift * alike, (0, 0), spread) / near
777
+ return made + local
778
+
779
+
780
+ def serve(paths, her=False):
781
+ server = Server(paths, her)
782
+
783
+ def read():
784
+ for line in sys.stdin:
785
+ line = line.strip()
786
+ if line:
787
+ try:
788
+ server.take(json.loads(line))
789
+ except Exception as error:
790
+ emit({'error': str(error)})
791
+ os._exit(0)
792
+
793
+ threading.Thread(target=read, daemon=True).start()
794
+ server.run()
795
+
796
+
797
+ if __name__ == '__main__':
798
+ os.environ.setdefault('TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD', '1')
799
+ parser = argparse.ArgumentParser()
800
+ parser.add_argument('command', choices=['setup', 'serve', 'her'])
801
+ parser.add_argument('--home', required=True)
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')
805
+ args = parser.parse_args()
806
+ paths = Paths(os.path.abspath(args.home), os.path.abspath(args.faces), args.more and os.path.abspath(args.more))
807
+ try:
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)
814
+ except Exception as error:
815
+ emit({'error': f'{type(error).__name__}: {error}'})
816
+ sys.exit(1)